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