[trunk] WIP: fix the decoding process with conformance files and V2 framework
[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 opj_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         /* J2K decoding */
1493         if( j2k_decode_v2(jp2->j2k, cio, p_image, p_manager) ) {
1494                 opj_event_msg_v2(p_manager, EVT_ERROR, "Failed to decode J2K image\n");
1495                 return OPJ_FALSE;
1496         }
1497
1498         /* Set Image Color Space */
1499         if (jp2->enumcs == 16)
1500                 p_image->color_space = CLRSPC_SRGB;
1501         else if (jp2->enumcs == 17)
1502                 p_image->color_space = CLRSPC_GRAY;
1503         else if (jp2->enumcs == 18)
1504                 p_image->color_space = CLRSPC_SYCC;
1505         else
1506                 p_image->color_space = CLRSPC_UNKNOWN;
1507
1508         /* Apply the color space if needed */
1509         if(jp2->color.jp2_cdef) {
1510                 jp2_apply_cdef(p_image, &(jp2->color));
1511         }
1512
1513         if(jp2->color.jp2_pclr) {
1514                 /* Part 1, I.5.3.4: Either both or none : */
1515                 if( !jp2->color.jp2_pclr->cmap)
1516                         jp2_free_pclr(&(jp2->color));
1517                 else
1518                         jp2_apply_pclr(p_image, &(jp2->color));
1519         }
1520
1521         if(jp2->color.icc_profile_buf) {
1522                 p_image->icc_profile_buf = jp2->color.icc_profile_buf;
1523                 p_image->icc_profile_len = jp2->color.icc_profile_len;
1524         }
1525
1526         return OPJ_TRUE;
1527 }
1528
1529
1530 void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) {
1531         opj_jp2_box_t box;
1532
1533         box.init_pos = cio_tell(cio);
1534         cio_skip(cio, 4);
1535         cio_write(cio, JP2_JP2H, 4);    /* JP2H */
1536
1537         jp2_write_ihdr(jp2, cio);
1538
1539         if (jp2->bpc == 255) {
1540                 jp2_write_bpcc(jp2, cio);
1541         }
1542         jp2_write_colr(jp2, cio);
1543
1544         box.length = cio_tell(cio) - box.init_pos;
1545         cio_seek(cio, box.init_pos);
1546         cio_write(cio, box.length, 4);  /* L */
1547         cio_seek(cio, box.init_pos + box.length);
1548 }
1549
1550 static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
1551         unsigned int i;
1552         opj_jp2_box_t box;
1553
1554         box.init_pos = cio_tell(cio);
1555         cio_skip(cio, 4);
1556         cio_write(cio, JP2_FTYP, 4);            /* FTYP */
1557
1558         cio_write(cio, jp2->brand, 4);          /* BR */
1559         cio_write(cio, jp2->minversion, 4);     /* MinV */
1560
1561         for (i = 0; i < jp2->numcl; i++) {
1562                 cio_write(cio, jp2->cl[i], 4);  /* CL */
1563         }
1564
1565         box.length = cio_tell(cio) - box.init_pos;
1566         cio_seek(cio, box.init_pos);
1567         cio_write(cio, box.length, 4);  /* L */
1568         cio_seek(cio, box.init_pos + box.length);
1569 }
1570
1571 static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
1572         int i;
1573         opj_jp2_box_t box;
1574
1575         opj_common_ptr cinfo = jp2->cinfo;
1576
1577         jp2_read_boxhdr(cinfo, cio, &box);
1578
1579         if (JP2_FTYP != box.type) {
1580                 opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
1581                 return OPJ_FALSE;
1582         }
1583
1584         jp2->brand = cio_read(cio, 4);          /* BR */
1585         jp2->minversion = cio_read(cio, 4);     /* MinV */
1586         jp2->numcl = (box.length - 16) / 4;
1587         jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
1588
1589         for (i = 0; i < (int)jp2->numcl; i++) {
1590                 jp2->cl[i] = cio_read(cio, 4);  /* CLi */
1591         }
1592
1593         if (cio_tell(cio) - box.init_pos != box.length) {
1594                 opj_event_msg(cinfo, EVT_ERROR, "Error with FTYP Box\n");
1595                 return OPJ_FALSE;
1596         }
1597
1598         return OPJ_TRUE;
1599 }
1600
1601 static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
1602         unsigned int j2k_codestream_offset, j2k_codestream_length;
1603         opj_jp2_box_t box;
1604
1605         opj_j2k_t *j2k = jp2->j2k;
1606
1607         box.init_pos = cio_tell(cio);
1608         cio_skip(cio, 4);
1609         cio_write(cio, JP2_JP2C, 4);    /* JP2C */
1610
1611         /* J2K encoding */
1612         j2k_codestream_offset = cio_tell(cio);
1613         if(!j2k_encode(j2k, cio, image, cstr_info)) {
1614                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Failed to encode image\n");
1615                 return 0;
1616         }
1617         j2k_codestream_length = cio_tell(cio) - j2k_codestream_offset;
1618
1619         jp2->j2k_codestream_offset = j2k_codestream_offset;
1620         jp2->j2k_codestream_length = j2k_codestream_length;
1621
1622         box.length = 8 + jp2->j2k_codestream_length;
1623         cio_seek(cio, box.init_pos);
1624         cio_write(cio, box.length, 4);  /* L */
1625         cio_seek(cio, box.init_pos + box.length);
1626
1627         return box.length;
1628 }
1629
1630 static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset) {
1631         opj_jp2_box_t box;
1632
1633         opj_common_ptr cinfo = jp2->cinfo;
1634
1635         jp2_read_boxhdr(cinfo, cio, &box);
1636         do {
1637                 if(JP2_JP2C != box.type) {
1638                         cio_skip(cio, box.length - 8);
1639                         jp2_read_boxhdr(cinfo, cio, &box);
1640                 }
1641         } while(JP2_JP2C != box.type);
1642
1643         *j2k_codestream_offset = cio_tell(cio);
1644         *j2k_codestream_length = box.length - 8;
1645
1646         return OPJ_TRUE;
1647 }
1648
1649 static void jp2_write_jp(opj_cio_t *cio) {
1650         opj_jp2_box_t box;
1651
1652         box.init_pos = cio_tell(cio);
1653         cio_skip(cio, 4);
1654         cio_write(cio, JP2_JP, 4);              /* JP2 signature */
1655         cio_write(cio, 0x0d0a870a, 4);
1656
1657         box.length = cio_tell(cio) - box.init_pos;
1658         cio_seek(cio, box.init_pos);
1659         cio_write(cio, box.length, 4);  /* L */
1660         cio_seek(cio, box.init_pos + box.length);
1661 }
1662
1663 static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
1664         opj_jp2_box_t box;
1665
1666         opj_common_ptr cinfo = jp2->cinfo;
1667
1668         jp2_read_boxhdr(cinfo, cio, &box);
1669         if (JP2_JP != box.type) {
1670                 opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
1671                 return OPJ_FALSE;
1672         }
1673         if (0x0d0a870a != cio_read(cio, 4)) {
1674                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Marker\n");
1675                 return OPJ_FALSE;
1676         }
1677         if (cio_tell(cio) - box.init_pos != box.length) {
1678                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Box size\n");
1679                 return OPJ_FALSE;
1680         }
1681
1682         return OPJ_TRUE;
1683 }
1684
1685
1686 static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
1687         opj_jp2_color_t *color) {
1688         if (!jp2_read_jp(jp2, cio))
1689                 return OPJ_FALSE;
1690         if (!jp2_read_ftyp(jp2, cio))
1691                 return OPJ_FALSE;
1692         if (!jp2_read_jp2h(jp2, cio, color))
1693                 return OPJ_FALSE;
1694         if (!jp2_read_jp2c(jp2, cio, &jp2->j2k_codestream_length, &jp2->j2k_codestream_offset))
1695                 return OPJ_FALSE;
1696         
1697         return OPJ_TRUE;
1698 }
1699
1700
1701 static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
1702 {  
1703   int len, lenp;
1704   
1705   lenp = cio_tell( cio);
1706   cio_skip( cio, 4);              /* L [at the end] */
1707   cio_write( cio, JPIP_FIDX, 4);  /* IPTR           */
1708   
1709   write_prxy( offset_jp2c, length_jp2c, offset_idx, length_idx, cio);
1710
1711   len = cio_tell( cio)-lenp;
1712   cio_seek( cio, lenp);
1713   cio_write( cio, len, 4);        /* L              */
1714   cio_seek( cio, lenp+len);  
1715
1716   return len;
1717 }
1718
1719 static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
1720 {
1721   int len, lenp;
1722
1723   lenp = cio_tell( cio);
1724   cio_skip( cio, 4);              /* L [at the end] */
1725   cio_write( cio, JPIP_PRXY, 4);  /* IPTR           */
1726   
1727   cio_write( cio, offset_jp2c, 8); /* OOFF           */
1728   cio_write( cio, length_jp2c, 4); /* OBH part 1     */
1729   cio_write( cio, JP2_JP2C, 4);        /* OBH part 2     */
1730   
1731   cio_write( cio, 1,1);           /* NI             */
1732
1733   cio_write( cio, offset_idx, 8);  /* IOFF           */
1734   cio_write( cio, length_idx, 4);  /* IBH part 1     */
1735   cio_write( cio, JPIP_CIDX, 4);   /* IBH part 2     */
1736
1737   len = cio_tell( cio)-lenp;
1738   cio_seek( cio, lenp);
1739   cio_write( cio, len, 4);        /* L              */
1740   cio_seek( cio, lenp+len);
1741 }
1742
1743 static void write_iptr( int offset, int length, opj_cio_t *cio)
1744 {
1745   int len, lenp;
1746   
1747   lenp = cio_tell( cio);
1748   cio_skip( cio, 4);              /* L [at the end] */
1749   cio_write( cio, JPIP_IPTR, 4);  /* IPTR           */
1750   
1751   cio_write( cio, offset, 8);
1752   cio_write( cio, length, 8);
1753
1754   len = cio_tell( cio)-lenp;
1755   cio_seek( cio, lenp);
1756   cio_write( cio, len, 4);        /* L             */
1757   cio_seek( cio, lenp+len);
1758 }
1759
1760
1761 /* ----------------------------------------------------------------------- */
1762 /* JP2 decoder interface                                             */
1763 /* ----------------------------------------------------------------------- */
1764
1765 opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo) {
1766         opj_jp2_t *jp2 = (opj_jp2_t*) opj_calloc(1, sizeof(opj_jp2_t));
1767         if(jp2) {
1768                 jp2->cinfo = cinfo;
1769                 /* create the J2K codec */
1770                 jp2->j2k = j2k_create_decompress(cinfo);
1771                 if(jp2->j2k == NULL) {
1772                         jp2_destroy_decompress(jp2);
1773                         return NULL;
1774                 }
1775         }
1776         return jp2;
1777 }
1778
1779 void jp2_destroy_decompress(opj_jp2_t *jp2) {
1780         if(jp2) {
1781                 /* destroy the J2K codec */
1782                 j2k_destroy_decompress(jp2->j2k);
1783
1784                 if(jp2->comps) {
1785                         opj_free(jp2->comps);
1786                 }
1787                 if(jp2->cl) {
1788                         opj_free(jp2->cl);
1789                 }
1790                 opj_free(jp2);
1791         }
1792 }
1793
1794 void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
1795         /* setup the J2K codec */
1796         j2k_setup_decoder(jp2->j2k, parameters);
1797         /* further JP2 initializations go here */
1798 }
1799
1800 void jp2_setup_decoder_v2(opj_jp2_v2_t *jp2, opj_dparameters_t *parameters)
1801 {
1802         /* setup the J2K codec */
1803         j2k_setup_decoder_v2(jp2->j2k, parameters);
1804
1805         /* further JP2 initializations go here */
1806         jp2->color.jp2_has_colr = 0;
1807 }
1808
1809
1810 /* ----------------------------------------------------------------------- */
1811 /* JP2 encoder interface                                             */
1812 /* ----------------------------------------------------------------------- */
1813
1814 opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
1815         opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
1816         if(jp2) {
1817                 jp2->cinfo = cinfo;
1818                 /* create the J2K codec */
1819                 jp2->j2k = j2k_create_compress(cinfo);
1820                 if(jp2->j2k == NULL) {
1821                         jp2_destroy_compress(jp2);
1822                         return NULL;
1823                 }
1824         }
1825         return jp2;
1826 }
1827
1828 void jp2_destroy_compress(opj_jp2_t *jp2) {
1829         if(jp2) {
1830                 /* destroy the J2K codec */
1831                 j2k_destroy_compress(jp2->j2k);
1832
1833                 if(jp2->comps) {
1834                         opj_free(jp2->comps);
1835                 }
1836                 if(jp2->cl) {
1837                         opj_free(jp2->cl);
1838                 }
1839                 opj_free(jp2);
1840         }
1841 }
1842
1843 void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image) {
1844         int i;
1845         int depth_0, sign;
1846
1847         if(!jp2 || !parameters || !image)
1848                 return;
1849
1850         /* setup the J2K codec */
1851         /* ------------------- */
1852
1853         /* Check if number of components respects standard */
1854         if (image->numcomps < 1 || image->numcomps > 16384) {
1855                 opj_event_msg(jp2->cinfo, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
1856                 return;
1857         }
1858
1859         j2k_setup_encoder(jp2->j2k, parameters, image);
1860
1861         /* setup the JP2 codec */
1862         /* ------------------- */
1863         
1864         /* Profile box */
1865
1866         jp2->brand = JP2_JP2;   /* BR */
1867         jp2->minversion = 0;    /* MinV */
1868         jp2->numcl = 1;
1869         jp2->cl = (unsigned int*) opj_malloc(jp2->numcl * sizeof(unsigned int));
1870         jp2->cl[0] = JP2_JP2;   /* CL0 : JP2 */
1871
1872         /* Image Header box */
1873
1874         jp2->numcomps = image->numcomps;        /* NC */
1875         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
1876         jp2->h = image->y1 - image->y0;         /* HEIGHT */
1877         jp2->w = image->x1 - image->x0;         /* WIDTH */
1878         /* BPC */
1879         depth_0 = image->comps[0].prec - 1;
1880         sign = image->comps[0].sgnd;
1881         jp2->bpc = depth_0 + (sign << 7);
1882         for (i = 1; i < image->numcomps; i++) {
1883                 int depth = image->comps[i].prec - 1;
1884                 sign = image->comps[i].sgnd;
1885                 if (depth_0 != depth)
1886                         jp2->bpc = 255;
1887         }
1888         jp2->C = 7;                     /* C : Always 7 */
1889         jp2->UnkC = 0;          /* UnkC, colorspace specified in colr box */
1890         jp2->IPR = 0;           /* IPR, no intellectual property */
1891         
1892         /* BitsPerComponent box */
1893
1894         for (i = 0; i < image->numcomps; i++) {
1895                 jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
1896         }
1897         jp2->meth = 1;
1898         if (image->color_space == 1)
1899                 jp2->enumcs = 16;       /* sRGB as defined by IEC 61966-2.1 */
1900         else if (image->color_space == 2)
1901                 jp2->enumcs = 17;       /* greyscale */
1902         else if (image->color_space == 3)
1903                 jp2->enumcs = 18;       /* YUV */
1904         jp2->precedence = 0;    /* PRECEDENCE */
1905         jp2->approx = 0;                /* APPROX */
1906         
1907         jp2->jpip_on = parameters->jpip_on;
1908 }
1909
1910 opj_bool opj_jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
1911
1912         int pos_iptr, pos_cidx, pos_jp2c, len_jp2c, len_cidx, end_pos, pos_fidx, len_fidx;
1913
1914         /* JP2 encoding */
1915
1916         /* JPEG 2000 Signature box */
1917         jp2_write_jp(cio);
1918         /* File Type box */
1919         jp2_write_ftyp(jp2, cio);
1920         /* JP2 Header box */
1921         jp2_write_jp2h(jp2, cio);
1922
1923         if( jp2->jpip_on){
1924           pos_iptr = cio_tell( cio);
1925           cio_skip( cio, 24); /* IPTR further ! */
1926           
1927           pos_jp2c = cio_tell( cio);
1928         }
1929
1930         /* J2K encoding */
1931         if(!(len_jp2c = jp2_write_jp2c( jp2, cio, image, cstr_info))){
1932             opj_event_msg(jp2->cinfo, EVT_ERROR, "Failed to encode image\n");
1933             return OPJ_FALSE;
1934         }
1935
1936         if( jp2->jpip_on){
1937           pos_cidx = cio_tell( cio);
1938           
1939           len_cidx = write_cidx( pos_jp2c+8, cio, image, *cstr_info, len_jp2c-8);
1940           
1941           pos_fidx = cio_tell( cio);
1942           len_fidx = write_fidx( pos_jp2c, len_jp2c, pos_cidx, len_cidx, cio);
1943           
1944           end_pos = cio_tell( cio);
1945           
1946           cio_seek( cio, pos_iptr);
1947           write_iptr( pos_fidx, len_fidx, cio);
1948                   cio_seek( cio, end_pos);
1949         }
1950
1951         return OPJ_TRUE;
1952 }
1953
1954 /**
1955  * Ends the decompression procedures and possibiliy add data to be read after the
1956  * codestream.
1957  */
1958 opj_bool jp2_end_decompress(opj_jp2_v2_t *jp2, opj_stream_private_t *cio, opj_event_mgr_t * p_manager)
1959 {
1960         // preconditions
1961         assert(jp2 != 00);
1962         assert(cio != 00);
1963         assert(p_manager != 00);
1964
1965         /* customization of the end encoding */
1966         jp2_setup_end_header_reading(jp2);
1967
1968         /* write header */
1969         if (! jp2_exec (jp2,jp2->m_procedure_list,cio,p_manager)) {
1970                 return OPJ_FALSE;
1971         }
1972
1973         return j2k_end_decompress(jp2->j2k, cio, p_manager);
1974 }
1975
1976 /**
1977  * Sets up the procedures to do on reading header after the codestream.
1978  * Developpers wanting to extend the library can add their own writting procedures.
1979  */
1980 void jp2_setup_end_header_reading (opj_jp2_v2_t *jp2)
1981 {
1982         // preconditions
1983         assert(jp2 != 00);
1984         opj_procedure_list_add_procedure(jp2->m_procedure_list,(void*)jp2_read_header_procedure );
1985         /* DEVELOPER CORNER, add your custom procedures */
1986 }
1987
1988
1989 /**
1990  * Reads a jpeg2000 file header structure.
1991  *
1992  * @param cio the stream to read data from.
1993  * @param jp2 the jpeg2000 file header structure.
1994  * @param p_manager the user event manager.
1995  *
1996  * @return true if the box is valid.
1997  */
1998 opj_bool jp2_read_header_procedure(
1999                                          opj_jp2_v2_t *jp2,
2000                                          opj_stream_private_t *cio,
2001                                          opj_event_mgr_t * p_manager)
2002 {
2003         opj_jp2_box_t box;
2004         OPJ_UINT32 l_nb_bytes_read;
2005         const opj_jp2_header_handler_t * l_current_handler;
2006         OPJ_UINT32 l_last_data_size = BOX_SIZE;
2007         OPJ_UINT32 l_current_data_size;
2008         unsigned char * l_current_data = 00;
2009
2010         // preconditions
2011         assert(cio != 00);
2012         assert(jp2 != 00);
2013         assert(p_manager != 00);
2014
2015         l_current_data = (unsigned char*)opj_malloc(l_last_data_size);
2016
2017         if (l_current_data == 00) {
2018                 opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory to handle jpeg2000 file header\n");
2019                 return OPJ_FALSE;
2020         }
2021         memset(l_current_data, 0 , l_last_data_size);
2022
2023         while (jp2_read_boxhdr_v2(&box,&l_nb_bytes_read,cio,p_manager)) {
2024                 // is it the codestream box ?
2025                 if (box.type == JP2_JP2C) {
2026                         if (jp2->jp2_state & JP2_STATE_HEADER) {
2027                                 jp2->jp2_state |= JP2_STATE_CODESTREAM;
2028                 opj_free(l_current_data);
2029                                 return OPJ_TRUE;
2030                         }
2031                         else {
2032                                 opj_event_msg_v2(p_manager, EVT_ERROR, "bad placed jpeg codestream\n");
2033                                 opj_free(l_current_data);
2034                                 return OPJ_FALSE;
2035                         }
2036                 }
2037                 else if (box.length == 0) {
2038                         opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
2039                         opj_free(l_current_data);
2040                         return OPJ_FALSE;
2041                 }
2042
2043                 l_current_handler = jp2_find_handler(box.type);
2044                 l_current_data_size = box.length - l_nb_bytes_read;
2045
2046                 if (l_current_handler != 00) {
2047                         if (l_current_data_size > l_last_data_size) {
2048                                 l_current_data = (unsigned char*)opj_realloc(l_current_data,l_current_data_size);
2049                                 l_last_data_size = l_current_data_size;
2050                         }
2051
2052                         l_nb_bytes_read = opj_stream_read_data(cio,l_current_data,l_current_data_size,p_manager);
2053                         if (l_nb_bytes_read != l_current_data_size) {
2054                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Problem with reading JPEG2000 box, stream error\n");
2055                                 return OPJ_FALSE;
2056                         }
2057
2058                         if (! l_current_handler->handler(jp2,l_current_data,l_current_data_size,p_manager)) {
2059                                 opj_free(l_current_data);
2060                                 return OPJ_FALSE;
2061                         }
2062                 }
2063                 else {
2064                         jp2->jp2_state |= JP2_STATE_UNKNOWN;
2065                         if (opj_stream_skip(cio,l_current_data_size,p_manager) != l_current_data_size) {
2066                                 opj_event_msg_v2(p_manager, EVT_ERROR, "Problem with skipping JPEG2000 box, stream error\n");
2067                                 opj_free(l_current_data);
2068                                 return OPJ_FALSE;
2069                         }
2070                 }
2071         }
2072
2073         opj_free(l_current_data);
2074
2075         return OPJ_TRUE;
2076 }
2077
2078 /**
2079  * Excutes the given procedures on the given codec.
2080  *
2081  * @param       p_procedure_list        the list of procedures to execute
2082  * @param       jp2                                     the jpeg2000 file codec to execute the procedures on.
2083  * @param       cio                                     the stream to execute the procedures on.
2084  * @param       p_manager                       the user manager.
2085  *
2086  * @return      true                            if all the procedures were successfully executed.
2087  */
2088 opj_bool jp2_exec (
2089                                         opj_jp2_v2_t * jp2,
2090                                         opj_procedure_list_t * p_procedure_list,
2091                                         opj_stream_private_t *cio,
2092                                         opj_event_mgr_t * p_manager
2093                                   )
2094 {
2095         opj_bool (** l_procedure) (opj_jp2_v2_t * jp2, opj_stream_private_t *, opj_event_mgr_t *) = 00;
2096         opj_bool l_result = OPJ_TRUE;
2097         OPJ_UINT32 l_nb_proc, i;
2098
2099         // preconditions
2100         assert(p_procedure_list != 00);
2101         assert(jp2 != 00);
2102         assert(cio != 00);
2103         assert(p_manager != 00);
2104
2105         l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list);
2106         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);
2107
2108         for     (i=0;i<l_nb_proc;++i) {
2109                 l_result = l_result && (*l_procedure) (jp2,cio,p_manager);
2110                 ++l_procedure;
2111         }
2112
2113         // and clear the procedure list at the end.
2114         opj_procedure_list_clear(p_procedure_list);
2115         return l_result;
2116 }
2117
2118
2119 /**
2120  * Finds the execution function related to the given box id.
2121  *
2122  * @param       p_id    the id of the handler to fetch.
2123  *
2124  * @return      the given handler or 00 if it could not be found.
2125  */
2126 const opj_jp2_header_handler_t * jp2_find_handler (int p_id)
2127 {
2128         OPJ_UINT32 i, l_handler_size = sizeof(jp2_header) / sizeof(opj_jp2_header_handler_t);
2129
2130         for (i=0;i<l_handler_size;++i) {
2131                 if (jp2_header[i].id == p_id) {
2132                         return &jp2_header[i];
2133                 }
2134         }
2135         return NULL;
2136 }
2137
2138 /**
2139  * Finds the image execution function related to the given box id.
2140  *
2141  * @param       p_id    the id of the handler to fetch.
2142  *
2143  * @return      the given handler or 00 if it could not be found.
2144  */
2145 static const opj_jp2_header_handler_t * jp2_img_find_handler (
2146                                                                                                 int p_id
2147                                                                                                 )
2148 {
2149         OPJ_UINT32 i, l_handler_size = sizeof(jp2_img_header) / sizeof(opj_jp2_header_handler_t);
2150         for (i=0;i<l_handler_size;++i)
2151         {
2152                 if (jp2_img_header[i].id == p_id) {
2153                         return &jp2_img_header[i];
2154                 }
2155         }
2156
2157         return NULL;
2158 }
2159
2160
2161 /**
2162  * Reads a jpeg2000 file signature box.
2163  *
2164  * @param       p_header_data   the data contained in the signature box.
2165  * @param       jp2                             the jpeg2000 file codec.
2166  * @param       p_header_size   the size of the data contained in the signature box.
2167  * @param       p_manager               the user event manager.
2168  *
2169  * @return true if the file signature box is valid.
2170  */
2171 opj_bool jp2_read_jp_v2(
2172                                         opj_jp2_v2_t *jp2,
2173                                         unsigned char * p_header_data,
2174                                         unsigned int p_header_size,
2175                                         opj_event_mgr_t * p_manager
2176                                  )
2177 {
2178         unsigned int l_magic_number;
2179
2180         // preconditions
2181         assert(p_header_data != 00);
2182         assert(jp2 != 00);
2183         assert(p_manager != 00);
2184
2185         if (jp2->jp2_state != JP2_STATE_NONE) {
2186                 opj_event_msg_v2(p_manager, EVT_ERROR, "The signature box must be the first box in the file.\n");
2187                 return OPJ_FALSE;
2188         }
2189
2190         /* assure length of data is correct (4 -> magic number) */
2191         if (p_header_size != 4) {
2192                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with JP signature Box size\n");
2193                 return OPJ_FALSE;
2194         }
2195
2196         // rearrange data
2197         opj_read_bytes(p_header_data,&l_magic_number,4);
2198         if (l_magic_number != 0x0d0a870a ) {
2199                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with JP Signature : bad magic number\n");
2200                 return OPJ_FALSE;
2201         }
2202
2203         jp2->jp2_state |= JP2_STATE_SIGNATURE;
2204
2205         return OPJ_TRUE;
2206 }
2207
2208
2209 /**
2210  * Reads a a FTYP box - File type box
2211  *
2212  * @param       p_header_data   the data contained in the FTYP box.
2213  * @param       jp2                             the jpeg2000 file codec.
2214  * @param       p_header_size   the size of the data contained in the FTYP box.
2215  * @param       p_manager               the user event manager.
2216  *
2217  * @return true if the FTYP box is valid.
2218  */
2219 opj_bool jp2_read_ftyp_v2(
2220                                                         opj_jp2_v2_t *jp2,
2221                                                         unsigned char * p_header_data,
2222                                                         unsigned int p_header_size,
2223                                                         opj_event_mgr_t * p_manager
2224                                                 )
2225 {
2226         OPJ_UINT32 i, l_remaining_bytes;
2227
2228         // preconditions
2229         assert(p_header_data != 00);
2230         assert(jp2 != 00);
2231         assert(p_manager != 00);
2232
2233         if (jp2->jp2_state != JP2_STATE_SIGNATURE) {
2234                 opj_event_msg_v2(p_manager, EVT_ERROR, "The ftyp box must be the second box in the file.\n");
2235                 return OPJ_FALSE;
2236         }
2237
2238         /* assure length of data is correct */
2239         if (p_header_size < 8) {
2240                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with FTYP signature Box size\n");
2241                 return OPJ_FALSE;
2242         }
2243
2244         opj_read_bytes(p_header_data,&jp2->brand,4);            /* BR */
2245         p_header_data += 4;
2246
2247         opj_read_bytes(p_header_data,&jp2->minversion,4);               /* MinV */
2248         p_header_data += 4;
2249
2250         l_remaining_bytes = p_header_size - 8;
2251
2252         /* the number of remaining bytes should be a multiple of 4 */
2253         if ((l_remaining_bytes & 0x3) != 0) {
2254                 opj_event_msg_v2(p_manager, EVT_ERROR, "Error with FTYP signature Box size\n");
2255                 return OPJ_FALSE;
2256         }
2257
2258         /* div by 4 */
2259         jp2->numcl = l_remaining_bytes >> 2;
2260         if (jp2->numcl) {
2261                 jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
2262                 if (jp2->cl == 00) {
2263                         opj_event_msg_v2(p_manager, EVT_ERROR, "Not enough memory with FTYP Box\n");
2264                         return OPJ_FALSE;
2265                 }
2266                 memset(jp2->cl,0,jp2->numcl * sizeof(unsigned int));
2267         }
2268
2269         for (i = 0; i < jp2->numcl; ++i)
2270         {
2271                 opj_read_bytes(p_header_data,&jp2->cl[i],4);            /* CLi */
2272                 p_header_data += 4;
2273         }
2274
2275         jp2->jp2_state |= JP2_STATE_FILE_TYPE;
2276
2277         return OPJ_TRUE;
2278 }
2279
2280
2281 /**
2282  * Reads the Jpeg2000 file Header box - JP2 Header box (warning, this is a super box).
2283  *
2284  * @param       p_header_data   the data contained in the file header box.
2285  * @param       jp2                             the jpeg2000 file codec.
2286  * @param       p_header_size   the size of the data contained in the file header box.
2287  * @param       p_manager               the user event manager.
2288  *
2289  * @return true if the JP2 Header box was successfully reconized.
2290 */
2291 opj_bool jp2_read_jp2h_v2(
2292                                                 opj_jp2_v2_t *jp2,
2293                                                 unsigned char * p_header_data,
2294                                                 unsigned int p_header_size,
2295                                                 opj_event_mgr_t * p_manager
2296                                         )
2297 {
2298         OPJ_UINT32 l_box_size=0, l_current_data_size = 0;
2299         opj_jp2_box_t box;
2300         const opj_jp2_header_handler_t * l_current_handler;
2301
2302         // preconditions
2303         assert(p_header_data != 00);
2304         assert(jp2 != 00);
2305         assert(p_manager != 00);
2306
2307         /* make sure the box is well placed */
2308         if ((jp2->jp2_state & JP2_STATE_FILE_TYPE) != JP2_STATE_FILE_TYPE ) {
2309                 opj_event_msg_v2(p_manager, EVT_ERROR, "The  box must be the first box in the file.\n");
2310                 return OPJ_FALSE;
2311         }
2312
2313         jp2->jp2_img_state = JP2_IMG_STATE_NONE;
2314
2315         /* iterate while remaining data */
2316         while (p_header_size > 0) {
2317
2318                 if (! jp2_read_boxhdr_char(&box,p_header_data,&l_box_size,p_header_size, p_manager)) {
2319                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box\n");
2320                         return OPJ_FALSE;
2321                 }
2322
2323                 if (box.length > p_header_size) {
2324                         opj_event_msg_v2(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box: box length is inconsistent.\n");
2325                         return OPJ_FALSE;
2326                 }
2327
2328                 l_current_handler = jp2_img_find_handler(box.type);
2329                 l_current_data_size = box.length - l_box_size;
2330                 p_header_data += l_box_size;
2331
2332                 if (l_current_handler != 00) {
2333                         if (! l_current_handler->handler(jp2,p_header_data,l_current_data_size,p_manager)) {
2334                                 return OPJ_FALSE;
2335                         }
2336                 }
2337                 else {
2338                         jp2->jp2_img_state |= JP2_IMG_STATE_UNKNOWN;
2339                 }
2340
2341                 p_header_data += l_current_data_size;
2342                 p_header_size -= box.length;
2343         }
2344
2345         jp2->jp2_state |= JP2_STATE_HEADER;
2346
2347         return OPJ_TRUE;
2348 }
2349
2350 /**
2351  * Reads a box header. The box is the way data is packed inside a jpeg2000 file structure. Data is read from a character string
2352  *
2353  * @param       p_data                                  the character string to read data from.
2354  * @param       box                                             the box structure to fill.
2355  * @param       p_number_bytes_read             pointer to an int that will store the number of bytes read from the stream (shoul usually be 2).
2356  * @param       p_box_max_size                  the maximum number of bytes in the box.
2357  *
2358  * @return      true if the box is reconized, false otherwise
2359 */
2360 static opj_bool jp2_read_boxhdr_char(
2361                                                                 opj_jp2_box_t *box,
2362                                                                 OPJ_BYTE * p_data,
2363                                                                 OPJ_UINT32 * p_number_bytes_read,
2364                                                                 OPJ_UINT32 p_box_max_size,
2365                                                                 opj_event_mgr_t * p_manager
2366                                                         )
2367 {
2368         OPJ_UINT32 l_value;
2369
2370         // preconditions
2371         assert(p_data != 00);
2372         assert(box != 00);
2373         assert(p_number_bytes_read != 00);
2374         assert(p_manager != 00);
2375
2376         if (p_box_max_size < 8) {
2377                 opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box of less than 8 bytes\n");
2378                 return OPJ_FALSE;
2379         }
2380
2381         /* process read data */
2382         opj_read_bytes(p_data, &l_value, 4);
2383         p_data += 4;
2384         box->length = (OPJ_INT32)(l_value);
2385
2386         opj_read_bytes(p_data, &l_value, 4);
2387         p_data += 4;
2388         box->type = (OPJ_INT32)(l_value);
2389
2390         *p_number_bytes_read = 8;
2391
2392         // do we have a "special very large box ?"
2393         // read then the XLBox
2394         if (box->length == 1) {
2395                 unsigned int l_xl_part_size;
2396
2397                 if (p_box_max_size < 16) {
2398                         opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle XL box of less than 16 bytes\n");
2399                         return OPJ_FALSE;
2400                 }
2401
2402                 opj_read_bytes(p_data,&l_xl_part_size, 4);
2403                 p_data += 4;
2404                 *p_number_bytes_read += 4;
2405
2406                 if (l_xl_part_size != 0) {
2407                         opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
2408                         return OPJ_FALSE;
2409                 }
2410
2411                 opj_read_bytes(p_data, &l_value, 4);
2412                 *p_number_bytes_read += 4;
2413                 box->length = (OPJ_INT32)(l_value);
2414
2415                 if (box->length == 0) {
2416                         opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
2417                         return OPJ_FALSE;
2418                 }
2419         }
2420         else if (box->length == 0) {
2421                 opj_event_msg_v2(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
2422                 return OPJ_FALSE;
2423         }
2424
2425         return OPJ_TRUE;
2426 }
2427
2428
2429 /**
2430  * Reads a jpeg2000 file header structure.
2431  *
2432  * @param cio the stream to read data from.
2433  * @param jp2 the jpeg2000 file header structure.
2434  * @param p_manager the user event manager.
2435  *
2436  * @return true if the box is valid.
2437  */
2438 opj_bool jp2_read_header(       struct opj_stream_private *p_stream,
2439                                                         opj_jp2_v2_t *jp2,
2440                                                         opj_image_t* p_image,
2441                                                         struct opj_event_mgr * p_manager
2442                                                         )
2443 {
2444         // preconditions
2445         assert(jp2 != 00);
2446         assert(p_stream != 00);
2447         assert(p_manager != 00);
2448
2449         /* customization of the validation */
2450         jp2_setup_decoding_validation (jp2);
2451
2452         /* customization of the encoding */
2453         jp2_setup_header_reading(jp2);
2454
2455         /* validation of the parameters codec */
2456         if (! jp2_exec(jp2,jp2->m_validation_list,p_stream,p_manager)) {
2457                 return OPJ_FALSE;
2458         }
2459
2460         /* read header */
2461         if (! jp2_exec (jp2,jp2->m_procedure_list,p_stream,p_manager)) {
2462                 return OPJ_FALSE;
2463         }
2464
2465         return j2k_read_header( p_stream,
2466                                                         jp2->j2k,
2467                                                         p_image,
2468                                                         p_manager);
2469 }
2470
2471 /**
2472  * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
2473  * are valid. Developpers wanting to extend the library can add their own validation procedures.
2474  */
2475 void jp2_setup_decoding_validation (opj_jp2_v2_t *jp2)
2476 {
2477         // preconditions
2478         assert(jp2 != 00);
2479         /* DEVELOPER CORNER, add your custom validation procedure */
2480 }
2481
2482 /**
2483  * Sets up the procedures to do on reading header.
2484  * Developpers wanting to extend the library can add their own writting procedures.
2485  */
2486 void jp2_setup_header_reading (opj_jp2_v2_t *jp2)
2487 {
2488         // preconditions
2489         assert(jp2 != 00);
2490
2491         opj_procedure_list_add_procedure(jp2->m_procedure_list,(void*)jp2_read_header_procedure );
2492         /* DEVELOPER CORNER, add your custom procedures */
2493 }
2494
2495
2496 /**
2497  * Reads a tile header.
2498  * @param       p_j2k           the jpeg2000 codec.
2499  * @param       p_stream                        the stream to write data to.
2500  * @param       p_manager       the user event manager.
2501  */
2502 opj_bool jp2_read_tile_header(  opj_jp2_v2_t * p_jp2,
2503                                                                 OPJ_UINT32 * p_tile_index,
2504                                                                 OPJ_UINT32 * p_data_size,
2505                                                                 OPJ_INT32 * p_tile_x0, OPJ_INT32 * p_tile_y0,
2506                                                                 OPJ_INT32 * p_tile_x1, OPJ_INT32 * p_tile_y1,
2507                                                                 OPJ_UINT32 * p_nb_comps,
2508                                                                 opj_bool * p_go_on,
2509                                                                 opj_stream_private_t *p_stream,
2510                                                                 opj_event_mgr_t * p_manager )
2511 {
2512         return j2k_read_tile_header(p_jp2->j2k,
2513                                                                 p_tile_index,
2514                                                                 p_data_size,
2515                                                                 p_tile_x0, p_tile_y0,
2516                                                                 p_tile_x1, p_tile_y1,
2517                                                                 p_nb_comps,
2518                                                                 p_go_on,
2519                                                                 p_stream,
2520                                                                 p_manager);
2521 }
2522
2523 /**
2524  * Decode tile data.
2525  * @param       p_j2k           the jpeg2000 codec.
2526  * @param       p_stream                        the stream to write data to.
2527  * @param       p_manager       the user event manager.
2528  */
2529 opj_bool opj_jp2_decode_tile (
2530                                         opj_jp2_v2_t * p_jp2,
2531                                         OPJ_UINT32 p_tile_index,
2532                                         OPJ_BYTE * p_data,
2533                                         OPJ_UINT32 p_data_size,
2534                                         opj_stream_private_t *p_stream,
2535                                         opj_event_mgr_t * p_manager
2536                                         )
2537 {
2538         return j2k_decode_tile (p_jp2->j2k,p_tile_index,p_data,p_data_size,p_stream,p_manager);
2539 }
2540
2541 /**
2542  * Destroys a jpeg2000 file decompressor.
2543  *
2544  * @param       jp2             a jpeg2000 file decompressor.
2545  */
2546 void jp2_destroy(opj_jp2_v2_t *jp2)
2547 {
2548         if (jp2) {
2549                 /* destroy the J2K codec */
2550                 j2k_destroy(jp2->j2k);
2551                 jp2->j2k = 00;
2552
2553                 if (jp2->comps) {
2554                         opj_free(jp2->comps);
2555                         jp2->comps = 00;
2556                 }
2557
2558                 if (jp2->cl) {
2559                         opj_free(jp2->cl);
2560                         jp2->cl = 00;
2561                 }
2562
2563                 if (jp2->color.icc_profile_buf) {
2564                         opj_free(jp2->color.icc_profile_buf);
2565                         jp2->color.icc_profile_buf = 00;
2566                 }
2567
2568                 if (jp2->color.jp2_cdef) {
2569                         opj_free(jp2->color.jp2_cdef);
2570                         jp2->color.jp2_cdef = 00;
2571                 }
2572
2573                 if (jp2->color.jp2_pclr) {
2574                         opj_free(jp2->color.jp2_pclr);
2575                         jp2->color.jp2_pclr = 00;
2576                 }
2577
2578                 if (jp2->m_validation_list) {
2579                         opj_procedure_list_destroy(jp2->m_validation_list);
2580                         jp2->m_validation_list = 00;
2581                 }
2582
2583                 if (jp2->m_procedure_list) {
2584                         opj_procedure_list_destroy(jp2->m_procedure_list);
2585                         jp2->m_procedure_list = 00;
2586                 }
2587
2588                 opj_free(jp2);
2589         }
2590 }
2591
2592 /**
2593  * Sets the given area to be decoded. This function should be called right after opj_read_header and before any tile header reading.
2594  *
2595  * @param       p_jp2                   the jpeg2000 codec.
2596  * @param       p_end_x                 the right position of the rectangle to decode (in image coordinates).
2597  * @param       p_start_y               the up position of the rectangle to decode (in image coordinates).
2598  * @param       p_end_y                 the bottom position of the rectangle to decode (in image coordinates).
2599  * @param       p_manager               the user event manager
2600  *
2601  * @return      true                    if the area could be set.
2602  */
2603 opj_bool jp2_set_decode_area(   opj_jp2_v2_t *p_jp2,
2604                                                                 OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
2605                                                                 OPJ_INT32 p_end_x, OPJ_INT32 p_end_y,
2606                                                                 struct opj_event_mgr * p_manager )
2607 {
2608         return j2k_set_decode_area(p_jp2->j2k, p_start_x, p_start_y, p_end_x, p_end_y, p_manager);
2609 }
2610
2611 /* ----------------------------------------------------------------------- */
2612 /* JP2 encoder interface                                             */
2613 /* ----------------------------------------------------------------------- */
2614
2615 opj_jp2_v2_t* jp2_create(opj_bool p_is_decoder)
2616 {
2617         opj_jp2_v2_t *jp2 = (opj_jp2_v2_t*)opj_malloc(sizeof(opj_jp2_v2_t));
2618         if (jp2) {
2619                 memset(jp2,0,sizeof(opj_jp2_t));
2620
2621                 /* create the J2K codec */
2622                 if (! p_is_decoder) {
2623                         jp2->j2k = j2k_create_compress_v2();
2624                 }
2625                 else {
2626                         jp2->j2k = j2k_create_decompress_v2();
2627                 }
2628
2629                 if (jp2->j2k == 00) {
2630                         jp2_destroy(jp2);
2631                         return 00;
2632                 }
2633
2634                 // validation list creation
2635                 jp2->m_validation_list = opj_procedure_list_create();
2636                 if (! jp2->m_validation_list) {
2637                         jp2_destroy(jp2);
2638                         return 00;
2639                 }
2640
2641                 // execution list creation
2642                 jp2->m_procedure_list = opj_procedure_list_create();
2643                 if (! jp2->m_procedure_list) {
2644                         jp2_destroy(jp2);
2645                         return 00;
2646                 }
2647         }
2648
2649         return jp2;
2650 }