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