blib/lib/EBook/Tools/PalmDoc.pm

filter: Statementstmt 76.0% 19 / 25 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 87.5% 7 / 8 Podpod n/a totaltotal 78.7% 26 / 33 CC 1 SCAR 1.5
CC
1
Cov
76%
import
2.0
BEGIN
1.3
BEGIN
1.0
CRAP 1.2
« Build ↑ Summary blib/lib/EBook/Tools/EReader.pm »
1 package EBook::Tools::PalmDoc;
2 1 ▶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 1 ▶use version 0.74; our $VERSION = qv("0.4.8");
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 # Mixed case subs and the variable %record are inherited from Palm::PDB
6 ## no critic (ProhibitAmbiguousNames)
7 ## no critic (ProhibitMixedCaseSubs)
8  
9 =head1 NAME
10  
11 EBook::Tools::PalmDoc - Palm::PDB handler for manipulating the PalmDoc/PilotDoc/AportisDoc format
12  
13 =head1 SYNOPSIS
14  
15 use EBook::Tools::PalmDoc qw(uncompress_palmdoc);
16 use Palm::PDB;
17  
18 my $pdb = Palm::PDB->new();
19  
20 or
21  
22 use EBook::Tools::PalmDoc qw(:all);
23  
24 my $pdb = EBook::Tools::PalmDoc->new();
25 $pdb->set_text($text);
26 $pdb->Write('textfile.pdb');
27  
28 my $pdb2 = EBook::Tools::PalmDoc->new();
29 $pdb2->{attributes}{resource} = 1;
30 $pdb->import_textfile('textfile.txt');
31 $pdb->Write('textfile.prc');
32  
33 =head1 DESCRIPTION
34  
35 This module contains a L<Palm::PDB> handler (subclassed from
36 L<Palm::Raw>) and some associated general procedures for dealing with
37 PalmDoc books. This handles PalmDoc and only PalmDoc. For
38 Mobipocket, eReader, or other .pdb/.prc formats, see the module
39 specific to the format.
40  
41 =cut
42  
43 require Exporter;
44 1 ▶use base qw(Exporter Palm::Raw);
Subroutine BEGIN: called CC=1 SCAR=0.0
45  
46 our @EXPORT_OK;
47 @EXPORT_OK = qw (
48 &compress_palmdoc
49 &parse_palmdoc_header
50 &uncompress_palmdoc
51 );
52 our %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
53  
54 sub import ## no critic (Always unpack @_ first)
55 {
56 0 ▶ &Palm::PDB::RegisterPDBHandlers( __PACKAGE__, [ "REAd", "TEXt" ], );
Subroutine import: not called CC=1 SCAR=6.9
57 0 &Palm::PDB::RegisterPRCHandlers( __PACKAGE__, [ "REAd", "TEXt" ], );
58 0 EBook::Tools::PalmDoc->export_to_level(1, @_);
59 0 return;
60 }
61  
62 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
63 1 ▶use EBook::Tools qw(debug hexstring);
Subroutine BEGIN: called CC=1 SCAR=2.6
64 use File::Basename qw(fileparse);
65 use Palm::PDB;
66 use Palm::Raw();
67  
68 my $htmlsupport = 0;
69 eval
70 {
71 require HTML::TextToHTML;
72 EBook::Tools::DRM->import();
73 }; # Trailing semicolon is required here
74 unless($@){ $htmlsupport = 1; }
75  
76  
77 #################################
78 ########## CONSTRUCTOR ##########
79 #################################
80  
81 =head1 CONSTRUCTOR
82  
83 =head2 C<new()>
84  
85 Instantiates a new Ebook::Tools::PalmDoc object. To create a Palm
86 Resource file instead of a Palm Database file, set
87 C<$self->{attributes}{resource}> to be true immediately after
88 construction.
89  
90 Create a new Doc object. By default, it's not a resource database. Setting
91 C<$self->{attributes}{resource}> to C<1> before any manipulations will
92 cause it to become a resource database.
93  
94 =cut
95  
96 sub new ## no critic (Always unpack @_ first)
97 {
98 my $class = shift;
99 my $self = $class->SUPER::new(@_);
100  
101 $self->{'creator'} = 'REAd';
102 $self->{'type'} = 'TEXt';
103  
104 $self->{attributes}{resource} = 0;
105  
106 $self->{appinfo} = undef;
107 $self->{sort} = undef;
108 $self->{records} = [];
109 $self->{text} = '';
110 $self->{bookmarks} = {};
111  
112 return $self;
113 }
114  
115  
116 ######################################
117 ########## ACCESSOR METHODS ##########
118 ######################################
119  
120 =head1 ACCESSOR METHODS
121  
122 =head2 C<bookmarks()>
123  
124 Returns a hash of bookmarks, where the keys are the bookmark offsets
125 and the values are the bookmark names.
126  
127 =cut
128  
129 sub bookmarks :method
130 {
131 my $self = shift;
132 my %bookmarks;
133  
134 if($self->{bookmarks} and ref($self->{bookmarks}) eq 'HASH')
135 {
136 %bookmarks = %{$self->{bookmarks}};
137 }
138 elsif($self->{bookmarks})
139 {
140 %bookmarks = $self->{bookmarks}
141 }
142 else
143 {
144 %bookmarks = ();
145 }
146 return %bookmarks;
147 }
148  
149  
150 =head2 C<text()>
151  
152 Returns the text of the file
153  
154 =cut
155  
156 sub text :method
157 {
158 my $self = shift;
159 my $subname = ( caller(0) )[3];
160 debug(2,"DEBUG[",$subname,"]");
161  
162 my $length = length($self->{text});
163  
164 carp("WARNING: actual text length (",$length,
165 ") does not match specified text length (",
166 $self->{header}{textlength},")\n")
167 unless($length == $self->{header}{textlength});
168  
169 return $self->{text};
170 }
171  
172  
173 =head2 C<html()>
174  
175 Returns the text of the file converted to HTML via L<HTML::TextToHTML>.
176  
177 =cut
178  
179 sub html :method
180 {
181 my $self = shift;
182 my $subname = ( caller(0) )[3];
183 debug(2,"DEBUG[",$subname,"]");
184  
185 croak("HTML support requires that HTML::TextToHTML be installed!\n")
186 unless($htmlsupport);
187  
188 my $conv = HTML::TextToHTML->new();
189 my $header = "<html>\n<head>\n <title>" . $self->{name} . "</title>\n";
190 $header .= "</head>\n<body>\n";
191 my $footer = "</body>\n</html>\n";
192  
193 return $header . $conv->process_chunk($self->{text}) . $footer;
194 }
195  
196  
197 ######################################
198 ########## MODIFIER METHODS ##########
199 ######################################
200  
201 =head1 MODIFIER METHODS
202  
203 These methods have two naming/capitalization schemes -- methods
204 directly related to the subclassing of Palm::PDB use its
205 MethodName capitalization style. Any other methods are
206 lowercase_with_underscores for consistency with the rest of
207 EBook::Tools.
208  
209  
210 =head2 C<ParseRecord(%record)>
211  
212 Parses PDB records, updating the object attributes. This method is
213 called automatically on every database record (in .pdb files) during
214 C<Load()>.
215  
216 =cut
217  
218 sub ParseRecord :method ## no critic (Always unpack @_ first)
219 {
220 my $self = shift;
221 my %record = @_;
222 my $subname = ( caller(0) )[3];
223 debug(3,"DEBUG[",$subname,"]");
224  
225 my $currentrecord = scalar @{$$self{records}};
226  
227 if($currentrecord == 0)
228 {
229 $$self{header} = parse_palmdoc_header($record{data});
230 return \%record;
231 }
232  
233 if($currentrecord <= $$self{header}{textrecords})
234 {
235 $self->ParseRecordText($record{data});
236 }
237 else
238 {
239 # Bookmark records at end of file
240 $self->ParseRecordBookmark($record{data},$currentrecord);
241 }
242 return \%record;
243 }
244  
245  
246 =head2 C<ParseResource(%resource)>
247  
248 Parses PDB resources, updating object attributes. This is called
249 automatically on every database resource (in .prc files) during
250 C<Load()>.
251  
252 =cut
253  
254 sub ParseResource :method ## no critic (Always unpack @_ first)
255 {
256 my $self = shift;
257 my %resource = @_;
258 my $subname = ( caller(0) )[3];
259 debug(3,"DEBUG[",$subname,"]");
260  
261 my $currentresource = scalar @{$$self{resources}};
262  
263 if($currentresource == 0)
264 {
265 $self->{header} = parse_palmdoc_header($resource{data});
266 return \%resource;
267 }
268  
269 if($currentresource <= $self->{header}{textrecords})
270 {
271 $self->ParseRecordText($resource{data});
272 }
273 else
274 {
275 # Bookmark records at end of file
276 $self->ParseRecordBookmark($resource{data},$currentresource);
277 }
278 return \%resource;
279 }
280  
281  
282 =head2 C<ParseRecordBookmark($data,$currentrecord)>
283  
284 Parses bookmark records/resources, updating object attributes, most
285 notably C<$self->{bookmarks}>.
286  
287 The C<$currentrecord> argument is optional, but without it the
288 debugging information may be less useful. This is called
289 automatically by L<ParseRecord()> and L<ParseResource()> as needed.
290  
291 =cut
292  
293 sub ParseRecordBookmark :method ## no critic (Always unpack @_ first)
294 {
295 my $self = shift;
296 my ($data,$currentrecord) = @_;
297 my $subname = ( caller(0) )[3];
298 debug(2,"DEBUG[",$subname,"]");
299  
300 $currentrecord = '[unknown]' unless(defined $currentrecord);
301 my $bookmark;
302 my $offset;
303  
304 if(length($data) < 20)
305 {
306 croak($subname,"(): bookmark record ",$currentrecord,
307 " is only ",length($data)," bytes (need 20)\n");
308 }
309 elsif(length($data) == 20)
310 {
311 debug(1,"bookmark record ",$currentrecord," is ",
312 length($data)," bytes (expected 20)");
313 }
314  
315 $bookmark = substr($data,0,18);
316 $bookmark =~ s/\0+//gx;
317 $offset = unpack('n',substr($data,18,2));
318 $self->{bookmarks}->{$offset} = $bookmark;
319 debug(1,"DEBUG: record ",$currentrecord,
320 " is bookmark '",$bookmark,"' [offset ",$offset,"]");
321 return 1;
322 }
323  
324  
325 =head2 C<ParseRecordText($data)>
326  
327 Parses text records, updating object attributes, most notably
328 appending text to C<$self->{text}>.
329  
330 This is called automatically by L</ParseRecord()> and
331 L</ParseResource()> as needed.
332  
333 =cut
334  
335 sub ParseRecordText :method
336 {
337 my $self = shift;
338 my $data = shift;
339 my $subname = ( caller(0) )[3];
340 debug(2,"DEBUG[",$subname,"]");
341  
342 my $compression = $self->{header}{compression};
343  
344 if($compression == 1) # No compression
345 {
346 $self->{text} .= $data;
347 }
348 elsif($compression == 2) # PalmDoc compression
349 {
350 $self->{text} .= uncompress_palmdoc($data);
351 }
352 else
353 {
354 croak($subname,"(): unknown compression value (",
355 $compression,")\n");
356 }
357 return 1;
358 }
359  
360  
361 =head2 C<set_text(@text)>
362  
363 Uses the contents of C<@text> (concatenated) as the text of the PDB.
364  
365 =cut
366  
367 sub set_text ## no critic (Always unpack @_ first)
368 {
369 my $self = shift;
370 my $text = join('',@_);
371 my $subname = ( caller(0) )[3];
372 debug(2,"DEBUG[",$subname,"]");
373  
374 my $isresource = $self->{attributes}{resource};
375 my $record0;
376 my $record;
377 my $compression = 2;
378 my $offset;
379 my $textblock;
380  
381 $self->{'records'} = [];
382 $self->{'resources'} = [];
383  
384 $record0 = ($isresource)?
385 $self->append_Resource()
386 : $self->append_Record();
387 $record0->{'compression'} = $compression;
388 $record0->{'length'} = 0;
389 $record0->{'spare'} = 0;
390 $record0->{'textrecords'} = 0;
391 $record0->{'recsize'} = 4096;
392  
393 for($offset = 0; $offset < length($text); $offset += 4096 )
394 {
395 $record = ($isresource) ?
396 $self->append_Resource
397 : $self->append_Record;
398 $textblock = substr($text,$offset,4096);
399 $record->{'data'} = compress_palmdoc($textblock);
400  
401 $record0->{'textrecords'} ++;
402 $record0->{'length'} += length($text);
403 }
404 if($record0->{'length'} < 4096)
405 {
406 $record0->{'recsize'} = $record0->{'length'};
407 }
408  
409 $record0->{'data'} =
410 pack('nnNnnN',
411 $record0->{'compression'}, $record0->{'spare'},
412 $record0->{'length'},
413 $record0->{'textrecords'}, $record0->{'recsize'}, 0 );
414  
415 return 1;
416 }
417  
418  
419 =head2 import_textfile($filename)
420  
421 Set the contents of the Doc to the contents of the file and sets the
422 name of the PDB to the basename of the file.
423  
424 =cut
425  
426 sub import_textfile :method
427 {
428 my $self = shift;
429 my $filename = shift;
430 my $subname = ( caller(0) )[3];
431 debug(2,"DEBUG[",$subname,"]");
432  
433 my $fh;
434 open($fh,"<:raw",$filename)
435 or croak($subname,"(): unable to open '",$filename,"' [",@!,"]");
436 $self->set_text('',<$fh>);
437 close($fh)
438 or croak($subname,"(): unable to close '",$filename,"' [",@!,"]");
439  
440 $self->{'name'} = fileparse($filename,'\.\w+$');
441 return 1;
442 }
443  
444  
445 ################################
446 ########## PROCEDURES ##########
447 ################################
448  
449 =head1 PROCEDURES
450  
451 All procedures are exportable, but none are exported by default.
452  
453 =head2 C<compress_palmdoc($text)>
454  
455 Compresses input text using the simplified Lempel-Ziv 77 encoding used
456 by PalmDoc and some other formats and returns the compressed string.
457  
458 See L</uncompress_palmdoc()> for more details on the algorithm.
459  
460 This procedure was taken from L<Palm::Doc> with some minor changes.
461  
462 =cut
463  
464 sub compress_palmdoc
465 {
466 my $text = shift;
467 my $subname = ( caller(0) )[3];
468 debug(3,"DEBUG[",$subname,"]");
469  
470 my $textlength = length($text);
471 my $compressed = '';
472  
473 debug(1,"WARNING: input text is longer than 4096 bytes (",$textlength,
474 " bytes) and may not produce a valid PDB if used.")
475 if($textlength > 4096);
476  
477 my $offset = 0;
478 while($offset < $textlength)
479 {
480 # See http://web.archive.org/web/20061024025145/http://patb.dyndns.org/Programming/PilotDoc.htm
481  
482 # Try type B compression first.
483 # If the next 3 to 10 bytes are already in the compressed
484 # buffer, we can encode them into a 2 byte sequence. Don't
485 # bother too close to the ends, however... Makes the boundary
486 # conditions simpler.
487 if( $offset > 10 and $textlength - $offset > 10 )
488 {
489 my $chunk = '';
490 my $match = -1;
491  
492 # the preamble is what'll be in the decoders output buffer.
493 my $preamble = substr( $text, 0, $offset );
494 for( my $j = 10; $j >= 3; $j -- )
495 {
496 $chunk = substr($text,$offset,$j); # grab next $j characters
497 $match = rindex($preamble,$chunk); # in the output?
498  
499 # type B code has a 2047 byte sliding window, so
500 # matches have to be within that range to be useful
501 last if $match >= 0 and ($offset - $match) <= 2047;
502 $match = -1;
503 }
504  
505 my $n = length $chunk;
506 if( $match >= 0 and $n <= 10 and $n >= 3 )
507 {
508 my $m = $offset - $match;
509  
510 # first 2 bits are 10, next 11 are offset, next 3 are length-3
511 $compressed .= pack( "n", 0x8000 + (($m<<3)&0x3ff8) + ($n-3) );
512  
513 $offset += $n;
514  
515 next;
516 }
517 }
518  
519 my $ch = substr( $text, $offset ++, 1 );
520 my $och = ord($ch);
521  
522 # Try type C compression.
523 if( $offset+1 < $textlength and $ch eq ' ' )
524 {
525 my $nch = substr( $text, $offset, 1 );
526 my $onch = ord($nch);
527  
528 if( $onch >= 0x40 and $onch < 0x80 )
529 {
530 # space plus ASCII character compression
531 $compressed .= chr($onch ^ 0x80);
532 $offset ++;
533  
534 next;
535 }
536 }
537  
538 if( $och == 0 or ($och >= 9 and $och < 0x80) )
539 {
540 # pass through
541 $compressed .= $ch;
542 }
543 else
544 {
545 # Type A code. This is essentially an 'escape' like '\\'
546 # in strings. For efficiency, it's best to encode as long
547 # a sequence as possible with one copy.
548 #
549 # This might seem like it would cause us to miss out on a
550 # type B sequence, but in actuality keeping long binary
551 # strings together improves the likelyhood of a later type
552 # B sequence than interspersing them with x01's.
553  
554 my $next = substr($text,$offset - 1);
555 if( $next =~ /([\x01-\x08\x80-\xff]{1,8})/o )
556 {
557 my $binseq = $1;
558 $compressed .= chr(length $binseq);
559 $compressed .= $binseq;
560 # first char, $ch, is already counted
561 $offset += length( $binseq ) - 1;
562 }
563 }
564 }
565 return $compressed;
566 }
567  
568  
569 =head2 C<parse_palmdoc_header($data)>
570  
571 Takes as an argument a scalar containing the 16 bytes of the PalmDoc
572 header (also used by Mobipocket). Returns a hashref containing those
573 values keyed to recognizable names.
574  
575 See:
576  
577 http://wiki.mobileread.com/wiki/DOC#PalmDOC
578  
579 and
580  
581 http://wiki.mobileread.com/wiki/MOBI
582  
583 =head3 keys
584  
585 The returned hashref will have the following keys:
586  
587 =over
588  
589 =item * C<compression>
590  
591 Possible values:
592  
593 =over
594  
595 =item 1 - no compression
596  
597 =item 2 - PalmDoc compression
598  
599 =item 128 - iSilo3?
600  
601 =item 17480 (the characters 'DH') - Mobipocket 'Dictionary Huffman'
602 compression (aka HuffDic aka Huff/CDIC)
603  
604 =back
605  
606 A warning will be carped if an unknown value is found.
607  
608 =item * C<textlength>
609  
610 Uncompressed length of book text in bytes
611  
612 =item * C<textrecords>
613  
614 Number of PDB records used for book text
615  
616 =item * C<recordsize>
617  
618 Maximum size of each record containing book text. This should always
619 be 2048 (for some Mobipocket files) or 4096 (for everything else). A
620 warning will be carped if it isn't.
621  
622 =item * C<spare>
623  
624 Two bytes that should always be zero. A warning will be carped if
625 they aren't.
626  
627 =item * C<unknown12>
628  
629 32 bits of unknown data, generally zero. This key may be changed
630 later if more information is discovered. Use with caution.
631  
632 =back
633  
634 Note that the current position component of the header is discarded.
635  
636 =cut
637  
638 sub parse_palmdoc_header
639 {
640 my $data = shift;
641 my $subname = ( caller(0) )[3];
642 debug(2,"DEBUG[",$subname,"]");
643  
644 my %pdbcompression = (
645 1 => 'no compression',
646 2 => 'PalmDoc compression',
647 128 => 'iSilo3 compression',
648 17480 => 'Dictionary Huffman compression',
649 );
650  
651 # We're expecting 16 bytes of data exactly. We won't croak on
652 # more, but it will be reported
653 croak($subname,"(): record 0 is too short (only ",
654 length($data)," bytes, need at least 16)!\n")
655 if(length($data) < 16);
656 debug(1,"DEBUG: ",length($data)," bytes of PalmDoc header data",
657 " (expected 16)")
658 if(length($data) != 16);
659  
660 my @list = unpack("nnNnnN",$data);
661 my %header;
662  
663 $header{compression} = $list[0]; # Bytes 00-01
664 $header{spare} = $list[1]; # Bytes 01-02
665 $header{textlength} = $list[2]; # Bytes 03-07
666 $header{textrecords} = $list[3]; # Bytes 08-09
667 $header{recordsize} = $list[4]; # Bytes 10-11
668 $header{unknown12} = $list[5]; # Bytes 12-15
669  
670 carp($subname,"(): value ",$header{spare},
671 " found in header 'spare' (expected 0)")
672 unless($header{spare} == 0);
673 carp($subname,"(): found text record size ",$header{recordsize},
674 ", expected 2048 or 4096")
675 unless($header{recordsize} == 2048
676 or $header{recordsize} == 4096);
677 carp($subname,"(): found unknown compression value ",$header{compression})
678 unless(defined $pdbcompression{$header{compression}});
679 debug(1,"DEBUG: PDB compression type is ",
680 $pdbcompression{$header{compression}});
681  
682 foreach my $key (sort keys %header)
683 {
684 debug(2,'DEBUG: palmdoc{',$key,'}=0x',sprintf("%04x",$header{$key}));
685 }
686 return \%header;
687 }
688  
689  
690 =head2 C<uncompress_palmdoc($data,%args)>
691  
692 Uncompresses data compressed using the simplified Lempel-Ziv 77 scheme
693 used by PalmDoc and some other formats, and returns the uncompressed
694 string.
695  
696 If an error is encountered during uncompression outputs a debug
697 message and returns undef.
698  
699 =head3 Arguments
700  
701 C<uncompress_palmdoc> takes one optional named argument:
702  
703 =over
704  
705 =item C<trailing>
706  
707 This specifies the number of trailing bytes to ignore on each record
708 during decompression. Extra data such as this is sometimes found on
709 version 6 Mobipocket records.
710  
711 =back
712  
713 =head3 Algorithm
714  
715 The decoding mechanism is as follows:
716  
717 Start by reading a byte from the compressed stream. If the byte is:
718  
719 =over
720  
721 =item * 0x00: copy unmodified
722  
723 =item * 0x01 to 0x08: "Type A" command
724  
725 This specifies that the next 1-8 bytes are to be copied unmodified.
726  
727 =item * 0x09 to 0x7f: copy unmodified
728  
729 =item * 0x80 to 0xbf: "Type B" command
730  
731 This specifies that the 16 bits (two characters) starting at that
732 point represent a length-offset pair. Of the 16 bits that make up
733 these two bytes, the two leftmost bits (which should be '10') are
734 simply an identifier and are discarded. The next 11 bits encode the
735 offset backwards from the end of uncompressed text, and the last three
736 encode the length of text to copy from that point (copying n+3 bytes).
737  
738 =item * 0xc0 to 0xff: "Type C" command
739  
740 This compresses spaces with the next character, with the value of that
741 character being XORed with 0x80.
742  
743 =back
744  
745 =cut
746  
747 sub uncompress_palmdoc
748 {
749 my $data = shift;
750 my (%args) = @_;
751 my $subname = ( caller(0) )[3];
752 debug(3,"DEBUG[",$subname,"]");
753  
754 my %valid_args = (
755 'trailing' => 1,
756 );
757 foreach my $arg (keys %args)
758 {
759 croak($subname,"(): invalid argument '",$arg,"'")
760 if(!$valid_args{$arg});
761 }
762  
763 my $trailing = $args{trailing} || 0;
764 my $reallength = length($data);
765 my $length = $reallength - $trailing;
766 my $traildata = substr($data,$length,$trailing);
767  
768 my $offset = 0; # Current offset into data
769 my $char; # Character being examined
770 my $ord; # Ordinal of $char
771 my $lz77; # 16-bit Lempel-Ziv 77 length-offset pair
772 my $lz77offset; # LZ77 offset
773 my $lz77length; # LZ77 length
774 my $lz77pos; # Position inside $lz77length
775 my $text = ''; # Output (uncompressed) text
776 my $textlength; # Length of uncompressed text during LZ77 pass
777 my $textpos; # Position inside $text during LZ77 pass
778  
779 while($offset < $length)
780 {
781 $char = substr($data,$offset++,1);
782 $ord = ord($char);
783  
784 # The long if-elsif chain is the best logic for $ord handling
785 ## no critic (Cascading if-elsif chain)
786 if($ord == 0)
787 {
788 # Nulls are literal
789 $text .= $char;
790 }
791 elsif($ord <= 8)
792 {
793 # Next $ord bytes are literal
794 if($offset + $ord > $length)
795 {
796 debug(1,"WARNING: ",$ord," literal bytes starting at ",$offset,
797 " exceeds data size (",$length,")");
798 return $text;
799 }
800 $text .= substr($data,$offset,$ord);
801 $offset += $ord;
802 }
803 elsif($ord <= 0x7f)
804 {
805 # Values from 0x09 through 0x7f are literal
806 $text .= $char;
807 }
808 elsif($ord <= 0xbf)
809 {
810 # Data is LZ77-compressed
811  
812 # From Wikipedia:
813 # "A length-distance pair is always encoded by a two-byte
814 # sequence. Of the 16 bits that make up these two bytes,
815 # 11 bits go to encoding the distance, 3 go to encoding
816 # the length, and the remaining two are used to make sure
817 # the decoder can identify the first byte as the beginning
818 # of such a two-byte sequence."
819  
820 $offset++;
821 if($offset > length($data))
822 {
823 debug(1,"WARNING: offset to LZ77 bits (",$offset,
824 ") is outside of the data (size ",length($data),")");
825 return $text;
826 }
827 $lz77 = unpack('n',substr($data,$offset-2,2));
828  
829 # Leftmost two bits are ID bits and need to be dropped
830 $lz77 &= 0x3fff;
831  
832 # Length is rightmost 3 bits + 3
833 $lz77length = ($lz77 & 0x0007) + 3;
834  
835 # Remaining 11 bits are offset
836 $lz77offset = $lz77 >> 3;
837 if($lz77offset < 1)
838 {
839 debug(1,"WARNING: LZ77 decompression offset at ",$offset,
840 " is invalid!");
841 return;
842 }
843  
844 # Getting text from the offset is a little tricky, because
845 # in theory you can be referring to characters you haven't
846 # actually decompressed yet. You therefore have to check
847 # the reference one character at a time.
848 $textlength = length($text);
849 for($lz77pos = 0; $lz77pos < $lz77length; $lz77pos++)
850 {
851 $textpos = $textlength - $lz77offset;
852 if($textpos < 0)
853 {
854 debug(1,"WARNING: LZ77 decompression reference is before",
855 " beginning of text!");
856 return;
857 }
858 $text .= substr($text,$textpos,1);
859 $textlength++;
860 }
861 }
862 else
863 {
864 # 0xc0 - 0xff are single characters (XOR 0x80) preceded by
865 # a space
866 $text .= ' ' . chr($ord ^ 0x80);
867 }
868 }
869 if($reallength > $length)
870 {
871 debug(3,"DEBUG: skipping ",$trailing," bytes at end of record: 0x",
872 hexstring($traildata));
873 }
874 return $text;
875 }
876  
877 1;
878 __END__
« Build ↑ Summary blib/lib/EBook/Tools/EReader.pm »