Repository navigation
Expand file tree
/
Copy pathtinydng_codec.c
More file actions
1919 lines (1833 loc) · 67.4 KB
/
Copy pathtinydng_codec.c
File metadata and controls
1919 lines (1833 loc) · 67.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* tinydng_codec.c - lazy decode: geometry, predictors, uncompressed + LJPEG,
* tile/strip -> image assembly.
* SPDX-License-Identifier: MIT
*/
#include "td_internal.h"
#include "tiny_dng_ljpeg92_v2.h"
#ifndef TINYDNG_NO_ZIP
#include "miniz.h"
#endif
#ifndef TINYDNG_NO_BASELINE_JPEG
#define STBI_NO_STDIO
#include "stb_image.h"
#endif
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
static int td_host_big(void) {
uint16_t x = 1u;
uint8_t b[2];
memcpy(b, &x, 2);
return b[0] == 0u;
}
typedef struct td_geom {
uint32_t width, height;
uint16_t spp;
uint16_t bps; /* stored bits per sample */
uint16_t out_bps; /* decoded bits per sample (8/16/32) */
uint16_t sample_format;
uint16_t planar;
uint16_t predictor;
size_t out_bytes; /* out_bps / 8 */
size_t pixel_stride; /* spp * out_bytes (chunky) */
size_t row_stride; /* width * pixel_stride */
size_t image_size; /* row_stride * height */
uint16_t packed; /* 1 => keep raw sub-byte packed bytes */
uint16_t invert_1bit; /* 1 => map stored bit 1 -> 0, 0 -> 255
(PSD bitmap mode: bit 1 = black) */
} td_geom;
/* Forward decls (defined below). */
static int td_packed_row_bytes(uint32_t width, uint16_t spp, uint16_t bps,
size_t *out);
static tinydng_status td_compute_geom(tinydng_context *ctx,
const tinydng_image_info *img,
td_geom *g, int keep_packed,
tinydng_error *err) {
uint16_t out_bps;
(void)ctx;
memset(g, 0, sizeof(*g));
g->width = img->width;
g->height = img->height;
g->spp = img->samples_per_pixel;
g->bps = img->bits_per_sample;
g->sample_format = img->sample_format;
g->planar = img->planar_configuration;
g->predictor = img->predictor;
/* Sub-byte packed output is only defined for chunky (planar config 1)
sub-byte samples; planar images fall back to the unpacked layout. */
g->packed = (uint16_t)((keep_packed && g->bps > 8u && g->bps < 16u &&
g->planar != 2u) ? 1u : 0u);
if (g->packed) {
size_t rowb;
g->out_bps = g->bps;
g->out_bytes = (size_t)(g->bps + 7u) / 8u;
if (g->spp == 0u || g->width == 0u || g->height == 0u) {
td_set_error(err, TINYDNG_E_PARSE, TINYDNG_STAGE_DECODE, 0, 0, 0,
"invalid decode geometry");
return TINYDNG_E_PARSE;
}
if (!td_packed_row_bytes(g->width, g->spp, g->bps, &rowb) ||
!td_safe_mul_size(rowb, (size_t)g->height, &g->image_size)) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"decoded image size overflow");
return TINYDNG_E_BOUNDS;
}
g->pixel_stride = rowb; /* per-row packed bytes (no per-pixel stride) */
g->row_stride = rowb;
return TINYDNG_OK;
}
if (img->compression == TINYDNG_COMPRESSION_LOSSY_JPEG) {
out_bps = 8; /* baseline/lossy JPEG decodes to 8-bit */
} else if (img->compression == TINYDNG_COMPRESSION_OLD_JPEG ||
img->compression == TINYDNG_COMPRESSION_NEW_JPEG) {
/* bps<=8 => baseline JPEG preview (8-bit); else lossless JPEG (16-bit). */
out_bps = (g->bps <= 8) ? 8 : 16;
} else if (g->bps <= 8) {
out_bps = 8;
} else if (g->bps <= 16) {
out_bps = 16;
} else {
out_bps = 32;
}
g->out_bps = out_bps;
g->out_bytes = (size_t)out_bps / 8u;
if (g->spp == 0u || g->width == 0u || g->height == 0u) {
td_set_error(err, TINYDNG_E_PARSE, TINYDNG_STAGE_DECODE, 0, 0, 0,
"invalid decode geometry");
return TINYDNG_E_PARSE;
}
if (g->planar != 1u && g->planar != 2u) {
td_set_error(err, TINYDNG_E_PARSE, TINYDNG_STAGE_DECODE, 0, 0, 0,
"invalid planar configuration %u", (unsigned)g->planar);
return TINYDNG_E_PARSE;
}
if (!td_safe_mul_size((size_t)g->spp, g->out_bytes, &g->pixel_stride) ||
!td_safe_mul_size((size_t)g->width, g->pixel_stride, &g->row_stride) ||
!td_safe_mul_size((size_t)g->height, g->row_stride, &g->image_size)) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"decoded image size overflow");
return TINYDNG_E_BOUNDS;
}
return TINYDNG_OK;
}
/* Reusable growable scratch buffer. Per-worker instances keep multi-segment
decodes from hammering the (locked) context allocator for every segment.
Ownership: allocated through the ctx allocator, released with
td_scratch_free when the worker finishes. */
typedef struct {
uint8_t* p;
size_t cap;
} td_scratch;
static void td_scratch_free(tinydng_context* ctx, td_scratch* s) {
if (s->p) {
td_ctx_free(ctx, s->p);
s->p = NULL;
s->cap = 0;
}
}
static uint8_t* td_scratch_get(tinydng_context* ctx, td_scratch* s, size_t need,
tinydng_error* err) {
if (s->cap < need) {
td_ctx_free(ctx, s->p);
s->p = (uint8_t*)td_ctx_alloc(ctx, need, err);
if (!s->p) {
s->cap = 0;
return NULL;
}
s->cap = need;
}
return s->p;
}
/* Obtain a contiguous pointer to a segment's compressed/raw bytes. Uses
zero-copy map when available; otherwise allocates `*owned` and reads.
When `re` is non-NULL it is used as a reusable growable read buffer (the
result stays valid only until the next request on the same scratch), which
lets multi-segment decodes avoid per-segment allocator traffic. */
static const uint8_t* td_segment_bytes(tinydng_context* ctx, tinydng_io* io,
uint64_t io_size, uint64_t off,
size_t len, td_scratch* re,
tinydng_error* err) {
uint8_t *buf;
if (len == 0u) {
return NULL;
}
if (io->map) {
const uint8_t *p = io->map(io, off, len);
if (p) {
return p;
}
}
if (re) {
buf = td_scratch_get(ctx, re, len, err);
} else {
buf = (uint8_t*)td_ctx_alloc(ctx, len, err);
}
if (!buf) {
return NULL;
}
if (td_io_view(io, io_size, off, len, buf, len) == NULL) {
if (!re) {
td_ctx_free(ctx, buf);
}
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, off,
"segment bytes out of range");
return NULL;
}
return buf;
}
/* ------------------------------------------------------------------ */
/* Predictors (operate on one decoded block, chunky) */
/* ------------------------------------------------------------------ */
static void td_unpredict_h(uint8_t *buf, uint32_t w, uint32_t h, uint16_t spp,
size_t bytes) {
uint32_t y, x;
uint16_t c;
size_t row_elems = (size_t)w * spp;
if (w < 2u) {
return;
}
for (y = 0; y < h; y++) {
size_t base = (size_t)y * row_elems;
for (c = 0; c < spp; c++) {
/* Pointer-stepped per channel: cur += prev with prev tracking the
previous sample of the SAME channel. Semantically identical to
p[x*spp+c] += p[(x-1)*spp+c], without per-iteration multiplications. */
if (bytes == 1u) {
uint8_t* p = buf + base + c;
uint8_t prev = p[0];
for (x = 1; x < w; x++) {
p += spp;
prev = (uint8_t)(*p + prev);
*p = prev;
}
} else if (bytes == 2u) {
uint8_t* p = buf + (base + c) * 2u;
const size_t step = (size_t)spp * 2u;
uint16_t prev;
memcpy(&prev, p, 2);
for (x = 1; x < w; x++) {
uint16_t cur;
p += step;
memcpy(&cur, p, 2);
cur = (uint16_t)(cur + prev);
memcpy(p, &cur, 2);
prev = cur;
}
} else if (bytes == 4u) {
uint8_t* p = buf + (base + c) * 4u;
const size_t step = (size_t)spp * 4u;
uint32_t prev;
memcpy(&prev, p, 4);
for (x = 1; x < w; x++) {
uint32_t cur;
p += step;
memcpy(&cur, p, 4);
cur = cur + prev;
memcpy(p, &cur, 4);
prev = cur;
}
}
}
}
}
/* Fast row unpackers for the common raw depths. Groups are chosen so each
consumes a whole number of bytes (12b: 2 samples / 3 bytes, 10b: 4 / 5,
14b: 4 / 7), removing the per-sample refill branch of the generic loop.
`n` is the sample count; tails fall back to the byte-aligned generic path. */
static void td_unpack_tail(const uint8_t* rp, uint16_t* dst, size_t n,
unsigned bps) {
uint32_t bitbuf = 0;
int nbits = 0;
size_t s;
for (s = 0; s < n; s++) {
uint32_t v;
while (nbits < (int)bps) {
bitbuf = (bitbuf << 8) | (uint32_t)(*rp++);
nbits += 8;
}
v = (bitbuf >> (nbits - (int)bps)) & ((1u << bps) - 1u);
nbits -= (int)bps;
bitbuf &= (1u << nbits) - 1u;
dst[s] = (uint16_t)v;
}
}
static void td_unpack_row_12(const uint8_t* rp, uint16_t* dst, size_t n) {
size_t i = 0;
for (; i + 2 <= n; i += 2, rp += 3) {
uint32_t t =
((uint32_t)rp[0] << 16) | ((uint32_t)rp[1] << 8) | (uint32_t)rp[2];
dst[i] = (uint16_t)(t >> 12);
dst[i + 1] = (uint16_t)(t & 0x0FFFu);
}
td_unpack_tail(rp, dst + i, n - i, 12u);
}
static void td_unpack_row_10(const uint8_t* rp, uint16_t* dst, size_t n) {
size_t i = 0;
for (; i + 4 <= n; i += 4, rp += 5) {
uint64_t t = ((uint64_t)rp[0] << 32) | ((uint64_t)rp[1] << 24) |
((uint64_t)rp[2] << 16) | ((uint64_t)rp[3] << 8) |
(uint64_t)rp[4];
dst[i] = (uint16_t)(t >> 30);
dst[i + 1] = (uint16_t)((t >> 20) & 0x03FFu);
dst[i + 2] = (uint16_t)((t >> 10) & 0x03FFu);
dst[i + 3] = (uint16_t)(t & 0x03FFu);
}
td_unpack_tail(rp, dst + i, n - i, 10u);
}
static void td_unpack_row_14(const uint8_t* rp, uint16_t* dst, size_t n) {
size_t i = 0;
for (; i + 4 <= n; i += 4, rp += 7) {
uint64_t t = ((uint64_t)rp[0] << 48) | ((uint64_t)rp[1] << 40) |
((uint64_t)rp[2] << 32) | ((uint64_t)rp[3] << 24) |
((uint64_t)rp[4] << 16) | ((uint64_t)rp[5] << 8) |
(uint64_t)rp[6];
dst[i] = (uint16_t)(t >> 42);
dst[i + 1] = (uint16_t)((t >> 28) & 0x3FFFu);
dst[i + 2] = (uint16_t)((t >> 14) & 0x3FFFu);
dst[i + 3] = (uint16_t)(t & 0x3FFFu);
}
td_unpack_tail(rp, dst + i, n - i, 14u);
}
/* Floating-point predictor (TIFF predictor 3), libtiff fpAcc algorithm. */
static int td_unpredict_fp(tinydng_context *ctx, uint8_t *buf, uint32_t w,
uint32_t h, uint16_t spp, size_t bytes,
tinydng_error *err) {
uint32_t y;
size_t wc = (size_t)w * spp; /* samples per row */
size_t cc = wc * bytes; /* bytes per row */
int host_big = td_host_big();
uint8_t *tmp;
if (bytes != 2u && bytes != 4u) {
return 1; /* nothing to do */
}
tmp = (uint8_t *)td_ctx_alloc(ctx, cc, err);
if (!tmp) {
return 0;
}
for (y = 0; y < h; y++) {
uint8_t *row = buf + (size_t)y * cc;
size_t i, n, b;
for (i = (size_t)spp; i < cc; i++) {
row[i] = (uint8_t)(row[i] + row[i - (size_t)spp]);
}
memcpy(tmp, row, cc);
for (n = 0; n < wc; n++) {
for (b = 0; b < bytes; b++) {
size_t src = host_big ? (b * wc + n) : ((bytes - 1u - b) * wc + n);
row[bytes * n + b] = tmp[src];
}
}
}
td_ctx_free(ctx, tmp);
return 1;
}
static int td_apply_predictor(tinydng_context *ctx, const td_geom *g,
uint8_t *block, uint32_t bw, uint32_t bh,
tinydng_error *err) {
if (g->predictor == 2u) {
if (g->sample_format == TINYDNG_SAMPLEFORMAT_IEEEFP) {
td_set_error(err, TINYDNG_E_UNSUPPORTED, TINYDNG_STAGE_DECODE, 0, 0, 0,
"predictor 2 invalid for float samples");
return 0;
}
td_unpredict_h(block, bw, bh, g->spp, g->out_bytes);
return 1;
}
if (g->predictor == 3u) {
if (g->sample_format != TINYDNG_SAMPLEFORMAT_IEEEFP) {
td_set_error(err, TINYDNG_E_UNSUPPORTED, TINYDNG_STAGE_DECODE, 0, 0, 0,
"predictor 3 requires float samples");
return 0;
}
return td_unpredict_fp(ctx, block, bw, bh, g->spp, g->out_bytes, err);
}
return 1; /* predictor 1 / none */
}
/* ------------------------------------------------------------------ */
/* Block decoders */
/* ------------------------------------------------------------------ */
/* Bytes of stored (pre-decode) sample data for one bw*bh block. */
/* Byte count of one row of MSB-first packed samples (width*spp*bps bits,
rounded up to a whole byte). Rows are independent and byte-aligned. */
static int td_packed_row_bytes(uint32_t width, uint16_t spp, uint16_t bps,
size_t *out) {
size_t bits;
if (!td_safe_mul_size((size_t)width, (size_t)spp, &bits) ||
!td_safe_mul_size(bits, (size_t)bps, &bits)) {
return 0;
}
*out = bits / 8u + ((bits % 8u) != 0u);
return 1;
}
static int td_stored_block_size(const td_geom *g, uint32_t bw, uint32_t bh,
size_t *out) {
size_t spr, in_row, total;
/* samples per row = bw * spp; overflow-safe so 32-bit builds fail closed. */
if (!td_safe_mul_size((size_t)bw, (size_t)g->spp, &spr)) {
return 0;
}
if (g->bps == 8u || g->bps == 16u || g->bps == 32u) {
if (!td_safe_mul_size(spr, (size_t)g->bps / 8u, &in_row)) {
return 0;
}
} else if (g->bps >= 1u && g->bps <= 16u) {
size_t bits;
if (!td_safe_mul_size(spr, (size_t)g->bps, &bits)) {
return 0;
}
in_row = bits / 8u + ((bits % 8u) != 0u);
} else {
return 0;
}
if (!td_safe_mul_size(in_row, bh, &total)) {
return 0;
}
*out = total;
return 1;
}
/* Convert a contiguous stored-byte block (file byte order) into the decoded
`block` (host order, out_bps samples). Handles 8/16/32 + 10/12/14 packed. */
static tinydng_status td_fill_block_from_stored(const td_geom *g, int big_endian,
const uint8_t *src,
size_t src_len, uint32_t bw,
uint32_t bh, uint8_t *block,
tinydng_error *err) {
uint32_t y;
size_t need;
if (!td_stored_block_size(g, bw, bh, &need)) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"stored block size overflow");
return TINYDNG_E_BOUNDS;
}
if (src_len < need) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"stored data too small: need=%zu have=%zu", need, src_len);
return TINYDNG_E_BOUNDS;
}
if (g->packed) {
/* KEEP_PACKED: emit the raw stored bytes (already MSB-first, row-aligned,
predictor already applied at the sample level by the encoder). */
size_t rowb;
if (!td_packed_row_bytes(bw, g->spp, g->bps, &rowb)) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"packed row size overflow");
return TINYDNG_E_BOUNDS;
}
for (y = 0; y < bh; y++) {
memcpy(block + (size_t)y * rowb, src + (size_t)y * rowb, rowb);
}
return TINYDNG_OK;
}
if (g->bps == 8u || g->bps == 16u || g->bps == 32u) {
size_t stored_bytes = (size_t)g->bps / 8u;
size_t samples_per_row, in_row_bytes;
if (!td_safe_mul_size((size_t)bw, (size_t)g->spp, &samples_per_row) ||
!td_safe_mul_size(samples_per_row, stored_bytes, &in_row_bytes)) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"stored row size overflow");
return TINYDNG_E_BOUNDS;
}
int need_swap = (stored_bytes > 1u) && (big_endian != td_host_big());
for (y = 0; y < bh; y++) {
memcpy(block + (size_t)y * in_row_bytes, src + (size_t)y * in_row_bytes,
in_row_bytes);
}
if (need_swap) {
size_t total_samples;
size_t i;
if (!td_safe_mul_size(samples_per_row, (size_t)bh, &total_samples)) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"stored sample count overflow");
return TINYDNG_E_BOUNDS;
}
if (stored_bytes == 2u) {
uint8_t* q = block;
for (i = 0; i < total_samples; i++, q += 2) {
uint8_t t = q[0];
q[0] = q[1];
q[1] = t;
}
} else {
uint8_t* q = block;
for (i = 0; i < total_samples; i++, q += 4) {
uint8_t a = q[0], b = q[1], c = q[2], d = q[3];
q[0] = d;
q[1] = c;
q[2] = b;
q[3] = a;
}
}
}
return TINYDNG_OK;
}
/* Packed sub-byte depths (10/12/14): MSB-first, rows byte-aligned. */
{
size_t samples_per_row, bits_per_row, in_row_bytes;
if (!td_safe_mul_size((size_t)bw, (size_t)g->spp, &samples_per_row) ||
!td_safe_mul_size(samples_per_row, (size_t)g->bps, &bits_per_row)) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"packed row size overflow");
return TINYDNG_E_BOUNDS;
}
in_row_bytes = bits_per_row / 8u + ((bits_per_row % 8u) != 0u);
for (y = 0; y < bh; y++) {
const uint8_t *rp = src + (size_t)y * in_row_bytes;
size_t row_base = (size_t)y * samples_per_row;
if (g->out_bytes == 1u) {
/* bps < 8: 8-bit output elements (incl. PSD bitmap polarity). */
uint32_t bitbuf = 0;
int nbits = 0;
size_t s;
for (s = 0; s < samples_per_row; s++) {
uint32_t v;
while (nbits < g->bps) {
bitbuf = (bitbuf << 8) | (uint32_t)(*rp++);
nbits += 8;
}
v = bitbuf >> (nbits - g->bps);
nbits -= g->bps;
bitbuf &= (1u << nbits) - 1u; /* keep only the unconsumed low bits */
if (g->invert_1bit && g->bps == 1u) {
/* PSD bitmap polarity: stored bit 1 = black. */
v = v ? 0u : 255u;
}
((uint8_t *)block)[row_base + s] = (uint8_t)v;
}
} else if (g->bps == 12u && samples_per_row >= 2u &&
in_row_bytes == ((samples_per_row / 2u) * 3u)) {
/* Fast paths for the common raw depths; group boundaries are
byte-aligned so the tail handler resumes cleanly. */
td_unpack_row_12(rp, (uint16_t*)(void*)block + row_base,
samples_per_row);
} else if (g->bps == 10u && samples_per_row >= 4u &&
in_row_bytes == ((samples_per_row / 4u) * 5u)) {
td_unpack_row_10(rp, (uint16_t*)(void*)block + row_base,
samples_per_row);
} else if (g->bps == 14u && samples_per_row >= 4u &&
in_row_bytes == ((samples_per_row / 4u) * 7u)) {
td_unpack_row_14(rp, (uint16_t*)(void*)block + row_base,
samples_per_row);
} else {
/* MSB-first accumulator: shift whole bytes in, pull bps bits out of
the top. nbits stays below bps+8 <= 24, so one 32-bit value
suffices. */
uint32_t bitbuf = 0;
int nbits = 0;
size_t s;
for (s = 0; s < samples_per_row; s++) {
uint32_t v;
while (nbits < g->bps) {
bitbuf = (bitbuf << 8) | (uint32_t)(*rp++);
nbits += 8;
}
v = bitbuf >> (nbits - g->bps);
nbits -= g->bps;
bitbuf &= (1u << nbits) - 1u;
{
uint16_t w16 = (uint16_t)v;
memcpy((uint8_t*)block + (row_base + s) * 2u, &w16, sizeof(w16));
}
}
}
}
}
return TINYDNG_OK;
}
/* Decode one uncompressed segment into `block`. */
static tinydng_status td_decode_block_uncompressed(
tinydng_context* ctx, tinydng_io* io, uint64_t io_size, int big_endian,
const td_geom* g, const tinydng_segment* seg, uint32_t bw, uint32_t bh,
uint8_t* block, td_scratch* in_re, tinydng_error* err) {
const uint8_t *src;
size_t need;
tinydng_status st;
if (!td_stored_block_size(g, bw, bh, &need)) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"uncompressed input size overflow");
return TINYDNG_E_BOUNDS;
}
if ((uint64_t)need > seg->byte_count) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, seg->offset,
"strip/tile too small: need=%zu have=%llu", need,
(unsigned long long)seg->byte_count);
return TINYDNG_E_BOUNDS;
}
src = td_segment_bytes(ctx, io, io_size, seg->offset, need, in_re, err);
if (!src) {
return td_error_status_or(err, TINYDNG_E_BOUNDS);
}
st = td_fill_block_from_stored(g, big_endian, src, need, bw, bh, block, err);
return st;
}
#if !defined(TINYDNG_NO_LZW) || !defined(TINYDNG_NO_PACKBITS) || \
!defined(TINYDNG_NO_ZIP)
/* Shared helper: decode a compressed segment into a stored-byte scratch of
exactly `need` bytes, then convert to the output block. */
static tinydng_status td_finish_compressed(tinydng_context *ctx, int big_endian,
const td_geom *g, uint8_t *stored,
size_t got, size_t need, uint32_t bw,
uint32_t bh, uint8_t *block,
tinydng_error *err) {
(void)ctx;
if (got != need) {
td_set_error(err, TINYDNG_E_DECODE, TINYDNG_STAGE_DECODE, 0, 0, 0,
"decompressed size mismatch: got=%zu need=%zu", got, need);
return TINYDNG_E_DECODE;
}
return td_fill_block_from_stored(g, big_endian, stored, need, bw, bh, block,
err);
}
#endif
#ifndef TINYDNG_NO_LZW
/* TIFF LZW (early-change, MSB-first). Returns decoded byte count or -1.
*
* Like libtiff, decoding stops as soon as the output buffer is satisfied:
* real-world encoders (Photoshop, NASA PDS) may terminate strips without an
* explicit EOI and pad the final bits with garbage, so consuming codes past
* the expected byte count would spuriously fail valid files.
*/
static long td_lzw_decode(const uint8_t *in, size_t in_len, uint8_t *out,
size_t out_cap) {
enum { CLEAR = 256, EOI = 257 };
uint16_t prefix[4096];
uint8_t suffix[4096];
int code_size = 9;
int next_code = 258;
size_t out_pos = 0;
uint64_t bitbuf = 0;
int bitcnt = 0;
size_t in_pos = 0;
int prev = -1;
for (;;) {
int code;
/* Refill up to 5 bytes at once so <=12-bit codes rarely stall; identical
semantics to a byte-at-a-time MSB-first reader. */
while (bitcnt < code_size) {
size_t avail = in_len - in_pos;
size_t take = avail < 5u ? avail : 5u;
uint64_t v = 0;
size_t i;
if (take == 0) {
break;
}
for (i = 0; i < take; i++) {
v = (v << 8) | in[in_pos + i];
}
in_pos += take;
bitbuf = (bitbuf << (take * 8u)) | v;
bitcnt += (int)(take * 8u);
}
if (bitcnt < code_size) {
break; /* ran out of input */
}
code = (int)((bitbuf >> (bitcnt - code_size)) & ((1u << code_size) - 1u));
bitcnt -= code_size;
if (code == EOI) {
break;
}
if (code == CLEAR) {
code_size = 9;
next_code = 258;
prev = -1;
continue;
}
if (prev == -1) {
if (code >= 256) {
return -1;
}
if (out_pos >= out_cap) {
return -1;
}
out[out_pos++] = (uint8_t)code;
prev = code;
if (out_pos >= out_cap) {
break; /* output satisfied */
}
continue;
}
{
int kwk = (code == next_code);
int head = kwk ? prev : code;
int c = head;
size_t len = 0;
if (!kwk && code > next_code) {
return -1; /* invalid code */
}
/* Measure the string so the capacity is verified with one check, then
emit it forward directly into the output (no intermediate stack).
The prefix-chain walk visits characters last-to-first, so bytes are
written through a descending cursor. */
while (c >= 256) {
len++;
c = prefix[c];
}
/* c == leading literal == first char of this string */
len += kwk ? 2u : 1u;
if (out_pos > out_cap || len > out_cap - out_pos) {
return -1;
}
{
size_t w_last = out_pos + len - 1u; /* inclusive last slot */
size_t w = kwk ? (w_last - 1u) : w_last;
if (kwk) {
/* KwKwK: one extra copy of this string's first char. */
out[w_last] = (uint8_t)c;
}
c = head;
while (c >= 256) {
out[w--] = suffix[c];
c = prefix[c];
}
out[out_pos] = (uint8_t)c; /* leading literal / first char */
out_pos += len;
/* Add new entry prev + firstchar(this string). */
if (next_code < 4096) {
prefix[next_code] = (uint16_t)prev;
suffix[next_code] = (uint8_t)c;
next_code++;
/* TIFF early change: widen one code before the table fills. */
if (code_size < 12 && next_code == (1 << code_size) - 1) {
code_size++;
}
}
}
prev = code;
}
if (out_pos >= out_cap) {
break; /* output satisfied */
}
}
return (long)out_pos;
}
#endif /* TINYDNG_NO_LZW */
#ifndef TINYDNG_NO_PACKBITS
long td_packbits_decode(const uint8_t *in, size_t in_len, uint8_t *out,
size_t out_cap) {
size_t ip = 0;
size_t op = 0;
while (ip < in_len) {
int8_t n = (int8_t)in[ip++];
if (n >= 0) {
size_t cnt = (size_t)n + 1u;
if (cnt > in_len - ip || cnt > out_cap - op) {
return -1;
}
memcpy(out + op, in + ip, cnt);
op += cnt;
ip += cnt;
} else if (n != -128) {
size_t cnt = (size_t)(1 - n);
uint8_t v;
if (ip >= in_len || cnt > out_cap - op) {
return -1;
}
v = in[ip++];
memset(out + op, v, cnt);
op += cnt;
}
}
return (long)op;
}
#endif /* TINYDNG_NO_PACKBITS */
/* Decode one LZW/PackBits/ZIP segment into `block`. `in_re`/`st_re` are
optional reusable per-worker scratches (input bytes / decompressed bytes). */
static tinydng_status td_decode_block_compressed(
tinydng_context* ctx, tinydng_io* io, uint64_t io_size, int big_endian,
const td_geom* g, const tinydng_segment* seg, uint16_t compression,
uint32_t bw, uint32_t bh, uint8_t* block, td_scratch* in_re,
td_scratch* st_re, tinydng_error* err) {
const uint8_t *src;
uint8_t* stored = NULL;
size_t need;
long got = -1;
tinydng_status st;
if (!td_stored_block_size(g, bw, bh, &need)) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, 0,
"stored block size overflow");
return TINYDNG_E_BOUNDS;
}
if (seg->byte_count > (uint64_t)INT32_MAX) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, seg->offset,
"compressed segment too large");
return TINYDNG_E_BOUNDS;
}
src = td_segment_bytes(ctx, io, io_size, seg->offset, (size_t)seg->byte_count,
in_re, err);
if (!src) {
return td_error_status_or(err, TINYDNG_E_BOUNDS);
}
/* Fast path: when the stored layout equals the output layout (8-bit
samples, or matching byte order for 16/32), decompress straight into the
destination block and skip both the scratch and the final copy pass.
PSD zip-with-prediction is excluded: its unpredict pass must run before
the block conversion. */
if (compression != (uint16_t)TD_COMPRESSION_PSD_ZIP_PRED && !g->packed &&
g->bps == g->out_bps && (g->bps == 8u || big_endian == td_host_big())) {
#ifndef TINYDNG_NO_LZW
if (compression == TINYDNG_COMPRESSION_LZW) {
got = td_lzw_decode(src, (size_t)seg->byte_count, block, need);
} else
#endif
#ifndef TINYDNG_NO_PACKBITS
if (compression == TINYDNG_COMPRESSION_PACKBITS) {
got = td_packbits_decode(src, (size_t)seg->byte_count, block, need);
} else
#endif
#ifndef TINYDNG_NO_ZIP
if (compression == TINYDNG_COMPRESSION_ZIP) {
mz_ulong dlen = (mz_ulong)need;
int mzr = mz_uncompress(block, &dlen, src, (mz_ulong)seg->byte_count);
got = (mzr == MZ_OK) ? (long)dlen : -1;
} else
#endif
{
/* fall through to the generic path below */
}
if (got >= 0) {
if ((size_t)got != need) {
td_set_error(err, TINYDNG_E_DECODE, TINYDNG_STAGE_DECODE, 0, 0, 0,
"decompressed size mismatch: got=%ld need=%zu", got, need);
return TINYDNG_E_DECODE;
}
return TINYDNG_OK; /* predictor is applied by the caller */
}
got = -1; /* fall back to the generic path for uniform error reporting */
}
stored = st_re ? td_scratch_get(ctx, st_re, need, err)
: (uint8_t*)td_ctx_alloc(ctx, need, err);
if (!stored) {
return TINYDNG_E_OOM;
}
switch (compression) {
#ifndef TINYDNG_NO_LZW
case TINYDNG_COMPRESSION_LZW:
got = td_lzw_decode(src, (size_t)seg->byte_count, stored, need);
break;
#endif
#ifndef TINYDNG_NO_PACKBITS
case TINYDNG_COMPRESSION_PACKBITS:
got = td_packbits_decode(src, (size_t)seg->byte_count, stored, need);
break;
#endif
#ifndef TINYDNG_NO_ZIP
case TINYDNG_COMPRESSION_ZIP: {
mz_ulong dlen = (mz_ulong)need;
int mzr = mz_uncompress(stored, &dlen, src, (mz_ulong)seg->byte_count);
got = (mzr == MZ_OK) ? (long)dlen : -1;
break;
}
#ifndef TINYDNG_NO_PSD
case TD_COMPRESSION_PSD_ZIP_PRED: {
/* PSD zip-with-prediction: one whole channel plane per segment. */
mz_ulong dlen = (mz_ulong)need;
int mzr = mz_uncompress(stored, &dlen, src, (mz_ulong)seg->byte_count);
got = (mzr == MZ_OK) ? (long)dlen : -1;
if (got == (long)need &&
!td_psd_unpredict_plane(ctx, stored, bw, bh, g->bps, err)) {
got = -1;
}
break;
}
#endif
#endif
default:
if (!st_re) {
td_ctx_free(ctx, stored);
}
td_set_error(err, TINYDNG_E_UNSUPPORTED, TINYDNG_STAGE_DECODE, 0, 0, 0,
"compression %u not enabled", (unsigned)compression);
return TINYDNG_E_UNSUPPORTED;
}
if (got < 0) {
if (!st_re) {
td_ctx_free(ctx, stored);
}
td_set_error(err, TINYDNG_E_DECODE, TINYDNG_STAGE_DECODE, 0, 0, seg->offset,
"decompression failed (comp=%u)", (unsigned)compression);
return TINYDNG_E_DECODE;
}
st = td_finish_compressed(ctx, big_endian, g, stored, (size_t)got, need, bw,
bh, block, err);
if (!st_re) {
td_ctx_free(ctx, stored);
}
return st;
}
#ifndef TINYDNG_NO_BASELINE_JPEG
/* Decode one baseline/lossy JPEG segment (8-bit) into `block`. */
static tinydng_status td_decode_block_baseline(
tinydng_context* ctx, tinydng_io* io, uint64_t io_size, const td_geom* g,
const tinydng_segment* seg, uint8_t* block, uint32_t bw, uint32_t bh,
td_scratch* in_re, tinydng_error* err) {
td_scratch local;
td_scratch* sc = in_re ? in_re : &local;
const uint8_t *src;
int w = 0, h = 0, comp = 0;
stbi_uc *pixels;
if (!in_re) {
local.p = NULL;
local.cap = 0;
}
if (seg->byte_count > (uint64_t)INT32_MAX) {
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0, seg->offset,
"jpeg segment too large");
return TINYDNG_E_BOUNDS;
}
src = td_segment_bytes(ctx, io, io_size, seg->offset, (size_t)seg->byte_count,
sc, err);
if (!src) {
return td_error_status_or(err, TINYDNG_E_BOUNDS);
}
/* Decompression-bomb guard: stb_image allocates through libc malloc,
* outside the tracked allocator and its memory cap. Probe the header and
* reject images whose decoded size cannot fit the remaining budget before
* letting stb allocate. */
if (!stbi_info_from_memory(src, (int)seg->byte_count, &w, &h, &comp)) {
if (sc == &local) td_scratch_free(ctx, sc);
td_set_error(err, TINYDNG_E_DECODE, TINYDNG_STAGE_DECODE, 0, 0, seg->offset,
"jpeg header parse failed: %s", stbi_failure_reason());
return TINYDNG_E_DECODE;
}
{
uint64_t need_px = (uint64_t)(uint32_t)w * (uint64_t)(uint32_t)h;
uint64_t need_bytes;
uint64_t budget;
/* Read the accounting under the allocator's lock discipline so a
* multi-threaded decode never races td_ctx_alloc's bookkeeping. */
td_mutex *L = ctx->mt_active ? ctx->lock : NULL;
td_mutex_lock(L);
budget = ctx->memory_cap_bytes ? (ctx->memory_cap_bytes - ctx->memory_used)
: UINT64_MAX;
td_mutex_unlock(L);
if (!td_safe_mul_u64(need_px, (uint64_t)((unsigned)g->spp),
&need_bytes) ||
need_bytes > budget) {
if (sc == &local) td_scratch_free(ctx, sc);
td_set_error(err, TINYDNG_E_BOUNDS, TINYDNG_STAGE_DECODE, 0, 0,
seg->offset,
"jpeg decoded size %dx%dx%u exceeds memory budget (%llu "
"bytes left)",
w, h, (unsigned)g->spp, (unsigned long long)budget);
return TINYDNG_E_BOUNDS;
}
}
pixels = stbi_load_from_memory(src, (int)seg->byte_count, &w, &h, &comp,
(int)g->spp);
if (sc == &local) td_scratch_free(ctx, sc);
if (!pixels) {
td_set_error(err, TINYDNG_E_DECODE, TINYDNG_STAGE_DECODE, 0, 0, seg->offset,
"stb baseline JPEG decode failed: %s", stbi_failure_reason());
return TINYDNG_E_DECODE;
}
if ((uint32_t)w != bw || (uint32_t)h != bh) {
stbi_image_free(pixels);
td_set_error(err, TINYDNG_E_DECODE, TINYDNG_STAGE_DECODE, 0, 0, seg->offset,
"baseline JPEG dims %dx%d != block %ux%u", w, h, bw, bh);
return TINYDNG_E_DECODE;
}
memcpy(block, pixels, (size_t)bw * bh * g->spp); /* 8-bit, spp channels */
stbi_image_free(pixels);
return TINYDNG_OK;
}
#endif /* TINYDNG_NO_BASELINE_JPEG */
/* Streaming adapter: exposes a byte range of a tinydng_io to the LJPEG
streaming decoder, so stdio (map == NULL) segments are never materialized
as a whole; the entropy payload is destuffed straight from the backend. */
typedef struct td_lj92_stream_io {
tinydng_io *io;
uint64_t base; /* absolute file offset of the segment */
uint64_t size; /* segment size */
} td_lj92_stream_io;
static size_t td_lj92_stream_read(void *user, uint64_t off, void *dst,
size_t len) {
td_lj92_stream_io *s = (td_lj92_stream_io *)user;
if (off > s->size || (uint64_t)len > (s->size - off)) {
return 0;
}
if (UINT64_MAX - s->base < off) {
return 0;
}
return s->io->read(s->io, s->base + off, dst, len);
}
static uint64_t td_lj92_stream_size(void *user) {
return ((td_lj92_stream_io *)user)->size;
}