Esempio n. 1
0
		/// <summary> Creates a ROIDeScaler object. The information needed to create the
		/// object is the Entropy decoder used and the parameters.
		/// 
		/// </summary>
		/// <param name="src">The source of data that is to be descaled
		/// 
		/// </param>
		/// <param name="pl">The parameter list (or options).
		/// 
		/// </param>
		/// <param name="decSpec">The decoding specifications
		/// 
		/// </param>
		/// <exception cref="IllegalArgumentException">If an error occurs while parsing
		/// the options in 'pl'
		/// 
		/// </exception>
		public static ROIDeScaler createInstance(CBlkQuantDataSrcDec src, ParameterList pl, DecoderSpecs decSpec)
		{
			System.String noRoi;
			//int i;
			
			// Check parameters
			pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo));
			
			// Check if no_roi specified in command line or no roi signalled
			// in bit stream
			noRoi = pl.getParameter("Rno_roi");
			if (noRoi != null || decSpec.rois == null)
			{
				// no_roi specified in commandline!
				return new ROIDeScaler(src, null);
			}
			
			return new ROIDeScaler(src, decSpec.rois);
		}
Esempio n. 2
0
        /// <summary> Initializes the EBCOT rate allocator of entropy coded data. The layout
        /// of layers, and their bitrate constraints, is specified by the 'lyrs'
        /// parameter.
        /// 
        /// </summary>
        /// <param name="src">The source of entropy coded data.
        /// 
        /// </param>
        /// <param name="lyrs">The layers layout specification.
        /// 
        /// </param>
        /// <param name="writer">The bit stream writer.
        /// 
        /// </param>
        /// <seealso cref="ProgressionType">
        /// 
        /// </seealso>
        public EBCOTRateAllocator(CodedCBlkDataSrcEnc src, LayersInfo lyrs, CodestreamWriter writer, EncoderSpecs encSpec, ParameterList pl)
            : base(src, lyrs.TotNumLayers, writer, encSpec)
        {
            int minsbi, maxsbi;
            int i;
            SubbandAn sb, sb2;
            Coord ncblks = null;

            // If we do timing create necessary structures
            #if DO_TIMING
            // If we are timing make sure that 'finalize' gets called.
            //UPGRADE_ISSUE: Method 'java.lang.System.runFinalizersOnExit' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangSystem'"
            // CONVERSION PROBLEM?
            //System_Renamed.runFinalizersOnExit(true);
            // The System.runFinalizersOnExit() method is deprecated in Java
            // 1.2 since it can cause a deadlock in some cases. However, here
            // we use it only for profiling purposes and is disabled in
            // production code.
            initTime = 0L;
            buildTime = 0L;
            writeTime = 0L;
            #endif

            // Save the layer specs
            lyrSpec = lyrs;

            //Initialize the size of the RD slope rates array
            RDSlopesRates = new int[RD_SUMMARY_SIZE];

            //Get number of tiles, components
            int nt = src.getNumTiles();
            int nc = NumComps;

            //Allocate the coded code-blocks and truncation points indexes arrays
            cblks = new CBlkRateDistStats[nt][][][][];
            for (int i2 = 0; i2 < nt; i2++)
            {
                cblks[i2] = new CBlkRateDistStats[nc][][][];
            }
            truncIdxs = new int[nt][][][][][];
            for (int i3 = 0; i3 < nt; i3++)
            {
                truncIdxs[i3] = new int[num_Layers][][][][];
                for (int i4 = 0; i4 < num_Layers; i4++)
                {
                    truncIdxs[i3][i4] = new int[nc][][][];
                }
            }

            int cblkPerSubband; // Number of code-blocks per subband
            int mrl; // Number of resolution levels
            int l; // layer index
            int s; //subband index

            // Used to compute the maximum number of precincts for each resolution
            // level
            int tx0, ty0, tx1, ty1; // Current tile position in the reference grid
            int tcx0, tcy0, tcx1, tcy1; // Current tile position in the domain of
            // the image component
            int trx0, try0, trx1, try1; // Current tile position in the reduced
            // resolution image domain
            int xrsiz, yrsiz; // Component sub-sampling factors
            Coord tileI = null;
            Coord nTiles = null;
            int xsiz, ysiz, x0siz, y0siz;
            int xt0siz, yt0siz;
            int xtsiz, ytsiz;

            int cb0x = src.CbULX;
            int cb0y = src.CbULY;

            src.setTile(0, 0);
            for (int t = 0; t < nt; t++)
            {
                // Loop on tiles
                nTiles = src.getNumTiles(nTiles);
                tileI = src.getTile(tileI);
                x0siz = ImgULX;
                y0siz = ImgULY;
                xsiz = x0siz + ImgWidth;
                ysiz = y0siz + ImgHeight;
                xt0siz = src.TilePartULX;
                yt0siz = src.TilePartULY;
                xtsiz = src.NomTileWidth;
                ytsiz = src.NomTileHeight;

                // Tile's coordinates on the reference grid
                tx0 = (tileI.x == 0)?x0siz:xt0siz + tileI.x * xtsiz;
                ty0 = (tileI.y == 0)?y0siz:yt0siz + tileI.y * ytsiz;
                tx1 = (tileI.x != nTiles.x - 1)?xt0siz + (tileI.x + 1) * xtsiz:xsiz;
                ty1 = (tileI.y != nTiles.y - 1)?yt0siz + (tileI.y + 1) * ytsiz:ysiz;

                for (int c = 0; c < nc; c++)
                {
                    // loop on components

                    //Get the number of resolution levels
                    sb = src.getAnSubbandTree(t, c);
                    mrl = sb.resLvl + 1;

                    // Initialize maximum number of precincts per resolution array
                    if (numPrec == null)
                    {
                        Coord[][][] tmpArray = new Coord[nt][][];
                        for (int i5 = 0; i5 < nt; i5++)
                        {
                            tmpArray[i5] = new Coord[nc][];
                        }
                        numPrec = tmpArray;
                    }
                    if (numPrec[t][c] == null)
                    {
                        numPrec[t][c] = new Coord[mrl];
                    }

                    // Subsampling factors
                    xrsiz = src.getCompSubsX(c);
                    yrsiz = src.getCompSubsY(c);

                    // Tile's coordinates in the image component domain
                    //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                    tcx0 = (int) System.Math.Ceiling(tx0 / (double) (xrsiz));
                    //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                    tcy0 = (int) System.Math.Ceiling(ty0 / (double) (yrsiz));
                    //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                    tcx1 = (int) System.Math.Ceiling(tx1 / (double) (xrsiz));
                    //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                    tcy1 = (int) System.Math.Ceiling(ty1 / (double) (yrsiz));

                    cblks[t][c] = new CBlkRateDistStats[mrl][][];

                    for (l = 0; l < num_Layers; l++)
                    {
                        truncIdxs[t][l][c] = new int[mrl][][];
                    }

                    for (int r = 0; r < mrl; r++)
                    {
                        // loop on resolution levels

                        // Tile's coordinates in the reduced resolution image
                        // domain
                        //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                        trx0 = (int) System.Math.Ceiling(tcx0 / (double) (1 << (mrl - 1 - r)));
                        //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                        try0 = (int) System.Math.Ceiling(tcy0 / (double) (1 << (mrl - 1 - r)));
                        //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                        trx1 = (int) System.Math.Ceiling(tcx1 / (double) (1 << (mrl - 1 - r)));
                        //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                        try1 = (int) System.Math.Ceiling(tcy1 / (double) (1 << (mrl - 1 - r)));

                        // Calculate the maximum number of precincts for each
                        // resolution level taking into account tile specific
                        // options.
                        double twoppx = (double) encSpec.pss.getPPX(t, c, r);
                        double twoppy = (double) encSpec.pss.getPPY(t, c, r);
                        numPrec[t][c][r] = new Coord();
                        if (trx1 > trx0)
                        {
                            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                            numPrec[t][c][r].x = (int) System.Math.Ceiling((trx1 - cb0x) / twoppx) - (int) System.Math.Floor((trx0 - cb0x) / twoppx);
                        }
                        else
                        {
                            numPrec[t][c][r].x = 0;
                        }
                        if (try1 > try0)
                        {
                            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                            numPrec[t][c][r].y = (int) System.Math.Ceiling((try1 - cb0y) / twoppy) - (int) System.Math.Floor((try0 - cb0y) / (double) twoppy);
                        }
                        else
                        {
                            numPrec[t][c][r].y = 0;
                        }

                        minsbi = (r == 0)?0:1;
                        maxsbi = (r == 0)?1:4;

                        cblks[t][c][r] = new CBlkRateDistStats[maxsbi][];
                        for (l = 0; l < num_Layers; l++)
                        {
                            truncIdxs[t][l][c][r] = new int[maxsbi][];
                        }

                        for (s = minsbi; s < maxsbi; s++)
                        {
                            // loop on subbands
                            //Get the number of blocks in the current subband
                            sb2 = (SubbandAn) sb.getSubbandByIdx(r, s);
                            ncblks = sb2.numCb;
                            cblkPerSubband = ncblks.x * ncblks.y;
                            cblks[t][c][r][s] = new CBlkRateDistStats[cblkPerSubband];

                            for (l = 0; l < num_Layers; l++)
                            {
                                truncIdxs[t][l][c][r][s] = new int[cblkPerSubband];
                                for (i = 0; i < cblkPerSubband; i++)
                                {
                                    truncIdxs[t][l][c][r][s][i] = - 1;
                                }
                            }
                        } // End loop on subbands
                    } // End lopp on resolution levels
                } // End loop on components
                if (t != nt - 1)
                {
                    src.nextTile();
                }
            } // End loop on tiles

            //Initialize the packet encoder
            pktEnc = new PktEncoder(src, encSpec, numPrec, pl);

            // The layers array has to be initialized after the constructor since
            // it is needed that the bit stream header has been entirely written
        }
Esempio n. 3
0
		/// <summary> Constructs a new 'IntegerSpec' for the specified number of tiles and
		/// components, the allowed specifications type and the ParameterList
		/// instance. This constructor is normally called at encoder side and parse
		/// arguments of specified option.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">The allowed specifications type
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		/// <param name="optName">The name of the option to process
		/// 
		/// </param>
		public IntegerSpec(int nt, int nc, byte type, ParameterList pl, System.String optName):base(nt, nc, type)
		{
			
			System.Int32 value_Renamed;
			System.String param = pl.getParameter(optName);
			
			if (param == null)
			{
				// No parameter specified
				param = pl.DefaultParameterList.getParameter(optName);
				try
				{
					setDefault((System.Object) System.Int32.Parse(param));
				}
				catch (System.FormatException)
				{
					throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					default: 
						try
						{
							value_Renamed = System.Int32.Parse(word);
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + word);
						}
						
						if (curSpecType == SPEC_DEF)
						{
							setDefault((System.Object) value_Renamed);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, (System.Object) value_Renamed);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, (System.Object) value_Renamed);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, (System.Object) value_Renamed);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					param = pl.DefaultParameterList.getParameter(optName);
					try
					{
						setDefault((System.Object) System.Int32.Parse(param));
					}
					catch (System.FormatException)
					{
						throw new System.ArgumentException("Non recognized value" + " for option -" + optName + ": " + param);
					}
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Esempio n. 4
0
		/// <summary> Constructs a new 'GuardBitsSpec' for the specified number of components
		/// and tiles and the arguments of "-Qguard_bits" option.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public GuardBitsSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Qguard_bits");
			if (param == null)
			{
				throw new System.ArgumentException("Qguard_bits option not " + "specified");
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			System.Int32 value_Renamed; // value of the guard bits
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken().ToLower();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_TILE_DEF;
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_COMP_DEF;
						break;
					
					default:  // Step size value
						try
						{
							value_Renamed = System.Int32.Parse(word);
						}
						catch (System.FormatException)
						{
							throw new System.ArgumentException("Bad parameter for " + "-Qguard_bits option" + " : " + word);
						}
						
						if ((float) value_Renamed <= 0.0f)
						{
							throw new System.ArgumentException("Guard bits value " + "must be positive : " + value_Renamed);
						}
						
						
						if (curSpecType == SPEC_DEF)
						{
							setDefault((System.Object) value_Renamed);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, (System.Object) value_Renamed);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, (System.Object) value_Renamed);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, (System.Object) value_Renamed);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					setDefault((System.Object) System.Int32.Parse(pl.DefaultParameterList.getParameter("Qguard_bits")));
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Esempio n. 5
0
        public static ParameterList GetDefaultParameterList(string[][] pinfo)
        {
            ParameterList pl = new ParameterList();
            string[][] str;

            str = BitstreamReaderAgent.ParameterInfo;
            if (str != null) for (int i = str.Length - 1; i >= 0; i--)
                    pl.Set(str[i][0], str[i][3]);

            str = EntropyDecoder.ParameterInfo;
            if (str != null) for (int i = str.Length - 1; i >= 0; i--)
                    pl.Set(str[i][0], str[i][3]);

            str = ROIDeScaler.ParameterInfo;
            if (str != null) for (int i = str.Length - 1; i >= 0; i--)
                    pl.Set(str[i][0], str[i][3]);

            str = Dequantizer.ParameterInfo;
            if (str != null) for (int i = str.Length - 1; i >= 0; i--)
                    pl.Set(str[i][0], str[i][3]);

            str = InvCompTransf.ParameterInfo;
            if (str != null) for (int i = str.Length - 1; i >= 0; i--)
                    pl.Set(str[i][0], str[i][3]);

            str = HeaderDecoder.ParameterInfo;
            if (str != null) for (int i = str.Length - 1; i >= 0; i--)
                    pl.Set(str[i][0], str[i][3]);

            str = ICCProfiler.ParameterInfo;
            if (str != null) for (int i = str.Length - 1; i >= 0; i--)
                    pl.Set(str[i][0], str[i][3]);

            str = pinfo;
            if (str != null) for (int i = str.Length - 1; i >= 0; i--)
                    pl.Set(str[i][0], str[i][3]);

            return pl;
        }
Esempio n. 6
0
		/// <summary> Constructs an empty ParameterList object with the provided default
		/// parameters. The list can be later updated by adding elements one by
		/// one, by loading them from a file, or by initializing them from an
		/// argument string.
		/// 
		/// </summary>
		/// <param name="def">The defaults parameters
		/// 
		/// </param>
		//UPGRADE_TODO: Format of property file may need to be changed. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1089'"
		//UPGRADE_ISSUE: Class hierarchy differences between 'java.util.Properties' and 'System.Collections.Specialized.NameValueCollection' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'"
		public ParameterList(ParameterList def):base()
		{
            defaults=def;
		}
Esempio n. 7
0
		/// <summary> Creates a ROIScaler object. The Quantizer is the source of data to
		/// scale.
		/// 
		/// <p>The ROI Scaler creates a ROIMaskGenerator depending on what ROI
		/// information is in the ParameterList. If only rectangular ROI are used,
		/// the fast mask generator for rectangular ROI can be used.</p>
		/// 
		/// </summary>
		/// <param name="src">The source of data to scale
		/// 
		/// </param>
		/// <param name="pl">The parameter list (or options).
		/// 
		/// </param>
		/// <param name="encSpec">The encoder specifications for addition of roi specs
		/// 
		/// </param>
		/// <exception cref="IllegalArgumentException">If an error occurs while parsing
		/// the options in 'pl'
		/// 
		/// </exception>
		public static ROIScaler createInstance(Quantizer src, ParameterList pl, EncoderSpecs encSpec)
		{
			System.Collections.ArrayList roiVector = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
			ROIMaskGenerator maskGen = null;
			
			// Check parameters
			pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo));
			
			// Get parameters and check if there are and ROIs specified 
			System.String roiopt = pl.getParameter("Rroi");
			if (roiopt == null)
			{
				// No ROIs specified! Create ROIScaler with no mask generator
				return new ROIScaler(src, null, false, - 1, false, encSpec);
			}
			
			// Check if the lowest resolution levels should belong to the ROI 
			int sLev = pl.getIntParameter("Rstart_level");
			
			// Check if the ROIs are block-aligned
			bool useBlockAligned = pl.getBooleanParameter("Ralign");
			
			// Check if generic mask generation is specified 
			bool onlyRect = !pl.getBooleanParameter("Rno_rect");
			
			// Parse the ROIs
			parseROIs(roiopt, src.NumComps, roiVector);
			ROI[] roiArray = new ROI[roiVector.Count];
			roiVector.CopyTo(roiArray);
			
			// If onlyRect has been forced, check if there are any non-rectangular
			// ROIs specified.  Currently, only the presence of circular ROIs will
			// make this false
			if (onlyRect)
			{
				for (int i = roiArray.Length - 1; i >= 0; i--)
					if (!roiArray[i].rect)
					{
						onlyRect = false;
						break;
					}
			}
			
			if (onlyRect)
			{
				// It's possible to use the fast ROI mask generation when only
				// rectangular ROIs are specified.
				maskGen = new RectROIMaskGenerator(roiArray, src.NumComps);
			}
			else
			{
				// It's necessary to use the generic mask generation
				maskGen = new ArbROIMaskGenerator(roiArray, src.NumComps, src);
			}
			return new ROIScaler(src, maskGen, true, sLev, useBlockAligned, encSpec);
		}
Esempio n. 8
0
        /// <summary> Initializes the header writer with the references to the coding chain.
        /// 
        /// </summary>
        /// <param name="origsrc">The original image data (before any component mixing,
        /// tiling, etc.)
        /// 
        /// </param>
        /// <param name="isorigsig">An array specifying for each component if it was
        /// originally signed or not.
        /// 
        /// </param>
        /// <param name="dwt">The discrete wavelet transform module.
        /// 
        /// </param>
        /// <param name="tiler">The tiler module.
        /// 
        /// </param>
        /// <param name="encSpec">The encoder specifications
        /// 
        /// </param>
        /// <param name="roiSc">The ROI scaler module.
        /// 
        /// </param>
        /// <param name="ralloc">The post compression rate allocator.
        /// 
        /// </param>
        /// <param name="pl">ParameterList instance.
        /// 
        /// </param>
        public HeaderEncoder(ImgData origsrc, bool[] isorigsig, ForwardWT dwt, Tiler tiler, EncoderSpecs encSpec, ROIScaler roiSc, PostCompRateAllocator ralloc, ParameterList pl)
        {
            pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo));
            if (origsrc.NumComps != isorigsig.Length)
            {
                throw new System.ArgumentException();
            }
            this.origSrc = origsrc;
            this.isOrigSig = isorigsig;
            this.dwt = dwt;
            this.tiler = tiler;
            this.encSpec = encSpec;
            this.roiSc = roiSc;
            this.ralloc = ralloc;

            baos = new System.IO.MemoryStream();
            //UPGRADE_TODO: Class 'java.io.DataOutputStream' was converted to 'System.IO.BinaryWriter' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioDataOutputStream'"
            hbuf = new CSJ2K.Util.EndianBinaryWriter(baos, true);
            nComp = origsrc.NumComps;
            enJJ2KMarkSeg = pl.getBooleanParameter("Hjj2000_COM");
            otherCOMMarkSeg = pl.getParameter("HCOM");
        }
Esempio n. 9
0
        /// <summary> Constructs a new 'QuantStepSizeSpec' for the specified number of
        /// components and tiles and the arguments of "-Qstep" option.
        /// 
        /// </summary>
        /// <param name="nt">The number of tiles
        /// 
        /// </param>
        /// <param name="nc">The number of components
        /// 
        /// </param>
        /// <param name="type">the type of the specification module i.e. tile specific,
        /// component specific or both.
        /// 
        /// </param>
        /// <param name="pl">The ParameterList
        /// 
        /// </param>
        public QuantStepSizeSpec(int nt, int nc, byte type, ParameterList pl)
            : base(nt, nc, type)
        {
            System.String param = pl.getParameter("Qstep");
            if (param == null)
            {
                throw new System.ArgumentException("Qstep option not specified");
            }

            // Parse argument
            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            System.String word; // current word
            byte curSpecType = SPEC_DEF; // Specification type of the
            // current parameter
            bool[] tileSpec = null; // Tiles concerned by the specification
            bool[] compSpec = null; // Components concerned by the specification
            System.Single value_Renamed; // value of the current step size

            while (stk.HasMoreTokens())
            {
                word = stk.NextToken().ToLower();

                switch (word[0])
                {

                    case 't':  // Tiles specification
                        tileSpec = parseIdx(word, nTiles);
                        if (curSpecType == SPEC_COMP_DEF)
                            curSpecType = SPEC_TILE_COMP;
                        else
                            curSpecType = SPEC_TILE_DEF;
                        break;

                    case 'c':  // Components specification
                        compSpec = parseIdx(word, nComp);
                        if (curSpecType == SPEC_TILE_DEF)
                            curSpecType = SPEC_TILE_COMP;
                        else
                            curSpecType = SPEC_COMP_DEF;
                        break;

                    default:  // Step size value
                        try
                        {
                            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                            value_Renamed = System.Single.Parse(word);
                        }
                        catch (System.FormatException e)
                        {
                            throw new System.ArgumentException("Bad parameter for " + "-Qstep option : " + word);
                        }

                        //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.floatValue' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                        if ((float) value_Renamed <= 0.0f)
                        {
                            //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Float.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                            throw new System.ArgumentException("Normalized base step " + "must be positive : " + value_Renamed);
                        }

                        if (curSpecType == SPEC_DEF)
                        {
                            setDefault((System.Object) value_Renamed);
                        }
                        else if (curSpecType == SPEC_TILE_DEF)
                        {
                            for (int i = tileSpec.Length - 1; i >= 0; i--)
                                if (tileSpec[i])
                                {
                                    setTileDef(i, (System.Object) value_Renamed);
                                }
                        }
                        else if (curSpecType == SPEC_COMP_DEF)
                        {
                            for (int i = compSpec.Length - 1; i >= 0; i--)
                                if (compSpec[i])
                                {
                                    setCompDef(i, (System.Object) value_Renamed);
                                }
                        }
                        else
                        {
                            for (int i = tileSpec.Length - 1; i >= 0; i--)
                            {
                                for (int j = compSpec.Length - 1; j >= 0; j--)
                                {
                                    if (tileSpec[i] && compSpec[j])
                                    {
                                        setTileCompVal(i, j, (System.Object) value_Renamed);
                                    }
                                }
                            }
                        }

                        // Re-initialize
                        curSpecType = SPEC_DEF;
                        tileSpec = null;
                        compSpec = null;
                        break;

                }
            }

            // Check that default value has been specified
            if (getDefault() == null)
            {
                int ndefspec = 0;
                for (int t = nt - 1; t >= 0; t--)
                {
                    for (int c = nc - 1; c >= 0; c--)
                    {
                        if (specValType[t][c] == SPEC_DEF)
                        {
                            ndefspec++;
                        }
                    }
                }

                // If some tile-component have received no specification, it takes
                // the default value defined in ParameterList
                if (ndefspec != 0)
                {
                    //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                    setDefault((System.Object) System.Single.Parse(pl.DefaultParameterList.getParameter("Qstep")));
                }
                else
                {
                    // All tile-component have been specified, takes the first
                    // tile-component value as default.
                    setDefault(getTileCompVal(0, 0));
                    switch (specValType[0][0])
                    {

                        case SPEC_TILE_DEF:
                            for (int c = nc - 1; c >= 0; c--)
                            {
                                if (specValType[0][c] == SPEC_TILE_DEF)
                                    specValType[0][c] = SPEC_DEF;
                            }
                            tileDef[0] = null;
                            break;

                        case SPEC_COMP_DEF:
                            for (int t = nt - 1; t >= 0; t--)
                            {
                                if (specValType[t][0] == SPEC_COMP_DEF)
                                    specValType[t][0] = SPEC_DEF;
                            }
                            compDef[0] = null;
                            break;

                        case SPEC_TILE_COMP:
                            specValType[0][0] = SPEC_DEF;
                            tileCompVal["t0c0"] = null;
                            break;
                        }
                }
            }
        }
Esempio n. 10
0
        static J2KEncoder()
        {
            pl = new ParameterList();
            string[][] parameters = GetAllParameters();
            for (int i = 0; i < parameters.Length; i++)
            {
                string[] param = parameters[i];
                pl.Set(param[0], param[3]);
            }

            // Custom parameters
            pl.Set("Aptype", "layer");
            pl.Set("Qguard_bits", "1");
            pl.Set("Alayers", "sl");
            //pl.Set("lossless", "on");
        }
		/// <summary> Creates a PostCompRateAllocator object for the appropriate rate
		/// allocation parameters in the parameter list 'pl', having 'src' as the
		/// source of entropy coded data, 'rate' as the target bitrate and 'bw' as
		/// the bit stream writer object.
		/// 
		/// </summary>
		/// <param name="src">The source of entropy coded data.
		/// 
		/// </param>
		/// <param name="pl">The parameter lis (or options).
		/// 
		/// </param>
		/// <param name="rate">The target bitrate for the rate allocation
		/// 
		/// </param>
		/// <param name="bw">The bit stream writer object, where the bit stream data will
		/// be written.
		/// 
		/// </param>
		public static PostCompRateAllocator createInstance(CodedCBlkDataSrcEnc src, ParameterList pl, float rate, CodestreamWriter bw, EncoderSpecs encSpec)
		{
			// Check parameters
			pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo));
			
			// Construct the layer specification from the 'Alayers' option
			LayersInfo lyrs = parseAlayers(pl.getParameter("Alayers"), rate);
			
			int nTiles = encSpec.nTiles;
			int nComp = encSpec.nComp;
			int numLayers = lyrs.TotNumLayers;
			
			// Parse the progressive type
			encSpec.pocs = new ProgressionSpec(nTiles, nComp, numLayers, encSpec.dls, ModuleSpec.SPEC_TYPE_TILE_COMP, pl);
			
			return new EBCOTRateAllocator(src, lyrs, bw, encSpec, pl);
		}
Esempio n. 12
0
        /// <summary>General utility used by ctors </summary>
        private void initialize()
        {
            this.pl = csMap.pl;
            this.ncomps = src.NumComps;

            shiftValueArray = new int[ncomps];
            maxValueArray = new int[ncomps];
            fixedPtBitsArray = new int[ncomps];

            srcBlk = new DataBlk[ncomps];
            inInt = new DataBlkInt[ncomps];
            inFloat = new DataBlkFloat[ncomps];
            workInt = new DataBlkInt[ncomps];
            workFloat = new DataBlkFloat[ncomps];
            dataInt = new int[ncomps][];
            dataFloat = new float[ncomps][];
            workDataInt = new int[ncomps][];
            workDataFloat = new float[ncomps][];
            dataInt = new int[ncomps][];
            dataFloat = new float[ncomps][];

            /* For each component, get a reference to the pixel data and
            * set up working DataBlks for both integer and float output.
            */
            for (int i = 0; i < ncomps; ++i)
            {

                shiftValueArray[i] = 1 << (src.getNomRangeBits(i) - 1);
                maxValueArray[i] = (1 << src.getNomRangeBits(i)) - 1;
                fixedPtBitsArray[i] = src.getFixedPoint(i);

                inInt[i] = new DataBlkInt();
                inFloat[i] = new DataBlkFloat();
                workInt[i] = new DataBlkInt();
                workInt[i].progressive = inInt[i].progressive;
                workFloat[i] = new DataBlkFloat();
                workFloat[i].progressive = inFloat[i].progressive;
            }
        }
Esempio n. 13
0
		/// <summary> Creates a new CBlkSizeSpec object for the specified number of tiles and
		/// components and the ParameterList instance.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="imgsrc">The image source (used to get the image size)
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		public CBlkSizeSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			bool firstVal = true;
			System.String param = pl.getParameter(optName);
			
			// Precinct partition is used : parse arguments
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
            int ci, ti; //  i, xIdx removed
			System.String word = null; // current word
			System.String errMsg = null;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					
					default: 
						if (!System.Char.IsDigit(word[0]))
						{
							errMsg = "Bad construction for parameter: " + word;
							throw new System.ArgumentException(errMsg);
						}
						System.Int32[] dim = new System.Int32[2];
						// Get code-block's width
						try
						{
							dim[0] = System.Int32.Parse(word);
							// Check that width is not >
							// StdEntropyCoderOptions.MAX_CB_DIM
							if (dim[0] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM)
							{
								errMsg = "'" + optName + "' option : the code-block's " + "width cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM;
								throw new System.ArgumentException(errMsg);
							}
							// Check that width is not <
							// StdEntropyCoderOptions.MIN_CB_DIM
							if (dim[0] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM)
							{
								errMsg = "'" + optName + "' option : the code-block's " + "width cannot be less than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM;
								throw new System.ArgumentException(errMsg);
							}
							// Check that width is a power of 2
							if (dim[0] != (1 << MathUtil.log2(dim[0])))
							{
								errMsg = "'" + optName + "' option : the code-block's " + "width must be a power of 2";
								throw new System.ArgumentException(errMsg);
							}
						}
						catch (System.FormatException)
						{
							errMsg = "'" + optName + "' option : the code-block's " + "width could not be parsed.";
							throw new System.ArgumentException(errMsg);
						}
						// Get the next word in option
						try
						{
							word = stk.NextToken();
						}
						catch (System.ArgumentOutOfRangeException)
						{
							errMsg = "'" + optName + "' option : could not parse the " + "code-block's height";
							throw new System.ArgumentException(errMsg);
						}
						// Get the code-block's height
						try
						{
							dim[1] = System.Int32.Parse(word);
							// Check that height is not >
							// StdEntropyCoderOptions.MAX_CB_DIM
							if (dim[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM)
							{
								errMsg = "'" + optName + "' option : the code-block's " + "height cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_DIM;
								throw new System.ArgumentException(errMsg);
							}
							// Check that height is not <
							// StdEntropyCoderOptions.MIN_CB_DIM
							if (dim[1] < CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM)
							{
								errMsg = "'" + optName + "' option : the code-block's " + "height cannot be less than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MIN_CB_DIM;
								throw new System.ArgumentException(errMsg);
							}
							// Check that height is a power of 2
							if (dim[1] != (1 << MathUtil.log2(dim[1])))
							{
								errMsg = "'" + optName + "' option : the code-block's " + "height must be a power of 2";
								throw new System.ArgumentException(errMsg);
							}
							// Check that the code-block 'area' (i.e. width*height) is
							// not greater than StdEntropyCoderOptions.MAX_CB_AREA
							if (dim[0] * dim[1] > CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA)
							{
								errMsg = "'" + optName + "' option : The " + "code-block's area (i.e. width*height) " + "cannot be greater than " + CSJ2K.j2k.entropy.StdEntropyCoderOptions.MAX_CB_AREA;
								throw new System.ArgumentException(errMsg);
							}
						}
						catch (System.FormatException)
						{
							errMsg = "'" + optName + "' option : the code-block's height " + "could not be parsed.";
							throw new System.ArgumentException(errMsg);
						}
						
						// Store the maximum dimensions if necessary
						if (dim[0] > maxCBlkWidth)
						{
							maxCBlkWidth = dim[0];
						}
						
						if (dim[1] > maxCBlkHeight)
						{
							maxCBlkHeight = dim[1];
						}
						
						if (firstVal)
						{
							// This is the first time a value is given so we set it as
							// the default one 
							setDefault((System.Object) (dim));
							firstVal = false;
						}
						
						switch (curSpecType)
						{
							
							case SPEC_DEF: 
								setDefault((System.Object) (dim));
								break;
							
							case SPEC_TILE_DEF: 
								for (ti = tileSpec.Length - 1; ti >= 0; ti--)
								{
									if (tileSpec[ti])
									{
										setTileDef(ti, (System.Object) (dim));
									}
								}
								break;
							
							case SPEC_COMP_DEF: 
								for (ci = compSpec.Length - 1; ci >= 0; ci--)
								{
									if (compSpec[ci])
									{
										setCompDef(ci, (System.Object) (dim));
									}
								}
								break;
							
							default: 
								for (ti = tileSpec.Length - 1; ti >= 0; ti--)
								{
									for (ci = compSpec.Length - 1; ci >= 0; ci--)
									{
										if (tileSpec[ti] && compSpec[ci])
										{
											setTileCompVal(ti, ci, (System.Object) (dim));
										}
									}
								}
								break;
							
						}
						break;
					
				} // end switch
			}
		}
Esempio n. 14
0
		/// <summary> Creates a bit stream reader of the correct type that works on the
		/// provided RandomAccessIO, with the special parameters from the parameter
		/// list.
		/// 
		/// </summary>
		/// <param name="in">The RandomAccessIO source from which to read the bit stream.
		/// 
		/// </param>
		/// <param name="hd">Header of the codestream.
		/// 
		/// </param>
		/// <param name="pl">The parameter list containing parameters applicable to the
		/// bit stream read (other parameters may also be present).
		/// 
		/// </param>
		/// <param name="decSpec">The decoder specifications
		/// 
		/// </param>
		/// <param name="cdstrInfo">Whether or not to print information found in
		/// codestream. 
		/// 
		/// </param>
		/// <param name="hi">Reference to the HeaderInfo instance.
		/// 
		/// </param>
		/// <exception cref="IOException">If an I/O error occurs while reading initial
		/// data from the bit stream.
		/// </exception>
		/// <exception cref="IllegalArgumentException">If an unrecognised bit stream
		/// reader option is present.
		/// 
		/// </exception>
		public static BitstreamReaderAgent createInstance(RandomAccessIO in_Renamed, HeaderDecoder hd, ParameterList pl, DecoderSpecs decSpec, bool cdstrInfo, HeaderInfo hi)
		{
			
			// Check parameters
			pl.checkList(BitstreamReaderAgent.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(BitstreamReaderAgent.ParameterInfo));
			
			return new FileBitstreamReaderAgent(hd, in_Renamed, decSpec, pl, cdstrInfo, hi);
		}
Esempio n. 15
0
		/// <summary> Creates a ForwardWT object with the specified filters, and with other
		/// options specified in the parameter list 'pl'.
		/// 
		/// </summary>
		/// <param name="src">The source of data to be transformed
		/// 
		/// </param>
		/// <param name="pl">The parameter list (or options).
		/// 
		/// </param>
		/// <param name="kers">The encoder specifications.
		/// 
		/// </param>
		/// <returns> A new ForwardWT object with the specified filters and options
		/// from 'pl'.
		/// 
		/// </returns>
		/// <exception cref="IllegalArgumentException">If mandatory parameters are missing 
		/// or if invalid values are given.
		/// 
		/// </exception>
		public static ForwardWT createInstance(BlkImgDataSrc src, ParameterList pl, EncoderSpecs encSpec)
		{
            int deflev; // defdec removed
			//System.String decompstr;
			//System.String wtstr;
			//System.String pstr;
			//SupportClass.StreamTokenizerSupport stok;
			//SupportClass.Tokenizer strtok;
			//int prefx, prefy; // Partitioning reference point coordinates
			
			// Check parameters
			pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo));
			
			deflev = ((System.Int32) encSpec.dls.getDefault());
			
			// Code-block partition origin
			System.String str = "";
			if (pl.getParameter("Wcboff") == null)
			{
				throw new System.ApplicationException("You must specify an argument to the '-Wcboff' " + "option. See usage with the '-u' option");
			}
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(pl.getParameter("Wcboff"));
			if (stk.Count != 2)
			{
				throw new System.ArgumentException("'-Wcboff' option needs two" + " arguments. See usage with " + "the '-u' option.");
			}
			int cb0x = 0;
			str = stk.NextToken();
			try
			{
				cb0x = (System.Int32.Parse(str));
			}
			catch (System.FormatException)
			{
				throw new System.ArgumentException("Bad first parameter for the " + "'-Wcboff' option: " + str);
			}
			if (cb0x < 0 || cb0x > 1)
			{
				throw new System.ArgumentException("Invalid horizontal " + "code-block partition origin.");
			}
			int cb0y = 0;
			str = stk.NextToken();
			try
			{
				cb0y = (System.Int32.Parse(str));
			}
			catch (System.FormatException)
			{
				throw new System.ArgumentException("Bad second parameter for the " + "'-Wcboff' option: " + str);
			}
			if (cb0y < 0 || cb0y > 1)
			{
				throw new System.ArgumentException("Invalid vertical " + "code-block partition origin.");
			}
			if (cb0x != 0 || cb0y != 0)
			{
				FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Code-blocks partition origin is " + "different from (0,0). This is defined in JPEG 2000" + " part 2 and may be not supported by all JPEG 2000 " + "decoders.");
			}
			
			return new ForwWTFull(src, encSpec, cb0x, cb0y);
		}
Esempio n. 16
0
		/// <summary> Constructs a new 'ForwCompTransfSpec' for the specified number of
		/// components and tiles, the wavelet filters type and the parameter of the
		/// option 'Mct'. This constructor is called by the encoder. It also checks
		/// that the arguments belong to the recognized arguments list.
		/// 
		/// <p>This constructor chose the component transformation type depending
		/// on the wavelet filters : RCT with w5x3 filter and ICT with w9x7
		/// filter. Note: All filters must use the same data type.</p>
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="wfs">The wavelet filter specifications
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public ForwCompTransfSpec(int nt, int nc, byte type, AnWTFilterSpec wfs, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Mct");
			
			if (param == null)
			{
				// The option has not been specified
				
				// If less than three component, do not use any component
				// transformation 
				if (nc < 3)
				{
					setDefault("none");
					return ;
				}
				// If the compression is lossless, uses RCT
				else if (pl.getBooleanParameter("lossless"))
				{
					setDefault("rct");
					return ;
				}
				else
				{
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getCompDef(c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three first components use the same filters
					bool reject = false;
					for (int c = 1; c < 3; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setDefault("none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getCompDef(0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setDefault("ict");
						}
						else
						{
							setDefault("rct");
						}
					}
				}
				
				// Each tile receives a component transform specification
				// according the type of wavelet filters that are used by the
				// three first components
				for (int t = 0; t < nt; t++)
				{
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three components use the same filters
					bool reject = false;
					for (int c = 1; c < nComp; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setTileDef(t, "none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, 0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setTileDef(t, "ict");
						}
						else
						{
							setTileDef(t, "rct");
						}
					}
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the
			// specification
			//System.Boolean value_Renamed;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						throw new System.ArgumentException("Component specific " + " parameters" + " not allowed with " + "'-Mct' option");
					
					default: 
						if (word.Equals("off"))
						{
							if (curSpecType == SPEC_DEF)
							{
								setDefault("none");
							}
							else if (curSpecType == SPEC_TILE_DEF)
							{
								for (int i = tileSpec.Length - 1; i >= 0; i--)
									if (tileSpec[i])
									{
										setTileDef(i, "none");
									}
							}
						}
						else if (word.Equals("on"))
						{
							if (nc < 3)
							{
								throw new System.ArgumentException("Cannot use component" + " transformation on a " + "image with less than " + "three components");
							}
							
							if (curSpecType == SPEC_DEF)
							{
								// Set arbitrarily the default
								// value to RCT (later will be found the suitable
								// component transform for each tile)
								setDefault("rct");
							}
							else if (curSpecType == SPEC_TILE_DEF)
							{
								for (int i = tileSpec.Length - 1; i >= 0; i--)
								{
									if (tileSpec[i])
									{
										if (getFilterType(i, wfs) == CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3)
										{
											setTileDef(i, "rct");
										}
										else
										{
											setTileDef(i, "ict");
										}
									}
								}
							}
						}
						else
						{
							throw new System.ArgumentException("Default parameter of " + "option Mct not" + " recognized: " + param);
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						break;
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				// If not, set arbitrarily the default value to 'none' but
				// specifies explicitely a default value for each tile depending
				// on the wavelet transform that is used
				setDefault("none");
				
				for (int t = 0; t < nt; t++)
				{
					if (isTileSpecified(t))
					{
						continue;
					}
					
					AnWTFilter[][] anfilt;
					int[] filtType = new int[nComp];
					for (int c = 0; c < 3; c++)
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, c);
						filtType[c] = anfilt[0][0].FilterType;
					}
					
					// Check that the three components use the same filters
					bool reject = false;
					for (int c = 1; c < nComp; c++)
					{
						if (filtType[c] != filtType[0])
							reject = true;
					}
					
					if (reject)
					{
						setTileDef(t, "none");
					}
					else
					{
						anfilt = (AnWTFilter[][]) wfs.getTileCompVal(t, 0);
						if (anfilt[0][0].FilterType == CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7)
						{
							setTileDef(t, "ict");
						}
						else
						{
							setTileDef(t, "rct");
						}
					}
				}
			}
			
			// Check validity of component transformation of each tile compared to
			// the filter used.
			for (int t = nt - 1; t >= 0; t--)
			{
				
				if (((System.String) getTileDef(t)).Equals("none"))
				{
					// No comp. transf is used. No check is needed
					continue;
				}
				else if (((System.String) getTileDef(t)).Equals("rct"))
				{
					// Tile is using Reversible component transform
					int filterType = getFilterType(t, wfs);
					switch (filterType)
					{
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3:  // OK
							break;
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7:  // Must use ICT
							if (isTileSpecified(t))
							{
								// User has requested RCT -> Error
								throw new System.ArgumentException("Cannot use RCT " + "with 9x7 filter " + "in tile " + t);
							}
							else
							{
								// Specify ICT for this tile
								setTileDef(t, "ict");
							}
							break;
						
						default: 
							throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant");
						
					}
				}
				else
				{
					// ICT
					int filterType = getFilterType(t, wfs);
					switch (filterType)
					{
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W5X3:  // Must use RCT
							if (isTileSpecified(t))
							{
								// User has requested ICT -> Error
								throw new System.ArgumentException("Cannot use ICT " + "with filter 5x3 " + "in tile " + t);
							}
							else
							{
								setTileDef(t, "rct");
							}
							break;
						
						case CSJ2K.j2k.wavelet.FilterTypes_Fields.W9X7:  // OK
							break;
						
						default: 
							throw new System.ArgumentException("Default filter is " + "not JPEG 2000 part" + " I compliant");
						
					}
				}
			}
		}
Esempio n. 17
0
        /// <summary> Creates a new ProgressionSpec object for the specified number of tiles,
        /// components and the ParameterList instance.
        /// 
        /// </summary>
        /// <param name="nt">The number of tiles
        /// 
        /// </param>
        /// <param name="nc">The number of components
        /// 
        /// </param>
        /// <param name="nl">The number of layer
        /// 
        /// </param>
        /// <param name="dls">The number of decomposition levels specifications
        /// 
        /// </param>
        /// <param name="type">the type of the specification module. The ProgressionSpec
        /// class should only be used only with the type ModuleSpec.SPEC_TYPE_TILE.
        /// 
        /// </param>
        /// <param name="pl">The ParameterList instance
        /// 
        /// </param>
        public ProgressionSpec(int nt, int nc, int nl, IntegerSpec dls, byte type, ParameterList pl)
            : base(nt, nc, type)
        {
            System.String param = pl.getParameter("Aptype");
            Progression[] prog;
            int mode = - 1;

            if (param == null)
            {
                // No parameter specified
                if (pl.getParameter("Rroi") == null)
                {
                    mode = checkProgMode("res");
                }
                else
                {
                    mode = checkProgMode("layer");
                }

                if (mode == - 1)
                {
                    System.String errMsg = "Unknown progression type : '" + param + "'";
                    throw new System.ArgumentException(errMsg);
                }
                prog = new Progression[1];
                prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                setDefault(prog);
                return ;
            }

            SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
            byte curSpecType = SPEC_DEF; // Specification type of the
            // current parameter
            bool[] tileSpec = null; // Tiles concerned by the specification
            System.String word = null; // current word
            System.String errMsg2 = null; // Error message
            bool needInteger = false; // True if an integer value is expected
            int intType = 0; // Type of read integer value (0=index of first
            // resolution level, 1= index of first component, 2=index of first
            // layer not included, 3= index of first resolution level not
            // included, 4= index of  first component not included
            System.Collections.Generic.List<Progression> progression = new List<Progression>(10);
            int tmp = 0;
            Progression curProg = null;

            while (stk.HasMoreTokens())
            {
                word = stk.NextToken();

                switch (word[0])
                {

                    case 't':
                        // If progression were previously found, store them
                        if (progression.Count > 0)
                        {
                            // Ensure that all information has been taken
                            curProg.ce = nc;
                            curProg.lye = nl;
                            curProg.re = dls.Max + 1;
                            prog = new Progression[progression.Count];
                            progression.CopyTo(prog);
                            if (curSpecType == SPEC_DEF)
                            {
                                setDefault(prog);
                            }
                            else if (curSpecType == SPEC_TILE_DEF)
                            {
                                for (int i = tileSpec.Length - 1; i >= 0; i--)
                                    if (tileSpec[i])
                                    {
                                        setTileDef(i, prog);
                                    }
                            }
                        }
                        progression.Clear();
                        intType = - 1;
                        needInteger = false;

                        // Tiles specification
                        tileSpec = parseIdx(word, nTiles);
                        curSpecType = SPEC_TILE_DEF;
                        break;

                    default:
                        // Here, words is either a Integer (progression bound index)
                        // or a String (progression order type). This is determined by
                        // the value of needInteger.
                        if (needInteger)
                        {
                            // Progression bound info
                            try
                            {
                                tmp = (System.Int32.Parse(word));
                            }
                            catch (System.FormatException e)
                            {
                                // Progression has missing parameters
                                throw new System.ArgumentException("Progression " + "order" + " specification " + "has missing " + "parameters: " + param);
                            }

                            switch (intType)
                            {

                                case 0:  // cs
                                    if (tmp < 0 || tmp > (dls.Max + 1))
                                        throw new System.ArgumentException("Invalid res_start " + "in '-Aptype'" + " option: " + tmp);
                                    curProg.rs = tmp; break;

                                case 1:  // rs
                                    if (tmp < 0 || tmp > nc)
                                    {
                                        throw new System.ArgumentException("Invalid comp_start " + "in '-Aptype' " + "option: " + tmp);
                                    }
                                    curProg.cs = tmp; break;

                                case 2:  // lye
                                    if (tmp < 0)
                                        throw new System.ArgumentException("Invalid layer_end " + "in '-Aptype'" + " option: " + tmp);
                                    if (tmp > nl)
                                    {
                                        tmp = nl;
                                    }
                                    curProg.lye = tmp; break;

                                case 3:  // ce
                                    if (tmp < 0)
                                        throw new System.ArgumentException("Invalid res_end " + "in '-Aptype'" + " option: " + tmp);
                                    if (tmp > (dls.Max + 1))
                                    {
                                        tmp = dls.Max + 1;
                                    }
                                    curProg.re = tmp; break;

                                case 4:  // re
                                    if (tmp < 0)
                                        throw new System.ArgumentException("Invalid comp_end " + "in '-Aptype'" + " option: " + tmp);
                                    if (tmp > nc)
                                    {
                                        tmp = nc;
                                    }
                                    curProg.ce = tmp; break;
                                }

                            if (intType < 4)
                            {
                                intType++;
                                needInteger = true;
                                break;
                            }
                            else if (intType == 4)
                            {
                                intType = 0;
                                needInteger = false;
                                break;
                            }
                            else
                            {
                                throw new System.InvalidOperationException("Error in usage of 'Aptype' " + "option: " + param);
                            }
                        }

                        if (!needInteger)
                        {
                            // Progression type info
                            mode = checkProgMode(word);
                            if (mode == - 1)
                            {
                                errMsg2 = "Unknown progression type : '" + word + "'";
                                throw new System.ArgumentException(errMsg2);
                            }
                            needInteger = true;
                            intType = 0;
                            if (progression.Count == 0)
                            {
                                curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                            }
                            else
                            {
                                curProg = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                            }
                            progression.Add(curProg);
                        }
                        break;

                } // switch
            } // while

            if (progression.Count == 0)
            {
                // No progression defined
                if (pl.getParameter("Rroi") == null)
                {
                    mode = checkProgMode("res");
                }
                else
                {
                    mode = checkProgMode("layer");
                }
                if (mode == - 1)
                {
                    errMsg2 = "Unknown progression type : '" + param + "'";
                    throw new System.ArgumentException(errMsg2);
                }
                prog = new Progression[1];
                prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                setDefault(prog);
                return ;
            }

            // Ensure that all information has been taken
            curProg.ce = nc;
            curProg.lye = nl;
            curProg.re = dls.Max + 1;

            // Store found progression
            prog = new Progression[progression.Count];
            progression.CopyTo(prog);

            if (curSpecType == SPEC_DEF)
            {
                setDefault(prog);
            }
            else if (curSpecType == SPEC_TILE_DEF)
            {
                for (int i = tileSpec.Length - 1; i >= 0; i--)
                    if (tileSpec[i])
                    {
                        setTileDef(i, prog);
                    }
            }

            // Check that default value has been specified
            if (getDefault() == null)
            {
                int ndefspec = 0;
                for (int t = nt - 1; t >= 0; t--)
                {
                    for (int c = nc - 1; c >= 0; c--)
                    {
                        if (specValType[t][c] == SPEC_DEF)
                        {
                            ndefspec++;
                        }
                    }
                }

                // If some tile-component have received no specification, they
                // receive the default progressiveness.
                if (ndefspec != 0)
                {
                    if (pl.getParameter("Rroi") == null)
                    {
                        mode = checkProgMode("res");
                    }
                    else
                    {
                        mode = checkProgMode("layer");
                    }
                    if (mode == - 1)
                    {
                        errMsg2 = "Unknown progression type : '" + param + "'";
                        throw new System.ArgumentException(errMsg2);
                    }
                    prog = new Progression[1];
                    prog[0] = new Progression(mode, 0, nc, 0, dls.Max + 1, nl);
                    setDefault(prog);
                }
                else
                {
                    // All tile-component have been specified, takes the first
                    // tile-component value as default.
                    setDefault(getTileCompVal(0, 0));
                    switch (specValType[0][0])
                    {

                        case SPEC_TILE_DEF:
                            for (int c = nc - 1; c >= 0; c--)
                            {
                                if (specValType[0][c] == SPEC_TILE_DEF)
                                    specValType[0][c] = SPEC_DEF;
                            }
                            tileDef[0] = null;
                            break;

                        case SPEC_COMP_DEF:
                            for (int t = nt - 1; t >= 0; t--)
                            {
                                if (specValType[t][0] == SPEC_COMP_DEF)
                                    specValType[t][0] = SPEC_DEF;
                            }
                            compDef[0] = null;
                            break;

                        case SPEC_TILE_COMP:
                            specValType[0][0] = SPEC_DEF;
                            tileCompVal["t0c0"] = null;
                            break;
                        }
                }
            }
        }
Esempio n. 18
0
        public static List<int> GetLayerBoundaries(Stream stream)
        {
            RandomAccessIO in_stream = new ISRandomAccessIO(stream);

            // Create parameter list using defaults
            ParameterList pl = new ParameterList(GetDefaultParameterList(decoder_pinfo));

            // **** File Format ****
            // If the codestream is wrapped in the jp2 fileformat, Read the
            // file format wrapper
            FileFormatReader ff = new FileFormatReader(in_stream);
            ff.readFileFormat();
            if (ff.JP2FFUsed)
            {
                in_stream.seek(ff.FirstCodeStreamPos);
            }

            // +----------------------------+
            // | Instantiate decoding chain |
            // +----------------------------+

            // **** Header decoder ****
            // Instantiate header decoder and read main header 
            HeaderInfo hi = new HeaderInfo();
            HeaderDecoder hd;
            try
            {
                hd = new HeaderDecoder(in_stream, pl, hi);
            }
            catch (EndOfStreamException e)
            {
                throw new ArgumentException("Codestream too short or bad header, unable to decode.", e);
            }

            int nCompCod = hd.NumComps;
            int nTiles = hi.sizValue.NumTiles;
            DecoderSpecs decSpec = hd.DecoderSpecs;

            // Get demixed bitdepths
            int[] depth = new int[nCompCod];
            for (int i = 0; i < nCompCod; i++)
            {
                depth[i] = hd.getOriginalBitDepth(i);
            }

            // **** Bit stream reader ****
            BitstreamReaderAgent breader;
            try
            {
                breader = BitstreamReaderAgent.createInstance(in_stream, hd, pl, decSpec, false, hi);
            }
            catch (IOException e)
            {
                throw new ArgumentException("Error while reading bit stream header or parsing packets.", e);
            }
            catch (ArgumentException e)
            {
                throw new ArgumentException("Cannot instantiate bit stream reader.", e);
            }

            breader.setTile(0, 0);

            return ((FileBitstreamReaderAgent)breader).layerStarts;
        }
Esempio n. 19
0
        /// <summary> Creates a new packet encoder object, using the information from the
        /// 'infoSrc' object. 
        /// 
        /// </summary>
        /// <param name="infoSrc">The source of information to construct the object.
        /// 
        /// </param>
        /// <param name="encSpec">The encoding parameters.
        /// 
        /// </param>
        /// <param name="numPrec">Maximum number of precincts in each tile, component
        /// and resolution level.
        /// 
        /// </param>
        /// <param name="pl">ParameterList instance that holds command line options
        /// 
        /// </param>
        public PktEncoder(CodedCBlkDataSrcEnc infoSrc, EncoderSpecs encSpec, Coord[][][] numPrec, ParameterList pl)
        {
            this.infoSrc = infoSrc;
            this.encSpec = encSpec;

            // Check parameters
            pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo));

            // Get number of components and tiles
            int nc = infoSrc.NumComps;
            int nt = infoSrc.getNumTiles();

            // Do initial allocation
            ttIncl = new TagTreeEncoder[nt][][][][];
            for (int i = 0; i < nt; i++)
            {
                ttIncl[i] = new TagTreeEncoder[nc][][][];
            }
            ttMaxBP = new TagTreeEncoder[nt][][][][];
            for (int i2 = 0; i2 < nt; i2++)
            {
                ttMaxBP[i2] = new TagTreeEncoder[nc][][][];
            }
            lblock = new int[nt][][][][];
            for (int i3 = 0; i3 < nt; i3++)
            {
                lblock[i3] = new int[nc][][][];
            }
            prevtIdxs = new int[nt][][][][];
            for (int i4 = 0; i4 < nt; i4++)
            {
                prevtIdxs[i4] = new int[nc][][][];
            }
            ppinfo = new PrecInfo[nt][][][];
            for (int i5 = 0; i5 < nt; i5++)
            {
                ppinfo[i5] = new PrecInfo[nc][][];
            }

            // Finish allocation
            SubbandAn root, sb;
            int maxs, mins;
            int mrl;
            //Coord tmpCoord = null;
            int numcb; // Number of code-blocks
            //System.Collections.ArrayList cblks = null;
            infoSrc.setTile(0, 0);
            for (int t = 0; t < nt; t++)
            {
                // Loop on tiles
                for (int c = 0; c < nc; c++)
                {
                    // Loop on components
                    // Get number of resolution levels
                    root = infoSrc.getAnSubbandTree(t, c);
                    mrl = root.resLvl;

                    lblock[t][c] = new int[mrl + 1][][];
                    ttIncl[t][c] = new TagTreeEncoder[mrl + 1][][];
                    ttMaxBP[t][c] = new TagTreeEncoder[mrl + 1][][];
                    prevtIdxs[t][c] = new int[mrl + 1][][];
                    ppinfo[t][c] = new PrecInfo[mrl + 1][];

                    for (int r = 0; r <= mrl; r++)
                    {
                        // Loop on resolution levels
                        mins = (r == 0)?0:1;
                        maxs = (r == 0)?1:4;

                        int maxPrec = numPrec[t][c][r].x * numPrec[t][c][r].y;

                        ttIncl[t][c][r] = new TagTreeEncoder[maxPrec][];
                        for (int i6 = 0; i6 < maxPrec; i6++)
                        {
                            ttIncl[t][c][r][i6] = new TagTreeEncoder[maxs];
                        }
                        ttMaxBP[t][c][r] = new TagTreeEncoder[maxPrec][];
                        for (int i7 = 0; i7 < maxPrec; i7++)
                        {
                            ttMaxBP[t][c][r][i7] = new TagTreeEncoder[maxs];
                        }
                        prevtIdxs[t][c][r] = new int[maxs][];
                        lblock[t][c][r] = new int[maxs][];

                        // Precincts and code-blocks
                        ppinfo[t][c][r] = new PrecInfo[maxPrec];
                        fillPrecInfo(t, c, r);

                        for (int s = mins; s < maxs; s++)
                        {
                            // Loop on subbands
                            sb = (SubbandAn) root.getSubbandByIdx(r, s);
                            numcb = sb.numCb.x * sb.numCb.y;

                            lblock[t][c][r][s] = new int[numcb];
                            ArrayUtil.intArraySet(lblock[t][c][r][s], INIT_LBLOCK);

                            prevtIdxs[t][c][r][s] = new int[numcb];
                            ArrayUtil.intArraySet(prevtIdxs[t][c][r][s], - 1);
                        }
                    }
                }
                if (t != nt - 1)
                    infoSrc.nextTile();
            }
        }
Esempio n. 20
0
        public static Image FromStream(Stream stream)
        {
            RandomAccessIO in_stream = new ISRandomAccessIO(stream);

            // Initialize default parameters
            ParameterList defpl = GetDefaultParameterList(decoder_pinfo);

            // Create parameter list using defaults
            ParameterList pl = new ParameterList(defpl);

            // **** File Format ****
            // If the codestream is wrapped in the jp2 fileformat, Read the
            // file format wrapper
            FileFormatReader ff = new FileFormatReader(in_stream);
            ff.readFileFormat();
            if (ff.JP2FFUsed)
            {
                in_stream.seek(ff.FirstCodeStreamPos);
            }

            // +----------------------------+
            // | Instantiate decoding chain |
            // +----------------------------+

            // **** Header decoder ****
            // Instantiate header decoder and read main header 
            HeaderInfo hi = new HeaderInfo();
            HeaderDecoder hd;
            try
            {
                hd = new HeaderDecoder(in_stream, pl, hi);
            }
            catch (EndOfStreamException e)
            {
                throw new ApplicationException("Codestream too short or bad header, unable to decode.", e);
            }

            int nCompCod = hd.NumComps;
            int nTiles = hi.sizValue.NumTiles;
            DecoderSpecs decSpec = hd.DecoderSpecs;

            // Get demixed bitdepths
            int[] depth = new int[nCompCod];
            for (int i = 0; i < nCompCod; i++)
            {
                depth[i] = hd.getOriginalBitDepth(i);
            }

            // **** Bit stream reader ****
            BitstreamReaderAgent breader;
            try
            {
                breader = BitstreamReaderAgent.
                    createInstance(in_stream, hd, pl, decSpec,
                                   false, hi);
            }
            catch (IOException e)
            {
                throw new ApplicationException("Error while reading bit stream header or parsing packets.", e);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate bit stream reader.", e);
            }

            // **** Entropy decoder ****
            EntropyDecoder entdec;
            try
            {
                entdec = hd.createEntropyDecoder(breader, pl);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate entropy decoder.", e);
            }

            // **** ROI de-scaler ****
            ROIDeScaler roids;
            try
            {
                roids = hd.createROIDeScaler(entdec, pl, decSpec);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate roi de-scaler.", e);
            }

            // **** Dequantizer ****
            Dequantizer deq;
            try
            {
                deq = hd.createDequantizer(roids, depth, decSpec);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate dequantizer.", e);
            }

            // **** Inverse wavelet transform ***
            InverseWT invWT;
            try
            {
                // full page inverse wavelet transform
                invWT = InverseWT.createInstance(deq, decSpec);
            }
            catch (ArgumentException e)
            {
                throw new ApplicationException("Cannot instantiate inverse wavelet transform.", e);
            }

            int res = breader.ImgRes;
            invWT.ImgResLevel = res;

            // **** Data converter **** (after inverse transform module)
            ImgDataConverter converter = new ImgDataConverter(invWT, 0);

            // **** Inverse component transformation **** 
            InvCompTransf ictransf = new InvCompTransf(converter, decSpec, depth, pl);

            // **** Color space mapping ****
            BlkImgDataSrc color;
            if (ff.JP2FFUsed && pl.getParameter("nocolorspace").Equals("off"))
            {
                try
                {
                    ColorSpace csMap = new ColorSpace(in_stream, hd, pl);
                    BlkImgDataSrc channels = hd.createChannelDefinitionMapper(ictransf, csMap);
                    BlkImgDataSrc resampled = hd.createResampler(channels, csMap);
                    BlkImgDataSrc palettized = hd.createPalettizedColorSpaceMapper(resampled, csMap);
                    color = hd.createColorSpaceMapper(palettized, csMap);
                }
                catch (ArgumentException e)
                {
                    throw new ApplicationException("Could not instantiate ICC profiler.", e);
                }
                catch (ColorSpaceException e)
                {
                    throw new ApplicationException("Error processing ColorSpace information.", e);
                }
            }
            else
            { // Skip colorspace mapping
                color = ictransf;
            }

            // This is the last image in the decoding chain and should be
            // assigned by the last transformation:
            BlkImgDataSrc decodedImage = color;
            if (color == null)
            {
                decodedImage = ictransf;
            }
            int numComps = decodedImage.NumComps;

            int bytesPerPixel = (numComps == 4 ? 4 : 3);

            // **** Copy to Bitmap ****
            PixelFormat pixelFormat;
            switch (numComps)
            {
                case 1:
                    pixelFormat = PixelFormat.Format24bppRgb; break;
                case 3:
                    pixelFormat = PixelFormat.Format24bppRgb; break;
                case 4:
                    pixelFormat = PixelFormat.Format32bppArgb; break;
                default:
                    throw new ApplicationException("Unsupported PixelFormat.  " + numComps + " components.");
            }

            Bitmap dst = new Bitmap(decodedImage.ImgWidth, decodedImage.ImgHeight, pixelFormat);

            Coord numTiles = decodedImage.getNumTiles(null);

            int tIdx = 0;

            for (int y = 0; y < numTiles.y; y++)
            {
                // Loop on horizontal tiles
                for (int x = 0; x < numTiles.x; x++, tIdx++)
                {
                    decodedImage.setTile(x, y);

                    int height = decodedImage.getTileCompHeight(tIdx, 0);
                    int width = decodedImage.getTileCompWidth(tIdx, 0);

                    int tOffx = decodedImage.getCompULX(0) -
                        (int)Math.Ceiling(decodedImage.ImgULX /
                           (double)decodedImage.getCompSubsX(0));

                    int tOffy = decodedImage.getCompULY(0) -
                        (int)Math.Ceiling(decodedImage.ImgULY /
                            (double)decodedImage.getCompSubsY(0));

                    DataBlkInt[] db = new DataBlkInt[numComps];
                    int[] ls = new int[numComps];
                    int[] mv = new int[numComps];
                    int[] fb = new int[numComps];
                    for (int i = 0; i < numComps; i++)
                    {
                        db[i] = new DataBlkInt();
                        ls[i] = 1 << (decodedImage.getNomRangeBits(0) - 1);
                        mv[i] = (1 << decodedImage.getNomRangeBits(0)) - 1;
                        fb[i] = decodedImage.getFixedPoint(0);
                    }
                    for (int l = 0; l < height; l++)
                    {
                        for (int i = numComps - 1; i >= 0; i--)
                        {
                            db[i].ulx = 0;
                            db[i].uly = l;
                            db[i].w = width;
                            db[i].h = 1;
                            decodedImage.getInternCompData(db[i], i);
                        }
                        int[] k = new int[numComps];
                        for (int i = numComps - 1; i >= 0; i--) k[i] = db[i].offset + width - 1;

                        byte[] rowvalues = new byte[width * bytesPerPixel];

                        for (int i = width - 1; i >= 0; i--)
                        {
                            int[] tmp = new int[numComps];
                            for (int j = numComps - 1; j >= 0; j--)
                            {
                                tmp[j] = (db[j].data_array[k[j]--] >> fb[j]) + ls[j];
                                tmp[j] = (tmp[j] < 0) ? 0 : ((tmp[j] > mv[j]) ? mv[j] : tmp[j]);

                                if (decodedImage.getNomRangeBits(j) != 8)
                                    tmp[j] = (int)Math.Round(((double)tmp[j] / Math.Pow(2D, (double)decodedImage.getNomRangeBits(j))) * 255D);

                            }
                            int offset = i * bytesPerPixel;
                            switch (numComps)
                            {
                                case 1:
                                    rowvalues[offset + 0] = (byte)tmp[0];
                                    rowvalues[offset + 1] = (byte)tmp[0];
                                    rowvalues[offset + 2] = (byte)tmp[0];
                                    break;
                                case 3:
                                    rowvalues[offset + 0] = (byte)tmp[2];
                                    rowvalues[offset + 1] = (byte)tmp[1];
                                    rowvalues[offset + 2] = (byte)tmp[0];
                                    break;
                                case 4:
                                    rowvalues[offset + 0] = (byte)tmp[3];
                                    rowvalues[offset + 1] = (byte)tmp[2];
                                    rowvalues[offset + 2] = (byte)tmp[1];
                                    rowvalues[offset + 3] = (byte)tmp[0];
                                    break;
                            }
                        }

                        BitmapData dstdata = dst.LockBits(
                            new System.Drawing.Rectangle(tOffx, tOffy + l, width, 1),
                            ImageLockMode.ReadWrite, pixelFormat);

                        IntPtr ptr = dstdata.Scan0;
                        System.Runtime.InteropServices.Marshal.Copy(rowvalues, 0, ptr, rowvalues.Length);
                        dst.UnlockBits(dstdata);
                    }
                }
            }
            return dst;
        }
Esempio n. 21
0
		/// <summary> Creates a HeaderDecoder instance and read in two passes the main header
		/// of the codestream. The first and last marker segments shall be
		/// respectively SOC and SOT.
		/// 
		/// </summary>
		/// <param name="ehs">The encoded header stream where marker segments are
		/// extracted.
		/// 
		/// </param>
		/// <param name="pl">The ParameterList object of the decoder
		/// 
		/// </param>
		/// <param name="hi">The HeaderInfo holding information found in marker segments
		/// 
		/// </param>
		/// <exception cref="IOException">If an I/O error occurs while reading from the
		/// encoded header stream.
		/// </exception>
		/// <exception cref="EOFException">If the end of the encoded header stream is
		/// reached before getting all the data.
		/// </exception>
		/// <exception cref="CorruptedCodestreamException">If invalid data is found in the
		/// codestream main header.
		/// 
		/// </exception>
		public HeaderDecoder(RandomAccessIO ehs, ParameterList pl, HeaderInfo hi)
		{
			
			this.hi = hi;
            // CONVERSION PROBLEM?
			//this.verbose = verbose;
			
			pl.checkList(OPT_PREFIX, ParameterList.toNameArray(pinfo));
			
			mainHeadOff = ehs.Pos;
			if (((short) ehs.readShort()) != CSJ2K.j2k.codestream.Markers.SOC)
			{
				throw new CorruptedCodestreamException("SOC marker segment not " + " found at the " + "beginning of the " + "codestream.");
			}
			
			// First Pass: Decode and store main header information until the SOT
			// marker segment is found
			nfMarkSeg = 0;
			do 
			{
				extractMainMarkSeg(ehs.readShort(), ehs);
			}
			while ((nfMarkSeg & SOT_FOUND) == 0); //Stop when SOT is found
			ehs.seek(ehs.Pos - 2); // Realign codestream on SOT marker
			
			// Second pass: Read each marker segment previously found
			readFoundMainMarkSeg();
		}
Esempio n. 22
0
		/// <summary> Constructs a new 'AnWTFilterSpec' for the specified number of
		/// components and tiles.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="qts">Quantization specifications
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public AnWTFilterSpec(int nt, int nc, byte type, QuantTypeSpec qts, ParameterList pl):base(nt, nc, type)
		{
			
			// Check parameters
			pl.checkList(AnWTFilter.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(AnWTFilter.ParameterInfo));
			
			System.String param = pl.getParameter("Ffilters");
			bool isFilterSpecified = true;
			
			// No parameter specified
			if (param == null)
			{
				isFilterSpecified = false;
				
				// If lossless compression, uses the reversible filters in each
				// tile-components 
				if (pl.getBooleanParameter("lossless"))
				{
					setDefault(parseFilters(REV_FILTER_STR));
					return ;
				}
				
				// If no filter is specified through the command-line, use
				// REV_FILTER_STR or NON_REV_FILTER_STR according to the
				// quantization type
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						switch (qts.getSpecValType(t, c))
						{
							
							case SPEC_DEF: 
								if (getDefault() == null)
								{
									if (pl.getBooleanParameter("lossless"))
										setDefault(parseFilters(REV_FILTER_STR));
									if (((System.String) qts.getDefault()).Equals("reversible"))
									{
										setDefault(parseFilters(REV_FILTER_STR));
									}
									else
									{
										setDefault(parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_DEF;
								break;
							
							case SPEC_COMP_DEF: 
								if (!isCompSpecified(c))
								{
									if (((System.String) qts.getCompDef(c)).Equals("reversible"))
									{
										setCompDef(c, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setCompDef(c, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_COMP_DEF;
								break;
							
							case SPEC_TILE_DEF: 
								if (!isTileSpecified(t))
								{
									if (((System.String) qts.getTileDef(t)).Equals("reversible"))
									{
										setTileDef(t, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setTileDef(t, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_TILE_DEF;
								break;
							
							case SPEC_TILE_COMP: 
								if (!isTileCompSpecified(t, c))
								{
									if (((System.String) qts.getTileCompVal(t, c)).Equals("reversible"))
									{
										setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
									}
									else
									{
										setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
									}
								}
								specValType[t][c] = SPEC_TILE_COMP;
								break;
							
							default: 
								throw new System.ArgumentException("Unsupported " + "specification " + "type");
							
						}
					}
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			AnWTFilter[][] filter;
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken();
				
				switch (word[0])
				{
					
					case 't': 
					// Tiles specification
					case 'T':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_TILE_DEF;
						break;
					
					case 'c': 
					// Components specification
					case 'C':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
							curSpecType = SPEC_TILE_COMP;
						else
							curSpecType = SPEC_COMP_DEF;
						break;
					
					case 'w': 
					// WT filters specification
					case 'W':  // WT filters specification
						if (pl.getBooleanParameter("lossless") && word.ToUpper().Equals("w9x7".ToUpper()))
						{
							throw new System.ArgumentException("Cannot use non " + "reversible " + "wavelet transform with" + " '-lossless' option");
						}
						
						filter = parseFilters(word);
						if (curSpecType == SPEC_DEF)
						{
							setDefault(filter);
						}
						else if (curSpecType == SPEC_TILE_DEF)
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
								if (tileSpec[i])
								{
									setTileDef(i, filter);
								}
						}
						else if (curSpecType == SPEC_COMP_DEF)
						{
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, filter);
								}
						}
						else
						{
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, filter);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
					
					default: 
						throw new System.ArgumentException("Bad construction for " + "parameter: " + word);
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, it takes
				// the default value defined in ParameterList
				if (ndefspec != 0)
				{
					if (((System.String) qts.getDefault()).Equals("reversible"))
						setDefault(parseFilters(REV_FILTER_STR));
					else
						setDefault(parseFilters(NON_REV_FILTER_STR));
				}
				else
				{
					// All tile-component have been specified, takes the first
					// tile-component value as default.
					setDefault(getTileCompVal(0, 0));
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
			
			// Check consistency between filter and quantization type
			// specification
			for (int t = nt - 1; t >= 0; t--)
			{
				for (int c = nc - 1; c >= 0; c--)
				{
					// Reversible quantization
					if (((System.String) qts.getTileCompVal(t, c)).Equals("reversible"))
					{
						// If filter is reversible, it is OK
						if (isReversible(t, c))
							continue;
						
						// If no filter has been defined, use reversible filter
						if (!isFilterSpecified)
						{
							setTileCompVal(t, c, parseFilters(REV_FILTER_STR));
						}
						else
						{
							// Non reversible filter specified -> Error
							throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "reversible " + "quantization. " + "Specify '-Qtype " + "expounded' or " + "'-Qtype derived'" + "in " + "the command line.");
						}
					}
					else
					{
						// No reversible quantization
						// No reversible filter -> OK
						if (!isReversible(t, c))
							continue;
						
						// If no filter has been specified, use non-reversible
						// filter
						if (!isFilterSpecified)
						{
							setTileCompVal(t, c, parseFilters(NON_REV_FILTER_STR));
						}
						else
						{
							// Reversible filter specified -> Error
							throw new System.ArgumentException("Filter of " + "tile-component" + " (" + t + "," + c + ") does" + " not allow " + "non-reversible " + "quantization. " + "Specify '-Qtype " + "reversible' in " + "the command line");
						}
					}
				}
			}
		}
Esempio n. 23
0
		/// <summary> Creates and returns the entropy decoder corresponding to the
		/// information read from the codestream header and with the special
		/// additional parameters from the parameter list.
		/// 
		/// </summary>
		/// <param name="src">The bit stream reader agent where to get code-block data
		/// from.
		/// 
		/// </param>
		/// <param name="pl">The parameter list containing parameters applicable to the
		/// entropy decoder (other parameters can also be present).
		/// 
		/// </param>
		/// <returns> The entropy decoder
		/// 
		/// </returns>
		public virtual EntropyDecoder createEntropyDecoder(CodedCBlkDataSrcDec src, ParameterList pl)
		{
			bool doer;
			bool verber;
			int mMax;
			
			// Check parameters
			pl.checkList(EntropyDecoder.OPT_PREFIX, ParameterList.toNameArray(EntropyDecoder.ParameterInfo));
			// Get error detection option
			doer = pl.getBooleanParameter("Cer");
			// Get verbose error detection option
			verber = pl.getBooleanParameter("Cverber");
			
			// Get maximum number of bit planes from m quit condition
			mMax = pl.getIntParameter("m_quit");
			return new StdEntropyDecoder(src, decSpec, doer, verber, mMax);
		}
Esempio n. 24
0
		/// <summary> Constructs a new 'QuantTypeSpec' for the specified number of components
		/// and tiles and the arguments of "-Qtype" option. This constructor is
		/// called by the encoder.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="pl">The ParameterList
		/// 
		/// </param>
		public QuantTypeSpec(int nt, int nc, byte type, ParameterList pl):base(nt, nc, type)
		{
			
			System.String param = pl.getParameter("Qtype");
			if (param == null)
			{
				if (pl.getBooleanParameter("lossless"))
				{
					setDefault("reversible");
				}
				else
				{
					setDefault("expounded");
				}
				return ;
			}
			
			// Parse argument
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			System.String word; // current word
			byte curSpecValType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
			
			while (stk.HasMoreTokens())
			{
				word = stk.NextToken().ToLower();
				
				switch (word[0])
				{
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						
						if (curSpecValType == SPEC_COMP_DEF)
						{
							curSpecValType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecValType = SPEC_TILE_DEF;
						}
						break;
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						
						if (curSpecValType == SPEC_TILE_DEF)
						{
							curSpecValType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecValType = SPEC_COMP_DEF;
						}
						break;
					
					case 'r': 
					// reversible specification
					case 'd': 
					// derived quantization step size specification
					case 'e':  // expounded quantization step size specification
						if (!word.ToUpper().Equals("reversible".ToUpper()) && !word.ToUpper().Equals("derived".ToUpper()) && !word.ToUpper().Equals("expounded".ToUpper()))
						{
							throw new System.ArgumentException("Unknown parameter " + "for " + "'-Qtype' option: " + word);
						}
						
						if (pl.getBooleanParameter("lossless") && (word.ToUpper().Equals("derived".ToUpper()) || word.ToUpper().Equals("expounded".ToUpper())))
						{
							throw new System.ArgumentException("Cannot use non " + "reversible " + "quantization with " + "'-lossless' option");
						}
						
						if (curSpecValType == SPEC_DEF)
						{
							// Default specification
							setDefault(word);
						}
						else if (curSpecValType == SPEC_TILE_DEF)
						{
							// Tile default specification
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								if (tileSpec[i])
								{
									setTileDef(i, word);
								}
							}
						}
						else if (curSpecValType == SPEC_COMP_DEF)
						{
							// Component default specification 
							for (int i = compSpec.Length - 1; i >= 0; i--)
								if (compSpec[i])
								{
									setCompDef(i, word);
								}
						}
						else
						{
							// Tile-component specification
							for (int i = tileSpec.Length - 1; i >= 0; i--)
							{
								for (int j = compSpec.Length - 1; j >= 0; j--)
								{
									if (tileSpec[i] && compSpec[j])
									{
										setTileCompVal(i, j, word);
									}
								}
							}
						}
						
						// Re-initialize
						curSpecValType = SPEC_DEF;
						tileSpec = null;
						compSpec = null;
						break;
					
					
					default: 
						throw new System.ArgumentException("Unknown parameter for " + "'-Qtype' option: " + word);
					
				}
			}
			
			// Check that default value has been specified
			if (getDefault() == null)
			{
				int ndefspec = 0;
				for (int t = nt - 1; t >= 0; t--)
				{
					for (int c = nc - 1; c >= 0; c--)
					{
						if (specValType[t][c] == SPEC_DEF)
						{
							ndefspec++;
						}
					}
				}
				
				// If some tile-component have received no specification, the
				// quantization type is 'reversible' (if '-lossless' is specified)
				// or 'expounded' (if not). 
				if (ndefspec != 0)
				{
					if (pl.getBooleanParameter("lossless"))
					{
						setDefault("reversible");
					}
					else
					{
						setDefault("expounded");
					}
				}
				else
				{
					// All tile-component have been specified, takes arbitrarily
					// the first tile-component value as default and modifies the
					// specification type of all tile-component sharing this
					// value.
					setDefault(getTileCompVal(0, 0));
					
					switch (specValType[0][0])
					{
						
						case SPEC_TILE_DEF: 
							for (int c = nc - 1; c >= 0; c--)
							{
								if (specValType[0][c] == SPEC_TILE_DEF)
									specValType[0][c] = SPEC_DEF;
							}
							tileDef[0] = null;
							break;
						
						case SPEC_COMP_DEF: 
							for (int t = nt - 1; t >= 0; t--)
							{
								if (specValType[t][0] == SPEC_COMP_DEF)
									specValType[t][0] = SPEC_DEF;
							}
							compDef[0] = null;
							break;
						
						case SPEC_TILE_COMP: 
							specValType[0][0] = SPEC_DEF;
							tileCompVal["t0c0"] = null;
							break;
						}
				}
			}
		}
Esempio n. 25
0
		/// <summary> Creates and returns the ROIDeScaler corresponding to the information
		/// read from the codestream header and with the special additional
		/// parameters from the parameter list.
		/// 
		/// </summary>
		/// <param name="src">The bit stream reader agent where to get code-block data
		/// from.
		/// 
		/// </param>
		/// <param name="pl">The parameter list containing parameters applicable to the
		/// entropy decoder (other parameters can also be present).
		/// 
		/// </param>
		/// <param name="decSpec2">The DecoderSpecs instance after any image manipulation.
		/// 
		/// </param>
		/// <returns> The ROI descaler.
		/// 
		/// </returns>
		public virtual ROIDeScaler createROIDeScaler(CBlkQuantDataSrcDec src, ParameterList pl, DecoderSpecs decSpec2)
		{
			return ROIDeScaler.createInstance(src, pl, decSpec2);
		}
Esempio n. 26
0
		/// <summary> Creates a EntropyCoder object for the appropriate entropy coding
		/// parameters in the parameter list 'pl', and having 'src' as the source
		/// of quantized data.
		/// 
		/// </summary>
		/// <param name="src">The source of data to be entropy coded
		/// 
		/// </param>
		/// <param name="pl">The parameter list (or options).
		/// 
		/// </param>
		/// <param name="cbks">Code-block size specifications
		/// 
		/// </param>
		/// <param name="pss">Precinct partition specifications
		/// 
		/// </param>
		/// <param name="bms">By-pass mode specifications
		/// 
		/// </param>
		/// <param name="mqrs">MQ-reset specifications
		/// 
		/// </param>
		/// <param name="rts">Regular termination specifications
		/// 
		/// </param>
		/// <param name="css">Causal stripes specifications
		/// 
		/// </param>
		/// <param name="sss">Error resolution segment symbol use specifications
		/// 
		/// </param>
		/// <param name="lcs">Length computation specifications
		/// 
		/// </param>
		/// <param name="tts">Termination type specifications
		/// 
		/// </param>
		/// <exception cref="IllegalArgumentException">If an error occurs while parsing
		/// the options in 'pl'
		/// 
		/// </exception>
		public static EntropyCoder createInstance(CBlkQuantDataSrcEnc src, ParameterList pl, CBlkSizeSpec cblks, PrecinctSizeSpec pss, StringSpec bms, StringSpec mqrs, StringSpec rts, StringSpec css, StringSpec sss, StringSpec lcs, StringSpec tts)
		{
			// Check parameters
			pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo));
			return new StdEntropyCoder(src, cblks, pss, bms, mqrs, rts, css, sss, lcs, tts);
		}
Esempio n. 27
0
		/// <summary> Initialize all members with the given number of tiles and components
		/// and the command-line arguments stored in a ParameterList instance
		/// 
		/// </summary>
		/// <param name="nt">Number of tiles
		/// 
		/// </param>
		/// <param name="nc">Number of components
		/// 
		/// </param>
		/// <param name="imgsrc">The image source (used to get the image size)
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		public EncoderSpecs(int nt, int nc, BlkImgDataSrc imgsrc, ParameterList pl)
		{
			nTiles = nt;
			nComp = nc;
			
			// ROI
			rois = new MaxShiftSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP);
			
			// Quantization
			pl.checkList(Quantizer.OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(Quantizer.ParameterInfo));
			qts = new QuantTypeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl);
			qsss = new QuantStepSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl);
			gbs = new GuardBitsSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl);
			
			// Wavelet transform
			wfs = new AnWTFilterSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, qts, pl);
			dls = new IntegerSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl, "Wlev");
			
			// Component transformation
			cts = new ForwCompTransfSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, wfs, pl);
			
			// Entropy coder
			System.String[] strLcs = new System.String[]{"near_opt", "lazy_good", "lazy"};
			lcs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Clen_calc", strLcs, pl);
			System.String[] strTerm = new System.String[]{"near_opt", "easy", "predict", "full"};
			tts = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cterm_type", strTerm, pl);
			System.String[] strBoolean = new System.String[]{"on", "off"};
			sss = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cseg_symbol", strBoolean, pl);
			css = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Ccausal", strBoolean, pl);
			rts = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cterminate", strBoolean, pl);
			mqrs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "CresetMQ", strBoolean, pl);
			bms = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, "Cbypass", strBoolean, pl);
			cblks = new CBlkSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, pl);
			
			// Precinct partition
			pss = new PrecinctSizeSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE_COMP, imgsrc, dls, pl);
			
			// Codestream
			sops = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, "Psop", strBoolean, pl);
			ephs = new StringSpec(nt, nc, ModuleSpec.SPEC_TYPE_TILE, "Peph", strBoolean, pl);
		}
Esempio n. 28
0
		/// <summary> Creates a new PrecinctSizeSpec object for the specified number of tiles
		/// and components and the ParameterList instance.
		/// 
		/// </summary>
		/// <param name="nt">The number of tiles
		/// 
		/// </param>
		/// <param name="nc">The number of components
		/// 
		/// </param>
		/// <param name="type">the type of the specification module i.e. tile specific,
		/// component specific or both.
		/// 
		/// </param>
		/// <param name="imgsrc">The image source (used to get the image size)
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance
		/// 
		/// </param>
		public PrecinctSizeSpec(int nt, int nc, byte type, BlkImgDataSrc imgsrc, IntegerSpec dls, ParameterList pl):base(nt, nc, type)
		{
			
			this.dls = dls;
			
			// The precinct sizes are stored in a 2 elements vector array, the
			// first element containing a vector for the precincts width for each
			// resolution level and the second element containing a vector for the
			// precincts height for each resolution level. The precincts sizes are
			// specified from the highest resolution level to the lowest one
			// (i.e. 0).  If there are less elements than the number of
			// decomposition levels, the last element is used for all remaining
			// resolution levels (i.e. if the precincts sizes are specified only
			// for resolutions levels 5, 4 and 3, then the precincts size for
			// resolution levels 2, 1 and 0 will be the same as the size used for
			// resolution level 3).
			
			// Boolean used to know if we were previously reading a precinct's 
			// size or if we were reading something else.
			bool wasReadingPrecinctSize = false;
			
			System.String param = pl.getParameter(optName);
			
			// Set precinct sizes to default i.e. 2^15 =
			// Markers.PRECINCT_PARTITION_DEF_SIZE
			System.Collections.ArrayList[] tmpv = new System.Collections.ArrayList[2];
			tmpv[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx
			tmpv[0].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
			tmpv[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy
			tmpv[1].Add((System.Int32) CSJ2K.j2k.codestream.Markers.PRECINCT_PARTITION_DEF_SIZE);
			setDefault(tmpv);
			
			if (param == null)
			{
				// No precinct size specified in the command line so we do not try 
				// to parse it.
				return ;
			}
			
			// Precinct partition is used : parse arguments
			SupportClass.Tokenizer stk = new SupportClass.Tokenizer(param);
			byte curSpecType = SPEC_DEF; // Specification type of the
			// current parameter
			bool[] tileSpec = null; // Tiles concerned by the specification
			bool[] compSpec = null; // Components concerned by the specification
            int ci, ti; //i, xIdx removed
			
			bool endOfParamList = false;
			System.String word = null; // current word
			System.Int32 w, h;
			System.String errMsg = null;
			
			while ((stk.HasMoreTokens() || wasReadingPrecinctSize) && !endOfParamList)
			{
				
				System.Collections.ArrayList[] v = new System.Collections.ArrayList[2]; // v[0] : ppx, v[1] : ppy
				
				// We do not read the next token if we were reading a precinct's
				// size argument as we have already read the next token into word.
				if (!wasReadingPrecinctSize)
				{
					word = stk.NextToken();
				}
				
				wasReadingPrecinctSize = false;
				
				switch (word[0])
				{
					
					
					case 't':  // Tiles specification
						tileSpec = parseIdx(word, nTiles);
						if (curSpecType == SPEC_COMP_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_TILE_DEF;
						}
						break;
					
					
					case 'c':  // Components specification
						compSpec = parseIdx(word, nComp);
						if (curSpecType == SPEC_TILE_DEF)
						{
							curSpecType = SPEC_TILE_COMP;
						}
						else
						{
							curSpecType = SPEC_COMP_DEF;
						}
						break;
					
					
					default: 
						if (!System.Char.IsDigit(word[0]))
						{
							errMsg = "Bad construction for parameter: " + word;
							throw new System.ArgumentException(errMsg);
						}
						
						// Initialises Vector objects
						v[0] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppx
						v[1] = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); // ppy
						
						while (true)
						{
							
							// Now get the precinct dimensions
							try
							{
								// Get precinct width
								w = System.Int32.Parse(word);
								
								// Get next word in argument list
								try
								{
									word = stk.NextToken();
								}
								catch (System.ArgumentOutOfRangeException)
								{
									errMsg = "'" + optName + "' option : could not " + "parse the precinct's width";
									throw new System.ArgumentException(errMsg);
								}
								// Get precinct height
								h = System.Int32.Parse(word);
								if (w != (1 << MathUtil.log2(w)) || h != (1 << MathUtil.log2(h)))
								{
									errMsg = "Precinct dimensions must be powers of 2";
									throw new System.ArgumentException(errMsg);
								}
							}
							catch (System.FormatException)
							{
								errMsg = "'" + optName + "' option : the argument '" + word + "' could not be parsed.";
								throw new System.ArgumentException(errMsg);
							}
							// Store packet's dimensions in Vector arrays
							v[0].Add(w);
							v[1].Add(h);
							
							// Try to get the next token
							if (stk.HasMoreTokens())
							{
								word = stk.NextToken();
								if (!System.Char.IsDigit(word[0]))
								{
									// The next token does not start with a digit so
									// it is not a precinct's size argument. We set
									// the wasReadingPrecinctSize booleen such that we
									// know that we don't have to read another token
									// and check for the end of the parameters list.
									wasReadingPrecinctSize = true;
									
									if (curSpecType == SPEC_DEF)
									{
										setDefault(v);
									}
									else if (curSpecType == SPEC_TILE_DEF)
									{
										for (ti = tileSpec.Length - 1; ti >= 0; ti--)
										{
											if (tileSpec[ti])
											{
												setTileDef(ti, v);
											}
										}
									}
									else if (curSpecType == SPEC_COMP_DEF)
									{
										for (ci = compSpec.Length - 1; ci >= 0; ci--)
										{
											if (compSpec[ci])
											{
												setCompDef(ci, v);
											}
										}
									}
									else
									{
										for (ti = tileSpec.Length - 1; ti >= 0; ti--)
										{
											for (ci = compSpec.Length - 1; ci >= 0; ci--)
											{
												if (tileSpec[ti] && compSpec[ci])
												{
													setTileCompVal(ti, ci, v);
												}
											}
										}
									}
									// Re-initialize
									curSpecType = SPEC_DEF;
									tileSpec = null;
									compSpec = null;
									
									// Go back to 'normal' parsing
									break;
								}
								else
								{
									// Next token starts with a digit so read it
								}
							}
							else
							{
								// We have reached the end of the parameters list so
								// we store the last precinct's sizes and we stop
								if (curSpecType == SPEC_DEF)
								{
									setDefault(v);
								}
								else if (curSpecType == SPEC_TILE_DEF)
								{
									for (ti = tileSpec.Length - 1; ti >= 0; ti--)
									{
										if (tileSpec[ti])
										{
											setTileDef(ti, v);
										}
									}
								}
								else if (curSpecType == SPEC_COMP_DEF)
								{
									for (ci = compSpec.Length - 1; ci >= 0; ci--)
									{
										if (compSpec[ci])
										{
											setCompDef(ci, v);
										}
									}
								}
								else
								{
									for (ti = tileSpec.Length - 1; ti >= 0; ti--)
									{
										for (ci = compSpec.Length - 1; ci >= 0; ci--)
										{
											if (tileSpec[ti] && compSpec[ci])
											{
												setTileCompVal(ti, ci, v);
											}
										}
									}
								}
								endOfParamList = true;
								break;
							}
						} // while (true)
						break;
					
				} // switch
			} // while
		}
Esempio n. 29
0
		/// <summary> Constructs a new ForwCompTransf object that operates on the
		/// specified source of image data.
		/// 
		/// </summary>
		/// <param name="imgSrc">The source from where to get the data to be
		/// transformed
		/// 
		/// </param>
		/// <param name="decSpec">The decoder specifications
		/// 
		/// </param>
		/// <param name="utdepth">The bit depth of the un-transformed components 
		/// 
		/// </param>
		/// <param name="pl">The command line optinons of the decoder
		/// 
		/// </param>
		/// <seealso cref="BlkImgDataSrc">
		/// 
		/// </seealso>
		public InvCompTransf(BlkImgDataSrc imgSrc, DecoderSpecs decSpec, int[] utdepth, ParameterList pl):base(imgSrc)
		{
			this.cts = decSpec.cts;
			this.wfs = decSpec.wfs;
			src = imgSrc;
			this.utdepth = utdepth;
			noCompTransf = !(pl.getBooleanParameter("comp_transf"));
		}
		/// <summary> Reads all tiles headers and keep offset of their first
		/// packet. Finally it calls the rate allocation method.
		/// 
		/// </summary>
		/// <param name="hd">HeaderDecoder of the codestream.
		/// 
		/// </param>
		/// <param name="ehs">The input stream where to read bit-stream.
		/// 
		/// </param>
		/// <param name="decSpec">The decoder specifications 
		/// 
		/// </param>
		/// <param name="pl">The ParameterList instance created from the
		/// command-line arguments.
		/// 
		/// </param>
		/// <param name="cdstrInfo">Whether or not to print information found in
		/// codestream. 
		/// 
		/// </param>
		/// <seealso cref="allocateRate">
		/// 
		/// </seealso>
		public FileBitstreamReaderAgent(HeaderDecoder hd, RandomAccessIO ehs, DecoderSpecs decSpec, ParameterList pl, bool cdstrInfo, HeaderInfo hi):base(hd, decSpec)
		{
			
			this.pl = pl;
			this.printInfo = cdstrInfo;
			this.hi = hi;
			
			// Check whether quit conditiosn used
			usePOCQuit = pl.getBooleanParameter("poc_quit");
			
			// Get decoding rate
			bool rateInBytes;
			bool parsing = pl.getBooleanParameter("parsing");
			try
			{
				trate = pl.getFloatParameter("rate");
				if (trate == - 1)
				{
					trate = System.Single.MaxValue;
				}
			}
			catch (System.FormatException)
			{
				throw new System.ApplicationException("Invalid value in 'rate' option: " + pl.getParameter("rate"));
			}
			catch (System.ArgumentException)
			{
				throw new System.ApplicationException("'rate' option is missing");
			}
			
			try
			{
				tnbytes = pl.getIntParameter("nbytes");
			}
			catch (System.FormatException)
			{
				throw new System.ApplicationException("Invalid value in 'nbytes' option: " + pl.getParameter("nbytes"));
			}
			catch (System.ArgumentException)
			{
				throw new System.ApplicationException("'nbytes' option is missing");
			}
			
			// Check that '-rate' and '-nbytes' are not used at the same time
			ParameterList defaults = pl.DefaultParameterList;
			if (tnbytes != defaults.getFloatParameter("nbytes"))
			{
				rateInBytes = true;
			}
			else
			{
				rateInBytes = false;
			}
			
			if (rateInBytes)
			{
				trate = tnbytes * 8f / hd.MaxCompImgWidth / hd.MaxCompImgHeight;
			}
			else
			{
				//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
				tnbytes = (int) (trate * hd.MaxCompImgWidth * hd.MaxCompImgHeight) / 8;
                if (tnbytes < 0) tnbytes = int.MaxValue;
			}
			isTruncMode = !pl.getBooleanParameter("parsing");
			
			// Check if quit conditions are being used
			int ncbQuit;
			try
			{
				ncbQuit = pl.getIntParameter("ncb_quit");
			}
			catch (System.FormatException)
			{
				throw new System.ApplicationException("Invalid value in 'ncb_quit' option: " + pl.getParameter("ncb_quit"));
			}
			catch (System.ArgumentException)
			{
				throw new System.ApplicationException("'ncb_quit' option is missing");
			}
			if (ncbQuit != - 1 && !isTruncMode)
			{
				throw new System.ApplicationException("Cannot use -parsing and -ncb_quit condition at " + "the same time.");
			}
			
			try
			{
				lQuit = pl.getIntParameter("l_quit");
			}
			catch (System.FormatException)
			{
				throw new System.ApplicationException("Invalid value in 'l_quit' option: " + pl.getParameter("l_quit"));
			}
			catch (System.ArgumentException)
			{
				throw new System.ApplicationException("'l_quit' option is missing");
			}
			
			// initializations
			in_Renamed = ehs;
			pktDec = new PktDecoder(decSpec, hd, ehs, this, isTruncMode, ncbQuit);
			
			tileParts = new int[nt];
			totTileLen = new int[nt];
			tilePartLen = new int[nt][];
			tilePartNum = new int[nt][];
			firstPackOff = new int[nt][];
			tilePartsRead = new int[nt];
			totTileHeadLen = new int[nt];
			tilePartHeadLen = new int[nt][];
			nBytes = new int[nt];
			baknBytes = new int[nt];
			hd.nTileParts = new int[nt];
			
            // CONVERSION PROBLEM?
			//this.isTruncMode = isTruncMode;
			int t = 0, pos, tp = 0, tptot = 0;
			
			// Keeps main header's length, takes file format overhead into account
			int cdstreamStart = hd.mainHeadOff; // Codestream offset in the file
			mainHeadLen = in_Renamed.Pos - cdstreamStart;
			headLen = mainHeadLen;
			
			// If ncb and lbody quit conditions are used, headers are not counted
			if (ncbQuit == - 1)
			{
				anbytes = mainHeadLen;
			}
			else
			{
				anbytes = 0;
			}
			
			// If cannot even read the first tile-part
			if (anbytes > tnbytes)
			{
				throw new System.ApplicationException("Requested bitrate is too small.");
			}
			
			// Read all tile-part headers from all tiles.
			int tilePartStart;
			bool rateReached = false;
			int mdl;
			//int numtp = 0;
			totAllTileLen = 0;
			remainingTileParts = nt; // at least as many tile-parts as tiles
			int maxTP = nt; // If maximum 1 tile part per tile specified
			
			try
			{
				while (remainingTileParts != 0)
				{
					
					tilePartStart = in_Renamed.Pos;
					// Read tile-part header
					try
					{
						t = readTilePartHeader();
						if (isEOCFound)
						{
							// Some tiles are missing but the
							// codestream is OK
							break;
						}
						tp = tilePartsRead[t];
						if (isPsotEqualsZero)
						{
							// Psot may equals zero for the
							// last tile-part: it is assumed that this tile-part
							// contain all data until EOC
							tilePartLen[t][tp] = in_Renamed.length() - 2 - tilePartStart;
						}
					}
					catch (System.IO.EndOfStreamException e)
					{
						firstPackOff[t][tp] = in_Renamed.length();
						throw e;
					}
					
					pos = in_Renamed.Pos;
					
					// In truncation mode, if target decoding rate is reached in
					// tile-part header, skips the tile-part and stop reading
					// unless the ncb and lbody quit condition is in use
					if (isTruncMode && ncbQuit == - 1)
					{
						if ((pos - cdstreamStart) > tnbytes)
						{
							firstPackOff[t][tp] = in_Renamed.length();
							rateReached = true;
							break;
						}
					}
					
					// Set tile part position and header length
					firstPackOff[t][tp] = pos;
					tilePartHeadLen[t][tp] = (pos - tilePartStart);
					
					// Update length counters
					totTileLen[t] += tilePartLen[t][tp];
					totTileHeadLen[t] += tilePartHeadLen[t][tp];
					totAllTileLen += tilePartLen[t][tp];
					if (isTruncMode)
					{
						if (anbytes + tilePartLen[t][tp] > tnbytes)
						{
							anbytes += tilePartHeadLen[t][tp];
							headLen += tilePartHeadLen[t][tp];
							rateReached = true;
							nBytes[t] += (tnbytes - anbytes);
							break;
						}
						else
						{
							anbytes += tilePartHeadLen[t][tp];
							headLen += tilePartHeadLen[t][tp];
							nBytes[t] += (tilePartLen[t][tp] - tilePartHeadLen[t][tp]);
						}
					}
					else
					{
						if (anbytes + tilePartHeadLen[t][tp] > tnbytes)
						{
							break;
						}
						else
						{
							anbytes += tilePartHeadLen[t][tp];
							headLen += tilePartHeadLen[t][tp];
						}
					}
					
					// If this is first tile-part, remember header length
					if (tptot == 0)
						firstTilePartHeadLen = tilePartHeadLen[t][tp];
					
					// Go to the beginning of next tile part
					tilePartsRead[t]++;
					in_Renamed.seek(tilePartStart + tilePartLen[t][tp]);
					remainingTileParts--;
					maxTP--;
					tptot++;
					
					// If Psot of the current tile-part was equal to zero, it is
					// assumed that it contains all data until the EOC marker
					if (isPsotEqualsZero)
					{
						if (remainingTileParts != 0)
						{
							FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Some tile-parts have not " + "been found. The codestream may be corrupted.");
						}
						break;
					}
				}
			}
			catch (System.IO.EndOfStreamException)
			{
				if (printInfo)
				{
				}
				FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Codestream truncated in tile " + t);
				
				// Set specified rate to end of file if valid
				int fileLen = in_Renamed.length();
				if (fileLen < tnbytes)
				{
					tnbytes = fileLen;
					trate = tnbytes * 8f / hd.MaxCompImgWidth / hd.MaxCompImgHeight;
				}
				
				// Bit-rate allocation
				if (!isTruncMode)
				{
					allocateRate();
				}
				
				// Update 'res' value once all tile-part headers are read
				if (pl.getParameter("res") == null)
				{
					targetRes = decSpec.dls.Min;
				}
				else
				{
					try
					{
						targetRes = pl.getIntParameter("res");
						if (targetRes < 0)
						{
							throw new System.ArgumentException("Specified negative " + "resolution level " + "index: " + targetRes);
						}
					}
					catch (System.FormatException)
					{
						throw new System.ArgumentException("Invalid resolution level " + "index ('-res' option) " + pl.getParameter("res"));
					}
				}
				
				// Verify reduction in resolution level
				mdl = decSpec.dls.Min;
				if (targetRes > mdl)
				{
					FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Specified resolution level (" + targetRes + ") is larger" + " than the maximum value. Setting it to " + mdl + " (maximum value)");
					targetRes = mdl;
				}
				
				// Backup nBytes
				for (int tIdx = 0; tIdx < nt; tIdx++)
				{
					baknBytes[tIdx] = nBytes[tIdx];
				}
				
				return ;
			}
			remainingTileParts = 0;
			
			// Update 'res' value once all tile-part headers are read
			if (pl.getParameter("res") == null)
			{
				targetRes = decSpec.dls.Min;
			}
			else
			{
				try
				{
					targetRes = pl.getIntParameter("res");
					if (targetRes < 0)
					{
						throw new System.ArgumentException("Specified negative " + "resolution level index: " + targetRes);
					}
				}
				catch (System.FormatException)
				{
					throw new System.ArgumentException("Invalid resolution level " + "index ('-res' option) " + pl.getParameter("res"));
				}
			}
			
			// Verify reduction in resolution level
			mdl = decSpec.dls.Min;
			if (targetRes > mdl)
			{
				FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "Specified resolution level (" + targetRes + ") is larger" + " than the maximum possible. Setting it to " + mdl + " (maximum possible)");
				targetRes = mdl;
			}
			
			if (printInfo)
			{
			}
			
			// Check presence of EOC marker is decoding rate not reached or if
			// this marker has not been found yet
			if (!isEOCFound && !isPsotEqualsZero)
			{
				try
				{
                    short eocCheck = 0;
                    if (in_Renamed.Pos + sizeof(short) <= in_Renamed.length())
                        eocCheck = in_Renamed.readShort();

					if (!rateReached && !isPsotEqualsZero && eocCheck != CSJ2K.j2k.codestream.Markers.EOC)
					{
						FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "EOC marker not found. " + "Codestream is corrupted.");
					}
				}
				catch (System.IO.EndOfStreamException)
				{
					FacilityManager.getMsgLogger().printmsg(CSJ2K.j2k.util.MsgLogger_Fields.WARNING, "EOC marker is missing");
				}
			}
			
			// Bit-rate allocation
			if (!isTruncMode)
			{
				allocateRate();
			}
			else
			{
				// Take EOC into account if rate is not reached
				if (in_Renamed.Pos >= tnbytes)
					anbytes += 2;
			}
			
			// Backup nBytes
			for (int tIdx = 0; tIdx < nt; tIdx++)
			{
				baknBytes[tIdx] = nBytes[tIdx];
				if (printInfo)
				{
					FacilityManager.getMsgLogger().println("" + hi.toStringTileHeader(tIdx, tilePartLen[tIdx].Length), 2, 2);
				}
			}
		}
Esempio n. 31
0
 /// <summary> Constructs an empty ParameterList object with the provided default
 /// parameters. The list can be later updated by adding elements one by
 /// one, by loading them from a file, or by initializing them from an
 /// argument string.
 ///
 /// </summary>
 /// <param name="def">The defaults parameters
 ///
 /// </param>
 //UPGRADE_TODO: Format of property file may need to be changed. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1089'"
 //UPGRADE_ISSUE: Class hierarchy differences between 'java.util.Properties' and 'System.Collections.Specialized.NameValueCollection' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'"
 public ParameterList(ParameterList def) : base()
 {
     defaults = def;
 }