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 <ucw/mempool.h>
14 #include <ucw/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 uint 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 uint 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, uint 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 uint buf_size = i->src.bytes_in_buffer;
228 uint 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 uint 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 uint read_flags = io->flags;
360 /* Select color space */
361 switch (i->cinfo.jpeg_color_space)
364 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_YCBCR;
365 i->cinfo.out_color_space = JCS_YCbCr;
368 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_YCBCR;
369 i->cinfo.out_color_space = JCS_YCbCr;
372 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_CMYK;
373 i->cinfo.out_color_space = JCS_CMYK;
376 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_YCCK;
377 i->cinfo.out_color_space = JCS_YCCK;
380 read_flags = (read_flags & ~IMAGE_COLOR_SPACE & IMAGE_CHANNELS_FORMAT) | COLOR_SPACE_RGB;
381 i->cinfo.out_color_space = JCS_RGB;
385 /* Prepare the image */
386 struct image_io_read_data_internals rdi;
387 if (io->cols <= (i->cinfo.image_width >> 3) && io->rows <= (i->cinfo.image_height >> 3))
389 DBG("Scaling to 1/8");
390 i->cinfo.scale_num = 1;
391 i->cinfo.scale_denom = 8;
393 else if (io->cols <= (i->cinfo.image_width >> 2) && io->rows <= (i->cinfo.image_height >> 2))
395 DBG("Scaling to 1/4");
396 i->cinfo.scale_num = 1;
397 i->cinfo.scale_denom = 4;
399 else if (io->cols <= (i->cinfo.image_width >> 1) && io->rows <= (i->cinfo.image_height >> 1))
401 DBG("Scaling to 1/2");
402 i->cinfo.scale_num = 1;
403 i->cinfo.scale_denom = 2;
405 jpeg_calc_output_dimensions(&i->cinfo);
406 DBG("Output dimensions %ux%u", (uint)i->cinfo.output_width, (uint)i->cinfo.output_height);
407 if (unlikely(!image_io_read_data_prepare(&rdi, io, i->cinfo.output_width, i->cinfo.output_height, read_flags)))
409 jpeg_destroy_decompress(&i->cinfo);
414 if (setjmp(i->err.setjmp_buf))
416 DBG("Libjpeg failed to read the image, longjump saved us");
417 jpeg_destroy_decompress(&i->cinfo);
418 image_io_read_data_break(&rdi, io);
422 /* Decompress the image */
423 struct image *img = rdi.image;
424 jpeg_start_decompress(&i->cinfo);
425 if ((int)img->pixel_size == i->cinfo.output_components)
427 byte *pixels = img->pixels;
428 for (uint r = img->rows; r--; )
430 jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&pixels, 1);
431 pixels += img->row_size;
436 switch (img->pixel_size)
438 case 2: /* Grayscale -> Grayscale+Alpha */
440 ASSERT(i->cinfo.output_components == 1);
441 byte buf[img->cols], *src;
442 # define IMAGE_WALK_PREFIX(x) walk_##x
443 # define IMAGE_WALK_INLINE
444 # define IMAGE_WALK_IMAGE img
445 # define IMAGE_WALK_UNROLL 4
446 # define IMAGE_WALK_COL_STEP 2
447 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
448 # define IMAGE_WALK_DO_STEP do{ walk_pos[0] = *src++; walk_pos[1] = 255; }while(0)
449 # include <images/image-walk.h>
452 case 4: /* * -> *+Alpha or aligned * */
454 ASSERT(i->cinfo.output_components == 3);
455 byte buf[img->cols * 3], *src;
456 # define IMAGE_WALK_PREFIX(x) walk_##x
457 # define IMAGE_WALK_INLINE
458 # define IMAGE_WALK_IMAGE img
459 # define IMAGE_WALK_UNROLL 4
460 # define IMAGE_WALK_COL_STEP 4
461 # define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
462 # define IMAGE_WALK_DO_STEP do{ *(u32 *)walk_pos = *(u32 *)src; walk_pos[3] = 255; src += 3; }while(0)
463 # include <images/image-walk.h>
472 ASSERT(i->cinfo.output_scanline == i->cinfo.output_height);
474 /* Destroy libjpeg object */
475 jpeg_finish_decompress(&i->cinfo);
476 jpeg_destroy_decompress(&i->cinfo);
478 /* Finish the image */
479 return image_io_read_data_finish(&rdi, io);
483 libjpeg_write(struct image_io *io)
485 DBG("libjpeg_write()");
486 struct libjpeg_write_internals i;
487 i.fastbuf = io->fastbuf;
489 /* Create libjpeg write structure */
490 DBG("Creating libjpeg write structure");
491 i.cinfo.err = jpeg_std_error(&i.err.pub);
492 i.err.pub.error_exit = libjpeg_write_error_exit;
493 i.err.pub.emit_message = libjpeg_emit_message;
495 if (setjmp(i.err.setjmp_buf))
497 DBG("Libjpeg failed to write the image, longjump saved us");
498 jpeg_destroy_compress(&i.cinfo);
501 jpeg_create_compress(&i.cinfo);
503 /* Initialize destination manager */
504 i.cinfo.dest = &i.dest;
505 i.dest.init_destination = libjpeg_init_destination;
506 i.dest.term_destination = libjpeg_term_destination;
507 i.dest.empty_output_buffer = libjpeg_empty_output_buffer;
509 /* Set output parameters */
510 struct image *img = io->image;
511 i.cinfo.image_width = img->cols;
512 i.cinfo.image_height = img->rows;
513 switch (img->flags & IMAGE_COLOR_SPACE)
515 case COLOR_SPACE_GRAYSCALE:
516 i.cinfo.in_color_space = JCS_GRAYSCALE;
518 case COLOR_SPACE_RGB:
519 i.cinfo.in_color_space = JCS_RGB;
521 case COLOR_SPACE_YCBCR:
522 i.cinfo.in_color_space = JCS_YCbCr;
524 case COLOR_SPACE_CMYK:
525 i.cinfo.in_color_space = JCS_CMYK;
527 case COLOR_SPACE_YCCK:
528 i.cinfo.in_color_space = JCS_YCCK;
531 jpeg_destroy_compress(&i.cinfo);
532 IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Unsupported pixel format.");
535 i.cinfo.input_components = color_space_channels[img->flags & IMAGE_COLOR_SPACE];
536 jpeg_set_defaults(&i.cinfo);
537 jpeg_set_colorspace(&i.cinfo, i.cinfo.in_color_space);
538 if (io->jpeg_quality)
539 jpeg_set_quality(&i.cinfo, MIN(io->jpeg_quality, 100), 1);
542 /* According to the Exif specification, the Exif APP1 marker has to follow immediately after the SOI,
543 * just as the JFIF specification requires the same for the JFIF APP0 marker!
544 * Therefore a JPEG file cannot legally be both Exif and JFIF. */
545 i.cinfo.write_JFIF_header = FALSE;
546 i.cinfo.write_Adobe_marker = FALSE;
549 /* Compress the image */
550 jpeg_start_compress(&i.cinfo, TRUE);
554 jpeg_write_marker(&i.cinfo, JPEG_APP0 + 1, io->exif_data, io->exif_size);
556 if ((int)img->pixel_size == i.cinfo.input_components)
558 byte *pixels = img->pixels;
559 for (uint r = img->rows; r--; )
561 jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&pixels, 1);
562 pixels += img->row_size;
567 switch (img->pixel_size)
569 case 2: /* Grayscale+Alpha -> Grayscale */
571 ASSERT(i.cinfo.input_components == 1);
572 byte buf[img->cols], *dest = buf;
573 # define IMAGE_WALK_PREFIX(x) walk_##x
574 # define IMAGE_WALK_INLINE
575 # define IMAGE_WALK_IMAGE img
576 # define IMAGE_WALK_UNROLL 4
577 # define IMAGE_WALK_COL_STEP 2
578 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
579 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; }while(0)
580 # include <images/image-walk.h>
583 case 4: /* *+Alpha or aligned * -> * */
585 ASSERT(i.cinfo.input_components == 3);
586 byte buf[img->cols * 3], *dest = buf;
587 # define IMAGE_WALK_PREFIX(x) walk_##x
588 # define IMAGE_WALK_INLINE
589 # define IMAGE_WALK_IMAGE img
590 # define IMAGE_WALK_UNROLL 4
591 # define IMAGE_WALK_COL_STEP 4
592 # define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
593 # define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; *dest++ = walk_pos[1]; *dest++ = walk_pos[2]; }while(0)
594 # include <images/image-walk.h>
601 ASSERT(i.cinfo.next_scanline == i.cinfo.image_height);
602 jpeg_finish_compress(&i.cinfo);
603 jpeg_destroy_compress(&i.cinfo);