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