style cleanup: follow style guide for formatting of if/for/while loops, and else...
[blender.git] / source / blender / imbuf / intern / jp2.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  * Contributor(s): Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/imbuf/intern/jp2.c
24  *  \ingroup imbuf
25  */
26
27 #include "MEM_guardedalloc.h"
28
29 #include "BLI_blenlib.h"
30 #include "BLI_math.h"
31
32 #include "imbuf.h"
33
34 #include "IMB_imbuf_types.h"
35 #include "IMB_imbuf.h"
36 #include "IMB_allocimbuf.h"
37 #include "IMB_filetype.h"
38
39 #include "openjpeg.h"
40
41 #define JP2_FILEHEADER_SIZE 14
42
43 static char JP2_HEAD[]= {0x0, 0x0, 0x0, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A};
44
45 /* We only need this because of how the presets are set */
46 typedef struct img_folder{
47         /** The directory path of the folder containing input images*/
48         char *imgdirpath;
49         /** Output format*/
50         char *out_format;
51         /** Enable option*/
52         char set_imgdir;
53         /** Enable Cod Format for output*/
54         char set_out_format;
55         /** User specified rate stored in case of cinema option*/
56         float *rates;
57 }img_fol_t;
58
59 static int check_jp2(unsigned char *mem) /* J2K_CFMT */
60 {
61         return memcmp(JP2_HEAD, mem, 12) ? 0 : 1;
62 }
63
64 int imb_is_a_jp2(unsigned char *buf)
65 {       
66         return check_jp2(buf);
67 }
68
69
70 /**
71  * sample error callback expecting a FILE* client object
72  */
73 static void error_callback(const char *msg, void *client_data)
74 {
75         FILE *stream = (FILE*)client_data;
76         fprintf(stream, "[ERROR] %s", msg);
77 }
78 /**
79  * sample warning callback expecting a FILE* client object
80  */
81 static void warning_callback(const char *msg, void *client_data)
82 {
83         FILE *stream = (FILE*)client_data;
84         fprintf(stream, "[WARNING] %s", msg);
85 }
86 /**
87  * sample debug callback expecting no client object
88  */
89 static void info_callback(const char *msg, void *client_data)
90 {
91         (void)client_data;
92         fprintf(stdout, "[INFO] %s", msg);
93 }
94
95
96
97 struct ImBuf *imb_jp2_decode(unsigned char *mem, size_t size, int flags)
98 {
99         struct ImBuf *ibuf = NULL;
100         int use_float = 0; /* for precision higher then 8 use float */
101         
102         long signed_offsets[4]= {0, 0, 0, 0};
103         int float_divs[4]= {1, 1, 1, 1};
104
105         int index;
106         
107         int w, h, planes;
108         
109         opj_dparameters_t parameters;   /* decompression parameters */
110         
111         opj_event_mgr_t event_mgr;              /* event manager */
112         opj_image_t *image = NULL;
113         
114         int i;
115         
116         opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
117         opj_cio_t *cio = NULL;
118
119         if (check_jp2(mem) == 0) return(NULL);
120
121         /* configure the event callbacks (not required) */
122         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
123         event_mgr.error_handler = error_callback;
124         event_mgr.warning_handler = warning_callback;
125         event_mgr.info_handler = info_callback;
126
127
128         /* set decoding parameters to default values */
129         opj_set_default_decoder_parameters(&parameters);
130
131
132         /* JPEG 2000 compressed image data */
133
134         /* get a decoder handle */
135         dinfo = opj_create_decompress(CODEC_JP2);
136
137         /* catch events using our callbacks and give a local context */
138         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
139
140         /* setup the decoder decoding parameters using the current image and user parameters */
141         opj_setup_decoder(dinfo, &parameters);
142
143         /* open a byte stream */
144         cio = opj_cio_open((opj_common_ptr)dinfo, mem, size);
145
146         /* decode the stream and fill the image structure */
147         image = opj_decode(dinfo, cio);
148         
149         if (!image) {
150                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
151                 opj_destroy_decompress(dinfo);
152                 opj_cio_close(cio);
153                 return NULL;
154         }
155
156         /* close the byte stream */
157         opj_cio_close(cio);
158
159
160         if ((image->numcomps * image->x1 * image->y1) == 0) {
161                 fprintf(stderr,"\nError: invalid raw image parameters\n");
162                 return NULL;
163         }
164         
165         w = image->comps[0].w;
166         h = image->comps[0].h;
167         
168         switch (image->numcomps) {
169         case 1: /* Greyscale */
170         case 3: /* Color */
171                 planes= 24;
172                 break;
173         default: /* 2 or 4 - Greyscale or Color + alpha */
174                 planes= 32; /* greyscale + alpha */
175                 break;
176         }
177         
178         
179         i = image->numcomps;
180         if (i>4) i= 4;
181         
182         while (i) {
183                 i--;
184                 
185                 if (image->comps[i].prec > 8)
186                         use_float = 1;
187                 
188                 if (image->comps[i].sgnd)
189                         signed_offsets[i]=  1 << (image->comps[i].prec - 1); 
190                 
191                 /* only needed for float images but dosnt hurt to calc this */
192                 float_divs[i]= (1<<image->comps[i].prec)-1;
193         }
194         
195         ibuf= IMB_allocImBuf(w, h, planes, use_float ? IB_rectfloat : IB_rect);
196         
197         if (ibuf==NULL) {
198                 if (dinfo)
199                         opj_destroy_decompress(dinfo);
200                 return NULL;
201         }
202         
203         ibuf->ftype = JP2;
204         
205         if (use_float) {
206                 float *rect_float= ibuf->rect_float;
207
208                 if (image->numcomps < 3) {
209                         /* greyscale 12bits+ */
210                         for (i = 0; i < w * h; i++, rect_float+=4) {
211                                 index = w * h - ((i) / (w) + 1) * w + (i) % (w);
212                                 
213                                 rect_float[0]= rect_float[1]= rect_float[2]= (float)(image->comps[0].data[index] + signed_offsets[0]) / float_divs[0];
214                                 
215                                 if (image->numcomps == 2)
216                                         rect_float[3]= (image->comps[1].data[index] + signed_offsets[1]) / float_divs[1];
217                                 else
218                                         rect_float[3]= 1.0f;
219                         }
220                 }
221                 else {
222                         /* rgb or rgba 12bits+ */
223                         for (i = 0; i < w * h; i++, rect_float+=4) {
224                                 index = w * h - ((i) / (w) + 1) * w + (i) % (w);
225                                 
226                                 rect_float[0]= (float)(image->comps[0].data[index] + signed_offsets[0]) / float_divs[0];
227                                 rect_float[1]= (float)(image->comps[1].data[index] + signed_offsets[1]) / float_divs[1];
228                                 rect_float[2]= (float)(image->comps[2].data[index] + signed_offsets[2]) / float_divs[2];
229                                 
230                                 if (image->numcomps >= 4)
231                                         rect_float[3]= (float)(image->comps[3].data[index] + signed_offsets[3]) / float_divs[3];
232                                 else
233                                         rect_float[3]= 1.0f;
234                         }
235                 }
236                 
237         }
238         else {
239                 unsigned char *rect= (unsigned char *)ibuf->rect;
240
241                 if (image->numcomps < 3) {
242                         /* greyscale */
243                         for (i = 0; i < w * h; i++, rect+=4) {
244                                 index = w * h - ((i) / (w) + 1) * w + (i) % (w);
245                                 
246                                 rect[0]= rect[1]= rect[2]= (image->comps[0].data[index] + signed_offsets[0]);
247                                 
248                                 if (image->numcomps == 2)
249                                         rect[3]= image->comps[1].data[index] + signed_offsets[1];
250                                 else
251                                         rect[3]= 255;
252                         }
253                 }
254                 else {
255                         /* 8bit rgb or rgba */
256                         for (i = 0; i < w * h; i++, rect+=4) {
257                                 int index = w * h - ((i) / (w) + 1) * w + (i) % (w);
258                                 
259                                 rect[0]= image->comps[0].data[index] + signed_offsets[0];
260                                 rect[1]= image->comps[1].data[index] + signed_offsets[1];
261                                 rect[2]= image->comps[2].data[index] + signed_offsets[2];
262                                 
263                                 if (image->numcomps >= 4)
264                                         rect[3]= image->comps[3].data[index] + signed_offsets[3];
265                                 else
266                                         rect[3]= 255;
267                         }
268                 }
269         }
270         
271         /* free remaining structures */
272         if (dinfo) {
273                 opj_destroy_decompress(dinfo);
274         }
275         
276         /* free image data structure */
277         opj_image_destroy(image);
278         
279         if (flags & IB_rect) {
280                 IMB_rect_from_float(ibuf);
281         }
282         
283         return(ibuf);
284 }
285
286 //static opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp) {
287 /* prec can be 8, 12, 16 */
288
289 #define UPSAMPLE_8_TO_12(_val) ((_val<<4) | (_val & ((1<<4)-1)))
290 #define UPSAMPLE_8_TO_16(_val) ((_val<<8)+_val)
291
292 #define DOWNSAMPLE_FLOAT_TO_8BIT(_val)  (_val)<=0.0f?0: ((_val)>=1.0f?255: (int)(255.0f*(_val)))
293 #define DOWNSAMPLE_FLOAT_TO_12BIT(_val) (_val)<=0.0f?0: ((_val)>=1.0f?4095: (int)(4095.0f*(_val)))
294 #define DOWNSAMPLE_FLOAT_TO_16BIT(_val) (_val)<=0.0f?0: ((_val)>=1.0f?65535: (int)(65535.0f*(_val)))
295
296
297 /*
298  * 2048x1080 (2K) at 24 fps or 48 fps, or 4096x2160 (4K) at 24 fps; 3x12 bits per pixel, XYZ color space
299  *
300  * - In 2K, for Scope (2.39:1) presentation 2048x858 pixels of the imager is used
301  * - In 2K, for Flat (1.85:1) presentation 1998x1080 pixels of the imager is used
302  */
303
304 /* ****************************** COPIED FROM image_to_j2k.c */
305
306 /* ----------------------------------------------------------------------- */
307 #define CINEMA_24_CS 1302083    /*Codestream length for 24fps*/
308 #define CINEMA_48_CS 651041             /*Codestream length for 48fps*/
309 #define COMP_24_CS 1041666              /*Maximum size per color component for 2K & 4K @ 24fps*/
310 #define COMP_48_CS 520833               /*Maximum size per color component for 2K @ 48fps*/
311
312
313 static int initialise_4K_poc(opj_poc_t *POC, int numres)
314 {
315         POC[0].tile  = 1; 
316         POC[0].resno0  = 0; 
317         POC[0].compno0 = 0;
318         POC[0].layno1  = 1;
319         POC[0].resno1  = numres-1;
320         POC[0].compno1 = 3;
321         POC[0].prg1 = CPRL;
322         POC[1].tile  = 1;
323         POC[1].resno0  = numres-1; 
324         POC[1].compno0 = 0;
325         POC[1].layno1  = 1;
326         POC[1].resno1  = numres;
327         POC[1].compno1 = 3;
328         POC[1].prg1 = CPRL;
329         return 2;
330 }
331
332 static void cinema_parameters(opj_cparameters_t *parameters)
333 {
334         parameters->tile_size_on = FALSE;
335         parameters->cp_tdx=1;
336         parameters->cp_tdy=1;
337         
338         /*Tile part*/
339         parameters->tp_flag = 'C';
340         parameters->tp_on = 1;
341
342         /*Tile and Image shall be at (0,0)*/
343         parameters->cp_tx0 = 0;
344         parameters->cp_ty0 = 0;
345         parameters->image_offset_x0 = 0;
346         parameters->image_offset_y0 = 0;
347
348         /*Codeblock size= 32*32*/
349         parameters->cblockw_init = 32;  
350         parameters->cblockh_init = 32;
351         parameters->csty |= 0x01;
352
353         /*The progression order shall be CPRL*/
354         parameters->prog_order = CPRL;
355
356         /* No ROI */
357         parameters->roi_compno = -1;
358
359         parameters->subsampling_dx = 1;         parameters->subsampling_dy = 1;
360
361         /* 9-7 transform */
362         parameters->irreversible = 1;
363
364 }
365
366 static void cinema_setup_encoder(opj_cparameters_t *parameters,opj_image_t *image, img_fol_t *img_fol)
367 {
368         int i;
369         float temp_rate;
370
371         switch (parameters->cp_cinema) {
372         case CINEMA2K_24:
373         case CINEMA2K_48:
374                 if (parameters->numresolution > 6) {
375                         parameters->numresolution = 6;
376                 }
377                 if (!((image->comps[0].w == 2048) || (image->comps[0].h == 1080))) {
378                         fprintf(stdout,"Image coordinates %d x %d is not 2K compliant.\nJPEG Digital Cinema Profile-3 "
379                                 "(2K profile) compliance requires that at least one of coordinates match 2048 x 1080\n",
380                                 image->comps[0].w,image->comps[0].h);
381                         parameters->cp_rsiz = STD_RSIZ;
382                 }
383         break;
384         
385         case CINEMA4K_24:
386                 if (parameters->numresolution < 1) {
387                         parameters->numresolution = 1;
388                 }
389                 else if (parameters->numresolution > 7) {
390                         parameters->numresolution = 7;
391                 }
392                 if (!((image->comps[0].w == 4096) || (image->comps[0].h == 2160))) {
393                         fprintf(stdout,"Image coordinates %d x %d is not 4K compliant.\nJPEG Digital Cinema Profile-4"
394                                         "(4K profile) compliance requires that at least one of coordinates match 4096 x 2160\n",
395                                         image->comps[0].w,image->comps[0].h);
396                         parameters->cp_rsiz = STD_RSIZ;
397                 }
398                 parameters->numpocs = initialise_4K_poc(parameters->POC,parameters->numresolution);
399                 break;
400         case OFF:
401                 /* do nothing */
402                 break;
403         }
404
405         switch (parameters->cp_cinema) {
406         case CINEMA2K_24:
407         case CINEMA4K_24:
408                 for (i=0 ; i<parameters->tcp_numlayers ; i++) {
409                         temp_rate = 0;
410                         if (img_fol->rates[i]== 0) {
411                                 parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ 
412                                         (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
413                         }
414                         else {
415                                 temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ 
416                                         (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);
417                                 if (temp_rate > CINEMA_24_CS ) {
418                                         parameters->tcp_rates[i]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ 
419                                                 (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
420                                 }
421                                 else {
422                                         parameters->tcp_rates[i]= img_fol->rates[i];
423                                 }
424                         }
425                 }
426                 parameters->max_comp_size = COMP_24_CS;
427                 break;
428                 
429         case CINEMA2K_48:
430                 for (i=0 ; i<parameters->tcp_numlayers ; i++) {
431                         temp_rate = 0;
432                         if (img_fol->rates[i]== 0) {
433                                 parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ 
434                                         (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
435                         }
436                         else {
437                                 temp_rate =((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ 
438                                         (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);
439                                 if (temp_rate > CINEMA_48_CS ) {
440                                         parameters->tcp_rates[0]= ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec))/ 
441                                                 (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
442                                 }
443                                 else {
444                                         parameters->tcp_rates[i]= img_fol->rates[i];
445                                 }
446                         }
447                 }
448                 parameters->max_comp_size = COMP_48_CS;
449                 break;
450         case OFF:
451                 /* do nothing */
452                 break;
453         }
454         parameters->cp_disto_alloc = 1;
455 }
456
457
458 static opj_image_t* ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
459 {
460         unsigned char *rect;
461         float *rect_float;
462         
463         int subsampling_dx = parameters->subsampling_dx;
464         int subsampling_dy = parameters->subsampling_dy;
465         
466
467         int i, numcomps, w, h, prec;
468         int x,y, y_row;
469         OPJ_COLOR_SPACE color_space;
470         opj_image_cmptparm_t cmptparm[4];       /* maximum of 4 components */
471         opj_image_t * image = NULL;
472         
473         img_fol_t img_fol; /* only needed for cinema presets */
474         memset(&img_fol,0,sizeof(img_fol_t));
475         
476         if (ibuf->ftype & JP2_CINE) {
477                 
478                 if (ibuf->x==4096 || ibuf->y==2160)
479                         parameters->cp_cinema= CINEMA4K_24;
480                 else {
481                         if (ibuf->ftype & JP2_CINE_48FPS) {
482                                 parameters->cp_cinema= CINEMA2K_48;
483                         }
484                         else {
485                                 parameters->cp_cinema= CINEMA2K_24;
486                         }
487                 }
488                 if (parameters->cp_cinema) {
489                         img_fol.rates = (float*)MEM_mallocN(parameters->tcp_numlayers * sizeof(float), "jp2_rates");
490                         for (i=0; i< parameters->tcp_numlayers; i++) {
491                                 img_fol.rates[i] = parameters->tcp_rates[i];
492                         }
493                         cinema_parameters(parameters);
494                 }
495                 
496                 color_space= CLRSPC_SYCC;
497                 prec= 12;
498                 numcomps= 3;
499         }
500         else { 
501                 /* Get settings from the imbuf */
502                 color_space = (ibuf->ftype & JP2_YCC) ? CLRSPC_SYCC : CLRSPC_SRGB;
503                 
504                 if (ibuf->ftype & JP2_16BIT)            prec= 16;
505                 else if (ibuf->ftype & JP2_12BIT)       prec= 12;
506                 else                                            prec= 8;
507                 
508                 /* 32bit images == alpha channel */
509                 /* grayscale not supported yet */
510                 numcomps= (ibuf->planes==32) ? 4 : 3;
511         }
512         
513         w= ibuf->x;
514         h= ibuf->y;
515         
516         
517         /* initialize image components */
518         memset(&cmptparm[0], 0, 4 * sizeof(opj_image_cmptparm_t));
519         for (i = 0; i < numcomps; i++) {
520                 cmptparm[i].prec = prec;
521                 cmptparm[i].bpp = prec;
522                 cmptparm[i].sgnd = 0;
523                 cmptparm[i].dx = subsampling_dx;
524                 cmptparm[i].dy = subsampling_dy;
525                 cmptparm[i].w = w;
526                 cmptparm[i].h = h;
527         }
528         /* create the image */
529         image = opj_image_create(numcomps, &cmptparm[0], color_space);
530         if (!image) {
531                 printf("Error: opj_image_create() failed\n");
532                 return NULL;
533         }
534
535         /* set image offset and reference grid */
536         image->x0 = parameters->image_offset_x0;
537         image->y0 = parameters->image_offset_y0;
538         image->x1 = parameters->image_offset_x0 + (w - 1) *     subsampling_dx + 1;
539         image->y1 = parameters->image_offset_y0 + (h - 1) *     subsampling_dy + 1;
540         
541         /* set image data */
542         rect = (unsigned char*) ibuf->rect;
543         rect_float= ibuf->rect_float;
544         
545         if (rect_float && rect && prec==8) {
546                 /* No need to use the floating point buffer, just write the 8 bits from the char buffer */
547                 rect_float= NULL;
548         }
549         
550         
551         if (rect_float) {
552                 float rgb[3];
553                 
554                 switch (prec) {
555                 case 8: /* Convert blenders float color channels to 8,12 or 16bit ints */
556                         for (y=h-1; y>=0; y--) {
557                                 y_row = y*w;
558                                 for (x=0; x<w; x++, rect_float+=4) {
559                                         i = y_row + x;
560                                         
561                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB)
562                                                 linearrgb_to_srgb_v3_v3(rgb, rect_float);
563                                         else
564                                                 copy_v3_v3(rgb, rect_float);
565                                 
566                                         image->comps[0].data[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rgb[0]);
567                                         image->comps[1].data[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rgb[1]);
568                                         image->comps[2].data[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rgb[2]);
569                                         if (numcomps>3)
570                                                 image->comps[3].data[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[3]);
571                                 }
572                         }
573                         break;
574                         
575                 case 12:
576                         for (y=h-1; y>=0; y--) {
577                                 y_row = y*w;
578                                 for (x=0; x<w; x++, rect_float+=4) {
579                                         i = y_row + x;
580                                         
581                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB)
582                                                 linearrgb_to_srgb_v3_v3(rgb, rect_float);
583                                         else
584                                                 copy_v3_v3(rgb, rect_float);
585                                 
586                                         image->comps[0].data[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rgb[0]);
587                                         image->comps[1].data[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rgb[1]);
588                                         image->comps[2].data[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rgb[2]);
589                                         if (numcomps>3)
590                                                 image->comps[3].data[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[3]);
591                                 }
592                         }
593                         break;
594                 case 16:
595                         for (y=h-1; y>=0; y--) {
596                                 y_row = y*w;
597                                 for (x=0; x<w; x++, rect_float+=4) {
598                                         i = y_row + x;
599                                         
600                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB)
601                                                 linearrgb_to_srgb_v3_v3(rgb, rect_float);
602                                         else
603                                                 copy_v3_v3(rgb, rect_float);
604                                 
605                                         image->comps[0].data[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rgb[0]);
606                                         image->comps[1].data[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rgb[1]);
607                                         image->comps[2].data[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rgb[2]);
608                                         if (numcomps>3)
609                                                 image->comps[3].data[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[3]);
610                                 }
611                         }
612                         break;
613                 }
614         }
615         else {
616                 /* just use rect*/
617                 switch (prec) {
618                 case 8:
619                         for (y=h-1; y>=0; y--) {
620                                 y_row = y*w;
621                                 for (x=0; x<w; x++, rect+=4) {
622                                         i = y_row + x;
623                                 
624                                         image->comps[0].data[i] = rect[0];
625                                         image->comps[1].data[i] = rect[1];
626                                         image->comps[2].data[i] = rect[2];
627                                         if (numcomps>3)
628                                                 image->comps[3].data[i] = rect[3];
629                                 }
630                         }
631                         break;
632                         
633                 case 12: /* Up Sampling, a bit pointless but best write the bit depth requested */
634                         for (y=h-1; y>=0; y--) {
635                                 y_row = y*w;
636                                 for (x=0; x<w; x++, rect+=4) {
637                                         i = y_row + x;
638                                 
639                                         image->comps[0].data[i]= UPSAMPLE_8_TO_12(rect[0]);
640                                         image->comps[1].data[i]= UPSAMPLE_8_TO_12(rect[1]);
641                                         image->comps[2].data[i]= UPSAMPLE_8_TO_12(rect[2]);
642                                         if (numcomps>3)
643                                                 image->comps[3].data[i]= UPSAMPLE_8_TO_12(rect[3]);
644                                 }
645                         }
646                         break;
647                 case 16:
648                         for (y=h-1; y>=0; y--) {
649                                 y_row = y*w;
650                                 for (x=0; x<w; x++, rect+=4) {
651                                         i = y_row + x;
652                                 
653                                         image->comps[0].data[i]= UPSAMPLE_8_TO_16(rect[0]);
654                                         image->comps[1].data[i]= UPSAMPLE_8_TO_16(rect[1]);
655                                         image->comps[2].data[i]= UPSAMPLE_8_TO_16(rect[2]);
656                                         if (numcomps>3)
657                                                 image->comps[3].data[i]= UPSAMPLE_8_TO_16(rect[3]);
658                                 }
659                         }
660                         break;
661                 }
662         }
663         
664         /* Decide if MCT should be used */
665         parameters->tcp_mct = image->numcomps == 3 ? 1 : 0;
666         
667         if (parameters->cp_cinema) {
668                 cinema_setup_encoder(parameters,image,&img_fol);
669         }
670         
671         if (img_fol.rates)
672                 MEM_freeN(img_fol.rates);
673         
674         return image;
675 }
676
677
678 /* Found write info at http://users.ece.gatech.edu/~slabaugh/personal/c/bitmapUnix.c */
679 int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags)
680 {
681         int quality = ibuf->ftype & 0xff;
682         
683         int bSuccess;
684         opj_cparameters_t parameters;   /* compression parameters */
685         opj_event_mgr_t event_mgr;              /* event manager */
686         opj_image_t *image = NULL;
687         
688         (void)flags; /* unused */
689         
690         /*
691          * configure the event callbacks (not required)
692          * setting of each callback is optionnal
693          */
694         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
695         event_mgr.error_handler = error_callback;
696         event_mgr.warning_handler = warning_callback;
697         event_mgr.info_handler = info_callback;
698         
699         /* set encoding parameters to default values */
700         opj_set_default_encoder_parameters(&parameters);
701         
702         /* compression ratio */
703         /* invert range, from 10-100, 100-1
704          * where jpeg see's 1 and highest quality (lossless) and 100 is very low quality*/
705         parameters.tcp_rates[0]= ((100-quality)/90.0f*99.0f) + 1;
706
707         
708         parameters.tcp_numlayers = 1; // only one resolution
709         parameters.cp_disto_alloc = 1;
710
711         image= ibuftoimage(ibuf, &parameters);
712         
713         
714         {                       /* JP2 format output */
715                 int codestream_length;
716                 opj_cio_t *cio = NULL;
717                 FILE *f = NULL;
718
719                 /* get a JP2 compressor handle */
720                 opj_cinfo_t* cinfo = opj_create_compress(CODEC_JP2);
721
722                 /* catch events using our callbacks and give a local context */
723                 opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);                   
724
725                 /* setup the encoder parameters using the current image and using user parameters */
726                 opj_setup_encoder(cinfo, &parameters, image);
727
728                 /* open a byte stream for writing */
729                 /* allocate memory for all tiles */
730                 cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
731
732                 /* encode the image */
733                 bSuccess = opj_encode(cinfo, cio, image, NULL); /* last arg used to be parameters.index but this deprecated */
734                 
735                 if (!bSuccess) {
736                         opj_cio_close(cio);
737                         fprintf(stderr, "failed to encode image\n");
738                         return 0;
739                 }
740                 codestream_length = cio_tell(cio);
741
742                 /* write the buffer to disk */
743                 f = BLI_fopen(name, "wb");
744                 
745                 if (!f) {
746                         fprintf(stderr, "failed to open %s for writing\n", name);
747                         return 1;
748                 }
749                 fwrite(cio->buffer, 1, codestream_length, f);
750                 fclose(f);
751                 fprintf(stderr,"Generated outfile %s\n",name);
752                 /* close and free the byte stream */
753                 opj_cio_close(cio);
754                 
755                 /* free remaining compression structures */
756                 opj_destroy_compress(cinfo);
757         }
758
759         /* free image data */
760         opj_image_destroy(image);
761         
762         return 1;
763 }