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