lza_file_compression.pl 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 15 December 2022
  4. # Edit: 19 March 2024
  5. # https://github.com/trizen
  6. # Compress/decompress files using LZ77 compression + Arithmetic Coding (in fixed bits).
  7. # Reference:
  8. # Basic arithmetic coder in C++
  9. # https://github.com/billbird/arith32
  10. use 5.020;
  11. use strict;
  12. use warnings;
  13. use experimental qw(signatures);
  14. use Getopt::Std qw(getopts);
  15. use File::Basename qw(basename);
  16. use List::Util qw(max);
  17. use constant {
  18. PKGNAME => 'LZA',
  19. VERSION => '0.01',
  20. FORMAT => 'lza',
  21. CHUNK_SIZE => 1 << 16,
  22. };
  23. # Container signature
  24. use constant SIGNATURE => uc(FORMAT) . chr(1);
  25. # Arithmetic Coding settings
  26. use constant BITS => 32;
  27. use constant MAX => oct('0b' . ('1' x BITS));
  28. sub usage {
  29. my ($code) = @_;
  30. print <<"EOH";
  31. usage: $0 [options] [input file] [output file]
  32. options:
  33. -e : extract
  34. -i <filename> : input filename
  35. -o <filename> : output filename
  36. -r : rewrite output
  37. -v : version number
  38. -h : this message
  39. examples:
  40. $0 document.txt
  41. $0 document.txt archive.${\FORMAT}
  42. $0 archive.${\FORMAT} document.txt
  43. $0 -e -i archive.${\FORMAT} -o document.txt
  44. EOH
  45. exit($code // 0);
  46. }
  47. sub version {
  48. printf("%s %s\n", PKGNAME, VERSION);
  49. exit;
  50. }
  51. sub valid_archive {
  52. my ($fh) = @_;
  53. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  54. $sig eq SIGNATURE || return;
  55. }
  56. return 1;
  57. }
  58. sub main {
  59. my %opt;
  60. getopts('ei:o:vhr', \%opt);
  61. $opt{h} && usage(0);
  62. $opt{v} && version();
  63. my ($input, $output) = @ARGV;
  64. $input //= $opt{i} // usage(2);
  65. $output //= $opt{o};
  66. my $ext = qr{\.${\FORMAT}\z}io;
  67. if ($opt{e} || $input =~ $ext) {
  68. if (not defined $output) {
  69. ($output = basename($input)) =~ s{$ext}{}
  70. || die "$0: no output file specified!\n";
  71. }
  72. if (not $opt{r} and -e $output) {
  73. print "'$output' already exists! -- Replace? [y/N] ";
  74. <STDIN> =~ /^y/i || exit 17;
  75. }
  76. decompress_file($input, $output)
  77. || die "$0: error: decompression failed!\n";
  78. }
  79. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  80. $output //= basename($input) . '.' . FORMAT;
  81. compress_file($input, $output)
  82. || die "$0: error: compression failed!\n";
  83. }
  84. else {
  85. warn "$0: don't know what to do...\n";
  86. usage(1);
  87. }
  88. }
  89. sub read_bit ($fh, $bitstring) {
  90. if (($$bitstring // '') eq '') {
  91. $$bitstring = unpack('b*', getc($fh) // return undef);
  92. }
  93. chop($$bitstring);
  94. }
  95. sub read_bits ($fh, $bits_len) {
  96. my $data = '';
  97. read($fh, $data, $bits_len >> 3);
  98. $data = unpack('B*', $data);
  99. while (length($data) < $bits_len) {
  100. $data .= unpack('B*', getc($fh) // return undef);
  101. }
  102. if (length($data) > $bits_len) {
  103. $data = substr($data, 0, $bits_len);
  104. }
  105. return $data;
  106. }
  107. sub delta_encode ($integers, $double = 0) {
  108. my @deltas;
  109. my $prev = 0;
  110. unshift(@$integers, scalar(@$integers));
  111. while (@$integers) {
  112. my $curr = shift(@$integers);
  113. push @deltas, $curr - $prev;
  114. $prev = $curr;
  115. }
  116. my $bitstring = '';
  117. foreach my $d (@deltas) {
  118. if ($d == 0) {
  119. $bitstring .= '0';
  120. }
  121. elsif ($double) {
  122. my $t = sprintf('%b', abs($d) + 1);
  123. my $l = sprintf('%b', length($t));
  124. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($l) - 1)) . '0' . substr($l, 1) . substr($t, 1);
  125. }
  126. else {
  127. my $t = sprintf('%b', abs($d));
  128. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($t) - 1)) . '0' . substr($t, 1);
  129. }
  130. }
  131. pack('B*', $bitstring);
  132. }
  133. sub delta_decode ($fh, $double = 0) {
  134. my @deltas;
  135. my $buffer = '';
  136. my $len = 0;
  137. for (my $k = 0 ; $k <= $len ; ++$k) {
  138. my $bit = read_bit($fh, \$buffer);
  139. if ($bit eq '0') {
  140. push @deltas, 0;
  141. }
  142. elsif ($double) {
  143. my $bit = read_bit($fh, \$buffer);
  144. my $bl = 0;
  145. ++$bl while (read_bit($fh, \$buffer) eq '1');
  146. my $bl2 = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $bl));
  147. my $int = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. ($bl2 - 1)));
  148. push @deltas, ($bit eq '1' ? 1 : -1) * ($int - 1);
  149. }
  150. else {
  151. my $bit = read_bit($fh, \$buffer);
  152. my $n = 0;
  153. ++$n while (read_bit($fh, \$buffer) eq '1');
  154. my $d = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $n));
  155. push @deltas, ($bit eq '1' ? $d : -$d);
  156. }
  157. if ($k == 0) {
  158. $len = pop(@deltas);
  159. }
  160. }
  161. my @acc;
  162. my $prev = $len;
  163. foreach my $d (@deltas) {
  164. $prev += $d;
  165. push @acc, $prev;
  166. }
  167. return \@acc;
  168. }
  169. sub lz77_compression ($str, $uncompressed, $indices, $lengths) {
  170. my $la = 0;
  171. my $prefix = '';
  172. my @chars = split(//, $str);
  173. my $end = $#chars;
  174. while ($la <= $end) {
  175. my $n = 1;
  176. my $p = 0;
  177. my $tmp;
  178. my $token = $chars[$la];
  179. while ( $n < 255
  180. and $la + $n <= $end
  181. and ($tmp = index($prefix, $token, $p)) >= 0) {
  182. $p = $tmp;
  183. $token .= $chars[$la + $n];
  184. ++$n;
  185. }
  186. --$n;
  187. push @$indices, $p;
  188. push @$lengths, $n;
  189. push @$uncompressed, $chars[$la + $n];
  190. $la += $n + 1;
  191. $prefix .= $token;
  192. }
  193. return;
  194. }
  195. sub lz77_decompression ($uncompressed, $indices, $lengths) {
  196. my $ret = '';
  197. my $chunk = '';
  198. foreach my $i (0 .. $#{$uncompressed}) {
  199. $chunk .= substr($chunk, $indices->[$i], $lengths->[$i]) . chr($uncompressed->[$i]);
  200. if (length($chunk) >= CHUNK_SIZE) {
  201. $ret .= $chunk;
  202. $chunk = '';
  203. }
  204. }
  205. if ($chunk ne '') {
  206. $ret .= $chunk;
  207. }
  208. $ret;
  209. }
  210. sub create_cfreq ($freq) {
  211. my @cf;
  212. my $T = 0;
  213. foreach my $i (sort { $a <=> $b } keys %$freq) {
  214. $freq->{$i} // next;
  215. $cf[$i] = $T;
  216. $T += $freq->{$i};
  217. $cf[$i + 1] = $T;
  218. }
  219. return (\@cf, $T);
  220. }
  221. sub ac_encode ($bytes_arr) {
  222. my $enc = '';
  223. my $EOF_SYMBOL = (max(@$bytes_arr) // 0) + 1;
  224. my @bytes = (@$bytes_arr, $EOF_SYMBOL);
  225. my %freq;
  226. ++$freq{$_} for @bytes;
  227. my ($cf, $T) = create_cfreq(\%freq);
  228. if ($T > MAX) {
  229. die "Too few bits: $T > ${\MAX}";
  230. }
  231. my $low = 0;
  232. my $high = MAX;
  233. my $uf_count = 0;
  234. foreach my $c (@bytes) {
  235. my $w = $high - $low + 1;
  236. $high = ($low + int(($w * $cf->[$c + 1]) / $T) - 1) & MAX;
  237. $low = ($low + int(($w * $cf->[$c]) / $T)) & MAX;
  238. if ($high > MAX) {
  239. die "high > MAX: $high > ${\MAX}";
  240. }
  241. if ($low >= $high) { die "$low >= $high" }
  242. while (1) {
  243. if (($high >> (BITS - 1)) == ($low >> (BITS - 1))) {
  244. my $bit = $high >> (BITS - 1);
  245. $enc .= $bit;
  246. if ($uf_count > 0) {
  247. $enc .= join('', 1 - $bit) x $uf_count;
  248. $uf_count = 0;
  249. }
  250. $low <<= 1;
  251. ($high <<= 1) |= 1;
  252. }
  253. elsif (((($low >> (BITS - 2)) & 0x1) == 1) && ((($high >> (BITS - 2)) & 0x1) == 0)) {
  254. ($high <<= 1) |= (1 << (BITS - 1));
  255. $high |= 1;
  256. ($low <<= 1) &= ((1 << (BITS - 1)) - 1);
  257. ++$uf_count;
  258. }
  259. else {
  260. last;
  261. }
  262. $low &= MAX;
  263. $high &= MAX;
  264. }
  265. }
  266. $enc .= '0';
  267. $enc .= '1';
  268. while (length($enc) % 8 != 0) {
  269. $enc .= '1';
  270. }
  271. return ($enc, \%freq);
  272. }
  273. sub ac_decode ($fh, $freq) {
  274. my ($cf, $T) = create_cfreq($freq);
  275. my @dec;
  276. my $low = 0;
  277. my $high = MAX;
  278. my $enc = oct('0b' . join '', map { getc($fh) // 1 } 1 .. BITS);
  279. my @table;
  280. foreach my $i (sort { $a <=> $b } keys %$freq) {
  281. foreach my $j ($cf->[$i] .. $cf->[$i + 1] - 1) {
  282. $table[$j] = $i;
  283. }
  284. }
  285. my $EOF_SYMBOL = max(keys %$freq) // 0;
  286. while (1) {
  287. my $w = $high - $low + 1;
  288. my $ss = int((($T * ($enc - $low + 1)) - 1) / $w);
  289. my $i = $table[$ss] // last;
  290. last if ($i == $EOF_SYMBOL);
  291. push @dec, $i;
  292. $high = ($low + int(($w * $cf->[$i + 1]) / $T) - 1) & MAX;
  293. $low = ($low + int(($w * $cf->[$i]) / $T)) & MAX;
  294. if ($high > MAX) {
  295. die "error";
  296. }
  297. if ($low >= $high) { die "$low >= $high" }
  298. while (1) {
  299. if (($high >> (BITS - 1)) == ($low >> (BITS - 1))) {
  300. ($high <<= 1) |= 1;
  301. $low <<= 1;
  302. ($enc <<= 1) |= (getc($fh) // 1);
  303. }
  304. elsif (((($low >> (BITS - 2)) & 0x1) == 1) && ((($high >> (BITS - 2)) & 0x1) == 0)) {
  305. ($high <<= 1) |= (1 << (BITS - 1));
  306. $high |= 1;
  307. ($low <<= 1) &= ((1 << (BITS - 1)) - 1);
  308. $enc = (($enc >> (BITS - 1)) << (BITS - 1)) | (($enc & ((1 << (BITS - 2)) - 1)) << 1) | (getc($fh) // 1);
  309. }
  310. else {
  311. last;
  312. }
  313. $low &= MAX;
  314. $high &= MAX;
  315. $enc &= MAX;
  316. }
  317. }
  318. return \@dec;
  319. }
  320. sub create_ac_entry ($bytes, $out_fh) {
  321. my ($enc, $freq) = ac_encode($bytes);
  322. my $max_symbol = max(keys %$freq) // 0;
  323. my @freqs;
  324. foreach my $k (0 .. $max_symbol) {
  325. push @freqs, $freq->{$k} // 0;
  326. }
  327. push @freqs, length($enc) >> 3;
  328. print $out_fh delta_encode(\@freqs);
  329. print $out_fh pack("B*", $enc);
  330. }
  331. sub decode_ac_entry ($fh) {
  332. my @freqs = @{delta_decode($fh)};
  333. my $bits_len = pop(@freqs);
  334. my %freq;
  335. foreach my $i (0 .. $#freqs) {
  336. if ($freqs[$i]) {
  337. $freq{$i} = $freqs[$i];
  338. }
  339. }
  340. say "Encoded length: $bits_len";
  341. my $bits = read_bits($fh, $bits_len << 3);
  342. if ($bits_len > 0) {
  343. open my $bits_fh, '<:raw', \$bits;
  344. return ac_decode($bits_fh, \%freq);
  345. }
  346. return [];
  347. }
  348. # Compress file
  349. sub compress_file ($input, $output) {
  350. open my $fh, '<:raw', $input
  351. or die "Can't open file <<$input>> for reading: $!";
  352. my $header = SIGNATURE;
  353. # Open the output file for writing
  354. open my $out_fh, '>:raw', $output
  355. or die "Can't open file <<$output>> for write: $!";
  356. # Print the header
  357. print $out_fh $header;
  358. my (@uncompressed, @indices, @lengths);
  359. # Compress data
  360. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  361. lz77_compression($chunk, \@uncompressed, \@indices, \@lengths);
  362. }
  363. @indices = unpack('C*', pack('S*', @indices));
  364. @uncompressed = unpack('C*', join('', @uncompressed));
  365. create_ac_entry(\@uncompressed, $out_fh);
  366. create_ac_entry(\@indices, $out_fh);
  367. create_ac_entry(\@lengths, $out_fh);
  368. # Close the file
  369. close $out_fh;
  370. }
  371. # Decompress file
  372. sub decompress_file ($input, $output) {
  373. # Open and validate the input file
  374. open my $fh, '<:raw', $input
  375. or die "Can't open file <<$input>> for reading: $!";
  376. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  377. # Open the output file
  378. open my $out_fh, '>:raw', $output
  379. or die "Can't open file <<$output>> for writing: $!";
  380. my $uncompressed = decode_ac_entry($fh);
  381. my @indices = unpack('S*', pack('C*', @{decode_ac_entry($fh)}));
  382. my $lengths = decode_ac_entry($fh);
  383. print $out_fh lz77_decompression($uncompressed, \@indices, $lengths);
  384. # Close the file
  385. close $fh;
  386. close $out_fh;
  387. }
  388. main();
  389. exit(0);