bwlzad2_file_compression.pl 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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) + Move-to-front transform (MTF) + LZ77 compression (LZHD variant) + Adaptive 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 POSIX qw(ceil log2);
  22. use constant {
  23. PKGNAME => 'BWLZAD2',
  24. VERSION => '0.01',
  25. FORMAT => 'bwlzad2',
  26. COMPRESSED_BYTE => chr(1),
  27. UNCOMPRESSED_BYTE => chr(0),
  28. CHUNK_SIZE => 1 << 17, # higher value = better compression
  29. LOOKAHEAD_LEN => 128,
  30. RANDOM_DATA_THRESHOLD => 1, # in ratio
  31. };
  32. # Arithmetic Coding settings
  33. use constant BITS => 32;
  34. use constant MAX => oct('0b' . ('1' x BITS));
  35. use constant INITIAL_FREQ => 1;
  36. # Container signature
  37. use constant SIGNATURE => uc(FORMAT) . chr(1);
  38. # [distance value, offset bits]
  39. my @DISTANCE_SYMBOLS = map { [$_, 0] } (0 .. 4);
  40. until ($DISTANCE_SYMBOLS[-1][0] > CHUNK_SIZE) {
  41. push @DISTANCE_SYMBOLS, [int($DISTANCE_SYMBOLS[-1][0] * (4 / 3)), $DISTANCE_SYMBOLS[-1][1] + 1];
  42. push @DISTANCE_SYMBOLS, [int($DISTANCE_SYMBOLS[-1][0] * (3 / 2)), $DISTANCE_SYMBOLS[-1][1]];
  43. }
  44. my @DISTANCE_INDICES;
  45. foreach my $i (0 .. $#DISTANCE_SYMBOLS) {
  46. my ($min, $bits) = @{$DISTANCE_SYMBOLS[$i]};
  47. foreach my $k ($min .. $min + (1 << $bits) - 1) {
  48. last if ($k > CHUNK_SIZE);
  49. $DISTANCE_INDICES[$k] = $i;
  50. }
  51. }
  52. sub usage {
  53. my ($code) = @_;
  54. print <<"EOH";
  55. usage: $0 [options] [input file] [output file]
  56. options:
  57. -e : extract
  58. -i <filename> : input filename
  59. -o <filename> : output filename
  60. -r : rewrite output
  61. -v : version number
  62. -h : this message
  63. examples:
  64. $0 document.txt
  65. $0 document.txt archive.${\FORMAT}
  66. $0 archive.${\FORMAT} document.txt
  67. $0 -e -i archive.${\FORMAT} -o document.txt
  68. EOH
  69. exit($code // 0);
  70. }
  71. sub version {
  72. printf("%s %s\n", PKGNAME, VERSION);
  73. exit;
  74. }
  75. sub valid_archive {
  76. my ($fh) = @_;
  77. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  78. $sig eq SIGNATURE || return;
  79. }
  80. return 1;
  81. }
  82. sub main {
  83. my %opt;
  84. getopts('ei:o:vhr', \%opt);
  85. $opt{h} && usage(0);
  86. $opt{v} && version();
  87. my ($input, $output) = @ARGV;
  88. $input //= $opt{i} // usage(2);
  89. $output //= $opt{o};
  90. my $ext = qr{\.${\FORMAT}\z}io;
  91. if ($opt{e} || $input =~ $ext) {
  92. if (not defined $output) {
  93. ($output = basename($input)) =~ s{$ext}{}
  94. || die "$0: no output file specified!\n";
  95. }
  96. if (not $opt{r} and -e $output) {
  97. print "'$output' already exists! -- Replace? [y/N] ";
  98. <STDIN> =~ /^y/i || exit 17;
  99. }
  100. decompress_file($input, $output)
  101. || die "$0: error: decompression failed!\n";
  102. }
  103. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  104. $output //= basename($input) . '.' . FORMAT;
  105. compress_file($input, $output)
  106. || die "$0: error: compression failed!\n";
  107. }
  108. else {
  109. warn "$0: don't know what to do...\n";
  110. usage(1);
  111. }
  112. }
  113. sub lz77_compression ($str, $uncompressed, $indices, $lengths) {
  114. my $la = 0;
  115. my $prefix = '';
  116. my @chars = split(//, $str);
  117. my $end = $#chars;
  118. while ($la <= $end) {
  119. my $n = 1;
  120. my $p = length($prefix);
  121. my $tmp;
  122. my $token = $chars[$la];
  123. while ( $n < 255
  124. and $la + $n <= $end
  125. and ($tmp = rindex($prefix, $token, $p)) >= 0) {
  126. $p = $tmp;
  127. $token .= $chars[$la + $n];
  128. ++$n;
  129. }
  130. --$n;
  131. push @$indices, $la - $p;
  132. push @$lengths, $n;
  133. push @$uncompressed, ord($chars[$la + $n]);
  134. $la += $n + 1;
  135. $prefix .= $token;
  136. }
  137. return;
  138. }
  139. sub lz77_decompression ($uncompressed, $indices, $lengths) {
  140. my $chunk = '';
  141. my $offset = 0;
  142. foreach my $i (0 .. $#{$uncompressed}) {
  143. $chunk .= substr($chunk, $offset - $indices->[$i], $lengths->[$i]) . chr($uncompressed->[$i]);
  144. $offset += $lengths->[$i] + 1;
  145. }
  146. return $chunk;
  147. }
  148. sub read_bit ($fh, $bitstring) {
  149. if (($$bitstring // '') eq '') {
  150. $$bitstring = unpack('b*', getc($fh) // return undef);
  151. }
  152. chop($$bitstring);
  153. }
  154. sub read_bits ($fh, $bits_len) {
  155. my $data = '';
  156. read($fh, $data, $bits_len >> 3);
  157. $data = unpack('B*', $data);
  158. while (length($data) < $bits_len) {
  159. $data .= unpack('B*', getc($fh) // return undef);
  160. }
  161. if (length($data) > $bits_len) {
  162. $data = substr($data, 0, $bits_len);
  163. }
  164. return $data;
  165. }
  166. sub delta_encode ($integers, $double = 0) {
  167. my @deltas;
  168. my $prev = 0;
  169. unshift(@$integers, scalar(@$integers));
  170. while (@$integers) {
  171. my $curr = shift(@$integers);
  172. push @deltas, $curr - $prev;
  173. $prev = $curr;
  174. }
  175. my $bitstring = '';
  176. foreach my $d (@deltas) {
  177. if ($d == 0) {
  178. $bitstring .= '0';
  179. }
  180. elsif ($double) {
  181. my $t = sprintf('%b', abs($d) + 1);
  182. my $l = sprintf('%b', length($t));
  183. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($l) - 1)) . '0' . substr($l, 1) . substr($t, 1);
  184. }
  185. else {
  186. my $t = sprintf('%b', abs($d));
  187. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($t) - 1)) . '0' . substr($t, 1);
  188. }
  189. }
  190. pack('B*', $bitstring);
  191. }
  192. sub delta_decode ($fh, $double = 0) {
  193. my @deltas;
  194. my $buffer = '';
  195. my $len = 0;
  196. for (my $k = 0 ; $k <= $len ; ++$k) {
  197. my $bit = read_bit($fh, \$buffer);
  198. if ($bit eq '0') {
  199. push @deltas, 0;
  200. }
  201. elsif ($double) {
  202. my $bit = read_bit($fh, \$buffer);
  203. my $bl = 0;
  204. ++$bl while (read_bit($fh, \$buffer) eq '1');
  205. my $bl2 = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $bl));
  206. my $int = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. ($bl2 - 1)));
  207. push @deltas, ($bit eq '1' ? 1 : -1) * ($int - 1);
  208. }
  209. else {
  210. my $bit = read_bit($fh, \$buffer);
  211. my $n = 0;
  212. ++$n while (read_bit($fh, \$buffer) eq '1');
  213. my $d = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $n));
  214. push @deltas, ($bit eq '1' ? $d : -$d);
  215. }
  216. if ($k == 0) {
  217. $len = pop(@deltas);
  218. }
  219. }
  220. my @acc;
  221. my $prev = $len;
  222. foreach my $d (@deltas) {
  223. $prev += $d;
  224. push @acc, $prev;
  225. }
  226. return \@acc;
  227. }
  228. sub create_cfreq ($freq_value, $max_symbol) {
  229. my $T = 0;
  230. my (@cf, @freq);
  231. foreach my $i (0 .. $max_symbol) {
  232. $freq[$i] = $freq_value;
  233. $cf[$i] = $T;
  234. $T += $freq_value;
  235. $cf[$i + 1] = $T;
  236. }
  237. return (\@freq, \@cf, $T);
  238. }
  239. sub increment_freq ($c, $max_symbol, $freq, $cf) {
  240. ++$freq->[$c];
  241. my $T = $cf->[$c];
  242. foreach my $i ($c .. $max_symbol) {
  243. $cf->[$i] = $T;
  244. $T += $freq->[$i];
  245. $cf->[$i + 1] = $T;
  246. }
  247. return $T;
  248. }
  249. sub ac_encode ($bytes_arr) {
  250. my $enc = '';
  251. my @bytes = (@$bytes_arr, (max(@$bytes_arr) // 0) + 1);
  252. my $max_symbol = max(@bytes) // 0;
  253. my ($freq, $cf, $T) = create_cfreq(INITIAL_FREQ, $max_symbol);
  254. if ($T > MAX) {
  255. die "Too few bits: $T > ${\MAX}";
  256. }
  257. my $low = 0;
  258. my $high = MAX;
  259. my $uf_count = 0;
  260. foreach my $c (@bytes) {
  261. my $w = $high - $low + 1;
  262. $high = ($low + int(($w * $cf->[$c + 1]) / $T) - 1) & MAX;
  263. $low = ($low + int(($w * $cf->[$c]) / $T)) & MAX;
  264. $T = increment_freq($c, $max_symbol, $freq, $cf);
  265. if ($high > MAX) {
  266. die "high > MAX: $high > ${\MAX}";
  267. }
  268. if ($low >= $high) { die "$low >= $high" }
  269. while (1) {
  270. if (($high >> (BITS - 1)) == ($low >> (BITS - 1))) {
  271. my $bit = $high >> (BITS - 1);
  272. $enc .= $bit;
  273. if ($uf_count > 0) {
  274. $enc .= join('', 1 - $bit) x $uf_count;
  275. $uf_count = 0;
  276. }
  277. $low <<= 1;
  278. ($high <<= 1) |= 1;
  279. }
  280. elsif (((($low >> (BITS - 2)) & 0x1) == 1) && ((($high >> (BITS - 2)) & 0x1) == 0)) {
  281. ($high <<= 1) |= (1 << (BITS - 1));
  282. $high |= 1;
  283. ($low <<= 1) &= ((1 << (BITS - 1)) - 1);
  284. ++$uf_count;
  285. }
  286. else {
  287. last;
  288. }
  289. $low &= MAX;
  290. $high &= MAX;
  291. }
  292. }
  293. $enc .= '0';
  294. $enc .= '1';
  295. while (length($enc) % 8 != 0) {
  296. $enc .= '1';
  297. }
  298. return ($enc, $max_symbol);
  299. }
  300. sub ac_decode ($fh, $max_symbol) {
  301. my ($freq, $cf, $T) = create_cfreq(INITIAL_FREQ, $max_symbol);
  302. my @dec;
  303. my $low = 0;
  304. my $high = MAX;
  305. my $enc = oct('0b' . join '', map { getc($fh) // 1 } 1 .. BITS);
  306. while (1) {
  307. my $w = ($high + 1) - $low;
  308. my $ss = int((($T * ($enc - $low + 1)) - 1) / $w);
  309. my $i = 0;
  310. foreach my $j (0 .. $max_symbol) {
  311. if ($cf->[$j] <= $ss and $ss < $cf->[$j + 1]) {
  312. $i = $j;
  313. last;
  314. }
  315. }
  316. last if ($i == $max_symbol);
  317. push @dec, $i;
  318. $high = ($low + int(($w * $cf->[$i + 1]) / $T) - 1) & MAX;
  319. $low = ($low + int(($w * $cf->[$i]) / $T)) & MAX;
  320. $T = increment_freq($i, $max_symbol, $freq, $cf);
  321. if ($high > MAX) {
  322. die "high > MAX: ($high > ${\MAX})";
  323. }
  324. if ($low >= $high) { die "$low >= $high" }
  325. while (1) {
  326. if (($high >> (BITS - 1)) == ($low >> (BITS - 1))) {
  327. ($high <<= 1) |= 1;
  328. $low <<= 1;
  329. ($enc <<= 1) |= (getc($fh) // 1);
  330. }
  331. elsif (((($low >> (BITS - 2)) & 0x1) == 1) && ((($high >> (BITS - 2)) & 0x1) == 0)) {
  332. ($high <<= 1) |= (1 << (BITS - 1));
  333. $high |= 1;
  334. ($low <<= 1) &= ((1 << (BITS - 1)) - 1);
  335. $enc = (($enc >> (BITS - 1)) << (BITS - 1)) | (($enc & ((1 << (BITS - 2)) - 1)) << 1) | (getc($fh) // 1);
  336. }
  337. else {
  338. last;
  339. }
  340. $low &= MAX;
  341. $high &= MAX;
  342. $enc &= MAX;
  343. }
  344. }
  345. return \@dec;
  346. }
  347. sub create_ac_entry ($bytes, $out_fh) {
  348. my ($enc, $max_symbol) = ac_encode($bytes);
  349. print $out_fh delta_encode([$max_symbol, length($enc)], 1);
  350. print $out_fh pack("B*", $enc);
  351. }
  352. sub decode_ac_entry ($fh) {
  353. my ($max_symbol, $enc_len) = @{delta_decode($fh, 1)};
  354. say "Encoded length: $enc_len";
  355. if ($enc_len > 0) {
  356. my $bits = read_bits($fh, $enc_len);
  357. open my $bits_fh, '<:raw', \$bits;
  358. return ac_decode($bits_fh, $max_symbol);
  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. if ($est_ratio > RANDOM_DATA_THRESHOLD) {
  599. print $out_fh COMPRESSED_BYTE;
  600. create_ac_entry(\@uncompressed, $out_fh);
  601. create_ac_entry(\@lengths, $out_fh);
  602. encode_distances(\@indices, $out_fh);
  603. }
  604. else {
  605. print $out_fh UNCOMPRESSED_BYTE;
  606. create_ac_entry([unpack('C*', $chunk)], $out_fh);
  607. }
  608. }
  609. sub lzhd_decompression ($fh) {
  610. my $compression_byte = getc($fh) // die "decompression error";
  611. if ($compression_byte eq COMPRESSED_BYTE) {
  612. my $uncompressed = decode_ac_entry($fh);
  613. my $lengths = decode_ac_entry($fh);
  614. my $indices = decode_distances($fh);
  615. return lz77_decompression($uncompressed, $indices, $lengths);
  616. }
  617. elsif ($compression_byte eq UNCOMPRESSED_BYTE) {
  618. return pack('C*', @{decode_ac_entry($fh)});
  619. }
  620. else {
  621. die "Invalid compression...";
  622. }
  623. }
  624. sub compression ($chunk, $out_fh) {
  625. my @chunk_bytes = unpack('C*', $chunk);
  626. my $data = pack('C*', @{rle4_encode(\@chunk_bytes)});
  627. my ($bwt, $idx) = bwt_encode($data);
  628. my @bytes = unpack('C*', $bwt);
  629. my @alphabet = sort { $a <=> $b } uniq(@bytes);
  630. my $enc_bytes = mtf_encode(\@bytes, [@alphabet]);
  631. if (max(@$enc_bytes) < 255) {
  632. print $out_fh chr(1);
  633. $enc_bytes = rle_encode($enc_bytes);
  634. }
  635. else {
  636. print $out_fh chr(0);
  637. $enc_bytes = rle4_encode($enc_bytes);
  638. }
  639. print $out_fh pack('N', $idx);
  640. print $out_fh encode_alphabet(\@alphabet);
  641. lzhd_compression(pack('C*', @$enc_bytes), $out_fh);
  642. }
  643. sub decompression ($fh, $out_fh) {
  644. my $rle_encoded = ord(getc($fh) // die "error");
  645. my $idx = unpack('N', join('', map { getc($fh) // die "error" } 1 .. 4));
  646. my $alphabet = decode_alphabet($fh);
  647. my $bytes = [unpack('C*', lzhd_decompression($fh))];
  648. if ($rle_encoded) {
  649. $bytes = rle_decode($bytes);
  650. }
  651. else {
  652. $bytes = rle4_decode($bytes);
  653. }
  654. $bytes = mtf_decode($bytes, [@$alphabet]);
  655. print $out_fh pack('C*', @{rle4_decode([unpack('C*', bwt_decode(pack('C*', @$bytes), $idx))])});
  656. }
  657. # Compress file
  658. sub compress_file ($input, $output) {
  659. open my $fh, '<:raw', $input
  660. or die "Can't open file <<$input>> for reading: $!";
  661. my $header = SIGNATURE;
  662. # Open the output file for writing
  663. open my $out_fh, '>:raw', $output
  664. or die "Can't open file <<$output>> for write: $!";
  665. # Print the header
  666. print $out_fh $header;
  667. # Compress data
  668. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  669. compression($chunk, $out_fh);
  670. }
  671. # Close the output file
  672. close $out_fh;
  673. }
  674. # Decompress file
  675. sub decompress_file ($input, $output) {
  676. # Open and validate the input file
  677. open my $fh, '<:raw', $input
  678. or die "Can't open file <<$input>> for reading: $!";
  679. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  680. # Open the output file
  681. open my $out_fh, '>:raw', $output
  682. or die "Can't open file <<$output>> for writing: $!";
  683. while (!eof($fh)) {
  684. decompression($fh, $out_fh);
  685. }
  686. # Close the output file
  687. close $out_fh;
  688. }
  689. main();
  690. exit(0);