blib/lib/Image/ParseGIF.pm untested

filter: Statementstmt 0.0% 0 / 313 Branchbran 0.0% 0 / 204 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 622 CC 103 SCAR 51.8
CC
103
Cov
0%
_read_extension
702.0
_read_image_descriptor
182.0
parse
90.0
CRAP 177.9
1 package Image::ParseGIF;
2 #
3 ######################################################################
4 #
5 # Parse a GIF image into its component parts.
6 # (c) 1999/2000 University of NSW
7 #
8 # Written by Benjamin Low <b.d.low@unsw.edu.au>
9 #
10 ######################################################################
11 #
12 # Change Log
13 # 1999/08/30 0.01 First release.
14 # 1999/09/01 0.02 Fixed image version test.
15 # 2000/05/15 0.10 Fixed a number of embarrasing problems (I was
16 # mixing up the initial bytes of each part)...
17 # Thanks to Doug Bagley for letting me know.
18 # - also added the deanimate method.
19 # 2000/05/15 0.11 Fixed typo in print_parts
20 # 2000/06/05 0.20 Colour table manipulations, written by Ed Halley
21 # - also added binmode to file i/o (also thanks to Ed)
22 #
23 ######################################################################
24 #
25  
26 #use diagnostics; # turn on -w warning explanations (verbose!)
27 use strict; # try and pick up silly errors at compile time
28  
29 use vars qw/@ISA @EXPORT_OK %EXPORT_TAGS $VERSION/;
30  
31 use Exporter ();
32 @ISA = qw/Exporter/;
33 @EXPORT_OK = qw//;
34 %EXPORT_TAGS = qw//;
35 # add %EXPORT_TAGS to @EXPORT_OK
36 Exporter::export_tags();
37 Exporter::export_ok_tags();
38  
39 $VERSION = 0.20;
40  
41 use Fcntl qw(:DEFAULT :flock); # sysopen, flock symbolic constants
42  
43 use IO::Handle;
44 # also use IO::File in ::open()
45  
46 sub new
47 # create a new object
48 {
49 my ($class, $filename, @args) = @_;
50 my $args; # -> %args
51  
52 # check if %args were passed in by reference
53 # ie. there's only one key with no value, and it's a hash ref
54 if (@args == 1 && ref($args[0]) eq 'HASH') { $args = $args[0]; }
55 elsif (@args % 2 == 0) { $args = {@args}; }
56 else { $@ = "bad argument list"; return undef; }
57  
58 # instance data
59 my $self =
60 {
61 header => '', # GIF header, screen desc, colour table
62 parts => [], # (image, control) parts
63 trailer => '', # trailer
64  
65 delay => 0, # default delay between frames
66  
67 # three new options added by Ed Halley [ed@explorati.com]
68 # - when set, these operations are applied to all colour table(s)
69 invert => 0, # toggle colour table(s) inversion (light-for-dark)
70 posterize => 0, # flatten colour table(s) (to N colours, 0 == off)
71 desaturate => 0, # toggle desaturatation (grayscale)
72  
73 debug => 0, # debug state
74 output => undef, # IO::Handle to send output to (STDOUT by default)
75 };
76  
77 # merge arguments
78 while (my ($k, $v) = each %{$args})
79 {
80 $self->{lc($k)} = $v;
81 }
82  
83 # allow the non-American spelling :-)
84 $self->{posterize} = delete $self->{posterise}
85 if (exists $self->{posterise});
86  
87 bless ($self, $class);
88  
89 # set output filehandle
90 $self->output($self->{'output'});
91  
92 # open input file if provided
93 if ($filename) { return $self = undef unless $self->open($filename); }
94  
95 return $self;
96 }
97  
98 sub debug
99 {
100 my ($self, $l) = @_;
101 return defined($l) ? $self->{'debug'} = $l : $self->{'debug'};
102 }
103  
104 # new options added by Ed Halley [ed@explorati.com]
105 sub invert
106 {
107 my ($self, $l) = @_;
108 return defined($l) ? $self->{'invert'} = $l : $self->{'invert'};
109 }
110  
111 # new option added by Ed Halley [ed@explorati.com]
112 sub posterize
113 {
114 my ($self, $l) = @_;
115 return defined($l) ? $self->{'posterize'} = $l : $self->{'posterize'};
116 }
117 sub posterise { shift->posterize(@_) }
118  
119 # new option added by Ed Halley [ed@explorati.com]
120 sub desaturate
121 {
122 my ($self, $l) = @_;
123 return defined($l) ? $self->{'desaturate'} = $l : $self->{'desaturate'};
124 }
125  
126 sub _read
127 # read and confirm I got what I asked for
128 # - read $len and write into buffer at $offset
129 # - if offset < 0, writes to (end of buffer + offset + 1) (this is different
130 # to perl's inbuilt read, which writes at end + offset, i.e. overwrites
131 # last 'offset' bytes)
132 # - returns false on error
133 # e.g.
134 # _read($fh, $buf, 1); # read 1 byte into offset 0
135 # _read($fh, $buf, 1, 5); # read 1 byte into offset 5
136 # _read($fh, $buf, 1, -1); # read 1 byte into offset (len($buf) + 'offset' + 1)
137 #
138 {
139 my ($io, $buf, $len, $offset) = @_;
140  
141 $offset ||= 0; # 0, if not defined or ''
142 $offset += ($buf ? length($buf) + 1 : 1) if $offset < 0;
143 $offset = 0 if ($offset < 0);
144  
145 my $r = $io->read($_[1], $len, $offset);
146  
147 $@ = "read error: $!", return undef unless (defined($r));
148  
149 # eof is ok
150 $@ = "short read: $r / $len" unless ($r == 0 or $r == $len);
151  
152 return ($r == $len);
153 }
154  
155 sub open
156 # open a gif and parse it
157 {
158 use IO::File;
159  
160 my ($self, $filename) = @_;
161  
162 my $io = new IO::File ($filename, O_RDONLY);
163  
164 unless (defined $io)
165 { $@ = $!; warn "$@\n" if $self->{'debug'}; return undef }
166  
167 # be nice to non-unix users
168 binmode($io);
169  
170 my $r = $self->parse($io);
171 $io->close();
172 return $r;
173 }
174  
175 my $_autoflush = 1; # class variable
176  
177 sub _wrap
178 # wrap a filehandle (a la IO::Wrap, but use IO::Handle instead of FileHandle)
179 {
180 my ($io, $mode) = @_;
181  
182 unless (UNIVERSAL::can($io, 'read'))
183 {
184 my $fh = $io;
185 $io = new IO::Handle;
186 # fdopen() the filehandle directly (i.e. dup the filehandle), rather
187 # than using fileno($fh). Using the fileno directly will cause the
188 # original file to be closed when the IO object is destroyed.
189 unless ($io->fdopen($fh, $mode))
190 {
191 $@ = "could not open IO::Handle on [$fh]: $!";
192 warn "$@\n";
193 return undef;
194 }
195  
196 $io->autoflush($_autoflush);
197  
198 # be nice to non-unix users
199 binmode($io);
200 }
201  
202 return $_[0] = $io;
203 }
204  
205 sub autoflush
206 # class method to turn on/off autoflush for newly created IO::Handles
207 # - as per IO::Handle's autoflush, calling autoflush without parameters
208 # will turn on autoflush.
209 {
210 my ($self, $v) = @_;
211 return $_autoflush = (defined($v) ? $v : 1);
212 }
213  
214 sub _read_and_adjust_color_table
215 # colour-table reading and adjusting made into function by Ed Halley [ed@explorati.com]
216 # probably a lot of faster ways to do the transforms, but this is readable
217 {
218 my ($self, $io, $flags) = @_;
219 my $nColors = (1<<(($flags & 0x07) + 1));
220 my $aColors = ' ' x (3*$nColors);
221  
222 warn "\treading colour table " .
223 "[" . (3 * $nColors) . " bytes]\n" if $self->{'debug'};
224  
225 _read($io, $aColors, 3 * $nColors);
226  
227 my $i;
228 if ($self->{'invert'})
229 {
230 warn "\tinverting colour table\n" if $self->{'debug'};
231 for $i (0 .. ($nColors-1))
232 {
233 my ($r, $g, $b) = unpack("CCC", substr($aColors, 3*$i, 3));
234 $r = 255-$r;
235 $g = 255-$g;
236 $b = 255-$b;
237 substr($aColors, 3*$i, 3) = pack("CCC", $r, $g, $b);
238 }
239 }
240 if ($self->{'desaturate'})
241 {
242 warn "\tdesaturating colour table\n" if $self->{'debug'};
243 for $i (0 .. ($nColors-1))
244 {
245 my ($r, $g, $b) = unpack("CCC", substr($aColors, 3*$i, 3));
246 my $avg = ($r + $g + $b) / 3;
247 $r = $avg;
248 $g = $avg;
249 $b = $avg;
250 substr($aColors, 3*$i, 3) = pack("CCC", $r, $g, $b);
251 }
252 }
253 if ($self->{'posterize'})
254 {
255 warn "\tposterizing colour table\n" if $self->{'debug'};
256 for $i (0 .. ($nColors-1))
257 {
258 my ($r, $g, $b) = unpack("CCC", substr($aColors, 3*$i, 3));
259 #$r = ($r < 128 ? 0 : 255);
260 #$g = ($g < 128 ? 0 : 255);
261 #$b = ($b < 128 ? 0 : 255);
262 # quantise each colour (BDL)
263 my $s = 255 / $self->{'posterize'};
264 $r = int (int($r/$s + 0.5) * $s);
265 $g = int (int($g/$s + 0.5) * $s);
266 $b = int (int($b/$s + 0.5) * $s);
267 substr($aColors, 3*$i, 3) = pack("CCC", $r, $g, $b);
268 }
269 }
270  
271 $aColors;
272 }
273  
274 sub _read_header
275 {
276 my ($self, $io) = @_;
277 my $b; # used to buffer 'headers' which need to be unpacked
278 my $flags; # used for flag bitmaps
279  
280 warn "reading header\n" if $self->{'debug'};
281  
282 # get the GIF 'signature' (e.g. 'GIF89a')
283 _read($io, $self->{'header'}, 6, 0);
284  
285 unless ($self->{'header'} =~ /^GIF(\d\d)([a-z])/)
286 {
287 $@ = "not a GIF - signature is [$self->{'header'}]";
288 warn "$@\n" if $self->{'debug'};
289 return undef;
290 }
291  
292 my @spec_ver = qw/89 a/;
293 my @img_ver = ($1, $2);
294  
295 # check the image version (note numbering = 87,88,...99, 00, 01, ..., 86)
296 {
297 local $"='';
298 warn "\tGIF version [@img_ver] greater than [@spec_ver]\n"
299 if (($img_ver[0] < 87 ? $img_ver[0] + 100 : $img_ver[0]) > $spec_ver[0]
300 or ($img_ver[0] == $spec_ver[0] and $img_ver[1] gt $spec_ver[1]));
301 }
302  
303 # get logical screen description and test for presence of colour table
304 _read($io, $b, 7);
305 $self->{'header'} .= $b;
306  
307 ($flags) = unpack("x4 C x2", $b);
308  
309 if ($flags & 0x80) # get global color table if present
310 {
311 my $ctable = $self->_read_and_adjust_color_table($io, $flags);
312 $self->{'header'} .= $ctable;
313 }
314  
315 return 1;
316 }
317  
318 sub _read_image_descriptor
319 # read an image descriptor and add to current part
320 {
321 my ($self, $io, $part, $b) = @_;
322 # $b - used to buffer 'headers' which need to be unpacked
323 # - should contain the 'image separator' byte (0x2c) to start
324  
325 warn "reading image descriptor (-> part $part)\n" if $self->{'debug'};
326  
327 unless (ord($b) == 0x2c)
328 {
329 $@ = "not an image separator [$b]";
330 warn "$@\n" if $self->{'debug'};
331 return undef;
332 }
333  
334 # append separator to current part
335 $self->{'parts'}[$part] .= $b;
336  
337 # read descriptor
338 _read($io, $b, 9);
339  
340 # append descriptor to current part
341 $self->{'parts'}[$part] .= $b;
342  
343 if ($self->{'debug'} > 1)
344 {
345 # write (width x height) @ (top, left) (flags)
346 my ($l, $t, $w, $h, $flags) = unpack("v v v v C", $b);
347 my @f;
348 push (@f, 'LOCAL_COLOUR_TABLE') if ($flags & 0x80);
349 push (@f, 'INTERLACED') if ($flags & 0x40);
350 push (@f, 'SORTED_COLOUR_TABLE') if ($flags & 0x20);
351 push (@f, sprintf 'RESERVED(0x%x)', ($flags & 0x18)>>3)
352 if ($flags & 0x18);
353 warn sprintf("\t%dx%d@%d,%d (0x%.2x = %s)\n", $w, $h, $l, $t,
354 $flags, join('|', @f) || '-');
355 }
356  
357 my ($flags) = unpack("x8 C", $b);
358 if ($flags & 0x80) # local colour map?
359 {
360 my $ctable = $self->_read_and_adjust_color_table($io, $flags);
361 $self->{'parts'}[$part] .= $ctable;
362 }
363  
364 # get 'LZW code size' parameter
365 warn "\treading LZW code size\n" if $self->{'debug'};
366 _read($io, $self->{'parts'}[$part], 1, -1); # read 1 byte -> append to part
367  
368 # and now the sub-block/s
369 _read($io, $b, 1); # get block length
370 $self->{'parts'}[$part] .= $b;
371 while (ord($b) > 0)
372 {
373 warn "\t reading sub-block [" , ord($b), " bytes]\n" if
374 $self->{'debug'} > 1;
375 _read($io, $self->{'parts'}[$part], ord($b), -1);
376 # get either the block terminator (0x00) (ie. no more blocks),
377 # or the block size of the next block
378 _read($io, $b, 1); # get block length
379 $self->{'parts'}[$part] .= $b;
380 }
381 warn "\tdone sub-block, next part\n" if $self->{'debug'};
382  
383 return 1;
384 }
385  
386 sub _read_extension
387 # read an extension, but only and add to current part if it is a graphic
388 # control
389 {
390 my ($self, $io, $part, $b) = @_;
391 # $b - used to buffer 'headers' which need to be unpacked
392 # - should contain the 'extension introducer' byte (0x21) to start
393  
394 warn "reading extension (-> part $part)\n" if $self->{'debug'};
395  
396 unless (ord($b) == 0x21)
397 {
398 $@ = "not an extension [$b]";
399 warn "$@\n" if $self->{'debug'};
400 return undef;
401 }
402  
403 # read extension type
404 _read($io, $b, 1);
405  
406 my $t = ord($b);
407  
408 if ($t == 0xf9) # graphic control (precursor to an image)
409 {
410 # graphic control precedes an image decriptor
411 warn "\tgraphic control\n" if $self->{'debug'};
412  
413 # ok, want this extension so add introducer and type to current part
414 $self->{'parts'}[$part] .= pack('C2', 0x21, 0xf9);
415  
416 _read($io, $b, 6); # get the gc 'header'
417  
418 if ($self->{'debug'} > 1)
419 {
420 # write delay, transparent index, (flags)
421 my ($s, $flags, $d, $i) = unpack("C C v C", $b);
422 warn "\tERROR: invalid size (got $s, expected 4\n" if $s != 4;
423 my @f;
424 push (@f, sprintf 'RESERVED(0x%x)', ($flags & 0xe0)>>5)
425 if ($flags & 0xe0);
426 push (@f, sprintf 'DISPOSAL_METHOD(%d)', ($flags & 0x1c)>>2)
427 if ($flags & 0x1c);
428 push (@f, 'USER_INPUT') if ($flags & 0x02);
429 push (@f, "TRANSPARENT($i)") if ($flags & 0x01);
430 warn sprintf("\t[dt=%dms (0x%.2x = %s)]\n", $d*10,
431 $flags, join('|', @f) || '-');
432 }
433  
434 # update delay
435 my ($s, $flags, $delay, $tci, $bt) = unpack("C C v C C", $b);
436  
437 $b = pack("C C v C C", $s, $flags, $self->{'delay'}, $tci, $bt);
438 $self->{'parts'}[$part] .= $b;
439 }
440 elsif ($t == 0x01) # plain text - skip
441 {
442 warn "\tplain text (skipping)\n" if $self->{'debug'};
443 _read($io, $b, 13); # 'header'
444 _read($io, $b, 1); # block length, or terminator (==0)
445 while (ord($b) > 0)
446 {
447 warn "\t skipping sub-block [" , ord($b), " bytes]\n" if
448 $self->{'debug'} > 1;
449 _read($io, $b, ord($b));
450 # filter as per the GIF Plain Text Extension Recommendation,
451 # - except use ? rather than space
452 $b =~ s/[\x00-\x1f\x7f-\xff]/?/sg;
453 warn "\t[$b]\n" if $self->{'debug'} > 1;
454 _read($io, $b, 1); # block length, or terminator (==0)
455 }
456 }
457 elsif ($t == 0xff) # application extension - skip
458 {
459 warn "\tapplication extension (skipping)\n" if $self->{'debug'};
460 _read($io, $b, 12); # 'header'
461 if ($self->{'debug'} > 1)
462 {
463 my ($s, $id, @c) = unpack ('C a8 C3', $b);
464 warn "\tERROR: invalid size (got $s, expected 11\n" if $s != 11;
465 $id =~ s/[\x00-\x1f\x7f-\xff]/?/sg; # filter non-printable chars
466 warn "\t[$id, " . sprintf ('0x%x%x%x', @c) . "]\n";
467 }
468 _read($io, $b, 1); # block length, or terminator (==0)
469 while (ord($b) > 0)
470 {
471 warn "\t skipping sub-block [" , ord($b), " bytes]\n" if
472 $self->{'debug'} > 1;
473 _read($io, $b, ord($b));
474 _read($io, $b, 1); # block length, or terminator (==0)
475 }
476 }
477 elsif ($t == 0xfe) # comment - skip
478 {
479 warn "\tcomment (skipping)\n" if $self->{'debug'};
480 # no 'header'
481  
482 _read($io, $b, 1); # block length, or terminator (==0)
483 while (ord($b) > 0)
484 {
485 warn "\t skipping sub-block [" , ord($b), " bytes]\n" if
486 $self->{'debug'} > 1;
487 _read($io, $b, ord($b));
488 $b =~ s/[\x00-\x1f\x7f-\xff]/?/sg; # filter non-printable chars
489 warn "\t[$b]\n" if $self->{'debug'} > 1;
490 _read($io, $b, 1); # block length, or terminator (==0)
491 }
492 }
493 else
494 {
495 $@ = "invalid extension label found";
496 warn "$@\n" if $self->{'debug'};
497 return undef;
498 }
499  
500 return 1;
501 }
502  
503 sub parse
504 # parse a GIF, reading from a given filehandle or IO object
505 {
506 my ($self, $io) = @_;
507 my $b; # used to buffer 'headers' which need to be unpacked
508  
509 unless (_wrap($io, 'r'))
510 {
511 $@ ||= "could not wrap [$io]";
512 return undef;
513 }
514  
515 # read header, aborting if it doesn't look like a GIF
516 _read_header($self, $io) or return undef;
517  
518 # parse the parts, adding to any existing parts
519 my $part = @{$self->{'parts'}};
520 my $t; # block type
521  
522 my $fp; # file position (for debugging)
523 warn "fpos=" . ($fp = tell($io)) . "\n" if $self->{'debug'} > 2;
524  
525 while (_read($io, $b, 1))
526 {
527 my $p = $part; # used in debugging, below
528  
529 $t = ord($b);
530  
531 if ($t == 0x3b) # trailer
532 {
533 warn "reading trailer\n" if $self->{'debug'};
534 $self->{'trailer'} = $b;
535 }
536  
537 elsif ($t == 0x2c) # image descriptor
538 {
539 _read_image_descriptor($self, $io, $part, $b);
540 $part++; # start the next part
541 }
542  
543 elsif ($t == 0x21) # some kind of extension
544 {
545 _read_extension($self, $io, $part, $b);
546 }
547  
548 else
549 {
550 # fall-through
551 $@ = "invalid block label found [$t]";
552 warn "$@\n" if $self->{'debug'};
553 return undef;
554 }
555  
556 if ($self->{'debug'} > 2)
557 {
558 $_ = tell($io);
559 warn "fpos=$_ (+" . ($_ - $fp) . ") partlen=" .
560 length($self->{'parts'}[$p]||'') . "\n";
561 $fp = $_;
562 }
563 }
564  
565 return 1;
566  
567 }
568  
569 sub header
570 # Return the image header
571 {
572 return shift->{'header'};
573 }
574  
575 sub trailer
576 # Return the image trailer
577 {
578 return shift->{'trailer'};
579 }
580  
581 sub parts
582 # Return list of the image parts in array context, or number of parts in
583 # scalar context. (Does not include header or trailer).
584 {
585 return wantarray ? @{shift->{'parts'}} : scalar(@{shift->{'parts'}});
586 }
587  
588 sub part
589 # Return an image part
590 # - part == undef gives header
591 # - part > num_parts gives trailer
592 {
593 my ($self, $part) = @_;
594  
595 warn "returning part [" . (defined($part) ?
596 ($part > $#{$self->{'parts'}} ? 'trailer' : $part) : 'header') .
597 "]\n" if ($self->{'debug'} > 1);
598  
599 return $self->{'header'} unless defined($part);
600 return $self->{'trailer'} if ($part > $#{$self->{'parts'}});
601 return $self->{'parts'}->[$part];
602 }
603  
604 sub output
605 # Specify output filehandle.
606 {
607 my ($self, $io) = @_;
608  
609 $io = *STDOUT unless defined($io);
610 warn "output to $io\n" if ($self->{'debug'} > 1);
611 unless (_wrap($io, 'w'))
612 {
613 $@ ||= "could not wrap [$io]";
614 return undef;
615 }
616 warn "\t-> $io\n" if ($self->{'debug'} > 1);
617  
618 $self->{'output'} = $io;
619 }
620  
621 sub print_part
622 # print a part to given fh, or default (set via ::output()) if none supplied
623 {
624 my ($self, $part, $io) = @_;
625  
626 $io = defined($io) ? _wrap($io, 'w') : $self->{'output'};
627  
628 warn "printing part " . (defined $part ? $part : '-') . " to $io\n"
629 if $self->{'debug'} > 1;
630  
631 $io->print($self->{'parts'}->[$part]);
632 }
633  
634 sub deanimate
635 # print header, given part and trailer to given / default fh
636 # - print a random part for indices < 0
637 {
638 my ($self, $part, $io) = @_;
639  
640 $io = defined($io) ? _wrap($io, 'w') : $self->{'output'};
641  
642 $part ||= 0;
643 $part = int rand(@{$self->{'parts'}}) if $part < 0;
644  
645 $io->print($self->{'header'});
646 $io->print($self->{'parts'}->[$part]);
647 $io->print($self->{'trailer'});
648 }
649  
650 sub print_parts
651 # print zero or more parts to given / default fh
652 {
653 my ($self, $part, $io) = @_;
654  
655 $io = defined($io) ? _wrap($io, 'w') : $self->{'output'};
656 $part = @{$self->{'parts'}} unless defined $part;
657  
658 # where were we up to?
659 my $ppart = $self->{'_ppart'} || 0;
660 warn "printing parts $ppart - $part to $io\n" if ($self->{'debug'} > 1);
661 while ($ppart <= $part)
662 {
663 warn " $ppart (" . length($self->{'parts'}->[$ppart]) . ") bytes\n"
664 if ($self->{'debug'} > 2);
665 $io->print($self->{'parts'}->[$ppart++]);
666 }
667 $self->{'_ppart'} = $ppart;
668 }
669  
670 sub print_percent
671 {
672 my ($self, $p, $io) = @_;
673 $p = 1 if $p > 1;
674 $p = 0 if $p < 0;
675 $self->print_parts(int($p * $#{$self->{'parts'}} + 0.5), $io);
676 }
677  
678 sub print_header
679 {
680 my ($self, $io) = @_;
681 $io = defined($io) ? _wrap($io, 'w') : $self->{'output'};
682 warn "printing header to $io\n" if ($self->{'debug'} > 1);
683 $io->print($self->{'header'});
684 }
685  
686 sub print_trailer
687 {
688 my ($self, $io) = @_;
689 $io = defined($io) ? _wrap($io, 'w') : $self->{'output'};
690 warn "printing trailer to $io\n" if ($self->{'debug'} > 1);
691 $io->print($self->{'trailer'});
692 }
693  
694  
695 1; # return true, as require requires
696  
697 __END__