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