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