public void ShouldHandleNotAlignedWrites() { const int iterationCount = 80000; var stream = new MemoryStream(); using (var writer = new PrimitiveWriter(stream)) { writer.Write((byte)1); for (var i = 0; i < iterationCount; i++) { writer.Write(int.MaxValue); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using (var reader = new PrimitiveReader(stream)) { Assert.AreEqual((byte)1, reader.ReadByte()); for (var i = 0; i < iterationCount; i++) { Assert.AreEqual(int.MaxValue, reader.ReadInt32()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); }
public async ValueTask Read(PrimitiveReader primitiveReader, CancellationToken cancellationToken) { BoolValue = await primitiveReader.ReadBool(cancellationToken); ByteValue = await primitiveReader.ReadByte(cancellationToken); SByteValue = await primitiveReader.ReadSByte(cancellationToken); ShortValue = await primitiveReader.ReadInt16(cancellationToken); UShortValue = await primitiveReader.ReadUInt16(cancellationToken); IntValue = await primitiveReader.ReadInt32(cancellationToken); UIntValue = await primitiveReader.ReadUInt32(cancellationToken); LongValue = await primitiveReader.ReadInt64(cancellationToken); ULongValue = await primitiveReader.ReadUInt64(cancellationToken); FloatValue = await primitiveReader.ReadSingle(cancellationToken); DoubleValue = await primitiveReader.ReadDouble(cancellationToken); StringValue = await primitiveReader.ReadString(cancellationToken); deserializationCounter++; }
public void ShouldReadAndWriteLimits() { var stream = new MemoryStream(); using (var writer = new PrimitiveWriter(stream)) { writer.Write(byte.MinValue); writer.Write(byte.MaxValue); writer.Write(sbyte.MinValue); writer.Write(sbyte.MaxValue); writer.Write(short.MinValue); writer.Write(short.MaxValue); writer.Write(ushort.MinValue); writer.Write(ushort.MaxValue); writer.Write(int.MinValue); writer.Write(int.MaxValue); writer.Write(uint.MinValue); writer.Write(uint.MaxValue); writer.Write(long.MinValue); writer.Write(long.MaxValue); writer.Write(ulong.MinValue); writer.Write(ulong.MaxValue); } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using (var reader = new PrimitiveReader(stream)) { Assert.AreEqual(byte.MinValue, reader.ReadByte()); Assert.AreEqual(byte.MaxValue, reader.ReadByte()); Assert.AreEqual(sbyte.MinValue, reader.ReadSByte()); Assert.AreEqual(sbyte.MaxValue, reader.ReadSByte()); Assert.AreEqual(short.MinValue, reader.ReadInt16()); Assert.AreEqual(short.MaxValue, reader.ReadInt16()); Assert.AreEqual(ushort.MinValue, reader.ReadUInt16()); Assert.AreEqual(ushort.MaxValue, reader.ReadUInt16()); Assert.AreEqual(int.MinValue, reader.ReadInt32()); Assert.AreEqual(int.MaxValue, reader.ReadInt32()); Assert.AreEqual(uint.MinValue, reader.ReadUInt32()); Assert.AreEqual(uint.MaxValue, reader.ReadUInt32()); Assert.AreEqual(long.MinValue, reader.ReadInt64()); Assert.AreEqual(long.MaxValue, reader.ReadInt64()); Assert.AreEqual(ulong.MinValue, reader.ReadUInt64()); Assert.AreEqual(ulong.MaxValue, reader.ReadUInt64()); } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); }
public async override ValueTask Read(PrimitiveReader primitiveReader, CancellationToken cancellationToken) { Reads++; for (int i = 0; i < data.Length; i++) { data[i] = await primitiveReader.ReadByte(cancellationToken); } }
public override void Read(PrimitiveReader reader) { Locale = reader.ReadStringProto(16); ViewDistance = reader.ReadByte(); ChatMode = (ChatModeEnum)reader.ReadVarint(); if (!(ChatMode == ChatModeEnum.Enabled || ChatMode == ChatModeEnum.CommandsOnly || ChatMode == ChatModeEnum.Hidden)) { throw new InvalidPacketException(nameof(ChatMode), ChatMode); } var mask = reader.ReadByte(); if ((mask & 0x01) != 0) { CapeEnabled = true; } if ((mask & 0x02) != 0) { JacketEnabled = true; } if ((mask & 0x04) != 0) { LeftSleeveEnabled = true; } if ((mask & 0x08) != 0) { RightSleeveEnabled = true; } if ((mask & 0x10) != 0) { LeftPantsLegEnabled = true; } if ((mask & 0x20) != 0) { RightPantsLegEnabled = true; } if ((mask & 0x40) != 0) { HatEnabled = true; } MainHand = (HandSide)reader.ReadVarint(); if (!MainHand.IsValid()) { throw new InvalidPacketException(nameof(MainHand), MainHand); } }
public override void Read(PrimitiveReader reader) { WindowId = reader.ReadByte(); Slot = reader.ReadShort(); Button = reader.ReadSByte(); ActionNum = reader.ReadShort(); Mode = reader.ReadVarint(); ClickedItem = reader.ReadItemStackProto(); }
void ReadID31( PrimitiveReader reader ) { MusicInfo[MusicInfoKeys.Title] = ReadFixedASCIIString( reader, 30 ); MusicInfo[MusicInfoKeys.Artist] = ReadFixedASCIIString( reader, 30 ); MusicInfo[MusicInfoKeys.Album] = ReadFixedASCIIString( reader, 30 ); MusicInfo[MusicInfoKeys.YearReleased] = ReadFixedASCIIString( reader, 4 ); // TODO: check for track number in comment field string comment = ReadFixedASCIIString( reader, 30 ); byte genre = reader.ReadByte(); }
public void Load(PrimitiveReader reader) { var length = reader.ReadInt32(); data = new IntPtr[length]; for (var i = 0; i < length; i++) { data[i] = new IntPtr(reader.ReadByte()); } }
public async override ValueTask Read(PrimitiveReader primitiveReader, CancellationToken cancellationToken) { Reads++; Pings.Add((int)stopwatch.ElapsedMilliseconds); for (int i = 0; i < data.Length; i++) { data[i] = await primitiveReader.ReadByte(cancellationToken); } stopwatch.Reset(); }
void ReadID31Extended( PrimitiveReader reader ) { // TODO: Concat these 3 strings with their ID31.1 strings string title = ReadFixedASCIIString( reader, 60 ); string artist = ReadFixedASCIIString( reader, 60 ); string album = ReadFixedASCIIString( reader, 60 ); byte speed = reader.ReadByte(); string genre = ReadFixedASCIIString( reader, 30 ); string startTime = ReadFixedASCIIString( reader, 6 ); string endTime = ReadFixedASCIIString( reader, 6 ); }
public void Load(PrimitiveReader reader) { var fileName = TemporaryFilesManager.Instance.GetTemporaryFile(); underlyingStream = new FileStream(fileName, FileMode.OpenOrCreate); underlyingStreamOffset = 0; length = reader.ReadInt64(); PaddingByte = reader.ReadByte(); var numberOfBytes = reader.ReadInt64(); reader.CopyTo(underlyingStream, numberOfBytes); Position = reader.ReadInt64(); }
public override void Read(PrimitiveReader reader) { Sideways = reader.ReadFloat(); Forward = reader.ReadFloat(); var flags = reader.ReadByte(); if ((flags & 0x01) != 0) { Jump = true; } if ((flags & 0x02) != 0) { Unmount = true; } }
public ID3v2Frame( Mp3Container container, PrimitiveReader reader, byte majorVersion ) { revision = reader.ReadByte(); headerFlags = reader.ReadByte(); dataSize = ReadSyncSafeInt32( reader ); reader.BigEndian = true; this.container = container; this.majorVersion = majorVersion; bool useUnsynch = ( headerFlags & 0x80 ) != 0; if( useUnsynch ) { reader.stream = new UnsynchronisationStream( reader.stream ); } if( majorVersion == 3 ) { ReadV3( reader ); } else { throw new NotImplementedException( "Support for ID3 version " + majorVersion + " not yet done." ); } if( useUnsynch ) { reader.stream = ( (UnsynchronisationStream)reader.stream ).UnderlyingStream; } }
public static ItemStack ReadItemStackProto(this PrimitiveReader reader) { var id = reader.ReadShort(); if (id == -1) { return(ItemStack.Empty); } return(new ItemStack() { Item = Item.GetFromId(id), Count = reader.ReadByte(), Damage = reader.ReadShort(), Nbt = reader.ReadNbtBlob() }); }
/// <summary> /// Reads an Uncompressed NbtBlob. /// </summary> /// <exception cref="NBTException">Invalid NbtBlob</exception> public static NbtBlob ReadNbtBlob(this PrimitiveReader reader) { var id = reader.ReadByte(); if (id == Tag.EndId) { return(NbtBlob.Empty); } if (id != Tag.Compound.Id) { throw new NBTException("NBT root is not a compound."); } var name = reader.ReadStringNbt(); var tag = new Tag.Compound(); tag.Read(reader, 0); return(new NbtBlob(name, tag)); }
internal override void Read(PrimitiveReader reader, int level) { level++; if (level > MaxNestLevel) { ThrowMaxNestLevel(); } while (true) { var id = reader.ReadByte(); if (id == EndId) { break; } var tag = CreateTagFromID(id); var name = reader.ReadStringNbt(); tag.Read(reader, level); this[name] = tag; } }
public override void Read(PrimitiveReader reader) { Status = (StatusEnum)reader.ReadVarint(); if (!(Status == StatusEnum.StartDigging || Status == StatusEnum.CancelDigging || Status == StatusEnum.FinishDigging || Status == StatusEnum.DropItemStack || Status == StatusEnum.DropItem || Status == StatusEnum.FinishUseItem || Status == StatusEnum.SwapItem)) { throw new InvalidPacketException(nameof(Status), Status); } Location = reader.ReadBlockPosProto(); var facing = reader.ReadByte(); Facing = Facing.GetFromValue(facing); if (Facing == null) { throw new InvalidPacketException(nameof(Facing), facing); } }
public override void Read(PrimitiveReader reader) { var flags = reader.ReadByte(); if ((flags & 0x01) != 0) { IsCreative = true; } if ((flags & 0x02) != 0) { IsFlying = true; } if ((flags & 0x04) != 0) { CanFly = true; } if ((flags & 0x08) != 0) { GodMode = true; } FlyingSpeed = reader.ReadFloat(); WalkingSpeed = reader.ReadFloat(); }
public void ShouldHandleNotAlignedWrites() { const int iterationCount = 80000; var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream)) { writer.Write((byte)1); for(var i = 0; i < iterationCount; i++) { writer.Write(int.MaxValue); } } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream)) { Assert.AreEqual((byte)1, reader.ReadByte()); for(var i = 0; i < iterationCount; i++) { Assert.AreEqual(int.MaxValue, reader.ReadInt32()); } } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); }
internal override void Read(PrimitiveReader reader, int level) { level++; if (level > MaxNestLevel) { ThrowMaxNestLevel(); } var id = reader.ReadByte(); var length = reader.ReadInt(); if (length <= 0) { return; } Value.Capacity = length; for (var i = 0; i < length; i++) { var tag = CreateTagFromID(id); tag.Read(reader, level); Value.Add(tag); } }
protected string ReadNullTerminatedEncodedString( PrimitiveReader reader, ref int bytesLeft ) { byte encoding = reader.ReadByte(); bytesLeft--; byte[] stringData = null; Encoding textEncoding = null; int index = 0; if( encoding == 0 ) { textEncoding = Encoding.GetEncoding( 28591 ); stringData = new byte[bytesLeft]; while( bytesLeft > 0 ) { byte part = reader.ReadByte(); if( part == 0x00 ) break; stringData[index++] = part; bytesLeft--; } } else if( encoding == 1 ) { ushort bom = reader.ReadUInt16(); bytesLeft -= 2; stringData = new byte[bytesLeft]; if( bom == 0xFEFF ) { textEncoding = Encoding.BigEndianUnicode; } else if( bom == 0xFFFE ) { textEncoding = Encoding.Unicode; } else { throw new InvalidDataException( "Invalid bom: " + bom ); } while( bytesLeft > 0 ) { byte part1 = reader.ReadByte(); byte part2 = reader.ReadByte(); if( part1 == 0x00 && part2 == 0x00 ) break; stringData[index++] = part1; bytesLeft--; stringData[index++] = part2; bytesLeft--; } } else { throw new NotSupportedException( "Unsupported encoding " + encoding ); } return textEncoding.GetString( stringData, 0, index ); }
public async ValueTask Read(PrimitiveReader primitiveReader, CancellationToken cancellationToken) { byte key = await primitiveReader.ReadByte(cancellationToken); await index[key].Read(primitiveReader, cancellationToken); }
protected string ReadNullTerminatedString( PrimitiveReader reader, ref int bytesLeft ) { int index = 0; Encoding textEncoding = Encoding.GetEncoding( 28591 ); byte[] stringData = new byte[bytesLeft]; while( bytesLeft > 0 ) { byte part = reader.ReadByte(); if( part == 0x00 ) break; stringData[index++] = part; bytesLeft--; } return textEncoding.GetString( stringData, 0, index ); }
bool ReadMetadataBlock( PrimitiveReader reader ) { byte flags = reader.ReadByte(); bool lastBlock = ( flags & 0x80 ) != 0; flags &= 0x7F; MetadataBlockType blockType = (MetadataBlockType)flags; int metaLength = reader.ReadUInt24(); switch( blockType ) { case MetadataBlockType.StreamInfo: ProcessMetadataStreamInfo( metaLength, reader ); break; case MetadataBlockType.Padding: ProcessMetadataPadding( metaLength, reader ); break; case MetadataBlockType.Application: ProcessMetadataApplication( metaLength, reader ); break; case MetadataBlockType.SeekTable: ProcessMetadataSeekTable( metaLength, reader ); break; case MetadataBlockType.VorbisComment: ProcessMetadataVorbisComment( metaLength, reader ); break; case MetadataBlockType.Cuesheet: ProcessMetadataCuesheet( metaLength, reader ); break; case MetadataBlockType.Picture: ProcessMetadataPicture( metaLength, reader ); break; default: throw new InvalidDataException( "Invalid metadata block type." ); } return lastBlock; }
public IEnumerable<AudioChunk> StreamData( Stream source ) { info = new AudioChunk(); PrimitiveReader reader = new PrimitiveReader( source ); while( true ) { // Read frame header BitReader bitReader = new BitReader( reader ); bitReader.BigEndian = true; //Console.WriteLine( "start pos" + reader.Position ); // Skip any padding('00') bytes before the start of a frame byte data = 0; while( ( data = reader.ReadByte() ) == 0 ); // Make sure that the 'data' byte is the first 8 bits of the sync word. if( data != 0xFF ) { throw new InvalidDataException( "Invalid frame sync value." ); } int frameSync = bitReader.ReadBits( 3/*11*/ ); if( frameSync != 0x7/*FF*/ ) { throw new InvalidDataException( "Invalid frame sync value." ); } int versionId = bitReader.ReadBits( 2 ); int layerIndex = bitReader.ReadBits( 2 ); bool crcProtection = bitReader.ReadBit() == 0; int bitrateIndex = bitReader.ReadBits( 4 ); int samplingRateIndex = bitReader.ReadBits( 2 ); bool padded = bitReader.ReadBit() != 0; int privateBit = bitReader.ReadBit(); int channelMode = bitReader.ReadBits( 2 ); int modeExtension = bitReader.ReadBits( 2 ); int copyrightBit = bitReader.ReadBit(); int originalBit = bitReader.ReadBit(); int emphasis = bitReader.ReadBits( 2 ); int bitrate = GetBitRate( (MpegVersion)versionId, layerIndex, bitrateIndex ); info.Frequency = samplingRates[versionId][samplingRateIndex]; ushort crc = 0; if( crcProtection ) { crc = (ushort)bitReader.ReadBits( 16 ); } MpegFrame frame = new MpegFrame(); frame.Bitrate = bitrate; frame.ChannelMode = (ChannelMode)channelMode; frame.Channels = Common.GetNumberOfChannels( frame.ChannelMode ); frame.CrcProtected = crcProtection; frame.Padding = padded; frame.ModeExtension = modeExtension; frame.SampleRate = info.Frequency; frame.Emphasis = emphasis; frame.Version = (MpegVersion)versionId; LayerIndex index2 = (LayerIndex)layerIndex; info.Data = null; //Console.WriteLine( "padding: {0}, type: {1}, sr: {2}, br: {3}", //frame.Padding, index2, frame.SampleRate, frame.Bitrate ); if( layerIndex == (int)LayerIndex.Layer1 ) { info.Data = decoder1.Decode( frame, bitReader ); } else if( layerIndex == (int)LayerIndex.Layer2 ) { info.Data = decoder2.Decode( frame, bitReader ); } else if( layerIndex == (int)LayerIndex.Layer3 ) { throw new NotSupportedException( "Layer III not supported" ); } else { throw new InvalidDataException( "Invalid layer" ); } info.Channels = frame.Channels; info.BitsPerSample = 16; //if( bitReader.offset == 8 ) { //reader.ReadByte(); //} yield return info; } }
byte[] ReadRawUTF8Char( PrimitiveReader reader ) { int byteCount = 0; byte header = reader.ReadByte(); for( int bit = 7; bit >= 0; bit-- ) { if( ( header & ( 1 << bit ) ) != 0 ) { byteCount++; header &= (byte)~( 1 << bit ); } else { break; } } if( byteCount == 0 ) return new byte[] { header }; byte[] data = new byte[byteCount]; data[0] = header; reader.FillBuffer( data, 1, byteCount - 1 ); for( int i = 1; i < data.Length; i++ ) { data[i] &= 0x3F; // Clear highest two bits. } return data; }
void ProcessMetadataCuesheet( int len, PrimitiveReader reader ) { string catalogueNumber = reader.ReadASCIIString( 128 ); ulong leadInSamplesCount = reader.ReadUInt64(); byte format = reader.ReadByte(); // All bits other than 1 are reserved. bool compactDisc = ( format & 0x01 ) != 0; byte[] reserved = reader.ReadBytes( 258 ); byte trackCount = reader.ReadByte(); bool cdda = leadInSamplesCount != 0; for( int i = 0; i < trackCount; i++ ) { ulong trackOffset = reader.ReadUInt64(); byte trackNumber = reader.ReadByte(); bool leadOut = cdda ? trackNumber == 170 : trackNumber == 255; string isrc = reader.ReadASCIIString( 12 ); byte trackFlags = reader.ReadByte(); // All bits other than 1 and 2 are reserved. bool audio = ( trackFlags & 0x01 ) == 0; bool preEmphasis = ( trackFlags & 0x02 ) != 0; byte[] trackReserved = reader.ReadBytes( 13 ); byte indexCount = reader.ReadByte(); for( int j = 0; j < indexCount; j++ ) { ulong indexOffset = reader.ReadUInt64(); byte indexPointNumber = reader.ReadByte(); byte[] indexReserved = reader.ReadBytes( 3 ); } } }
public IEnumerable<AudioChunk> StreamData( Stream source ) { PrimitiveReader reader = new PrimitiveReader( source ); reader.BigEndian = true; while( true ) { #region Frame header FlacBitReader bitReader = new FlacBitReader( reader ); bitReader.BigEndian = true; int syncCode = bitReader.ReadBits( 14 ); if( syncCode != 0x3FFE ) { throw new InvalidDataException( "Invalid synchronisation code." ); } int reserved = bitReader.ReadBit(); bool variableBlockSize = bitReader.ReadBit() != 0; int blockSizeFlags = bitReader.ReadBits( 4 ); int sampleRateFlags = bitReader.ReadBits( 4 ); int channelAssignment = bitReader.ReadBits( 4 ); int sampleSizeFlags = bitReader.ReadBits( 3 ); if( bitReader.ReadBit() != 0 ) throw new InvalidDataException( "Reserved bit is not 0." ); byte[] numberData = ReadRawUTF8Char( reader ); /*int frameNumber = numberData[0]; for( int i = 1; i < numberData.Length; i++ ) { frameNumber <<= 6; frameNumber |= numberData[i]; } Console.WriteLine( frameNumber );*/ int blockSize = 0; if( blockSizeFlags == 0x0 ) { throw new InvalidDataException( "0 is reserved for block sizes." ); } else if( blockSizeFlags == 0x1 ) { blockSize = 192; } else if( blockSizeFlags >= 0x2 && blockSizeFlags <= 0x5 ) { blockSize = 576 * ( 1 << ( blockSizeFlags - 2 ) ); // 2^x. } else if( blockSizeFlags == 0x6 ) { blockSize = reader.ReadByte() + 1; } else if( blockSizeFlags == 0x7 ) { blockSize = reader.ReadUInt16() + 1; } else { blockSize = 256 * ( 1 << ( blockSizeFlags - 8 ) ); // 2^x. } int sampleRate = 0; if( sampleRateFlags == 0x0 ) { sampleRate = metaSampleRate; } else if( sampleRateFlags >= 0x01 && sampleRateFlags <= 0xB ) { sampleRate = sampleRates[sampleRateFlags]; } else if( sampleRateFlags == 0xC ) { sampleRate = reader.ReadByte(); } else if( sampleRateFlags == 0xD ) { sampleRate = reader.ReadUInt16(); } else if( sampleRateFlags == 0xE ) { sampleRate = reader.ReadUInt16() * 10; } else { throw new InvalidDataException( "Invalid sample rate flag." ); } int bitsPerSample; if( sampleSizeFlags == 0 ) { bitsPerSample = metaBitsPerSample; } else if( sampleSizeFlags == 0x3 || sampleRateFlags == 0x7 ) { throw new InvalidDataException( "Sample size is reserved." ); } else { bitsPerSample = bitSampleSizes[sampleSizeFlags]; } int channelsCount; ChannelAssignment soundAssignment = (ChannelAssignment)channelAssignment; if( channelAssignment < 0x08 ) { channelsCount = channelAssignment + 1; } else if( channelAssignment < 0x0B ) { channelsCount = 2; } else { throw new InvalidDataException( "Channel assignment values > 1010 are reserved." ); } byte crc8 = reader.ReadByte(); #endregion #region Subframe int[][] channelsData = new int[channelsCount][]; for( int i = 0; i < channelsCount; i++ ) { if( bitReader.ReadBit() != 0 ) { throw new InvalidDataException( "Padding bit should be 0." ); } int[] channelData = null; int subframeType = bitReader.ReadBits( 6 ); bool wastedBitsPerSampleFlag = bitReader.ReadBit() != 0; int adjustedBitsPerSample = bitsPerSample; switch( soundAssignment ) { case ChannelAssignment.LeftSide: if( i == 1 ) adjustedBitsPerSample++; break; case ChannelAssignment.RightSide: if( i == 0 ) adjustedBitsPerSample++; break; case ChannelAssignment.MidSide: if( i == 1 ) adjustedBitsPerSample++; break; } int wastedBitsPerSample = 0; if( wastedBitsPerSampleFlag ) { wastedBitsPerSample = 1 + bitReader.ReadUnary(); } if( subframeType == 0x00 ) { channelData = ProcessConstantSubframe( bitReader, adjustedBitsPerSample, blockSize ); } else if( subframeType == 0x01 ) { channelData = ProcessVerbatimSubframe( bitReader, adjustedBitsPerSample, blockSize ); } else { if( ( subframeType & 0x20 ) != 0 ) { int order = ( subframeType & 0x1F ) + 1; channelData = ProcessLpcSubframe( bitReader, adjustedBitsPerSample, order, blockSize ); } else if( ( subframeType & 0x08 ) != 0 ) { int order = subframeType & 0x07; channelData = ProcessFixedSubframe( bitReader, adjustedBitsPerSample, order, blockSize ); } } channelsData[i] = channelData; } bitReader.SkipRemainingBits(); #endregion // Transform the samples into left right switch( soundAssignment ) { case ChannelAssignment.LeftSide: TransformSamplesLS( channelsData[0], channelsData[1] ); break; case ChannelAssignment.RightSide: TransformSamplesSR( channelsData[0], channelsData[1] ); break; case ChannelAssignment.MidSide: TransformSamplesMS( channelsData[0], channelsData[1] ); break; } int bytesPerSample = (int)Math.Ceiling( bitsPerSample / 8.0 ); byte[] data = new byte[channelsCount * bytesPerSample * blockSize]; bool use16Bits = bitsPerSample <= 16; bool use8Bits = bitsPerSample <= 8; int offset = 0; for( int i = 0; i < blockSize; i++ ) { for( int ch = 0; ch < channelsCount; ch++ ) { int[] channelData = channelsData[ch]; if( use16Bits ) { ushort sample = (ushort)channelData[i]; data[offset++] = (byte)( sample ); data[offset++] = (byte)( sample >> 8 ); } else if( use8Bits ) { data[offset++] = (byte)channelData[i]; } } } // Read frame footer ushort crc16 = reader.ReadUInt16(); AudioChunk chunk = new AudioChunk(); chunk.Frequency = sampleRate; chunk.Channels = channelsCount; chunk.BitsPerSample = bitsPerSample; chunk.Data = data; yield return chunk; } }
void ProcessCommonChunk( AiffChunkHeader chunk, PrimitiveReader reader ) { byte[] chunkData = reader.ReadBytes( chunk.DataSize ); Stream source = reader.stream; reader.stream = new MemoryStream( chunkData ); int channelsCount = reader.ReadInt16(); uint frameCount = reader.ReadUInt32(); int bitsPerSample = reader.ReadInt16(); byte[] sampleRateBytes = reader.ReadBytes( 10 ); double sampleRate = ConvertFromIeeeExtended( sampleRateBytes ); Console.WriteLine( sampleRate ); AppendInfoLine( 2, "Channels Count: {0}", channelsCount ); AppendInfoLine( 2, "Sample rate (frames/sec): {0}", sampleRate ); AppendInfoLine( 2, "Bits per sample: {0}", bitsPerSample ); AppendInfoLine( 2, "Frame count: {0}", frameCount ); int byteRate = (int)Math.Ceiling( sampleRate ) * channelsCount * bitsPerSample / 8; info.Frequency = (int)sampleRate; Console.WriteLine( "BPS:" + bitsPerSample + ", SR:" + info.Frequency ); transformer = EmptyTransformer.Instance; if( bitsPerSample > 8 && bitsPerSample <= 16 ) { transformer = BigEndian16BitTo16BitTransformer.Instance; } if( bitsPerSample > 16 && bitsPerSample <= 24 ) { transformer = BigEndian24BitTo16BitTransformer.Instance; } // Number of bytes that make up a second's worth of audio data. bufferSize = byteRate; info.Channels = channelsCount; actualBitsPerSample = bitsPerSample; // TODO: Remove this hackery. if( bitsPerSample > 16 ) bitsPerSample = 16; info.BitsPerSample = bitsPerSample; if( aifcFormat ) { string compressionType = reader.ReadASCIIString( 4 ); string compressionName = reader.ReadASCIIString( reader.ReadByte() ); AppendInfoLine( 2, "Compression type: {0}", compressionType ); AppendInfoLine( 2, "Compression name: {0}", compressionName ); switch( compressionType ) { case "NONE": case "sowt": break; case "alaw": case "ALAW": info.BitsPerSample = 16; transformer = ALawTransformer.Instance; break; case "ulaw": case "ULAW": info.BitsPerSample = 16; transformer = MuLawTransformer.Instance; break; } } reader.stream = source; }
bool ReadV3Frame( PrimitiveReader reader, ref int len ) { string frameId = reader.ReadASCIIString( 4 ); len -= 4; if( frameId == "\0\0\0\0" ) return true; int frameDataSize = reader.ReadInt32(); ushort frameFlags = reader.ReadUInt16(); len -= ( frameDataSize + 4 + 2 ); bool encryption = ( frameFlags & 0x80 ) != 0; bool compression = ( frameFlags & 0x40 ) != 0; bool groupingInfo = ( frameFlags & 0x20 ) != 0; if( groupingInfo ) { byte groupIdentifier = reader.ReadByte(); } if( encryption || compression ) throw new NotImplementedException( "encryption and/or compression support is not yet implemented." ); Console.WriteLine( "reading frame: " + frameId ); if( v3TagConstructors == null ) { v3TagConstructors = ID3v2Tag.Makev3TagConstructors(); } Func<ID3v2Tag> constructor; if( v3TagConstructors.TryGetValue( frameId, out constructor ) ) { ID3v2Tag tag = constructor(); tag.Identifier = frameId; tag.DataSize = frameDataSize; tag.Read( container, reader ); } else { Console.WriteLine( " skipping frame." ); reader.SkipData( frameDataSize ); } return false; }
public override void Read(PrimitiveReader reader) { WindowId = reader.ReadByte(); }
public override void Read(PrimitiveReader reader) { WindowId = reader.ReadSByte(); EnchantmentPos = reader.ReadByte(); }
public void ShouldReadAndWriteLimits() { var stream = new MemoryStream(); using(var writer = new PrimitiveWriter(stream)) { writer.Write(byte.MinValue); writer.Write(byte.MaxValue); writer.Write(sbyte.MinValue); writer.Write(sbyte.MaxValue); writer.Write(short.MinValue); writer.Write(short.MaxValue); writer.Write(ushort.MinValue); writer.Write(ushort.MaxValue); writer.Write(int.MinValue); writer.Write(int.MaxValue); writer.Write(uint.MinValue); writer.Write(uint.MaxValue); writer.Write(long.MinValue); writer.Write(long.MaxValue); writer.Write(ulong.MinValue); writer.Write(ulong.MaxValue); } var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); using(var reader = new PrimitiveReader(stream)) { Assert.AreEqual(byte.MinValue, reader.ReadByte()); Assert.AreEqual(byte.MaxValue, reader.ReadByte()); Assert.AreEqual(sbyte.MinValue, reader.ReadSByte()); Assert.AreEqual(sbyte.MaxValue, reader.ReadSByte()); Assert.AreEqual(short.MinValue, reader.ReadInt16()); Assert.AreEqual(short.MaxValue, reader.ReadInt16()); Assert.AreEqual(ushort.MinValue, reader.ReadUInt16()); Assert.AreEqual(ushort.MaxValue, reader.ReadUInt16()); Assert.AreEqual(int.MinValue, reader.ReadInt32()); Assert.AreEqual(int.MaxValue, reader.ReadInt32()); Assert.AreEqual(uint.MinValue, reader.ReadUInt32()); Assert.AreEqual(uint.MaxValue, reader.ReadUInt32()); Assert.AreEqual(long.MinValue, reader.ReadInt64()); Assert.AreEqual(long.MaxValue, reader.ReadInt64()); Assert.AreEqual(ulong.MinValue, reader.ReadUInt64()); Assert.AreEqual(ulong.MaxValue, reader.ReadUInt64()); } Assert.AreEqual(position, stream.Position, StreamCorruptedMessage); }
public static double ReadAngleProto(this PrimitiveReader reader) { return(reader.ReadByte() * 360d / 256d); }