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