Tools/LZSS.pm

filter: Statementstmt 92.5% 25 / 27 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.4% 34 / 36 CC 1 SCAR 0.3
CC
1
Cov
93%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Tools/IMP.pm ↑ Summary Tools/Unpack.pm »
1 package EBook::Tools::LZSS;
2 2 ▶use warnings; use strict; use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use English qw( -no_match_vars );
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use version 0.74; our $VERSION = qv("0.5.0");
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 ## Perl Critic overrides:
7 # RequireBriefOpen seems to be way too brief to be useful
8 ## no critic (RequireBriefOpen)
9 # We're not interpolating constants and not making them lexical makes identifying them easier
10 ## no critic (ProhibitConstantPragma)
11  
12 =head1 NAME
13  
14 EBook::Tools::LZSS - Lempel-Ziv-Storer-Szymanski compression and decompression
15  
16 =head1 SYNOPSIS
17  
18 use EBook::Tools::LZSS;
19 my $lzss = EBook::Tools::LZSS->new(lengthbits => 3,
20 offsetbits => 14,
21 windowinit => 'the man');
22 my $textref = $lzss->uncompress(\$data);
23  
24 =cut
25  
26 require Exporter;
27 2 ▶use base qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
28  
29 our @EXPORT_OK;
30 @EXPORT_OK = qw (
31 );
32 our %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
33  
34  
35 2 ▶use Bit::Vector;
Subroutine BEGIN: called CC=1 SCAR=0.0
36 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 0 ▶use EBook::Tools qw(:all);
Subroutine BEGIN: called CC=1 SCAR=2.6
38 use Encode;
39 use File::Basename qw(dirname fileparse);
40 use File::Path; # Exports 'mkpath' and 'rmtree'
41 binmode(STDERR,':encoding(UTF-8)');
42  
43  
44 use constant ENCODED => 0;
45 use constant UNCODED => 1;
46  
47  
48  
49 ####################################################
50 ########## CONSTRUCTOR AND INITIALIZATION ##########
51 ####################################################
52  
53 my %rwfields = (
54 'lengthbits' => 'integer',
55 'offsetbits' => 'integer',
56 'windowinit' => 'string',
57 'windowsize' => 'integer',
58 'windowstart' => 'integer',
59 'maxuncoded' => 'integer',
60 'screwybits' => 'boolean',
61 'verbose' => 'integer',
62 );
63 my %rofields = (
64 );
65 my %privatefields = (
66 );
67  
68 # A simple 'use fields' will not work here: use takes place inside
69 # BEGIN {}, so the @...fields variables won't exist.
70 require fields;
71 fields->import(
72 keys(%rwfields),keys(%rofields),keys(%privatefields)
73 );
74  
75  
76 =head1 CONSTRUCTOR AND INITIALIZATION
77  
78 =head2 C<new(%args)>
79  
80 Instantiates a new EBook::Tools::LZSS object.
81  
82 =head3 Arguments
83  
84 All arguments are optional, but must be identical between compression
85 and decompression for the result to be valid.
86  
87 =over
88  
89 =item * C<lengthbits>
90  
91 The number of bits used to encode the length of a LZSS reference. If
92 not specified defaults to 4 bits.
93  
94 The eBookwise .IMP format typically compresses with 3 length bits.
95  
96 Note that the actual length of the LZSS reference in bytes is greater
97 than the value stored in the length bits. The actual number of bytes
98 returned is the decoded length bits value plus C<maxuncoded> plus 1,
99  
100 =item * C<offsetbits>
101  
102 The number of bits used to encode the offset to a LZSS reference.
103 This also determines the size of the sliding window of reference data.
104 If not specified, it defaults to 12 bits (4096-byte window).
105  
106 The eBookwise .IMP format typically compresses with 14 offset bits
107 (16384-byte window).
108  
109 =item * C<windowinit>
110  
111 A string used to initalize the sliding window. If specified, this
112 string MUST be the same length as the window size, or the subroutine
113 will croak. If not specified, the window will be initialized with
114 spaces.
115  
116 =item * C<windowstart>
117  
118 The first byte position in the window that will be overwritten by
119 decoded text. If not specified, defaults to 0.
120  
121 =item * C<maxuncoded>
122  
123 The maximum number of uncoded bytes (?). This currently isn't used
124 for that purpose, but determines the actual length of a LZSS reference.
125  
126 =item * C<screwybits>
127  
128 If set to true and the number of offset bits is greater than 8, then
129 the offset bits will be read first in a chunk of 8 for the least
130 significant bits, and then the remaining bits will be read and use as
131 the most significant bits. This seems to be necessary for
132 compatibility with Michael Dipperstein's LZSS C compression library
133 but does not hold true for IMP e-book LZSS decompression.
134  
135 =item * C<verbose>
136  
137 If set to true, compression and uncompression will provide additional
138 status feedback on STDOUT.
139  
140 =back
141  
142 =cut
143  
144 sub new ## no critic (Always unpack @_ first)
145 {
146 my $self = shift;
147 my $class = ref($self) || $self;
148 my %args = @_;
149 my $subname = (caller(0))[3];
150 debug(2,"DEBUG[",$subname,"]");
151  
152 my %valid_args = (
153 'lengthbits' => 1,
154 'offsetbits' => 1,
155 'windowinit' => 1,
156 'windowstart' => 1,
157 'maxuncoded' => 1,
158 'screwybits' => 1,
159 'verbose' => 1,
160 );
161  
162 foreach my $arg (keys %args)
163 {
164 croak($subname,"(): invalid argument '",$arg,"'")
165 if(!$valid_args{$arg});
166 }
167  
168 $self = fields::new($class);
169 $self->{lengthbits} = $args{lengthbits} || 4;
170 $self->{offsetbits} = $args{offsetbits} || 12;
171 $self->{windowsize} = 1 << $self->{offsetbits};
172 $self->{windowinit} = $args{windowinit} || ' ' x $self->{windowsize};
173 if(defined $args{windowstart})
174 {
175 $self->{windowstart} = $args{windowstart};
176 }
177 else { $self->{windowstart} = 0; }
178 $self->{maxuncoded} = $args{maxuncoded} || 2;
179 $self->{screwybits} = $args{screwybits};
180 $self->{verbose} = $args{verbose} || 0;
181  
182 if($self->{windowinit}
183 and length($self->{windowinit}) != $self->{windowsize})
184 {
185 croak($subname,"(): \n window initialization string size (",
186 length($self->{windowinit}),
187 " does not match specified number of offset bits (",
188 $self->{windowsize},")\n")
189 }
190  
191 return $self;
192 }
193  
194  
195 #############################
196 ########## METHODS ##########
197 #############################
198  
199 =head1 METHODS
200  
201 =head2 C<uncompress(\$dataref)>
202  
203 Takes a reference to a compressed data string, uncompresses the data
204 string and returns a reference to the uncompressed string.
205  
206 =cut
207  
208 sub uncompress :method
209 {
210 my ($self,$dataref) = @_;
211 my $subname = (caller(0))[3];
212 debug(2,"DEBUG[",$subname,"]");
213  
214 croak($subname,"(): no data provided!\n")
215 unless($dataref);
216 croak($subname,"(): data is not a reference!\n")
217 unless(ref $dataref);
218  
219 my $lengthbits = $self->{lengthbits} || 4;
220 my $offsetbits = $self->{offsetbits} || 12;
221 my $windowsize = $self->{windowsize};
222 my $window = $self->{windowinit};
223 my $max_uncoded = $self->{maxuncoded} || 2;
224 my $max_encoded = (1 << $lengthbits) + $max_uncoded;
225 my $windowpos = $self->{windowstart} || 0;
226  
227 if(length($window) != $windowsize)
228 {
229 croak($subname,"(): \n window initialization string size (",
230 length($window),
231 " does not match specified number of offset bits (",
232 $windowsize,")\n")
233 }
234  
235 if($self->{verbose} > 1)
236 {
237 print {*STDERR} ("Uncompressing with ",$lengthbits," length bits, ",
238 $offsetbits," offset bits, windowpos = ",
239 $windowpos,"\n");
240 }
241  
242 my $bitsize = length($$dataref) * 8;
243 my $bitvector = Bit::Vector->new($bitsize);
244 my $bitoffset;
245 my $bitpos = 0;
246 my $bits;
247  
248 my $encflag;
249 my $dataoffset = 0;
250 my $lzss_offset;
251 my $lzss_length;
252 my $lzss_text;
253 my $uncompressed;
254  
255 # Unfortunately, the bitstream needs to be processed from left to
256 # right, and Bit::Vector really likes to process from right to
257 # left, so we have to process by chunk instead of using
258 # Block_Store
259 while($bitpos < $bitsize)
260 {
261 $bitoffset = $bitsize-$bitpos;
262 $bits = unpack('C',substr($$dataref,$dataoffset,1));
263 $bitvector->Chunk_Store(8,$bitoffset-8,$bits);
264 $dataoffset++;
265 $bitpos += 8;
266 }
267  
268 $bitpos = 0;
269 while($bitpos < $bitsize - 8)
270 {
271 # If there are less than 8 bits left, there's nothing to
272 # decode and we can stop. Otherwise, uncompress.
273  
274 if($self->{verbose} or $EBook::Tools::debug > 0)
275 {
276 my $percent = int( ($bitpos / $bitsize) * 100);
277  
278 print("Uncompressing text... [",$percent,"%]\r")
279 if($percent % 5 == 0);
280 }
281 $bitoffset = $bitsize - $bitpos;
282 $encflag = $bitvector->Chunk_Read(1,$bitoffset-1);
283 $bitpos++;
284 $bitoffset--;
285  
286 if($encflag == UNCODED)
287 {
288 if($bitoffset - 8 < 0)
289 {
290 debug(1,"DEBUG: ran out of bits at bit position ",
291 $bitpos,"!");
292 last;
293 }
294  
295 $bitoffset -= 8;
296 $bitpos += 8;
297 $bits = $bitvector->Chunk_Read(8,$bitoffset);
298 $uncompressed .= chr($bits);
299 substr($window,$windowpos,1,chr($bits));
300 $windowpos++;
301 $windowpos %= $windowsize;
302 }
303 else
304 {
305 if($bitoffset - ($offsetbits + $lengthbits) < 0)
306 {
307 if($bitoffset >= 16)
308 {
309 carp($subname,,"(): ran out of bits at bit position ",
310 $bitpos," [",$bitoffset," bits remaining]!");
311 }
312 last;
313 }
314 if($self->{screwybits} and $offsetbits > 8)
315 {
316 my $lowoffset;
317 my $highoffset;
318 my $extrabits = $offsetbits - 8;
319  
320 $bitoffset -= 8;
321 $lowoffset = $bitvector->Chunk_Read(8,$bitoffset);
322 $bitoffset -= $extrabits;
323 $highoffset = $bitvector->Chunk_Read($extrabits,$bitoffset);
324  
325 $lzss_offset = (256 * $highoffset) + $lowoffset;
326 }
327 else
328 {
329 $bitoffset -= $offsetbits;
330 $lzss_offset = $bitvector->Chunk_Read($offsetbits,$bitoffset);
331 }
332 $bitoffset -= $lengthbits;
333 $lzss_length = $bitvector->Chunk_Read($lengthbits,$bitoffset);
334  
335 if($lzss_offset > $windowsize)
336 {
337 carp($subname,"(): LZSS offset points outside window!\n");
338 last;
339 }
340  
341 if($lzss_length == 0
342 and $lzss_offset == 0)
343 {
344 if($bitoffset >= 16)
345 {
346 carp($subname,"(): invalid LZSS code at bit position ",
347 $bitpos," [",$bitoffset," bits remaining]!\n");
348 }
349 last;
350 }
351 $bitpos += ($offsetbits + $lengthbits);
352 $lzss_length += $max_uncoded + 1;
353  
354 foreach my $lzss_pos (0 .. ($lzss_length - 1) )
355 {
356 my $windowoffset;
357 my $char = substr($window,
358 ($lzss_offset + $lzss_pos) % $windowsize,
359 1);
360 substr($window,$windowpos,1,$char);
361 $windowpos++;
362 $windowpos %= $windowsize;
363 $uncompressed .= $char;
364 }
365 }
366 }
367  
368 if($self->{verbose} or $EBook::Tools::debug > 0)
369 {
370 print("Finished uncompressing text.\n");
371 }
372 return \$uncompressed;
373 }
374  
375  
376 ################################
377 ########## PROCEDURES ##########
378 ################################
379  
380  
381 ########## END CODE ##########
382  
383 =head1 BUGS AND LIMITATIONS
384  
385 =over
386  
387 =item * Compression not yet implemented.
388  
389 =item * The LZSS algorithm isn't documented in the POD.
390  
391 =item * Once compression is implemented and the algorithm is
392 documented, this module is a good candidate for being forked off into
393 its own project. Relying on it to keep its current name may be
394 unwise.
395  
396 =back
397  
398  
399 =head1 AUTHOR
400  
401 Zed Pobre <zed@debian.org>
402  
403 The design of this module was based on the C LZSS library by Michael
404 Dipperstein, version 0.5.2, at http://michael.dipperstein.com/lzss/
405  
406  
407 =head1 LICENSE AND COPYRIGHT
408  
409 Copyright 2008 Zed Pobre
410  
411 Licensed to the public under the terms of the GNU GPL, version 2.
412  
413 =cut
414  
415 1;
416 __END__
« Tools/IMP.pm ↑ Summary Tools/Unpack.pm »