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