hfm_file_compression.pl 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 01 December 2022
  4. # Edit: 28 April 2023
  5. # https://github.com/trizen
  6. # Compress/decompress files using Huffman coding.
  7. # Huffman coding algorithm from:
  8. # https://rosettacode.org/wiki/Huffman_coding#Perl
  9. # See also:
  10. # https://en.wikipedia.org/wiki/Huffman_coding
  11. use 5.020;
  12. use strict;
  13. use warnings;
  14. use experimental qw(signatures);
  15. use List::Util qw(min max);
  16. use Getopt::Std qw(getopts);
  17. use File::Basename qw(basename);
  18. use constant {
  19. PKGNAME => 'HFM',
  20. VERSION => '0.03',
  21. FORMAT => 'hfm',
  22. };
  23. use constant {
  24. CHUNK_SIZE => 1 << 15,
  25. SIGNATURE => uc(FORMAT) . chr(3),
  26. };
  27. sub usage {
  28. my ($code) = @_;
  29. print <<"EOH";
  30. usage: $0 [options] [input file] [output file]
  31. options:
  32. -e : extract
  33. -i <filename> : input filename
  34. -o <filename> : output filename
  35. -r : rewrite output
  36. -v : version number
  37. -h : this message
  38. examples:
  39. $0 document.txt
  40. $0 document.txt archive.${\FORMAT}
  41. $0 archive.${\FORMAT} document.txt
  42. $0 -e -i archive.${\FORMAT} -o document.txt
  43. EOH
  44. exit($code // 0);
  45. }
  46. sub version {
  47. printf("%s %s\n", PKGNAME, VERSION);
  48. exit;
  49. }
  50. sub main {
  51. my %opt;
  52. getopts('ei:o:vhr', \%opt);
  53. $opt{h} && usage(0);
  54. $opt{v} && version();
  55. my ($input, $output) = @ARGV;
  56. $input //= $opt{i} // usage(2);
  57. $output //= $opt{o};
  58. my $ext = qr{\.${\FORMAT}\z}io;
  59. if ($opt{e} || $input =~ $ext) {
  60. if (not defined $output) {
  61. ($output = basename($input)) =~ s{$ext}{}
  62. || die "$0: no output file specified!\n";
  63. }
  64. if (not $opt{r} and -e $output) {
  65. print "'$output' already exists! -- Replace? [y/N] ";
  66. <STDIN> =~ /^y/i || exit 17;
  67. }
  68. decompress($input, $output)
  69. || die "$0: error: decompression failed!\n";
  70. }
  71. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  72. $output //= basename($input) . '.' . FORMAT;
  73. compress($input, $output)
  74. || die "$0: error: compression failed!\n";
  75. }
  76. else {
  77. warn "$0: don't know what to do...\n";
  78. usage(1);
  79. }
  80. }
  81. sub read_bit ($fh, $bitstring) {
  82. if (($$bitstring // '') eq '') {
  83. $$bitstring = unpack('b*', getc($fh) // return undef);
  84. }
  85. chop($$bitstring);
  86. }
  87. sub delta_encode ($integers) {
  88. my @deltas;
  89. my $prev = 0;
  90. unshift(@$integers, scalar(@$integers));
  91. while (@$integers) {
  92. my $curr = shift(@$integers);
  93. push @deltas, $curr - $prev;
  94. $prev = $curr;
  95. }
  96. my $bitstring = '';
  97. foreach my $d (@deltas) {
  98. if ($d == 0) {
  99. $bitstring .= '0';
  100. }
  101. else {
  102. my $t = sprintf('%b', abs($d) + 1);
  103. my $l = sprintf('%b', length($t));
  104. $bitstring .= '1' . (($d < 0) ? '0' : '1') . ('1' x (length($l) - 1)) . '0' . substr($l, 1) . substr($t, 1);
  105. }
  106. }
  107. pack('B*', $bitstring);
  108. }
  109. sub delta_decode ($fh) {
  110. my @deltas;
  111. my $buffer = '';
  112. my $len = 0;
  113. for (my $k = 0 ; $k <= $len ; ++$k) {
  114. my $bit = read_bit($fh, \$buffer);
  115. if ($bit eq '0') {
  116. push @deltas, 0;
  117. }
  118. else {
  119. my $bit = read_bit($fh, \$buffer);
  120. my $bl = 0;
  121. ++$bl while (read_bit($fh, \$buffer) eq '1');
  122. my $bl2 = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $bl));
  123. my $int = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. ($bl2 - 1)));
  124. push @deltas, ($bit eq '1' ? 1 : -1) * ($int - 1);
  125. }
  126. if ($k == 0) {
  127. $len = pop(@deltas);
  128. }
  129. }
  130. my @acc;
  131. my $prev = $len;
  132. foreach my $d (@deltas) {
  133. $prev += $d;
  134. push @acc, $prev;
  135. }
  136. return \@acc;
  137. }
  138. # produce encode and decode dictionary from a tree
  139. sub walk ($node, $code, $h, $rev_h) {
  140. my $c = $node->[0] // return ($h, $rev_h);
  141. if (ref $c) { walk($c->[$_], $code . $_, $h, $rev_h) for ('0', '1') }
  142. else { $h->{$c} = $code; $rev_h->{$code} = $c }
  143. return ($h, $rev_h);
  144. }
  145. # make a tree, and return resulting dictionaries
  146. sub mktree_from_freq ($freq) {
  147. my @nodes = map { [$_, $freq->{$_}] } sort { $a <=> $b } keys %$freq;
  148. do { # poor man's priority queue
  149. @nodes = sort { $a->[1] <=> $b->[1] } @nodes;
  150. my ($x, $y) = splice(@nodes, 0, 2);
  151. if (defined($x)) {
  152. if (defined($y)) {
  153. push @nodes, [[$x, $y], $x->[1] + $y->[1]];
  154. }
  155. else {
  156. push @nodes, [[$x], $x->[1]];
  157. }
  158. }
  159. } while (@nodes > 1);
  160. walk($nodes[0], '', {}, {});
  161. }
  162. sub huffman_encode ($bytes, $dict) {
  163. join('', @{$dict}{@$bytes});
  164. }
  165. sub huffman_decode ($bits, $hash) {
  166. local $" = '|';
  167. $bits =~ s/(@{[sort { length($a) <=> length($b) } keys %{$hash}]})/$hash->{$1}/gr; # very fast
  168. }
  169. sub valid_archive {
  170. my ($fh) = @_;
  171. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  172. $sig eq SIGNATURE || return;
  173. }
  174. return 1;
  175. }
  176. sub create_huffman_entry ($bytes, $out_fh) {
  177. my %freq;
  178. ++$freq{$_} for @$bytes;
  179. my ($h, $rev_h) = mktree_from_freq(\%freq);
  180. my $enc = huffman_encode($bytes, $h);
  181. my $max_symbol = max(keys %freq) // 0;
  182. my @freqs;
  183. foreach my $i (0 .. $max_symbol) {
  184. push @freqs, $freq{$i} // 0;
  185. }
  186. print $out_fh delta_encode(\@freqs);
  187. print $out_fh pack("N", length($enc));
  188. print $out_fh pack("B*", $enc);
  189. }
  190. sub compress ($input, $output) {
  191. # Open the input file
  192. open my $fh, '<:raw', $input
  193. or die "Can't open file <<$input>> for reading: $!";
  194. # Open the output file and write the archive signature
  195. open my $out_fh, '>:raw', $output
  196. or die "Can't open file <<$output>> for writing: $!";
  197. print $out_fh SIGNATURE;
  198. # Read and encode
  199. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  200. create_huffman_entry([unpack('C*', $chunk)], $out_fh);
  201. }
  202. return 1;
  203. }
  204. sub read_bits ($fh, $bits_len) {
  205. my $data = '';
  206. read($fh, $data, $bits_len >> 3);
  207. $data = unpack('B*', $data);
  208. while (length($data) < $bits_len) {
  209. $data .= unpack('B*', getc($fh) // return undef);
  210. }
  211. if (length($data) > $bits_len) {
  212. $data = substr($data, 0, $bits_len);
  213. }
  214. return $data;
  215. }
  216. sub decode_huffman_entry ($fh, $out_fh) {
  217. my @freqs = @{delta_decode($fh)};
  218. my %freq;
  219. foreach my $i (0 .. $#freqs) {
  220. if ($freqs[$i]) {
  221. $freq{$i} = $freqs[$i];
  222. }
  223. }
  224. my (undef, $rev_dict) = mktree_from_freq(\%freq);
  225. foreach my $k (keys %$rev_dict) {
  226. $rev_dict->{$k} = chr($rev_dict->{$k});
  227. }
  228. my $enc_len = unpack('N', join('', map { getc($fh) // die "error" } 1 .. 4));
  229. if ($enc_len > 0) {
  230. print $out_fh huffman_decode(read_bits($fh, $enc_len), $rev_dict);
  231. return 1;
  232. }
  233. return 0;
  234. }
  235. sub decompress ($input, $output) {
  236. # Open and validate the input file
  237. open my $fh, '<:raw', $input
  238. or die "Can't open file <<$input>> for reading: $!";
  239. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  240. # Open the output file
  241. open my $out_fh, '>:raw', $output
  242. or die "Can't open file <<$output>> for writing: $!";
  243. # Decode
  244. while (!eof($fh)) {
  245. decode_huffman_entry($fh, $out_fh) || last;
  246. }
  247. return 1;
  248. }
  249. main();
  250. exit(0);