Debian Codegraph @

heifio/decoder_png.cc

raw
1 /*
2 libheif example application "heif".
3
4 MIT License
5
6 Copyright (c) 2023 Dirk Farin <[email protected]>
7
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14
15 The above copyright notice and this permission notice shall be included in all
16 copies or substantial portions of the Software.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 SOFTWARE.
25 */
26
27 #include <cstdlib>
28 #include <cstring>
29 #include <cassert>
30 #include <iostream>
31 #include <memory>
32 #include "decoder_png.h"
33 #include "exif.h"
34
35 extern "C" {
36 #include <png.h>
37 }
38
39 static struct heif_error heif_error_ok = {heif_error_Ok, heif_suberror_Unspecified, "Success"};
40
41 static void
42 user_read_fn(png_structp png_ptr, png_bytep data, png_size_t length)
43 {
44 FILE* fh = (FILE*) png_get_io_ptr(png_ptr);
45 size_t n = fread((char*) data, length, 1, fh);
46 (void) n;
47 } // user_read_data
48
49
50 heif_error loadPNG(const char* filename, int output_bit_depth, InputImage *input_image)
51 {
52 FILE* fh = fopen(filename, "rb");
53 if (!fh) {
54 struct heif_error err = {
55 .code = heif_error_Invalid_input,
56 .subcode = heif_suberror_Unspecified,
57 .message = "Cannot open PNG file"};
58 return err;
59 }
60
61 // ### Code copied from LibVideoGfx and slightly modified to use HeifPixelImage
62
63 struct heif_image* image = nullptr;
64
65 png_structp png_ptr;
66 png_infop info_ptr;
67 png_uint_32 width, height;
68 int bit_depth, color_type, interlace_type;
69 int compression_type;
70 png_charp name;
71 #if (PNG_LIBPNG_VER < 10500)
72 png_charp png_profile_data;
73 #else
74 png_bytep png_profile_data;
75 #endif
76 uint8_t* profile_data = nullptr;
77 png_uint_32 profile_length = 5;
78
79 /* Create and initialize the png_struct with the desired error handler
80 * functions. If you want to use the default stderr and longjump method,
81 * you can supply NULL for the last three parameters. We also supply the
82 * the compiler header file version, so that we know if the application
83 * was compiled with a compatible version of the library. REQUIRED
84 */
85 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
86 assert(png_ptr != NULL);
87
88 /* Allocate/initialize the memory for image information. REQUIRED. */
89 info_ptr = png_create_info_struct(png_ptr);
90 if (info_ptr == NULL) {
91 png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL);
92 assert(false); // , "could not create info_ptr");
93 } // if
94
95 /* Set error handling if you are using the setjmp/longjmp method (this is
96 * the normal method of doing things with libpng). REQUIRED unless you
97 * set up your own error handlers in the png_create_read_struct() earlier.
98 */
99 if (setjmp(png_jmpbuf(png_ptr))) {
100 /* Free all of the memory associated with the png_ptr and info_ptr */
101 png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
102 /* If we get here, we had a problem reading the file */
103 assert(false); // , "fatal error in png library");
104 } // if
105
106 /* If you are using replacement read functions, instead of calling
107 * png_init_io() here you would call: */
108 png_set_read_fn(png_ptr, (void*) fh, user_read_fn);
109 /* where user_io_ptr is a structure you want available to the callbacks */
110
111 /* The call to png_read_info() gives us all of the information from the
112 * PNG file before the first IDAT (image data chunk). REQUIRED
113 */
114 png_read_info(png_ptr, info_ptr);
115
116 png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
117 &interlace_type, NULL, NULL);
118
119 if (png_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP)) {
120 if (PNG_INFO_iCCP ==
121 png_get_iCCP(png_ptr, info_ptr, &name, &compression_type, &png_profile_data, &profile_length) &&
122 profile_length > 0) {
123 profile_data = (uint8_t*) malloc(profile_length);
124 if (profile_data) {
125 memcpy(profile_data, png_profile_data, profile_length);
126 }
127 }
128 }
129 /**** Set up the data transformations you want. Note that these are all
130 **** optional. Only call them if you want/need them. Many of the
131 **** transformations only work on specific types of images, and many
132 **** are mutually exclusive.
133 ****/
134
135 // \TODO
136 // /* Strip alpha bytes from the input data without combining with the
137 // * background (not recommended).
138 // */
139 // png_set_strip_alpha(png_ptr);
140
141 /* Extract multiple pixels with bit depths of 1, 2, and 4 from a single
142 * byte into separate bytes (useful for paletted and grayscale images).
143 */
144 png_set_packing(png_ptr);
145
146
147 /* Expand paletted colors into true RGB triplets */
148 if (color_type == PNG_COLOR_TYPE_PALETTE) {
149 png_set_palette_to_rgb(png_ptr);
150 bit_depth = 8;
151 }
152
153 /* Expand grayscale images to the full 8 bits from 1, 2, or 4 bits/pixel */
154 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) {
155 png_set_expand_gray_1_2_4_to_8(png_ptr);
156 bit_depth = 8;
157 }
158
159 /* Set the background color to draw transparent and alpha images over.
160 * It is possible to set the red, green, and blue components directly
161 * for paletted images instead of supplying a palette index. Note that
162 * even if the PNG file supplies a background, you are not required to
163 * use it - you should use the (solid) application background if it has one.
164 */
165
166 #if 0
167 // \TODO 0 is index in color lookup table - correct? used already?
168 png_color_16 my_background = {0, 255, 255, 255, 255};
169 png_color_16 *image_background;
170
171 if (png_get_bKGD(png_ptr, info_ptr, &image_background))
172 png_set_background(png_ptr, image_background, PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
173 else
174 png_set_background(png_ptr, &my_background, PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
175 #endif
176
177
178 /* Optional call to gamma correct and add the background to the palette
179 * and update info structure. REQUIRED if you are expecting libpng to
180 * update the palette for you (ie you selected such a transform above).
181 */
182 png_read_update_info(png_ptr, info_ptr);
183
184 /* Allocate the memory to hold the image using the fields of info_ptr. */
185
186 /* The easiest way to read the image: */
187 uint8_t** row_pointers = new png_bytep[height];
188 assert(row_pointers != NULL);
189
190 for (uint32_t y = 0; y < height; y++) {
191 row_pointers[y] = (png_bytep) malloc(png_get_rowbytes(png_ptr, info_ptr));
192 assert(row_pointers[y] != NULL);
193 } // for
194
195 /* Now it's time to read the image. One of these methods is REQUIRED */
196 png_read_image(png_ptr, row_pointers);
197
198 /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
199 png_read_end(png_ptr, info_ptr);
200
201
202 // --- read EXIF data
203
204 #ifdef PNG_eXIf_SUPPORTED
205 png_bytep exifPtr = nullptr;
206 png_uint_32 exifSize = 0;
207 if (png_get_eXIf_1(png_ptr, info_ptr, &exifSize, &exifPtr) == PNG_INFO_eXIf) {
208 input_image->exif.resize(exifSize);
209 memcpy(input_image->exif.data(), exifPtr, exifSize);
210
211 // remove the EXIF orientation since it is informal only in PNG and we do not want to confuse with an orientation not matching irot/imir
212 modify_exif_orientation_tag_if_it_exists(input_image->exif.data(), (int) input_image->exif.size(), 1);
213 }
214 #endif
215
216 // --- read XMP data
217
218 #ifdef PNG_iTXt_SUPPORTED
219 png_textp textPtr = nullptr;
220 const png_uint_32 nTextChunks = png_get_text(png_ptr, info_ptr, &textPtr, nullptr);
221 for (png_uint_32 i = 0; i < nTextChunks; i++, textPtr++) {
222 png_size_t textLength = textPtr->text_length;
223 if ((textPtr->compression == PNG_ITXT_COMPRESSION_NONE) || (textPtr->compression == PNG_ITXT_COMPRESSION_zTXt)) {
224 textLength = textPtr->itxt_length;
225 }
226
227 if (!strcmp(textPtr->key, "XML:com.adobe.xmp")) {
228 if (textLength == 0) {
229 // TODO: error
230 }
231 else {
232 input_image->xmp.resize(textLength);
233 memcpy(input_image->xmp.data(), textPtr->text, textLength);
234 }
235 }
236 }
237 #endif
238
239 int band = png_get_channels(png_ptr, info_ptr);
240
241 /* clean up after the read, and free any memory allocated - REQUIRED */
242 png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL);
243
244
245 struct heif_error err;
246
247 bool has_alpha = (band == 2 || band == 4);
248
249 if (band == 1 && bit_depth == 8) {
250 err = heif_image_create((int) width, (int) height,
251 heif_colorspace_monochrome,
252 heif_chroma_monochrome,
253 &image);
254 (void) err;
255
256 heif_image_add_plane(image, heif_channel_Y, (int) width, (int) height, 8);
257
258 size_t y_stride;
259 size_t a_stride;
260 uint8_t* py = heif_image_get_plane2(image, heif_channel_Y, &y_stride);
261 uint8_t* pa = nullptr;
262
263 if (has_alpha) {
264 heif_image_add_plane(image, heif_channel_Alpha, (int) width, (int) height, 8);
265
266 pa = heif_image_get_plane2(image, heif_channel_Alpha, &a_stride);
267 }
268
269
270 for (uint32_t y = 0; y < height; y++) {
271 uint8_t* p = row_pointers[y];
272
273 if (has_alpha) {
274 for (uint32_t x = 0; x < width; x++) {
275 py[y * y_stride + x] = *p++;
276 pa[y * a_stride + x] = *p++;
277 }
278 }
279 else {
280 memcpy(&py[y * y_stride], p, width);
281 }
282 }
283 }
284 else if (band == 1) {
285 assert(bit_depth > 8);
286
287 err = heif_image_create((int) width, (int) height,
288 heif_colorspace_monochrome,
289 heif_chroma_monochrome,
290 &image);
291 (void) err;
292
293 int bdShift = 16 - output_bit_depth;
294
295 heif_image_add_plane(image, heif_channel_Y, (int) width, (int) height, output_bit_depth);
296
297 size_t y_stride;
298 size_t a_stride = 0;
299 uint16_t* py = (uint16_t*) heif_image_get_plane2(image, heif_channel_Y, &y_stride);
300 uint16_t* pa = nullptr;
301
302 if (has_alpha) {
303 heif_image_add_plane(image, heif_channel_Alpha, (int) width, (int) height, output_bit_depth);
304
305 pa = (uint16_t*) heif_image_get_plane2(image, heif_channel_Alpha, &a_stride);
306 }
307
308 y_stride /= 2;
309 a_stride /= 2;
310
311 for (uint32_t y = 0; y < height; y++) {
312 uint8_t* p = row_pointers[y];
313
314 if (has_alpha) {
315 for (uint32_t x = 0; x < width; x++) {
316 uint16_t vp = (uint16_t) (((p[0] << 8) | p[1]) >> bdShift);
317 uint16_t va = (uint16_t) (((p[2] << 8) | p[3]) >> bdShift);
318
319 py[x + y * y_stride] = vp;
320 pa[x + y * y_stride] = va;
321
322 p += 4;
323 }
324 }
325 else {
326 for (uint32_t x = 0; x < width; x++) {
327 uint16_t vp = (uint16_t) (((p[0] << 8) | p[1]) >> bdShift);
328
329 py[x + y * y_stride] = vp;
330
331 p += 2;
332 }
333 }
334 }
335 }
336 else if (band == 2 && bit_depth==8) {
337 err = heif_image_create((int) width, (int) height,
338 heif_colorspace_monochrome,
339 heif_chroma_monochrome,
340 &image);
341 (void) err;
342
343 heif_image_add_plane(image, heif_channel_Y, (int) width, (int) height, 8);
344 heif_image_add_plane(image, heif_channel_Alpha, (int) width, (int) height, 8);
345
346 size_t stride;
347 uint8_t* p = heif_image_get_plane2(image, heif_channel_Y, &stride);
348
349 size_t strideA;
350 uint8_t* pA = heif_image_get_plane2(image, heif_channel_Alpha, &strideA);
351
352 for (uint32_t y = 0; y < height; y++) {
353 for (uint32_t x = 0; x < width; x++) {
354 p[y * stride + x] = row_pointers[y][2 * x];
355 pA[y * strideA + x] = row_pointers[y][2 * x + 1];
356 }
357 }
358 }
359 else if (bit_depth == 8) {
360 err = heif_image_create((int) width, (int) height,
361 heif_colorspace_RGB,
362 has_alpha ? heif_chroma_interleaved_RGBA : heif_chroma_interleaved_RGB,
363 &image);
364 (void) err;
365
366 heif_image_add_plane(image, heif_channel_interleaved, (int) width, (int) height,
367 has_alpha ? 32 : 24);
368
369 size_t stride;
370 uint8_t* p = heif_image_get_plane2(image, heif_channel_interleaved, &stride);
371
372 for (uint32_t y = 0; y < height; y++) {
373 if (has_alpha) {
374 memcpy(p + y * stride, row_pointers[y], width * 4);
375 }
376 else {
377 memcpy(p + y * stride, row_pointers[y], width * 3);
378 }
379 }
380 }
381 else {
382 if (output_bit_depth == 8) {
383 err = heif_image_create((int) width, (int) height,
384 heif_colorspace_RGB,
385 has_alpha ?
386 heif_chroma_interleaved_RGBA :
387 heif_chroma_interleaved_RGB,
388 &image);
389 }
390 else {
391 err = heif_image_create((int) width, (int) height,
392 heif_colorspace_RGB,
393 has_alpha ?
394 heif_chroma_interleaved_RRGGBBAA_LE :
395 heif_chroma_interleaved_RRGGBB_LE,
396 &image);
397 }
398 (void) err;
399
400 int bdShift = 16 - output_bit_depth;
401
402 heif_image_add_plane(image, heif_channel_interleaved, (int) width, (int) height, output_bit_depth);
403
404 size_t stride;
405 uint8_t* p_out = (uint8_t*) heif_image_get_plane2(image, heif_channel_interleaved, &stride);
406
407 if (output_bit_depth==8) {
408 // convert HDR to SDR
409
410 for (uint32_t y = 0; y < height; y++) {
411 uint8_t* p = row_pointers[y];
412
413 uint32_t nVal = (has_alpha ? 4 : 3) * width;
414
415 for (uint32_t x = 0; x < nVal; x++) {
416 p_out[x + y * stride] = p[0];
417 p+=2;
418 }
419 }
420 }
421 else {
422 for (uint32_t y = 0; y < height; y++) {
423 uint8_t* p = row_pointers[y];
424
425 uint32_t nVal = (has_alpha ? 4 : 3) * width;
426
427 for (uint32_t x = 0; x < nVal; x++) {
428 uint16_t v = (uint16_t) (((p[0] << 8) | p[1]) >> bdShift);
429 p_out[2 * x + y * stride + 1] = (uint8_t) (v >> 8);
430 p_out[2 * x + y * stride + 0] = (uint8_t) (v & 0xFF);
431 p += 2;
432 }
433 }
434 }
435 }
436
437 if (profile_data && profile_length > 0) {
438 heif_image_set_raw_color_profile(image, "prof", profile_data, (size_t) profile_length);
439 }
440
441 free(profile_data);
442 for (uint32_t y = 0; y < height; y++) {
443 free(row_pointers[y]);
444 } // for
445
446 delete[] row_pointers;
447 fclose(fh);
448
449 input_image->image = std::shared_ptr<heif_image>(image,
450 [](heif_image* img) { heif_image_release(img); });
451
452 return heif_error_ok;
453 }