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