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