lzbwh_file_compression.pl 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 07 September 2023
  4. # Edit: 11 April 2024
  5. # https://github.com/trizen
  6. # Compress/decompress files using LZ77 compression + DEFLATE integers encoding + Burrows-Wheeler Transform (BWT) + Huffman coding.
  7. # References:
  8. # Data Compression (Summer 2023) - Lecture 13 - BZip2
  9. # https://youtube.com/watch?v=cvoZbBZ3M2A
  10. #
  11. # Data Compression (Summer 2023) - Lecture 11 - DEFLATE (gzip)
  12. # https://youtube.com/watch?v=SJPvNi4HrWQ
  13. use 5.036;
  14. use Getopt::Std qw(getopts);
  15. use File::Basename qw(basename);
  16. use Compression::Util qw(:all);
  17. use constant {
  18. PKGNAME => 'LZBWH',
  19. VERSION => '0.01',
  20. FORMAT => 'lzbwh',
  21. COMPRESSED_BYTE => chr(1),
  22. UNCOMPRESSED_BYTE => chr(0),
  23. CHUNK_SIZE => 1 << 16, # higher value = better compression
  24. RANDOM_DATA_THRESHOLD => 1, # in ratio
  25. };
  26. # Container signature
  27. use constant SIGNATURE => uc(FORMAT) . chr(1);
  28. sub usage {
  29. my ($code) = @_;
  30. print <<"EOH";
  31. usage: $0 [options] [input file] [output file]
  32. options:
  33. -e : extract
  34. -i <filename> : input filename
  35. -o <filename> : output filename
  36. -r : rewrite output
  37. -v : version number
  38. -h : this message
  39. examples:
  40. $0 document.txt
  41. $0 document.txt archive.${\FORMAT}
  42. $0 archive.${\FORMAT} document.txt
  43. $0 -e -i archive.${\FORMAT} -o document.txt
  44. EOH
  45. exit($code // 0);
  46. }
  47. sub version {
  48. printf("%s %s\n", PKGNAME, VERSION);
  49. exit;
  50. }
  51. sub valid_archive {
  52. my ($fh) = @_;
  53. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  54. $sig eq SIGNATURE || return;
  55. }
  56. return 1;
  57. }
  58. sub main {
  59. my %opt;
  60. getopts('ei:o:vhr', \%opt);
  61. $opt{h} && usage(0);
  62. $opt{v} && version();
  63. my ($input, $output) = @ARGV;
  64. $input //= $opt{i} // usage(2);
  65. $output //= $opt{o};
  66. my $ext = qr{\.${\FORMAT}\z}io;
  67. if ($opt{e} || $input =~ $ext) {
  68. if (not defined $output) {
  69. ($output = basename($input)) =~ s{$ext}{}
  70. || die "$0: no output file specified!\n";
  71. }
  72. if (not $opt{r} and -e $output) {
  73. print "'$output' already exists! -- Replace? [y/N] ";
  74. <STDIN> =~ /^y/i || exit 17;
  75. }
  76. decompress_file($input, $output)
  77. || die "$0: error: decompression failed!\n";
  78. }
  79. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  80. $output //= basename($input) . '.' . FORMAT;
  81. compress_file($input, $output)
  82. || die "$0: error: compression failed!\n";
  83. }
  84. else {
  85. warn "$0: don't know what to do...\n";
  86. usage(1);
  87. }
  88. }
  89. # Compress file
  90. sub compress_file ($input, $output) {
  91. open my $fh, '<:raw', $input
  92. or die "Can't open file <<$input>> for reading: $!";
  93. my $header = SIGNATURE;
  94. # Open the output file for writing
  95. open my $out_fh, '>:raw', $output
  96. or die "Can't open file <<$output>> for write: $!";
  97. # Print the header
  98. print $out_fh $header;
  99. my $lengths_str = '';
  100. my $uncompressed_str = '';
  101. my @sizes;
  102. my @distances_block;
  103. open my $uc_fh, '>:raw', \$uncompressed_str;
  104. open my $len_fh, '>:raw', \$lengths_str;
  105. my $create_bz2_block = sub {
  106. scalar(@sizes) > 0 or return;
  107. print $out_fh COMPRESSED_BYTE;
  108. print $out_fh delta_encode(\@sizes);
  109. print $out_fh bz2_compress($uncompressed_str);
  110. print $out_fh bz2_compress($lengths_str);
  111. print $out_fh bz2_compress(obh_encode(\@distances_block));
  112. @sizes = ();
  113. @distances_block = ();
  114. open $uc_fh, '>:raw', \$uncompressed_str;
  115. open $len_fh, '>:raw', \$lengths_str;
  116. };
  117. # Compress data
  118. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  119. my ($literals, $distances, $lengths) = lz77_encode($chunk);
  120. my $est_ratio = length($chunk) / (4 * scalar(@$literals));
  121. say "Est. ratio: ", $est_ratio, " (", scalar(@$literals), " uncompressed bytes)";
  122. if ($est_ratio > RANDOM_DATA_THRESHOLD) {
  123. push @sizes, scalar(@$literals);
  124. print $uc_fh pack('C*', @$literals);
  125. print $len_fh pack('C*', @$lengths);
  126. push @distances_block, @$distances;
  127. }
  128. else {
  129. say "Random data detected...";
  130. $create_bz2_block->();
  131. print $out_fh UNCOMPRESSED_BYTE;
  132. print $out_fh create_huffman_entry(string2symbols($chunk));
  133. }
  134. if (length($uncompressed_str) >= CHUNK_SIZE) {
  135. $create_bz2_block->();
  136. }
  137. }
  138. $create_bz2_block->();
  139. close $out_fh;
  140. }
  141. # Decompress file
  142. sub decompress_file ($input, $output) {
  143. # Open and validate the input file
  144. open my $fh, '<:raw', $input
  145. or die "Can't open file <<$input>> for reading: $!";
  146. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  147. # Open the output file
  148. open my $out_fh, '>:raw', $output
  149. or die "Can't open file <<$output>> for writing: $!";
  150. while (!eof($fh)) {
  151. my $compression_byte = getc($fh) // die "decompression error";
  152. if ($compression_byte eq UNCOMPRESSED_BYTE) {
  153. say "Decoding random data...";
  154. print $out_fh pack('C*', @{decode_huffman_entry($fh)});
  155. next;
  156. }
  157. elsif ($compression_byte ne COMPRESSED_BYTE) {
  158. die "decompression error";
  159. }
  160. my @sizes = @{delta_decode($fh)};
  161. my @uncompressed = unpack('C*', bz2_decompress($fh));
  162. my @lengths = unpack('C*', bz2_decompress($fh));
  163. my @distances = @{obh_decode(bz2_decompress($fh))};
  164. while (@uncompressed) {
  165. my $size = shift(@sizes) // die "decompression error";
  166. my @uncompressed_chunk = splice(@uncompressed, 0, $size);
  167. my @lengths_chunk = splice(@lengths, 0, $size);
  168. my @distances_chunk = splice(@distances, 0, $size);
  169. scalar(@uncompressed_chunk) == $size or die "decompression error";
  170. scalar(@lengths_chunk) == $size or die "decompression error";
  171. scalar(@distances_chunk) == $size or die "decompression error";
  172. print $out_fh lz77_decode(\@uncompressed_chunk, \@distances_chunk, \@lengths_chunk);
  173. }
  174. }
  175. close $fh;
  176. close $out_fh;
  177. }
  178. main();
  179. exit(0);