bwlzad_file_compression.pl 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 15 June 2023
  4. # Edit: 07 March 2024
  5. # https://github.com/trizen
  6. # Compress/decompress files using Burrows-Wheeler Transform (BWT) + Move-to-front transform (MTF) + LZ77 compression (LZSS) + Adaptive Arithmetic Coding (in fixed bits).
  7. # Encoding the literals and the pointers using a DEFLATE-like approach.
  8. # References:
  9. # Data Compression (Summer 2023) - Lecture 11 - DEFLATE (gzip)
  10. # https://youtube.com/watch?v=SJPvNi4HrWQ
  11. #
  12. # Data Compression (Summer 2023) - Lecture 13 - BZip2
  13. # https://youtube.com/watch?v=cvoZbBZ3M2A
  14. #
  15. # Basic arithmetic coder in C++
  16. # https://github.com/billbird/arith32
  17. use 5.036;
  18. use Getopt::Std qw(getopts);
  19. use File::Basename qw(basename);
  20. use List::Util qw(max uniq);
  21. use Compression::Util qw(:all);
  22. use constant {
  23. PKGNAME => 'BWLZAD',
  24. VERSION => '0.01',
  25. FORMAT => 'bwlzad',
  26. CHUNK_SIZE => 1 << 17, # higher value = better compression
  27. };
  28. # Arithmetic Coding settings
  29. use constant BITS => 32;
  30. use constant MAX => oct('0b' . ('1' x BITS));
  31. use constant INITIAL_FREQ => 1;
  32. # Container signature
  33. use constant SIGNATURE => uc(FORMAT) . chr(1);
  34. sub usage {
  35. my ($code) = @_;
  36. print <<"EOH";
  37. usage: $0 [options] [input file] [output file]
  38. options:
  39. -e : extract
  40. -i <filename> : input filename
  41. -o <filename> : output filename
  42. -r : rewrite output
  43. -v : version number
  44. -h : this message
  45. examples:
  46. $0 document.txt
  47. $0 document.txt archive.${\FORMAT}
  48. $0 archive.${\FORMAT} document.txt
  49. $0 -e -i archive.${\FORMAT} -o document.txt
  50. EOH
  51. exit($code // 0);
  52. }
  53. sub version {
  54. printf("%s %s\n", PKGNAME, VERSION);
  55. exit;
  56. }
  57. sub valid_archive {
  58. my ($fh) = @_;
  59. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  60. $sig eq SIGNATURE || return;
  61. }
  62. return 1;
  63. }
  64. sub main {
  65. my %opt;
  66. getopts('ei:o:vhr', \%opt);
  67. $opt{h} && usage(0);
  68. $opt{v} && version();
  69. my ($input, $output) = @ARGV;
  70. $input //= $opt{i} // usage(2);
  71. $output //= $opt{o};
  72. my $ext = qr{\.${\FORMAT}\z}io;
  73. if ($opt{e} || $input =~ $ext) {
  74. if (not defined $output) {
  75. ($output = basename($input)) =~ s{$ext}{}
  76. || die "$0: no output file specified!\n";
  77. }
  78. if (not $opt{r} and -e $output) {
  79. print "'$output' already exists! -- Replace? [y/N] ";
  80. <STDIN> =~ /^y/i || exit 17;
  81. }
  82. decompress_file($input, $output)
  83. || die "$0: error: decompression failed!\n";
  84. }
  85. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  86. $output //= basename($input) . '.' . FORMAT;
  87. compress_file($input, $output)
  88. || die "$0: error: compression failed!\n";
  89. }
  90. else {
  91. warn "$0: don't know what to do...\n";
  92. usage(1);
  93. }
  94. }
  95. sub compression ($chunk, $out_fh) {
  96. my @chunk_bytes = unpack('C*', $chunk);
  97. my $data = pack('C*', @{rle4_encode(\@chunk_bytes, 254)});
  98. my ($bwt, $idx) = bwt_encode($data);
  99. my @bytes = unpack('C*', $bwt);
  100. my @alphabet = sort { $a <=> $b } uniq(@bytes);
  101. my $enc_bytes = mtf_encode(\@bytes, \@alphabet);
  102. if (max(@$enc_bytes) < 255) {
  103. print $out_fh chr(1);
  104. $enc_bytes = zrle_encode($enc_bytes);
  105. }
  106. else {
  107. print $out_fh chr(0);
  108. $enc_bytes = rle4_encode($enc_bytes);
  109. }
  110. print $out_fh pack('N', $idx);
  111. print $out_fh encode_alphabet(\@alphabet);
  112. print $out_fh lzss_compress(pack('C*', @$enc_bytes), \&create_adaptive_ac_entry);
  113. }
  114. sub decompression ($fh, $out_fh) {
  115. my $rle_encoded = ord(getc($fh) // die "error");
  116. my $idx = unpack('N', join('', map { getc($fh) // die "error" } 1 .. 4));
  117. my $alphabet = decode_alphabet($fh);
  118. my $bytes = [unpack('C*', lzss_decompress($fh, \&decode_adaptive_ac_entry))];
  119. if ($rle_encoded) {
  120. $bytes = zrle_decode($bytes);
  121. }
  122. else {
  123. $bytes = rle4_decode($bytes);
  124. }
  125. $bytes = mtf_decode($bytes, $alphabet);
  126. print $out_fh symbols2string(rle4_decode(string2symbols(bwt_decode(pack('C*', @$bytes), $idx))));
  127. }
  128. # Compress file
  129. sub compress_file ($input, $output) {
  130. open my $fh, '<:raw', $input
  131. or die "Can't open file <<$input>> for reading: $!";
  132. my $header = SIGNATURE;
  133. # Open the output file for writing
  134. open my $out_fh, '>:raw', $output
  135. or die "Can't open file <<$output>> for write: $!";
  136. # Print the header
  137. print $out_fh $header;
  138. # Compress data
  139. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  140. compression($chunk, $out_fh);
  141. }
  142. # Close the output file
  143. close $out_fh;
  144. }
  145. # Decompress file
  146. sub decompress_file ($input, $output) {
  147. # Open and validate the input file
  148. open my $fh, '<:raw', $input
  149. or die "Can't open file <<$input>> for reading: $!";
  150. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  151. # Open the output file
  152. open my $out_fh, '>:raw', $output
  153. or die "Can't open file <<$output>> for writing: $!";
  154. while (!eof($fh)) {
  155. decompression($fh, $out_fh);
  156. }
  157. # Close the output file
  158. close $out_fh;
  159. }
  160. main();
  161. exit(0);