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