2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % W W EEEEE BBBB PPPP %
8 % W W W EEE BBBB PPPP %
13 % Read/Write WebP Image Format %
20 % Copyright 1999-2017 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 % https://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(
143 const unsigned char *magick_restrict data)
145 register const unsigned char
152 value=(uint32_t) (*p++);
153 value|=((uint32_t) (*p++)) << 8;
154 value|=((uint32_t) (*p++)) << 16;
155 value|=((uint32_t) (*p++)) << 24;
159 static MagickBooleanType IsWEBPImageLossless(const unsigned char *stream,
162 #define VP8_CHUNK_INDEX 15
163 #define LOSSLESS_FLAG 'L'
164 #define EXTENDED_HEADER 'X'
165 #define VP8_CHUNK_HEADER "VP8"
166 #define VP8_CHUNK_HEADER_SIZE 3
167 #define RIFF_HEADER_SIZE 12
168 #define VP8X_CHUNK_SIZE 10
170 #define CHUNK_SIZE_BYTES 4
171 #define CHUNK_HEADER_SIZE 8
172 #define MAX_CHUNK_PAYLOAD (~0U-CHUNK_HEADER_SIZE-1)
180 if (stream[VP8_CHUNK_INDEX] != EXTENDED_HEADER)
181 return(stream[VP8_CHUNK_INDEX] == LOSSLESS_FLAG ? MagickTrue : MagickFalse);
183 Read extended header.
185 offset=RIFF_HEADER_SIZE+TAG_SIZE+CHUNK_SIZE_BYTES+VP8X_CHUNK_SIZE;
186 while (offset <= (ssize_t) length)
192 chunk_size=ReadWebPLSBWord(stream+offset+TAG_SIZE);
193 if (chunk_size > MAX_CHUNK_PAYLOAD)
195 chunk_size_pad=(CHUNK_HEADER_SIZE+chunk_size+1) & ~1;
196 if (memcmp(stream+offset,VP8_CHUNK_HEADER,VP8_CHUNK_HEADER_SIZE) == 0)
197 return(*(stream+offset+VP8_CHUNK_HEADER_SIZE) == LOSSLESS_FLAG ?
198 MagickTrue : MagickFalse);
199 offset+=chunk_size_pad;
204 static Image *ReadWEBPImage(const ImageInfo *image_info,
205 ExceptionInfo *exception)
207 #define ThrowWEBPException(severity,tag) \
209 if (stream != (unsigned char *) NULL) \
210 stream=(unsigned char*) RelinquishMagickMemory(stream); \
211 if (webp_image != (WebPDecBuffer *) NULL) \
212 WebPFreeDecBuffer(webp_image); \
213 ThrowReaderException(severity,tag); \
225 register unsigned char
243 *magick_restrict webp_image = &configure.output;
245 WebPBitstreamFeatures
246 *magick_restrict features = &configure.input;
251 assert(image_info != (const ImageInfo *) NULL);
252 assert(image_info->signature == MagickCoreSignature);
253 if (image_info->debug != MagickFalse)
254 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
255 image_info->filename);
256 assert(exception != (ExceptionInfo *) NULL);
257 assert(exception->signature == MagickCoreSignature);
258 image=AcquireImage(image_info,exception);
259 status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
260 if (status == MagickFalse)
262 image=DestroyImageList(image);
263 return((Image *) NULL);
265 stream=(unsigned char *) NULL;
266 if (WebPInitDecoderConfig(&configure) == 0)
267 ThrowReaderException(ResourceLimitError,"UnableToDecodeImageFile");
268 webp_image->colorspace=MODE_RGBA;
269 count=ReadBlob(image,12,header);
271 ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
272 status=IsWEBP(header,count);
273 if (status == MagickFalse)
274 ThrowWEBPException(CorruptImageError,"CorruptImage");
275 length=(size_t) (ReadWebPLSBWord(header+4)+8);
277 ThrowWEBPException(CorruptImageError,"CorruptImage");
278 if (length > GetBlobSize(image))
279 ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
280 stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream));
281 if (stream == (unsigned char *) NULL)
282 ThrowWEBPException(ResourceLimitError,"MemoryAllocationFailed");
283 (void) memcpy(stream,header,12);
284 count=ReadBlob(image,length-12,stream+12);
285 if (count != (ssize_t) (length-12))
286 ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
287 webp_status=WebPGetFeatures(stream,length,features);
288 if (webp_status == VP8_STATUS_OK)
290 image->columns=(size_t) features->width;
291 image->rows=(size_t) features->height;
293 image->alpha_trait=features->has_alpha != 0 ? BlendPixelTrait :
295 if (IsWEBPImageLossless(stream,length) != MagickFalse)
297 if (image_info->ping != MagickFalse)
299 stream=(unsigned char*) RelinquishMagickMemory(stream);
300 (void) CloseBlob(image);
301 return(GetFirstImageInList(image));
303 status=SetImageExtent(image,image->columns,image->rows,exception);
304 if (status == MagickFalse)
306 stream=(unsigned char*) RelinquishMagickMemory(stream);
307 (void) CloseBlob(image);
308 return(DestroyImageList(image));
310 webp_status=WebPDecode(stream,length,&configure);
312 if (webp_status != VP8_STATUS_OK)
315 case VP8_STATUS_OUT_OF_MEMORY:
317 ThrowWEBPException(ResourceLimitError,"MemoryAllocationFailed");
320 case VP8_STATUS_INVALID_PARAM:
322 ThrowWEBPException(CorruptImageError,"invalid parameter");
325 case VP8_STATUS_BITSTREAM_ERROR:
327 ThrowWEBPException(CorruptImageError,"CorruptImage");
330 case VP8_STATUS_UNSUPPORTED_FEATURE:
332 ThrowWEBPException(CoderError,"DataEncodingSchemeIsNotSupported");
335 case VP8_STATUS_SUSPENDED:
337 ThrowWEBPException(CorruptImageError,"decoder suspended");
340 case VP8_STATUS_USER_ABORT:
342 ThrowWEBPException(CorruptImageError,"user abort");
345 case VP8_STATUS_NOT_ENOUGH_DATA:
347 ThrowWEBPException(CorruptImageError,"InsufficientImageDataInFile");
351 ThrowWEBPException(CorruptImageError,"CorruptImage");
353 p=(unsigned char *) webp_image->u.RGBA.rgba;
354 for (y=0; y < (ssize_t) image->rows; y++)
362 q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
363 if (q == (Quantum *) NULL)
365 for (x=0; x < (ssize_t) image->columns; x++)
367 SetPixelRed(image,ScaleCharToQuantum(*p++),q);
368 SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
369 SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
370 SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
371 q+=GetPixelChannels(image);
373 if (SyncAuthenticPixels(image,exception) == MagickFalse)
375 status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
377 if (status == MagickFalse)
380 WebPFreeDecBuffer(webp_image);
381 stream=(unsigned char*) RelinquishMagickMemory(stream);
382 (void) CloseBlob(image);
388 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
392 % R e g i s t e r W E B P I m a g e %
396 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
398 % RegisterWEBPImage() adds attributes for the WebP image format to
399 % the list of supported formats. The attributes include the image format
400 % tag, a method to read and/or write the format, whether the format
401 % supports the saving of more than one frame to the same file or blob,
402 % whether the format supports native in-memory I/O, and a brief
403 % description of the format.
405 % The format of the RegisterWEBPImage method is:
407 % size_t RegisterWEBPImage(void)
410 ModuleExport size_t RegisterWEBPImage(void)
413 version[MagickPathExtent];
419 entry=AcquireMagickInfo("WEBP","WEBP","WebP Image Format");
420 #if defined(MAGICKCORE_WEBP_DELEGATE)
421 entry->decoder=(DecodeImageHandler *) ReadWEBPImage;
422 entry->encoder=(EncodeImageHandler *) WriteWEBPImage;
423 (void) FormatLocaleString(version,MagickPathExtent,"libwebp %d.%d.%d [%04X]",
424 (WebPGetDecoderVersion() >> 16) & 0xff,
425 (WebPGetDecoderVersion() >> 8) & 0xff,
426 (WebPGetDecoderVersion() >> 0) & 0xff,WEBP_DECODER_ABI_VERSION);
428 entry->mime_type=ConstantString("image/webp");
429 entry->flags|=CoderDecoderSeekableStreamFlag;
430 entry->flags^=CoderAdjoinFlag;
431 entry->magick=(IsImageFormatHandler *) IsWEBP;
432 if (*version != '\0')
433 entry->version=ConstantString(version);
434 (void) RegisterMagickInfo(entry);
435 return(MagickImageCoderSignature);
439 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
443 % U n r e g i s t e r W E B P I m a g e %
447 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
449 % UnregisterWEBPImage() removes format registrations made by the WebP module
450 % from the list of supported formats.
452 % The format of the UnregisterWEBPImage method is:
454 % UnregisterWEBPImage(void)
457 ModuleExport void UnregisterWEBPImage(void)
459 (void) UnregisterMagickInfo("WEBP");
461 #if defined(MAGICKCORE_WEBP_DELEGATE)
464 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
468 % W r i t e W E B P I m a g e %
472 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
474 % WriteWEBPImage() writes an image in the WebP image format.
476 % The format of the WriteWEBPImage method is:
478 % MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
481 % A description of each parameter follows.
483 % o image_info: the image info.
485 % o image: The image.
489 #if WEBP_DECODER_ABI_VERSION >= 0x0100
490 static int WebPEncodeProgress(int percent,const WebPPicture* picture)
492 #define EncodeImageTag "Encode/Image"
500 image=(Image *) picture->custom_ptr;
501 status=SetImageProgress(image,EncodeImageTag,percent-1,100);
502 return(status == MagickFalse ? 0 : 1);
506 static int WebPEncodeWriter(const unsigned char *stream,size_t length,
507 const WebPPicture *const picture)
512 image=(Image *) picture->custom_ptr;
513 return(length != 0 ? (int) WriteBlob(image,length,stream) : 1);
516 static MagickBooleanType WriteWEBPImage(const ImageInfo *image_info,
517 Image *image,ExceptionInfo *exception)
547 Open output image file.
549 assert(image_info != (const ImageInfo *) NULL);
550 assert(image_info->signature == MagickCoreSignature);
551 assert(image != (Image *) NULL);
552 assert(image->signature == MagickCoreSignature);
553 if (image->debug != MagickFalse)
554 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
555 if ((image->columns > 16383UL) || (image->rows > 16383UL))
556 ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
557 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
558 if (status == MagickFalse)
560 if ((WebPPictureInit(&picture) == 0) || (WebPConfigInit(&configure) == 0))
561 ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
562 picture.writer=WebPEncodeWriter;
563 picture.custom_ptr=(void *) image;
564 #if WEBP_DECODER_ABI_VERSION >= 0x0100
565 picture.progress_hook=WebPEncodeProgress;
567 picture.stats=(&statistics);
568 picture.width=(int) image->columns;
569 picture.height=(int) image->rows;
570 picture.argb_stride=(int) image->columns;
572 if (image->quality != UndefinedCompressionQuality)
573 configure.quality=(float) image->quality;
574 if (image->quality >= 100)
575 configure.lossless=1;
576 value=GetImageOption(image_info,"webp:lossless");
577 if (value != (char *) NULL)
578 configure.lossless=(int) ParseCommandOption(MagickBooleanOptions,
580 value=GetImageOption(image_info,"webp:method");
581 if (value != (char *) NULL)
582 configure.method=StringToInteger(value);
583 value=GetImageOption(image_info,"webp:image-hint");
584 if (value != (char *) NULL)
586 if (LocaleCompare(value,"default") == 0)
587 configure.image_hint=WEBP_HINT_DEFAULT;
588 if (LocaleCompare(value,"photo") == 0)
589 configure.image_hint=WEBP_HINT_PHOTO;
590 if (LocaleCompare(value,"picture") == 0)
591 configure.image_hint=WEBP_HINT_PICTURE;
592 #if WEBP_DECODER_ABI_VERSION >= 0x0200
593 if (LocaleCompare(value,"graph") == 0)
594 configure.image_hint=WEBP_HINT_GRAPH;
597 value=GetImageOption(image_info,"webp:target-size");
598 if (value != (char *) NULL)
599 configure.target_size=StringToInteger(value);
600 value=GetImageOption(image_info,"webp:target-psnr");
601 if (value != (char *) NULL)
602 configure.target_PSNR=(float) StringToDouble(value,(char **) NULL);
603 value=GetImageOption(image_info,"webp:segments");
604 if (value != (char *) NULL)
605 configure.segments=StringToInteger(value);
606 value=GetImageOption(image_info,"webp:sns-strength");
607 if (value != (char *) NULL)
608 configure.sns_strength=StringToInteger(value);
609 value=GetImageOption(image_info,"webp:filter-strength");
610 if (value != (char *) NULL)
611 configure.filter_strength=StringToInteger(value);
612 value=GetImageOption(image_info,"webp:filter-sharpness");
613 if (value != (char *) NULL)
614 configure.filter_sharpness=StringToInteger(value);
615 value=GetImageOption(image_info,"webp:filter-type");
616 if (value != (char *) NULL)
617 configure.filter_type=StringToInteger(value);
618 value=GetImageOption(image_info,"webp:auto-filter");
619 if (value != (char *) NULL)
620 configure.autofilter=(int) ParseCommandOption(MagickBooleanOptions,
622 value=GetImageOption(image_info,"webp:alpha-compression");
623 if (value != (char *) NULL)
624 configure.alpha_compression=StringToInteger(value);
625 value=GetImageOption(image_info,"webp:alpha-filtering");
626 if (value != (char *) NULL)
627 configure.alpha_filtering=StringToInteger(value);
628 value=GetImageOption(image_info,"webp:alpha-quality");
629 if (value != (char *) NULL)
630 configure.alpha_quality=StringToInteger(value);
631 value=GetImageOption(image_info,"webp:pass");
632 if (value != (char *) NULL)
633 configure.pass=StringToInteger(value);
634 value=GetImageOption(image_info,"webp:show-compressed");
635 if (value != (char *) NULL)
636 configure.show_compressed=StringToInteger(value);
637 value=GetImageOption(image_info,"webp:preprocessing");
638 if (value != (char *) NULL)
639 configure.preprocessing=StringToInteger(value);
640 value=GetImageOption(image_info,"webp:partitions");
641 if (value != (char *) NULL)
642 configure.partitions=StringToInteger(value);
643 value=GetImageOption(image_info,"webp:partition-limit");
644 if (value != (char *) NULL)
645 configure.partition_limit=StringToInteger(value);
646 #if WEBP_DECODER_ABI_VERSION >= 0x0201
647 value=GetImageOption(image_info,"webp:emulate-jpeg-size");
648 if (value != (char *) NULL)
649 configure.emulate_jpeg_size=(int) ParseCommandOption(MagickBooleanOptions,
651 value=GetImageOption(image_info,"webp:low-memory");
652 if (value != (char *) NULL)
653 configure.low_memory=(int) ParseCommandOption(MagickBooleanOptions,
655 value=GetImageOption(image_info,"webp:thread-level");
656 if (value != (char *) NULL)
657 configure.thread_level=StringToInteger(value);
659 if (WebPValidateConfig(&configure) == 0)
660 ThrowWriterException(ResourceLimitError,"UnableToEncodeImageFile");
662 Allocate memory for pixels.
664 (void) TransformImageColorspace(image,sRGBColorspace,exception);
665 pixel_info=AcquireVirtualMemory(image->columns,image->rows*
666 sizeof(*picture.argb));
667 if (pixel_info == (MemoryInfo *) NULL)
668 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
669 picture.argb=(uint32_t *) GetVirtualMemoryBlob(pixel_info);
671 Convert image to WebP raster pixels.
674 for (y=0; y < (ssize_t) image->rows; y++)
676 register const Quantum
682 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
683 if (p == (const Quantum *) NULL)
685 for (x=0; x < (ssize_t) image->columns; x++)
687 *q++=(uint32_t) (image->alpha_trait != UndefinedPixelTrait ?
688 ScaleQuantumToChar(GetPixelAlpha(image,p)) << 24 : 0xff000000) |
689 (ScaleQuantumToChar(GetPixelRed(image,p)) << 16) |
690 (ScaleQuantumToChar(GetPixelGreen(image,p)) << 8) |
691 (ScaleQuantumToChar(GetPixelBlue(image,p)));
692 p+=GetPixelChannels(image);
694 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
696 if (status == MagickFalse)
699 webp_status=WebPEncode(&configure,&picture);
700 if (webp_status == 0)
705 switch (picture.error_code)
707 case VP8_ENC_ERROR_OUT_OF_MEMORY:
709 message="out of memory";
712 case VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY:
714 message="bitstream out of memory";
717 case VP8_ENC_ERROR_NULL_PARAMETER:
719 message="NULL parameter";
722 case VP8_ENC_ERROR_INVALID_CONFIGURATION:
724 message="invalid configuration";
727 case VP8_ENC_ERROR_BAD_DIMENSION:
729 message="bad dimension";
732 case VP8_ENC_ERROR_PARTITION0_OVERFLOW:
734 message="partition 0 overflow (> 512K)";
737 case VP8_ENC_ERROR_PARTITION_OVERFLOW:
739 message="partition overflow (> 16M)";
742 case VP8_ENC_ERROR_BAD_WRITE:
747 case VP8_ENC_ERROR_FILE_TOO_BIG:
749 message="file too big (> 4GB)";
752 #if WEBP_DECODER_ABI_VERSION >= 0x0100
753 case VP8_ENC_ERROR_USER_ABORT:
755 message="user abort";
761 message="unknown exception";
765 (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
766 (char *) message,"`%s'",image->filename);
768 picture.argb=(uint32_t *) NULL;
769 WebPPictureFree(&picture);
770 pixel_info=RelinquishVirtualMemory(pixel_info);
771 (void) CloseBlob(image);
772 return(webp_status == 0 ? MagickFalse : MagickTrue);