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