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