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