lzb2_file_compression.pl 8.5 KB

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