00f596e2745a1729737fd05914f82cb0056bb561
[openjpeg.git] / src / bin / jp2 / convertpng.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses
3  * BSD License, included below. This software may be subject to other third
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * Copyright (c) 2006-2007, Parvatha Elangovan
15  * Copyright (c) 2015, Matthieu Darbois
16  * All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
28  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
31  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGE.
38  */
39 #include "opj_apps_config.h"
40
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <ctype.h>
45
46 #include <zlib.h>
47 #include <png.h>
48
49 #include "openjpeg.h"
50 #include "convert.h"
51
52 #define PNG_MAGIC "\x89PNG\x0d\x0a\x1a\x0a"
53 #define MAGIC_SIZE 8
54 /* PNG allows bits per sample: 1, 2, 4, 8, 16 */
55
56
57 static void convert_16u32s_C1R(const OPJ_BYTE* pSrc, OPJ_INT32* pDst,
58                                OPJ_SIZE_T length)
59 {
60     OPJ_SIZE_T i;
61     for (i = 0; i < length; i++) {
62         OPJ_INT32 val0 = *pSrc++;
63         OPJ_INT32 val1 = *pSrc++;
64         pDst[i] = val0 << 8 | val1;
65     }
66 }
67
68 opj_image_t *pngtoimage(const char *read_idf, opj_cparameters_t * params)
69 {
70     png_structp  png = NULL;
71     png_infop    info = NULL;
72     double gamma;
73     int bit_depth, interlace_type, compression_type, filter_type;
74     OPJ_UINT32 i;
75     png_uint_32  width, height = 0U;
76     int color_type;
77     FILE *reader = NULL;
78     OPJ_BYTE** rows = NULL;
79     OPJ_INT32* row32s = NULL;
80     /* j2k: */
81     opj_image_t *image = NULL;
82     opj_image_cmptparm_t cmptparm[4];
83     OPJ_UINT32 nr_comp;
84     OPJ_BYTE sigbuf[8];
85     convert_XXx32s_C1R cvtXXTo32s = NULL;
86     convert_32s_CXPX cvtCxToPx = NULL;
87     OPJ_INT32* planes[4];
88
89     if ((reader = fopen(read_idf, "rb")) == NULL) {
90         fprintf(stderr, "pngtoimage: can not open %s\n", read_idf);
91         return NULL;
92     }
93
94     if (fread(sigbuf, 1, MAGIC_SIZE, reader) != MAGIC_SIZE
95             || memcmp(sigbuf, PNG_MAGIC, MAGIC_SIZE) != 0) {
96         fprintf(stderr, "pngtoimage: %s is no valid PNG file\n", read_idf);
97         goto fin;
98     }
99
100     if ((png = png_create_read_struct(PNG_LIBPNG_VER_STRING,
101                                       NULL, NULL, NULL)) == NULL) {
102         goto fin;
103     }
104     if ((info = png_create_info_struct(png)) == NULL) {
105         goto fin;
106     }
107
108     if (setjmp(png_jmpbuf(png))) {
109         goto fin;
110     }
111
112     png_init_io(png, reader);
113     png_set_sig_bytes(png, MAGIC_SIZE);
114
115     png_read_info(png, info);
116
117     if (png_get_IHDR(png, info, &width, &height,
118                      &bit_depth, &color_type, &interlace_type,
119                      &compression_type, &filter_type) == 0) {
120         goto fin;
121     }
122
123     /* png_set_expand():
124      * expand paletted images to RGB, expand grayscale images of
125      * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
126      * to alpha channels.
127      */
128     if (color_type == PNG_COLOR_TYPE_PALETTE) {
129         png_set_expand(png);
130     }
131
132     if (png_get_valid(png, info, PNG_INFO_tRNS)) {
133         png_set_expand(png);
134     }
135     /* We might wan't to expand background */
136     /*
137     if(png_get_valid(png, info, PNG_INFO_bKGD)) {
138         png_color_16p bgnd;
139         png_get_bKGD(png, info, &bgnd);
140         png_set_background(png, bgnd, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
141     }
142     */
143
144     if (!png_get_gAMA(png, info, &gamma)) {
145         gamma = 1.0;
146     }
147
148     /* we're not displaying but converting, screen gamma == 1.0 */
149     png_set_gamma(png, 1.0, gamma);
150
151     png_read_update_info(png, info);
152
153     color_type = png_get_color_type(png, info);
154
155     switch (color_type) {
156     case PNG_COLOR_TYPE_GRAY:
157         nr_comp = 1;
158         break;
159     case PNG_COLOR_TYPE_GRAY_ALPHA:
160         nr_comp = 2;
161         break;
162     case PNG_COLOR_TYPE_RGB:
163         nr_comp = 3;
164         break;
165     case PNG_COLOR_TYPE_RGB_ALPHA:
166         nr_comp = 4;
167         break;
168     default:
169         fprintf(stderr, "pngtoimage: colortype %d is not supported\n", color_type);
170         goto fin;
171     }
172     cvtCxToPx = convert_32s_CXPX_LUT[nr_comp];
173     bit_depth = png_get_bit_depth(png, info);
174
175     switch (bit_depth) {
176     case 1:
177     case 2:
178     case 4:
179     case 8:
180         cvtXXTo32s = convert_XXu32s_C1R_LUT[bit_depth];
181         break;
182     case 16: /* 16 bpp is specific to PNG */
183         cvtXXTo32s = convert_16u32s_C1R;
184         break;
185     default:
186         fprintf(stderr, "pngtoimage: bit depth %d is not supported\n", bit_depth);
187         goto fin;
188     }
189
190
191     rows = (OPJ_BYTE**)calloc(height + 1, sizeof(OPJ_BYTE*));
192     if (rows == NULL) {
193         fprintf(stderr, "pngtoimage: memory out\n");
194         goto fin;
195     }
196     for (i = 0; i < height; ++i) {
197         rows[i] = (OPJ_BYTE*)malloc(png_get_rowbytes(png, info));
198         if (rows[i] == NULL) {
199             fprintf(stderr, "pngtoimage: memory out\n");
200             goto fin;
201         }
202     }
203     png_read_image(png, rows);
204
205     /* Create image */
206     memset(cmptparm, 0, sizeof(cmptparm));
207     for (i = 0; i < nr_comp; ++i) {
208         cmptparm[i].prec = (OPJ_UINT32)bit_depth;
209         /* bits_per_pixel: 8 or 16 */
210         cmptparm[i].bpp = (OPJ_UINT32)bit_depth;
211         cmptparm[i].sgnd = 0;
212         cmptparm[i].dx = (OPJ_UINT32)params->subsampling_dx;
213         cmptparm[i].dy = (OPJ_UINT32)params->subsampling_dy;
214         cmptparm[i].w = (OPJ_UINT32)width;
215         cmptparm[i].h = (OPJ_UINT32)height;
216     }
217
218     image = opj_image_create(nr_comp, &cmptparm[0],
219                              (nr_comp > 2U) ? OPJ_CLRSPC_SRGB : OPJ_CLRSPC_GRAY);
220     if (image == NULL) {
221         goto fin;
222     }
223     image->x0 = (OPJ_UINT32)params->image_offset_x0;
224     image->y0 = (OPJ_UINT32)params->image_offset_y0;
225     image->x1 = (OPJ_UINT32)(image->x0 + (width  - 1) * (OPJ_UINT32)
226                              params->subsampling_dx + 1);
227     image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)
228                              params->subsampling_dy + 1);
229
230     row32s = (OPJ_INT32 *)malloc((size_t)width * nr_comp * sizeof(OPJ_INT32));
231     if (row32s == NULL) {
232         goto fin;
233     }
234
235     /* Set alpha channel */
236     image->comps[nr_comp - 1U].alpha = 1U - (nr_comp & 1U);
237
238     for (i = 0; i < nr_comp; i++) {
239         planes[i] = image->comps[i].data;
240     }
241
242     for (i = 0; i < height; ++i) {
243         cvtXXTo32s(rows[i], row32s, (OPJ_SIZE_T)width * nr_comp);
244         cvtCxToPx(row32s, planes, width);
245         planes[0] += width;
246         planes[1] += width;
247         planes[2] += width;
248         planes[3] += width;
249     }
250 fin:
251     if (rows) {
252         for (i = 0; i < height; ++i)
253             if (rows[i]) {
254                 free(rows[i]);
255             }
256         free(rows);
257     }
258     if (row32s) {
259         free(row32s);
260     }
261     if (png) {
262         png_destroy_read_struct(&png, &info, NULL);
263     }
264
265     fclose(reader);
266
267     return image;
268
269 }/* pngtoimage() */
270
271
272 static void convert_32s16u_C1R(const OPJ_INT32* pSrc, OPJ_BYTE* pDst,
273                                OPJ_SIZE_T length)
274 {
275     OPJ_SIZE_T i;
276     for (i = 0; i < length; i++) {
277         OPJ_UINT32 val = (OPJ_UINT32)pSrc[i];
278         *pDst++ = (OPJ_BYTE)(val >> 8);
279         *pDst++ = (OPJ_BYTE)val;
280     }
281 }
282 int imagetopng(opj_image_t * image, const char *write_idf)
283 {
284     FILE * volatile writer = NULL;
285     png_structp png = NULL;
286     png_infop info = NULL;
287     png_bytep volatile row_buf = NULL;
288     int nr_comp, color_type;
289     volatile int prec;
290     png_color_8 sig_bit;
291     OPJ_INT32 const* planes[4];
292     int i;
293     OPJ_INT32* volatile buffer32s = NULL;
294
295     volatile int fails = 1;
296
297     memset(&sig_bit, 0, sizeof(sig_bit));
298     prec = (int)image->comps[0].prec;
299     planes[0] = image->comps[0].data;
300     if (planes[0] == NULL) {
301         fprintf(stderr,
302                 "imagetopng: planes[%d] == NULL.\n", 0);
303         fprintf(stderr, "\tAborting\n");
304         return 1;
305     }
306     nr_comp = (int)image->numcomps;
307
308     if (nr_comp > 4) {
309         nr_comp = 4;
310     }
311     for (i = 1; i < nr_comp; ++i) {
312         if (image->comps[0].dx != image->comps[i].dx) {
313             break;
314         }
315         if (image->comps[0].dy != image->comps[i].dy) {
316             break;
317         }
318         if (image->comps[0].prec != image->comps[i].prec) {
319             break;
320         }
321         if (image->comps[0].sgnd != image->comps[i].sgnd) {
322             break;
323         }
324         planes[i] = image->comps[i].data;
325         if (planes[i] == NULL) {
326             fprintf(stderr,
327                     "imagetopng: planes[%d] == NULL.\n", i);
328             fprintf(stderr, "\tAborting\n");
329             return 1;
330         }
331     }
332     if (i != nr_comp) {
333         fprintf(stderr,
334                 "imagetopng: All components shall have the same subsampling, same bit depth, same sign.\n");
335         fprintf(stderr, "\tAborting\n");
336         return 1;
337     }
338     for (i = 0; i < nr_comp; ++i) {
339         clip_component(&(image->comps[i]), image->comps[0].prec);
340     }
341     if (prec > 8 && prec < 16) {
342         for (i = 0; i < nr_comp; ++i) {
343             scale_component(&(image->comps[i]), 16);
344         }
345         prec = 16;
346     } else if (prec < 8 && nr_comp > 1) { /* GRAY_ALPHA, RGB, RGB_ALPHA */
347         for (i = 0; i < nr_comp; ++i) {
348             scale_component(&(image->comps[i]), 8);
349         }
350         prec = 8;
351     } else if ((prec > 1) && (prec < 8) && ((prec == 6) ||
352                                             ((prec & 1) == 1))) { /* GRAY with non native precision */
353         if ((prec == 5) || (prec == 6)) {
354             prec = 8;
355         } else {
356             prec++;
357         }
358         for (i = 0; i < nr_comp; ++i) {
359             scale_component(&(image->comps[i]), (OPJ_UINT32)prec);
360         }
361     }
362
363     if (prec != 1 && prec != 2 && prec != 4 && prec != 8 && prec != 16) {
364         fprintf(stderr, "imagetopng: can not create %s\n\twrong bit_depth %d\n",
365                 write_idf, prec);
366         return fails;
367     }
368
369     writer = fopen(write_idf, "wb");
370
371     if (writer == NULL) {
372         return fails;
373     }
374
375     /* Create and initialize the png_struct with the desired error handler
376      * functions.  If you want to use the default stderr and longjump method,
377      * you can supply NULL for the last three parameters.  We also check that
378      * the library version is compatible with the one used at compile time,
379      * in case we are using dynamically linked libraries.  REQUIRED.
380      */
381     png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
382                                   NULL, NULL, NULL);
383     /*png_voidp user_error_ptr, user_error_fn, user_warning_fn); */
384
385     if (png == NULL) {
386         goto fin;
387     }
388
389     /* Allocate/initialize the image information data.  REQUIRED
390      */
391     info = png_create_info_struct(png);
392
393     if (info == NULL) {
394         goto fin;
395     }
396
397     /* Set error handling.  REQUIRED if you are not supplying your own
398      * error handling functions in the png_create_write_struct() call.
399      */
400     if (setjmp(png_jmpbuf(png))) {
401         goto fin;
402     }
403
404     /* I/O initialization functions is REQUIRED
405      */
406     png_init_io(png, writer);
407
408     /* Set the image information here.  Width and height are up to 2^31,
409      * bit_depth is one of 1, 2, 4, 8, or 16, but valid values also depend on
410      * the color_type selected. color_type is one of PNG_COLOR_TYPE_GRAY,
411      * PNG_COLOR_TYPE_GRAY_ALPHA, PNG_COLOR_TYPE_PALETTE, PNG_COLOR_TYPE_RGB,
412      * or PNG_COLOR_TYPE_RGB_ALPHA.  interlace is either PNG_INTERLACE_NONE or
413      * PNG_INTERLACE_ADAM7, and the compression_type and filter_type MUST
414      * currently be PNG_COMPRESSION_TYPE_BASE and PNG_FILTER_TYPE_BASE.
415      * REQUIRED
416      *
417      * ERRORS:
418      *
419      * color_type == PNG_COLOR_TYPE_PALETTE && bit_depth > 8
420      * color_type == PNG_COLOR_TYPE_RGB && bit_depth < 8
421      * color_type == PNG_COLOR_TYPE_GRAY_ALPHA && bit_depth < 8
422      * color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8
423      *
424      */
425     png_set_compression_level(png, Z_BEST_COMPRESSION);
426
427     if (nr_comp >= 3) { /* RGB(A) */
428         color_type = PNG_COLOR_TYPE_RGB;
429         sig_bit.red = sig_bit.green = sig_bit.blue = (png_byte)prec;
430     } else { /* GRAY(A) */
431         color_type = PNG_COLOR_TYPE_GRAY;
432         sig_bit.gray = (png_byte)prec;
433     }
434     if ((nr_comp & 1) == 0) { /* ALPHA */
435         color_type |= PNG_COLOR_MASK_ALPHA;
436         sig_bit.alpha = (png_byte)prec;
437     }
438
439     png_set_IHDR(png, info, image->comps[0].w, image->comps[0].h, prec, color_type,
440                  PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,  PNG_FILTER_TYPE_BASE);
441
442     png_set_sBIT(png, info, &sig_bit);
443     /* png_set_gamma(png, 2.2, 1./2.2); */
444     /* png_set_sRGB(png, info, PNG_sRGB_INTENT_PERCEPTUAL); */
445     png_write_info(png, info);
446
447     /* setup conversion */
448     {
449         OPJ_SIZE_T rowStride;
450         png_size_t png_row_size;
451
452         png_row_size = png_get_rowbytes(png, info);
453         rowStride = ((OPJ_SIZE_T)image->comps[0].w * (OPJ_SIZE_T)nr_comp *
454                      (OPJ_SIZE_T)prec + 7U) / 8U;
455         if (rowStride != (OPJ_SIZE_T)png_row_size) {
456             fprintf(stderr, "Invalid PNG row size\n");
457             goto fin;
458         }
459         row_buf = (png_bytep)malloc(png_row_size);
460         if (row_buf == NULL) {
461             fprintf(stderr, "Can't allocate memory for PNG row\n");
462             goto fin;
463         }
464         buffer32s = (OPJ_INT32*)malloc((OPJ_SIZE_T)image->comps[0].w *
465                                        (OPJ_SIZE_T)nr_comp * sizeof(OPJ_INT32));
466         if (buffer32s == NULL) {
467             fprintf(stderr, "Can't allocate memory for interleaved 32s row\n");
468             goto fin;
469         }
470     }
471
472     /* convert */
473     {
474         OPJ_SIZE_T width = image->comps[0].w;
475         OPJ_UINT32 y;
476         convert_32s_PXCX cvtPxToCx = convert_32s_PXCX_LUT[nr_comp];
477         convert_32sXXx_C1R cvt32sToPack = NULL;
478         OPJ_INT32 adjust = image->comps[0].sgnd ? 1 << (prec - 1) : 0;
479         png_bytep row_buf_cpy = row_buf;
480         OPJ_INT32* buffer32s_cpy = buffer32s;
481
482         switch (prec) {
483         case 1:
484         case 2:
485         case 4:
486         case 8:
487             cvt32sToPack = convert_32sXXu_C1R_LUT[prec];
488             break;
489         case 16:
490             cvt32sToPack = convert_32s16u_C1R;
491             break;
492         default:
493             /* never here */
494             break;
495         }
496
497         for (y = 0; y < image->comps[0].h; ++y) {
498             cvtPxToCx(planes, buffer32s_cpy, width, adjust);
499             cvt32sToPack(buffer32s_cpy, row_buf_cpy, width * (OPJ_SIZE_T)nr_comp);
500             png_write_row(png, row_buf_cpy);
501             planes[0] += width;
502             planes[1] += width;
503             planes[2] += width;
504             planes[3] += width;
505         }
506     }
507
508     png_write_end(png, info);
509
510     fails = 0;
511
512 fin:
513     if (png) {
514         png_destroy_write_struct(&png, &info);
515     }
516     if (row_buf) {
517         free(row_buf);
518     }
519     if (buffer32s) {
520         free(buffer32s);
521     }
522     fclose(writer);
523
524     if (fails) {
525         (void)remove(write_idf);    /* ignore return value */
526     }
527
528     return fails;
529 }/* imagetopng() */