rans_file_compression.pl 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #!/usr/bin/perl
  2. # File compression with rANS encoding, using big integers.
  3. # Reference:
  4. # ‎Stanford EE274: Data Compression I 2023 I Lecture 7 - ANS
  5. # https://youtube.com/watch?v=5Hp4bnvSjng
  6. use 5.036;
  7. use Getopt::Std qw(getopts);
  8. use File::Basename qw(basename);
  9. use List::Util qw(max);
  10. use Math::GMPz;
  11. use constant {
  12. PKGNAME => 'rANS',
  13. VERSION => '0.01',
  14. FORMAT => 'rans',
  15. };
  16. # Container signature
  17. use constant SIGNATURE => uc(FORMAT) . chr(1);
  18. sub usage ($code = 0) {
  19. print <<"EOH";
  20. usage: $0 [options] [input file] [output file]
  21. options:
  22. -e : extract
  23. -i <filename> : input filename
  24. -o <filename> : output filename
  25. -r : rewrite output
  26. -v : version number
  27. -h : this message
  28. examples:
  29. $0 document.txt
  30. $0 document.txt archive.${\FORMAT}
  31. $0 archive.${\FORMAT} document.txt
  32. $0 -e -i archive.${\FORMAT} -o document.txt
  33. EOH
  34. exit($code);
  35. }
  36. sub version {
  37. printf("%s %s\n", PKGNAME, VERSION);
  38. exit;
  39. }
  40. sub main {
  41. my %opt;
  42. getopts('ei:o:vhr', \%opt);
  43. $opt{h} && usage(0);
  44. $opt{v} && version();
  45. my ($input, $output) = @ARGV;
  46. $input //= $opt{i} // usage(2);
  47. $output //= $opt{o};
  48. my $ext = qr{\.${\FORMAT}\z}io;
  49. if ($opt{e} || $input =~ $ext) {
  50. if (not defined $output) {
  51. ($output = basename($input)) =~ s{$ext}{}
  52. || die "$0: no output file specified!\n";
  53. }
  54. if (not $opt{r} and -e $output) {
  55. print "'$output' already exists! -- Replace? [y/N] ";
  56. <STDIN> =~ /^y/i || exit 17;
  57. }
  58. decompress($input, $output)
  59. || die "$0: error: decompression failed!\n";
  60. }
  61. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  62. $output //= basename($input) . '.' . FORMAT;
  63. compress($input, $output)
  64. || die "$0: error: compression failed!\n";
  65. }
  66. else {
  67. warn "$0: don't know what to do...\n";
  68. usage(1);
  69. }
  70. }
  71. sub valid_archive ($fh) {
  72. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  73. $sig eq SIGNATURE || return;
  74. }
  75. return 1;
  76. }
  77. sub read_bit ($fh, $bitstring) {
  78. if (($$bitstring // '') eq '') {
  79. $$bitstring = unpack('b*', getc($fh) // return undef);
  80. }
  81. chop($$bitstring);
  82. }
  83. sub read_bits ($fh, $bits_len) {
  84. my $data = '';
  85. read($fh, $data, $bits_len >> 3);
  86. $data = unpack('B*', $data);
  87. while (length($data) < $bits_len) {
  88. $data .= unpack('B*', getc($fh) // return undef);
  89. }
  90. if (length($data) > $bits_len) {
  91. $data = substr($data, 0, $bits_len);
  92. }
  93. return $data;
  94. }
  95. sub delta_encode ($integers) {
  96. my @deltas;
  97. my $prev = 0;
  98. unshift(@$integers, scalar(@$integers));
  99. while (@$integers) {
  100. my $curr = shift(@$integers);
  101. push @deltas, $curr - $prev;
  102. $prev = $curr;
  103. }
  104. my $bitstring = '';
  105. foreach my $d (@deltas) {
  106. if ($d == 0) {
  107. $bitstring .= '0';
  108. }
  109. else {
  110. my $t = sprintf('%b', abs($d));
  111. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($t) - 1)) . '0' . substr($t, 1);
  112. }
  113. }
  114. pack('B*', $bitstring);
  115. }
  116. sub delta_decode ($fh) {
  117. my @deltas;
  118. my $buffer = '';
  119. my $len = 0;
  120. for (my $k = 0 ; $k <= $len ; ++$k) {
  121. my $bit = read_bit($fh, \$buffer);
  122. if ($bit eq '0') {
  123. push @deltas, 0;
  124. }
  125. else {
  126. my $bit = read_bit($fh, \$buffer);
  127. my $n = 0;
  128. ++$n while (read_bit($fh, \$buffer) eq '1');
  129. my $d = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $n));
  130. push @deltas, ($bit eq '1' ? $d : -$d);
  131. }
  132. if ($k == 0) {
  133. $len = pop(@deltas);
  134. }
  135. }
  136. my @acc;
  137. my $prev = $len;
  138. foreach my $d (@deltas) {
  139. $prev += $d;
  140. push @acc, $prev;
  141. }
  142. return \@acc;
  143. }
  144. sub cumulative_freq ($freq) {
  145. my %cf;
  146. my $total = Math::GMPz->new(0);
  147. foreach my $c (sort keys %{$freq}) {
  148. $cf{$c} = $total;
  149. $total += $freq->{$c};
  150. }
  151. return %cf;
  152. }
  153. sub rans_base_enc($freq, $cumul, $M, $x_prev, $s, $block_id, $x) {
  154. Math::GMPz::Rmpz_div_ui($block_id, $x_prev, $freq->{$s});
  155. my $r = Math::GMPz::Rmpz_mod_ui($x, $x_prev, $freq->{$s});
  156. my $slot = $cumul->{$s} + $r;
  157. Math::GMPz::Rmpz_mul_ui($x, $block_id, $M);
  158. Math::GMPz::Rmpz_add_ui($x, $x, $slot);
  159. return $x;
  160. }
  161. sub encode($input, $freq, $cumul, $M) {
  162. my $x = Math::GMPz::Rmpz_init_set_ui(0);
  163. my $block_id = Math::GMPz::Rmpz_init();
  164. my $next_x = Math::GMPz::Rmpz_init();
  165. foreach my $s (@$input) {
  166. $x = rans_base_enc($freq, $cumul, $M, $x, $s, $block_id, $next_x);
  167. }
  168. return $x;
  169. }
  170. sub rans_base_dec($alphabet, $freq, $cumul, $M, $x, $block_id, $slot, $x_prev) {
  171. Math::GMPz::Rmpz_tdiv_qr_ui($block_id, $slot, $x, $M);
  172. my ($left, $right, $mid, $cmp) = (0, $#{$alphabet});
  173. while (1) {
  174. $mid = ($left + $right) >> 1;
  175. $cmp = ($cumul->{$alphabet->[$mid]} <=> $slot) || last;
  176. if ($cmp < 0) {
  177. $left = $mid + 1;
  178. $left > $right and last;
  179. }
  180. else {
  181. $right = $mid - 1;
  182. if ($left > $right) {
  183. $mid -= 1;
  184. last;
  185. }
  186. }
  187. }
  188. my $s = $alphabet->[$mid];
  189. Math::GMPz::Rmpz_mul_ui($x_prev, $block_id, $freq->{$s});
  190. Math::GMPz::Rmpz_add($x_prev, $x_prev, $slot);
  191. Math::GMPz::Rmpz_sub_ui($x_prev, $x_prev, $cumul->{$s});
  192. return ($s, $x_prev);
  193. }
  194. sub decode($x, $alphabet, $freq, $cumul, $M) {
  195. my @dec;
  196. my $s = undef;
  197. my $block_id = Math::GMPz::Rmpz_init();
  198. my $slot = Math::GMPz::Rmpz_init();
  199. my $x_prev = Math::GMPz::Rmpz_init();
  200. for (1 .. $M) {
  201. ($s, $x) = rans_base_dec($alphabet, $freq, $cumul, $M, $x, $block_id, $slot, $x_prev);
  202. push @dec, $s;
  203. }
  204. return [reverse @dec];
  205. }
  206. sub compress ($input, $output) {
  207. # Open the input file
  208. open my $fh, '<:raw', $input;
  209. # Open the output file and write the archive signature
  210. open my $out_fh, '>:raw', $output;
  211. print {$out_fh} SIGNATURE;
  212. my $str = do {
  213. local $/;
  214. scalar(<$fh>);
  215. };
  216. close $fh;
  217. my (%freq, %cumul);
  218. my @symbols = unpack('C*', $str);
  219. ++$freq{$_} for @symbols;
  220. my @alphabet = sort { $a <=> $b } keys %freq;
  221. my $t = 0;
  222. foreach my $s (@alphabet) {
  223. $cumul{$s} = $t;
  224. $t += $freq{$s};
  225. }
  226. my $M = $t;
  227. my $enc = encode(\@symbols, \%freq, \%cumul, $M);
  228. my $bin = Math::GMPz::Rmpz_get_str($enc, 2);
  229. my $max_symbol = max(keys %freq) // 0;
  230. my @freqs;
  231. foreach my $k (0 .. $max_symbol) {
  232. push @freqs, $freq{$k} // 0;
  233. }
  234. print {$out_fh} delta_encode(\@freqs);
  235. print {$out_fh} pack('N', length($bin));
  236. print {$out_fh} pack('B*', $bin);
  237. close $out_fh;
  238. }
  239. sub decompress ($input, $output) {
  240. # Open and validate the input file
  241. open my $fh, '<:raw', $input;
  242. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E archive!\n";
  243. my @freqs = @{delta_decode($fh)};
  244. my $bits_len = unpack('N', join('', map { getc($fh) // die "error" } 1 .. 4));
  245. # Create the frequency table
  246. my %freq;
  247. foreach my $i (0 .. $#freqs) {
  248. if ($freqs[$i] > 0) {
  249. $freq{$i} = $freqs[$i];
  250. }
  251. }
  252. # Decode the bits into an integer
  253. my $enc = Math::GMPz->new(read_bits($fh, $bits_len), 2);
  254. # Open the output file
  255. open my $out_fh, '>:raw', $output;
  256. my @alphabet = sort { $a <=> $b } keys %freq;
  257. my $t = 0;
  258. my %cumul;
  259. foreach my $s (@alphabet) {
  260. $cumul{$s} = $t;
  261. $t += $freq{$s};
  262. }
  263. my $M = $t;
  264. my $symbols = decode($enc, \@alphabet, \%freq, \%cumul, $M);
  265. print $out_fh pack('C*', @$symbols);
  266. close $out_fh;
  267. }
  268. main();
  269. exit(0);