Color Management, Stage 2: Switch color pipeline to use OpenColorIO
[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
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 imager is used
391  * - In 2K, for Flat (1.85:1) presentation 1998x1080 pixels of the imager 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
548 static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
549 {
550         unsigned char *rect_uchar;
551         float *rect_float;
552         
553         unsigned int subsampling_dx = parameters->subsampling_dx;
554         unsigned int subsampling_dy = parameters->subsampling_dy;
555         
556         unsigned int i, i_next, numcomps, w, h, prec;
557         unsigned int y;
558         int *r, *g, *b, *a; /* matching 'opj_image_comp.data' type */
559         OPJ_COLOR_SPACE color_space;
560         opj_image_cmptparm_t cmptparm[4];   /* maximum of 4 components */
561         opj_image_t *image = NULL;
562         
563         img_fol_t img_fol; /* only needed for cinema presets */
564         memset(&img_fol, 0, sizeof(img_fol_t));
565         
566         if (ibuf->ftype & JP2_CINE) {
567                 
568                 if (ibuf->x == 4096 || ibuf->y == 2160)
569                         parameters->cp_cinema = CINEMA4K_24;
570                 else {
571                         if (ibuf->ftype & JP2_CINE_48FPS) {
572                                 parameters->cp_cinema = CINEMA2K_48;
573                         }
574                         else {
575                                 parameters->cp_cinema = CINEMA2K_24;
576                         }
577                 }
578                 if (parameters->cp_cinema) {
579                         img_fol.rates = (float *)MEM_mallocN(parameters->tcp_numlayers * sizeof(float), "jp2_rates");
580                         for (i = 0; i < parameters->tcp_numlayers; i++) {
581                                 img_fol.rates[i] = parameters->tcp_rates[i];
582                         }
583                         cinema_parameters(parameters);
584                 }
585                 
586                 color_space = CLRSPC_SYCC;
587                 prec = 12;
588                 numcomps = 3;
589         }
590         else { 
591                 /* Get settings from the imbuf */
592                 color_space = (ibuf->ftype & JP2_YCC) ? CLRSPC_SYCC : CLRSPC_SRGB;
593                 
594                 if (ibuf->ftype & JP2_16BIT) prec = 16;
595                 else if (ibuf->ftype & JP2_12BIT) prec = 12;
596                 else prec = 8;
597                 
598                 /* 32bit images == alpha channel */
599                 /* grayscale not supported yet */
600                 numcomps = (ibuf->planes == 32) ? 4 : 3;
601         }
602         
603         w = ibuf->x;
604         h = ibuf->y;
605         
606         
607         /* initialize image components */
608         memset(&cmptparm, 0, 4 * sizeof(opj_image_cmptparm_t));
609         for (i = 0; i < numcomps; i++) {
610                 cmptparm[i].prec = prec;
611                 cmptparm[i].bpp = prec;
612                 cmptparm[i].sgnd = 0;
613                 cmptparm[i].dx = subsampling_dx;
614                 cmptparm[i].dy = subsampling_dy;
615                 cmptparm[i].w = w;
616                 cmptparm[i].h = h;
617         }
618         /* create the image */
619         image = opj_image_create(numcomps, &cmptparm[0], color_space);
620         if (!image) {
621                 printf("Error: opj_image_create() failed\n");
622                 return NULL;
623         }
624
625         /* set image offset and reference grid */
626         image->x0 = parameters->image_offset_x0;
627         image->y0 = parameters->image_offset_y0;
628         image->x1 = image->x0 + (w - 1) * subsampling_dx + 1 + image->x0;
629         image->y1 = image->y0 + (h - 1) * subsampling_dy + 1 + image->y0;
630
631         /* set image data */
632         rect_uchar = (unsigned char *) ibuf->rect;
633         rect_float = ibuf->rect_float;
634         
635         /* set the destination channels */
636         r = image->comps[0].data;
637         g = image->comps[1].data;
638         b = image->comps[2].data;
639         a = (numcomps == 4) ? image->comps[3].data : NULL;
640
641         if (rect_float && rect_uchar && prec == 8) {
642                 /* No need to use the floating point buffer, just write the 8 bits from the char buffer */
643                 rect_float = NULL;
644         }
645         
646         if (rect_float) {
647                 switch (prec) {
648                         case 8: /* Convert blenders float color channels to 8, 12 or 16bit ints */
649                                 if (numcomps == 4) {
650                                         PIXEL_LOOPER_BEGIN(rect_float)
651                                         {
652                                                 r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[0]));
653                                                 g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[1]));
654                                                 b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[2]));
655                                                 a[i] = DOWNSAMPLE_FLOAT_TO_8BIT(rect_float[3]);
656                                         }
657                                         PIXEL_LOOPER_END;
658                                 }
659                                 else {
660                                         PIXEL_LOOPER_BEGIN(rect_float)
661                                         {
662                                                 r[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[0]));
663                                                 g[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[1]));
664                                                 b[i] = DOWNSAMPLE_FLOAT_TO_8BIT(linearrgb_to_srgb(rect_float[2]));
665                                         }
666                                         PIXEL_LOOPER_END;
667                                 }
668                                 break;
669                         
670                         case 12:
671                                 if (numcomps == 4) {
672                                         PIXEL_LOOPER_BEGIN(rect_float)
673                                         {
674                                                 r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[0]));
675                                                 g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[1]));
676                                                 b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[2]));
677                                                 a[i] = DOWNSAMPLE_FLOAT_TO_12BIT(rect_float[3]);
678                                         }
679                                         PIXEL_LOOPER_END;
680                                 }
681                                 else {
682                                         PIXEL_LOOPER_BEGIN(rect_float)
683                                         {
684                                                 r[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[0]));
685                                                 g[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[1]));
686                                                 b[i] = DOWNSAMPLE_FLOAT_TO_12BIT(linearrgb_to_srgb(rect_float[2]));
687                                         }
688                                         PIXEL_LOOPER_END;
689                                 }
690                                 break;
691
692                         case 16:
693                                 if (numcomps == 4) {
694                                         PIXEL_LOOPER_BEGIN(rect_float)
695                                         {
696                                                 r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[0]));
697                                                 g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[1]));
698                                                 b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[2]));
699                                                 a[i] = DOWNSAMPLE_FLOAT_TO_16BIT(rect_float[3]);
700                                         }
701                                         PIXEL_LOOPER_END;
702                                 }
703                                 else {
704                                         PIXEL_LOOPER_BEGIN(rect_float)
705                                         {
706                                                 r[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[0]));
707                                                 g[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[1]));
708                                                 b[i] = DOWNSAMPLE_FLOAT_TO_16BIT(linearrgb_to_srgb(rect_float[2]));
709                                         }
710                                         PIXEL_LOOPER_END;
711                                 }
712                                 break;
713                 }
714         }
715         else {
716                 /* just use rect*/
717                 switch (prec) {
718                         case 8:
719                                 if (numcomps == 4) {
720                                         PIXEL_LOOPER_BEGIN(rect_uchar)
721                                         {
722                                                 r[i] = rect_uchar[0];
723                                                 g[i] = rect_uchar[1];
724                                                 b[i] = rect_uchar[2];
725                                                 a[i] = rect_uchar[3];
726                                         }
727                                         PIXEL_LOOPER_END;
728                                 }
729                                 else {
730                                         PIXEL_LOOPER_BEGIN(rect_uchar)
731                                         {
732                                                 r[i] = rect_uchar[0];
733                                                 g[i] = rect_uchar[1];
734                                                 b[i] = rect_uchar[2];
735                                         }
736                                         PIXEL_LOOPER_END;
737                                 }
738                                 break;
739                         
740                         case 12: /* Up Sampling, a bit pointless but best write the bit depth requested */
741                                 if (numcomps == 4) {
742                                         PIXEL_LOOPER_BEGIN(rect_uchar)
743                                         {
744                                                 r[i] = UPSAMPLE_8_TO_12(rect_uchar[0]);
745                                                 g[i] = UPSAMPLE_8_TO_12(rect_uchar[1]);
746                                                 b[i] = UPSAMPLE_8_TO_12(rect_uchar[2]);
747                                                 a[i] = UPSAMPLE_8_TO_12(rect_uchar[3]);
748                                         }
749                                         PIXEL_LOOPER_END;
750                                 }
751                                 else {
752                                         PIXEL_LOOPER_BEGIN(rect_uchar)
753                                         {
754                                                 r[i] = UPSAMPLE_8_TO_12(rect_uchar[0]);
755                                                 g[i] = UPSAMPLE_8_TO_12(rect_uchar[1]);
756                                                 b[i] = UPSAMPLE_8_TO_12(rect_uchar[2]);
757                                         }
758                                         PIXEL_LOOPER_END;
759                                 }
760                                 break;
761
762                         case 16:
763                                 if (numcomps == 4) {
764                                         PIXEL_LOOPER_BEGIN(rect_uchar)
765                                         {
766                                                 r[i] = UPSAMPLE_8_TO_16(rect_uchar[0]);
767                                                 g[i] = UPSAMPLE_8_TO_16(rect_uchar[1]);
768                                                 b[i] = UPSAMPLE_8_TO_16(rect_uchar[2]);
769                                                 a[i] = UPSAMPLE_8_TO_16(rect_uchar[3]);
770                                         }
771                                         PIXEL_LOOPER_END;
772                                 }
773                                 else {
774                                         PIXEL_LOOPER_BEGIN(rect_uchar)
775                                         {
776                                                 r[i] = UPSAMPLE_8_TO_16(rect_uchar[0]);
777                                                 g[i] = UPSAMPLE_8_TO_16(rect_uchar[1]);
778                                                 b[i] = UPSAMPLE_8_TO_16(rect_uchar[2]);
779                                         }
780                                         PIXEL_LOOPER_END;
781                                 }
782                                 break;
783                 }
784         }
785         
786         /* Decide if MCT should be used */
787         parameters->tcp_mct = image->numcomps == 3 ? 1 : 0;
788         
789         if (parameters->cp_cinema) {
790                 cinema_setup_encoder(parameters, image, &img_fol);
791         }
792         
793         if (img_fol.rates)
794                 MEM_freeN(img_fol.rates);
795         
796         return image;
797 }
798
799
800 /* Found write info at http://users.ece.gatech.edu/~slabaugh/personal/c/bitmapUnix.c */
801 int imb_savejp2(struct ImBuf *ibuf, const char *name, int flags)
802 {
803         int quality = ibuf->ftype & 0xff;
804         
805         int bSuccess;
806         opj_cparameters_t parameters;   /* compression parameters */
807         opj_event_mgr_t event_mgr;      /* event manager */
808         opj_image_t *image = NULL;
809         
810         (void)flags; /* unused */
811         
812         /*
813          * configure the event callbacks (not required)
814          * setting of each callback is optional
815          */
816         memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
817         event_mgr.error_handler = error_callback;
818         event_mgr.warning_handler = warning_callback;
819         event_mgr.info_handler = info_callback;
820         
821         /* set encoding parameters to default values */
822         opj_set_default_encoder_parameters(&parameters);
823         
824         /* compression ratio */
825         /* invert range, from 10-100, 100-1
826          * where jpeg see's 1 and highest quality (lossless) and 100 is very low quality*/
827         parameters.tcp_rates[0] = ((100 - quality) / 90.0f * 99.0f) + 1;
828
829         
830         parameters.tcp_numlayers = 1; /* only one resolution */
831         parameters.cp_disto_alloc = 1;
832
833         image = ibuftoimage(ibuf, &parameters);
834         
835         
836         {   /* JP2 format output */
837                 int codestream_length;
838                 opj_cio_t *cio = NULL;
839                 FILE *f = NULL;
840
841                 /* get a JP2 compressor handle */
842                 opj_cinfo_t *cinfo = opj_create_compress(CODEC_JP2);
843
844                 /* catch events using our callbacks and give a local context */
845                 opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
846
847                 /* setup the encoder parameters using the current image and using user parameters */
848                 opj_setup_encoder(cinfo, &parameters, image);
849
850                 /* open a byte stream for writing */
851                 /* allocate memory for all tiles */
852                 cio = opj_cio_open((opj_common_ptr)cinfo, NULL, 0);
853
854                 /* encode the image */
855                 bSuccess = opj_encode(cinfo, cio, image, NULL); /* last arg used to be parameters.index but this deprecated */
856                 
857                 if (!bSuccess) {
858                         opj_cio_close(cio);
859                         fprintf(stderr, "failed to encode image\n");
860                         return 0;
861                 }
862                 codestream_length = cio_tell(cio);
863
864                 /* write the buffer to disk */
865                 f = BLI_fopen(name, "wb");
866                 
867                 if (!f) {
868                         fprintf(stderr, "failed to open %s for writing\n", name);
869                         return 1;
870                 }
871                 fwrite(cio->buffer, 1, codestream_length, f);
872                 fclose(f);
873                 fprintf(stderr, "Generated outfile %s\n", name);
874                 /* close and free the byte stream */
875                 opj_cio_close(cio);
876                 
877                 /* free remaining compression structures */
878                 opj_destroy_compress(cinfo);
879         }
880
881         /* free image data */
882         opj_image_destroy(image);
883         
884         return 1;
885 }