CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hrydgard

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: hrydgard/ppsspp
Path: blob/master/ext/libpng17/pngrtran.c
Views: 1401
1
#ifdef _MSC_VER
2
#pragma warning (disable:4146)
3
#endif
4
5
/* pngrtran.c - transforms the data in a row for PNG readers
6
*
7
* Last changed in libpng 1.7.0 [(PENDING RELEASE)]
8
* Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
9
* (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
10
* (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
11
*
12
* This code is released under the libpng license.
13
* For conditions of distribution and use, see the disclaimer
14
* and license in png.h
15
*
16
* This file contains functions optionally called by an application
17
* in order to tell libpng how to handle data when reading a PNG.
18
* Transformations that are used in both reading and writing are
19
* in pngtrans.c.
20
*/
21
22
#include "pngpriv.h"
23
#define PNG_SRC_FILE PNG_SRC_FILE_pngrtran
24
25
#ifdef PNG_READ_QUANTIZE_SUPPORTED
26
typedef struct
27
{
28
png_transform tr;
29
png_byte map[256U]; /* Map of palette values */
30
png_byte lut[1U << /* LUT for RGB values */
31
(PNG_QUANTIZE_RED_BITS+PNG_QUANTIZE_GREEN_BITS+PNG_QUANTIZE_BLUE_BITS)];
32
} png_transform_quantize;
33
34
#define PNG_QUANTIZE_MAP 1U /* map is present and not a 1:1 mapping */
35
#define PNG_QUANTIZE_LUT 2U /* lut has been built */
36
37
static void
38
do_quantize_rgb(png_transformp *transform, png_transform_controlp tc)
39
{
40
# define png_ptr (tc->png_ptr)
41
png_transform_quantize *tr = png_transform_cast(png_transform_quantize,
42
*transform);
43
unsigned int channels = PNG_TC_CHANNELS(*tc);
44
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
45
png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - channels/*safety*/;
46
png_bytep dp = png_voidcast(png_bytep, tc->dp);
47
48
affirm(tc->bit_depth == 8 && (channels == 3 || channels == 4) &&
49
!(tc->format & PNG_FORMAT_FLAG_SWAPPED) &&
50
(tr->tr.args & PNG_QUANTIZE_LUT) != 0);
51
52
tc->sp = dp;
53
tc->format |= PNG_FORMAT_FLAG_COLORMAP;
54
55
while (sp <= ep)
56
{
57
unsigned int r = sp[0];
58
unsigned int g = sp[1];
59
unsigned int b = sp[2];
60
61
/* This looks real messy, but the compiler will reduce
62
* it down to a reasonable formula. For example, with
63
* 5 bits per color, we get:
64
* p = (((r >> 3) & 0x1f) << 10) |
65
* (((g >> 3) & 0x1f) << 5) |
66
* ((b >> 3) & 0x1f);
67
*/
68
*dp++ = tr->lut[(((r >> (8 - PNG_QUANTIZE_RED_BITS)) &
69
((1 << PNG_QUANTIZE_RED_BITS) - 1)) <<
70
(PNG_QUANTIZE_GREEN_BITS + PNG_QUANTIZE_BLUE_BITS)) |
71
(((g >> (8 - PNG_QUANTIZE_GREEN_BITS)) &
72
((1 << PNG_QUANTIZE_GREEN_BITS) - 1)) <<
73
(PNG_QUANTIZE_BLUE_BITS)) |
74
((b >> (8 - PNG_QUANTIZE_BLUE_BITS)) &
75
((1 << PNG_QUANTIZE_BLUE_BITS) - 1))];
76
77
sp += channels;
78
}
79
80
affirm(sp == ep+channels);
81
UNTESTED
82
# undef png_ptr
83
}
84
85
static void
86
do_quantize_pal(png_transformp *transform, png_transform_controlp tc)
87
{
88
# define png_ptr (tc->png_ptr)
89
png_transform_quantize *tr = png_transform_cast(png_transform_quantize,
90
*transform);
91
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
92
png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc);
93
png_bytep dp = png_voidcast(png_bytep, tc->dp);
94
95
affirm(tc->bit_depth == 8 && (tc->format & PNG_FORMAT_FLAG_COLORMAP) != 0 &&
96
!(tc->format & PNG_FORMAT_FLAG_SWAPPED) &&
97
(tr->tr.args & PNG_QUANTIZE_MAP) != 0);
98
99
tc->sp = dp;
100
101
while (sp < ep)
102
*dp++ = tr->map[*sp++];
103
104
UNTESTED
105
# undef png_ptr
106
}
107
108
static void
109
png_init_quantize(png_transformp *transform, png_transform_controlp tc)
110
{
111
if (tc->bit_depth == 8 && (tc->format & PNG_FORMAT_FLAG_COLOR) != 0)
112
{
113
/* Either colormapped input, RGB or RGBA: */
114
if (!(tc->format & PNG_FORMAT_FLAG_COLORMAP)) /* RGB, RGBA */
115
{
116
/* This must be a 'palette' lookup */
117
if (((*transform)->args & PNG_QUANTIZE_LUT) != 0)
118
{
119
/* This changes the format and invalidates pretty much everything in
120
* the info struct:
121
*/
122
tc->format |= PNG_FORMAT_FLAG_COLORMAP;
123
124
if (tc->init == PNG_TC_INIT_FINAL)
125
{
126
(*transform)->fn = do_quantize_rgb;
127
tc->invalid_info |= PNG_INFO_tRNS+PNG_INFO_hIST+PNG_INFO_pCAL+
128
PNG_INFO_sBIT+PNG_INFO_bKGD;
129
tc->sBIT_R = tc->sBIT_G = tc->sBIT_B = tc->sBIT_A =
130
png_check_byte(tc->png_ptr, tc->bit_depth);
131
}
132
133
return;
134
}
135
}
136
137
else /* colormapped */
138
{
139
/* This must be a 'quantize' lookup */
140
if (((*transform)->args & PNG_QUANTIZE_MAP) != 0)
141
{
142
/* This doesn't change the format, just the values: */
143
if (tc->init == PNG_TC_INIT_FINAL)
144
{
145
(*transform)->fn = do_quantize_pal;
146
tc->invalid_info |= PNG_INFO_sBIT+PNG_INFO_pCAL;
147
tc->sBIT_R = tc->sBIT_G = tc->sBIT_B = tc->sBIT_A =
148
png_check_byte(tc->png_ptr, tc->bit_depth);
149
}
150
151
return;
152
}
153
}
154
}
155
156
/* Else not applicable */
157
(*transform)->fn = NULL;
158
}
159
160
/* Dither file to 8-bit. Supply a palette, the current number
161
* of elements in the palette, the maximum number of elements
162
* allowed, and a histogram if possible. If the current number
163
* of colors is greater then the maximum number, the palette will be
164
* modified to fit in the maximum number. "full_quantize" indicates
165
* whether we need a quantizing cube set up for RGB images, or if we
166
* simply are reducing the number of colors in a paletted image.
167
*/
168
typedef struct png_dsort_struct
169
{
170
struct png_dsort_struct * next;
171
png_byte left;
172
png_byte right;
173
} png_dsort;
174
typedef png_dsort * png_dsortp;
175
typedef png_dsort * * png_dsortpp;
176
177
static void
178
init_map(png_bytep map)
179
/* Initialize a mapping table to be 1:1 */
180
{
181
png_byte b = 0U;
182
183
do
184
map[b] = b;
185
while (b++ != 255U);
186
}
187
188
/* Save typing and make code easier to understand */
189
#define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
190
abs((int)((c1).green) - (int)((c2).green)) + \
191
abs((int)((c1).blue) - (int)((c2).blue)))
192
193
void PNGAPI
194
png_set_quantize(png_structrp png_ptr, png_colorp palette,
195
int num_palette, int maximum_colors, png_const_uint_16p histogram,
196
int full_quantize)
197
{
198
png_debug(1, "in png_set_quantize");
199
200
if (png_ptr != NULL)
201
{
202
png_transform_quantize *tr = png_transform_cast(png_transform_quantize,
203
png_add_transform(png_ptr, sizeof (png_transform_quantize),
204
png_init_quantize, PNG_TR_QUANTIZE));
205
206
/* This is weird (consider what happens to png_set_background on a palette
207
* image with a tRNS chunk).
208
*/
209
if (palette == png_ptr->palette)
210
png_app_warning(png_ptr, "png_set_quantize: PLTE will be damaged");
211
212
if (maximum_colors <= 0 || num_palette > 256)
213
{
214
/* The spuriously allocated transform will be removed by the init
215
* code.
216
*/
217
png_app_error(png_ptr, "png_set_quantize: invalid color count");
218
return;
219
}
220
221
/* The app passed in a palette with too many colors, it's not clear why
222
* libpng is providing this functionality, it's nothing to do with PNG and
223
* can be done by the application without any PNG specific knowledge.
224
*/
225
if (num_palette > maximum_colors)
226
{
227
int map_changed = 0;
228
229
/* The map table must be preset to do no mapping initially: */
230
init_map(tr->map);
231
232
if (histogram != NULL)
233
{
234
/* This is easy enough, just throw out the least used colors.
235
* Perhaps not the best solution, but good enough.
236
*/
237
int i;
238
png_byte quantize_sort[256U];
239
240
/* Initialize an array to sort colors */
241
init_map(quantize_sort);
242
243
/* Find the least used palette entries by starting a
244
* bubble sort, and running it until we have sorted
245
* out enough colors. Note that we don't care about
246
* sorting all the colors, just finding which are
247
* least used.
248
*/
249
for (i = num_palette - 1; i >= maximum_colors; i--)
250
{
251
int done; /* To stop early if the list is pre-sorted */
252
int j;
253
254
done = 1;
255
for (j = 0; j < i; j++)
256
{
257
if (histogram[quantize_sort[j]] <
258
histogram[quantize_sort[j+1]])
259
{
260
png_byte t = quantize_sort[j];
261
quantize_sort[j] = quantize_sort[j+1];
262
quantize_sort[j+1] = t;
263
done = 0;
264
}
265
}
266
267
if (done != 0)
268
break;
269
}
270
271
/* Swap the palette around, and set up a table, if necessary */
272
if (full_quantize)
273
{
274
int j = num_palette;
275
276
/* Put all the useful colors within the max, but don't
277
* move the others.
278
*
279
* NOTE: if the app passes in the result of png_get_PLTE it will
280
* be overwritten at this point, what is the API?
281
*/
282
for (i = 0; i < maximum_colors; i++)
283
{
284
if (quantize_sort[i] >= maximum_colors)
285
{
286
do
287
j--;
288
while (quantize_sort[j] >= maximum_colors);
289
290
/* NOTE: NOT swapped, so the original palette[i] has been
291
* lost.
292
*/
293
palette[i] = palette[j];
294
}
295
}
296
}
297
298
else /* !full_quantize */
299
{
300
int j = num_palette;
301
302
/* Move all the used colors inside the max limit, and
303
* develop a translation table.
304
*/
305
for (i = 0; i < maximum_colors; i++)
306
{
307
/* Only move the colors we need to */
308
if (quantize_sort[i] >= maximum_colors)
309
{
310
png_color tmp_color;
311
312
do
313
j--;
314
while (quantize_sort[j] >= maximum_colors);
315
316
tmp_color = palette[j];
317
palette[j] = palette[i];
318
palette[i] = tmp_color;
319
/* Indicate where the color went */
320
tr->map[j] = png_check_byte(png_ptr, i);
321
tr->map[i] = png_check_byte(png_ptr, j);
322
map_changed = 1;
323
}
324
}
325
326
/* Find closest color for those colors we are not using */
327
for (i = 0; i < num_palette; i++)
328
{
329
if (tr->map[i] >= maximum_colors)
330
{
331
int min_d, k, min_k, d_index;
332
333
/* Find the closest color to one we threw out */
334
d_index = tr->map[i];
335
min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
336
for (k = 1, min_k = 0; k < maximum_colors; k++)
337
{
338
int d;
339
340
d = PNG_COLOR_DIST(palette[d_index], palette[k]);
341
342
if (d < min_d)
343
{
344
min_d = d;
345
min_k = k;
346
}
347
}
348
349
/* Point to closest color */
350
tr->map[i] = png_check_byte(png_ptr, min_k);
351
map_changed = 1;
352
}
353
}
354
} /* !full_quantize */
355
} /* have a histogram */
356
357
else /* no histogram */
358
{
359
/* This is much harder to do simply (and quickly). Perhaps
360
* we need to go through a median cut routine, but those
361
* don't always behave themselves with only a few colors
362
* as input. So we will just find the closest two colors,
363
* and throw out one of them (chosen somewhat randomly).
364
* [We don't understand this at all, so if someone wants to
365
* work on improving it, be our guest - AED, GRP]
366
*/
367
int max_d;
368
int num_new_palette;
369
png_byte index_to_palette[256U];
370
png_byte palette_to_index[256U];
371
png_dsortp hash[769];
372
373
/* Initialize palette index sort arrays */
374
init_map(index_to_palette);
375
init_map(palette_to_index);
376
memset(hash, 0, sizeof hash);
377
num_new_palette = num_palette;
378
379
/* Initial wild guess at how far apart the farthest pixel
380
* pair we will be eliminating will be. Larger
381
* numbers mean more areas will be allocated, Smaller
382
* numbers run the risk of not saving enough data, and
383
* having to do this all over again.
384
*
385
* I have not done extensive checking on this number.
386
*/
387
max_d = 96;
388
389
while (num_new_palette > maximum_colors)
390
{
391
int i;
392
png_dsortp t = NULL;
393
394
for (i = 0; i < num_new_palette - 1; i++)
395
{
396
int j;
397
398
for (j = i + 1; j < num_new_palette; j++)
399
{
400
int d = PNG_COLOR_DIST(palette[i], palette[j]);
401
402
if (d <= max_d)
403
{
404
405
t = png_voidcast(png_dsortp, png_malloc_warn(png_ptr,
406
sizeof (*t)));
407
408
if (t == NULL)
409
break;
410
411
t->next = hash[d];
412
t->left = png_check_byte(png_ptr, i);
413
t->right = png_check_byte(png_ptr, j);
414
hash[d] = t;
415
}
416
}
417
if (t == NULL)
418
break;
419
}
420
421
if (t != NULL) for (i = 0; i <= max_d; i++)
422
{
423
if (hash[i] != NULL)
424
{
425
png_dsortp p;
426
427
for (p = hash[i]; p != NULL; p = p->next)
428
{
429
if (index_to_palette[p->left] < num_new_palette &&
430
index_to_palette[p->right] < num_new_palette)
431
{
432
int j, next_j;
433
434
if (num_new_palette & 0x01)
435
{
436
j = p->left;
437
next_j = p->right;
438
}
439
else
440
{
441
j = p->right;
442
next_j = p->left;
443
}
444
445
num_new_palette--;
446
/* NOTE: overwrites palette */
447
palette[index_to_palette[j]] =
448
palette[num_new_palette];
449
450
if (full_quantize == 0)
451
{
452
int k;
453
454
for (k = 0; k < num_palette; k++)
455
{
456
if (tr->map[k] == index_to_palette[j])
457
{
458
tr->map[k] = index_to_palette[next_j];
459
map_changed = 1;
460
}
461
462
if (tr->map[k] == num_new_palette)
463
{
464
tr->map[k] = index_to_palette[j];
465
map_changed = 1;
466
}
467
}
468
}
469
470
index_to_palette[palette_to_index[num_new_palette]] =
471
index_to_palette[j];
472
473
palette_to_index[index_to_palette[j]] =
474
palette_to_index[num_new_palette];
475
476
index_to_palette[j] =
477
png_check_byte(png_ptr, num_new_palette);
478
479
palette_to_index[num_new_palette] =
480
png_check_byte(png_ptr, j);
481
}
482
483
if (num_new_palette <= maximum_colors)
484
break;
485
}
486
487
if (num_new_palette <= maximum_colors)
488
break;
489
}
490
}
491
492
for (i = 0; i < 769; i++)
493
{
494
if (hash[i] != NULL)
495
{
496
png_dsortp p = hash[i];
497
498
while (p)
499
{
500
t = p->next;
501
png_free(png_ptr, p);
502
p = t;
503
}
504
505
hash[i] = NULL;
506
}
507
}
508
509
max_d += 96;
510
} /* while num_new_colors > maximum_colors */
511
} /* no histogram */
512
513
num_palette = maximum_colors;
514
515
if (map_changed) /* else the map is 1:1 */
516
tr->tr.args |= PNG_QUANTIZE_MAP;
517
} /* num_palette > maximum_colors */
518
519
/* The palette has been reduced to the requested number of colors if it
520
* was over maximum colors before.
521
*/
522
523
/* TODO: what is this? Apparently the png_struct::palette member gets
524
* updated if it didn't originally have a palette, but the update relies
525
* on the app not freeing the passed in palette.
526
*/
527
if (png_ptr->palette == NULL)
528
png_ptr->palette = palette;
529
530
png_ptr->num_palette = png_check_bits(png_ptr, num_palette, 9);
531
532
if (full_quantize)
533
{
534
int i;
535
png_byte distance[1U << (PNG_QUANTIZE_RED_BITS+PNG_QUANTIZE_GREEN_BITS+
536
PNG_QUANTIZE_BLUE_BITS)];
537
538
memset(distance, 0xff, sizeof distance);
539
540
for (i = 0; i < num_palette; i++)
541
{
542
int ir;
543
int r = (palette[i].red >> (8 - PNG_QUANTIZE_RED_BITS));
544
int g = (palette[i].green >> (8 - PNG_QUANTIZE_GREEN_BITS));
545
int b = (palette[i].blue >> (8 - PNG_QUANTIZE_BLUE_BITS));
546
547
for (ir = 0; ir < (1<<PNG_QUANTIZE_RED_BITS); ir++)
548
{
549
/* int dr = abs(ir - r); */
550
int ig;
551
int dr = ((ir > r) ? ir - r : r - ir);
552
int index_r = (ir << (PNG_QUANTIZE_BLUE_BITS +
553
PNG_QUANTIZE_GREEN_BITS));
554
555
for (ig = 0; ig < (1<<PNG_QUANTIZE_GREEN_BITS); ig++)
556
{
557
/* int dg = abs(ig - g); */
558
int ib;
559
int dg = ((ig > g) ? ig - g : g - ig);
560
int dt = dr + dg;
561
int dm = ((dr > dg) ? dr : dg);
562
int index_g = index_r | (ig << PNG_QUANTIZE_BLUE_BITS);
563
564
for (ib = 0; ib < (1<<PNG_QUANTIZE_BLUE_BITS); ib++)
565
{
566
int d_index = index_g | ib;
567
/* int db = abs(ib - b); */
568
int db = ((ib > b) ? ib - b : b - ib);
569
int dmax = ((dm > db) ? dm : db);
570
int d = dmax + dt + db;
571
572
if (d < distance[d_index])
573
{
574
distance[d_index] = png_check_byte(png_ptr, d);
575
tr->lut[d_index] = png_check_byte(png_ptr, i);
576
}
577
} /* for blue */
578
} /* for green */
579
} /* for red */
580
} /* num_palette */
581
} /* full_quantize */
582
} /* png_ptr != NULL */
583
}
584
#endif /* READ_QUANTIZE */
585
586
#ifdef PNG_READ_PACK_SUPPORTED
587
/* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
588
* without changing the actual values. Thus, if you had a row with
589
* a bit depth of 1, you would end up with bytes that only contained
590
* the numbers 0 or 1. If you would rather they contain 0 and 255, use
591
* png_set_expand_gray_1_2_4_to_8 instead.
592
*/
593
static void
594
png_do_read_unpack(png_transformp *transform, png_transform_controlp tc)
595
{
596
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
597
png_const_bytep ep = png_voidcast(png_const_bytep, tc->dp);
598
png_bytep dp = png_voidcast(png_bytep, tc->dp);
599
600
sp += PNG_TC_ROWBYTES(*tc) - 1; /* Start from end */
601
dp += tc->width; /* output bit depth is 8 */
602
603
# define png_ptr (tc->png_ptr)
604
png_debug(1, "in png_do_unpack");
605
606
switch (tc->bit_depth)
607
{
608
case 1:
609
{
610
/* Because we copy from the last pixel down the shift required
611
* at the start is 8-pixels_in_last_byte, which is just:
612
*/
613
unsigned int shift = 7U & -tc->width;
614
615
while (dp > ep)
616
{
617
*--dp = (*sp >> shift) & 1U;
618
shift = 7U & (shift+1U);
619
if (shift == 0U)
620
--sp;
621
}
622
623
debug(shift == 0U);
624
break;
625
}
626
627
case 2:
628
{
629
unsigned int shift = 7U & -(tc->width << 1);
630
631
while (dp > ep)
632
{
633
*--dp = (*sp >> shift) & 3U;
634
shift = 7U & (shift+2U);
635
if (shift == 0U)
636
--sp;
637
}
638
639
debug(shift == 0U);
640
break;
641
}
642
643
case 4:
644
{
645
unsigned int shift = 7U & -(tc->width << 2);
646
647
while (dp > ep)
648
{
649
*--dp = (*sp >> shift) & 15U;
650
shift = 7U & (shift+4U);
651
if (shift == 0U)
652
--sp;
653
}
654
655
debug(shift == 0U);
656
break;
657
}
658
659
default:
660
impossible("bit depth");
661
}
662
663
debug(dp == ep && sp == png_upcast(png_const_bytep, tc->sp)-1U);
664
tc->sp = dp;
665
666
if ((tc->format & PNG_FORMAT_FLAG_COLORMAP) == 0U)
667
{
668
tc->range++;
669
tc->format |= PNG_FORMAT_FLAG_RANGE;
670
}
671
672
tc->bit_depth = 8U;
673
PNG_UNUSED(transform)
674
# undef png_ptr
675
}
676
677
/* Called from the curiously named png_set_packing API in pngtrans.c; the read
678
* and write code is separated because read 'unpacks' (from PNG format) and
679
* write 'packs' (to PNG format.)
680
*/
681
void /* PRIVATE */
682
png_init_read_pack(png_transformp *transform, png_transform_controlp tc)
683
{
684
# define png_ptr tc->png_ptr
685
debug(tc->init);
686
687
if (tc->bit_depth < 8) /* else no packing/unpacking */
688
{
689
/* For indexed images the pack operation does not invalidate the range; in
690
* fact the corresponding shift operation would!
691
*/
692
if ((tc->format & PNG_FORMAT_FLAG_COLORMAP) == 0U)
693
{
694
tc->range++;
695
tc->format |= PNG_FORMAT_FLAG_RANGE;
696
}
697
698
tc->bit_depth = 8U;
699
700
if (tc->init == PNG_TC_INIT_FINAL)
701
(*transform)->fn = png_do_read_unpack/* sic: it unpacks */;
702
}
703
704
else /* the transform is not applicable */
705
(*transform)->fn = NULL;
706
707
# undef png_ptr
708
}
709
#endif /* READ_PACK */
710
711
#if defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
712
# ifdef PNG_READ_tRNS_SUPPORTED
713
static unsigned int
714
fill_transparent_pixel(png_const_structrp png_ptr, png_byte *trans)
715
/* Fill a byte array according to the transparent pixel value and return a
716
* count of the number of bytes. Low bit depth gray values are replicated in
717
* the first byte. Writes from 1 to 6 bytes.
718
*/
719
{
720
/* There must be a tRNS chunk and this must not be a palette image: */
721
debug(png_ptr->num_trans == 1 &&
722
!(png_ptr->color_type & (PNG_COLOR_MASK_ALPHA+PNG_COLOR_MASK_PALETTE)));
723
724
if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* gray */
725
{
726
unsigned int t = png_ptr->trans_color.gray;
727
unsigned int depth = png_ptr->bit_depth;
728
729
if (depth < 16U)
730
{
731
/* ISO PNG 11.3.2.1 "tRNS Transparency": "If the image bit depth is
732
* less than 16, the least significant bits are used and the others are
733
* 0." So mask out the upper bits.
734
*/
735
t &= (1U<<depth)-1U;
736
737
/* And replicate low bit-depth values across the byte: */
738
while (depth < 8U)
739
{
740
t |= t << depth;
741
depth <<= 1;
742
}
743
744
trans[0] = PNG_BYTE(t);
745
return 1U;
746
}
747
748
/* Else a 16 bit value: */
749
trans[0] = PNG_BYTE(t >> 8);
750
trans[1] = PNG_BYTE(t);
751
return 2U;
752
}
753
754
else /* color */ switch (png_ptr->bit_depth)
755
{
756
case 8: /* 8-bit RGB */
757
trans[0] = PNG_BYTE(png_ptr->trans_color.red);
758
trans[1] = PNG_BYTE(png_ptr->trans_color.green);
759
trans[2] = PNG_BYTE(png_ptr->trans_color.blue);
760
return 3U;
761
762
case 16: /* 16-bit RGB */
763
trans[0] = PNG_BYTE(png_ptr->trans_color.red >> 8);
764
trans[1] = PNG_BYTE(png_ptr->trans_color.red);
765
trans[2] = PNG_BYTE(png_ptr->trans_color.green >> 8);
766
trans[3] = PNG_BYTE(png_ptr->trans_color.green);
767
trans[4] = PNG_BYTE(png_ptr->trans_color.blue >> 8);
768
trans[5] = PNG_BYTE(png_ptr->trans_color.blue);
769
return 6U;
770
771
default:
772
NOT_REACHED;
773
return 0U; /* safe */
774
}
775
}
776
# endif /* READ_tRNS */
777
#endif /* READ_EXPAND || READ_BACKGROUND */
778
779
#ifdef PNG_READ_EXPAND_SUPPORTED
780
/* Flags for png_init_expand */
781
#define PNG_EXPAND_PALETTE 1U /* palette images only, includes tRNS */
782
#define PNG_EXPAND_LBD_GRAY 2U /* grayscale low-bit depth only */
783
#define PNG_EXPAND_tRNS 4U /* non-palette images only */
784
785
/* This struct is only required for tRNS matching, but it is convenient to
786
* allocated it anyway even if READ_tRNS is not supported.
787
*/
788
typedef struct
789
{
790
png_transform tr;
791
unsigned int ntrans; /* number of bytes below */
792
png_byte transparent_pixel[6]; /* the transparent pixel value */
793
} png_expand;
794
795
#ifdef PNG_READ_tRNS_SUPPORTED
796
/* Look for colors matching the trans_color in png_ptr, low bit depth gray is
797
* covered below so this only need handle 8 abd 16-bit channels.
798
*/
799
static void
800
png_do_expand_tRNS(png_transformp *transform, png_transform_controlp tc)
801
{
802
# define png_ptr (tc->png_ptr)
803
png_expand *tr = png_transform_cast(png_expand, *transform);
804
png_bytep dp = png_voidcast(png_bytep, tc->dp);
805
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
806
const png_const_bytep ep = sp;
807
const unsigned int spixel_size = PNG_TC_PIXEL_DEPTH(*tc) >> 3;
808
unsigned int alpha_size;
809
810
/* We expect opaque and transparent pixels to be interleaved but with long
811
* sequences of each. Because we are adding an alpha channel we must copy
812
* down.
813
*/
814
debug(!(tc->format & PNG_FORMAT_FLAG_ALPHA));
815
debug(spixel_size == tr->ntrans);
816
sp += PNG_TC_ROWBYTES(*tc);
817
tc->sp = dp;
818
tc->format |= PNG_FORMAT_FLAG_ALPHA;
819
tc->invalid_info |= PNG_INFO_tRNS;
820
tc->transparent_alpha = 1U;
821
alpha_size = (PNG_TC_PIXEL_DEPTH(*tc)>>3) - spixel_size;
822
debug(alpha_size == 1 || alpha_size == 2);
823
dp += PNG_TC_ROWBYTES(*tc);
824
825
do
826
{
827
unsigned int i = spixel_size;
828
png_byte alpha = 0U;
829
830
dp -= alpha_size;
831
alpha = 0U;
832
833
/* Copy and check one source pixel (backwards, to avoid any
834
* overwrite):
835
*/
836
do if ((*--dp = *--sp) != tr->transparent_pixel[--i]) /* pixel != tRNS */
837
alpha = 0xFFU;
838
while (i != 0U);
839
840
/* i == 0 */
841
do
842
dp[spixel_size + i] = alpha;
843
while (++i < alpha_size);
844
} while (sp > ep);
845
846
debug(sp == ep && dp == tc->dp); /* else overwrite */
847
# undef png_ptr
848
}
849
#endif /* READ_tRNS */
850
851
/* Expand grayscale images of less than 8-bit depth to 8 bits.
852
* libpng 1.7.0: this no longer expands everything, it just expands the low bit
853
* depth gray row. It does *NOT* expand the tRNS into an alpha channel unless
854
* it is told to do so.
855
*
856
* API CHANGE: the function now does what it was always meant to do.
857
*
858
* This is like do_unpack except that the packed data is expanded to the full
859
* 8-bit range; scaled up. This is not a good thing to do on an indexed image;
860
* the indices will be invalid.
861
*
862
* The tRNS handling is included here too; speed is not important because the
863
* result will always be cached unless the PNG is very small.
864
*/
865
static void
866
png_do_expand_lbd_gray(png_transformp *transform, png_transform_controlp tc)
867
{
868
# define png_ptr (tc->png_ptr)
869
png_bytep dp = png_voidcast(png_bytep, tc->dp);
870
const png_const_bytep ep = dp;
871
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
872
const unsigned int bit_depth = tc->bit_depth;
873
# ifdef PNG_READ_sBIT_SUPPORTED
874
unsigned int insignificant_bits = 0U;
875
# endif /* READ_sBIT */
876
# ifdef PNG_READ_tRNS_SUPPORTED
877
unsigned int gray = 0xffffU; /* doesn't match anything */
878
unsigned int do_alpha = 0U;
879
# endif /* READ_tRNS */
880
881
sp += PNG_TC_ROWBYTES(*tc); /* last byte +1 */
882
tc->bit_depth = 8U;
883
tc->invalid_info |= PNG_INFO_tRNS;
884
# ifdef PNG_READ_sBIT_SUPPORTED
885
if (bit_depth > 1U /* irrelevant for bit depth 1 */ &&
886
!(tc->invalid_info & PNG_INFO_sBIT) &&
887
tc->sBIT_G > 0U/*SAFETY*/ && tc->sBIT_G < bit_depth)
888
insignificant_bits = bit_depth - tc->sBIT_G;
889
# endif /* READ_sBIT */
890
891
# ifdef PNG_READ_tRNS_SUPPORTED
892
if (((*transform)->args & PNG_EXPAND_tRNS) != 0)
893
{
894
tc->format |= PNG_FORMAT_FLAG_ALPHA;
895
tc->transparent_alpha = 1U;
896
gray = png_ptr->trans_color.gray & ((1U << bit_depth)-1U);
897
do_alpha = 1U;
898
}
899
900
/* This helps avoid cluttering the code up with #ifdefs: */
901
# define check_tRNS if (do_alpha) *--dp = (pixel != gray) * 255U;
902
# else /* !READ_tRNS */
903
# define check_tRNS
904
# endif /* READ_tRNS */
905
906
dp += PNG_TC_ROWBYTES(*tc); /* pre-decremented below */
907
908
switch (bit_depth)
909
{
910
case 1:
911
{
912
unsigned int shift = 7U & -tc->width;
913
unsigned int s = *--sp;
914
915
for(;;)
916
{
917
if (shift == 8U) s = *--sp, shift = 0;
918
919
{
920
const unsigned int pixel = (s >> shift) & 1U;
921
922
check_tRNS
923
*--dp = PNG_BYTE(pixel * 255U);
924
if (dp <= ep) break;
925
}
926
++shift;
927
}
928
929
debug(dp == ep && shift == 7U && sp == tc->sp);
930
break;
931
}
932
933
case 2:
934
{
935
unsigned int shift = 7U & -(tc->width << 1)/*overflow ok*/;
936
unsigned int s = *--sp;
937
938
for (;;)
939
{
940
if (shift == 8U) s = *--sp, shift = 0;
941
{
942
const unsigned int pixel = (s >> shift) & 3U;
943
944
check_tRNS
945
946
# ifdef PNG_READ_sBIT_SUPPORTED
947
/* 'sig_bits' must be 1 or 2 leaving insignificant_bits 0 or
948
* 1. This may look silly but it allows a compact representation
949
* of 1 bit gray + 1 bit alpha (transparency):
950
*/
951
if (insignificant_bits /* only 1 bit significant */)
952
*--dp = PNG_BYTE((pixel >> 1) * 255U);
953
954
else
955
# endif
956
*--dp = PNG_BYTE(pixel * 85U);
957
958
if (dp <= ep) break;
959
}
960
shift += 2U;
961
}
962
963
debug(dp == ep && shift == 6U && sp == tc->sp);
964
break;
965
}
966
967
case 4:
968
{
969
unsigned int shift = 7U & -(tc->width << 2)/*overflow ok*/;
970
unsigned int s = *--sp;
971
# ifdef PNG_READ_sBIT_SUPPORTED
972
const unsigned int div = (1U << (4U-insignificant_bits)) - 1U;
973
# endif
974
975
for (;;)
976
{
977
if (shift == 8U) s = *--sp, shift = 0;
978
{
979
unsigned int pixel = (s >> shift) & 15U;
980
981
check_tRNS
982
983
# ifdef PNG_READ_sBIT_SUPPORTED
984
/* insignificant_bits may be 0, 1, 2 or 3, requiring a multiply
985
* by 17, 255/7, 85 or 255. Since this operation is always
986
* cached we don't much care about the time to do the divide
987
* below.
988
*/
989
if (insignificant_bits)
990
pixel = ((pixel>>insignificant_bits) * 255U + (div>>1)) / div;
991
992
else
993
# endif
994
pixel *= 17U;
995
996
*--dp = PNG_BYTE(pixel);
997
if (dp <= ep) break;
998
}
999
1000
shift += 4U;
1001
}
1002
1003
debug(dp == ep && shift == 4U && sp == tc->sp);
1004
break;
1005
}
1006
1007
default:
1008
impossible("bit depth");
1009
}
1010
1011
tc->sp = ep;
1012
1013
# undef check_tRNS
1014
# undef png_ptr
1015
}
1016
1017
static void
1018
png_init_expand(png_transformp *transform, png_transform_controlp tc)
1019
{
1020
# define png_ptr (tc->png_ptr)
1021
/* The possible combinations are:
1022
*
1023
* 1) PALETTE: the 'palette' flag should be set on the transform control and
1024
* all that need be done is cancel this to cause the cache code to do the
1025
* expansion.
1026
*
1027
* 2) LBP_GRAY, LBP_GRAY+tRNS: use png_do_expand_lbd_gray to do the required
1028
* expand. Can be cached.
1029
*
1030
* 3) tRNS: scan the row for the relevant tRNS value.
1031
*
1032
* Note that expanding 8 to 16 bits is a byte op in pngtrans.c (it just
1033
* replicates bytes).
1034
*/
1035
if (tc->palette)
1036
{
1037
debug(tc->caching && !(tc->format & PNG_FORMAT_FLAG_COLORMAP));
1038
1039
if (((*transform)->args & PNG_EXPAND_PALETTE) != 0U)
1040
{
1041
tc->palette = 0U;
1042
tc->invalid_info |= PNG_INFO_PLTE + PNG_INFO_tRNS;
1043
tc->cost = PNG_CACHE_COST_LIMIT; /* the cache is required! */
1044
}
1045
1046
/* Note that this needs to happen when the row is processed (!tc->init) as
1047
* well.
1048
*/
1049
}
1050
1051
else if (!(tc->format & PNG_FORMAT_FLAG_COLORMAP))
1052
{
1053
png_uint_32 args = (*transform)->args & PNG_BIC_MASK(PNG_EXPAND_PALETTE);
1054
unsigned int bit_depth = tc->bit_depth;
1055
1056
debug(tc->init);
1057
1058
if (bit_depth >= 8U)
1059
args &= PNG_BIC_MASK(PNG_EXPAND_LBD_GRAY);
1060
1061
# ifdef PNG_READ_tRNS_SUPPORTED
1062
if (png_ptr->num_trans == 0U ||
1063
(tc->format & PNG_FORMAT_FLAG_ALPHA) != 0U ||
1064
(tc->invalid_info & PNG_INFO_tRNS) != 0U)
1065
# endif
1066
args &= PNG_BIC_MASK(PNG_EXPAND_tRNS);
1067
1068
(*transform)->args = args;
1069
1070
switch (args)
1071
{
1072
case PNG_EXPAND_LBD_GRAY:
1073
tc->bit_depth = 8U;
1074
tc->invalid_info |= PNG_INFO_tRNS;
1075
1076
if (tc->init == PNG_TC_INIT_FINAL)
1077
(*transform)->fn = png_do_expand_lbd_gray;
1078
break;
1079
1080
# ifdef PNG_READ_tRNS_SUPPORTED
1081
case PNG_EXPAND_LBD_GRAY + PNG_EXPAND_tRNS:
1082
tc->bit_depth = 8U;
1083
tc->format |= PNG_FORMAT_FLAG_ALPHA;
1084
tc->invalid_info |= PNG_INFO_tRNS;
1085
tc->transparent_alpha = 1U;
1086
1087
/* In this case tRNS must be left unmodified for the expansion code
1088
* to handle.
1089
*/
1090
if (tc->init == PNG_TC_INIT_FINAL)
1091
(*transform)->fn = png_do_expand_lbd_gray;
1092
break;
1093
1094
case PNG_EXPAND_tRNS:
1095
if (tc->init == PNG_TC_INIT_FINAL)
1096
{
1097
png_expand *tr = png_transform_cast(png_expand, *transform);
1098
1099
affirm((tc->bit_depth == 8U || tc->bit_depth == 16U) &&
1100
(tc->format &
1101
(PNG_FORMAT_FLAG_COLORMAP|PNG_FORMAT_FLAG_ALPHA)) == 0U);
1102
1103
tr->ntrans = fill_transparent_pixel(png_ptr,
1104
tr->transparent_pixel);
1105
tr->tr.fn = png_do_expand_tRNS;
1106
} /* TC_INIT_FINAL */
1107
1108
tc->format |= PNG_FORMAT_FLAG_ALPHA;
1109
tc->invalid_info |= PNG_INFO_tRNS;
1110
tc->transparent_alpha = 1U;
1111
break;
1112
# endif /* READ_tRNS */
1113
1114
default: /* transform not applicable */
1115
(*transform)->fn = NULL;
1116
break;
1117
}
1118
1119
implies(tc->init == PNG_TC_INIT_FINAL,
1120
(*transform)->fn != png_init_expand);
1121
}
1122
1123
else /* not applicable */
1124
{
1125
debug(tc->init);
1126
(*transform)->fn = NULL;
1127
NOT_REACHED;
1128
}
1129
# undef png_ptr
1130
}
1131
1132
void PNGAPI
1133
png_set_expand_gray_1_2_4_to_8(png_structrp png_ptr)
1134
{
1135
if (png_ptr != NULL)
1136
png_add_transform(png_ptr, sizeof (png_expand), png_init_expand,
1137
PNG_TR_EXPAND)->args |= PNG_EXPAND_LBD_GRAY;
1138
}
1139
1140
/* Expand paletted images to 8-bit RGB or, if there is a tRNS chunk, RGBA.
1141
* Note that this is effectively handled by the read code palette optimizations.
1142
*
1143
* API CHANGE: this used to have the completely unexpected side effect of
1144
* turning on the above two optimizations.
1145
*/
1146
void PNGAPI
1147
png_set_palette_to_rgb(png_structrp png_ptr)
1148
{
1149
if (png_ptr != NULL)
1150
png_add_transform(png_ptr, sizeof (png_expand), png_init_expand,
1151
PNG_TR_EXPAND)->args |= PNG_EXPAND_PALETTE;
1152
}
1153
1154
/* Expand paletted images to RGB, expand grayscale images of less than 8-bit
1155
* depth to 8-bit depth, and expand tRNS chunks to alpha channels. I.e. all the
1156
* above.
1157
*/
1158
void PNGAPI
1159
png_set_expand(png_structrp png_ptr)
1160
{
1161
if (png_ptr != NULL)
1162
{
1163
png_set_palette_to_rgb(png_ptr);
1164
png_set_expand_gray_1_2_4_to_8(png_ptr);
1165
png_set_tRNS_to_alpha(png_ptr);
1166
}
1167
}
1168
#endif /* READ_EXPAND */
1169
1170
#if defined(PNG_READ_EXPAND_SUPPORTED) ||\
1171
defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
1172
1173
#define PNG_INIT_STRIP_ALPHA 1U
1174
#define PNG_INIT_EXPAND_tRNS 2U
1175
static void
1176
png_init_alpha(png_transformp *transform, png_transform_controlp tc)
1177
{
1178
# define png_ptr (tc->png_ptr)
1179
int required = 0;
1180
1181
# if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_tRNS_SUPPORTED)
1182
if ((*transform)->args & PNG_INIT_EXPAND_tRNS)
1183
{
1184
/* Prior to 1.7 the alpha channel was stripped after expanding the tRNS
1185
* chunk, so this effectively cancelled out the expand.
1186
*/
1187
if (png_ptr->num_trans > 0 && !tc->palette &&
1188
!((*transform)->args & PNG_INIT_STRIP_ALPHA))
1189
{
1190
debug((tc->format & PNG_FORMAT_FLAG_COLORMAP) == 0);
1191
1192
required = 1;
1193
tc->expand_tRNS = 1U;
1194
1195
/* This happens as a result of an explicit API call to
1196
* png_set_tRNS_to_alpha, so expand low-bit-depth gray too:
1197
*/
1198
if (tc->init == PNG_TC_INIT_FORMAT)
1199
png_add_transform(png_ptr, sizeof (png_expand), png_init_expand,
1200
PNG_TR_EXPAND)->args |= PNG_EXPAND_tRNS + PNG_EXPAND_LBD_GRAY;
1201
}
1202
1203
else
1204
(*transform)->args &= PNG_BIC_MASK(PNG_INIT_EXPAND_tRNS);
1205
}
1206
# endif /* READ_EXPAND && READ_tRNS */
1207
1208
# ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1209
if ((*transform)->args & PNG_INIT_STRIP_ALPHA)
1210
{
1211
/* When compose is being done tRNS will be expanded regardless of the
1212
* above test. Rather that trying to work out if this will happen the
1213
* code just inserts a strip operation; it will be removed later if it
1214
* is not needed.
1215
*/
1216
required = 1;
1217
tc->strip_alpha = 1U;
1218
1219
if (tc->init == PNG_TC_INIT_FORMAT)
1220
png_add_strip_alpha_byte_ops(png_ptr);
1221
}
1222
# endif /* READ_STRIP_ALPHA */
1223
1224
if (!required)
1225
(*transform)->fn = NULL;
1226
# undef png_ptr
1227
}
1228
#endif /* READ_EXPAND || READ_STRIP_ALPHA */
1229
1230
#ifdef PNG_READ_EXPAND_SUPPORTED
1231
/* Expand tRNS chunks to alpha channels. This only expands the tRNS chunk on
1232
* non-palette formats; call png_set_palette_to_rgb to get the corresponding
1233
* effect for a palette.
1234
*
1235
* Note that this will expand low bit depth gray if there is a tRNS chunk, but
1236
* if not nothing will happen.
1237
*
1238
* API CHANGE: this used to do all the expansions, it was rather pointless
1239
* calling it.
1240
*/
1241
void PNGAPI
1242
png_set_tRNS_to_alpha(png_structrp png_ptr)
1243
{
1244
if (png_ptr != NULL)
1245
png_add_transform(png_ptr, 0/*size*/, png_init_alpha, PNG_TR_INIT_ALPHA)->
1246
args |= PNG_INIT_EXPAND_tRNS;
1247
}
1248
#endif /* READ_EXPAND */
1249
1250
#ifdef PNG_READ_STRIP_ALPHA_SUPPORTED
1251
void PNGAPI
1252
png_set_strip_alpha(png_structrp png_ptr)
1253
{
1254
if (png_ptr != NULL)
1255
png_add_transform(png_ptr, 0/*size*/, png_init_alpha, PNG_TR_INIT_ALPHA)->
1256
args |= PNG_INIT_STRIP_ALPHA;
1257
}
1258
#endif /* READ_STRIP_ALPHA */
1259
1260
#ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED
1261
static void
1262
png_do_chop_16_to_8(png_transformp *transform, png_transform_controlp tc)
1263
/* This is actually a repeat of the byte transform, unnecessary code
1264
* replication.
1265
*
1266
* TODO: remove this
1267
*/
1268
{
1269
# define png_ptr (tc->png_ptr)
1270
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp); /* source */
1271
png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc); /* end+1 */
1272
png_bytep dp = png_voidcast(png_bytep, tc->dp); /* destination */
1273
1274
debug(tc->bit_depth == 16U);
1275
tc->sp = dp;
1276
tc->bit_depth = 8U;
1277
1278
while (sp < ep)
1279
*dp++ = *sp, sp += 2;
1280
1281
debug(sp == ep);
1282
# undef png_ptr
1283
1284
PNG_UNUSED(transform)
1285
}
1286
1287
/* A transform containing some useful scaling values... */
1288
typedef struct
1289
{
1290
png_transform tr;
1291
png_uint_32 shifts; /* 4 4-bit values preceeded by a shibboleth (1) */
1292
png_uint_32 channel_scale[4];
1293
} png_transform_scale_16_to_8;
1294
1295
/* Scale rows of bit depth 16 down to 8 accurately */
1296
static void
1297
png_do_scale_16_to_8(png_transformp *transform, png_transform_controlp tc)
1298
{
1299
# define png_ptr (tc->png_ptr)
1300
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp); /* source */
1301
png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc); /* end+1 */
1302
png_bytep dp = png_voidcast(png_bytep, tc->dp); /* destination */
1303
png_transform_scale_16_to_8 *tr =
1304
png_transform_cast(png_transform_scale_16_to_8, *transform);
1305
png_uint_32p scale = 0;
1306
png_uint_32 shift = 1U; /* set the shibboleth at the start */
1307
1308
debug(tc->bit_depth == 16U);
1309
tc->sp = dp;
1310
tc->bit_depth = 8U;
1311
1312
while (sp < ep)
1313
{
1314
/* The input is an array of 16 bit components, these must be scaled to
1315
* 8 bits each taking into account the sBIT setting. The calculation
1316
* requires that the insignificant bits be stripped from the input value
1317
* via a shift then scaled back to 8 bits:
1318
*
1319
* output = ((input >> shift) * scale + round) >> 24
1320
*
1321
* The shifts are packed into tr->shifts, with the end of the list marked
1322
* by a shibboleth, 1, which is preset above.
1323
*/
1324
png_uint_32 v = png_get_uint_16(sp);
1325
1326
sp += 2;
1327
1328
if (shift == 1U)
1329
{
1330
shift = tr->shifts;
1331
scale = tr->channel_scale;
1332
}
1333
1334
*dp++ = PNG_BYTE(((v >> (shift & 0xFU)) * *scale++ + 0x800000U) >> 24);
1335
shift >>= 4;
1336
}
1337
1338
affirm(sp == ep);
1339
# undef png_ptr
1340
}
1341
1342
static int
1343
add_scale(png_transform_scale_16_to_8 *tr, unsigned int sBIT, unsigned int ch)
1344
{
1345
/* This is the output max (255) scaled by 2^24 divided by the input max'
1346
* (which is variable) and rounded. It gives the exact 8-bit answer for all
1347
* input sBIT depths when used in the calculation:
1348
*
1349
* output = ((input >> shift) * scale + 0x800000U) >> 24
1350
*/
1351
tr->channel_scale[ch] = (0xFF000000U + ((1U<<sBIT)>>1)) / ((1U<<sBIT)-1U);
1352
tr->shifts |= ((16U-sBIT) & 0xFU) << (4U*ch);
1353
1354
/* The result says whether there are 8 or fewer significant bits in the
1355
* input value; if so we can just drop the low byte.
1356
*/
1357
return sBIT <= 8U;
1358
}
1359
1360
static void
1361
png_init_scale_16_to_8(png_transformp *transform, png_transform_controlp tc)
1362
{
1363
if (tc->bit_depth == 16U)
1364
{
1365
# define png_ptr (tc->png_ptr)
1366
tc->bit_depth = 8U;
1367
/* But this invalidates tRNS (a 16-bit tRNS cannot be updated to match
1368
* 8-bit data correctly).
1369
*/
1370
tc->invalid_info |= PNG_INFO_tRNS+PNG_INFO_hIST+PNG_INFO_pCAL;
1371
/* TODO: These need further processing: PNG_INFO_bKGD */
1372
1373
if (tc->init == PNG_TC_INIT_FINAL)
1374
{
1375
png_transform_scale_16_to_8 *tr =
1376
png_transform_cast(png_transform_scale_16_to_8, *transform);
1377
1378
/* Set the scale factors for each channel (up to 4), the factors are
1379
* made so that:
1380
*
1381
* ((channel >> shift) * factor + 0x800000U) >> 24
1382
*
1383
* Gives the required 8-bit value. The 'shift' is stored in a single
1384
* png_uint_32 with a shibboleth at the end.
1385
*/
1386
unsigned int channels = 0U;
1387
int chop_ok = 1;
1388
1389
tr->shifts = 0U;
1390
1391
/* This adds up to four scale factors, the remainder are left as 0
1392
* which is safe and leads to obvious errors in the output images in
1393
* the event of an (internal) error.
1394
*/
1395
if (tc->format & PNG_FORMAT_FLAG_COLOR)
1396
chop_ok &= add_scale(tr, tc->sBIT_R, channels++);
1397
1398
chop_ok &= add_scale(tr, tc->sBIT_G, channels++);
1399
1400
if (tc->format & PNG_FORMAT_FLAG_COLOR)
1401
chop_ok &= add_scale(tr, tc->sBIT_B, channels++);
1402
1403
if (tc->format & PNG_FORMAT_FLAG_ALPHA)
1404
chop_ok &= add_scale(tr, tc->sBIT_A, channels++);
1405
1406
if (chop_ok)
1407
tr->tr.fn = png_do_chop_16_to_8;
1408
1409
else
1410
{
1411
int handled = 1;
1412
1413
/* Add the shibboleth at the end */
1414
tr->shifts |= 1U << (4U*channels);
1415
tr->tr.fn = png_do_scale_16_to_8;
1416
1417
/* sBIT is a little tricky; it has to be processed in the scaling
1418
* operation. The result will have the same number of bits unless
1419
* there were more than 8 before. The sBIT flags in the transform
1420
* control are left unchanged here because the data is still valid,
1421
* unless all the values end up as 8 in which case there is no
1422
* remaining sBIT info.
1423
*
1424
* Note that fields, such as alpha, which are not set for this row
1425
* format will always have max values, so won't reset 'handled':
1426
*/
1427
if (tc->sBIT_R >= 8U) tc->sBIT_R = 8U; else handled = 0;
1428
if (tc->sBIT_G >= 8U) tc->sBIT_G = 8U; else handled = 0;
1429
if (tc->sBIT_B >= 8U) tc->sBIT_B = 8U; else handled = 0;
1430
if (tc->sBIT_A >= 8U) tc->sBIT_A = 8U; else handled = 0;
1431
1432
/* If all the sBIT values were >= 8U all the bits are now
1433
* significant:
1434
*/
1435
if (handled)
1436
tc->invalid_info |= PNG_INFO_sBIT;
1437
}
1438
}
1439
1440
# undef png_ptr
1441
}
1442
1443
else /* not applicable */
1444
(*transform)->fn = NULL;
1445
}
1446
1447
void PNGAPI
1448
png_set_scale_16(png_structrp png_ptr)
1449
{
1450
if (png_ptr != NULL)
1451
png_add_transform(png_ptr, sizeof (png_transform_scale_16_to_8),
1452
png_init_scale_16_to_8, PNG_TR_SCALE_16_TO_8);
1453
}
1454
#endif /* READ_SCALE_16_TO_8 */
1455
1456
#ifdef PNG_READ_GAMMA_SUPPORTED
1457
/* Code that depends on READ_GAMMA support; RGB to gray convertion and
1458
* background composition (including the various alpha-mode handling
1459
* operations which produce pre-multiplied alpha by composing on 0).
1460
*/
1461
/* Calculate a reciprocal, return 0 on div-by-zero or overflow. */
1462
static png_fixed_point
1463
png_reciprocal(png_fixed_point a)
1464
{
1465
#ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
1466
double r = floor(1E10/a+.5);
1467
1468
if (r <= 2147483647. && r >= -2147483648.)
1469
return (png_fixed_point)r;
1470
#else
1471
png_fixed_point res;
1472
1473
if (png_muldiv(&res, PNG_FP_1, PNG_FP_1, a) != 0)
1474
return res;
1475
#endif
1476
1477
return 0; /* error/overflow */
1478
}
1479
1480
/* This is the shared test on whether a gamma value is 'significant' - whether
1481
* it is worth doing gamma correction. 'significant_bits' is the number of bits
1482
* in the values to be corrected which are significant.
1483
*/
1484
static int
1485
png_gamma_significant(png_const_structrp png_ptr, png_fixed_point gamma_val,
1486
unsigned int sbits)
1487
{
1488
#if 0
1489
/* This seems to be wrong. The issue is that when the app asks for a higher
1490
* bit depth output than the input has significant bits it causes gamma
1491
* correction to be skipped (this was the intent) however there's no
1492
* particular guarantee that the app won't go on to do further gamma
1493
* processing - pngstest does this - and this messes up the results
1494
* completely.
1495
*
1496
* TODO: work out how to optimize this correctly.
1497
*/
1498
/* The following table lists the threshold as a difference from PNG_FP_1 at
1499
* which the gamma correction will make a change to at least an 'sbits'
1500
* value. There is no entry for 1 bit values; gamma correction is never
1501
* significant.
1502
*/
1503
static const png_uint_16 gamma_threshold_by_sbit[15][2] =
1504
{
1505
{ 36907, 63092 }, /* 2 bits */
1506
{ 17812, 21518 }, /* 3 bits */
1507
{ 8675, 9496 }, /* 4 bits */
1508
{ 4290, 4484 }, /* 5 bits */
1509
{ 2134, 2181 }, /* 6 bits */
1510
{ 1064, 1075 }, /* 7 bits */
1511
{ 531, 534 }, /* 8 bits */
1512
{ 265, 266 }, /* 9 bits */
1513
{ 132, 132 }, /* 10 bits */
1514
{ 66, 66 }, /* 11 bits */
1515
{ 33, 33 }, /* 12 bits */
1516
{ 16, 16 }, /* 13 bits */
1517
{ 8, 8 }, /* 14 bits */
1518
{ 4, 4 }, /* 15 bits */
1519
{ 2, 2 }, /* 16 bits */
1520
};
1521
1522
/* Handle out of range values in release by doing the gamma correction: */
1523
debug_handled(sbits > 0U && sbits <= 16U);
1524
if (sbits == 0U || sbits > 16U)
1525
return 1;
1526
1527
/* 1 bit input or zero gamma, no correction possible/required: */
1528
if (gamma_val == 0 || sbits < 2U)
1529
return 0;
1530
1531
if (gamma_val < PNG_FP_1 - gamma_threshold_by_sbit[sbits-2U][0U])
1532
return gamma_val < PNG_FP_1 - png_ptr->gamma_threshold;
1533
1534
else if (gamma_val > PNG_FP_1 + gamma_threshold_by_sbit[sbits-2U][1U])
1535
return gamma_val > PNG_FP_1 + png_ptr->gamma_threshold;
1536
#else /* FIXUP */
1537
if (gamma_val < PNG_FP_1)
1538
return gamma_val < PNG_FP_1 - png_ptr->gamma_threshold;
1539
1540
else if (gamma_val > PNG_FP_1)
1541
return gamma_val > PNG_FP_1 + png_ptr->gamma_threshold;
1542
1543
PNG_UNUSED(sbits)
1544
#endif /* FIXUP */
1545
1546
return 0; /* not significant */
1547
}
1548
1549
static int
1550
png_gamma_equal(png_const_structrp png_ptr, png_fixed_point g1,
1551
png_fixed_point g2, png_fixed_point *c, unsigned int sbits)
1552
/* Gamma values are equal, or at least one is unknown; c is the correction
1553
* factor from g1 to g2, i.e. g2/g1.
1554
*/
1555
{
1556
return sbits == 1U || g1 == 0 || g2 == 0 || g1 == g2 ||
1557
(png_muldiv(c, g2, PNG_FP_1, g1) &&
1558
!png_gamma_significant(png_ptr, *c, sbits));
1559
}
1560
1561
#ifdef PNG_SIMPLIFIED_READ_SUPPORTED
1562
int
1563
png_need_gamma_correction(png_const_structrp png_ptr, png_fixed_point gamma,
1564
int sRGB_output)
1565
/* This is a hook for the simplified code; it just decides whether or not the
1566
* given gamma (which defaults to that of the PNG data) is close enough to
1567
* linear or sRGB not to require gamma correction.
1568
*/
1569
{
1570
if (gamma == 0)
1571
gamma = png_ptr->colorspace.gamma;
1572
1573
if (gamma != 0 &&
1574
(png_ptr->colorspace.flags &
1575
(PNG_COLORSPACE_INVALID|PNG_COLORSPACE_HAVE_GAMMA)) ==
1576
PNG_COLORSPACE_HAVE_GAMMA)
1577
{
1578
1579
if (sRGB_output && !png_muldiv(&gamma, gamma, PNG_GAMMA_sRGB, PNG_FP_1))
1580
return 0; /* overflow, so no correction */
1581
1582
return png_gamma_significant(png_ptr, gamma, (png_ptr->color_type &
1583
PNG_COLOR_MASK_PALETTE) ? 8U : png_ptr->bit_depth);
1584
}
1585
1586
return 0; /* no info, no correction */
1587
}
1588
#endif /* SIMPLIFIED_READ */
1589
1590
#ifndef PNG_FLOATING_ARITHMETIC_SUPPORTED
1591
/* Fixed point gamma.
1592
*
1593
* The code to calculate the tables used below can be found in the shell script
1594
* contrib/tools/intgamma.sh
1595
*
1596
* To calculate gamma this code implements fast log() and exp() calls using only
1597
* fixed point arithmetic. This code has sufficient precision for either 8-bit
1598
* or 16-bit sample values.
1599
*
1600
* The tables used here were calculated using simple 'bc' programs, but C double
1601
* precision floating point arithmetic would work fine.
1602
*
1603
* 8-bit log table
1604
* This is a table of -log(value/255)/log(2) for 'value' in the range 128 to
1605
* 255, so it's the base 2 logarithm of a normalized 8-bit floating point
1606
* mantissa. The numbers are 32-bit fractions.
1607
*/
1608
static const png_uint_32
1609
png_8bit_l2[128] =
1610
{
1611
4270715492U, 4222494797U, 4174646467U, 4127164793U, 4080044201U, 4033279239U,
1612
3986864580U, 3940795015U, 3895065449U, 3849670902U, 3804606499U, 3759867474U,
1613
3715449162U, 3671346997U, 3627556511U, 3584073329U, 3540893168U, 3498011834U,
1614
3455425220U, 3413129301U, 3371120137U, 3329393864U, 3287946700U, 3246774933U,
1615
3205874930U, 3165243125U, 3124876025U, 3084770202U, 3044922296U, 3005329011U,
1616
2965987113U, 2926893432U, 2888044853U, 2849438323U, 2811070844U, 2772939474U,
1617
2735041326U, 2697373562U, 2659933400U, 2622718104U, 2585724991U, 2548951424U,
1618
2512394810U, 2476052606U, 2439922311U, 2404001468U, 2368287663U, 2332778523U,
1619
2297471715U, 2262364947U, 2227455964U, 2192742551U, 2158222529U, 2123893754U,
1620
2089754119U, 2055801552U, 2022034013U, 1988449497U, 1955046031U, 1921821672U,
1621
1888774511U, 1855902668U, 1823204291U, 1790677560U, 1758320682U, 1726131893U,
1622
1694109454U, 1662251657U, 1630556815U, 1599023271U, 1567649391U, 1536433567U,
1623
1505374214U, 1474469770U, 1443718700U, 1413119487U, 1382670639U, 1352370686U,
1624
1322218179U, 1292211689U, 1262349810U, 1232631153U, 1203054352U, 1173618059U,
1625
1144320946U, 1115161701U, 1086139034U, 1057251672U, 1028498358U, 999877854U,
1626
971388940U, 943030410U, 914801076U, 886699767U, 858725327U, 830876614U,
1627
803152505U, 775551890U, 748073672U, 720716771U, 693480120U, 666362667U,
1628
639363374U, 612481215U, 585715177U, 559064263U, 532527486U, 506103872U,
1629
479792461U, 453592303U, 427502463U, 401522014U, 375650043U, 349885648U,
1630
324227938U, 298676034U, 273229066U, 247886176U, 222646516U, 197509248U,
1631
172473545U, 147538590U, 122703574U, 97967701U, 73330182U, 48790236U,
1632
24347096U, 0U
1633
1634
#if 0 /* NOT USED */
1635
/* The following are the values for 16-bit tables - these work fine for the
1636
* 8-bit conversions but produce very slightly larger errors in the 16-bit
1637
* log (about 1.2 as opposed to 0.7 absolute error in the final value). To
1638
* use these all the shifts below must be adjusted appropriately.
1639
*/
1640
65166, 64430, 63700, 62976, 62257, 61543, 60835, 60132, 59434, 58741, 58054,
1641
57371, 56693, 56020, 55352, 54689, 54030, 53375, 52726, 52080, 51439, 50803,
1642
50170, 49542, 48918, 48298, 47682, 47070, 46462, 45858, 45257, 44661, 44068,
1643
43479, 42894, 42312, 41733, 41159, 40587, 40020, 39455, 38894, 38336, 37782,
1644
37230, 36682, 36137, 35595, 35057, 34521, 33988, 33459, 32932, 32408, 31887,
1645
31369, 30854, 30341, 29832, 29325, 28820, 28319, 27820, 27324, 26830, 26339,
1646
25850, 25364, 24880, 24399, 23920, 23444, 22970, 22499, 22029, 21562, 21098,
1647
20636, 20175, 19718, 19262, 18808, 18357, 17908, 17461, 17016, 16573, 16132,
1648
15694, 15257, 14822, 14390, 13959, 13530, 13103, 12678, 12255, 11834, 11415,
1649
10997, 10582, 10168, 9756, 9346, 8937, 8531, 8126, 7723, 7321, 6921, 6523,
1650
6127, 5732, 5339, 4947, 4557, 4169, 3782, 3397, 3014, 2632, 2251, 1872, 1495,
1651
1119, 744, 372
1652
#endif
1653
};
1654
1655
#if 0 /* UNUSED */
1656
static png_int_32
1657
png_log8bit(unsigned int x)
1658
{
1659
png_uint_32 lg2 = 0U;
1660
1661
/* Each time 'x' is multiplied by 2, 1 must be subtracted off the final log,
1662
* because the log is actually negate that means adding 1. The final
1663
* returned value thus has the range 0 (for 255 input) to 7.994 (for 1
1664
* input), return -1 for the overflow (log 0) case, - so the result is
1665
* always at most 19 bits.
1666
*/
1667
if ((x &= 0xffU) == 0U) /* 0 input, -inf output */
1668
return -0xfffff;
1669
1670
if ((x & 0xf0U) == 0U)
1671
lg2 = 4U, x <<= 4;
1672
1673
if ((x & 0xc0U) == 0U)
1674
lg2 += 2U, x <<= 2;
1675
1676
if ((x & 0x80U) == 0U)
1677
lg2 += 1U, x <<= 1;
1678
1679
/* result is at most 19 bits, so this cast is safe: */
1680
return (png_int_32)((lg2 << 16) + ((png_8bit_l2[x-128U]+32768U)>>16));
1681
}
1682
#endif /* UNUSED */
1683
1684
/* The above gives exact (to 16 binary places) log2 values for 8-bit images,
1685
* for 16-bit images we use the most significant 8 bits of the 16-bit value to
1686
* get an approximation then multiply the approximation by a correction factor
1687
* determined by the remaining up to 8 bits. This requires an additional step
1688
* in the 16-bit case.
1689
*
1690
* We want log2(value/65535), we have log2(v'/255), where:
1691
*
1692
* value = v' * 256 + v''
1693
* = v' * f
1694
*
1695
* So f is value/v', which is equal to (256+v''/v') since v' is in the range 128
1696
* to 255 and v'' is in the range 0 to 255 f will be in the range 256 to less
1697
* than 258. The final factor also needs to correct for the fact that our 8-bit
1698
* value is scaled by 255, whereas the 16-bit values must be scaled by 65535.
1699
*
1700
* This gives a final formula using a calculated value 'x' which is value/v' and
1701
* scaling by 65536 to match the above table:
1702
*
1703
* log2(x/257) * 65536
1704
*
1705
* Since these numbers are so close to '1' we can use simple linear
1706
* interpolation between the two end values 256/257 (result -368.61) and 258/257
1707
* (result 367.179). The values used below are scaled by a further 64 to give
1708
* 16-bit precision in the interpolation:
1709
*
1710
* Start (256): -23591
1711
* Zero (257): 0
1712
* End (258): 23499
1713
*
1714
* In libpng 1.7.0 this is further generalized to return -log2(value/maxval) for
1715
* any maxval up to 65535. This is done by evaluating -log2(value/65535) first
1716
* then adjusting for the required maxval:
1717
*
1718
* ( value) (value 65535) (value) ( 65535)
1719
* -log2(------) = -log2(----- x ------) = -log2(-----)-log2(------)
1720
* (maxval) (65535 maxval) (65535) (maxval)
1721
*
1722
* The extra argument, 'factor', is (2^(16+12))*log2(65535/maxval) (a positive
1723
* value less than 2^32) and this is *subtracted* from the intermediate
1724
* calculation below.
1725
*/
1726
static png_int_32
1727
png_log(unsigned int x, png_uint_32 factor)
1728
/* x: a value of up to 16 bits,
1729
* factor: a 4.28 number which is subtracted from the log below
1730
*/
1731
{
1732
png_uint_32 lg2 = 0U;
1733
1734
/* As above, but now the input has 16 bits. */
1735
if ((x &= 0xffffU) == 0U)
1736
return -0xfffff;
1737
1738
if ((x & 0xff00U) == 0U)
1739
lg2 = 8U, x <<= 8;
1740
1741
if ((x & 0xf000U) == 0U)
1742
lg2 += 4U, x <<= 4;
1743
1744
if ((x & 0xc000U) == 0U)
1745
lg2 += 2U, x <<= 2;
1746
1747
if ((x & 0x8000U) == 0U)
1748
lg2 += 1U, x <<= 1;
1749
1750
/* Calculate the base logarithm from the top 8 bits as a 28-bit fractional
1751
* value.
1752
*/
1753
lg2 <<= 28;
1754
lg2 += (png_8bit_l2[(x>>8)-128U]+8U) >> 4;
1755
1756
/* Now we need to interpolate the factor, this requires a division by the top
1757
* 8 bits. Do this with maximum precision.
1758
*/
1759
{
1760
png_uint_32 i = x;
1761
1762
i = ((i << 16) + (i >> 9)) / (x>> 8);
1763
1764
/* Since we divided by the top 8 bits of 'x' there will be a '1' at 1<<24,
1765
* the value at 1<<16 (ignoring this) will be 0 or 1; this gives us
1766
* exactly 16 bits to interpolate to get the low bits of the result.
1767
* Round the answer. Note that the end point values are scaled by 64 to
1768
* retain overall precision and that 'lg2' is current scaled by an extra
1769
* 12 bits, so adjust the overall scaling by 6-12. Round at every step.
1770
*/
1771
i -= 1U << 24;
1772
1773
if (i <= 65536U) /* <= '257' */
1774
lg2 += ((23591U * (65536U-i)) + (1U << (16+6-12-1))) >> (16+6-12);
1775
1776
else
1777
lg2 -= ((23499U * (i-65536U)) + (1U << (16+6-12-1))) >> (16+6-12);
1778
}
1779
1780
if (lg2 >= factor)
1781
return (png_int_32)/*SAFE*/((lg2 - factor + 2048U) >> 12);
1782
1783
else /* the result will be greater than 1.0, so negative: */
1784
return -(png_int_32)/*SAFE*/((factor - lg2 + 2048U) >> 12);
1785
}
1786
1787
#if 0 /* UNUSED */
1788
static png_int_32
1789
png_log16bit(unsigned int x)
1790
{
1791
return png_log(x, 0U);
1792
}
1793
#endif /* UNUSED */
1794
1795
/* libpng 1.7.0: generalization of png_log{8,16}bit to accept an n-bit input
1796
* value. We want to maintain 1% accuracy in linear light space. This
1797
* corresponds to, approximately, (1*g)% in a gamma encoded space where the
1798
* gamma encoding is 'g' (in the PNG sense, e.g. 0.45455 for sRGB). Apparently
1799
* this requires unbounded accuracy as the gamma encoding value goes down and
1800
* this is a problem for modern HDR data because it may require a high gamma to
1801
* accurately encode image data over a wide dynamic range; the dynamic range of
1802
* 16-bit linear data is only 655:1 if 1% accuracy is needed!
1803
*
1804
* However 16-bit gamma encoded data is still limited because PNG can only
1805
* express gamma encoding. (A log-to-base-1.01 encoding is unlimited; a 12-bit
1806
* value, with 4094 steps, has a dynamic range of more than 1:10^17, which
1807
* exceeds the human eye's range of 1:10^14.)
1808
*
1809
* Notice that sRGB uses a 1/2.4 encoding and CIELab uses a 1/3 encoding. It is
1810
* obvious that, if we assume a maximum D difference in the luminance of
1811
* adjacent pixel values the dynamic range is given by the lowest pixel value
1812
* which is D or less greater than its predecessor, so:
1813
*
1814
* ( P ) (1)
1815
* (---)^(-) = D
1816
* (P-1) (g)
1817
*
1818
* and the maximum dynamic range that can be achieved using M+1 separate values,
1819
* where M+1 is 2^N-1 for an N bit value, reserving the first value for 0, is:
1820
*
1821
* (M) (1)
1822
* range(R) = (-)^(-)
1823
* (P) (g)
1824
*
1825
* So we can eliminate 'P' from the two equations:
1826
*
1827
* P = (P-1) x (D^g)
1828
*
1829
* D^g
1830
* P = -----
1831
* D^g-1
1832
*
1833
* (M x (D^g-1)) (1)
1834
* R = (-----------)^(-)
1835
* ( D^g ) (g)
1836
*
1837
* (M x (D^g-1)) ^ (1/g)
1838
* = ---------------------
1839
* D
1840
*
1841
* Which is a function in two variables (R and g) for a given D (maximum delta
1842
* between two adjacent pixel values) and M (number of pixel values, controlled
1843
* by the channel bit depth).
1844
*
1845
* See contrib/tools/dynamic-range.c for code exploring this function. This
1846
* program will output the optimal gamma for a given number of bits and
1847
* precision.
1848
*
1849
* The range of sensitivity of human vision is roughly as follows (this comes
1850
* from the wikipedia article on scotopic vision):
1851
*
1852
* scotopic: 10^-6 to 10^-3.5 cd/m^2
1853
* mesopic: 10^-3 to 10^0.5 cd/m^2
1854
* photopic: 10 to 10^8 cd/m^2
1855
*
1856
* Giving a total range of about 1:10^14. The maximum precision at which this
1857
* range can be achieved using 16-bit channels is about .15% using a gamma of
1858
* 36, higher ranges are possible using higher gammas but precision is reduced.
1859
* The range with 1% precision and 16-bit channels is 1:10^104, using a gamma of
1860
* 240.
1861
*
1862
* In general the optimal gamma for n-bit channels (where 'n' is at least 7 and
1863
* precision is .01 or less) is:
1864
*
1865
* 2^n * precision
1866
* gamma = ---------------
1867
* 2.736
1868
*
1869
* Or: (24000 * precision) for 16-bit data.
1870
*
1871
* The net effect is that we can't rely on the encoding gamma being limited to
1872
* values around 1/2.5!
1873
*/
1874
static png_int_32
1875
png_log_nbit(unsigned int x, unsigned int nbits)
1876
{
1877
static const png_uint_32 factors[16] =
1878
{
1879
4294961387U, /* 1 bit */
1880
3869501255U, /* 2 bit */
1881
3541367788U, /* 3 bit */
1882
3246213428U, /* 4 bit */
1883
2965079441U, /* 5 bit */
1884
2690447525U, /* 6 bit */
1885
2418950626U, /* 7 bit */
1886
2148993476U, /* 8 bit */
1887
1879799410U, /* 9 bit */
1888
1610985205U, /* 10 bit */
1889
1342360514U, /* 11 bit */
1890
1073830475U, /* 12 bit */
1891
805347736U, /* 13 bit */
1892
536888641U, /* 14 bit */
1893
268441365U, /* 15 bit */
1894
0U /* 16 bit */
1895
};
1896
1897
return png_log(x, factors[nbits-1]);
1898
}
1899
1900
1901
/* The 'exp()' case must invert the above, taking a 20-bit fixed point
1902
* logarithmic value and returning a 16 or 8-bit number as appropriate. In
1903
* each case only the low 16 bits are relevant - the fraction - since the
1904
* integer bits (the top 4) simply determine a shift.
1905
*
1906
* The worst case is the 16-bit distinction between 65535 and 65534. This
1907
* requires perhaps spurious accuracy in the decoding of the logarithm to
1908
* distinguish log2(65535/65534.5) - 10^-5 or 17 bits. There is little chance
1909
* of needing this accuracy in practice.
1910
*
1911
* To deal with this the following exp() function works out the exponent of the
1912
* frational part of the logarithm by using an accurate 32-bit value from the
1913
* top four fractional bits then multiplying in the remaining bits.
1914
*/
1915
static const png_uint_32
1916
png_32bit_exp[16] =
1917
{
1918
/* NOTE: the first entry is deliberately set to the maximum 32-bit value. */
1919
4294967295U, 4112874773U, 3938502376U, 3771522796U, 3611622603U, 3458501653U,
1920
3311872529U, 3171459999U, 3037000500U, 2908241642U, 2784941738U, 2666869345U,
1921
2553802834U, 2445529972U, 2341847524U, 2242560872U
1922
};
1923
1924
/* Adjustment table; provided to explain the numbers in the code below. */
1925
#if 0 /* BC CODE */
1926
for (i=11;i>=0;--i){ print i, " ", (1 - e(-(2^i)/65536*l(2))) * 2^(32-i), "\n"}
1927
11 44937.64284865548751208448
1928
10 45180.98734845585101160448
1929
9 45303.31936980687359311872
1930
8 45364.65110595323018870784
1931
7 45395.35850361789624614912
1932
6 45410.72259715102037508096
1933
5 45418.40724413220722311168
1934
4 45422.25021786898173001728
1935
3 45424.17186732298419044352
1936
2 45425.13273269940811464704
1937
1 45425.61317555035558641664
1938
0 45425.85339951654943850496
1939
#endif
1940
1941
static png_uint_32
1942
png_exp(png_int_32 x)
1943
/* Utility, the value 'x' must be in the range 0..0x1fffff */
1944
{
1945
/* Obtain a 4-bit approximation */
1946
png_uint_32 e = png_32bit_exp[(x >> 12) & 0xf];
1947
1948
/* Incorporate the low 12 bits - these decrease the returned value by
1949
* multiplying by a number less than 1 if the bit is set. The multiplier
1950
* is determined by the above table and the shift. Notice that the values
1951
* converge on 45426 and this is used to allow linear interpolation of the
1952
* low bits.
1953
*/
1954
if (x & 0x800)
1955
e -= (((e >> 16) * 44938U) + 16U) >> 5;
1956
1957
if (x & 0x400)
1958
e -= (((e >> 16) * 45181U) + 32U) >> 6;
1959
1960
if (x & 0x200)
1961
e -= (((e >> 16) * 45303U) + 64U) >> 7;
1962
1963
if (x & 0x100)
1964
e -= (((e >> 16) * 45365U) + 128U) >> 8;
1965
1966
if (x & 0x080)
1967
e -= (((e >> 16) * 45395U) + 256U) >> 9;
1968
1969
if (x & 0x040)
1970
e -= (((e >> 16) * 45410U) + 512U) >> 10;
1971
1972
/* And handle the low 6 bits in a single block. */
1973
e -= (((e >> 16) * 355U * (x & 0x3fU)) + 256U) >> 9;
1974
1975
/* Handle the upper bits of x, note that this works for x up to 0x1fffff but
1976
* fails for larger or negative x, where the shift (x >> 16) exceeds 31:
1977
*/
1978
e >>= x >> 16;
1979
return e;
1980
}
1981
1982
#if 0 /* UNUSED */
1983
static png_byte
1984
png_exp8bit(png_int_32 lg2)
1985
{
1986
/* The input is a negative fixed point (16:16) logarithm with a useable range
1987
* of [0.0..8.0). Clamp the value so that the output of png_exp is in the
1988
* range (254.5/255..0.5/255):
1989
*/
1990
if (lg2 <= 185) /* -log2(254.5/255) */
1991
return 255U;
1992
1993
else if (lg2 > 589453) /* -log2(0.5/255) */
1994
return 0U;
1995
1996
else
1997
{
1998
/* Get a 32-bit value: */
1999
png_uint_32 x = png_exp(lg2);
2000
2001
/* Convert the 32-bit value to 0..255 by multiplying by 256-1. Note that
2002
* the second, rounding, step can't overflow because of the first,
2003
* subtraction, step.
2004
*/
2005
x -= x >> 8;
2006
return PNG_BYTE((x + 0x7fffffU) >> 24);
2007
}
2008
}
2009
2010
static png_uint_16
2011
png_exp16bit(png_int_32 lg2)
2012
{
2013
if (lg2 <= 0) /* -log2(65534.5/65535) */
2014
return 65535U;
2015
2016
else if (lg2 > 1114110) /* -log2(0.5/65535) */
2017
return 0U;
2018
2019
else
2020
{
2021
/* Get a 32-bit value: */
2022
png_uint_32 x = png_exp(lg2);
2023
2024
/* Convert the 32-bit value to 0..65535 by multiplying by 65536-1: */
2025
x -= x >> 16;
2026
return PNG_UINT_16((x + 32767U) >> 16);
2027
}
2028
}
2029
#endif /* UNUSED */
2030
2031
static png_uint_32
2032
png_exp_nbit(png_int_32 lg2, unsigned int n)
2033
{
2034
/* These pre-computed limits give the low value of lg2 at and below which
2035
* 2^(-lg2/65536) * (2^n-1) gives (2^n-1) and the high value of lg2 above
2036
* which 2(^-lg2/65536) * (2^n-1) gives 0:
2037
*/
2038
static const png_int_32 limits[16][2] =
2039
{
2040
{ 65535, 65535 }, /* bits = 1 */
2041
{ 17238, 169408 }, /* bits = 2 */
2042
{ 7006, 249518 }, /* bits = 3 */
2043
{ 3205, 321577 }, /* bits = 4 */
2044
{ 1537, 390214 }, /* bits = 5 */
2045
{ 753, 457263 }, /* bits = 6 */
2046
{ 372, 523546 }, /* bits = 7 */
2047
{ 185, 589453 }, /* bits = 8 */
2048
{ 92, 655175 }, /* bits = 9 */
2049
{ 46, 720803 }, /* bits = 10 */
2050
{ 23, 786385 }, /* bits = 11 */
2051
{ 11, 851944 }, /* bits = 12 */
2052
{ 5, 917492 }, /* bits = 13 */
2053
{ 2, 983034 }, /* bits = 14 */
2054
{ 1, 1048573 }, /* bits = 15 */
2055
{ 0, 1114110 } /* bits = 16 */
2056
};
2057
2058
/* If 'max' is 2^n-1: */
2059
if (lg2 <= limits[n-1][0]) /* -log2((max-.5)/max) */
2060
return (1U << n)-1U;
2061
2062
else if (lg2 > limits[n-1][1]) /* -log2(.5/max) */
2063
return 0U;
2064
2065
else /* 'n' will be at least 2 */
2066
{
2067
/* Get a 32-bit value: */
2068
png_uint_32 x = png_exp(lg2);
2069
2070
/* Convert the 32-bit value to 0..(2^n-1) by multiplying by 2^n-1: */
2071
x -= x >> n;
2072
return (x + ((1U<<(31U-n))-1U)) >> (32U-n);
2073
}
2074
}
2075
#endif /* !FLOATING_ARITHMETIC */
2076
2077
#if 0 /* UNUSED */
2078
static png_byte
2079
png_gamma_8bit_correct(unsigned int value, png_fixed_point gamma_val)
2080
{
2081
if (value == 0U)
2082
return 0U;
2083
2084
else if (value >= 255U)
2085
return 255U;
2086
2087
else
2088
{
2089
# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2090
/* 'value' is unsigned, ANSI-C90 requires the compiler to correctly
2091
* convert this to a floating point value. This includes values that
2092
* would overflow if 'value' were to be converted to 'int'.
2093
*
2094
* Apparently GCC, however, does an intermediate conversion to (int)
2095
* on some (ARM) but not all (x86) platforms, possibly because of
2096
* hardware FP limitations. (E.g. if the hardware conversion always
2097
* assumes the integer register contains a signed value.) This results
2098
* in ANSI-C undefined behavior for large values.
2099
*
2100
* Other implementations on the same machine might actually be ANSI-C90
2101
* conformant and therefore compile spurious extra code for the large
2102
* values.
2103
*
2104
* We can be reasonably sure that an unsigned to float conversion
2105
* won't be faster than an int to float one. Therefore this code
2106
* assumes responsibility for the undefined behavior, which it knows
2107
* can't happen because of the check above.
2108
*
2109
* Note the argument to this routine is an (unsigned int) because, on
2110
* 16-bit platforms, it is assigned a value which might be out of
2111
* range for an (int); that would result in undefined behavior in the
2112
* caller if the *argument* ('value') were to be declared (int).
2113
*/
2114
double r = 255*pow((int)/*SAFE*/value/255.,gamma_val*.00001);
2115
if (r < .5)
2116
return 0U;
2117
2118
else if (r >= 254.5)
2119
return 255U;
2120
2121
r = floor(r+.5);
2122
return (png_byte)/*SAFE*/r;
2123
# else
2124
png_int_32 lg2 = png_log8bit(value);
2125
png_int_32 res;
2126
2127
/* Overflow in the muldiv means underflow in the calculation, this is
2128
* OK (it happens for ridiculously high gamma).
2129
*/
2130
if (!png_muldiv(&res, gamma_val, lg2, PNG_FP_1))
2131
return 0U; /* underflow */
2132
2133
return png_exp8bit(res);
2134
# endif
2135
}
2136
}
2137
#endif /* UNUSED */
2138
2139
/* libpng-1.7.0: this private function converts an n-bit input value to an
2140
* m-bit output value.
2141
*/
2142
unsigned int
2143
png_gamma_nxmbit_correct(unsigned int value, png_fixed_point gamma_val,
2144
unsigned int n/*input bits*/, unsigned int m/*output bits */)
2145
{
2146
if (value == 0U)
2147
return 0U;
2148
2149
else
2150
{
2151
unsigned int min = (1U<<n) - 1U;
2152
unsigned int mout = (1U<<m) - 1U;
2153
2154
if (value >= min)
2155
return mout;
2156
2157
else
2158
{
2159
# ifdef PNG_FLOATING_ARITHMETIC_SUPPORTED
2160
double r = value;
2161
r /= min;
2162
r = floor(mout * pow(r, gamma_val*.00001)+.5);
2163
if (r < 1)
2164
return 0U;
2165
2166
else if (r >= mout)
2167
return mout;
2168
2169
return (unsigned int)/*SAFE*/r;
2170
# else
2171
png_int_32 lg2 = png_log_nbit(value, n);
2172
png_int_32 res;
2173
2174
if (!png_muldiv(&res, gamma_val, lg2, PNG_FP_1))
2175
return 0U; /* underflow */
2176
2177
return png_exp_nbit(res, m);
2178
# endif
2179
}
2180
}
2181
}
2182
2183
#if 0 /*UNUSED*/
2184
static unsigned int
2185
png_gamma_sbit_correct(unsigned int value, png_fixed_point gamma_val,
2186
unsigned int n/*input bits*/, unsigned int sbits,
2187
unsigned int m/*output bits */)
2188
/* As above but the number of significant bits in 'n' is passed in. */
2189
{
2190
if (sbits < n)
2191
{
2192
value >>= (n-sbits);
2193
n = sbits;
2194
}
2195
2196
return png_gamma_nxmbit_correct(value, gamma_val, n, m);
2197
}
2198
#endif /*UNUSED*/
2199
2200
static int
2201
push_gamma_expand(png_transformp *transform, png_transform_controlp tc,
2202
int need_alpha)
2203
/* Utility to push a transform to expand low-bit-depth gray and, where
2204
* required, tRNS chunks. The caller must return immediately if this
2205
* returns true because the init of the new transform has been run in place
2206
* of the caller's.
2207
*/
2208
{
2209
# define png_ptr (tc->png_ptr)
2210
unsigned int expand = 0;
2211
2212
affirm(tc->init == PNG_TC_INIT_FINAL);
2213
2214
if (tc->bit_depth < 8U) /* low bit gray: expand to 8 bits */
2215
expand = PNG_EXPAND_LBD_GRAY;
2216
2217
/* Gamma correction invalidates tRNS, so if it is being expanded and
2218
* alpha is not being stripped expand it now.
2219
*/
2220
if ((tc->format & PNG_FORMAT_FLAG_ALPHA) == 0 && !tc->palette &&
2221
png_ptr->num_trans == 1 && (tc->invalid_info & PNG_INFO_tRNS) == 0)
2222
{
2223
if (need_alpha || (tc->expand_tRNS && !tc->strip_alpha))
2224
expand |= PNG_EXPAND_tRNS;
2225
2226
else
2227
tc->invalid_info |= PNG_INFO_tRNS;
2228
}
2229
2230
if (expand == 0)
2231
return 0; /* nothing needs to be done */
2232
2233
{
2234
png_transformp tr = png_push_transform(png_ptr, sizeof (png_expand),
2235
png_init_expand, transform, NULL/*don't run init*/);
2236
2237
debug(tr == *transform);
2238
tr->args |= expand;
2239
2240
/* This must be run immediately, because it just got inserted where this
2241
* transform is; this is safe, the caller must return immediately.
2242
*/
2243
png_init_expand(transform, tc);
2244
affirm(tr->fn != NULL); /* because it should need to do something! */
2245
}
2246
2247
return 1;
2248
# undef png_ptr
2249
}
2250
2251
/* Low bit depth gray gamma correction. The 1-bit case is a no-op because 0 and
2252
* 1 always map to 0 and 1. The 2-bit case has the following possiblities:
2253
*
2254
* bits/correction: g0 g1 g2 g3 g4 g5 g6
2255
* 00 -> 00 00 00 00 00 00 00
2256
* 01 -> 11 10 10 01 00 00 00
2257
* 10 -> 11 11 10 10 10 01 00
2258
* 11 -> 11 11 11 11 11 11 11
2259
*
2260
* Where the breakpoints are:
2261
*
2262
* g0: correction <= 16595 (1 - log(2.5/3))
2263
* g1: 16595 < correction <= 44966 (log(2.5/3)/log(2/3))
2264
* g2: 44966 < correction <= 63092 (1 - log(1.5/3))
2265
* g3: 63092 < correction <= 163092 (1 - log(.5/3))
2266
* g4: 163092 < correction <= 170951 (log(1.5/3)/log(2/3))
2267
* g5: 170951 < correction <= 441902 (log(.5/3)/log(2/3)
2268
* g6 441902 < correction
2269
*
2270
* This can be done by bit-hacking on the byte values (4 pixels), given that
2271
* the correction is fixed (indeed, it can be done on whole 32-bit values!)
2272
*
2273
* g0: B |= B>>1; B &= 0x55U; B |= B<<1; * either bit set
2274
* g1: B ^= B>>1; B &= 0x55U; B += B; * one bit set
2275
* g2: B &= (~B)>>1; B &= 0x55U; B += B; * low bit set, high bit unset
2276
* g3: no-op
2277
* g4: B &= (~B)>>1; B &= 0x55U; B -= B; * low bit set, high bit unset
2278
* g5: B ^= B>>1; B &= 0x55U; B -= B; * one bit set
2279
* g6: B &= B>>1; B &= 0x55U; B |= B<<1; * both bits set
2280
*/
2281
typedef struct
2282
{
2283
png_transform tr;
2284
png_fixed_point correct;
2285
png_fixed_point to_gamma;
2286
png_uint_32 shifts; /* 1 followed by up to 4 4-bit shifts */
2287
png_uint_32 channel_scale[4]; /* up to 4 channel scale factors */
2288
/* These factors are used:
2289
*
2290
* (input >> (shifts & 0xFU) * channel_scale + SCALE_R) >> SCALE_S
2291
*
2292
* Where the rounding value, SCALE_R and the shift SCALE_S are dependent
2293
* on the bit depth:
2294
*
2295
* SCALE_S = 32 - bit_depth range 16..31
2296
* SCALE_R = 1 << (SCALE_S-1)
2297
*/
2298
unsigned int to_bit_depth;
2299
unsigned int encode_alpha :1;
2300
unsigned int optimize_alpha :1;
2301
} png_transform_gamma;
2302
2303
static unsigned int
2304
init_gamma_sBIT(png_transform_gamma *tr, png_transform_controlp tc)
2305
/* Returns true if sBIT processing is required, otherwise all relevant sBIT
2306
* values match the from (tc) bit depth.
2307
*/
2308
{
2309
/* The to_bit_depth and to_gamma fields are already set, but updated values
2310
* are needed for sBIT and the shifts and channel_scale fields must be filled
2311
* in correctly. The do_gamma setting says whether gamma correction will be
2312
* done, but the scale factors are filled in regardless.
2313
*
2314
* The general scaling equation is:
2315
*
2316
* ((in >> shift) * factor + round) >> (32 - to_bit_depth)
2317
*
2318
* 'factor' is then the rounded value of:
2319
*
2320
* out_max
2321
* ------- . (1 << (32-to_bit_depth))
2322
* in_max
2323
*/
2324
# define png_ptr (tc->png_ptr)
2325
const unsigned int to_bit_depth = tr->to_bit_depth;
2326
const png_uint_32 numerator = ((1U<<to_bit_depth)-1U) << (32U-to_bit_depth);
2327
/* in_max depends on the number of significant bits */
2328
const unsigned int from_bit_depth = tc->bit_depth;
2329
2330
/* The data in the gamma transform is stored in the order of the channels in
2331
* the input row, which is the PNG order. It may be reversed below.
2332
*/
2333
png_uint_32p channel_scale = tr->channel_scale;
2334
png_uint_32 shifts = 0U;
2335
unsigned int count = 0U;
2336
unsigned int need_sBIT = 0U;
2337
2338
if (tc->format & PNG_FORMAT_FLAG_COLOR)
2339
{
2340
const unsigned int sBIT = tc->sBIT_R;
2341
2342
if (sBIT < from_bit_depth)
2343
need_sBIT = 1U;
2344
2345
debug(sBIT > 0U && sBIT <= from_bit_depth);
2346
shifts |= (from_bit_depth - sBIT) << count;
2347
count += 4U;
2348
/* round the scale: */
2349
*channel_scale++ = (numerator + (1U<<(sBIT-1U))) / ((1U << sBIT)-1U);
2350
}
2351
2352
{
2353
const unsigned int sBIT = tc->sBIT_G;
2354
2355
if (sBIT < from_bit_depth)
2356
need_sBIT = 1U;
2357
2358
debug(sBIT > 0U && sBIT <= from_bit_depth);
2359
shifts |= (from_bit_depth - sBIT) << count;
2360
count += 4U;
2361
*channel_scale++ = (numerator + (1U<<(sBIT-1U))) / ((1U << sBIT)-1U);
2362
}
2363
2364
if (tc->format & PNG_FORMAT_FLAG_COLOR)
2365
{
2366
const unsigned int sBIT = tc->sBIT_B;
2367
2368
if (sBIT < from_bit_depth)
2369
need_sBIT = 1U;
2370
2371
debug(sBIT > 0U && sBIT <= from_bit_depth);
2372
shifts |= (from_bit_depth - sBIT) << count;
2373
count += 4U;
2374
/* round the scale: */
2375
*channel_scale++ = (numerator + (1U<<(sBIT-1U))) / ((1U << sBIT)-1U);
2376
}
2377
2378
if (tc->format & PNG_FORMAT_FLAG_ALPHA)
2379
{
2380
const unsigned int sBIT = tc->sBIT_A;
2381
2382
if (sBIT < from_bit_depth)
2383
need_sBIT = 1U;
2384
2385
debug(sBIT > 0U && sBIT <= from_bit_depth);
2386
shifts |= (from_bit_depth - sBIT) << count;
2387
count += 4U;
2388
/* round the scale: */
2389
*channel_scale++ = (numerator + (1U<<(sBIT-1U))) / ((1U << sBIT)-1U);
2390
}
2391
2392
tr->shifts = shifts | (1U << count);
2393
2394
return need_sBIT;
2395
# undef png_ptr
2396
}
2397
2398
static void
2399
reverse_gamma_sBIT(png_transform_gamma *tr)
2400
{
2401
/* This is called for the 'down' gamma implementations, they read the shifts
2402
* and the channel scales in reverse, so:
2403
*/
2404
png_uint_32 shifts = tr->shifts;
2405
png_uint_32 scales[4U];
2406
unsigned int count = 0U;
2407
2408
tr->shifts = 1U;
2409
2410
while (shifts != 1U)
2411
{
2412
scales[3U-count] = tr->channel_scale[count];
2413
++count;
2414
tr->shifts <<= 4;
2415
tr->shifts |= shifts & 0xFU;
2416
shifts >>= 4;
2417
}
2418
2419
memcpy(tr->channel_scale, scales+(4U-count), count * sizeof (png_uint_32));
2420
}
2421
2422
static void
2423
png_do_gamma8_up(png_transformp *transform, png_transform_controlp tc)
2424
{
2425
# define png_ptr (tc->png_ptr)
2426
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
2427
png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc);
2428
png_bytep dp = png_voidcast(png_bytep, tc->dp);
2429
png_transform_gamma *tr =
2430
png_transform_cast(png_transform_gamma, *transform);
2431
const png_fixed_point correct = tr->correct;
2432
const unsigned int bit_depth = tr->to_bit_depth;
2433
const png_uint_32 shifts = tr->shifts;
2434
2435
affirm(tc->bit_depth == 8U);
2436
affirm(tr->shifts != 0U/*uninitialized*/);
2437
debug((shifts & 0x8888U) == 0U); /* all shifts 7 or less */
2438
debug(!tr->encode_alpha && !tr->optimize_alpha); /* only set for 16 bits */
2439
2440
tc->sp = dp;
2441
tc->bit_depth = bit_depth;
2442
tc->gamma = tr->to_gamma;
2443
2444
/* Handle the <8 bit output case differently because there can be no alpha
2445
* channel.
2446
*/
2447
if (bit_depth < 8U)
2448
{
2449
const unsigned int shift = shifts & 0xFU;
2450
unsigned int bits = 8U;
2451
unsigned int ob = 0U;
2452
2453
debug((shifts >> 4) == 1U && shift < 8U);
2454
affirm(PNG_TC_CHANNELS(*tc) == 1);
2455
2456
do
2457
{
2458
const unsigned int inb = png_gamma_nxmbit_correct(
2459
*sp++ >> shift, correct, 8U-shift, bit_depth);
2460
bits -= bit_depth;
2461
ob = ob | (inb << bits);
2462
if (bits == 0U)
2463
bits = 8U, *dp++ = PNG_BYTE(ob), ob = 0U;
2464
}
2465
while (sp < ep);
2466
2467
if (bits < 8U)
2468
*dp++ = PNG_BYTE(ob);
2469
}
2470
2471
else /* 8-bit --> 8-bit */
2472
{
2473
png_uint_32 alpha_scale;
2474
const unsigned int channels = PNG_TC_CHANNELS(*tc);
2475
unsigned int channel, alpha;
2476
2477
debug(bit_depth == 8U && (shifts >> (4*channels)) == 1U);
2478
2479
/* The alpha channel is always last, so if present checking against the
2480
* top bits of 'channels' works because of the 1U shibboleth at the end.
2481
*/
2482
if ((tc->format & PNG_FORMAT_FLAG_ALPHA) == 0)
2483
alpha_scale = alpha = 0U;
2484
2485
else
2486
{
2487
alpha = shifts >> (4U*(channels-1U));
2488
alpha_scale = tr->channel_scale[channels-1U];
2489
}
2490
2491
channel = 1U;
2492
2493
do
2494
{
2495
unsigned int inb = *sp++, shift;
2496
2497
if (channel == 1U)
2498
channel = shifts;
2499
2500
shift = channel & 0xFU;
2501
inb >>= shift;
2502
2503
/* The alpha channel is not gamma encoded but it may need some
2504
* appropriate scaling.
2505
*/
2506
if (channel == alpha)
2507
inb = (inb * alpha_scale + 0x800000U) >> 24;
2508
2509
else
2510
inb = png_gamma_nxmbit_correct(inb, correct, 8U-shift, 8U);
2511
2512
channel >>= 4; /* for the next channel, or the shibboleth */
2513
*dp++ = PNG_BYTE(inb);
2514
}
2515
while (sp < ep);
2516
2517
debug(channel == 1U);
2518
}
2519
# undef png_ptr
2520
}
2521
2522
static void
2523
png_do_gamma16_up(png_transformp *transform, png_transform_controlp tc)
2524
{
2525
# define png_ptr (tc->png_ptr)
2526
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
2527
png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 1U/*safety*/;
2528
png_bytep dp = png_voidcast(png_bytep, tc->dp);
2529
png_transform_gamma *tr =
2530
png_transform_cast(png_transform_gamma, *transform);
2531
const png_fixed_point correct = tr->correct;
2532
const unsigned int bit_depth = tr->to_bit_depth;
2533
const png_uint_32 shifts = tr->shifts;
2534
2535
affirm(tc->bit_depth == 16U);
2536
affirm(tr->shifts != 0U/*uninitialized*/);
2537
debug(!tr->optimize_alpha);
2538
2539
/* This is exactly the same as above but the input has 16 bits per component,
2540
* not 8.
2541
*/
2542
tc->sp = dp;
2543
tc->bit_depth = bit_depth;
2544
tc->gamma = tr->to_gamma;
2545
2546
/* Handle the <8 bit output case differently, the input cannot be color (at
2547
* present) and, if there is an alpha channel, then it is for the
2548
* low-bit-depth gray input case and we expect the alpha to be transparent.
2549
*/
2550
if (bit_depth < 8U)
2551
{
2552
const unsigned int shift = shifts & 0xFU;
2553
unsigned int bits = 8U;
2554
unsigned int ob = 0U;
2555
2556
affirm((tc->format & PNG_FORMAT_FLAG_COLOR) == 0U);
2557
2558
if ((tc->format & PNG_FORMAT_FLAG_ALPHA) == 0U)
2559
{
2560
debug((shifts >> 4) == 1U && shift < 16U);
2561
debug(!tr->encode_alpha && !tr->optimize_alpha);
2562
2563
do
2564
{
2565
unsigned int inb = *sp++ << 8; /* high bits first */
2566
inb = png_gamma_nxmbit_correct(
2567
(inb + *sp++) >> shift, correct, 16U-shift, bit_depth);
2568
2569
bits -= bit_depth;
2570
ob = ob | (inb << bits);
2571
if (bits == 0U)
2572
bits = 8U, *dp++ = PNG_BYTE(ob), ob = 0U;
2573
}
2574
while (sp < ep);
2575
2576
UNTESTED
2577
}
2578
2579
else /* low bit GA intermediate format */
2580
{
2581
debug((shifts >> 8) == 1U && shift < 16U);
2582
debug(!tr->encode_alpha && !tr->optimize_alpha);
2583
debug(tc->transparent_alpha);
2584
2585
/* Gray is first then the alpha component, the alpha component is just
2586
* mapped to 0 or 1.
2587
*/
2588
do
2589
{
2590
unsigned int gray = *sp++ << 8; /* high bits first */
2591
unsigned int alpha;
2592
gray += *sp++;
2593
2594
alpha = (*sp++ << 8);
2595
alpha += *sp++;
2596
2597
if (alpha == 0U)
2598
gray = 0U; /* will be replaced later */
2599
2600
else
2601
{
2602
gray = png_gamma_nxmbit_correct(gray >> shift, correct,
2603
16U-shift, bit_depth);
2604
debug(alpha == 65535U);
2605
alpha = (1U << bit_depth)-1U;
2606
}
2607
2608
bits -= bit_depth;
2609
ob = ob | (gray << bits);
2610
bits -= bit_depth;
2611
ob = ob | (alpha << bits);
2612
2613
if (bits == 0U)
2614
bits = 8U, *dp++ = PNG_BYTE(ob), ob = 0U;
2615
}
2616
while (sp < ep-2U);
2617
}
2618
2619
if (bits < 8U)
2620
*dp++ = PNG_BYTE(ob);
2621
2622
debug(sp == ep+1U);
2623
}
2624
2625
else
2626
{
2627
png_uint_32 alpha_scale;
2628
const unsigned int channels = PNG_TC_CHANNELS(*tc);
2629
unsigned int channel, alpha;
2630
2631
debug((bit_depth == 8U || bit_depth == 16U) &&
2632
(shifts >> (4*channels)) == 1U);
2633
2634
/* Note that 'encode_alpha' turns on gamma encoding of the alpha
2635
* channel (and this is a really weird operation!)
2636
*/
2637
if ((tc->format & PNG_FORMAT_FLAG_ALPHA) == 0 || tr->encode_alpha)
2638
alpha_scale = alpha = 0U;
2639
2640
else
2641
{
2642
alpha = shifts >> (4U*(channels-1U));
2643
alpha_scale = tr->channel_scale[channels-1U];
2644
}
2645
2646
channel = 1U;
2647
2648
if (bit_depth == 16U)
2649
{
2650
do
2651
{
2652
unsigned int inb = *sp++ << 8, shift;
2653
inb += *sp++;
2654
2655
if (channel == 1U)
2656
channel = shifts;
2657
2658
shift = channel & 0xFU;
2659
inb >>= shift;
2660
2661
/* The 16-16bit scaling factor equation may be off-by-1 but this
2662
* hardly matters for alpha or for gamma operations.
2663
*/
2664
if (channel == alpha)
2665
inb = (inb * alpha_scale + 0x8000U) >> 16;
2666
2667
else
2668
inb = png_gamma_nxmbit_correct(inb, correct, 16U-shift, 16U);
2669
2670
channel >>= 4; /* for the next channel, or the shibboleth */
2671
*dp++ = PNG_BYTE(inb >> 8);
2672
*dp++ = PNG_BYTE(inb);
2673
}
2674
while (sp < ep);
2675
2676
debug(channel == 1U && sp == ep+1U);
2677
}
2678
2679
else /* bit_depth == 8U */
2680
{
2681
do
2682
{
2683
unsigned int inb = *sp++ << 8, shift;
2684
inb += *sp++;
2685
2686
if (channel == 1U)
2687
channel = shifts;
2688
2689
shift = channel & 0xFU;
2690
inb >>= shift;
2691
2692
if (channel == alpha)
2693
inb = (inb * alpha_scale + 0x800000U) >> 24;
2694
2695
else
2696
inb = png_gamma_nxmbit_correct(inb, correct, 16U-shift, 8U);
2697
2698
channel >>= 4; /* for the next channel, or the shibboleth */
2699
*dp++ = PNG_BYTE(inb);
2700
}
2701
while (sp < ep);
2702
2703
debug(channel == 1U && sp == ep+1U);
2704
}
2705
}
2706
# undef png_ptr
2707
}
2708
2709
#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
2710
static void
2711
png_do_gamma16_up_optimize(png_transformp *transform, png_transform_controlp tc)
2712
/* As above, but the alpha channel is 'optimized' */
2713
{
2714
# define png_ptr (tc->png_ptr)
2715
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
2716
png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc);
2717
png_bytep dp = png_voidcast(png_bytep, tc->dp);
2718
png_transform_gamma *tr =
2719
png_transform_cast(png_transform_gamma, *transform);
2720
const png_fixed_point correct = tr->correct;
2721
2722
/* The input always as 16 bits, the output 8 or 16. There is always an alpha
2723
* channel and it is converted to the 'optimized' form, where pixels with
2724
* alpha not 0.0 or 1.0 are left in linear form (not gamma corrected.) Where
2725
* bit depth convertion is required it is from 16-bits to 8-bits and the
2726
* DIV257 macro can be used.
2727
*
2728
* The following affirms and NOT_REACHED cases are consequences of the way
2729
* the background (compose) code works:
2730
*/
2731
affirm(tr->optimize_alpha && !tr->encode_alpha && tc->bit_depth == 16U);
2732
2733
/* TODO: split this into separate functions */
2734
switch (tr->to_bit_depth)
2735
{
2736
case 8U: /* 16-bit --> 8-bit */
2737
tc->sp = dp;
2738
tc->bit_depth = 8U;
2739
tc->gamma = tr->to_gamma;
2740
2741
switch (PNG_TC_CHANNELS(*tc))
2742
{
2743
case 2:/* GA */
2744
debug(tr->shifts == 0x100U);
2745
ep -= 3U; /*SAFETY*/
2746
2747
do
2748
{
2749
png_uint_32 alpha = PNG_DIV257((sp[2] << 8) + sp[3]);
2750
2751
switch (alpha)
2752
{
2753
case 0U:
2754
dp[1] = dp[0] = 0U;
2755
break;
2756
2757
default: /* optimized case: linear color data */
2758
dp[0] = png_check_byte(png_ptr,
2759
PNG_DIV257((sp[0] << 8) + sp[1]));
2760
dp[1] = PNG_BYTE(alpha);
2761
break;
2762
2763
case 255U: /* opaque pixels are encoded */
2764
dp[0] = PNG_BYTE(png_gamma_nxmbit_correct(
2765
(sp[0] << 8) + sp[1], correct, 16U, 8U));
2766
dp[1] = 255U;
2767
break;
2768
}
2769
2770
sp += 4U;
2771
dp += 2U;
2772
}
2773
while (sp < ep);
2774
2775
debug(sp == ep+3U);
2776
break;
2777
2778
case 4:/* RGBA */
2779
debug(tr->shifts == 0x10000U);
2780
ep -= 7U; /*SAFETY*/
2781
2782
do
2783
{
2784
png_uint_32 alpha = PNG_DIV257((sp[6] << 8) + sp[7]);
2785
2786
switch (alpha)
2787
{
2788
case 0U:
2789
memset(dp, 0U, 4U);
2790
break;
2791
2792
default: /* optimized case: linear color data */
2793
dp[0] = PNG_BYTE(PNG_DIV257((sp[0] << 8) + sp[1]));
2794
dp[1] = PNG_BYTE(PNG_DIV257((sp[2] << 8) + sp[3]));
2795
dp[2] = PNG_BYTE(PNG_DIV257((sp[4] << 8) + sp[5]));
2796
dp[3] = PNG_BYTE(alpha);
2797
break;
2798
2799
case 255U: /* opaque pixels are encoded */
2800
dp[0] = PNG_BYTE(png_gamma_nxmbit_correct(
2801
(sp[0] << 8) + sp[1], correct, 16U, 8U));
2802
dp[1] = PNG_BYTE(png_gamma_nxmbit_correct(
2803
(sp[2] << 8) + sp[3], correct, 16U, 8U));
2804
dp[2] = PNG_BYTE(png_gamma_nxmbit_correct(
2805
(sp[4] << 8) + sp[5], correct, 16U, 8U));
2806
dp[3] = 255U;
2807
break;
2808
}
2809
2810
sp += 8U;
2811
dp += 4U;
2812
}
2813
while (sp < ep);
2814
2815
debug(sp == ep+7U);
2816
break;
2817
2818
default:
2819
NOT_REACHED;
2820
break;
2821
}
2822
break;
2823
2824
case 16: /* 16-bit to 16-bit */
2825
tc->sp = dp;
2826
tc->bit_depth = 16U;
2827
tc->gamma = tr->to_gamma;
2828
2829
switch (PNG_TC_CHANNELS(*tc))
2830
{
2831
case 2:/* GA */
2832
debug(tr->shifts == 0x100U);
2833
ep -= 3U; /*SAFETY*/
2834
2835
do
2836
{
2837
unsigned int alpha = (sp[2] << 8) + sp[3];
2838
2839
switch (alpha)
2840
{
2841
case 0U:
2842
memset(dp, 0U, 4U);
2843
break;
2844
2845
default: /* optimized case: linear color data */
2846
if (dp != sp)
2847
{
2848
memcpy(dp, sp, 4U);
2849
UNTESTED
2850
}
2851
break;
2852
2853
case 65535U: /* opaque pixels are encoded */
2854
{
2855
unsigned int gray = png_gamma_nxmbit_correct(
2856
(sp[0] << 8) + sp[1], correct, 16U, 16U);
2857
dp[0] = PNG_BYTE(gray >> 8);
2858
dp[1] = PNG_BYTE(gray);
2859
}
2860
dp[3] = dp[2] = 255U;
2861
break;
2862
}
2863
2864
sp += 4U;
2865
dp += 4U;
2866
}
2867
while (sp < ep);
2868
2869
debug(sp == ep+3U);
2870
break;
2871
2872
case 4:/* RGBA */
2873
debug(tr->shifts == 0x10000U);
2874
ep -= 7U; /*SAFETY*/
2875
2876
do
2877
{
2878
unsigned int alpha = (sp[6] << 8) + sp[7];
2879
2880
switch (alpha)
2881
{
2882
case 0U:
2883
memset(dp, 0U, 8U);
2884
break;
2885
2886
default: /* optimized case: linear color data */
2887
if (dp != sp)
2888
{
2889
memcpy(dp, sp, 8U);
2890
UNTESTED
2891
}
2892
break;
2893
2894
case 65535U: /* opaque pixels are encoded */
2895
{
2896
unsigned int c = png_gamma_nxmbit_correct(
2897
(sp[0] << 8) + sp[1], correct, 16U, 16U);
2898
dp[0] = PNG_BYTE(c >> 8);
2899
dp[1] = PNG_BYTE(c);
2900
2901
c = png_gamma_nxmbit_correct(
2902
(sp[2] << 8) + sp[3], correct, 16U, 16U);
2903
dp[2] = PNG_BYTE(c >> 8);
2904
dp[3] = PNG_BYTE(c);
2905
2906
c = png_gamma_nxmbit_correct(
2907
(sp[4] << 8) + sp[5], correct, 16U, 16U);
2908
dp[4] = PNG_BYTE(c >> 8);
2909
dp[5] = PNG_BYTE(c);
2910
}
2911
dp[7] = dp[6] = 255U;
2912
break;
2913
}
2914
2915
sp += 8U;
2916
dp += 8U;
2917
}
2918
while (sp < ep);
2919
2920
debug(sp == ep+7U);
2921
break;
2922
2923
default:
2924
NOT_REACHED;
2925
break;
2926
}
2927
break;
2928
2929
default:
2930
NOT_REACHED;
2931
break;
2932
}
2933
# undef png_ptr
2934
}
2935
#endif /* READ_ALPHA_MODE */
2936
2937
static void
2938
png_do_scale16_up(png_transformp *transform, png_transform_controlp tc)
2939
{
2940
# define png_ptr (tc->png_ptr)
2941
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
2942
png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc);
2943
png_bytep dp = png_voidcast(png_bytep, tc->dp);
2944
png_transform_gamma *tr =
2945
png_transform_cast(png_transform_gamma, *transform);
2946
const unsigned int bit_depth = tr->to_bit_depth;
2947
2948
affirm(tc->bit_depth == 16U && bit_depth < 8U);
2949
affirm(tr->shifts != 0U/*uninitialized*/);
2950
2951
/* This is exactly the same as above but without the gamma correction and
2952
* without the 8-bit target support. The code handles one or two channels,
2953
* but the result is not a PNG format unless the number of channels is just
2954
* 1 (grayscale).
2955
*
2956
* For multi-channel low bit depth the channels are packed into bytes using
2957
* the standard PNG big-endian packing.
2958
*/
2959
affirm((tc->format & PNG_FORMAT_FLAG_COLOR) == 0);
2960
/* The alpha shift is actually ignored; at present we only get here with an
2961
* alpha channel if it is to be removed for transparent alpha processing.
2962
*/
2963
debug(tc->format & PNG_FORMAT_FLAG_ALPHA ?
2964
(tr->shifts >> 8) == 1U : (tr->shifts >> 4) == 1U);
2965
debug(tc->transparent_alpha);
2966
2967
tc->sp = dp;
2968
/* This is a pure scaling operation so sBIT is not invalidated or altered. */
2969
tc->bit_depth = bit_depth;
2970
2971
/* TODO: maybe do this properly and use the alpha shift, but only the top bit
2972
* matters.
2973
*/
2974
{
2975
const unsigned int shift = tr->shifts & 0xFU;
2976
const png_uint_32 factor = tr->channel_scale[0];
2977
const png_uint_32 round = 1U << (31U-bit_depth);
2978
unsigned int bits = 8U;
2979
unsigned int ob = 0U;
2980
2981
do
2982
{
2983
png_uint_32 inb = *sp++ << 8; /* high bits first */
2984
inb += *sp++;
2985
2986
inb = ((inb >> shift) * factor + round) >> (32U-bit_depth);
2987
bits -= bit_depth;
2988
ob = ob | (inb << bits);
2989
if (bits == 0U)
2990
bits = 8U, *dp++ = PNG_BYTE(ob), ob = 0U;
2991
}
2992
while (sp < ep);
2993
2994
if (bits < 8U)
2995
*dp++ = PNG_BYTE(ob);
2996
}
2997
# undef png_ptr
2998
}
2999
3000
static void
3001
png_do_gamma8_down(png_transformp *transform, png_transform_controlp tc)
3002
{
3003
# define png_ptr (tc->png_ptr)
3004
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
3005
png_bytep dp = png_voidcast(png_bytep, tc->dp);
3006
png_const_bytep ep = dp + 1U/*safety*/;
3007
png_transform_gamma *tr =
3008
png_transform_cast(png_transform_gamma, *transform);
3009
const png_fixed_point correct = tr->correct;
3010
const png_uint_32 shifts = tr->shifts;
3011
3012
affirm(tc->bit_depth == 8U && tr->to_bit_depth == 16U);
3013
affirm(tr->shifts != 0U/*uninitialized*/);
3014
debug((shifts & 0x8888U) == 0U); /* all shifts 7 or less */
3015
debug(!tr->encode_alpha && !tr->optimize_alpha); /* only set for 16 bits */
3016
3017
sp += PNG_TC_ROWBYTES(*tc);
3018
tc->sp = dp;
3019
tc->bit_depth = tr->to_bit_depth;
3020
tc->gamma = tr->to_gamma;
3021
dp += PNG_TC_ROWBYTES(*tc);
3022
3023
{
3024
png_uint_32 alpha_scale;
3025
unsigned int channel, alpha;
3026
3027
debug((shifts >> (4*PNG_TC_CHANNELS(*tc))) == 1U);
3028
3029
/* We are going down so alpha, if present, is first. Notice that the init
3030
* routine has to reverse both 'shifts' and 'channel_scale' for the _down
3031
* cases.
3032
*/
3033
if ((tc->format & PNG_FORMAT_FLAG_ALPHA) == 0)
3034
alpha_scale = alpha = 0U;
3035
3036
else
3037
{
3038
alpha = shifts;
3039
alpha_scale = tr->channel_scale[0U];
3040
}
3041
3042
channel = 1U;
3043
3044
do /* 8-bit --> 16-bit */
3045
{
3046
unsigned int inb = *--sp, shift;
3047
3048
if (channel == 1U)
3049
channel = shifts;
3050
3051
shift = channel & 0xFU;
3052
inb >>= shift;
3053
3054
if (channel == alpha) /* unencoded alpha, must scale */
3055
inb = (inb * alpha_scale + 0x8000U) >> 16;
3056
3057
else
3058
inb = png_gamma_nxmbit_correct(inb, correct, 8U-shift, 16U);
3059
3060
channel >>= 4;
3061
3062
*--dp = PNG_BYTE(inb);
3063
*--dp = PNG_BYTE(inb >> 8);
3064
}
3065
while (dp > ep);
3066
3067
debug(channel == 1U && dp == ep-1U);
3068
}
3069
# undef png_ptr
3070
}
3071
3072
static void
3073
png_do_expand8_down(png_transformp *transform, png_transform_controlp tc)
3074
{
3075
# define png_ptr (tc->png_ptr)
3076
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
3077
png_bytep dp = png_voidcast(png_bytep, tc->dp);
3078
png_const_bytep ep = dp + 1U/*safety*/;
3079
png_transform_gamma *tr =
3080
png_transform_cast(png_transform_gamma, *transform);
3081
const png_uint_32 shifts = tr->shifts;
3082
3083
affirm(tc->bit_depth == 8U && tr->to_bit_depth == 16U);
3084
affirm(tr->shifts != 0U/*uninitialized*/);
3085
3086
sp += PNG_TC_ROWBYTES(*tc);
3087
tc->sp = dp;
3088
tc->bit_depth = 16U;
3089
dp += PNG_TC_ROWBYTES(*tc);
3090
3091
{
3092
png_uint_32 channel = 1U;
3093
png_const_uint_32p scale = 0U;
3094
3095
do /* 8-bit -> 16-bit */
3096
{
3097
unsigned int inb = *--sp, shift;
3098
3099
if (channel == 1U)
3100
channel = shifts, scale = tr->channel_scale;
3101
3102
shift = channel & 0xFU;
3103
channel >>= 4;
3104
inb >>= shift;
3105
inb = (inb * *scale++ + 0x8000U) >> 16;
3106
/* dp starts beyond the end: */
3107
*--dp = PNG_BYTE(inb);
3108
*--dp = PNG_BYTE(inb >> 8);
3109
}
3110
while (dp > ep);
3111
3112
debug(channel == 1U && dp == ep-1U);
3113
}
3114
# undef png_ptr
3115
}
3116
3117
static void
3118
png_do_expand8_down_fast(png_transformp *transform, png_transform_controlp tc)
3119
/* Optimized version of the above for when the sBIT settings are all a full 8
3120
* bits (the normal case).
3121
*/
3122
{
3123
# define png_ptr (tc->png_ptr)
3124
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
3125
png_bytep dp = png_voidcast(png_bytep, tc->dp);
3126
png_const_bytep ep = dp + 1U/*safety*/;
3127
png_transform_gamma *tr =
3128
png_transform_cast(png_transform_gamma, *transform);
3129
3130
affirm(tc->bit_depth == 8U && tr->to_bit_depth == 16U);
3131
affirm(tr->shifts != 0U/*uninitialized*/);
3132
3133
sp += PNG_TC_ROWBYTES(*tc);
3134
tc->sp = dp;
3135
tc->bit_depth = 16U;
3136
dp += PNG_TC_ROWBYTES(*tc);
3137
3138
do
3139
dp -= 2, dp[0] = dp[1] = *--sp;
3140
while (dp > ep);
3141
3142
debug(dp == ep-1U);
3143
# undef png_ptr
3144
}
3145
3146
static void
3147
png_init_gamma_uncached(png_transformp *transform, png_transform_controlp tc)
3148
{
3149
# define png_ptr (tc->png_ptr)
3150
png_transform_gamma *tr =
3151
png_transform_cast(png_transform_gamma, *transform);
3152
3153
debug(tc->init == PNG_TC_INIT_FINAL);
3154
3155
/* Set this first; the result says if the sBIT data is significant, but it is
3156
* ignored here.
3157
*/
3158
(void)init_gamma_sBIT(tr, tc);
3159
3160
/* If png_set_alpha_mode is called but no background processing needs to be
3161
* done (because there is no alpha channel or tRNS) we get to here with
3162
* potentially spurious alpha mode flags.
3163
*/
3164
if (!(tc->format & PNG_FORMAT_FLAG_ALPHA))
3165
tr->encode_alpha = tr->optimize_alpha = 0U;
3166
3167
/* Use separate functions for the two input depths but not for the five
3168
* possible output depths and four channel counts.
3169
*/
3170
if (tc->bit_depth == 8U)
3171
{
3172
if (tr->to_bit_depth <= 8U)
3173
tr->tr.fn = png_do_gamma8_up;
3174
3175
else
3176
{
3177
debug(tr->to_bit_depth == 16U);
3178
reverse_gamma_sBIT(tr);
3179
tr->tr.fn = png_do_gamma8_down;
3180
}
3181
}
3182
3183
else
3184
{
3185
affirm(tc->bit_depth == 16U);
3186
# ifdef PNG_READ_ALPHA_MODE_SUPPORTED
3187
if (!tr->optimize_alpha)
3188
tr->tr.fn = png_do_gamma16_up;
3189
else
3190
tr->tr.fn = png_do_gamma16_up_optimize;
3191
# else /* !READ_ALPHA_MODE */
3192
tr->tr.fn = png_do_gamma16_up;
3193
# endif /* !READ_ALPHA_MODE */
3194
}
3195
3196
/* Since the 'do' routines always perform gamma correction they will always
3197
* expand the significant bits to the full output bit depth.
3198
*/
3199
tc->invalid_info |= PNG_INFO_sBIT;
3200
tc->bit_depth = tr->to_bit_depth;
3201
tc->sBIT_R = tc->sBIT_G = tc->sBIT_B =
3202
png_check_byte(png_ptr, tc->bit_depth);
3203
if (tr->encode_alpha)
3204
tc->sBIT_A = tc->sBIT_G;
3205
tc->gamma = tr->to_gamma;
3206
# undef png_ptr
3207
}
3208
3209
#ifdef PNG_READ_sBIT_SUPPORTED
3210
static unsigned int
3211
tc_sBIT(png_const_transform_controlp tc)
3212
/* Determine the maximum number of significant bits in the row at this point.
3213
* This uses the png_struct::sig_bit field if it has not been invalidated,
3214
* otherwise it just returns the current bit depth.
3215
*/
3216
{
3217
const png_structrp png_ptr = tc->png_ptr;
3218
unsigned int bit_depth = tc->bit_depth;
3219
3220
if ((tc->invalid_info & PNG_INFO_sBIT) == 0U)
3221
{
3222
/* Normally the bit depth will not have been changed from the original PNG
3223
* depth, but it currently is changed by the grayscale expand to 8 bits,
3224
* an operation which doesn't invalidate sBIT.
3225
*/
3226
unsigned int sBIT;
3227
3228
if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0U)
3229
{
3230
/* Must use the largest of the sBIT depths, except that unset values
3231
* take priority.
3232
*/
3233
sBIT = png_ptr->sig_bit.red && png_ptr->sig_bit.green &&
3234
png_ptr->sig_bit.blue;
3235
3236
if (sBIT != 0U)
3237
{
3238
sBIT = png_ptr->sig_bit.red;
3239
3240
if (png_ptr->sig_bit.green > sBIT)
3241
sBIT = png_ptr->sig_bit.green;
3242
if (png_ptr->sig_bit.blue > sBIT)
3243
sBIT = png_ptr->sig_bit.blue;
3244
}
3245
}
3246
3247
else
3248
sBIT = png_ptr->sig_bit.gray;
3249
3250
if (sBIT > 0U && sBIT < bit_depth)
3251
bit_depth = sBIT;
3252
}
3253
3254
return bit_depth;
3255
}
3256
#else /* !READ_sBIT */
3257
# define tc_sBIT(tc) ((tc)->bit_depth)
3258
#endif /* READ_sBIT */
3259
3260
static void
3261
png_init_gamma(png_transformp *transform, png_transform_controlp tc)
3262
{
3263
const png_structrp png_ptr = tc->png_ptr;
3264
png_transform_gamma *tr =
3265
png_transform_cast(png_transform_gamma, *transform);
3266
3267
if (tc->init == PNG_TC_INIT_FORMAT)
3268
{
3269
/* This should only happen for the final encode gamma transform, which
3270
* never initializes the target bit depth (see png_set_gamma and
3271
* png_set_alpha_mode). The affirm is required here; in we can't continue
3272
* safely if the bit depth has been set somehow.
3273
*/
3274
debug(tr->tr.order == PNG_TR_GAMMA_ENCODE);
3275
affirm(tr->to_gamma > 0 && tr->to_bit_depth == 0U);
3276
3277
/* At this point the output gamma should not have been set yet: */
3278
debug(png_ptr->row_gamma == 0);
3279
3280
/* The following must be true; png_set_gamma and png_set_alpha_mode set
3281
* (or default) the PNG gamma and other routines that insert a gamma
3282
* transform must only do in PNG_TC_INIT_FINAL:
3283
*/
3284
debug(tc->gamma > 0);
3285
3286
/* At this point the data gamma must be updated so that we get the correct
3287
* png_struct::row_gamma at the end of the init:
3288
*/
3289
tc->gamma = tr->to_gamma;
3290
3291
/* For safety invalidate the sBIT information too; we don't know yet
3292
* whether a gamma transform will be required but if it is the sBIT
3293
* information becomes invalid.
3294
*/
3295
tc->invalid_info |= PNG_INFO_sBIT;
3296
}
3297
3298
else /* PNG_TC_INIT_FINAL */
3299
{
3300
/* It is very bad if we get here when processing a row: */
3301
affirm(tc->init == PNG_TC_INIT_FINAL && png_ptr->row_bit_depth > 0);
3302
3303
/* There are three cases:
3304
*
3305
* 1) Gamma correction is required, output bit depth may need to be
3306
* defaulted.
3307
* 2) Gamma correction is not required but a bit depth change is
3308
* necessary.
3309
* 3) Neither is required; the transform can be eliminated.
3310
*
3311
* First default the bit depth if it is not already set. Note that if the
3312
* output is a palette then 'row_bit_depth' refers to the palette size and
3313
* 8U must be used here. tc->palette is irrelevant; it only tells us that
3314
* the data came from a palette.
3315
*/
3316
if (tr->to_bit_depth == 0)
3317
{
3318
if ((png_ptr->row_format & PNG_FORMAT_FLAG_COLORMAP) != 0U)
3319
tr->to_bit_depth = 8U;
3320
3321
else
3322
tr->to_bit_depth = png_ptr->row_bit_depth;
3323
}
3324
3325
/* (1); is gamma correction required? If tc->gamma is 0 at this point it
3326
* is not, but then the png_struct::row_gamma should be 0 too.
3327
*/
3328
implies(tc->gamma == 0, png_ptr->row_gamma == 0);
3329
implies(tr->to_gamma == 0, tc->gamma == 0);
3330
3331
if (!png_gamma_equal(png_ptr, tc->gamma, tr->to_gamma, &tr->correct,
3332
tc_sBIT(tc)))
3333
{
3334
/* First make sure the input doesn't have a tRNS chunk which needs to
3335
* be expanded now; if it does push_gamma_expand will push an
3336
* appropriate transform *before* this one and we need to return
3337
* immediately (the caller will call back to this function).
3338
*/
3339
if (push_gamma_expand(transform, tc, 0/*need alpha*/))
3340
{
3341
affirm(tc->bit_depth >= 8U &&
3342
(tc->invalid_info & PNG_INFO_tRNS) != 0U &&
3343
*transform != &tr->tr);
3344
return;
3345
}
3346
3347
debug(*transform == &tr->tr && tc->bit_depth >= 8U);
3348
3349
/* The format is now 8 or 16-bit G, GA, RGB or RGBA and gamma
3350
* correction is required.
3351
*/
3352
png_init_gamma_uncached(transform, tc);
3353
/* TODO: implement caching for the !tc->caching cases! */
3354
return;
3355
}
3356
3357
/* The cases where the two gamma values are close enough to be considered
3358
* equal. The code lies about the gamma; this prevents apps and the
3359
* simplified API getting into loops or bad conditions because the gamma
3360
* was not set to the expected value.
3361
*
3362
* Note that png_transform_control::gamma is only set here if both the
3363
* input and output gamma values are known, otherwise the transform
3364
* introduces a spurious know gamma value.
3365
*/
3366
if (tr->to_gamma > 0 && tc->gamma > 0)
3367
tc->gamma = tr->to_gamma;
3368
3369
if (tr->to_bit_depth > tc->bit_depth)
3370
{
3371
/* This is either the to-linear operation, in which case the expected
3372
* bit depth is 16U, or it is the final encode in the case where an
3373
* 'expand' operation was also specified.
3374
*
3375
* We don't care about the PNG_TR_GAMMA_ENCODE case because we know
3376
* that there has to be an expand operation further down the pipeline.
3377
*/
3378
if (tr->tr.order < PNG_TR_GAMMA_ENCODE)
3379
{
3380
affirm(tr->to_bit_depth == 16U);
3381
3382
if (push_gamma_expand(transform, tc, 0/*need alpha*/))
3383
{
3384
affirm(tc->bit_depth == 8U &&
3385
(tc->invalid_info & PNG_INFO_tRNS) != 0U &&
3386
*transform != &tr->tr);
3387
return;
3388
}
3389
3390
debug(*transform == &tr->tr);
3391
affirm(tc->bit_depth == 8U); /* if 16U we would not be here! */
3392
3393
/* not using byte_ops here, but if there is no sBIT required
3394
* (normally the case) the fast code can be used:
3395
*/
3396
if (init_gamma_sBIT(tr, tc))
3397
tr->tr.fn = png_do_expand8_down;
3398
3399
else
3400
tr->tr.fn = png_do_expand8_down_fast;
3401
3402
tc->bit_depth = 16U;
3403
}
3404
3405
else /* PNG_TR_GAMMA_ENCODE: nothing need be done */
3406
tr->tr.fn = NULL;
3407
}
3408
3409
else if (tr->to_bit_depth < tc->bit_depth)
3410
{
3411
/* No gamma correction but bit depth *reduction* is required. Expect
3412
* the 'from' bit depth to always be 16, otherwise this transform
3413
* should not have been pushed. Also expect this to be the gamma
3414
* 'encode' operation at the end of the arithmetic.
3415
*/
3416
affirm(tc->bit_depth == 16U && tr->tr.order == PNG_TR_GAMMA_ENCODE);
3417
3418
/* If the target bit depth is 8-bit delay the operation and use the
3419
* standard 16-8-bit scale code. For low bit depth do it now.
3420
*/
3421
if (tr->to_bit_depth == 8U)
3422
{
3423
png_set_scale_16(png_ptr);
3424
tr->tr.fn = NULL;
3425
}
3426
3427
else /* low bit depth */
3428
{
3429
(void)init_gamma_sBIT(tr, tc);
3430
tr->tr.fn = png_do_scale16_up;
3431
tc->bit_depth = tr->to_bit_depth;
3432
}
3433
}
3434
3435
else /* gamma !significant and nothing to do */
3436
tr->tr.fn = NULL;
3437
}
3438
}
3439
3440
#if !PNG_RELEASE_BUILD
3441
int /* PRIVATE(debug only) */
3442
png_gamma_check(png_const_structrp png_ptr, png_const_transform_controlp tc)
3443
/* Debugging only routine to repeat the test used above to determine if the
3444
* gamma was insignificant.
3445
*
3446
* NOTE: JB20160723: This may still be incorrect in a complicated transform
3447
* pipeline because it uses 'tc_sBIT' for the end of the pipeline whereas the
3448
* init above happens earlier. I don't think this matters because the test
3449
* is only invoked if the gamma transform is eliminated or if there is a bug
3450
* and in the former case the sBIT values should remain unchanged.
3451
*/
3452
{
3453
png_fixed_point dummy;
3454
3455
return png_gamma_equal(png_ptr, png_ptr->row_gamma, tc->gamma, &dummy,
3456
tc_sBIT(tc));
3457
}
3458
#endif /* !RELEASE_BUILD */
3459
3460
static png_fixed_point
3461
translate_gamma_flags(png_const_structrp png_ptr, png_fixed_point gamma,
3462
int is_screen)
3463
/* If 'is_screen' is set this returns the inverse of the supplied value; i.e.
3464
* this routine always returns an encoding value.
3465
*/
3466
{
3467
/* Check for flag values. The main reason for having the old Mac value as a
3468
* flag is that it is pretty near impossible to work out what the correct
3469
* value is from Apple documentation - a working Mac system is needed to
3470
* discover the value!
3471
*/
3472
switch (gamma)
3473
{
3474
case PNG_DEFAULT_sRGB:
3475
case PNG_GAMMA_sRGB:
3476
case PNG_FP_1/PNG_GAMMA_sRGB: /* stupid case: -100000 */
3477
gamma = PNG_GAMMA_sRGB_INVERSE;
3478
break;
3479
3480
case PNG_GAMMA_MAC_18:
3481
case PNG_FP_1/PNG_GAMMA_MAC_18: /* stupid case: -50000 */
3482
gamma = PNG_GAMMA_MAC_INVERSE;
3483
break;
3484
3485
default:
3486
if (is_screen)
3487
{
3488
/* Check for a ridiculously low value; this will result in an
3489
* overflow
3490
* in the reciprocal calculation.
3491
*/
3492
if (gamma < 5)
3493
{
3494
png_app_error(png_ptr, "invalid screen gamma (too low)");
3495
gamma = 0;
3496
}
3497
3498
else if (gamma != PNG_FP_1) /* optimize linear */
3499
gamma = png_reciprocal(gamma);
3500
}
3501
3502
else if (gamma <= 0)
3503
{
3504
png_app_error(png_ptr, "invalid file gamma (too low)");
3505
gamma = 0;
3506
}
3507
break;
3508
}
3509
3510
return gamma;
3511
}
3512
3513
static png_transform_gamma *
3514
add_gamma_transform(png_structrp png_ptr, unsigned int order,
3515
png_fixed_point gamma, unsigned int bit_depth, int force)
3516
{
3517
/* Add a png_transform_gamma transform at the given position; this is a
3518
* utility which just adds the transform and (unconditionally) overwrites the
3519
* to_gamma field. gamma must be valid. If 'force' is true the gamma value
3520
* in an existing transform will be overwritten, otherwise this is just a
3521
* default value.
3522
*/
3523
png_transform_gamma *tr = png_transform_cast(png_transform_gamma,
3524
png_add_transform(png_ptr, sizeof (png_transform_gamma), png_init_gamma,
3525
order));
3526
3527
if (force || tr->to_gamma == 0)
3528
tr->to_gamma = gamma;
3529
3530
tr->to_bit_depth = bit_depth;
3531
3532
return tr;
3533
}
3534
3535
void PNGFAPI
3536
png_set_gamma_fixed(png_structrp png_ptr, png_fixed_point scrn_gamma,
3537
png_fixed_point file_gamma)
3538
{
3539
png_debug(1, "in png_set_gamma_fixed");
3540
3541
/* Validate the passed in file gamma value: */
3542
file_gamma = translate_gamma_flags(png_ptr, file_gamma, 0/*file*/);
3543
3544
/* The returned value may be 0, this results in a png_app_error above which
3545
* may be ignored; if that happens simply ignore the setting.
3546
*/
3547
if (file_gamma > 0)
3548
{
3549
/* Set the colorspace gamma value unconditionally - this overrides the
3550
* value in the PNG file if a gAMA chunk was present. png_set_alpha_mode
3551
* provides a different, easier, way to default the file gamma.
3552
*/
3553
png_ptr->colorspace.gamma = file_gamma;
3554
if (png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID)
3555
png_ptr->colorspace.flags = PNG_COLORSPACE_HAVE_GAMMA;
3556
else
3557
png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
3558
}
3559
3560
/* Do the same thing with the screen gamma; check it and handle it if valid.
3561
* This adds/sets the encoding of the final gamma transform in the chain.
3562
* png_set_alpha_mode does the same thing.
3563
*/
3564
scrn_gamma = translate_gamma_flags(png_ptr, scrn_gamma, 1/*screen*/);
3565
3566
if (scrn_gamma > 0)
3567
(void)add_gamma_transform(png_ptr, PNG_TR_GAMMA_ENCODE, scrn_gamma,
3568
0/*bit depth*/, 1/*force to_gamma to scrn_gamma*/);
3569
}
3570
3571
#ifdef PNG_FLOATING_POINT_SUPPORTED
3572
static png_fixed_point
3573
convert_gamma_value(png_structrp png_ptr, double output_gamma)
3574
{
3575
/* The following silently ignores cases where fixed point (times 100,000)
3576
* gamma values are passed to the floating point API. This is safe and it
3577
* means the fixed point constants work just fine with the floating point
3578
* API. The alternative would just lead to undetected errors and spurious
3579
* bug reports. Negative values fail inside the _fixed API unless they
3580
* correspond to the flag values.
3581
*/
3582
if (output_gamma < 0 || output_gamma > 128)
3583
output_gamma *= .00001;
3584
3585
return png_fixed(png_ptr, output_gamma, "gamma value");
3586
}
3587
3588
void PNGAPI
3589
png_set_gamma(png_structrp png_ptr, double scrn_gamma, double file_gamma)
3590
{
3591
png_set_gamma_fixed(png_ptr, convert_gamma_value(png_ptr, scrn_gamma),
3592
convert_gamma_value(png_ptr, file_gamma));
3593
}
3594
#endif /* FLOATING_POINT */
3595
#endif /* READ_GAMMA */
3596
3597
#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED
3598
static void
3599
png_do_rtog_48(png_transformp *transform, png_transform_controlp tc)
3600
{
3601
# define png_ptr (tc->png_ptr)
3602
const png_uint_32 r = (*transform)->args >> 16;
3603
const png_uint_32 g = (*transform)->args & 0xFFFFU;
3604
const png_uint_32 b = 65536U - r - g;
3605
3606
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
3607
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 6U;
3608
png_bytep dp = png_voidcast(png_bytep, tc->dp);
3609
3610
debug(tc->bit_depth == 16U && tc->format == PNG_FORMAT_FLAG_COLOR &&
3611
(tc->gamma == 0U || !png_gamma_significant(png_ptr, tc->gamma, 16U)));
3612
3613
tc->sp = dp;
3614
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_COLOR);
3615
3616
while (sp <= ep)
3617
{
3618
png_uint_32 gray = (((sp[0] << 8) + sp[1]) * r +
3619
((sp[2] << 8) + sp[3]) * g +
3620
((sp[4] << 8) + sp[5]) * b + 32767U) >> 16;
3621
3622
debug(gray < 65536U);
3623
*dp++ = PNG_BYTE(gray >> 8);
3624
*dp++ = PNG_BYTE(gray);
3625
sp += 6U;
3626
}
3627
# undef png_ptr
3628
}
3629
3630
static void
3631
png_do_rtog_64(png_transformp *transform, png_transform_controlp tc)
3632
{
3633
# define png_ptr (tc->png_ptr)
3634
const png_uint_32 r = (*transform)->args >> 16;
3635
const png_uint_32 g = (*transform)->args & 0xFFFFU;
3636
const png_uint_32 b = 65536U - r - g;
3637
3638
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
3639
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 8U;
3640
png_bytep dp = png_voidcast(png_bytep, tc->dp);
3641
3642
debug(tc->bit_depth == 16U &&
3643
tc->format == PNG_FORMAT_FLAG_COLOR+PNG_FORMAT_FLAG_ALPHA &&
3644
(tc->gamma == 0U || !png_gamma_significant(png_ptr, tc->gamma, 16U)));
3645
3646
tc->sp = dp;
3647
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_COLOR);
3648
3649
while (sp <= ep)
3650
{
3651
png_uint_32 gray = (((sp[0] << 8) + sp[1]) * r +
3652
((sp[2] << 8) + sp[3]) * g +
3653
((sp[4] << 8) + sp[5]) * b + 32767U) >> 16;
3654
3655
debug(gray < 65536U);
3656
*dp++ = PNG_BYTE(gray >> 8);
3657
*dp++ = PNG_BYTE(gray);
3658
sp += 6U;
3659
*dp++ = *sp++; /* alpha */
3660
*dp++ = *sp++;
3661
}
3662
# undef png_ptr
3663
}
3664
3665
static void
3666
png_init_rgb_to_gray_arithmetic(png_transformp *transform,
3667
png_transform_controlp tc)
3668
{
3669
# define png_ptr (tc->png_ptr)
3670
/* This only gets used in the final init stage: */
3671
debug(tc->init == PNG_TC_INIT_FINAL && tc->bit_depth == 16U &&
3672
(tc->format & PNG_BIC_MASK(PNG_FORMAT_FLAG_ALPHA)) ==
3673
PNG_FORMAT_FLAG_COLOR);
3674
3675
(*transform)->fn = (tc->format & PNG_FORMAT_FLAG_ALPHA) ? png_do_rtog_64 :
3676
png_do_rtog_48;
3677
3678
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_COLOR);
3679
tc->invalid_info |= PNG_INFO_sBIT;
3680
tc->sBIT_R = tc->sBIT_G = tc->sBIT_B = tc->sBIT_A =
3681
png_check_byte(png_ptr, tc->bit_depth);
3682
# undef png_ptr
3683
}
3684
3685
typedef struct
3686
{
3687
png_transform tr;
3688
png_fixed_point red_coefficient;
3689
png_fixed_point green_coefficient;
3690
unsigned int coefficients_set :1;
3691
unsigned int error_action :2;
3692
} png_transform_rgb_to_gray;
3693
3694
static void
3695
png_update_rgb_status(png_structrp png_ptr, png_transformp *transform)
3696
{
3697
png_transform_rgb_to_gray *tr = png_transform_cast(png_transform_rgb_to_gray,
3698
*transform);
3699
3700
png_ptr->rgb_to_gray_status = 1U;
3701
tr->tr.fn = NULL; /* one warning/error only */
3702
3703
switch (tr->error_action)
3704
{
3705
case PNG_ERROR_ACTION_WARN:
3706
png_warning(png_ptr, "RGB to gray found nongray pixel");
3707
break;
3708
3709
case PNG_ERROR_ACTION_ERROR:
3710
png_error(png_ptr, "RGB to gray found nongray pixel");
3711
break;
3712
3713
default:
3714
break;
3715
}
3716
}
3717
3718
static void
3719
png_do_rgb_check24(png_transformp *transform, png_transform_controlp tc)
3720
{
3721
# define png_ptr (tc->png_ptr)
3722
/* Sets 'rgb_to_gray' status if a pixel is found where the red green and blue
3723
* channels are not equal.
3724
*/
3725
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
3726
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 3U;
3727
3728
debug(tc->bit_depth == 8U && tc->format == PNG_FORMAT_FLAG_COLOR);
3729
3730
while (sp <= ep)
3731
{
3732
if ((sp[0] ^ sp[1]) | (sp[2] ^ sp[1]))
3733
{
3734
png_update_rgb_status(png_ptr, transform);
3735
break;
3736
}
3737
3738
sp += 3U;
3739
}
3740
# undef png_ptr
3741
}
3742
3743
static void
3744
png_do_rgb_check32(png_transformp *transform, png_transform_controlp tc)
3745
{
3746
# define png_ptr (tc->png_ptr)
3747
/* Sets 'rgb_to_gray' status if a pixel is found where the red green and blue
3748
* channels are not equal and alpha is not zero.
3749
*/
3750
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
3751
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 4U;
3752
3753
debug(tc->bit_depth == 8U &&
3754
tc->format == PNG_FORMAT_FLAG_COLOR+PNG_FORMAT_FLAG_ALPHA);
3755
3756
while (sp <= ep)
3757
{
3758
if (((sp[0] ^ sp[1]) | (sp[2] ^ sp[1])) && sp[3] != 0)
3759
{
3760
png_update_rgb_status(png_ptr, transform);
3761
break;
3762
}
3763
3764
sp += 4U;
3765
}
3766
# undef png_ptr
3767
}
3768
3769
static void
3770
png_do_rgb_check48(png_transformp *transform, png_transform_controlp tc)
3771
{
3772
# define png_ptr (tc->png_ptr)
3773
/* Sets 'rgb_to_gray' status if a pixel is found where the red green and blue
3774
* channels are not equal.
3775
*/
3776
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
3777
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 6U;
3778
3779
debug(tc->bit_depth == 16U && tc->format == PNG_FORMAT_FLAG_COLOR);
3780
3781
while (sp <= ep)
3782
{
3783
if ((sp[0] ^ sp[2]) | (sp[4] ^ sp[2]) |
3784
(sp[1] ^ sp[3]) | (sp[5] ^ sp[3]))
3785
{
3786
png_update_rgb_status(png_ptr, transform);
3787
break;
3788
}
3789
3790
sp += 6U;
3791
}
3792
# undef png_ptr
3793
}
3794
3795
static void
3796
png_do_rgb_check64(png_transformp *transform, png_transform_controlp tc)
3797
{
3798
# define png_ptr (tc->png_ptr)
3799
/* Sets 'rgb_to_gray' status if a pixel is found where the red green and blue
3800
* channels are not equal and alpha is not zero.
3801
*/
3802
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
3803
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 8U;
3804
3805
debug(tc->bit_depth == 16U &&
3806
tc->format == PNG_FORMAT_FLAG_COLOR+PNG_FORMAT_FLAG_ALPHA);
3807
3808
while (sp <= ep)
3809
{
3810
if (((sp[0] ^ sp[2]) | (sp[4] ^ sp[2]) |
3811
(sp[1] ^ sp[3]) | (sp[5] ^ sp[3])) &&
3812
(sp[6] | sp[7]) != 0)
3813
{
3814
png_update_rgb_status(png_ptr, transform);
3815
break;
3816
}
3817
3818
sp += 8U;
3819
}
3820
# undef png_ptr
3821
}
3822
3823
static void
3824
png_init_rgb_to_gray(png_transformp *transform, png_transform_controlp tc)
3825
{
3826
png_structrp png_ptr = tc->png_ptr;
3827
3828
/* Basic checks: if there is no color in the format this transform is not
3829
* applicable.
3830
*/
3831
if ((tc->format & PNG_FORMAT_FLAG_COLOR) != 0)
3832
{
3833
png_transform_rgb_to_gray *tr = png_transform_cast(
3834
png_transform_rgb_to_gray, *transform);
3835
3836
/* no colormap allowed: */
3837
affirm(tc->init && !(tc->format & PNG_FORMAT_FLAG_COLORMAP));
3838
/* no extra flags yet: */
3839
debug(!(tc->format &
3840
PNG_BIC_MASK(PNG_FORMAT_FLAG_COLOR+PNG_FORMAT_FLAG_ALPHA)));
3841
/* at present no non-palette caching: */
3842
implies(tc->caching, tc->palette);
3843
3844
if (tc->init == PNG_TC_INIT_FORMAT)
3845
{
3846
/* The convertion should just remove the 'COLOR' flag and do nothing
3847
* else, but if a tRNS chunk is present this would invalidate it.
3848
* Handle this by expanding it now.
3849
*/
3850
if ((tc->format & PNG_FORMAT_FLAG_ALPHA) == 0 && !tc->palette &&
3851
png_ptr->num_trans == 1 && !(tc->invalid_info & PNG_INFO_tRNS))
3852
{
3853
/* Only if expand was requested and not cancelled: */
3854
if (tc->expand_tRNS && !tc->strip_alpha)
3855
tc->format |= PNG_FORMAT_FLAG_ALPHA;
3856
3857
tc->invalid_info |= PNG_INFO_tRNS; /* prevent expansion later */
3858
}
3859
3860
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_COLOR);
3861
}
3862
3863
else /* PNG_TC_INIT_FINAL */
3864
{
3865
unsigned int index; /* channel to select (invalid) */
3866
png_byte sBIT_color; /* sBIT of that channel if valid */
3867
png_fixed_point r, g; /* Coefficients in range 0..65536 */
3868
3869
/* Push a tRNS transform if required. Because this is a push the
3870
* transform the init needs to be run now. This needs to go in
3871
* before the check on r==g==b because a color key might be used.
3872
*/
3873
if ((tc->format & PNG_FORMAT_FLAG_ALPHA) == 0 && !tc->palette &&
3874
png_ptr->num_trans == 1 && !(tc->invalid_info & PNG_INFO_tRNS))
3875
{
3876
if (tc->expand_tRNS && !tc->strip_alpha)
3877
{
3878
png_transformp tr_expand = png_push_transform(png_ptr,
3879
sizeof (png_expand), png_init_expand, transform, NULL);
3880
3881
debug(*transform == tr_expand);
3882
tr_expand->args |= PNG_EXPAND_tRNS;
3883
png_init_expand(transform, tc);
3884
/* Check for the infinite loop possibility: */
3885
affirm((tc->invalid_info & PNG_INFO_tRNS) != 0);
3886
return;
3887
}
3888
3889
else
3890
tc->invalid_info |= PNG_INFO_tRNS;
3891
}
3892
3893
{
3894
png_fixed_point red, green;
3895
3896
if (tr->coefficients_set)
3897
{
3898
red = tr->red_coefficient;
3899
green = tr->green_coefficient;
3900
}
3901
3902
# ifdef PNG_COLORSPACE_SUPPORTED
3903
else if ((png_ptr->colorspace.flags &
3904
(PNG_COLORSPACE_HAVE_ENDPOINTS+PNG_COLORSPACE_INVALID))
3905
== PNG_COLORSPACE_HAVE_ENDPOINTS)
3906
{
3907
red = png_ptr->colorspace.end_points_XYZ.red_Y;
3908
green = png_ptr->colorspace.end_points_XYZ.green_Y;
3909
}
3910
# endif
3911
3912
else /* no colorspace support, assume sRGB */
3913
{
3914
/* From IEC 61966-2-1:1999, the reverse transformation from sRGB
3915
* RGB values to XYZ D65 values (not CIEXYZ!). These are not
3916
* exact inverses of the forward transformation; they only have
3917
* four (decimal) digits of precision.
3918
*
3919
* API CHANGE: in 1.7.0 the sRGB values from the official IEC
3920
* specification are used, previously libpng used values from
3921
* Charles Poynton's ColorFAQ of 1998-01-04. The original page
3922
* is gone, however up to date information can be found below:
3923
*
3924
* http://www.poynton.com/ColorFAQ.html
3925
*
3926
* At the time of reading (20150628) this web site quotes the
3927
* same values as below and cites ITU Rec 709 as the source.
3928
*/
3929
red = 21260;
3930
green = 71520;
3931
}
3932
3933
/* Prior to 1.7 this calculation was done with 15-bit precision,
3934
* this is because the code was written pre-muldiv and tried to
3935
* work round the problems caused by the signs in integer
3936
* calculations.
3937
*/
3938
(void)png_muldiv(&r, red, 65536, PNG_FP_1);
3939
(void)png_muldiv(&g, green, 65536, PNG_FP_1);
3940
}
3941
3942
/* If the convertion can be deduced to select a single channel do so.
3943
* If the error action is set to error just copy the red channel, if
3944
* the coefficients select just one channel use that.
3945
*/
3946
if (tr->error_action == PNG_ERROR_ACTION_ERROR || r >= 65536)
3947
index = 0U, sBIT_color = tc->sBIT_R; /* select red */
3948
3949
else if (g >= 65536)
3950
index = 1U, sBIT_color = tc->sBIT_G; /* select green */
3951
3952
else if (r + g == 0)
3953
index = 2U, sBIT_color = tc->sBIT_B; /* select blue */
3954
3955
else
3956
index = 3U, sBIT_color = 0U/*UNUSED*/;
3957
3958
if (index == 3U)
3959
{
3960
/* Arithmetic will have to be done. For this we need linear 16-bit
3961
* data which must then be converted back to the required bit depth,
3962
* png_init_gamma handles this. It may push other expand operations
3963
* (it shouldn't but it can), so give it some space.
3964
*
3965
* The gamma must be restored to the original value, 0U for the bit
3966
* depth means use the output bit depth.
3967
*/
3968
(void)add_gamma_transform(png_ptr, PNG_TR_GAMMA_ENCODE, tc->gamma,
3969
0U/*bit depth*/, 0/*default*/);
3970
3971
/* If png_init_gamma is called with tc->gamma 0 it does the right
3972
* thing in PNG_TC_INIT_FINAL; it just does any required bit depth
3973
* adjustment.
3974
*/
3975
(void)add_gamma_transform(png_ptr, tr->tr.order + 0x10U, PNG_FP_1,
3976
16U, 1/*force: doesn't matter*/);
3977
3978
{
3979
/* This init routine will update the sBIT information
3980
* appropriately.
3981
*/
3982
png_transformp tr_rtog = png_add_transform(png_ptr, 0/*size*/,
3983
png_init_rgb_to_gray_arithmetic, tr->tr.order + 0x20U);
3984
3985
/* r and g are known to be in the range 0..65535, so pack them
3986
* into the 'args' argument of a new transform.
3987
*/
3988
tr_rtog->args = (((png_uint_32)r) << 16) + g;
3989
}
3990
}
3991
3992
else /* index < 3 */
3993
{
3994
/* TODO: does this need to select the correct sBIT value too? */
3995
png_add_rgb_to_gray_byte_ops(png_ptr, tc, index,
3996
tr->tr.order + 0x10U);
3997
tc->sBIT_G = sBIT_color;
3998
}
3999
4000
/* Prior to 1.7 libpng would always check for r!=g!=b. In 1.7 an extra
4001
* error_action setting is added to prevent this overhead.
4002
*/
4003
if (tr->error_action)
4004
tr->tr.fn = tc->bit_depth == 8 ?
4005
((tc->format & PNG_FORMAT_FLAG_ALPHA) ?
4006
png_do_rgb_check32 : png_do_rgb_check24) :
4007
((tc->format & PNG_FORMAT_FLAG_ALPHA) ?
4008
png_do_rgb_check64 : png_do_rgb_check48);
4009
4010
else
4011
tr->tr.fn = NULL; /* PNG_ERROR_ACTION_NO_CHECK */
4012
}
4013
}
4014
4015
else /* not color: transform not applicable */
4016
(*transform)->fn = NULL;
4017
}
4018
4019
void PNGFAPI
4020
png_set_rgb_to_gray_fixed(png_structrp png_ptr, int error_action,
4021
png_fixed_point red, png_fixed_point green)
4022
/* API CHANGE: in 1.7 calling this on a palette PNG no longer causes the
4023
* palette to be expanded (unless explicitly requested), rather it converts
4024
* the palette to grayscale.
4025
*/
4026
{
4027
/* The coefficients must be reasonable, the error handling is to warn (pre
4028
* 1.7) or app error (1.7) and drop back to the cHRM definition of Y. The
4029
* drop back is done in the init routine if relevant flag is unset. Passing
4030
* negative values causes this default to be used without a warning.
4031
*/
4032
int pset = 0;
4033
4034
if (red >= 0 && green >= 0)
4035
{
4036
if (red <= PNG_FP_1 && green <= PNG_FP_1 && red + green <= PNG_FP_1)
4037
pset = 1;
4038
4039
else /* overflow */
4040
png_app_error(png_ptr, "rgb_to_gray coefficients too large (ignored)");
4041
}
4042
4043
{
4044
png_transform_rgb_to_gray *tr =
4045
png_transform_cast(png_transform_rgb_to_gray,
4046
png_add_transform(png_ptr, sizeof (png_transform_rgb_to_gray),
4047
png_init_rgb_to_gray, PNG_TR_RGB_TO_GRAY));
4048
4049
tr->error_action = 0x3U & error_action;
4050
4051
if (red < 0 || green < 0) /* use cHRM default */
4052
tr->coefficients_set = 0U;
4053
4054
else if (pset) /* else bad coefficients which get ignored */
4055
{
4056
tr->coefficients_set = 1U;
4057
tr->red_coefficient = red;
4058
tr->green_coefficient = green;
4059
}
4060
}
4061
}
4062
4063
#ifdef PNG_FLOATING_POINT_SUPPORTED
4064
/* Convert a RGB image to a grayscale of the same width. This allows us,
4065
* for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
4066
*/
4067
4068
void PNGAPI
4069
png_set_rgb_to_gray(png_structrp png_ptr, int error_action, double red,
4070
double green)
4071
{
4072
png_set_rgb_to_gray_fixed(png_ptr, error_action,
4073
png_fixed(png_ptr, red, "rgb to gray red coefficient"),
4074
png_fixed(png_ptr, green, "rgb to gray green coefficient"));
4075
}
4076
#endif /* FLOATING POINT */
4077
#endif /* RGB_TO_GRAY */
4078
4079
#ifdef PNG_READ_BACKGROUND_SUPPORTED
4080
typedef struct
4081
{
4082
png_transform tr;
4083
struct
4084
{
4085
png_color_16 background;
4086
unsigned int need_expand :1; /* Background matches format of PNG */
4087
unsigned int rgb_to_gray :1; /* RGB-to-gray transform found */
4088
unsigned int compose_background :1; /* png_set_background */
4089
unsigned int associate_alpha :1;
4090
unsigned int encode_alpha :1;
4091
unsigned int optimize_alpha :1;
4092
unsigned int background_is_gray :1; /* Background color is gray */
4093
unsigned int background_bit_depth :5; /* bit depth, 1..16 */
4094
unsigned int ntrans :3; /* 1..6 bytes */
4095
png_byte transparent_pixel[6];
4096
png_byte background_pixel[6];
4097
png_fixed_point background_gamma;
4098
} st; /* to allow the whole state to be copied reliably */
4099
} png_transform_background;
4100
4101
static void
4102
resolve_background_color(png_transform_background *tr,
4103
png_transform_controlp tc)
4104
{
4105
png_const_structp png_ptr = tc->png_ptr;
4106
4107
/* Deduce the bit depth and color information for the background, the
4108
* special case is when need_expand is set and the PNG has palette format,
4109
* then (and only then) the background value is a palette index.
4110
*/
4111
if (tr->st.need_expand && tc->palette)
4112
{
4113
unsigned int i = tr->st.background.index;
4114
png_byte r, g, b;
4115
4116
if (i >= png_ptr->num_palette)
4117
{
4118
png_app_error(png_ptr, "background index out of range");
4119
tr->tr.fn = NULL;
4120
return;
4121
}
4122
4123
tr->st.background_bit_depth = 8U;
4124
r = png_ptr->palette[i].red;
4125
g = png_ptr->palette[i].green;
4126
b = png_ptr->palette[i].blue;
4127
4128
if (r == g && g == b)
4129
{
4130
tr->st.background_is_gray = 1U;
4131
tr->st.background.gray = g;
4132
UNTESTED
4133
}
4134
4135
else
4136
{
4137
tr->st.background_is_gray = 0U;
4138
tr->st.background.red = r;
4139
tr->st.background.green = g;
4140
tr->st.background.blue = b;
4141
UNTESTED
4142
}
4143
}
4144
4145
else /* background is not a palette index */
4146
{
4147
int use_rgb;
4148
png_uint_16 mask;
4149
4150
/* First work out the bit depth and whether or not to use the RGB
4151
* fields of the background.
4152
*/
4153
if (tr->st.need_expand)
4154
{
4155
affirm(!(tc->format & PNG_FORMAT_FLAG_COLORMAP));
4156
tr->st.background_bit_depth =
4157
png_check_bits(png_ptr, png_ptr->bit_depth, 5U);
4158
use_rgb = (png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0;
4159
}
4160
4161
else /* screen format background */
4162
{
4163
/* If the final output is in palette format assume the background
4164
* is in a matching format. This covers two cases, an original
4165
* COLORMAP PNG and png_set_quantize.
4166
*/
4167
if ((png_ptr->row_format & PNG_FORMAT_FLAG_COLORMAP) != 0)
4168
tr->st.background_bit_depth = 8U;
4169
4170
else
4171
tr->st.background_bit_depth =
4172
png_check_bits(png_ptr, png_ptr->row_bit_depth, 5U);
4173
4174
use_rgb = (png_ptr->row_format & PNG_FORMAT_FLAG_COLOR) != 0;
4175
}
4176
4177
/* The PNG spec says to use the low bits of the values, so we mask out
4178
* the high bits here (at present no warning is produced if they are
4179
* set.)
4180
*/
4181
mask = png_check_u16(png_ptr, (1U << tr->st.background_bit_depth)-1U);
4182
4183
if (use_rgb)
4184
{
4185
png_uint_16 r, g, b;
4186
4187
r = tr->st.background.red & mask;
4188
g = tr->st.background.green & mask;
4189
b = tr->st.background.blue & mask;
4190
4191
if (r == g && g == b)
4192
{
4193
tr->st.background_is_gray = 1U;
4194
tr->st.background.gray = g;
4195
}
4196
4197
else
4198
{
4199
tr->st.background_is_gray = 0U;
4200
tr->st.background.red = r;
4201
tr->st.background.green = g;
4202
tr->st.background.blue = b;
4203
}
4204
}
4205
4206
else /* gray */
4207
{
4208
tr->st.background_is_gray = 1U;
4209
tr->st.background.gray = tr->st.background.gray & mask;
4210
}
4211
}
4212
}
4213
4214
static void
4215
gamma_correct_background_component(png_const_structrp png_ptr, png_uint_16p cp,
4216
unsigned int bdc, png_fixed_point correction, unsigned int bdout)
4217
/* Utility function for gamma_correct_background. */
4218
{
4219
unsigned int c = *cp;
4220
4221
/* 0.0 and 1.0 are unchanged (and common): */
4222
if (c > 0U && c < (1U<<bdc)-1U)
4223
{
4224
if (correction != 0)
4225
c = png_check_bits(png_ptr,
4226
png_gamma_nxmbit_correct(c, correction, bdc, bdout), bdout);
4227
4228
else if (bdc != bdout)
4229
{
4230
/* Scale the value from bdc to bdout bits. */
4231
png_int_32 i;
4232
affirm(png_muldiv(&i, c, (1U<<bdout)-1U, (1U<<bdc)-1U));
4233
c = png_check_bits(png_ptr, i, bdout);
4234
}
4235
}
4236
4237
else if (c != 0U)
4238
c = (1U << bdout) - 1U;
4239
4240
*cp = PNG_UINT_16(c);
4241
PNG_UNUSED(png_ptr) /* if checking disabled */
4242
}
4243
4244
static void
4245
gamma_correct_background(png_transform_background *tr,
4246
png_const_transform_controlp tc)
4247
{
4248
# define png_ptr (tc->png_ptr)
4249
png_fixed_point correction = tc->gamma;
4250
const unsigned int bdback = tr->st.background_bit_depth;
4251
const unsigned int bdrow = tc->bit_depth;
4252
4253
/* This is harmless if it fails but it will damage the output pixels - they
4254
* won't have the requested color depth accuracy where the background is
4255
* used.
4256
*/
4257
debug(bdback <= bdrow);
4258
debug(tr->st.background_is_gray || (bdrow >= 8U && bdback >= 8U));
4259
4260
/* The background is assumed to be full precision; there is no sBIT
4261
* information for it. The convertion converts from the current depth and
4262
* gamma of the background to that in the transform control. It uses the
4263
* full 16-bit precision when considering the gamma values even though this
4264
* is probably spurious.
4265
*/
4266
if (correction != 0 && (tr->st.background_gamma == 0 ||
4267
png_gamma_equal(png_ptr, tr->st.background_gamma, correction,
4268
&correction, 16U)))
4269
correction = 0; /* no correction! */
4270
4271
if (tr->st.background_is_gray)
4272
gamma_correct_background_component(png_ptr, &tr->st.background.gray,
4273
bdback, correction, bdrow);
4274
4275
else
4276
{
4277
gamma_correct_background_component(png_ptr, &tr->st.background.red,
4278
bdback, correction, bdrow);
4279
gamma_correct_background_component(png_ptr, &tr->st.background.green,
4280
bdback, correction, bdrow);
4281
gamma_correct_background_component(png_ptr, &tr->st.background.blue,
4282
bdback, correction, bdrow);
4283
}
4284
4285
/* Regardless of whether there was a correction set the background gamma: */
4286
tr->st.background_gamma = tc->gamma;
4287
tr->st.background_bit_depth = png_check_bits(png_ptr, bdrow, 5U);
4288
# undef png_ptr
4289
}
4290
4291
static void
4292
fill_background_pixel(png_transform_background *tr, png_transform_controlp tc)
4293
{
4294
# define png_ptr (tc->png_ptr)
4295
/* Fill in 'background_pixel' if the appropriate sequence of bytes for the
4296
* format given in the transform control.
4297
*/
4298
unsigned int bdtc = tc->bit_depth;
4299
4300
/* If necessary adjust the background pixel to the current row format (it is
4301
* important to do this as late as possible to avoid spurious
4302
* interconvertions).
4303
*/
4304
gamma_correct_background(tr, tc);
4305
4306
if (tr->st.background_is_gray)
4307
{
4308
unsigned int g = tr->st.background.gray;
4309
4310
/* 'g' now has enough bits for the destination, note that in the case of
4311
* low bit depth gray this causes the pixel to be replicated through the
4312
* written byte. Fill all six bytes with the replicated background:
4313
*/
4314
while (bdtc < 8U)
4315
{
4316
g &= (1U << bdtc) - 1U; /* use only the low bits */
4317
g |= g << bdtc;
4318
bdtc <<= 1;
4319
}
4320
4321
memset(tr->st.background_pixel, PNG_BYTE(g), 6U);
4322
if (bdtc == 16U)
4323
tr->st.background_pixel[0] = tr->st.background_pixel[2] =
4324
tr->st.background_pixel[4] = PNG_BYTE(g >> 8);
4325
/* Must not include the alpha channel here: */
4326
tr->st.ntrans = png_check_bits(png_ptr,
4327
((tc->format & PNG_FORMAT_FLAG_COLOR)+1U) << (bdtc == 16U), 3U);
4328
}
4329
4330
else
4331
{
4332
unsigned int r = tr->st.background.red;
4333
unsigned int g = tr->st.background.green;
4334
unsigned int b = tr->st.background.blue;
4335
4336
debug((tc->format & PNG_FORMAT_FLAG_COLOR) != 0);
4337
4338
switch (bdtc)
4339
{
4340
case 8U:
4341
tr->st.background_pixel[0] = PNG_BYTE(r);
4342
tr->st.background_pixel[1] = PNG_BYTE(g);
4343
tr->st.background_pixel[2] = PNG_BYTE(b);
4344
tr->st.ntrans = 3U;
4345
break;
4346
4347
case 16U:
4348
tr->st.background_pixel[0] = PNG_BYTE(r>>8);
4349
tr->st.background_pixel[1] = PNG_BYTE(r);
4350
tr->st.background_pixel[2] = PNG_BYTE(g>>8);
4351
tr->st.background_pixel[3] = PNG_BYTE(g);
4352
tr->st.background_pixel[4] = PNG_BYTE(b>>8);
4353
tr->st.background_pixel[5] = PNG_BYTE(b);
4354
tr->st.ntrans = 6U;
4355
break;
4356
4357
default:
4358
NOT_REACHED;
4359
}
4360
}
4361
# undef png_ptr
4362
}
4363
4364
/* Look for colors matching the trans_color in png_ptr and replace them. This
4365
* must handle all the non-alpha formats.
4366
*/
4367
static void
4368
png_do_replace_tRNS_multi(png_transformp *transform, png_transform_controlp tc)
4369
{
4370
# define png_ptr (tc->png_ptr)
4371
png_transform_background *tr =
4372
png_transform_cast(png_transform_background, *transform);
4373
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4374
const unsigned int cbytes = tr->st.ntrans;
4375
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4376
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - cbytes/*safety*/;
4377
const int copy = dp != sp;
4378
4379
/* We expect opaque and transparent pixels to be interleaved but with long
4380
* sequences of each.
4381
*/
4382
debug(!(tc->format & PNG_FORMAT_FLAG_ALPHA) &&
4383
PNG_TC_PIXEL_DEPTH(*tc) == cbytes << 3);
4384
tc->invalid_info |= PNG_INFO_tRNS;
4385
tc->sp = dp;
4386
4387
/* Look for pixels that match the transparent value, copying opaque ones as
4388
* required.
4389
*/
4390
do
4391
{
4392
const png_const_bytep opaque_start = sp;
4393
size_t cb;
4394
4395
/* Find a transparent pixel, or the end: */
4396
do
4397
{
4398
if (memcmp(sp, tr->st.transparent_pixel, cbytes) == 0) /*transparent*/
4399
break;
4400
sp += cbytes;
4401
}
4402
while (sp <= ep);
4403
4404
cb = sp - opaque_start;
4405
4406
/* Copy any opaque pixels: */
4407
if (cb > 0)
4408
{
4409
if (copy)
4410
memcpy(dp, opaque_start, cb);
4411
dp += cb;
4412
}
4413
4414
/* Set transparent pixels to the background (this has to be done one-by
4415
* one; the case where all the bytes in the background are equal is not
4416
* optimized.)
4417
*/
4418
if (sp <= ep) do
4419
{
4420
memcpy(dp, tr->st.background_pixel, cbytes);
4421
sp += cbytes;
4422
dp += cbytes;
4423
}
4424
while (sp <= ep && memcmp(sp, tr->st.transparent_pixel, cbytes) == 0);
4425
} while (sp <= ep);
4426
4427
debug(sp == ep+cbytes);
4428
# undef png_ptr
4429
}
4430
4431
static void
4432
png_do_replace_tRNS_8(png_transformp *transform, png_transform_controlp tc)
4433
/* The single byte version: 8-bit gray */
4434
{
4435
# define png_ptr (tc->png_ptr)
4436
png_transform_background *tr =
4437
png_transform_cast(png_transform_background, *transform);
4438
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4439
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4440
png_alloc_size_t row_bytes = tc->width;
4441
const int copy = dp != sp;
4442
const int transparent_pixel = tr->st.transparent_pixel[0];
4443
const int background_pixel = tr->st.background_pixel[0];
4444
4445
/* We expect opaque and transparent pixels to be interleaved but with long
4446
* sequences of each.
4447
*/
4448
debug(!(tc->format & PNG_FORMAT_FLAG_ALPHA) &&
4449
PNG_TC_PIXEL_DEPTH(*tc) == 8 && tr->st.ntrans == 1);
4450
tc->invalid_info |= PNG_INFO_tRNS;
4451
tc->sp = dp;
4452
4453
/* Now search for a byte that matches the transparent pixel. */
4454
do
4455
{
4456
const png_const_bytep tp = png_voidcast(png_const_bytep,
4457
memchr(sp, transparent_pixel, row_bytes));
4458
png_alloc_size_t cb;
4459
4460
if (tp == NULL) /* all remaining pixels are opaque */
4461
{
4462
if (copy)
4463
memcpy(dp, sp, row_bytes);
4464
return;
4465
}
4466
4467
cb = tp - sp;
4468
if (cb > 0) /* some opaque pixels found */
4469
{
4470
if (copy)
4471
memcpy(dp, sp, cb);
4472
sp = tp;
4473
dp += cb;
4474
debug(row_bytes > cb);
4475
row_bytes -= cb;
4476
}
4477
4478
/* Now count the transparent pixels, this could use strspn but for the
4479
* moment does not.
4480
*/
4481
debug(row_bytes > 0);
4482
++sp; /* next to check, may be beyond the last */
4483
while (--row_bytes > 0 && *sp == transparent_pixel) ++sp;
4484
4485
cb = sp - tp;
4486
memset(dp, background_pixel, cb);
4487
dp += cb;
4488
} while (row_bytes > 0);
4489
UNTESTED
4490
# undef png_ptr
4491
}
4492
4493
static void
4494
png_do_set_row(png_transformp *transform, png_transform_controlp tc)
4495
/* This is a no-op transform that both invalidates INFO from args and sets
4496
* the entire row to the byte given in the top bits.
4497
*/
4498
{
4499
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4500
4501
tc->sp = dp;
4502
memset(dp, (*transform)->args >> 24, PNG_TC_ROWBYTES(*tc));
4503
}
4504
4505
static void
4506
png_do_replace_tRNS_lbd(png_transformp *transform, png_transform_controlp tc)
4507
{
4508
/* This is the 2 or 4 bit depth grayscale case; the 1 bit case is handled by
4509
* the two routines above and the 8-bit and 16-bit cases by the two before
4510
* that.
4511
*
4512
* The transform contains pixel values that have been expanded to one byte,
4513
* the code needs to match the tRNS pixel and substitute the background one
4514
* in each byte.
4515
*/
4516
# define png_ptr (tc->png_ptr)
4517
png_transform_background *tr =
4518
png_transform_cast(png_transform_background, *transform);
4519
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4520
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4521
png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc);
4522
const unsigned int copy = sp != dp;
4523
const png_byte transparent_pixel = tr->st.transparent_pixel[0];
4524
const png_byte background_pixel = tr->st.background_pixel[0];
4525
4526
/* We expect opaque and transparent pixels to be interleaved but with long
4527
* sequences of each.
4528
*/
4529
debug(!(tc->format & PNG_FORMAT_FLAG_ALPHA) &&
4530
PNG_TC_PIXEL_DEPTH(*tc) < 8 && tr->st.ntrans == 1);
4531
tc->sp = dp;
4532
4533
/* Now search for a byte that contains the transparent pixel
4534
*
4535
* NOTE: this is the "strlen" algorithm, I first saw a variant implemented in
4536
* Acorn RISC iX (strlen) around 1991, almost certainly derived from a
4537
* suggestion by Alan Mycroft dating from April 27, 1987 (Mycroft was one of
4538
* the authors of the 'Norcroft' compiler used for RISC iX, and well known to
4539
* the RISC iX implementors.) See, e.g.:
4540
*
4541
* http://bits.stephan-brumme.com/null.html.
4542
*
4543
* The exact form used here is the one reported by Brumme; I haven't been
4544
* able to find the original Mycroft posting, it was probably on comp.arch.
4545
*
4546
* The 4-bit and 2-bit versions (probably slower in the 4-bit case than the
4547
* do-it-by-pixel version, but definately faster once 32-bit handling is
4548
* implemented):
4549
*
4550
* 4 bit: (byte - 0x11) & ~byte & 0x88
4551
* 2 bit: (byte - 0x55) & ~byte & 0xcc
4552
*
4553
* The generalizations to 32 bits (8 and 16 pixels per step) should be
4554
* obvious.
4555
*
4556
* This algorithm reads pixels within a byte beyond the end of the row and,
4557
* potentially, changes the non-existent pixels. This is harmless and not
4558
* a security risk.
4559
*/
4560
if (tc->bit_depth == 4U)
4561
{
4562
/* For the moment the algorithm isn't used; there are only two pixels in
4563
* each byte so it is likely to be quicker to check as below:
4564
*/
4565
do
4566
{
4567
const png_byte b = *sp++;
4568
const unsigned int m = b ^ transparent_pixel;
4569
4570
if (m == 0U) /* both transparent */
4571
*dp = background_pixel;
4572
4573
else if ((m & 0xF0U) == 0U) /* first transparent */
4574
*dp = PNG_BYTE((background_pixel & 0xF0U) | (b & 0x0FU));
4575
4576
else if ((m & 0x0FU) == 0U) /* second transparent */
4577
*dp = PNG_BYTE((background_pixel & 0x0FU) | (b & 0xF0U));
4578
4579
else if (copy) /* neither transparent */
4580
*dp = b;
4581
4582
++dp;
4583
} while (sp < ep);
4584
}
4585
4586
else
4587
{
4588
affirm(tc->bit_depth == 2U);
4589
4590
do
4591
{
4592
const png_byte b = *sp++;
4593
const unsigned int m = b ^ transparent_pixel;
4594
4595
if (m == 0U) /* transparent */
4596
*dp = background_pixel;
4597
4598
else if (0xAAU & ((m - 0x55U) & ~m))
4599
{
4600
/* One or more pixels transparent */
4601
const unsigned int mask =
4602
(m & 0xC0U ? 0xC0U : 0U) |
4603
(m & 0x30U ? 0x30U : 0U) |
4604
(m & 0x0CU ? 0x0CU : 0U) |
4605
(m & 0x03U ? 0x03U : 0U);
4606
4607
*dp = PNG_BYTE((b & mask) | (background_pixel & ~mask));
4608
}
4609
4610
else if (copy) /* no transparent pixels */
4611
*dp = b;
4612
4613
++dp;
4614
} while (sp < ep);
4615
}
4616
4617
# undef png_ptr
4618
}
4619
4620
static void
4621
png_do_background_with_transparent_GA8(png_transformp *transform,
4622
png_transform_controlp tc)
4623
{
4624
# define png_ptr (tc->png_ptr)
4625
png_transform_background *tr =
4626
png_transform_cast(png_transform_background, *transform);
4627
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4628
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4629
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 1U/*safety*/;
4630
const png_byte background_pixel = tr->st.background_pixel[0];
4631
4632
/* Because this is an alpha format and we are removing the alpha channel we
4633
* can copy up.
4634
*/
4635
debug(tc->bit_depth == 8U && tc->format == PNG_FORMAT_GA &&
4636
tr->st.ntrans == 1U);
4637
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_ALPHA);
4638
tc->sp = dp;
4639
4640
/* Look for pixels that have alpha 0; all others should have alpha 1.0,
4641
* however they are simply treated as opaque regardless.
4642
*/
4643
do
4644
{
4645
*dp++ = (sp[1] == 0U) ? background_pixel : sp[0];
4646
sp += 2U;
4647
} while (sp < ep);
4648
4649
debug(sp == ep+1U);
4650
# undef png_ptr
4651
}
4652
4653
static void
4654
png_do_background_with_transparent_GA16(png_transformp *transform,
4655
png_transform_controlp tc)
4656
{
4657
# define png_ptr (tc->png_ptr)
4658
png_transform_background *tr =
4659
png_transform_cast(png_transform_background, *transform);
4660
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4661
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4662
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 3U/*safety*/;
4663
4664
debug(tc->bit_depth == 16U && tc->format == PNG_FORMAT_GA &&
4665
tr->st.ntrans == 2U);
4666
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_ALPHA);
4667
tc->sp = dp;
4668
4669
do
4670
{
4671
if (sp[2] == 0U && sp[3] == 0U) /* transparent */
4672
dp[0] = tr->st.background_pixel[0], dp[1] = tr->st.background_pixel[1];
4673
4674
else
4675
dp[0] = sp[0], dp[1] = sp[1];
4676
4677
dp += 2U;
4678
sp += 4U;
4679
} while (sp < ep);
4680
4681
debug(sp == ep+3U);
4682
# undef png_ptr
4683
}
4684
4685
static void
4686
png_do_background_with_transparent_GAlbd(png_transformp *transform,
4687
png_transform_controlp tc)
4688
/* This is the low-bit-depth gray case, the input is 1, 2 or 4-bit per
4689
* channel gray-alpha.
4690
*/
4691
{
4692
# define png_ptr (tc->png_ptr)
4693
png_transform_background *tr =
4694
png_transform_cast(png_transform_background, *transform);
4695
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4696
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4697
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc);
4698
const unsigned int bit_depth = tc->bit_depth;
4699
const unsigned int mask = (1U << bit_depth) - 1U;
4700
const unsigned int back = tr->st.background_pixel[0] & mask;
4701
unsigned int opos, ob, inb;
4702
4703
debug(bit_depth < 8U && tc->format == PNG_FORMAT_GA && tr->st.ntrans == 1U);
4704
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_ALPHA);
4705
tc->sp = dp;
4706
4707
ob = 0U; /* output byte */
4708
opos = 0U; /* bit index of previous output pixel (counts down) */
4709
inb = 0U; /* quiet a GCC 4.8.5 warning */
4710
4711
for (;;)
4712
{
4713
/* The output is half the size of the input, so we need a new input byte
4714
* for every 4 bits of output:
4715
*/
4716
if (opos == 0U || opos == 4U)
4717
{
4718
if (sp >= ep)
4719
break;
4720
4721
inb = *sp++;
4722
}
4723
4724
/* Move to the next *output* pixel, this wraps when bits is 0U: */
4725
opos = (opos - bit_depth) & 0x7U;
4726
4727
/* Extract the whole input pixel to the low bits of a temporary: */
4728
{
4729
unsigned int pixel = inb >> ((opos*2U) & 0x7U);
4730
4731
/* The alpha channel is second, check for a value of 0: */
4732
if ((pixel & mask)/* A component*/ == 0U)
4733
pixel = back;
4734
4735
else
4736
{
4737
debug((pixel & mask) == mask);
4738
pixel = (pixel >> bit_depth) & mask; /* G component */
4739
}
4740
4741
ob |= pixel << opos;
4742
}
4743
4744
if (opos == 0U)
4745
*dp++ = PNG_BYTE(ob), ob = 0U;
4746
}
4747
4748
if (opos != 0U)
4749
*dp++ = PNG_BYTE(ob);
4750
4751
debug(sp == ep);
4752
# undef png_ptr
4753
}
4754
4755
static void
4756
png_do_background_with_transparent_RGBA8(png_transformp *transform,
4757
png_transform_controlp tc)
4758
{
4759
# define png_ptr (tc->png_ptr)
4760
png_transform_background *tr =
4761
png_transform_cast(png_transform_background, *transform);
4762
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4763
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4764
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 3U/*safety*/;
4765
4766
debug(tc->bit_depth == 8U && tc->format == PNG_FORMAT_RGBA &&
4767
tr->st.ntrans == 3U);
4768
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_ALPHA);
4769
tc->sp = dp;
4770
4771
do
4772
{
4773
if (sp[3] == 0U) /* transparent */
4774
memcpy(dp, tr->st.background_pixel, 3U);
4775
4776
else
4777
memmove(dp, sp, 3U);
4778
4779
dp += 3U;
4780
sp += 4U;
4781
} while (sp < ep);
4782
4783
debug(sp == ep+3U);
4784
# undef png_ptr
4785
}
4786
4787
static void
4788
png_do_background_with_transparent_RGBA16(png_transformp *transform,
4789
png_transform_controlp tc)
4790
{
4791
# define png_ptr (tc->png_ptr)
4792
png_transform_background *tr =
4793
png_transform_cast(png_transform_background, *transform);
4794
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4795
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4796
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 7U/*safety*/;
4797
4798
debug(tc->bit_depth == 16U && tc->format == PNG_FORMAT_RGBA &&
4799
tr->st.ntrans == 6U);
4800
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_ALPHA);
4801
tc->sp = dp;
4802
4803
do
4804
{
4805
if (sp[6] == 0U && sp[7] == 0U) /* transparent */
4806
memcpy(dp, tr->st.background_pixel, 6U);
4807
4808
else
4809
memmove(dp, sp, 6U);
4810
4811
dp += 6U;
4812
sp += 8U;
4813
} while (sp < ep);
4814
4815
debug(sp == ep+7U);
4816
# undef png_ptr
4817
}
4818
4819
static void
4820
png_init_background_transparent(png_transformp *transform,
4821
png_transform_controlp tc)
4822
/* Select the correct version of the above routines. */
4823
{
4824
# define png_ptr (tc->png_ptr)
4825
png_transform_background *tr =
4826
png_transform_cast(png_transform_background, *transform);
4827
4828
debug(tc->init == PNG_TC_INIT_FINAL /* never called in 'FORMAT' */ &&
4829
(tc->format & PNG_FORMAT_FLAG_ALPHA) != 0);
4830
4831
/* Now we know the format on which processing will happen so it is possible
4832
* to generate the correct fill pixel value to use.
4833
*/
4834
fill_background_pixel(tr, tc);
4835
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_ALPHA);
4836
tc->invalid_info |= PNG_INFO_sBIT;
4837
tc->sBIT_R = tc->sBIT_G = tc->sBIT_B = tc->sBIT_A =
4838
png_check_byte(png_ptr, tc->bit_depth);
4839
4840
if (!(tc->format & PNG_FORMAT_FLAG_COLOR))
4841
{
4842
if (tc->bit_depth == 8U)
4843
tr->tr.fn = png_do_background_with_transparent_GA8;
4844
4845
else if (tc->bit_depth == 16U)
4846
tr->tr.fn = png_do_background_with_transparent_GA16;
4847
4848
else /* low-bit-depth gray with alpha (not a PNG format!) */
4849
tr->tr.fn = png_do_background_with_transparent_GAlbd;
4850
}
4851
4852
else /* color */
4853
{
4854
if (tc->bit_depth == 8U)
4855
tr->tr.fn = png_do_background_with_transparent_RGBA8;
4856
4857
else
4858
{
4859
debug(tc->bit_depth == 16U);
4860
tr->tr.fn = png_do_background_with_transparent_RGBA16;
4861
}
4862
}
4863
# undef png_ptr
4864
}
4865
4866
/* The calculated values below have the range 0..65535*65535, the output has the
4867
* range 0..65535, so divide by 65535. Two approaches are given here, one
4868
* modifies the value in place, the other uses a more complex expression. With
4869
* gcc on an AMD64 system the in-place approach is very slightly faster.
4870
*
4871
* The two expressions are slightly different in what they calculate but both
4872
* give the exact answer (verified by exhaustive testing.)
4873
*
4874
* The macro must be given a png_uint_32 variable (lvalue), normally an auto
4875
* variable.
4876
*/
4877
#ifndef PNG_COMPOSE_DIV_65535
4878
# ifdef PNG_COMPOSE_DIV_EXPRESSION_SUPPORTED
4879
# define PNG_COMPOSE_DIV_65535(v)\
4880
(v = ((v + (v>>16) + (v>>31) + 32768U) >> 16))
4881
# else
4882
# define PNG_COMPOSE_DIV_65535(v)\
4883
(v += v >> 16, v += v >> 31, v += 32768U, v >>= 16)
4884
# endif
4885
#endif
4886
4887
static void
4888
png_do_background_alpha_GA(png_transformp *transform, png_transform_controlp tc)
4889
{
4890
# define png_ptr (tc->png_ptr)
4891
png_transform_background *tr =
4892
png_transform_cast(png_transform_background, *transform);
4893
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4894
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4895
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 3U/*safety*/;
4896
const unsigned int background = tr->st.background.gray;
4897
const int copy = (sp != dp);
4898
const int compose = tr->st.compose_background;
4899
4900
affirm(tc->bit_depth == 16U && tc->format == PNG_FORMAT_GA &&
4901
tr->st.background_bit_depth == 16U);
4902
4903
/* If gamma transforms are eliminated this might fail: */
4904
debug(tr->st.background_gamma == tc->gamma ||
4905
tr->st.background_gamma == 0 ||
4906
tc->sBIT_G == 1);
4907
4908
tc->sp = tc->dp; /* nothing else changes */
4909
4910
do
4911
{
4912
const png_uint_32 alpha = (sp[2] << 8) + sp[3];
4913
4914
switch (alpha)
4915
{
4916
case 0U: /* transparent */
4917
memset(dp, 0U, 4U);
4918
break;
4919
4920
default:
4921
{
4922
png_uint_32 v = ((sp[0] << 8) + sp[1]) * alpha +
4923
background * (65535U - alpha);
4924
4925
PNG_COMPOSE_DIV_65535(v);
4926
debug(v <= 65535U);
4927
dp[0] = PNG_BYTE(v >> 8);
4928
dp[1] = PNG_BYTE(v);
4929
}
4930
4931
if (compose)
4932
dp[3] = dp[2] = 0xFFU; /* alpha; set to 1.0 */
4933
4934
else if (copy)
4935
{
4936
dp[2] = PNG_BYTE(alpha >> 8);
4937
dp[3] = PNG_BYTE(alpha);
4938
}
4939
break;
4940
4941
case 65535U: /* opaque */
4942
if (copy)
4943
memcpy(dp, sp, 4U);
4944
break;
4945
}
4946
4947
sp += 4U;
4948
dp += 4U;
4949
}
4950
while (sp < ep);
4951
4952
debug(sp == ep+3U);
4953
# undef png_ptr
4954
}
4955
4956
static void
4957
png_do_background_alpha_RGBA(png_transformp *transform,
4958
png_transform_controlp tc)
4959
{
4960
# define png_ptr (tc->png_ptr)
4961
png_transform_background *tr =
4962
png_transform_cast(png_transform_background, *transform);
4963
png_bytep dp = png_voidcast(png_bytep, tc->dp);
4964
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
4965
const png_const_bytep ep = sp + PNG_TC_ROWBYTES(*tc) - 7U/*safety*/;
4966
const unsigned int bred = tr->st.background.red;
4967
const unsigned int bgreen = tr->st.background.green;
4968
const unsigned int bblue = tr->st.background.blue;
4969
const int copy = (sp != dp);
4970
const int compose = tr->st.compose_background;
4971
4972
affirm(tc->bit_depth == 16U && tc->format == PNG_FORMAT_RGBA &&
4973
tr->st.background_bit_depth == 16U);
4974
4975
debug(tr->st.background_gamma == tc->gamma ||
4976
tr->st.background_gamma == 0 ||
4977
(tc->sBIT_R == 1 && tc->sBIT_G == 1 && tc->sBIT_B == 1));
4978
4979
tc->sp = tc->dp; /* nothing else changes */
4980
4981
do
4982
{
4983
const png_uint_32 alpha = (sp[6] << 8) + sp[7];
4984
4985
switch (alpha)
4986
{
4987
case 0U: /* transparent */
4988
memset(dp, 0U, 8U);
4989
break;
4990
4991
default:
4992
{
4993
const png_uint_32 balpha = (65535U - alpha);
4994
png_uint_32 r = ((sp[0] << 8) + sp[1]) * alpha + bred * balpha;
4995
png_uint_32 g = ((sp[2] << 8) + sp[3]) * alpha + bgreen * balpha;
4996
png_uint_32 b = ((sp[4] << 8) + sp[5]) * alpha + bblue * balpha;
4997
4998
PNG_COMPOSE_DIV_65535(r);
4999
PNG_COMPOSE_DIV_65535(g);
5000
PNG_COMPOSE_DIV_65535(b);
5001
debug(r <= 65535U && g <= 65535U && b <= 65535U);
5002
dp[0] = PNG_BYTE(r >> 8);
5003
dp[1] = PNG_BYTE(r);
5004
dp[2] = PNG_BYTE(g >> 8);
5005
dp[3] = PNG_BYTE(g);
5006
dp[4] = PNG_BYTE(b >> 8);
5007
dp[5] = PNG_BYTE(b);
5008
}
5009
5010
if (compose)
5011
dp[7] = dp[6] = 0xFFU;
5012
5013
else if (copy)
5014
{
5015
dp[6] = PNG_BYTE(alpha >> 8);
5016
dp[7] = PNG_BYTE(alpha);
5017
}
5018
break;
5019
5020
case 65535U: /* opaque */
5021
if (copy)
5022
memcpy(dp, sp, 8U);
5023
break;
5024
}
5025
5026
sp += 8U;
5027
dp += 8U;
5028
}
5029
while (sp < ep);
5030
5031
debug(sp == ep+7U);
5032
# undef png_ptr
5033
}
5034
5035
static void
5036
png_init_background_alpha_end(png_transformp *transform,
5037
png_transform_controlp tc)
5038
/* This is just the last part of png_init_background_alpha (below) */
5039
{
5040
# define png_ptr (tc->png_ptr)
5041
png_transform_background *tr =
5042
png_transform_cast(png_transform_background, *transform);
5043
5044
debug(tc->init == PNG_TC_INIT_FINAL);
5045
5046
/* Repeat the tests at the end of png_init_background_alpha: */
5047
affirm(tc->bit_depth == 16U && (tc->format & PNG_FORMAT_FLAG_ALPHA) != 0);
5048
debug(tc->gamma == 0 ||
5049
!png_gamma_significant(png_ptr, tc->gamma, tc_sBIT(tc)));
5050
5051
/* tr->st.background_is_gray was filled in by resolve_background_color and
5052
* records if either the background was a gray value or it was a color
5053
* value with all the channels equal.
5054
*/
5055
if (!tr->st.background_is_gray && !(tc->format & PNG_FORMAT_FLAG_COLOR))
5056
{
5057
# ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED
5058
/* Color background with gray data: this happens when there is a
5059
* gray to RGB transform in the pipeline but it hasn't happened
5060
* yet. Unfortunately it has to happen now to be able to do the
5061
* compose against the colored background.
5062
*/
5063
png_push_gray_to_rgb_byte_ops(transform, tc);
5064
affirm((tc->format & PNG_FORMAT_FLAG_COLOR) != 0);
5065
return;
5066
# else /* !GRAY_TO_RGB */
5067
impossible("gray to RGB"); /* how can this happen? */
5068
# endif /* !GRAY_TO_RGB */
5069
}
5070
5071
/* The transform happens in two parts, a part to do the arithmetic on
5072
* pixels where it is required followed by a part to replace transparent
5073
* pixels. These two parts require different versions of the background
5074
* pixel. Set up the second part first.
5075
*
5076
* This only happens with background composition, otherwise the
5077
* transparent pixels are already 0 and nothing needs to be done.
5078
*/
5079
if (tr->st.compose_background)
5080
{
5081
/* The transparent pixel handling happens *after* the data has been
5082
* re-encoded to the output gamma:
5083
*/
5084
png_transform_background *tr_alpha =
5085
png_transform_cast(png_transform_background,
5086
png_add_transform(png_ptr, sizeof (png_transform_background),
5087
png_init_background_transparent, PNG_TR_GAMMA_ENCODE+0xF0U));
5088
5089
/* Copy the current state into the new png_transform_background: */
5090
tr_alpha->st = tr->st;
5091
tr_alpha->tr.args = tr->tr.args;
5092
}
5093
5094
/* Now it is possible to overwrite tr->st.background with the linear version.
5095
*/
5096
gamma_correct_background(tr, tc);
5097
5098
/* sBIT informationmust also be invalidated here, because a gamma
5099
* transform may run before the transparent pixel handling.
5100
*/
5101
tc->invalid_info |= PNG_INFO_sBIT;
5102
tc->sBIT_R = tc->sBIT_G = tc->sBIT_B = tc->sBIT_A =
5103
png_check_byte(png_ptr, tc->bit_depth);
5104
5105
/* And select an appropriate function; there are only two choices: */
5106
switch (tc->format)
5107
{
5108
case PNG_FORMAT_GA:
5109
/* If the background format is color this indicates that there is a
5110
* gray to RGB transform missing and we need it to happen before
5111
* this point!
5112
*/
5113
affirm(tr->st.background_is_gray);
5114
tr->tr.fn = png_do_background_alpha_GA;
5115
break;
5116
5117
case PNG_FORMAT_RGBA:
5118
if (tr->st.background_is_gray)
5119
tr->st.background.blue = tr->st.background.green =
5120
tr->st.background.red = tr->st.background.gray;
5121
tr->tr.fn = png_do_background_alpha_RGBA;
5122
break;
5123
5124
default:
5125
NOT_REACHED;
5126
}
5127
# undef png_ptr
5128
}
5129
5130
static void
5131
png_init_background_alpha(png_transformp *transform, png_transform_controlp tc)
5132
/* This is used when alpha composition is required because the alpha channel
5133
* may contain values that are between 0 and 1. Because doing alpha
5134
* composition requires linear arithmetic the data is converted to 16-bit
5135
* linear, however this means that the background pixel gets converted too
5136
* and, for 16-bit output, this tends to smash the value. Consequently the
5137
* algorithm used here is to skip those pixels and use the 'transparent
5138
* alpha' routines to replace them after the gamma correction step.
5139
*/
5140
{
5141
# define png_ptr (tc->png_ptr)
5142
png_transform_background *tr =
5143
png_transform_cast(png_transform_background, *transform);
5144
5145
debug(tc->init == PNG_TC_INIT_FINAL);
5146
/* png_init_background ensures this is true: */
5147
debug((tc->format & PNG_FORMAT_FLAG_ALPHA) != 0);
5148
5149
/* Always push gamma transforms; don't try to optimize the case when they
5150
* aren't needed because that would be an attempt to duplicate the tests in
5151
* png_init_gamma and it might now work reliably.
5152
*
5153
* Need to push the to-linear transform *before* this transform and add gamma
5154
* correction afterward to get back to the screen format. Do the afterward
5155
* bit first to avoid complexity over *transform:
5156
*/
5157
{
5158
png_transform_gamma *tr_end = add_gamma_transform(png_ptr,
5159
PNG_TR_GAMMA_ENCODE, tc->gamma, 0U/*bit depth*/, 0/*default*/);
5160
5161
/* Encoding the alpha channel happens in the last step, so this needs to
5162
* be set here. Notice that in C++ terms we are very friendly with
5163
* png_transform_gamma.
5164
*/
5165
tr_end->encode_alpha = tr->st.encode_alpha;
5166
tr_end->optimize_alpha = tr->st.optimize_alpha;
5167
}
5168
5169
{
5170
/* Now add tr_gamma before this transform, expect it to go in at
5171
* *transform or the whole thing won't work:
5172
*/
5173
png_transform_gamma *tr_gamma = png_transform_cast(png_transform_gamma,
5174
png_push_transform(png_ptr, sizeof (png_transform_gamma),
5175
png_init_gamma, transform, NULL/*don't run init*/));
5176
5177
/* This must happen before we run png_gamma_init: */
5178
tr_gamma->to_gamma = PNG_FP_1;
5179
tr_gamma->to_bit_depth = 16U;
5180
5181
/* Now run the this transform; it was pushed before this one, so it gets
5182
* to do its init first and this function must return as the caller will
5183
* immediately call here again.
5184
*/
5185
debug(*transform == &tr_gamma->tr);
5186
png_init_gamma(transform, tc);
5187
affirm(tc->bit_depth == 16U &&
5188
(tc->format & PNG_FORMAT_FLAG_ALPHA) != 0);
5189
/* This is only a 'debug' because it needs to replicate the test in
5190
* png_init_gamma and that is easy to get wrong (a harmless mistake).
5191
*/
5192
debug(tc->gamma == 0 ||
5193
!png_gamma_significant(png_ptr, tc->gamma, tc_sBIT(tc)));
5194
}
5195
5196
/* A transform was pushed, so this transform init will be run again: */
5197
tr->tr.fn = png_init_background_alpha_end;
5198
# undef png_ptr
5199
}
5200
5201
/* Handle alpha and tRNS via a background color */
5202
static void
5203
png_init_background(png_transformp *transform, png_transform_controlp tc)
5204
{
5205
/* This init function is called right at the start, this means it can get at
5206
* the tRNS values if appropriate. If not the RGB to gray transform comes
5207
* next followed by PNG_TR_COMPOSE_ALPHA, which actually does the non-tRNS
5208
* work.
5209
*/
5210
png_structp png_ptr = tc->png_ptr;
5211
png_transform_background *tr =
5212
png_transform_cast(png_transform_background, *transform);
5213
5214
if (tc->init == PNG_TC_INIT_FORMAT)
5215
{
5216
/* Background composition removes the alpha channel, so the other
5217
* operations become irrelevant:
5218
*/
5219
if (tr->st.compose_background)
5220
tr->st.associate_alpha = tr->st.encode_alpha = tr->st.optimize_alpha =
5221
0U;
5222
5223
else if (!tr->st.associate_alpha)
5224
{
5225
/* There is nothing to do, delete the whole transform. */
5226
tr->tr.fn = NULL;
5227
return;
5228
}
5229
5230
/* Else alpha association ('pre-multiplication') which is achieved by
5231
* composing on a 0 background. The background color will be black (all
5232
* zeros) and the background gamma will be zero.
5233
*/
5234
5235
/* Because we are in PNG_TC_INIT_FORMAT no other transforms will have been
5236
* inserted between this one and an rgb-to-gray transform, so we can find
5237
* out if rgb-to-gray has been requested:
5238
*/
5239
tr->st.rgb_to_gray = tr->tr.next != NULL &&
5240
tr->tr.next->order == PNG_TR_RGB_TO_GRAY;
5241
5242
if ((tc->format & PNG_FORMAT_FLAG_ALPHA) != 0)
5243
{
5244
/* Associated alpha does not strip the alpha channel! */
5245
if (tr->st.compose_background)
5246
tc->format &= PNG_BIC_MASK(PNG_FORMAT_FLAG_ALPHA);
5247
}
5248
5249
else if (!tc->palette &&
5250
png_ptr->num_trans == 1 && !(tc->invalid_info & PNG_INFO_tRNS))
5251
{
5252
/* tRNS will be expanded, or handled */
5253
tc->invalid_info |= PNG_INFO_tRNS;
5254
if (!tr->st.compose_background)
5255
{
5256
tc->format |= PNG_FORMAT_FLAG_ALPHA;
5257
/* And in this case, only, because we are adding an alpha channel we
5258
* need to have a channel depth of at least 8:
5259
*/
5260
if (tc->bit_depth < 8U)
5261
tc->bit_depth = 8U;
5262
}
5263
}
5264
5265
else /* no transparent pixels to change */
5266
tr->tr.fn = NULL;
5267
}
5268
5269
else /* PNG_TC_INIT_FINAL */
5270
{
5271
png_fixed_point correction;
5272
5273
debug(tc->init == PNG_TC_INIT_FINAL &&
5274
((tc->format & PNG_FORMAT_FLAG_ALPHA) != 0 ||
5275
(!tc->palette && png_ptr->num_trans == 1 &&
5276
!(tc->invalid_info & PNG_INFO_tRNS))));
5277
5278
/* The screen gamma is known, so the background gamma can be found, note
5279
* that both the gamma values used below will be 0 if no gamma information
5280
* was in the PNG and no gamma information has been provided by
5281
* png_set_gamma or png_set_alpha_mode.
5282
*/
5283
switch (tr->st.background_gamma)
5284
{
5285
case PNG_BACKGROUND_GAMMA_FILE:
5286
/* png_init_transform_control has already found the file gamma,
5287
* and because this is the first arithmetic transformation
5288
* nothing has changed it.
5289
*/
5290
tr->st.background_gamma = tc->gamma;
5291
break;
5292
5293
case PNG_BACKGROUND_GAMMA_SCREEN:
5294
tr->st.background_gamma = png_ptr->row_gamma;
5295
break;
5296
5297
default:
5298
/* already set */
5299
break;
5300
}
5301
5302
/* Work out what the background color is, this only depends on 'tc' for
5303
* palette information, so it can be done now before we know the actual
5304
* bit_depth/format that will be required:
5305
*/
5306
resolve_background_color(tr, tc);
5307
5308
/* Is this format compatible with the current row data? If it is then it
5309
* is possible to avoid the arithmetic if no alpha processing is required.
5310
* This is a useful optimization because PNG files with just transparent
5311
* pixels and no alpha are common.
5312
*
5313
* NOTE: if an RGB-to-gray transform is present this is fine so long as
5314
* the background is gray, otherwise (non-gray background) there is a
5315
* following gray-to-RGB transform and the now gray image must be
5316
* composited on a color background.
5317
*/
5318
if (tr->st.compose_background /* alpha channel stripped */ &&
5319
(tr->st.background_is_gray ||
5320
((tc->format & PNG_FORMAT_FLAG_COLOR) != 0 && !tr->st.rgb_to_gray))
5321
/* color compatible */ &&
5322
tc->bit_depth >= tr->st.background_bit_depth
5323
/* bit depth compatible */ &&
5324
(tc->transparent_alpha ||
5325
(!tc->palette && png_ptr->num_trans == 1 &&
5326
!(tc->invalid_info & PNG_INFO_tRNS)))
5327
/* no alpha processing */ &&
5328
png_gamma_equal(png_ptr, tc->gamma, png_ptr->row_gamma, &correction,
5329
tc->bit_depth) /* gamma compatible (so no gamma processing) */)
5330
{
5331
/* How the operation gets performed depends on whether the current data
5332
* has an alpha channel or not.
5333
*/
5334
if ((tc->format & PNG_FORMAT_FLAG_ALPHA) != 0)
5335
{
5336
affirm(tc->transparent_alpha);
5337
/* This init routine does the sBIT handling: */
5338
png_init_background_transparent(transform, tc);
5339
}
5340
5341
else if (!tc->palette && png_ptr->num_trans == 1 &&
5342
!(tc->invalid_info & PNG_INFO_tRNS))
5343
{
5344
/* The background pixel needs to be filled in now; no more init
5345
* routines are called in this case. It is important to delay this
5346
* as late as possible because it needs to know the actual tc format
5347
* that must be used.
5348
*/
5349
fill_background_pixel(tr, tc);
5350
5351
debug(!(png_ptr->color_type & PNG_COLOR_MASK_PALETTE));
5352
5353
/* The pixel depth should not have been changed yet: */
5354
debug(PNG_PIXEL_DEPTH(*png_ptr) == PNG_TC_PIXEL_DEPTH(*tc));
5355
5356
/* The transparent_pixel value needs to be filled in. */
5357
affirm(tr->st.ntrans ==
5358
fill_transparent_pixel(png_ptr, tr->st.transparent_pixel));
5359
5360
/* The whole operation is a no-op if the transparent pixel and the
5361
* background pixel match, even in the associated alpha case where
5362
* both will be 0 throughout.
5363
*
5364
* NOTE: for palette images this test happens in the caching
5365
* operation, so the answer is still correct.
5366
*
5367
* NOTE: for low bit depth gray both 'transparent_pixel' and
5368
* 'background_pixel' have been expanded to fill a byte, so this
5369
* works.
5370
*/
5371
if (memcmp(tr->st.transparent_pixel, tr->st.background_pixel,
5372
tr->st.ntrans) == 0)
5373
tr->tr.fn = NULL;
5374
5375
/* Then the processing function depends on the pixel size: */
5376
else if (tr->st.ntrans > 1U)
5377
tr->tr.fn = png_do_replace_tRNS_multi;
5378
5379
else if (tc->bit_depth == 8U)
5380
tr->tr.fn = png_do_replace_tRNS_8;
5381
5382
else if (tc->bit_depth == 1U)
5383
{
5384
/* This is the silly case: the replacement pixel does not match
5385
* the transparent pixel (handled above) so either all the '0'
5386
* bits are replaced by '1' or all the '1' bits are replaced by
5387
* '0':
5388
*/
5389
png_uint_32 args = tr->st.background_pixel[0];
5390
5391
args <<= 24;
5392
args |= PNG_INFO_tRNS | PNG_INFO_sRGB;
5393
tr->tr.args = args;
5394
tr->tr.fn = png_do_set_row;
5395
}
5396
5397
else
5398
tr->tr.fn = png_do_replace_tRNS_lbd;
5399
5400
tc->invalid_info |= PNG_INFO_tRNS | PNG_INFO_sBIT;
5401
tc->sBIT_R = tc->sBIT_G = tc->sBIT_B = tc->sBIT_A =
5402
png_check_byte(png_ptr, tc->bit_depth);
5403
}
5404
5405
else
5406
{
5407
/* Nothing to do; should have been eliminated before! */
5408
tr->tr.fn = NULL;
5409
NOT_REACHED;
5410
}
5411
}
5412
5413
else /* alpha, or maybe gamma, processing required */
5414
{
5415
/* Alpha case, add an appropriate transform; this has to be done
5416
* *after* the RGB-to-gray case so move the transform info there:
5417
*/
5418
png_transform_background *tr_alpha =
5419
png_transform_cast(png_transform_background,
5420
png_add_transform(png_ptr, sizeof (png_transform_background),
5421
png_init_background_alpha, PNG_TR_COMPOSE_ALPHA));
5422
5423
/* Copy the current state into the new png_transform_background: */
5424
tr_alpha->st = tr->st;
5425
tr_alpha->tr.args = tr->tr.args;
5426
5427
/* The rest of the init occurs later; this transform is no longer
5428
* needed.
5429
*/
5430
tr->tr.fn = NULL;
5431
5432
/* Ensure that png_init_background_alpha gets an alpha channel, this
5433
* needs to happen here because otherwise intervening transforms can
5434
* invalidate tRNS.
5435
*/
5436
tc->expand_tRNS = 1U;
5437
if (tr->st.compose_background)
5438
tc->strip_alpha = 0U;
5439
5440
/* And push the expand: */
5441
(void)push_gamma_expand(transform, tc, 1/*need alpha*/);
5442
5443
/* Regardless of whether anything got pushed the following should now
5444
* be true:
5445
*/
5446
affirm((tc->format & PNG_FORMAT_FLAG_ALPHA) != 0 &&
5447
tc->bit_depth >= 8U);
5448
}
5449
}
5450
}
5451
5452
void PNGFAPI
5453
png_set_background_fixed(png_structrp png_ptr,
5454
png_const_color_16p background_color, int background_gamma_code,
5455
int need_expand, png_fixed_point background_gamma)
5456
{
5457
if (png_ptr != NULL)
5458
{
5459
if (background_color != NULL)
5460
{
5461
png_transform_background *tr =
5462
png_transform_cast(png_transform_background,
5463
png_add_transform(png_ptr, sizeof (png_transform_background),
5464
png_init_background, PNG_TR_COMPOSE));
5465
5466
/* This silently overwrites the information if png_set_background is
5467
* called more than once.
5468
*/
5469
tr->st.background = *background_color;
5470
tr->st.need_expand = need_expand != 0;
5471
tr->st.compose_background = 1U; /* png_set_background called */
5472
switch (background_gamma_code)
5473
{
5474
case PNG_BACKGROUND_GAMMA_SCREEN:
5475
case PNG_BACKGROUND_GAMMA_FILE:
5476
tr->st.background_gamma = background_gamma_code;
5477
break;
5478
5479
case PNG_BACKGROUND_GAMMA_UNIQUE:
5480
if (background_gamma >= 16 && background_gamma <= 625000000)
5481
{
5482
tr->st.background_gamma = background_gamma;
5483
break;
5484
}
5485
5486
png_app_error(png_ptr, "gamma value out of range");
5487
/* FALL THROUGH */
5488
default:
5489
png_app_error(png_ptr, "invalid gamma information");
5490
tr->st.background_gamma = (need_expand ?
5491
PNG_BACKGROUND_GAMMA_FILE : PNG_BACKGROUND_GAMMA_SCREEN);
5492
break;
5493
}
5494
}
5495
5496
else
5497
png_app_error(png_ptr, "missing background color");
5498
}
5499
}
5500
5501
# ifdef PNG_FLOATING_POINT_SUPPORTED
5502
void PNGAPI
5503
png_set_background(png_structrp png_ptr,
5504
png_const_color_16p background_color, int background_gamma_code,
5505
int need_expand, double background_gamma)
5506
{
5507
png_set_background_fixed(png_ptr, background_color, background_gamma_code,
5508
need_expand, png_fixed(png_ptr, background_gamma, "png_set_background"));
5509
}
5510
# endif /* FLOATING_POINT */
5511
#endif /* READ_BACKGROUND */
5512
5513
#ifdef PNG_READ_ALPHA_MODE_SUPPORTED
5514
void PNGFAPI
5515
png_set_alpha_mode_fixed(png_structrp png_ptr, int mode,
5516
png_fixed_point output_gamma)
5517
{
5518
if (png_ptr != NULL)
5519
{
5520
/* Check the passed in output_gamma value; it must be valid and it must be
5521
* converted to the reciprocal for use below:
5522
*/
5523
output_gamma = translate_gamma_flags(png_ptr, output_gamma, 1/*screen*/);
5524
5525
if (output_gamma > 0) /* Else an app_error has been signalled. */
5526
{
5527
/* Only set the colorspace gamma if it has not already been set (this
5528
* has the side effect that the gamma in a second call to
5529
* png_set_alpha_mode will be ignored.)
5530
*/
5531
if ((png_ptr->colorspace.flags &
5532
(PNG_COLORSPACE_INVALID | PNG_COLORSPACE_HAVE_GAMMA)) !=
5533
PNG_COLORSPACE_HAVE_GAMMA)
5534
{
5535
/* The default file gamma is the output gamma encoding: */
5536
png_ptr->colorspace.gamma = output_gamma;
5537
if (png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID)
5538
png_ptr->colorspace.flags = PNG_COLORSPACE_HAVE_GAMMA;
5539
else
5540
png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA;
5541
}
5542
5543
/* Always set the output gamma, note that it may be changed to PNG_FP_1
5544
* for the associated alpha support. This means that the last call to
5545
* png_set_gamma[_fixed] or png_set_alpha_mode sets the output gamma,
5546
* which is probably what is expected.
5547
*/
5548
{
5549
png_transform_gamma *tr_gamma = add_gamma_transform(png_ptr,
5550
PNG_TR_GAMMA_ENCODE,
5551
mode == PNG_ALPHA_ASSOCIATED ? PNG_FP_1 : output_gamma, 0U,
5552
1/*force*/);
5553
5554
/* Get a background transform and set the appropriate fields.
5555
*
5556
* png_set_background removes the alpha channel so it effectively
5557
* disbles png_set_alpha_mode however png_set_alpha_mode is still
5558
* useful to set a default gamma value.
5559
*/
5560
png_transform_background *tr =
5561
png_transform_cast(png_transform_background,
5562
png_add_transform(png_ptr, sizeof (png_transform_background),
5563
png_init_background, PNG_TR_COMPOSE));
5564
5565
/* There are really 8 possibilities here, composed of any
5566
* combination of:
5567
*
5568
* premultiply the color channels
5569
* do not encode non-opaque pixels (leave as linear)
5570
* encode the alpha as well as the color channels
5571
*
5572
* The differences disappear if the input/output ('screen') gamma is
5573
* 1.0, because then the encoding is a no-op and there is only the
5574
* choice of premultiplying the color channels or not.
5575
*/
5576
switch (mode)
5577
{
5578
case PNG_ALPHA_PNG: /* default: png standard */
5579
/* No compose, but it may be set by png_set_background! This
5580
* is the only mode that doesn't interfere with what
5581
* png_set_background does.
5582
*/
5583
tr->st.associate_alpha = 0U;
5584
tr_gamma->encode_alpha = tr->st.encode_alpha = 0U;
5585
tr_gamma->optimize_alpha = tr->st.optimize_alpha = 0U;
5586
break;
5587
5588
case PNG_ALPHA_ASSOCIATED: /* color channels premultiplied */
5589
tr->st.associate_alpha = 1U;
5590
tr_gamma->encode_alpha = tr->st.encode_alpha = 0U;
5591
tr_gamma->optimize_alpha = tr->st.optimize_alpha = 0U;
5592
break;
5593
5594
case PNG_ALPHA_OPTIMIZED:
5595
/* associated with opaque pixels having the given gamma and
5596
* non-opaque pixels being linear.
5597
*/
5598
tr->st.associate_alpha = 1U;
5599
tr_gamma->encode_alpha = tr->st.encode_alpha = 0U;
5600
tr_gamma->optimize_alpha = tr->st.optimize_alpha = 1U;
5601
/* output_gamma records the encoding of opaque pixels! */
5602
break;
5603
5604
case PNG_ALPHA_BROKEN:
5605
/* associated+non-linear+alpha encoded */
5606
tr->st.associate_alpha = 1U;
5607
tr_gamma->encode_alpha = tr->st.encode_alpha = 1U;
5608
tr_gamma->optimize_alpha = tr->st.optimize_alpha = 0U;
5609
break;
5610
5611
default:
5612
png_app_error(png_ptr, "invalid alpha mode");
5613
/* A return at this point is safe; if a background transform
5614
* was created the init routine will remove it because
5615
* nothing is set.
5616
*/
5617
break;
5618
} /* alpha mode switch */
5619
} /* add gamma and background transforms */
5620
} /* valid output gamma */
5621
} /* png_ptr != NULL */
5622
}
5623
5624
#ifdef PNG_FLOATING_POINT_SUPPORTED
5625
void PNGAPI
5626
png_set_alpha_mode(png_structrp png_ptr, int mode, double output_gamma)
5627
{
5628
png_set_alpha_mode_fixed(png_ptr, mode, convert_gamma_value(png_ptr,
5629
output_gamma));
5630
}
5631
#endif /* FLOATING_POINT */
5632
#endif /* READ_ALPHA_MODE */
5633
5634
#ifdef PNG_READ_TRANSFORMS_SUPPORTED
5635
typedef struct
5636
{
5637
png_transform tr;
5638
png_transform_control tc;
5639
union
5640
{
5641
png_uint_32 u32[1]; /* ensure alignment */
5642
png_uint_16 u16[1];
5643
png_byte b8[1];
5644
} cache;
5645
} png_transform_cache;
5646
5647
#define png_transform_cache_size(size)\
5648
(offsetof(png_transform_cache, cache)+(size))
5649
#define png_transform_cache_cast(pointer,size)\
5650
png_voidcast(png_transform_cache*,\
5651
png_transform_cast_check(png_ptr, PNG_SRC_LINE, (pointer),\
5652
png_transform_cache_size(size)))
5653
/* This is like png_transform_cast except that 'size' is the size of the
5654
* cache part in the above structure and the type returned is always
5655
* 'png_transform_cache*'.
5656
*/
5657
5658
/* Functions to handle the cache operation. These don't do any initialization;
5659
* that happens below when PNG_TC_INIT_FINAL is being run on the whole list.
5660
* These functions are only implemented for read so the transform control
5661
* source and destination are always aligned.
5662
*
5663
* First some utility functions:
5664
*/
5665
static void
5666
png_transform_control_cp(png_transform_controlp tcDest,
5667
png_const_transform_controlp tcSrc)
5668
{
5669
/* Copy tcSrc over tcDest without overwriting the information specific to the
5670
* row being transformed.
5671
*/
5672
png_structp png_ptr = tcDest->png_ptr;
5673
png_const_voidp sp = tcDest->sp;
5674
png_voidp dp = tcDest->dp;
5675
png_uint_32 width = tcDest->width;
5676
unsigned int init = tcDest->init;
5677
5678
*tcDest = *tcSrc;
5679
5680
tcDest->png_ptr = png_ptr;
5681
tcDest->sp = sp;
5682
tcDest->dp = dp;
5683
tcDest->width = width;
5684
tcDest->init = png_check_bits(tcDest->png_ptr, init, 2);
5685
}
5686
5687
#if !PNG_RELEASE_BUILD
5688
static int
5689
png_transform_control_eq(png_const_transform_controlp tc1,
5690
png_const_transform_controlp tc2)
5691
{
5692
/* Say if *tc1 == *tc2, ignoring differences in uncopied fields and 'cost':
5693
*/
5694
return
5695
# ifdef PNG_READ_GAMMA_SUPPORTED
5696
tc1->gamma == tc2->gamma &&
5697
# endif
5698
tc1->format == tc2->format &&
5699
tc1->range == tc2->range &&
5700
tc1->bit_depth == tc2->bit_depth &&
5701
tc1->caching == tc2->caching &&
5702
tc1->palette == tc2->palette;
5703
/* invalid_info, cost, interchannel and channel_add are only set during
5704
* init, so don't do the compare.
5705
*/
5706
}
5707
#endif /* !RELEASE_BUILD */
5708
5709
/* Now the routines that actually perform the transform. There are two basic
5710
* cases:
5711
*
5712
* 1) A cached transform that does not change the pixel size and where the pixel
5713
* size 8 bits or less. This can be done by a 256-entry single byte lookup
5714
* table, regardless of the bit depth. Two versions of the code exist, one
5715
* which just transforms the row, the other which transforms and records the
5716
* maximum pixel depth.
5717
*
5718
* 2) A cached transform that increases pixel depth. The destination pixel
5719
* depth will always be a multiple of 8 bits, the source pixel will be less
5720
* than or equal to 8 bits and will be in the PNG native (big endian) layout.
5721
*/
5722
#define png_ptr (tc->png_ptr) /* Used in all functions below */
5723
/* (1): single-byte cached transforms: */
5724
static void
5725
do_transform_cache_byte(png_transformp *trIn, png_transform_controlp tc)
5726
{
5727
png_transform_cache *tr = png_transform_cache_cast(*trIn, 256U);
5728
5729
/* Copy the bytes through the 256-byte LUT: */
5730
png_bytep dp = png_voidcast(png_bytep, tc->dp);
5731
png_const_bytep ep = dp + PNG_TC_ROWBYTES(*tc);
5732
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
5733
5734
tc->sp = dp;
5735
5736
do
5737
*dp++ = tr->cache.b8[*sp++];
5738
while (dp < ep);
5739
5740
png_transform_control_cp(tc, &tr->tc);
5741
}
5742
5743
/* (2) A cached transform that increases pixel depth.
5744
*
5745
* There are six output depth possibilites, all a whole number of bytes:
5746
*
5747
* 1 byte, 8 bits: palette or grayscale
5748
* 2 bytes, 16 bits: 16-bit grayscale or 8-bit gray+alpa
5749
* 3 bytes, 24 bits: 8-bit RGB
5750
* 4 bytes, 32 bits: 16-bit gray+alpha or 8-bit RGBA
5751
* 6 bytes, 48 bits: 16-bit RGB
5752
* 8 bytes, 64 bits: 16-bit RGBA
5753
*
5754
* The input must be 1, 2, 4 or 8-bit gray or palette. The first 1-byte case is
5755
* handled for 8-bit gray/palette above, so there are 22 possibilities. The
5756
* function names below are:
5757
*
5758
* do_transform_cache_<input-bits>_<output-bits>
5759
*/
5760
#define transform_cache_size(ipd,opd) ((((1U << (ipd)) * (opd))+7U) >> 3)
5761
static void
5762
do_transform_cache_(png_transformp *trIn, png_transform_controlp tc,
5763
unsigned int ipd, unsigned int opd)
5764
/* This is the implementation for unknown ipd, opd, below it is called with
5765
* fixed values. The purpose of this is to allow the compiler/system builder
5766
* to decide how to optimize for size vs space vs speed. Note that this
5767
* implementation, while it would work for 8 bit ipd, is not used in that
5768
* case.
5769
*/
5770
{
5771
png_transform_cache *tr =
5772
png_transform_cache_cast(*trIn, transform_cache_size(ipd, opd));
5773
5774
png_bytep dp = png_voidcast(png_bytep, tc->dp);
5775
png_const_bytep ep = dp;
5776
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
5777
unsigned int s, shift, mask;
5778
5779
sp += PNG_TC_ROWBYTES(*tc); /* One byte beyond the end */
5780
5781
png_transform_control_cp(tc, &tr->tc);
5782
dp += PNG_TC_ROWBYTES(*tc);
5783
5784
shift = 7U & -(tc->width * ipd);
5785
/* MSB: shift right required to get last pixel */
5786
mask = (1U << ipd) - 1U;
5787
/* Mask to extract a single pixel from the low bits of a byte */
5788
opd >>= 3;
5789
/* Output pixel size in bytes */
5790
s = *--sp;
5791
/* The first byte; the last byte of the input row */
5792
5793
for (;;)
5794
{
5795
png_const_bytep opixel = (((s >> shift) & mask)+1U) * opd + tr->cache.b8;
5796
/* Points to the byte after last byte of the output value */
5797
unsigned int i;
5798
5799
for (i=0; i<opd; ++i)
5800
*--dp = *--opixel;
5801
5802
if (dp <= ep)
5803
break;
5804
5805
shift += ipd; /* To find shift for *previous* pixel */
5806
5807
if (shift == 8U)
5808
s = *--sp, shift = 0U/*right-most pixel*/;
5809
}
5810
5811
debug(dp == ep && shift == 8U-ipd && sp == tc->sp);
5812
tc->sp = ep; /* start of row, safe even if the above fails */
5813
}
5814
5815
#define do_transform_cache(ipd,opd)\
5816
static void \
5817
do_transform_cache_##ipd##_##opd(png_transformp *tr, png_transform_controlp tc)\
5818
{\
5819
do_transform_cache_(tr, tc, ipd, opd);\
5820
}
5821
5822
#define TCLOW(opd)\
5823
do_transform_cache(1,opd)\
5824
do_transform_cache(2,opd)\
5825
do_transform_cache(4,opd)
5826
5827
TCLOW(8)
5828
TCLOW(16)
5829
TCLOW(24)
5830
TCLOW(32)
5831
TCLOW(48)
5832
TCLOW(64)
5833
5834
#undef TCLOW
5835
#undef do_transform_cache
5836
5837
static void
5838
do_transform_cache_8_(png_transformp *trIn, png_transform_controlp tc,
5839
unsigned int opd)
5840
/* This is the 8-bit input implementation. */
5841
{
5842
png_transform_cache *tr =
5843
png_transform_cache_cast(*trIn, transform_cache_size(8, opd));
5844
5845
png_bytep dp = png_voidcast(png_bytep, tc->dp);
5846
png_const_bytep ep = dp;
5847
png_const_bytep sp = png_voidcast(png_const_bytep, tc->sp);
5848
5849
sp += PNG_TC_ROWBYTES(*tc); /* One byte beyond the end */
5850
5851
png_transform_control_cp(tc, &tr->tc);
5852
dp += PNG_TC_ROWBYTES(*tc);
5853
5854
opd >>= 3; /* Output pixel size in bytes */
5855
do
5856
{
5857
png_const_bytep opixel = (*--sp + 1U) * opd + tr->cache.b8;
5858
/* Points to the byte after last byte of the output value */
5859
unsigned int i;
5860
5861
for (i=0; i<opd; ++i)
5862
*--dp = *--opixel;
5863
}
5864
while (dp > ep);
5865
5866
debug(dp == ep && sp == tc->sp);
5867
tc->sp = ep; /* start of row, safe even if the above fails */
5868
}
5869
5870
#define do_transform_cache(opd)\
5871
static void \
5872
do_transform_cache_8_##opd(png_transformp *tr, png_transform_controlp tc)\
5873
{\
5874
do_transform_cache_8_(tr, tc, opd);\
5875
}
5876
5877
/* The 8-bit to 8-bit case uses the byte transform code */
5878
do_transform_cache(16)
5879
do_transform_cache(24)
5880
do_transform_cache(32)
5881
do_transform_cache(48)
5882
do_transform_cache(64)
5883
5884
#undef do_transform_cache
5885
5886
#define do_transform_cache(ipd,opd) do_transform_cache_##ipd##_##opd
5887
5888
#undef png_ptr
5889
5890
typedef struct
5891
{
5892
png_transformp *start;
5893
/* This is a pointer to the pointer to the start of the list being cached,
5894
* i.e. *start is the first transform in the list.
5895
*/
5896
png_transform_control tstart;
5897
/* This is the transform control at the start; i.e. before (*start)->fn is
5898
* called. Note that for palette data it will contain the original
5899
* palette format/bit-depth, not that passed to (*start)->fn which will
5900
* represent the palette.
5901
*/
5902
png_transformp *end;
5903
png_transform_control tend;
5904
/* The same data from the end of the run to be cached, i.e. after the
5905
* function of the transform which *contains* '*end' (end points to
5906
* tr->next).
5907
*/
5908
} png_cache_params, *png_cache_paramsp;
5909
5910
static void
5911
init_caching(png_structp png_ptr, png_transform_controlp tend)
5912
/* Given an already initialized tend turn on caching if appropriate. */
5913
{
5914
/* Handle the colormap case, where a cache is always required: */
5915
if (tend->format & PNG_FORMAT_FLAG_COLORMAP)
5916
{
5917
/* This turns starts the palette caching with the next transform: */
5918
tend->palette = tend->caching = 1U;
5919
# ifdef PNG_READ_tRNS_SUPPORTED
5920
tend->transparent_alpha = png_ptr->transparent_palette;
5921
# else /* !READ_tRNS */
5922
tend->transparent_alpha = 0;
5923
PNG_UNUSED(png_ptr)
5924
# endif /* !READ_tRNS */
5925
tend->format = PNG_FORMAT_FLAG_COLOR;
5926
# ifdef PNG_READ_tRNS_SUPPORTED
5927
if (png_ptr->num_trans > 0 && !(tend->invalid_info & PNG_INFO_tRNS))
5928
{
5929
tend->format |= PNG_FORMAT_FLAG_ALPHA;
5930
}
5931
# endif /* READ_tRNS */
5932
tend->bit_depth = 8U;
5933
}
5934
5935
else if (PNG_TC_PIXEL_DEPTH(*tend) <= 8)
5936
{
5937
/* Cacheable pixel transforms; the pixel is less than 8 bits in size so
5938
* the cache makes sense.
5939
*
5940
* TODO: check the cost estimate and the image size to avoid expensive
5941
* caches of very small images.
5942
*/
5943
tend->caching = 1U;
5944
}
5945
5946
/* TODO: handle handle 8-bit GA/RGB/RGBA */
5947
}
5948
5949
static void
5950
add_cache_transform(png_structp png_ptr, unsigned int order,
5951
png_transform_fn fn, png_cache_paramsp cp,
5952
png_const_bytep cache, unsigned int size)
5953
/* Add a transform from the input format cp->tstart to the output format
5954
* stored in cp->tend.
5955
*/
5956
{
5957
affirm(size <= 2048U); /* 256 8-byte pixels at most */
5958
{
5959
png_transform_cache *tr = png_transform_cache_cast(
5960
png_add_transform(png_ptr, png_transform_cache_size(size), fn, order),
5961
size);
5962
5963
/* This must have replaced the transform in *cp->start: */
5964
affirm(&tr->tr == *cp->start);
5965
5966
/* Fill in the respective members: */
5967
tr->tc = cp->tend;
5968
memcpy(tr->cache.b8, cache, size);
5969
5970
/* Skip this transform, because the calling routine has already executed
5971
* the cache (it could be executed again, just to verify that it works;
5972
* cp->tstart should be correct.)
5973
*/
5974
cp->start = &tr->tr.next;
5975
}
5976
}
5977
5978
static unsigned int
5979
setup_palette_cache(png_structp png_ptr, png_byte cache[8*256])
5980
/* This returns the number of entries in the cache; the width */
5981
{
5982
const unsigned int num_palette = png_ptr->num_palette;
5983
# ifdef PNG_READ_tRNS_SUPPORTED
5984
unsigned int num_trans = png_ptr->num_trans;
5985
# endif /* READ_tRNS */
5986
const png_colorp palette = png_ptr->palette;
5987
png_bytep p;
5988
unsigned int i;
5989
# ifdef PNG_READ_tRNS_SUPPORTED
5990
const png_bytep trans_alpha = png_ptr->trans_alpha;
5991
# endif /* READ_tRNS */
5992
5993
for (i=0, p=cache; i<num_palette; ++i)
5994
{
5995
*p++ = palette[i].red;
5996
*p++ = palette[i].green;
5997
*p++ = palette[i].blue;
5998
# ifdef PNG_READ_tRNS_SUPPORTED
5999
if (num_trans > 0)
6000
{
6001
if (i < num_trans)
6002
*p++ = trans_alpha[i];
6003
6004
else
6005
*p++ = 0xFFU;
6006
}
6007
# endif /* READ_tRNS */
6008
}
6009
6010
return num_palette;
6011
}
6012
6013
static void
6014
png_remove_PLTE_and_tRNS(png_structrp png_ptr)
6015
{
6016
if (png_ptr->palette != NULL)
6017
png_free(png_ptr, png_ptr->palette);
6018
6019
png_ptr->palette = NULL;
6020
png_ptr->num_palette = 0;
6021
6022
# ifdef PNG_READ_tRNS_SUPPORTED
6023
if (png_ptr->trans_alpha != NULL)
6024
png_free(png_ptr, png_ptr->trans_alpha);
6025
6026
png_ptr->trans_alpha = NULL;
6027
png_ptr->num_trans = 0;
6028
# endif /* READ_tRNS */
6029
6030
png_ptr->palette_updated = 1U;
6031
}
6032
6033
static void
6034
update_palette(png_structp png_ptr, png_cache_paramsp cp,
6035
unsigned int max_depth)
6036
{
6037
union
6038
{
6039
png_uint_32 u32[1];
6040
png_uint_16 u16[1]; /* For alignment */
6041
png_byte b8[8*256]; /* For 16-bit RGBA intermediate */
6042
} cache;
6043
6044
/* The caller only calls this function if the initial transform control had
6045
* the palette flag set, implying that the original 'format' was a COLORMAP
6046
* one. Also this can only happen (at present) when starting the transform
6047
* list, so:
6048
*/
6049
affirm((cp->tstart.format & PNG_FORMAT_FLAG_COLORMAP) != 0); /* required */
6050
6051
/* Run the whole of the given list on the palette data. PNG_TC_INIT_FINAL
6052
* has already been run; this is a full run (with init == 0).
6053
*/
6054
{
6055
unsigned int check_depth;
6056
only_deb(png_transform_control orig = cp->tend;)
6057
6058
cp->tend = cp->tstart;
6059
init_caching(png_ptr, &cp->tend);
6060
/* And set up tend to actually work out the palette: */
6061
cp->tend.init = 0U;
6062
cp->tend.width = setup_palette_cache(png_ptr, cache.b8);
6063
cp->tend.sp = cache.b8;
6064
cp->tend.dp = cache.b8;
6065
6066
check_depth =
6067
png_run_this_transform_list_forwards(&cp->tend, cp->start, *cp->end);
6068
6069
/* If we get here these two things must be true or there are been some
6070
* buggy difference of opinion between the INIT code and the actual run:
6071
*/
6072
affirm(check_depth == max_depth && cp->tend.palette);
6073
6074
/* This should match the passed in final format obtained before, this
6075
* debug statement detects discrepancies between the init code and the
6076
* run code:
6077
*/
6078
debug(png_transform_control_eq(&cp->tend, &orig));
6079
6080
/* Also, expect the palette to still be valid: */
6081
debug((cp->tend.invalid_info & PNG_INFO_PLTE) == 0);
6082
}
6083
6084
/* The result must be compatible with a PNG palette with respect to bit
6085
* depth; specifically the expand-16 transform has no effect on palette data.
6086
*
6087
* The colormap setting must not have been re-introduced here either; there
6088
* may be some quantize interactions here, neither can unexpected flags be
6089
* handled; just COLOR and ALPHA.
6090
*/
6091
affirm(cp->tend.bit_depth == 8 &&
6092
(cp->tend.format & PNG_FORMAT_FLAG_COLORMAP) == 0);
6093
6094
/* Remove all the transforms between start(inclusive) and end(exclusive);
6095
* they have been processed. The effect they had on the transform control
6096
* is irrelevant because the caller re-instates the settings from tstart.
6097
*/
6098
{
6099
png_transformp list = *cp->start; /* list to free */
6100
6101
*cp->start = *cp->end; /* part of list not to be freed */
6102
*cp->end = NULL; /* terminate the list to be freed */
6103
cp->end = cp->start; /* else cp->end points to the end of the list! */
6104
6105
png_transform_free(png_ptr, &list);
6106
}
6107
6108
/* Adjust the PNG palette and, if required, the tRNS entries. Note that
6109
* if the transforms stripped the alpha channel from the palette num_trans
6110
* will get set to 0 here.
6111
*
6112
* This is the point where the gamma gets frozen too. The alternative
6113
* design is to pass palette, tRNS and gamma up the transform chain, but
6114
* that doesn't work because the palette change would, apparently, have to
6115
* be repeated on each row. This seems simpler at the cost of a little
6116
* obscurity; the answer to the question, "Where does the palette get
6117
* updated?", is "Here!"
6118
*
6119
* API CHANGE: (fix): previously the init code would silently overwrite
6120
* the palette information shared with png_info, breaking the API for
6121
* png_read_update_info, which doesn't update the info if it isn't called,
6122
* by changing the palette and maybe tRNS when the first row was read!
6123
*
6124
* NOTE: PNG_FORMAT_FLAG_RANGE is lost at this point, even if the palette
6125
* entries were shifted or inverted. This could be fixed, but it would
6126
* complicate the libpng API to expose the information.
6127
*/
6128
/* Write the transformed palette: */
6129
{
6130
png_colorp palette = png_voidcast(png_colorp, png_calloc(png_ptr,
6131
sizeof (png_color[PNG_MAX_PALETTE_LENGTH])));
6132
png_const_bytep p;
6133
const int is_color = (cp->tend.format & PNG_FORMAT_FLAG_COLOR) != 0;
6134
unsigned int i;
6135
# ifdef PNG_READ_tRNS_SUPPORTED
6136
unsigned int num_trans = 0;
6137
const int do_trans = (cp->tend.format & PNG_FORMAT_FLAG_ALPHA) != 0;
6138
png_byte trans_alpha[PNG_MAX_PALETTE_LENGTH];
6139
# endif /* READ_tRNS */
6140
6141
memset(palette, 0xFFU, sizeof (png_color[PNG_MAX_PALETTE_LENGTH]));
6142
png_free(png_ptr, png_ptr->palette);
6143
png_ptr->palette = palette;
6144
6145
for (i=0, p=cache.b8; i<cp->tend.width; ++i)
6146
{
6147
if (is_color)
6148
{
6149
palette[i].red = *p++;
6150
palette[i].green = *p++;
6151
palette[i].blue = *p++;
6152
}
6153
6154
else
6155
palette[i].blue = palette[i].green = palette[i].red = *p++;
6156
6157
# ifdef PNG_READ_tRNS_SUPPORTED
6158
if (do_trans)
6159
{
6160
png_byte a = *p++;
6161
trans_alpha[i] = a;
6162
6163
/* Strip opaque entries from the end: */
6164
if (a < 0xFFU)
6165
num_trans = i+1;
6166
}
6167
# endif /* READ_tRNS */
6168
}
6169
6170
png_ptr->num_palette = png_check_bits(png_ptr, cp->tend.width, 9);
6171
6172
# ifdef PNG_READ_tRNS_SUPPORTED
6173
if (num_trans > 0)
6174
{
6175
png_bytep tRNS = png_voidcast(png_bytep, png_malloc(png_ptr,
6176
PNG_MAX_PALETTE_LENGTH));
6177
6178
memset(tRNS, 0xFFU, PNG_MAX_PALETTE_LENGTH);
6179
6180
if (png_ptr->trans_alpha != NULL)
6181
png_free(png_ptr, png_ptr->trans_alpha);
6182
6183
png_ptr->trans_alpha = tRNS;
6184
6185
memcpy(tRNS, trans_alpha, num_trans);
6186
png_ptr->num_trans = png_check_bits(png_ptr, num_trans, 9);
6187
}
6188
# endif /* READ_tRNS */
6189
}
6190
6191
/* NOTE: the caller sets cp->start to cp->end and cp->tend to cp->tstart,
6192
* this causes processing to continue with the palette format and the
6193
* first unprocessed transform. The reset of the transform control loses the
6194
* gamma information as well, of course, as any information about the palette
6195
* and tRNS changes (such as the RANGE flags).
6196
*
6197
* The following ensures that png_read_update_info knows to update the
6198
* palette in png_info (which is no longer shared).
6199
*/
6200
png_ptr->palette_updated = 1U;
6201
}
6202
6203
/* These structure and the save/restore routines that follow it exist to save
6204
* data from a png_transform_control that is specific to the sample encoding of
6205
* the PNG data, rather than the row format itself.
6206
*/
6207
typedef struct
6208
{
6209
# ifdef PNG_READ_GAMMA_SUPPORTED
6210
png_fixed_point gamma;
6211
# endif
6212
png_byte sBIT_R;
6213
png_byte sBIT_G;
6214
png_byte sBIT_B;
6215
png_byte sBIT_A; /* Signnificant bits in the row channels. */
6216
unsigned int invalid_info; /* PNG_INFO_* for invalidated chunks */
6217
} png_tc_channel_data;
6218
6219
static void
6220
save_cp_channel_data(png_tc_channel_data *save, png_const_transform_controlp tc)
6221
{
6222
# ifdef PNG_READ_GAMMA_SUPPORTED
6223
save->gamma = tc->gamma;
6224
# endif /* READ_GAMMA */
6225
6226
/* The sBIT information and the list of invalidated chunks must also be
6227
* preserved:
6228
*/
6229
save->sBIT_R = tc->sBIT_R;
6230
save->sBIT_G = tc->sBIT_G;
6231
save->sBIT_B = tc->sBIT_B;
6232
save->sBIT_A = tc->sBIT_A;
6233
save->invalid_info = tc->invalid_info;
6234
}
6235
6236
static void
6237
restore_cp_channel_data(png_transform_controlp tc,
6238
const png_tc_channel_data *save)
6239
/* Reverse the above */
6240
{
6241
# ifdef PNG_READ_GAMMA_SUPPORTED
6242
tc->gamma = save->gamma;
6243
# endif /* READ_GAMMA */
6244
6245
tc->sBIT_R = save->sBIT_R;
6246
tc->sBIT_G = save->sBIT_G;
6247
tc->sBIT_B = save->sBIT_B;
6248
tc->sBIT_A = save->sBIT_A;
6249
tc->invalid_info = save->invalid_info;
6250
}
6251
6252
static void
6253
make_cache(png_structp png_ptr, png_cache_paramsp cp, unsigned int max_depth)
6254
{
6255
/* At present the cache is just a byte lookup table. We need the original
6256
* pixel depth to work out how big the working buffer needs to be.
6257
*/
6258
const unsigned int ipd = PNG_TC_PIXEL_DEPTH(cp->tstart);
6259
const unsigned int opd = PNG_TC_PIXEL_DEPTH(cp->tend);
6260
unsigned int order; /* records position of start transform */
6261
unsigned int width; /* width of cache in pixels */
6262
png_tc_channel_data save; /* Record of the final channel info */
6263
union
6264
{
6265
png_uint_32 u32[1];
6266
png_uint_16 u16[1]; /* For alignment */
6267
png_byte b8[8*256]; /* For 16-bit RGBA */
6268
} cache;
6269
6270
debug(cp->tend.init == PNG_TC_INIT_FINAL);
6271
affirm(opd <= 64 && max_depth <= 64); /* or the cache is not big enough */
6272
affirm(ipd == opd || (opd & 0x7U) == 0);
6273
6274
if ((cp->tstart.format & PNG_FORMAT_FLAG_COLORMAP) != 0)
6275
width = setup_palette_cache(png_ptr, cache.b8);
6276
6277
else switch (ipd)
6278
{
6279
/* The input to the cache is the full range of possible pixel values: */
6280
case 1:
6281
/* 2 1-bit pixels, MSB first */
6282
cache.b8[0] = 0x40U;
6283
width = 2;
6284
break;
6285
6286
case 2:
6287
/* 4 2-bit pixels, MSB first */
6288
cache.b8[0] = 0x1BU;
6289
width = 4;
6290
break;
6291
6292
case 4:
6293
/* 16 4-bit pixels, MSB first */
6294
cache.b8[0] = 0x01U;
6295
cache.b8[1] = 0x23U;
6296
cache.b8[2] = 0x45U;
6297
cache.b8[3] = 0x67U;
6298
cache.b8[4] = 0x89U;
6299
cache.b8[5] = 0xABU;
6300
cache.b8[6] = 0xCDU;
6301
cache.b8[7] = 0xEFU;
6302
width = 16;
6303
break;
6304
6305
case 8:
6306
/* 256 8-bit pixels */
6307
{
6308
unsigned int i;
6309
6310
for (i=0; i<256; ++i)
6311
cache.b8[i] = PNG_BYTE(i);
6312
}
6313
width = 256;
6314
break;
6315
6316
default:
6317
impossible("cache input bit depth");
6318
}
6319
6320
/* Reset the transform control to run the transforms on this data, but save
6321
* the channel info because the row processing functions do not always
6322
* write it.
6323
*/
6324
save_cp_channel_data(&save, &cp->tend);
6325
cp->tend = cp->tstart;
6326
init_caching(png_ptr, &cp->tend);
6327
/* And set tend to work out the result of transforming each possible pixel
6328
* value:
6329
*/
6330
cp->tend.init = 0U;
6331
cp->tend.width = width;
6332
cp->tend.sp = cache.b8;
6333
cp->tend.dp = cache.b8;
6334
6335
{
6336
unsigned int check_depth =
6337
png_run_this_transform_list_forwards(&cp->tend, cp->start, *cp->end);
6338
6339
/* This must not change: */
6340
affirm(PNG_TC_PIXEL_DEPTH(cp->tend) == opd && check_depth == max_depth);
6341
}
6342
6343
/* Restore the potentially lost channel data. */
6344
restore_cp_channel_data(&cp->tend, &save);
6345
6346
/* This is all the information required to cache the set of transforms
6347
* between 'start' and 'end'. We take the transformed pixels and make a
6348
* cache transform of them. The cache transform skips the work, transforms
6349
* the row, and sets the tranform_control to (a copy of) cp->tend.
6350
*
6351
* Remove all the transforms between start(inclusive) and end(exclusive);
6352
* they have been processed. The effect they had on the transform control
6353
* is irrelevant because the caller re-instates the settings from tstart.
6354
*/
6355
{
6356
png_transformp list = *cp->start; /* list to free */
6357
6358
*cp->start = *cp->end; /* part of list not to be freed */
6359
*cp->end = NULL; /* terminate the list to be freed */
6360
cp->end = NULL; /* reset below */
6361
6362
order = list->order; /* used below when adding the cache transform */
6363
png_transform_free(png_ptr, &list);
6364
}
6365
6366
/* Make the required cache, as enumerated above there are 22 possibilities,
6367
* this selects between them, fixes up the cache for the 'byte' cases (where
6368
* multiple pixels can be handled byte-by-byte) and selects the correct
6369
* transform function.
6370
*/
6371
if (ipd == opd)
6372
{
6373
/* We already know that ipd is <= 8 bits, so we can expand this case to
6374
* the byte transform. The complexity is that for ipd < 8 bits we only
6375
* have information for individual pixel values and these may be
6376
* pixel-swapped within the byte.
6377
*/
6378
if (ipd < 8)
6379
{
6380
const int lsb = (cp->tend.format & PNG_FORMAT_FLAG_SWAPPED) != 0;
6381
unsigned int ishift, b;
6382
png_byte bcache[256];
6383
6384
switch (ipd)
6385
{
6386
case 1: ishift = 3U; break;
6387
case 2: ishift = 2U; break;
6388
case 4: ishift = 1U; break;
6389
default: impossible("ipd");
6390
}
6391
6392
/* Work out the right answer for each byte of pixels: */
6393
for (b=0U; b<256U; ++b)
6394
{
6395
unsigned int o = 0U; /* output byte */
6396
unsigned int p = 8U; /* right shift to find input pixel */
6397
6398
do
6399
{
6400
unsigned int q = ((1U<<ipd)-1U) & (b >> (p-=ipd));
6401
/* The input pixel. For a palette this value might be outside
6402
* the range of palette indices, in which case simply insert
6403
* '0':
6404
*/
6405
if (q < width)
6406
{
6407
unsigned int r = cache.b8[q >> ishift];
6408
r >>= ((lsb ? q : ~q) & ((1U<<ishift)-1U)) << (3U-ishift);
6409
r &= ((1U<<ipd)-1U);
6410
o |= r << (lsb ? (8U-ipd)-p : p);
6411
}
6412
6413
else
6414
{
6415
UNTESTED
6416
}
6417
}
6418
while (p != 0U);
6419
6420
bcache[b] = png_check_byte(png_ptr, o);
6421
}
6422
6423
/* This is a byte transform, with the optional check-for-invalid-index
6424
* functionality.
6425
*/
6426
add_cache_transform(png_ptr, order, do_transform_cache_byte, cp,
6427
bcache, 256U);
6428
}
6429
6430
else /* ipd == 8 */
6431
add_cache_transform(png_ptr, order, do_transform_cache_byte, cp,
6432
cache.b8, 256U);
6433
}
6434
6435
else
6436
{
6437
/* opd is a whole number of bytes, ipd is 1, 2, 4 or 8 and not equal to
6438
* opd.
6439
*/
6440
png_transform_fn fn;
6441
6442
# define C(ipd,opd) ((ipd) + 8*(opd))
6443
switch (C(ipd,opd))
6444
{
6445
# define CASE(ipd,opd)\
6446
case C(ipd,opd): fn = do_transform_cache(ipd,opd); break
6447
6448
CASE(1,8);
6449
CASE(2,8);
6450
CASE(4,8);
6451
/* No 8,8 */
6452
6453
# define CASES(opd)\
6454
CASE(1,opd);\
6455
CASE(2,opd);\
6456
CASE(4,opd);\
6457
CASE(8,opd)
6458
6459
CASES(16);
6460
CASES(24);
6461
CASES(32);
6462
CASES(48);
6463
CASES(64);
6464
# undef CASES
6465
# undef CASE
6466
6467
default:
6468
impossible("cache bit depths");
6469
}
6470
# undef C
6471
6472
/* In the event that the cache is not the full width implied by ipd zero
6473
* the remaining bytes for security; otherwise they get copied into the
6474
* cache transform and might get used. (Specifically if there is an
6475
* out-of-range palette index they do get used!)
6476
*/
6477
{
6478
unsigned int size = transform_cache_size(ipd, opd);
6479
png_alloc_size_t cachebytes = PNG_TC_ROWBYTES(cp->tend);
6480
6481
affirm(cachebytes <= sizeof cache.b8);
6482
6483
if (cachebytes < size)
6484
memset(cache.b8+cachebytes, 0, size - cachebytes);
6485
6486
add_cache_transform(png_ptr, order, fn, cp, cache.b8, size);
6487
}
6488
}
6489
6490
/* Because a transform was inserted cp->end needs to be set to the new
6491
* pointer to the original end. add_cache_transform sets cp->start to this,
6492
* so:
6493
*/
6494
cp->end = cp->start;
6495
6496
/* This invalidates the palette if that is what was cached because the
6497
* palette and, if present, tRNS chunk did not get updated above.
6498
*/
6499
if (cp->tstart.palette)
6500
png_remove_PLTE_and_tRNS(png_ptr);
6501
}
6502
6503
static void restore_cp(png_cache_paramsp cp)
6504
{
6505
/* A utility to restore cp->tstart by copying it into cp->tend. This is used
6506
* both in the palette case when restoring the transform control for the
6507
* indexed data and in the case where no transforms were cached. It
6508
* preserves the color-channel-specific data from cp->tend because in either
6509
* case it is possible for this data to be modified without preserving any
6510
* transforms, e.g. if only the gamma is changed but no gamma transform is
6511
* retained because the change was not significant.
6512
*/
6513
png_tc_channel_data save;
6514
6515
save_cp_channel_data(&save, &cp->tend);
6516
cp->tend = cp->tstart;
6517
restore_cp_channel_data(&cp->tend, &save);
6518
}
6519
6520
static void
6521
handle_cache(png_structp png_ptr, png_cache_paramsp cp, unsigned int max_depth)
6522
{
6523
/* There is nothing to do if there are no transforms between 'start' and
6524
* 'end':
6525
*/
6526
if (cp->start != cp->end)
6527
{
6528
only_deb(png_transformp tr_check = *cp->end;)
6529
6530
/* libpng doesn't currently implement any pixel size of more than 64 bits
6531
* so:
6532
*/
6533
affirm(max_depth <= 64);
6534
6535
if (cp->tend.palette)
6536
{
6537
/* The transforms being cached apply to the palette, the following
6538
* transforms will apply to the original index data and the transformed
6539
* data must be used to update the palette:
6540
*/
6541
if (cp->tend.init == PNG_TC_INIT_FINAL)
6542
update_palette(png_ptr, cp, max_depth);
6543
6544
cp->start = cp->end;
6545
restore_cp(cp); /* reset to palette data */
6546
}
6547
6548
else
6549
{
6550
/* Continue with the transform control in cp.tend; even if there was
6551
* palette data in cp.tstart it has been expanded.
6552
*/
6553
if (cp->tend.init == PNG_TC_INIT_FINAL)
6554
make_cache(png_ptr, cp, max_depth);
6555
6556
cp->tstart = cp->tend; /* keep current context */
6557
}
6558
6559
debug(tr_check == *cp->end);
6560
}
6561
6562
else /* no transforms cached */
6563
restore_cp(cp); /* removes any palette caching info */
6564
}
6565
6566
#ifdef PNG_READ_tRNS_SUPPORTED
6567
static void
6568
check_tRNS_for_alpha(png_structrp png_ptr)
6569
{
6570
unsigned int num_trans = png_ptr->num_trans;
6571
6572
debug(png_ptr->color_type == PNG_COLOR_TYPE_PALETTE);
6573
6574
while (num_trans > 0)
6575
{
6576
{
6577
const png_byte trans = png_ptr->trans_alpha[--num_trans];
6578
6579
if (trans == 0xFFU)
6580
continue;
6581
6582
if (trans > 0U)
6583
return; /* Palette has at least one entry >0, <0xff */
6584
}
6585
6586
/* There is some point to the tRNS chunk; it has a non-opaque entry, this
6587
* code could truncate it but there is no obvious performance advantage to
6588
* doing this.
6589
*/
6590
while (num_trans > 0)
6591
{
6592
const png_byte trans = png_ptr->trans_alpha[--num_trans];
6593
6594
if (trans > 0U && trans < 0xFFU)
6595
return;
6596
}
6597
6598
/* Here if the above did not find an entry >0 && <0xFFU but did find a
6599
* transparent entry (0u). Record this.
6600
*/
6601
png_ptr->transparent_palette = 1U;
6602
return;
6603
}
6604
6605
/* All entries opaque; remove the tRNS data: */
6606
// TODO: This optimization doesn't handle adding it back if RGBA is requested.
6607
// See PPSSPP issue #14628.
6608
//png_ptr->num_trans = 0U;
6609
}
6610
#endif /* READ_tRNS */
6611
6612
unsigned int /* PRIVATE */
6613
png_read_init_transform_mech(png_structp png_ptr, png_transform_controlp tc)
6614
/* This is called once for each init stage (PNG_TC_INIT_FORMAT and
6615
* PNG_TC_INIT_FINAL) to run the transform list forwards, returning the
6616
* maximum depth required to process the row. It handles caching of the
6617
* transforms and the processing of the palette for color-mapped PNG data.
6618
*/
6619
{
6620
png_transformp *list = &png_ptr->transform_list;
6621
unsigned int max_depth, cache_start_depth;
6622
png_cache_params cp;
6623
6624
/* PNG color-mapped data must be handled here so that the palette is updated
6625
* correctly. png_set_palette_to_rgb causes the palette flag to be removed
6626
* from the transform control but does no other change. png_set_quantize
6627
* causes 8-bit RGB, RGBA or palette data to be converted into palette
6628
* indices, setting the palette flag.
6629
*/
6630
# ifdef PNG_READ_tRNS_SUPPORTED
6631
/* This happens once at the start to find out if the tRNS chunk consisted
6632
* entirely of opaque (255) and/or transparent (0) entries.
6633
*/
6634
if (tc->init == PNG_TC_INIT_FORMAT &&
6635
png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
6636
check_tRNS_for_alpha(png_ptr);
6637
# endif /* READ_tRNS */
6638
cp.end = cp.start = list;
6639
cp.tend = cp.tstart = *tc;
6640
max_depth = cache_start_depth = PNG_TC_PIXEL_DEPTH(cp.tend);
6641
6642
while (*cp.end != NULL)
6643
{
6644
png_transformp tr = *cp.end;
6645
6646
/* The user transform cannot be cached. */
6647
if (tr->order >= PNG_TR_USER)
6648
break;
6649
6650
/* If caching is not on and this transform is after PNG_TR_START_CACHE
6651
* try to turn it on.
6652
*/
6653
if (tr->order > PNG_TR_START_CACHE && !cp.tend.caching)
6654
{
6655
cp.start = cp.end;
6656
cp.tstart = cp.tend;
6657
init_caching(png_ptr, &cp.tend);
6658
6659
if (cp.tend.caching)
6660
{
6661
cache_start_depth = max_depth;
6662
max_depth = PNG_TC_PIXEL_DEPTH(cp.tend);
6663
}
6664
}
6665
6666
/* If the 'palette' flag is set and the next transform has order
6667
* PNG_TR_ENCODING or later cache the results so far and continue with the
6668
* original palette data (cp.tstart).
6669
*/
6670
if (cp.tend.palette && tr->order >= PNG_TR_ENCODING)
6671
{
6672
handle_cache(png_ptr, &cp, max_depth);
6673
6674
/* The cache handling function must maintain cp.end; */
6675
affirm(tr == *cp.end);
6676
max_depth = PNG_TC_PIXEL_DEPTH(cp.tend);
6677
if (max_depth < cache_start_depth)
6678
max_depth = cache_start_depth;
6679
}
6680
6681
/* Now run the transform list entry: */
6682
if (tr->fn != NULL)
6683
{
6684
tr->fn(cp.end, &cp.tend);
6685
tr = *cp.end; /* in case something was inserted */
6686
}
6687
6688
if (tr->fn == NULL) /* delete this transform */
6689
png_remove_transform(png_ptr, cp.end);
6690
6691
else
6692
{
6693
/* Handle the initialization of the maximum pixel depth. */
6694
unsigned int tc_depth = PNG_TC_PIXEL_DEPTH(cp.tend);
6695
6696
if (tc_depth > max_depth)
6697
max_depth = tc_depth;
6698
6699
/* Advance to the next transform. */
6700
cp.end = &tr->next;
6701
}
6702
}
6703
6704
/* At the end if still caching record the cache information (this is common;
6705
* this is generally the case for an expanded palette.)
6706
*/
6707
if (cp.tend.caching)
6708
{
6709
png_transformp tr = *cp.end;
6710
handle_cache(png_ptr, &cp, max_depth);
6711
affirm(tr == *cp.end);
6712
max_depth = PNG_TC_PIXEL_DEPTH(cp.tend);
6713
if (max_depth < cache_start_depth)
6714
max_depth = cache_start_depth;
6715
}
6716
6717
/* At the end run the init on the user transform: */
6718
if (*cp.end != NULL)
6719
{
6720
png_transformp tr = *cp.end;
6721
affirm(tr->order == PNG_TR_USER);
6722
if (tr->fn != NULL)
6723
tr->fn(cp.end, &cp.tend);
6724
/* This cannot insert anything, so: */
6725
affirm(tr == *cp.end && tr->next == NULL);
6726
6727
if (tr->fn == NULL) /* delete this transform */
6728
png_remove_transform(png_ptr, cp.end);
6729
6730
else
6731
{
6732
unsigned int tc_depth = PNG_TC_PIXEL_DEPTH(cp.tend);
6733
6734
if (tc_depth > max_depth)
6735
max_depth = tc_depth;
6736
}
6737
}
6738
6739
/* And write the input transform control: */
6740
*tc = cp.tend;
6741
6742
return max_depth;
6743
}
6744
6745
/* Modify the info structure to reflect the transformations. The
6746
* info should be updated so a PNG file could be written with it,
6747
* assuming the transformations result in valid PNG data.
6748
*/
6749
void /* PRIVATE */
6750
png_read_transform_info(png_structrp png_ptr, png_inforp info_ptr)
6751
{
6752
png_debug(1, "in png_read_transform_info");
6753
6754
/* WARNING: this is very basic at present. It just updates the format
6755
* information. It should update the palette (and will eventually) as well
6756
* as invalidating chunks that the transforms break.
6757
*/
6758
# ifdef PNG_TRANSFORM_MECH_SUPPORTED
6759
info_ptr->format = png_ptr->row_format;
6760
info_ptr->bit_depth = png_ptr->row_bit_depth;
6761
# ifdef PNG_READ_GAMMA_SUPPORTED
6762
/* If an info struct is used with a different png_ptr in a call to
6763
* png_set_gAMA then the png_struct information won't be updated, this
6764
* doesn't matter on write, but don't zap the value in the info on read
6765
* unless it is known:
6766
*
6767
* TODO: review this whole mess.
6768
*/
6769
if (png_ptr->row_gamma > 0)
6770
info_ptr->colorspace.gamma = png_ptr->row_gamma;
6771
# endif
6772
6773
/* Invalidate chunks marked as invalid: */
6774
# ifdef PNG_READ_TRANSFORMS_SUPPORTED
6775
info_ptr->valid &= ~png_ptr->invalid_info;
6776
6777
/* If the palette or tRNS chunk was changed copy them over to the info
6778
* structure; this may actually re-validate the PLTE or tRNS chunks,
6779
* but only if png_ptr has a new version, otherwise the invalid_info
6780
* settings from above can still invalidate the chunk.
6781
*/
6782
if (png_ptr->palette_updated)
6783
{
6784
if (png_ptr->num_palette > 0)
6785
png_set_PLTE(png_ptr, info_ptr, png_ptr->palette,
6786
png_ptr->num_palette);
6787
6788
else
6789
{
6790
png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
6791
info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_PLTE);
6792
}
6793
6794
# ifdef PNG_READ_tRNS
6795
/* If the output format is not a palette format the tRNS
6796
* information was a single color which is now invalid
6797
* (probably), otherwise the array of tRNS values must be
6798
* updated.
6799
*/
6800
if ((info_ptr->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
6801
{
6802
if (png_ptr->num_trans > 0)
6803
png_set_tRNS(png_ptr, info_ptr, png_ptr->trans_alpha,
6804
png_ptr->num_trans, NULL/*trans color*/);
6805
6806
else
6807
{
6808
png_free_data(png_ptr, info_ptr, PNG_FREE_tRNS, 0);
6809
info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_tRNS);
6810
}
6811
}
6812
6813
else
6814
info_ptr->valid &= PNG_BIC_MASK(PNG_INFO_tRNS);
6815
# endif /* READ_tRNS */
6816
}
6817
# endif /* READ_TRANSFORMS */
6818
# else /* !TRANSFORM_MECH */
6819
PNG_UNUSED(png_ptr)
6820
PNG_UNUSED(info_ptr)
6821
# endif /* !TRANSFORM_MECH */
6822
}
6823
#endif /* READ_TRANSFORMS */
6824
6825