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