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