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