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