File Coverage

blib/lib/Image/ExifTool/Flash.pm
Criterion Covered Total %
statement 205 271 75.6
branch 101 190 53.1
condition 28 69 40.5
subroutine 9 9 100.0
pod 0 5 0.0
total 343 544 63.0


line stmt bran cond sub pod time code
1             #------------------------------------------------------------------------------
2             # File: Flash.pm
3             #
4             # Description: Read Shockwave Flash meta information
5             #
6             # Revisions: 05/16/2006 - P. Harvey Created
7             # 06/07/2007 - PH Added support for FLV (Flash Video) files
8             # 10/23/2008 - PH Added support for XMP in FLV and SWF
9             #
10             # References: 1) http://www.the-labs.com/MacromediaFlash/SWF-Spec/SWFfileformat.html
11             # 2) http://sswf.sourceforge.net/SWFalexref.html
12             # 3) http://osflash.org/flv/
13             # 4) http://www.irisa.fr/texmex/people/dufouil/ffmpegdoxy/flv_8h.html
14             # 5) http://www.adobe.com/devnet/xmp/pdfs/XMPSpecificationPart3.pdf (Oct 2008)
15             # 6) http://www.adobe.com/devnet/swf/pdf/swf_file_format_spec_v9.pdf
16             # 7) http://help.adobe.com/en_US/FlashMediaServer/3.5_Deving/WS5b3ccc516d4fbf351e63e3d11a0773d56e-7ff6.html
17             # 8) http://www.adobe.com/devnet/flv/pdf/video_file_format_spec_v10.pdf
18             #
19             # Notes: I'll add AMF3 support if someone sends me a FLV with AMF3 data
20             #------------------------------------------------------------------------------
21              
22             package Image::ExifTool::Flash;
23              
24 1     1   4585 use strict;
  1         2  
  1         35  
25 1     1   3 use vars qw($VERSION);
  1         2  
  1         36  
26 1     1   3 use Image::ExifTool qw(:DataAccess :Utils);
  1         2  
  1         175  
27 1     1   434 use Image::ExifTool::FLAC;
  1         2  
  1         2793  
28              
29             $VERSION = '1.13';
30              
31             sub ProcessMeta($$$;$);
32              
33             # Meta packets that we process
34             my %processMetaPacket = ( onMetaData => 1, onXMPData => 1 );
35              
36             # information extracted from SWF header
37             %Image::ExifTool::Flash::Main = (
38             GROUPS => { 2 => 'Video' },
39             VARS => { ALPHA_FIRST => 1 },
40             NOTES => q{
41             The information below is extracted from SWF (Shockwave Flash) files. Tags
42             with string ID's represent information extracted from the file header.
43             },
44             FlashVersion => { },
45             Compressed => { PrintConv => { 0 => 'False', 1 => 'True' } },
46             ImageWidth => { },
47             ImageHeight => { },
48             FrameRate => { },
49             FrameCount => { },
50             Duration => {
51             Notes => 'calculated from FrameRate and FrameCount',
52             PrintConv => 'ConvertDuration($val)',
53             },
54             69 => {
55             Name => 'FlashAttributes',
56             PrintConv => { BITMASK => {
57             0 => 'UseNetwork',
58             3 => 'ActionScript3',
59             4 => 'HasMetadata',
60             } },
61             },
62             77 => {
63             Name => 'XMP',
64             SubDirectory => { TagTable => 'Image::ExifTool::XMP::Main' },
65             },
66             );
67              
68             # packets in Flash Video files
69             %Image::ExifTool::Flash::FLV = (
70             NOTES => q{
71             Information is extracted from the following packets in FLV (Flash Video)
72             files.
73             },
74             0x08 => {
75             Name => 'Audio',
76             BitMask => 0x04,
77             SubDirectory => { TagTable => 'Image::ExifTool::Flash::Audio' },
78             },
79             0x09 => {
80             Name => 'Video',
81             BitMask => 0x01,
82             SubDirectory => { TagTable => 'Image::ExifTool::Flash::Video' },
83             },
84             0x12 => {
85             Name => 'Meta',
86             SubDirectory => { TagTable => 'Image::ExifTool::Flash::Meta' },
87             },
88             );
89              
90             # tags in Flash Video packet header
91             %Image::ExifTool::Flash::Audio = (
92             PROCESS_PROC => \&Image::ExifTool::FLAC::ProcessBitStream,
93             GROUPS => { 2 => 'Audio' },
94             NOTES => 'Information extracted from the Flash Audio header.',
95             'Bit0-3' => {
96             Name => 'AudioEncoding',
97             PrintConv => {
98             0 => 'PCM-BE (uncompressed)', # PCM-BE according to ref 4
99             1 => 'ADPCM',
100             2 => 'MP3',
101             3 => 'PCM-LE (uncompressed)', #4
102             4 => 'Nellymoser 16kHz Mono', #8
103             5 => 'Nellymoser 8kHz Mono',
104             6 => 'Nellymoser',
105             7 => 'G.711 A-law logarithmic PCM', #8
106             8 => 'G.711 mu-law logarithmic PCM', #8
107             # (9 is reserved, ref 8)
108             10 => 'AAC', #8
109             11 => 'Speex', #8
110             13 => 'MP3 8-Khz', #8
111             15 => 'Device-specific sound', #8
112             },
113             },
114             'Bit4-5' => {
115             Name => 'AudioSampleRate',
116             ValueConv => {
117             0 => 5512,
118             1 => 11025,
119             2 => 22050,
120             3 => 44100,
121             },
122             },
123             'Bit6' => {
124             Name => 'AudioBitsPerSample',
125             ValueConv => '8 * ($val + 1)',
126             },
127             'Bit7' => {
128             Name => 'AudioChannels',
129             ValueConv => '$val + 1',
130             PrintConv => {
131             1 => '1 (mono)',
132             2 => '2 (stereo)',
133             },
134             },
135             );
136              
137             # tags in Flash Video packet header
138             %Image::ExifTool::Flash::Video = (
139             PROCESS_PROC => \&Image::ExifTool::FLAC::ProcessBitStream,
140             GROUPS => { 2 => 'Video' },
141             NOTES => 'Information extracted from the Flash Video header.',
142             'Bit4-7' => {
143             Name => 'VideoEncoding',
144             PrintConv => {
145             1 => 'JPEG', #8
146             2 => 'Sorensen H.263',
147             3 => 'Screen Video',
148             4 => 'On2 VP6',
149             5 => 'On2 VP6 Alpha', #3
150             6 => 'Screen Video 2', #3
151             7 => 'H.264', #7 (called "AVC" by ref 8)
152             },
153             },
154             );
155              
156             # tags in Flash META packet (in ActionScript Message Format)
157             %Image::ExifTool::Flash::Meta = (
158             PROCESS_PROC => \&ProcessMeta,
159             GROUPS => { 2 => 'Video' },
160             NOTES => q{
161             Below are a few observed FLV Meta tags, but ExifTool will attempt to extract
162             information from any tag found.
163             },
164             'audiocodecid' => { Name => 'AudioCodecID', Groups => { 2 => 'Audio' } },
165             'audiodatarate' => {
166             Name => 'AudioBitrate',
167             Groups => { 2 => 'Audio' },
168             ValueConv => '$val * 1000',
169             PrintConv => 'ConvertBitrate($val)',
170             },
171             'audiodelay' => { Name => 'AudioDelay', Groups => { 2 => 'Audio' } },
172             'audiosamplerate'=>{ Name => 'AudioSampleRate', Groups => { 2 => 'Audio' } },
173             'audiosamplesize'=>{ Name => 'AudioSampleSize', Groups => { 2 => 'Audio' } },
174             'audiosize' => { Name => 'AudioSize', Groups => { 2 => 'Audio' } },
175             'bytelength' => 'ByteLength', # (youtube)
176             'canseekontime' => 'CanSeekOnTime', # (youtube)
177             'canSeekToEnd' => 'CanSeekToEnd',
178             'creationdate' => {
179             # (not an AMF date type in my sample)
180             Name => 'CreateDate',
181             Groups => { 2 => 'Time' },
182             ValueConv => '$val=~s/\s+$//; $val', # trim trailing whitespace
183             },
184             'createdby' => 'CreatedBy', #7
185             'cuePoints' => {
186             Name => 'CuePoint',
187             SubDirectory => { TagTable => 'Image::ExifTool::Flash::CuePoint' },
188             },
189             'datasize' => 'DataSize',
190             'duration' => {
191             Name => 'Duration',
192             PrintConv => 'ConvertDuration($val)',
193             },
194             'filesize' => 'FileSizeBytes',
195             'framerate' => {
196             Name => 'FrameRate',
197             PrintConv => 'int($val * 1000 + 0.5) / 1000',
198             },
199             'hasAudio' => { Name => 'HasAudio', Groups => { 2 => 'Audio' } },
200             'hasCuePoints' => 'HasCuePoints',
201             'hasKeyframes' => 'HasKeyFrames',
202             'hasMetadata' => 'HasMetadata',
203             'hasVideo' => 'HasVideo',
204             'height' => 'ImageHeight',
205             'httphostheader'=> 'HTTPHostHeader', # (youtube)
206             'keyframesTimes'=> 'KeyFramesTimes',
207             'keyframesFilepositions' => 'KeyFramePositions',
208             'lasttimestamp' => 'LastTimeStamp',
209             'lastkeyframetimestamp' => 'LastKeyFrameTime',
210             'metadatacreator'=>'MetadataCreator',
211             'metadatadate' => {
212             Name => 'MetadataDate',
213             Groups => { 2 => 'Time' },
214             PrintConv => '$self->ConvertDateTime($val)',
215             },
216             'purl' => 'URL', # (youtube) (what does P mean?)
217             'pmsg' => 'Message', # (youtube) (what does P mean?)
218             'sourcedata' => 'SourceData', # (youtube)
219             'starttime' => { # (youtube)
220             Name => 'StartTime',
221             PrintConv => 'ConvertDuration($val)',
222             },
223             'stereo' => { Name => 'Stereo', Groups => { 2 => 'Audio' } },
224             'totalduration' => { # (youtube)
225             Name => 'TotalDuration',
226             PrintConv => 'ConvertDuration($val)',
227             },
228             'totaldatarate' => { # (youtube)
229             Name => 'TotalDataRate',
230             ValueConv => '$val * 1000',
231             PrintConv => 'int($val + 0.5)',
232             },
233             'totalduration' => 'TotalDuration',
234             'videocodecid' => 'VideoCodecID',
235             'videodatarate' => {
236             Name => 'VideoBitrate',
237             ValueConv => '$val * 1000',
238             PrintConv => 'ConvertBitrate($val)',
239             },
240             'videosize' => 'VideoSize',
241             'width' => 'ImageWidth',
242             # tags in 'onXMPData' packets
243             'liveXML' => { #5
244             Name => 'XMP',
245             SubDirectory => { TagTable => 'Image::ExifTool::XMP::Main' },
246             },
247             );
248              
249             # tags in Flash META CuePoint structure
250             %Image::ExifTool::Flash::CuePoint = (
251             PROCESS_PROC => \&ProcessMeta,
252             GROUPS => { 2 => 'Video' },
253             NOTES => q{
254             These tag names are added to the CuePoint name to generate complete tag
255             names like "CuePoint0Name".
256             },
257             'name' => 'Name',
258             'type' => 'Type',
259             'time' => 'Time',
260             'parameters' => {
261             Name => 'Parameter',
262             SubDirectory => { TagTable => 'Image::ExifTool::Flash::Parameter' },
263             },
264             );
265              
266             # tags in Flash META CuePoint Parameter structure
267             %Image::ExifTool::Flash::Parameter = (
268             PROCESS_PROC => \&ProcessMeta,
269             GROUPS => { 2 => 'Video' },
270             NOTES => q{
271             There are no pre-defined parameter tags, but ExifTool will extract any
272             existing parameters, with tag names like "CuePoint0ParameterXxx".
273             },
274             );
275              
276             # name lookup for known AMF data types
277             my @amfType = qw(double boolean string object movieClip null undefined reference
278             mixedArray objectEnd array date longString unsupported recordSet
279             XML typedObject AMF3data);
280              
281             # test for AMF structure types (object, mixed array or typed object)
282             my %isStruct = ( 0x03 => 1, 0x08 => 1, 0x10 => 1 );
283              
284             #------------------------------------------------------------------------------
285             # Process Flash Video AMF Meta packet (ref 3)
286             # Inputs: 0) ExifTool object ref, 1) dirInfo ref, 2) tag table ref
287             # 3) Set to extract single type/value only
288             # Returns: 1 on success, (or type/value if extracting single value)
289             # Notes: Updates DataPos in dirInfo if extracting single value
290             sub ProcessMeta($$$;$)
291             {
292 57     57 0 71 my ($et, $dirInfo, $tagTablePtr, $single) = @_;
293 57         59 my $dataPt = $$dirInfo{DataPt};
294 57         64 my $dataPos = $$dirInfo{DataPos};
295 57   33     129 my $dirLen = $$dirInfo{DirLen} || length($$dataPt);
296 57   100     107 my $pos = $$dirInfo{Pos} || 0;
297 57         59 my ($type, $val, $rec);
298              
299 57 100       87 $et->VerboseDir('Meta') unless $single;
300              
301 57         67 Record: for ($rec=0; ; ++$rec) {
302 59 100       77 last if $pos >= $dirLen;
303 58         75 $type = ord(substr($$dataPt, $pos));
304 58         81 ++$pos;
305 58 100 100     146 if ($type == 0x00 or $type == 0x0b) { # double or date
    100 33        
    100 66        
    100 66        
    100 0        
    50          
    50          
    0          
306 28 50       42 last if $pos + 8 > $dirLen;
307 28         38 $val = GetDouble($dataPt, $pos);
308 28         30 $pos += 8;
309 28 100       35 if ($type == 0x0b) { # date
310 1         3 $val /= 1000; # convert to seconds
311             # get time zone
312 1 50       3 last if $pos + 2 > $dirLen;
313 1         3 my $tz = Get16s($dataPt, $pos);
314 1         2 $pos += 2;
315             # construct date/time string
316 1         3 $val = Image::ExifTool::ConvertUnixTime($val, 0, 6);
317             # add timezone
318 1 50       15 if ($tz < 0) {
319 1         2 $val .= '-';
320 1         2 $tz *= -1;
321             } else {
322 0         0 $val .= '+';
323             }
324 1         5 $val .= sprintf('%.2d:%.2d', int($tz/60), $tz%60);
325             }
326             } elsif ($type == 0x01) { # boolean
327 7 50       11 last if $pos + 1 > $dirLen;
328 7         15 $val = Get8u($dataPt, $pos);
329 7 50       24 $val = { 0 => 'No', 1 => 'Yes' }->{$val} if $val < 2;
330 7         11 ++$pos;
331             } elsif ($type == 0x02) { # string
332 10 50       18 last if $pos + 2 > $dirLen;
333 10         15 my $len = Get16u($dataPt, $pos);
334 10 50       17 last if $pos + 2 + $len > $dirLen;
335 10         15 $val = substr($$dataPt, $pos + 2, $len);
336 10         14 $pos += 2 + $len;
337             } elsif ($isStruct{$type}) { # object, mixed array or typed object
338 5         20 $et->VPrint(1, " + [$amfType[$type]]\n");
339 5         5 my $getName;
340 5         6 $val = ''; # dummy value
341 5 100       8 if ($type == 0x08) { # mixed array
    50          
342             # skip last array index for mixed array
343 4 50       6 last if $pos + 4 > $dirLen;
344 4         6 $pos += 4;
345             } elsif ($type == 0x10) { # typed object
346 0         0 $getName = 1;
347             }
348 5         5 for (;;) {
349             # get tag ID (or typed object name)
350 45 50       58 last Record if $pos + 2 > $dirLen;
351 45         67 my $len = Get16u($dataPt, $pos);
352 45 50       67 if ($pos + 2 + $len > $dirLen) {
353 0         0 $et->Warn("Truncated $amfType[$type] record");
354 0         0 last Record;
355             }
356 45         65 my $tag = substr($$dataPt, $pos + 2, $len);
357 45         46 $pos += 2 + $len;
358             # first string of a typed object is the object name
359 45 50       59 if ($getName) {
360 0         0 $et->VPrint(1," | (object name '${tag}')\n");
361 0         0 undef $getName;
362 0         0 next; # (ignore name for now)
363             }
364 45         38 my $subTablePtr = $tagTablePtr;
365 45         59 my $tagInfo = $$subTablePtr{$tag};
366             # switch to subdirectory table if necessary
367 45 100 100     89 if ($tagInfo and $$tagInfo{SubDirectory}) {
368 2         4 my $subTable = $tagInfo->{SubDirectory}->{TagTable};
369             # descend into Flash SubDirectory
370 2 50       7 if ($subTable =~ /^Image::ExifTool::Flash::/) {
371 2         3 $tag = $$tagInfo{Name}; # use our name for the tag
372 2         5 $subTablePtr = GetTagTable($subTable);
373             }
374             }
375             # get object value
376 45         46 my $valPos = $pos + 1;
377 45         66 $$dirInfo{Pos} = $pos;
378 45         48 my $structName = $$dirInfo{StructName};
379             # add structure name to start of tag name
380 45 100       71 $tag = $structName . ucfirst($tag) if defined $structName;
381 45         53 $$dirInfo{StructName} = $tag; # set new structure name
382 45         89 my ($t, $v) = ProcessMeta($et, $dirInfo, $subTablePtr, 1);
383 45         50 $$dirInfo{StructName} = $structName;# restore original structure name
384 45         47 $pos = $$dirInfo{Pos}; # update to new position in packet
385             # all done if this value contained tags
386 45 50 33     85 last Record unless defined $t and defined $v;
387 45 100       128 next if $isStruct{$t}; # already handled tags in sub-structures
388 43 100 100     72 next if ref($v) eq 'ARRAY' and not @$v; # ignore empty arrays
389 42 100       56 last if $t == 0x09; # (end of object)
390 37 100 66     94 if (not $$subTablePtr{$tag} and $tag =~ /^\w+$/) {
391 9         37 AddTagToTable($subTablePtr, $tag, { Name => ucfirst($tag) });
392 9         22 $et->VPrint(1, " | (adding $tag)\n");
393             }
394 37   33     97 $et->HandleTag($subTablePtr, $tag, $v,
395             DataPt => $dataPt,
396             DataPos => $dataPos,
397             Start => $valPos,
398             Size => $pos - $valPos,
399             Format => $amfType[$t] || sprintf('0x%x',$t),
400             );
401             }
402             # } elsif ($type == 0x04) { # movie clip (not supported)
403             } elsif ($type == 0x05 or $type == 0x06 or $type == 0x09 or $type == 0x0d) {
404             # null, undefined, dirLen of object, or unsupported
405 5         5 $val = '';
406             } elsif ($type == 0x07) { # reference
407 0 0       0 last if $pos + 2 > $dirLen;
408 0         0 $val = Get16u($dataPt, $pos);
409 0         0 $pos += 2;
410             } elsif ($type == 0x0a) { # array
411 3 50       6 last if $pos + 4 > $dirLen;
412 3         6 my $num = Get32u($dataPt, $pos);
413 3         5 $$dirInfo{Pos} = $pos + 4;
414 3         3 my ($i, @vals);
415             # add array index to compound tag name
416 3         4 my $structName = $$dirInfo{StructName};
417 3         6 for ($i=0; $i<$num; ++$i) {
418 10 50       18 $$dirInfo{StructName} = $structName . $i if defined $structName;
419 10         31 my ($t, $v) = ProcessMeta($et, $dirInfo, $tagTablePtr, 1);
420 10 50       18 last Record unless defined $v;
421             # save value unless contained in a sub-structure
422 10 100       24 push @vals, $v unless $isStruct{$t};
423             }
424 3         5 $$dirInfo{StructName} = $structName;
425 3         4 $pos = $$dirInfo{Pos};
426 3         5 $val = \@vals;
427             } elsif ($type == 0x0c or $type == 0x0f) { # long string or XML
428 0 0       0 last if $pos + 4 > $dirLen;
429 0         0 my $len = Get32u($dataPt, $pos);
430 0 0       0 last if $pos + 4 + $len > $dirLen;
431 0         0 $val = substr($$dataPt, $pos + 4, $len);
432 0         0 $pos += 4 + $len;
433             # } elsif ($type == 0x0e) { # record set (not supported)
434             # } elsif ($type == 0x11) { # AMF3 data (can't add support for this without a test sample)
435             } else {
436 0   0     0 my $t = $amfType[$type] || sprintf('type 0x%x',$type);
437 0         0 $et->Warn("AMF $t record not yet supported");
438 0         0 undef $type; # (so we don't print another warning)
439 0         0 last; # can't continue
440             }
441 58 100       89 last if $single; # all done if extracting single value
442 3 100       6 unless ($isStruct{$type}) {
443             # only process certain Meta packets
444 2 50 33     6 if ($type == 0x02 and not $rec) {
445 2 100       12 my $verb = $processMetaPacket{$val} ? 'processing' : 'ignoring';
446 2         8 $et->VPrint(0, " | ($verb $val information)\n");
447 2 100       5 last unless $processMetaPacket{$val};
448             } else {
449             # give verbose indication if we ignore a lone value
450 0   0     0 my $t = $amfType[$type] || sprintf('type 0x%x',$type);
451 0         0 $et->VPrint(1, " | (ignored lone $t value '${val}')\n");
452             }
453             }
454             }
455 57 50 33     83 if (not defined $val and defined $type) {
456 0         0 $et->Warn(sprintf("Truncated AMF record 0x%x",$type));
457             }
458 57 100       83 return 1 unless $single; # all done
459 55         61 $$dirInfo{Pos} = $pos; # update position
460 55         107 return($type,$val); # return single type/value pair
461             }
462              
463             #------------------------------------------------------------------------------
464             # Read information frame a Flash Video file
465             # Inputs: 0) ExifTool object reference, 1) Directory information reference
466             # Returns: 1 on success, 0 if this wasn't a valid Flash Video file
467             sub ProcessFLV($$)
468             {
469 1     1 0 4 my ($et, $dirInfo) = @_;
470 1         3 my $verbose = $et->Options('Verbose');
471 1         2 my $raf = $$dirInfo{RAF};
472 1         2 my $buff;
473              
474 1 50       3 $raf->Read($buff, 9) == 9 or return 0;
475 1 50       4 $buff =~ /^FLV\x01/ or return 0;
476 1         3 SetByteOrder('MM');
477 1         5 $et->SetFileType();
478 1         3 my ($flags, $offset) = unpack('x4CN', $buff);
479 1 50 0     3 $raf->Seek($offset-9, 1) or return 1 if $offset > 9;
480 1         2 $flags &= 0x05; # only look for audio/video
481 1         1 my $found = 0;
482 1         4 my $tagTablePtr = GetTagTable('Image::ExifTool::Flash::FLV');
483 1         1 for (;;) {
484 4 50       11 $raf->Read($buff, 15) == 15 or last;
485 4         8 my $len = unpack('x4N', $buff);
486 4         4 my $type = $len >> 24;
487 4         5 $len &= 0x00ffffff;
488 4         10 my $tagInfo = $et->GetTagInfo($tagTablePtr, $type);
489 4 50       5 if ($verbose > 1) {
490 0 0       0 my $name = $tagInfo ? $$tagInfo{Name} : "type $type";
491 0         0 $et->VPrint(1, "FLV $name packet, len $len\n");
492             }
493 4         7 undef $buff;
494 4 50 33     10 if ($tagInfo and $$tagInfo{SubDirectory}) {
495 4         5 my $mask = $$tagInfo{BitMask};
496 4 100       11 if ($mask) {
    50          
497             # handle audio or video packet
498 2 50       4 unless ($found & $mask) {
499 2         4 $found |= $mask;
500 2         3 $flags &= ~$mask;
501 2 50 33     7 if ($len>=1 and $raf->Read($buff, 1) == 1) {
502 2         3 $len -= 1;
503             } else {
504 0         0 $et->Warn("Bad $$tagInfo{Name} packet");
505 0         0 last;
506             }
507             }
508             } elsif ($raf->Read($buff, $len) == $len) {
509 2         4 $len = 0;
510             } else {
511 0         0 $et->Warn('Truncated Meta packet');
512 0         0 last;
513             }
514             }
515 4 50       8 if (defined $buff) {
516 4         9 $et->HandleTag($tagTablePtr, $type, undef,
517             DataPt => \$buff,
518             DataPos => $raf->Tell() - length($buff),
519             );
520             }
521 4 100       9 last unless $flags;
522 3 100 50     7 $raf->Seek($len, 1) or last if $len;
523             }
524 1         2 return 1;
525             }
526              
527             #------------------------------------------------------------------------------
528             # Found a Flash tag
529             # Inputs: 0) ExifTool object ref, 1) tag name, 2) tag value
530             sub FoundFlashTag($$$)
531             {
532 8     8 0 13 my ($et, $tag, $val) = @_;
533 8         18 $et->HandleTag(\%Image::ExifTool::Flash::Main, $tag, $val);
534             }
535              
536             #------------------------------------------------------------------------------
537             # Read data from possibly compressed file
538             # Inputs: 0) RAF reference, 1) data buffer, 2) bytes to read, 2) compressed flag
539             # Returns: number of bytes read (may be greater than requested bytes if compressed)
540             # - concatenates data to current buffer
541             # - updates compressed flag with reference to inflate object for future calls
542             # (or sets to error message and returns zero on error)
543             sub ReadCompressed($$$$)
544             {
545 3     3 0 6 my ($raf, $len, $inflate) = ($_[0], $_[2], $_[3]);
546 3         3 my $buff;
547 3 50       7 unless ($raf->Read($buff, $len)) {
548 0         0 $_[3] = 'Error reading file';
549 0         0 return 0;
550             }
551             # uncompress if necessary
552 3 50       4 if ($inflate) {
553 0 0       0 unless (ref $inflate) {
554 0 0       0 unless (eval { require Compress::Zlib }) {
  0         0  
555 0         0 $_[3] = 'Install Compress::Zlib to extract compressed information';
556 0         0 return 0;
557             }
558 0         0 $inflate = Compress::Zlib::inflateInit();
559 0 0       0 unless ($inflate) {
560 0         0 $_[3] = 'Error initializing inflate for Flash data';
561 0         0 return 0;
562             }
563 0         0 $_[3] = $inflate; # pass inflate object back to caller
564             }
565 0         0 my $tmp = $buff;
566 0         0 $buff = '';
567             # read 64 more bytes at a time and inflate until we get enough uncompressed data
568 0         0 for (;;) {
569 0         0 my ($dat, $stat) = $inflate->inflate($tmp);
570 0 0 0     0 if ($stat == Compress::Zlib::Z_STREAM_END() or
571             $stat == Compress::Zlib::Z_OK())
572             {
573 0         0 $buff .= $dat; # add inflated data to buffer
574 0 0 0     0 last if length $buff >= $len or $stat == Compress::Zlib::Z_STREAM_END();
575 0 0       0 $raf->Read($tmp,64) or last; # must read a bit more data
576             } else {
577 0         0 $buff = '';
578 0         0 last;
579             }
580             }
581 0 0       0 $_[3] = 'Error inflating compressed Flash data' unless length $buff;
582             }
583 3 50       8 $_[1] = defined $_[1] ? $_[1] . $buff : $buff;
584 3         8 return length $buff;
585             }
586              
587             #------------------------------------------------------------------------------
588             # Read information frame a Flash file
589             # Inputs: 0) ExifTool object reference, 1) Directory information reference
590             # Returns: 1 on success, 0 if this wasn't a valid Flash file
591             sub ProcessSWF($$)
592             {
593 1     1 0 2 my ($et, $dirInfo) = @_;
594 1         3 my $raf = $$dirInfo{RAF};
595 1         1 my ($buff, $hasMeta);
596              
597 1 50       4 $raf->Read($buff, 8) == 8 or return 0;
598 1 50       5 $buff =~ /^(F|C)WS([^\0])/ or return 0;
599 1 50       6 my ($compressed, $vers) = ($1 eq 'C' ? 1 : 0, ord($2));
600              
601 1         5 SetByteOrder('II');
602 1         5 $et->SetFileType();
603 1         9 GetTagTable('Image::ExifTool::Flash::Main'); # make sure table is initialized
604              
605 1         4 FoundFlashTag($et, FlashVersion => $vers);
606 1         3 FoundFlashTag($et, Compressed => $compressed);
607              
608             # read the next 64 bytes of the file (and inflate if necessary)
609 1         2 $buff = '';
610 1 50       3 unless (ReadCompressed($raf, $buff, 64, $compressed)) {
611 0 0       0 $et->Warn($compressed) if $compressed;
612 0         0 return 1;
613             }
614              
615             # unpack elements of bit-packed Flash Rect structure
616 1         3 my $nBits = unpack('C', $buff) >> 3; # bits in x1,x2,y1,y2 elements
617 1         2 my $totBits = 5 + $nBits * 4; # total bits in Rect structure
618 1         3 my $nBytes = int(($totBits + 7) / 8); # byte length of Rect structure
619 1 50       3 if (length $buff < $nBytes + 4) {
620 0         0 $et->Warn('Truncated Flash file');
621 0         0 return 1;
622             }
623 1         4 my $bits = unpack("B$totBits", $buff);
624             # isolate Rect elements and convert from ASCII bit strings to integers
625 1         5 my @vals = unpack('x5' . "a$nBits" x 4, $bits);
626             # (do conversion the hard way because oct("0b$val") requires Perl 5.6)
627 1         2 map { $_ = unpack('N', pack('B32', '0' x (32 - length $_) . $_)) } @vals;
  4         12  
628              
629             # calculate and store ImageWidth/Height
630 1         3 FoundFlashTag($et, ImageWidth => ($vals[1] - $vals[0]) / 20);
631 1         4 FoundFlashTag($et, ImageHeight => ($vals[3] - $vals[2]) / 20);
632              
633             # get frame rate and count
634 1         4 @vals = unpack("x${nBytes}v2", $buff);
635 1         3 FoundFlashTag($et, FrameRate => $vals[0] / 256);
636 1         3 FoundFlashTag($et, FrameCount => $vals[1]);
637 1 50       3 FoundFlashTag($et, Duration => $vals[1] * 256 / $vals[0]) if $vals[0];
638              
639             # scan through the tags to find FlashAttributes and XMP
640 1         2 $buff = substr($buff, $nBytes + 4);
641 1         13 for (;;) {
642 1         2 my $buffLen = length $buff;
643 1 50       2 last if $buffLen < 2;
644 1         4 my $code = Get16u(\$buff, 0);
645 1         1 my $pos = 2;
646 1         2 my $tag = $code >> 6;
647 1         2 my $size = $code & 0x3f;
648 1         7 $et->VPrint(1, "SWF tag $tag ($size bytes):\n");
649 1 50 33     5 last unless $tag == 69 or $tag == 77 or $hasMeta;
      33        
650             # read enough to get a complete short record
651 1 50       3 if ($pos + $size > $buffLen) {
652             # (read 2 extra bytes if available to get next tag word)
653 1 50       2 unless (ReadCompressed($raf, $buff, $size + 2, $compressed)) {
654 0 0       0 $et->Warn($compressed) if $compressed;
655 0         0 return 1;
656             }
657 1         2 $buffLen = length $buff;
658 1 50       3 last if $pos + $size > $buffLen;
659             }
660             # read extended record if necessary
661 1 50       2 if ($size == 0x3f) {
662 1 50       2 last if $pos + 4 > $buffLen;
663 1         5 $size = Get32u(\$buff, $pos);
664 1         1 $pos += 4;
665 1 50       8 last if $size > 1000000; # don't read anything huge
666 1 50       2 if ($pos + $size > $buffLen) {
667 1 50       2 unless (ReadCompressed($raf, $buff, $size + 2, $compressed)) {
668 0 0       0 $et->Warn($compressed) if $compressed;
669 0         0 return 1;
670             }
671 1         2 $buffLen = length $buff;
672 1 50       3 last if $pos + $size > $buffLen;
673             }
674 1         4 $et->VPrint(1, " [extended size $size bytes]\n");
675             }
676 1 50       5 if ($tag == 69) { # FlashAttributes
    50          
677 0 0       0 last unless $size;
678 0         0 my $flags = Get8u(\$buff, $pos);
679 0         0 FoundFlashTag($et, $tag => $flags);
680 0 0       0 last unless $flags & 0x10; # only continue if we have metadata (XMP)
681 0         0 $hasMeta = 1;
682             } elsif ($tag == 77) { # Metadata
683 1         3 my $val = substr($buff, $pos, $size);
684 1         2 FoundFlashTag($et, $tag => $val);
685 1         2 last;
686             }
687 0 0       0 last if $pos + 2 > $buffLen;
688 0         0 $buff = substr($buff, $pos); # remove everything before the next tag
689             }
690 1         4 return 1;
691             }
692              
693             1; # end
694              
695             __END__