]> Creatis software - gdcm.git/blob - src/gdcmjasper/src/libjasper/jpc/jpc_enc.c
ENH: Ok since OJ warnings are not going to be fixed anytime soon remove them
[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.5 2005/06/11 02:05:20 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   (void)ret; /* ret' is assigned a value that is never used in function cp_create */
772   return 0;
773 }
774
775 void jpc_enc_cp_destroy(jpc_enc_cp_t *cp)
776 {
777   if (cp->ccps) {
778     if (cp->tcp.ilyrrates) {
779       jas_free(cp->tcp.ilyrrates);
780     }
781     jas_free(cp->ccps);
782   }
783   jas_free(cp);
784 }
785
786 int ratestrtosize(char *s, uint_fast32_t rawsize, uint_fast32_t *size)
787 {
788   char *cp;
789   jpc_flt_t f;
790
791   /* Note: This function must not modify output size on failure. */
792   if ((cp = strchr(s, 'B'))) {
793     *size = atoi(s);
794   } else {
795     f = atof(s);
796     if (f < 0) {
797       *size = 0;
798     } else if (f > 1.0) {
799       *size = rawsize + 1;
800     } else {
801       *size = (uint_fast32_t)(f * rawsize);
802     }
803   }
804   (void)cp; /* 'cp' is assigned a value that is never used in function ratestrtosize */
805   return 0;
806 }
807
808 /******************************************************************************\
809 * Encoder constructor and destructor.
810 \******************************************************************************/
811
812 jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image)
813 {
814   jpc_enc_t *enc;
815
816   enc = 0;
817
818   if (!(enc = jas_malloc(sizeof(jpc_enc_t)))) {
819     goto error;
820   }
821
822   enc->image = image;
823   enc->out = out;
824   enc->cp = cp;
825   enc->cstate = 0;
826   enc->tmpstream = 0;
827   enc->mrk = 0;
828   enc->curtile = 0;
829
830   if (!(enc->cstate = jpc_cstate_create())) {
831     goto error;
832   }
833   enc->len = 0;
834   enc->mainbodysize = 0;
835
836   return enc;
837
838 error:
839
840   if (enc) {
841     jpc_enc_destroy(enc);
842   }
843   return 0;
844 }
845
846 void jpc_enc_destroy(jpc_enc_t *enc)
847 {
848   /* The image object (i.e., enc->image) and output stream object
849   (i.e., enc->out) are created outside of the encoder.
850   Therefore, they must not be destroyed here. */
851
852   if (enc->curtile) {
853     jpc_enc_tile_destroy(enc->curtile);
854   }
855   if (enc->cp) {
856     jpc_enc_cp_destroy(enc->cp);
857   }
858   if (enc->cstate) {
859     jpc_cstate_destroy(enc->cstate);
860   }
861   if (enc->tmpstream) {
862     jas_stream_close(enc->tmpstream);
863   }
864
865   jas_free(enc);
866 }
867
868 /******************************************************************************\
869 * Code.
870 \******************************************************************************/
871
872 #if 0
873 static int jpc_calcssmant(jpc_fix_t stepsize)
874 {
875   int n;
876   int e;
877   int m;
878
879   n = jpc_firstone(stepsize);
880   e = n - JPC_FIX_FRACBITS;
881   if (n >= 11) {
882     m = (stepsize >> (n - 11)) & 0x7ff;
883   } else {
884     m = (stepsize & ((1 << n) - 1)) << (11 - n);
885   }
886   return m;
887 }
888
889 static int jpc_calcssexp(jpc_fix_t stepsize)
890 {
891   return jpc_firstone(stepsize) - JPC_FIX_FRACBITS;
892 }
893 #endif
894
895 static int jpc_enc_encodemainhdr(jpc_enc_t *enc)
896 {
897   jpc_siz_t *siz;
898   jpc_cod_t *cod;
899   jpc_qcd_t *qcd;
900   int i;
901 long startoff;
902 long mainhdrlen;
903   jpc_enc_cp_t *cp;
904   jpc_qcc_t *qcc;
905   jpc_enc_tccp_t *tccp;
906   uint_fast16_t cmptno;
907   jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
908   jpc_fix_t mctsynweight;
909   jpc_enc_tcp_t *tcp;
910   jpc_tsfb_t *tsfb;
911   jpc_tsfb_band_t *bandinfo;
912   uint_fast16_t numbands;
913   uint_fast16_t bandno;
914   uint_fast16_t rlvlno;
915   uint_fast16_t analgain;
916   jpc_fix_t absstepsize;
917   char buf[1024];
918   jpc_com_t *com;
919
920   cp = enc->cp;
921
922 startoff = jas_stream_getrwcount(enc->out);
923
924   /* Write SOC marker segment. */
925   if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {
926     return -1;
927   }
928   if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
929     fprintf(stderr, "cannot write SOC marker\n");
930     return -1;
931   }
932   jpc_ms_destroy(enc->mrk);
933   enc->mrk = 0;
934
935   /* Write SIZ marker segment. */
936   if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {
937     return -1;
938   }
939   siz = &enc->mrk->parms.siz;
940   siz->caps = 0;
941   siz->xoff = cp->imgareatlx;
942   siz->yoff = cp->imgareatly;
943   siz->width = cp->refgrdwidth;
944   siz->height = cp->refgrdheight;
945   siz->tilexoff = cp->tilegrdoffx;
946   siz->tileyoff = cp->tilegrdoffy;
947   siz->tilewidth = cp->tilewidth;
948   siz->tileheight = cp->tileheight;
949   siz->numcomps = cp->numcmpts;
950   siz->comps = jas_malloc(siz->numcomps * sizeof(jpc_sizcomp_t));
951   assert(siz->comps);
952   for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {
953     siz->comps[i].prec = cp->ccps[i].prec;
954     siz->comps[i].sgnd = cp->ccps[i].sgnd;
955     siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;
956     siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;
957   }
958   if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
959     fprintf(stderr, "cannot write SIZ marker\n");
960     return -1;
961   }
962   jpc_ms_destroy(enc->mrk);
963   enc->mrk = 0;
964
965   if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {
966     return -1;
967   }
968   sprintf(buf, "Creator: JasPer Version %s", jas_getversion());
969   com = &enc->mrk->parms.com;
970   com->len = strlen(buf);
971   com->regid = JPC_COM_LATIN;
972   if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) {
973     abort();
974   }
975   if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
976     fprintf(stderr, "cannot write COM marker\n");
977     return -1;
978   }
979   jpc_ms_destroy(enc->mrk);
980   enc->mrk = 0;
981
982 #if 0
983   if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {
984     return -1;
985   }
986   crg = &enc->mrk->parms.crg;
987   crg->comps = jas_malloc(crg->numcomps * sizeof(jpc_crgcomp_t));
988   if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
989     fprintf(stderr, "cannot write CRG marker\n");
990     return -1;
991   }
992   jpc_ms_destroy(enc->mrk);
993   enc->mrk = 0;
994 #endif
995
996   tcp = &cp->tcp;
997   tccp = &cp->tccp;
998   for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
999     tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);
1000     jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,
1001       bandinfos);
1002     jpc_tsfb_destroy(tsfb);
1003     mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno);
1004     numbands = 3 * tccp->maxrlvls - 2;
1005     for (bandno = 0, bandinfo = bandinfos; bandno < numbands;
1006       ++bandno, ++bandinfo) {
1007       rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;
1008       analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,
1009         rlvlno, bandinfo->orient);
1010       if (!tcp->intmode) {
1011         absstepsize = jpc_fix_div(jpc_inttofix(1 <<
1012           (analgain + 1)), bandinfo->synenergywt);
1013       } else {
1014         absstepsize = jpc_inttofix(1);
1015       }  
1016       cp->ccps[cmptno].stepsizes[bandno] =
1017         jpc_abstorelstepsize(absstepsize,
1018         cp->ccps[cmptno].prec + analgain);
1019     }
1020     cp->ccps[cmptno].numstepsizes = numbands;
1021   }
1022
1023   if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
1024     return -1;
1025   }
1026   cod = &enc->mrk->parms.cod;
1027   cod->csty = cp->tccp.csty | cp->tcp.csty;
1028   cod->compparms.csty = cp->tccp.csty | cp->tcp.csty;
1029   cod->compparms.numdlvls = cp->tccp.maxrlvls - 1;
1030   cod->compparms.numrlvls = cp->tccp.maxrlvls;
1031   cod->prg = cp->tcp.prg;
1032   cod->numlyrs = cp->tcp.numlyrs;
1033   cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);
1034   cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);
1035   cod->compparms.cblksty = cp->tccp.cblksty;
1036   cod->compparms.qmfbid = cp->tccp.qmfbid;
1037   cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);
1038   if (tccp->csty & JPC_COX_PRT) {
1039     for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
1040       cod->compparms.rlvls[rlvlno].parwidthval = (uint_fast8_t)tccp->prcwidthexpns[rlvlno];
1041       cod->compparms.rlvls[rlvlno].parheightval = (uint_fast8_t)tccp->prcheightexpns[rlvlno];
1042     }
1043   }
1044   if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
1045     fprintf(stderr, "cannot write COD marker\n");
1046     return -1;
1047   }
1048   jpc_ms_destroy(enc->mrk);
1049   enc->mrk = 0;
1050
1051   if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {
1052     return -1;
1053   }
1054   qcd = &enc->mrk->parms.qcd;
1055   qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
1056     JPC_QCX_SEQNT : JPC_QCX_NOQNT;
1057   qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;
1058   qcd->compparms.numguard = cp->tccp.numgbits;
1059   qcd->compparms.stepsizes = cp->ccps[0].stepsizes;
1060   if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
1061     return -1;
1062   }
1063   /* We do not want the step size array to be freed! */
1064   qcd->compparms.stepsizes = 0;
1065   jpc_ms_destroy(enc->mrk);
1066   enc->mrk = 0;
1067
1068   tccp = &cp->tccp;
1069   for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {
1070     if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
1071       return -1;
1072     }
1073     qcc = &enc->mrk->parms.qcc;
1074     qcc->compno = cmptno;
1075     qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
1076       JPC_QCX_SEQNT : JPC_QCX_NOQNT;
1077     qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;
1078     qcc->compparms.numguard = cp->tccp.numgbits;
1079     qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;
1080     if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
1081       return -1;
1082     }
1083     /* We do not want the step size array to be freed! */
1084     qcc->compparms.stepsizes = 0;
1085     jpc_ms_destroy(enc->mrk);
1086     enc->mrk = 0;
1087   }
1088
1089 #define MAINTLRLEN  2
1090   mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
1091   enc->len += mainhdrlen;
1092   if (enc->cp->totalsize != UINT_FAST32_MAX) {
1093     uint_fast32_t overhead;
1094     overhead = mainhdrlen + MAINTLRLEN;
1095     enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
1096       (enc->cp->totalsize - overhead) : 0;
1097   } else {
1098     enc->mainbodysize = UINT_FAST32_MAX;
1099   }
1100
1101   (void)mctsynweight; /* 'mctsynweight' is assigned a value that is never used in function jpc_enc_encodemainhdr */
1102   return 0;
1103 }
1104
1105 static int jpc_enc_encodemainbody(jpc_enc_t *enc)
1106 {
1107   int tileno;
1108   int i;
1109   jpc_sot_t *sot;
1110   jpc_enc_tcmpt_t *comp;
1111   jpc_enc_tcmpt_t *endcomps;
1112   jpc_enc_band_t *band;
1113   jpc_enc_band_t *endbands;
1114   jpc_enc_rlvl_t *lvl;
1115   int rlvlno;
1116   jpc_qcc_t *qcc;
1117   jpc_cod_t *cod;
1118   int adjust;
1119   int j;
1120   int absbandno;
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   for (tileno = 0; tileno < JAS_CAST(int, cp->numtiles); ++tileno) {
1143
1144     if (!(enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno))) {
1145       abort();
1146     }
1147
1148     tile = enc->curtile;
1149
1150     if (jas_getdbglevel() >= 10) {
1151       jpc_enc_dump(enc);
1152     }
1153
1154     endcomps = &tile->tcmpts[tile->numtcmpts];
1155     for (cmptno = 0, comp = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno, ++comp) {
1156       if (!cp->ccps[cmptno].sgnd) {
1157         adjust = 1 << (cp->ccps[cmptno].prec - 1);
1158         for (i = 0; i < jas_matrix_numrows(comp->data); ++i) {
1159           for (j = 0; j < jas_matrix_numcols(comp->data); ++j) {
1160             *jas_matrix_getref(comp->data, i, j) -= adjust;
1161           }
1162         }
1163       }
1164     }
1165
1166     if (!tile->intmode) {
1167         endcomps = &tile->tcmpts[tile->numtcmpts];
1168         for (comp = tile->tcmpts; comp != endcomps; ++comp) {
1169           jas_matrix_asl(comp->data, JPC_FIX_FRACBITS);
1170         }
1171     }
1172
1173     switch (tile->mctid) {
1174     case JPC_MCT_RCT:
1175 assert(jas_image_numcmpts(enc->image) == 3);
1176       jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data,
1177         tile->tcmpts[2].data);
1178       break;
1179     case JPC_MCT_ICT:
1180 assert(jas_image_numcmpts(enc->image) == 3);
1181       jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data,
1182         tile->tcmpts[2].data);
1183       break;
1184     default:
1185       break;
1186     }
1187
1188     for (i = 0; i < jas_image_numcmpts(enc->image); ++i) {
1189       comp = &tile->tcmpts[i];
1190       jpc_tsfb_analyze(comp->tsfb, ((comp->qmfbid == JPC_COX_RFT) ? JPC_TSFB_RITIMODE : 0), comp->data);
1191
1192     }
1193
1194
1195     endcomps = &tile->tcmpts[tile->numtcmpts];
1196     for (cmptno = 0, comp = tile->tcmpts; comp != endcomps; ++cmptno, ++comp) {
1197       mingbits = 0;
1198       absbandno = 0;
1199       /* All bands must have a corresponding quantizer step size,
1200         even if they contain no samples and are never coded. */
1201       /* Some bands may not be hit by the loop below, so we must
1202         initialize all of the step sizes to a sane value. */
1203       memset(comp->stepsizes, 0, sizeof(comp->stepsizes));
1204       for (rlvlno = 0, lvl = comp->rlvls; rlvlno < comp->numrlvls; ++rlvlno, ++lvl) {
1205         if (!lvl->bands) {
1206           absbandno += rlvlno ? 3 : 1;
1207           continue;
1208         }
1209         endbands = &lvl->bands[lvl->numbands];
1210         for (band = lvl->bands; band != endbands; ++band) {
1211           if (!band->data) {
1212             ++absbandno;
1213             continue;
1214           }
1215           actualnumbps = 0;
1216           mxmag = 0;
1217           for (y = 0; y < JAS_CAST(uint_fast32_t, jas_matrix_numrows(band->data)); ++y) {
1218             for (x = 0; x < JAS_CAST(uint_fast32_t, jas_matrix_numcols(band->data)); ++x) {
1219               mag = abs(jas_matrix_get(band->data, y, x));
1220               if (mag > mxmag) {
1221                 mxmag = mag;
1222               }
1223             }
1224           }
1225           if (tile->intmode) {
1226             actualnumbps = jpc_firstone(mxmag) + 1;
1227           } else {
1228             actualnumbps = jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;
1229           }
1230           numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 +
1231             band->analgain);
1232 #if 0
1233 fprintf(stderr, "%d %d mag=%d actual=%d numgbits=%d\n", cp->ccps[cmptno].prec, band->analgain, mxmag, actualnumbps, numgbits);
1234 #endif
1235           if (numgbits > mingbits) {
1236             mingbits = numgbits;
1237           }
1238           if (!tile->intmode) {
1239             band->absstepsize = jpc_fix_div(jpc_inttofix(1
1240               << (band->analgain + 1)),
1241               band->synweight);
1242           } else {
1243             band->absstepsize = jpc_inttofix(1);
1244           }
1245           band->stepsize = jpc_abstorelstepsize(
1246             band->absstepsize, cp->ccps[cmptno].prec +
1247             band->analgain);
1248           band->numbps = cp->tccp.numgbits +
1249             JPC_QCX_GETEXPN(band->stepsize) - 1;
1250
1251           if ((!tile->intmode) && band->data) {
1252             quantize(band->data, band->absstepsize);
1253           }
1254
1255           comp->stepsizes[absbandno] = band->stepsize;
1256           ++absbandno;
1257         }
1258       }
1259
1260       assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);
1261       if (!tile->intmode) {
1262         jas_matrix_divpow2(comp->data, JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);
1263       } else {
1264         jas_matrix_asl(comp->data, JPC_NUMEXTRABITS);
1265       }
1266
1267 #if 0
1268 fprintf(stderr, "mingbits %d\n", mingbits);
1269 #endif
1270       if (mingbits > cp->tccp.numgbits) {
1271         fprintf(stderr, "error: too few guard bits (need at least %d)\n",
1272           mingbits);
1273         return -1;
1274       }
1275     }
1276
1277     if (!(enc->tmpstream = jas_stream_memopen(0, 0))) {
1278       fprintf(stderr, "cannot open tmp file\n");
1279       return -1;
1280     }
1281
1282     /* Write the tile header. */
1283     if (!(enc->mrk = jpc_ms_create(JPC_MS_SOT))) {
1284       return -1;
1285     }
1286     sot = &enc->mrk->parms.sot;
1287     sot->len = 0;
1288     sot->tileno = tileno;
1289     sot->partno = 0;
1290     sot->numparts = 1;
1291     if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
1292       fprintf(stderr, "cannot write SOT marker\n");
1293       return -1;
1294     }
1295     jpc_ms_destroy(enc->mrk);
1296     enc->mrk = 0;
1297
1298 /************************************************************************/
1299 /************************************************************************/
1300 /************************************************************************/
1301
1302     tccp = &cp->tccp;
1303     for (cmptno = 0; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno) {
1304       comp = &tile->tcmpts[cmptno];
1305       if (comp->numrlvls != tccp->maxrlvls) {
1306         if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
1307           return -1;
1308         }
1309 /* XXX = this is not really correct. we are using comp #0's precint sizes
1310 and other characteristics */
1311         comp = &tile->tcmpts[0];
1312         cod = &enc->mrk->parms.cod;
1313         cod->compparms.csty = 0;
1314         cod->compparms.numdlvls = comp->numrlvls - 1;
1315         cod->prg = tile->prg;
1316         cod->numlyrs = tile->numlyrs;
1317         cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn);
1318         cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn);
1319         cod->compparms.cblksty = comp->cblksty;
1320         cod->compparms.qmfbid = comp->qmfbid;
1321         cod->mctrans = (tile->mctid != JPC_MCT_NONE);
1322         for (i = 0; i < comp->numrlvls; ++i) {
1323           cod->compparms.rlvls[i].parwidthval = comp->rlvls[i].prcwidthexpn;
1324           cod->compparms.rlvls[i].parheightval = comp->rlvls[i].prcheightexpn;
1325         }
1326         if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
1327           return -1;
1328         }
1329         jpc_ms_destroy(enc->mrk);
1330         enc->mrk = 0;
1331       }
1332     }
1333
1334     for (cmptno = 0, comp = tile->tcmpts; cmptno < JAS_CAST(int, cp->numcmpts); ++cmptno, ++comp) {
1335       ccps = &cp->ccps[cmptno];
1336       if (JAS_CAST(int, ccps->numstepsizes) == comp->numstepsizes) {
1337         samestepsizes = 1;
1338         for (bandno = 0; bandno < JAS_CAST(int, ccps->numstepsizes); ++bandno) {
1339           if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {
1340             samestepsizes = 0;
1341             break;
1342           }
1343         }
1344       } else {
1345         samestepsizes = 0;
1346       }
1347       if (!samestepsizes) {
1348         if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
1349           return -1;
1350         }
1351         qcc = &enc->mrk->parms.qcc;
1352         qcc->compno = cmptno;
1353         qcc->compparms.numguard = cp->tccp.numgbits;
1354         qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?
1355           JPC_QCX_SEQNT : JPC_QCX_NOQNT;
1356         qcc->compparms.numstepsizes = comp->numstepsizes;
1357         qcc->compparms.stepsizes = comp->stepsizes;
1358         if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
1359           return -1;
1360         }
1361         qcc->compparms.stepsizes = 0;
1362         jpc_ms_destroy(enc->mrk);
1363         enc->mrk = 0;
1364       }
1365     }
1366
1367     /* Write a SOD marker to indicate the end of the tile header. */
1368     if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {
1369       return -1;
1370     }
1371     if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
1372       fprintf(stderr, "cannot write SOD marker\n");
1373       return -1;
1374     }
1375     jpc_ms_destroy(enc->mrk);
1376     enc->mrk = 0;
1377 tilehdrlen = jas_stream_getrwcount(enc->tmpstream);
1378
1379 /************************************************************************/
1380 /************************************************************************/
1381 /************************************************************************/
1382
1383 if (jpc_enc_enccblks(enc)) {
1384   abort();
1385   return -1;
1386 }
1387
1388     cp = enc->cp;
1389     rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) /
1390       ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -
1391       cp->imgareatly));
1392     tile->rawsize = (uint_fast32_t)(cp->rawsize * rho);
1393
1394     for (lyrno = 0; lyrno < tile->numlyrs - 1; ++lyrno) {
1395       tile->lyrsizes[lyrno] = (uint_fast32_t)(tile->rawsize * jpc_fixtodbl(
1396         cp->tcp.ilyrrates[lyrno]));
1397     }
1398     tile->lyrsizes[tile->numlyrs - 1] = (uint_fast32_t)((cp->totalsize != UINT_FAST32_MAX) ?
1399       (rho * enc->mainbodysize) : UINT_FAST32_MAX);
1400     for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
1401       if (tile->lyrsizes[lyrno] != UINT_FAST32_MAX) {
1402         if (tilehdrlen <= JAS_CAST(long, tile->lyrsizes[lyrno])) {
1403           tile->lyrsizes[lyrno] -= tilehdrlen;
1404         } else {
1405           tile->lyrsizes[lyrno] = 0;
1406         }
1407       }
1408     }
1409
1410     if (rateallocate(enc, tile->numlyrs, tile->lyrsizes)) {
1411       return -1;
1412     }
1413
1414 #if 0
1415 fprintf(stderr, "ENCODE TILE DATA\n");
1416 #endif
1417     if (jpc_enc_encodetiledata(enc)) {
1418       fprintf(stderr, "dotile failed\n");
1419       return -1;
1420     }
1421
1422 /************************************************************************/
1423 /************************************************************************/
1424 /************************************************************************/
1425
1426 /************************************************************************/
1427 /************************************************************************/
1428 /************************************************************************/
1429
1430     tilelen = jas_stream_tell(enc->tmpstream);
1431
1432     if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {
1433       return -1;
1434     }
1435     jpc_putuint32(enc->tmpstream, tilelen);
1436
1437     if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {
1438       return -1;
1439     }
1440     if (jpc_putdata(enc->out, enc->tmpstream, -1)) {
1441       return -1;
1442     }
1443     enc->len += tilelen;
1444
1445     jas_stream_close(enc->tmpstream);
1446     enc->tmpstream = 0;
1447
1448     jpc_enc_tile_destroy(enc->curtile);
1449     enc->curtile = 0;
1450
1451   }
1452
1453   return 0;
1454 }
1455
1456 int jpc_enc_encodetiledata(jpc_enc_t *enc)
1457 {
1458 assert(enc->tmpstream);
1459   if (jpc_enc_encpkts(enc, enc->tmpstream)) {
1460     return -1;
1461   }
1462   return 0;
1463 }
1464
1465 int dump_passes(jpc_enc_pass_t *passes, int numpasses, jpc_enc_cblk_t *cblk)
1466 {
1467   jpc_enc_pass_t *pass;
1468   int i;
1469   jas_stream_memobj_t *smo;
1470
1471   smo = cblk->stream->obj_;
1472
1473   pass = passes;
1474   for (i = 0; i < numpasses; ++i) {
1475     fprintf(stderr, "start=%d end=%d type=%d term=%d lyrno=%d firstchar=%02x size=%ld pos=%ld\n",
1476       (int)pass->start, (int)pass->end, (int)pass->type, (int)pass->term, (int)pass->lyrno,
1477       smo->buf_[pass->start], (long)smo->len_, (long)smo->pos_);
1478 #if 0
1479     jas_memdump(stderr, &smo->buf_[pass->start], pass->end - pass->start);
1480 #endif
1481     ++pass;
1482   }
1483   return 0;
1484 }
1485
1486 void quantize(jas_matrix_t *data, jpc_fix_t stepsize)
1487 {
1488   int i;
1489   int j;
1490   jpc_fix_t t;
1491
1492   if (stepsize == jpc_inttofix(1)) {
1493     return;
1494   }
1495
1496   for (i = 0; i < jas_matrix_numrows(data); ++i) {
1497     for (j = 0; j < jas_matrix_numcols(data); ++j) {
1498       t = jas_matrix_get(data, i, j);
1499
1500 {
1501   if (t < 0) {
1502     t = jpc_fix_neg(jpc_fix_div(jpc_fix_neg(t), stepsize));
1503   } else {
1504     t = jpc_fix_div(t, stepsize);
1505   }
1506 }
1507
1508       jas_matrix_set(data, i, j, t);
1509     }
1510   }
1511 }
1512
1513 void calcrdslopes(jpc_enc_cblk_t *cblk)
1514 {
1515   jpc_enc_pass_t *endpasses;
1516   jpc_enc_pass_t *pass0;
1517   jpc_enc_pass_t *pass1;
1518   jpc_enc_pass_t *pass2;
1519   jpc_flt_t slope0;
1520   jpc_flt_t slope;
1521   jpc_flt_t dd;
1522   long dr;
1523
1524   endpasses = &cblk->passes[cblk->numpasses];
1525   pass2 = cblk->passes;
1526   slope0 = 0;
1527   while (pass2 != endpasses) {
1528     pass0 = 0;
1529     for (pass1 = cblk->passes; pass1 != endpasses; ++pass1) {
1530       dd = pass1->cumwmsedec;
1531       dr = pass1->end;
1532       if (pass0) {
1533         dd -= pass0->cumwmsedec;
1534         dr -= pass0->end;
1535       }
1536       if (dd <= 0) {
1537         pass1->rdslope = JPC_BADRDSLOPE;
1538         if (pass1 >= pass2) {
1539           pass2 = &pass1[1];
1540         }
1541         continue;
1542       }
1543       if (pass1 < pass2 && pass1->rdslope <= 0) {
1544         continue;
1545       }
1546       if (!dr) {
1547         assert(pass0);
1548         pass0->rdslope = 0;
1549         break;
1550       }
1551       slope = dd / dr;
1552       if (pass0 && slope >= slope0) {
1553         pass0->rdslope = 0;
1554         break;
1555       }
1556       pass1->rdslope = slope;
1557       if (pass1 >= pass2) {
1558         pass2 = &pass1[1];
1559       }
1560       pass0 = pass1;
1561       slope0 = slope;
1562     }
1563   }
1564
1565 #if 0
1566   for (pass0 = cblk->passes; pass0 != endpasses; ++pass0) {
1567 if (pass0->rdslope > 0.0) {
1568     fprintf(stderr, "pass %02d nmsedec=%lf dec=%lf end=%d %lf\n", pass0 - cblk->passes,
1569       fixtodbl(pass0->nmsedec), pass0->wmsedec, pass0->end, pass0->rdslope);
1570 }
1571   }
1572 #endif
1573 }
1574
1575 void dump_layeringinfo(jpc_enc_t *enc)
1576 {
1577
1578   jpc_enc_tcmpt_t *tcmpt;
1579   int tcmptno;
1580   jpc_enc_rlvl_t *rlvl;
1581   int rlvlno;
1582   jpc_enc_band_t *band;
1583   int bandno;
1584   jpc_enc_prc_t *prc;
1585   int prcno;
1586   jpc_enc_cblk_t *cblk;
1587   int cblkno;
1588   jpc_enc_pass_t *pass;
1589   int passno;
1590   int lyrno;
1591   jpc_enc_tile_t *tile;
1592
1593   tile = enc->curtile;
1594
1595   for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
1596     fprintf(stderr, "lyrno = %02d\n", lyrno);
1597     for (tcmptno = 0, tcmpt = tile->tcmpts; tcmptno < tile->numtcmpts;
1598       ++tcmptno, ++tcmpt) {
1599       for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
1600         ++rlvlno, ++rlvl) {
1601         if (!rlvl->bands) {
1602           continue;
1603         }
1604         for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
1605           ++bandno, ++band) {
1606           if (!band->data) {
1607             continue;
1608           }
1609           for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
1610             ++prcno, ++prc) {
1611             if (!prc->cblks) {
1612               continue;
1613             }
1614             for (cblkno = 0, cblk = prc->cblks; cblkno <
1615               prc->numcblks; ++cblkno, ++cblk) {
1616               for (passno = 0, pass = cblk->passes; passno <
1617                 cblk->numpasses && pass->lyrno == lyrno;
1618                 ++passno, ++pass) {
1619                 fprintf(stderr, "lyrno=%02d cmptno=%02d rlvlno=%02d bandno=%02d prcno=%02d cblkno=%03d passno=%03d\n", lyrno, tcmptno, rlvlno, bandno, prcno, cblkno, passno);
1620               }
1621             }
1622           }
1623         }
1624       }
1625     }
1626   }
1627 }
1628
1629 int rateallocate(jpc_enc_t *enc, int numlyrs, uint_fast32_t *cumlens)
1630 {
1631   jpc_flt_t lo;
1632   jpc_flt_t hi;
1633   jas_stream_t *out;
1634   unsigned long cumlen;
1635   int lyrno;
1636   jpc_flt_t thresh;
1637   jpc_flt_t goodthresh;
1638   int success;
1639   long pos;
1640   long oldpos;
1641   int numiters;
1642
1643   jpc_enc_tcmpt_t *comp;
1644   jpc_enc_tcmpt_t *endcomps;
1645   jpc_enc_rlvl_t *lvl;
1646   jpc_enc_rlvl_t *endlvls;
1647   jpc_enc_band_t *band;
1648   jpc_enc_band_t *endbands;
1649   jpc_enc_cblk_t *cblk;
1650   jpc_enc_cblk_t *endcblks;
1651   jpc_enc_pass_t *pass;
1652   jpc_enc_pass_t *endpasses;
1653   jpc_enc_pass_t *pass1;
1654   jpc_flt_t mxrdslope;
1655   jpc_flt_t mnrdslope;
1656   jpc_enc_tile_t *tile;
1657   jpc_enc_prc_t *prc;
1658   int prcno;
1659
1660   tile = enc->curtile;
1661
1662   for (lyrno = 1; lyrno < numlyrs - 1; ++lyrno) {
1663     if (cumlens[lyrno - 1] > cumlens[lyrno]) {
1664       abort();
1665     }
1666   }
1667
1668   if (!(out = jas_stream_memopen(0, 0))) {
1669     return -1;
1670   }
1671
1672
1673   /* Find minimum and maximum R-D slope values. */
1674   mnrdslope = DBL_MAX;
1675   mxrdslope = 0;
1676   endcomps = &tile->tcmpts[tile->numtcmpts];
1677   for (comp = tile->tcmpts; comp != endcomps; ++comp) {
1678     endlvls = &comp->rlvls[comp->numrlvls];
1679     for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
1680       if (!lvl->bands) {
1681         continue;
1682       }
1683       endbands = &lvl->bands[lvl->numbands];
1684       for (band = lvl->bands; band != endbands; ++band) {
1685         if (!band->data) {
1686           continue;
1687         }
1688         for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
1689           if (!prc->cblks) {
1690             continue;
1691           }
1692           endcblks = &prc->cblks[prc->numcblks];
1693           for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
1694             calcrdslopes(cblk);
1695             endpasses = &cblk->passes[cblk->numpasses];
1696             for (pass = cblk->passes; pass != endpasses; ++pass) {
1697               if (pass->rdslope > 0) {
1698                 if (pass->rdslope < mnrdslope) {
1699                   mnrdslope = pass->rdslope;
1700                 }
1701                 if (pass->rdslope > mxrdslope) {
1702                   mxrdslope = pass->rdslope;
1703                 }
1704               }
1705             }
1706           }
1707         }
1708       }
1709     }
1710   }
1711 if (jas_getdbglevel()) {
1712   fprintf(stderr, "min rdslope = %f max rdslope = %f\n", mnrdslope, mxrdslope);
1713 }
1714
1715   jpc_init_t2state(enc, 1);
1716
1717   for (lyrno = 0; lyrno < numlyrs; ++lyrno) {
1718
1719     lo = mnrdslope;
1720     hi = mxrdslope;
1721
1722     success = 0;
1723     goodthresh = 0;
1724     numiters = 0;
1725
1726     do {
1727
1728       cumlen = cumlens[lyrno];
1729       if (cumlen == UINT_FAST32_MAX) {
1730         /* Only the last layer can be free of a rate
1731           constraint (e.g., for lossless coding). */
1732         assert(lyrno == numlyrs - 1);
1733         goodthresh = -1;
1734         success = 1;
1735         break;
1736       }
1737
1738       thresh = (lo + hi) / 2;
1739
1740       /* Save the tier 2 coding state. */
1741       jpc_save_t2state(enc);
1742       oldpos = jas_stream_tell(out);
1743       assert(oldpos >= 0);
1744
1745       /* Assign all passes with R-D slopes greater than or
1746         equal to the current threshold to this layer. */
1747       endcomps = &tile->tcmpts[tile->numtcmpts];
1748       for (comp = tile->tcmpts; comp != endcomps; ++comp) {
1749         endlvls = &comp->rlvls[comp->numrlvls];
1750         for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
1751           if (!lvl->bands) {
1752             continue;
1753           }
1754           endbands = &lvl->bands[lvl->numbands];
1755           for (band = lvl->bands; band != endbands; ++band) {
1756             if (!band->data) {
1757               continue;
1758             }
1759             for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
1760               if (!prc->cblks) {
1761                 continue;
1762               }
1763               endcblks = &prc->cblks[prc->numcblks];
1764               for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
1765                 if (cblk->curpass) {
1766                   endpasses = &cblk->passes[cblk->numpasses];
1767                   pass1 = cblk->curpass;
1768                   for (pass = cblk->curpass; pass != endpasses; ++pass) {
1769                     if (pass->rdslope >= thresh) {
1770                       pass1 = &pass[1];
1771                     }
1772                   }
1773                   for (pass = cblk->curpass; pass != pass1; ++pass) {
1774                     pass->lyrno = lyrno;
1775                   }
1776                   for (; pass != endpasses; ++pass) {
1777                     pass->lyrno = -1;
1778                   }
1779                 }
1780               }
1781             }
1782           }
1783         }
1784       }
1785
1786       /* Perform tier 2 coding. */
1787       endcomps = &tile->tcmpts[tile->numtcmpts];
1788       for (comp = tile->tcmpts; comp != endcomps; ++comp) {
1789         endlvls = &comp->rlvls[comp->numrlvls];
1790         for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
1791           if (!lvl->bands) {
1792             continue;
1793           }
1794           for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
1795             if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) {
1796               return -1;
1797             }
1798           }
1799         }
1800       }
1801
1802       pos = jas_stream_tell(out);
1803
1804       /* Check the rate constraint. */
1805       assert(pos >= 0);
1806       if (pos > (long)cumlen) {
1807         /* The rate is too high. */
1808         lo = thresh;
1809       } else if (pos <= (long)cumlen) {
1810         /* The rate is low enough, so try higher. */
1811         hi = thresh;
1812         if (!success || thresh < goodthresh) {
1813           goodthresh = thresh;
1814           success = 1;
1815         }
1816       }
1817
1818       /* Save the tier 2 coding state. */
1819       jpc_restore_t2state(enc);
1820       if (jas_stream_seek(out, oldpos, SEEK_SET) < 0) {
1821         abort();
1822       }
1823
1824 if (jas_getdbglevel()) {
1825 fprintf(stderr, "maxlen=%08ld actuallen=%08ld thresh=%f\n", cumlen, pos, thresh);
1826 }
1827
1828       ++numiters;
1829     } while (lo < hi - 1e-3 && numiters < 32);
1830
1831     if (!success) {
1832       fprintf(stderr, "warning: empty layer generated\n");
1833     }
1834
1835 if (jas_getdbglevel()) {
1836 fprintf(stderr, "success %d goodthresh %f\n", success, goodthresh);
1837 }
1838
1839     /* Assign all passes with R-D slopes greater than or
1840       equal to the selected threshold to this layer. */
1841     endcomps = &tile->tcmpts[tile->numtcmpts];
1842     for (comp = tile->tcmpts; comp != endcomps; ++comp) {
1843       endlvls = &comp->rlvls[comp->numrlvls];
1844       for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
1845 if (!lvl->bands) {
1846   continue;
1847 }
1848         endbands = &lvl->bands[lvl->numbands];
1849         for (band = lvl->bands; band != endbands; ++band) {
1850           if (!band->data) {
1851             continue;
1852           }
1853           for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
1854             if (!prc->cblks) {
1855               continue;
1856             }
1857             endcblks = &prc->cblks[prc->numcblks];
1858             for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
1859               if (cblk->curpass) {
1860                 endpasses = &cblk->passes[cblk->numpasses];
1861                 pass1 = cblk->curpass;
1862                 if (success) {
1863                   for (pass = cblk->curpass; pass != endpasses; ++pass) {
1864                     if (pass->rdslope >= goodthresh) {
1865                       pass1 = &pass[1];
1866                     }
1867                   }
1868                 }
1869                 for (pass = cblk->curpass; pass != pass1; ++pass) {
1870                   pass->lyrno = lyrno;
1871                 }
1872                 for (; pass != endpasses; ++pass) {
1873                   pass->lyrno = -1;
1874                 }
1875               }
1876             }
1877           }
1878         }
1879       }
1880     }
1881
1882     /* Perform tier 2 coding. */
1883     endcomps = &tile->tcmpts[tile->numtcmpts];
1884     for (comp = tile->tcmpts; comp != endcomps; ++comp) {
1885       endlvls = &comp->rlvls[comp->numrlvls];
1886       for (lvl = comp->rlvls; lvl != endlvls; ++lvl) {
1887         if (!lvl->bands) {
1888           continue;
1889         }
1890         for (prcno = 0; prcno < lvl->numprcs; ++prcno) {
1891           if (jpc_enc_encpkt(enc, out, comp - tile->tcmpts, lvl - comp->rlvls, prcno, lyrno)) {
1892             return -1;
1893           }
1894         }
1895       }
1896     }
1897   }
1898
1899   if (jas_getdbglevel() >= 5) {
1900     dump_layeringinfo(enc);
1901   }
1902
1903   jas_stream_close(out);
1904
1905   JAS_DBGLOG(10, ("done doing rateallocation\n"));
1906 #if 0
1907 fprintf(stderr, "DONE RATE ALLOCATE\n");
1908 #endif
1909
1910   return 0;
1911 }
1912
1913 /******************************************************************************\
1914 * Tile constructors and destructors.
1915 \******************************************************************************/
1916
1917 jpc_enc_tile_t *jpc_enc_tile_create(jpc_enc_cp_t *cp, jas_image_t *image, int tileno)
1918 {
1919   jpc_enc_tile_t *tile;
1920   uint_fast32_t htileno;
1921   uint_fast32_t vtileno;
1922   int_fast16_t lyrno;
1923   uint_fast16_t cmptno;
1924   jpc_enc_tcmpt_t *tcmpt;
1925
1926   if (!(tile = jas_malloc(sizeof(jpc_enc_tile_t)))) {
1927     goto error;
1928   }
1929
1930   /* Initialize a few members used in error recovery. */
1931   tile->tcmpts = 0;
1932   tile->lyrsizes = 0;
1933   tile->numtcmpts = cp->numcmpts;
1934   tile->pi = 0;
1935
1936   tile->tileno = tileno;
1937   htileno = tileno % cp->numhtiles;
1938   vtileno = tileno / cp->numhtiles;
1939
1940   /* Calculate the coordinates of the top-left and bottom-right
1941     corners of the tile. */
1942   tile->tlx = JAS_MAX(cp->tilegrdoffx + htileno * cp->tilewidth,
1943     cp->imgareatlx);
1944   tile->tly = JAS_MAX(cp->tilegrdoffy + vtileno * cp->tileheight,
1945     cp->imgareatly);
1946   tile->brx = JAS_MIN(cp->tilegrdoffx + (htileno + 1) * cp->tilewidth,
1947     cp->refgrdwidth);
1948   tile->bry = JAS_MIN(cp->tilegrdoffy + (vtileno + 1) * cp->tileheight,
1949     cp->refgrdheight);
1950
1951   /* Initialize some tile coding parameters. */
1952   tile->intmode = cp->tcp.intmode;
1953   tile->csty = cp->tcp.csty;
1954   tile->prg = cp->tcp.prg;
1955   tile->mctid = cp->tcp.mctid;
1956
1957   tile->numlyrs = cp->tcp.numlyrs;
1958   if (!(tile->lyrsizes = jas_malloc(tile->numlyrs *
1959     sizeof(uint_fast32_t)))) {
1960     goto error;
1961   }
1962   for (lyrno = 0; lyrno < tile->numlyrs; ++lyrno) {
1963     tile->lyrsizes[lyrno] = 0;
1964   }
1965
1966   /* Allocate an array for the per-tile-component information. */
1967   if (!(tile->tcmpts = jas_malloc(cp->numcmpts * sizeof(jpc_enc_tcmpt_t)))) {
1968     goto error;
1969   }
1970   /* Initialize a few members critical for error recovery. */
1971   for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
1972     ++cmptno, ++tcmpt) {
1973     tcmpt->rlvls = 0;
1974     tcmpt->tsfb = 0;
1975     tcmpt->data = 0;
1976   }
1977   /* Initialize the per-tile-component information. */
1978   for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
1979     ++cmptno, ++tcmpt) {
1980     if (!tcmpt_create(tcmpt, cp, image, tile)) {
1981       goto error;
1982     }
1983   }
1984
1985   /* Initialize the synthesis weights for the MCT. */
1986   switch (tile->mctid) {
1987   case JPC_MCT_RCT:
1988     tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0));
1989     tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(0.6875));
1990     tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(0.6875));
1991     break;
1992   case JPC_MCT_ICT:
1993     tile->tcmpts[0].synweight = jpc_dbltofix(sqrt(3.0000));
1994     tile->tcmpts[1].synweight = jpc_dbltofix(sqrt(3.2584));
1995     tile->tcmpts[2].synweight = jpc_dbltofix(sqrt(2.4755));
1996     break;
1997   default:
1998   case JPC_MCT_NONE:
1999     for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < cp->numcmpts;
2000       ++cmptno, ++tcmpt) {
2001       tcmpt->synweight = JPC_FIX_ONE;
2002     }
2003     break;
2004   }
2005
2006   if (!(tile->pi = jpc_enc_pi_create(cp, tile))) {
2007     goto error;
2008   }
2009
2010   return tile;
2011
2012 error:
2013
2014   if (tile) {
2015     jpc_enc_tile_destroy(tile);
2016   }
2017   return 0;
2018 }
2019
2020 void jpc_enc_tile_destroy(jpc_enc_tile_t *tile)
2021 {
2022   jpc_enc_tcmpt_t *tcmpt;
2023   int_fast16_t cmptno;
2024
2025   if (tile->tcmpts) {
2026     for (cmptno = 0, tcmpt = tile->tcmpts; cmptno <
2027       tile->numtcmpts; ++cmptno, ++tcmpt) {
2028       tcmpt_destroy(tcmpt);
2029     }
2030     jas_free(tile->tcmpts);
2031   }
2032   if (tile->lyrsizes) {
2033     jas_free(tile->lyrsizes);
2034   }
2035   if (tile->pi) {
2036     jpc_pi_destroy(tile->pi);
2037   }
2038   jas_free(tile);
2039 }
2040
2041 static jpc_enc_tcmpt_t *tcmpt_create(jpc_enc_tcmpt_t *tcmpt, jpc_enc_cp_t *cp,
2042   jas_image_t *image, jpc_enc_tile_t *tile)
2043 {
2044   uint_fast16_t cmptno;
2045   int_fast16_t rlvlno;
2046   jpc_enc_rlvl_t *rlvl;
2047   uint_fast32_t tlx;
2048   uint_fast32_t tly;
2049   uint_fast32_t brx;
2050   uint_fast32_t bry;
2051   uint_fast32_t cmpttlx;
2052   uint_fast32_t cmpttly;
2053   jpc_enc_ccp_t *ccp;
2054   jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
2055
2056   tcmpt->tile = tile;
2057   tcmpt->tsfb = 0;
2058   tcmpt->data = 0;
2059   tcmpt->rlvls = 0;
2060
2061   /* Deduce the component number. */
2062   cmptno = tcmpt - tile->tcmpts;
2063
2064   ccp = &cp->ccps[cmptno];
2065
2066   /* Compute the coordinates of the top-left and bottom-right
2067     corners of this tile-component. */
2068   tlx = JPC_CEILDIV(tile->tlx, ccp->sampgrdstepx);
2069   tly = JPC_CEILDIV(tile->tly, ccp->sampgrdstepy);
2070   brx = JPC_CEILDIV(tile->brx, ccp->sampgrdstepx);
2071   bry = JPC_CEILDIV(tile->bry, ccp->sampgrdstepy);
2072
2073   /* Create a sequence to hold the tile-component sample data. */
2074   if (!(tcmpt->data = jas_seq2d_create(tlx, tly, brx, bry))) {
2075     goto error;
2076   }
2077
2078   /* Get the image data associated with this tile-component. */
2079   cmpttlx = JPC_CEILDIV(cp->imgareatlx, ccp->sampgrdstepx);
2080   cmpttly = JPC_CEILDIV(cp->imgareatly, ccp->sampgrdstepy);
2081   if (jas_image_readcmpt(image, cmptno, tlx - cmpttlx, tly - cmpttly,
2082     brx - tlx, bry - tly, tcmpt->data)) {
2083     goto error;
2084   }
2085
2086   tcmpt->synweight = 0;
2087   tcmpt->qmfbid = cp->tccp.qmfbid;
2088   tcmpt->numrlvls = cp->tccp.maxrlvls;
2089   tcmpt->numbands = 3 * tcmpt->numrlvls - 2;
2090   if (!(tcmpt->tsfb = jpc_cod_gettsfb(tcmpt->qmfbid, tcmpt->numrlvls - 1))) {
2091     goto error;
2092   }
2093
2094   for (rlvlno = 0; rlvlno < tcmpt->numrlvls; ++rlvlno) {
2095     tcmpt->prcwidthexpns[rlvlno] = cp->tccp.prcwidthexpns[rlvlno];
2096     tcmpt->prcheightexpns[rlvlno] = cp->tccp.prcheightexpns[rlvlno];
2097   }
2098   tcmpt->cblkwidthexpn = cp->tccp.cblkwidthexpn;
2099   tcmpt->cblkheightexpn = cp->tccp.cblkheightexpn;
2100   tcmpt->cblksty = cp->tccp.cblksty;
2101   tcmpt->csty = cp->tccp.csty;
2102
2103   tcmpt->numstepsizes = tcmpt->numbands;
2104   assert(tcmpt->numstepsizes <= JPC_MAXBANDS);
2105   memset(tcmpt->stepsizes, 0, sizeof(tcmpt->numstepsizes *
2106     sizeof(uint_fast16_t)));
2107
2108   /* Retrieve information about the various bands. */
2109   jpc_tsfb_getbands(tcmpt->tsfb, jas_seq2d_xstart(tcmpt->data),
2110     jas_seq2d_ystart(tcmpt->data), jas_seq2d_xend(tcmpt->data),
2111     jas_seq2d_yend(tcmpt->data), bandinfos);
2112
2113   if (!(tcmpt->rlvls = jas_malloc(tcmpt->numrlvls * sizeof(jpc_enc_rlvl_t)))) {
2114     goto error;
2115   }
2116   for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
2117     ++rlvlno, ++rlvl) {
2118     rlvl->bands = 0;
2119     rlvl->tcmpt = tcmpt;
2120   }
2121   for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
2122     ++rlvlno, ++rlvl) {
2123     if (!rlvl_create(rlvl, cp, tcmpt, bandinfos)) {
2124       goto error;
2125     }
2126   }
2127
2128   return tcmpt;
2129
2130 error:
2131
2132   tcmpt_destroy(tcmpt);
2133   return 0;
2134
2135 }
2136
2137 static void tcmpt_destroy(jpc_enc_tcmpt_t *tcmpt)
2138 {
2139   jpc_enc_rlvl_t *rlvl;
2140   int_fast16_t rlvlno;
2141
2142   if (tcmpt->rlvls) {
2143     for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
2144       ++rlvlno, ++rlvl) {
2145       rlvl_destroy(rlvl);
2146     }
2147     jas_free(tcmpt->rlvls);
2148   }
2149
2150   if (tcmpt->data) {
2151     jas_seq2d_destroy(tcmpt->data);
2152   }
2153   if (tcmpt->tsfb) {
2154     jpc_tsfb_destroy(tcmpt->tsfb);
2155   }
2156 }
2157
2158 static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp,
2159   jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos)
2160 {
2161   uint_fast16_t rlvlno;
2162   uint_fast32_t tlprctlx;
2163   uint_fast32_t tlprctly;
2164   uint_fast32_t brprcbrx;
2165   uint_fast32_t brprcbry;
2166   int_fast16_t bandno;
2167   jpc_enc_band_t *band;
2168
2169   /* Deduce the resolution level. */
2170   rlvlno = rlvl - tcmpt->rlvls;
2171
2172   /* Initialize members required for error recovery. */
2173   rlvl->bands = 0;
2174   rlvl->tcmpt = tcmpt;
2175
2176   /* Compute the coordinates of the top-left and bottom-right
2177     corners of the tile-component at this resolution. */
2178   rlvl->tlx = JPC_CEILDIVPOW2(jas_seq2d_xstart(tcmpt->data), tcmpt->numrlvls -
2179     1 - rlvlno);
2180   rlvl->tly = JPC_CEILDIVPOW2(jas_seq2d_ystart(tcmpt->data), tcmpt->numrlvls -
2181     1 - rlvlno);
2182   rlvl->brx = JPC_CEILDIVPOW2(jas_seq2d_xend(tcmpt->data), tcmpt->numrlvls -
2183     1 - rlvlno);
2184   rlvl->bry = JPC_CEILDIVPOW2(jas_seq2d_yend(tcmpt->data), tcmpt->numrlvls -
2185     1 - rlvlno);
2186
2187   if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) {
2188     rlvl->numhprcs = 0;
2189     rlvl->numvprcs = 0;
2190     rlvl->numprcs = 0;
2191     return rlvl;
2192   }
2193
2194   rlvl->numbands = (!rlvlno) ? 1 : 3;
2195   rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno];
2196   rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno];
2197   if (!rlvlno) {
2198     rlvl->cbgwidthexpn = rlvl->prcwidthexpn;
2199     rlvl->cbgheightexpn = rlvl->prcheightexpn;
2200   } else {
2201     rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1;
2202     rlvl->cbgheightexpn = rlvl->prcheightexpn - 1;
2203   }
2204   rlvl->cblkwidthexpn = JAS_MIN((int)cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn);
2205   rlvl->cblkheightexpn = JAS_MIN((int)cp->tccp.cblkheightexpn, rlvl->cbgheightexpn);
2206
2207   /* Compute the number of precincts. */
2208   tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
2209   tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
2210   brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn);
2211   brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn);
2212   rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn);
2213   rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn);
2214   rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs;
2215
2216   if (!(rlvl->bands = jas_malloc(rlvl->numbands * sizeof(jpc_enc_band_t)))) {
2217     goto error;
2218   }
2219   for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
2220     ++bandno, ++band) {
2221     band->prcs = 0;
2222     band->data = 0;
2223     band->rlvl = rlvl;
2224   }
2225   for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
2226     ++bandno, ++band) {
2227     if (!band_create(band, cp, rlvl, bandinfos)) {
2228       goto error;
2229     }
2230   }
2231
2232   return rlvl;
2233 error:
2234
2235   rlvl_destroy(rlvl);
2236   return 0;
2237 }
2238
2239 static void rlvl_destroy(jpc_enc_rlvl_t *rlvl)
2240 {
2241   jpc_enc_band_t *band;
2242   int_fast16_t bandno;
2243
2244   if (rlvl->bands) {
2245     for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
2246       ++bandno, ++band) {
2247       band_destroy(band);
2248     }
2249     jas_free(rlvl->bands);
2250   }
2251 }
2252
2253 static jpc_enc_band_t *band_create(jpc_enc_band_t *band, jpc_enc_cp_t *cp,
2254   jpc_enc_rlvl_t *rlvl, jpc_tsfb_band_t *bandinfos)
2255 {
2256   uint_fast16_t bandno;
2257   uint_fast16_t gblbandno;
2258   uint_fast16_t rlvlno;
2259   jpc_tsfb_band_t *bandinfo;
2260   jpc_enc_tcmpt_t *tcmpt;
2261   int_fast32_t prcno;
2262   jpc_enc_prc_t *prc;
2263
2264   tcmpt = rlvl->tcmpt;
2265   band->data = 0;
2266   band->prcs = 0;
2267   band->rlvl = rlvl;
2268
2269   /* Deduce the resolution level and band number. */
2270   rlvlno = rlvl - rlvl->tcmpt->rlvls;
2271   bandno = band - rlvl->bands;
2272   gblbandno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1);
2273
2274   bandinfo = &bandinfos[gblbandno];
2275
2276 if (bandinfo->xstart != bandinfo->xend && bandinfo->ystart != bandinfo->yend) {
2277   if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) {
2278     goto error;
2279   }
2280   jas_seq2d_bindsub(band->data, tcmpt->data, bandinfo->locxstart,
2281     bandinfo->locystart, bandinfo->locxend, bandinfo->locyend);
2282   jas_seq2d_setshift(band->data, bandinfo->xstart, bandinfo->ystart);
2283 }
2284   band->orient = bandinfo->orient;
2285   band->analgain = JPC_NOMINALGAIN(cp->tccp.qmfbid, tcmpt->numrlvls, rlvlno,
2286     band->orient);
2287   band->numbps = 0;
2288   band->absstepsize = 0;
2289   band->stepsize = 0;
2290   band->synweight = bandinfo->synenergywt;
2291
2292 if (band->data) {
2293   if (!(band->prcs = jas_malloc(rlvl->numprcs * sizeof(jpc_enc_prc_t)))) {
2294     goto error;
2295   }
2296   for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
2297     ++prc) {
2298     prc->cblks = 0;
2299     prc->incltree = 0;
2300     prc->nlibtree = 0;
2301     prc->savincltree = 0;
2302     prc->savnlibtree = 0;
2303     prc->band = band;
2304   }
2305   for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs; ++prcno,
2306     ++prc) {
2307     if (!prc_create(prc, cp, band)) {
2308       goto error;
2309     }
2310   }
2311 }
2312
2313   return band;
2314
2315 error:
2316   band_destroy(band);
2317   return 0;
2318 }
2319
2320 static void band_destroy(jpc_enc_band_t *band)
2321 {
2322   jpc_enc_prc_t *prc;
2323   jpc_enc_rlvl_t *rlvl;
2324   int_fast32_t prcno;
2325
2326   if (band->prcs) {
2327     rlvl = band->rlvl;
2328     for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
2329       ++prcno, ++prc) {
2330       prc_destroy(prc);
2331     }
2332     jas_free(band->prcs);
2333   }
2334   if (band->data) {
2335     jas_seq2d_destroy(band->data);
2336   }
2337 }
2338
2339 static jpc_enc_prc_t *prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, jpc_enc_band_t *band)
2340 {
2341   uint_fast32_t prcno;
2342   uint_fast32_t prcxind;
2343   uint_fast32_t prcyind;
2344   uint_fast32_t cbgtlx;
2345   uint_fast32_t cbgtly;
2346   uint_fast32_t tlprctlx;
2347   uint_fast32_t tlprctly;
2348   uint_fast32_t tlcbgtlx;
2349   uint_fast32_t tlcbgtly;
2350   uint_fast16_t rlvlno;
2351   jpc_enc_rlvl_t *rlvl;
2352   uint_fast32_t tlcblktlx;
2353   uint_fast32_t tlcblktly;
2354   uint_fast32_t brcblkbrx;
2355   uint_fast32_t brcblkbry;
2356   int_fast32_t cblkno;
2357   jpc_enc_cblk_t *cblk;
2358   jpc_enc_tcmpt_t *tcmpt;
2359
2360   prc->cblks = 0;
2361   prc->incltree = 0;
2362   prc->savincltree = 0;
2363   prc->nlibtree = 0;
2364   prc->savnlibtree = 0;
2365
2366   rlvl = band->rlvl;
2367   tcmpt = rlvl->tcmpt;
2368 rlvlno = rlvl - tcmpt->rlvls;
2369   prcno = prc - band->prcs;
2370   prcxind = prcno % rlvl->numhprcs;
2371   prcyind = prcno / rlvl->numhprcs;
2372   prc->band = band;
2373
2374 tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn);
2375 tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn);
2376 if (!rlvlno) {
2377   tlcbgtlx = tlprctlx;
2378   tlcbgtly = tlprctly;
2379 } else {
2380   tlcbgtlx = JPC_CEILDIVPOW2(tlprctlx, 1);
2381   tlcbgtly = JPC_CEILDIVPOW2(tlprctly, 1);
2382 }
2383
2384   /* Compute the coordinates of the top-left and bottom-right
2385     corners of the precinct. */
2386   cbgtlx = tlcbgtlx + (prcxind << rlvl->cbgwidthexpn);
2387   cbgtly = tlcbgtly + (prcyind << rlvl->cbgheightexpn);
2388   prc->tlx = JAS_MAX((uint_fast32_t)jas_seq2d_xstart(band->data), cbgtlx);
2389   prc->tly = JAS_MAX((uint_fast32_t)jas_seq2d_ystart(band->data), cbgtly);
2390   prc->brx = JAS_MIN((uint_fast32_t)jas_seq2d_xend(band->data), cbgtlx +
2391     (1 << rlvl->cbgwidthexpn));
2392   prc->bry = JAS_MIN((uint_fast32_t)jas_seq2d_yend(band->data), cbgtly +
2393     (1 << rlvl->cbgheightexpn));
2394
2395   if (prc->tlx < prc->brx && prc->tly < prc->bry) {
2396     /* The precinct contains at least one code block. */
2397
2398     tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
2399     tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
2400     brcblkbrx = JPC_CEILTOMULTPOW2(prc->brx, rlvl->cblkwidthexpn);
2401     brcblkbry = JPC_CEILTOMULTPOW2(prc->bry, rlvl->cblkheightexpn);
2402     prc->numhcblks = JPC_FLOORDIVPOW2(brcblkbrx - tlcblktlx,
2403       rlvl->cblkwidthexpn);
2404     prc->numvcblks = JPC_FLOORDIVPOW2(brcblkbry - tlcblktly,
2405       rlvl->cblkheightexpn);
2406     prc->numcblks = prc->numhcblks * prc->numvcblks;
2407
2408     if (!(prc->incltree = jpc_tagtree_create(prc->numhcblks,
2409       prc->numvcblks))) {
2410       goto error;
2411     }
2412     if (!(prc->nlibtree = jpc_tagtree_create(prc->numhcblks,
2413       prc->numvcblks))) {
2414       goto error;
2415     }
2416     if (!(prc->savincltree = jpc_tagtree_create(prc->numhcblks,
2417       prc->numvcblks))) {
2418       goto error;
2419     }
2420     if (!(prc->savnlibtree = jpc_tagtree_create(prc->numhcblks,
2421       prc->numvcblks))) {
2422       goto error;
2423     }
2424
2425     if (!(prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_enc_cblk_t)))) {
2426       goto error;
2427     }
2428     for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
2429       ++cblkno, ++cblk) {
2430       cblk->passes = 0;
2431       cblk->stream = 0;
2432       cblk->mqenc = 0;
2433       cblk->data = 0;
2434       cblk->flags = 0;
2435       cblk->prc = prc;
2436     }
2437     for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
2438       ++cblkno, ++cblk) {
2439       if (!cblk_create(cblk, cp, prc)) {
2440         goto error;
2441       }
2442     }
2443   } else {
2444     /* The precinct does not contain any code blocks. */
2445     prc->tlx = prc->brx;
2446     prc->tly = prc->bry;
2447     prc->numcblks = 0;
2448     prc->numhcblks = 0;
2449     prc->numvcblks = 0;
2450     prc->cblks = 0;
2451     prc->incltree = 0;
2452     prc->nlibtree = 0;
2453     prc->savincltree = 0;
2454     prc->savnlibtree = 0;
2455   }
2456
2457   return prc;
2458
2459 error:
2460   prc_destroy(prc);
2461   return 0;
2462 }
2463
2464 static void prc_destroy(jpc_enc_prc_t *prc)
2465 {
2466   jpc_enc_cblk_t *cblk;
2467   int_fast32_t cblkno;
2468
2469   if (prc->cblks) {
2470     for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
2471       ++cblkno, ++cblk) {
2472       cblk_destroy(cblk);
2473     }
2474     jas_free(prc->cblks);
2475   }
2476   if (prc->incltree) {
2477     jpc_tagtree_destroy(prc->incltree);
2478   }
2479   if (prc->nlibtree) {
2480     jpc_tagtree_destroy(prc->nlibtree);
2481   }
2482   if (prc->savincltree) {
2483     jpc_tagtree_destroy(prc->savincltree);
2484   }
2485   if (prc->savnlibtree) {
2486     jpc_tagtree_destroy(prc->savnlibtree);
2487   }
2488 }
2489
2490 static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp, jpc_enc_prc_t *prc)
2491 {
2492   jpc_enc_band_t *band;
2493   uint_fast32_t cblktlx;
2494   uint_fast32_t cblktly;
2495   uint_fast32_t cblkbrx;
2496   uint_fast32_t cblkbry;
2497   jpc_enc_rlvl_t *rlvl;
2498   uint_fast32_t cblkxind;
2499   uint_fast32_t cblkyind;
2500   uint_fast32_t cblkno;
2501   uint_fast32_t tlcblktlx;
2502   uint_fast32_t tlcblktly;
2503   /* unused:*/
2504   (void)cp;
2505
2506   cblkno = cblk - prc->cblks;
2507   cblkxind = cblkno % prc->numhcblks;
2508   cblkyind = cblkno / prc->numhcblks;
2509   rlvl = prc->band->rlvl;
2510   cblk->prc = prc;
2511
2512   cblk->numpasses = 0;
2513   cblk->passes = 0;
2514   cblk->numencpasses = 0;
2515   cblk->numimsbs = 0;
2516   cblk->numlenbits = 0;
2517   cblk->stream = 0;
2518   cblk->mqenc = 0;
2519   cblk->flags = 0;
2520   cblk->numbps = 0;
2521   cblk->curpass = 0;
2522   cblk->data = 0;
2523   cblk->savedcurpass = 0;
2524   cblk->savednumlenbits = 0;
2525   cblk->savednumencpasses = 0;
2526
2527   band = prc->band;
2528   tlcblktlx = JPC_FLOORTOMULTPOW2(prc->tlx, rlvl->cblkwidthexpn);
2529   tlcblktly = JPC_FLOORTOMULTPOW2(prc->tly, rlvl->cblkheightexpn);
2530   cblktlx = JAS_MAX(tlcblktlx + (cblkxind << rlvl->cblkwidthexpn), prc->tlx);
2531   cblktly = JAS_MAX(tlcblktly + (cblkyind << rlvl->cblkheightexpn), prc->tly);
2532   cblkbrx = JAS_MIN(tlcblktlx + ((cblkxind + 1) << rlvl->cblkwidthexpn),
2533     prc->brx);
2534   cblkbry = JAS_MIN(tlcblktly + ((cblkyind + 1) << rlvl->cblkheightexpn),
2535     prc->bry);
2536
2537   assert(cblktlx < cblkbrx && cblktly < cblkbry);
2538   if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) {
2539     goto error;
2540   }
2541   jas_seq2d_bindsub(cblk->data, band->data, cblktlx, cblktly, cblkbrx, cblkbry);
2542
2543   return cblk;
2544
2545 error:
2546   cblk_destroy(cblk);
2547   return 0;
2548 }
2549
2550 static void cblk_destroy(jpc_enc_cblk_t *cblk)
2551 {
2552   int_fast16_t passno;
2553   jpc_enc_pass_t *pass;
2554   if (cblk->passes) {
2555     for (passno = 0, pass = cblk->passes; passno < cblk->numpasses;
2556       ++passno, ++pass) {
2557       pass_destroy(pass);
2558     }
2559     jas_free(cblk->passes);
2560   }
2561   if (cblk->stream) {
2562     jas_stream_close(cblk->stream);
2563   }
2564   if (cblk->mqenc) {
2565     jpc_mqenc_destroy(cblk->mqenc);
2566   }
2567   if (cblk->data) {
2568     jas_seq2d_destroy(cblk->data);
2569   }
2570   if (cblk->flags) {
2571     jas_seq2d_destroy(cblk->flags);
2572   }
2573 }
2574
2575 static void pass_destroy(jpc_enc_pass_t *pass)
2576 {
2577   /* XXX - need to free resources here */
2578   (void)pass;
2579 }
2580
2581 void jpc_enc_dump(jpc_enc_t *enc)
2582 {
2583   jpc_enc_tile_t *tile;
2584   jpc_enc_tcmpt_t *tcmpt;
2585   jpc_enc_rlvl_t *rlvl;
2586   jpc_enc_band_t *band;
2587   jpc_enc_prc_t *prc;
2588   jpc_enc_cblk_t *cblk;
2589   int_fast16_t cmptno;
2590   int_fast16_t rlvlno;
2591   int_fast16_t bandno;
2592   int_fast32_t prcno;
2593   int_fast32_t cblkno;
2594
2595   tile = enc->curtile;
2596
2597   for (cmptno = 0, tcmpt = tile->tcmpts; cmptno < tile->numtcmpts; ++cmptno,
2598     ++tcmpt) {
2599     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));
2600     for (rlvlno = 0, rlvl = tcmpt->rlvls; rlvlno < tcmpt->numrlvls;
2601       ++rlvlno, ++rlvl) {
2602       fprintf(stderr, "    rlvl %5d %5d %5d %5d\n", rlvl->tlx, rlvl->tly, rlvl->brx, rlvl->bry);
2603       for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
2604         ++bandno, ++band) {
2605         if (!band->data) {
2606           continue;
2607         }
2608         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));
2609         for (prcno = 0, prc = band->prcs; prcno < rlvl->numprcs;
2610           ++prcno, ++prc) {
2611           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);
2612           if (!prc->cblks) {
2613             continue;
2614           }
2615           for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks;
2616             ++cblkno, ++cblk) {
2617             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));
2618           }
2619         }
2620       }
2621     }
2622   }
2623 }