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