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