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