mra_file_compression.pl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 14 June 2023
  4. # Edit: 29 February 2024
  5. # https://github.com/trizen
  6. # Compress/decompress files using Move-to-Front Transform + Run-length encoding + Arithmetic Coding.
  7. use 5.036;
  8. use Getopt::Std qw(getopts);
  9. use File::Basename qw(basename);
  10. use List::Util qw(max uniq);
  11. use constant {
  12. PKGNAME => 'MRA',
  13. VERSION => '0.01',
  14. FORMAT => 'mra',
  15. CHUNK_SIZE => 1 << 17,
  16. };
  17. # Arithmetic Coding settings
  18. use constant BITS => 32;
  19. use constant MAX => oct('0b' . ('1' x BITS));
  20. # Container signature
  21. use constant SIGNATURE => uc(FORMAT) . chr(3);
  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 mtf_encode ($bytes, $alphabet = [0 .. 255]) {
  84. my @C;
  85. my @table;
  86. @table[@$alphabet] = (0 .. $#{$alphabet});
  87. foreach my $c (@$bytes) {
  88. push @C, (my $index = $table[$c]);
  89. unshift(@$alphabet, splice(@$alphabet, $index, 1));
  90. @table[@{$alphabet}[0 .. $index]] = (0 .. $index);
  91. }
  92. return \@C;
  93. }
  94. sub mtf_decode ($encoded, $alphabet = [0 .. 255]) {
  95. my @S;
  96. foreach my $p (@$encoded) {
  97. push @S, $alphabet->[$p];
  98. unshift(@$alphabet, splice(@$alphabet, $p, 1));
  99. }
  100. return \@S;
  101. }
  102. sub read_bit ($fh, $bitstring) {
  103. if (($$bitstring // '') eq '') {
  104. $$bitstring = unpack('b*', getc($fh) // return undef);
  105. }
  106. chop($$bitstring);
  107. }
  108. sub read_bits ($fh, $bits_len) {
  109. my $data = '';
  110. read($fh, $data, $bits_len >> 3);
  111. $data = unpack('B*', $data);
  112. while (length($data) < $bits_len) {
  113. $data .= unpack('B*', getc($fh) // return undef);
  114. }
  115. if (length($data) > $bits_len) {
  116. $data = substr($data, 0, $bits_len);
  117. }
  118. return $data;
  119. }
  120. sub delta_encode ($integers, $double = 0) {
  121. my @deltas;
  122. my $prev = 0;
  123. unshift(@$integers, scalar(@$integers));
  124. while (@$integers) {
  125. my $curr = shift(@$integers);
  126. push @deltas, $curr - $prev;
  127. $prev = $curr;
  128. }
  129. my $bitstring = '';
  130. foreach my $d (@deltas) {
  131. if ($d == 0) {
  132. $bitstring .= '0';
  133. }
  134. elsif ($double) {
  135. my $t = sprintf('%b', abs($d) + 1);
  136. my $l = sprintf('%b', length($t));
  137. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($l) - 1)) . '0' . substr($l, 1) . substr($t, 1);
  138. }
  139. else {
  140. my $t = sprintf('%b', abs($d));
  141. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($t) - 1)) . '0' . substr($t, 1);
  142. }
  143. }
  144. pack('B*', $bitstring);
  145. }
  146. sub delta_decode ($fh, $double = 0) {
  147. my @deltas;
  148. my $buffer = '';
  149. my $len = 0;
  150. for (my $k = 0 ; $k <= $len ; ++$k) {
  151. my $bit = read_bit($fh, \$buffer);
  152. if ($bit eq '0') {
  153. push @deltas, 0;
  154. }
  155. elsif ($double) {
  156. my $bit = read_bit($fh, \$buffer);
  157. my $bl = 0;
  158. ++$bl while (read_bit($fh, \$buffer) eq '1');
  159. my $bl2 = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $bl));
  160. my $int = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. ($bl2 - 1)));
  161. push @deltas, ($bit eq '1' ? 1 : -1) * ($int - 1);
  162. }
  163. else {
  164. my $bit = read_bit($fh, \$buffer);
  165. my $n = 0;
  166. ++$n while (read_bit($fh, \$buffer) eq '1');
  167. my $d = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $n));
  168. push @deltas, ($bit eq '1' ? $d : -$d);
  169. }
  170. if ($k == 0) {
  171. $len = pop(@deltas);
  172. }
  173. }
  174. my @acc;
  175. my $prev = $len;
  176. foreach my $d (@deltas) {
  177. $prev += $d;
  178. push @acc, $prev;
  179. }
  180. return \@acc;
  181. }
  182. sub create_cfreq ($freq) {
  183. my @cf;
  184. my $T = 0;
  185. foreach my $i (sort { $a <=> $b } keys %$freq) {
  186. $freq->{$i} // next;
  187. $cf[$i] = $T;
  188. $T += $freq->{$i};
  189. $cf[$i + 1] = $T;
  190. }
  191. return (\@cf, $T);
  192. }
  193. sub ac_encode ($bytes_arr) {
  194. my $enc = '';
  195. my $EOF_SYMBOL = (max(@$bytes_arr) // 0) + 1;
  196. my @bytes = (@$bytes_arr, $EOF_SYMBOL);
  197. my %freq;
  198. ++$freq{$_} for @bytes;
  199. my ($cf, $T) = create_cfreq(\%freq);
  200. if ($T > MAX) {
  201. die "Too few bits: $T > ${\MAX}";
  202. }
  203. my $low = 0;
  204. my $high = MAX;
  205. my $uf_count = 0;
  206. foreach my $c (@bytes) {
  207. my $w = $high - $low + 1;
  208. $high = ($low + int(($w * $cf->[$c + 1]) / $T) - 1) & MAX;
  209. $low = ($low + int(($w * $cf->[$c]) / $T)) & MAX;
  210. if ($high > MAX) {
  211. die "high > MAX: $high > ${\MAX}";
  212. }
  213. if ($low >= $high) { die "$low >= $high" }
  214. while (1) {
  215. if (($high >> (BITS - 1)) == ($low >> (BITS - 1))) {
  216. my $bit = $high >> (BITS - 1);
  217. $enc .= $bit;
  218. if ($uf_count > 0) {
  219. $enc .= join('', 1 - $bit) x $uf_count;
  220. $uf_count = 0;
  221. }
  222. $low <<= 1;
  223. ($high <<= 1) |= 1;
  224. }
  225. elsif (((($low >> (BITS - 2)) & 0x1) == 1) && ((($high >> (BITS - 2)) & 0x1) == 0)) {
  226. ($high <<= 1) |= (1 << (BITS - 1));
  227. $high |= 1;
  228. ($low <<= 1) &= ((1 << (BITS - 1)) - 1);
  229. ++$uf_count;
  230. }
  231. else {
  232. last;
  233. }
  234. $low &= MAX;
  235. $high &= MAX;
  236. }
  237. }
  238. $enc .= '0';
  239. $enc .= '1';
  240. while (length($enc) % 8 != 0) {
  241. $enc .= '1';
  242. }
  243. return ($enc, \%freq);
  244. }
  245. sub ac_decode ($fh, $freq) {
  246. my ($cf, $T) = create_cfreq($freq);
  247. my @dec;
  248. my $low = 0;
  249. my $high = MAX;
  250. my $enc = oct('0b' . join '', map { getc($fh) // 1 } 1 .. BITS);
  251. my @table;
  252. foreach my $i (sort { $a <=> $b } keys %$freq) {
  253. foreach my $j ($cf->[$i] .. $cf->[$i + 1] - 1) {
  254. $table[$j] = $i;
  255. }
  256. }
  257. my $EOF_SYMBOL = max(keys %$freq) // 0;
  258. while (1) {
  259. my $w = $high - $low + 1;
  260. my $ss = int((($T * ($enc - $low + 1)) - 1) / $w);
  261. my $i = $table[$ss] // last;
  262. last if ($i == $EOF_SYMBOL);
  263. push @dec, $i;
  264. $high = ($low + int(($w * $cf->[$i + 1]) / $T) - 1) & MAX;
  265. $low = ($low + int(($w * $cf->[$i]) / $T)) & MAX;
  266. if ($high > MAX) {
  267. die "error";
  268. }
  269. if ($low >= $high) { die "$low >= $high" }
  270. while (1) {
  271. if (($high >> (BITS - 1)) == ($low >> (BITS - 1))) {
  272. ($high <<= 1) |= 1;
  273. $low <<= 1;
  274. ($enc <<= 1) |= (getc($fh) // 1);
  275. }
  276. elsif (((($low >> (BITS - 2)) & 0x1) == 1) && ((($high >> (BITS - 2)) & 0x1) == 0)) {
  277. ($high <<= 1) |= (1 << (BITS - 1));
  278. $high |= 1;
  279. ($low <<= 1) &= ((1 << (BITS - 1)) - 1);
  280. $enc = (($enc >> (BITS - 1)) << (BITS - 1)) | (($enc & ((1 << (BITS - 2)) - 1)) << 1) | (getc($fh) // 1);
  281. }
  282. else {
  283. last;
  284. }
  285. $low &= MAX;
  286. $high &= MAX;
  287. $enc &= MAX;
  288. }
  289. }
  290. return \@dec;
  291. }
  292. sub create_ac_entry ($bytes, $out_fh) {
  293. my ($enc, $freq) = ac_encode($bytes);
  294. my $max_symbol = max(keys %$freq) // 0;
  295. my @freqs;
  296. foreach my $k (0 .. $max_symbol) {
  297. push @freqs, $freq->{$k} // 0;
  298. }
  299. push @freqs, length($enc) >> 3;
  300. say "Max symbol: $max_symbol\n";
  301. print $out_fh delta_encode(\@freqs);
  302. print $out_fh pack("B*", $enc);
  303. }
  304. sub decode_ac_entry ($fh) {
  305. my @freqs = @{delta_decode($fh)};
  306. my $bits_len = pop(@freqs);
  307. my %freq;
  308. foreach my $i (0 .. $#freqs) {
  309. if ($freqs[$i]) {
  310. $freq{$i} = $freqs[$i];
  311. }
  312. }
  313. say "Encoded length: $bits_len\n";
  314. my $bits = read_bits($fh, $bits_len << 3);
  315. if ($bits_len > 0) {
  316. open my $bits_fh, '<:raw', \$bits;
  317. return ac_decode($bits_fh, \%freq);
  318. }
  319. return [];
  320. }
  321. sub rle4_encode ($bytes) { # RLE1
  322. my @rle;
  323. my $end = $#{$bytes};
  324. my $prev = -1;
  325. my $run = 0;
  326. for (my $i = 0 ; $i <= $end ; ++$i) {
  327. if ($bytes->[$i] == $prev) {
  328. ++$run;
  329. }
  330. else {
  331. $run = 1;
  332. }
  333. push @rle, $bytes->[$i];
  334. $prev = $bytes->[$i];
  335. if ($run >= 4) {
  336. $run = 0;
  337. $i += 1;
  338. while ($run < 254 and $i <= $end and $bytes->[$i] == $prev) {
  339. ++$run;
  340. ++$i;
  341. }
  342. push @rle, $run;
  343. $run = 1;
  344. if ($i <= $end) {
  345. $prev = $bytes->[$i];
  346. push @rle, $bytes->[$i];
  347. }
  348. }
  349. }
  350. return \@rle;
  351. }
  352. sub rle4_decode ($bytes) { # RLE1
  353. my @dec = $bytes->[0];
  354. my $end = $#{$bytes};
  355. my $prev = $bytes->[0];
  356. my $run = 1;
  357. for (my $i = 1 ; $i <= $end ; ++$i) {
  358. if ($bytes->[$i] == $prev) {
  359. ++$run;
  360. }
  361. else {
  362. $run = 1;
  363. }
  364. push @dec, $bytes->[$i];
  365. $prev = $bytes->[$i];
  366. if ($run >= 4) {
  367. if (++$i <= $end) {
  368. $run = $bytes->[$i];
  369. push @dec, (($prev) x $run);
  370. }
  371. $run = 0;
  372. }
  373. }
  374. return \@dec;
  375. }
  376. sub rle_encode ($bytes) { # RLE2
  377. my @rle;
  378. my $end = $#{$bytes};
  379. for (my $i = 0 ; $i <= $end ; ++$i) {
  380. my $run = 0;
  381. while ($i <= $end and $bytes->[$i] == 0) {
  382. ++$run;
  383. ++$i;
  384. }
  385. if ($run >= 1) {
  386. my $t = sprintf('%b', $run + 1);
  387. push @rle, split(//, substr($t, 1));
  388. }
  389. if ($i <= $end) {
  390. push @rle, $bytes->[$i] + 1;
  391. }
  392. }
  393. return \@rle;
  394. }
  395. sub rle_decode ($rle) { # RLE2
  396. my @dec;
  397. my $end = $#{$rle};
  398. for (my $i = 0 ; $i <= $end ; ++$i) {
  399. my $k = $rle->[$i];
  400. if ($k == 0 or $k == 1) {
  401. my $run = 1;
  402. while (($i <= $end) and ($k == 0 or $k == 1)) {
  403. ($run <<= 1) |= $k;
  404. $k = $rle->[++$i];
  405. }
  406. push @dec, (0) x ($run - 1);
  407. }
  408. if ($i <= $end) {
  409. push @dec, $k - 1;
  410. }
  411. }
  412. return \@dec;
  413. }
  414. sub encode_alphabet ($alphabet) {
  415. my %table;
  416. @table{@$alphabet} = ();
  417. my $populated = 0;
  418. my @marked;
  419. for (my $i = 0 ; $i <= 255 ; $i += 32) {
  420. my $enc = 0;
  421. foreach my $j (0 .. 31) {
  422. if (exists($table{$i + $j})) {
  423. $enc |= 1 << $j;
  424. }
  425. }
  426. if ($enc == 0) {
  427. $populated <<= 1;
  428. }
  429. else {
  430. ($populated <<= 1) |= 1;
  431. push @marked, $enc;
  432. }
  433. }
  434. my $delta = delta_encode([@marked], 1);
  435. say "Populated : ", sprintf('%08b', $populated);
  436. say "Marked : @marked";
  437. say "Delta len : ", length($delta);
  438. my $encoded = '';
  439. $encoded .= chr($populated);
  440. $encoded .= $delta;
  441. return $encoded;
  442. }
  443. sub decode_alphabet ($fh) {
  444. my @populated = split(//, sprintf('%08b', ord(getc($fh))));
  445. my $marked = delta_decode($fh, 1);
  446. my @alphabet;
  447. for (my $i = 0 ; $i <= 255 ; $i += 32) {
  448. if (shift(@populated)) {
  449. my $m = shift(@$marked);
  450. foreach my $j (0 .. 31) {
  451. if ($m & 1) {
  452. push @alphabet, $i + $j;
  453. }
  454. $m >>= 1;
  455. }
  456. }
  457. }
  458. return \@alphabet;
  459. }
  460. sub compression ($chunk, $out_fh) {
  461. my $bytes = [unpack('C*', $chunk)];
  462. my @alphabet = sort { $a <=> $b } uniq(@$bytes);
  463. my $alphabet_enc = encode_alphabet(\@alphabet);
  464. $bytes = mtf_encode($bytes, [@alphabet]);
  465. $bytes = rle_encode($bytes);
  466. $bytes = rle4_encode($bytes);
  467. print $out_fh $alphabet_enc;
  468. create_ac_entry($bytes, $out_fh);
  469. }
  470. sub decompression ($fh, $out_fh) {
  471. my $alphabet = decode_alphabet($fh);
  472. say "Alphabet size: ", scalar(@$alphabet);
  473. my $bytes = decode_ac_entry($fh);
  474. $bytes = rle4_decode($bytes);
  475. $bytes = rle_decode($bytes);
  476. $bytes = mtf_decode($bytes, [@$alphabet]);
  477. print $out_fh pack('C*', @$bytes);
  478. }
  479. # Compress file
  480. sub compress_file ($input, $output) {
  481. open my $fh, '<:raw', $input
  482. or die "Can't open file <<$input>> for reading: $!";
  483. my $header = SIGNATURE;
  484. # Open the output file for writing
  485. open my $out_fh, '>:raw', $output
  486. or die "Can't open file <<$output>> for write: $!";
  487. # Print the header
  488. print $out_fh $header;
  489. # Compress data
  490. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  491. compression($chunk, $out_fh);
  492. }
  493. # Close the file
  494. close $out_fh;
  495. }
  496. # Decompress file
  497. sub decompress_file ($input, $output) {
  498. # Open and validate the input file
  499. open my $fh, '<:raw', $input
  500. or die "Can't open file <<$input>> for reading: $!";
  501. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  502. # Open the output file
  503. open my $out_fh, '>:raw', $output
  504. or die "Can't open file <<$output>> for writing: $!";
  505. while (!eof($fh)) {
  506. decompression($fh, $out_fh);
  507. }
  508. # Close the file
  509. close $fh;
  510. close $out_fh;
  511. }
  512. main();
  513. exit(0);