LibTIFF 4.7.2
TIFF library public API and implementation reference
Loading...
Searching...
No Matches
tif_lerc.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2018, Even Rouault
3 * Author: <even.rouault at spatialys.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 LERC_SUPPORT
32/*
33 * TIFF Library.
34 *
35 * LERC Compression Support
36 *
37 */
38
39#include "Lerc_c_api.h"
40#include "zlib.h"
41#include <math.h>
42#ifdef ZSTD_SUPPORT
43#include "zstd.h"
44#endif
45
46#if LIBDEFLATE_SUPPORT
47#include "libdeflate.h"
48#endif
49#define LIBDEFLATE_MAX_COMPRESSION_LEVEL 12
50
51#include <assert.h>
52
53#define LSTATE_INIT_DECODE 0x01
54#define LSTATE_INIT_ENCODE 0x02
55
56#ifndef LERC_AT_LEAST_VERSION
57#define LERC_AT_LEAST_VERSION(maj, min, patch) 0
58#endif
59
60/*
61 * State block for each open TIFF file using LERC compression/decompression.
62 */
71typedef struct
72{
77 double maxzerror;
89 int state;
90
92 uint32_t segment_width;
95
97 unsigned int uncompressed_size;
102 unsigned int uncompressed_alloc;
110
115
117 unsigned int mask_size;
119 uint8_t *mask_buffer;
120
122 unsigned int compressed_size;
125
126#if LIBDEFLATE_SUPPORT
131 struct libdeflate_decompressor *libdeflate_dec;
136 struct libdeflate_compressor *libdeflate_enc;
137#endif
138
143} LERCState;
144
145#define GetLERCState(tif) ((LERCState *)(tif)->tif_data)
146#define LERCDecoderState(tif) GetLERCState(tif)
147#define LERCEncoderState(tif) GetLERCState(tif)
148
149static int LERCDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s);
150
160static int LERCFixupTags(TIFF *tif)
161{
162 (void)tif;
163 return 1;
164}
165
178static int LERCSetupDecode(TIFF *tif)
179{
180 LERCState *sp = LERCDecoderState(tif);
181
182 assert(sp != NULL);
183
184 /* if we were last encoding, terminate this mode */
185 if (sp->state & LSTATE_INIT_ENCODE)
186 {
187 sp->state = 0;
188 }
189
191 return 1;
192}
193
207static int GetLercDataType(TIFF *tif)
208{
209 TIFFDirectory *td = &tif->tif_dir;
210 static const char module[] = "GetLercDataType";
211
213 {
214 return 0;
215 }
216
218 {
219 return 1;
220 }
221
222 if (td->td_sampleformat == SAMPLEFORMAT_INT && td->td_bitspersample == 16)
223 {
224 return 2;
225 }
226
227 if (td->td_sampleformat == SAMPLEFORMAT_UINT && td->td_bitspersample == 16)
228 {
229 return 3;
230 }
231
232 if (td->td_sampleformat == SAMPLEFORMAT_INT && td->td_bitspersample == 32)
233 {
234 return 4;
235 }
236
237 if (td->td_sampleformat == SAMPLEFORMAT_UINT && td->td_bitspersample == 32)
238 {
239 return 5;
240 }
241
243 td->td_bitspersample == 32)
244 {
245 return 6;
246 }
247
249 td->td_bitspersample == 64)
250 {
251 return 7;
252 }
253
255 tif, module,
256 "Unsupported combination of SampleFormat and td_bitspersample");
257 return -1;
258}
259
283static int SetupBuffers(TIFF *tif, LERCState *sp, const char *module)
284{
285 TIFFDirectory *td = &tif->tif_dir;
286 uint64_t new_size_64;
287 uint64_t new_alloc_64;
288 unsigned int new_size;
289 unsigned int new_alloc;
290
291 sp->uncompressed_offset = 0;
292
293 if (isTiled(tif))
294 {
295 sp->segment_width = td->td_tilewidth;
297 }
298 else
299 {
302 if (sp->segment_height > td->td_rowsperstrip)
304 }
305
306 new_size_64 = (uint64_t)sp->segment_width * sp->segment_height *
307 (td->td_bitspersample / 8);
309 {
310 new_size_64 *= td->td_samplesperpixel;
311 }
312
313 /* The narrowing below has no check of its own; make it explicit rather
314 * than relying on the allocation-size check further down. */
315 if (new_size_64 > UINT_MAX)
316 {
317 TIFFErrorExtR(tif, module, "Too large uncompressed strip/tile");
318 return 0;
319 }
320
321 new_size = (unsigned int)new_size_64;
322 sp->uncompressed_size = new_size;
323
324 /* add some margin as we are going to use it also to store deflate/zstd
325 * compressed data. We also need extra margin when writing very small
326 * rasters with one mask per band. */
327 new_alloc_64 = 256 + new_size_64 + new_size_64 / 3;
328#ifdef ZSTD_SUPPORT
329 {
330 size_t zstd_max = ZSTD_compressBound((size_t)new_size_64);
331 if (new_alloc_64 < zstd_max)
332 {
333 new_alloc_64 = zstd_max;
334 }
335 }
336#endif
337 new_alloc = (unsigned int)new_alloc_64;
338 if (new_alloc != new_alloc_64)
339 {
340 TIFFErrorExtR(tif, module, "Too large uncompressed strip/tile");
342 sp->uncompressed_buffer = NULL;
343 sp->uncompressed_alloc = 0;
344 return 0;
345 }
346
347 if (sp->uncompressed_alloc < new_alloc)
348 {
350 sp->uncompressed_buffer = (uint8_t *)_TIFFmallocExt(tif, new_alloc);
351 if (!sp->uncompressed_buffer)
352 {
353 TIFFErrorExtR(tif, module, "Cannot allocate buffer");
355 sp->uncompressed_buffer = NULL;
356 sp->uncompressed_alloc = 0;
357 return 0;
358 }
359 sp->uncompressed_alloc = new_alloc;
360 }
361
363 td->td_extrasamples > 0 && td->td_sampleinfo &&
365 GetLercDataType(tif) == 1) ||
367 (td->td_bitspersample == 32 || td->td_bitspersample == 64)))
368 {
369 unsigned int mask_size =
370 _TIFFMultiply32(tif, sp->segment_width, sp->segment_height, module);
371 if (mask_size == 0)
372 return 0;
373#if LERC_AT_LEAST_VERSION(3, 0, 0)
376 {
377 /* We may need one mask per band */
378 mask_size =
379 _TIFFMultiply32(tif, mask_size, td->td_samplesperpixel, module);
380 if (mask_size == 0)
381 return 0;
382 }
383#endif
384 if (sp->mask_size < mask_size)
385 {
386 void *mask_buffer =
387 _TIFFreallocExt(tif, sp->mask_buffer, mask_size);
388 if (mask_buffer == NULL)
389 {
390 TIFFErrorExtR(tif, module, "Cannot allocate buffer");
391 sp->mask_size = 0;
393 sp->uncompressed_buffer = NULL;
394 sp->uncompressed_alloc = 0;
395 return 0;
396 }
397 sp->mask_buffer = (uint8_t *)mask_buffer;
398 sp->mask_size = mask_size;
399 }
400 }
401
402 return 1;
403}
404
405/*
406 * Setup state for decoding a strip.
407 */
433static int LERCPreDecode(TIFF *tif, uint16_t s)
434{
435 static const char module[] = "LERCPreDecode";
436 lerc_status lerc_ret;
437 TIFFDirectory *td = &tif->tif_dir;
438 LERCState *sp = LERCDecoderState(tif);
439 int lerc_data_type;
440 unsigned int infoArray[9];
441 unsigned nomask_bands = td->td_samplesperpixel;
442 int ndims;
443 int use_mask = 0;
444 uint8_t *lerc_data = tif->tif_rawcp;
445 unsigned int lerc_data_size = (unsigned int)tif->tif_rawcc;
446
447 (void)s;
448 assert(sp != NULL);
449 if (sp->state != LSTATE_INIT_DECODE)
450 tif->tif_setupdecode(tif);
451
452 lerc_data_type = GetLercDataType(tif);
453 if (lerc_data_type < 0)
454 return 0;
455
456 if (!SetupBuffers(tif, sp, module))
457 return 0;
458
460 {
462 {
465 if (!sp->compressed_buffer)
466 {
467 sp->compressed_size = 0;
468 return 0;
469 }
471 }
472 }
473
475 {
476#if LIBDEFLATE_SUPPORT
477 enum libdeflate_result res;
478 size_t lerc_data_sizet = 0;
479 if (sp->libdeflate_dec == NULL)
480 {
481 sp->libdeflate_dec = libdeflate_alloc_decompressor();
482 if (sp->libdeflate_dec == NULL)
483 {
484 TIFFErrorExtR(tif, module, "Cannot allocate decompressor");
485 return 0;
486 }
487 }
488
489 res = libdeflate_zlib_decompress(
490 sp->libdeflate_dec, tif->tif_rawcp, (size_t)tif->tif_rawcc,
491 sp->compressed_buffer, sp->compressed_size, &lerc_data_sizet);
492 if (res != LIBDEFLATE_SUCCESS)
493 {
494 TIFFErrorExtR(tif, module, "Decoding error at scanline %lu",
495 (unsigned long)tif->tif_dir.td_row);
496 return 0;
497 }
498 assert(lerc_data_sizet == (unsigned int)lerc_data_sizet);
499 lerc_data = (uint8_t *)sp->compressed_buffer;
500 lerc_data_size = (unsigned int)lerc_data_sizet;
501#else
502 z_stream strm;
503 int zlib_ret;
504
505 memset(&strm, 0, sizeof(strm));
506 strm.zalloc = NULL;
507 strm.zfree = NULL;
508 strm.opaque = NULL;
509 zlib_ret = inflateInit(&strm);
510 if (zlib_ret != Z_OK)
511 {
512 TIFFErrorExtR(tif, module, "inflateInit() failed");
513 inflateEnd(&strm);
514 return 0;
515 }
516
517 strm.avail_in = (uInt)tif->tif_rawcc;
518 strm.next_in = tif->tif_rawcp;
519 strm.avail_out = sp->compressed_size;
520 strm.next_out = (Bytef *)sp->compressed_buffer;
521 zlib_ret = inflate(&strm, Z_FINISH);
522 if (zlib_ret != Z_STREAM_END && zlib_ret != Z_OK)
523 {
524 TIFFErrorExtR(tif, module, "inflate() failed");
525 inflateEnd(&strm);
526 return 0;
527 }
528 lerc_data = (uint8_t *)sp->compressed_buffer;
529 lerc_data_size = sp->compressed_size - strm.avail_out;
530 inflateEnd(&strm);
531#endif
532 }
534 {
535#ifdef ZSTD_SUPPORT
536 size_t zstd_ret;
537
538 zstd_ret = ZSTD_decompress(sp->compressed_buffer, sp->compressed_size,
539 tif->tif_rawcp, (size_t)tif->tif_rawcc);
540 if (ZSTD_isError(zstd_ret))
541 {
542 TIFFErrorExtR(tif, module, "Error in ZSTD_decompress(): %s",
543 ZSTD_getErrorName(zstd_ret));
544 return 0;
545 }
546
547 lerc_data = (uint8_t *)sp->compressed_buffer;
548 lerc_data_size = (unsigned int)zstd_ret;
549#else
550 TIFFErrorExtR(tif, module, "ZSTD support missing");
551 return 0;
552#endif
553 }
555 {
556 TIFFErrorExtR(tif, module, "Unhandled additional compression");
557 return 0;
558 }
559
560 lerc_ret =
561 lerc_getBlobInfo(lerc_data, lerc_data_size, infoArray, NULL, 9, 0);
562 if (lerc_ret != 0)
563 {
564 TIFFErrorExtR(tif, module, "lerc_getBlobInfo() failed");
565 return 0;
566 }
567
568 /* If the configuration is compatible of a LERC mask, and that the */
569 /* LERC info has dim == samplesperpixel - 1, then there is a LERC */
570 /* mask. */
572 td->td_sampleinfo &&
574 GetLercDataType(tif) == 1 &&
575 infoArray[2] == td->td_samplesperpixel - 1U)
576 {
577 use_mask = 1;
578 nomask_bands--;
579 }
580 else if (td->td_sampleformat == SAMPLEFORMAT_IEEEFP)
581 {
582 use_mask = 1;
583 }
584
585 ndims =
586 (int)(td->td_planarconfig == PLANARCONFIG_CONTIG ? nomask_bands : 1);
587
588 /* Info returned in infoArray is { version, dataType, nDim/nDepth, nCols,
589 nRows, nBands, nValidPixels, blobSize,
590 and starting with liblerc 3.0 nRequestedMasks } */
591 if (infoArray[0] != (unsigned)sp->lerc_version)
592 {
593 TIFFWarningExtR(tif, module,
594 "Unexpected version number: %u. Expected: %d",
595 infoArray[0], sp->lerc_version);
596 }
597 if (infoArray[1] != (unsigned)lerc_data_type)
598 {
599 TIFFErrorExtR(tif, module, "Unexpected dataType: %u. Expected: %d",
600 infoArray[1], lerc_data_type);
601 return 0;
602 }
603
604 const unsigned nFoundDims = infoArray[2];
605#if LERC_AT_LEAST_VERSION(3, 0, 0)
608 td->td_samplesperpixel > 1)
609 {
610 if (nFoundDims != 1 && nFoundDims != (unsigned)ndims)
611 {
612 TIFFErrorExtR(tif, module, "Unexpected nDim: %u. Expected: 1 or %d",
613 nFoundDims, ndims);
614 return 0;
615 }
616 }
617 else
618#endif
619 if (nFoundDims != (unsigned)ndims)
620 {
621 TIFFErrorExtR(tif, module, "Unexpected nDim: %u. Expected: %d",
622 nFoundDims, ndims);
623 return 0;
624 }
625
626 if (infoArray[3] != sp->segment_width)
627 {
628 TIFFErrorExtR(tif, module, "Unexpected nCols: %u. Expected: %u",
629 infoArray[3], sp->segment_width);
630 return 0;
631 }
632 if (infoArray[4] != sp->segment_height)
633 {
634 TIFFErrorExtR(tif, module, "Unexpected nRows: %u. Expected: %u",
635 infoArray[4], sp->segment_height);
636 return 0;
637 }
638
639 const unsigned nFoundBands = infoArray[5];
642 td->td_samplesperpixel > 1 && nFoundDims == 1)
643 {
644#if !LERC_AT_LEAST_VERSION(3, 0, 0)
645 if (nFoundBands == td->td_samplesperpixel)
646 {
648 tif, module,
649 "Unexpected nBands: %d. This file may have been generated with "
650 "a liblerc version >= 3.0, with one mask per band, and is not "
651 "supported by this older version of liblerc",
652 nFoundBands);
653 return 0;
654 }
655#endif
656 if (nFoundBands != td->td_samplesperpixel)
657 {
658 TIFFErrorExtR(tif, module, "Unexpected nBands: %u. Expected: %d",
659 nFoundBands, td->td_samplesperpixel);
660 return 0;
661 }
662 }
663 else if (nFoundBands != 1)
664 {
665 TIFFErrorExtR(tif, module, "Unexpected nBands: %u. Expected: %d",
666 nFoundBands, 1);
667 return 0;
668 }
669
670 if (infoArray[7] != lerc_data_size)
671 {
672 TIFFErrorExtR(tif, module, "Unexpected blobSize: %u. Expected: %u",
673 infoArray[7], lerc_data_size);
674 return 0;
675 }
676
677 int nRequestedMasks = use_mask ? 1 : 0;
678#if LERC_AT_LEAST_VERSION(3, 0, 0)
679 const int nFoundMasks = (int)infoArray[8];
682 td->td_samplesperpixel > 1 && nFoundDims == 1)
683 {
684 if (nFoundMasks != 0 && nFoundMasks != td->td_samplesperpixel)
685 {
686 TIFFErrorExtR(tif, module,
687 "Unexpected nFoundMasks: %d. Expected: 0 or %d",
688 nFoundMasks, td->td_samplesperpixel);
689 return 0;
690 }
691 nRequestedMasks = nFoundMasks;
692 }
693 else
694 {
695 if (nFoundMasks != 0 && nFoundMasks != 1)
696 {
697 TIFFErrorExtR(tif, module,
698 "Unexpected nFoundMasks: %d. Expected: 0 or 1",
699 nFoundMasks);
700 return 0;
701 }
702 }
703 if (td->td_sampleformat == SAMPLEFORMAT_IEEEFP && nFoundMasks == 0)
704 {
705 nRequestedMasks = 0;
706 use_mask = 0;
707 }
708#endif
709
710 const unsigned nb_pixels =
711 _TIFFMultiply32(tif, sp->segment_width, sp->segment_height, module);
712 if (nb_pixels == 0)
713 return 0;
714
715#if LERC_AT_LEAST_VERSION(3, 0, 0)
716 if (nRequestedMasks > 1)
717 {
718 unsigned int num_bytes_needed =
719 _TIFFMultiply32(tif, nb_pixels, td->td_samplesperpixel, module);
720 if (num_bytes_needed == 0)
721 return 0;
722 num_bytes_needed =
723 _TIFFMultiply32(tif, num_bytes_needed,
724 (uint32_t)(td->td_bitspersample / 8), module);
725 if (num_bytes_needed == 0)
726 return 0;
727 if (sp->uncompressed_buffer_multiband_alloc < num_bytes_needed)
728 {
731 (uint8_t *)_TIFFmallocExt(tif, num_bytes_needed);
733 {
735 return 0;
736 }
737 sp->uncompressed_buffer_multiband_alloc = num_bytes_needed;
738 }
739 lerc_ret = lerc_decode(lerc_data, lerc_data_size, nRequestedMasks,
740 sp->mask_buffer, (int)nFoundDims,
741 (int)sp->segment_width, (int)sp->segment_height,
742 (int)nFoundBands, (unsigned int)lerc_data_type,
744 }
745 else
746#endif
747 {
748 lerc_ret = lerc_decode(
749 lerc_data, lerc_data_size,
750#if LERC_AT_LEAST_VERSION(3, 0, 0)
751 nRequestedMasks,
752#endif
753 use_mask ? sp->mask_buffer : NULL, (int)nFoundDims,
754 (int)sp->segment_width, (int)sp->segment_height, (int)nFoundBands,
755 (unsigned int)lerc_data_type, sp->uncompressed_buffer);
756 }
757 if (lerc_ret != 0)
758 {
759 TIFFErrorExtR(tif, module, "lerc_decode() failed");
760 return 0;
761 }
762
763 /* Interleave alpha mask with other samples. */
764 if (use_mask && GetLercDataType(tif) == 1)
765 {
766 unsigned src_stride = (unsigned int)((td->td_samplesperpixel - 1) *
767 (td->td_bitspersample / 8));
768 unsigned dst_stride =
769 (unsigned int)(td->td_samplesperpixel * (td->td_bitspersample / 8));
770 unsigned i = nb_pixels;
771 /* Operate from end to begin to be able to move in place */
772 while (i > 0 && i > nomask_bands)
773 {
774 i--;
775 sp->uncompressed_buffer[i * dst_stride + td->td_samplesperpixel -
776 1] = (uint8_t)(255 * sp->mask_buffer[i]);
777 memcpy(sp->uncompressed_buffer + i * dst_stride,
778 sp->uncompressed_buffer + i * src_stride, src_stride);
779 }
780 /* First pixels must use memmove due to overlapping areas */
781 while (i > 0)
782 {
783 i--;
784 sp->uncompressed_buffer[i * dst_stride + td->td_samplesperpixel -
785 1] = (uint8_t)(255 * sp->mask_buffer[i]);
786 memmove(sp->uncompressed_buffer + i * dst_stride,
787 sp->uncompressed_buffer + i * src_stride, src_stride);
788 }
789 }
790 else if (use_mask && td->td_sampleformat == SAMPLEFORMAT_IEEEFP)
791 {
792 unsigned i;
793#if WORDS_BIGENDIAN
794 const unsigned char nan_bytes[] = {0x7f, 0xc0, 0, 0};
795#else
796 const unsigned char nan_bytes[] = {0, 0, 0xc0, 0x7f};
797#endif
798 float nan_float32;
799 memcpy(&nan_float32, nan_bytes, 4);
800
802 td->td_samplesperpixel == 1)
803 {
804 if (td->td_bitspersample == 32)
805 {
806 for (i = 0; i < nb_pixels; i++)
807 {
808 if (sp->mask_buffer[i] == 0)
809 ((float *)sp->uncompressed_buffer)[i] = nan_float32;
810 }
811 }
812 else
813 {
814 const double nan_float64 = (double)nan_float32;
815 for (i = 0; i < nb_pixels; i++)
816 {
817 if (sp->mask_buffer[i] == 0)
818 ((double *)sp->uncompressed_buffer)[i] = nan_float64;
819 }
820 }
821 }
822 else if (nRequestedMasks == 1)
823 {
824 assert(nFoundDims == td->td_samplesperpixel);
825 assert(nFoundBands == 1);
826
827 unsigned k = 0;
828 if (td->td_bitspersample == 32)
829 {
830 for (i = 0; i < nb_pixels; i++)
831 {
832 for (int j = 0; j < td->td_samplesperpixel; j++)
833 {
834 if (sp->mask_buffer[i] == 0)
835 ((float *)sp->uncompressed_buffer)[k] = nan_float32;
836 ++k;
837 }
838 }
839 }
840 else
841 {
842 const double nan_float64 = (double)nan_float32;
843 for (i = 0; i < nb_pixels; i++)
844 {
845 for (int j = 0; j < td->td_samplesperpixel; j++)
846 {
847 if (sp->mask_buffer[i] == 0)
848 ((double *)sp->uncompressed_buffer)[k] =
849 nan_float64;
850 ++k;
851 }
852 }
853 }
854 }
855#if LERC_AT_LEAST_VERSION(3, 0, 0)
856 else
857 {
858 assert(nRequestedMasks == td->td_samplesperpixel);
859 assert(nFoundDims == 1);
860 assert(nFoundBands == td->td_samplesperpixel);
861
862 unsigned k = 0;
863 if (td->td_bitspersample == 32)
864 {
865 for (i = 0; i < nb_pixels; i++)
866 {
867 for (int j = 0; j < td->td_samplesperpixel; j++)
868 {
869 if (sp->mask_buffer[i + (unsigned int)j * nb_pixels] ==
870 0)
871 ((float *)sp->uncompressed_buffer)[k] = nan_float32;
872 else
873 ((float *)sp->uncompressed_buffer)[k] =
874 ((float *)sp->uncompressed_buffer_multiband)
875 [i + (unsigned int)j * nb_pixels];
876 ++k;
877 }
878 }
879 }
880 else
881 {
882 const double nan_float64 = (double)nan_float32;
883 for (i = 0; i < nb_pixels; i++)
884 {
885 for (int j = 0; j < td->td_samplesperpixel; j++)
886 {
887 if (sp->mask_buffer[i + (unsigned int)j * nb_pixels] ==
888 0)
889 ((double *)sp->uncompressed_buffer)[k] =
890 nan_float64;
891 else
892 ((double *)sp->uncompressed_buffer)[k] =
893 ((double *)sp->uncompressed_buffer_multiband)
894 [i + (unsigned int)j * nb_pixels];
895 ++k;
896 }
897 }
898 }
899 }
900#endif
901 }
902
903 return 1;
904}
905
906/*
907 * Decode a strip, tile or scanline.
908 */
928static int LERCDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
929{
930 static const char module[] = "LERCDecode";
931 LERCState *sp = LERCDecoderState(tif);
932
933 (void)s;
934 assert(sp != NULL);
935 assert(sp->state == LSTATE_INIT_DECODE);
936
937 if (sp->uncompressed_buffer == NULL)
938 {
939 memset(op, 0, (size_t)occ);
940 TIFFErrorExtR(tif, module, "Uncompressed buffer not allocated");
941 return 0;
942 }
943
944 if ((uint64_t)sp->uncompressed_offset + (uint64_t)occ >
945 sp->uncompressed_size)
946 {
947 memset(op, 0, (size_t)occ);
948 TIFFErrorExtR(tif, module, "Too many bytes read");
949 return 0;
950 }
951
952 memcpy(op, sp->uncompressed_buffer + sp->uncompressed_offset, (size_t)occ);
953 sp->uncompressed_offset += (unsigned int)occ;
954
955 return 1;
956}
957
958#ifndef LERC_READ_ONLY
959
972static int LERCSetupEncode(TIFF *tif)
973{
974 LERCState *sp = LERCEncoderState(tif);
975
976 assert(sp != NULL);
977 if (sp->state & LSTATE_INIT_DECODE)
978 {
979 sp->state = 0;
980 }
981
983
984 return 1;
985}
986
987/*
988 * Reset encoding state at the start of a strip.
989 */
1005static int LERCPreEncode(TIFF *tif, uint16_t s)
1006{
1007 static const char module[] = "LERCPreEncode";
1008 LERCState *sp = LERCEncoderState(tif);
1009 int lerc_data_type;
1010
1011 (void)s;
1012 assert(sp != NULL);
1013 if (sp->state != LSTATE_INIT_ENCODE)
1014 tif->tif_setupencode(tif);
1015
1016 lerc_data_type = GetLercDataType(tif);
1017 if (lerc_data_type < 0)
1018 return 0;
1019
1020 if (!SetupBuffers(tif, sp, module))
1021 return 0;
1022
1023 return 1;
1024}
1025
1026/*
1027 * Encode a chunk of pixels.
1028 */
1049static int LERCEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
1050{
1051 static const char module[] = "LERCEncode";
1052 LERCState *sp = LERCEncoderState(tif);
1053
1054 (void)s;
1055 assert(sp != NULL);
1056 if (sp->state != LSTATE_INIT_ENCODE)
1057 {
1058 TIFFErrorExtR(tif, module,
1059 "LERC codec state is not initialized for encoding");
1060 return 0;
1061 }
1062
1063 if ((uint64_t)sp->uncompressed_offset + (uint64_t)cc >
1064 sp->uncompressed_size)
1065 {
1066 TIFFErrorExtR(tif, module, "Too many bytes written");
1067 return 0;
1068 }
1069
1070 memcpy(sp->uncompressed_buffer + sp->uncompressed_offset, bp, (size_t)cc);
1071 sp->uncompressed_offset += (unsigned int)cc;
1072
1073 return 1;
1074}
1075
1076/*
1077 * Finish off an encoded strip by flushing it.
1078 */
1106static int LERCPostEncode(TIFF *tif)
1107{
1108 lerc_status lerc_ret;
1109 static const char module[] = "LERCPostEncode";
1110 LERCState *sp = LERCEncoderState(tif);
1111 unsigned int numBytesWritten = 0;
1112 TIFFDirectory *td = &tif->tif_dir;
1113 int use_mask = 0;
1114 unsigned dst_nbands = td->td_samplesperpixel;
1115
1116 if (sp->state != LSTATE_INIT_ENCODE)
1117 {
1118 TIFFErrorExtR(tif, module,
1119 "LERC codec state is not initialized for encoding");
1120 return 0;
1121 }
1122
1123 if (sp->uncompressed_offset != sp->uncompressed_size)
1124 {
1125 TIFFErrorExtR(tif, module, "Unexpected number of bytes in the buffer");
1126 return 0;
1127 }
1128
1129 int mask_count = 1;
1130 const unsigned nb_pixels =
1131 _TIFFMultiply32(tif, sp->segment_width, sp->segment_height, module);
1132 if (nb_pixels == 0)
1133 return 0;
1134
1135 /* Extract alpha mask (if containing only 0 and 255 values, */
1136 /* and compact array of regular bands */
1137 if (td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_extrasamples > 0 &&
1138 td->td_sampleinfo &&
1140 GetLercDataType(tif) == 1)
1141 {
1142 const unsigned dst_stride =
1143 (unsigned int)((td->td_samplesperpixel - 1) *
1144 (td->td_bitspersample / 8));
1145 const unsigned src_stride =
1146 (unsigned int)(td->td_samplesperpixel * (td->td_bitspersample / 8));
1147 unsigned i = 0;
1148
1149 use_mask = 1;
1150 for (i = 0; i < nb_pixels; i++)
1151 {
1152 int v = sp->uncompressed_buffer[i * src_stride +
1153 td->td_samplesperpixel - 1];
1154 if (v != 0 && v != 255)
1155 {
1156 use_mask = 0;
1157 break;
1158 }
1159 }
1160
1161 if (use_mask)
1162 {
1163 dst_nbands--;
1164 /* First pixels must use memmove due to overlapping areas */
1165 for (i = 0; i < dst_nbands && i < nb_pixels; i++)
1166 {
1167 memmove(sp->uncompressed_buffer + i * dst_stride,
1168 sp->uncompressed_buffer + i * src_stride, dst_stride);
1169 sp->mask_buffer[i] =
1170 sp->uncompressed_buffer[i * src_stride +
1171 td->td_samplesperpixel - 1];
1172 }
1173 for (; i < nb_pixels; i++)
1174 {
1175 memcpy(sp->uncompressed_buffer + i * dst_stride,
1176 sp->uncompressed_buffer + i * src_stride, dst_stride);
1177 sp->mask_buffer[i] =
1178 sp->uncompressed_buffer[i * src_stride +
1179 td->td_samplesperpixel - 1];
1180 }
1181 }
1182 }
1183 else if (td->td_sampleformat == SAMPLEFORMAT_IEEEFP &&
1184 (td->td_bitspersample == 32 || td->td_bitspersample == 64))
1185 {
1186 /* Check for NaN values */
1187 unsigned i;
1188 if (td->td_bitspersample == 32)
1189 {
1190 if (td->td_planarconfig == PLANARCONFIG_CONTIG && dst_nbands > 1)
1191 {
1192 unsigned k = 0;
1193 for (i = 0; i < nb_pixels; i++)
1194 {
1195 int count_nan = 0;
1196 for (int j = 0; j < td->td_samplesperpixel; ++j)
1197 {
1198 const float val = ((float *)sp->uncompressed_buffer)[k];
1199 ++k;
1200 if (isnan(val))
1201 {
1202 ++count_nan;
1203 }
1204 }
1205 if (count_nan > 0)
1206 {
1207 use_mask = 1;
1208 if (count_nan < td->td_samplesperpixel)
1209 {
1210 mask_count = td->td_samplesperpixel;
1211 break;
1212 }
1213 }
1214 }
1215 }
1216 else
1217 {
1218 for (i = 0; i < nb_pixels; i++)
1219 {
1220 const float val = ((float *)sp->uncompressed_buffer)[i];
1221 if (isnan(val))
1222 {
1223 use_mask = 1;
1224 break;
1225 }
1226 }
1227 }
1228 }
1229 else
1230 {
1231 if (td->td_planarconfig == PLANARCONFIG_CONTIG && dst_nbands > 1)
1232 {
1233 unsigned k = 0;
1234 for (i = 0; i < nb_pixels; i++)
1235 {
1236 int count_nan = 0;
1237 for (int j = 0; j < td->td_samplesperpixel; ++j)
1238 {
1239 const double val =
1240 ((double *)sp->uncompressed_buffer)[k];
1241 ++k;
1242 if (isnan(val))
1243 {
1244 ++count_nan;
1245 }
1246 }
1247 if (count_nan > 0)
1248 {
1249 use_mask = 1;
1250 if (count_nan < td->td_samplesperpixel)
1251 {
1252 mask_count = td->td_samplesperpixel;
1253 break;
1254 }
1255 }
1256 }
1257 }
1258 else
1259 {
1260 for (i = 0; i < nb_pixels; i++)
1261 {
1262 const double val = ((double *)sp->uncompressed_buffer)[i];
1263 if (isnan(val))
1264 {
1265 use_mask = 1;
1266 break;
1267 }
1268 }
1269 }
1270 }
1271
1272 if (use_mask)
1273 {
1274 if (mask_count > 1)
1275 {
1276#if LERC_AT_LEAST_VERSION(3, 0, 0)
1277 unsigned int num_bytes_needed =
1278 _TIFFMultiply32(tif, nb_pixels, dst_nbands, module);
1279 if (num_bytes_needed == 0)
1280 return 0;
1281 num_bytes_needed = _TIFFMultiply32(
1282 tif, num_bytes_needed, (uint32_t)(td->td_bitspersample / 8),
1283 module);
1284 if (num_bytes_needed == 0)
1285 return 0;
1286 if (sp->uncompressed_buffer_multiband_alloc < num_bytes_needed)
1287 {
1288 _TIFFfreeExt(tif, sp->uncompressed_buffer_multiband);
1289 sp->uncompressed_buffer_multiband =
1290 (uint8_t *)_TIFFmallocExt(tif, num_bytes_needed);
1291 if (!sp->uncompressed_buffer_multiband)
1292 {
1293 sp->uncompressed_buffer_multiband_alloc = 0;
1294 return 0;
1295 }
1296 sp->uncompressed_buffer_multiband_alloc = num_bytes_needed;
1297 }
1298
1299 unsigned k = 0;
1300 if (td->td_bitspersample == 32)
1301 {
1302 for (i = 0; i < nb_pixels; i++)
1303 {
1304 for (int j = 0; j < td->td_samplesperpixel; ++j)
1305 {
1306 const float val =
1307 ((float *)sp->uncompressed_buffer)[k];
1308 ((float *)sp->uncompressed_buffer_multiband)
1309 [i + (unsigned int)j * nb_pixels] = val;
1310 ++k;
1311 sp->mask_buffer[i + (unsigned int)j * nb_pixels] =
1312 !isnan(val) ? 255 : 0;
1313 }
1314 }
1315 }
1316 else
1317 {
1318 for (i = 0; i < nb_pixels; i++)
1319 {
1320 for (int j = 0; j < td->td_samplesperpixel; ++j)
1321 {
1322 const double val =
1323 ((double *)sp->uncompressed_buffer)[k];
1324 ((double *)sp->uncompressed_buffer_multiband)
1325 [i + (unsigned int)j * nb_pixels] = val;
1326 ++k;
1327 sp->mask_buffer[i + (unsigned int)j * nb_pixels] =
1328 !isnan(val) ? 255 : 0;
1329 }
1330 }
1331 }
1332#else
1333 TIFFErrorExtR(tif, module,
1334 "lerc_encode() would need to create one mask per "
1335 "sample, but this requires liblerc >= 3.0");
1336 return 0;
1337#endif
1338 }
1339 else if (td->td_planarconfig == PLANARCONFIG_CONTIG &&
1340 dst_nbands > 1)
1341 {
1342 if (td->td_bitspersample == 32)
1343 {
1344 for (i = 0; i < nb_pixels; i++)
1345 {
1346 const float val =
1347 ((float *)sp->uncompressed_buffer)[i * dst_nbands];
1348 sp->mask_buffer[i] = !isnan(val) ? 255 : 0;
1349 }
1350 }
1351 else
1352 {
1353 for (i = 0; i < nb_pixels; i++)
1354 {
1355 const double val =
1356 ((double *)sp->uncompressed_buffer)[i * dst_nbands];
1357 sp->mask_buffer[i] = !isnan(val) ? 255 : 0;
1358 }
1359 }
1360 }
1361 else
1362 {
1363 if (td->td_bitspersample == 32)
1364 {
1365 for (i = 0; i < nb_pixels; i++)
1366 {
1367 const float val = ((float *)sp->uncompressed_buffer)[i];
1368 sp->mask_buffer[i] = !isnan(val) ? 255 : 0;
1369 }
1370 }
1371 else
1372 {
1373 for (i = 0; i < nb_pixels; i++)
1374 {
1375 const double val =
1376 ((double *)sp->uncompressed_buffer)[i];
1377 sp->mask_buffer[i] = !isnan(val) ? 255 : 0;
1378 }
1379 }
1380 }
1381 }
1382 }
1383
1384 unsigned int estimated_compressed_size = sp->uncompressed_alloc;
1385#if LERC_AT_LEAST_VERSION(3, 0, 0)
1386 if (mask_count > 1)
1387 {
1388 uint64_t mask_overhead =
1389 ((uint64_t)sp->segment_width * sp->segment_height *
1390 (unsigned)mask_count +
1391 7) /
1392 8;
1393 if (mask_overhead > UINT_MAX - estimated_compressed_size)
1394 {
1395 TIFFErrorExtR(tif, module,
1396 "Integer overflow in estimated compressed size");
1397 return 0;
1398 }
1399 estimated_compressed_size += (unsigned int)mask_overhead;
1400 }
1401#endif
1402
1403 if (sp->compressed_size < estimated_compressed_size)
1404 {
1405 _TIFFfreeExt(tif, sp->compressed_buffer);
1406 sp->compressed_buffer = _TIFFmallocExt(tif, estimated_compressed_size);
1407 if (!sp->compressed_buffer)
1408 {
1409 sp->compressed_size = 0;
1410 return 0;
1411 }
1412 sp->compressed_size = estimated_compressed_size;
1413 }
1414
1415#if LERC_AT_LEAST_VERSION(3, 0, 0)
1416 if (mask_count > 1)
1417 {
1418 lerc_ret = lerc_encodeForVersion(
1419 sp->uncompressed_buffer_multiband, sp->lerc_version,
1420 (unsigned int)GetLercDataType(tif), 1, (int)sp->segment_width,
1421 (int)sp->segment_height, (int)dst_nbands, (int)dst_nbands,
1422 sp->mask_buffer, sp->maxzerror,
1423 (unsigned char *)sp->compressed_buffer, sp->compressed_size,
1424 &numBytesWritten);
1425 }
1426 else
1427#endif
1428 {
1429 lerc_ret = lerc_encodeForVersion(
1430 sp->uncompressed_buffer, sp->lerc_version,
1431 (unsigned int)GetLercDataType(tif),
1432 (int)(td->td_planarconfig == PLANARCONFIG_CONTIG ? dst_nbands : 1),
1433 (int)sp->segment_width, (int)sp->segment_height, 1,
1434#if LERC_AT_LEAST_VERSION(3, 0, 0)
1435 use_mask ? 1 : 0,
1436#endif
1437 use_mask ? sp->mask_buffer : NULL, sp->maxzerror,
1438 (unsigned char *)sp->compressed_buffer, sp->compressed_size,
1439 &numBytesWritten);
1440 }
1441 if (lerc_ret != 0)
1442 {
1443 TIFFErrorExtR(tif, module, "lerc_encode() failed");
1444 return 0;
1445 }
1446 assert(numBytesWritten < estimated_compressed_size);
1447
1448 if (sp->additional_compression == LERC_ADD_COMPRESSION_DEFLATE)
1449 {
1450#if LIBDEFLATE_SUPPORT
1451 if (sp->libdeflate_enc == NULL)
1452 {
1453 /* To get results as good as zlib, we ask for an extra */
1454 /* level of compression */
1455 sp->libdeflate_enc = libdeflate_alloc_compressor(
1456 sp->zipquality == Z_DEFAULT_COMPRESSION ? 7
1457 : sp->zipquality >= 6 && sp->zipquality <= 9
1458 ? sp->zipquality + 1
1459 : sp->zipquality);
1460 if (sp->libdeflate_enc == NULL)
1461 {
1462 TIFFErrorExtR(tif, module, "Cannot allocate compressor");
1463 return 0;
1464 }
1465 }
1466
1467 /* Should not happen normally */
1468 if (libdeflate_zlib_compress_bound(
1469 sp->libdeflate_enc, numBytesWritten) > sp->uncompressed_alloc)
1470 {
1471 TIFFErrorExtR(tif, module,
1472 "Output buffer for libdeflate too small");
1473 return 0;
1474 }
1475
1476 tif->tif_rawcc = (tmsize_t)libdeflate_zlib_compress(
1477 sp->libdeflate_enc, sp->compressed_buffer, numBytesWritten,
1478 sp->uncompressed_buffer, sp->uncompressed_alloc);
1479
1480 if (tif->tif_rawcc == 0)
1481 {
1482 TIFFErrorExtR(tif, module, "Encoder error at scanline %lu",
1483 (unsigned long)tif->tif_dir.td_row);
1484 return 0;
1485 }
1486#else
1487 z_stream strm;
1488 int zlib_ret;
1489 int cappedQuality = sp->zipquality;
1490 if (cappedQuality > Z_BEST_COMPRESSION)
1491 cappedQuality = Z_BEST_COMPRESSION;
1492
1493 memset(&strm, 0, sizeof(strm));
1494 strm.zalloc = NULL;
1495 strm.zfree = NULL;
1496 strm.opaque = NULL;
1497 zlib_ret = deflateInit(&strm, cappedQuality);
1498 if (zlib_ret != Z_OK)
1499 {
1500 TIFFErrorExtR(tif, module, "deflateInit() failed");
1501 return 0;
1502 }
1503
1504 strm.avail_in = numBytesWritten;
1505 strm.next_in = sp->compressed_buffer;
1506 strm.avail_out = sp->uncompressed_alloc;
1507 strm.next_out = sp->uncompressed_buffer;
1508 zlib_ret = deflate(&strm, Z_FINISH);
1509 if (zlib_ret == Z_STREAM_END)
1510 {
1511 tif->tif_rawcc = sp->uncompressed_alloc - strm.avail_out;
1512 }
1513 deflateEnd(&strm);
1514 if (zlib_ret != Z_STREAM_END)
1515 {
1516 TIFFErrorExtR(tif, module, "deflate() failed");
1517 return 0;
1518 }
1519#endif
1520 {
1521 int ret;
1522 uint8_t *tif_rawdata_backup = tif->tif_rawdata;
1523 tmsize_t tif_rawdatasize_backup = tif->tif_rawdatasize;
1524 tif->tif_rawdatasize = (tmsize_t)sp->uncompressed_alloc;
1525 tif->tif_rawdata = sp->uncompressed_buffer;
1526 ret = TIFFFlushData1(tif);
1527 tif->tif_rawdatasize = tif_rawdatasize_backup;
1528 tif->tif_rawdata = tif_rawdata_backup;
1529 if (!ret)
1530 {
1531 return 0;
1532 }
1533 }
1534 }
1535 else if (sp->additional_compression == LERC_ADD_COMPRESSION_ZSTD)
1536 {
1537#ifdef ZSTD_SUPPORT
1538 size_t zstd_ret = ZSTD_compress(
1539 sp->uncompressed_buffer, sp->uncompressed_alloc,
1540 sp->compressed_buffer, numBytesWritten, sp->zstd_compress_level);
1541 if (ZSTD_isError(zstd_ret))
1542 {
1543 TIFFErrorExtR(tif, module, "Error in ZSTD_compress(): %s",
1544 ZSTD_getErrorName(zstd_ret));
1545 return 0;
1546 }
1547
1548 {
1549 int ret;
1550 uint8_t *tif_rawdata_backup = tif->tif_rawdata;
1551 tmsize_t tif_rawdatasize_backup = tif->tif_rawdatasize;
1552 tif->tif_rawdatasize = (tmsize_t)sp->uncompressed_alloc;
1553 tif->tif_rawdata = sp->uncompressed_buffer;
1554 tif->tif_rawcc = (tmsize_t)zstd_ret;
1555 ret = TIFFFlushData1(tif);
1556 tif->tif_rawdatasize = tif_rawdatasize_backup;
1557 tif->tif_rawdata = tif_rawdata_backup;
1558 if (!ret)
1559 {
1560 return 0;
1561 }
1562 }
1563#else
1564 TIFFErrorExtR(tif, module, "ZSTD support missing");
1565 return 0;
1566#endif
1567 }
1568 else if (sp->additional_compression != LERC_ADD_COMPRESSION_NONE)
1569 {
1570 TIFFErrorExtR(tif, module, "Unhandled additional compression");
1571 return 0;
1572 }
1573 else
1574 {
1575 int ret;
1576 uint8_t *tif_rawdata_backup = tif->tif_rawdata;
1577 tmsize_t tif_rawdatasize_backup = tif->tif_rawdatasize;
1578 tif->tif_rawdatasize = (tmsize_t)sp->compressed_size;
1579 tif->tif_rawdata = (uint8_t *)sp->compressed_buffer;
1580 tif->tif_rawcc = numBytesWritten;
1581 ret = TIFFFlushData1(tif);
1582 tif->tif_rawdatasize = tif_rawdatasize_backup;
1583 tif->tif_rawdata = tif_rawdata_backup;
1584 if (!ret)
1585 return 0;
1586 }
1587
1588 return 1;
1589}
1590
1591#endif /* LERC_READ_ONLY */
1592
1606static void LERCCleanup(TIFF *tif)
1607{
1608 LERCState *sp = GetLERCState(tif);
1609
1610 assert(sp != NULL);
1611
1614
1618 _TIFFfreeExt(tif, sp->mask_buffer);
1619
1620#if LIBDEFLATE_SUPPORT
1621 if (sp->libdeflate_dec)
1622 libdeflate_free_decompressor(sp->libdeflate_dec);
1623 if (sp->libdeflate_enc)
1624 libdeflate_free_compressor(sp->libdeflate_enc);
1625#endif
1626
1627 _TIFFfreeExt(tif, sp);
1628 tif->tif_data = NULL;
1629
1631}
1632
1641static const TIFFField LERCFields[] = {
1644 (char *)"LercParameters", NULL},
1646 FIELD_PSEUDO, TRUE, FALSE, (char *)"LercMaximumError", NULL},
1648 FALSE, FALSE, (char *)"LercVersion", NULL},
1650 FIELD_PSEUDO, FALSE, FALSE, (char *)"LercAdditionalCompression", NULL},
1652 FALSE, (char *)"ZSTD zstd_compress_level", NULL},
1654 FALSE, (char *)"", NULL},
1655};
1656
1673static int LERCVSetFieldBase(TIFF *tif, uint32_t tag, ...)
1674{
1675 LERCState *sp = GetLERCState(tif);
1676 int ret;
1677 va_list ap;
1678 va_start(ap, tag);
1679 ret = (*sp->vsetparent)(tif, tag, ap);
1680 va_end(ap);
1681 return ret;
1682}
1683
1709static int LERCVSetField(TIFF *tif, uint32_t tag, va_list ap)
1710{
1711 static const char module[] = "LERCVSetField";
1712 LERCState *sp = GetLERCState(tif);
1713
1714 switch (tag)
1715 {
1717 {
1718 uint32_t count = (uint32_t)va_arg(ap, int);
1719 int *params = va_arg(ap, int *);
1720 if (count < 2)
1721 {
1722 TIFFErrorExtR(tif, module,
1723 "Invalid count for LercParameters: %u", count);
1724 return 0;
1725 }
1726 sp->lerc_version = params[0];
1727 sp->additional_compression = params[1];
1728 return LERCVSetFieldBase(tif, TIFFTAG_LERC_PARAMETERS, count,
1729 params);
1730 }
1732 sp->maxzerror = va_arg(ap, double);
1733 return 1;
1735 {
1736 int params[2] = {0, 0};
1737 int version = va_arg(ap, int);
1738 if (version != LERC_VERSION_2_4)
1739 {
1740 TIFFErrorExtR(tif, module, "Invalid value for LercVersion: %d",
1741 version);
1742 return 0;
1743 }
1744 sp->lerc_version = version;
1745 params[0] = sp->lerc_version;
1746 params[1] = sp->additional_compression;
1747 return LERCVSetFieldBase(tif, TIFFTAG_LERC_PARAMETERS, 2, params);
1748 }
1750 {
1751 int params[2] = {0, 0};
1752 int additional_compression = va_arg(ap, int);
1753#ifndef ZSTD_SUPPORT
1754 if (additional_compression == LERC_ADD_COMPRESSION_ZSTD)
1755 {
1756 TIFFErrorExtR(tif, module,
1757 "LERC_ZSTD requested, but ZSTD not available");
1758 return 0;
1759 }
1760#endif
1761 if (additional_compression != LERC_ADD_COMPRESSION_NONE &&
1762 additional_compression != LERC_ADD_COMPRESSION_DEFLATE &&
1763 additional_compression != LERC_ADD_COMPRESSION_ZSTD)
1764 {
1765 TIFFErrorExtR(tif, module,
1766 "Invalid value for LercAdditionalCompression: %d",
1767 additional_compression);
1768 return 0;
1769 }
1770 sp->additional_compression = additional_compression;
1771 params[0] = sp->lerc_version;
1772 params[1] = sp->additional_compression;
1773 return LERCVSetFieldBase(tif, TIFFTAG_LERC_PARAMETERS, 2, params);
1774 }
1775#ifdef ZSTD_SUPPORT
1776 case TIFFTAG_ZSTD_LEVEL:
1777 {
1778 sp->zstd_compress_level = (int)va_arg(ap, int);
1779 if (sp->zstd_compress_level <= 0 ||
1780 sp->zstd_compress_level > ZSTD_maxCLevel())
1781 {
1782 TIFFWarningExtR(tif, module,
1783 "ZSTD_LEVEL should be between 1 and %d",
1784 ZSTD_maxCLevel());
1785 }
1786 return 1;
1787 }
1788#endif
1789 case TIFFTAG_ZIPQUALITY:
1790 {
1791 sp->zipquality = (int)va_arg(ap, int);
1792 if (sp->zipquality < Z_DEFAULT_COMPRESSION ||
1793 sp->zipquality > LIBDEFLATE_MAX_COMPRESSION_LEVEL)
1794 {
1796 tif, module,
1797 "Invalid ZipQuality value. Should be in [-1,%d] range",
1799 return 0;
1800 }
1801
1802#if LIBDEFLATE_SUPPORT
1803 if (sp->libdeflate_enc)
1804 {
1805 libdeflate_free_compressor(sp->libdeflate_enc);
1806 sp->libdeflate_enc = NULL;
1807 }
1808#endif
1809
1810 return (1);
1811 }
1812 default:
1813 return (*sp->vsetparent)(tif, tag, ap);
1814 }
1815 /*NOTREACHED*/
1816}
1817
1836static int LERCVGetField(TIFF *tif, uint32_t tag, va_list ap)
1837{
1838 LERCState *sp = GetLERCState(tif);
1839
1840 switch (tag)
1841 {
1843 *va_arg(ap, double *) = sp->maxzerror;
1844 break;
1846 *va_arg(ap, int *) = sp->lerc_version;
1847 break;
1849 *va_arg(ap, int *) = sp->additional_compression;
1850 break;
1851 case TIFFTAG_ZSTD_LEVEL:
1852 *va_arg(ap, int *) = sp->zstd_compress_level;
1853 break;
1854 case TIFFTAG_ZIPQUALITY:
1855 *va_arg(ap, int *) = sp->zipquality;
1856 break;
1857 default:
1858 return (*sp->vgetparent)(tif, tag, ap);
1859 }
1860 return 1;
1861}
1862
1863int TIFFInitLERC(TIFF *tif, int scheme)
1864{
1865 static const char module[] = "TIFFInitLERC";
1866 LERCState *sp;
1867
1868 (void)scheme;
1869 assert(scheme == COMPRESSION_LERC);
1870
1871 /*
1872 * Merge codec-specific tag information.
1873 */
1875 {
1876 TIFFErrorExtR(tif, module, "Merging LERC codec-specific tags failed");
1877 return 0;
1878 }
1879
1880 /*
1881 * Allocate state block so tag methods have storage to record values.
1882 */
1883 tif->tif_data = (uint8_t *)_TIFFcallocExt(tif, 1, sizeof(LERCState));
1884 if (tif->tif_data == NULL)
1885 goto bad;
1886 sp = GetLERCState(tif);
1887
1888 /*
1889 * Override parent get/set field methods.
1890 */
1891 sp->vgetparent = tif->tif_tagmethods.vgetfield;
1892 tif->tif_tagmethods.vgetfield = LERCVGetField; /* hook for codec tags */
1893 sp->vsetparent = tif->tif_tagmethods.vsetfield;
1894 tif->tif_tagmethods.vsetfield = LERCVSetField; /* hook for codec tags */
1895
1896 /*
1897 * Install codec methods.
1898 */
1905#ifndef LERC_READ_ONLY
1912#endif
1913 tif->tif_cleanup = LERCCleanup;
1914
1915 /* LERC compression ratio can grow to several millions */
1916 /* eg. 5703725 for Lerc deflate on 16383x16383 array */
1917 /* or 3829644 for regular Lerc */
1918 /* See README_for_libtiff_developpers.md for raw data used to estimate
1919 * the maximum compression rate. */
1920 /* so we don't define tif->tif_getmaxcompressionratio */
1921
1922 /* Default values for codec-specific fields */
1925 sp->maxzerror = 0.0;
1926 sp->zstd_compress_level = 9; /* default comp. level */
1927 sp->zipquality = Z_DEFAULT_COMPRESSION; /* default comp. level */
1928 sp->state = 0;
1929
1930 return 1;
1931bad:
1932 TIFFErrorExtR(tif, module, "No space for LERC state block");
1933 return 0;
1934}
1935#endif /* LERC_SUPPORT */
1936
uint32_t _TIFFMultiply32(TIFF *tif, uint32_t first, uint32_t second, const char *where)
Multiply two unsigned values with an overflow check.
Definition tif_aux.c:40
void _TIFFSetDefaultCompressionState(TIFF *tif)
Install fallback codec callbacks and reset raw-access flags.
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_DOUBLE
Double scalar storage.
Definition tif_dir.h:758
@ TIFF_SETGET_INT
Promoted int scalar representation.
Definition tif_dir.h:762
@ TIFF_SETGET_C32_UINT32
Unsigned 32-bit array with 32-bit explicit count.
Definition tif_dir.h:824
@ TIFF_SETGET_UINT32
Unsigned 32-bit scalar storage.
Definition tif_dir.h:748
int TIFFFlushData1(TIFF *tif)
Append buffered encoded bytes without invoking postencode recursively.
Definition tif_write.c:1213
static int LERCSetupEncode(TIFF *tif)
Select LERC encode mode.
Definition tif_lerc.c:972
int TIFFInitLERC(TIFF *tif, int scheme)
Allocate LERC staging state and install frame callbacks and pseudo-tags.
Definition tif_lerc.c:1863
static int SetupBuffers(TIFF *tif, LERCState *sp, const char *module)
Size and reserve full-strile sample and validity-mask storage.
Definition tif_lerc.c:283
static int GetLercDataType(TIFF *tif)
Map TIFF sample format and depth to a LERC scalar code.
Definition tif_lerc.c:207
static int LERCPostEncode(TIFF *tif)
Encode a fully staged LERC strile and flush optional secondary compression.
Definition tif_lerc.c:1106
static int LERCPreDecode(TIFF *tif, uint16_t s)
Decode and validate an entire LERC strile into owned staging.
Definition tif_lerc.c:433
#define LERCDecoderState(tif)
Alias of GetLERCState(), returning the LERCState for decoding.
Definition tif_lerc.c:146
static int LERCSetupDecode(TIFF *tif)
Select LERC decode mode.
Definition tif_lerc.c:178
#define GetLERCState(tif)
Cast tif->tif_data to the LERCState.
Definition tif_lerc.c:145
#define LERC_AT_LEAST_VERSION(maj, min, patch)
Fallback used when the LERC header lacks LERC_AT_LEAST_VERSION.
Definition tif_lerc.c:57
#define LERCEncoderState(tif)
Alias of GetLERCState(), returning the LERCState for encoding.
Definition tif_lerc.c:147
static int LERCEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
Stage the next LERC input bytes for later frame encoding.
Definition tif_lerc.c:1049
static int LERCDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
Copy the next decoded byte extent from LERC staging.
Definition tif_lerc.c:928
static const TIFFField LERCFields[]
Define LERC parameters error tolerance version and secondary-compression tags.
Definition tif_lerc.c:1641
#define LSTATE_INIT_ENCODE
Bit 0x02 of the codec state field: encoding has been set up.
Definition tif_lerc.c:54
static int LERCVSetField(TIFF *tif, uint32_t tag, va_list ap)
Set LERC version error tolerance or secondary-compression controls.
Definition tif_lerc.c:1709
#define LSTATE_INIT_DECODE
Bit 0x01 of the codec state field: decoding has been set up.
Definition tif_lerc.c:53
static int LERCPreEncode(TIFF *tif, uint16_t s)
Validate LERC sample type and prepare full-strile input storage.
Definition tif_lerc.c:1005
static void LERCCleanup(TIFF *tif)
Release LERC staging masks secondary compressors and outer state.
Definition tif_lerc.c:1606
static int LERCVSetFieldBase(TIFF *tif, uint32_t tag,...)
Forward a variadic assignment directly to the saved parent setter.
Definition tif_lerc.c:1673
static int LERCFixupTags(TIFF *tif)
Accept LERC tag fixup without changes.
Definition tif_lerc.c:160
static int LERCVGetField(TIFF *tif, uint32_t tag, va_list ap)
Retrieve cached LERC controls or delegate another tag query.
Definition tif_lerc.c:1836
#define LIBDEFLATE_MAX_COMPRESSION_LEVEL
Highest accepted TIFFTAG_ZIPQUALITY value: 12.
Definition tif_lerc.c:49
void _TIFFfreeExt(TIFF *tif, void *p)
Release a handle-aware allocation and its payload charge.
Definition tif_open.c:301
void * _TIFFreallocExt(TIFF *tif, void *p, tmsize_t s)
Resize a handle-aware block or release it for a nonpositive size.
Definition tif_open.c:257
void * _TIFFmallocExt(TIFF *tif, tmsize_t s)
Allocate uninitialised bytes under a handle's allocation policy.
Definition tif_open.c:195
void * _TIFFcallocExt(TIFF *tif, tmsize_t nmemb, tmsize_t siz)
Allocate a zero-filled array under a handle's allocation policy.
Definition tif_open.c:224
#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
#define FIELD_CUSTOM
Identify a field stored through the custom-metadata mechanism.
Definition tiffio.h:1316
#define TIFF_ANY
Match any data type when searching for a field descriptor.
Definition tiffio.h:1289
#define TIFF_VARIABLE2
Mark a variable-length field with a 32-bit count convention.
Definition tiffio.h:1310
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
#define TIFFTAG_LERC_MAXZERROR
Pseudo-tag: LERC maximum error.
Definition tiff.h:1655
#define LERC_ADD_COMPRESSION_DEFLATE
Deflate compression around the LERC bitstream.
Definition tiff.h:1651
#define TIFFTAG_LERC_ADD_COMPRESSION
Pseudo-tag: LERC additional compression.
Definition tiff.h:1647
#define LERC_ADD_COMPRESSION_ZSTD
Zstandard compression around the LERC bitstream.
Definition tiff.h:1653
#define TIFFTAG_ZSTD_LEVEL
Pseudo-tag: ZSTD compression level.
Definition tiff.h:1641
#define TIFFTAG_LERC_VERSION
Pseudo-tag: LERC version.
Definition tiff.h:1643
#define LERC_VERSION_2_4
Select the LERC 2.4-compatible bitstream format.
Definition tiff.h:1645
#define LERC_ADD_COMPRESSION_NONE
No additional compression around the LERC bitstream.
Definition tiff.h:1649
#define TIFFTAG_ZIPQUALITY
Pseudo-tag: Deflate compression level control.
Definition tiff.h:1610
int(* TIFFVGetMethod)(TIFF *tif, uint32_t tag, va_list ap)
Implement a handle's variadic tag getter.
Definition tiffio.h:1540
int TIFFSetField(TIFF *tif, uint32_t tag,...)
Set a tag value in the current in-memory directory.
Definition tif_dir.c:1627
int(* TIFFVSetMethod)(TIFF *tif, uint32_t tag, va_list ap)
Implement a handle's variadic tag setter.
Definition tiffio.h:1521
#define PLANARCONFIG_SEPARATE
Separate planes of data.
Definition tiff.h:474
#define EXTRASAMPLE_UNASSALPHA
Unassociated alpha data (introduced in TIFF 6.0).
Definition tiff.h:606
#define TIFFTAG_LERC_PARAMETERS
TIFF tag: Stores LERC version and additional compression method.
Definition tiff.h:958
#define SAMPLEFORMAT_UINT
Unsigned integer data (introduced in TIFF 6.0).
Definition tiff.h:610
#define COMPRESSION_LERC
ESRI LERC compression.
Definition tiff.h:364
#define SAMPLEFORMAT_IEEEFP
IEEE floating point data (introduced in TIFF 6.0).
Definition tiff.h:614
#define SAMPLEFORMAT_INT
Signed integer data (introduced in TIFF 6.0).
Definition tiff.h:612
#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
@ TIFF_LONG
Unsigned 32-bit integer.
Definition tiff.h:239
Own LERC full-strile staging masks and secondary-compression state.
Definition tif_lerc.c:72
TIFFVSetMethod vsetparent
Borrowed parent tag setter restored during cleanup.
Definition tif_lerc.c:142
void * compressed_buffer
Owned Ext LERC blob or secondary-decompressed staging.
Definition tif_lerc.c:124
uint32_t segment_width
Current strile width in pixels.
Definition tif_lerc.c:92
int state
Encode/decode mode flags.
Definition tif_lerc.c:89
unsigned int uncompressed_buffer_multiband_alloc
Multiband staging capacity in bytes.
Definition tif_lerc.c:114
unsigned int mask_size
Validity-mask allocation capacity in bytes.
Definition tif_lerc.c:117
uint8_t * uncompressed_buffer
Owned Ext row-interleaved staging reused as secondary-compression output.
Definition tif_lerc.c:107
unsigned int uncompressed_offset
Next staged input/output byte offset.
Definition tif_lerc.c:109
int zstd_compress_level
Cached ZSTD level, including warned values.
Definition tif_lerc.c:83
int additional_compression
Secondary none/Deflate/ZSTD selection.
Definition tif_lerc.c:81
int zipquality
Cached Deflate quality, including rejected attempted assignments.
Definition tif_lerc.c:87
uint8_t * mask_buffer
Owned Ext pixel or per-band validity masks.
Definition tif_lerc.c:119
uint32_t segment_height
Current tile or truncated-strip height in rows.
Definition tif_lerc.c:94
int lerc_version
Cached encoded LERC version.
Definition tif_lerc.c:79
TIFFVGetMethod vgetparent
Borrowed parent tag getter restored during cleanup.
Definition tif_lerc.c:140
unsigned int compressed_size
Compressed/intermediate allocation capacity in bytes.
Definition tif_lerc.c:122
unsigned int uncompressed_size
Logical current-strile decoded extent in bytes.
Definition tif_lerc.c:97
double maxzerror
Cached maximum encoding error, zero for default lossless operation.
Definition tif_lerc.c:77
uint8_t * uncompressed_buffer_multiband
Owned Ext planar multiband staging for per-band masks.
Definition tif_lerc.c:112
unsigned int uncompressed_alloc
Allocated main staging capacity in bytes, including compression margin.
Definition tif_lerc.c:102
Store the current directory values and image traversal state.
Definition tif_dir.h:143
uint16_t * td_sampleinfo
Owned ExtraSamples interpretation array of td_extrasamples entries, or NULL.
Definition tif_dir.h:237
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_extrasamples
Number of extra samples described by td_sampleinfo.
Definition tif_dir.h:232
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
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
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
uint8_t * tif_rawdata
Raw buffer; ownership/mapping follow TIFF_MYBUFFER and TIFF_BUFFERMMAP.
Definition tiffiop.h:681
tmsize_t tif_rawdatasize
Raw-buffer capacity in bytes; kept in step with tif_rawdata, including zero whenever tif_rawdata is N...
Definition tiffiop.h:686
TIFFCodeMethod tif_decodetile
Codec callback decoding tile data.
Definition tiffiop.h:651
Declare private library state, callbacks, and implementation helpers.