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