[1.5] Check the number of tiles
[openjpeg.git] / libopenjpeg / jp2.c
1 /*
2  * Copyright (c) 2002-2007, Communications and Remote Sensing Laboratory, Universite catholique de Louvain (UCL), Belgium
3  * Copyright (c) 2002-2007, Professor Benoit Macq
4  * Copyright (c) 2001-2003, David Janssens
5  * Copyright (c) 2002-2003, Yannick Verschueren
6  * Copyright (c) 2003-2007, Francois-Olivier Devaux and Antonin Descampe
7  * Copyright (c) 2005, Herve Drolon, FreeImage Team
8  * Copyright (c) 2010-2011, Kaori Hagihara
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 #include "opj_includes.h"
33 #include <assert.h>
34
35 /** @defgroup JP2 JP2 - JPEG-2000 file format reader/writer */
36 /*@{*/
37
38 /** @name Local static functions */
39 /*@{*/
40
41 /**
42 Read box headers
43 @param cinfo Codec context info
44 @param cio Input stream
45 @param box
46 @return Returns true if successful, returns false otherwise
47 */
48 static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box);
49 /*static void jp2_write_url(opj_cio_t *cio, char *Idx_file);*/
50 /**
51 Read the IHDR box - Image Header box
52 @param jp2 JP2 handle
53 @param cio Input buffer stream
54 @return Returns true if successful, returns false otherwise
55 */
56 static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio);
57 static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio);
58 static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio);
59 static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio);
60 static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio);
61 /**
62 Write the FTYP box - File type box
63 @param jp2 JP2 handle
64 @param cio Output buffer stream
65 */
66 static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio);
67 /**
68 Read the FTYP box - File type box
69 @param jp2 JP2 handle
70 @param cio Input buffer stream
71 @return Returns true if successful, returns false otherwise
72 */
73 static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio);
74 static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info);
75 static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset);
76 static void jp2_write_jp(opj_cio_t *cio);
77 /**
78 Read the JP box - JPEG 2000 signature
79 @param jp2 JP2 handle
80 @param cio Input buffer stream
81 @return Returns true if successful, returns false otherwise
82 */
83 static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio);
84 /**
85 Decode the structure of a JP2 file
86 @param jp2 JP2 handle
87 @param cio Input buffer stream
88 @param color Collector for profile, cdef and pclr data
89 @return Returns true if successful, returns false otherwise
90 */
91 static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
92         opj_jp2_color_t *color);
93 /**
94 Apply collected palette data
95 @param color Collector for profile, cdef and pclr data
96 @param image 
97 */
98 static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_common_ptr cinfo);
99 /**
100 Collect palette data
101 @param jp2 JP2 handle
102 @param cio Input buffer stream
103 @param box
104 @param color Collector for profile, cdef and pclr data
105 @return Returns true if successful, returns false otherwise
106 */
107 static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio,
108     opj_jp2_box_t *box, opj_jp2_color_t *color);
109 /**
110 Collect component mapping data
111 @param jp2 JP2 handle
112 @param cio Input buffer stream
113 @param box
114 @param color Collector for profile, cdef and pclr data
115 @return Returns true if successful, returns false otherwise
116 */
117 static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio,
118     opj_jp2_box_t *box, opj_jp2_color_t *color);
119 /**
120 Collect colour specification data
121 @param jp2 JP2 handle
122 @param cio Input buffer stream
123 @param box
124 @param color Collector for profile, cdef and pclr data
125 @return Returns true if successful, returns false otherwise
126 */
127 static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio,
128     opj_jp2_box_t *box, opj_jp2_color_t *color);
129 /**
130 Write file Index (superbox)
131 @param[in] offset_jp2c offset of jp2c box
132 @param[in] length_jp2c length of jp2c box
133 @param[in] offset_idx  offset of cidx box
134 @param[in] length_idx  length of cidx box
135 @param[in] cio         file output handle
136 @return                length of fidx box
137 */
138 static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio);
139 /**
140 Write index Finder box
141 @param[in] offset offset of fidx box
142 @param[in] length length of fidx box
143 @param[in] cio         file output handle
144 */
145 static void write_iptr( int offset, int length, opj_cio_t *cio);
146 /**
147 Write proxy box
148 @param[in] offset_jp2c offset of jp2c box
149 @param[in] length_jp2c length of jp2c box
150 @param[in] offset_idx  offset of cidx box
151 @param[in] length_idx  length of cidx box
152 @param[in] cio         file output handle
153 */
154 static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio);
155 /*@}*/
156
157 /*@}*/
158
159 /* ----------------------------------------------------------------------- */
160
161 static opj_bool jp2_read_boxhdr(opj_common_ptr cinfo, opj_cio_t *cio, opj_jp2_box_t *box) {
162         box->init_pos = cio_tell(cio);
163         box->length = cio_read(cio, 4);
164         box->type = cio_read(cio, 4);
165         if (box->length == 1) {
166                 if (cio_read(cio, 4) != 0) {
167                         opj_event_msg(cinfo, EVT_ERROR, "Cannot handle box sizes higher than 2^32\n");
168                         return OPJ_FALSE;
169                 }
170                 box->length = cio_read(cio, 4);
171                 if (box->length == 0) 
172                         box->length = cio_numbytesleft(cio) + 12;
173         }
174         else if (box->length == 0) {
175                 box->length = cio_numbytesleft(cio) + 8;
176         } else if (box->length < 0) {
177                 opj_event_msg(cinfo, EVT_ERROR, "Integer overflow in box->length\n");
178                 return OPJ_FALSE; /* TODO: actually check jp2_read_boxhdr's return value */
179         }
180         
181         return OPJ_TRUE;
182 }
183
184 #if 0
185 static void jp2_write_url(opj_cio_t *cio, char *Idx_file) {
186         unsigned int i;
187         opj_jp2_box_t box;
188
189         box.init_pos = cio_tell(cio);
190         cio_skip(cio, 4);
191         cio_write(cio, JP2_URL, 4);     /* DBTL */
192         cio_write(cio, 0, 1);           /* VERS */
193         cio_write(cio, 0, 3);           /* FLAG */
194
195         if(Idx_file) {
196                 for (i = 0; i < strlen(Idx_file); i++) {
197                         cio_write(cio, Idx_file[i], 1);
198                 }
199         }
200
201         box.length = cio_tell(cio) - box.init_pos;
202         cio_seek(cio, box.init_pos);
203         cio_write(cio, box.length, 4);  /* L */
204         cio_seek(cio, box.init_pos + box.length);
205 }
206 #endif
207
208 static opj_bool jp2_read_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
209         opj_jp2_box_t box;
210
211         opj_common_ptr cinfo = jp2->cinfo;
212
213   if(jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
214     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
215     return OPJ_FALSE;
216   }
217         if (JP2_IHDR != box.type) {
218                 opj_event_msg(cinfo, EVT_ERROR, "Expected IHDR Marker\n");
219                 return OPJ_FALSE;
220         }
221
222         jp2->h = cio_read(cio, 4);                      /* HEIGHT */
223         jp2->w = cio_read(cio, 4);                      /* WIDTH */
224         jp2->numcomps = cio_read(cio, 2);       /* NC */
225         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
226
227         jp2->bpc = cio_read(cio, 1);            /* BPC */
228
229         jp2->C = cio_read(cio, 1);                      /* C */
230         jp2->UnkC = cio_read(cio, 1);           /* UnkC */
231         jp2->IPR = cio_read(cio, 1);            /* IPR */
232
233         if (cio_tell(cio) - box.init_pos != box.length) {
234                 opj_event_msg(cinfo, EVT_ERROR, "Error with IHDR Box\n");
235                 return OPJ_FALSE;
236         }
237
238         return OPJ_TRUE;
239 }
240
241 static void jp2_write_ihdr(opj_jp2_t *jp2, opj_cio_t *cio) {
242         opj_jp2_box_t box;
243
244         box.init_pos = cio_tell(cio);
245         cio_skip(cio, 4);
246         cio_write(cio, JP2_IHDR, 4);            /* IHDR */
247
248         cio_write(cio, jp2->h, 4);                      /* HEIGHT */
249         cio_write(cio, jp2->w, 4);                      /* WIDTH */
250         cio_write(cio, jp2->numcomps, 2);       /* NC */
251
252         cio_write(cio, jp2->bpc, 1);            /* BPC */
253
254         cio_write(cio, jp2->C, 1);                      /* C : Always 7 */
255         cio_write(cio, jp2->UnkC, 1);           /* UnkC, colorspace unknown */
256         cio_write(cio, jp2->IPR, 1);            /* IPR, no intellectual property */
257
258         box.length = cio_tell(cio) - box.init_pos;
259         cio_seek(cio, box.init_pos);
260         cio_write(cio, box.length, 4);  /* L */
261         cio_seek(cio, box.init_pos + box.length);
262 }
263
264 static void jp2_write_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
265         unsigned int i;
266         opj_jp2_box_t box;
267
268         box.init_pos = cio_tell(cio);
269         cio_skip(cio, 4);
270         cio_write(cio, JP2_BPCC, 4);    /* BPCC */
271
272         for (i = 0; i < jp2->numcomps; i++) {
273                 cio_write(cio, jp2->comps[i].bpcc, 1);
274         }
275
276         box.length = cio_tell(cio) - box.init_pos;
277         cio_seek(cio, box.init_pos);
278         cio_write(cio, box.length, 4);  /* L */
279         cio_seek(cio, box.init_pos + box.length);
280 }
281
282
283 static opj_bool jp2_read_bpcc(opj_jp2_t *jp2, opj_cio_t *cio) {
284         unsigned int i;
285         opj_jp2_box_t box;
286
287         opj_common_ptr cinfo = jp2->cinfo;
288
289   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
290     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
291     return OPJ_FALSE;
292   }
293         if (JP2_BPCC != box.type) {
294                 opj_event_msg(cinfo, EVT_ERROR, "Expected BPCC Marker\n");
295                 return OPJ_FALSE;
296         }
297
298         for (i = 0; i < jp2->numcomps; i++) {
299                 jp2->comps[i].bpcc = cio_read(cio, 1);
300         }
301
302         if (cio_tell(cio) - box.init_pos != box.length) {
303                 opj_event_msg(cinfo, EVT_ERROR, "Error with BPCC Box\n");
304                 return OPJ_FALSE;
305         }
306
307         return OPJ_TRUE;
308 }
309
310 static void jp2_write_colr(opj_jp2_t *jp2, opj_cio_t *cio) {
311         opj_jp2_box_t box;
312
313         box.init_pos = cio_tell(cio);
314         cio_skip(cio, 4);
315         cio_write(cio, JP2_COLR, 4);            /* COLR */
316
317         cio_write(cio, jp2->meth, 1);           /* METH */
318         cio_write(cio, jp2->precedence, 1);     /* PRECEDENCE */
319         cio_write(cio, jp2->approx, 1);         /* APPROX */
320
321         if(jp2->meth == 2)
322          jp2->enumcs = 0;
323
324         cio_write(cio, jp2->enumcs, 4); /* EnumCS */
325
326         box.length = cio_tell(cio) - box.init_pos;
327         cio_seek(cio, box.init_pos);
328         cio_write(cio, box.length, 4);  /* L */
329         cio_seek(cio, box.init_pos + box.length);
330 }
331
332 static void jp2_free_pclr(opj_jp2_color_t *color)
333 {
334     opj_free(color->jp2_pclr->channel_sign);
335     opj_free(color->jp2_pclr->channel_size);
336     opj_free(color->jp2_pclr->entries);
337
338         if(color->jp2_pclr->cmap) opj_free(color->jp2_pclr->cmap);
339
340     opj_free(color->jp2_pclr); color->jp2_pclr = NULL;
341 }
342
343 static void free_color_data(opj_jp2_color_t *color)
344 {
345         if(color->jp2_pclr)
346    {
347         jp2_free_pclr(color);
348    }
349         if(color->jp2_cdef) 
350    {
351         if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info);
352         opj_free(color->jp2_cdef);
353    }
354         if(color->icc_profile_buf) opj_free(color->icc_profile_buf);
355 }
356
357 static void jp2_apply_pclr(opj_jp2_color_t *color, opj_image_t *image, opj_common_ptr cinfo)
358 {
359         opj_image_comp_t *old_comps, *new_comps;
360         unsigned char *channel_size, *channel_sign;
361         unsigned int *entries;
362         opj_jp2_cmap_comp_t *cmap;
363         int *src, *dst;
364         unsigned int j, max;
365         unsigned short i, nr_channels, cmp, pcol;
366         int k, top_k;
367
368         channel_size = color->jp2_pclr->channel_size;
369         channel_sign = color->jp2_pclr->channel_sign;
370         entries = color->jp2_pclr->entries;
371         cmap = color->jp2_pclr->cmap;
372         nr_channels = color->jp2_pclr->nr_channels;
373
374         old_comps = image->comps;
375         new_comps = (opj_image_comp_t*)
376          opj_malloc(nr_channels * sizeof(opj_image_comp_t));
377
378         for(i = 0; i < nr_channels; ++i)
379    {
380         pcol = cmap[i].pcol; cmp = cmap[i].cmp;
381
382   if( pcol < nr_channels )
383     new_comps[pcol] = old_comps[cmp];
384   else
385     {
386     opj_event_msg(cinfo, EVT_ERROR, "Error with pcol value %d (max: %d). skipping\n", pcol, nr_channels);
387     continue;
388     }
389
390         if(cmap[i].mtyp == 0) /* Direct use */
391   {
392         old_comps[cmp].data = NULL; continue;
393   }
394 /* Palette mapping: */
395         new_comps[pcol].data = (int*)
396          opj_malloc(old_comps[cmp].w * old_comps[cmp].h * sizeof(int));
397         new_comps[pcol].prec = channel_size[i];
398         new_comps[pcol].sgnd = channel_sign[i];
399    }
400         top_k = color->jp2_pclr->nr_entries - 1;
401
402         for(i = 0; i < nr_channels; ++i)
403    {
404 /* Direct use: */
405         if(cmap[i].mtyp == 0) continue;
406
407 /* Palette mapping: */
408         cmp = cmap[i].cmp; pcol = cmap[i].pcol;
409         src = old_comps[cmp].data; 
410         dst = new_comps[pcol].data;
411         max = new_comps[pcol].w * new_comps[pcol].h;
412
413         for(j = 0; j < max; ++j)
414   {
415 /* The index */
416         if((k = src[j]) < 0) k = 0; else if(k > top_k) k = top_k;
417 /* The colour */
418         dst[j] = entries[k * nr_channels + pcol];
419   }
420    }
421         max = image->numcomps;
422         for(i = 0; i < max; ++i)
423    {
424         if(old_comps[i].data) opj_free(old_comps[i].data);
425    }
426         opj_free(old_comps);
427         image->comps = new_comps;
428         image->numcomps = nr_channels;
429
430         jp2_free_pclr(color);
431
432 }/* apply_pclr() */
433
434 static opj_bool jp2_read_pclr(opj_jp2_t *jp2, opj_cio_t *cio,
435         opj_jp2_box_t *box, opj_jp2_color_t *color)
436 {
437         opj_jp2_pclr_t *jp2_pclr;
438         unsigned char *channel_size, *channel_sign;
439         unsigned int *entries;
440         unsigned short nr_entries, nr_channels;
441         unsigned short i, j;
442         unsigned char uc;
443
444         OPJ_ARG_NOT_USED(box);
445         OPJ_ARG_NOT_USED(jp2);
446
447 /* Part 1, I.5.3.4: 'There shall be at most one Palette box inside
448  * a JP2 Header box' :
449 */
450         if(color->jp2_pclr) return OPJ_FALSE;
451
452         nr_entries = (unsigned short)cio_read(cio, 2); /* NE */
453         nr_channels = (unsigned short)cio_read(cio, 1);/* NPC */
454
455         entries = (unsigned int*)
456          opj_malloc(nr_channels * nr_entries * sizeof(unsigned int));
457         channel_size = (unsigned char*)opj_malloc(nr_channels);
458         channel_sign = (unsigned char*)opj_malloc(nr_channels);
459
460         jp2_pclr = (opj_jp2_pclr_t*)opj_malloc(sizeof(opj_jp2_pclr_t));
461         jp2_pclr->channel_sign = channel_sign;
462         jp2_pclr->channel_size = channel_size;
463         jp2_pclr->entries = entries;
464         jp2_pclr->nr_entries = nr_entries;
465         jp2_pclr->nr_channels = nr_channels;
466         jp2_pclr->cmap = NULL;
467
468         color->jp2_pclr = jp2_pclr;
469
470         for(i = 0; i < nr_channels; ++i)
471    {
472         uc = cio_read(cio, 1); /* Bi */
473         channel_size[i] = (uc & 0x7f) + 1;
474         channel_sign[i] = (uc & 0x80)?1:0;
475    }
476
477         for(j = 0; j < nr_entries; ++j)
478    {
479         for(i = 0; i < nr_channels; ++i)
480   {
481 /* Cji */
482         *entries++ = cio_read(cio, (channel_size[i]+7)>>3);
483   }
484    }
485
486         return OPJ_TRUE;
487 }/* jp2_read_pclr() */
488
489 static opj_bool jp2_read_cmap(opj_jp2_t *jp2, opj_cio_t *cio,
490         opj_jp2_box_t *box, opj_jp2_color_t *color)
491 {
492         opj_jp2_cmap_comp_t *cmap;
493         unsigned short i, nr_channels;
494
495         OPJ_ARG_NOT_USED(box);
496         OPJ_ARG_NOT_USED(jp2);
497
498 /* Need nr_channels: */
499         if(color->jp2_pclr == NULL) return OPJ_FALSE;
500
501 /* Part 1, I.5.3.5: 'There shall be at most one Component Mapping box
502  * inside a JP2 Header box' :
503 */
504         if(color->jp2_pclr->cmap) return OPJ_FALSE;
505
506         nr_channels = color->jp2_pclr->nr_channels;
507         cmap = (opj_jp2_cmap_comp_t*)
508          opj_malloc(nr_channels * sizeof(opj_jp2_cmap_comp_t));
509
510         for(i = 0; i < nr_channels; ++i)
511    {
512         cmap[i].cmp = (unsigned short)cio_read(cio, 2);
513         cmap[i].mtyp = cio_read(cio, 1);
514         cmap[i].pcol = cio_read(cio, 1);
515
516    }
517         color->jp2_pclr->cmap = cmap;
518
519         return OPJ_TRUE;
520 }/* jp2_read_cmap() */
521
522 static void jp2_apply_cdef(opj_image_t *image, opj_jp2_color_t *color)
523 {
524         opj_jp2_cdef_info_t *info;
525         unsigned short i, n, cn, typ, asoc, acn;
526
527         info = color->jp2_cdef->info;
528         n = color->jp2_cdef->n;
529
530         for(i = 0; i < n; ++i)
531    {
532 /* WATCH: acn = asoc - 1 ! */
533         if((asoc = info[i].asoc) == 0) continue;
534
535         cn = info[i].cn; typ = info[i].typ; acn = asoc - 1;
536   (void)typ;
537
538         if(cn != acn)
539   {
540         opj_image_comp_t saved;
541
542         memcpy(&saved, &image->comps[cn], sizeof(opj_image_comp_t));
543         memcpy(&image->comps[cn], &image->comps[acn], sizeof(opj_image_comp_t));
544         memcpy(&image->comps[acn], &saved, sizeof(opj_image_comp_t));
545
546         info[i].asoc = cn + 1;
547         info[acn].asoc = info[acn].cn + 1;
548   }
549    }
550         if(color->jp2_cdef->info) opj_free(color->jp2_cdef->info);
551
552         opj_free(color->jp2_cdef); color->jp2_cdef = NULL;
553
554 }/* jp2_apply_cdef() */
555
556 static opj_bool jp2_read_cdef(opj_jp2_t *jp2, opj_cio_t *cio,
557         opj_jp2_box_t *box, opj_jp2_color_t *color)
558 {
559         opj_jp2_cdef_info_t *info;
560         unsigned short i, n;
561
562         OPJ_ARG_NOT_USED(box);
563         OPJ_ARG_NOT_USED(jp2);
564
565 /* Part 1, I.5.3.6: 'The shall be at most one Channel Definition box
566  * inside a JP2 Header box.' 
567 */
568         if(color->jp2_cdef) return OPJ_FALSE;
569
570         if((n = (unsigned short)cio_read(cio, 2)) == 0) return OPJ_FALSE; /* szukw000: FIXME */
571
572         info = (opj_jp2_cdef_info_t*)
573          opj_malloc(n * sizeof(opj_jp2_cdef_info_t));
574
575         color->jp2_cdef = (opj_jp2_cdef_t*)opj_malloc(sizeof(opj_jp2_cdef_t));
576         color->jp2_cdef->info = info;
577         color->jp2_cdef->n = n;
578
579         for(i = 0; i < n; ++i)
580    {
581         info[i].cn = (unsigned short)cio_read(cio, 2);
582         info[i].typ = (unsigned short)cio_read(cio, 2);
583         info[i].asoc = (unsigned short)cio_read(cio, 2);
584
585    }
586         return OPJ_TRUE;
587 }/* jp2_read_cdef() */
588
589 static opj_bool jp2_read_colr(opj_jp2_t *jp2, opj_cio_t *cio,
590         opj_jp2_box_t *box, opj_jp2_color_t *color) 
591 {
592         int skip_len;
593     opj_common_ptr cinfo;
594
595 /* Part 1, I.5.3.3 : 'A conforming JP2 reader shall ignore all Colour
596  * Specification boxes after the first.' 
597 */
598         if(color->jp2_has_colr) return OPJ_FALSE;
599
600         cinfo = jp2->cinfo;
601
602         jp2->meth = cio_read(cio, 1);           /* METH */
603         jp2->precedence = cio_read(cio, 1);     /* PRECEDENCE */
604         jp2->approx = cio_read(cio, 1);         /* APPROX */
605
606         if (jp2->meth == 1) 
607    {
608         jp2->enumcs = cio_read(cio, 4); /* EnumCS */
609    } 
610         else
611         if (jp2->meth == 2) 
612    {
613 /* skip PROFILE */
614         skip_len = box->init_pos + box->length - cio_tell(cio);
615         if (skip_len < 0) 
616   {
617         opj_event_msg(cinfo, EVT_ERROR, "Error with COLR box size\n");
618         return OPJ_FALSE;
619   }
620         if(skip_len > 0)
621   {
622         unsigned char *start;
623
624         start = cio_getbp(cio);
625         color->icc_profile_buf = (unsigned char*)opj_malloc(skip_len);
626         color->icc_profile_len = skip_len;
627
628         cio_skip(cio, box->init_pos + box->length - cio_tell(cio));
629
630         memcpy(color->icc_profile_buf, start, skip_len);
631   }
632    }
633
634         if (cio_tell(cio) - box->init_pos != box->length) 
635    {
636         opj_event_msg(cinfo, EVT_ERROR, "Error with COLR Box\n");
637         return OPJ_FALSE;
638    }
639         color->jp2_has_colr = 1;
640
641         return OPJ_TRUE;
642 }/* jp2_read_colr() */
643
644 opj_bool jp2_read_jp2h(opj_jp2_t *jp2, opj_cio_t *cio, opj_jp2_color_t *color) 
645 {
646         opj_jp2_box_t box;
647         int jp2h_end;
648
649         opj_common_ptr cinfo = jp2->cinfo;
650
651   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
652   do {
653     if (JP2_JP2H != box.type) 
654       {
655       if (box.type == JP2_JP2C) 
656         {
657         opj_event_msg(cinfo, EVT_ERROR, "Expected JP2H Marker\n");
658         return OPJ_FALSE;
659         }
660           if (box.length <= 8) return OPJ_FALSE;
661       cio_skip(cio, box.length - 8);
662
663       if(cio->bp >= cio->end) return OPJ_FALSE;
664
665       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
666       }
667   } while(JP2_JP2H != box.type);
668
669         if (!jp2_read_ihdr(jp2, cio))
670                 return OPJ_FALSE;
671         jp2h_end = box.init_pos + box.length;
672
673   if (jp2->bpc == 255) 
674     {
675     if (!jp2_read_bpcc(jp2, cio))
676       return OPJ_FALSE;
677     }
678   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
679
680   while(cio_tell(cio) < jp2h_end)
681     {
682     if(box.type == JP2_COLR)
683       {
684       if( !jp2_read_colr(jp2, cio, &box, color))
685         {
686         if (box.length <= 8) return OPJ_FALSE;
687         cio_seek(cio, box.init_pos + 8);
688         cio_skip(cio, box.length - 8);
689         }
690       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
691       continue;
692       }
693     if(box.type == JP2_CDEF && !jp2->ignore_pclr_cmap_cdef)
694       {
695       if( !jp2_read_cdef(jp2, cio, &box, color))
696         {
697         if (box.length <= 8) return OPJ_FALSE;
698         cio_seek(cio, box.init_pos + 8);
699         cio_skip(cio, box.length - 8);
700         }
701       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
702       continue;
703       }
704     if(box.type == JP2_PCLR && !jp2->ignore_pclr_cmap_cdef)
705       {
706       if( !jp2_read_pclr(jp2, cio, &box, color))
707         {
708         if (box.length <= 8) return OPJ_FALSE;
709         cio_seek(cio, box.init_pos + 8);
710         cio_skip(cio, box.length - 8);
711         }
712       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
713       continue;
714       }
715     if(box.type == JP2_CMAP && !jp2->ignore_pclr_cmap_cdef)
716       {
717       if( !jp2_read_cmap(jp2, cio, &box, color))
718         {
719         if (box.length <= 8) return OPJ_FALSE;
720         cio_seek(cio, box.init_pos + 8);
721         cio_skip(cio, box.length - 8);
722         }
723       if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
724       continue;
725       }
726     if (box.length <= 8) return OPJ_FALSE;
727     cio_seek(cio, box.init_pos + 8);
728     cio_skip(cio, box.length - 8);
729     if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
730
731     }/* while(cio_tell(cio) < box_end) */
732
733   cio_seek(cio, jp2h_end);
734
735   /* Part 1, I.5.3.3 : 'must contain at least one' */
736   return (color->jp2_has_colr == 1);
737
738 }/* jp2_read_jp2h() */
739
740 static opj_bool opj_jp2_check_color(opj_image_t *image, opj_jp2_color_t *color, opj_common_ptr cinfo)
741 {
742         int i;
743
744         /* testcase 4149.pdf.SIGSEGV.cf7.3501 */
745         if (color->jp2_cdef) {
746                 opj_jp2_cdef_info_t *info = color->jp2_cdef->info;
747                 int n = color->jp2_cdef->n;
748
749                 for (i = 0; i < n; i++) {
750                         if (info[i].cn >= image->numcomps) {
751                                 opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].cn, image->numcomps);
752                                 return OPJ_FALSE;
753                         }
754                         if (info[i].asoc > 0 && (info[i].asoc - 1) >= image->numcomps) {
755                                 opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", info[i].asoc - 1, image->numcomps);
756                                 return OPJ_FALSE;
757                         }
758                 }
759         }
760
761         /* testcases 451.pdf.SIGSEGV.f4c.3723, 451.pdf.SIGSEGV.5b5.3723 and
762            66ea31acbb0f23a2bbc91f64d69a03f5_signal_sigsegv_13937c0_7030_5725.pdf */
763         if (color->jp2_pclr && color->jp2_pclr->cmap) {
764                 int nr_channels = color->jp2_pclr->nr_channels;
765                 opj_jp2_cmap_comp_t *cmap = color->jp2_pclr->cmap;
766                 opj_bool *pcol_usage, is_sane = OPJ_TRUE;
767
768                 /* verify that all original components match an existing one */
769                 for (i = 0; i < nr_channels; i++) {
770                         if (cmap[i].cmp >= image->numcomps) {
771                                 opj_event_msg(cinfo, EVT_ERROR, "Invalid component index %d (>= %d).\n", cmap[i].cmp, image->numcomps);
772                                 is_sane = OPJ_FALSE;
773                         }
774                 }
775
776                 pcol_usage = opj_calloc(nr_channels, sizeof(opj_bool));
777                 if (!pcol_usage) {
778                         opj_event_msg(cinfo, EVT_ERROR, "Unexpected OOM.\n");
779                         return OPJ_FALSE;
780                 }
781                 /* verify that no component is targeted more than once */
782                 for (i = 0; i < nr_channels; i++) {
783       int pcol = cmap[i].pcol;
784       assert(cmap[i].mtyp == 0 || cmap[i].mtyp == 1);
785                         if (pcol >= nr_channels) {
786                                 opj_event_msg(cinfo, EVT_ERROR, "Invalid component/palette index for direct mapping %d.\n", pcol);
787                                 is_sane = OPJ_FALSE;
788                         }
789                         else if (pcol_usage[pcol] && cmap[i].mtyp == 1) {
790                                 opj_event_msg(cinfo, EVT_ERROR, "Component %d is mapped twice.\n", pcol);
791                                 is_sane = OPJ_FALSE;
792                         }
793       else if (cmap[i].mtyp == 0 && cmap[i].pcol != 0) {
794         /* I.5.3.5 PCOL: If the value of the MTYP field for this channel is 0, then
795          * the value of this field shall be 0. */
796                                 opj_event_msg(cinfo, EVT_ERROR, "Direct use at #%d however pcol=%d.\n", i, pcol);
797                                 is_sane = OPJ_FALSE;
798       }
799                         else
800                                 pcol_usage[pcol] = OPJ_TRUE;
801                 }
802                 /* verify that all components are targeted at least once */
803                 for (i = 0; i < nr_channels; i++) {
804                         if (!pcol_usage[i] && cmap[i].mtyp != 0) {
805                                 opj_event_msg(cinfo, EVT_ERROR, "Component %d doesn't have a mapping.\n", i);
806                                 is_sane = OPJ_FALSE;
807                         }
808                 }
809                 opj_free(pcol_usage);
810                 if (!is_sane) {
811                         return OPJ_FALSE;
812                 }
813         }
814
815         return OPJ_TRUE;
816 }
817
818 opj_image_t* opj_jp2_decode(opj_jp2_t *jp2, opj_cio_t *cio, 
819         opj_codestream_info_t *cstr_info) 
820 {
821         opj_common_ptr cinfo;
822         opj_image_t *image = NULL;
823         opj_jp2_color_t color;
824
825         if(!jp2 || !cio) 
826    {
827         return NULL;
828    }
829         memset(&color, 0, sizeof(opj_jp2_color_t));
830         cinfo = jp2->cinfo;
831
832 /* JP2 decoding */
833         if(!jp2_read_struct(jp2, cio, &color)) 
834    {
835         free_color_data(&color);
836         opj_event_msg(cinfo, EVT_ERROR, "Failed to decode jp2 structure\n");
837         return NULL;
838    }
839
840 /* J2K decoding */
841         image = j2k_decode(jp2->j2k, cio, cstr_info);
842
843         if(!image) 
844    {
845         free_color_data(&color);
846         opj_event_msg(cinfo, EVT_ERROR, "Failed to decode J2K image\n");
847         return NULL;
848    }
849    
850     if (!jp2->ignore_pclr_cmap_cdef){
851             if (!opj_jp2_check_color(image, &color, cinfo)) {
852         opj_event_msg(cinfo, EVT_ERROR, "Failed to decode PCRL box\n");
853                     return NULL;
854             }
855
856     /* Set Image Color Space */
857         if (jp2->enumcs == 16)
858                 image->color_space = CLRSPC_SRGB;
859         else if (jp2->enumcs == 17)
860                 image->color_space = CLRSPC_GRAY;
861         else if (jp2->enumcs == 18)
862                 image->color_space = CLRSPC_SYCC;
863         else
864                 image->color_space = CLRSPC_UNKNOWN;
865
866         if(color.jp2_cdef)
867    {
868         jp2_apply_cdef(image, &color);
869    }
870         if(color.jp2_pclr)
871    {
872 /* Part 1, I.5.3.4: Either both or none : */
873         if( !color.jp2_pclr->cmap) 
874          jp2_free_pclr(&color);
875         else
876          jp2_apply_pclr(&color, image, cinfo);
877    }
878         if(color.icc_profile_buf)
879    {
880         image->icc_profile_buf = color.icc_profile_buf;
881         color.icc_profile_buf = NULL;
882         image->icc_profile_len = color.icc_profile_len;
883    }
884    }
885    
886         return image;
887
888 }/* opj_jp2_decode() */
889
890
891 void jp2_write_jp2h(opj_jp2_t *jp2, opj_cio_t *cio) {
892         opj_jp2_box_t box;
893
894         box.init_pos = cio_tell(cio);
895         cio_skip(cio, 4);
896         cio_write(cio, JP2_JP2H, 4);    /* JP2H */
897
898         jp2_write_ihdr(jp2, cio);
899
900         if (jp2->bpc == 255) {
901                 jp2_write_bpcc(jp2, cio);
902         }
903         jp2_write_colr(jp2, cio);
904
905         box.length = cio_tell(cio) - box.init_pos;
906         cio_seek(cio, box.init_pos);
907         cio_write(cio, box.length, 4);  /* L */
908         cio_seek(cio, box.init_pos + box.length);
909 }
910
911 static void jp2_write_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
912         unsigned int i;
913         opj_jp2_box_t box;
914
915         box.init_pos = cio_tell(cio);
916         cio_skip(cio, 4);
917         cio_write(cio, JP2_FTYP, 4);            /* FTYP */
918
919         cio_write(cio, jp2->brand, 4);          /* BR */
920         cio_write(cio, jp2->minversion, 4);     /* MinV */
921
922         for (i = 0; i < jp2->numcl; i++) {
923                 cio_write(cio, jp2->cl[i], 4);  /* CL */
924         }
925
926         box.length = cio_tell(cio) - box.init_pos;
927         cio_seek(cio, box.init_pos);
928         cio_write(cio, box.length, 4);  /* L */
929         cio_seek(cio, box.init_pos + box.length);
930 }
931
932 static opj_bool jp2_read_ftyp(opj_jp2_t *jp2, opj_cio_t *cio) {
933         int i;
934         opj_jp2_box_t box;
935
936         opj_common_ptr cinfo = jp2->cinfo;
937
938   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
939     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
940     return OPJ_FALSE;
941   }
942         if (JP2_FTYP != box.type) {
943                 opj_event_msg(cinfo, EVT_ERROR, "Expected FTYP Marker\n");
944                 return OPJ_FALSE;
945         }
946
947         jp2->brand = cio_read(cio, 4);          /* BR */
948         jp2->minversion = cio_read(cio, 4);     /* MinV */
949         jp2->numcl = (box.length - 16) / 4;
950
951   /* edf_c2_1673169.jp2 */
952         if (cio_numbytesleft(cio) < ((int)jp2->numcl * 4)) {
953                 opj_event_msg(cinfo, EVT_ERROR, "Not enough bytes in FTYP Box "
954                                 "(expected %d, but only %d left)\n",
955                                 ((int)jp2->numcl * 4), cio_numbytesleft(cio));
956                 return OPJ_FALSE;
957         }
958         jp2->cl = (unsigned int *) opj_malloc(jp2->numcl * sizeof(unsigned int));
959
960         for (i = 0; i < (int)jp2->numcl; i++) {
961                 jp2->cl[i] = cio_read(cio, 4);  /* CLi */
962         }
963
964         if (cio_tell(cio) - box.init_pos != box.length) {
965                 opj_event_msg(cinfo, EVT_ERROR, "Error with FTYP Box\n");
966                 return OPJ_FALSE;
967         }
968
969         return OPJ_TRUE;
970 }
971
972 static int jp2_write_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
973         unsigned int j2k_codestream_offset, j2k_codestream_length;
974         opj_jp2_box_t box;
975
976         opj_j2k_t *j2k = jp2->j2k;
977
978         box.init_pos = cio_tell(cio);
979         cio_skip(cio, 4);
980         cio_write(cio, JP2_JP2C, 4);    /* JP2C */
981
982         /* J2K encoding */
983         j2k_codestream_offset = cio_tell(cio);
984         if(!j2k_encode(j2k, cio, image, cstr_info)) {
985                 opj_event_msg(j2k->cinfo, EVT_ERROR, "Failed to encode image\n");
986                 return 0;
987         }
988         j2k_codestream_length = cio_tell(cio) - j2k_codestream_offset;
989
990         jp2->j2k_codestream_offset = j2k_codestream_offset;
991         jp2->j2k_codestream_length = j2k_codestream_length;
992
993         box.length = 8 + jp2->j2k_codestream_length;
994         cio_seek(cio, box.init_pos);
995         cio_write(cio, box.length, 4);  /* L */
996         cio_seek(cio, box.init_pos + box.length);
997
998         return box.length;
999 }
1000
1001 static opj_bool jp2_read_jp2c(opj_jp2_t *jp2, opj_cio_t *cio, unsigned int *j2k_codestream_length, unsigned int *j2k_codestream_offset) {
1002         opj_jp2_box_t box;
1003
1004         opj_common_ptr cinfo = jp2->cinfo;
1005
1006   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
1007     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
1008     return OPJ_FALSE;
1009   }
1010         do {
1011                 if(JP2_JP2C != box.type) {
1012                         if (box.length <= 8) return OPJ_FALSE;
1013                         cio_skip(cio, box.length - 8);
1014                         if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) return OPJ_FALSE;
1015                 }
1016         } while(JP2_JP2C != box.type);
1017
1018         *j2k_codestream_offset = cio_tell(cio);
1019         if (box.length <= 8) return OPJ_FALSE;
1020         *j2k_codestream_length = box.length - 8;
1021
1022         return OPJ_TRUE;
1023 }
1024
1025 static void jp2_write_jp(opj_cio_t *cio) {
1026         opj_jp2_box_t box;
1027
1028         box.init_pos = cio_tell(cio);
1029         cio_skip(cio, 4);
1030         cio_write(cio, JP2_JP, 4);              /* JP2 signature */
1031         cio_write(cio, 0x0d0a870a, 4);
1032
1033         box.length = cio_tell(cio) - box.init_pos;
1034         cio_seek(cio, box.init_pos);
1035         cio_write(cio, box.length, 4);  /* L */
1036         cio_seek(cio, box.init_pos + box.length);
1037 }
1038
1039 static opj_bool jp2_read_jp(opj_jp2_t *jp2, opj_cio_t *cio) {
1040         opj_jp2_box_t box;
1041
1042         opj_common_ptr cinfo = jp2->cinfo;
1043
1044   if( jp2_read_boxhdr(cinfo, cio, &box) == OPJ_FALSE ) {
1045     opj_event_msg(cinfo, EVT_ERROR, "Failed to read boxhdr\n");
1046     return OPJ_FALSE;
1047   }
1048         if (JP2_JP != box.type) {
1049                 opj_event_msg(cinfo, EVT_ERROR, "Expected JP Marker\n");
1050                 return OPJ_FALSE;
1051         }
1052         if (0x0d0a870a != cio_read(cio, 4)) {
1053                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Marker\n");
1054                 return OPJ_FALSE;
1055         }
1056         if (cio_tell(cio) - box.init_pos != box.length) {
1057                 opj_event_msg(cinfo, EVT_ERROR, "Error with JP Box size\n");
1058                 return OPJ_FALSE;
1059         }
1060
1061         return OPJ_TRUE;
1062 }
1063
1064
1065 static opj_bool jp2_read_struct(opj_jp2_t *jp2, opj_cio_t *cio,
1066         opj_jp2_color_t *color) {
1067         if (!jp2_read_jp(jp2, cio))
1068                 return OPJ_FALSE;
1069         if (!jp2_read_ftyp(jp2, cio))
1070                 return OPJ_FALSE;
1071         if (!jp2_read_jp2h(jp2, cio, color))
1072                 return OPJ_FALSE;
1073         if (!jp2_read_jp2c(jp2, cio, &jp2->j2k_codestream_length, &jp2->j2k_codestream_offset))
1074                 return OPJ_FALSE;
1075         
1076         return OPJ_TRUE;
1077 }
1078
1079
1080 static int write_fidx( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
1081 {  
1082   int len, lenp;
1083   
1084   lenp = cio_tell( cio);
1085   cio_skip( cio, 4);              /* L [at the end] */
1086   cio_write( cio, JPIP_FIDX, 4);  /* IPTR           */
1087   
1088   write_prxy( offset_jp2c, length_jp2c, offset_idx, length_idx, cio);
1089
1090   len = cio_tell( cio)-lenp;
1091   cio_seek( cio, lenp);
1092   cio_write( cio, len, 4);        /* L              */
1093   cio_seek( cio, lenp+len);  
1094
1095   return len;
1096 }
1097
1098 static void write_prxy( int offset_jp2c, int length_jp2c, int offset_idx, int length_idx, opj_cio_t *cio)
1099 {
1100   int len, lenp;
1101
1102   lenp = cio_tell( cio);
1103   cio_skip( cio, 4);              /* L [at the end] */
1104   cio_write( cio, JPIP_PRXY, 4);  /* IPTR           */
1105   
1106   cio_write( cio, offset_jp2c, 8); /* OOFF           */
1107   cio_write( cio, length_jp2c, 4); /* OBH part 1     */
1108   cio_write( cio, JP2_JP2C, 4);        /* OBH part 2     */
1109   
1110   cio_write( cio, 1,1);           /* NI             */
1111
1112   cio_write( cio, offset_idx, 8);  /* IOFF           */
1113   cio_write( cio, length_idx, 4);  /* IBH part 1     */
1114   cio_write( cio, JPIP_CIDX, 4);   /* IBH part 2     */
1115
1116   len = cio_tell( cio)-lenp;
1117   cio_seek( cio, lenp);
1118   cio_write( cio, len, 4);        /* L              */
1119   cio_seek( cio, lenp+len);
1120 }
1121
1122 static void write_iptr( int offset, int length, opj_cio_t *cio)
1123 {
1124   int len, lenp;
1125   
1126   lenp = cio_tell( cio);
1127   cio_skip( cio, 4);              /* L [at the end] */
1128   cio_write( cio, JPIP_IPTR, 4);  /* IPTR           */
1129   
1130   cio_write( cio, offset, 8);
1131   cio_write( cio, length, 8);
1132
1133   len = cio_tell( cio)-lenp;
1134   cio_seek( cio, lenp);
1135   cio_write( cio, len, 4);        /* L             */
1136   cio_seek( cio, lenp+len);
1137 }
1138
1139
1140 /* ----------------------------------------------------------------------- */
1141 /* JP2 decoder interface                                             */
1142 /* ----------------------------------------------------------------------- */
1143
1144 opj_jp2_t* jp2_create_decompress(opj_common_ptr cinfo) {
1145         opj_jp2_t *jp2 = (opj_jp2_t*) opj_calloc(1, sizeof(opj_jp2_t));
1146         if(jp2) {
1147                 jp2->cinfo = cinfo;
1148                 /* create the J2K codec */
1149                 jp2->j2k = j2k_create_decompress(cinfo);
1150                 if(jp2->j2k == NULL) {
1151                         jp2_destroy_decompress(jp2);
1152                         return NULL;
1153                 }
1154         }
1155         return jp2;
1156 }
1157
1158 void jp2_destroy_decompress(opj_jp2_t *jp2) {
1159         if(jp2) {
1160                 /* destroy the J2K codec */
1161                 j2k_destroy_decompress(jp2->j2k);
1162
1163                 if(jp2->comps) {
1164                         opj_free(jp2->comps);
1165                 }
1166                 if(jp2->cl) {
1167                         opj_free(jp2->cl);
1168                 }
1169                 opj_free(jp2);
1170         }
1171 }
1172
1173 void jp2_setup_decoder(opj_jp2_t *jp2, opj_dparameters_t *parameters) {
1174         /* setup the J2K codec */
1175         j2k_setup_decoder(jp2->j2k, parameters);
1176         /* further JP2 initializations go here */
1177         jp2->ignore_pclr_cmap_cdef = parameters->flags & OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;
1178 }
1179
1180 /* ----------------------------------------------------------------------- */
1181 /* JP2 encoder interface                                             */
1182 /* ----------------------------------------------------------------------- */
1183
1184 opj_jp2_t* jp2_create_compress(opj_common_ptr cinfo) {
1185         opj_jp2_t *jp2 = (opj_jp2_t*)opj_malloc(sizeof(opj_jp2_t));
1186         if(jp2) {
1187                 memset(jp2, 0, sizeof(opj_jp2_t));
1188                 jp2->cinfo = cinfo;
1189                 /* create the J2K codec */
1190                 jp2->j2k = j2k_create_compress(cinfo);
1191                 if(jp2->j2k == NULL) {
1192                         jp2_destroy_compress(jp2);
1193                         return NULL;
1194                 }
1195         }
1196         return jp2;
1197 }
1198
1199 void jp2_destroy_compress(opj_jp2_t *jp2) {
1200         if(jp2) {
1201                 /* destroy the J2K codec */
1202                 j2k_destroy_compress(jp2->j2k);
1203
1204                 if(jp2->comps) {
1205                         opj_free(jp2->comps);
1206                 }
1207                 if(jp2->cl) {
1208                         opj_free(jp2->cl);
1209                 }
1210                 opj_free(jp2);
1211         }
1212 }
1213
1214 void jp2_setup_encoder(opj_jp2_t *jp2, opj_cparameters_t *parameters, opj_image_t *image) {
1215         int i;
1216         int depth_0, sign;
1217
1218         if(!jp2 || !parameters || !image)
1219                 return;
1220
1221         /* setup the J2K codec */
1222         /* ------------------- */
1223
1224         /* Check if number of components respects standard */
1225         if (image->numcomps < 1 || image->numcomps > 16384) {
1226                 opj_event_msg(jp2->cinfo, EVT_ERROR, "Invalid number of components specified while setting up JP2 encoder\n");
1227                 return;
1228         }
1229
1230         j2k_setup_encoder(jp2->j2k, parameters, image);
1231
1232         /* setup the JP2 codec */
1233         /* ------------------- */
1234         
1235         /* Profile box */
1236
1237         jp2->brand = JP2_JP2;   /* BR */
1238         jp2->minversion = 0;    /* MinV */
1239         jp2->numcl = 1;
1240         jp2->cl = (unsigned int*) opj_malloc(jp2->numcl * sizeof(unsigned int));
1241         jp2->cl[0] = JP2_JP2;   /* CL0 : JP2 */
1242
1243         /* Image Header box */
1244
1245         jp2->numcomps = image->numcomps;        /* NC */
1246         jp2->comps = (opj_jp2_comps_t*) opj_malloc(jp2->numcomps * sizeof(opj_jp2_comps_t));
1247         jp2->h = image->y1 - image->y0;         /* HEIGHT */
1248         jp2->w = image->x1 - image->x0;         /* WIDTH */
1249         /* BPC */
1250         depth_0 = image->comps[0].prec - 1;
1251         sign = image->comps[0].sgnd;
1252         jp2->bpc = depth_0 + (sign << 7);
1253         for (i = 1; i < image->numcomps; i++) {
1254                 int depth = image->comps[i].prec - 1;
1255                 sign = image->comps[i].sgnd;
1256                 if (depth_0 != depth)
1257                         jp2->bpc = 255;
1258         }
1259         jp2->C = 7;                     /* C : Always 7 */
1260         jp2->UnkC = 0;          /* UnkC, colorspace specified in colr box */
1261         jp2->IPR = 0;           /* IPR, no intellectual property */
1262         
1263         /* BitsPerComponent box */
1264
1265         for (i = 0; i < image->numcomps; i++) {
1266                 jp2->comps[i].bpcc = image->comps[i].prec - 1 + (image->comps[i].sgnd << 7);
1267         }
1268         jp2->meth = 1;
1269         if (image->color_space == 1)
1270                 jp2->enumcs = 16;       /* sRGB as defined by IEC 61966-2.1 */
1271         else if (image->color_space == 2)
1272                 jp2->enumcs = 17;       /* greyscale */
1273         else if (image->color_space == 3)
1274                 jp2->enumcs = 18;       /* YUV */
1275         jp2->precedence = 0;    /* PRECEDENCE */
1276         jp2->approx = 0;                /* APPROX */
1277         
1278         jp2->jpip_on = parameters->jpip_on;
1279 }
1280
1281 opj_bool opj_jp2_encode(opj_jp2_t *jp2, opj_cio_t *cio, opj_image_t *image, opj_codestream_info_t *cstr_info) {
1282
1283         int pos_iptr, pos_cidx, pos_jp2c, len_jp2c, len_cidx, end_pos, pos_fidx, len_fidx;
1284         pos_jp2c = pos_iptr = -1; /* remove a warning */
1285
1286         /* JP2 encoding */
1287
1288         /* JPEG 2000 Signature box */
1289         jp2_write_jp(cio);
1290         /* File Type box */
1291         jp2_write_ftyp(jp2, cio);
1292         /* JP2 Header box */
1293         jp2_write_jp2h(jp2, cio);
1294
1295         if( jp2->jpip_on){
1296           pos_iptr = cio_tell( cio);
1297           cio_skip( cio, 24); /* IPTR further ! */
1298           
1299           pos_jp2c = cio_tell( cio);
1300         }
1301
1302         /* J2K encoding */
1303         if(!(len_jp2c = jp2_write_jp2c( jp2, cio, image, cstr_info))){
1304             opj_event_msg(jp2->cinfo, EVT_ERROR, "Failed to encode image\n");
1305             return OPJ_FALSE;
1306         }
1307
1308         if( jp2->jpip_on){
1309           pos_cidx = cio_tell( cio);
1310           
1311           len_cidx = write_cidx( pos_jp2c+8, cio, image, *cstr_info, len_jp2c-8);
1312           
1313           pos_fidx = cio_tell( cio);
1314           len_fidx = write_fidx( pos_jp2c, len_jp2c, pos_cidx, len_cidx, cio);
1315           
1316           end_pos = cio_tell( cio);
1317           
1318           cio_seek( cio, pos_iptr);
1319           write_iptr( pos_fidx, len_fidx, cio);
1320           
1321           cio_seek( cio, end_pos);
1322         }
1323
1324         return OPJ_TRUE;
1325 }