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