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