tac_file_compression.pl 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 01 May 2015
  5. # Website: https://github.com/trizen
  6. #
  7. ## The arithmetic coding algorithm.
  8. #
  9. # See: https://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 Math::BigInt (try => 'GMP');
  17. use constant {
  18. PKGNAME => 'TAC Compressor',
  19. VERSION => '0.02',
  20. FORMAT => 'tac',
  21. };
  22. # Container signature
  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::BigInt->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 = Math::BigInt->new(scalar @chars);
  116. # Lower bound
  117. my $L = Math::BigInt->new(0);
  118. # Product of all frequencies
  119. my $pf = Math::BigInt->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->bmuladd($base, $cf{$c} * $pf);
  124. $pf->bmul($freq{$c});
  125. }
  126. # Upper bound
  127. my $U = $L + $pf;
  128. my $pow = $pf->copy->blog(2);
  129. my $enc = ($U - 1)->bdiv(Math::BigInt->new(2)->bpow($pow));
  130. # Remove any divisibility by 2
  131. while ($enc > 0 and $enc % 2 == 0) {
  132. $pow->binc;
  133. $enc->brsft(1);
  134. }
  135. my $bin = substr($enc->as_bin, 2);
  136. my $encoded = pack('L', $pow); # the power value
  137. $encoded .= chr(scalar(keys %freq) - 1); # number of unique chars
  138. $encoded .= chr(length($bin) % 8); # padding
  139. while (my ($k, $v) = each %freq) {
  140. $encoded .= $k . pack('S', $v); # char => freq
  141. }
  142. print {$out_fh} $encoded, pack('B*', $bin);
  143. close $out_fh;
  144. }
  145. sub decompress {
  146. my ($input, $output) = @_;
  147. use bytes;
  148. # Open and validate the input file
  149. open my $fh, '<:raw', $input;
  150. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E archive!\n";
  151. my $content = do { local $/; <$fh> };
  152. close $fh;
  153. my ($pow, $uniq, $padd) = unpack('LCC', $content);
  154. substr($content, 0, length(pack('LCC', 0, 0, 0)), '');
  155. # Create the frequency table (char => freq)
  156. my %freq;
  157. foreach my $i (0 .. $uniq) {
  158. my ($char, $f) = unpack('aS', $content);
  159. $freq{$char} = $f;
  160. substr($content, 0, length(pack('aS', 0, 0)), '');
  161. }
  162. # Decode the bits into an integer
  163. my $enc = Math::BigInt->new('0b' . unpack('B*', $content));
  164. # Remove the trailing bits (if any)
  165. if ($padd != 0) {
  166. $enc >>= (8 - $padd);
  167. }
  168. $pow = Math::BigInt->new($pow);
  169. $enc->blsft($pow);
  170. my $base = Math::BigInt->new(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 $pow = $base**($base - 1) ; $pow > 0 ; $pow /= $base) {
  193. my $div = $enc / $pow;
  194. my $c = $dict{$div};
  195. my $fv = $freq{$c};
  196. my $cv = $cf{$c};
  197. $enc = ($enc - $pow * $cv) / $fv;
  198. print {$out_fh} $c;
  199. }
  200. close $out_fh;
  201. }
  202. main();
  203. exit(0);