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