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