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