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_YCbCr;
383 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_RGB;
384 i->cinfo.out_color_space = JCS_RGB;
390 /* Prepare the image */
391 struct image_io_read_data_internals rdi;
392 if (io->cols <= (i->cinfo.image_width >> 3) && io->rows <= (i->cinfo.image_height >> 3))
394 DBG("Scaling to 1/8");
395 i->cinfo.scale_num = 1;
396 i->cinfo.scale_denom = 8;
398 else if (io->cols <= (i->cinfo.image_width >> 2) && io->rows <= (i->cinfo.image_height >> 2))
400 DBG("Scaling to 1/4");
401 i->cinfo.scale_num = 1;
402 i->cinfo.scale_denom = 4;
404 else if (io->cols <= (i->cinfo.image_width >> 1) && io->rows <= (i->cinfo.image_height >> 1))
406 DBG("Scaling to 1/2");
407 i->cinfo.scale_num = 1;
408 i->cinfo.scale_denom = 2;
410 jpeg_calc_output_dimensions(&i->cinfo);
411 DBG("Output dimensions %ux%u", (uns)i->cinfo.output_width, (uns)i->cinfo.output_height);
412 if (unlikely(!image_io_read_data_prepare(&rdi, io, i->cinfo.output_width, i->cinfo.output_height, read_flags)))
414 jpeg_destroy_decompress(&i->cinfo);
419 if (setjmp(i->err.setjmp_buf))
421 DBG("Libjpeg failed to read the image, longjump saved us");
422 jpeg_destroy_decompress(&i->cinfo);
423 image_io_read_data_break(&rdi, io);
427 /* Decompress the image */
428 struct image *img = rdi.image;
429 jpeg_start_decompress(&i->cinfo);
430 if ((int)img->pixel_size == i->cinfo.output_components)
432 byte *pixels = img->pixels;
433 for (uns r = img->rows; r--; )
435 jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&pixels, 1);
436 pixels += img->row_size;
441 switch (img->pixel_size)
443 case 2: /* Grayscale -> Grayscale+Alpha */
445 ASSERT(i->cinfo.output_components == 1);
446 byte buf[img->cols], *src;
447 # define IMAGE_WALK_PREFIX(x) walk_##x
448 # define IMAGE_WALK_INLINE
449 # define IMAGE_WALK_IMAGE img
450 # define IMAGE_WALK_UNROLL 4
451 # define IMAGE_WALK_COL_STEP 2
452 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
453 # define IMAGE_WALK_DO_STEP do{ walk_pos[0] = *src++; walk_pos[1] = 255; }while(0)
454 # include "images/image-walk.h"
457 case 4: /* * -> *+Alpha or aligned * */
459 ASSERT(i->cinfo.output_components == 3);
460 byte buf[img->cols * 3], *src;
461 # define IMAGE_WALK_PREFIX(x) walk_##x
462 # define IMAGE_WALK_INLINE
463 # define IMAGE_WALK_IMAGE img
464 # define IMAGE_WALK_UNROLL 4
465 # define IMAGE_WALK_COL_STEP 4
466 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
467 # define IMAGE_WALK_DO_STEP do{ *(u32 *)walk_pos = *(u32 *)src; walk_pos[3] = 255; src += 3; }while(0)
468 # include "images/image-walk.h"
477 ASSERT(i->cinfo.output_scanline == i->cinfo.output_height);
479 /* Destroy libjpeg object */
480 jpeg_finish_decompress(&i->cinfo);
481 jpeg_destroy_decompress(&i->cinfo);
483 /* Finish the image */
484 return image_io_read_data_finish(&rdi, io);
488 libjpeg_write(struct image_io *io)
490 DBG("libjpeg_write()");
491 struct libjpeg_write_internals i;
492 i.fastbuf = io->fastbuf;
494 /* Create libjpeg write structure */
495 DBG("Creating libjpeg write structure");
496 i.cinfo.err = jpeg_std_error(&i.err.pub);
497 i.err.pub.error_exit = libjpeg_write_error_exit;
498 i.err.pub.emit_message = libjpeg_emit_message;
500 if (setjmp(i.err.setjmp_buf))
502 DBG("Libjpeg failed to write the image, longjump saved us");
503 jpeg_destroy_compress(&i.cinfo);
506 jpeg_create_compress(&i.cinfo);
508 /* Initialize destination manager */
509 i.cinfo.dest = &i.dest;
510 i.dest.init_destination = libjpeg_init_destination;
511 i.dest.term_destination = libjpeg_term_destination;
512 i.dest.empty_output_buffer = libjpeg_empty_output_buffer;
514 /* Set output parameters */
515 struct image *img = io->image;
516 i.cinfo.image_width = img->cols;
517 i.cinfo.image_height = img->rows;
518 switch (img->flags & IMAGE_COLOR_SPACE)
520 case COLOR_SPACE_GRAYSCALE:
521 i.cinfo.in_color_space = JCS_GRAYSCALE;
523 case COLOR_SPACE_RGB:
524 i.cinfo.in_color_space = JCS_RGB;
526 case COLOR_SPACE_YCBCR:
527 i.cinfo.in_color_space = JCS_YCbCr;
529 case COLOR_SPACE_CMYK:
530 i.cinfo.in_color_space = JCS_CMYK;
532 case COLOR_SPACE_YCCK:
533 i.cinfo.in_color_space = JCS_YCCK;
536 jpeg_destroy_compress(&i.cinfo);
537 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Unsupported pixel format.");
540 i.cinfo.input_components = color_space_channels[img->flags & IMAGE_COLOR_SPACE];
541 jpeg_set_defaults(&i.cinfo);
542 if (io->jpeg_quality)
543 jpeg_set_quality(&i.cinfo, MIN(io->jpeg_quality, 100), 1);
546 /* According to the Exif specification, the Exif APP1 marker has to follow immediately after the SOI,
547 * just as the JFIF specification requires the same for the JFIF APP0 marker!
548 * Therefore a JPEG file cannot legally be both Exif and JFIF. */
549 i.cinfo.write_JFIF_header = FALSE;
550 i.cinfo.write_Adobe_marker = FALSE;
553 /* Compress the image */
554 jpeg_start_compress(&i.cinfo, TRUE);
558 jpeg_write_marker(&i.cinfo, JPEG_APP0 + 1, io->exif_data, io->exif_size);
560 if ((int)img->pixel_size == i.cinfo.input_components)
562 byte *pixels = img->pixels;
563 for (uns r = img->rows; r--; )
565 jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&pixels, 1);
566 pixels += img->row_size;
571 switch (img->pixel_size)
573 case 2: /* Grayscale+Alpha -> Grayscale */
575 ASSERT(i.cinfo.input_components == 1);
576 byte buf[img->cols], *dest = buf;
577 # define IMAGE_WALK_PREFIX(x) walk_##x
578 # define IMAGE_WALK_INLINE
579 # define IMAGE_WALK_IMAGE img
580 # define IMAGE_WALK_UNROLL 4
581 # define IMAGE_WALK_COL_STEP 2
582 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
583 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; }while(0)
584 # include "images/image-walk.h"
587 case 4: /* *+Alpha or aligned * -> * */
589 ASSERT(i.cinfo.input_components == 3);
590 byte buf[img->cols * 3], *dest = buf;
591 # define IMAGE_WALK_PREFIX(x) walk_##x
592 # define IMAGE_WALK_INLINE
593 # define IMAGE_WALK_IMAGE img
594 # define IMAGE_WALK_UNROLL 4
595 # define IMAGE_WALK_COL_STEP 4
596 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
597 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; *dest++ = walk_pos[1]; *dest++ = walk_pos[2]; }while(0)
598 # include "images/image-walk.h"
605 ASSERT(i.cinfo.next_scanline == i.cinfo.image_height);
606 jpeg_finish_compress(&i.cinfo);
607 jpeg_destroy_compress(&i.cinfo);