Home | History | Annotate | Download | only in libjasper
      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  * $Id: jpc_enc.c,v 1.2 2008-05-26 09:40:52 vp153 Exp $
     66  */
     67 
     68 /******************************************************************************\
     69 * Includes.
     70 \******************************************************************************/
     71 
     72 #include <stdio.h>
     73 #include <stdlib.h>
     74 #include <assert.h>
     75 #include <math.h>
     76 #include <float.h>
     77 
     78 #include "jasper/jas_types.h"
     79 #include "jasper/jas_string.h"
     80 #include "jasper/jas_malloc.h"
     81 #include "jasper/jas_image.h"
     82 #include "jasper/jas_fix.h"
     83 #include "jasper/jas_tvp.h"
     84 #include "jasper/jas_version.h"
     85 #include "jasper/jas_math.h"
     86 #include "jasper/jas_debug.h"
     87 
     88 #include "jpc_flt.h"
     89 #include "jpc_fix.h"
     90 #include "jpc_tagtree.h"
     91 #include "jpc_enc.h"
     92 #include "jpc_cs.h"
     93 #include "jpc_mct.h"
     94 #include "jpc_tsfb.h"
     95 #include "jpc_qmfb.h"
     96 #include "jpc_t1enc.h"
     97 #include "jpc_t2enc.h"
     98 #include "jpc_cod.h"
     99 #include "jpc_math.h"
    100 #include "jpc_util.h"
    101 
    102 /******************************************************************************\
    103 *
    104 \******************************************************************************/
    105 
    106 #define JPC_POW2(n) \
    107     (1 << (n))
    108 
    109 #define JPC_FLOORTOMULTPOW2(x, n) \
    110   (((n) > 0) ? ((x) & (~((1 << n) - 1))) : (x))
    111 /* Round to the nearest multiple of the specified power of two in the
    112   direction of negative infinity. */
    113 
    114 #define	JPC_CEILTOMULTPOW2(x, n) \
    115   (((n) > 0) ? JPC_FLOORTOMULTPOW2(((x) + (1 << (n)) - 1), n) : (x))
    116 /* Round to the nearest multiple of the specified power of two in the
    117   direction of positive infinity. */
    118 
    119 #define	JPC_POW2(n)	\
    120   (1 << (n))
    121 
    122 jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno);
    123 void jpc_enc_tile_destroy(jpc_enc_tile_t *tile);
    124 
    125 static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp,
    126   jas_image_t *image, jpc_enc_tile_t *tile);
    127 static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt);
    128 static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
    129   jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos);
    130 static void rlvl_destroy(jpc_enc_rlvl_t *rlvl);
    131 static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,
    132   jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos);
    133 static void band_destroy(jpc_enc_band_t *bands);
    134 static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp,
    135   jpc_enc_band_t *band);
    136 static void prc_destroy(jpc_enc_prc_t *prcs);
    137 static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp,
    138   jpc_enc_prc_t *prc);
    139 static void cblk_destroy(jpc_enc_cblk_t *cblks);
    140 int ratestrtosize(char *s, uint_fast32_t rawsize, uint_fast32_t *size);
    141 static void pass_destroy(jpc_enc_pass_t *pass);
    142 void jpc_enc_dump(jpc_enc_t *enc);
    143 
    144 /******************************************************************************\
    145 * Local prototypes.
    146 \******************************************************************************/
    147 
    148 int dump_passes(jpc_enc_pass_t *passes, int numpasses, jpc_enc_cblk_t *cblk);
    149 void calcrdslopes(jpc_enc_cblk_t *cblk);
    150 void dump_layeringinfo(jpc_enc_t *enc);
    151 static int jpc_calcssexp(jpc_fix_t stepsize);
    152 static int jpc_calcssmant(jpc_fix_t stepsize);
    153 void jpc_quantize(jas_matrix_t *data, jpc_fix_t stepsize);
    154 static int jpc_enc_encodemainhdr(jpc_enc_t *enc);
    155 static int jpc_enc_encodemainbody(jpc_enc_t *enc);
    156 int jpc_enc_encodetiledata(jpc_enc_t *enc);
    157 jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image);
    158 void jpc_enc_destroy(jpc_enc_t *enc);
    159 static int jpc_enc_encodemainhdr(jpc_enc_t *enc);
    160 static int jpc_enc_encodemainbody(jpc_enc_t *enc);
    161 int jpc_enc_encodetiledata(jpc_enc_t *enc);
    162 int rateallocate(jpc_enc_t *enc, int numlyrs, uint_fast32_t *cumlens);
    163 int setins(int numvalues, jpc_flt_t *values, jpc_flt_t value);
    164 static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image);
    165 void jpc_enc_cp_destroy(jpc_enc_cp_t *cp);
    166 static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn);
    167 
    168 static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn)
    169 {
    170     int p;
    171     uint_fast32_t mant;
    172     uint_fast32_t expn;
    173     int n;
    174 
    175     if (absdelta < 0) {
    176         abort();
    177     }
    178 
    179     p = jpc_firstone(absdelta) - JPC_FIX_FRACBITS;
    180     n = 11 - jpc_firstone(absdelta);
    181     mant = ((n < 0) ? (absdelta >> (-n)) : (absdelta << n)) & 0x7ff;
    182     expn = scaleexpn - p;
    183     if (scaleexpn < p) {
    184         abort();
    185     }
    186     return JPC_QCX_EXPN(expn) | JPC_QCX_MANT(mant);
    187 }
    188 
    189 typedef enum {
    190     OPT_DEBUG,
    191     OPT_IMGAREAOFFX,
    192     OPT_IMGAREAOFFY,
    193     OPT_TILEGRDOFFX,
    194     OPT_TILEGRDOFFY,
    195     OPT_TILEWIDTH,
    196     OPT_TILEHEIGHT,
    197     OPT_PRCWIDTH,
    198     OPT_PRCHEIGHT,
    199     OPT_CBLKWIDTH,
    200     OPT_CBLKHEIGHT,
    201     OPT_MODE,
    202     OPT_PRG,
    203     OPT_NOMCT,
    204     OPT_MAXRLVLS,
    205     OPT_SOP,
    206     OPT_EPH,
    207     OPT_LAZY,
    208     OPT_TERMALL,
    209     OPT_SEGSYM,
    210     OPT_VCAUSAL,
    211     OPT_RESET,
    212     OPT_PTERM,
    213     OPT_NUMGBITS,
    214     OPT_RATE,
    215     OPT_ILYRRATES,
    216     OPT_JP2OVERHEAD
    217 } optid_t;
    218 
    219 jas_taginfo_t encopts[] = {
    220     {OPT_DEBUG, "debug"},
    221     {OPT_IMGAREAOFFX, "imgareatlx"},
    222     {OPT_IMGAREAOFFY, "imgareatly"},
    223     {OPT_TILEGRDOFFX, "tilegrdtlx"},
    224     {OPT_TILEGRDOFFY, "tilegrdtly"},
    225     {OPT_TILEWIDTH, "tilewidth"},
    226     {OPT_TILEHEIGHT, "tileheight"},
    227     {OPT_PRCWIDTH, "prcwidth"},
    228     {OPT_PRCHEIGHT, "prcheight"},
    229     {OPT_CBLKWIDTH, "cblkwidth"},
    230     {OPT_CBLKHEIGHT, "cblkheight"},
    231     {OPT_MODE, "mode"},
    232     {OPT_PRG, "prg"},
    233     {OPT_NOMCT, "nomct"},
    234     {OPT_MAXRLVLS, "numrlvls"},
    235     {OPT_SOP, "sop"},
    236     {OPT_EPH, "eph"},
    237     {OPT_LAZY, "lazy"},
    238     {OPT_TERMALL, "termall"},
    239     {OPT_SEGSYM, "segsym"},
    240     {OPT_VCAUSAL, "vcausal"},
    241     {OPT_PTERM, "pterm"},
    242     {OPT_RESET, "resetprob"},
    243     {OPT_NUMGBITS, "numgbits"},
    244     {OPT_RATE, "rate"},
    245     {OPT_ILYRRATES, "ilyrrates"},
    246     {OPT_JP2OVERHEAD, "_jp2overhead"},
    247     {-1, 0}
    248 };
    249 
    250 typedef enum {
    251     PO_L = 0,
    252     PO_R
    253 } poid_t;
    254 
    255 
    256 jas_taginfo_t prgordtab[] = {
    257     {JPC_COD_LRCPPRG, "lrcp"},
    258     {JPC_COD_RLCPPRG, "rlcp"},
    259     {JPC_COD_RPCLPRG, "rpcl"},
    260     {JPC_COD_PCRLPRG, "pcrl"},
    261     {JPC_COD_CPRLPRG, "cprl"},
    262     {-1, 0}
    263 };
    264 
    265 typedef enum {
    266     MODE_INT,
    267     MODE_REAL
    268 } modeid_t;
    269 
    270 jas_taginfo_t modetab[] = {
    271     {MODE_INT, "int"},
    272     {MODE_REAL, "real"},
    273     {-1, 0}
    274 };
    275 
    276 /******************************************************************************\
    277 * The main encoder entry point.
    278 \******************************************************************************/
    279 
    280 int jpc_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
    281 {
    282     jpc_enc_t *enc;
    283     jpc_enc_cp_t *cp;
    284 
    285     enc = 0;
    286     cp = 0;
    287 
    288     jpc_initluts();
    289 
    290     if (!(cp = cp_create(optstr, image))) {
    291         jas_eprintf("invalid JP encoder options\n");
    292         goto error;
    293     }
    294 
    295     if (!(enc = jpc_enc_create(cp, out, image))) {
    296         goto error;
    297     }
    298     cp = 0;
    299 
    300     /* Encode the main header. */
    301     if (jpc_enc_encodemainhdr(enc)) {
    302         goto error;
    303     }
    304 
    305     /* Encode the main body.  This constitutes most of the encoding work. */
    306     if (jpc_enc_encodemainbody(enc)) {
    307         goto error;
    308     }
    309 
    310     /* Write EOC marker segment. */
    311     if (!(enc->mrk = jpc_ms_create(JPC_MS_EOC))) {
    312         goto error;
    313     }
    314     if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
    315         jas_eprintf("cannot write EOI marker\n");
    316         goto error;
    317     }
    318     jpc_ms_destroy(enc->mrk);
    319     enc->mrk = 0;
    320 
    321     if (jas_stream_flush(enc->out)) {
    322         goto error;
    323     }
    324 
    325     jpc_enc_destroy(enc);
    326 
    327     return 0;
    328 
    329 error:
    330     if (cp) {
    331         jpc_enc_cp_destroy(cp);
    332     }
    333     if (enc) {
    334         jpc_enc_destroy(enc);
    335     }
    336     return -1;
    337 }
    338 
    339 /******************************************************************************\
    340 * Option parsing code.
    341 \******************************************************************************/
    342 
    343 static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image)
    344 {
    345     jpc_enc_cp_t *cp;
    346     jas_tvparser_t *tvp;
    347     int ret;
    348     int numilyrrates;
    349     double *ilyrrates;
    350     int i;
    351     int tagid;
    352     jpc_enc_tcp_t *tcp;
    353     jpc_enc_tccp_t *tccp;
    354     jpc_enc_ccp_t *ccp;
    355     int cmptno;
    356     uint_fast16_t rlvlno;
    357     uint_fast16_t prcwidthexpn;
    358     uint_fast16_t prcheightexpn;
    359     bool enablemct;
    360     uint_fast32_t jp2overhead;
    361     uint_fast16_t lyrno;
    362     uint_fast32_t hsteplcm;
    363     uint_fast32_t vsteplcm;
    364     bool mctvalid;
    365 
    366     tvp = 0;
    367     cp = 0;
    368     ilyrrates = 0;
    369     numilyrrates = 0;
    370 
    371     if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) {
    372         goto error;
    373     }
    374 
    375     prcwidthexpn = 15;
    376     prcheightexpn = 15;
    377     enablemct = true;
    378     jp2overhead = 0;
    379 
    380     cp->ccps = 0;
    381     cp->debug = 0;
    382     cp->imgareatlx = UINT_FAST32_MAX;
    383     cp->imgareatly = UINT_FAST32_MAX;
    384     cp->refgrdwidth = 0;
    385     cp->refgrdheight = 0;
    386     cp->tilegrdoffx = UINT_FAST32_MAX;
    387     cp->tilegrdoffy = UINT_FAST32_MAX;
    388     cp->tilewidth = 0;
    389     cp->tileheight = 0;
    390     cp->numcmpts = jas_image_numcmpts(image);
    391 
    392     hsteplcm = 1;
    393     vsteplcm = 1;
    394     for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
    395         if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <=
    396           jas_image_brx(image) || jas_image_cmptbry(image, cmptno) +
    397           jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) {
    398             jas_eprintf("unsupported image type\n");
    399             goto error;
    400         }
    401         /* Note: We ought to be calculating the LCMs here.  Fix some day. */
    402         hsteplcm *= jas_image_cmpthstep(image, cmptno);
    403         vsteplcm *= jas_image_cmptvstep(image, cmptno);
    404     }
    405 
    406     if (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) {
    407         goto error;
    408     }
    409     for (cmptno = 0, ccp = cp->ccps; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno,
    410       ++ccp) {
    411         ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno);
    412         ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno);
    413         /* XXX - this isn't quite correct for more general image */
    414         ccp->sampgrdsubstepx = 0;
    415         ccp->sampgrdsubstepx = 0;
    416         ccp->prec = jas_image_cmptprec(image, cmptno);
    417         ccp->sgnd = jas_image_cmptsgnd(image, cmptno);
    418         ccp->numstepsizes = 0;
    419         memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes));
    420     }
    421 
    422     cp->rawsize = jas_image_rawsize(image);
    423     cp->totalsize = UINT_FAST32_MAX;
    424 
    425     tcp = &cp->tcp;
    426     tcp->csty = 0;
    427     tcp->intmode = true;
    428     tcp->prg = JPC_COD_LRCPPRG;
    429     tcp->numlyrs = 1;
    430     tcp->ilyrrates = 0;
    431 
    432     tccp = &cp->tccp;
    433     tccp->csty = 0;
    434     tccp->maxrlvls = 6;
    435     tccp->cblkwidthexpn = 6;
    436     tccp->cblkheightexpn = 6;
    437     tccp->cblksty = 0;
    438     tccp->numgbits = 2;
    439 
    440     if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
    441         goto error;
    442     }
    443 
    444     while (!(ret = jas_tvparser_next(tvp))) {
    445         switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts,
    446           jas_tvparser_gettag(tvp)))->id) {
    447         case OPT_DEBUG:
    448             cp->debug = atoi(jas_tvparser_getval(tvp));
    449             break;
    450         case OPT_IMGAREAOFFX:
    451             cp->imgareatlx = atoi(jas_tvparser_getval(tvp));
    452             break;
    453         case OPT_IMGAREAOFFY:
    454             cp->imgareatly = atoi(jas_tvparser_getval(tvp));
    455             break;
    456         case OPT_TILEGRDOFFX:
    457             cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp));
    458             break;
    459         case OPT_TILEGRDOFFY:
    460             cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp));
    461             break;
    462         case OPT_TILEWIDTH:
    463             cp->tilewidth = atoi(jas_tvparser_getval(tvp));
    464             break;
    465         case OPT_TILEHEIGHT:
    466             cp->tileheight = atoi(jas_tvparser_getval(tvp));
    467             break;
    468         case OPT_PRCWIDTH:
    469             prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
    470             break;
    471         case OPT_PRCHEIGHT:
    472             prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
    473             break;
    474         case OPT_CBLKWIDTH:
    475             tccp->cblkwidthexpn =
    476               jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
    477             break;
    478         case OPT_CBLKHEIGHT:
    479             tccp->cblkheightexpn =
    480               jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
    481             break;
    482         case OPT_MODE:
    483             if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab,
    484               jas_tvparser_getval(tvp)))->id) < 0) {
    485                 jas_eprintf("ignoring invalid mode %s\n",
    486                   jas_tvparser_getval(tvp));
    487             } else {
    488                 tcp->intmode = (tagid == MODE_INT);
    489             }
    490             break;
    491         case OPT_PRG:
    492             if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab,
    493               jas_tvparser_getval(tvp)))->id) < 0) {
    494                 jas_eprintf("ignoring invalid progression order %s\n",
    495                   jas_tvparser_getval(tvp));
    496             } else {
    497                 tcp->prg = tagid;
    498             }
    499             break;
    500         case OPT_NOMCT:
    501             enablemct = false;
    502             break;
    503         case OPT_MAXRLVLS:
    504             tccp->maxrlvls = atoi(jas_tvparser_getval(tvp));
    505             break;
    506         case OPT_SOP:
    507             cp->tcp.csty |= JPC_COD_SOP;
    508             break;
    509         case OPT_EPH:
    510             cp->tcp.csty |= JPC_COD_EPH;
    511             break;
    512         case OPT_LAZY:
    513             tccp->cblksty |= JPC_COX_LAZY;
    514             break;
    515         case OPT_TERMALL:
    516             tccp->cblksty |= JPC_COX_TERMALL;
    517             break;
    518         case OPT_SEGSYM:
    519             tccp->cblksty |= JPC_COX_SEGSYM;
    520             break;
    521         case OPT_VCAUSAL:
    522             tccp->cblksty |= JPC_COX_VSC;
    523             break;
    524         case OPT_RESET:
    525             tccp->cblksty |= JPC_COX_RESET;
    526             break;
    527         case OPT_PTERM:
    528             tccp->cblksty |= JPC_COX_PTERM;
    529             break;
    530         case OPT_NUMGBITS:
    531             cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));
    532             break;
    533         case OPT_RATE:
    534             if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
    535               &cp->totalsize)) {
    536                 jas_eprintf("ignoring bad rate specifier %s\n",
    537                   jas_tvparser_getval(tvp));
    538             }
    539             break;
    540         case OPT_ILYRRATES:
    541             if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,
    542               &ilyrrates)) {
    543                 jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n",
    544                   jas_tvparser_getval(tvp));
    545             }
    546             break;
    547 
    548         case OPT_JP2OVERHEAD:
    549             jp2overhead = atoi(jas_tvparser_getval(tvp));
    550             break;
    551         default:
    552             jas_eprintf("warning: ignoring invalid option %s\n",
    553              jas_tvparser_gettag(tvp));
    554             break;
    555         }
    556     }
    557 
    558     jas_tvparser_destroy(tvp);
    559     tvp = 0;
    560 
    561     if (cp->totalsize != UINT_FAST32_MAX) {
    562         cp->totalsize = (cp->totalsize > jp2overhead) ?
    563           (cp->totalsize - jp2overhead) : 0;
    564     }
    565 
    566     if (cp->imgareatlx == UINT_FAST32_MAX) {
    567         cp->imgareatlx = 0;
    568     } else {
    569         if (hsteplcm != 1) {
    570             jas_eprintf("warning: overriding imgareatlx value\n");
    571         }
    572         cp->imgareatlx *= hsteplcm;
    573     }
    574     if (cp->imgareatly == UINT_FAST32_MAX) {
    575         cp->imgareatly = 0;
    576     } else {
    577         if (vsteplcm != 1) {
    578             jas_eprintf("warning: overriding imgareatly value\n");
    579         }
    580         cp->imgareatly *= vsteplcm;
    581     }
    582     cp->refgrdwidth = cp->imgareatlx + jas_image_width(image);
    583     cp->refgrdheight = cp->imgareatly + jas_image_height(image);
    584     if (cp->tilegrdoffx == UINT_FAST32_MAX) {
    585         cp->tilegrdoffx = cp->imgareatlx;
    586     }
    587     if (cp->tilegrdoffy == UINT_FAST32_MAX) {
    588         cp->tilegrdoffy = cp->imgareatly;
    589     }
    590     if (!cp->tilewidth) {
    591         cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx;
    592     }
    593     if (!cp->tileheight) {
    594         cp->tileheight = cp->refgrdheight - cp->tilegrdoffy;
    595     }
    596 
    597     if (cp->numcmpts == 3) {
    598         mctvalid = true;
    599         for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
    600             if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) ||
    601               jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) ||
    602               jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) ||
    603               jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) {
    604                 mctvalid = false;
    605             }
    606         }
    607     } else {
    608         mctvalid = false;
    609     }
    610     if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) {
    611         jas_eprintf("warning: color space apparently not RGB\n");
    612     }
    613     if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) {
    614         tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT);
    615     } else {
    616         tcp->mctid = JPC_MCT_NONE;
    617     }
    618     tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS);
    619 
    620     for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
    621         tccp->prcwidthexpns[rlvlno] = prcwidthexpn;
    622         tccp->prcheightexpns[rlvlno] = prcheightexpn;
    623     }
    624     if (prcwidthexpn != 15 || prcheightexpn != 15) {
    625         tccp->csty |= JPC_COX_PRT;
    626     }
    627 
    628     /* Ensure that the tile width and height is valid. */
    629     if (!cp->tilewidth) {
    630         jas_eprintf("invalid tile width %lu\n", (unsigned long)
    631           cp->tilewidth);
    632         goto error;
    633     }
    634     if (!cp->tileheight) {
    635         jas_eprintf("invalid tile height %lu\n", (unsigned long)
    636           cp->tileheight);
    637         goto error;
    638     }
    639 
    640     /* Ensure that the tile grid offset is valid. */
    641     if (cp->tilegrdoffx > cp->imgareatlx ||
    642       cp->tilegrdoffy > cp->imgareatly ||
    643       cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx ||
    644       cp->tilegrdoffy + cp->tileheight < cp->imgareatly) {
    645         jas_eprintf("invalid tile grid offset (%lu, %lu)\n",
    646           (unsigned long) cp->tilegrdoffx, (unsigned long)
    647           cp->tilegrdoffy);
    648         goto error;
    649     }
    650 
    651     cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx,
    652       cp->tilewidth);
    653     cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy,
    654       cp->tileheight);
    655     cp->numtiles = cp->numhtiles * cp->numvtiles;
    656 
    657     if (ilyrrates && numilyrrates > 0) {
    658         tcp->numlyrs = numilyrrates + 1;
    659         if (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1),
    660           sizeof(jpc_fix_t)))) {
    661             goto error;
    662         }
    663         for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) {
    664             tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]);
    665         }
    666     }
    667 
    668     /* Ensure that the integer mode is used in the case of lossless
    669       coding. */
    670     if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) {
    671         jas_eprintf("cannot use real mode for lossless coding\n");
    672         goto error;
    673     }
    674 
    675     /* Ensure that the precinct width is valid. */
    676     if (prcwidthexpn > 15) {
    677         jas_eprintf("invalid precinct width\n");
    678         goto error;
    679     }
    680 
    681     /* Ensure that the precinct height is valid. */
    682     if (prcheightexpn > 15) {
    683         jas_eprintf("invalid precinct height\n");
    684         goto error;
    685     }
    686 
    687     /* Ensure that the code block width is valid. */
    688     if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) {
    689         jas_eprintf("invalid code block width %d\n",
    690           JPC_POW2(cp->tccp.cblkwidthexpn));
    691         goto error;
    692     }
    693 
    694     /* Ensure that the code block height is valid. */
    695     if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) {
    696         jas_eprintf("invalid code block height %d\n",
    697           JPC_POW2(cp->tccp.cblkheightexpn));
    698         goto error;
    699     }
    700 
    701     /* Ensure that the code block size is not too large. */
    702     if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) {
    703         jas_eprintf("code block size too large\n");
    704         goto error;
    705     }
    706 
    707     /* Ensure that the number of layers is valid. */
    708     if (cp->tcp.numlyrs > 16384) {
    709         jas_eprintf("too many layers\n");
    710         goto error;
    711     }
    712 
    713     /* There must be at least one resolution level. */
    714     if (cp->tccp.maxrlvls < 1) {
    715         jas_eprintf("must be at least one resolution level\n");
    716         goto error;
    717     }
    718 
    719     /* Ensure that the number of guard bits is valid. */
    720     if (cp->tccp.numgbits > 8) {
    721         jas_eprintf("invalid number of guard bits\n");
    722         goto error;
    723     }
    724 
    725     /* Ensure that the rate is within the legal range. */
    726     if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) {
    727         jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize);
    728     }
    729 
    730     /* Ensure that the intermediate layer rates are valid. */
    731     if (tcp->numlyrs > 1) {
    732         /* The intermediate layers rates must increase monotonically. */
    733         for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {
    734             if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {
    735                 jas_eprintf("intermediate layer rates must increase monotonically\n");
    736                 goto error;
    737             }
    738         }
    739         /* The intermediate layer rates must be less than the overall rate. */
    740         if (cp->totalsize != UINT_FAST32_MAX) {
    741             for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) {
    742                 if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize)
    743                   / cp->rawsize) {
    744                     jas_eprintf("warning: intermediate layer rates must be less than overall rate\n");
    745                     goto error;
    746                 }
    747             }
    748         }
    749     }
    750 
    751     if (ilyrrates) {
    752         jas_free(ilyrrates);
    753     }
    754 
    755     return cp;
    756 
    757 error:
    758 
    759     if (ilyrrates) {
    760         jas_free(ilyrrates);
    761     }
    762     if (tvp) {
    763         jas_tvparser_destroy(tvp);
    764     }
    765     if (cp) {
    766         jpc_enc_cp_destroy(cp);
    767     }
    768     return 0;
    769 }
    770 
    771 void jpc_enc_cp_destroy(jpc_enc_cp_t *cp)
    772 {
    773     if (cp->ccps) {
    774         if (cp->tcp.ilyrrates) {
    775             jas_free(cp->tcp.ilyrrates);
    776         }
    777         jas_free(cp->ccps);
    778     }
    779     jas_free(cp);
    780 }
    781 
    782 int ratestrtosize(char *s, uint_fast32_t rawsize, uint_fast32_t *size)
    783 {
    784     char *cp;
    785     jpc_flt_t f;
    786 
    787     /* Note: This function must not modify output size on failure. */
    788     if ((cp = strchr(s, 'B'))) {
    789         *size = atoi(s);
    790     } else {
    791         f = atof(s);
    792         if (f < 0) {
    793             *size = 0;
    794         } else if (f > 1.0) {
    795             *size = rawsize + 1;
    796         } else {
    797             *size = f * rawsize;
    798         }
    799     }
    800     return 0;
    801 }
    802 
    803 /******************************************************************************\
    804 * Encoder constructor and destructor.
    805 \******************************************************************************/
    806 
    807 jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image)
    808 {
    809     jpc_enc_t *enc;
    810 
    811     enc = 0;
    812 
    813     if (!(enc = jas_malloc(sizeof(jpc_enc_t)))) {
    814         goto error;
    815     }
    816 
    817     enc->image = image;
    818     enc->out = out;
    819     enc->cp = cp;
    820     enc->cstate = 0;
    821     enc->tmpstream = 0;
    822     enc->mrk = 0;
    823     enc->curtile = 0;
    824 
    825     if (!(enc->cstate = jpc_cstate_create())) {
    826         goto error;
    827     }
    828     enc->len = 0;
    829     enc->mainbodysize = 0;
    830 
    831     return enc;
    832 
    833 error:
    834 
    835     if (enc) {
    836         jpc_enc_destroy(enc);
    837     }
    838     return 0;
    839 }
    840 
    841 void jpc_enc_destroy(jpc_enc_t *enc)
    842 {
    843     /* The image object (i.e., enc->image) and output stream object
    844     (i.e., enc->out) are created outside of the encoder.
    845     Therefore, they must not be destroyed here. */
    846 
    847     if (enc->curtile) {
    848         jpc_enc_tile_destroy(enc->curtile);
    849     }
    850     if (enc->cp) {
    851         jpc_enc_cp_destroy(enc->cp);
    852     }
    853     if (enc->cstate) {
    854         jpc_cstate_destroy(enc->cstate);
    855     }
    856     if (enc->tmpstream) {
    857         jas_stream_close(enc->tmpstream);
    858     }
    859 
    860     jas_free(enc);
    861 }
    862 
    863 /******************************************************************************\
    864 * Code.
    865 \******************************************************************************/
    866 
    867 static int jpc_calcssmant(jpc_fix_t stepsize)
    868 {
    869     int n;
    870     int e;
    871     int m;
    872 
    873     n = jpc_firstone(stepsize);
    874     e = n - JPC_FIX_FRACBITS;
    875     if (n >= 11) {
    876         m = (stepsize >> (n - 11)) & 0x7ff;
    877     } else {
    878         m = (stepsize & ((1 << n) - 1)) << (11 - n);
    879     }
    880     return m;
    881 }
    882 
    883 static int jpc_calcssexp(jpc_fix_t stepsize)
    884 {
    885     return jpc_firstone(stepsize) - JPC_FIX_FRACBITS;
    886 }
    887 
    888 static int jpc_enc_encodemainhdr(jpc_enc_t *enc)
    889 {
    890     jpc_siz_t *siz;
    891     jpc_cod_t *cod;
    892     jpc_qcd_t *qcd;
    893     int i;
    894 long startoff;
    895 long mainhdrlen;
    896     jpc_enc_cp_t *cp;
    897     jpc_qcc_t *qcc;
    898     jpc_enc_tccp_t *tccp;
    899     uint_fast16_t cmptno;
    900     jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
    901     jpc_fix_t mctsynweight;
    902     jpc_enc_tcp_t *tcp;
    903     jpc_tsfb_t *tsfb;
    904     jpc_tsfb_band_t *bandinfo;
    905     uint_fast16_t numbands;
    906     uint_fast16_t bandno;
    907     uint_fast16_t rlvlno;
    908     uint_fast16_t analgain;
    909     jpc_fix_t absstepsize;
    910     char buf[1024];
    911     jpc_com_t *com;
    912 
    913     cp = enc->cp;
    914 
    915 startoff = jas_stream_getrwcount(enc->out);
    916 
    917     /* Write SOC marker segment. */
    918     if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {
    919         return -1;
    920     }
    921     if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
    922         jas_eprintf("cannot write SOC marker\n");
    923         return -1;
    924     }
    925     jpc_ms_destroy(enc->mrk);
    926     enc->mrk = 0;
    927 
    928     /* Write SIZ marker segment. */
    929     if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {
    930         return -1;
    931     }
    932     siz = &enc->mrk->parms.siz;
    933     siz->caps = 0;
    934     siz->xoff = cp->imgareatlx;
    935     siz->yoff = cp->imgareatly;
    936     siz->width = cp->refgrdwidth;
    937     siz->height = cp->refgrdheight;
    938     siz->tilexoff = cp->tilegrdoffx;
    939     siz->tileyoff = cp->tilegrdoffy;
    940     siz->tilewidth = cp->tilewidth;
    941     siz->tileheight = cp->tileheight;
    942     siz->numcomps = cp->numcmpts;
    943     siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t));
    944     assert(siz->comps);
    945     for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {
    946         siz->comps[i].prec = cp->ccps[i].prec;
    947         siz->comps[i].sgnd = cp->ccps[i].sgnd;
    948         siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;
    949         siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;
    950     }
    951     if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
    952         jas_eprintf("cannot write SIZ marker\n");
    953         return -1;
    954     }
    955     jpc_ms_destroy(enc->mrk);
    956     enc->mrk = 0;
    957 
    958     if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {
    959         return -1;
    960     }
    961     sprintf(buf, "Creator: JasPer Version %s", jas_getversion());
    962     com = &enc->mrk->parms.com;
    963     com->len = strlen(buf);
    964     com->regid = JPC_COM_LATIN;
    965     if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) {
    966         abort();
    967     }
    968     if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
    969         jas_eprintf("cannot write COM marker\n");
    970         return -1;
    971     }
    972     jpc_ms_destroy(enc->mrk);
    973     enc->mrk = 0;
    974 
    975 #if 0
    976     if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {
    977         return -1;
    978     }
    979     crg = &enc->mrk->parms.crg;
    980     crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t));
    981     if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
    982         jas_eprintf("cannot write CRG marker\n");
    983         return -1;
    984     }
    985     jpc_ms_destroy(enc->mrk);
    986     enc->mrk = 0;
    987 #endif
    988 
    989     tcp = &cp->tcp;
    990     tccp = &cp->tccp;
    991     for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
    992         tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);
    993         jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,
    994           bandinfos);
    995         jpc_tsfb_destroy(tsfb);
    996         mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno);
    997         numbands = 3 * tccp->maxrlvls - 2;
    998         for (bandno = 0, bandinfo = bandinfos; bandno < numbands;
    999           ++bandno, ++bandinfo) {
   1000             rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;
   1001             analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,
   1002               rlvlno, bandinfo->orient);
   1003             if (!tcp->intmode) {
   1004                 absstepsize = jpc_fix_div(jpc_inttofix(1 <<
   1005                   (analgain + 1)), bandinfo->synenergywt);
   1006             } else {
   1007                 absstepsize = jpc_inttofix(1);
   1008             }
   1009             cp->ccps[cmptno].stepsizes[bandno] =
   1010               jpc_abstorelstepsize(absstepsize,
   1011               cp->ccps[cmptno].prec + analgain);
   1012         }
   1013         cp->ccps[cmptno].numstepsizes = numbands;
   1014     }
   1015 
   1016     if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
   1017         return -1;
   1018     }
   1019     cod = &enc->mrk->parms.cod;
   1020     cod->csty = cp->tccp.csty | cp->tcp.csty;
   1021     cod->compparms.csty = cp->tccp.csty | cp->tcp.csty;
   1022     cod->compparms.numdlvls = cp->tccp.maxrlvls - 1;
   1023     cod->compparms.numrlvls = cp->tccp.maxrlvls;
   1024     cod->prg = cp->tcp.prg;
   1025     cod->numlyrs = cp->tcp.numlyrs;
   1026     cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);
   1027     cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);
   1028     cod->compparms.cblksty = cp->tccp.cblksty;
   1029     cod->compparms.qmfbid = cp->tccp.qmfbid;
   1030     cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);
   1031     if (tccp->csty & JPC_COX_PRT) {
   1032         for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
   1033             cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno];
   1034             cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno];
   1035         }
   1036     }
   1037     if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
   1038         jas_eprintf("cannot write COD marker\n");
   1039         return -1;
   1040     }
   1041     jpc_ms_destroy(enc->mrk);
   1042     enc->mrk = 0;
   1043 
   1044     if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {
   1045         return -1;
   1046     }
   1047     qcd = &enc->mrk->parms.qcd;
   1048     qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
   1049       JPC_QCX_SEQNT : JPC_QCX_NOQNT;
   1050     qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;
   1051     qcd->compparms.numguard = cp->tccp.numgbits;
   1052     qcd->compparms.stepsizes = cp->ccps[0].stepsizes;
   1053     if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
   1054         return -1;
   1055     }
   1056     /* We do not want the step size array to be freed! */
   1057     qcd->compparms.stepsizes = 0;
   1058     jpc_ms_destroy(enc->mrk);
   1059     enc->mrk = 0;
   1060 
   1061     tccp = &cp->tccp;
   1062     for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {
   1063         if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
   1064             return -1;
   1065         }
   1066         qcc = &enc->mrk->parms.qcc;
   1067         qcc->compno = cmptno;
   1068         qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
   1069           JPC_QCX_SEQNT : JPC_QCX_NOQNT;
   1070         qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;
   1071         qcc->compparms.numguard = cp->tccp.numgbits;
   1072         qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;
   1073         if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
   1074             return -1;
   1075         }
   1076         /* We do not want the step size array to be freed! */
   1077         qcc->compparms.stepsizes = 0;
   1078         jpc_ms_destroy(enc->mrk);
   1079         enc->mrk = 0;
   1080     }
   1081 
   1082 #define MAINTLRLEN	2
   1083     mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
   1084     enc->len += mainhdrlen;
   1085     if (enc->cp->totalsize != UINT_FAST32_MAX) {
   1086         uint_fast32_t overhead;
   1087         overhead = mainhdrlen + MAINTLRLEN;
   1088         enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
   1089           (enc->cp->totalsize - overhead) : 0;
   1090     } else {
   1091         enc->mainbodysize = UINT_FAST32_MAX;
   1092     }
   1093 
   1094     return 0;
   1095 }
   1096 
   1097 static int jpc_enc_encodemainbody(jpc_enc_t *enc)
   1098 {
   1099     int tileno;
   1100     int tilex;
   1101     int tiley;
   1102     int i;
   1103     jpc_sot_t *sot;
   1104     jpc_enc_tcmpt_t *comp;
   1105     jpc_enc_tcmpt_t *endcomps;
   1106     jpc_enc_band_t *band;
   1107     jpc_enc_band_t *endbands;
   1108     jpc_enc_rlvl_t *lvl;
   1109     int rlvlno;
   1110     jpc_qcc_t *qcc;
   1111     jpc_cod_t *cod;
   1112     int adjust;
   1113     int j;
   1114     int absbandno;
   1115     long numbytes;
   1116     long tilehdrlen;
   1117     long tilelen;
   1118     jpc_enc_tile_t *tile;
   1119     jpc_enc_cp_t *cp;
   1120     double rho;
   1121     int lyrno;
   1122     int cmptno;
   1123     int samestepsizes;
   1124     jpc_enc_ccp_t *ccps;
   1125     jpc_enc_tccp_t *tccp;
   1126 int bandno;
   1127 uint_fast32_t x;
   1128 uint_fast32_t y;
   1129 int mingbits;
   1130 int actualnumbps;
   1131 jpc_fix_t mxmag;
   1132 jpc_fix_t mag;
   1133 int numgbits;
   1134 
   1135     cp = enc->cp;
   1136 
   1137     /* Avoid compile warnings. */
   1138     numbytes = 0;
   1139 
   1140     for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) {
   1141         tilex = tileno % cp->numhtiles;
   1142         tiley = tileno / cp->numhtiles;
   1143 
   1144         if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno))) {
   1145             abort();
   1146         }
   1147 
   1148         tile = enc->curtile;
   1149 
   1150         if (jas_getdbglevel() >= 10) {
   1151             jpc_enc_dump(enc);
   1152         }
   1153 
   1154         endcomps = &tile->tcmpts[tile->numtcmpts];
   1155         for (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) {
   1156             if (!cp->ccps[cmptno].sgnd) {
   1157                 adjust = 1 << (cp->ccps[cmptno].prec - 1);
   1158                 for (i = 0; i < jas_matrix_numrows(comp->data); ++i) {
   1159                     for (j = 0; j < jas_matrix_numcols(comp->data); ++j) {
   1160                         *jas_matrix_getref(comp->data, i, j) -= adjust;
   1161                     }
   1162                 }
   1163             }
   1164         }
   1165 
   1166         if (!tile->intmode) {
   1167                 endcomps = &tile->tcmpts[tile->numtcmpts];
   1168                 for (comp = tile->tcmpts; comp != endcomps; ++comp) {
   1169                     jas_matrix_asl(comp->data, JPC_FIX_FRACBITS);
   1170                 }
   1171         }
   1172 
   1173         switch (tile->mctid) {
   1174         case JPC_MCT_RCT:
   1175 assert(jas_image_numcmpts(enc->image) == 3);
   1176             jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data,
   1177               tile->tcmpts[2].data);
   1178             break;
   1179         case JPC_MCT_ICT:
   1180 assert(jas_image_numcmpts(enc->image) == 3);
   1181             jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data,
   1182               tile->tcmpts[2].data);
   1183             break;
   1184         default:
   1185             break;
   1186         }
   1187 
   1188         for (i = 0; i < jas_image_numcmpts(enc->image); ++i) {
   1189             comp = &tile->tcmpts[i];
   1190             jpc_tsfb_analyze(comp->tsfb, comp->data);
   1191 
   1192         }
   1193 
   1194 
   1195         endcomps = &tile->tcmpts[tile->numtcmpts];
   1196         for (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) {
   1197             mingbits = 0;
   1198             absbandno = 0;
   1199             /* All bands must have a corresponding quantizer step size,
   1200               even if they contain no samples and are never coded. */
   1201             /* Some bands may not be hit by the loop below, so we must
   1202               initialize all of the step sizes to a sane value. */
   1203             memset(comp->stepsizes, 0, sizeof(comp->stepsizes));
   1204             for (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) {
   1205                 if (!lvl->bands) {
   1206                     absbandno += rlvlno ? 3 : 1;
   1207                     continue;
   1208                 }
   1209                 endbands = &lvl->bands[lvl->numbands];
   1210                 for (band = lvl->bands; band != endbands; ++band) {
   1211                     if (!band->data) {
   1212                         ++absbandno;
   1213                         continue;
   1214                     }
   1215                     actualnumbps = 0;
   1216                     mxmag = 0;
   1217                     for (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) {
   1218                         for (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) {
   1219                             mag = abs(jas_matrix_get(band->data, y, x));
   1220                             if (mag > mxmag) {
   1221                                 mxmag = mag;
   1222                             }
   1223                         }
   1224                     }
   1225                     if (tile->intmode) {
   1226                         actualnumbps = jpc_firstone(mxmag) + 1;
   1227                     } else {
   1228                         actualnumbps = jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;
   1229                     }
   1230                     numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 +
   1231                       band->analgain);
   1232 #if 0
   1233 jas_eprintf("%d %d mag=%d actual=%d numgbits=%d\n", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits);
   1234 #endif
   1235                     if (numgbits > mingbits) {
   1236                         mingbits = numgbits;
   1237                     }
   1238                     if (!tile->intmode) {
   1239                         band->absstepsize = jpc_fix_div(jpc_inttofix(1
   1240                           << (band->analgain + 1)),
   1241                           band->synweight);
   1242                     } else {
   1243                         band->absstepsize = jpc_inttofix(1);
   1244                     }
   1245                     band->stepsize = jpc_abstorelstepsize(
   1246                       band->absstepsize, cp->ccps[cmptno].prec +
   1247                       band->analgain);
   1248                     band->numbps = cp->tccp.numgbits +
   1249                       JPC_QCX_GETEXPN(band->stepsize) - 1;
   1250 
   1251                     if ((!tile->intmode) && band->data) {
   1252                         jpc_quantize(band->data, band->absstepsize);
   1253                     }
   1254 
   1255                     comp->stepsizes[absbandno] = band->stepsize;
   1256                     ++absbandno;
   1257                 }
   1258             }
   1259 
   1260             assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);
   1261             if (!tile->intmode) {
   1262                 jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);
   1263             } else {
   1264                 jas_matrix_asl(comp->data, JPC_NUMEXTRABITS);
   1265             }
   1266 
   1267 #if 0
   1268 jas_eprintf("mingbits %d\n", mingbits);
   1269 #endif
   1270             if (mingbits > cp->tccp.numgbits) {
   1271                 jas_eprintf("error: too few guard bits (need at least %d)\n",
   1272                   mingbits);
   1273                 return -1;
   1274             }
   1275         }
   1276 
   1277         if (!(enc->tmpstream = jas_stream_memopen(0, 0))) {
   1278             jas_eprintf("cannot open tmp file\n");
   1279             return -1;
   1280         }
   1281 
   1282         /* Write the tile header. */
   1283         if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) {
   1284             return -1;
   1285         }
   1286         sot = &enc->mrk->parms.sot;
   1287         sot->len = 0;
   1288         sot->tileno = tileno;
   1289         sot->partno = 0;
   1290         sot->numparts = 1;
   1291         if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
   1292             jas_eprintf("cannot write SOT marker\n");
   1293             return -1;
   1294         }
   1295         jpc_ms_destroy(enc->mrk);
   1296         enc->mrk = 0;
   1297 
   1298 /************************************************************************/
   1299 /************************************************************************/
   1300 /************************************************************************/
   1301 
   1302         tccp = &cp->tccp;
   1303         for (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) {
   1304             comp = &tile->tcmpts[cmptno];
   1305             if (comp->numrlvls != tccp->maxrlvls) {
   1306                 if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
   1307                     return -1;
   1308                 }
   1309 /* XXX = this is not really correct. we are using comp #0's precint sizes
   1310 and other characteristics */
   1311                 comp = &tile->tcmpts[0];
   1312                 cod = &enc->mrk->parms.cod;
   1313                 cod->compparms.csty = 0;
   1314                 cod->compparms.numdlvls = comp->numrlvls - 1;
   1315                 cod->prg = tile->prg;
   1316                 cod->numlyrs = tile->numlyrs;
   1317                 cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn);
   1318                 cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn);
   1319                 cod->compparms.cblksty = comp->cblksty;
   1320                 cod->compparms.qmfbid = comp->qmfbid;
   1321                 cod->mctrans = (tile->mctid != JPC_MCT_NONE);
   1322                 for (i = 0; i < comp->numrlvls; ++i) {
   1323                     cod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn;
   1324                     cod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn;
   1325                 }
   1326                 if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
   1327                     return -1;
   1328                 }
   1329                 jpc_ms_destroy(enc->mrk);
   1330                 enc->mrk = 0;
   1331             }
   1332         }
   1333 
   1334         for (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno, ++comp) {
   1335             ccps = &cp->ccps[cmptno];
   1336             if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) {
   1337                 samestepsizes = 1;
   1338                 for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes); ++bandno) {
   1339                     if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {
   1340                         samestepsizes = 0;
   1341                         break;
   1342                     }
   1343                 }
   1344             } else {
   1345                 samestepsizes = 0;
   1346             }
   1347             if (!samestepsizes) {
   1348                 if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
   1349                     return -1;
   1350                 }
   1351                 qcc = &enc->mrk->parms.qcc;
   1352                 qcc->compno = cmptno;
   1353                 qcc->compparms.numguard = cp->tccp.numgbits;
   1354                 qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?
   1355                   JPC_QCX_SEQNT : JPC_QCX_NOQNT;
   1356                 qcc->compparms.numstepsizes = comp->numstepsizes;
   1357                 qcc->compparms.stepsizes = comp->stepsizes;
   1358                 if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
   1359                     return -1;
   1360                 }
   1361                 qcc->compparms.stepsizes = 0;
   1362                 jpc_ms_destroy(enc->mrk);
   1363                 enc->mrk = 0;
   1364             }
   1365         }
   1366 
   1367         /* Write a SOD marker to indicate the end of the tile header. */
   1368         if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {
   1369             return -1;
   1370         }
   1371         if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
   1372             jas_eprintf("cannot write SOD marker\n");
   1373             return -1;
   1374         }
   1375         jpc_ms_destroy(enc->mrk);
   1376         enc->mrk = 0;
   1377 tilehdrlen = jas_stream_getrwcount(enc->tmpstream);
   1378 
   1379 /************************************************************************/
   1380 /************************************************************************/
   1381 /************************************************************************/
   1382 
   1383 if (jpc_enc_enccblks(enc)) {
   1384     abort();
   1385     return -1;
   1386 }
   1387 
   1388         cp = enc->cp;
   1389         rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) /
   1390           ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -
   1391           cp->imgareatly));
   1392         tile->rawsize = cp->rawsize * rho;
   1393 
   1394         for (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) {
   1395             tile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl(
   1396               cp->tcp.ilyrrates[lyrno]);
   1397         }
   1398         tile->lyrsizes[tile->numlyrs - 1] = (cp->totalsize != UINT_FAST32_MAX) ?
   1399           (rho * enc->mainbodysize) : UINT_FAST32_MAX;
   1400         for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
   1401             if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) {
   1402                 if (tilehdrlen <= JAS_CAST(long, tile->lyrsizes[lyrno])) {
   1403                     tile->lyrsizes[lyrno] -= tilehdrlen;
   1404                 } else {
   1405                     tile->lyrsizes[lyrno] = 0;
   1406                 }
   1407             }
   1408         }
   1409 
   1410         if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) {
   1411             return -1;
   1412         }
   1413 
   1414 #if 0
   1415 jas_eprintf("ENCODE TILE DATA\n");
   1416 #endif
   1417         if (jpc_enc_encodetiledata(enc)) {
   1418             jas_eprintf("dotile failed\n");
   1419             return -1;
   1420         }
   1421 
   1422 /************************************************************************/
   1423 /************************************************************************/
   1424 /************************************************************************/
   1425 
   1426 /************************************************************************/
   1427 /************************************************************************/
   1428 /************************************************************************/
   1429 
   1430         tilelen = jas_stream_tell(enc->tmpstream);
   1431 
   1432         if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {
   1433             return -1;
   1434         }
   1435         jpc_putuint32(enc->tmpstream, tilelen);
   1436 
   1437         if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {
   1438             return -1;
   1439         }
   1440         if (jpc_putdata(enc->out, enc->tmpstream, -1)) {
   1441             return -1;
   1442         }
   1443         enc->len += tilelen;
   1444 
   1445         jas_stream_close(enc->tmpstream);
   1446         enc->tmpstream = 0;
   1447 
   1448         jpc_enc_tile_destroy(enc->curtile);
   1449         enc->curtile = 0;
   1450 
   1451     }
   1452 
   1453     return 0;
   1454 }
   1455 
   1456 int jpc_enc_encodetiledata(jpc_enc_t *enc)
   1457 {
   1458 assert(enc->tmpstream);
   1459     if (jpc_enc_encpkts(enc, enc->tmpstream)) {
   1460         return -1;
   1461     }
   1462     return 0;
   1463 }
   1464 
   1465 int dump_passes(jpc_enc_pass_t *passes, int numpasses, jpc_enc_cblk_t *cblk)
   1466 {
   1467     jpc_enc_pass_t *pass;
   1468     int i;
   1469     jas_stream_memobj_t *smo;
   1470 
   1471     smo = cblk->stream->obj_;
   1472 
   1473     pass = passes;
   1474     for (i = 0; i < numpasses; ++i) {
   1475         jas_eprintf("start=%d end=%d type=%d term=%d lyrno=%d firstchar=%02x size=%ld pos=%ld\n",
   1476           (int)pass->start, (int)pass->end, (int)pass->type, (int)pass->term, (int)pass->lyrno,
   1477           smo->buf_[pass->start], (long)smo->len_, (long)smo->pos_);
   1478 #if 0
   1479         jas_memdump(stderr, &smo->buf_[pass->start], pass->end - pass->start);
   1480 #endif
   1481         ++pass;
   1482     }
   1483     return 0;
   1484 }
   1485 
   1486 void jpc_quantize(jas_matrix_t *data, jpc_fix_t stepsize)
   1487 {
   1488     int i;
   1489     int j;
   1490     jpc_fix_t t;
   1491 
   1492     if (stepsize == jpc_inttofix(1)) {
   1493         return;
   1494     }
   1495 
   1496     for (i = 0; i < jas_matrix_numrows(data); ++i) {
   1497         for (j = 0; j < jas_matrix_numcols(data); ++j) {
   1498             t = jas_matrix_get(data, i, j);
   1499 
   1500 {
   1501     if (t < 0) {
   1502         t = jpc_fix_neg(jpc_fix_div(jpc_fix_neg(t), stepsize));
   1503     } else {
   1504         t = jpc_fix_div(t, stepsize);
   1505     }
   1506 }
   1507 
   1508             jas_matrix_set(data, i, j, t);
   1509         }
   1510     }
   1511 }
   1512 
   1513 void calcrdslopes(jpc_enc_cblk_t *cblk)
   1514 {
   1515     jpc_enc_pass_t *endpasses;
   1516     jpc_enc_pass_t *pass0;
   1517     jpc_enc_pass_t *pass1;
   1518     jpc_enc_pass_t *pass2;
   1519     jpc_flt_t slope0;
   1520     jpc_flt_t slope;
   1521     jpc_flt_t dd;
   1522     long dr;
   1523 
   1524     endpasses = &cblk->passes[cblk->numpasses];
   1525     pass2 = cblk->passes;
   1526     slope0 = 0;
   1527     while (pass2 != endpasses) {
   1528         pass0 = 0;
   1529         for (pass1 = cblk->passes; pass1 != endpasses; ++pass1) {
   1530             dd = pass1->cumwmsedec;
   1531             dr = pass1->end;
   1532             if (pass0) {
   1533                 dd -= pass0->cumwmsedec;
   1534                 dr -= pass0->end;
   1535             }
   1536             if (dd <= 0) {
   1537                 pass1->rdslope = JPC_BADRDSLOPE;
   1538                 if (pass1 >= pass2) {
   1539                     pass2 = &pass1[1];
   1540                 }
   1541                 continue;
   1542             }
   1543             if (pass1 < pass2 && pass1->rdslope <= 0) {
   1544                 continue;
   1545             }
   1546             if (!dr) {
   1547                 assert(pass0);
   1548                 pass0->rdslope = 0;
   1549                 break;
   1550             }
   1551             slope = dd / dr;
   1552             if (pass0 && slope >= slope0) {
   1553                 pass0->rdslope = 0;
   1554                 break;
   1555             }
   1556             pass1->rdslope = slope;
   1557             if (pass1 >= pass2) {
   1558                 pass2 = &pass1[1];
   1559             }
   1560             pass0 = pass1;
   1561             slope0 = slope;
   1562         }
   1563     }
   1564 
   1565 #if 0
   1566     for (pass0 = cblk->passes; pass0 != endpasses; ++pass0) {
   1567 if (pass0->rdslope > 0.0) {
   1568         jas_eprintf("pass %02d nmsedec=%lf dec=%lf end=%d %lf\n", pass0 - cblk->passes,
   1569           fixtodbl(pass0->nmsedec), pass0->wmsedec, pass0->end, pass0->rdslope);
   1570 }
   1571     }
   1572 #endif
   1573 }
   1574 
   1575 void dump_layeringinfo(jpc_enc_t *enc)
   1576 {
   1577 
   1578     jpc_enc_tcmpt_t *tcmpt;
   1579     int tcmptno;
   1580     jpc_enc_rlvl_t *rlvl;
   1581     int rlvlno;
   1582     jpc_enc_band_t *band;
   1583     int bandno;
   1584     jpc_enc_prc_t *prc;
   1585     int prcno;
   1586     jpc_enc_cblk_t *cblk;
   1587     int cblkno;
   1588     jpc_enc_pass_t *pass;
   1589     int passno;
   1590     int lyrno;
   1591     jpc_enc_tile_t *tile;
   1592 
   1593     tile = enc->curtile;
   1594 
   1595     for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
   1596         jas_eprintf("lyrno = %02d\n", lyrno);
   1597         for (tcmptno = 0, tcmpt = tile->tcmpts; tcmptno < tile->numtcmpts;
   1598           ++tcmptno, ++tcmpt) {
   1599             for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
   1600               ++rlvlno, ++rlvl) {
   1601                 if (!rlvl->bands) {
   1602                     continue;
   1603                 }
   1604                 for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
   1605                   ++bandno, ++band) {
   1606                     if (!band->data) {
   1607                         continue;
   1608                     }
   1609                     for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
   1610                       ++prcno, ++prc) {
   1611                         if (!prc->cblks) {
   1612                             continue;
   1613                         }
   1614                         for (cblkno = 0, cblk = prc->cblks; cblkno <
   1615                           prc->numcblks; ++cblkno, ++cblk) {
   1616                             for (passno = 0, pass = cblk->passes; passno <
   1617                               cblk->numpasses && pass->lyrno == lyrno;
   1618                               ++passno, ++pass) {
   1619                                 jas_eprintf("lyrno=%02d cmptno=%02d rlvlno=%02d bandno=%02d prcno=%02d cblkno=%03d passno=%03d\n", lyrno, tcmptno, rlvlno, bandno, prcno, cblkno, passno);
   1620                             }
   1621                         }
   1622                     }
   1623                 }
   1624             }
   1625         }
   1626     }
   1627 }
   1628 
   1629 int rateallocate(jpc_enc_t *enc, int numlyrs, uint_fast32_t *cumlens)
   1630 {
   1631     jpc_flt_t lo;
   1632     jpc_flt_t hi;
   1633     jas_stream_t *out;
   1634     long cumlen;
   1635     int lyrno;
   1636     jpc_flt_t thresh;
   1637     jpc_flt_t goodthresh;
   1638     int success;
   1639     long pos;
   1640     long oldpos;
   1641     int numiters;
   1642 
   1643     jpc_enc_tcmpt_t *comp;
   1644     jpc_enc_tcmpt_t *endcomps;
   1645     jpc_enc_rlvl_t *lvl;
   1646     jpc_enc_rlvl_t *endlvls;
   1647     jpc_enc_band_t *band;
   1648     jpc_enc_band_t *endbands;
   1649     jpc_enc_cblk_t *cblk;
   1650     jpc_enc_cblk_t *endcblks;
   1651     jpc_enc_pass_t *pass;
   1652     jpc_enc_pass_t *endpasses;
   1653     jpc_enc_pass_t *pass1;
   1654     jpc_flt_t mxrdslope;
   1655     jpc_flt_t mnrdslope;
   1656     jpc_enc_tile_t *tile;
   1657     jpc_enc_prc_t *prc;
   1658     int prcno;
   1659 
   1660     tile = enc->curtile;
   1661 
   1662     for (lyrno = 1; lyrno < numlyrs - 1; ++lyrno) {
   1663         if (cumlens[lyrno - 1] > cumlens[lyrno]) {
   1664             abort();
   1665         }
   1666     }
   1667 
   1668     if (!(out = jas_stream_memopen(0, 0))) {
   1669         return -1;
   1670     }
   1671 
   1672 
   1673     /* Find minimum and maximum R-D slope values. */
   1674     mnrdslope = DBL_MAX;
   1675     mxrdslope = 0;
   1676     endcomps = &tile->tcmpts[tile->numtcmpts];
   1677     for (comp = tile->tcmpts; comp != endcomps; ++comp) {
   1678         endlvls = &comp->rlvls[comp->numrlvls];
   1679         for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
   1680             if (!lvl->bands) {
   1681                 continue;
   1682             }
   1683             endbands = &lvl->bands[lvl->numbands];
   1684             for (band = lvl->bands; band != endbands; ++band) {
   1685                 if (!band->data) {
   1686                     continue;
   1687                 }
   1688                 for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
   1689                     if (!prc->cblks) {
   1690                         continue;
   1691                     }
   1692                     endcblks = &prc->cblks[prc->numcblks];
   1693                     for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
   1694                         calcrdslopes(cblk);
   1695                         endpasses = &cblk->passes[cblk->numpasses];
   1696                         for (pass = cblk->passes; pass != endpasses; ++pass) {
   1697                             if (pass->rdslope > 0) {
   1698                                 if (pass->rdslope < mnrdslope) {
   1699                                     mnrdslope = pass->rdslope;
   1700                                 }
   1701                                 if (pass->rdslope > mxrdslope) {
   1702                                     mxrdslope = pass->rdslope;
   1703                                 }
   1704                             }
   1705                         }
   1706                     }
   1707                 }
   1708             }
   1709         }
   1710     }
   1711 if (jas_getdbglevel()) {
   1712     jas_eprintf("min rdslope = %f max rdslope = %f\n", mnrdslope, mxrdslope);
   1713 }
   1714 
   1715     jpc_init_t2state(enc, 1);
   1716 
   1717     for (lyrno = 0; lyrno < numlyrs; ++lyrno) {
   1718 
   1719         lo = mnrdslope;
   1720         hi = mxrdslope;
   1721 
   1722         success = 0;
   1723         goodthresh = 0;
   1724         numiters = 0;
   1725 
   1726         do {
   1727 
   1728             cumlen = cumlens[lyrno];
   1729             if (cumlen == UINT_FAST32_MAX) {
   1730                 /* Only the last layer can be free of a rate
   1731                   constraint (e.g., for lossless coding). */
   1732                 assert(lyrno == numlyrs - 1);
   1733                 goodthresh = -1;
   1734                 success = 1;
   1735                 break;
   1736             }
   1737 
   1738             thresh = (lo + hi) / 2;
   1739 
   1740             /* Save the tier 2 coding state. */
   1741             jpc_save_t2state(enc);
   1742             oldpos = jas_stream_tell(out);
   1743             assert(oldpos >= 0);
   1744 
   1745             /* Assign all passes with R-D slopes greater than or
   1746               equal to the current threshold to this layer. */
   1747             endcomps = &tile->tcmpts[tile->numtcmpts];
   1748             for (comp = tile->tcmpts; comp != endcomps; ++comp) {
   1749                 endlvls = &comp->rlvls[comp->numrlvls];
   1750                 for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
   1751                     if (!lvl->bands) {
   1752                         continue;
   1753                     }
   1754                     endbands = &lvl->bands[lvl->numbands];
   1755                     for (band = lvl->bands; band != endbands; ++band) {
   1756                         if (!band->data) {
   1757                             continue;
   1758                         }
   1759                         for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
   1760                             if (!prc->cblks) {
   1761                                 continue;
   1762                             }
   1763                             endcblks = &prc->cblks[prc->numcblks];
   1764                             for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
   1765                                 if (cblk->curpass) {
   1766                                     endpasses = &cblk->passes[cblk->numpasses];
   1767                                     pass1 = cblk->curpass;
   1768                                     for (pass = cblk->curpass; pass != endpasses; ++pass) {
   1769                                         if (pass->rdslope >= thresh) {
   1770                                             pass1 = &pass[1];
   1771                                         }
   1772                                     }
   1773                                     for (pass = cblk->curpass; pass != pass1; ++pass) {
   1774                                         pass->lyrno = lyrno;
   1775                                     }
   1776                                     for (; pass != endpasses; ++pass) {
   1777                                         pass->lyrno = -1;
   1778                                     }
   1779                                 }
   1780                             }
   1781                         }
   1782                     }
   1783                 }
   1784             }
   1785 
   1786             /* Perform tier 2 coding. */
   1787             endcomps = &tile->tcmpts[tile->numtcmpts];
   1788             for (comp = tile->tcmpts; comp != endcomps; ++comp) {
   1789                 endlvls = &comp->rlvls[comp->numrlvls];
   1790                 for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
   1791                     if (!lvl->bands) {
   1792                         continue;
   1793                     }
   1794                     for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
   1795                         if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) {
   1796                             return -1;
   1797                         }
   1798                     }
   1799                 }
   1800             }
   1801 
   1802             pos = jas_stream_tell(out);
   1803 
   1804             /* Check the rate constraint. */
   1805             assert(pos >= 0);
   1806             if (pos > cumlen) {
   1807                 /* The rate is too high. */
   1808                 lo = thresh;
   1809             } else if (pos <= cumlen) {
   1810                 /* The rate is low enough, so try higher. */
   1811                 hi = thresh;
   1812                 if (!success || thresh < goodthresh) {
   1813                     goodthresh = thresh;
   1814                     success = 1;
   1815                 }
   1816             }
   1817 
   1818             /* Save the tier 2 coding state. */
   1819             jpc_restore_t2state(enc);
   1820             if (jas_stream_seek(out, oldpos, SEEK_SET) < 0) {
   1821                 abort();
   1822             }
   1823 
   1824 if (jas_getdbglevel()) {
   1825 jas_eprintf("maxlen=%08ld actuallen=%08ld thresh=%f\n", cumlen, pos, thresh);
   1826 }
   1827 
   1828             ++numiters;
   1829         } while (lo < hi - 1e-3 && numiters < 32);
   1830 
   1831         if (!success) {
   1832             jas_eprintf("warning: empty layer generated\n");
   1833         }
   1834 
   1835 if (jas_getdbglevel()) {
   1836 jas_eprintf("success %d goodthresh %f\n", success, goodthresh);
   1837 }
   1838 
   1839         /* Assign all passes with R-D slopes greater than or
   1840           equal to the selected threshold to this layer. */
   1841         endcomps = &tile->tcmpts[tile->numtcmpts];
   1842         for (comp = tile->tcmpts; comp != endcomps; ++comp) {
   1843             endlvls = &comp->rlvls[comp->numrlvls];
   1844             for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
   1845 if (!lvl->bands) {
   1846     continue;
   1847 }
   1848                 endbands = &lvl->bands[lvl->numbands];
   1849                 for (band = lvl->bands; band != endbands; ++band) {
   1850                     if (!band->data) {
   1851                         continue;
   1852                     }
   1853                     for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
   1854                         if (!prc->cblks) {
   1855                             continue;
   1856                         }
   1857                         endcblks = &prc->cblks[prc->numcblks];
   1858                         for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
   1859                             if (cblk->curpass) {
   1860                                 endpasses = &cblk->passes[cblk->numpasses];
   1861                                 pass1 = cblk->curpass;
   1862                                 if (success) {
   1863                                     for (pass = cblk->curpass; pass != endpasses; ++pass) {
   1864                                         if (pass->rdslope >= goodthresh) {
   1865                                             pass1 = &pass[1];
   1866                                         }
   1867                                     }
   1868                                 }
   1869                                 for (pass = cblk->curpass; pass != pass1; ++pass) {
   1870                                     pass->lyrno = lyrno;
   1871                                 }
   1872                                 for (; pass != endpasses; ++pass) {
   1873                                     pass->lyrno = -1;
   1874                                 }
   1875                             }
   1876                         }
   1877                     }
   1878                 }
   1879             }
   1880         }
   1881 
   1882         /* Perform tier 2 coding. */
   1883         endcomps = &tile->tcmpts[tile->numtcmpts];
   1884         for (comp = tile->tcmpts; comp != endcomps; ++comp) {
   1885             endlvls = &comp->rlvls[comp->numrlvls];
   1886             for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
   1887                 if (!lvl->bands) {
   1888                     continue;
   1889                 }
   1890                 for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
   1891                     if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) {
   1892                         return -1;
   1893                     }
   1894                 }
   1895             }
   1896         }
   1897     }
   1898 
   1899     if (jas_getdbglevel() >= 5) {
   1900         dump_layeringinfo(enc);
   1901     }
   1902 
   1903     jas_stream_close(out);
   1904 
   1905     JAS_DBGLOG(10, ("done doing rateallocation\n"));
   1906 #if 0
   1907 jas_eprintf("DONE RATE ALLOCATE\n");
   1908 #endif
   1909 
   1910     return 0;
   1911 }
   1912 
   1913 /******************************************************************************\
   1914 * Tile constructors and destructors.
   1915 \******************************************************************************/
   1916 
   1917 jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno)
   1918 {
   1919     jpc_enc_tile_t *tile;
   1920     uint_fast32_t htileno;
   1921     uint_fast32_t vtileno;
   1922     uint_fast16_t lyrno;
   1923     uint_fast16_t cmptno;
   1924     jpc_enc_tcmpt_t *tcmpt;
   1925 
   1926     if (!(tile = jas_malloc(sizeof(jpc_enc_tile_t)))) {
   1927         goto error;
   1928     }
   1929 
   1930     /* Initialize a few members used in error recovery. */
   1931     tile->tcmpts = 0;
   1932     tile->lyrsizes = 0;
   1933     tile->numtcmpts = cp->numcmpts;
   1934     tile->pi = 0;
   1935 
   1936     tile->tileno = tileno;
   1937     htileno = tileno % cp->numhtiles;
   1938     vtileno = tileno / cp->numhtiles;
   1939 
   1940     /* Calculate the coordinates of the top-left and bottom-right
   1941       corners of the tile. */
   1942     tile->tlx = JAS_MAX(cp->tilegrdoffx + htileno * cp->tilewidth,
   1943       cp->imgareatlx);
   1944     tile->tly = JAS_MAX(cp->tilegrdoffy + vtileno * cp->tileheight,
   1945       cp->imgareatly);
   1946     tile->brx = JAS_MIN(cp->tilegrdoffx + (htileno + 1) * cp->tilewidth,
   1947       cp->refgrdwidth);
   1948     tile->bry = JAS_MIN(cp->tilegrdoffy + (vtileno + 1) * cp->tileheight,
   1949       cp->refgrdheight);
   1950 
   1951     /* Initialize some tile coding parameters. */
   1952     tile->intmode = cp->tcp.intmode;
   1953     tile->csty = cp->tcp.csty;
   1954     tile->prg = cp->tcp.prg;
   1955     tile->mctid = cp->tcp.mctid;
   1956 
   1957     tile->numlyrs = cp->tcp.numlyrs;
   1958     if (!(tile->lyrsizes = jas_alloc2(tile->numlyrs,
   1959       sizeof(uint_fast32_t)))) {
   1960         goto error;
   1961     }
   1962     for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
   1963         tile->lyrsizes[lyrno] = 0;
   1964     }
   1965 
   1966     /* Allocate an array for the per-tile-component information. */
   1967     if (!(tile->tcmpts = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_tcmpt_t)))) {
   1968         goto error;
   1969     }
   1970     /* Initialize a few members critical for error recovery. */
   1971     for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
   1972       ++cmptno, ++tcmpt) {
   1973         tcmpt->rlvls = 0;
   1974         tcmpt->tsfb = 0;
   1975         tcmpt->data = 0;
   1976     }
   1977     /* Initialize the per-tile-component information. */
   1978     for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
   1979       ++cmptno, ++tcmpt) {
   1980         if (!tcmpt_create(tcmpt, cp, image, tile)) {
   1981             goto error;
   1982         }
   1983     }
   1984 
   1985     /* Initialize the synthesis weights for the MCT. */
   1986     switch (tile->mctid) {
   1987     case JPC_MCT_RCT:
   1988         tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0));
   1989         tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(0.6875));
   1990         tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(0.6875));
   1991         break;
   1992     case JPC_MCT_ICT:
   1993         tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0000));
   1994         tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(3.2584));
   1995         tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(2.4755));
   1996         break;
   1997     default:
   1998     case JPC_MCT_NONE:
   1999         for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
   2000           ++cmptno, ++tcmpt) {
   2001             tcmpt->synweight = JPC_FIX_ONE;
   2002         }
   2003         break;
   2004     }
   2005 
   2006     if (!(tile->pi = jpc_enc_pi_create(cp, tile))) {
   2007         goto error;
   2008     }
   2009 
   2010     return tile;
   2011 
   2012 error:
   2013 
   2014     if (tile) {
   2015         jpc_enc_tile_destroy(tile);
   2016     }
   2017     return 0;
   2018 }
   2019 
   2020 void jpc_enc_tile_destroy(jpc_enc_tile_t *tile)
   2021 {
   2022     jpc_enc_tcmpt_t *tcmpt;
   2023     uint_fast16_t cmptno;
   2024 
   2025     if (tile->tcmpts) {
   2026         for (cmptno = 0, tcmpt = tile->tcmpts; cmptno <
   2027           tile->numtcmpts; ++cmptno, ++tcmpt) {
   2028             tcmpt_destroy(tcmpt);
   2029         }
   2030         jas_free(tile->tcmpts);
   2031     }
   2032     if (tile->lyrsizes) {
   2033         jas_free(tile->lyrsizes);
   2034     }
   2035     if (tile->pi) {
   2036         jpc_pi_destroy(tile->pi);
   2037     }
   2038     jas_free(tile);
   2039 }
   2040 
   2041 static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp,
   2042   jas_image_t *image, jpc_enc_tile_t *tile)
   2043 {
   2044     uint_fast16_t cmptno;
   2045     uint_fast16_t rlvlno;
   2046     jpc_enc_rlvl_t *rlvl;
   2047     uint_fast32_t tlx;
   2048     uint_fast32_t tly;
   2049     uint_fast32_t brx;
   2050     uint_fast32_t bry;
   2051     uint_fast32_t cmpttlx;
   2052     uint_fast32_t cmpttly;
   2053     jpc_enc_ccp_t *ccp;
   2054     jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
   2055 
   2056     tcmpt->tile = tile;
   2057     tcmpt->tsfb = 0;
   2058     tcmpt->data = 0;
   2059     tcmpt->rlvls = 0;
   2060 
   2061     /* Deduce the component number. */
   2062     cmptno = tcmpt - tile->tcmpts;
   2063 
   2064     ccp = &cp->ccps[cmptno];
   2065 
   2066     /* Compute the coordinates of the top-left and bottom-right
   2067       corners of this tile-component. */
   2068     tlx = JPC_CEILDIV(tile->tlx, ccp->sampgrdstepx);
   2069     tly = JPC_CEILDIV(tile->tly, ccp->sampgrdstepy);
   2070     brx = JPC_CEILDIV(tile->brx, ccp->sampgrdstepx);
   2071     bry = JPC_CEILDIV(tile->bry, ccp->sampgrdstepy);
   2072 
   2073     /* Create a sequence to hold the tile-component sample data. */
   2074     if (!(tcmpt->data = jas_seq2d_create(tlx, tly, brx, bry))) {
   2075         goto error;
   2076     }
   2077 
   2078     /* Get the image data associated with this tile-component. */
   2079     cmpttlx = JPC_CEILDIV(cp->imgareatlx, ccp->sampgrdstepx);
   2080     cmpttly = JPC_CEILDIV(cp->imgareatly, ccp->sampgrdstepy);
   2081     if (jas_image_readcmpt(image, cmptno, tlx - cmpttlx, tly - cmpttly,
   2082       brx - tlx, bry - tly, tcmpt->data)) {
   2083         goto error;
   2084     }
   2085 
   2086     tcmpt->synweight = 0;
   2087     tcmpt->qmfbid = cp->tccp.qmfbid;
   2088     tcmpt->numrlvls = cp->tccp.maxrlvls;
   2089     tcmpt->numbands = 3 * tcmpt->numrlvls - 2;
   2090     if (!(tcmpt->tsfb = jpc_cod_gettsfb(tcmpt->qmfbid, tcmpt->numrlvls - 1))) {
   2091         goto error;
   2092     }
   2093 
   2094     for (rlvlno = 0; rlvlno < tcmpt->numrlvls; ++rlvlno) {
   2095         tcmpt->prcwidthexpns[rlvlno] = cp->tccp.prcwidthexpns[rlvlno];
   2096         tcmpt->prcheightexpns[rlvlno] = cp->tccp.prcheightexpns[rlvlno];
   2097     }
   2098     tcmpt->cblkwidthexpn = cp->tccp.cblkwidthexpn;
   2099     tcmpt->cblkheightexpn = cp->tccp.cblkheightexpn;
   2100     tcmpt->cblksty = cp->tccp.cblksty;
   2101     tcmpt->csty = cp->tccp.csty;
   2102 
   2103     tcmpt->numstepsizes = tcmpt->numbands;
   2104     assert(tcmpt->numstepsizes <= JPC_MAXBANDS);
   2105     memset(tcmpt->stepsizes, 0, tcmpt->numstepsizes *
   2106       sizeof(uint_fast16_t));
   2107 
   2108     /* Retrieve information about the various bands. */
   2109     jpc_tsfb_getbands(tcmpt->tsfb, jas_seq2d_xstart(tcmpt->data),
   2110       jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data),
   2111       jas_seq2d_yend(tcmpt->data), bandinfos);
   2112 
   2113     if (!(tcmpt->rlvls = jas_alloc2(tcmpt->numrlvls, sizeof(jpc_enc_rlvl_t)))) {
   2114         goto error;
   2115     }
   2116     for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
   2117       ++rlvlno, ++rlvl) {
   2118         rlvl->bands = 0;
   2119         rlvl->tcmpt = tcmpt;
   2120     }
   2121     for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
   2122       ++rlvlno, ++rlvl) {
   2123         if (!rlvl_create(rlvl, cp, tcmpt, bandinfos)) {
   2124             goto error;
   2125         }
   2126     }
   2127 
   2128     return tcmpt;
   2129 
   2130 error:
   2131 
   2132     tcmpt_destroy(tcmpt);
   2133     return 0;
   2134 
   2135 }
   2136 
   2137 static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt)
   2138 {
   2139     jpc_enc_rlvl_t *rlvl;
   2140     uint_fast16_t rlvlno;
   2141 
   2142     if (tcmpt->rlvls) {
   2143         for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
   2144           ++rlvlno, ++rlvl) {
   2145             rlvl_destroy(rlvl);
   2146         }
   2147         jas_free(tcmpt->rlvls);
   2148     }
   2149 
   2150     if (tcmpt->data) {
   2151         jas_seq2d_destroy(tcmpt->data);
   2152     }
   2153     if (tcmpt->tsfb) {
   2154         jpc_tsfb_destroy(tcmpt->tsfb);
   2155     }
   2156 }
   2157 
   2158 static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
   2159   jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos)
   2160 {
   2161     uint_fast16_t rlvlno;
   2162     uint_fast32_t tlprctlx;
   2163     uint_fast32_t tlprctly;
   2164     uint_fast32_t brprcbrx;
   2165     uint_fast32_t brprcbry;
   2166     uint_fast16_t bandno;
   2167     jpc_enc_band_t *band;
   2168 
   2169     /* Deduce the resolution level. */
   2170     rlvlno = rlvl - tcmpt->rlvls;
   2171 
   2172     /* Initialize members required for error recovery. */
   2173     rlvl->bands = 0;
   2174     rlvl->tcmpt = tcmpt;
   2175 
   2176     /* Compute the coordinates of the top-left and bottom-right
   2177       corners of the tile-component at this resolution. */
   2178     rlvl->tlx = JPC_CEILDIVPOW2(jas_seq2d_xstart(tcmpt->data), tcmpt->numrlvls -
   2179       1 - rlvlno);
   2180     rlvl->tly = JPC_CEILDIVPOW2(jas_seq2d_ystart(tcmpt->data), tcmpt->numrlvls -
   2181       1 - rlvlno);
   2182     rlvl->brx = JPC_CEILDIVPOW2(jas_seq2d_xend(tcmpt->data), tcmpt->numrlvls -
   2183       1 - rlvlno);
   2184     rlvl->bry = JPC_CEILDIVPOW2(jas_seq2d_yend(tcmpt->data), tcmpt->numrlvls -
   2185       1 - rlvlno);
   2186 
   2187     if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) {
   2188         rlvl->numhprcs = 0;
   2189         rlvl->numvprcs = 0;
   2190         rlvl->numprcs = 0;
   2191         return rlvl;
   2192     }
   2193 
   2194     rlvl->numbands = (!rlvlno) ? 1 : 3;
   2195     rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno];
   2196     rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno];
   2197     if (!rlvlno) {
   2198         rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
   2199         rlvl->cbgheightexpn = rlvl->prcheightexpn;
   2200     } else {
   2201         rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
   2202         rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
   2203     }
   2204     rlvl->cblkwidthexpn = JAS_MIN(cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn);
   2205     rlvl->cblkheightexpn = JAS_MIN(cp->tccp.cblkheightexpn, rlvl->cbgheightexpn);
   2206 
   2207     /* Compute the number of precincts. */
   2208     tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
   2209     tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
   2210     brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn);
   2211     brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn);
   2212     rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn);
   2213     rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn);
   2214     rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
   2215 
   2216     if (!(rlvl->bands = jas_alloc2(rlvl->numbands, sizeof(jpc_enc_band_t)))) {
   2217         goto error;
   2218     }
   2219     for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
   2220       ++bandno, ++band) {
   2221         band->prcs = 0;
   2222         band->data = 0;
   2223         band->rlvl = rlvl;
   2224     }
   2225     for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
   2226       ++bandno, ++band) {
   2227         if (!band_create(band, cp, rlvl, bandinfos)) {
   2228             goto error;
   2229         }
   2230     }
   2231 
   2232     return rlvl;
   2233 error:
   2234 
   2235     rlvl_destroy(rlvl);
   2236     return 0;
   2237 }
   2238 
   2239 static void rlvl_destroy(jpc_enc_rlvl_t *rlvl)
   2240 {
   2241     jpc_enc_band_t *band;
   2242     uint_fast16_t bandno;
   2243 
   2244     if (rlvl->bands) {
   2245         for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
   2246           ++bandno, ++band) {
   2247             band_destroy(band);
   2248         }
   2249         jas_free(rlvl->bands);
   2250     }
   2251 }
   2252 
   2253 static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,
   2254   jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos)
   2255 {
   2256     uint_fast16_t bandno;
   2257     uint_fast16_t gblbandno;
   2258     uint_fast16_t rlvlno;
   2259     jpc_tsfb_band_t *bandinfo;
   2260     jpc_enc_tcmpt_t *tcmpt;
   2261     uint_fast32_t prcno;
   2262     jpc_enc_prc_t *prc;
   2263 
   2264     tcmpt = rlvl->tcmpt;
   2265     band->data = 0;
   2266     band->prcs = 0;
   2267     band->rlvl = rlvl;
   2268 
   2269     /* Deduce the resolution level and band number. */
   2270     rlvlno = rlvl - rlvl->tcmpt->rlvls;
   2271     bandno = band - rlvl->bands;
   2272     gblbandno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1);
   2273 
   2274     bandinfo = &bandinfos[gblbandno];
   2275 
   2276 if (bandinfo->xstart != bandinfo->xend && bandinfo->ystart != bandinfo->yend) {
   2277     if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
   2278         goto error;
   2279     }
   2280     jas_seq2d_bindsub(band->data, tcmpt->data, bandinfo->locxstart,
   2281       bandinfo->locystart, bandinfo->locxend, bandinfo->locyend);
   2282     jas_seq2d_setshift(band->data, bandinfo->xstart, bandinfo->ystart);
   2283 }
   2284     band->orient = bandinfo->orient;
   2285     band->analgain = JPC_NOMINALGAIN(cp->tccp.qmfbid, tcmpt->numrlvls, rlvlno,
   2286       band->orient);
   2287     band->numbps = 0;
   2288     band->absstepsize = 0;
   2289     band->stepsize = 0;
   2290     band->synweight = bandinfo->synenergywt;
   2291 
   2292 if (band->data) {
   2293     if (!(band->prcs = jas_alloc2(rlvl->numprcs, sizeof(jpc_enc_prc_t)))) {
   2294         goto error;
   2295     }
   2296     for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
   2297       ++prc) {
   2298         prc->cblks = 0;
   2299         prc->incltree = 0;
   2300         prc->nlibtree = 0;
   2301         prc->savincltree = 0;
   2302         prc->savnlibtree = 0;
   2303         prc->band = band;
   2304     }
   2305     for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
   2306       ++prc) {
   2307         if (!prc_create(prc, cp, band)) {
   2308             goto error;
   2309         }
   2310     }
   2311 }
   2312 
   2313     return band;
   2314 
   2315 error:
   2316     band_destroy(band);
   2317     return 0;
   2318 }
   2319 
   2320 static void band_destroy(jpc_enc_band_t *band)
   2321 {
   2322     jpc_enc_prc_t *prc;
   2323     jpc_enc_rlvl_t *rlvl;
   2324     uint_fast32_t prcno;
   2325 
   2326     if (band->prcs) {
   2327         rlvl = band->rlvl;
   2328         for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
   2329           ++prcno, ++prc) {
   2330             prc_destroy(prc);
   2331         }
   2332         jas_free(band->prcs);
   2333     }
   2334     if (band->data) {
   2335         jas_seq2d_destroy(band->data);
   2336     }
   2337 }
   2338 
   2339 static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, jpc_enc_band_t *band)
   2340 {
   2341     uint_fast32_t prcno;
   2342     uint_fast32_t prcxind;
   2343     uint_fast32_t prcyind;
   2344     uint_fast32_t cbgtlx;
   2345     uint_fast32_t cbgtly;
   2346     uint_fast32_t tlprctlx;
   2347     uint_fast32_t tlprctly;
   2348     uint_fast32_t tlcbgtlx;
   2349     uint_fast32_t tlcbgtly;
   2350     uint_fast16_t rlvlno;
   2351     jpc_enc_rlvl_t *rlvl;
   2352     uint_fast32_t tlcblktlx;
   2353     uint_fast32_t tlcblktly;
   2354     uint_fast32_t brcblkbrx;
   2355     uint_fast32_t brcblkbry;
   2356     uint_fast32_t cblkno;
   2357     jpc_enc_cblk_t *cblk;
   2358     jpc_enc_tcmpt_t *tcmpt;
   2359 
   2360     prc->cblks = 0;
   2361     prc->incltree = 0;
   2362     prc->savincltree = 0;
   2363     prc->nlibtree = 0;
   2364     prc->savnlibtree = 0;
   2365 
   2366     rlvl = band->rlvl;
   2367     tcmpt = rlvl->tcmpt;
   2368 rlvlno = rlvl - tcmpt->rlvls;
   2369     prcno = prc - band->prcs;
   2370     prcxind = prcno % rlvl->numhprcs;
   2371     prcyind = prcno / rlvl->numhprcs;
   2372     prc->band = band;
   2373 
   2374 tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
   2375 tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
   2376 if (!rlvlno) {
   2377     tlcbgtlx = tlprctlx;
   2378     tlcbgtly = tlprctly;
   2379 } else {
   2380     tlcbgtlx = JPC_CEILDIVPOW2(tlprctlx, 1);
   2381     tlcbgtly = JPC_CEILDIVPOW2(tlprctly, 1);
   2382 }
   2383 
   2384     /* Compute the coordinates of the top-left and bottom-right
   2385       corners of the precinct. */
   2386     cbgtlx = tlcbgtlx + (prcxind << rlvl->cbgwidthexpn);
   2387     cbgtly = tlcbgtly + (prcyind << rlvl->cbgheightexpn);
   2388     prc->tlx = JAS_MAX(jas_seq2d_xstart(band->data), cbgtlx);
   2389     prc->tly = JAS_MAX(jas_seq2d_ystart(band->data), cbgtly);
   2390     prc->brx = JAS_MIN(jas_seq2d_xend(band->data), cbgtlx +
   2391       (1 << rlvl->cbgwidthexpn));
   2392     prc->bry = JAS_MIN(jas_seq2d_yend(band->data), cbgtly +
   2393       (1 << rlvl->cbgheightexpn));
   2394 
   2395     if (prc->tlx < prc->brx && prc->tly < prc->bry) {
   2396         /* The precinct contains at least one code block. */
   2397 
   2398         tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
   2399         tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
   2400         brcblkbrx = JPC_CEILTOMULTPOW2(prc->brx, rlvl->cblkwidthexpn);
   2401         brcblkbry = JPC_CEILTOMULTPOW2(prc->bry, rlvl->cblkheightexpn);
   2402         prc->numhcblks = JPC_FLOORDIVPOW2(brcblkbrx - tlcblktlx,
   2403           rlvl->cblkwidthexpn);
   2404         prc->numvcblks = JPC_FLOORDIVPOW2(brcblkbry - tlcblktly,
   2405           rlvl->cblkheightexpn);
   2406         prc->numcblks = prc->numhcblks * prc->numvcblks;
   2407 
   2408         if (!(prc->incltree = jpc_tagtree_create(prc->numhcblks,
   2409           prc->numvcblks))) {
   2410             goto error;
   2411         }
   2412         if (!(prc->nlibtree = jpc_tagtree_create(prc->numhcblks,
   2413           prc->numvcblks))) {
   2414             goto error;
   2415         }
   2416         if (!(prc->savincltree = jpc_tagtree_create(prc->numhcblks,
   2417           prc->numvcblks))) {
   2418             goto error;
   2419         }
   2420         if (!(prc->savnlibtree = jpc_tagtree_create(prc->numhcblks,
   2421           prc->numvcblks))) {
   2422             goto error;
   2423         }
   2424 
   2425         if (!(prc->cblks = jas_alloc2(prc->numcblks, sizeof(jpc_enc_cblk_t)))) {
   2426             goto error;
   2427         }
   2428         for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
   2429           ++cblkno, ++cblk) {
   2430             cblk->passes = 0;
   2431             cblk->stream = 0;
   2432             cblk->mqenc = 0;
   2433             cblk->data = 0;
   2434             cblk->flags = 0;
   2435             cblk->prc = prc;
   2436         }
   2437         for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
   2438           ++cblkno, ++cblk) {
   2439             if (!cblk_create(cblk, cp, prc)) {
   2440                 goto error;
   2441             }
   2442         }
   2443     } else {
   2444         /* The precinct does not contain any code blocks. */
   2445         prc->tlx = prc->brx;
   2446         prc->tly = prc->bry;
   2447         prc->numcblks = 0;
   2448         prc->numhcblks = 0;
   2449         prc->numvcblks = 0;
   2450         prc->cblks = 0;
   2451         prc->incltree = 0;
   2452         prc->nlibtree = 0;
   2453         prc->savincltree = 0;
   2454         prc->savnlibtree = 0;
   2455     }
   2456 
   2457     return prc;
   2458 
   2459 error:
   2460     prc_destroy(prc);
   2461     return 0;
   2462 }
   2463 
   2464 static void prc_destroy(jpc_enc_prc_t *prc)
   2465 {
   2466     jpc_enc_cblk_t *cblk;
   2467     uint_fast32_t cblkno;
   2468 
   2469     if (prc->cblks) {
   2470         for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
   2471           ++cblkno, ++cblk) {
   2472             cblk_destroy(cblk);
   2473         }
   2474         jas_free(prc->cblks);
   2475     }
   2476     if (prc->incltree) {
   2477         jpc_tagtree_destroy(prc->incltree);
   2478     }
   2479     if (prc->nlibtree) {
   2480         jpc_tagtree_destroy(prc->nlibtree);
   2481     }
   2482     if (prc->savincltree) {
   2483         jpc_tagtree_destroy(prc->savincltree);
   2484     }
   2485     if (prc->savnlibtree) {
   2486         jpc_tagtree_destroy(prc->savnlibtree);
   2487     }
   2488 }
   2489 
   2490 static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp, jpc_enc_prc_t *prc)
   2491 {
   2492     jpc_enc_band_t *band;
   2493     uint_fast32_t cblktlx;
   2494     uint_fast32_t cblktly;
   2495     uint_fast32_t cblkbrx;
   2496     uint_fast32_t cblkbry;
   2497     jpc_enc_rlvl_t *rlvl;
   2498     uint_fast32_t cblkxind;
   2499     uint_fast32_t cblkyind;
   2500     uint_fast32_t cblkno;
   2501     uint_fast32_t tlcblktlx;
   2502     uint_fast32_t tlcblktly;
   2503 
   2504     cblkno = cblk - prc->cblks;
   2505     cblkxind = cblkno % prc->numhcblks;
   2506     cblkyind = cblkno / prc->numhcblks;
   2507     rlvl = prc->band->rlvl;
   2508     cblk->prc = prc;
   2509 
   2510     cblk->numpasses = 0;
   2511     cblk->passes = 0;
   2512     cblk->numencpasses = 0;
   2513     cblk->numimsbs = 0;
   2514     cblk->numlenbits = 0;
   2515     cblk->stream = 0;
   2516     cblk->mqenc = 0;
   2517     cblk->flags = 0;
   2518     cblk->numbps = 0;
   2519     cblk->curpass = 0;
   2520     cblk->data = 0;
   2521     cblk->savedcurpass = 0;
   2522     cblk->savednumlenbits = 0;
   2523     cblk->savednumencpasses = 0;
   2524 
   2525     band = prc->band;
   2526     tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
   2527     tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
   2528     cblktlx = JAS_MAX(tlcblktlx + (cblkxind << rlvl->cblkwidthexpn), prc->tlx);
   2529     cblktly = JAS_MAX(tlcblktly + (cblkyind << rlvl->cblkheightexpn), prc->tly);
   2530     cblkbrx = JAS_MIN(tlcblktlx + ((cblkxind + 1) << rlvl->cblkwidthexpn),
   2531       prc->brx);
   2532     cblkbry = JAS_MIN(tlcblktly + ((cblkyind + 1) << rlvl->cblkheightexpn),
   2533       prc->bry);
   2534 
   2535     assert(cblktlx < cblkbrx && cblktly < cblkbry);
   2536     if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) {
   2537         goto error;
   2538     }
   2539     jas_seq2d_bindsub(cblk->data, band->data, cblktlx, cblktly, cblkbrx, cblkbry);
   2540 
   2541     return cblk;
   2542 
   2543 error:
   2544     cblk_destroy(cblk);
   2545     return 0;
   2546 }
   2547 
   2548 static void cblk_destroy(jpc_enc_cblk_t *cblk)
   2549 {
   2550     uint_fast16_t passno;
   2551     jpc_enc_pass_t *pass;
   2552     if (cblk->passes) {
   2553         for (passno = 0, pass = cblk->passes; passno < cblk->numpasses;
   2554           ++passno, ++pass) {
   2555             pass_destroy(pass);
   2556         }
   2557         jas_free(cblk->passes);
   2558     }
   2559     if (cblk->stream) {
   2560         jas_stream_close(cblk->stream);
   2561     }
   2562     if (cblk->mqenc) {
   2563         jpc_mqenc_destroy(cblk->mqenc);
   2564     }
   2565     if (cblk->data) {
   2566         jas_seq2d_destroy(cblk->data);
   2567     }
   2568     if (cblk->flags) {
   2569         jas_seq2d_destroy(cblk->flags);
   2570     }
   2571 }
   2572 
   2573 static void pass_destroy(jpc_enc_pass_t *pass)
   2574 {
   2575     /* XXX - need to free resources here */
   2576 }
   2577 
   2578 void jpc_enc_dump(jpc_enc_t *enc)
   2579 {
   2580     jpc_enc_tile_t *tile;
   2581     jpc_enc_tcmpt_t *tcmpt;
   2582     jpc_enc_rlvl_t *rlvl;
   2583     jpc_enc_band_t *band;
   2584     jpc_enc_prc_t *prc;
   2585     jpc_enc_cblk_t *cblk;
   2586     uint_fast16_t cmptno;
   2587     uint_fast16_t rlvlno;
   2588     uint_fast16_t bandno;
   2589     uint_fast32_t prcno;
   2590     uint_fast32_t cblkno;
   2591 
   2592     tile = enc->curtile;
   2593 
   2594     for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno,
   2595       ++tcmpt) {
   2596         jas_eprintf("  tcmpt %5d %5d %5d %5d\n", jas_seq2d_xstart(tcmpt->data), jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data), jas_seq2d_yend(tcmpt->data));
   2597         for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
   2598           ++rlvlno, ++rlvl) {
   2599             jas_eprintf("    rlvl %5d %5d %5d %5d\n", rlvl->tlx, rlvl->tly, rlvl->brx, rlvl->bry);
   2600             for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
   2601               ++bandno, ++band) {
   2602                 if (!band->data) {
   2603                     continue;
   2604                 }
   2605                 jas_eprintf("      band %5d %5d %5d %5d\n", jas_seq2d_xstart(band->data), jas_seq2d_ystart(band->data), jas_seq2d_xend(band->data), jas_seq2d_yend(band->data));
   2606                 for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
   2607                   ++prcno, ++prc) {
   2608                     jas_eprintf("        prc %5d %5d %5d %5d (%5d %5d)\n", prc->tlx, prc->tly, prc->brx, prc->bry, prc->brx - prc->tlx, prc->bry - prc->tly);
   2609                     if (!prc->cblks) {
   2610                         continue;
   2611                     }
   2612                     for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
   2613                       ++cblkno, ++cblk) {
   2614                         jas_eprintf("         cblk %5d %5d %5d %5d\n", jas_seq2d_xstart(cblk->data), jas_seq2d_ystart(cblk->data), jas_seq2d_xend(cblk->data), jas_seq2d_yend(cblk->data));
   2615                     }
   2616                 }
   2617             }
   2618         }
   2619     }
   2620 }
   2621