tac-compressor.pl 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 01 May 2015
  5. # Website: http://github.com/trizen
  6. #
  7. ## The arithmetic coding algorithm.
  8. #
  9. # See: http://en.wikipedia.org/wiki/Arithmetic_coding#Arithmetic_coding_as_a_generalized_change_of_radix
  10. use 5.010;
  11. use strict;
  12. use autodie;
  13. use warnings;
  14. use Getopt::Std qw(getopts);
  15. use File::Basename qw(basename);
  16. use lib qw(../lib);
  17. use Math::AnyNum qw(ipow idiv ilog2);
  18. use constant {
  19. PKGNAME => 'TAC Compressor',
  20. VERSION => '0.02',
  21. FORMAT => 'tac',
  22. };
  23. use constant {SIGNATURE => uc(FORMAT) . chr(1)};
  24. sub usage {
  25. my ($code) = @_;
  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 // 0);
  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 {
  79. my ($fh) = @_;
  80. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  81. $sig eq SIGNATURE || return;
  82. }
  83. return 1;
  84. }
  85. sub cumulative_freq {
  86. my ($freq) = @_;
  87. my %cf;
  88. my $total = Math::AnyNum->new(0);
  89. foreach my $c (sort keys %{$freq}) {
  90. $cf{$c} = $total;
  91. $total += $freq->{$c};
  92. }
  93. return %cf;
  94. }
  95. sub compress {
  96. my ($input, $output) = @_;
  97. use bytes;
  98. # Open the input file
  99. open my $fh, '<:raw', $input;
  100. # Open the output file and write the archive signature
  101. open my $out_fh, '>:raw', $output;
  102. print {$out_fh} SIGNATURE;
  103. my $str = do {
  104. local $/;
  105. scalar(<$fh>);
  106. };
  107. close $fh;
  108. my @chars = split(//, $str);
  109. # The frequency characters
  110. my %freq;
  111. $freq{$_}++ for @chars;
  112. # Create the cumulative frequency table
  113. my %cf = cumulative_freq(\%freq);
  114. # Limit and base
  115. my $base = scalar @chars;
  116. # Lower bound
  117. my $L = Math::AnyNum->new(0);
  118. # Product of all frequencies
  119. my $pf = Math::AnyNum->new(1);
  120. # Each term is multiplied by the product of the
  121. # frequencies of all previously occurring symbols
  122. foreach my $c (@chars) {
  123. $L *= $base;
  124. $L += $cf{$c} * $pf;
  125. $pf *= $freq{$c};
  126. }
  127. # Upper bound
  128. my $U = $L + $pf;
  129. my $pow = ilog2($pf);
  130. my $enc = ($U - 1) >> $pow;
  131. # Remove any divisibility by 2
  132. while ($enc > 0 and $enc % 2 == 0) {
  133. ++$pow;
  134. $enc >>= 1;
  135. }
  136. my $bin = $enc->as_bin;
  137. my $encoded = pack('L', $pow); # the power value
  138. $encoded .= chr(scalar(keys %freq) - 1); # number of unique chars
  139. $encoded .= chr(length($bin) % 8); # padding
  140. while (my ($k, $v) = each %freq) {
  141. $encoded .= $k . pack('S', $v); # char => freq
  142. }
  143. print {$out_fh} $encoded, pack('B*', $bin);
  144. close $out_fh;
  145. }
  146. sub decompress {
  147. my ($input, $output) = @_;
  148. use bytes;
  149. # Open and validate the input file
  150. open my $fh, '<:raw', $input;
  151. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E archive!\n";
  152. my $content = do { local $/; <$fh> };
  153. close $fh;
  154. my ($pow, $uniq, $padd) = unpack('LCC', $content);
  155. substr($content, 0, length(pack('LCC', 0, 0, 0)), '');
  156. # Create the frequency table (char => freq)
  157. my %freq;
  158. foreach my $i (0 .. $uniq) {
  159. my ($char, $f) = unpack('aS', $content);
  160. $freq{$char} = $f;
  161. substr($content, 0, length(pack('aS', 0, 0)), '');
  162. }
  163. # Decode the bits into an integer
  164. my $enc = Math::AnyNum->new(unpack('B*', $content), 2);
  165. # Remove the trailing bits (if any)
  166. if ($padd != 0) {
  167. $enc >>= (8 - $padd);
  168. }
  169. $enc <<= $pow;
  170. my $base = 0;
  171. $base += $_ for values %freq;
  172. # Create the cumulative frequency table
  173. my %cf = cumulative_freq(\%freq);
  174. # Create the dictionary
  175. my %dict;
  176. while (my ($k, $v) = each %cf) {
  177. $dict{$v} = $k;
  178. }
  179. # Fill the gaps in the dictionary
  180. my $lchar;
  181. foreach my $i (0 .. $base - 1) {
  182. if (exists $dict{$i}) {
  183. $lchar = $dict{$i};
  184. }
  185. elsif (defined $lchar) {
  186. $dict{$i} = $lchar;
  187. }
  188. }
  189. # Open the output file
  190. open my $out_fh, '>:raw', $output;
  191. # Decode the input number
  192. for (my ($i, $pow) = (0, ipow($base, $base - 1)) ; $i < $base ; ++$i, $pow = idiv($pow, $base)) {
  193. my $div = idiv($enc, $pow);
  194. my $c = $dict{$div};
  195. my $fv = $freq{$c};
  196. my $cv = $cf{$c};
  197. $enc -= $pow * $cv;
  198. $enc = idiv($enc, $fv);
  199. print {$out_fh} $c;
  200. }
  201. close $out_fh;
  202. }
  203. main();
  204. exit(0);