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