Remove some unreachable code (usually returns after throwing exceptions)
[lhc/web/wiklou.git] / includes / media / PNGMetadataExtractor.php
1 <?php
2 /**
3 * PNG frame counter.
4 * Slightly derived from GIFMetadataExtractor.php
5 * Deliberately not using MWExceptions to avoid external dependencies, encouraging
6 * redistribution.
7 *
8 * @file
9 * @ingroup Media
10 */
11
12 /**
13 * PNG frame counter.
14 *
15 * @ingroup Media
16 */
17 class PNGMetadataExtractor {
18 static $png_sig;
19 static $CRC_size;
20
21 static function getMetadata( $filename ) {
22 self::$png_sig = pack( "C8", 137, 80, 78, 71, 13, 10, 26, 10 );
23 self::$CRC_size = 4;
24
25 $frameCount = 0;
26 $loopCount = 1;
27 $duration = 0.0;
28
29 if (!$filename)
30 throw new Exception( __METHOD__ . ": No file name specified" );
31 elseif ( !file_exists($filename) || is_dir($filename) )
32 throw new Exception( __METHOD__ . ": File $filename does not exist" );
33
34 $fh = fopen( $filename, 'r' );
35
36 if (!$fh)
37 throw new Exception( __METHOD__ . ": Unable to open file $filename" );
38
39 // Check for the PNG header
40 $buf = fread( $fh, 8 );
41 if ( !($buf == self::$png_sig) ) {
42 throw new Exception( __METHOD__ . ": Not a valid PNG file; header: $buf" );
43 }
44
45 // Read chunks
46 while( !feof( $fh ) ) {
47 $buf = fread( $fh, 4 );
48 if( !$buf ) {
49 throw new Exception( __METHOD__ . ": Read error" );
50 }
51 $chunk_size = unpack( "N", $buf);
52 $chunk_size = $chunk_size[1];
53
54 $chunk_type = fread( $fh, 4 );
55 if( !$chunk_type ) {
56 throw new Exception( __METHOD__ . ": Read error" );
57 }
58
59 if ( $chunk_type == "acTL" ) {
60 $buf = fread( $fh, $chunk_size );
61 if( !$buf ) {
62 throw new Exception( __METHOD__ . ": Read error" );
63 }
64
65 $actl = unpack( "Nframes/Nplays", $buf );
66 $frameCount = $actl['frames'];
67 $loopCount = $actl['plays'];
68 } elseif ( $chunk_type == "fcTL" ) {
69 $buf = fread( $fh, $chunk_size );
70 if( !$buf ) {
71 throw new Exception( __METHOD__ . ": Read error" );
72 }
73 $buf = substr( $buf, 20 );
74
75 $fctldur = unpack( "ndelay_num/ndelay_den", $buf );
76 if( $fctldur['delay_den'] == 0 ) $fctldur['delay_den'] = 100;
77 if( $fctldur['delay_num'] ) {
78 $duration += $fctldur['delay_num'] / $fctldur['delay_den'];
79 }
80 } elseif ( ( $chunk_type == "IDAT" || $chunk_type == "IEND" ) && $frameCount == 0 ) {
81 // Not a valid animated image. No point in continuing.
82 break;
83 } elseif ( $chunk_type == "IEND" ) {
84 break;
85 } else {
86 fseek( $fh, $chunk_size, SEEK_CUR );
87 }
88 fseek( $fh, self::$CRC_size, SEEK_CUR );
89 }
90 fclose( $fh );
91
92 if( $loopCount > 1 ) {
93 $duration *= $loopCount;
94 }
95
96 return array(
97 'frameCount' => $frameCount,
98 'loopCount' => $loopCount,
99 'duration' => $duration
100 );
101
102 }
103 }