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