jpc_enc.c 81.2 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * Copyright (c) 1999-2000 Image Power, Inc. and the University of
 *   British Columbia.
 * Copyright (c) 2001-2003 Michael David Adams.
 * All rights reserved.
 */

/* __START_OF_JASPER_LICENSE__
9
 *
10
 * JasPer License Version 2.0
11
 *
12 13 14
 * Copyright (c) 2001-2006 Michael David Adams
 * Copyright (c) 1999-2000 Image Power, Inc.
 * Copyright (c) 1999-2000 The University of British Columbia
15
 *
16
 * All rights reserved.
17
 *
18 19 20 21 22 23 24
 * Permission is hereby granted, free of charge, to any person (the
 * "User") obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the
 * following conditions:
25
 *
26 27 28
 * 1.  The above copyright notices and this permission notice (which
 * includes the disclaimer below) shall be included in all copies or
 * substantial portions of the Software.
29
 *
30 31 32
 * 2.  The name of a copyright holder shall not be used to endorse or
 * promote products derived from the Software without specific prior
 * written permission.
33
 *
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
 * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
 * LICENSE.  NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
 * THIS DISCLAIMER.  THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
 * "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.  IN NO
 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
 * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.  NO ASSURANCES ARE
 * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
 * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
 * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
 * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
 * PROPERTY RIGHTS OR OTHERWISE.  AS A CONDITION TO EXERCISING THE RIGHTS
 * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
 * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY.  THE SOFTWARE
 * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
 * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
 * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
 * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
 * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
 * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
 * RISK ACTIVITIES").  THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
 * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
60
 *
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
 * __END_OF_JASPER_LICENSE__
 */

/*
 * $Id: jpc_enc.c,v 1.2 2008-05-26 09:40:52 vp153 Exp $
 */

/******************************************************************************\
* Includes.
\******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <float.h>

#include "jasper/jas_types.h"
#include "jasper/jas_string.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_image.h"
#include "jasper/jas_fix.h"
#include "jasper/jas_tvp.h"
#include "jasper/jas_version.h"
#include "jasper/jas_math.h"
#include "jasper/jas_debug.h"

#include "jpc_flt.h"
#include "jpc_fix.h"
#include "jpc_tagtree.h"
#include "jpc_enc.h"
#include "jpc_cs.h"
#include "jpc_mct.h"
#include "jpc_tsfb.h"
#include "jpc_qmfb.h"
#include "jpc_t1enc.h"
#include "jpc_t2enc.h"
#include "jpc_cod.h"
#include "jpc_math.h"
#include "jpc_util.h"

/******************************************************************************\
*
\******************************************************************************/

#define JPC_POW2(n) \
107
    (1 << (n))
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169

#define JPC_FLOORTOMULTPOW2(x, n) \
  (((n) > 0) ? ((x) & (~((1 << n) - 1))) : (x))
/* Round to the nearest multiple of the specified power of two in the
  direction of negative infinity. */

#define	JPC_CEILTOMULTPOW2(x, n) \
  (((n) > 0) ? JPC_FLOORTOMULTPOW2(((x) + (1 << (n)) - 1), n) : (x))
/* Round to the nearest multiple of the specified power of two in the
  direction of positive infinity. */

#define	JPC_POW2(n)	\
  (1 << (n))

jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno);
void jpc_enc_tile_destroy(jpc_enc_tile_t *tile);

static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp,
  jas_image_t *image, jpc_enc_tile_t *tile);
static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt);
static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
  jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos);
static void rlvl_destroy(jpc_enc_rlvl_t *rlvl);
static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,
  jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos);
static void band_destroy(jpc_enc_band_t *bands);
static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp,
  jpc_enc_band_t *band);
static void prc_destroy(jpc_enc_prc_t *prcs);
static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp,
  jpc_enc_prc_t *prc);
static void cblk_destroy(jpc_enc_cblk_t *cblks);
int ratestrtosize(char *s, uint_fast32_t rawsize, uint_fast32_t *size);
static void pass_destroy(jpc_enc_pass_t *pass);
void jpc_enc_dump(jpc_enc_t *enc);

/******************************************************************************\
* Local prototypes.
\******************************************************************************/

int dump_passes(jpc_enc_pass_t *passes, int numpasses, jpc_enc_cblk_t *cblk);
void calcrdslopes(jpc_enc_cblk_t *cblk);
void dump_layeringinfo(jpc_enc_t *enc);
static int jpc_calcssexp(jpc_fix_t stepsize);
static int jpc_calcssmant(jpc_fix_t stepsize);
void jpc_quantize(jas_matrix_t *data, jpc_fix_t stepsize);
static int jpc_enc_encodemainhdr(jpc_enc_t *enc);
static int jpc_enc_encodemainbody(jpc_enc_t *enc);
int jpc_enc_encodetiledata(jpc_enc_t *enc);
jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image);
void jpc_enc_destroy(jpc_enc_t *enc);
static int jpc_enc_encodemainhdr(jpc_enc_t *enc);
static int jpc_enc_encodemainbody(jpc_enc_t *enc);
int jpc_enc_encodetiledata(jpc_enc_t *enc);
int rateallocate(jpc_enc_t *enc, int numlyrs, uint_fast32_t *cumlens);
int setins(int numvalues, jpc_flt_t *values, jpc_flt_t value);
static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image);
void jpc_enc_cp_destroy(jpc_enc_cp_t *cp);
static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn);

static uint_fast32_t jpc_abstorelstepsize(jpc_fix_t absdelta, int scaleexpn)
{
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    int p;
    uint_fast32_t mant;
    uint_fast32_t expn;
    int n;

    if (absdelta < 0) {
        abort();
    }

    p = jpc_firstone(absdelta) - JPC_FIX_FRACBITS;
    n = 11 - jpc_firstone(absdelta);
    mant = ((n < 0) ? (absdelta >> (-n)) : (absdelta << n)) & 0x7ff;
    expn = scaleexpn - p;
    if (scaleexpn < p) {
        abort();
    }
    return JPC_QCX_EXPN(expn) | JPC_QCX_MANT(mant);
187 188 189
}

typedef enum {
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    OPT_DEBUG,
    OPT_IMGAREAOFFX,
    OPT_IMGAREAOFFY,
    OPT_TILEGRDOFFX,
    OPT_TILEGRDOFFY,
    OPT_TILEWIDTH,
    OPT_TILEHEIGHT,
    OPT_PRCWIDTH,
    OPT_PRCHEIGHT,
    OPT_CBLKWIDTH,
    OPT_CBLKHEIGHT,
    OPT_MODE,
    OPT_PRG,
    OPT_NOMCT,
    OPT_MAXRLVLS,
    OPT_SOP,
    OPT_EPH,
    OPT_LAZY,
    OPT_TERMALL,
    OPT_SEGSYM,
    OPT_VCAUSAL,
    OPT_RESET,
    OPT_PTERM,
    OPT_NUMGBITS,
    OPT_RATE,
    OPT_ILYRRATES,
    OPT_JP2OVERHEAD
217 218 219
} optid_t;

jas_taginfo_t encopts[] = {
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    {OPT_DEBUG, "debug"},
    {OPT_IMGAREAOFFX, "imgareatlx"},
    {OPT_IMGAREAOFFY, "imgareatly"},
    {OPT_TILEGRDOFFX, "tilegrdtlx"},
    {OPT_TILEGRDOFFY, "tilegrdtly"},
    {OPT_TILEWIDTH, "tilewidth"},
    {OPT_TILEHEIGHT, "tileheight"},
    {OPT_PRCWIDTH, "prcwidth"},
    {OPT_PRCHEIGHT, "prcheight"},
    {OPT_CBLKWIDTH, "cblkwidth"},
    {OPT_CBLKHEIGHT, "cblkheight"},
    {OPT_MODE, "mode"},
    {OPT_PRG, "prg"},
    {OPT_NOMCT, "nomct"},
    {OPT_MAXRLVLS, "numrlvls"},
    {OPT_SOP, "sop"},
    {OPT_EPH, "eph"},
    {OPT_LAZY, "lazy"},
    {OPT_TERMALL, "termall"},
    {OPT_SEGSYM, "segsym"},
    {OPT_VCAUSAL, "vcausal"},
    {OPT_PTERM, "pterm"},
    {OPT_RESET, "resetprob"},
    {OPT_NUMGBITS, "numgbits"},
    {OPT_RATE, "rate"},
    {OPT_ILYRRATES, "ilyrrates"},
    {OPT_JP2OVERHEAD, "_jp2overhead"},
    {-1, 0}
248 249 250
};

typedef enum {
251 252
    PO_L = 0,
    PO_R
253 254 255 256
} poid_t;


jas_taginfo_t prgordtab[] = {
257 258 259 260 261 262
    {JPC_COD_LRCPPRG, "lrcp"},
    {JPC_COD_RLCPPRG, "rlcp"},
    {JPC_COD_RPCLPRG, "rpcl"},
    {JPC_COD_PCRLPRG, "pcrl"},
    {JPC_COD_CPRLPRG, "cprl"},
    {-1, 0}
263 264 265
};

typedef enum {
266 267
    MODE_INT,
    MODE_REAL
268 269 270
} modeid_t;

jas_taginfo_t modetab[] = {
271 272 273
    {MODE_INT, "int"},
    {MODE_REAL, "real"},
    {-1, 0}
274 275 276 277 278 279 280 281
};

/******************************************************************************\
* The main encoder entry point.
\******************************************************************************/

int jpc_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
{
282 283
    jpc_enc_t *enc;
    jpc_enc_cp_t *cp;
284

285 286
    enc = 0;
    cp = 0;
287

288
    jpc_initluts();
289

290 291 292 293
    if (!(cp = cp_create(optstr, image))) {
        jas_eprintf("invalid JP encoder options\n");
        goto error;
    }
294

295 296 297 298
    if (!(enc = jpc_enc_create(cp, out, image))) {
        goto error;
    }
    cp = 0;
299

300 301 302 303
    /* Encode the main header. */
    if (jpc_enc_encodemainhdr(enc)) {
        goto error;
    }
304

305 306 307 308
    /* Encode the main body.  This constitutes most of the encoding work. */
    if (jpc_enc_encodemainbody(enc)) {
        goto error;
    }
309

310 311 312 313 314 315 316 317 318 319
    /* Write EOC marker segment. */
    if (!(enc->mrk = jpc_ms_create(JPC_MS_EOC))) {
        goto error;
    }
    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
        jas_eprintf("cannot write EOI marker\n");
        goto error;
    }
    jpc_ms_destroy(enc->mrk);
    enc->mrk = 0;
320

321 322 323
    if (jas_stream_flush(enc->out)) {
        goto error;
    }
324

325
    jpc_enc_destroy(enc);
326

327
    return 0;
328 329

error:
330 331 332 333 334 335 336
    if (cp) {
        jpc_enc_cp_destroy(cp);
    }
    if (enc) {
        jpc_enc_destroy(enc);
    }
    return -1;
337 338 339 340 341 342 343 344
}

/******************************************************************************\
* Option parsing code.
\******************************************************************************/

static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image)
{
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
    jpc_enc_cp_t *cp;
    jas_tvparser_t *tvp;
    int ret;
    int numilyrrates;
    double *ilyrrates;
    int i;
    int tagid;
    jpc_enc_tcp_t *tcp;
    jpc_enc_tccp_t *tccp;
    jpc_enc_ccp_t *ccp;
    int cmptno;
    uint_fast16_t rlvlno;
    uint_fast16_t prcwidthexpn;
    uint_fast16_t prcheightexpn;
    bool enablemct;
    uint_fast32_t jp2overhead;
    uint_fast16_t lyrno;
    uint_fast32_t hsteplcm;
    uint_fast32_t vsteplcm;
    bool mctvalid;

    tvp = 0;
    cp = 0;
    ilyrrates = 0;
    numilyrrates = 0;

    if (!(cp = jas_malloc(sizeof(jpc_enc_cp_t)))) {
        goto error;
    }

    prcwidthexpn = 15;
    prcheightexpn = 15;
    enablemct = true;
    jp2overhead = 0;

    cp->ccps = 0;
    cp->debug = 0;
    cp->imgareatlx = UINT_FAST32_MAX;
    cp->imgareatly = UINT_FAST32_MAX;
    cp->refgrdwidth = 0;
    cp->refgrdheight = 0;
    cp->tilegrdoffx = UINT_FAST32_MAX;
    cp->tilegrdoffy = UINT_FAST32_MAX;
    cp->tilewidth = 0;
    cp->tileheight = 0;
    cp->numcmpts = jas_image_numcmpts(image);

    hsteplcm = 1;
    vsteplcm = 1;
    for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
        if (jas_image_cmptbrx(image, cmptno) + jas_image_cmpthstep(image, cmptno) <=
          jas_image_brx(image) || jas_image_cmptbry(image, cmptno) +
          jas_image_cmptvstep(image, cmptno) <= jas_image_bry(image)) {
            jas_eprintf("unsupported image type\n");
            goto error;
        }
        /* Note: We ought to be calculating the LCMs here.  Fix some day. */
        hsteplcm *= jas_image_cmpthstep(image, cmptno);
        vsteplcm *= jas_image_cmptvstep(image, cmptno);
    }

    if (!(cp->ccps = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_ccp_t)))) {
        goto error;
    }
    for (cmptno = 0, ccp = cp->ccps; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno,
      ++ccp) {
        ccp->sampgrdstepx = jas_image_cmpthstep(image, cmptno);
        ccp->sampgrdstepy = jas_image_cmptvstep(image, cmptno);
        /* XXX - this isn't quite correct for more general image */
        ccp->sampgrdsubstepx = 0;
        ccp->sampgrdsubstepx = 0;
        ccp->prec = jas_image_cmptprec(image, cmptno);
        ccp->sgnd = jas_image_cmptsgnd(image, cmptno);
        ccp->numstepsizes = 0;
        memset(ccp->stepsizes, 0, sizeof(ccp->stepsizes));
    }

    cp->rawsize = jas_image_rawsize(image);
    cp->totalsize = UINT_FAST32_MAX;

    tcp = &cp->tcp;
    tcp->csty = 0;
    tcp->intmode = true;
    tcp->prg = JPC_COD_LRCPPRG;
    tcp->numlyrs = 1;
    tcp->ilyrrates = 0;

    tccp = &cp->tccp;
    tccp->csty = 0;
    tccp->maxrlvls = 6;
    tccp->cblkwidthexpn = 6;
    tccp->cblkheightexpn = 6;
    tccp->cblksty = 0;
    tccp->numgbits = 2;

    if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
        goto error;
    }

    while (!(ret = jas_tvparser_next(tvp))) {
        switch (jas_taginfo_nonull(jas_taginfos_lookup(encopts,
          jas_tvparser_gettag(tvp)))->id) {
        case OPT_DEBUG:
            cp->debug = atoi(jas_tvparser_getval(tvp));
            break;
        case OPT_IMGAREAOFFX:
            cp->imgareatlx = atoi(jas_tvparser_getval(tvp));
            break;
        case OPT_IMGAREAOFFY:
            cp->imgareatly = atoi(jas_tvparser_getval(tvp));
            break;
        case OPT_TILEGRDOFFX:
            cp->tilegrdoffx = atoi(jas_tvparser_getval(tvp));
            break;
        case OPT_TILEGRDOFFY:
            cp->tilegrdoffy = atoi(jas_tvparser_getval(tvp));
            break;
        case OPT_TILEWIDTH:
            cp->tilewidth = atoi(jas_tvparser_getval(tvp));
            break;
        case OPT_TILEHEIGHT:
            cp->tileheight = atoi(jas_tvparser_getval(tvp));
            break;
        case OPT_PRCWIDTH:
            prcwidthexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
            break;
        case OPT_PRCHEIGHT:
            prcheightexpn = jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
            break;
        case OPT_CBLKWIDTH:
            tccp->cblkwidthexpn =
              jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
            break;
        case OPT_CBLKHEIGHT:
            tccp->cblkheightexpn =
              jpc_floorlog2(atoi(jas_tvparser_getval(tvp)));
            break;
        case OPT_MODE:
            if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(modetab,
              jas_tvparser_getval(tvp)))->id) < 0) {
                jas_eprintf("ignoring invalid mode %s\n",
                  jas_tvparser_getval(tvp));
            } else {
                tcp->intmode = (tagid == MODE_INT);
            }
            break;
        case OPT_PRG:
            if ((tagid = jas_taginfo_nonull(jas_taginfos_lookup(prgordtab,
              jas_tvparser_getval(tvp)))->id) < 0) {
                jas_eprintf("ignoring invalid progression order %s\n",
                  jas_tvparser_getval(tvp));
            } else {
                tcp->prg = tagid;
            }
            break;
        case OPT_NOMCT:
            enablemct = false;
            break;
        case OPT_MAXRLVLS:
            tccp->maxrlvls = atoi(jas_tvparser_getval(tvp));
            break;
        case OPT_SOP:
            cp->tcp.csty |= JPC_COD_SOP;
            break;
        case OPT_EPH:
            cp->tcp.csty |= JPC_COD_EPH;
            break;
        case OPT_LAZY:
            tccp->cblksty |= JPC_COX_LAZY;
            break;
        case OPT_TERMALL:
            tccp->cblksty |= JPC_COX_TERMALL;
            break;
        case OPT_SEGSYM:
            tccp->cblksty |= JPC_COX_SEGSYM;
            break;
        case OPT_VCAUSAL:
            tccp->cblksty |= JPC_COX_VSC;
            break;
        case OPT_RESET:
            tccp->cblksty |= JPC_COX_RESET;
            break;
        case OPT_PTERM:
            tccp->cblksty |= JPC_COX_PTERM;
            break;
        case OPT_NUMGBITS:
            cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));
            break;
        case OPT_RATE:
            if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
              &cp->totalsize)) {
                jas_eprintf("ignoring bad rate specifier %s\n",
                  jas_tvparser_getval(tvp));
            }
            break;
        case OPT_ILYRRATES:
            if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,
              &ilyrrates)) {
                jas_eprintf("warning: invalid intermediate layer rates specifier ignored (%s)\n",
                  jas_tvparser_getval(tvp));
            }
            break;

        case OPT_JP2OVERHEAD:
            jp2overhead = atoi(jas_tvparser_getval(tvp));
            break;
        default:
            jas_eprintf("warning: ignoring invalid option %s\n",
             jas_tvparser_gettag(tvp));
            break;
        }
    }

    jas_tvparser_destroy(tvp);
    tvp = 0;

    if (cp->totalsize != UINT_FAST32_MAX) {
        cp->totalsize = (cp->totalsize > jp2overhead) ?
          (cp->totalsize - jp2overhead) : 0;
    }

    if (cp->imgareatlx == UINT_FAST32_MAX) {
        cp->imgareatlx = 0;
    } else {
        if (hsteplcm != 1) {
            jas_eprintf("warning: overriding imgareatlx value\n");
        }
        cp->imgareatlx *= hsteplcm;
    }
    if (cp->imgareatly == UINT_FAST32_MAX) {
        cp->imgareatly = 0;
    } else {
        if (vsteplcm != 1) {
            jas_eprintf("warning: overriding imgareatly value\n");
        }
        cp->imgareatly *= vsteplcm;
    }
    cp->refgrdwidth = cp->imgareatlx + jas_image_width(image);
    cp->refgrdheight = cp->imgareatly + jas_image_height(image);
    if (cp->tilegrdoffx == UINT_FAST32_MAX) {
        cp->tilegrdoffx = cp->imgareatlx;
    }
    if (cp->tilegrdoffy == UINT_FAST32_MAX) {
        cp->tilegrdoffy = cp->imgareatly;
    }
    if (!cp->tilewidth) {
        cp->tilewidth = cp->refgrdwidth - cp->tilegrdoffx;
    }
    if (!cp->tileheight) {
        cp->tileheight = cp->refgrdheight - cp->tilegrdoffy;
    }

    if (cp->numcmpts == 3) {
        mctvalid = true;
        for (cmptno = 0; cmptno < jas_image_numcmpts(image); ++cmptno) {
            if (jas_image_cmptprec(image, cmptno) != jas_image_cmptprec(image, 0) ||
              jas_image_cmptsgnd(image, cmptno) != jas_image_cmptsgnd(image, 0) ||
              jas_image_cmptwidth(image, cmptno) != jas_image_cmptwidth(image, 0) ||
              jas_image_cmptheight(image, cmptno) != jas_image_cmptheight(image, 0)) {
                mctvalid = false;
            }
        }
    } else {
        mctvalid = false;
    }
    if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) != JAS_CLRSPC_FAM_RGB) {
        jas_eprintf("warning: color space apparently not RGB\n");
    }
    if (mctvalid && enablemct && jas_clrspc_fam(jas_image_clrspc(image)) == JAS_CLRSPC_FAM_RGB) {
        tcp->mctid = (tcp->intmode) ? (JPC_MCT_RCT) : (JPC_MCT_ICT);
    } else {
        tcp->mctid = JPC_MCT_NONE;
    }
    tccp->qmfbid = (tcp->intmode) ? (JPC_COX_RFT) : (JPC_COX_INS);

    for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
        tccp->prcwidthexpns[rlvlno] = prcwidthexpn;
        tccp->prcheightexpns[rlvlno] = prcheightexpn;
    }
    if (prcwidthexpn != 15 || prcheightexpn != 15) {
        tccp->csty |= JPC_COX_PRT;
    }

    /* Ensure that the tile width and height is valid. */
    if (!cp->tilewidth) {
        jas_eprintf("invalid tile width %lu\n", (unsigned long)
          cp->tilewidth);
        goto error;
    }
    if (!cp->tileheight) {
        jas_eprintf("invalid tile height %lu\n", (unsigned long)
          cp->tileheight);
        goto error;
    }

    /* Ensure that the tile grid offset is valid. */
    if (cp->tilegrdoffx > cp->imgareatlx ||
      cp->tilegrdoffy > cp->imgareatly ||
      cp->tilegrdoffx + cp->tilewidth < cp->imgareatlx ||
      cp->tilegrdoffy + cp->tileheight < cp->imgareatly) {
        jas_eprintf("invalid tile grid offset (%lu, %lu)\n",
          (unsigned long) cp->tilegrdoffx, (unsigned long)
          cp->tilegrdoffy);
        goto error;
    }

    cp->numhtiles = JPC_CEILDIV(cp->refgrdwidth - cp->tilegrdoffx,
      cp->tilewidth);
    cp->numvtiles = JPC_CEILDIV(cp->refgrdheight - cp->tilegrdoffy,
      cp->tileheight);
    cp->numtiles = cp->numhtiles * cp->numvtiles;

    if (ilyrrates && numilyrrates > 0) {
        tcp->numlyrs = numilyrrates + 1;
        if (!(tcp->ilyrrates = jas_alloc2((tcp->numlyrs - 1),
          sizeof(jpc_fix_t)))) {
            goto error;
        }
        for (i = 0; i < JAS_CAST(int, tcp->numlyrs - 1); ++i) {
            tcp->ilyrrates[i] = jpc_dbltofix(ilyrrates[i]);
        }
    }

    /* Ensure that the integer mode is used in the case of lossless
      coding. */
    if (cp->totalsize == UINT_FAST32_MAX && (!cp->tcp.intmode)) {
        jas_eprintf("cannot use real mode for lossless coding\n");
        goto error;
    }

    /* Ensure that the precinct width is valid. */
    if (prcwidthexpn > 15) {
        jas_eprintf("invalid precinct width\n");
        goto error;
    }

    /* Ensure that the precinct height is valid. */
    if (prcheightexpn > 15) {
        jas_eprintf("invalid precinct height\n");
        goto error;
    }

    /* Ensure that the code block width is valid. */
    if (cp->tccp.cblkwidthexpn < 2 || cp->tccp.cblkwidthexpn > 12) {
        jas_eprintf("invalid code block width %d\n",
          JPC_POW2(cp->tccp.cblkwidthexpn));
        goto error;
    }

    /* Ensure that the code block height is valid. */
    if (cp->tccp.cblkheightexpn < 2 || cp->tccp.cblkheightexpn > 12) {
        jas_eprintf("invalid code block height %d\n",
          JPC_POW2(cp->tccp.cblkheightexpn));
        goto error;
    }

    /* Ensure that the code block size is not too large. */
    if (cp->tccp.cblkwidthexpn + cp->tccp.cblkheightexpn > 12) {
        jas_eprintf("code block size too large\n");
        goto error;
    }

    /* Ensure that the number of layers is valid. */
    if (cp->tcp.numlyrs > 16384) {
        jas_eprintf("too many layers\n");
        goto error;
    }

    /* There must be at least one resolution level. */
    if (cp->tccp.maxrlvls < 1) {
        jas_eprintf("must be at least one resolution level\n");
        goto error;
    }

    /* Ensure that the number of guard bits is valid. */
    if (cp->tccp.numgbits > 8) {
        jas_eprintf("invalid number of guard bits\n");
        goto error;
    }

    /* Ensure that the rate is within the legal range. */
    if (cp->totalsize != UINT_FAST32_MAX && cp->totalsize > cp->rawsize) {
        jas_eprintf("warning: specified rate is unreasonably large (%lu > %lu)\n", (unsigned long) cp->totalsize, (unsigned long) cp->rawsize);
    }

    /* Ensure that the intermediate layer rates are valid. */
    if (tcp->numlyrs > 1) {
        /* The intermediate layers rates must increase monotonically. */
        for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {
            if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {
                jas_eprintf("intermediate layer rates must increase monotonically\n");
                goto error;
            }
        }
        /* The intermediate layer rates must be less than the overall rate. */
        if (cp->totalsize != UINT_FAST32_MAX) {
            for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) {
                if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) > ((double) cp->totalsize)
                  / cp->rawsize) {
                    jas_eprintf("warning: intermediate layer rates must be less than overall rate\n");
                    goto error;
                }
            }
        }
    }

    if (ilyrrates) {
        jas_free(ilyrrates);
    }

    return cp;
756 757 758

error:

759 760 761 762 763 764 765 766 767 768
    if (ilyrrates) {
        jas_free(ilyrrates);
    }
    if (tvp) {
        jas_tvparser_destroy(tvp);
    }
    if (cp) {
        jpc_enc_cp_destroy(cp);
    }
    return 0;
769 770 771 772
}

void jpc_enc_cp_destroy(jpc_enc_cp_t *cp)
{
773 774 775 776 777 778 779
    if (cp->ccps) {
        if (cp->tcp.ilyrrates) {
            jas_free(cp->tcp.ilyrrates);
        }
        jas_free(cp->ccps);
    }
    jas_free(cp);
780 781 782 783
}

int ratestrtosize(char *s, uint_fast32_t rawsize, uint_fast32_t *size)
{
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
    char *cp;
    jpc_flt_t f;

    /* Note: This function must not modify output size on failure. */
    if ((cp = strchr(s, 'B'))) {
        *size = atoi(s);
    } else {
        f = atof(s);
        if (f < 0) {
            *size = 0;
        } else if (f > 1.0) {
            *size = rawsize + 1;
        } else {
            *size = f * rawsize;
        }
    }
    return 0;
801 802 803 804 805 806 807 808
}

/******************************************************************************\
* Encoder constructor and destructor.
\******************************************************************************/

jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image)
{
809
    jpc_enc_t *enc;
810

811
    enc = 0;
812

813 814 815
    if (!(enc = jas_malloc(sizeof(jpc_enc_t)))) {
        goto error;
    }
816

817 818 819 820 821 822 823
    enc->image = image;
    enc->out = out;
    enc->cp = cp;
    enc->cstate = 0;
    enc->tmpstream = 0;
    enc->mrk = 0;
    enc->curtile = 0;
824

825 826 827 828 829
    if (!(enc->cstate = jpc_cstate_create())) {
        goto error;
    }
    enc->len = 0;
    enc->mainbodysize = 0;
830

831
    return enc;
832 833 834

error:

835 836 837 838
    if (enc) {
        jpc_enc_destroy(enc);
    }
    return 0;
839 840 841 842
}

void jpc_enc_destroy(jpc_enc_t *enc)
{
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
    /* The image object (i.e., enc->image) and output stream object
    (i.e., enc->out) are created outside of the encoder.
    Therefore, they must not be destroyed here. */

    if (enc->curtile) {
        jpc_enc_tile_destroy(enc->curtile);
    }
    if (enc->cp) {
        jpc_enc_cp_destroy(enc->cp);
    }
    if (enc->cstate) {
        jpc_cstate_destroy(enc->cstate);
    }
    if (enc->tmpstream) {
        jas_stream_close(enc->tmpstream);
    }

    jas_free(enc);
861 862 863 864 865 866 867 868
}

/******************************************************************************\
* Code.
\******************************************************************************/

static int jpc_calcssmant(jpc_fix_t stepsize)
{
869 870 871 872 873 874 875 876 877 878 879 880
    int n;
    int e;
    int m;

    n = jpc_firstone(stepsize);
    e = n - JPC_FIX_FRACBITS;
    if (n >= 11) {
        m = (stepsize >> (n - 11)) & 0x7ff;
    } else {
        m = (stepsize & ((1 << n) - 1)) << (11 - n);
    }
    return m;
881 882 883 884
}

static int jpc_calcssexp(jpc_fix_t stepsize)
{
885
    return jpc_firstone(stepsize) - JPC_FIX_FRACBITS;
886 887 888 889
}

static int jpc_enc_encodemainhdr(jpc_enc_t *enc)
{
890 891 892 893
    jpc_siz_t *siz;
    jpc_cod_t *cod;
    jpc_qcd_t *qcd;
    int i;
894 895
long startoff;
long mainhdrlen;
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    jpc_enc_cp_t *cp;
    jpc_qcc_t *qcc;
    jpc_enc_tccp_t *tccp;
    uint_fast16_t cmptno;
    jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
    jpc_fix_t mctsynweight;
    jpc_enc_tcp_t *tcp;
    jpc_tsfb_t *tsfb;
    jpc_tsfb_band_t *bandinfo;
    uint_fast16_t numbands;
    uint_fast16_t bandno;
    uint_fast16_t rlvlno;
    uint_fast16_t analgain;
    jpc_fix_t absstepsize;
    char buf[1024];
    jpc_com_t *com;

    cp = enc->cp;
914 915 916

startoff = jas_stream_getrwcount(enc->out);

917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
    /* Write SOC marker segment. */
    if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {
        return -1;
    }
    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
        jas_eprintf("cannot write SOC marker\n");
        return -1;
    }
    jpc_ms_destroy(enc->mrk);
    enc->mrk = 0;

    /* Write SIZ marker segment. */
    if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {
        return -1;
    }
    siz = &enc->mrk->parms.siz;
    siz->caps = 0;
    siz->xoff = cp->imgareatlx;
    siz->yoff = cp->imgareatly;
    siz->width = cp->refgrdwidth;
    siz->height = cp->refgrdheight;
    siz->tilexoff = cp->tilegrdoffx;
    siz->tileyoff = cp->tilegrdoffy;
    siz->tilewidth = cp->tilewidth;
    siz->tileheight = cp->tileheight;
    siz->numcomps = cp->numcmpts;
    siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t));
    assert(siz->comps);
    for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {
        siz->comps[i].prec = cp->ccps[i].prec;
        siz->comps[i].sgnd = cp->ccps[i].sgnd;
        siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;
        siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;
    }
    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
        jas_eprintf("cannot write SIZ marker\n");
        return -1;
    }
    jpc_ms_destroy(enc->mrk);
    enc->mrk = 0;

    if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {
        return -1;
    }
    sprintf(buf, "Creator: JasPer Version %s", jas_getversion());
    com = &enc->mrk->parms.com;
    com->len = strlen(buf);
    com->regid = JPC_COM_LATIN;
    if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) {
        abort();
    }
    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
        jas_eprintf("cannot write COM marker\n");
        return -1;
    }
    jpc_ms_destroy(enc->mrk);
    enc->mrk = 0;
974 975

#if 0
976 977 978 979 980 981 982 983 984 985 986
    if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {
        return -1;
    }
    crg = &enc->mrk->parms.crg;
    crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t));
    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
        jas_eprintf("cannot write CRG marker\n");
        return -1;
    }
    jpc_ms_destroy(enc->mrk);
    enc->mrk = 0;
987 988
#endif

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    tcp = &cp->tcp;
    tccp = &cp->tccp;
    for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
        tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);
        jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,
          bandinfos);
        jpc_tsfb_destroy(tsfb);
        mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno);
        numbands = 3 * tccp->maxrlvls - 2;
        for (bandno = 0, bandinfo = bandinfos; bandno < numbands;
          ++bandno, ++bandinfo) {
            rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;
            analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,
              rlvlno, bandinfo->orient);
            if (!tcp->intmode) {
                absstepsize = jpc_fix_div(jpc_inttofix(1 <<
                  (analgain + 1)), bandinfo->synenergywt);
            } else {
                absstepsize = jpc_inttofix(1);
            }
            cp->ccps[cmptno].stepsizes[bandno] =
              jpc_abstorelstepsize(absstepsize,
              cp->ccps[cmptno].prec + analgain);
        }
        cp->ccps[cmptno].numstepsizes = numbands;
    }

    if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
        return -1;
    }
    cod = &enc->mrk->parms.cod;
    cod->csty = cp->tccp.csty | cp->tcp.csty;
    cod->compparms.csty = cp->tccp.csty | cp->tcp.csty;
    cod->compparms.numdlvls = cp->tccp.maxrlvls - 1;
    cod->compparms.numrlvls = cp->tccp.maxrlvls;
    cod->prg = cp->tcp.prg;
    cod->numlyrs = cp->tcp.numlyrs;
    cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);
    cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);
    cod->compparms.cblksty = cp->tccp.cblksty;
    cod->compparms.qmfbid = cp->tccp.qmfbid;
    cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);
    if (tccp->csty & JPC_COX_PRT) {
        for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
            cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno];
            cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno];
        }
    }
    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
        jas_eprintf("cannot write COD marker\n");
        return -1;
    }
    jpc_ms_destroy(enc->mrk);
    enc->mrk = 0;

    if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {
        return -1;
    }
    qcd = &enc->mrk->parms.qcd;
    qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
      JPC_QCX_SEQNT : JPC_QCX_NOQNT;
    qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;
    qcd->compparms.numguard = cp->tccp.numgbits;
    qcd->compparms.stepsizes = cp->ccps[0].stepsizes;
    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
        return -1;
    }
    /* We do not want the step size array to be freed! */
    qcd->compparms.stepsizes = 0;
    jpc_ms_destroy(enc->mrk);
    enc->mrk = 0;

    tccp = &cp->tccp;
    for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {
        if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
            return -1;
        }
        qcc = &enc->mrk->parms.qcc;
        qcc->compno = cmptno;
        qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
          JPC_QCX_SEQNT : JPC_QCX_NOQNT;
        qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;
        qcc->compparms.numguard = cp->tccp.numgbits;
        qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;
        if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
            return -1;
        }
        /* We do not want the step size array to be freed! */
        qcc->compparms.stepsizes = 0;
        jpc_ms_destroy(enc->mrk);
        enc->mrk = 0;
    }
1081 1082

#define MAINTLRLEN	2
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
    enc->len += mainhdrlen;
    if (enc->cp->totalsize != UINT_FAST32_MAX) {
        uint_fast32_t overhead;
        overhead = mainhdrlen + MAINTLRLEN;
        enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
          (enc->cp->totalsize - overhead) : 0;
    } else {
        enc->mainbodysize = UINT_FAST32_MAX;
    }

    return 0;
1095 1096 1097 1098
}

static int jpc_enc_encodemainbody(jpc_enc_t *enc)
{
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    int tileno;
    int tilex;
    int tiley;
    int i;
    jpc_sot_t *sot;
    jpc_enc_tcmpt_t *comp;
    jpc_enc_tcmpt_t *endcomps;
    jpc_enc_band_t *band;
    jpc_enc_band_t *endbands;
    jpc_enc_rlvl_t *lvl;
    int rlvlno;
    jpc_qcc_t *qcc;
    jpc_cod_t *cod;
    int adjust;
    int j;
    int absbandno;
    long numbytes;
    long tilehdrlen;
    long tilelen;
    jpc_enc_tile_t *tile;
    jpc_enc_cp_t *cp;
    double rho;
    int lyrno;
    int cmptno;
    int samestepsizes;
    jpc_enc_ccp_t *ccps;
    jpc_enc_tccp_t *tccp;
1126 1127 1128 1129 1130 1131 1132 1133 1134
int bandno;
uint_fast32_t x;
uint_fast32_t y;
int mingbits;
int actualnumbps;
jpc_fix_t mxmag;
jpc_fix_t mag;
int numgbits;

1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
    cp = enc->cp;

    /* Avoid compile warnings. */
    numbytes = 0;

    for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) {
        tilex = tileno % cp->numhtiles;
        tiley = tileno / cp->numhtiles;

        if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno))) {
            abort();
        }

        tile = enc->curtile;

        if (jas_getdbglevel() >= 10) {
            jpc_enc_dump(enc);
        }

        endcomps = &tile->tcmpts[tile->numtcmpts];
        for (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) {
            if (!cp->ccps[cmptno].sgnd) {
                adjust = 1 << (cp->ccps[cmptno].prec - 1);
                for (i = 0; i < jas_matrix_numrows(comp->data); ++i) {
                    for (j = 0; j < jas_matrix_numcols(comp->data); ++j) {
                        *jas_matrix_getref(comp->data, i, j) -= adjust;
                    }
                }
            }
        }

        if (!tile->intmode) {
                endcomps = &tile->tcmpts[tile->numtcmpts];
                for (comp = tile->tcmpts; comp != endcomps; ++comp) {
                    jas_matrix_asl(comp->data, JPC_FIX_FRACBITS);
                }
        }

        switch (tile->mctid) {
        case JPC_MCT_RCT:
1175
assert(jas_image_numcmpts(enc->image) == 3);
1176 1177 1178 1179
            jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data,
              tile->tcmpts[2].data);
            break;
        case JPC_MCT_ICT:
1180
assert(jas_image_numcmpts(enc->image) == 3);
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
            jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data,
              tile->tcmpts[2].data);
            break;
        default:
            break;
        }

        for (i = 0; i < jas_image_numcmpts(enc->image); ++i) {
            comp = &tile->tcmpts[i];
            jpc_tsfb_analyze(comp->tsfb, comp->data);

        }


        endcomps = &tile->tcmpts[tile->numtcmpts];
        for (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) {
            mingbits = 0;
            absbandno = 0;
            /* All bands must have a corresponding quantizer step size,
              even if they contain no samples and are never coded. */
            /* Some bands may not be hit by the loop below, so we must
              initialize all of the step sizes to a sane value. */
            memset(comp->stepsizes, 0, sizeof(comp->stepsizes));
            for (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) {
                if (!lvl->bands) {
                    absbandno += rlvlno ? 3 : 1;
                    continue;
                }
                endbands = &lvl->bands[lvl->numbands];
                for (band = lvl->bands; band != endbands; ++band) {
                    if (!band->data) {
                        ++absbandno;
                        continue;
                    }
                    actualnumbps = 0;
                    mxmag = 0;
                    for (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) {
                        for (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) {
                            mag = abs(jas_matrix_get(band->data, y, x));
                            if (mag > mxmag) {
                                mxmag = mag;
                            }
                        }
                    }
                    if (tile->intmode) {
                        actualnumbps = jpc_firstone(mxmag) + 1;
                    } else {
                        actualnumbps = jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;
                    }
                    numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 +
                      band->analgain);
1232 1233 1234
#if 0
jas_eprintf("%d %d mag=%d actual=%d numgbits=%d\n", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits);
#endif
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
                    if (numgbits > mingbits) {
                        mingbits = numgbits;
                    }
                    if (!tile->intmode) {
                        band->absstepsize = jpc_fix_div(jpc_inttofix(1
                          << (band->analgain + 1)),
                          band->synweight);
                    } else {
                        band->absstepsize = jpc_inttofix(1);
                    }
                    band->stepsize = jpc_abstorelstepsize(
                      band->absstepsize, cp->ccps[cmptno].prec +
                      band->analgain);
                    band->numbps = cp->tccp.numgbits +
                      JPC_QCX_GETEXPN(band->stepsize) - 1;

                    if ((!tile->intmode) && band->data) {
                        jpc_quantize(band->data, band->absstepsize);
                    }

                    comp->stepsizes[absbandno] = band->stepsize;
                    ++absbandno;
                }
            }

            assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);
            if (!tile->intmode) {
                jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);
            } else {
                jas_matrix_asl(comp->data, JPC_NUMEXTRABITS);
            }
1266 1267 1268 1269

#if 0
jas_eprintf("mingbits %d\n", mingbits);
#endif
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
            if (mingbits > cp->tccp.numgbits) {
                jas_eprintf("error: too few guard bits (need at least %d)\n",
                  mingbits);
                return -1;
            }
        }

        if (!(enc->tmpstream = jas_stream_memopen(0, 0))) {
            jas_eprintf("cannot open tmp file\n");
            return -1;
        }

        /* Write the tile header. */
        if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) {
            return -1;
        }
        sot = &enc->mrk->parms.sot;
        sot->len = 0;
        sot->tileno = tileno;
        sot->partno = 0;
        sot->numparts = 1;
        if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
            jas_eprintf("cannot write SOT marker\n");
            return -1;
        }
        jpc_ms_destroy(enc->mrk);
        enc->mrk = 0;
1297 1298 1299 1300 1301

/************************************************************************/
/************************************************************************/
/************************************************************************/

1302 1303 1304 1305 1306 1307 1308
        tccp = &cp->tccp;
        for (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) {
            comp = &tile->tcmpts[cmptno];
            if (comp->numrlvls != tccp->maxrlvls) {
                if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
                    return -1;
                }
1309 1310
/* XXX = this is not really correct. we are using comp #0's precint sizes
and other characteristics */
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
                comp = &tile->tcmpts[0];
                cod = &enc->mrk->parms.cod;
                cod->compparms.csty = 0;
                cod->compparms.numdlvls = comp->numrlvls - 1;
                cod->prg = tile->prg;
                cod->numlyrs = tile->numlyrs;
                cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn);
                cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn);
                cod->compparms.cblksty = comp->cblksty;
                cod->compparms.qmfbid = comp->qmfbid;
                cod->mctrans = (tile->mctid != JPC_MCT_NONE);
                for (i = 0; i < comp->numrlvls; ++i) {
                    cod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn;
                    cod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn;
                }
                if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
                    return -1;
                }
                jpc_ms_destroy(enc->mrk);
                enc->mrk = 0;
            }
        }

        for (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno, ++comp) {
            ccps = &cp->ccps[cmptno];
            if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) {
                samestepsizes = 1;
                for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes); ++bandno) {
                    if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {
                        samestepsizes = 0;
                        break;
                    }
                }
            } else {
                samestepsizes = 0;
            }
            if (!samestepsizes) {
                if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
                    return -1;
                }
                qcc = &enc->mrk->parms.qcc;
                qcc->compno = cmptno;
                qcc->compparms.numguard = cp->tccp.numgbits;
                qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?
                  JPC_QCX_SEQNT : JPC_QCX_NOQNT;
                qcc->compparms.numstepsizes = comp->numstepsizes;
                qcc->compparms.stepsizes = comp->stepsizes;
                if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
                    return -1;
                }
                qcc->compparms.stepsizes = 0;
                jpc_ms_destroy(enc->mrk);
                enc->mrk = 0;
            }
        }

        /* Write a SOD marker to indicate the end of the tile header. */
        if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {
            return -1;
        }
        if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
            jas_eprintf("cannot write SOD marker\n");
            return -1;
        }
        jpc_ms_destroy(enc->mrk);
        enc->mrk = 0;
1377 1378 1379 1380 1381 1382 1383
tilehdrlen = jas_stream_getrwcount(enc->tmpstream);

/************************************************************************/
/************************************************************************/
/************************************************************************/

if (jpc_enc_enccblks(enc)) {
1384 1385
    abort();
    return -1;
1386 1387
}

1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
        cp = enc->cp;
        rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) /
          ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -
          cp->imgareatly));
        tile->rawsize = cp->rawsize * rho;

        for (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) {
            tile->lyrsizes[lyrno] = tile->rawsize * jpc_fixtodbl(
              cp->tcp.ilyrrates[lyrno]);
        }
        tile->lyrsizes[tile->numlyrs - 1] = (cp->totalsize != UINT_FAST32_MAX) ?
          (rho * enc->mainbodysize) : UINT_FAST32_MAX;
        for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
            if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) {
                if (tilehdrlen <= JAS_CAST(long, tile->lyrsizes[lyrno])) {
                    tile->lyrsizes[lyrno] -= tilehdrlen;
                } else {
                    tile->lyrsizes[lyrno] = 0;
                }
            }
        }

        if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) {
            return -1;
        }
1413 1414 1415 1416

#if 0
jas_eprintf("ENCODE TILE DATA\n");
#endif
1417 1418 1419 1420
        if (jpc_enc_encodetiledata(enc)) {
            jas_eprintf("dotile failed\n");
            return -1;
        }
1421 1422 1423 1424 1425 1426 1427 1428 1429

/************************************************************************/
/************************************************************************/
/************************************************************************/

/************************************************************************/
/************************************************************************/
/************************************************************************/

1430
        tilelen = jas_stream_tell(enc->tmpstream);
1431

1432 1433 1434 1435
        if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {
            return -1;
        }
        jpc_putuint32(enc->tmpstream, tilelen);
1436

1437 1438 1439 1440 1441 1442 1443
        if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {
            return -1;
        }
        if (jpc_putdata(enc->out, enc->tmpstream, -1)) {
            return -1;
        }
        enc->len += tilelen;
1444

1445 1446
        jas_stream_close(enc->tmpstream);
        enc->tmpstream = 0;
1447

1448 1449
        jpc_enc_tile_destroy(enc->curtile);
        enc->curtile = 0;
1450

1451
    }
1452

1453
    return 0;
1454 1455 1456 1457 1458
}

int jpc_enc_encodetiledata(jpc_enc_t *enc)
{
assert(enc->tmpstream);
1459 1460 1461 1462
    if (jpc_enc_encpkts(enc, enc->tmpstream)) {
        return -1;
    }
    return 0;
1463 1464 1465 1466
}

int dump_passes(jpc_enc_pass_t *passes, int numpasses, jpc_enc_cblk_t *cblk)
{
1467 1468 1469
    jpc_enc_pass_t *pass;
    int i;
    jas_stream_memobj_t *smo;
1470

1471
    smo = cblk->stream->obj_;
1472

1473 1474 1475 1476 1477
    pass = passes;
    for (i = 0; i < numpasses; ++i) {
        jas_eprintf("start=%d end=%d type=%d term=%d lyrno=%d firstchar=%02x size=%ld pos=%ld\n",
          (int)pass->start, (int)pass->end, (int)pass->type, (int)pass->term, (int)pass->lyrno,
          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 1482 1483
        ++pass;
    }
    return 0;
1484 1485 1486 1487
}

void jpc_quantize(jas_matrix_t *data, jpc_fix_t stepsize)
{
1488 1489 1490
    int i;
    int j;
    jpc_fix_t t;
1491

1492 1493 1494
    if (stepsize == jpc_inttofix(1)) {
        return;
    }
1495

1496 1497 1498
    for (i = 0; i < jas_matrix_numrows(data); ++i) {
        for (j = 0; j < jas_matrix_numcols(data); ++j) {
            t = jas_matrix_get(data, i, j);
1499 1500

{
1501 1502 1503 1504 1505
    if (t < 0) {
        t = jpc_fix_neg(jpc_fix_div(jpc_fix_neg(t), stepsize));
    } else {
        t = jpc_fix_div(t, stepsize);
    }
1506 1507
}

1508 1509 1510
            jas_matrix_set(data, i, j, t);
        }
    }
1511 1512 1513 1514
}

void calcrdslopes(jpc_enc_cblk_t *cblk)
{
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
    jpc_enc_pass_t *endpasses;
    jpc_enc_pass_t *pass0;
    jpc_enc_pass_t *pass1;
    jpc_enc_pass_t *pass2;
    jpc_flt_t slope0;
    jpc_flt_t slope;
    jpc_flt_t dd;
    long dr;

    endpasses = &cblk->passes[cblk->numpasses];
    pass2 = cblk->passes;
    slope0 = 0;
    while (pass2 != endpasses) {
        pass0 = 0;
        for (pass1 = cblk->passes; pass1 != endpasses; ++pass1) {
            dd = pass1->cumwmsedec;
            dr = pass1->end;
            if (pass0) {
                dd -= pass0->cumwmsedec;
                dr -= pass0->end;
            }
            if (dd <= 0) {
                pass1->rdslope = JPC_BADRDSLOPE;
                if (pass1 >= pass2) {
                    pass2 = &pass1[1];
                }
                continue;
            }
            if (pass1 < pass2 && pass1->rdslope <= 0) {
                continue;
            }
            if (!dr) {
                assert(pass0);
                pass0->rdslope = 0;
                break;
            }
            slope = dd / dr;
            if (pass0 && slope >= slope0) {
                pass0->rdslope = 0;
                break;
            }
            pass1->rdslope = slope;
            if (pass1 >= pass2) {
                pass2 = &pass1[1];
            }
            pass0 = pass1;
            slope0 = slope;
        }
    }
1564 1565

#if 0
1566
    for (pass0 = cblk->passes; pass0 != endpasses; ++pass0) {
1567
if (pass0->rdslope > 0.0) {
1568 1569
        jas_eprintf("pass %02d nmsedec=%lf dec=%lf end=%d %lf\n", pass0 - cblk->passes,
          fixtodbl(pass0->nmsedec), pass0->wmsedec, pass0->end, pass0->rdslope);
1570
}
1571
    }
1572 1573 1574 1575 1576 1577
#endif
}

void dump_layeringinfo(jpc_enc_t *enc)
{

1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
    jpc_enc_tcmpt_t *tcmpt;
    int tcmptno;
    jpc_enc_rlvl_t *rlvl;
    int rlvlno;
    jpc_enc_band_t *band;
    int bandno;
    jpc_enc_prc_t *prc;
    int prcno;
    jpc_enc_cblk_t *cblk;
    int cblkno;
    jpc_enc_pass_t *pass;
    int passno;
    int lyrno;
    jpc_enc_tile_t *tile;

    tile = enc->curtile;

    for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
        jas_eprintf("lyrno = %02d\n", lyrno);
        for (tcmptno = 0, tcmpt = tile->tcmpts; tcmptno < tile->numtcmpts;
          ++tcmptno, ++tcmpt) {
            for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
              ++rlvlno, ++rlvl) {
                if (!rlvl->bands) {
                    continue;
                }
                for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
                  ++bandno, ++band) {
                    if (!band->data) {
                        continue;
                    }
                    for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
                      ++prcno, ++prc) {
                        if (!prc->cblks) {
                            continue;
                        }
                        for (cblkno = 0, cblk = prc->cblks; cblkno <
                          prc->numcblks; ++cblkno, ++cblk) {
                            for (passno = 0, pass = cblk->passes; passno <
                              cblk->numpasses && pass->lyrno == lyrno;
                              ++passno, ++pass) {
                                jas_eprintf("lyrno=%02d cmptno=%02d rlvlno=%02d bandno=%02d prcno=%02d cblkno=%03d passno=%03d\n", lyrno, tcmptno, rlvlno, bandno, prcno, cblkno, passno);
                            }
                        }
                    }
                }
            }
        }
    }
1627 1628 1629 1630
}

int rateallocate(jpc_enc_t *enc, int numlyrs, uint_fast32_t *cumlens)
{
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
    jpc_flt_t lo;
    jpc_flt_t hi;
    jas_stream_t *out;
    long cumlen;
    int lyrno;
    jpc_flt_t thresh;
    jpc_flt_t goodthresh;
    int success;
    long pos;
    long oldpos;
    int numiters;

    jpc_enc_tcmpt_t *comp;
    jpc_enc_tcmpt_t *endcomps;
    jpc_enc_rlvl_t *lvl;
    jpc_enc_rlvl_t *endlvls;
    jpc_enc_band_t *band;
    jpc_enc_band_t *endbands;
    jpc_enc_cblk_t *cblk;
    jpc_enc_cblk_t *endcblks;
    jpc_enc_pass_t *pass;
    jpc_enc_pass_t *endpasses;
    jpc_enc_pass_t *pass1;
    jpc_flt_t mxrdslope;
    jpc_flt_t mnrdslope;
    jpc_enc_tile_t *tile;
    jpc_enc_prc_t *prc;
    int prcno;

    tile = enc->curtile;

    for (lyrno = 1; lyrno < numlyrs - 1; ++lyrno) {
        if (cumlens[lyrno - 1] > cumlens[lyrno]) {
            abort();
        }
    }

    if (!(out = jas_stream_memopen(0, 0))) {
        return -1;
    }


    /* Find minimum and maximum R-D slope values. */
    mnrdslope = DBL_MAX;
    mxrdslope = 0;
    endcomps = &tile->tcmpts[tile->numtcmpts];
    for (comp = tile->tcmpts; comp != endcomps; ++comp) {
        endlvls = &comp->rlvls[comp->numrlvls];
        for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
            if (!lvl->bands) {
                continue;
            }
            endbands = &lvl->bands[lvl->numbands];
            for (band = lvl->bands; band != endbands; ++band) {
                if (!band->data) {
                    continue;
                }
                for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
                    if (!prc->cblks) {
                        continue;
                    }
                    endcblks = &prc->cblks[prc->numcblks];
                    for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
                        calcrdslopes(cblk);
                        endpasses = &cblk->passes[cblk->numpasses];
                        for (pass = cblk->passes; pass != endpasses; ++pass) {
                            if (pass->rdslope > 0) {
                                if (pass->rdslope < mnrdslope) {
                                    mnrdslope = pass->rdslope;
                                }
                                if (pass->rdslope > mxrdslope) {
                                    mxrdslope = pass->rdslope;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
1711
if (jas_getdbglevel()) {
1712
    jas_eprintf("min rdslope = %f max rdslope = %f\n", mnrdslope, mxrdslope);
1713 1714
}

1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
    jpc_init_t2state(enc, 1);

    for (lyrno = 0; lyrno < numlyrs; ++lyrno) {

        lo = mnrdslope;
        hi = mxrdslope;

        success = 0;
        goodthresh = 0;
        numiters = 0;

        do {

            cumlen = cumlens[lyrno];
            if (cumlen == UINT_FAST32_MAX) {
                /* Only the last layer can be free of a rate
                  constraint (e.g., for lossless coding). */
                assert(lyrno == numlyrs - 1);
                goodthresh = -1;
                success = 1;
                break;
            }

            thresh = (lo + hi) / 2;

            /* Save the tier 2 coding state. */
            jpc_save_t2state(enc);
            oldpos = jas_stream_tell(out);
            assert(oldpos >= 0);

            /* Assign all passes with R-D slopes greater than or
              equal to the current threshold to this layer. */
            endcomps = &tile->tcmpts[tile->numtcmpts];
            for (comp = tile->tcmpts; comp != endcomps; ++comp) {
                endlvls = &comp->rlvls[comp->numrlvls];
                for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
                    if (!lvl->bands) {
                        continue;
                    }
                    endbands = &lvl->bands[lvl->numbands];
                    for (band = lvl->bands; band != endbands; ++band) {
                        if (!band->data) {
                            continue;
                        }
                        for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
                            if (!prc->cblks) {
                                continue;
                            }
                            endcblks = &prc->cblks[prc->numcblks];
                            for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
                                if (cblk->curpass) {
                                    endpasses = &cblk->passes[cblk->numpasses];
                                    pass1 = cblk->curpass;
                                    for (pass = cblk->curpass; pass != endpasses; ++pass) {
                                        if (pass->rdslope >= thresh) {
                                            pass1 = &pass[1];
                                        }
                                    }
                                    for (pass = cblk->curpass; pass != pass1; ++pass) {
                                        pass->lyrno = lyrno;
                                    }
                                    for (; pass != endpasses; ++pass) {
                                        pass->lyrno = -1;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            /* Perform tier 2 coding. */
            endcomps = &tile->tcmpts[tile->numtcmpts];
            for (comp = tile->tcmpts; comp != endcomps; ++comp) {
                endlvls = &comp->rlvls[comp->numrlvls];
                for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
                    if (!lvl->bands) {
                        continue;
                    }
                    for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
                        if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) {
                            return -1;
                        }
                    }
                }
            }

            pos = jas_stream_tell(out);

            /* Check the rate constraint. */
            assert(pos >= 0);
            if (pos > cumlen) {
                /* The rate is too high. */
                lo = thresh;
            } else if (pos <= cumlen) {
                /* The rate is low enough, so try higher. */
                hi = thresh;
                if (!success || thresh < goodthresh) {
                    goodthresh = thresh;
                    success = 1;
                }
            }

            /* Save the tier 2 coding state. */
            jpc_restore_t2state(enc);
            if (jas_stream_seek(out, oldpos, SEEK_SET) < 0) {
                abort();
            }
1823 1824 1825 1826 1827

if (jas_getdbglevel()) {
jas_eprintf("maxlen=%08ld actuallen=%08ld thresh=%f\n", cumlen, pos, thresh);
}

1828 1829
            ++numiters;
        } while (lo < hi - 1e-3 && numiters < 32);
1830

1831 1832 1833
        if (!success) {
            jas_eprintf("warning: empty layer generated\n");
        }
1834 1835 1836 1837 1838

if (jas_getdbglevel()) {
jas_eprintf("success %d goodthresh %f\n", success, goodthresh);
}

1839 1840 1841 1842 1843 1844
        /* Assign all passes with R-D slopes greater than or
          equal to the selected threshold to this layer. */
        endcomps = &tile->tcmpts[tile->numtcmpts];
        for (comp = tile->tcmpts; comp != endcomps; ++comp) {
            endlvls = &comp->rlvls[comp->numrlvls];
            for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
1845
if (!lvl->bands) {
1846
    continue;
1847
}
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
                endbands = &lvl->bands[lvl->numbands];
                for (band = lvl->bands; band != endbands; ++band) {
                    if (!band->data) {
                        continue;
                    }
                    for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
                        if (!prc->cblks) {
                            continue;
                        }
                        endcblks = &prc->cblks[prc->numcblks];
                        for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
                            if (cblk->curpass) {
                                endpasses = &cblk->passes[cblk->numpasses];
                                pass1 = cblk->curpass;
                                if (success) {
                                    for (pass = cblk->curpass; pass != endpasses; ++pass) {
                                        if (pass->rdslope >= goodthresh) {
                                            pass1 = &pass[1];
                                        }
                                    }
                                }
                                for (pass = cblk->curpass; pass != pass1; ++pass) {
                                    pass->lyrno = lyrno;
                                }
                                for (; pass != endpasses; ++pass) {
                                    pass->lyrno = -1;
                                }
                            }
                        }
                    }
                }
            }
        }

        /* Perform tier 2 coding. */
        endcomps = &tile->tcmpts[tile->numtcmpts];
        for (comp = tile->tcmpts; comp != endcomps; ++comp) {
            endlvls = &comp->rlvls[comp->numrlvls];
            for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
                if (!lvl->bands) {
                    continue;
                }
                for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
                    if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) {
                        return -1;
                    }
                }
            }
        }
    }

    if (jas_getdbglevel() >= 5) {
        dump_layeringinfo(enc);
    }

    jas_stream_close(out);

    JAS_DBGLOG(10, ("done doing rateallocation\n"));
1906 1907 1908 1909
#if 0
jas_eprintf("DONE RATE ALLOCATE\n");
#endif

1910
    return 0;
1911 1912 1913 1914 1915 1916 1917 1918
}

/******************************************************************************\
* Tile constructors and destructors.
\******************************************************************************/

jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno)
{
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
    jpc_enc_tile_t *tile;
    uint_fast32_t htileno;
    uint_fast32_t vtileno;
    uint_fast16_t lyrno;
    uint_fast16_t cmptno;
    jpc_enc_tcmpt_t *tcmpt;

    if (!(tile = jas_malloc(sizeof(jpc_enc_tile_t)))) {
        goto error;
    }

    /* Initialize a few members used in error recovery. */
    tile->tcmpts = 0;
    tile->lyrsizes = 0;
    tile->numtcmpts = cp->numcmpts;
    tile->pi = 0;

    tile->tileno = tileno;
    htileno = tileno % cp->numhtiles;
    vtileno = tileno / cp->numhtiles;

    /* Calculate the coordinates of the top-left and bottom-right
      corners of the tile. */
    tile->tlx = JAS_MAX(cp->tilegrdoffx + htileno * cp->tilewidth,
      cp->imgareatlx);
    tile->tly = JAS_MAX(cp->tilegrdoffy + vtileno * cp->tileheight,
      cp->imgareatly);
    tile->brx = JAS_MIN(cp->tilegrdoffx + (htileno + 1) * cp->tilewidth,
      cp->refgrdwidth);
    tile->bry = JAS_MIN(cp->tilegrdoffy + (vtileno + 1) * cp->tileheight,
      cp->refgrdheight);

    /* Initialize some tile coding parameters. */
    tile->intmode = cp->tcp.intmode;
    tile->csty = cp->tcp.csty;
    tile->prg = cp->tcp.prg;
    tile->mctid = cp->tcp.mctid;

    tile->numlyrs = cp->tcp.numlyrs;
    if (!(tile->lyrsizes = jas_alloc2(tile->numlyrs,
      sizeof(uint_fast32_t)))) {
        goto error;
    }
    for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
        tile->lyrsizes[lyrno] = 0;
    }

    /* Allocate an array for the per-tile-component information. */
    if (!(tile->tcmpts = jas_alloc2(cp->numcmpts, sizeof(jpc_enc_tcmpt_t)))) {
        goto error;
    }
    /* Initialize a few members critical for error recovery. */
    for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
      ++cmptno, ++tcmpt) {
        tcmpt->rlvls = 0;
        tcmpt->tsfb = 0;
        tcmpt->data = 0;
    }
    /* Initialize the per-tile-component information. */
    for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
      ++cmptno, ++tcmpt) {
        if (!tcmpt_create(tcmpt, cp, image, tile)) {
            goto error;
        }
    }

    /* Initialize the synthesis weights for the MCT. */
    switch (tile->mctid) {
    case JPC_MCT_RCT:
        tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0));
        tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(0.6875));
        tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(0.6875));
        break;
    case JPC_MCT_ICT:
        tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0000));
        tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(3.2584));
        tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(2.4755));
        break;
    default:
    case JPC_MCT_NONE:
        for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
          ++cmptno, ++tcmpt) {
            tcmpt->synweight = JPC_FIX_ONE;
        }
        break;
    }

    if (!(tile->pi = jpc_enc_pi_create(cp, tile))) {
        goto error;
    }

    return tile;
2011 2012 2013

error:

2014 2015 2016 2017
    if (tile) {
        jpc_enc_tile_destroy(tile);
    }
    return 0;
2018 2019 2020 2021
}

void jpc_enc_tile_destroy(jpc_enc_tile_t *tile)
{
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
    jpc_enc_tcmpt_t *tcmpt;
    uint_fast16_t cmptno;

    if (tile->tcmpts) {
        for (cmptno = 0, tcmpt = tile->tcmpts; cmptno <
          tile->numtcmpts; ++cmptno, ++tcmpt) {
            tcmpt_destroy(tcmpt);
        }
        jas_free(tile->tcmpts);
    }
    if (tile->lyrsizes) {
        jas_free(tile->lyrsizes);
    }
    if (tile->pi) {
        jpc_pi_destroy(tile->pi);
    }
    jas_free(tile);
2039 2040 2041 2042 2043
}

static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp,
  jas_image_t *image, jpc_enc_tile_t *tile)
{
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
    uint_fast16_t cmptno;
    uint_fast16_t rlvlno;
    jpc_enc_rlvl_t *rlvl;
    uint_fast32_t tlx;
    uint_fast32_t tly;
    uint_fast32_t brx;
    uint_fast32_t bry;
    uint_fast32_t cmpttlx;
    uint_fast32_t cmpttly;
    jpc_enc_ccp_t *ccp;
    jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];

    tcmpt->tile = tile;
    tcmpt->tsfb = 0;
    tcmpt->data = 0;
    tcmpt->rlvls = 0;

    /* Deduce the component number. */
    cmptno = tcmpt - tile->tcmpts;

    ccp = &cp->ccps[cmptno];

    /* Compute the coordinates of the top-left and bottom-right
      corners of this tile-component. */
    tlx = JPC_CEILDIV(tile->tlx, ccp->sampgrdstepx);
    tly = JPC_CEILDIV(tile->tly, ccp->sampgrdstepy);
    brx = JPC_CEILDIV(tile->brx, ccp->sampgrdstepx);
    bry = JPC_CEILDIV(tile->bry, ccp->sampgrdstepy);

    /* Create a sequence to hold the tile-component sample data. */
    if (!(tcmpt->data = jas_seq2d_create(tlx, tly, brx, bry))) {
        goto error;
    }

    /* Get the image data associated with this tile-component. */
    cmpttlx = JPC_CEILDIV(cp->imgareatlx, ccp->sampgrdstepx);
    cmpttly = JPC_CEILDIV(cp->imgareatly, ccp->sampgrdstepy);
    if (jas_image_readcmpt(image, cmptno, tlx - cmpttlx, tly - cmpttly,
      brx - tlx, bry - tly, tcmpt->data)) {
        goto error;
    }

    tcmpt->synweight = 0;
    tcmpt->qmfbid = cp->tccp.qmfbid;
    tcmpt->numrlvls = cp->tccp.maxrlvls;
    tcmpt->numbands = 3 * tcmpt->numrlvls - 2;
    if (!(tcmpt->tsfb = jpc_cod_gettsfb(tcmpt->qmfbid, tcmpt->numrlvls - 1))) {
        goto error;
    }

    for (rlvlno = 0; rlvlno < tcmpt->numrlvls; ++rlvlno) {
        tcmpt->prcwidthexpns[rlvlno] = cp->tccp.prcwidthexpns[rlvlno];
        tcmpt->prcheightexpns[rlvlno] = cp->tccp.prcheightexpns[rlvlno];
    }
    tcmpt->cblkwidthexpn = cp->tccp.cblkwidthexpn;
    tcmpt->cblkheightexpn = cp->tccp.cblkheightexpn;
    tcmpt->cblksty = cp->tccp.cblksty;
    tcmpt->csty = cp->tccp.csty;

    tcmpt->numstepsizes = tcmpt->numbands;
    assert(tcmpt->numstepsizes <= JPC_MAXBANDS);
    memset(tcmpt->stepsizes, 0, tcmpt->numstepsizes *
      sizeof(uint_fast16_t));

    /* Retrieve information about the various bands. */
    jpc_tsfb_getbands(tcmpt->tsfb, jas_seq2d_xstart(tcmpt->data),
      jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data),
      jas_seq2d_yend(tcmpt->data), bandinfos);

    if (!(tcmpt->rlvls = jas_alloc2(tcmpt->numrlvls, sizeof(jpc_enc_rlvl_t)))) {
        goto error;
    }
    for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
      ++rlvlno, ++rlvl) {
        rlvl->bands = 0;
        rlvl->tcmpt = tcmpt;
    }
    for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
      ++rlvlno, ++rlvl) {
        if (!rlvl_create(rlvl, cp, tcmpt, bandinfos)) {
            goto error;
        }
    }

    return tcmpt;
2129 2130 2131

error:

2132 2133
    tcmpt_destroy(tcmpt);
    return 0;
2134 2135 2136 2137 2138

}

static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt)
{
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
    jpc_enc_rlvl_t *rlvl;
    uint_fast16_t rlvlno;

    if (tcmpt->rlvls) {
        for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
          ++rlvlno, ++rlvl) {
            rlvl_destroy(rlvl);
        }
        jas_free(tcmpt->rlvls);
    }

    if (tcmpt->data) {
        jas_seq2d_destroy(tcmpt->data);
    }
    if (tcmpt->tsfb) {
        jpc_tsfb_destroy(tcmpt->tsfb);
    }
2156 2157 2158 2159 2160
}

static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
  jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos)
{
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
    uint_fast16_t rlvlno;
    uint_fast32_t tlprctlx;
    uint_fast32_t tlprctly;
    uint_fast32_t brprcbrx;
    uint_fast32_t brprcbry;
    uint_fast16_t bandno;
    jpc_enc_band_t *band;

    /* Deduce the resolution level. */
    rlvlno = rlvl - tcmpt->rlvls;

    /* Initialize members required for error recovery. */
    rlvl->bands = 0;
    rlvl->tcmpt = tcmpt;

    /* Compute the coordinates of the top-left and bottom-right
      corners of the tile-component at this resolution. */
    rlvl->tlx = JPC_CEILDIVPOW2(jas_seq2d_xstart(tcmpt->data), tcmpt->numrlvls -
      1 - rlvlno);
    rlvl->tly = JPC_CEILDIVPOW2(jas_seq2d_ystart(tcmpt->data), tcmpt->numrlvls -
      1 - rlvlno);
    rlvl->brx = JPC_CEILDIVPOW2(jas_seq2d_xend(tcmpt->data), tcmpt->numrlvls -
      1 - rlvlno);
    rlvl->bry = JPC_CEILDIVPOW2(jas_seq2d_yend(tcmpt->data), tcmpt->numrlvls -
      1 - rlvlno);

    if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) {
        rlvl->numhprcs = 0;
        rlvl->numvprcs = 0;
        rlvl->numprcs = 0;
        return rlvl;
    }

    rlvl->numbands = (!rlvlno) ? 1 : 3;
    rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno];
    rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno];
    if (!rlvlno) {
        rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
        rlvl->cbgheightexpn = rlvl->prcheightexpn;
    } else {
        rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
        rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
    }
    rlvl->cblkwidthexpn = JAS_MIN(cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn);
    rlvl->cblkheightexpn = JAS_MIN(cp->tccp.cblkheightexpn, rlvl->cbgheightexpn);

    /* Compute the number of precincts. */
    tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
    tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
    brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn);
    brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn);
    rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn);
    rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn);
    rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;

    if (!(rlvl->bands = jas_alloc2(rlvl->numbands, sizeof(jpc_enc_band_t)))) {
        goto error;
    }
    for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
      ++bandno, ++band) {
        band->prcs = 0;
        band->data = 0;
        band->rlvl = rlvl;
    }
    for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
      ++bandno, ++band) {
        if (!band_create(band, cp, rlvl, bandinfos)) {
            goto error;
        }
    }

    return rlvl;
2233 2234
error:

2235 2236
    rlvl_destroy(rlvl);
    return 0;
2237 2238 2239 2240
}

static void rlvl_destroy(jpc_enc_rlvl_t *rlvl)
{
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
    jpc_enc_band_t *band;
    uint_fast16_t bandno;

    if (rlvl->bands) {
        for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
          ++bandno, ++band) {
            band_destroy(band);
        }
        jas_free(rlvl->bands);
    }
2251 2252 2253 2254 2255
}

static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,
  jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos)
{
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
    uint_fast16_t bandno;
    uint_fast16_t gblbandno;
    uint_fast16_t rlvlno;
    jpc_tsfb_band_t *bandinfo;
    jpc_enc_tcmpt_t *tcmpt;
    uint_fast32_t prcno;
    jpc_enc_prc_t *prc;

    tcmpt = rlvl->tcmpt;
    band->data = 0;
    band->prcs = 0;
    band->rlvl = rlvl;

    /* Deduce the resolution level and band number. */
    rlvlno = rlvl - rlvl->tcmpt->rlvls;
    bandno = band - rlvl->bands;
    gblbandno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1);

    bandinfo = &bandinfos[gblbandno];
2275 2276

if (bandinfo->xstart != bandinfo->xend && bandinfo->ystart != bandinfo->yend) {
2277 2278 2279 2280 2281 2282
    if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
        goto error;
    }
    jas_seq2d_bindsub(band->data, tcmpt->data, bandinfo->locxstart,
      bandinfo->locystart, bandinfo->locxend, bandinfo->locyend);
    jas_seq2d_setshift(band->data, bandinfo->xstart, bandinfo->ystart);
2283
}
2284 2285 2286 2287 2288 2289 2290
    band->orient = bandinfo->orient;
    band->analgain = JPC_NOMINALGAIN(cp->tccp.qmfbid, tcmpt->numrlvls, rlvlno,
      band->orient);
    band->numbps = 0;
    band->absstepsize = 0;
    band->stepsize = 0;
    band->synweight = bandinfo->synenergywt;
2291 2292

if (band->data) {
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
    if (!(band->prcs = jas_alloc2(rlvl->numprcs, sizeof(jpc_enc_prc_t)))) {
        goto error;
    }
    for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
      ++prc) {
        prc->cblks = 0;
        prc->incltree = 0;
        prc->nlibtree = 0;
        prc->savincltree = 0;
        prc->savnlibtree = 0;
        prc->band = band;
    }
    for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
      ++prc) {
        if (!prc_create(prc, cp, band)) {
            goto error;
        }
    }
2311 2312
}

2313
    return band;
2314 2315

error:
2316 2317
    band_destroy(band);
    return 0;
2318 2319 2320 2321
}

static void band_destroy(jpc_enc_band_t *band)
{
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
    jpc_enc_prc_t *prc;
    jpc_enc_rlvl_t *rlvl;
    uint_fast32_t prcno;

    if (band->prcs) {
        rlvl = band->rlvl;
        for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
          ++prcno, ++prc) {
            prc_destroy(prc);
        }
        jas_free(band->prcs);
    }
    if (band->data) {
        jas_seq2d_destroy(band->data);
    }
2337 2338 2339 2340
}

static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, jpc_enc_band_t *band)
{
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
    uint_fast32_t prcno;
    uint_fast32_t prcxind;
    uint_fast32_t prcyind;
    uint_fast32_t cbgtlx;
    uint_fast32_t cbgtly;
    uint_fast32_t tlprctlx;
    uint_fast32_t tlprctly;
    uint_fast32_t tlcbgtlx;
    uint_fast32_t tlcbgtly;
    uint_fast16_t rlvlno;
    jpc_enc_rlvl_t *rlvl;
    uint_fast32_t tlcblktlx;
    uint_fast32_t tlcblktly;
    uint_fast32_t brcblkbrx;
    uint_fast32_t brcblkbry;
    uint_fast32_t cblkno;
    jpc_enc_cblk_t *cblk;
    jpc_enc_tcmpt_t *tcmpt;

    prc->cblks = 0;
    prc->incltree = 0;
    prc->savincltree = 0;
    prc->nlibtree = 0;
    prc->savnlibtree = 0;

    rlvl = band->rlvl;
    tcmpt = rlvl->tcmpt;
2368
rlvlno = rlvl - tcmpt->rlvls;
2369 2370 2371 2372
    prcno = prc - band->prcs;
    prcxind = prcno % rlvl->numhprcs;
    prcyind = prcno / rlvl->numhprcs;
    prc->band = band;
2373 2374 2375 2376

tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
if (!rlvlno) {
2377 2378
    tlcbgtlx = tlprctlx;
    tlcbgtly = tlprctly;
2379
} else {
2380 2381
    tlcbgtlx = JPC_CEILDIVPOW2(tlprctlx, 1);
    tlcbgtly = JPC_CEILDIVPOW2(tlprctly, 1);
2382 2383
}

2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457
    /* Compute the coordinates of the top-left and bottom-right
      corners of the precinct. */
    cbgtlx = tlcbgtlx + (prcxind << rlvl->cbgwidthexpn);
    cbgtly = tlcbgtly + (prcyind << rlvl->cbgheightexpn);
    prc->tlx = JAS_MAX(jas_seq2d_xstart(band->data), cbgtlx);
    prc->tly = JAS_MAX(jas_seq2d_ystart(band->data), cbgtly);
    prc->brx = JAS_MIN(jas_seq2d_xend(band->data), cbgtlx +
      (1 << rlvl->cbgwidthexpn));
    prc->bry = JAS_MIN(jas_seq2d_yend(band->data), cbgtly +
      (1 << rlvl->cbgheightexpn));

    if (prc->tlx < prc->brx && prc->tly < prc->bry) {
        /* The precinct contains at least one code block. */

        tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
        tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
        brcblkbrx = JPC_CEILTOMULTPOW2(prc->brx, rlvl->cblkwidthexpn);
        brcblkbry = JPC_CEILTOMULTPOW2(prc->bry, rlvl->cblkheightexpn);
        prc->numhcblks = JPC_FLOORDIVPOW2(brcblkbrx - tlcblktlx,
          rlvl->cblkwidthexpn);
        prc->numvcblks = JPC_FLOORDIVPOW2(brcblkbry - tlcblktly,
          rlvl->cblkheightexpn);
        prc->numcblks = prc->numhcblks * prc->numvcblks;

        if (!(prc->incltree = jpc_tagtree_create(prc->numhcblks,
          prc->numvcblks))) {
            goto error;
        }
        if (!(prc->nlibtree = jpc_tagtree_create(prc->numhcblks,
          prc->numvcblks))) {
            goto error;
        }
        if (!(prc->savincltree = jpc_tagtree_create(prc->numhcblks,
          prc->numvcblks))) {
            goto error;
        }
        if (!(prc->savnlibtree = jpc_tagtree_create(prc->numhcblks,
          prc->numvcblks))) {
            goto error;
        }

        if (!(prc->cblks = jas_alloc2(prc->numcblks, sizeof(jpc_enc_cblk_t)))) {
            goto error;
        }
        for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
          ++cblkno, ++cblk) {
            cblk->passes = 0;
            cblk->stream = 0;
            cblk->mqenc = 0;
            cblk->data = 0;
            cblk->flags = 0;
            cblk->prc = prc;
        }
        for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
          ++cblkno, ++cblk) {
            if (!cblk_create(cblk, cp, prc)) {
                goto error;
            }
        }
    } else {
        /* The precinct does not contain any code blocks. */
        prc->tlx = prc->brx;
        prc->tly = prc->bry;
        prc->numcblks = 0;
        prc->numhcblks = 0;
        prc->numvcblks = 0;
        prc->cblks = 0;
        prc->incltree = 0;
        prc->nlibtree = 0;
        prc->savincltree = 0;
        prc->savnlibtree = 0;
    }

    return prc;
2458 2459

error:
2460 2461
    prc_destroy(prc);
    return 0;
2462 2463 2464 2465
}

static void prc_destroy(jpc_enc_prc_t *prc)
{
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
    jpc_enc_cblk_t *cblk;
    uint_fast32_t cblkno;

    if (prc->cblks) {
        for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
          ++cblkno, ++cblk) {
            cblk_destroy(cblk);
        }
        jas_free(prc->cblks);
    }
    if (prc->incltree) {
        jpc_tagtree_destroy(prc->incltree);
    }
    if (prc->nlibtree) {
        jpc_tagtree_destroy(prc->nlibtree);
    }
    if (prc->savincltree) {
        jpc_tagtree_destroy(prc->savincltree);
    }
    if (prc->savnlibtree) {
        jpc_tagtree_destroy(prc->savnlibtree);
    }
2488 2489 2490 2491
}

static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp, jpc_enc_prc_t *prc)
{
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
    jpc_enc_band_t *band;
    uint_fast32_t cblktlx;
    uint_fast32_t cblktly;
    uint_fast32_t cblkbrx;
    uint_fast32_t cblkbry;
    jpc_enc_rlvl_t *rlvl;
    uint_fast32_t cblkxind;
    uint_fast32_t cblkyind;
    uint_fast32_t cblkno;
    uint_fast32_t tlcblktlx;
    uint_fast32_t tlcblktly;

    cblkno = cblk - prc->cblks;
    cblkxind = cblkno % prc->numhcblks;
    cblkyind = cblkno / prc->numhcblks;
    rlvl = prc->band->rlvl;
    cblk->prc = prc;

    cblk->numpasses = 0;
    cblk->passes = 0;
    cblk->numencpasses = 0;
    cblk->numimsbs = 0;
    cblk->numlenbits = 0;
    cblk->stream = 0;
    cblk->mqenc = 0;
    cblk->flags = 0;
    cblk->numbps = 0;
    cblk->curpass = 0;
    cblk->data = 0;
    cblk->savedcurpass = 0;
    cblk->savednumlenbits = 0;
    cblk->savednumencpasses = 0;

    band = prc->band;
    tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
    tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
    cblktlx = JAS_MAX(tlcblktlx + (cblkxind << rlvl->cblkwidthexpn), prc->tlx);
    cblktly = JAS_MAX(tlcblktly + (cblkyind << rlvl->cblkheightexpn), prc->tly);
    cblkbrx = JAS_MIN(tlcblktlx + ((cblkxind + 1) << rlvl->cblkwidthexpn),
      prc->brx);
    cblkbry = JAS_MIN(tlcblktly + ((cblkyind + 1) << rlvl->cblkheightexpn),
      prc->bry);

    assert(cblktlx < cblkbrx && cblktly < cblkbry);
    if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) {
        goto error;
    }
    jas_seq2d_bindsub(cblk->data, band->data, cblktlx, cblktly, cblkbrx, cblkbry);

    return cblk;
2542 2543

error:
2544 2545
    cblk_destroy(cblk);
    return 0;
2546 2547 2548 2549
}

static void cblk_destroy(jpc_enc_cblk_t *cblk)
{
2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
    uint_fast16_t passno;
    jpc_enc_pass_t *pass;
    if (cblk->passes) {
        for (passno = 0, pass = cblk->passes; passno < cblk->numpasses;
          ++passno, ++pass) {
            pass_destroy(pass);
        }
        jas_free(cblk->passes);
    }
    if (cblk->stream) {
        jas_stream_close(cblk->stream);
    }
    if (cblk->mqenc) {
        jpc_mqenc_destroy(cblk->mqenc);
    }
    if (cblk->data) {
        jas_seq2d_destroy(cblk->data);
    }
    if (cblk->flags) {
        jas_seq2d_destroy(cblk->flags);
    }
2571 2572 2573 2574
}

static void pass_destroy(jpc_enc_pass_t *pass)
{
2575
    /* XXX - need to free resources here */
2576 2577 2578 2579
}

void jpc_enc_dump(jpc_enc_t *enc)
{
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
    jpc_enc_tile_t *tile;
    jpc_enc_tcmpt_t *tcmpt;
    jpc_enc_rlvl_t *rlvl;
    jpc_enc_band_t *band;
    jpc_enc_prc_t *prc;
    jpc_enc_cblk_t *cblk;
    uint_fast16_t cmptno;
    uint_fast16_t rlvlno;
    uint_fast16_t bandno;
    uint_fast32_t prcno;
    uint_fast32_t cblkno;

    tile = enc->curtile;

    for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno,
      ++tcmpt) {
        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));
        for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
          ++rlvlno, ++rlvl) {
            jas_eprintf("    rlvl %5d %5d %5d %5d\n", rlvl->tlx, rlvl->tly, rlvl->brx, rlvl->bry);
            for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
              ++bandno, ++band) {
                if (!band->data) {
                    continue;
                }
                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));
                for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
                  ++prcno, ++prc) {
                    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);
                    if (!prc->cblks) {
                        continue;
                    }
                    for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
                      ++cblkno, ++cblk) {
                        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));
                    }
                }
            }
        }
    }
2620
}