lzbf_file_compression.pl 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 11 May 2024
  4. # https://github.com/trizen
  5. # Compress/decompress files using LZ77 compression (LZSS variant with hash tables), using a byte-aligned encoding, similar to LZ4.
  6. # References:
  7. # https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md
  8. # https://github.com/lz4/lz4/blob/dev/doc/lz4_Block_format.md
  9. use 5.036;
  10. use Getopt::Std qw(getopts);
  11. use File::Basename qw(basename);
  12. use constant {
  13. PKGNAME => 'LZBF',
  14. VERSION => '0.01',
  15. FORMAT => 'lzbf',
  16. MIN_MATCH_LEN => 5, # minimum match length
  17. MAX_MATCH_LEN => ~0, # maximum match length
  18. MAX_MATCH_DIST => (1 << 16) - 1, # maximum match distance
  19. CHUNK_SIZE => 1 << 18,
  20. };
  21. # Container signature
  22. use constant SIGNATURE => uc(FORMAT) . chr(1);
  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. sub lzss_encode_fast($str) {
  85. my $la = 0;
  86. my @symbols = unpack('C*', $str);
  87. my $end = $#symbols;
  88. my $min_len = MIN_MATCH_LEN; # minimum match length
  89. my $max_len = MAX_MATCH_LEN; # maximum match length
  90. my $max_dist = MAX_MATCH_DIST; # maximum match distance
  91. my (@literals, @distances, @lengths, %table);
  92. while ($la <= $end) {
  93. my $best_n = 1;
  94. my $best_p = $la;
  95. my $lookahead = substr($str, $la, $min_len);
  96. if (exists($table{$lookahead}) and $la - $table{$lookahead} <= $max_dist) {
  97. my $p = $table{$lookahead};
  98. my $n = $min_len;
  99. while ($n <= $max_len and $la + $n <= $end and $symbols[$la + $n - 1] == $symbols[$p + $n - 1]) {
  100. ++$n;
  101. }
  102. $best_p = $p;
  103. $best_n = $n;
  104. $table{$lookahead} = $la;
  105. }
  106. else {
  107. $table{$lookahead} = $la;
  108. }
  109. if ($best_n > $min_len) {
  110. push @lengths, $best_n - 1;
  111. push @distances, $la - $best_p;
  112. push @literals, undef;
  113. $la += $best_n - 1;
  114. }
  115. else {
  116. push @lengths, (0) x $best_n;
  117. push @distances, (0) x $best_n;
  118. push @literals, @symbols[$best_p .. $best_p + $best_n - 1];
  119. $la += $best_n;
  120. }
  121. }
  122. return (\@literals, \@distances, \@lengths);
  123. }
  124. sub compression($chunk, $out_fh) {
  125. my ($literals, $distances, $lengths) = lzss_encode_fast($chunk);
  126. my $literals_end = $#{$literals};
  127. for (my $i = 0 ; $i <= $literals_end ; ++$i) {
  128. my @uncompressed;
  129. while ($i <= $literals_end and defined($literals->[$i])) {
  130. push @uncompressed, $literals->[$i];
  131. ++$i;
  132. }
  133. my $literals_string = pack('C*', @uncompressed);
  134. my $literals_length = scalar(@uncompressed);
  135. my $dist = $distances->[$i] // 0;
  136. my $match_len = $lengths->[$i] // 0;
  137. my $len_byte = 0;
  138. $len_byte |= ($literals_length >= 15 ? 15 : $literals_length) << 4;
  139. $len_byte |= ($match_len >= 15 ? 15 : $match_len);
  140. $literals_length -= 15;
  141. $match_len -= 15;
  142. print $out_fh chr($len_byte);
  143. while ($literals_length >= 0) {
  144. print $out_fh chr($literals_length >= 255 ? 255 : $literals_length);
  145. $literals_length -= 255;
  146. }
  147. print $out_fh $literals_string;
  148. while ($match_len >= 0) {
  149. print $out_fh chr($match_len >= 255 ? 255 : $match_len);
  150. $match_len -= 255;
  151. }
  152. if ($dist >= 1 << 16) {
  153. die "Too large distance: $dist";
  154. }
  155. print $out_fh pack('B*', sprintf('%016b', $dist));
  156. }
  157. }
  158. sub decompression($fh, $out_fh) {
  159. my $search_window = '';
  160. while (!eof($fh)) {
  161. my $len_byte = ord(getc($fh));
  162. my $literals_length = $len_byte >> 4;
  163. my $match_len = $len_byte & 0b1111;
  164. if ($literals_length == 15) {
  165. while (1) {
  166. my $byte_len = ord(getc($fh));
  167. $literals_length += $byte_len;
  168. last if $byte_len != 255;
  169. }
  170. }
  171. my $literals = '';
  172. if ($literals_length > 0) {
  173. read($fh, $literals, $literals_length);
  174. }
  175. if ($match_len == 15) {
  176. while (1) {
  177. my $byte_len = ord(getc($fh));
  178. $match_len += $byte_len;
  179. last if $byte_len != 255;
  180. }
  181. }
  182. my $offset = oct('0b' . unpack('B*', getc($fh) . getc($fh)));
  183. $search_window .= $literals;
  184. if ($offset == 1) {
  185. $search_window .= substr($search_window, -1) x $match_len;
  186. }
  187. elsif ($offset >= $match_len) { # non-overlapping matches
  188. $search_window .= substr($search_window, length($search_window) - $offset, $match_len);
  189. }
  190. else { # overlapping matches
  191. foreach my $i (1 .. $match_len) {
  192. $search_window .= substr($search_window, length($search_window) - $offset, 1);
  193. }
  194. }
  195. print $out_fh substr($search_window, -($match_len + $literals_length));
  196. $search_window = substr($search_window, -MAX_MATCH_DIST) if (length($search_window) > 2 * MAX_MATCH_DIST);
  197. }
  198. }
  199. # Compress file
  200. sub compress_file ($input, $output) {
  201. open my $fh, '<:raw', $input
  202. or die "Can't open file <<$input>> for reading: $!";
  203. my $header = SIGNATURE;
  204. # Open the output file for writing
  205. open my $out_fh, '>:raw', $output
  206. or die "Can't open file <<$output>> for write: $!";
  207. # Print the header
  208. print $out_fh $header;
  209. # Compress data
  210. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  211. compression($chunk, $out_fh);
  212. }
  213. # Close the file
  214. close $out_fh;
  215. }
  216. # Decompress file
  217. sub decompress_file ($input, $output) {
  218. # Open and validate the input file
  219. open my $fh, '<:raw', $input
  220. or die "Can't open file <<$input>> for reading: $!";
  221. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  222. # Open the output file
  223. open my $out_fh, '>:raw', $output
  224. or die "Can't open file <<$output>> for writing: $!";
  225. while (!eof($fh)) {
  226. decompression($fh, $out_fh);
  227. }
  228. # Close the file
  229. close $fh;
  230. close $out_fh;
  231. }
  232. main();
  233. exit(0);