File format fixes
[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_math.h"
30 #include "BLI_fileops.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 static char J2K_HEAD[] = {0xFF, 0x4F, 0xFF, 0x51, 0x00};
45
46 /* We only need this because of how the presets are set */
47 /* this typedef is copied from 'openjpeg-1.5.0/applications/codec/image_to_j2k.c' */
48 typedef struct img_folder {
49         /** The directory path of the folder containing input images*/
50         char *imgdirpath;
51         /** Output format*/
52         char *out_format;
53         /** Enable option*/
54         char set_imgdir;
55         /** Enable Cod Format for output*/
56         char set_out_format;
57         /** User specified rate stored in case of cinema option*/
58         float *rates;
59 } img_fol_t;
60
61 static int check_jp2(unsigned char *mem) /* J2K_CFMT */
62 {
63         return memcmp(JP2_HEAD, mem, sizeof(JP2_HEAD)) ? 0 : 1;
64 }
65
66 static int check_j2k(unsigned char *mem) /* J2K_CFMT */
67 {
68         return memcmp(J2K_HEAD, mem, sizeof(J2K_HEAD)) ? 0 : 1;
69 }
70
71 int imb_is_a_jp2(unsigned char *buf)
72 {
73         return check_jp2(buf);
74 }
75
76 /**
77  * sample error callback expecting a FILE* client object
78  */
79 static void error_callback(const char *msg, void *client_data)
80 {
81         FILE *stream = (FILE *)client_data;
82         fprintf(stream, "[ERROR] %s", msg);
83 }
84 /**
85  * sample warning callback expecting a FILE* client object
86  */
87 static void warning_callback(const char *msg, void *client_data)
88 {
89         FILE *stream = (FILE *)client_data;
90         fprintf(stream, "[WARNING] %s", msg);
91 }
92 /**
93  * sample debug callback expecting no client object
94  */
95 static void info_callback(const char *msg, void *client_data)
96 {
97         (void)client_data;
98         fprintf(stdout, "[INFO] %s", msg);
99 }
100
101 #   define PIXEL_LOOPER_BEGIN(_rect)                                          \
102         for (y = h - 1; y != (unsigned int)(-1); y--) {                           \
103                 for (i = y * w, i_next = (y + 1) * w;                                 \
104                      i < i_next;                                                      \
105                      i++, _rect += 4)                                                 \
106                 {                                                                     \
107
108 #   define PIXEL_LOOPER_END \
109         } \
110         } (void)0 \
111
112 struct ImBuf *imb_jp2_decode(unsigned char *mem, size_t size, int flags)
113 {
114         struct ImBuf *ibuf = NULL;
115         int use_float = FALSE; /* for precision higher then 8 use float */
116         int use_alpha = FALSE;
117         
118         long signed_offsets[4] = {0, 0, 0, 0};
119         int float_divs[4] = {1, 1, 1, 1};
120
121         unsigned int i, i_next, w, h, planes;
122         unsigned int y;
123         int *r, *g, *b, *a; /* matching 'opj_image_comp.data' type */
124         int is_jp2, is_j2k;
125         
126         opj_dparameters_t parameters;   /* decompression parameters */
127         
128         opj_event_mgr_t event_mgr;      /* event manager */
129         opj_image_t *image = NULL;
130
131         opj_dinfo_t *dinfo = NULL;  /* handle to a decompressor */
132         opj_cio_t *cio = NULL;
133
134         is_jp2 = check_jp2(mem);
135         is_j2k = check_j2k(mem);
136
137         if (!is_jp2 && !is_j2k)
138                 return(NULL);
139
140         /* configure the event callbacks (not required) */
141         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
142         event_mgr.error_handler = error_callback;
143         event_mgr.warning_handler = warning_callback;
144         event_mgr.info_handler = info_callback;
145
146
147         /* set decoding parameters to default values */
148         opj_set_default_decoder_parameters(&parameters);
149
150
151         /* JPEG 2000 compressed image data */
152
153         /* get a decoder handle */
154         dinfo = opj_create_decompress(is_jp2 ? CODEC_JP2 : CODEC_J2K);
155
156         /* catch events using our callbacks and give a local context */
157         opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);
158
159         /* setup the decoder decoding parameters using the current image and user parameters */
160         opj_setup_decoder(dinfo, &parameters);
161
162         /* open a byte stream */
163         cio = opj_cio_open((opj_common_ptr)dinfo, mem, size);
164
165         /* decode the stream and fill the image structure */
166         image = opj_decode(dinfo, cio);
167         
168         if (!image) {
169                 fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
170                 opj_destroy_decompress(dinfo);
171                 opj_cio_close(cio);
172                 return NULL;
173         }
174
175         /* close the byte stream */
176         opj_cio_close(cio);
177
178
179         if ((image->numcomps * image->x1 * image->y1) == 0) {
180                 fprintf(stderr, "\nError: invalid raw image parameters\n");
181                 return NULL;
182         }
183         
184         w = image->comps[0].w;
185         h = image->comps[0].h;
186         
187         switch (image->numcomps) {
188                 case 1: /* Grayscale */
189                 case 3: /* Color */
190                         planes = 24;
191                         use_alpha = FALSE;
192                         break;
193                 default: /* 2 or 4 - Grayscale or Color + alpha */
194                         planes = 32; /* grayscale + alpha */
195                         use_alpha = TRUE;
196                         break;
197         }
198         
199         
200         i = image->numcomps;
201         if (i > 4) i = 4;
202         
203         while (i) {
204                 i--;
205                 
206                 if (image->comps[i].prec > 8)
207                         use_float = TRUE;
208                 
209                 if (image->comps[i].sgnd)
210                         signed_offsets[i] =  1 << (image->comps[i].prec - 1);
211                 
212                 /* only needed for float images but dosnt hurt to calc this */
213                 float_divs[i] = (1 << image->comps[i].prec) - 1;
214         }
215         
216         ibuf = IMB_allocImBuf(w, h, planes, use_float ? IB_rectfloat : IB_rect);
217         
218         if (ibuf == NULL) {
219                 if (dinfo)
220                         opj_destroy_decompress(dinfo);
221                 return NULL;
222         }
223         
224         ibuf->ftype = JP2;
225         
226         if (use_float) {
227                 float *rect_float = ibuf->rect_float;
228
229                 if (image->numcomps < 3) {
230                         r = image->comps[0].data;
231                         a = (use_alpha) ? image->comps[1].data : NULL;
232
233                         /* grayscale 12bits+ */
234                         if (use_alpha) {
235                                 a = image->comps[1].data;
236                                 PIXEL_LOOPER_BEGIN(rect_float) {
237                                         rect_float[0] = rect_float[1] = rect_float[2] = (float)(r[i] + signed_offsets[0]) / float_divs[0];
238                                         rect_float[3] = (a[i] + signed_offsets[1]) / float_divs[1];
239                                 }
240                                 PIXEL_LOOPER_END;
241                         }
242                         else {
243                                 PIXEL_LOOPER_BEGIN(rect_float) {
244                                         rect_float[0] = rect_float[1] = rect_float[2] = (float)(r[i] + signed_offsets[0]) / float_divs[0];
245                                         rect_float[3] = 1.0f;
246                                 }
247                                 PIXEL_LOOPER_END;
248                         }
249                 }
250                 else {
251                         r = image->comps[0].data;
252                         g = image->comps[1].data;
253                         b = image->comps[2].data;
254
255                         /* rgb or rgba 12bits+ */
256                         if (use_alpha) {
257                                 a = image->comps[3].data;
258                                 PIXEL_LOOPER_BEGIN(rect_float) {
259                                         rect_float[0] = (float)(r[i] + signed_offsets[0]) / float_divs[0];
260                                         rect_float[1] = (float)(g[i] + signed_offsets[1]) / float_divs[1];
261                                         rect_float[2] = (float)(b[i] + signed_offsets[2]) / float_divs[2];
262                                         rect_float[3] = (float)(a[i] + signed_offsets[3]) / float_divs[3];
263                                 }
264                                 PIXEL_LOOPER_END;
265                         }
266                         else {
267                                 PIXEL_LOOPER_BEGIN(rect_float) {
268                                         rect_float[0] = (float)(r[i] + signed_offsets[0]) / float_divs[0];
269                                         rect_float[1] = (float)(g[i] + signed_offsets[1]) / float_divs[1];
270                                         rect_float[2] = (float)(b[i] + signed_offsets[2]) / float_divs[2];
271                                         rect_float[3] = 1.0f;
272                                 }
273                                 PIXEL_LOOPER_END;
274                         }
275                 }
276                 
277         }
278         else {
279                 unsigned char *rect_uchar = (unsigned char *)ibuf->rect;
280
281                 if (image->numcomps < 3) {
282                         r = image->comps[0].data;
283                         a = (use_alpha) ? image->comps[1].data : NULL;
284
285                         /* grayscale */
286                         if (use_alpha) {
287                                 a = image->comps[3].data;
288                                 PIXEL_LOOPER_BEGIN(rect_uchar) {
289                                         rect_uchar[0] = rect_uchar[1] = rect_uchar[2] = (r[i] + signed_offsets[0]);
290                                         rect_uchar[3] = a[i] + signed_offsets[1];
291                                 }
292                                 PIXEL_LOOPER_END;
293                         }
294                         else {
295                                 PIXEL_LOOPER_BEGIN(rect_uchar) {
296                                         rect_uchar[0] = rect_uchar[1] = rect_uchar[2] = (r[i] + signed_offsets[0]);
297                                         rect_uchar[3] = 255;
298                                 }
299                                 PIXEL_LOOPER_END;
300                         }
301                 }
302                 else {
303                         r = image->comps[0].data;
304                         g = image->comps[1].data;
305                         b = image->comps[2].data;
306
307                         /* 8bit rgb or rgba */
308                         if (use_alpha) {
309                                 a = image->comps[3].data;
310                                 PIXEL_LOOPER_BEGIN(rect_uchar) {
311                                         rect_uchar[0] = r[i] + signed_offsets[0];
312                                         rect_uchar[1] = g[i] + signed_offsets[1];
313                                         rect_uchar[2] = b[i] + signed_offsets[2];
314                                         rect_uchar[3] = a[i] + signed_offsets[3];
315                                 }
316                                 PIXEL_LOOPER_END;
317                         }
318                         else {
319                                 PIXEL_LOOPER_BEGIN(rect_uchar) {
320                                         rect_uchar[0] = r[i] + signed_offsets[0];
321                                         rect_uchar[1] = g[i] + signed_offsets[1];
322                                         rect_uchar[2] = b[i] + signed_offsets[2];
323                                         rect_uchar[3] = 255;
324                                 }
325                                 PIXEL_LOOPER_END;
326                         }
327                 }
328         }
329         
330         /* free remaining structures */
331         if (dinfo) {
332                 opj_destroy_decompress(dinfo);
333         }
334         
335         /* free image data structure */
336         opj_image_destroy(image);
337         
338         if (flags & IB_rect) {
339                 IMB_rect_from_float(ibuf);
340         }
341         
342         return(ibuf);
343 }
344
345 //static opj_image_t* rawtoimage(const char *filename, opj_cparameters_t *parameters, raw_cparameters_t *raw_cp)
346 /* prec can be 8, 12, 16 */
347
348 /* use inline because the float passed can be a function call that would end up being called many times */
349 #if 0
350 #define UPSAMPLE_8_TO_12(_val) ((_val << 4) | (_val & ((1 << 4) - 1)))
351 #define UPSAMPLE_8_TO_16(_val) ((_val << 8) + _val)
352
353 #define DOWNSAMPLE_FLOAT_TO_8BIT(_val)  (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 255 : (int)(255.0f * (_val)))
354 #define DOWNSAMPLE_FLOAT_TO_12BIT(_val) (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 4095 : (int)(4095.0f * (_val)))
355 #define DOWNSAMPLE_FLOAT_TO_16BIT(_val) (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 65535 : (int)(65535.0f * (_val)))
356 #else
357
358 BLI_INLINE int UPSAMPLE_8_TO_12(const unsigned char _val)
359 {
360         return (_val << 4) | (_val & ((1 << 4) - 1));
361 }
362 BLI_INLINE int UPSAMPLE_8_TO_16(const unsigned char _val)
363 {
364         return (_val << 8) + _val;
365 }
366
367 BLI_INLINE int DOWNSAMPLE_FLOAT_TO_8BIT(const float _val)
368 {
369         return (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 255 : (int)(255.0f * (_val)));
370 }
371 BLI_INLINE int DOWNSAMPLE_FLOAT_TO_12BIT(const float _val)
372 {
373         return (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 4095 : (int)(4095.0f * (_val)));
374 }
375 BLI_INLINE int DOWNSAMPLE_FLOAT_TO_16BIT(const float _val)
376 {
377         return (_val) <= 0.0f ? 0 : ((_val) >= 1.0f ? 65535 : (int)(65535.0f * (_val)));
378 }
379 #endif
380
381 /*
382  * 2048x1080 (2K) at 24 fps or 48 fps, or 4096x2160 (4K) at 24 fps; 3x12 bits per pixel, XYZ color space
383  *
384  * - In 2K, for Scope (2.39:1) presentation 2048x858 pixels of the imager is used
385  * - In 2K, for Flat (1.85:1) presentation 1998x1080 pixels of the imager is used
386  */
387
388 /* ****************************** COPIED FROM image_to_j2k.c */
389
390 /* ----------------------------------------------------------------------- */
391 #define CINEMA_24_CS 1302083    /*Codestream length for 24fps*/
392 #define CINEMA_48_CS 651041     /*Codestream length for 48fps*/
393 #define COMP_24_CS 1041666      /*Maximum size per color component for 2K & 4K @ 24fps*/
394 #define COMP_48_CS 520833       /*Maximum size per color component for 2K @ 48fps*/
395
396
397 static int initialise_4K_poc(opj_poc_t *POC, int numres)
398 {
399         POC[0].tile  = 1; 
400         POC[0].resno0  = 0; 
401         POC[0].compno0 = 0;
402         POC[0].layno1  = 1;
403         POC[0].resno1  = numres - 1;
404         POC[0].compno1 = 3;
405         POC[0].prg1 = CPRL;
406         POC[1].tile  = 1;
407         POC[1].resno0  = numres - 1;
408         POC[1].compno0 = 0;
409         POC[1].layno1  = 1;
410         POC[1].resno1  = numres;
411         POC[1].compno1 = 3;
412         POC[1].prg1 = CPRL;
413         return 2;
414 }
415
416 static void cinema_parameters(opj_cparameters_t *parameters)
417 {
418         parameters->tile_size_on = 0; /* FALSE */
419         parameters->cp_tdx = 1;
420         parameters->cp_tdy = 1;
421         
422         /*Tile part*/
423         parameters->tp_flag = 'C';
424         parameters->tp_on = 1;
425
426         /*Tile and Image shall be at (0, 0)*/
427         parameters->cp_tx0 = 0;
428         parameters->cp_ty0 = 0;
429         parameters->image_offset_x0 = 0;
430         parameters->image_offset_y0 = 0;
431
432         /*Codeblock size = 32 * 32*/
433         parameters->cblockw_init = 32;  
434         parameters->cblockh_init = 32;
435         parameters->csty |= 0x01;
436
437         /*The progression order shall be CPRL*/
438         parameters->prog_order = CPRL;
439
440         /* No ROI */
441         parameters->roi_compno = -1;
442
443         parameters->subsampling_dx = 1;     parameters->subsampling_dy = 1;
444
445         /* 9-7 transform */
446         parameters->irreversible = 1;
447
448 }
449
450 static void cinema_setup_encoder(opj_cparameters_t *parameters, opj_image_t *image, img_fol_t *img_fol)
451 {
452         int i;
453         float temp_rate;
454
455         switch (parameters->cp_cinema) {
456                 case CINEMA2K_24:
457                 case CINEMA2K_48:
458                         if (parameters->numresolution > 6) {
459                                 parameters->numresolution = 6;
460                         }
461                         if (!((image->comps[0].w == 2048) || (image->comps[0].h == 1080))) {
462                                 fprintf(stdout, "Image coordinates %d x %d is not 2K compliant.\nJPEG Digital Cinema Profile-3 "
463                                         "(2K profile) compliance requires that at least one of coordinates match 2048 x 1080\n",
464                                         image->comps[0].w, image->comps[0].h);
465                                 parameters->cp_rsiz = STD_RSIZ;
466                         }
467                         break;
468         
469                 case CINEMA4K_24:
470                         if (parameters->numresolution < 1) {
471                                 parameters->numresolution = 1;
472                         }
473                         else if (parameters->numresolution > 7) {
474                                 parameters->numresolution = 7;
475                         }
476                         if (!((image->comps[0].w == 4096) || (image->comps[0].h == 2160))) {
477                                 fprintf(stdout, "Image coordinates %d x %d is not 4K compliant.\nJPEG Digital Cinema Profile-4"
478                                         "(4K profile) compliance requires that at least one of coordinates match 4096 x 2160\n",
479                                         image->comps[0].w, image->comps[0].h);
480                                 parameters->cp_rsiz = STD_RSIZ;
481                         }
482                         parameters->numpocs = initialise_4K_poc(parameters->POC, parameters->numresolution);
483                         break;
484                 case OFF:
485                         /* do nothing */
486                         break;
487         }
488
489         switch (parameters->cp_cinema) {
490                 case CINEMA2K_24:
491                 case CINEMA4K_24:
492                         for (i = 0; i < parameters->tcp_numlayers; i++) {
493                                 temp_rate = 0;
494                                 if (img_fol->rates[i] == 0) {
495                                         parameters->tcp_rates[0] = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) /
496                                                                    (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
497                                 }
498                                 else {
499                                         temp_rate = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) /
500                                                     (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);
501                                         if (temp_rate > CINEMA_24_CS) {
502                                                 parameters->tcp_rates[i] = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) /
503                                                                            (CINEMA_24_CS * 8 * image->comps[0].dx * image->comps[0].dy);
504                                         }
505                                         else {
506                                                 parameters->tcp_rates[i] = img_fol->rates[i];
507                                         }
508                                 }
509                         }
510                         parameters->max_comp_size = COMP_24_CS;
511                         break;
512                 
513                 case CINEMA2K_48:
514                         for (i = 0; i < parameters->tcp_numlayers; i++) {
515                                 temp_rate = 0;
516                                 if (img_fol->rates[i] == 0) {
517                                         parameters->tcp_rates[0] = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) /
518                                                                    (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
519                                 }
520                                 else {
521                                         temp_rate = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) /
522                                                     (img_fol->rates[i] * 8 * image->comps[0].dx * image->comps[0].dy);
523                                         if (temp_rate > CINEMA_48_CS) {
524                                                 parameters->tcp_rates[0] = ((float) (image->numcomps * image->comps[0].w * image->comps[0].h * image->comps[0].prec)) /
525                                                                            (CINEMA_48_CS * 8 * image->comps[0].dx * image->comps[0].dy);
526                                         }
527                                         else {
528                                                 parameters->tcp_rates[i] = img_fol->rates[i];
529                                         }
530                                 }
531                         }
532                         parameters->max_comp_size = COMP_48_CS;
533                         break;
534                 case OFF:
535                         /* do nothing */
536                         break;
537         }
538         parameters->cp_disto_alloc = 1;
539 }
540
541
542 static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
543 {
544         unsigned char *rect_uchar;
545         float *rect_float;
546         
547         unsigned int subsampling_dx = parameters->subsampling_dx;
548         unsigned int subsampling_dy = parameters->subsampling_dy;
549         
550         unsigned int i, i_next, numcomps, w, h, prec;
551         unsigned int y;
552         int *r, *g, *b, *a; /* matching 'opj_image_comp.data' type */
553         OPJ_COLOR_SPACE color_space;
554         opj_image_cmptparm_t cmptparm[4];   /* maximum of 4 components */
555         opj_image_t *image = NULL;
556         
557         img_fol_t img_fol; /* only needed for cinema presets */
558         memset(&img_fol, 0, sizeof(img_fol_t));
559         
560         if (ibuf->ftype & JP2_CINE) {
561                 
562                 if (ibuf->x == 4096 || ibuf->y == 2160)
563                         parameters->cp_cinema = CINEMA4K_24;
564                 else {
565                         if (ibuf->ftype & JP2_CINE_48FPS) {
566                                 parameters->cp_cinema = CINEMA2K_48;
567                         }
568                         else {
569                                 parameters->cp_cinema = CINEMA2K_24;
570                         }
571                 }
572                 if (parameters->cp_cinema) {
573                         img_fol.rates = (float *)MEM_mallocN(parameters->tcp_numlayers * sizeof(float), "jp2_rates");
574                         for (i = 0; i < parameters->tcp_numlayers; i++) {
575                                 img_fol.rates[i] = parameters->tcp_rates[i];
576                         }
577                         cinema_parameters(parameters);
578                 }
579                 
580                 color_space = CLRSPC_SYCC;
581                 prec = 12;
582                 numcomps = 3;
583         }
584         else { 
585                 /* Get settings from the imbuf */
586                 color_space = (ibuf->ftype & JP2_YCC) ? CLRSPC_SYCC : CLRSPC_SRGB;
587                 
588                 if (ibuf->ftype & JP2_16BIT) prec = 16;
589                 else if (ibuf->ftype & JP2_12BIT) prec = 12;
590                 else prec = 8;
591                 
592                 /* 32bit images == alpha channel */
593                 /* grayscale not supported yet */
594                 numcomps = (ibuf->planes == 32) ? 4 : 3;
595         }
596         
597         w = ibuf->x;
598         h = ibuf->y;
599         
600         
601         /* initialize image components */
602         memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
603         for (i = 0; i < numcomps; i++) {
604                 cmptparm[i].prec = prec;
605                 cmptparm[i].bpp = prec;
606                 cmptparm[i].sgnd = 0;
607                 cmptparm[i].dx = subsampling_dx;
608                 cmptparm[i].dy = subsampling_dy;
609                 cmptparm[i].w = w;
610                 cmptparm[i].h = h;
611         }
612         /* create the image */
613         image = opj_image_create(numcomps, &cmptparm[0], color_space);
614         if (!image) {
615                 printf("Error: opj_image_create() failed\n");
616                 return NULL;
617         }
618
619         /* set image offset and reference grid */
620         image->x0 = parameters->image_offset_x0;
621         image->y0 = parameters->image_offset_y0;
622         image->x1 = image->x0 + (w - 1) * subsampling_dx + 1 + image->x0;
623         image->y1 = image->y0 + (h - 1) * subsampling_dy + 1 + image->y0;
624
625         /* set image data */
626         rect_uchar = (unsigned char *) ibuf->rect;
627         rect_float = ibuf->rect_float;
628         
629         /* set the destination channels */
630         r = image->comps[0].data;
631         g = image->comps[1].data;
632         b = image->comps[2].data;
633         a = (numcomps == 4) ? image->comps[3].data : NULL;
634
635         if (rect_float && rect_uchar && prec == 8) {
636                 /* No need to use the floating point buffer, just write the 8 bits from the char buffer */
637                 rect_float = NULL;
638         }
639         
640         if (rect_float) {
641                 switch (prec) {
642                         case 8: /* Convert blenders float color channels to 8, 12 or 16bit ints */
643                                 if (numcomps == 4) {
644                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB) {
645                                                 PIXEL_LOOPER_BEGIN(rect_float)
646                                                 {
647                                                         r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[0]));
648                                                         g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[1]));
649                                                         b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[2]));
650                                                         a[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[3]);
651                                                 }
652                                                 PIXEL_LOOPER_END;
653                                         }
654                                         else {
655                                                 PIXEL_LOOPER_BEGIN(rect_float)
656                                                 {
657                                                         r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[0]);
658                                                         g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[1]);
659                                                         b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[2]);
660                                                         a[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[3]);
661                                                 }
662                                                 PIXEL_LOOPER_END;
663                                         }
664                                 }
665                                 else {
666                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB) {
667                                                 PIXEL_LOOPER_BEGIN(rect_float)
668                                                 {
669                                                         r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[0]));
670                                                         g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[1]));
671                                                         b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[2]));
672                                                 }
673                                                 PIXEL_LOOPER_END;
674                                         }
675                                         else {
676                                                 PIXEL_LOOPER_BEGIN(rect_float)
677                                                 {
678                                                         r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[0]);
679                                                         g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[1]);
680                                                         b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[2]);
681                                                 }
682                                                 PIXEL_LOOPER_END;
683                                         }
684                                 }
685                                 break;
686                         
687                         case 12:
688                                 if (numcomps == 4) {
689                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB) {
690                                                 PIXEL_LOOPER_BEGIN(rect_float)
691                                                 {
692                                                         r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[0]));
693                                                         g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[1]));
694                                                         b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[2]));
695                                                         a[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[3]);
696                                                 }
697                                                 PIXEL_LOOPER_END;
698                                         }
699                                         else {
700                                                 PIXEL_LOOPER_BEGIN(rect_float)
701                                                 {
702                                                         r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[0]);
703                                                         g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[1]);
704                                                         b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[2]);
705                                                         a[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[3]);
706                                                 }
707                                                 PIXEL_LOOPER_END;
708                                         }
709                                 }
710                                 else {
711                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB) {
712                                                 PIXEL_LOOPER_BEGIN(rect_float)
713                                                 {
714                                                         r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[0]));
715                                                         g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[1]));
716                                                         b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[2]));
717                                                 }
718                                                 PIXEL_LOOPER_END;
719                                         }
720                                         else {
721                                                 PIXEL_LOOPER_BEGIN(rect_float)
722                                                 {
723                                                         r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[0]);
724                                                         g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[1]);
725                                                         b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[2]);
726                                                 }
727                                                 PIXEL_LOOPER_END;
728                                         }
729                                 }
730                                 break;
731
732                         case 16:
733                                 if (numcomps == 4) {
734                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB) {
735                                                 PIXEL_LOOPER_BEGIN(rect_float)
736                                                 {
737                                                         r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[0]));
738                                                         g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[1]));
739                                                         b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[2]));
740                                                         a[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[3]);
741                                                 }
742                                                 PIXEL_LOOPER_END;
743                                         }
744                                         else {
745                                                 PIXEL_LOOPER_BEGIN(rect_float)
746                                                 {
747                                                         r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[0]);
748                                                         g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[1]);
749                                                         b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[2]);
750                                                         a[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[3]);
751                                                 }
752                                                 PIXEL_LOOPER_END;
753                                         }
754                                 }
755                                 else {
756                                         if (ibuf->profile == IB_PROFILE_LINEAR_RGB) {
757                                                 PIXEL_LOOPER_BEGIN(rect_float)
758                                                 {
759                                                         r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[0]));
760                                                         g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[1]));
761                                                         b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[2]));
762                                                 }
763                                                 PIXEL_LOOPER_END;
764                                         }
765                                         else {
766                                                 PIXEL_LOOPER_BEGIN(rect_float)
767                                                 {
768                                                         r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[0]);
769                                                         g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[1]);
770                                                         b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[2]);
771                                                 }
772                                                 PIXEL_LOOPER_END;
773                                         }
774                                 }
775                                 break;
776                 }
777         }
778         else {
779                 /* just use rect*/
780                 switch (prec) {
781                         case 8:
782                                 if (numcomps == 4) {
783                                         PIXEL_LOOPER_BEGIN(rect_uchar)
784                                         {
785                                                 r[i] = rect_uchar[0];
786                                                 g[i] = rect_uchar[1];
787                                                 b[i] = rect_uchar[2];
788                                                 a[i] = rect_uchar[3];
789                                         }
790                                         PIXEL_LOOPER_END;
791                                 }
792                                 else {
793                                         PIXEL_LOOPER_BEGIN(rect_uchar)
794                                         {
795                                                 r[i] = rect_uchar[0];
796                                                 g[i] = rect_uchar[1];
797                                                 b[i] = rect_uchar[2];
798                                         }
799                                         PIXEL_LOOPER_END;
800                                 }
801                                 break;
802                         
803                         case 12: /* Up Sampling, a bit pointless but best write the bit depth requested */
804                                 if (numcomps == 4) {
805                                         PIXEL_LOOPER_BEGIN(rect_uchar)
806                                         {
807                                                 r[i] = UPSAMPLE_8_TO_12(rect_uchar[0]);
808                                                 g[i] = UPSAMPLE_8_TO_12(rect_uchar[1]);
809                                                 b[i] = UPSAMPLE_8_TO_12(rect_uchar[2]);
810                                                 a[i] = UPSAMPLE_8_TO_12(rect_uchar[3]);
811                                         }
812                                         PIXEL_LOOPER_END;
813                                 }
814                                 else {
815                                         PIXEL_LOOPER_BEGIN(rect_uchar)
816                                         {
817                                                 r[i] = UPSAMPLE_8_TO_12(rect_uchar[0]);
818                                                 g[i] = UPSAMPLE_8_TO_12(rect_uchar[1]);
819                                                 b[i] = UPSAMPLE_8_TO_12(rect_uchar[2]);
820                                         }
821                                         PIXEL_LOOPER_END;
822                                 }
823                                 break;
824
825                         case 16:
826                                 if (numcomps == 4) {
827                                         PIXEL_LOOPER_BEGIN(rect_uchar)
828                                         {
829                                                 r[i] = UPSAMPLE_8_TO_16(rect_uchar[0]);
830                                                 g[i] = UPSAMPLE_8_TO_16(rect_uchar[1]);
831                                                 b[i] = UPSAMPLE_8_TO_16(rect_uchar[2]);
832                                                 a[i] = UPSAMPLE_8_TO_16(rect_uchar[3]);
833                                         }
834                                         PIXEL_LOOPER_END;
835                                 }
836                                 else {
837                                         PIXEL_LOOPER_BEGIN(rect_uchar)
838                                         {
839                                                 r[i] = UPSAMPLE_8_TO_16(rect_uchar[0]);
840                                                 g[i] = UPSAMPLE_8_TO_16(rect_uchar[1]);
841                                                 b[i] = UPSAMPLE_8_TO_16(rect_uchar[2]);
842                                         }
843                                         PIXEL_LOOPER_END;
844                                 }
845                                 break;
846                 }
847         }
848         
849         /* Decide if MCT should be used */
850         parameters->tcp_mct = image->numcomps == 3 ? 1 : 0;
851         
852         if (parameters->cp_cinema) {
853                 cinema_setup_encoder(parameters, image, &img_fol);
854         }
855         
856         if (img_fol.rates)
857                 MEM_freeN(img_fol.rates);
858         
859         return image;
860 }
861
862
863 /* Found write info at http://users.ece.gatech.edu/~slabaugh/personal/c/bitmapUnix.c */
864 int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags)
865 {
866         int quality = ibuf->ftype & 0xff;
867         
868         int bSuccess;
869         opj_cparameters_t parameters;   /* compression parameters */
870         opj_event_mgr_t event_mgr;      /* event manager */
871         opj_image_t *image = NULL;
872         
873         (void)flags; /* unused */
874         
875         /*
876          * configure the event callbacks (not required)
877          * setting of each callback is optional
878          */
879         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
880         event_mgr.error_handler = error_callback;
881         event_mgr.warning_handler = warning_callback;
882         event_mgr.info_handler = info_callback;
883         
884         /* set encoding parameters to default values */
885         opj_set_default_encoder_parameters(&parameters);
886         
887         /* compression ratio */
888         /* invert range, from 10-100, 100-1
889          * where jpeg see's 1 and highest quality (lossless) and 100 is very low quality*/
890         parameters.tcp_rates[0] = ((100 - quality) / 90.0f * 99.0f) + 1;
891
892         
893         parameters.tcp_numlayers = 1; /* only one resolution */
894         parameters.cp_disto_alloc = 1;
895
896         image = ibuftoimage(ibuf, &parameters);
897         
898         
899         {   /* JP2 format output */
900                 int codestream_length;
901                 opj_cio_t *cio = NULL;
902                 FILE *f = NULL;
903
904                 /* get a JP2 compressor handle */
905                 opj_cinfo_t *cinfo = opj_create_compress(CODEC_JP2);
906
907                 /* catch events using our callbacks and give a local context */
908                 opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
909
910                 /* setup the encoder parameters using the current image and using user parameters */
911                 opj_setup_encoder(cinfo, &parameters, image);
912
913                 /* open a byte stream for writing */
914                 /* allocate memory for all tiles */
915                 cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
916
917                 /* encode the image */
918                 bSuccess = opj_encode(cinfo, cio, image, NULL); /* last arg used to be parameters.index but this deprecated */
919                 
920                 if (!bSuccess) {
921                         opj_cio_close(cio);
922                         fprintf(stderr, "failed to encode image\n");
923                         return 0;
924                 }
925                 codestream_length = cio_tell(cio);
926
927                 /* write the buffer to disk */
928                 f = BLI_fopen(name, "wb");
929                 
930                 if (!f) {
931                         fprintf(stderr, "failed to open %s for writing\n", name);
932                         return 1;
933                 }
934                 fwrite(cio->buffer, 1, codestream_length, f);
935                 fclose(f);
936                 fprintf(stderr, "Generated outfile %s\n", name);
937                 /* close and free the byte stream */
938                 opj_cio_close(cio);
939                 
940                 /* free remaining compression structures */
941                 opj_destroy_compress(cinfo);
942         }
943
944         /* free image data */
945         opj_image_destroy(image);
946         
947         return 1;
948 }