lzw_file_compression.pl 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 08 December 2022
  4. # Edit: 15 June 2023
  5. # https://github.com/trizen
  6. # Compress/decompress files using LZW compression.
  7. # See also:
  8. # https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch
  9. use 5.020;
  10. use strict;
  11. use warnings;
  12. use experimental qw(signatures);
  13. use Getopt::Std qw(getopts);
  14. use File::Basename qw(basename);
  15. use constant {
  16. PKGNAME => 'LZW',
  17. VERSION => '0.03',
  18. FORMAT => 'lzw',
  19. CHUNK_SIZE => 1 << 17, # higher value = better compression
  20. };
  21. # Container signature
  22. use constant SIGNATURE => uc(FORMAT) . chr(3);
  23. sub usage {
  24. my ($code) = @_;
  25. print <<"EOH";
  26. usage: $0 [options] [input file] [output file]
  27. options:
  28. -e : extract
  29. -i <filename> : input filename
  30. -o <filename> : output filename
  31. -r : rewrite output
  32. -v : version number
  33. -h : this message
  34. examples:
  35. $0 document.txt
  36. $0 document.txt archive.${\FORMAT}
  37. $0 archive.${\FORMAT} document.txt
  38. $0 -e -i archive.${\FORMAT} -o document.txt
  39. EOH
  40. exit($code // 0);
  41. }
  42. sub version {
  43. printf("%s %s\n", PKGNAME, VERSION);
  44. exit;
  45. }
  46. sub valid_archive {
  47. my ($fh) = @_;
  48. if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
  49. $sig eq SIGNATURE || return;
  50. }
  51. return 1;
  52. }
  53. sub main {
  54. my %opt;
  55. getopts('ei:o:vhr', \%opt);
  56. $opt{h} && usage(0);
  57. $opt{v} && version();
  58. my ($input, $output) = @ARGV;
  59. $input //= $opt{i} // usage(2);
  60. $output //= $opt{o};
  61. my $ext = qr{\.${\FORMAT}\z}io;
  62. if ($opt{e} || $input =~ $ext) {
  63. if (not defined $output) {
  64. ($output = basename($input)) =~ s{$ext}{}
  65. || die "$0: no output file specified!\n";
  66. }
  67. if (not $opt{r} and -e $output) {
  68. print "'$output' already exists! -- Replace? [y/N] ";
  69. <STDIN> =~ /^y/i || exit 17;
  70. }
  71. decompress_file($input, $output)
  72. || die "$0: error: decompression failed!\n";
  73. }
  74. elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
  75. $output //= basename($input) . '.' . FORMAT;
  76. compress_file($input, $output)
  77. || die "$0: error: compression failed!\n";
  78. }
  79. else {
  80. warn "$0: don't know what to do...\n";
  81. usage(1);
  82. }
  83. }
  84. # Compress a string to a list of output symbols
  85. sub compress ($uncompressed) {
  86. # Build the dictionary
  87. my $dict_size = 256;
  88. my %dictionary;
  89. foreach my $i (0 .. $dict_size - 1) {
  90. $dictionary{chr($i)} = $i;
  91. }
  92. my $w = '';
  93. my @result;
  94. foreach my $c (split(//, $uncompressed)) {
  95. my $wc = $w . $c;
  96. if (exists $dictionary{$wc}) {
  97. $w = $wc;
  98. }
  99. else {
  100. push @result, $dictionary{$w};
  101. # Add wc to the dictionary
  102. $dictionary{$wc} = $dict_size++;
  103. $w = $c;
  104. }
  105. }
  106. # Output the code for w
  107. if ($w ne '') {
  108. push @result, $dictionary{$w};
  109. }
  110. return \@result;
  111. }
  112. # Decompress a list of output ks to a string
  113. sub decompress ($compressed) {
  114. # Build the dictionary
  115. my $dict_size = 256;
  116. my @dictionary = map { chr($_) } 0 .. $dict_size - 1;
  117. my $w = $dictionary[$compressed->[0]];
  118. my $result = $w;
  119. foreach my $j (1 .. $#{$compressed}) {
  120. my $k = $compressed->[$j];
  121. my $entry =
  122. ($k < $dict_size) ? $dictionary[$k]
  123. : ($k == $dict_size) ? ($w . substr($w, 0, 1))
  124. : die "Bad compressed k: $k";
  125. $result .= $entry;
  126. # Add w+entry[0] to the dictionary
  127. push @dictionary, $w . substr($entry, 0, 1);
  128. ++$dict_size;
  129. $w = $entry;
  130. }
  131. return \$result;
  132. }
  133. sub read_bit ($fh, $bitstring) {
  134. if (($$bitstring // '') eq '') {
  135. $$bitstring = unpack('b*', getc($fh) // return undef);
  136. }
  137. chop($$bitstring);
  138. }
  139. sub read_bits ($fh, $bits_len) {
  140. my $data = '';
  141. read($fh, $data, $bits_len >> 3);
  142. $data = unpack('B*', $data);
  143. while (length($data) < $bits_len) {
  144. $data .= unpack('B*', getc($fh) // return undef);
  145. }
  146. if (length($data) > $bits_len) {
  147. $data = substr($data, 0, $bits_len);
  148. }
  149. return $data;
  150. }
  151. sub elias_encoding ($integers) {
  152. my $bitstring = '';
  153. foreach my $k (scalar(@$integers), @$integers) {
  154. if ($k == 0) {
  155. $bitstring .= '0';
  156. }
  157. else {
  158. my $t = sprintf('%b', $k);
  159. my $l = length($t) + 1;
  160. my $L = sprintf('%b', $l);
  161. $bitstring .= ('1' x (length($L) - 1)) . '0' . substr($L, 1) . substr($t, 1);
  162. }
  163. }
  164. pack('B*', $bitstring);
  165. }
  166. sub elias_decoding ($fh) {
  167. my @ints;
  168. my $len = 0;
  169. my $buffer = '';
  170. for (my $k = 0 ; $k <= $len ; ++$k) {
  171. my $bl = 0;
  172. ++$bl while (read_bit($fh, \$buffer) eq '1');
  173. if ($bl > 0) {
  174. my $bl2 = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. $bl)) - 1;
  175. my $int = oct('0b1' . join('', map { read_bit($fh, \$buffer) } 1 .. ($bl2 - 1)));
  176. push @ints, $int;
  177. }
  178. else {
  179. push @ints, 0;
  180. }
  181. if ($k == 0) {
  182. $len = pop(@ints);
  183. }
  184. }
  185. return \@ints;
  186. }
  187. sub encode_integers ($integers) {
  188. my @counts;
  189. my $count = 0;
  190. my $bits_width = 1;
  191. my $bits_max_symbol = 1 << $bits_width;
  192. my $processed_len = 0;
  193. foreach my $k (@$integers) {
  194. while ($k >= $bits_max_symbol) {
  195. if ($count > 0) {
  196. push @counts, [$bits_width, $count];
  197. $processed_len += $count;
  198. }
  199. $count = 0;
  200. $bits_max_symbol *= 2;
  201. $bits_width += 1;
  202. }
  203. ++$count;
  204. }
  205. push @counts, grep { $_->[1] > 0 } [$bits_width, scalar(@$integers) - $processed_len];
  206. say "Bit sizes: ", join(' ', map { $_->[0] } @counts);
  207. say "Lengths : ", join(' ', map { $_->[1] } @counts);
  208. say '';
  209. my $compressed = elias_encoding([(map { $_->[0] } @counts), (map { $_->[1] } @counts)]);
  210. my $bits = '';
  211. foreach my $pair (@counts) {
  212. my ($blen, $len) = @$pair;
  213. foreach my $symbol (splice(@$integers, 0, $len)) {
  214. $bits .= sprintf("%0*b", $blen, $symbol);
  215. }
  216. }
  217. $compressed .= pack('B*', $bits);
  218. return $compressed;
  219. }
  220. sub decode_integers ($fh) {
  221. my $ints = elias_decoding($fh);
  222. my $half = scalar(@$ints) >> 1;
  223. my @counts;
  224. foreach my $i (0 .. ($half - 1)) {
  225. push @counts, [$ints->[$i], $ints->[$half + $i]];
  226. }
  227. my $bits_len = 0;
  228. foreach my $pair (@counts) {
  229. my ($blen, $len) = @$pair;
  230. $bits_len += $blen * $len;
  231. }
  232. my $bits = read_bits($fh, $bits_len);
  233. my @integers;
  234. foreach my $pair (@counts) {
  235. my ($blen, $len) = @$pair;
  236. foreach my $chunk (unpack(sprintf('(a%d)*', $blen), substr($bits, 0, $blen * $len, ''))) {
  237. push @integers, oct('0b' . $chunk);
  238. }
  239. }
  240. return \@integers;
  241. }
  242. # Compress file
  243. sub compress_file ($input, $output) {
  244. open my $fh, '<:raw', $input
  245. or die "Can't open file <<$input>> for reading: $!";
  246. my $header = SIGNATURE;
  247. # Open the output file for writing
  248. open my $out_fh, '>:raw', $output
  249. or die "Can't open file <<$output>> for write: $!";
  250. # Print the header
  251. print $out_fh $header;
  252. # Compress data
  253. while (read($fh, (my $chunk), CHUNK_SIZE)) {
  254. print $out_fh encode_integers(compress($chunk));
  255. }
  256. # Close the output file
  257. close $out_fh;
  258. }
  259. # Decompress file
  260. sub decompress_file ($input, $output) {
  261. # Open and validate the input file
  262. open my $fh, '<:raw', $input
  263. or die "Can't open file <<$input>> for reading: $!";
  264. valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
  265. # Open the output file
  266. open my $out_fh, '>:raw', $output
  267. or die "Can't open file <<$output>> for writing: $!";
  268. while (!eof($fh)) {
  269. print $out_fh ${decompress(decode_integers($fh))};
  270. }
  271. # Close the output file
  272. close $out_fh;
  273. }
  274. main();
  275. exit(0);