//****************************************************************************************************** // WaveFormatChunk.cs - Gbtc // // Copyright © 2010, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may // not use this file except in compliance with the License. You may obtain a copy of the License at: // // http://www.opensource.org/licenses/eclipse-1.0.php // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 07/29/2009 - J. Ritchie Carroll // Generated original version of source code. // 09/14/2009 - Stephen C. Wills // Added new header and license agreement. // 10/8/2012 - Danyelle Gilliam // Modified Header // //****************************************************************************************************** #region [ Contributor License Agreements ] /**************************************************************************\ Copyright © 2009 - J. Ritchie Carroll All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \**************************************************************************/ #endregion using GSF.Parsing; using System; using System.IO; namespace GSF.Media { /// /// Represents the format chunk in a WAVE media format file. /// public class WaveFormatChunk : RiffChunk, ISupportBinaryImage { #region [ Members ] // Constants /// /// RIFF type ID for wave format chunk (i.e., "fmt "). /// public const string RiffTypeID = "fmt "; // Fields private ushort m_audioFormat; private short m_channels; private int m_sampleRate; private int m_byteRate; private short m_blockAlignment; private short m_bitsPerSample; private short m_extraParametersSize; private byte[] m_extraParameters; #endregion #region [ Constructors ] /// /// Constructs a new using the specified audio parameters. /// /// Sample rate for the . /// Bits per sample for the . /// Audio channels for the . /// Audio format for the . /// Invalid bit rate specified - wave file bit rates must be a multiple of 8. [CLSCompliant(false)] public WaveFormatChunk(int sampleRate, short bitsPerSample, short channels, ushort audioFormat) : base(RiffTypeID) { if (bitsPerSample % 8 != 0) throw new InvalidDataException("Invalid bit rate specified - wave file bit rates must be a multiple of 8"); m_sampleRate = sampleRate; m_bitsPerSample = bitsPerSample; m_channels = channels; m_audioFormat = audioFormat; UpdateByteRate(); UpdateBlockAlignment(); } /// Reads a new from the specified stream. /// Pre-parsed header. /// Source stream to read data from. /// WAVE format or extra parameters section too small, wave file corrupted. /// Invalid bit rate encountered - wave file bit rates must be a multiple of 8. public WaveFormatChunk(RiffChunk preRead, Stream source) : base(preRead, RiffTypeID) { int length = ChunkSize; byte[] buffer = BufferPool.TakeBuffer(length); try { int bytesRead = source.Read(buffer, 0, length); // Initialize class from buffer ParseBinaryImage(buffer, 0, bytesRead); // Read extra parameters, if any if (m_extraParametersSize > 0) { m_extraParameters = new byte[m_extraParametersSize]; bytesRead = source.Read(m_extraParameters, 0, m_extraParametersSize); if (bytesRead < m_extraParametersSize) throw new InvalidOperationException("WAVE extra parameters section too small, wave file corrupted"); } } finally { if (buffer != null) BufferPool.ReturnBuffer(buffer); } } #endregion #region [ Properties ] /// Size of . public override int ChunkSize { get { // Trust the read size over the typical constants if available int chunkSize = base.ChunkSize; if (chunkSize == 0) chunkSize = 16; if (m_extraParametersSize > 0) return chunkSize + 2 + m_extraParametersSize; else return chunkSize; } set { throw new NotImplementedException(); } } /// /// Gets the length of . /// public override int BinaryLength { get { return base.BinaryLength + ChunkSize; } } /// /// Gets or sets audio format used by the . /// /// /// PCM = 1 (i.e., linear quantization), values other than 1 typically indicate some form of compression. /// See enumeration for more details. /// [CLSCompliant(false)] public ushort AudioFormat { get { return m_audioFormat; } set { m_audioFormat = value; } } /// /// Gets or sets number of audio channels in the . /// /// /// This property defines the number of channels (e.g., mono = 1, stereo = 2, etc.) defined /// in each sample block. See enumeration for more details. /// public short Channels { get { return m_channels; } set { m_channels = value; UpdateByteRate(); UpdateBlockAlignment(); } } /// /// Gets or sets the sample rate (i.e., the number of samples per second) defined in the . /// /// /// This property defines the number of samples per second defined in each second of data in /// the . See enumeraion for more details. /// public int SampleRate { get { return m_sampleRate; } set { m_sampleRate = value; UpdateByteRate(); } } /// /// Gets or sets the byte rate used for buffer estimation. /// /// /// /// This property is not usually changed. It will be automatically calculated for new wave files. /// /// /// This is typically just the arithmetic result of: /// * * / 8. /// However, this value can be changed as needed to accomodate better buffer estimations during /// data read cycle. /// /// public int ByteRate { get { return m_byteRate; } set { m_byteRate = value; } } /// /// Gets or sets the block size of a complete sample of data (i.e., samples for all channels of data at /// one instant in time). /// /// /// /// This property is not usually changed. It will be automatically calculated for new wave files. /// /// /// This is typically just the arithmetic result of: /// * / 8. /// However, this value can be changed as needed to accomodate even block-alignment of non-standard /// values. /// /// public short BlockAlignment { get { return m_blockAlignment; } set { m_blockAlignment = value; } } /// /// Gets or sets number of bits-per-sample in the . /// /// /// This property defines the number of bits-per-sample (e.g., 8, 16, 24, 32, etc.) used /// by each sample in a block of samples - effectively the data sample size. See /// enumeration for more details. /// public short BitsPerSample { get { return m_bitsPerSample; } set { m_bitsPerSample = value; UpdateByteRate(); UpdateBlockAlignment(); } } /// /// Gets the size of the buffer, if defined. /// public short ExtraParametersSize { get { return m_extraParametersSize; } } /// /// Gets or sets any extra parameters defined in the format header of the . /// /// /// See the class for an example of usage of this property. /// public byte[] ExtraParameters { get { return m_extraParameters; } set { m_extraParameters = value; if ((object)m_extraParameters == null) m_extraParametersSize = 0; else m_extraParametersSize = (short)m_extraParameters.Length; } } #endregion #region [ Methods ] /// /// Parses object by parsing the specified containing a binary image. /// /// Buffer containing binary image to parse. /// 0-based starting index in the to start parsing. /// Valid number of bytes within from . /// The number of bytes used for initialization in the (i.e., the number of bytes parsed). /// WAVE format section too small, wave file corrupted. /// is null. /// /// or is less than 0 -or- /// and will exceed length. /// public int ParseBinaryImage(byte[] buffer, int startIndex, int length) { buffer.ValidateParameters(startIndex, length); if (length < ChunkSize) throw new InvalidOperationException("WAVE format section too small, wave file corrupted"); m_audioFormat = EndianOrder.LittleEndian.ToUInt16(buffer, 0); m_channels = EndianOrder.LittleEndian.ToInt16(buffer, 2); m_sampleRate = EndianOrder.LittleEndian.ToInt32(buffer, 4); m_byteRate = EndianOrder.LittleEndian.ToInt32(buffer, 8); m_blockAlignment = EndianOrder.LittleEndian.ToInt16(buffer, 12); m_bitsPerSample = EndianOrder.LittleEndian.ToInt16(buffer, 14); if (m_bitsPerSample % 8 != 0) throw new InvalidDataException("Invalid bit rate encountered - wave file bit rates must be a multiple of 8"); if (length > 16) { m_extraParametersSize = EndianOrder.LittleEndian.ToInt16(buffer, 16); return 18; } return 16; } /// /// Generates a binary representation of this and copies it into the given buffer. /// /// Buffer used to hold generated binary image of the source object. /// 0-based starting index in the to start writing. /// The number of bytes written to the . /// is null. /// /// or is less than 0 -or- /// and will exceed length. /// public override int GenerateBinaryImage(byte[] buffer, int startIndex) { int length = BinaryLength; buffer.ValidateParameters(startIndex, length); startIndex += base.GenerateBinaryImage(buffer, startIndex); EndianOrder.LittleEndian.CopyBytes(m_audioFormat, buffer, startIndex); EndianOrder.LittleEndian.CopyBytes(m_channels, buffer, startIndex + 2); EndianOrder.LittleEndian.CopyBytes(m_sampleRate, buffer, startIndex + 4); EndianOrder.LittleEndian.CopyBytes(m_byteRate, buffer, startIndex + 8); EndianOrder.LittleEndian.CopyBytes(m_blockAlignment, buffer, startIndex + 12); EndianOrder.LittleEndian.CopyBytes(m_bitsPerSample, buffer, startIndex + 14); startIndex += 16; if (m_extraParametersSize > 0) { EndianOrder.LittleEndian.CopyBytes(m_extraParametersSize, buffer, startIndex); startIndex += 2; if (m_extraParametersSize > 0 && (object)m_extraParameters != null) { Buffer.BlockCopy(m_extraParameters, 0, buffer, startIndex, m_extraParametersSize); startIndex += m_extraParametersSize; } } return length; } /// /// Creates a copy of the . /// /// A new copy of the . public new WaveFormatChunk Clone() { WaveFormatChunk waveFormatChunk = new WaveFormatChunk(m_sampleRate, m_bitsPerSample, m_channels, m_audioFormat); if ((object)m_extraParameters != null) { byte[] extraParameters = new byte[m_extraParameters.Length]; Buffer.BlockCopy(m_extraParameters, 0, extraParameters, 0, m_extraParameters.Length); waveFormatChunk.ExtraParameters = extraParameters; } return waveFormatChunk; } /// /// Determines sample data type code based on defined /// and . /// /// /// Sample type code based on defined and /// . /// public TypeCode GetSampleTypeCode() { // Determine sample data type based on bit size and audio format switch (m_bitsPerSample) { case 8: return TypeCode.Byte; case 16: return TypeCode.Int16; case 24: // .NET does not define an Int24 type code and since an Int24 will // fit inside an Int32, the Int32 type code is returned. return TypeCode.Int32; case 32: if (m_audioFormat == (ushort)WaveFormat.IeeeFloat) return TypeCode.Single; else return TypeCode.Int32; case 64: if (m_audioFormat == (ushort)WaveFormat.IeeeFloat) return TypeCode.Double; else return TypeCode.Int64; default: // Unable to determine proper type code, consumer may be using a special data format... return TypeCode.Empty; } } /// /// Casts sample value to its equivalent native type based on defined /// and . /// /// Sample value. /// /// Sample value cast to its equivalent native type based on defined /// and . /// public LittleBinaryValue CastSample(double sample) { // Cast sample value to appropriate data type based on bit size switch (m_bitsPerSample) { case 8: // Bytes are unsigned and need 128 byte offset return (Byte)(sample + 128); case 16: return (Int16)sample; case 24: return (Int24)sample; case 32: if (m_audioFormat == (ushort)WaveFormat.IeeeFloat) return (Single)sample; else return (Int32)sample; case 64: if (m_audioFormat == (ushort)WaveFormat.IeeeFloat) return (Double)sample; else return (Int64)sample; default: throw new InvalidOperationException(string.Format("Cannot cast sample \'{0}\' into {1}-bits.", sample, BitsPerSample)); } } private void UpdateByteRate() { m_byteRate = m_sampleRate * m_channels * (m_bitsPerSample / 8); } private void UpdateBlockAlignment() { m_blockAlignment = (short)(m_channels * (m_bitsPerSample / 8)); } #endregion } }