Reformatage : indent -kr -i2 -ci2 $(find . -name '*.c') $(find . -name '*.h')
[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   int present;
307
308   if (layno == 0) {
309     for (bandno = 0; bandno < res->numbands; bandno++) {
310       tcd_band_t *band = &res->bands[bandno];
311       tcd_precinct_t *prc = &band->precincts[precno];
312       tgt_reset(prc->incltree);
313       tgt_reset(prc->imsbtree);
314       for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
315         tcd_cblk_t *cblk = &prc->cblks[cblkno];
316         cblk->numsegs = 0;
317       }
318     }
319   }
320
321   /* When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
322      This part deal with this caracteristic
323      step 1: Read packet header in the saved structure
324      step 2: (futher) return to codestream for decoding */
325   if (cp->ppm == 1) {           /* PPM */
326     c = cp->ppm_data;
327     bio_init_dec(c, 1000);
328   } else {
329     if (tcp->ppt == 1) {        /* PPT */
330       c = tcp->ppt_data;
331       bio_init_dec(c, 1000);
332     } else {                    /* Normal Case */
333
334       if (tcp->csty & J2K_CP_CSTY_SOP) {
335         if ((*c) != 255 || (*(c + 1) != 145)) {
336           printf("Error : expected SOP marker [1]!!!\n");
337         }
338         c += 6;
339       }
340       bio_init_dec(c, src + len - c);
341     }
342   }
343
344   present = bio_read(1);
345
346   if (!present) {
347     bio_inalign();
348     /* Normal case */
349     c += bio_numbytes();
350     if (tcp->csty & J2K_CP_CSTY_EPH) {
351       if ((*c) != 255 || (*(c + 1) != 146)) {
352         printf("Error : expected EPH marker [1]!!!\n");
353       }
354       c += 2;
355     }
356
357     /* PPT and PPM dealing */
358     if (cp->ppm == 1) {         /* PPM */
359       cp->ppm_data = c;
360       return 0;
361     }
362     if (tcp->ppt == 1) {        /* PPT */
363       tcp->ppt_data = c;
364       return 0;
365     }
366     return c - src;
367   }
368   for (bandno = 0; bandno < res->numbands; bandno++) {
369     tcd_band_t *band = &res->bands[bandno];
370     tcd_precinct_t *prc = &band->precincts[precno];
371     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
372       int included, increment, n;
373       tcd_cblk_t *cblk = &prc->cblks[cblkno];
374       tcd_seg_t *seg;
375       /* if cblk not yet included before --> inclusion tagtree */
376       if (!cblk->numsegs) {
377         included = tgt_decode(prc->incltree, cblkno, layno + 1);
378         /* else one bit */
379       } else {
380         included = bio_read(1);
381       }
382       /* if cblk not included */
383       if (!included) {
384         cblk->numnewpasses = 0;
385         continue;
386       }
387       /* if cblk not yet included --> zero-bitplane tagtree */
388       if (!cblk->numsegs) {
389         int i, numimsbs;
390         for (i = 0; !tgt_decode(prc->imsbtree, cblkno, i); i++) {
391         }
392         numimsbs = i - 1;
393         cblk->numbps = band->numbps - numimsbs;
394         cblk->numlenbits = 3;
395       }
396       /* number of coding passes */
397       cblk->numnewpasses = t2_getnumpasses();
398       increment = t2_getcommacode();
399       /* length indicator increment */
400       cblk->numlenbits += increment;
401       if (!cblk->numsegs) {
402         seg = &cblk->segs[0];
403         t2_init_seg(seg, tcp->tccps[compno].cblksty, 1);
404       } else {
405         seg = &cblk->segs[cblk->numsegs - 1];
406         if (seg->numpasses == seg->maxpasses) {
407           t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);
408         }
409       }
410       n = cblk->numnewpasses;
411
412       do {
413         seg->numnewpasses = int_min(seg->maxpasses - seg->numpasses, n);
414         seg->newlen =
415           bio_read(cblk->numlenbits + int_floorlog2(seg->numnewpasses));
416         n -= seg->numnewpasses;
417         if (n > 0) {
418           t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);
419         }
420       } while (n > 0);
421     }
422   }
423   if (bio_inalign())
424     return -999;
425
426   c += bio_numbytes();
427
428   if (tcp->csty & J2K_CP_CSTY_EPH) {    /* EPH marker */
429     if ((*c) != 255 || (*(c + 1) != 146)) {
430       printf("Error : expected EPH marker [2]!!!\n");
431     }
432     c += 2;
433   }
434
435   /* PPT Step 2 : see above for details */
436   if (cp->ppm == 1) {
437     cp->ppm_data = c;           /* Update pointer */
438
439     c = src;
440     if (tcp->csty & J2K_CP_CSTY_SOP) {
441       if ((*c) != 255 || (*(c + 1) != 145)) {
442         printf("Error : expected SOP marker [2] !!!\n");
443       }
444       c += 6;
445     }
446     bio_init_dec(c, src + len - c);
447   } else {
448     if (tcp->ppt == 1) {
449       tcp->ppt_data = c;        /* Update pointer */
450       c = src;
451       if (tcp->csty & J2K_CP_CSTY_SOP) {        /* SOP marker */
452         if ((*c) != 255 || (*(c + 1) != 145)) {
453           printf("Error : expected SOP marker [2] !!!\n");
454         }
455         c += 6;
456       }
457       bio_init_dec(c, src + len - c);
458
459     }
460   }
461
462   for (bandno = 0; bandno < res->numbands; bandno++) {
463     tcd_band_t *band = &res->bands[bandno];
464     tcd_precinct_t *prc = &band->precincts[precno];
465     for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
466       tcd_cblk_t *cblk = &prc->cblks[cblkno];
467       tcd_seg_t *seg;
468       if (!cblk->numnewpasses)
469         continue;
470       if (!cblk->numsegs) {
471         seg = &cblk->segs[cblk->numsegs++];
472         cblk->len = 0;
473       } else {
474         seg = &cblk->segs[cblk->numsegs - 1];
475         if (seg->numpasses == seg->maxpasses) {
476           seg++;
477           cblk->numsegs++;
478         }
479       }
480       do {
481         if (c + seg->newlen > src + len) {
482           return -999;
483         }
484
485         memcpy(cblk->data + cblk->len, c, seg->newlen);
486         if (seg->numpasses == 0) {
487           seg->data = cblk->data + cblk->len;
488         }
489         c += seg->newlen;
490         cblk->len += seg->newlen;
491         seg->len += seg->newlen;
492         seg->numpasses += seg->numnewpasses;
493         cblk->numnewpasses -= seg->numnewpasses;
494         if (cblk->numnewpasses > 0) {
495           seg++;
496           cblk->numsegs++;
497         }
498       } while (cblk->numnewpasses > 0);
499     }
500   }
501
502   return c - src;
503 }
504
505
506
507 /*
508  * Encode the packets of a tile to a destination buffer
509  *
510  * img        : the source image
511  * cp         : the image coding parameters
512  * tileno     : number of the tile encoded
513  * tile       : the tile for which to write the packets
514  * maxlayers  : maximum number of layers
515  * dest       : the destination buffer
516  * len        : the length of the destination buffer
517  * info_IM    : structure to create an index file
518  */
519 int t2_encode_packets(j2k_image_t * img, j2k_cp_t * cp, int tileno,
520                       tcd_tile_t * tile, int maxlayers,
521                       unsigned char *dest, int len, info_image * info_IM)
522 {
523   unsigned char *c = dest;
524   int e = 0;
525   pi_iterator_t *pi;
526   int pino, compno;
527
528   pi = pi_create(img, cp, tileno);
529
530   for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {
531     while (pi_next(&pi[pino])) {
532       if (pi[pino].layno < maxlayers) {
533         e = t2_encode_packet(tile, &cp->tcps[tileno],
534                              pi[pino].compno, pi[pino].resno,
535                              pi[pino].precno, pi[pino].layno, c,
536                              dest + len - c, info_IM, tileno);
537         if (e == -999) {
538           break;
539         } else
540           c += e;
541         /* INDEX >> */
542         if (info_IM->index_write && info_IM->index_on) {
543           info_tile *info_TL = &info_IM->tile[tileno];
544           info_packet *info_PK = &info_TL->packet[info_IM->num];
545           if (!info_IM->num) {
546             info_PK->start_pos = info_TL->end_header + 1;
547           } else {
548             info_PK->start_pos =
549               info_TL->packet[info_IM->num - 1].end_pos + 1;
550           }
551           info_PK->end_pos = info_PK->start_pos + e - 1;
552
553         }
554         /* << INDEX */
555         if ((info_IM->index_write
556              && cp->tcps[tileno].csty & J2K_CP_CSTY_SOP)
557             || (info_IM->index_write && info_IM->index_on)) {
558           info_IM->num++;
559         }
560       }
561
562     }
563
564     /* FREE space memory taken by pi */
565     for (compno = 0; compno < pi[pino].numcomps; compno++) {
566       free(pi[pino].comps[compno].resolutions);
567     }
568     free(pi[pino].comps);
569   }
570   free(pi[0].include);
571   free(pi);
572   if (e == -999)
573     return e;
574   else
575     return c - dest;
576 }
577
578
579
580 /*
581  * Decode the packets of a tile from a source buffer
582  *
583  * src: the source buffer
584  * len: length of the source buffer
585  * img: destination image
586  * cp: image coding parameters
587  * tileno: number that identifies the tile for which to decode the packets
588  * tile: tile for which to decode the packets
589  */
590 int t2_decode_packets(unsigned char *src, int len, j2k_image_t * img,
591                       j2k_cp_t * cp, int tileno, tcd_tile_t * tile)
592 {
593   unsigned char *c = src;
594   pi_iterator_t *pi;
595   int pino, compno, e = 0;
596   int n = 0;
597
598   pi = pi_create(img, cp, tileno);
599
600   for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {
601     while (pi_next(&pi[pino])) {
602       e = t2_decode_packet(c, src + len - c, tile, cp,
603                            &cp->tcps[tileno], pi[pino].compno,
604                            pi[pino].resno, pi[pino].precno,
605                            pi[pino].layno);
606
607       /* progression in resolution */
608       img->comps[pi[pino].compno].resno_decoded =
609         e > 0 ? int_max(pi[pino].resno,
610                         img->comps[pi[pino].compno].
611                         resno_decoded) : img->comps[pi[pino].
612                                                     compno].resno_decoded;
613       n++;
614
615       if (e == -999) {          /* ADD */
616         break;
617       } else
618         c += e;
619     }
620
621     /* FREE space memory taken by pi */
622     for (compno = 0; compno < pi[pino].numcomps; compno++) {
623       free(pi[pino].comps[compno].resolutions);
624     }
625     free(pi[pino].comps);
626   }
627   free(pi[0].include);
628   free(pi);
629
630   if (e == -999)
631     return e;
632   else
633     return c - src;
634 }