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