lzhd_file_compression.pl 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 15 December 2022
  4. # Edit: 11 April 2024
  5. # https://github.com/trizen
  6. # Compress/decompress files using LZ77 compression + Huffman coding.
  7. # Encoding the distances/indices using a DEFLATE-like approach.
  8. use 5.036;
  9. use Getopt::Std qw(getopts);
  10. use File::Basename qw(basename);
  11. use Compression::Util qw(:all);
  12. use constant {
  13. PKGNAME => 'LZHD',
  14. VERSION => '0.02',
  15. FORMAT => 'lzhd',
  16. COMPRESSED_BYTE => chr(1),
  17. UNCOMPRESSED_BYTE => chr(0),
  18. CHUNK_SIZE => 1 << 16, # higher value = better compression
  19. RANDOM_DATA_THRESHOLD => 1, # in ratio
  20. };
  21. # Container signature
  22. use constant SIGNATURE => uc(FORMAT) . chr(2);
  23. sub usage {
  24. my ($code) = @_;
  25. print <<"EOH";
  26. usage: $0 [options] [input file] [output file]
  27. options:
  28. -e : extract
  29. -i <filename> : input filename
  30. -o <filename> : output filename
  31. -r : rewrite output
  32. -v : version number
  33. -h : this message
  34. examples:
  35. $0 document.txt
  36. $0 document.txt archive.${\FORMAT}
  37. $0 archive.${\FORMAT} document.txt
  38. $0 -e -i archive.${\FORMAT} -o document.txt
  39. EOH
  40. exit($code // 0);
  41. }
  42. sub version {
  43. printf("%s %s\n", PKGNAME, VERSION);
  44. exit;
  45. }
  46. sub valid_archive {
  47. my ($fh) = @_;
  48. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  49. $sig eq SIGNATURE || return;
  50. }
  51. return 1;
  52. }
  53. sub main {
  54. my %opt;
  55. getopts('ei:o:vhr', \%opt);
  56. $opt{h} && usage(0);
  57. $opt{v} && version();
  58. my ($input, $output) = @ARGV;
  59. $input //= $opt{i} // usage(2);
  60. $output //= $opt{o};
  61. my $ext = qr{\.${\FORMAT}\z}io;
  62. if ($opt{e} || $input =~ $ext) {
  63. if (not defined $output) {
  64. ($output = basename($input)) =~ s{$ext}{}
  65. || die "$0: no output file specified!\n";
  66. }
  67. if (not $opt{r} and -e $output) {
  68. print "'$output' already exists! -- Replace? [y/N] ";
  69. <STDIN> =~ /^y/i || exit 17;
  70. }
  71. decompress_file($input, $output)
  72. || die "$0: error: decompression failed!\n";
  73. }
  74. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  75. $output //= basename($input) . '.' . FORMAT;
  76. compress_file($input, $output)
  77. || die "$0: error: compression failed!\n";
  78. }
  79. else {
  80. warn "$0: don't know what to do...\n";
  81. usage(1);
  82. }
  83. }
  84. # Compress file
  85. sub compress_file ($input, $output) {
  86. open my $fh, '<:raw', $input
  87. or die "Can't open file <<$input>> for reading: $!";
  88. my $header = SIGNATURE;
  89. # Open the output file for writing
  90. open my $out_fh, '>:raw', $output
  91. or die "Can't open file <<$output>> for write: $!";
  92. # Print the header
  93. print $out_fh $header;
  94. # Compress data
  95. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  96. my ($uncompressed, $distances, $lengths) = lz77_encode($chunk);
  97. my $est_ratio = length($chunk) / (4 * scalar(@$uncompressed));
  98. say(scalar(@$uncompressed), ' -> ', $est_ratio);
  99. if ($est_ratio > RANDOM_DATA_THRESHOLD) {
  100. print $out_fh COMPRESSED_BYTE;
  101. print $out_fh create_huffman_entry($uncompressed);
  102. print $out_fh create_huffman_entry($lengths);
  103. print $out_fh obh_encode($distances);
  104. }
  105. else {
  106. print $out_fh UNCOMPRESSED_BYTE;
  107. print $out_fh create_huffman_entry([unpack('C*', $chunk)]);
  108. }
  109. }
  110. # Close the file
  111. close $out_fh;
  112. }
  113. # Decompress file
  114. sub decompress_file ($input, $output) {
  115. # Open and validate the input file
  116. open my $fh, '<:raw', $input
  117. or die "Can't open file <<$input>> for reading: $!";
  118. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  119. # Open the output file
  120. open my $out_fh, '>:raw', $output
  121. or die "Can't open file <<$output>> for writing: $!";
  122. while (!eof($fh)) {
  123. my $compression_byte = getc($fh) // die "decompression error";
  124. if ($compression_byte eq COMPRESSED_BYTE) {
  125. my $uncompressed = decode_huffman_entry($fh);
  126. my $lengths = decode_huffman_entry($fh);
  127. my $distances = obh_decode($fh);
  128. print $out_fh lz77_decode($uncompressed, $distances, $lengths);
  129. }
  130. elsif ($compression_byte eq UNCOMPRESSED_BYTE) {
  131. print $out_fh pack('C*', @{decode_huffman_entry($fh)});
  132. }
  133. else {
  134. die "Invalid compression...";
  135. }
  136. }
  137. # Close the file
  138. close $fh;
  139. close $out_fh;
  140. }
  141. main();
  142. exit(0);