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