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