2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % W W EEEEE BBBB PPPP %
8 % W W W EEE BBBB PPPP %
13 % Read/Write WebP Image Format %
20 % Copyright 1999-2013 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
28 % Unless required by applicable law or agreed to in writing, software %
29 % distributed under the License is distributed on an "AS IS" BASIS, %
30 % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31 % See the License for the specific language governing permissions and %
32 % limitations under the License. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
42 #include "MagickCore/studio.h"
43 #include "MagickCore/artifact.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/client.h"
47 #include "MagickCore/colorspace-private.h"
48 #include "MagickCore/display.h"
49 #include "MagickCore/exception.h"
50 #include "MagickCore/exception-private.h"
51 #include "MagickCore/image.h"
52 #include "MagickCore/image-private.h"
53 #include "MagickCore/list.h"
54 #include "MagickCore/magick.h"
55 #include "MagickCore/monitor.h"
56 #include "MagickCore/monitor-private.h"
57 #include "MagickCore/memory_.h"
58 #include "MagickCore/option.h"
59 #include "MagickCore/pixel-accessor.h"
60 #include "MagickCore/quantum-private.h"
61 #include "MagickCore/static.h"
62 #include "MagickCore/string_.h"
63 #include "MagickCore/string-private.h"
64 #include "MagickCore/module.h"
65 #include "MagickCore/utility.h"
66 #include "MagickCore/xwindow.h"
67 #include "MagickCore/xwindow-private.h"
68 #if defined(MAGICKCORE_WEBP_DELEGATE)
69 #include <webp/decode.h>
70 #include <webp/encode.h>
76 #if defined(MAGICKCORE_WEBP_DELEGATE)
77 static MagickBooleanType
78 WriteWEBPImage(const ImageInfo *,Image *,ExceptionInfo *);
82 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
90 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
92 % IsWEBP() returns MagickTrue if the image format type, identified by the
93 % magick string, is WebP.
95 % The format of the IsWEBP method is:
97 % MagickBooleanType IsWEBP(const unsigned char *magick,const size_t length)
99 % A description of each parameter follows:
101 % o magick: compare image format pattern against these bytes.
103 % o length: Specifies the length of the magick string.
106 static MagickBooleanType IsWEBP(const unsigned char *magick,const size_t length)
110 if (LocaleNCompare((const char *) magick+8,"WEBP",4) == 0)
115 #if defined(MAGICKCORE_WEBP_DELEGATE)
117 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
121 % R e a d W E B P I m a g e %
125 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
127 % ReadWEBPImage() reads an image in the WebP image format.
129 % The format of the ReadWEBPImage method is:
131 % Image *ReadWEBPImage(const ImageInfo *image_info,
132 % ExceptionInfo *exception)
134 % A description of each parameter follows:
136 % o image_info: the image info.
138 % o exception: return any errors or warnings in this structure.
142 static inline uint32_t ReadWebPLSBWord(const unsigned char *restrict data)
144 register const unsigned char
151 value=(uint32_t) (*p++);
152 value|=((uint32_t) (*p++)) << 8;
153 value|=((uint32_t) (*p++)) << 16;
154 value|=((uint32_t) (*p++)) << 24;
158 static MagickBooleanType IsWEBPImageLossless(const unsigned char *stream,
161 #define VP8_CHUNK_INDEX 15
162 #define LOSSLESS_FLAG 'L'
163 #define EXTENDED_HEADER 'X'
164 #define VP8_CHUNK_HEADER "VP8"
165 #define VP8_CHUNK_HEADER_SIZE 3
166 #define RIFF_HEADER_SIZE 12
167 #define VP8X_CHUNK_SIZE 10
169 #define CHUNK_SIZE_BYTES 4
170 #define CHUNK_HEADER_SIZE 8
171 #define MAX_CHUNK_PAYLOAD (~0U-CHUNK_HEADER_SIZE-1)
179 if (stream[VP8_CHUNK_INDEX] != EXTENDED_HEADER)
180 return(stream[VP8_CHUNK_INDEX] == LOSSLESS_FLAG ? MagickTrue : MagickFalse);
182 Read extended header.
184 offset=RIFF_HEADER_SIZE+TAG_SIZE+CHUNK_SIZE_BYTES+VP8X_CHUNK_SIZE;
185 while (offset <= (ssize_t) length)
191 chunk_size=ReadWebPLSBWord(stream+offset+TAG_SIZE);
192 if (chunk_size > MAX_CHUNK_PAYLOAD)
194 chunk_size_pad=(CHUNK_HEADER_SIZE+chunk_size+1) & ~1;
195 if (memcmp(stream+offset,VP8_CHUNK_HEADER,VP8_CHUNK_HEADER_SIZE) == 0)
196 return(*(stream+offset+VP8_CHUNK_HEADER_SIZE) == LOSSLESS_FLAG ?
197 MagickTrue : MagickFalse);
198 offset+=chunk_size_pad;
203 static Image *ReadWEBPImage(const ImageInfo *image_info,
204 ExceptionInfo *exception)
215 register unsigned char
232 *restrict webp_image = &configure.output;
234 WebPBitstreamFeatures
235 *restrict features = &configure.input;
240 assert(image_info != (const ImageInfo *) NULL);
241 assert(image_info->signature == MagickSignature);
242 if (image_info->debug != MagickFalse)
243 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
244 image_info->filename);
245 assert(exception != (ExceptionInfo *) NULL);
246 assert(exception->signature == MagickSignature);
247 image=AcquireImage(image_info,exception);
248 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
249 if (status == MagickFalse)
251 image=DestroyImageList(image);
252 return((Image *) NULL);
254 if (WebPInitDecoderConfig(&configure) == 0)
255 ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile");
256 webp_image->colorspace=MODE_RGBA;
257 length=(size_t) GetBlobSize(image);
258 stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream));
259 if (stream == (unsigned char *) NULL)
260 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
261 count=ReadBlob(image,length,stream);
262 if (count != (ssize_t) length)
263 ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
264 webp_status=WebPGetFeatures(stream,length,features);
265 if (webp_status == VP8_STATUS_OK)
267 image->columns=(size_t) features->width;
268 image->rows=(size_t) features->height;
270 image->alpha_trait=features->has_alpha != 0 ? BlendPixelTrait :
272 if (image_info->ping != MagickFalse)
274 stream=(unsigned char*) RelinquishMagickMemory(stream);
275 (void) CloseBlob(image);
276 return(GetFirstImageInList(image));
278 webp_status=WebPDecode(stream,length,&configure);
280 if (webp_status != VP8_STATUS_OK)
282 stream=(unsigned char*) RelinquishMagickMemory(stream);
285 case VP8_STATUS_OUT_OF_MEMORY:
287 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
290 case VP8_STATUS_BITSTREAM_ERROR:
292 ThrowReaderException(CorruptImageError,"CorruptImage");
295 case VP8_STATUS_UNSUPPORTED_FEATURE:
297 ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
300 case VP8_STATUS_NOT_ENOUGH_DATA:
302 ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
306 ThrowReaderException(CorruptImageError,"CorruptImage");
309 if (IsWEBPImageLossless(stream,length) != MagickFalse)
311 p=webp_image->u.RGBA.rgba;
312 for (y=0; y < (ssize_t) image->rows; y++)
320 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
321 if (q == (Quantum *) NULL)
323 for (x=0; x < (ssize_t) image->columns; x++)
325 SetPixelRed(image,ScaleCharToQuantum(*p++),q);
326 SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
327 SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
328 SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
329 q+=GetPixelChannels(image);
331 if (SyncAuthenticPixels(image,exception) == MagickFalse)
333 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
335 if (status == MagickFalse)
338 WebPFreeDecBuffer(webp_image);
339 stream=(unsigned char*) RelinquishMagickMemory(stream);
345 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
349 % R e g i s t e r W E B P I m a g e %
353 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
355 % RegisterWEBPImage() adds attributes for the WebP image format to
356 % the list of supported formats. The attributes include the image format
357 % tag, a method to read and/or write the format, whether the format
358 % supports the saving of more than one frame to the same file or blob,
359 % whether the format supports native in-memory I/O, and a brief
360 % description of the format.
362 % The format of the RegisterWEBPImage method is:
364 % size_t RegisterWEBPImage(void)
367 ModuleExport size_t RegisterWEBPImage(void)
370 version[MaxTextExtent];
376 entry=SetMagickInfo("WEBP");
377 #if defined(MAGICKCORE_WEBP_DELEGATE)
378 entry->decoder=(DecodeImageHandler *) ReadWEBPImage;
379 entry->encoder=(EncodeImageHandler *) WriteWEBPImage;
380 (void) FormatLocaleString(version,MaxTextExtent,"libwebp %d.%d.%d",
381 (WebPGetDecoderVersion() >> 16) & 0xff,
382 (WebPGetDecoderVersion() >> 8) & 0xff,
383 (WebPGetDecoderVersion() >> 0) & 0xff);
385 entry->description=ConstantString("WebP Image Format");
386 entry->mime_type=ConstantString("image/x-webp");
387 entry->adjoin=MagickFalse;
388 entry->module=ConstantString("WEBP");
389 entry->magick=(IsImageFormatHandler *) IsWEBP;
390 if (*version != '\0')
391 entry->version=ConstantString(version);
392 (void) RegisterMagickInfo(entry);
393 return(MagickImageCoderSignature);
397 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
401 % U n r e g i s t e r W E B P I m a g e %
405 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
407 % UnregisterWEBPImage() removes format registrations made by the WebP module
408 % from the list of supported formats.
410 % The format of the UnregisterWEBPImage method is:
412 % UnregisterWEBPImage(void)
415 ModuleExport void UnregisterWEBPImage(void)
417 (void) UnregisterMagickInfo("WEBP");
419 #if defined(MAGICKCORE_WEBP_DELEGATE)
422 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
426 % W r i t e W E B P I m a g e %
430 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
432 % WriteWEBPImage() writes an image in the WebP image format.
434 % The format of the WriteWEBPImage method is:
436 % MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
439 % A description of each parameter follows.
441 % o image_info: the image info.
443 % o image: The image.
447 static int WebPWriter(const unsigned char *stream,size_t length,
448 const WebPPicture *const picture)
453 image=(Image *) picture->custom_ptr;
454 return(length != 0 ? (int) WriteBlob(image,length,stream) : 1);
457 static MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
458 Image *image,ExceptionInfo *exception)
488 Open output image file.
490 assert(image_info != (const ImageInfo *) NULL);
491 assert(image_info->signature == MagickSignature);
492 assert(image != (Image *) NULL);
493 assert(image->signature == MagickSignature);
494 if (image->debug != MagickFalse)
495 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
496 if ((image->columns > 16383UL) || (image->rows > 16383UL))
497 ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
498 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
499 if (status == MagickFalse)
501 if ((WebPPictureInit(&picture) == 0) || (WebPConfigInit(&configure) == 0))
502 ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
503 picture.writer=WebPWriter;
504 picture.custom_ptr=(void *) image;
505 picture.stats=(&statistics);
506 picture.width=(int) image->columns;
507 picture.height=(int) image->rows;
508 picture.argb_stride=(int) image->columns;
510 if (image->quality != UndefinedCompressionQuality)
511 configure.quality=(float) image->quality;
513 if (image->quality >= 100)
514 configure.lossless=1;
515 value=GetImageOption(image_info,"webp:lossless");
516 if (value != (char *) NULL)
517 configure.lossless=ParseCommandOption(MagickBooleanOptions,MagickFalse,
519 value=GetImageOption(image_info,"webp:method");
520 if (value != (char *) NULL)
521 configure.method=StringToInteger(value);
522 value=GetImageOption(image_info,"webp:image-hint");
523 if (value != (char *) NULL)
525 if (LocaleCompare(value,"graph") == 0)
526 configure.image_hint=WEBP_HINT_GRAPH;
527 if (LocaleCompare(value,"photo") == 0)
528 configure.image_hint=WEBP_HINT_PHOTO;
529 if (LocaleCompare(value,"picture") == 0)
530 configure.image_hint=WEBP_HINT_PICTURE;
532 value=GetImageOption(image_info,"webp:target-size");
533 if (value != (char *) NULL)
534 configure.target_size=StringToInteger(value);
535 value=GetImageOption(image_info,"webp:target-psnr");
536 if (value != (char *) NULL)
537 configure.target_PSNR=(float) StringToDouble(value,(char **) NULL);
538 value=GetImageOption(image_info,"webp:segments");
539 if (value != (char *) NULL)
540 configure.segments=StringToInteger(value);
541 value=GetImageOption(image_info,"webp:sns-strength");
542 if (value != (char *) NULL)
543 configure.sns_strength=StringToInteger(value);
544 value=GetImageOption(image_info,"webp:filter-strength");
545 if (value != (char *) NULL)
546 configure.filter_strength=StringToInteger(value);
547 value=GetImageOption(image_info,"webp:filter-sharpness");
548 if (value != (char *) NULL)
549 configure.filter_sharpness=StringToInteger(value);
550 value=GetImageOption(image_info,"webp:filter-type");
551 if (value != (char *) NULL)
552 configure.filter_type=StringToInteger(value);
553 value=GetImageOption(image_info,"webp:auto-filter");
554 if (value != (char *) NULL)
555 configure.autofilter=ParseCommandOption(MagickBooleanOptions,MagickFalse,
557 value=GetImageOption(image_info,"webp:alpha-compression");
558 if (value != (char *) NULL)
559 configure.alpha_compression=StringToInteger(value);
560 value=GetImageOption(image_info,"webp:alpha-filtering");
561 if (value != (char *) NULL)
562 configure.alpha_filtering=StringToInteger(value);
563 value=GetImageOption(image_info,"webp:alpha-quality");
564 if (value != (char *) NULL)
565 configure.alpha_quality=StringToInteger(value);
566 value=GetImageOption(image_info,"webp:pass");
567 if (value != (char *) NULL)
568 configure.pass=StringToInteger(value);
569 value=GetImageOption(image_info,"webp:show-compressed");
570 if (value != (char *) NULL)
571 configure.show_compressed=StringToInteger(value);
572 value=GetImageOption(image_info,"webp:preprocessing");
573 if (value != (char *) NULL)
574 configure.preprocessing=StringToInteger(value);
575 value=GetImageOption(image_info,"webp:partitions");
576 if (value != (char *) NULL)
577 configure.partitions=StringToInteger(value);
578 value=GetImageOption(image_info,"webp:partition-limit");
579 if (value != (char *) NULL)
580 configure.partition_limit=StringToInteger(value);
581 if (WebPValidateConfig(&configure) == 0)
582 ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
584 Allocate memory for pixels.
586 (void) TransformImageColorspace(image,sRGBColorspace,exception);
587 pixel_info=AcquireVirtualMemory(image->columns,image->rows*
588 sizeof(*picture.argb));
589 if (pixel_info == (MemoryInfo *) NULL)
590 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
591 picture.argb=(uint32_t *) GetVirtualMemoryBlob(pixel_info);
593 Convert image to WebP raster pixels.
596 for (y=0; y < (ssize_t) image->rows; y++)
598 register const Quantum
604 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
605 if (p == (const Quantum *) NULL)
607 for (x=0; x < (ssize_t) image->columns; x++)
609 *q++=(uint32_t) (image->alpha_trait == BlendPixelTrait ?
610 ScaleQuantumToChar(GetPixelAlpha(image,p)) << 24 : 0xff000000) |
611 (ScaleQuantumToChar(GetPixelRed(image,p)) << 16) |
612 (ScaleQuantumToChar(GetPixelGreen(image,p)) << 8) |
613 (ScaleQuantumToChar(GetPixelBlue(image,p)));
614 p+=GetPixelChannels(image);
616 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
618 if (status == MagickFalse)
621 webp_status=WebPEncode(&configure,&picture);
622 if (webp_status == 0)
627 switch (picture.error_code)
629 case VP8_ENC_ERROR_OUT_OF_MEMORY:
631 message="out of memory";
634 case VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY:
636 message="bitstream out of memory";
639 case VP8_ENC_ERROR_NULL_PARAMETER:
641 message="NULL parameter";
644 case VP8_ENC_ERROR_INVALID_CONFIGURATION:
646 message="invalid configuration";
649 case VP8_ENC_ERROR_BAD_DIMENSION:
651 message="bad dimension";
654 case VP8_ENC_ERROR_PARTITION0_OVERFLOW:
656 message="partition 0 overflow (> 512K)";
659 case VP8_ENC_ERROR_PARTITION_OVERFLOW:
661 message="partition overflow (> 16M)";
664 case VP8_ENC_ERROR_BAD_WRITE:
669 case VP8_ENC_ERROR_FILE_TOO_BIG:
671 message="file too big (> 4GB)";
674 #if WEBP_ENCODER_ABI_VERSION >= 0x0100
675 case VP8_ENC_ERROR_USER_ABORT:
677 message="user abort";
683 message="unknown exception";
687 (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
688 (char *) message,"`%s'",image->filename);
690 WebPPictureFree(&picture);
691 pixel_info=RelinquishVirtualMemory(pixel_info);
692 (void) CloseBlob(image);
693 return(webp_status == 0 ? MagickFalse : MagickTrue);