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