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