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