bwlza2_file_compression.pl 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 15 June 2023
  4. # Edit: 19 March 2024
  5. # https://github.com/trizen
  6. # Compress/decompress files using Burrows-Wheeler Transform (BWT) + LZ77 compression (LZHD variant) + Arithmetic Coding (in fixed bits).
  7. # Encoding the distances using a DEFLATE-like approach.
  8. # References:
  9. # Data Compression (Summer 2023) - Lecture 11 - DEFLATE (gzip)
  10. # https://youtube.com/watch?v=SJPvNi4HrWQ
  11. #
  12. # Data Compression (Summer 2023) - Lecture 13 - BZip2
  13. # https://youtube.com/watch?v=cvoZbBZ3M2A
  14. #
  15. # Basic arithmetic coder in C++
  16. # https://github.com/billbird/arith32
  17. use 5.036;
  18. use Getopt::Std qw(getopts);
  19. use File::Basename qw(basename);
  20. use List::Util qw(max uniq sum);
  21. use constant {
  22. PKGNAME => 'BWLZA2',
  23. VERSION => '0.01',
  24. FORMAT => 'bwlza2',
  25. CHUNK_SIZE => 1 << 17, # higher value = better compression
  26. LOOKAHEAD_LEN => 128,
  27. };
  28. # Arithmetic Coding settings
  29. use constant BITS => 32;
  30. use constant MAX => oct('0b' . ('1' x BITS));
  31. # Container signature
  32. use constant SIGNATURE => uc(FORMAT) . chr(1);
  33. # [distance value, offset bits]
  34. my @DISTANCE_SYMBOLS = map { [$_, 0] } (0 .. 4);
  35. until ($DISTANCE_SYMBOLS[-1][0] > CHUNK_SIZE) {
  36. push @DISTANCE_SYMBOLS, [int($DISTANCE_SYMBOLS[-1][0] * (4 / 3)), $DISTANCE_SYMBOLS[-1][1] + 1];
  37. push @DISTANCE_SYMBOLS, [int($DISTANCE_SYMBOLS[-1][0] * (3 / 2)), $DISTANCE_SYMBOLS[-1][1]];
  38. }
  39. my @DISTANCE_INDICES;
  40. foreach my $i (0 .. $#DISTANCE_SYMBOLS) {
  41. my ($min, $bits) = @{$DISTANCE_SYMBOLS[$i]};
  42. foreach my $k ($min .. $min + (1 << $bits) - 1) {
  43. last if ($k > CHUNK_SIZE);
  44. $DISTANCE_INDICES[$k] = $i;
  45. }
  46. }
  47. sub usage {
  48. my ($code) = @_;
  49. print <<"EOH";
  50. usage: $0 [options] [input file] [output file]
  51. options:
  52. -e : extract
  53. -i <filename> : input filename
  54. -o <filename> : output filename
  55. -r : rewrite output
  56. -v : version number
  57. -h : this message
  58. examples:
  59. $0 document.txt
  60. $0 document.txt archive.${\FORMAT}
  61. $0 archive.${\FORMAT} document.txt
  62. $0 -e -i archive.${\FORMAT} -o document.txt
  63. EOH
  64. exit($code // 0);
  65. }
  66. sub version {
  67. printf("%s %s\n", PKGNAME, VERSION);
  68. exit;
  69. }
  70. sub valid_archive {
  71. my ($fh) = @_;
  72. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  73. $sig eq SIGNATURE || return;
  74. }
  75. return 1;
  76. }
  77. sub main {
  78. my %opt;
  79. getopts('ei:o:vhr', \%opt);
  80. $opt{h} && usage(0);
  81. $opt{v} && version();
  82. my ($input, $output) = @ARGV;
  83. $input //= $opt{i} // usage(2);
  84. $output //= $opt{o};
  85. my $ext = qr{\.${\FORMAT}\z}io;
  86. if ($opt{e} || $input =~ $ext) {
  87. if (not defined $output) {
  88. ($output = basename($input)) =~ s{$ext}{}
  89. || die "$0: no output file specified!\n";
  90. }
  91. if (not $opt{r} and -e $output) {
  92. print "'$output' already exists! -- Replace? [y/N] ";
  93. <STDIN> =~ /^y/i || exit 17;
  94. }
  95. decompress_file($input, $output)
  96. || die "$0: error: decompression failed!\n";
  97. }
  98. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  99. $output //= basename($input) . '.' . FORMAT;
  100. compress_file($input, $output)
  101. || die "$0: error: compression failed!\n";
  102. }
  103. else {
  104. warn "$0: don't know what to do...\n";
  105. usage(1);
  106. }
  107. }
  108. sub lz77_compression ($str, $uncompressed, $indices, $lengths) {
  109. my $la = 0;
  110. my $prefix = '';
  111. my @chars = split(//, $str);
  112. my $end = $#chars;
  113. while ($la <= $end) {
  114. my $n = 1;
  115. my $p = length($prefix);
  116. my $tmp;
  117. my $token = $chars[$la];
  118. while ( $n < 255
  119. and $la + $n <= $end
  120. and ($tmp = rindex($prefix, $token, $p)) >= 0) {
  121. $p = $tmp;
  122. $token .= $chars[$la + $n];
  123. ++$n;
  124. }
  125. --$n;
  126. push @$indices, $la - $p;
  127. push @$lengths, $n;
  128. push @$uncompressed, ord($chars[$la + $n]);
  129. $la += $n + 1;
  130. $prefix .= $token;
  131. }
  132. return;
  133. }
  134. sub lz77_decompression ($uncompressed, $indices, $lengths) {
  135. my $chunk = '';
  136. my $offset = 0;
  137. foreach my $i (0 .. $#{$uncompressed}) {
  138. $chunk .= substr($chunk, $offset - $indices->[$i], $lengths->[$i]) . chr($uncompressed->[$i]);
  139. $offset += $lengths->[$i] + 1;
  140. }
  141. return $chunk;
  142. }
  143. sub read_bit ($fh, $bitstring) {
  144. if (($$bitstring // '') eq '') {
  145. $$bitstring = unpack('b*', getc($fh) // return undef);
  146. }
  147. chop($$bitstring);
  148. }
  149. sub read_bits ($fh, $bits_len) {
  150. my $data = '';
  151. read($fh, $data, $bits_len >> 3);
  152. $data = unpack('B*', $data);
  153. while (length($data) < $bits_len) {
  154. $data .= unpack('B*', getc($fh) // return undef);
  155. }
  156. if (length($data) > $bits_len) {
  157. $data = substr($data, 0, $bits_len);
  158. }
  159. return $data;
  160. }
  161. sub delta_encode ($integers, $double = 0) {
  162. my @deltas;
  163. my $prev = 0;
  164. unshift(@$integers, scalar(@$integers));
  165. while (@$integers) {
  166. my $curr = shift(@$integers);
  167. push @deltas, $curr - $prev;
  168. $prev = $curr;
  169. }
  170. my $bitstring = '';
  171. foreach my $d (@deltas) {
  172. if ($d == 0) {
  173. $bitstring .= '0';
  174. }
  175. elsif ($double) {
  176. my $t = sprintf('%b', abs($d) + 1);
  177. my $l = sprintf('%b', length($t));
  178. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($l) - 1)) . '0' . substr($l, 1) . substr($t, 1);
  179. }
  180. else {
  181. my $t = sprintf('%b', abs($d));
  182. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($t) - 1)) . '0' . substr($t, 1);
  183. }
  184. }
  185. pack('B*', $bitstring);
  186. }
  187. sub delta_decode ($fh, $double = 0) {
  188. my @deltas;
  189. my $buffer = '';
  190. my $len = 0;
  191. for (my $k = 0 ; $k <= $len ; ++$k) {
  192. my $bit = read_bit($fh, \$buffer);
  193. if ($bit eq '0') {
  194. push @deltas, 0;
  195. }
  196. elsif ($double) {
  197. my $bit = read_bit($fh, \$buffer);
  198. my $bl = 0;
  199. ++$bl while (read_bit($fh, \$buffer) eq '1');
  200. my $bl2 = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $bl));
  201. my $int = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. ($bl2 - 1)));
  202. push @deltas, ($bit eq '1' ? 1 : -1) * ($int - 1);
  203. }
  204. else {
  205. my $bit = read_bit($fh, \$buffer);
  206. my $n = 0;
  207. ++$n while (read_bit($fh, \$buffer) eq '1');
  208. my $d = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $n));
  209. push @deltas, ($bit eq '1' ? $d : -$d);
  210. }
  211. if ($k == 0) {
  212. $len = pop(@deltas);
  213. }
  214. }
  215. my @acc;
  216. my $prev = $len;
  217. foreach my $d (@deltas) {
  218. $prev += $d;
  219. push @acc, $prev;
  220. }
  221. return \@acc;
  222. }
  223. sub create_cfreq ($freq) {
  224. my @cf;
  225. my $T = 0;
  226. foreach my $i (sort { $a <=> $b } keys %$freq) {
  227. $freq->{$i} // next;
  228. $cf[$i] = $T;
  229. $T += $freq->{$i};
  230. $cf[$i + 1] = $T;
  231. }
  232. return (\@cf, $T);
  233. }
  234. sub ac_encode ($bytes_arr) {
  235. my $enc = '';
  236. my $EOF_SYMBOL = (max(@$bytes_arr) // 0) + 1;
  237. my @bytes = (@$bytes_arr, $EOF_SYMBOL);
  238. my %freq;
  239. ++$freq{$_} for @bytes;
  240. my ($cf, $T) = create_cfreq(\%freq);
  241. if ($T > MAX) {
  242. die "Too few bits: $T > ${\MAX}";
  243. }
  244. my $low = 0;
  245. my $high = MAX;
  246. my $uf_count = 0;
  247. foreach my $c (@bytes) {
  248. my $w = $high - $low + 1;
  249. $high = ($low + int(($w * $cf->[$c + 1]) / $T) - 1) & MAX;
  250. $low = ($low + int(($w * $cf->[$c]) / $T)) & MAX;
  251. if ($high > MAX) {
  252. die "high > MAX: $high > ${\MAX}";
  253. }
  254. if ($low >= $high) { die "$low >= $high" }
  255. while (1) {
  256. if (($high >> (BITS - 1)) == ($low >> (BITS - 1))) {
  257. my $bit = $high >> (BITS - 1);
  258. $enc .= $bit;
  259. if ($uf_count > 0) {
  260. $enc .= join('', 1 - $bit) x $uf_count;
  261. $uf_count = 0;
  262. }
  263. $low <<= 1;
  264. ($high <<= 1) |= 1;
  265. }
  266. elsif (((($low >> (BITS - 2)) & 0x1) == 1) && ((($high >> (BITS - 2)) & 0x1) == 0)) {
  267. ($high <<= 1) |= (1 << (BITS - 1));
  268. $high |= 1;
  269. ($low <<= 1) &= ((1 << (BITS - 1)) - 1);
  270. ++$uf_count;
  271. }
  272. else {
  273. last;
  274. }
  275. $low &= MAX;
  276. $high &= MAX;
  277. }
  278. }
  279. $enc .= '0';
  280. $enc .= '1';
  281. while (length($enc) % 8 != 0) {
  282. $enc .= '1';
  283. }
  284. return ($enc, \%freq);
  285. }
  286. sub ac_decode ($fh, $freq) {
  287. my ($cf, $T) = create_cfreq($freq);
  288. my @dec;
  289. my $low = 0;
  290. my $high = MAX;
  291. my $enc = oct('0b' . join '', map { getc($fh) // 1 } 1 .. BITS);
  292. my @table;
  293. foreach my $i (sort { $a <=> $b } keys %$freq) {
  294. foreach my $j ($cf->[$i] .. $cf->[$i + 1] - 1) {
  295. $table[$j] = $i;
  296. }
  297. }
  298. my $EOF_SYMBOL = max(keys %$freq) // 0;
  299. while (1) {
  300. my $w = $high - $low + 1;
  301. my $ss = int((($T * ($enc - $low + 1)) - 1) / $w);
  302. my $i = $table[$ss] // last;
  303. last if ($i == $EOF_SYMBOL);
  304. push @dec, $i;
  305. $high = ($low + int(($w * $cf->[$i + 1]) / $T) - 1) & MAX;
  306. $low = ($low + int(($w * $cf->[$i]) / $T)) & MAX;
  307. if ($high > MAX) {
  308. die "error";
  309. }
  310. if ($low >= $high) { die "$low >= $high" }
  311. while (1) {
  312. if (($high >> (BITS - 1)) == ($low >> (BITS - 1))) {
  313. ($high <<= 1) |= 1;
  314. $low <<= 1;
  315. ($enc <<= 1) |= (getc($fh) // 1);
  316. }
  317. elsif (((($low >> (BITS - 2)) & 0x1) == 1) && ((($high >> (BITS - 2)) & 0x1) == 0)) {
  318. ($high <<= 1) |= (1 << (BITS - 1));
  319. $high |= 1;
  320. ($low <<= 1) &= ((1 << (BITS - 1)) - 1);
  321. $enc = (($enc >> (BITS - 1)) << (BITS - 1)) | (($enc & ((1 << (BITS - 2)) - 1)) << 1) | (getc($fh) // 1);
  322. }
  323. else {
  324. last;
  325. }
  326. $low &= MAX;
  327. $high &= MAX;
  328. $enc &= MAX;
  329. }
  330. }
  331. return \@dec;
  332. }
  333. sub create_ac_entry ($bytes, $out_fh) {
  334. my ($enc, $freq) = ac_encode($bytes);
  335. my $max_symbol = max(keys %$freq) // 0;
  336. my @freqs;
  337. foreach my $k (0 .. $max_symbol) {
  338. push @freqs, $freq->{$k} // 0;
  339. }
  340. push @freqs, length($enc) >> 3;
  341. say "Max symbol: $max_symbol";
  342. print $out_fh delta_encode(\@freqs);
  343. print $out_fh pack("B*", $enc);
  344. }
  345. sub decode_ac_entry ($fh) {
  346. my @freqs = @{delta_decode($fh)};
  347. my $bits_len = pop(@freqs);
  348. my %freq;
  349. foreach my $i (0 .. $#freqs) {
  350. if ($freqs[$i]) {
  351. $freq{$i} = $freqs[$i];
  352. }
  353. }
  354. say "Encoded length: $bits_len";
  355. my $bits = read_bits($fh, $bits_len << 3);
  356. if ($bits_len > 0) {
  357. open my $bits_fh, '<:raw', \$bits;
  358. return ac_decode($bits_fh, \%freq);
  359. }
  360. return [];
  361. }
  362. sub encode_distances ($distances, $out_fh) {
  363. my @symbols;
  364. my $offset_bits = '';
  365. foreach my $dist (@$distances) {
  366. my $i = $DISTANCE_INDICES[$dist];
  367. my ($min, $bits) = @{$DISTANCE_SYMBOLS[$i]};
  368. push @symbols, $i;
  369. if ($bits > 0) {
  370. $offset_bits .= sprintf('%0*b', $bits, $dist - $min);
  371. }
  372. }
  373. create_ac_entry(\@symbols, $out_fh);
  374. print $out_fh pack('B*', $offset_bits);
  375. }
  376. sub decode_distances ($fh) {
  377. my $symbols = decode_ac_entry($fh);
  378. my $bits_len = 0;
  379. foreach my $i (@$symbols) {
  380. $bits_len += $DISTANCE_SYMBOLS[$i][1];
  381. }
  382. my $bits = read_bits($fh, $bits_len);
  383. my @distances;
  384. foreach my $i (@$symbols) {
  385. push @distances, $DISTANCE_SYMBOLS[$i][0] + oct('0b' . substr($bits, 0, $DISTANCE_SYMBOLS[$i][1], ''));
  386. }
  387. return \@distances;
  388. }
  389. sub mtf_encode ($bytes, $alphabet = [0 .. 255]) {
  390. my @C;
  391. my @table;
  392. @table[@$alphabet] = (0 .. $#{$alphabet});
  393. foreach my $c (@$bytes) {
  394. push @C, (my $index = $table[$c]);
  395. unshift(@$alphabet, splice(@$alphabet, $index, 1));
  396. @table[@{$alphabet}[0 .. $index]] = (0 .. $index);
  397. }
  398. return \@C;
  399. }
  400. sub mtf_decode ($encoded, $alphabet = [0 .. 255]) {
  401. my @S;
  402. foreach my $p (@$encoded) {
  403. push @S, $alphabet->[$p];
  404. unshift(@$alphabet, splice(@$alphabet, $p, 1));
  405. }
  406. return \@S;
  407. }
  408. sub bwt_balanced ($s) { # O(n * LOOKAHEAD_LEN) space (fast)
  409. #<<<
  410. [
  411. map { $_->[1] } sort {
  412. ($a->[0] cmp $b->[0])
  413. || ((substr($s, $a->[1]) . substr($s, 0, $a->[1])) cmp(substr($s, $b->[1]) . substr($s, 0, $b->[1])))
  414. }
  415. map {
  416. my $t = substr($s, $_, LOOKAHEAD_LEN);
  417. if (length($t) < LOOKAHEAD_LEN) {
  418. $t .= substr($s, 0, ($_ < LOOKAHEAD_LEN) ? $_ : (LOOKAHEAD_LEN - length($t)));
  419. }
  420. [$t, $_]
  421. } 0 .. length($s) - 1
  422. ];
  423. #>>>
  424. }
  425. sub bwt_encode ($s) {
  426. my $bwt = bwt_balanced($s);
  427. my $ret = join('', map { substr($s, $_ - 1, 1) } @$bwt);
  428. my $idx = 0;
  429. foreach my $i (@$bwt) {
  430. $i || last;
  431. ++$idx;
  432. }
  433. return ($ret, $idx);
  434. }
  435. sub bwt_decode ($bwt, $idx) { # fast inversion
  436. my @tail = split(//, $bwt);
  437. my @head = sort @tail;
  438. my %indices;
  439. foreach my $i (0 .. $#tail) {
  440. push @{$indices{$tail[$i]}}, $i;
  441. }
  442. my @table;
  443. foreach my $v (@head) {
  444. push @table, shift(@{$indices{$v}});
  445. }
  446. my $dec = '';
  447. my $i = $idx;
  448. for (1 .. scalar(@head)) {
  449. $dec .= $head[$i];
  450. $i = $table[$i];
  451. }
  452. return $dec;
  453. }
  454. sub rle4_encode ($bytes) { # RLE1
  455. my @rle;
  456. my $end = $#{$bytes};
  457. my $prev = -1;
  458. my $run = 0;
  459. for (my $i = 0 ; $i <= $end ; ++$i) {
  460. if ($bytes->[$i] == $prev) {
  461. ++$run;
  462. }
  463. else {
  464. $run = 1;
  465. }
  466. push @rle, $bytes->[$i];
  467. $prev = $bytes->[$i];
  468. if ($run >= 4) {
  469. $run = 0;
  470. $i += 1;
  471. while ($run < 254 and $i <= $end and $bytes->[$i] == $prev) {
  472. ++$run;
  473. ++$i;
  474. }
  475. push @rle, $run;
  476. $run = 1;
  477. if ($i <= $end) {
  478. $prev = $bytes->[$i];
  479. push @rle, $bytes->[$i];
  480. }
  481. }
  482. }
  483. return \@rle;
  484. }
  485. sub rle4_decode ($bytes) { # RLE1
  486. my @dec = $bytes->[0];
  487. my $end = $#{$bytes};
  488. my $prev = $bytes->[0];
  489. my $run = 1;
  490. for (my $i = 1 ; $i <= $end ; ++$i) {
  491. if ($bytes->[$i] == $prev) {
  492. ++$run;
  493. }
  494. else {
  495. $run = 1;
  496. }
  497. push @dec, $bytes->[$i];
  498. $prev = $bytes->[$i];
  499. if ($run >= 4) {
  500. if (++$i <= $end) {
  501. $run = $bytes->[$i];
  502. push @dec, (($prev) x $run);
  503. }
  504. $run = 0;
  505. }
  506. }
  507. return \@dec;
  508. }
  509. sub rle_encode ($bytes) { # RLE2
  510. my @rle;
  511. my $end = $#{$bytes};
  512. for (my $i = 0 ; $i <= $end ; ++$i) {
  513. my $run = 0;
  514. while ($i <= $end and $bytes->[$i] == 0) {
  515. ++$run;
  516. ++$i;
  517. }
  518. if ($run >= 1) {
  519. my $t = sprintf('%b', $run + 1);
  520. push @rle, split(//, substr($t, 1));
  521. }
  522. if ($i <= $end) {
  523. push @rle, $bytes->[$i] + 1;
  524. }
  525. }
  526. return \@rle;
  527. }
  528. sub rle_decode ($rle) { # RLE2
  529. my @dec;
  530. my $end = $#{$rle};
  531. for (my $i = 0 ; $i <= $end ; ++$i) {
  532. my $k = $rle->[$i];
  533. if ($k == 0 or $k == 1) {
  534. my $run = 1;
  535. while (($i <= $end) and ($k == 0 or $k == 1)) {
  536. ($run <<= 1) |= $k;
  537. $k = $rle->[++$i];
  538. }
  539. push @dec, (0) x ($run - 1);
  540. }
  541. if ($i <= $end) {
  542. push @dec, $k - 1;
  543. }
  544. }
  545. return \@dec;
  546. }
  547. sub encode_alphabet ($alphabet) {
  548. my %table;
  549. @table{@$alphabet} = ();
  550. my $populated = 0;
  551. my @marked;
  552. for (my $i = 0 ; $i <= 255 ; $i += 32) {
  553. my $enc = 0;
  554. foreach my $j (0 .. 31) {
  555. if (exists($table{$i + $j})) {
  556. $enc |= 1 << $j;
  557. }
  558. }
  559. if ($enc == 0) {
  560. $populated <<= 1;
  561. }
  562. else {
  563. ($populated <<= 1) |= 1;
  564. push @marked, $enc;
  565. }
  566. }
  567. my $delta = delta_encode([@marked], 1);
  568. say "Populated : ", sprintf('%08b', $populated);
  569. say "Marked : @marked";
  570. say "Delta len : ", length($delta);
  571. my $encoded = '';
  572. $encoded .= chr($populated);
  573. $encoded .= $delta;
  574. return $encoded;
  575. }
  576. sub decode_alphabet ($fh) {
  577. my @populated = split(//, sprintf('%08b', ord(getc($fh) // die "error")));
  578. my $marked = delta_decode($fh, 1);
  579. my @alphabet;
  580. for (my $i = 0 ; $i <= 255 ; $i += 32) {
  581. if (shift(@populated)) {
  582. my $m = shift(@$marked);
  583. foreach my $j (0 .. 31) {
  584. if ($m & 1) {
  585. push @alphabet, $i + $j;
  586. }
  587. $m >>= 1;
  588. }
  589. }
  590. }
  591. return \@alphabet;
  592. }
  593. sub lzhd_compression ($chunk, $out_fh) {
  594. my (@uncompressed, @indices, @lengths);
  595. lz77_compression($chunk, \@uncompressed, \@indices, \@lengths);
  596. my $est_ratio = length($chunk) / (4 * scalar(@uncompressed));
  597. say(scalar(@uncompressed), ' -> ', $est_ratio);
  598. create_ac_entry(\@uncompressed, $out_fh);
  599. create_ac_entry(\@lengths, $out_fh);
  600. encode_distances(\@indices, $out_fh);
  601. }
  602. sub lzhd_decompression ($fh) {
  603. my $uncompressed = decode_ac_entry($fh);
  604. my $lengths = decode_ac_entry($fh);
  605. my $indices = decode_distances($fh);
  606. return lz77_decompression($uncompressed, $indices, $lengths);
  607. }
  608. sub compression ($chunk, $out_fh) {
  609. my @chunk_bytes = unpack('C*', $chunk);
  610. my $data = pack('C*', @{rle4_encode(\@chunk_bytes)});
  611. my ($bwt, $idx) = bwt_encode($data);
  612. my @bytes = unpack('C*', $bwt);
  613. my @alphabet = sort { $a <=> $b } uniq(@bytes);
  614. my $enc_bytes = mtf_encode(\@bytes, [@alphabet]);
  615. if (max(@$enc_bytes) < 255) {
  616. print $out_fh chr(1);
  617. $enc_bytes = rle_encode($enc_bytes);
  618. }
  619. else {
  620. print $out_fh chr(0);
  621. $enc_bytes = rle4_encode($enc_bytes);
  622. }
  623. print $out_fh pack('N', $idx);
  624. print $out_fh encode_alphabet(\@alphabet);
  625. lzhd_compression(pack('C*', @$enc_bytes), $out_fh);
  626. }
  627. sub decompression ($fh, $out_fh) {
  628. my $rle_encoded = ord(getc($fh) // die "error");
  629. my $idx = unpack('N', join('', map { getc($fh) // die "error" } 1 .. 4));
  630. my $alphabet = decode_alphabet($fh);
  631. my $bytes = [unpack('C*', lzhd_decompression($fh))];
  632. if ($rle_encoded) {
  633. $bytes = rle_decode($bytes);
  634. }
  635. else {
  636. $bytes = rle4_decode($bytes);
  637. }
  638. $bytes = mtf_decode($bytes, [@$alphabet]);
  639. print $out_fh pack('C*', @{rle4_decode([unpack('C*', bwt_decode(pack('C*', @$bytes), $idx))])});
  640. }
  641. # Compress file
  642. sub compress_file ($input, $output) {
  643. open my $fh, '<:raw', $input
  644. or die "Can't open file <<$input>> for reading: $!";
  645. my $header = SIGNATURE;
  646. # Open the output file for writing
  647. open my $out_fh, '>:raw', $output
  648. or die "Can't open file <<$output>> for write: $!";
  649. # Print the header
  650. print $out_fh $header;
  651. # Compress data
  652. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  653. compression($chunk, $out_fh);
  654. }
  655. # Close the output file
  656. close $out_fh;
  657. }
  658. # Decompress file
  659. sub decompress_file ($input, $output) {
  660. # Open and validate the input file
  661. open my $fh, '<:raw', $input
  662. or die "Can't open file <<$input>> for reading: $!";
  663. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  664. # Open the output file
  665. open my $out_fh, '>:raw', $output
  666. or die "Can't open file <<$output>> for writing: $!";
  667. while (!eof($fh)) {
  668. decompression($fh, $out_fh);
  669. }
  670. # Close the output file
  671. close $out_fh;
  672. }
  673. main();
  674. exit(0);