lzbf_file_compression.pl 7.4 KB

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