lzb_file_compression.pl 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 => 'LZB',
  14. VERSION => '0.01',
  15. FORMAT => 'lzb',
  16. MIN_MATCH_LEN => 4, # minimum match length
  17. MAX_MATCH_LEN => ~0, # maximum match length
  18. MAX_MATCH_DIST => (1 << 16) - 1, # maximum match distance
  19. MAX_CHAIN_LEN => 48, # higher value = better compression
  20. CHUNK_SIZE => 1 << 18,
  21. };
  22. # Container signature
  23. use constant SIGNATURE => uc(FORMAT) . chr(1);
  24. sub usage {
  25. my ($code) = @_;
  26. print <<"EOH";
  27. usage: $0 [options] [input file] [output file]
  28. options:
  29. -e : extract
  30. -i <filename> : input filename
  31. -o <filename> : output filename
  32. -r : rewrite output
  33. -v : version number
  34. -h : this message
  35. examples:
  36. $0 document.txt
  37. $0 document.txt archive.${\FORMAT}
  38. $0 archive.${\FORMAT} document.txt
  39. $0 -e -i archive.${\FORMAT} -o document.txt
  40. EOH
  41. exit($code // 0);
  42. }
  43. sub version {
  44. printf("%s %s\n", PKGNAME, VERSION);
  45. exit;
  46. }
  47. sub valid_archive {
  48. my ($fh) = @_;
  49. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  50. $sig eq SIGNATURE || return;
  51. }
  52. return 1;
  53. }
  54. sub main {
  55. my %opt;
  56. getopts('ei:o:vhr', \%opt);
  57. $opt{h} && usage(0);
  58. $opt{v} && version();
  59. my ($input, $output) = @ARGV;
  60. $input //= $opt{i} // usage(2);
  61. $output //= $opt{o};
  62. my $ext = qr{\.${\FORMAT}\z}io;
  63. if ($opt{e} || $input =~ $ext) {
  64. if (not defined $output) {
  65. ($output = basename($input)) =~ s{$ext}{}
  66. || die "$0: no output file specified!\n";
  67. }
  68. if (not $opt{r} and -e $output) {
  69. print "'$output' already exists! -- Replace? [y/N] ";
  70. <STDIN> =~ /^y/i || exit 17;
  71. }
  72. decompress_file($input, $output)
  73. || die "$0: error: decompression failed!\n";
  74. }
  75. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  76. $output //= basename($input) . '.' . FORMAT;
  77. compress_file($input, $output)
  78. || die "$0: error: compression failed!\n";
  79. }
  80. else {
  81. warn "$0: don't know what to do...\n";
  82. usage(1);
  83. }
  84. }
  85. sub lzss_encode($str) {
  86. my $la = 0;
  87. my @symbols = unpack('C*', $str);
  88. my $end = $#symbols;
  89. my $min_len = MIN_MATCH_LEN; # minimum match length
  90. my $max_len = MAX_MATCH_LEN; # maximum match length
  91. my $max_dist = MAX_MATCH_DIST; # maximum match distance
  92. my $max_chain_len = MAX_CHAIN_LEN; # how many recent positions to keep track of
  93. my (@literals, @distances, @lengths, %table);
  94. while ($la <= $end) {
  95. my $best_n = 1;
  96. my $best_p = $la;
  97. my $lookahead = substr($str, $la, $min_len);
  98. if (exists($table{$lookahead})) {
  99. foreach my $p (@{$table{$lookahead}}) {
  100. if ($la - $p > $max_dist) {
  101. last;
  102. }
  103. my $n = $min_len;
  104. while ($n <= $max_len and $la + $n <= $end and $symbols[$la + $n - 1] == $symbols[$p + $n - 1]) {
  105. ++$n;
  106. }
  107. if ($n > $best_n) {
  108. $best_p = $p;
  109. $best_n = $n;
  110. }
  111. }
  112. my $matched = substr($str, $la, $best_n);
  113. foreach my $i (0 .. length($matched) - $min_len) {
  114. my $key = substr($matched, $i, $min_len);
  115. unshift @{$table{$key}}, $la + $i;
  116. if (scalar(@{$table{$key}}) > $max_chain_len) {
  117. pop @{$table{$key}};
  118. }
  119. }
  120. }
  121. else {
  122. $table{$lookahead} = [$la];
  123. }
  124. if ($best_n > $min_len) {
  125. push @lengths, $best_n - 1;
  126. push @distances, $la - $best_p;
  127. push @literals, undef;
  128. $la += $best_n - 1;
  129. }
  130. else {
  131. push @lengths, (0) x $best_n;
  132. push @distances, (0) x $best_n;
  133. push @literals, @symbols[$best_p .. $best_p + $best_n - 1];
  134. $la += $best_n;
  135. }
  136. }
  137. return (\@literals, \@distances, \@lengths);
  138. }
  139. sub compression($chunk, $out_fh) {
  140. my ($literals, $distances, $lengths) = lzss_encode($chunk);
  141. my $literals_end = $#{$literals};
  142. for (my $i = 0 ; $i <= $literals_end ; ++$i) {
  143. my @uncompressed;
  144. while ($i <= $literals_end and defined($literals->[$i])) {
  145. push @uncompressed, $literals->[$i];
  146. ++$i;
  147. }
  148. my $literals_string = pack('C*', @uncompressed);
  149. my $literals_length = scalar(@uncompressed);
  150. my $dist = $distances->[$i] // 0;
  151. my $match_len = $lengths->[$i] // 0;
  152. my $len_byte = 0;
  153. $len_byte |= ($literals_length >= 15 ? 15 : $literals_length) << 4;
  154. $len_byte |= ($match_len >= 15 ? 15 : $match_len);
  155. $literals_length -= 15;
  156. $match_len -= 15;
  157. print $out_fh chr($len_byte);
  158. while ($literals_length >= 0) {
  159. print $out_fh chr($literals_length >= 255 ? 255 : $literals_length);
  160. $literals_length -= 255;
  161. }
  162. print $out_fh $literals_string;
  163. while ($match_len >= 0) {
  164. print $out_fh chr($match_len >= 255 ? 255 : $match_len);
  165. $match_len -= 255;
  166. }
  167. if ($dist >= 1 << 16) {
  168. die "Too large distance: $dist";
  169. }
  170. print $out_fh pack('B*', sprintf('%016b', $dist));
  171. }
  172. }
  173. sub decompression($fh, $out_fh) {
  174. my $search_window = '';
  175. while (!eof($fh)) {
  176. my $len_byte = ord(getc($fh));
  177. my $literals_length = $len_byte >> 4;
  178. my $match_len = $len_byte & 0b1111;
  179. if ($literals_length == 15) {
  180. while (1) {
  181. my $byte_len = ord(getc($fh));
  182. $literals_length += $byte_len;
  183. last if $byte_len != 255;
  184. }
  185. }
  186. my $literals = '';
  187. if ($literals_length > 0) {
  188. read($fh, $literals, $literals_length);
  189. }
  190. if ($match_len == 15) {
  191. while (1) {
  192. my $byte_len = ord(getc($fh));
  193. $match_len += $byte_len;
  194. last if $byte_len != 255;
  195. }
  196. }
  197. my $offset = oct('0b' . unpack('B*', getc($fh) . getc($fh)));
  198. $search_window .= $literals;
  199. if ($offset == 1) {
  200. $search_window .= substr($search_window, -1) x $match_len;
  201. }
  202. elsif ($offset >= $match_len) { # non-overlapping matches
  203. $search_window .= substr($search_window, length($search_window) - $offset, $match_len);
  204. }
  205. else { # overlapping matches
  206. foreach my $i (1 .. $match_len) {
  207. $search_window .= substr($search_window, length($search_window) - $offset, 1);
  208. }
  209. }
  210. print $out_fh substr($search_window, -($match_len + $literals_length));
  211. $search_window = substr($search_window, -MAX_MATCH_DIST) if (length($search_window) > 2 * MAX_MATCH_DIST);
  212. }
  213. }
  214. # Compress file
  215. sub compress_file ($input, $output) {
  216. open my $fh, '<:raw', $input
  217. or die "Can't open file <<$input>> for reading: $!";
  218. my $header = SIGNATURE;
  219. # Open the output file for writing
  220. open my $out_fh, '>:raw', $output
  221. or die "Can't open file <<$output>> for write: $!";
  222. # Print the header
  223. print $out_fh $header;
  224. # Compress data
  225. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  226. compression($chunk, $out_fh);
  227. }
  228. # Close the file
  229. close $out_fh;
  230. }
  231. # Decompress file
  232. sub decompress_file ($input, $output) {
  233. # Open and validate the input file
  234. open my $fh, '<:raw', $input
  235. or die "Can't open file <<$input>> for reading: $!";
  236. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  237. # Open the output file
  238. open my $out_fh, '>:raw', $output
  239. or die "Can't open file <<$output>> for writing: $!";
  240. while (!eof($fh)) {
  241. decompression($fh, $out_fh);
  242. }
  243. # Close the file
  244. close $fh;
  245. close $out_fh;
  246. }
  247. main();
  248. exit(0);