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