]> mj.ucw.cz Git - libucw.git/blob - images/io-libjpeg.c
Merge with git+ssh://cvs.ucw.cz/projects/sherlock/GIT/sherlock.git
[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   libjpeg_read_buf(i, header, 6);
231   if (memcmp(header, libjpeg_exif_header, 6))
232     {
233       libjpeg_skip_input_data(cinfo, len - 6);
234       return TRUE;
235     }
236   io->exif_size = len;
237   io->exif_data = mp_alloc(io->internal_pool, len);
238   memcpy(io->exif_data, header, 6);
239   libjpeg_read_buf(i, io->exif_data + 6, len - 6);
240   DBG("Parsed EXIF of length %u", len);
241   return TRUE;
242 }
243
244 #endif
245
246 static void
247 libjpeg_read_cancel(struct image_io *io)
248 {
249   DBG("libjpeg_read_cancel()");
250   struct libjpeg_read_internals *i = io->read_data;
251   jpeg_destroy_decompress(&i->cinfo);
252 }
253
254 int
255 libjpeg_read_header(struct image_io *io)
256 {
257   DBG("libjpeg_read_header()");
258   struct libjpeg_read_internals *i = io->read_data = mp_alloc(io->internal_pool, sizeof(*i));
259   i->fastbuf = io->fastbuf;
260
261   /* Create libjpeg read structure */
262   DBG("Creating libjpeg read structure");
263   i->cinfo.err = jpeg_std_error(&i->err.pub);
264   i->err.pub.error_exit = libjpeg_read_error_exit;
265   i->err.pub.emit_message = libjpeg_emit_message;
266   i->err.io = io;
267   if (setjmp(i->err.setjmp_buf))
268     {
269       DBG("Libjpeg failed to read the image, longjump saved us");
270       jpeg_destroy_decompress(&i->cinfo);
271       return 0;
272     }
273   jpeg_create_decompress(&i->cinfo);
274
275   /* Initialize source manager */
276   i->cinfo.src = &i->src;
277   i->src.init_source = libjpeg_init_source;
278   i->src.fill_input_buffer = libjpeg_fill_input_buffer;
279   i->src.skip_input_data = libjpeg_skip_input_data;
280   i->src.resync_to_restart = jpeg_resync_to_restart;
281   i->src.term_source = libjpeg_term_source;
282
283 #ifdef CONFIG_IMAGES_EXIF
284   if (io->flags & IMAGE_IO_WANT_EXIF)
285     jpeg_set_marker_processor(&i->cinfo, JPEG_APP0 + 1, libjpeg_app1_preprocessor);
286 #endif
287
288   /* Read JPEG header and setup decompression options */
289   DBG("Reading image header");
290   jpeg_read_header(&i->cinfo, TRUE);
291   switch (i->cinfo.jpeg_color_space)
292     {
293       case JCS_GRAYSCALE:
294         io->flags = COLOR_SPACE_GRAYSCALE;
295         io->number_of_colors = 1 << 8;
296         break;
297       default:
298         io->flags = COLOR_SPACE_RGB;
299         io->number_of_colors = 1 << 24;
300         break;
301     }
302   io->cols = i->cinfo.image_width;
303   io->rows = i->cinfo.image_height;
304
305   io->read_cancel = libjpeg_read_cancel;
306   return 1;
307 }
308
309 int
310 libjpeg_read_data(struct image_io *io)
311 {
312   DBG("libjpeg_read_data()");
313
314   struct libjpeg_read_internals *i = io->read_data;
315
316   /* Select color space */
317   switch (io->flags & IMAGE_COLOR_SPACE)
318     {
319       case COLOR_SPACE_GRAYSCALE:
320         i->cinfo.out_color_space = JCS_GRAYSCALE;
321         break;
322       case COLOR_SPACE_RGB:
323         i->cinfo.out_color_space = JCS_RGB;
324         break;
325       default:
326         jpeg_destroy_decompress(&i->cinfo);
327         image_thread_err(io->thread, IMAGE_ERR_INVALID_PIXEL_FORMAT, "Unsupported color space.");
328         return 0;
329     }
330
331   /* Prepare the image  */
332   struct image_io_read_data_internals rdi;
333   if (io->cols <= (i->cinfo.image_width >> 3) && io->rows <= (i->cinfo.image_height >> 3))
334     {
335       DBG("Scaling to 1/8");
336       i->cinfo.scale_num = 1;
337       i->cinfo.scale_denom = 8;
338     }
339   else if (io->cols <= (i->cinfo.image_width >> 2) && io->rows <= (i->cinfo.image_height >> 2))
340     {
341       DBG("Scaling to 1/4");
342       i->cinfo.scale_num = 1;
343       i->cinfo.scale_denom = 4;
344     }
345   else if (io->cols <= (i->cinfo.image_width >> 1) && io->rows <= (i->cinfo.image_height >> 1))
346     {
347       DBG("Scaling to 1/2");
348       i->cinfo.scale_num = 1;
349       i->cinfo.scale_denom = 2;
350     }
351   jpeg_calc_output_dimensions(&i->cinfo);
352   DBG("Output dimensions %ux%u", (uns)i->cinfo.output_width, (uns)i->cinfo.output_height);
353   if (unlikely(!image_io_read_data_prepare(&rdi, io, i->cinfo.output_width, i->cinfo.output_height, io->flags)))
354     {
355       jpeg_destroy_decompress(&i->cinfo);
356       return 0;
357     }
358
359   /* Setup fallback */
360   if (setjmp(i->err.setjmp_buf))
361     {
362       DBG("Libjpeg failed to read the image, longjump saved us");
363       jpeg_destroy_decompress(&i->cinfo);
364       image_io_read_data_break(&rdi, io);
365       return 0;
366     }
367
368   /* Decompress the image */
369   struct image *img = rdi.image;
370   jpeg_start_decompress(&i->cinfo);
371   switch (img->pixel_size)
372     {
373       /* grayscale or RGB */
374       case 1:
375       case 3:
376         {
377           byte *pixels = img->pixels;
378           for (uns r = img->rows; r--; )
379             {
380               jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&pixels, 1);
381               pixels += img->row_size;
382             }
383         }
384         break;
385       /* grayscale with alpha */
386       case 2:
387         {
388           byte buf[img->cols], *src;
389 #         define IMAGE_WALK_PREFIX(x) walk_##x
390 #         define IMAGE_WALK_INLINE
391 #         define IMAGE_WALK_IMAGE img
392 #         define IMAGE_WALK_UNROLL 4
393 #         define IMAGE_WALK_COL_STEP 2
394 #         define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
395 #         define IMAGE_WALK_DO_STEP do{ walk_pos[0] = *src++; walk_pos[1] = 255; }while(0)
396 #         include "images/image-walk.h"
397         }
398         break;
399       /* RGBA or aligned RGB */
400       case 4:
401         {
402           byte buf[img->cols * 3], *src;
403 #         define IMAGE_WALK_PREFIX(x) walk_##x
404 #         define IMAGE_WALK_INLINE
405 #         define IMAGE_WALK_IMAGE img
406 #         define IMAGE_WALK_UNROLL 4
407 #         define IMAGE_WALK_COL_STEP 4
408 #         define IMAGE_WALK_DO_ROW_START do{ src = buf; jpeg_read_scanlines(&i->cinfo, (JSAMPLE **)&src, 1); }while(0)
409 #         define IMAGE_WALK_DO_STEP do{ *(u32 *)walk_pos = *(u32 *)src; walk_pos[3] = 255; src += 3; }while(0)
410 #         include "images/image-walk.h"
411         }
412         break;
413       default:
414         ASSERT(0);
415     }
416   ASSERT(i->cinfo.output_scanline == i->cinfo.output_height);
417
418   /* Destroy libjpeg object */
419   jpeg_finish_decompress(&i->cinfo);
420   jpeg_destroy_decompress(&i->cinfo);
421
422   /* Finish the image */
423   return image_io_read_data_finish(&rdi, io);
424 }
425
426 int
427 libjpeg_write(struct image_io *io)
428 {
429   DBG("libjpeg_write()");
430   struct libjpeg_write_internals i;
431   i.fastbuf = io->fastbuf;
432
433   /* Create libjpeg write structure */
434   DBG("Creating libjpeg write structure");
435   i.cinfo.err = jpeg_std_error(&i.err.pub);
436   i.err.pub.error_exit = libjpeg_write_error_exit;
437   i.err.pub.emit_message = libjpeg_emit_message;
438   i.err.io = io;
439   if (setjmp(i.err.setjmp_buf))
440     {
441       DBG("Libjpeg failed to write the image, longjump saved us");
442       jpeg_destroy_compress(&i.cinfo);
443       return 0;
444     }
445   jpeg_create_compress(&i.cinfo);
446
447   /* Initialize destination manager */
448   i.cinfo.dest = &i.dest;
449   i.dest.init_destination = libjpeg_init_destination;
450   i.dest.term_destination = libjpeg_term_destination;
451   i.dest.empty_output_buffer = libjpeg_empty_output_buffer;
452
453   /* Set output parameters */
454   struct image *img = io->image;
455   i.cinfo.image_width = img->cols;
456   i.cinfo.image_height = img->rows;
457   switch (img->flags & IMAGE_COLOR_SPACE)
458     {
459       case COLOR_SPACE_GRAYSCALE:
460         i.cinfo.input_components = 1;
461         i.cinfo.in_color_space = JCS_GRAYSCALE;
462         break;
463       case COLOR_SPACE_RGB:
464         i.cinfo.input_components = 3;
465         i.cinfo.in_color_space = JCS_RGB;
466         break;
467       default:
468         jpeg_destroy_compress(&i.cinfo);
469         image_thread_err(io->thread, IMAGE_ERR_INVALID_PIXEL_FORMAT, "Unsupported pixel format.");
470         return 0;
471     }
472   jpeg_set_defaults(&i.cinfo);
473   if (io->jpeg_quality)
474     jpeg_set_quality(&i.cinfo, MIN(io->jpeg_quality, 100), 1);
475 #ifdef CONFIG_IMAGES_EXIF
476   if (io->exif_size)
477     {
478       /* According to the Exif specification, the Exif APP1 marker has to follow immediately after the SOI,
479        * just as the JFIF specification requires the same for the JFIF APP0 marker!
480        * Therefore a JPEG file cannot legally be both Exif and JFIF.  */
481       i.cinfo.write_JFIF_header = FALSE;
482       i.cinfo.write_Adobe_marker = FALSE;
483     }
484 #endif
485
486   /* Compress the image */
487   jpeg_start_compress(&i.cinfo, TRUE);
488 #ifdef CONFIG_IMAGES_EXIF
489   if (io->exif_size)
490     {
491       DBG("Writing EXIF");
492       jpeg_write_marker(&i.cinfo, JPEG_APP0 + 1, io->exif_data, io->exif_size);
493     }
494 #endif
495   switch (img->pixel_size)
496     {
497       /* grayscale or RGB */
498       case 1:
499       case 3:
500         {
501           byte *pixels = img->pixels;
502           for (uns r = img->rows; r--; )
503             {
504               jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&pixels, 1);
505               pixels += img->row_size;
506             }
507         }
508         break;
509       /* grayscale with alpha (ignore alpha) */
510       case 2:
511         {
512           byte buf[img->cols], *dest = buf;
513 #         define IMAGE_WALK_PREFIX(x) walk_##x
514 #         define IMAGE_WALK_INLINE
515 #         define IMAGE_WALK_IMAGE img
516 #         define IMAGE_WALK_UNROLL 4
517 #         define IMAGE_WALK_COL_STEP 2
518 #         define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
519 #         define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; }while(0)
520 #         include "images/image-walk.h"
521         }
522         break;
523       /* RGBA (ignore alpha) or aligned RGB */
524       case 4:
525         {
526           byte buf[img->cols * 3], *dest = buf;
527 #         define IMAGE_WALK_PREFIX(x) walk_##x
528 #         define IMAGE_WALK_INLINE
529 #         define IMAGE_WALK_IMAGE img
530 #         define IMAGE_WALK_UNROLL 4
531 #         define IMAGE_WALK_COL_STEP 4
532 #         define IMAGE_WALK_DO_ROW_END do{ dest = buf; jpeg_write_scanlines(&i.cinfo, (JSAMPLE **)&dest, 1); }while(0)
533 #         define IMAGE_WALK_DO_STEP do{ *dest++ = walk_pos[0]; *dest++ = walk_pos[1]; *dest++ = walk_pos[2]; }while(0)
534 #         include "images/image-walk.h"
535         }
536         break;
537       default:
538         ASSERT(0);
539     }
540   ASSERT(i.cinfo.next_scanline == i.cinfo.image_height);
541   jpeg_finish_compress(&i.cinfo);
542   jpeg_destroy_compress(&i.cinfo);
543   return 1;
544 }