MediaWiki  1.28.1
WebP.php
Go to the documentation of this file.
1 <?php
29 class WebPHandler extends BitmapHandler {
30  const BROKEN_FILE = '0'; // value to store in img_metadata if error extracting metadata.
34  const MINIMUM_CHUNK_HEADER_LENGTH = 18;
38  const _MW_WEBP_VERSION = 1;
39 
40  const VP8X_ICC = 32;
41  const VP8X_ALPHA = 16;
42  const VP8X_EXIF = 8;
43  const VP8X_XMP = 4;
44  const VP8X_ANIM = 2;
45 
46  public function getMetadata( $image, $filename ) {
47  $parsedWebPData = self::extractMetadata( $filename );
48  if ( !$parsedWebPData ) {
49  return self::BROKEN_FILE;
50  }
51 
52  $parsedWebPData['metadata']['_MW_WEBP_VERSION'] = self::_MW_WEBP_VERSION;
53  return serialize( $parsedWebPData );
54  }
55 
56  public function getMetadataType( $image ) {
57  return 'parsed-webp';
58  }
59 
60  public function isMetadataValid( $image, $metadata ) {
61  if ( $metadata === self::BROKEN_FILE ) {
62  // Do not repetitivly regenerate metadata on broken file.
63  return self::METADATA_GOOD;
64  }
65 
66  MediaWiki\suppressWarnings();
67  $data = unserialize( $metadata );
68  MediaWiki\restoreWarnings();
69 
70  if ( !$data || !is_array( $data ) ) {
71  wfDebug( __METHOD__ . " invalid WebP metadata\n" );
72 
73  return self::METADATA_BAD;
74  }
75 
76  if ( !isset( $data['metadata']['_MW_WEBP_VERSION'] )
77  || $data['metadata']['_MW_WEBP_VERSION'] != self::_MW_WEBP_VERSION
78  ) {
79  wfDebug( __METHOD__ . " old but compatible WebP metadata\n" );
80 
81  return self::METADATA_COMPATIBLE;
82  }
83  return self::METADATA_GOOD;
84  }
85 
94  public static function extractMetadata( $filename ) {
95  wfDebugLog( 'WebP', __METHOD__ . ": Extracting metadata from $filename\n" );
96 
97  $info = RiffExtractor::findChunksFromFile( $filename, 100 );
98  if ( $info === false ) {
99  wfDebugLog( 'WebP', __METHOD__ . ": Not a valid RIFF file\n" );
100  return false;
101  }
102 
103  if ( $info['fourCC'] != 'WEBP' ) {
104  wfDebugLog( 'WebP', __METHOD__ . ': FourCC was not WEBP: ' .
105  bin2hex( $info['fourCC'] ) . " \n" );
106  return false;
107  }
108 
109  $metadata = self::extractMetadataFromChunks( $info['chunks'], $filename );
110  if ( !$metadata ) {
111  wfDebugLog( 'WebP', __METHOD__ . ": No VP8 chunks found\n" );
112  return false;
113  }
114 
115  return $metadata;
116  }
117 
124  public static function extractMetadataFromChunks( $chunks, $filename ) {
125  $vp8Info = [];
126 
127  foreach ( $chunks as $chunk ) {
128  if ( !in_array( $chunk['fourCC'], [ 'VP8 ', 'VP8L', 'VP8X' ] ) ) {
129  // Not a chunk containing interesting metadata
130  continue;
131  }
132 
133  $chunkHeader = file_get_contents( $filename, false, null,
134  $chunk['start'], self::MINIMUM_CHUNK_HEADER_LENGTH );
135  wfDebugLog( 'WebP', __METHOD__ . ": {$chunk['fourCC']}\n" );
136 
137  switch ( $chunk['fourCC'] ) {
138  case 'VP8 ':
139  return array_merge( $vp8Info,
140  self::decodeLossyChunkHeader( $chunkHeader ) );
141  case 'VP8L':
142  return array_merge( $vp8Info,
143  self::decodeLosslessChunkHeader( $chunkHeader ) );
144  case 'VP8X':
145  $vp8Info = array_merge( $vp8Info,
146  self::decodeExtendedChunkHeader( $chunkHeader ) );
147  // Continue looking for other chunks to improve the metadata
148  break;
149  }
150  }
151  return $vp8Info;
152  }
153 
159  protected static function decodeLossyChunkHeader( $header ) {
160  // Bytes 0-3 are 'VP8 '
161  // Bytes 4-7 are the VP8 stream size
162  // Bytes 8-10 are the frame tag
163  // Bytes 11-13 are 0x9D 0x01 0x2A called the sync code
164  $syncCode = substr( $header, 11, 3 );
165  if ( $syncCode != "\x9D\x01\x2A" ) {
166  wfDebugLog( 'WebP', __METHOD__ . ': Invalid sync code: ' .
167  bin2hex( $syncCode ) . "\n" );
168  return [];
169  }
170  // Bytes 14-17 are image size
171  $imageSize = unpack( 'v2', substr( $header, 14, 4 ) );
172  // Image sizes are 14 bit, 2 MSB are scaling parameters which are ignored here
173  return [
174  'compression' => 'lossy',
175  'width' => $imageSize[1] & 0x3FFF,
176  'height' => $imageSize[2] & 0x3FFF
177  ];
178  }
179 
185  public static function decodeLosslessChunkHeader( $header ) {
186  // Bytes 0-3 are 'VP8L'
187  // Bytes 4-7 are chunk stream size
188  // Byte 8 is 0x2F called the signature
189  if ( $header{8} != "\x2F" ) {
190  wfDebugLog( 'WebP', __METHOD__ . ': Invalid signature: ' .
191  bin2hex( $header{8} ) . "\n" );
192  return [];
193  }
194  // Bytes 9-12 contain the image size
195  // Bits 0-13 are width-1; bits 15-27 are height-1
196  $imageSize = unpack( 'C4', substr( $header, 9, 4 ) );
197  return [
198  'compression' => 'lossless',
199  'width' => ( $imageSize[1] | ( ( $imageSize[2] & 0x3F ) << 8 ) ) + 1,
200  'height' => ( ( ( $imageSize[2] & 0xC0 ) >> 6 ) |
201  ( $imageSize[3] << 2 ) | ( ( $imageSize[4] & 0x03 ) << 10 ) ) + 1
202  ];
203  }
204 
210  public static function decodeExtendedChunkHeader( $header ) {
211  // Bytes 0-3 are 'VP8X'
212  // Byte 4-7 are chunk length
213  // Byte 8-11 are a flag bytes
214  $flags = unpack( 'c', substr( $header, 8, 1 ) );
215 
216  // Byte 12-17 are image size (24 bits)
217  $width = unpack( 'V', substr( $header, 12, 3 ) . "\x00" );
218  $height = unpack( 'V', substr( $header, 15, 3 ) . "\x00" );
219 
220  return [
221  'compression' => 'unknown',
222  'animated' => ( $flags[1] & self::VP8X_ANIM ) == self::VP8X_ANIM,
223  'transparency' => ( $flags[1] & self::VP8X_ALPHA ) == self::VP8X_ALPHA,
224  'width' => ( $width[1] & 0xFFFFFF ) + 1,
225  'height' => ( $height[1] & 0xFFFFFF ) + 1
226  ];
227  }
228 
229  public function getImageSize( $file, $path, $metadata = false ) {
230  if ( $file === null ) {
231  $metadata = self::getMetadata( $file, $path );
232  }
233  if ( $metadata === false && $file instanceof File ) {
234  $metadata = $file->getMetadata();
235  }
236 
237  MediaWiki\suppressWarnings();
238  $metadata = unserialize( $metadata );
239  MediaWiki\restoreWarnings();
240 
241  if ( $metadata == false ) {
242  return false;
243  }
244  return [ $metadata['width'], $metadata['height'] ];
245  }
246 
251  public function mustRender( $file ) {
252  return true;
253  }
254 
259  public function canRender( $file ) {
260  if ( self::isAnimatedImage( $file ) ) {
261  return false;
262  }
263  return true;
264  }
265 
270  public function isAnimatedImage( $image ) {
271  $ser = $image->getMetadata();
272  if ( $ser ) {
273  $metadata = unserialize( $ser );
274  if ( isset( $metadata['animated'] ) && $metadata['animated'] === true ) {
275  return true;
276  }
277  }
278 
279  return false;
280  }
281 
282  public function canAnimateThumbnail( $file ) {
283  return false;
284  }
285 
294  public function getThumbType( $ext, $mime, $params = null ) {
295  return [ 'png', 'image/png' ];
296  }
297 
303  protected function getScalerType( $dstPath, $checkDstPath = true ) {
304  return 'im';
305  }
306 }
getThumbType($ext, $mime, $params=null)
Render files as PNG.
Definition: WebP.php:294
static decodeLossyChunkHeader($header)
Decodes a lossy chunk header.
Definition: WebP.php:159
getMetadataType($image)
Definition: WebP.php:56
getMetadata($image, $filename)
Definition: WebP.php:46
static extractMetadataFromChunks($chunks, $filename)
Extracts the image size and WebP type from a file based on the chunk list.
Definition: WebP.php:124
if($ext== 'php'||$ext== 'php5') $mime
Definition: router.php:65
canAnimateThumbnail($file)
Definition: WebP.php:282
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2703
static extractMetadata($filename)
Extracts the image size and WebP type from a file.
Definition: WebP.php:94
static decodeLosslessChunkHeader($header)
Decodes a lossless chunk header.
Definition: WebP.php:185
Handler for Google's WebP format https://developers.google.com/speed/webp/
Definition: WebP.php:29
static findChunksFromFile($filename, $maxChunks=-1)
getImageSize($file, $path, $metadata=false)
Definition: WebP.php:229
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
isMetadataValid($image, $metadata)
Definition: WebP.php:60
unserialize($serialized)
Definition: ApiMessage.php:102
const VP8X_XMP
Definition: WebP.php:43
isAnimatedImage($image)
Definition: WebP.php:270
$params
$header
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
const VP8X_ALPHA
Definition: WebP.php:41
Generic handler for bitmap images.
Definition: Bitmap.php:29
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition: hooks.txt:802
mustRender($file)
Definition: WebP.php:251
canRender($file)
Definition: WebP.php:259
const VP8X_ANIM
Definition: WebP.php:44
static decodeExtendedChunkHeader($header)
Decodes an extended chunk header.
Definition: WebP.php:210
serialize()
Definition: ApiMessage.php:94
const BROKEN_FILE
Definition: WebP.php:30
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:50
const VP8X_ICC
Definition: WebP.php:40
getScalerType($dstPath, $checkDstPath=true)
Must use "im" for XCF.
Definition: WebP.php:303
const VP8X_EXIF
Definition: WebP.php:42