Blender V5.3
format_jpeg.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9/* This little block needed for linking to Blender... */
10#include <algorithm>
11#include <csetjmp>
12#include <cstdio>
13#include <limits>
14
15#include "MEM_guardedalloc.h"
16
17#include "BLI_fileops.hh"
18#include "BLI_listbase.hh"
19#include "BLI_math_base.hh"
20#include "BLI_string.hh"
21#include "BLI_string_utf8.hh"
22#include "BLI_utildefines.hh"
23
24#include "BKE_idprop.hh"
25
26#include "DNA_ID.h" /* ID property definitions. */
27
29#include "IMB_filetype.hh"
30#include "IMB_imbuf.hh"
31#include "IMB_imbuf_types.hh"
32#include "IMB_metadata.hh"
33
34#include "CLG_log.h"
35
36#include <cstring>
37#include <jerror.h>
38#include <jpeglib.h>
39
40namespace blender {
41
42const char *imb_file_extensions_jpeg[] = {".jpg", ".jpeg", nullptr};
43
44static CLG_LogRef LOG = {"image.jpeg"};
45
46/* the types are from the jpeg lib */
47static void jpeg_error(j_common_ptr cinfo) ATTR_NORETURN;
48static void init_source(j_decompress_ptr cinfo);
49static boolean fill_input_buffer(j_decompress_ptr cinfo);
50static void skip_input_data(j_decompress_ptr cinfo, long num_bytes);
51static void term_source(j_decompress_ptr cinfo);
52static void memory_source(j_decompress_ptr cinfo, const uchar *buffer, size_t size);
53static boolean handle_app1(j_decompress_ptr cinfo);
54
55static const uchar jpeg_default_quality = 75;
57
58/* -------------------------------------------------------------------- */
61
62bool imb_is_a_jpeg(const uchar *mem, const size_t size)
63{
64 const char magic[2] = {0xFF, 0xD8};
65 if (size < sizeof(magic)) {
66 return false;
67 }
68 return memcmp(mem, magic, sizeof(magic)) == 0;
69}
70
72
73/* -------------------------------------------------------------------- */
76
78 jpeg_error_mgr pub; /* "public" fields */
79
80 jmp_buf setjmp_buffer; /* for return to caller */
81};
82
84
85static void jpeg_error(j_common_ptr cinfo)
86{
87 my_error_ptr err = reinterpret_cast<my_error_ptr>(cinfo->err);
88
89 /* Always display the message */
90 (*cinfo->err->output_message)(cinfo);
91
92 /* Let the memory manager delete any temp files before we die */
93 jpeg_destroy(cinfo);
94
95 /* return control to the setjmp point */
96 longjmp(err->setjmp_buffer, 1);
97}
98
100
101/* -------------------------------------------------------------------- */
104
106 jpeg_source_mgr pub; /* public fields */
107
108 const uchar *buffer;
109 int size;
110 JOCTET terminal[2];
111};
112
114
115static void init_source(j_decompress_ptr cinfo)
116{
117 (void)cinfo; /* unused */
118}
119
120static boolean fill_input_buffer(j_decompress_ptr cinfo)
121{
122 my_src_ptr src = reinterpret_cast<my_src_ptr>(cinfo->src);
123
124 /* Since we have given all we have got already
125 * we simply fake an end of file
126 */
127
128 src->pub.next_input_byte = src->terminal;
129 src->pub.bytes_in_buffer = 2;
130 src->terminal[0] = JOCTET(0xFF);
131 src->terminal[1] = JOCTET(JPEG_EOI);
132
133 return true;
134}
135
136static void skip_input_data(j_decompress_ptr cinfo, long num_bytes)
137{
138 my_src_ptr src = reinterpret_cast<my_src_ptr>(cinfo->src);
139
140 if (num_bytes > 0) {
141 /* prevent skipping over file end */
142 size_t skip_size = size_t(num_bytes) <= src->pub.bytes_in_buffer ? num_bytes :
143 src->pub.bytes_in_buffer;
144
145 src->pub.next_input_byte = src->pub.next_input_byte + skip_size;
146 src->pub.bytes_in_buffer = src->pub.bytes_in_buffer - skip_size;
147 }
148}
149
150static void term_source(j_decompress_ptr cinfo)
151{
152 (void)cinfo; /* unused */
153}
154
155static void memory_source(j_decompress_ptr cinfo, const uchar *buffer, size_t size)
156{
157 my_src_ptr src;
158
159 if (cinfo->src == nullptr) { /* first time for this JPEG object? */
160 cinfo->src = static_cast<jpeg_source_mgr *>((*cinfo->mem->alloc_small)(
161 reinterpret_cast<j_common_ptr>(cinfo), JPOOL_PERMANENT, sizeof(my_source_mgr)));
162 }
163
164 src = reinterpret_cast<my_src_ptr>(cinfo->src);
165 src->pub.init_source = init_source;
166 src->pub.fill_input_buffer = fill_input_buffer;
167 src->pub.skip_input_data = skip_input_data;
168 src->pub.resync_to_restart = jpeg_resync_to_restart;
169 src->pub.term_source = term_source;
170
171 src->pub.bytes_in_buffer = size;
172 src->pub.next_input_byte = buffer;
173
174 src->buffer = buffer;
175 src->size = size;
176}
177
179
180/* -------------------------------------------------------------------- */
183
184#define MAKESTMT(stuff) \
185 do { \
186 stuff \
187 } while (0)
188
189#define INPUT_VARS(cinfo) \
190 jpeg_source_mgr *datasrc = (cinfo)->src; \
191 const JOCTET *next_input_byte = datasrc->next_input_byte; \
192 size_t bytes_in_buffer = datasrc->bytes_in_buffer
193
194/* Unload the local copies --- do this only at a restart boundary */
195#define INPUT_SYNC(cinfo) \
196 (datasrc->next_input_byte = next_input_byte, datasrc->bytes_in_buffer = bytes_in_buffer)
197
198/* Reload the local copies --- seldom used except in MAKE_BYTE_AVAIL */
199#define INPUT_RELOAD(cinfo) \
200 (next_input_byte = datasrc->next_input_byte, bytes_in_buffer = datasrc->bytes_in_buffer)
201
202/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
203 * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
204 * but we must reload the local copies after a successful fill.
205 */
206#define MAKE_BYTE_AVAIL(cinfo, action) \
207 if (bytes_in_buffer == 0) { \
208 if (!(*datasrc->fill_input_buffer)(cinfo)) { \
209 action; \
210 } \
211 INPUT_RELOAD(cinfo); \
212 } \
213 (void)0
214
215/* Read a byte into variable V.
216 * If must suspend, take the specified action (typically "return false").
217 */
218#define INPUT_BYTE(cinfo, V, action) \
219 MAKESTMT(MAKE_BYTE_AVAIL(cinfo, action); bytes_in_buffer--; V = GETJOCTET(*next_input_byte++);)
220
221/* As above, but read two bytes interpreted as an unsigned 16-bit integer.
222 * V should be declared `uint` or perhaps INT32.
223 */
224#define INPUT_2BYTES(cinfo, V, action) \
225 MAKESTMT(MAKE_BYTE_AVAIL(cinfo, action); bytes_in_buffer--; \
226 V = uint(GETJOCTET(*next_input_byte++)) << 8; \
227 MAKE_BYTE_AVAIL(cinfo, action); \
228 bytes_in_buffer--; \
229 V += GETJOCTET(*next_input_byte++);)
230
237BLI_STATIC_ASSERT(sizeof(NeoGeo_Word) == 4, "Must be 4 bytes");
238
239static boolean handle_app1(j_decompress_ptr cinfo)
240{
241 INT32 length; /* initialized by the macro */
242 INT32 i;
243 char neogeo[128];
244
245 INPUT_VARS(cinfo);
246
247 INPUT_2BYTES(cinfo, length, return false);
248 length -= 2;
249
250 if (length < 16) {
251 for (i = 0; i < length; i++) {
252 INPUT_BYTE(cinfo, neogeo[i], return false);
253 }
254 length = 0;
255 if (STRPREFIX(neogeo, "NeoGeo")) {
256 NeoGeo_Word *neogeo_word = reinterpret_cast<NeoGeo_Word *>(neogeo + 6);
257 ibuf_quality = neogeo_word->quality;
258 }
259 }
260 INPUT_SYNC(cinfo); /* do before skip_input_data */
261 if (length > 0) {
262 (*cinfo->src->skip_input_data)(cinfo, length);
263 }
264 return true;
265}
266
268
269/* -------------------------------------------------------------------- */
272
273static ImBuf *ibJpegImageFromCinfo(jpeg_decompress_struct *cinfo,
274 ImBufFlags flags,
275 int max_size,
276 size_t *r_width,
277 size_t *r_height)
278{
279 JSAMPARRAY row_pointer;
280 JSAMPLE *buffer = nullptr;
281 int row_stride;
282 int x, y, depth, r, g, b, k;
283 ImBuf *ibuf = nullptr;
284 uchar *rect;
285 jpeg_saved_marker_ptr marker;
286 char *str, *key, *value;
287
288 /* install own app1 handler */
290 jpeg_set_marker_processor(cinfo, 0xe1, handle_app1);
291 cinfo->dct_method = JDCT_FLOAT;
292 jpeg_save_markers(cinfo, JPEG_COM, 0xffff);
293
294 if (jpeg_read_header(cinfo, false) == JPEG_HEADER_OK) {
295 depth = cinfo->num_components;
296
297 if (cinfo->jpeg_color_space == JCS_YCCK) {
298 cinfo->out_color_space = JCS_CMYK;
299 }
300
301 if (r_width) {
302 *r_width = cinfo->image_width;
303 }
304 if (r_height) {
305 *r_height = cinfo->image_height;
306 }
307
308 if (max_size > 0) {
309 /* `libjpeg` can more quickly decompress while scaling down to 1/2, 1/4, 1/8,
310 * while `libjpeg-turbo` can also do 3/8, 5/8, etc. But max is 1/8. */
311 float scale = float(max_size) / std::max(cinfo->image_width, cinfo->image_height);
312 cinfo->scale_denom = 8;
313 cinfo->scale_num = max_uu(1, min_uu(8, ceill(scale * float(cinfo->scale_denom))));
314 cinfo->dct_method = JDCT_FASTEST;
315 cinfo->dither_mode = JDITHER_ORDERED;
316 }
317
318 jpeg_start_decompress(cinfo);
319
320 x = cinfo->output_width;
321 y = cinfo->output_height;
322
323 ImColorMode color_mode = ImColorMode::RGBA;
324 if (depth == 1) {
325 color_mode = ImColorMode::BW;
326 }
327 else if (depth == 3) {
328 color_mode = ImColorMode::RGB;
329 }
330
331 if (flag_is_set(flags, ImBufFlags::Test)) {
332 jpeg_abort_decompress(cinfo);
334 if (ibuf) {
335 ibuf->color_mode = color_mode;
336 }
337 }
338 else if ((ibuf = IMB_allocImBuf(
340 {
341 jpeg_abort_decompress(cinfo);
342 }
343 else {
344 ibuf->color_mode = color_mode;
345 row_stride = cinfo->output_width * depth;
346
347 row_pointer = (*cinfo->mem->alloc_sarray)(
348 reinterpret_cast<j_common_ptr>(cinfo), JPOOL_IMAGE, row_stride, 1);
349
350 uchar *byte_data = ibuf->byte_data_for_write();
351 for (y = ibuf->y - 1; y >= 0; y--) {
352 jpeg_read_scanlines(cinfo, row_pointer, 1);
353 rect = byte_data + 4 * y * size_t(ibuf->x);
354 buffer = row_pointer[0];
355
356 switch (depth) {
357 case 1:
358 for (x = ibuf->x; x > 0; x--) {
359 rect[3] = 255;
360 rect[0] = rect[1] = rect[2] = *buffer++;
361 rect += 4;
362 }
363 break;
364 case 3:
365 for (x = ibuf->x; x > 0; x--) {
366 rect[3] = 255;
367 rect[0] = *buffer++;
368 rect[1] = *buffer++;
369 rect[2] = *buffer++;
370 rect += 4;
371 }
372 break;
373 case 4:
374 for (x = ibuf->x; x > 0; x--) {
375 r = *buffer++;
376 g = *buffer++;
377 b = *buffer++;
378 k = *buffer++;
379
380 r = (r * k) / 255;
381 g = (g * k) / 255;
382 b = (b * k) / 255;
383
384 rect[3] = 255;
385 rect[2] = b;
386 rect[1] = g;
387 rect[0] = r;
388 rect += 4;
389 }
390 break;
391 }
392 }
393
394 marker = cinfo->marker_list;
395 while (marker) {
396 if (marker->marker != JPEG_COM) {
397 goto next_stamp_marker;
398 }
399
400 /*
401 * JPEG marker strings are not meant to be null-terminated,
402 * create a null-terminated copy before going further.
403 *
404 * Files saved from Blender pre v4.0 were null terminated,
405 * use `BLI_strnlen` to prevent assertion on passing in too short a string. */
407 reinterpret_cast<const char *>(marker->data),
408 BLI_strnlen(reinterpret_cast<const char *>(marker->data), marker->data_length));
409
410 /*
411 * Because JPEG format don't support the
412 * pair "key/value" like PNG, we store the
413 * stamp-info in a single "encode" string:
414 * "Blender:key:value"
415 *
416 * That is why we need split it to the
417 * common key/value here.
418 */
419 if (!STRPREFIX(str, "Blender")) {
420 /*
421 * Maybe the file have text that
422 * we don't know "what it's", in that
423 * case we keep the text (with a
424 * key "None").
425 * This is only for don't "lose"
426 * the information when we write
427 * it back to disk.
428 */
431 MEM_delete(str);
432 goto next_stamp_marker;
433 }
434
435 key = strchr(str, ':');
436 /*
437 * A little paranoid, but the file maybe
438 * is broken... and a "extra" check is better then a segfault :)
439 */
440 if (!key) {
441 MEM_delete(str);
442 goto next_stamp_marker;
443 }
444
445 key++;
446 value = strchr(key, ':');
447 if (!value) {
448 MEM_delete(str);
449 goto next_stamp_marker;
450 }
451
452 *value = '\0'; /* need finish the key string */
453 value++;
454 IMB_metadata_set_field(ibuf->metadata_for_write(), key, value);
456 MEM_delete(str);
457 next_stamp_marker:
458 marker = marker->next;
459 }
460
461 jpeg_finish_decompress(cinfo);
462 }
463
464 if (ibuf) {
465 /* Density_unit may be 0 for unknown, 1 for dots/inch, or 2 for dots/cm. */
466 if (cinfo->density_unit == 1) {
467 /* Convert inches to meters. */
468 ibuf->ppm[0] = double(cinfo->X_density) / 0.0254;
469 ibuf->ppm[1] = double(cinfo->Y_density) / 0.0254;
470 }
471 else if (cinfo->density_unit == 2) {
472 ibuf->ppm[0] = double(cinfo->X_density) * 100.0;
473 ibuf->ppm[1] = double(cinfo->Y_density) * 100.0;
474 }
475
476 ibuf->ftype = IMB_FTYPE_JPG;
477 ibuf->foptions.quality = std::min<char>(ibuf_quality, 100);
478 }
479 jpeg_destroy(reinterpret_cast<j_common_ptr>(cinfo));
480 }
481
482 return ibuf;
483}
484
485ImBuf *imb_load_jpeg(const uchar *buffer,
486 size_t size,
487 ImBufFlags flags,
488 ImFileColorSpace & /*r_colorspace*/)
489{
490 jpeg_decompress_struct _cinfo, *cinfo = &_cinfo;
491 my_error_mgr jerr;
492 ImBuf *ibuf;
493
494 if (!imb_is_a_jpeg(buffer, size)) {
495 return nullptr;
496 }
497
498 cinfo->err = jpeg_std_error(&jerr.pub);
499 jerr.pub.error_exit = jpeg_error;
500
501 /* Establish the setjmp return context for my_error_exit to use. */
502 if (setjmp(jerr.setjmp_buffer)) {
503 /* If we get here, the JPEG code has signaled an error.
504 * We need to clean up the JPEG object, close the input file, and return.
505 */
506 jpeg_destroy_decompress(cinfo);
507 return nullptr;
508 }
509
510 jpeg_create_decompress(cinfo);
511 memory_source(cinfo, buffer, size);
512
513 ibuf = ibJpegImageFromCinfo(cinfo, flags, -1, nullptr, nullptr);
514
515 return ibuf;
516}
517
519
520/* -------------------------------------------------------------------- */
523
524/* Defines for JPEG Header markers and segment size. */
525#define JPEG_MARKER_MSB (0xFF)
526#define JPEG_MARKER_SOI (0xD8)
527#define JPEG_MARKER_APP1 (0xE1)
528#define JPEG_APP1_MAX (1 << 16)
529
530ImBuf *imb_thumbnail_jpeg(const char *filepath,
531 const ImBufFlags flags,
532 const size_t max_thumb_size,
533 ImFileColorSpace &r_colorspace,
534 size_t *r_width,
535 size_t *r_height)
536{
537 jpeg_decompress_struct _cinfo, *cinfo = &_cinfo;
538 my_error_mgr jerr;
539 FILE *infile = nullptr;
540
541 cinfo->err = jpeg_std_error(&jerr.pub);
542 jerr.pub.error_exit = jpeg_error;
543
544 /* Establish the setjmp return context for my_error_exit to use. */
545 if (setjmp(jerr.setjmp_buffer)) {
546 /* If we get here, the JPEG code has signaled an error.
547 * We need to clean up the JPEG object, close the input file, and return.
548 */
549 jpeg_destroy_decompress(cinfo);
550 return nullptr;
551 }
552
553 if ((infile = BLI_fopen(filepath, "rb")) == nullptr) {
554 CLOG_ERROR(&LOG, "Cannot open \"%s\"", filepath);
555 return nullptr;
556 }
557
558 /* If file contains an embedded thumbnail, let's return that instead. */
559
560 if ((fgetc(infile) == JPEG_MARKER_MSB) && (fgetc(infile) == JPEG_MARKER_SOI) &&
561 (fgetc(infile) == JPEG_MARKER_MSB) && (fgetc(infile) == JPEG_MARKER_APP1))
562 {
563 /* This is a JPEG in EXIF format (SOI + APP1), not JFIF (SOI + APP0). */
565 /* All EXIF data is within this 64K header segment. Skip ahead until next SOI for thumbnail. */
566 while (!((fgetc(infile) == JPEG_MARKER_MSB) && (fgetc(infile) == JPEG_MARKER_SOI)) &&
567 !feof(infile) && i--)
568 {
569 }
570 if (i > 0 && !feof(infile)) {
571 /* We found a JPEG thumbnail inside this image. */
572 ImBuf *ibuf = nullptr;
573 uchar *buffer = MEM_new_array_zeroed<uchar>(JPEG_APP1_MAX, "thumbbuffer");
574 /* Just put SOI directly in buffer rather than seeking back 2 bytes. */
575 buffer[0] = JPEG_MARKER_MSB;
576 buffer[1] = JPEG_MARKER_SOI;
577 if (fread(buffer + 2, JPEG_APP1_MAX - 2, 1, infile) == 1) {
578 ibuf = imb_load_jpeg(buffer, JPEG_APP1_MAX, flags, r_colorspace);
579 }
580 MEM_SAFE_DELETE(buffer);
581 if (ibuf) {
582 fclose(infile);
583 return ibuf;
584 }
585 }
586 }
587
588 /* No embedded thumbnail found, so let's create a new one. */
589
590 fseek(infile, 0, SEEK_SET);
591 jpeg_create_decompress(cinfo);
592
593 jpeg_stdio_src(cinfo, infile);
594 ImBuf *ibuf = ibJpegImageFromCinfo(cinfo, flags, max_thumb_size, r_width, r_height);
595 fclose(infile);
596
597 return ibuf;
598}
599
600#undef JPEG_MARKER_MSB
601#undef JPEG_MARKER_SOI
602#undef JPEG_MARKER_APP1
603#undef JPEG_APP1_MAX
604
606
607/* -------------------------------------------------------------------- */
610
611/* `libjpeg` has a maximum comment/marker length of 65533, however it does not provide a definition
612 * for that, so we hard-code it ourselves. */
613#define MAX_LIBJPEG_MARKER_LENGTH 65533
614
615static void write_jpeg(jpeg_compress_struct *cinfo, ImBuf *ibuf)
616{
617 JSAMPLE *buffer = nullptr;
618 JSAMPROW row_pointer[1];
619 int x, y;
620 char neogeo[128];
621 NeoGeo_Word *neogeo_word;
622
623 jpeg_start_compress(cinfo, true);
624
625 STRNCPY_UTF8(neogeo, "NeoGeo");
626 neogeo_word = reinterpret_cast<NeoGeo_Word *>(neogeo + 6);
627 memset(neogeo_word, 0, sizeof(*neogeo_word));
628 neogeo_word->quality = ibuf->foptions.quality;
629 jpeg_write_marker(cinfo, 0xe1, reinterpret_cast<JOCTET *>(neogeo), 10);
630 if (ibuf->metadata()) {
631
632 /* Static storage array for the short metadata. */
633 char static_text[1024];
634 const size_t static_text_size = ARRAY_SIZE(static_text);
635 for (IDProperty &prop : ibuf->metadata()->data.group) {
636 if (prop.type == IDP_STRING) {
637 size_t text_len;
638 if (STREQ(prop.name, "None")) {
639 jpeg_write_marker(
640 cinfo, JPEG_COM, reinterpret_cast<JOCTET *> IDP_string_get(&prop), prop.len);
641 }
642
643 char *text = static_text;
644 size_t text_size = static_text_size;
645 /* 7 is for Blender, 2 colon separators, length of property
646 * name and property value, followed by the nullptr-terminator
647 * which isn't needed by JPEG but #BLI_snprintf_rlen requires it. */
648 const size_t text_length_required = 7 + 2 + strlen(prop.name) +
649 strlen(IDP_string_get(&prop)) + 1;
650 if (text_length_required > static_text_size) {
651 text = MEM_new_array_uninitialized<char>(text_length_required, "jpeg metadata field");
652 text_size = text_length_required;
653 }
654
655 /*
656 * The JPEG format don't support a pair "key/value"
657 * like PNG, so we "encode" the stamp in a
658 * single string:
659 * "Blender:key:value"
660 *
661 * The first "Blender" is a simple identify to help
662 * in the read process.
663 */
664 text_len = BLI_snprintf_utf8_rlen(
665 text, text_size, "Blender:%s:%s", prop.name, IDP_string_get(&prop));
666 /* Truncate the data if it does not fit in a single marker, as giving a buffer to `libjpeg`
667 * bigger that #MAX_LIBJPEG_MARKER_LENGTH will result in the JPEG file not being written.
668 * See #158751.
669 */
670 if (text_len > MAX_LIBJPEG_MARKER_LENGTH) {
671 CLOG_WARN(&LOG, "Writing truncated data for \"%s\"", prop.name);
672 text_len = MAX_LIBJPEG_MARKER_LENGTH;
673 }
674 /* Don't write the null byte (not expected by the JPEG format). */
675 jpeg_write_marker(cinfo, JPEG_COM, reinterpret_cast<JOCTET *>(text), uint(text_len));
676
677 /* TODO(sergey): Ideally we will try to re-use allocation as
678 * much as possible. In practice, such long fields don't happen
679 * often. */
680 if (text != static_text) {
681 MEM_delete(text);
682 }
683 }
684 }
685 }
686
687 /* Write ICC profile if there is one associated with the colorspace.
688 * Our profiles are only valid for RGB channels. */
690 if (colorspace && cinfo->in_color_space == JCS_RGB) {
692 if (!icc_profile.is_empty()) {
693 icc_profile.prepend({'I', 'C', 'C', '_', 'P', 'R', 'O', 'F', 'I', 'L', 'E', 0, 0, 1});
694 jpeg_write_marker(cinfo,
695 JPEG_APP0 + 2,
696 reinterpret_cast<const JOCTET *>(icc_profile.data()),
697 icc_profile.size());
698 }
699 }
700
702 size_t(cinfo->input_components) * size_t(cinfo->image_width), "jpeg row_pointer");
703
704 const uchar *byte_data = ibuf->byte_data();
705 for (y = ibuf->y - 1; y >= 0; y--) {
706 const uchar *rect = byte_data + 4 * y * size_t(ibuf->x);
707 buffer = row_pointer[0];
708
709 switch (cinfo->in_color_space) {
710 case JCS_RGB:
711 for (x = 0; x < ibuf->x; x++) {
712 *buffer++ = rect[0];
713 *buffer++ = rect[1];
714 *buffer++ = rect[2];
715 rect += 4;
716 }
717 break;
718 case JCS_GRAYSCALE:
719 for (x = 0; x < ibuf->x; x++) {
720 *buffer++ = rect[0];
721 rect += 4;
722 }
723 break;
724 case JCS_UNKNOWN:
725 memcpy(buffer, rect, 4 * ibuf->x);
726 break;
727 /* default was missing... intentional ? */
728 default:
729 /* do nothing */
730 break;
731 }
732
733 jpeg_write_scanlines(cinfo, row_pointer, 1);
734 }
735
736 jpeg_finish_compress(cinfo);
737 MEM_delete(row_pointer[0]);
738}
739
746static double jpeg_density_from_ppm(const double ppm[2],
747 const double unit_scale,
748 UINT16 r_density[2])
749{
750 double error = 0.0;
751 for (int i = 0; i < 2; i++) {
752 const double density = ppm[i] * unit_scale;
753 const double density_round = math::round(density);
754 if (!(density_round >= 1.0 && density_round <= double(std::numeric_limits<UINT16>::max()))) {
755 return std::numeric_limits<double>::max();
756 }
757 r_density[i] = UINT16(density_round);
758 error += math::abs(density_round - density) / density;
759 }
760 return error;
761}
762
763static int init_jpeg(FILE *outfile, jpeg_compress_struct *cinfo, ImBuf *ibuf)
764{
765 int quality;
766
767 quality = ibuf->foptions.quality;
768 if (quality <= 0) {
769 quality = jpeg_default_quality;
770 }
771 quality = std::min(quality, 100);
772
773 jpeg_create_compress(cinfo);
774 jpeg_stdio_dest(cinfo, outfile);
775
776 cinfo->image_width = ibuf->x;
777 cinfo->image_height = ibuf->y;
778
779 cinfo->in_color_space = JCS_RGB;
780 if (ibuf->color_mode == ImColorMode::BW) {
781 cinfo->in_color_space = JCS_GRAYSCALE;
782 }
783 switch (cinfo->in_color_space) {
784 case JCS_RGB:
785 cinfo->input_components = 3;
786 break;
787 case JCS_GRAYSCALE:
788 cinfo->input_components = 1;
789 break;
790 case JCS_UNKNOWN:
791 cinfo->input_components = 4;
792 break;
793 /* default was missing... intentional ? */
794 default:
795 /* do nothing */
796 break;
797 }
798 jpeg_set_defaults(cinfo);
799
800 /* own settings */
801
802 cinfo->dct_method = JDCT_FLOAT;
803 jpeg_set_quality(cinfo, quality, true);
804
805 /* JFIF stores the density as integers in either dots per inch or centimeter.
806 * Use whichever unit rounds with the least error. */
807 if (ibuf->ppm[0] > 0.0 && ibuf->ppm[1] > 0.0) {
808 /* The JFIF unit code & the size of the unit in meters. */
809 struct Unit {
810 UINT8 code;
811 double scale;
812 };
813 const Unit units[] = {
814 {1, 0.0254}, /* Inches. */
815 {2, 0.01}, /* Centimeters. */
816 };
817 double error_best = std::numeric_limits<double>::max();
818 for (const Unit &unit : units) {
819 UINT16 density[2];
820 const double error_test = jpeg_density_from_ppm(ibuf->ppm, unit.scale, density);
821 if (error_test < error_best) {
822 error_best = error_test;
823 cinfo->density_unit = unit.code;
824 cinfo->X_density = density[0];
825 cinfo->Y_density = density[1];
826 }
827 }
828 }
829
830 return 0;
831}
832
833static bool save_stdjpeg(const char *filepath, ImBuf *ibuf)
834{
835 FILE *outfile;
836 jpeg_compress_struct _cinfo, *cinfo = &_cinfo;
837 my_error_mgr jerr;
838
839 if ((outfile = BLI_fopen(filepath, "wb")) == nullptr) {
840 return false;
841 }
842
843 cinfo->err = jpeg_std_error(&jerr.pub);
844 jerr.pub.error_exit = jpeg_error;
845
846 /* Establish the setjmp return context for jpeg_error to use. */
847 if (setjmp(jerr.setjmp_buffer)) {
848 /* If we get here, the JPEG code has signaled an error.
849 * We need to clean up the JPEG object, close the input file, and return.
850 */
851 jpeg_destroy_compress(cinfo);
852 fclose(outfile);
853 remove(filepath);
854 return false;
855 }
856
857 init_jpeg(outfile, cinfo, ibuf);
858
859 write_jpeg(cinfo, ibuf);
860
861 fclose(outfile);
862 jpeg_destroy_compress(cinfo);
863
864 return true;
865}
866
867bool imb_savejpeg(ImBuf *ibuf, const char *filepath, ImBufFlags flags)
868{
869
870 ibuf->flags = flags;
871 return save_stdjpeg(filepath, ibuf);
872}
873
875
876} // namespace blender
#define IDP_string_get(prop)
#define ATTR_NORETURN
File and directory operations.
#define STRNCPY_UTF8(dst, src)
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
ID and Library types, which are fundamental for SDNA.
Read Blender memory allocation and freeing.
#define STRPREFIX(a, b)
#define STREQ(a, b)
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
Definition btDbvt.cpp:52
int64_t size() const
void prepend(const T &value)
bool is_empty() const
#define str(s)
#define JPEG_MARKER_APP1
#define INPUT_BYTE(cinfo, V, action)
#define JPEG_MARKER_MSB
#define JPEG_MARKER_SOI
#define INPUT_2BYTES(cinfo, V, action)
#define INPUT_VARS(cinfo)
#define INPUT_SYNC(cinfo)
#define MAX_LIBJPEG_MARKER_LENGTH
#define JPEG_APP1_MAX
float length(VecOp< float, D >) RET
unsigned int uchar
float3x3 scale(float3x3 mat, float2 scale)
T abs(const T &a)
T round(const T &a)
BMesh Iterators.
my_source_mgr * my_src_ptr
static boolean fill_input_buffer(j_decompress_ptr cinfo)
BLI_STATIC_ASSERT(ARRAY_SIZE(data_mode_strings)==CTX_MODE_NUM+1, "Must have a string for each context mode") const char *CTX_data_mode_string(const bContext *C)
static void jpeg_error(j_common_ptr cinfo) ATTR_NORETURN
unsigned int uint
Definition BKE_text.h:55
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
Vector< char > IMB_colormanagement_space_to_icc_profile(const ColorSpace *colorspace)
static const uchar jpeg_default_quality
FILE * BLI_fopen(const char *filepath, const char *mode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
static ImBuf * ibJpegImageFromCinfo(jpeg_decompress_struct *cinfo, ImBufFlags flags, int max_size, size_t *r_width, size_t *r_height)
static void memory_source(j_decompress_ptr cinfo, const uchar *buffer, size_t size)
static uchar ibuf_quality
MINLINE uint max_uu(uint a, uint b)
char * BLI_strdupn(const char *str, size_t len) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
my_error_mgr * my_error_ptr
bool imb_is_a_jpeg(const uchar *mem, const size_t size)
ImBuf * imb_load_jpeg(const uchar *buffer, size_t size, ImBufFlags flags, ImFileColorSpace &)
static double jpeg_density_from_ppm(const double ppm[2], const double unit_scale, UINT16 r_density[2])
static void init_source(j_decompress_ptr cinfo)
static void write_jpeg(jpeg_compress_struct *cinfo, ImBuf *ibuf)
static boolean handle_app1(j_decompress_ptr cinfo)
unsigned char uchar
Definition BKE_text.h:58
static int init_jpeg(FILE *outfile, jpeg_compress_struct *cinfo, ImBuf *ibuf)
const char * imb_file_extensions_jpeg[]
static void skip_input_data(j_decompress_ptr cinfo, long num_bytes)
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
int char char int int int int size_t BLI_strnlen(const char *str, size_t maxlen) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
bool imb_savejpeg(ImBuf *ibuf, const char *filepath, ImBufFlags flags)
ImBuf * IMB_allocImBuf(unsigned int x, unsigned int y, ImBufFlags flags)
static void term_source(j_decompress_ptr cinfo)
static CLG_LogRef LOG
Definition logging.cpp:12
size_t BLI_snprintf_utf8_rlen(char *__restrict dst, size_t dst_maxncpy, const char *__restrict format,...) ATTR_NONNULL(1
ImBuf * imb_thumbnail_jpeg(const char *filepath, const ImBufFlags flags, const size_t max_thumb_size, ImFileColorSpace &r_colorspace, size_t *r_width, size_t *r_height)
void IMB_metadata_set_field(IDProperty *metadata, const char *key, const char *value)
ocio::ColorSpace ColorSpace
Definition BLF_api.hh:42
void * MEM_new_array_zeroed(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
MINLINE uint min_uu(uint a, uint b)
static bool save_stdjpeg(const char *filepath, ImBuf *ibuf)
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
ListBaseT< struct IDProperty > group
Definition DNA_ID.h:133
IDPropertyData data
Definition DNA_ID.h:157
const ColorSpace * colorspace
ImbFormatOptions foptions
ImBufByteBuffer byte_buffer
const uint8_t * byte_data() const
uint8_t * byte_data_for_write()
Definition allocimbuf.cc:60
IDProperty * metadata_for_write()
const IDProperty * metadata() const
ImColorMode color_mode
eImbFileType ftype
jpeg_error_mgr pub
jpeg_source_mgr pub