Final merge of HEAD (bf-blender) into the orange branch.
[blender.git] / source / blender / imbuf / intern / jpeg.c
1 /**
2  *
3  * ***** BEGIN GPL/BL DUAL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version. The Blender
9  * Foundation also sells licenses for use in proprietary software under
10  * the Blender License.  See http://www.blender.org/BL/ for information
11  * about this.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL/BL DUAL LICENSE BLOCK *****
30  * jpeg.c
31  *
32  * $Id$
33  */
34
35
36 /* This little block needed for linking to Blender... */
37 #include <stdio.h>
38 #include "BLI_blenlib.h"
39
40 #include "imbuf.h"
41 #include "imbuf_patch.h"
42 #include "IMB_imbuf_types.h"
43 #include "IMB_imbuf.h"
44 #include "IMB_jpeg.h"
45 #include "jpeglib.h" 
46
47 /* the types are from the jpeg lib */
48 static void jpeg_error (j_common_ptr cinfo);
49 static void init_source(j_decompress_ptr cinfo);
50 static boolean fill_input_buffer(j_decompress_ptr cinfo);
51 static void skip_input_data(j_decompress_ptr cinfo, long num_bytes);
52 static void term_source(j_decompress_ptr cinfo);
53 static void memory_source(j_decompress_ptr cinfo, unsigned char *buffer, int size);
54 static boolean handle_app1 (j_decompress_ptr cinfo);
55 static ImBuf * ibJpegImageFromCinfo(struct jpeg_decompress_struct * cinfo, int flags);
56
57
58 /*
59  * In principle there are 4 jpeg formats.
60  * 
61  * 1. jpeg - standard printing, u & v at quarter of resulution
62  * 2. jvid - standaard video, u & v half resolution, frame not interlaced
63
64 type 3 is unsupported as of jul 05 2000 Frank.
65
66  * 3. jstr - as 2, but written in 2 seperate fields
67
68  * 4. jmax - no scaling in the components
69  */
70
71 static int jpeg_failed = FALSE;
72 static int jpeg_default_quality;
73 static int ibuf_ftype;
74
75 static void jpeg_error (j_common_ptr cinfo)
76 {
77         /* Always display the message */
78         (*cinfo->err->output_message) (cinfo);
79
80         /* Let the memory manager delete any temp files before we die */
81         jpeg_destroy(cinfo);
82
83         jpeg_failed = TRUE;
84 }
85
86 //----------------------------------------------------------
87 //      INPUT HANDLER FROM MEMORY
88 //----------------------------------------------------------
89
90 typedef struct {
91         unsigned char   *buffer;
92         int             filled;
93 } buffer_struct;
94
95 typedef struct {
96         struct jpeg_source_mgr pub;     /* public fields */
97
98         unsigned char   *buffer;
99         int                             size;
100         JOCTET                  terminal[2];
101 } my_source_mgr;
102
103 typedef my_source_mgr * my_src_ptr;
104
105 static void init_source(j_decompress_ptr cinfo)
106 {
107 }
108
109
110 static boolean fill_input_buffer(j_decompress_ptr cinfo)
111 {
112         my_src_ptr src = (my_src_ptr) cinfo->src;
113
114         /* Since we have given all we have got already
115         * we simply fake an end of file
116         */
117
118         src->pub.next_input_byte = src->terminal;
119         src->pub.bytes_in_buffer = 2;
120         src->terminal[0] = (JOCTET) 0xFF;
121         src->terminal[1] = (JOCTET) JPEG_EOI;
122
123         return TRUE;
124 }
125
126
127 static void skip_input_data(j_decompress_ptr cinfo, long num_bytes)
128 {
129         my_src_ptr src = (my_src_ptr) cinfo->src;
130
131         src->pub.next_input_byte = src->pub.next_input_byte + num_bytes;
132 }
133
134
135 static void term_source(j_decompress_ptr cinfo)
136 {
137 }
138
139 static void memory_source(j_decompress_ptr cinfo, unsigned char *buffer, int size)
140 {
141         my_src_ptr src;
142
143         if (cinfo->src == NULL)
144         {       /* first time for this JPEG object? */
145                 cinfo->src = (struct jpeg_source_mgr *)(*cinfo->mem->alloc_small)
146                         ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_source_mgr));
147         }
148
149         src = (my_src_ptr) cinfo->src;
150         src->pub.init_source            = init_source;
151         src->pub.fill_input_buffer      = fill_input_buffer;
152         src->pub.skip_input_data        = skip_input_data;
153         src->pub.resync_to_restart      = jpeg_resync_to_restart; 
154         src->pub.term_source            = term_source;
155
156         src->pub.bytes_in_buffer        = size;
157         src->pub.next_input_byte        = buffer;
158
159         src->buffer = buffer;
160         src->size = size;
161 }
162
163
164 #define MAKESTMT(stuff)         do { stuff } while (0)
165
166 #define INPUT_VARS(cinfo)  \
167         struct jpeg_source_mgr * datasrc = (cinfo)->src;  \
168         const JOCTET * next_input_byte = datasrc->next_input_byte;  \
169         size_t bytes_in_buffer = datasrc->bytes_in_buffer
170
171 /* Unload the local copies --- do this only at a restart boundary */
172 #define INPUT_SYNC(cinfo)  \
173         ( datasrc->next_input_byte = next_input_byte,  \
174           datasrc->bytes_in_buffer = bytes_in_buffer )
175
176 /* Reload the local copies --- seldom used except in MAKE_BYTE_AVAIL */
177 #define INPUT_RELOAD(cinfo)  \
178         ( next_input_byte = datasrc->next_input_byte,  \
179           bytes_in_buffer = datasrc->bytes_in_buffer )
180
181 /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
182  * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
183  * but we must reload the local copies after a successful fill.
184  */
185 #define MAKE_BYTE_AVAIL(cinfo,action)  \
186         if (bytes_in_buffer == 0) {  \
187                 if (! (*datasrc->fill_input_buffer) (cinfo))  \
188                         { action; }  \
189                 INPUT_RELOAD(cinfo);  \
190         }  \
191         bytes_in_buffer--
192
193 /* Read a byte into variable V.
194  * If must suspend, take the specified action (typically "return FALSE").
195  */
196 #define INPUT_BYTE(cinfo,V,action)  \
197         MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
198                   V = GETJOCTET(*next_input_byte++); )
199
200 /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
201  * V should be declared unsigned int or perhaps INT32.
202  */
203 #define INPUT_2BYTES(cinfo,V,action)  \
204         MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
205                   V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
206                   MAKE_BYTE_AVAIL(cinfo,action); \
207                   V += GETJOCTET(*next_input_byte++); )
208
209
210 static boolean
211 handle_app1 (j_decompress_ptr cinfo)
212 {
213         INT32 length, i;
214         char neogeo[128];
215         
216         INPUT_VARS(cinfo);
217
218         INPUT_2BYTES(cinfo, length, return FALSE);
219         length -= 2;
220         
221         if (length < 16) {
222                 for (i = 0; i < length; i++) INPUT_BYTE(cinfo, neogeo[i], return FALSE);
223                 length = 0;
224                 if (strncmp(neogeo, "NeoGeo", 6) == 0) memcpy(&ibuf_ftype, neogeo + 6, 4);
225                 ibuf_ftype = BIG_LONG(ibuf_ftype);
226         }
227         INPUT_SYNC(cinfo);              /* do before skip_input_data */
228         if (length > 0) (*cinfo->src->skip_input_data) (cinfo, length);
229         return TRUE;
230 }
231
232
233 static ImBuf * ibJpegImageFromCinfo(struct jpeg_decompress_struct * cinfo, int flags)
234 {
235         JSAMPARRAY row_pointer;
236         JSAMPLE * buffer = 0;
237         int row_stride;
238         int x, y, depth, r, g, b, k;
239         struct ImBuf * ibuf = 0;
240         uchar * rect;
241
242         /* install own app1 handler */
243         ibuf_ftype = 0;
244         jpeg_set_marker_processor(cinfo, 0xe1, handle_app1);
245         cinfo->dct_method = JDCT_FLOAT;
246
247         if (jpeg_read_header(cinfo, FALSE) == JPEG_HEADER_OK) {
248                 x = cinfo->image_width;
249                 y = cinfo->image_height;
250                 depth = cinfo->num_components;
251                 
252                 if (cinfo->jpeg_color_space == JCS_YCCK) cinfo->out_color_space = JCS_CMYK;
253
254                 jpeg_start_decompress(cinfo);
255
256                 if (ibuf_ftype == 0) {
257                         ibuf_ftype = JPG_STD;
258                         if (cinfo->max_v_samp_factor == 1) {
259                                 if (cinfo->max_h_samp_factor == 1) ibuf_ftype = JPG_MAX;
260                                 else ibuf_ftype = JPG_VID;
261                         }
262                 }
263
264                 if (flags & IB_test) {
265                         jpeg_abort_decompress(cinfo);
266                         ibuf = IMB_allocImBuf(x, y, 8 * depth, 0, 0);
267                 } else {
268                         ibuf = IMB_allocImBuf(x, y, 8 * depth, IB_rect, 0);
269
270                         row_stride = cinfo->output_width * depth;
271
272                         row_pointer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, row_stride, 1);
273                         
274                         for (y = ibuf->y - 1; y >= 0; y--) {
275                                 jpeg_read_scanlines(cinfo, row_pointer, 1);
276                                 if (flags & IB_ttob) {
277                                         rect = (uchar *) (ibuf->rect + (ibuf->y - 1 - y) * ibuf->x);
278                                 } else {
279                                         rect = (uchar *) (ibuf->rect + y * ibuf->x);
280                                 }
281                                 buffer = row_pointer[0];
282                                 
283                                 switch(depth) {
284                                         case 1:
285                                                 for (x = ibuf->x; x > 0; x--) {
286                                                         rect[3] = 255;
287                                                         rect[0] = rect[1] = rect[2] = *buffer++;
288                                                         rect += 4;
289                                                 }
290                                                 break;
291                                         case 3:
292                                                 for (x = ibuf->x; x > 0; x--) {
293                                                         rect[3] = 255;
294                                                         rect[0] = *buffer++;
295                                                         rect[1] = *buffer++;
296                                                         rect[2] = *buffer++;
297                                                         rect += 4;
298                                                 }
299                                                 break;
300                                         case 4:
301                                                 for (x = ibuf->x; x > 0; x--) {
302                                                         r = *buffer++;
303                                                         g = *buffer++;
304                                                         b = *buffer++;
305                                                         k = *buffer++;
306                                                         
307                                                         k = 255 - k;
308                                                         r -= k;
309                                                         if (r & 0xffffff00) {
310                                                                 if (r < 0) r = 0;
311                                                                 else r = 255;
312                                                         }
313                                                         g -= k;
314                                                         if (g & 0xffffff00) {
315                                                                 if (g < 0) g = 0;
316                                                                 else g = 255;
317                                                         }
318                                                         b -= k;
319                                                         if (b & 0xffffff00) {
320                                                                 if (b < 0) b = 0;
321                                                                 else b = 255;
322                                                         }                                                       
323                                                         
324                                                         rect[3] = 255 - k;
325                                                         rect[2] = b;
326                                                         rect[1] = g;
327                                                         rect[0] = r;
328                                                         rect += 4;
329                                                 }
330                                 }
331                         }
332                         jpeg_finish_decompress(cinfo);
333                 }
334                 
335                 jpeg_destroy((j_common_ptr) cinfo);
336                 ibuf->ftype = ibuf_ftype;
337         }
338         
339         return(ibuf);
340 }
341
342 ImBuf * imb_ibJpegImageFromFilename (char * filename, int flags)
343 {
344         struct jpeg_decompress_struct _cinfo, *cinfo = &_cinfo;
345         struct jpeg_error_mgr jerr;
346         FILE * infile;
347         ImBuf * ibuf;
348         
349         if ((infile = fopen(filename, "rb")) == NULL) return 0;
350
351         cinfo->err = jpeg_std_error(&jerr);
352         jerr.error_exit = jpeg_error;
353
354         jpeg_create_decompress(cinfo);
355         jpeg_stdio_src(cinfo, infile);
356
357         ibuf = ibJpegImageFromCinfo(cinfo, flags);
358         
359         fclose(infile);
360         return(ibuf);
361 }
362
363 ImBuf * imb_ibJpegImageFromMemory (unsigned char * buffer, int size, int flags)
364 {
365         struct jpeg_decompress_struct _cinfo, *cinfo = &_cinfo;
366         struct jpeg_error_mgr jerr;
367         ImBuf * ibuf;
368         
369         cinfo->err = jpeg_std_error(&jerr);
370         jerr.error_exit = jpeg_error;
371
372         jpeg_create_decompress(cinfo);
373         memory_source(cinfo, buffer, size);
374
375         ibuf = ibJpegImageFromCinfo(cinfo, flags);
376         
377         return(ibuf);
378 }
379
380
381 static void write_jpeg(struct jpeg_compress_struct * cinfo, struct ImBuf * ibuf)
382 {
383         JSAMPLE * buffer = 0;
384         JSAMPROW row_pointer[1];
385         uchar * rect;
386         int x, y;
387         char neogeo[128];
388
389
390         jpeg_start_compress(cinfo, TRUE);
391
392         strcpy(neogeo, "NeoGeo");
393         ibuf_ftype = BIG_LONG(ibuf->ftype);
394         
395         memcpy(neogeo + 6, &ibuf_ftype, 4);
396         jpeg_write_marker(cinfo, 0xe1, (JOCTET*) neogeo, 10);
397
398         row_pointer[0] =
399                 mallocstruct(JSAMPLE,
400                                          cinfo->input_components *
401                                          cinfo->image_width);
402
403         for(y = ibuf->y - 1; y >= 0; y--){
404                 rect = (uchar *) (ibuf->rect + y * ibuf->x);
405                 buffer = row_pointer[0];
406
407                 switch(cinfo->in_color_space){
408                 case JCS_RGB:
409                         for (x = 0; x < ibuf->x; x++) {
410                                 *buffer++ = rect[0];
411                                 *buffer++ = rect[1];
412                                 *buffer++ = rect[2];
413                                 rect += 4;
414                         }
415                         break;
416                 case JCS_GRAYSCALE:
417                         for (x = 0; x < ibuf->x; x++) {
418                                 *buffer++ = rect[0];
419                                 rect += 4;
420                         }
421                         break;
422                 case JCS_UNKNOWN:
423                         memcpy(buffer, rect, 4 * ibuf->x);
424                         break;
425                         /* default was missing... intentional ? */
426                 default:
427                         ; /* do nothing */
428                 }
429
430                 jpeg_write_scanlines(cinfo, row_pointer, 1);
431
432                 if (jpeg_failed) break;
433         }
434
435         if (jpeg_failed == FALSE) jpeg_finish_compress(cinfo);
436         free(row_pointer[0]);
437 }
438
439
440 static int init_jpeg(FILE * outfile, struct jpeg_compress_struct * cinfo, struct ImBuf *ibuf)
441 {
442         int quality;
443
444         quality = ibuf->ftype & 0xff;
445         if (quality <= 0) quality = jpeg_default_quality;
446         if (quality > 100) quality = 100;
447
448         jpeg_create_compress(cinfo);
449         jpeg_stdio_dest(cinfo, outfile);
450
451         cinfo->image_width = ibuf->x;
452         cinfo->image_height = ibuf->y;
453
454         cinfo->in_color_space = JCS_RGB;
455         if (ibuf->depth == 8 && ibuf->cmap == 0) cinfo->in_color_space = JCS_GRAYSCALE;
456         if (ibuf->depth == 32) cinfo->in_color_space = JCS_UNKNOWN;
457         
458         switch(cinfo->in_color_space){
459         case JCS_RGB:
460                 cinfo->input_components = 3;
461                 break;
462         case JCS_GRAYSCALE:
463                 cinfo->input_components = 1;
464                 break;
465         case JCS_UNKNOWN:
466                 cinfo->input_components = 4;
467                 break;
468                 /* default was missing... intentional ? */
469         default:
470                 ; /* do nothing */
471         }
472         jpeg_set_defaults(cinfo);
473         
474         /* own settings */
475
476         cinfo->dct_method = JDCT_FLOAT;
477         jpeg_set_quality(cinfo, quality, TRUE);
478
479         return(0);
480 }
481
482
483 static int save_stdjpeg(char * name, struct ImBuf * ibuf)
484 {
485         FILE * outfile;
486         struct jpeg_compress_struct _cinfo, *cinfo = &_cinfo;
487         struct jpeg_error_mgr jerr;
488
489         if ((outfile = fopen(name, "wb")) == NULL) return 0;
490         jpeg_default_quality = 75;
491
492         cinfo->err = jpeg_std_error(&jerr);
493         jerr.error_exit = jpeg_error;
494
495         init_jpeg(outfile, cinfo, ibuf);
496
497         write_jpeg(cinfo, ibuf);
498
499         fclose(outfile);
500         jpeg_destroy_compress(cinfo);
501
502         if (jpeg_failed) {
503                 remove(name);
504                 return 0;
505         }
506         return 1;
507 }
508
509
510 static int save_vidjpeg(char * name, struct ImBuf * ibuf)
511 {
512         FILE * outfile;
513         struct jpeg_compress_struct _cinfo, *cinfo = &_cinfo;
514         struct jpeg_error_mgr jerr;
515
516         if ((outfile = fopen(name, "wb")) == NULL) return 0;
517         jpeg_default_quality = 90;
518
519         cinfo->err = jpeg_std_error(&jerr);
520         jerr.error_exit = jpeg_error;
521
522         init_jpeg(outfile, cinfo, ibuf);
523
524         /* adjust scaling factors */
525         if (cinfo->in_color_space == JCS_RGB) {
526                 cinfo->comp_info[0].h_samp_factor = 2;
527                 cinfo->comp_info[0].v_samp_factor = 1;
528         }
529
530         write_jpeg(cinfo, ibuf);
531
532         fclose(outfile);
533         jpeg_destroy_compress(cinfo);
534
535         if (jpeg_failed) {
536                 remove(name);
537                 return 0;
538         }
539         return 1;
540 }
541
542 static int save_jstjpeg(char * name, struct ImBuf * ibuf)
543 {
544         char fieldname[1024];
545         struct ImBuf * tbuf;
546         int oldy, returnval;
547
548         tbuf = IMB_allocImBuf(ibuf->x, ibuf->y / 2, 24, IB_rect, 0);
549         tbuf->ftype = ibuf->ftype;
550         tbuf->flags = ibuf->flags;
551         
552         oldy = ibuf->y;
553         ibuf->x *= 2;
554         ibuf->y /= 2;
555
556         IMB_rectcpy(tbuf, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
557         sprintf(fieldname, "%s.jf0", name);
558
559         returnval = save_vidjpeg(fieldname, tbuf) ;
560         if (returnval == 1) {
561                 IMB_rectcpy(tbuf, ibuf, 0, 0, tbuf->x, 0, ibuf->x, ibuf->y);
562                 sprintf(fieldname, "%s.jf1", name);
563                 returnval = save_vidjpeg(fieldname, tbuf);
564         }
565
566         ibuf->y = oldy;
567         ibuf->x /= 2;
568         IMB_freeImBuf(tbuf);
569
570         return returnval;
571 }
572
573 static int save_maxjpeg(char * name, struct ImBuf * ibuf)
574 {
575         FILE * outfile;
576         struct jpeg_compress_struct _cinfo, *cinfo = &_cinfo;
577         struct jpeg_error_mgr jerr;
578
579         if ((outfile = fopen(name, "wb")) == NULL) return 0;
580         jpeg_default_quality = 100;
581
582         cinfo->err = jpeg_std_error(&jerr);
583         jerr.error_exit = jpeg_error;
584
585         init_jpeg(outfile, cinfo, ibuf);
586
587         /* adjust scaling factors */
588         if (cinfo->in_color_space == JCS_RGB) {
589                 cinfo->comp_info[0].h_samp_factor = 1;
590                 cinfo->comp_info[0].v_samp_factor = 1;
591         }
592
593         write_jpeg(cinfo, ibuf);
594
595         fclose(outfile);
596         jpeg_destroy_compress(cinfo);
597
598         if (jpeg_failed) {
599                 remove(name);
600                 return 0;
601         }
602         return 1;
603 }
604
605 int imb_savejpeg(struct ImBuf * ibuf, char * name, int flags)
606 {
607         
608         ibuf->flags = flags;
609         if (IS_stdjpg(ibuf)) return save_stdjpeg(name, ibuf);
610         if (IS_jstjpg(ibuf)) return save_jstjpeg(name, ibuf);
611         if (IS_maxjpg(ibuf)) return save_maxjpeg(name, ibuf);
612         return save_vidjpeg(name, ibuf);
613 }
614