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