001/*
002 * $RCSfile: BitstreamReaderAgent.java,v $
003 * $Revision: 1.1 $
004 * $Date: 2005/02/11 05:02:00 $
005 * $State: Exp $
006 *
007 * Class:                   BitstreamReaderAgent
008 *
009 * Description:             The generic interface for bit stream
010 *                          transport agents.
011 *
012 *
013 *
014 * COPYRIGHT:
015 *
016 * This software module was originally developed by Raphaël Grosbois and
017 * Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
018 * Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David
019 * Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research
020 * Centre France S.A) in the course of development of the JPEG2000
021 * standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This
022 * software module is an implementation of a part of the JPEG 2000
023 * Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio
024 * Systems AB and Canon Research Centre France S.A (collectively JJ2000
025 * Partners) agree not to assert against ISO/IEC and users of the JPEG
026 * 2000 Standard (Users) any of their rights under the copyright, not
027 * including other intellectual property rights, for this software module
028 * with respect to the usage by ISO/IEC and Users of this software module
029 * or modifications thereof for use in hardware or software products
030 * claiming conformance to the JPEG 2000 Standard. Those intending to use
031 * this software module in hardware or software products are advised that
032 * their use may infringe existing patents. The original developers of
033 * this software module, JJ2000 Partners and ISO/IEC assume no liability
034 * for use of this software module or modifications thereof. No license
035 * or right to this software module is granted for non JPEG 2000 Standard
036 * conforming products. JJ2000 Partners have full right to use this
037 * software module for his/her own purpose, assign or donate this
038 * software module to any third party and to inhibit third parties from
039 * using this software module for non JPEG 2000 Standard conforming
040 * products. This copyright notice must be included in all copies or
041 * derivative works of this software module.
042 *
043 * Copyright (c) 1999/2000 JJ2000 Partners.
044 *  */
045package jj2000.j2k.codestream.reader;
046import java.awt.Point;
047
048import jj2000.j2k.quantization.dequantizer.*;
049import jj2000.j2k.wavelet.synthesis.*;
050import jj2000.j2k.entropy.decoder.*;
051import jj2000.j2k.codestream.*;
052import jj2000.j2k.wavelet.*;
053import jj2000.j2k.decoder.*;
054import jj2000.j2k.image.*;
055import jj2000.j2k.util.*;
056import jj2000.j2k.io.*;
057import jj2000.j2k.*;
058
059import java.io.*;
060
061import com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReadParamJava;
062
063/**
064 * This is the generic interface for bit stream reader agents. A bit stream
065 * reader agent is an entity that allows reading from a bit stream and
066 * requesting compressed code-blocks. It can be a simple file reader, or a
067 * network connection, or anything else.
068 *
069 * <P>The bit stream reader agent allows to make request for compressed block
070 * data in any order. The amount of data returned would normally depend on the
071 * data available at the time of the request, be it from a file or from a
072 * network connection.
073 *
074 * <P>The bit stream reader agent has the notion of a current tile, and
075 * coordinates are relative to the current tile, where applicable.
076 *
077 * <P>Resolution level 0 is the lowest resolution level, i.e. the LL subband
078 * alone.
079 * */
080public abstract class BitstreamReaderAgent implements CodedCBlkDataSrcDec {
081
082    /** The decoder specifications */
083    protected DecoderSpecs decSpec;
084
085    /**
086     * Whether or not the components in the current tile uses a derived
087     * quantization step size (only relevant in non reversible quantization
088     * mode). This field is actualized by the setTile method in
089     * FileBitstreamReaderAgent.
090     *
091     * @see FileBitstreamReaderAgent#initSubbandsFields
092     * */
093    protected boolean derived[] = null;
094
095    /**
096     * Number of guard bits off all component in the current tile. This field
097     * is actualized by the setTile method in FileBitstreamReaderAgent.
098     *
099     * @see FileBitstreamReaderAgent#initSubbandsFields
100     * */
101    protected int[] gb = null;
102
103    /**
104     * Dequantization parameters of all subbands and all components in the
105     * current tile. The value is actualized by the setTile method in
106     * FileBitstreamReaderAgent.
107     *
108     * @see FileBitstreamReaderAgent#initSubbandsFields
109     * */
110    protected StdDequantizerParams params[] = null;
111
112    /** The prefix for bit stream reader options: 'B' */
113    public final static char OPT_PREFIX = 'B';
114
115    /** The list of parameters that is accepted by the bit stream
116     * readers. They start with 'B'. */
117    private static final String [][] pinfo = null;
118
119    /**
120     * The maximum number of decompostion levels for each component of the
121     * current tile. It means that component c has mdl[c]+1 resolution levels
122     * (indexed from 0 to mdl[c])
123     * */
124    protected int mdl[];
125
126    /** The number of components */
127    protected final int nc;
128
129    /** Image resolution level to generate */
130    protected int targetRes;
131
132    /**
133     * The subband trees for each component in the current tile. Each element
134     * in the array is the root element of the subband tree for a
135     * component. The number of magnitude bits in each subband (magBits member
136     * variable) is not initialized.
137     * */
138    protected SubbandSyn subbTrees[];
139
140    /** The image width on the hi-res reference grid */
141    protected final int imgW;
142
143    /** The image width on the hi-res reference grid */
144    protected final int imgH;
145
146    /** The horizontal coordinate of the image origin in the canvas system, on
147     * the reference grid. */
148    protected final int ax;
149
150    /** The vertical coordinate of the image origin in the canvas system, on
151     * the reference grid. */
152    protected final int ay;
153
154    /** The horizontal coordinate of the tiling origin in the canvas system, on
155     * the reference grid. */
156    protected final int px;
157
158    /** The vertical coordinate of the tiling origin in the canvas system, on
159     * the reference grid. */
160    protected final int py;
161
162    /** The horizontal offsets of the upper-left corner of the current tile
163     * (not active tile) with respect to the canvas origin, in the component
164     * hi-res grid, for each component. */
165    protected final int offX[];
166
167    /** The vertical offsets of the upper-left corner of the current tile (not
168     * active tile) with respect to the canvas origin, in the component hi-res
169     * grid, for each component. */
170    protected final int offY[];
171
172    /** The horizontal coordinates of the upper-left corner of the active
173     * tile, with respect to the canvas origin, in the component hi-res grid,
174     * for each component. */
175    protected final int culx[];
176
177    /** The vertical coordinates of the upper-left corner of the active tile,
178     * with respect to the canvas origin, in the component hi-res grid, for
179     * each component. */
180    protected final int culy[];
181
182    /** The nominal tile width, in the hi-res reference grid */
183    protected final int ntW;
184
185    /** The nominal tile height, in the hi-res reference grid */
186    protected final int ntH;
187
188    /** The number of tile in the horizontal direction */
189    protected final int ntX;
190
191    /** The number of tiles in the vertical direction */
192    protected final int ntY;
193
194    /** The total number of tiles. */
195    protected final int nt;
196
197    /** The current tile horizontal index */
198    protected int ctX;
199
200    /** The current tile vertical index */
201    protected int ctY;
202
203    /** The decoded bit stream header */
204    protected final HeaderDecoder hd;
205
206    /** Number of bytes targeted to be read */
207    protected int tnbytes;
208
209    /** Actual number of read bytes */
210    protected int anbytes;
211
212    /** Target decoding rate in bpp */
213    protected float trate;
214
215    /** Actual decoding rate in bpp */
216    protected float arate;
217
218    /**
219     * Initializes members of this class. This constructor takes a
220     * HeaderDecoder object. This object must be initialized by the
221     * constructor of the implementing class from the header of the bit
222     * stream.
223     *
224     * @param hd The decoded header of the bit stream from where to initialize
225     * the values.
226     *
227     * @param decSpec The decoder specifications
228     * */
229    protected BitstreamReaderAgent(HeaderDecoder hd,DecoderSpecs decSpec){
230        Point co;
231        int i,j,max;
232
233        this.decSpec = decSpec;
234        this.hd = hd;
235
236        // Number of components
237        nc = hd.getNumComps();
238        offX = new int[nc];
239        offY = new int[nc];
240        culx = new int[nc];
241        culy = new int[nc];
242
243        // Image size and origin
244        imgW = hd.getImgWidth();
245        imgH = hd.getImgHeight();
246        ax = hd.getImgULX();
247        ay = hd.getImgULY();
248
249        // Tiles
250        co = hd.getTilingOrigin(null);
251        px = co.x;
252        py = co.y;
253        ntW = hd.getNomTileWidth();
254        ntH = hd.getNomTileHeight();
255        ntX = (ax+imgW-px+ntW-1) / ntW;
256        ntY = (ay+imgH-py+ntH-1) / ntH;
257        nt = ntX * ntY;
258    }
259
260    /**
261     * Returns the vertical code-block partition origin. Allowable values are
262     * 0 and 1, nothing else.
263     * */
264    public final int getCbULX() {
265        return hd.getCbULX();
266    }
267
268    /**
269     * Returns the vertical code-block partition origin. Allowable values are
270     * 0 and 1, nothing else.
271     * */
272    public int getCbULY() {
273        return hd.getCbULY();
274    }
275
276    /**
277     * Returns the number of components in the image.
278     *
279     * @return The number of components in the image.
280     * */
281    public final int getNumComps() {
282        return nc;
283    }
284
285    /**
286     * Returns the component subsampling factor in the horizontal direction,
287     * for the specified component. This is, approximately, the ratio of
288     * dimensions between the reference grid and the component itself, see the
289     * 'ImgData' interface desription for details.
290     *
291     * @param c The index of the component (between 0 and N-1)
292     *
293     * @return The horizontal subsampling factor of component 'c'
294     *
295     * @see jj2000.j2k.image.ImgData
296     * */
297    public final int getCompSubsX(int c) {
298        return hd.getCompSubsX(c);
299    }
300
301    /**
302     * Returns the component subsampling factor in the vertical direction, for
303     * the specified component. This is, approximately, the ratio of
304     * dimensions between the reference grid and the component itself, see the
305     * 'ImgData' interface desription for details.
306     *
307     * @param c The index of the component (between 0 and C-1)
308     *
309     * @return The vertical subsampling factor of component 'c'
310     *
311     * @see jj2000.j2k.image.ImgData
312     * */
313    public int getCompSubsY(int c) {
314        return hd.getCompSubsY(c);
315    }
316
317    /**
318     * Returns the overall width of the current tile in pixels for the given
319     * (tile) resolution level. This is the tile's width without accounting
320     * for any component subsampling.
321     *
322     * <P>Note: Tile resolution level indexes may be different from
323     * tile-component resolution index. They are indeed indexed starting from
324     * the lowest number of decomposition levels of each component of the
325     * tile.
326     *
327     * <P>For an image (1 tile) with 2 components (component 0 having 2
328     * decomposition levels and component 1 having 3 decomposition levels),
329     * the first (tile-)component has 3 resolution levels and the second one
330     * has 4 resolution levels, whereas the tile has only 3 resolution levels
331     * available.
332     *
333     * @param rl The (tile) resolution level.
334     *
335     * @return The current tile's width in pixels.
336     * */
337    public int getTileWidth(int rl){
338        // The minumum number of decomposition levels between all the
339        // components
340        int mindl = decSpec.dls.getMinInTile(getTileIdx());
341        if(rl>mindl){
342            throw new IllegalArgumentException("Requested resolution level"+
343                                               " is not available for, at "+
344                                               "least, one component in "+
345                                               "tile: "+ctX+"x"+ctY);
346        }
347        int ctulx,ntulx;
348        int dl = mindl-rl; // Number of decomposition to obtain this
349        // resolution
350
351        // Calculate starting X of current tile at hi-res
352        ctulx = (ctX == 0) ? ax : px+ctX*ntW;
353        // Calculate starting X of next tile X-wise at hi-res
354        ntulx = (ctX < ntX-1) ? px+(ctX+1)*ntW : ax+imgW;
355        dl = 1 << dl;
356        // The difference at the rl resolution level is the width
357        return (ntulx+dl-1)/dl-(ctulx+dl-1)/dl;
358    }
359
360    /**
361     * Returns the overall height of the current tile in pixels, for the given
362     * resolution level. This is the tile's height without accounting for any
363     * component subsampling.
364     *
365     * <P>Note: Tile resolution level indexes may be different from
366     * tile-component resolution index. They are indeed indexed starting from
367     * the lowest number of decomposition levels of each component of the
368     * tile.
369     *
370     * <P>For an image (1 tile) with 2 components (component 0 having 2
371     * decomposition levels and component 1 having 3 decomposition levels),
372     * the first (tile-)component has 3 resolution levels and the second one
373     * has 4 resolution levels, whereas the tile has only 3 resolution levels
374     * available.
375     *
376     * @param rl The (tile) resolution level.
377     *
378     * @return The total current tile's height in pixels.
379     * */
380    public int getTileHeight(int rl){
381        // The minumum number of decomposition levels between all the
382        // components
383        int mindl = decSpec.dls.getMinInTile(getTileIdx());
384        if(rl>mindl){
385            throw new IllegalArgumentException("Requested resolution level"+
386                                               " is not available for, at "+
387                                               "least, one component in"+
388                                               " tile: "+ctX+"x"+ctY);
389        }
390
391        int ctuly,ntuly;
392        int dl = mindl-rl; // Number of decomposition to obtain this
393        // resolution
394
395        // Calculate starting Y of current tile at hi-res
396        ctuly = (ctY == 0) ? ay : py+ctY*ntH;
397        // Calculate starting Y of next tile Y-wise at hi-res
398        ntuly = (ctY < ntY-1) ? py+(ctY+1)*ntH : ay+imgH;
399        dl = 1 <<dl;
400        // The difference at the rl level is the height
401        return (ntuly+dl-1)/dl-(ctuly+dl-1)/dl;
402    }
403
404    /**
405     * Returns the overall width of the image in pixels, for the given (image)
406     * resolution level. This is the image's width without accounting for any
407     * component subsampling or tiling.
408     *
409     * <P>Note: Image resolution level indexes may differ from tile-component
410     * resolution index. They are indeed indexed starting from the lowest
411     * number of decomposition levels of each component of each tile.
412     *
413     * <P>Example: For an image (1 tile) with 2 components (component 0 having
414     * 2 decomposition levels and component 1 having 3 decomposition levels),
415     * the first (tile-) component has 3 resolution levels and the second one
416     * has 4 resolution levels, whereas the image has only 3 resolution levels
417     * available.
418     *
419     * @param rl The image resolution level.
420     *
421     * @return The total image's width in pixels.
422     * */
423    public int getImgWidth(int rl){
424        // The minimum number of decomposition levels of each
425        // tile-component
426        int mindl = decSpec.dls.getMin();
427        if(rl>mindl){
428            throw new IllegalArgumentException("Requested resolution level"+
429                                               " is not available for, at "+
430                                               "least, one tile-component");
431        }
432        // Retrieve number of decomposition levels corresponding to
433        // this resolution level
434        int dl = 1 << mindl - rl;
435        return (ax+imgW+dl-1)/dl-(ax+dl-1)/dl;
436    }
437
438    /**
439     * Returns the overall height of the image in pixels, for the given
440     * resolution level. This is the image's height without accounting for any
441     * component subsampling or tiling.
442     *
443     * <P>Note: Image resolution level indexes may differ from tile-component
444     * resolution index. They are indeed indexed starting from the lowest
445     * number of decomposition levels of each component of each tile.
446     *
447     * <P>Example: For an image (1 tile) with 2 components (component 0 having
448     * 2 decomposition levels and component 1 having 3 decomposition levels),
449     * the first (tile-) component has 3 resolution levels and the second one
450     * has 4 resolution levels, whereas the image has only 3 resolution levels
451     * available.
452     *
453     * @param rl The image resolution level, from 0 to L.
454     *
455     * @return The total image's height in pixels.
456     * */
457    public int getImgHeight(int rl){
458        int mindl = decSpec.dls.getMin();
459        if(rl>mindl){
460            throw new IllegalArgumentException("Requested resolution level"+
461                                               " is not available for, at "+
462                                               "least, one tile-component");
463        }
464        // Retrieve number of decomposition levels corresponding to this
465        // resolution level
466        int dl = 1 << mindl - rl;
467        return (ay+imgH+dl-1)/dl-(ay+dl-1)/dl;
468    }
469
470    /**
471     * Returns the horizontal coordinate of the image origin, the top-left
472     * corner, in the canvas system, on the reference grid at the specified
473     * resolution level.
474     *
475     * <P>Note: Image resolution level indexes may differ from tile-component
476     * resolution index. They are indeed indexed starting from the lowest
477     * number of decomposition levels of each component of each tile.
478     *
479     * <P>Example: For an image (1 tile) with 2 components (component 0 having
480     * 2 decomposition levels and component 1 having 3 decomposition levels),
481     * the first (tile-) component has 3 resolution levels and the second one
482     * has 4 resolution levels, whereas the image has only 3 resolution levels
483     * available.
484     *
485     * @param rl The resolution level, from 0 to L.
486     *
487     * @return The horizontal coordinate of the image origin in the canvas
488     * system, on the reference grid.
489     * */
490    public int getImgULX(int rl){
491        int mindl = decSpec.dls.getMin();
492        if(rl>mindl){
493            throw new IllegalArgumentException("Requested resolution level"+
494                                               " is not available for, at "+
495                                               "least, one tile-component");
496        }
497        // Retrieve number of decomposition levels corresponding to this
498        // resolution level
499        int dl = 1 << mindl - rl;
500        return (ax+dl-1)/dl;
501    }
502
503    /**
504     * Returns the vertical coordinate of the image origin, the top-left
505     * corner, in the canvas system, on the reference grid at the specified
506     * resolution level.
507     *
508     * <P>Note: Image resolution level indexes may differ from tile-component
509     * resolution index. They are indeed indexed starting from the lowest
510     * number of decomposition levels of each component of each tile.
511     *
512     * <P>Example: For an image (1 tile) with 2 components (component 0 having
513     * 2 decomposition levels and component 1 having 3 decomposition levels),
514     * the first (tile-) component has 3 resolution levels and the second one
515     * has 4 resolution levels, whereas the image has only 3 resolution levels
516     * available.
517     *
518     * @param rl The resolution level, from 0 to L.
519     *
520     * @return The vertical coordinate of the image origin in the canvas
521     * system, on the reference grid.
522     * */
523    public int getImgULY(int rl){
524        int mindl = decSpec.dls.getMin();
525        if(rl>mindl){
526            throw new IllegalArgumentException("Requested resolution level"+
527                                               " is not available for, at "+
528                                               "least, one tile-component");
529        }
530        // Retrieve number of decomposition levels corresponding to this
531        // resolution level
532        int dl = 1 << mindl - rl;
533        return (ay+dl-1)/dl;
534    }
535
536    /**
537     * Returns the width in pixels of the specified tile-component for the
538     * given (tile-component) resolution level.
539     *
540     * @param t The tile index
541     *
542     * @param c The index of the component, from 0 to N-1.
543     *
544     * @param rl The resolution level, from 0 to L.
545     *
546     * @return The width in pixels of component <tt>c</tt> in tile <tt>t</tt>
547     * for resolution level <tt>rl</tt>.
548     * */
549    public final int getTileCompWidth(int t,int c,int rl) {
550        int tIdx = getTileIdx();
551        if(t!=tIdx) {
552            throw new Error("Asking the tile-component width of a tile "+
553                            "different  from the current one.");
554        }
555        // Calculate starting X of next tile X-wise at reference grid hi-res
556        int ntulx = (ctX < ntX-1) ? px+(ctX+1)*ntW : ax+imgW;
557        // Convert reference grid hi-res to component grid hi-res
558        ntulx = (ntulx+hd.getCompSubsX(c)-1)/hd.getCompSubsX(c);
559        int dl = 1 << mdl[c]-rl;
560        // Starting X of current tile at component grid hi-res is culx[c]
561        // The difference at the rl level is the width
562        return (ntulx+dl-1)/dl-(culx[c]+dl-1)/dl;
563    }
564
565    /**
566     * Returns the height in pixels of the specified tile-component for the
567     * given (tile-component) resolution level.
568     *
569     * @param t The tile index.
570     *
571     * @param c The index of the component, from 0 to N-1.
572     *
573     * @param rl The resolution level, from 0 to L.
574     *
575     * @return The height in pixels of component <tt>c</tt> in the current
576     * tile.
577     * */
578    public final int getTileCompHeight(int t,int c,int rl) {
579        int tIdx = getTileIdx();
580        if(t!=tIdx) {
581            throw new Error("Asking the tile-component width of a tile "+
582                            "different  from the current one.");
583        }
584        // Calculate starting Y of next tile Y-wise at reference grid hi-res
585        int ntuly = (ctY < ntY-1) ? py+(ctY+1)*ntH : ay+imgH;
586        // Convert reference grid hi-res to component grid hi-res
587        ntuly = (ntuly+hd.getCompSubsY(c)-1)/hd.getCompSubsY(c);
588        int dl = 1 << mdl[c]-rl; // Revert level indexation (0 is hi-res)
589        // Starting Y of current tile at component grid hi-res is culy[c]
590        // The difference at the rl level is the height
591        return (ntuly+dl-1)/dl-(culy[c]+dl-1)/dl;
592    }
593
594
595    /**
596     * Returns the width in pixels of the specified component in the overall
597     * image, for the given (component) resolution level.
598     *
599     * <P>Note: Component resolution level indexes may differ from
600     * tile-component resolution index. They are indeed indexed starting from
601     * the lowest number of decomposition levels of same component of each
602     * tile.
603     *
604     * <P>Example: For an image (2 tiles) with 1 component (tile 0 having 2
605     * decomposition levels and tile 1 having 3 decomposition levels), the
606     * first tile(-component) has 3 resolution levels and the second one has 4
607     * resolution levels, whereas the component has only 3 resolution levels
608     * available.
609     *
610     * @param c The index of the component, from 0 to N-1.
611     *
612     * @param rl The resolution level, from 0 to L.
613     *
614     * @return The width in pixels of component <tt>c</tt> in the overall
615     * image.
616     * */
617    public final int getCompImgWidth(int c,int rl){
618        // indexation (0 is hi-res)
619        // Calculate image starting x at component hi-res grid
620        int sx = (ax+hd.getCompSubsX(c)-1)/hd.getCompSubsX(c);
621        // Calculate image ending (excluding) x at component hi-res grid
622        int ex = (ax+imgW+hd.getCompSubsX(c)-1)/hd.getCompSubsX(c);
623        int dl = 1 << decSpec.dls.getMinInComp(c)-rl;
624        // The difference at the rl level is the width
625        return (ex+dl-1)/dl-(sx+dl-1)/dl;
626    }
627
628    /**
629     * Returns the height in pixels of the specified component in the overall
630     * image, for the given (component) resolution level.
631     *
632     * <P>Note: Component resolution level indexes may differ from
633     * tile-component resolution index. They are indeed indexed starting from
634     * the lowest number of decomposition levels of same component of each
635     * tile.
636     *
637     * <P>Example: For an image (2 tiles) with 1 component (tile 0 having 2
638     * decomposition levels and tile 1 having 3 decomposition levels), the
639     * first tile(-component) has 3 resolution levels and the second one has 4
640     * resolution levels, whereas the component has only 3 resolution levels
641     * available.
642     *
643     * @param c The index of the component, from 0 to N-1.
644     *
645     * @param rl The resolution level, from 0 to L.
646     *
647     * @return The height in pixels of component <tt>c</tt> in the overall
648     * image.
649     * */
650    public final int getCompImgHeight(int c,int rl){
651        // indexation (0 is hi-res)
652        // Calculate image starting x at component hi-res grid
653        int sy = (ay+hd.getCompSubsY(c)-1)/hd.getCompSubsY(c);
654        // Calculate image ending (excluding) x at component hi-res grid
655        int ey = (ay+imgH+hd.getCompSubsY(c)-1)/hd.getCompSubsY(c);
656        int dl = 1 << decSpec.dls.getMinInComp(c)-rl;
657        // The difference at the rl level is the width
658        return (ey+dl-1)/dl-(sy+dl-1)/dl;
659    }
660
661    /**
662     * Changes the current tile, given the new indexes. An
663     * IllegalArgumentException is thrown if the indexes do not correspond to
664     * a valid tile.
665     *
666     * @param x The horizontal indexes the tile.
667     *
668     * @param y The vertical indexes of the new tile.
669     * */
670    public abstract void setTile(int x, int y);
671
672    /**
673     * Advances to the next tile, in standard scan-line order (by rows then
674     * columns). An NoNextElementException is thrown if the current tile is
675     * the last one (i.e. there is no next tile).
676     * */
677    public abstract void nextTile();
678
679    /**
680     * Returns the indexes of the current tile. These are the horizontal and
681     * vertical indexes of the current tile.
682     *
683     * @param co If not null this object is used to return the information. If
684     * null a new one is created and returned.
685     *
686     * @return The current tile's indexes (vertical and horizontal indexes).
687     * */
688    public final Point getTile(Point co) {
689        if (co != null) {
690            co.x = ctX;
691            co.y = ctY;
692            return co;
693        }
694        else {
695            return new Point(ctX,ctY);
696        }
697    }
698
699    /**
700     * Returns the index of the current tile, relative to a standard scan-line
701     * order.
702     *
703     * @return The current tile's index (starts at 0).
704     * */
705    public final int getTileIdx() {
706        return ctY*ntX+ctX;
707    }
708
709    /** 
710     * Returns the horizontal coordinate of the upper-left corner of the
711     * specified resolution in the given component of the current tile.
712     *  
713     * @param c The component index.
714     *  
715     * @param rl The resolution level index.
716     * */
717    public final int getResULX(int c,int rl) {
718        int dl = mdl[c]-rl;
719        if(dl<0){
720            throw new IllegalArgumentException("Requested resolution level"+
721                                               " is not available for, at "+
722                                               "least, one component in "+
723                                               "tile: "+ctX+"x"+ctY);
724        }
725        int tx0 = (int)Math.max(px+ctX*ntW,ax);
726        int tcx0 = (int)Math.ceil(tx0/(double)getCompSubsX(c));
727        return (int)Math.ceil(tcx0/(double)(1<<dl));
728    }
729
730    /**
731     * Returns the vertical coordinate of the upper-left corner of the
732     * specified component in the given component of the current tile.
733     *
734     * @param c The component index.
735     *
736     * @param rl The resolution level index.
737     * */
738    public final int getResULY(int c,int rl) {
739        int dl = mdl[c]-rl;
740        if(dl<0){
741            throw new IllegalArgumentException("Requested resolution level"+
742                                               " is not available for, at "+
743                                               "least, one component in "+
744                                               "tile: "+ctX+"x"+ctY);
745        }
746        int ty0 = (int)Math.max(py+ctY*ntH,ay);
747        int tcy0 = (int)Math.ceil(ty0/(double)getCompSubsY(c));
748        return (int)Math.ceil(tcy0/(double)(1<<dl));
749    }
750
751    /**
752     * Returns the number of tiles in the horizontal and vertical directions.
753     *
754     * @param co If not null this object is used to return the information. If
755     * null a new one is created and returned.
756     *
757     * @return The number of tiles in the horizontal (Point.x) and vertical
758     * (Point.y) directions.
759     * */
760    public final Point getNumTiles(Point co) {
761        if (co != null) {
762            co.x = ntX;
763            co.y = ntY;
764            return co;
765        }
766        else {
767            return new Point(ntX,ntY);
768        }
769    }
770
771    /**
772     * Returns the total number of tiles in the image.
773     *
774     * @return The total number of tiles in the image.
775     * */
776    public final int getNumTiles() {
777        return ntX*ntY;
778    }
779
780    /**
781     * Returns the subband tree, for the specified tile-component. This method
782     * returns the root element of the subband tree structure, see Subband and
783     * SubbandSyn. The tree comprises all the available resolution levels.
784     *
785     * <p>Note: this method is not able to return subband tree for a tile
786     * different than the current one.</p>
787     *
788     * <p>The number of magnitude bits ('magBits' member variable) for each
789     * subband is not initialized.</p>
790     *
791     * @param t The tile index
792     *
793     * @param c The index of the component, from 0 to C-1.
794     *
795     * @return The root of the tree structure.
796     * */
797    public final SubbandSyn getSynSubbandTree(int t,int c) {
798        if(t!=getTileIdx()) {
799            throw new IllegalArgumentException("Can not request subband"+
800                                               " tree of a different tile"+
801                                               " than the current one");
802        }
803        if(c<0 || c>=nc) {
804            throw new IllegalArgumentException("Component index out of range");
805        }
806        return subbTrees[c];
807    }
808
809
810    /**
811     * Creates a bit stream reader of the correct type that works on the
812     * provided RandomAccessIO, with the special parameters from the parameter
813     * list.
814     *
815     * @param in The RandomAccessIO source from which to read the bit stream.
816     *
817     * @param hd Header of the codestream.
818     *
819     * @param j2krparam The parameters applicable to the
820     * bit stream read (other parameters may also be present).
821     *
822     * @param decSpec The decoder specifications
823     *
824     * @param cdstrInfo Whether or not to print information found in
825     * codestream. 
826     *
827     * @param hi Reference to the HeaderInfo instance.
828     *
829     * @exception IOException If an I/O error occurs while reading initial
830     * data from the bit stream.
831     * @exception IllegalArgumentException If an unrecognised bit stream
832     * reader option is present.
833     * */
834    public static BitstreamReaderAgent createInstance(RandomAccessIO in,
835                                                      HeaderDecoder hd,
836                                                      J2KImageReadParamJava j2krparam,
837                                                      DecoderSpecs decSpec,
838                                                      boolean cdstrInfo,
839                                                      HeaderInfo hi)
840        throws IOException {
841        // Check header length
842/*
843        if (in.getPos() != hd.getTotalHeaderLength() + hd.initPos) {
844            throw new IllegalArgumentException("Invalid header length");
845        }
846*/
847        return new FileBitstreamReaderAgent(hd,in,decSpec,j2krparam,cdstrInfo,hi);
848    }
849
850
851    /**
852     * Returns the parameters that are used in this class and implementing
853     * classes. It returns a 2D String array. Each of the 1D arrays is for a
854     * different option, and they have 3 elements. The first element is the
855     * option name, the second one is the synopsis and the third one is a long
856     * description of what the parameter is. The synopsis or description may
857     * be 'null', in which case it is assumed that there is no synopsis or
858     * description of the option, respectively. Null may be returned if no
859     * options are supported.
860     *
861     * @return the options name, their synopsis and their explanation, or null
862     * if no options are supported.
863     * */
864    public static String[][] getParameterInfo() {
865        return pinfo;
866    }
867
868    /**
869     * Returns the precinct partition width for the specified tile-component
870     * and (tile-component) resolution level.
871     *
872     * @param t the tile index
873     *
874     * @param c The index of the component (between 0 and N-1)
875     *
876     * @param rl The resolution level, from 0 to L.
877     *
878     * @return the precinct partition width for the specified component,
879     * resolution level and tile.
880     * */
881    public final int getPPX(int t,int c,int rl){
882        return decSpec.pss.getPPX(t,c,rl);
883    }
884
885    /**
886     * Returns the precinct partition height for the specified tile-component
887     * and (tile-component) resolution level.
888     *
889     * @param t The tile index
890     *
891     * @param c The index of the component (between 0 and N-1)
892     *
893     * @param rl The resolution level, from 0 to L.
894     *
895     * @return The precinct partition height in the specified component, for
896     * the specified resolution level, for the current tile.
897     * */
898    public final int getPPY(int t,int c,int rl){
899        return decSpec.pss.getPPY(t,c,rl);
900    }
901
902    /**
903     * Initialises subbands fields, such as code-blocks dimension and number
904     * of magnitude bits, in the subband tree. The nominal code-block
905     * width/height depends on the precincts dimensions if used. The way the
906     * number of magnitude bits is computed depends on the quantization type
907     * (reversible, derived, expounded).
908     *
909     * @param c The component index
910     *
911     * @param sb The subband tree to be initialised.
912     * */
913    protected void initSubbandsFields(int c,SubbandSyn sb){
914        int t = getTileIdx();
915        int rl = sb.resLvl;
916        int cbw, cbh;
917
918        cbw = decSpec.cblks.getCBlkWidth(ModuleSpec.SPEC_TILE_COMP,t,c);
919        cbh = decSpec.cblks.getCBlkHeight(ModuleSpec.SPEC_TILE_COMP,t,c);
920
921        if( !sb.isNode ){
922            if( hd.precinctPartitionUsed() ){
923                // The precinct partition is used
924                int ppxExp, ppyExp, cbwExp, cbhExp;
925
926                // Get exponents
927                ppxExp = MathUtil.log2(getPPX(t,c,rl));
928                ppyExp = MathUtil.log2(getPPY(t,c,rl));
929                cbwExp = MathUtil.log2(cbw);
930                cbhExp = MathUtil.log2(cbh);
931
932                switch (sb.resLvl) {
933                    case 0:
934                        sb.nomCBlkW = ( cbwExp<ppxExp ?
935                            (1<<cbwExp) : (1<<ppxExp) );
936                        sb.nomCBlkH = ( cbhExp<ppyExp ?
937                            (1<<cbhExp) : (1<<ppyExp) );
938                        break;
939
940                    default:
941                        sb.nomCBlkW = ( cbwExp<ppxExp-1 ?
942                            (1<<cbwExp) : (1<<(ppxExp-1)) );
943                        sb.nomCBlkH = ( cbhExp<ppyExp-1 ?
944                            (1<<cbhExp) : (1<<(ppyExp-1)) );
945                        break;
946                }
947            }
948            else {
949                sb.nomCBlkW = cbw;
950                sb.nomCBlkH = cbh;
951            }
952
953            // Number of code-blocks
954            if(sb.numCb == null) sb.numCb = new Point();
955            if (sb.w==0 || sb.h==0) {
956                sb.numCb.x = 0;
957                sb.numCb.y = 0;
958            } else {
959                int cb0x = getCbULX();
960                int cb0y = getCbULY();
961                int tmp;
962
963                // Projects code-block partition origin to subband. Since the
964                // origin is always 0 or 1, it projects to the low-pass side
965                // (throught the ceil operator) as itself (i.e. no change) and
966                // to the high-pass side (through the floor operator) as 0,
967                // always.
968                int acb0x = cb0x;
969                int acb0y = cb0y;
970
971                switch (sb.sbandIdx) {
972                case Subband.WT_ORIENT_LL:
973                    // No need to project since all low-pass => nothing to do
974                    break;
975                case Subband.WT_ORIENT_HL:
976                    acb0x = 0;
977                    break;
978                case Subband.WT_ORIENT_LH:
979                    acb0y = 0;
980                    break;
981                case Subband.WT_ORIENT_HH:
982                    acb0x = 0;
983                    acb0y = 0;
984                    break;
985                default:
986                    throw new Error("Internal JJ2000 error");
987                }
988                if(sb.ulcx-acb0x<0 || sb.ulcy-acb0y<0) {
989                    throw new IllegalArgumentException("Invalid code-blocks "+
990                                                       "partition origin or "+
991                                                       "image offset in the "+
992                                                       "reference grid.");
993                }
994
995                // NOTE: when calculating "floor()" by integer division the
996                // dividend and divisor must be positive, we ensure that by
997                // adding the divisor to the dividend and then substracting 1
998                // to the result of the division
999
1000                tmp = sb.ulcx-acb0x+sb.nomCBlkW;
1001                sb.numCb.x = (tmp+sb.w-1)/sb.nomCBlkW - (tmp/sb.nomCBlkW-1);
1002
1003                tmp = sb.ulcy-acb0y+sb.nomCBlkH;
1004                sb.numCb.y = (tmp+sb.h-1)/sb.nomCBlkH - (tmp/sb.nomCBlkH-1);
1005            }
1006
1007            if(derived[c]){
1008                sb.magbits = gb[c]+(params[c].exp[0][0]-(mdl[c]-sb.level))-1;
1009            }
1010            else {
1011                sb.magbits = gb[c]+params[c].exp[sb.resLvl][sb.sbandIdx]-1;
1012            }
1013        }
1014        else {
1015            initSubbandsFields(c,(SubbandSyn)sb.getLL());
1016            initSubbandsFields(c,(SubbandSyn)sb.getHL());
1017            initSubbandsFields(c,(SubbandSyn)sb.getLH());
1018            initSubbandsFields(c,(SubbandSyn)sb.getHH());
1019        }
1020    }
1021
1022    /**
1023     * Returns the image resolution level to reconstruct from the
1024     * codestream. This value cannot be computed before every main and tile
1025     * headers are read.
1026     *
1027     * @return The image  resolution level
1028     * */
1029    public int getImgRes(){
1030        return targetRes;
1031    }
1032
1033    /**
1034     * Return the target decoding rate in bits per pixel.
1035     *
1036     * @return Target decoding rate in bpp.
1037     * */
1038    public float getTargetRate(){
1039        return trate;
1040    }
1041
1042    /**
1043     * Return the actual decoding rate in bits per pixel.
1044     *
1045     * @return Actual decoding rate in bpp.
1046     * */
1047    public float getActualRate() {
1048        arate = anbytes*8f/hd.getMaxCompImgWidth()/hd.getMaxCompImgHeight();
1049        return arate;
1050    }
1051
1052    /**
1053     * Return the target number of read bytes.
1054     *
1055     * @return Target decoding rate in bytes.
1056     * */
1057    public int getTargetNbytes(){
1058        return tnbytes;
1059    }
1060
1061    /**
1062     * Return the actual number of read bytes.
1063     *
1064     * @return Actual decoding rate in bytes.
1065     * */
1066    public int getActualNbytes(){
1067        return anbytes;
1068    }
1069
1070    /** Returns the horizontal offset of tile partition */
1071    public int getTilePartULX() {
1072        return hd.getTilingOrigin(null).x;
1073    }
1074
1075    /** Returns the vertical offset of tile partition */
1076    public int getTilePartULY() {
1077        return hd.getTilingOrigin(null).y;
1078    }
1079
1080    /** Returns the nominal tile width */
1081    public int getNomTileWidth() {
1082        return hd.getNomTileWidth();
1083    }
1084
1085    /** Returns the nominal tile height */
1086    public int getNomTileHeight() {
1087        return hd.getNomTileHeight();
1088    }
1089}