Debian Codegraph @

JPEG/imjpeg.c

raw
1 /*
2 =head1 NAME
3
4 jpeg.c - implement saving and loading JPEG images
5
6 =head1 SYNOPSIS
7
8 io_glue *ig;
9 if (!i_writejpeg_wiol(im, ig, quality)) {
10 .. error ..
11 }
12 im = i_readjpeg_wiol(ig, length, iptc_text, itlength);
13
14 =head1 DESCRIPTION
15
16 Reads and writes JPEG images
17
18 =over
19
20 =cut
21 */
22
23 #include "imjpeg.h"
24 #include "imext.h"
25 #include <stdio.h>
26 #include <sys/stat.h>
27 #ifndef _MSC_VER
28 #include <unistd.h>
29 #endif
30 #include <setjmp.h>
31 #include <string.h>
32
33 #include "jpeglib.h"
34 #include "jerror.h"
35 #include <errno.h>
36 #include <stdlib.h>
37 #include <math.h>
38
39 #define JPEG_APP13 0xED /* APP13 marker code */
40 #define JPEG_APP1 (JPEG_APP0 + 1)
41 #define JPGS 16384
42
43 #define JPEG_DIM_MAX JPEG_MAX_DIMENSION
44
45 #define _STRINGIFY(x) #x
46 #define STRINGIFY(x) _STRINGIFY(x)
47
48 static unsigned char fake_eoi[]={(JOCTET) 0xFF,(JOCTET) JPEG_EOI};
49
50 #ifdef JPEG_C_PARAM_SUPPORTED
51 #define IS_MOZJPEG
52 #endif
53
54 /* Source and Destination managers */
55
56 typedef struct {
57 struct jpeg_source_mgr pub; /* public fields */
58 io_glue *data;
59 JOCTET *buffer; /* start of buffer */
60 int length; /* Do I need this? */
61 boolean start_of_file; /* have we gotten any data yet? */
62 } wiol_source_mgr;
63
64 typedef struct {
65 struct jpeg_destination_mgr pub; /* public fields */
66 io_glue *data;
67 JOCTET *buffer; /* start of buffer */
68 boolean start_of_file; /* have we gotten any data yet? */
69 } wiol_destination_mgr;
70
71 typedef wiol_source_mgr *wiol_src_ptr;
72 typedef wiol_destination_mgr *wiol_dest_ptr;
73
74 /*
75 * Methods for io manager objects
76 *
77 * Methods for source managers:
78 *
79 * init_source (j_decompress_ptr cinfo);
80 * skip_input_data (j_decompress_ptr cinfo, long num_bytes);
81 * fill_input_buffer (j_decompress_ptr cinfo);
82 * term_source (j_decompress_ptr cinfo);
83 */
84
85
86
87 static void
88 wiol_init_source (j_decompress_ptr cinfo) {
89 wiol_src_ptr src = (wiol_src_ptr) cinfo->src;
90
91 /* We reset the empty-input-file flag for each image, but we don't clear
92 * the input buffer. This is correct behavior for reading a series of
93 * images from one source.
94 */
95 src->start_of_file = TRUE;
96 }
97
98
99
100 static boolean
101 wiol_fill_input_buffer(j_decompress_ptr cinfo) {
102 wiol_src_ptr src = (wiol_src_ptr) cinfo->src;
103 ssize_t nbytes; /* We assume that reads are "small" */
104
105 mm_log((1,"wiol_fill_input_buffer(cinfo %p)\n", cinfo));
106
107 nbytes = i_io_read(src->data, src->buffer, JPGS);
108
109 if (nbytes <= 0) { /* Insert a fake EOI marker */
110 src->pub.next_input_byte = fake_eoi;
111 src->pub.bytes_in_buffer = 2;
112 } else {
113 src->pub.next_input_byte = src->buffer;
114 src->pub.bytes_in_buffer = nbytes;
115 }
116 src->start_of_file = FALSE;
117 return TRUE;
118 }
119
120
121 static void
122 wiol_skip_input_data (j_decompress_ptr cinfo, long num_bytes) {
123 wiol_src_ptr src = (wiol_src_ptr) cinfo->src;
124
125 /* Just a dumb implementation for now. Could use fseek() except
126 * it doesn't work on pipes. Not clear that being smart is worth
127 * any trouble anyway --- large skips are infrequent.
128 */
129
130 if (num_bytes > 0) {
131 while (num_bytes > (long) src->pub.bytes_in_buffer) {
132 num_bytes -= (long) src->pub.bytes_in_buffer;
133 (void) wiol_fill_input_buffer(cinfo);
134 /* note we assume that fill_input_buffer will never return FALSE,
135 * so suspension need not be handled.
136 */
137 }
138 src->pub.next_input_byte += (size_t) num_bytes;
139 src->pub.bytes_in_buffer -= (size_t) num_bytes;
140 }
141 }
142
143 static void
144 wiol_term_source (j_decompress_ptr cinfo) {
145 (void)cinfo;
146 /* no work necessary here */
147 /* we used to free memory for the I/O buffer,
148 but we let the library handle that now
149 */
150 }
151
152
153 /* Source manager Constructor */
154
155 static void
156 jpeg_wiol_src(j_decompress_ptr cinfo, io_glue *ig, int length) {
157 wiol_src_ptr src;
158
159 if (cinfo->src == NULL) { /* first time for this JPEG object? */
160 cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small)
161 ((j_common_ptr) cinfo, JPOOL_PERMANENT,sizeof(wiol_source_mgr));
162 src = (wiol_src_ptr) cinfo->src;
163 }
164
165 /* put the request method call in here later */
166
167 src = (wiol_src_ptr) cinfo->src;
168 src->data = ig;
169 src->buffer = (*cinfo->mem->alloc_small)((j_common_ptr) cinfo, JPOOL_PERMANENT, JPGS);
170 src->length = length;
171
172 src->pub.init_source = wiol_init_source;
173 src->pub.fill_input_buffer = wiol_fill_input_buffer;
174 src->pub.skip_input_data = wiol_skip_input_data;
175 src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
176 src->pub.term_source = wiol_term_source;
177 src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
178 src->pub.next_input_byte = NULL; /* until buffer loaded */
179 }
180
181
182
183
184 /*
185 * Methods for destination managers:
186 *
187 * init_destination (j_compress_ptr cinfo);
188 * empty_output_buffer (j_compress_ptr cinfo);
189 * term_destination (j_compress_ptr cinfo);
190 *
191 */
192
193 static void
194 wiol_init_destination (j_compress_ptr cinfo) {
195 wiol_dest_ptr dest = (wiol_dest_ptr) cinfo->dest;
196
197 /* We reset the empty-input-file flag for each image, but we don't clear
198 * the input buffer. This is correct behavior for reading a series of
199 * images from one source.
200 */
201 dest->start_of_file = TRUE;
202 }
203
204 static boolean
205 wiol_empty_output_buffer(j_compress_ptr cinfo) {
206 wiol_dest_ptr dest = (wiol_dest_ptr) cinfo->dest;
207 ssize_t rc;
208 /*
209 Previously this code was checking free_in_buffer to see how much
210 needed to be written. This does not follow the documentation:
211
212 "In typical applications, it should write out the
213 *entire* buffer (use the saved start address and buffer length;
214 ignore the current state of next_output_byte and free_in_buffer)."
215
216 ssize_t nbytes = JPGS - dest->pub.free_in_buffer;
217 */
218
219 mm_log((1,"wiol_empty_output_buffer(cinfo %p)\n", cinfo));
220 rc = i_io_write(dest->data, dest->buffer, JPGS);
221
222 if (rc != JPGS) { /* XXX: Should raise some jpeg error */
223 mm_log((1, "wiol_empty_output_buffer: Error: nbytes = %d != rc = %d\n", JPGS, (int)rc));
224 ERREXIT(cinfo, JERR_FILE_WRITE);
225 }
226 dest->pub.free_in_buffer = JPGS;
227 dest->pub.next_output_byte = dest->buffer;
228 return TRUE;
229 }
230
231 static void
232 wiol_term_destination (j_compress_ptr cinfo) {
233 wiol_dest_ptr dest = (wiol_dest_ptr) cinfo->dest;
234 size_t nbytes = JPGS - dest->pub.free_in_buffer;
235 /* yes, this needs to flush the buffer */
236 /* needs error handling */
237
238 if (i_io_write(dest->data, dest->buffer, nbytes) != (ssize_t)nbytes) {
239 ERREXIT(cinfo, JERR_FILE_WRITE);
240 }
241 }
242
243
244 /* Destination manager Constructor */
245
246 static void
247 jpeg_wiol_dest(j_compress_ptr cinfo, io_glue *ig) {
248 wiol_dest_ptr dest;
249
250 if (cinfo->dest == NULL) { /* first time for this JPEG object? */
251 cinfo->dest =
252 (struct jpeg_destination_mgr *)
253 (*cinfo->mem->alloc_small)
254 ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(wiol_destination_mgr));
255 }
256
257 dest = (wiol_dest_ptr) cinfo->dest;
258 dest->data = ig;
259 dest->buffer =
260 (*cinfo->mem->alloc_small)((j_common_ptr) cinfo, JPOOL_PERMANENT, JPGS);
261
262 dest->pub.init_destination = wiol_init_destination;
263 dest->pub.empty_output_buffer = wiol_empty_output_buffer;
264 dest->pub.term_destination = wiol_term_destination;
265 dest->pub.free_in_buffer = JPGS;
266 dest->pub.next_output_byte = dest->buffer;
267 }
268
269 METHODDEF(void)
270 my_output_message (j_common_ptr cinfo) {
271 char buffer[JMSG_LENGTH_MAX];
272
273 /* Create the message */
274 (*cinfo->err->format_message) (cinfo, buffer);
275
276 i_push_error(0, buffer);
277
278 /* Send it to stderr, adding a newline */
279 mm_log((1, "%s\n", buffer));
280 }
281
282 struct my_error_mgr {
283 struct jpeg_error_mgr pub; /* "public" fields */
284 jmp_buf setjmp_buffer; /* for return to caller */
285 };
286
287 typedef struct my_error_mgr * my_error_ptr;
288
289 /* Here's the routine that will replace the standard error_exit method */
290
291 METHODDEF(void)
292 my_error_exit (j_common_ptr cinfo) {
293 /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
294 my_error_ptr myerr = (my_error_ptr) cinfo->err;
295
296 /* Always display the message. */
297 /* We could postpone this until after returning, if we chose. */
298 (*cinfo->err->output_message) (cinfo);
299
300 /* Return control to the setjmp point */
301 longjmp(myerr->setjmp_buffer, 1);
302 }
303
304 static void
305 transfer_cmyk_inverted(i_color *out, JSAMPARRAY in, int width) {
306 JSAMPROW inrow = *in;
307 while (width--) {
308 /* extract and convert to real CMYK */
309 /* horribly enough this is correct given cmyk values are inverted */
310 int c = *inrow++;
311 int m = *inrow++;
312 int y = *inrow++;
313 int k = *inrow++;
314 out->rgba.r = (c * k) / MAXJSAMPLE;
315 out->rgba.g = (m * k) / MAXJSAMPLE;
316 out->rgba.b = (y * k) / MAXJSAMPLE;
317 ++out;
318 }
319 }
320
321 static void
322 transfer_rgb(i_color *out, JSAMPARRAY in, int width) {
323 JSAMPROW inrow = *in;
324 while (width--) {
325 out->rgba.r = *inrow++;
326 out->rgba.g = *inrow++;
327 out->rgba.b = *inrow++;
328 ++out;
329 }
330 }
331
332 static void
333 transfer_gray(i_color *out, JSAMPARRAY in, int width) {
334 JSAMPROW inrow = *in;
335 while (width--) {
336 out->gray.gray_color = *inrow++;
337 ++out;
338 }
339 }
340
341 typedef void (*transfer_function_t)(i_color *out, JSAMPARRAY in, int width);
342
343 static const char version_string[] =
344 #if defined(IS_MOZJPEG)
345 "mozjpeg version " STRINGIFY(LIBJPEG_TURBO_VERSION) " api " STRINGIFY(JPEG_LIB_VERSION)
346 #elif defined(LIBJPEG_TURBO_VERSION)
347 "libjpeg-turbo version " STRINGIFY(LIBJPEG_TURBO_VERSION) " api " STRINGIFY(JPEG_LIB_VERSION)
348 #else
349 "libjpeg version " STRINGIFY(JPEG_LIB_VERSION) " api " STRINGIFY(JPEG_LIB_VERSION)
350 #endif
351 ;
352
353 /*
354 =item i_libjpeg_version()
355
356 =cut
357 */
358
359 const char *
360 i_libjpeg_version(void) {
361 return version_string;
362 }
363
364 int
365 is_turbojpeg(void) {
366 #if defined(LIBJPEG_TURBO_VERSION)
367 return 1;
368 #else
369 return 0;
370 #endif
371 }
372
373 int
374 is_mozjpeg(void) {
375 #ifdef IS_MOZJPEG
376 return 1;
377 #else
378 return 0;
379 #endif
380 }
381
382 int
383 has_encode_arith_coding(void) {
384 #ifdef C_ARITH_CODING_SUPPORTED
385 return 1;
386 #else
387 return 0;
388 #endif
389 }
390
391 int
392 has_decode_arith_coding(void) {
393 #ifdef D_ARITH_CODING_SUPPORTED
394 return 1;
395 #else
396 return 0;
397 #endif
398 }
399
400 /*
401 =item i_readjpeg_wiol(data, length, iptc_itext, itlength)
402
403 =cut
404 */
405 i_img*
406 i_readjpeg_wiol(io_glue *data, int length, char** iptc_itext, int *itlength) {
407 i_img * volatile im = NULL;
408 int seen_exif;
409 i_color * volatile line_buffer = NULL;
410 struct jpeg_decompress_struct cinfo;
411 struct my_error_mgr jerr;
412 JSAMPARRAY buffer; /* Output row buffer */
413 int row_stride; /* physical row width in output buffer */
414 jpeg_saved_marker_ptr markerp;
415 transfer_function_t transfer_f;
416 int channels;
417 volatile int src_set = 0;
418
419 mm_log((1,"i_readjpeg_wiol(data %p, length %d,iptc_itext %p)\n", data, length, iptc_itext));
420
421 i_clear_error();
422
423 *iptc_itext = NULL;
424 *itlength = 0;
425
426 cinfo.err = jpeg_std_error(&jerr.pub);
427 jerr.pub.error_exit = my_error_exit;
428 jerr.pub.output_message = my_output_message;
429
430 /* Set error handler */
431 if (setjmp(jerr.setjmp_buffer)) {
432 if (src_set)
433 wiol_term_source(&cinfo);
434 jpeg_destroy_decompress(&cinfo);
435 if (line_buffer)
436 myfree(line_buffer);
437 if (im)
438 i_img_destroy(im);
439 return NULL;
440 }
441
442 jpeg_create_decompress(&cinfo);
443 jpeg_save_markers(&cinfo, JPEG_APP13, 0xFFFF);
444 jpeg_save_markers(&cinfo, JPEG_APP1, 0xFFFF);
445 jpeg_save_markers(&cinfo, JPEG_COM, 0xFFFF);
446 jpeg_wiol_src(&cinfo, data, length);
447 src_set = 1;
448
449 (void) jpeg_read_header(&cinfo, TRUE);
450 (void) jpeg_start_decompress(&cinfo);
451
452 channels = cinfo.output_components;
453 switch (cinfo.out_color_space) {
454 case JCS_GRAYSCALE:
455 if (cinfo.output_components != 1) {
456 mm_log((1, "i_readjpeg: grayscale image with %d channels\n", cinfo.output_components));
457 i_push_errorf(0, "grayscale image with invalid components %d", cinfo.output_components);
458 wiol_term_source(&cinfo);
459 jpeg_destroy_decompress(&cinfo);
460 return NULL;
461 }
462 transfer_f = transfer_gray;
463 break;
464
465 case JCS_RGB:
466 transfer_f = transfer_rgb;
467 if (cinfo.output_components != 3) {
468 mm_log((1, "i_readjpeg: RGB image with %d channels\n", cinfo.output_components));
469 i_push_errorf(0, "RGB image with invalid components %d", cinfo.output_components);
470 wiol_term_source(&cinfo);
471 jpeg_destroy_decompress(&cinfo);
472 return NULL;
473 }
474 break;
475
476 case JCS_CMYK:
477 if (cinfo.output_components == 4) {
478 /* we treat the CMYK values as inverted, because that's what that
479 buggy photoshop does, and everyone has to follow the gorilla.
480
481 Is there any app that still produces correct CMYK JPEGs?
482 */
483 transfer_f = transfer_cmyk_inverted;
484 channels = 3;
485 }
486 else {
487 mm_log((1, "i_readjpeg: cmyk image with %d channels\n", cinfo.output_components));
488 i_push_errorf(0, "CMYK image with invalid components %d", cinfo.output_components);
489 wiol_term_source(&cinfo);
490 jpeg_destroy_decompress(&cinfo);
491 return NULL;
492 }
493 break;
494
495 default:
496 mm_log((1, "i_readjpeg: unknown color space %d\n", cinfo.out_color_space));
497 i_push_errorf(0, "Unknown color space %d", cinfo.out_color_space);
498 wiol_term_source(&cinfo);
499 jpeg_destroy_decompress(&cinfo);
500 return NULL;
501 }
502
503 if (!i_int_check_image_file_limits(cinfo.output_width, cinfo.output_height,
504 channels, sizeof(i_sample_t))) {
505 mm_log((1, "i_readjpeg: image size exceeds limits\n"));
506 wiol_term_source(&cinfo);
507 jpeg_destroy_decompress(&cinfo);
508 return NULL;
509 }
510
511 im = i_img_8_new(cinfo.output_width, cinfo.output_height, channels);
512 if (!im) {
513 wiol_term_source(&cinfo);
514 jpeg_destroy_decompress(&cinfo);
515 return NULL;
516 }
517 row_stride = cinfo.output_width * cinfo.output_components;
518 buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
519 line_buffer = mymalloc(sizeof(i_color) * cinfo.output_width);
520 while (cinfo.output_scanline < cinfo.output_height) {
521 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
522 transfer_f(line_buffer, buffer, cinfo.output_width);
523 i_plin(im, 0, cinfo.output_width, cinfo.output_scanline-1, line_buffer);
524 }
525 myfree(line_buffer);
526 line_buffer = NULL;
527
528 /* check for APP1 marker and save */
529 markerp = cinfo.marker_list;
530 seen_exif = 0;
531 while (markerp != NULL) {
532 if (markerp->marker == JPEG_COM) {
533 i_tags_set(&im->tags, "jpeg_comment", (const char *)markerp->data,
534 markerp->data_length);
535 }
536 else if (markerp->marker == JPEG_APP1 && !seen_exif) {
537 unsigned char *data = markerp->data;
538 size_t len = markerp->data_length;
539 if (len >= 6 && memcmp(data, "Exif\0\0", 6) == 0) {
540 seen_exif = im_decode_exif(im, data+6, len-6);
541 }
542 }
543 else if (markerp->marker == JPEG_APP13) {
544 if (*iptc_itext)
545 myfree(*iptc_itext);
546 *iptc_itext = mymalloc(markerp->data_length);
547 memcpy(*iptc_itext, markerp->data, markerp->data_length);
548 *itlength = markerp->data_length;
549 }
550
551 markerp = markerp->next;
552 }
553
554 i_tags_setn(&im->tags, "jpeg_out_color_space", cinfo.out_color_space);
555 i_tags_setn(&im->tags, "jpeg_color_space", cinfo.jpeg_color_space);
556 i_tags_setn(&im->tags, "jpeg_read_arithmetic", cinfo.arith_code);
557
558 i_tags_setn(&im->tags, "jpeg_read_jfif", !!cinfo.saw_JFIF_marker);
559 if (cinfo.saw_JFIF_marker) {
560 double xres = cinfo.X_density;
561 double yres = cinfo.Y_density;
562
563 i_tags_setn(&im->tags, "jpeg_density_unit", cinfo.density_unit);
564 switch (cinfo.density_unit) {
565 case 0: /* values are just the aspect ratio */
566 i_tags_setn(&im->tags, "i_aspect_only", 1);
567 i_tags_set(&im->tags, "jpeg_density_unit_name", "none", -1);
568 break;
569
570 case 1: /* per inch */
571 i_tags_set(&im->tags, "jpeg_density_unit_name", "inch", -1);
572 break;
573
574 case 2: /* per cm */
575 i_tags_set(&im->tags, "jpeg_density_unit_name", "centimeter", -1);
576 xres *= 2.54;
577 yres *= 2.54;
578 break;
579 }
580 i_tags_set_float2(&im->tags, "i_xres", 0, xres, 6);
581 i_tags_set_float2(&im->tags, "i_yres", 0, yres, 6);
582 }
583
584 /* I originally used jpeg_has_multiple_scans() here, but that can
585 * return true for non-progressive files too. The progressive_mode
586 * member is available at least as far back as 6b and does the right
587 * thing.
588 */
589 i_tags_setn(&im->tags, "jpeg_progressive",
590 cinfo.progressive_mode ? 1 : 0);
591
592 (void) jpeg_finish_decompress(&cinfo);
593 jpeg_destroy_decompress(&cinfo);
594
595 i_tags_set(&im->tags, "i_format", "jpeg", 4);
596
597 mm_log((1,"i_readjpeg_wiol -> (%p)\n",im));
598 return im;
599 }
600
601 struct moz_option {
602 const char *name;
603 #ifdef IS_MOZJPEG
604 unsigned tag;
605 #endif
606 };
607
608 #ifdef IS_MOZJPEG
609 #define MOZ_OPTION_ENTRY(name, tag) { name, tag }
610 #else
611 #define MOZ_OPTION_ENTRY(name, tag) { name }
612 #endif
613
614 static struct moz_option
615 boolean_options[] = {
616 MOZ_OPTION_ENTRY("jpeg_optimize_scans", JBOOLEAN_OPTIMIZE_SCANS),
617 MOZ_OPTION_ENTRY("jpeg_trellis_quant", JBOOLEAN_TRELLIS_QUANT),
618 MOZ_OPTION_ENTRY("jpeg_trellis_quant_dc", JBOOLEAN_TRELLIS_QUANT_DC),
619 MOZ_OPTION_ENTRY("jpeg_tresllis_eob_opt", JBOOLEAN_TRELLIS_EOB_OPT),
620 MOZ_OPTION_ENTRY("jpeg_use_lambda_weight_tbl", JBOOLEAN_USE_LAMBDA_WEIGHT_TBL),
621 MOZ_OPTION_ENTRY("jpeg_use_scans_in_trellis", JBOOLEAN_USE_SCANS_IN_TRELLIS),
622 MOZ_OPTION_ENTRY("jpeg_overshoot_deringing", JBOOLEAN_OVERSHOOT_DERINGING)
623 };
624
625 const ssize_t
626 boolean_option_count = sizeof(boolean_options) / sizeof(boolean_options[0]);
627
628 static struct moz_option float_options[] = {
629 MOZ_OPTION_ENTRY("jpeg_lambda_log_scale1", JFLOAT_LAMBDA_LOG_SCALE1),
630 MOZ_OPTION_ENTRY("jpeg_lambda_log_scale2", JFLOAT_LAMBDA_LOG_SCALE2),
631 MOZ_OPTION_ENTRY("jpeg_trellis_delta_dc_weight", JFLOAT_TRELLIS_DELTA_DC_WEIGHT)
632 };
633
634 const ssize_t
635 float_option_count = sizeof(float_options) / sizeof(float_options[0]);
636
637 static struct moz_option int_options[] = {
638 MOZ_OPTION_ENTRY("jpeg_trellis_freq_split", JINT_TRELLIS_FREQ_SPLIT),
639 MOZ_OPTION_ENTRY("jpeg_trellis_num_loops", JINT_TRELLIS_NUM_LOOPS),
640 MOZ_OPTION_ENTRY("jpeg_base_quant_tbl_idx", JINT_BASE_QUANT_TBL_IDX),
641 MOZ_OPTION_ENTRY("jpeg_dc_scan_opt_mode", JINT_DC_SCAN_OPT_MODE)
642 };
643
644 const ssize_t
645 int_option_count = sizeof(int_options) / sizeof(int_options[0]);
646
647 /*
648 =item i_writejpeg_wiol(im, ig, qfactor)
649
650 =cut
651 */
652
653 undef_int
654 i_writejpeg_wiol(i_img *im, io_glue *ig, int qfactor) {
655 JSAMPLE *image_buffer;
656 int got_xres, got_yres, aspect_only, resunit;
657 double xres, yres;
658 int comment_entry;
659 volatile int want_channels = im->channels;
660 int progressive = 0;
661 int optimize = 0;
662 int arithmetic = 0;
663 char profile_name[20] = "";
664 int jfif;
665
666 struct jpeg_compress_struct cinfo;
667 struct my_error_mgr jerr;
668
669 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
670 int row_stride; /* physical row width in image buffer */
671 unsigned char * data = NULL;
672 i_color *line_buf = NULL;
673
674 mm_log((1,"i_writejpeg(im %p, ig %p, qfactor %d)\n", im, ig, qfactor));
675
676 i_clear_error();
677
678 if (im->xsize > JPEG_DIM_MAX || im->ysize > JPEG_DIM_MAX) {
679 i_push_error(0, "image too large for JPEG");
680 return 0;
681 }
682
683 if (!(im->channels==1 || im->channels==3)) {
684 want_channels = im->channels - 1;
685 }
686
687 cinfo.err = jpeg_std_error(&jerr.pub);
688 jerr.pub.error_exit = my_error_exit;
689 jerr.pub.output_message = my_output_message;
690
691 jpeg_create_compress(&cinfo);
692
693 if (setjmp(jerr.setjmp_buffer)) {
694 fail:
695 jpeg_destroy_compress(&cinfo);
696 if (data)
697 myfree(data);
698 if (line_buf)
699 myfree(line_buf);
700 return 0;
701 }
702
703 jpeg_wiol_dest(&cinfo, ig);
704
705 cinfo.image_width = im -> xsize; /* image width and height, in pixels */
706 cinfo.image_height = im -> ysize;
707
708 if (want_channels==3) {
709 cinfo.input_components = 3; /* # of color components per pixel */
710 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
711 }
712
713 if (want_channels==1) {
714 cinfo.input_components = 1; /* # of color components per pixel */
715 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
716 }
717
718 if (i_tags_get_string(&im->tags, "jpeg_compress_profile", 0,
719 profile_name, sizeof(profile_name))) {
720 if (strcmp(profile_name, "fastest") == 0) {
721 #ifdef IS_MOZJPEG
722 jpeg_c_set_int_param(&cinfo, JINT_COMPRESS_PROFILE, JCP_FASTEST);
723 #endif
724 /* else default */
725 }
726 else if (strcmp(profile_name, "max") == 0) {
727 #ifdef IS_MOZJPEG
728 jpeg_c_set_int_param(&cinfo, JINT_COMPRESS_PROFILE, JCP_MAX_COMPRESSION);
729 #else
730 i_push_error(0, "jpeg_compress_profile=max requires mozjpeg");
731 goto fail;
732 #endif
733 }
734 else {
735 i_push_errorf(0, "jpeg_compress_profile=%s unknown", profile_name);
736 goto fail;
737 }
738 }
739 #ifdef IS_MOZJPEG
740 else {
741 jpeg_c_set_int_param(&cinfo, JINT_COMPRESS_PROFILE, JCP_FASTEST);
742 }
743 #endif
744
745 jpeg_set_defaults(&cinfo);
746
747 {
748 char tune_str[20];
749 if (i_tags_get_string(&im->tags, "jpeg_tune", 0, tune_str, sizeof(tune_str))) {
750 if (strcmp(tune_str, "psnr") == 0) {
751 #ifdef IS_MOZJPEG
752 jpeg_c_set_int_param(&cinfo, JINT_BASE_QUANT_TBL_IDX, 1);
753 jpeg_c_set_float_param(&cinfo, JFLOAT_LAMBDA_LOG_SCALE1, 9.0);
754 jpeg_c_set_float_param(&cinfo, JFLOAT_LAMBDA_LOG_SCALE2, 0.0);
755 jpeg_c_set_bool_param(&cinfo, JBOOLEAN_USE_LAMBDA_WEIGHT_TBL, FALSE);
756 #endif
757 }
758 else if (strcmp(tune_str, "ssim") == 0) {
759 #ifdef IS_MOZJPEG
760 jpeg_c_set_int_param(&cinfo, JINT_BASE_QUANT_TBL_IDX, 1);
761 jpeg_c_set_float_param(&cinfo, JFLOAT_LAMBDA_LOG_SCALE1, 11.5);
762 jpeg_c_set_float_param(&cinfo, JFLOAT_LAMBDA_LOG_SCALE2, 12.75);
763 jpeg_c_set_bool_param(&cinfo, JBOOLEAN_USE_LAMBDA_WEIGHT_TBL, FALSE);
764 #endif
765 }
766 else if (strcmp(tune_str, "ms-ssim") == 0) {
767 #ifdef IS_MOZJPEG
768 jpeg_c_set_int_param(&cinfo, JINT_BASE_QUANT_TBL_IDX, 3);
769 jpeg_c_set_float_param(&cinfo, JFLOAT_LAMBDA_LOG_SCALE1, 12.0);
770 jpeg_c_set_float_param(&cinfo, JFLOAT_LAMBDA_LOG_SCALE2, 13.0);
771 jpeg_c_set_bool_param(&cinfo, JBOOLEAN_USE_LAMBDA_WEIGHT_TBL, TRUE);
772 #endif
773 }
774 else if (strcmp(tune_str, "hvs-psnr") == 0) {
775 #ifdef IS_MOZJPEG
776 jpeg_c_set_int_param(&cinfo, JINT_BASE_QUANT_TBL_IDX, 3);
777 jpeg_c_set_float_param(&cinfo, JFLOAT_LAMBDA_LOG_SCALE1, 14.75);
778 jpeg_c_set_float_param(&cinfo, JFLOAT_LAMBDA_LOG_SCALE2, 16.5);
779 jpeg_c_set_bool_param(&cinfo, JBOOLEAN_USE_LAMBDA_WEIGHT_TBL, TRUE);
780 #endif
781 }
782 else {
783 i_push_errorf(0, "unknown value '%s' for jpeg_tune", tune_str);
784 goto fail;
785 }
786 #ifndef IS_MOZJPEG
787 i_push_error(0, "jpeg_tune requires Imager::File::JPEG be built with mozjpeg");
788 goto fail;
789 #endif
790 }
791 }
792
793 jpeg_set_quality(&cinfo, qfactor, TRUE); /* limit to baseline-JPEG values */
794
795 if (i_tags_get_int(&im->tags, "jpeg_jfif", 0, &jfif) && !jfif) {
796 cinfo.write_JFIF_header = 0;
797 }
798
799 {
800 int i;
801 for (i = 0; i < boolean_option_count; ++i) {
802 int val;
803 const struct moz_option *opt = boolean_options + i;
804 if (i_tags_get_int(&im->tags, opt->name, 0, &val)) {
805 #ifdef IS_MOZJPEG
806 jpeg_c_set_bool_param(&cinfo, opt->tag, !!val);
807 #else
808 i_push_errorf(0, "option %s requires Imager::File::JPEG be built with mozjpeg",
809 opt->name);
810 goto fail;
811 #endif
812 }
813 }
814 }
815
816 {
817 int i;
818 for (i = 0; i < float_option_count; ++i) {
819 double val;
820 const struct moz_option *opt = float_options + i;
821 if (i_tags_get_float(&im->tags, opt->name, 0, &val)) {
822 #ifdef IS_MOZJPEG
823 float f = val;
824 float g;
825 jpeg_c_set_float_param(&cinfo, opt->tag, f);
826 g = jpeg_c_get_float_param(&cinfo, opt->tag);
827 if (fabs(g-f) > 0.0001) {
828 i_push_errorf(0, "invalid value %g for tag %s", val, opt->name);
829 }
830 #else
831 i_push_errorf(0, "option %s requires Imager::File::JPEG be built with mozjpeg",
832 opt->name);
833 goto fail;
834 #endif
835 }
836 }
837 }
838
839 {
840 int i;
841 for (i = 0; i < int_option_count; ++i) {
842 int val;
843 const struct moz_option *opt = int_options + i;
844 if (i_tags_get_int(&im->tags, opt->name, 0, &val)) {
845 #ifdef IS_MOZJPEG
846 jpeg_c_set_int_param(&cinfo, opt->tag, val);
847 if (jpeg_c_get_int_param(&cinfo, opt->tag) != val) {
848 i_push_errorf(0, "invalid value %d for tag %s", val, opt->name);
849 }
850 #else
851 i_push_errorf(0, "option %s requires Imager::File::JPEG be built with mozjpeg",
852 opt->name);
853 goto fail;
854 #endif
855 }
856 }
857 }
858
859 if (!i_tags_get_int(&im->tags, "jpeg_progressive", 0, &progressive))
860 progressive = 0;
861 if (progressive) {
862 jpeg_simple_progression(&cinfo);
863 }
864 if (!i_tags_get_int(&im->tags, "jpeg_optimize", 0, &optimize))
865 optimize = 0;
866 cinfo.optimize_coding = optimize;
867 if (i_tags_get_int(&im->tags, "jpeg_arithmetic", 0, &arithmetic)) {
868 cinfo.arith_code = arithmetic != 0;
869 }
870
871 got_xres = i_tags_get_float(&im->tags, "i_xres", 0, &xres);
872 got_yres = i_tags_get_float(&im->tags, "i_yres", 0, &yres);
873 if (!i_tags_get_int(&im->tags, "i_aspect_only", 0,&aspect_only))
874 aspect_only = 0;
875 if (!i_tags_get_int(&im->tags, "jpeg_density_unit", 0, &resunit))
876 resunit = 1; /* per inch */
877 if (resunit < 0 || resunit > 2) /* default to inch if invalid */
878 resunit = 1;
879 if (got_xres || got_yres) {
880 if (!got_xres)
881 xres = yres;
882 else if (!got_yres)
883 yres = xres;
884 if (aspect_only)
885 resunit = 0; /* standard tags override format tags */
886 if (resunit == 2) {
887 /* convert to per cm */
888 xres /= 2.54;
889 yres /= 2.54;
890 }
891 cinfo.density_unit = resunit;
892 cinfo.X_density = (int)(xres + 0.5);
893 cinfo.Y_density = (int)(yres + 0.5);
894 }
895
896 {
897 int smooth;
898 if (i_tags_get_int(&im->tags, "jpeg_smooth", 0, &smooth)) {
899 if (smooth < 0 || smooth > 100) {
900 i_push_error(0, "jpeg_smooth must be an integer from 0 to 100");
901 goto fail;
902 }
903 cinfo.smoothing_factor = smooth;
904 }
905 }
906
907 {
908 char restart_str[20];
909 if (i_tags_get_string(&im->tags, "jpeg_restart", 0, restart_str, sizeof(restart_str))) {
910 long restart_count;
911 char block_flag = '\0';
912 if (sscanf(restart_str, "%ld%c", &restart_count, &block_flag) > 0
913 && restart_count >= 0 && restart_count <= 65535
914 && (block_flag == '\0' || block_flag == 'b' || block_flag == 'B')) {
915 if (block_flag) {
916 cinfo.restart_interval = (unsigned)restart_count;
917 }
918 else {
919 cinfo.restart_in_rows = (int)restart_count;
920 }
921 }
922 else {
923 i_push_error(0, "jpeg_restart must be an integer from 0 to 65535 followed by an optional b");
924 goto fail;
925 }
926 }
927 }
928
929 {
930 char sample_str[80];
931
932 if (i_tags_get_string(&im->tags, "jpeg_sample", 0, sample_str, sizeof(sample_str))) {
933 int x, y, n;
934 char sep;
935 char *p = sample_str;
936 int index = 0;
937 while (*p) {
938 if (sscanf(p, "%d%c%d%n", &x, &sep, &y, &n) == 3 &&
939 x >= 1 && x <= 4 && y >= 1 && y <= 4 &&
940 (sep == 'x' || sep == 'X') &&
941 index < MAX_COMPONENTS) {
942 cinfo.comp_info[index].h_samp_factor = x;
943 cinfo.comp_info[index].v_samp_factor = y;
944 ++index;
945 }
946 else {
947 failsample:
948 i_push_error(0, "jpeg_sample: must match /^[1-4]x[1-4](,[1-4]x[1-4]){0,9}$/aai");
949 goto fail;
950 }
951 p += n;
952 if (p[0] == ',') {
953 if (!p[1])
954 goto failsample;
955 ++p;
956 }
957 else if (p[0]) {
958 goto failsample;
959 }
960 }
961 /* fill the rest with 1x1 like cjpeg does */
962 for ( ; index < MAX_COMPONENTS; ++index) {
963 cinfo.comp_info[index].h_samp_factor = x;
964 cinfo.comp_info[index].v_samp_factor = y;
965 }
966 }
967 }
968
969 jpeg_start_compress(&cinfo, TRUE);
970
971 if (i_tags_find(&im->tags, "jpeg_comment", 0, &comment_entry)) {
972 jpeg_write_marker(&cinfo, JPEG_COM,
973 (const JOCTET *)im->tags.tags[comment_entry].data,
974 im->tags.tags[comment_entry].size);
975 }
976
977 row_stride = im->xsize * im->channels; /* JSAMPLEs per row in image_buffer */
978
979 if (!i_img_virtual(im) && im->type == i_direct_type && im->bits == i_8_bits
980 && im->channels == want_channels) {
981 image_buffer=im->idata;
982
983 while (cinfo.next_scanline < cinfo.image_height) {
984 /* jpeg_write_scanlines expects an array of pointers to scanlines.
985 * Here the array is only one element long, but you could pass
986 * more than one scanline at a time if that's more convenient.
987 */
988 row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
989 (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
990 }
991 }
992 else {
993 i_color bg;
994
995 i_get_file_background(im, &bg);
996 data = mymalloc(im->xsize * im->channels);
997 if (data) {
998 while (cinfo.next_scanline < cinfo.image_height) {
999 /* jpeg_write_scanlines expects an array of pointers to scanlines.
1000 * Here the array is only one element long, but you could pass
1001 * more than one scanline at a time if that's more convenient.
1002 */
1003 i_gsamp_bg(im, 0, im->xsize, cinfo.next_scanline, data,
1004 want_channels, &bg);
1005 row_pointer[0] = data;
1006 (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
1007 }
1008 myfree(data);
1009 }
1010 else {
1011 jpeg_destroy_compress(&cinfo);
1012 i_push_error(0, "out of memory");
1013 return 0; /* out of memory? */
1014 }
1015 }
1016
1017 /* Step 6: Finish compression */
1018
1019 jpeg_finish_compress(&cinfo);
1020
1021 jpeg_destroy_compress(&cinfo);
1022
1023 if (i_io_close(ig))
1024 return 0;
1025
1026 return(1);
1027 }
1028
1029 /*
1030 =back
1031
1032 =head1 AUTHOR
1033
1034 Arnar M. Hrafnkelsson, [email protected]
1035
1036 =head1 SEE ALSO
1037
1038 Imager(3)
1039
1040 =cut
1041 */