Merging r40242 through r40264 from trunk into soc-2011-tomato
[blender.git] / source / blender / imbuf / intern / jp2.c
1 /*
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * Contributor(s): Campbell Barton
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  */
23
24 /** \file blender/imbuf/intern/jp2.c
25  *  \ingroup imbuf
26  */
27
28
29 #ifdef WITH_OPENJPEG
30
31 #include "MEM_guardedalloc.h"
32
33 #include "BLI_blenlib.h"
34 #include "BLI_math.h"
35
36 #include "imbuf.h"
37
38 #include "IMB_imbuf_types.h"
39 #include "IMB_imbuf.h"
40 #include "IMB_allocimbuf.h"
41 #include "IMB_filetype.h"
42
43 #include "openjpeg.h"
44
45 #define JP2_FILEHEADER_SIZE 14
46
47 static char JP2_HEAD[]= {0x0, 0x0, 0x0, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A};
48
49 /* We only need this because of how the presets are set */
50 typedef struct img_folder{
51         /** The directory path of the folder containing input images*/
52         char *imgdirpath;
53         /** Output format*/
54         char *out_format;
55         /** Enable option*/
56         char set_imgdir;
57         /** Enable Cod Format for output*/
58         char set_out_format;
59         /** User specified rate stored in case of cinema option*/
60         float *rates;
61 }img_fol_t;
62
63 static int check_jp2(unsigned char *mem) /* J2K_CFMT */
64 {
65         return memcmp(JP2_HEAD, mem, 12) ? 0 : 1;
66 }
67
68 int imb_is_a_jp2(unsigned char *buf)
69 {       
70         return check_jp2(buf);
71 }
72
73
74 /**
75 sample error callback expecting a FILE* client object
76 */
77 static void error_callback(const char *msg, void *client_data) {
78         FILE *stream = (FILE*)client_data;
79         fprintf(stream, "[ERROR] %s", msg);
80 }
81 /**
82 sample warning callback expecting a FILE* client object
83 */
84 static void warning_callback(const char *msg, void *client_data) {
85         FILE *stream = (FILE*)client_data;
86         fprintf(stream, "[WARNING] %s", msg);
87 }
88 /**
89 sample debug callback expecting no client object
90 */
91 static void info_callback(const char *msg, void *client_data) {
92         (void)client_data;
93         fprintf(stdout, "[INFO] %s", msg);
94 }
95
96
97
98 struct ImBuf *imb_jp2_decode(unsigned char *mem, size_t size, int flags)
99 {
100         struct ImBuf *ibuf = NULL;
101         int use_float = 0; /* for precision higher then 8 use float */
102         
103         long signed_offsets[4]= {0, 0, 0, 0};
104         int float_divs[4]= {1, 1, 1, 1};
105
106         int index;
107         
108         int w, h, depth;
109         
110         opj_dparameters_t parameters;   /* decompression parameters */
111         
112         opj_event_mgr_t event_mgr;              /* event manager */
113         opj_image_t *image = NULL;
114         
115         int i;
116         
117         opj_dinfo_t* dinfo = NULL;      /* handle to a decompressor */
118         opj_cio_t *cio = NULL;
119
120         if (check_jp2(mem) == 0) return(NULL);
121
122         /* configure the event callbacks (not required) */
123         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
124         event_mgr.error_handler = error_callback;
125         event_mgr.warning_handler = warning_callback;
126         event_mgr.info_handler = info_callback;
127
128
129         /* set decoding parameters to default values */
130         opj_set_default_decoder_parameters(&parameters);
131
132
133         /* JPEG 2000 compressed image data */
134
135         /* get a decoder handle */
136         dinfo = opj_create_decompress(CODEC_JP2);
137
138         /* catch events using our callbacks and give a local context */
139         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
140
141         /* setup the decoder decoding parameters using the current image and user parameters */
142         opj_setup_decoder(dinfo, &parameters);
143
144         /* open a byte stream */
145         cio = opj_cio_open((opj_common_ptr)dinfo, mem, size);
146
147         /* decode the stream and fill the image structure */
148         image = opj_decode(dinfo, cio);
149         
150         if(!image) {
151                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
152                 opj_destroy_decompress(dinfo);
153                 opj_cio_close(cio);
154                 return NULL;
155         }
156
157         /* close the byte stream */
158         opj_cio_close(cio);
159
160
161         if((image->numcomps * image->x1 * image->y1) == 0)
162         {
163                 fprintf(stderr,"\nError: invalid raw image parameters\n");
164                 return NULL;
165         }
166         
167         w = image->comps[0].w;
168         h = image->comps[0].h;
169         
170         switch (image->numcomps) {
171         case 1: /* Greyscale */
172         case 3: /* Color */
173                 depth= 24; 
174                 break;
175         default: /* 2 or 4 - Greyscale or Color + alpha */
176                 depth= 32; /* greyscale + alpha */
177                 break;
178         }
179         
180         
181         i = image->numcomps;
182         if (i>4) i= 4;
183         
184         while (i) {
185                 i--;
186                 
187                 if (image->comps[i].prec > 8)
188                         use_float = 1;
189                 
190                 if (image->comps[i].sgnd)
191                         signed_offsets[i]=  1 << (image->comps[i].prec - 1); 
192                 
193                 /* only needed for float images but dosnt hurt to calc this */
194                 float_divs[i]= (1<<image->comps[i].prec)-1;
195         }
196         
197         ibuf= IMB_allocImBuf(w, h, depth, use_float ? IB_rectfloat : IB_rect);
198         
199         if (ibuf==NULL) {
200                 if(dinfo)
201                         opj_destroy_decompress(dinfo);
202                 return NULL;
203         }
204         
205         ibuf->ftype = JP2;
206         
207         if (use_float) {
208                 float *rect_float= ibuf->rect_float;
209
210                 if (image->numcomps < 3) {
211                         /* greyscale 12bits+ */
212                         for (i = 0; i < w * h; i++, rect_float+=4) {
213                                 index = w * h - ((i) / (w) + 1) * w + (i) % (w);
214                                 
215                                 rect_float[0]= rect_float[1]= rect_float[2]= (float)(image->comps[0].data[index] + signed_offsets[0]) / float_divs[0];
216                                 
217                                 if (image->numcomps == 2)
218                                         rect_float[3]= (image->comps[1].data[index] + signed_offsets[1]) / float_divs[1];
219                                 else
220                                         rect_float[3]= 1.0f;
221                         }
222                 } else {
223                         /* rgb or rgba 12bits+ */
224                         for (i = 0; i < w * h; i++, rect_float+=4) {
225                                 index = w * h - ((i) / (w) + 1) * w + (i) % (w);
226                                 
227                                 rect_float[0]= (float)(image->comps[0].data[index] + signed_offsets[0]) / float_divs[0];
228                                 rect_float[1]= (float)(image->comps[1].data[index] + signed_offsets[1]) / float_divs[1];
229                                 rect_float[2]= (float)(image->comps[2].data[index] + signed_offsets[2]) / float_divs[2];
230                                 
231                                 if (image->numcomps >= 4)
232                                         rect_float[3]= (float)(image->comps[3].data[index] + signed_offsets[3]) / float_divs[3];
233                                 else
234                                         rect_float[3]= 1.0f;
235                         }
236                 }
237                 
238         } else {
239                 unsigned char *rect= (unsigned char *)ibuf->rect;
240
241                 if (image->numcomps < 3) {
242                         /* greyscale */
243                         for (i = 0; i < w * h; i++, rect+=4) {
244                                 index = w * h - ((i) / (w) + 1) * w + (i) % (w);
245                                 
246                                 rect[0]= rect[1]= rect[2]= (image->comps[0].data[index] + signed_offsets[0]);
247                                 
248                                 if (image->numcomps == 2)
249                                         rect[3]= image->comps[1].data[index] + signed_offsets[1];
250                                 else
251                                         rect[3]= 255;
252                         }
253                 } 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[3].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; 3x12 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 static 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 static 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                 float rgb[3];
544                 
545                 switch (prec) {
546                 case 8: /* Convert blenders float color channels to 8,12 or 16bit ints */
547                         for(y=h-1; y>=0; y--) {
548                                 y_row = y*w;
549                                 for(x=0; x<w; x++, rect_float+=4) {
550                                         i = y_row + x;
551                                         
552                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB)
553                                                 linearrgb_to_srgb_v3_v3(rgb, rect_float);
554                                         else
555                                                 copy_v3_v3(rgb, rect_float);
556                                 
557                                         image->comps[0].data[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rgb[0]);
558                                         image->comps[1].data[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rgb[1]);
559                                         image->comps[2].data[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rgb[2]);
560                                         if (numcomps>3)
561                                                 image->comps[3].data[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[3]);
562                                 }
563                         }
564                         break;
565                         
566                 case 12:
567                         for(y=h-1; y>=0; y--) {
568                                 y_row = y*w;
569                                 for(x=0; x<w; x++, rect_float+=4) {
570                                         i = y_row + x;
571                                         
572                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB)
573                                                 linearrgb_to_srgb_v3_v3(rgb, rect_float);
574                                         else
575                                                 copy_v3_v3(rgb, rect_float);
576                                 
577                                         image->comps[0].data[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rgb[0]);
578                                         image->comps[1].data[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rgb[1]);
579                                         image->comps[2].data[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rgb[2]);
580                                         if (numcomps>3)
581                                                 image->comps[3].data[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[3]);
582                                 }
583                         }
584                         break;
585                 case 16:
586                         for(y=h-1; y>=0; y--) {
587                                 y_row = y*w;
588                                 for(x=0; x<w; x++, rect_float+=4) {
589                                         i = y_row + x;
590                                         
591                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB)
592                                                 linearrgb_to_srgb_v3_v3(rgb, rect_float);
593                                         else
594                                                 copy_v3_v3(rgb, rect_float);
595                                 
596                                         image->comps[0].data[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rgb[0]);
597                                         image->comps[1].data[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rgb[1]);
598                                         image->comps[2].data[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rgb[2]);
599                                         if (numcomps>3)
600                                                 image->comps[3].data[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[3]);
601                                 }
602                         }
603                         break;
604                 }
605         } else {
606                 /* just use rect*/
607                 switch (prec) {
608                 case 8:
609                         for(y=h-1; y>=0; y--) {
610                                 y_row = y*w;
611                                 for(x=0; x<w; x++, rect+=4) {
612                                         i = y_row + x;
613                                 
614                                         image->comps[0].data[i] = rect[0];
615                                         image->comps[1].data[i] = rect[1];
616                                         image->comps[2].data[i] = rect[2];
617                                         if (numcomps>3)
618                                                 image->comps[3].data[i] = rect[3];
619                                 }
620                         }
621                         break;
622                         
623                 case 12: /* Up Sampling, a bit pointless but best write the bit depth requested */
624                         for(y=h-1; y>=0; y--) {
625                                 y_row = y*w;
626                                 for(x=0; x<w; x++, rect+=4) {
627                                         i = y_row + x;
628                                 
629                                         image->comps[0].data[i]= UPSAMPLE_8_TO_12(rect[0]);
630                                         image->comps[1].data[i]= UPSAMPLE_8_TO_12(rect[1]);
631                                         image->comps[2].data[i]= UPSAMPLE_8_TO_12(rect[2]);
632                                         if (numcomps>3)
633                                                 image->comps[3].data[i]= UPSAMPLE_8_TO_12(rect[3]);
634                                 }
635                         }
636                         break;
637                 case 16:
638                         for(y=h-1; y>=0; y--) {
639                                 y_row = y*w;
640                                 for(x=0; x<w; x++, rect+=4) {
641                                         i = y_row + x;
642                                 
643                                         image->comps[0].data[i]= UPSAMPLE_8_TO_16(rect[0]);
644                                         image->comps[1].data[i]= UPSAMPLE_8_TO_16(rect[1]);
645                                         image->comps[2].data[i]= UPSAMPLE_8_TO_16(rect[2]);
646                                         if (numcomps>3)
647                                                 image->comps[3].data[i]= UPSAMPLE_8_TO_16(rect[3]);
648                                 }
649                         }
650                         break;
651                 }
652         }
653         
654         /* Decide if MCT should be used */
655         parameters->tcp_mct = image->numcomps == 3 ? 1 : 0;
656         
657         if(parameters->cp_cinema){
658                 cinema_setup_encoder(parameters,image,&img_fol);
659         }
660         
661         if (img_fol.rates)
662                 MEM_freeN(img_fol.rates);
663         
664         return image;
665 }
666
667
668 /* Found write info at http://users.ece.gatech.edu/~slabaugh/personal/c/bitmapUnix.c */
669 int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags) {
670         
671         int quality = ibuf->ftype & 0xff;
672         
673         int bSuccess;
674         opj_cparameters_t parameters;   /* compression parameters */
675         opj_event_mgr_t event_mgr;              /* event manager */
676         opj_image_t *image = NULL;
677         
678         (void)flags; /* unused */
679         
680         /*
681         configure the event callbacks (not required)
682         setting of each callback is optionnal
683         */
684         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
685         event_mgr.error_handler = error_callback;
686         event_mgr.warning_handler = warning_callback;
687         event_mgr.info_handler = info_callback;
688         
689         /* set encoding parameters to default values */
690         opj_set_default_encoder_parameters(&parameters);
691         
692         /* compression ratio */
693         /* invert range, from 10-100, 100-1
694         * where jpeg see's 1 and highest quality (lossless) and 100 is very low quality*/
695         parameters.tcp_rates[0]= ((100-quality)/90.0f*99.0f) + 1;
696
697         
698         parameters.tcp_numlayers = 1; // only one resolution
699         parameters.cp_disto_alloc = 1;
700
701         image= ibuftoimage(ibuf, &parameters);
702         
703         
704         {                       /* JP2 format output */
705                 int codestream_length;
706                 opj_cio_t *cio = NULL;
707                 FILE *f = NULL;
708
709                 /* get a JP2 compressor handle */
710                 opj_cinfo_t* cinfo = opj_create_compress(CODEC_JP2);
711
712                 /* catch events using our callbacks and give a local context */
713                 opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);                   
714
715                 /* setup the encoder parameters using the current image and using user parameters */
716                 opj_setup_encoder(cinfo, &parameters, image);
717
718                 /* open a byte stream for writing */
719                 /* allocate memory for all tiles */
720                 cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
721
722                 /* encode the image */
723                 bSuccess = opj_encode(cinfo, cio, image, NULL); /* last arg used to be parameters.index but this deprecated */
724                 
725                 if (!bSuccess) {
726                         opj_cio_close(cio);
727                         fprintf(stderr, "failed to encode image\n");
728                         return 0;
729                 }
730                 codestream_length = cio_tell(cio);
731
732                 /* write the buffer to disk */
733                 f = fopen(name, "wb");
734                 
735                 if (!f) {
736                         fprintf(stderr, "failed to open %s for writing\n", name);
737                         return 1;
738                 }
739                 fwrite(cio->buffer, 1, codestream_length, f);
740                 fclose(f);
741                 fprintf(stderr,"Generated outfile %s\n",name);
742                 /* close and free the byte stream */
743                 opj_cio_close(cio);
744                 
745                 /* free remaining compression structures */
746                 opj_destroy_compress(cinfo);
747         }
748
749         /* free image data */
750         opj_image_destroy(image);
751         
752         return 1;
753 }
754
755 #endif /* WITH_OPENJPEG */