2 * Image Library -- libjpeg
4 * (c) 2006 Pavel Charvat <pchar@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
13 #include "lib/mempool.h"
14 #include "lib/fastbuf.h"
15 #include "images/images.h"
16 #include "images/error.h"
17 #include "images/color.h"
18 #include "images/io-main.h"
21 #include <sys/types.h>
27 struct jpeg_error_mgr pub;
32 struct libjpeg_read_internals {
33 struct jpeg_decompress_struct cinfo;
34 struct jpeg_source_mgr src;
35 struct libjpeg_err err;
36 struct fastbuf *fastbuf;
40 struct libjpeg_write_internals {
41 struct jpeg_compress_struct cinfo;
42 struct jpeg_destination_mgr dest;
43 struct libjpeg_err err;
44 struct fastbuf *fastbuf;
49 libjpeg_read_error_exit(j_common_ptr cinfo)
51 DBG("libjpeg_error_exit()");
52 struct libjpeg_err *e = (struct libjpeg_err *)cinfo->err;
53 byte buf[JMSG_LENGTH_MAX];
54 e->pub.format_message(cinfo, buf);
55 IMAGE_ERROR(e->io->context, IMAGE_ERROR_READ_FAILED, "libjpeg: %s", buf);
56 longjmp(e->setjmp_buf, 1);
60 libjpeg_write_error_exit(j_common_ptr cinfo)
62 DBG("libjpeg_error_exit()");
63 struct libjpeg_err *e = (struct libjpeg_err *)cinfo->err;
64 byte buf[JMSG_LENGTH_MAX];
65 e->pub.format_message(cinfo, buf);
66 IMAGE_ERROR(e->io->context, IMAGE_ERROR_WRITE_FAILED, "libjpeg: %s", buf);
67 longjmp(e->setjmp_buf, 1);
71 libjpeg_emit_message(j_common_ptr cinfo UNUSED, int msg_level UNUSED)
74 byte buf[JMSG_LENGTH_MAX];
75 cinfo->err->format_message(cinfo, buf);
76 DBG("libjpeg_emit_message(): [%d] %s", msg_level, buf);
79 // Terminate on warning?
80 if (unlikely(msg_level == -1))
82 struct libjpeg_err *e = (struct libjpeg_err *)cinfo->err;
83 byte buf[JMSG_LENGTH_MAX];
84 cinfo->err->format_message(cinfo, buf);
85 IMAGE_ERROR(e->io->context, 0, "libjpeg: %s", buf);
86 longjmp(e->setjmp_buf, 1);
92 libjpeg_fastbuf_read_prepare(struct libjpeg_read_internals *i)
94 DBG("libjpeg_fb_read_prepare()");
96 uns len = bdirect_read_prepare(i->fastbuf, &start);
99 // XXX: maybe only generate a warning and return EOI markers to recover from such errors (also in skip_input_data)
100 IMAGE_ERROR(i->err.io->context, IMAGE_ERROR_READ_FAILED, "Incomplete JPEG file");
101 longjmp(i->err.setjmp_buf, 1);
103 i->fastbuf_pos = start + len;
104 i->src.next_input_byte = start;
105 i->src.bytes_in_buffer = len;
110 libjpeg_fastbuf_read_commit(struct libjpeg_read_internals *i)
112 DBG("libjpeg_fb_read_commit()");
113 bdirect_read_commit(i->fastbuf, i->fastbuf_pos);
117 libjpeg_init_source(j_decompress_ptr cinfo)
119 DBG("libjpeg_init_source()");
120 libjpeg_fastbuf_read_prepare((struct libjpeg_read_internals *)cinfo);
124 libjpeg_term_source(j_decompress_ptr cinfo UNUSED)
126 DBG("libjpeg_term_source()");
127 //libjpeg_fastbuf_read_commit((struct libjpeg_read_internals *)cinfo);
131 libjpeg_fill_input_buffer(j_decompress_ptr cinfo)
133 DBG("libjpeg_fill_input_buffer()");
134 struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
135 libjpeg_fastbuf_read_commit(i);
140 libjpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
142 DBG("libjpeg_skip_input_data(num_bytes=%d)", (int)num_bytes);
145 struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
146 if ((unsigned long)num_bytes <= i->src.bytes_in_buffer)
148 i->src.next_input_byte += num_bytes;
149 i->src.bytes_in_buffer -= num_bytes;
153 num_bytes -= i->src.bytes_in_buffer;
154 libjpeg_fastbuf_read_commit(i);
155 if (!bskip(i->fastbuf, num_bytes))
157 IMAGE_ERROR(i->err.io->context, IMAGE_ERROR_READ_FAILED, "Incomplete JPEG file");
158 longjmp(i->err.setjmp_buf, 1);
160 libjpeg_fastbuf_read_prepare(i);
166 libjpeg_fastbuf_write_prepare(struct libjpeg_write_internals *i)
169 uns len = bdirect_write_prepare(i->fastbuf, &start);
170 i->fastbuf_pos = start + len;
171 i->dest.next_output_byte = start;
172 i->dest.free_in_buffer = len;
175 IMAGE_ERROR(i->err.io->context, IMAGE_ERROR_WRITE_FAILED, "Unexpected end of stream");
176 longjmp(i->err.setjmp_buf, 1);
181 libjpeg_init_destination(j_compress_ptr cinfo)
183 DBG("libjpeg_init_destination()");
184 libjpeg_fastbuf_write_prepare((struct libjpeg_write_internals *)cinfo);
188 libjpeg_term_destination(j_compress_ptr cinfo)
190 DBG("libjpeg_term_destination()");
191 struct libjpeg_write_internals *i = (struct libjpeg_write_internals *)cinfo;
192 bdirect_write_commit(i->fastbuf, (byte *)i->dest.next_output_byte);
196 libjpeg_empty_output_buffer(j_compress_ptr cinfo)
198 DBG("libjpeg_empty_output_buffer()");
199 struct libjpeg_write_internals *i = (struct libjpeg_write_internals *)cinfo;
200 bdirect_write_commit(i->fastbuf, i->fastbuf_pos);
201 libjpeg_fastbuf_write_prepare(i);
206 libjpeg_read_byte(struct libjpeg_read_internals *i)
208 DBG("libjpeg_read_byte()");
209 if (!i->src.bytes_in_buffer)
210 if (!libjpeg_fill_input_buffer(&i->cinfo))
211 ERREXIT(&i->cinfo, JERR_CANT_SUSPEND);
212 i->src.bytes_in_buffer--;
213 return *i->src.next_input_byte++;
217 libjpeg_read_buf(struct libjpeg_read_internals *i, byte *buf, uns len)
219 DBG("libjpeg_read_buf(len=%u)", len);
222 if (!i->src.bytes_in_buffer)
223 if (!libjpeg_fill_input_buffer(&i->cinfo))
224 ERREXIT(&i->cinfo, JERR_CANT_SUSPEND);
225 uns buf_size = i->src.bytes_in_buffer;
226 uns read_size = MIN(buf_size, len);
227 memcpy(buf, i->src.next_input_byte, read_size);
228 i->src.bytes_in_buffer -= read_size;
229 i->src.next_input_byte += read_size;
234 static byte libjpeg_exif_header[6] = { 'E', 'x', 'i', 'f', 0, 0 };
237 libjpeg_app1_preprocessor(j_decompress_ptr cinfo)
239 struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
240 struct image_io *io = i->err.io;
241 uns len = libjpeg_read_byte(i) << 8;
242 len += libjpeg_read_byte(i);
243 DBG("Found APP1 marker, len=%u", len);
247 if (len < 7 /*|| io->exif_size*/)
249 libjpeg_skip_input_data(cinfo, len);
253 libjpeg_read_buf(i, header, 6);
254 if (memcmp(header, libjpeg_exif_header, 6))
256 libjpeg_skip_input_data(cinfo, len - 6);
260 io->exif_data = mp_alloc(io->internal_pool, len);
261 memcpy(io->exif_data, header, 6);
262 libjpeg_read_buf(i, io->exif_data + 6, len - 6);
263 DBG("Parsed EXIF of length %u", len);
268 libjpeg_read_cancel(struct image_io *io)
270 DBG("libjpeg_read_cancel()");
271 struct libjpeg_read_internals *i = io->read_data;
272 jpeg_destroy_decompress(&i->cinfo);
276 libjpeg_read_header(struct image_io *io)
278 DBG("libjpeg_read_header()");
279 struct libjpeg_read_internals *i = io->read_data = mp_alloc(io->internal_pool, sizeof(*i));
280 i->fastbuf = io->fastbuf;
282 /* Create libjpeg read structure */
283 DBG("Creating libjpeg read structure");
284 i->cinfo.err = jpeg_std_error(&i->err.pub);
285 i->err.pub.error_exit = libjpeg_read_error_exit;
286 i->err.pub.emit_message = libjpeg_emit_message;
288 if (setjmp(i->err.setjmp_buf))
290 DBG("Libjpeg failed to read the image, longjump saved us");
291 jpeg_destroy_decompress(&i->cinfo);
294 jpeg_create_decompress(&i->cinfo);
296 /* Initialize source manager */
297 i->cinfo.src = &i->src;
298 i->src.init_source = libjpeg_init_source;
299 i->src.fill_input_buffer = libjpeg_fill_input_buffer;
300 i->src.skip_input_data = libjpeg_skip_input_data;
301 i->src.resync_to_restart = jpeg_resync_to_restart;
302 i->src.term_source = libjpeg_term_source;
304 if (io->flags & IMAGE_IO_WANT_EXIF)
305 jpeg_set_marker_processor(&i->cinfo, JPEG_APP0 + 1, libjpeg_app1_preprocessor);
307 /* Read JPEG header and setup decompression options */
308 DBG("Reading image header");
309 jpeg_read_header(&i->cinfo, TRUE);
310 switch (i->cinfo.jpeg_color_space)
313 io->flags = COLOR_SPACE_GRAYSCALE;
316 io->flags = COLOR_SPACE_RGB;
319 io->flags = COLOR_SPACE_YCBCR;
322 io->flags = COLOR_SPACE_CMYK;
325 io->flags = COLOR_SPACE_YCCK;
328 if (unlikely(i->cinfo.num_components < 1 || i->cinfo.num_components > 4))
330 jpeg_destroy_decompress(&i->cinfo);
331 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Invalid color space.");
334 io->flags = COLOR_SPACE_UNKNOWN + i->cinfo.num_components;
337 if (unlikely(i->cinfo.num_components != (int)color_space_channels[io->flags]))
339 jpeg_destroy_decompress(&i->cinfo);
340 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Invalid number of color channels.");
343 io->cols = i->cinfo.image_width;
344 io->rows = i->cinfo.image_height;
345 io->number_of_colors = (i->cinfo.num_components < 4) ? (1U << (i->cinfo.num_components * 8)) : 0xffffffff;
346 io->read_cancel = libjpeg_read_cancel;
351 libjpeg_read_data(struct image_io *io)
353 DBG("libjpeg_read_data()");
355 struct libjpeg_read_internals *i = io->read_data;
356 uns read_flags = io->flags;
358 /* Select color space */
359 switch (read_flags & IMAGE_COLOR_SPACE)
361 case COLOR_SPACE_GRAYSCALE:
362 i->cinfo.out_color_space = JCS_GRAYSCALE;
364 case COLOR_SPACE_YCBCR:
365 i->cinfo.out_color_space = JCS_YCbCr;
367 case COLOR_SPACE_CMYK:
368 i->cinfo.out_color_space = JCS_CMYK;
370 case COLOR_SPACE_YCCK:
371 i->cinfo.out_color_space = JCS_YCCK;
374 switch (i->cinfo.jpeg_color_space)
377 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_CMYK;
378 i->cinfo.out_color_space = JCS_YCbCr;
381 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_RGB;
382 i->cinfo.out_color_space = JCS_RGB;
388 /* Prepare the image */
389 struct image_io_read_data_internals rdi;
390 if (io->cols <= (i->cinfo.image_width >> 3) && io->rows <= (i->cinfo.image_height >> 3))
392 DBG("Scaling to 1/8");
393 i->cinfo.scale_num = 1;
394 i->cinfo.scale_denom = 8;
396 else if (io->cols <= (i->cinfo.image_width >> 2) && io->rows <= (i->cinfo.image_height >> 2))
398 DBG("Scaling to 1/4");
399 i->cinfo.scale_num = 1;
400 i->cinfo.scale_denom = 4;
402 else if (io->cols <= (i->cinfo.image_width >> 1) && io->rows <= (i->cinfo.image_height >> 1))
404 DBG("Scaling to 1/2");
405 i->cinfo.scale_num = 1;
406 i->cinfo.scale_denom = 2;
408 jpeg_calc_output_dimensions(&i->cinfo);
409 DBG("Output dimensions %ux%u", (uns)i->cinfo.output_width, (uns)i->cinfo.output_height);
410 if (unlikely(!image_io_read_data_prepare(&rdi, io, i->cinfo.output_width, i->cinfo.output_height, read_flags)))
412 jpeg_destroy_decompress(&i->cinfo);
417 if (setjmp(i->err.setjmp_buf))
419 DBG("Libjpeg failed to read the image, longjump saved us");
420 jpeg_destroy_decompress(&i->cinfo);
421 image_io_read_data_break(&rdi, io);
425 /* Decompress the image */
426 struct image *img = rdi.image;
427 jpeg_start_decompress(&i->cinfo);
428 if ((int)img->pixel_size == i->cinfo.output_components)
430 byte *pixels = img->pixels;
431 for (uns r = img->rows; r--; )
433 jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&pixels, 1);
434 pixels += img->row_size;
439 switch (img->pixel_size)
441 case 2: /* Grayscale -> Grayscale+Alpha */
443 ASSERT(i->cinfo.output_components == 1);
444 byte buf[img->cols], *src;
445 # define IMAGE_WALK_PREFIX(x) walk_##x
446 # define IMAGE_WALK_INLINE
447 # define IMAGE_WALK_IMAGE img
448 # define IMAGE_WALK_UNROLL 4
449 # define IMAGE_WALK_COL_STEP 2
450 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
451 # define IMAGE_WALK_DO_STEP do{ walk_pos[0] = *src++; walk_pos[1] = 255; }while(0)
452 # include "images/image-walk.h"
455 case 4: /* * -> *+Alpha or aligned * */
457 ASSERT(i->cinfo.output_components == 3);
458 byte buf[img->cols * 3], *src;
459 # define IMAGE_WALK_PREFIX(x) walk_##x
460 # define IMAGE_WALK_INLINE
461 # define IMAGE_WALK_IMAGE img
462 # define IMAGE_WALK_UNROLL 4
463 # define IMAGE_WALK_COL_STEP 4
464 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
465 # define IMAGE_WALK_DO_STEP do{ *(u32 *)walk_pos = *(u32 *)src; walk_pos[3] = 255; src += 3; }while(0)
466 # include "images/image-walk.h"
475 ASSERT(i->cinfo.output_scanline == i->cinfo.output_height);
477 /* Destroy libjpeg object */
478 jpeg_finish_decompress(&i->cinfo);
479 jpeg_destroy_decompress(&i->cinfo);
481 /* Finish the image */
482 return image_io_read_data_finish(&rdi, io);
486 libjpeg_write(struct image_io *io)
488 DBG("libjpeg_write()");
489 struct libjpeg_write_internals i;
490 i.fastbuf = io->fastbuf;
492 /* Create libjpeg write structure */
493 DBG("Creating libjpeg write structure");
494 i.cinfo.err = jpeg_std_error(&i.err.pub);
495 i.err.pub.error_exit = libjpeg_write_error_exit;
496 i.err.pub.emit_message = libjpeg_emit_message;
498 if (setjmp(i.err.setjmp_buf))
500 DBG("Libjpeg failed to write the image, longjump saved us");
501 jpeg_destroy_compress(&i.cinfo);
504 jpeg_create_compress(&i.cinfo);
506 /* Initialize destination manager */
507 i.cinfo.dest = &i.dest;
508 i.dest.init_destination = libjpeg_init_destination;
509 i.dest.term_destination = libjpeg_term_destination;
510 i.dest.empty_output_buffer = libjpeg_empty_output_buffer;
512 /* Set output parameters */
513 struct image *img = io->image;
514 i.cinfo.image_width = img->cols;
515 i.cinfo.image_height = img->rows;
516 switch (img->flags & IMAGE_COLOR_SPACE)
518 case COLOR_SPACE_GRAYSCALE:
519 i.cinfo.in_color_space = JCS_GRAYSCALE;
521 case COLOR_SPACE_RGB:
522 i.cinfo.in_color_space = JCS_RGB;
524 case COLOR_SPACE_YCBCR:
525 i.cinfo.in_color_space = JCS_YCbCr;
527 case COLOR_SPACE_CMYK:
528 i.cinfo.in_color_space = JCS_CMYK;
530 case COLOR_SPACE_YCCK:
531 i.cinfo.in_color_space = JCS_YCCK;
534 jpeg_destroy_compress(&i.cinfo);
535 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Unsupported pixel format.");
538 i.cinfo.input_components = color_space_channels[img->flags & IMAGE_COLOR_SPACE];
539 jpeg_set_defaults(&i.cinfo);
540 if (io->jpeg_quality)
541 jpeg_set_quality(&i.cinfo, MIN(io->jpeg_quality, 100), 1);
544 /* According to the Exif specification, the Exif APP1 marker has to follow immediately after the SOI,
545 * just as the JFIF specification requires the same for the JFIF APP0 marker!
546 * Therefore a JPEG file cannot legally be both Exif and JFIF. */
547 i.cinfo.write_JFIF_header = FALSE;
548 i.cinfo.write_Adobe_marker = FALSE;
551 /* Compress the image */
552 jpeg_start_compress(&i.cinfo, TRUE);
556 jpeg_write_marker(&i.cinfo, JPEG_APP0 + 1, io->exif_data, io->exif_size);
558 if ((int)img->pixel_size == i.cinfo.input_components)
560 byte *pixels = img->pixels;
561 for (uns r = img->rows; r--; )
563 jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&pixels, 1);
564 pixels += img->row_size;
569 switch (img->pixel_size)
571 case 2: /* Grayscale+Alpha -> Grayscale */
573 ASSERT(i.cinfo.input_components == 1);
574 byte buf[img->cols], *dest = buf;
575 # define IMAGE_WALK_PREFIX(x) walk_##x
576 # define IMAGE_WALK_INLINE
577 # define IMAGE_WALK_IMAGE img
578 # define IMAGE_WALK_UNROLL 4
579 # define IMAGE_WALK_COL_STEP 2
580 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
581 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; }while(0)
582 # include "images/image-walk.h"
585 case 4: /* *+Alpha or aligned * -> * */
587 ASSERT(i.cinfo.input_components == 3);
588 byte buf[img->cols * 3], *dest = buf;
589 # define IMAGE_WALK_PREFIX(x) walk_##x
590 # define IMAGE_WALK_INLINE
591 # define IMAGE_WALK_IMAGE img
592 # define IMAGE_WALK_UNROLL 4
593 # define IMAGE_WALK_COL_STEP 4
594 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
595 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; *dest++ = walk_pos[1]; *dest++ = walk_pos[2]; }while(0)
596 # include "images/image-walk.h"
603 ASSERT(i.cinfo.next_scanline == i.cinfo.image_height);
604 jpeg_finish_compress(&i.cinfo);
605 jpeg_destroy_compress(&i.cinfo);