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