1/*
2 * Copyright (c) 1999-2000 Image Power, Inc. and the University of
3 *   British Columbia.
4 * Copyright (c) 2001-2003 Michael David Adams.
5 * All rights reserved.
6 */
7
8/* __START_OF_JASPER_LICENSE__
9 *
10 * JasPer License Version 2.0
11 *
12 * Copyright (c) 2001-2006 Michael David Adams
13 * Copyright (c) 1999-2000 Image Power, Inc.
14 * Copyright (c) 1999-2000 The University of British Columbia
15 *
16 * All rights reserved.
17 *
18 * Permission is hereby granted, free of charge, to any person (the
19 * "User") obtaining a copy of this software and associated documentation
20 * files (the "Software"), to deal in the Software without restriction,
21 * including without limitation the rights to use, copy, modify, merge,
22 * publish, distribute, and/or sell copies of the Software, and to permit
23 * persons to whom the Software is furnished to do so, subject to the
24 * following conditions:
25 *
26 * 1.  The above copyright notices and this permission notice (which
27 * includes the disclaimer below) shall be included in all copies or
28 * substantial portions of the Software.
29 *
30 * 2.  The name of a copyright holder shall not be used to endorse or
31 * promote products derived from the Software without specific prior
32 * written permission.
33 *
34 * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
35 * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
36 * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
37 * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
38 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
39 * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.  IN NO
40 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
41 * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
42 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
43 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
44 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
45 * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
46 * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
47 * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
48 * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
49 * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
50 * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
51 * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
52 * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
53 * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
54 * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
55 * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
56 * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
57 * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
58 * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
59 * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
60 *
61 * __END_OF_JASPER_LICENSE__
62 */
63
64/*
65 * Tier 2 Decoder
66 *
67 * $Id: jpc_t2dec.c,v 1.2 2008-05-26 09:40:52 vp153 Exp $
68 */
69
70/******************************************************************************\
71* Includes.
72\******************************************************************************/
73
74#include <stdio.h>
75#include <stdlib.h>
76#include <assert.h>
77
78#include "jasper/jas_types.h"
79#include "jasper/jas_fix.h"
80#include "jasper/jas_malloc.h"
81#include "jasper/jas_math.h"
82#include "jasper/jas_stream.h"
83#include "jasper/jas_debug.h"
84
85#include "jpc_bs.h"
86#include "jpc_dec.h"
87#include "jpc_cs.h"
88#include "jpc_mqdec.h"
89#include "jpc_t2dec.h"
90#include "jpc_t1cod.h"
91#include "jpc_math.h"
92
93/******************************************************************************\
94*
95\******************************************************************************/
96
97long jpc_dec_lookahead(jas_stream_t *in);
98static int jpc_getcommacode(jpc_bitstream_t *in);
99static int jpc_getnumnewpasses(jpc_bitstream_t *in);
100static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int lvlno,
101  int prcno, int lyrno);
102
103/******************************************************************************\
104* Code.
105\******************************************************************************/
106
107static int jpc_getcommacode(jpc_bitstream_t *in)
108{
109    int n;
110    int v;
111
112    n = 0;
113    for (;;) {
114        if ((v = jpc_bitstream_getbit(in)) < 0) {
115            return -1;
116        }
117        if (jpc_bitstream_eof(in)) {
118            return -1;
119        }
120        if (!v) {
121            break;
122        }
123        ++n;
124    }
125
126    return n;
127}
128
129static int jpc_getnumnewpasses(jpc_bitstream_t *in)
130{
131    int n;
132
133    if ((n = jpc_bitstream_getbit(in)) > 0) {
134        if ((n = jpc_bitstream_getbit(in)) > 0) {
135            if ((n = jpc_bitstream_getbits(in, 2)) == 3) {
136                if ((n = jpc_bitstream_getbits(in, 5)) == 31) {
137                    if ((n = jpc_bitstream_getbits(in, 7)) >= 0) {
138                        n += 36 + 1;
139                    }
140                } else if (n >= 0) {
141                    n += 5 + 1;
142                }
143            } else if (n >= 0) {
144                n += 2 + 1;
145            }
146        } else if (!n) {
147            n += 2;
148        }
149    } else if (!n) {
150        ++n;
151    }
152
153    return n;
154}
155
156static int jpc_dec_decodepkt(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in, int compno, int rlvlno,
157  int prcno, int lyrno)
158{
159    jpc_bitstream_t *inb;
160    jpc_dec_tcomp_t *tcomp;
161    jpc_dec_rlvl_t *rlvl;
162    jpc_dec_band_t *band;
163    jpc_dec_cblk_t *cblk;
164    int n;
165    int m;
166    int i;
167    jpc_tagtreenode_t *leaf;
168    int included;
169    int ret;
170    int numnewpasses;
171    jpc_dec_seg_t *seg;
172    int len;
173    int present;
174    int savenumnewpasses;
175    int mycounter;
176    jpc_ms_t *ms;
177    jpc_dec_tile_t *tile;
178    jpc_dec_ccp_t *ccp;
179    jpc_dec_cp_t *cp;
180    int bandno;
181    jpc_dec_prc_t *prc;
182    int usedcblkcnt;
183    int cblkno;
184    uint_fast32_t bodylen;
185    bool discard;
186    int passno;
187    int maxpasses;
188    int hdrlen;
189    int hdroffstart;
190    int hdroffend;
191
192    /* Avoid compiler warning about possible use of uninitialized
193      variable. */
194    bodylen = 0;
195
196    discard = (lyrno >= dec->maxlyrs);
197
198    tile = dec->curtile;
199    cp = tile->cp;
200    ccp = &cp->ccps[compno];
201
202    /*
203     * Decode the packet header.
204     */
205
206    /* Decode the SOP marker segment if present. */
207    if (cp->csty & JPC_COD_SOP) {
208        if (jpc_dec_lookahead(in) == JPC_MS_SOP) {
209            if (!(ms = jpc_getms(in, dec->cstate))) {
210                return -1;
211            }
212            if (jpc_ms_gettype(ms) != JPC_MS_SOP) {
213                jpc_ms_destroy(ms);
214                jas_eprintf("missing SOP marker segment\n");
215                return -1;
216            }
217            jpc_ms_destroy(ms);
218        }
219    }
220
221hdroffstart = jas_stream_getrwcount(pkthdrstream);
222
223    if (!(inb = jpc_bitstream_sopen(pkthdrstream, "r"))) {
224        return -1;
225    }
226
227    if ((present = jpc_bitstream_getbit(inb)) < 0) {
228        return 1;
229    }
230    JAS_DBGLOG(10, ("\n", present));
231    JAS_DBGLOG(10, ("present=%d ", present));
232
233    /* Is the packet non-empty? */
234    if (present) {
235        /* The packet is non-empty. */
236        tcomp = &tile->tcomps[compno];
237        rlvl = &tcomp->rlvls[rlvlno];
238        bodylen = 0;
239        for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
240          ++bandno, ++band) {
241            if (!band->data) {
242                continue;
243            }
244            prc = &band->prcs[prcno];
245            if (!prc->cblks) {
246                continue;
247            }
248            usedcblkcnt = 0;
249            for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
250              ++cblkno, ++cblk) {
251                ++usedcblkcnt;
252                if (!cblk->numpasses) {
253                    leaf = jpc_tagtree_getleaf(prc->incltagtree, usedcblkcnt - 1);
254                    if ((included = jpc_tagtree_decode(prc->incltagtree, leaf, lyrno + 1, inb)) < 0) {
255                        return -1;
256                    }
257                } else {
258                    if ((included = jpc_bitstream_getbit(inb)) < 0) {
259                        return -1;
260                    }
261                }
262                JAS_DBGLOG(10, ("\n"));
263                JAS_DBGLOG(10, ("included=%d ", included));
264                if (!included) {
265                    continue;
266                }
267                if (!cblk->numpasses) {
268                    i = 1;
269                    leaf = jpc_tagtree_getleaf(prc->numimsbstagtree, usedcblkcnt - 1);
270                    for (;;) {
271                        if ((ret = jpc_tagtree_decode(prc->numimsbstagtree, leaf, i, inb)) < 0) {
272                            return -1;
273                        }
274                        if (ret) {
275                            break;
276                        }
277                        ++i;
278                    }
279                    cblk->numimsbs = i - 1;
280                    cblk->firstpassno = cblk->numimsbs * 3;
281                }
282                if ((numnewpasses = jpc_getnumnewpasses(inb)) < 0) {
283                    return -1;
284                }
285                JAS_DBGLOG(10, ("numnewpasses=%d ", numnewpasses));
286                seg = cblk->curseg;
287                savenumnewpasses = numnewpasses;
288                mycounter = 0;
289                if (numnewpasses > 0) {
290                    if ((m = jpc_getcommacode(inb)) < 0) {
291                        return -1;
292                    }
293                    cblk->numlenbits += m;
294                    JAS_DBGLOG(10, ("increment=%d ", m));
295                    while (numnewpasses > 0) {
296                        passno = cblk->firstpassno + cblk->numpasses + mycounter;
297    /* XXX - the maxpasses is not set precisely but this doesn't matter... */
298                        maxpasses = JPC_SEGPASSCNT(passno, cblk->firstpassno, 10000, (ccp->cblkctx & JPC_COX_LAZY) != 0, (ccp->cblkctx & JPC_COX_TERMALL) != 0);
299                        if (!discard && !seg) {
300                            if (!(seg = jpc_seg_alloc())) {
301                                return -1;
302                            }
303                            jpc_seglist_insert(&cblk->segs, cblk->segs.tail, seg);
304                            if (!cblk->curseg) {
305                                cblk->curseg = seg;
306                            }
307                            seg->passno = passno;
308                            seg->type = JPC_SEGTYPE(seg->passno, cblk->firstpassno, (ccp->cblkctx & JPC_COX_LAZY) != 0);
309                            seg->maxpasses = maxpasses;
310                        }
311                        n = JAS_MIN(numnewpasses, maxpasses);
312                        mycounter += n;
313                        numnewpasses -= n;
314                        if ((len = jpc_bitstream_getbits(inb, cblk->numlenbits + jpc_floorlog2(n))) < 0) {
315                            return -1;
316                        }
317                        JAS_DBGLOG(10, ("len=%d ", len));
318                        if (!discard) {
319                            seg->lyrno = lyrno;
320                            seg->numpasses += n;
321                            seg->cnt = len;
322                            seg = seg->next;
323                        }
324                        bodylen += len;
325                    }
326                }
327                cblk->numpasses += savenumnewpasses;
328            }
329        }
330
331        jpc_bitstream_inalign(inb, 0, 0);
332
333    } else {
334        if (jpc_bitstream_inalign(inb, 0x7f, 0)) {
335            jas_eprintf("alignment failed\n");
336            return -1;
337        }
338    }
339    jpc_bitstream_close(inb);
340
341    hdroffend = jas_stream_getrwcount(pkthdrstream);
342    hdrlen = hdroffend - hdroffstart;
343    if (jas_getdbglevel() >= 5) {
344        jas_eprintf("hdrlen=%lu bodylen=%lu \n", (unsigned long) hdrlen,
345          (unsigned long) bodylen);
346    }
347
348    if (cp->csty & JPC_COD_EPH) {
349        if (jpc_dec_lookahead(pkthdrstream) == JPC_MS_EPH) {
350            if (!(ms = jpc_getms(pkthdrstream, dec->cstate))) {
351                jas_eprintf("cannot get (EPH) marker segment\n");
352                return -1;
353            }
354            if (jpc_ms_gettype(ms) != JPC_MS_EPH) {
355                jpc_ms_destroy(ms);
356                jas_eprintf("missing EPH marker segment\n");
357                return -1;
358            }
359            jpc_ms_destroy(ms);
360        }
361    }
362
363    /* decode the packet body. */
364
365    if (jas_getdbglevel() >= 1) {
366        jas_eprintf("packet body offset=%06ld\n", (long) jas_stream_getrwcount(in));
367    }
368
369    if (!discard) {
370        tcomp = &tile->tcomps[compno];
371        rlvl = &tcomp->rlvls[rlvlno];
372        for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
373          ++bandno, ++band) {
374            if (!band->data) {
375                continue;
376            }
377            prc = &band->prcs[prcno];
378            if (!prc->cblks) {
379                continue;
380            }
381            for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
382              ++cblkno, ++cblk) {
383                seg = cblk->curseg;
384                while (seg) {
385                    if (!seg->stream) {
386                        if (!(seg->stream = jas_stream_memopen(0, 0))) {
387                            return -1;
388                        }
389                    }
390#if 0
391jas_eprintf("lyrno=%02d, compno=%02d, lvlno=%02d, prcno=%02d, bandno=%02d, cblkno=%02d, passno=%02d numpasses=%02d cnt=%d numbps=%d, numimsbs=%d\n", lyrno, compno, rlvlno, prcno, band - rlvl->bands, cblk - prc->cblks, seg->passno, seg->numpasses, seg->cnt, band->numbps, cblk->numimsbs);
392#endif
393                    if (seg->cnt > 0) {
394                        if (jpc_getdata(in, seg->stream, seg->cnt) < 0) {
395                            return -1;
396                        }
397                        seg->cnt = 0;
398                    }
399                    if (seg->numpasses >= seg->maxpasses) {
400                        cblk->curseg = seg->next;
401                    }
402                    seg = seg->next;
403                }
404            }
405        }
406    } else {
407        if (jas_stream_gobble(in, bodylen) != JAS_CAST(int, bodylen)) {
408            return -1;
409        }
410    }
411    return 0;
412}
413
414/********************************************************************************************/
415/********************************************************************************************/
416
417int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in)
418{
419    jpc_dec_tile_t *tile;
420    jpc_pi_t *pi;
421    int ret;
422
423    tile = dec->curtile;
424    pi = tile->pi;
425    for (;;) {
426if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) {
427        switch (jpc_dec_lookahead(in)) {
428        case JPC_MS_EOC:
429        case JPC_MS_SOT:
430            return 0;
431            break;
432        case JPC_MS_SOP:
433        case JPC_MS_EPH:
434        case 0:
435            break;
436        default:
437            return -1;
438            break;
439        }
440}
441        if ((ret = jpc_pi_next(pi))) {
442            return ret;
443        }
444if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) {
445    jas_eprintf("warning: stopping decode prematurely as requested\n");
446    return 0;
447}
448        if (jas_getdbglevel() >= 1) {
449            jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d "
450              "rlvlno=%02d prcno=%03d lyrno=%02d\n", (long)
451              jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi),
452              jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi));
453        }
454        if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi),
455          jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) {
456            return -1;
457        }
458++dec->numpkts;
459    }
460
461    return 0;
462}
463
464jpc_pi_t *jpc_dec_pi_create(jpc_dec_t *dec, jpc_dec_tile_t *tile)
465{
466    jpc_pi_t *pi;
467    int compno;
468    jpc_picomp_t *picomp;
469    jpc_pirlvl_t *pirlvl;
470    jpc_dec_tcomp_t *tcomp;
471    int rlvlno;
472    jpc_dec_rlvl_t *rlvl;
473    int prcno;
474    int *prclyrno;
475    jpc_dec_cmpt_t *cmpt;
476
477    if (!(pi = jpc_pi_create0())) {
478        return 0;
479    }
480    pi->numcomps = dec->numcomps;
481    if (!(pi->picomps = jas_alloc2(pi->numcomps, sizeof(jpc_picomp_t)))) {
482        jpc_pi_destroy(pi);
483        return 0;
484    }
485    for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno,
486      ++picomp) {
487        picomp->pirlvls = 0;
488    }
489
490    for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps;
491      compno < pi->numcomps; ++compno, ++tcomp, ++picomp) {
492        picomp->numrlvls = tcomp->numrlvls;
493        if (!(picomp->pirlvls = jas_alloc2(picomp->numrlvls,
494          sizeof(jpc_pirlvl_t)))) {
495            jpc_pi_destroy(pi);
496            return 0;
497        }
498        for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
499          picomp->numrlvls; ++rlvlno, ++pirlvl) {
500            pirlvl->prclyrnos = 0;
501        }
502        for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls;
503          rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) {
504/* XXX sizeof(long) should be sizeof different type */
505            pirlvl->numprcs = rlvl->numprcs;
506            if (!(pirlvl->prclyrnos = jas_alloc2(pirlvl->numprcs,
507              sizeof(long)))) {
508                jpc_pi_destroy(pi);
509                return 0;
510            }
511        }
512    }
513
514    pi->maxrlvls = 0;
515    for (compno = 0, tcomp = tile->tcomps, picomp = pi->picomps, cmpt =
516      dec->cmpts; compno < pi->numcomps; ++compno, ++tcomp, ++picomp,
517      ++cmpt) {
518        picomp->hsamp = cmpt->hstep;
519        picomp->vsamp = cmpt->vstep;
520        for (rlvlno = 0, pirlvl = picomp->pirlvls, rlvl = tcomp->rlvls;
521          rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl, ++rlvl) {
522            pirlvl->prcwidthexpn = rlvl->prcwidthexpn;
523            pirlvl->prcheightexpn = rlvl->prcheightexpn;
524            for (prcno = 0, prclyrno = pirlvl->prclyrnos;
525              prcno < pirlvl->numprcs; ++prcno, ++prclyrno) {
526                *prclyrno = 0;
527            }
528            pirlvl->numhprcs = rlvl->numhprcs;
529        }
530        if (pi->maxrlvls < tcomp->numrlvls) {
531            pi->maxrlvls = tcomp->numrlvls;
532        }
533    }
534
535    pi->numlyrs = tile->cp->numlyrs;
536    pi->xstart = tile->xstart;
537    pi->ystart = tile->ystart;
538    pi->xend = tile->xend;
539    pi->yend = tile->yend;
540
541    pi->picomp = 0;
542    pi->pirlvl = 0;
543    pi->x = 0;
544    pi->y = 0;
545    pi->compno = 0;
546    pi->rlvlno = 0;
547    pi->prcno = 0;
548    pi->lyrno = 0;
549    pi->xstep = 0;
550    pi->ystep = 0;
551
552    pi->pchgno = -1;
553
554    pi->defaultpchg.prgord = tile->cp->prgord;
555    pi->defaultpchg.compnostart = 0;
556    pi->defaultpchg.compnoend = pi->numcomps;
557    pi->defaultpchg.rlvlnostart = 0;
558    pi->defaultpchg.rlvlnoend = pi->maxrlvls;
559    pi->defaultpchg.lyrnoend = pi->numlyrs;
560    pi->pchg = 0;
561
562    pi->valid = 0;
563
564    return pi;
565}
566
567long jpc_dec_lookahead(jas_stream_t *in)
568{
569    uint_fast16_t x;
570    if (jpc_getuint16(in, &x)) {
571        return -1;
572    }
573    if (jas_stream_ungetc(in, x & 0xff) == EOF ||
574      jas_stream_ungetc(in, x >> 8) == EOF) {
575        return -1;
576    }
577    if (x >= JPC_MS_INMIN /*&& x <= JPC_MS_INMAX*/) {
578        return x;
579    }
580    return 0;
581}
582