Flash.pm 27 KB

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