Conversions from int to unsigned int to ensure correct execution of int_min at line...
[openjpeg.git] / libopenjpeg / t2.c
1 /*
2  * Copyright (c) 2001-2002, David Janssens
3  * Copyright (c) 2002-2004, Yannick Verschueren
4  * Copyright (c) 2002-2004, Communications and remote sensing Laboratory, Universite catholique de Louvain, Belgium
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include "t2.h"
30 #include "tcd.h"
31 #include "bio.h"
32 #include "j2k.h"
33 #include "pi.h"
34 #include "tgt.h"
35 #include "int.h"
36 #include "cio.h"
37 #include <stdio.h>
38 #include <setjmp.h>
39 #include <string.h>
40 #include <stdlib.h>
41
42 #define RESTART 0x04
43
44 extern jmp_buf j2k_error;
45
46 void t2_putcommacode(int n)
47 {
48   while (--n >= 0) {
49     bio_write(1, 1);
50   }
51   bio_write(0, 1);
52 }
53
54 int t2_getcommacode()
55 {
56   int n;
57   for (n = 0; bio_read(1); n++) {
58   }
59   return n;
60 }
61
62 /* <summary> */
63 /* Variable length code for signalling delta Zil (truncation point) */
64 /* <val> n : delta Zil */
65 /* <\summary> */
66 void t2_putnumpasses(int n)
67 {
68   if (n == 1) {
69     bio_write(0, 1);
70   } else if (n == 2) {
71     bio_write(2, 2);
72   } else if (n <= 5) {
73     bio_write(0xc | (n - 3), 4);
74   } else if (n <= 36) {
75     bio_write(0x1e0 | (n - 6), 9);
76   } else if (n <= 164) {
77     bio_write(0xff80 | (n - 37), 16);
78   }
79 }
80
81 int t2_getnumpasses()
82 {
83   int n;
84   if (!bio_read(1))
85     return 1;
86   if (!bio_read(1))
87     return 2;
88   if ((n = bio_read(2)) != 3)
89     return 3 + n;
90   if ((n = bio_read(5)) != 31)
91     return 6 + n;
92   return 37 + bio_read(7);
93 }
94
95 /*
96  * Encode a packet of a tile to a destination buffer
97  *
98  * Tile    : the tile for which to write the packets
99  * tcp     : the tile coding parameters
100  * compno  : Identity of the packet --> component value
101  * resno   : Identity of the packet --> resolution level value
102  * precno  : Identity of the packet --> precinct value
103  * layno   : Identity of the packet --> quality layer value
104  * dest    : the destination buffer
105  * len     : the length of the destination buffer
106  * info_IM : structure to create an index file
107  * tileno  : number of the tile encoded
108 */
109 int t2_encode_packet(tcd_tile_t * tile, j2k_tcp_t * tcp, int compno,
110                      int resno, int precno, int layno, unsigned char *dest,
111                      int len, info_image * info_IM, int tileno)
112 {
113   int bandno, cblkno;
114   unsigned char *sop = 0, *eph = 0;
115   tcd_tilecomp_t *tilec = &tile->comps[compno];
116   tcd_resolution_t *res = &tilec->resolutions[resno];
117   unsigned char *c = dest;
118
119   /* <SOP 0xff91> */
120   if (tcp->csty & J2K_CP_CSTY_SOP) {
121     sop = (unsigned char *) malloc(6 * sizeof(unsigned char));
122     sop[0] = 255;
123     sop[1] = 145;
124     sop[2] = 0;
125     sop[3] = 4;
126     sop[4] = (info_IM->num % 65536) / 256;
127     sop[5] = (info_IM->num % 65536) % 256;
128     memcpy(c, sop, 6);
129     free(sop);
130     c += 6;
131   }
132   /* </SOP> */
133
134   if (!layno) {
135     for (bandno = 0; bandno < res->numbands; bandno++) {
136       tcd_band_t *band = &res->bands[bandno];
137       tcd_precinct_t *prc = &band->precincts[precno];
138       tgt_reset(prc->incltree);
139       tgt_reset(prc->imsbtree);
140       for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
141         tcd_cblk_t *cblk = &prc->cblks[cblkno];
142         cblk->numpasses = 0;
143         tgt_setvalue(prc->imsbtree, cblkno, band->numbps - cblk->numbps);
144       }
145     }
146   }
147
148   bio_init_enc(c, len);
149   bio_write(1, 1);              /* Empty header bit */
150
151   /* Writing Packet header */
152   for (bandno = 0; bandno < res->numbands; bandno++) {
153     tcd_band_t *band = &res->bands[bandno];
154     tcd_precinct_t *prc = &band->precincts[precno];
155     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
156       tcd_cblk_t *cblk = &prc->cblks[cblkno];
157       tcd_layer_t *layer = &cblk->layers[layno];
158       if (!cblk->numpasses && layer->numpasses) {
159         tgt_setvalue(prc->incltree, cblkno, layno);
160       }
161     }
162     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
163       tcd_cblk_t *cblk = &prc->cblks[cblkno];
164       tcd_layer_t *layer = &cblk->layers[layno];
165       int increment = 0;
166       int nump = 0;
167       int len = 0, passno;
168       /* cblk inclusion bits */
169       if (!cblk->numpasses) {
170         tgt_encode(prc->incltree, cblkno, layno + 1);
171       } else {
172         bio_write(layer->numpasses != 0, 1);
173       }
174       /* if cblk not included, go to the next cblk  */
175       if (!layer->numpasses) {
176         continue;
177       }
178       /* if first instance of cblk --> zero bit-planes information */
179       if (!cblk->numpasses) {
180         cblk->numlenbits = 3;
181         tgt_encode(prc->imsbtree, cblkno, 999);
182       }
183       /* number of coding passes included */
184       t2_putnumpasses(layer->numpasses);
185
186       /* computation of the increase of the length indicator and insertion in the header     */
187       for (passno = cblk->numpasses;
188            passno < cblk->numpasses + layer->numpasses; passno++) {
189         tcd_pass_t *pass = &cblk->passes[passno];
190         nump++;
191         len += pass->len;
192         if (pass->term
193             || passno == (cblk->numpasses + layer->numpasses) - 1) {
194           increment =
195             int_max(increment,
196                     int_floorlog2(len) + 1 -
197                     (cblk->numlenbits + int_floorlog2(nump)));
198           len = 0;
199           nump = 0;
200         }
201       }
202       t2_putcommacode(increment);
203       /* computation of the new Length indicator */
204       cblk->numlenbits += increment;
205       /* insertion of the codeword segment length */
206
207       for (passno = cblk->numpasses;
208            passno < cblk->numpasses + layer->numpasses; passno++) {
209         tcd_pass_t *pass = &cblk->passes[passno];
210         nump++;
211         len += pass->len;
212         if (pass->term
213             || passno == (cblk->numpasses + layer->numpasses) - 1) {
214           bio_write(len, cblk->numlenbits + int_floorlog2(nump));
215           len = 0;
216           nump = 0;
217         }
218       }
219     }
220   }
221
222   if (bio_flush())
223     return -999;                /* modified to eliminate longjmp !! */
224
225   c += bio_numbytes();
226
227   /* <EPH 0xff92> */
228   if (tcp->csty & J2K_CP_CSTY_EPH) {
229     eph = (unsigned char *) malloc(2 * sizeof(unsigned char));
230     eph[0] = 255;
231     eph[1] = 146;
232     memcpy(c, eph, 2);
233     free(eph);
234     c += 2;
235   }
236   /* </EPH> */
237
238   /* Writing the packet body */
239
240   for (bandno = 0; bandno < res->numbands; bandno++) {
241     tcd_band_t *band = &res->bands[bandno];
242     tcd_precinct_t *prc = &band->precincts[precno];
243     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
244       tcd_cblk_t *cblk = &prc->cblks[cblkno];
245       tcd_layer_t *layer = &cblk->layers[layno];
246       if (!layer->numpasses) {
247         continue;
248       }
249       if (c + layer->len > dest + len) {
250         return -999;
251       }
252
253       memcpy(c, layer->data, layer->len);
254       cblk->numpasses += layer->numpasses;
255       c += layer->len;
256       /* ADD for index Cfr. Marcela --> delta disto by packet */
257       if (info_IM->index_write && info_IM->index_on) {
258         info_tile *info_TL = &info_IM->tile[tileno];
259         info_packet *info_PK = &info_TL->packet[info_IM->num];
260         info_PK->disto += layer->disto;
261         if (info_IM->D_max < info_PK->disto)
262           info_IM->D_max = info_PK->disto;
263       }                         /* </ADD> */
264     }
265   }
266   return c - dest;
267 }
268
269 void t2_init_seg(tcd_seg_t * seg, int cblksty, int first)
270 {
271   seg->numpasses = 0;
272   seg->len = 0;
273   if (cblksty & J2K_CCP_CBLKSTY_TERMALL)
274     seg->maxpasses = 1;
275   else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
276     if (first)
277       seg->maxpasses = 10;
278     else
279       seg->maxpasses = (((seg - 1)->maxpasses == 1)
280                         || ((seg - 1)->maxpasses == 10)) ? 2 : 1;
281   } else
282     seg->maxpasses = 109;
283 }
284
285 /*  
286  * Decode a packet of a tile from a source buffer
287  *
288  * src          : the source buffer
289  * len          : the length of the source buffer
290  * tile         : the tile for which to write the packets
291  * cp           : the image coding parameters
292  * tcp          : the tile coding parameters
293  * compno  : Identity of the packet --> component value
294  * resno      : Identity of the packet --> resolution level value
295  * precno    : Identity of the packet --> precinct value
296  * layno      : Identity of the packet --> quality layer value
297  */
298 int t2_decode_packet(unsigned char *src, int len, tcd_tile_t * tile,
299                      j2k_cp_t * cp, j2k_tcp_t * tcp, int compno, int resno,
300                      int precno, int layno)
301 {
302   int bandno, cblkno;
303   tcd_tilecomp_t *tilec = &tile->comps[compno];
304   tcd_resolution_t *res = &tilec->resolutions[resno];
305   unsigned char *c = src;
306
307   unsigned char *hd = NULL;
308   int present;
309
310   if (layno == 0) {
311     for (bandno = 0; bandno < res->numbands; bandno++) {
312       tcd_band_t *band = &res->bands[bandno];
313       tcd_precinct_t *prc = &band->precincts[precno];
314
315       
316
317       //Add Antonin : sizebug1
318
319       if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue;
320
321       //ddA
322
323       
324       tgt_reset(prc->incltree);
325       tgt_reset(prc->imsbtree);
326       for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
327         tcd_cblk_t *cblk = &prc->cblks[cblkno];
328         cblk->numsegs = 0;
329       }
330     }
331   }
332
333   
334
335   // SOP markers
336
337   if (tcp->csty & J2K_CP_CSTY_SOP) {
338
339     if ((*c) != 0xff || (*(c + 1) != 0x91)) {
340
341       fprintf(stderr,"Warning : expected SOP marker\n");
342
343     } else {
344
345       c += 6;
346
347     }
348
349     //TODO : check the Nsop value
350
351   }
352
353   /* When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
354   This part deal with this caracteristic
355   step 1: Read packet header in the saved structure
356   step 2: Return to codestream for decoding */
357
358
359   if (cp->ppm == 1) {           /* PPM */
360     hd = cp->ppm_data;
361     bio_init_dec(hd, cp->ppm_len); //Mod Antonin : ppmbug1
362   } else if (tcp->ppt == 1) {   /* PPT */
363     hd = tcp->ppt_data;
364     bio_init_dec(hd, tcp->ppt_len);  //Mod Antonin : ppmbug1
365   } else {                      /* Normal Case */
366
367     hd = c;
368
369     bio_init_dec(hd, src+len-hd);
370
371   }
372   
373   present = bio_read(1);
374
375   if (!present) {
376     bio_inalign();
377
378     hd += bio_numbytes();
379
380
381
382     // EPH markers
383
384     if (tcp->csty & J2K_CP_CSTY_EPH) {
385
386       if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {
387
388         printf("Error : expected EPH marker\n");
389
390       } else {
391
392         hd += 2;
393
394       }
395
396     }
397
398     if (cp->ppm == 1) {         /* PPM case */
399
400       cp->ppm_len+=cp->ppm_data-hd;
401       cp->ppm_data = hd;
402       return c - src;
403     }
404     if (tcp->ppt == 1) {        /* PPT case */
405
406       tcp->ppt_len+=tcp->ppt_data-hd;
407       tcp->ppt_data = hd;
408       return c - src;
409     }
410
411
412     return hd - src;
413   }
414
415
416   for (bandno = 0; bandno < res->numbands; bandno++) {
417     tcd_band_t *band = &res->bands[bandno];
418     tcd_precinct_t *prc = &band->precincts[precno];
419
420
421
422     //Add Antonin : sizebug1
423
424     if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue;
425
426     //ddA
427
428
429     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
430       int included, increment, n;
431       tcd_cblk_t *cblk = &prc->cblks[cblkno];
432       tcd_seg_t *seg;
433       /* if cblk not yet included before --> inclusion tagtree */
434       if (!cblk->numsegs) {
435         included = tgt_decode(prc->incltree, cblkno, layno + 1);
436         /* else one bit */
437       } else {
438         included = bio_read(1);
439       }
440       /* if cblk not included */
441       if (!included) {
442         cblk->numnewpasses = 0;
443         continue;
444       }
445       /* if cblk not yet included --> zero-bitplane tagtree */
446       if (!cblk->numsegs) {
447         int i, numimsbs;
448         for (i = 0; !tgt_decode(prc->imsbtree, cblkno, i); i++) {
449         }
450         numimsbs = i - 1;
451         cblk->numbps = band->numbps - numimsbs;
452         cblk->numlenbits = 3;
453       }
454       /* number of coding passes */
455       cblk->numnewpasses = t2_getnumpasses();
456       increment = t2_getcommacode();
457       /* length indicator increment */
458       cblk->numlenbits += increment;
459       if (!cblk->numsegs) {
460         seg = &cblk->segs[0];
461         t2_init_seg(seg, tcp->tccps[compno].cblksty, 1);
462       } else {
463         seg = &cblk->segs[cblk->numsegs - 1];
464         if (seg->numpasses == seg->maxpasses) {
465           t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);
466         }
467       }
468       n = cblk->numnewpasses;
469
470       do {
471         seg->numnewpasses = int_min(seg->maxpasses - seg->numpasses, n);
472         seg->newlen =
473           bio_read(cblk->numlenbits + int_floorlog2(seg->numnewpasses));
474         n -= seg->numnewpasses;
475         if (n > 0) {
476           t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);
477         }
478       } while (n > 0);
479     }
480   }
481   if (bio_inalign())
482     return -999;
483
484   hd += bio_numbytes();
485
486
487   // EPH markers
488   if (tcp->csty & J2K_CP_CSTY_EPH) {
489     if ((*hd) != 0xff || (*(hd + 1) != 0x92)) {
490       fprintf(stderr,"Error : expected EPH marker\n");
491     } else {
492       hd += 2;
493
494     }
495   }
496
497
498
499   if (cp->ppm==1) {
500
501     cp->ppm_len+=cp->ppm_data-hd;
502
503     cp->ppm_data = hd;
504
505   } else if (tcp->ppt == 1) {
506
507     tcp->ppt_len+=tcp->ppt_data-hd;
508
509     tcp->ppt_data = hd;
510
511   } else {
512
513     c=hd;
514
515   }
516
517   for (bandno = 0; bandno < res->numbands; bandno++) {
518     tcd_band_t *band = &res->bands[bandno];
519     tcd_precinct_t *prc = &band->precincts[precno];
520
521
522
523     //Add Antonin : sizebug1
524
525     if ((band->x1-band->x0 == 0)||(band->y1-band->y0 == 0)) continue;
526
527     //ddA
528
529
530     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
531       tcd_cblk_t *cblk = &prc->cblks[cblkno];
532       tcd_seg_t *seg;
533       if (!cblk->numnewpasses)
534         continue;
535       if (!cblk->numsegs) {
536         seg = &cblk->segs[0];
537
538         cblk->numsegs++;
539         cblk->len = 0;
540       } else {
541         seg = &cblk->segs[cblk->numsegs - 1];
542         if (seg->numpasses == seg->maxpasses) {
543           seg++;
544           cblk->numsegs++;
545         }
546       }
547       do {
548         if (c + seg->newlen > src + len) {
549           return -999;
550         }
551
552         memcpy(cblk->data + cblk->len, c, seg->newlen);
553         if (seg->numpasses == 0) {
554           seg->data = cblk->data + cblk->len;
555         }
556         c += seg->newlen;
557         cblk->len += seg->newlen;
558         seg->len += seg->newlen;
559         seg->numpasses += seg->numnewpasses;
560         cblk->numnewpasses -= seg->numnewpasses;
561         if (cblk->numnewpasses > 0) {
562           seg++;
563           cblk->numsegs++;
564         }
565       } while (cblk->numnewpasses > 0);
566     }
567   }
568
569   return c - src;
570 }
571
572
573
574 /*
575  * Encode the packets of a tile to a destination buffer
576  *
577  * img        : the source image
578  * cp         : the image coding parameters
579  * tileno     : number of the tile encoded
580  * tile       : the tile for which to write the packets
581  * maxlayers  : maximum number of layers
582  * dest       : the destination buffer
583  * len        : the length of the destination buffer
584  * info_IM    : structure to create an index file
585  */
586 int t2_encode_packets(j2k_image_t * img, j2k_cp_t * cp, int tileno,
587                       tcd_tile_t * tile, int maxlayers,
588                       unsigned char *dest, int len, info_image * info_IM)
589 {
590   unsigned char *c = dest;
591   int e = 0;
592   pi_iterator_t *pi;
593   int pino, compno;
594
595   pi = pi_create(img, cp, tileno);
596
597   for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {
598     while (pi_next(&pi[pino])) {
599       if (pi[pino].layno < maxlayers) {
600         e = t2_encode_packet(tile, &cp->tcps[tileno],
601                              pi[pino].compno, pi[pino].resno,
602                              pi[pino].precno, pi[pino].layno, c,
603                              dest + len - c, info_IM, tileno);
604         if (e == -999) {
605           break;
606         } else
607           c += e;
608         /* INDEX >> */
609         if (info_IM->index_write && info_IM->index_on) {
610           info_tile *info_TL = &info_IM->tile[tileno];
611           info_packet *info_PK = &info_TL->packet[info_IM->num];
612           if (!info_IM->num) {
613             info_PK->start_pos = info_TL->end_header + 1;
614           } else {
615             info_PK->start_pos =
616               info_TL->packet[info_IM->num - 1].end_pos + 1;
617           }
618           info_PK->end_pos = info_PK->start_pos + e - 1;
619
620         }
621         /* << INDEX */
622         if ((info_IM->index_write
623              && cp->tcps[tileno].csty & J2K_CP_CSTY_SOP)
624             || (info_IM->index_write && info_IM->index_on)) {
625           info_IM->num++;
626         }
627       }
628
629     }
630
631     /* FREE space memory taken by pi */
632     for (compno = 0; compno < pi[pino].numcomps; compno++) {
633       free(pi[pino].comps[compno].resolutions);
634     }
635     free(pi[pino].comps);
636   }
637   free(pi[0].include);
638   free(pi);
639   if (e == -999)
640     return e;
641   else
642     return c - dest;
643 }
644
645
646
647 /*
648  * Decode the packets of a tile from a source buffer
649  *
650  * src: the source buffer
651  * len: length of the source buffer
652  * img: destination image
653  * cp: image coding parameters
654  * tileno: number that identifies the tile for which to decode the packets
655  * tile: tile for which to decode the packets
656  */
657 int t2_decode_packets(unsigned char *src, int len, j2k_image_t * img,
658                       j2k_cp_t * cp, int tileno, tcd_tile_t * tile)
659 {
660   unsigned char *c = src;
661   pi_iterator_t *pi;
662   int pino, compno, e = 0;
663   int n = 0;
664
665   pi = pi_create(img, cp, tileno);
666
667   for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {
668     while (pi_next(&pi[pino])) {
669       
670       if ((cp->layer==0) || (cp->layer>=((pi[pino].layno)+1))) {
671         e = t2_decode_packet(c, src + len - c, tile, cp,
672           &cp->tcps[tileno], pi[pino].compno,
673           pi[pino].resno, pi[pino].precno,
674           pi[pino].layno);
675       } else {
676         e = 0;
677       }
678       
679       /* progression in resolution */
680       img->comps[pi[pino].compno].resno_decoded =
681         e > 0 ? int_max(pi[pino].resno,
682         img->comps[pi[pino].compno].
683         resno_decoded) : img->comps[pi[pino].
684         compno].resno_decoded;
685       n++;
686       
687       if (e == -999) {          /* ADD */
688         break;
689       } else {
690         c += e;
691       }
692     }
693
694     /* FREE space memory taken by pi */
695     for (compno = 0; compno < pi[pino].numcomps; compno++) {
696       free(pi[pino].comps[compno].resolutions);
697     }
698     free(pi[pino].comps);
699   }
700   free(pi[0].include);
701   free(pi);
702
703   if (e == -999)
704     return e;
705   else
706     return c - src;
707 }