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