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);
78 if (unlikely(msg_level == -1))
79 longjmp(((struct libjpeg_err *)(cinfo)->err)->setjmp_buf, 1);
83 libjpeg_fastbuf_read_prepare(struct libjpeg_read_internals *i)
86 uns len = bdirect_read_prepare(i->fastbuf, &start);
87 i->fastbuf_pos = start + len;
88 i->src.next_input_byte = start;
89 i->src.bytes_in_buffer = len;
94 libjpeg_fastbuf_read_commit(struct libjpeg_read_internals *i)
96 bdirect_read_commit(i->fastbuf, i->fastbuf_pos);
100 libjpeg_init_source(j_decompress_ptr cinfo)
102 DBG("libjpeg_init_source()");
103 libjpeg_fastbuf_read_prepare((struct libjpeg_read_internals *)cinfo);
107 libjpeg_term_source(j_decompress_ptr cinfo UNUSED)
109 DBG("libjpeg_term_source()");
110 //libjpeg_fastbuf_read_commit((struct libjpeg_read_internals *)cinfo);
114 libjpeg_fill_input_buffer(j_decompress_ptr cinfo)
116 DBG("libjpeg_fill_input_buffer()");
117 struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
118 libjpeg_fastbuf_read_commit(i);
119 return !!libjpeg_fastbuf_read_prepare(i);
123 libjpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
125 DBG("libjpeg_skip_input_data(num_bytes=%d)", (int)num_bytes);
128 struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
129 if ((unsigned long)num_bytes <= i->src.bytes_in_buffer)
131 i->src.next_input_byte += num_bytes;
132 i->src.bytes_in_buffer -= num_bytes;
136 num_bytes -= i->src.bytes_in_buffer;
137 libjpeg_fastbuf_read_commit(i);
138 if (!bskip(i->fastbuf, num_bytes))
140 IMAGE_ERROR(i->err.io->context, IMAGE_ERROR_READ_FAILED, "Incomplete JPEG file");
141 longjmp(i->err.setjmp_buf, 1);
143 libjpeg_fastbuf_read_prepare(i);
149 libjpeg_fastbuf_write_prepare(struct libjpeg_write_internals *i)
152 uns len = bdirect_write_prepare(i->fastbuf, &start);
153 i->fastbuf_pos = start + len;
154 i->dest.next_output_byte = start;
155 i->dest.free_in_buffer = len;
158 IMAGE_ERROR(i->err.io->context, IMAGE_ERROR_WRITE_FAILED, "Unexpected end of stream");
159 longjmp(i->err.setjmp_buf, 1);
164 libjpeg_init_destination(j_compress_ptr cinfo)
166 DBG("libjpeg_init_destination()");
167 libjpeg_fastbuf_write_prepare((struct libjpeg_write_internals *)cinfo);
171 libjpeg_term_destination(j_compress_ptr cinfo)
173 DBG("libjpeg_term_destination()");
174 struct libjpeg_write_internals *i = (struct libjpeg_write_internals *)cinfo;
175 bdirect_write_commit(i->fastbuf, (byte *)i->dest.next_output_byte);
179 libjpeg_empty_output_buffer(j_compress_ptr cinfo)
181 DBG("libjpeg_empty_output_buffer()");
182 struct libjpeg_write_internals *i = (struct libjpeg_write_internals *)cinfo;
183 bdirect_write_commit(i->fastbuf, i->fastbuf_pos);
184 libjpeg_fastbuf_write_prepare(i);
189 libjpeg_read_byte(struct libjpeg_read_internals *i)
191 DBG("libjpeg_read_byte()");
192 if (!i->src.bytes_in_buffer)
193 if (!libjpeg_fill_input_buffer(&i->cinfo))
194 ERREXIT(&i->cinfo, JERR_CANT_SUSPEND);
195 i->src.bytes_in_buffer--;
196 return *i->src.next_input_byte++;
200 libjpeg_read_buf(struct libjpeg_read_internals *i, byte *buf, uns len)
202 DBG("libjpeg_read_buf(len=%u)", len);
205 if (!i->src.bytes_in_buffer)
206 if (!libjpeg_fill_input_buffer(&i->cinfo))
207 ERREXIT(&i->cinfo, JERR_CANT_SUSPEND);
208 uns buf_size = i->src.bytes_in_buffer;
209 uns read_size = MIN(buf_size, len);
210 memcpy(buf, i->src.next_input_byte, read_size);
211 i->src.bytes_in_buffer -= read_size;
212 i->src.next_input_byte += read_size;
217 static byte libjpeg_exif_header[6] = { 'E', 'x', 'i', 'f', 0, 0 };
220 libjpeg_app1_preprocessor(j_decompress_ptr cinfo)
222 struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
223 struct image_io *io = i->err.io;
224 uns len = libjpeg_read_byte(i) << 8;
225 len += libjpeg_read_byte(i);
226 DBG("Found APP1 marker, len=%u", len);
230 if (len < 7 /*|| io->exif_size*/)
232 libjpeg_skip_input_data(cinfo, len);
236 libjpeg_read_buf(i, header, 6);
237 if (memcmp(header, libjpeg_exif_header, 6))
239 libjpeg_skip_input_data(cinfo, len - 6);
243 io->exif_data = mp_alloc(io->internal_pool, len);
244 memcpy(io->exif_data, header, 6);
245 libjpeg_read_buf(i, io->exif_data + 6, len - 6);
246 DBG("Parsed EXIF of length %u", len);
251 libjpeg_read_cancel(struct image_io *io)
253 DBG("libjpeg_read_cancel()");
254 struct libjpeg_read_internals *i = io->read_data;
255 jpeg_destroy_decompress(&i->cinfo);
259 libjpeg_read_header(struct image_io *io)
261 DBG("libjpeg_read_header()");
262 struct libjpeg_read_internals *i = io->read_data = mp_alloc(io->internal_pool, sizeof(*i));
263 i->fastbuf = io->fastbuf;
265 /* Create libjpeg read structure */
266 DBG("Creating libjpeg read structure");
267 i->cinfo.err = jpeg_std_error(&i->err.pub);
268 i->err.pub.error_exit = libjpeg_read_error_exit;
269 i->err.pub.emit_message = libjpeg_emit_message;
271 if (setjmp(i->err.setjmp_buf))
273 DBG("Libjpeg failed to read the image, longjump saved us");
274 jpeg_destroy_decompress(&i->cinfo);
277 jpeg_create_decompress(&i->cinfo);
279 /* Initialize source manager */
280 i->cinfo.src = &i->src;
281 i->src.init_source = libjpeg_init_source;
282 i->src.fill_input_buffer = libjpeg_fill_input_buffer;
283 i->src.skip_input_data = libjpeg_skip_input_data;
284 i->src.resync_to_restart = jpeg_resync_to_restart;
285 i->src.term_source = libjpeg_term_source;
287 if (io->flags & IMAGE_IO_WANT_EXIF)
288 jpeg_set_marker_processor(&i->cinfo, JPEG_APP0 + 1, libjpeg_app1_preprocessor);
290 /* Read JPEG header and setup decompression options */
291 DBG("Reading image header");
292 jpeg_read_header(&i->cinfo, TRUE);
293 switch (i->cinfo.jpeg_color_space)
296 io->flags = COLOR_SPACE_GRAYSCALE;
299 io->flags = COLOR_SPACE_RGB;
302 io->flags = COLOR_SPACE_YCBCR;
305 io->flags = COLOR_SPACE_CMYK;
308 io->flags = COLOR_SPACE_YCCK;
311 if (unlikely(i->cinfo.num_components < 1 || i->cinfo.num_components > 4))
313 jpeg_destroy_decompress(&i->cinfo);
314 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Invalid color space.");
317 io->flags = COLOR_SPACE_UNKNOWN + i->cinfo.num_components;
320 if (unlikely(i->cinfo.num_components != (int)color_space_channels[io->flags]))
322 jpeg_destroy_decompress(&i->cinfo);
323 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Invalid number of color channels.");
326 io->cols = i->cinfo.image_width;
327 io->rows = i->cinfo.image_height;
328 io->number_of_colors = (i->cinfo.num_components < 4) ? (1U << (i->cinfo.num_components * 8)) : 0xffffffff;
329 io->read_cancel = libjpeg_read_cancel;
334 libjpeg_read_data(struct image_io *io)
336 DBG("libjpeg_read_data()");
338 struct libjpeg_read_internals *i = io->read_data;
339 uns read_flags = io->flags;
341 /* Select color space */
342 switch (read_flags & IMAGE_COLOR_SPACE)
344 case COLOR_SPACE_GRAYSCALE:
345 i->cinfo.out_color_space = JCS_GRAYSCALE;
347 case COLOR_SPACE_YCBCR:
348 i->cinfo.out_color_space = JCS_YCbCr;
350 case COLOR_SPACE_CMYK:
351 i->cinfo.out_color_space = JCS_CMYK;
353 case COLOR_SPACE_YCCK:
354 i->cinfo.out_color_space = JCS_YCCK;
357 switch (i->cinfo.jpeg_color_space)
360 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_CMYK;
361 i->cinfo.out_color_space = JCS_CMYK;
364 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_YCCK;
365 i->cinfo.out_color_space = JCS_YCCK;
368 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_RGB;
369 i->cinfo.out_color_space = JCS_RGB;
375 /* Prepare the image */
376 struct image_io_read_data_internals rdi;
377 if (io->cols <= (i->cinfo.image_width >> 3) && io->rows <= (i->cinfo.image_height >> 3))
379 DBG("Scaling to 1/8");
380 i->cinfo.scale_num = 1;
381 i->cinfo.scale_denom = 8;
383 else if (io->cols <= (i->cinfo.image_width >> 2) && io->rows <= (i->cinfo.image_height >> 2))
385 DBG("Scaling to 1/4");
386 i->cinfo.scale_num = 1;
387 i->cinfo.scale_denom = 4;
389 else if (io->cols <= (i->cinfo.image_width >> 1) && io->rows <= (i->cinfo.image_height >> 1))
391 DBG("Scaling to 1/2");
392 i->cinfo.scale_num = 1;
393 i->cinfo.scale_denom = 2;
395 jpeg_calc_output_dimensions(&i->cinfo);
396 DBG("Output dimensions %ux%u", (uns)i->cinfo.output_width, (uns)i->cinfo.output_height);
397 if (unlikely(!image_io_read_data_prepare(&rdi, io, i->cinfo.output_width, i->cinfo.output_height, read_flags)))
399 jpeg_destroy_decompress(&i->cinfo);
404 if (setjmp(i->err.setjmp_buf))
406 DBG("Libjpeg failed to read the image, longjump saved us");
407 jpeg_destroy_decompress(&i->cinfo);
408 image_io_read_data_break(&rdi, io);
412 /* Decompress the image */
413 struct image *img = rdi.image;
414 jpeg_start_decompress(&i->cinfo);
415 if ((int)img->pixel_size == i->cinfo.output_components)
417 byte *pixels = img->pixels;
418 for (uns r = img->rows; r--; )
420 jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&pixels, 1);
421 pixels += img->row_size;
426 switch (img->pixel_size)
428 case 2: /* Grayscale -> Grayscale+Alpha */
430 ASSERT(i->cinfo.output_components == 1);
431 byte buf[img->cols], *src;
432 # define IMAGE_WALK_PREFIX(x) walk_##x
433 # define IMAGE_WALK_INLINE
434 # define IMAGE_WALK_IMAGE img
435 # define IMAGE_WALK_UNROLL 4
436 # define IMAGE_WALK_COL_STEP 2
437 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
438 # define IMAGE_WALK_DO_STEP do{ walk_pos[0] = *src++; walk_pos[1] = 255; }while(0)
439 # include "images/image-walk.h"
442 case 4: /* * -> *+Alpha or aligned * */
444 ASSERT(i->cinfo.output_components == 3);
445 byte buf[img->cols * 3], *src;
446 # define IMAGE_WALK_PREFIX(x) walk_##x
447 # define IMAGE_WALK_INLINE
448 # define IMAGE_WALK_IMAGE img
449 # define IMAGE_WALK_UNROLL 4
450 # define IMAGE_WALK_COL_STEP 4
451 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
452 # define IMAGE_WALK_DO_STEP do{ *(u32 *)walk_pos = *(u32 *)src; walk_pos[3] = 255; src += 3; }while(0)
453 # include "images/image-walk.h"
462 ASSERT(i->cinfo.output_scanline == i->cinfo.output_height);
464 /* Destroy libjpeg object */
465 jpeg_finish_decompress(&i->cinfo);
466 jpeg_destroy_decompress(&i->cinfo);
468 /* Finish the image */
469 return image_io_read_data_finish(&rdi, io);
473 libjpeg_write(struct image_io *io)
475 DBG("libjpeg_write()");
476 struct libjpeg_write_internals i;
477 i.fastbuf = io->fastbuf;
479 /* Create libjpeg write structure */
480 DBG("Creating libjpeg write structure");
481 i.cinfo.err = jpeg_std_error(&i.err.pub);
482 i.err.pub.error_exit = libjpeg_write_error_exit;
483 i.err.pub.emit_message = libjpeg_emit_message;
485 if (setjmp(i.err.setjmp_buf))
487 DBG("Libjpeg failed to write the image, longjump saved us");
488 jpeg_destroy_compress(&i.cinfo);
491 jpeg_create_compress(&i.cinfo);
493 /* Initialize destination manager */
494 i.cinfo.dest = &i.dest;
495 i.dest.init_destination = libjpeg_init_destination;
496 i.dest.term_destination = libjpeg_term_destination;
497 i.dest.empty_output_buffer = libjpeg_empty_output_buffer;
499 /* Set output parameters */
500 struct image *img = io->image;
501 i.cinfo.image_width = img->cols;
502 i.cinfo.image_height = img->rows;
503 switch (img->flags & IMAGE_COLOR_SPACE)
505 case COLOR_SPACE_GRAYSCALE:
506 i.cinfo.in_color_space = JCS_GRAYSCALE;
508 case COLOR_SPACE_RGB:
509 i.cinfo.in_color_space = JCS_RGB;
511 case COLOR_SPACE_YCBCR:
512 i.cinfo.in_color_space = JCS_YCbCr;
514 case COLOR_SPACE_CMYK:
515 i.cinfo.in_color_space = JCS_CMYK;
517 case COLOR_SPACE_YCCK:
518 i.cinfo.in_color_space = JCS_YCCK;
521 jpeg_destroy_compress(&i.cinfo);
522 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Unsupported pixel format.");
525 i.cinfo.input_components = color_space_channels[img->flags & IMAGE_COLOR_SPACE];
526 jpeg_set_defaults(&i.cinfo);
527 jpeg_set_colorspace(&i.cinfo, i.cinfo.in_color_space);
528 if (io->jpeg_quality)
529 jpeg_set_quality(&i.cinfo, MIN(io->jpeg_quality, 100), 1);
532 /* According to the Exif specification, the Exif APP1 marker has to follow immediately after the SOI,
533 * just as the JFIF specification requires the same for the JFIF APP0 marker!
534 * Therefore a JPEG file cannot legally be both Exif and JFIF. */
535 i.cinfo.write_JFIF_header = FALSE;
536 i.cinfo.write_Adobe_marker = FALSE;
539 /* Compress the image */
540 jpeg_start_compress(&i.cinfo, TRUE);
544 jpeg_write_marker(&i.cinfo, JPEG_APP0 + 1, io->exif_data, io->exif_size);
546 if ((int)img->pixel_size == i.cinfo.input_components)
548 byte *pixels = img->pixels;
549 for (uns r = img->rows; r--; )
551 jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&pixels, 1);
552 pixels += img->row_size;
557 switch (img->pixel_size)
559 case 2: /* Grayscale+Alpha -> Grayscale */
561 ASSERT(i.cinfo.input_components == 1);
562 byte buf[img->cols], *dest = buf;
563 # define IMAGE_WALK_PREFIX(x) walk_##x
564 # define IMAGE_WALK_INLINE
565 # define IMAGE_WALK_IMAGE img
566 # define IMAGE_WALK_UNROLL 4
567 # define IMAGE_WALK_COL_STEP 2
568 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
569 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; }while(0)
570 # include "images/image-walk.h"
573 case 4: /* *+Alpha or aligned * -> * */
575 ASSERT(i.cinfo.input_components == 3);
576 byte buf[img->cols * 3], *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 4
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]; *dest++ = walk_pos[1]; *dest++ = walk_pos[2]; }while(0)
584 # include "images/image-walk.h"
591 ASSERT(i.cinfo.next_scanline == i.cinfo.image_height);
592 jpeg_finish_compress(&i.cinfo);
593 jpeg_destroy_compress(&i.cinfo);