-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathumbrielpng.c
1477 lines (1307 loc) · 45.5 KB
/
umbrielpng.c
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
/**
* @file umbrielpng.c
* @author Leo Izen <[email protected]>
* @brief PNG Tweaker
* @version 0.1
* @date 2023-07-15
*
* BSD 3-Clause License
*
* Copyright (c) 2023-2024, Leo Izen (Traneptora)
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <errno.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <zlib.h>
#define maketag(a,b,c,d) ((((uint32_t)(a)) << 24) | (((uint32_t)(b)) << 16) |\
(((uint32_t)(c)) << 8) | (uint32_t)(d))
#define abs(a) ((a) < 0 ? -(a) : (a))
#define within(a,b,tolerance) (abs((a)-(b)) <= (tolerance))
#define freep(p) do { \
if (p) free(p); \
(p) = NULL; \
} while (0)
#define tag_IHDR maketag('I','H','D','R')
#define tag_PLTE maketag('P','L','T','E')
#define tag_IDAT maketag('I','D','A','T')
#define tag_IEND maketag('I','E','N','D')
#define tag_cICP maketag('c','I','C','P')
#define tag_iCCP maketag('i','C','C','P')
#define tag_sRGB maketag('s','R','G','B')
#define tag_cHRM maketag('c','H','R','M')
#define tag_gAMA maketag('g','A','M','A')
#define tag_fdAT maketag('f','d','A','T')
#define tag_acTL maketag('a','c','T','L')
#define tag_fcTL maketag('f','c','T','L')
#define tag_sBIT maketag('s','B','I','T')
#define tag_tRNS maketag('t','R','N','S')
#define tag_hIST maketag('h','I','S','T')
#define tag_bKGD maketag('b','K','G','D')
#define tag_eXIf maketag('e','X','I','f')
#define tag_pHYs maketag('p','H','Y','s')
#define tag_sPLT maketag('s','P','L','T')
#define tag_tIME maketag('t','I','M','E')
#define tag_tEXt maketag('t','E','X','t')
#define tag_zTXt maketag('z','T','X','t')
#define tag_iTXt maketag('i','T','X','t')
#define tag_cLLi maketag('c','L','L','i')
#define tag_mDCv maketag('m','D','C','v')
#define array_size(a) (sizeof((a))/sizeof(*(a)))
#define NEGERROR(e) (-abs(e))
typedef struct UmbPngChunk {
uint32_t chunk_size;
uint32_t tag;
uint8_t *data;
uint32_t data_size;
uint32_t crc32;
size_t offset;
} UmbPngChunk;
typedef struct UmbPngChunkChain {
UmbPngChunk chunk;
struct UmbPngChunkChain *prev;
struct UmbPngChunkChain *next;
} UmbPngChunkChain;
enum UmbPngColorType {
COLOR_GRAY = 0,
COLOR_TRUE = 2,
COLOR_INDEXED = 3,
COLOR_GRAY_A = 4,
COLOR_RGBA = 6,
};
enum UmbPngColorPrim {
PRIM_RESERVED0,
PRIM_BT709,
PRIM_UNSPECIFIED,
PRIM_RESERVED3,
PRIM_BT470M,
PRIM_BT470BG,
PRIM_BT601,
PRIM_SMPTE_ST_240,
PRIM_FILM_C,
PRIM_BT2020,
PRIM_SMPTE_ST_428_1,
PRIM_SMPTE_RP_431_2,
PRIM_SMPTE_EG_432_1,
PRIM_H273_22 = 22,
};
enum UmbPngColorTrc {
TRC_RESERVED0,
TRC_BT709,
TRC_UNSPECIFIED,
TRC_RESERVED3,
TRC_GAMMA22,
TRC_GAMMA28,
TRC_BT601,
TRC_SMPTE_ST_240,
TRC_LINEAR,
TRC_LOGARITHMIC_100,
TRC_LOGARITHMIC_100_ROOT10,
TRC_IEC61966_2_4,
TRC_BT1361,
TRC_SRGB,
TRC_BT2020_10,
TRC_BT2020_12,
TRC_SMPTE_ST_2084_PQ,
TRC_SMPTE_ST_428_1,
TRC_ARIB_STD_B67_HLG,
};
typedef struct UmbPngScanData {
int have_cicp;
int have_iccp;
int have_srgb;
int have_chrm;
int have_gama;
int have_plte;
int icc_is_srgb;
int cicp_is_srgb;
int chrm_is_srgb;
uint32_t width;
uint32_t height;
int depth;
enum UmbPngColorType color;
int sbit[4];
} UmbPngScanData;
typedef struct UmbBuffer {
size_t size;
uint8_t *data;
} UmbBuffer;
typedef struct UmbPngOptions {
int verbose;
int fix;
const char *argv0;
const char *input;
const char *output;
int force_cicp;
int forced_prim;
int forced_trc;
} UmbPngOptions;
typedef struct UmbPngIccScan {
int32_t wp_xyz[3];
int32_t red_xyz[3];
int32_t green_xyz[3];
int32_t blue_xyz[3];
int32_t para_curv[7];
} UmbPngIccScan;
static const char *const color_names[7] = {
"Grayscale",
"",
"RGB",
"Indexed",
"Grayscale + Alpha",
"",
"RGB + Alpha",
};
static const int color_channels[7] = {
1, 0, 3, 3, 2, 0, 4,
};
static const uint8_t png_signature[8] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
};
typedef struct LookupTableEntry {
int index;
const char *names[8];
} LookupTableEntry;
static const LookupTableEntry prim_names[] = {
{PRIM_RESERVED0, {"0", "Reserved0", NULL}},
{PRIM_BT709, {"1", "BT.709", "BT709", "709", NULL}},
{PRIM_UNSPECIFIED, {"2", "Unspecified", "Unknown", NULL}},
{PRIM_RESERVED3, {"3", "Reserved", "Reserved3", NULL}},
{PRIM_BT470M, {"4", "BT.470M", "BT470M", NULL}},
{PRIM_BT470BG, {"5", "BT.470BG", "BT470BG", NULL}},
{PRIM_BT601, {"6", "BT.601", "BT601", "601", NULL}},
{PRIM_SMPTE_ST_240, {"7", "SMPTEST240", "ST240", NULL}},
{PRIM_FILM_C, {"8", "FilmIlluminantC", "C", NULL}},
{PRIM_BT2020, {"9", "BT.2020", "BT2020", "BT.2100", "BT2100", "2020", "2100", NULL}},
{PRIM_SMPTE_ST_428_1, {"10", "SMPTE428", "CIEXYZ", "XYZ", NULL}},
{PRIM_SMPTE_RP_431_2, {"11", "DCIP3", "SMPTE431-2", NULL}},
{PRIM_SMPTE_EG_432_1, {"12", "DisplayP3", "P3", "SMPTE432-1", "P3D65", NULL}},
{PRIM_H273_22, {"22", "Ebu3213-E", NULL}},
};
static const LookupTableEntry trc_names[] = {
{TRC_RESERVED0, {"0", "Reserved0", NULL}},
{TRC_BT709, {"1", "BT.709", "BT709", "709", NULL}},
{TRC_UNSPECIFIED, {"2", "Unspecified", "Unknown", NULL}},
{TRC_RESERVED3, {"3", "Reserved", "Reserved3", NULL}},
{TRC_GAMMA22, {"4", "Gamma2.2", "Gamma22", "Gamma45", "Gamma45455", NULL}},
{TRC_GAMMA28, {"5", "Gamma2.8", "Gamma28", "Gamma36", "Gamma35", "Gamma35714", NULL}},
{TRC_BT601, {"6", "BT.601", "BT601", "601", NULL}},
{TRC_SMPTE_ST_240, {"7", "SMPTE240", NULL}},
{TRC_LINEAR, {"8", "Linear", "LinearLight", NULL}},
{TRC_LOGARITHMIC_100, {"9", "Logarithmic", "LogarithmicLight", "LogarithmicLight100", NULL}},
{TRC_LOGARITHMIC_100_ROOT10, {"10", "LogarithmicRoot10", NULL}},
{TRC_IEC61966_2_4, {"11", "IEC61966-2-4", "61966-2-4", NULL}},
{TRC_BT1361, {"12", "BT.1361", "BT1361", "1361", NULL}},
{TRC_SRGB, {"13", "sRGB", "IEC61966-2-1", "61966-2-1", NULL}},
{TRC_BT2020_10, {"14", "BT.2020_10", "BT2020_10", "2020_10", NULL}},
{TRC_BT2020_10, {"15", "BT.2020_12", "BT2020_12", "2020_12", NULL}},
{TRC_SMPTE_ST_2084_PQ, {"16", "PQ", "SMPTE2084", NULL}},
{TRC_SMPTE_ST_428_1, {"17", "DCI", "SMPTE428-1", "Gamma26", "Gamma2.6", "Gamma38", "Gamma38462", NULL}},
{TRC_ARIB_STD_B67_HLG, {"18", "HLG", "B67", "HybridLogGamma", NULL}},
};
static const UmbPngChunk default_srgb_chunk = {
.chunk_size = 13,
.tag = tag_sRGB,
.data = (uint8_t[]){1},
.data_size = 1,
.crc32 = 0xd9c92c7f,
.offset = 12,
};
static const uint32_t default_chrm_data[8] = {
31270, 32900, 64000, 33000, 30000, 60000, 15000, 6000,
};
static const char *const srgb_rendering_intents[] = {
"Perceptual",
"Relative",
"Saturation",
"Absolute",
};
static const uint32_t strip_chunks[8] = {
tag_bKGD, tag_eXIf, tag_pHYs, tag_sPLT,
tag_tIME, tag_tEXt, tag_zTXt, tag_iTXt,
};
static inline uint32_t rbe32(const uint8_t *tag) {
return maketag(tag[0],tag[1],tag[2],tag[3]);
}
static inline void wbe32(uint8_t *tag, uint32_t be32) {
tag[0] = (be32 >> 24) & 0xFF;
tag[1] = (be32 >> 16) & 0xFF;
tag[2] = (be32 >> 8) & 0xFF;
tag[3] = be32 & 0xFF;
}
static inline UmbBuffer buffer_from_chunk(const UmbPngChunk *chunk) {
UmbBuffer buf = {
.data = chunk->data,
.size = chunk->data_size,
};
return buf;
}
static int lookup_array(const LookupTableEntry *array, size_t len, const char *lookup) {
for (size_t i = 0; i < len; i++) {
for (size_t j = 0; array[i].names[j]; j++) {
if (!strcasecmp(array[i].names[j], lookup))
return array[i].index;
}
}
return -1;
}
static int scan_chunk(FILE *in, UmbPngChunk *chunk, const UmbPngChunk *last, const char **error) {
size_t read;
uint8_t tag[4];
read = fread(tag, 4, 1, in);
if (!read)
goto fail;
chunk->data_size = rbe32(tag);
read = fread(tag, 4, 1, in);
if (!read)
goto fail;
chunk->tag = rbe32(tag);
if (fseek(in, chunk->data_size, SEEK_CUR) < 0)
goto fail;
read = fread(tag, 4, 1, in);
if (!read)
goto fail;
chunk->crc32 = rbe32(tag);
chunk->chunk_size = 12 + chunk->data_size;
chunk->offset = last ? last->offset + last->chunk_size : 8;
return 0;
fail:
if (feof(in)) {
*error = NULL;
} else {
perror(*error);
*error = "Error reading chunk";
}
return -1;
}
static int read_chunk(FILE *in, UmbPngChunk *chunk, const char **error) {
int ret;
uint8_t tag[4];
size_t total = 0;
uint32_t crc;
wbe32(tag, chunk->tag);
crc = crc32_z(0, tag, 4);
if (chunk->data_size)
chunk->data = malloc(chunk->data_size);
if (chunk->data_size && !chunk->data) {
fprintf(stderr, "Allocation failed\n");
return NEGERROR(ENOMEM);
}
if (chunk->data_size) {
ret = fseek(in, chunk->offset + 8, SEEK_SET);
if (ret < 0)
goto fail;
}
while (total < chunk->data_size) {
size_t read = fread(chunk->data + total, 1, chunk->data_size - total, in);
if (!read)
goto fail;
crc = crc32_z(crc, chunk->data + total, read);
total += read;
}
if (crc != chunk->crc32) {
fprintf(stderr, "Warning: computed CRC32 %08x does not match read CRC32 %08x\n", crc, chunk->crc32);
chunk->crc32 = crc;
}
return 0;
fail:
perror(*error);
*error = "Error reading chunk data";
freep(chunk->data);
return -1;
}
static int write_chunk(FILE *out, const UmbPngChunk *chunk, const char **error) {
uint8_t tag[4];
size_t count;
size_t total = 0;
wbe32(tag, chunk->data_size);
count = fwrite(tag, 4, 1, out);
if (!count)
goto fail;
wbe32(tag, chunk->tag);
count = fwrite(tag, 4, 1, out);
if (!count)
goto fail;
while (total < chunk->data_size) {
count = fwrite(chunk->data + total, 1, chunk->data_size - total, out);
if (!count)
goto fail;
total += count;
}
wbe32(tag, chunk->crc32);
count = fwrite(tag, 4, 1, out);
if (!count)
goto fail;
return 0;
fail:
perror(*error);
*error = "Error writing chunk data";
return -1;
}
static int inflate_zlib_buffer(const UmbBuffer *zbuf, UmbBuffer *outbuf, const char **error) {
z_stream strm = { 0 };
size_t size = zbuf->size;
size_t total_read = 0;
int ret;
void *temp;
ret = inflateInit(&strm);
if (ret != Z_OK)
goto fail;
temp = realloc(outbuf->data, size);
if (!temp)
goto fail;
outbuf->data = temp;
strm.next_in = zbuf->data;
strm.avail_in = zbuf->size;
do {
size_t have;
if (size <= total_read) {
size *= total_read / size + 1;
temp = realloc(outbuf->data, size);
if (!temp)
goto fail;
outbuf->data = temp;
}
strm.next_out = outbuf->data + total_read;
strm.avail_out = size - total_read;
ret = inflate(&strm, Z_NO_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END)
goto fail;
have = size - total_read - strm.avail_out;
total_read += have;
} while (ret != Z_STREAM_END);
inflateEnd(&strm);
outbuf->size = total_read;
return 0;
fail:
inflateEnd(&strm);
freep(outbuf->data);
*error = "Error inflating zlib-compresed buffer";
return -1;
}
/**
* Wrapper around strnlen, caps at max_len, or buffer->size if max_len is zero
* If the terminating '\0' is not found, returns an error.
*
* This is used when parsing various chunks that have a 1-79 byte keyword
* followed by a NUL terminator.
*
* init_len includes the terminating NUL byte, unlike strlen() and family.
*
* If an error is returned, init_len is left untouched.
*/
static int get_initial_text_len(size_t *init_len, const UmbBuffer *buffer, size_t max_len, const char **error) {
size_t max = buffer->size;
size_t text_len;
if (max_len && max > max_len)
max = max_len;
text_len = strnlen((const char *) buffer->data, max);
if (buffer->data[text_len]) {
*error = "Not null terminated initial text";
return -1;
}
*init_len = text_len + 1;
return 0;
}
/**
* Extracts the ICC profile from the iCCP chunk and allocates it into
* the buffer in *profile. profile->data must be already allocated, or NULL.
*
* The returned profile must be freed elsewhere.
*/
static int inflate_iccp(const UmbPngChunk *iccp, UmbBuffer *profile, const char **error) {
int ret;
size_t name_len;
UmbBuffer zbuf;
UmbBuffer iccp_buf = buffer_from_chunk(iccp);
if (iccp->data_size < 4)
goto fail;
ret = get_initial_text_len(&name_len, &iccp_buf, 79, error);
if (ret < 0)
goto fail;
zbuf.data = iccp->data + name_len + 1;
zbuf.size = iccp->data_size - name_len - 1;
return inflate_zlib_buffer(&zbuf, profile, error);
fail:
*error = "Error analyzing iCCP chunk data";
return -1;
}
static inline void xyz_to_xy(int32_t xyz[3], int32_t xy[2]) {
int32_t total = xyz[0] + xyz[1] + xyz[2];
xy[0] = (int32_t) ((xyz[0] * 100000.0f) / total);
xy[1] = (int32_t) ((xyz[1] * 100000.0f) / total);
}
static int scan_icc(const UmbBuffer *profile, UmbPngIccScan *scan, const char **error) {
uint8_t *header;
uint32_t tag_count;
if (profile->size < 144) {
*error = "ICC profile too short";
return -1;
}
if (rbe32(profile->data) != profile->size) {
*error = "ICC profile size mismatch";
return -1;
}
tag_count = rbe32(profile->data + 128);
header = profile->data + 132;
for (uint32_t i = 0; i < tag_count; i++, header += 12) {
uint32_t sig, offset, size;
if (header + 12 > profile->data + profile->size) {
*error = "ICC profile tag out of bounds";
return -1;
}
sig = rbe32(header);
offset = rbe32(header + 4);
size = rbe32(header + 8);
if (offset + size > profile->size) {
*error = "ICC profile tag offset out of bounds";
return -1;
}
if (sig == maketag('w','t','p','t')) {
if (size != 20) {
*error = "Illegal `wtpt` tag size";
return -1;
}
sig = rbe32(profile->data + offset);
if (sig != maketag('X','Y','Z',' '))
continue;
scan->wp_xyz[0] = rbe32(profile->data + offset + 8);
scan->wp_xyz[1] = rbe32(profile->data + offset + 12);
scan->wp_xyz[2] = rbe32(profile->data + offset + 16);
} else if (sig == maketag('r','X','Y','Z')) {
if (size != 20) {
*error = "Illegal `rXYZ` tag size";
return -1;
}
sig = rbe32(profile->data + offset);
if (sig != maketag('X','Y','Z',' '))
continue;
scan->red_xyz[0] = rbe32(profile->data + offset + 8);
scan->red_xyz[1] = rbe32(profile->data + offset + 12);
scan->red_xyz[2] = rbe32(profile->data + offset + 16);
} else if (sig == maketag('g','X','Y','Z')) {
if (size != 20) {
*error = "Illegal `gXYZ` tag size";
return -1;
}
sig = rbe32(profile->data + offset);
if (sig != maketag('X','Y','Z',' '))
continue;
scan->green_xyz[0] = rbe32(profile->data + offset + 8);
scan->green_xyz[1] = rbe32(profile->data + offset + 12);
scan->green_xyz[2] = rbe32(profile->data + offset + 16);
} else if (sig == maketag('b','X','Y','Z')) {
if (size != 20) {
*error = "Illegal `bXYZ` tag size";
return -1;
}
sig = rbe32(profile->data + offset);
if (sig != maketag('X','Y','Z',' '))
continue;
scan->blue_xyz[0] = rbe32(profile->data + offset + 8);
scan->blue_xyz[1] = rbe32(profile->data + offset + 12);
scan->blue_xyz[2] = rbe32(profile->data + offset + 16);
} else if (sig == maketag('r','T','R','C') || sig == maketag('g','T','R','C') ||
sig == maketag('b','T','R','C')) {
if (size < 12) {
*error = "Illegal `?TRC` tag size";
return -1;
}
sig = rbe32(profile->data + offset);
if (sig != maketag('p','a','r','a'))
continue;
sig = rbe32(profile->data + offset + 8);
if (sig != 0x30000 && sig != 0x40000)
continue;
if (size != 8 + (sig >> 13))
continue;
scan->para_curv[0] = rbe32(profile->data + offset + 12);
scan->para_curv[1] = rbe32(profile->data + offset + 16);
scan->para_curv[2] = rbe32(profile->data + offset + 20);
scan->para_curv[3] = rbe32(profile->data + offset + 24);
scan->para_curv[4] = rbe32(profile->data + offset + 28);
if (sig == 0x40000) {
scan->para_curv[5] = rbe32(profile->data + offset + 32);
scan->para_curv[6] = rbe32(profile->data + offset + 36);
} else {
scan->para_curv[5] = 0;
scan->para_curv[6] = 0;
}
}
}
return 0;
}
static const UmbPngIccScan srgb_icc_profile = {
.wp_xyz = {63190, 65536, 54061},
.red_xyz = {28564, 14574, 912},
.green_xyz = {25253, 46992, 6336},
.blue_xyz = {9373, 3971, 46782},
.para_curv = {157286, 62119, 3416, 5072, 2651, 0, 0},
};
static int matches_srgb(const UmbPngIccScan *scan) {
for (int i = 0; i < array_size(srgb_icc_profile.para_curv); i++) {
if (!within(srgb_icc_profile.para_curv[i], scan->para_curv[i], 32))
return 0;
}
for (int i = 0; i < 3; i++) {
if (!within(srgb_icc_profile.wp_xyz[i], scan->wp_xyz[i], 32))
return 0;
if (!within(srgb_icc_profile.red_xyz[i], scan->red_xyz[i], 32))
return 0;
if (!within(srgb_icc_profile.green_xyz[i], scan->green_xyz[i], 32))
return 0;
if (!within(srgb_icc_profile.blue_xyz[i], scan->blue_xyz[i], 32))
return 0;
}
return 1;
}
/**
* Allocates a UTF-8 buffer from the given Latin-1 buffer.
*
* Latin-1 is an extension of ASCII that uses one-byte 0-255 to represent
* Unicode code points between 0 and 255. UTF-8 is a variable-length extension
* of ASCIIthat uses one byte to represent code points 0-127, and two bytes to
* represent code points 128-255 (plus others, not relevant here), by splitting
* the bits into 110xxxxx -> 10xxxxxx.
*
* Because code points 128-255 all require 8 bits, this is effectively just
* 110000xx -> 10xxxxxx.
*
* The latin-1 buffer here does not need to be NUL-terminated. This function always
* NUL-terminates the UTF-8 buffer that it allocates and returns.
*
* utf8->data needs to be freed elsewhere via free() or equivalent.
*
* @return This function returns 0 on success and negative on failure.
*/
static int get_utf8_from_latin1(UmbBuffer *utf8, const UmbBuffer *latin1) {
const uint8_t *in = latin1->data;
const uint8_t *const end = latin1->data + latin1->size;
uint8_t *out;
void *temp;
temp = realloc(utf8->data, 2 * latin1->size + 1);
if (!temp)
return NEGERROR(ENOMEM);
utf8->data = temp;
out = utf8->data;
while (in < end) {
if (*in < 0x80)
*out++ = *in++;
else {
*out++ = 0xc2 | ((*in & 0x40) >> 6);
*out++ = (*in++ & 0x3f) | 0x80;
}
}
*out = 0;
return 0;
}
static int parse_text(const UmbPngChunk *text, const UmbPngOptions *options, const char **error) {
int ret = 0;
size_t init_len;
UmbBuffer utf8 = { 0 };
UmbBuffer latin1;
UmbBuffer text_buf = buffer_from_chunk(text);
ret = get_initial_text_len(&init_len, &text_buf, 79, error);
if (ret < 0)
goto end;
fprintf(stderr, "tEXt key: %s\n", text->data);
if (options->verbose < 2)
goto end;
latin1.size = text->data_size - init_len;
latin1.data = text->data + init_len;
ret = get_utf8_from_latin1(&utf8, &latin1);
if (ret < 0) {
*error = "Error converting Latin-1 tEXt to UTF-8";
goto end;
}
fprintf(stderr, "tEXt value: %s\n", utf8.data);
end:
freep(utf8.data);
return ret;
}
static int parse_ztxt(const UmbPngChunk *ztxt, const UmbPngOptions *options, const char **error) {
int ret = 0;
size_t init_len;
UmbBuffer zbuf;
UmbBuffer latin1 = { 0 };
UmbBuffer utf8 = { 0 };
UmbBuffer ztxt_buf = buffer_from_chunk(ztxt);
ret = get_initial_text_len(&init_len, &ztxt_buf, 79, error);
if (ret < 0)
goto end;
fprintf(stderr, "zTXt key: %s\n", ztxt->data);
if (ztxt->data[init_len]) {
fprintf(stderr, "Warning: Unknown zTXt compression method: %d\n", ztxt->data[init_len]);
goto end;
}
if (options->verbose < 2)
goto end;
zbuf.data = ztxt->data + init_len + 1;
zbuf.size = ztxt->data_size - init_len - 1;
ret = inflate_zlib_buffer(&zbuf, &latin1, error);
if (ret < 0)
goto end;
ret = get_utf8_from_latin1(&utf8, &latin1);
if (ret < 0)
goto end;
fprintf(stderr, "zTXt value: %s\n", utf8.data);
end:
freep(utf8.data);
freep(latin1.data);
return ret;
}
static int parse_itxt(const UmbPngChunk *itxt, const UmbPngOptions *options, const char **error) {
int ret = 0;
size_t init_len;
UmbBuffer curr_buff = buffer_from_chunk(itxt);
UmbBuffer inflated = { 0 };
int compressed, method;
ret = get_initial_text_len(&init_len, &curr_buff, 79, error);
if (ret < 0)
goto end;
fprintf(stderr, "iTXt key: %s\n", curr_buff.data);
if (options->verbose < 1)
goto end;
if (curr_buff.size < init_len + 2) {
*error = "iTXt chunk too small";
ret = -1;
goto end;
}
compressed = curr_buff.data[init_len];
method = curr_buff.data[init_len + 1];
curr_buff.data += init_len + 2;
curr_buff.size -= init_len + 2;
if (compressed && method) {
*error = "Invalid iTXt compression method";
ret = -1;
goto end;
}
fprintf(stderr, "iTXt compression: %s\n", compressed ? "compressed" : "uncompressed");
if (curr_buff.size < 1) {
*error = "iTXt chunk too small";
ret = -1;
goto end;
}
ret = get_initial_text_len(&init_len, &curr_buff, curr_buff.size, error);
if (ret < 0)
goto end;
if (init_len <= 1)
fprintf(stderr, "iTXt lang: Unspecified\n");
else
fprintf(stderr, "iTXt lang: %s\n", curr_buff.data);
curr_buff.data += init_len;
curr_buff.size -= init_len;
if (curr_buff.size < 1) {
*error = "iTXt chunk too small";
ret = -1;
goto end;
}
ret = get_initial_text_len(&init_len, &curr_buff, curr_buff.size, error);
if (ret < 0)
goto end;
fprintf(stderr, "iTXt translated key: %s\n", curr_buff.data);
if (options->verbose < 2)
goto end;
curr_buff.data += init_len;
curr_buff.size -= init_len;
if (!curr_buff.size)
goto end;
if (compressed) {
ret = inflate_zlib_buffer(&curr_buff, &inflated, error);
if (ret < 0)
goto end;
if (!inflated.size)
goto end;
}
fprintf(stderr, "iTXt value: ");
fwrite(compressed ? inflated.data : curr_buff.data, compressed ? inflated.size : curr_buff.size, 1, stderr);
fprintf(stderr, "\n");
fflush(stderr);
end:
freep(inflated.data);
return ret;
}
static int parse_ihdr(const UmbPngChunk *ihdr, UmbPngScanData *data, const char **error) {
if (ihdr->data_size != 13) {
*error = "Illegal IHDR chunk size";
return -1;
}
data->width = rbe32(ihdr->data);
data->height = rbe32(ihdr->data + 4);
data->depth = ihdr->data[8];
data->color = ihdr->data[9];
if (ihdr->data[10]) {
*error = "Illegal Compression Method";
return -1;
}
if (ihdr->data[11]) {
*error = "Illegal filter method";
return -1;
}
if (ihdr->data[12] > 1) {
*error = "Illegal interlace method";
return -1;
}
switch (data->color) {
case COLOR_INDEXED:
case COLOR_GRAY:
if (data->depth == 1 || data->depth == 2 || data->depth == 4)
break;
case COLOR_TRUE:
case COLOR_GRAY_A:
case COLOR_RGBA:
if ((data->depth != 8 && data->depth != 16) ||
(data->depth == 16 && data->color == COLOR_INDEXED)) {
*error = "Illegal bit depth";
return -1;
}
break;
default:
*error = "Illegal color type";
return -1;
}
return 0;
}
static int write_idats(FILE *out, const UmbPngChunkChain **initial, const char **error) {
const UmbPngChunkChain *chain = *initial;
const UmbPngChunkChain *final = NULL;
uint64_t total_size = 0;
uint32_t crc = 0x35af061e; // crc32_z(0, "IDAT", 4);
uint8_t tag[4];
size_t count;
for (chain = *initial; chain->chunk.tag == tag_IDAT; chain = chain->next) {
total_size += chain->chunk.data_size;
if (total_size >= INT32_MAX) {
total_size -= chain->chunk.data_size;
final = chain->prev;
break;
}
final = chain;
}
wbe32(tag, total_size);
count = fwrite(tag, 4, 1, out);
if (!count)
goto fail;
count = fwrite("IDAT", 4, 1, out);
if (!count)
goto fail;
for (chain = *initial; chain && chain->prev != final; chain = chain->next) {
size_t tot = 0;
while (tot < chain->chunk.data_size) {
count = fwrite(chain->chunk.data + tot, 1, chain->chunk.data_size - tot, out);
if (!count)
goto fail;
crc = crc32_z(crc, chain->chunk.data + tot, count);
tot += count;
}
}
wbe32(tag, crc);
count = fwrite(tag, 4, 1, out);
if (!count)
goto fail;
*initial = final->next;
return 0;
fail:
perror(*error);
*error = "Error writing chunk data";
return -1;
}
/** frees everything except the base node */
static void free_chain(UmbPngChunkChain *file) {
UmbPngChunkChain *prev = file;
if (!file)
return;
do {
prev = file;
file = file->next;
} while (file);
file = prev;
while (file) {
freep(file->chunk.data);
file = file->prev;
if (file)
freep(file->next);
}