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