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);
97 DBG("readed %u bytes at %p", len, start);
100 // XXX: maybe only generate a warning and return EOI markers to recover from such errors (also in skip_input_data)
101 IMAGE_ERROR(i->err.io->context, IMAGE_ERROR_READ_FAILED, "Incomplete JPEG file");
102 longjmp(i->err.setjmp_buf, 1);
104 i->fastbuf_pos = start + len;
105 i->src.next_input_byte = start;
106 i->src.bytes_in_buffer = len;
111 libjpeg_fastbuf_read_commit(struct libjpeg_read_internals *i)
113 DBG("libjpeg_fb_read_commit()");
114 bdirect_read_commit(i->fastbuf, i->fastbuf_pos);
118 libjpeg_init_source(j_decompress_ptr cinfo)
120 DBG("libjpeg_init_source()");
121 libjpeg_fastbuf_read_prepare((struct libjpeg_read_internals *)cinfo);
125 libjpeg_term_source(j_decompress_ptr cinfo UNUSED)
127 DBG("libjpeg_term_source()");
128 //libjpeg_fastbuf_read_commit((struct libjpeg_read_internals *)cinfo);
132 libjpeg_fill_input_buffer(j_decompress_ptr cinfo)
134 DBG("libjpeg_fill_input_buffer()");
135 struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
136 libjpeg_fastbuf_read_commit(i);
137 libjpeg_fastbuf_read_prepare(i);
142 libjpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
144 DBG("libjpeg_skip_input_data(num_bytes=%d)", (int)num_bytes);
147 struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
148 if ((unsigned long)num_bytes <= i->src.bytes_in_buffer)
150 i->src.next_input_byte += num_bytes;
151 i->src.bytes_in_buffer -= num_bytes;
155 num_bytes -= i->src.bytes_in_buffer;
156 libjpeg_fastbuf_read_commit(i);
157 if (!bskip(i->fastbuf, num_bytes))
159 IMAGE_ERROR(i->err.io->context, IMAGE_ERROR_READ_FAILED, "Incomplete JPEG file");
160 longjmp(i->err.setjmp_buf, 1);
162 libjpeg_fastbuf_read_prepare(i);
168 libjpeg_fastbuf_write_prepare(struct libjpeg_write_internals *i)
171 uns len = bdirect_write_prepare(i->fastbuf, &start);
172 i->fastbuf_pos = start + len;
173 i->dest.next_output_byte = start;
174 i->dest.free_in_buffer = len;
177 IMAGE_ERROR(i->err.io->context, IMAGE_ERROR_WRITE_FAILED, "Unexpected end of stream");
178 longjmp(i->err.setjmp_buf, 1);
183 libjpeg_init_destination(j_compress_ptr cinfo)
185 DBG("libjpeg_init_destination()");
186 libjpeg_fastbuf_write_prepare((struct libjpeg_write_internals *)cinfo);
190 libjpeg_term_destination(j_compress_ptr cinfo)
192 DBG("libjpeg_term_destination()");
193 struct libjpeg_write_internals *i = (struct libjpeg_write_internals *)cinfo;
194 bdirect_write_commit(i->fastbuf, (byte *)i->dest.next_output_byte);
198 libjpeg_empty_output_buffer(j_compress_ptr cinfo)
200 DBG("libjpeg_empty_output_buffer()");
201 struct libjpeg_write_internals *i = (struct libjpeg_write_internals *)cinfo;
202 bdirect_write_commit(i->fastbuf, i->fastbuf_pos);
203 libjpeg_fastbuf_write_prepare(i);
208 libjpeg_read_byte(struct libjpeg_read_internals *i)
210 DBG("libjpeg_read_byte()");
211 if (!i->src.bytes_in_buffer)
212 if (!libjpeg_fill_input_buffer(&i->cinfo))
213 ERREXIT(&i->cinfo, JERR_CANT_SUSPEND);
214 i->src.bytes_in_buffer--;
215 return *i->src.next_input_byte++;
219 libjpeg_read_buf(struct libjpeg_read_internals *i, byte *buf, uns len)
221 DBG("libjpeg_read_buf(len=%u)", len);
224 if (!i->src.bytes_in_buffer)
225 if (!libjpeg_fill_input_buffer(&i->cinfo))
226 ERREXIT(&i->cinfo, JERR_CANT_SUSPEND);
227 uns buf_size = i->src.bytes_in_buffer;
228 uns read_size = MIN(buf_size, len);
229 memcpy(buf, i->src.next_input_byte, read_size);
230 i->src.bytes_in_buffer -= read_size;
231 i->src.next_input_byte += read_size;
236 static byte libjpeg_exif_header[6] = { 'E', 'x', 'i', 'f', 0, 0 };
239 libjpeg_app1_preprocessor(j_decompress_ptr cinfo)
241 struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
242 struct image_io *io = i->err.io;
243 uns len = libjpeg_read_byte(i) << 8;
244 len += libjpeg_read_byte(i);
245 DBG("Found APP1 marker, len=%u", len);
249 if (len < 7 /*|| io->exif_size*/)
251 libjpeg_skip_input_data(cinfo, len);
255 libjpeg_read_buf(i, header, 6);
256 if (memcmp(header, libjpeg_exif_header, 6))
258 libjpeg_skip_input_data(cinfo, len - 6);
262 io->exif_data = mp_alloc(io->internal_pool, len);
263 memcpy(io->exif_data, header, 6);
264 libjpeg_read_buf(i, io->exif_data + 6, len - 6);
265 DBG("Parsed EXIF of length %u", len);
270 libjpeg_read_cancel(struct image_io *io)
272 DBG("libjpeg_read_cancel()");
273 struct libjpeg_read_internals *i = io->read_data;
274 jpeg_destroy_decompress(&i->cinfo);
278 libjpeg_read_header(struct image_io *io)
280 DBG("libjpeg_read_header()");
281 struct libjpeg_read_internals *i = io->read_data = mp_alloc(io->internal_pool, sizeof(*i));
282 i->fastbuf = io->fastbuf;
284 /* Create libjpeg read structure */
285 DBG("Creating libjpeg read structure");
286 i->cinfo.err = jpeg_std_error(&i->err.pub);
287 i->err.pub.error_exit = libjpeg_read_error_exit;
288 i->err.pub.emit_message = libjpeg_emit_message;
290 if (setjmp(i->err.setjmp_buf))
292 DBG("Libjpeg failed to read the image, longjump saved us");
293 jpeg_destroy_decompress(&i->cinfo);
296 jpeg_create_decompress(&i->cinfo);
298 /* Initialize source manager */
299 i->cinfo.src = &i->src;
300 i->src.init_source = libjpeg_init_source;
301 i->src.fill_input_buffer = libjpeg_fill_input_buffer;
302 i->src.skip_input_data = libjpeg_skip_input_data;
303 i->src.resync_to_restart = jpeg_resync_to_restart;
304 i->src.term_source = libjpeg_term_source;
306 if (io->flags & IMAGE_IO_WANT_EXIF)
307 jpeg_set_marker_processor(&i->cinfo, JPEG_APP0 + 1, libjpeg_app1_preprocessor);
309 /* Read JPEG header and setup decompression options */
310 DBG("Reading image header");
311 jpeg_read_header(&i->cinfo, TRUE);
312 switch (i->cinfo.jpeg_color_space)
315 io->flags = COLOR_SPACE_GRAYSCALE;
318 io->flags = COLOR_SPACE_RGB;
321 io->flags = COLOR_SPACE_YCBCR;
324 io->flags = COLOR_SPACE_CMYK;
327 io->flags = COLOR_SPACE_YCCK;
330 if (unlikely(i->cinfo.num_components < 1 || i->cinfo.num_components > 4))
332 jpeg_destroy_decompress(&i->cinfo);
333 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Invalid color space.");
336 io->flags = COLOR_SPACE_UNKNOWN + i->cinfo.num_components;
339 if (unlikely(i->cinfo.num_components != (int)color_space_channels[io->flags]))
341 jpeg_destroy_decompress(&i->cinfo);
342 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Invalid number of color channels.");
345 io->cols = i->cinfo.image_width;
346 io->rows = i->cinfo.image_height;
347 io->number_of_colors = (i->cinfo.num_components < 4) ? (1U << (i->cinfo.num_components * 8)) : 0xffffffff;
348 io->read_cancel = libjpeg_read_cancel;
353 libjpeg_read_data(struct image_io *io)
355 DBG("libjpeg_read_data()");
357 struct libjpeg_read_internals *i = io->read_data;
358 uns read_flags = io->flags;
360 /* Select color space */
361 switch (read_flags & IMAGE_COLOR_SPACE)
363 case COLOR_SPACE_GRAYSCALE:
364 i->cinfo.out_color_space = JCS_GRAYSCALE;
366 case COLOR_SPACE_YCBCR:
367 i->cinfo.out_color_space = JCS_YCbCr;
369 case COLOR_SPACE_CMYK:
370 i->cinfo.out_color_space = JCS_CMYK;
372 case COLOR_SPACE_YCCK:
373 i->cinfo.out_color_space = JCS_YCCK;
376 switch (i->cinfo.jpeg_color_space)
379 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_CMYK;
380 i->cinfo.out_color_space = JCS_CMYK;
383 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_YCCK;
384 i->cinfo.out_color_space = JCS_YCCK;
387 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_RGB;
388 i->cinfo.out_color_space = JCS_RGB;
394 /* Prepare the image */
395 struct image_io_read_data_internals rdi;
396 if (io->cols <= (i->cinfo.image_width >> 3) && io->rows <= (i->cinfo.image_height >> 3))
398 DBG("Scaling to 1/8");
399 i->cinfo.scale_num = 1;
400 i->cinfo.scale_denom = 8;
402 else if (io->cols <= (i->cinfo.image_width >> 2) && io->rows <= (i->cinfo.image_height >> 2))
404 DBG("Scaling to 1/4");
405 i->cinfo.scale_num = 1;
406 i->cinfo.scale_denom = 4;
408 else if (io->cols <= (i->cinfo.image_width >> 1) && io->rows <= (i->cinfo.image_height >> 1))
410 DBG("Scaling to 1/2");
411 i->cinfo.scale_num = 1;
412 i->cinfo.scale_denom = 2;
414 jpeg_calc_output_dimensions(&i->cinfo);
415 DBG("Output dimensions %ux%u", (uns)i->cinfo.output_width, (uns)i->cinfo.output_height);
416 if (unlikely(!image_io_read_data_prepare(&rdi, io, i->cinfo.output_width, i->cinfo.output_height, read_flags)))
418 jpeg_destroy_decompress(&i->cinfo);
423 if (setjmp(i->err.setjmp_buf))
425 DBG("Libjpeg failed to read the image, longjump saved us");
426 jpeg_destroy_decompress(&i->cinfo);
427 image_io_read_data_break(&rdi, io);
431 /* Decompress the image */
432 struct image *img = rdi.image;
433 jpeg_start_decompress(&i->cinfo);
434 if ((int)img->pixel_size == i->cinfo.output_components)
436 byte *pixels = img->pixels;
437 for (uns r = img->rows; r--; )
439 jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&pixels, 1);
440 pixels += img->row_size;
445 switch (img->pixel_size)
447 case 2: /* Grayscale -> Grayscale+Alpha */
449 ASSERT(i->cinfo.output_components == 1);
450 byte buf[img->cols], *src;
451 # define IMAGE_WALK_PREFIX(x) walk_##x
452 # define IMAGE_WALK_INLINE
453 # define IMAGE_WALK_IMAGE img
454 # define IMAGE_WALK_UNROLL 4
455 # define IMAGE_WALK_COL_STEP 2
456 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
457 # define IMAGE_WALK_DO_STEP do{ walk_pos[0] = *src++; walk_pos[1] = 255; }while(0)
458 # include "images/image-walk.h"
461 case 4: /* * -> *+Alpha or aligned * */
463 ASSERT(i->cinfo.output_components == 3);
464 byte buf[img->cols * 3], *src;
465 # define IMAGE_WALK_PREFIX(x) walk_##x
466 # define IMAGE_WALK_INLINE
467 # define IMAGE_WALK_IMAGE img
468 # define IMAGE_WALK_UNROLL 4
469 # define IMAGE_WALK_COL_STEP 4
470 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
471 # define IMAGE_WALK_DO_STEP do{ *(u32 *)walk_pos = *(u32 *)src; walk_pos[3] = 255; src += 3; }while(0)
472 # include "images/image-walk.h"
481 ASSERT(i->cinfo.output_scanline == i->cinfo.output_height);
483 /* Destroy libjpeg object */
484 jpeg_finish_decompress(&i->cinfo);
485 jpeg_destroy_decompress(&i->cinfo);
487 /* Finish the image */
488 return image_io_read_data_finish(&rdi, io);
492 libjpeg_write(struct image_io *io)
494 DBG("libjpeg_write()");
495 struct libjpeg_write_internals i;
496 i.fastbuf = io->fastbuf;
498 /* Create libjpeg write structure */
499 DBG("Creating libjpeg write structure");
500 i.cinfo.err = jpeg_std_error(&i.err.pub);
501 i.err.pub.error_exit = libjpeg_write_error_exit;
502 i.err.pub.emit_message = libjpeg_emit_message;
504 if (setjmp(i.err.setjmp_buf))
506 DBG("Libjpeg failed to write the image, longjump saved us");
507 jpeg_destroy_compress(&i.cinfo);
510 jpeg_create_compress(&i.cinfo);
512 /* Initialize destination manager */
513 i.cinfo.dest = &i.dest;
514 i.dest.init_destination = libjpeg_init_destination;
515 i.dest.term_destination = libjpeg_term_destination;
516 i.dest.empty_output_buffer = libjpeg_empty_output_buffer;
518 /* Set output parameters */
519 struct image *img = io->image;
520 i.cinfo.image_width = img->cols;
521 i.cinfo.image_height = img->rows;
522 switch (img->flags & IMAGE_COLOR_SPACE)
524 case COLOR_SPACE_GRAYSCALE:
525 i.cinfo.in_color_space = JCS_GRAYSCALE;
527 case COLOR_SPACE_RGB:
528 i.cinfo.in_color_space = JCS_RGB;
530 case COLOR_SPACE_YCBCR:
531 i.cinfo.in_color_space = JCS_YCbCr;
533 case COLOR_SPACE_CMYK:
534 i.cinfo.in_color_space = JCS_CMYK;
536 case COLOR_SPACE_YCCK:
537 i.cinfo.in_color_space = JCS_YCCK;
540 jpeg_destroy_compress(&i.cinfo);
541 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Unsupported pixel format.");
544 i.cinfo.input_components = color_space_channels[img->flags & IMAGE_COLOR_SPACE];
545 jpeg_set_defaults(&i.cinfo);
546 jpeg_set_colorspace(&i.cinfo, i.cinfo.in_color_space);
547 if (io->jpeg_quality)
548 jpeg_set_quality(&i.cinfo, MIN(io->jpeg_quality, 100), 1);
551 /* According to the Exif specification, the Exif APP1 marker has to follow immediately after the SOI,
552 * just as the JFIF specification requires the same for the JFIF APP0 marker!
553 * Therefore a JPEG file cannot legally be both Exif and JFIF. */
554 i.cinfo.write_JFIF_header = FALSE;
555 i.cinfo.write_Adobe_marker = FALSE;
558 /* Compress the image */
559 jpeg_start_compress(&i.cinfo, TRUE);
563 jpeg_write_marker(&i.cinfo, JPEG_APP0 + 1, io->exif_data, io->exif_size);
565 if ((int)img->pixel_size == i.cinfo.input_components)
567 byte *pixels = img->pixels;
568 for (uns r = img->rows; r--; )
570 jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&pixels, 1);
571 pixels += img->row_size;
576 switch (img->pixel_size)
578 case 2: /* Grayscale+Alpha -> Grayscale */
580 ASSERT(i.cinfo.input_components == 1);
581 byte buf[img->cols], *dest = buf;
582 # define IMAGE_WALK_PREFIX(x) walk_##x
583 # define IMAGE_WALK_INLINE
584 # define IMAGE_WALK_IMAGE img
585 # define IMAGE_WALK_UNROLL 4
586 # define IMAGE_WALK_COL_STEP 2
587 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
588 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; }while(0)
589 # include "images/image-walk.h"
592 case 4: /* *+Alpha or aligned * -> * */
594 ASSERT(i.cinfo.input_components == 3);
595 byte buf[img->cols * 3], *dest = buf;
596 # define IMAGE_WALK_PREFIX(x) walk_##x
597 # define IMAGE_WALK_INLINE
598 # define IMAGE_WALK_IMAGE img
599 # define IMAGE_WALK_UNROLL 4
600 # define IMAGE_WALK_COL_STEP 4
601 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
602 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; *dest++ = walk_pos[1]; *dest++ = walk_pos[2]; }while(0)
603 # include "images/image-walk.h"
610 ASSERT(i.cinfo.next_scanline == i.cinfo.image_height);
611 jpeg_finish_compress(&i.cinfo);
612 jpeg_destroy_compress(&i.cinfo);