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