-
Notifications
You must be signed in to change notification settings - Fork 1
/
png22pnm.c
executable file
·1323 lines (1197 loc) · 38.8 KB
/
png22pnm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define DUMMY \
set -ex; \
gcc -O2 -ansi -pedantic -W -Wall -Wshadow -Winline -Wstrict-prototypes \
png22pnm.c -o png22pnm -lpng; \
exit 0
/*
** png22pnm.c
** edited by [email protected] at Tue Dec 10 16:33:53 CET 2002
**
** png22pnm.c has been tested with libpng 1.2 and 1.5. It should work with
** libpng 1.2 or later. Compatiblity with libpng versions earlier than 1.2 is
** not a goal.
**
** based on pngtopnm.c -
** read a Portable Network Graphics file and produce a portable anymap
**
** Copyright (C) 1995,1998 by Alexander Lehmann <[email protected]>
** and Willem van Schaik <[email protected]>
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
**
** modeled after giftopnm by David Koblas and
** with lots of bits pasted from libpng.txt by Guy Eric Schalnat
*/
/*
BJH 20000408: rename PPM_MAXMAXVAL to PPM_OVERALLMAXVAL
BJH 20000303: fix include statement so dependencies work out right.
*/
/* GRR 19991203: moved VERSION to new version.h header file */
/* GRR 19990713: fixed redundant freeing of png_ptr and info_ptr in setjmp()
* blocks and added "pm_close(ifp)" in each. */
/* GRR 19990317: declared "clobberable" automatic variables in convertpng()
* static to fix Solaris/gcc stack-corruption bug. Also installed custom
* error-handler to avoid jmp_buf size-related problems (i.e., jmp_buf
* compiled with one size in libpng and another size here). */
#include <math.h>
#include <png.h> /* includes zlib.h and setjmp.h */
#if 0
#define VERSION "p2.37.4 (5 December 1999) +netpbm"
#else
#define VERSION "0.11"
#endif
/**** pts ****/
#define PBMPLUS_RAWBITS 1
#define PGM_OVERALLMAXVAL 65535
#define PPM_OVERALLMAXVAL PGM_OVERALLMAXVAL
/* #include "pnm.h" */
typedef struct _jmpbuf_wrapper {
jmp_buf jmpbuf;
} jmpbuf_wrapper;
/* GRR 19991205: this is used as a test for pre-1999 versions of netpbm and
* pbmplus vs. 1999 or later (in which pm_close was split into two)
*/
#ifdef PBMPLUS_RAWBITS
# define pm_closer pm_close
# define pm_closew pm_close
#endif
#ifndef TRUE
# define TRUE 1
#endif
#ifndef FALSE
# define FALSE 0
#endif
#ifndef NONE
# define NONE 0
#endif
/**** pts ****/
#include <stdio.h> /* fprintf() */
#include <string.h> /* strcmp() */
#include <stdlib.h> /* exit() */
#include <assert.h>
/* #include "pnm.h" */
#if (defined(__STDC__) && !defined(NO_PROTO)) || defined(__cplusplus)
# define _(args) args
# define OF(args) args
# define ___(arg2s,arg1s,argafter) arg2s
#else
# define _(args) ()
# define OF(args) ()
# define ___(arg2s,arg1s,argafter) arg1s argafter
#endif
#define u_char unsigned char
typedef unsigned dimen_t;
/* typedef unsigned char xel[4]; */ /* "RGBA" */
typedef unsigned pixval;
#define PBM_TYPE 1
#define PGM_TYPE 2
#define PPM_TYPE 3
#define pnm_init(_a,_b)
#define PMM(immed_str) stderr, "notice: " immed_str "\n"
#define pm_message printf
#define PME(immed_str) stderr, "error: " immed_str "\n"
#define pm_error printf /* !! exit */
#define pm_errexit() exit(3)
#define pm_close(file) fflush(file)
#define pm_keymatch(stra, strb, _x) (0==strcmp((stra),(strb)))
#define PPM_MAXMAXVAL 1023
typedef unsigned long pixel;
#define PPM_GETR(p) (((p) & 0x3ff00000) >> 20)
#define PPM_GETG(p) (((p) & 0xffc00) >> 10)
#define PPM_GETB(p) ((p) & 0x3ff)
/************* added definitions *****************/
#define PPM_PUTR(p, red) ((p) |= (((red) & 0x3ff) << 20))
#define PPM_PUTG(p, grn) ((p) |= (((grn) & 0x3ff) << 10))
#define PPM_PUTB(p, blu) ((p) |= ( (blu) & 0x3ff))
/**************************************************/
#define PPM_ASSIGN(p,red,grn,blu) (p) = ((pixel) (red) << 20) | ((pixel) (grn) << 10) | (pixel) (blu)
#define PPM_EQUAL(p,q) ((p) == (q))
static void* pm_allocrow (int const cols, int const size);
#define pnm_allocrow( cols ) ((xel*) pm_allocrow( cols, sizeof(xel) ))
#define PNM_ASSIGN1(x,v) PPM_ASSIGN(x,0,0,v)
#define PNM_GET1(x) PPM_GETB(x)
typedef pixel xel;
typedef pixval xelval;
static pixel ppm_parsecolor _(( char* colorname, pixval maxval ));
/* static void pnm_writepnminit _(( FILE* file, int cols, int rows, xelval maxval, int format, int forceplain )); */
#define pnm_freerow( xelrow ) pm_freerow( (char*) xelrow )
#define pm_freerow(x) free(x)
/* static void pnm_writepnmrow _(( FILE* file, xel* xelrow, int cols, xelval maxval, int format, int forceplain )); */
static FILE* pm_openr (const char* const name);
static FILE* pm_openw (const char* const name);
static void pm_usage (const char usage[], FILE *f) {
fprintf(f, /*"png22pnm "VERSION"\n"*/"usage: %s\n", usage);
exit(1);
}
static void* pm_allocrow(int const cols, int const size) {
register char* itrow;
itrow = (char*) malloc( cols * size );
if ( itrow == (char*) 0 ) {
fprintf(stderr, "out of memory allocating a row\n" );
exit(1);
}
return itrow;
}
static FILE*
pm_openr(const char * const name) {
FILE* f;
if (strcmp(name, "-") == 0)
f = stdin;
else {
#ifndef VMS
f = fopen(name, "rb");
#else
f = fopen (name, "r", "ctx=stm");
#endif
if (f == NULL) {
fprintf(stderr,"not found: %s\n", name);
exit(1);
}
}
return f;
}
static FILE*
pm_openw(const char * const name) {
FILE* f;
if (strcmp(name, "-") == 0)
f = stdout;
else {
#ifndef VMS
f = fopen(name, "wb");
#else
f = fopen (name, "w", "mbc=32", "mbf=2"); /* set buffer factors */
#endif
if (f == NULL) {
fprintf(stderr,"not found: %s\n", name);
exit(1);
}
}
return f;
}
static long
rgbnorm(const long rgb, const long lmaxval, const int n,
const char * const colorname) {
/*----------------------------------------------------------------------------
Normalize the color (r, g, or b) value 'rgb', which was specified with
'n' digits, to a maxval of 'lmaxval'. If the number of digits isn't
valid, issue an error message and identify the complete color
color specification in error as 'colorname'.
For example, if the user says 0ff/000/000 and the maxval is 100,
then rgb is 0xff, n is 3, and our result is
0xff / (16**3-1) * 100 = 6.
-----------------------------------------------------------------------------*/
switch (n) {
case 1:
return (long)((double) rgb * lmaxval / 15 + 0.5);
case 2:
return (long) ((double) rgb * lmaxval / 255 + 0.5);
case 3:
return (long) ((double) rgb * lmaxval / 4095 + 0.5);
case 4:
return (long) ((double) rgb * lmaxval / 65535L + 0.5);
default:
{ pm_error( "invalid color specifier - \"%s\"", colorname ); exit(1); }
}
return 0;
}
static pixel
ppm_parsecolor( char* colorname, pixval maxval )
{
int hexit[256], i;
pixel p;
long lmaxval, r=0, g=0, b=0;
char* inval = "invalid color specifier - \"%s\"";
for ( i = 0; i < 256; ++i )
hexit[i] = 1234567890;
hexit['0'] = 0;
hexit['1'] = 1;
hexit['2'] = 2;
hexit['3'] = 3;
hexit['4'] = 4;
hexit['5'] = 5;
hexit['6'] = 6;
hexit['7'] = 7;
hexit['8'] = 8;
hexit['9'] = 9;
hexit['a'] = hexit['A'] = 10;
hexit['b'] = hexit['B'] = 11;
hexit['c'] = hexit['C'] = 12;
hexit['d'] = hexit['D'] = 13;
hexit['e'] = hexit['E'] = 14;
hexit['f'] = hexit['F'] = 15;
lmaxval = maxval;
if ( strncmp( colorname, "rgb:", 4 ) == 0 )
{
/* It's a new-X11-style hexadecimal rgb specifier. */
char* cp;
cp = colorname + 4;
r = g = b = 0;
for ( i = 0; *cp != '/'; ++i, ++cp )
r = r * 16 + hexit[(int)*cp];
r = rgbnorm( r, lmaxval, i, colorname );
for ( i = 0, ++cp; *cp != '/'; ++i, ++cp )
g = g * 16 + hexit[(int)*cp];
g = rgbnorm( g, lmaxval, i, colorname );
for ( i = 0, ++cp; *cp != '\0'; ++i, ++cp )
b = b * 16 + hexit[(int)*cp];
b = rgbnorm( b, lmaxval, i, colorname );
if ( r < 0 || r > lmaxval || g < 0 || g > lmaxval
|| b < 0 || b > lmaxval )
{ pm_error( inval, colorname ); exit(1); }
}
else if ( strncmp( colorname, "rgbi:", 5 ) == 0 )
{
/* It's a new-X11-style decimal/float rgb specifier. */
float fr, fg, fb;
if ( sscanf( colorname, "rgbi:%f/%f/%f", &fr, &fg, &fb ) != 3 )
{ pm_error( inval, colorname ); exit(1); }
if ( fr < 0.0 || fr > 1.0 || fg < 0.0 || fg > 1.0
|| fb < 0.0 || fb > 1.0 )
{ pm_error( "invalid color specifier - \"%s\" - "
"values must be between 0.0 and 1.0", colorname ); exit(1); }
r = fr * lmaxval;
g = fg * lmaxval;
b = fb * lmaxval;
}
else if ( colorname[0] == '#' )
{
/* It's an old-X11-style hexadecimal rgb specifier. */
switch ( strlen( colorname ) - 1 /* (Number of hex digits) */ )
{
case 3:
r = hexit[(int)colorname[1]];
g = hexit[(int)colorname[2]];
b = hexit[(int)colorname[3]];
r = rgbnorm( r, lmaxval, 1, colorname );
g = rgbnorm( g, lmaxval, 1, colorname );
b = rgbnorm( b, lmaxval, 1, colorname );
break;
case 6:
r = ( hexit[(int)colorname[1]] << 4 ) + hexit[(int)colorname[2]];
g = ( hexit[(int)colorname[3]] << 4 ) + hexit[(int)colorname[4]];
b = ( hexit[(int)colorname[5]] << 4 ) + hexit[(int)colorname[6]];
r = rgbnorm( r, lmaxval, 2, colorname );
g = rgbnorm( g, lmaxval, 2, colorname );
b = rgbnorm( b, lmaxval, 2, colorname );
break;
case 9:
r = ( hexit[(int)colorname[1]] << 8 ) +
( hexit[(int)colorname[2]] << 4 ) +
hexit[(int)colorname[3]];
g = ( hexit[(int)colorname[4]] << 8 ) +
( hexit[(int)colorname[5]] << 4 ) +
hexit[(int)colorname[6]];
b = ( hexit[(int)colorname[7]] << 8 ) +
( hexit[(int)colorname[8]] << 4 ) +
hexit[(int)colorname[9]];
r = rgbnorm( r, lmaxval, 3, colorname );
g = rgbnorm( g, lmaxval, 3, colorname );
b = rgbnorm( b, lmaxval, 3, colorname );
break;
case 12:
r = ( hexit[(int)colorname[1]] << 12 ) +
( hexit[(int)colorname[2]] << 8 ) +
( hexit[(int)colorname[3]] << 4 ) + hexit[(int)colorname[4]];
g = ( hexit[(int)colorname[5]] << 12 ) +
( hexit[(int)colorname[6]] << 8 ) +
( hexit[(int)colorname[7]] << 4 ) + hexit[(int)colorname[8]];
b = ( hexit[(int)colorname[9]] << 12 ) +
( hexit[(int)colorname[10]] << 8 ) +
( hexit[(int)colorname[11]] << 4 ) + hexit[(int)colorname[12]];
r = rgbnorm( r, lmaxval, 4, colorname );
g = rgbnorm( g, lmaxval, 4, colorname );
b = rgbnorm( b, lmaxval, 4, colorname );
break;
default:
{ pm_error( inval, colorname ); exit(1); }
}
if ( r < 0 || r > lmaxval || g < 0 || g > lmaxval
|| b < 0 || b > lmaxval )
{ pm_error( inval, colorname ); exit(1); }
}
else if ( ( colorname[0] >= '0' && colorname[0] <= '9' ) ||
colorname[0] == '.' )
{
/* It's an old-style decimal/float rgb specifier. */
float fr, fg, fb;
if ( sscanf( colorname, "%f,%f,%f", &fr, &fg, &fb ) != 3 )
{ pm_error( inval, colorname ); exit(1); }
if ( fr < 0.0 || fr > 1.0 || fg < 0.0 || fg > 1.0
|| fb < 0.0 || fb > 1.0 )
{ pm_error( "invalid color specifier - \"%s\" - "
"values must be between 0.0 and 1.0", colorname ); exit(1); }
r = fr * lmaxval;
g = fg * lmaxval;
b = fb * lmaxval;
}
else
{
/* Must be a name from the X-style rgb file. */
{ pm_error( "unknown color - \"%s\"", colorname ); exit(1); }
}
PPM_ASSIGN( p, r, g, b );
return p;
}
/* ----- */
/* function prototypes */
#ifdef __STDC__
static png_uint_16 _get_png_val (png_byte **pp, int bit_depth);
static void store_pixel (xel *pix, png_uint_16 r, png_uint_16 g, png_uint_16 b, png_uint_16 a);
static int iscolor (png_color c);
static void save_text (png_structp png_ptr, png_info *info_ptr, FILE *tfp);
static void show_time (png_structp png_ptr, png_info *info_ptr);
static void pngtopnm_error_handler (png_structp png_ptr, png_const_charp msg);
static void convertpng (FILE *ifp, FILE *tfp);
int main (int argc, char *argv[]);
#endif
enum alpha_handling
{none, alpha_only, mix_only, none_and_alpha};
static png_uint_16 maxval, maxmaxval;
static png_uint_16 bgr, bgg, bgb; /* background colors */
static int verbose = FALSE;
static enum alpha_handling alpha = none;
static int do_background = -1;
static char *backstring;
static float displaygamma = -1.0; /* display gamma */
static float totalgamma = -1.0;
static int text = FALSE;
static char *text_file;
static int mtime = FALSE;
static jmpbuf_wrapper pngtopnm_jmpbuf_struct;
#define get_png_val(p) _get_png_val (&(p), bit_depth)
#ifdef __STDC__
static png_uint_16 _get_png_val (png_byte **pp, int bit_depth)
#else
static png_uint_16 _get_png_val (pp, bit_depth)
png_byte **pp;
int bit_depth;
#endif
{
png_uint_16 c = 0;
if (bit_depth == 16) {
c = (*((*pp)++)) << 8;
}
c |= (*((*pp)++));
if (maxval > maxmaxval)
c /= ((maxval + 1) / (maxmaxval + 1));
return c;
}
#ifdef __STDC__
static void store_pixel (xel *pix, png_uint_16 r, png_uint_16 g, png_uint_16 b, png_uint_16 a)
#else
static void store_pixel (pix, r, g, b, a)
xel *pix;
png_uint_16 r, g, b, a;
#endif
{
if (alpha == alpha_only) {
PNM_ASSIGN1 (*pix, a);
} else {
if (((alpha == mix_only) /*|| (alpha == mix_and_alpha)*/) && (a != maxval)) {
r = r * (double)a / maxval + ((1.0 - (double)a / maxval) * bgr);
g = g * (double)a / maxval + ((1.0 - (double)a / maxval) * bgg);
b = b * (double)a / maxval + ((1.0 - (double)a / maxval) * bgb);
}
PPM_ASSIGN (*pix, r, g, b);
}
}
#ifdef __STDC__
static png_uint_16 gamma_correct (png_uint_16 v, float g)
#else
static png_uint_16 gamma_correct (v, g)
png_uint_16 v;
float g;
#endif
{
if (g != -1.0)
return (png_uint_16) (pow ((double) v / maxval,
(1.0 / g)) * maxval + 0.5);
else
return v;
}
#ifdef __STDC__
static int iscolor (png_color c)
#else
static int iscolor (c)
png_color c;
#endif
{
return c.red != c.green || c.green != c.blue;
}
#ifdef __STDC__
static void save_text (png_structp png_ptr, png_info *info_ptr, FILE *tfp)
#else
static void save_text (png_ptr, info_ptr, tfp)
png_structp png_ptr;
png_info *info_ptr;
FILE *tfp;
#endif
{
int i, j, k;
png_textp text;
int num_text;
png_get_text(png_ptr, info_ptr, &text, &num_text);
for (i = 0 ; i < num_text ; i++) {
j = 0;
while (text[i].key[j] != '\0' && text[i].key[j] != ' ')
j++;
if (text[i].key[j] != ' ') {
fprintf (tfp, "%s", text[i].key);
for (j = strlen (text[i].key) ; j < 15 ; j++)
putc (' ', tfp);
} else {
fprintf (tfp, "\"%s\"", text[i].key);
for (j = strlen (text[i].key) ; j < 13 ; j++)
putc (' ', tfp);
}
putc (' ', tfp); /* at least one space between key and text */
for (j = 0 ; j+0U < text[i].text_length ; j++) {
putc (text[i].text[j], tfp);
if (text[i].text[j] == '\n')
for (k = 0 ; k < 16 ; k++)
putc ((int)' ', tfp);
}
putc ((int)'\n', tfp);
}
}
#ifdef __STDC__
static void show_time (png_structp png_ptr, png_info *info_ptr)
#else
static void show_time (png_ptr, info_ptr)
png_structp png_ptr;
png_info *info_ptr;
#endif
{
static char *month[] =
{"", "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
png_timep mod_time;
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tIME)) {
png_get_tIME(png_ptr, info_ptr, &mod_time);
pm_message ("modification time: %02d %s %d %02d:%02d:%02d",
mod_time->day, month[mod_time->month],
mod_time->year, mod_time->hour,
mod_time->minute, mod_time->second);
}
}
#ifdef __STDC__
static void pngtopnm_error_handler (png_structp png_ptr, png_const_charp msg)
#else
static void pngtopnm_error_handler (png_ptr, msg)
png_structp png_ptr;
png_const_charp msg;
#endif
{
jmpbuf_wrapper *jmpbuf_ptr;
/* this function, aside from the extra step of retrieving the "error
* pointer" (below) and the fact that it exists within the application
* rather than within libpng, is essentially identical to libpng's
* default error handler. The second point is critical: since both
* setjmp() and longjmp() are called from the same code, they are
* guaranteed to have compatible notions of how big a jmp_buf is,
* regardless of whether _BSD_SOURCE or anything else has (or has not)
* been defined. */
fprintf(stderr, "pnmtopng: fatal libpng error: %s\n", msg);
fflush(stderr);
jmpbuf_ptr = png_get_error_ptr(png_ptr);
if (jmpbuf_ptr == NULL) { /* we are completely hosed now */
fprintf(stderr,
"pnmtopng: EXTREMELY fatal error: jmpbuf unrecoverable; terminating.\n");
fflush(stderr);
exit(99);
}
longjmp(jmpbuf_ptr->jmpbuf, 1);
}
#define SIG_CHECK_SIZE 4
/* If __MINGW32__ is defined, then _WIN32 is also defined. */
#if defined(_WIN32) || defined(__CYGWIN__)
#define DO_WIN 1
#else
#undef DO_WIN
#endif
#if DO_WIN
#undef __STRICT_ANSI__
#include <fcntl.h>
#define __STRICT_ANSI__ 1
extern int setmode(int, int);
extern FILE *fdopen(int, const char*);
#endif
#ifdef __STDC__
static void convertpng (FILE *ifp, FILE *tfp)
#else
static void convertpng (ifp, tfp)
FILE *ifp;
FILE *tfp;
#endif
{
unsigned char sig_buf [SIG_CHECK_SIZE];
png_struct *png_ptr;
png_info *info_ptr;
pixel *row;
png_byte **png_image;
png_byte *png_pixel;
png_uint_32 width;
png_uint_32 height;
pixel *pnm_pixel;
int bit_depth;
png_byte color_type;
png_color_16p background;
double gamma;
png_bytep trans_alpha;
int num_trans;
png_color_16p trans_color;
png_color_8p sig_bit;
int num_palette;
png_colorp palette;
png_uint_32 x_pixels_per_unit, y_pixels_per_unit;
int phys_unit_type;
int has_phys;
int x, y;
int linesize;
png_uint_16 c, c2, c3, a;
int pnm_type;
int i;
int trans_mix;
pixel backcolor;
char gamma_string[80];
/* these variables are declared static because gcc wasn't kidding
* about "variable XXX might be clobbered by `longjmp' or `vfork'"
* (stack corruption observed on Solaris 2.6 with gcc 2.8.1, even
* in the absence of any other error condition) */
static char *type_string;
static char *alpha_string;
#if DO_WIN
FILE *so; int sofd;
setmode(1, O_BINARY);
if (0>(sofd=dup(1))) abort(); /* BUGFIX at Tue Mar 18 17:03:42 CET 2003 */
setmode(sofd, O_BINARY);
if (NULL==(so=fdopen(sofd, "wb"))) abort(); /* binary stdout */
#else
FILE *so=stdout;
#endif
type_string = alpha_string = "";
if (fread (sig_buf, 1, SIG_CHECK_SIZE, ifp) != SIG_CHECK_SIZE) {
pm_closer (ifp);
{ pm_error ("input file empty or too short"); exit(1); }
}
if (png_sig_cmp (sig_buf, (png_size_t) 0, (png_size_t) SIG_CHECK_SIZE) != 0) {
pm_closer (ifp);
{ pm_error ("input file not a PNG file"); exit(1); }
}
png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,
&pngtopnm_jmpbuf_struct, pngtopnm_error_handler, NULL);
if (png_ptr == NULL) {
pm_closer (ifp);
{ pm_error ("cannot allocate LIBPNG structure"); exit(1); }
}
info_ptr = png_create_info_struct (png_ptr);
if (info_ptr == NULL) {
png_destroy_read_struct (&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
pm_closer (ifp);
{ pm_error ("cannot allocate LIBPNG structures"); exit(1); }
}
if (setjmp (pngtopnm_jmpbuf_struct.jmpbuf)) {
png_destroy_read_struct (&png_ptr, &info_ptr, (png_infopp)NULL);
pm_closer (ifp);
{ pm_error ("setjmp returns error condition"); exit(1); }
}
png_init_io (png_ptr, ifp);
png_set_sig_bytes (png_ptr, SIG_CHECK_SIZE);
png_read_info (png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_bKGD)) {
png_get_bKGD(png_ptr, info_ptr, &background);
} else {
background = NULL;
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA)) {
png_get_gAMA(png_ptr, info_ptr, &gamma);
} else {
gamma = -1;
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans, &trans_color);
} else {
trans_alpha = NULL;
num_trans = 0;
trans_color = NULL;
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE)) {
png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
} else {
palette = NULL;
num_palette = 0;
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT)) {
png_get_sBIT(png_ptr, info_ptr, &sig_bit);
} else {
sig_bit = NULL;
}
if (0 != (has_phys = png_get_valid(png_ptr, info_ptr, PNG_INFO_pHYs))) {
png_get_pHYs(png_ptr, info_ptr, &x_pixels_per_unit, &y_pixels_per_unit,
&phys_unit_type);
}
if (verbose) {
switch (color_type) {
case PNG_COLOR_TYPE_GRAY:
type_string = "gray";
alpha_string = "";
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
type_string = "gray";
alpha_string = "+alpha";
break;
case PNG_COLOR_TYPE_PALETTE:
type_string = "palette";
alpha_string = "";
break;
case PNG_COLOR_TYPE_RGB:
type_string = "truecolor";
alpha_string = "";
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
type_string = "truecolor";
alpha_string = "+alpha";
break;
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
alpha_string = "+transparency";
}
if (gamma >= 0) {
sprintf (gamma_string, ", image gamma = %4.2f", gamma);
} else {
strcpy (gamma_string, "");
}
if (verbose) {
pm_message ("reading a %ldw x %ldh image, %d bit%s %s%s%s%s",
width + 0L, height + 0L,
bit_depth, bit_depth > 1 ? "s" : "",
type_string, alpha_string, gamma_string,
png_get_interlace_type(png_ptr, info_ptr) ?
", Adam7 interlaced" : "");
if (background != NULL) {
pm_message ("background {index, gray, red, green, blue} = "
"{%d, %d, %d, %d, %d}",
background->index,
background->gray,
background->red,
background->green,
background->blue);
}
}
}
png_image = (png_byte **)malloc (height * sizeof (png_byte*));
if (png_image == NULL) {
png_destroy_read_struct (&png_ptr, &info_ptr, (png_infopp)NULL);
pm_closer (ifp);
{ pm_error ("couldn't allocate space for image"); exit(1); }
}
if (bit_depth == 16)
linesize = 2 * width;
else
linesize = width;
if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
linesize *= 2;
else
if (color_type == PNG_COLOR_TYPE_RGB)
linesize *= 3;
else
if (color_type == PNG_COLOR_TYPE_RGB_ALPHA)
linesize *= 4;
for (y = 0 ; y+0U < height ; y++) {
png_image[y] = malloc (linesize);
if (png_image[y] == NULL) {
for (x = 0 ; x < y ; x++)
free (png_image[x]);
free (png_image);
png_destroy_read_struct (&png_ptr, &info_ptr, (png_infopp)NULL);
pm_closer (ifp);
{ pm_error ("couldn't allocate space for image"); exit(1); }
}
}
if (bit_depth < 8)
png_set_packing (png_ptr);
if (color_type == PNG_COLOR_TYPE_PALETTE) {
maxval = 255;
} else {
maxval = (1l << bit_depth) - 1;
}
/* gamma-correction */
if (displaygamma != -1.0) {
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA)) {
if (displaygamma != gamma) {
png_set_gamma (png_ptr, displaygamma, gamma);
totalgamma = (double) gamma * (double) displaygamma;
/* in case of gamma-corrections, sBIT's as in the PNG-file are not valid anymore */
sig_bit = NULL;
if (verbose)
pm_message ("image gamma is %4.2f, converted for display gamma of %4.2f",
gamma, displaygamma);
}
} else {
if (displaygamma != gamma) {
png_set_gamma (png_ptr, displaygamma, 1.0);
totalgamma = (double) displaygamma;
sig_bit = NULL;
if (verbose)
pm_message ("image gamma assumed 1.0, converted for display gamma of %4.2f",
displaygamma);
}
}
}
/* sBIT handling is very tricky. If we are extracting only the image, we
can use the sBIT info for grayscale and color images, if the three
values agree. If we extract the transparency/alpha mask, sBIT is
irrelevant for trans and valid for alpha. If we mix both, the
multiplication may result in values that require the normal bit depth,
so we will use the sBIT info only for transparency, if we know that only
solid and fully transparent is used */
if (sig_bit != NULL) {
switch (alpha) {
/*case mix_and_alpha: */
case mix_only:
if (color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
break;
if (color_type == PNG_COLOR_TYPE_PALETTE &&
png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
trans_mix = TRUE;
for (i = 0 ; i < num_trans ; i++)
if (trans_alpha[i] != 0 && trans_alpha[i] != 255) {
trans_mix = FALSE;
break;
}
if (!trans_mix)
break;
}
/* else fall though to normal case */
case none_and_alpha:
case none:
if ((color_type == PNG_COLOR_TYPE_PALETTE ||
color_type == PNG_COLOR_TYPE_RGB ||
color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
(sig_bit->red != sig_bit->green ||
sig_bit->red != sig_bit->blue) &&
alpha == none) {
pm_message ("different bit depths for color channels not supported");
pm_message ("writing file with %d bit resolution", bit_depth);
} else {
if ((color_type == PNG_COLOR_TYPE_PALETTE) &&
(sig_bit->red < 255)) {
for (i = 0 ; i < num_palette ; i++) {
palette[i].red >>= (8 - sig_bit->red);
palette[i].green >>= (8 - sig_bit->green);
palette[i].blue >>= (8 - sig_bit->blue);
}
maxval = (1l << sig_bit->red) - 1;
if (verbose)
pm_message ("image has fewer significant bits, writing file with %d bits per channel",
sig_bit->red);
} else
if ((color_type == PNG_COLOR_TYPE_RGB ||
color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
(sig_bit->red < bit_depth)) {
png_set_shift (png_ptr, sig_bit);
maxval = (1l << sig_bit->red) - 1;
if (verbose)
pm_message ("image has fewer significant bits, writing file with %d bits per channel",
sig_bit->red);
} else
if ((color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA) &&
(sig_bit->gray < bit_depth)) {
png_set_shift (png_ptr, sig_bit);
maxval = (1l << sig_bit->gray) - 1;
if (verbose)
pm_message ("image has fewer significant bits, writing file with %d bits",
sig_bit->gray);
}
}
break;
case alpha_only:
if ((color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
color_type == PNG_COLOR_TYPE_GRAY_ALPHA) &&
(sig_bit->gray < bit_depth)) {
png_set_shift (png_ptr, sig_bit);
if (verbose)
pm_message ("image has fewer significant bits, writing file with %d bits",
sig_bit->alpha);
maxval = (1l << sig_bit->alpha) - 1;
}
break;
}
}
/* didn't manage to get libpng to work (bugs?) concerning background */
/* processing, therefore we do our own using bgr, bgg and bgb */
if (background != NULL)
switch (color_type) {
case PNG_COLOR_TYPE_GRAY:
case PNG_COLOR_TYPE_GRAY_ALPHA:
bgr = bgg = bgb = gamma_correct (background->gray, totalgamma);
break;
case PNG_COLOR_TYPE_PALETTE:
bgr = gamma_correct (palette[background->index].red, totalgamma);
bgg = gamma_correct (palette[background->index].green, totalgamma);
bgb = gamma_correct (palette[background->index].blue, totalgamma);
break;
case PNG_COLOR_TYPE_RGB:
case PNG_COLOR_TYPE_RGB_ALPHA:
bgr = gamma_correct (background->red, totalgamma);
bgg = gamma_correct (background->green, totalgamma);
bgb = gamma_correct (background->blue, totalgamma);
break;
}
else
/* when no background given, we use white [from version 2.37] */
bgr = bgg = bgb = maxval;
/* but if background was specified from the command-line, we always use that */
/* I chose to do no gamma-correction in this case; which is a bit arbitrary */
if (do_background > -1)
{
backcolor = ppm_parsecolor (backstring, maxval);
switch (color_type) {
case PNG_COLOR_TYPE_GRAY:
case PNG_COLOR_TYPE_GRAY_ALPHA:
bgr = bgg = bgb = PNM_GET1 (backcolor);
break;
case PNG_COLOR_TYPE_PALETTE:
case PNG_COLOR_TYPE_RGB:
case PNG_COLOR_TYPE_RGB_ALPHA:
bgr = PPM_GETR (backcolor);
bgg = PPM_GETG (backcolor);
bgb = PPM_GETB (backcolor);
break;
}
}
png_read_image (png_ptr, png_image);
png_read_end (png_ptr, info_ptr);
if (mtime)
show_time (png_ptr, info_ptr);
if (text)
save_text (png_ptr, info_ptr, tfp);
if (has_phys) {
double r;
r = (double)x_pixels_per_unit / y_pixels_per_unit;
if (r != 1.0) {
pm_message ("warning - non-square pixels; to fix do a 'pnmscale -%cscale %g'",
r < 1.0 ? 'x' : 'y',
r < 1.0 ? 1.0 / r : r );
}
}
if ((row = pnm_allocrow (width)) == NULL) {
for (y = 0 ; y+0U < height ; y++)
free (png_image[y]);
free (png_image);
png_destroy_read_struct (&png_ptr, &info_ptr, (png_infopp)NULL);
pm_closer (ifp);
{ pm_error ("couldn't allocate space for image"); exit(1); }
}
if (alpha == alpha_only) {
if (color_type == PNG_COLOR_TYPE_GRAY ||
color_type == PNG_COLOR_TYPE_RGB) {
pnm_type = PBM_TYPE;
} else