9ed7f5a0bd9bc78de043bbabd3dce47e53616eef
[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 #define BOX_SIZE        1024
38
39 /** @name Local static functions */
40 /*@{*/
41
42 /**
43 Read box headers
44 @param cinfo Codec context info
45 @param cio Input stream
46 @param box
47 @return Returns true if successful, returns false otherwise
48 */
49 static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box);
50 /*static void jp2_write_url(opj_cio_t *cio, char *Idx_file);*/
51 /**
52 Read the IHDR box - Image Header box
53 @param jp2 JP2 handle
54 @param cio Input buffer stream
55 @return Returns true if successful, returns false otherwise
56 */
57 static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio);
58
59 /**
60  * Reads a IHDR box - Image Header box
61  *
62  * @param       p_image_header_data                     pointer to actual data (already read from file)
63  * @param       jp2                                                     the jpeg2000 file codec.
64  * @param       p_image_header_size                     the size of the image header
65  * @param       p_manager                                       the user event manager.
66  *
67  * @return      true if the image header is valid, fale else.
68  */
69 static opj_bool jp2_read_ihdr_v2(
70                                                         opj_jp2_v2_t *jp2,
71                                                         unsigned char * p_image_header_data,
72                                                         unsigned int p_image_header_size,
73                                                         struct opj_event_mgr * p_manager
74                                                   );
75
76 static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio);
77 static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio);
78 static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio);
79
80 /**
81  * Reads a Bit per Component box.
82  *
83  * @param       p_bpc_header_data                       pointer to actual data (already read from file)
84  * @param       jp2                                                     the jpeg2000 file codec.
85  * @param       p_bpc_header_size                       the size of the bpc header
86  * @param       p_manager                                       the user event manager.
87  *
88  * @return      true if the bpc header is valid, fale else.
89  */
90 static opj_bool jp2_read_bpcc_v2(
91                                                         opj_jp2_v2_t *jp2,
92                                                         unsigned char * p_bpc_header_data,
93                                                         unsigned int p_bpc_header_size,
94                                                         struct opj_event_mgr * p_manager
95                                                   );
96
97 static opj_bool jp2_read_cdef_v2(       opj_jp2_v2_t * jp2,
98                                                                         unsigned char * p_cdef_header_data,
99                                                                         OPJ_UINT32 p_cdef_header_size,
100                                                                         opj_event_mgr_t * p_manager
101                                                                         );
102
103 static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio);
104 /**
105 Write the FTYP box - File type box
106 @param jp2 JP2 handle
107 @param cio Output buffer stream
108 */
109 static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio);
110 /**
111 Read the FTYP box - File type box
112 @param jp2 JP2 handle
113 @param cio Input buffer stream
114 @return Returns true if successful, returns false otherwise
115 */
116 static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio);
117
118 /**
119  * Reads a a FTYP box - File type box
120  *
121  * @param       p_header_data   the data contained in the FTYP box.
122  * @param       jp2                             the jpeg2000 file codec.
123  * @param       p_header_size   the size of the data contained in the FTYP box.
124  * @param       p_manager               the user event manager.
125  *
126  * @return true if the FTYP box is valid.
127  */
128 static opj_bool jp2_read_ftyp_v2(
129                                                         opj_jp2_v2_t *jp2,
130                                                         unsigned char * p_header_data,
131                                                         unsigned int p_header_size,
132                                                         struct opj_event_mgr * p_manager
133                                                 );
134
135 /**
136  * Reads the Jpeg2000 file Header box - JP2 Header box (warning, this is a super box).
137  *
138  * @param       p_header_data   the data contained in the file header box.
139  * @param       jp2                             the jpeg2000 file codec.
140  * @param       p_header_size   the size of the data contained in the file header box.
141  * @param       p_manager               the user event manager.
142  *
143  * @return true if the JP2 Header box was successfully reconized.
144 */
145 static opj_bool jp2_read_jp2h_v2(
146                                                 opj_jp2_v2_t *jp2,
147                                                 unsigned char * p_header_data,
148                                                 unsigned int p_header_size,
149                                                 struct opj_event_mgr * p_manager
150                                         );
151
152 static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info);
153 static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset);
154 static void jp2_write_jp(opj_cio_t *cio);
155 /**
156 Read the JP box - JPEG 2000 signature
157 @param jp2 JP2 handle
158 @param cio Input buffer stream
159 @return Returns true if successful, returns false otherwise
160 */
161 static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio);
162
163 /**
164  * Reads a jpeg2000 file signature box.
165  *
166  * @param       p_header_data   the data contained in the signature box.
167  * @param       jp2                             the jpeg2000 file codec.
168  * @param       p_header_size   the size of the data contained in the signature box.
169  * @param       p_manager               the user event manager.
170  *
171  * @return true if the file signature box is valid.
172  */
173 static opj_bool jp2_read_jp_v2(
174                                         opj_jp2_v2_t *jp2,
175                                         unsigned char * p_header_data,
176                                         unsigned int p_header_size,
177                                         struct opj_event_mgr * p_manager
178                                  );
179
180 /**
181 Decode the structure of a JP2 file
182 @param jp2 JP2 handle
183 @param cio Input buffer stream
184 @param color Collector for profile, cdef and pclr data
185 @return Returns true if successful, returns false otherwise
186 */
187 static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
188         opj_jp2_color_t *color);
189 /**
190 Apply collected palette data
191 @param color Collector for profile, cdef and pclr data
192 @param image 
193 */
194 static void jp2_apply_pclr(opj_image_t *image, opj_jp2_color_t *color);
195 /**
196 Collect palette data
197 @param jp2 JP2 handle
198 @param cio Input buffer stream
199 @param box
200 @param color Collector for profile, cdef and pclr data
201 @return Returns true if successful, returns false otherwise
202 */
203 static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio,
204     opj_jp2_box_t *box, opj_jp2_color_t *color);
205
206 static opj_bool jp2_read_pclr_v2(       opj_jp2_v2_t *jp2,
207                                                         unsigned char * p_pclr_header_data,
208                                                         OPJ_UINT32 p_pclr_header_size,
209                                                         opj_event_mgr_t * p_manager
210                                                   );
211
212 /**
213 Collect component mapping data
214 @param jp2 JP2 handle
215 @param cio Input buffer stream
216 @param box
217 @param color Collector for profile, cdef and pclr data
218 @return Returns true if successful, returns false otherwise
219 */
220 static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio,
221     opj_jp2_box_t *box, opj_jp2_color_t *color);
222
223
224 static opj_bool jp2_read_cmap_v2(       opj_jp2_v2_t * jp2,
225                                                         unsigned char * p_cmap_header_data,
226                                                         OPJ_UINT32 p_cmap_header_size,
227                                                         opj_event_mgr_t * p_manager
228                                                   );
229
230 /**
231 Collect colour specification data
232 @param jp2 JP2 handle
233 @param cio Input buffer stream
234 @param box
235 @param color Collector for profile, cdef and pclr data
236 @return Returns true if successful, returns false otherwise
237 */
238 static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio,
239     opj_jp2_box_t *box, opj_jp2_color_t *color);
240
241 /**
242  * Reads the Color Specification box.
243  *
244  * @param       p_colr_header_data                      pointer to actual data (already read from file)
245  * @param       jp2                                                     the jpeg2000 file codec.
246  * @param       p_colr_header_size                      the size of the color header
247  * @param       p_manager                                       the user event manager.
248  *
249  * @return      true if the bpc header is valid, fale else.
250 */
251 static opj_bool jp2_read_colr_v2(
252                                                         opj_jp2_v2_t *jp2,
253                                                         unsigned char * p_colr_header_data,
254                                                         OPJ_UINT32 p_colr_header_size,
255                                                         struct opj_event_mgr * p_manager
256                                                   );
257
258 /**
259 Write file Index (superbox)
260 @param[in] offset_jp2c offset of jp2c box
261 @param[in] length_jp2c length of jp2c box
262 @param[in] offset_idx  offset of cidx box
263 @param[in] length_idx  length of cidx box
264 @param[in] cio         file output handle
265 @return                length of fidx box
266 */
267 static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio);
268 /**
269 Write index Finder box
270 @param[in] offset offset of fidx box
271 @param[in] length length of fidx box
272 @param[in] cio         file output handle
273 */
274 static void write_iptr( int offset, int length, opj_cio_t *cio);
275 /**
276
277 Write proxy box
278 @param[in] offset_jp2c offset of jp2c box
279 @param[in] length_jp2c length of jp2c box
280 @param[in] offset_idx  offset of cidx box
281 @param[in] length_idx  length of cidx box
282 @param[in] cio         file output handle
283 */
284 static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio);
285 /*@}*/
286
287 /*@}*/
288
289 /**
290  * Sets up the procedures to do on reading header after the codestream.
291  * Developpers wanting to extend the library can add their own writting procedures.
292  */
293 static void jp2_setup_end_header_reading (opj_jp2_v2_t *jp2);
294
295 /**
296  * Reads a jpeg2000 file header structure.
297  *
298  * @param cio the stream to read data from.
299  * @param jp2 the jpeg2000 file header structure.
300  * @param p_manager the user event manager.
301  *
302  * @return true if the box is valid.
303  */
304 opj_bool jp2_read_header_procedure(
305                                                                 opj_jp2_v2_t *jp2,
306                                                                 struct opj_stream_private *cio,
307                                                                 struct opj_event_mgr * p_manager
308                                                         );
309
310 /**
311  * Excutes the given procedures on the given codec.
312  *
313  * @param       p_procedure_list        the list of procedures to execute
314  * @param       jp2                                     the jpeg2000 file codec to execute the procedures on.
315  * @param       cio                                     the stream to execute the procedures on.
316  * @param       p_manager                       the user manager.
317  *
318  * @return      true                            if all the procedures were successfully executed.
319  */
320 static opj_bool jp2_exec (
321                                         opj_jp2_v2_t * jp2,
322                                         struct opj_procedure_list * p_procedure_list,
323                                         struct opj_stream_private *cio,
324                                         struct opj_event_mgr * p_manager
325                                   );
326
327 /**
328  * Reads a box header. The box is the way data is packed inside a jpeg2000 file structure.
329  *
330  * @param       cio                                             the input stream to read data from.
331  * @param       box                                             the box structure to fill.
332  * @param       p_number_bytes_read             pointer to an int that will store the number of bytes read from the stream (shoul usually be 2).
333  * @param       p_manager                               user event manager.
334  *
335  * @return      true if the box is reconized, false otherwise
336 */
337 static opj_bool jp2_read_boxhdr_v2(
338                                                                 opj_jp2_box_t *box,
339                                                                 OPJ_UINT32 * p_number_bytes_read,
340                                                                 struct opj_stream_private *cio,
341                                                                 struct opj_event_mgr * p_manager
342                                                         );
343
344 /**
345  * Finds the execution function related to the given box id.
346  *
347  * @param       p_id    the id of the handler to fetch.
348  *
349  * @return      the given handler or NULL if it could not be found.
350  */
351 static const opj_jp2_header_handler_t * jp2_find_handler (int p_id );
352
353 /**
354  * Finds the image execution function related to the given box id.
355  *
356  * @param       p_id    the id of the handler to fetch.
357  *
358  * @return      the given handler or NULL if it could not be found.
359  */
360 static const opj_jp2_header_handler_t * jp2_img_find_handler (int p_id);
361
362 const opj_jp2_header_handler_t jp2_header [] =
363 {
364         {JP2_JP,jp2_read_jp_v2},
365         {JP2_FTYP,jp2_read_ftyp_v2},
366         {JP2_JP2H,jp2_read_jp2h_v2}
367 };
368
369 const opj_jp2_header_handler_t jp2_img_header [] =
370 {
371         {JP2_IHDR,jp2_read_ihdr_v2},
372         {JP2_COLR,jp2_read_colr_v2},
373         {JP2_BPCC,jp2_read_bpcc_v2},
374         {JP2_PCLR,jp2_read_pclr_v2},
375         {JP2_CMAP,jp2_read_cmap_v2},
376         {JP2_CDEF,jp2_read_cdef_v2}
377
378 };
379
380 /**
381  * Reads a box header. The box is the way data is packed inside a jpeg2000 file structure. Data is read from a character string
382  *
383  * @param       p_data                                  the character string to read data from.
384  * @param       box                                             the box structure to fill.
385  * @param       p_number_bytes_read             pointer to an int that will store the number of bytes read from the stream (shoul usually be 2).
386  * @param       p_box_max_size                  the maximum number of bytes in the box.
387  *
388  * @return      true if the box is reconized, false otherwise
389 */
390 static opj_bool jp2_read_boxhdr_char(
391                                                                 opj_jp2_box_t *box,
392                                                                 OPJ_BYTE * p_data,
393                                                                 OPJ_UINT32 * p_number_bytes_read,
394                                                                 OPJ_UINT32 p_box_max_size,
395                                                                 struct opj_event_mgr * p_manager
396                                                         );
397
398 /**
399  * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
400  * are valid. Developpers wanting to extend the library can add their own validation procedures.
401  */
402 static void jp2_setup_decoding_validation (opj_jp2_v2_t *jp2);
403
404 /**
405  * Sets up the procedures to do on reading header.
406  * Developpers wanting to extend the library can add their own writting procedures.
407  */
408 static void jp2_setup_header_reading (opj_jp2_v2_t *jp2);
409
410
411
412 /* ----------------------------------------------------------------------- */
413
414 static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box) {
415         box->init_pos = cio_tell(cio);
416         box->length = cio_read(cio, 4);
417         box->type = cio_read(cio, 4);
418         if (box->length == 1) {
419                 if (cio_read(cio, 4) != 0) {
420                         opj_event_msg(cinfo, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
421                         return OPJ_FALSE;
422                 }
423                 box->length = cio_read(cio, 4);
424                 if (box->length == 0) 
425                         box->length = cio_numbytesleft(cio) + 12;
426         }
427         else if (box->length == 0) {
428                 box->length = cio_numbytesleft(cio) + 8;
429         }
430         
431         return OPJ_TRUE;
432 }
433
434 /**
435  * Reads a box header. The box is the way data is packed inside a jpeg2000 file structure.
436  *
437  * @param       cio                                             the input stream to read data from.
438  * @param       box                                             the box structure to fill.
439  * @param       p_number_bytes_read             pointer to an int that will store the number of bytes read from the stream (should usually be 8).
440  * @param       p_manager                               user event manager.
441  *
442  * @return      true if the box is reconized, false otherwise
443 */
444 opj_bool jp2_read_boxhdr_v2(opj_jp2_box_t *box, OPJ_UINT32 * p_number_bytes_read, opj_stream_private_t *cio, opj_event_mgr_t * p_manager)
445 {
446         /* read header from file */
447         unsigned char l_data_header [8];
448
449         // preconditions
450         assert(cio != 00);
451         assert(box != 00);
452         assert(p_number_bytes_read != 00);
453         assert(p_manager != 00);
454
455         *p_number_bytes_read = opj_stream_read_data(cio,l_data_header,8,p_manager);
456         if (*p_number_bytes_read != 8) {
457                 return OPJ_FALSE;
458         }
459
460         /* process read data */
461         opj_read_bytes(l_data_header,&(box->length), 4);
462         opj_read_bytes(l_data_header+4,&(box->type), 4);
463
464         // do we have a "special very large box ?"
465         // read then the XLBox
466         if (box->length == 1) {
467                 OPJ_UINT32 l_xl_part_size;
468
469                 OPJ_UINT32 l_nb_bytes_read = opj_stream_read_data(cio,l_data_header,8,p_manager);
470                 if (l_nb_bytes_read != 8) {
471                         if (l_nb_bytes_read > 0) {
472                                 *p_number_bytes_read += l_nb_bytes_read;
473                         }
474
475                         return OPJ_FALSE;
476                 }
477
478                 opj_read_bytes(l_data_header,&l_xl_part_size, 4);
479                 if (l_xl_part_size != 0) {
480                         opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
481                         return OPJ_FALSE;
482                 }
483                 opj_read_bytes(l_data_header,&(box->length), 4);
484         }
485         return OPJ_TRUE;
486 }
487
488 #if 0
489 static void jp2_write_url(opj_cio_t *cio, char *Idx_file) {
490         unsigned int i;
491         opj_jp2_box_t box;
492
493         box.init_pos = cio_tell(cio);
494         cio_skip(cio, 4);
495         cio_write(cio, JP2_URL, 4);     /* DBTL */
496         cio_write(cio, 0, 1);           /* VERS */
497         cio_write(cio, 0, 3);           /* FLAG */
498
499         if(Idx_file) {
500                 for (i = 0; i < strlen(Idx_file); i++) {
501                         cio_write(cio, Idx_file[i], 1);
502                 }
503         }
504
505         box.length = cio_tell(cio) - box.init_pos;
506         cio_seek(cio, box.init_pos);
507         cio_write(cio, box.length, 4);  /* L */
508         cio_seek(cio, box.init_pos + box.length);
509 }
510 #endif
511
512 static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
513         opj_jp2_box_t box;
514
515         opj_common_ptr cinfo = jp2->cinfo;
516
517         jp2_read_boxhdr(cinfo, cio, &box);
518         if (JP2_IHDR != box.type) {
519                 opj_event_msg(cinfo, EVT_ERROR, "Expected IHDR Marker\n");
520                 return OPJ_FALSE;
521         }
522
523         jp2->h = cio_read(cio, 4);                      /* HEIGHT */
524         jp2->w = cio_read(cio, 4);                      /* WIDTH */
525         jp2->numcomps = cio_read(cio, 2);       /* NC */
526         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
527
528         jp2->bpc = cio_read(cio, 1);            /* BPC */
529
530         jp2->C = cio_read(cio, 1);                      /* C */
531         jp2->UnkC = cio_read(cio, 1);           /* UnkC */
532         jp2->IPR = cio_read(cio, 1);            /* IPR */
533
534         if (cio_tell(cio) - box.init_pos != box.length) {
535                 opj_event_msg(cinfo, EVT_ERROR, "Error with IHDR Box\n");
536                 return OPJ_FALSE;
537         }
538
539         return OPJ_TRUE;
540 }
541
542 /**
543  * Reads a IHDR box - Image Header box
544  *
545  * @param       jp2                                                     the jpeg2000 file codec.
546  * @param       p_image_header_data                     pointer to actual data (already read from file)
547  * @param       p_image_header_size                     the size of the image header
548  * @param       p_manager                                       the user event manager.
549  *
550  * @return      true if the image header is valid, fale else.
551  */
552 opj_bool jp2_read_ihdr_v2(
553                                                         opj_jp2_v2_t *jp2,
554                                                         unsigned char * p_image_header_data,
555                                                         unsigned int p_image_header_size,
556                                                         opj_event_mgr_t * p_manager
557                                                   )
558 {
559         // preconditions
560         assert(p_image_header_data != 00);
561         assert(jp2 != 00);
562         assert(p_manager != 00);
563
564         if (p_image_header_size != 14) {
565                 opj_event_msg_v2(p_manager, EVT_ERROR, "Bad image header box (bad size)\n");
566                 return OPJ_FALSE;
567         }
568
569         opj_read_bytes(p_image_header_data,&(jp2->h),4);                        /* HEIGHT */
570         p_image_header_data += 4;
571         opj_read_bytes(p_image_header_data,&(jp2->w),4);                        /* WIDTH */
572         p_image_header_data += 4;
573         opj_read_bytes(p_image_header_data,&(jp2->numcomps),2);                 /* NC */
574         p_image_header_data += 2;
575
576         /* allocate memory for components */
577         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
578         if (jp2->comps == 0) {
579                 opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory to handle image header (ihdr)\n");
580                 return OPJ_FALSE;
581         }
582         memset(jp2->comps,0,jp2->numcomps * sizeof(opj_jp2_comps_t));
583
584         opj_read_bytes(p_image_header_data,&(jp2->bpc),1);                      /* BPC */
585         ++ p_image_header_data;
586
587         // if equal to 0 then need a BPC box (cf. chapter about image header box of the norm)
588         /*if (jp2->bpc == 0){
589                         // indicate with a flag that we will wait a BPC box
590                 }*/
591
592         opj_read_bytes(p_image_header_data,&(jp2->C),1);                        /* C */
593         ++ p_image_header_data;
594
595         // Should be equal to 7 cf. chapter about image header box of the norm
596         if (jp2->C != 7){
597                 opj_event_msg_v2(p_manager, EVT_INFO, "JP2 IHDR box: compression type indicate that the file is not a conforming JP2 file (%d) \n", jp2->C);
598         }
599
600         opj_read_bytes(p_image_header_data,&(jp2->UnkC),1);                     /* UnkC */
601         ++ p_image_header_data;
602         opj_read_bytes(p_image_header_data,&(jp2->IPR),1);                      /* IPR */
603         ++ p_image_header_data;
604
605         return OPJ_TRUE;
606 }
607
608 static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
609         opj_jp2_box_t box;
610
611         box.init_pos = cio_tell(cio);
612         cio_skip(cio, 4);
613         cio_write(cio, JP2_IHDR, 4);            /* IHDR */
614
615         cio_write(cio, jp2->h, 4);                      /* HEIGHT */
616         cio_write(cio, jp2->w, 4);                      /* WIDTH */
617         cio_write(cio, jp2->numcomps, 2);       /* NC */
618
619         cio_write(cio, jp2->bpc, 1);            /* BPC */
620
621         cio_write(cio, jp2->C, 1);                      /* C : Always 7 */
622         cio_write(cio, jp2->UnkC, 1);           /* UnkC, colorspace unknown */
623         cio_write(cio, jp2->IPR, 1);            /* IPR, no intellectual property */
624
625         box.length = cio_tell(cio) - box.init_pos;
626         cio_seek(cio, box.init_pos);
627         cio_write(cio, box.length, 4);  /* L */
628         cio_seek(cio, box.init_pos + box.length);
629 }
630
631 static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
632         unsigned int i;
633         opj_jp2_box_t box;
634
635         box.init_pos = cio_tell(cio);
636         cio_skip(cio, 4);
637         cio_write(cio, JP2_BPCC, 4);    /* BPCC */
638
639         for (i = 0; i < jp2->numcomps; i++) {
640                 cio_write(cio, jp2->comps[i].bpcc, 1);
641         }
642
643         box.length = cio_tell(cio) - box.init_pos;
644         cio_seek(cio, box.init_pos);
645         cio_write(cio, box.length, 4);  /* L */
646         cio_seek(cio, box.init_pos + box.length);
647 }
648
649
650 static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
651         unsigned int i;
652         opj_jp2_box_t box;
653
654         opj_common_ptr cinfo = jp2->cinfo;
655
656         jp2_read_boxhdr(cinfo, cio, &box);
657         if (JP2_BPCC != box.type) {
658                 opj_event_msg(cinfo, EVT_ERROR, "Expected BPCC Marker\n");
659                 return OPJ_FALSE;
660         }
661
662         for (i = 0; i < jp2->numcomps; i++) {
663                 jp2->comps[i].bpcc = cio_read(cio, 1);
664         }
665
666         if (cio_tell(cio) - box.init_pos != box.length) {
667                 opj_event_msg(cinfo, EVT_ERROR, "Error with BPCC Box\n");
668                 return OPJ_FALSE;
669         }
670
671         return OPJ_TRUE;
672 }
673
674 /**
675  * Reads a Bit per Component box.
676  *
677  * @param       jp2                                                     the jpeg2000 file codec.
678  * @param       p_bpc_header_data                       pointer to actual data (already read from file)
679  * @param       p_bpc_header_size                       pointer that will hold the size of the bpc header
680  * @param       p_manager                                       the user event manager.
681  *
682  * @return      true if the bpc header is valid, false otherwise.
683  */
684 opj_bool jp2_read_bpcc_v2(      opj_jp2_v2_t *jp2,
685                                                         unsigned char * p_bpc_header_data,
686                                                         unsigned int p_bpc_header_size,
687                                                         opj_event_mgr_t * p_manager
688                                                   )
689 {
690         OPJ_UINT32 i;
691
692         // preconditions
693         assert(p_bpc_header_data != 00);
694         assert(jp2 != 00);
695         assert(p_manager != 00);
696
697         // TODO MSD
698         /*if (jp2->bpc != 0 ){
699                 opj_event_msg_v2(p_manager, EVT_WARNING, "A BPCC header box is available although BPC is different to zero (%d)\n",jp2->bpc);
700         }*/
701
702         // and length is relevant
703         if (p_bpc_header_size != jp2->numcomps) {
704                 opj_event_msg_v2(p_manager, EVT_ERROR, "Bad BPCC header box (bad size)\n");
705                 return OPJ_FALSE;
706         }
707
708         // read info for each component
709         for (i = 0; i < jp2->numcomps; ++i) {
710                 opj_read_bytes(p_bpc_header_data,&jp2->comps[i].bpcc ,1);       /* read each BPCC component */
711                 ++p_bpc_header_data;
712         }
713
714         return OPJ_TRUE;
715 }
716
717 static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio) {
718         opj_jp2_box_t box;
719
720         box.init_pos = cio_tell(cio);
721         cio_skip(cio, 4);
722         cio_write(cio, JP2_COLR, 4);            /* COLR */
723
724         cio_write(cio, jp2->meth, 1);           /* METH */
725         cio_write(cio, jp2->precedence, 1);     /* PRECEDENCE */
726         cio_write(cio, jp2->approx, 1);         /* APPROX */
727
728         if(jp2->meth == 2)
729          jp2->enumcs = 0;
730
731         cio_write(cio, jp2->enumcs, 4); /* EnumCS */
732
733         box.length = cio_tell(cio) - box.init_pos;
734         cio_seek(cio, box.init_pos);
735         cio_write(cio, box.length, 4);  /* L */
736         cio_seek(cio, box.init_pos + box.length);
737 }
738
739 static void jp2_free_pclr(opj_jp2_color_t *color)
740 {
741     opj_free(color->jp2_pclr->channel_sign);
742     opj_free(color->jp2_pclr->channel_size);
743     opj_free(color->jp2_pclr->entries);
744
745         if(color->jp2_pclr->cmap) opj_free(color->jp2_pclr->cmap);
746
747     opj_free(color->jp2_pclr); color->jp2_pclr = NULL;
748 }
749
750 static void free_color_data(opj_jp2_color_t *color)
751 {
752         if(color->jp2_pclr)
753    {
754         jp2_free_pclr(color);
755    }
756         if(color->jp2_cdef) 
757    {
758         if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info);
759         opj_free(color->jp2_cdef);
760    }
761         if(color->icc_profile_buf) opj_free(color->icc_profile_buf);
762 }
763
764
765 static void jp2_apply_pclr(opj_image_t *image, opj_jp2_color_t *color)
766 {
767         opj_image_comp_t *old_comps, *new_comps;
768         OPJ_BYTE *channel_size, *channel_sign;
769         OPJ_UINT32 *entries;
770         opj_jp2_cmap_comp_t *cmap;
771         OPJ_INT32 *src, *dst;
772         OPJ_UINT32 j, max;
773         OPJ_UINT16 i, nr_channels, cmp, pcol;
774         OPJ_INT32 k, top_k;
775
776         channel_size = color->jp2_pclr->channel_size;
777         channel_sign = color->jp2_pclr->channel_sign;
778         entries = color->jp2_pclr->entries;
779         cmap = color->jp2_pclr->cmap;
780         nr_channels = color->jp2_pclr->nr_channels;
781
782         old_comps = image->comps;
783         new_comps = (opj_image_comp_t*)
784                         opj_malloc(nr_channels * sizeof(opj_image_comp_t));
785
786         for(i = 0; i < nr_channels; ++i) {
787                 pcol = cmap[i].pcol; cmp = cmap[i].cmp;
788
789                 new_comps[pcol] = old_comps[cmp];
790
791                 /* Direct use */
792                 if(cmap[i].mtyp == 0){
793                         old_comps[cmp].data = NULL; continue;
794                 }
795
796                 /* Palette mapping: */
797                 new_comps[pcol].data = (int*)
798                                 opj_malloc(old_comps[cmp].w * old_comps[cmp].h * sizeof(int));
799                 new_comps[pcol].prec = channel_size[i];
800                 new_comps[pcol].sgnd = channel_sign[i];
801         }
802
803         top_k = color->jp2_pclr->nr_entries - 1;
804
805         for(i = 0; i < nr_channels; ++i) {
806                 /* Direct use: */
807                 if(cmap[i].mtyp == 0) continue;
808
809                 /* Palette mapping: */
810                 cmp = cmap[i].cmp; pcol = cmap[i].pcol;
811                 src = old_comps[cmp].data;
812                 dst = new_comps[pcol].data;
813                 max = new_comps[pcol].w * new_comps[pcol].h;
814
815                 for(j = 0; j < max; ++j)
816                 {
817                         /* The index */
818                         if((k = src[j]) < 0) k = 0; else if(k > top_k) k = top_k;
819
820                         /* The colour */
821                         dst[j] = entries[k * nr_channels + pcol];
822                 }
823         }
824
825         max = image->numcomps;
826         for(i = 0; i < max; ++i) {
827                 if(old_comps[i].data) opj_free(old_comps[i].data);
828         }
829
830         opj_free(old_comps);
831         image->comps = new_comps;
832         image->numcomps = nr_channels;
833
834         jp2_free_pclr(color);
835
836 }/* apply_pclr() */
837
838
839 static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio,
840         opj_jp2_box_t *box, opj_jp2_color_t *color)
841 {
842         opj_jp2_pclr_t *jp2_pclr;
843         unsigned char *channel_size, *channel_sign;
844         unsigned int *entries;
845         unsigned short nr_entries, nr_channels;
846         unsigned short i, j;
847         unsigned char uc;
848
849         OPJ_ARG_NOT_USED(box);
850         OPJ_ARG_NOT_USED(jp2);
851
852 /* Part 1, I.5.3.4: 'There shall be at most one Palette box inside
853  * a JP2 Header box' :
854 */
855         if(color->jp2_pclr) return OPJ_FALSE;
856
857         nr_entries = (unsigned short)cio_read(cio, 2); /* NE */
858         nr_channels = (unsigned short)cio_read(cio, 1);/* NPC */
859
860         entries = (unsigned int*)
861          opj_malloc(nr_channels * nr_entries * sizeof(unsigned int));
862         channel_size = (unsigned char*)opj_malloc(nr_channels);
863         channel_sign = (unsigned char*)opj_malloc(nr_channels);
864
865         jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t));
866         jp2_pclr->channel_sign = channel_sign;
867         jp2_pclr->channel_size = channel_size;
868         jp2_pclr->entries = entries;
869         jp2_pclr->nr_entries = nr_entries;
870         jp2_pclr->nr_channels = nr_channels;
871         jp2_pclr->cmap = NULL;
872
873         color->jp2_pclr = jp2_pclr;
874
875         for(i = 0; i < nr_channels; ++i)
876    {
877         uc = cio_read(cio, 1); /* Bi */
878         channel_size[i] = (uc & 0x7f) + 1;
879         channel_sign[i] = (uc & 0x80)?1:0;
880    }
881
882         for(j = 0; j < nr_entries; ++j)
883    {
884         for(i = 0; i < nr_channels; ++i)
885   {
886 /* Cji */
887         *entries++ = cio_read(cio, channel_size[i]>>3);
888   }
889    }
890
891         return OPJ_TRUE;
892 }/* jp2_read_pclr() */
893
894 /**
895  * Reads a palette box.
896  *
897  * @param       jp2                                                     the jpeg2000 file codec.
898  * @param       p_pclr_header_data                      pointer to actual data (already read from file)
899  * @param       p_pclr_header_size                      pointer that will hold the size of the PCLR header
900  * @param       p_manager                                       the user event manager.
901  *
902  * @return      true if the bpc header is valid, fale else.
903  */
904 opj_bool jp2_read_pclr_v2(      opj_jp2_v2_t *jp2,
905                                                         unsigned char * p_pclr_header_data,
906                                                         OPJ_UINT32 p_pclr_header_size,
907                                                         opj_event_mgr_t * p_manager
908                                                   ){
909         opj_jp2_pclr_t *jp2_pclr;
910         OPJ_BYTE *channel_size, *channel_sign;
911         OPJ_UINT32 *entries;
912         OPJ_UINT16 nr_entries,nr_channels;
913         OPJ_UINT16 i, j;
914         OPJ_UINT32 l_value;
915
916         // preconditions
917         assert(p_pclr_header_data != 00);
918         assert(jp2 != 00);
919         assert(p_manager != 00);
920
921         if(jp2->color.jp2_pclr)
922                 return OPJ_FALSE;
923
924         opj_read_bytes(p_pclr_header_data, &l_value , 2);       /* NE */
925         p_pclr_header_data += 2;
926         nr_entries = (OPJ_UINT16) l_value;
927
928         opj_read_bytes(p_pclr_header_data, &l_value , 1);       /* NPC */
929         ++p_pclr_header_data;
930         nr_channels = (OPJ_UINT16) l_value;
931
932         entries = (OPJ_UINT32*) opj_malloc(nr_channels * nr_entries * sizeof(OPJ_UINT32));
933         channel_size = (OPJ_BYTE*) opj_malloc(nr_channels);
934         channel_sign = (OPJ_BYTE*) opj_malloc(nr_channels);
935
936         jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t));
937         jp2_pclr->channel_sign = channel_sign;
938         jp2_pclr->channel_size = channel_size;
939         jp2_pclr->entries = entries;
940         jp2_pclr->nr_entries = nr_entries;
941         jp2_pclr->nr_channels = nr_channels;
942         jp2_pclr->cmap = NULL;
943
944         jp2->color.jp2_pclr = jp2_pclr;
945
946         for(i = 0; i < nr_channels; ++i) {
947                 opj_read_bytes(p_pclr_header_data, &l_value , 1);       /* Bi */
948                 ++p_pclr_header_data;
949
950                 channel_size[i] = (l_value & 0x7f) + 1;
951                 channel_sign[i] = (l_value & 0x80)? 1 : 0;
952         }
953
954         for(j = 0; j < nr_entries; ++j) {
955                 for(i = 0; i < nr_channels; ++i) {
956                         //*entries++ = cio_read(cio, channel_size[i]>>3);
957                         opj_read_bytes(p_pclr_header_data, &l_value , channel_size[i]>>3);      /* Cji */
958                         p_pclr_header_data += channel_size[i]>>3;
959                         *entries = (OPJ_UINT32) l_value;
960                         entries++;
961                 }
962         }
963
964         return OPJ_TRUE;
965 }
966
967
968 static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio,
969         opj_jp2_box_t *box, opj_jp2_color_t *color)
970 {
971         opj_jp2_cmap_comp_t *cmap;
972         unsigned short i, nr_channels;
973
974         OPJ_ARG_NOT_USED(box);
975         OPJ_ARG_NOT_USED(jp2);
976
977 /* Need nr_channels: */
978         if(color->jp2_pclr == NULL) return OPJ_FALSE;
979
980 /* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box
981  * inside a JP2 Header box' :
982 */
983         if(color->jp2_pclr->cmap) return OPJ_FALSE;
984
985         nr_channels = color->jp2_pclr->nr_channels;
986         cmap = (opj_jp2_cmap_comp_t*)
987          opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t));
988
989         for(i = 0; i < nr_channels; ++i)
990    {
991         cmap[i].cmp = (unsigned short)cio_read(cio, 2);
992         cmap[i].mtyp = cio_read(cio, 1);
993         cmap[i].pcol = cio_read(cio, 1);
994
995    }
996         color->jp2_pclr->cmap = cmap;
997
998         return OPJ_TRUE;
999
1000 }/* jp2_read_cmap() */
1001
1002 /**
1003  * Reads the Component Mapping box.
1004  *
1005  * @param       p_cmap_header_data                      pointer to actual data (already read from file)
1006  * @param       jp2                                                     the jpeg2000 file codec.
1007  * @param       p_cmap_header_size                      pointer that will hold the size of the color header
1008  * @param       p_manager                                       the user event manager.
1009  *
1010  * @return      true if the cdef header is valid, false else.
1011 */
1012 static opj_bool jp2_read_cmap_v2(       opj_jp2_v2_t * jp2,
1013                                                         unsigned char * p_cmap_header_data,
1014                                                         OPJ_UINT32 p_cmap_header_size,
1015                                                         opj_event_mgr_t * p_manager
1016                                                   )
1017 {
1018         opj_jp2_cmap_comp_t *cmap;
1019         OPJ_BYTE i, nr_channels;
1020         OPJ_UINT32 l_value;
1021
1022         // preconditions
1023         assert(jp2 != 00);
1024         assert(p_cmap_header_data != 00);
1025         assert(p_manager != 00);
1026
1027         /* Need nr_channels: */
1028         if(jp2->color.jp2_pclr == NULL) {
1029                 opj_event_msg_v2(p_manager, EVT_ERROR, "Need to read a PCLR box before the CMAP box.\n");
1030                 return OPJ_FALSE;
1031         }
1032
1033         /* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box
1034          * inside a JP2 Header box' :
1035         */
1036         if(jp2->color.jp2_pclr->cmap) {
1037                 opj_event_msg_v2(p_manager, EVT_ERROR, "Only one CMAP box is allowed.\n");
1038                 return OPJ_FALSE;
1039         }
1040
1041         nr_channels = jp2->color.jp2_pclr->nr_channels;
1042         cmap = (opj_jp2_cmap_comp_t*) opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t));
1043
1044         for(i = 0; i < nr_channels; ++i) {
1045                 opj_read_bytes(p_cmap_header_data, &l_value, 2);                        /* CMP^i */
1046                 p_cmap_header_data +=2;
1047                 cmap[i].cmp = (OPJ_UINT16) l_value;
1048
1049                 opj_read_bytes(p_cmap_header_data, &l_value, 1);                        /* MTYP^i */
1050                 ++p_cmap_header_data;
1051                 cmap[i].mtyp = (OPJ_BYTE) l_value;
1052
1053                 opj_read_bytes(p_cmap_header_data, &l_value, 1);                        /* PCOL^i */
1054                 ++p_cmap_header_data;
1055                 cmap[i].pcol = (OPJ_BYTE) l_value;
1056         }
1057
1058         jp2->color.jp2_pclr->cmap = cmap;
1059
1060         return OPJ_TRUE;
1061 }
1062
1063 static void jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color)
1064 {
1065         opj_jp2_cdef_info_t *info;
1066         OPJ_INT32 color_space;
1067         OPJ_UINT16 i, n, cn, typ, asoc, acn;
1068
1069         color_space = image->color_space;
1070         info = color->jp2_cdef->info;
1071         n = color->jp2_cdef->n;
1072
1073         for(i = 0; i < n; ++i)
1074         {
1075                 /* WATCH: acn = asoc - 1 ! */
1076                 if((asoc = info[i].asoc) == 0) continue;
1077
1078                 cn = info[i].cn; typ = info[i].typ; acn = asoc - 1;
1079
1080                 if(cn != acn)
1081                 {
1082                         opj_image_comp_t saved;
1083
1084                         memcpy(&saved, &image->comps[cn], sizeof(opj_image_comp_t));
1085                         memcpy(&image->comps[cn], &image->comps[acn], sizeof(opj_image_comp_t));
1086                         memcpy(&image->comps[acn], &saved, sizeof(opj_image_comp_t));
1087
1088                         info[i].asoc = cn + 1;
1089                         info[acn].asoc = info[acn].cn + 1;
1090                 }
1091         }
1092
1093         if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info);
1094
1095         opj_free(color->jp2_cdef); color->jp2_cdef = NULL;
1096
1097 }/* jp2_apply_cdef() */
1098
1099 static opj_bool jp2_read_cdef(opj_jp2_t *jp2, opj_cio_t *cio,
1100         opj_jp2_box_t *box, opj_jp2_color_t *color)
1101 {
1102         opj_jp2_cdef_info_t *info;
1103         unsigned short i, n;
1104
1105         OPJ_ARG_NOT_USED(box);
1106         OPJ_ARG_NOT_USED(jp2);
1107
1108 /* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box
1109  * inside a JP2 Header box.' 
1110 */
1111         if(color->jp2_cdef) return OPJ_FALSE;
1112
1113         if((n = (unsigned short)cio_read(cio, 2)) == 0) return OPJ_FALSE; /* szukw000: FIXME */
1114
1115         info = (opj_jp2_cdef_info_t*)
1116          opj_malloc(n * sizeof(opj_jp2_cdef_info_t));
1117
1118         color->jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
1119         color->jp2_cdef->info = info;
1120         color->jp2_cdef->n = n;
1121
1122         for(i = 0; i < n; ++i)
1123    {
1124         info[i].cn = (unsigned short)cio_read(cio, 2);
1125         info[i].typ = (unsigned short)cio_read(cio, 2);
1126         info[i].asoc = (unsigned short)cio_read(cio, 2);
1127
1128    }
1129         return OPJ_TRUE;
1130 }/* jp2_read_cdef() */
1131
1132 /**
1133  * Reads the Component Definition box.
1134  *
1135  * @param       p_cdef_header_data                      pointer to actual data (already read from file)
1136  * @param       jp2                                                     the jpeg2000 file codec.
1137  * @param       p_cdef_header_size                      pointer that will hold the size of the color header
1138  * @param       p_manager                                       the user event manager.
1139  *
1140  * @return      true if the cdef header is valid, false else.
1141 */
1142 static opj_bool jp2_read_cdef_v2(       opj_jp2_v2_t * jp2,
1143                                                         unsigned char * p_cdef_header_data,
1144                                                         OPJ_UINT32 p_cdef_header_size,
1145                                                         opj_event_mgr_t * p_manager
1146                                                   )
1147 {
1148         opj_jp2_cdef_info_t *cdef_info;
1149         unsigned short i;
1150         OPJ_UINT32 l_value;
1151
1152         // preconditions
1153         assert(jp2 != 00);
1154         assert(p_cdef_header_data != 00);
1155         assert(p_manager != 00);
1156
1157         /* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box
1158          * inside a JP2 Header box.'*/
1159         if(jp2->color.jp2_cdef) return OPJ_FALSE;
1160
1161         opj_read_bytes(p_cdef_header_data,&l_value ,2);                 /* N */
1162         p_cdef_header_data+= 2;
1163
1164         if ( (OPJ_UINT16)l_value == 0){ /* szukw000: FIXME */
1165                 opj_event_msg_v2(p_manager, EVT_ERROR, "Number of channel description is equal to zero in CDEF box.\n");
1166                 return OPJ_FALSE;
1167         }
1168
1169         cdef_info = (opj_jp2_cdef_info_t*) opj_malloc(l_value * sizeof(opj_jp2_cdef_info_t));
1170
1171         jp2->color.jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
1172         jp2->color.jp2_cdef->info = cdef_info;
1173         jp2->color.jp2_cdef->n = (OPJ_UINT16) l_value;
1174
1175         for(i = 0; i < jp2->color.jp2_cdef->n; ++i) {
1176                 opj_read_bytes(p_cdef_header_data, &l_value, 2);                        /* Cn^i */
1177                 p_cdef_header_data +=2;
1178                 cdef_info[i].cn = (OPJ_UINT16) l_value;
1179
1180                 opj_read_bytes(p_cdef_header_data, &l_value, 2);                        /* Typ^i */
1181                 p_cdef_header_data +=2;
1182                 cdef_info[i].typ = (OPJ_UINT16) l_value;
1183
1184                 opj_read_bytes(p_cdef_header_data, &l_value, 2);                        /* Asoc^i */
1185                 p_cdef_header_data +=2;
1186                 cdef_info[i].asoc = (OPJ_UINT16) l_value;
1187    }
1188
1189         return OPJ_TRUE;
1190 }
1191
1192
1193 static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio,
1194         opj_jp2_box_t *box, opj_jp2_color_t *color) 
1195 {
1196         int skip_len;
1197     opj_common_ptr cinfo;
1198
1199 /* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour
1200  * Specification boxes after the first.' 
1201 */
1202         if(color->jp2_has_colr) return OPJ_FALSE;
1203
1204         cinfo = jp2->cinfo;
1205
1206         jp2->meth = cio_read(cio, 1);           /* METH */
1207         jp2->precedence = cio_read(cio, 1);     /* PRECEDENCE */
1208         jp2->approx = cio_read(cio, 1);         /* APPROX */
1209
1210         if (jp2->meth == 1) 
1211    {
1212         jp2->enumcs = cio_read(cio, 4); /* EnumCS */
1213    } 
1214         else
1215         if (jp2->meth == 2) 
1216    {
1217 /* skip PROFILE */
1218         skip_len = box->init_pos + box->length - cio_tell(cio);
1219         if (skip_len < 0) 
1220   {
1221         opj_event_msg(cinfo, EVT_ERROR, "Error with COLR box size\n");
1222         return OPJ_FALSE;
1223   }
1224         if(skip_len > 0)
1225   {
1226         unsigned char *start;
1227
1228         start = cio_getbp(cio);
1229         color->icc_profile_buf = (unsigned char*)opj_malloc(skip_len);
1230         color->icc_profile_len = skip_len;
1231
1232         cio_skip(cio, box->init_pos + box->length - cio_tell(cio));
1233
1234         memcpy(color->icc_profile_buf, start, skip_len);
1235   }
1236    }
1237
1238         if (cio_tell(cio) - box->init_pos != box->length) 
1239    {
1240         opj_event_msg(cinfo, EVT_ERROR, "Error with COLR Box\n");
1241         return OPJ_FALSE;
1242    }
1243         color->jp2_has_colr = 1;
1244
1245         return OPJ_TRUE;
1246 }/* jp2_read_colr() */
1247
1248 /**
1249  * Reads the Colour Specification box.
1250  *
1251  * @param       p_colr_header_data                      pointer to actual data (already read from file)
1252  * @param       jp2                                                     the jpeg2000 file codec.
1253  * @param       p_colr_header_size                      pointer that will hold the size of the color header
1254  * @param       p_colr_header_max_size          maximum size of the header, any size bigger than this value should result the function to output false.
1255  * @param       p_manager                                       the user event manager.
1256  *
1257  * @return      true if the bpc header is valid, fale else.
1258 */
1259 static opj_bool jp2_read_colr_v2(       opj_jp2_v2_t * jp2,
1260                                                         unsigned char * p_colr_header_data,
1261                                                         OPJ_UINT32 p_colr_header_size,
1262                                                         opj_event_mgr_t * p_manager
1263                                                   )
1264 {
1265         OPJ_UINT32 l_value;
1266
1267         // preconditions
1268         assert(jp2 != 00);
1269         assert(p_colr_header_data != 00);
1270         assert(p_manager != 00);
1271
1272         if (p_colr_header_size < 3) {
1273                 opj_event_msg_v2(p_manager, EVT_ERROR, "Bad COLR header box (bad size)\n");
1274                 return OPJ_FALSE;
1275         }
1276
1277         /* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour
1278          * Specification boxes after the first.'
1279         */
1280         if(jp2->color.jp2_has_colr) {
1281                 opj_event_msg_v2(p_manager, EVT_INFO, "A conforming JP2 reader shall ignore all Colour Specification boxes after the first, so we ignore this one.\n");
1282                 p_colr_header_data += p_colr_header_size;
1283                 return OPJ_TRUE;
1284         }
1285
1286         opj_read_bytes(p_colr_header_data,&jp2->meth ,1);                       /* METH */
1287         ++p_colr_header_data;
1288
1289         opj_read_bytes(p_colr_header_data,&jp2->precedence ,1);         /* PRECEDENCE */
1290         ++p_colr_header_data;
1291
1292         opj_read_bytes(p_colr_header_data,&jp2->approx ,1);                     /* APPROX */
1293         ++p_colr_header_data;
1294
1295         if (jp2->meth == 1) {
1296                 if (p_colr_header_size != 7) {
1297                         opj_event_msg_v2(p_manager, EVT_ERROR, "Bad BPCC header box (bad size)\n");
1298                         return OPJ_FALSE;
1299                 }
1300
1301                 opj_read_bytes(p_colr_header_data,&jp2->enumcs ,4);                     /* EnumCS */
1302         }
1303         else if (jp2->meth == 2) {
1304                 // ICC profile
1305                 int it_icc_value = 0;
1306                 int icc_len = p_colr_header_size - 3;
1307
1308                 jp2->color.icc_profile_len = icc_len;
1309                 jp2->color.icc_profile_buf = (unsigned char*) opj_malloc(icc_len);
1310
1311                 memset(jp2->color.icc_profile_buf, 0, icc_len * sizeof(unsigned char));
1312
1313                 for (it_icc_value = 0; it_icc_value < icc_len; ++it_icc_value)
1314                 {
1315                         opj_read_bytes(p_colr_header_data,&l_value,1);          /* icc values */
1316                         ++p_colr_header_data;
1317                         jp2->color.icc_profile_buf[it_icc_value] = (OPJ_BYTE) l_value;
1318                 }
1319
1320         }
1321         else // TODO MSD
1322                 opj_event_msg_v2(p_manager, EVT_INFO, "COLR BOX meth value is not a regular value (%d), so we will skip the fields following the approx field.\n", jp2->meth);
1323
1324         jp2->color.jp2_has_colr = 1;
1325
1326         return OPJ_TRUE;
1327 }
1328
1329 opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color) 
1330 {
1331         opj_jp2_box_t box;
1332         int jp2h_end;
1333
1334         opj_common_ptr cinfo = jp2->cinfo;
1335
1336         jp2_read_boxhdr(cinfo, cio, &box);
1337         do 
1338    {
1339         if (JP2_JP2H != box.type) 
1340   {
1341         if (box.type == JP2_JP2C) 
1342  {
1343         opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
1344         return OPJ_FALSE;
1345  }
1346         cio_skip(cio, box.length - 8);
1347
1348         if(cio->bp >= cio->end) return OPJ_FALSE;
1349
1350         jp2_read_boxhdr(cinfo, cio, &box);
1351   }
1352    } while(JP2_JP2H != box.type);
1353
1354         if (!jp2_read_ihdr(jp2, cio))
1355                 return OPJ_FALSE;
1356         jp2h_end = box.init_pos + box.length;
1357
1358         if (jp2->bpc == 255) 
1359    {
1360         if (!jp2_read_bpcc(jp2, cio))
1361                 return OPJ_FALSE;
1362    }
1363         jp2_read_boxhdr(cinfo, cio, &box);
1364
1365         while(cio_tell(cio) < jp2h_end)
1366    {
1367         if(box.type == JP2_COLR)
1368   {
1369         if( !jp2_read_colr(jp2, cio, &box, color))
1370  {
1371     cio_seek(cio, box.init_pos + 8);
1372     cio_skip(cio, box.length - 8);
1373  }
1374     jp2_read_boxhdr(cinfo, cio, &box);
1375     continue;
1376   }
1377     if(box.type == JP2_CDEF && !jp2->ignore_pclr_cmap_cdef)
1378   {
1379     if( !jp2_read_cdef(jp2, cio, &box, color))
1380  {
1381     cio_seek(cio, box.init_pos + 8);
1382     cio_skip(cio, box.length - 8);
1383  }
1384     jp2_read_boxhdr(cinfo, cio, &box);
1385     continue;
1386   }
1387     if(box.type == JP2_PCLR && !jp2->ignore_pclr_cmap_cdef)
1388   {
1389     if( !jp2_read_pclr(jp2, cio, &box, color))
1390  {
1391     cio_seek(cio, box.init_pos + 8);
1392     cio_skip(cio, box.length - 8);
1393  }
1394     jp2_read_boxhdr(cinfo, cio, &box);
1395     continue;
1396   }
1397     if(box.type == JP2_CMAP && !jp2->ignore_pclr_cmap_cdef)
1398   {
1399     if( !jp2_read_cmap(jp2, cio, &box, color))
1400  {
1401     cio_seek(cio, box.init_pos + 8);
1402     cio_skip(cio, box.length - 8);
1403  }
1404     jp2_read_boxhdr(cinfo, cio, &box);
1405     continue;
1406   }
1407         cio_seek(cio, box.init_pos + 8);
1408         cio_skip(cio, box.length - 8);
1409         jp2_read_boxhdr(cinfo, cio, &box);
1410
1411    }/* while(cio_tell(cio) < box_end) */
1412
1413         cio_seek(cio, jp2h_end);
1414
1415 /* Part 1, I.5.3.3 : 'must contain at least one' */
1416         return (color->jp2_has_colr == 1);
1417
1418 }/* jp2_read_jp2h() */
1419
1420 opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, 
1421         opj_codestream_info_t *cstr_info) 
1422 {
1423         opj_common_ptr cinfo;
1424         opj_image_t *image = NULL;
1425         opj_jp2_color_t color;
1426
1427         if(!jp2 || !cio) 
1428    {
1429         return NULL;
1430    }
1431         memset(&color, 0, sizeof(opj_jp2_color_t));
1432         cinfo = jp2->cinfo;
1433
1434 /* JP2 decoding */
1435         if(!jp2_read_struct(jp2, cio, &color)) 
1436    {
1437         free_color_data(&color);
1438         opj_event_msg(cinfo, EVT_ERROR, "Failed to decode jp2 structure\n");
1439         return NULL;
1440    }
1441
1442 /* J2K decoding */
1443         image = j2k_decode(jp2->j2k, cio, cstr_info);
1444
1445         if(!image) 
1446    {
1447         free_color_data(&color);
1448         opj_event_msg(cinfo, EVT_ERROR, "Failed to decode J2K image\n");
1449         return NULL;
1450    }
1451    
1452     if (!jp2->ignore_pclr_cmap_cdef){
1453
1454     /* Set Image Color Space */
1455         if (jp2->enumcs == 16)
1456                 image->color_space = CLRSPC_SRGB;
1457         else if (jp2->enumcs == 17)
1458                 image->color_space = CLRSPC_GRAY;
1459         else if (jp2->enumcs == 18)
1460                 image->color_space = CLRSPC_SYCC;
1461         else
1462                 image->color_space = CLRSPC_UNKNOWN;
1463
1464         if(color.jp2_cdef)
1465    {
1466         jp2_apply_cdef(image, &color);
1467    }
1468         if(color.jp2_pclr)
1469    {
1470 /* Part 1, I.5.3.4: Either both or none : */
1471         if( !color.jp2_pclr->cmap) 
1472          jp2_free_pclr(&color);
1473         else
1474          jp2_apply_pclr(image, &color);
1475    }
1476         if(color.icc_profile_buf)
1477    {
1478         image->icc_profile_buf = color.icc_profile_buf;
1479         color.icc_profile_buf = NULL;
1480         image->icc_profile_len = color.icc_profile_len;
1481    }
1482    }
1483    
1484         return image;
1485
1486 }/* opj_jp2_decode() */
1487
1488 opj_bool jp2_decode_v2( opj_jp2_v2_t *jp2,
1489                                                 struct opj_stream_private *cio,
1490                                                 opj_image_t* p_image,
1491                                                 struct opj_event_mgr * p_manager)
1492 {
1493         if (!p_image)
1494                 return OPJ_FALSE;
1495
1496         /* J2K decoding */
1497         if( ! j2k_decode_v2(jp2->j2k, cio, p_image, p_manager) ) {
1498                 opj_event_msg_v2(p_manager, EVT_ERROR, "Failed to decode the codestream in the JP2 file\n");
1499                 return OPJ_FALSE;
1500         }
1501
1502         /* Set Image Color Space */
1503         if (jp2->enumcs == 16)
1504                 p_image->color_space = CLRSPC_SRGB;
1505         else if (jp2->enumcs == 17)
1506                 p_image->color_space = CLRSPC_GRAY;
1507         else if (jp2->enumcs == 18)
1508                 p_image->color_space = CLRSPC_SYCC;
1509         else
1510                 p_image->color_space = CLRSPC_UNKNOWN;
1511
1512         /* Apply the color space if needed */
1513         if(jp2->color.jp2_cdef) {
1514                 jp2_apply_cdef(p_image, &(jp2->color));
1515         }
1516
1517         if(jp2->color.jp2_pclr) {
1518                 /* Part 1, I.5.3.4: Either both or none : */
1519                 if( !jp2->color.jp2_pclr->cmap)
1520                         jp2_free_pclr(&(jp2->color));
1521                 else
1522                         jp2_apply_pclr(p_image, &(jp2->color));
1523         }
1524
1525         if(jp2->color.icc_profile_buf) {
1526                 p_image->icc_profile_buf = jp2->color.icc_profile_buf;
1527                 p_image->icc_profile_len = jp2->color.icc_profile_len;
1528                 jp2->color.icc_profile_buf = NULL;
1529         }
1530
1531         return OPJ_TRUE;
1532 }
1533
1534
1535 void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) {
1536         opj_jp2_box_t box;
1537
1538         box.init_pos = cio_tell(cio);
1539         cio_skip(cio, 4);
1540         cio_write(cio, JP2_JP2H, 4);    /* JP2H */
1541
1542         jp2_write_ihdr(jp2, cio);
1543
1544         if (jp2->bpc == 255) {
1545                 jp2_write_bpcc(jp2, cio);
1546         }
1547         jp2_write_colr(jp2, cio);
1548
1549         box.length = cio_tell(cio) - box.init_pos;
1550         cio_seek(cio, box.init_pos);
1551         cio_write(cio, box.length, 4);  /* L */
1552         cio_seek(cio, box.init_pos + box.length);
1553 }
1554
1555 static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
1556         unsigned int i;
1557         opj_jp2_box_t box;
1558
1559         box.init_pos = cio_tell(cio);
1560         cio_skip(cio, 4);
1561         cio_write(cio, JP2_FTYP, 4);            /* FTYP */
1562
1563         cio_write(cio, jp2->brand, 4);          /* BR */
1564         cio_write(cio, jp2->minversion, 4);     /* MinV */
1565
1566         for (i = 0; i < jp2->numcl; i++) {
1567                 cio_write(cio, jp2->cl[i], 4);  /* CL */
1568         }
1569
1570         box.length = cio_tell(cio) - box.init_pos;
1571         cio_seek(cio, box.init_pos);
1572         cio_write(cio, box.length, 4);  /* L */
1573         cio_seek(cio, box.init_pos + box.length);
1574 }
1575
1576 static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
1577         int i;
1578         opj_jp2_box_t box;
1579
1580         opj_common_ptr cinfo = jp2->cinfo;
1581
1582         jp2_read_boxhdr(cinfo, cio, &box);
1583
1584         if (JP2_FTYP != box.type) {
1585                 opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
1586                 return OPJ_FALSE;
1587         }
1588
1589         jp2->brand = cio_read(cio, 4);          /* BR */
1590         jp2->minversion = cio_read(cio, 4);     /* MinV */
1591         jp2->numcl = (box.length - 16) / 4;
1592         jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
1593
1594         for (i = 0; i < (int)jp2->numcl; i++) {
1595                 jp2->cl[i] = cio_read(cio, 4);  /* CLi */
1596         }
1597
1598         if (cio_tell(cio) - box.init_pos != box.length) {
1599                 opj_event_msg(cinfo, EVT_ERROR, "Error with FTYP Box\n");
1600                 return OPJ_FALSE;
1601         }
1602
1603         return OPJ_TRUE;
1604 }
1605
1606 static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
1607         unsigned int j2k_codestream_offset, j2k_codestream_length;
1608         opj_jp2_box_t box;
1609
1610         opj_j2k_t *j2k = jp2->j2k;
1611
1612         box.init_pos = cio_tell(cio);
1613         cio_skip(cio, 4);
1614         cio_write(cio, JP2_JP2C, 4);    /* JP2C */
1615
1616         /* J2K encoding */
1617         j2k_codestream_offset = cio_tell(cio);
1618         if(!j2k_encode(j2k, cio, image, cstr_info)) {
1619                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Failed to encode image\n");
1620                 return 0;
1621         }
1622         j2k_codestream_length = cio_tell(cio) - j2k_codestream_offset;
1623
1624         jp2->j2k_codestream_offset = j2k_codestream_offset;
1625         jp2->j2k_codestream_length = j2k_codestream_length;
1626
1627         box.length = 8 + jp2->j2k_codestream_length;
1628         cio_seek(cio, box.init_pos);
1629         cio_write(cio, box.length, 4);  /* L */
1630         cio_seek(cio, box.init_pos + box.length);
1631
1632         return box.length;
1633 }
1634
1635 static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset) {
1636         opj_jp2_box_t box;
1637
1638         opj_common_ptr cinfo = jp2->cinfo;
1639
1640         jp2_read_boxhdr(cinfo, cio, &box);
1641         do {
1642                 if(JP2_JP2C != box.type) {
1643                         cio_skip(cio, box.length - 8);
1644                         jp2_read_boxhdr(cinfo, cio, &box);
1645                 }
1646         } while(JP2_JP2C != box.type);
1647
1648         *j2k_codestream_offset = cio_tell(cio);
1649         *j2k_codestream_length = box.length - 8;
1650
1651         return OPJ_TRUE;
1652 }
1653
1654 static void jp2_write_jp(opj_cio_t *cio) {
1655         opj_jp2_box_t box;
1656
1657         box.init_pos = cio_tell(cio);
1658         cio_skip(cio, 4);
1659         cio_write(cio, JP2_JP, 4);              /* JP2 signature */
1660         cio_write(cio, 0x0d0a870a, 4);
1661
1662         box.length = cio_tell(cio) - box.init_pos;
1663         cio_seek(cio, box.init_pos);
1664         cio_write(cio, box.length, 4);  /* L */
1665         cio_seek(cio, box.init_pos + box.length);
1666 }
1667
1668 static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
1669         opj_jp2_box_t box;
1670
1671         opj_common_ptr cinfo = jp2->cinfo;
1672
1673         jp2_read_boxhdr(cinfo, cio, &box);
1674         if (JP2_JP != box.type) {
1675                 opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
1676                 return OPJ_FALSE;
1677         }
1678         if (0x0d0a870a != cio_read(cio, 4)) {
1679                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Marker\n");
1680                 return OPJ_FALSE;
1681         }
1682         if (cio_tell(cio) - box.init_pos != box.length) {
1683                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Box size\n");
1684                 return OPJ_FALSE;
1685         }
1686
1687         return OPJ_TRUE;
1688 }
1689
1690
1691 static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
1692         opj_jp2_color_t *color) {
1693         if (!jp2_read_jp(jp2, cio))
1694                 return OPJ_FALSE;
1695         if (!jp2_read_ftyp(jp2, cio))
1696                 return OPJ_FALSE;
1697         if (!jp2_read_jp2h(jp2, cio, color))
1698                 return OPJ_FALSE;
1699         if (!jp2_read_jp2c(jp2, cio, &jp2->j2k_codestream_length, &jp2->j2k_codestream_offset))
1700                 return OPJ_FALSE;
1701         
1702         return OPJ_TRUE;
1703 }
1704
1705
1706 static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
1707 {  
1708   int len, lenp;
1709   
1710   lenp = cio_tell( cio);
1711   cio_skip( cio, 4);              /* L [at the end] */
1712   cio_write( cio, JPIP_FIDX, 4);  /* IPTR           */
1713   
1714   write_prxy( offset_jp2c, length_jp2c, offset_idx, length_idx, cio);
1715
1716   len = cio_tell( cio)-lenp;
1717   cio_seek( cio, lenp);
1718   cio_write( cio, len, 4);        /* L              */
1719   cio_seek( cio, lenp+len);  
1720
1721   return len;
1722 }
1723
1724 static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
1725 {
1726   int len, lenp;
1727
1728   lenp = cio_tell( cio);
1729   cio_skip( cio, 4);              /* L [at the end] */
1730   cio_write( cio, JPIP_PRXY, 4);  /* IPTR           */
1731   
1732   cio_write( cio, offset_jp2c, 8); /* OOFF           */
1733   cio_write( cio, length_jp2c, 4); /* OBH part 1     */
1734   cio_write( cio, JP2_JP2C, 4);        /* OBH part 2     */
1735   
1736   cio_write( cio, 1,1);           /* NI             */
1737
1738   cio_write( cio, offset_idx, 8);  /* IOFF           */
1739   cio_write( cio, length_idx, 4);  /* IBH part 1     */
1740   cio_write( cio, JPIP_CIDX, 4);   /* IBH part 2     */
1741
1742   len = cio_tell( cio)-lenp;
1743   cio_seek( cio, lenp);
1744   cio_write( cio, len, 4);        /* L              */
1745   cio_seek( cio, lenp+len);
1746 }
1747
1748 static void write_iptr( int offset, int length, opj_cio_t *cio)
1749 {
1750   int len, lenp;
1751   
1752   lenp = cio_tell( cio);
1753   cio_skip( cio, 4);              /* L [at the end] */
1754   cio_write( cio, JPIP_IPTR, 4);  /* IPTR           */
1755   
1756   cio_write( cio, offset, 8);
1757   cio_write( cio, length, 8);
1758
1759   len = cio_tell( cio)-lenp;
1760   cio_seek( cio, lenp);
1761   cio_write( cio, len, 4);        /* L             */
1762   cio_seek( cio, lenp+len);
1763 }
1764
1765
1766 /* ----------------------------------------------------------------------- */
1767 /* JP2 decoder interface                                             */
1768 /* ----------------------------------------------------------------------- */
1769
1770 opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo) {
1771         opj_jp2_t *jp2 = (opj_jp2_t*) opj_calloc(1, sizeof(opj_jp2_t));
1772         if(jp2) {
1773                 jp2->cinfo = cinfo;
1774                 /* create the J2K codec */
1775                 jp2->j2k = j2k_create_decompress(cinfo);
1776                 if(jp2->j2k == NULL) {
1777                         jp2_destroy_decompress(jp2);
1778                         return NULL;
1779                 }
1780         }
1781         return jp2;
1782 }
1783
1784 void jp2_destroy_decompress(opj_jp2_t *jp2) {
1785         if(jp2) {
1786                 /* destroy the J2K codec */
1787                 j2k_destroy_decompress(jp2->j2k);
1788
1789                 if(jp2->comps) {
1790                         opj_free(jp2->comps);
1791                 }
1792                 if(jp2->cl) {
1793                         opj_free(jp2->cl);
1794                 }
1795                 opj_free(jp2);
1796         }
1797 }
1798
1799 void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
1800         /* setup the J2K codec */
1801         j2k_setup_decoder(jp2->j2k, parameters);
1802         /* further JP2 initializations go here */
1803         jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
1804 }
1805
1806 void jp2_setup_decoder_v2(opj_jp2_v2_t *jp2, opj_dparameters_t *parameters)
1807 {
1808         /* setup the J2K codec */
1809         j2k_setup_decoder_v2(jp2->j2k, parameters);
1810
1811         /* further JP2 initializations go here */
1812         jp2->color.jp2_has_colr = 0;
1813 }
1814
1815
1816 /* ----------------------------------------------------------------------- */
1817 /* JP2 encoder interface                                             */
1818 /* ----------------------------------------------------------------------- */
1819
1820 opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
1821         opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
1822         if(jp2) {
1823                 jp2->cinfo = cinfo;
1824                 /* create the J2K codec */
1825                 jp2->j2k = j2k_create_compress(cinfo);
1826                 if(jp2->j2k == NULL) {
1827                         jp2_destroy_compress(jp2);
1828                         return NULL;
1829                 }
1830         }
1831         return jp2;
1832 }
1833
1834 void jp2_destroy_compress(opj_jp2_t *jp2) {
1835         if(jp2) {
1836                 /* destroy the J2K codec */
1837                 j2k_destroy_compress(jp2->j2k);
1838
1839                 if(jp2->comps) {
1840                         opj_free(jp2->comps);
1841                 }
1842                 if(jp2->cl) {
1843                         opj_free(jp2->cl);
1844                 }
1845                 opj_free(jp2);
1846         }
1847 }
1848
1849 void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image) {
1850         int i;
1851         int depth_0, sign;
1852
1853         if(!jp2 || !parameters || !image)
1854                 return;
1855
1856         /* setup the J2K codec */
1857         /* ------------------- */
1858
1859         /* Check if number of components respects standard */
1860         if (image->numcomps < 1 || image->numcomps > 16384) {
1861                 opj_event_msg(jp2->cinfo, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
1862                 return;
1863         }
1864
1865         j2k_setup_encoder(jp2->j2k, parameters, image);
1866
1867         /* setup the JP2 codec */
1868         /* ------------------- */
1869         
1870         /* Profile box */
1871
1872         jp2->brand = JP2_JP2;   /* BR */
1873         jp2->minversion = 0;    /* MinV */
1874         jp2->numcl = 1;
1875         jp2->cl = (unsigned int*) opj_malloc(jp2->numcl * sizeof(unsigned int));
1876         jp2->cl[0] = JP2_JP2;   /* CL0 : JP2 */
1877
1878         /* Image Header box */
1879
1880         jp2->numcomps = image->numcomps;        /* NC */
1881         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
1882         jp2->h = image->y1 - image->y0;         /* HEIGHT */
1883         jp2->w = image->x1 - image->x0;         /* WIDTH */
1884         /* BPC */
1885         depth_0 = image->comps[0].prec - 1;
1886         sign = image->comps[0].sgnd;
1887         jp2->bpc = depth_0 + (sign << 7);
1888         for (i = 1; i < image->numcomps; i++) {
1889                 int depth = image->comps[i].prec - 1;
1890                 sign = image->comps[i].sgnd;
1891                 if (depth_0 != depth)
1892                         jp2->bpc = 255;
1893         }
1894         jp2->C = 7;                     /* C : Always 7 */
1895         jp2->UnkC = 0;          /* UnkC, colorspace specified in colr box */
1896         jp2->IPR = 0;           /* IPR, no intellectual property */
1897         
1898         /* BitsPerComponent box */
1899
1900         for (i = 0; i < image->numcomps; i++) {
1901                 jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
1902         }
1903         jp2->meth = 1;
1904         if (image->color_space == 1)
1905                 jp2->enumcs = 16;       /* sRGB as defined by IEC 61966-2.1 */
1906         else if (image->color_space == 2)
1907                 jp2->enumcs = 17;       /* greyscale */
1908         else if (image->color_space == 3)
1909                 jp2->enumcs = 18;       /* YUV */
1910         jp2->precedence = 0;    /* PRECEDENCE */
1911         jp2->approx = 0;                /* APPROX */
1912         
1913         jp2->jpip_on = parameters->jpip_on;
1914 }
1915
1916 opj_bool opj_jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
1917
1918         int pos_iptr, pos_cidx, pos_jp2c, len_jp2c, len_cidx, end_pos, pos_fidx, len_fidx;
1919         pos_jp2c = pos_iptr = -1; /* remove a warning */
1920
1921         /* JP2 encoding */
1922
1923         /* JPEG 2000 Signature box */
1924         jp2_write_jp(cio);
1925         /* File Type box */
1926         jp2_write_ftyp(jp2, cio);
1927         /* JP2 Header box */
1928         jp2_write_jp2h(jp2, cio);
1929
1930         if( jp2->jpip_on){
1931           pos_iptr = cio_tell( cio);
1932           cio_skip( cio, 24); /* IPTR further ! */
1933           
1934           pos_jp2c = cio_tell( cio);
1935         }
1936
1937         /* J2K encoding */
1938         if(!(len_jp2c = jp2_write_jp2c( jp2, cio, image, cstr_info))){
1939             opj_event_msg(jp2->cinfo, EVT_ERROR, "Failed to encode image\n");
1940             return OPJ_FALSE;
1941         }
1942
1943         if( jp2->jpip_on){
1944           pos_cidx = cio_tell( cio);
1945           
1946           len_cidx = write_cidx( pos_jp2c+8, cio, image, *cstr_info, len_jp2c-8);
1947           
1948           pos_fidx = cio_tell( cio);
1949           len_fidx = write_fidx( pos_jp2c, len_jp2c, pos_cidx, len_cidx, cio);
1950           
1951           end_pos = cio_tell( cio);
1952           
1953           cio_seek( cio, pos_iptr);
1954           write_iptr( pos_fidx, len_fidx, cio);
1955                   cio_seek( cio, end_pos);
1956         }
1957
1958         return OPJ_TRUE;
1959 }
1960
1961 /**
1962  * Ends the decompression procedures and possibiliy add data to be read after the
1963  * codestream.
1964  */
1965 opj_bool jp2_end_decompress(opj_jp2_v2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager)
1966 {
1967         // preconditions
1968         assert(jp2 != 00);
1969         assert(cio != 00);
1970         assert(p_manager != 00);
1971
1972         /* customization of the end encoding */
1973         jp2_setup_end_header_reading(jp2);
1974
1975         /* write header */
1976         if (! jp2_exec (jp2,jp2->m_procedure_list,cio,p_manager)) {
1977                 return OPJ_FALSE;
1978         }
1979
1980         return j2k_end_decompress(jp2->j2k, cio, p_manager);
1981 }
1982
1983 /**
1984  * Sets up the procedures to do on reading header after the codestream.
1985  * Developpers wanting to extend the library can add their own writting procedures.
1986  */
1987 void jp2_setup_end_header_reading (opj_jp2_v2_t *jp2)
1988 {
1989         // preconditions
1990         assert(jp2 != 00);
1991         opj_procedure_list_add_procedure(jp2->m_procedure_list,(void*)jp2_read_header_procedure );
1992         /* DEVELOPER CORNER, add your custom procedures */
1993 }
1994
1995
1996 /**
1997  * Reads a jpeg2000 file header structure.
1998  *
1999  * @param cio the stream to read data from.
2000  * @param jp2 the jpeg2000 file header structure.
2001  * @param p_manager the user event manager.
2002  *
2003  * @return true if the box is valid.
2004  */
2005 opj_bool jp2_read_header_procedure(
2006                                          opj_jp2_v2_t *jp2,
2007                                          opj_stream_private_t *cio,
2008                                          opj_event_mgr_t * p_manager)
2009 {
2010         opj_jp2_box_t box;
2011         OPJ_UINT32 l_nb_bytes_read;
2012         const opj_jp2_header_handler_t * l_current_handler;
2013         OPJ_UINT32 l_last_data_size = BOX_SIZE;
2014         OPJ_UINT32 l_current_data_size;
2015         unsigned char * l_current_data = 00;
2016
2017         // preconditions
2018         assert(cio != 00);
2019         assert(jp2 != 00);
2020         assert(p_manager != 00);
2021
2022         l_current_data = (unsigned char*)opj_malloc(l_last_data_size);
2023
2024         if (l_current_data == 00) {
2025                 opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory to handle jpeg2000 file header\n");
2026                 return OPJ_FALSE;
2027         }
2028         memset(l_current_data, 0 , l_last_data_size);
2029
2030         while (jp2_read_boxhdr_v2(&box,&l_nb_bytes_read,cio,p_manager)) {
2031                 // is it the codestream box ?
2032                 if (box.type == JP2_JP2C) {
2033                         if (jp2->jp2_state & JP2_STATE_HEADER) {
2034                                 jp2->jp2_state |= JP2_STATE_CODESTREAM;
2035                 opj_free(l_current_data);
2036                                 return OPJ_TRUE;
2037                         }
2038                         else {
2039                                 opj_event_msg_v2(p_manager, EVT_ERROR, "bad placed jpeg codestream\n");
2040                                 opj_free(l_current_data);
2041                                 return OPJ_FALSE;
2042                         }
2043                 }
2044                 else if (box.length == 0) {
2045                         opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
2046                         opj_free(l_current_data);
2047                         return OPJ_FALSE;
2048                 }
2049
2050                 l_current_handler = jp2_find_handler(box.type);
2051                 l_current_data_size = box.length - l_nb_bytes_read;
2052
2053                 if (l_current_handler != 00) {
2054                         if (l_current_data_size > l_last_data_size) {
2055                                 l_current_data = (unsigned char*)opj_realloc(l_current_data,l_current_data_size);
2056                                 if (!l_current_data){
2057                                         opj_free(l_current_data);
2058                                         return OPJ_FALSE;
2059                                 }
2060                                 l_last_data_size = l_current_data_size;
2061                         }
2062
2063                         l_nb_bytes_read = opj_stream_read_data(cio,l_current_data,l_current_data_size,p_manager);
2064                         if (l_nb_bytes_read != l_current_data_size) {
2065                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Problem with reading JPEG2000 box, stream error\n");
2066                                 return OPJ_FALSE;
2067                         }
2068
2069                         if (! l_current_handler->handler(jp2,l_current_data,l_current_data_size,p_manager)) {
2070                                 opj_free(l_current_data);
2071                                 return OPJ_FALSE;
2072                         }
2073                 }
2074                 else {
2075                         jp2->jp2_state |= JP2_STATE_UNKNOWN;
2076                         if (opj_stream_skip(cio,l_current_data_size,p_manager) != l_current_data_size) {
2077                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Problem with skipping JPEG2000 box, stream error\n");
2078                                 opj_free(l_current_data);
2079                                 return OPJ_FALSE;
2080                         }
2081                 }
2082         }
2083
2084         opj_free(l_current_data);
2085
2086         return OPJ_TRUE;
2087 }
2088
2089 /**
2090  * Excutes the given procedures on the given codec.
2091  *
2092  * @param       p_procedure_list        the list of procedures to execute
2093  * @param       jp2                                     the jpeg2000 file codec to execute the procedures on.
2094  * @param       cio                                     the stream to execute the procedures on.
2095  * @param       p_manager                       the user manager.
2096  *
2097  * @return      true                            if all the procedures were successfully executed.
2098  */
2099 opj_bool jp2_exec (
2100                                         opj_jp2_v2_t * jp2,
2101                                         opj_procedure_list_t * p_procedure_list,
2102                                         opj_stream_private_t *cio,
2103                                         opj_event_mgr_t * p_manager
2104                                   )
2105 {
2106         opj_bool (** l_procedure) (opj_jp2_v2_t * jp2, opj_stream_private_t *, opj_event_mgr_t *) = 00;
2107         opj_bool l_result = OPJ_TRUE;
2108         OPJ_UINT32 l_nb_proc, i;
2109
2110         // preconditions
2111         assert(p_procedure_list != 00);
2112         assert(jp2 != 00);
2113         assert(cio != 00);
2114         assert(p_manager != 00);
2115
2116         l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list);
2117         l_procedure = (opj_bool (**) (opj_jp2_v2_t * jp2, opj_stream_private_t *, opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list);
2118
2119         for     (i=0;i<l_nb_proc;++i) {
2120                 l_result = l_result && (*l_procedure) (jp2,cio,p_manager);
2121                 ++l_procedure;
2122         }
2123
2124         // and clear the procedure list at the end.
2125         opj_procedure_list_clear(p_procedure_list);
2126         return l_result;
2127 }
2128
2129
2130 /**
2131  * Finds the execution function related to the given box id.
2132  *
2133  * @param       p_id    the id of the handler to fetch.
2134  *
2135  * @return      the given handler or 00 if it could not be found.
2136  */
2137 const opj_jp2_header_handler_t * jp2_find_handler (int p_id)
2138 {
2139         OPJ_UINT32 i, l_handler_size = sizeof(jp2_header) / sizeof(opj_jp2_header_handler_t);
2140
2141         for (i=0;i<l_handler_size;++i) {
2142                 if (jp2_header[i].id == p_id) {
2143                         return &jp2_header[i];
2144                 }
2145         }
2146         return NULL;
2147 }
2148
2149 /**
2150  * Finds the image execution function related to the given box id.
2151  *
2152  * @param       p_id    the id of the handler to fetch.
2153  *
2154  * @return      the given handler or 00 if it could not be found.
2155  */
2156 static const opj_jp2_header_handler_t * jp2_img_find_handler (
2157                                                                                                 int p_id
2158                                                                                                 )
2159 {
2160         OPJ_UINT32 i, l_handler_size = sizeof(jp2_img_header) / sizeof(opj_jp2_header_handler_t);
2161         for (i=0;i<l_handler_size;++i)
2162         {
2163                 if (jp2_img_header[i].id == p_id) {
2164                         return &jp2_img_header[i];
2165                 }
2166         }
2167
2168         return NULL;
2169 }
2170
2171
2172 /**
2173  * Reads a jpeg2000 file signature box.
2174  *
2175  * @param       p_header_data   the data contained in the signature box.
2176  * @param       jp2                             the jpeg2000 file codec.
2177  * @param       p_header_size   the size of the data contained in the signature box.
2178  * @param       p_manager               the user event manager.
2179  *
2180  * @return true if the file signature box is valid.
2181  */
2182 opj_bool jp2_read_jp_v2(
2183                                         opj_jp2_v2_t *jp2,
2184                                         unsigned char * p_header_data,
2185                                         unsigned int p_header_size,
2186                                         opj_event_mgr_t * p_manager
2187                                  )
2188 {
2189         unsigned int l_magic_number;
2190
2191         // preconditions
2192         assert(p_header_data != 00);
2193         assert(jp2 != 00);
2194         assert(p_manager != 00);
2195
2196         if (jp2->jp2_state != JP2_STATE_NONE) {
2197                 opj_event_msg_v2(p_manager, EVT_ERROR, "The signature box must be the first box in the file.\n");
2198                 return OPJ_FALSE;
2199         }
2200
2201         /* assure length of data is correct (4 -> magic number) */
2202         if (p_header_size != 4) {
2203                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with JP signature Box size\n");
2204                 return OPJ_FALSE;
2205         }
2206
2207         // rearrange data
2208         opj_read_bytes(p_header_data,&l_magic_number,4);
2209         if (l_magic_number != 0x0d0a870a ) {
2210                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with JP Signature : bad magic number\n");
2211                 return OPJ_FALSE;
2212         }
2213
2214         jp2->jp2_state |= JP2_STATE_SIGNATURE;
2215
2216         return OPJ_TRUE;
2217 }
2218
2219
2220 /**
2221  * Reads a a FTYP box - File type box
2222  *
2223  * @param       p_header_data   the data contained in the FTYP box.
2224  * @param       jp2                             the jpeg2000 file codec.
2225  * @param       p_header_size   the size of the data contained in the FTYP box.
2226  * @param       p_manager               the user event manager.
2227  *
2228  * @return true if the FTYP box is valid.
2229  */
2230 opj_bool jp2_read_ftyp_v2(
2231                                                         opj_jp2_v2_t *jp2,
2232                                                         unsigned char * p_header_data,
2233                                                         unsigned int p_header_size,
2234                                                         opj_event_mgr_t * p_manager
2235                                                 )
2236 {
2237         OPJ_UINT32 i, l_remaining_bytes;
2238
2239         // preconditions
2240         assert(p_header_data != 00);
2241         assert(jp2 != 00);
2242         assert(p_manager != 00);
2243
2244         if (jp2->jp2_state != JP2_STATE_SIGNATURE) {
2245                 opj_event_msg_v2(p_manager, EVT_ERROR, "The ftyp box must be the second box in the file.\n");
2246                 return OPJ_FALSE;
2247         }
2248
2249         /* assure length of data is correct */
2250         if (p_header_size < 8) {
2251                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with FTYP signature Box size\n");
2252                 return OPJ_FALSE;
2253         }
2254
2255         opj_read_bytes(p_header_data,&jp2->brand,4);            /* BR */
2256         p_header_data += 4;
2257
2258         opj_read_bytes(p_header_data,&jp2->minversion,4);               /* MinV */
2259         p_header_data += 4;
2260
2261         l_remaining_bytes = p_header_size - 8;
2262
2263         /* the number of remaining bytes should be a multiple of 4 */
2264         if ((l_remaining_bytes & 0x3) != 0) {
2265                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with FTYP signature Box size\n");
2266                 return OPJ_FALSE;
2267         }
2268
2269         /* div by 4 */
2270         jp2->numcl = l_remaining_bytes >> 2;
2271         if (jp2->numcl) {
2272                 jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
2273                 if (jp2->cl == 00) {
2274                         opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory with FTYP Box\n");
2275                         return OPJ_FALSE;
2276                 }
2277                 memset(jp2->cl,0,jp2->numcl * sizeof(unsigned int));
2278         }
2279
2280         for (i = 0; i < jp2->numcl; ++i)
2281         {
2282                 opj_read_bytes(p_header_data,&jp2->cl[i],4);            /* CLi */
2283                 p_header_data += 4;
2284         }
2285
2286         jp2->jp2_state |= JP2_STATE_FILE_TYPE;
2287
2288         return OPJ_TRUE;
2289 }
2290
2291
2292 /**
2293  * Reads the Jpeg2000 file Header box - JP2 Header box (warning, this is a super box).
2294  *
2295  * @param       p_header_data   the data contained in the file header box.
2296  * @param       jp2                             the jpeg2000 file codec.
2297  * @param       p_header_size   the size of the data contained in the file header box.
2298  * @param       p_manager               the user event manager.
2299  *
2300  * @return true if the JP2 Header box was successfully reconized.
2301 */
2302 opj_bool jp2_read_jp2h_v2(
2303                                                 opj_jp2_v2_t *jp2,
2304                                                 unsigned char * p_header_data,
2305                                                 unsigned int p_header_size,
2306                                                 opj_event_mgr_t * p_manager
2307                                         )
2308 {
2309         OPJ_UINT32 l_box_size=0, l_current_data_size = 0;
2310         opj_jp2_box_t box;
2311         const opj_jp2_header_handler_t * l_current_handler;
2312
2313         // preconditions
2314         assert(p_header_data != 00);
2315         assert(jp2 != 00);
2316         assert(p_manager != 00);
2317
2318         /* make sure the box is well placed */
2319         if ((jp2->jp2_state & JP2_STATE_FILE_TYPE) != JP2_STATE_FILE_TYPE ) {
2320                 opj_event_msg_v2(p_manager, EVT_ERROR, "The  box must be the first box in the file.\n");
2321                 return OPJ_FALSE;
2322         }
2323
2324         jp2->jp2_img_state = JP2_IMG_STATE_NONE;
2325
2326         /* iterate while remaining data */
2327         while (p_header_size > 0) {
2328
2329                 if (! jp2_read_boxhdr_char(&box,p_header_data,&l_box_size,p_header_size, p_manager)) {
2330                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box\n");
2331                         return OPJ_FALSE;
2332                 }
2333
2334                 if (box.length > p_header_size) {
2335                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box: box length is inconsistent.\n");
2336                         return OPJ_FALSE;
2337                 }
2338
2339                 l_current_handler = jp2_img_find_handler(box.type);
2340                 l_current_data_size = box.length - l_box_size;
2341                 p_header_data += l_box_size;
2342
2343                 if (l_current_handler != 00) {
2344                         if (! l_current_handler->handler(jp2,p_header_data,l_current_data_size,p_manager)) {
2345                                 return OPJ_FALSE;
2346                         }
2347                 }
2348                 else {
2349                         jp2->jp2_img_state |= JP2_IMG_STATE_UNKNOWN;
2350                 }
2351
2352                 p_header_data += l_current_data_size;
2353                 p_header_size -= box.length;
2354         }
2355
2356         jp2->jp2_state |= JP2_STATE_HEADER;
2357
2358         return OPJ_TRUE;
2359 }
2360
2361 /**
2362  * Reads a box header. The box is the way data is packed inside a jpeg2000 file structure. Data is read from a character string
2363  *
2364  * @param       p_data                                  the character string to read data from.
2365  * @param       box                                             the box structure to fill.
2366  * @param       p_number_bytes_read             pointer to an int that will store the number of bytes read from the stream (shoul usually be 2).
2367  * @param       p_box_max_size                  the maximum number of bytes in the box.
2368  *
2369  * @return      true if the box is reconized, false otherwise
2370 */
2371 static opj_bool jp2_read_boxhdr_char(
2372                                                                 opj_jp2_box_t *box,
2373                                                                 OPJ_BYTE * p_data,
2374                                                                 OPJ_UINT32 * p_number_bytes_read,
2375                                                                 OPJ_UINT32 p_box_max_size,
2376                                                                 opj_event_mgr_t * p_manager
2377                                                         )
2378 {
2379         OPJ_UINT32 l_value;
2380
2381         // preconditions
2382         assert(p_data != 00);
2383         assert(box != 00);
2384         assert(p_number_bytes_read != 00);
2385         assert(p_manager != 00);
2386
2387         if (p_box_max_size < 8) {
2388                 opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box of less than 8 bytes\n");
2389                 return OPJ_FALSE;
2390         }
2391
2392         /* process read data */
2393         opj_read_bytes(p_data, &l_value, 4);
2394         p_data += 4;
2395         box->length = (OPJ_INT32)(l_value);
2396
2397         opj_read_bytes(p_data, &l_value, 4);
2398         p_data += 4;
2399         box->type = (OPJ_INT32)(l_value);
2400
2401         *p_number_bytes_read = 8;
2402
2403         // do we have a "special very large box ?"
2404         // read then the XLBox
2405         if (box->length == 1) {
2406                 unsigned int l_xl_part_size;
2407
2408                 if (p_box_max_size < 16) {
2409                         opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle XL box of less than 16 bytes\n");
2410                         return OPJ_FALSE;
2411                 }
2412
2413                 opj_read_bytes(p_data,&l_xl_part_size, 4);
2414                 p_data += 4;
2415                 *p_number_bytes_read += 4;
2416
2417                 if (l_xl_part_size != 0) {
2418                         opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
2419                         return OPJ_FALSE;
2420                 }
2421
2422                 opj_read_bytes(p_data, &l_value, 4);
2423                 *p_number_bytes_read += 4;
2424                 box->length = (OPJ_INT32)(l_value);
2425
2426                 if (box->length == 0) {
2427                         opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
2428                         return OPJ_FALSE;
2429                 }
2430         }
2431         else if (box->length == 0) {
2432                 opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
2433                 return OPJ_FALSE;
2434         }
2435
2436         return OPJ_TRUE;
2437 }
2438
2439
2440 /**
2441  * Reads a jpeg2000 file header structure.
2442  *
2443  * @param cio the stream to read data from.
2444  * @param jp2 the jpeg2000 file header structure.
2445  * @param p_manager the user event manager.
2446  *
2447  * @return true if the box is valid.
2448  */
2449 opj_bool jp2_read_header(       struct opj_stream_private *p_stream,
2450                                                         opj_jp2_v2_t *jp2,
2451                                                         opj_image_t** p_image,
2452                                                         struct opj_event_mgr * p_manager
2453                                                         )
2454 {
2455         /* preconditions */
2456         assert(jp2 != 00);
2457         assert(p_stream != 00);
2458         assert(p_manager != 00);
2459
2460         /* customization of the validation */
2461         jp2_setup_decoding_validation (jp2);
2462
2463         /* customization of the encoding */
2464         jp2_setup_header_reading(jp2);
2465
2466         /* validation of the parameters codec */
2467         if (! jp2_exec(jp2,jp2->m_validation_list,p_stream,p_manager)) {
2468                 return OPJ_FALSE;
2469         }
2470
2471         /* read header */
2472         if (! jp2_exec (jp2,jp2->m_procedure_list,p_stream,p_manager)) {
2473                 return OPJ_FALSE;
2474         }
2475
2476         return j2k_read_header( p_stream,
2477                                                         jp2->j2k,
2478                                                         p_image,
2479                                                         p_manager);
2480 }
2481
2482 /**
2483  * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
2484  * are valid. Developpers wanting to extend the library can add their own validation procedures.
2485  */
2486 void jp2_setup_decoding_validation (opj_jp2_v2_t *jp2)
2487 {
2488         // preconditions
2489         assert(jp2 != 00);
2490         /* DEVELOPER CORNER, add your custom validation procedure */
2491 }
2492
2493 /**
2494  * Sets up the procedures to do on reading header.
2495  * Developpers wanting to extend the library can add their own writting procedures.
2496  */
2497 void jp2_setup_header_reading (opj_jp2_v2_t *jp2)
2498 {
2499         // preconditions
2500         assert(jp2 != 00);
2501
2502         opj_procedure_list_add_procedure(jp2->m_procedure_list,(void*)jp2_read_header_procedure );
2503         /* DEVELOPER CORNER, add your custom procedures */
2504 }
2505
2506
2507 /**
2508  * Reads a tile header.
2509  * @param       p_j2k           the jpeg2000 codec.
2510  * @param       p_stream                        the stream to write data to.
2511  * @param       p_manager       the user event manager.
2512  */
2513 opj_bool jp2_read_tile_header(  opj_jp2_v2_t * p_jp2,
2514                                                                 OPJ_UINT32 * p_tile_index,
2515                                                                 OPJ_UINT32 * p_data_size,
2516                                                                 OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0,
2517                                                                 OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1,
2518                                                                 OPJ_UINT32 * p_nb_comps,
2519                                                                 opj_bool * p_go_on,
2520                                                                 opj_stream_private_t *p_stream,
2521                                                                 opj_event_mgr_t * p_manager )
2522 {
2523         return j2k_read_tile_header(p_jp2->j2k,
2524                                                                 p_tile_index,
2525                                                                 p_data_size,
2526                                                                 p_tile_x0, p_tile_y0,
2527                                                                 p_tile_x1, p_tile_y1,
2528                                                                 p_nb_comps,
2529                                                                 p_go_on,
2530                                                                 p_stream,
2531                                                                 p_manager);
2532 }
2533
2534 /**
2535  * Decode tile data.
2536  * @param       p_j2k           the jpeg2000 codec.
2537  * @param       p_stream                        the stream to write data to.
2538  * @param       p_manager       the user event manager.
2539  */
2540 opj_bool jp2_decode_tile (
2541                                         opj_jp2_v2_t * p_jp2,
2542                                         OPJ_UINT32 p_tile_index,
2543                                         OPJ_BYTE * p_data,
2544                                         OPJ_UINT32 p_data_size,
2545                                         opj_stream_private_t *p_stream,
2546                                         opj_event_mgr_t * p_manager
2547                                         )
2548 {
2549         return j2k_decode_tile (p_jp2->j2k,p_tile_index,p_data,p_data_size,p_stream,p_manager);
2550 }
2551
2552 /**
2553  * Destroys a jpeg2000 file decompressor.
2554  *
2555  * @param       jp2             a jpeg2000 file decompressor.
2556  */
2557 void jp2_destroy(opj_jp2_v2_t *jp2)
2558 {
2559         if (jp2) {
2560                 /* destroy the J2K codec */
2561                 j2k_destroy(jp2->j2k);
2562                 jp2->j2k = 00;
2563
2564                 if (jp2->comps) {
2565                         opj_free(jp2->comps);
2566                         jp2->comps = 00;
2567                 }
2568
2569                 if (jp2->cl) {
2570                         opj_free(jp2->cl);
2571                         jp2->cl = 00;
2572                 }
2573
2574                 if (jp2->color.icc_profile_buf) {
2575                         opj_free(jp2->color.icc_profile_buf);
2576                         jp2->color.icc_profile_buf = 00;
2577                 }
2578
2579                 if (jp2->color.jp2_cdef) {
2580                         if (jp2->color.jp2_cdef->info) {
2581                                 opj_free(jp2->color.jp2_cdef->info);
2582                                 jp2->color.jp2_cdef->info = NULL;
2583                         }
2584
2585                         opj_free(jp2->color.jp2_cdef);
2586                         jp2->color.jp2_cdef = 00;
2587                 }
2588
2589                 if (jp2->color.jp2_pclr) {
2590                         if (jp2->color.jp2_pclr->cmap) {
2591                                 opj_free(jp2->color.jp2_pclr->cmap);
2592                                 jp2->color.jp2_pclr->cmap = NULL;
2593                         }
2594                         if (jp2->color.jp2_pclr->channel_sign) {
2595                                 opj_free(jp2->color.jp2_pclr->channel_sign);
2596                                 jp2->color.jp2_pclr->channel_sign = NULL;
2597                         }
2598                         if (jp2->color.jp2_pclr->channel_size) {
2599                                 opj_free(jp2->color.jp2_pclr->channel_size);
2600                                 jp2->color.jp2_pclr->channel_size = NULL;
2601                         }
2602                         if (jp2->color.jp2_pclr->entries) {
2603                                 opj_free(jp2->color.jp2_pclr->entries);
2604                                 jp2->color.jp2_pclr->entries = NULL;
2605                         }
2606
2607                         opj_free(jp2->color.jp2_pclr);
2608                         jp2->color.jp2_pclr = 00;
2609                 }
2610
2611                 if (jp2->m_validation_list) {
2612                         opj_procedure_list_destroy(jp2->m_validation_list);
2613                         jp2->m_validation_list = 00;
2614                 }
2615
2616                 if (jp2->m_procedure_list) {
2617                         opj_procedure_list_destroy(jp2->m_procedure_list);
2618                         jp2->m_procedure_list = 00;
2619                 }
2620
2621                 opj_free(jp2);
2622         }
2623 }
2624
2625 /**
2626  * Sets the given area to be decoded. This function should be called right after opj_read_header and before any tile header reading.
2627  *
2628  * @param       p_jp2                   the jpeg2000 codec.
2629  * @param       p_end_x                 the right position of the rectangle to decode (in image coordinates).
2630  * @param       p_start_y               the up position of the rectangle to decode (in image coordinates).
2631  * @param       p_end_y                 the bottom position of the rectangle to decode (in image coordinates).
2632  * @param       p_manager               the user event manager
2633  *
2634  * @return      true                    if the area could be set.
2635  */
2636 opj_bool jp2_set_decode_area(   opj_jp2_v2_t *p_jp2,
2637                                                                 opj_image_t* p_image,
2638                                                                 OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
2639                                                                 OPJ_INT32 p_end_x, OPJ_INT32 p_end_y,
2640                                                                 struct opj_event_mgr * p_manager )
2641 {
2642         return j2k_set_decode_area(p_jp2->j2k, p_image, p_start_x, p_start_y, p_end_x, p_end_y, p_manager);
2643 }
2644
2645 /**
2646  * Get the decoded tile.
2647  *
2648  * @param       jp2                     the jpeg2000 codec.
2649  * @param       p_stream                input_stream
2650  * @param       p_image                 output image.   .
2651  * @param       p_manager               the user event manager
2652  * @param       tile_index              index of the tile we want decode
2653  *
2654  * @return      true                    if succeed.
2655  */
2656 opj_bool jp2_get_tile(  opj_jp2_v2_t *jp2,
2657                                                 opj_stream_private_t *p_stream,
2658                                                 opj_image_t* p_image,
2659                                                 struct opj_event_mgr * p_manager,
2660                                                 OPJ_UINT32 tile_index )
2661 {
2662         if (!p_image)
2663                 return OPJ_FALSE;
2664
2665         opj_event_msg_v2(p_manager, EVT_WARNING, "JP2 box which are after the codestream will not be read by this function.\n");
2666
2667         if (! j2k_get_tile(jp2->j2k, p_stream, p_image, p_manager, tile_index) ){
2668                 opj_event_msg_v2(p_manager, EVT_ERROR, "Failed to decode the codestream in the JP2 file\n");
2669                 return OPJ_FALSE;
2670         }
2671
2672         /* Set Image Color Space */
2673         if (jp2->enumcs == 16)
2674                 p_image->color_space = CLRSPC_SRGB;
2675         else if (jp2->enumcs == 17)
2676                 p_image->color_space = CLRSPC_GRAY;
2677         else if (jp2->enumcs == 18)
2678                 p_image->color_space = CLRSPC_SYCC;
2679         else
2680                 p_image->color_space = CLRSPC_UNKNOWN;
2681
2682         /* Apply the color space if needed */
2683         if(jp2->color.jp2_cdef) {
2684                 jp2_apply_cdef(p_image, &(jp2->color));
2685         }
2686
2687         if(jp2->color.jp2_pclr) {
2688                 /* Part 1, I.5.3.4: Either both or none : */
2689                 if( !jp2->color.jp2_pclr->cmap)
2690                         jp2_free_pclr(&(jp2->color));
2691                 else
2692                         jp2_apply_pclr(p_image, &(jp2->color));
2693         }
2694
2695         if(jp2->color.icc_profile_buf) {
2696                 p_image->icc_profile_buf = jp2->color.icc_profile_buf;
2697                 p_image->icc_profile_len = jp2->color.icc_profile_len;
2698                 jp2->color.icc_profile_buf = NULL;
2699         }
2700
2701         return OPJ_TRUE;
2702 }
2703
2704
2705
2706 /* ----------------------------------------------------------------------- */
2707 /* JP2 encoder interface                                             */
2708 /* ----------------------------------------------------------------------- */
2709
2710 opj_jp2_v2_t* jp2_create(opj_bool p_is_decoder)
2711 {
2712         opj_jp2_v2_t *jp2 = (opj_jp2_v2_t*)opj_malloc(sizeof(opj_jp2_v2_t));
2713         if (jp2) {
2714                 memset(jp2,0,sizeof(opj_jp2_t));
2715
2716                 /* create the J2K codec */
2717                 if (! p_is_decoder) {
2718                         jp2->j2k = j2k_create_compress_v2();
2719                 }
2720                 else {
2721                         jp2->j2k = j2k_create_decompress_v2();
2722                 }
2723
2724                 if (jp2->j2k == 00) {
2725                         jp2_destroy(jp2);
2726                         return 00;
2727                 }
2728
2729                 /* Color structure */
2730                 jp2->color.icc_profile_buf = NULL;
2731                 jp2->color.icc_profile_len = 0;
2732                 jp2->color.jp2_cdef = NULL;
2733                 jp2->color.jp2_pclr = NULL;
2734                 jp2->color.jp2_has_colr = 0;
2735
2736                 // validation list creation
2737                 jp2->m_validation_list = opj_procedure_list_create();
2738                 if (! jp2->m_validation_list) {
2739                         jp2_destroy(jp2);
2740                         return 00;
2741                 }
2742
2743                 // execution list creation
2744                 jp2->m_procedure_list = opj_procedure_list_create();
2745                 if (! jp2->m_procedure_list) {
2746                         jp2_destroy(jp2);
2747                         return 00;
2748                 }
2749         }
2750
2751         return jp2;
2752 }
2753
2754 void jp2_dump(opj_jp2_v2_t* p_jp2, OPJ_INT32 flag, FILE* out_stream)
2755 {
2756         /* preconditions */
2757         assert(p_jp2 != 00);
2758
2759         j2k_dump(p_jp2->j2k,
2760                                         flag,
2761                                         out_stream);
2762 }
2763
2764 opj_codestream_index_t* jp2_get_cstr_index(opj_jp2_v2_t* p_jp2)
2765 {
2766         return j2k_get_cstr_index(p_jp2->j2k);
2767 }
2768
2769 opj_codestream_info_v2_t* jp2_get_cstr_info(opj_jp2_v2_t* p_jp2)
2770 {
2771         return j2k_get_cstr_info(p_jp2->j2k);
2772 }
2773
2774 opj_bool jp2_set_decoded_resolution_factor(opj_jp2_v2_t *p_jp2, OPJ_UINT32 res_factor, opj_event_mgr_t * p_manager)
2775 {
2776         return j2k_set_decoded_resolution_factor(p_jp2->j2k, res_factor, p_manager);
2777 }
2778