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