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