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