lzhc_file_compression.pl 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Created on: 21 May 2014
  5. # Latest edit on: 26 April 2015
  6. # Website: https://github.com/trizen
  7. # A new type of LZ compression + Huffman coding, featuring a very short decompression time.
  8. use 5.010;
  9. use strict;
  10. use autodie;
  11. use warnings;
  12. use Getopt::Std qw(getopts);
  13. use File::Basename qw(basename);
  14. use constant {
  15. PKGNAME => 'lzhc',
  16. VERSION => '0.02',
  17. FORMAT => 'lzhc',
  18. };
  19. use constant {
  20. MIN => 4,
  21. BUFFER => 256,
  22. SIGNATURE => uc(FORMAT) . chr(2),
  23. };
  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 walk {
  79. my ($n, $s, $h) = @_;
  80. if (exists($n->{a})) {
  81. $h->{$n->{a}} = $s;
  82. return 1;
  83. }
  84. walk($n->{'0'}, $s . '0', $h);
  85. walk($n->{'1'}, $s . '1', $h);
  86. }
  87. sub mktree {
  88. my ($text) = @_;
  89. my %letters;
  90. ++$letters{$_} for (split(//, $text));
  91. my @nodes;
  92. if ((@nodes = map { {a => $_, freq => $letters{$_}} } keys %letters) == 1) {
  93. return {$nodes[0]{a} => '0'};
  94. }
  95. my %n;
  96. while ((@nodes = sort { $a->{freq} <=> $b->{freq} } @nodes) > 1) {
  97. %n = ('0' => {%{shift(@nodes)}}, '1' => {%{shift(@nodes)}});
  98. $n{freq} = $n{'0'}{freq} + $n{'1'}{freq};
  99. push @nodes, {%n};
  100. }
  101. walk(\%n, '', $n{tree} = {});
  102. return $n{tree};
  103. }
  104. sub huffman_encode {
  105. my ($str, $dict) = @_;
  106. join('', map { $dict->{$_} // die("bad char $_") } split(//, $str));
  107. }
  108. sub huffman_decode {
  109. my ($hash, $bytes) = @_;
  110. local $" = '|';
  111. unpack('B*', $bytes) =~ s/(@{[sort {length($a) <=> length($b)} keys %{$hash}]})/$hash->{$1}/gr;
  112. }
  113. sub valid_archive {
  114. my ($fh) = @_;
  115. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  116. $sig eq SIGNATURE || return;
  117. }
  118. return 1;
  119. }
  120. sub compress {
  121. my ($input, $output) = @_;
  122. # Open the input file
  123. open my $fh, '<:raw', $input;
  124. # Open the output file and write the archive signature
  125. open my $out_fh, '>:raw', $output;
  126. print {$out_fh} SIGNATURE;
  127. while ((my $len = read($fh, (my $block), BUFFER)) > 0) {
  128. my %dict;
  129. my $max = int($len / 2);
  130. foreach my $i (reverse(MIN .. $max)) {
  131. foreach my $j (0 .. $len - $i * 2) {
  132. if ((my $pos = index($block, substr($block, $j, $i), $j + $i)) != -1) {
  133. if (not exists $dict{$pos} or $i > $dict{$pos}[1]) {
  134. $dict{$pos} = [$j, $i];
  135. }
  136. }
  137. }
  138. }
  139. my @pairs;
  140. my $uncompressed = '';
  141. for (my $i = 0 ; $i < $len ; $i++) {
  142. if (exists $dict{$i}) {
  143. my ($key, $vlen) = @{$dict{$i}};
  144. push @pairs, [$i, $key, $vlen];
  145. $i += $vlen - 1;
  146. }
  147. else {
  148. $uncompressed .= substr($block, $i, 1);
  149. }
  150. }
  151. my $huffman_hash = mktree($uncompressed);
  152. my $huffman_enc = huffman_encode($uncompressed, $huffman_hash);
  153. my %huffman_dict;
  154. foreach my $k (keys %{$huffman_hash}) {
  155. push @{$huffman_dict{length($huffman_hash->{$k})}}, [$k, $huffman_hash->{$k}];
  156. }
  157. {
  158. use bytes;
  159. my $binary_enc = pack('B*', $huffman_enc);
  160. my $encoding_len = length($binary_enc);
  161. printf("%3d -> %3d (%.2f%%)\n", $len, $encoding_len, ($len - $encoding_len) / $len * 100);
  162. print {$out_fh}
  163. # Length of the uncompressed text
  164. chr(length($uncompressed) - 1),
  165. # LZT pairs num
  166. chr($#pairs + 1),
  167. # LZT pairs encoded into bytes
  168. (
  169. map {
  170. map { chr }
  171. @{$_}
  172. } @pairs
  173. ),
  174. # Huffman dictionary size
  175. chr(scalar(keys(%huffman_dict)) > 0 ? scalar(keys(%huffman_dict)) - 1 : 0),
  176. # Huffman dictionary into bytes
  177. (
  178. join(
  179. '',
  180. map {
  181. chr($_)
  182. . chr($#{$huffman_dict{$_}} + 1)
  183. . join('', map { $_->[0] } @{$huffman_dict{$_}})
  184. . pack('B*', join('', map { $_->[1] } @{$huffman_dict{$_}}))
  185. } sort { $a <=> $b } keys %huffman_dict
  186. )
  187. ),
  188. # Huffman encoded bytes length
  189. chr($encoding_len - 1),
  190. # Huffman encoded bytes
  191. $binary_enc
  192. }
  193. # exit;
  194. }
  195. close $fh;
  196. close $out_fh;
  197. }
  198. sub decompress {
  199. my ($input, $output) = @_;
  200. # Open and validate the input file
  201. open my $fh, '<:raw', $input;
  202. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E archive!\n";
  203. # Open the output file
  204. open my $out_fh, '>:raw', $output;
  205. while (read($fh, (my $len_byte), 1) > 0) {
  206. read($fh, (my $lzt_pairs), 1);
  207. # Create the LZT dictionary
  208. my %dict;
  209. for my $i (1 .. ord($lzt_pairs)) {
  210. read($fh, (my $at_byte), 1);
  211. read($fh, (my $from_byte), 1);
  212. read($fh, (my $size_byte), 1);
  213. $dict{ord($at_byte)} = [ord($from_byte), ord($size_byte)];
  214. }
  215. read($fh, (my $huffman_pairs), 1);
  216. # Create the Huffman dictionary
  217. my %huffman_dict;
  218. for my $i (1 .. ord($huffman_pairs) + 1) {
  219. read($fh, (my $pattern_len), 1);
  220. read($fh, (my $pattern_num), 1);
  221. my $bits_num = ord($pattern_len) * ord($pattern_num);
  222. if ($bits_num % 8 != 0) {
  223. $bits_num += 8 - ($bits_num % 8);
  224. }
  225. read($fh, (my $chars), ord($pattern_num));
  226. read($fh, (my $patterns), $bits_num / 8);
  227. my $bits = unpack('B*', $patterns);
  228. foreach my $char (split(//, $chars)) {
  229. $huffman_dict{substr($bits, 0, ord($pattern_len), '')} = $char;
  230. }
  231. }
  232. read($fh, (my $bytes_len), 1);
  233. read($fh, (my $bytes), ord($bytes_len) + 1);
  234. # Huffman decoding
  235. my $len = ord($len_byte) + 1;
  236. my $block = substr(huffman_decode(\%huffman_dict, $bytes), 0, $len);
  237. my $acc = 0;
  238. my $decompressed = '';
  239. # LZT decoding
  240. for (my $i = 0 ; $i <= $len ; $i++) {
  241. if (exists($dict{$i + $acc})) {
  242. my $pos = $dict{$i + $acc};
  243. $decompressed .= substr($decompressed, $pos->[0], $pos->[1]);
  244. $acc += $pos->[1];
  245. $i--;
  246. }
  247. else {
  248. $decompressed .= substr($block, $i, 1);
  249. }
  250. }
  251. print {$out_fh} $decompressed;
  252. }
  253. close $fh;
  254. close $out_fh;
  255. }
  256. main();
  257. exit(0);