bwrl3_file_compression.pl 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 10 September 2023
  4. # Edit: 13 April 2024
  5. # https://github.com/trizen
  6. # Compress/decompress files using Burrows-Wheeler Transform (BWT) + Variable Run-Length encoding + Huffman coding + Bzip2.
  7. # Reference:
  8. # Data Compression (Summer 2023) - Lecture 13 - BZip2
  9. # https://youtube.com/watch?v=cvoZbBZ3M2A
  10. use 5.036;
  11. use Getopt::Std qw(getopts);
  12. use File::Basename qw(basename);
  13. use Compression::Util qw(:all);
  14. use constant {
  15. PKGNAME => 'BWRL3',
  16. VERSION => '0.01',
  17. FORMAT => 'bwrl3',
  18. CHUNK_SIZE => 1 << 17, # higher value = better compression
  19. };
  20. # Container signature
  21. use constant SIGNATURE => uc(FORMAT) . chr(1);
  22. sub usage {
  23. my ($code) = @_;
  24. print <<"EOH";
  25. usage: $0 [options] [input file] [output file]
  26. options:
  27. -e : extract
  28. -i <filename> : input filename
  29. -o <filename> : output filename
  30. -r : rewrite output
  31. -v : version number
  32. -h : this message
  33. examples:
  34. $0 document.txt
  35. $0 document.txt archive.${\FORMAT}
  36. $0 archive.${\FORMAT} document.txt
  37. $0 -e -i archive.${\FORMAT} -o document.txt
  38. EOH
  39. exit($code // 0);
  40. }
  41. sub version {
  42. printf("%s %s\n", PKGNAME, VERSION);
  43. exit;
  44. }
  45. sub valid_archive {
  46. my ($fh) = @_;
  47. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  48. $sig eq SIGNATURE || return;
  49. }
  50. return 1;
  51. }
  52. sub main {
  53. my %opt;
  54. getopts('ei:o:vhr', \%opt);
  55. $opt{h} && usage(0);
  56. $opt{v} && version();
  57. my ($input, $output) = @ARGV;
  58. $input //= $opt{i} // usage(2);
  59. $output //= $opt{o};
  60. my $ext = qr{\.${\FORMAT}\z}io;
  61. if ($opt{e} || $input =~ $ext) {
  62. if (not defined $output) {
  63. ($output = basename($input)) =~ s{$ext}{}
  64. || die "$0: no output file specified!\n";
  65. }
  66. if (not $opt{r} and -e $output) {
  67. print "'$output' already exists! -- Replace? [y/N] ";
  68. <STDIN> =~ /^y/i || exit 17;
  69. }
  70. decompress_file($input, $output)
  71. || die "$0: error: decompression failed!\n";
  72. }
  73. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  74. $output //= basename($input) . '.' . FORMAT;
  75. compress_file($input, $output)
  76. || die "$0: error: compression failed!\n";
  77. }
  78. else {
  79. warn "$0: don't know what to do...\n";
  80. usage(1);
  81. }
  82. }
  83. sub VLR_encoding ($bytes) {
  84. my $uncompressed = '';
  85. my $bitstream = '';
  86. my $rle = run_length($bytes);
  87. foreach my $cv (@$rle) {
  88. my ($c, $v) = @$cv;
  89. $uncompressed .= chr($c);
  90. if ($v == 1) {
  91. $bitstream .= '0';
  92. }
  93. else {
  94. my $t = sprintf('%b', $v);
  95. $bitstream .= join('', '1' x (length($t) - 1), '0', substr($t, 1));
  96. }
  97. }
  98. return ($uncompressed, pack('B*', $bitstream));
  99. }
  100. sub VLR_decoding ($uncompressed, $bits_fh) {
  101. my $decoded = '';
  102. my $buffer = '';
  103. foreach my $c (@$uncompressed) {
  104. my $bl = 0;
  105. while (read_bit($bits_fh, \$buffer) == 1) {
  106. ++$bl;
  107. }
  108. if ($bl > 0) {
  109. $decoded .= chr($c) x oct('0b1' . join('', map { read_bit($bits_fh, \$buffer) } 1 .. $bl));
  110. }
  111. else {
  112. $decoded .= chr($c);
  113. }
  114. }
  115. return $decoded;
  116. }
  117. # Compress file
  118. sub compress_file ($input, $output) {
  119. open my $fh, '<:raw', $input
  120. or die "Can't open file <<$input>> for reading: $!";
  121. my $header = SIGNATURE;
  122. # Open the output file for writing
  123. open my $out_fh, '>:raw', $output
  124. or die "Can't open file <<$output>> for write: $!";
  125. # Print the header
  126. print $out_fh $header;
  127. # Compress data
  128. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  129. my ($bwt, $idx) = bwt_encode($chunk);
  130. my ($uncompressed, $lengths) = VLR_encoding(string2symbols($bwt));
  131. print $out_fh pack('N', $idx);
  132. print $out_fh mrl_compress_symbolic($uncompressed, \&bwt_compress_symbolic);
  133. print $out_fh create_huffman_entry(rle4_encode(string2symbols($lengths)));
  134. }
  135. close $out_fh;
  136. }
  137. # Decompress file
  138. sub decompress_file ($input, $output) {
  139. # Open and validate the input file
  140. open my $fh, '<:raw', $input
  141. or die "Can't open file <<$input>> for reading: $!";
  142. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  143. # Open the output file
  144. open my $out_fh, '>:raw', $output
  145. or die "Can't open file <<$output>> for writing: $!";
  146. while (!eof($fh)) {
  147. my $idx = unpack('N', join('', map { getc($fh) // die "decompression error" } 1 .. 4));
  148. my $uncompressed = mrl_decompress_symbolic($fh, \&bwt_decompress_symbolic); # uncompressed
  149. open my $len_fh, '+>:raw', \my $lengths;
  150. print $len_fh symbols2string(rle4_decode(decode_huffman_entry($fh)));
  151. seek($len_fh, 0, 0);
  152. my $dec = VLR_decoding($uncompressed, $len_fh);
  153. print $out_fh bwt_decode($dec, $idx);
  154. }
  155. close $fh;
  156. close $out_fh;
  157. }
  158. main();
  159. exit(0);