aboutsummaryrefslogtreecommitdiffstats
path: root/includes/media/WebPHandler.php
blob: c6e19c739da4839e41a1129c037b58c9ee3322f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<?php
/**
 * Handler for Google's WebP format <https://developers.google.com/speed/webp/>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Media
 */

use MediaWiki\FileRepo\File\File;
use MediaWiki\Logger\LoggerFactory;
use MediaWiki\MediaWikiServices;
use Wikimedia\XMPReader\Reader as XMPReader;

/**
 * Handler for Google's WebP format <https://developers.google.com/speed/webp/>
 *
 * @ingroup Media
 */
class WebPHandler extends BitmapHandler {
	/**
	 * Value to store in img_metadata if there was an error extracting metadata
	 */
	private const BROKEN_FILE = '0';
	/**
	 * Minimum chunk header size to be able to read all header types
	 */
	private const MINIMUM_CHUNK_HEADER_LENGTH = 18;
	/**
	 * Max size of metadata chunk to extract
	 */
	private const MAX_METADATA_CHUNK_SIZE = 1024 * 1024 * 2;
	/**
	 * Version of the metadata stored in db records
	 */
	private const _MW_WEBP_VERSION = 2;

	private const VP8X_ICC = 32;
	private const VP8X_ALPHA = 16;
	private const VP8X_EXIF = 8;
	private const VP8X_XMP = 4;
	private const VP8X_ANIM = 2;

	public function getSizeAndMetadata( $state, $filename ) {
		$parsedWebPData = self::extractMetadata( $filename );
		if ( !$parsedWebPData ) {
			return [ 'metadata' => [ '_error' => self::BROKEN_FILE ] ];
		}

		$parsedWebPData['metadata']['_MW_WEBP_VERSION'] = self::_MW_WEBP_VERSION;
		$info = [
			'width' => $parsedWebPData['width'],
			'height' => $parsedWebPData['height'],
			'metadata' => $parsedWebPData
		];
		return $info;
	}

	public function getMetadataType( $image ) {
		return 'parsed-webp';
	}

	public function isFileMetadataValid( $image ) {
		$data = $image->getMetadataArray();
		if ( $data === [ '_error' => self::BROKEN_FILE ] ) {
				// Do not repetitivly regenerate metadata on broken file.
				return self::METADATA_GOOD;
		}

		if ( !$data || !isset( $data['_error'] ) ) {
				wfDebug( __METHOD__ . " invalid WebP metadata" );

				return self::METADATA_BAD;
		}

		if ( !isset( $data['metadata']['_MW_WEBP_VERSION'] )
				|| $data['metadata']['_MW_WEBP_VERSION'] != self::_MW_WEBP_VERSION
		) {
				wfDebug( __METHOD__ . " old but compatible WebP metadata" );

				return self::METADATA_COMPATIBLE;
		}
		return self::METADATA_GOOD;
	}

	/**
	 * Extracts the image size and WebP type from a file
	 *
	 * @param string $filename
	 * @return array|false Header data array with entries 'compression', 'width' and 'height',
	 * where 'compression' can be 'lossy', 'lossless', 'animated' or 'unknown'. False if
	 * file is not a valid WebP file.
	 */
	public static function extractMetadata( $filename ) {
		wfDebugLog( 'WebP', __METHOD__ . ": Extracting metadata from $filename" );

		$info = RiffExtractor::findChunksFromFile( $filename, 100 );
		if ( $info === false ) {
			wfDebugLog( 'WebP', __METHOD__ . ": Not a valid RIFF file" );
			return false;
		}

		if ( $info['fourCC'] !== 'WEBP' ) {
			wfDebugLog( 'WebP', __METHOD__ . ': FourCC was not WEBP: ' .
				bin2hex( $info['fourCC'] ) );
			return false;
		}
		$metadata = self::extractMetadataFromChunks( $info['chunks'], $filename );
		if ( !$metadata ) {
			wfDebugLog( 'WebP', __METHOD__ . ": No VP8 chunks found" );
			return false;
		}

		return $metadata;
	}

	/**
	 * Extracts the image size and WebP type from a file based on the chunk list
	 * @param array[] $chunks Chunks as extracted by RiffExtractor
	 * @param string $filename
	 * @return array Header data array with entries 'compression', 'width' and 'height', where
	 * 'compression' can be 'lossy', 'lossless', 'animated' or 'unknown'
	 */
	public static function extractMetadataFromChunks( $chunks, $filename ) {
		$vp8Info = [];
		$exifData = null;
		$xmpData = null;

		foreach ( $chunks as $chunk ) {
			// Note, spec says it should be 'XMP ' but some real life files use "XMP\0"
			if ( !in_array( $chunk['fourCC'], [ 'VP8 ', 'VP8L', 'VP8X', 'EXIF', 'XMP ', "XMP\0" ] ) ) {
				// Not a chunk containing interesting metadata
				continue;
			}

			$chunkHeader = file_get_contents( $filename, false, null,
				$chunk['start'], self::MINIMUM_CHUNK_HEADER_LENGTH );
			wfDebugLog( 'WebP', __METHOD__ . ": {$chunk['fourCC']}" );

			switch ( $chunk['fourCC'] ) {
				case 'VP8 ':
					$vp8Info = array_merge( $vp8Info,
						self::decodeLossyChunkHeader( $chunkHeader ) );
					break;
				case 'VP8L':
					$vp8Info = array_merge( $vp8Info,
						self::decodeLosslessChunkHeader( $chunkHeader ) );
					break;
				case 'VP8X':
					$vp8Info = array_merge( $vp8Info,
						self::decodeExtendedChunkHeader( $chunkHeader ) );
					// Continue looking for other chunks to improve the metadata
					break;
				case 'EXIF':
					// Spec says ignore all but first one
					$exifData ??= self::extractChunk( $chunk, $filename );
					break;
				case 'XMP ':
				case "XMP\0":
					$xmpData ??= self::extractChunk( $chunk, $filename );
					break;
			}
		}
		$vp8Info = array_merge( $vp8Info,
			self::decodeMediaMetadata( $exifData, $xmpData, $filename ) );
		return $vp8Info;
	}

	/**
	 * Decode metadata about the file (XMP & Exif).
	 *
	 * @param string|null $exifData Binary exif data from file
	 * @param string|null $xmpData XMP data from file
	 * @param string|null $filename (Used for logging only)
	 * @return array
	 */
	private static function decodeMediaMetadata( $exifData, $xmpData, $filename ) {
		if ( $exifData === null && $xmpData === null ) {
			// Nothing to do
			return [];
		}
		$bitmapMetadataHandler = new BitmapMetadataHandler;

		if ( $xmpData && XMPReader::isSupported() ) {
			$xmpReader = new XMPReader( LoggerFactory::getInstance( 'XMP' ), $filename );
			$xmpReader->parse( $xmpData );
			$res = $xmpReader->getResults();
			foreach ( $res as $type => $array ) {
				$bitmapMetadataHandler->addMetadata( $array, $type );
			}
		}

		if ( $exifData ) {
			// The Exif section of a webp file is basically a tiff file without an image.
			// Some files start with an Exif\0\0. This is wrong according to standard and
			// will prevent us from reading file, so remove for compatibility.
			if ( substr( $exifData, 0, 6 ) === "Exif\x00\x00" ) {
				$exifData = substr( $exifData, 6 );
			}
			$tmpFile = MediaWikiServices::getInstance()->
				getTempFSFileFactory()->
				newTempFSFile( 'webp-exif_', 'tiff' );

			$exifDataFile = $tmpFile->getPath();
			file_put_contents( $exifDataFile, $exifData );
			$byteOrder = BitmapMetadataHandler::getTiffByteOrder( $exifDataFile );
			$bitmapMetadataHandler->getExif( $exifDataFile, $byteOrder );
		}
		return [ 'media-metadata' => $bitmapMetadataHandler->getMetadataArray() ];
	}

	/**
	 * @param array $chunk Information about chunk
	 * @param string $filename
	 * @return null|string Contents of chunk (excluding fourcc, size and padding)
	 */
	private static function extractChunk( $chunk, $filename ) {
		if ( $chunk['size'] > self::MAX_METADATA_CHUNK_SIZE || $chunk['size'] < 1 ) {
			return null;
		}

		// Skip first 8 bytes as that is the fourCC header followed by size of chunk.
		return file_get_contents( $filename, false, null, $chunk['start'] + 8, $chunk['size'] );
	}

	/**
	 * Decodes a lossy chunk header
	 * @param string $header First few bytes of the header, expected to be at least 18 bytes long
	 * @return bool|array See WebPHandler::decodeHeader
	 */
	protected static function decodeLossyChunkHeader( $header ) {
		// Bytes 0-3 are 'VP8 '
		// Bytes 4-7 are the VP8 stream size
		// Bytes 8-10 are the frame tag
		// Bytes 11-13 are 0x9D 0x01 0x2A called the sync code
		$syncCode = substr( $header, 11, 3 );
		if ( $syncCode !== "\x9D\x01\x2A" ) {
			wfDebugLog( 'WebP', __METHOD__ . ': Invalid sync code: ' .
				bin2hex( $syncCode ) );
			return [];
		}
		// Bytes 14-17 are image size
		$imageSize = unpack( 'v2', substr( $header, 14, 4 ) );
		// Image sizes are 14 bit, 2 MSB are scaling parameters which are ignored here
		return [
			'compression' => 'lossy',
			'width' => $imageSize[1] & 0x3FFF,
			'height' => $imageSize[2] & 0x3FFF
		];
	}

	/**
	 * Decodes a lossless chunk header
	 * @param string $header First few bytes of the header, expected to be at least 13 bytes long
	 * @return bool|array See WebPHandler::decodeHeader
	 */
	public static function decodeLosslessChunkHeader( $header ) {
		// Bytes 0-3 are 'VP8L'
		// Bytes 4-7 are chunk stream size
		// Byte 8 is 0x2F called the signature
		if ( $header[8] !== "\x2F" ) {
			wfDebugLog( 'WebP', __METHOD__ . ': Invalid signature: ' .
				bin2hex( $header[8] ) );
			return [];
		}
		// Bytes 9-12 contain the image size
		// Bits 0-13 are width-1; bits 15-27 are height-1
		$imageSize = unpack( 'C4', substr( $header, 9, 4 ) );
		return [
				'compression' => 'lossless',
				'width' => ( $imageSize[1] | ( ( $imageSize[2] & 0x3F ) << 8 ) ) + 1,
				'height' => ( ( ( $imageSize[2] & 0xC0 ) >> 6 ) |
						( $imageSize[3] << 2 ) | ( ( $imageSize[4] & 0x03 ) << 10 ) ) + 1
		];
	}

	/**
	 * Decodes an extended chunk header
	 * @param string $header First few bytes of the header, expected to be at least 18 bytes long
	 * @return bool|array See WebPHandler::decodeHeader
	 */
	public static function decodeExtendedChunkHeader( $header ) {
		// Bytes 0-3 are 'VP8X'
		// Byte 4-7 are chunk length
		// Byte 8-11 are a flag bytes
		$flags = unpack( 'c', substr( $header, 8, 1 ) );

		// Byte 12-17 are image size (24 bits)
		$width = unpack( 'V', substr( $header, 12, 3 ) . "\x00" );
		$height = unpack( 'V', substr( $header, 15, 3 ) . "\x00" );

		return [
			'compression' => 'unknown',
			'animated' => ( $flags[1] & self::VP8X_ANIM ) === self::VP8X_ANIM,
			'transparency' => ( $flags[1] & self::VP8X_ALPHA ) === self::VP8X_ALPHA,
			'width' => ( $width[1] & 0xFFFFFF ) + 1,
			'height' => ( $height[1] & 0xFFFFFF ) + 1
		];
	}

	/**
	 * @param File $file
	 * @return bool True, not all browsers support WebP
	 */
	public function mustRender( $file ) {
		return true;
	}

	/**
	 * @param File $file
	 * @return bool False if we are unable to render this image
	 */
	public function canRender( $file ) {
		if ( $this->isAnimatedImage( $file ) ) {
			return false;
		}
		return true;
	}

	/**
	 * @param File $image
	 * @return bool
	 */
	public function isAnimatedImage( $image ) {
		$metadata = $image->getMetadataArray();
		if ( isset( $metadata['animated'] ) && $metadata['animated'] === true ) {
			return true;
		}

		return false;
	}

	public function canAnimateThumbnail( $file ) {
		return false;
	}

	/**
	 * Render files as PNG
	 *
	 * @param string $ext
	 * @param string $mime
	 * @param array|null $params
	 * @return array
	 */
	public function getThumbType( $ext, $mime, $params = null ) {
		return [ 'png', 'image/png' ];
	}

	protected function hasGDSupport() {
		return function_exists( 'gd_info' ) && ( gd_info()['WebP Support'] ?? false );
	}

	public function getCommonMetaArray( File $image ) {
		$meta = $image->getMetadataArray();
		return $meta['media-metadata'] ?? [];
	}

	public function formatMetadata( $image, $context = false ) {
		$meta = $this->getCommonMetaArray( $image );
		if ( !$meta ) {
			return false;
		}

		return $this->formatMetadataHelper( $meta, $context );
	}
}