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