Merge pull request #647 from stweil/master
[openjpeg.git] / src / lib / openmj2 / jp2.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses 
3  * BSD License, included below. This software may be subject to other third 
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux 
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * Copyright (c) 2010-2011, Kaori Hagihara
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
27  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 #include "opj_includes.h"
39
40 /** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
41 /*@{*/
42
43 /** @name Local static functions */
44 /*@{*/
45
46 /**
47 Read box headers
48 @param cinfo Codec context info
49 @param cio Input stream
50 @param box
51 @return Returns true if successful, returns false otherwise
52 */
53 static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box);
54 /*static void jp2_write_url(opj_cio_t *cio, char *Idx_file);*/
55 /**
56 Read the IHDR box - Image Header box
57 @param jp2 JP2 handle
58 @param cio Input buffer stream
59 @return Returns true if successful, returns false otherwise
60 */
61 static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio);
62 static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio);
63 static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio);
64 static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio);
65 static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio);
66 /**
67 Write the FTYP box - File type box
68 @param jp2 JP2 handle
69 @param cio Output buffer stream
70 */
71 static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio);
72 /**
73 Read the FTYP box - File type box
74 @param jp2 JP2 handle
75 @param cio Input buffer stream
76 @return Returns true if successful, returns false otherwise
77 */
78 static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio);
79 static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info);
80 static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset);
81 static void jp2_write_jp(opj_cio_t *cio);
82 /**
83 Read the JP box - JPEG 2000 signature
84 @param jp2 JP2 handle
85 @param cio Input buffer stream
86 @return Returns true if successful, returns false otherwise
87 */
88 static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio);
89 /**
90 Decode the structure of a JP2 file
91 @param jp2 JP2 handle
92 @param cio Input buffer stream
93 @param color Collector for profile, cdef and pclr data
94 @return Returns true if successful, returns false otherwise
95 */
96 static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
97         opj_jp2_color_t *color);
98 /**
99 Apply collected palette data
100 @param color Collector for profile, cdef and pclr data
101 @param image 
102 */
103 static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_common_ptr cinfo);
104 /**
105 Collect palette data
106 @param jp2 JP2 handle
107 @param cio Input buffer stream
108 @param box
109 @param color Collector for profile, cdef and pclr data
110 @return Returns true if successful, returns false otherwise
111 */
112 static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio,
113     opj_jp2_box_t *box, opj_jp2_color_t *color);
114 /**
115 Collect component mapping data
116 @param jp2 JP2 handle
117 @param cio Input buffer stream
118 @param box
119 @param color Collector for profile, cdef and pclr data
120 @return Returns true if successful, returns false otherwise
121 */
122 static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio,
123     opj_jp2_box_t *box, opj_jp2_color_t *color);
124 /**
125 Collect colour specification data
126 @param jp2 JP2 handle
127 @param cio Input buffer stream
128 @param box
129 @param color Collector for profile, cdef and pclr data
130 @return Returns true if successful, returns false otherwise
131 */
132 static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio,
133     opj_jp2_box_t *box, opj_jp2_color_t *color);
134 /*@}*/
135
136 /*@}*/
137
138 /* ----------------------------------------------------------------------- */
139
140 static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box) {
141         box->init_pos = cio_tell(cio);
142         box->length = cio_read(cio, 4);
143         box->type = cio_read(cio, 4);
144         if (box->length == 1) {
145                 if (cio_read(cio, 4) != 0) {
146                         opj_event_msg(cinfo, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
147                         return OPJ_FALSE;
148                 }
149                 box->length = cio_read(cio, 4);
150                 if (box->length == 0) 
151                         box->length = cio_numbytesleft(cio) + 12;
152         }
153         else if (box->length == 0) {
154                 box->length = cio_numbytesleft(cio) + 8;
155         }
156         if (box->length < 0) {
157                 opj_event_msg(cinfo, EVT_ERROR, "Integer overflow in box->length\n");
158                 return OPJ_FALSE; /* TODO: actually check jp2_read_boxhdr's return value */
159         }
160         
161         return OPJ_TRUE;
162 }
163
164 #if 0
165 static void jp2_write_url(opj_cio_t *cio, char *Idx_file) {
166         unsigned int i;
167         opj_jp2_box_t box;
168
169         box.init_pos = cio_tell(cio);
170         cio_skip(cio, 4);
171         cio_write(cio, JP2_URL, 4);     /* DBTL */
172         cio_write(cio, 0, 1);           /* VERS */
173         cio_write(cio, 0, 3);           /* FLAG */
174
175         if(Idx_file) {
176                 for (i = 0; i < strlen(Idx_file); i++) {
177                         cio_write(cio, Idx_file[i], 1);
178                 }
179         }
180
181         box.length = cio_tell(cio) - box.init_pos;
182         cio_seek(cio, box.init_pos);
183         cio_write(cio, box.length, 4);  /* L */
184         cio_seek(cio, box.init_pos + box.length);
185 }
186 #endif
187
188 static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
189         opj_jp2_box_t box;
190
191         opj_common_ptr cinfo = jp2->cinfo;
192
193   if(jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
194     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
195     return OPJ_FALSE;
196   }
197         if (JP2_IHDR != box.type) {
198                 opj_event_msg(cinfo, EVT_ERROR, "Expected IHDR Marker\n");
199                 return OPJ_FALSE;
200         }
201
202         jp2->h = cio_read(cio, 4);                      /* HEIGHT */
203         jp2->w = cio_read(cio, 4);                      /* WIDTH */
204         jp2->numcomps = cio_read(cio, 2);       /* NC */
205         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
206
207         jp2->bpc = cio_read(cio, 1);            /* BPC */
208
209         jp2->C = cio_read(cio, 1);                      /* C */
210         jp2->UnkC = cio_read(cio, 1);           /* UnkC */
211         jp2->IPR = cio_read(cio, 1);            /* IPR */
212
213         if (cio_tell(cio) - box.init_pos != box.length) {
214                 opj_event_msg(cinfo, EVT_ERROR, "Error with IHDR Box\n");
215                 return OPJ_FALSE;
216         }
217
218         return OPJ_TRUE;
219 }
220
221 static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
222         opj_jp2_box_t box;
223
224         box.init_pos = cio_tell(cio);
225         cio_skip(cio, 4);
226         cio_write(cio, JP2_IHDR, 4);            /* IHDR */
227
228         cio_write(cio, jp2->h, 4);                      /* HEIGHT */
229         cio_write(cio, jp2->w, 4);                      /* WIDTH */
230         cio_write(cio, jp2->numcomps, 2);       /* NC */
231
232         cio_write(cio, jp2->bpc, 1);            /* BPC */
233
234         cio_write(cio, jp2->C, 1);                      /* C : Always 7 */
235         cio_write(cio, jp2->UnkC, 1);           /* UnkC, colorspace unknown */
236         cio_write(cio, jp2->IPR, 1);            /* IPR, no intellectual property */
237
238         box.length = cio_tell(cio) - box.init_pos;
239         cio_seek(cio, box.init_pos);
240         cio_write(cio, box.length, 4);  /* L */
241         cio_seek(cio, box.init_pos + box.length);
242 }
243
244 static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
245         unsigned int i;
246         opj_jp2_box_t box;
247
248         box.init_pos = cio_tell(cio);
249         cio_skip(cio, 4);
250         cio_write(cio, JP2_BPCC, 4);    /* BPCC */
251
252         for (i = 0; i < jp2->numcomps; i++) {
253                 cio_write(cio, jp2->comps[i].bpcc, 1);
254         }
255
256         box.length = cio_tell(cio) - box.init_pos;
257         cio_seek(cio, box.init_pos);
258         cio_write(cio, box.length, 4);  /* L */
259         cio_seek(cio, box.init_pos + box.length);
260 }
261
262
263 static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
264         unsigned int i;
265         opj_jp2_box_t box;
266
267         opj_common_ptr cinfo = jp2->cinfo;
268
269   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
270     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
271     return OPJ_FALSE;
272   }
273         if (JP2_BPCC != box.type) {
274                 opj_event_msg(cinfo, EVT_ERROR, "Expected BPCC Marker\n");
275                 return OPJ_FALSE;
276         }
277
278         for (i = 0; i < jp2->numcomps; i++) {
279                 jp2->comps[i].bpcc = cio_read(cio, 1);
280         }
281
282         if (cio_tell(cio) - box.init_pos != box.length) {
283                 opj_event_msg(cinfo, EVT_ERROR, "Error with BPCC Box\n");
284                 return OPJ_FALSE;
285         }
286
287         return OPJ_TRUE;
288 }
289
290 static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio) {
291         opj_jp2_box_t box;
292
293         box.init_pos = cio_tell(cio);
294         cio_skip(cio, 4);
295         cio_write(cio, JP2_COLR, 4);            /* COLR */
296
297         cio_write(cio, jp2->meth, 1);           /* METH */
298         cio_write(cio, jp2->precedence, 1);     /* PRECEDENCE */
299         cio_write(cio, jp2->approx, 1);         /* APPROX */
300
301         if(jp2->meth == 2)
302          jp2->enumcs = 0;
303
304         cio_write(cio, jp2->enumcs, 4); /* EnumCS */
305
306         box.length = cio_tell(cio) - box.init_pos;
307         cio_seek(cio, box.init_pos);
308         cio_write(cio, box.length, 4);  /* L */
309         cio_seek(cio, box.init_pos + box.length);
310 }
311
312 static void jp2_free_pclr(opj_jp2_color_t *color)
313 {
314     opj_free(color->jp2_pclr->channel_sign);
315     opj_free(color->jp2_pclr->channel_size);
316     opj_free(color->jp2_pclr->entries);
317
318         if(color->jp2_pclr->cmap) opj_free(color->jp2_pclr->cmap);
319
320     opj_free(color->jp2_pclr); color->jp2_pclr = NULL;
321 }
322
323 static void free_color_data(opj_jp2_color_t *color)
324 {
325         if(color->jp2_pclr)
326    {
327         jp2_free_pclr(color);
328    }
329         if(color->jp2_cdef) 
330    {
331         if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info);
332         opj_free(color->jp2_cdef);
333    }
334         if(color->icc_profile_buf) opj_free(color->icc_profile_buf);
335 }
336
337 static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_common_ptr cinfo)
338 {
339         opj_image_comp_t *old_comps, *new_comps;
340         unsigned char *channel_size, *channel_sign;
341         unsigned int *entries;
342         opj_jp2_cmap_comp_t *cmap;
343         int *src, *dst;
344         unsigned int j, max;
345         unsigned short i, nr_channels, cmp, pcol;
346         int k, top_k;
347
348         channel_size = color->jp2_pclr->channel_size;
349         channel_sign = color->jp2_pclr->channel_sign;
350         entries = color->jp2_pclr->entries;
351         cmap = color->jp2_pclr->cmap;
352         nr_channels = color->jp2_pclr->nr_channels;
353
354         old_comps = image->comps;
355         new_comps = (opj_image_comp_t*)
356          opj_malloc(nr_channels * sizeof(opj_image_comp_t));
357
358         for(i = 0; i < nr_channels; ++i)
359    {
360         pcol = cmap[i].pcol; cmp = cmap[i].cmp;
361
362   if( pcol < nr_channels )
363     new_comps[pcol] = old_comps[cmp];
364   else
365     {
366     opj_event_msg(cinfo, EVT_ERROR, "Error with pcol value %d (max: %d). skipping\n", pcol, nr_channels);
367     continue;
368     }
369
370         if(cmap[i].mtyp == 0) /* Direct use */
371   {
372         old_comps[cmp].data = NULL; continue;
373   }
374 /* Palette mapping: */
375         new_comps[pcol].data = (int*)
376          opj_malloc(old_comps[cmp].w * old_comps[cmp].h * sizeof(int));
377         new_comps[pcol].prec = channel_size[i];
378         new_comps[pcol].sgnd = channel_sign[i];
379    }
380         top_k = color->jp2_pclr->nr_entries - 1;
381
382         for(i = 0; i < nr_channels; ++i)
383    {
384 /* Direct use: */
385         if(cmap[i].mtyp == 0) continue;
386
387 /* Palette mapping: */
388         cmp = cmap[i].cmp; pcol = cmap[i].pcol;
389         src = old_comps[cmp].data; 
390         dst = new_comps[pcol].data;
391         max = new_comps[pcol].w * new_comps[pcol].h;
392
393         for(j = 0; j < max; ++j)
394   {
395 /* The index */
396         if((k = src[j]) < 0) k = 0; else if(k > top_k) k = top_k;
397 /* The colour */
398         dst[j] = entries[k * nr_channels + pcol];
399   }
400    }
401         max = image->numcomps;
402         for(i = 0; i < max; ++i)
403    {
404         if(old_comps[i].data) opj_free(old_comps[i].data);
405    }
406         opj_free(old_comps);
407         image->comps = new_comps;
408         image->numcomps = nr_channels;
409
410         jp2_free_pclr(color);
411
412 }/* apply_pclr() */
413
414 static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio,
415         opj_jp2_box_t *box, opj_jp2_color_t *color)
416 {
417         opj_jp2_pclr_t *jp2_pclr;
418         unsigned char *channel_size, *channel_sign;
419         unsigned int *entries;
420         unsigned short nr_entries, nr_channels;
421         unsigned short i, j;
422         unsigned char uc;
423
424         OPJ_ARG_NOT_USED(box);
425         OPJ_ARG_NOT_USED(jp2);
426
427 /* Part 1, I.5.3.4: 'There shall be at most one Palette box inside
428  * a JP2 Header box' :
429 */
430         if(color->jp2_pclr) return OPJ_FALSE;
431
432         nr_entries = (unsigned short)cio_read(cio, 2); /* NE */
433         nr_channels = (unsigned short)cio_read(cio, 1);/* NPC */
434
435         entries = (unsigned int*)
436          opj_malloc(nr_channels * nr_entries * sizeof(unsigned int));
437         channel_size = (unsigned char*)opj_malloc(nr_channels);
438         channel_sign = (unsigned char*)opj_malloc(nr_channels);
439
440         jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t));
441         jp2_pclr->channel_sign = channel_sign;
442         jp2_pclr->channel_size = channel_size;
443         jp2_pclr->entries = entries;
444         jp2_pclr->nr_entries = nr_entries;
445         jp2_pclr->nr_channels = nr_channels;
446         jp2_pclr->cmap = NULL;
447
448         color->jp2_pclr = jp2_pclr;
449
450         for(i = 0; i < nr_channels; ++i)
451    {
452         uc = cio_read(cio, 1); /* Bi */
453         channel_size[i] = (uc & 0x7f) + 1;
454         channel_sign[i] = (uc & 0x80)?1:0;
455    }
456
457         for(j = 0; j < nr_entries; ++j)
458    {
459         for(i = 0; i < nr_channels; ++i)
460   {
461 /* Cji */
462         *entries++ = cio_read(cio, (channel_size[i]+7)>>3);
463   }
464    }
465
466         return OPJ_TRUE;
467 }/* jp2_read_pclr() */
468
469 static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio,
470         opj_jp2_box_t *box, opj_jp2_color_t *color)
471 {
472         opj_jp2_cmap_comp_t *cmap;
473         unsigned short i, nr_channels;
474
475         OPJ_ARG_NOT_USED(box);
476         OPJ_ARG_NOT_USED(jp2);
477
478 /* Need nr_channels: */
479         if(color->jp2_pclr == NULL) return OPJ_FALSE;
480
481 /* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box
482  * inside a JP2 Header box' :
483 */
484         if(color->jp2_pclr->cmap) return OPJ_FALSE;
485
486         nr_channels = color->jp2_pclr->nr_channels;
487         cmap = (opj_jp2_cmap_comp_t*)
488          opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t));
489
490         for(i = 0; i < nr_channels; ++i)
491    {
492         cmap[i].cmp = (unsigned short)cio_read(cio, 2);
493         cmap[i].mtyp = cio_read(cio, 1);
494         cmap[i].pcol = cio_read(cio, 1);
495
496    }
497         color->jp2_pclr->cmap = cmap;
498
499         return OPJ_TRUE;
500 }/* jp2_read_cmap() */
501
502 static void jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color)
503 {
504         opj_jp2_cdef_info_t *info;
505         int color_space;
506         unsigned short i, n, cn, typ, asoc, acn;
507
508         color_space = image->color_space;
509         info = color->jp2_cdef->info;
510         n = color->jp2_cdef->n;
511
512         for(i = 0; i < n; ++i)
513    {
514 /* WATCH: acn = asoc - 1 ! */
515         if((asoc = info[i].asoc) == 0) continue;
516
517         cn = info[i].cn; typ = info[i].typ; acn = asoc - 1;
518
519         if(cn != acn)
520   {
521         opj_image_comp_t saved;
522
523         memcpy(&saved, &image->comps[cn], sizeof(opj_image_comp_t));
524         memcpy(&image->comps[cn], &image->comps[acn], sizeof(opj_image_comp_t));
525         memcpy(&image->comps[acn], &saved, sizeof(opj_image_comp_t));
526
527         info[i].asoc = cn + 1;
528         info[acn].asoc = info[acn].cn + 1;
529   }
530    }
531         if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info);
532
533         opj_free(color->jp2_cdef); color->jp2_cdef = NULL;
534
535 }/* jp2_apply_cdef() */
536
537 static opj_bool jp2_read_cdef(opj_jp2_t *jp2, opj_cio_t *cio,
538         opj_jp2_box_t *box, opj_jp2_color_t *color)
539 {
540         opj_jp2_cdef_info_t *info;
541         unsigned short i, n;
542
543         OPJ_ARG_NOT_USED(box);
544         OPJ_ARG_NOT_USED(jp2);
545
546 /* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box
547  * inside a JP2 Header box.' 
548 */
549         if(color->jp2_cdef) return OPJ_FALSE;
550
551         if((n = (unsigned short)cio_read(cio, 2)) == 0) return OPJ_FALSE; /* szukw000: FIXME */
552
553         info = (opj_jp2_cdef_info_t*)
554          opj_malloc(n * sizeof(opj_jp2_cdef_info_t));
555
556         color->jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
557         color->jp2_cdef->info = info;
558         color->jp2_cdef->n = n;
559
560         for(i = 0; i < n; ++i)
561    {
562         info[i].cn = (unsigned short)cio_read(cio, 2);
563         info[i].typ = (unsigned short)cio_read(cio, 2);
564         info[i].asoc = (unsigned short)cio_read(cio, 2);
565
566    }
567         return OPJ_TRUE;
568 }/* jp2_read_cdef() */
569
570 static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio,
571         opj_jp2_box_t *box, opj_jp2_color_t *color) 
572 {
573         int skip_len;
574     opj_common_ptr cinfo;
575
576 /* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour
577  * Specification boxes after the first.' 
578 */
579         if(color->jp2_has_colr) return OPJ_FALSE;
580
581         cinfo = jp2->cinfo;
582
583         jp2->meth = cio_read(cio, 1);           /* METH */
584         jp2->precedence = cio_read(cio, 1);     /* PRECEDENCE */
585         jp2->approx = cio_read(cio, 1);         /* APPROX */
586
587         if (jp2->meth == 1) 
588    {
589         jp2->enumcs = cio_read(cio, 4); /* EnumCS */
590    } 
591         else
592         if (jp2->meth == 2) 
593    {
594 /* skip PROFILE */
595         skip_len = box->init_pos + box->length - cio_tell(cio);
596         if (skip_len < 0) 
597   {
598         opj_event_msg(cinfo, EVT_ERROR, "Error with COLR box size\n");
599         return OPJ_FALSE;
600   }
601         if(skip_len > 0)
602   {
603         unsigned char *start;
604
605         start = cio_getbp(cio);
606         color->icc_profile_buf = (unsigned char*)opj_malloc(skip_len);
607         color->icc_profile_len = skip_len;
608
609         cio_skip(cio, box->init_pos + box->length - cio_tell(cio));
610
611         memcpy(color->icc_profile_buf, start, skip_len);
612   }
613    }
614
615         if (cio_tell(cio) - box->init_pos != box->length) 
616    {
617         opj_event_msg(cinfo, EVT_ERROR, "Error with COLR Box\n");
618         return OPJ_FALSE;
619    }
620         color->jp2_has_colr = 1;
621
622         return OPJ_TRUE;
623 }/* jp2_read_colr() */
624
625 opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color) 
626 {
627         opj_jp2_box_t box;
628         int jp2h_end;
629
630         opj_common_ptr cinfo = jp2->cinfo;
631
632   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
633   do {
634     if (JP2_JP2H != box.type) 
635       {
636       if (box.type == JP2_JP2C) 
637         {
638         opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
639         return OPJ_FALSE;
640         }
641           if (box.length <= 8) return OPJ_FALSE;
642       cio_skip(cio, box.length - 8);
643
644       if(cio->bp >= cio->end) return OPJ_FALSE;
645
646       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
647       }
648   } while(JP2_JP2H != box.type);
649
650         if (!jp2_read_ihdr(jp2, cio))
651                 return OPJ_FALSE;
652         jp2h_end = box.init_pos + box.length;
653
654   if (jp2->bpc == 255) 
655     {
656     if (!jp2_read_bpcc(jp2, cio))
657       return OPJ_FALSE;
658     }
659   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
660
661   while(cio_tell(cio) < jp2h_end)
662     {
663     if(box.type == JP2_COLR)
664       {
665       if( !jp2_read_colr(jp2, cio, &box, color))
666         {
667         if (box.length <= 8) return OPJ_FALSE;
668         cio_seek(cio, box.init_pos + 8);
669         cio_skip(cio, box.length - 8);
670         }
671       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
672       continue;
673       }
674     if(box.type == JP2_CDEF && !jp2->ignore_pclr_cmap_cdef)
675       {
676       if( !jp2_read_cdef(jp2, cio, &box, color))
677         {
678         if (box.length <= 8) return OPJ_FALSE;
679         cio_seek(cio, box.init_pos + 8);
680         cio_skip(cio, box.length - 8);
681         }
682       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
683       continue;
684       }
685     if(box.type == JP2_PCLR && !jp2->ignore_pclr_cmap_cdef)
686       {
687       if( !jp2_read_pclr(jp2, cio, &box, color))
688         {
689         if (box.length <= 8) return OPJ_FALSE;
690         cio_seek(cio, box.init_pos + 8);
691         cio_skip(cio, box.length - 8);
692         }
693       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
694       continue;
695       }
696     if(box.type == JP2_CMAP && !jp2->ignore_pclr_cmap_cdef)
697       {
698       if( !jp2_read_cmap(jp2, cio, &box, color))
699         {
700         if (box.length <= 8) return OPJ_FALSE;
701         cio_seek(cio, box.init_pos + 8);
702         cio_skip(cio, box.length - 8);
703         }
704       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
705       continue;
706       }
707     if (box.length <= 8) return OPJ_FALSE;
708     cio_seek(cio, box.init_pos + 8);
709     cio_skip(cio, box.length - 8);
710     if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
711
712     }/* while(cio_tell(cio) < box_end) */
713
714   cio_seek(cio, jp2h_end);
715
716   /* Part 1, I.5.3.3 : 'must contain at least one' */
717   return (color->jp2_has_colr == 1);
718
719 }/* jp2_read_jp2h() */
720
721 opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, 
722         opj_codestream_info_t *cstr_info) 
723 {
724         opj_common_ptr cinfo;
725         opj_image_t *image = NULL;
726         opj_jp2_color_t color;
727
728         if(!jp2 || !cio) 
729    {
730         return NULL;
731    }
732         memset(&color, 0, sizeof(opj_jp2_color_t));
733         cinfo = jp2->cinfo;
734
735 /* JP2 decoding */
736         if(!jp2_read_struct(jp2, cio, &color)) 
737    {
738         free_color_data(&color);
739         opj_event_msg(cinfo, EVT_ERROR, "Failed to decode jp2 structure\n");
740         return NULL;
741    }
742
743 /* J2K decoding */
744         image = j2k_decode(jp2->j2k, cio, cstr_info);
745
746         if(!image) 
747    {
748         free_color_data(&color);
749         opj_event_msg(cinfo, EVT_ERROR, "Failed to decode J2K image\n");
750         return NULL;
751    }
752    
753     if (!jp2->ignore_pclr_cmap_cdef){
754
755     /* Set Image Color Space */
756         if (jp2->enumcs == 16)
757                 image->color_space = CLRSPC_SRGB;
758         else if (jp2->enumcs == 17)
759                 image->color_space = CLRSPC_GRAY;
760         else if (jp2->enumcs == 18)
761                 image->color_space = CLRSPC_SYCC;
762         else
763                 image->color_space = CLRSPC_UNKNOWN;
764
765         if(color.jp2_cdef)
766    {
767         jp2_apply_cdef(image, &color);
768    }
769         if(color.jp2_pclr)
770    {
771 /* Part 1, I.5.3.4: Either both or none : */
772         if( !color.jp2_pclr->cmap) 
773          jp2_free_pclr(&color);
774         else
775          jp2_apply_pclr(&color, image, cinfo);
776    }
777         if(color.icc_profile_buf)
778    {
779         image->icc_profile_buf = color.icc_profile_buf;
780         color.icc_profile_buf = NULL;
781         image->icc_profile_len = color.icc_profile_len;
782    }
783    }
784    
785         return image;
786
787 }/* opj_jp2_decode() */
788
789
790 void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) {
791         opj_jp2_box_t box;
792
793         box.init_pos = cio_tell(cio);
794         cio_skip(cio, 4);
795         cio_write(cio, JP2_JP2H, 4);    /* JP2H */
796
797         jp2_write_ihdr(jp2, cio);
798
799         if (jp2->bpc == 255) {
800                 jp2_write_bpcc(jp2, cio);
801         }
802         jp2_write_colr(jp2, cio);
803
804         box.length = cio_tell(cio) - box.init_pos;
805         cio_seek(cio, box.init_pos);
806         cio_write(cio, box.length, 4);  /* L */
807         cio_seek(cio, box.init_pos + box.length);
808 }
809
810 static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
811         unsigned int i;
812         opj_jp2_box_t box;
813
814         box.init_pos = cio_tell(cio);
815         cio_skip(cio, 4);
816         cio_write(cio, JP2_FTYP, 4);            /* FTYP */
817
818         cio_write(cio, jp2->brand, 4);          /* BR */
819         cio_write(cio, jp2->minversion, 4);     /* MinV */
820
821         for (i = 0; i < jp2->numcl; i++) {
822                 cio_write(cio, jp2->cl[i], 4);  /* CL */
823         }
824
825         box.length = cio_tell(cio) - box.init_pos;
826         cio_seek(cio, box.init_pos);
827         cio_write(cio, box.length, 4);  /* L */
828         cio_seek(cio, box.init_pos + box.length);
829 }
830
831 static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
832         int i;
833         opj_jp2_box_t box;
834
835         opj_common_ptr cinfo = jp2->cinfo;
836
837   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
838     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
839     return OPJ_FALSE;
840   }
841         if (JP2_FTYP != box.type) {
842                 opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
843                 return OPJ_FALSE;
844         }
845
846         jp2->brand = cio_read(cio, 4);          /* BR */
847         jp2->minversion = cio_read(cio, 4);     /* MinV */
848         jp2->numcl = (box.length - 16) / 4;
849         jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
850
851         for (i = 0; i < (int)jp2->numcl; i++) {
852                 jp2->cl[i] = cio_read(cio, 4);  /* CLi */
853         }
854
855         if (cio_tell(cio) - box.init_pos != box.length) {
856                 opj_event_msg(cinfo, EVT_ERROR, "Error with FTYP Box\n");
857                 return OPJ_FALSE;
858         }
859
860         return OPJ_TRUE;
861 }
862
863 static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
864         unsigned int j2k_codestream_offset, j2k_codestream_length;
865         opj_jp2_box_t box;
866
867         opj_j2k_t *j2k = jp2->j2k;
868
869         box.init_pos = cio_tell(cio);
870         cio_skip(cio, 4);
871         cio_write(cio, JP2_JP2C, 4);    /* JP2C */
872
873         /* J2K encoding */
874         j2k_codestream_offset = cio_tell(cio);
875         if(!j2k_encode(j2k, cio, image, cstr_info)) {
876                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Failed to encode image\n");
877                 return 0;
878         }
879         j2k_codestream_length = cio_tell(cio) - j2k_codestream_offset;
880
881         jp2->j2k_codestream_offset = j2k_codestream_offset;
882         jp2->j2k_codestream_length = j2k_codestream_length;
883
884         box.length = 8 + jp2->j2k_codestream_length;
885         cio_seek(cio, box.init_pos);
886         cio_write(cio, box.length, 4);  /* L */
887         cio_seek(cio, box.init_pos + box.length);
888
889         return box.length;
890 }
891
892 static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset) {
893         opj_jp2_box_t box;
894
895         opj_common_ptr cinfo = jp2->cinfo;
896
897   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
898     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
899     return OPJ_FALSE;
900   }
901         do {
902                 if(JP2_JP2C != box.type) {
903                         if (box.length <= 8) return OPJ_FALSE;
904                         cio_skip(cio, box.length - 8);
905                         if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
906                 }
907         } while(JP2_JP2C != box.type);
908
909         *j2k_codestream_offset = cio_tell(cio);
910         if (box.length <= 8) return OPJ_FALSE;
911         *j2k_codestream_length = box.length - 8;
912
913         return OPJ_TRUE;
914 }
915
916 static void jp2_write_jp(opj_cio_t *cio) {
917         opj_jp2_box_t box;
918
919         box.init_pos = cio_tell(cio);
920         cio_skip(cio, 4);
921         cio_write(cio, JP2_JP, 4);              /* JP2 signature */
922         cio_write(cio, 0x0d0a870a, 4);
923
924         box.length = cio_tell(cio) - box.init_pos;
925         cio_seek(cio, box.init_pos);
926         cio_write(cio, box.length, 4);  /* L */
927         cio_seek(cio, box.init_pos + box.length);
928 }
929
930 static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
931         opj_jp2_box_t box;
932
933         opj_common_ptr cinfo = jp2->cinfo;
934
935   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
936     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
937     return OPJ_FALSE;
938   }
939         if (JP2_JP != box.type) {
940                 opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
941                 return OPJ_FALSE;
942         }
943         if (0x0d0a870a != cio_read(cio, 4)) {
944                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Marker\n");
945                 return OPJ_FALSE;
946         }
947         if (cio_tell(cio) - box.init_pos != box.length) {
948                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Box size\n");
949                 return OPJ_FALSE;
950         }
951
952         return OPJ_TRUE;
953 }
954
955
956 static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
957         opj_jp2_color_t *color) {
958         if (!jp2_read_jp(jp2, cio))
959                 return OPJ_FALSE;
960         if (!jp2_read_ftyp(jp2, cio))
961                 return OPJ_FALSE;
962         if (!jp2_read_jp2h(jp2, cio, color))
963                 return OPJ_FALSE;
964         if (!jp2_read_jp2c(jp2, cio, &jp2->j2k_codestream_length, &jp2->j2k_codestream_offset))
965                 return OPJ_FALSE;
966         
967         return OPJ_TRUE;
968 }
969
970
971
972
973 /* ----------------------------------------------------------------------- */
974 /* JP2 decoder interface                                             */
975 /* ----------------------------------------------------------------------- */
976
977 opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo) {
978         opj_jp2_t *jp2 = (opj_jp2_t*) opj_calloc(1, sizeof(opj_jp2_t));
979         if(jp2) {
980                 jp2->cinfo = cinfo;
981                 /* create the J2K codec */
982                 jp2->j2k = j2k_create_decompress(cinfo);
983                 if(jp2->j2k == NULL) {
984                         jp2_destroy_decompress(jp2);
985                         return NULL;
986                 }
987         }
988         return jp2;
989 }
990
991 void jp2_destroy_decompress(opj_jp2_t *jp2) {
992         if(jp2) {
993                 /* destroy the J2K codec */
994                 j2k_destroy_decompress(jp2->j2k);
995
996                 if(jp2->comps) {
997                         opj_free(jp2->comps);
998                 }
999                 if(jp2->cl) {
1000                         opj_free(jp2->cl);
1001                 }
1002                 opj_free(jp2);
1003         }
1004 }
1005
1006 void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
1007         /* setup the J2K codec */
1008         j2k_setup_decoder(jp2->j2k, parameters);
1009         /* further JP2 initializations go here */
1010         jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
1011 }
1012
1013 /* ----------------------------------------------------------------------- */
1014 /* JP2 encoder interface                                             */
1015 /* ----------------------------------------------------------------------- */
1016
1017 opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
1018         opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
1019         if(jp2) {
1020                 jp2->cinfo = cinfo;
1021                 /* create the J2K codec */
1022                 jp2->j2k = j2k_create_compress(cinfo);
1023                 if(jp2->j2k == NULL) {
1024                         jp2_destroy_compress(jp2);
1025                         return NULL;
1026                 }
1027         }
1028         return jp2;
1029 }
1030
1031 void jp2_destroy_compress(opj_jp2_t *jp2) {
1032         if(jp2) {
1033                 /* destroy the J2K codec */
1034                 j2k_destroy_compress(jp2->j2k);
1035
1036                 if(jp2->comps) {
1037                         opj_free(jp2->comps);
1038                 }
1039                 if(jp2->cl) {
1040                         opj_free(jp2->cl);
1041                 }
1042                 opj_free(jp2);
1043         }
1044 }
1045
1046 void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image) {
1047         int i;
1048         int depth_0, sign;
1049
1050         if(!jp2 || !parameters || !image)
1051                 return;
1052
1053         /* setup the J2K codec */
1054         /* ------------------- */
1055
1056         /* Check if number of components respects standard */
1057         if (image->numcomps < 1 || image->numcomps > 16384) {
1058                 opj_event_msg(jp2->cinfo, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
1059                 return;
1060         }
1061
1062         j2k_setup_encoder(jp2->j2k, parameters, image);
1063
1064         /* setup the JP2 codec */
1065         /* ------------------- */
1066         
1067         /* Profile box */
1068
1069         jp2->brand = JP2_JP2;   /* BR */
1070         jp2->minversion = 0;    /* MinV */
1071         jp2->numcl = 1;
1072         jp2->cl = (unsigned int*) opj_malloc(jp2->numcl * sizeof(unsigned int));
1073         jp2->cl[0] = JP2_JP2;   /* CL0 : JP2 */
1074
1075         /* Image Header box */
1076
1077         jp2->numcomps = image->numcomps;        /* NC */
1078         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
1079         jp2->h = image->y1 - image->y0;         /* HEIGHT */
1080         jp2->w = image->x1 - image->x0;         /* WIDTH */
1081         /* BPC */
1082         depth_0 = image->comps[0].prec - 1;
1083         sign = image->comps[0].sgnd;
1084         jp2->bpc = depth_0 + (sign << 7);
1085         for (i = 1; i < image->numcomps; i++) {
1086                 int depth = image->comps[i].prec - 1;
1087                 sign = image->comps[i].sgnd;
1088                 if (depth_0 != depth)
1089                         jp2->bpc = 255;
1090         }
1091         jp2->C = 7;                     /* C : Always 7 */
1092         jp2->UnkC = 0;          /* UnkC, colorspace specified in colr box */
1093         jp2->IPR = 0;           /* IPR, no intellectual property */
1094         
1095         /* BitsPerComponent box */
1096
1097         for (i = 0; i < image->numcomps; i++) {
1098                 jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
1099         }
1100         jp2->meth = 1;
1101         if (image->color_space == 1)
1102                 jp2->enumcs = 16;       /* sRGB as defined by IEC 61966-2.1 */
1103         else if (image->color_space == 2)
1104                 jp2->enumcs = 17;       /* greyscale */
1105         else if (image->color_space == 3)
1106                 jp2->enumcs = 18;       /* YUV */
1107         jp2->precedence = 0;    /* PRECEDENCE */
1108         jp2->approx = 0;                /* APPROX */
1109 }
1110
1111 opj_bool opj_jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
1112
1113         int pos_iptr, pos_jp2c, len_jp2c;
1114         pos_jp2c = pos_iptr = -1; /* remove a warning */
1115
1116         /* JP2 encoding */
1117
1118         /* JPEG 2000 Signature box */
1119         jp2_write_jp(cio);
1120         /* File Type box */
1121         jp2_write_ftyp(jp2, cio);
1122         /* JP2 Header box */
1123         jp2_write_jp2h(jp2, cio);
1124
1125         /* J2K encoding */
1126         if(!(len_jp2c = jp2_write_jp2c( jp2, cio, image, cstr_info))){
1127             opj_event_msg(jp2->cinfo, EVT_ERROR, "Failed to encode image\n");
1128             return OPJ_FALSE;
1129         }
1130
1131         return OPJ_TRUE;
1132 }