LibTIFF 4.7.2
TIFF library public API and implementation reference
Loading...
Searching...
No Matches
tif_zstd.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2017, Planet Labs
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 ZSTD_SUPPORT
32/*
33 * TIFF Library.
34 *
35 * ZSTD Compression Support
36 *
37 */
38
39#include "tif_predict.h"
40#include "zstd.h"
41
42#include <stdio.h>
43
44/*
45 * State block for each open TIFF file using ZSTD compression/decompression.
46 */
55typedef struct
56{
63 ZSTD_DStream *dstream;
67 ZSTD_CStream *cstream;
74 ZSTD_outBuffer out_buffer;
79 int state;
80#define LSTATE_INIT_DECODE 0x01
81#define LSTATE_INIT_ENCODE 0x02
82
87} ZSTDState;
88
89#define GetZSTDState(tif) ((ZSTDState *)(tif)->tif_data)
90#define ZSTDDecoderState(tif) GetZSTDState(tif)
91#define ZSTDEncoderState(tif) GetZSTDState(tif)
92
93static int ZSTDEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s);
94static int ZSTDDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s);
95
105static int ZSTDFixupTags(TIFF *tif)
106{
107 (void)tif;
108 return 1;
109}
110
123static int ZSTDSetupDecode(TIFF *tif)
124{
125 ZSTDState *sp = ZSTDDecoderState(tif);
126
127 assert(sp != NULL);
128
129 /* if we were last encoding, terminate this mode */
130 if (sp->state & LSTATE_INIT_ENCODE)
131 {
132 ZSTD_freeCStream(sp->cstream);
133 sp->cstream = NULL;
134 sp->state = 0;
135 }
136
138 return 1;
139}
140
141/*
142 * Setup state for decoding a strip.
143 */
158static int ZSTDPreDecode(TIFF *tif, uint16_t s)
159{
160 static const char module[] = "ZSTDPreDecode";
161 ZSTDState *sp = ZSTDDecoderState(tif);
162 size_t zstd_ret;
163
164 (void)s;
165 assert(sp != NULL);
166
167 if ((sp->state & LSTATE_INIT_DECODE) == 0)
168 tif->tif_setupdecode(tif);
169
170 if (sp->dstream == NULL)
171 {
172 sp->dstream = ZSTD_createDStream();
173 if (sp->dstream == NULL)
174 {
175 TIFFErrorExtR(tif, module, "Cannot allocate decompression stream");
176 return 0;
177 }
178 }
179
180 zstd_ret = ZSTD_initDStream(sp->dstream);
181 if (ZSTD_isError(zstd_ret))
182 {
183 TIFFErrorExtR(tif, module, "Error in ZSTD_initDStream(): %s",
184 ZSTD_getErrorName(zstd_ret));
185 return 0;
186 }
187
188 return 1;
189}
190
212static int ZSTDDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
213{
214 static const char module[] = "ZSTDDecode";
215 ZSTDState *sp = ZSTDDecoderState(tif);
216 ZSTD_inBuffer in_buffer;
217 ZSTD_outBuffer out_buffer;
218 size_t zstd_ret;
219
220 (void)s;
221 assert(sp != NULL);
222 assert(sp->state == LSTATE_INIT_DECODE);
223
224 in_buffer.src = tif->tif_rawcp;
225 in_buffer.size = (size_t)tif->tif_rawcc;
226 in_buffer.pos = 0;
227
228 out_buffer.dst = op;
229 out_buffer.size = (size_t)occ;
230 out_buffer.pos = 0;
231
232 do
233 {
234 zstd_ret = ZSTD_decompressStream(sp->dstream, &out_buffer, &in_buffer);
235 if (ZSTD_isError(zstd_ret))
236 {
237 memset(op + out_buffer.pos, 0, out_buffer.size - out_buffer.pos);
238 TIFFErrorExtR(tif, module, "Error in ZSTD_decompressStream(): %s",
239 ZSTD_getErrorName(zstd_ret));
240 return 0;
241 }
242 } while (zstd_ret != 0 && in_buffer.pos < in_buffer.size &&
243 out_buffer.pos < out_buffer.size);
244
245 if (out_buffer.pos < (size_t)occ)
246 {
247 memset(op + out_buffer.pos, 0, out_buffer.size - out_buffer.pos);
248 TIFFErrorExtR(tif, module,
249 "Not enough data at scanline %lu (short %lu bytes)",
250 (unsigned long)tif->tif_dir.td_row,
251 (unsigned long)((size_t)occ - out_buffer.pos));
252 return 0;
253 }
254
255 tif->tif_rawcp += in_buffer.pos;
256 tif->tif_rawcc -= (tmsize_t)in_buffer.pos;
257
258 return 1;
259}
260
273static int ZSTDSetupEncode(TIFF *tif)
274{
275 ZSTDState *sp = ZSTDEncoderState(tif);
276
277 assert(sp != NULL);
278 if (sp->state & LSTATE_INIT_DECODE)
279 {
280 ZSTD_freeDStream(sp->dstream);
281 sp->dstream = NULL;
282 sp->state = 0;
283 }
284
286 return 1;
287}
288
289/*
290 * Reset encoding state at the start of a strip.
291 */
308static int ZSTDPreEncode(TIFF *tif, uint16_t s)
309{
310 static const char module[] = "ZSTDPreEncode";
311 ZSTDState *sp = ZSTDEncoderState(tif);
312 size_t zstd_ret;
313
314 (void)s;
315 assert(sp != NULL);
316 if (sp->state != LSTATE_INIT_ENCODE)
317 tif->tif_setupencode(tif);
318
319 if (sp->cstream == NULL)
320 {
321 sp->cstream = ZSTD_createCStream();
322 if (sp->cstream == NULL)
323 {
324 TIFFErrorExtR(tif, module, "Cannot allocate compression stream");
325 return 0;
326 }
327 }
328
329 zstd_ret = ZSTD_initCStream(sp->cstream, sp->compression_level);
330 if (ZSTD_isError(zstd_ret))
331 {
332 TIFFErrorExtR(tif, module, "Error in ZSTD_initCStream(): %s",
333 ZSTD_getErrorName(zstd_ret));
334 return 0;
335 }
336
337 sp->out_buffer.dst = tif->tif_rawdata;
338 sp->out_buffer.size = (size_t)tif->tif_rawdatasize;
339 sp->out_buffer.pos = 0;
340
341 return 1;
342}
343
344/*
345 * Encode a chunk of pixels.
346 */
366static int ZSTDEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
367{
368 static const char module[] = "ZSTDEncode";
369 ZSTDState *sp = ZSTDEncoderState(tif);
370 ZSTD_inBuffer in_buffer;
371 size_t zstd_ret;
372
373 assert(sp != NULL);
374 if (sp->state != LSTATE_INIT_ENCODE)
375 {
376 TIFFErrorExtR(tif, module,
377 "ZSTD codec state is not initialized for encoding");
378 return 0;
379 }
380
381 (void)s;
382
383 in_buffer.src = bp;
384 in_buffer.size = (size_t)cc;
385 in_buffer.pos = 0;
386
387 do
388 {
389 zstd_ret =
390 ZSTD_compressStream(sp->cstream, &sp->out_buffer, &in_buffer);
391 if (ZSTD_isError(zstd_ret))
392 {
393 TIFFErrorExtR(tif, module, "Error in ZSTD_compressStream(): %s",
394 ZSTD_getErrorName(zstd_ret));
395 return 0;
396 }
397 if (sp->out_buffer.pos == sp->out_buffer.size)
398 {
399 tif->tif_rawcc = tif->tif_rawdatasize;
400 if (!TIFFFlushData1(tif))
401 return 0;
402 sp->out_buffer.dst = tif->tif_rawcp;
403 sp->out_buffer.pos = 0;
404 }
405 } while (in_buffer.pos < in_buffer.size);
406
407 return 1;
408}
409
410/*
411 * Finish off an encoded strip by flushing it.
412 */
428static int ZSTDPostEncode(TIFF *tif)
429{
430 static const char module[] = "ZSTDPostEncode";
431 ZSTDState *sp = ZSTDEncoderState(tif);
432 size_t zstd_ret;
433
434 if (sp->state != LSTATE_INIT_ENCODE)
435 {
436 TIFFErrorExtR(tif, module,
437 "ZSTD codec state is not initialized for encoding");
438 return 0;
439 }
440
441 do
442 {
443 zstd_ret = ZSTD_endStream(sp->cstream, &sp->out_buffer);
444 if (ZSTD_isError(zstd_ret))
445 {
446 TIFFErrorExtR(tif, module, "Error in ZSTD_endStream(): %s",
447 ZSTD_getErrorName(zstd_ret));
448 return 0;
449 }
450 if (sp->out_buffer.pos > 0)
451 {
452 tif->tif_rawcc = (tmsize_t)sp->out_buffer.pos;
453 if (!TIFFFlushData1(tif))
454 return 0;
455 sp->out_buffer.dst = tif->tif_rawcp;
456 sp->out_buffer.pos = 0;
457 }
458 } while (zstd_ret != 0);
459 return 1;
460}
461
475static void ZSTDCleanup(TIFF *tif)
476{
477 ZSTDState *sp = GetZSTDState(tif);
478
479 assert(sp != 0);
480
481 (void)TIFFPredictorCleanup(tif);
482
485
486 if (sp->dstream)
487 {
488 ZSTD_freeDStream(sp->dstream);
489 sp->dstream = NULL;
490 }
491 if (sp->cstream)
492 {
493 ZSTD_freeCStream(sp->cstream);
494 sp->cstream = NULL;
495 }
496 _TIFFfreeExt(tif, sp);
497 tif->tif_data = NULL;
498
500}
501
520static int ZSTDVSetField(TIFF *tif, uint32_t tag, va_list ap)
521{
522 static const char module[] = "ZSTDVSetField";
523 ZSTDState *sp = GetZSTDState(tif);
524
525 switch (tag)
526 {
528 sp->compression_level = (int)va_arg(ap, int);
529 if (sp->compression_level <= 0 ||
530 sp->compression_level > ZSTD_maxCLevel())
531 {
532 TIFFWarningExtR(tif, module,
533 "ZSTD_LEVEL should be between 1 and %d",
534 ZSTD_maxCLevel());
535 }
536 return 1;
537 default:
538 return (*sp->vsetparent)(tif, tag, ap);
539 }
540 /*NOTREACHED*/
541}
542
558static int ZSTDVGetField(TIFF *tif, uint32_t tag, va_list ap)
559{
560 ZSTDState *sp = GetZSTDState(tif);
561
562 switch (tag)
563 {
565 *va_arg(ap, int *) = sp->compression_level;
566 break;
567 default:
568 return (*sp->vgetparent)(tif, tag, ap);
569 }
570 return 1;
571}
572
580static const TIFFField ZSTDFields[] = {
582 FALSE, "ZSTD compression_level", NULL},
583};
584
595static uint64_t ZSTDGetMaxCompressionRatio(TIFF *tif)
596{
597 (void)tif;
598 /* Value from the issue #479 tile allocation guard that previously lived
599 * in _TIFFReadEncodedTileAndAllocBuffer(). */
600 return 33000;
601}
602
603int TIFFInitZSTD(TIFF *tif, int scheme)
604{
605 static const char module[] = "TIFFInitZSTD";
606 ZSTDState *sp;
607
608 (void)scheme;
609 assert(scheme == COMPRESSION_ZSTD);
610
611 /*
612 * Merge codec-specific tag information.
613 */
615 {
616 TIFFErrorExtR(tif, module, "Merging ZSTD codec-specific tags failed");
617 return 0;
618 }
619
620 /*
621 * Allocate state block so tag methods have storage to record values.
622 */
623 tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(ZSTDState));
624 if (tif->tif_data == NULL)
625 goto bad;
626 sp = GetZSTDState(tif);
627
628 /*
629 * Override parent get/set field methods.
630 */
631 sp->vgetparent = tif->tif_tagmethods.vgetfield;
632 tif->tif_tagmethods.vgetfield = ZSTDVGetField; /* hook for codec tags */
633 sp->vsetparent = tif->tif_tagmethods.vsetfield;
634 tif->tif_tagmethods.vsetfield = ZSTDVSetField; /* hook for codec tags */
635
636 /* Default values for codec-specific fields */
637 sp->compression_level = 9; /* default comp. level */
638 sp->state = 0;
639 sp->dstream = 0;
640 sp->cstream = 0;
641 sp->out_buffer.dst = NULL;
642 sp->out_buffer.size = 0;
643 sp->out_buffer.pos = 0;
644
645 /*
646 * Install codec methods.
647 */
662 /*
663 * Setup predictor setup.
664 */
665 (void)TIFFPredictorInit(tif);
666 return 1;
667bad:
668 TIFFErrorExtR(tif, module, "No space for ZSTD state block");
669 return 0;
670}
671#endif /* ZSTD_SUPPORT */
672
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_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
int TIFFPredictorCleanup(TIFF *tif)
Restore saved Predictor tag print and setup hooks.
int TIFFPredictorInit(TIFF *tif)
Install Predictor tag and setup hooks around a codec.
#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 ZSTDDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
Decompress cached ZSTD input into caller output.
Definition tif_zstd.c:212
static int ZSTDPreEncode(TIFF *tif, uint16_t s)
Create and initialise a ZSTD compression stream for a strile.
Definition tif_zstd.c:308
static int ZSTDPostEncode(TIFF *tif)
Finish the ZSTD frame and flush its remaining output.
Definition tif_zstd.c:428
static int ZSTDFixupTags(TIFF *tif)
Accept ZSTD tag fixup without changes.
Definition tif_zstd.c:105
static int ZSTDSetupDecode(TIFF *tif)
Switch ZSTD state into decode mode.
Definition tif_zstd.c:123
#define ZSTDDecoderState(tif)
Alias of GetZSTDState(), returning the ZSTDState for decoding.
Definition tif_zstd.c:90
static int ZSTDEncode(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
Compress input through the active ZSTD stream.
Definition tif_zstd.c:366
int TIFFInitZSTD(TIFF *tif, int scheme)
Allocate ZSTD state and install predictor-aware streaming methods.
Definition tif_zstd.c:603
static uint64_t ZSTDGetMaxCompressionRatio(TIFF *tif)
Report the ZSTD expansion allocation heuristic.
Definition tif_zstd.c:595
#define LSTATE_INIT_ENCODE
Bit 0x02 of the codec state field: encoding has been set up.
Definition tif_zstd.c:81
static int ZSTDVSetField(TIFF *tif, uint32_t tag, va_list ap)
Store ZSTD compression level or delegate another tag assignment.
Definition tif_zstd.c:520
#define LSTATE_INIT_DECODE
Bit 0x01 of the codec state field: decoding has been set up.
Definition tif_zstd.c:80
static int ZSTDVGetField(TIFF *tif, uint32_t tag, va_list ap)
Retrieve ZSTD compression level or delegate another tag query.
Definition tif_zstd.c:558
#define ZSTDEncoderState(tif)
Alias of GetZSTDState(), returning the ZSTDState for encoding.
Definition tif_zstd.c:91
static const TIFFField ZSTDFields[]
Define the ZSTD compression-level pseudo-tag.
Definition tif_zstd.c:580
static int ZSTDPreDecode(TIFF *tif, uint16_t s)
Create or reset the ZSTD decompression stream for a strile.
Definition tif_zstd.c:158
#define GetZSTDState(tif)
Cast tif->tif_data to the ZSTDState.
Definition tif_zstd.c:89
static int ZSTDSetupEncode(TIFF *tif)
Switch ZSTD state into encode mode.
Definition tif_zstd.c:273
static void ZSTDCleanup(TIFF *tif)
Release ZSTD streams state and chained codec methods.
Definition tif_zstd.c:475
#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
#define TIFFTAG_ZSTD_LEVEL
Pseudo-tag: ZSTD compression level.
Definition tiff.h:1641
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 COMPRESSION_ZSTD
Zstandard compression; not registered in the Adobe-maintained registry.
Definition tiff.h:372
TIFF_SSIZE_T tmsize_t
Represent a signed memory or I/O size in bytes.
Definition tiffio.h:89
uint32_t td_row
Current scanline index; UINT32_MAX before traversal starts.
Definition tif_dir.h:240
Prefix codec state with Predictor method chains and row geometry.
Definition tif_predict.h:76
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 ZSTD streams predictor prefix and output cursor.
Definition tif_zstd.c:56
int state
Decode/encode initialisation flags; switching modes releases the old stream.
Definition tif_zstd.c:79
ZSTD_DStream * dstream
Owned dependency decompression stream; released by ZSTD_freeDStream.
Definition tif_zstd.c:63
TIFFPredictorState predict
Predictor prefix, first in the codec state.
Definition tif_zstd.c:58
int compression_level
Cached level applied on the next compression-stream initialisation.
Definition tif_zstd.c:72
TIFFVGetMethod vgetparent
Borrowed parent tag getter restored during cleanup.
Definition tif_zstd.c:84
ZSTD_outBuffer out_buffer
Dependency output descriptor borrowing the handle raw buffer.
Definition tif_zstd.c:74
TIFFVSetMethod vsetparent
Borrowed parent tag setter restored during cleanup.
Definition tif_zstd.c:86
ZSTD_CStream * cstream
Owned dependency compression stream; released by ZSTD_freeCStream.
Definition tif_zstd.c:67
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
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
Define the predictor prefix and method-chain contracts.
Declare private library state, callbacks, and implementation helpers.