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_CMYK;
381 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_YCCK;
382 i->cinfo.out_color_space = JCS_YCCK;
385 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_RGB;
386 i->cinfo.out_color_space = JCS_RGB;
392 /* Prepare the image */
393 struct image_io_read_data_internals rdi;
394 if (io->cols <= (i->cinfo.image_width >> 3) && io->rows <= (i->cinfo.image_height >> 3))
396 DBG("Scaling to 1/8");
397 i->cinfo.scale_num = 1;
398 i->cinfo.scale_denom = 8;
400 else if (io->cols <= (i->cinfo.image_width >> 2) && io->rows <= (i->cinfo.image_height >> 2))
402 DBG("Scaling to 1/4");
403 i->cinfo.scale_num = 1;
404 i->cinfo.scale_denom = 4;
406 else if (io->cols <= (i->cinfo.image_width >> 1) && io->rows <= (i->cinfo.image_height >> 1))
408 DBG("Scaling to 1/2");
409 i->cinfo.scale_num = 1;
410 i->cinfo.scale_denom = 2;
412 jpeg_calc_output_dimensions(&i->cinfo);
413 DBG("Output dimensions %ux%u", (uns)i->cinfo.output_width, (uns)i->cinfo.output_height);
414 if (unlikely(!image_io_read_data_prepare(&rdi, io, i->cinfo.output_width, i->cinfo.output_height, read_flags)))
416 jpeg_destroy_decompress(&i->cinfo);
421 if (setjmp(i->err.setjmp_buf))
423 DBG("Libjpeg failed to read the image, longjump saved us");
424 jpeg_destroy_decompress(&i->cinfo);
425 image_io_read_data_break(&rdi, io);
429 /* Decompress the image */
430 struct image *img = rdi.image;
431 jpeg_start_decompress(&i->cinfo);
432 if ((int)img->pixel_size == i->cinfo.output_components)
434 byte *pixels = img->pixels;
435 for (uns r = img->rows; r--; )
437 jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&pixels, 1);
438 pixels += img->row_size;
443 switch (img->pixel_size)
445 case 2: /* Grayscale -> Grayscale+Alpha */
447 ASSERT(i->cinfo.output_components == 1);
448 byte buf[img->cols], *src;
449 # define IMAGE_WALK_PREFIX(x) walk_##x
450 # define IMAGE_WALK_INLINE
451 # define IMAGE_WALK_IMAGE img
452 # define IMAGE_WALK_UNROLL 4
453 # define IMAGE_WALK_COL_STEP 2
454 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
455 # define IMAGE_WALK_DO_STEP do{ walk_pos[0] = *src++; walk_pos[1] = 255; }while(0)
456 # include "images/image-walk.h"
459 case 4: /* * -> *+Alpha or aligned * */
461 ASSERT(i->cinfo.output_components == 3);
462 byte buf[img->cols * 3], *src;
463 # define IMAGE_WALK_PREFIX(x) walk_##x
464 # define IMAGE_WALK_INLINE
465 # define IMAGE_WALK_IMAGE img
466 # define IMAGE_WALK_UNROLL 4
467 # define IMAGE_WALK_COL_STEP 4
468 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
469 # define IMAGE_WALK_DO_STEP do{ *(u32 *)walk_pos = *(u32 *)src; walk_pos[3] = 255; src += 3; }while(0)
470 # include "images/image-walk.h"
479 ASSERT(i->cinfo.output_scanline == i->cinfo.output_height);
481 /* Destroy libjpeg object */
482 jpeg_finish_decompress(&i->cinfo);
483 jpeg_destroy_decompress(&i->cinfo);
485 /* Finish the image */
486 return image_io_read_data_finish(&rdi, io);
490 libjpeg_write(struct image_io *io)
492 DBG("libjpeg_write()");
493 struct libjpeg_write_internals i;
494 i.fastbuf = io->fastbuf;
496 /* Create libjpeg write structure */
497 DBG("Creating libjpeg write structure");
498 i.cinfo.err = jpeg_std_error(&i.err.pub);
499 i.err.pub.error_exit = libjpeg_write_error_exit;
500 i.err.pub.emit_message = libjpeg_emit_message;
502 if (setjmp(i.err.setjmp_buf))
504 DBG("Libjpeg failed to write the image, longjump saved us");
505 jpeg_destroy_compress(&i.cinfo);
508 jpeg_create_compress(&i.cinfo);
510 /* Initialize destination manager */
511 i.cinfo.dest = &i.dest;
512 i.dest.init_destination = libjpeg_init_destination;
513 i.dest.term_destination = libjpeg_term_destination;
514 i.dest.empty_output_buffer = libjpeg_empty_output_buffer;
516 /* Set output parameters */
517 struct image *img = io->image;
518 i.cinfo.image_width = img->cols;
519 i.cinfo.image_height = img->rows;
520 switch (img->flags & IMAGE_COLOR_SPACE)
522 case COLOR_SPACE_GRAYSCALE:
523 i.cinfo.in_color_space = JCS_GRAYSCALE;
525 case COLOR_SPACE_RGB:
526 i.cinfo.in_color_space = JCS_RGB;
528 case COLOR_SPACE_YCBCR:
529 i.cinfo.in_color_space = JCS_YCbCr;
531 case COLOR_SPACE_CMYK:
532 i.cinfo.in_color_space = JCS_CMYK;
534 case COLOR_SPACE_YCCK:
535 i.cinfo.in_color_space = JCS_YCCK;
538 jpeg_destroy_compress(&i.cinfo);
539 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Unsupported pixel format.");
542 i.cinfo.input_components = color_space_channels[img->flags & IMAGE_COLOR_SPACE];
543 jpeg_set_defaults(&i.cinfo);
544 jpeg_set_colorspace(&i.cinfo, i.cinfo.in_color_space);
545 if (io->jpeg_quality)
546 jpeg_set_quality(&i.cinfo, MIN(io->jpeg_quality, 100), 1);
549 /* According to the Exif specification, the Exif APP1 marker has to follow immediately after the SOI,
550 * just as the JFIF specification requires the same for the JFIF APP0 marker!
551 * Therefore a JPEG file cannot legally be both Exif and JFIF. */
552 i.cinfo.write_JFIF_header = FALSE;
553 i.cinfo.write_Adobe_marker = FALSE;
556 /* Compress the image */
557 jpeg_start_compress(&i.cinfo, TRUE);
561 jpeg_write_marker(&i.cinfo, JPEG_APP0 + 1, io->exif_data, io->exif_size);
563 if ((int)img->pixel_size == i.cinfo.input_components)
565 byte *pixels = img->pixels;
566 for (uns r = img->rows; r--; )
568 jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&pixels, 1);
569 pixels += img->row_size;
574 switch (img->pixel_size)
576 case 2: /* Grayscale+Alpha -> Grayscale */
578 ASSERT(i.cinfo.input_components == 1);
579 byte buf[img->cols], *dest = buf;
580 # define IMAGE_WALK_PREFIX(x) walk_##x
581 # define IMAGE_WALK_INLINE
582 # define IMAGE_WALK_IMAGE img
583 # define IMAGE_WALK_UNROLL 4
584 # define IMAGE_WALK_COL_STEP 2
585 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
586 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; }while(0)
587 # include "images/image-walk.h"
590 case 4: /* *+Alpha or aligned * -> * */
592 ASSERT(i.cinfo.input_components == 3);
593 byte buf[img->cols * 3], *dest = buf;
594 # define IMAGE_WALK_PREFIX(x) walk_##x
595 # define IMAGE_WALK_INLINE
596 # define IMAGE_WALK_IMAGE img
597 # define IMAGE_WALK_UNROLL 4
598 # define IMAGE_WALK_COL_STEP 4
599 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
600 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; *dest++ = walk_pos[1]; *dest++ = walk_pos[2]; }while(0)
601 # include "images/image-walk.h"
608 ASSERT(i.cinfo.next_scanline == i.cinfo.image_height);
609 jpeg_finish_compress(&i.cinfo);
610 jpeg_destroy_compress(&i.cinfo);