34dc10dec88eb18c5300d0bb5729dc6964f1fa10
[openjpeg.git] / src / lib / openmj2 / 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, opj_common_ptr cinfo);
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
130 /*@}*/
131
132 /* ----------------------------------------------------------------------- */
133
134 static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box) {
135         box->init_pos = cio_tell(cio);
136         box->length = cio_read(cio, 4);
137         box->type = cio_read(cio, 4);
138         if (box->length == 1) {
139                 if (cio_read(cio, 4) != 0) {
140                         opj_event_msg(cinfo, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
141                         return OPJ_FALSE;
142                 }
143                 box->length = cio_read(cio, 4);
144                 if (box->length == 0) 
145                         box->length = cio_numbytesleft(cio) + 12;
146         }
147         else if (box->length == 0) {
148                 box->length = cio_numbytesleft(cio) + 8;
149         }
150         if (box->length < 0) {
151                 opj_event_msg(cinfo, EVT_ERROR, "Integer overflow in box->length\n");
152                 return OPJ_FALSE; /* TODO: actually check jp2_read_boxhdr's return value */
153         }
154         
155         return OPJ_TRUE;
156 }
157
158 #if 0
159 static void jp2_write_url(opj_cio_t *cio, char *Idx_file) {
160         unsigned int i;
161         opj_jp2_box_t box;
162
163         box.init_pos = cio_tell(cio);
164         cio_skip(cio, 4);
165         cio_write(cio, JP2_URL, 4);     /* DBTL */
166         cio_write(cio, 0, 1);           /* VERS */
167         cio_write(cio, 0, 3);           /* FLAG */
168
169         if(Idx_file) {
170                 for (i = 0; i < strlen(Idx_file); i++) {
171                         cio_write(cio, Idx_file[i], 1);
172                 }
173         }
174
175         box.length = cio_tell(cio) - box.init_pos;
176         cio_seek(cio, box.init_pos);
177         cio_write(cio, box.length, 4);  /* L */
178         cio_seek(cio, box.init_pos + box.length);
179 }
180 #endif
181
182 static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
183         opj_jp2_box_t box;
184
185         opj_common_ptr cinfo = jp2->cinfo;
186
187   if(jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
188     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
189     return OPJ_FALSE;
190   }
191         if (JP2_IHDR != box.type) {
192                 opj_event_msg(cinfo, EVT_ERROR, "Expected IHDR Marker\n");
193                 return OPJ_FALSE;
194         }
195
196         jp2->h = cio_read(cio, 4);                      /* HEIGHT */
197         jp2->w = cio_read(cio, 4);                      /* WIDTH */
198         jp2->numcomps = cio_read(cio, 2);       /* NC */
199         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
200
201         jp2->bpc = cio_read(cio, 1);            /* BPC */
202
203         jp2->C = cio_read(cio, 1);                      /* C */
204         jp2->UnkC = cio_read(cio, 1);           /* UnkC */
205         jp2->IPR = cio_read(cio, 1);            /* IPR */
206
207         if (cio_tell(cio) - box.init_pos != box.length) {
208                 opj_event_msg(cinfo, EVT_ERROR, "Error with IHDR Box\n");
209                 return OPJ_FALSE;
210         }
211
212         return OPJ_TRUE;
213 }
214
215 static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
216         opj_jp2_box_t box;
217
218         box.init_pos = cio_tell(cio);
219         cio_skip(cio, 4);
220         cio_write(cio, JP2_IHDR, 4);            /* IHDR */
221
222         cio_write(cio, jp2->h, 4);                      /* HEIGHT */
223         cio_write(cio, jp2->w, 4);                      /* WIDTH */
224         cio_write(cio, jp2->numcomps, 2);       /* NC */
225
226         cio_write(cio, jp2->bpc, 1);            /* BPC */
227
228         cio_write(cio, jp2->C, 1);                      /* C : Always 7 */
229         cio_write(cio, jp2->UnkC, 1);           /* UnkC, colorspace unknown */
230         cio_write(cio, jp2->IPR, 1);            /* IPR, no intellectual property */
231
232         box.length = cio_tell(cio) - box.init_pos;
233         cio_seek(cio, box.init_pos);
234         cio_write(cio, box.length, 4);  /* L */
235         cio_seek(cio, box.init_pos + box.length);
236 }
237
238 static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
239         unsigned int i;
240         opj_jp2_box_t box;
241
242         box.init_pos = cio_tell(cio);
243         cio_skip(cio, 4);
244         cio_write(cio, JP2_BPCC, 4);    /* BPCC */
245
246         for (i = 0; i < jp2->numcomps; i++) {
247                 cio_write(cio, jp2->comps[i].bpcc, 1);
248         }
249
250         box.length = cio_tell(cio) - box.init_pos;
251         cio_seek(cio, box.init_pos);
252         cio_write(cio, box.length, 4);  /* L */
253         cio_seek(cio, box.init_pos + box.length);
254 }
255
256
257 static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
258         unsigned int i;
259         opj_jp2_box_t box;
260
261         opj_common_ptr cinfo = jp2->cinfo;
262
263   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
264     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
265     return OPJ_FALSE;
266   }
267         if (JP2_BPCC != box.type) {
268                 opj_event_msg(cinfo, EVT_ERROR, "Expected BPCC Marker\n");
269                 return OPJ_FALSE;
270         }
271
272         for (i = 0; i < jp2->numcomps; i++) {
273                 jp2->comps[i].bpcc = cio_read(cio, 1);
274         }
275
276         if (cio_tell(cio) - box.init_pos != box.length) {
277                 opj_event_msg(cinfo, EVT_ERROR, "Error with BPCC Box\n");
278                 return OPJ_FALSE;
279         }
280
281         return OPJ_TRUE;
282 }
283
284 static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio) {
285         opj_jp2_box_t box;
286
287         box.init_pos = cio_tell(cio);
288         cio_skip(cio, 4);
289         cio_write(cio, JP2_COLR, 4);            /* COLR */
290
291         cio_write(cio, jp2->meth, 1);           /* METH */
292         cio_write(cio, jp2->precedence, 1);     /* PRECEDENCE */
293         cio_write(cio, jp2->approx, 1);         /* APPROX */
294
295         if(jp2->meth == 2)
296          jp2->enumcs = 0;
297
298         cio_write(cio, jp2->enumcs, 4); /* EnumCS */
299
300         box.length = cio_tell(cio) - box.init_pos;
301         cio_seek(cio, box.init_pos);
302         cio_write(cio, box.length, 4);  /* L */
303         cio_seek(cio, box.init_pos + box.length);
304 }
305
306 static void jp2_free_pclr(opj_jp2_color_t *color)
307 {
308     opj_free(color->jp2_pclr->channel_sign);
309     opj_free(color->jp2_pclr->channel_size);
310     opj_free(color->jp2_pclr->entries);
311
312         if(color->jp2_pclr->cmap) opj_free(color->jp2_pclr->cmap);
313
314     opj_free(color->jp2_pclr); color->jp2_pclr = NULL;
315 }
316
317 static void free_color_data(opj_jp2_color_t *color)
318 {
319         if(color->jp2_pclr)
320    {
321         jp2_free_pclr(color);
322    }
323         if(color->jp2_cdef) 
324    {
325         if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info);
326         opj_free(color->jp2_cdef);
327    }
328         if(color->icc_profile_buf) opj_free(color->icc_profile_buf);
329 }
330
331 static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_common_ptr cinfo)
332 {
333         opj_image_comp_t *old_comps, *new_comps;
334         unsigned char *channel_size, *channel_sign;
335         unsigned int *entries;
336         opj_jp2_cmap_comp_t *cmap;
337         int *src, *dst;
338         unsigned int j, max;
339         unsigned short i, nr_channels, cmp, pcol;
340         int k, top_k;
341
342         channel_size = color->jp2_pclr->channel_size;
343         channel_sign = color->jp2_pclr->channel_sign;
344         entries = color->jp2_pclr->entries;
345         cmap = color->jp2_pclr->cmap;
346         nr_channels = color->jp2_pclr->nr_channels;
347
348         old_comps = image->comps;
349         new_comps = (opj_image_comp_t*)
350          opj_malloc(nr_channels * sizeof(opj_image_comp_t));
351
352         for(i = 0; i < nr_channels; ++i)
353    {
354         pcol = cmap[i].pcol; cmp = cmap[i].cmp;
355
356   if( pcol < nr_channels )
357     new_comps[pcol] = old_comps[cmp];
358   else
359     {
360     opj_event_msg(cinfo, EVT_ERROR, "Error with pcol value %d (max: %d). skipping\n", pcol, nr_channels);
361     continue;
362     }
363
364         if(cmap[i].mtyp == 0) /* Direct use */
365   {
366         old_comps[cmp].data = NULL; continue;
367   }
368 /* Palette mapping: */
369         new_comps[pcol].data = (int*)
370          opj_malloc(old_comps[cmp].w * old_comps[cmp].h * sizeof(int));
371         new_comps[pcol].prec = channel_size[i];
372         new_comps[pcol].sgnd = channel_sign[i];
373    }
374         top_k = color->jp2_pclr->nr_entries - 1;
375
376         for(i = 0; i < nr_channels; ++i)
377    {
378 /* Direct use: */
379         if(cmap[i].mtyp == 0) continue;
380
381 /* Palette mapping: */
382         cmp = cmap[i].cmp; pcol = cmap[i].pcol;
383         src = old_comps[cmp].data; 
384         dst = new_comps[pcol].data;
385         max = new_comps[pcol].w * new_comps[pcol].h;
386
387         for(j = 0; j < max; ++j)
388   {
389 /* The index */
390         if((k = src[j]) < 0) k = 0; else if(k > top_k) k = top_k;
391 /* The colour */
392         dst[j] = entries[k * nr_channels + pcol];
393   }
394    }
395         max = image->numcomps;
396         for(i = 0; i < max; ++i)
397    {
398         if(old_comps[i].data) opj_free(old_comps[i].data);
399    }
400         opj_free(old_comps);
401         image->comps = new_comps;
402         image->numcomps = nr_channels;
403
404         jp2_free_pclr(color);
405
406 }/* apply_pclr() */
407
408 static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio,
409         opj_jp2_box_t *box, opj_jp2_color_t *color)
410 {
411         opj_jp2_pclr_t *jp2_pclr;
412         unsigned char *channel_size, *channel_sign;
413         unsigned int *entries;
414         unsigned short nr_entries, nr_channels;
415         unsigned short i, j;
416         unsigned char uc;
417
418         OPJ_ARG_NOT_USED(box);
419         OPJ_ARG_NOT_USED(jp2);
420
421 /* Part 1, I.5.3.4: 'There shall be at most one Palette box inside
422  * a JP2 Header box' :
423 */
424         if(color->jp2_pclr) return OPJ_FALSE;
425
426         nr_entries = (unsigned short)cio_read(cio, 2); /* NE */
427         nr_channels = (unsigned short)cio_read(cio, 1);/* NPC */
428
429         entries = (unsigned int*)
430          opj_malloc(nr_channels * nr_entries * sizeof(unsigned int));
431         channel_size = (unsigned char*)opj_malloc(nr_channels);
432         channel_sign = (unsigned char*)opj_malloc(nr_channels);
433
434         jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t));
435         jp2_pclr->channel_sign = channel_sign;
436         jp2_pclr->channel_size = channel_size;
437         jp2_pclr->entries = entries;
438         jp2_pclr->nr_entries = nr_entries;
439         jp2_pclr->nr_channels = nr_channels;
440         jp2_pclr->cmap = NULL;
441
442         color->jp2_pclr = jp2_pclr;
443
444         for(i = 0; i < nr_channels; ++i)
445    {
446         uc = cio_read(cio, 1); /* Bi */
447         channel_size[i] = (uc & 0x7f) + 1;
448         channel_sign[i] = (uc & 0x80)?1:0;
449    }
450
451         for(j = 0; j < nr_entries; ++j)
452    {
453         for(i = 0; i < nr_channels; ++i)
454   {
455 /* Cji */
456         *entries++ = cio_read(cio, (channel_size[i]+7)>>3);
457   }
458    }
459
460         return OPJ_TRUE;
461 }/* jp2_read_pclr() */
462
463 static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio,
464         opj_jp2_box_t *box, opj_jp2_color_t *color)
465 {
466         opj_jp2_cmap_comp_t *cmap;
467         unsigned short i, nr_channels;
468
469         OPJ_ARG_NOT_USED(box);
470         OPJ_ARG_NOT_USED(jp2);
471
472 /* Need nr_channels: */
473         if(color->jp2_pclr == NULL) return OPJ_FALSE;
474
475 /* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box
476  * inside a JP2 Header box' :
477 */
478         if(color->jp2_pclr->cmap) return OPJ_FALSE;
479
480         nr_channels = color->jp2_pclr->nr_channels;
481         cmap = (opj_jp2_cmap_comp_t*)
482          opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t));
483
484         for(i = 0; i < nr_channels; ++i)
485    {
486         cmap[i].cmp = (unsigned short)cio_read(cio, 2);
487         cmap[i].mtyp = cio_read(cio, 1);
488         cmap[i].pcol = cio_read(cio, 1);
489
490    }
491         color->jp2_pclr->cmap = cmap;
492
493         return OPJ_TRUE;
494 }/* jp2_read_cmap() */
495
496 static void jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color)
497 {
498         opj_jp2_cdef_info_t *info;
499         int color_space;
500         unsigned short i, n, cn, typ, asoc, acn;
501
502         color_space = image->color_space;
503         info = color->jp2_cdef->info;
504         n = color->jp2_cdef->n;
505
506         for(i = 0; i < n; ++i)
507    {
508 /* WATCH: acn = asoc - 1 ! */
509         if((asoc = info[i].asoc) == 0) continue;
510
511         cn = info[i].cn; typ = info[i].typ; acn = asoc - 1;
512
513         if(cn != acn)
514   {
515         opj_image_comp_t saved;
516
517         memcpy(&saved, &image->comps[cn], sizeof(opj_image_comp_t));
518         memcpy(&image->comps[cn], &image->comps[acn], sizeof(opj_image_comp_t));
519         memcpy(&image->comps[acn], &saved, sizeof(opj_image_comp_t));
520
521         info[i].asoc = cn + 1;
522         info[acn].asoc = info[acn].cn + 1;
523   }
524    }
525         if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info);
526
527         opj_free(color->jp2_cdef); color->jp2_cdef = NULL;
528
529 }/* jp2_apply_cdef() */
530
531 static opj_bool jp2_read_cdef(opj_jp2_t *jp2, opj_cio_t *cio,
532         opj_jp2_box_t *box, opj_jp2_color_t *color)
533 {
534         opj_jp2_cdef_info_t *info;
535         unsigned short i, n;
536
537         OPJ_ARG_NOT_USED(box);
538         OPJ_ARG_NOT_USED(jp2);
539
540 /* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box
541  * inside a JP2 Header box.' 
542 */
543         if(color->jp2_cdef) return OPJ_FALSE;
544
545         if((n = (unsigned short)cio_read(cio, 2)) == 0) return OPJ_FALSE; /* szukw000: FIXME */
546
547         info = (opj_jp2_cdef_info_t*)
548          opj_malloc(n * sizeof(opj_jp2_cdef_info_t));
549
550         color->jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
551         color->jp2_cdef->info = info;
552         color->jp2_cdef->n = n;
553
554         for(i = 0; i < n; ++i)
555    {
556         info[i].cn = (unsigned short)cio_read(cio, 2);
557         info[i].typ = (unsigned short)cio_read(cio, 2);
558         info[i].asoc = (unsigned short)cio_read(cio, 2);
559
560    }
561         return OPJ_TRUE;
562 }/* jp2_read_cdef() */
563
564 static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio,
565         opj_jp2_box_t *box, opj_jp2_color_t *color) 
566 {
567         int skip_len;
568     opj_common_ptr cinfo;
569
570 /* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour
571  * Specification boxes after the first.' 
572 */
573         if(color->jp2_has_colr) return OPJ_FALSE;
574
575         cinfo = jp2->cinfo;
576
577         jp2->meth = cio_read(cio, 1);           /* METH */
578         jp2->precedence = cio_read(cio, 1);     /* PRECEDENCE */
579         jp2->approx = cio_read(cio, 1);         /* APPROX */
580
581         if (jp2->meth == 1) 
582    {
583         jp2->enumcs = cio_read(cio, 4); /* EnumCS */
584    } 
585         else
586         if (jp2->meth == 2) 
587    {
588 /* skip PROFILE */
589         skip_len = box->init_pos + box->length - cio_tell(cio);
590         if (skip_len < 0) 
591   {
592         opj_event_msg(cinfo, EVT_ERROR, "Error with COLR box size\n");
593         return OPJ_FALSE;
594   }
595         if(skip_len > 0)
596   {
597         unsigned char *start;
598
599         start = cio_getbp(cio);
600         color->icc_profile_buf = (unsigned char*)opj_malloc(skip_len);
601         color->icc_profile_len = skip_len;
602
603         cio_skip(cio, box->init_pos + box->length - cio_tell(cio));
604
605         memcpy(color->icc_profile_buf, start, skip_len);
606   }
607    }
608
609         if (cio_tell(cio) - box->init_pos != box->length) 
610    {
611         opj_event_msg(cinfo, EVT_ERROR, "Error with COLR Box\n");
612         return OPJ_FALSE;
613    }
614         color->jp2_has_colr = 1;
615
616         return OPJ_TRUE;
617 }/* jp2_read_colr() */
618
619 opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color) 
620 {
621         opj_jp2_box_t box;
622         int jp2h_end;
623
624         opj_common_ptr cinfo = jp2->cinfo;
625
626   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
627   do {
628     if (JP2_JP2H != box.type) 
629       {
630       if (box.type == JP2_JP2C) 
631         {
632         opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
633         return OPJ_FALSE;
634         }
635           if (box.length <= 8) return OPJ_FALSE;
636       cio_skip(cio, box.length - 8);
637
638       if(cio->bp >= cio->end) return OPJ_FALSE;
639
640       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
641       }
642   } while(JP2_JP2H != box.type);
643
644         if (!jp2_read_ihdr(jp2, cio))
645                 return OPJ_FALSE;
646         jp2h_end = box.init_pos + box.length;
647
648   if (jp2->bpc == 255) 
649     {
650     if (!jp2_read_bpcc(jp2, cio))
651       return OPJ_FALSE;
652     }
653   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
654
655   while(cio_tell(cio) < jp2h_end)
656     {
657     if(box.type == JP2_COLR)
658       {
659       if( !jp2_read_colr(jp2, cio, &box, color))
660         {
661         if (box.length <= 8) return OPJ_FALSE;
662         cio_seek(cio, box.init_pos + 8);
663         cio_skip(cio, box.length - 8);
664         }
665       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
666       continue;
667       }
668     if(box.type == JP2_CDEF && !jp2->ignore_pclr_cmap_cdef)
669       {
670       if( !jp2_read_cdef(jp2, cio, &box, color))
671         {
672         if (box.length <= 8) return OPJ_FALSE;
673         cio_seek(cio, box.init_pos + 8);
674         cio_skip(cio, box.length - 8);
675         }
676       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
677       continue;
678       }
679     if(box.type == JP2_PCLR && !jp2->ignore_pclr_cmap_cdef)
680       {
681       if( !jp2_read_pclr(jp2, cio, &box, color))
682         {
683         if (box.length <= 8) return OPJ_FALSE;
684         cio_seek(cio, box.init_pos + 8);
685         cio_skip(cio, box.length - 8);
686         }
687       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
688       continue;
689       }
690     if(box.type == JP2_CMAP && !jp2->ignore_pclr_cmap_cdef)
691       {
692       if( !jp2_read_cmap(jp2, cio, &box, color))
693         {
694         if (box.length <= 8) return OPJ_FALSE;
695         cio_seek(cio, box.init_pos + 8);
696         cio_skip(cio, box.length - 8);
697         }
698       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
699       continue;
700       }
701     if (box.length <= 8) return OPJ_FALSE;
702     cio_seek(cio, box.init_pos + 8);
703     cio_skip(cio, box.length - 8);
704     if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
705
706     }/* while(cio_tell(cio) < box_end) */
707
708   cio_seek(cio, jp2h_end);
709
710   /* Part 1, I.5.3.3 : 'must contain at least one' */
711   return (color->jp2_has_colr == 1);
712
713 }/* jp2_read_jp2h() */
714
715 opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, 
716         opj_codestream_info_t *cstr_info) 
717 {
718         opj_common_ptr cinfo;
719         opj_image_t *image = NULL;
720         opj_jp2_color_t color;
721
722         if(!jp2 || !cio) 
723    {
724         return NULL;
725    }
726         memset(&color, 0, sizeof(opj_jp2_color_t));
727         cinfo = jp2->cinfo;
728
729 /* JP2 decoding */
730         if(!jp2_read_struct(jp2, cio, &color)) 
731    {
732         free_color_data(&color);
733         opj_event_msg(cinfo, EVT_ERROR, "Failed to decode jp2 structure\n");
734         return NULL;
735    }
736
737 /* J2K decoding */
738         image = j2k_decode(jp2->j2k, cio, cstr_info);
739
740         if(!image) 
741    {
742         free_color_data(&color);
743         opj_event_msg(cinfo, EVT_ERROR, "Failed to decode J2K image\n");
744         return NULL;
745    }
746    
747     if (!jp2->ignore_pclr_cmap_cdef){
748
749     /* Set Image Color Space */
750         if (jp2->enumcs == 16)
751                 image->color_space = CLRSPC_SRGB;
752         else if (jp2->enumcs == 17)
753                 image->color_space = CLRSPC_GRAY;
754         else if (jp2->enumcs == 18)
755                 image->color_space = CLRSPC_SYCC;
756         else
757                 image->color_space = CLRSPC_UNKNOWN;
758
759         if(color.jp2_cdef)
760    {
761         jp2_apply_cdef(image, &color);
762    }
763         if(color.jp2_pclr)
764    {
765 /* Part 1, I.5.3.4: Either both or none : */
766         if( !color.jp2_pclr->cmap) 
767          jp2_free_pclr(&color);
768         else
769          jp2_apply_pclr(&color, image, cinfo);
770    }
771         if(color.icc_profile_buf)
772    {
773         image->icc_profile_buf = color.icc_profile_buf;
774         color.icc_profile_buf = NULL;
775         image->icc_profile_len = color.icc_profile_len;
776    }
777    }
778    
779         return image;
780
781 }/* opj_jp2_decode() */
782
783
784 void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) {
785         opj_jp2_box_t box;
786
787         box.init_pos = cio_tell(cio);
788         cio_skip(cio, 4);
789         cio_write(cio, JP2_JP2H, 4);    /* JP2H */
790
791         jp2_write_ihdr(jp2, cio);
792
793         if (jp2->bpc == 255) {
794                 jp2_write_bpcc(jp2, cio);
795         }
796         jp2_write_colr(jp2, cio);
797
798         box.length = cio_tell(cio) - box.init_pos;
799         cio_seek(cio, box.init_pos);
800         cio_write(cio, box.length, 4);  /* L */
801         cio_seek(cio, box.init_pos + box.length);
802 }
803
804 static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
805         unsigned int i;
806         opj_jp2_box_t box;
807
808         box.init_pos = cio_tell(cio);
809         cio_skip(cio, 4);
810         cio_write(cio, JP2_FTYP, 4);            /* FTYP */
811
812         cio_write(cio, jp2->brand, 4);          /* BR */
813         cio_write(cio, jp2->minversion, 4);     /* MinV */
814
815         for (i = 0; i < jp2->numcl; i++) {
816                 cio_write(cio, jp2->cl[i], 4);  /* CL */
817         }
818
819         box.length = cio_tell(cio) - box.init_pos;
820         cio_seek(cio, box.init_pos);
821         cio_write(cio, box.length, 4);  /* L */
822         cio_seek(cio, box.init_pos + box.length);
823 }
824
825 static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
826         int i;
827         opj_jp2_box_t box;
828
829         opj_common_ptr cinfo = jp2->cinfo;
830
831   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
832     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
833     return OPJ_FALSE;
834   }
835         if (JP2_FTYP != box.type) {
836                 opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
837                 return OPJ_FALSE;
838         }
839
840         jp2->brand = cio_read(cio, 4);          /* BR */
841         jp2->minversion = cio_read(cio, 4);     /* MinV */
842         jp2->numcl = (box.length - 16) / 4;
843         jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
844
845         for (i = 0; i < (int)jp2->numcl; i++) {
846                 jp2->cl[i] = cio_read(cio, 4);  /* CLi */
847         }
848
849         if (cio_tell(cio) - box.init_pos != box.length) {
850                 opj_event_msg(cinfo, EVT_ERROR, "Error with FTYP Box\n");
851                 return OPJ_FALSE;
852         }
853
854         return OPJ_TRUE;
855 }
856
857 static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
858         unsigned int j2k_codestream_offset, j2k_codestream_length;
859         opj_jp2_box_t box;
860
861         opj_j2k_t *j2k = jp2->j2k;
862
863         box.init_pos = cio_tell(cio);
864         cio_skip(cio, 4);
865         cio_write(cio, JP2_JP2C, 4);    /* JP2C */
866
867         /* J2K encoding */
868         j2k_codestream_offset = cio_tell(cio);
869         if(!j2k_encode(j2k, cio, image, cstr_info)) {
870                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Failed to encode image\n");
871                 return 0;
872         }
873         j2k_codestream_length = cio_tell(cio) - j2k_codestream_offset;
874
875         jp2->j2k_codestream_offset = j2k_codestream_offset;
876         jp2->j2k_codestream_length = j2k_codestream_length;
877
878         box.length = 8 + jp2->j2k_codestream_length;
879         cio_seek(cio, box.init_pos);
880         cio_write(cio, box.length, 4);  /* L */
881         cio_seek(cio, box.init_pos + box.length);
882
883         return box.length;
884 }
885
886 static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset) {
887         opj_jp2_box_t box;
888
889         opj_common_ptr cinfo = jp2->cinfo;
890
891   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
892     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
893     return OPJ_FALSE;
894   }
895         do {
896                 if(JP2_JP2C != box.type) {
897                         if (box.length <= 8) return OPJ_FALSE;
898                         cio_skip(cio, box.length - 8);
899                         if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
900                 }
901         } while(JP2_JP2C != box.type);
902
903         *j2k_codestream_offset = cio_tell(cio);
904         if (box.length <= 8) return OPJ_FALSE;
905         *j2k_codestream_length = box.length - 8;
906
907         return OPJ_TRUE;
908 }
909
910 static void jp2_write_jp(opj_cio_t *cio) {
911         opj_jp2_box_t box;
912
913         box.init_pos = cio_tell(cio);
914         cio_skip(cio, 4);
915         cio_write(cio, JP2_JP, 4);              /* JP2 signature */
916         cio_write(cio, 0x0d0a870a, 4);
917
918         box.length = cio_tell(cio) - box.init_pos;
919         cio_seek(cio, box.init_pos);
920         cio_write(cio, box.length, 4);  /* L */
921         cio_seek(cio, box.init_pos + box.length);
922 }
923
924 static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
925         opj_jp2_box_t box;
926
927         opj_common_ptr cinfo = jp2->cinfo;
928
929   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
930     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
931     return OPJ_FALSE;
932   }
933         if (JP2_JP != box.type) {
934                 opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
935                 return OPJ_FALSE;
936         }
937         if (0x0d0a870a != cio_read(cio, 4)) {
938                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Marker\n");
939                 return OPJ_FALSE;
940         }
941         if (cio_tell(cio) - box.init_pos != box.length) {
942                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Box size\n");
943                 return OPJ_FALSE;
944         }
945
946         return OPJ_TRUE;
947 }
948
949
950 static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
951         opj_jp2_color_t *color) {
952         if (!jp2_read_jp(jp2, cio))
953                 return OPJ_FALSE;
954         if (!jp2_read_ftyp(jp2, cio))
955                 return OPJ_FALSE;
956         if (!jp2_read_jp2h(jp2, cio, color))
957                 return OPJ_FALSE;
958         if (!jp2_read_jp2c(jp2, cio, &jp2->j2k_codestream_length, &jp2->j2k_codestream_offset))
959                 return OPJ_FALSE;
960         
961         return OPJ_TRUE;
962 }
963
964
965
966
967 /* ----------------------------------------------------------------------- */
968 /* JP2 decoder interface                                             */
969 /* ----------------------------------------------------------------------- */
970
971 opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo) {
972         opj_jp2_t *jp2 = (opj_jp2_t*) opj_calloc(1, sizeof(opj_jp2_t));
973         if(jp2) {
974                 jp2->cinfo = cinfo;
975                 /* create the J2K codec */
976                 jp2->j2k = j2k_create_decompress(cinfo);
977                 if(jp2->j2k == NULL) {
978                         jp2_destroy_decompress(jp2);
979                         return NULL;
980                 }
981         }
982         return jp2;
983 }
984
985 void jp2_destroy_decompress(opj_jp2_t *jp2) {
986         if(jp2) {
987                 /* destroy the J2K codec */
988                 j2k_destroy_decompress(jp2->j2k);
989
990                 if(jp2->comps) {
991                         opj_free(jp2->comps);
992                 }
993                 if(jp2->cl) {
994                         opj_free(jp2->cl);
995                 }
996                 opj_free(jp2);
997         }
998 }
999
1000 void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
1001         /* setup the J2K codec */
1002         j2k_setup_decoder(jp2->j2k, parameters);
1003         /* further JP2 initializations go here */
1004         jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
1005 }
1006
1007 /* ----------------------------------------------------------------------- */
1008 /* JP2 encoder interface                                             */
1009 /* ----------------------------------------------------------------------- */
1010
1011 opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
1012         opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
1013         if(jp2) {
1014                 jp2->cinfo = cinfo;
1015                 /* create the J2K codec */
1016                 jp2->j2k = j2k_create_compress(cinfo);
1017                 if(jp2->j2k == NULL) {
1018                         jp2_destroy_compress(jp2);
1019                         return NULL;
1020                 }
1021         }
1022         return jp2;
1023 }
1024
1025 void jp2_destroy_compress(opj_jp2_t *jp2) {
1026         if(jp2) {
1027                 /* destroy the J2K codec */
1028                 j2k_destroy_compress(jp2->j2k);
1029
1030                 if(jp2->comps) {
1031                         opj_free(jp2->comps);
1032                 }
1033                 if(jp2->cl) {
1034                         opj_free(jp2->cl);
1035                 }
1036                 opj_free(jp2);
1037         }
1038 }
1039
1040 void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image) {
1041         int i;
1042         int depth_0, sign;
1043
1044         if(!jp2 || !parameters || !image)
1045                 return;
1046
1047         /* setup the J2K codec */
1048         /* ------------------- */
1049
1050         /* Check if number of components respects standard */
1051         if (image->numcomps < 1 || image->numcomps > 16384) {
1052                 opj_event_msg(jp2->cinfo, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
1053                 return;
1054         }
1055
1056         j2k_setup_encoder(jp2->j2k, parameters, image);
1057
1058         /* setup the JP2 codec */
1059         /* ------------------- */
1060         
1061         /* Profile box */
1062
1063         jp2->brand = JP2_JP2;   /* BR */
1064         jp2->minversion = 0;    /* MinV */
1065         jp2->numcl = 1;
1066         jp2->cl = (unsigned int*) opj_malloc(jp2->numcl * sizeof(unsigned int));
1067         jp2->cl[0] = JP2_JP2;   /* CL0 : JP2 */
1068
1069         /* Image Header box */
1070
1071         jp2->numcomps = image->numcomps;        /* NC */
1072         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
1073         jp2->h = image->y1 - image->y0;         /* HEIGHT */
1074         jp2->w = image->x1 - image->x0;         /* WIDTH */
1075         /* BPC */
1076         depth_0 = image->comps[0].prec - 1;
1077         sign = image->comps[0].sgnd;
1078         jp2->bpc = depth_0 + (sign << 7);
1079         for (i = 1; i < image->numcomps; i++) {
1080                 int depth = image->comps[i].prec - 1;
1081                 sign = image->comps[i].sgnd;
1082                 if (depth_0 != depth)
1083                         jp2->bpc = 255;
1084         }
1085         jp2->C = 7;                     /* C : Always 7 */
1086         jp2->UnkC = 0;          /* UnkC, colorspace specified in colr box */
1087         jp2->IPR = 0;           /* IPR, no intellectual property */
1088         
1089         /* BitsPerComponent box */
1090
1091         for (i = 0; i < image->numcomps; i++) {
1092                 jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
1093         }
1094         jp2->meth = 1;
1095         if (image->color_space == 1)
1096                 jp2->enumcs = 16;       /* sRGB as defined by IEC 61966-2.1 */
1097         else if (image->color_space == 2)
1098                 jp2->enumcs = 17;       /* greyscale */
1099         else if (image->color_space == 3)
1100                 jp2->enumcs = 18;       /* YUV */
1101         jp2->precedence = 0;    /* PRECEDENCE */
1102         jp2->approx = 0;                /* APPROX */
1103         
1104         jp2->jpip_on = parameters->jpip_on;
1105 }
1106
1107 opj_bool opj_jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
1108
1109         int pos_iptr, pos_cidx, pos_jp2c, len_jp2c, len_cidx, end_pos, pos_fidx, len_fidx;
1110         pos_jp2c = pos_iptr = -1; /* remove a warning */
1111
1112         /* JP2 encoding */
1113
1114         /* JPEG 2000 Signature box */
1115         jp2_write_jp(cio);
1116         /* File Type box */
1117         jp2_write_ftyp(jp2, cio);
1118         /* JP2 Header box */
1119         jp2_write_jp2h(jp2, cio);
1120
1121 #if 0
1122         if( jp2->jpip_on){
1123           pos_iptr = cio_tell( cio);
1124           cio_skip( cio, 24); /* IPTR further ! */
1125           
1126           pos_jp2c = cio_tell( cio);
1127         }
1128 #endif
1129
1130         /* J2K encoding */
1131         if(!(len_jp2c = jp2_write_jp2c( jp2, cio, image, cstr_info))){
1132             opj_event_msg(jp2->cinfo, EVT_ERROR, "Failed to encode image\n");
1133             return OPJ_FALSE;
1134         }
1135
1136 #if 0
1137         if( jp2->jpip_on){
1138           pos_cidx = cio_tell( cio);
1139           
1140           len_cidx = write_cidx( pos_jp2c+8, cio, image, *cstr_info, len_jp2c-8);
1141           
1142           pos_fidx = cio_tell( cio);
1143           len_fidx = write_fidx( pos_jp2c, len_jp2c, pos_cidx, len_cidx, cio);
1144           
1145           end_pos = cio_tell( cio);
1146           
1147           cio_seek( cio, pos_iptr);
1148           write_iptr( pos_fidx, len_fidx, cio);
1149           
1150           cio_seek( cio, end_pos);
1151         }
1152 #endif
1153
1154         return OPJ_TRUE;
1155 }