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