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