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