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