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