Fix unsigned int overflow reported by UBSan (#761)
[openjpeg.git] / src / lib / openjp2 / jp2.c
1 /*
2  * The copyright in this software is being made available under the 2-clauses 
3  * BSD License, included below. This software may be subject to other third 
4  * party and contributor rights, including patent rights, and no such rights
5  * are granted under this license.
6  *
7  * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
8  * Copyright (c) 2002-2014, Professor Benoit Macq
9  * Copyright (c) 2001-2003, David Janssens
10  * Copyright (c) 2002-2003, Yannick Verschueren
11  * Copyright (c) 2003-2007, Francois-Olivier Devaux 
12  * Copyright (c) 2003-2014, Antonin Descampe
13  * Copyright (c) 2005, Herve Drolon, FreeImage Team
14  * Copyright (c) 2010-2011, Kaori Hagihara
15  * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR 
16  * Copyright (c) 2012, CS Systemes d'Information, France
17  * All rights reserved.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
29  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
32  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40 #include "opj_includes.h"
41
42 /** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
43 /*@{*/
44
45 #define OPJ_BOX_SIZE    1024
46
47 /** @name Local static functions */
48 /*@{*/
49
50 /*static void jp2_write_url(opj_cio_t *cio, char *Idx_file);*/
51
52 /**
53  * Reads a IHDR box - Image Header box
54  *
55  * @param       p_image_header_data                     pointer to actual data (already read from file)
56  * @param       jp2                                                     the jpeg2000 file codec.
57  * @param       p_image_header_size                     the size of the image header
58  * @param       p_manager                                       the user event manager.
59  *
60  * @return      true if the image header is valid, false else.
61  */
62 static OPJ_BOOL opj_jp2_read_ihdr(  opj_jp2_t *jp2,
63                                     OPJ_BYTE *p_image_header_data,
64                                     OPJ_UINT32 p_image_header_size,
65                                     opj_event_mgr_t * p_manager );
66
67 /**
68  * Writes the Image Header box - Image Header box.
69  *
70  * @param jp2                                   jpeg2000 file codec.
71  * @param p_nb_bytes_written    pointer to store the nb of bytes written by the function.
72  *
73  * @return      the data being copied.
74 */
75 static OPJ_BYTE * opj_jp2_write_ihdr(opj_jp2_t *jp2,
76                                      OPJ_UINT32 * p_nb_bytes_written );
77
78 /**
79  * Writes the Bit per Component box.
80  *
81  * @param       jp2                                             jpeg2000 file codec.
82  * @param       p_nb_bytes_written              pointer to store the nb of bytes written by the function.
83  *
84  * @return      the data being copied.
85 */
86 static OPJ_BYTE * opj_jp2_write_bpcc(   opj_jp2_t *jp2,
87                                                                         OPJ_UINT32 * p_nb_bytes_written );
88
89 /**
90  * Reads a Bit per Component box.
91  *
92  * @param       p_bpc_header_data                       pointer to actual data (already read from file)
93  * @param       jp2                                                     the jpeg2000 file codec.
94  * @param       p_bpc_header_size                       the size of the bpc header
95  * @param       p_manager                                       the user event manager.
96  *
97  * @return      true if the bpc header is valid, false else.
98  */
99 static OPJ_BOOL opj_jp2_read_bpcc(  opj_jp2_t *jp2,
100                                     OPJ_BYTE * p_bpc_header_data,
101                                     OPJ_UINT32 p_bpc_header_size,
102                                     opj_event_mgr_t * p_manager );
103
104 static OPJ_BOOL opj_jp2_read_cdef(      opj_jp2_t * jp2,
105                                     OPJ_BYTE * p_cdef_header_data,
106                                                                         OPJ_UINT32 p_cdef_header_size,
107                                                                         opj_event_mgr_t * p_manager );
108
109 static void opj_jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color, opj_event_mgr_t *);
110
111 /**
112  * Writes the Channel Definition box.
113  *
114  * @param jp2                                   jpeg2000 file codec.
115  * @param p_nb_bytes_written    pointer to store the nb of bytes written by the function.
116  *
117  * @return      the data being copied.
118  */
119 static OPJ_BYTE * opj_jp2_write_cdef(   opj_jp2_t *jp2,
120                                                                                                                                                  OPJ_UINT32 * p_nb_bytes_written );
121
122 /**
123  * Writes the Colour Specification box.
124  *
125  * @param jp2                                   jpeg2000 file codec.
126  * @param p_nb_bytes_written    pointer to store the nb of bytes written by the function.
127  *
128  * @return      the data being copied.
129 */
130 static OPJ_BYTE * opj_jp2_write_colr(   opj_jp2_t *jp2,
131                                                                             OPJ_UINT32 * p_nb_bytes_written );
132
133 /**
134  * Writes a FTYP box - File type box
135  *
136  * @param       cio                     the stream to write data to.
137  * @param       jp2                     the jpeg2000 file codec.
138  * @param       p_manager       the user event manager.
139  *
140  * @return      true if writing was successful.
141  */
142 static OPJ_BOOL opj_jp2_write_ftyp(     opj_jp2_t *jp2,
143                                                                         opj_stream_private_t *cio,
144                                                                         opj_event_mgr_t * p_manager );
145
146 /**
147  * Reads a a FTYP box - File type box
148  *
149  * @param       p_header_data   the data contained in the FTYP box.
150  * @param       jp2                             the jpeg2000 file codec.
151  * @param       p_header_size   the size of the data contained in the FTYP box.
152  * @param       p_manager               the user event manager.
153  *
154  * @return true if the FTYP box is valid.
155  */
156 static OPJ_BOOL opj_jp2_read_ftyp(      opj_jp2_t *jp2,
157                                                                         OPJ_BYTE * p_header_data,
158                                                                         OPJ_UINT32 p_header_size,
159                                                                         opj_event_mgr_t * p_manager );
160
161 static OPJ_BOOL opj_jp2_skip_jp2c(      opj_jp2_t *jp2,
162                                                     opj_stream_private_t *cio,
163                                                     opj_event_mgr_t * p_manager );
164
165 /**
166  * Reads the Jpeg2000 file Header box - JP2 Header box (warning, this is a super box).
167  *
168  * @param       p_header_data   the data contained in the file header box.
169  * @param       jp2                             the jpeg2000 file codec.
170  * @param       p_header_size   the size of the data contained in the file header box.
171  * @param       p_manager               the user event manager.
172  *
173  * @return true if the JP2 Header box was successfully recognized.
174 */
175 static OPJ_BOOL opj_jp2_read_jp2h(  opj_jp2_t *jp2,
176                                     OPJ_BYTE *p_header_data,
177                                     OPJ_UINT32 p_header_size,
178                                     opj_event_mgr_t * p_manager );
179
180 /**
181  * Writes the Jpeg2000 file Header box - JP2 Header box (warning, this is a super box).
182  *
183  * @param  jp2      the jpeg2000 file codec.
184  * @param  stream      the stream to write data to.
185  * @param  p_manager  user event manager.
186  *
187  * @return true if writing was successful.
188  */
189 static OPJ_BOOL opj_jp2_write_jp2h(opj_jp2_t *jp2,
190                                                                                                                 opj_stream_private_t *stream,
191                                                                                                                 opj_event_mgr_t * p_manager );
192
193 /**
194  * Writes the Jpeg2000 codestream Header box - JP2C Header box. This function must be called AFTER the coding has been done.
195  *
196  * @param       cio                     the stream to write data to.
197  * @param       jp2                     the jpeg2000 file codec.
198  * @param       p_manager       user event manager.
199  *
200  * @return true if writing was successful.
201 */
202 static OPJ_BOOL opj_jp2_write_jp2c(     opj_jp2_t *jp2,
203                                                                     opj_stream_private_t *cio,
204                                                                     opj_event_mgr_t * p_manager );
205
206 #ifdef USE_JPIP
207 /**
208  * Write index Finder box
209  * @param cio     the stream to write to.
210  * @param       jp2                     the jpeg2000 file codec.
211  * @param       p_manager       user event manager.
212 */
213 static OPJ_BOOL opj_jpip_write_iptr(    opj_jp2_t *jp2,
214                                                                     opj_stream_private_t *cio,
215                                                                     opj_event_mgr_t * p_manager );
216
217 /**
218  * Write index Finder box
219  * @param cio     the stream to write to.
220  * @param       jp2                     the jpeg2000 file codec.
221  * @param       p_manager       user event manager.
222  */
223 static OPJ_BOOL opj_jpip_write_cidx(opj_jp2_t *jp2,
224   opj_stream_private_t *cio,
225   opj_event_mgr_t * p_manager );
226
227 /**
228  * Write file Index (superbox)
229  * @param cio     the stream to write to.
230  * @param       jp2                     the jpeg2000 file codec.
231  * @param       p_manager       user event manager.
232  */
233 static OPJ_BOOL opj_jpip_write_fidx(opj_jp2_t *jp2,
234   opj_stream_private_t *cio,
235   opj_event_mgr_t * p_manager );
236 #endif /* USE_JPIP */
237
238 /**
239  * Reads a jpeg2000 file signature box.
240  *
241  * @param       p_header_data   the data contained in the signature box.
242  * @param       jp2                             the jpeg2000 file codec.
243  * @param       p_header_size   the size of the data contained in the signature box.
244  * @param       p_manager               the user event manager.
245  *
246  * @return true if the file signature box is valid.
247  */
248 static OPJ_BOOL opj_jp2_read_jp(opj_jp2_t *jp2,
249                                 OPJ_BYTE * p_header_data,
250                                 OPJ_UINT32 p_header_size,
251                                 opj_event_mgr_t * p_manager);
252
253 /**
254  * Writes a jpeg2000 file signature box.
255  *
256  * @param cio the stream to write data to.
257  * @param       jp2                     the jpeg2000 file codec.
258  * @param p_manager the user event manager.
259  *
260  * @return true if writing was successful.
261  */
262 static OPJ_BOOL opj_jp2_write_jp(       opj_jp2_t *jp2,
263                                                     opj_stream_private_t *cio,
264                                                         opj_event_mgr_t * p_manager );
265
266 /**
267 Apply collected palette data
268 @param color Collector for profile, cdef and pclr data
269 @param image
270 */
271 static void opj_jp2_apply_pclr(opj_image_t *image, opj_jp2_color_t *color);
272
273 static void opj_jp2_free_pclr(opj_jp2_color_t *color);
274
275 /**
276  * Collect palette data
277  *
278  * @param jp2 JP2 handle
279  * @param p_pclr_header_data    FIXME DOC
280  * @param p_pclr_header_size    FIXME DOC
281  * @param p_manager
282  *
283  * @return Returns true if successful, returns false otherwise
284 */
285 static OPJ_BOOL opj_jp2_read_pclr(      opj_jp2_t *jp2,
286                                     OPJ_BYTE * p_pclr_header_data,
287                                     OPJ_UINT32 p_pclr_header_size,
288                                     opj_event_mgr_t * p_manager );
289
290 /**
291  * Collect component mapping data
292  *
293  * @param jp2                 JP2 handle
294  * @param p_cmap_header_data  FIXME DOC
295  * @param p_cmap_header_size  FIXME DOC
296  * @param p_manager           FIXME DOC
297  *
298  * @return Returns true if successful, returns false otherwise
299 */
300
301 static OPJ_BOOL opj_jp2_read_cmap(      opj_jp2_t * jp2,
302                                     OPJ_BYTE * p_cmap_header_data,
303                                     OPJ_UINT32 p_cmap_header_size,
304                                     opj_event_mgr_t * p_manager );
305
306 /**
307  * Reads the Color Specification box.
308  *
309  * @param       p_colr_header_data                      pointer to actual data (already read from file)
310  * @param       jp2                                                     the jpeg2000 file codec.
311  * @param       p_colr_header_size                      the size of the color header
312  * @param       p_manager                                       the user event manager.
313  *
314  * @return      true if the bpc header is valid, false else.
315 */
316 static OPJ_BOOL opj_jp2_read_colr(  opj_jp2_t *jp2,
317                                     OPJ_BYTE * p_colr_header_data,
318                                     OPJ_UINT32 p_colr_header_size,
319                                     opj_event_mgr_t * p_manager );
320
321 /*@}*/
322
323 /*@}*/
324
325 /**
326  * Sets up the procedures to do on writing header after the codestream.
327  * Developpers wanting to extend the library can add their own writing procedures.
328  */
329 static OPJ_BOOL opj_jp2_setup_end_header_writing (opj_jp2_t *jp2, opj_event_mgr_t * p_manager);
330
331 /**
332  * Sets up the procedures to do on reading header after the codestream.
333  * Developpers wanting to extend the library can add their own writing procedures.
334  */
335 static OPJ_BOOL opj_jp2_setup_end_header_reading (opj_jp2_t *jp2, opj_event_mgr_t * p_manager);
336
337 /**
338  * Reads a jpeg2000 file header structure.
339  *
340  * @param jp2 the jpeg2000 file header structure.
341  * @param stream the stream to read data from.
342  * @param p_manager the user event manager.
343  *
344  * @return true if the box is valid.
345  */
346 static OPJ_BOOL opj_jp2_read_header_procedure(  opj_jp2_t *jp2,
347                                                 opj_stream_private_t *stream,
348                                                 opj_event_mgr_t * p_manager );
349
350 /**
351  * Excutes the given procedures on the given codec.
352  *
353  * @param       p_procedure_list        the list of procedures to execute
354  * @param       jp2                                     the jpeg2000 file codec to execute the procedures on.
355  * @param       stream                                  the stream to execute the procedures on.
356  * @param       p_manager                       the user manager.
357  *
358  * @return      true                            if all the procedures were successfully executed.
359  */
360 static OPJ_BOOL opj_jp2_exec (  opj_jp2_t * jp2,
361                                 opj_procedure_list_t * p_procedure_list,
362                                 opj_stream_private_t *stream,
363                                 opj_event_mgr_t * p_manager );
364
365 /**
366  * Reads a box header. The box is the way data is packed inside a jpeg2000 file structure.
367  *
368  * @param       cio                                             the input stream to read data from.
369  * @param       box                                             the box structure to fill.
370  * @param       p_number_bytes_read             pointer to an int that will store the number of bytes read from the stream (shoul usually be 2).
371  * @param       p_manager                               user event manager.
372  *
373  * @return      true if the box is recognized, false otherwise
374 */
375 static OPJ_BOOL opj_jp2_read_boxhdr(opj_jp2_box_t *box,
376                                     OPJ_UINT32 * p_number_bytes_read,
377                                     opj_stream_private_t *cio,
378                                     opj_event_mgr_t * p_manager);
379
380 /**
381  * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
382  * are valid. Developpers wanting to extend the library can add their own validation procedures.
383  */
384 static OPJ_BOOL opj_jp2_setup_encoding_validation (opj_jp2_t *jp2, opj_event_mgr_t * p_manager);
385
386 /**
387  * Sets up the procedures to do on writing header. Developpers wanting to extend the library can add their own writing procedures.
388  */
389 static OPJ_BOOL opj_jp2_setup_header_writing (opj_jp2_t *jp2, opj_event_mgr_t * p_manager);
390
391 static OPJ_BOOL opj_jp2_default_validation (    opj_jp2_t * jp2,
392                                         opj_stream_private_t *cio,
393                                         opj_event_mgr_t * p_manager );
394
395 /**
396  * Finds the image execution function related to the given box id.
397  *
398  * @param       p_id    the id of the handler to fetch.
399  *
400  * @return      the given handler or NULL if it could not be found.
401  */
402 static const opj_jp2_header_handler_t * opj_jp2_img_find_handler (OPJ_UINT32 p_id);
403
404 /**
405  * Finds the execution function related to the given box id.
406  *
407  * @param       p_id    the id of the handler to fetch.
408  *
409  * @return      the given handler or NULL if it could not be found.
410  */
411 static const opj_jp2_header_handler_t * opj_jp2_find_handler (OPJ_UINT32 p_id );
412
413 static const opj_jp2_header_handler_t jp2_header [] =
414 {
415         {JP2_JP,opj_jp2_read_jp},
416         {JP2_FTYP,opj_jp2_read_ftyp},
417         {JP2_JP2H,opj_jp2_read_jp2h}
418 };
419
420 static const opj_jp2_header_handler_t jp2_img_header [] =
421 {
422         {JP2_IHDR,opj_jp2_read_ihdr},
423         {JP2_COLR,opj_jp2_read_colr},
424         {JP2_BPCC,opj_jp2_read_bpcc},
425         {JP2_PCLR,opj_jp2_read_pclr},
426         {JP2_CMAP,opj_jp2_read_cmap},
427         {JP2_CDEF,opj_jp2_read_cdef}
428
429 };
430
431 /**
432  * Reads a box header. The box is the way data is packed inside a jpeg2000 file structure. Data is read from a character string
433  *
434  * @param       box                                             the box structure to fill.
435  * @param       p_data                                  the character string to read data from.
436  * @param       p_number_bytes_read             pointer to an int that will store the number of bytes read from the stream (shoul usually be 2).
437  * @param       p_box_max_size                  the maximum number of bytes in the box.
438  * @param       p_manager         FIXME DOC
439  *
440  * @return      true if the box is recognized, false otherwise
441 */
442 static OPJ_BOOL opj_jp2_read_boxhdr_char(   opj_jp2_box_t *box,
443                                             OPJ_BYTE * p_data,
444                                             OPJ_UINT32 * p_number_bytes_read,
445                                             OPJ_UINT32 p_box_max_size,
446                                             opj_event_mgr_t * p_manager );
447
448 /**
449  * Sets up the validation ,i.e. adds the procedures to lauch to make sure the codec parameters
450  * are valid. Developpers wanting to extend the library can add their own validation procedures.
451  */
452 static OPJ_BOOL opj_jp2_setup_decoding_validation (opj_jp2_t *jp2, opj_event_mgr_t * p_manager);
453
454 /**
455  * Sets up the procedures to do on reading header.
456  * Developpers wanting to extend the library can add their own writing procedures.
457  */
458 static OPJ_BOOL opj_jp2_setup_header_reading (opj_jp2_t *jp2, opj_event_mgr_t * p_manager);
459
460 /* ----------------------------------------------------------------------- */
461 static OPJ_BOOL opj_jp2_read_boxhdr(opj_jp2_box_t *box,
462                               OPJ_UINT32 * p_number_bytes_read,
463                               opj_stream_private_t *cio,
464                               opj_event_mgr_t * p_manager )
465 {
466         /* read header from file */
467         OPJ_BYTE l_data_header [8];
468
469         /* preconditions */
470         assert(cio != 00);
471         assert(box != 00);
472         assert(p_number_bytes_read != 00);
473         assert(p_manager != 00);
474
475         *p_number_bytes_read = (OPJ_UINT32)opj_stream_read_data(cio,l_data_header,8,p_manager);
476         if (*p_number_bytes_read != 8) {
477                 return OPJ_FALSE;
478         }
479
480         /* process read data */
481         opj_read_bytes(l_data_header,&(box->length), 4);
482         opj_read_bytes(l_data_header+4,&(box->type), 4);
483     
484   if(box->length == 0)/* last box */
485   {
486     const OPJ_OFF_T bleft = opj_stream_get_number_byte_left(cio);
487     if (bleft > (OPJ_OFF_T)(0xFFFFFFFFU - 8U)) {
488       opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
489       return OPJ_FALSE;
490     }
491     box->length = (OPJ_UINT32)bleft + 8U;
492     assert( (OPJ_OFF_T)box->length == bleft + 8 );
493     return OPJ_TRUE;
494   }
495
496         /* do we have a "special very large box ?" */
497         /* read then the XLBox */
498         if (box->length == 1) {
499                 OPJ_UINT32 l_xl_part_size;
500
501                 OPJ_UINT32 l_nb_bytes_read = (OPJ_UINT32)opj_stream_read_data(cio,l_data_header,8,p_manager);
502                 if (l_nb_bytes_read != 8) {
503                         if (l_nb_bytes_read > 0) {
504                                 *p_number_bytes_read += l_nb_bytes_read;
505                         }
506
507                         return OPJ_FALSE;
508                 }
509
510         *p_number_bytes_read = 16;
511                 opj_read_bytes(l_data_header,&l_xl_part_size, 4);
512                 if (l_xl_part_size != 0) {
513                         opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
514                         return OPJ_FALSE;
515                 }
516                 opj_read_bytes(l_data_header+4,&(box->length), 4);
517         }
518     return OPJ_TRUE;
519 }
520
521 #if 0
522 static void jp2_write_url(opj_cio_t *cio, char *Idx_file) {
523         OPJ_UINT32 i;
524         opj_jp2_box_t box;
525
526         box.init_pos = cio_tell(cio);
527         cio_skip(cio, 4);
528         cio_write(cio, JP2_URL, 4);     /* DBTL */
529         cio_write(cio, 0, 1);           /* VERS */
530         cio_write(cio, 0, 3);           /* FLAG */
531
532         if(Idx_file) {
533                 for (i = 0; i < strlen(Idx_file); i++) {
534                         cio_write(cio, Idx_file[i], 1);
535                 }
536         }
537
538         box.length = cio_tell(cio) - box.init_pos;
539         cio_seek(cio, box.init_pos);
540         cio_write(cio, box.length, 4);  /* L */
541         cio_seek(cio, box.init_pos + box.length);
542 }
543 #endif
544
545 static OPJ_BOOL opj_jp2_read_ihdr( opj_jp2_t *jp2,
546                             OPJ_BYTE *p_image_header_data,
547                             OPJ_UINT32 p_image_header_size,
548                             opj_event_mgr_t * p_manager )
549 {
550         /* preconditions */
551         assert(p_image_header_data != 00);
552         assert(jp2 != 00);
553         assert(p_manager != 00);
554
555         if (p_image_header_size != 14) {
556                 opj_event_msg(p_manager, EVT_ERROR, "Bad image header box (bad size)\n");
557                 return OPJ_FALSE;
558         }
559
560         opj_read_bytes(p_image_header_data,&(jp2->h),4);                        /* HEIGHT */
561         p_image_header_data += 4;
562         opj_read_bytes(p_image_header_data,&(jp2->w),4);                        /* WIDTH */
563         p_image_header_data += 4;
564         opj_read_bytes(p_image_header_data,&(jp2->numcomps),2);         /* NC */
565         p_image_header_data += 2;
566
567         /* allocate memory for components */
568         jp2->comps = (opj_jp2_comps_t*) opj_calloc(jp2->numcomps, sizeof(opj_jp2_comps_t));
569         if (jp2->comps == 0) {
570                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle image header (ihdr)\n");
571                 return OPJ_FALSE;
572         }
573
574         opj_read_bytes(p_image_header_data,&(jp2->bpc),1);                      /* BPC */
575         ++ p_image_header_data;
576
577         opj_read_bytes(p_image_header_data,&(jp2->C),1);                        /* C */
578         ++ p_image_header_data;
579
580         /* Should be equal to 7 cf. chapter about image header box of the norm */
581         if (jp2->C != 7){
582                 opj_event_msg(p_manager, EVT_INFO, "JP2 IHDR box: compression type indicate that the file is not a conforming JP2 file (%d) \n", jp2->C);
583         }
584
585         opj_read_bytes(p_image_header_data,&(jp2->UnkC),1);                     /* UnkC */
586         ++ p_image_header_data;
587         opj_read_bytes(p_image_header_data,&(jp2->IPR),1);                      /* IPR */
588         ++ p_image_header_data;
589
590         return OPJ_TRUE;
591 }
592
593 static OPJ_BYTE * opj_jp2_write_ihdr(opj_jp2_t *jp2,
594                               OPJ_UINT32 * p_nb_bytes_written
595                               )
596 {
597         OPJ_BYTE * l_ihdr_data,* l_current_ihdr_ptr;
598         
599         /* preconditions */
600         assert(jp2 != 00);
601         assert(p_nb_bytes_written != 00);
602
603         /* default image header is 22 bytes wide */
604         l_ihdr_data = (OPJ_BYTE *) opj_calloc(1,22);
605         if (l_ihdr_data == 00) {
606                 return 00;
607         }
608
609         l_current_ihdr_ptr = l_ihdr_data;
610         
611         opj_write_bytes(l_current_ihdr_ptr,22,4);                               /* write box size */
612         l_current_ihdr_ptr+=4;
613
614         opj_write_bytes(l_current_ihdr_ptr,JP2_IHDR, 4);                /* IHDR */
615         l_current_ihdr_ptr+=4;
616         
617         opj_write_bytes(l_current_ihdr_ptr,jp2->h, 4);          /* HEIGHT */
618         l_current_ihdr_ptr+=4;
619         
620         opj_write_bytes(l_current_ihdr_ptr, jp2->w, 4);         /* WIDTH */
621         l_current_ihdr_ptr+=4;
622         
623         opj_write_bytes(l_current_ihdr_ptr, jp2->numcomps, 2);          /* NC */
624         l_current_ihdr_ptr+=2;
625         
626         opj_write_bytes(l_current_ihdr_ptr, jp2->bpc, 1);               /* BPC */
627         ++l_current_ihdr_ptr;
628         
629         opj_write_bytes(l_current_ihdr_ptr, jp2->C, 1);         /* C : Always 7 */
630         ++l_current_ihdr_ptr;
631         
632         opj_write_bytes(l_current_ihdr_ptr, jp2->UnkC, 1);              /* UnkC, colorspace unknown */
633         ++l_current_ihdr_ptr;
634         
635         opj_write_bytes(l_current_ihdr_ptr, jp2->IPR, 1);               /* IPR, no intellectual property */
636         ++l_current_ihdr_ptr;
637         
638         *p_nb_bytes_written = 22;
639         
640         return l_ihdr_data;
641 }
642
643 static OPJ_BYTE * opj_jp2_write_bpcc(   opj_jp2_t *jp2,
644                                                         OPJ_UINT32 * p_nb_bytes_written
645                                 )
646 {
647         OPJ_UINT32 i;
648         /* room for 8 bytes for box and 1 byte for each component */
649         OPJ_UINT32 l_bpcc_size = 8 + jp2->numcomps;
650         OPJ_BYTE * l_bpcc_data,* l_current_bpcc_ptr;
651         
652         /* preconditions */
653         assert(jp2 != 00);
654         assert(p_nb_bytes_written != 00);
655
656         l_bpcc_data = (OPJ_BYTE *) opj_calloc(1,l_bpcc_size);
657         if (l_bpcc_data == 00) {
658                 return 00;
659         }
660
661         l_current_bpcc_ptr = l_bpcc_data;
662
663         opj_write_bytes(l_current_bpcc_ptr,l_bpcc_size,4);                              /* write box size */
664         l_current_bpcc_ptr += 4;
665         
666         opj_write_bytes(l_current_bpcc_ptr,JP2_BPCC,4);                                 /* BPCC */
667         l_current_bpcc_ptr += 4;
668
669         for (i = 0; i < jp2->numcomps; ++i)  {
670                 opj_write_bytes(l_current_bpcc_ptr, jp2->comps[i].bpcc, 1); /* write each component information */
671                 ++l_current_bpcc_ptr;
672         }
673
674         *p_nb_bytes_written = l_bpcc_size;
675         
676         return l_bpcc_data;
677 }
678
679 static OPJ_BOOL opj_jp2_read_bpcc( opj_jp2_t *jp2,
680                             OPJ_BYTE * p_bpc_header_data,
681                             OPJ_UINT32 p_bpc_header_size,
682                             opj_event_mgr_t * p_manager
683                             )
684 {
685         OPJ_UINT32 i;
686
687         /* preconditions */
688         assert(p_bpc_header_data != 00);
689         assert(jp2 != 00);
690         assert(p_manager != 00);
691
692         
693         if (jp2->bpc != 255 ){
694                 opj_event_msg(p_manager, EVT_WARNING, "A BPCC header box is available although BPC given by the IHDR box (%d) indicate components bit depth is constant\n",jp2->bpc);
695         }
696
697         /* and length is relevant */
698         if (p_bpc_header_size != jp2->numcomps) {
699                 opj_event_msg(p_manager, EVT_ERROR, "Bad BPCC header box (bad size)\n");
700                 return OPJ_FALSE;
701         }
702
703         /* read info for each component */
704         for (i = 0; i < jp2->numcomps; ++i) {
705                 opj_read_bytes(p_bpc_header_data,&jp2->comps[i].bpcc ,1);       /* read each BPCC component */
706                 ++p_bpc_header_data;
707         }
708
709         return OPJ_TRUE;
710 }
711 static OPJ_BYTE * opj_jp2_write_cdef(opj_jp2_t *jp2, OPJ_UINT32 * p_nb_bytes_written)
712 {
713         /* room for 8 bytes for box, 2 for n */
714         OPJ_UINT32 l_cdef_size = 10;
715         OPJ_BYTE * l_cdef_data,* l_current_cdef_ptr;
716         OPJ_UINT32 l_value;
717         OPJ_UINT16 i;
718
719         /* preconditions */
720         assert(jp2 != 00);
721         assert(p_nb_bytes_written != 00);
722         assert(jp2->color.jp2_cdef != 00);
723         assert(jp2->color.jp2_cdef->info != 00);
724         assert(jp2->color.jp2_cdef->n > 0U);
725
726         l_cdef_size += 6U * jp2->color.jp2_cdef->n;
727
728         l_cdef_data = (OPJ_BYTE *) opj_malloc(l_cdef_size);
729         if (l_cdef_data == 00) {
730                 return 00;
731         }
732
733         l_current_cdef_ptr = l_cdef_data;
734         
735         opj_write_bytes(l_current_cdef_ptr,l_cdef_size,4);                      /* write box size */
736         l_current_cdef_ptr += 4;
737
738         opj_write_bytes(l_current_cdef_ptr,JP2_CDEF,4);                                 /* BPCC */
739         l_current_cdef_ptr += 4;
740
741         l_value = jp2->color.jp2_cdef->n;
742         opj_write_bytes(l_current_cdef_ptr,l_value,2);                                  /* N */
743         l_current_cdef_ptr += 2;
744
745         for (i = 0U; i < jp2->color.jp2_cdef->n; ++i) {
746                 l_value = jp2->color.jp2_cdef->info[i].cn;
747                 opj_write_bytes(l_current_cdef_ptr,l_value,2);                                  /* Cni */
748                 l_current_cdef_ptr += 2;
749                 l_value = jp2->color.jp2_cdef->info[i].typ;
750                 opj_write_bytes(l_current_cdef_ptr,l_value,2);                                  /* Typi */
751                 l_current_cdef_ptr += 2;
752                 l_value = jp2->color.jp2_cdef->info[i].asoc;
753                 opj_write_bytes(l_current_cdef_ptr,l_value,2);                                  /* Asoci */
754                 l_current_cdef_ptr += 2;
755         }
756         *p_nb_bytes_written = l_cdef_size;
757
758         return l_cdef_data;
759 }
760
761 static OPJ_BYTE * opj_jp2_write_colr(  opj_jp2_t *jp2,
762                                                             OPJ_UINT32 * p_nb_bytes_written
763                                 )
764 {
765         /* room for 8 bytes for box 3 for common data and variable upon profile*/
766         OPJ_UINT32 l_colr_size = 11;
767         OPJ_BYTE * l_colr_data,* l_current_colr_ptr;
768
769         /* preconditions */
770         assert(jp2 != 00);
771         assert(p_nb_bytes_written != 00);
772     assert(jp2->meth == 1 || jp2->meth == 2);
773
774         switch (jp2->meth) { 
775                 case 1 :
776                         l_colr_size += 4; /* EnumCS */
777                         break;
778                 case 2 :
779             assert(jp2->color.icc_profile_len); /* ICC profile */
780             l_colr_size += jp2->color.icc_profile_len;
781                         break;
782                 default :
783                         return 00;
784         }
785
786         l_colr_data = (OPJ_BYTE *) opj_calloc(1,l_colr_size);
787         if (l_colr_data == 00) {
788                 return 00;
789         }
790         
791         l_current_colr_ptr = l_colr_data;
792
793         opj_write_bytes(l_current_colr_ptr,l_colr_size,4);                              /* write box size */
794         l_current_colr_ptr += 4;
795         
796         opj_write_bytes(l_current_colr_ptr,JP2_COLR,4);                                 /* BPCC */
797         l_current_colr_ptr += 4;
798         
799         opj_write_bytes(l_current_colr_ptr, jp2->meth,1);                               /* METH */
800         ++l_current_colr_ptr;
801         
802         opj_write_bytes(l_current_colr_ptr, jp2->precedence,1);                 /* PRECEDENCE */
803         ++l_current_colr_ptr;
804         
805         opj_write_bytes(l_current_colr_ptr, jp2->approx,1);                             /* APPROX */
806         ++l_current_colr_ptr;
807         
808         if (jp2->meth == 1) { /* Meth value is restricted to 1 or 2 (Table I.9 of part 1) */
809         opj_write_bytes(l_current_colr_ptr, jp2->enumcs,4); }       /* EnumCS */
810     else {
811         if (jp2->meth == 2) {                                      /* ICC profile */
812             OPJ_UINT32 i;
813             for(i = 0; i < jp2->color.icc_profile_len; ++i) {
814                 opj_write_bytes(l_current_colr_ptr, jp2->color.icc_profile_buf[i], 1);
815                 ++l_current_colr_ptr;
816             }
817         }
818         }
819
820         *p_nb_bytes_written = l_colr_size;
821         
822         return l_colr_data;
823 }
824
825 static void opj_jp2_free_pclr(opj_jp2_color_t *color)
826 {
827     opj_free(color->jp2_pclr->channel_sign);
828     opj_free(color->jp2_pclr->channel_size);
829     opj_free(color->jp2_pclr->entries);
830
831         if(color->jp2_pclr->cmap) opj_free(color->jp2_pclr->cmap);
832
833     opj_free(color->jp2_pclr); color->jp2_pclr = NULL;
834 }
835
836 static OPJ_BOOL opj_jp2_check_color(opj_image_t *image, opj_jp2_color_t *color, opj_event_mgr_t *p_manager)
837 {
838         OPJ_UINT16 i;
839
840         /* testcase 4149.pdf.SIGSEGV.cf7.3501 */
841         if (color->jp2_cdef) {
842                 opj_jp2_cdef_info_t *info = color->jp2_cdef->info;
843                 OPJ_UINT16 n = color->jp2_cdef->n;
844                 OPJ_UINT32 nr_channels = image->numcomps; /* FIXME image->numcomps == jp2->numcomps before color is applied ??? */
845
846                 /* cdef applies to cmap channels if any */
847                 if (color->jp2_pclr && color->jp2_pclr->cmap) {
848                         nr_channels = (OPJ_UINT32)color->jp2_pclr->nr_channels;
849                 }
850
851                 for (i = 0; i < n; i++) {
852                         if (info[i].cn >= nr_channels) {
853                                 opj_event_msg(p_manager, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].cn, nr_channels);
854                                 return OPJ_FALSE;
855                         }
856                         if (info[i].asoc == 65535U) continue;
857
858                         if (info[i].asoc > 0 && (OPJ_UINT32)(info[i].asoc - 1) >= nr_channels) {
859                                 opj_event_msg(p_manager, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].asoc - 1, nr_channels);
860                                 return OPJ_FALSE;
861                         }
862                 }
863
864                 /* issue 397 */
865                 /* ISO 15444-1 states that if cdef is present, it shall contain a complete list of channel definitions. */
866                 while (nr_channels > 0)
867                 {
868                         for(i = 0; i < n; ++i) {
869                                 if ((OPJ_UINT32)info[i].cn == (nr_channels - 1U)) {
870                                         break;
871                                 }
872                         }
873                         if (i == n) {
874                                 opj_event_msg(p_manager, EVT_ERROR, "Incomplete channel definitions.\n");
875                                 return OPJ_FALSE;
876                         }
877                         --nr_channels;
878                 }
879         }
880
881         /* testcases 451.pdf.SIGSEGV.f4c.3723, 451.pdf.SIGSEGV.5b5.3723 and
882            66ea31acbb0f23a2bbc91f64d69a03f5_signal_sigsegv_13937c0_7030_5725.pdf */
883         if (color->jp2_pclr && color->jp2_pclr->cmap) {
884                 OPJ_UINT16 nr_channels = color->jp2_pclr->nr_channels;
885                 opj_jp2_cmap_comp_t *cmap = color->jp2_pclr->cmap;
886                 OPJ_BOOL *pcol_usage, is_sane = OPJ_TRUE;
887
888                 /* verify that all original components match an existing one */
889                 for (i = 0; i < nr_channels; i++) {
890                         if (cmap[i].cmp >= image->numcomps) {
891                                 opj_event_msg(p_manager, EVT_ERROR, "Invalid component index %d (>= %d).\n", cmap[i].cmp, image->numcomps);
892                                 is_sane = OPJ_FALSE;
893                         }
894                 }
895
896                 pcol_usage = (OPJ_BOOL *) opj_calloc(nr_channels, sizeof(OPJ_BOOL));
897                 if (!pcol_usage) {
898                         opj_event_msg(p_manager, EVT_ERROR, "Unexpected OOM.\n");
899                         return OPJ_FALSE;
900                 }
901                 /* verify that no component is targeted more than once */
902                 for (i = 0; i < nr_channels; i++) {
903       OPJ_UINT16 pcol = cmap[i].pcol;
904       assert(cmap[i].mtyp == 0 || cmap[i].mtyp == 1);
905                         if (pcol >= nr_channels) {
906                                 opj_event_msg(p_manager, EVT_ERROR, "Invalid component/palette index for direct mapping %d.\n", pcol);
907                                 is_sane = OPJ_FALSE;
908                         }
909                         else if (pcol_usage[pcol] && cmap[i].mtyp == 1) {
910                                 opj_event_msg(p_manager, EVT_ERROR, "Component %d is mapped twice.\n", pcol);
911                                 is_sane = OPJ_FALSE;
912                         }
913       else if (cmap[i].mtyp == 0 && cmap[i].pcol != 0) {
914         /* I.5.3.5 PCOL: If the value of the MTYP field for this channel is 0, then
915          * the value of this field shall be 0. */
916                                 opj_event_msg(p_manager, EVT_ERROR, "Direct use at #%d however pcol=%d.\n", i, pcol);
917                                 is_sane = OPJ_FALSE;
918       }
919                         else
920                                 pcol_usage[pcol] = OPJ_TRUE;
921                 }
922                 /* verify that all components are targeted at least once */
923                 for (i = 0; i < nr_channels; i++) {
924                         if (!pcol_usage[i] && cmap[i].mtyp != 0) {
925                                 opj_event_msg(p_manager, EVT_ERROR, "Component %d doesn't have a mapping.\n", i);
926                                 is_sane = OPJ_FALSE;
927                         }
928                 }
929                 /* Issue 235/447 weird cmap */
930                 if (1 && is_sane && (image->numcomps==1U)) {
931                         for (i = 0; i < nr_channels; i++) {
932                                 if (!pcol_usage[i]) {
933                                         is_sane = 0U;
934                                         opj_event_msg(p_manager, EVT_WARNING, "Component mapping seems wrong. Trying to correct.\n", i);
935                                         break;
936                                 }
937                         }
938                         if (!is_sane) {
939                                 is_sane = OPJ_TRUE;
940                                 for (i = 0; i < nr_channels; i++) {
941                                         cmap[i].mtyp = 1U;
942                                         cmap[i].pcol = (OPJ_BYTE) i;
943                                 }
944                         }
945                 }
946                 opj_free(pcol_usage);
947                 if (!is_sane) {
948                         return OPJ_FALSE;
949                 }
950         }
951
952         return OPJ_TRUE;
953 }
954
955 /* file9.jp2 */
956 static void opj_jp2_apply_pclr(opj_image_t *image, opj_jp2_color_t *color)
957 {
958         opj_image_comp_t *old_comps, *new_comps;
959         OPJ_BYTE *channel_size, *channel_sign;
960         OPJ_UINT32 *entries;
961         opj_jp2_cmap_comp_t *cmap;
962         OPJ_INT32 *src, *dst;
963         OPJ_UINT32 j, max;
964         OPJ_UINT16 i, nr_channels, cmp, pcol;
965         OPJ_INT32 k, top_k;
966
967         channel_size = color->jp2_pclr->channel_size;
968         channel_sign = color->jp2_pclr->channel_sign;
969         entries = color->jp2_pclr->entries;
970         cmap = color->jp2_pclr->cmap;
971         nr_channels = color->jp2_pclr->nr_channels;
972
973         old_comps = image->comps;
974         new_comps = (opj_image_comp_t*)
975                         opj_malloc(nr_channels * sizeof(opj_image_comp_t));
976         if (!new_comps) {
977                 /* FIXME no error code for opj_jp2_apply_pclr */
978                 /* FIXME event manager error callback */
979                 return;
980         }
981         for(i = 0; i < nr_channels; ++i) {
982                 pcol = cmap[i].pcol; cmp = cmap[i].cmp;
983
984                 /* Direct use */
985     if(cmap[i].mtyp == 0){
986       assert( pcol == 0 );
987       new_comps[i] = old_comps[cmp];
988     } else {
989       assert( i == pcol );
990       new_comps[pcol] = old_comps[cmp];
991     }
992
993                 /* Palette mapping: */
994                 new_comps[i].data = (OPJ_INT32*)
995                                 opj_malloc(old_comps[cmp].w * old_comps[cmp].h * sizeof(OPJ_INT32));
996                 if (!new_comps[i].data) {
997                         opj_free(new_comps);
998                         new_comps = NULL;
999                         /* FIXME no error code for opj_jp2_apply_pclr */
1000                         /* FIXME event manager error callback */
1001                         return;
1002                 }
1003                 new_comps[i].prec = channel_size[i];
1004                 new_comps[i].sgnd = channel_sign[i];
1005         }
1006
1007         top_k = color->jp2_pclr->nr_entries - 1;
1008
1009         for(i = 0; i < nr_channels; ++i) {
1010                 /* Palette mapping: */
1011                 cmp = cmap[i].cmp; pcol = cmap[i].pcol;
1012                 src = old_comps[cmp].data;
1013     assert( src );
1014                 max = new_comps[pcol].w * new_comps[pcol].h;
1015
1016                 /* Direct use: */
1017     if(cmap[i].mtyp == 0) {
1018       assert( cmp == 0 );
1019       dst = new_comps[i].data;
1020       assert( dst );
1021       for(j = 0; j < max; ++j) {
1022         dst[j] = src[j];
1023       }
1024     }
1025     else {
1026       assert( i == pcol );
1027       dst = new_comps[pcol].data;
1028       assert( dst );
1029       for(j = 0; j < max; ++j) {
1030         /* The index */
1031         if((k = src[j]) < 0) k = 0; else if(k > top_k) k = top_k;
1032
1033         /* The colour */
1034         dst[j] = (OPJ_INT32)entries[k * nr_channels + pcol];
1035         }
1036     }
1037         }
1038
1039         max = image->numcomps;
1040         for(i = 0; i < max; ++i) {
1041                 if(old_comps[i].data) opj_free(old_comps[i].data);
1042         }
1043
1044         opj_free(old_comps);
1045         image->comps = new_comps;
1046         image->numcomps = nr_channels;
1047
1048         opj_jp2_free_pclr(color);
1049
1050 }/* apply_pclr() */
1051
1052 static OPJ_BOOL opj_jp2_read_pclr(      opj_jp2_t *jp2,
1053                             OPJ_BYTE * p_pclr_header_data,
1054                             OPJ_UINT32 p_pclr_header_size,
1055                             opj_event_mgr_t * p_manager
1056                             )
1057 {
1058         opj_jp2_pclr_t *jp2_pclr;
1059         OPJ_BYTE *channel_size, *channel_sign;
1060         OPJ_UINT32 *entries;
1061         OPJ_UINT16 nr_entries,nr_channels;
1062         OPJ_UINT16 i, j;
1063         OPJ_UINT32 l_value;
1064         OPJ_BYTE *orig_header_data = p_pclr_header_data;
1065
1066         /* preconditions */
1067         assert(p_pclr_header_data != 00);
1068         assert(jp2 != 00);
1069         assert(p_manager != 00);
1070     (void)p_pclr_header_size;
1071
1072         if(jp2->color.jp2_pclr)
1073                 return OPJ_FALSE;
1074
1075         if (p_pclr_header_size < 3)
1076                 return OPJ_FALSE;
1077
1078         opj_read_bytes(p_pclr_header_data, &l_value , 2);       /* NE */
1079         p_pclr_header_data += 2;
1080         nr_entries = (OPJ_UINT16) l_value;
1081         if ((nr_entries == 0U) || (nr_entries > 1024U)) {
1082                 opj_event_msg(p_manager, EVT_ERROR, "Invalid PCLR box. Reports %d entries\n", (int)nr_entries);
1083                 return OPJ_FALSE;
1084         }
1085
1086         opj_read_bytes(p_pclr_header_data, &l_value , 1);       /* NPC */
1087         ++p_pclr_header_data;
1088         nr_channels = (OPJ_UINT16) l_value;
1089         if (nr_channels == 0U) {
1090                 opj_event_msg(p_manager, EVT_ERROR, "Invalid PCLR box. Reports 0 palette columns\n");
1091                 return OPJ_FALSE;
1092         }
1093
1094         if (p_pclr_header_size < 3 + (OPJ_UINT32)nr_channels)
1095                 return OPJ_FALSE;
1096
1097         entries = (OPJ_UINT32*) opj_malloc((size_t)nr_channels * nr_entries * sizeof(OPJ_UINT32));
1098     if (!entries)
1099         return OPJ_FALSE;
1100         channel_size = (OPJ_BYTE*) opj_malloc(nr_channels);
1101     if (!channel_size)
1102     {
1103         opj_free(entries);
1104         return OPJ_FALSE;
1105     }
1106         channel_sign = (OPJ_BYTE*) opj_malloc(nr_channels);
1107         if (!channel_sign)
1108         {
1109         opj_free(entries);
1110         opj_free(channel_size);
1111         return OPJ_FALSE;
1112         }
1113
1114         jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t));
1115     if (!jp2_pclr)
1116     {
1117         opj_free(entries);
1118         opj_free(channel_size);
1119         opj_free(channel_sign);
1120         return OPJ_FALSE;
1121     }
1122
1123         jp2_pclr->channel_sign = channel_sign;
1124         jp2_pclr->channel_size = channel_size;
1125         jp2_pclr->entries = entries;
1126         jp2_pclr->nr_entries = nr_entries;
1127         jp2_pclr->nr_channels = (OPJ_BYTE) l_value;
1128         jp2_pclr->cmap = NULL;
1129
1130         jp2->color.jp2_pclr = jp2_pclr;
1131
1132         for(i = 0; i < nr_channels; ++i) {
1133                 opj_read_bytes(p_pclr_header_data, &l_value , 1);       /* Bi */
1134                 ++p_pclr_header_data;
1135
1136                 channel_size[i] = (OPJ_BYTE)((l_value & 0x7f) + 1);
1137                 channel_sign[i] = (l_value & 0x80) ? 1 : 0;
1138         }
1139
1140         for(j = 0; j < nr_entries; ++j) {
1141                 for(i = 0; i < nr_channels; ++i) {
1142                         OPJ_UINT32 bytes_to_read = (OPJ_UINT32)((channel_size[i]+7)>>3);
1143
1144                         if (bytes_to_read > sizeof(OPJ_UINT32))
1145                                 bytes_to_read = sizeof(OPJ_UINT32);
1146                         if ((ptrdiff_t)p_pclr_header_size < (ptrdiff_t)(p_pclr_header_data - orig_header_data) + (ptrdiff_t)bytes_to_read)
1147                                 return OPJ_FALSE;
1148
1149                         opj_read_bytes(p_pclr_header_data, &l_value , bytes_to_read);   /* Cji */
1150                         p_pclr_header_data += bytes_to_read;
1151                         *entries = (OPJ_UINT32) l_value;
1152                         entries++;
1153                 }
1154         }
1155
1156         return OPJ_TRUE;
1157 }
1158
1159 static OPJ_BOOL opj_jp2_read_cmap(      opj_jp2_t * jp2,
1160                             OPJ_BYTE * p_cmap_header_data,
1161                             OPJ_UINT32 p_cmap_header_size,
1162                             opj_event_mgr_t * p_manager
1163                             )
1164 {
1165         opj_jp2_cmap_comp_t *cmap;
1166         OPJ_BYTE i, nr_channels;
1167         OPJ_UINT32 l_value;
1168
1169         /* preconditions */
1170         assert(jp2 != 00);
1171         assert(p_cmap_header_data != 00);
1172         assert(p_manager != 00);
1173     (void)p_cmap_header_size;
1174
1175         /* Need nr_channels: */
1176         if(jp2->color.jp2_pclr == NULL) {
1177                 opj_event_msg(p_manager, EVT_ERROR, "Need to read a PCLR box before the CMAP box.\n");
1178                 return OPJ_FALSE;
1179         }
1180
1181         /* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box
1182          * inside a JP2 Header box' :
1183         */
1184         if(jp2->color.jp2_pclr->cmap) {
1185                 opj_event_msg(p_manager, EVT_ERROR, "Only one CMAP box is allowed.\n");
1186                 return OPJ_FALSE;
1187         }
1188
1189         nr_channels = jp2->color.jp2_pclr->nr_channels;
1190         if (p_cmap_header_size < (OPJ_UINT32)nr_channels * 4) {
1191                 opj_event_msg(p_manager, EVT_ERROR, "Insufficient data for CMAP box.\n");
1192                 return OPJ_FALSE;
1193         }
1194
1195         cmap = (opj_jp2_cmap_comp_t*) opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t));
1196     if (!cmap)
1197         return OPJ_FALSE;
1198
1199
1200         for(i = 0; i < nr_channels; ++i) {
1201                 opj_read_bytes(p_cmap_header_data, &l_value, 2);                        /* CMP^i */
1202                 p_cmap_header_data +=2;
1203                 cmap[i].cmp = (OPJ_UINT16) l_value;
1204
1205                 opj_read_bytes(p_cmap_header_data, &l_value, 1);                        /* MTYP^i */
1206                 ++p_cmap_header_data;
1207                 cmap[i].mtyp = (OPJ_BYTE) l_value;
1208
1209                 opj_read_bytes(p_cmap_header_data, &l_value, 1);                        /* PCOL^i */
1210                 ++p_cmap_header_data;
1211                 cmap[i].pcol = (OPJ_BYTE) l_value;
1212         }
1213
1214         jp2->color.jp2_pclr->cmap = cmap;
1215
1216         return OPJ_TRUE;
1217 }
1218
1219 static void opj_jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color, opj_event_mgr_t *manager)
1220 {
1221         opj_jp2_cdef_info_t *info;
1222         OPJ_UINT16 i, n, cn, asoc, acn;
1223         
1224         info = color->jp2_cdef->info;
1225         n = color->jp2_cdef->n;
1226         
1227         for(i = 0; i < n; ++i)
1228         {
1229                 /* WATCH: acn = asoc - 1 ! */
1230                 asoc = info[i].asoc;
1231                 cn = info[i].cn;
1232                 
1233                 if( cn >= image->numcomps)
1234                 {
1235                         opj_event_msg(manager, EVT_WARNING, "opj_jp2_apply_cdef: cn=%d, numcomps=%d\n", cn, image->numcomps);
1236                         continue;
1237                 }
1238                 if(asoc == 0 || asoc == 65535)
1239                 {
1240                         image->comps[cn].alpha = info[i].typ;
1241                         continue;
1242                 }
1243                 
1244                 acn = (OPJ_UINT16)(asoc - 1);
1245                 if( acn >= image->numcomps )
1246                 {
1247                         opj_event_msg(manager, EVT_WARNING, "opj_jp2_apply_cdef: acn=%d, numcomps=%d\n", acn, image->numcomps);
1248                         continue;
1249                 }
1250                 
1251                 /* Swap only if color channel */
1252                 if((cn != acn) && (info[i].typ == 0))
1253                 {
1254                         opj_image_comp_t saved;
1255                         OPJ_UINT16 j;
1256                         
1257                         memcpy(&saved, &image->comps[cn], sizeof(opj_image_comp_t));
1258                         memcpy(&image->comps[cn], &image->comps[acn], sizeof(opj_image_comp_t));
1259                         memcpy(&image->comps[acn], &saved, sizeof(opj_image_comp_t));
1260                         
1261                         /* Swap channels in following channel definitions, don't bother with j <= i that are already processed */
1262                         for (j = (OPJ_UINT16)(i + 1U); j < n ; ++j)
1263                         {
1264                                 if (info[j].cn == cn) {
1265                                         info[j].cn = acn;
1266                                 }
1267                                 else if (info[j].cn == acn) {
1268                                         info[j].cn = cn;
1269                                 }
1270                                 /* asoc is related to color index. Do not update. */
1271                         }
1272                 }
1273                 
1274                 image->comps[cn].alpha = info[i].typ;
1275         }
1276         
1277         if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info);
1278         
1279         opj_free(color->jp2_cdef); color->jp2_cdef = NULL;
1280         
1281 }/* jp2_apply_cdef() */
1282
1283 static OPJ_BOOL opj_jp2_read_cdef(      opj_jp2_t * jp2,
1284                             OPJ_BYTE * p_cdef_header_data,
1285                                                         OPJ_UINT32 p_cdef_header_size,
1286                                                         opj_event_mgr_t * p_manager
1287                             )
1288 {
1289         opj_jp2_cdef_info_t *cdef_info;
1290         OPJ_UINT16 i;
1291         OPJ_UINT32 l_value;
1292
1293         /* preconditions */
1294         assert(jp2 != 00);
1295         assert(p_cdef_header_data != 00);
1296         assert(p_manager != 00);
1297     (void)p_cdef_header_size;
1298
1299         /* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box
1300          * inside a JP2 Header box.'*/
1301         if(jp2->color.jp2_cdef) return OPJ_FALSE;
1302
1303         if (p_cdef_header_size < 2) {
1304                 opj_event_msg(p_manager, EVT_ERROR, "Insufficient data for CDEF box.\n");
1305                 return OPJ_FALSE;
1306         }
1307
1308         opj_read_bytes(p_cdef_header_data,&l_value ,2);                 /* N */
1309         p_cdef_header_data+= 2;
1310
1311         if ( (OPJ_UINT16)l_value == 0){ /* szukw000: FIXME */
1312                 opj_event_msg(p_manager, EVT_ERROR, "Number of channel description is equal to zero in CDEF box.\n");
1313                 return OPJ_FALSE;
1314         }
1315
1316         if (p_cdef_header_size < 2 + (OPJ_UINT32)(OPJ_UINT16)l_value * 6) {
1317                 opj_event_msg(p_manager, EVT_ERROR, "Insufficient data for CDEF box.\n");
1318                 return OPJ_FALSE;
1319         }
1320
1321         cdef_info = (opj_jp2_cdef_info_t*) opj_malloc(l_value * sizeof(opj_jp2_cdef_info_t));
1322         if (!cdef_info)
1323                 return OPJ_FALSE;
1324
1325         jp2->color.jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
1326         if(!jp2->color.jp2_cdef)
1327         {
1328                 opj_free(cdef_info);
1329                 return OPJ_FALSE;
1330         }
1331         jp2->color.jp2_cdef->info = cdef_info;
1332         jp2->color.jp2_cdef->n = (OPJ_UINT16) l_value;
1333
1334         for(i = 0; i < jp2->color.jp2_cdef->n; ++i) {
1335                 opj_read_bytes(p_cdef_header_data, &l_value, 2);                        /* Cn^i */
1336                 p_cdef_header_data +=2;
1337                 cdef_info[i].cn = (OPJ_UINT16) l_value;
1338
1339                 opj_read_bytes(p_cdef_header_data, &l_value, 2);                        /* Typ^i */
1340                 p_cdef_header_data +=2;
1341                 cdef_info[i].typ = (OPJ_UINT16) l_value;
1342
1343                 opj_read_bytes(p_cdef_header_data, &l_value, 2);                        /* Asoc^i */
1344                 p_cdef_header_data +=2;
1345                 cdef_info[i].asoc = (OPJ_UINT16) l_value;
1346    }
1347
1348         return OPJ_TRUE;
1349 }
1350
1351 static OPJ_BOOL opj_jp2_read_colr( opj_jp2_t *jp2,
1352                             OPJ_BYTE * p_colr_header_data,
1353                             OPJ_UINT32 p_colr_header_size,
1354                             opj_event_mgr_t * p_manager
1355                             )
1356 {
1357         OPJ_UINT32 l_value;
1358
1359         /* preconditions */
1360         assert(jp2 != 00);
1361         assert(p_colr_header_data != 00);
1362         assert(p_manager != 00);
1363
1364         if (p_colr_header_size < 3) {
1365                 opj_event_msg(p_manager, EVT_ERROR, "Bad COLR header box (bad size)\n");
1366                 return OPJ_FALSE;
1367         }
1368
1369         /* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour
1370          * Specification boxes after the first.'
1371         */
1372         if(jp2->color.jp2_has_colr) {
1373                 opj_event_msg(p_manager, EVT_INFO, "A conforming JP2 reader shall ignore all Colour Specification boxes after the first, so we ignore this one.\n");
1374                 p_colr_header_data += p_colr_header_size;
1375                 return OPJ_TRUE;
1376         }
1377
1378         opj_read_bytes(p_colr_header_data,&jp2->meth ,1);                       /* METH */
1379         ++p_colr_header_data;
1380
1381         opj_read_bytes(p_colr_header_data,&jp2->precedence ,1);         /* PRECEDENCE */
1382         ++p_colr_header_data;
1383
1384         opj_read_bytes(p_colr_header_data,&jp2->approx ,1);                     /* APPROX */
1385         ++p_colr_header_data;
1386
1387         if (jp2->meth == 1) {
1388                 if (p_colr_header_size < 7) {
1389                         opj_event_msg(p_manager, EVT_ERROR, "Bad COLR header box (bad size: %d)\n", p_colr_header_size);
1390                         return OPJ_FALSE;
1391                 }
1392                 if ((p_colr_header_size > 7) && (jp2->enumcs != 14)) { /* handled below for CIELab) */
1393                         /* testcase Altona_Technical_v20_x4.pdf */
1394                         opj_event_msg(p_manager, EVT_WARNING, "Bad COLR header box (bad size: %d)\n", p_colr_header_size);
1395                 }
1396
1397                 opj_read_bytes(p_colr_header_data,&jp2->enumcs ,4);                     /* EnumCS */
1398
1399                 p_colr_header_data += 4;
1400
1401                 if(jp2->enumcs == 14)/* CIELab */
1402                 {
1403                         OPJ_UINT32 *cielab;
1404                         OPJ_UINT32 rl, ol, ra, oa, rb, ob, il;
1405
1406                         cielab = (OPJ_UINT32*)opj_malloc(9 * sizeof(OPJ_UINT32));
1407                         cielab[0] = 14; /* enumcs */
1408                         
1409                         /* default values */
1410                         rl = ra = rb = ol = oa = ob = 0;
1411                         il = 0x00443530; /* D50 */
1412                         cielab[1] = 0x44454600;/* DEF */
1413
1414                         if(p_colr_header_size == 35)
1415                         {
1416                                 opj_read_bytes(p_colr_header_data, &rl, 4);
1417                                 p_colr_header_data += 4;
1418                                 opj_read_bytes(p_colr_header_data, &ol, 4);
1419                                 p_colr_header_data += 4;
1420                                 opj_read_bytes(p_colr_header_data, &ra, 4);
1421                                 p_colr_header_data += 4;
1422                                 opj_read_bytes(p_colr_header_data, &oa, 4);
1423                                 p_colr_header_data += 4;
1424                                 opj_read_bytes(p_colr_header_data, &rb, 4);
1425                                 p_colr_header_data += 4;
1426                                 opj_read_bytes(p_colr_header_data, &ob, 4);
1427                                 p_colr_header_data += 4;
1428                                 opj_read_bytes(p_colr_header_data, &il, 4);
1429                                 p_colr_header_data += 4;
1430                                 
1431                                 cielab[1] = 0;
1432                         }
1433                         else if(p_colr_header_size != 7)
1434                         {
1435                                 opj_event_msg(p_manager, EVT_WARNING, "Bad COLR header box (CIELab, bad size: %d)\n", p_colr_header_size);
1436                         }
1437                         cielab[2] = rl; cielab[4] = ra; cielab[6] = rb;
1438                         cielab[3] = ol; cielab[5] = oa; cielab[7] = ob;
1439                         cielab[8] = il;
1440
1441                         jp2->color.icc_profile_buf = (OPJ_BYTE*)cielab;
1442                         jp2->color.icc_profile_len = 0;
1443                 }
1444                 jp2->color.jp2_has_colr = 1;
1445         }
1446         else if (jp2->meth == 2) {
1447                 /* ICC profile */
1448                 OPJ_INT32 it_icc_value = 0;
1449                 OPJ_INT32 icc_len = (OPJ_INT32)p_colr_header_size - 3;
1450
1451                 jp2->color.icc_profile_len = (OPJ_UINT32)icc_len;
1452                 jp2->color.icc_profile_buf = (OPJ_BYTE*) opj_calloc(1,(size_t)icc_len);
1453                 if (!jp2->color.icc_profile_buf)
1454                 {
1455                         jp2->color.icc_profile_len = 0;
1456                         return OPJ_FALSE;
1457                 }
1458
1459                 for (it_icc_value = 0; it_icc_value < icc_len; ++it_icc_value)
1460                 {
1461                         opj_read_bytes(p_colr_header_data,&l_value,1);          /* icc values */
1462                         ++p_colr_header_data;
1463                         jp2->color.icc_profile_buf[it_icc_value] = (OPJ_BYTE) l_value;
1464                 }
1465             
1466                 jp2->color.jp2_has_colr = 1;
1467         }
1468         else if (jp2->meth > 2)
1469         {
1470                 /*      ISO/IEC 15444-1:2004 (E), Table I.9 Legal METH values:
1471                 conforming JP2 reader shall ignore the entire Colour Specification box.*/
1472                 opj_event_msg(p_manager, EVT_INFO, "COLR BOX meth value is not a regular value (%d), "
1473                         "so we will ignore the entire Colour Specification box. \n", jp2->meth);
1474         }
1475         return OPJ_TRUE;
1476 }
1477
1478 OPJ_BOOL opj_jp2_decode(opj_jp2_t *jp2,
1479                         opj_stream_private_t *p_stream,
1480                         opj_image_t* p_image,
1481                         opj_event_mgr_t * p_manager)
1482 {
1483         if (!p_image)
1484                 return OPJ_FALSE;
1485
1486         /* J2K decoding */
1487         if( ! opj_j2k_decode(jp2->j2k, p_stream, p_image, p_manager) ) {
1488                 opj_event_msg(p_manager, EVT_ERROR, "Failed to decode the codestream in the JP2 file\n");
1489                 return OPJ_FALSE;
1490         }
1491
1492         if (!jp2->ignore_pclr_cmap_cdef){
1493                 if (!opj_jp2_check_color(p_image, &(jp2->color), p_manager)) {
1494                         return OPJ_FALSE;
1495                 }
1496
1497                 /* Set Image Color Space */
1498                 if (jp2->enumcs == 16)
1499                         p_image->color_space = OPJ_CLRSPC_SRGB;
1500                 else if (jp2->enumcs == 17)
1501                         p_image->color_space = OPJ_CLRSPC_GRAY;
1502                 else if (jp2->enumcs == 18)
1503                         p_image->color_space = OPJ_CLRSPC_SYCC;
1504                 else if (jp2->enumcs == 24)
1505                         p_image->color_space = OPJ_CLRSPC_EYCC;
1506                 else if (jp2->enumcs == 12)
1507                         p_image->color_space = OPJ_CLRSPC_CMYK;
1508                 else
1509                         p_image->color_space = OPJ_CLRSPC_UNKNOWN;
1510
1511                 if(jp2->color.jp2_pclr) {
1512                         /* Part 1, I.5.3.4: Either both or none : */
1513                         if( !jp2->color.jp2_pclr->cmap)
1514                                 opj_jp2_free_pclr(&(jp2->color));
1515                         else
1516                                 opj_jp2_apply_pclr(p_image, &(jp2->color));
1517                 }
1518
1519                 /* Apply the color space if needed */
1520                 if(jp2->color.jp2_cdef) {
1521                         opj_jp2_apply_cdef(p_image, &(jp2->color), p_manager);
1522                 }
1523
1524                 if(jp2->color.icc_profile_buf) {
1525                         p_image->icc_profile_buf = jp2->color.icc_profile_buf;
1526                         p_image->icc_profile_len = jp2->color.icc_profile_len;
1527                         jp2->color.icc_profile_buf = NULL;
1528                 }
1529         }
1530
1531         return OPJ_TRUE;
1532 }
1533
1534 static OPJ_BOOL opj_jp2_write_jp2h(opj_jp2_t *jp2,
1535                             opj_stream_private_t *stream,
1536                             opj_event_mgr_t * p_manager
1537                             )
1538 {
1539         opj_jp2_img_header_writer_handler_t l_writers [4];
1540         opj_jp2_img_header_writer_handler_t * l_current_writer;
1541
1542         OPJ_INT32 i, l_nb_pass;
1543         /* size of data for super box*/
1544         OPJ_UINT32 l_jp2h_size = 8;
1545         OPJ_BOOL l_result = OPJ_TRUE;
1546
1547         /* to store the data of the super box */
1548         OPJ_BYTE l_jp2h_data [8];
1549         
1550         /* preconditions */
1551         assert(stream != 00);
1552         assert(jp2 != 00);
1553         assert(p_manager != 00);
1554
1555         memset(l_writers,0,sizeof(l_writers));
1556
1557         if (jp2->bpc == 255) {
1558                 l_nb_pass = 3;
1559                 l_writers[0].handler = opj_jp2_write_ihdr;
1560                 l_writers[1].handler = opj_jp2_write_bpcc;
1561                 l_writers[2].handler = opj_jp2_write_colr;
1562         }
1563         else {
1564                 l_nb_pass = 2;
1565                 l_writers[0].handler = opj_jp2_write_ihdr;
1566                 l_writers[1].handler = opj_jp2_write_colr;
1567         }
1568         
1569         if (jp2->color.jp2_cdef != NULL) {
1570                 l_writers[l_nb_pass].handler = opj_jp2_write_cdef;
1571                 l_nb_pass++;
1572         }
1573         
1574         /* write box header */
1575         /* write JP2H type */
1576         opj_write_bytes(l_jp2h_data+4,JP2_JP2H,4);
1577
1578         l_current_writer = l_writers;
1579         for (i=0;i<l_nb_pass;++i) {
1580                 l_current_writer->m_data = l_current_writer->handler(jp2,&(l_current_writer->m_size));
1581                 if (l_current_writer->m_data == 00) {
1582                         opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to hold JP2 Header data\n");
1583                         l_result = OPJ_FALSE;
1584                         break;
1585                 }
1586
1587                 l_jp2h_size += l_current_writer->m_size;
1588                 ++l_current_writer;
1589         }
1590
1591         if (! l_result) {
1592                 l_current_writer = l_writers;
1593                 for (i=0;i<l_nb_pass;++i) {
1594                         if (l_current_writer->m_data != 00) {
1595                                 opj_free(l_current_writer->m_data );
1596                         }
1597                         ++l_current_writer;
1598                 }
1599
1600                 return OPJ_FALSE;
1601         }
1602
1603         /* write super box size */
1604         opj_write_bytes(l_jp2h_data,l_jp2h_size,4);
1605         
1606         /* write super box data on stream */
1607         if (opj_stream_write_data(stream,l_jp2h_data,8,p_manager) != 8) {
1608                 opj_event_msg(p_manager, EVT_ERROR, "Stream error while writing JP2 Header box\n");
1609                 l_result = OPJ_FALSE;
1610         }
1611         
1612         if (l_result) {
1613                 l_current_writer = l_writers;
1614                 for (i=0;i<l_nb_pass;++i) {
1615                         if (opj_stream_write_data(stream,l_current_writer->m_data,l_current_writer->m_size,p_manager) != l_current_writer->m_size) {
1616                                 opj_event_msg(p_manager, EVT_ERROR, "Stream error while writing JP2 Header box\n");
1617                                 l_result = OPJ_FALSE;
1618                                 break;
1619                         }
1620                         ++l_current_writer;
1621                 }
1622         }
1623
1624         l_current_writer = l_writers;
1625         
1626         /* cleanup */
1627         for (i=0;i<l_nb_pass;++i) {
1628                 if (l_current_writer->m_data != 00) {
1629                         opj_free(l_current_writer->m_data );
1630                 }
1631                 ++l_current_writer;
1632         }
1633
1634         return l_result;
1635 }
1636
1637 static OPJ_BOOL opj_jp2_write_ftyp(opj_jp2_t *jp2,
1638                                                         opj_stream_private_t *cio,
1639                                                         opj_event_mgr_t * p_manager )
1640 {
1641         OPJ_UINT32 i;
1642         OPJ_UINT32 l_ftyp_size = 16 + 4 * jp2->numcl;
1643         OPJ_BYTE * l_ftyp_data, * l_current_data_ptr;
1644         OPJ_BOOL l_result;
1645
1646         /* preconditions */
1647         assert(cio != 00);
1648         assert(jp2 != 00);
1649         assert(p_manager != 00);
1650
1651         l_ftyp_data = (OPJ_BYTE *) opj_calloc(1,l_ftyp_size);
1652         
1653         if (l_ftyp_data == 00) {
1654                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle ftyp data\n");
1655                 return OPJ_FALSE;
1656         }
1657
1658         l_current_data_ptr = l_ftyp_data;
1659
1660         opj_write_bytes(l_current_data_ptr, l_ftyp_size,4); /* box size */
1661         l_current_data_ptr += 4;
1662
1663         opj_write_bytes(l_current_data_ptr, JP2_FTYP,4); /* FTYP */
1664         l_current_data_ptr += 4;
1665
1666         opj_write_bytes(l_current_data_ptr, jp2->brand,4); /* BR */
1667         l_current_data_ptr += 4;
1668
1669         opj_write_bytes(l_current_data_ptr, jp2->minversion,4); /* MinV */
1670         l_current_data_ptr += 4;
1671
1672         for (i = 0; i < jp2->numcl; i++)  {
1673                 opj_write_bytes(l_current_data_ptr, jp2->cl[i],4);      /* CL */
1674         }
1675         
1676         l_result = (opj_stream_write_data(cio,l_ftyp_data,l_ftyp_size,p_manager) == l_ftyp_size);
1677         if (! l_result)
1678         {
1679                 opj_event_msg(p_manager, EVT_ERROR, "Error while writing ftyp data to stream\n");
1680         }
1681
1682         opj_free(l_ftyp_data);
1683         
1684         return l_result;
1685 }
1686
1687 static OPJ_BOOL opj_jp2_write_jp2c(opj_jp2_t *jp2,
1688                                                         opj_stream_private_t *cio,
1689                                                         opj_event_mgr_t * p_manager )
1690 {
1691         OPJ_OFF_T j2k_codestream_exit;
1692         OPJ_BYTE l_data_header [8];
1693         
1694         /* preconditions */
1695         assert(jp2 != 00);
1696         assert(cio != 00);
1697         assert(p_manager != 00);
1698         assert(opj_stream_has_seek(cio));
1699         
1700         j2k_codestream_exit = opj_stream_tell(cio);
1701         opj_write_bytes(l_data_header,
1702                     (OPJ_UINT32) (j2k_codestream_exit - jp2->j2k_codestream_offset),
1703                     4); /* size of codestream */
1704         opj_write_bytes(l_data_header + 4,JP2_JP2C,4);                                                                     /* JP2C */
1705
1706         if (! opj_stream_seek(cio,jp2->j2k_codestream_offset,p_manager)) {
1707                 opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
1708                 return OPJ_FALSE;
1709         }
1710         
1711         if (opj_stream_write_data(cio,l_data_header,8,p_manager) != 8) {
1712                 opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
1713                 return OPJ_FALSE;
1714         }
1715
1716         if (! opj_stream_seek(cio,j2k_codestream_exit,p_manager)) {
1717                 opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
1718                 return OPJ_FALSE;
1719         }
1720
1721         return OPJ_TRUE;
1722 }
1723
1724 static OPJ_BOOL opj_jp2_write_jp(       opj_jp2_t *jp2,
1725                                             opj_stream_private_t *cio,
1726                                                 opj_event_mgr_t * p_manager )
1727 {
1728         /* 12 bytes will be read */
1729         OPJ_BYTE l_signature_data [12];
1730
1731         /* preconditions */
1732         assert(cio != 00);
1733         assert(jp2 != 00);
1734         assert(p_manager != 00);
1735
1736         /* write box length */
1737         opj_write_bytes(l_signature_data,12,4);
1738         /* writes box type */
1739         opj_write_bytes(l_signature_data+4,JP2_JP,4);
1740         /* writes magic number*/
1741         opj_write_bytes(l_signature_data+8,0x0d0a870a,4);
1742         
1743         if (opj_stream_write_data(cio,l_signature_data,12,p_manager) != 12) {
1744                 return OPJ_FALSE;
1745         }
1746
1747         return OPJ_TRUE;
1748 }
1749
1750 /* ----------------------------------------------------------------------- */
1751 /* JP2 decoder interface                                             */
1752 /* ----------------------------------------------------------------------- */
1753
1754 void opj_jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters)
1755 {
1756         /* setup the J2K codec */
1757         opj_j2k_setup_decoder(jp2->j2k, parameters);
1758
1759         /* further JP2 initializations go here */
1760         jp2->color.jp2_has_colr = 0;
1761     jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
1762 }
1763
1764 /* ----------------------------------------------------------------------- */
1765 /* JP2 encoder interface                                             */
1766 /* ----------------------------------------------------------------------- */
1767
1768 OPJ_BOOL opj_jp2_setup_encoder( opj_jp2_t *jp2,
1769                             opj_cparameters_t *parameters,
1770                             opj_image_t *image,
1771                             opj_event_mgr_t * p_manager)
1772 {
1773         OPJ_UINT32 i;
1774         OPJ_UINT32 depth_0;
1775   OPJ_UINT32 sign;
1776         OPJ_UINT32 alpha_count;
1777         OPJ_UINT32 color_channels = 0U;
1778         OPJ_UINT32 alpha_channel = 0U;
1779         
1780
1781         if(!jp2 || !parameters || !image)
1782                 return OPJ_FALSE;
1783
1784         /* setup the J2K codec */
1785         /* ------------------- */
1786
1787         /* Check if number of components respects standard */
1788         if (image->numcomps < 1 || image->numcomps > 16384) {
1789                 opj_event_msg(p_manager, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
1790                 return OPJ_FALSE;
1791         }
1792
1793         if (opj_j2k_setup_encoder(jp2->j2k, parameters, image, p_manager ) == OPJ_FALSE) {
1794                 return OPJ_FALSE;
1795         }
1796
1797         /* setup the JP2 codec */
1798         /* ------------------- */
1799         
1800         /* Profile box */
1801
1802         jp2->brand = JP2_JP2;   /* BR */
1803         jp2->minversion = 0;    /* MinV */
1804         jp2->numcl = 1;
1805         jp2->cl = (OPJ_UINT32*) opj_malloc(jp2->numcl * sizeof(OPJ_UINT32));
1806         if (!jp2->cl){
1807                 jp2->cl = NULL;
1808                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n");
1809                 return OPJ_FALSE;
1810         }
1811         jp2->cl[0] = JP2_JP2;   /* CL0 : JP2 */
1812
1813         /* Image Header box */
1814
1815         jp2->numcomps = image->numcomps;        /* NC */
1816         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
1817         if (!jp2->comps) {
1818                 jp2->comps = NULL;
1819                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory when setup the JP2 encoder\n");
1820                 /* Memory of jp2->cl will be freed by opj_jp2_destroy */
1821                 return OPJ_FALSE;
1822         }
1823
1824         jp2->h = image->y1 - image->y0;         /* HEIGHT */
1825         jp2->w = image->x1 - image->x0;         /* WIDTH */
1826         /* BPC */
1827         depth_0 = image->comps[0].prec - 1;
1828         sign = image->comps[0].sgnd;
1829         jp2->bpc = depth_0 + (sign << 7);
1830         for (i = 1; i < image->numcomps; i++) {
1831                 OPJ_UINT32 depth = image->comps[i].prec - 1;
1832                 sign = image->comps[i].sgnd;
1833                 if (depth_0 != depth)
1834                         jp2->bpc = 255;
1835         }
1836         jp2->C = 7;                     /* C : Always 7 */
1837         jp2->UnkC = 0;          /* UnkC, colorspace specified in colr box */
1838         jp2->IPR = 0;           /* IPR, no intellectual property */
1839         
1840         /* BitsPerComponent box */
1841         for (i = 0; i < image->numcomps; i++) {
1842                 jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
1843         }
1844
1845         /* Colour Specification box */
1846     if(image->icc_profile_len) {
1847         jp2->meth = 2;
1848         jp2->enumcs = 0;
1849     } 
1850     else {
1851         jp2->meth = 1;
1852         if (image->color_space == 1)
1853             jp2->enumcs = 16;   /* sRGB as defined by IEC 61966-2-1 */
1854         else if (image->color_space == 2)
1855             jp2->enumcs = 17;   /* greyscale */
1856         else if (image->color_space == 3)
1857             jp2->enumcs = 18;   /* YUV */
1858     }
1859
1860         /* Channel Definition box */
1861         /* FIXME not provided by parameters */
1862         /* We try to do what we can... */
1863         alpha_count = 0U;
1864         for (i = 0; i < image->numcomps; i++) {
1865                 if (image->comps[i].alpha != 0) {
1866                         alpha_count++;
1867                         alpha_channel = i;
1868                 }
1869         }
1870         if (alpha_count == 1U) { /* no way to deal with more than 1 alpha channel */
1871                 switch (jp2->enumcs) {
1872                         case 16:
1873                         case 18:
1874                                 color_channels = 3;
1875                                 break;
1876                         case 17:
1877                                 color_channels = 1;
1878                                 break;
1879                         default:
1880                                 alpha_count = 0U;
1881                                 break;
1882                 }
1883                 if (alpha_count == 0U) {
1884                         opj_event_msg(p_manager, EVT_WARNING, "Alpha channel specified but unknown enumcs. No cdef box will be created.\n");
1885                 } else if (image->numcomps < (color_channels+1)) {
1886                         opj_event_msg(p_manager, EVT_WARNING, "Alpha channel specified but not enough image components for an automatic cdef box creation.\n");
1887                         alpha_count = 0U;
1888                 } else if ((OPJ_UINT32)alpha_channel < color_channels) {
1889                         opj_event_msg(p_manager, EVT_WARNING, "Alpha channel position conflicts with color channel. No cdef box will be created.\n");
1890                         alpha_count = 0U;
1891                 }
1892         } else if (alpha_count > 1) {
1893                 opj_event_msg(p_manager, EVT_WARNING, "Multiple alpha channels specified. No cdef box will be created.\n");
1894         }
1895         if (alpha_count == 1U) { /* if here, we know what we can do */
1896                 jp2->color.jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
1897                 if(!jp2->color.jp2_cdef) {
1898                         opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup the JP2 encoder\n");
1899                         return OPJ_FALSE;
1900                 }
1901                 /* no memset needed, all values will be overwritten except if jp2->color.jp2_cdef->info allocation fails, */
1902                 /* in which case jp2->color.jp2_cdef->info will be NULL => valid for destruction */
1903                 jp2->color.jp2_cdef->info = (opj_jp2_cdef_info_t*) opj_malloc(image->numcomps * sizeof(opj_jp2_cdef_info_t));
1904                 if (!jp2->color.jp2_cdef->info) {
1905                         /* memory will be freed by opj_jp2_destroy */
1906                         opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to setup the JP2 encoder\n");
1907                         return OPJ_FALSE;
1908                 }
1909                 jp2->color.jp2_cdef->n = (OPJ_UINT16) image->numcomps; /* cast is valid : image->numcomps [1,16384] */
1910                 for (i = 0U; i < color_channels; i++) {
1911                         jp2->color.jp2_cdef->info[i].cn = (OPJ_UINT16)i; /* cast is valid : image->numcomps [1,16384] */
1912                         jp2->color.jp2_cdef->info[i].typ = 0U;
1913                         jp2->color.jp2_cdef->info[i].asoc = (OPJ_UINT16)(i+1U); /* No overflow + cast is valid : image->numcomps [1,16384] */
1914                 }
1915                 for (; i < image->numcomps; i++) {
1916                         if (image->comps[i].alpha != 0) { /* we'll be here exactly once */
1917                                 jp2->color.jp2_cdef->info[i].cn = (OPJ_UINT16)i; /* cast is valid : image->numcomps [1,16384] */
1918                                 jp2->color.jp2_cdef->info[i].typ = 1U; /* Opacity channel */
1919                                 jp2->color.jp2_cdef->info[i].asoc = 0U; /* Apply alpha channel to the whole image */
1920                         } else {
1921                                 /* Unknown channel */
1922                                 jp2->color.jp2_cdef->info[i].cn = (OPJ_UINT16)i; /* cast is valid : image->numcomps [1,16384] */
1923                                 jp2->color.jp2_cdef->info[i].typ = 65535U;
1924                                 jp2->color.jp2_cdef->info[i].asoc = 65535U;
1925                         }
1926                 }
1927         }
1928
1929         jp2->precedence = 0;    /* PRECEDENCE */
1930         jp2->approx = 0;                /* APPROX */
1931
1932         jp2->jpip_on = parameters->jpip_on;
1933
1934         return OPJ_TRUE;
1935 }
1936
1937 OPJ_BOOL opj_jp2_encode(opj_jp2_t *jp2,
1938                                                 opj_stream_private_t *stream,
1939                                                 opj_event_mgr_t * p_manager)
1940 {
1941         return opj_j2k_encode(jp2->j2k, stream, p_manager);
1942 }
1943
1944 OPJ_BOOL opj_jp2_end_decompress(opj_jp2_t *jp2,
1945                                 opj_stream_private_t *cio,
1946                                 opj_event_mgr_t * p_manager
1947                                 )
1948 {
1949         /* preconditions */
1950         assert(jp2 != 00);
1951         assert(cio != 00);
1952         assert(p_manager != 00);
1953
1954         /* customization of the end encoding */
1955         if (! opj_jp2_setup_end_header_reading(jp2, p_manager)) {
1956                 return OPJ_FALSE;
1957         }
1958
1959         /* write header */
1960         if (! opj_jp2_exec (jp2,jp2->m_procedure_list,cio,p_manager)) {
1961                 return OPJ_FALSE;
1962         }
1963
1964         return opj_j2k_end_decompress(jp2->j2k, cio, p_manager);
1965 }
1966
1967 OPJ_BOOL opj_jp2_end_compress(  opj_jp2_t *jp2,
1968                                                             opj_stream_private_t *cio,
1969                                                             opj_event_mgr_t * p_manager
1970                                 )
1971 {
1972         /* preconditions */
1973         assert(jp2 != 00);
1974         assert(cio != 00);
1975         assert(p_manager != 00);
1976
1977         /* customization of the end encoding */
1978         if (! opj_jp2_setup_end_header_writing(jp2, p_manager)) {
1979                 return OPJ_FALSE;
1980         }
1981
1982         if (! opj_j2k_end_compress(jp2->j2k,cio,p_manager)) {
1983                 return OPJ_FALSE;
1984         }
1985
1986         /* write header */
1987         return opj_jp2_exec(jp2,jp2->m_procedure_list,cio,p_manager);
1988 }
1989
1990 static OPJ_BOOL opj_jp2_setup_end_header_writing (opj_jp2_t *jp2, opj_event_mgr_t * p_manager)
1991 {
1992         /* preconditions */
1993         assert(jp2 != 00);
1994         assert(p_manager != 00);
1995
1996 #ifdef USE_JPIP
1997         if( jp2->jpip_on ) {
1998                 if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jpip_write_iptr, p_manager)) {
1999                         return OPJ_FALSE;
2000                 }
2001         }
2002 #endif
2003         if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_write_jp2c, p_manager)) {
2004                 return OPJ_FALSE;
2005         }
2006         /* DEVELOPER CORNER, add your custom procedures */
2007 #ifdef USE_JPIP
2008   if( jp2->jpip_on )
2009         {
2010                 if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jpip_write_cidx, p_manager)) {
2011                         return OPJ_FALSE;
2012                 }
2013                 if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jpip_write_fidx, p_manager)) {
2014                         return OPJ_FALSE;
2015                 }
2016         }
2017 #endif
2018         return OPJ_TRUE;
2019 }
2020
2021 static OPJ_BOOL opj_jp2_setup_end_header_reading (opj_jp2_t *jp2, opj_event_mgr_t * p_manager)
2022 {
2023         /* preconditions */
2024         assert(jp2 != 00);
2025         assert(p_manager != 00);
2026         
2027         if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_read_header_procedure, p_manager)) {
2028                 return OPJ_FALSE;
2029         }
2030         /* DEVELOPER CORNER, add your custom procedures */
2031         
2032         return OPJ_TRUE;
2033 }
2034
2035 static OPJ_BOOL opj_jp2_default_validation (    opj_jp2_t * jp2,
2036                                         opj_stream_private_t *cio,
2037                                         opj_event_mgr_t * p_manager
2038                                         )
2039 {
2040         OPJ_BOOL l_is_valid = OPJ_TRUE;
2041         OPJ_UINT32 i;
2042
2043         /* preconditions */
2044         assert(jp2 != 00);
2045         assert(cio != 00);
2046         assert(p_manager != 00);
2047
2048         /* JPEG2000 codec validation */
2049
2050         /* STATE checking */
2051         /* make sure the state is at 0 */
2052         l_is_valid &= (jp2->jp2_state == JP2_STATE_NONE);
2053
2054         /* make sure not reading a jp2h ???? WEIRD */
2055         l_is_valid &= (jp2->jp2_img_state == JP2_IMG_STATE_NONE);
2056
2057         /* POINTER validation */
2058         /* make sure a j2k codec is present */
2059         l_is_valid &= (jp2->j2k != 00);
2060
2061         /* make sure a procedure list is present */
2062         l_is_valid &= (jp2->m_procedure_list != 00);
2063
2064         /* make sure a validation list is present */
2065         l_is_valid &= (jp2->m_validation_list != 00);
2066
2067         /* PARAMETER VALIDATION */
2068         /* number of components */
2069         l_is_valid &= (jp2->numcl > 0);
2070         /* width */
2071         l_is_valid &= (jp2->h > 0);
2072         /* height */
2073         l_is_valid &= (jp2->w > 0);
2074         /* precision */
2075         for (i = 0; i < jp2->numcomps; ++i)     {
2076                 l_is_valid &= ((jp2->comps[i].bpcc & 0x7FU) < 38U); /* 0 is valid, ignore sign for check */
2077         }
2078
2079         /* METH */
2080         l_is_valid &= ((jp2->meth > 0) && (jp2->meth < 3));
2081
2082         /* stream validation */
2083         /* back and forth is needed */
2084         l_is_valid &= opj_stream_has_seek(cio);
2085
2086         return l_is_valid;
2087 }
2088
2089 static OPJ_BOOL opj_jp2_read_header_procedure(  opj_jp2_t *jp2,
2090                                                 opj_stream_private_t *stream,
2091                                                 opj_event_mgr_t * p_manager
2092                                                 )
2093 {
2094         opj_jp2_box_t box;
2095         OPJ_UINT32 l_nb_bytes_read;
2096         const opj_jp2_header_handler_t * l_current_handler;
2097         const opj_jp2_header_handler_t * l_current_handler_misplaced;
2098         OPJ_UINT32 l_last_data_size = OPJ_BOX_SIZE;
2099         OPJ_UINT32 l_current_data_size;
2100         OPJ_BYTE * l_current_data = 00;
2101
2102         /* preconditions */
2103         assert(stream != 00);
2104         assert(jp2 != 00);
2105         assert(p_manager != 00);
2106
2107         l_current_data = (OPJ_BYTE*)opj_calloc(1,l_last_data_size);
2108
2109         if (l_current_data == 00) {
2110                 opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle jpeg2000 file header\n");
2111                 return OPJ_FALSE;
2112         }
2113
2114         while (opj_jp2_read_boxhdr(&box,&l_nb_bytes_read,stream,p_manager)) {
2115                 /* is it the codestream box ? */
2116                 if (box.type == JP2_JP2C) {
2117                         if (jp2->jp2_state & JP2_STATE_HEADER) {
2118                                 jp2->jp2_state |= JP2_STATE_CODESTREAM;
2119                                 opj_free(l_current_data);
2120                                 return OPJ_TRUE;
2121                         }
2122                         else {
2123                                 opj_event_msg(p_manager, EVT_ERROR, "bad placed jpeg codestream\n");
2124                                 opj_free(l_current_data);
2125                                 return OPJ_FALSE;
2126                         }
2127                 }
2128                 else if (box.length == 0) {
2129                         opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
2130                         opj_free(l_current_data);
2131                         return OPJ_FALSE;
2132                 }
2133                 /* testcase 1851.pdf.SIGSEGV.ce9.948 */
2134                 else if (box.length < l_nb_bytes_read) {
2135                         opj_event_msg(p_manager, EVT_ERROR, "invalid box size %d (%x)\n", box.length, box.type);
2136                         opj_free(l_current_data);
2137                         return OPJ_FALSE;
2138                 }
2139
2140                 l_current_handler = opj_jp2_find_handler(box.type);
2141                 l_current_handler_misplaced = opj_jp2_img_find_handler(box.type);
2142                 l_current_data_size = box.length - l_nb_bytes_read;
2143
2144                 if ((l_current_handler != 00) || (l_current_handler_misplaced != 00)) {
2145                         if (l_current_handler == 00) {
2146                                 opj_event_msg(p_manager, EVT_WARNING, "Found a misplaced '%c%c%c%c' box outside jp2h box\n", (OPJ_BYTE)(box.type>>24), (OPJ_BYTE)(box.type>>16), (OPJ_BYTE)(box.type>>8), (OPJ_BYTE)(box.type>>0));
2147                                 if (jp2->jp2_state & JP2_STATE_HEADER) {
2148                                         /* read anyway, we already have jp2h */
2149                                         l_current_handler = l_current_handler_misplaced;
2150                                 } else {
2151                                         opj_event_msg(p_manager, EVT_WARNING, "JPEG2000 Header box not read yet, '%c%c%c%c' box will be ignored\n", (OPJ_BYTE)(box.type>>24), (OPJ_BYTE)(box.type>>16), (OPJ_BYTE)(box.type>>8), (OPJ_BYTE)(box.type>>0));
2152                                         jp2->jp2_state |= JP2_STATE_UNKNOWN;
2153                                         if (opj_stream_skip(stream,l_current_data_size,p_manager) != l_current_data_size) {
2154                                                         opj_event_msg(p_manager, EVT_ERROR, "Problem with skipping JPEG2000 box, stream error\n");
2155                                                         opj_free(l_current_data);
2156                                                         return OPJ_FALSE;
2157                                         }
2158                                         continue;
2159                                 }
2160                         }
2161                         if ((OPJ_OFF_T)l_current_data_size > opj_stream_get_number_byte_left(stream)) {
2162                                 /* do not even try to malloc if we can't read */
2163                                 opj_event_msg(p_manager, EVT_ERROR, "Invalid box size %d for box '%c%c%c%c'. Need %d bytes, %d bytes remaining \n", box.length, (OPJ_BYTE)(box.type>>24), (OPJ_BYTE)(box.type>>16), (OPJ_BYTE)(box.type>>8), (OPJ_BYTE)(box.type>>0), l_current_data_size, (OPJ_UINT32)opj_stream_get_number_byte_left(stream));
2164                                 opj_free(l_current_data);
2165                                 return OPJ_FALSE;
2166                         }
2167                         if (l_current_data_size > l_last_data_size) {
2168                                 OPJ_BYTE* new_current_data = (OPJ_BYTE*)opj_realloc(l_current_data,l_current_data_size);
2169                                 if (!new_current_data) {
2170                                         opj_free(l_current_data);
2171                     opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle jpeg2000 box\n");
2172                                         return OPJ_FALSE;
2173                                 }
2174                 l_current_data = new_current_data;
2175                                 l_last_data_size = l_current_data_size;
2176                         }
2177
2178                         l_nb_bytes_read = (OPJ_UINT32)opj_stream_read_data(stream,l_current_data,l_current_data_size,p_manager);
2179                         if (l_nb_bytes_read != l_current_data_size) {
2180                                 opj_event_msg(p_manager, EVT_ERROR, "Problem with reading JPEG2000 box, stream error\n");
2181                 opj_free(l_current_data);                
2182                                 return OPJ_FALSE;
2183                         }
2184
2185                         if (! l_current_handler->handler(jp2,l_current_data,l_current_data_size,p_manager)) {
2186                                 opj_free(l_current_data);
2187                                 return OPJ_FALSE;
2188                         }
2189                 }
2190                 else {
2191                         if (!(jp2->jp2_state & JP2_STATE_SIGNATURE)) {
2192                                 opj_event_msg(p_manager, EVT_ERROR, "Malformed JP2 file format: first box must be JPEG 2000 signature box\n");
2193                                 opj_free(l_current_data);
2194                                 return OPJ_FALSE;
2195                         }
2196                         if (!(jp2->jp2_state & JP2_STATE_FILE_TYPE)) {
2197                                 opj_event_msg(p_manager, EVT_ERROR, "Malformed JP2 file format: second box must be file type box\n");
2198                                 opj_free(l_current_data);
2199                                 return OPJ_FALSE;
2200                         }
2201                         jp2->jp2_state |= JP2_STATE_UNKNOWN;
2202                         if (opj_stream_skip(stream,l_current_data_size,p_manager) != l_current_data_size) {
2203                                 opj_event_msg(p_manager, EVT_ERROR, "Problem with skipping JPEG2000 box, stream error\n");
2204                                 opj_free(l_current_data);
2205                                 return OPJ_FALSE;
2206                         }
2207                 }
2208         }
2209
2210         opj_free(l_current_data);
2211
2212         return OPJ_TRUE;
2213 }
2214
2215 /**
2216  * Excutes the given procedures on the given codec.
2217  *
2218  * @param       p_procedure_list        the list of procedures to execute
2219  * @param       jp2                                     the jpeg2000 file codec to execute the procedures on.
2220  * @param       stream                                  the stream to execute the procedures on.
2221  * @param       p_manager                       the user manager.
2222  *
2223  * @return      true                            if all the procedures were successfully executed.
2224  */
2225 static OPJ_BOOL opj_jp2_exec (  opj_jp2_t * jp2,
2226                                 opj_procedure_list_t * p_procedure_list,
2227                                 opj_stream_private_t *stream,
2228                                 opj_event_mgr_t * p_manager
2229                                 )
2230
2231 {
2232         OPJ_BOOL (** l_procedure) (opj_jp2_t * jp2, opj_stream_private_t *, opj_event_mgr_t *) = 00;
2233         OPJ_BOOL l_result = OPJ_TRUE;
2234         OPJ_UINT32 l_nb_proc, i;
2235
2236         /* preconditions */
2237         assert(p_procedure_list != 00);
2238         assert(jp2 != 00);
2239         assert(stream != 00);
2240         assert(p_manager != 00);
2241
2242         l_nb_proc = opj_procedure_list_get_nb_procedures(p_procedure_list);
2243         l_procedure = (OPJ_BOOL (**) (opj_jp2_t * jp2, opj_stream_private_t *, opj_event_mgr_t *)) opj_procedure_list_get_first_procedure(p_procedure_list);
2244
2245         for     (i=0;i<l_nb_proc;++i) {
2246                 l_result = l_result && (*l_procedure) (jp2,stream,p_manager);
2247                 ++l_procedure;
2248         }
2249
2250         /* and clear the procedure list at the end. */
2251         opj_procedure_list_clear(p_procedure_list);
2252         return l_result;
2253 }
2254
2255 OPJ_BOOL opj_jp2_start_compress(opj_jp2_t *jp2,
2256                                 opj_stream_private_t *stream,
2257                                 opj_image_t * p_image,
2258                                 opj_event_mgr_t * p_manager
2259                                 )
2260 {
2261         /* preconditions */
2262         assert(jp2 != 00);
2263         assert(stream != 00);
2264         assert(p_manager != 00);
2265
2266         /* customization of the validation */
2267         if (! opj_jp2_setup_encoding_validation (jp2, p_manager)) {
2268                 return OPJ_FALSE;
2269         }
2270
2271         /* validation of the parameters codec */
2272         if (! opj_jp2_exec(jp2,jp2->m_validation_list,stream,p_manager)) {
2273                 return OPJ_FALSE;
2274         }
2275
2276         /* customization of the encoding */
2277         if (! opj_jp2_setup_header_writing(jp2, p_manager)) {
2278                 return OPJ_FALSE;
2279         }
2280
2281         /* write header */
2282         if (! opj_jp2_exec (jp2,jp2->m_procedure_list,stream,p_manager)) {
2283                 return OPJ_FALSE;
2284         }
2285
2286         return opj_j2k_start_compress(jp2->j2k,stream,p_image,p_manager);
2287 }
2288
2289 static const opj_jp2_header_handler_t * opj_jp2_find_handler (OPJ_UINT32 p_id)
2290 {
2291         OPJ_UINT32 i, l_handler_size = sizeof(jp2_header) / sizeof(opj_jp2_header_handler_t);
2292
2293         for (i=0;i<l_handler_size;++i) {
2294                 if (jp2_header[i].id == p_id) {
2295                         return &jp2_header[i];
2296                 }
2297         }
2298         return NULL;
2299 }
2300
2301 /**
2302  * Finds the image execution function related to the given box id.
2303  *
2304  * @param       p_id    the id of the handler to fetch.
2305  *
2306  * @return      the given handler or 00 if it could not be found.
2307  */
2308 static const opj_jp2_header_handler_t * opj_jp2_img_find_handler (OPJ_UINT32 p_id)
2309 {
2310         OPJ_UINT32 i, l_handler_size = sizeof(jp2_img_header) / sizeof(opj_jp2_header_handler_t);
2311         for (i=0;i<l_handler_size;++i)
2312         {
2313                 if (jp2_img_header[i].id == p_id) {
2314                         return &jp2_img_header[i];
2315                 }
2316         }
2317
2318         return NULL;
2319 }
2320
2321 /**
2322  * Reads a jpeg2000 file signature box.
2323  *
2324  * @param       p_header_data   the data contained in the signature box.
2325  * @param       jp2                             the jpeg2000 file codec.
2326  * @param       p_header_size   the size of the data contained in the signature box.
2327  * @param       p_manager               the user event manager.
2328  *
2329  * @return true if the file signature box is valid.
2330  */
2331 static OPJ_BOOL opj_jp2_read_jp(opj_jp2_t *jp2,
2332                                 OPJ_BYTE * p_header_data,
2333                                 OPJ_UINT32 p_header_size,
2334                                 opj_event_mgr_t * p_manager
2335                                 )
2336
2337 {
2338         OPJ_UINT32 l_magic_number;
2339
2340         /* preconditions */
2341         assert(p_header_data != 00);
2342         assert(jp2 != 00);
2343         assert(p_manager != 00);
2344
2345         if (jp2->jp2_state != JP2_STATE_NONE) {
2346                 opj_event_msg(p_manager, EVT_ERROR, "The signature box must be the first box in the file.\n");
2347                 return OPJ_FALSE;
2348         }
2349
2350         /* assure length of data is correct (4 -> magic number) */
2351         if (p_header_size != 4) {
2352                 opj_event_msg(p_manager, EVT_ERROR, "Error with JP signature Box size\n");
2353                 return OPJ_FALSE;
2354         }
2355
2356         /* rearrange data */
2357         opj_read_bytes(p_header_data,&l_magic_number,4);
2358         if (l_magic_number != 0x0d0a870a ) {
2359                 opj_event_msg(p_manager, EVT_ERROR, "Error with JP Signature : bad magic number\n");
2360                 return OPJ_FALSE;
2361         }
2362
2363         jp2->jp2_state |= JP2_STATE_SIGNATURE;
2364
2365         return OPJ_TRUE;
2366 }
2367
2368 /**
2369  * Reads a a FTYP box - File type box
2370  *
2371  * @param       p_header_data   the data contained in the FTYP box.
2372  * @param       jp2                             the jpeg2000 file codec.
2373  * @param       p_header_size   the size of the data contained in the FTYP box.
2374  * @param       p_manager               the user event manager.
2375  *
2376  * @return true if the FTYP box is valid.
2377  */
2378 static OPJ_BOOL opj_jp2_read_ftyp(      opj_jp2_t *jp2,
2379                                                                         OPJ_BYTE * p_header_data,
2380                                                                         OPJ_UINT32 p_header_size,
2381                                                                         opj_event_mgr_t * p_manager
2382                                     )
2383 {
2384         OPJ_UINT32 i, l_remaining_bytes;
2385
2386         /* preconditions */
2387         assert(p_header_data != 00);
2388         assert(jp2 != 00);
2389         assert(p_manager != 00);
2390
2391         if (jp2->jp2_state != JP2_STATE_SIGNATURE) {
2392                 opj_event_msg(p_manager, EVT_ERROR, "The ftyp box must be the second box in the file.\n");
2393                 return OPJ_FALSE;
2394         }
2395
2396         /* assure length of data is correct */
2397         if (p_header_size < 8) {
2398                 opj_event_msg(p_manager, EVT_ERROR, "Error with FTYP signature Box size\n");
2399                 return OPJ_FALSE;
2400         }
2401
2402         opj_read_bytes(p_header_data,&jp2->brand,4);            /* BR */
2403         p_header_data += 4;
2404
2405         opj_read_bytes(p_header_data,&jp2->minversion,4);               /* MinV */
2406         p_header_data += 4;
2407
2408         l_remaining_bytes = p_header_size - 8;
2409
2410         /* the number of remaining bytes should be a multiple of 4 */
2411         if ((l_remaining_bytes & 0x3) != 0) {
2412                 opj_event_msg(p_manager, EVT_ERROR, "Error with FTYP signature Box size\n");
2413                 return OPJ_FALSE;
2414         }
2415
2416         /* div by 4 */
2417         jp2->numcl = l_remaining_bytes >> 2;
2418         if (jp2->numcl) {
2419                 jp2->cl = (OPJ_UINT32 *) opj_calloc(jp2->numcl, sizeof(OPJ_UINT32));
2420                 if (jp2->cl == 00) {
2421                         opj_event_msg(p_manager, EVT_ERROR, "Not enough memory with FTYP Box\n");
2422                         return OPJ_FALSE;
2423                 }
2424         }
2425
2426         for (i = 0; i < jp2->numcl; ++i)
2427         {
2428                 opj_read_bytes(p_header_data,&jp2->cl[i],4);            /* CLi */
2429                 p_header_data += 4;
2430         }
2431
2432         jp2->jp2_state |= JP2_STATE_FILE_TYPE;
2433
2434         return OPJ_TRUE;
2435 }
2436
2437 static OPJ_BOOL opj_jp2_skip_jp2c(      opj_jp2_t *jp2,
2438                                                 opj_stream_private_t *stream,
2439                                                 opj_event_mgr_t * p_manager )
2440 {
2441         /* preconditions */
2442         assert(jp2 != 00);
2443         assert(stream != 00);
2444         assert(p_manager != 00);
2445
2446         jp2->j2k_codestream_offset = opj_stream_tell(stream);
2447
2448         if (opj_stream_skip(stream,8,p_manager) != 8) {
2449                 return OPJ_FALSE;
2450         }
2451
2452         return OPJ_TRUE;
2453 }
2454
2455 static OPJ_BOOL opj_jpip_skip_iptr(     opj_jp2_t *jp2,
2456   opj_stream_private_t *stream,
2457   opj_event_mgr_t * p_manager )
2458 {
2459   /* preconditions */
2460   assert(jp2 != 00);
2461   assert(stream != 00);
2462   assert(p_manager != 00);
2463
2464   jp2->jpip_iptr_offset = opj_stream_tell(stream);
2465
2466   if (opj_stream_skip(stream,24,p_manager) != 24) {
2467     return OPJ_FALSE;
2468   }
2469
2470   return OPJ_TRUE;
2471 }
2472
2473 /**
2474  * Reads the Jpeg2000 file Header box - JP2 Header box (warning, this is a super box).
2475  *
2476  * @param       p_header_data   the data contained in the file header box.
2477  * @param       jp2                             the jpeg2000 file codec.
2478  * @param       p_header_size   the size of the data contained in the file header box.
2479  * @param       p_manager               the user event manager.
2480  *
2481  * @return true if the JP2 Header box was successfully recognized.
2482 */
2483 static OPJ_BOOL opj_jp2_read_jp2h(  opj_jp2_t *jp2,
2484                                     OPJ_BYTE *p_header_data,
2485                                     OPJ_UINT32 p_header_size,
2486                                     opj_event_mgr_t * p_manager
2487                                     )
2488 {
2489         OPJ_UINT32 l_box_size=0, l_current_data_size = 0;
2490         opj_jp2_box_t box;
2491         const opj_jp2_header_handler_t * l_current_handler;
2492         OPJ_BOOL l_has_ihdr = 0;
2493
2494         /* preconditions */
2495         assert(p_header_data != 00);
2496         assert(jp2 != 00);
2497         assert(p_manager != 00);
2498
2499         /* make sure the box is well placed */
2500         if ((jp2->jp2_state & JP2_STATE_FILE_TYPE) != JP2_STATE_FILE_TYPE ) {
2501                 opj_event_msg(p_manager, EVT_ERROR, "The  box must be the first box in the file.\n");
2502                 return OPJ_FALSE;
2503         }
2504
2505         jp2->jp2_img_state = JP2_IMG_STATE_NONE;
2506
2507         /* iterate while remaining data */
2508         while (p_header_size > 0) {
2509
2510                 if (! opj_jp2_read_boxhdr_char(&box,p_header_data,&l_box_size,p_header_size, p_manager)) {
2511                         opj_event_msg(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box\n");
2512                         return OPJ_FALSE;
2513                 }
2514
2515                 if (box.length > p_header_size) {
2516                         opj_event_msg(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box: box length is inconsistent.\n");
2517                         return OPJ_FALSE;
2518                 }
2519
2520                 l_current_handler = opj_jp2_img_find_handler(box.type);
2521                 l_current_data_size = box.length - l_box_size;
2522                 p_header_data += l_box_size;
2523
2524                 if (l_current_handler != 00) {
2525                         if (! l_current_handler->handler(jp2,p_header_data,l_current_data_size,p_manager)) {
2526                                 return OPJ_FALSE;
2527                         }
2528                 }
2529                 else {
2530                         jp2->jp2_img_state |= JP2_IMG_STATE_UNKNOWN;
2531                 }
2532
2533                 if (box.type == JP2_IHDR) {
2534                         l_has_ihdr = 1;
2535                 }
2536
2537                 p_header_data += l_current_data_size;
2538                 p_header_size -= box.length;
2539         }
2540
2541         if (l_has_ihdr == 0) {
2542                 opj_event_msg(p_manager, EVT_ERROR, "Stream error while reading JP2 Header box: no 'ihdr' box.\n");
2543                 return OPJ_FALSE;
2544         }
2545
2546         jp2->jp2_state |= JP2_STATE_HEADER;
2547
2548         return OPJ_TRUE;
2549 }
2550
2551 static OPJ_BOOL opj_jp2_read_boxhdr_char(   opj_jp2_box_t *box,
2552                                      OPJ_BYTE * p_data,
2553                                      OPJ_UINT32 * p_number_bytes_read,
2554                                      OPJ_UINT32 p_box_max_size,
2555                                      opj_event_mgr_t * p_manager
2556                                      )
2557 {
2558         OPJ_UINT32 l_value;
2559
2560         /* preconditions */
2561         assert(p_data != 00);
2562         assert(box != 00);
2563         assert(p_number_bytes_read != 00);
2564         assert(p_manager != 00);
2565
2566         if (p_box_max_size < 8) {
2567                 opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of less than 8 bytes\n");
2568                 return OPJ_FALSE;
2569         }
2570
2571         /* process read data */
2572         opj_read_bytes(p_data, &l_value, 4);
2573         p_data += 4;
2574         box->length = (OPJ_UINT32)(l_value);
2575
2576         opj_read_bytes(p_data, &l_value, 4);
2577         p_data += 4;
2578         box->type = (OPJ_UINT32)(l_value);
2579
2580         *p_number_bytes_read = 8;
2581
2582         /* do we have a "special very large box ?" */
2583         /* read then the XLBox */
2584         if (box->length == 1) {
2585                 OPJ_UINT32 l_xl_part_size;
2586
2587                 if (p_box_max_size < 16) {
2588                         opj_event_msg(p_manager, EVT_ERROR, "Cannot handle XL box of less than 16 bytes\n");
2589                         return OPJ_FALSE;
2590                 }
2591
2592                 opj_read_bytes(p_data,&l_xl_part_size, 4);
2593                 p_data += 4;
2594                 *p_number_bytes_read += 4;
2595
2596                 if (l_xl_part_size != 0) {
2597                         opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
2598                         return OPJ_FALSE;
2599                 }
2600
2601                 opj_read_bytes(p_data, &l_value, 4);
2602                 *p_number_bytes_read += 4;
2603                 box->length = (OPJ_UINT32)(l_value);
2604
2605                 if (box->length == 0) {
2606                         opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
2607                         return OPJ_FALSE;
2608                 }
2609         }
2610         else if (box->length == 0) {
2611                 opj_event_msg(p_manager, EVT_ERROR, "Cannot handle box of undefined sizes\n");
2612                 return OPJ_FALSE;
2613         }
2614         if (box->length < *p_number_bytes_read) {
2615                 opj_event_msg(p_manager, EVT_ERROR, "Box length is inconsistent.\n");
2616                 return OPJ_FALSE;
2617         }
2618         return OPJ_TRUE;
2619 }
2620
2621 OPJ_BOOL opj_jp2_read_header(   opj_stream_private_t *p_stream,
2622                                 opj_jp2_t *jp2,
2623                                 opj_image_t ** p_image,
2624                                 opj_event_mgr_t * p_manager
2625                                 )
2626 {
2627         /* preconditions */
2628         assert(jp2 != 00);
2629         assert(p_stream != 00);
2630         assert(p_manager != 00);
2631
2632         /* customization of the validation */
2633         if (! opj_jp2_setup_decoding_validation (jp2, p_manager)) {
2634                 return OPJ_FALSE;
2635         }
2636
2637         /* customization of the encoding */
2638         if (! opj_jp2_setup_header_reading(jp2, p_manager)) {
2639                 return OPJ_FALSE;
2640         }
2641
2642         /* validation of the parameters codec */
2643         if (! opj_jp2_exec(jp2,jp2->m_validation_list,p_stream,p_manager)) {
2644                 return OPJ_FALSE;
2645         }
2646
2647         /* read header */
2648         if (! opj_jp2_exec (jp2,jp2->m_procedure_list,p_stream,p_manager)) {
2649                 return OPJ_FALSE;
2650         }
2651
2652         return opj_j2k_read_header(     p_stream,
2653                                                         jp2->j2k,
2654                                                         p_image,
2655                                                         p_manager);
2656 }
2657
2658 static OPJ_BOOL opj_jp2_setup_encoding_validation (opj_jp2_t *jp2, opj_event_mgr_t * p_manager)
2659 {
2660         /* preconditions */
2661         assert(jp2 != 00);
2662         assert(p_manager != 00);
2663
2664         if (! opj_procedure_list_add_procedure(jp2->m_validation_list, (opj_procedure)opj_jp2_default_validation, p_manager)) {
2665                 return OPJ_FALSE;
2666         }
2667         /* DEVELOPER CORNER, add your custom validation procedure */
2668         
2669         return OPJ_TRUE;
2670 }
2671
2672 static OPJ_BOOL opj_jp2_setup_decoding_validation (opj_jp2_t *jp2, opj_event_mgr_t * p_manager)
2673 {
2674         /* preconditions */
2675         assert(jp2 != 00);
2676         assert(p_manager != 00);
2677         
2678         /* DEVELOPER CORNER, add your custom validation procedure */
2679         
2680         return OPJ_TRUE;
2681 }
2682
2683 static OPJ_BOOL opj_jp2_setup_header_writing (opj_jp2_t *jp2, opj_event_mgr_t * p_manager)
2684 {
2685         /* preconditions */
2686         assert(jp2 != 00);
2687         assert(p_manager != 00);
2688
2689         if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_write_jp, p_manager)) {
2690                 return OPJ_FALSE;
2691         }
2692         if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_write_ftyp, p_manager)) {
2693                 return OPJ_FALSE;
2694         }
2695         if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_write_jp2h, p_manager)) {
2696                 return OPJ_FALSE;
2697         }
2698         if( jp2->jpip_on ) {
2699                 if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jpip_skip_iptr, p_manager)) {
2700                         return OPJ_FALSE;
2701                 }
2702         }
2703         if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_skip_jp2c,p_manager)) {
2704                 return OPJ_FALSE;
2705         }
2706
2707         /* DEVELOPER CORNER, insert your custom procedures */
2708
2709         return OPJ_TRUE;
2710 }
2711
2712 static OPJ_BOOL opj_jp2_setup_header_reading (opj_jp2_t *jp2, opj_event_mgr_t * p_manager)
2713 {
2714         /* preconditions */
2715         assert(jp2 != 00);
2716         assert(p_manager != 00);
2717
2718         if (! opj_procedure_list_add_procedure(jp2->m_procedure_list,(opj_procedure)opj_jp2_read_header_procedure, p_manager)) {
2719                 return OPJ_FALSE;
2720         }
2721         
2722         /* DEVELOPER CORNER, add your custom procedures */
2723         
2724         return OPJ_TRUE;
2725 }
2726
2727 OPJ_BOOL opj_jp2_read_tile_header ( opj_jp2_t * p_jp2,
2728                                     OPJ_UINT32 * p_tile_index,
2729                                     OPJ_UINT32 * p_data_size,
2730                                     OPJ_INT32 * p_tile_x0,
2731                                     OPJ_INT32 * p_tile_y0,
2732                                     OPJ_INT32 * p_tile_x1,
2733                                     OPJ_INT32 * p_tile_y1,
2734                                     OPJ_UINT32 * p_nb_comps,
2735                                     OPJ_BOOL * p_go_on,
2736                                     opj_stream_private_t *p_stream,
2737                                     opj_event_mgr_t * p_manager
2738                                     )
2739 {
2740         return opj_j2k_read_tile_header(p_jp2->j2k,
2741                                                                 p_tile_index,
2742                                                                 p_data_size,
2743                                                                 p_tile_x0, p_tile_y0,
2744                                                                 p_tile_x1, p_tile_y1,
2745                                                                 p_nb_comps,
2746                                                                 p_go_on,
2747                                                                 p_stream,
2748                                                                 p_manager);
2749 }
2750
2751 OPJ_BOOL opj_jp2_write_tile (   opj_jp2_t *p_jp2,
2752                                                             OPJ_UINT32 p_tile_index,
2753                                                             OPJ_BYTE * p_data,
2754                                                             OPJ_UINT32 p_data_size,
2755                                                             opj_stream_private_t *p_stream,
2756                                                             opj_event_mgr_t * p_manager
2757                                 )
2758
2759 {
2760         return opj_j2k_write_tile (p_jp2->j2k,p_tile_index,p_data,p_data_size,p_stream,p_manager);
2761 }
2762
2763 OPJ_BOOL opj_jp2_decode_tile (  opj_jp2_t * p_jp2,
2764                                 OPJ_UINT32 p_tile_index,
2765                                 OPJ_BYTE * p_data,
2766                                 OPJ_UINT32 p_data_size,
2767                                 opj_stream_private_t *p_stream,
2768                                 opj_event_mgr_t * p_manager
2769                                 )
2770 {
2771         return opj_j2k_decode_tile (p_jp2->j2k,p_tile_index,p_data,p_data_size,p_stream,p_manager);
2772 }
2773
2774 void opj_jp2_destroy(opj_jp2_t *jp2)
2775 {
2776         if (jp2) {
2777                 /* destroy the J2K codec */
2778                 opj_j2k_destroy(jp2->j2k);
2779                 jp2->j2k = 00;
2780
2781                 if (jp2->comps) {
2782                         opj_free(jp2->comps);
2783                         jp2->comps = 00;
2784                 }
2785
2786                 if (jp2->cl) {
2787                         opj_free(jp2->cl);
2788                         jp2->cl = 00;
2789                 }
2790
2791                 if (jp2->color.icc_profile_buf) {
2792                         opj_free(jp2->color.icc_profile_buf);
2793                         jp2->color.icc_profile_buf = 00;
2794                 }
2795
2796                 if (jp2->color.jp2_cdef) {
2797                         if (jp2->color.jp2_cdef->info) {
2798                                 opj_free(jp2->color.jp2_cdef->info);
2799                                 jp2->color.jp2_cdef->info = NULL;
2800                         }
2801
2802                         opj_free(jp2->color.jp2_cdef);
2803                         jp2->color.jp2_cdef = 00;
2804                 }
2805
2806                 if (jp2->color.jp2_pclr) {
2807                         if (jp2->color.jp2_pclr->cmap) {
2808                                 opj_free(jp2->color.jp2_pclr->cmap);
2809                                 jp2->color.jp2_pclr->cmap = NULL;
2810                         }
2811                         if (jp2->color.jp2_pclr->channel_sign) {
2812                                 opj_free(jp2->color.jp2_pclr->channel_sign);
2813                                 jp2->color.jp2_pclr->channel_sign = NULL;
2814                         }
2815                         if (jp2->color.jp2_pclr->channel_size) {
2816                                 opj_free(jp2->color.jp2_pclr->channel_size);
2817                                 jp2->color.jp2_pclr->channel_size = NULL;
2818                         }
2819                         if (jp2->color.jp2_pclr->entries) {
2820                                 opj_free(jp2->color.jp2_pclr->entries);
2821                                 jp2->color.jp2_pclr->entries = NULL;
2822                         }
2823
2824                         opj_free(jp2->color.jp2_pclr);
2825                         jp2->color.jp2_pclr = 00;
2826                 }
2827
2828                 if (jp2->m_validation_list) {
2829                         opj_procedure_list_destroy(jp2->m_validation_list);
2830                         jp2->m_validation_list = 00;
2831                 }
2832
2833                 if (jp2->m_procedure_list) {
2834                         opj_procedure_list_destroy(jp2->m_procedure_list);
2835                         jp2->m_procedure_list = 00;
2836                 }
2837
2838                 opj_free(jp2);
2839         }
2840 }
2841
2842 OPJ_BOOL opj_jp2_set_decode_area(       opj_jp2_t *p_jp2,
2843                                                                     opj_image_t* p_image,
2844                                                                     OPJ_INT32 p_start_x, OPJ_INT32 p_start_y,
2845                                                                     OPJ_INT32 p_end_x, OPJ_INT32 p_end_y,
2846                                                                     opj_event_mgr_t * p_manager
2847                                     )
2848 {
2849         return opj_j2k_set_decode_area(p_jp2->j2k, p_image, p_start_x, p_start_y, p_end_x, p_end_y, p_manager);
2850 }
2851
2852 OPJ_BOOL opj_jp2_get_tile(      opj_jp2_t *p_jp2,
2853                             opj_stream_private_t *p_stream,
2854                             opj_image_t* p_image,
2855                             opj_event_mgr_t * p_manager,
2856                             OPJ_UINT32 tile_index
2857                             )
2858 {
2859         if (!p_image)
2860                 return OPJ_FALSE;
2861
2862         opj_event_msg(p_manager, EVT_WARNING, "JP2 box which are after the codestream will not be read by this function.\n");
2863
2864         if (! opj_j2k_get_tile(p_jp2->j2k, p_stream, p_image, p_manager, tile_index) ){
2865                 opj_event_msg(p_manager, EVT_ERROR, "Failed to decode the codestream in the JP2 file\n");
2866                 return OPJ_FALSE;
2867         }
2868
2869         if (!opj_jp2_check_color(p_image, &(p_jp2->color), p_manager)) {
2870                 return OPJ_FALSE;
2871         }
2872
2873         /* Set Image Color Space */
2874         if (p_jp2->enumcs == 16)
2875                 p_image->color_space = OPJ_CLRSPC_SRGB;
2876         else if (p_jp2->enumcs == 17)
2877                 p_image->color_space = OPJ_CLRSPC_GRAY;
2878         else if (p_jp2->enumcs == 18)
2879                 p_image->color_space = OPJ_CLRSPC_SYCC;
2880         else if (p_jp2->enumcs == 24)
2881                 p_image->color_space = OPJ_CLRSPC_EYCC;
2882         else if (p_jp2->enumcs == 12)
2883                 p_image->color_space = OPJ_CLRSPC_CMYK;
2884         else
2885                 p_image->color_space = OPJ_CLRSPC_UNKNOWN;
2886
2887         if(p_jp2->color.jp2_pclr) {
2888                 /* Part 1, I.5.3.4: Either both or none : */
2889                 if( !p_jp2->color.jp2_pclr->cmap)
2890                         opj_jp2_free_pclr(&(p_jp2->color));
2891                 else
2892                         opj_jp2_apply_pclr(p_image, &(p_jp2->color));
2893         }
2894         
2895         /* Apply the color space if needed */
2896         if(p_jp2->color.jp2_cdef) {
2897                 opj_jp2_apply_cdef(p_image, &(p_jp2->color), p_manager);
2898         }
2899
2900         if(p_jp2->color.icc_profile_buf) {
2901                 p_image->icc_profile_buf = p_jp2->color.icc_profile_buf;
2902                 p_image->icc_profile_len = p_jp2->color.icc_profile_len;
2903                 p_jp2->color.icc_profile_buf = NULL;
2904         }
2905
2906         return OPJ_TRUE;
2907 }
2908
2909 /* ----------------------------------------------------------------------- */
2910 /* JP2 encoder interface                                             */
2911 /* ----------------------------------------------------------------------- */
2912
2913 opj_jp2_t* opj_jp2_create(OPJ_BOOL p_is_decoder)
2914 {
2915         opj_jp2_t *jp2 = (opj_jp2_t*)opj_calloc(1,sizeof(opj_jp2_t));
2916         if (jp2) {
2917
2918                 /* create the J2K codec */
2919                 if (! p_is_decoder) {
2920                         jp2->j2k = opj_j2k_create_compress();
2921                 }
2922                 else {
2923                         jp2->j2k = opj_j2k_create_decompress();
2924                 }
2925
2926                 if (jp2->j2k == 00) {
2927                         opj_jp2_destroy(jp2);
2928                         return 00;
2929                 }
2930
2931                 /* Color structure */
2932                 jp2->color.icc_profile_buf = NULL;
2933                 jp2->color.icc_profile_len = 0;
2934                 jp2->color.jp2_cdef = NULL;
2935                 jp2->color.jp2_pclr = NULL;
2936                 jp2->color.jp2_has_colr = 0;
2937
2938                 /* validation list creation */
2939                 jp2->m_validation_list = opj_procedure_list_create();
2940                 if (! jp2->m_validation_list) {
2941                         opj_jp2_destroy(jp2);
2942                         return 00;
2943                 }
2944
2945                 /* execution list creation */
2946                 jp2->m_procedure_list = opj_procedure_list_create();
2947                 if (! jp2->m_procedure_list) {
2948                         opj_jp2_destroy(jp2);
2949                         return 00;
2950                 }
2951         }
2952
2953         return jp2;
2954 }
2955
2956 void jp2_dump(opj_jp2_t* p_jp2, OPJ_INT32 flag, FILE* out_stream)
2957 {
2958         /* preconditions */
2959         assert(p_jp2 != 00);
2960
2961         j2k_dump(p_jp2->j2k,
2962                                         flag,
2963                                         out_stream);
2964 }
2965
2966 opj_codestream_index_t* jp2_get_cstr_index(opj_jp2_t* p_jp2)
2967 {
2968         return j2k_get_cstr_index(p_jp2->j2k);
2969 }
2970
2971 opj_codestream_info_v2_t* jp2_get_cstr_info(opj_jp2_t* p_jp2)
2972 {
2973         return j2k_get_cstr_info(p_jp2->j2k);
2974 }
2975
2976 OPJ_BOOL opj_jp2_set_decoded_resolution_factor(opj_jp2_t *p_jp2,
2977                                                OPJ_UINT32 res_factor,
2978                                                opj_event_mgr_t * p_manager)
2979 {
2980         return opj_j2k_set_decoded_resolution_factor(p_jp2->j2k, res_factor, p_manager);
2981 }
2982
2983 /* JPIP specific */
2984
2985 #ifdef USE_JPIP
2986 static OPJ_BOOL opj_jpip_write_iptr(opj_jp2_t *jp2,
2987   opj_stream_private_t *cio,
2988   opj_event_mgr_t * p_manager )
2989 {
2990   OPJ_OFF_T j2k_codestream_exit;
2991   OPJ_BYTE l_data_header [24];
2992
2993   /* preconditions */
2994   assert(jp2 != 00);
2995   assert(cio != 00);
2996   assert(p_manager != 00);
2997   assert(opj_stream_has_seek(cio));
2998
2999   j2k_codestream_exit = opj_stream_tell(cio);
3000   opj_write_bytes(l_data_header, 24, 4); /* size of iptr */
3001   opj_write_bytes(l_data_header + 4,JPIP_IPTR,4);                                                                          /* IPTR */
3002 #if 0
3003   opj_write_bytes(l_data_header + 4 + 4, 0, 8); /* offset */
3004   opj_write_bytes(l_data_header + 8 + 8, 0, 8); /* length */
3005 #else
3006   opj_write_double(l_data_header + 4 + 4, 0); /* offset */
3007   opj_write_double(l_data_header + 8 + 8, 0); /* length */
3008 #endif
3009
3010   if (! opj_stream_seek(cio,jp2->jpip_iptr_offset,p_manager)) {
3011     opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
3012     return OPJ_FALSE;
3013   }
3014
3015   if (opj_stream_write_data(cio,l_data_header,24,p_manager) != 24) {
3016     opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
3017     return OPJ_FALSE;
3018   }
3019
3020   if (! opj_stream_seek(cio,j2k_codestream_exit,p_manager)) {
3021     opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
3022     return OPJ_FALSE;
3023   }
3024
3025   return OPJ_TRUE;
3026 }
3027
3028 static OPJ_BOOL opj_jpip_write_fidx(opj_jp2_t *jp2,
3029   opj_stream_private_t *cio,
3030   opj_event_mgr_t * p_manager )
3031 {
3032   OPJ_OFF_T j2k_codestream_exit;
3033   OPJ_BYTE l_data_header [24];
3034
3035   /* preconditions */
3036   assert(jp2 != 00);
3037   assert(cio != 00);
3038   assert(p_manager != 00);
3039   assert(opj_stream_has_seek(cio));
3040
3041   opj_write_bytes(l_data_header, 24, 4); /* size of iptr */
3042   opj_write_bytes(l_data_header + 4,JPIP_FIDX,4);                                                                          /* IPTR */
3043   opj_write_double(l_data_header + 4 + 4, 0); /* offset */
3044   opj_write_double(l_data_header + 8 + 8, 0); /* length */
3045
3046   if (opj_stream_write_data(cio,l_data_header,24,p_manager) != 24) {
3047     opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
3048     return OPJ_FALSE;
3049   }
3050
3051   j2k_codestream_exit = opj_stream_tell(cio);
3052   if (! opj_stream_seek(cio,j2k_codestream_exit,p_manager)) {
3053     opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
3054     return OPJ_FALSE;
3055   }
3056
3057   return OPJ_TRUE;
3058 }
3059
3060 static OPJ_BOOL opj_jpip_write_cidx(opj_jp2_t *jp2,
3061   opj_stream_private_t *cio,
3062   opj_event_mgr_t * p_manager )
3063 {
3064   OPJ_OFF_T j2k_codestream_exit;
3065   OPJ_BYTE l_data_header [24];
3066
3067   /* preconditions */
3068   assert(jp2 != 00);
3069   assert(cio != 00);
3070   assert(p_manager != 00);
3071   assert(opj_stream_has_seek(cio));
3072
3073   j2k_codestream_exit = opj_stream_tell(cio);
3074   opj_write_bytes(l_data_header, 24, 4); /* size of iptr */
3075   opj_write_bytes(l_data_header + 4,JPIP_CIDX,4);                                                                          /* IPTR */
3076 #if 0
3077   opj_write_bytes(l_data_header + 4 + 4, 0, 8); /* offset */
3078   opj_write_bytes(l_data_header + 8 + 8, 0, 8); /* length */
3079 #else
3080   opj_write_double(l_data_header + 4 + 4, 0); /* offset */
3081   opj_write_double(l_data_header + 8 + 8, 0); /* length */
3082 #endif
3083
3084   if (! opj_stream_seek(cio,j2k_codestream_exit,p_manager)) {
3085     opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
3086     return OPJ_FALSE;
3087   }
3088
3089   if (opj_stream_write_data(cio,l_data_header,24,p_manager) != 24) {
3090     opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
3091     return OPJ_FALSE;
3092   }
3093
3094   j2k_codestream_exit = opj_stream_tell(cio);
3095   if (! opj_stream_seek(cio,j2k_codestream_exit,p_manager)) {
3096     opj_event_msg(p_manager, EVT_ERROR, "Failed to seek in the stream.\n");
3097     return OPJ_FALSE;
3098   }
3099
3100   return OPJ_TRUE;
3101 }
3102
3103 #if 0
3104 static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_stream_private_t *cio,
3105   opj_event_mgr_t * p_manager )
3106 {
3107   OPJ_BYTE l_data_header [8];
3108   OPJ_OFF_T len, lenp;
3109
3110   lenp = opj_stream_tell(cio);
3111   opj_stream_skip(cio, 4, p_manager);         /* L [at the end] */
3112   opj_write_bytes(l_data_header,JPIP_PRXY,4); /* IPTR           */
3113   opj_stream_write_data(cio,l_data_header,4,p_manager);
3114
3115   opj_write_bytes( l_data_header, offset_jp2c, 8); /* OOFF           */
3116   opj_stream_write_data(cio,l_data_header,8,p_manager);
3117   opj_write_bytes( l_data_header, length_jp2c, 4); /* OBH part 1     */
3118   opj_write_bytes( l_data_header+4, JP2_JP2C, 4);  /* OBH part 2     */
3119   opj_stream_write_data(cio,l_data_header,8,p_manager);
3120
3121   opj_write_bytes( l_data_header, 1, 1);/* NI             */
3122   opj_stream_write_data(cio,l_data_header,1,p_manager);
3123
3124   opj_write_bytes( l_data_header, offset_idx, 8);  /* IOFF           */
3125   opj_stream_write_data(cio,l_data_header,8,p_manager);
3126   opj_write_bytes( l_data_header, length_idx, 4);  /* IBH part 1     */
3127   opj_write_bytes( l_data_header+4, JPIP_CIDX, 4);   /* IBH part 2     */
3128   opj_stream_write_data(cio,l_data_header,8,p_manager);
3129
3130   len = opj_stream_tell(cio)-lenp;
3131   opj_stream_skip(cio, lenp, p_manager);
3132   opj_write_bytes(l_data_header,len,4);/* L              */
3133   opj_stream_write_data(cio,l_data_header,4,p_manager);
3134   opj_stream_seek(cio, lenp+len,p_manager);
3135 }
3136 #endif
3137
3138
3139 #if 0
3140 static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_stream_private_t *cio,
3141   opj_event_mgr_t * p_manager )
3142 {
3143   OPJ_BYTE l_data_header [4];
3144   OPJ_OFF_T len, lenp;
3145
3146   lenp = opj_stream_tell(cio);
3147   opj_stream_skip(cio, 4, p_manager);
3148   opj_write_bytes(l_data_header,JPIP_FIDX,4); /* FIDX */
3149   opj_stream_write_data(cio,l_data_header,4,p_manager);
3150
3151   write_prxy( offset_jp2c, length_jp2c, offset_idx, length_idx, cio,p_manager);
3152
3153   len = opj_stream_tell(cio)-lenp;
3154   opj_stream_skip(cio, lenp, p_manager);
3155   opj_write_bytes(l_data_header,len,4);/* L              */
3156   opj_stream_write_data(cio,l_data_header,4,p_manager);
3157   opj_stream_seek(cio, lenp+len,p_manager);
3158
3159   return len;
3160 }
3161 #endif
3162 #endif /* USE_JPIP */