Пример #1
0
 public void ReadFromStream(BufferedBinaryReader r)
 {
     ID               = Utils.Latin1Encoding.GetString(r.ReadBytes(4));
     StreamVersion    = r.ReadByte();
     TypeFlag         = r.ReadByte();
     AbsolutePosition = r.ReadUInt64();
     Serial           = r.ReadInt32();
     PageNumber       = r.ReadInt32();
     Checksum         = r.ReadUInt32();
     Segments         = r.ReadByte();
     LacingValues     = r.ReadBytes(Segments);
 }
Пример #2
0
        /// <summary>
        /// Reads the data.
        /// </summary>
        /// <param name="reader">Reader.</param>
        /// <param name="bitmapColorTableSize">Size of the bitmap color table.</param>
        /// <param name="bitmapWidth">Width of the bitmap.</param>
        /// <param name="bitmapHeight">Height of the bitmap.</param>
        /// <param name="toRead">To read.</param>
        public void ReadData(BufferedBinaryReader reader, byte bitmapColorTableSize,
                             ushort bitmapWidth, ushort bitmapHeight, int toRead)
        {
            int size = ((bitmapColorTableSize + 1) * 3) + (bitmapWidth * bitmapHeight);

            byte[] uncompressed = new byte[size];

            byte[] compressed = reader.ReadBytes(toRead);
            uncompressed = DeflatorWraper.Decompress(compressed);

            int readed = 0;
            int offset = size;

            colorTableRGB = new RGB[bitmapColorTableSize + 1];
            for (int i = 0; i < bitmapColorTableSize + 1; i++)
            {
                byte red = uncompressed[readed];
                readed++;
                byte green = uncompressed[readed];
                readed++;
                byte blue = uncompressed[readed];
                readed++;
                colorTableRGB[i] = new RGB(red, green, blue);
                offset          -= 3;
            }

            colorMapPixelData = new byte[offset];
            for (int i = 0; i < offset; i++, readed++)
            {
                colorMapPixelData[i] = uncompressed[readed];
            }
        }
Пример #3
0
        private void readInstruments(BufferedBinaryReader source, int nbInstruments)
        {
            uint   instrumentHeaderSize;
            ushort nbSamples;

            IList <UInt32> sampleSizes = new List <uint>();

            for (int i = 0; i < nbInstruments; i++)
            {
                Instrument instrument = new Instrument();
                instrumentHeaderSize   = source.ReadUInt32();
                instrument.DisplayName = Utils.Latin1Encoding.GetString(source.ReadBytes(22)).Trim();
                instrument.DisplayName = instrument.DisplayName.Replace("\0", "");
                source.Seek(1, SeekOrigin.Current); // Instrument type; useless according to documentation
                nbSamples = source.ReadUInt16();
                source.Seek(instrumentHeaderSize - 29, SeekOrigin.Current);

                if (nbSamples > 0)
                {
                    sampleSizes.Clear();
                    for (int j = 0; j < nbSamples; j++) // Sample headers
                    {
                        sampleSizes.Add(source.ReadUInt32());
                        source.Seek(36, SeekOrigin.Current);
                    }
                    for (int j = 0; j < nbSamples; j++) // Sample data
                    {
                        source.Seek(sampleSizes[j], SeekOrigin.Current);
                    }
                }

                FInstruments.Add(instrument);
            }
        }
Пример #4
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);
            }
        }
Пример #5
0
        /// <summary>
        /// Obtains the value of this field from the specified <see cref="BufferedBinaryReader"/>.
        /// </summary>
        /// <param name="br">The <see cref="BufferedBinaryReader"/> to read from.</param>
        /// <returns>The object that was read.</returns>
        /// <remarks>
        /// While it may technically be possible to remove this boxing by doing the switch statement
        /// outside of the class (where this method is being used), the result goes directly into
        /// a DataRow which boxes anyway.
        /// </remarks>
        internal object GetValue(ref BufferedBinaryReader br)
        {
            //IMPLEMENT: Support for DBT files. https://en.wikipedia.org/wiki/.dbf#Level_5_DOS_headers
            try
            {
                switch (FieldType)
                {
                case EFieldType.Memo:
                case EFieldType.Character:
                    //TODO: Can we do this without allocation of another string that trims the 0-bytes? Is it safe to remove trailing 0 bytes?
                    return(Encoding.GetString(br.ReadBytes(FieldLength)).Trim('\0'));

                case EFieldType.Binary:
                case EFieldType.General:
                    // We do not support DBT tables.
                    return(DBNull.Value);

                case EFieldType.Float:
                case EFieldType.Numeric:
                    // We cannot simply assume it takes up 4 or 8 bytes for a float or double respectively.
                    return(double.Parse(Encoding.GetString(br.ReadBytes(FieldLength)), NumericCulture));

                case EFieldType.Logical:
                {
                    string value = Encoding.GetString(br.ReadBytes(FieldLength));

                    return(value == "Y" || value == "y"
                            ? true
                            : value == "?"
                                ? (object)DBNull.Value
                                : false);
                }

                case EFieldType.Date: return(DateTime.TryParseExact(Encoding.GetString(br.ReadBytes(FieldLength)), "yyyyMMdd", DateCulture, DateTimeStyles.None, out var result) ? result : (object)DBNull.Value);

                case EFieldType.DateTime: return(DateTime.FromOADate(br.ReadInt64() - 2415018.5));

                default: return(DBNull.Value);
                }
            }
            catch (FormatException e)
            {
                throw new FormatException($"Input string was not in a correct format [DbType = {FieldType}].", e);
            }
        }
Пример #6
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 lenght = System.Convert.ToInt32(rh.TagLength);

            actionRecord = binaryReader.ReadBytes(lenght);
        }
Пример #7
0
        public DatabaseFieldDescriptor(ref BufferedBinaryReader reader, ParserOptions parserOptions)
        {
            Encoding       = parserOptions.Encoding ?? Encoding.ASCII;
            NumericCulture = parserOptions.InvariantNumbers ? CultureInfo.InvariantCulture : parserOptions.Culture ?? CultureInfo.InvariantCulture;
            DateCulture    = parserOptions.InvariantDates ? CultureInfo.InvariantCulture : parserOptions.Culture ?? CultureInfo.InvariantCulture;

            FieldName      = reader.ReadBytes(11);
            FieldType      = (EFieldType)reader.ReadByte();
            Reserved01     = reader.ReadBytes(4);
            FieldLength    = reader.ReadByte();
            FieldPrecision = reader.ReadByte();
#pragma warning disable 618
            FieldFlags = (EFieldFlags)reader.ReadByte();
#pragma warning restore 618
            Reserved02 = reader.ReadByte();
            WorkAreaId = reader.ReadByte();
            Reserved03 = reader.ReadBytes(10);
            TableFlags = (ETableFlags)reader.ReadByte();
        }
Пример #8
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);

            jpegData = binaryReader.ReadBytes(tl);
        }
Пример #9
0
        public DatabaseHeader(ref BufferedBinaryReader reader)
        {
            byte versionInfo = reader.ReadByte();

            Level                 = (EDatabaseLevel)(versionInfo & 0b0000_0111);
            Version               = (EDatabaseVersion)(versionInfo & 0b1111_1000);
            UpdateYear            = reader.ReadByte();
            UpdateMonth           = reader.ReadByte();
            UpdateDay             = reader.ReadByte();
            RecordCount           = reader.ReadInt32();
            HeaderLength          = reader.ReadInt16();
            RecordLength          = reader.ReadInt16();
            Reserved01            = reader.ReadBytes(2);
            IncompleteTransaction = reader.ReadByte();
            EncryptionFlag        = reader.ReadByte();
            Reserved02            = reader.ReadBytes(12);
            TableFlags            = (ETableFlags)reader.ReadByte();
            LanguageDriverId      = reader.ReadByte();
            EndOfHeaderMarker     = reader.ReadInt16();
        }
Пример #10
0
        /// <summary>
        /// Reads the data.
        /// </summary>
        /// <param name="binaryReader">Binary reader.</param>
        /// <param name="condActionSize">Size of the cond action.</param>
        public void ReadData(BufferedBinaryReader binaryReader,
                             ushort condActionSize)
        {
            int offset = condActionSize - 5;

            condO   = binaryReader.ReadByte();
            condKey = binaryReader.ReadByte();

            actions = binaryReader.ReadBytes(offset);
            byte end = binaryReader.ReadByte();
        }
Пример #11
0
        private IEnumerable <Guid> Populate()
        {
            _heap.Seek(0, SeekOrigin.Begin);

            long size = _heap.Length;

            while (size > 0)
            {
                var guid = _heap.ReadBytes(16);
                yield return(new Guid(guid));

                size -= 16;
            }
        }
Пример #12
0
        /// <summary>
        /// Reads the data from the binary reader.
        /// </summary>
        /// <param name="binaryReader">Binary reader.</param>
        public override void ReadData(BufferedBinaryReader binaryReader)
        {
            byte[]   b  = binaryReader.ReadBytes(4);
            BitArray ba = BitParser.GetBitValues(b);

            blockWidth  = (int)BitParser.ReadUInt32(ba, 0, 4);
            imageWidth  = (int)BitParser.ReadUInt32(ba, 4, 12);
            blockHeight = (int)BitParser.ReadUInt32(ba, 16, 4);
            imageHeight = (int)BitParser.ReadUInt32(ba, 20, 12);

            int   nbWBlock    = 0;
            int   nbBlockWInt = imageWidth / blockWidth;
            float nbBlockWDec = imageWidth / blockWidth;

            if (nbBlockWInt == nbBlockWDec)
            {
                nbWBlock = nbBlockWInt;
            }
            else
            {
                nbWBlock = nbBlockWInt + 1;
            }

            int   nbHBlock    = 0;
            int   nbBlockHInt = imageHeight / blockHeight;
            float nbBlockHDec = imageHeight / blockHeight;

            if (nbBlockHInt == nbBlockHDec)
            {
                nbHBlock = nbBlockHInt;
            }
            else
            {
                nbHBlock = nbBlockHInt + 1;
            }

            int nbBlock = nbWBlock * nbHBlock;

            if (nbBlock > 0)
            {
                blocks = new ImageBlock[nbBlock];

                for (int i = 0; i < nbBlock; i++)
                {
                    blocks[i] = new ImageBlock();
                    blocks[i].ReadData(binaryReader);
                }
            }
        }
Пример #13
0
        /// <summary>
        /// Reads the data from a binary reader.
        /// </summary>
        /// <param name="binaryReader">Binary reader.</param>
        public void ReadData(BufferedBinaryReader binaryReader)
        {
            byte[]   b  = binaryReader.ReadBytes(2);
            BitArray ba = BitParser.GetBitValues(b);

            dataSize = (int)BitParser.ReadUInt32(ba, 0, 16);

            data = null;
            if (dataSize != 0)
            {
                data = new byte[dataSize];
                for (int i = 0; i < dataSize; i++)
                {
                    data[i] = binaryReader.ReadByte();
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Read next tag from swf input stream.
        /// </summary>
        /// <param name="version">Version.</param>
        /// <param name="binaryReader">Binary reader.</param>
        /// <param name="tagList">Tag list.</param>
        /// <returns></returns>
        internal static BaseTag ReadTag(byte version, BufferedBinaryReader binaryReader, BaseTagCollection tagList)
        {
            long         posBefore = binaryReader.BaseStream.Position;
            RecordHeader rh        = new RecordHeader();

            rh.ReadData(binaryReader);

            int offset = (int)(binaryReader.BaseStream.Position - posBefore);

            binaryReader.BaseStream.Position = posBefore;

            BaseTag resTag = null;

            switch (rh.TagCode)
            {
            case (int)TagCodeEnum.DefineBitsJpeg2: resTag = new DefineBitsJpeg2Tag(); break;

            case (int)TagCodeEnum.DefineBitsJpeg3: resTag = new DefineBitsJpeg3Tag(); break;

            case (int)TagCodeEnum.DefineBitsLossLess: resTag = new DefineBitsLossLessTag(); break;

            case (int)TagCodeEnum.DefineBitsLossLess2: resTag = new DefineBitsLossLess2Tag(); break;

            case (int)TagCodeEnum.End: resTag = new EndTag(); break;

            case (int)TagCodeEnum.SymbolClass: resTag = new SymbolClass(); break;

            default: resTag = new BaseTag(binaryReader.ReadBytes(System.Convert.ToInt32(rh.TagLength + offset))); break;
            }

            //Read the data of the current tag
            resTag.ReadData(version, binaryReader);

            //LOG
            long mustRead = rh.TagLength + offset;

            if (posBefore + mustRead != binaryReader.BaseStream.Position)
            {
                binaryReader.BaseStream.Position = posBefore + rh.TagLength + offset;
            }

            return(resTag);
        }
Пример #15
0
        private void readInstruments(BufferedBinaryReader source, IList <UInt32> instrumentPointers)
        {
            foreach (var pos in instrumentPointers)
            {
                source.Seek(pos, SeekOrigin.Begin);
                var instrument = new Instrument();

                source.Seek(4, SeekOrigin.Current); // Signature
                instrument.FileName = Utils.Latin1Encoding.GetString(source.ReadBytes(12)).Trim();
                instrument.FileName = instrument.FileName.Replace("\0", "");

                source.Seek(16, SeekOrigin.Current); // Data not relevant for ModifiedAtl

                instrument.DisplayName = StreamUtils.ReadNullTerminatedStringFixed(source, Utils.Latin1Encoding, 26);
                instrument.DisplayName = instrument.DisplayName.Replace("\0", "");

                instruments.Add(instrument);
            }
        }
Пример #16
0
        // === PRIVATE METHODS ===

        private bool readHeader(BufferedBinaryReader source, ReadTagParams readTagParams)
        {
            string str;

            if (GYM_SIGNATURE.Equals(Utils.Latin1Encoding.GetString(source.ReadBytes(GYM_SIGNATURE.Length))))
            {
                if (readTagParams.PrepareForWriting)
                {
                    structureHelper.AddZone(source.Position, 416, CORE_SIGNATURE);
                }

                tagExists = true;

                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.IntegrateValue(TagData.TAG_FIELD_TITLE, str);
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.IntegrateValue(TagData.TAG_FIELD_ALBUM, str);
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.IntegrateValue(TagData.TAG_FIELD_COPYRIGHT, str);
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "EMULATOR", str));
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(32))).Trim();
                tagData.AdditionalFields.Add(new MetaFieldInfo(getImplementedTagType(), "DUMPER", str));
                str = Utils.StripEndingZeroChars(Encoding.UTF8.GetString(source.ReadBytes(256))).Trim();
                tagData.IntegrateValue(TagData.TAG_FIELD_COMMENT, str);

                loopStart = source.ReadUInt32();
                uint packedSize = source.ReadUInt32();
                AudioDataOffset = source.Position;
                AudioDataSize   = sizeInfo.FileSize - AudioDataOffset;

                if (packedSize > 0)
                {
                    LogDelegator.GetLogDelegate()(Log.LV_WARNING, "GZIP-compressed files are not supported"); // will be as soon as I find a sample to test with
                    return(false);
                }

                return(true);
            }
            else
            {
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, "Not a GYM file");
                return(false);
            }
        }
Пример #17
0
        public string Fetch(uint offset)
        {
            if (offset == 0)
            {
                throw new BadMetadataException("Invalid #US heap offset.");
            }


            _heap.Seek(offset, SeekOrigin.Begin);

            int length = _heap.ReadPackedInt();
            var bytes  = _heap.ReadBytes(length);

            if (bytes[length - 1] == 0 || bytes[length - 1] == 1)
            {
                length--;
            }

            return(Encoding.Unicode.GetString(bytes, 0, length));
        }
Пример #18
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;
        }
Пример #19
0
        private void readInstruments(BufferedBinaryReader source, IList <ushort> instrumentPointers)
        {
            foreach (ushort pos in instrumentPointers)
            {
                source.Seek(pos << 4, SeekOrigin.Begin);
                Instrument instrument = new Instrument();
                instrument.Type     = source.ReadByte();
                instrument.FileName = Utils.Latin1Encoding.GetString(source.ReadBytes(12)).Trim();
                instrument.FileName = instrument.FileName.Replace("\0", "");

                if (instrument.Type > 0) // Same offsets for PCM and AdLib display names
                {
                    source.Seek(35, SeekOrigin.Current);
                    instrument.DisplayName = StreamUtils.ReadNullTerminatedStringFixed(source, Encoding.ASCII, 28);
                    instrument.DisplayName = instrument.DisplayName.Replace("\0", "");
                    source.Seek(4, SeekOrigin.Current);
                }

                FInstruments.Add(instrument);
            }
        }
Пример #20
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);

            buttonId   = binaryReader.ReadUInt16();
            characters = new ButtonRecordCollection();

            bool characterEndFlag = false;

            while (!characterEndFlag)
            {
                byte first = binaryReader.ReadByte();
                if (first == 0)
                {
                    characterEndFlag = true;
                }
                else
                {
                    ButtonRecord buttRecord = new ButtonRecord();
                    buttRecord.ReadData(binaryReader, first, TagCodeEnum.DefineButton);
                    characters.Add(buttRecord);
                }
            }

            int offset = 2;

            foreach (ButtonRecord butRec in characters)
            {
                offset += butRec.GetSizeOf();
            }

            int lenght = System.Convert.ToInt32(rh.TagLength) - offset - 1;

            //-1 for the ActionEndFlag
            actions = binaryReader.ReadBytes(lenght);
            //Read ActionEndFlag
            binaryReader.ReadByte();
        }
        public void Reset()
        {
            const string s             = "The quick brown fox jumped over the lazy dog.";
            string       expectedValue = s.Substring(4);
            string       observedValue;
            long         observedBufferPosition;
            byte         observedByte;

            using (var memoryStream = new MemoryStream())
            {
                using (var writer = new ExtendedBinaryWriter(memoryStream, Encoding.UTF8, true))
                {
                    writer.Write(Encoding.ASCII.GetBytes(s));
                }

                memoryStream.Position = 0;

                using (var reader = new BufferedBinaryReader(memoryStream))
                {
                    reader.ReadInt32();
                    observedBufferPosition = reader.BufferPosition;

                    reader.BufferPosition = 2;
                    observedByte          = reader.ReadByte();

                    memoryStream.Position = 4;
                    reader.Reset();

                    var bytes = reader.ReadBytes(s.Length - 4);
                    observedValue = Encoding.ASCII.GetString(bytes);
                }
            }

            Assert.Equal(expectedValue, observedValue);
            Assert.Equal((byte)'e', observedByte);
            Assert.Equal(4, observedBufferPosition);
        }
Пример #22
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);
        }
Пример #23
0
        // ---------------------------------------------------------------------------

        // Read total samples of OGG file, which are located on the very last page of the file
        private ulong getSamples(BufferedBinaryReader source)
        {
            OggHeader header = new OggHeader();

            string headerId;
            byte   typeFlag;

            byte[] lacingValues   = new byte[255];
            byte   nbLacingValues = 0;
            long   nextPageOffset = 0;

            // TODO - fine tune seekSize value
            int seekSize = (int)Math.Round(MAX_PAGE_SIZE * 0.75);

            if (seekSize > source.Length)
            {
                seekSize = (int)Math.Round(source.Length * 0.5);
            }
            source.Seek(-seekSize, SeekOrigin.End);
            if (!StreamUtils.FindSequence(source, Utils.Latin1Encoding.GetBytes(OGG_PAGE_ID)))
            {
                LogDelegator.GetLogDelegate()(Log.LV_ERROR, "No OGG header found; aborting read operation"); // Throw exception ?
                return(0);
            }
            source.Seek(-4, SeekOrigin.Current);

            // Iterate until last page is encountered
            do
            {
                if (source.Position + nextPageOffset + 27 > source.Length) // End of stream about to be reached => last OGG header did not have the proper type flag
                {
                    break;
                }

                source.Seek(nextPageOffset, SeekOrigin.Current);

                headerId = Utils.Latin1Encoding.GetString(source.ReadBytes(4));

                if (headerId.Equals(OGG_PAGE_ID))
                {
                    source.Seek(1, SeekOrigin.Current);
                    typeFlag = source.ReadByte();
                    source.Seek(20, SeekOrigin.Current);
                    nbLacingValues = source.ReadByte();
                    nextPageOffset = 0;
                    source.Read(lacingValues, 0, nbLacingValues);
                    for (int i = 0; i < nbLacingValues; i++)
                    {
                        nextPageOffset += lacingValues[i];
                    }
                }
                else
                {
                    LogDelegator.GetLogDelegate()(Log.LV_ERROR, "Invalid OGG header found while looking for total samples; aborting read operation"); // Throw exception ?
                    return(0);
                }
            } while (0 == (typeFlag & 0x04)); // 0x04 marks the last page of the logical bitstream


            // Stream is positioned at the end of the last page header; backtracking to read AbsolutePosition field
            source.Seek(-nbLacingValues - 21, SeekOrigin.Current);

            return(source.ReadUInt64());
        }
Пример #24
0
        /// <summary>
        /// Read next tag from swf input stream.
        /// </summary>
        /// <param name="version">Version.</param>
        /// <param name="binaryReader">Binary reader.</param>
        /// <param name="tagList">Tag list.</param>
        /// <returns></returns>
        internal static BaseTag ReadTag(byte version, BufferedBinaryReader binaryReader, BaseTagCollection tagList)
        {
            long         posBefore = binaryReader.BaseStream.Position;
            RecordHeader rh        = new RecordHeader();

            rh.ReadData(binaryReader);

            int offset = (int)(binaryReader.BaseStream.Position - posBefore);

            binaryReader.BaseStream.Position = posBefore;

            BaseTag resTag = null;

            switch (rh.TagCode)
            {
            case (int)TagCodeEnum.DefineBits: resTag = new DefineBitsTag(); break;

            case (int)TagCodeEnum.DefineBitsJpeg2: resTag = new DefineBitsJpeg2Tag(); break;

            case (int)TagCodeEnum.DefineBitsJpeg3: resTag = new DefineBitsJpeg3Tag(); break;

            case (int)TagCodeEnum.DefineBitsLossLess: resTag = new DefineBitsLossLessTag(); break;

            case (int)TagCodeEnum.DefineBitsLossLess2: resTag = new DefineBitsLossLess2Tag(); break;

            case (int)TagCodeEnum.DefineButton: resTag = new DefineButtonTag(); break;

            case (int)TagCodeEnum.DefineButton2: resTag = new DefineButton2Tag(); break;

            case (int)TagCodeEnum.DefineButtonCxForm: resTag = new DefineButtonCxFormTag(); break;

            case (int)TagCodeEnum.DefineButtonSound: resTag = new DefineButtonSoundTag(); break;

            case (int)TagCodeEnum.DefineEditText: resTag = new DefineEditTextTag(); break;

            case (int)TagCodeEnum.DefineFont: resTag = new DefineFontTag(); break;

            case (int)TagCodeEnum.DefineFont2: resTag = new DefineFont2Tag(); break;

            case (int)TagCodeEnum.DefineFontInfo: resTag = new DefineFontInfoTag(); break;

            case (int)TagCodeEnum.DefineFontInfo2: resTag = new DefineFontInfo2Tag(); break;

            case (int)TagCodeEnum.DefineMorphShape: resTag = new DefineMorphShapeTag(); break;

            case (int)TagCodeEnum.DefineShape: resTag = new DefineShapeTag(); break;

            case (int)TagCodeEnum.DefineShape2: resTag = new DefineShape2Tag(); break;

            case (int)TagCodeEnum.DefineShape3: resTag = new DefineShape3Tag(); break;

            case (int)TagCodeEnum.DefineSound: resTag = new DefineSoundTag(); break;

            case (int)TagCodeEnum.DefineSprite: resTag = new DefineSpriteTag(); break;

            case (int)TagCodeEnum.DefineText: resTag = new DefineTextTag(); break;

            case (int)TagCodeEnum.DefineText2: resTag = new DefineText2Tag(); break;

            case (int)TagCodeEnum.DefineVideoStream: resTag = new DefineVideoStreamTag(); break;

            case (int)TagCodeEnum.DoAction: resTag = new DoActionTag(); break;

            case (int)TagCodeEnum.EnableDebugger: resTag = new EnableDebuggerTag(); break;

            case (int)TagCodeEnum.EnableDebugger2: resTag = new EnableDebugger2Tag(); break;

            case (int)TagCodeEnum.End: resTag = new EndTag(); break;

            case (int)TagCodeEnum.ExportAssets: resTag = new ExportAssetsTag(); break;

            case (int)TagCodeEnum.FrameLabel: resTag = new FrameLabelTag(); break;

            case (int)TagCodeEnum.ImportAssets: resTag = new ImportAssetsTag(); break;

            case (int)TagCodeEnum.InitAction: resTag = new InitActionTag(); break;

            case (int)TagCodeEnum.JpegTable: resTag = new JpegTableTag(); break;

            case (int)TagCodeEnum.PlaceObject: resTag = new PlaceObjectTag(); break;

            case (int)TagCodeEnum.PlaceObject2:     resTag = new PlaceObject2Tag(); break;

            case (int)TagCodeEnum.Protect: resTag = new ProtectTag(); break;

            case (int)TagCodeEnum.RemoveObject: resTag = new RemoveObjectTag(); break;

            case (int)TagCodeEnum.RemoveObject2: resTag = new RemoveObject2Tag(); break;

            case (int)TagCodeEnum.ScriptLimit: resTag = new ScriptLimitTag(); break;

            case (int)TagCodeEnum.SetBackgroundColor: resTag = new SetBackgroundColorTag(); break;

            case (int)TagCodeEnum.SetTabIndex: resTag = new SetTabIndexTag(); break;

            case (int)TagCodeEnum.ShowFrame: resTag = new ShowFrameTag(); break;

            case (int)TagCodeEnum.SoundStreamBlock: resTag = new SoundStreamBlockTag(); break;

            case (int)TagCodeEnum.SoundStreamHead: resTag = new SoundStreamHeadTag(); break;

            case (int)TagCodeEnum.SoundStreamHead2: resTag = new SoundStreamHead2Tag(); break;

            case (int)TagCodeEnum.StartSound: resTag = new StartSoundTag(); break;

            case (int)TagCodeEnum.Metadata: resTag = new MetadataTag(); break;

            case (int)TagCodeEnum.SymbolClass: resTag = new SymbolClassTag(); break;

            //TODO: Sorenson Codec
            case (int)TagCodeEnum.VideoFrame: resTag = ReadVideoFrameTag(binaryReader, tagList); break;

            default: resTag = new BaseTag(binaryReader.ReadBytes(System.Convert.ToInt32(rh.TagLength + offset)), rh.TagCode); break;
            }

            //Read the data of the current tag
            resTag.ReadData(version, binaryReader);

            //LOG
            long mustRead = rh.TagLength + offset;

            if (posBefore + mustRead != binaryReader.BaseStream.Position)
            {
                binaryReader.BaseStream.Position = posBefore + rh.TagLength + offset;
                if (log.IsErrorEnabled)
                {
                    log.Error(Enum.GetName(TagCodeEnum.DefineBits.GetType(), rh.TagCode) + "....KO");
                }
            }
            else if (log.IsInfoEnabled)
            {
                log.Info(Enum.GetName(TagCodeEnum.DefineBits.GetType(), rh.TagCode) + "....OK (" + mustRead + ")");
            }

            return(resTag);
        }
Пример #25
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);
        }
Пример #26
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);

            bool placeFlagHasClipActions    = binaryReader.ReadBoolean();
            bool placeFlagHasClipDepth      = binaryReader.ReadBoolean();
            bool placeFlagHasName           = binaryReader.ReadBoolean();
            bool placeFlagHasRatio          = binaryReader.ReadBoolean();
            bool placeFlagHasColorTransform = binaryReader.ReadBoolean();
            bool placeFlagHasMatrix         = binaryReader.ReadBoolean();
            bool placeFlagHasCharacter      = binaryReader.ReadBoolean();

            placeFlagMove = binaryReader.ReadBoolean();

            depth       = binaryReader.ReadUInt16();
            characterId = 0;
            if (placeFlagHasCharacter)
            {
                characterId = binaryReader.ReadUInt16();
            }
            matrix = null;
            if (placeFlagHasMatrix)
            {
                matrix = new Matrix();
                matrix.ReadData(binaryReader);
            }
            colorTransform = null;
            if (placeFlagHasColorTransform)
            {
                colorTransform = new CXFormWithAlphaData();
                colorTransform.ReadData(binaryReader);
            }
            ratio = 0;
            if (placeFlagHasRatio)
            {
                ratio = binaryReader.ReadUInt16() / 65535.0f;
            }
            name = null;
            if (placeFlagHasName)
            {
                name = binaryReader.ReadString();
            }
            clipDepth = 0;
            if (placeFlagHasClipDepth)
            {
                clipDepth = binaryReader.ReadUInt16();
            }

            // get bytecode actions
            clipActions = null;
            if (placeFlagHasClipActions)
            {
                // different behaviour for Flash 6+
                actionHead = (version >= 6) ? binaryReader.ReadBytes(6) : binaryReader.ReadBytes(4);
                // read clip action records to list
                ArrayList clpAc = new ArrayList();
                //ClipActionRec a = null;
                bool res = true;
                do
                {
                    ClipActionRec action = new ClipActionRec();
                    res = action.ReadData(binaryReader, version);
                    if (res)
                    {
                        clpAc.Add(action);
                    }
                }while (res);
                // copy list to array
                clipActions = new ClipActionRec[clpAc.Count];
                clpAc.CopyTo(clipActions, 0);
            }
        }
Пример #27
0
        protected override bool read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams)
        {
            bool result = true;

            ushort nbOrders      = 0;
            ushort nbPatterns    = 0;
            ushort nbInstruments = 0;

            ushort flags;
            ushort trackerVersion;

            StringBuilder comment = new StringBuilder("");

            IList <ushort> patternPointers    = new List <ushort>();
            IList <ushort> instrumentPointers = new List <ushort>();

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

            // Title = first 28 chars
            string title = StreamUtils.ReadNullTerminatedStringFixed(bSource, System.Text.Encoding.ASCII, 28);

            if (readTagParams.PrepareForWriting)
            {
                structureHelper.AddZone(0, 28, new byte[28] {
                    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, 0, 0
                }, ZONE_TITLE);
            }
            tagData.IntegrateValue(TagData.TAG_FIELD_TITLE, title.Trim());
            bSource.Seek(4, SeekOrigin.Current);

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

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

            trackerName = getTrackerName(trackerVersion);

            bSource.Seek(2, SeekOrigin.Current); // sampleType (16b)
            if (!S3M_SIGNATURE.Equals(Utils.Latin1Encoding.GetString(bSource.ReadBytes(4))))
            {
                result = false;
                throw new Exception("Invalid S3M file (file signature mismatch)");
            }
            bSource.Seek(1, SeekOrigin.Current); // globalVolume (8b)

            tagExists = true;

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

            bSource.Seek(1, SeekOrigin.Current); // masterVolume (8b)
            bSource.Seek(1, SeekOrigin.Current); // ultraClickRemoval (8b)
            bSource.Seek(1, SeekOrigin.Current); // defaultPan (8b)
            bSource.Seek(8, SeekOrigin.Current); // defaultPan (64b)
            bSource.Seek(2, SeekOrigin.Current); // ptrSpecial (16b)

            // Channel table
            for (int i = 0; i < 32; i++)
            {
                FChannelTable.Add(bSource.ReadByte());
                if (FChannelTable[FChannelTable.Count - 1] < 30)
                {
                    nbChannels++;
                }
            }

            // Pattern table
            for (int i = 0; i < nbOrders; i++)
            {
                FPatternTable.Add(bSource.ReadByte());
            }

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

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

            readInstruments(bSource, instrumentPointers);
            readPatterns(bSource, patternPointers);


            // == Computing track properties

            duration = calculateDuration() * 1000.0;

            foreach (Instrument i in FInstruments)
            {
                string displayName = i.DisplayName.Trim();
                if (displayName.Length > 0)
                {
                    comment.Append(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);
        }
        /// <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 beforePos = (int)binaryReader.BaseStream.Position;
            int toReaded  = (int)rh.TagLength - 7;

            _characterId          = binaryReader.ReadUInt16();
            _bitmapFormat         = binaryReader.ReadByte();
            _bitmapWidth          = binaryReader.ReadUInt16();
            _bitmapHeight         = binaryReader.ReadUInt16();
            _bitmapColorTableSize = 0;

            if (_bitmapFormat == 3)
            {
                _bitmapColorTableSize = binaryReader.ReadByte();
                toReaded--;
            }

            int imageSize = _bitmapWidth * _bitmapHeight;

            if (_bitmapFormat == 3)
            {
                int    uncompressedSize = imageSize + ((_bitmapColorTableSize + 1) * 4);
                byte[] uncompressed     = new byte[uncompressedSize];
                byte[] compressed       = binaryReader.ReadBytes(toReaded);
                uncompressed = DeflatorWraper.Decompress(compressed);

                _alphaColorMapData = new AlphaColorMapData();
                _alphaColorMapData.ColorTableRgb = new RGBA[_bitmapColorTableSize + 1];
                int offset = 0;
                for (int i = 0; i < _bitmapColorTableSize + 1; i++, offset += 4)
                {
                    byte red   = uncompressed[offset];
                    byte green = uncompressed[offset + 1];
                    byte blue  = uncompressed[offset + 2];
                    byte alpha = uncompressed[offset + 3];
                    _alphaColorMapData.ColorTableRgb[i] = new RGBA(red, green, blue, alpha);
                }
                _alphaColorMapData.ColorMapPixelData = new byte[uncompressedSize - offset];
                for (int i = 0; i < uncompressedSize - offset; i++, offset++)
                {
                    _alphaColorMapData.ColorMapPixelData[i] = uncompressed[offset];
                }
            }
            else if (_bitmapFormat == 4 || _bitmapFormat == 5)
            {
                int    uncompressedSize = imageSize * 4;
                byte[] uncompressed     = new byte[uncompressedSize];
                byte[] compressed       = binaryReader.ReadBytes(toReaded);
                uncompressed = DeflatorWraper.Decompress(compressed);

                _alphaBitmapData = new AlphaBitmapData();
                _alphaBitmapData.BitmapPixelData = new RGBA[imageSize];
                for (int i = 0, j = 0; i < imageSize; i++, j += 4)
                {
                    byte red   = uncompressed[j];
                    byte green = uncompressed[j + 1];
                    byte blue  = uncompressed[j + 2];
                    byte alpha = uncompressed[j + 3];
                    _alphaBitmapData.BitmapPixelData[i] = new RGBA(red, green, blue, alpha);
                }
            }
        }
Пример #29
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);
        }
Пример #30
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 beforePos = (int)binaryReader.BaseStream.Position;
            int toReaded  = (int)rh.TagLength - 7;

            _characterId          = binaryReader.ReadUInt16();
            _bitmapFormat         = binaryReader.ReadByte();
            _bitmapWidth          = binaryReader.ReadUInt16();
            _bitmapHeight         = binaryReader.ReadUInt16();
            _bitmapColorTableSize = 0;

            if (_bitmapFormat == 3)
            {
                _bitmapColorTableSize = binaryReader.ReadByte();
                toReaded--;
            }

            if (_bitmapFormat == 3)
            {
                _colorMapData = new ColorMapData();
                _colorMapData.ReadData(binaryReader, _bitmapColorTableSize, _bitmapWidth, _bitmapHeight, toReaded);
            }
            else if (_bitmapFormat == 4 || _bitmapFormat == 5)
            {
                int imageSize        = _bitmapWidth * _bitmapHeight;
                int uncompressedSize = imageSize;
                if (_bitmapFormat == 4)
                {
                    uncompressedSize *= 2;
                }
                else
                {
                    uncompressedSize *= 4;
                }

                byte[] uncompressed = new byte[uncompressedSize];
                byte[] compressed   = binaryReader.ReadBytes(toReaded);
                uncompressed = DeflatorWraper.Decompress(compressed);

                _bitmapColorData = null;
                if (_bitmapFormat == 4)
                {
                    Pix15[] bitmapPixelData = new Pix15[imageSize];
                    for (int i = 0, j = 0; i < imageSize; i++, j += 2)
                    {
                        byte[] data = new byte[2] {
                            uncompressed[j], uncompressed[j + 1]
                        };
                        bitmapPixelData[i] = new Pix15(data);
                    }
                    _bitmapColorData = new BitmapColorData(bitmapPixelData);
                }
                else
                {
                    Pix24[] bitmapPixelData = new Pix24[imageSize];
                    for (int i = 0, j = 0; i < imageSize; i++, j += 4)
                    {
                        byte reserved = uncompressed[j];
                        byte red      = uncompressed[j + 1];
                        byte green    = uncompressed[j + 2];
                        byte blue     = uncompressed[j + 3];
                        bitmapPixelData[i] = new Pix24(red, green, blue);
                    }
                    _bitmapColorData = new BitmapColorData(bitmapPixelData);
                }
            }
        }