Debian Codegraph @

src/jpeg.c

raw symbols SCIP
1 /*
2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15 */
16
17 #define LE 0 // Exif byte orders
18 #define BE 1
19
20 // Force JCS_EXTENSIONS to off for non-x86 platforms, the way we build our
21 // i386+ppc OSX binary needs this
22 #ifndef __i386__
23 # undef JCS_EXTENSIONS
24 #endif
25
26 // Unfortunately we need a global variable in order to display the filename
27 // during libjpeg output messages
28 #define FILENAME_LEN 255
29 char filename[FILENAME_LEN + 1];
30
31 struct sv_dst_mgr {
32 struct jpeg_destination_mgr jdst;
33 SV *sv_buf;
34 JOCTET *buf;
35 JOCTET *off;
36 };
37
38 typedef struct buf_src_mgr {
39 struct jpeg_source_mgr jsrc;
40 image *im;
41 } buf_src_mgr;
42
43 // Source manager to read JPEG from buffer
44 static void
45 buf_src_init(j_decompress_ptr cinfo)
46 {
47 // Nothing
48 }
49
50 static boolean
51 buf_src_fill_input_buffer(j_decompress_ptr cinfo)
52 {
53 static JOCTET mybuffer[4];
54 buf_src_mgr *src = (buf_src_mgr *)cinfo->src;
55 image *im = src->im;
56
57 DEBUG_TRACE("JPEG fill_input_buffer\n");
58
59 // Consume the entire buffer, even if bytes are still in bytes_in_buffer
60 buffer_consume(im->buf, buffer_len(im->buf));
61
62 if (im->fh != NULL) {
63 if ( !_check_buf(im->fh, im->buf, 1, BUFFER_SIZE) ) {
64 goto eof;
65 }
66 }
67 else {
68 // read from SV into buffer
69 int sv_readlen = MIN(sv_len(im->sv_data) - im->sv_offset, BUFFER_SIZE);
70
71 // corrupt JPEGs read from SV buffers need to check for EOF
72 if (sv_readlen <= 0)
73 goto eof;
74
75 DEBUG_TRACE(" Reading %d bytes of SV data @ %d\n", sv_readlen, im->sv_offset);
76 buffer_append(im->buf, SvPVX(im->sv_data) + im->sv_offset, sv_readlen);
77 im->sv_offset += sv_readlen;
78 }
79
80 cinfo->src->next_input_byte = (JOCTET *)buffer_ptr(im->buf);
81 cinfo->src->bytes_in_buffer = buffer_len(im->buf);
82
83 goto ok;
84
85 eof:
86 // Insert a fake EOI marker if we can't read enough data
87 DEBUG_TRACE(" EOF, returning EOI marker\n");
88
89 mybuffer[0] = (JOCTET) 0xFF;
90 mybuffer[1] = (JOCTET) JPEG_EOI;
91
92 cinfo->src->next_input_byte = mybuffer;
93 cinfo->src->bytes_in_buffer = 2;
94
95 ok:
96 return TRUE;
97 }
98
99 static void
100 buf_src_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
101 {
102 buf_src_mgr *src = (buf_src_mgr *)cinfo->src;
103 image *im = src->im;
104
105 if (num_bytes > 0) {
106 DEBUG_TRACE("JPEG skip requested: num_bytes=%ld, src->bytes_in_buffer=%ld\n", num_bytes, cinfo->src->bytes_in_buffer);
107
108 while (num_bytes > cinfo->src->bytes_in_buffer) {
109 num_bytes -= (long)cinfo->src->bytes_in_buffer;
110
111 // fill_input_buffer will discard the data in the current buffer
112 (void) (*cinfo->src->fill_input_buffer)(cinfo);
113
114 DEBUG_TRACE("After fill_input_buffer, num_bytes=%ld bytes, src->bytes_in_buffer=%ld\n", num_bytes, cinfo->src->bytes_in_buffer);
115 }
116
117 // Discard the remaining bytes, taking into account the amount libjpeg has already read
118 DEBUG_TRACE(" JPEG buffer consume %ld bytes\n", (buffer_len(im->buf) - cinfo->src->bytes_in_buffer) + num_bytes);
119 buffer_consume(im->buf, (buffer_len(im->buf) - cinfo->src->bytes_in_buffer) + num_bytes);
120
121 cinfo->src->next_input_byte = (JOCTET *)buffer_ptr(im->buf);
122 cinfo->src->bytes_in_buffer = buffer_len(im->buf);
123 }
124 }
125
126 static void
127 buf_src_term_source(j_decompress_ptr cinfo)
128 {
129 // Nothing
130 }
131
132 static void
133 image_jpeg_buf_src(image *im)
134 {
135 j_decompress_ptr cinfo = (j_decompress_ptr)im->cinfo;
136 buf_src_mgr *src;
137
138 if (cinfo->src == NULL) {
139 cinfo->src = (struct jpeg_source_mgr *)
140 (*cinfo->mem->alloc_small)((j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(struct buf_src_mgr));
141 }
142
143 src = (buf_src_mgr *)cinfo->src;
144
145 src->im = im;
146
147 src->jsrc.init_source = buf_src_init;
148 src->jsrc.fill_input_buffer = buf_src_fill_input_buffer;
149 src->jsrc.skip_input_data = buf_src_skip_input_data;
150 src->jsrc.resync_to_restart = jpeg_resync_to_restart; // use default
151 src->jsrc.term_source = buf_src_term_source;
152 src->jsrc.bytes_in_buffer = buffer_len(im->buf);
153 src->jsrc.next_input_byte = (JOCTET *)buffer_ptr(im->buf);
154
155 DEBUG_TRACE("Init JPEG buffer src, %d bytes in buffer\n", buffer_len(im->buf));
156 }
157
158 // Destination manager to copy compressed data to an SV
159 static void
160 sv_dst_mgr_init(j_compress_ptr cinfo)
161 {
162 struct sv_dst_mgr *dst = (void *)cinfo->dest;
163
164 New(0, dst->buf, BUFFER_SIZE, JOCTET);
165
166 dst->off = dst->buf;
167 dst->jdst.next_output_byte = dst->off;
168 dst->jdst.free_in_buffer = BUFFER_SIZE;
169 }
170
171 static boolean
172 sv_dst_mgr_empty(j_compress_ptr cinfo)
173 {
174 struct sv_dst_mgr *dst = (void *)cinfo->dest;
175
176 // Copy buffer to SV
177 sv_catpvn(dst->sv_buf, (char *)dst->buf, BUFFER_SIZE);
178
179 // Reuse the buffer for the next chunk
180 dst->off = dst->buf;
181 dst->jdst.next_output_byte = dst->off;
182 dst->jdst.free_in_buffer = BUFFER_SIZE;
183
184 DEBUG_TRACE("sv_dst_mgr_empty, copied %d bytes\n", BUFFER_SIZE);
185
186 return TRUE;
187 }
188
189 static void
190 sv_dst_mgr_term(j_compress_ptr cinfo)
191 {
192 struct sv_dst_mgr *dst = (void *)cinfo->dest;
193
194 size_t sz = BUFFER_SIZE - dst->jdst.free_in_buffer;
195
196 if (sz > 0) {
197 // Copy buffer to SV
198 sv_catpvn(dst->sv_buf, (char *)dst->buf, sz);
199 }
200
201 Safefree(dst->buf);
202
203 DEBUG_TRACE("sv_dst_mgr_term, copied %ld bytes\n", sz);
204 }
205
206 static void
207 image_jpeg_sv_dest(j_compress_ptr cinfo, struct sv_dst_mgr *dst, SV *sv_buf)
208 {
209 dst->sv_buf = sv_buf;
210 dst->jdst.init_destination = sv_dst_mgr_init;
211 dst->jdst.empty_output_buffer = sv_dst_mgr_empty;
212 dst->jdst.term_destination = sv_dst_mgr_term;
213 cinfo->dest = (void *)dst;
214 }
215
216 static void
217 image_jpeg_parse_exif_orientation(image *im, Buffer *exif)
218 {
219 int bo, offset, num_entries;
220
221 buffer_consume(exif, 6); // Exif\0\0
222 bo = (buffer_get_short(exif) == 0x4949) ? LE : BE;
223
224 buffer_consume(exif, 2); // 0x2a00
225
226 offset = (bo == LE) ? buffer_get_int_le(exif) : buffer_get_int(exif);
227 buffer_consume(exif, offset - 8); // skip to offset (from the start of the byte order)
228
229 num_entries = (bo == LE) ? buffer_get_short_le(exif) : buffer_get_short(exif);
230
231 // All we care about is the orientation
232 while (num_entries--) {
233 int type_id = (bo == LE) ? buffer_get_short_le(exif) : buffer_get_short(exif);
234
235 if (type_id == 0x112) {
236 buffer_consume(exif, 6);
237 im->orientation = (bo == LE) ? buffer_get_short_le(exif) : buffer_get_short(exif);
238
239 DEBUG_TRACE("Exif Orientation: %d\n", im->orientation);
240 break;
241 }
242
243 buffer_consume(exif, 10);
244 }
245
246 // Save original orientation in case it is changed by ignore_exif
247 im->orientation_orig = im->orientation;
248 }
249
250 jmp_buf setjmp_buffer;
251 static void
252 libjpeg_error_handler(j_common_ptr cinfo)
253 {
254 cinfo->err->output_message(cinfo);
255 longjmp(setjmp_buffer, 1);
256 return;
257 }
258
259 static void
260 libjpeg_output_message(j_common_ptr cinfo)
261 {
262 char buffer[JMSG_LENGTH_MAX];
263
264 /* Create the message */
265 (*cinfo->err->format_message) (cinfo, buffer);
266
267 warn("Image::Scale libjpeg error: %s (%s)\n", buffer, filename);
268 }
269
270 int
271 image_jpeg_read_header(image *im)
272 {
273 Newz(0, im->cinfo, sizeof(struct jpeg_decompress_struct), struct jpeg_decompress_struct);
274 im->memory_used += sizeof(struct jpeg_decompress_struct);
275
276 Newz(0, im->jpeg_error_pub, sizeof(struct jpeg_error_mgr), struct jpeg_error_mgr);
277
278 im->cinfo->err = jpeg_std_error(im->jpeg_error_pub);
279 im->jpeg_error_pub->error_exit = libjpeg_error_handler;
280 im->jpeg_error_pub->output_message = libjpeg_output_message;
281
282 if (setjmp(setjmp_buffer)) {
283 image_jpeg_finish(im);
284 return 0;
285 }
286
287 // Save filename in case any warnings/errors occur
288 strncpy(filename, SvPVX(im->path), FILENAME_LEN);
289 if (sv_len(im->path) > FILENAME_LEN)
290 filename[FILENAME_LEN] = 0;
291
292 jpeg_create_decompress(im->cinfo);
293
294 // Init custom source manager to read from existing buffer
295 image_jpeg_buf_src(im);
296
297 #ifdef AUDIO_SCAN_DEBUG
298 // Enable for libjpeg debug output
299 //im->cinfo->err->trace_level = 3;
300 #endif
301
302 // Save APP1 marker for EXIF
303 jpeg_save_markers(im->cinfo, 0xE1, 1024 * 64);
304
305 jpeg_read_header(im->cinfo, TRUE);
306
307 im->width = im->cinfo->image_width;
308 im->height = im->cinfo->image_height;
309 im->channels = im->cinfo->num_components;
310
311 // Process Exif looking for orientation tag
312 if (im->cinfo->marker_list != NULL) {
313 jpeg_saved_marker_ptr marker = im->cinfo->marker_list;
314
315 while (marker != NULL) {
316 DEBUG_TRACE("Found marker: %x len %d\n", marker->marker, marker->data_length);
317
318 if (marker->marker == 0xE1
319 && marker->data[0] == 'E' && marker->data[1] == 'x'
320 && marker->data[2] == 'i' && marker->data[3] == 'f'
321 ) {
322 Buffer exif;
323
324 buffer_init(&exif, marker->data_length);
325 buffer_append(&exif, marker->data, marker->data_length);
326
327 image_jpeg_parse_exif_orientation(im, &exif);
328
329 buffer_free(&exif);
330 break;
331 }
332
333 marker = marker->next;
334 }
335 }
336
337 return 1;
338 }
339
340 int
341 image_jpeg_load(image *im)
342 {
343 float scale_factor;
344 int x, w, h, ofs;
345 unsigned char *line[1], *ptr = NULL;
346
347 if (setjmp(setjmp_buffer)) {
348 // See if we have partially decoded an image and hit a fatal error, but still have a usable image
349 if (ptr != NULL) {
350 Safefree(ptr);
351 ptr = NULL;
352 }
353
354 if (im->cinfo->output_scanline > 0) {
355 DEBUG_TRACE("Fatal error but already processed %d scanlines, continuing...\n", im->cinfo->output_scanline);
356 return 1;
357 }
358
359 image_jpeg_finish(im);
360 return 0;
361 }
362
363 // Abort on progressive JPEGs if memory_limit is in use,
364 // as progressive JPEGs can use many MBs of memory and there
365 // is no other easy way to alter libjpeg's memory use
366 if (im->memory_limit && im->cinfo->progressive_mode) {
367 warn("Image::Scale will not decode progressive JPEGs when memory_limit is in use (%s)\n", SvPVX(im->path));
368 image_jpeg_finish(im);
369 return 0;
370 }
371
372 // If reusing the object a second time, we need to read the header again
373 if (im->used) {
374 DEBUG_TRACE("Reusing JPEG object, re-reading header\n");
375
376 if (im->fh != NULL) {
377 // reset file to begining of image
378 PerlIO_seek(im->fh, im->image_offset, SEEK_SET);
379 }
380 else {
381 // reset SV read
382 im->sv_offset = im->image_offset;
383 }
384
385 buffer_clear(im->buf);
386
387 im->cinfo->src->bytes_in_buffer = 0;
388
389 jpeg_read_header(im->cinfo, TRUE);
390 }
391
392 im->cinfo->do_fancy_upsampling = FALSE;
393 im->cinfo->do_block_smoothing = FALSE;
394
395 // Choose optimal scaling factor
396 jpeg_calc_output_dimensions(im->cinfo);
397 scale_factor = (float)im->cinfo->output_width / im->target_width;
398 if (scale_factor > ((float)im->cinfo->output_height / im->target_height))
399 scale_factor = (float)im->cinfo->output_height / im->target_height;
400 if (scale_factor > 1) { // Avoid divide by 0
401 im->cinfo->scale_denom *= (unsigned int)scale_factor;
402 jpeg_calc_output_dimensions(im->cinfo);
403 }
404
405 w = im->cinfo->output_width;
406 h = im->cinfo->output_height;
407
408 // Change the original values to the scaled size
409 im->width = w;
410 im->height = h;
411
412 DEBUG_TRACE("Using JPEG scale factor %d/%d, new output dimensions %d x %d\n",
413 im->cinfo->scale_num, im->cinfo->scale_denom, w, h);
414
415 // Save filename in case any warnings/errors occur
416 strncpy(filename, SvPVX(im->path), FILENAME_LEN);
417 if (sv_len(im->path) > FILENAME_LEN)
418 filename[FILENAME_LEN] = 0;
419
420 // XXX Tested libjpeg-turbo's JCS_EXT_XBGR but it writes zeros
421 // instead of FF for alpha, doesn't support CMYK, etc
422
423 jpeg_start_decompress(im->cinfo);
424
425 // Allocate storage for decompressed image
426 image_alloc(im, w, h);
427
428 ofs = 0;
429
430 New(0, ptr, w * im->cinfo->output_components, unsigned char);
431 line[0] = ptr;
432
433 if (im->cinfo->output_components == 3) { // RGB
434 while (im->cinfo->output_scanline < im->cinfo->output_height) {
435 jpeg_read_scanlines(im->cinfo, line, 1);
436 for (x = 0; x < w; x++) {
437 im->pixbuf[ofs++] = COL(ptr[x + x + x], ptr[x + x + x + 1], ptr[x + x + x + 2]);
438 }
439 }
440 }
441 else if (im->cinfo->output_components == 4) { // CMYK inverted (Photoshop)
442 while (im->cinfo->output_scanline < im->cinfo->output_height) {
443 JSAMPROW row = *line;
444 jpeg_read_scanlines(im->cinfo, line, 1);
445 for (x = 0; x < w; x++) {
446 int c = *row++;
447 int m = *row++;
448 int y = *row++;
449 int k = *row++;
450
451 im->pixbuf[ofs++] = COL((c * k) / MAXJSAMPLE, (m * k) / MAXJSAMPLE, (y * k) / MAXJSAMPLE);
452 }
453 }
454 }
455 else { // grayscale
456 while (im->cinfo->output_scanline < im->cinfo->output_height) {
457 jpeg_read_scanlines(im->cinfo, line, 1);
458 for (x = 0; x < w; x++) {
459 im->pixbuf[ofs++] = COL(ptr[x], ptr[x], ptr[x]);
460 }
461 }
462 }
463
464 Safefree(ptr);
465
466 jpeg_finish_decompress(im->cinfo);
467
468 return 1;
469 }
470
471 static void
472 image_jpeg_compress(image *im, struct jpeg_compress_struct *cinfo, int quality)
473 {
474 int x;
475 #ifdef JCS_EXTENSIONS
476 JSAMPROW *data = NULL;
477 #else
478 volatile unsigned char *data = NULL;
479 JSAMPROW row_pointer[1];
480 int i, row_stride;
481 #endif
482
483 cinfo->image_width = im->target_width;
484 cinfo->image_height = im->target_height;
485 cinfo->input_components = 3;
486 cinfo->in_color_space = JCS_RGB; // output is always RGB even if source was grayscale
487
488 if (setjmp(setjmp_buffer)) {
489 if (data != NULL)
490 Safefree(data);
491 return;
492 }
493
494 #ifdef JCS_EXTENSIONS
495 // Use libjpeg-turbo support for direct reading from source buffer
496 cinfo->input_components = 4;
497 cinfo->in_color_space = JCS_EXT_XBGR;
498 #endif
499
500 jpeg_set_defaults(cinfo);
501 jpeg_set_quality(cinfo, quality, TRUE);
502 jpeg_start_compress(cinfo, TRUE);
503
504 #ifdef JCS_EXTENSIONS
505 New(0, data, im->target_height, JSAMPROW);
506
507 for (x = 0; x < im->target_height; x++)
508 data[x] = (JSAMPROW)&im->outbuf[x * im->target_width];
509
510 while (cinfo->next_scanline < cinfo->image_height) {
511 jpeg_write_scanlines(cinfo, &data[cinfo->next_scanline],
512 cinfo->image_height - cinfo->next_scanline);
513 }
514
515 #else
516 // Normal libjpeg
517 row_stride = cinfo->image_width * 3;
518 New(0, data, row_stride, unsigned char);
519
520 i = 0;
521 while (cinfo->next_scanline < cinfo->image_height) {
522 for (x = 0; x < cinfo->image_width; x++) {
523 data[x + x + x] = COL_RED( im->outbuf[i]);
524 data[x + x + x + 1] = COL_GREEN(im->outbuf[i]);
525 data[x + x + x + 2] = COL_BLUE( im->outbuf[i]);
526 i++;
527 }
528 row_pointer[0] = (unsigned char *)data;
529 jpeg_write_scanlines(cinfo, row_pointer, 1);
530 }
531 #endif
532
533 jpeg_finish_compress(cinfo);
534
535 Safefree(data);
536 }
537
538 void
539 image_jpeg_save(image *im, const char *path, int quality)
540 {
541 struct jpeg_compress_struct cinfo;
542 struct jpeg_error_mgr jerr;
543 FILE *out;
544
545 if (im->outbuf == NULL)
546 croak("Image::Scale cannot write JPEG with no output data\n");
547
548 if ((out = fopen(path, "wb")) == NULL) {
549 croak("Image::Scale cannot open %s for writing\n", path);
550 }
551
552 cinfo.err = jpeg_std_error(&jerr);
553 jpeg_create_compress(&cinfo);
554 jpeg_stdio_dest(&cinfo, out);
555
556 image_jpeg_compress(im, &cinfo, quality);
557
558 jpeg_destroy_compress(&cinfo);
559 fclose(out);
560 }
561
562 void
563 image_jpeg_to_sv(image *im, int quality, SV *sv_buf)
564 {
565 struct jpeg_compress_struct cinfo;
566 struct jpeg_error_mgr jerr;
567 struct sv_dst_mgr dst;
568
569 if (im->outbuf == NULL)
570 croak("Image::Scale cannot write JPEG with no output data\n");
571
572 cinfo.err = jpeg_std_error(&jerr);
573 jpeg_create_compress(&cinfo);
574 image_jpeg_sv_dest(&cinfo, &dst, sv_buf);
575
576 image_jpeg_compress(im, &cinfo, quality);
577
578 jpeg_destroy_compress(&cinfo);
579 }
580
581 void
582 image_jpeg_finish(image *im)
583 {
584 if (im->cinfo != NULL) {
585 DEBUG_TRACE("libjpeg destroy\n");
586 jpeg_destroy_decompress(im->cinfo);
587 Safefree(im->cinfo);
588 im->cinfo = NULL;
589 im->memory_used -= sizeof(struct jpeg_decompress_struct);
590
591 Safefree(im->jpeg_error_pub);
592 im->jpeg_error_pub = NULL;
593 }
594 }