Esempio n. 1
0
        /// <summary>
        /// Reads the data from a binary file
        /// </summary>
        /// <param name="binaryReader">Binary reader.</param>
        public void ReadData(BufferedBinaryReader binaryReader)
        {
            this.signature = binaryReader.ReadString(3);
            this.version   = binaryReader.ReadByte();

            if (this.version > MAX_VERSION)
            {
                throw new InvalidSwfVersionException(this.version, MAX_VERSION);
            }

            this.fileSize = binaryReader.ReadUInt32();
            this.rect     = new Rect();
            this.rect.ReadData(binaryReader);
            binaryReader.SynchBits();
            this.fps    = binaryReader.ReadFloatWord(8, 8);
            this.frames = binaryReader.ReadUInt16();
        }
Esempio n. 2
0
        /// <summary>
        /// see <see cref="SwfDotNet.IO.Tags.BaseTag">base class</see>
        /// </summary>
        public override void ReadData(byte version, BufferedBinaryReader binaryReader)
        {
            RecordHeader rh = new RecordHeader();

            rh.ReadData(binaryReader);

            int tl = System.Convert.ToInt32(rh.TagLength);

            characterId = binaryReader.ReadUInt16();
            int imgLen = Convert.ToInt32(binaryReader.ReadUInt32());

            if (imgLen > 0)
            {
                jpegData  = binaryReader.ReadBytes(imgLen);
                alphaData = binaryReader.ReadBytes(tl - 6 - imgLen);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Inflate compressed swf
        /// </summary>
        private void Inflate()
        {
            // read size
            br.BaseStream.Position = 4;             // skip signature
            int size = Convert.ToInt32(br.ReadUInt32());

            // read swf head
            byte[] uncompressed = new byte[size];
            br.BaseStream.Position = 0;
            br.Read(uncompressed, 0, 8);           // header data is not compress

            // un-zip
            byte[] compressed = br.ReadBytes(size);
            uncompressed = DeflatorWraper.Decompress(compressed);

            // new memory stream for uncompressed swf
            MemoryStream m = new MemoryStream(uncompressed);

            br = new BufferedBinaryReader(m);
            br.BaseStream.Position = 0;
        }
Esempio n. 4
0
        internal MetadataRow(MetadataReader metadata, MetadataTable table, BufferedBinaryReader reader, int index)
        {
            Index = index;

            int n = table.Columns.Count;

            _cells = new MetadataCell[n];

            for (int i = 0; i < n; i++)
            {
                var column = table.Columns[i];
                Debug.Assert(column.Size != 0);

                uint value = column.Size == 2 ? reader.ReadUInt16() : reader.ReadUInt32();
                if (column.Type == ColumnType.CodedIndex)
                {
                    value = column.CodedIndex.Decode(value);
                }

                _cells[i] = new MetadataCell(metadata, column, value);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// see <see cref="SwfDotNet.IO.Tags.BaseTag">base class</see>
        /// </summary>
        public override void ReadData(byte version, BufferedBinaryReader binaryReader)
        {
            RecordHeader rh = new RecordHeader();

            rh.ReadData(binaryReader);

            soundId = binaryReader.ReadUInt16();

            soundFormat = binaryReader.ReadUBits(4);
            soundRate   = binaryReader.ReadUBits(2);
            soundSize   = binaryReader.ReadUBits(1);
            soundType   = binaryReader.ReadUBits(1);

            soundSampleCount = binaryReader.ReadUInt32();

            uint size = rh.TagLength - 2 - 1 - 4;

            soundData = new byte[size];
            for (uint i = 0; i < size; i++)
            {
                soundData[i] = binaryReader.ReadByte();
            }
        }
Esempio n. 6
0
        internal static BitmapSection BuildFrom(BufferedBinaryReader raf, long dataPointsNumber)
        {
            var length = raf.ReadUInt32();

            var section = raf.ReadUInt8();

            if (section != (int)SectionCode.BitmapSection)
            {
                throw new UnexpectedGribSectionException(
                          SectionCode.BitmapSection,
                          section
                          );
            }

            var bitmapIndicator = raf.ReadUInt8();
            var bitmapOffset    = raf.Position;

            // Skip through the bitmap data
            // There is no need to load it now
            raf.Skip((int)length - 6);

            return(new BitmapSection(length, section, bitmapIndicator, dataPointsNumber, bitmapOffset));
        }
        /// <summary>
        /// see <see cref="SwfDotNet.IO.Tags.BaseTag">base class</see>
        /// </summary>
        public override void ReadData(byte version, BufferedBinaryReader binaryReader)
        {
            RecordHeader rh = new RecordHeader();

            rh.ReadData(binaryReader);

            characterId = binaryReader.ReadUInt16();
            binaryReader.SynchBits();

            startBounds = new Rect();
            startBounds.ReadData(binaryReader);

            binaryReader.SynchBits();
            endBounds = new Rect();
            endBounds.ReadData(binaryReader);
            binaryReader.SynchBits();

            offset = binaryReader.ReadUInt32();

            morphFillStyles = new MorphFillStyleCollection();
            morphFillStyles.ReadData(binaryReader);

            morphLineStyles = new MorphLineStyleCollection();
            morphLineStyles.ReadData(binaryReader);

            ShapeWithStyle.NumFillBits = (uint)morphFillStyles.Count;
            ShapeWithStyle.NumLineBits = (uint)morphLineStyles.Count;

            startEdges = new ShapeRecordCollection();
            startEdges.ReadData(binaryReader, ShapeType.None);

            ShapeWithStyle.NumFillBits = (uint)morphFillStyles.Count;
            ShapeWithStyle.NumLineBits = (uint)morphLineStyles.Count;

            endEdges = new ShapeRecordCollection();
            endEdges.ReadData(binaryReader, ShapeType.None);
        }
Esempio n. 8
0
        internal static DataSection BuildFrom(BufferedBinaryReader reader)
        {
            // octets 1-4 (Length of DS)
            var length = reader.ReadUInt32();

            // octet 5  section 7
            var section = reader.ReadUInt8();

            if (section != (int)SectionCode.DataSection)
            {
                throw new UnexpectedGribSectionException(
                          SectionCode.DataSection,
                          section
                          );
            }

            var dataOffset = reader.Position;

            var dataLength = length - 5;

            reader.Skip((int)dataLength);

            return(new DataSection(length, section, dataOffset, dataLength));
        }
Esempio n. 9
0
        internal static ProductDefinitionSection BuildFrom(BufferedBinaryReader reader, Discipline discipline)
        {
            var currentPosition = reader.Position;

            // octets 1-4 (Length of PDS)
            var length = reader.ReadUInt32();

            // octet 5
            var section = reader.ReadUInt8();

            // octet 6-7
            var coordinates = reader.ReadUInt16();

            // octet 8-9
            var productDefinitionTemplateNumber = reader.ReadUInt16();

            var productDefinition = ProductDefinitionFactories.Build(reader, productDefinitionTemplateNumber, discipline);

            // Prevent from over-reading the stream
            reader.Seek(currentPosition + length, SeekOrigin.Begin);

            return(new ProductDefinitionSection(length, section, coordinates, productDefinitionTemplateNumber,
                                                productDefinition));
        }
        internal GaussianLatLonGridDefinition(BufferedBinaryReader reader) : base(reader)
        {
            Angle             = reader.ReadUInt32();
            Subdivisionsangle = reader.ReadUInt32();
            if (Angle == 0)
            {
                Ratio = 1e-6;
            }
            else
            {
                Ratio = Angle / (double)Subdivisionsangle;
            }

            La1        = reader.ReadInt32() * Ratio;
            Lo1        = reader.ReadInt32() * Ratio;
            Resolution = reader.ReadUInt8();
            La2        = reader.ReadUInt32() * Ratio;
            Lo2        = reader.ReadUInt32() * Ratio;
            Dx         = reader.ReadUInt32() * Ratio;
            N          = reader.ReadUInt32();
            ScanMode   = reader.ReadUInt8();
        }
 private protected GridPointEarthGridDefinition(BufferedBinaryReader reader) : base(reader)
 {
     La1        = reader.ReadInt32() * 1e-6;
     Lo1        = reader.ReadUInt32() * 1e-6;
     Resolution = reader.ReadUInt8();
 }
Esempio n. 12
0
        /// <summary>
        /// see <see cref="SwfDotNet.IO.Tags.BaseTag">base class</see>
        /// </summary>
        public override void ReadData(byte version, BufferedBinaryReader binaryReader)
        {
            RecordHeader rh = new RecordHeader();

            rh.ReadData(binaryReader);

            fontId = binaryReader.ReadUInt16();

            bool fontFlagsHasLayout = binaryReader.ReadBoolean();

            fontFlagsShiftJIS  = binaryReader.ReadBoolean();
            fontFlagsSmallText = binaryReader.ReadBoolean();
            fontFlagsANSI      = binaryReader.ReadBoolean();
            bool fontFlagsWideOffsets = binaryReader.ReadBoolean();
            bool fontFlagsWideCodes   = binaryReader.ReadBoolean();

            fontFlagsItalic = binaryReader.ReadBoolean();
            fontFlagsBold   = binaryReader.ReadBoolean();
            languageCode    = (LanguageCode)binaryReader.ReadByte();
            byte fontNameLength = binaryReader.ReadByte();

            fontName = binaryReader.ReadString(fontNameLength);

            ushort numGlyphs = binaryReader.ReadUInt16();

            if (numGlyphs > 0)
            {
                uint[] offsetTable = new uint[numGlyphs];
                for (int i = 0; i < numGlyphs; i++)
                {
                    if (fontFlagsWideOffsets)
                    {
                        offsetTable[i] = binaryReader.ReadUInt32();
                    }
                    else
                    {
                        offsetTable[i] = (uint)binaryReader.ReadUInt16();
                    }
                }
            }
            uint codeTableOffset = 0;

            if (fontFlagsWideOffsets)
            {
                codeTableOffset = binaryReader.ReadUInt32();
            }
            else
            {
                codeTableOffset = (uint)binaryReader.ReadUInt16();
            }

            if (numGlyphs > 0)
            {
                this.glyphShapesTable.IsWideCodes = fontFlagsWideCodes;
                this.glyphShapesTable.ReadData(binaryReader, numGlyphs);
            }

            if (fontFlagsHasLayout)
            {
                fontAscent  = binaryReader.ReadInt16();
                fontDescent = binaryReader.ReadInt16();
                fontLeading = binaryReader.ReadInt16();

                if (numGlyphs > 0)
                {
                    fontAdvanceTable.ReadData(binaryReader, numGlyphs);
                    fontBoundsTable.ReadData(binaryReader, numGlyphs);
                    fontKerningTable.ReadData(binaryReader, fontFlagsWideCodes);
                }
            }
        }
 internal RotatedGaussianLatLonGridDefinition(BufferedBinaryReader reader) : base(reader)
 {
     SpLat         = reader.ReadInt32() * Ratio;
     SpLon         = reader.ReadUInt32() * Ratio;
     Rotationangle = reader.ReadUInt32();
 }
Esempio n. 14
0
 internal RotatedSphericalHarmonicCoefficientsGridDefinition(BufferedBinaryReader reader) : base(reader)
 {
     SpLat         = reader.ReadInt32() * 1e-6f;
     SpLon         = reader.ReadUInt32() * 1e-6f;
     Rotationangle = reader.ReadUInt32();
 }
Esempio n. 15
0
        private void readPatterns(BufferedBinaryReader source, int nbPatterns)
        {
            byte                   firstByte;
            IList <Event>          aRow;
            IList <IList <Event> > aPattern;

            uint   headerLength;
            ushort nbRows;
            uint   packedDataSize;

            for (int i = 0; i < nbPatterns; i++)
            {
                aPattern = new List <IList <Event> >();

                headerLength = source.ReadUInt32();
                source.Seek(1, SeekOrigin.Current); // Packing type
                nbRows = source.ReadUInt16();

                packedDataSize = source.ReadUInt16();

                if (packedDataSize > 0) // The patterns is not empty
                {
                    for (int j = 0; j < nbRows; j++)
                    {
                        aRow = new List <Event>();

                        for (int k = 0; k < nbChannels; k++)
                        {
                            Event e = new Event();
                            e.Channel = k + 1;

                            firstByte = source.ReadByte();
                            if ((firstByte & 0x80) > 0) // Most Significant Byte (MSB) is set => packed data layout
                            {
                                if ((firstByte & 0x1) > 0)
                                {
                                    source.Seek(1, SeekOrigin.Current);                       // Note
                                }
                                if ((firstByte & 0x2) > 0)
                                {
                                    source.Seek(1, SeekOrigin.Current);                       // Instrument
                                }
                                if ((firstByte & 0x4) > 0)
                                {
                                    source.Seek(1, SeekOrigin.Current);                       // Volume
                                }
                                if ((firstByte & 0x8) > 0)
                                {
                                    e.Command = source.ReadByte();                                       // Effect type
                                }
                                if ((firstByte & 0x10) > 0)
                                {
                                    e.Info = source.ReadByte();                                          // Effect param
                                }
                            }
                            else     // No MSB set => standard data layout
                            // firstByte is the Note
                            {
                                source.Seek(1, SeekOrigin.Current); // Instrument
                                source.Seek(1, SeekOrigin.Current); // Volume
                                e.Command = source.ReadByte();
                                e.Info    = source.ReadByte();
                            }

                            aRow.Add(e);
                        }

                        aPattern.Add(aRow);
                    }
                }

                FPatterns.Add(aPattern);
            }
        }
Esempio n. 16
0
 internal RotatedLatLonGridDefinition(BufferedBinaryReader reader) : base(reader)
 {
     SpLat         = reader.ReadInt32() * 1e-6f;
     SpLon         = reader.ReadUInt32() * 1e-6f;
     Rotationangle = reader.ReadSingle();
 }
Esempio n. 17
0
		private object ReadValue(BufferedBinaryReader reader, IType type)
		{
			var st = type.SystemType();
			if (st != null)
			{
				switch (st.Code)
				{
					case SystemTypeCode.Boolean:
						return reader.ReadBoolean();
					case SystemTypeCode.Int8:
						return reader.ReadInt8();
					case SystemTypeCode.UInt8:
						return reader.ReadUInt8();
					case SystemTypeCode.Int16:
						return reader.ReadInt16();
					case SystemTypeCode.UInt16:
						return reader.ReadUInt16();
					case SystemTypeCode.Int32:
						return reader.ReadInt32();
					case SystemTypeCode.UInt32:
						return reader.ReadUInt32();
					case SystemTypeCode.Int64:
						return reader.ReadInt64();
					case SystemTypeCode.UInt64:
						return reader.ReadUInt64();
					case SystemTypeCode.Single:
						return reader.ReadSingle();
					case SystemTypeCode.Double:
						return reader.ReadDouble();
					case SystemTypeCode.Char:
						return reader.ReadChar();
					case SystemTypeCode.String:
						return reader.ReadCountedUtf8();
					case SystemTypeCode.Object:
						//boxed value type
						var e = (ElementType)reader.ReadInt8();
						return ReadValue(reader, e);
					case SystemTypeCode.Type:
						return ReadType(reader);
				}
			}

			if (type.TypeKind == TypeKind.Enum)
			{
				return ReadValue(reader, type.ValueType);
			}

			if (type.IsArray)
			{
				int numElem = reader.ReadInt32();
				Array arr = null;
				for (int i = 0; i < numElem; ++i)
				{
					var val = ReadValue(reader, type.ElementType);
					if (arr == null)
						arr = Array.CreateInstance(val.GetType(), numElem);
					arr.SetValue(val, i);
				}
				return arr;
			}

			return null;
		}
Esempio n. 18
0
        /// <summary>
        /// Загрузка базы данных в память
        /// </summary>
        /// <returns></returns>
        public void Load()
        {
            string      filePath = Path.Combine(_environment.ContentRootPath, _dbFileName);
            BinGeoModel binModel;

            using (FileStream stream = new FileStream(filePath, FileMode.Open))
            {
                Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();

                using (BufferedBinaryReader bufferedReader = new BufferedBinaryReader(stream, 65536))
                {
                    stopwatch.Start();

                    bufferedReader.FillBuffer();

                    int    version         = bufferedReader.ReadInt32();
                    byte[] nameBytes       = bufferedReader.Read(0, 32);
                    ulong  timestamp       = bufferedReader.ReadUInt64();
                    int    records         = bufferedReader.ReadInt32();
                    uint   offsetRanges    = bufferedReader.ReadUInt32();
                    uint   offsetCities    = bufferedReader.ReadUInt32();
                    uint   offsetLocations = bufferedReader.ReadUInt32();

                    binModel = new BinGeoModel(version, nameBytes, timestamp, records, offsetRanges, offsetCities, offsetLocations);

                    int currentIndex = 0;
                    binModel.IpRangeCollection = new BinIpRange[binModel.RecordsCount];
                    while (bufferedReader.FillBuffer() && currentIndex < binModel.RecordsCount)
                    {
                        for (; currentIndex < binModel.RecordsCount && bufferedReader.NumBytesAvailable >= IpRangeBytesCount; currentIndex++)
                        {
                            binModel.IpRangeCollection[currentIndex] = new BinIpRange()
                            {
                                IpFrom        = bufferedReader.ReadUInt32(),
                                IpTo          = bufferedReader.ReadUInt32(),
                                LocationIndex = bufferedReader.ReadUInt32()
                            };
                        }
                    }

                    currentIndex = 0;
                    binModel.LocationCollection = new BinLocation[binModel.RecordsCount];
                    while (bufferedReader.FillBuffer() && currentIndex < binModel.RecordsCount)
                    {
                        for (; currentIndex < binModel.RecordsCount && bufferedReader.NumBytesAvailable >= LocationBytesCount; currentIndex++)
                        {
                            byte[] country      = bufferedReader.Read(0, 8);
                            byte[] region       = bufferedReader.Read(0, 12);
                            byte[] postal       = bufferedReader.Read(0, 12);
                            byte[] city         = bufferedReader.Read(0, 24);
                            byte[] organization = bufferedReader.Read(0, 32);
                            float  latitude     = bufferedReader.ReadSingle();
                            float  longitude    = bufferedReader.ReadSingle();

                            binModel.LocationCollection[currentIndex] = new BinLocation(country, region, postal, city, organization, latitude, longitude);
                        }
                    }

                    currentIndex     = 0;
                    binModel.Indexes = new uint[binModel.RecordsCount];
                    while (bufferedReader.FillBuffer() && currentIndex < binModel.RecordsCount)
                    {
                        for (; currentIndex < binModel.RecordsCount && bufferedReader.NumBytesAvailable >= IndexBytesCount; currentIndex++)
                        {
                            binModel.Indexes[currentIndex] = bufferedReader.ReadUInt32();
                        }
                    }

                    stopwatch.Stop();
                    DatabaseLoadedTimeMs = stopwatch.ElapsedMilliseconds;
                    _logger.LogInformation($"Database loading time: {stopwatch.ElapsedMilliseconds} ms");
                }

                // Отображение объектов сущностей двоичной базы в объекты бизнес сущностей
                GeoModel = _mapper.Map <GeoModel>(binModel);
            }
        }
Esempio n. 19
0
 internal StretchedRotatedSphericalHarmonicCoefficientsGridDefinition(BufferedBinaryReader reader) : base(reader)
 {
     PoleLat = reader.ReadInt32() * 1e-6f;
     PoleLon = reader.ReadUInt32() * 1e-6f;
     Factor  = reader.ReadSingle();
 }
Esempio n. 20
0
		private object ReadValue(BufferedBinaryReader reader, ElementType e)
		{
			switch (e)
			{
				case ElementType.Boolean:
					return reader.ReadBoolean();

				case ElementType.Char:
					return reader.ReadChar();

				case ElementType.Int8:
					return reader.ReadSByte();

				case ElementType.UInt8:
					return reader.ReadByte();

				case ElementType.Int16:
					return reader.ReadInt16();

				case ElementType.UInt16:
					return reader.ReadUInt16();

				case ElementType.Int32:
					return reader.ReadInt32();

				case ElementType.UInt32:
					return reader.ReadUInt32();

				case ElementType.Int64:
					return reader.ReadInt64();

				case ElementType.UInt64:
					return reader.ReadUInt64();

				case ElementType.Single:
					return reader.ReadSingle();

				case ElementType.Double:
					return reader.ReadDouble();

				case ElementType.String:
					return reader.ReadCountedUtf8();

				case ElementType.Object:
				case ElementType.CustomArgsBoxedObject:
					{
						var elem = (ElementType)reader.ReadInt8();
						return ReadValue(reader, elem);
					}

				case ElementType.CustomArgsEnum:
					{
						string enumTypeName = reader.ReadCountedUtf8();
						var enumType = FindType(enumTypeName);
						if (enumType == null)
						{
							//TODO:
							throw new BadMetadataException();
						}
						return ReadValue(reader, enumType);
					}

				case ElementType.CustomArgsType:
					return ReadType(reader);

				case ElementType.ArraySz:
					{
						var arrElemType = (ElementType)reader.ReadInt8();
						return ReadArray(reader, arrElemType);
					}

				default:
					throw new ArgumentOutOfRangeException();
			}
		}
Esempio n. 21
0
 private static DataDirectory ReadDataDirectory(BufferedBinaryReader reader)
 {
     return(new DataDirectory(reader.ReadUInt32(), reader.ReadUInt32()));
 }
Esempio n. 22
0
        protected override Boolean read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams)
        {
            var result = true;

            UInt16 nbOrders      = 0;
            UInt16 nbPatterns    = 0;
            UInt16 nbSamples     = 0;
            UInt16 nbInstruments = 0;

            UInt16 flags;
            UInt16 special;
            UInt16 trackerVersion;
            UInt16 trackerVersionCompatibility;

            var useSamplesAsInstruments = false;

            UInt16 messageLength;
            UInt32 messageOffset;
            var    message = "";

            IList <UInt32> patternPointers    = new List <UInt32>();
            IList <UInt32> instrumentPointers = new List <UInt32>();
            IList <UInt32> samplePointers     = new List <UInt32>();

            resetData();
            var bSource = new BufferedBinaryReader(source.BaseStream);


            if (!IT_SIGNATURE.Equals(Utils.Latin1Encoding.GetString(bSource.ReadBytes(4))))
            {
                result = false;
                throw new Exception(sizeInfo.FileSize + " : Invalid IT file (file signature mismatch)"); // TODO - might be a compressed file -> PK header
            }

            tagExists = true;

            // Title = max first 26 chars after file signature; null-terminated
            var title = StreamUtils.ReadNullTerminatedStringFixed(bSource, Utils.Latin1Encoding, 26);

            if (readTagParams.PrepareForWriting)
            {
                structureHelper.AddZone(4, 26, new Byte[26] {
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                }, ZONE_TITLE);
            }
            tagData.IntegrateValue(TagData.TAG_FIELD_TITLE, title.Trim());
            bSource.Seek(2, SeekOrigin.Current); // Pattern row highlight information

            nbOrders      = bSource.ReadUInt16();
            nbInstruments = bSource.ReadUInt16();
            nbSamples     = bSource.ReadUInt16();
            nbPatterns    = bSource.ReadUInt16();

            trackerVersion = bSource.ReadUInt16();
            trackerVersionCompatibility = bSource.ReadUInt16();

            flags = bSource.ReadUInt16();

            useSamplesAsInstruments = !((flags & 0x04) > 0);

            special = bSource.ReadUInt16();

            //            trackerName = "Impulse tracker"; // TODO use TrackerVersion to add version

            bSource.Seek(2, SeekOrigin.Current); // globalVolume (8b), masterVolume (8b)

            initialSpeed = bSource.ReadByte();
            initialTempo = bSource.ReadByte();

            bSource.Seek(2, SeekOrigin.Current); // panningSeparation (8b), pitchWheelDepth (8b)

            messageLength = bSource.ReadUInt16();
            messageOffset = bSource.ReadUInt32();
            bSource.Seek(132, SeekOrigin.Current); // reserved (32b), channel Pan (64B), channel Vol (64B)

            // Orders table
            for (var i = 0; i < nbOrders; i++)
            {
                patternTable.Add(bSource.ReadByte());
            }

            // Instruments pointers
            for (var i = 0; i < nbInstruments; i++)
            {
                instrumentPointers.Add(bSource.ReadUInt32());
            }

            // Samples pointers
            for (var i = 0; i < nbSamples; i++)
            {
                samplePointers.Add(bSource.ReadUInt32());
            }

            // Patterns pointers
            for (var i = 0; i < nbPatterns; i++)
            {
                patternPointers.Add(bSource.ReadUInt32());
            }

            if ((!useSamplesAsInstruments) && (instrumentPointers.Count > 0))
            {
                if (trackerVersionCompatibility < 0x200)
                {
                    readInstrumentsOld(bSource, instrumentPointers);
                }
                else
                {
                    readInstruments(bSource, instrumentPointers);
                }
            }
            else
            {
                readSamples(bSource, samplePointers);
            }
            readPatterns(bSource, patternPointers);

            // IT Message
            if ((special & 0x1) > 0)
            {
                bSource.Seek(messageOffset, SeekOrigin.Begin);
                //message = new String( StreamUtils.ReadOneByteChars(source, messageLength) );
                message = StreamUtils.ReadNullTerminatedStringFixed(bSource, Utils.Latin1Encoding, messageLength);
            }


            // == Computing track properties

            duration = calculateDuration() * 1000.0;

            String commentStr;

            if (messageLength > 0) // Get Comment from the "IT message" field
            {
                commentStr = message;
            }
            else // Get Comment from all the instrument names (common practice in the tracker community)
            {
                var comment = new StringBuilder("");
                // NB : Whatever the value of useSamplesAsInstruments, FInstruments contain the right data
                foreach (var i in instruments)
                {
                    if (i.DisplayName.Length > 0)
                    {
                        comment.Append(i.DisplayName).Append(Settings.InternalValueSeparator);
                    }
                }
                if (comment.Length > 0)
                {
                    comment.Remove(comment.Length - 1, 1);
                }
                commentStr = comment.ToString();
            }
            tagData.IntegrateValue(TagData.TAG_FIELD_COMMENT, commentStr);

            bitrate = (Double)sizeInfo.FileSize / duration;

            return(result);
        }
Esempio n. 23
0
 internal StretchedRotatedGaussianLatLonGridDefinition(BufferedBinaryReader reader) : base(reader)
 {
     PoleLat = reader.ReadInt32() * Ratio;
     PoleLon = reader.ReadUInt32() * Ratio;
     Factor  = reader.ReadUInt32();
 }
Esempio n. 24
0
        private bool getInfo(BufferedBinaryReader source, FileInfo info, ReadTagParams readTagParams)
        {
            // Get info from file
            bool result        = false;
            bool isValidHeader = false;

            // Check for ID3v2 (NB : this case should not even exist since OGG has its own native tagging system, and is not deemed compatible with ID3v2 according to the ID3 FAQ)
            source.Seek(sizeInfo.ID3v2Size, SeekOrigin.Begin);

            // Read global file header
            info.IdentificationHeader.ReadFromStream(source);

            if (info.IdentificationHeader.IsValid())
            {
                source.Seek(sizeInfo.ID3v2Size + info.IdentificationHeader.Segments + 27, SeekOrigin.Begin); // 27 being the size from 'ID' to 'Segments'

                // Read Vorbis or Opus stream info
                long position = source.Position;

                String headerStart = Utils.Latin1Encoding.GetString(source.ReadBytes(3));
                source.Seek(position, SeekOrigin.Begin);
                if (VORBIS_HEADER_ID.StartsWith(headerStart))
                {
                    contents = CONTENTS_VORBIS;
                    info.VorbisParameters.ID = Utils.Latin1Encoding.GetString(source.ReadBytes(7));
                    isValidHeader            = VORBIS_HEADER_ID.Equals(info.VorbisParameters.ID);

                    info.VorbisParameters.BitstreamVersion = source.ReadBytes(4);
                    info.VorbisParameters.ChannelMode      = source.ReadByte();
                    info.VorbisParameters.SampleRate       = source.ReadInt32();
                    info.VorbisParameters.BitRateMaximal   = source.ReadInt32();
                    info.VorbisParameters.BitRateNominal   = source.ReadInt32();
                    info.VorbisParameters.BitRateMinimal   = source.ReadInt32();
                    info.VorbisParameters.BlockSize        = source.ReadByte();
                    info.VorbisParameters.StopFlag         = source.ReadByte();
                }
                else if (OPUS_HEADER_ID.StartsWith(headerStart))
                {
                    contents = CONTENTS_OPUS;
                    info.OpusParameters.ID = Utils.Latin1Encoding.GetString(source.ReadBytes(8));
                    isValidHeader          = OPUS_HEADER_ID.Equals(info.OpusParameters.ID);

                    info.OpusParameters.Version            = source.ReadByte();
                    info.OpusParameters.OutputChannelCount = source.ReadByte();
                    info.OpusParameters.PreSkip            = source.ReadUInt16();
                    //info.OpusParameters.InputSampleRate = source.ReadUInt32();
                    info.OpusParameters.InputSampleRate = 48000; // Actual sample rate is hardware-dependent. Let's assume for now that the hardware ATL runs on supports 48KHz
                    source.Seek(4, SeekOrigin.Current);
                    info.OpusParameters.OutputGain = source.ReadInt16();

                    info.OpusParameters.ChannelMappingFamily = source.ReadByte();

                    if (info.OpusParameters.ChannelMappingFamily > 0)
                    {
                        info.OpusParameters.StreamCount        = source.ReadByte();
                        info.OpusParameters.CoupledStreamCount = source.ReadByte();

                        info.OpusParameters.ChannelMapping = new byte[info.OpusParameters.OutputChannelCount];
                        for (int i = 0; i < info.OpusParameters.OutputChannelCount; i++)
                        {
                            info.OpusParameters.ChannelMapping[i] = source.ReadByte();
                        }
                    }
                }

                if (isValidHeader)
                {
                    info.CommentHeaderStart = source.Position;
                    IList <long> pagePos = new List <long>();

                    // Reads all related Vorbis pages that describe Comment and Setup headers
                    // and concatenate their content into a single, continuous data stream
                    bool loop  = true;
                    bool first = true;
                    using (MemoryStream s = new MemoryStream())
                    {
                        // Reconstruct the whole Comment header from OGG pages to a MemoryStream
                        while (loop)
                        {
                            info.SetupHeaderEnd              = source.Position; // When the loop stops, cursor is starting to read a brand new page located after Comment _and_ Setup headers
                            info.CommentHeader.ID            = Utils.Latin1Encoding.GetString(source.ReadBytes(4));
                            info.CommentHeader.StreamVersion = source.ReadByte();
                            info.CommentHeader.TypeFlag      = source.ReadByte();
                            // 0 marks a new page
                            if (0 == info.CommentHeader.TypeFlag)
                            {
                                loop = first;
                            }
                            if (loop)
                            {
                                info.CommentHeader.AbsolutePosition = source.ReadUInt64();
                                info.CommentHeader.Serial           = source.ReadInt32();
                                info.CommentHeader.PageNumber       = source.ReadInt32();
                                info.CommentHeader.Checksum         = source.ReadUInt32();
                                info.CommentHeader.Segments         = source.ReadByte();
                                info.CommentHeader.LacingValues     = source.ReadBytes(info.CommentHeader.Segments);
                                s.Write(source.ReadBytes(info.CommentHeader.GetPageLength()), 0, info.CommentHeader.GetPageLength());
                                pagePos.Add(info.SetupHeaderEnd);
                            }
                            first = false;
                        }

                        if (readTagParams.PrepareForWriting) // Metrics to prepare writing
                        {
                            if (pagePos.Count > 1)
                            {
                                source.Position = pagePos[pagePos.Count - 2];
                            }
                            else
                            {
                                source.Position = pagePos[0];
                            }

                            // Determine the boundaries of 3rd header (Setup header) by searching from last-but-one page
                            if (StreamUtils.FindSequence(source, Utils.Latin1Encoding.GetBytes(VORBIS_SETUP_ID)))
                            {
                                info.SetupHeaderStart = source.Position - VORBIS_SETUP_ID.Length;
                                info.CommentHeaderEnd = info.SetupHeaderStart;

                                if (pagePos.Count > 1)
                                {
                                    int firstSetupPage = -1;
                                    for (int i = 1; i < pagePos.Count; i++)
                                    {
                                        if (info.CommentHeaderEnd < pagePos[i])
                                        {
                                            info.CommentHeaderSpanPages = i - 1;
                                            firstSetupPage = i - 1;
                                        }
                                        if (info.SetupHeaderEnd < pagePos[i])
                                        {
                                            info.SetupHeaderSpanPages = i - firstSetupPage;
                                        }
                                    }
                                    /// Not found yet => comment header takes up all pages, and setup header is on the end of the last page
                                    if (-1 == firstSetupPage)
                                    {
                                        info.CommentHeaderSpanPages = pagePos.Count;
                                        info.SetupHeaderSpanPages   = 1;
                                    }
                                }
                                else
                                {
                                    info.CommentHeaderSpanPages = 1;
                                    info.SetupHeaderSpanPages   = 1;
                                }
                            }
                        }

                        // Get total number of samples
                        info.Samples = getSamples(source);

                        // Read metadata from the reconstructed Comment header inside the memoryStream
                        if (readTagParams.ReadTag)
                        {
                            BinaryReader msr = new BinaryReader(s);
                            s.Seek(0, SeekOrigin.Begin);

                            string tagId;
                            bool   isValidTagHeader = false;
                            if (contents.Equals(CONTENTS_VORBIS))
                            {
                                tagId            = Utils.Latin1Encoding.GetString(msr.ReadBytes(7));
                                isValidTagHeader = (VORBIS_TAG_ID.Equals(tagId));
                            }
                            else if (contents.Equals(CONTENTS_OPUS))
                            {
                                tagId            = Utils.Latin1Encoding.GetString(msr.ReadBytes(8));
                                isValidTagHeader = (OPUS_TAG_ID.Equals(tagId));
                            }

                            if (isValidTagHeader)
                            {
                                vorbisTag.Clear();
                                vorbisTag.Read(msr, readTagParams);
                            }
                        }
                    } // using MemoryStream

                    result = true;
                }
            }

            return(result);
        }
Esempio n. 25
0
 private protected XyEarthGridDefinition(BufferedBinaryReader reader) : base(reader)
 {
     Nx = reader.ReadUInt32();
     Ny = reader.ReadUInt32();
 }
Esempio n. 26
0
        protected override bool read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams)
        {
            bool result = true;

            ushort nbPatterns    = 0;
            ushort nbInstruments = 0;

            ushort trackerVersion;

            uint headerSize = 0;
            uint songLength = 0;

            StringBuilder comment = new StringBuilder("");

            resetData();
            BufferedBinaryReader bSource = new BufferedBinaryReader(source.BaseStream);

            // File format signature
            if (!XM_SIGNATURE.Equals(Utils.Latin1Encoding.GetString(bSource.ReadBytes(17))))
            {
                result = false;
                throw new Exception("Invalid XM file (file signature String mismatch)");
            }

            // Title = chars 17 to 37 (length 20)
            string title = StreamUtils.ReadNullTerminatedStringFixed(bSource, System.Text.Encoding.ASCII, 20);

            if (readTagParams.PrepareForWriting)
            {
                structureHelper.AddZone(17, 20, new byte[20] {
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                }, ZONE_TITLE);
            }
            tagData.IntegrateValue(TagData.TAG_FIELD_TITLE, title.Trim());

            // File format signature
            if (!0x1a.Equals(bSource.ReadByte()))
            {
                result = false;
                throw new Exception("Invalid XM file (file signature ID mismatch)");
            }

            tagExists = true;

            trackerName = StreamUtils.ReadNullTerminatedStringFixed(bSource, System.Text.Encoding.ASCII, 20).Trim();

            trackerVersion = bSource.ReadUInt16(); // hi-byte major and low-byte minor
            trackerName   += (trackerVersion << 8) + "." + (trackerVersion & 0xFF00);

            headerSize = bSource.ReadUInt32(); // Calculated FROM THIS OFFSET, not from the beginning of the file
            songLength = bSource.ReadUInt16();

            bSource.Seek(2, SeekOrigin.Current); // Restart position

            nbChannels    = (byte)Math.Min(bSource.ReadUInt16(), (ushort)0xFF);
            nbPatterns    = bSource.ReadUInt16();
            nbInstruments = bSource.ReadUInt16();

            bSource.Seek(2, SeekOrigin.Current); // Flags for frequency tables; useless for ATL

            initialSpeed = bSource.ReadUInt16();
            initialTempo = bSource.ReadUInt16();

            // Pattern table
            for (int i = 0; i < (headerSize - 20); i++) // 20 being the number of bytes read since the header size marker
            {
                if (i < songLength)
                {
                    FPatternTable.Add(bSource.ReadByte());
                }
                else
                {
                    bSource.Seek(1, SeekOrigin.Current);
                }
            }

            readPatterns(bSource, nbPatterns);
            readInstruments(bSource, nbInstruments);


            // == Computing track properties

            duration = calculateDuration() * 1000.0;

            foreach (Instrument i in FInstruments)
            {
                if (i.DisplayName.Length > 0)
                {
                    comment.Append(i.DisplayName).Append(Settings.InternalValueSeparator);
                }
            }
            if (comment.Length > 0)
            {
                comment.Remove(comment.Length - 1, 1);
            }

            tagData.IntegrateValue(TagData.TAG_FIELD_COMMENT, comment.ToString());
            bitrate = sizeInfo.FileSize / duration;

            return(result);
        }
Esempio n. 27
0
 /// <summary>
 /// Reads the data.
 /// </summary>
 /// <param name="binaryReader">Binary reader.</param>
 public void ReadData(BufferedBinaryReader binaryReader)
 {
     this.pos44      = binaryReader.ReadUInt32();
     this.leftLevel  = binaryReader.ReadUInt16();
     this.rightLevel = binaryReader.ReadUInt16();
 }