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