forked from trizen/perl-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lzbf_file_compression.pl
316 lines (230 loc) · 7.83 KB
/
lzbf_file_compression.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/perl
# Author: Trizen
# Date: 11 May 2024
# https://github.com/trizen
# Compress/decompress files using LZ77 compression (LZSS variant with hash tables), using a byte-aligned encoding, similar to LZ4.
# References:
# https://github.com/lz4/lz4/blob/dev/doc/lz4_Frame_format.md
# https://github.com/lz4/lz4/blob/dev/doc/lz4_Block_format.md
use 5.036;
use Getopt::Std qw(getopts);
use File::Basename qw(basename);
use constant {
PKGNAME => 'LZBF',
VERSION => '0.01',
FORMAT => 'lzbf',
MIN_MATCH_LEN => 5, # minimum match length
MAX_MATCH_LEN => ~0, # maximum match length
MAX_MATCH_DIST => (1 << 16) - 1, # maximum match distance
CHUNK_SIZE => 1 << 18,
};
# Container signature
use constant SIGNATURE => uc(FORMAT) . chr(1);
sub usage {
my ($code) = @_;
print <<"EOH";
usage: $0 [options] [input file] [output file]
options:
-e : extract
-i <filename> : input filename
-o <filename> : output filename
-r : rewrite output
-v : version number
-h : this message
examples:
$0 document.txt
$0 document.txt archive.${\FORMAT}
$0 archive.${\FORMAT} document.txt
$0 -e -i archive.${\FORMAT} -o document.txt
EOH
exit($code // 0);
}
sub version {
printf("%s %s\n", PKGNAME, VERSION);
exit;
}
sub valid_archive {
my ($fh) = @_;
if (read($fh, (my $sig), length(SIGNATURE), 0) == length(SIGNATURE)) {
$sig eq SIGNATURE || return;
}
return 1;
}
sub main {
my %opt;
getopts('ei:o:vhr', \%opt);
$opt{h} && usage(0);
$opt{v} && version();
my ($input, $output) = @ARGV;
$input //= $opt{i} // usage(2);
$output //= $opt{o};
my $ext = qr{\.${\FORMAT}\z}io;
if ($opt{e} || $input =~ $ext) {
if (not defined $output) {
($output = basename($input)) =~ s{$ext}{}
|| die "$0: no output file specified!\n";
}
if (not $opt{r} and -e $output) {
print "'$output' already exists! -- Replace? [y/N] ";
<STDIN> =~ /^y/i || exit 17;
}
decompress_file($input, $output)
|| die "$0: error: decompression failed!\n";
}
elsif ($input !~ $ext || (defined($output) && $output =~ $ext)) {
$output //= basename($input) . '.' . FORMAT;
compress_file($input, $output)
|| die "$0: error: compression failed!\n";
}
else {
warn "$0: don't know what to do...\n";
usage(1);
}
}
sub lzss_encode_fast($str) {
my $la = 0;
my @symbols = unpack('C*', $str);
my $end = $#symbols;
my $min_len = MIN_MATCH_LEN; # minimum match length
my $max_len = MAX_MATCH_LEN; # maximum match length
my $max_dist = MAX_MATCH_DIST; # maximum match distance
my (@literals, @distances, @lengths, %table);
while ($la <= $end) {
my $best_n = 1;
my $best_p = $la;
my $lookahead = substr($str, $la, $min_len);
if (exists($table{$lookahead}) and $la - $table{$lookahead} <= $max_dist) {
my $p = $table{$lookahead};
my $n = $min_len;
while ($n <= $max_len and $la + $n <= $end and $symbols[$la + $n - 1] == $symbols[$p + $n - 1]) {
++$n;
}
$best_p = $p;
$best_n = $n;
}
$table{$lookahead} = $la;
if ($best_n > $min_len) {
push @lengths, $best_n - 1;
push @distances, $la - $best_p;
push @literals, undef;
$la += $best_n - 1;
}
else {
push @lengths, (0) x $best_n;
push @distances, (0) x $best_n;
push @literals, @symbols[$best_p .. $best_p + $best_n - 1];
$la += $best_n;
}
}
return (\@literals, \@distances, \@lengths);
}
sub compression($chunk, $out_fh) {
my ($literals, $distances, $lengths) = lzss_encode_fast($chunk);
my $literals_end = $#{$literals};
for (my $i = 0 ; $i <= $literals_end ; ++$i) {
my @uncompressed;
while ($i <= $literals_end and defined($literals->[$i])) {
push @uncompressed, $literals->[$i];
++$i;
}
my $literals_string = pack('C*', @uncompressed);
my $literals_length = scalar(@uncompressed);
my $dist = $distances->[$i] // 0;
my $match_len = $lengths->[$i] // 0;
my $len_byte = 0;
$len_byte |= ($literals_length >= 15 ? 15 : $literals_length) << 4;
$len_byte |= ($match_len >= 15 ? 15 : $match_len);
$literals_length -= 15;
$match_len -= 15;
print $out_fh chr($len_byte);
while ($literals_length >= 0) {
print $out_fh chr($literals_length >= 255 ? 255 : $literals_length);
$literals_length -= 255;
}
print $out_fh $literals_string;
while ($match_len >= 0) {
print $out_fh chr($match_len >= 255 ? 255 : $match_len);
$match_len -= 255;
}
if ($dist >= 1 << 16) {
die "Too large distance: $dist";
}
print $out_fh pack('B*', sprintf('%016b', $dist));
}
}
sub decompression($fh, $out_fh) {
my $search_window = '';
while (!eof($fh)) {
my $len_byte = ord(getc($fh));
my $literals_length = $len_byte >> 4;
my $match_len = $len_byte & 0b1111;
if ($literals_length == 15) {
while (1) {
my $byte_len = ord(getc($fh));
$literals_length += $byte_len;
last if $byte_len != 255;
}
}
my $literals = '';
if ($literals_length > 0) {
read($fh, $literals, $literals_length);
}
if ($match_len == 15) {
while (1) {
my $byte_len = ord(getc($fh));
$match_len += $byte_len;
last if $byte_len != 255;
}
}
my $offset = oct('0b' . unpack('B*', getc($fh) . getc($fh)));
$search_window .= $literals;
if ($offset == 1) {
$search_window .= substr($search_window, -1) x $match_len;
}
elsif ($offset >= $match_len) { # non-overlapping matches
$search_window .= substr($search_window, length($search_window) - $offset, $match_len);
}
else { # overlapping matches
foreach my $i (1 .. $match_len) {
$search_window .= substr($search_window, length($search_window) - $offset, 1);
}
}
print $out_fh substr($search_window, -($match_len + $literals_length));
$search_window = substr($search_window, -MAX_MATCH_DIST) if (length($search_window) > 2 * MAX_MATCH_DIST);
}
}
# Compress file
sub compress_file ($input, $output) {
open my $fh, '<:raw', $input
or die "Can't open file <<$input>> for reading: $!";
my $header = SIGNATURE;
# Open the output file for writing
open my $out_fh, '>:raw', $output
or die "Can't open file <<$output>> for write: $!";
# Print the header
print $out_fh $header;
# Compress data
while (read($fh, (my $chunk), CHUNK_SIZE)) {
compression($chunk, $out_fh);
}
# Close the file
close $out_fh;
}
# Decompress file
sub decompress_file ($input, $output) {
# Open and validate the input file
open my $fh, '<:raw', $input
or die "Can't open file <<$input>> for reading: $!";
valid_archive($fh) || die "$0: file `$input' is not a \U${\FORMAT}\E v${\VERSION} archive!\n";
# Open the output file
open my $out_fh, '>:raw', $output
or die "Can't open file <<$output>> for writing: $!";
while (!eof($fh)) {
decompression($fh, $out_fh);
}
# Close the file
close $fh;
close $out_fh;
}
main();
exit(0);