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