lzbf_file_compression.pl 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. }
  105. $table{$lookahead} = $la;
  106. if ($best_n > $min_len) {
  107. push @lengths, $best_n - 1;
  108. push @distances, $la - $best_p;
  109. push @literals, undef;
  110. $la += $best_n - 1;
  111. }
  112. else {
  113. push @lengths, (0) x $best_n;
  114. push @distances, (0) x $best_n;
  115. push @literals, @symbols[$best_p .. $best_p + $best_n - 1];
  116. $la += $best_n;
  117. }
  118. }
  119. return (\@literals, \@distances, \@lengths);
  120. }
  121. sub compression($chunk, $out_fh) {
  122. my ($literals, $distances, $lengths) = lzss_encode_fast($chunk);
  123. my $literals_end = $#{$literals};
  124. for (my $i = 0 ; $i <= $literals_end ; ++$i) {
  125. my @uncompressed;
  126. while ($i <= $literals_end and defined($literals->[$i])) {
  127. push @uncompressed, $literals->[$i];
  128. ++$i;
  129. }
  130. my $literals_string = pack('C*', @uncompressed);
  131. my $literals_length = scalar(@uncompressed);
  132. my $dist = $distances->[$i] // 0;
  133. my $match_len = $lengths->[$i] // 0;
  134. my $len_byte = 0;
  135. $len_byte |= ($literals_length >= 15 ? 15 : $literals_length) << 4;
  136. $len_byte |= ($match_len >= 15 ? 15 : $match_len);
  137. $literals_length -= 15;
  138. $match_len -= 15;
  139. print $out_fh chr($len_byte);
  140. while ($literals_length >= 0) {
  141. print $out_fh chr($literals_length >= 255 ? 255 : $literals_length);
  142. $literals_length -= 255;
  143. }
  144. print $out_fh $literals_string;
  145. while ($match_len >= 0) {
  146. print $out_fh chr($match_len >= 255 ? 255 : $match_len);
  147. $match_len -= 255;
  148. }
  149. if ($dist >= 1 << 16) {
  150. die "Too large distance: $dist";
  151. }
  152. print $out_fh pack('B*', sprintf('%016b', $dist));
  153. }
  154. }
  155. sub decompression($fh, $out_fh) {
  156. my $search_window = '';
  157. while (!eof($fh)) {
  158. my $len_byte = ord(getc($fh));
  159. my $literals_length = $len_byte >> 4;
  160. my $match_len = $len_byte & 0b1111;
  161. if ($literals_length == 15) {
  162. while (1) {
  163. my $byte_len = ord(getc($fh));
  164. $literals_length += $byte_len;
  165. last if $byte_len != 255;
  166. }
  167. }
  168. my $literals = '';
  169. if ($literals_length > 0) {
  170. read($fh, $literals, $literals_length);
  171. }
  172. if ($match_len == 15) {
  173. while (1) {
  174. my $byte_len = ord(getc($fh));
  175. $match_len += $byte_len;
  176. last if $byte_len != 255;
  177. }
  178. }
  179. my $offset = oct('0b' . unpack('B*', getc($fh) . getc($fh)));
  180. $search_window .= $literals;
  181. if ($offset == 1) {
  182. $search_window .= substr($search_window, -1) x $match_len;
  183. }
  184. elsif ($offset >= $match_len) { # non-overlapping matches
  185. $search_window .= substr($search_window, length($search_window) - $offset, $match_len);
  186. }
  187. else { # overlapping matches
  188. foreach my $i (1 .. $match_len) {
  189. $search_window .= substr($search_window, length($search_window) - $offset, 1);
  190. }
  191. }
  192. print $out_fh substr($search_window, -($match_len + $literals_length));
  193. $search_window = substr($search_window, -MAX_MATCH_DIST) if (length($search_window) > 2 * MAX_MATCH_DIST);
  194. }
  195. }
  196. # Compress file
  197. sub compress_file ($input, $output) {
  198. open my $fh, '<:raw', $input
  199. or die "Can't open file <<$input>> for reading: $!";
  200. my $header = SIGNATURE;
  201. # Open the output file for writing
  202. open my $out_fh, '>:raw', $output
  203. or die "Can't open file <<$output>> for write: $!";
  204. # Print the header
  205. print $out_fh $header;
  206. # Compress data
  207. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  208. compression($chunk, $out_fh);
  209. }
  210. # Close the file
  211. close $out_fh;
  212. }
  213. # Decompress file
  214. sub decompress_file ($input, $output) {
  215. # Open and validate the input file
  216. open my $fh, '<:raw', $input
  217. or die "Can't open file <<$input>> for reading: $!";
  218. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  219. # Open the output file
  220. open my $out_fh, '>:raw', $output
  221. or die "Can't open file <<$output>> for writing: $!";
  222. while (!eof($fh)) {
  223. decompression($fh, $out_fh);
  224. }
  225. # Close the file
  226. close $fh;
  227. close $out_fh;
  228. }
  229. main();
  230. exit(0);