Debian Codegraph @

heifio/encoder_png.cc

raw
1 /*
2 libheif example application.
3
4 MIT License
5
6 Copyright (c) 2017 struktur AG, Joachim Bauch <[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 #include <cerrno>
27 #include <png.h>
28 #include <cstring>
29 #include <cstdlib>
30 #include <vector>
31
32 #include "encoder_png.h"
33
34 #include "common_utils.h"
35 #include "exif.h"
36
37 PngEncoder::PngEncoder() = default;
38
39 // Returns false if ICC profile recognized invalid and could not be fixed.
40 bool fix_icc_profile(uint8_t* profile_data, uint32_t& profile_size)
41 {
42 if (profile_size < 128) {
43 return false;
44 }
45
46
47 // --- check that profile size specified in header matches the real size
48
49 uint32_t size_in_header = four_bytes_to_uint32(profile_data[0],
50 profile_data[1],
51 profile_data[2],
52 profile_data[3]);
53
54 if (size_in_header != profile_size) {
55
56 // Size in header is smaller than actual size, but alignment indicates that it might
57 // be correct. Replace real data length with size in header.
58 if (size_in_header < profile_size && (size_in_header & 3)==0) {
59 fprintf(stderr, "Input ICC profile has wrong size in header (%d instead of %d). Skipping extra bytes at the end. "
60 "Note that this may still be incorrect and the ICC profile may be broken.\n", size_in_header, profile_size);
61
62 profile_size = size_in_header;
63 }
64 else {
65 return false;
66 }
67 }
68
69 return true;
70 }
71
72
73 bool PngEncoder::Encode(const heif_image_handle* handle,
74 const heif_image* image, const std::string& filename)
75 {
76 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr,
77 nullptr, nullptr);
78 if (!png_ptr) {
79 fprintf(stderr, "libpng initialization failed (1)\n");
80 return false;
81 }
82
83 png_infop info_ptr = png_create_info_struct(png_ptr);
84 if (!info_ptr) {
85 png_destroy_write_struct(&png_ptr, nullptr);
86 fprintf(stderr, "libpng initialization failed (2)\n");
87 return false;
88 }
89
90 if (m_compression_level != -1) {
91 png_set_compression_level(png_ptr, m_compression_level);
92 }
93
94 FILE* fp = fopen(filename.c_str(), "wb");
95 if (!fp) {
96 fprintf(stderr, "Can't open %s: %s\n", filename.c_str(), strerror(errno));
97 png_destroy_write_struct(&png_ptr, &info_ptr);
98 return false;
99 }
100
101 if (setjmp(png_jmpbuf(png_ptr))) {
102 png_destroy_write_struct(&png_ptr, &info_ptr);
103 fclose(fp);
104 fprintf(stderr, "Error while encoding image\n");
105 return false;
106 }
107
108 png_init_io(png_ptr, fp);
109
110 bool withAlpha = (heif_image_get_chroma_format(image) == heif_chroma_interleaved_RGBA ||
111 heif_image_get_chroma_format(image) == heif_chroma_interleaved_RRGGBBAA_BE);
112
113 int width = heif_image_get_width(image, heif_channel_interleaved);
114 int height = heif_image_get_height(image, heif_channel_interleaved);
115
116 int bitDepth;
117 int input_bpp = heif_image_get_bits_per_pixel_range(image, heif_channel_interleaved);
118 if (input_bpp > 8) {
119 bitDepth = 16;
120 }
121 else {
122 bitDepth = 8;
123 }
124
125 const int colorType = withAlpha ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_RGB;
126
127 png_set_IHDR(png_ptr, info_ptr, width, height, bitDepth, colorType,
128 PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
129
130 // --- write ICC profile
131
132 if (handle) {
133 uint32_t profile_size = static_cast<uint32_t>(heif_image_handle_get_raw_color_profile_size(handle));
134 if (profile_size > 0) {
135 uint8_t* profile_data = static_cast<uint8_t*>(malloc(profile_size));
136 heif_image_handle_get_raw_color_profile(handle, profile_data);
137 if (fix_icc_profile(profile_data, profile_size)) {
138 char profile_name[] = "unknown";
139 png_set_iCCP(png_ptr, info_ptr, profile_name, PNG_COMPRESSION_TYPE_BASE,
140 #if PNG_LIBPNG_VER < 10500
141 (png_charp)profile_data,
142 #else
143 (png_const_bytep) profile_data,
144 #endif
145 (png_uint_32) profile_size);
146 }
147 else {
148 fprintf(stderr, "Invalid ICC profile. Writing PNG file without ICC.\n");
149 }
150 free(profile_data);
151 }
152 }
153
154 // --- write EXIF metadata
155
156 #ifdef PNG_eXIf_SUPPORTED
157 if (handle) {
158 size_t exifsize = 0;
159 uint8_t* exifdata = GetExifMetaData(handle, &exifsize);
160 if (exifdata) {
161 if (exifsize > 4) {
162 uint32_t skip = four_bytes_to_uint32(exifdata[0], exifdata[1], exifdata[2], exifdata[3]);
163 if (skip < (exifsize - 4)) {
164 skip += 4;
165 uint8_t* ptr = exifdata + skip;
166 size_t size = exifsize - skip;
167
168 // libheif by default normalizes the image orientation, so that we have to set the EXIF Orientation to "Horizontal (normal)"
169 modify_exif_orientation_tag_if_it_exists(ptr, (int) size, 1);
170 overwrite_exif_image_size_if_it_exists(ptr, (int) size, width, height);
171
172 png_set_eXIf_1(png_ptr, info_ptr, (png_uint_32) size, ptr);
173 }
174 }
175
176 free(exifdata);
177 }
178 }
179 #endif
180
181 // --- write XMP metadata
182
183 #ifdef PNG_iTXt_SUPPORTED
184 if (handle) {
185 // spec: https://raw.githubusercontent.com/adobe/xmp-docs/master/XMPSpecifications/XMPSpecificationPart3.pdf
186 std::vector<uint8_t> xmp = get_xmp_metadata(handle);
187 if (!xmp.empty()) {
188 // make sure that XMP string is always null terminated.
189 if (xmp.back() != 0) {
190 xmp.push_back(0);
191 }
192
193 // compute XMP string length
194 size_t text_length = 0;
195 while (xmp[text_length] != 0) {
196 text_length++;
197 }
198
199 png_text xmp_text{}; // important to zero-initialize the structure so that the remaining fields are NULL !
200 xmp_text.compression = PNG_ITXT_COMPRESSION_NONE;
201 xmp_text.key = (char*) "XML:com.adobe.xmp";
202 xmp_text.text = (char*) xmp.data();
203 xmp_text.text_length = 0; // should be 0 for ITXT according the libpng documentation
204 xmp_text.itxt_length = text_length;
205 png_set_text(png_ptr, info_ptr, &xmp_text, 1);
206 }
207 }
208 #endif
209
210 png_write_info(png_ptr, info_ptr);
211
212 uint8_t** row_pointers = new uint8_t* [height];
213
214 size_t stride_rgb;
215 const uint8_t* row_rgb = heif_image_get_plane_readonly2(image,
216 heif_channel_interleaved, &stride_rgb);
217
218 for (int y = 0; y < height; ++y) {
219 row_pointers[y] = const_cast<uint8_t*>(&row_rgb[y * stride_rgb]);
220 }
221
222 if (bitDepth == 16) {
223 // shift image data to full 16bit range
224
225 int shift = 16 - input_bpp;
226 if (shift > 0) {
227 for (int y = 0; y < height; ++y) {
228 for (size_t x = 0; x < stride_rgb; x += 2) {
229 uint8_t* p = (&row_pointers[y][x]);
230 int v = (p[0] << 8) | p[1];
231 v = (v << shift) | (v >> (16 - shift));
232 p[0] = (uint8_t) (v >> 8);
233 p[1] = (uint8_t) (v & 0xFF);
234 }
235 }
236 }
237 }
238
239
240 png_write_image(png_ptr, row_pointers);
241
242 png_write_end(png_ptr, nullptr);
243 png_destroy_write_struct(&png_ptr, &info_ptr);
244 delete[] row_pointers;
245 fclose(fp);
246 return true;
247 }