]> mj.ucw.cz Git - libucw.git/blob - images/io-libjpeg.c
30bd0fff4b90061f16a135a275e7bbd2c9a73634
[libucw.git] / images / io-libjpeg.c
1 /*
2  *      Image Library -- libjpeg
3  *
4  *      (c) 2006 Pavel Charvat <pchar@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #undef LOCAL_DEBUG
11
12 #include "lib/lib.h"
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"
19
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <jpeglib.h>
23 #include <jerror.h>
24 #include <setjmp.h>
25
26 struct libjpeg_err {
27   struct jpeg_error_mgr pub;
28   jmp_buf setjmp_buf;
29   struct image_io *io;
30 };
31
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;
37   byte *fastbuf_pos;
38 };
39
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;
45   byte *fastbuf_pos;
46 };
47
48 static void NONRET
49 libjpeg_read_error_exit(j_common_ptr cinfo)
50 {
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, "%s", buf);
56   longjmp(e->setjmp_buf, 1);
57 }
58
59 static void NONRET
60 libjpeg_write_error_exit(j_common_ptr cinfo)
61 {
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, "%s", buf);
67   longjmp(e->setjmp_buf, 1);
68 }
69
70 static void
71 libjpeg_emit_message(j_common_ptr cinfo UNUSED, int msg_level UNUSED)
72 {
73 #ifdef LOCAL_DEBUG
74   byte buf[JMSG_LENGTH_MAX];
75   cinfo->err->format_message(cinfo, buf);
76   DBG("libjpeg_emit_message(): [%d] %s", msg_level, buf);
77 #endif
78   if (unlikely(msg_level == -1))
79     longjmp(((struct libjpeg_err *)(cinfo)->err)->setjmp_buf, 1);
80 }
81
82 static inline uns
83 libjpeg_fastbuf_read_prepare(struct libjpeg_read_internals *i)
84 {
85   byte *start;
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;
90   return len;
91 }
92
93 static inline void
94 libjpeg_fastbuf_read_commit(struct libjpeg_read_internals *i)
95 {
96   bdirect_read_commit(i->fastbuf, i->fastbuf_pos);
97 }
98
99 static void
100 libjpeg_init_source(j_decompress_ptr cinfo)
101 {
102   DBG("libjpeg_init_source()");
103   libjpeg_fastbuf_read_prepare((struct libjpeg_read_internals *)cinfo);
104 }
105
106 static void
107 libjpeg_term_source(j_decompress_ptr cinfo UNUSED)
108 {
109   DBG("libjpeg_term_source()");
110   //libjpeg_fastbuf_read_commit((struct libjpeg_read_internals *)cinfo);
111 }
112
113 static boolean
114 libjpeg_fill_input_buffer(j_decompress_ptr cinfo)
115 {
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);
120 }
121
122 static void
123 libjpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
124 {
125   DBG("libjpeg_skip_input_data(num_bytes=%d)", (int)num_bytes);
126   if (num_bytes > 0)
127     {
128       struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
129       if ((unsigned long)num_bytes <= i->src.bytes_in_buffer)
130         {
131           i->src.next_input_byte += num_bytes;
132           i->src.bytes_in_buffer -= num_bytes;
133         }
134       else
135         {
136           num_bytes -= i->src.bytes_in_buffer;
137           libjpeg_fastbuf_read_commit(i);
138           bskip(i->fastbuf, num_bytes);
139           libjpeg_fastbuf_read_prepare(i);
140         }
141     }
142 }
143
144 static inline void
145 libjpeg_fastbuf_write_prepare(struct libjpeg_write_internals *i)
146 {
147   byte *start;
148   uns len = bdirect_write_prepare(i->fastbuf, &start);
149   i->fastbuf_pos = start + len;
150   i->dest.next_output_byte = start;
151   i->dest.free_in_buffer = len;
152   if (!len)
153     {
154       IMAGE_ERROR(i->err.io->context, IMAGE_ERROR_WRITE_FAILED, "Unexpected end of stream");
155       longjmp(i->err.setjmp_buf, 1);
156     }
157 }
158
159 static void
160 libjpeg_init_destination(j_compress_ptr cinfo)
161 {
162   DBG("libjpeg_init_destination()");
163   libjpeg_fastbuf_write_prepare((struct libjpeg_write_internals *)cinfo);
164 }
165
166 static void
167 libjpeg_term_destination(j_compress_ptr cinfo)
168 {
169   DBG("libjpeg_term_destination()");
170   struct libjpeg_write_internals *i = (struct libjpeg_write_internals *)cinfo;
171   bdirect_write_commit(i->fastbuf, (byte *)i->dest.next_output_byte);
172 }
173
174 static boolean
175 libjpeg_empty_output_buffer(j_compress_ptr cinfo)
176 {
177   DBG("libjpeg_empty_output_buffer()");
178   struct libjpeg_write_internals *i = (struct libjpeg_write_internals *)cinfo;
179   bdirect_write_commit(i->fastbuf, i->fastbuf_pos);
180   libjpeg_fastbuf_write_prepare(i);
181   return TRUE;
182 }
183
184 #ifdef CONFIG_IMAGES_EXIF
185
186 static inline uns
187 libjpeg_read_byte(struct libjpeg_read_internals *i)
188 {
189   DBG("libjpeg_read_byte()");
190   if (!i->src.bytes_in_buffer)
191     if (!libjpeg_fill_input_buffer(&i->cinfo))
192       ERREXIT(&i->cinfo, JERR_CANT_SUSPEND);
193   i->src.bytes_in_buffer--;
194   return *i->src.next_input_byte++;
195 }
196
197 static inline void
198 libjpeg_read_buf(struct libjpeg_read_internals *i, byte *buf, uns len)
199 {
200   DBG("libjpeg_read_buf(len=%u)", len);
201   while (len)
202     {
203       if (!i->src.bytes_in_buffer)
204         if (!libjpeg_fill_input_buffer(&i->cinfo))
205           ERREXIT(&i->cinfo, JERR_CANT_SUSPEND);
206       uns buf_size = i->src.bytes_in_buffer;
207       uns read_size = MIN(buf_size, len);
208       memcpy(buf, i->src.next_input_byte, read_size);
209       i->src.bytes_in_buffer -= read_size;
210       i->src.next_input_byte += read_size;
211       len -= read_size;
212     }
213 }
214
215 static byte libjpeg_exif_header[6] = { 'E', 'x', 'i', 'f', 0, 0 };
216
217 static boolean
218 libjpeg_app1_preprocessor(j_decompress_ptr cinfo)
219 {
220   struct libjpeg_read_internals *i = (struct libjpeg_read_internals *)cinfo;
221   struct image_io *io = i->err.io;
222   uns len = (libjpeg_read_byte(i) << 8) + libjpeg_read_byte(i);
223   DBG("Found APP1 marker, len=%u", len);
224   if (len < 2)
225     return TRUE;
226   len -= 2;
227   if (len < 7 /*|| io->exif_size*/)
228     {
229       libjpeg_skip_input_data(cinfo, len);
230       return TRUE;
231     }
232   byte header[6];
233   libjpeg_read_buf(i, header, 6);
234   if (memcmp(header, libjpeg_exif_header, 6))
235     {
236       libjpeg_skip_input_data(cinfo, len - 6);
237       return TRUE;
238     }
239   io->exif_size = len;
240   io->exif_data = mp_alloc(io->internal_pool, len);
241   memcpy(io->exif_data, header, 6);
242   libjpeg_read_buf(i, io->exif_data + 6, len - 6);
243   DBG("Parsed EXIF of length %u", len);
244   return TRUE;
245 }
246
247 #endif
248
249 static void
250 libjpeg_read_cancel(struct image_io *io)
251 {
252   DBG("libjpeg_read_cancel()");
253   struct libjpeg_read_internals *i = io->read_data;
254   jpeg_destroy_decompress(&i->cinfo);
255 }
256
257 int
258 libjpeg_read_header(struct image_io *io)
259 {
260   DBG("libjpeg_read_header()");
261   struct libjpeg_read_internals *i = io->read_data = mp_alloc(io->internal_pool, sizeof(*i));
262   i->fastbuf = io->fastbuf;
263
264   /* Create libjpeg read structure */
265   DBG("Creating libjpeg read structure");
266   i->cinfo.err = jpeg_std_error(&i->err.pub);
267   i->err.pub.error_exit = libjpeg_read_error_exit;
268   i->err.pub.emit_message = libjpeg_emit_message;
269   i->err.io = io;
270   if (setjmp(i->err.setjmp_buf))
271     {
272       DBG("Libjpeg failed to read the image, longjump saved us");
273       jpeg_destroy_decompress(&i->cinfo);
274       return 0;
275     }
276   jpeg_create_decompress(&i->cinfo);
277
278   /* Initialize source manager */
279   i->cinfo.src = &i->src;
280   i->src.init_source = libjpeg_init_source;
281   i->src.fill_input_buffer = libjpeg_fill_input_buffer;
282   i->src.skip_input_data = libjpeg_skip_input_data;
283   i->src.resync_to_restart = jpeg_resync_to_restart;
284   i->src.term_source = libjpeg_term_source;
285
286 #ifdef CONFIG_IMAGES_EXIF
287   if (io->flags & IMAGE_IO_WANT_EXIF)
288     jpeg_set_marker_processor(&i->cinfo, JPEG_APP0 + 1, libjpeg_app1_preprocessor);
289 #endif
290
291   /* Read JPEG header and setup decompression options */
292   DBG("Reading image header");
293   jpeg_read_header(&i->cinfo, TRUE);
294   switch (i->cinfo.jpeg_color_space)
295     {
296       case JCS_GRAYSCALE:
297         io->flags = COLOR_SPACE_GRAYSCALE;
298         io->number_of_colors = 1 << 8;
299         break;
300       default:
301         io->flags = COLOR_SPACE_RGB;
302         io->number_of_colors = 1 << 24;
303         break;
304     }
305   io->cols = i->cinfo.image_width;
306   io->rows = i->cinfo.image_height;
307
308   io->read_cancel = libjpeg_read_cancel;
309   return 1;
310 }
311
312 int
313 libjpeg_read_data(struct image_io *io)
314 {
315   DBG("libjpeg_read_data()");
316
317   struct libjpeg_read_internals *i = io->read_data;
318
319   /* Select color space */
320   switch (io->flags & IMAGE_COLOR_SPACE)
321     {
322       case COLOR_SPACE_GRAYSCALE:
323         i->cinfo.out_color_space = JCS_GRAYSCALE;
324         break;
325       case COLOR_SPACE_RGB:
326         i->cinfo.out_color_space = JCS_RGB;
327         break;
328       default:
329         jpeg_destroy_decompress(&i->cinfo);
330         IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Unsupported color space.");
331         return 0;
332     }
333
334   /* Prepare the image  */
335   struct image_io_read_data_internals rdi;
336   if (io->cols <= (i->cinfo.image_width >> 3) && io->rows <= (i->cinfo.image_height >> 3))
337     {
338       DBG("Scaling to 1/8");
339       i->cinfo.scale_num = 1;
340       i->cinfo.scale_denom = 8;
341     }
342   else if (io->cols <= (i->cinfo.image_width >> 2) && io->rows <= (i->cinfo.image_height >> 2))
343     {
344       DBG("Scaling to 1/4");
345       i->cinfo.scale_num = 1;
346       i->cinfo.scale_denom = 4;
347     }
348   else if (io->cols <= (i->cinfo.image_width >> 1) && io->rows <= (i->cinfo.image_height >> 1))
349     {
350       DBG("Scaling to 1/2");
351       i->cinfo.scale_num = 1;
352       i->cinfo.scale_denom = 2;
353     }
354   jpeg_calc_output_dimensions(&i->cinfo);
355   DBG("Output dimensions %ux%u", (uns)i->cinfo.output_width, (uns)i->cinfo.output_height);
356   if (unlikely(!image_io_read_data_prepare(&rdi, io, i->cinfo.output_width, i->cinfo.output_height, io->flags)))
357     {
358       jpeg_destroy_decompress(&i->cinfo);
359       return 0;
360     }
361
362   /* Setup fallback */
363   if (setjmp(i->err.setjmp_buf))
364     {
365       DBG("Libjpeg failed to read the image, longjump saved us");
366       jpeg_destroy_decompress(&i->cinfo);
367       image_io_read_data_break(&rdi, io);
368       return 0;
369     }
370
371   /* Decompress the image */
372   struct image *img = rdi.image;
373   jpeg_start_decompress(&i->cinfo);
374   switch (img->pixel_size)
375     {
376       /* grayscale or RGB */
377       case 1:
378       case 3:
379         {
380           byte *pixels = img->pixels;
381           for (uns r = img->rows; r--; )
382             {
383               jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&pixels, 1);
384               pixels += img->row_size;
385             }
386         }
387         break;
388       /* grayscale with alpha */
389       case 2:
390         {
391           byte buf[img->cols], *src;
392 #         define IMAGE_WALK_PREFIX(x) walk_##x
393 #         define IMAGE_WALK_INLINE
394 #         define IMAGE_WALK_IMAGE img
395 #         define IMAGE_WALK_UNROLL 4
396 #         define IMAGE_WALK_COL_STEP 2
397 #         define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
398 #         define IMAGE_WALK_DO_STEP do{ walk_pos[0] = *src++; walk_pos[1] = 255; }while(0)
399 #         include "images/image-walk.h"
400         }
401         break;
402       /* RGBA or aligned RGB */
403       case 4:
404         {
405           byte buf[img->cols * 3], *src;
406 #         define IMAGE_WALK_PREFIX(x) walk_##x
407 #         define IMAGE_WALK_INLINE
408 #         define IMAGE_WALK_IMAGE img
409 #         define IMAGE_WALK_UNROLL 4
410 #         define IMAGE_WALK_COL_STEP 4
411 #         define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
412 #         define IMAGE_WALK_DO_STEP do{ *(u32 *)walk_pos = *(u32 *)src; walk_pos[3] = 255; src += 3; }while(0)
413 #         include "images/image-walk.h"
414         }
415         break;
416       default:
417         ASSERT(0);
418     }
419   ASSERT(i->cinfo.output_scanline == i->cinfo.output_height);
420
421   /* Destroy libjpeg object */
422   jpeg_finish_decompress(&i->cinfo);
423   jpeg_destroy_decompress(&i->cinfo);
424
425   /* Finish the image */
426   return image_io_read_data_finish(&rdi, io);
427 }
428
429 int
430 libjpeg_write(struct image_io *io)
431 {
432   DBG("libjpeg_write()");
433   struct libjpeg_write_internals i;
434   i.fastbuf = io->fastbuf;
435
436   /* Create libjpeg write structure */
437   DBG("Creating libjpeg write structure");
438   i.cinfo.err = jpeg_std_error(&i.err.pub);
439   i.err.pub.error_exit = libjpeg_write_error_exit;
440   i.err.pub.emit_message = libjpeg_emit_message;
441   i.err.io = io;
442   if (setjmp(i.err.setjmp_buf))
443     {
444       DBG("Libjpeg failed to write the image, longjump saved us");
445       jpeg_destroy_compress(&i.cinfo);
446       return 0;
447     }
448   jpeg_create_compress(&i.cinfo);
449
450   /* Initialize destination manager */
451   i.cinfo.dest = &i.dest;
452   i.dest.init_destination = libjpeg_init_destination;
453   i.dest.term_destination = libjpeg_term_destination;
454   i.dest.empty_output_buffer = libjpeg_empty_output_buffer;
455
456   /* Set output parameters */
457   struct image *img = io->image;
458   i.cinfo.image_width = img->cols;
459   i.cinfo.image_height = img->rows;
460   switch (img->flags & IMAGE_COLOR_SPACE)
461     {
462       case COLOR_SPACE_GRAYSCALE:
463         i.cinfo.input_components = 1;
464         i.cinfo.in_color_space = JCS_GRAYSCALE;
465         break;
466       case COLOR_SPACE_RGB:
467         i.cinfo.input_components = 3;
468         i.cinfo.in_color_space = JCS_RGB;
469         break;
470       default:
471         jpeg_destroy_compress(&i.cinfo);
472         IMAGE_ERROR(io->context, IMAGE_ERROR_INVALID_PIXEL_FORMAT, "Unsupported pixel format.");
473         return 0;
474     }
475   jpeg_set_defaults(&i.cinfo);
476   if (io->jpeg_quality)
477     jpeg_set_quality(&i.cinfo, MIN(io->jpeg_quality, 100), 1);
478 #ifdef CONFIG_IMAGES_EXIF
479   if (io->exif_size)
480     {
481       /* According to the Exif specification, the Exif APP1 marker has to follow immediately after the SOI,
482        * just as the JFIF specification requires the same for the JFIF APP0 marker!
483        * Therefore a JPEG file cannot legally be both Exif and JFIF.  */
484       i.cinfo.write_JFIF_header = FALSE;
485       i.cinfo.write_Adobe_marker = FALSE;
486     }
487 #endif
488
489   /* Compress the image */
490   jpeg_start_compress(&i.cinfo, TRUE);
491 #ifdef CONFIG_IMAGES_EXIF
492   if (io->exif_size)
493     {
494       DBG("Writing EXIF");
495       jpeg_write_marker(&i.cinfo, JPEG_APP0 + 1, io->exif_data, io->exif_size);
496     }
497 #endif
498   switch (img->pixel_size)
499     {
500       /* grayscale or RGB */
501       case 1:
502       case 3:
503         {
504           byte *pixels = img->pixels;
505           for (uns r = img->rows; r--; )
506             {
507               jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&pixels, 1);
508               pixels += img->row_size;
509             }
510         }
511         break;
512       /* grayscale with alpha (ignore alpha) */
513       case 2:
514         {
515           byte buf[img->cols], *dest = buf;
516 #         define IMAGE_WALK_PREFIX(x) walk_##x
517 #         define IMAGE_WALK_INLINE
518 #         define IMAGE_WALK_IMAGE img
519 #         define IMAGE_WALK_UNROLL 4
520 #         define IMAGE_WALK_COL_STEP 2
521 #         define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
522 #         define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; }while(0)
523 #         include "images/image-walk.h"
524         }
525         break;
526       /* RGBA (ignore alpha) or aligned RGB */
527       case 4:
528         {
529           byte buf[img->cols * 3], *dest = buf;
530 #         define IMAGE_WALK_PREFIX(x) walk_##x
531 #         define IMAGE_WALK_INLINE
532 #         define IMAGE_WALK_IMAGE img
533 #         define IMAGE_WALK_UNROLL 4
534 #         define IMAGE_WALK_COL_STEP 4
535 #         define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
536 #         define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; *dest++ = walk_pos[1]; *dest++ = walk_pos[2]; }while(0)
537 #         include "images/image-walk.h"
538         }
539         break;
540       default:
541         ASSERT(0);
542     }
543   ASSERT(i.cinfo.next_scanline == i.cinfo.image_height);
544   jpeg_finish_compress(&i.cinfo);
545   jpeg_destroy_compress(&i.cinfo);
546   return 1;
547 }