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