Reformatage : indent -kr $(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,
144                              band->numbps - cblk->numbps);
145             }
146         }
147     }
148
149     bio_init_enc(c, len);
150     bio_write(1, 1);            /* Empty header bit */
151
152     /* Writing Packet header */
153     for (bandno = 0; bandno < res->numbands; bandno++) {
154         tcd_band_t *band = &res->bands[bandno];
155         tcd_precinct_t *prc = &band->precincts[precno];
156         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
157             tcd_cblk_t *cblk = &prc->cblks[cblkno];
158             tcd_layer_t *layer = &cblk->layers[layno];
159             if (!cblk->numpasses && layer->numpasses) {
160                 tgt_setvalue(prc->incltree, cblkno, layno);
161             }
162         }
163         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
164             tcd_cblk_t *cblk = &prc->cblks[cblkno];
165             tcd_layer_t *layer = &cblk->layers[layno];
166             int increment = 0;
167             int nump = 0;
168             int len = 0, passno;
169             /* cblk inclusion bits */
170             if (!cblk->numpasses) {
171                 tgt_encode(prc->incltree, cblkno, layno + 1);
172             } else {
173                 bio_write(layer->numpasses != 0, 1);
174             }
175             /* if cblk not included, go to the next cblk  */
176             if (!layer->numpasses) {
177                 continue;
178             }
179             /* if first instance of cblk --> zero bit-planes information */
180             if (!cblk->numpasses) {
181                 cblk->numlenbits = 3;
182                 tgt_encode(prc->imsbtree, cblkno, 999);
183             }
184             /* number of coding passes included */
185             t2_putnumpasses(layer->numpasses);
186
187             /* computation of the increase of the length indicator and insertion in the header     */
188             for (passno = cblk->numpasses;
189                  passno < cblk->numpasses + layer->numpasses; passno++) {
190                 tcd_pass_t *pass = &cblk->passes[passno];
191                 nump++;
192                 len += pass->len;
193                 if (pass->term
194                     || passno ==
195                     (cblk->numpasses + layer->numpasses) - 1) {
196                     increment =
197                         int_max(increment,
198                                 int_floorlog2(len) + 1 -
199                                 (cblk->numlenbits + int_floorlog2(nump)));
200                     len = 0;
201                     nump = 0;
202                 }
203             }
204             t2_putcommacode(increment);
205             /* computation of the new Length indicator */
206             cblk->numlenbits += increment;
207             /* insertion of the codeword segment length */
208
209             for (passno = cblk->numpasses;
210                  passno < cblk->numpasses + layer->numpasses; passno++) {
211                 tcd_pass_t *pass = &cblk->passes[passno];
212                 nump++;
213                 len += pass->len;
214                 if (pass->term
215                     || passno ==
216                     (cblk->numpasses + layer->numpasses) - 1) {
217                     bio_write(len, cblk->numlenbits + int_floorlog2(nump));
218                     len = 0;
219                     nump = 0;
220                 }
221             }
222         }
223     }
224
225     if (bio_flush())
226         return -999;            /* modified to eliminate longjmp !! */
227
228     c += bio_numbytes();
229
230     /* <EPH 0xff92> */
231     if (tcp->csty & J2K_CP_CSTY_EPH) {
232         eph = (unsigned char *) malloc(2 * sizeof(unsigned char));
233         eph[0] = 255;
234         eph[1] = 146;
235         memcpy(c, eph, 2);
236         free(eph);
237         c += 2;
238     }
239     /* </EPH> */
240
241     /* Writing the packet body */
242
243     for (bandno = 0; bandno < res->numbands; bandno++) {
244         tcd_band_t *band = &res->bands[bandno];
245         tcd_precinct_t *prc = &band->precincts[precno];
246         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
247             tcd_cblk_t *cblk = &prc->cblks[cblkno];
248             tcd_layer_t *layer = &cblk->layers[layno];
249             if (!layer->numpasses) {
250                 continue;
251             }
252             if (c + layer->len > dest + len) {
253                 return -999;
254             }
255
256             memcpy(c, layer->data, layer->len);
257             cblk->numpasses += layer->numpasses;
258             c += layer->len;
259             /* ADD for index Cfr. Marcela --> delta disto by packet */
260             if (info_IM->index_write && info_IM->index_on) {
261                 info_tile *info_TL = &info_IM->tile[tileno];
262                 info_packet *info_PK = &info_TL->packet[info_IM->num];
263                 info_PK->disto += layer->disto;
264                 if (info_IM->D_max < info_PK->disto)
265                     info_IM->D_max = info_PK->disto;
266             }                   /* </ADD> */
267         }
268     }
269     return c - dest;
270 }
271
272 void t2_init_seg(tcd_seg_t * seg, int cblksty, int first)
273 {
274     seg->numpasses = 0;
275     seg->len = 0;
276     if (cblksty & J2K_CCP_CBLKSTY_TERMALL)
277         seg->maxpasses = 1;
278     else if (cblksty & J2K_CCP_CBLKSTY_LAZY) {
279         if (first)
280             seg->maxpasses = 10;
281         else
282             seg->maxpasses = (((seg - 1)->maxpasses == 1)
283                               || ((seg - 1)->maxpasses == 10)) ? 2 : 1;
284     } else
285         seg->maxpasses = 109;
286 }
287
288 /*  
289  * Decode a packet of a tile from a source buffer
290  *
291  * src          : the source buffer
292  * len          : the length of the source buffer
293  * tile         : the tile for which to write the packets
294  * cp           : the image coding parameters
295  * tcp          : the tile coding parameters
296  * compno  : Identity of the packet --> component value
297  * resno      : Identity of the packet --> resolution level value
298  * precno    : Identity of the packet --> precinct value
299  * layno      : Identity of the packet --> quality layer value
300  */
301 int t2_decode_packet(unsigned char *src, int len, tcd_tile_t * tile,
302                      j2k_cp_t * cp, j2k_tcp_t * tcp, int compno, int resno,
303                      int precno, int layno)
304 {
305     int bandno, cblkno;
306     tcd_tilecomp_t *tilec = &tile->comps[compno];
307     tcd_resolution_t *res = &tilec->resolutions[resno];
308     unsigned char *c = src;
309     int present;
310
311     if (layno == 0) {
312         for (bandno = 0; bandno < res->numbands; bandno++) {
313             tcd_band_t *band = &res->bands[bandno];
314             tcd_precinct_t *prc = &band->precincts[precno];
315             tgt_reset(prc->incltree);
316             tgt_reset(prc->imsbtree);
317             for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
318                 tcd_cblk_t *cblk = &prc->cblks[cblkno];
319                 cblk->numsegs = 0;
320             }
321         }
322     }
323
324     /* When the marker PPT/PPM is used the packet header are store in PPT/PPM marker
325        This part deal with this caracteristic
326        step 1: Read packet header in the saved structure
327        step 2: (futher) return to codestream for decoding */
328     if (cp->ppm == 1) {         /* PPM */
329         c = cp->ppm_data;
330         bio_init_dec(c, 1000);
331     } else {
332         if (tcp->ppt == 1) {    /* PPT */
333             c = tcp->ppt_data;
334             bio_init_dec(c, 1000);
335         } else {                /* Normal Case */
336
337             if (tcp->csty & J2K_CP_CSTY_SOP) {
338                 if ((*c) != 255 || (*(c + 1) != 145)) {
339                     printf("Error : expected SOP marker [1]!!!\n");
340                 }
341                 c += 6;
342             }
343             bio_init_dec(c, src + len - c);
344         }
345     }
346
347     present = bio_read(1);
348
349     if (!present) {
350         bio_inalign();
351         /* Normal case */
352         c += bio_numbytes();
353         if (tcp->csty & J2K_CP_CSTY_EPH) {
354             if ((*c) != 255 || (*(c + 1) != 146)) {
355                 printf("Error : expected EPH marker [1]!!!\n");
356             }
357             c += 2;
358         }
359
360         /* PPT and PPM dealing */
361         if (cp->ppm == 1) {     /* PPM */
362             cp->ppm_data = c;
363             return 0;
364         }
365         if (tcp->ppt == 1) {    /* PPT */
366             tcp->ppt_data = c;
367             return 0;
368         }
369         return c - src;
370     }
371     for (bandno = 0; bandno < res->numbands; bandno++) {
372         tcd_band_t *band = &res->bands[bandno];
373         tcd_precinct_t *prc = &band->precincts[precno];
374         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
375             int included, increment, n;
376             tcd_cblk_t *cblk = &prc->cblks[cblkno];
377             tcd_seg_t *seg;
378             /* if cblk not yet included before --> inclusion tagtree */
379             if (!cblk->numsegs) {
380                 included = tgt_decode(prc->incltree, cblkno, layno + 1);
381                 /* else one bit */
382             } else {
383                 included = bio_read(1);
384             }
385             /* if cblk not included */
386             if (!included) {
387                 cblk->numnewpasses = 0;
388                 continue;
389             }
390             /* if cblk not yet included --> zero-bitplane tagtree */
391             if (!cblk->numsegs) {
392                 int i, numimsbs;
393                 for (i = 0; !tgt_decode(prc->imsbtree, cblkno, i); i++) {
394                 }
395                 numimsbs = i - 1;
396                 cblk->numbps = band->numbps - numimsbs;
397                 cblk->numlenbits = 3;
398             }
399             /* number of coding passes */
400             cblk->numnewpasses = t2_getnumpasses();
401             increment = t2_getcommacode();
402             /* length indicator increment */
403             cblk->numlenbits += increment;
404             if (!cblk->numsegs) {
405                 seg = &cblk->segs[0];
406                 t2_init_seg(seg, tcp->tccps[compno].cblksty, 1);
407             } else {
408                 seg = &cblk->segs[cblk->numsegs - 1];
409                 if (seg->numpasses == seg->maxpasses) {
410                     t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);
411                 }
412             }
413             n = cblk->numnewpasses;
414
415             do {
416                 seg->numnewpasses =
417                     int_min(seg->maxpasses - seg->numpasses, n);
418                 seg->newlen =
419                     bio_read(cblk->numlenbits +
420                              int_floorlog2(seg->numnewpasses));
421                 n -= seg->numnewpasses;
422                 if (n > 0) {
423                     t2_init_seg(++seg, tcp->tccps[compno].cblksty, 0);
424                 }
425             } while (n > 0);
426         }
427     }
428     if (bio_inalign())
429         return -999;
430
431     c += bio_numbytes();
432
433     if (tcp->csty & J2K_CP_CSTY_EPH) {  /* EPH marker */
434         if ((*c) != 255 || (*(c + 1) != 146)) {
435             printf("Error : expected EPH marker [2]!!!\n");
436         }
437         c += 2;
438     }
439
440     /* PPT Step 2 : see above for details */
441     if (cp->ppm == 1) {
442         cp->ppm_data = c;       /* Update pointer */
443
444         c = src;
445         if (tcp->csty & J2K_CP_CSTY_SOP) {
446             if ((*c) != 255 || (*(c + 1) != 145)) {
447                 printf("Error : expected SOP marker [2] !!!\n");
448             }
449             c += 6;
450         }
451         bio_init_dec(c, src + len - c);
452     } else {
453         if (tcp->ppt == 1) {
454             tcp->ppt_data = c;  /* Update pointer */
455             c = src;
456             if (tcp->csty & J2K_CP_CSTY_SOP) {  /* SOP marker */
457                 if ((*c) != 255 || (*(c + 1) != 145)) {
458                     printf("Error : expected SOP marker [2] !!!\n");
459                 }
460                 c += 6;
461             }
462             bio_init_dec(c, src + len - c);
463
464         }
465     }
466
467     for (bandno = 0; bandno < res->numbands; bandno++) {
468         tcd_band_t *band = &res->bands[bandno];
469         tcd_precinct_t *prc = &band->precincts[precno];
470         for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
471             tcd_cblk_t *cblk = &prc->cblks[cblkno];
472             tcd_seg_t *seg;
473             if (!cblk->numnewpasses)
474                 continue;
475             if (!cblk->numsegs) {
476                 seg = &cblk->segs[cblk->numsegs++];
477                 cblk->len = 0;
478             } else {
479                 seg = &cblk->segs[cblk->numsegs - 1];
480                 if (seg->numpasses == seg->maxpasses) {
481                     seg++;
482                     cblk->numsegs++;
483                 }
484             }
485             do {
486                 if (c + seg->newlen > src + len) {
487                     return -999;
488                 }
489
490                 memcpy(cblk->data + cblk->len, c, seg->newlen);
491                 if (seg->numpasses == 0) {
492                     seg->data = cblk->data + cblk->len;
493                 }
494                 c += seg->newlen;
495                 cblk->len += seg->newlen;
496                 seg->len += seg->newlen;
497                 seg->numpasses += seg->numnewpasses;
498                 cblk->numnewpasses -= seg->numnewpasses;
499                 if (cblk->numnewpasses > 0) {
500                     seg++;
501                     cblk->numsegs++;
502                 }
503             } while (cblk->numnewpasses > 0);
504         }
505     }
506
507     return c - src;
508 }
509
510
511
512 /*
513  * Encode the packets of a tile to a destination buffer
514  *
515  * img        : the source image
516  * cp         : the image coding parameters
517  * tileno     : number of the tile encoded
518  * tile       : the tile for which to write the packets
519  * maxlayers  : maximum number of layers
520  * dest       : the destination buffer
521  * len        : the length of the destination buffer
522  * info_IM    : structure to create an index file
523  */
524 int t2_encode_packets(j2k_image_t * img, j2k_cp_t * cp, int tileno,
525                       tcd_tile_t * tile, int maxlayers,
526                       unsigned char *dest, int len, info_image * info_IM)
527 {
528     unsigned char *c = dest;
529     int e = 0;
530     pi_iterator_t *pi;
531     int pino, compno;
532
533     pi = pi_create(img, cp, tileno);
534
535     for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {
536         while (pi_next(&pi[pino])) {
537             if (pi[pino].layno < maxlayers) {
538                 e = t2_encode_packet(tile, &cp->tcps[tileno],
539                                      pi[pino].compno, pi[pino].resno,
540                                      pi[pino].precno, pi[pino].layno, c,
541                                      dest + len - c, info_IM, tileno);
542                 if (e == -999) {
543                     break;
544                 } else
545                     c += e;
546                 /* INDEX >> */
547                 if (info_IM->index_write && info_IM->index_on) {
548                     info_tile *info_TL = &info_IM->tile[tileno];
549                     info_packet *info_PK = &info_TL->packet[info_IM->num];
550                     if (!info_IM->num) {
551                         info_PK->start_pos = info_TL->end_header + 1;
552                     } else {
553                         info_PK->start_pos =
554                             info_TL->packet[info_IM->num - 1].end_pos + 1;
555                     }
556                     info_PK->end_pos = info_PK->start_pos + e - 1;
557
558                 }
559                 /* << INDEX */
560                 if ((info_IM->index_write
561                      && cp->tcps[tileno].csty & J2K_CP_CSTY_SOP)
562                     || (info_IM->index_write && info_IM->index_on)) {
563                     info_IM->num++;
564                 }
565             }
566
567         }
568
569         /* FREE space memory taken by pi */
570         for (compno = 0; compno < pi[pino].numcomps; compno++) {
571             free(pi[pino].comps[compno].resolutions);
572         }
573         free(pi[pino].comps);
574     }
575     free(pi[0].include);
576     free(pi);
577     if (e == -999)
578         return e;
579     else
580         return c - dest;
581 }
582
583
584
585 /*
586  * Decode the packets of a tile from a source buffer
587  *
588  * src: the source buffer
589  * len: length of the source buffer
590  * img: destination image
591  * cp: image coding parameters
592  * tileno: number that identifies the tile for which to decode the packets
593  * tile: tile for which to decode the packets
594  */
595 int t2_decode_packets(unsigned char *src, int len, j2k_image_t * img,
596                       j2k_cp_t * cp, int tileno, tcd_tile_t * tile)
597 {
598     unsigned char *c = src;
599     pi_iterator_t *pi;
600     int pino, compno, e = 0;
601     int n = 0;
602
603     pi = pi_create(img, cp, tileno);
604
605     for (pino = 0; pino <= cp->tcps[tileno].numpocs; pino++) {
606         while (pi_next(&pi[pino])) {
607             e = t2_decode_packet(c, src + len - c, tile, cp,
608                                  &cp->tcps[tileno], pi[pino].compno,
609                                  pi[pino].resno, pi[pino].precno,
610                                  pi[pino].layno);
611
612             /* progression in resolution */
613             img->comps[pi[pino].compno].resno_decoded =
614                 e > 0 ? int_max(pi[pino].resno,
615                                 img->comps[pi[pino].compno].
616                                 resno_decoded) : img->comps[pi[pino].
617                                                             compno].
618                 resno_decoded;
619             n++;
620
621             if (e == -999) {    /* ADD */
622                 break;
623             } else
624                 c += e;
625         }
626
627         /* FREE space memory taken by pi */
628         for (compno = 0; compno < pi[pino].numcomps; compno++) {
629             free(pi[pino].comps[compno].resolutions);
630         }
631         free(pi[pino].comps);
632     }
633     free(pi[0].include);
634     free(pi);
635
636     if (e == -999)
637         return e;
638     else
639         return c - src;
640 }