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