6c3b759426404f928625c23f6cae4efec0ba6e96
[blender.git] / source / blender / imbuf / intern / jpeg.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/imbuf/intern/jpeg.c
29  *  \ingroup imbuf
30  */
31
32
33
34 /* This little block needed for linking to Blender... */
35 #include <stdio.h>
36 #include <setjmp.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLI_blenlib.h"
41
42 #include "imbuf.h"
43 #include "IMB_imbuf_types.h"
44 #include "IMB_imbuf.h"
45 #include "IMB_metadata.h"
46 #include "IMB_filetype.h"
47 #include "jpeglib.h" 
48 #include "jerror.h"
49
50 #define IS_jpg(x)               (x->ftype & JPG)
51 #define IS_stdjpg(x)    ((x->ftype & JPG_MSK) == JPG_STD)
52 #define IS_vidjpg(x)    ((x->ftype & JPG_MSK) == JPG_VID)
53 #define IS_jstjpg(x)    ((x->ftype & JPG_MSK) == JPG_JST)
54 #define IS_maxjpg(x)    ((x->ftype & JPG_MSK) == JPG_MAX)
55
56 /* the types are from the jpeg lib */
57 static void jpeg_error (j_common_ptr cinfo);
58 static void init_source(j_decompress_ptr cinfo);
59 static boolean fill_input_buffer(j_decompress_ptr cinfo);
60 static void skip_input_data(j_decompress_ptr cinfo, long num_bytes);
61 static void term_source(j_decompress_ptr cinfo);
62 static void memory_source(j_decompress_ptr cinfo, unsigned char *buffer, size_t size);
63 static boolean handle_app1 (j_decompress_ptr cinfo);
64 static ImBuf * ibJpegImageFromCinfo(struct jpeg_decompress_struct * cinfo, int flags);
65
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 separate fields
76
77  * 4. jmax - no scaling in the components
78  */
79
80 static int jpeg_default_quality;
81 static int ibuf_ftype;
82
83 int imb_is_a_jpeg(unsigned char *mem)
84 {
85         if ((mem[0]== 0xFF) && (mem[1] == 0xD8))return 1;
86         return 0;
87 }
88
89 //----------------------------------------------------------
90 //      JPG ERROR HANDLING
91 //----------------------------------------------------------
92
93 typedef struct my_error_mgr {
94         struct jpeg_error_mgr pub;      /* "public" fields */
95
96         jmp_buf setjmp_buffer;  /* for return to caller */
97 } my_error_mgr;
98
99 typedef my_error_mgr * my_error_ptr;
100
101 static void jpeg_error (j_common_ptr cinfo)
102 {
103         my_error_ptr err = (my_error_ptr)cinfo->err;
104
105         /* Always display the message */
106         (*cinfo->err->output_message) (cinfo);
107
108         /* Let the memory manager delete any temp files before we die */
109         jpeg_destroy(cinfo);
110
111         /* return control to the setjmp point */
112         longjmp(err->setjmp_buffer, 1);
113 }
114
115 //----------------------------------------------------------
116 //      INPUT HANDLER FROM MEMORY
117 //----------------------------------------------------------
118
119 typedef struct {
120         unsigned char   *buffer;
121         int             filled;
122 } buffer_struct;
123
124 typedef struct {
125         struct jpeg_source_mgr pub;     /* public fields */
126
127         unsigned char   *buffer;
128         int                             size;
129         JOCTET                  terminal[2];
130 } my_source_mgr;
131
132 typedef my_source_mgr * my_src_ptr;
133
134 static void init_source(j_decompress_ptr cinfo)
135 {
136         (void)cinfo; /* unused */
137 }
138
139
140 static boolean fill_input_buffer(j_decompress_ptr cinfo)
141 {
142         my_src_ptr src = (my_src_ptr) cinfo->src;
143
144         /* Since we have given all we have got already
145         * we simply fake an end of file
146         */
147
148         src->pub.next_input_byte = src->terminal;
149         src->pub.bytes_in_buffer = 2;
150         src->terminal[0] = (JOCTET) 0xFF;
151         src->terminal[1] = (JOCTET) JPEG_EOI;
152
153         return TRUE;
154 }
155
156
157 static void skip_input_data(j_decompress_ptr cinfo, long num_bytes)
158 {
159         my_src_ptr src = (my_src_ptr) cinfo->src;
160
161         if(num_bytes > 0) {
162                 // prevent skipping over file end
163                 size_t skip_size = (size_t)num_bytes <= src->pub.bytes_in_buffer ? num_bytes : src->pub.bytes_in_buffer;
164
165                 src->pub.next_input_byte = src->pub.next_input_byte + skip_size;
166                 src->pub.bytes_in_buffer = src->pub.bytes_in_buffer - skip_size;
167         }
168 }
169
170
171 static void term_source(j_decompress_ptr cinfo)
172 {
173         (void)cinfo; /* unused */
174 }
175
176 static void memory_source(j_decompress_ptr cinfo, unsigned char *buffer, size_t size)
177 {
178         my_src_ptr src;
179
180         if (cinfo->src == NULL)
181         {       /* first time for this JPEG object? */
182                 cinfo->src = (struct jpeg_source_mgr *)(*cinfo->mem->alloc_small)
183                         ((j_common_ptr) cinfo, JPOOL_PERMANENT, sizeof(my_source_mgr));
184         }
185
186         src = (my_src_ptr) cinfo->src;
187         src->pub.init_source            = init_source;
188         src->pub.fill_input_buffer      = fill_input_buffer;
189         src->pub.skip_input_data        = skip_input_data;
190         src->pub.resync_to_restart      = jpeg_resync_to_restart;
191         src->pub.term_source            = term_source;
192
193         src->pub.bytes_in_buffer        = size;
194         src->pub.next_input_byte        = buffer;
195
196         src->buffer = buffer;
197         src->size = size;
198 }
199
200
201 #define MAKESTMT(stuff)         do { stuff } while (0)
202
203 #define INPUT_VARS(cinfo)  \
204         struct jpeg_source_mgr * datasrc = (cinfo)->src;  \
205         const JOCTET * next_input_byte = datasrc->next_input_byte;  \
206         size_t bytes_in_buffer = datasrc->bytes_in_buffer
207
208 /* Unload the local copies --- do this only at a restart boundary */
209 #define INPUT_SYNC(cinfo)  \
210         ( datasrc->next_input_byte = next_input_byte,  \
211           datasrc->bytes_in_buffer = bytes_in_buffer )
212
213 /* Reload the local copies --- seldom used except in MAKE_BYTE_AVAIL */
214 #define INPUT_RELOAD(cinfo)  \
215         ( next_input_byte = datasrc->next_input_byte,  \
216           bytes_in_buffer = datasrc->bytes_in_buffer )
217
218 /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
219  * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
220  * but we must reload the local copies after a successful fill.
221  */
222 #define MAKE_BYTE_AVAIL(cinfo, action)                                        \
223         if (bytes_in_buffer == 0) {                                               \
224                 if (! (*datasrc->fill_input_buffer) (cinfo))                          \
225                         { action; }                                                       \
226                 INPUT_RELOAD(cinfo);  \
227         }
228
229
230 /* Read a byte into variable V.
231  * If must suspend, take the specified action (typically "return FALSE").
232  */
233 #define INPUT_BYTE(cinfo,V,action)  \
234         MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
235                   bytes_in_buffer--; \
236                   V = GETJOCTET(*next_input_byte++); )
237
238 /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
239  * V should be declared unsigned int or perhaps INT32.
240  */
241 #define INPUT_2BYTES(cinfo,V,action)  \
242         MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
243                   bytes_in_buffer--; \
244                   V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
245                   MAKE_BYTE_AVAIL(cinfo,action); \
246                   bytes_in_buffer--; \
247                   V += GETJOCTET(*next_input_byte++); )
248
249
250 static boolean
251 handle_app1 (j_decompress_ptr cinfo)
252 {
253         INT32 length; /* initialized by the macro */
254         INT32 i;
255         char neogeo[128];
256         
257         INPUT_VARS(cinfo);
258
259         INPUT_2BYTES(cinfo, length, return FALSE);
260         length -= 2;
261         
262         if (length < 16) {
263                 for (i = 0; i < length; i++) INPUT_BYTE(cinfo, neogeo[i], return FALSE);
264                 length = 0;
265                 if (strncmp(neogeo, "NeoGeo", 6) == 0) memcpy(&ibuf_ftype, neogeo + 6, 4);
266                 ibuf_ftype = BIG_LONG(ibuf_ftype);
267         }
268         INPUT_SYNC(cinfo);              /* do before skip_input_data */
269         if (length > 0) (*cinfo->src->skip_input_data) (cinfo, length);
270         return TRUE;
271 }
272
273
274 static ImBuf * ibJpegImageFromCinfo(struct jpeg_decompress_struct * cinfo, int flags)
275 {
276         JSAMPARRAY row_pointer;
277         JSAMPLE * buffer = NULL;
278         int row_stride;
279         int x, y, depth, r, g, b, k;
280         struct ImBuf * ibuf = NULL;
281         uchar * rect;
282         jpeg_saved_marker_ptr marker;
283         char *str, *key, *value;
284
285         /* install own app1 handler */
286         ibuf_ftype = 0;
287         jpeg_set_marker_processor(cinfo, 0xe1, handle_app1);
288         cinfo->dct_method = JDCT_FLOAT;
289         jpeg_save_markers(cinfo, JPEG_COM, 0xffff);
290
291         if (jpeg_read_header(cinfo, FALSE) == JPEG_HEADER_OK) {
292                 x = cinfo->image_width;
293                 y = cinfo->image_height;
294                 depth = cinfo->num_components;
295
296                 if (cinfo->jpeg_color_space == JCS_YCCK) cinfo->out_color_space = JCS_CMYK;
297
298                 jpeg_start_decompress(cinfo);
299
300                 if (ibuf_ftype == 0) {
301                         ibuf_ftype = JPG_STD;
302                         if (cinfo->max_v_samp_factor == 1) {
303                                 if (cinfo->max_h_samp_factor == 1) ibuf_ftype = JPG_MAX;
304                                 else ibuf_ftype = JPG_VID;
305                         }
306                 }
307
308                 if (flags & IB_test) {
309                         jpeg_abort_decompress(cinfo);
310                         ibuf = IMB_allocImBuf(x, y, 8 * depth, 0);
311                 }
312                 else if ((ibuf = IMB_allocImBuf(x, y, 8 * depth, IB_rect)) == NULL) {
313                         jpeg_abort_decompress(cinfo);
314                 }
315                 else {
316                         row_stride = cinfo->output_width * depth;
317
318                         row_pointer = (*cinfo->mem->alloc_sarray) ((j_common_ptr) cinfo, JPOOL_IMAGE, row_stride, 1);
319                         
320                         for (y = ibuf->y - 1; y >= 0; y--) {
321                                 jpeg_read_scanlines(cinfo, row_pointer, 1);
322                                 rect = (uchar *) (ibuf->rect + y * ibuf->x);
323                                 buffer = row_pointer[0];
324                                 
325                                 switch(depth) {
326                                         case 1:
327                                                 for (x=ibuf->x; x >0; x--) {
328                                                         rect[3] = 255;
329                                                         rect[0] = rect[1] = rect[2] = *buffer++;
330                                                         rect += 4;
331                                                 }
332                                                 break;
333                                         case 3:
334                                                 for (x=ibuf->x; x >0; x--) {
335                                                         rect[3] = 255;
336                                                         rect[0] = *buffer++;
337                                                         rect[1] = *buffer++;
338                                                         rect[2] = *buffer++;
339                                                         rect += 4;
340                                                 }
341                                                 break;
342                                         case 4:
343                                                 for (x=ibuf->x; x >0; x--) {
344                                                         r = *buffer++;
345                                                         g = *buffer++;
346                                                         b = *buffer++;
347                                                         k = *buffer++;
348                                                         
349                                                         k = 255 - k;
350                                                         r -= k;
351                                                         if (r & 0xffffff00) {
352                                                                 if (r < 0) r = 0;
353                                                                 else r = 255;
354                                                         }
355                                                         g -= k;
356                                                         if (g & 0xffffff00) {
357                                                                 if (g < 0) g = 0;
358                                                                 else g = 255;
359                                                         }
360                                                         b -= k;
361                                                         if (b & 0xffffff00) {
362                                                                 if (b < 0) b = 0;
363                                                                 else b = 255;
364                                                         }
365                                                         
366                                                         rect[3] = 255 - k;
367                                                         rect[2] = b;
368                                                         rect[1] = g;
369                                                         rect[0] = r;
370                                                         rect += 4;
371                                                 }
372                                 }
373                         }
374
375                         marker= cinfo->marker_list;
376                         while(marker) {
377                                 if(marker->marker != JPEG_COM)
378                                         goto next_stamp_marker;
379
380                                 /*
381                                  * Because JPEG format don't support the
382                                  * pair "key/value" like PNG, we store the
383                                  * stampinfo in a single "encode" string:
384                                  *      "Blender:key:value"
385                                  *
386                                  * That is why we need split it to the
387                                  * common key/value here.
388                                  */
389                                 if(strncmp((char *) marker->data, "Blender", 7)) {
390                                         /*
391                                          * Maybe the file have text that
392                                          * we don't know "what it's", in that
393                                          * case we keep the text (with a
394                                          * key "None").
395                                          * This is only for don't "lose"
396                                          * the information when we write
397                                          * it back to disk.
398                                          */
399                                         IMB_metadata_add_field(ibuf, "None", (char *) marker->data);
400                                         ibuf->flags |= IB_metadata;
401                                         goto next_stamp_marker;
402                                 }
403
404                                 str = BLI_strdup ((char *) marker->data);
405                                 key = strchr (str, ':');
406                                 /*
407                                  * A little paranoid, but the file maybe
408                                  * is broken... and a "extra" check is better
409                                  * that a segfaul ;)
410                                  */
411                                 if (!key) {
412                                         MEM_freeN(str);
413                                         goto next_stamp_marker;
414                                 }
415
416                                 key++;
417                                 value = strchr (key, ':');
418                                 if (!value) {
419                                         MEM_freeN(str);
420                                         goto next_stamp_marker;
421                                 }
422
423                                 *value = '\0'; /* need finish the key string */
424                                 value++;
425                                 IMB_metadata_add_field(ibuf, key, value);
426                                 ibuf->flags |= IB_metadata;
427                                 MEM_freeN(str);
428 next_stamp_marker:
429                                 marker= marker->next;
430                         }
431
432                         jpeg_finish_decompress(cinfo);
433                 }
434                 
435                 jpeg_destroy((j_common_ptr) cinfo);
436                 if(ibuf) {
437                         ibuf->ftype = ibuf_ftype;
438                         ibuf->profile = IB_PROFILE_SRGB;
439                 }
440         }
441
442         return(ibuf);
443 }
444
445 ImBuf * imb_load_jpeg (unsigned char * buffer, size_t size, int flags)
446 {
447         struct jpeg_decompress_struct _cinfo, *cinfo = &_cinfo;
448         struct my_error_mgr jerr;
449         ImBuf * ibuf;
450
451         if(!imb_is_a_jpeg(buffer)) return NULL;
452         
453         cinfo->err = jpeg_std_error(&jerr.pub);
454         jerr.pub.error_exit = jpeg_error;
455
456         /* Establish the setjmp return context for my_error_exit to use. */
457         if (setjmp(jerr.setjmp_buffer)) {
458                 /* If we get here, the JPEG code has signaled an error.
459                  * We need to clean up the JPEG object, close the input file, and return.
460                  */
461                 jpeg_destroy_decompress(cinfo);
462                 return NULL;
463         }
464
465         jpeg_create_decompress(cinfo);
466         memory_source(cinfo, buffer, size);
467
468         ibuf = ibJpegImageFromCinfo(cinfo, flags);
469         
470         return(ibuf);
471 }
472
473
474 static void write_jpeg(struct jpeg_compress_struct * cinfo, struct ImBuf * ibuf)
475 {
476         JSAMPLE * buffer = NULL;
477         JSAMPROW row_pointer[1];
478         uchar * rect;
479         int x, y;
480         char neogeo[128];
481         ImMetaData *iptr;
482         char *text;
483
484         jpeg_start_compress(cinfo, TRUE);
485
486         strcpy(neogeo, "NeoGeo");
487         ibuf_ftype = BIG_LONG(ibuf->ftype);
488         
489         memcpy(neogeo + 6, &ibuf_ftype, 4);
490         jpeg_write_marker(cinfo, 0xe1, (JOCTET*) neogeo, 10);
491
492         if(ibuf->metadata) {
493                 /* key + max value + "Blender" */
494                 text= MEM_mallocN(530, "stamp info read");
495                 iptr= ibuf->metadata;
496                 while(iptr) {
497                         if (!strcmp (iptr->key, "None")) {
498                                 jpeg_write_marker(cinfo, JPEG_COM, (JOCTET *) iptr->value, strlen (iptr->value) + 1);
499                                 goto next_stamp_info;
500                         }
501
502                         /*
503                          * The JPEG format don't support a pair "key/value"
504                          * like PNG, so we "encode" the stamp in a
505                          * single string:
506                          *      "Blender:key:value"
507                          *
508                          * The first "Blender" is a simple identify to help
509                          * in the read process.
510                          */
511                         sprintf (text, "Blender:%s:%s", iptr->key, iptr->value);
512                         jpeg_write_marker(cinfo, JPEG_COM, (JOCTET *) text, strlen (text)+1);
513 next_stamp_info:
514                         iptr = iptr->next;
515                 }
516                 MEM_freeN(text);
517         }
518
519         row_pointer[0] =
520                 MEM_mallocN(sizeof(JSAMPLE) *
521                                          cinfo->input_components *
522                                          cinfo->image_width, "jpeg row_pointer");
523
524         for(y = ibuf->y - 1; y >= 0; y--){
525                 rect = (uchar *) (ibuf->rect + y * ibuf->x);
526                 buffer = row_pointer[0];
527
528                 switch(cinfo->in_color_space){
529                         case JCS_RGB:
530                                 for (x = 0; x < ibuf->x; x++) {
531                                         *buffer++ = rect[0];
532                                         *buffer++ = rect[1];
533                                         *buffer++ = rect[2];
534                                         rect += 4;
535                                 }
536                                 break;
537                         case JCS_GRAYSCALE:
538                                 for (x = 0; x < ibuf->x; x++) {
539                                         *buffer++ = rect[0];
540                                         rect += 4;
541                                 }
542                                 break;
543                         case JCS_UNKNOWN:
544                                 memcpy(buffer, rect, 4 * ibuf->x);
545                                 break;
546                                 /* default was missing... intentional ? */
547                         default:
548                                 ; /* do nothing */
549                 }
550
551                 jpeg_write_scanlines(cinfo, row_pointer, 1);
552         }
553
554         jpeg_finish_compress(cinfo);
555         MEM_freeN(row_pointer[0]);
556 }
557
558
559 static int init_jpeg(FILE * outfile, struct jpeg_compress_struct * cinfo, struct ImBuf *ibuf)
560 {
561         int quality;
562
563         quality = ibuf->ftype & 0xff;
564         if (quality <= 0) quality = jpeg_default_quality;
565         if (quality > 100) quality = 100;
566
567         jpeg_create_compress(cinfo);
568         jpeg_stdio_dest(cinfo, outfile);
569
570         cinfo->image_width = ibuf->x;
571         cinfo->image_height = ibuf->y;
572
573         cinfo->in_color_space = JCS_RGB;
574         if (ibuf->planes == 8) cinfo->in_color_space = JCS_GRAYSCALE;
575 #if 0
576         /* just write RGBA as RGB,
577          * unsupported feature only confuses other s/w */
578
579         if (ibuf->planes == 32) cinfo->in_color_space = JCS_UNKNOWN;
580 #endif
581         switch(cinfo->in_color_space){
582                 case JCS_RGB:
583                         cinfo->input_components = 3;
584                         break;
585                 case JCS_GRAYSCALE:
586                         cinfo->input_components = 1;
587                         break;
588                 case JCS_UNKNOWN:
589                         cinfo->input_components = 4;
590                         break;
591                         /* default was missing... intentional ? */
592                 default:
593                         ; /* do nothing */
594         }
595         jpeg_set_defaults(cinfo);
596         
597         /* own settings */
598
599         cinfo->dct_method = JDCT_FLOAT;
600         jpeg_set_quality(cinfo, quality, TRUE);
601
602         return(0);
603 }
604
605
606 static int save_stdjpeg(const char *name, struct ImBuf *ibuf)
607 {
608         FILE * outfile;
609         struct jpeg_compress_struct _cinfo, *cinfo = &_cinfo;
610         struct my_error_mgr jerr;
611
612         if ((outfile = fopen(name, "wb")) == NULL) return 0;
613         jpeg_default_quality = 75;
614
615         cinfo->err = jpeg_std_error(&jerr.pub);
616         jerr.pub.error_exit = jpeg_error;
617
618         /* Establish the setjmp return context for jpeg_error to use. */
619         if (setjmp(jerr.setjmp_buffer)) {
620                 /* If we get here, the JPEG code has signaled an error.
621                  * We need to clean up the JPEG object, close the input file, and return.
622                  */
623                 jpeg_destroy_compress(cinfo);
624                 fclose(outfile);
625                 remove(name);
626                 return 0;
627         }
628
629         init_jpeg(outfile, cinfo, ibuf);
630
631         write_jpeg(cinfo, ibuf);
632
633         fclose(outfile);
634         jpeg_destroy_compress(cinfo);
635
636         return 1;
637 }
638
639
640 static int save_vidjpeg(const char *name, struct ImBuf *ibuf)
641 {
642         FILE * outfile;
643         struct jpeg_compress_struct _cinfo, *cinfo = &_cinfo;
644         struct my_error_mgr jerr;
645
646         if ((outfile = fopen(name, "wb")) == NULL) return 0;
647         jpeg_default_quality = 90;
648
649         cinfo->err = jpeg_std_error(&jerr.pub);
650         jerr.pub.error_exit = jpeg_error;
651
652         /* Establish the setjmp return context for jpeg_error to use. */
653         if (setjmp(jerr.setjmp_buffer)) {
654                 /* If we get here, the JPEG code has signaled an error.
655                  * We need to clean up the JPEG object, close the input file, and return.
656                  */
657                 jpeg_destroy_compress(cinfo);
658                 fclose(outfile);
659                 remove(name);
660                 return 0;
661         }
662
663         init_jpeg(outfile, cinfo, ibuf);
664
665         /* adjust scaling factors */
666         if (cinfo->in_color_space == JCS_RGB) {
667                 cinfo->comp_info[0].h_samp_factor = 2;
668                 cinfo->comp_info[0].v_samp_factor = 1;
669         }
670
671         write_jpeg(cinfo, ibuf);
672
673         fclose(outfile);
674         jpeg_destroy_compress(cinfo);
675
676         return 1;
677 }
678
679 static int save_jstjpeg(const char *name, struct ImBuf *ibuf)
680 {
681         char fieldname[1024];
682         struct ImBuf * tbuf;
683         int oldy, returnval;
684
685         tbuf = IMB_allocImBuf(ibuf->x, ibuf->y / 2, 24, IB_rect);
686         tbuf->ftype = ibuf->ftype;
687         tbuf->flags = ibuf->flags;
688         
689         oldy = ibuf->y;
690         ibuf->x *= 2;
691         ibuf->y /= 2;
692
693         IMB_rectcpy(tbuf, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
694         sprintf(fieldname, "%s.jf0", name);
695
696         returnval = save_vidjpeg(fieldname, tbuf);
697         if (returnval == 1) {
698                 IMB_rectcpy(tbuf, ibuf, 0, 0, tbuf->x, 0, ibuf->x, ibuf->y);
699                 sprintf(fieldname, "%s.jf1", name);
700                 returnval = save_vidjpeg(fieldname, tbuf);
701         }
702
703         ibuf->y = oldy;
704         ibuf->x /= 2;
705         IMB_freeImBuf(tbuf);
706
707         return returnval;
708 }
709
710 static int save_maxjpeg(const char *name, struct ImBuf *ibuf)
711 {
712         FILE * outfile;
713         struct jpeg_compress_struct _cinfo, *cinfo = &_cinfo;
714         struct my_error_mgr jerr;
715
716         if ((outfile = fopen(name, "wb")) == NULL) return 0;
717         jpeg_default_quality = 100;
718
719         cinfo->err = jpeg_std_error(&jerr.pub);
720         jerr.pub.error_exit = jpeg_error;
721
722         /* Establish the setjmp return context for jpeg_error to use. */
723         if (setjmp(jerr.setjmp_buffer)) {
724                 /* If we get here, the JPEG code has signaled an error.
725                  * We need to clean up the JPEG object, close the input file, and return.
726                  */
727                 jpeg_destroy_compress(cinfo);
728                 fclose(outfile);
729                 remove(name);
730                 return 0;
731         }
732
733         init_jpeg(outfile, cinfo, ibuf);
734
735         /* adjust scaling factors */
736         if (cinfo->in_color_space == JCS_RGB) {
737                 cinfo->comp_info[0].h_samp_factor = 1;
738                 cinfo->comp_info[0].v_samp_factor = 1;
739         }
740
741         write_jpeg(cinfo, ibuf);
742
743         fclose(outfile);
744         jpeg_destroy_compress(cinfo);
745
746         return 1;
747 }
748
749 int imb_savejpeg(struct ImBuf *ibuf, const char *name, int flags)
750 {
751         
752         ibuf->flags = flags;
753         if (IS_stdjpg(ibuf)) return save_stdjpeg(name, ibuf);
754         if (IS_jstjpg(ibuf)) return save_jstjpeg(name, ibuf);
755         if (IS_maxjpg(ibuf)) return save_maxjpeg(name, ibuf);
756         return save_vidjpeg(name, ibuf);
757 }
758