tacc_file_compression.pl 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 11 February 2016
  4. # Edit: 14 July 2023
  5. # https://github.com/trizen
  6. # Arithmetic coding compressor for small files.
  7. # See also:
  8. # https://en.wikipedia.org/wiki/Arithmetic_coding#Arithmetic_coding_as_a_generalized_change_of_radix
  9. use 5.020;
  10. use strict;
  11. use autodie;
  12. use warnings;
  13. use Getopt::Std qw(getopts);
  14. use File::Basename qw(basename);
  15. use List::Util qw(sum max);
  16. use experimental qw(signatures);
  17. use Math::GMPz;
  18. use constant {
  19. PKGNAME => 'TAC Compressor',
  20. VERSION => '0.05',
  21. FORMAT => 'tacc',
  22. };
  23. # Container signature
  24. use constant SIGNATURE => uc(FORMAT) . chr(5);
  25. sub usage ($code = 0) {
  26. print <<"EOH";
  27. usage: $0 [options] [input file] [output file]
  28. options:
  29. -e : extract
  30. -i <filename> : input filename
  31. -o <filename> : output filename
  32. -r : rewrite output
  33. -v : version number
  34. -h : this message
  35. examples:
  36. $0 document.txt
  37. $0 document.txt archive.${\FORMAT}
  38. $0 archive.${\FORMAT} document.txt
  39. $0 -e -i archive.${\FORMAT} -o document.txt
  40. EOH
  41. exit($code);
  42. }
  43. sub version {
  44. printf("%s %s\n", PKGNAME, VERSION);
  45. exit;
  46. }
  47. sub main {
  48. my %opt;
  49. getopts('ei:o:vhr', \%opt);
  50. $opt{h} && usage(0);
  51. $opt{v} && version();
  52. my ($input, $output) = @ARGV;
  53. $input //= $opt{i} // usage(2);
  54. $output //= $opt{o};
  55. my $ext = qr{\.${\FORMAT}\z}io;
  56. if ($opt{e} || $input =~ $ext) {
  57. if (not defined $output) {
  58. ($output = basename($input)) =~ s{$ext}{}
  59. || die "$0: no output file specified!\n";
  60. }
  61. if (not $opt{r} and -e $output) {
  62. print "'$output' already exists! -- Replace? [y/N] ";
  63. <STDIN> =~ /^y/i || exit 17;
  64. }
  65. decompress($input, $output)
  66. || die "$0: error: decompression failed!\n";
  67. }
  68. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  69. $output //= basename($input) . '.' . FORMAT;
  70. compress($input, $output)
  71. || die "$0: error: compression failed!\n";
  72. }
  73. else {
  74. warn "$0: don't know what to do...\n";
  75. usage(1);
  76. }
  77. }
  78. sub valid_archive ($fh) {
  79. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  80. $sig eq SIGNATURE || return;
  81. }
  82. return 1;
  83. }
  84. sub read_bit ($fh, $bitstring) {
  85. if (($$bitstring // '') eq '') {
  86. $$bitstring = unpack('b*', getc($fh) // return undef);
  87. }
  88. chop($$bitstring);
  89. }
  90. sub read_bits ($fh, $bits_len) {
  91. my $data = '';
  92. read($fh, $data, $bits_len >> 3);
  93. $data = unpack('B*', $data);
  94. while (length($data) < $bits_len) {
  95. $data .= unpack('B*', getc($fh) // return undef);
  96. }
  97. if (length($data) > $bits_len) {
  98. $data = substr($data, 0, $bits_len);
  99. }
  100. return $data;
  101. }
  102. sub delta_encode ($integers) {
  103. my @deltas;
  104. my $prev = 0;
  105. unshift(@$integers, scalar(@$integers));
  106. while (@$integers) {
  107. my $curr = shift(@$integers);
  108. push @deltas, $curr - $prev;
  109. $prev = $curr;
  110. }
  111. my $bitstring = '';
  112. foreach my $d (@deltas) {
  113. if ($d == 0) {
  114. $bitstring .= '0';
  115. }
  116. else {
  117. my $t = sprintf('%b', abs($d));
  118. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($t) - 1)) . '0' . substr($t, 1);
  119. }
  120. }
  121. pack('B*', $bitstring);
  122. }
  123. sub delta_decode ($fh) {
  124. my @deltas;
  125. my $buffer = '';
  126. my $len = 0;
  127. for (my $k = 0 ; $k <= $len ; ++$k) {
  128. my $bit = read_bit($fh, \$buffer);
  129. if ($bit eq '0') {
  130. push @deltas, 0;
  131. }
  132. else {
  133. my $bit = read_bit($fh, \$buffer);
  134. my $n = 0;
  135. ++$n while (read_bit($fh, \$buffer) eq '1');
  136. my $d = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $n));
  137. push @deltas, ($bit eq '1' ? $d : -$d);
  138. }
  139. if ($k == 0) {
  140. $len = pop(@deltas);
  141. }
  142. }
  143. my @acc;
  144. my $prev = $len;
  145. foreach my $d (@deltas) {
  146. $prev += $d;
  147. push @acc, $prev;
  148. }
  149. return \@acc;
  150. }
  151. sub cumulative_freq ($freq) {
  152. my %cf;
  153. my $total = Math::GMPz->new(0);
  154. foreach my $c (sort keys %{$freq}) {
  155. $cf{$c} = $total;
  156. $total += $freq->{$c};
  157. }
  158. return %cf;
  159. }
  160. sub compress ($input, $output) {
  161. # Open the input file
  162. open my $fh, '<:raw', $input;
  163. # Open the output file and write the archive signature
  164. open my $out_fh, '>:raw', $output;
  165. print {$out_fh} SIGNATURE;
  166. my $str = do {
  167. local $/;
  168. scalar(<$fh>);
  169. };
  170. close $fh;
  171. my @chars = split(//, $str);
  172. # The frequency characters
  173. my %freq;
  174. $freq{$_}++ for @chars;
  175. # Create the cumulative frequency table
  176. my %cf = cumulative_freq(\%freq);
  177. # Limit and base
  178. my $base = Math::GMPz->new(scalar @chars);
  179. # Lower bound
  180. my $L = Math::GMPz->new(0);
  181. # Product of all frequencies
  182. my $pf = Math::GMPz->new(1);
  183. # Each term is multiplied by the product of the
  184. # frequencies of all previously occurring symbols
  185. foreach my $c (@chars) {
  186. Math::GMPz::Rmpz_mul($L, $L, $base);
  187. Math::GMPz::Rmpz_addmul($L, $pf, $cf{$c});
  188. Math::GMPz::Rmpz_mul_ui($pf, $pf, $freq{$c});
  189. }
  190. # Upper bound
  191. my $U = $L + $pf;
  192. # Compute the power for left shift
  193. my $pow = Math::GMPz::Rmpz_sizeinbase($pf, 2) - 1;
  194. # Set $enc to (U-1) divided by 2^pow
  195. my $enc = ($U - 1) >> $pow;
  196. # Remove any divisibility by 2
  197. if ($enc > 0 and Math::GMPz::Rmpz_even_p($enc)) {
  198. $pow += Math::GMPz::Rmpz_remove($enc, $enc, Math::GMPz->new(2));
  199. }
  200. my $bin = Math::GMPz::Rmpz_get_str($enc, 2);
  201. my $max_symbol = max(map { ord($_) } keys %freq) // 0;
  202. my @freqs;
  203. foreach my $k (0 .. $max_symbol) {
  204. push @freqs, $freq{chr($k)} // 0;
  205. }
  206. push @freqs, $pow;
  207. print {$out_fh} delta_encode(\@freqs);
  208. print {$out_fh} pack('N', length($bin));
  209. print {$out_fh} pack('B*', $bin);
  210. close $out_fh;
  211. }
  212. sub decompress ($input, $output) {
  213. # Open and validate the input file
  214. open my $fh, '<:raw', $input;
  215. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E archive!\n";
  216. my @freqs = @{delta_decode($fh)};
  217. my $pow2 = pop(@freqs);
  218. my $bits_len = unpack('N', join('', map { getc($fh) // die "error" } 1 .. 4));
  219. # Create the frequency table
  220. my %freq;
  221. foreach my $i (0 .. $#freqs) {
  222. if ($freqs[$i] > 0) {
  223. $freq{chr($i)} = $freqs[$i];
  224. }
  225. }
  226. # Decode the bits into an integer
  227. my $enc = Math::GMPz->new(read_bits($fh, $bits_len), 2);
  228. $enc <<= $pow2;
  229. my $base = sum(values %freq) // 0;
  230. # Create the cumulative frequency table
  231. my %cf = cumulative_freq(\%freq);
  232. # Create the dictionary
  233. my %dict;
  234. while (my ($k, $v) = each %cf) {
  235. $dict{$v} = $k;
  236. }
  237. # Fill the gaps in the dictionary
  238. my $lchar;
  239. foreach my $i (0 .. $base - 1) {
  240. if (exists $dict{$i}) {
  241. $lchar = $dict{$i};
  242. }
  243. elsif (defined $lchar) {
  244. $dict{$i} = $lchar;
  245. }
  246. }
  247. # Open the output file
  248. open my $out_fh, '>:raw', $output;
  249. if ($base == 0) {
  250. close $out_fh;
  251. return;
  252. }
  253. elsif ($base == 1) {
  254. print {$out_fh} keys %freq;
  255. close $out_fh;
  256. return;
  257. }
  258. my $div = Math::GMPz::Rmpz_init();
  259. # Decode the input number
  260. for (my $pow = Math::GMPz->new($base)**($base - 1) ; Math::GMPz::Rmpz_sgn($pow) > 0 ; Math::GMPz::Rmpz_tdiv_q_ui($pow, $pow, $base)) {
  261. Math::GMPz::Rmpz_tdiv_q($div, $enc, $pow);
  262. my $c = $dict{$div};
  263. my $fv = $freq{$c};
  264. my $cv = $cf{$c};
  265. Math::GMPz::Rmpz_submul($enc, $pow, $cv);
  266. Math::GMPz::Rmpz_tdiv_q_ui($enc, $enc, $fv);
  267. print {$out_fh} $c;
  268. }
  269. close $out_fh;
  270. }
  271. main();
  272. exit(0);