Merge to trunk everything in img_metadata branch.
[lhc/web/wiklou.git] / includes / media / GIFMetadataExtractor.php
1 <?php
2 /**
3 * GIF frame counter.
4 *
5 * Originally written in Perl by Steve Sanbeg.
6 * Ported to PHP by Andrew Garrett
7 * Deliberately not using MWExceptions to avoid external dependencies, encouraging
8 * redistribution.
9 *
10 * @file
11 * @ingroup Media
12 */
13
14 /**
15 * GIF frame counter.
16 *
17 * @ingroup Media
18 */
19 class GIFMetadataExtractor {
20 static $gif_frame_sep;
21 static $gif_extension_sep;
22 static $gif_term;
23
24 const VERSION = 1;
25
26 // Each sub-block is less than or equal to 255 bytes.
27 // Most of the time its 255 bytes, except for in XMP
28 // blocks, where it's usually between 32-127 bytes each.
29 const MAX_SUBBLOCKS = 262144; // 5mb divided by 20.
30
31 static function getMetadata( $filename ) {
32 self::$gif_frame_sep = pack( "C", ord("," ) );
33 self::$gif_extension_sep = pack( "C", ord("!" ) );
34 self::$gif_term = pack( "C", ord(";" ) );
35
36 $frameCount = 0;
37 $duration = 0.0;
38 $isLooped = false;
39 $xmp = "";
40 $comment = array();
41
42 if ( !$filename ) {
43 throw new Exception( "No file name specified" );
44 } elseif ( !file_exists( $filename ) || is_dir( $filename ) ) {
45 throw new Exception( "File $filename does not exist" );
46 }
47
48 $fh = fopen( $filename, 'r' );
49
50 if ( !$fh ) {
51 throw new Exception( "Unable to open file $filename" );
52 }
53
54 // Check for the GIF header
55 $buf = fread( $fh, 6 );
56 if ( !($buf == 'GIF87a' || $buf == 'GIF89a') ) {
57 throw new Exception( "Not a valid GIF file; header: $buf" );
58 }
59
60 // Skip over width and height.
61 fread( $fh, 4 );
62
63 // Read BPP
64 $buf = fread( $fh, 1 );
65 $bpp = self::decodeBPP( $buf );
66
67 // Skip over background and aspect ratio
68 fread( $fh, 2 );
69
70 // Skip over the GCT
71 self::readGCT( $fh, $bpp );
72
73 while( !feof( $fh ) ) {
74 $buf = fread( $fh, 1 );
75
76 if ($buf == self::$gif_frame_sep) {
77 // Found a frame
78 $frameCount++;
79
80 ## Skip bounding box
81 fread( $fh, 8 );
82
83 ## Read BPP
84 $buf = fread( $fh, 1 );
85 $bpp = self::decodeBPP( $buf );
86
87 ## Read GCT
88 self::readGCT( $fh, $bpp );
89 fread( $fh, 1 );
90 self::skipBlock( $fh );
91 } elseif ( $buf == self::$gif_extension_sep ) {
92 $buf = fread( $fh, 1 );
93 $extension_code = unpack( 'C', $buf );
94 $extension_code = $extension_code[1];
95
96 if ($extension_code == 0xF9) {
97 // Graphics Control Extension.
98 fread( $fh, 1 ); // Block size
99
100 fread( $fh, 1 ); // Transparency, disposal method, user input
101
102 $buf = fread( $fh, 2 ); // Delay, in hundredths of seconds.
103 $delay = unpack( 'v', $buf );
104 $delay = $delay[1];
105 $duration += $delay * 0.01;
106
107 fread( $fh, 1 ); // Transparent colour index
108
109 $term = fread( $fh, 1 ); // Should be a terminator
110 $term = unpack( 'C', $term );
111 $term = $term[1];
112 if ($term != 0 ) {
113 throw new Exception( "Malformed Graphics Control Extension block" );
114 }
115 } elseif ($extension_code == 0xFE) {
116 // Comment block(s).
117 $data = '';
118
119 $data = self::readBlock( $fh );
120 if ( $data === "" ) {
121 throw new Exception( 'Read error, zero-length comment block' );
122 }
123
124 // The standard says this should be ASCII, however its unclear if
125 // thats true in practise. Check to see if its valid utf-8, if so
126 // assume its that, otherwise assume its iso-8859-1
127 $dataCopy = $data;
128 // quickIsNFCVerify has the side effect of replacing any invalid characters
129 UtfNormal::quickIsNFCVerify( $dataCopy );
130
131 if ( $dataCopy !== $data ) {
132 wfSuppressWarnings();
133 $data = iconv( 'ISO-8859-1', 'UTF-8', $data );
134 wfRestoreWarnings();
135 }
136
137 $commentCount = count( $comment );
138 if ( $commentCount === 0
139 || $comment[$commentCount-1] !== $data )
140 {
141 // Some applications repeat the same comment on each
142 // frame of an animated GIF image, so if this comment
143 // is identical to the last, only extract once.
144 $comment[] = $data;
145 }
146 } elseif ($extension_code == 0xFF) {
147 // Application extension (Netscape info about the animated gif)
148 // or XMP (or theoretically any other type of extension block)
149 $blockLength = fread( $fh, 1 );
150 $blockLength = unpack( 'C', $blockLength );
151 $blockLength = $blockLength[1];
152 $data = fread( $fh, $blockLength );
153
154 if ($blockLength != 11 ) {
155 wfDebug( __METHOD__ . ' GIF application block with wrong length' );
156 fseek( $fh, -($blockLength + 1), SEEK_CUR );
157 self::skipBlock( $fh );
158 continue;
159 }
160
161 // NETSCAPE2.0 (application name for animated gif)
162 if ( $data == 'NETSCAPE2.0' ) {
163
164 $data = fread( $fh, 2 ); // Block length and introduction, should be 03 01
165
166 if ($data != "\x03\x01") {
167 throw new Exception( "Expected \x03\x01, got $data" );
168 }
169
170 // Unsigned little-endian integer, loop count or zero for "forever"
171 $loopData = fread( $fh, 2 );
172 $loopData = unpack( 'v', $loopData );
173 $loopCount = $loopData[1];
174
175 if ($loopCount != 1) {
176 $isLooped = true;
177 }
178
179 // Read out terminator byte
180 fread( $fh, 1 );
181 } elseif ( $data == 'XMP DataXMP' ) {
182 // application name for XMP data.
183 // see pg 18 of XMP spec part 3.
184
185 $xmp = self::readBlock( $fh, true );
186
187 if ( substr( $xmp, -257, 3 ) !== "\x01\xFF\xFE"
188 || substr( $xmp, -4 ) !== "\x03\x02\x01\x00" )
189 {
190 // this is just a sanity check.
191 throw new Exception( "XMP does not have magic trailer!" );
192 }
193
194 // strip out trailer.
195 $xmp = substr( $xmp, 0, -257 );
196
197 } else {
198 // unrecognized extension block
199 fseek( $fh, -($blockLength + 1), SEEK_CUR );
200 self::skipBlock( $fh );
201 continue;
202 }
203 } else {
204 self::skipBlock( $fh );
205 }
206 } elseif ( $buf == self::$gif_term ) {
207 break;
208 } else {
209 $byte = unpack( 'C', $buf );
210 $byte = $byte[1];
211 throw new Exception( "At position: ".ftell($fh). ", Unknown byte ".$byte );
212 }
213 }
214
215 return array(
216 'frameCount' => $frameCount,
217 'looped' => $isLooped,
218 'duration' => $duration,
219 'xmp' => $xmp,
220 'comment' => $comment,
221 );
222 }
223
224 static function readGCT( $fh, $bpp ) {
225 if ( $bpp > 0 ) {
226 for( $i=1; $i<=pow( 2, $bpp ); ++$i ) {
227 fread( $fh, 3 );
228 }
229 }
230 }
231
232 static function decodeBPP( $data ) {
233 $buf = unpack( 'C', $data );
234 $buf = $buf[1];
235 $bpp = ( $buf & 7 ) + 1;
236 $buf >>= 7;
237
238 $have_map = $buf & 1;
239
240 return $have_map ? $bpp : 0;
241 }
242
243 static function skipBlock( $fh ) {
244 while ( !feof( $fh ) ) {
245 $buf = fread( $fh, 1 );
246 $block_len = unpack( 'C', $buf );
247 $block_len = $block_len[1];
248 if ($block_len == 0) {
249 return;
250 }
251 fread( $fh, $block_len );
252 }
253 }
254 /**
255 * Read a block. In the GIF format, a block is made up of
256 * several sub-blocks. Each sub block starts with one byte
257 * saying how long the sub-block is, followed by the sub-block.
258 * The entire block is terminated by a sub-block of length
259 * 0.
260 * @param $fh FileHandle
261 * @param $includeLengths Boolean Include the length bytes of the
262 * sub-blocks in the returned value. Normally this is false,
263 * except XMP is weird and does a hack where you need to keep
264 * these length bytes.
265 * @return The data.
266 */
267 static function readBlock( $fh, $includeLengths = false ) {
268 $data = '';
269 $subLength = fread( $fh, 1 );
270 $blocks = 0;
271
272 while( $subLength !== "\0" ) {
273 $blocks++;
274 if ( $blocks > self::MAX_SUBBLOCKS ) {
275 throw new Exception( "MAX_SUBBLOCKS exceeded (over $blocks sub-blocks)" );
276 }
277 if ( feof( $fh ) ) {
278 throw new Exception( "Read error: Unexpected EOF." );
279 }
280 if ( $includeLengths ) {
281 $data .= $subLength;
282 }
283
284 $data .= fread( $fh, ord( $subLength ) );
285 $subLength = fread( $fh, 1 );
286 }
287 return $data;
288 }
289
290 }