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