Debian Codegraph @

heifio/decoder_jpeg.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 <memory>
28 #include <vector>
29 #include <cstdlib>
30 #include <cstring>
31 #include <cstdio>
32 #include <iostream>
33 #include <cassert>
34 #include <algorithm>
35 #include <array>
36 #include "decoder_jpeg.h"
37 #include "exif.h"
38
39 extern "C" {
40 // Prevent duplicate definition for libjpeg-turbo v2.0
41 // Note: these 'undef's are only a workaround for a libjpeg-turbo-v2.0 bug and
42 // should be removed again later. Bug has been fixed in libjpeg-turbo-v2.0.1.
43 #include <jconfig.h>
44 #if defined(LIBJPEG_TURBO_VERSION_NUMBER) && LIBJPEG_TURBO_VERSION_NUMBER == 2000000
45 #undef HAVE_STDDEF_H
46 #undef HAVE_STDLIB_H
47 #endif
48 #include <jpeglib.h>
49 }
50
51 #define JPEG_EXIF_MARKER (JPEG_APP0+1) /* JPEG marker code for EXIF */
52 #define JPEG_EXIF_MARKER_LEN 6 // "Exif/0/0"
53 #define JPEG_XMP_MARKER (JPEG_APP0+1) /* JPEG marker code for XMP */
54 #define JPEG_XMP_MARKER_ID "http://ns.adobe.com/xap/1.0/"
55 #define JPEG_ICC_MARKER (JPEG_APP0+2) /* JPEG marker code for ICC */
56 #define JPEG_ICC_OVERHEAD_LEN 14 /* size of non-profile data in APP2 */
57
58 static struct heif_error heif_error_ok = {heif_error_Ok, heif_suberror_Unspecified, "Success"};
59
60 static bool JPEGMarkerIsIcc(jpeg_saved_marker_ptr marker)
61 {
62 return
63 marker->marker == JPEG_ICC_MARKER &&
64 marker->data_length >= JPEG_ICC_OVERHEAD_LEN &&
65 /* verify the identifying string */
66 GETJOCTET(marker->data[0]) == 0x49 &&
67 GETJOCTET(marker->data[1]) == 0x43 &&
68 GETJOCTET(marker->data[2]) == 0x43 &&
69 GETJOCTET(marker->data[3]) == 0x5F &&
70 GETJOCTET(marker->data[4]) == 0x50 &&
71 GETJOCTET(marker->data[5]) == 0x52 &&
72 GETJOCTET(marker->data[6]) == 0x4F &&
73 GETJOCTET(marker->data[7]) == 0x46 &&
74 GETJOCTET(marker->data[8]) == 0x49 &&
75 GETJOCTET(marker->data[9]) == 0x4C &&
76 GETJOCTET(marker->data[10]) == 0x45 &&
77 GETJOCTET(marker->data[11]) == 0x0;
78 }
79
80 bool ReadICCProfileFromJPEG(j_decompress_ptr cinfo,
81 JOCTET** icc_data_ptr,
82 unsigned int* icc_data_len)
83 {
84 jpeg_saved_marker_ptr marker;
85 int num_markers = 0;
86 int seq_no;
87 JOCTET* icc_data;
88 unsigned int total_length;
89 #define MAX_SEQ_NO 255 /* sufficient since marker numbers are bytes */
90 char marker_present[MAX_SEQ_NO + 1]; /* 1 if marker found */
91 unsigned int data_length[MAX_SEQ_NO + 1]; /* size of profile data in marker */
92 unsigned int data_offset[MAX_SEQ_NO + 1]; /* offset for data in marker */
93
94 *icc_data_ptr = NULL; /* avoid confusion if FALSE return */
95 *icc_data_len = 0;
96
97 /* This first pass over the saved markers discovers whether there are
98 * any ICC markers and verifies the consistency of the marker numbering.
99 */
100
101 for (seq_no = 1; seq_no <= MAX_SEQ_NO; seq_no++)
102 marker_present[seq_no] = 0;
103
104 for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) {
105 if (JPEGMarkerIsIcc(marker)) {
106 if (num_markers == 0)
107 num_markers = GETJOCTET(marker->data[13]);
108 else if (num_markers != GETJOCTET(marker->data[13]))
109 return FALSE; /* inconsistent num_markers fields */
110 seq_no = GETJOCTET(marker->data[12]);
111 if (seq_no <= 0 || seq_no > num_markers)
112 return FALSE; /* bogus sequence number */
113 if (marker_present[seq_no])
114 return FALSE; /* duplicate sequence numbers */
115 marker_present[seq_no] = 1;
116 data_length[seq_no] = marker->data_length - JPEG_ICC_OVERHEAD_LEN;
117 }
118 }
119
120 if (num_markers == 0)
121 return FALSE;
122
123 /* Check for missing markers, count total space needed,
124 * compute offset of each marker's part of the data.
125 */
126
127 total_length = 0;
128 for (seq_no = 1; seq_no <= num_markers; seq_no++) {
129 if (marker_present[seq_no] == 0)
130 return FALSE; /* missing sequence number */
131 data_offset[seq_no] = total_length;
132 total_length += data_length[seq_no];
133 }
134
135 if (total_length <= 0)
136 return FALSE; /* found only empty markers? */
137
138 /* Allocate space for assembled data */
139 icc_data = (JOCTET*) malloc(total_length * sizeof(JOCTET));
140 if (icc_data == NULL)
141 return FALSE; /* oops, out of memory */
142
143 /* and fill it in */
144 for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) {
145 if (JPEGMarkerIsIcc(marker)) {
146 JOCTET FAR* src_ptr;
147 JOCTET* dst_ptr;
148 unsigned int length;
149 seq_no = GETJOCTET(marker->data[12]);
150 dst_ptr = icc_data + data_offset[seq_no];
151 src_ptr = marker->data + JPEG_ICC_OVERHEAD_LEN;
152 length = data_length[seq_no];
153 while (length--) {
154 *dst_ptr++ = *src_ptr++;
155 }
156 }
157 }
158
159 *icc_data_ptr = icc_data;
160 *icc_data_len = total_length;
161
162 return TRUE;
163 }
164
165
166 static bool JPEGMarkerIsXMP(jpeg_saved_marker_ptr marker)
167 {
168 return
169 marker->marker == JPEG_XMP_MARKER &&
170 marker->data_length >= strlen(JPEG_XMP_MARKER_ID) + 1 &&
171 strncmp((const char*) (marker->data), JPEG_XMP_MARKER_ID, strlen(JPEG_XMP_MARKER_ID)) == 0;
172 }
173
174 bool ReadXMPFromJPEG(j_decompress_ptr cinfo,
175 std::vector<uint8_t>& xmpData)
176 {
177 jpeg_saved_marker_ptr marker;
178
179 for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) {
180 if (JPEGMarkerIsXMP(marker)) {
181 int length = (int) (marker->data_length - (strlen(JPEG_XMP_MARKER_ID) + 1));
182 xmpData.resize(length);
183 memcpy(xmpData.data(), marker->data + strlen(JPEG_XMP_MARKER_ID) + 1, length);
184 return true;
185 }
186 }
187
188 return false;
189 }
190
191
192 static bool JPEGMarkerIsEXIF(jpeg_saved_marker_ptr marker)
193 {
194 return marker->marker == JPEG_EXIF_MARKER &&
195 marker->data_length >= JPEG_EXIF_MARKER_LEN &&
196 GETJOCTET(marker->data[0]) == 'E' &&
197 GETJOCTET(marker->data[1]) == 'x' &&
198 GETJOCTET(marker->data[2]) == 'i' &&
199 GETJOCTET(marker->data[3]) == 'f' &&
200 GETJOCTET(marker->data[4]) == 0 &&
201 GETJOCTET(marker->data[5]) == 0;
202 }
203
204 bool ReadEXIFFromJPEG(j_decompress_ptr cinfo,
205 std::vector<uint8_t>& exifData)
206 {
207 jpeg_saved_marker_ptr marker;
208
209 for (marker = cinfo->marker_list; marker != NULL; marker = marker->next) {
210 if (JPEGMarkerIsEXIF(marker)) {
211 int length = (int) (marker->data_length - JPEG_EXIF_MARKER_LEN);
212 exifData.resize(length);
213 memcpy(exifData.data(), marker->data + JPEG_EXIF_MARKER_LEN, length);
214 return true;
215 }
216 }
217
218 return false;
219 }
220
221
222 #if JPEG_LIB_VERSION < 70
223 #define DCT_h_scaled_size DCT_scaled_size
224 #define DCT_v_scaled_size DCT_scaled_size
225 #endif
226
227
228 heif_error loadJPEG(const char *filename, InputImage *input_image)
229 {
230 struct heif_image* image = nullptr;
231 struct heif_error err = heif_error_ok;
232
233 // ### Code copied from LibVideoGfx and slightly modified to use HeifPixelImage
234
235 struct jpeg_decompress_struct cinfo;
236 struct jpeg_error_mgr jerr;
237
238 // to store embedded icc profile
239 uint32_t iccLen;
240 uint8_t* iccBuffer = NULL;
241
242 std::vector<uint8_t> xmpData;
243 std::vector<uint8_t> exifData;
244
245 // open input file
246
247 FILE* infile;
248 if ((infile = fopen(filename, "rb")) == NULL) {
249 struct heif_error err = {
250 .code = heif_error_Invalid_input,
251 .subcode = heif_suberror_Unspecified,
252 .message = "Cannot open JPEG file"};
253 return err;
254 }
255
256
257 // initialize decompressor
258
259 jpeg_create_decompress(&cinfo);
260
261 cinfo.err = jpeg_std_error(&jerr);
262 jpeg_stdio_src(&cinfo, infile);
263
264 /* Adding this part to prepare for icc profile reading. */
265 jpeg_save_markers(&cinfo, JPEG_ICC_MARKER, 0xFFFF);
266 jpeg_save_markers(&cinfo, JPEG_XMP_MARKER, 0xFFFF);
267 jpeg_save_markers(&cinfo, JPEG_EXIF_MARKER, 0xFFFF);
268
269 jpeg_read_header(&cinfo, TRUE);
270
271 bool embeddedIccFlag = ReadICCProfileFromJPEG(&cinfo, &iccBuffer, &iccLen);
272 bool embeddedXMPFlag = ReadXMPFromJPEG(&cinfo, xmpData);
273 if (embeddedXMPFlag) {
274 input_image->xmp = xmpData;
275 }
276
277 bool embeddedEXIFFlag = ReadEXIFFromJPEG(&cinfo, exifData);
278 if (embeddedEXIFFlag) {
279 input_image->exif = exifData;
280 input_image->orientation = (heif_orientation) read_exif_orientation_tag(exifData.data(), (int) exifData.size());
281 }
282
283 if (cinfo.jpeg_color_space == JCS_GRAYSCALE) {
284 cinfo.out_color_space = JCS_GRAYSCALE;
285
286 jpeg_start_decompress(&cinfo);
287
288 JSAMPARRAY buffer;
289 buffer = (*cinfo.mem->alloc_sarray)
290 ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width * cinfo.output_components, 1);
291
292
293 // create destination image
294
295 err = heif_image_create(cinfo.output_width, cinfo.output_height,
296 heif_colorspace_monochrome,
297 heif_chroma_monochrome,
298 &image);
299 if (err.code) {
300 goto cleanup;
301 }
302
303 err = heif_image_add_plane(image, heif_channel_Y, cinfo.output_width, cinfo.output_height, 8);
304 if (err.code) { goto cleanup; }
305
306 size_t y_stride;
307 uint8_t* py = heif_image_get_plane2(image, heif_channel_Y, &y_stride);
308
309
310 // read the image
311
312 while (cinfo.output_scanline < cinfo.output_height) {
313 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
314
315 memcpy(py + (cinfo.output_scanline - 1) * y_stride, *buffer, cinfo.output_width);
316 }
317 }
318 else if (cinfo.jpeg_color_space == JCS_YCbCr) {
319 cinfo.out_color_space = JCS_YCbCr;
320
321 bool read_raw = false;
322 heif_chroma output_chroma = heif_chroma_420;
323
324 if (cinfo.comp_info[1].h_samp_factor == 1 &&
325 cinfo.comp_info[1].v_samp_factor == 1 &&
326 cinfo.comp_info[2].h_samp_factor == 1 &&
327 cinfo.comp_info[2].v_samp_factor == 1) {
328
329 if (cinfo.comp_info[0].h_samp_factor == 1 &&
330 cinfo.comp_info[0].v_samp_factor == 1) {
331 output_chroma = heif_chroma_444;
332 read_raw = true;
333 }
334 else if (cinfo.comp_info[0].h_samp_factor == 2 &&
335 cinfo.comp_info[0].v_samp_factor == 1) {
336 output_chroma = heif_chroma_422;
337 read_raw = true;
338 }
339 else if (cinfo.comp_info[0].h_samp_factor == 2 &&
340 cinfo.comp_info[0].v_samp_factor == 2) {
341 output_chroma = heif_chroma_420;
342 read_raw = true;
343 }
344 }
345
346 int cw=0,ch=0;
347 switch (output_chroma) {
348 case heif_chroma_420:
349 cw = (cinfo.image_width + 1) / 2;
350 ch = (cinfo.image_height + 1) / 2;
351 break;
352 case heif_chroma_422:
353 cw = (cinfo.image_width + 1) / 2;
354 ch = cinfo.image_height;
355 break;
356 case heif_chroma_444:
357 cw = cinfo.image_width;
358 ch = cinfo.image_height;
359 break;
360 default:
361 assert(false);
362 }
363
364 //read_raw = false;
365
366 cinfo.raw_data_out = boolean(read_raw);
367
368 jpeg_start_decompress(&cinfo);
369
370
371 // create destination image
372
373 struct heif_error err = heif_image_create(cinfo.output_width, cinfo.output_height,
374 heif_colorspace_YCbCr,
375 output_chroma,
376 &image);
377 if (err.code) { goto cleanup; }
378
379 err = heif_image_add_plane(image, heif_channel_Y, cinfo.output_width, cinfo.output_height, 8);
380 if (err.code) { goto cleanup; }
381
382 err = heif_image_add_plane(image, heif_channel_Cb, cw, ch, 8);
383 if (err.code) { goto cleanup; }
384
385 err = heif_image_add_plane(image, heif_channel_Cr, cw, ch, 8);
386 if (err.code) { goto cleanup; }
387
388 size_t stride[3];
389 uint8_t* p[3];
390 p[0] = heif_image_get_plane2(image, heif_channel_Y, &stride[0]);
391 p[1] = heif_image_get_plane2(image, heif_channel_Cb, &stride[1]);
392 p[2] = heif_image_get_plane2(image, heif_channel_Cr, &stride[2]);
393
394 // read the image
395
396 if (read_raw) {
397 // adapted from https://github.com/AOMediaCodec/libavif/blob/430ea2df584dcb95ff1632c17643ebbbb2f3bc81/apps/shared/avifjpeg.c
398
399 JSAMPIMAGE buffer;
400 buffer = (JSAMPIMAGE)(cinfo.mem->alloc_small)((j_common_ptr)&cinfo, JPOOL_IMAGE, sizeof(JSAMPARRAY) * cinfo.num_components);
401
402 // lines of output image to be read per jpeg_read_raw_data call
403 int readLines = 0;
404 // lines of samples to be read per call (for each channel)
405 int linesPerCall[3] = { 0, 0, 0 };
406 // expected count of sample lines (for each channel)
407 int targetRead[3] = { 0, 0, 0 };
408 for (int i = 0; i < cinfo.num_components; ++i) {
409 jpeg_component_info * comp = &cinfo.comp_info[i];
410
411 linesPerCall[i] = comp->v_samp_factor * comp->DCT_v_scaled_size;
412 targetRead[i] = comp->downsampled_height;
413 buffer[i] = (cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo,
414 JPOOL_IMAGE,
415 comp->width_in_blocks * comp->DCT_h_scaled_size,
416 linesPerCall[i]);
417 readLines = std::max(readLines, linesPerCall[i]);
418 }
419
420 // count of already-read lines (for each channel)
421 int alreadyRead[3] = { 0, 0, 0 };
422 int width[3] = { (int)cinfo.output_width, cw, cw};
423
424 std::array<int,3> targetChannel{0,1,2};
425
426 if (cinfo.jpeg_color_space == JCS_RGB) {
427 targetChannel = {2, 0, 1};
428 }
429 else if (cinfo.jpeg_color_space == JCS_YCbCr ||
430 cinfo.jpeg_color_space == JCS_GRAYSCALE) {
431 targetChannel = {0, 1, 2};
432 }
433 else {
434 return heif_error{heif_error_Unsupported_filetype,
435 heif_suberror_Unsupported_image_type,
436 "JPEG with unsupported colorspace"};
437 }
438
439 while (cinfo.output_scanline < cinfo.output_height) {
440 jpeg_read_raw_data(&cinfo, buffer, readLines);
441
442 int workComponents = 3;
443
444 for (int i = 0; i < workComponents; ++i) {
445 int linesRead = std::min(targetRead[i] - alreadyRead[i], linesPerCall[i]);
446
447 for (int j = 0; j < linesRead; ++j) {
448 memcpy(p[targetChannel[i]] + ((size_t)stride[targetChannel[i]]) * (alreadyRead[i] + j),
449 buffer[i][j],
450 width[targetChannel[i]]);
451 }
452 alreadyRead[i] += linesPerCall[i];
453 }
454 }
455 }
456 else {
457 JSAMPARRAY buffer;
458 buffer = (*cinfo.mem->alloc_sarray)
459 ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width * cinfo.output_components, 1);
460
461 while (cinfo.output_scanline < cinfo.output_height) {
462 JOCTET* bufp;
463
464 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
465
466 bufp = buffer[0];
467
468 size_t y = cinfo.output_scanline - 1;
469
470 for (unsigned int x = 0; x < cinfo.output_width; x += 2) {
471 p[0][y * stride[0] + x] = *bufp++;
472 p[1][y / 2 * stride[1] + x / 2] = *bufp++;
473 p[2][y / 2 * stride[2] + x / 2] = *bufp++;
474
475 if (x + 1 < cinfo.output_width) {
476 p[0][y * stride[0] + x + 1] = *bufp++;
477 }
478
479 bufp += 2;
480 }
481
482
483 if (cinfo.output_scanline < cinfo.output_height) {
484 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
485
486 bufp = buffer[0];
487
488 y = cinfo.output_scanline - 1;
489
490 for (unsigned int x = 0; x < cinfo.output_width; x++) {
491 p[0][y * stride[0] + x] = *bufp++;
492 bufp += 2;
493 }
494 }
495 }
496 }
497 }
498 else {
499 // TODO: error, unsupported JPEG colorspace
500 }
501
502 if (embeddedIccFlag && iccLen > 0) {
503 heif_image_set_raw_color_profile(image, "prof", iccBuffer, (size_t) iccLen);
504 }
505
506 input_image->image = std::shared_ptr<heif_image>(image,
507 [](heif_image* img) { heif_image_release(img); });
508
509 // cleanup
510 cleanup:
511 free(iccBuffer);
512 jpeg_finish_decompress(&cinfo);
513 jpeg_destroy_decompress(&cinfo);
514
515 fclose(infile);
516
517 return err;
518 }