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