LibTIFF 4.7.2
TIFF library public API and implementation reference
Loading...
Searching...
No Matches
tif_webp.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2018, Mapbox
3 * Author: <norman.barker at mapbox.com>
4 *
5 * Permission to use, copy, modify, distribute, and sell this software and
6 * its documentation for any purpose is hereby granted without fee, provided
7 * that (i) the above copyright notices and this permission notice appear in
8 * all copies of the software and related documentation, and (ii) the names of
9 * Sam Leffler and Silicon Graphics may not be used in any advertising or
10 * publicity relating to the software without the specific, prior written
11 * permission of Sam Leffler and Silicon Graphics.
12 *
13 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
14 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
15 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
16 *
17 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
18 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
19 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
20 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
21 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
22 * OF THIS SOFTWARE.
23 */
24
30#include "tiffiop.h"
31#ifdef WEBP_SUPPORT
32/*
33 * TIFF Library.
34 *
35 * WEBP Compression Support
36 *
37 */
38
39#include "webp/decode.h"
40#include "webp/encode.h"
41
42#include <stdbool.h>
43#include <stdio.h>
44
45#define LSTATE_INIT_DECODE 0x01
46#define LSTATE_INIT_ENCODE 0x02
47/*
48 * State block for each open TIFF
49 * file using WEBP compression/decompression.
50 */
59typedef struct
60{
62 uint16_t nSamples;
63
82 WebPPicture sPicture;
84 WebPConfig sEncoderConfig;
89 uint8_t *pBuffer;
91 unsigned int buffer_offset;
95 unsigned int buffer_size;
96
98 WebPIDecoder *psDecoder;
103 WebPDecBuffer sDecBuffer;
106
108 int state;
109
114} WebPState;
115
116#define LState(tif) ((WebPState *)(tif)->tif_data)
117#define DecoderState(tif) LState(tif)
118#define EncoderState(tif) LState(tif)
119
120static int TWebPEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s);
121static int TWebPDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s);
122
136static void TWebPGetStrileDimensions(const TIFF *tif, uint32_t *width,
137 uint32_t *height)
138{
139 const TIFFDirectory *td = &tif->tif_dir;
140
141 if (isTiled(tif))
142 {
143 *width = td->td_tilewidth;
144 *height = td->td_tilelength;
145 }
146 else
147 {
148 *width = td->td_imagewidth;
149 *height = td->td_imagelength - td->td_row;
150 if (*height > td->td_rowsperstrip)
151 *height = td->td_rowsperstrip;
152 }
153}
154
172static int TWebPDatasetWriter(const uint8_t *data, size_t data_size,
173 const WebPPicture *const picture)
174{
175 static const char module[] = "TWebPDatasetWriter";
176 TIFF *tif = (TIFF *)(picture->custom_ptr);
177
178 if ((tif->tif_rawcc + (tmsize_t)data_size) > tif->tif_rawdatasize)
179 {
180 TIFFErrorExtR(tif, module,
181 "Buffer too small by %" TIFF_SIZE_FORMAT " bytes.",
182 (size_t)((uint64_t)tif->tif_rawcc + (uint64_t)data_size -
183 (uint64_t)tif->tif_rawdatasize));
184 return 0;
185 }
186 else
187 {
188 _TIFFmemcpy(tif->tif_rawcp, data, (tmsize_t)data_size);
189 tif->tif_rawcc += (tmsize_t)data_size;
190 tif->tif_rawcp += data_size;
191 return 1;
192 }
193}
194
195/*
196 * Encode a chunk of pixels.
197 */
221static int TWebPEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
222{
223 static const char module[] = "TWebPEncode";
224 WebPState *sp = EncoderState(tif);
225 (void)s;
226
227 assert(sp != NULL);
228 if (sp->state != LSTATE_INIT_ENCODE)
229 {
230 TIFFErrorExtR(tif, module,
231 "WebP codec state is not initialized for encoding");
232 return 0;
233 }
234
235 if ((uint64_t)sp->buffer_offset + (uint64_t)cc > sp->buffer_size)
236 {
237 TIFFErrorExtR(tif, module, "Too many bytes to be written");
238 return 0;
239 }
240
241 memcpy(sp->pBuffer + sp->buffer_offset, bp, (size_t)cc);
242 sp->buffer_offset += (unsigned)cc;
243
244 return 1;
245}
246
275static int TWebPDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
276{
277 static const char module[] = "TWebPDecode";
278 VP8StatusCode status = VP8_STATUS_OK;
279 WebPState *sp = DecoderState(tif);
280 uint32_t segment_width, segment_height;
281 bool decode_whole_strile = false;
282
283 (void)s;
284
285 assert(sp != NULL);
286 assert(sp->state == LSTATE_INIT_DECODE);
287
288 if (sp->read_error)
289 {
290 memset(op, 0, (size_t)occ);
291 TIFFErrorExtR(tif, module,
292 "ZIPDecode: Scanline %" PRIu32 " cannot be read due to "
293 "previous error",
294 tif->tif_dir.td_row);
295 return 0;
296 }
297
298 if (sp->psDecoder == NULL)
299 {
300 uint32_t buffer_size;
301
302 TWebPGetStrileDimensions(tif, &segment_width, &segment_height);
303
304 int webp_width, webp_height;
305 if (!WebPGetInfo(tif->tif_rawcp,
306 (uint64_t)tif->tif_rawcc > UINT32_MAX
307 ? UINT32_MAX
308 : (uint32_t)tif->tif_rawcc,
309 &webp_width, &webp_height))
310 {
311 memset(op, 0, (size_t)occ);
312 sp->read_error = 1;
313 TIFFErrorExtR(tif, module, "WebPGetInfo() failed");
314 return 0;
315 }
316 if ((uint32_t)webp_width != segment_width ||
317 (uint32_t)webp_height != segment_height)
318 {
319 memset(op, 0, (size_t)occ);
320 sp->read_error = 1;
322 tif, module, "WebP blob dimension is %dx%d. Expected %ux%u",
323 webp_width, webp_height, segment_width, segment_height);
324 return 0;
325 }
326
327#if WEBP_DECODER_ABI_VERSION >= 0x0002
328 WebPDecoderConfig config;
329 if (!WebPInitDecoderConfig(&config))
330 {
331 memset(op, 0, (size_t)occ);
332 sp->read_error = 1;
333 TIFFErrorExtR(tif, module, "WebPInitDecoderConfig() failed");
334 return 0;
335 }
336
337 const bool bWebPGetFeaturesOK =
338 WebPGetFeatures(tif->tif_rawcp,
339 (uint64_t)tif->tif_rawcc > UINT32_MAX
340 ? UINT32_MAX
341 : (uint32_t)tif->tif_rawcc,
342 &config.input) == VP8_STATUS_OK;
343
344 WebPFreeDecBuffer(&config.output);
345
346 if (!bWebPGetFeaturesOK)
347 {
348 memset(op, 0, (size_t)occ);
349 sp->read_error = 1;
350 TIFFErrorExtR(tif, module, "WebPInitDecoderConfig() failed");
351 return 0;
352 }
353
354 const int webp_bands = config.input.has_alpha ? 4 : 3;
355 if (webp_bands != sp->nSamples &&
356 /* We accept the situation where the WebP blob has only 3 bands,
357 * whereas the raster is 4 bands. This can happen when the alpha
358 * channel is fully opaque, and WebP decoding works fine in that
359 * situation.
360 */
361 !(webp_bands == 3 && sp->nSamples == 4))
362 {
363 memset(op, 0, (size_t)occ);
364 sp->read_error = 1;
365 TIFFErrorExtR(tif, module,
366 "WebP blob band count is %d. Expected %d", webp_bands,
367 sp->nSamples);
368 return 0;
369 }
370#endif
371
372 buffer_size = segment_width * segment_height * sp->nSamples;
373 if (occ == (tmsize_t)buffer_size)
374 {
375 /* If decoding the whole strip/tile, we can directly use the */
376 /* output buffer */
377 decode_whole_strile = true;
378 }
379 else if (sp->pBuffer == NULL || buffer_size > sp->buffer_size)
380 {
381 if (sp->pBuffer != NULL)
382 {
383 _TIFFfreeExt(tif, sp->pBuffer);
384 sp->pBuffer = NULL;
385 }
386
387 sp->pBuffer = (uint8_t *)_TIFFmallocExt(tif, buffer_size);
388 if (!sp->pBuffer)
389 {
390 TIFFErrorExtR(tif, module, "Cannot allocate buffer");
391 memset(op, 0, (size_t)occ);
392 sp->read_error = 1;
393 return 0;
394 }
395 sp->buffer_size = buffer_size;
396 }
397
398 sp->last_y = 0;
399
400 WebPInitDecBuffer(&sp->sDecBuffer);
401
402 sp->sDecBuffer.is_external_memory = 1;
403 sp->sDecBuffer.width = (int)segment_width;
404 sp->sDecBuffer.height = (int)segment_height;
405 sp->sDecBuffer.u.RGBA.rgba = decode_whole_strile ? op : sp->pBuffer;
406 sp->sDecBuffer.u.RGBA.stride = (int)(segment_width * sp->nSamples);
407 sp->sDecBuffer.u.RGBA.size = buffer_size;
408
409 if (sp->nSamples > 3)
410 {
411 sp->sDecBuffer.colorspace = MODE_RGBA;
412 }
413 else
414 {
415 sp->sDecBuffer.colorspace = MODE_RGB;
416 }
417
418 sp->psDecoder = WebPINewDecoder(&sp->sDecBuffer);
419
420 if (sp->psDecoder == NULL)
421 {
422 memset(op, 0, (size_t)occ);
423 sp->read_error = 1;
424 TIFFErrorExtR(tif, module, "Unable to allocate WebP decoder.");
425 return 0;
426 }
427 }
428
429 if (occ % sp->sDecBuffer.u.RGBA.stride)
430 {
431 // read_error not set here as this is a usage issue that can be
432 // recovered in a following call.
433 memset(op, 0, (size_t)occ);
434 /* Do not set read_error as could potentially be recovered */
435 TIFFErrorExtR(tif, module, "Fractional scanlines cannot be read");
436 return 0;
437 }
438
439 status = WebPIAppend(sp->psDecoder, tif->tif_rawcp, (size_t)tif->tif_rawcc);
440
441 if (status != VP8_STATUS_OK && status != VP8_STATUS_SUSPENDED)
442 {
443 if (status == VP8_STATUS_INVALID_PARAM)
444 {
445 TIFFErrorExtR(tif, module, "Invalid parameter used.");
446 }
447 else if (status == VP8_STATUS_OUT_OF_MEMORY)
448 {
449 TIFFErrorExtR(tif, module, "Out of memory.");
450 }
451 else
452 {
453 TIFFErrorExtR(tif, module, "Unrecognized error.");
454 }
455 memset(op, 0, (size_t)occ);
456 sp->read_error = 1;
457 return 0;
458 }
459 else
460 {
461 int current_y, stride;
462 uint8_t *buf;
463
464 /* Returns the RGB/A image decoded so far */
465 buf = WebPIDecGetRGB(sp->psDecoder, &current_y, NULL, NULL, &stride);
466
467 if ((buf != NULL) &&
468 (occ <= (tmsize_t)stride * (current_y - sp->last_y)))
469 {
470 const int numberOfExpectedLines =
471 (int)(occ / sp->sDecBuffer.u.RGBA.stride);
472 if (decode_whole_strile)
473 {
474 if (current_y != numberOfExpectedLines)
475 {
476 memset(op, 0, (size_t)occ);
477 sp->read_error = 1;
478 TIFFErrorExtR(tif, module,
479 "Unable to decode WebP data: less lines than "
480 "expected.");
481 return 0;
482 }
483 }
484 else
485 {
486 memcpy(op, buf + (sp->last_y * stride), (size_t)occ);
487 }
488
489 tif->tif_rawcp += tif->tif_rawcc;
490 tif->tif_rawcc = 0;
491 sp->last_y += numberOfExpectedLines;
492
493 if (decode_whole_strile)
494 {
495 /* We can now free the decoder as we're completely done */
496 if (sp->psDecoder != NULL)
497 {
498 WebPIDelete(sp->psDecoder);
499 WebPFreeDecBuffer(&sp->sDecBuffer);
500 sp->psDecoder = NULL;
501 }
502 }
503 return 1;
504 }
505 else
506 {
507 memset(op, 0, (size_t)occ);
508 sp->read_error = 1;
509 TIFFErrorExtR(tif, module, "Unable to decode WebP data.");
510 return 0;
511 }
512 }
513}
514
526static int TWebPFixupTags(TIFF *tif)
527{
528 (void)tif;
530 {
531 static const char module[] = "TWebPFixupTags";
532 TIFFErrorExtR(tif, module,
533 "TIFF WEBP requires data to be stored contiguously in "
534 "RGB e.g. RGBRGBRGB "
535#if WEBP_ENCODER_ABI_VERSION >= 0x0100
536 "or RGBARGBARGBA"
537#endif
538 );
539 return 0;
540 }
541 return 1;
542}
543
560static int TWebPSetupDecode(TIFF *tif)
561{
562 static const char module[] = "TWebPSetupDecode";
563 uint16_t nBitsPerSample = tif->tif_dir.td_bitspersample;
564 uint16_t sampleFormat = tif->tif_dir.td_sampleformat;
565
566 WebPState *sp = DecoderState(tif);
567 assert(sp != NULL);
568
570
571 /* check band count */
572 if (sp->nSamples != 3
573#if WEBP_ENCODER_ABI_VERSION >= 0x0100
574 && sp->nSamples != 4
575#endif
576 )
577 {
578 TIFFErrorExtR(tif, module,
579 "WEBP driver doesn't support %d bands. Must be 3 (RGB) "
580#if WEBP_ENCODER_ABI_VERSION >= 0x0100
581 "or 4 (RGBA) "
582#endif
583 "bands.",
584 sp->nSamples);
585 return 0;
586 }
587
588 /* check bits per sample and data type */
589 if ((nBitsPerSample != 8) && (sampleFormat != 1))
590 {
591 TIFFErrorExtR(tif, module, "WEBP driver requires 8 bit unsigned data");
592 return 0;
593 }
594
595 /* if we were last encoding, terminate this mode */
596 if (sp->state & LSTATE_INIT_ENCODE)
597 {
598 WebPPictureFree(&sp->sPicture);
599 if (sp->pBuffer != NULL)
600 {
601 _TIFFfreeExt(tif, sp->pBuffer);
602 sp->pBuffer = NULL;
603 }
604 sp->buffer_offset = 0;
605 sp->state = 0;
606 }
607
609
610 return 1;
611}
612
613/*
614 * Setup state for decoding a strip.
615 */
633static int TWebPPreDecode(TIFF *tif, uint16_t s)
634{
635 static const char module[] = "TWebPPreDecode";
636 uint32_t segment_width, segment_height;
637 WebPState *sp = DecoderState(tif);
638 (void)s;
639 assert(sp != NULL);
640
641 TWebPGetStrileDimensions(tif, &segment_width, &segment_height);
642
643 if (segment_width > 16383 || segment_height > 16383)
644 {
645 TIFFErrorExtR(tif, module,
646 "WEBP maximum image dimensions are 16383 x 16383.");
647 return 0;
648 }
649
650 if ((sp->state & LSTATE_INIT_DECODE) == 0)
651 tif->tif_setupdecode(tif);
652
653 if (sp->psDecoder != NULL)
654 {
655 WebPIDelete(sp->psDecoder);
656 WebPFreeDecBuffer(&sp->sDecBuffer);
657 sp->psDecoder = NULL;
658 }
659
660 sp->read_error = 0;
661
662 return 1;
663}
664
684static int TWebPSetupEncode(TIFF *tif)
685{
686 static const char module[] = "TWebPSetupEncode";
687 uint16_t nBitsPerSample = tif->tif_dir.td_bitspersample;
688 uint16_t sampleFormat = tif->tif_dir.td_sampleformat;
689
690 WebPState *sp = EncoderState(tif);
691 assert(sp != NULL);
692
694
696 {
697 TIFFErrorExtR(tif, module,
698 "TIFF WEBP requires data to be stored contiguously in "
699 "RGB e.g. RGBRGBRGB "
700#if WEBP_ENCODER_ABI_VERSION >= 0x0100
701 "or RGBARGBARGBA"
702#endif
703 );
704 return 0;
705 }
706
707 /* check band count */
708 if (sp->nSamples != 3
709#if WEBP_ENCODER_ABI_VERSION >= 0x0100
710 && sp->nSamples != 4
711#endif
712 )
713 {
714 TIFFErrorExtR(tif, module,
715 "WEBP driver doesn't support %d bands. Must be 3 (RGB) "
716#if WEBP_ENCODER_ABI_VERSION >= 0x0100
717 "or 4 (RGBA) "
718#endif
719 "bands.",
720 sp->nSamples);
721 return 0;
722 }
723
724 /* check bits per sample and data type */
725 if ((nBitsPerSample != 8) || (sampleFormat != SAMPLEFORMAT_UINT))
726 {
727 TIFFErrorExtR(tif, module, "WEBP driver requires 8 bit unsigned data");
728 return 0;
729 }
730
731 if (sp->state & LSTATE_INIT_DECODE)
732 {
733 WebPIDelete(sp->psDecoder);
734 WebPFreeDecBuffer(&sp->sDecBuffer);
735 sp->psDecoder = NULL;
736 sp->last_y = 0;
737 sp->state = 0;
738 }
739
741
742 if (!WebPPictureInit(&sp->sPicture))
743 {
744 TIFFErrorExtR(tif, module, "Error initializing WebP picture.");
745 return 0;
746 }
747
748 if (!WebPConfigInitInternal(&sp->sEncoderConfig, WEBP_PRESET_DEFAULT,
749 (float)sp->quality_level,
750 WEBP_ENCODER_ABI_VERSION))
751 {
752 TIFFErrorExtR(tif, module,
753 "Error creating WebP encoder configuration.");
754 return 0;
755 }
756
757// WebPConfigInitInternal above sets lossless to false
758#if WEBP_ENCODER_ABI_VERSION >= 0x0100
759 sp->sEncoderConfig.lossless = sp->lossless;
760 if (sp->lossless)
761 {
762 sp->sPicture.use_argb = 1;
763#if WEBP_ENCODER_ABI_VERSION >= 0x0209
764 sp->sEncoderConfig.exact = sp->lossless_exact;
765#endif
766 }
767#endif
768
769 if (!WebPValidateConfig(&sp->sEncoderConfig))
770 {
771 TIFFErrorExtR(tif, module, "Error with WebP encoder configuration.");
772 return 0;
773 }
774
775 return 1;
776}
777
778/*
779 * Reset encoding state at the start of a strip.
780 */
801static int TWebPPreEncode(TIFF *tif, uint16_t s)
802{
803 static const char module[] = "TWebPPreEncode";
804 uint32_t segment_width, segment_height;
805 WebPState *sp = EncoderState(tif);
806
807 (void)s;
808
809 assert(sp != NULL);
810 if (sp->state != LSTATE_INIT_ENCODE && !tif->tif_setupencode(tif))
811 return 0;
812
813 TWebPGetStrileDimensions(tif, &segment_width, &segment_height);
814
815 if (segment_width > 16383 || segment_height > 16383)
816 {
817 TIFFErrorExtR(tif, module,
818 "WEBP maximum image dimensions are 16383 x 16383.");
819 return 0;
820 }
821
822 /* set up buffer for raw data */
823 /* given above check and that nSamples <= 4, buffer_size is <= 1 GB */
824 sp->buffer_size = segment_width * segment_height * sp->nSamples;
825
826 if (sp->pBuffer != NULL)
827 {
828 _TIFFfreeExt(tif, sp->pBuffer);
829 sp->pBuffer = NULL;
830 }
831
832 sp->pBuffer = (uint8_t *)_TIFFmallocExt(tif, sp->buffer_size);
833 if (!sp->pBuffer)
834 {
835 TIFFErrorExtR(tif, module, "Cannot allocate buffer");
836 return 0;
837 }
838 sp->buffer_offset = 0;
839
840 sp->sPicture.width = (int)segment_width;
841 sp->sPicture.height = (int)segment_height;
842 sp->sPicture.writer = TWebPDatasetWriter;
843 sp->sPicture.custom_ptr = tif;
844
845 return 1;
846}
847
848/*
849 * Finish off an encoded strip by flushing it.
850 */
870static int TWebPPostEncode(TIFF *tif)
871{
872 static const char module[] = "TWebPPostEncode";
873 int64_t stride;
874 WebPState *sp = EncoderState(tif);
875 assert(sp != NULL);
876
877 if (sp->state != LSTATE_INIT_ENCODE)
878 {
879 TIFFErrorExtR(tif, module,
880 "WebP codec state is not initialized for encoding");
881 return 0;
882 }
883
884 stride = (int64_t)sp->sPicture.width * sp->nSamples;
885
886 /* The whole buffer is compressed below. If fewer bytes than a full
887 * strip/tile were written, clear the rest instead of compressing
888 * uninitialized memory into the file. The state check above ensures
889 * this is the encode buffer, not a decode buffer left by switching to
890 * reading on an "r+" handle. */
891 if (sp->pBuffer != NULL && sp->buffer_offset < sp->buffer_size)
892 memset(sp->pBuffer + sp->buffer_offset, 0,
893 sp->buffer_size - sp->buffer_offset);
894
895#if WEBP_ENCODER_ABI_VERSION >= 0x0100
896 if (sp->nSamples == 4)
897 {
898 if (!WebPPictureImportRGBA(&sp->sPicture, sp->pBuffer, (int)stride))
899 {
900 TIFFErrorExtR(tif, module, "WebPPictureImportRGBA() failed");
901 return 0;
902 }
903 }
904 else
905#endif
906 if (!WebPPictureImportRGB(&sp->sPicture, sp->pBuffer, (int)stride))
907 {
908 TIFFErrorExtR(tif, module, "WebPPictureImportRGB() failed");
909 return 0;
910 }
911
912 if (!WebPEncode(&sp->sEncoderConfig, &sp->sPicture))
913 {
914
915#if WEBP_ENCODER_ABI_VERSION >= 0x0100
916 const char *pszErrorMsg = NULL;
917 switch (sp->sPicture.error_code)
918 {
919 case VP8_ENC_ERROR_OUT_OF_MEMORY:
920 pszErrorMsg = "Out of memory";
921 break;
922 case VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY:
923 pszErrorMsg = "Out of memory while flushing bits";
924 break;
925 case VP8_ENC_ERROR_NULL_PARAMETER:
926 pszErrorMsg = "A pointer parameter is NULL";
927 break;
928 case VP8_ENC_ERROR_INVALID_CONFIGURATION:
929 pszErrorMsg = "Configuration is invalid";
930 break;
931 case VP8_ENC_ERROR_BAD_DIMENSION:
932 pszErrorMsg = "Picture has invalid width/height";
933 break;
934 case VP8_ENC_ERROR_PARTITION0_OVERFLOW:
935 pszErrorMsg = "Partition is bigger than 512k. Try using less "
936 "SEGMENTS, or increase PARTITION_LIMIT value";
937 break;
938 case VP8_ENC_ERROR_PARTITION_OVERFLOW:
939 pszErrorMsg = "Partition is bigger than 16M";
940 break;
941 case VP8_ENC_ERROR_BAD_WRITE:
942 pszErrorMsg = "Error while fludshing bytes";
943 break;
944 case VP8_ENC_ERROR_FILE_TOO_BIG:
945 pszErrorMsg = "File is bigger than 4G";
946 break;
947 case VP8_ENC_ERROR_USER_ABORT:
948 pszErrorMsg = "User interrupted";
949 break;
950 case VP8_ENC_OK:
951 case VP8_ENC_ERROR_LAST:
952 default:
953 TIFFErrorExtR(tif, module,
954 "WebPEncode returned an unknown error code: %u",
955 sp->sPicture.error_code);
956 pszErrorMsg = "Unknown WebP error type.";
957 break;
958 }
959 TIFFErrorExtR(tif, module, "WebPEncode() failed : %s", pszErrorMsg);
960#else
961 TIFFErrorExtR(tif, module, "Error in WebPEncode()");
962#endif
963 return 0;
964 }
965
966 sp->sPicture.custom_ptr = NULL;
967
968 if (!TIFFFlushData1(tif))
969 {
970 TIFFErrorExtR(tif, module, "Error flushing TIFF WebP encoder.");
971 return 0;
972 }
973
974 return 1;
975}
976
991static void TWebPCleanup(TIFF *tif)
992{
993 WebPState *sp = LState(tif);
994
995 assert(sp != 0);
996
999
1000 if (sp->state & LSTATE_INIT_ENCODE)
1001 {
1002 WebPPictureFree(&sp->sPicture);
1003 }
1004
1005 if (sp->psDecoder != NULL)
1006 {
1007 WebPIDelete(sp->psDecoder);
1008 WebPFreeDecBuffer(&sp->sDecBuffer);
1009 sp->psDecoder = NULL;
1010 sp->last_y = 0;
1011 }
1012
1013 if (sp->pBuffer != NULL)
1014 {
1015 _TIFFfreeExt(tif, sp->pBuffer);
1016 sp->pBuffer = NULL;
1017 }
1018
1019 _TIFFfreeExt(tif, tif->tif_data);
1020 tif->tif_data = NULL;
1021
1023}
1024
1045static int TWebPVSetField(TIFF *tif, uint32_t tag, va_list ap)
1046{
1047 static const char module[] = "TWebPVSetField";
1048 WebPState *sp = LState(tif);
1049
1050 switch (tag)
1051 {
1052 case TIFFTAG_WEBP_LEVEL:
1053 sp->quality_level = (int)va_arg(ap, int);
1054 if (sp->quality_level <= 0 || sp->quality_level > 100)
1055 {
1056 TIFFWarningExtR(tif, module,
1057 "WEBP_LEVEL should be between 1 and 100");
1058 }
1059 return 1;
1061#if WEBP_ENCODER_ABI_VERSION >= 0x0100
1062 sp->lossless = va_arg(ap, int);
1063 if (sp->lossless)
1064 {
1065 sp->quality_level = 100;
1066 }
1067 return 1;
1068#else
1070 tif, module,
1071 "Need to upgrade WEBP driver, this version doesn't support "
1072 "lossless compression.");
1073 return 0;
1074#endif
1076#if WEBP_ENCODER_ABI_VERSION >= 0x0209
1077 sp->lossless_exact = va_arg(ap, int);
1078 return 1;
1079#else
1081 tif, module,
1082 "Need to upgrade WEBP driver, this version doesn't support "
1083 "lossless compression.");
1084 return 0;
1085#endif
1086 default:
1087 return (*sp->vsetparent)(tif, tag, ap);
1088 }
1089 /*NOTREACHED*/
1090}
1091
1108static int TWebPVGetField(TIFF *tif, uint32_t tag, va_list ap)
1109{
1110 WebPState *sp = LState(tif);
1111
1112 switch (tag)
1113 {
1114 case TIFFTAG_WEBP_LEVEL:
1115 *va_arg(ap, int *) = sp->quality_level;
1116 break;
1118 *va_arg(ap, int *) = sp->lossless;
1119 break;
1121 *va_arg(ap, int *) = sp->lossless_exact;
1122 break;
1123 default:
1124 return (*sp->vgetparent)(tif, tag, ap);
1125 }
1126 return 1;
1127}
1128
1136static const TIFFField TWebPFields[] = {
1138 FALSE, "WEBP quality", NULL},
1140 TRUE, FALSE, "WEBP lossless/lossy", NULL},
1142 FIELD_PSEUDO, TRUE, FALSE, "WEBP exact lossless", NULL},
1143};
1144
1157{
1158 /* See README_for_libtiff_developpers.md for raw data used to estimate
1159 * the maximum compression rate. */
1160
1161 /* lossy compression: */
1162 /* return (tif->tif_dir.td_samplesperpixel == 4) ? 2199 : 1685; */
1163 /* lossless compression: */
1164 return (tif->tif_dir.td_samplesperpixel == 4) ? 104194 : 78146;
1165}
1166
1167int TIFFInitWebP(TIFF *tif, int scheme)
1168{
1169 static const char module[] = "TIFFInitWebP";
1170 WebPState *sp;
1171
1172 (void)scheme;
1173 assert(scheme == COMPRESSION_WEBP);
1174
1175 /*
1176 * Merge codec-specific tag information.
1177 */
1179 {
1180 TIFFErrorExtR(tif, module, "Merging WebP codec-specific tags failed");
1181 return 0;
1182 }
1183
1184 /*
1185 * Allocate state block so tag methods have storage to record values.
1186 */
1187 tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(WebPState));
1188 if (tif->tif_data == NULL)
1189 goto bad;
1190 sp = LState(tif);
1191
1192 /*
1193 * Override parent get/set field methods.
1194 */
1195 sp->vgetparent = tif->tif_tagmethods.vgetfield;
1196 tif->tif_tagmethods.vgetfield = TWebPVGetField; /* hook for codec tags */
1197 sp->vsetparent = tif->tif_tagmethods.vsetfield;
1198 tif->tif_tagmethods.vsetfield = TWebPVSetField; /* hook for codec tags */
1199
1200 /* Default values for codec-specific fields */
1201 sp->quality_level = 75; /* default comp. level */
1202 sp->lossless = 0; /* default to false */
1203 sp->lossless_exact = 1; /* exact lossless mode (if lossless enabled) */
1204 sp->state = 0;
1205 sp->nSamples = 0;
1206 sp->psDecoder = NULL;
1207 sp->last_y = 0;
1208
1209 sp->buffer_offset = 0;
1210 sp->pBuffer = NULL;
1211
1212 /*
1213 * Install codec methods.
1214 * Notes:
1215 * encoderow is not supported
1216 */
1231
1232 return 1;
1233bad:
1234 TIFFErrorExtR(tif, module, "No space for WebP state block");
1235 return 0;
1236}
1237
1238#endif /* WEBP_SUPPORT */
1239
void _TIFFSetDefaultCompressionState(TIFF *tif)
Install fallback codec callbacks and reset raw-access flags.
#define TIFF_SIZE_FORMAT
Provide the printf conversion fragment for size_t, without a percent sign.
Definition tif_config.h:287
int _TIFFMergeFields(TIFF *tif, const TIFFField info[], uint32_t n)
Merge borrowed field definitions into the lookup table.
#define FIELD_PSEUDO
Share bit zero with FIELD_IGNORE for pseudo-tags.
Definition tif_dir.h:620
@ TIFF_SETGET_INT
Promoted int scalar representation.
Definition tif_dir.h:762
int TIFFFlushData1(TIFF *tif)
Append buffered encoded bytes without invoking postencode recursively.
Definition tif_write.c:1213
void _TIFFfreeExt(TIFF *tif, void *p)
Release a handle-aware allocation and its payload charge.
Definition tif_open.c:301
void * _TIFFmallocExt(TIFF *tif, tmsize_t s)
Allocate uninitialised bytes under a handle's allocation policy.
Definition tif_open.c:195
#define isTiled(tif)
Test whether a handle uses tiled storage.
Definition tiffiop.h:833
#define TRUE
Represent the legacy internal true value.
Definition tiffiop.h:131
#define FALSE
Represent the legacy internal false value.
Definition tiffiop.h:136
#define TIFFArrayCount(a)
Compute the element count of an actual array.
Definition tiffiop.h:1239
static int TWebPPreDecode(TIFF *tif, uint16_t s)
Reset WebP per-strile decode state and error latch.
Definition tif_webp.c:633
static int TWebPPreEncode(TIFF *tif, uint16_t s)
Allocate full-strile WebP input staging and attach the output writer.
Definition tif_webp.c:801
static int TWebPDatasetWriter(const uint8_t *data, size_t data_size, const WebPPicture *const picture)
Append one dependency output fragment to the raw TIFF buffer.
Definition tif_webp.c:172
#define EncoderState(tif)
Alias of LState(), returning the WebPState for encoding.
Definition tif_webp.c:118
static int TWebPSetupEncode(TIFF *tif)
Validate WebP input and initialise picture and encoder configuration.
Definition tif_webp.c:684
static int TWebPSetupDecode(TIFF *tif)
Validate WebP channel support and enter decode mode.
Definition tif_webp.c:560
static int TWebPVGetField(TIFF *tif, uint32_t tag, va_list ap)
Retrieve WebP quality or lossless settings or delegate a tag.
Definition tif_webp.c:1108
#define DecoderState(tif)
Alias of LState(), returning the WebPState for decoding.
Definition tif_webp.c:117
#define LState(tif)
Cast tif->tif_data to the WebPState.
Definition tif_webp.c:116
static int TWebPVSetField(TIFF *tif, uint32_t tag, va_list ap)
Store WebP quality lossless settings or delegate another tag.
Definition tif_webp.c:1045
static int TWebPPostEncode(TIFF *tif)
Import staged RGB or RGBA encode it and flush the WebP frame.
Definition tif_webp.c:870
#define LSTATE_INIT_ENCODE
Bit 0x02 of the codec state field: encoding has been set up.
Definition tif_webp.c:46
static int TWebPDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
Decode a WebP strile or retrieve its next decoded rows.
Definition tif_webp.c:275
static uint64_t TWebPGetMaxCompressionRatio(TIFF *tif)
Report the channel-dependent WebP expansion heuristic.
Definition tif_webp.c:1156
static const TIFFField TWebPFields[]
Define WebP quality lossless and exact pseudo-tags.
Definition tif_webp.c:1136
static void TWebPGetStrileDimensions(const TIFF *tif, uint32_t *width, uint32_t *height)
Compute the pixel extent of the current strip or tile.
Definition tif_webp.c:136
#define LSTATE_INIT_DECODE
Bit 0x01 of the codec state field: decoding has been set up.
Definition tif_webp.c:45
static int TWebPEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
Accumulate decoded WebP input in the strile staging buffer.
Definition tif_webp.c:221
static int TWebPFixupTags(TIFF *tif)
Reject noncontiguous WebP sample organisation.
Definition tif_webp.c:526
static void TWebPCleanup(TIFF *tif)
Release WebP picture decoder staging and outer codec state.
Definition tif_webp.c:991
int TIFFInitWebP(TIFF *tif, int scheme)
Allocate WebP codec state and install buffered frame callbacks.
Definition tif_webp.c:1167
#define TIFF_ANY
Match any data type when searching for a field descriptor.
Definition tiffio.h:1289
void TIFFWarningExtR(TIFF *tif, const char *module, const char *fmt,...)
Dispatch a warning diagnostic to the configured handlers.
Definition tif_warning.c:85
void TIFFErrorExtR(TIFF *tif, const char *module, const char *fmt,...)
Dispatch a error diagnostic to the configured handlers.
Definition tif_error.c:112
void _TIFFmemcpy(void *d, const void *s, tmsize_t c)
Copy a non-overlapping byte range.
Definition tif_unix.c:497
#define TIFFTAG_WEBP_LEVEL
Pseudo-tag: WebP quality setting.
Definition tiff.h:1657
#define TIFFTAG_WEBP_LOSSLESS_EXACT
Pseudo-tag: Preserve RGB values under fully transparent pixels in lossless WebP.
Definition tiff.h:1669
#define TIFFTAG_WEBP_LOSSLESS
Pseudo-tag: WebP lossless/lossy.
Definition tiff.h:1659
int(* TIFFVGetMethod)(TIFF *tif, uint32_t tag, va_list ap)
Implement a handle's variadic tag getter.
Definition tiffio.h:1540
int(* TIFFVSetMethod)(TIFF *tif, uint32_t tag, va_list ap)
Implement a handle's variadic tag setter.
Definition tiffio.h:1521
#define SAMPLEFORMAT_UINT
Unsigned integer data (introduced in TIFF 6.0).
Definition tiff.h:610
#define COMPRESSION_WEBP
WebP compression; not registered in the Adobe-maintained registry.
Definition tiff.h:374
#define PLANARCONFIG_CONTIG
Single image plane.
Definition tiff.h:472
TIFF_SSIZE_T tmsize_t
Represent a signed memory or I/O size in bytes.
Definition tiffio.h:89
Store the current directory values and image traversal state.
Definition tif_dir.h:143
uint32_t td_rowsperstrip
Rows per strip; UINT32_MAX represents one whole-image strip.
Definition tif_dir.h:184
uint32_t td_imagewidth
Image width in pixels.
Definition tif_dir.h:154
uint32_t td_tilewidth
Tile width in pixels.
Definition tif_dir.h:160
uint16_t td_bitspersample
Bits in each sample.
Definition tif_dir.h:168
uint32_t td_row
Current scanline index; UINT32_MAX before traversal starts.
Definition tif_dir.h:240
uint16_t td_planarconfig
PLANARCONFIG_* sample-plane arrangement.
Definition tif_dir.h:200
uint16_t td_sampleformat
SAMPLEFORMAT_* interpretation of samples.
Definition tif_dir.h:170
uint16_t td_samplesperpixel
Samples per pixel, including extra samples.
Definition tif_dir.h:182
uint32_t td_imagelength
Image length in rows.
Definition tif_dir.h:156
uint32_t td_tilelength
Tile length in rows.
Definition tif_dir.h:162
TIFFVGetMethod vgetfield
Variadic tag-query implementation for the handle.
Definition tiffio.h:1577
TIFFVSetMethod vsetfield
Variadic tag-setting implementation for the handle.
Definition tiffio.h:1575
Own WebP frame staging dependency objects and saved tag methods.
Definition tif_webp.c:60
WebPPicture sPicture
Embedded dependency picture owning imported samples until WebPPictureFree.
Definition tif_webp.c:82
unsigned int buffer_size
Staging capacity in bytes, bounded by validated frame dimensions.
Definition tif_webp.c:95
TIFFVGetMethod vgetparent
Borrowed parent getter restored on cleanup.
Definition tif_webp.c:111
WebPDecBuffer sDecBuffer
External-memory descriptor borrowing pBuffer or caller whole-strile output.
Definition tif_webp.c:103
int quality_level
Cached compression quality, including warned out-of-range assignments.
Definition tif_webp.c:77
TIFFVSetMethod vsetparent
Borrowed parent setter restored on cleanup.
Definition tif_webp.c:113
uint16_t nSamples
Cached RGB/RGBA channel count.
Definition tif_webp.c:62
int read_error
Same-strile decode failure latch reset by predecode.
Definition tif_webp.c:65
WebPConfig sEncoderConfig
Embedded dependency encoder configuration.
Definition tif_webp.c:84
int lossless
Cached lossless option applied at encoder setup.
Definition tif_webp.c:67
WebPIDecoder * psDecoder
Owned incremental dependency decoder, released by WebPIDelete.
Definition tif_webp.c:98
uint8_t * pBuffer
Owned Ext full-strile input/output staging, released on replacement/cleanup.
Definition tif_webp.c:89
unsigned int buffer_offset
Number of staged input bytes.
Definition tif_webp.c:91
int state
Decode/encode initialisation flags.
Definition tif_webp.c:108
int lossless_exact
Cached preservation of RGB under zero alpha in supported lossless ABI.
Definition tif_webp.c:72
int last_y
Number of decoded rows already returned.
Definition tif_webp.c:105
Describe a field's file type and internal argument contract.
Definition tif_dir.h:993
Hold private state for one open TIFF library instance.
Definition tiffiop.h:389
TIFFCodeMethod tif_encodestrip
Codec callback encoding strip data.
Definition tiffiop.h:649
TIFFCodeMethod tif_encodetile
Codec callback encoding tile data.
Definition tiffiop.h:653
TIFFTagMethods tif_tagmethods
Inline table of directory field and print callbacks.
Definition tiffiop.h:742
TIFFPreMethod tif_preencode
Codec callback preparing a row, strip, or tile encode.
Definition tiffiop.h:639
TIFFBoolMethod tif_fixuptags
Codec callback for directory-dependent tag corrections.
Definition tiffiop.h:626
tmsize_t tif_rawcc
Raw-buffer byte count interpreted according to read/write state.
Definition tiffiop.h:696
TIFFPreMethod tif_predecode
Codec callback preparing a row, strip, or tile decode.
Definition tiffiop.h:630
TIFFCodeMethod tif_decodestrip
Codec callback decoding strip data.
Definition tiffiop.h:647
TIFFGetMaxCompressionRatioMethod tif_getmaxcompressionratio
Codec callback returning its maximum compression ratio.
Definition tiffiop.h:670
TIFFCodeMethod tif_decoderow
Codec callback decoding a scanline.
Definition tiffiop.h:643
TIFFBoolMethod tif_setupencode
Codec setup callback run before preencode.
Definition tiffiop.h:632
TIFFDirectory tif_dir
Inline representation of the current image directory.
Definition tiffiop.h:572
TIFFBoolMethod tif_postencode
Codec callback completing buffered encoding.
Definition tiffiop.h:641
TIFFCodeMethod tif_encoderow
Codec callback encoding a scanline.
Definition tiffiop.h:645
TIFFVoidMethod tif_cleanup
Codec callback releasing codec-private state.
Definition tiffiop.h:661
uint8_t * tif_data
Codec-private storage; allocation and cleanup follow the selected codec.
Definition tiffiop.h:675
uint8_t * tif_rawcp
Borrowed current-position pointer into the raw buffer.
Definition tiffiop.h:692
TIFFBoolMethod tif_setupdecode
Codec setup callback run before predecode.
Definition tiffiop.h:628
TIFFCodeMethod tif_decodetile
Codec callback decoding tile data.
Definition tiffiop.h:651
Declare private library state, callbacks, and implementation helpers.