LibTIFF 4.7.2
TIFF library public API and implementation reference
Loading...
Searching...
No Matches
tif_packbits.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 1988-1997 Sam Leffler
3 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
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 "tif_bytecursor.h"
31#include "tiffiop.h"
32#ifdef PACKBITS_SUPPORT
33/*
34 * TIFF Library.
35 *
36 * PackBits Compression Algorithm Support
37 */
38#include <stdio.h>
39
40#ifndef PACKBITS_READ_ONLY
41
57static int PackBitsPreEncode(TIFF *tif, uint16_t s)
58{
59 (void)s;
60
61 tif->tif_data = (uint8_t *)_TIFFmallocExt(tif, sizeof(tmsize_t));
62 if (tif->tif_data == NULL)
63 return (0);
64 /*
65 * Calculate the scanline/tile-width size in bytes.
66 */
67 if (isTiled(tif))
68 *(tmsize_t *)tif->tif_data = TIFFTileRowSize(tif);
69 else
70 *(tmsize_t *)tif->tif_data = TIFFScanlineSize(tif);
71 return (1);
72}
73
87static int PackBitsPostEncode(TIFF *tif)
88{
89 if (tif->tif_data)
90 _TIFFfreeExt(tif, tif->tif_data);
91 tif->tif_data = NULL;
92 return (1);
93}
94
95/*
96 * Encode a run of pixels.
97 */
122static int PackBitsEncode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
123{
124 static const char module[] = "PackBitsEncode";
125 unsigned char *bp = (unsigned char *)buf;
126 uint8_t *op;
127 uint8_t *ep;
128 uint8_t *lastliteral;
129 long n, slop;
130 tmsize_t need;
131 int b;
132 enum
133 {
135 BASE,
137 LITERAL,
139 RUN,
141 LITERAL_RUN
142 } state;
143
144 (void)s;
145 op = tif->tif_rawcp;
146 ep = tif->tif_rawdata + tif->tif_rawdatasize;
147 state = BASE;
148 lastliteral = NULL;
149 while (cc > 0)
150 {
151 /*
152 * Find the longest string of identical bytes.
153 */
154 b = *bp++;
155 cc--;
156 n = 1;
157 for (; cc > 0 && b == *bp; cc--, bp++)
158 n++;
159 again:
160 if (op + 2 >= ep)
161 { /* insure space for new data */
162 /*
163 * Be careful about writing the last
164 * literal. Must write up to that point
165 * and then copy the remainder to the
166 * front of the buffer.
167 */
168 if (state == LITERAL || state == LITERAL_RUN)
169 {
170 slop = (long)(op - lastliteral);
171 tif->tif_rawcc += (tmsize_t)(lastliteral - tif->tif_rawcp);
172 if (!TIFFFlushData1(tif))
173 return (0);
174 op = tif->tif_rawcp;
175 while (slop-- > 0)
176 *op++ = *lastliteral++;
177 lastliteral = tif->tif_rawcp;
178 }
179 else
180 {
181 tif->tif_rawcc += (tmsize_t)(op - tif->tif_rawcp);
182 if (!TIFFFlushData1(tif))
183 return (0);
184 op = tif->tif_rawcp;
185 }
186 }
187 /*
188 * The flush above does not guarantee room for the next unit when the
189 * caller's raw buffer is small: a carried literal can fill it, and an
190 * empty buffer may still be smaller than the two bytes written next.
191 * Check the room the switch below needs and refuse rather than write
192 * past the end of the buffer. Extending a literal needs one byte;
193 * LITERAL_RUN writes nothing and restarts the loop.
194 */
195 need =
196 (state == LITERAL && n == 1) ? 1 : (state == LITERAL_RUN ? 0 : 2);
197 if ((tmsize_t)(ep - op) < need)
198 {
199 tif->tif_rawcc += (tmsize_t)(op - tif->tif_rawcp);
200 tif->tif_rawcp = op;
201 TIFFErrorExtR(tif, module,
202 "Raw data buffer of %" TIFF_SSIZE_FORMAT
203 " bytes is too small for PackBits encoding",
204 tif->tif_rawdatasize);
205 return (0);
206 }
207 switch (state)
208 {
209 case BASE: /* initial state, set run/literal */
210 if (n > 1)
211 {
212 state = RUN;
213 if (n > 128)
214 {
215 *op++ = (uint8_t)-127;
216 *op++ = (uint8_t)b;
217 n -= 128;
218 goto again;
219 }
220 *op++ = (uint8_t)(-(n - 1));
221 *op++ = (uint8_t)b;
222 }
223 else
224 {
225 lastliteral = op;
226 *op++ = 0;
227 *op++ = (uint8_t)b;
228 state = LITERAL;
229 }
230 break;
231 case LITERAL: /* last object was literal string */
232 if (n > 1)
233 {
234 state = LITERAL_RUN;
235 if (n > 128)
236 {
237 *op++ = (uint8_t)-127;
238 *op++ = (uint8_t)b;
239 n -= 128;
240 goto again;
241 }
242 *op++ = (uint8_t)(-(n - 1)); /* encode run */
243 *op++ = (uint8_t)b;
244 }
245 else
246 { /* extend literal */
247 if (++(*lastliteral) == 127)
248 state = BASE;
249 *op++ = (uint8_t)b;
250 }
251 break;
252 case RUN: /* last object was run */
253 if (n > 1)
254 {
255 if (n > 128)
256 {
257 *op++ = (uint8_t)-127;
258 *op++ = (uint8_t)b;
259 n -= 128;
260 goto again;
261 }
262 *op++ = (uint8_t)(-(n - 1));
263 *op++ = (uint8_t)b;
264 }
265 else
266 {
267 lastliteral = op;
268 *op++ = 0;
269 *op++ = (uint8_t)b;
270 state = LITERAL;
271 }
272 break;
273 case LITERAL_RUN: /* literal followed by a run */
274 /*
275 * Check to see if previous run should
276 * be converted to a literal, in which
277 * case we convert literal-run-literal
278 * to a single literal.
279 */
280 if (n == 1 && op[-2] == (uint8_t)-1 && *lastliteral < 126)
281 {
282 state =
283 (((*lastliteral) = (uint8_t)(*lastliteral + 2)) == 127
284 ? BASE
285 : LITERAL);
286 op[-2] = op[-1]; /* replicate */
287 }
288 else
289 state = RUN;
290 goto again;
291 default:
292 break;
293 }
294 }
295 tif->tif_rawcc += (tmsize_t)(op - tif->tif_rawcp);
296 tif->tif_rawcp = op;
297 return (1);
298}
299
300/*
301 * Encode a rectangular chunk of pixels. We break it up
302 * into row-sized pieces to insure that encoded runs do
303 * not span rows. Otherwise, there can be problems with
304 * the decoder if data is read, for example, by scanlines
305 * when it was encoded by strips.
306 */
325static int PackBitsEncodeChunk(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
326{
327 tmsize_t rowsize = *(tmsize_t *)tif->tif_data;
328
329 while (cc > 0)
330 {
331 tmsize_t chunk = rowsize;
332
333 if (cc < chunk)
334 chunk = cc;
335
336 if (!PackBitsEncode(tif, bp, chunk, s))
337 {
338 /*
339 * The caller returns without calling tif_postencode, so release
340 * the per-strip state that tif_preencode allocated here.
341 */
343 return (0);
344 }
345 bp += chunk;
346 cc -= chunk;
347 }
348 return (1);
349}
350
351#endif
352
370static int PackBitsDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
371{
372 static const char module[] = "PackBitsDecode";
373 TIFFByteCursor in = {tif->tif_rawcp, tif->tif_rawcc};
374 TIFFByteCursor out = {op, occ};
375 uint8_t c = 0;
376 long n;
377
378 (void)s;
379 while (in.left > 0 && out.left > 0)
380 {
381 (void)_TIFFByteCursorGetU8(&in, &c);
382 n = (long)(int8_t)c;
383 if (n < 0)
384 { /* replicate next byte -n+1 times */
385 if (n == -128) /* nop */
386 continue;
387 n = -n + 1;
388 if (out.left < (tmsize_t)n)
389 {
390 TIFFWarningExtR(tif, module,
391 "Discarding %" TIFF_SSIZE_FORMAT
392 " bytes to avoid buffer overrun",
393 (tmsize_t)n - out.left);
394 n = (long)out.left;
395 }
396 if (!_TIFFByteCursorGetU8(&in, &c))
397 {
399 tif, module,
400 "Terminating PackBitsDecode due to lack of data.");
401 break;
402 }
403 if (!_TIFFByteCursorFill(&out, c, (tmsize_t)n))
404 break; /* unreachable: n was clamped to out.left above */
405 }
406 else
407 { /* copy next n+1 bytes literally */
408 if (out.left < (tmsize_t)(n + 1))
409 {
410 TIFFWarningExtR(tif, module,
411 "Discarding %" TIFF_SSIZE_FORMAT
412 " bytes to avoid buffer overrun",
413 (tmsize_t)n - out.left + 1);
414 n = (long)out.left - 1;
415 }
416 if (in.left < (tmsize_t)(n + 1))
417 {
419 tif, module,
420 "Terminating PackBitsDecode due to lack of data.");
421 break;
422 }
423 if (!_TIFFByteCursorCopy(&out, &in, (tmsize_t)(n + 1)))
424 break; /* unreachable: both counts were checked above */
425 }
426 }
427 tif->tif_rawcp = in.p;
428 tif->tif_rawcc = in.left;
429 if (out.left > 0)
430 {
431 memset(out.p, 0, (size_t)out.left);
432 TIFFErrorExtR(tif, module, "Not enough data for scanline %" PRIu32,
433 tif->tif_dir.td_row);
434 return (0);
435 }
436 return (1);
437}
438
450{
451 (void)tif;
452
453 /* See README_for_libtiff_developpers.md for raw data used to estimate
454 * the maximum compression rate. */
455
456 return 64;
457}
458
459int TIFFInitPackBits(TIFF *tif, int scheme)
460{
461 (void)scheme;
465#ifndef PACKBITS_READ_ONLY
471#endif
473
474 return (1);
475}
476#endif /* PACKBITS_SUPPORT */
int TIFFInitPackBits(TIFF *tif, int scheme)
Install PackBits transfer callbacks.
static int _TIFFByteCursorFill(TIFFByteCursor *dst, uint8_t value, tmsize_t n)
Write n copies of value to a cursor.
static int _TIFFByteCursorCopy(TIFFByteCursor *dst, TIFFByteCursor *src, tmsize_t n)
Move n bytes from src to dst.
static uint64_t PackBitsGetMaxCompressionRatio(TIFF *tif)
Report the PackBits expansion heuristic.
static int PackBitsPostEncode(TIFF *tif)
Release the PackBits cached row-size allocation.
static int PackBitsEncode(TIFF *tif, uint8_t *buf, tmsize_t cc, uint16_t s)
Encode one byte run region using PackBits packets.
static int PackBitsEncodeChunk(TIFF *tif, uint8_t *bp, tmsize_t cc, uint16_t s)
Split PackBits input into row-bounded encoding requests.
static int PackBitsDecode(TIFF *tif, uint8_t *op, tmsize_t occ, uint16_t s)
Expand PackBits packets into a bounded byte destination.
static int PackBitsPreEncode(TIFF *tif, uint16_t s)
Allocate and cache the PackBits row byte extent.
static int _TIFFByteCursorGetU8(TIFFByteCursor *c, uint8_t *out)
Read one byte from a cursor.
#define TIFF_SSIZE_FORMAT
Provide the printf conversion fragment for tmsize_t, without a percent sign.
Definition tif_config.h:294
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
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
tmsize_t TIFFScanlineSize(TIFF *tif)
Compute the current scanline I/O byte estimate.
Definition tif_strip.c:383
tmsize_t TIFFTileRowSize(TIFF *tif)
Compute the packed byte count of one tile row.
Definition tif_tile.c:276
TIFF_SSIZE_T tmsize_t
Represent a signed memory or I/O size in bytes.
Definition tiffio.h:89
Track a borrowed byte range as a pointer and a remaining count.
tmsize_t left
Number of bytes remaining from p.
uint8_t * p
Next byte to read or write.
uint32_t td_row
Current scanline index; UINT32_MAX before traversal starts.
Definition tif_dir.h:240
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
TIFFPreMethod tif_preencode
Codec callback preparing a row, strip, or tile encode.
Definition tiffiop.h:639
tmsize_t tif_rawcc
Raw-buffer byte count interpreted according to read/write state.
Definition tiffiop.h:696
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
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
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
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 small bounds-checked byte cursors for codec decoders.
Declare private library state, callbacks, and implementation helpers.