123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358 |
- #!/usr/bin/perl
- # Author: Trizen
- # Date: 14 June 2023
- # Edit: 19 March 2024
- # https://github.com/trizen
- # Compress/decompress files using Binary Burrows-Wheeler Transform (BWT) + Binary Variable Run-Length Encoding.
- # References:
- # Data Compression (Summer 2023) - Lecture 13 - BZip2
- # https://youtube.com/watch?v=cvoZbBZ3M2A
- #
- # Data Compression (Summer 2023) - Lecture 5 - Basic Techniques
- # https://youtube.com/watch?v=TdFWb8mL5Gk
- use 5.036;
- use Getopt::Std qw(getopts);
- use File::Basename qw(basename);
- use List::Util qw(max uniq);
- use constant {
- PKGNAME => 'BBWR',
- VERSION => '0.02',
- FORMAT => 'bbwr',
- CHUNK_SIZE => 1 << 13, # larger values == better compression
- LOOKAHEAD_LEN => 128,
- };
- # Container signature
- use constant SIGNATURE => uc(FORMAT) . chr(2);
- sub usage {
- my ($code) = @_;
- print <<"EOH";
- usage: $0 [options] [input file] [output file]
- options:
- -e : extract
- -i <filename> : input filename
- -o <filename> : output filename
- -r : rewrite output
- -v : version number
- -h : this message
- examples:
- $0 document.txt
- $0 document.txt archive.${\FORMAT}
- $0 archive.${\FORMAT} document.txt
- $0 -e -i archive.${\FORMAT} -o document.txt
- EOH
- exit($code // 0);
- }
- sub version {
- printf("%s %s\n", PKGNAME, VERSION);
- exit;
- }
- sub valid_archive {
- my ($fh) = @_;
- if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
- $sig eq SIGNATURE || return;
- }
- return 1;
- }
- sub main {
- my %opt;
- getopts('ei:o:vhr', \%opt);
- $opt{h} && usage(0);
- $opt{v} && version();
- my ($input, $output) = @ARGV;
- $input //= $opt{i} // usage(2);
- $output //= $opt{o};
- my $ext = qr{\.${\FORMAT}\z}io;
- if ($opt{e} || $input =~ $ext) {
- if (not defined $output) {
- ($output = basename($input)) =~ s{$ext}{}
- || die "$0: no output file specified!\n";
- }
- if (not $opt{r} and -e $output) {
- print "'$output' already exists! -- Replace? [y/N] ";
- <STDIN> =~ /^y/i || exit 17;
- }
- decompress_file($input, $output)
- || die "$0: error: decompression failed!\n";
- }
- elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
- $output //= basename($input) . '.' . FORMAT;
- compress_file($input, $output)
- || die "$0: error: compression failed!\n";
- }
- else {
- warn "$0: don't know what to do...\n";
- usage(1);
- }
- }
- sub read_bit ($fh, $bitstring) {
- if (($$bitstring // '') eq '') {
- $$bitstring = unpack('b*', getc($fh) // return undef);
- }
- chop($$bitstring);
- }
- sub read_bits ($fh, $bits_len) {
- my $data = '';
- read($fh, $data, $bits_len >> 3);
- $data = unpack('B*', $data);
- while (length($data) < $bits_len) {
- $data .= unpack('B*', getc($fh) // return undef);
- }
- if (length($data) > $bits_len) {
- $data = substr($data, 0, $bits_len);
- }
- return $data;
- }
- sub bwt_balanced ($s) { # O(n * LOOKAHEAD_LEN) space (fast)
- #<<<
- [
- map { $_->[1] } sort {
- ($a->[0] cmp $b->[0])
- || ((substr($s, $a->[1]) . substr($s, 0, $a->[1])) cmp(substr($s, $b->[1]) . substr($s, 0, $b->[1])))
- }
- map {
- my $t = substr($s, $_, LOOKAHEAD_LEN);
- if (length($t) < LOOKAHEAD_LEN) {
- $t .= substr($s, 0, ($_ < LOOKAHEAD_LEN) ? $_ : (LOOKAHEAD_LEN - length($t)));
- }
- [$t, $_]
- } 0 .. length($s) - 1
- ];
- #>>>
- }
- sub bwt_encode ($s) {
- my $bwt = bwt_balanced($s);
- my $ret = join('', map { substr($s, $_ - 1, 1) } @$bwt);
- my $idx = 0;
- foreach my $i (@$bwt) {
- $i || last;
- ++$idx;
- }
- return ($ret, $idx);
- }
- sub bwt_decode ($bwt, $idx) { # fast inversion
- my @tail = split(//, $bwt);
- my @head = sort @tail;
- my %indices;
- foreach my $i (0 .. $#tail) {
- push @{$indices{$tail[$i]}}, $i;
- }
- my @table;
- foreach my $v (@head) {
- push @table, shift(@{$indices{$v}});
- }
- my $dec = '';
- my $i = $idx;
- for (1 .. scalar(@head)) {
- $dec .= $head[$i];
- $i = $table[$i];
- }
- return $dec;
- }
- sub run_length ($arr) {
- @$arr || return [];
- my @result = [$arr->[0], 1];
- my $prev_value = $arr->[0];
- foreach my $i (1 .. $#{$arr}) {
- my $curr_value = $arr->[$i];
- if ($curr_value eq $prev_value) {
- ++$result[-1][1];
- }
- else {
- push(@result, [$curr_value, 1]);
- }
- $prev_value = $curr_value;
- }
- return \@result;
- }
- sub binary_vrl_encoding ($str) {
- my @bits = split(//, $str);
- my $bitstring = $bits[0];
- foreach my $rle (@{run_length(\@bits)}) {
- my ($c, $v) = @$rle;
- if ($v == 1) {
- $bitstring .= '0';
- }
- else {
- my $t = sprintf('%b', $v - 1);
- $bitstring .= join('', '1' x length($t), '0', substr($t, 1));
- }
- }
- return $bitstring;
- }
- sub binary_vrl_decoding ($bitstring) {
- my $decoded = '';
- my $bit = substr($bitstring, 0, 1, '');
- while ($bitstring ne '') {
- $decoded .= $bit;
- my $bl = 0;
- while (substr($bitstring, 0, 1, '') eq '1') {
- ++$bl;
- }
- if ($bl > 0) {
- $decoded .= $bit x oct('0b1' . join('', map { substr($bitstring, 0, 1, '') } 1 .. $bl - 1));
- }
- $bit = ($bit eq '1' ? '0' : '1');
- }
- return $decoded;
- }
- sub compression ($chunk, $out_fh) {
- my $bits = unpack('B*', $chunk);
- my $vrle1 = binary_vrl_encoding($bits);
- if (length($vrle1) < length($bits)) {
- printf "Doing early VLR, saving %s bits\n", length($bits) - length($vrle1);
- print $out_fh chr(1);
- }
- else {
- print $out_fh chr(0);
- $vrle1 = $bits;
- }
- my ($bwt, $idx) = bwt_encode($vrle1);
- my $vrle2 = binary_vrl_encoding($bwt);
- say "BWT index: $idx";
- print $out_fh pack('N', $idx);
- print $out_fh pack('N', length($vrle2));
- print $out_fh pack('B*', $vrle2);
- }
- sub decompression ($fh, $out_fh) {
- my $compressed_byte = ord(getc($fh) // die "error");
- my $idx = unpack('N', join('', map { getc($fh) // die "error" } 1 .. 4));
- my $bits_len = unpack('N', join('', map { getc($fh) // die "error" } 1 .. 4));
- say "BWT index = $idx";
- my $bwt = binary_vrl_decoding(read_bits($fh, $bits_len));
- my $data = bwt_decode($bwt, $idx);
- if ($compressed_byte == 1) {
- $data = binary_vrl_decoding($data);
- }
- print $out_fh pack('B*', $data);
- }
- # Compress file
- sub compress_file ($input, $output) {
- open my $fh, '<:raw', $input
- or die "Can't open file <<$input>> for reading: $!";
- my $header = SIGNATURE;
- # Open the output file for writing
- open my $out_fh, '>:raw', $output
- or die "Can't open file <<$output>> for write: $!";
- # Print the header
- print $out_fh $header;
- # Compress data
- while (read($fh, (my $chunk), CHUNK_SIZE)) {
- compression($chunk, $out_fh);
- }
- # Close the file
- close $out_fh;
- }
- # Decompress file
- sub decompress_file ($input, $output) {
- # Open and validate the input file
- open my $fh, '<:raw', $input
- or die "Can't open file <<$input>> for reading: $!";
- valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
- # Open the output file
- open my $out_fh, '>:raw', $output
- or die "Can't open file <<$output>> for writing: $!";
- while (!eof($fh)) {
- decompression($fh, $out_fh);
- }
- # Close the file
- close $fh;
- close $out_fh;
- }
- main();
- exit(0);
|