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