diff --git a/Assets/Plugins/NAudio.Vorbis.meta b/Assets/Plugins/NAudio.Vorbis.meta new file mode 100644 index 000000000..511d0c43d --- /dev/null +++ b/Assets/Plugins/NAudio.Vorbis.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 48c03a97d634e7340a6530b0e9f0bf2d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NAudio.Vorbis/EndOfStreamEventArgs.cs b/Assets/Plugins/NAudio.Vorbis/EndOfStreamEventArgs.cs new file mode 100644 index 000000000..c5e4614af --- /dev/null +++ b/Assets/Plugins/NAudio.Vorbis/EndOfStreamEventArgs.cs @@ -0,0 +1,26 @@ +using System; + +namespace NAudio.Vorbis +{ + /// + /// Arguments for the EndOfStream event. + /// + [Serializable] + public class EndOfStreamEventArgs : EventArgs + { + /// + /// Creates a new instance of . + /// + public EndOfStreamEventArgs() { } + + /// + /// Gets or sets whether to auto-advance to the next stream. + /// + public bool AdvanceToNextStream { get; set; } + + /// + /// Gets or sets whether to remember the ended stream or dispose and remove it from the list. + /// + public bool KeepStream { get; set; } = true; + } +} diff --git a/Assets/Plugins/NAudio.Vorbis/EndOfStreamEventArgs.cs.meta b/Assets/Plugins/NAudio.Vorbis/EndOfStreamEventArgs.cs.meta new file mode 100644 index 000000000..47c1f990b --- /dev/null +++ b/Assets/Plugins/NAudio.Vorbis/EndOfStreamEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9c0272a97d0141e4cb696486a3ffe7d4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NAudio.Vorbis/NAudio.Vorbis.csproj.meta b/Assets/Plugins/NAudio.Vorbis/NAudio.Vorbis.csproj.meta new file mode 100644 index 000000000..2e591edfe --- /dev/null +++ b/Assets/Plugins/NAudio.Vorbis/NAudio.Vorbis.csproj.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 439a40688fad3804da940a77ea55709a +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NAudio.Vorbis/VorbisSampleProvider.cs b/Assets/Plugins/NAudio.Vorbis/VorbisSampleProvider.cs new file mode 100644 index 000000000..32ab97c2b --- /dev/null +++ b/Assets/Plugins/NAudio.Vorbis/VorbisSampleProvider.cs @@ -0,0 +1,406 @@ +using NAudio.Wave; +using NVorbis.Contracts; +using System; +using System.Collections.Generic; + +namespace NAudio.Vorbis +{ + /// + /// Implements for NVorbis. + /// + public sealed class VorbisSampleProvider : ISampleProvider, IDisposable + { + private IContainerReader _containerReader; + private IStreamDecoder _streamDecoder; + private readonly LinkedList _streamDecoders = new LinkedList(); + private bool _hasEnded; + + /// + /// Gets the number of streams currently known by this instance. + /// + public int StreamCount => _streamDecoders.Count; + + /// + /// Gets the of the current stream. + /// + public WaveFormat WaveFormat { get; private set; } + + /// + /// Gets the position of the current stream, in samples. + /// + public long SamplePosition => _streamDecoder.SamplePosition; + + /// + /// Gets whether the current stream can seek. + /// + public bool CanSeek { get; } + + /// + /// Gets the length of the current stream, in samples. + /// + public long Length => _streamDecoder.TotalSamples; + + /// + /// Gets the instance for the current stream. + /// + public IStreamStats Stats => _streamDecoder.Stats; + + /// + /// Gets the instance for the current stream. + /// + public ITagData Tags => _streamDecoder.Tags; + + /// + /// Gets the encoder's upper bitrate of the current selected Vorbis stream + /// + public int UpperBitrate => _streamDecoder.UpperBitrate; + + /// + /// Gets the encoder's nominal bitrate of the current selected Vorbis stream + /// + public int NominalBitrate => _streamDecoder.NominalBitrate; + + /// + /// Gets the encoder's lower bitrate of the current selected Vorbis stream + /// + public int LowerBitrate => _streamDecoder.LowerBitrate; + + /// + /// Raised when the current stream has been fully read. + /// + public event EventHandler EndOfStream; + + /// + /// Raised when a new stream is selected that has a different than the previous stream. + /// + public event EventHandler WaveFormatChange; + + /// + /// Raised when a new stream is selected. + /// + public event EventHandler StreamChange; + + private bool ProcessNewStream(IPacketProvider packetProvider) + { + IStreamDecoder decoder; + try + { + decoder = new NVorbis.StreamDecoder(packetProvider); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) + { + // an exception here probably means the packet provider returned non-Vorbis data, so warn and reject the stream + System.Diagnostics.Trace.TraceWarning($"Could not load stream {packetProvider.StreamSerial} due to error: {ex.Message}"); + return false; + } +#pragma warning restore CA1031 // Do not catch general exception types + _streamDecoders.AddLast(decoder); + return true; + } + + private bool? GetNextDecoder(bool keepOldDecoder) + { + // look for the next unplayed decoder after our current decoder + LinkedListNode node; + if (_streamDecoder == null) + { + // first stream... + node = _streamDecoders.First; + } + else + { + node = _streamDecoders.Find(_streamDecoder); + while (node != null && node.Value.IsEndOfStream) + { + node = node.Next; + } + } + + // clean up and remove the old decoder if we're not keeping it + if (!keepOldDecoder) + { + _streamDecoders.Remove(_streamDecoder); + _streamDecoder.Dispose(); + } + + // finally, if we still don't have a valid decoder, try to find a new stream in the container + if (node == null && FindNextStream()) + { + node = _streamDecoders.Last; + } + + // switch to the new decoder, if one was found + if (node != null) + { + return SwitchToDecoder(node.Value); + } + return null; + } + + private bool SwitchToDecoder(IStreamDecoder nextDecoder) + { + _streamDecoder = nextDecoder; + _hasEnded = false; + + var channels = WaveFormat?.Channels; + var sampleRate = WaveFormat?.SampleRate; + WaveFormat = WaveFormat.CreateIeeeFloatWaveFormat(_streamDecoder.SampleRate, _streamDecoder.Channels); + + if ((channels ?? WaveFormat.Channels) != WaveFormat.Channels || (sampleRate ?? WaveFormat.SampleRate) != WaveFormat.SampleRate) + { + WaveFormatChange?.Invoke(this, EventArgs.Empty); + return true; + } + + StreamChange?.Invoke(this, EventArgs.Empty); + return false; + } + + delegate T NodeFoundAction(LinkedListNode node); + + private T FindStreamNode(int index, NodeFoundAction action) + { + if (_containerReader == null) throw new InvalidOperationException("Cannot operate on more than the current stream if not loaded from stream!"); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); + + var node = _streamDecoders.First; + var count = -1; + while (++count < index) + { + if (node.Next == null && !FindNextStream()) + { + throw new ArgumentOutOfRangeException(nameof(index)); + } + + node = node.Next; + } + return action(node); + } + + private bool ForgetStreamAction(LinkedListNode node) + { + node.Value.Dispose(); + _streamDecoders.Remove(node); + return false; + } + + private bool SwitchStreamsAction(LinkedListNode node) + { + return SwitchToDecoder(node.Value); + } + + internal int GetCurrentStreamIndex() + { + var cnt = -1; + var node = _streamDecoders.First; + while (node != null) + { + ++cnt; + if (node.Value == _streamDecoder) + { + break; + } + node = node.Next; + } + return cnt; + } + + internal int? GetNextStreamIndex() + { + if (_containerReader == null) return null; + + var cnt = -1; + var node = _streamDecoders.First; + while (node != null) + { + ++cnt; + var sd = node.Value; + node = node.Next; + if (sd == _streamDecoder) + { + break; + } + } + if (node != null) + { + // if we have a node, that means we have at least one known stream after the current one + return cnt + 1; + } + + // if we get here, we're out of known streams... + + // if we don't need the current stream or the container can seek, we can try for more... + if (_containerReader.CanSeek || _streamDecoder.IsEndOfStream) + { + ++cnt; + while (_containerReader.FindNextStream()) + { + if (_streamDecoders.Count > cnt) + { + return cnt; + } + } + } + + // no more streams + return null; + } + + /// + /// Creates a new instance of . + /// + /// The stream to read for data. + public VorbisSampleProvider(System.IO.Stream sourceStream, bool closeOnDispose = false) + { + _containerReader = new NVorbis.Ogg.ContainerReader(sourceStream, closeOnDispose) + { + NewStreamCallback = ProcessNewStream + }; + CanSeek = _containerReader.CanSeek; + if (!_containerReader.TryInit()) throw new ArgumentException("Could not initialize container!"); + + if (!GetNextDecoder(true).HasValue) + { + throw new InvalidOperationException("Container initialized, but no stream found?"); + } + } + + /// + /// Creates a new instance of that will attempt to use the specified to decode audio. + /// + /// + public VorbisSampleProvider(IPacketProvider packetProvider) + : this(new NVorbis.StreamDecoder(packetProvider), packetProvider.CanSeek) + { + } + + /// + /// Creates a new instance of that will read from a single specified decoder stream. + /// + /// The decoder to read from. + /// Sets whether to allow seek operations to be attempted on this stream. Note that setting this to + /// when the underlying stream doesn't support it will still generate an exception from the decoder when attempting seek operations. + public VorbisSampleProvider(IStreamDecoder streamDecoder, bool allowSeek) + { + _streamDecoders.AddLast(streamDecoder); + SwitchToDecoder(streamDecoder); + CanSeek = allowSeek; + } + + /// + /// Reads decoded audio data from the current stream. + /// + /// The buffer to write the data to. + /// The offset into to start writing data. + /// The number of values to write. This must be a multiple of . + /// The number of values writte to . + public int Read(float[] buffer, int offset, int count) + { + if (_streamDecoder.IsEndOfStream) + { + if (_hasEnded) + { + // we've ended and don't have any data, so just bail + return 0; + } + + var eosea = new EndOfStreamEventArgs(); + EndOfStream?.Invoke(this, eosea); + _hasEnded = true; + if (eosea.AdvanceToNextStream) + { + var formatChanged = GetNextDecoder(eosea.KeepStream); + if (formatChanged ?? true) + { + return 0; + } + } + } + + return _streamDecoder.Read(buffer, offset, count); + } + + /// + /// Seeks the current stream to the sample position specified. + /// + /// The sample position to seek to. + /// The sample position seeked to. + public long Seek(long samplePosition) + { + if (!CanSeek) throw new InvalidOperationException("Cannot seek underlying stream!"); + if (samplePosition < 0 || samplePosition > _streamDecoder.TotalSamples) throw new ArgumentOutOfRangeException(nameof(samplePosition)); + + _streamDecoder.SeekTo(samplePosition); + + return _streamDecoder.SamplePosition; + } + + /// + /// Removes the stream at the index specified from the internal list and cleans up its resources. + /// + /// The index to remove + public void RemoveStream(int index) => FindStreamNode(index, ForgetStreamAction); + + /// + /// Switches to the stream index specified. + /// + /// The index to switch to. + /// if the newly-selected decoder has a different sample rate or number of channels than the previous one. Otherwise, . + public bool SwitchStreams(int index) => FindStreamNode(index, SwitchStreamsAction); + + /// + /// Finds all available streams in the container. + /// + public void FindAllStreams() + { + if (!CanSeek) + { + if (_containerReader == null) throw new InvalidOperationException("No container loaded!"); + throw new InvalidOperationException("Cannot seek container! Will discover streams as they are encountered."); + } + + while (_containerReader.FindNextStream()) + { + } + } + + /// + /// Finds the next available stream in the container. + /// + /// if another Vorbis stream was found, otherwise . + public bool FindNextStream() + { + if (_containerReader?.CanSeek ?? false) + { + var lastStream = _streamDecoders.Last?.Value; + while (_containerReader.FindNextStream() && lastStream == _streamDecoders.Last.Value) + { + } + return _streamDecoders.Last != null && lastStream != _streamDecoders.Last.Value; + } + return false; + } + + /// + /// Cleans up resources used by this instance. + /// + public void Dispose() + { + var foundCurrent = false; + foreach (var decoder in _streamDecoders) + { + foundCurrent |= decoder == _streamDecoder; + decoder.Dispose(); + } + _streamDecoders.Clear(); + if (!foundCurrent) + { + _streamDecoder.Dispose(); + } + + _containerReader?.Dispose(); + _containerReader = null; + } + } +} diff --git a/Assets/Plugins/NAudio.Vorbis/VorbisSampleProvider.cs.meta b/Assets/Plugins/NAudio.Vorbis/VorbisSampleProvider.cs.meta new file mode 100644 index 000000000..937afa170 --- /dev/null +++ b/Assets/Plugins/NAudio.Vorbis/VorbisSampleProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d92daf34675e714439f3ad19912cae91 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NAudio.Vorbis/VorbisWaveReader.cs b/Assets/Plugins/NAudio.Vorbis/VorbisWaveReader.cs new file mode 100644 index 000000000..53d401af1 --- /dev/null +++ b/Assets/Plugins/NAudio.Vorbis/VorbisWaveReader.cs @@ -0,0 +1,152 @@ +using System; +using System.Linq; + +namespace NAudio.Vorbis +{ + public class VorbisWaveReader : Wave.WaveStream, Wave.ISampleProvider + { + VorbisSampleProvider _sampleProvider; + + public VorbisWaveReader(string fileName) + : this(System.IO.File.OpenRead(fileName), true) + { + } + + public VorbisWaveReader(System.IO.Stream sourceStream, bool closeOnDispose = false) + { + // To maintain consistent semantics with v1.1, we don't expose the events and auto-advance / stream removal features of VorbisSampleProvider. + // If one wishes to use those features, they should really use VorbisSampleProvider directly... + _sampleProvider = new VorbisSampleProvider(sourceStream, closeOnDispose); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _sampleProvider?.Dispose(); + _sampleProvider = null; + } + + base.Dispose(disposing); + } + + public override Wave.WaveFormat WaveFormat => _sampleProvider.WaveFormat; + + public override long Length => _sampleProvider.Length * _sampleProvider.WaveFormat.BlockAlign; + + public override long Position + { + get => _sampleProvider.SamplePosition * _sampleProvider.WaveFormat.BlockAlign; + set + { + if (!_sampleProvider.CanSeek) throw new InvalidOperationException("Cannot seek!"); + if (value < 0 || value > Length) throw new ArgumentOutOfRangeException(nameof(value)); + + _sampleProvider.Seek(value / _sampleProvider.WaveFormat.BlockAlign); + } + } + + // This buffer can be static because it can only be used by 1 instance per thread + [ThreadStatic] + static float[] _conversionBuffer = null; + + public override int Read(byte[] buffer, int offset, int count) + { + // adjust count so it is in floats instead of bytes + count /= sizeof(float); + + // make sure we don't have an odd count + count -= count % _sampleProvider.WaveFormat.Channels; + + // get the buffer, creating a new one if none exists or the existing one is too small + var cb = _conversionBuffer ?? (_conversionBuffer = new float[count]); + if (cb.Length < count) + { + cb = (_conversionBuffer = new float[count]); + } + + // let Read(float[], int, int) do the actual reading; adjust count back to bytes + int cnt = Read(cb, 0, count) * sizeof(float); + + // move the data back to the request buffer + Buffer.BlockCopy(cb, 0, buffer, offset, cnt); + + // done! + return cnt; + } + + public int Read(float[] buffer, int offset, int count) + { + if (IsParameterChange) throw new InvalidOperationException("A parameter change is pending. Call ClearParameterChange() to clear it."); + + return _sampleProvider.Read(buffer, offset, count); + } + + [Obsolete("Was never used and will be removed.")] + public bool IsParameterChange => false; + + [Obsolete("Was never used and will be removed.")] + public void ClearParameterChange() { } + + public int StreamCount => _sampleProvider.StreamCount; + + public int? NextStreamIndex { get; set; } + + public bool GetNextStreamIndex() + { + if (!NextStreamIndex.HasValue) + { + NextStreamIndex = _sampleProvider.GetNextStreamIndex(); + return NextStreamIndex.HasValue; + } + return false; + } + + public int CurrentStream + { + get => _sampleProvider.GetCurrentStreamIndex(); + set + { + _sampleProvider.SwitchStreams(value); + + NextStreamIndex = null; + } + } + + /// + /// Gets the encoder's upper bitrate of the current selected Vorbis stream + /// + public int UpperBitrate => _sampleProvider.UpperBitrate; + + /// + /// Gets the encoder's nominal bitrate of the current selected Vorbis stream + /// + public int NominalBitrate => _sampleProvider.NominalBitrate; + + /// + /// Gets the encoder's lower bitrate of the current selected Vorbis stream + /// + public int LowerBitrate => _sampleProvider.LowerBitrate; + + /// + /// Gets the encoder's vendor string for the current selected Vorbis stream + /// + public string Vendor => _sampleProvider.Tags.EncoderVendor; + + /// + /// Gets the comments in the current selected Vorbis stream + /// + public string[] Comments => _sampleProvider.Tags.All.SelectMany(k => k.Value, (kvp, Item) => $"{kvp.Key}={Item}").ToArray(); + + /// + /// Gets the number of bits read that are related to framing and transport alone + /// + [Obsolete("No longer supported.", true)] + public long ContainerOverheadBits => throw new NotSupportedException(); + + /// + /// Gets stats from each decoder stream available + /// + public NVorbis.Contracts.IStreamStats[] Stats => new[] { _sampleProvider.Stats }; + } +} diff --git a/Assets/Plugins/NAudio.Vorbis/VorbisWaveReader.cs.meta b/Assets/Plugins/NAudio.Vorbis/VorbisWaveReader.cs.meta new file mode 100644 index 000000000..15f88b258 --- /dev/null +++ b/Assets/Plugins/NAudio.Vorbis/VorbisWaveReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 034bab70ad6171b47ac74f810d000213 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NAudio.dll b/Assets/Plugins/NAudio.dll new file mode 100644 index 000000000..84643f17c Binary files /dev/null and b/Assets/Plugins/NAudio.dll differ diff --git a/Assets/Plugins/NAudio.dll.meta b/Assets/Plugins/NAudio.dll.meta new file mode 100644 index 000000000..16b0b3953 --- /dev/null +++ b/Assets/Plugins/NAudio.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: b34c82ff57051124391a84fb17ef920d +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NAudio.xml b/Assets/Plugins/NAudio.xml new file mode 100644 index 000000000..39108b5b1 --- /dev/null +++ b/Assets/Plugins/NAudio.xml @@ -0,0 +1,22556 @@ + + + + NAudio + + + + + a-law decoder + based on code from: + http://hazelware.luggle.com/tutorials/mulawcompression.html + + + + + only 512 bytes required, so just use a lookup + + + + + Converts an a-law encoded byte to a 16 bit linear sample + + a-law encoded byte + Linear sample + + + + A-law encoder + + + + + Encodes a single 16 bit sample to a-law + + 16 bit PCM sample + a-law encoded byte + + + + SpanDSP - a series of DSP components for telephony + + g722_decode.c - The ITU G.722 codec, decode part. + + Written by Steve Underwood <steveu@coppice.org> + + Copyright (C) 2005 Steve Underwood + Ported to C# by Mark Heath 2011 + + Despite my general liking of the GPL, I place my own contributions + to this code in the public domain for the benefit of all mankind - + even the slimy ones who might try to proprietize my work and use it + to my detriment. + + Based in part on a single channel G.722 codec which is: + Copyright (c) CMU 1993 + Computer Science, Speech Group + Chengxiang Lu and Alex Hauptmann + + + + + hard limits to 16 bit samples + + + + + Decodes a buffer of G722 + + Codec state + Output buffer (to contain decompressed PCM samples) + + Number of bytes in input G722 data to decode + Number of samples written into output buffer + + + + Encodes a buffer of G722 + + Codec state + Output buffer (to contain encoded G722) + PCM 16 bit samples to encode + Number of samples in the input buffer to encode + Number of encoded bytes written into output buffer + + + + Stores state to be used between calls to Encode or Decode + + + + + ITU Test Mode + TRUE if the operating in the special ITU test mode, with the band split filters disabled. + + + + + TRUE if the G.722 data is packed + + + + + 8kHz Sampling + TRUE if encode from 8k samples/second + + + + + Bits Per Sample + 6 for 48000kbps, 7 for 56000kbps, or 8 for 64000kbps. + + + + + Signal history for the QMF (x) + + + + + Band + + + + + In bit buffer + + + + + Number of bits in InBuffer + + + + + Out bit buffer + + + + + Number of bits in OutBuffer + + + + + Creates a new instance of G722 Codec State for a + new encode or decode session + + Bitrate (typically 64000) + Special options + + + + Band data for G722 Codec + + + + s + + + sp + + + sz + + + r + + + a + + + ap + + + p + + + d + + + b + + + bp + + + sg + + + nb + + + det + + + + G722 Flags + + + + + None + + + + + Using a G722 sample rate of 8000 + + + + + Packed + + + + + mu-law decoder + based on code from: + http://hazelware.luggle.com/tutorials/mulawcompression.html + + + + + only 512 bytes required, so just use a lookup + + + + + Converts a mu-law encoded byte to a 16 bit linear sample + + mu-law encoded byte + Linear sample + + + + mu-law encoder + based on code from: + http://hazelware.luggle.com/tutorials/mulawcompression.html + + + + + Encodes a single 16 bit sample to mu-law + + 16 bit PCM sample + mu-law encoded byte + + + + Audio Capture Client + + + + + Gets a pointer to the buffer + + Pointer to the buffer + + + + Gets a pointer to the buffer + + Number of frames to read + Buffer flags + Pointer to the buffer + + + + Gets the size of the next packet + + + + + Release buffer + + Number of frames written + + + + Release the COM object + + + + + Windows CoreAudio AudioClient + + + + + Retrieves the stream format that the audio engine uses for its internal processing of shared-mode streams. + Can be called before initialize + + + + + Initializes the Audio Client + + Share Mode + Stream Flags + Buffer Duration + Periodicity + Wave Format + Audio Session GUID (can be null) + + + + Retrieves the size (maximum capacity) of the audio buffer associated with the endpoint. (must initialize first) + + + + + Retrieves the maximum latency for the current stream and can be called any time after the stream has been initialized. + + + + + Retrieves the number of frames of padding in the endpoint buffer (must initialize first) + + + + + Retrieves the length of the periodic interval separating successive processing passes by the audio engine on the data in the endpoint buffer. + (can be called before initialize) + + + + + Gets the minimum device period + (can be called before initialize) + + + + + Returns the AudioStreamVolume service for this AudioClient. + + + This returns the AudioStreamVolume object ONLY for shared audio streams. + + + This is thrown when an exclusive audio stream is being used. + + + + + Gets the AudioClockClient service + + + + + Gets the AudioRenderClient service + + + + + Gets the AudioCaptureClient service + + + + + Determines whether if the specified output format is supported + + The share mode. + The desired format. + True if the format is supported + + + + Determines if the specified output format is supported in shared mode + + Share Mode + Desired Format + Output The closest match format. + True if the format is supported + + + + Starts the audio stream + + + + + Stops the audio stream. + + + + + Set the Event Handle for buffer synchro. + + The Wait Handle to setup + + + + Resets the audio stream + Reset is a control method that the client calls to reset a stopped audio stream. + Resetting the stream flushes all pending data and resets the audio clock stream + position to 0. This method fails if it is called on a stream that is not stopped + + + + + Dispose + + + + + Audio Client Buffer Flags + + + + + None + + + + + AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY + + + + + AUDCLNT_BUFFERFLAGS_SILENT + + + + + AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR + + + + + The AudioClientProperties structure is used to set the parameters that describe the properties of the client's audio stream. + + http://msdn.microsoft.com/en-us/library/windows/desktop/hh968105(v=vs.85).aspx + + + + The size of the buffer for the audio stream. + + + + + Boolean value to indicate whether or not the audio stream is hardware-offloaded + + + + + An enumeration that is used to specify the category of the audio stream. + + + + + A bit-field describing the characteristics of the stream. Supported in Windows 8.1 and later. + + + + + AUDCLNT_SHAREMODE + + + + + AUDCLNT_SHAREMODE_SHARED, + + + + + AUDCLNT_SHAREMODE_EXCLUSIVE + + + + + AUDCLNT_STREAMFLAGS + + + + + None + + + + + AUDCLNT_STREAMFLAGS_CROSSPROCESS + + + + + AUDCLNT_STREAMFLAGS_LOOPBACK + + + + + AUDCLNT_STREAMFLAGS_EVENTCALLBACK + + + + + AUDCLNT_STREAMFLAGS_NOPERSIST + + + + + Defines values that describe the characteristics of an audio stream. + + + + + No stream options. + + + + + The audio stream is a 'raw' stream that bypasses all signal processing except for endpoint specific, always-on processing in the APO, driver, and hardware. + + + + + Audio Clock Client + + + + + Characteristics + + + + + Frequency + + + + + Get Position + + + + + Adjusted Position + + + + + Can Adjust Position + + + + + Dispose + + + + + Audio Endpoint Volume Channel + + + + + GUID to pass to AudioEndpointVolumeCallback + + + + + Volume Level + + + + + Volume Level Scalar + + + + + Audio Endpoint Volume Channels + + + + + Channel Count + + + + + Indexer - get a specific channel + + + + + Audio Endpoint Volume Notifiaction Delegate + + Audio Volume Notification Data + + + + Audio Endpoint Volume Step Information + + + + + Step + + + + + StepCount + + + + + Audio Endpoint Volume Volume Range + + + + + Minimum Decibels + + + + + Maximum Decibels + + + + + Increment Decibels + + + + + Audio Meter Information Channels + + + + + Metering Channel Count + + + + + Get Peak value + + Channel index + Peak value + + + + Audio Render Client + + + + + Gets a pointer to the buffer + + Number of frames requested + Pointer to the buffer + + + + Release buffer + + Number of frames written + Buffer flags + + + + Release the COM object + + + + + AudioSessionControl object for information + regarding an audio session + + + + + Constructor. + + + + + + Dispose + + + + + Finalizer + + + + + Audio meter information of the audio session. + + + + + Simple audio volume of the audio session (for volume and mute status). + + + + + The current state of the audio session. + + + + + The name of the audio session. + + + + + the path to the icon shown in the mixer. + + + + + The session identifier of the audio session. + + + + + The session instance identifier of the audio session. + + + + + The process identifier of the audio session. + + + + + Is the session a system sounds session. + + + + + the grouping param for an audio session grouping + + + + + + For chanigng the grouping param and supplying the context of said change + + + + + + + Registers an even client for callbacks + + + + + + Unregisters an event client from receiving callbacks + + + + + + AudioSessionEvents callback implementation + + + + + Constructor. + + + + + + Notifies the client that the display name for the session has changed. + + The new display name for the session. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the display icon for the session has changed. + + The path for the new display icon for the session. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the volume level or muting state of the session has changed. + + The new volume level for the audio session. + The new muting state. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the volume level of an audio channel in the session submix has changed. + + The channel count. + An array of volumnes cooresponding with each channel index. + The number of the channel whose volume level changed. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the grouping parameter for the session has changed. + + The new grouping parameter for the session. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the stream-activity state of the session has changed. + + The new session state. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the session has been disconnected. + + The reason that the audio session was disconnected. + An HRESULT code indicating whether the operation succeeded of failed. + + + + AudioSessionManager + + Designed to manage audio sessions and in particuar the + SimpleAudioVolume interface to adjust a session volume + + + + + + + + + + + + Occurs when audio session has been added (for example run another program that use audio playback). + + + + + SimpleAudioVolume object + for adjusting the volume for the user session + + + + + AudioSessionControl object + for registring for callbacks and other session information + + + + + Refresh session of current device. + + + + + Returns list of sessions of current device. + + + + + Dispose. + + + + + Finalizer. + + + + + Specifies the category of an audio stream. + + + + + Other audio stream. + + + + + Media that will only stream when the app is in the foreground. + + + + + Media that can be streamed when the app is in the background. + + + + + Real-time communications, such as VOIP or chat. + + + + + Alert sounds. + + + + + Sound effects. + + + + + Game sound effects. + + + + + Background audio for games. + + + + + Manages the AudioStreamVolume for the . + + + + + Verify that the channel index is valid. + + + + + + + Return the current stream volumes for all channels + + An array of volume levels between 0.0 and 1.0 for each channel in the audio stream. + + + + Returns the current number of channels in this audio stream. + + + + + Return the current volume for the requested channel. + + The 0 based index into the channels. + The volume level for the channel between 0.0 and 1.0. + + + + Set the volume level for each channel of the audio stream. + + An array of volume levels (between 0.0 and 1.0) one for each channel. + + A volume level MUST be supplied for reach channel in the audio stream. + + + Thrown when does not contain elements. + + + + + Sets the volume level for one channel in the audio stream. + + The 0-based index into the channels to adjust the volume of. + The volume level between 0.0 and 1.0 for this channel of the audio stream. + + + + Dispose + + + + + Release/cleanup objects during Dispose/finalization. + + True if disposing and false if being finalized. + + + + Audio Volume Notification Data + + + + + Event Context + + + + + Muted + + + + + Guid that raised the event + + + + + Master Volume + + + + + Channels + + + + + Channel Volume + + + + + Audio Volume Notification Data + + + + + + + + + + Audio Client WASAPI Error Codes (HResult) + + + + + AUDCLNT_E_NOT_INITIALIZED + + + + + AUDCLNT_E_UNSUPPORTED_FORMAT + + + + + AUDCLNT_E_DEVICE_IN_USE + + + + + AUDCLNT_E_RESOURCES_INVALIDATED + + + + + Defined in AudioClient.h + + + + + Defined in AudioClient.h + + + + + Windows CoreAudio IAudioSessionControl interface + Defined in AudioPolicy.h + + + + + Retrieves the current state of the audio session. + + Receives the current session state. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the display name for the audio session. + + Receives a string that contains the display name. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Assigns a display name to the current audio session. + + A string that contains the new display name for the session. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the path for the display icon for the audio session. + + Receives a string that specifies the fully qualified path of the file that contains the icon. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Assigns a display icon to the current session. + + A string that specifies the fully qualified path of the file that contains the new icon. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the grouping parameter of the audio session. + + Receives the grouping parameter ID. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Assigns a session to a grouping of sessions. + + The new grouping parameter ID. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Registers the client to receive notifications of session events, including changes in the session state. + + A client-implemented interface. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Deletes a previous registration by the client to receive notifications. + + A client-implemented interface. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Windows CoreAudio IAudioSessionControl interface + Defined in AudioPolicy.h + + + + + Retrieves the current state of the audio session. + + Receives the current session state. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the display name for the audio session. + + Receives a string that contains the display name. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Assigns a display name to the current audio session. + + A string that contains the new display name for the session. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the path for the display icon for the audio session. + + Receives a string that specifies the fully qualified path of the file that contains the icon. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Assigns a display icon to the current session. + + A string that specifies the fully qualified path of the file that contains the new icon. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the grouping parameter of the audio session. + + Receives the grouping parameter ID. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Assigns a session to a grouping of sessions. + + The new grouping parameter ID. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Registers the client to receive notifications of session events, including changes in the session state. + + A client-implemented interface. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Deletes a previous registration by the client to receive notifications. + + A client-implemented interface. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the identifier for the audio session. + + Receives the session identifier. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the identifier of the audio session instance. + + Receives the identifier of a particular instance. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the process identifier of the audio session. + + Receives the process identifier of the audio session. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Indicates whether the session is a system sounds session. + + An HRESULT code indicating whether the operation succeeded of failed. + + + + Enables or disables the default stream attenuation experience (auto-ducking) provided by the system. + + A variable that enables or disables system auto-ducking. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Defines constants that indicate the current state of an audio session. + + + MSDN Reference: http://msdn.microsoft.com/en-us/library/dd370792.aspx + + + + + The audio session is inactive. + + + + + The audio session is active. + + + + + The audio session has expired. + + + + + Defines constants that indicate a reason for an audio session being disconnected. + + + MSDN Reference: Unknown + + + + + The user removed the audio endpoint device. + + + + + The Windows audio service has stopped. + + + + + The stream format changed for the device that the audio session is connected to. + + + + + The user logged off the WTS session that the audio session was running in. + + + + + The WTS session that the audio session was running in was disconnected. + + + + + The (shared-mode) audio session was disconnected to make the audio endpoint device available for an exclusive-mode connection. + + + + + Windows CoreAudio IAudioSessionControl interface + Defined in AudioPolicy.h + + + + + Notifies the client that the display name for the session has changed. + + The new display name for the session. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the display icon for the session has changed. + + The path for the new display icon for the session. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the volume level or muting state of the session has changed. + + The new volume level for the audio session. + The new muting state. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the volume level of an audio channel in the session submix has changed. + + The channel count. + An array of volumnes cooresponding with each channel index. + The number of the channel whose volume level changed. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the grouping parameter for the session has changed. + + The new grouping parameter for the session. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the stream-activity state of the session has changed. + + The new session state. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Notifies the client that the session has been disconnected. + + The reason that the audio session was disconnected. + An HRESULT code indicating whether the operation succeeded of failed. + + + + interface to receive session related events + + + + + notification of volume changes including muting of audio session + + the current volume + the current mute state, true muted, false otherwise + + + + notification of display name changed + + the current display name + + + + notification of icon path changed + + the current icon path + + + + notification of the client that the volume level of an audio channel in the session submix has changed + + The channel count. + An array of volumnes cooresponding with each channel index. + The number of the channel whose volume level changed. + + + + notification of the client that the grouping parameter for the session has changed + + >The new grouping parameter for the session. + + + + notification of the client that the stream-activity state of the session has changed + + The new session state. + + + + notification of the client that the session has been disconnected + + The reason that the audio session was disconnected. + + + + Windows CoreAudio IAudioSessionManager interface + Defined in AudioPolicy.h + + + + + Retrieves an audio session control. + + A new or existing session ID. + Audio session flags. + Receives an interface for the audio session. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves a simple audio volume control. + + A new or existing session ID. + Audio session flags. + Receives an interface for the audio session. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves an audio session control. + + A new or existing session ID. + Audio session flags. + Receives an interface for the audio session. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves a simple audio volume control. + + A new or existing session ID. + Audio session flags. + Receives an interface for the audio session. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Windows CoreAudio IAudioSessionNotification interface + Defined in AudioPolicy.h + + + + + + + session being added + An HRESULT code indicating whether the operation succeeded of failed. + + + + Windows CoreAudio ISimpleAudioVolume interface + Defined in AudioClient.h + + + + + Sets the master volume level for the audio session. + + The new volume level expressed as a normalized value between 0.0 and 1.0. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the client volume level for the audio session. + + Receives the volume level expressed as a normalized value between 0.0 and 1.0. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Sets the muting state for the audio session. + + The new muting state. + A user context value that is passed to the notification callback. + An HRESULT code indicating whether the operation succeeded of failed. + + + + Retrieves the current muting state for the audio session. + + Receives the muting state. + An HRESULT code indicating whether the operation succeeded of failed. + + + + is defined in WTypes.h + + + + + Windows CoreAudio IAudioClient interface + Defined in AudioClient.h + + + + + The GetBufferSize method retrieves the size (maximum capacity) of the endpoint buffer. + + + + + The GetService method accesses additional services from the audio client object. + + The interface ID for the requested service. + Pointer to a pointer variable into which the method writes the address of an instance of the requested interface. + + + + defined in MMDeviceAPI.h + + + + + IMMNotificationClient + + + + + Device State Changed + + + + + Device Added + + + + + Device Removed + + + + + Default Device Changed + + + + + Property Value Changed + + + + + + + is defined in propsys.h + + + + + implements IMMDeviceEnumerator + + + + + MMDevice STGM enumeration + + + + + from Propidl.h. + http://msdn.microsoft.com/en-us/library/aa380072(VS.85).aspx + contains a union so we have to do an explicit layout + + + + + Creates a new PropVariant containing a long value + + + + + Helper method to gets blob data + + + + + Interprets a blob as an array of structs + + + + + Gets the type of data in this PropVariant + + + + + Property value + + + + + allows freeing up memory, might turn this into a Dispose method? + + + + + Clears with a known pointer + + + + + Multimedia Device Collection + + + + + Device count + + + + + Get device by index + + Device index + Device at the specified index + + + + Get Enumerator + + Device enumerator + + + + Property Keys + + + + + PKEY_DeviceInterface_FriendlyName + + + + + PKEY_AudioEndpoint_FormFactor + + + + + PKEY_AudioEndpoint_ControlPanelPageProvider + + + + + PKEY_AudioEndpoint_Association + + + + + PKEY_AudioEndpoint_PhysicalSpeakers + + + + + PKEY_AudioEndpoint_GUID + + + + + PKEY_AudioEndpoint_Disable_SysFx + + + + + PKEY_AudioEndpoint_FullRangeSpeakers + + + + + PKEY_AudioEndpoint_Supports_EventDriven_Mode + + + + + PKEY_AudioEndpoint_JackSubType + + + + + PKEY_AudioEngine_DeviceFormat + + + + + PKEY_AudioEngine_OEMFormat + + + + + PKEY _Devie_FriendlyName + + + + + PKEY _Device_IconPath + + + + + Collection of sessions. + + + + + Returns session at index. + + + + + + + Number of current sessions. + + + + + Windows CoreAudio SimpleAudioVolume + + + + + Creates a new Audio endpoint volume + + ISimpleAudioVolume COM interface + + + + Dispose + + + + + Finalizer + + + + + Allows the user to adjust the volume from + 0.0 to 1.0 + + + + + Mute + + + + + Represents state of a capture device + + + + + Not recording + + + + + Beginning to record + + + + + Recording in progress + + + + + Requesting stop + + + + + Audio Capture using Wasapi + See http://msdn.microsoft.com/en-us/library/dd370800%28VS.85%29.aspx + + + + + Indicates recorded data is available + + + + + Indicates that all recorded data has now been received. + + + + + Initialises a new instance of the WASAPI capture class + + + + + Initialises a new instance of the WASAPI capture class + + Capture device to use + + + + Initializes a new instance of the class. + + The capture device. + true if sync is done with event. false use sleep. + + + + Initializes a new instance of the class. + + The capture device. + true if sync is done with event. false use sleep. + Length of the audio buffer in milliseconds. A lower value means lower latency but increased CPU usage. + + + + Share Mode - set before calling StartRecording + + + + + Current Capturing State + + + + + Capturing wave format + + + + + Gets the default audio capture device + + The default audio capture device + + + + To allow overrides to specify different flags (e.g. loopback) + + + + + Start Capturing + + + + + Stop Capturing (requests a stop, wait for RecordingStopped event to know it has finished) + + + + + Dispose + + + + + Audio Endpoint Volume + + + + + GUID to pass to AudioEndpointVolumeCallback + + + + + On Volume Notification + + + + + Volume Range + + + + + Hardware Support + + + + + Step Information + + + + + Channels + + + + + Master Volume Level + + + + + Master Volume Level Scalar + + + + + Mute + + + + + Volume Step Up + + + + + Volume Step Down + + + + + Creates a new Audio endpoint volume + + IAudioEndpointVolume COM interface + + + + Dispose + + + + + Finalizer + + + + + Audio Meter Information + + + + + Peak Values + + + + + Hardware Support + + + + + Master Peak Value + + + + + Device State + + + + + DEVICE_STATE_ACTIVE + + + + + DEVICE_STATE_DISABLED + + + + + DEVICE_STATE_NOTPRESENT + + + + + DEVICE_STATE_UNPLUGGED + + + + + DEVICE_STATEMASK_ALL + + + + + Endpoint Hardware Support + + + + + Volume + + + + + Mute + + + + + Meter + + + + + The EDataFlow enumeration defines constants that indicate the direction + in which audio data flows between an audio endpoint device and an application + + + + + Audio rendering stream. + Audio data flows from the application to the audio endpoint device, which renders the stream. + + + + + Audio capture stream. Audio data flows from the audio endpoint device that captures the stream, + to the application + + + + + Audio rendering or capture stream. Audio data can flow either from the application to the audio + endpoint device, or from the audio endpoint device to the application. + + + + + PROPERTYKEY is defined in wtypes.h + + + + + Format ID + + + + + Property ID + + + + + + + + + + + The ERole enumeration defines constants that indicate the role + that the system has assigned to an audio endpoint device + + + + + Games, system notification sounds, and voice commands. + + + + + Music, movies, narration, and live music recording + + + + + Voice communications (talking to another person). + + + + + MM Device + + + + + Audio Client + + + + + Audio Meter Information + + + + + Audio Endpoint Volume + + + + + AudioSessionManager instance + + + + + Properties + + + + + Friendly name for the endpoint + + + + + Friendly name of device + + + + + Icon path of device + + + + + Device ID + + + + + Data Flow + + + + + Device State + + + + + To string + + + + + MM Device Enumerator + + + + + Creates a new MM Device Enumerator + + + + + Enumerate Audio Endpoints + + Desired DataFlow + State Mask + Device Collection + + + + Get Default Endpoint + + Data Flow + Role + Device + + + + Check to see if a default audio end point exists without needing an exception. + + Data Flow + Role + True if one exists, and false if one does not exist. + + + + Get device by ID + + Device ID + Device + + + + Registers a call back for Device Events + + Object implementing IMMNotificationClient type casted as IMMNotificationClient interface + + + + + Unregisters a call back for Device Events + + Object implementing IMMNotificationClient type casted as IMMNotificationClient interface + + + + + + + + Called to dispose/finalize contained objects. + + True if disposing, false if called from a finalizer. + + + + Property Store class, only supports reading properties at the moment. + + + + + Property Count + + + + + Gets property by index + + Property index + The property + + + + Contains property guid + + Looks for a specific key + True if found + + + + Indexer by guid + + Property Key + Property or null if not found + + + + Gets property key at sepecified index + + Index + Property key + + + + Gets property value at specified index + + Index + Property value + + + + Creates a new property store + + IPropertyStore COM interface + + + + Property Store Property + + + + + Property Key + + + + + Property Value + + + + + Envelope generator (ADSR) + + + + + Envelope State + + + + + Idle + + + + + Attack + + + + + Decay + + + + + Sustain + + + + + Release + + + + + Creates and Initializes an Envelope Generator + + + + + Attack Rate (seconds * SamplesPerSecond) + + + + + Decay Rate (seconds * SamplesPerSecond) + + + + + Release Rate (seconds * SamplesPerSecond) + + + + + Sustain Level (1 = 100%) + + + + + Sets the attack curve + + + + + Sets the decay release curve + + + + + Read the next volume multiplier from the envelope generator + + A volume multiplier + + + + Trigger the gate + + If true, enter attack phase, if false enter release phase (unless already idle) + + + + Current envelope state + + + + + Reset to idle state + + + + + Get the current output level + + + + + Fully managed resampler, based on Cockos WDL Resampler + + + + + Creates a new Resampler + + + + + sets the mode + if sinc set, it overrides interp or filtercnt + + + + + Sets the filter parameters + used for filtercnt>0 but not sinc + + + + + Set feed mode + + if true, that means the first parameter to ResamplePrepare will specify however much input you have, not how much you want + + + + Reset + + + + + Prepare + note that it is safe to call ResamplePrepare without calling ResampleOut (the next call of ResamplePrepare will function as normal) + nb inbuffer was WDL_ResampleSample **, returning a place to put the in buffer, so we return a buffer and offset + + req_samples is output samples desired if !wantInputDriven, or if wantInputDriven is input samples that we have + + + + returns number of samples desired (put these into *inbuffer) + + + + SMB Pitch Shifter + + + + + Pitch Shift + + + + + Pitch Shift + + + + + Short Time Fourier Transform + + + + + BiQuad filter + + + + + Passes a single sample through the filter + + Input sample + Output sample + + + + Set this up as a low pass filter + + Sample Rate + Cut-off Frequency + Bandwidth + + + + Set this up as a peaking EQ + + Sample Rate + Centre Frequency + Bandwidth (Q) + Gain in decibels + + + + Set this as a high pass filter + + + + + Create a low pass filter + + + + + Create a High pass filter + + + + + Create a bandpass filter with constant skirt gain + + + + + Create a bandpass filter with constant peak gain + + + + + Creates a notch filter + + + + + Creaes an all pass filter + + + + + Create a Peaking EQ + + + + + H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1) + + + + a "shelf slope" parameter (for shelving EQ only). + When S = 1, the shelf slope is as steep as it can be and remain monotonically + increasing or decreasing gain with frequency. The shelf slope, in dB/octave, + remains proportional to S for all other values for a fixed f0/Fs and dBgain. + Gain in decibels + + + + H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A) + + + + + + + + + + Type to represent complex number + + + + + Real Part + + + + + Imaginary Part + + + + + Summary description for FastFourierTransform. + + + + + This computes an in-place complex-to-complex FFT + x and y are the real and imaginary arrays of 2^m points. + + + + + Applies a Hamming Window + + Index into frame + Frame size (e.g. 1024) + Multiplier for Hamming window + + + + Applies a Hann Window + + Index into frame + Frame size (e.g. 1024) + Multiplier for Hann window + + + + Applies a Blackman-Harris Window + + Index into frame + Frame size (e.g. 1024) + Multiplier for Blackmann-Harris window + + + + Summary description for ImpulseResponseConvolution. + + + + + A very simple mono convolution algorithm + + + This will be very slow + + + + + This is actually a downwards normalize for data that will clip + + + + + http://tech.ebu.ch/docs/tech/tech3306-2009.pdf + + + + + WaveFormat + + + + + Data Chunk Position + + + + + Data Chunk Length + + + + + Riff Chunks + + + + + Represents an entry in a Cakewalk drum map + + + + + User customisable note name + + + + + Input MIDI note number + + + + + Output MIDI note number + + + + + Output port + + + + + Output MIDI Channel + + + + + Velocity adjustment + + + + + Velocity scaling - in percent + + + + + Describes this drum map entry + + + + + Represents a Cakewalk Drum Map file (.map) + + + + + Parses a Cakewalk Drum Map file + + Path of the .map file + + + + The drum mappings in this drum map + + + + + Describes this drum map + + + + + MP3 Frame decompressor using the Windows Media MP3 Decoder DMO object + + + + + Initializes a new instance of the DMO MP3 Frame decompressor + + + + + + Converted PCM WaveFormat + + + + + Decompress a single frame of MP3 + + + + + Alerts us that a reposition has occured so the MP3 decoder needs to reset its state + + + + + Dispose of this obejct and clean up resources + + + + + Audio Subtype GUIDs + http://msdn.microsoft.com/en-us/library/windows/desktop/aa372553%28v=vs.85%29.aspx + + + + + Advanced Audio Coding (AAC). + + + + + Not used + + + + + Dolby AC-3 audio over Sony/Philips Digital Interface (S/PDIF). + + + + + Encrypted audio data used with secure audio path. + + + + + Digital Theater Systems (DTS) audio. + + + + + Uncompressed IEEE floating-point audio. + + + + + MPEG Audio Layer-3 (MP3). + + + + + MPEG-1 audio payload. + + + + + Windows Media Audio 9 Voice codec. + + + + + Uncompressed PCM audio. + + + + + Windows Media Audio 9 Professional codec over S/PDIF. + + + + + Windows Media Audio 9 Lossless codec or Windows Media Audio 9.1 codec. + + + + + Windows Media Audio 8 codec, Windows Media Audio 9 codec, or Windows Media Audio 9.1 codec. + + + + + Windows Media Audio 9 Professional codec or Windows Media Audio 9.1 Professional codec. + + + + + Dolby Digital (AC-3). + + + + + MPEG-4 and AAC Audio Types + http://msdn.microsoft.com/en-us/library/windows/desktop/dd317599(v=vs.85).aspx + Reference : wmcodecdsp.h + + + + + Dolby Audio Types + http://msdn.microsoft.com/en-us/library/windows/desktop/dd317599(v=vs.85).aspx + Reference : wmcodecdsp.h + + + + + Dolby Audio Types + http://msdn.microsoft.com/en-us/library/windows/desktop/dd317599(v=vs.85).aspx + Reference : wmcodecdsp.h + + + + + μ-law coding + http://msdn.microsoft.com/en-us/library/windows/desktop/dd390971(v=vs.85).aspx + Reference : Ksmedia.h + + + + + Adaptive delta pulse code modulation (ADPCM) + http://msdn.microsoft.com/en-us/library/windows/desktop/dd390971(v=vs.85).aspx + Reference : Ksmedia.h + + + + + Dolby Digital Plus formatted for HDMI output. + http://msdn.microsoft.com/en-us/library/windows/hardware/ff538392(v=vs.85).aspx + Reference : internet + + + + + MSAudio1 - unknown meaning + Reference : wmcodecdsp.h + + + + + IMA ADPCM ACM Wrapper + + + + + WMSP2 - unknown meaning + Reference: wmsdkidl.h + + + + + Creates an instance of either the sink writer or the source reader. + + + + + Creates an instance of the sink writer or source reader, given a URL. + + + + + Creates an instance of the sink writer or source reader, given an IUnknown pointer. + + + + + CLSID_MFReadWriteClassFactory + + + + + Media Foundation Errors + + + + RANGES + 14000 - 14999 = General Media Foundation errors + 15000 - 15999 = ASF parsing errors + 16000 - 16999 = Media Source errors + 17000 - 17999 = MEDIAFOUNDATION Network Error Events + 18000 - 18999 = MEDIAFOUNDATION WMContainer Error Events + 19000 - 19999 = MEDIAFOUNDATION Media Sink Error Events + 20000 - 20999 = Renderer errors + 21000 - 21999 = Topology Errors + 25000 - 25999 = Timeline Errors + 26000 - 26999 = Unused + 28000 - 28999 = Transform errors + 29000 - 29999 = Content Protection errors + 40000 - 40999 = Clock errors + 41000 - 41999 = MF Quality Management Errors + 42000 - 42999 = MF Transcode API Errors + + + + + MessageId: MF_E_PLATFORM_NOT_INITIALIZED + + MessageText: + + Platform not initialized. Please call MFStartup().%0 + + + + + MessageId: MF_E_BUFFERTOOSMALL + + MessageText: + + The buffer was too small to carry out the requested action.%0 + + + + + MessageId: MF_E_INVALIDREQUEST + + MessageText: + + The request is invalid in the current state.%0 + + + + + MessageId: MF_E_INVALIDSTREAMNUMBER + + MessageText: + + The stream number provided was invalid.%0 + + + + + MessageId: MF_E_INVALIDMEDIATYPE + + MessageText: + + The data specified for the media type is invalid, inconsistent, or not supported by this object.%0 + + + + + MessageId: MF_E_NOTACCEPTING + + MessageText: + + The callee is currently not accepting further input.%0 + + + + + MessageId: MF_E_NOT_INITIALIZED + + MessageText: + + This object needs to be initialized before the requested operation can be carried out.%0 + + + + + MessageId: MF_E_UNSUPPORTED_REPRESENTATION + + MessageText: + + The requested representation is not supported by this object.%0 + + + + + MessageId: MF_E_NO_MORE_TYPES + + MessageText: + + An object ran out of media types to suggest therefore the requested chain of streaming objects cannot be completed.%0 + + + + + MessageId: MF_E_UNSUPPORTED_SERVICE + + MessageText: + + The object does not support the specified service.%0 + + + + + MessageId: MF_E_UNEXPECTED + + MessageText: + + An unexpected error has occurred in the operation requested.%0 + + + + + MessageId: MF_E_INVALIDNAME + + MessageText: + + Invalid name.%0 + + + + + MessageId: MF_E_INVALIDTYPE + + MessageText: + + Invalid type.%0 + + + + + MessageId: MF_E_INVALID_FILE_FORMAT + + MessageText: + + The file does not conform to the relevant file format specification. + + + + + MessageId: MF_E_INVALIDINDEX + + MessageText: + + Invalid index.%0 + + + + + MessageId: MF_E_INVALID_TIMESTAMP + + MessageText: + + An invalid timestamp was given.%0 + + + + + MessageId: MF_E_UNSUPPORTED_SCHEME + + MessageText: + + The scheme of the given URL is unsupported.%0 + + + + + MessageId: MF_E_UNSUPPORTED_BYTESTREAM_TYPE + + MessageText: + + The byte stream type of the given URL is unsupported.%0 + + + + + MessageId: MF_E_UNSUPPORTED_TIME_FORMAT + + MessageText: + + The given time format is unsupported.%0 + + + + + MessageId: MF_E_NO_SAMPLE_TIMESTAMP + + MessageText: + + The Media Sample does not have a timestamp.%0 + + + + + MessageId: MF_E_NO_SAMPLE_DURATION + + MessageText: + + The Media Sample does not have a duration.%0 + + + + + MessageId: MF_E_INVALID_STREAM_DATA + + MessageText: + + The request failed because the data in the stream is corrupt.%0\n. + + + + + MessageId: MF_E_RT_UNAVAILABLE + + MessageText: + + Real time services are not available.%0 + + + + + MessageId: MF_E_UNSUPPORTED_RATE + + MessageText: + + The specified rate is not supported.%0 + + + + + MessageId: MF_E_THINNING_UNSUPPORTED + + MessageText: + + This component does not support stream-thinning.%0 + + + + + MessageId: MF_E_REVERSE_UNSUPPORTED + + MessageText: + + The call failed because no reverse playback rates are available.%0 + + + + + MessageId: MF_E_UNSUPPORTED_RATE_TRANSITION + + MessageText: + + The requested rate transition cannot occur in the current state.%0 + + + + + MessageId: MF_E_RATE_CHANGE_PREEMPTED + + MessageText: + + The requested rate change has been pre-empted and will not occur.%0 + + + + + MessageId: MF_E_NOT_FOUND + + MessageText: + + The specified object or value does not exist.%0 + + + + + MessageId: MF_E_NOT_AVAILABLE + + MessageText: + + The requested value is not available.%0 + + + + + MessageId: MF_E_NO_CLOCK + + MessageText: + + The specified operation requires a clock and no clock is available.%0 + + + + + MessageId: MF_S_MULTIPLE_BEGIN + + MessageText: + + This callback and state had already been passed in to this event generator earlier.%0 + + + + + MessageId: MF_E_MULTIPLE_BEGIN + + MessageText: + + This callback has already been passed in to this event generator.%0 + + + + + MessageId: MF_E_MULTIPLE_SUBSCRIBERS + + MessageText: + + Some component is already listening to events on this event generator.%0 + + + + + MessageId: MF_E_TIMER_ORPHANED + + MessageText: + + This timer was orphaned before its callback time arrived.%0 + + + + + MessageId: MF_E_STATE_TRANSITION_PENDING + + MessageText: + + A state transition is already pending.%0 + + + + + MessageId: MF_E_UNSUPPORTED_STATE_TRANSITION + + MessageText: + + The requested state transition is unsupported.%0 + + + + + MessageId: MF_E_UNRECOVERABLE_ERROR_OCCURRED + + MessageText: + + An unrecoverable error has occurred.%0 + + + + + MessageId: MF_E_SAMPLE_HAS_TOO_MANY_BUFFERS + + MessageText: + + The provided sample has too many buffers.%0 + + + + + MessageId: MF_E_SAMPLE_NOT_WRITABLE + + MessageText: + + The provided sample is not writable.%0 + + + + + MessageId: MF_E_INVALID_KEY + + MessageText: + + The specified key is not valid. + + + + + MessageId: MF_E_BAD_STARTUP_VERSION + + MessageText: + + You are calling MFStartup with the wrong MF_VERSION. Mismatched bits? + + + + + MessageId: MF_E_UNSUPPORTED_CAPTION + + MessageText: + + The caption of the given URL is unsupported.%0 + + + + + MessageId: MF_E_INVALID_POSITION + + MessageText: + + The operation on the current offset is not permitted.%0 + + + + + MessageId: MF_E_ATTRIBUTENOTFOUND + + MessageText: + + The requested attribute was not found.%0 + + + + + MessageId: MF_E_PROPERTY_TYPE_NOT_ALLOWED + + MessageText: + + The specified property type is not allowed in this context.%0 + + + + + MessageId: MF_E_PROPERTY_TYPE_NOT_SUPPORTED + + MessageText: + + The specified property type is not supported.%0 + + + + + MessageId: MF_E_PROPERTY_EMPTY + + MessageText: + + The specified property is empty.%0 + + + + + MessageId: MF_E_PROPERTY_NOT_EMPTY + + MessageText: + + The specified property is not empty.%0 + + + + + MessageId: MF_E_PROPERTY_VECTOR_NOT_ALLOWED + + MessageText: + + The vector property specified is not allowed in this context.%0 + + + + + MessageId: MF_E_PROPERTY_VECTOR_REQUIRED + + MessageText: + + A vector property is required in this context.%0 + + + + + MessageId: MF_E_OPERATION_CANCELLED + + MessageText: + + The operation is cancelled.%0 + + + + + MessageId: MF_E_BYTESTREAM_NOT_SEEKABLE + + MessageText: + + The provided bytestream was expected to be seekable and it is not.%0 + + + + + MessageId: MF_E_DISABLED_IN_SAFEMODE + + MessageText: + + The Media Foundation platform is disabled when the system is running in Safe Mode.%0 + + + + + MessageId: MF_E_CANNOT_PARSE_BYTESTREAM + + MessageText: + + The Media Source could not parse the byte stream.%0 + + + + + MessageId: MF_E_SOURCERESOLVER_MUTUALLY_EXCLUSIVE_FLAGS + + MessageText: + + Mutually exclusive flags have been specified to source resolver. This flag combination is invalid.%0 + + + + + MessageId: MF_E_MEDIAPROC_WRONGSTATE + + MessageText: + + MediaProc is in the wrong state%0 + + + + + MessageId: MF_E_RT_THROUGHPUT_NOT_AVAILABLE + + MessageText: + + Real time I/O service can not provide requested throughput.%0 + + + + + MessageId: MF_E_RT_TOO_MANY_CLASSES + + MessageText: + + The workqueue cannot be registered with more classes.%0 + + + + + MessageId: MF_E_RT_WOULDBLOCK + + MessageText: + + This operation cannot succeed because another thread owns this object.%0 + + + + + MessageId: MF_E_NO_BITPUMP + + MessageText: + + Internal. Bitpump not found.%0 + + + + + MessageId: MF_E_RT_OUTOFMEMORY + + MessageText: + + No more RT memory available.%0 + + + + + MessageId: MF_E_RT_WORKQUEUE_CLASS_NOT_SPECIFIED + + MessageText: + + An MMCSS class has not been set for this work queue.%0 + + + + + MessageId: MF_E_INSUFFICIENT_BUFFER + + MessageText: + + Insufficient memory for response.%0 + + + + + MessageId: MF_E_CANNOT_CREATE_SINK + + MessageText: + + Activate failed to create mediasink. Call OutputNode::GetUINT32(MF_TOPONODE_MAJORTYPE) for more information. %0 + + + + + MessageId: MF_E_BYTESTREAM_UNKNOWN_LENGTH + + MessageText: + + The length of the provided bytestream is unknown.%0 + + + + + MessageId: MF_E_SESSION_PAUSEWHILESTOPPED + + MessageText: + + The media session cannot pause from a stopped state.%0 + + + + + MessageId: MF_S_ACTIVATE_REPLACED + + MessageText: + + The activate could not be created in the remote process for some reason it was replaced with empty one.%0 + + + + + MessageId: MF_E_FORMAT_CHANGE_NOT_SUPPORTED + + MessageText: + + The data specified for the media type is supported, but would require a format change, which is not supported by this object.%0 + + + + + MessageId: MF_E_INVALID_WORKQUEUE + + MessageText: + + The operation failed because an invalid combination of workqueue ID and flags was specified.%0 + + + + + MessageId: MF_E_DRM_UNSUPPORTED + + MessageText: + + No DRM support is available.%0 + + + + + MessageId: MF_E_UNAUTHORIZED + + MessageText: + + This operation is not authorized.%0 + + + + + MessageId: MF_E_OUT_OF_RANGE + + MessageText: + + The value is not in the specified or valid range.%0 + + + + + MessageId: MF_E_INVALID_CODEC_MERIT + + MessageText: + + The registered codec merit is not valid.%0 + + + + + MessageId: MF_E_HW_MFT_FAILED_START_STREAMING + + MessageText: + + Hardware MFT failed to start streaming due to lack of hardware resources.%0 + + + + + MessageId: MF_S_ASF_PARSEINPROGRESS + + MessageText: + + Parsing is still in progress and is not yet complete.%0 + + + + + MessageId: MF_E_ASF_PARSINGINCOMPLETE + + MessageText: + + Not enough data have been parsed to carry out the requested action.%0 + + + + + MessageId: MF_E_ASF_MISSINGDATA + + MessageText: + + There is a gap in the ASF data provided.%0 + + + + + MessageId: MF_E_ASF_INVALIDDATA + + MessageText: + + The data provided are not valid ASF.%0 + + + + + MessageId: MF_E_ASF_OPAQUEPACKET + + MessageText: + + The packet is opaque, so the requested information cannot be returned.%0 + + + + + MessageId: MF_E_ASF_NOINDEX + + MessageText: + + The requested operation failed since there is no appropriate ASF index.%0 + + + + + MessageId: MF_E_ASF_OUTOFRANGE + + MessageText: + + The value supplied is out of range for this operation.%0 + + + + + MessageId: MF_E_ASF_INDEXNOTLOADED + + MessageText: + + The index entry requested needs to be loaded before it can be available.%0 + + + + + MessageId: MF_E_ASF_TOO_MANY_PAYLOADS + + MessageText: + + The packet has reached the maximum number of payloads.%0 + + + + + MessageId: MF_E_ASF_UNSUPPORTED_STREAM_TYPE + + MessageText: + + Stream type is not supported.%0 + + + + + MessageId: MF_E_ASF_DROPPED_PACKET + + MessageText: + + One or more ASF packets were dropped.%0 + + + + + MessageId: MF_E_NO_EVENTS_AVAILABLE + + MessageText: + + There are no events available in the queue.%0 + + + + + MessageId: MF_E_INVALID_STATE_TRANSITION + + MessageText: + + A media source cannot go from the stopped state to the paused state.%0 + + + + + MessageId: MF_E_END_OF_STREAM + + MessageText: + + The media stream cannot process any more samples because there are no more samples in the stream.%0 + + + + + MessageId: MF_E_SHUTDOWN + + MessageText: + + The request is invalid because Shutdown() has been called.%0 + + + + + MessageId: MF_E_MP3_NOTFOUND + + MessageText: + + The MP3 object was not found.%0 + + + + + MessageId: MF_E_MP3_OUTOFDATA + + MessageText: + + The MP3 parser ran out of data before finding the MP3 object.%0 + + + + + MessageId: MF_E_MP3_NOTMP3 + + MessageText: + + The file is not really a MP3 file.%0 + + + + + MessageId: MF_E_MP3_NOTSUPPORTED + + MessageText: + + The MP3 file is not supported.%0 + + + + + MessageId: MF_E_NO_DURATION + + MessageText: + + The Media stream has no duration.%0 + + + + + MessageId: MF_E_INVALID_FORMAT + + MessageText: + + The Media format is recognized but is invalid.%0 + + + + + MessageId: MF_E_PROPERTY_NOT_FOUND + + MessageText: + + The property requested was not found.%0 + + + + + MessageId: MF_E_PROPERTY_READ_ONLY + + MessageText: + + The property is read only.%0 + + + + + MessageId: MF_E_PROPERTY_NOT_ALLOWED + + MessageText: + + The specified property is not allowed in this context.%0 + + + + + MessageId: MF_E_MEDIA_SOURCE_NOT_STARTED + + MessageText: + + The media source is not started.%0 + + + + + MessageId: MF_E_UNSUPPORTED_FORMAT + + MessageText: + + The Media format is recognized but not supported.%0 + + + + + MessageId: MF_E_MP3_BAD_CRC + + MessageText: + + The MPEG frame has bad CRC.%0 + + + + + MessageId: MF_E_NOT_PROTECTED + + MessageText: + + The file is not protected.%0 + + + + + MessageId: MF_E_MEDIA_SOURCE_WRONGSTATE + + MessageText: + + The media source is in the wrong state%0 + + + + + MessageId: MF_E_MEDIA_SOURCE_NO_STREAMS_SELECTED + + MessageText: + + No streams are selected in source presentation descriptor.%0 + + + + + MessageId: MF_E_CANNOT_FIND_KEYFRAME_SAMPLE + + MessageText: + + No key frame sample was found.%0 + + + + + MessageId: MF_E_NETWORK_RESOURCE_FAILURE + + MessageText: + + An attempt to acquire a network resource failed.%0 + + + + + MessageId: MF_E_NET_WRITE + + MessageText: + + Error writing to the network.%0 + + + + + MessageId: MF_E_NET_READ + + MessageText: + + Error reading from the network.%0 + + + + + MessageId: MF_E_NET_REQUIRE_NETWORK + + MessageText: + + Internal. Entry cannot complete operation without network.%0 + + + + + MessageId: MF_E_NET_REQUIRE_ASYNC + + MessageText: + + Internal. Async op is required.%0 + + + + + MessageId: MF_E_NET_BWLEVEL_NOT_SUPPORTED + + MessageText: + + Internal. Bandwidth levels are not supported.%0 + + + + + MessageId: MF_E_NET_STREAMGROUPS_NOT_SUPPORTED + + MessageText: + + Internal. Stream groups are not supported.%0 + + + + + MessageId: MF_E_NET_MANUALSS_NOT_SUPPORTED + + MessageText: + + Manual stream selection is not supported.%0 + + + + + MessageId: MF_E_NET_INVALID_PRESENTATION_DESCRIPTOR + + MessageText: + + Invalid presentation descriptor.%0 + + + + + MessageId: MF_E_NET_CACHESTREAM_NOT_FOUND + + MessageText: + + Cannot find cache stream.%0 + + + + + MessageId: MF_I_MANUAL_PROXY + + MessageText: + + The proxy setting is manual.%0 + + + + duplicate removed + MessageId=17011 Severity=Informational Facility=MEDIAFOUNDATION SymbolicName=MF_E_INVALID_REQUEST + Language=English + The request is invalid in the current state.%0 + . + + MessageId: MF_E_NET_REQUIRE_INPUT + + MessageText: + + Internal. Entry cannot complete operation without input.%0 + + + + + MessageId: MF_E_NET_REDIRECT + + MessageText: + + The client redirected to another server.%0 + + + + + MessageId: MF_E_NET_REDIRECT_TO_PROXY + + MessageText: + + The client is redirected to a proxy server.%0 + + + + + MessageId: MF_E_NET_TOO_MANY_REDIRECTS + + MessageText: + + The client reached maximum redirection limit.%0 + + + + + MessageId: MF_E_NET_TIMEOUT + + MessageText: + + The server, a computer set up to offer multimedia content to other computers, could not handle your request for multimedia content in a timely manner. Please try again later.%0 + + + + + MessageId: MF_E_NET_CLIENT_CLOSE + + MessageText: + + The control socket is closed by the client.%0 + + + + + MessageId: MF_E_NET_BAD_CONTROL_DATA + + MessageText: + + The server received invalid data from the client on the control connection.%0 + + + + + MessageId: MF_E_NET_INCOMPATIBLE_SERVER + + MessageText: + + The server is not a compatible streaming media server.%0 + + + + + MessageId: MF_E_NET_UNSAFE_URL + + MessageText: + + Url.%0 + + + + + MessageId: MF_E_NET_CACHE_NO_DATA + + MessageText: + + Data is not available.%0 + + + + + MessageId: MF_E_NET_EOL + + MessageText: + + End of line.%0 + + + + + MessageId: MF_E_NET_BAD_REQUEST + + MessageText: + + The request could not be understood by the server.%0 + + + + + MessageId: MF_E_NET_INTERNAL_SERVER_ERROR + + MessageText: + + The server encountered an unexpected condition which prevented it from fulfilling the request.%0 + + + + + MessageId: MF_E_NET_SESSION_NOT_FOUND + + MessageText: + + Session not found.%0 + + + + + MessageId: MF_E_NET_NOCONNECTION + + MessageText: + + There is no connection established with the Windows Media server. The operation failed.%0 + + + + + MessageId: MF_E_NET_CONNECTION_FAILURE + + MessageText: + + The network connection has failed.%0 + + + + + MessageId: MF_E_NET_INCOMPATIBLE_PUSHSERVER + + MessageText: + + The Server service that received the HTTP push request is not a compatible version of Windows Media Services (WMS). This error may indicate the push request was received by IIS instead of WMS. Ensure WMS is started and has the HTTP Server control protocol properly enabled and try again.%0 + + + + + MessageId: MF_E_NET_SERVER_ACCESSDENIED + + MessageText: + + The Windows Media server is denying access. The username and/or password might be incorrect.%0 + + + + + MessageId: MF_E_NET_PROXY_ACCESSDENIED + + MessageText: + + The proxy server is denying access. The username and/or password might be incorrect.%0 + + + + + MessageId: MF_E_NET_CANNOTCONNECT + + MessageText: + + Unable to establish a connection to the server.%0 + + + + + MessageId: MF_E_NET_INVALID_PUSH_TEMPLATE + + MessageText: + + The specified push template is invalid.%0 + + + + + MessageId: MF_E_NET_INVALID_PUSH_PUBLISHING_POINT + + MessageText: + + The specified push publishing point is invalid.%0 + + + + + MessageId: MF_E_NET_BUSY + + MessageText: + + The requested resource is in use.%0 + + + + + MessageId: MF_E_NET_RESOURCE_GONE + + MessageText: + + The Publishing Point or file on the Windows Media Server is no longer available.%0 + + + + + MessageId: MF_E_NET_ERROR_FROM_PROXY + + MessageText: + + The proxy experienced an error while attempting to contact the media server.%0 + + + + + MessageId: MF_E_NET_PROXY_TIMEOUT + + MessageText: + + The proxy did not receive a timely response while attempting to contact the media server.%0 + + + + + MessageId: MF_E_NET_SERVER_UNAVAILABLE + + MessageText: + + The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.%0 + + + + + MessageId: MF_E_NET_TOO_MUCH_DATA + + MessageText: + + The encoding process was unable to keep up with the amount of supplied data.%0 + + + + + MessageId: MF_E_NET_SESSION_INVALID + + MessageText: + + Session not found.%0 + + + + + MessageId: MF_E_OFFLINE_MODE + + MessageText: + + The requested URL is not available in offline mode.%0 + + + + + MessageId: MF_E_NET_UDP_BLOCKED + + MessageText: + + A device in the network is blocking UDP traffic.%0 + + + + + MessageId: MF_E_NET_UNSUPPORTED_CONFIGURATION + + MessageText: + + The specified configuration value is not supported.%0 + + + + + MessageId: MF_E_NET_PROTOCOL_DISABLED + + MessageText: + + The networking protocol is disabled.%0 + + + + + MessageId: MF_E_ALREADY_INITIALIZED + + MessageText: + + This object has already been initialized and cannot be re-initialized at this time.%0 + + + + + MessageId: MF_E_BANDWIDTH_OVERRUN + + MessageText: + + The amount of data passed in exceeds the given bitrate and buffer window.%0 + + + + + MessageId: MF_E_LATE_SAMPLE + + MessageText: + + The sample was passed in too late to be correctly processed.%0 + + + + + MessageId: MF_E_FLUSH_NEEDED + + MessageText: + + The requested action cannot be carried out until the object is flushed and the queue is emptied.%0 + + + + + MessageId: MF_E_INVALID_PROFILE + + MessageText: + + The profile is invalid.%0 + + + + + MessageId: MF_E_INDEX_NOT_COMMITTED + + MessageText: + + The index that is being generated needs to be committed before the requested action can be carried out.%0 + + + + + MessageId: MF_E_NO_INDEX + + MessageText: + + The index that is necessary for the requested action is not found.%0 + + + + + MessageId: MF_E_CANNOT_INDEX_IN_PLACE + + MessageText: + + The requested index cannot be added in-place to the specified ASF content.%0 + + + + + MessageId: MF_E_MISSING_ASF_LEAKYBUCKET + + MessageText: + + The ASF leaky bucket parameters must be specified in order to carry out this request.%0 + + + + + MessageId: MF_E_INVALID_ASF_STREAMID + + MessageText: + + The stream id is invalid. The valid range for ASF stream id is from 1 to 127.%0 + + + + + MessageId: MF_E_STREAMSINK_REMOVED + + MessageText: + + The requested Stream Sink has been removed and cannot be used.%0 + + + + + MessageId: MF_E_STREAMSINKS_OUT_OF_SYNC + + MessageText: + + The various Stream Sinks in this Media Sink are too far out of sync for the requested action to take place.%0 + + + + + MessageId: MF_E_STREAMSINKS_FIXED + + MessageText: + + Stream Sinks cannot be added to or removed from this Media Sink because its set of streams is fixed.%0 + + + + + MessageId: MF_E_STREAMSINK_EXISTS + + MessageText: + + The given Stream Sink already exists.%0 + + + + + MessageId: MF_E_SAMPLEALLOCATOR_CANCELED + + MessageText: + + Sample allocations have been canceled.%0 + + + + + MessageId: MF_E_SAMPLEALLOCATOR_EMPTY + + MessageText: + + The sample allocator is currently empty, due to outstanding requests.%0 + + + + + MessageId: MF_E_SINK_ALREADYSTOPPED + + MessageText: + + When we try to sopt a stream sink, it is already stopped %0 + + + + + MessageId: MF_E_ASF_FILESINK_BITRATE_UNKNOWN + + MessageText: + + The ASF file sink could not reserve AVIO because the bitrate is unknown.%0 + + + + + MessageId: MF_E_SINK_NO_STREAMS + + MessageText: + + No streams are selected in sink presentation descriptor.%0 + + + + + MessageId: MF_S_SINK_NOT_FINALIZED + + MessageText: + + The sink has not been finalized before shut down. This may cause sink generate a corrupted content.%0 + + + + + MessageId: MF_E_METADATA_TOO_LONG + + MessageText: + + A metadata item was too long to write to the output container.%0 + + + + + MessageId: MF_E_SINK_NO_SAMPLES_PROCESSED + + MessageText: + + The operation failed because no samples were processed by the sink.%0 + + + + + MessageId: MF_E_VIDEO_REN_NO_PROCAMP_HW + + MessageText: + + There is no available procamp hardware with which to perform color correction.%0 + + + + + MessageId: MF_E_VIDEO_REN_NO_DEINTERLACE_HW + + MessageText: + + There is no available deinterlacing hardware with which to deinterlace the video stream.%0 + + + + + MessageId: MF_E_VIDEO_REN_COPYPROT_FAILED + + MessageText: + + A video stream requires copy protection to be enabled, but there was a failure in attempting to enable copy protection.%0 + + + + + MessageId: MF_E_VIDEO_REN_SURFACE_NOT_SHARED + + MessageText: + + A component is attempting to access a surface for sharing that is not shared.%0 + + + + + MessageId: MF_E_VIDEO_DEVICE_LOCKED + + MessageText: + + A component is attempting to access a shared device that is already locked by another component.%0 + + + + + MessageId: MF_E_NEW_VIDEO_DEVICE + + MessageText: + + The device is no longer available. The handle should be closed and a new one opened.%0 + + + + + MessageId: MF_E_NO_VIDEO_SAMPLE_AVAILABLE + + MessageText: + + A video sample is not currently queued on a stream that is required for mixing.%0 + + + + + MessageId: MF_E_NO_AUDIO_PLAYBACK_DEVICE + + MessageText: + + No audio playback device was found.%0 + + + + + MessageId: MF_E_AUDIO_PLAYBACK_DEVICE_IN_USE + + MessageText: + + The requested audio playback device is currently in use.%0 + + + + + MessageId: MF_E_AUDIO_PLAYBACK_DEVICE_INVALIDATED + + MessageText: + + The audio playback device is no longer present.%0 + + + + + MessageId: MF_E_AUDIO_SERVICE_NOT_RUNNING + + MessageText: + + The audio service is not running.%0 + + + + + MessageId: MF_E_TOPO_INVALID_OPTIONAL_NODE + + MessageText: + + The topology contains an invalid optional node. Possible reasons are incorrect number of outputs and inputs or optional node is at the beginning or end of a segment. %0 + + + + + MessageId: MF_E_TOPO_CANNOT_FIND_DECRYPTOR + + MessageText: + + No suitable transform was found to decrypt the content. %0 + + + + + MessageId: MF_E_TOPO_CODEC_NOT_FOUND + + MessageText: + + No suitable transform was found to encode or decode the content. %0 + + + + + MessageId: MF_E_TOPO_CANNOT_CONNECT + + MessageText: + + Unable to find a way to connect nodes%0 + + + + + MessageId: MF_E_TOPO_UNSUPPORTED + + MessageText: + + Unsupported operations in topoloader%0 + + + + + MessageId: MF_E_TOPO_INVALID_TIME_ATTRIBUTES + + MessageText: + + The topology or its nodes contain incorrectly set time attributes%0 + + + + + MessageId: MF_E_TOPO_LOOPS_IN_TOPOLOGY + + MessageText: + + The topology contains loops, which are unsupported in media foundation topologies%0 + + + + + MessageId: MF_E_TOPO_MISSING_PRESENTATION_DESCRIPTOR + + MessageText: + + A source stream node in the topology does not have a presentation descriptor%0 + + + + + MessageId: MF_E_TOPO_MISSING_STREAM_DESCRIPTOR + + MessageText: + + A source stream node in the topology does not have a stream descriptor%0 + + + + + MessageId: MF_E_TOPO_STREAM_DESCRIPTOR_NOT_SELECTED + + MessageText: + + A stream descriptor was set on a source stream node but it was not selected on the presentation descriptor%0 + + + + + MessageId: MF_E_TOPO_MISSING_SOURCE + + MessageText: + + A source stream node in the topology does not have a source%0 + + + + + MessageId: MF_E_TOPO_SINK_ACTIVATES_UNSUPPORTED + + MessageText: + + The topology loader does not support sink activates on output nodes.%0 + + + + + MessageId: MF_E_SEQUENCER_UNKNOWN_SEGMENT_ID + + MessageText: + + The sequencer cannot find a segment with the given ID.%0\n. + + + + + MessageId: MF_S_SEQUENCER_CONTEXT_CANCELED + + MessageText: + + The context was canceled.%0\n. + + + + + MessageId: MF_E_NO_SOURCE_IN_CACHE + + MessageText: + + Cannot find source in source cache.%0\n. + + + + + MessageId: MF_S_SEQUENCER_SEGMENT_AT_END_OF_STREAM + + MessageText: + + Cannot update topology flags.%0\n. + + + + + MessageId: MF_E_TRANSFORM_TYPE_NOT_SET + + MessageText: + + A valid type has not been set for this stream or a stream that it depends on.%0 + + + + + MessageId: MF_E_TRANSFORM_STREAM_CHANGE + + MessageText: + + A stream change has occurred. Output cannot be produced until the streams have been renegotiated.%0 + + + + + MessageId: MF_E_TRANSFORM_INPUT_REMAINING + + MessageText: + + The transform cannot take the requested action until all of the input data it currently holds is processed or flushed.%0 + + + + + MessageId: MF_E_TRANSFORM_PROFILE_MISSING + + MessageText: + + The transform requires a profile but no profile was supplied or found.%0 + + + + + MessageId: MF_E_TRANSFORM_PROFILE_INVALID_OR_CORRUPT + + MessageText: + + The transform requires a profile but the supplied profile was invalid or corrupt.%0 + + + + + MessageId: MF_E_TRANSFORM_PROFILE_TRUNCATED + + MessageText: + + The transform requires a profile but the supplied profile ended unexpectedly while parsing.%0 + + + + + MessageId: MF_E_TRANSFORM_PROPERTY_PID_NOT_RECOGNIZED + + MessageText: + + The property ID does not match any property supported by the transform.%0 + + + + + MessageId: MF_E_TRANSFORM_PROPERTY_VARIANT_TYPE_WRONG + + MessageText: + + The variant does not have the type expected for this property ID.%0 + + + + + MessageId: MF_E_TRANSFORM_PROPERTY_NOT_WRITEABLE + + MessageText: + + An attempt was made to set the value on a read-only property.%0 + + + + + MessageId: MF_E_TRANSFORM_PROPERTY_ARRAY_VALUE_WRONG_NUM_DIM + + MessageText: + + The array property value has an unexpected number of dimensions.%0 + + + + + MessageId: MF_E_TRANSFORM_PROPERTY_VALUE_SIZE_WRONG + + MessageText: + + The array or blob property value has an unexpected size.%0 + + + + + MessageId: MF_E_TRANSFORM_PROPERTY_VALUE_OUT_OF_RANGE + + MessageText: + + The property value is out of range for this transform.%0 + + + + + MessageId: MF_E_TRANSFORM_PROPERTY_VALUE_INCOMPATIBLE + + MessageText: + + The property value is incompatible with some other property or mediatype set on the transform.%0 + + + + + MessageId: MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_OUTPUT_MEDIATYPE + + MessageText: + + The requested operation is not supported for the currently set output mediatype.%0 + + + + + MessageId: MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_INPUT_MEDIATYPE + + MessageText: + + The requested operation is not supported for the currently set input mediatype.%0 + + + + + MessageId: MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_MEDIATYPE_COMBINATION + + MessageText: + + The requested operation is not supported for the currently set combination of mediatypes.%0 + + + + + MessageId: MF_E_TRANSFORM_CONFLICTS_WITH_OTHER_CURRENTLY_ENABLED_FEATURES + + MessageText: + + The requested feature is not supported in combination with some other currently enabled feature.%0 + + + + + MessageId: MF_E_TRANSFORM_NEED_MORE_INPUT + + MessageText: + + The transform cannot produce output until it gets more input samples.%0 + + + + + MessageId: MF_E_TRANSFORM_NOT_POSSIBLE_FOR_CURRENT_SPKR_CONFIG + + MessageText: + + The requested operation is not supported for the current speaker configuration.%0 + + + + + MessageId: MF_E_TRANSFORM_CANNOT_CHANGE_MEDIATYPE_WHILE_PROCESSING + + MessageText: + + The transform cannot accept mediatype changes in the middle of processing.%0 + + + + + MessageId: MF_S_TRANSFORM_DO_NOT_PROPAGATE_EVENT + + MessageText: + + The caller should not propagate this event to downstream components.%0 + + + + + MessageId: MF_E_UNSUPPORTED_D3D_TYPE + + MessageText: + + The input type is not supported for D3D device.%0 + + + + + MessageId: MF_E_TRANSFORM_ASYNC_LOCKED + + MessageText: + + The caller does not appear to support this transform's asynchronous capabilities.%0 + + + + + MessageId: MF_E_TRANSFORM_CANNOT_INITIALIZE_ACM_DRIVER + + MessageText: + + An audio compression manager driver could not be initialized by the transform.%0 + + + + + MessageId: MF_E_LICENSE_INCORRECT_RIGHTS + + MessageText: + + You are not allowed to open this file. Contact the content provider for further assistance.%0 + + + + + MessageId: MF_E_LICENSE_OUTOFDATE + + MessageText: + + The license for this media file has expired. Get a new license or contact the content provider for further assistance.%0 + + + + + MessageId: MF_E_LICENSE_REQUIRED + + MessageText: + + You need a license to perform the requested operation on this media file.%0 + + + + + MessageId: MF_E_DRM_HARDWARE_INCONSISTENT + + MessageText: + + The licenses for your media files are corrupted. Contact Microsoft product support.%0 + + + + + MessageId: MF_E_NO_CONTENT_PROTECTION_MANAGER + + MessageText: + + The APP needs to provide IMFContentProtectionManager callback to access the protected media file.%0 + + + + + MessageId: MF_E_LICENSE_RESTORE_NO_RIGHTS + + MessageText: + + Client does not have rights to restore licenses.%0 + + + + + MessageId: MF_E_BACKUP_RESTRICTED_LICENSE + + MessageText: + + Licenses are restricted and hence can not be backed up.%0 + + + + + MessageId: MF_E_LICENSE_RESTORE_NEEDS_INDIVIDUALIZATION + + MessageText: + + License restore requires machine to be individualized.%0 + + + + + MessageId: MF_S_PROTECTION_NOT_REQUIRED + + MessageText: + + Protection for stream is not required.%0 + + + + + MessageId: MF_E_COMPONENT_REVOKED + + MessageText: + + Component is revoked.%0 + + + + + MessageId: MF_E_TRUST_DISABLED + + MessageText: + + Trusted functionality is currently disabled on this component.%0 + + + + + MessageId: MF_E_WMDRMOTA_NO_ACTION + + MessageText: + + No Action is set on WMDRM Output Trust Authority.%0 + + + + + MessageId: MF_E_WMDRMOTA_ACTION_ALREADY_SET + + MessageText: + + Action is already set on WMDRM Output Trust Authority.%0 + + + + + MessageId: MF_E_WMDRMOTA_DRM_HEADER_NOT_AVAILABLE + + MessageText: + + DRM Heaader is not available.%0 + + + + + MessageId: MF_E_WMDRMOTA_DRM_ENCRYPTION_SCHEME_NOT_SUPPORTED + + MessageText: + + Current encryption scheme is not supported.%0 + + + + + MessageId: MF_E_WMDRMOTA_ACTION_MISMATCH + + MessageText: + + Action does not match with current configuration.%0 + + + + + MessageId: MF_E_WMDRMOTA_INVALID_POLICY + + MessageText: + + Invalid policy for WMDRM Output Trust Authority.%0 + + + + + MessageId: MF_E_POLICY_UNSUPPORTED + + MessageText: + + The policies that the Input Trust Authority requires to be enforced are unsupported by the outputs.%0 + + + + + MessageId: MF_E_OPL_NOT_SUPPORTED + + MessageText: + + The OPL that the license requires to be enforced are not supported by the Input Trust Authority.%0 + + + + + MessageId: MF_E_TOPOLOGY_VERIFICATION_FAILED + + MessageText: + + The topology could not be successfully verified.%0 + + + + + MessageId: MF_E_SIGNATURE_VERIFICATION_FAILED + + MessageText: + + Signature verification could not be completed successfully for this component.%0 + + + + + MessageId: MF_E_DEBUGGING_NOT_ALLOWED + + MessageText: + + Running this process under a debugger while using protected content is not allowed.%0 + + + + + MessageId: MF_E_CODE_EXPIRED + + MessageText: + + MF component has expired.%0 + + + + + MessageId: MF_E_GRL_VERSION_TOO_LOW + + MessageText: + + The current GRL on the machine does not meet the minimum version requirements.%0 + + + + + MessageId: MF_E_GRL_RENEWAL_NOT_FOUND + + MessageText: + + The current GRL on the machine does not contain any renewal entries for the specified revocation.%0 + + + + + MessageId: MF_E_GRL_EXTENSIBLE_ENTRY_NOT_FOUND + + MessageText: + + The current GRL on the machine does not contain any extensible entries for the specified extension GUID.%0 + + + + + MessageId: MF_E_KERNEL_UNTRUSTED + + MessageText: + + The kernel isn't secure for high security level content.%0 + + + + + MessageId: MF_E_PEAUTH_UNTRUSTED + + MessageText: + + The response from protected environment driver isn't valid.%0 + + + + + MessageId: MF_E_NON_PE_PROCESS + + MessageText: + + A non-PE process tried to talk to PEAuth.%0 + + + + + MessageId: MF_E_REBOOT_REQUIRED + + MessageText: + + We need to reboot the machine.%0 + + + + + MessageId: MF_S_WAIT_FOR_POLICY_SET + + MessageText: + + Protection for this stream is not guaranteed to be enforced until the MEPolicySet event is fired.%0 + + + + + MessageId: MF_S_VIDEO_DISABLED_WITH_UNKNOWN_SOFTWARE_OUTPUT + + MessageText: + + This video stream is disabled because it is being sent to an unknown software output.%0 + + + + + MessageId: MF_E_GRL_INVALID_FORMAT + + MessageText: + + The GRL file is not correctly formed, it may have been corrupted or overwritten.%0 + + + + + MessageId: MF_E_GRL_UNRECOGNIZED_FORMAT + + MessageText: + + The GRL file is in a format newer than those recognized by this GRL Reader.%0 + + + + + MessageId: MF_E_ALL_PROCESS_RESTART_REQUIRED + + MessageText: + + The GRL was reloaded and required all processes that can run protected media to restart.%0 + + + + + MessageId: MF_E_PROCESS_RESTART_REQUIRED + + MessageText: + + The GRL was reloaded and the current process needs to restart.%0 + + + + + MessageId: MF_E_USERMODE_UNTRUSTED + + MessageText: + + The user space is untrusted for protected content play.%0 + + + + + MessageId: MF_E_PEAUTH_SESSION_NOT_STARTED + + MessageText: + + PEAuth communication session hasn't been started.%0 + + + + + MessageId: MF_E_PEAUTH_PUBLICKEY_REVOKED + + MessageText: + + PEAuth's public key is revoked.%0 + + + + + MessageId: MF_E_GRL_ABSENT + + MessageText: + + The GRL is absent.%0 + + + + + MessageId: MF_S_PE_TRUSTED + + MessageText: + + The Protected Environment is trusted.%0 + + + + + MessageId: MF_E_PE_UNTRUSTED + + MessageText: + + The Protected Environment is untrusted.%0 + + + + + MessageId: MF_E_PEAUTH_NOT_STARTED + + MessageText: + + The Protected Environment Authorization service (PEAUTH) has not been started.%0 + + + + + MessageId: MF_E_INCOMPATIBLE_SAMPLE_PROTECTION + + MessageText: + + The sample protection algorithms supported by components are not compatible.%0 + + + + + MessageId: MF_E_PE_SESSIONS_MAXED + + MessageText: + + No more protected environment sessions can be supported.%0 + + + + + MessageId: MF_E_HIGH_SECURITY_LEVEL_CONTENT_NOT_ALLOWED + + MessageText: + + WMDRM ITA does not allow protected content with high security level for this release.%0 + + + + + MessageId: MF_E_TEST_SIGNED_COMPONENTS_NOT_ALLOWED + + MessageText: + + WMDRM ITA cannot allow the requested action for the content as one or more components is not properly signed.%0 + + + + + MessageId: MF_E_ITA_UNSUPPORTED_ACTION + + MessageText: + + WMDRM ITA does not support the requested action.%0 + + + + + MessageId: MF_E_ITA_ERROR_PARSING_SAP_PARAMETERS + + MessageText: + + WMDRM ITA encountered an error in parsing the Secure Audio Path parameters.%0 + + + + + MessageId: MF_E_POLICY_MGR_ACTION_OUTOFBOUNDS + + MessageText: + + The Policy Manager action passed in is invalid.%0 + + + + + MessageId: MF_E_BAD_OPL_STRUCTURE_FORMAT + + MessageText: + + The structure specifying Output Protection Level is not the correct format.%0 + + + + + MessageId: MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_PROTECTION_GUID + + MessageText: + + WMDRM ITA does not recognize the Explicite Analog Video Output Protection guid specified in the license.%0 + + + + + MessageId: MF_E_NO_PMP_HOST + + MessageText: + + IMFPMPHost object not available.%0 + + + + + MessageId: MF_E_ITA_OPL_DATA_NOT_INITIALIZED + + MessageText: + + WMDRM ITA could not initialize the Output Protection Level data.%0 + + + + + MessageId: MF_E_ITA_UNRECOGNIZED_ANALOG_VIDEO_OUTPUT + + MessageText: + + WMDRM ITA does not recognize the Analog Video Output specified by the OTA.%0 + + + + + MessageId: MF_E_ITA_UNRECOGNIZED_DIGITAL_VIDEO_OUTPUT + + MessageText: + + WMDRM ITA does not recognize the Digital Video Output specified by the OTA.%0 + + + + + MessageId: MF_E_CLOCK_INVALID_CONTINUITY_KEY + + MessageText: + + The continuity key supplied is not currently valid.%0 + + + + + MessageId: MF_E_CLOCK_NO_TIME_SOURCE + + MessageText: + + No Presentation Time Source has been specified.%0 + + + + + MessageId: MF_E_CLOCK_STATE_ALREADY_SET + + MessageText: + + The clock is already in the requested state.%0 + + + + + MessageId: MF_E_CLOCK_NOT_SIMPLE + + MessageText: + + The clock has too many advanced features to carry out the request.%0 + + + + + MessageId: MF_S_CLOCK_STOPPED + + MessageText: + + Timer::SetTimer returns this success code if called happened while timer is stopped. Timer is not going to be dispatched until clock is running%0 + + + + + MessageId: MF_E_NO_MORE_DROP_MODES + + MessageText: + + The component does not support any more drop modes.%0 + + + + + MessageId: MF_E_NO_MORE_QUALITY_LEVELS + + MessageText: + + The component does not support any more quality levels.%0 + + + + + MessageId: MF_E_DROPTIME_NOT_SUPPORTED + + MessageText: + + The component does not support drop time functionality.%0 + + + + + MessageId: MF_E_QUALITYKNOB_WAIT_LONGER + + MessageText: + + Quality Manager needs to wait longer before bumping the Quality Level up.%0 + + + + + MessageId: MF_E_QM_INVALIDSTATE + + MessageText: + + Quality Manager is in an invalid state. Quality Management is off at this moment.%0 + + + + + MessageId: MF_E_TRANSCODE_NO_CONTAINERTYPE + + MessageText: + + No transcode output container type is specified.%0 + + + + + MessageId: MF_E_TRANSCODE_PROFILE_NO_MATCHING_STREAMS + + MessageText: + + The profile does not have a media type configuration for any selected source streams.%0 + + + + + MessageId: MF_E_TRANSCODE_NO_MATCHING_ENCODER + + MessageText: + + Cannot find an encoder MFT that accepts the user preferred output type.%0 + + + + + MessageId: MF_E_ALLOCATOR_NOT_INITIALIZED + + MessageText: + + Memory allocator is not initialized.%0 + + + + + MessageId: MF_E_ALLOCATOR_NOT_COMMITED + + MessageText: + + Memory allocator is not committed yet.%0 + + + + + MessageId: MF_E_ALLOCATOR_ALREADY_COMMITED + + MessageText: + + Memory allocator has already been committed.%0 + + + + + MessageId: MF_E_STREAM_ERROR + + MessageText: + + An error occurred in media stream.%0 + + + + + MessageId: MF_E_INVALID_STREAM_STATE + + MessageText: + + Stream is not in a state to handle the request.%0 + + + + + MessageId: MF_E_HW_STREAM_NOT_CONNECTED + + MessageText: + + Hardware stream is not connected yet.%0 + + + + + Major Media Types + http://msdn.microsoft.com/en-us/library/windows/desktop/aa367377%28v=vs.85%29.aspx + + + + + Default + + + + + Audio + + + + + Video + + + + + Protected Media + + + + + Synchronized Accessible Media Interchange (SAMI) captions. + + + + + Script stream + + + + + Still image stream. + + + + + HTML stream. + + + + + Binary stream. + + + + + A stream that contains data files. + + + + + IMFActivate, defined in mfobjects.h + + + + + Retrieves the value associated with a key. + + + + + Retrieves the data type of the value associated with a key. + + + + + Queries whether a stored attribute value equals a specified PROPVARIANT. + + + + + Compares the attributes on this object with the attributes on another object. + + + + + Retrieves a UINT32 value associated with a key. + + + + + Retrieves a UINT64 value associated with a key. + + + + + Retrieves a double value associated with a key. + + + + + Retrieves a GUID value associated with a key. + + + + + Retrieves the length of a string value associated with a key. + + + + + Retrieves a wide-character string associated with a key. + + + + + Retrieves a wide-character string associated with a key. This method allocates the memory for the string. + + + + + Retrieves the length of a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. This method allocates the memory for the array. + + + + + Retrieves an interface pointer associated with a key. + + + + + Associates an attribute value with a key. + + + + + Removes a key/value pair from the object's attribute list. + + + + + Removes all key/value pairs from the object's attribute list. + + + + + Associates a UINT32 value with a key. + + + + + Associates a UINT64 value with a key. + + + + + Associates a double value with a key. + + + + + Associates a GUID value with a key. + + + + + Associates a wide-character string with a key. + + + + + Associates a byte array with a key. + + + + + Associates an IUnknown pointer with a key. + + + + + Locks the attribute store so that no other thread can access it. + + + + + Unlocks the attribute store. + + + + + Retrieves the number of attributes that are set on this object. + + + + + Retrieves an attribute at the specified index. + + + + + Copies all of the attributes from this object into another attribute store. + + + + + Creates the object associated with this activation object. + + + + + Shuts down the created object. + + + + + Detaches the created object from the activation object. + + + + + Represents a generic collection of IUnknown pointers. + + + + + Retrieves the number of objects in the collection. + + + + + Retrieves an object in the collection. + + + + + Adds an object to the collection. + + + + + Removes an object from the collection. + + + + + Removes an object from the collection. + + + + + Removes all items from the collection. + + + + + IMFMediaEvent - Represents an event generated by a Media Foundation object. Use this interface to get information about the event. + http://msdn.microsoft.com/en-us/library/windows/desktop/ms702249%28v=vs.85%29.aspx + Mfobjects.h + + + + + Retrieves the value associated with a key. + + + + + Retrieves the data type of the value associated with a key. + + + + + Queries whether a stored attribute value equals a specified PROPVARIANT. + + + + + Compares the attributes on this object with the attributes on another object. + + + + + Retrieves a UINT32 value associated with a key. + + + + + Retrieves a UINT64 value associated with a key. + + + + + Retrieves a double value associated with a key. + + + + + Retrieves a GUID value associated with a key. + + + + + Retrieves the length of a string value associated with a key. + + + + + Retrieves a wide-character string associated with a key. + + + + + Retrieves a wide-character string associated with a key. This method allocates the memory for the string. + + + + + Retrieves the length of a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. This method allocates the memory for the array. + + + + + Retrieves an interface pointer associated with a key. + + + + + Associates an attribute value with a key. + + + + + Removes a key/value pair from the object's attribute list. + + + + + Removes all key/value pairs from the object's attribute list. + + + + + Associates a UINT32 value with a key. + + + + + Associates a UINT64 value with a key. + + + + + Associates a double value with a key. + + + + + Associates a GUID value with a key. + + + + + Associates a wide-character string with a key. + + + + + Associates a byte array with a key. + + + + + Associates an IUnknown pointer with a key. + + + + + Locks the attribute store so that no other thread can access it. + + + + + Unlocks the attribute store. + + + + + Retrieves the number of attributes that are set on this object. + + + + + Retrieves an attribute at the specified index. + + + + + Copies all of the attributes from this object into another attribute store. + + + + + Retrieves the event type. + + + virtual HRESULT STDMETHODCALLTYPE GetType( + /* [out] */ __RPC__out MediaEventType *pmet) = 0; + + + + + Retrieves the extended type of the event. + + + virtual HRESULT STDMETHODCALLTYPE GetExtendedType( + /* [out] */ __RPC__out GUID *pguidExtendedType) = 0; + + + + + Retrieves an HRESULT that specifies the event status. + + + virtual HRESULT STDMETHODCALLTYPE GetStatus( + /* [out] */ __RPC__out HRESULT *phrStatus) = 0; + + + + + Retrieves the value associated with the event, if any. + + + virtual HRESULT STDMETHODCALLTYPE GetValue( + /* [out] */ __RPC__out PROPVARIANT *pvValue) = 0; + + + + + Implemented by the Microsoft Media Foundation sink writer object. + + + + + Adds a stream to the sink writer. + + + + + Sets the input format for a stream on the sink writer. + + + + + Initializes the sink writer for writing. + + + + + Delivers a sample to the sink writer. + + + + + Indicates a gap in an input stream. + + + + + Places a marker in the specified stream. + + + + + Notifies the media sink that a stream has reached the end of a segment. + + + + + Flushes one or more streams. + + + + + (Finalize) Completes all writing operations on the sink writer. + + + + + Queries the underlying media sink or encoder for an interface. + + + + + Gets statistics about the performance of the sink writer. + + + + + IMFTransform, defined in mftransform.h + + + + + Retrieves the minimum and maximum number of input and output streams. + + + virtual HRESULT STDMETHODCALLTYPE GetStreamLimits( + /* [out] */ __RPC__out DWORD *pdwInputMinimum, + /* [out] */ __RPC__out DWORD *pdwInputMaximum, + /* [out] */ __RPC__out DWORD *pdwOutputMinimum, + /* [out] */ __RPC__out DWORD *pdwOutputMaximum) = 0; + + + + + Retrieves the current number of input and output streams on this MFT. + + + virtual HRESULT STDMETHODCALLTYPE GetStreamCount( + /* [out] */ __RPC__out DWORD *pcInputStreams, + /* [out] */ __RPC__out DWORD *pcOutputStreams) = 0; + + + + + Retrieves the stream identifiers for the input and output streams on this MFT. + + + virtual HRESULT STDMETHODCALLTYPE GetStreamIDs( + DWORD dwInputIDArraySize, + /* [size_is][out] */ __RPC__out_ecount_full(dwInputIDArraySize) DWORD *pdwInputIDs, + DWORD dwOutputIDArraySize, + /* [size_is][out] */ __RPC__out_ecount_full(dwOutputIDArraySize) DWORD *pdwOutputIDs) = 0; + + + + + Gets the buffer requirements and other information for an input stream on this Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE GetInputStreamInfo( + DWORD dwInputStreamID, + /* [out] */ __RPC__out MFT_INPUT_STREAM_INFO *pStreamInfo) = 0; + + + + + Gets the buffer requirements and other information for an output stream on this Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE GetOutputStreamInfo( + DWORD dwOutputStreamID, + /* [out] */ __RPC__out MFT_OUTPUT_STREAM_INFO *pStreamInfo) = 0; + + + + + Gets the global attribute store for this Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE GetAttributes( + /* [out] */ __RPC__deref_out_opt IMFAttributes **pAttributes) = 0; + + + + + Retrieves the attribute store for an input stream on this MFT. + + + virtual HRESULT STDMETHODCALLTYPE GetInputStreamAttributes( + DWORD dwInputStreamID, + /* [out] */ __RPC__deref_out_opt IMFAttributes **pAttributes) = 0; + + + + + Retrieves the attribute store for an output stream on this MFT. + + + virtual HRESULT STDMETHODCALLTYPE GetOutputStreamAttributes( + DWORD dwOutputStreamID, + /* [out] */ __RPC__deref_out_opt IMFAttributes **pAttributes) = 0; + + + + + Removes an input stream from this MFT. + + + virtual HRESULT STDMETHODCALLTYPE DeleteInputStream( + DWORD dwStreamID) = 0; + + + + + Adds one or more new input streams to this MFT. + + + virtual HRESULT STDMETHODCALLTYPE AddInputStreams( + DWORD cStreams, + /* [in] */ __RPC__in DWORD *adwStreamIDs) = 0; + + + + + Gets an available media type for an input stream on this Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE GetInputAvailableType( + DWORD dwInputStreamID, + DWORD dwTypeIndex, + /* [out] */ __RPC__deref_out_opt IMFMediaType **ppType) = 0; + + + + + Retrieves an available media type for an output stream on this MFT. + + + virtual HRESULT STDMETHODCALLTYPE GetOutputAvailableType( + DWORD dwOutputStreamID, + DWORD dwTypeIndex, + /* [out] */ __RPC__deref_out_opt IMFMediaType **ppType) = 0; + + + + + Sets, tests, or clears the media type for an input stream on this Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE SetInputType( + DWORD dwInputStreamID, + /* [in] */ __RPC__in_opt IMFMediaType *pType, + DWORD dwFlags) = 0; + + + + + Sets, tests, or clears the media type for an output stream on this Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE SetOutputType( + DWORD dwOutputStreamID, + /* [in] */ __RPC__in_opt IMFMediaType *pType, + DWORD dwFlags) = 0; + + + + + Gets the current media type for an input stream on this Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE GetInputCurrentType( + DWORD dwInputStreamID, + /* [out] */ __RPC__deref_out_opt IMFMediaType **ppType) = 0; + + + + + Gets the current media type for an output stream on this Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE GetOutputCurrentType( + DWORD dwOutputStreamID, + /* [out] */ __RPC__deref_out_opt IMFMediaType **ppType) = 0; + + + + + Queries whether an input stream on this Media Foundation transform (MFT) can accept more data. + + + virtual HRESULT STDMETHODCALLTYPE GetInputStatus( + DWORD dwInputStreamID, + /* [out] */ __RPC__out DWORD *pdwFlags) = 0; + + + + + Queries whether the Media Foundation transform (MFT) is ready to produce output data. + + + virtual HRESULT STDMETHODCALLTYPE GetOutputStatus( + /* [out] */ __RPC__out DWORD *pdwFlags) = 0; + + + + + Sets the range of time stamps the client needs for output. + + + virtual HRESULT STDMETHODCALLTYPE SetOutputBounds( + LONGLONG hnsLowerBound, + LONGLONG hnsUpperBound) = 0; + + + + + Sends an event to an input stream on this Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE ProcessEvent( + DWORD dwInputStreamID, + /* [in] */ __RPC__in_opt IMFMediaEvent *pEvent) = 0; + + + + + Sends a message to the Media Foundation transform (MFT). + + + virtual HRESULT STDMETHODCALLTYPE ProcessMessage( + MFT_MESSAGE_TYPE eMessage, + ULONG_PTR ulParam) = 0; + + + + + Delivers data to an input stream on this Media Foundation transform (MFT). + + + virtual /* [local] */ HRESULT STDMETHODCALLTYPE ProcessInput( + DWORD dwInputStreamID, + IMFSample *pSample, + DWORD dwFlags) = 0; + + + + + Generates output from the current input data. + + + virtual /* [local] */ HRESULT STDMETHODCALLTYPE ProcessOutput( + DWORD dwFlags, + DWORD cOutputBufferCount, + /* [size_is][out][in] */ MFT_OUTPUT_DATA_BUFFER *pOutputSamples, + /* [out] */ DWORD *pdwStatus) = 0; + + + + + See mfobjects.h + + + + + Unknown event type. + + + + + Signals a serious error. + + + + + Custom event type. + + + + + A non-fatal error occurred during streaming. + + + + + Session Unknown + + + + + Raised after the IMFMediaSession::SetTopology method completes asynchronously + + + + + Raised by the Media Session when the IMFMediaSession::ClearTopologies method completes asynchronously. + + + + + Raised when the IMFMediaSession::Start method completes asynchronously. + + + + + Raised when the IMFMediaSession::Pause method completes asynchronously. + + + + + Raised when the IMFMediaSession::Stop method completes asynchronously. + + + + + Raised when the IMFMediaSession::Close method completes asynchronously. + + + + + Raised by the Media Session when it has finished playing the last presentation in the playback queue. + + + + + Raised by the Media Session when the playback rate changes. + + + + + Raised by the Media Session when it completes a scrubbing request. + + + + + Raised by the Media Session when the session capabilities change. + + + + + Raised by the Media Session when the status of a topology changes. + + + + + Raised by the Media Session when a new presentation starts. + + + + + Raised by a media source a new presentation is ready. + + + + + License acquisition is about to begin. + + + + + License acquisition is complete. + + + + + Individualization is about to begin. + + + + + Individualization is complete. + + + + + Signals the progress of a content enabler object. + + + + + A content enabler object's action is complete. + + + + + Raised by a trusted output if an error occurs while enforcing the output policy. + + + + + Contains status information about the enforcement of an output policy. + + + + + A media source started to buffer data. + + + + + A media source stopped buffering data. + + + + + The network source started opening a URL. + + + + + The network source finished opening a URL. + + + + + Raised by a media source at the start of a reconnection attempt. + + + + + Raised by a media source at the end of a reconnection attempt. + + + + + Raised by the enhanced video renderer (EVR) when it receives a user event from the presenter. + + + + + Raised by the Media Session when the format changes on a media sink. + + + + + Source Unknown + + + + + Raised when a media source starts without seeking. + + + + + Raised by a media stream when the source starts without seeking. + + + + + Raised when a media source seeks to a new position. + + + + + Raised by a media stream after a call to IMFMediaSource::Start causes a seek in the stream. + + + + + Raised by a media source when it starts a new stream. + + + + + Raised by a media source when it restarts or seeks a stream that is already active. + + + + + Raised by a media source when the IMFMediaSource::Stop method completes asynchronously. + + + + + Raised by a media stream when the IMFMediaSource::Stop method completes asynchronously. + + + + + Raised by a media source when the IMFMediaSource::Pause method completes asynchronously. + + + + + Raised by a media stream when the IMFMediaSource::Pause method completes asynchronously. + + + + + Raised by a media source when a presentation ends. + + + + + Raised by a media stream when the stream ends. + + + + + Raised when a media stream delivers a new sample. + + + + + Signals that a media stream does not have data available at a specified time. + + + + + Raised by a media stream when it starts or stops thinning the stream. + + + + + Raised by a media stream when the media type of the stream changes. + + + + + Raised by a media source when the playback rate changes. + + + + + Raised by the sequencer source when a segment is completed and is followed by another segment. + + + + + Raised by a media source when the source's characteristics change. + + + + + Raised by a media source to request a new playback rate. + + + + + Raised by a media source when it updates its metadata. + + + + + Raised by the sequencer source when the IMFSequencerSource::UpdateTopology method completes asynchronously. + + + + + Sink Unknown + + + + + Raised by a stream sink when it completes the transition to the running state. + + + + + Raised by a stream sink when it completes the transition to the stopped state. + + + + + Raised by a stream sink when it completes the transition to the paused state. + + + + + Raised by a stream sink when the rate has changed. + + + + + Raised by a stream sink to request a new media sample from the pipeline. + + + + + Raised by a stream sink after the IMFStreamSink::PlaceMarker method is called. + + + + + Raised by a stream sink when the stream has received enough preroll data to begin rendering. + + + + + Raised by a stream sink when it completes a scrubbing request. + + + + + Raised by a stream sink when the sink's media type is no longer valid. + + + + + Raised by the stream sinks of the EVR if the video device changes. + + + + + Provides feedback about playback quality to the quality manager. + + + + + Raised when a media sink becomes invalid. + + + + + The audio session display name changed. + + + + + The volume or mute state of the audio session changed + + + + + The audio device was removed. + + + + + The Windows audio server system was shut down. + + + + + The grouping parameters changed for the audio session. + + + + + The audio session icon changed. + + + + + The default audio format for the audio device changed. + + + + + The audio session was disconnected from a Windows Terminal Services session + + + + + The audio session was preempted by an exclusive-mode connection. + + + + + Trust Unknown + + + + + The output policy for a stream changed. + + + + + Content protection message + + + + + The IMFOutputTrustAuthority::SetPolicy method completed. + + + + + DRM License Backup Completed + + + + + DRM License Backup Progress + + + + + DRM License Restore Completed + + + + + DRM License Restore Progress + + + + + DRM License Acquisition Completed + + + + + DRM Individualization Completed + + + + + DRM Individualization Progress + + + + + DRM Proximity Completed + + + + + DRM License Store Cleaned + + + + + DRM Revocation Download Completed + + + + + Transform Unknown + + + + + Sent by an asynchronous MFT to request a new input sample. + + + + + Sent by an asynchronous MFT when new output data is available from the MFT. + + + + + Sent by an asynchronous Media Foundation transform (MFT) when a drain operation is complete. + + + + + Sent by an asynchronous MFT in response to an MFT_MESSAGE_COMMAND_MARKER message. + + + + + Media Foundation attribute guids + http://msdn.microsoft.com/en-us/library/windows/desktop/ms696989%28v=vs.85%29.aspx + + + + + Specifies whether an MFT performs asynchronous processing. + + + + + Enables the use of an asynchronous MFT. + + + + + Contains flags for an MFT activation object. + + + + + Specifies the category for an MFT. + + + + + Contains the class identifier (CLSID) of an MFT. + + + + + Contains the registered input types for a Media Foundation transform (MFT). + + + + + Contains the registered output types for a Media Foundation transform (MFT). + + + + + Contains the symbolic link for a hardware-based MFT. + + + + + Contains the display name for a hardware-based MFT. + + + + + Contains a pointer to the stream attributes of the connected stream on a hardware-based MFT. + + + + + Specifies whether a hardware-based MFT is connected to another hardware-based MFT. + + + + + Specifies the preferred output format for an encoder. + + + + + Specifies whether an MFT is registered only in the application's process. + + + + + Contains configuration properties for an encoder. + + + + + Specifies whether a hardware device source uses the system time for time stamps. + + + + + Contains an IMFFieldOfUseMFTUnlock pointer, which can be used to unlock the MFT. + + + + + Contains the merit value of a hardware codec. + + + + + Specifies whether a decoder is optimized for transcoding rather than for playback. + + + + + Contains a pointer to the proxy object for the application's presentation descriptor. + + + + + Contains a pointer to the presentation descriptor from the protected media path (PMP). + + + + + Specifies the duration of a presentation, in 100-nanosecond units. + + + + + Specifies the total size of the source file, in bytes. + + + + + Specifies the audio encoding bit rate for the presentation, in bits per second. + + + + + Specifies the video encoding bit rate for the presentation, in bits per second. + + + + + Specifies the MIME type of the content. + + + + + Specifies when a presentation was last modified. + + + + + The identifier of the playlist element in the presentation. + + + + + Contains the preferred RFC 1766 language of the media source. + + + + + The time at which the presentation must begin, relative to the start of the media source. + + + + + Specifies whether the audio streams in the presentation have a variable bit rate. + + + + + Media type Major Type + + + + + Media Type subtype + + + + + Audio block alignment + + + + + Audio average bytes per second + + + + + Audio number of channels + + + + + Audio samples per second + + + + + Audio bits per sample + + + + + Enables the source reader or sink writer to use hardware-based Media Foundation transforms (MFTs). + + + + + Contains additional format data for a media type. + + + + + Specifies for a media type whether each sample is independent of the other samples in the stream. + + + + + Specifies for a media type whether the samples have a fixed size. + + + + + Contains a DirectShow format GUID for a media type. + + + + + Specifies the preferred legacy format structure to use when converting an audio media type. + + + + + Specifies for a media type whether the media data is compressed. + + + + + Approximate data rate of the video stream, in bits per second, for a video media type. + + + + + Specifies the payload type of an Advanced Audio Coding (AAC) stream. + 0 - The stream contains raw_data_block elements only + 1 - Audio Data Transport Stream (ADTS). The stream contains an adts_sequence, as defined by MPEG-2. + 2 - Audio Data Interchange Format (ADIF). The stream contains an adif_sequence, as defined by MPEG-2. + 3 - The stream contains an MPEG-4 audio transport stream with a synchronization layer (LOAS) and a multiplex layer (LATM). + + + + + Specifies the audio profile and level of an Advanced Audio Coding (AAC) stream, as defined by ISO/IEC 14496-3. + + + + + Main interface for using Media Foundation with NAudio + + + + + initializes MediaFoundation - only needs to be called once per process + + + + + Enumerate the installed MediaFoundation transforms in the specified category + + A category from MediaFoundationTransformCategories + + + + + uninitializes MediaFoundation + + + + + Creates a Media type + + + + + Creates a media type from a WaveFormat + + + + + Creates a memory buffer of the specified size + + Memory buffer size in bytes + The memory buffer + + + + Creates a sample object + + The sample object + + + + Creates a new attributes store + + Initial size + The attributes store + + + + Creates a media foundation byte stream based on a stream object + (usable with WinRT streams) + + The input stream + A media foundation byte stream + + + + Creates a source reader based on a byte stream + + The byte stream + A media foundation source reader + + + + Interop definitions for MediaFoundation + thanks to Lucian Wischik for the initial work on many of these definitions (also various interfaces) + n.b. the goal is to make as much of this internal as possible, and provide + better .NET APIs using the MediaFoundationApi class instead + + + + + Initializes Microsoft Media Foundation. + + + + + Shuts down the Microsoft Media Foundation platform + + + + + Creates an empty media type. + + + + + Initializes a media type from a WAVEFORMATEX structure. + + + + + Converts a Media Foundation audio media type to a WAVEFORMATEX structure. + + TODO: try making second parameter out WaveFormatExtraData + + + + Creates the source reader from a URL. + + + + + Creates the source reader from a byte stream. + + + + + Creates the sink writer from a URL or byte stream. + + + + + Creates a Microsoft Media Foundation byte stream that wraps an IRandomAccessStream object. + + + + + Gets a list of Microsoft Media Foundation transforms (MFTs) that match specified search criteria. + + + + + Creates an empty media sample. + + + + + Allocates system memory and creates a media buffer to manage it. + + + + + Creates an empty attribute store. + + + + + Gets a list of output formats from an audio encoder. + + + + + All streams + + + + + First audio stream + + + + + First video stream + + + + + Media source + + + + + Media Foundation SDK Version + + + + + Media Foundation API Version + + + + + Media Foundation Version + + + + + Provides a generic way to store key/value pairs on an object. + http://msdn.microsoft.com/en-gb/library/windows/desktop/ms704598%28v=vs.85%29.aspx + + + + + Retrieves the value associated with a key. + + + + + Retrieves the data type of the value associated with a key. + + + + + Queries whether a stored attribute value equals a specified PROPVARIANT. + + + + + Compares the attributes on this object with the attributes on another object. + + + + + Retrieves a UINT32 value associated with a key. + + + + + Retrieves a UINT64 value associated with a key. + + + + + Retrieves a double value associated with a key. + + + + + Retrieves a GUID value associated with a key. + + + + + Retrieves the length of a string value associated with a key. + + + + + Retrieves a wide-character string associated with a key. + + + + + Retrieves a wide-character string associated with a key. This method allocates the memory for the string. + + + + + Retrieves the length of a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. This method allocates the memory for the array. + + + + + Retrieves an interface pointer associated with a key. + + + + + Associates an attribute value with a key. + + + + + Removes a key/value pair from the object's attribute list. + + + + + Removes all key/value pairs from the object's attribute list. + + + + + Associates a UINT32 value with a key. + + + + + Associates a UINT64 value with a key. + + + + + Associates a double value with a key. + + + + + Associates a GUID value with a key. + + + + + Associates a wide-character string with a key. + + + + + Associates a byte array with a key. + + + + + Associates an IUnknown pointer with a key. + + + + + Locks the attribute store so that no other thread can access it. + + + + + Unlocks the attribute store. + + + + + Retrieves the number of attributes that are set on this object. + + + + + Retrieves an attribute at the specified index. + + + + + Copies all of the attributes from this object into another attribute store. + + + + + IMFByteStream + http://msdn.microsoft.com/en-gb/library/windows/desktop/ms698720%28v=vs.85%29.aspx + + + + + Retrieves the characteristics of the byte stream. + virtual HRESULT STDMETHODCALLTYPE GetCapabilities(/*[out]*/ __RPC__out DWORD *pdwCapabilities) = 0; + + + + + Retrieves the length of the stream. + virtual HRESULT STDMETHODCALLTYPE GetLength(/*[out]*/ __RPC__out QWORD *pqwLength) = 0; + + + + + Sets the length of the stream. + virtual HRESULT STDMETHODCALLTYPE SetLength(/*[in]*/ QWORD qwLength) = 0; + + + + + Retrieves the current read or write position in the stream. + virtual HRESULT STDMETHODCALLTYPE GetCurrentPosition(/*[out]*/ __RPC__out QWORD *pqwPosition) = 0; + + + + + Sets the current read or write position. + virtual HRESULT STDMETHODCALLTYPE SetCurrentPosition(/*[in]*/ QWORD qwPosition) = 0; + + + + + Queries whether the current position has reached the end of the stream. + virtual HRESULT STDMETHODCALLTYPE IsEndOfStream(/*[out]*/ __RPC__out BOOL *pfEndOfStream) = 0; + + + + + Reads data from the stream. + virtual HRESULT STDMETHODCALLTYPE Read(/*[size_is][out]*/ __RPC__out_ecount_full(cb) BYTE *pb, /*[in]*/ ULONG cb, /*[out]*/ __RPC__out ULONG *pcbRead) = 0; + + + + + Begins an asynchronous read operation from the stream. + virtual /*[local]*/ HRESULT STDMETHODCALLTYPE BeginRead(/*[out]*/ _Out_writes_bytes_(cb) BYTE *pb, /*[in]*/ ULONG cb, /*[in]*/ IMFAsyncCallback *pCallback, /*[in]*/ IUnknown *punkState) = 0; + + + + + Completes an asynchronous read operation. + virtual /*[local]*/ HRESULT STDMETHODCALLTYPE EndRead(/*[in]*/ IMFAsyncResult *pResult, /*[out]*/ _Out_ ULONG *pcbRead) = 0; + + + + + Writes data to the stream. + virtual HRESULT STDMETHODCALLTYPE Write(/*[size_is][in]*/ __RPC__in_ecount_full(cb) const BYTE *pb, /*[in]*/ ULONG cb, /*[out]*/ __RPC__out ULONG *pcbWritten) = 0; + + + + + Begins an asynchronous write operation to the stream. + virtual /*[local]*/ HRESULT STDMETHODCALLTYPE BeginWrite(/*[in]*/ _In_reads_bytes_(cb) const BYTE *pb, /*[in]*/ ULONG cb, /*[in]*/ IMFAsyncCallback *pCallback, /*[in]*/ IUnknown *punkState) = 0; + + + + + Completes an asynchronous write operation. + virtual /*[local]*/ HRESULT STDMETHODCALLTYPE EndWrite(/*[in]*/ IMFAsyncResult *pResult, /*[out]*/ _Out_ ULONG *pcbWritten) = 0; + + + + + Moves the current position in the stream by a specified offset. + virtual HRESULT STDMETHODCALLTYPE Seek(/*[in]*/ MFBYTESTREAM_SEEK_ORIGIN SeekOrigin, /*[in]*/ LONGLONG llSeekOffset, /*[in]*/ DWORD dwSeekFlags, /*[out]*/ __RPC__out QWORD *pqwCurrentPosition) = 0; + + + + + Clears any internal buffers used by the stream. + virtual HRESULT STDMETHODCALLTYPE Flush( void) = 0; + + + + + Closes the stream and releases any resources associated with the stream. + virtual HRESULT STDMETHODCALLTYPE Close( void) = 0; + + + + + IMFMediaBuffer + http://msdn.microsoft.com/en-gb/library/windows/desktop/ms696261%28v=vs.85%29.aspx + + + + + Gives the caller access to the memory in the buffer. + + + + + Unlocks a buffer that was previously locked. + + + + + Retrieves the length of the valid data in the buffer. + + + + + Sets the length of the valid data in the buffer. + + + + + Retrieves the allocated size of the buffer. + + + + + Represents a description of a media format. + http://msdn.microsoft.com/en-us/library/windows/desktop/ms704850%28v=vs.85%29.aspx + + + + + Retrieves the value associated with a key. + + + + + Retrieves the data type of the value associated with a key. + + + + + Queries whether a stored attribute value equals a specified PROPVARIANT. + + + + + Compares the attributes on this object with the attributes on another object. + + + + + Retrieves a UINT32 value associated with a key. + + + + + Retrieves a UINT64 value associated with a key. + + + + + Retrieves a double value associated with a key. + + + + + Retrieves a GUID value associated with a key. + + + + + Retrieves the length of a string value associated with a key. + + + + + Retrieves a wide-character string associated with a key. + + + + + Retrieves a wide-character string associated with a key. This method allocates the memory for the string. + + + + + Retrieves the length of a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. This method allocates the memory for the array. + + + + + Retrieves an interface pointer associated with a key. + + + + + Associates an attribute value with a key. + + + + + Removes a key/value pair from the object's attribute list. + + + + + Removes all key/value pairs from the object's attribute list. + + + + + Associates a UINT32 value with a key. + + + + + Associates a UINT64 value with a key. + + + + + Associates a double value with a key. + + + + + Associates a GUID value with a key. + + + + + Associates a wide-character string with a key. + + + + + Associates a byte array with a key. + + + + + Associates an IUnknown pointer with a key. + + + + + Locks the attribute store so that no other thread can access it. + + + + + Unlocks the attribute store. + + + + + Retrieves the number of attributes that are set on this object. + + + + + Retrieves an attribute at the specified index. + + + + + Copies all of the attributes from this object into another attribute store. + + + + + Retrieves the major type of the format. + + + + + Queries whether the media type is a compressed format. + + + + + Compares two media types and determines whether they are identical. + + + + + Retrieves an alternative representation of the media type. + + + + + Frees memory that was allocated by the GetRepresentation method. + + + + + http://msdn.microsoft.com/en-gb/library/windows/desktop/ms702192%28v=vs.85%29.aspx + + + + + Retrieves the value associated with a key. + + + + + Retrieves the data type of the value associated with a key. + + + + + Queries whether a stored attribute value equals a specified PROPVARIANT. + + + + + Compares the attributes on this object with the attributes on another object. + + + + + Retrieves a UINT32 value associated with a key. + + + + + Retrieves a UINT64 value associated with a key. + + + + + Retrieves a double value associated with a key. + + + + + Retrieves a GUID value associated with a key. + + + + + Retrieves the length of a string value associated with a key. + + + + + Retrieves a wide-character string associated with a key. + + + + + Retrieves a wide-character string associated with a key. This method allocates the memory for the string. + + + + + Retrieves the length of a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. + + + + + Retrieves a byte array associated with a key. This method allocates the memory for the array. + + + + + Retrieves an interface pointer associated with a key. + + + + + Associates an attribute value with a key. + + + + + Removes a key/value pair from the object's attribute list. + + + + + Removes all key/value pairs from the object's attribute list. + + + + + Associates a UINT32 value with a key. + + + + + Associates a UINT64 value with a key. + + + + + Associates a double value with a key. + + + + + Associates a GUID value with a key. + + + + + Associates a wide-character string with a key. + + + + + Associates a byte array with a key. + + + + + Associates an IUnknown pointer with a key. + + + + + Locks the attribute store so that no other thread can access it. + + + + + Unlocks the attribute store. + + + + + Retrieves the number of attributes that are set on this object. + + + + + Retrieves an attribute at the specified index. + + + + + Copies all of the attributes from this object into another attribute store. + + + + + Retrieves flags associated with the sample. + + + + + Sets flags associated with the sample. + + + + + Retrieves the presentation time of the sample. + + + + + Sets the presentation time of the sample. + + + + + Retrieves the duration of the sample. + + + + + Sets the duration of the sample. + + + + + Retrieves the number of buffers in the sample. + + + + + Retrieves a buffer from the sample. + + + + + Converts a sample with multiple buffers into a sample with a single buffer. + + + + + Adds a buffer to the end of the list of buffers in the sample. + + + + + Removes a buffer at a specified index from the sample. + + + + + Removes all buffers from the sample. + + + + + Retrieves the total length of the valid data in all of the buffers in the sample. + + + + + Copies the sample data to a buffer. + + + + + IMFSourceReader interface + http://msdn.microsoft.com/en-us/library/windows/desktop/dd374655%28v=vs.85%29.aspx + + + + + Queries whether a stream is selected. + + + + + Selects or deselects one or more streams. + + + + + Gets a format that is supported natively by the media source. + + + + + Gets the current media type for a stream. + + + + + Sets the media type for a stream. + + + + + Seeks to a new position in the media source. + + + + + Reads the next sample from the media source. + + + + + Flushes one or more streams. + + + + + Queries the underlying media source or decoder for an interface. + + + + + Gets an attribute from the underlying media source. + + + + + Contains flags that indicate the status of the IMFSourceReader::ReadSample method + http://msdn.microsoft.com/en-us/library/windows/desktop/dd375773(v=vs.85).aspx + + + + + No Error + + + + + An error occurred. If you receive this flag, do not make any further calls to IMFSourceReader methods. + + + + + The source reader reached the end of the stream. + + + + + One or more new streams were created + + + + + The native format has changed for one or more streams. The native format is the format delivered by the media source before any decoders are inserted. + + + + + The current media has type changed for one or more streams. To get the current media type, call the IMFSourceReader::GetCurrentMediaType method. + + + + + There is a gap in the stream. This flag corresponds to an MEStreamTick event from the media source. + + + + + All transforms inserted by the application have been removed for a particular stream. + + + + + Media Foundation Transform Categories + + + + + MFT_CATEGORY_VIDEO_DECODER + + + + + MFT_CATEGORY_VIDEO_ENCODER + + + + + MFT_CATEGORY_VIDEO_EFFECT + + + + + MFT_CATEGORY_MULTIPLEXER + + + + + MFT_CATEGORY_DEMULTIPLEXER + + + + + MFT_CATEGORY_AUDIO_DECODER + + + + + MFT_CATEGORY_AUDIO_ENCODER + + + + + MFT_CATEGORY_AUDIO_EFFECT + + + + + MFT_CATEGORY_VIDEO_PROCESSOR + + + + + MFT_CATEGORY_OTHER + + + + + Contains information about an input stream on a Media Foundation transform (MFT) + + + + + Maximum amount of time between an input sample and the corresponding output sample, in 100-nanosecond units. + + + + + Bitwise OR of zero or more flags from the _MFT_INPUT_STREAM_INFO_FLAGS enumeration. + + + + + The minimum size of each input buffer, in bytes. + + + + + Maximum amount of input data, in bytes, that the MFT holds to perform lookahead. + + + + + The memory alignment required for input buffers. If the MFT does not require a specific alignment, the value is zero. + + + + + Contains information about an output buffer for a Media Foundation transform. + + + + + Output stream identifier. + + + + + Pointer to the IMFSample interface. + + + + + Before calling ProcessOutput, set this member to zero. + + + + + Before calling ProcessOutput, set this member to NULL. + + + + + Contains information about an output stream on a Media Foundation transform (MFT). + + + + + Bitwise OR of zero or more flags from the _MFT_OUTPUT_STREAM_INFO_FLAGS enumeration. + + + + + Minimum size of each output buffer, in bytes. + + + + + The memory alignment required for output buffers. + + + + + Defines messages for a Media Foundation transform (MFT). + + + + + Requests the MFT to flush all stored data. + + + + + Requests the MFT to drain any stored data. + + + + + Sets or clears the Direct3D Device Manager for DirectX Video Accereration (DXVA). + + + + + Drop samples - requires Windows 7 + + + + + Command Tick - requires Windows 8 + + + + + Notifies the MFT that streaming is about to begin. + + + + + Notifies the MFT that streaming is about to end. + + + + + Notifies the MFT that an input stream has ended. + + + + + Notifies the MFT that the first sample is about to be processed. + + + + + Marks a point in the stream. This message applies only to asynchronous MFTs. Requires Windows 7 + + + + + Contains media type information for registering a Media Foundation transform (MFT). + + + + + The major media type. + + + + + The Media Subtype + + + + + Contains statistics about the performance of the sink writer. + + + + + The size of the structure, in bytes. + + + + + The time stamp of the most recent sample given to the sink writer. + + + + + The time stamp of the most recent sample to be encoded. + + + + + The time stamp of the most recent sample given to the media sink. + + + + + The time stamp of the most recent stream tick. + + + + + The system time of the most recent sample request from the media sink. + + + + + The number of samples received. + + + + + The number of samples encoded. + + + + + The number of samples given to the media sink. + + + + + The number of stream ticks received. + + + + + The amount of data, in bytes, currently waiting to be processed. + + + + + The total amount of data, in bytes, that has been sent to the media sink. + + + + + The number of pending sample requests. + + + + + The average rate, in media samples per 100-nanoseconds, at which the application sent samples to the sink writer. + + + + + The average rate, in media samples per 100-nanoseconds, at which the sink writer sent samples to the encoder + + + + + The average rate, in media samples per 100-nanoseconds, at which the sink writer sent samples to the media sink. + + + + + Contains flags for registering and enumeration Media Foundation transforms (MFTs). + + + + + None + + + + + The MFT performs synchronous data processing in software. + + + + + The MFT performs asynchronous data processing in software. + + + + + The MFT performs hardware-based data processing, using either the AVStream driver or a GPU-based proxy MFT. + + + + + The MFT that must be unlocked by the application before use. + + + + + For enumeration, include MFTs that were registered in the caller's process. + + + + + The MFT is optimized for transcoding rather than playback. + + + + + For enumeration, sort and filter the results. + + + + + Bitwise OR of all the flags, excluding MFT_ENUM_FLAG_SORTANDFILTER. + + + + + Indicates the status of an input stream on a Media Foundation transform (MFT). + + + + + None + + + + + The input stream can receive more data at this time. + + + + + Describes an input stream on a Media Foundation transform (MFT). + + + + + No flags set + + + + + Each media sample (IMFSample interface) of input data must contain complete, unbroken units of data. + + + + + Each media sample that the client provides as input must contain exactly one unit of data, as defined for the MFT_INPUT_STREAM_WHOLE_SAMPLES flag. + + + + + All input samples must be the same size. + + + + + MTF Input Stream Holds buffers + + + + + The MFT does not hold input samples after the IMFTransform::ProcessInput method returns. + + + + + This input stream can be removed by calling IMFTransform::DeleteInputStream. + + + + + This input stream is optional. + + + + + The MFT can perform in-place processing. + + + + + Defines flags for the IMFTransform::ProcessOutput method. + + + + + None + + + + + The MFT can still generate output from this stream without receiving any more input. + + + + + The format has changed on this output stream, or there is a new preferred format for this stream. + + + + + The MFT has removed this output stream. + + + + + There is no sample ready for this stream. + + + + + Indicates whether a Media Foundation transform (MFT) can produce output data. + + + + + None + + + + + There is a sample available for at least one output stream. + + + + + Describes an output stream on a Media Foundation transform (MFT). + + + + + No flags set + + + + + Each media sample (IMFSample interface) of output data from the MFT contains complete, unbroken units of data. + + + + + Each output sample contains exactly one unit of data, as defined for the MFT_OUTPUT_STREAM_WHOLE_SAMPLES flag. + + + + + All output samples are the same size. + + + + + The MFT can discard the output data from this output stream, if requested by the client. + + + + + This output stream is optional. + + + + + The MFT provides the output samples for this stream, either by allocating them internally or by operating directly on the input samples. + + + + + The MFT can either provide output samples for this stream or it can use samples that the client allocates. + + + + + The MFT does not require the client to process the output for this stream. + + + + + The MFT might remove this output stream during streaming. + + + + + Defines flags for processing output samples in a Media Foundation transform (MFT). + + + + + None + + + + + Do not produce output for streams in which the pSample member of the MFT_OUTPUT_DATA_BUFFER structure is NULL. + + + + + Regenerates the last output sample. + + + + + Process Output Status flags + + + + + None + + + + + The Media Foundation transform (MFT) has created one or more new output streams. + + + + + Defines flags for the setting or testing the media type on a Media Foundation transform (MFT). + + + + + None + + + + + Test the proposed media type, but do not set it. + + + + + Media Type helper class, simplifying working with IMFMediaType + (will probably change in the future, to inherit from an attributes class) + Currently does not release the COM object, so you must do that yourself + + + + + Wraps an existing IMFMediaType object + + The IMFMediaType object + + + + Creates and wraps a new IMFMediaType object + + + + + Creates and wraps a new IMFMediaType object based on a WaveFormat + + WaveFormat + + + + Tries to get a UINT32 value, returning a default value if it doesn't exist + + Attribute key + Default value + Value or default if key doesn't exist + + + + The Sample Rate (valid for audio media types) + + + + + The number of Channels (valid for audio media types) + + + + + The number of bits per sample (n.b. not always valid for compressed audio types) + + + + + The average bytes per second (valid for audio media types) + + + + + The Media Subtype. For audio, is a value from the AudioSubtypes class + + + + + The Major type, e.g. audio or video (from the MediaTypes class) + + + + + Access to the actual IMFMediaType object + Use to pass to MF APIs or Marshal.ReleaseComObject when you are finished with it + + + + + An abstract base class for simplifying working with Media Foundation Transforms + You need to override the method that actually creates and configures the transform + + + + + The Source Provider + + + + + The Output WaveFormat + + + + + Constructs a new MediaFoundationTransform wrapper + Will read one second at a time + + The source provider for input data to the transform + The desired output format + + + + To be implemented by overriding classes. Create the transform object, set up its input and output types, + and configure any custom properties in here + + An object implementing IMFTrasform + + + + Disposes this MediaFoundation transform + + + + + Disposes this Media Foundation Transform + + + + + Destructor + + + + + The output WaveFormat of this Media Foundation Transform + + + + + Reads data out of the source, passing it through the transform + + Output buffer + Offset within buffer to write to + Desired byte count + Number of bytes read + + + + Attempts to read from the transform + Some useful info here: + http://msdn.microsoft.com/en-gb/library/windows/desktop/aa965264%28v=vs.85%29.aspx#process_data + + + + + + Indicate that the source has been repositioned and completely drain out the transforms buffers + + + + + Represents a MIDI meta event with raw data + + + + + Raw data contained in the meta event + + + + + Creates a meta event with raw data + + + + + Creates a deep clone of this MIDI event. + + + + + Describes this meta event + + + + + + + + + + MIDI In Message Information + + + + + Create a new MIDI In Message EventArgs + + + + + + + The Raw message received from the MIDI In API + + + + + The raw message interpreted as a MidiEvent + + + + + The timestamp in milliseconds for this message + + + + + Represents a MIDI Channel AfterTouch Event. + + + + + Creates a new ChannelAfterTouchEvent from raw MIDI data + + A binary reader + + + + Creates a new Channel After-Touch Event + + Absolute time + Channel + After-touch pressure + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + The aftertouch pressure value + + + + + Represents a MIDI control change event + + + + + Reads a control change event from a MIDI stream + + Binary reader on the MIDI stream + + + + Creates a control change event + + Time + MIDI Channel Number + The MIDI Controller + Controller value + + + + Describes this control change event + + A string describing this event + + + + + + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + The controller number + + + + + The controller value + + + + + Represents a MIDI key signature event event + + + + + Reads a new track sequence number event from a MIDI stream + + The MIDI stream + the data length + + + + Creates a new Key signature event with the specified data + + + + + Creates a deep clone of this MIDI event. + + + + + Number of sharps or flats + + + + + Major or Minor key + + + + + Describes this event + + String describing the event + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Represents a MIDI meta event + + + + + Gets the type of this meta event + + + + + Empty constructor + + + + + Custom constructor for use by derived types, who will manage the data themselves + + Meta event type + Meta data length + Absolute time + + + + Creates a deep clone of this MIDI event. + + + + + Reads a meta-event from a stream + + A binary reader based on the stream of MIDI data + A new MetaEvent object + + + + Describes this meta event + + + + + + + + + + MIDI MetaEvent Type + + + + Track sequence number + + + Text event + + + Copyright + + + Sequence track name + + + Track instrument name + + + Lyric + + + Marker + + + Cue point + + + Program (patch) name + + + Device (port) name + + + MIDI Channel (not official?) + + + MIDI Port (not official?) + + + End track + + + Set tempo + + + SMPTE offset + + + Time signature + + + Key signature + + + Sequencer specific + + + + MIDI command codes + + + + Note Off + + + Note On + + + Key After-touch + + + Control change + + + Patch change + + + Channel after-touch + + + Pitch wheel change + + + Sysex message + + + Eox (comes at end of a sysex message) + + + Timing clock (used when synchronization is required) + + + Start sequence + + + Continue sequence + + + Stop sequence + + + Auto-Sensing + + + Meta-event + + + + MidiController enumeration + http://www.midi.org/techspecs/midimessages.php#3 + + + + Bank Select (MSB) + + + Modulation (MSB) + + + Breath Controller + + + Foot controller (MSB) + + + Main volume + + + Pan + + + Expression + + + Bank Select LSB + + + Sustain + + + Portamento On/Off + + + Sostenuto On/Off + + + Soft Pedal On/Off + + + Legato Footswitch + + + Reset all controllers + + + All notes off + + + + Represents an individual MIDI event + + + + The MIDI command code + + + + Creates a MidiEvent from a raw message received using + the MME MIDI In APIs + + The short MIDI message + A new MIDI Event + + + + Constructs a MidiEvent from a BinaryStream + + The binary stream of MIDI data + The previous MIDI event (pass null for first event) + A new MidiEvent + + + + Converts this MIDI event to a short message (32 bit integer) that + can be sent by the Windows MIDI out short message APIs + Cannot be implemented for all MIDI messages + + A short message + + + + Default constructor + + + + + Creates a MIDI event with specified parameters + + Absolute time of this event + MIDI channel number + MIDI command code + + + + Creates a deep clone of this MIDI event. + + + + + The MIDI Channel Number for this event (1-16) + + + + + The Delta time for this event + + + + + The absolute time for this event + + + + + The command code for this event + + + + + Whether this is a note off event + + + + + Whether this is a note on event + + + + + Determines if this is an end track event + + + + + Displays a summary of the MIDI event + + A string containing a brief description of this MIDI event + + + + Utility function that can read a variable length integer from a binary stream + + The binary stream + The integer read + + + + Writes a variable length integer to a binary stream + + Binary stream + The value to write + + + + Exports this MIDI event's data + Overriden in derived classes, but they should call this version + + Absolute time used to calculate delta. + Is updated ready for the next delta calculation + Stream to write to + + + + A helper class to manage collection of MIDI events + It has the ability to organise them in tracks + + + + + Creates a new Midi Event collection + + Initial file type + Delta Ticks Per Quarter Note + + + + The number of tracks + + + + + The absolute time that should be considered as time zero + Not directly used here, but useful for timeshifting applications + + + + + The number of ticks per quarter note + + + + + Gets events on a specified track + + Track number + The list of events + + + + Gets events on a specific track + + Track number + The list of events + + + + Adds a new track + + The new track event list + + + + Adds a new track + + Initial events to add to the new track + The new track event list + + + + Removes a track + + Track number to remove + + + + Clears all events + + + + + The MIDI file type + + + + + Adds an event to the appropriate track depending on file type + + The event to be added + The original (or desired) track number + When adding events in type 0 mode, the originalTrack parameter + is ignored. If in type 1 mode, it will use the original track number to + store the new events. If the original track was 0 and this is a channel based + event, it will create new tracks if necessary and put it on the track corresponding + to its channel number + + + + Sorts, removes empty tracks and adds end track markers + + + + + Gets an enumerator for the lists of track events + + + + + Gets an enumerator for the lists of track events + + + + + Utility class for comparing MidiEvent objects + + + + + Compares two MidiEvents + Sorts by time, with EndTrack always sorted to the end + + + + + Class able to read a MIDI file + + + + + Opens a MIDI file for reading + + Name of MIDI file + + + + MIDI File format + + + + + Opens a MIDI file for reading + + Name of MIDI file + If true will error on non-paired note events + + + + The collection of events in this MIDI file + + + + + Number of tracks in this MIDI file + + + + + Delta Ticks Per Quarter Note + + + + + Describes the MIDI file + + A string describing the MIDI file and its events + + + + Exports a MIDI file + + Filename to export to + Events to export + + + + Represents a MIDI in device + + + + + Called when a MIDI message is received + + + + + An invalid MIDI message + + + + + Gets the number of MIDI input devices available in the system + + + + + Opens a specified MIDI in device + + The device number + + + + Closes this MIDI in device + + + + + Closes this MIDI in device + + + + + Start the MIDI in device + + + + + Stop the MIDI in device + + + + + Reset the MIDI in device + + + + + Gets the MIDI in device info + + + + + Closes the MIDI out device + + True if called from Dispose + + + + Cleanup + + + + + MIDI In Device Capabilities + + + + + wMid + + + + + wPid + + + + + vDriverVersion + + + + + Product Name + + + + + Support - Reserved + + + + + Gets the manufacturer of this device + + + + + Gets the product identifier (manufacturer specific) + + + + + Gets the product name + + + + + MIM_OPEN + + + + + MIM_CLOSE + + + + + MIM_DATA + + + + + MIM_LONGDATA + + + + + MIM_ERROR + + + + + MIM_LONGERROR + + + + + MIM_MOREDATA + + + + + MOM_OPEN + + + + + MOM_CLOSE + + + + + MOM_DONE + + + + + Represents a MIDI message + + + + + Creates a new MIDI message + + Status + Data parameter 1 + Data parameter 2 + + + + Creates a new MIDI message from a raw message + + A packed MIDI message from an MMIO function + + + + Creates a Note On message + + Note number (0 to 127) + Volume (0 to 127) + MIDI channel (1 to 16) + A new MidiMessage object + + + + Creates a Note Off message + + Note number + Volume + MIDI channel (1-16) + A new MidiMessage object + + + + Creates a patch change message + + The patch number + The MIDI channel number (1-16) + A new MidiMessageObject + + + + Creates a Control Change message + + The controller number to change + The value to set the controller to + The MIDI channel number (1-16) + A new MidiMessageObject + + + + Returns the raw MIDI message data + + + + + Represents a MIDI out device + + + + + Gets the number of MIDI devices available in the system + + + + + Gets the MIDI Out device info + + + + + Opens a specified MIDI out device + + The device number + + + + Closes this MIDI out device + + + + + Closes this MIDI out device + + + + + Gets or sets the volume for this MIDI out device + + + + + Resets the MIDI out device + + + + + Sends a MIDI out message + + Message + Parameter 1 + Parameter 2 + + + + Sends a MIDI message to the MIDI out device + + The message to send + + + + Closes the MIDI out device + + True if called from Dispose + + + + Send a long message, for example sysex. + + The bytes to send. + + + + Cleanup + + + + + class representing the capabilities of a MIDI out device + MIDIOUTCAPS: http://msdn.microsoft.com/en-us/library/dd798467%28VS.85%29.aspx + + + + + MIDICAPS_VOLUME + + + + + separate left-right volume control + MIDICAPS_LRVOLUME + + + + + MIDICAPS_CACHE + + + + + MIDICAPS_STREAM + driver supports midiStreamOut directly + + + + + Gets the manufacturer of this device + + + + + Gets the product identifier (manufacturer specific) + + + + + Gets the product name + + + + + Returns the number of supported voices + + + + + Gets the polyphony of the device + + + + + Returns true if the device supports all channels + + + + + Queries whether a particular channel is supported + + Channel number to test + True if the channel is supported + + + + Returns true if the device supports patch caching + + + + + Returns true if the device supports separate left and right volume + + + + + Returns true if the device supports MIDI stream out + + + + + Returns true if the device supports volume control + + + + + Returns the type of technology used by this MIDI out device + + + + + Represents the different types of technology used by a MIDI out device + + from mmsystem.h + + + The device is a MIDI port + + + The device is a MIDI synth + + + The device is a square wave synth + + + The device is an FM synth + + + The device is a MIDI mapper + + + The device is a WaveTable synth + + + The device is a software synth + + + + Represents a note MIDI event + + + + + Reads a NoteEvent from a stream of MIDI data + + Binary Reader for the stream + + + + Creates a MIDI Note Event with specified parameters + + Absolute time of this event + MIDI channel number + MIDI command code + MIDI Note Number + MIDI Note Velocity + + + + + + + + + The MIDI note number + + + + + The note velocity + + + + + The note name + + + + + Describes the Note Event + + Note event as a string + + + + + + + + + Represents a MIDI note on event + + + + + Reads a new Note On event from a stream of MIDI data + + Binary reader on the MIDI data stream + + + + Creates a NoteOn event with specified parameters + + Absolute time of this event + MIDI channel number + MIDI note number + MIDI note velocity + MIDI note duration + + + + Creates a deep clone of this MIDI event. + + + + + The associated Note off event + + + + + Get or set the Note Number, updating the off event at the same time + + + + + Get or set the channel, updating the off event at the same time + + + + + The duration of this note + + + There must be a note off event + + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Represents a MIDI patch change event + + + + + Gets the default MIDI instrument names + + + + + Reads a new patch change event from a MIDI stream + + Binary reader for the MIDI stream + + + + Creates a new patch change event + + Time of the event + Channel number + Patch number + + + + The Patch Number + + + + + Describes this patch change event + + String describing the patch change event + + + + Gets as a short message for sending with the midiOutShortMsg API + + short message + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Represents a MIDI pitch wheel change event + + + + + Reads a pitch wheel change event from a MIDI stream + + The MIDI stream to read from + + + + Creates a new pitch wheel change event + + Absolute event time + Channel + Pitch wheel value + + + + Describes this pitch wheel change event + + String describing this pitch wheel change event + + + + Pitch Wheel Value 0 is minimum, 0x2000 (8192) is default, 0x3FFF (16383) is maximum + + + + + Gets a short message + + Integer to sent as short message + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Represents a Sequencer Specific event + + + + + Reads a new sequencer specific event from a MIDI stream + + The MIDI stream + The data length + + + + Creates a new Sequencer Specific event + + The sequencer specific data + Absolute time of this event + + + + Creates a deep clone of this MIDI event. + + + + + The contents of this sequencer specific + + + + + Describes this MIDI text event + + A string describing this event + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Creates a new time signature event + + + + + Reads a new time signature event from a MIDI stream + + The MIDI stream + The data length + + + + Creates a deep clone of this MIDI event. + + + + + Hours + + + + + Minutes + + + + + Seconds + + + + + Frames + + + + + SubFrames + + + + + Describes this time signature event + + A string describing this event + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Represents a MIDI sysex message + + + + + Reads a sysex message from a MIDI stream + + Stream of MIDI data + a new sysex message + + + + Creates a deep clone of this MIDI event. + + + + + Describes this sysex message + + A string describing the sysex message + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Represents a MIDI tempo event + + + + + Reads a new tempo event from a MIDI stream + + The MIDI stream + the data length + + + + Creates a new tempo event with specified settings + + Microseconds per quarter note + Absolute time + + + + Creates a deep clone of this MIDI event. + + + + + Describes this tempo event + + String describing the tempo event + + + + Microseconds per quarter note + + + + + Tempo + + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Represents a MIDI text event + + + + + Reads a new text event from a MIDI stream + + The MIDI stream + The data length + + + + Creates a new TextEvent + + The text in this type + MetaEvent type (must be one that is + associated with text data) + Absolute time of this event + + + + Creates a deep clone of this MIDI event. + + + + + The contents of this text event + + + + + Describes this MIDI text event + + A string describing this event + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Represents a MIDI time signature event + + + + + Reads a new time signature event from a MIDI stream + + The MIDI stream + The data length + + + + Creates a new TimeSignatureEvent + + Time at which to create this event + Numerator + Denominator + Ticks in Metronome Click + No of 32nd Notes in Quarter Click + + + + Creates a deep clone of this MIDI event. + + + + + Numerator (number of beats in a bar) + + + + + Denominator (Beat unit), + 1 means 2, 2 means 4 (crochet), 3 means 8 (quaver), 4 means 16 and 5 means 32 + + + + + Ticks in a metronome click + + + + + Number of 32nd notes in a quarter note + + + + + The time signature + + + + + Describes this time signature event + + A string describing this event + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Represents a MIDI track sequence number event event + + + + + Creates a new track sequence number event + + + + + Reads a new track sequence number event from a MIDI stream + + The MIDI stream + the data length + + + + Creates a deep clone of this MIDI event. + + + + + Describes this event + + String describing the event + + + + Calls base class export first, then exports the data + specific to this event + MidiEvent.Export + + + + + Chunk Identifier helpers + + + + + Chunk identifier to Int32 (replaces mmioStringToFOURCC) + + four character chunk identifier + Chunk identifier as int 32 + + + + Allows us to add descriptions to interop members + + + + + The description + + + + + Field description + + + + + String representation + + + + + + these will become extension methods once we move to .NET 3.5 + + + + + Checks if the buffer passed in is entirely full of nulls + + + + + Converts to a string containing the buffer described in hex + + + + + Decodes the buffer using the specified encoding, stopping at the first null + + + + + Concatenates the given arrays into a single array. + + The arrays to concatenate + The concatenated resulting array. + + + + Helper to get descriptions + + + + + Describes the Guid by looking for a FieldDescription attribute on the specified class + + + + + Support for Marshal Methods in both UWP and .NET 3.5 + + + + + SizeOf a structure + + + + + Offset of a field in a structure + + + + + Pointer to Structure + + + + + WavePosition extension methods + + + + + Get Position as timespan + + + + + Methods for converting between IEEE 80-bit extended double precision + and standard C# double precision. + + + + + Converts a C# double precision number to an 80-bit + IEEE extended double precision number (occupying 10 bytes). + + The double precision number to convert to IEEE extended. + An array of 10 bytes containing the IEEE extended number. + + + + Converts an IEEE 80-bit extended precision number to a + C# double precision number. + + The 80-bit IEEE extended number (as an array of 10 bytes). + A C# double precision number that is a close representation of the IEEE extended number. + + + + General purpose native methods for internal NAudio use + + + + + Helper methods for working with audio buffers + + + + + Ensures the buffer is big enough + + + + + + + + Ensures the buffer is big enough + + + + + + + + An encoding for use with file types that have one byte per character + + + + + The one and only instance of this class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + A very basic circular buffer implementation + + + + + Create a new circular buffer + + Max buffer size in bytes + + + + Write data to the buffer + + Data to write + Offset into data + Number of bytes to write + number of bytes written + + + + Read from the buffer + + Buffer to read into + Offset into read buffer + Bytes to read + Number of bytes actually read + + + + Maximum length of this circular buffer + + + + + Number of bytes currently stored in the circular buffer + + + + + Resets the buffer + + + + + Advances the buffer, discarding bytes + + Bytes to advance + + + + A util class for conversions + + + + + linear to dB conversion + + linear value + decibel value + + + + dB to linear conversion + + decibel value + linear value + + + + HResult + + + + + S_OK + + + + + S_FALSE + + + + + E_INVALIDARG (from winerror.h) + + + + + MAKE_HRESULT macro + + + + + Helper to deal with the fact that in Win Store apps, + the HResult property name has changed + + COM Exception + The HResult + + + + Pass-through stream that ignores Dispose + Useful for dealing with MemoryStreams that you want to re-use + + + + + The source stream all other methods fall through to + + + + + If true the Dispose will be ignored, if false, will pass through to the SourceStream + Set to true by default + + + + + Creates a new IgnoreDisposeStream + + The source stream + + + + Can Read + + + + + Can Seek + + + + + Can write to the underlying stream + + + + + Flushes the underlying stream + + + + + Gets the length of the underlying stream + + + + + Gets or sets the position of the underlying stream + + + + + Reads from the underlying stream + + + + + Seeks on the underlying stream + + + + + Sets the length of the underlying stream + + + + + Writes to the underlying stream + + + + + Dispose - by default (IgnoreDispose = true) will do nothing, + leaving the underlying stream undisposed + + + + + In-place and stable implementation of MergeSort + + + + + MergeSort a list of comparable items + + + + + MergeSort a list + + + + + A thread-safe Progress Log Control + + + + + Creates a new progress log control + + + + + The contents of the log as text + + + + + Log a message + + + + + Clear the log + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + ASIO 64 bit value + Unfortunately the ASIO API was implemented it before compiler supported consistently 64 bit + integer types. By using the structure the data layout on a little-endian system like the + Intel x86 architecture will result in a "non native" storage of the 64 bit data. The most + significant 32 bit are stored first in memory, the least significant bits are stored in the + higher memory space. However each 32 bit is stored in the native little-endian fashion + + + + + most significant bits (Bits 32..63) + + + + + least significant bits (Bits 0..31) + + + + + ASIO Callbacks + + + + + ASIO Buffer Switch Callback + + + + + ASIO Sample Rate Did Change Callback + + + + + ASIO Message Callback + + + + + ASIO Buffer Switch Time Info Callback + + + + + Buffer switch callback + void (*bufferSwitch) (long doubleBufferIndex, AsioBool directProcess); + + + + + Sample Rate Changed callback + void (*sampleRateDidChange) (AsioSampleRate sRate); + + + + + ASIO Message callback + long (*asioMessage) (long selector, long value, void* message, double* opt); + + + + + ASIO Buffer Switch Time Info Callback + AsioTime* (*bufferSwitchTimeInfo) (AsioTime* params, long doubleBufferIndex, AsioBool directProcess); + + + + + ASIO Channel Info + + + + + on input, channel index + + + + + Is Input + + + + + Is Active + + + + + Channel Info + + + + + ASIO Sample Type + + + + + Name + + + + + ASIODriverCapability holds all the information from the AsioDriver. + Use ASIODriverExt to get the Capabilities + + + + + Drive Name + + + + + Number of Input Channels + + + + + Number of Output Channels + + + + + Input Latency + + + + + Output Latency + + + + + Buffer Minimum Size + + + + + Buffer Maximum Size + + + + + Buffer Preferred Size + + + + + Buffer Granularity + + + + + Sample Rate + + + + + Input Channel Info + + + + + Output Channel Info + + + + + ASIO Error Codes + + + + + This value will be returned whenever the call succeeded + + + + + unique success return value for ASIOFuture calls + + + + + hardware input or output is not present or available + + + + + hardware is malfunctioning (can be returned by any ASIO function) + + + + + input parameter invalid + + + + + hardware is in a bad mode or used in a bad mode + + + + + hardware is not running when sample position is inquired + + + + + sample clock or rate cannot be determined or is not present + + + + + not enough memory for completing the request + + + + + ASIO Message Selector + + + + + selector in <value>, returns 1L if supported, + + + + + returns engine (host) asio implementation version, + + + + + request driver reset. if accepted, this + + + + + not yet supported, will currently always return 0L. + + + + + the driver went out of sync, such that + + + + + the drivers latencies have changed. The engine + + + + + if host returns true here, it will expect the + + + + + supports timecode + + + + + unused - value: number of commands, message points to mmc commands + + + + + kAsioSupportsXXX return 1 if host supports this + + + + + unused and undefined + + + + + unused and undefined + + + + + unused and undefined + + + + + unused and undefined + + + + + driver detected an overload + + + + + ASIO Sample Type + + + + + Int 16 MSB + + + + + Int 24 MSB (used for 20 bits as well) + + + + + Int 32 MSB + + + + + IEEE 754 32 bit float + + + + + IEEE 754 64 bit double float + + + + + 32 bit data with 16 bit alignment + + + + + 32 bit data with 18 bit alignment + + + + + 32 bit data with 20 bit alignment + + + + + 32 bit data with 24 bit alignment + + + + + Int 16 LSB + + + + + Int 24 LSB + used for 20 bits as well + + + + + Int 32 LSB + + + + + IEEE 754 32 bit float, as found on Intel x86 architecture + + + + + IEEE 754 64 bit double float, as found on Intel x86 architecture + + + + + 32 bit data with 16 bit alignment + + + + + 32 bit data with 18 bit alignment + + + + + 32 bit data with 20 bit alignment + + + + + 32 bit data with 24 bit alignment + + + + + DSD 1 bit data, 8 samples per byte. First sample in Least significant bit. + + + + + DSD 1 bit data, 8 samples per byte. First sample in Most significant bit. + + + + + DSD 8 bit data, 1 sample per byte. No Endianness required. + + + + + Main AsioDriver Class. To use this class, you need to query first the GetAsioDriverNames() and + then use the GetAsioDriverByName to instantiate the correct AsioDriver. + This is the first AsioDriver binding fully implemented in C#! + + Contributor: Alexandre Mutel - email: alexandre_mutel at yahoo.fr + + + + + Gets the ASIO driver names installed. + + a list of driver names. Use this name to GetAsioDriverByName + + + + Instantiate a AsioDriver given its name. + + The name of the driver + an AsioDriver instance + + + + Instantiate the ASIO driver by GUID. + + The GUID. + an AsioDriver instance + + + + Inits the AsioDriver.. + + The sys handle. + + + + + Gets the name of the driver. + + + + + + Gets the driver version. + + + + + + Gets the error message. + + + + + + Starts this instance. + + + + + Stops this instance. + + + + + Gets the number of channels. + + The num input channels. + The num output channels. + + + + Gets the latencies (n.b. does not throw an exception) + + The input latency. + The output latency. + + + + Gets the size of the buffer. + + Size of the min. + Size of the max. + Size of the preferred. + The granularity. + + + + Determines whether this instance can use the specified sample rate. + + The sample rate. + + true if this instance [can sample rate] the specified sample rate; otherwise, false. + + + + + Gets the sample rate. + + + + + + Sets the sample rate. + + The sample rate. + + + + Gets the clock sources. + + The clocks. + The num sources. + + + + Sets the clock source. + + The reference. + + + + Gets the sample position. + + The sample pos. + The time stamp. + + + + Gets the channel info. + + The channel number. + if set to true [true for input info]. + Channel Info + + + + Creates the buffers. + + The buffer infos. + The num channels. + Size of the buffer. + The callbacks. + + + + Disposes the buffers. + + + + + Controls the panel. + + + + + Futures the specified selector. + + The selector. + The opt. + + + + Notifies OutputReady to the AsioDriver. + + + + + + Releases this instance. + + + + + Handles the exception. Throws an exception based on the error. + + The error to check. + Method name + + + + Inits the vTable method from GUID. This is a tricky part of this class. + + The ASIO GUID. + + + + Internal VTable structure to store all the delegates to the C++ COM method. + + + + + Callback used by the AsioDriverExt to get wave data + + + + + AsioDriverExt is a simplified version of the AsioDriver. It provides an easier + way to access the capabilities of the Driver and implement the callbacks necessary + for feeding the driver. + Implementation inspired from Rob Philpot's with a managed C++ ASIO wrapper BlueWave.Interop.Asio + http://www.codeproject.com/KB/mcpp/Asio.Net.aspx + + Contributor: Alexandre Mutel - email: alexandre_mutel at yahoo.fr + + + + + Initializes a new instance of the class based on an already + instantiated AsioDriver instance. + + A AsioDriver already instantiated. + + + + Allows adjustment of which is the first output channel we write to + + Output Channel offset + Input Channel offset + + + + Gets the driver used. + + The ASIOdriver. + + + + Starts playing the buffers. + + + + + Stops playing the buffers. + + + + + Shows the control panel. + + + + + Releases this instance. + + + + + Determines whether the specified sample rate is supported. + + The sample rate. + + true if [is sample rate supported]; otherwise, false. + + + + + Sets the sample rate. + + The sample rate. + + + + Gets or sets the fill buffer callback. + + The fill buffer callback. + + + + Gets the capabilities of the AsioDriver. + + The capabilities. + + + + Creates the buffers for playing. + + The number of outputs channels. + The number of input channel. + if set to true [use max buffer size] else use Prefered size + + + + Builds the capabilities internally. + + + + + Callback called by the AsioDriver on fill buffer demand. Redirect call to external callback. + + Index of the double buffer. + if set to true [direct process]. + + + + Callback called by the AsioDriver on event "Samples rate changed". + + The sample rate. + + + + Asio message call back. + + The selector. + The value. + The message. + The opt. + + + + + Buffers switch time info call back. + + The asio time param. + Index of the double buffer. + if set to true [direct process]. + + + + + This class stores convertors for different interleaved WaveFormat to ASIOSampleType separate channel + format. + + + + + Selects the sample convertor based on the input WaveFormat and the output ASIOSampleTtype. + + The wave format. + The type. + + + + + Optimized convertor for 2 channels SHORT + + + + + Generic convertor for SHORT + + + + + Optimized convertor for 2 channels FLOAT + + + + + Generic convertor SHORT + + + + + Optimized convertor for 2 channels SHORT + + + + + Generic convertor for SHORT + + + + + Optimized convertor for 2 channels FLOAT + + + + + Generic convertor SHORT + + + + + Generic converter 24 LSB + + + + + Generic convertor for float + + + + + ASIO common Exception. + + + + + Gets the name of the error. + + The error. + the name of the error + + + + Flags for use with acmDriverAdd + + + + + ACM_DRIVERADDF_LOCAL + + + + + ACM_DRIVERADDF_GLOBAL + + + + + ACM_DRIVERADDF_FUNCTION + + + + + ACM_DRIVERADDF_NOTIFYHWND + + + + + Represents an installed ACM Driver + + + + + Helper function to determine whether a particular codec is installed + + The short name of the function + Whether the codec is installed + + + + Attempts to add a new ACM driver from a file + + Full path of the .acm or dll file containing the driver + Handle to the driver + + + + Removes a driver previously added using AddLocalDriver + + Local driver to remove + + + + Show Format Choose Dialog + + Owner window handle, can be null + Window title + Enumeration flags. None to get everything + Enumeration format. Only needed with certain enumeration flags + The selected format + Textual description of the selected format + Textual description of the selected format tag + True if a format was selected + + + + Gets the maximum size needed to store a WaveFormat for ACM interop functions + + + + + Finds a Driver by its short name + + Short Name + The driver, or null if not found + + + + Gets a list of the ACM Drivers installed + + + + + The callback for acmDriverEnum + + + + + Creates a new ACM Driver object + + Driver handle + + + + The short name of this driver + + + + + The full name of this driver + + + + + The driver ID + + + + + ToString + + + + + The list of FormatTags for this ACM Driver + + + + + Gets all the supported formats for a given format tag + + Format tag + Supported formats + + + + Opens this driver + + + + + Closes this driver + + + + + Dispose + + + + + Interop structure for ACM driver details (ACMDRIVERDETAILS) + http://msdn.microsoft.com/en-us/library/dd742889%28VS.85%29.aspx + + + + + DWORD cbStruct + + + + + FOURCC fccType + + + + + FOURCC fccComp + + + + + WORD wMid; + + + + + WORD wPid + + + + + DWORD vdwACM + + + + + DWORD vdwDriver + + + + + DWORD fdwSupport; + + + + + DWORD cFormatTags + + + + + DWORD cFilterTags + + + + + HICON hicon + + + + + TCHAR szShortName[ACMDRIVERDETAILS_SHORTNAME_CHARS]; + + + + + TCHAR szLongName[ACMDRIVERDETAILS_LONGNAME_CHARS]; + + + + + TCHAR szCopyright[ACMDRIVERDETAILS_COPYRIGHT_CHARS]; + + + + + TCHAR szLicensing[ACMDRIVERDETAILS_LICENSING_CHARS]; + + + + + TCHAR szFeatures[ACMDRIVERDETAILS_FEATURES_CHARS]; + + + + + ACMDRIVERDETAILS_SHORTNAME_CHARS + + + + + ACMDRIVERDETAILS_LONGNAME_CHARS + + + + + ACMDRIVERDETAILS_COPYRIGHT_CHARS + + + + + ACMDRIVERDETAILS_LICENSING_CHARS + + + + + ACMDRIVERDETAILS_FEATURES_CHARS + + + + + Flags indicating what support a particular ACM driver has + + + + ACMDRIVERDETAILS_SUPPORTF_CODEC - Codec + + + ACMDRIVERDETAILS_SUPPORTF_CONVERTER - Converter + + + ACMDRIVERDETAILS_SUPPORTF_FILTER - Filter + + + ACMDRIVERDETAILS_SUPPORTF_HARDWARE - Hardware + + + ACMDRIVERDETAILS_SUPPORTF_ASYNC - Async + + + ACMDRIVERDETAILS_SUPPORTF_LOCAL - Local + + + ACMDRIVERDETAILS_SUPPORTF_DISABLED - Disabled + + + + ACM_DRIVERENUMF_NOLOCAL, Only global drivers should be included in the enumeration + + + + + ACM_DRIVERENUMF_DISABLED, Disabled ACM drivers should be included in the enumeration + + + + + ACM Format + + + + + Format Index + + + + + Format Tag + + + + + Support Flags + + + + + WaveFormat + + + + + WaveFormat Size + + + + + Format Description + + + + + ACMFORMATCHOOSE + http://msdn.microsoft.com/en-us/library/dd742911%28VS.85%29.aspx + + + + + DWORD cbStruct; + + + + + DWORD fdwStyle; + + + + + HWND hwndOwner; + + + + + LPWAVEFORMATEX pwfx; + + + + + DWORD cbwfx; + + + + + LPCTSTR pszTitle; + + + + + TCHAR szFormatTag[ACMFORMATTAGDETAILS_FORMATTAG_CHARS]; + + + + + TCHAR szFormat[ACMFORMATDETAILS_FORMAT_CHARS]; + + + + + LPTSTR pszName; + n.b. can be written into + + + + + DWORD cchName + Should be at least 128 unless name is zero + + + + + DWORD fdwEnum; + + + + + LPWAVEFORMATEX pwfxEnum; + + + + + HINSTANCE hInstance; + + + + + LPCTSTR pszTemplateName; + + + + + LPARAM lCustData; + + + + + ACMFORMATCHOOSEHOOKPROC pfnHook; + + + + + None + + + + + ACMFORMATCHOOSE_STYLEF_SHOWHELP + + + + + ACMFORMATCHOOSE_STYLEF_ENABLEHOOK + + + + + ACMFORMATCHOOSE_STYLEF_ENABLETEMPLATE + + + + + ACMFORMATCHOOSE_STYLEF_ENABLETEMPLATEHANDLE + + + + + ACMFORMATCHOOSE_STYLEF_INITTOWFXSTRUCT + + + + + ACMFORMATCHOOSE_STYLEF_CONTEXTHELP + + + + + ACMFORMATDETAILS + http://msdn.microsoft.com/en-us/library/dd742913%28VS.85%29.aspx + + + + + DWORD cbStruct; + + + + + DWORD dwFormatIndex; + + + + + DWORD dwFormatTag; + + + + + DWORD fdwSupport; + + + + + LPWAVEFORMATEX pwfx; + + + + + DWORD cbwfx; + + + + + TCHAR szFormat[ACMFORMATDETAILS_FORMAT_CHARS]; + + + + + ACMFORMATDETAILS_FORMAT_CHARS + + + + + Format Enumeration Flags + + + + + None + + + + + ACM_FORMATENUMF_CONVERT + The WAVEFORMATEX structure pointed to by the pwfx member of the ACMFORMATDETAILS structure is valid. The enumerator will only enumerate destination formats that can be converted from the given pwfx format. + + + + + ACM_FORMATENUMF_HARDWARE + The enumerator should only enumerate formats that are supported as native input or output formats on one or more of the installed waveform-audio devices. This flag provides a way for an application to choose only formats native to an installed waveform-audio device. This flag must be used with one or both of the ACM_FORMATENUMF_INPUT and ACM_FORMATENUMF_OUTPUT flags. Specifying both ACM_FORMATENUMF_INPUT and ACM_FORMATENUMF_OUTPUT will enumerate only formats that can be opened for input or output. This is true regardless of whether this flag is specified. + + + + + ACM_FORMATENUMF_INPUT + Enumerator should enumerate only formats that are supported for input (recording). + + + + + ACM_FORMATENUMF_NCHANNELS + The nChannels member of the WAVEFORMATEX structure pointed to by the pwfx member of the ACMFORMATDETAILS structure is valid. The enumerator will enumerate only a format that conforms to this attribute. + + + + + ACM_FORMATENUMF_NSAMPLESPERSEC + The nSamplesPerSec member of the WAVEFORMATEX structure pointed to by the pwfx member of the ACMFORMATDETAILS structure is valid. The enumerator will enumerate only a format that conforms to this attribute. + + + + + ACM_FORMATENUMF_OUTPUT + Enumerator should enumerate only formats that are supported for output (playback). + + + + + ACM_FORMATENUMF_SUGGEST + The WAVEFORMATEX structure pointed to by the pwfx member of the ACMFORMATDETAILS structure is valid. The enumerator will enumerate all suggested destination formats for the given pwfx format. This mechanism can be used instead of the acmFormatSuggest function to allow an application to choose the best suggested format for conversion. The dwFormatIndex member will always be set to zero on return. + + + + + ACM_FORMATENUMF_WBITSPERSAMPLE + The wBitsPerSample member of the WAVEFORMATEX structure pointed to by the pwfx member of the ACMFORMATDETAILS structure is valid. The enumerator will enumerate only a format that conforms to this attribute. + + + + + ACM_FORMATENUMF_WFORMATTAG + The wFormatTag member of the WAVEFORMATEX structure pointed to by the pwfx member of the ACMFORMATDETAILS structure is valid. The enumerator will enumerate only a format that conforms to this attribute. The dwFormatTag member of the ACMFORMATDETAILS structure must be equal to the wFormatTag member. + + + + + ACM_FORMATSUGGESTF_WFORMATTAG + + + + + ACM_FORMATSUGGESTF_NCHANNELS + + + + + ACM_FORMATSUGGESTF_NSAMPLESPERSEC + + + + + ACM_FORMATSUGGESTF_WBITSPERSAMPLE + + + + + ACM_FORMATSUGGESTF_TYPEMASK + + + + + ACM Format Tag + + + + + Format Tag Index + + + + + Format Tag + + + + + Format Size + + + + + Support Flags + + + + + Standard Formats Count + + + + + Format Description + + + + + DWORD cbStruct; + + + + + DWORD dwFormatTagIndex; + + + + + DWORD dwFormatTag; + + + + + DWORD cbFormatSize; + + + + + DWORD fdwSupport; + + + + + DWORD cStandardFormats; + + + + + TCHAR szFormatTag[ACMFORMATTAGDETAILS_FORMATTAG_CHARS]; + + + + + ACMFORMATTAGDETAILS_FORMATTAG_CHARS + + + + + Interop definitions for Windows ACM (Audio Compression Manager) API + + + + + http://msdn.microsoft.com/en-us/library/dd742910%28VS.85%29.aspx + UINT ACMFORMATCHOOSEHOOKPROC acmFormatChooseHookProc( + HWND hwnd, + UINT uMsg, + WPARAM wParam, + LPARAM lParam + + + + + http://msdn.microsoft.com/en-us/library/dd742916%28VS.85%29.aspx + MMRESULT acmFormatSuggest( + HACMDRIVER had, + LPWAVEFORMATEX pwfxSrc, + LPWAVEFORMATEX pwfxDst, + DWORD cbwfxDst, + DWORD fdwSuggest); + + + + + http://msdn.microsoft.com/en-us/library/dd742928%28VS.85%29.aspx + MMRESULT acmStreamOpen( + LPHACMSTREAM phas, + HACMDRIVER had, + LPWAVEFORMATEX pwfxSrc, + LPWAVEFORMATEX pwfxDst, + LPWAVEFILTER pwfltr, + DWORD_PTR dwCallback, + DWORD_PTR dwInstance, + DWORD fdwOpen + + + + + A version with pointers for troubleshooting + + + + + AcmStream encapsulates an Audio Compression Manager Stream + used to convert audio from one format to another + + + + + Creates a new ACM stream to convert one format to another. Note that + not all conversions can be done in one step + + The source audio format + The destination audio format + + + + Creates a new ACM stream to convert one format to another, using a + specified driver identified and wave filter + + the driver identifier + the source format + the wave filter + + + + Returns the number of output bytes for a given number of input bytes + + Number of input bytes + Number of output bytes + + + + Returns the number of source bytes for a given number of destination bytes + + Number of destination bytes + Number of source bytes + + + + Suggests an appropriate PCM format that the compressed format can be converted + to in one step + + The compressed format + The PCM format + + + + Returns the Source Buffer. Fill this with data prior to calling convert + + + + + Returns the Destination buffer. This will contain the converted data + after a successful call to Convert + + + + + Report that we have repositioned in the source stream + + + + + Converts the contents of the SourceBuffer into the DestinationBuffer + + The number of bytes in the SourceBuffer + that need to be converted + The number of source bytes actually converted + The number of converted bytes in the DestinationBuffer + + + + Converts the contents of the SourceBuffer into the DestinationBuffer + + The number of bytes in the SourceBuffer + that need to be converted + The number of converted bytes in the DestinationBuffer + + + + Frees resources associated with this ACM Stream + + + + + Frees resources associated with this ACM Stream + + + + + Frees resources associated with this ACM Stream + + + + + ACMSTREAMHEADER_STATUSF_DONE + + + + + ACMSTREAMHEADER_STATUSF_PREPARED + + + + + ACMSTREAMHEADER_STATUSF_INQUEUE + + + + + Interop structure for ACM stream headers. + ACMSTREAMHEADER + http://msdn.microsoft.com/en-us/library/dd742926%28VS.85%29.aspx + + + + + ACM_STREAMOPENF_QUERY, ACM will be queried to determine whether it supports the given conversion. A conversion stream will not be opened, and no handle will be returned in the phas parameter. + + + + + ACM_STREAMOPENF_ASYNC, Stream conversion should be performed asynchronously. If this flag is specified, the application can use a callback function to be notified when the conversion stream is opened and closed and after each buffer is converted. In addition to using a callback function, an application can examine the fdwStatus member of the ACMSTREAMHEADER structure for the ACMSTREAMHEADER_STATUSF_DONE flag. + + + + + ACM_STREAMOPENF_NONREALTIME, ACM will not consider time constraints when converting the data. By default, the driver will attempt to convert the data in real time. For some formats, specifying this flag might improve the audio quality or other characteristics. + + + + + CALLBACK_TYPEMASK, callback type mask + + + + + CALLBACK_NULL, no callback + + + + + CALLBACK_WINDOW, dwCallback is a HWND + + + + + CALLBACK_TASK, dwCallback is a HTASK + + + + + CALLBACK_FUNCTION, dwCallback is a FARPROC + + + + + CALLBACK_THREAD, thread ID replaces 16 bit task + + + + + CALLBACK_EVENT, dwCallback is an EVENT Handle + + + + + ACM_STREAMSIZEF_SOURCE + + + + + ACM_STREAMSIZEF_DESTINATION + + + + + Summary description for WaveFilter. + + + + + cbStruct + + + + + dwFilterTag + + + + + fdwFilter + + + + + reserved + + + + + ADSR sample provider allowing you to specify attack, decay, sustain and release values + + + + + Creates a new AdsrSampleProvider with default values + + + + + Attack time in seconds + + + + + Release time in seconds + + + + + Reads audio from this sample provider + + + + + Enters the Release phase + + + + + The output WaveFormat + + + + + Sample Provider to concatenate multiple sample providers together + + + + + Creates a new ConcatenatingSampleProvider + + The source providers to play one after the other. Must all share the same sample rate and channel count + + + + The WaveFormat of this Sample Provider + + + + + Read Samples from this sample provider + + + + + Sample Provider to allow fading in and out + + + + + Creates a new FadeInOutSampleProvider + + The source stream with the audio to be faded in or out + If true, we start faded out + + + + Requests that a fade-in begins (will start on the next call to Read) + + Duration of fade in milliseconds + + + + Requests that a fade-out begins (will start on the next call to Read) + + Duration of fade in milliseconds + + + + Reads samples from this sample provider + + Buffer to read into + Offset within buffer to write to + Number of samples desired + Number of samples read + + + + WaveFormat of this SampleProvider + + + + + Allows any number of inputs to be patched to outputs + Uses could include swapping left and right channels, turning mono into stereo, + feeding different input sources to different soundcard outputs etc + + + + + Creates a multiplexing sample provider, allowing re-patching of input channels to different + output channels + + Input sample providers. Must all be of the same sample rate, but can have any number of channels + Desired number of output channels. + + + + persistent temporary buffer to prevent creating work for garbage collector + + + + + Reads samples from this sample provider + + Buffer to be filled with sample data + Offset into buffer to start writing to, usually 0 + Number of samples required + Number of samples read + + + + The output WaveFormat for this SampleProvider + + + + + Connects a specified input channel to an output channel + + Input Channel index (zero based). Must be less than InputChannelCount + Output Channel index (zero based). Must be less than OutputChannelCount + + + + The number of input channels. Note that this is not the same as the number of input wave providers. If you pass in + one stereo and one mono input provider, the number of input channels is three. + + + + + The number of output channels, as specified in the constructor. + + + + + Allows you to: + 1. insert a pre-delay of silence before the source begins + 2. skip over a certain amount of the beginning of the source + 3. only play a set amount from the source + 4. insert silence at the end after the source is complete + + + + + Number of samples of silence to insert before playing source + + + + + Amount of silence to insert before playing + + + + + Number of samples in source to discard + + + + + Amount of audio to skip over from the source before beginning playback + + + + + Number of samples to read from source (if 0, then read it all) + + + + + Amount of audio to take from the source (TimeSpan.Zero means play to end) + + + + + Number of samples of silence to insert after playing source + + + + + Amount of silence to insert after playing source + + + + + Creates a new instance of offsetSampleProvider + + The Source Sample Provider to read from + + + + The WaveFormat of this SampleProvider + + + + + Reads from this sample provider + + Sample buffer + Offset within sample buffer to read to + Number of samples required + Number of samples read + + + + Converts an IWaveProvider containing 32 bit PCM to an + ISampleProvider + + + + + Initialises a new instance of Pcm32BitToSampleProvider + + Source Wave Provider + + + + Reads floating point samples from this sample provider + + sample buffer + offset within sample buffer to write to + number of samples required + number of samples provided + + + + Utility class for converting to SampleProvider + + + + + Helper function to go from IWaveProvider to a SampleProvider + Must already be PCM or IEEE float + + The WaveProvider to convert + A sample provider + + + + Converts a sample provider to 16 bit PCM, optionally clipping and adjusting volume along the way + + + + + Converts from an ISampleProvider (IEEE float) to a 16 bit PCM IWaveProvider. + Number of channels and sample rate remain unchanged. + + The input source provider + + + + Reads bytes from this wave stream + + The destination buffer + Offset into the destination buffer + Number of bytes read + Number of bytes read. + + + + + + + + + Volume of this channel. 1.0 = full scale + + + + + Converts a sample provider to 24 bit PCM, optionally clipping and adjusting volume along the way + + + + + Converts from an ISampleProvider (IEEE float) to a 16 bit PCM IWaveProvider. + Number of channels and sample rate remain unchanged. + + The input source provider + + + + Reads bytes from this wave stream, clipping if necessary + + The destination buffer + Offset into the destination buffer + Number of bytes read + Number of bytes read. + + + + The Format of this IWaveProvider + + + + + + Volume of this channel. 1.0 = full scale, 0.0 to mute + + + + + Signal Generator + Sin, Square, Triangle, SawTooth, White Noise, Pink Noise, Sweep. + + + Posibility to change ISampleProvider + Example : + --------- + WaveOut _waveOutGene = new WaveOut(); + WaveGenerator wg = new SignalGenerator(); + wg.Type = ... + wg.Frequency = ... + wg ... + _waveOutGene.Init(wg); + _waveOutGene.Play(); + + + + + Initializes a new instance for the Generator (Default :: 44.1Khz, 2 channels, Sinus, Frequency = 440, Gain = 1) + + + + + Initializes a new instance for the Generator (UserDef SampleRate & Channels) + + Desired sample rate + Number of channels + + + + The waveformat of this WaveProvider (same as the source) + + + + + Frequency for the Generator. (20.0 - 20000.0 Hz) + Sin, Square, Triangle, SawTooth, Sweep (Start Frequency). + + + + + Return Log of Frequency Start (Read only) + + + + + End Frequency for the Sweep Generator. (Start Frequency in Frequency) + + + + + Return Log of Frequency End (Read only) + + + + + Gain for the Generator. (0.0 to 1.0) + + + + + Channel PhaseReverse + + + + + Type of Generator. + + + + + Length Seconds for the Sweep Generator. + + + + + Reads from this provider. + + + + + Private :: Random for WhiteNoise & Pink Noise (Value form -1 to 1) + + Random value from -1 to +1 + + + + Signal Generator type + + + + + Pink noise + + + + + White noise + + + + + Sweep + + + + + Sine wave + + + + + Square wave + + + + + Triangle Wave + + + + + Sawtooth wave + + + + + Author: Freefall + Date: 05.08.16 + Based on: the port of Stephan M. Bernsee´s pitch shifting class + Port site: https://sites.google.com/site/mikescoderama/pitch-shifting + Test application and github site: https://github.com/Freefall63/NAudio-Pitchshifter + + NOTE: I strongly advice to add a Limiter for post-processing. + For my needs the FastAttackCompressor1175 provides acceptable results: + https://github.com/Jiyuu/SkypeFX/blob/master/JSNet/FastAttackCompressor1175.cs + + UPDATE: Added a simple Limiter based on the pydirac implementation. + https://github.com/echonest/remix/blob/master/external/pydirac225/source/Dirac_LE.cpp + + + + + + Creates a new SMB Pitch Shifting Sample Provider with default settings + + Source provider + + + + Creates a new SMB Pitch Shifting Sample Provider with custom settings + + Source provider + FFT Size (any power of two <= 4096: 4096, 2048, 1024, 512, ...) + Oversampling (number of overlapping windows) + Initial pitch (0.5f = octave down, 1.0f = normal, 2.0f = octave up) + + + + Read from this sample provider + + + + + WaveFormat + + + + + Pitch Factor (0.5f = octave down, 1.0f = normal, 2.0f = octave up) + + + + + Takes a stereo input and turns it to mono + + + + + Creates a new mono ISampleProvider based on a stereo input + + Stereo 16 bit PCM input + + + + 1.0 to mix the mono source entirely to the left channel + + + + + 1.0 to mix the mono source entirely to the right channel + + + + + Output Wave Format + + + + + Reads bytes from this SampleProvider + + + + + Helper class turning an already 64 bit floating point IWaveProvider + into an ISampleProvider - hopefully not needed for most applications + + + + + Initializes a new instance of the WaveToSampleProvider class + + Source wave provider, must be IEEE float + + + + Reads from this provider + + + + + Fully managed resampling sample provider, based on the WDL Resampler + + + + + Constructs a new resampler + + Source to resample + Desired output sample rate + + + + Reads from this sample provider + + + + + Output WaveFormat + + + + + Sample provider interface to make WaveChannel32 extensible + Still a bit ugly, hence internal at the moment - and might even make these into + bit depth converting WaveProviders + + + + + A sample provider mixer, allowing inputs to be added and removed + + + + + Creates a new MixingSampleProvider, with no inputs, but a specified WaveFormat + + The WaveFormat of this mixer. All inputs must be in this format + + + + Creates a new MixingSampleProvider, based on the given inputs + + Mixer inputs - must all have the same waveformat, and must + all be of the same WaveFormat. There must be at least one input + + + + Returns the mixer inputs (read-only - use AddMixerInput to add an input + + + + + When set to true, the Read method always returns the number + of samples requested, even if there are no inputs, or if the + current inputs reach their end. Setting this to true effectively + makes this a never-ending sample provider, so take care if you plan + to write it out to a file. + + + + + Adds a WaveProvider as a Mixer input. + Must be PCM or IEEE float already + + IWaveProvider mixer input + + + + Adds a new mixer input + + Mixer input + + + + Raised when a mixer input has been removed because it has ended + + + + + Removes a mixer input + + Mixer input to remove + + + + Removes all mixer inputs + + + + + The output WaveFormat of this sample provider + + + + + Reads samples from this sample provider + + Sample buffer + Offset into sample buffer + Number of samples required + Number of samples read + + + + SampleProvider event args + + + + + Constructs a new SampleProviderEventArgs + + + + + The Sample Provider + + + + + Converts a mono sample provider to stereo, with a customisable pan strategy + + + + + Initialises a new instance of the PanningSampleProvider + + Source sample provider, must be mono + + + + Pan value, must be between -1 (left) and 1 (right) + + + + + The pan strategy currently in use + + + + + The WaveFormat of this sample provider + + + + + Reads samples from this sample provider + + Sample buffer + Offset into sample buffer + Number of samples desired + Number of samples read + + + + Pair of floating point values, representing samples or multipliers + + + + + Left value + + + + + Right value + + + + + Required Interface for a Panning Strategy + + + + + Gets the left and right multipliers for a given pan value + + Pan value from -1 to 1 + Left and right multipliers in a stereo sample pair + + + + Simplistic "balance" control - treating the mono input as if it was stereo + In the centre, both channels full volume. Opposite channel decays linearly + as balance is turned to to one side + + + + + Gets the left and right channel multipliers for this pan value + + Pan value, between -1 and 1 + Left and right multipliers + + + + Square Root Pan, thanks to Yuval Naveh + + + + + Gets the left and right channel multipliers for this pan value + + Pan value, between -1 and 1 + Left and right multipliers + + + + Sinus Pan, thanks to Yuval Naveh + + + + + Gets the left and right channel multipliers for this pan value + + Pan value, between -1 and 1 + Left and right multipliers + + + + Linear Pan + + + + + Gets the left and right channel multipliers for this pan value + + Pan value, between -1 and 1 + Left and right multipliers + + + + Simple SampleProvider that passes through audio unchanged and raises + an event every n samples with the maximum sample value from the period + for metering purposes + + + + + Number of Samples per notification + + + + + Raised periodically to inform the user of the max volume + + + + + Initialises a new instance of MeteringSampleProvider that raises 10 stream volume + events per second + + Source sample provider + + + + Initialises a new instance of MeteringSampleProvider + + source sampler provider + Number of samples between notifications + + + + The WaveFormat of this sample provider + + + + + Reads samples from this Sample Provider + + Sample buffer + Offset into sample buffer + Number of samples required + Number of samples read + + + + Event args for aggregated stream volume + + + + + Max sample values array (one for each channel) + + + + + Simple class that raises an event on every sample + + + + + Initializes a new instance of NotifyingSampleProvider + + Source Sample Provider + + + + WaveFormat + + + + + Reads samples from this sample provider + + Sample buffer + Offset into sample buffer + Number of samples desired + Number of samples read + + + + Sample notifier + + + + + Very simple sample provider supporting adjustable gain + + + + + Initializes a new instance of VolumeSampleProvider + + Source Sample Provider + + + + WaveFormat + + + + + Reads samples from this sample provider + + Sample buffer + Offset into sample buffer + Number of samples desired + Number of samples read + + + + Allows adjusting the volume, 1.0f = full volume + + + + + Helper base class for classes converting to ISampleProvider + + + + + Source Wave Provider + + + + + Source buffer (to avoid constantly creating small buffers during playback) + + + + + Initialises a new instance of SampleProviderConverterBase + + Source Wave provider + + + + Wave format of this wave provider + + + + + Reads samples from the source wave provider + + Sample buffer + Offset into sample buffer + Number of samples required + Number of samples read + + + + Ensure the source buffer exists and is big enough + + Bytes required + + + + Helper class for when you need to convert back to an IWaveProvider from + an ISampleProvider. Keeps it as IEEE float + + + + + Initializes a new instance of the WaveProviderFloatToWaveProvider class + + Source wave provider + + + + Reads from this provider + + + + + The waveformat of this WaveProvider (same as the source) + + + + + No nonsense mono to stereo provider, no volume adjustment, + just copies input to left and right. + + + + + Initializes a new instance of MonoToStereoSampleProvider + + Source sample provider + + + + WaveFormat of this provider + + + + + Reads samples from this provider + + Sample buffer + Offset into sample buffer + Number of samples required + Number of samples read + + + + Multiplier for left channel (default is 1.0) + + + + + Multiplier for right channel (default is 1.0) + + + + + Helper class turning an already 32 bit floating point IWaveProvider + into an ISampleProvider - hopefully not needed for most applications + + + + + Initializes a new instance of the WaveToSampleProvider class + + Source wave provider, must be IEEE float + + + + Reads from this provider + + + + + Converts an IWaveProvider containing 16 bit PCM to an + ISampleProvider + + + + + Initialises a new instance of Pcm16BitToSampleProvider + + Source wave provider + + + + Reads samples from this sample provider + + Sample buffer + Offset into sample buffer + Samples required + Number of samples read + + + + Converts an IWaveProvider containing 24 bit PCM to an + ISampleProvider + + + + + Initialises a new instance of Pcm24BitToSampleProvider + + Source Wave Provider + + + + Reads floating point samples from this sample provider + + sample buffer + offset within sample buffer to write to + number of samples required + number of samples provided + + + + Converts an IWaveProvider containing 8 bit PCM to an + ISampleProvider + + + + + Initialises a new instance of Pcm8BitToSampleProvider + + Source wave provider + + + + Reads samples from this sample provider + + Sample buffer + Offset into sample buffer + Number of samples to read + Number of samples read + + + + Utility class that takes an IWaveProvider input at any bit depth + and exposes it as an ISampleProvider. Can turn mono inputs into stereo, + and allows adjusting of volume + (The eventual successor to WaveChannel32) + This class also serves as an example of how you can link together several simple + Sample Providers to form a more useful class. + + + + + Initialises a new instance of SampleChannel + + Source wave provider, must be PCM or IEEE + + + + Initialises a new instance of SampleChannel + + Source wave provider, must be PCM or IEEE + force mono inputs to become stereo + + + + Reads samples from this sample provider + + Sample buffer + Offset into sample buffer + Number of samples desired + Number of samples read + + + + The WaveFormat of this Sample Provider + + + + + Allows adjusting the volume, 1.0f = full volume + + + + + Raised periodically to inform the user of the max volume + (before the volume meter) + + + + + Useful extension methods to make switching between WaveAndSampleProvider easier + + + + + Converts a WaveProvider into a SampleProvider (only works for PCM) + + WaveProvider to convert + + + + + Allows sending a SampleProvider directly to an IWavePlayer without needing to convert + back to an IWaveProvider + + The WavePlayer + + + + + + Turns WaveFormatExtensible into a standard waveformat if possible + + Input wave format + A standard PCM or IEEE waveformat, or the original waveformat + + + + Converts a ISampleProvider to a IWaveProvider but still 32 bit float + + SampleProvider to convert + An IWaveProvider + + + + Converts a ISampleProvider to a IWaveProvider but and convert to 16 bit + + SampleProvider to convert + A 16 bit IWaveProvider + + + + Concatenates one Sample Provider on the end of another + + The sample provider to play first + The sample provider to play next + A single sampleprovider to play one after the other + + + + Concatenates one Sample Provider on the end of another with silence inserted + + The sample provider to play first + Silence duration to insert between the two + The sample provider to play next + A single sample provider + + + + Skips over a specified amount of time (by consuming source stream) + + Source sample provider + Duration to skip over + A sample provider that skips over the specified amount of time + + + + Takes a specified amount of time from the source stream + + Source sample provider + Duration to take + A sample provider that reads up to the specified amount of time + + + + Converts a Stereo Sample Provider to mono, allowing mixing of channel volume + + Stereo Source Provider + Amount of left channel to mix in (0 = mute, 1 = full, 0.5 for mixing half from each channel) + Amount of right channel to mix in (0 = mute, 1 = full, 0.5 for mixing half from each channel) + A mono SampleProvider + + + + Converts a Mono ISampleProvider to stereo + + Mono Source Provider + Amount to mix to left channel (1.0 is full volume) + Amount to mix to right channel (1.0 is full volume) + + + + + Recording using waveIn api with event callbacks. + Use this for recording in non-gui applications + Events are raised as recorded buffers are made available + + + + + Indicates recorded data is available + + + + + Indicates that all recorded data has now been received. + + + + + Prepares a Wave input device for recording + + + + + Returns the number of Wave In devices available in the system + + + + + Retrieves the capabilities of a waveIn device + + Device to test + The WaveIn device capabilities + + + + Milliseconds for the buffer. Recommended value is 100ms + + + + + Number of Buffers to use (usually 2 or 3) + + + + + The device number to use + + + + + Start recording + + + + + Stop recording + + + + + WaveFormat we are recording in + + + + + Dispose pattern + + + + + Microphone Level + + + + + Dispose method + + + + + Channel Mode + + + + + Stereo + + + + + Joint Stereo + + + + + Dual Channel + + + + + Mono + + + + + An ID3v2 Tag + + + + + Reads an ID3v2 tag from a stream + + + + + Creates a new ID3v2 tag from a collection of key-value pairs. + + A collection of key-value pairs containing the tags to include in the ID3v2 tag. + A new ID3v2 tag + + + + Convert the frame size to a byte array. + + The frame body size. + + + + + Creates an ID3v2 frame for the given key-value pair. + + + + + + + + Gets the Id3v2 Header size. The size is encoded so that only 7 bits per byte are actually used. + + + + + + + Creates the Id3v2 tag header and returns is as a byte array. + + The Id3v2 frames that will be included in the file. This is used to calculate the ID3v2 tag size. + + + + + Creates the Id3v2 tag for the given key-value pairs and returns it in the a stream. + + + + + + + Raw data from this tag + + + + + Interface for MP3 frame by frame decoder + + + + + Decompress a single MP3 frame + + Frame to decompress + Output buffer + Offset within output buffer + Bytes written to output buffer + + + + Tell the decoder that we have repositioned + + + + + PCM format that we are converting into + + + + + Represents an MP3 Frame + + + + + Reads an MP3 frame from a stream + + input stream + A valid MP3 frame, or null if none found + + + Reads an MP3Frame from a stream + http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm has some good info + also see http://www.codeproject.com/KB/audio-video/mpegaudioinfo.aspx + + A valid MP3 frame, or null if none found + + + + Constructs an MP3 frame + + + + + checks if the four bytes represent a valid header, + if they are, will parse the values into Mp3Frame + + + + + Sample rate of this frame + + + + + Frame length in bytes + + + + + Bit Rate + + + + + Raw frame data (includes header bytes) + + + + + MPEG Version + + + + + MPEG Layer + + + + + Channel Mode + + + + + The number of samples in this frame + + + + + The channel extension bits + + + + + The bitrate index (directly from the header) + + + + + Whether the Copyright bit is set + + + + + Whether a CRC is present + + + + + Not part of the MP3 frame itself - indicates where in the stream we found this header + + + + + MP3 Frame Decompressor using ACM + + + + + Creates a new ACM frame decompressor + + The MP3 source format + + + + Output format (PCM) + + + + + Decompresses a frame + + The MP3 frame + destination buffer + Offset within destination buffer + Bytes written into destination buffer + + + + Resets the MP3 Frame Decompressor after a reposition operation + + + + + Disposes of this MP3 frame decompressor + + + + + Finalizer ensuring that resources get released properly + + + + + MPEG Layer flags + + + + + Reserved + + + + + Layer 3 + + + + + Layer 2 + + + + + Layer 1 + + + + + MPEG Version Flags + + + + + Version 2.5 + + + + + Reserved + + + + + Version 2 + + + + + Version 1 + + + + + Represents a Xing VBR header + + + + + Load Xing Header + + Frame + Xing Header + + + + Sees if a frame contains a Xing header + + + + + Number of frames + + + + + Number of bytes + + + + + VBR Scale property + + + + + The MP3 frame + + + + ACM_METRIC_COUNT_DRIVERS + + + ACM_METRIC_COUNT_CODECS + + + ACM_METRIC_COUNT_CONVERTERS + + + ACM_METRIC_COUNT_FILTERS + + + ACM_METRIC_COUNT_DISABLED + + + ACM_METRIC_COUNT_HARDWARE + + + ACM_METRIC_COUNT_LOCAL_DRIVERS + + + ACM_METRIC_COUNT_LOCAL_CODECS + + + ACM_METRIC_COUNT_LOCAL_CONVERTERS + + + ACM_METRIC_COUNT_LOCAL_FILTERS + + + ACM_METRIC_COUNT_LOCAL_DISABLED + + + ACM_METRIC_HARDWARE_WAVE_INPUT + + + ACM_METRIC_HARDWARE_WAVE_OUTPUT + + + ACM_METRIC_MAX_SIZE_FORMAT + + + ACM_METRIC_MAX_SIZE_FILTER + + + ACM_METRIC_DRIVER_SUPPORT + + + ACM_METRIC_DRIVER_PRIORITY + + + + ACM_STREAMCONVERTF_BLOCKALIGN + + + + + ACM_STREAMCONVERTF_START + + + + + ACM_STREAMCONVERTF_END + + + + + WaveHeader interop structure (WAVEHDR) + http://msdn.microsoft.com/en-us/library/dd743837%28VS.85%29.aspx + + + + pointer to locked data buffer (lpData) + + + length of data buffer (dwBufferLength) + + + used for input only (dwBytesRecorded) + + + for client's use (dwUser) + + + assorted flags (dwFlags) + + + loop control counter (dwLoops) + + + PWaveHdr, reserved for driver (lpNext) + + + reserved for driver + + + + Wave Header Flags enumeration + + + + + WHDR_BEGINLOOP + This buffer is the first buffer in a loop. This flag is used only with output buffers. + + + + + WHDR_DONE + Set by the device driver to indicate that it is finished with the buffer and is returning it to the application. + + + + + WHDR_ENDLOOP + This buffer is the last buffer in a loop. This flag is used only with output buffers. + + + + + WHDR_INQUEUE + Set by Windows to indicate that the buffer is queued for playback. + + + + + WHDR_PREPARED + Set by Windows to indicate that the buffer has been prepared with the waveInPrepareHeader or waveOutPrepareHeader function. + + + + + WASAPI Loopback Capture + based on a contribution from "Pygmy" - http://naudio.codeplex.com/discussions/203605 + + + + + Initialises a new instance of the WASAPI capture class + + + + + Initialises a new instance of the WASAPI capture class + + Capture device to use + + + + Gets the default audio loopback capture device + + The default audio loopback capture device + + + + Capturing wave format + + + + + Specify loopback + + + + + Allows recording using the Windows waveIn APIs + Events are raised as recorded buffers are made available + + + + + Indicates recorded data is available + + + + + Indicates that all recorded data has now been received. + + + + + Prepares a Wave input device for recording + + + + + Creates a WaveIn device using the specified window handle for callbacks + + A valid window handle + + + + Prepares a Wave input device for recording + + + + + Returns the number of Wave In devices available in the system + + + + + Retrieves the capabilities of a waveIn device + + Device to test + The WaveIn device capabilities + + + + Milliseconds for the buffer. Recommended value is 100ms + + + + + Number of Buffers to use (usually 2 or 3) + + + + + The device number to use + + + + + Called when we get a new buffer of recorded data + + + + + Start recording + + + + + Stop recording + + + + + WaveFormat we are recording in + + + + + Dispose pattern + + + + + Microphone Level + + + + + Dispose method + + + + + WaveInCapabilities structure (based on WAVEINCAPS2 from mmsystem.h) + http://msdn.microsoft.com/en-us/library/ms713726(VS.85).aspx + + + + + wMid + + + + + wPid + + + + + vDriverVersion + + + + + Product Name (szPname) + + + + + Supported formats (bit flags) dwFormats + + + + + Supported channels (1 for mono 2 for stereo) (wChannels) + Seems to be set to -1 on a lot of devices + + + + + wReserved1 + + + + + Number of channels supported + + + + + The product name + + + + + The device name Guid (if provided) + + + + + The product name Guid (if provided) + + + + + The manufacturer guid (if provided) + + + + + Checks to see if a given SupportedWaveFormat is supported + + The SupportedWaveFormat + true if supported + + + + The device name from the registry if supported + + + + + Event Args for WaveInStream event + + + + + Creates new WaveInEventArgs + + + + + Buffer containing recorded data. Note that it might not be completely + full. + + + + + The number of recorded bytes in Buffer. + + + + + MME Wave function interop + + + + + CALLBACK_NULL + No callback + + + + + CALLBACK_FUNCTION + dwCallback is a FARPROC + + + + + CALLBACK_EVENT + dwCallback is an EVENT handle + + + + + CALLBACK_WINDOW + dwCallback is a HWND + + + + + CALLBACK_THREAD + callback is a thread ID + + + + + WIM_OPEN + + + + + WIM_CLOSE + + + + + WIM_DATA + + + + + WOM_CLOSE + + + + + WOM_DONE + + + + + WOM_OPEN + + + + + WaveOutCapabilities structure (based on WAVEOUTCAPS2 from mmsystem.h) + http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_waveoutcaps_str.asp + + + + + wMid + + + + + wPid + + + + + vDriverVersion + + + + + Product Name (szPname) + + + + + Supported formats (bit flags) dwFormats + + + + + Supported channels (1 for mono 2 for stereo) (wChannels) + Seems to be set to -1 on a lot of devices + + + + + wReserved1 + + + + + Optional functionality supported by the device + + + + + Number of channels supported + + + + + Whether playback control is supported + + + + + The product name + + + + + Checks to see if a given SupportedWaveFormat is supported + + The SupportedWaveFormat + true if supported + + + + The device name Guid (if provided) + + + + + The product name Guid (if provided) + + + + + The manufacturer guid (if provided) + + + + + Supported wave formats for WaveOutCapabilities + + + + + 11.025 kHz, Mono, 8-bit + + + + + 11.025 kHz, Stereo, 8-bit + + + + + 11.025 kHz, Mono, 16-bit + + + + + 11.025 kHz, Stereo, 16-bit + + + + + 22.05 kHz, Mono, 8-bit + + + + + 22.05 kHz, Stereo, 8-bit + + + + + 22.05 kHz, Mono, 16-bit + + + + + 22.05 kHz, Stereo, 16-bit + + + + + 44.1 kHz, Mono, 8-bit + + + + + 44.1 kHz, Stereo, 8-bit + + + + + 44.1 kHz, Mono, 16-bit + + + + + 44.1 kHz, Stereo, 16-bit + + + + + 44.1 kHz, Mono, 8-bit + + + + + 44.1 kHz, Stereo, 8-bit + + + + + 44.1 kHz, Mono, 16-bit + + + + + 44.1 kHz, Stereo, 16-bit + + + + + 48 kHz, Mono, 8-bit + + + + + 48 kHz, Stereo, 8-bit + + + + + 48 kHz, Mono, 16-bit + + + + + 48 kHz, Stereo, 16-bit + + + + + 96 kHz, Mono, 8-bit + + + + + 96 kHz, Stereo, 8-bit + + + + + 96 kHz, Mono, 16-bit + + + + + 96 kHz, Stereo, 16-bit + + + + + Flags indicating what features this WaveOut device supports + + + + supports pitch control (WAVECAPS_PITCH) + + + supports playback rate control (WAVECAPS_PLAYBACKRATE) + + + supports volume control (WAVECAPS_VOLUME) + + + supports separate left-right volume control (WAVECAPS_LRVOLUME) + + + (WAVECAPS_SYNC) + + + (WAVECAPS_SAMPLEACCURATE) + + + + GSM 610 + + + + + Creates a GSM 610 WaveFormat + For now hardcoded to 13kbps + + + + + Samples per block + + + + + Writes this structure to a BinaryWriter + + + + + IMA/DVI ADPCM Wave Format + Work in progress + + + + + parameterless constructor for Marshalling + + + + + Creates a new IMA / DVI ADPCM Wave Format + + Sample Rate + Number of channels + Bits Per Sample + + + + MP3 WaveFormat, MPEGLAYER3WAVEFORMAT from mmreg.h + + + + + Wave format ID (wID) + + + + + Padding flags (fdwFlags) + + + + + Block Size (nBlockSize) + + + + + Frames per block (nFramesPerBlock) + + + + + Codec Delay (nCodecDelay) + + + + + Creates a new MP3 WaveFormat + + + + + Wave Format Padding Flags + + + + + MPEGLAYER3_FLAG_PADDING_ISO + + + + + MPEGLAYER3_FLAG_PADDING_ON + + + + + MPEGLAYER3_FLAG_PADDING_OFF + + + + + Wave Format ID + + + + MPEGLAYER3_ID_UNKNOWN + + + MPEGLAYER3_ID_MPEG + + + MPEGLAYER3_ID_CONSTANTFRAMESIZE + + + + DSP Group TrueSpeech + + + + + DSP Group TrueSpeech WaveFormat + + + + + Writes this structure to a BinaryWriter + + + + + Represents a Wave file format + + + + format type + + + number of channels + + + sample rate + + + for buffer estimation + + + block size of data + + + number of bits per sample of mono data + + + number of following bytes + + + + Creates a new PCM 44.1Khz stereo 16 bit format + + + + + Creates a new 16 bit wave format with the specified sample + rate and channel count + + Sample Rate + Number of channels + + + + Gets the size of a wave buffer equivalent to the latency in milliseconds. + + The milliseconds. + + + + + Creates a WaveFormat with custom members + + The encoding + Sample Rate + Number of channels + Average Bytes Per Second + Block Align + Bits Per Sample + + + + + Creates an A-law wave format + + Sample Rate + Number of Channels + Wave Format + + + + Creates a Mu-law wave format + + Sample Rate + Number of Channels + Wave Format + + + + Creates a new PCM format with the specified sample rate, bit depth and channels + + + + + Creates a new 32 bit IEEE floating point wave format + + sample rate + number of channels + + + + Helper function to retrieve a WaveFormat structure from a pointer + + WaveFormat structure + + + + + Helper function to marshal WaveFormat to an IntPtr + + WaveFormat + IntPtr to WaveFormat structure (needs to be freed by callee) + + + + Reads in a WaveFormat (with extra data) from a fmt chunk (chunk identifier and + length should already have been read) + + Binary reader + Format chunk length + A WaveFormatExtraData + + + + Reads a new WaveFormat object from a stream + + A binary reader that wraps the stream + + + + Reports this WaveFormat as a string + + String describing the wave format + + + + Compares with another WaveFormat object + + Object to compare to + True if the objects are the same + + + + Provides a Hashcode for this WaveFormat + + A hashcode + + + + Returns the encoding type used + + + + + Writes this WaveFormat object to a stream + + the output stream + + + + Returns the number of channels (1=mono,2=stereo etc) + + + + + Returns the sample rate (samples per second) + + + + + Returns the average number of bytes used per second + + + + + Returns the block alignment + + + + + Returns the number of bits per sample (usually 16 or 32, sometimes 24 or 8) + Can be 0 for some codecs + + + + + Returns the number of extra bytes used by this waveformat. Often 0, + except for compressed formats which store extra data after the WAVEFORMATEX header + + + + + Microsoft ADPCM + See http://icculus.org/SDL_sound/downloads/external_documentation/wavecomp.htm + + + + + Empty constructor needed for marshalling from a pointer + + + + + Samples per block + + + + + Number of coefficients + + + + + Coefficients + + + + + Microsoft ADPCM + + Sample Rate + Channels + + + + Serializes this wave format + + Binary writer + + + + String Description of this WaveFormat + + + + + Custom marshaller for WaveFormat structures + + + + + Gets the instance of this marshaller + + + + + + + Clean up managed data + + + + + Clean up native data + + + + + + Get native data size + + + + + Marshal managed to native + + + + + Marshal Native to Managed + + + + + Summary description for WaveFormatEncoding. + + + + WAVE_FORMAT_UNKNOWN, Microsoft Corporation + + + WAVE_FORMAT_PCM Microsoft Corporation + + + WAVE_FORMAT_ADPCM Microsoft Corporation + + + WAVE_FORMAT_IEEE_FLOAT Microsoft Corporation + + + WAVE_FORMAT_VSELP Compaq Computer Corp. + + + WAVE_FORMAT_IBM_CVSD IBM Corporation + + + WAVE_FORMAT_ALAW Microsoft Corporation + + + WAVE_FORMAT_MULAW Microsoft Corporation + + + WAVE_FORMAT_DTS Microsoft Corporation + + + WAVE_FORMAT_DRM Microsoft Corporation + + + WAVE_FORMAT_WMAVOICE9 + + + WAVE_FORMAT_OKI_ADPCM OKI + + + WAVE_FORMAT_DVI_ADPCM Intel Corporation + + + WAVE_FORMAT_IMA_ADPCM Intel Corporation + + + WAVE_FORMAT_MEDIASPACE_ADPCM Videologic + + + WAVE_FORMAT_SIERRA_ADPCM Sierra Semiconductor Corp + + + WAVE_FORMAT_G723_ADPCM Antex Electronics Corporation + + + WAVE_FORMAT_DIGISTD DSP Solutions, Inc. + + + WAVE_FORMAT_DIGIFIX DSP Solutions, Inc. + + + WAVE_FORMAT_DIALOGIC_OKI_ADPCM Dialogic Corporation + + + WAVE_FORMAT_MEDIAVISION_ADPCM Media Vision, Inc. + + + WAVE_FORMAT_CU_CODEC Hewlett-Packard Company + + + WAVE_FORMAT_YAMAHA_ADPCM Yamaha Corporation of America + + + WAVE_FORMAT_SONARC Speech Compression + + + WAVE_FORMAT_DSPGROUP_TRUESPEECH DSP Group, Inc + + + WAVE_FORMAT_ECHOSC1 Echo Speech Corporation + + + WAVE_FORMAT_AUDIOFILE_AF36, Virtual Music, Inc. + + + WAVE_FORMAT_APTX Audio Processing Technology + + + WAVE_FORMAT_AUDIOFILE_AF10, Virtual Music, Inc. + + + WAVE_FORMAT_PROSODY_1612, Aculab plc + + + WAVE_FORMAT_LRC, Merging Technologies S.A. + + + WAVE_FORMAT_DOLBY_AC2, Dolby Laboratories + + + WAVE_FORMAT_GSM610, Microsoft Corporation + + + WAVE_FORMAT_MSNAUDIO, Microsoft Corporation + + + WAVE_FORMAT_ANTEX_ADPCME, Antex Electronics Corporation + + + WAVE_FORMAT_CONTROL_RES_VQLPC, Control Resources Limited + + + WAVE_FORMAT_DIGIREAL, DSP Solutions, Inc. + + + WAVE_FORMAT_DIGIADPCM, DSP Solutions, Inc. + + + WAVE_FORMAT_CONTROL_RES_CR10, Control Resources Limited + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WAVE_FORMAT_MPEG, Microsoft Corporation + + + + + + + + + WAVE_FORMAT_MPEGLAYER3, ISO/MPEG Layer3 Format Tag + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WAVE_FORMAT_GSM + + + WAVE_FORMAT_G729 + + + WAVE_FORMAT_G723 + + + WAVE_FORMAT_ACELP + + + + WAVE_FORMAT_RAW_AAC1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Windows Media Audio, WAVE_FORMAT_WMAUDIO2, Microsoft Corporation + + + + + Windows Media Audio Professional WAVE_FORMAT_WMAUDIO3, Microsoft Corporation + + + + + Windows Media Audio Lossless, WAVE_FORMAT_WMAUDIO_LOSSLESS + + + + + Windows Media Audio Professional over SPDIF WAVE_FORMAT_WMASPDIF (0x0164) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Advanced Audio Coding (AAC) audio in Audio Data Transport Stream (ADTS) format. + The format block is a WAVEFORMATEX structure with wFormatTag equal to WAVE_FORMAT_MPEG_ADTS_AAC. + + + The WAVEFORMATEX structure specifies the core AAC-LC sample rate and number of channels, + prior to applying spectral band replication (SBR) or parametric stereo (PS) tools, if present. + No additional data is required after the WAVEFORMATEX structure. + + http://msdn.microsoft.com/en-us/library/dd317599%28VS.85%29.aspx + + + + Source wmCodec.h + + + + MPEG-4 audio transport stream with a synchronization layer (LOAS) and a multiplex layer (LATM). + The format block is a WAVEFORMATEX structure with wFormatTag equal to WAVE_FORMAT_MPEG_LOAS. + + + The WAVEFORMATEX structure specifies the core AAC-LC sample rate and number of channels, + prior to applying spectral SBR or PS tools, if present. + No additional data is required after the WAVEFORMATEX structure. + + http://msdn.microsoft.com/en-us/library/dd317599%28VS.85%29.aspx + + + NOKIA_MPEG_ADTS_AAC + Source wmCodec.h + + + NOKIA_MPEG_RAW_AAC + Source wmCodec.h + + + VODAFONE_MPEG_ADTS_AAC + Source wmCodec.h + + + VODAFONE_MPEG_RAW_AAC + Source wmCodec.h + + + + High-Efficiency Advanced Audio Coding (HE-AAC) stream. + The format block is an HEAACWAVEFORMAT structure. + + http://msdn.microsoft.com/en-us/library/dd317599%28VS.85%29.aspx + + + WAVE_FORMAT_DVM + + + WAVE_FORMAT_VORBIS1 "Og" Original stream compatible + + + WAVE_FORMAT_VORBIS2 "Pg" Have independent header + + + WAVE_FORMAT_VORBIS3 "Qg" Have no codebook header + + + WAVE_FORMAT_VORBIS1P "og" Original stream compatible + + + WAVE_FORMAT_VORBIS2P "pg" Have independent headere + + + WAVE_FORMAT_VORBIS3P "qg" Have no codebook header + + + WAVE_FORMAT_EXTENSIBLE + + + + + + + WaveFormatExtensible + http://www.microsoft.com/whdc/device/audio/multichaud.mspx + + + + + Parameterless constructor for marshalling + + + + + Creates a new WaveFormatExtensible for PCM or IEEE + + + + + WaveFormatExtensible for PCM or floating point can be awkward to work with + This creates a regular WaveFormat structure representing the same audio format + Returns the WaveFormat unchanged for non PCM or IEEE float + + + + + + SubFormat (may be one of AudioMediaSubtypes) + + + + + Serialize + + + + + + String representation + + + + + This class used for marshalling from unmanaged code + + + + + Allows the extra data to be read + + + + + parameterless constructor for marshalling + + + + + Reads this structure from a BinaryReader + + + + + Writes this structure to a BinaryWriter + + + + + The WMA wave format. + May not be much use because WMA codec is a DirectShow DMO not an ACM + + + + + Generic interface for wave recording + + + + + Recording WaveFormat + + + + + Start Recording + + + + + Stop Recording + + + + + Indicates recorded data is available + + + + + Indicates that all recorded data has now been received. + + + + + This class writes audio data to a .aif file on disk + + + + + Creates an Aiff file by reading all the data from a WaveProvider + BEWARE: the WaveProvider MUST return 0 from its Read method when it is finished, + or the Aiff File will grow indefinitely. + + The filename to use + The source WaveProvider + + + + AiffFileWriter that actually writes to a stream + + Stream to be written to + Wave format to use + + + + Creates a new AiffFileWriter + + The filename to write to + The Wave Format of the output data + + + + The aiff file name or null if not applicable + + + + + Number of bytes of audio in the data chunk + + + + + WaveFormat of this aiff file + + + + + Returns false: Cannot read from a AiffFileWriter + + + + + Returns true: Can write to a AiffFileWriter + + + + + Returns false: Cannot seek within a AiffFileWriter + + + + + Read is not supported for a AiffFileWriter + + + + + Seek is not supported for a AiffFileWriter + + + + + SetLength is not supported for AiffFileWriter + + + + + + Gets the Position in the AiffFile (i.e. number of bytes written so far) + + + + + Appends bytes to the AiffFile (assumes they are already in the correct format) + + the buffer containing the wave data + the offset from which to start writing + the number of bytes to write + + + + Writes a single sample to the Aiff file + + the sample to write (assumed floating point with 1.0f as max value) + + + + Writes 32 bit floating point samples to the Aiff file + They will be converted to the appropriate bit depth depending on the WaveFormat of the AIF file + + The buffer containing the floating point samples + The offset from which to start writing + The number of floating point samples to write + + + + Writes 16 bit samples to the Aiff file + + The buffer containing the 16 bit samples + The offset from which to start writing + The number of 16 bit samples to write + + + + Ensures data is written to disk + + + + + Actually performs the close,making sure the header contains the correct data + + True if called from Dispose + + + + Updates the header with file size information + + + + + Finaliser - should only be called if the user forgot to close this AiffFileWriter + + + + + Raised when ASIO data has been recorded. + It is important to handle this as quickly as possible as it is in the buffer callback + + + + + Initialises a new instance of AsioAudioAvailableEventArgs + + Pointers to the ASIO buffers for each channel + Pointers to the ASIO buffers for each channel + Number of samples in each buffer + Audio format within each buffer + + + + Pointer to a buffer per input channel + + + + + Pointer to a buffer per output channel + Allows you to write directly to the output buffers + If you do so, set SamplesPerBuffer = true, + and make sure all buffers are written to with valid data + + + + + Set to true if you have written to the output buffers + If so, AsioOut will not read from its source + + + + + Number of samples in each buffer + + + + + Converts all the recorded audio into a buffer of 32 bit floating point samples, interleaved by channel + + The samples as 32 bit floating point, interleaved + + + + Audio format within each buffer + Most commonly this will be one of, Int32LSB, Int16LSB, Int24LSB or Float32LSB + + + + + Gets as interleaved samples, allocating a float array + + The samples as 32 bit floating point values + + + + ASIO Out Player. New implementation using an internal C# binding. + + This implementation is only supporting Short16Bit and Float32Bit formats and is optimized + for 2 outputs channels . + SampleRate is supported only if AsioDriver is supporting it + + This implementation is probably the first AsioDriver binding fully implemented in C#! + + Original Contributor: Mark Heath + New Contributor to C# binding : Alexandre Mutel - email: alexandre_mutel at yahoo.fr + + + + + Playback Stopped + + + + + When recording, fires whenever recorded audio is available + + + + + Initializes a new instance of the class with the first + available ASIO Driver. + + + + + Initializes a new instance of the class with the driver name. + + Name of the device. + + + + Opens an ASIO output device + + Device number (zero based) + + + + Releases unmanaged resources and performs other cleanup operations before the + is reclaimed by garbage collection. + + + + + Dispose + + + + + Gets the names of the installed ASIO Driver. + + an array of driver names + + + + Determines whether ASIO is supported. + + + true if ASIO is supported; otherwise, false. + + + + + Inits the driver from the asio driver name. + + Name of the driver. + + + + Shows the control panel + + + + + Starts playback + + + + + Stops playback + + + + + Pauses playback + + + + + Initialises to play + + Source wave provider + + + + Initialises to play, with optional recording + + Source wave provider - set to null for record only + Number of channels to record + Specify sample rate here if only recording, ignored otherwise + + + + driver buffer update callback to fill the wave buffer. + + The input channels. + The output channels. + + + + Gets the latency (in ms) of the playback driver + + + + + Playback State + + + + + Driver Name + + + + + The number of output channels we are currently using for playback + (Must be less than or equal to DriverOutputChannelCount) + + + + + The number of input channels we are currently recording from + (Must be less than or equal to DriverInputChannelCount) + + + + + The maximum number of input channels this ASIO driver supports + + + + + The maximum number of output channels this ASIO driver supports + + + + + By default the first channel on the input WaveProvider is sent to the first ASIO output. + This option sends it to the specified channel number. + Warning: make sure you don't set it higher than the number of available output channels - + the number of source channels. + n.b. Future NAudio may modify this + + + + + Input channel offset (used when recording), allowing you to choose to record from just one + specific input rather than them all + + + + + Sets the volume (1.0 is unity gain) + Not supported for ASIO Out. Set the volume on the input stream instead + + + + + Get the input channel name + + channel index (zero based) + channel name + + + + Get the output channel name + + channel index (zero based) + channel name + + + + A wave file writer that adds cue support + + + + + Writes a wave file, including a cues chunk + + + + + Adds a cue to the Wave file + + Sample position + Label text + + + + Updates the header, and writes the cues out + + + + + Media Foundation Encoder class allows you to use Media Foundation to encode an IWaveProvider + to any supported encoding format + + + + + Queries the available bitrates for a given encoding output type, sample rate and number of channels + + Audio subtype - a value from the AudioSubtypes class + The sample rate of the PCM to encode + The number of channels of the PCM to encode + An array of available bitrates in average bits per second + + + + Gets all the available media types for a particular + + Audio subtype - a value from the AudioSubtypes class + An array of available media types that can be encoded with this subtype + + + + Helper function to simplify encoding Window Media Audio + Should be supported on Vista and above (not tested) + + Input provider, must be PCM + Output file path, should end with .wma + Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type + + + + Helper function to simplify encoding to MP3 + By default, will only be available on Windows 8 and above + + Input provider, must be PCM + Output file path, should end with .mp3 + Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type + + + + Helper function to simplify encoding to AAC + By default, will only be available on Windows 7 and above + + Input provider, must be PCM + Output file path, should end with .mp4 (or .aac on Windows 8) + Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type + + + + Tries to find the encoding media type with the closest bitrate to that specified + + Audio subtype, a value from AudioSubtypes + Your encoder input format (used to check sample rate and channel count) + Your desired bitrate + The closest media type, or null if none available + + + + Creates a new encoder that encodes to the specified output media type + + Desired output media type + + + + Encodes a file + + Output filename (container type is deduced from the filename) + Input provider (should be PCM, some encoders will also allow IEEE float) + + + + Disposes this instance + + + + + + Disposes this instance + + + + + Finalizer + + + + + Stopped Event Args + + + + + Initializes a new instance of StoppedEventArgs + + An exception to report (null if no exception) + + + + An exception. Will be null if the playback or record operation stopped + + + + + IWaveBuffer interface use to store wave datas. + Data can be manipulated with arrays (,, + , ) that are pointing to the same memory buffer. + This is a requirement for all subclasses. + + Use the associated Count property based on the type of buffer to get the number of data in the + buffer. + + for the standard implementation using C# unions. + + + + + Gets the byte buffer. + + The byte buffer. + + + + Gets the float buffer. + + The float buffer. + + + + Gets the short buffer. + + The short buffer. + + + + Gets the int buffer. + + The int buffer. + + + + Gets the max size in bytes of the byte buffer.. + + Maximum number of bytes in the buffer. + + + + Gets the byte buffer count. + + The byte buffer count. + + + + Gets the float buffer count. + + The float buffer count. + + + + Gets the short buffer count. + + The short buffer count. + + + + Gets the int buffer count. + + The int buffer count. + + + + Represents the interface to a device that can play a WaveFile + + + + + Begin playback + + + + + Stop playback + + + + + Pause Playback + + + + + Initialise playback + + The waveprovider to be played + + + + Current playback state + + + + + The volume 1.0 is full scale + + + + + Indicates that playback has gone into a stopped state due to + reaching the end of the input stream or an error has been encountered during playback + + + + + Interface for IWavePlayers that can report position + + + + + Position (in terms of bytes played - does not necessarily) + + Position in bytes + + + + Gets a instance indicating the format the hardware is using. + + + + + Generic interface for all WaveProviders. + + + + + Gets the WaveFormat of this WaveProvider. + + The wave format. + + + + Fill the specified buffer with wave data. + + The buffer to fill of wave data. + Offset into buffer + The number of bytes to read + the number of bytes written to the buffer. + + + + NativeDirectSoundOut using DirectSound COM interop. + Contact author: Alexandre Mutel - alexandre_mutel at yahoo.fr + Modified by: Graham "Gee" Plumb + + + + + Playback Stopped + + + + + Gets the DirectSound output devices in the system + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + + + + + Initializes a new instance of the class. + (40ms seems to work under Vista). + + The latency. + Selected device + + + + Releases unmanaged resources and performs other cleanup operations before the + is reclaimed by garbage collection. + + + + + Begin playback + + + + + Stop playback + + + + + Pause Playback + + + + + Gets the current position in bytes from the wave output device. + (n.b. this is not the same thing as the position within your reader + stream) + + Position in bytes + + + + Gets the current position from the wave output device. + + + + + Initialise playback + + The waveprovider to be played + + + + Current playback state + + + + + + The volume 1.0 is full scale + + + + + + Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + + + + + Determines whether the SecondaryBuffer is lost. + + + true if [is buffer lost]; otherwise, false. + + + + + Convert ms to bytes size according to WaveFormat + + The ms + number of byttes + + + + Processes the samples in a separate thread. + + + + + Stop playback + + + + + Feeds the SecondaryBuffer with the WaveStream + + number of bytes to feed + + + + IDirectSound interface + + + + + IDirectSoundBuffer interface + + + + + IDirectSoundNotify interface + + + + + Instanciate DirectSound from the DLL + + The GUID. + The direct sound. + The p unk outer. + + + + DirectSound default playback device GUID + + + + + DirectSound default capture device GUID + + + + + DirectSound default device for voice playback + + + + + DirectSound default device for voice capture + + + + + The DSEnumCallback function is an application-defined callback function that enumerates the DirectSound drivers. + The system calls this function in response to the application's call to the DirectSoundEnumerate or DirectSoundCaptureEnumerate function. + + Address of the GUID that identifies the device being enumerated, or NULL for the primary device. This value can be passed to the DirectSoundCreate8 or DirectSoundCaptureCreate8 function to create a device object for that driver. + Address of a null-terminated string that provides a textual description of the DirectSound device. + Address of a null-terminated string that specifies the module name of the DirectSound driver corresponding to this device. + Address of application-defined data. This is the pointer passed to DirectSoundEnumerate or DirectSoundCaptureEnumerate as the lpContext parameter. + Returns TRUE to continue enumerating drivers, or FALSE to stop. + + + + The DirectSoundEnumerate function enumerates the DirectSound drivers installed in the system. + + callback function + User context + + + + Gets the HANDLE of the desktop window. + + HANDLE of the Desktop window + + + + Class for enumerating DirectSound devices + + + + + The device identifier + + + + + Device description + + + + + Device module name + + + + + Like IWaveProvider, but makes it much simpler to put together a 32 bit floating + point mixing engine + + + + + Gets the WaveFormat of this Sample Provider. + + The wave format. + + + + Fill the specified buffer with 32 bit floating point samples + + The buffer to fill with samples. + Offset into buffer + The number of samples to read + the number of samples written to the buffer. + + + + Playback State + + + + + Stopped + + + + + Playing + + + + + Paused + + + + + Support for playback using Wasapi + + + + + Playback Stopped + + + + + WASAPI Out shared mode, defauult + + + + + WASAPI Out using default audio endpoint + + ShareMode - shared or exclusive + Desired latency in milliseconds + + + + WASAPI Out using default audio endpoint + + ShareMode - shared or exclusive + true if sync is done with event. false use sleep. + Desired latency in milliseconds + + + + Creates a new WASAPI Output + + Device to use + + true if sync is done with event. false use sleep. + Desired latency in milliseconds + + + + Gets the current position in bytes from the wave output device. + (n.b. this is not the same thing as the position within your reader + stream) + + Position in bytes + + + + Gets a instance indicating the format the hardware is using. + + + + + Begin Playback + + + + + Stop playback and flush buffers + + + + + Stop playback without flushing buffers + + + + + Initialize for playing the specified wave stream + + IWaveProvider to play + + + + Playback State + + + + + Volume + + + + + Retrieve the AudioStreamVolume object for this audio stream + + + This returns the AudioStreamVolume object ONLY for shared audio streams. + + + This is thrown when an exclusive audio stream is being used. + + + + + Dispose + + + + + WaveBuffer class use to store wave datas. Data can be manipulated with arrays + (,,, ) that are pointing to the + same memory buffer. Use the associated Count property based on the type of buffer to get the number of + data in the buffer. + Implicit casting is now supported to float[], byte[], int[], short[]. + You must not use Length on returned arrays. + + n.b. FieldOffset is 8 now to allow it to work natively on 64 bit + + + + + Number of Bytes + + + + + Initializes a new instance of the class. + + The number of bytes. The size of the final buffer will be aligned on 4 Bytes (upper bound) + + + + Initializes a new instance of the class binded to a specific byte buffer. + + A byte buffer to bound the WaveBuffer to. + + + + Binds this WaveBuffer instance to a specific byte buffer. + + A byte buffer to bound the WaveBuffer to. + + + + Performs an implicit conversion from to . + + The wave buffer. + The result of the conversion. + + + + Performs an implicit conversion from to . + + The wave buffer. + The result of the conversion. + + + + Performs an implicit conversion from to . + + The wave buffer. + The result of the conversion. + + + + Performs an implicit conversion from to . + + The wave buffer. + The result of the conversion. + + + + Gets the byte buffer. + + The byte buffer. + + + + Gets the float buffer. + + The float buffer. + + + + Gets the short buffer. + + The short buffer. + + + + Gets the int buffer. + + The int buffer. + + + + Gets the max size in bytes of the byte buffer.. + + Maximum number of bytes in the buffer. + + + + Gets or sets the byte buffer count. + + The byte buffer count. + + + + Gets or sets the float buffer count. + + The float buffer count. + + + + Gets or sets the short buffer count. + + The short buffer count. + + + + Gets or sets the int buffer count. + + The int buffer count. + + + + Clears the associated buffer. + + + + + Copy this WaveBuffer to a destination buffer up to ByteBufferCount bytes. + + + + + Checks the validity of the count parameters. + + Name of the arg. + The value. + The size of value. + + + + Wave Callback Info + + + + + Callback Strategy + + + + + Window Handle (if applicable) + + + + + Sets up a new WaveCallbackInfo for function callbacks + + + + + Sets up a new WaveCallbackInfo to use a New Window + IMPORTANT: only use this on the GUI thread + + + + + Sets up a new WaveCallbackInfo to use an existing window + IMPORTANT: only use this on the GUI thread + + + + + Wave Callback Strategy + + + + + Use a function + + + + + Create a new window (should only be done if on GUI thread) + + + + + Use an existing window handle + + + + + Use an event handle + + + + + This class writes WAV data to a .wav file on disk + + + + + Creates a 16 bit Wave File from an ISampleProvider + BEWARE: the source provider must not return data indefinitely + + The filename to write to + The source sample provider + + + + Creates a Wave file by reading all the data from a WaveProvider + BEWARE: the WaveProvider MUST return 0 from its Read method when it is finished, + or the Wave File will grow indefinitely. + + The filename to use + The source WaveProvider + + + + Writes to a stream by reading all the data from a WaveProvider + BEWARE: the WaveProvider MUST return 0 from its Read method when it is finished, + or the Wave File will grow indefinitely. + + The stream the method will output to + The source WaveProvider + + + + WaveFileWriter that actually writes to a stream + + Stream to be written to + Wave format to use + + + + Creates a new WaveFileWriter + + The filename to write to + The Wave Format of the output data + + + + The wave file name or null if not applicable + + + + + Number of bytes of audio in the data chunk + + + + + WaveFormat of this wave file + + + + + Returns false: Cannot read from a WaveFileWriter + + + + + Returns true: Can write to a WaveFileWriter + + + + + Returns false: Cannot seek within a WaveFileWriter + + + + + Read is not supported for a WaveFileWriter + + + + + Seek is not supported for a WaveFileWriter + + + + + SetLength is not supported for WaveFileWriter + + + + + + Gets the Position in the WaveFile (i.e. number of bytes written so far) + + + + + Appends bytes to the WaveFile (assumes they are already in the correct format) + + the buffer containing the wave data + the offset from which to start writing + the number of bytes to write + + + + Appends bytes to the WaveFile (assumes they are already in the correct format) + + the buffer containing the wave data + the offset from which to start writing + the number of bytes to write + + + + Writes a single sample to the Wave file + + the sample to write (assumed floating point with 1.0f as max value) + + + + Writes 32 bit floating point samples to the Wave file + They will be converted to the appropriate bit depth depending on the WaveFormat of the WAV file + + The buffer containing the floating point samples + The offset from which to start writing + The number of floating point samples to write + + + + Writes 16 bit samples to the Wave file + + The buffer containing the 16 bit samples + The offset from which to start writing + The number of 16 bit samples to write + + + + Writes 16 bit samples to the Wave file + + The buffer containing the 16 bit samples + The offset from which to start writing + The number of 16 bit samples to write + + + + Ensures data is written to disk + Also updates header, so that WAV file will be valid up to the point currently written + + + + + Actually performs the close,making sure the header contains the correct data + + True if called from Dispose + + + + Updates the header with file size information + + + + + Finaliser - should only be called if the user forgot to close this WaveFileWriter + + + + + Represents a wave out device + + + + + Indicates playback has stopped automatically + + + + + Retrieves the capabilities of a waveOut device + + Device to test + The WaveOut device capabilities + + + + Returns the number of Wave Out devices available in the system + + + + + Gets or sets the desired latency in milliseconds + Should be set before a call to Init + + + + + Gets or sets the number of buffers used + Should be set before a call to Init + + + + + Gets or sets the device number + Should be set before a call to Init + This must be between 0 and DeviceCount - 1. + + + + + Creates a default WaveOut device + Will use window callbacks if called from a GUI thread, otherwise function + callbacks + + + + + Creates a WaveOut device using the specified window handle for callbacks + + A valid window handle + + + + Opens a WaveOut device + + + + + Initialises the WaveOut device + + WaveProvider to play + + + + Start playing the audio from the WaveStream + + + + + Pause the audio + + + + + Resume playing after a pause from the same position + + + + + Stop and reset the WaveOut device + + + + + Gets the current position in bytes from the wave output device. + (n.b. this is not the same thing as the position within your reader + stream - it calls directly into waveOutGetPosition) + + Position in bytes + + + + Gets a instance indicating the format the hardware is using. + + + + + Playback State + + + + + Volume for this device 1.0 is full scale + + + + + Closes this WaveOut device + + + + + Closes the WaveOut device and disposes of buffers + + True if called from Dispose + + + + Finalizer. Only called when user forgets to call Dispose + + + + + Alternative WaveOut class, making use of the Event callback + + + + + Indicates playback has stopped automatically + + + + + Gets or sets the desired latency in milliseconds + Should be set before a call to Init + + + + + Gets or sets the number of buffers used + Should be set before a call to Init + + + + + Gets or sets the device number + Should be set before a call to Init + This must be between 0 and DeviceCount - 1. + + + + + Opens a WaveOut device + + + + + Initialises the WaveOut device + + WaveProvider to play + + + + Start playing the audio from the WaveStream + + + + + Pause the audio + + + + + Resume playing after a pause from the same position + + + + + Stop and reset the WaveOut device + + + + + Gets the current position in bytes from the wave output device. + (n.b. this is not the same thing as the position within your reader + stream - it calls directly into waveOutGetPosition) + + Position in bytes + + + + Gets a instance indicating the format the hardware is using. + + + + + Playback State + + + + + Obsolete property + + + + + Closes this WaveOut device + + + + + Closes the WaveOut device and disposes of buffers + + True if called from Dispose + + + + Finalizer. Only called when user forgets to call Dispose + + + + + Provides a buffered store of samples + Read method will return queued samples or fill buffer with zeroes + Now backed by a circular buffer + + + + + Creates a new buffered WaveProvider + + WaveFormat + + + + If true, always read the amount of data requested, padding with zeroes if necessary + By default is set to true + + + + + Buffer length in bytes + + + + + Buffer duration + + + + + If true, when the buffer is full, start throwing away data + if false, AddSamples will throw an exception when buffer is full + + + + + The number of buffered bytes + + + + + Buffered Duration + + + + + Gets the WaveFormat + + + + + Adds samples. Takes a copy of buffer, so that buffer can be reused if necessary + + + + + Reads from this WaveProvider + Will always return count bytes, since we will zero-fill the buffer if not enough available + + + + + Discards all audio from the buffer + + + + + The Media Foundation Resampler Transform + + + + + Creates the Media Foundation Resampler, allowing modifying of sample rate, bit depth and channel count + + Source provider, must be PCM + Output format, must also be PCM + + + + Creates a resampler with a specified target output sample rate + + Source provider + Output sample rate + + + + Creates and configures the actual Resampler transform + + A newly created and configured resampler MFT + + + + Gets or sets the Resampler quality. n.b. set the quality before starting to resample. + 1 is lowest quality (linear interpolation) and 60 is best quality + + + + + Disposes this resampler + + + + + WaveProvider that can mix together multiple 32 bit floating point input provider + All channels must have the same number of inputs and same sample rate + n.b. Work in Progress - not tested yet + + + + + Creates a new MixingWaveProvider32 + + + + + Creates a new 32 bit MixingWaveProvider32 + + inputs - must all have the same format. + Thrown if the input streams are not 32 bit floating point, + or if they have different formats to each other + + + + Add a new input to the mixer + + The wave input to add + + + + Remove an input from the mixer + + waveProvider to remove + + + + The number of inputs to this mixer + + + + + Reads bytes from this wave stream + + buffer to read into + offset into buffer + number of bytes required + Number of bytes read. + Thrown if an invalid number of bytes requested + + + + Actually performs the mixing + + + + + + + + + + Allows any number of inputs to be patched to outputs + Uses could include swapping left and right channels, turning mono into stereo, + feeding different input sources to different soundcard outputs etc + + + + + Creates a multiplexing wave provider, allowing re-patching of input channels to different + output channels + + Input wave providers. Must all be of the same format, but can have any number of channels + Desired number of output channels. + + + + persistent temporary buffer to prevent creating work for garbage collector + + + + + Reads data from this WaveProvider + + Buffer to be filled with sample data + Offset to write to within buffer, usually 0 + Number of bytes required + Number of bytes read + + + + The WaveFormat of this WaveProvider + + + + + Connects a specified input channel to an output channel + + Input Channel index (zero based). Must be less than InputChannelCount + Output Channel index (zero based). Must be less than OutputChannelCount + + + + The number of input channels. Note that this is not the same as the number of input wave providers. If you pass in + one stereo and one mono input provider, the number of input channels is three. + + + + + The number of output channels, as specified in the constructor. + + + + + Silence producing wave provider + Useful for playing silence when doing a WASAPI Loopback Capture + + + + + Creates a new silence producing wave provider + + Desired WaveFormat (should be PCM / IEE float + + + + Read silence from into the buffer + + + + + WaveFormat of this silence producing wave provider + + + + + Takes a stereo 16 bit input and turns it mono, allowing you to select left or right channel only or mix them together + + + + + Creates a new mono waveprovider based on a stereo input + + Stereo 16 bit PCM input + + + + 1.0 to mix the mono source entirely to the left channel + + + + + 1.0 to mix the mono source entirely to the right channel + + + + + Output Wave Format + + + + + Reads bytes from this WaveProvider + + + + + Converts from mono to stereo, allowing freedom to route all, some, or none of the incoming signal to left or right channels + + + + + Creates a new stereo waveprovider based on a mono input + + Mono 16 bit PCM input + + + + 1.0 to copy the mono stream to the left channel without adjusting volume + + + + + 1.0 to copy the mono stream to the right channel without adjusting volume + + + + + Output Wave Format + + + + + Reads bytes from this WaveProvider + + + + + Helper class allowing us to modify the volume of a 16 bit stream without converting to IEEE float + + + + + Constructs a new VolumeWaveProvider16 + + Source provider, must be 16 bit PCM + + + + Gets or sets volume. + 1.0 is full scale, 0.0 is silence, anything over 1.0 will amplify but potentially clip + + + + + WaveFormat of this WaveProvider + + + + + Read bytes from this WaveProvider + + Buffer to read into + Offset within buffer to read to + Bytes desired + Bytes read + + + + Converts IEEE float to 16 bit PCM, optionally clipping and adjusting volume along the way + + + + + Creates a new WaveFloatTo16Provider + + the source provider + + + + Reads bytes from this wave stream + + The destination buffer + Offset into the destination buffer + Number of bytes read + Number of bytes read. + + + + + + + + + Volume of this channel. 1.0 = full scale + + + + + Converts 16 bit PCM to IEEE float, optionally adjusting volume along the way + + + + + Creates a new Wave16toFloatProvider + + the source provider + + + + Reads bytes from this wave stream + + The destination buffer + Offset into the destination buffer + Number of bytes read + Number of bytes read. + + + + + + + + + Volume of this channel. 1.0 = full scale + + + + + Buffered WaveProvider taking source data from WaveIn + + + + + Creates a new WaveInProvider + n.b. Should make sure the WaveFormat is set correctly on IWaveIn before calling + + The source of wave data + + + + Reads data from the WaveInProvider + + + + + The WaveFormat + + + + + Base class for creating a 16 bit wave provider + + + + + Initializes a new instance of the WaveProvider16 class + defaulting to 44.1kHz mono + + + + + Initializes a new instance of the WaveProvider16 class with the specified + sample rate and number of channels + + + + + Allows you to specify the sample rate and channels for this WaveProvider + (should be initialised before you pass it to a wave player) + + + + + Implements the Read method of IWaveProvider by delegating to the abstract + Read method taking a short array + + + + + Method to override in derived classes + Supply the requested number of samples into the buffer + + + + + The Wave Format + + + + + Base class for creating a 32 bit floating point wave provider + Can also be used as a base class for an ISampleProvider that can + be plugged straight into anything requiring an IWaveProvider + + + + + Initializes a new instance of the WaveProvider32 class + defaulting to 44.1kHz mono + + + + + Initializes a new instance of the WaveProvider32 class with the specified + sample rate and number of channels + + + + + Allows you to specify the sample rate and channels for this WaveProvider + (should be initialised before you pass it to a wave player) + + + + + Implements the Read method of IWaveProvider by delegating to the abstract + Read method taking a float array + + + + + Method to override in derived classes + Supply the requested number of samples into the buffer + + + + + The Wave Format + + + + + Utility class to intercept audio from an IWaveProvider and + save it to disk + + + + + Constructs a new WaveRecorder + + The location to write the WAV file to + The Source Wave Provider + + + + Read simply returns what the source returns, but writes to disk along the way + + + + + The WaveFormat + + + + + Closes the WAV file + + + + A read-only stream of AIFF data based on an aiff file + with an associated WaveFormat + originally contributed to NAudio by Giawa + + + + Supports opening a AIF file + The AIF is of similar nastiness to the WAV format. + This supports basic reading of uncompressed PCM AIF files, + with 8, 16, 24 and 32 bit PCM data. + + + + + Creates an Aiff File Reader based on an input stream + + The input stream containing a AIF file including header + + + + Ensures valid AIFF header and then finds data offset. + + The stream, positioned at the start of audio data + The format found + The position of the data chunk + The length of the data chunk + Additional chunks found + + + + Cleans up the resources associated with this AiffFileReader + + + + + + + + + + + + + + + Number of Samples (if possible to calculate) + + + + + Position in the AIFF file + + + + + + Reads bytes from the AIFF File + + + + + + AIFF Chunk + + + + + Chunk Name + + + + + Chunk Length + + + + + Chunk start + + + + + Creates a new AIFF Chunk + + + + + AudioFileReader simplifies opening an audio file in NAudio + Simply pass in the filename, and it will attempt to open the + file and set up a conversion path that turns into PCM IEEE float. + ACM codecs will be used for conversion. + It provides a volume property and implements both WaveStream and + ISampleProvider, making it possibly the only stage in your audio + pipeline necessary for simple playback scenarios + + + + + Initializes a new instance of AudioFileReader + + The file to open + + + + Creates the reader stream, supporting all filetypes in the core NAudio library, + and ensuring we are in PCM format + + File Name + + + + WaveFormat of this stream + + + + + Length of this stream (in bytes) + + + + + Position of this stream (in bytes) + + + + + Reads from this wave stream + + Audio buffer + Offset into buffer + Number of bytes required + Number of bytes read + + + + Reads audio from this sample provider + + Sample buffer + Offset into sample buffer + Number of samples required + Number of samples read + + + + Gets or Sets the Volume of this AudioFileReader. 1.0f is full volume + + + + + Helper to convert source to dest bytes + + + + + Helper to convert dest to source bytes + + + + + Disposes this AudioFileReader + + True if called from Dispose + + + + Helper stream that lets us read from compressed audio files with large block alignment + as though we could read any amount and reposition anywhere + + + + + Creates a new BlockAlignReductionStream + + the input stream + + + + Block alignment of this stream + + + + + Wave Format + + + + + Length of this Stream + + + + + Current position within stream + + + + + Disposes this WaveStream + + + + + Reads data from this stream + + + + + + + + + Implementation of Com IStream + + + + + Holds information on a cue: a labeled position within a Wave file + + + + + Cue position in samples + + + + + Label of the cue + + + + + Creates a Cue based on a sample position and label + + + + + + + Holds a list of cues + + + The specs for reading and writing cues from the cue and list RIFF chunks + are from http://www.sonicspot.com/guide/wavefiles.html and http://www.wotsit.org/ + ------------------------------ + The cues are stored like this: + ------------------------------ + struct CuePoint + { + Int32 dwIdentifier; + Int32 dwPosition; + Int32 fccChunk; + Int32 dwChunkStart; + Int32 dwBlockStart; + Int32 dwSampleOffset; + } + + struct CueChunk + { + Int32 chunkID; + Int32 chunkSize; + Int32 dwCuePoints; + CuePoint[] points; + } + ------------------------------ + Labels look like this: + ------------------------------ + struct ListHeader + { + Int32 listID; /* 'list' */ + Int32 chunkSize; /* includes the Type ID below */ + Int32 typeID; /* 'adtl' */ + } + + struct LabelChunk + { + Int32 chunkID; + Int32 chunkSize; + Int32 dwIdentifier; + Char[] dwText; /* Encoded with extended ASCII */ + } LabelChunk; + + + + + Creates an empty cue list + + + + + Adds an item to the list + + Cue + + + + Gets sample positions for the embedded cues + + Array containing the cue positions + + + + Gets labels for the embedded cues + + Array containing the labels + + + + Creates a cue list from the cue RIFF chunk and the list RIFF chunk + + The data contained in the cue chunk + The data contained in the list chunk + + + + Gets the cues as the concatenated cue and list RIFF chunks. + + RIFF chunks containing the cue data + + + + Number of cues + + + + + Accesses the cue at the specified index + + + + + + + Checks if the cue and list chunks exist and if so, creates a cue list + + + + + A wave file reader supporting cue reading + + + + + Loads a wavefile and supports reading cues + + + + + + Cue List (can be null if cues not present) + + + + + An interface for WaveStreams which can report notification of individual samples + + + + + A sample has been detected + + + + + Sample event arguments + + + + + Left sample + + + + + Right sample + + + + + Constructor + + + + + Class for reading any file that Media Foundation can play + Will only work in Windows Vista and above + Automatically converts to PCM + If it is a video file with multiple audio streams, it will pick out the first audio stream + + + + + Allows customisation of this reader class + + + + + Sets up the default settings for MediaFoundationReader + + + + + Allows us to request IEEE float output (n.b. no guarantee this will be accepted) + + + + + If true, the reader object created in the constructor is used in Read + Should only be set to true if you are working entirely on an STA thread, or + entirely with MTA threads. + + + + + If true, the reposition does not happen immediately, but waits until the + next call to read to be processed. + + + + + Default constructor + + + + + Creates a new MediaFoundationReader based on the supplied file + + Filename (can also be a URL e.g. http:// mms:// file://) + + + + Creates a new MediaFoundationReader based on the supplied file + + Filename + Advanced settings + + + + Initializes + + + + + Creates the reader (overridable by ) + + + + + Reads from this wave stream + + Buffer to read into + Offset in buffer + Bytes required + Number of bytes read; 0 indicates end of stream + + + + WaveFormat of this stream (n.b. this is after converting to PCM) + + + + + The bytesRequired of this stream in bytes (n.b may not be accurate) + + + + + Current position within this stream + + + + + Cleans up after finishing with this reader + + true if called from Dispose + + + + WaveFormat has changed + + + + + Class for reading from MP3 files + + + + + The MP3 wave format (n.b. NOT the output format of this stream - see the WaveFormat property) + + + + Supports opening a MP3 file + + + Supports opening a MP3 file + MP3 File name + Factory method to build a frame decompressor + + + + Opens MP3 from a stream rather than a file + Will not dispose of this stream itself + + The incoming stream containing MP3 data + + + + Opens MP3 from a stream rather than a file + Will not dispose of this stream itself + + The incoming stream containing MP3 data + Factory method to build a frame decompressor + + + + Function that can create an MP3 Frame decompressor + + A WaveFormat object describing the MP3 file format + An MP3 Frame decompressor + + + + Creates an ACM MP3 Frame decompressor. This is the default with NAudio + + A WaveFormat object based + + + + + Gets the total length of this file in milliseconds. + + + + + ID3v2 tag if present + + + + + ID3v1 tag if present + + + + + Reads the next mp3 frame + + Next mp3 frame, or null if EOF + + + + Reads the next mp3 frame + + Next mp3 frame, or null if EOF + + + + This is the length in bytes of data available to be read out from the Read method + (i.e. the decompressed MP3 length) + n.b. this may return 0 for files whose length is unknown + + + + + + + + + + + + + + + Reads decompressed PCM data from our MP3 file. + + + + + Xing header if present + + + + + Disposes this WaveStream + + + + + WaveStream that simply passes on data from its source stream + (e.g. a MemoryStream) + + + + + Initialises a new instance of RawSourceWaveStream + + The source stream containing raw audio + The waveformat of the audio in the source stream + + + + Initialises a new instance of RawSourceWaveStream + + The buffer containing raw audio + Offset in the source buffer to read from + Number of bytes to read in the buffer + The waveformat of the audio in the source stream + + + + The WaveFormat of this stream + + + + + The length in bytes of this stream (if supported) + + + + + The current position in this stream + + + + + Reads data from the stream + + + + + Wave Stream for converting between sample rates + + + + + WaveStream to resample using the DMO Resampler + + Input Stream + Desired Output Format + + + + Stream Wave Format + + + + + Stream length in bytes + + + + + Stream position in bytes + + + + + Reads data from input stream + + buffer + offset into buffer + Bytes required + Number of bytes read + + + + Dispose + + True if disposing (not from finalizer) + + + + Holds information about a RIFF file chunk + + + + + Creates a RiffChunk object + + + + + The chunk identifier + + + + + The chunk identifier converted to a string + + + + + The chunk length + + + + + The stream position this chunk is located at + + + + + A simple compressor + + + + + Create a new simple compressor stream + + Source stream + + + + Make-up Gain + + + + + Threshold + + + + + Ratio + + + + + Attack time + + + + + Release time + + + + + Determine whether the stream has the required amount of data. + + Number of bytes of data required from the stream. + Flag indicating whether the required amount of data is avialable. + + + + Turns gain on or off + + + + + Returns the stream length + + + + + Gets or sets the current position in the stream + + + + + Gets the WaveFormat of this stream + + + + + Reads bytes from this stream + + Buffer to read into + Offset in array to read into + Number of bytes to read + Number of bytes read + + + + Disposes this stream + + true if the user called this + + + + Gets the block alignment for this stream + + + + + MediaFoundationReader supporting reading from a stream + + + + + Constructs a new media foundation reader from a stream + + + + + Creates the reader + + + + + WaveStream that converts 32 bit audio back down to 16 bit, clipping if necessary + + + + + The method reuses the same buffer to prevent + unnecessary allocations. + + + + + Creates a new Wave32To16Stream + + the source stream + + + + Sets the volume for this stream. 1.0f is full scale + + + + + + + + + + Returns the stream length + + + + + Gets or sets the current position in the stream + + + + + Reads bytes from this wave stream + + Destination buffer + Offset into destination buffer + + Number of bytes read. + + + + Conversion to 16 bit and clipping + + + + + + + + + + Clip indicator. Can be reset. + + + + + Disposes this WaveStream + + + + + Represents Channel for the WaveMixerStream + 32 bit output and 16 bit input + It's output is always stereo + The input stream can be panned + + + + + Creates a new WaveChannel32 + + the source stream + stream volume (1 is 0dB) + pan control (-1 to 1) + + + + Creates a WaveChannel32 with default settings + + The source stream + + + + Gets the block alignment for this WaveStream + + + + + Returns the stream length + + + + + Gets or sets the current position in the stream + + + + + Reads bytes from this wave stream + + The destination buffer + Offset into the destination buffer + Number of bytes read + Number of bytes read. + + + + If true, Read always returns the number of bytes requested + + + + + + + + + + Volume of this channel. 1.0 = full scale + + + + + Pan of this channel (from -1 to 1) + + + + + Determines whether this channel has any data to play + to allow optimisation to not read, but bump position forward + + + + + Disposes this WaveStream + + + + + Sample + + + + + Raise the sample event (no check for null because it has already been done) + + + + This class supports the reading of WAV files, + providing a repositionable WaveStream that returns the raw data + contained in the WAV file + + + + Supports opening a WAV file + The WAV file format is a real mess, but we will only + support the basic WAV file format which actually covers the vast + majority of WAV files out there. For more WAV file format information + visit www.wotsit.org. If you have a WAV file that can't be read by + this class, email it to the NAudio project and we will probably + fix this reader to support it + + + + + Creates a Wave File Reader based on an input stream + + The input stream containing a WAV file including header + + + + Gets a list of the additional chunks found in this file + + + + + Gets the data for the specified chunk + + + + + Cleans up the resources associated with this WaveFileReader + + + + + + + + + + This is the length of audio data contained in this WAV file, in bytes + (i.e. the byte length of the data chunk, not the length of the WAV file itself) + + + + + + Number of Sample Frames (if possible to calculate) + This currently does not take into account number of channels + Multiply number of channels if you want the total number of samples + + + + + Position in the WAV data chunk. + + + + + + Reads bytes from the Wave File + + + + + + Attempts to read the next sample or group of samples as floating point normalised into the range -1.0f to 1.0f + + An array of samples, 1 for mono, 2 for stereo etc. Null indicates end of file reached + + + + + Attempts to read a sample into a float. n.b. only applicable for uncompressed formats + Will normalise the value read into the range -1.0f to 1.0f if it comes from a PCM encoding + + False if the end of the WAV data chunk was reached + + + + IWaveProvider that passes through an ACM Codec + + + + + Create a new WaveFormat conversion stream + + Desired output format + Source Provider + + + + Gets the WaveFormat of this stream + + + + + Indicates that a reposition has taken place, and internal buffers should be reset + + + + + Reads bytes from this stream + + Buffer to read into + Offset in buffer to read into + Number of bytes to read + Number of bytes read + + + + Disposes this stream + + true if the user called this + + + + Disposes this resource + + + + + Finalizer + + + + + WaveStream that passes through an ACM Codec + + + + + Create a new WaveFormat conversion stream + + Desired output format + Source stream + + + + Creates a stream that can convert to PCM + + The source stream + A PCM stream + + + + Gets or sets the current position in the stream + + + + + Converts source bytes to destination bytes + + + + + Converts destination bytes to source bytes + + + + + Returns the stream length + + + + + Gets the WaveFormat of this stream + + + + + + + Buffer to read into + Offset within buffer to write to + Number of bytes to read + Bytes read + + + + Disposes this stream + + true if the user called this + + + + A buffer of Wave samples + + + + + creates a new wavebuffer + + WaveIn device to write to + Buffer size in bytes + + + + Place this buffer back to record more audio + + + + + Finalizer for this wave buffer + + + + + Releases resources held by this WaveBuffer + + + + + Releases resources held by this WaveBuffer + + + + + Provides access to the actual record buffer (for reading only) + + + + + Indicates whether the Done flag is set on this buffer + + + + + Indicates whether the InQueue flag is set on this buffer + + + + + Number of bytes recorded + + + + + The buffer size in bytes + + + + + WaveStream that can mix together multiple 32 bit input streams + (Normally used with stereo input channels) + All channels must have the same number of inputs + + + + + Creates a new 32 bit WaveMixerStream + + + + + Creates a new 32 bit WaveMixerStream + + An Array of WaveStreams - must all have the same format. + Use WaveChannel is designed for this purpose. + Automatically stop when all inputs have been read + Thrown if the input streams are not 32 bit floating point, + or if they have different formats to each other + + + + Add a new input to the mixer + + The wave input to add + + + + Remove a WaveStream from the mixer + + waveStream to remove + + + + The number of inputs to this mixer + + + + + Automatically stop when all inputs have been read + + + + + Reads bytes from this wave stream + + buffer to read into + offset into buffer + number of bytes required + Number of bytes read. + Thrown if an invalid number of bytes requested + + + + Actually performs the mixing + + + + + + + + + + Length of this Wave Stream (in bytes) + + + + + + Position within this Wave Stream (in bytes) + + + + + + + + + + + Disposes this WaveStream + + + + + Simply shifts the input stream in time, optionally + clipping its start and end. + (n.b. may include looping in the future) + + + + + Creates a new WaveOffsetStream + + the source stream + the time at which we should start reading from the source stream + amount to trim off the front of the source stream + length of time to play from source stream + + + + Creates a WaveOffsetStream with default settings (no offset or pre-delay, + and whole length of source stream) + + The source stream + + + + The length of time before which no audio will be played + + + + + An offset into the source stream from which to start playing + + + + + Length of time to read from the source stream + + + + + Gets the block alignment for this WaveStream + + + + + Returns the stream length + + + + + Gets or sets the current position in the stream + + + + + Reads bytes from this wave stream + + The destination buffer + Offset into the destination buffer + Number of bytes read + Number of bytes read. + + + + + + + + + Determines whether this channel has any data to play + to allow optimisation to not read, but bump position forward + + + + + Disposes this WaveStream + + + + + A buffer of Wave samples for streaming to a Wave Output device + + + + + creates a new wavebuffer + + WaveOut device to write to + Buffer size in bytes + Stream to provide more data + Lock to protect WaveOut API's from being called on >1 thread + + + + Finalizer for this wave buffer + + + + + Releases resources held by this WaveBuffer + + + + + Releases resources held by this WaveBuffer + + + + this is called by the WAVE callback and should be used to refill the buffer + + + + Whether the header's in queue flag is set + + + + + The buffer size in bytes + + + + + Base class for all WaveStream classes. Derives from stream. + + + + + Retrieves the WaveFormat for this stream + + + + + We can read from this stream + + + + + We can seek within this stream + + + + + We can't write to this stream + + + + + Flush does not need to do anything + See + + + + + An alternative way of repositioning. + See + + + + + Sets the length of the WaveStream. Not Supported. + + + + + + Writes to the WaveStream. Not Supported. + + + + + The block alignment for this wavestream. Do not modify the Position + to anything that is not a whole multiple of this value + + + + + Moves forward or backwards the specified number of seconds in the stream + + Number of seconds to move, can be negative + + + + The current position in the stream in Time format + + + + + Total length in real-time of the stream (may be an estimate for compressed files) + + + + + Whether the WaveStream has non-zero sample data at the current position for the + specified count + + Number of bytes to read + + + + Contains the name and CLSID of a DirectX Media Object + + + + + Name + + + + + Clsid + + + + + Initializes a new instance of DmoDescriptor + + + + + DirectX Media Object Enumerator + + + + + Get audio effect names + + Audio effect names + + + + Get audio encoder names + + Audio encoder names + + + + Get audio decoder names + + Audio decoder names + + + + DMO Guids for use with DMOEnum + dmoreg.h + + + + + MediaErr.h + + + + + DMO_PARTIAL_MEDIATYPE + + + + + defined in Medparam.h + + + + + Windows Media Resampler Props + wmcodecdsp.h + + + + + Range is 1 to 60 + + + + + Specifies the channel matrix. + + + + + Attempting to implement the COM IMediaBuffer interface as a .NET object + Not sure what will happen when I pass this to an unmanaged object + + + + + Creates a new Media Buffer + + Maximum length in bytes + + + + Dispose and free memory for buffer + + + + + Finalizer + + + + + Set length of valid data in the buffer + + length + HRESULT + + + + Gets the maximum length of the buffer + + Max length (output parameter) + HRESULT + + + + Gets buffer and / or length + + Pointer to variable into which buffer pointer should be written + Pointer to variable into which valid data length should be written + HRESULT + + + + Length of data in the media buffer + + + + + Loads data into this buffer + + Data to load + Number of bytes to load + + + + Retrieves the data in the output buffer + + buffer to retrieve into + offset within that buffer + + + + Media Object + + + + + Creates a new Media Object + + Media Object COM interface + + + + Number of input streams + + + + + Number of output streams + + + + + Gets the input media type for the specified input stream + + Input stream index + Input type index + DMO Media Type or null if there are no more input types + + + + Gets the DMO Media Output type + + The output stream + Output type index + DMO Media Type or null if no more available + + + + retrieves the media type that was set for an output stream, if any + + Output stream index + DMO Media Type or null if no more available + + + + Enumerates the supported input types + + Input stream index + Enumeration of input types + + + + Enumerates the output types + + Output stream index + Enumeration of supported output types + + + + Querys whether a specified input type is supported + + Input stream index + Media type to check + true if supports + + + + Sets the input type helper method + + Input stream index + Media type + Flags (can be used to test rather than set) + + + + Sets the input type + + Input stream index + Media Type + + + + Sets the input type to the specified Wave format + + Input stream index + Wave format + + + + Requests whether the specified Wave format is supported as an input + + Input stream index + Wave format + true if supported + + + + Helper function to make a DMO Media Type to represent a particular WaveFormat + + + + + Checks if a specified output type is supported + n.b. you may need to set the input type first + + Output stream index + Media type + True if supported + + + + Tests if the specified Wave Format is supported for output + n.b. may need to set the input type first + + Output stream index + Wave format + True if supported + + + + Helper method to call SetOutputType + + + + + Sets the output type + n.b. may need to set the input type first + + Output stream index + Media type to set + + + + Set output type to the specified wave format + n.b. may need to set input type first + + Output stream index + Wave format + + + + Get Input Size Info + + Input Stream Index + Input Size Info + + + + Get Output Size Info + + Output Stream Index + Output Size Info + + + + Process Input + + Input Stream index + Media Buffer + Flags + Timestamp + Duration + + + + Process Output + + Flags + Output buffer count + Output buffers + + + + Gives the DMO a chance to allocate any resources needed for streaming + + + + + Tells the DMO to free any resources needed for streaming + + + + + Gets maximum input latency + + input stream index + Maximum input latency as a ref-time + + + + Flushes all buffered data + + + + + Report a discontinuity on the specified input stream + + Input Stream index + + + + Is this input stream accepting data? + + Input Stream index + true if accepting data + + + + Experimental code, not currently being called + Not sure if it is necessary anyway + + + + + Media Object Size Info + + + + + Minimum Buffer Size, in bytes + + + + + Max Lookahead + + + + + Alignment + + + + + Media Object Size Info + + + + + ToString + + + + + MP_PARAMINFO + + + + + MP_TYPE + + + + + MPT_INT + + + + + MPT_FLOAT + + + + + MPT_BOOL + + + + + MPT_ENUM + + + + + MPT_MAX + + + + + MP_CURVE_TYPE + + + + + uuids.h, ksuuids.h + + + + + implements IMediaObject (DirectX Media Object) + implements IMFTransform (Media Foundation Transform) + On Windows XP, it is always an MM (if present at all) + + + + + Windows Media MP3 Decoder (as a DMO) + WORK IN PROGRESS - DO NOT USE! + + + + + Creates a new Resampler based on the DMO Resampler + + + + + Media Object + + + + + Dispose code - experimental at the moment + Was added trying to track down why Resampler crashes NUnit + This code not currently being called by ResamplerDmoStream + + + + + DMO Input Data Buffer Flags + + + + + None + + + + + DMO_INPUT_DATA_BUFFERF_SYNCPOINT + + + + + DMO_INPUT_DATA_BUFFERF_TIME + + + + + DMO_INPUT_DATA_BUFFERF_TIMELENGTH + + + + + http://msdn.microsoft.com/en-us/library/aa929922.aspx + DMO_MEDIA_TYPE + + + + + Major type + + + + + Major type name + + + + + Subtype + + + + + Subtype name + + + + + Fixed size samples + + + + + Sample size + + + + + Format type + + + + + Format type name + + + + + Gets the structure as a Wave format (if it is one) + + + + + Sets this object up to point to a wave format + + Wave format structure + + + + DMO Output Data Buffer + + + + + Creates a new DMO Output Data Buffer structure + + Maximum buffer size + + + + Dispose + + + + + Media Buffer + + + + + Length of data in buffer + + + + + Status Flags + + + + + Timestamp + + + + + Duration + + + + + Retrives the data in this buffer + + Buffer to receive data + Offset into buffer + + + + Is more data available + If true, ProcessOuput should be called again + + + + + DMO Output Data Buffer Flags + + + + + None + + + + + DMO_OUTPUT_DATA_BUFFERF_SYNCPOINT + + + + + DMO_OUTPUT_DATA_BUFFERF_TIME + + + + + DMO_OUTPUT_DATA_BUFFERF_TIMELENGTH + + + + + DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE + + + + + DMO Process Output Flags + + + + + None + + + + + DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER + + + + + IMediaBuffer Interface + + + + + Set Length + + Length + HRESULT + + + + Get Max Length + + Max Length + HRESULT + + + + Get Buffer and Length + + Pointer to variable into which to write the Buffer Pointer + Pointer to variable into which to write the Valid Data Length + HRESULT + + + + defined in mediaobj.h + + + + + From wmcodecsdp.h + Implements: + - IMediaObject + - IMFTransform (Media foundation - we will leave this for now as there is loads of MF stuff) + - IPropertyStore + - IWMResamplerProps + Can resample PCM or IEEE + + + + + DMO Resampler + + + + + Creates a new Resampler based on the DMO Resampler + + + + + Media Object + + + + + Dispose code - experimental at the moment + Was added trying to track down why Resampler crashes NUnit + This code not currently being called by ResamplerDmoStream + + + + + Soundfont generator + + + + + Gets the generator type + + + + + Generator amount as an unsigned short + + + + + Generator amount as a signed short + + + + + Low byte amount + + + + + High byte amount + + + + + Instrument + + + + + Sample Header + + + + + + + + + + Generator types + + + + Start address offset + + + End address offset + + + Start loop address offset + + + End loop address offset + + + Start address coarse offset + + + Modulation LFO to pitch + + + Vibrato LFO to pitch + + + Modulation envelope to pitch + + + Initial filter cutoff frequency + + + Initial filter Q + + + Modulation LFO to filter Cutoff frequency + + + Modulation envelope to filter cutoff frequency + + + End address coarse offset + + + Modulation LFO to volume + + + Unused + + + Chorus effects send + + + Reverb effects send + + + Pan + + + Unused + + + Unused + + + Unused + + + Delay modulation LFO + + + Frequency modulation LFO + + + Delay vibrato LFO + + + Frequency vibrato LFO + + + Delay modulation envelope + + + Attack modulation envelope + + + Hold modulation envelope + + + Decay modulation envelope + + + Sustain modulation envelop + + + Release modulation envelope + + + Key number to modulation envelope hold + + + Key number to modulation envelope decay + + + Delay volume envelope + + + Attack volume envelope + + + Hold volume envelope + + + Decay volume envelope + + + Sustain volume envelope + + + Release volume envelope + + + Key number to volume envelope hold + + + Key number to volume envelope decay + + + Instrument + + + Reserved + + + Key range + + + Velocity range + + + Start loop address coarse offset + + + Key number + + + Velocity + + + Initial attenuation + + + Reserved + + + End loop address coarse offset + + + Coarse tune + + + Fine tune + + + Sample ID + + + Sample modes + + + Reserved + + + Scale tuning + + + Exclusive class + + + Overriding root key + + + Unused + + + Unused + + + + A soundfont info chunk + + + + + SoundFont Version + + + + + WaveTable sound engine + + + + + Bank name + + + + + Data ROM + + + + + Creation Date + + + + + Author + + + + + Target Product + + + + + Copyright + + + + + Comments + + + + + Tools + + + + + ROM Version + + + + + + + + + + SoundFont instrument + + + + + instrument name + + + + + Zones + + + + + + + + + + Instrument Builder + + + + + Transform Types + + + + + Linear + + + + + Modulator + + + + + Source Modulation data type + + + + + Destination generator type + + + + + Amount + + + + + Source Modulation Amount Type + + + + + Source Transform Type + + + + + + + + + + Controller Sources + + + + + No Controller + + + + + Note On Velocity + + + + + Note On Key Number + + + + + Poly Pressure + + + + + Channel Pressure + + + + + Pitch Wheel + + + + + Pitch Wheel Sensitivity + + + + + Source Types + + + + + Linear + + + + + Concave + + + + + Convex + + + + + Switch + + + + + Modulator Type + + + + + + + + + + + A SoundFont Preset + + + + + Preset name + + + + + Patch Number + + + + + Bank number + + + + + Zones + + + + + + + + + + Class to read the SoundFont file presets chunk + + + + + The Presets contained in this chunk + + + + + The instruments contained in this chunk + + + + + The sample headers contained in this chunk + + + + + + + + + + just reads a chunk ID at the current position + + chunk ID + + + + reads a chunk at the current position + + + + + creates a new riffchunk from current position checking that we're not + at the end of this chunk first + + the new chunk + + + + useful for chunks that just contain a string + + chunk as string + + + + A SoundFont Sample Header + + + + + The sample name + + + + + Start offset + + + + + End offset + + + + + Start loop point + + + + + End loop point + + + + + Sample Rate + + + + + Original pitch + + + + + Pitch correction + + + + + Sample Link + + + + + SoundFont Sample Link Type + + + + + + + + + + SoundFont sample modes + + + + + No loop + + + + + Loop Continuously + + + + + Reserved no loop + + + + + Loop and continue + + + + + Sample Link Type + + + + + Mono Sample + + + + + Right Sample + + + + + Left Sample + + + + + Linked Sample + + + + + ROM Mono Sample + + + + + ROM Right Sample + + + + + ROM Left Sample + + + + + ROM Linked Sample + + + + + SoundFont Version Structure + + + + + Major Version + + + + + Minor Version + + + + + Builds a SoundFont version + + + + + Reads a SoundFont Version structure + + + + + Writes a SoundFont Version structure + + + + + Gets the length of this structure + + + + + Represents a SoundFont + + + + + Loads a SoundFont from a file + + Filename of the SoundFont + + + + Loads a SoundFont from a stream + + stream + + + + The File Info Chunk + + + + + The Presets + + + + + The Instruments + + + + + The Sample Headers + + + + + The Sample Data + + + + + + + + + + base class for structures that can read themselves + + + + + A SoundFont zone + + + + + + + + + + Modulators for this Zone + + + + + Generators for this Zone + + + + + Summary description for Fader. + + + + + Required designer variable. + + + + + Creates a new Fader control + + + + + Clean up any resources being used. + + + + + + + + + + + + + + + + + + + + + + + + + Minimum value of this fader + + + + + Maximum value of this fader + + + + + Current value of this fader + + + + + Fader orientation + + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + Pan slider control + + + + + Required designer variable. + + + + + True when pan value changed + + + + + Creates a new PanSlider control + + + + + Clean up any resources being used. + + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + + + + + + + + + + + + + + + + + The current Pan setting + + + + + Control that represents a potentiometer + TODO list: + Optional Log scale + Optional reverse scale + Keyboard control + Optional bitmap mode + Optional complete draw mode + Tooltip support + + + + + Value changed event + + + + + Creates a new pot control + + + + + Minimum Value of the Pot + + + + + Maximum Value of the Pot + + + + + The current value of the pot + + + + + Draws the control + + + + + Handles the mouse down event to allow changing value by dragging + + + + + Handles the mouse up event to allow changing value by dragging + + + + + Handles the mouse down event to allow changing value by dragging + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + Implements a rudimentary volume meter + + + + + Basic volume meter + + + + + On Fore Color Changed + + + + + Current Value + + + + + Minimum decibels + + + + + Maximum decibels + + + + + Meter orientation + + + + + Paints the volume meter + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + VolumeSlider control + + + + + Required designer variable. + + + + + Volume changed event + + + + + Creates a new VolumeSlider control + + + + + Clean up any resources being used. + + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + + + + + + + + + + + + + + + + The volume for this control + + + + + Windows Forms control for painting audio waveforms + + + + + Constructs a new instance of the WaveFormPainter class + + + + + On Resize + + + + + On ForeColor Changed + + + + + + Add Max Value + + + + + + On Paint + + + + + Required designer variable. + + + + + Clean up any resources being used. + + true if managed resources should be disposed; otherwise, false. + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + Control for viewing waveforms + + + + + Required designer variable. + + + + + Creates a new WaveViewer control + + + + + sets the associated wavestream + + + + + The zoom level, in samples per pixel + + + + + Start position (currently in bytes) + + + + + Clean up any resources being used. + + + + + + + + + + Required method for Designer support - do not modify + the contents of this method with the code editor. + + + + + Boolean mixer control + + + + + Gets the details for this control + + memory pointer + + + + The current value of the control + + + + + Custom Mixer control + + + + + Get the data for this custom control + + pointer to memory to receive data + + + + List text mixer control + + + + + Get the details for this control + + Memory location to read to + + + Represents a Windows mixer device + + + The number of mixer devices available + + + Connects to the specified mixer + The index of the mixer to use. + This should be between zero and NumberOfDevices - 1 + + + The number of destinations this mixer supports + + + The name of this mixer device + + + The manufacturer code for this mixer device + + + The product identifier code for this mixer device + + + Retrieve the specified MixerDestination object + The ID of the destination to use. + Should be between 0 and DestinationCount - 1 + + + + A way to enumerate the destinations + + + + + A way to enumerate all available devices + + + + + Represents a mixer control + + + + + Mixer Handle + + + + + Number of Channels + + + + + Mixer Handle Type + + + + + Gets all the mixer controls + + Mixer Handle + Mixer Line + Mixer Handle Type + + + + + Gets a specified Mixer Control + + Mixer Handle + Line ID + Control ID + Number of Channels + Flags to use (indicates the meaning of mixerHandle) + + + + + Gets the control details + + + + + Gets the control details + + + + + + Mixer control name + + + + + Mixer control type + + + + + Returns true if this is a boolean control + + Control type + + + + Is this a boolean control + + + + + Determines whether a specified mixer control type is a list text control + + + + + True if this is a list text control + + + + + True if this is a signed control + + + + + True if this is an unsigned control + + + + + True if this is a custom control + + + + + String representation for debug purposes + + + + + Mixer control types + + + + Custom + + + Boolean meter + + + Signed meter + + + Peak meter + + + Unsigned meter + + + Boolean + + + On Off + + + Mute + + + Mono + + + Loudness + + + Stereo Enhance + + + Button + + + Decibels + + + Signed + + + Unsigned + + + Percent + + + Slider + + + Pan + + + Q-sound pan + + + Fader + + + Volume + + + Bass + + + Treble + + + Equaliser + + + Single Select + + + Mux + + + Multiple select + + + Mixer + + + Micro time + + + Milli time + + + + Represents a mixer line (source or destination) + + + + + Creates a new mixer destination + + Mixer Handle + Destination Index + Mixer Handle Type + + + + Creates a new Mixer Source For a Specified Source + + Mixer Handle + Destination Index + Source Index + Flag indicating the meaning of mixerHandle + + + + Creates a new Mixer Source + + Wave In Device + + + + Mixer Line Name + + + + + Mixer Line short name + + + + + The line ID + + + + + Component Type + + + + + Mixer destination type description + + + + + Number of channels + + + + + Number of sources + + + + + Number of controls + + + + + Is this destination active + + + + + Is this destination disconnected + + + + + Is this destination a source + + + + + Gets the specified source + + + + + Enumerator for the controls on this Mixer Limne + + + + + Enumerator for the sources on this Mixer Line + + + + + The name of the target output device + + + + + Describes this Mixer Line (for diagnostic purposes) + + + + + Mixer Interop Flags + + + + + MIXER_OBJECTF_HANDLE = 0x80000000; + + + + + MIXER_OBJECTF_MIXER = 0x00000000; + + + + + MIXER_OBJECTF_HMIXER + + + + + MIXER_OBJECTF_WAVEOUT + + + + + MIXER_OBJECTF_HWAVEOUT + + + + + MIXER_OBJECTF_WAVEIN + + + + + MIXER_OBJECTF_HWAVEIN + + + + + MIXER_OBJECTF_MIDIOUT + + + + + MIXER_OBJECTF_HMIDIOUT + + + + + MIXER_OBJECTF_MIDIIN + + + + + MIXER_OBJECTF_HMIDIIN + + + + + MIXER_OBJECTF_AUX + + + + + MIXER_GETCONTROLDETAILSF_VALUE = 0x00000000; + MIXER_SETCONTROLDETAILSF_VALUE = 0x00000000; + + + + + MIXER_GETCONTROLDETAILSF_LISTTEXT = 0x00000001; + MIXER_SETCONTROLDETAILSF_LISTTEXT = 0x00000001; + + + + + MIXER_GETCONTROLDETAILSF_QUERYMASK = 0x0000000F; + MIXER_SETCONTROLDETAILSF_QUERYMASK = 0x0000000F; + MIXER_GETLINECONTROLSF_QUERYMASK = 0x0000000F; + + + + + MIXER_GETLINECONTROLSF_ALL = 0x00000000; + + + + + MIXER_GETLINECONTROLSF_ONEBYID = 0x00000001; + + + + + MIXER_GETLINECONTROLSF_ONEBYTYPE = 0x00000002; + + + + + MIXER_GETLINEINFOF_DESTINATION = 0x00000000; + + + + + MIXER_GETLINEINFOF_SOURCE = 0x00000001; + + + + + MIXER_GETLINEINFOF_LINEID = 0x00000002; + + + + + MIXER_GETLINEINFOF_COMPONENTTYPE = 0x00000003; + + + + + MIXER_GETLINEINFOF_TARGETTYPE = 0x00000004; + + + + + MIXER_GETLINEINFOF_QUERYMASK = 0x0000000F; + + + + + Mixer Line Flags + + + + + Audio line is active. An active line indicates that a signal is probably passing + through the line. + + + + + Audio line is disconnected. A disconnected line's associated controls can still be + modified, but the changes have no effect until the line is connected. + + + + + Audio line is an audio source line associated with a single audio destination line. + If this flag is not set, this line is an audio destination line associated with zero + or more audio source lines. + + + + + BOUNDS structure + + + + + dwMinimum / lMinimum / reserved 0 + + + + + dwMaximum / lMaximum / reserved 1 + + + + + reserved 2 + + + + + reserved 3 + + + + + reserved 4 + + + + + reserved 5 + + + + + METRICS structure + + + + + cSteps / reserved[0] + + + + + cbCustomData / reserved[1], number of bytes for control details + + + + + reserved 2 + + + + + reserved 3 + + + + + reserved 4 + + + + + reserved 5 + + + + + MIXERCONTROL struct + http://msdn.microsoft.com/en-us/library/dd757293%28VS.85%29.aspx + + + + + Mixer Line Component type enumeration + + + + + Audio line is a destination that cannot be defined by one of the standard component types. A mixer device is required to use this component type for line component types that have not been defined by Microsoft Corporation. + MIXERLINE_COMPONENTTYPE_DST_UNDEFINED + + + + + Audio line is a digital destination (for example, digital input to a DAT or CD audio device). + MIXERLINE_COMPONENTTYPE_DST_DIGITAL + + + + + Audio line is a line level destination (for example, line level input from a CD audio device) that will be the final recording source for the analog-to-digital converter (ADC). Because most audio cards for personal computers provide some sort of gain for the recording audio source line, the mixer device will use the MIXERLINE_COMPONENTTYPE_DST_WAVEIN type. + MIXERLINE_COMPONENTTYPE_DST_LINE + + + + + Audio line is a destination used for a monitor. + MIXERLINE_COMPONENTTYPE_DST_MONITOR + + + + + Audio line is an adjustable (gain and/or attenuation) destination intended to drive speakers. This is the typical component type for the audio output of audio cards for personal computers. + MIXERLINE_COMPONENTTYPE_DST_SPEAKERS + + + + + Audio line is an adjustable (gain and/or attenuation) destination intended to drive headphones. Most audio cards use the same audio destination line for speakers and headphones, in which case the mixer device simply uses the MIXERLINE_COMPONENTTYPE_DST_SPEAKERS type. + MIXERLINE_COMPONENTTYPE_DST_HEADPHONES + + + + + Audio line is a destination that will be routed to a telephone line. + MIXERLINE_COMPONENTTYPE_DST_TELEPHONE + + + + + Audio line is a destination that will be the final recording source for the waveform-audio input (ADC). This line typically provides some sort of gain or attenuation. This is the typical component type for the recording line of most audio cards for personal computers. + MIXERLINE_COMPONENTTYPE_DST_WAVEIN + + + + + Audio line is a destination that will be the final recording source for voice input. This component type is exactly like MIXERLINE_COMPONENTTYPE_DST_WAVEIN but is intended specifically for settings used during voice recording/recognition. Support for this line is optional for a mixer device. Many mixer devices provide only MIXERLINE_COMPONENTTYPE_DST_WAVEIN. + MIXERLINE_COMPONENTTYPE_DST_VOICEIN + + + + + Audio line is a source that cannot be defined by one of the standard component types. A mixer device is required to use this component type for line component types that have not been defined by Microsoft Corporation. + MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED + + + + + Audio line is a digital source (for example, digital output from a DAT or audio CD). + MIXERLINE_COMPONENTTYPE_SRC_DIGITAL + + + + + Audio line is a line-level source (for example, line-level input from an external stereo) that can be used as an optional recording source. Because most audio cards for personal computers provide some sort of gain for the recording source line, the mixer device will use the MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY type. + MIXERLINE_COMPONENTTYPE_SRC_LINE + + + + + Audio line is a microphone recording source. Most audio cards for personal computers provide at least two types of recording sources: an auxiliary audio line and microphone input. A microphone audio line typically provides some sort of gain. Audio cards that use a single input for use with a microphone or auxiliary audio line should use the MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE component type. + MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE + + + + + Audio line is a source originating from the output of an internal synthesizer. Most audio cards for personal computers provide some sort of MIDI synthesizer (for example, an Adlib®-compatible or OPL/3 FM synthesizer). + MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER + + + + + Audio line is a source originating from the output of an internal audio CD. This component type is provided for audio cards that provide an audio source line intended to be connected to an audio CD (or CD-ROM playing an audio CD). + MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC + + + + + Audio line is a source originating from an incoming telephone line. + MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE + + + + + Audio line is a source originating from personal computer speaker. Several audio cards for personal computers provide the ability to mix what would typically be played on the internal speaker with the output of an audio card. Some audio cards support the ability to use this output as a recording source. + MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER + + + + + Audio line is a source originating from the waveform-audio output digital-to-analog converter (DAC). Most audio cards for personal computers provide this component type as a source to the MIXERLINE_COMPONENTTYPE_DST_SPEAKERS destination. Some cards also allow this source to be routed to the MIXERLINE_COMPONENTTYPE_DST_WAVEIN destination. + MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT + + + + + Audio line is a source originating from the auxiliary audio line. This line type is intended as a source with gain or attenuation that can be routed to the MIXERLINE_COMPONENTTYPE_DST_SPEAKERS destination and/or recorded from the MIXERLINE_COMPONENTTYPE_DST_WAVEIN destination. + MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY + + + + + Audio line is an analog source (for example, analog output from a video-cassette tape). + MIXERLINE_COMPONENTTYPE_SRC_ANALOG + + + + + Represents a signed mixer control + + + + + Gets details for this contrl + + + + + The value of the control + + + + + Minimum value for this control + + + + + Maximum value for this control + + + + + Value of the control represented as a percentage + + + + + String Representation for debugging purposes + + + + + + Represents an unsigned mixer control + + + + + Gets the details for this control + + + + + The control value + + + + + The control's minimum value + + + + + The control's maximum value + + + + + Value of the control represented as a percentage + + + + + String Representation for debugging purposes + + + + + Manufacturer codes from mmreg.h + + + + Microsoft Corporation + + + Creative Labs, Inc + + + Media Vision, Inc. + + + Fujitsu Corp. + + + Artisoft, Inc. + + + Turtle Beach, Inc. + + + IBM Corporation + + + Vocaltec LTD. + + + Roland + + + DSP Solutions, Inc. + + + NEC + + + ATI + + + Wang Laboratories, Inc + + + Tandy Corporation + + + Voyetra + + + Antex Electronics Corporation + + + ICL Personal Systems + + + Intel Corporation + + + Advanced Gravis + + + Video Associates Labs, Inc. + + + InterActive Inc + + + Yamaha Corporation of America + + + Everex Systems, Inc + + + Echo Speech Corporation + + + Sierra Semiconductor Corp + + + Computer Aided Technologies + + + APPS Software International + + + DSP Group, Inc + + + microEngineering Labs + + + Computer Friends, Inc. + + + ESS Technology + + + Audio, Inc. + + + Motorola, Inc. + + + Canopus, co., Ltd. + + + Seiko Epson Corporation + + + Truevision + + + Aztech Labs, Inc. + + + Videologic + + + SCALACS + + + Korg Inc. + + + Audio Processing Technology + + + Integrated Circuit Systems, Inc. + + + Iterated Systems, Inc. + + + Metheus + + + Logitech, Inc. + + + Winnov, Inc. + + + NCR Corporation + + + EXAN + + + AST Research Inc. + + + Willow Pond Corporation + + + Sonic Foundry + + + Vitec Multimedia + + + MOSCOM Corporation + + + Silicon Soft, Inc. + + + Supermac + + + Audio Processing Technology + + + Speech Compression + + + Ahead, Inc. + + + Dolby Laboratories + + + OKI + + + AuraVision Corporation + + + Ing C. Olivetti & C., S.p.A. + + + I/O Magic Corporation + + + Matsushita Electric Industrial Co., LTD. + + + Control Resources Limited + + + Xebec Multimedia Solutions Limited + + + New Media Corporation + + + Natural MicroSystems + + + Lyrrus Inc. + + + Compusic + + + OPTi Computers Inc. + + + Adlib Accessories Inc. + + + Compaq Computer Corp. + + + Dialogic Corporation + + + InSoft, Inc. + + + M.P. Technologies, Inc. + + + Weitek + + + Lernout & Hauspie + + + Quanta Computer Inc. + + + Apple Computer, Inc. + + + Digital Equipment Corporation + + + Mark of the Unicorn + + + Workbit Corporation + + + Ositech Communications Inc. + + + miro Computer Products AG + + + Cirrus Logic + + + ISOLUTION B.V. + + + Horizons Technology, Inc + + + Computer Concepts Ltd + + + Voice Technologies Group, Inc. + + + Radius + + + Rockwell International + + + Co. XYZ for testing + + + Opcode Systems + + + Voxware Inc + + + Northern Telecom Limited + + + APICOM + + + Grande Software + + + ADDX + + + Wildcat Canyon Software + + + Rhetorex Inc + + + Brooktree Corporation + + + ENSONIQ Corporation + + + FAST Multimedia AG + + + NVidia Corporation + + + OKSORI Co., Ltd. + + + DiAcoustics, Inc. + + + Gulbransen, Inc. + + + Kay Elemetrics, Inc. + + + Crystal Semiconductor Corporation + + + Splash Studios + + + Quarterdeck Corporation + + + TDK Corporation + + + Digital Audio Labs, Inc. + + + Seer Systems, Inc. + + + PictureTel Corporation + + + AT&T Microelectronics + + + Osprey Technologies, Inc. + + + Mediatrix Peripherals + + + SounDesignS M.C.S. Ltd. + + + A.L. Digital Ltd. + + + Spectrum Signal Processing, Inc. + + + Electronic Courseware Systems, Inc. + + + AMD + + + Core Dynamics + + + CANAM Computers + + + Softsound, Ltd. + + + Norris Communications, Inc. + + + Danka Data Devices + + + EuPhonics + + + Precept Software, Inc. + + + Crystal Net Corporation + + + Chromatic Research, Inc + + + Voice Information Systems, Inc + + + Vienna Systems + + + Connectix Corporation + + + Gadget Labs LLC + + + Frontier Design Group LLC + + + Viona Development GmbH + + + Casio Computer Co., LTD + + + Diamond Multimedia + + + S3 + + + Fraunhofer + + + + Summary description for MmException. + + + + + Creates a new MmException + + The result returned by the Windows API call + The name of the Windows API that failed + + + + Helper function to automatically raise an exception on failure + + The result of the API call + The API function name + + + + Returns the Windows API result + + + + + Windows multimedia error codes from mmsystem.h. + + + + no error, MMSYSERR_NOERROR + + + unspecified error, MMSYSERR_ERROR + + + device ID out of range, MMSYSERR_BADDEVICEID + + + driver failed enable, MMSYSERR_NOTENABLED + + + device already allocated, MMSYSERR_ALLOCATED + + + device handle is invalid, MMSYSERR_INVALHANDLE + + + no device driver present, MMSYSERR_NODRIVER + + + memory allocation error, MMSYSERR_NOMEM + + + function isn't supported, MMSYSERR_NOTSUPPORTED + + + error value out of range, MMSYSERR_BADERRNUM + + + invalid flag passed, MMSYSERR_INVALFLAG + + + invalid parameter passed, MMSYSERR_INVALPARAM + + + handle being used simultaneously on another thread (eg callback),MMSYSERR_HANDLEBUSY + + + specified alias not found, MMSYSERR_INVALIDALIAS + + + bad registry database, MMSYSERR_BADDB + + + registry key not found, MMSYSERR_KEYNOTFOUND + + + registry read error, MMSYSERR_READERROR + + + registry write error, MMSYSERR_WRITEERROR + + + registry delete error, MMSYSERR_DELETEERROR + + + registry value not found, MMSYSERR_VALNOTFOUND + + + driver does not call DriverCallback, MMSYSERR_NODRIVERCB + + + more data to be returned, MMSYSERR_MOREDATA + + + unsupported wave format, WAVERR_BADFORMAT + + + still something playing, WAVERR_STILLPLAYING + + + header not prepared, WAVERR_UNPREPARED + + + device is synchronous, WAVERR_SYNC + + + Conversion not possible (ACMERR_NOTPOSSIBLE) + + + Busy (ACMERR_BUSY) + + + Header Unprepared (ACMERR_UNPREPARED) + + + Cancelled (ACMERR_CANCELED) + + + invalid line (MIXERR_INVALLINE) + + + invalid control (MIXERR_INVALCONTROL) + + + invalid value (MIXERR_INVALVALUE) + + + diff --git a/Assets/Plugins/NAudio.xml.meta b/Assets/Plugins/NAudio.xml.meta new file mode 100644 index 000000000..d5fe16955 --- /dev/null +++ b/Assets/Plugins/NAudio.xml.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 148c2387ff68be74487ccf4c82879475 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis.meta b/Assets/Plugins/NVorbis.meta new file mode 100644 index 000000000..2e5ce49e0 --- /dev/null +++ b/Assets/Plugins/NVorbis.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 65c6ff6cdedbf774a95a537a6d87bf2e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Codebook.cs b/Assets/Plugins/NVorbis/Codebook.cs new file mode 100644 index 000000000..bc2643a3c --- /dev/null +++ b/Assets/Plugins/NVorbis/Codebook.cs @@ -0,0 +1,330 @@ +using NVorbis.Contracts; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; + +namespace NVorbis +{ + class Codebook : ICodebook + { + // FastRange is "borrowed" from GitHub: TechnologicalPizza/MonoGame.NVorbis + class FastRange : IReadOnlyList + { + [ThreadStatic] + static FastRange _cachedRange; + + internal static FastRange Get(int start, int count) + { + var fr = _cachedRange ?? (_cachedRange = new FastRange()); + fr._start = start; + fr._count = count; + return fr; + } + + int _start; + int _count; + + private FastRange() { } + + public int this[int index] + { + get + { + if (index > _count) throw new ArgumentOutOfRangeException(); + return _start + index; + } + } + + public int Count => _count; + + public IEnumerator GetEnumerator() + { + throw new NotSupportedException(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + int[] _lengths; + float[] _lookupTable; + IReadOnlyList _overflowList; + IReadOnlyList _prefixList; + int _prefixBitLength; + int _maxBits; + + public void Init(IPacket packet, IHuffman huffman) + { + // first, check the sync pattern + var chkVal = packet.ReadBits(24); + if (chkVal != 0x564342UL) throw new InvalidDataException("Book header had invalid signature!"); + + // get the counts + Dimensions = (int)packet.ReadBits(16); + Entries = (int)packet.ReadBits(24); + + // init the storage + _lengths = new int[Entries]; + + InitTree(packet, huffman); + InitLookupTable(packet); + } + + private void InitTree(IPacket packet, IHuffman huffman) + { + bool sparse; + int total = 0; + + int maxLen; + if (packet.ReadBit()) + { + // ordered + var len = (int)packet.ReadBits(5) + 1; + for (var i = 0; i < Entries;) + { + var cnt = (int)packet.ReadBits(Utils.ilog(Entries - i)); + + while (--cnt >= 0) + { + _lengths[i++] = len; + } + + ++len; + } + total = 0; + sparse = false; + maxLen = len; + } + else + { + // unordered + maxLen = -1; + sparse = packet.ReadBit(); + for (var i = 0; i < Entries; i++) + { + if (!sparse || packet.ReadBit()) + { + _lengths[i] = (int)packet.ReadBits(5) + 1; + ++total; + } + else + { + // mark the entry as unused + _lengths[i] = -1; + } + if (_lengths[i] > maxLen) + { + maxLen = _lengths[i]; + } + } + } + + // figure out the maximum bit size; if all are unused, don't do anything else + if ((_maxBits = maxLen) > -1) + { + int[] codewordLengths = null; + if (sparse && total >= Entries >> 2) + { + codewordLengths = new int[Entries]; + Array.Copy(_lengths, codewordLengths, Entries); + + sparse = false; + } + + int sortedCount; + // compute size of sorted tables + if (sparse) + { + sortedCount = total; + } + else + { + sortedCount = 0; + } + + int[] values = null; + int[] codewords = null; + if (!sparse) + { + codewords = new int[Entries]; + } + else if (sortedCount != 0) + { + codewordLengths = new int[sortedCount]; + codewords = new int[sortedCount]; + values = new int[sortedCount]; + } + + if (!ComputeCodewords(sparse, codewords, codewordLengths, _lengths, Entries, values)) throw new InvalidDataException(); + + var valueList = (IReadOnlyList)values ?? FastRange.Get(0, codewords.Length); + + huffman.GenerateTable(valueList, codewordLengths ?? _lengths, codewords); + _prefixList = huffman.PrefixTree; + _prefixBitLength = huffman.TableBits; + _overflowList = huffman.OverflowList; + } + } + + bool ComputeCodewords(bool sparse, int[] codewords, int[] codewordLengths, int[] len, int n, int[] values) + { + int i, k, m = 0; + uint[] available = new uint[32]; + + for (k = 0; k < n; ++k) if (len[k] > 0) break; + if (k == n) return true; + + AddEntry(sparse, codewords, codewordLengths, 0, k, m++, len[k], values); + + for (i = 1; i <= len[k]; ++i) available[i] = 1U << (32 - i); + + for (i = k + 1; i < n; ++i) + { + uint res; + int z = len[i], y; + if (z <= 0) continue; + + while (z > 0 && available[z] == 0) --z; + if (z == 0) return false; + res = available[z]; + available[z] = 0; + AddEntry(sparse, codewords, codewordLengths, Utils.BitReverse(res), i, m++, len[i], values); + + if (z != len[i]) + { + for (y = len[i]; y > z; --y) + { + available[y] = res + (1U << (32 - y)); + } + } + } + + return true; + } + + void AddEntry(bool sparse, int[] codewords, int[] codewordLengths, uint huffCode, int symbol, int count, int len, int[] values) + { + if (sparse) + { + codewords[count] = (int)huffCode; + codewordLengths[count] = len; + values[count] = symbol; + } + else + { + codewords[symbol] = (int)huffCode; + } + } + + private void InitLookupTable(IPacket packet) + { + MapType = (int)packet.ReadBits(4); + if (MapType == 0) return; + + var minValue = Utils.ConvertFromVorbisFloat32((uint)packet.ReadBits(32)); + var deltaValue = Utils.ConvertFromVorbisFloat32((uint)packet.ReadBits(32)); + var valueBits = (int)packet.ReadBits(4) + 1; + var sequence_p = packet.ReadBit(); + + var lookupValueCount = Entries * Dimensions; + var lookupTable = new float[lookupValueCount]; + if (MapType == 1) + { + lookupValueCount = lookup1_values(); + } + + var multiplicands = new uint[lookupValueCount]; + for (var i = 0; i < lookupValueCount; i++) + { + multiplicands[i] = (uint)packet.ReadBits(valueBits); + } + + // now that we have the initial data read in, calculate the entry tree + if (MapType == 1) + { + for (var idx = 0; idx < Entries; idx++) + { + var last = 0.0; + var idxDiv = 1; + for (var i = 0; i < Dimensions; i++) + { + var moff = (idx / idxDiv) % lookupValueCount; + var value = (float)multiplicands[moff] * deltaValue + minValue + last; + lookupTable[idx * Dimensions + i] = (float)value; + + if (sequence_p) last = value; + + idxDiv *= lookupValueCount; + } + } + } + else + { + for (var idx = 0; idx < Entries; idx++) + { + var last = 0.0; + var moff = idx * Dimensions; + for (var i = 0; i < Dimensions; i++) + { + var value = multiplicands[moff] * deltaValue + minValue + last; + lookupTable[idx * Dimensions + i] = (float)value; + + if (sequence_p) last = value; + + ++moff; + } + } + } + + _lookupTable = lookupTable; + } + + int lookup1_values() + { + var r = (int)Math.Floor(Math.Exp(Math.Log(Entries) / Dimensions)); + + if (Math.Floor(Math.Pow(r + 1, Dimensions)) <= Entries) ++r; + + return r; + } + + public int DecodeScalar(IPacket packet) + { + var data = (int)packet.TryPeekBits(_prefixBitLength, out var bitsRead); + if (bitsRead == 0) return -1; + + // try to get the value from the prefix list... + var node = _prefixList[data]; + if (node != null) + { + packet.SkipBits(node.Length); + return node.Value; + } + + // nope, not possible... run through the overflow nodes + data = (int)packet.TryPeekBits(_maxBits, out _); + + for (var i = 0; i < _overflowList.Count; i++) + { + node = _overflowList[i]; + if (node.Bits == (data & node.Mask)) + { + packet.SkipBits(node.Length); + return node.Value; + } + } + return -1; + } + + public float this[int entry, int dim] => _lookupTable[entry * Dimensions + dim]; + + public int Dimensions { get; private set; } + + public int Entries { get; private set; } + + public int MapType { get; private set; } + } +} diff --git a/Assets/Plugins/NVorbis/Codebook.cs.meta b/Assets/Plugins/NVorbis/Codebook.cs.meta new file mode 100644 index 000000000..4a6899f11 --- /dev/null +++ b/Assets/Plugins/NVorbis/Codebook.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e28289d1443bba04cb21ddf6372b8f51 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts.meta b/Assets/Plugins/NVorbis/Contracts.meta new file mode 100644 index 000000000..3be7a331b --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1a5ab9635458ac04f99a1dc73f995ae5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/HuffmanListNode.cs b/Assets/Plugins/NVorbis/Contracts/HuffmanListNode.cs new file mode 100644 index 000000000..ec441dbbe --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/HuffmanListNode.cs @@ -0,0 +1,11 @@ +namespace NVorbis.Contracts +{ + class HuffmanListNode + { + internal int Value; + + internal int Length; + internal int Bits; + internal int Mask; + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/HuffmanListNode.cs.meta b/Assets/Plugins/NVorbis/Contracts/HuffmanListNode.cs.meta new file mode 100644 index 000000000..6d922cb28 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/HuffmanListNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc2afc015b1a04542ba4909a6f6e89a2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/ICodebook.cs b/Assets/Plugins/NVorbis/Contracts/ICodebook.cs new file mode 100644 index 000000000..379f13f03 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/ICodebook.cs @@ -0,0 +1,15 @@ +namespace NVorbis.Contracts +{ + interface ICodebook + { + void Init(IPacket packet, IHuffman huffman); + + int Dimensions { get; } + int Entries { get; } + int MapType { get; } + + float this[int entry, int dim] { get; } + + int DecodeScalar(IPacket packet); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/ICodebook.cs.meta b/Assets/Plugins/NVorbis/Contracts/ICodebook.cs.meta new file mode 100644 index 000000000..b3ec8e053 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/ICodebook.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 15acce2c276561d468f297c351e017df +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IContainerReader.cs b/Assets/Plugins/NVorbis/Contracts/IContainerReader.cs new file mode 100644 index 000000000..c008d353e --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IContainerReader.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; + +namespace NVorbis.Contracts +{ + /// + /// Encapsulates a method that initializes a stream reader, optionally ignoring the stream if desired. + /// + /// The instance for the new stream. + /// to process the stream, otherwise . + public delegate bool NewStreamHandler(IPacketProvider packetProvider); + + /// + /// Provides an interface for a Vorbis logical stream container. + /// + public interface IContainerReader : IDisposable + { + /// + /// Gets or sets the callback to invoke when a new stream is encountered in the container. + /// + NewStreamHandler NewStreamCallback { get; set; } + + /// + /// Returns a read-only list of the logical streams discovered in this container. + /// + IReadOnlyList GetStreams(); + + /// + /// Gets whether the underlying stream can seek. + /// + bool CanSeek { get; } + + /// + /// Gets the number of bits dedicated to container framing and overhead. + /// + long ContainerBits { get; } + + /// + /// Gets the number of bits that were skipped due to container framing and overhead. + /// + long WasteBits { get; } + + /// + /// Attempts to initialize the container. + /// + /// if successful, otherwise . + bool TryInit(); + + /// + /// Searches for the next logical stream in the container. + /// + /// if a new stream was found, otherwise . + bool FindNextStream(); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IContainerReader.cs.meta b/Assets/Plugins/NVorbis/Contracts/IContainerReader.cs.meta new file mode 100644 index 000000000..5a2fa8537 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IContainerReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 67c1f11cce678654f81b42eb860cb38a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IFactory.cs b/Assets/Plugins/NVorbis/Contracts/IFactory.cs new file mode 100644 index 000000000..39753bbc7 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IFactory.cs @@ -0,0 +1,13 @@ +namespace NVorbis.Contracts +{ + interface IFactory + { + ICodebook CreateCodebook(); + IFloor CreateFloor(IPacket packet); + IResidue CreateResidue(IPacket packet); + IMapping CreateMapping(IPacket packet); + IMode CreateMode(); + IMdct CreateMdct(); + IHuffman CreateHuffman(); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IFactory.cs.meta b/Assets/Plugins/NVorbis/Contracts/IFactory.cs.meta new file mode 100644 index 000000000..11b19f00f --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 60dcecc2e9be68646bf03b92fb15dfc6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IFloor.cs b/Assets/Plugins/NVorbis/Contracts/IFloor.cs new file mode 100644 index 000000000..8023aecd3 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IFloor.cs @@ -0,0 +1,11 @@ +namespace NVorbis.Contracts +{ + interface IFloor + { + void Init(IPacket packet, int channels, int block0Size, int block1Size, ICodebook[] codebooks); + + IFloorData Unpack(IPacket packet, int blockSize, int channel); + + void Apply(IFloorData floorData, int blockSize, float[] residue); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IFloor.cs.meta b/Assets/Plugins/NVorbis/Contracts/IFloor.cs.meta new file mode 100644 index 000000000..3de19d116 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IFloor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ac1cd38f1a3a28e47aaf539ab47cc654 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IFloorData.cs b/Assets/Plugins/NVorbis/Contracts/IFloorData.cs new file mode 100644 index 000000000..a6f8eb503 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IFloorData.cs @@ -0,0 +1,9 @@ +namespace NVorbis.Contracts +{ + interface IFloorData + { + bool ExecuteChannel { get; } + bool ForceEnergy { get; set; } + bool ForceNoEnergy { get; set; } + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IFloorData.cs.meta b/Assets/Plugins/NVorbis/Contracts/IFloorData.cs.meta new file mode 100644 index 000000000..0cde54b67 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IFloorData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6bd195e107deeab4db7939f12d463920 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IHuffman.cs b/Assets/Plugins/NVorbis/Contracts/IHuffman.cs new file mode 100644 index 000000000..7c7dc6d85 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IHuffman.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; + +namespace NVorbis.Contracts +{ + interface IHuffman + { + int TableBits { get; } + IReadOnlyList PrefixTree { get; } + IReadOnlyList OverflowList { get; } + + void GenerateTable(IReadOnlyList value, int[] lengthList, int[] codeList); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IHuffman.cs.meta b/Assets/Plugins/NVorbis/Contracts/IHuffman.cs.meta new file mode 100644 index 000000000..83141035d --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IHuffman.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cd99bd8f3307c4949a9c0d9ba5bd09fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IMapping.cs b/Assets/Plugins/NVorbis/Contracts/IMapping.cs new file mode 100644 index 000000000..683c5eb4d --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IMapping.cs @@ -0,0 +1,9 @@ +namespace NVorbis.Contracts +{ + interface IMapping + { + void Init(IPacket packet, int channels, IFloor[] floors, IResidue[] residues, IMdct mdct); + + void DecodePacket(IPacket packet, int blockSize, int channels, float[][] buffer); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IMapping.cs.meta b/Assets/Plugins/NVorbis/Contracts/IMapping.cs.meta new file mode 100644 index 000000000..2a50a96e0 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IMapping.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8d21417d55e5a7749a0c0448167b603c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IMdct.cs b/Assets/Plugins/NVorbis/Contracts/IMdct.cs new file mode 100644 index 000000000..1d4bd6ad5 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IMdct.cs @@ -0,0 +1,7 @@ +namespace NVorbis.Contracts +{ + interface IMdct + { + void Reverse(float[] samples, int sampleCount); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IMdct.cs.meta b/Assets/Plugins/NVorbis/Contracts/IMdct.cs.meta new file mode 100644 index 000000000..d4428e3e6 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IMdct.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9ac05507c9ccc8e4abbc910873f8b268 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IMode.cs b/Assets/Plugins/NVorbis/Contracts/IMode.cs new file mode 100644 index 000000000..3ed20fa24 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IMode.cs @@ -0,0 +1,11 @@ +namespace NVorbis.Contracts +{ + interface IMode + { + void Init(IPacket packet, int channels, int block0Size, int block1Size, IMapping[] mappings); + + bool Decode(IPacket packet, float[][] buffer, out int packetStartindex, out int packetValidLength, out int packetTotalLength); + + int GetPacketSampleCount(IPacket packet); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IMode.cs.meta b/Assets/Plugins/NVorbis/Contracts/IMode.cs.meta new file mode 100644 index 000000000..5ebd18a98 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IMode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a88539f981cbc41469f8d46ee41e3e95 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IPacket.cs b/Assets/Plugins/NVorbis/Contracts/IPacket.cs new file mode 100644 index 000000000..6d1d067bb --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IPacket.cs @@ -0,0 +1,74 @@ +namespace NVorbis.Contracts +{ + /// + /// Describes a packet of data from a data stream. + /// + public interface IPacket + { + /// + /// Gets whether this packet occurs immediately following a loss of sync in the stream. + /// + bool IsResync { get; } + + /// + /// Gets whether this packet did not read its full data. + /// + bool IsShort { get; } + + /// + /// Gets the granule position of the packet, if known. + /// + long? GranulePosition { get; } + + /// + /// Gets whether the packet is the last packet of the stream. + /// + bool IsEndOfStream { get; } + + /// + /// Gets the number of bits read from the packet. + /// + int BitsRead { get; } + + /// + /// Gets the number of bits left in the packet. + /// + int BitsRemaining { get; } + + /// + /// Gets the number of container overhead bits associated with this packet. + /// + int ContainerOverheadBits { get; } + + /// + /// Attempts to read the specified number of bits from the packet. Does not advance the read position. + /// + /// The number of bits to read. + /// Outputs the actual number of bits read. + /// The value of the bits read. + ulong TryPeekBits(int count, out int bitsRead); + + /// + /// Advances the read position by the the specified number of bits. + /// + /// The number of bits to skip reading. + void SkipBits(int count); + + /// + /// Reads the specified number of bits from the packet and advances the read position. + /// + /// The number of bits to read. + /// The value read. If not enough bits remained, this will be a truncated value. + ulong ReadBits(int count); + + /// + /// Frees the buffers and caching for the packet instance. + /// + void Done(); + + /// + /// Resets the read buffers to the beginning of the packet. + /// + void Reset(); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IPacket.cs.meta b/Assets/Plugins/NVorbis/Contracts/IPacket.cs.meta new file mode 100644 index 000000000..799a5d860 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IPacket.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2f6c792a07fce4b41b3bffa1d8542b56 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IPacketProvider.cs b/Assets/Plugins/NVorbis/Contracts/IPacketProvider.cs new file mode 100644 index 000000000..ccc18597c --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IPacketProvider.cs @@ -0,0 +1,51 @@ +namespace NVorbis.Contracts +{ + /// + /// Encapsulates a method that calculates the number of granules decodable from the specified packet. + /// + /// The to calculate. + /// The calculated number of granules. + public delegate int GetPacketGranuleCount(IPacket packet); + + /// + /// Describes an interface for a packet stream reader. + /// + public interface IPacketProvider + { + /// + /// Gets whether the provider supports seeking. + /// + bool CanSeek { get; } + + /// + /// Gets the serial number of this provider's data stream. + /// + int StreamSerial { get; } + + /// + /// Gets the next packet in the stream and advances to the next packet position. + /// + /// The instance for the next packet if available, otherwise . + IPacket GetNextPacket(); + + /// + /// Gets the next packet in the stream without advancing to the next packet position. + /// + /// The instance for the next packet if available, otherwise . + IPacket PeekNextPacket(); + + /// + /// Seeks the stream to the packet that is prior to the requested granule position by the specified preroll number of packets. + /// + /// The granule position to seek to. + /// The number of packets to seek backward prior to the granule position. + /// A delegate that returns the number of granules in the specified packet. + /// The granule position at the start of the packet containing the requested position. + long SeekTo(long granulePos, int preRoll, GetPacketGranuleCount getPacketGranuleCount); + + /// + /// Gets the total number of granule available in the stream. + /// + long GetGranuleCount(); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IPacketProvider.cs.meta b/Assets/Plugins/NVorbis/Contracts/IPacketProvider.cs.meta new file mode 100644 index 000000000..6f0d4ad60 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IPacketProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3674a25b304b6b8468f9eb257482afc1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IResidue.cs b/Assets/Plugins/NVorbis/Contracts/IResidue.cs new file mode 100644 index 000000000..79eccceab --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IResidue.cs @@ -0,0 +1,8 @@ +namespace NVorbis.Contracts +{ + interface IResidue + { + void Init(IPacket packet, int channels, ICodebook[] codebooks); + void Decode(IPacket packet, bool[] doNotDecodeChannel, int blockSize, float[][] buffer); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IResidue.cs.meta b/Assets/Plugins/NVorbis/Contracts/IResidue.cs.meta new file mode 100644 index 000000000..65453c603 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IResidue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c22bc7839a2ecd4a9b175ba2605d193 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IStreamDecoder.cs b/Assets/Plugins/NVorbis/Contracts/IStreamDecoder.cs new file mode 100644 index 000000000..f0d833b81 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IStreamDecoder.cs @@ -0,0 +1,106 @@ +using System; +using System.IO; + +namespace NVorbis.Contracts +{ + /// + /// Describes a stream decoder instance for Vorbis data. + /// + public interface IStreamDecoder : IDisposable + { + /// + /// Gets the number of channels in the stream. + /// + int Channels { get; } + + /// + /// Gets the sample rate of the stream. + /// + int SampleRate { get; } + + /// + /// Gets the upper bitrate limit for the stream, if specified. + /// + int UpperBitrate { get; } + + /// + /// Gets the nominal bitrate of the stream, if specified. May be calculated from and . + /// + int NominalBitrate { get; } + + /// + /// Gets the lower bitrate limit for the stream, if specified. + /// + int LowerBitrate { get; } + + /// + /// Gets the tag data from the stream's header. + /// + ITagData Tags { get; } + + /// + /// Gets the total duration of the decoded stream. + /// + TimeSpan TotalTime { get; } + + /// + /// Gets the total number of samples in the decoded stream. + /// + long TotalSamples { get; } + + /// + /// Gets or sets the current time position of the stream. + /// + TimeSpan TimePosition { get; set; } + + /// + /// Gets or sets the current sample position of the stream. + /// + long SamplePosition { get; set; } + + /// + /// Gets or sets whether to clip samples returned by . + /// + bool ClipSamples { get; set; } + + /// + /// Gets whether has returned any clipped samples. + /// + bool HasClipped { get; } + + /// + /// Gets whether the decoder has reached the end of the stream. + /// + bool IsEndOfStream { get; } + + /// + /// Gets the instance for this stream. + /// + IStreamStats Stats { get; } + + /// + /// Seeks the stream by the specified duration. + /// + /// The relative time to seek to. + /// The reference point used to obtain the new position. + void SeekTo(TimeSpan timePosition, SeekOrigin seekOrigin = SeekOrigin.Begin); + + /// + /// Seeks the stream by the specified sample count. + /// + /// The relative sample position to seek to. + /// The reference point used to obtain the new position. + void SeekTo(long samplePosition, SeekOrigin seekOrigin = SeekOrigin.Begin); + + /// + /// Reads samples into the specified buffer. + /// + /// The buffer to read the samples into. + /// The index to start reading samples into the buffer. + /// The number of samples that should be read into the buffer. Must be a multiple of . + /// The number of samples read into the buffer. + /// Thrown when the buffer is too small or is less than zero. + /// The data populated into is interleaved by channel in normal PCM fashion: Left, Right, Left, Right, Left, Right + int Read(Span buffer, int offset, int count); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IStreamDecoder.cs.meta b/Assets/Plugins/NVorbis/Contracts/IStreamDecoder.cs.meta new file mode 100644 index 000000000..42219f480 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IStreamDecoder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0e9a00f8df7274a46a8c92861b07c199 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IStreamStats.cs b/Assets/Plugins/NVorbis/Contracts/IStreamStats.cs new file mode 100644 index 000000000..fcfe632d1 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IStreamStats.cs @@ -0,0 +1,50 @@ +using System; + +namespace NVorbis.Contracts +{ + /// + /// Describes an interface for reading statistics about the current stream. + /// + public interface IStreamStats + { + /// + /// Resets the counters for bit rate and bits. + /// + void ResetStats(); + + /// + /// Gets the calculated bit rate of audio stream data for the everything decoded so far. + /// + int EffectiveBitRate { get; } + + /// + /// Gets the calculated bit rate per second of audio for the last two packets. + /// + int InstantBitRate { get; } + + /// + /// Gets the number of framing bits used by the container. + /// + long ContainerBits { get; } + + /// + /// Gets the number of bits read that do not contribute to the output audio. Does not include framing bits from the container. + /// + long OverheadBits { get; } + + /// + /// Gets the number of bits read that contribute to the output audio. + /// + long AudioBits { get; } + + /// + /// Gets the number of bits skipped. + /// + long WasteBits { get; } + + /// + /// Gets the number of packets read. + /// + int PacketCount { get; } + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IStreamStats.cs.meta b/Assets/Plugins/NVorbis/Contracts/IStreamStats.cs.meta new file mode 100644 index 000000000..ca2243d42 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IStreamStats.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d92121e8feaec34aad0aa885de3720c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/ITagData.cs b/Assets/Plugins/NVorbis/Contracts/ITagData.cs new file mode 100644 index 000000000..6ef565f1f --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/ITagData.cs @@ -0,0 +1,169 @@ +using System.Collections.Generic; + +namespace NVorbis.Contracts +{ + /// + /// Describes an interface to tag data. + /// + public interface ITagData + { + /// + /// Gets the full list of tags encountered in the stream. + /// + IReadOnlyDictionary> All { get; } + + /// + /// The vendor string from the stream header. + /// + string EncoderVendor { get; } + + #region Standard Tags + + /// + /// Track/Work name. + /// + string Title { get; } // TITLE + + /// + /// Track version name. + /// + string Version { get; } // VERSION + + /// + /// The collection name to which this track belongs. + /// + string Album { get; } // ALBUM + + /// + /// The track number of this piece if part of a specific larger collection or album. + /// + string TrackNumber { get; } // TRACKNUMBER + + /// + /// The artist generally considered responsible for the work. + /// + string Artist { get; } // ARTIST + + /// + /// The artist(s) who performed the work. + /// + IReadOnlyList Performers { get; } // PERFORMER; can be "PERFORMER[instrument]" + + /// + /// Copyright attribution. + /// + string Copyright { get; } // COPYRIGHT + + /// + /// License information. + /// + string License { get; } // LICENSE + + /// + /// The organization producing the track. + /// + string Organization { get; } // ORGANIZATION + + /// + /// A short text description of the contents. + /// + string Description { get; } // DESCRIPTION + + /// + /// A short text indication of the music genre. + /// + IReadOnlyList Genres { get; } // GENRE + + /// + /// Date the track was recorded. May have other dates with descriptions. + /// + IReadOnlyList Dates { get; } // DATE; value is ISO 8601 date with free text following + + /// + /// Location where the track was recorded. + /// + IReadOnlyList Locations { get; } // LOCATION + + /// + /// Contact information for the creators or distributors of the track. + /// + string Contact { get; } // CONTACT + + /// + /// The International Standard Recording Code number for the track. + /// + string Isrc { get; } // ISRC + + #endregion + + #region Extended Tags + /* + -- cover art and related... + COVERART + COVERARTMIME + METADATA_BLOCK_PICTURE + + -- exiftool "common" tags + COMPOSER + DIRECTOR + ACTOR + ENCODED_BY + ENCODED_USING + ENCODER + ENCODER_OPTIONS + REPLAYGAIN_ALBUM_GAIN + REPLAYGAIN_ALBUM_PEAK + REPLAYGAIN_TRACK_GAIN + REPLAYGAIN_TRACK_PEAK + + -- David Shea tags + SOURCE ARTIST + CONDUCTOR + ENSEMBLE + REMIXER + PRODUCER + ENGINEER + GUEST ARTIST + PUBLISHER + PRODUCTNUMBER + CATALOGNUMBER + VOLUME + RELEASE DATE + SOURCE MEDIUM + + -- reactor-core.org tags + ARRANGER + AUTHOR + COMMENT + DISCNUMBER + EAN/UPN + ENCODED-BY + ENCODING + LABEL + LABELNO + LYRICIST + OPUS + PART + PARTNUMBER + SOURCE WORK + SOURCEMEDIA + SPARS + */ + #endregion + + /// + /// Retrieves the value of a tag as a single value. + /// + /// The tag name to retrieve. + /// to concatenate multiple instances into multiple lines. to return just the last instance. + /// The requested tag value, if available. Otherwise . + string GetTagSingle(string key, bool concatenate = false); + + /// + /// Retrieves the values of a tag. + /// + /// The tag name to retrieve. + /// An containing the values in the order read from the stream. + IReadOnlyList GetTagMulti(string key); + } +} \ No newline at end of file diff --git a/Assets/Plugins/NVorbis/Contracts/ITagData.cs.meta b/Assets/Plugins/NVorbis/Contracts/ITagData.cs.meta new file mode 100644 index 000000000..fc08ed837 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/ITagData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 26c79db07b9cb8d4ebb106ad6d47e102 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/IVorbisReader.cs b/Assets/Plugins/NVorbis/Contracts/IVorbisReader.cs new file mode 100644 index 000000000..4744984eb --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IVorbisReader.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace NVorbis.Contracts +{ + /// + /// Describes the interface for . + /// + public interface IVorbisReader : IDisposable + { + /// + /// Raised when a new stream has been encountered in the file or container. + /// + event EventHandler NewStream; + + /// + /// Gets the number of bits read that are related to framing and transport alone. + /// + long ContainerOverheadBits { get; } + + /// + /// Gets the number of bits skipped in the container due to framing, ignored streams, or sync loss. + /// + long ContainerWasteBits { get; } + + /// + /// Gets the list of instances associated with the loaded file / container. + /// + IReadOnlyList Streams { get; } + + /// + /// Gets the currently-selected stream's index. + /// + int StreamIndex { get; } + + /// + /// Gets the number of channels in the stream. + /// + int Channels { get; } + + /// + /// Gets the sample rate of the stream. + /// + int SampleRate { get; } + + /// + /// Gets the upper bitrate limit for the stream, if specified. + /// + int UpperBitrate { get; } + + /// + /// Gets the nominal bitrate of the stream, if specified. May be calculated from and . + /// + int NominalBitrate { get; } + + /// + /// Gets the lower bitrate limit for the stream, if specified. + /// + int LowerBitrate { get; } + + /// + /// Gets the total duration of the decoded stream. + /// + TimeSpan TotalTime { get; } + + /// + /// Gets the total number of samples in the decoded stream. + /// + long TotalSamples { get; } + + /// + /// Gets or sets whether to clip samples returned by . + /// + bool ClipSamples { get; set; } + + /// + /// Gets or sets the current time position of the stream. + /// + TimeSpan TimePosition { get; set; } + + /// + /// Gets or sets the current sample position of the stream. + /// + long SamplePosition { get; set; } + + /// + /// Gets whether has returned any clipped samples. + /// + bool HasClipped { get; } + + /// + /// Gets whether the current stream has ended. + /// + bool IsEndOfStream { get; } + + /// + /// Gets the instance for this stream. + /// + IStreamStats StreamStats { get; } + + /// + /// Gets the tag data from the stream's header. + /// + ITagData Tags { get; } + + /// + /// Searches for the next stream in a concatenated file. Will raise for the found stream, and will add it to if not marked as ignored. + /// + /// if a new stream was found, otherwise . + bool FindNextStream(); + + /// + /// Switches to an alternate logical stream. + /// + /// The logical stream index to switch to + /// if the properties of the logical stream differ from those of the one previously being decoded. Otherwise, . + bool SwitchStreams(int index); + + /// + /// Reads samples into the specified buffer. + /// + /// The buffer to read the samples into. + /// The index to start reading samples into the buffer. + /// The number of samples that should be read into the buffer. Must be a multiple of . + /// The number of samples read into the buffer. + /// Thrown when the buffer is too small or is less than zero. + /// The data populated into is interleaved by channel in normal PCM fashion: Left, Right, Left, Right, Left, Right + int ReadSamples(float[] buffer, int offset, int count); + + /// + /// Seeks the stream by the specified duration. + /// + /// The relative time to seek to. + /// The reference point used to obtain the new position. + void SeekTo(TimeSpan timePosition, SeekOrigin seekOrigin = SeekOrigin.Begin); + + /// + /// Seeks the stream by the specified sample count. + /// + /// The relative sample position to seek to. + /// The reference point used to obtain the new position. + void SeekTo(long samplePosition, SeekOrigin seekOrigin = SeekOrigin.Begin); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/IVorbisReader.cs.meta b/Assets/Plugins/NVorbis/Contracts/IVorbisReader.cs.meta new file mode 100644 index 000000000..1ddf3c7ae --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/IVorbisReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eb426c182b6c016489e1c21c7e7f0d72 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg.meta b/Assets/Plugins/NVorbis/Contracts/Ogg.meta new file mode 100644 index 000000000..d0b2809c5 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6500991047ad19e4c800b3d51b3a2dba +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/ICrc.cs b/Assets/Plugins/NVorbis/Contracts/Ogg/ICrc.cs new file mode 100644 index 000000000..37c11fd81 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/ICrc.cs @@ -0,0 +1,9 @@ +namespace NVorbis.Contracts.Ogg +{ + interface ICrc + { + void Reset(); + void Update(int nextVal); + bool Test(uint checkCrc); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/ICrc.cs.meta b/Assets/Plugins/NVorbis/Contracts/Ogg/ICrc.cs.meta new file mode 100644 index 000000000..f34a9eb08 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/ICrc.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7e2e3609400849341a435152ba432f26 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IForwardOnlyPacketProvider.cs b/Assets/Plugins/NVorbis/Contracts/Ogg/IForwardOnlyPacketProvider.cs new file mode 100644 index 000000000..efbf03cfc --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IForwardOnlyPacketProvider.cs @@ -0,0 +1,8 @@ +namespace NVorbis.Contracts.Ogg +{ + interface IForwardOnlyPacketProvider : IPacketProvider + { + bool AddPage(byte[] buf, bool isResync); + void SetEndOfStream(); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IForwardOnlyPacketProvider.cs.meta b/Assets/Plugins/NVorbis/Contracts/Ogg/IForwardOnlyPacketProvider.cs.meta new file mode 100644 index 000000000..a0248ecbb --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IForwardOnlyPacketProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 228a2d9554fdfea4ab8096b877005856 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IPacketReader.cs b/Assets/Plugins/NVorbis/Contracts/Ogg/IPacketReader.cs new file mode 100644 index 000000000..0b02c6243 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IPacketReader.cs @@ -0,0 +1,11 @@ +using System; + +namespace NVorbis.Contracts.Ogg +{ + interface IPacketReader + { + Memory GetPacketData(int pagePacketIndex); + + void InvalidatePacketCache(IPacket packet); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IPacketReader.cs.meta b/Assets/Plugins/NVorbis/Contracts/Ogg/IPacketReader.cs.meta new file mode 100644 index 000000000..c347232aa --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IPacketReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bff7521b3645c2b40a7cac6a55aed48a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IPageData.cs b/Assets/Plugins/NVorbis/Contracts/Ogg/IPageData.cs new file mode 100644 index 000000000..016e3e69c --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IPageData.cs @@ -0,0 +1,19 @@ +using System; + +namespace NVorbis.Contracts.Ogg +{ + interface IPageData : IPageReader + { + long PageOffset { get; } + int StreamSerial { get; } + int SequenceNumber { get; } + PageFlags PageFlags { get; } + long GranulePosition { get; } + short PacketCount { get; } + bool? IsResync { get; } + bool IsContinued { get; } + int PageOverhead { get; } + + Memory[] GetPackets(); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IPageData.cs.meta b/Assets/Plugins/NVorbis/Contracts/Ogg/IPageData.cs.meta new file mode 100644 index 000000000..013473bc9 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IPageData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4b8f278220da354a84883d506249bb6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IPageReader.cs b/Assets/Plugins/NVorbis/Contracts/Ogg/IPageReader.cs new file mode 100644 index 000000000..96f7e6574 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IPageReader.cs @@ -0,0 +1,17 @@ +using System; + +namespace NVorbis.Contracts.Ogg +{ + interface IPageReader : IDisposable + { + void Lock(); + bool Release(); + + long ContainerBits { get; } + long WasteBits { get; } + + bool ReadNextPage(); + + bool ReadPageAt(long offset); + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IPageReader.cs.meta b/Assets/Plugins/NVorbis/Contracts/Ogg/IPageReader.cs.meta new file mode 100644 index 000000000..833dd31ad --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IPageReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9ec2c59b309d9664ab5c5c6d9ee87f3c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IStreamPageReader.cs b/Assets/Plugins/NVorbis/Contracts/Ogg/IStreamPageReader.cs new file mode 100644 index 000000000..04fe4bbeb --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IStreamPageReader.cs @@ -0,0 +1,27 @@ +using System; + +namespace NVorbis.Contracts.Ogg +{ + interface IStreamPageReader + { + IPacketProvider PacketProvider { get; } + + void AddPage(); + + Memory[] GetPagePackets(int pageIndex); + + int FindPage(long granulePos); + + bool GetPage(int pageIndex, out long granulePos, out bool isResync, out bool isContinuation, out bool isContinued, out int packetCount, out int pageOverhead); + + void SetEndOfStream(); + + int PageCount { get; } + + bool HasAllPages { get; } + + long? MaxGranulePosition { get; } + + int FirstDataPageIndex { get; } + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/IStreamPageReader.cs.meta b/Assets/Plugins/NVorbis/Contracts/Ogg/IStreamPageReader.cs.meta new file mode 100644 index 000000000..38fbd7374 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/IStreamPageReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4eb36b87c2e5abd459a6b9468686470a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/PageFlags.cs b/Assets/Plugins/NVorbis/Contracts/Ogg/PageFlags.cs new file mode 100644 index 000000000..5d6683b33 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/PageFlags.cs @@ -0,0 +1,13 @@ +using System; + +namespace NVorbis.Contracts.Ogg +{ + [Flags] + enum PageFlags + { + None = 0, + ContinuesPacket = 1, + BeginningOfStream = 2, + EndOfStream = 4, + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/Ogg/PageFlags.cs.meta b/Assets/Plugins/NVorbis/Contracts/Ogg/PageFlags.cs.meta new file mode 100644 index 000000000..4a66096e7 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/Ogg/PageFlags.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1a81dbb6e7d3b53438ca5462d7fcf90c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Contracts/ParameterChangeEventArgs.cs b/Assets/Plugins/NVorbis/Contracts/ParameterChangeEventArgs.cs new file mode 100644 index 000000000..e6b292f69 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/ParameterChangeEventArgs.cs @@ -0,0 +1,31 @@ +using System; + +namespace NVorbis.Contracts +{ + /// + /// Contains data for parameter change events. + /// + public class ParameterChangeEventArgs : EventArgs + { + /// + /// Creates a new instance of . + /// + /// The new number of channels. + /// The new sample rate. + public ParameterChangeEventArgs(int channels, int sampleRate) + { + Channels = channels; + SampleRate = sampleRate; + } + + /// + /// Get the new number of channels in the stream. + /// + public int Channels { get; } + + /// + /// Gets the new sample rate of the stream. + /// + public int SampleRate { get; } + } +} diff --git a/Assets/Plugins/NVorbis/Contracts/ParameterChangeEventArgs.cs.meta b/Assets/Plugins/NVorbis/Contracts/ParameterChangeEventArgs.cs.meta new file mode 100644 index 000000000..5505e1825 --- /dev/null +++ b/Assets/Plugins/NVorbis/Contracts/ParameterChangeEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 91190652c483d3848a6983eb9db1b530 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/DataPacket.cs b/Assets/Plugins/NVorbis/DataPacket.cs new file mode 100644 index 000000000..8eb6f18a8 --- /dev/null +++ b/Assets/Plugins/NVorbis/DataPacket.cs @@ -0,0 +1,285 @@ +using NVorbis.Contracts; +using System; + +namespace NVorbis +{ + /// + /// Provides a concrete base implementation of . + /// + abstract public class DataPacket : IPacket + { + /// + /// Defines flags to apply to the current packet + /// + [Flags] + // for now, let's use a byte... if we find we need more space, we can always expand it... + protected enum PacketFlags : byte + { + /// + /// Packet is first since reader had to resync with stream. + /// + IsResync = 0x01, + /// + /// Packet is the last in the logical stream. + /// + IsEndOfStream = 0x02, + /// + /// Packet does not have all its data available. + /// + IsShort = 0x04, + + /// + /// Flag for use by inheritors. + /// + User0 = 0x08, + /// + /// Flag for use by inheritors. + /// + User1 = 0x10, + /// + /// Flag for use by inheritors. + /// + User2 = 0x20, + /// + /// Flag for use by inheritors. + /// + User3 = 0x40, + /// + /// Flag for use by inheritors. + /// + User4 = 0x80, + } + + ulong _bitBucket; + int _bitCount; + byte _overflowBits; + PacketFlags _packetFlags; + int _readBits; + + /// + /// Gets the number of container overhead bits associated with this packet. + /// + public int ContainerOverheadBits { get; set; } + + /// + /// Gets the granule position of the packet, if known. + /// + public long? GranulePosition { get; set; } + + /// + /// Gets whether this packet occurs immediately following a loss of sync in the stream. + /// + public bool IsResync + { + get => GetFlag(PacketFlags.IsResync); + set => SetFlag(PacketFlags.IsResync, value); + } + + /// + /// Gets whether this packet did not read its full data. + /// + public bool IsShort + { + get => GetFlag(PacketFlags.IsShort); + private set => SetFlag(PacketFlags.IsShort, value); + } + + /// + /// Gets whether the packet is the last packet of the stream. + /// + public bool IsEndOfStream + { + get => GetFlag(PacketFlags.IsEndOfStream); + set => SetFlag(PacketFlags.IsEndOfStream, value); + } + + /// + /// Gets the number of bits read from the packet. + /// + public int BitsRead => _readBits; + + /// + /// Gets the number of bits left in the packet. + /// + public int BitsRemaining => TotalBits - _readBits; + + /// + /// Gets the total number of bits in the packet. + /// + abstract protected int TotalBits { get; } + + bool GetFlag(PacketFlags flag) => _packetFlags.HasFlag(flag); + + void SetFlag(PacketFlags flag, bool value) + { + if (value) + { + _packetFlags |= flag; + } + else + { + _packetFlags &= ~flag; + } + } + + /// + /// Reads the next byte in the packet. + /// + /// The next byte in the packet, or -1 if no more data is available. + abstract protected int ReadNextByte(); + + /// + /// Frees the buffers and caching for the packet instance. + /// + virtual public void Done() + { + // no-op for base + } + + /// + /// Resets the read buffers to the beginning of the packet. + /// + virtual public void Reset() + { + _bitBucket = 0; + _bitCount = 0; + _overflowBits = 0; + _readBits = 0; + } + + ulong IPacket.ReadBits(int count) + { + // short-circuit 0 + if (count == 0) return 0UL; + + var value = TryPeekBits(count, out _); + + SkipBits(count); + + return value; + } + + /// + /// Attempts to read the specified number of bits from the packet. Does not advance the read position. + /// + /// The number of bits to read. + /// Outputs the actual number of bits read. + /// The value of the bits read. + public ulong TryPeekBits(int count, out int bitsRead) + { + if (count < 0 || count > 64) throw new ArgumentOutOfRangeException(nameof(count)); + if (count == 0) + { + bitsRead = 0; + return 0UL; + } + + ulong value; + while (_bitCount < count) + { + var val = ReadNextByte(); + if (val == -1) + { + bitsRead = _bitCount; + value = _bitBucket; + return value; + } + _bitBucket = (ulong)(val & 0xFF) << _bitCount | _bitBucket; + _bitCount += 8; + + if (_bitCount > 64) + { + _overflowBits = (byte)(val >> (72 - _bitCount)); + } + } + + value = _bitBucket; + + if (count < 64) + { + value &= (1UL << count) - 1; + } + + bitsRead = count; + return value; + } + + /// + /// Advances the read position by the the specified number of bits. + /// + /// The number of bits to skip reading. + public void SkipBits(int count) + { + if (count > 0) + { + if (_bitCount > count) + { + // we still have bits left over... + if (count > 63) + { + _bitBucket = 0; + } + else + { + _bitBucket >>= count; + } + if (_bitCount > 64) + { + var overflowCount = _bitCount - 64; + _bitBucket |= (ulong)_overflowBits << (_bitCount - count - overflowCount); + + if (overflowCount > count) + { + // ugh, we have to keep bits in overflow + _overflowBits >>= count; + } + } + + _bitCount -= count; + _readBits += count; + } + else if (_bitCount == count) + { + _bitBucket = 0UL; + _bitCount = 0; + _readBits += count; + } + else // _bitCount < count + { + // we have to move more bits than we have available... + count -= _bitCount; + _readBits += _bitCount; + _bitCount = 0; + _bitBucket = 0; + + while (count > 8) + { + if (ReadNextByte() == -1) + { + count = 0; + IsShort = true; + break; + } + count -= 8; + _readBits += 8; + } + + if (count > 0) + { + var temp = ReadNextByte(); + if (temp == -1) + { + IsShort = true; + } + else + { + _bitBucket = (ulong)(temp >> count); + _bitCount = 8 - count; + _readBits += count; + } + } + } + } + } + } +} diff --git a/Assets/Plugins/NVorbis/DataPacket.cs.meta b/Assets/Plugins/NVorbis/DataPacket.cs.meta new file mode 100644 index 000000000..2c10ecd04 --- /dev/null +++ b/Assets/Plugins/NVorbis/DataPacket.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2ca6b6052b6c0974bb0bb1ef078578fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Extensions.cs b/Assets/Plugins/NVorbis/Extensions.cs new file mode 100644 index 000000000..960c1f165 --- /dev/null +++ b/Assets/Plugins/NVorbis/Extensions.cs @@ -0,0 +1,154 @@ +using NVorbis.Contracts; +using System; + +namespace NVorbis +{ + /// + /// Provides extension methods for NVorbis types. + /// + public static class Extensions + { + /// + /// Reads into the specified buffer. + /// + /// The packet instance to use. + /// The buffer to read into. + /// The index into the buffer to use. + /// The number of bytes to read into the buffer. + /// The number of bytes actually read into the buffer. + public static int Read(this IPacket packet, byte[] buffer, int index, int count) + { + if (index < 0 || index >= buffer.Length) throw new ArgumentOutOfRangeException(nameof(index)); + if (count < 0 || index + count > buffer.Length) throw new ArgumentOutOfRangeException(nameof(count)); + for (int i = 0; i < count; i++) + { + var value = (byte)packet.TryPeekBits(8, out var bitsRead); + if (bitsRead == 0) + { + return i; + } + buffer[index++] = value; + packet.SkipBits(8); + } + return count; + } + + /// + /// Reads the specified number of bytes from the packet and advances the position counter. + /// + /// + /// The number of bytes to read. + /// A byte array holding the data read. + public static byte[] ReadBytes(this IPacket packet, int count) + { + var buf = new byte[count]; + var cnt = Read(packet, buf, 0, count); + if (cnt < count) + { + var temp = new byte[cnt]; + Buffer.BlockCopy(buf, 0, temp, 0, cnt); + return temp; + } + return buf; + } + + /// + /// Reads one bit from the packet and advances the read position. + /// + /// if the bit was a one, otehrwise . + public static bool ReadBit(this IPacket packet) + { + return packet.ReadBits(1) == 1; + } + + /// + /// Reads the next byte from the packet. Does not advance the position counter. + /// + /// + /// The byte read from the packet. + public static byte PeekByte(this IPacket packet) + { + return (byte)packet.TryPeekBits(8, out _); + } + + /// + /// Reads the next byte from the packet and advances the position counter. + /// + /// + /// The byte read from the packet. + public static byte ReadByte(this IPacket packet) + { + return (byte)packet.ReadBits(8); + } + + /// + /// Reads the next 16 bits from the packet as a and advances the position counter. + /// + /// + /// The value of the next 16 bits. + public static short ReadInt16(this IPacket packet) + { + return (short)packet.ReadBits(16); + } + + /// + /// Reads the next 32 bits from the packet as a and advances the position counter. + /// + /// + /// The value of the next 32 bits. + public static int ReadInt32(this IPacket packet) + { + return (int)packet.ReadBits(32); + } + + /// + /// Reads the next 64 bits from the packet as a and advances the position counter. + /// + /// + /// The value of the next 64 bits. + public static long ReadInt64(this IPacket packet) + { + return (long)packet.ReadBits(64); + } + + /// + /// Reads the next 16 bits from the packet as a and advances the position counter. + /// + /// + /// The value of the next 16 bits. + public static ushort ReadUInt16(this IPacket packet) + { + return (ushort)packet.ReadBits(16); + } + + /// + /// Reads the next 32 bits from the packet as a and advances the position counter. + /// + /// + /// The value of the next 32 bits. + public static uint ReadUInt32(this IPacket packet) + { + return (uint)packet.ReadBits(32); + } + + /// + /// Reads the next 64 bits from the packet as a and advances the position counter. + /// + /// + /// The value of the next 64 bits. + public static ulong ReadUInt64(this IPacket packet) + { + return packet.ReadBits(64); + } + + /// + /// Advances the position counter by the specified number of bytes. + /// + /// + /// The number of bytes to advance. + public static void SkipBytes(this IPacket packet, int count) + { + packet.SkipBits(count * 8); + } + } +} diff --git a/Assets/Plugins/NVorbis/Extensions.cs.meta b/Assets/Plugins/NVorbis/Extensions.cs.meta new file mode 100644 index 000000000..f3fc661f1 --- /dev/null +++ b/Assets/Plugins/NVorbis/Extensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4e539671d6ba3e747aede5d5b9a20d91 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Factory.cs b/Assets/Plugins/NVorbis/Factory.cs new file mode 100644 index 000000000..0096c0df9 --- /dev/null +++ b/Assets/Plugins/NVorbis/Factory.cs @@ -0,0 +1,60 @@ +using NVorbis.Contracts; + +namespace NVorbis +{ + class Factory : IFactory + { + public IHuffman CreateHuffman() + { + return new Huffman(); + } + + public IMdct CreateMdct() + { + return new Mdct(); + } + + public ICodebook CreateCodebook() + { + return new Codebook(); + } + + public IFloor CreateFloor(IPacket packet) + { + var type = (int)packet.ReadBits(16); + switch (type) + { + case 0: return new Floor0(); + case 1: return new Floor1(); + default: throw new System.IO.InvalidDataException("Invalid floor type!"); + } + } + + public IMapping CreateMapping(IPacket packet) + { + if (packet.ReadBits(16) != 0) + { + throw new System.IO.InvalidDataException("Invalid mapping type!"); + } + + return new Mapping(); + } + + public IMode CreateMode() + { + return new Mode(); + } + + public IResidue CreateResidue(IPacket packet) + { + var type = (int)packet.ReadBits(16); + switch (type) + { + case 0: return new Residue0(); + case 1: return new Residue1(); + case 2: return new Residue2(); + default: throw new System.IO.InvalidDataException("Invalid residue type!"); + } + } + } +} diff --git a/Assets/Plugins/NVorbis/Factory.cs.meta b/Assets/Plugins/NVorbis/Factory.cs.meta new file mode 100644 index 000000000..1d2777568 --- /dev/null +++ b/Assets/Plugins/NVorbis/Factory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4cf4ee29e76049f44b2b114336ccd7eb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Floor0.cs b/Assets/Plugins/NVorbis/Floor0.cs new file mode 100644 index 000000000..6100e951a --- /dev/null +++ b/Assets/Plugins/NVorbis/Floor0.cs @@ -0,0 +1,214 @@ +using NVorbis.Contracts; +using System; +using System.Collections.Generic; +using System.IO; + +namespace NVorbis +{ + // Packed LSP values on dB amplittude and Bark frequency scale. Virtually unused (libvorbis did not use past beta 4). Probably untested. + class Floor0 : IFloor + { + class Data : IFloorData + { + internal float[] Coeff; + internal float Amp; + + public bool ExecuteChannel => (ForceEnergy || Amp > 0f) && !ForceNoEnergy; + + public bool ForceEnergy { get; set; } + public bool ForceNoEnergy { get; set; } + } + + int _order, _rate, _bark_map_size, _ampBits, _ampOfs, _ampDiv; + ICodebook[] _books; + int _bookBits; + Dictionary _wMap; + Dictionary _barkMaps; + + public void Init(IPacket packet, int channels, int block0Size, int block1Size, ICodebook[] codebooks) + { + // this is pretty well stolen directly from libvorbis... BSD license + _order = (int)packet.ReadBits(8); + _rate = (int)packet.ReadBits(16); + _bark_map_size = (int)packet.ReadBits(16); + _ampBits = (int)packet.ReadBits(6); + _ampOfs = (int)packet.ReadBits(8); + _books = new ICodebook[(int)packet.ReadBits(4) + 1]; + + if (_order < 1 || _rate < 1 || _bark_map_size < 1 || _books.Length == 0) throw new InvalidDataException(); + + _ampDiv = (1 << _ampBits) - 1; + + for (int i = 0; i < _books.Length; i++) + { + var num = (int)packet.ReadBits(8); + if (num < 0 || num >= codebooks.Length) throw new InvalidDataException(); + var book = codebooks[num]; + + if (book.MapType == 0 || book.Dimensions < 1) throw new InvalidDataException(); + + _books[i] = book; + } + _bookBits = Utils.ilog(_books.Length); + + _barkMaps = new Dictionary + { + [block0Size] = SynthesizeBarkCurve(block0Size / 2), + [block1Size] = SynthesizeBarkCurve(block1Size / 2) + }; + + _wMap = new Dictionary + { + [block0Size] = SynthesizeWDelMap(block0Size / 2), + [block1Size] = SynthesizeWDelMap(block1Size / 2) + }; + } + + int[] SynthesizeBarkCurve(int n) + { + var scale = _bark_map_size / toBARK(_rate / 2); + + var map = new int[n + 1]; + + for (int i = 0; i < n - 1; i++) + { + map[i] = Math.Min(_bark_map_size - 1, (int)Math.Floor(toBARK((_rate / 2f) / n * i) * scale)); + } + map[n] = -1; + return map; + } + + static float toBARK(double lsp) + { + return (float)(13.1 * Math.Atan(0.00074 * lsp) + 2.24 * Math.Atan(0.0000000185 * lsp * lsp) + .0001 * lsp); + } + + float[] SynthesizeWDelMap(int n) + { + var wdel = (float)(Math.PI / _bark_map_size); + + var map = new float[n]; + for (int i = 0; i < n; i++) + { + map[i] = 2f * (float)Math.Cos(wdel * i); + } + return map; + } + + public IFloorData Unpack(IPacket packet, int blockSize, int channel) + { + var data = new Data + { + Coeff = new float[_order + 1], + }; + + data.Amp = packet.ReadBits(_ampBits); + if (data.Amp > 0f) + { + // this is pretty well stolen directly from libvorbis... BSD license + Array.Clear(data.Coeff, 0, data.Coeff.Length); + + data.Amp = data.Amp / _ampDiv * _ampOfs; + + var bookNum = (uint)packet.ReadBits(_bookBits); + if (bookNum >= _books.Length) + { + // we ran out of data or the packet is corrupt... 0 the floor and return + data.Amp = 0; + return data; + } + var book = _books[bookNum]; + + // first, the book decode... + for (int i = 0; i < _order;) + { + var entry = book.DecodeScalar(packet); + if (entry == -1) + { + // we ran out of data or the packet is corrupt... 0 the floor and return + data.Amp = 0; + return data; + } + for (int j = 0; i < _order && j < book.Dimensions; j++, i++) + { + data.Coeff[i] = book[entry, j]; + } + } + + // then, the "averaging" + var last = 0f; + for (int j = 0; j < _order;) + { + for (int k = 0; j < _order && k < book.Dimensions; j++, k++) + { + data.Coeff[j] += last; + } + last = data.Coeff[j - 1]; + } + } + return data; + } + + public void Apply(IFloorData floorData, int blockSize, float[] residue) + { + if (!(floorData is Data data)) throw new ArgumentException("Incorrect packet data!"); + + var n = blockSize / 2; + + if (data.Amp > 0f) + { + // this is pretty well stolen directly from libvorbis... BSD license + var barkMap = _barkMaps[blockSize]; + var wMap = _wMap[blockSize]; + + int i = 0; + for (i = 0; i < _order; i++) + { + data.Coeff[i] = 2f * (float)Math.Cos(data.Coeff[i]); + } + + i = 0; + while (i < n) + { + int j; + var k = barkMap[i]; + var p = .5f; + var q = .5f; + var w = wMap[k]; + for (j = 1; j < _order; j += 2) + { + q *= w - data.Coeff[j - 1]; + p *= w - data.Coeff[j]; + } + if (j == _order) + { + // odd order filter; slightly assymetric + q *= w - data.Coeff[j - 1]; + p *= p * (4f - w * w); + q *= q; + } + else + { + // even order filter; still symetric + p *= p * (2f - w); + q *= q * (2f + w); + } + + // calc the dB of this bark section + q = data.Amp / (float)Math.Sqrt(p + q) - _ampOfs; + + // now convert to a linear sample multiplier + q = (float)Math.Exp(q * 0.11512925f); + + residue[i] *= q; + + while (barkMap[++i] == k) residue[i] *= q; + } + } + else + { + Array.Clear(residue, 0, n); + } + } + } +} diff --git a/Assets/Plugins/NVorbis/Floor0.cs.meta b/Assets/Plugins/NVorbis/Floor0.cs.meta new file mode 100644 index 000000000..a1039054d --- /dev/null +++ b/Assets/Plugins/NVorbis/Floor0.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: afedaa5d27283b248822a3a11e53d6f7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Floor1.cs b/Assets/Plugins/NVorbis/Floor1.cs new file mode 100644 index 000000000..d09c3142f --- /dev/null +++ b/Assets/Plugins/NVorbis/Floor1.cs @@ -0,0 +1,414 @@ +using NVorbis.Contracts; +using System; +using System.Collections.Generic; + +namespace NVorbis +{ + // Linear interpolated values on dB amplitude and linear frequency scale. Draws a curve between each point to define the low-resolution spectral data. + class Floor1 : IFloor + { + class Data : IFloorData + { + internal int[] Posts = new int[64]; + internal int PostCount; + + public bool ExecuteChannel => (ForceEnergy || PostCount > 0) && !ForceNoEnergy; + + public bool ForceEnergy { get; set; } + public bool ForceNoEnergy { get; set; } + } + + int[] _partitionClass, _classDimensions, _classSubclasses, _xList, _classMasterBookIndex, _hNeigh, _lNeigh, _sortIdx; + int _multiplier, _range, _yBits; + ICodebook[] _classMasterbooks; + ICodebook[][] _subclassBooks; + int[][] _subclassBookIndex; + + static readonly int[] _rangeLookup = { 256, 128, 86, 64 }; + static readonly int[] _yBitsLookup = { 8, 7, 7, 6 }; + + public void Init(IPacket packet, int channels, int block0Size, int block1Size, ICodebook[] codebooks) + { + var maximum_class = -1; + _partitionClass = new int[(int)packet.ReadBits(5)]; + for (int i = 0; i < _partitionClass.Length; i++) + { + _partitionClass[i] = (int)packet.ReadBits(4); + if (_partitionClass[i] > maximum_class) + { + maximum_class = _partitionClass[i]; + } + } + + _classDimensions = new int[++maximum_class]; + _classSubclasses = new int[maximum_class]; + _classMasterbooks = new ICodebook[maximum_class]; + _classMasterBookIndex = new int[maximum_class]; + _subclassBooks = new ICodebook[maximum_class][]; + _subclassBookIndex = new int[maximum_class][]; + for (int i = 0; i < maximum_class; i++) + { + _classDimensions[i] = (int)packet.ReadBits(3) + 1; + _classSubclasses[i] = (int)packet.ReadBits(2); + if (_classSubclasses[i] > 0) + { + _classMasterBookIndex[i] = (int)packet.ReadBits(8); + _classMasterbooks[i] = codebooks[_classMasterBookIndex[i]]; + } + + _subclassBooks[i] = new ICodebook[1 << _classSubclasses[i]]; + _subclassBookIndex[i] = new int[_subclassBooks[i].Length]; + for (int j = 0; j < _subclassBooks[i].Length; j++) + { + var bookNum = (int)packet.ReadBits(8) - 1; + if (bookNum >= 0) _subclassBooks[i][j] = codebooks[bookNum]; + _subclassBookIndex[i][j] = bookNum; + } + } + + _multiplier = (int)packet.ReadBits(2); + + _range = _rangeLookup[_multiplier]; + _yBits = _yBitsLookup[_multiplier]; + + ++_multiplier; + + var rangeBits = (int)packet.ReadBits(4); + + var xList = new List(); + xList.Add(0); + xList.Add(1 << rangeBits); + + for (int i = 0; i < _partitionClass.Length; i++) + { + var classNum = _partitionClass[i]; + for (int j = 0; j < _classDimensions[classNum]; j++) + { + xList.Add((int)packet.ReadBits(rangeBits)); + } + } + _xList = xList.ToArray(); + + // precalc the low and high neighbors (and init the sort table) + _lNeigh = new int[xList.Count]; + _hNeigh = new int[xList.Count]; + _sortIdx = new int[xList.Count]; + _sortIdx[0] = 0; + _sortIdx[1] = 1; + for (int i = 2; i < _lNeigh.Length; i++) + { + _lNeigh[i] = 0; + _hNeigh[i] = 1; + _sortIdx[i] = i; + for (int j = 2; j < i; j++) + { + var temp = _xList[j]; + if (temp < _xList[i]) + { + if (temp > _xList[_lNeigh[i]]) _lNeigh[i] = j; + } + else + { + if (temp < _xList[_hNeigh[i]]) _hNeigh[i] = j; + } + } + } + + // precalc the sort table + for (int i = 0; i < _sortIdx.Length - 1; i++) + { + for (int j = i + 1; j < _sortIdx.Length; j++) + { + if (_xList[i] == _xList[j]) throw new System.IO.InvalidDataException(); + + if (_xList[_sortIdx[i]] > _xList[_sortIdx[j]]) + { + // swap the sort indexes + var temp = _sortIdx[i]; + _sortIdx[i] = _sortIdx[j]; + _sortIdx[j] = temp; + } + } + } + } + + public IFloorData Unpack(IPacket packet, int blockSize, int channel) + { + var data = new Data(); + + // hoist ReadPosts to here since that's all we're doing... + if (packet.ReadBit()) + { + var postCount = 2; + data.Posts[0] = (int)packet.ReadBits(_yBits); + data.Posts[1] = (int)packet.ReadBits(_yBits); + + for (int i = 0; i < _partitionClass.Length; i++) + { + var clsNum = _partitionClass[i]; + var cdim = _classDimensions[clsNum]; + var cbits = _classSubclasses[clsNum]; + var csub = (1 << cbits) - 1; + var cval = 0U; + if (cbits > 0) + { + if ((cval = (uint)_classMasterbooks[clsNum].DecodeScalar(packet)) == uint.MaxValue) + { + // we read a bad value... bail + postCount = 0; + break; + } + } + for (int j = 0; j < cdim; j++) + { + var book = _subclassBooks[clsNum][cval & csub]; + cval >>= cbits; + if (book != null) + { + if ((data.Posts[postCount] = book.DecodeScalar(packet)) == -1) + { + // we read a bad value... bail + postCount = 0; + i = _partitionClass.Length; + break; + } + } + ++postCount; + } + } + + data.PostCount = postCount; + } + + return data; + } + + public void Apply(IFloorData floorData, int blockSize, float[] residue) + { + if (!(floorData is Data data)) throw new ArgumentException("Incorrect packet data!", "packetData"); + + var n = blockSize / 2; + + if (data.PostCount > 0) + { + var stepFlags = UnwrapPosts(data); + + var lx = 0; + var ly = data.Posts[0] * _multiplier; + for (int i = 1; i < data.PostCount; i++) + { + var idx = _sortIdx[i]; + + if (stepFlags[idx]) + { + var hx = _xList[idx]; + var hy = data.Posts[idx] * _multiplier; + if (lx < n) RenderLineMulti(lx, ly, Math.Min(hx, n), hy, residue); + lx = hx; + ly = hy; + } + if (lx >= n) break; + } + + if (lx < n) + { + RenderLineMulti(lx, ly, n, ly, residue); + } + } + else + { + Array.Clear(residue, 0, n); + } + } + + bool[] UnwrapPosts(Data data) + { + var stepFlags = new bool[64]; + stepFlags[0] = true; + stepFlags[1] = true; + + var finalY = new int[64]; + finalY[0] = data.Posts[0]; + finalY[1] = data.Posts[1]; + + for (int i = 2; i < data.PostCount; i++) + { + var lowOfs = _lNeigh[i]; + var highOfs = _hNeigh[i]; + + var predicted = RenderPoint(_xList[lowOfs], finalY[lowOfs], _xList[highOfs], finalY[highOfs], _xList[i]); + + var val = data.Posts[i]; + var highroom = _range - predicted; + var lowroom = predicted; + int room; + if (highroom < lowroom) + { + room = highroom * 2; + } + else + { + room = lowroom * 2; + } + if (val != 0) + { + stepFlags[lowOfs] = true; + stepFlags[highOfs] = true; + stepFlags[i] = true; + + if (val >= room) + { + if (highroom > lowroom) + { + finalY[i] = val - lowroom + predicted; + } + else + { + finalY[i] = predicted - val + highroom - 1; + } + } + else + { + if ((val % 2) == 1) + { + // odd + finalY[i] = predicted - ((val + 1) / 2); + } + else + { + // even + finalY[i] = predicted + (val / 2); + } + } + } + else + { + stepFlags[i] = false; + finalY[i] = predicted; + } + } + + for (int i = 0; i < data.PostCount; i++) + { + data.Posts[i] = finalY[i]; + } + + return stepFlags; + } + + int RenderPoint(int x0, int y0, int x1, int y1, int X) + { + var dy = y1 - y0; + var adx = x1 - x0; + var ady = Math.Abs(dy); + var err = ady * (X - x0); + var off = err / adx; + if (dy < 0) + { + return y0 - off; + } + else + { + return y0 + off; + } + } + + void RenderLineMulti(int x0, int y0, int x1, int y1, float[] v) + { + var dy = y1 - y0; + var adx = x1 - x0; + var ady = Math.Abs(dy); + var sy = 1 - (((dy >> 31) & 1) * 2); + var b = dy / adx; + var x = x0; + var y = y0; + var err = -adx; + + v[x0] *= inverse_dB_table[y0]; + ady -= Math.Abs(b) * adx; + + while (++x < x1) + { + y += b; + err += ady; + if (err >= 0) + { + err -= adx; + y += sy; + } + v[x] *= inverse_dB_table[y]; + } + } + + #region dB inversion table + + static readonly float[] inverse_dB_table = { + 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, + 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, + 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, + 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, + 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, + 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, + 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, + 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, + 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, + 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, + 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, + 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, + 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, + 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, + 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, + 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, + 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, + 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, + 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, + 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, + 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, + 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, + 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, + 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, + 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, + 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, + 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, + 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, + 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, + 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, + 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, + 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, + 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, + 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, + 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, + 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, + 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, + 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, + 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, + 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, + 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, + 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, + 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, + 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, + 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, + 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, + 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, + 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, + 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, + 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, + 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, + 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, + 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, + 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, + 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, + 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, + 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, + 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, + 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, + 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, + 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, + 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, + 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, + 0.82788260f, 0.88168307f, 0.9389798f, 1.0f + }; + + #endregion + } +} diff --git a/Assets/Plugins/NVorbis/Floor1.cs.meta b/Assets/Plugins/NVorbis/Floor1.cs.meta new file mode 100644 index 000000000..edd1c268d --- /dev/null +++ b/Assets/Plugins/NVorbis/Floor1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46c331814cd1bd54ba63fd90b7139953 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Huffman.cs b/Assets/Plugins/NVorbis/Huffman.cs new file mode 100644 index 000000000..95c10a242 --- /dev/null +++ b/Assets/Plugins/NVorbis/Huffman.cs @@ -0,0 +1,88 @@ +using NVorbis.Contracts; +using System; +using System.Collections.Generic; + +namespace NVorbis +{ + class Huffman : IHuffman, IComparer + { + const int MAX_TABLE_BITS = 10; + + public int TableBits { get; private set; } + public IReadOnlyList PrefixTree { get; private set; } + public IReadOnlyList OverflowList { get; private set; } + + public void GenerateTable(IReadOnlyList values, int[] lengthList, int[] codeList) + { + var list = new HuffmanListNode[lengthList.Length]; + + var maxLen = 0; + for (int i = 0; i < list.Length; i++) + { + list[i] = new HuffmanListNode + { + Value = values[i], + Length = lengthList[i] <= 0 ? 99999 : lengthList[i], + Bits = codeList[i], + Mask = (1 << lengthList[i]) - 1, + }; + if (lengthList[i] > 0 && maxLen < lengthList[i]) + { + maxLen = lengthList[i]; + } + } + + Array.Sort(list, 0, list.Length, this); + + var tableBits = maxLen > MAX_TABLE_BITS ? MAX_TABLE_BITS : maxLen; + + var prefixList = new List(1 << tableBits); + List overflowList = null; + for (int i = 0; i < list.Length && list[i].Length < 99999; i++) + { + var itemBits = list[i].Length; + if (itemBits > tableBits) + { + overflowList = new List(list.Length - i); + for (; i < list.Length && list[i].Length < 99999; i++) + { + overflowList.Add(list[i]); + } + } + else + { + var maxVal = 1 << (tableBits - itemBits); + var item = list[i]; + for (int j = 0; j < maxVal; j++) + { + var idx = (j << itemBits) | item.Bits; + while (prefixList.Count <= idx) + { + prefixList.Add(null); + } + prefixList[idx] = item; + } + } + } + + while (prefixList.Count < 1 << tableBits) + { + prefixList.Add(null); + } + + TableBits = tableBits; + PrefixTree = prefixList; + OverflowList = overflowList; + } + + int IComparer.Compare(HuffmanListNode x, HuffmanListNode y) + { + var len = x.Length - y.Length; + if (len == 0) + { + return x.Bits - y.Bits; + } + return len; + } + } +} diff --git a/Assets/Plugins/NVorbis/Huffman.cs.meta b/Assets/Plugins/NVorbis/Huffman.cs.meta new file mode 100644 index 000000000..612828dbd --- /dev/null +++ b/Assets/Plugins/NVorbis/Huffman.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e918d1712b695014ba3cbb5dd43e7cf8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/IContainerReader.cs b/Assets/Plugins/NVorbis/IContainerReader.cs new file mode 100644 index 000000000..8ee820954 --- /dev/null +++ b/Assets/Plugins/NVorbis/IContainerReader.cs @@ -0,0 +1,41 @@ +using System; + +namespace NVorbis +{ + /// + /// Old interface, current version moved to Contracts.IContainerReader + /// + [Obsolete("Moved to NVorbis.Contracts.IContainerReader", true)] + public interface IContainerReader : Contracts.IContainerReader + { + /// + /// Gets the list of stream serials found in the container so far. + /// + [Obsolete("Use Streams.Select(s => s.StreamSerial).ToArray() instead.", true)] + int[] StreamSerials { get; } + + /// + /// Gets the number of pages that have been read in the container. + /// + [Obsolete("No longer supported.", true)] + int PagesRead { get; } + + /// + /// Event raised when a new logical stream is found in the container. + /// + [Obsolete("Moved to NewStreamCallback.", true)] + event EventHandler NewStream; + + /// + /// Initializes the container and finds the first stream. + /// + [Obsolete("Renamed to TryInit().", true)] + bool Init(); + + /// + /// Retrieves the total number of pages in the container. + /// + [Obsolete("No longer supported.", true)] + int GetTotalPageCount(); + } +} diff --git a/Assets/Plugins/NVorbis/IContainerReader.cs.meta b/Assets/Plugins/NVorbis/IContainerReader.cs.meta new file mode 100644 index 000000000..1aad5d497 --- /dev/null +++ b/Assets/Plugins/NVorbis/IContainerReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f82be722ba985af48b3484d2b2c988c7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/IPacketProvider.cs b/Assets/Plugins/NVorbis/IPacketProvider.cs new file mode 100644 index 000000000..72dee7768 --- /dev/null +++ b/Assets/Plugins/NVorbis/IPacketProvider.cs @@ -0,0 +1,47 @@ +using System; + +namespace NVorbis +{ + /// + /// Old interface, current version moved to Contracts.IPacketProvider + /// + [Obsolete("Moved to NVorbis.Contracts.IPacketProvider", true)] + public interface IPacketProvider : Contracts.IPacketProvider + { + /// + /// Gets the number of bits of overhead in this stream's container. + /// + [Obsolete("Moved to per-stream IStreamStats instance on IStreamDecoder.Stats or VorbisReader.Stats.", true)] + long ContainerBits { get; } + + /// + /// Retrieves the total number of pages (or frames) this stream uses. + /// + [Obsolete("No longer supported.", true)] + int GetTotalPageCount(); + + /// + /// Retrieves the packet specified from the stream. + /// + [Obsolete("Getting a packet by index is no longer supported.", true)] + DataPacket GetPacket(int packetIndex); + + /// + /// Finds the packet index to the granule position specified in the current stream. + /// + [Obsolete("Moved to long SeekTo(long, int, GetPacketGranuleCount)", true)] + DataPacket FindPacket(long granulePos, Func packetGranuleCountCallback); + + /// + /// Sets the next packet to be returned, applying a pre-roll as necessary. + /// + [Obsolete("Seeking to a specified packet is no longer supported. See SeekTo(...) instead.", true)] + void SeekToPacket(DataPacket packet, int preRoll); + + /// + /// Occurs when the stream is about to change parameters. + /// + [Obsolete("No longer supported.", true)] + event EventHandler ParameterChange; + } +} diff --git a/Assets/Plugins/NVorbis/IPacketProvider.cs.meta b/Assets/Plugins/NVorbis/IPacketProvider.cs.meta new file mode 100644 index 000000000..7de06ef14 --- /dev/null +++ b/Assets/Plugins/NVorbis/IPacketProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2344f5c12edb72d4d99a05fada46e9fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/IVorbisStreamStatus.cs b/Assets/Plugins/NVorbis/IVorbisStreamStatus.cs new file mode 100644 index 000000000..ad6b03895 --- /dev/null +++ b/Assets/Plugins/NVorbis/IVorbisStreamStatus.cs @@ -0,0 +1,47 @@ +using System; + +namespace NVorbis +{ + /// + /// Backwards compatibility type + /// + [Obsolete("Moved to NVorbis.Contracts.IStreamStats", true)] + public interface IVorbisStreamStatus : Contracts.IStreamStats + { + /// + /// Gets the calculated latency per page + /// + [Obsolete("No longer supported.", true)] + TimeSpan PageLatency { get; } + + /// + /// Gets the calculated latency per packet + /// + [Obsolete("No longer supported.", true)] + TimeSpan PacketLatency { get; } + + /// + /// Gets the calculated latency per second of output + /// + [Obsolete("No longer supported.", true)] + TimeSpan SecondLatency { get; } + + /// + /// Gets the number of pages read so far in the current stream + /// + [Obsolete("No longer supported.", true)] + int PagesRead { get; } + + /// + /// Gets the total number of pages in the current stream + /// + [Obsolete("No longer supported.", true)] + int TotalPages { get; } + + /// + /// Gets whether the stream has been clipped since the last reset + /// + [Obsolete("Use IStreamDecoder.HasClipped instead. VorbisReader.HasClipped will return the same value for the stream it is handling.", true)] + bool Clipped { get; } + } +} diff --git a/Assets/Plugins/NVorbis/IVorbisStreamStatus.cs.meta b/Assets/Plugins/NVorbis/IVorbisStreamStatus.cs.meta new file mode 100644 index 000000000..d77ab37b9 --- /dev/null +++ b/Assets/Plugins/NVorbis/IVorbisStreamStatus.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 14f20b191bfaf034b8fafc788d4136c2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Mapping.cs b/Assets/Plugins/NVorbis/Mapping.cs new file mode 100644 index 000000000..c0cf0b621 --- /dev/null +++ b/Assets/Plugins/NVorbis/Mapping.cs @@ -0,0 +1,200 @@ +using NVorbis.Contracts; +using System; + +namespace NVorbis +{ + class Mapping : IMapping + { + IMdct _mdct; + int[] _couplingAngle; + int[] _couplingMangitude; + IFloor[] _submapFloor; + IResidue[] _submapResidue; + IFloor[] _channelFloor; + IResidue[] _channelResidue; + + public void Init(IPacket packet, int channels, IFloor[] floors, IResidue[] residues, IMdct mdct) + { + var submapCount = 1; + if (packet.ReadBit()) + { + submapCount += (int)packet.ReadBits(4); + } + + // square polar mapping + var couplingSteps = 0; + if (packet.ReadBit()) + { + couplingSteps = (int)packet.ReadBits(8) + 1; + } + + var couplingBits = Utils.ilog(channels - 1); + _couplingAngle = new int[couplingSteps]; + _couplingMangitude = new int[couplingSteps]; + for (var j = 0; j < couplingSteps; j++) + { + var magnitude = (int)packet.ReadBits(couplingBits); + var angle = (int)packet.ReadBits(couplingBits); + if (magnitude == angle || magnitude > channels - 1 || angle > channels - 1) + { + throw new System.IO.InvalidDataException("Invalid magnitude or angle in mapping header!"); + } + _couplingAngle[j] = angle; + _couplingMangitude[j] = magnitude; + } + + if (0 != packet.ReadBits(2)) + { + throw new System.IO.InvalidDataException("Reserved bits not 0 in mapping header."); + } + + var mux = new int[channels]; + if (submapCount > 1) + { + for (var c = 0; c < channels; c++) + { + mux[c] = (int)packet.ReadBits(4); + if (mux[c] > submapCount) + { + throw new System.IO.InvalidDataException("Invalid channel mux submap index in mapping header!"); + } + } + } + + _submapFloor = new IFloor[submapCount]; + _submapResidue = new IResidue[submapCount]; + for (var j = 0; j < submapCount; j++) + { + packet.SkipBits(8); // unused placeholder + var floorNum = (int)packet.ReadBits(8); + if (floorNum >= floors.Length) + { + throw new System.IO.InvalidDataException("Invalid floor number in mapping header!"); + } + var residueNum = (int)packet.ReadBits(8); + if (residueNum >= residues.Length) + { + throw new System.IO.InvalidDataException("Invalid residue number in mapping header!"); + } + + _submapFloor[j] = floors[floorNum]; + _submapResidue[j] = residues[residueNum]; + } + + _channelFloor = new IFloor[channels]; + _channelResidue = new IResidue[channels]; + for (var c = 0; c < channels; c++) + { + _channelFloor[c] = _submapFloor[mux[c]]; + _channelResidue[c] = _submapResidue[mux[c]]; + } + + _mdct = mdct; + } + + public void DecodePacket(IPacket packet, int blockSize, int channels, float[][] buffer) + { + var halfBlockSize = blockSize >> 1; + + // read the noise floor data + var floorData = new IFloorData[_channelFloor.Length]; + var noExecuteChannel = new bool[_channelFloor.Length]; + for (var i = 0; i < _channelFloor.Length; i++) + { + floorData[i] = _channelFloor[i].Unpack(packet, blockSize, i); + noExecuteChannel[i] = !floorData[i].ExecuteChannel; + + // pre-clear the residue buffers + Array.Clear(buffer[i], 0, halfBlockSize); + } + + // make sure we handle no-energy channels correctly given the couplings.. + for (var i = 0; i < _couplingAngle.Length; i++) + { + if (floorData[_couplingAngle[i]].ExecuteChannel || floorData[_couplingMangitude[i]].ExecuteChannel) + { + floorData[_couplingAngle[i]].ForceEnergy = true; + floorData[_couplingMangitude[i]].ForceEnergy = true; + } + } + + // decode the submaps into the residue buffer + for (var i = 0; i < _submapFloor.Length; i++) + { + for (var j = 0; j < _channelFloor.Length; j++) + { + if (_submapFloor[i] != _channelFloor[j] || _submapResidue[i] != _channelResidue[j]) + { + // the submap doesn't match, so this floor doesn't contribute + floorData[j].ForceNoEnergy = true; + } + } + + _submapResidue[i].Decode(packet, noExecuteChannel, blockSize, buffer); + } + + // inverse coupling + for (var i = _couplingAngle.Length - 1; i >= 0; i--) + { + if (floorData[_couplingAngle[i]].ExecuteChannel || floorData[_couplingMangitude[i]].ExecuteChannel) + { + var magnitude = buffer[_couplingMangitude[i]]; + var angle = buffer[_couplingAngle[i]]; + + // we only have to do the first half; MDCT ignores the last half + for (var j = 0; j < halfBlockSize; j++) + { + float newM, newA; + + var oldM = magnitude[j]; + var oldA = angle[j]; + if (oldM > 0) + { + if (oldA > 0) + { + newM = oldM; + newA = oldM - oldA; + } + else + { + newA = oldM; + newM = oldM + oldA; + } + } + else + { + if (oldA > 0) + { + newM = oldM; + newA = oldM + oldA; + } + else + { + newA = oldM; + newM = oldM - oldA; + } + } + + magnitude[j] = newM; + angle[j] = newA; + } + } + } + + // apply floor / dot product / MDCT (only run if we have sound energy in that channel) + for (var c = 0; c < _channelFloor.Length; c++) + { + if (floorData[c].ExecuteChannel) + { + _channelFloor[c].Apply(floorData[c], blockSize, buffer[c]); + _mdct.Reverse(buffer[c], blockSize); + } + else + { + // since we aren't doing the IMDCT, we have to explicitly clear the back half of the block + Array.Clear(buffer[c], halfBlockSize, halfBlockSize); + } + } + } + } +} diff --git a/Assets/Plugins/NVorbis/Mapping.cs.meta b/Assets/Plugins/NVorbis/Mapping.cs.meta new file mode 100644 index 000000000..1254321d0 --- /dev/null +++ b/Assets/Plugins/NVorbis/Mapping.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 966590956ba1f3d4c981962e04fcbc03 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Mdct.cs b/Assets/Plugins/NVorbis/Mdct.cs new file mode 100644 index 000000000..28b1c970e --- /dev/null +++ b/Assets/Plugins/NVorbis/Mdct.cs @@ -0,0 +1,538 @@ +using NVorbis.Contracts; +using System; +using System.Collections.Generic; + +namespace NVorbis +{ + class Mdct : IMdct + { + const float M_PI = 3.14159265358979323846264f; + + Dictionary _setupCache = new Dictionary(); + + public void Reverse(float[] samples, int sampleCount) + { + if (!_setupCache.TryGetValue(sampleCount, out var impl)) + { + impl = new MdctImpl(sampleCount); + _setupCache[sampleCount] = impl; + } + impl.CalcReverse(samples); + } + + class MdctImpl + { + readonly int _n, _n2, _n4, _n8, _ld; + + readonly float[] _a, _b, _c; + readonly ushort[] _bitrev; + + public MdctImpl(int n) + { + _n = n; + _n2 = n >> 1; + _n4 = _n2 >> 1; + _n8 = _n4 >> 1; + + _ld = Utils.ilog(n) - 1; + + // first, calc the "twiddle factors" + _a = new float[_n2]; + _b = new float[_n2]; + _c = new float[_n4]; + int k, k2; + for (k = k2 = 0; k < _n4; ++k, k2 += 2) + { + _a[k2] = (float)Math.Cos(4 * k * M_PI / n); + _a[k2 + 1] = (float)-Math.Sin(4 * k * M_PI / n); + _b[k2] = (float)Math.Cos((k2 + 1) * M_PI / n / 2) * .5f; + _b[k2 + 1] = (float)Math.Sin((k2 + 1) * M_PI / n / 2) * .5f; + } + for (k = k2 = 0; k < _n8; ++k, k2 += 2) + { + _c[k2] = (float)Math.Cos(2 * (k2 + 1) * M_PI / n); + _c[k2 + 1] = (float)-Math.Sin(2 * (k2 + 1) * M_PI / n); + } + + // now, calc the bit reverse table + _bitrev = new ushort[_n8]; + for (int i = 0; i < _n8; ++i) + { + _bitrev[i] = (ushort)(Utils.BitReverse((uint)i, _ld - 3) << 2); + } + } + + internal void CalcReverse(float[] buffer) + { + float[] u, v; + + var buf2 = new float[_n2]; + + // copy and reflect spectral data + // step 0 + + { + var d = _n2 - 2; // buf2 + var AA = 0; // A + var e = 0; // buffer + var e_stop = _n2;// buffer + while (e != e_stop) + { + buf2[d + 1] = (buffer[e] * _a[AA] - buffer[e + 2] * _a[AA + 1]); + buf2[d] = (buffer[e] * _a[AA + 1] + buffer[e + 2] * _a[AA]); + d -= 2; + AA += 2; + e += 4; + } + + e = _n2 - 3; + while (d >= 0) + { + buf2[d + 1] = (-buffer[e + 2] * _a[AA] - -buffer[e] * _a[AA + 1]); + buf2[d] = (-buffer[e + 2] * _a[AA + 1] + -buffer[e] * _a[AA]); + d -= 2; + AA += 2; + e -= 4; + } + } + + // apply "symbolic" names + u = buffer; + v = buf2; + + // step 2 + + { + var AA = _n2 - 8; // A + + var e0 = _n4; // v + var e1 = 0; // v + + var d0 = _n4; // u + var d1 = 0; // u + + while (AA >= 0) + { + float v40_20, v41_21; + + v41_21 = v[e0 + 1] - v[e1 + 1]; + v40_20 = v[e0] - v[e1]; + u[d0 + 1] = v[e0 + 1] + v[e1 + 1]; + u[d0] = v[e0] + v[e1]; + u[d1 + 1] = v41_21 * _a[AA + 4] - v40_20 * _a[AA + 5]; + u[d1] = v40_20 * _a[AA + 4] + v41_21 * _a[AA + 5]; + + v41_21 = v[e0 + 3] - v[e1 + 3]; + v40_20 = v[e0 + 2] - v[e1 + 2]; + u[d0 + 3] = v[e0 + 3] + v[e1 + 3]; + u[d0 + 2] = v[e0 + 2] + v[e1 + 2]; + u[d1 + 3] = v41_21 * _a[AA] - v40_20 * _a[AA + 1]; + u[d1 + 2] = v40_20 * _a[AA] + v41_21 * _a[AA + 1]; + + AA -= 8; + + d0 += 4; + d1 += 4; + e0 += 4; + e1 += 4; + } + } + + // step 3 + + // iteration 0 + step3_iter0_loop(_n >> 4, u, _n2 - 1 - _n4 * 0, -_n8); + step3_iter0_loop(_n >> 4, u, _n2 - 1 - _n4 * 1, -_n8); + + // iteration 1 + step3_inner_r_loop(_n >> 5, u, _n2 - 1 - _n8 * 0, -(_n >> 4), 16); + step3_inner_r_loop(_n >> 5, u, _n2 - 1 - _n8 * 1, -(_n >> 4), 16); + step3_inner_r_loop(_n >> 5, u, _n2 - 1 - _n8 * 2, -(_n >> 4), 16); + step3_inner_r_loop(_n >> 5, u, _n2 - 1 - _n8 * 3, -(_n >> 4), 16); + + // iterations 2 ... x + var l = 2; + for (; l < (_ld - 3) >> 1; ++l) + { + var k0 = _n >> (l + 2); + var k0_2 = k0 >> 1; + var lim = 1 << (l + 1); + for (int i = 0; i < lim; ++i) + { + step3_inner_r_loop(_n >> (l + 4), u, _n2 - 1 - k0 * i, -k0_2, 1 << (l + 3)); + } + } + + // iterations x ... end + for (; l < _ld - 6; ++l) + { + var k0 = _n >> (l + 2); + var k1 = 1 << (l + 3); + var k0_2 = k0 >> 1; + var rlim = _n >> (l + 6); + var lim = 1 << l + 1; + var i_off = _n2 - 1; + var A0 = 0; + + for (int r = rlim; r > 0; --r) + { + step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); + A0 += k1 * 4; + i_off -= 8; + } + } + + // combine some iteration steps... + step3_inner_s_loop_ld654(_n >> 5, u, _n2 - 1, _n); + + // steps 4, 5, and 6 + { + var bit = 0; + + var d0 = _n4 - 4; // v + var d1 = _n2 - 4; // v + while (d0 >= 0) + { + int k4; + + k4 = _bitrev[bit]; + v[d1 + 3] = u[k4]; + v[d1 + 2] = u[k4 + 1]; + v[d0 + 3] = u[k4 + 2]; + v[d0 + 2] = u[k4 + 3]; + + k4 = _bitrev[bit + 1]; + v[d1 + 1] = u[k4]; + v[d1] = u[k4 + 1]; + v[d0 + 1] = u[k4 + 2]; + v[d0] = u[k4 + 3]; + + d0 -= 4; + d1 -= 4; + bit += 2; + } + } + + // step 7 + { + var c = 0; // C + var d = 0; // v + var e = _n2 - 4; // v + + while (d < e) + { + float a02, a11, b0, b1, b2, b3; + + a02 = v[d] - v[e + 2]; + a11 = v[d + 1] + v[e + 3]; + + b0 = _c[c + 1] * a02 + _c[c] * a11; + b1 = _c[c + 1] * a11 - _c[c] * a02; + + b2 = v[d] + v[e + 2]; + b3 = v[d + 1] - v[e + 3]; + + v[d] = b2 + b0; + v[d + 1] = b3 + b1; + v[e + 2] = b2 - b0; + v[e + 3] = b1 - b3; + + a02 = v[d + 2] - v[e]; + a11 = v[d + 3] + v[e + 1]; + + b0 = _c[c + 3] * a02 + _c[c + 2] * a11; + b1 = _c[c + 3] * a11 - _c[c + 2] * a02; + + b2 = v[d + 2] + v[e]; + b3 = v[d + 3] - v[e + 1]; + + v[d + 2] = b2 + b0; + v[d + 3] = b3 + b1; + v[e] = b2 - b0; + v[e + 1] = b1 - b3; + + c += 4; + d += 4; + e -= 4; + } + } + + // step 8 + decode + { + var b = _n2 - 8; // B + var e = _n2 - 8; // buf2 + var d0 = 0; // buffer + var d1 = _n2 - 4;// buffer + var d2 = _n2; // buffer + var d3 = _n - 4; // buffer + while (e >= 0) + { + float p0, p1, p2, p3; + + p3 = buf2[e + 6] * _b[b + 7] - buf2[e + 7] * _b[b + 6]; + p2 = -buf2[e + 6] * _b[b + 6] - buf2[e + 7] * _b[b + 7]; + + buffer[d0] = p3; + buffer[d1 + 3] = -p3; + buffer[d2] = p2; + buffer[d3 + 3] = p2; + + p1 = buf2[e + 4] * _b[b + 5] - buf2[e + 5] * _b[b + 4]; + p0 = -buf2[e + 4] * _b[b + 4] - buf2[e + 5] * _b[b + 5]; + + buffer[d0 + 1] = p1; + buffer[d1 + 2] = -p1; + buffer[d2 + 1] = p0; + buffer[d3 + 2] = p0; + + + p3 = buf2[e + 2] * _b[b + 3] - buf2[e + 3] * _b[b + 2]; + p2 = -buf2[e + 2] * _b[b + 2] - buf2[e + 3] * _b[b + 3]; + + buffer[d0 + 2] = p3; + buffer[d1 + 1] = -p3; + buffer[d2 + 2] = p2; + buffer[d3 + 1] = p2; + + p1 = buf2[e] * _b[b + 1] - buf2[e + 1] * _b[b]; + p0 = -buf2[e] * _b[b] - buf2[e + 1] * _b[b + 1]; + + buffer[d0 + 3] = p1; + buffer[d1] = -p1; + buffer[d2 + 3] = p0; + buffer[d3] = p0; + + b -= 8; + e -= 8; + d0 += 4; + d2 += 4; + d1 -= 4; + d3 -= 4; + } + } + } + + void step3_iter0_loop(int n, float[] e, int i_off, int k_off) + { + var ee0 = i_off; // e + var ee2 = ee0 + k_off; // e + var a = 0; + for (int i = n >> 2; i > 0; --i) + { + float k00_20, k01_21; + + k00_20 = e[ee0] - e[ee2]; + k01_21 = e[ee0 - 1] - e[ee2 - 1]; + e[ee0] += e[ee2]; + e[ee0 - 1] += e[ee2 - 1]; + e[ee2] = k00_20 * _a[a] - k01_21 * _a[a + 1]; + e[ee2 - 1] = k01_21 * _a[a] + k00_20 * _a[a + 1]; + a += 8; + + k00_20 = e[ee0 - 2] - e[ee2 - 2]; + k01_21 = e[ee0 - 3] - e[ee2 - 3]; + e[ee0 - 2] += e[ee2 - 2]; + e[ee0 - 3] += e[ee2 - 3]; + e[ee2 - 2] = k00_20 * _a[a] - k01_21 * _a[a + 1]; + e[ee2 - 3] = k01_21 * _a[a] + k00_20 * _a[a + 1]; + a += 8; + + k00_20 = e[ee0 - 4] - e[ee2 - 4]; + k01_21 = e[ee0 - 5] - e[ee2 - 5]; + e[ee0 - 4] += e[ee2 - 4]; + e[ee0 - 5] += e[ee2 - 5]; + e[ee2 - 4] = k00_20 * _a[a] - k01_21 * _a[a + 1]; + e[ee2 - 5] = k01_21 * _a[a] + k00_20 * _a[a + 1]; + a += 8; + + k00_20 = e[ee0 - 6] - e[ee2 - 6]; + k01_21 = e[ee0 - 7] - e[ee2 - 7]; + e[ee0 - 6] += e[ee2 - 6]; + e[ee0 - 7] += e[ee2 - 7]; + e[ee2 - 6] = k00_20 * _a[a] - k01_21 * _a[a + 1]; + e[ee2 - 7] = k01_21 * _a[a] + k00_20 * _a[a + 1]; + a += 8; + + ee0 -= 8; + ee2 -= 8; + } + } + + void step3_inner_r_loop(int lim, float[] e, int d0, int k_off, int k1) + { + float k00_20, k01_21; + + var e0 = d0; // e + var e2 = e0 + k_off; // e + int a = 0; + + for (int i = lim >> 2; i > 0; --i) + { + k00_20 = e[e0] - e[e2]; + k01_21 = e[e0 - 1] - e[e2 - 1]; + e[e0] += e[e2]; + e[e0 - 1] += e[e2 - 1]; + e[e2] = k00_20 * _a[a] - k01_21 * _a[a + 1]; + e[e2 - 1] = k01_21 * _a[a] + k00_20 * _a[a + 1]; + + a += k1; + + k00_20 = e[e0 - 2] - e[e2 - 2]; + k01_21 = e[e0 - 3] - e[e2 - 3]; + e[e0 - 2] += e[e2 - 2]; + e[e0 - 3] += e[e2 - 3]; + e[e2 - 2] = k00_20 * _a[a] - k01_21 * _a[a + 1]; + e[e2 - 3] = k01_21 * _a[a] + k00_20 * _a[a + 1]; + + a += k1; + + k00_20 = e[e0 - 4] - e[e2 - 4]; + k01_21 = e[e0 - 5] - e[e2 - 5]; + e[e0 - 4] += e[e2 - 4]; + e[e0 - 5] += e[e2 - 5]; + e[e2 - 4] = k00_20 * _a[a] - k01_21 * _a[a + 1]; + e[e2 - 5] = k01_21 * _a[a] + k00_20 * _a[a + 1]; + + a += k1; + + k00_20 = e[e0 - 6] - e[e2 - 6]; + k01_21 = e[e0 - 7] - e[e2 - 7]; + e[e0 - 6] += e[e2 - 6]; + e[e0 - 7] += e[e2 - 7]; + e[e2 - 6] = k00_20 * _a[a] - k01_21 * _a[a + 1]; + e[e2 - 7] = k01_21 * _a[a] + k00_20 * _a[a + 1]; + + a += k1; + + e0 -= 8; + e2 -= 8; + } + } + + void step3_inner_s_loop(int n, float[] e, int i_off, int k_off, int a, int a_off, int k0) + { + var A0 = _a[a]; + var A1 = _a[a + 1]; + var A2 = _a[a + a_off]; + var A3 = _a[a + a_off + 1]; + var A4 = _a[a + a_off * 2]; + var A5 = _a[a + a_off * 2 + 1]; + var A6 = _a[a + a_off * 3]; + var A7 = _a[a + a_off * 3 + 1]; + + float k00, k11; + + var ee0 = i_off; // e + var ee2 = ee0 + k_off; // e + + for (int i = n; i > 0; --i) + { + k00 = e[ee0] - e[ee2]; + k11 = e[ee0 - 1] - e[ee2 - 1]; + e[ee0] += e[ee2]; + e[ee0 - 1] += e[ee2 - 1]; + e[ee2] = k00 * A0 - k11 * A1; + e[ee2 - 1] = k11 * A0 + k00 * A1; + + k00 = e[ee0 - 2] - e[ee2 - 2]; + k11 = e[ee0 - 3] - e[ee2 - 3]; + e[ee0 - 2] += e[ee2 - 2]; + e[ee0 - 3] += e[ee2 - 3]; + e[ee2 - 2] = k00 * A2 - k11 * A3; + e[ee2 - 3] = k11 * A2 + k00 * A3; + + k00 = e[ee0 - 4] - e[ee2 - 4]; + k11 = e[ee0 - 5] - e[ee2 - 5]; + e[ee0 - 4] += e[ee2 - 4]; + e[ee0 - 5] += e[ee2 - 5]; + e[ee2 - 4] = k00 * A4 - k11 * A5; + e[ee2 - 5] = k11 * A4 + k00 * A5; + + k00 = e[ee0 - 6] - e[ee2 - 6]; + k11 = e[ee0 - 7] - e[ee2 - 7]; + e[ee0 - 6] += e[ee2 - 6]; + e[ee0 - 7] += e[ee2 - 7]; + e[ee2 - 6] = k00 * A6 - k11 * A7; + e[ee2 - 7] = k11 * A6 + k00 * A7; + + ee0 -= k0; + ee2 -= k0; + } + } + + void step3_inner_s_loop_ld654(int n, float[] e, int i_off, int base_n) + { + var a_off = base_n >> 3; + var A2 = _a[a_off]; + var z = i_off; // e + var @base = z - 16 * n; // e + + while (z > @base) + { + float k00, k11; + + k00 = e[z] - e[z - 8]; + k11 = e[z - 1] - e[z - 9]; + e[z] += e[z - 8]; + e[z - 1] += e[z - 9]; + e[z - 8] = k00; + e[z - 9] = k11; + + k00 = e[z - 2] - e[z - 10]; + k11 = e[z - 3] - e[z - 11]; + e[z - 2] += e[z - 10]; + e[z - 3] += e[z - 11]; + e[z - 10] = (k00 + k11) * A2; + e[z - 11] = (k11 - k00) * A2; + + k00 = e[z - 12] - e[z - 4]; + k11 = e[z - 5] - e[z - 13]; + e[z - 4] += e[z - 12]; + e[z - 5] += e[z - 13]; + e[z - 12] = k11; + e[z - 13] = k00; + + k00 = e[z - 14] - e[z - 6]; + k11 = e[z - 7] - e[z - 15]; + e[z - 6] += e[z - 14]; + e[z - 7] += e[z - 15]; + e[z - 14] = (k00 + k11) * A2; + e[z - 15] = (k00 - k11) * A2; + + iter_54(e, z); + iter_54(e, z - 8); + + z -= 16; + } + } + + private void iter_54(float[] e, int z) + { + float k00, k11, k22, k33; + float y0, y1, y2, y3; + + k00 = e[z] - e[z - 4]; + y0 = e[z] + e[z - 4]; + y2 = e[z - 2] + e[z - 6]; + k22 = e[z - 2] - e[z - 6]; + + e[z] = y0 + y2; + e[z - 2] = y0 - y2; + + k33 = e[z - 3] - e[z - 7]; + + e[z - 4] = k00 + k33; + e[z - 6] = k00 - k33; + + k11 = e[z - 1] - e[z - 5]; + y1 = e[z - 1] + e[z - 5]; + y3 = e[z - 3] + e[z - 7]; + + e[z - 1] = y1 + y3; + e[z - 3] = y1 - y3; + e[z - 5] = k11 - k22; + e[z - 7] = k11 + k22; + } + } + } +} diff --git a/Assets/Plugins/NVorbis/Mdct.cs.meta b/Assets/Plugins/NVorbis/Mdct.cs.meta new file mode 100644 index 000000000..5df2cfc28 --- /dev/null +++ b/Assets/Plugins/NVorbis/Mdct.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 78fb1c4578bb90240817e37ed39f7058 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Mode.cs b/Assets/Plugins/NVorbis/Mode.cs new file mode 100644 index 000000000..932454d3a --- /dev/null +++ b/Assets/Plugins/NVorbis/Mode.cs @@ -0,0 +1,178 @@ +using NVorbis.Contracts; +using System; + +namespace NVorbis +{ + class Mode : IMode + { + private struct OverlapInfo + { + public int PacketStartIndex; + public int PacketTotalLength; + public int PacketValidLength; + } + + const float M_PI2 = 3.1415926539f / 2; + + int _channels; + bool _blockFlag; + int _blockSize; + IMapping _mapping; + float[][] _windows; + OverlapInfo[] _overlapInfo; + + public void Init(IPacket packet, int channels, int block0Size, int block1Size, IMapping[] mappings) + { + _channels = channels; + + _blockFlag = packet.ReadBit(); + if (0 != packet.ReadBits(32)) + { + throw new System.IO.InvalidDataException("Mode header had invalid window or transform type!"); + } + + var mappingIdx = (int)packet.ReadBits(8); + if (mappingIdx >= mappings.Length) + { + throw new System.IO.InvalidDataException("Mode header had invalid mapping index!"); + } + _mapping = mappings[mappingIdx]; + + if (_blockFlag) + { + _blockSize = block1Size; + _windows = new float[][] + { + CalcWindow(block0Size, block1Size, block0Size), + CalcWindow(block1Size, block1Size, block0Size), + CalcWindow(block0Size, block1Size, block1Size), + CalcWindow(block1Size, block1Size, block1Size), + }; + _overlapInfo = new OverlapInfo[] + { + CalcOverlap(block0Size, block1Size, block0Size), + CalcOverlap(block1Size, block1Size, block0Size), + CalcOverlap(block0Size, block1Size, block1Size), + CalcOverlap(block1Size, block1Size, block1Size), + }; + } + else + { + _blockSize = block0Size; + _windows = new float[][] + { + CalcWindow(block0Size, block0Size, block0Size), + }; + } + } + + private static float[] CalcWindow(int prevBlockSize, int blockSize, int nextBlockSize) + { + var array = new float[blockSize]; + + var left = prevBlockSize / 2; + var wnd = blockSize; + var right = nextBlockSize / 2; + + var leftbegin = wnd / 4 - left / 2; + var rightbegin = wnd - wnd / 4 - right / 2; + + for (int i = 0; i < left; i++) + { + var x = (float)Math.Sin((i + .5) / left * M_PI2); + x *= x; + array[leftbegin + i] = (float)Math.Sin(x * M_PI2); + } + + for (int i = leftbegin + left; i < rightbegin; i++) + { + array[i] = 1.0f; + } + + for (int i = 0; i < right; i++) + { + var x = (float)Math.Sin((right - i - .5) / right * M_PI2); + x *= x; + array[rightbegin + i] = (float)Math.Sin(x * M_PI2); + } + + return array; + } + + private static OverlapInfo CalcOverlap(int prevBlockSize, int blockSize, int nextBlockSize) + { + var leftOverlapHalfSize = prevBlockSize / 4; + var rightOverlapHalfSize = nextBlockSize / 4; + + var packetStartIndex = blockSize / 4 - leftOverlapHalfSize; + var packetTotalLength = blockSize / 4 * 3 + rightOverlapHalfSize; + var packetValidLength = packetTotalLength - rightOverlapHalfSize * 2; + + return new OverlapInfo + { + PacketStartIndex = packetStartIndex, + PacketValidLength = packetValidLength, + PacketTotalLength = packetTotalLength, + }; + } + + private bool GetPacketInfo(IPacket packet, out int windowIndex, out int packetStartIndex, out int packetValidLength, out int packetTotalLength) + { + if (packet.IsShort) + { + windowIndex = 0; + packetStartIndex = 0; + packetValidLength = 0; + packetTotalLength = 0; + return false; + } + + if (_blockFlag) + { + var prevFlag = packet.ReadBit(); + var nextFlag = packet.ReadBit(); + + windowIndex = (prevFlag ? 1 : 0) + (nextFlag ? 2 : 0); + + var overlapInfo = _overlapInfo[windowIndex]; + packetStartIndex = overlapInfo.PacketStartIndex; + packetValidLength = overlapInfo.PacketValidLength; + packetTotalLength = overlapInfo.PacketTotalLength; + } + else + { + windowIndex = 0; + packetStartIndex = 0; + packetValidLength = _blockSize / 2; + packetTotalLength = _blockSize; + } + + return true; + } + + public bool Decode(IPacket packet, float[][] buffer, out int packetStartindex, out int packetValidLength, out int packetTotalLength) + { + if (GetPacketInfo(packet, out var windowIndex, out packetStartindex, out packetValidLength, out packetTotalLength)) + { + _mapping.DecodePacket(packet, _blockSize, _channels, buffer); + + var window = _windows[windowIndex]; + for (var i = 0; i < _blockSize; i++) + { + for (var ch = 0; ch < _channels; ch++) + { + buffer[ch][i] *= window[i]; + } + } + return true; + } + return false; + } + + public int GetPacketSampleCount(IPacket packet) + { + GetPacketInfo(packet, out _, out var packetStartIndex, out var packetValidLength, out _); + return packetValidLength - packetStartIndex; + } + } +} diff --git a/Assets/Plugins/NVorbis/Mode.cs.meta b/Assets/Plugins/NVorbis/Mode.cs.meta new file mode 100644 index 000000000..d7774ee45 --- /dev/null +++ b/Assets/Plugins/NVorbis/Mode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 38e50bc5e6ad05a4ebfcf4d876d2bc76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/NVorbis.csproj.meta b/Assets/Plugins/NVorbis/NVorbis.csproj.meta new file mode 100644 index 000000000..ad38bcbcf --- /dev/null +++ b/Assets/Plugins/NVorbis/NVorbis.csproj.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 47d16d407bf61e246a2bdbfac66f0ec7 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/NewStreamEventArgs.cs b/Assets/Plugins/NVorbis/NewStreamEventArgs.cs new file mode 100644 index 000000000..54f5057c7 --- /dev/null +++ b/Assets/Plugins/NVorbis/NewStreamEventArgs.cs @@ -0,0 +1,31 @@ +using NVorbis.Contracts; +using System; + +namespace NVorbis +{ + /// + /// Event data for when a new logical stream is found in a container. + /// + [Serializable] + public class NewStreamEventArgs : EventArgs + { + /// + /// Creates a new instance of with the specified . + /// + /// An instance. + public NewStreamEventArgs(IStreamDecoder streamDecoder) + { + StreamDecoder = streamDecoder ?? throw new ArgumentNullException(nameof(streamDecoder)); + } + + /// + /// Gets new the instance. + /// + public IStreamDecoder StreamDecoder { get; } + + /// + /// Gets or sets whether to ignore the logical stream associated with the packet provider. + /// + public bool IgnoreStream { get; set; } + } +} diff --git a/Assets/Plugins/NVorbis/NewStreamEventArgs.cs.meta b/Assets/Plugins/NVorbis/NewStreamEventArgs.cs.meta new file mode 100644 index 000000000..3ba3e3bc9 --- /dev/null +++ b/Assets/Plugins/NVorbis/NewStreamEventArgs.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3e5380a6e3868ee4a9700936f62602c5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg.meta b/Assets/Plugins/NVorbis/Ogg.meta new file mode 100644 index 000000000..824f5ad72 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d3275dc33d250b44aa13096b05ab05ba +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg/ContainerReader.cs b/Assets/Plugins/NVorbis/Ogg/ContainerReader.cs new file mode 100644 index 000000000..3a76b4ce5 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/ContainerReader.cs @@ -0,0 +1,151 @@ +using NVorbis.Contracts; +using NVorbis.Contracts.Ogg; +using System; +using System.Collections.Generic; +using System.IO; + +namespace NVorbis.Ogg +{ + /// + /// Implements for Ogg format files for low memory cost. + /// + public sealed class ContainerReader : Contracts.IContainerReader + { + internal static Func, IPageReader> CreatePageReader { get; set; } = (s, cod, cb) => new PageReader(s, cod, cb); + internal static Func, IPageReader> CreateForwardOnlyPageReader { get; set; } = (s, cod, cb) => new ForwardOnlyPageReader(s, cod, cb); + + private IPageReader _reader; + private List> _packetProviders; + private bool _foundStream; + + /// + /// Gets or sets the callback to invoke when a new stream is encountered in the container. + /// + public NewStreamHandler NewStreamCallback { get; set; } + + /// + /// Returns a list of streams available from this container. + /// + public IReadOnlyList GetStreams() + { + var list = new List(_packetProviders.Count); + for (var i = 0; i < _packetProviders.Count; i++) + { + if (_packetProviders[i].TryGetTarget(out var pp)) + { + list.Add(pp); + } + else + { + list.RemoveAt(i); + --i; + } + } + return list; + } + + /// + /// Gets whether the underlying stream can seek. + /// + public bool CanSeek { get; } + + /// + /// Gets the number of bits in the container that are not associated with a logical stream. + /// + public long WasteBits => _reader.WasteBits; + + /// + /// Gets the number of bits in the container that are strictly for framing of logical streams. + /// + public long ContainerBits => _reader.ContainerBits; + + + /// + /// Creates a new instance of . + /// + /// The to read. + /// True to close the stream when disposed, otherwise false. + /// 's is False. + public ContainerReader(Stream stream, bool closeOnDispose) + { + if (stream == null) throw new ArgumentNullException(nameof(stream)); + + _packetProviders = new List>(); + + if (stream.CanSeek) + { + _reader = CreatePageReader(stream, closeOnDispose, ProcessNewStream); + CanSeek = true; + } + else + { + _reader = CreateForwardOnlyPageReader(stream, closeOnDispose, ProcessNewStream); + } + } + + /// + /// Attempts to initialize the container. + /// + /// if successful, otherwise . + public bool TryInit() + { + return FindNextStream(); + } + + /// + /// Finds the next new stream in the container. + /// + /// True if a new stream was found, otherwise False. + public bool FindNextStream() + { + _reader.Lock(); + try + { + _foundStream = false; + while (_reader.ReadNextPage()) + { + if (_foundStream) + { + return true; + } + } + return false; + } + finally + { + _reader.Release(); + } + } + + private bool ProcessNewStream(Contracts.IPacketProvider packetProvider) + { + var relock = _reader.Release(); + try + { + if (NewStreamCallback?.Invoke(packetProvider) ?? true) + { + _packetProviders.Add(new WeakReference(packetProvider)); + _foundStream = true; + return true; + } + return false; + } + finally + { + if (relock) + { + _reader.Lock(); + } + } + } + + /// + /// Cleans up + /// + public void Dispose() + { + _reader?.Dispose(); + _reader = null; + } + } +} diff --git a/Assets/Plugins/NVorbis/Ogg/ContainerReader.cs.meta b/Assets/Plugins/NVorbis/Ogg/ContainerReader.cs.meta new file mode 100644 index 000000000..53539b4c0 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/ContainerReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c2a2b59fd7ea4e4082333c067942aac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg/Crc.cs b/Assets/Plugins/NVorbis/Ogg/Crc.cs new file mode 100644 index 000000000..9713c1537 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/Crc.cs @@ -0,0 +1,44 @@ +namespace NVorbis.Ogg +{ + class Crc : Contracts.Ogg.ICrc + { + const uint CRC32_POLY = 0x04c11db7; + static readonly uint[] s_crcTable; + + static Crc() + { + s_crcTable = new uint[256]; + for (uint i = 0; i < 256; i++) + { + uint s = i << 24; + for (int j = 0; j < 8; ++j) + { + s = (s << 1) ^ (s >= (1U << 31) ? CRC32_POLY : 0); + } + s_crcTable[i] = s; + } + } + + uint _crc; + + public Crc() + { + Reset(); + } + + public void Reset() + { + _crc = 0U; + } + + public void Update(int nextVal) + { + _crc = (_crc << 8) ^ s_crcTable[nextVal ^ (_crc >> 24)]; + } + + public bool Test(uint checkCrc) + { + return _crc == checkCrc; + } + } +} diff --git a/Assets/Plugins/NVorbis/Ogg/Crc.cs.meta b/Assets/Plugins/NVorbis/Ogg/Crc.cs.meta new file mode 100644 index 000000000..55cd304cc --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/Crc.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 44b3576a7068b5a4ebda2a6cd9fca9a9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPacketProvider.cs b/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPacketProvider.cs new file mode 100644 index 000000000..e31a8dd2d --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPacketProvider.cs @@ -0,0 +1,324 @@ +using NVorbis.Contracts; +using NVorbis.Contracts.Ogg; +using System; +using System.Collections.Generic; + +namespace NVorbis.Ogg +{ + class ForwardOnlyPacketProvider : DataPacket, IForwardOnlyPacketProvider + { + private int _lastSeqNo; + private readonly Queue<(byte[] buf, bool isResync)> _pageQueue = new Queue<(byte[] buf, bool isResync)>(); + + private readonly IPageReader _reader; + private byte[] _pageBuf; + private int _packetIndex; + private bool _isEndOfStream; + private int _dataStart; + private bool _lastWasPeek; + + private Memory _packetBuf; + + private int _dataIndex; + + public ForwardOnlyPacketProvider(IPageReader reader, int streamSerial) + { + _reader = reader; + StreamSerial = streamSerial; + + // force the first page to read + _packetIndex = int.MaxValue; + } + + public bool CanSeek => false; + + public int StreamSerial { get; } + + public bool AddPage(byte[] buf, bool isResync) + { + if (((PageFlags)buf[5] & PageFlags.BeginningOfStream) != 0) + { + if (_isEndOfStream) + { + return false; + } + isResync = true; + _lastSeqNo = BitConverter.ToInt32(buf, 18); + } + else + { + // check the sequence number + var seqNo = BitConverter.ToInt32(buf, 18); + isResync |= seqNo != _lastSeqNo + 1; + _lastSeqNo = seqNo; + } + + // there must be at least one packet with data + var ttl = 0; + for (var i = 0; i < buf[26]; i++) + { + ttl += buf[27 + i]; + } + if (ttl == 0) + { + return false; + } + + _pageQueue.Enqueue((buf, isResync)); + return true; + } + + public void SetEndOfStream() + { + _isEndOfStream = true; + } + + public IPacket GetNextPacket() + { + // if not done... + if (_packetBuf.Length > 0) + { + // only allow if last call was for peek + if (!_lastWasPeek) throw new InvalidOperationException("Must call Done() on previous packet first."); + + // then return ourself, noting that we didn't peek the packet + _lastWasPeek = false; + return this; + } + + // always advance to the next packet + _lastWasPeek = false; + if (GetPacket()) + { + return this; + } + return null; + } + + public IPacket PeekNextPacket() + { + // if not done... + if (_packetBuf.Length > 0) + { + // only allow if last call was for peek + if (!_lastWasPeek) throw new InvalidOperationException("Must call Done() on previous packet first."); + + // then just return ourself + return this; + } + + // use a local variable to throw away the updated position + _lastWasPeek = true; + if (GetPacket()) + { + return this; + } + return null; + } + + private bool GetPacket() + { + // if we don't already have a page, grab it + byte[] pageBuf; + bool isResync; + int dataStart; + int packetIndex; + bool isCont, isCntd; + if (_pageBuf != null && _packetIndex < 27 + _pageBuf[26]) + { + pageBuf = _pageBuf; + isResync = false; + dataStart = _dataStart; + packetIndex = _packetIndex; + isCont = false; + isCntd = pageBuf[26 + pageBuf[26]] == 255; + } + else + { + if (!ReadNextPage(out pageBuf, out isResync, out dataStart, out packetIndex, out isCont, out isCntd)) + { + // couldn't read the next page... + return false; + } + } + + // first, set flags from the start page + var contOverhead = dataStart; + var isFirst = packetIndex == 27; + if (isCont) + { + if (isFirst) + { + // if it's a continuation, we just read it for a new packet and there's a continuity problem + isResync = true; + + // skip the first packet; it's a partial + contOverhead += GetPacketLength(pageBuf, ref packetIndex); + + // if we moved to the end of the page, we can't satisfy the request from here... + if (packetIndex == 27 + pageBuf[26]) + { + // ... so we'll just recurse and try again + return GetPacket(); + } + } + } + if (!isFirst) + { + contOverhead = 0; + } + + // second, determine how long the packet is + var dataLen = GetPacketLength(pageBuf, ref packetIndex); + var packetBuf = new Memory(pageBuf, dataStart, dataLen); + dataStart += dataLen; + + // third, determine if the packet is the last one in the page + var isLast = packetIndex == 27 + pageBuf[26]; + if (isCntd) + { + if (isLast) + { + // we're on the continued packet, so it really counts with the next page + isLast = false; + } + else + { + // whelp, not quite... gotta account for the continued packet + var pi = packetIndex; + GetPacketLength(pageBuf, ref pi); + isLast = pi == 27 + pageBuf[26]; + } + } + + // forth, if it is the last one, process continuations or flags & granulePos + var isEos = false; + long? granulePos = null; + if (isLast) + { + granulePos = BitConverter.ToInt64(pageBuf, 6); + + // fifth, set flags from the end page + if (((PageFlags)pageBuf[5] & PageFlags.EndOfStream) != 0 || (_isEndOfStream && _pageQueue.Count == 0)) + { + isEos = true; + } + } + else + { + while (isCntd && packetIndex == 27 + pageBuf[26]) + { + if (ReadNextPage(out pageBuf, out isResync, out dataStart, out packetIndex, out isCont, out isCntd) && !isResync && isCont) + { + // we're in the right spot! + + // update the overhead count + contOverhead += 27 + pageBuf[26]; + + // save off the previous buffer data + var prevBuf = packetBuf; + + // get the size of this page's portion + var contSz = GetPacketLength(pageBuf, ref packetIndex); + + // set up the new buffer and fill it + packetBuf = new Memory(new byte[prevBuf.Length + contSz]); + prevBuf.CopyTo(packetBuf); + (new Memory(pageBuf, dataStart, contSz)).CopyTo(packetBuf.Slice(prevBuf.Length)); + + // now that we've read, update our start position + dataStart += contSz; + } + else + { + // just use what data we can... + break; + } + } + } + + // last, save off our state and return true + IsResync = isResync; + GranulePosition = granulePos; + IsEndOfStream = isEos; + ContainerOverheadBits = contOverhead * 8; + _pageBuf = pageBuf; + _dataStart = dataStart; + _packetIndex = packetIndex; + _packetBuf = packetBuf; + _isEndOfStream |= isEos; + Reset(); + return true; + } + + private bool ReadNextPage(out byte[] pageBuf, out bool isResync, out int dataStart, out int packetIndex, out bool isContinuation, out bool isContinued) + { + while (_pageQueue.Count == 0) + { + if (_isEndOfStream || !_reader.ReadNextPage()) + { + // we must be done + pageBuf = null; + isResync = false; + dataStart = 0; + packetIndex = 0; + isContinuation = false; + isContinued = false; + return false; + } + } + + var temp = _pageQueue.Dequeue(); + pageBuf = temp.buf; + isResync = temp.isResync; + + dataStart = pageBuf[26] + 27; + packetIndex = 27; + isContinuation = ((PageFlags)pageBuf[5] & PageFlags.ContinuesPacket) != 0; + isContinued = pageBuf[26 + pageBuf[26]] == 255; + return true; + } + + private int GetPacketLength(byte[] pageBuf, ref int packetIndex) + { + var len = 0; + while (pageBuf[packetIndex] == 255 && packetIndex < pageBuf[26] + 27) + { + len += pageBuf[packetIndex]; + ++packetIndex; + } + if (packetIndex < pageBuf[26] + 27) + { + len += pageBuf[packetIndex]; + ++packetIndex; + } + return len; + } + + protected override int TotalBits => _packetBuf.Length * 8; + + protected override int ReadNextByte() + { + if (_dataIndex < _packetBuf.Length) + { + return _packetBuf.Span[_dataIndex++]; + } + return -1; + } + + public override void Reset() + { + _dataIndex = 0; + base.Reset(); + } + + public override void Done() + { + _packetBuf = Memory.Empty; + base.Done(); + } + + long Contracts.IPacketProvider.GetGranuleCount() => throw new NotSupportedException(); + long Contracts.IPacketProvider.SeekTo(long granulePos, int preRoll, GetPacketGranuleCount getPacketGranuleCount) => throw new NotSupportedException(); + } +} diff --git a/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPacketProvider.cs.meta b/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPacketProvider.cs.meta new file mode 100644 index 000000000..fbc5410e7 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPacketProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2aef5ca41c80fa747bec77a8695cabeb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPageReader.cs b/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPageReader.cs new file mode 100644 index 000000000..a2c9aa416 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPageReader.cs @@ -0,0 +1,67 @@ +using NVorbis.Contracts.Ogg; +using System; +using System.Collections.Generic; +using System.IO; + +namespace NVorbis.Ogg +{ + class ForwardOnlyPageReader : PageReaderBase + { + internal static Func CreatePacketProvider { get; set; } = (pr, ss) => new ForwardOnlyPacketProvider(pr, ss); + + private readonly Dictionary _packetProviders = new Dictionary(); + private readonly Func _newStreamCallback; + + public ForwardOnlyPageReader(Stream stream, bool closeOnDispose, Func newStreamCallback) + : base(stream, closeOnDispose) + { + _newStreamCallback = newStreamCallback; + } + + protected override bool AddPage(int streamSerial, byte[] pageBuf, bool isResync) + { + if (_packetProviders.TryGetValue(streamSerial, out var pp)) + { + // try to add the page... + if (pp.AddPage(pageBuf, isResync)) + { + // ..., then check to see if this is the end of the stream... + if (((PageFlags)pageBuf[5] & PageFlags.EndOfStream) != 0) + { + // ... and if so tell the packet provider the remove it from our list + pp.SetEndOfStream(); + _packetProviders.Remove(streamSerial); + } + // ..., then let our caller know we're good + return true; + } + // otherwise, let PageReaderBase.ReadNextPage() know that we can't use the page: + return false; + } + + // we don't already have the stream, so try to add it to the list. + pp = CreatePacketProvider(this, streamSerial); + if (pp.AddPage(pageBuf, isResync)) + { + _packetProviders.Add(streamSerial, pp); + if (_newStreamCallback(pp)) + { + return true; + } + _packetProviders.Remove(streamSerial); + } + return false; + } + + protected override void SetEndOfStreams() + { + foreach (var kvp in _packetProviders) + { + kvp.Value.SetEndOfStream(); + } + _packetProviders.Clear(); + } + + public override bool ReadPageAt(long offset) => throw new NotSupportedException(); + } +} diff --git a/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPageReader.cs.meta b/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPageReader.cs.meta new file mode 100644 index 000000000..893ac4eb5 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/ForwardOnlyPageReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ac5ee9e67796c5246afcf515c18e0d6c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg/Packet.cs b/Assets/Plugins/NVorbis/Ogg/Packet.cs new file mode 100644 index 000000000..746c0cfdb --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/Packet.cs @@ -0,0 +1,74 @@ +using NVorbis.Contracts.Ogg; +using System; +using System.Collections.Generic; + +namespace NVorbis.Ogg +{ + internal class Packet : DataPacket + { + // size with 1-2 packet segments (> 2 packet segments should be very uncommon): + // x86: 68 bytes + // x64: 104 bytes + + // this is the list of pages & packets in packed 24:8 format + // in theory, this is good for up to 1016 GiB of Ogg file + // in practice, probably closer to 300 days @ 160k bps + private IReadOnlyList _dataParts; + private IPacketReader _packetReader; // IntPtr + int _dataCount; + Memory _data; + int _dataIndex; // 4 + int _dataOfs; // 4 + + internal Packet(IReadOnlyList dataParts, IPacketReader packetReader, Memory initialData) + { + _dataParts = dataParts; + _packetReader = packetReader; + _data = initialData; + } + + protected override int TotalBits => (_dataCount + _data.Length) * 8; + + protected override int ReadNextByte() + { + if (_dataIndex == _dataParts.Count) return -1; + + var b = _data.Span[_dataOfs]; + + if (++_dataOfs == _data.Length) + { + _dataOfs = 0; + _dataCount += _data.Length; + if (++_dataIndex < _dataParts.Count) + { + _data = _packetReader.GetPacketData(_dataParts[_dataIndex]); + } + else + { + _data = Memory.Empty; + } + } + + return b; + } + + public override void Reset() + { + _dataIndex = 0; + _dataOfs = 0; + if (_dataParts.Count > 0) + { + _data = _packetReader.GetPacketData(_dataParts[0]); + } + + base.Reset(); + } + + public override void Done() + { + _packetReader?.InvalidatePacketCache(this); + + base.Done(); + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/NVorbis/Ogg/Packet.cs.meta b/Assets/Plugins/NVorbis/Ogg/Packet.cs.meta new file mode 100644 index 000000000..7bf85ead2 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/Packet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 566e8cb97479cab4ab24c7c66a40a3cd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg/PacketProvider.cs b/Assets/Plugins/NVorbis/Ogg/PacketProvider.cs new file mode 100644 index 000000000..82183c8d5 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/PacketProvider.cs @@ -0,0 +1,461 @@ +using NVorbis.Contracts; +using NVorbis.Contracts.Ogg; +using System; +using System.Collections.Generic; + +namespace NVorbis.Ogg +{ + class PacketProvider : Contracts.IPacketProvider, IPacketReader + { + private IStreamPageReader _reader; + + private int _pageIndex; + private int _packetIndex; + + private int _lastPacketPageIndex; + private int _lastPacketPacketIndex; + private Packet _lastPacket; + private int _nextPacketPageIndex; + private int _nextPacketPacketIndex; + + public bool CanSeek => true; + + public int StreamSerial { get; } + + internal PacketProvider(IStreamPageReader reader, int streamSerial) + { + _reader = reader ?? throw new ArgumentNullException(nameof(reader)); + + StreamSerial = streamSerial; + } + + public long GetGranuleCount() + { + if (_reader == null) throw new ObjectDisposedException(nameof(PacketProvider)); + + if (!_reader.HasAllPages) + { + // this will force the reader to attempt to read all pages + _reader.GetPage(int.MaxValue, out _, out _, out _, out _, out _, out _); + } + return _reader.MaxGranulePosition.Value; + } + + public IPacket GetNextPacket() + { + return GetNextPacket(ref _pageIndex, ref _packetIndex); + } + + public IPacket PeekNextPacket() + { + var pageIndex = _pageIndex; + var packetIndex = _packetIndex; + return GetNextPacket(ref pageIndex, ref packetIndex); + } + + public long SeekTo(long granulePos, int preRoll, GetPacketGranuleCount getPacketGranuleCount) + { + if (_reader == null) throw new ObjectDisposedException(nameof(PacketProvider)); + + int pageIndex = _reader.FindPage(granulePos); + int packetIndex = FindPacket(pageIndex, preRoll, ref granulePos, getPacketGranuleCount); + + if (!NormalizePacketIndex(ref pageIndex, ref packetIndex)) + { + throw new ArgumentOutOfRangeException(nameof(granulePos)); + } + + _lastPacket = null; + _pageIndex = pageIndex; + _packetIndex = packetIndex; + return granulePos; + } + + private (long lastPageGranulePos, int lastPagePacketLength, int firstRealPacket) GetPreviousPageInfo(int pageIndex, GetPacketGranuleCount getPacketGranuleCount) + { + if (pageIndex > 0) + { + int lastPagePacketLength; + if (_reader.GetPage(pageIndex - 1, out var lastPageGranulePos, out _, out _, out var isContinued, out var lastPacketCount, out _)) + { + if (pageIndex > _reader.FirstDataPageIndex) + { + --pageIndex; + var lastPacketIndex = lastPacketCount - 1; + // this will either be a continued packet OR the last packet of the last page + // in both cases that's precisely the value we need + var lastPacket = CreatePacket(ref pageIndex, ref lastPacketIndex, false, 0, false, isContinued, lastPacketCount, 0); + if (lastPacket == null) + { + throw new System.IO.InvalidDataException("Could not find end of continuation!"); + } + lastPagePacketLength = getPacketGranuleCount(lastPacket); + } + else + { + lastPagePacketLength = 0; + } + return (lastPageGranulePos, lastPagePacketLength, isContinued ? 1 : 0); + } + throw new System.IO.InvalidDataException("Could not get preceding page?!"); + } + else + { + return (0, 0, 0); + } + } + + private (long[] gps, long endGP) GetTargetPageInfo(int pageIndex, int firstRealPacket, int lastPagePacketLength, GetPacketGranuleCount getPacketGranuleCount) + { + if (!_reader.GetPage(pageIndex, out var pageGranulePos, out var isResync, out var isContinuation, out var isContinued, out var packetCount, out _)) + { + throw new System.IO.InvalidDataException("Could not get found page?!"); + } + + if (isContinued) + { + // if continued, the last packet index doesn't apply + packetCount--; + } + + // get the granule positions of all packets in the page + var gps = new long[packetCount]; + var endGP = pageGranulePos; + for (var i = packetCount - 1; i >= firstRealPacket; i--) + { + gps[i] = endGP; + + // it would be nice to pass false instead of isContinued, but (hypothetically) we don't know if getPacketGranuleCount(...) needs the whole thing... + // Vorbis doesn't, but someone might decide to try to use us for another purpose so we'll be good here. + var packet = CreatePacket(ref pageIndex, ref i, false, pageGranulePos, i == 0 && isResync, isContinued, packetCount, 0); + if (packet == null) + { + throw new System.IO.InvalidDataException("Could not find end of continuation!"); + } + endGP -= getPacketGranuleCount(packet); + } + + // if we're contnued, the the continued packet ends on our calcualted endGP + if (firstRealPacket == 1) + { + gps[0] = endGP; + endGP -= lastPagePacketLength; + } + + return (gps, endGP); + } + + private int FindPacket(int pageIndex, long[] gps, long endGP, long lastPageGranulePos, int lastPagePacketLength, ref long granulePos) + { + // next check for a bugged vorbis encoder... + if (endGP != lastPageGranulePos) + { + var diff = endGP - lastPageGranulePos; + if (GetIsVorbisBugDiff(diff)) + { + if (diff > 0) + { + // the last packet in the last page is a long block that was mis-counted by libvorbis + // if the requested granulePos is <= endGP, it's in that packet + // otherwise, the normal logic should be fine + // NOTE that this bug does not appear to happen on a continued packet, which makes this safe + if (granulePos <= endGP) + { + granulePos = endGP - lastPagePacketLength; + return -1; + } + } + else + { + // our pageGranulePos is wrong, so adjust everything and let the normal logic apply + for (var i = 0; i < gps.Length; i++) + { + gps[i] -= diff; + } + } + } + // if we're not on the first page, there's a problem... + // technically there could still be a problem on the first page, but we're ignoring it + else if (pageIndex > _reader.FirstDataPageIndex) + { + // unknown error... + throw new System.IO.InvalidDataException($"GranulePos mismatch: Page {pageIndex}, expected {lastPageGranulePos}, calculated {endGP}"); + } + } + + // finally, find the packet with the requested granulePos + for (var i = 0; i < gps.Length; i++) + { + if (gps[i] >= granulePos) + { + if (i == 0) + { + granulePos = endGP; + } + else + { + granulePos = gps[i - 1]; + } + return i; + } + } + + throw new System.IO.InvalidDataException("Could not find seek packet?!"); + } + + private int FindPacket(int pageIndex, int preRoll, ref long granulePos, GetPacketGranuleCount getPacketGranuleCount) + { + // pageIndex is _probably_ the correct page (bugs in libogg mean long->short over page boundary isn't always correct). + // We check for this by looking for a difference in the previous page's granulePos vs. the calculated value + + // first we look at the page info to see how it is set up + var (lastPageGranulePos, lastPagePacketLength, firstRealPacket) = GetPreviousPageInfo(pageIndex, getPacketGranuleCount); + + // now get the info on the target page + var (gps, endGP) = GetTargetPageInfo(pageIndex, firstRealPacket, lastPagePacketLength, getPacketGranuleCount); + + // finally figure out which packet in our known info we need to use + var packetIndex = FindPacket(pageIndex, gps, endGP, lastPageGranulePos, lastPagePacketLength, ref granulePos); + + // then apply the preRoll (but only if we're not seeking into the first packet, which is its own preRoll) + if (endGP > 0 || packetIndex > 1) + { + packetIndex -= preRoll; + } + return packetIndex; + } + + private bool GetIsVorbisBugDiff(long diff) + { + // This requires either breaking abstractions OR doing some fancy bit math... + // We're gonna use the latter to keep the abstractions clean. + // For our bug, the bit pattern is x set bits followed by y cleared bits: + // x = the number of bits between short & long block sizes + // y = the number of bits in the short block size - 2 + // So in binary it looks like 111000000 for 2048/256 block sizes. + // We pre-adjust the "/ 4" out by starting at 0 for y instead of 2 + + // we have to use the absolute value for this to work right + diff = Math.Abs(diff); + + // find the count for y + var temp = diff; + var shortBlockBits = 0; + while (temp > 0 && (temp & 1) == 0) + { + ++shortBlockBits; + temp >>= 1; + } + + // find the count for x (shortcut: start from shortBlockBits since this is really an offset from there) + var longBlockBits = shortBlockBits; + while ((temp & 1) == 1) + { + ++longBlockBits; + temp >>= 1; + } + + // if we've encountered the bug, temp will be 0 and diff will equal longBlock / 4 - shortBLock /4 + return temp == 0 && diff == (1 << longBlockBits) - (1 << shortBlockBits); + } + + // this method calc's the appropriate page and packet prior to the one specified, honoring continuations and handling negative packetIndex values + // if packet index is larger than the current page allows, we just return it as-is + private bool NormalizePacketIndex(ref int pageIndex, ref int packetIndex) + { + if (!_reader.GetPage(pageIndex, out _, out var isResync, out var isContinuation, out _, out _, out _)) + { + return false; + } + + var pgIdx = pageIndex; + var pktIdx = packetIndex; + + while (pktIdx < (isContinuation ? 1: 0)) + { + // can't merge across resync + if (isContinuation && isResync) return false; + + // get the previous packet + var wasContinuation = isContinuation; + if (!_reader.GetPage(--pgIdx, out _, out isResync, out isContinuation, out var isContinued, out var packetCount, out _)) + { + return false; + } + + // can't merge if continuation flags don't match + if (wasContinuation && !isContinued) return false; + + // add the previous packet's packetCount + pktIdx += packetCount - (wasContinuation ? 1 : 0); + } + + pageIndex = pgIdx; + packetIndex = pktIdx; + return true; + } + + private Packet GetNextPacket(ref int pageIndex, ref int packetIndex) + { + if (_reader == null) throw new ObjectDisposedException(nameof(PacketProvider)); + + if (_lastPacketPacketIndex != packetIndex || _lastPacketPageIndex != pageIndex || _lastPacket == null) + { + _lastPacket = null; + + while (_reader.GetPage(pageIndex, out var granulePos, out var isResync, out _, out var isContinued, out var packetCount, out var pageOverhead)) + { + _lastPacketPageIndex = pageIndex; + _lastPacketPacketIndex = packetIndex; + _lastPacket = CreatePacket(ref pageIndex, ref packetIndex, true, granulePos, isResync, isContinued, packetCount, pageOverhead); + _nextPacketPageIndex = pageIndex; + _nextPacketPacketIndex = packetIndex; + break; + } + } + else + { + pageIndex = _nextPacketPageIndex; + packetIndex = _nextPacketPacketIndex; + } + return _lastPacket; + } + + private Packet CreatePacket(ref int pageIndex, ref int packetIndex, bool advance, long granulePos, bool isResync, bool isContinued, int packetCount, int pageOverhead) + { + // save off the packet data for the initial packet + var firstPacketData = _reader.GetPagePackets(pageIndex)[packetIndex]; + + // create the packet list and add the item to it + var pktList = new List(2) { (pageIndex << 8) | packetIndex }; + + // make sure we handle continuations + bool isLastPacket; + bool isFirstPacket; + var finalPage = pageIndex; + if (isContinued && packetIndex == packetCount - 1) + { + // by definition, it's the first packet in the page it ends on + isFirstPacket = true; + + // but we don't want to include the current page's overhead if we didn't start the page + if (packetIndex > 0) + { + pageOverhead = 0; + } + + // go read the next page(s) that include this packet + var contPageIdx = pageIndex; + while (isContinued) + { + if (!_reader.GetPage(++contPageIdx, out granulePos, out isResync, out var isContinuation, out isContinued, out packetCount, out var contPageOverhead)) + { + // no more pages? In any case, we can't satify the request + return null; + } + pageOverhead += contPageOverhead; + + // if the next page isn't a continuation or is a resync, the stream is broken so we'll just return what we could get + if (!isContinuation || isResync) + { + break; + } + + // if the next page is continued, only keep reading if there are no more packets in the page + if (isContinued && packetCount > 1) + { + isContinued = false; + } + + // add the packet to the list + pktList.Add(contPageIdx << 8); + } + + // we're now the first packet in the final page, so we'll act like it... + isLastPacket = packetCount == 1; + + // track the final page read + finalPage = contPageIdx; + } + else + { + isFirstPacket = packetIndex == 0; + isLastPacket = packetIndex == packetCount - 1; + } + + // create the packet instance and populate it with the appropriate initial data + var packet = new Packet(pktList, this, firstPacketData) + { + IsResync = isResync, + }; + + // if it's the first packet, associate the container overhead with it + if (isFirstPacket) + { + packet.ContainerOverheadBits = pageOverhead * 8; + } + + // if we're the last packet completed in the page, set the .GranulePosition + if (isLastPacket) + { + packet.GranulePosition = granulePos; + + // if we're the last packet completed in the page, no more pages are available, and _hasAllPages is set, set .IsEndOfStream + if (_reader.HasAllPages && finalPage == _reader.PageCount - 1) + { + packet.IsEndOfStream = true; + } + } + + if (advance) + { + // if we've advanced a page, we continued a packet and should pick up with the next page + if (finalPage != pageIndex) + { + // we're on the final page now + pageIndex = finalPage; + + // the packet index will be modified below, so set it to the end of the continued packet + packetIndex = 0; + } + + // if we're on the last packet in the page, move to the next page + // we can't use isLast here because the logic is different; last in page granule vs. last in physical page + if (packetIndex == packetCount - 1) + { + ++pageIndex; + packetIndex = 0; + } + // otherwise, just move to the next packet + else + { + ++packetIndex; + } + } + + // done! + return packet; + } + + Memory IPacketReader.GetPacketData(int pagePacketIndex) + { + var pageIndex = (pagePacketIndex >> 8) & 0xFFFFFF; + var packetIndex = pagePacketIndex & 0xFF; + + var packets = _reader.GetPagePackets(pageIndex); + if (packetIndex < packets.Length) + { + return packets[packetIndex]; + } + return Memory.Empty; + } + + void IPacketReader.InvalidatePacketCache(IPacket packet) + { + if (ReferenceEquals(_lastPacket, packet)) + { + _lastPacket = null; + } + } + } +} diff --git a/Assets/Plugins/NVorbis/Ogg/PacketProvider.cs.meta b/Assets/Plugins/NVorbis/Ogg/PacketProvider.cs.meta new file mode 100644 index 000000000..63924453a --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/PacketProvider.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7eb58e7d04f8a8441984dd8b876696f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg/PageReader.cs b/Assets/Plugins/NVorbis/Ogg/PageReader.cs new file mode 100644 index 000000000..3071d4d1e --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/PageReader.cs @@ -0,0 +1,236 @@ +using NVorbis.Contracts.Ogg; +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; + +namespace NVorbis.Ogg +{ + class PageReader : PageReaderBase, IPageData + { + internal static Func CreateStreamPageReader { get; set; } = (pr, ss) => new StreamPageReader(pr, ss); + + private readonly Dictionary _streamReaders = new Dictionary(); + private readonly Func _newStreamCallback; + private readonly object _readLock = new object(); + + private long _nextPageOffset; + private ushort _pageSize; + Memory[] _packets; + + public PageReader(Stream stream, bool closeOnDispose, Func newStreamCallback) + : base(stream, closeOnDispose) + { + _newStreamCallback = newStreamCallback; + } + + private ushort ParsePageHeader(byte[] pageBuf, int? streamSerial, bool? isResync) + { + var segCnt = pageBuf[26]; + var dataLen = 0; + var pktCnt = 0; + var isContinued = false; + + var size = 0; + for (int i = 0, idx = 27; i < segCnt; i++, idx++) + { + var seg = pageBuf[idx]; + size += seg; + dataLen += seg; + if (seg < 255) + { + if (size > 0) + { + ++pktCnt; + } + size = 0; + } + } + if (size > 0) + { + isContinued = pageBuf[segCnt + 26] == 255; + ++pktCnt; + } + + StreamSerial = streamSerial ?? BitConverter.ToInt32(pageBuf, 14); + SequenceNumber = BitConverter.ToInt32(pageBuf, 18); + PageFlags = (PageFlags)pageBuf[5]; + GranulePosition = BitConverter.ToInt64(pageBuf, 6); + PacketCount = (short)pktCnt; + IsResync = isResync; + IsContinued = isContinued; + PageOverhead = 27 + segCnt; + return (ushort)(PageOverhead + dataLen); + } + + private static Memory[] ReadPackets(int packetCount, Span segments, Memory dataBuffer) + { + var list = new Memory[packetCount]; + var listIdx = 0; + var dataIdx = 0; + var size = 0; + + for (var i = 0; i < segments.Length; i++) + { + var seg = segments[i]; + size += seg; + if (seg < 255) + { + if (size > 0) + { + list[listIdx++] = dataBuffer.Slice(dataIdx, size); + dataIdx += size; + } + size = 0; + } + } + if (size > 0) + { + list[listIdx] = dataBuffer.Slice(dataIdx, size); + } + + return list; + } + + public override void Lock() + { + Monitor.Enter(_readLock); + } + + protected override bool CheckLock() + { + return Monitor.IsEntered(_readLock); + } + + public override bool Release() + { + if (Monitor.IsEntered(_readLock)) + { + Monitor.Exit(_readLock); + return true; + } + return false; + } + + protected override void SaveNextPageSearch() + { + _nextPageOffset = StreamPosition; + } + + protected override void PrepareStreamForNextPage() + { + SeekStream(_nextPageOffset); + } + + protected override bool AddPage(int streamSerial, byte[] pageBuf, bool isResync) + { + PageOffset = StreamPosition - pageBuf.Length; + ParsePageHeader(pageBuf, streamSerial, isResync); + + // if the page doesn't have any packets, we can't use it + if (PacketCount == 0) return false; + + _packets = ReadPackets(PacketCount, new Span(pageBuf, 27, pageBuf[26]), new Memory(pageBuf, 27 + pageBuf[26], pageBuf.Length - 27 - pageBuf[26])); + + if (_streamReaders.TryGetValue(streamSerial, out var spr)) + { + spr.AddPage(); + + // if we've read the last page, remove from our list so cleanup can happen. + // this is safe because the instance still has access to us for reading. + if ((PageFlags & PageFlags.EndOfStream) == PageFlags.EndOfStream) + { + _streamReaders.Remove(StreamSerial); + } + } + else + { + var streamReader = CreateStreamPageReader(this, StreamSerial); + streamReader.AddPage(); + _streamReaders.Add(StreamSerial, streamReader); + if (!_newStreamCallback(streamReader.PacketProvider)) + { + _streamReaders.Remove(StreamSerial); + return false; + } + } + return true; + } + + public override bool ReadPageAt(long offset) + { + // make sure we're locked; no sense reading if we aren't + if (!CheckLock()) throw new InvalidOperationException("Must be locked prior to reading!"); + + // this should be safe; we've already checked the page by now + + if (offset == PageOffset) + { + // short circuit for when we've already loaded the page + return true; + } + + var hdrBuf = new byte[282]; + + SeekStream(offset); + var cnt = EnsureRead(hdrBuf, 0, 27); + + PageOffset = offset; + if (VerifyHeader(hdrBuf, 0, ref cnt)) + { + // don't read the whole page yet; if our caller is seeking, they won't need packets anyway + _packets = null; + _pageSize = ParsePageHeader(hdrBuf, null, null); + return true; + } + return false; + } + + protected override void SetEndOfStreams() + { + foreach (var kvp in _streamReaders) + { + kvp.Value.SetEndOfStream(); + } + _streamReaders.Clear(); + } + + + #region IPacketData + + public long PageOffset { get; private set; } + + public int StreamSerial { get; private set; } + + public int SequenceNumber { get; private set; } + + public PageFlags PageFlags { get; private set; } + + public long GranulePosition { get; private set; } + + public short PacketCount { get; private set; } + + public bool? IsResync { get; private set; } + + public bool IsContinued { get; private set; } + + public int PageOverhead { get; private set; } + + public Memory[] GetPackets() + { + if (!CheckLock()) throw new InvalidOperationException("Must be locked!"); + + if (_packets == null) + { + var pageBuf = new byte[_pageSize]; + SeekStream(PageOffset); + EnsureRead(pageBuf, 0, _pageSize); + _packets = ReadPackets(PacketCount, new Span(pageBuf, 27, pageBuf[26]), new Memory(pageBuf, 27 + pageBuf[26], pageBuf.Length - 27 - pageBuf[26])); + } + + return _packets; + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/Plugins/NVorbis/Ogg/PageReader.cs.meta b/Assets/Plugins/NVorbis/Ogg/PageReader.cs.meta new file mode 100644 index 000000000..690cc0536 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/PageReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 66d91e2956a05d94fb2d20f30268d0cd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg/PageReaderBase.cs b/Assets/Plugins/NVorbis/Ogg/PageReaderBase.cs new file mode 100644 index 000000000..5bba86b15 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/PageReaderBase.cs @@ -0,0 +1,307 @@ +using NVorbis.Contracts.Ogg; +using System; +using System.Collections.Generic; +using System.IO; + +namespace NVorbis.Ogg +{ + abstract class PageReaderBase : IPageReader + { + internal static Func CreateCrc { get; set; } = () => new Crc(); + + private readonly ICrc _crc = CreateCrc(); + private readonly HashSet _ignoredSerials = new HashSet(); + private readonly byte[] _headerBuf = new byte[305]; // 27 - 4 + 27 + 255 (found sync at end of first buffer, and found page has full segment count) + private byte[] _overflowBuf; + private int _overflowBufIndex; + + private Stream _stream; + private bool _closeOnDispose; + + protected PageReaderBase(Stream stream, bool closeOnDispose) + { + _stream = stream; + _closeOnDispose = closeOnDispose; + } + + protected long StreamPosition => _stream?.Position ?? throw new ObjectDisposedException(nameof(PageReaderBase)); + + public long ContainerBits { get; private set; } + + public long WasteBits { get; private set; } + + private bool VerifyPage(byte[] headerBuf, int index, int cnt, out byte[] pageBuf, out int bytesRead) + { + var segCnt = headerBuf[index + 26]; + if (cnt - index < index + 27 + segCnt) + { + pageBuf = null; + bytesRead = 0; + return false; + } + + var dataLen = 0; + int i; + for (i = 0; i < segCnt; i++) + { + dataLen += headerBuf[index + i + 27]; + } + + pageBuf = new byte[dataLen + segCnt + 27]; + Buffer.BlockCopy(headerBuf, index, pageBuf, 0, segCnt + 27); + bytesRead = EnsureRead(pageBuf, segCnt + 27, dataLen); + if (bytesRead != dataLen) return false; + dataLen = pageBuf.Length; + + _crc.Reset(); + for (i = 0; i < 22; i++) + { + _crc.Update(pageBuf[i]); + } + _crc.Update(0); + _crc.Update(0); + _crc.Update(0); + _crc.Update(0); + for (i += 4; i < dataLen; i++) + { + _crc.Update(pageBuf[i]); + } + return _crc.Test(BitConverter.ToUInt32(pageBuf, 22)); + } + + private bool AddPage(byte[] pageBuf, bool isResync) + { + var streamSerial = BitConverter.ToInt32(pageBuf, 14); + if (!_ignoredSerials.Contains(streamSerial)) + { + if (AddPage(streamSerial, pageBuf, isResync)) + { + ContainerBits += 8 * (27 + pageBuf[26]); + return true; + } + _ignoredSerials.Add(streamSerial); + } + return false; + } + + private void EnqueueData(byte[] buf, int count) + { + if (_overflowBuf != null) + { + var newBuf = new byte[_overflowBuf.Length - _overflowBufIndex + count]; + Buffer.BlockCopy(_overflowBuf, _overflowBufIndex, newBuf, 0, newBuf.Length - count); + var index = buf.Length - count; + Buffer.BlockCopy(buf, index, newBuf, newBuf.Length - count, count); + _overflowBufIndex = 0; + } + else + { + _overflowBuf = buf; + _overflowBufIndex = buf.Length - count; + } + } + + private void ClearEnqueuedData(int count) + { + if (_overflowBuf != null && (_overflowBufIndex += count) >= _overflowBuf.Length) + { + _overflowBuf = null; + } + } + + private int FillHeader(byte[] buf, int index, int count, int maxTries = 10) + { + var copyCount = 0; + if (_overflowBuf != null) + { + copyCount = Math.Min(_overflowBuf.Length - _overflowBufIndex, count); + Buffer.BlockCopy(_overflowBuf, _overflowBufIndex, buf, index, copyCount); + index += copyCount; + count -= copyCount; + if ((_overflowBufIndex += copyCount) == _overflowBuf.Length) + { + _overflowBuf = null; + } + } + if (count > 0) + { + copyCount += EnsureRead(buf, index, count, maxTries); + } + return copyCount; + } + + private bool VerifyHeader(byte[] buffer, int index, ref int cnt, bool isFromReadNextPage) + { + if (buffer[index] == 0x4f && buffer[index + 1] == 0x67 && buffer[index + 2] == 0x67 && buffer[index + 3] == 0x53) + { + if (cnt < 27) + { + if (isFromReadNextPage) + { + cnt += FillHeader(buffer, 27 - cnt + index, 27 - cnt); + } + else + { + cnt += EnsureRead(buffer, 27 - cnt + index, 27 - cnt); + } + } + + if (cnt >= 27) + { + var segCnt = buffer[index + 26]; + if (isFromReadNextPage) + { + cnt += FillHeader(buffer, index + 27, segCnt); + } + else + { + cnt += EnsureRead(buffer, index + 27, segCnt); + } + if (cnt == index + 27 + segCnt) + { + return true; + } + } + } + return false; + } + + // Network streams don't always return the requested size immediately, so this + // method is used to ensure we fill the buffer if it is possible. + // Note that it will loop until getting a certain count of zero reads (default: 10). + // This means in most cases, the network stream probably died by the time we return + // a short read. + protected int EnsureRead(byte[] buf, int index, int count, int maxTries = 10) + { + var read = 0; + var tries = 0; + do + { + var cnt = _stream.Read(buf, index + read, count - read); + if (cnt == 0 && ++tries == maxTries) + { + break; + } + read += cnt; + } while (read < count); + return read; + } + + /// + /// Verifies the sync sequence and loads the rest of the header. + /// + /// if successful, otherwise . + protected bool VerifyHeader(byte[] buffer, int index, ref int cnt) + { + return VerifyHeader(buffer, index, ref cnt, false); + } + + /// + /// Seeks the underlying stream to the requested position. + /// + /// A byte offset relative to the origin parameter. + /// The new position of the stream. + /// The stream is not seekable. + protected long SeekStream(long offset) + { + // make sure we're locked; seeking won't matter if we aren't + if (!CheckLock()) throw new InvalidOperationException("Must be locked prior to reading!"); + + return _stream.Seek(offset, SeekOrigin.Begin); + } + + virtual protected void PrepareStreamForNextPage() { } + + virtual protected void SaveNextPageSearch() { } + + abstract protected bool AddPage(int streamSerial, byte[] pageBuf, bool isResync); + + abstract protected void SetEndOfStreams(); + + virtual public void Lock() { } + + virtual protected bool CheckLock() => true; + + virtual public bool Release() => false; + + public bool ReadNextPage() + { + // make sure we're locked; no sense reading if we aren't + if (!CheckLock()) throw new InvalidOperationException("Must be locked prior to reading!"); + + var isResync = false; + + var ofs = 0; + int cnt; + PrepareStreamForNextPage(); + while ((cnt = FillHeader(_headerBuf, ofs, 27 - ofs)) > 0) + { + cnt += ofs; + for (var i = 0; i < cnt - 4; i++) + { + if (VerifyHeader(_headerBuf, i, ref cnt, true)) + { + if (VerifyPage(_headerBuf, i, cnt, out var pageBuf, out var bytesRead)) + { + // one way or the other, we have to clear out the page's bytes from the queue (if queued) + ClearEnqueuedData(bytesRead); + + // also, we need to let our inheritors have a chance to save state for next time + SaveNextPageSearch(); + + // pass it to our inheritor + if (AddPage(pageBuf, isResync)) + { + return true; + } + + // otherwise, the whole page is useless... + + // save off that we've burned that many bits + WasteBits += pageBuf.Length * 8; + + // set up to load the next page, then loop + ofs = 0; + cnt = 0; + break; + } + else if (pageBuf != null) + { + EnqueueData(pageBuf, bytesRead); + } + } + WasteBits += 8; + isResync = true; + } + + if (cnt >= 3) + { + _headerBuf[0] = _headerBuf[cnt - 3]; + _headerBuf[1] = _headerBuf[cnt - 2]; + _headerBuf[2] = _headerBuf[cnt - 1]; + ofs = 3; + } + } + + if (cnt == 0) + { + SetEndOfStreams(); + } + + return false; + } + + abstract public bool ReadPageAt(long offset); + + public void Dispose() + { + SetEndOfStreams(); + + if (_closeOnDispose) + { + _stream?.Dispose(); + } + _stream = null; + } + } +} diff --git a/Assets/Plugins/NVorbis/Ogg/PageReaderBase.cs.meta b/Assets/Plugins/NVorbis/Ogg/PageReaderBase.cs.meta new file mode 100644 index 000000000..9eb6a1986 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/PageReaderBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 567f580cee650b74896edf042cb5c743 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Ogg/StreamPageReader.cs b/Assets/Plugins/NVorbis/Ogg/StreamPageReader.cs new file mode 100644 index 000000000..6988b0a37 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/StreamPageReader.cs @@ -0,0 +1,393 @@ +using NVorbis.Contracts.Ogg; +using System; +using System.Collections.Generic; + +namespace NVorbis.Ogg +{ + class StreamPageReader : IStreamPageReader + { + internal static Func CreatePacketProvider { get; set; } = (pr, ss) => new PacketProvider(pr, ss); + + private readonly IPageData _reader; + private readonly List _pageOffsets = new List(); + + private int _lastSeqNbr; + private int? _firstDataPageIndex; + private long _maxGranulePos; + + private int _lastPageIndex = -1; + private long _lastPageGranulePos; + private bool _lastPageIsResync; + private bool _lastPageIsContinuation; + private bool _lastPageIsContinued; + private int _lastPagePacketCount; + private int _lastPageOverhead; + + private Memory[] _cachedPagePackets; + + public Contracts.IPacketProvider PacketProvider { get; private set; } + + public StreamPageReader(IPageData pageReader, int streamSerial) + { + _reader = pageReader; + + // The packet provider has a reference to us, and we have a reference to it. + // The page reader has a reference to us. + // The container reader has a _weak_ reference to the packet provider. + // The user has a reference to the packet provider. + // So long as the user doesn't drop their reference and the page reader doesn't drop us, + // the packet provider will stay alive. + // This is important since the container reader only holds a week reference to it. + PacketProvider = CreatePacketProvider(this, streamSerial); + } + + public void AddPage() + { + // verify we haven't read all pages + if (!HasAllPages) + { + // verify the new page's flags + + // if the page's granule position is 0 or less it doesn't have any sample + if (_reader.GranulePosition != -1) + { + if (_firstDataPageIndex == null && _reader.GranulePosition > 0) + { + _firstDataPageIndex = _pageOffsets.Count; + } + else if (_maxGranulePos > _reader.GranulePosition) + { + // uuuuh, what?! + throw new System.IO.InvalidDataException("Granule Position regressed?!"); + } + _maxGranulePos = _reader.GranulePosition; + } + // granule position == -1, so this page doesn't complete any packets + // we don't really care if it's a continuation itself, only that it is continued and has a single packet + else if (_firstDataPageIndex.HasValue && (!_reader.IsContinued || _reader.PacketCount != 1)) + { + throw new System.IO.InvalidDataException("Granule Position was -1 but page does not have exactly 1 continued packet."); + } + + if ((_reader.PageFlags & PageFlags.EndOfStream) != 0) + { + HasAllPages = true; + } + + if (_reader.IsResync.Value || (_lastSeqNbr != 0 && _lastSeqNbr + 1 != _reader.SequenceNumber)) + { + // as a practical matter, if the sequence numbers are "wrong", our logical stream is now out of sync + // so whether the page header sync was lost or we just got an out of order page / sequence jump, we're counting it as a resync + _pageOffsets.Add(-_reader.PageOffset); + } + else + { + _pageOffsets.Add(_reader.PageOffset); + } + + _lastSeqNbr = _reader.SequenceNumber; + } + } + + public Memory[] GetPagePackets(int pageIndex) + { + if (_cachedPagePackets != null && _lastPageIndex == pageIndex) + { + return _cachedPagePackets; + } + + var pageOffset = _pageOffsets[pageIndex]; + if (pageOffset < 0) + { + pageOffset = -pageOffset; + } + + _reader.Lock(); + try + { + _reader.ReadPageAt(pageOffset); + var packets = _reader.GetPackets(); + if (pageIndex == _lastPageIndex) + { + _cachedPagePackets = packets; + } + return packets; + } + finally + { + _reader.Release(); + } + } + + public int FindPage(long granulePos) + { + // if we're being asked for the first granule, just grab the very first data page + int pageIndex = -1; + if (granulePos == 0) + { + pageIndex = FindFirstDataPage(); + } + else + { + // start by looking at the last read page's position... + var lastPageIndex = _pageOffsets.Count - 1; + if (GetPageRaw(lastPageIndex, out var pageGP)) + { + // most likely, we can look at previous pages for the appropriate one... + if (granulePos < pageGP) + { + pageIndex = FindPageBisection(granulePos, FindFirstDataPage(), lastPageIndex, pageGP); + } + // unless we're seeking forward, which is merely an excercise in reading forward... + else if (granulePos > pageGP) + { + pageIndex = FindPageForward(lastPageIndex, pageGP, granulePos); + } + // but of course, it's possible (though highly unlikely) that the last read page ended on the granule we're looking for. + else + { + pageIndex = lastPageIndex + 1; + } + } + } + if (pageIndex == -1) + { + throw new ArgumentOutOfRangeException(nameof(granulePos)); + } + return pageIndex; + } + + private int FindFirstDataPage() + { + while (!_firstDataPageIndex.HasValue) + { + if (!GetPageRaw(_pageOffsets.Count, out _)) + { + return -1; + } + } + return _firstDataPageIndex.Value; + } + + private int FindPageForward(int pageIndex, long pageGranulePos, long granulePos) + { + while (pageGranulePos <= granulePos) + { + if (++pageIndex == _pageOffsets.Count) + { + if (!GetNextPageGranulePos(out pageGranulePos)) + { + // if we couldn't get a page because we're EOS, allow finding the last granulePos + if (MaxGranulePosition < granulePos) + { + pageIndex = -1; + } + break; + } + } + else + { + if (!GetPageRaw(pageIndex, out pageGranulePos)) + { + pageIndex = -1; + break; + } + } + } + return pageIndex; + } + + private bool GetNextPageGranulePos(out long granulePos) + { + var pageCount = _pageOffsets.Count; + while (pageCount == _pageOffsets.Count && !HasAllPages) + { + _reader.Lock(); + try + { + if (!_reader.ReadNextPage()) + { + HasAllPages = true; + continue; + } + + if (pageCount < _pageOffsets.Count) + { + granulePos = _reader.GranulePosition; + return true; + } + } + finally + { + _reader.Release(); + } + } + granulePos = 0; + return false; + } + + private int FindPageBisection(long granulePos, int low, int high, long highGranulePos) + { + // we can treat low as always being before the first sample; later work will correct that if needed + var lowGranulePos = 0L; + int dist; + while ((dist = high - low) > 0) + { + // try to find the right page by assumming they are all about the same size + var index = low + (int)(dist * ((granulePos - lowGranulePos) / (double)(highGranulePos - lowGranulePos))); + + // go get the actual position of the selected page + if (!GetPageRaw(index, out var idxGranulePos)) + { + return -1; + } + + // figure out where to go from here + if (idxGranulePos > granulePos) + { + // we read a page after our target (could be the right one, but we don't know yet) + high = index; + highGranulePos = idxGranulePos; + } + else if (idxGranulePos < granulePos) + { + // we read a page before our target + low = index + 1; + lowGranulePos = idxGranulePos + 1; + } + else + { + // direct hit + return index + 1; + } + } + return low; + } + + private bool GetPageRaw(int pageIndex, out long pageGranulePos) + { + var offset = _pageOffsets[pageIndex]; + if (offset < 0) + { + offset = -offset; + } + + _reader.Lock(); + try + { + if (_reader.ReadPageAt(offset)) + { + pageGranulePos = _reader.GranulePosition; + return true; + } + pageGranulePos = 0; + return false; + } + finally + { + _reader.Release(); + } + } + + public bool GetPage(int pageIndex, out long granulePos, out bool isResync, out bool isContinuation, out bool isContinued, out int packetCount, out int pageOverhead) + { + if (_lastPageIndex == pageIndex) + { + granulePos = _lastPageGranulePos; + isResync = _lastPageIsResync; + isContinuation = _lastPageIsContinuation; + isContinued = _lastPageIsContinued; + packetCount = _lastPagePacketCount; + pageOverhead = _lastPageOverhead; + return true; + } + + _reader.Lock(); + try + { + while (pageIndex >= _pageOffsets.Count && !HasAllPages) + { + if (_reader.ReadNextPage()) + { + // if we found our page, return it from here so we don't have to do further processing + if (pageIndex < _pageOffsets.Count) + { + isResync = _reader.IsResync.Value; + ReadPageData(pageIndex, out granulePos, out isContinuation, out isContinued, out packetCount, out pageOverhead); + return true; + } + } + else + { + break; + } + } + } + finally + { + _reader.Release(); + } + + if (pageIndex < _pageOffsets.Count) + { + var offset = _pageOffsets[pageIndex]; + if (offset < 0) + { + isResync = true; + offset = -offset; + } + else + { + isResync = false; + } + + _reader.Lock(); + try + { + if (_reader.ReadPageAt(offset)) + { + _lastPageIsResync = isResync; + ReadPageData(pageIndex, out granulePos, out isContinuation, out isContinued, out packetCount, out pageOverhead); + return true; + } + } + finally + { + _reader.Release(); + } + } + + granulePos = 0; + isResync = false; + isContinuation = false; + isContinued = false; + packetCount = 0; + pageOverhead = 0; + return false; + } + + private void ReadPageData(int pageIndex, out long granulePos, out bool isContinuation, out bool isContinued, out int packetCount, out int pageOverhead) + { + _cachedPagePackets = null; + _lastPageGranulePos = granulePos = _reader.GranulePosition; + _lastPageIsContinuation = isContinuation = (_reader.PageFlags & PageFlags.ContinuesPacket) != 0; + _lastPageIsContinued = isContinued = _reader.IsContinued; + _lastPagePacketCount = packetCount = _reader.PacketCount; + _lastPageOverhead = pageOverhead = _reader.PageOverhead; + _lastPageIndex = pageIndex; + } + + public void SetEndOfStream() + { + HasAllPages = true; + } + + public int PageCount => _pageOffsets.Count; + + public bool HasAllPages { get; private set; } + + public long? MaxGranulePosition => HasAllPages ? (long?)_maxGranulePos : null; + + public int FirstDataPageIndex => FindFirstDataPage(); + } +} diff --git a/Assets/Plugins/NVorbis/Ogg/StreamPageReader.cs.meta b/Assets/Plugins/NVorbis/Ogg/StreamPageReader.cs.meta new file mode 100644 index 000000000..caf98d5f9 --- /dev/null +++ b/Assets/Plugins/NVorbis/Ogg/StreamPageReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 897c590ac5da042429505d92299b8961 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Residue0.cs b/Assets/Plugins/NVorbis/Residue0.cs new file mode 100644 index 000000000..cf47f66ff --- /dev/null +++ b/Assets/Plugins/NVorbis/Residue0.cs @@ -0,0 +1,203 @@ +using NVorbis.Contracts; +using System; +using System.IO; + +namespace NVorbis +{ + // each channel gets its own pass, one dimension at a time + class Residue0 : IResidue + { + static int icount(int v) + { + var ret = 0; + while (v != 0) + { + ret += (v & 1); + v >>= 1; + } + return ret; + } + + int _channels; + int _begin; + int _end; + int _partitionSize; + int _classifications; + int _maxStages; + + ICodebook[][] _books; + ICodebook _classBook; + + int[] _cascade; + int[][] _decodeMap; + + + virtual public void Init(IPacket packet, int channels, ICodebook[] codebooks) + { + // this is pretty well stolen directly from libvorbis... BSD license + _begin = (int)packet.ReadBits(24); + _end = (int)packet.ReadBits(24); + _partitionSize = (int)packet.ReadBits(24) + 1; + _classifications = (int)packet.ReadBits(6) + 1; + _classBook = codebooks[(int)packet.ReadBits(8)]; + + _cascade = new int[_classifications]; + var acc = 0; + for (int i = 0; i < _classifications; i++) + { + var low_bits = (int)packet.ReadBits(3); + if (packet.ReadBit()) + { + _cascade[i] = (int)packet.ReadBits(5) << 3 | low_bits; + } + else + { + _cascade[i] = low_bits; + } + acc += icount(_cascade[i]); + } + + var bookNums = new int[acc]; + for (var i = 0; i < acc; i++) + { + bookNums[i] = (int)packet.ReadBits(8); + if (codebooks[bookNums[i]].MapType == 0) throw new InvalidDataException(); + } + + var entries = _classBook.Entries; + var dim = _classBook.Dimensions; + var partvals = 1; + while (dim > 0) + { + partvals *= _classifications; + if (partvals > entries) throw new InvalidDataException(); + --dim; + } + + // now the lookups + _books = new ICodebook[_classifications][]; + + acc = 0; + var maxstage = 0; + int stages; + for (int j = 0; j < _classifications; j++) + { + stages = Utils.ilog(_cascade[j]); + _books[j] = new ICodebook[stages]; + if (stages > 0) + { + maxstage = Math.Max(maxstage, stages); + for (int k = 0; k < stages; k++) + { + if ((_cascade[j] & (1 << k)) > 0) + { + _books[j][k] = codebooks[bookNums[acc++]]; + } + } + } + } + _maxStages = maxstage; + + _decodeMap = new int[partvals][]; + for (int j = 0; j < partvals; j++) + { + var val = j; + var mult = partvals / _classifications; + _decodeMap[j] = new int[_classBook.Dimensions]; + for (int k = 0; k < _classBook.Dimensions; k++) + { + var deco = val / mult; + val -= deco * mult; + mult /= _classifications; + _decodeMap[j][k] = deco; + } + } + + _channels = channels; + } + + virtual public void Decode(IPacket packet, bool[] doNotDecodeChannel, int blockSize, float[][] buffer) + { + // this is pretty well stolen directly from libvorbis... BSD license + var end = _end < blockSize / 2 ? _end : blockSize / 2; + var n = end - _begin; + + if (n > 0 && Array.IndexOf(doNotDecodeChannel, false) != -1) + { + var partitionCount = n / _partitionSize; + + var partitionWords = (partitionCount + _classBook.Dimensions - 1) / _classBook.Dimensions; + var partWordCache = new int[_channels, partitionWords][]; + + for (var stage = 0; stage < _maxStages; stage++) + { + for (int partitionIdx = 0, entryIdx = 0; partitionIdx < partitionCount; entryIdx++) + { + if (stage == 0) + { + for (var ch = 0; ch < _channels; ch++) + { + var idx = _classBook.DecodeScalar(packet); + if (idx >= 0 && idx < _decodeMap.Length) + { + partWordCache[ch, entryIdx] = _decodeMap[idx]; + } + else + { + partitionIdx = partitionCount; + stage = _maxStages; + break; + } + } + } + for (var dimensionIdx = 0; partitionIdx < partitionCount && dimensionIdx < _classBook.Dimensions; dimensionIdx++, partitionIdx++) + { + var offset = _begin + partitionIdx * _partitionSize; + for (var ch = 0; ch < _channels; ch++) + { + var idx = partWordCache[ch, entryIdx][dimensionIdx]; + if ((_cascade[idx] & (1 << stage)) != 0) + { + var book = _books[idx][stage]; + if (book != null) + { + if (WriteVectors(book, packet, buffer, ch, offset, _partitionSize)) + { + // bad packet... exit now and try to use what we already have + partitionIdx = partitionCount; + stage = _maxStages; + break; + } + } + } + } + } + } + } + } + } + + virtual protected bool WriteVectors(ICodebook codebook, IPacket packet, float[][] residue, int channel, int offset, int partitionSize) + { + var res = residue[channel]; + var steps = partitionSize / codebook.Dimensions; + var entryCache = new int[steps]; + + for (var i = 0; i < steps; i++) + { + if ((entryCache[i] = codebook.DecodeScalar(packet)) == -1) + { + return true; + } + } + for (var dim = 0; dim < codebook.Dimensions; dim++) + { + for (var step = 0; step < steps; step++, offset++) + { + res[offset] += codebook[entryCache[step], dim]; + } + } + return false; + } + } +} diff --git a/Assets/Plugins/NVorbis/Residue0.cs.meta b/Assets/Plugins/NVorbis/Residue0.cs.meta new file mode 100644 index 000000000..124b31e1b --- /dev/null +++ b/Assets/Plugins/NVorbis/Residue0.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be4cf7556e9ba984fa1958aff9c92340 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Residue1.cs b/Assets/Plugins/NVorbis/Residue1.cs new file mode 100644 index 000000000..bfbd95f0c --- /dev/null +++ b/Assets/Plugins/NVorbis/Residue1.cs @@ -0,0 +1,28 @@ +using NVorbis.Contracts; + +namespace NVorbis +{ + // each channel gets its own pass, with the dimensions interleaved + class Residue1 : Residue0 + { + protected override bool WriteVectors(ICodebook codebook, IPacket packet, float[][] residue, int channel, int offset, int partitionSize) + { + var res = residue[channel]; + + for (int i = 0; i < partitionSize;) + { + var entry = codebook.DecodeScalar(packet); + if (entry == -1) + { + return true; + } + for (int j = 0; j < codebook.Dimensions; i++, j++) + { + res[offset + i] += codebook[entry, j]; + } + } + + return false; + } + } +} diff --git a/Assets/Plugins/NVorbis/Residue1.cs.meta b/Assets/Plugins/NVorbis/Residue1.cs.meta new file mode 100644 index 000000000..a21d010ca --- /dev/null +++ b/Assets/Plugins/NVorbis/Residue1.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d3b305e918ba8704b8ddfcffb79797b6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Residue2.cs b/Assets/Plugins/NVorbis/Residue2.cs new file mode 100644 index 000000000..c8ba8f876 --- /dev/null +++ b/Assets/Plugins/NVorbis/Residue2.cs @@ -0,0 +1,49 @@ +using NVorbis.Contracts; + +namespace NVorbis +{ + // all channels in one pass, interleaved + class Residue2 : Residue0 + { + int _channels; + + public override void Init(IPacket packet, int channels, ICodebook[] codebooks) + { + _channels = channels; + base.Init(packet, 1, codebooks); + } + + public override void Decode(IPacket packet, bool[] doNotDecodeChannel, int blockSize, float[][] buffer) + { + // since we're doing all channels in a single pass, the block size has to be multiplied. + // otherwise this is just a pass-through call + base.Decode(packet, doNotDecodeChannel, blockSize * _channels, buffer); + } + + protected override bool WriteVectors(ICodebook codebook, IPacket packet, float[][] residue, int channel, int offset, int partitionSize) + { + var chPtr = 0; + + offset /= _channels; + for (int c = 0; c < partitionSize;) + { + var entry = codebook.DecodeScalar(packet); + if (entry == -1) + { + return true; + } + for (var d = 0; d < codebook.Dimensions; d++, c++) + { + residue[chPtr][offset] += codebook[entry, d]; + if (++chPtr == _channels) + { + chPtr = 0; + offset++; + } + } + } + + return false; + } + } +} diff --git a/Assets/Plugins/NVorbis/Residue2.cs.meta b/Assets/Plugins/NVorbis/Residue2.cs.meta new file mode 100644 index 000000000..a10f68f74 --- /dev/null +++ b/Assets/Plugins/NVorbis/Residue2.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b0872ae9d84d232478ba9bf4398b2bc8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/StreamDecoder.cs b/Assets/Plugins/NVorbis/StreamDecoder.cs new file mode 100644 index 000000000..716ee47a0 --- /dev/null +++ b/Assets/Plugins/NVorbis/StreamDecoder.cs @@ -0,0 +1,742 @@ +using NVorbis.Contracts; +using System; +using System.IO; +using System.Text; + +namespace NVorbis +{ + /// + /// Implements a stream decoder for Vorbis data. + /// + public sealed class StreamDecoder : IStreamDecoder + { + static internal Func CreateFactory { get; set; } = () => new Factory(); + + private Contracts.IPacketProvider _packetProvider; + private IFactory _factory; + private StreamStats _stats; + + private byte _channels; + private int _sampleRate; + private int _block0Size; + private int _block1Size; + private IMode[] _modes; + private int _modeFieldBits; + + private string _vendor; + private string[] _comments; + private ITagData _tags; + + private long _currentPosition; + private bool _hasClipped; + private bool _hasPosition; + private bool _eosFound; + + private float[][] _nextPacketBuf; + private float[][] _prevPacketBuf; + private int _prevPacketStart; + private int _prevPacketEnd; + private int _prevPacketStop; + + /// + /// Creates a new instance of . + /// + /// A instance for the decoder to read from. + public StreamDecoder(Contracts.IPacketProvider packetProvider) + : this(packetProvider, new Factory()) + { + } + + internal StreamDecoder(Contracts.IPacketProvider packetProvider, IFactory factory) + { + _packetProvider = packetProvider ?? throw new ArgumentNullException(nameof(packetProvider)); + _factory = factory ?? throw new ArgumentNullException(nameof(factory)); + + _stats = new StreamStats(); + + _currentPosition = 0L; + ClipSamples = true; + + var packet = _packetProvider.PeekNextPacket(); + if (!ProcessHeaderPackets(packet)) + { + _packetProvider = null; + packet.Reset(); + + throw GetInvalidStreamException(packet); + } + } + + private static Exception GetInvalidStreamException(IPacket packet) + { + try + { + // let's give our caller some helpful hints about what they've encountered... + var header = packet.ReadBits(64); + if (header == 0x646165487375704ful) + { + return new ArgumentException("Found OPUS bitstream."); + } + else if ((header & 0xFF) == 0x7F) + { + return new ArgumentException("Found FLAC bitstream."); + } + else if (header == 0x2020207865657053ul) + { + return new ArgumentException("Found Speex bitstream."); + } + else if (header == 0x0064616568736966ul) + { + // ugh... we need to add support for this in the container reader + return new ArgumentException("Found Skeleton metadata bitstream."); + } + else if ((header & 0xFFFFFFFFFFFF00ul) == 0x61726f65687400ul) + { + return new ArgumentException("Found Theora bitsream."); + } + return new ArgumentException("Could not find Vorbis data to decode."); + } + finally + { + packet.Reset(); + } + } + + #region Init + + private bool ProcessHeaderPackets(IPacket packet) + { + if (!ProcessHeaderPacket(packet, LoadStreamHeader, _ => _packetProvider.GetNextPacket().Done())) + { + return false; + } + + if (!ProcessHeaderPacket(_packetProvider.GetNextPacket(), LoadComments, pkt => pkt.Done())) + { + return false; + } + + if (!ProcessHeaderPacket(_packetProvider.GetNextPacket(), LoadBooks, pkt => pkt.Done())) + { + return false; + } + + _currentPosition = 0; + ResetDecoder(); + return true; + } + + private static bool ProcessHeaderPacket(IPacket packet, Func processAction, Action doneAction) + { + if (packet != null) + { + try + { + return processAction(packet); + } + finally + { + doneAction(packet); + } + } + return false; + } + + static private readonly byte[] PacketSignatureStream = { 0x01, 0x76, 0x6f, 0x72, 0x62, 0x69, 0x73, 0x00, 0x00, 0x00, 0x00 }; + static private readonly byte[] PacketSignatureComments = { 0x03, 0x76, 0x6f, 0x72, 0x62, 0x69, 0x73 }; + static private readonly byte[] PacketSignatureBooks = { 0x05, 0x76, 0x6f, 0x72, 0x62, 0x69, 0x73 }; + + static private bool ValidateHeader(IPacket packet, byte[] expected) + { + for (var i = 0; i < expected.Length; i++) + { + if (expected[i] != packet.ReadBits(8)) + { + return false; + } + } + return true; + } + + static private string ReadString(IPacket packet) + { + var len = (int)packet.ReadBits(32); + + if(len == 0) + { + return string.Empty; + } + + var buf = new byte[len]; + var cnt = packet.Read(buf, 0, len); + if (cnt < len) + { + throw new InvalidDataException("Could not read full string!"); + } + return Encoding.UTF8.GetString(buf); + } + + private bool LoadStreamHeader(IPacket packet) + { + if (!ValidateHeader(packet, PacketSignatureStream)) + { + return false; + } + + _channels = (byte)packet.ReadBits(8); + _sampleRate = (int)packet.ReadBits(32); + UpperBitrate = (int)packet.ReadBits(32); + NominalBitrate = (int)packet.ReadBits(32); + LowerBitrate = (int)packet.ReadBits(32); + + _block0Size = 1 << (int)packet.ReadBits(4); + _block1Size = 1 << (int)packet.ReadBits(4); + + if (NominalBitrate == 0 && UpperBitrate > 0 && LowerBitrate > 0) + { + NominalBitrate = (UpperBitrate + LowerBitrate) / 2; + } + + _stats.SetSampleRate(_sampleRate); + _stats.AddPacket(-1, packet.BitsRead, packet.BitsRemaining, packet.ContainerOverheadBits); + + return true; + } + + private bool LoadComments(IPacket packet) + { + if (!ValidateHeader(packet, PacketSignatureComments)) + { + return false; + } + + _vendor = ReadString(packet); + + _comments = new string[packet.ReadBits(32)]; + for (var i = 0; i < _comments.Length; i++) + { + _comments[i] = ReadString(packet); + } + + _stats.AddPacket(-1, packet.BitsRead, packet.BitsRemaining, packet.ContainerOverheadBits); + + return true; + } + + private bool LoadBooks(IPacket packet) + { + if (!ValidateHeader(packet, PacketSignatureBooks)) + { + return false; + } + + var mdct = _factory.CreateMdct(); + var huffman = _factory.CreateHuffman(); + + // read the books + var books = new ICodebook[packet.ReadBits(8) + 1]; + for (var i = 0; i < books.Length; i++) + { + books[i] = _factory.CreateCodebook(); + books[i].Init(packet, huffman); + } + + // Vorbis never used this feature, so we just skip the appropriate number of bits + var times = (int)packet.ReadBits(6) + 1; + packet.SkipBits(16 * times); + + // read the floors + var floors = new IFloor[packet.ReadBits(6) + 1]; + for (var i = 0; i < floors.Length; i++) + { + floors[i] = _factory.CreateFloor(packet); + floors[i].Init(packet, _channels, _block0Size, _block1Size, books); + } + + // read the residues + var residues = new IResidue[packet.ReadBits(6) + 1]; + for (var i = 0; i < residues.Length; i++) + { + residues[i] = _factory.CreateResidue(packet); + residues[i].Init(packet, _channels, books); + } + + // read the mappings + var mappings = new IMapping[packet.ReadBits(6) + 1]; + for (var i = 0; i < mappings.Length; i++) + { + mappings[i] = _factory.CreateMapping(packet); + mappings[i].Init(packet, _channels, floors, residues, mdct); + } + + // read the modes + _modes = new IMode[packet.ReadBits(6) + 1]; + for (var i = 0; i < _modes.Length; i++) + { + _modes[i] = _factory.CreateMode(); + _modes[i].Init(packet, _channels, _block0Size, _block1Size, mappings); + } + + // verify the closing bit + if (!packet.ReadBit()) throw new InvalidDataException("Book packet did not end on correct bit!"); + + // save off the number of bits to read to determine packet mode + _modeFieldBits = Utils.ilog(_modes.Length - 1); + + _stats.AddPacket(-1, packet.BitsRead, packet.BitsRemaining, packet.ContainerOverheadBits); + + return true; + } + + #endregion + + #region State Change + + private void ResetDecoder() + { + _prevPacketBuf = null; + _prevPacketStart = 0; + _prevPacketEnd = 0; + _prevPacketStop = 0; + _nextPacketBuf = null; + _eosFound = false; + _hasClipped = false; + _hasPosition = false; + } + + #endregion + + #region Decoding + + /// + /// Reads samples into the specified buffer. + /// + /// The buffer to read the samples into. + /// The index to start reading samples into the buffer. + /// The number of samples that should be read into the buffer. Must be a multiple of . + /// The number of samples read into the buffer. + /// Thrown when the buffer is too small or is less than zero. + /// The data populated into is interleaved by channel in normal PCM fashion: Left, Right, Left, Right, Left, Right + public int Read(Span buffer, int offset, int count) + { + if (buffer == null) throw new ArgumentNullException(nameof(buffer)); + if (offset < 0 || offset + count > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); + if (count % _channels != 0) throw new ArgumentOutOfRangeException(nameof(count), "Must be a multiple of Channels!"); + if (_packetProvider == null) throw new ObjectDisposedException(nameof(StreamDecoder)); + + // if the caller didn't ask for any data, bail early + if (count == 0) + { + return 0; + } + + // save off value to track when we're done with the request + var idx = offset; + var tgt = offset + count; + + // try to fill the buffer; drain the last buffer if EOS, resync, bad packet, or parameter change + while (idx < tgt) + { + // if we don't have any more valid data in the current packet, read in the next packet + if (_prevPacketStart == _prevPacketEnd) + { + if (_eosFound) + { + _nextPacketBuf = null; + _prevPacketBuf = null; + + // no more samples, so just return + break; + } + + if (!ReadNextPacket((idx - offset) / _channels, out var samplePosition)) + { + // drain the current packet (the windowing will fade it out) + _prevPacketEnd = _prevPacketStop; + } + + // if we need to pick up a position, and the packet had one, apply the position now + if (samplePosition.HasValue && !_hasPosition) + { + _hasPosition = true; + _currentPosition = samplePosition.Value - (_prevPacketEnd - _prevPacketStart) - (idx - offset) / _channels; + } + } + + // we read out the valid samples from the previous packet + var copyLen = Math.Min((tgt - idx) / _channels, _prevPacketEnd - _prevPacketStart); + if (copyLen > 0) + { + if (ClipSamples) + { + idx += ClippingCopyBuffer(buffer, idx, copyLen); + } + else + { + idx += CopyBuffer(buffer, idx, copyLen); + } + } + } + + // update the count of floats written + count = idx - offset; + + // update the position + _currentPosition += count / _channels; + + // return count of floats written + return count; + } + + private int ClippingCopyBuffer(Span target, int targetIndex, int count) + { + var idx = targetIndex; + for (; count > 0; _prevPacketStart++, count--) + { + for (var ch = 0; ch < _channels; ch++) + { + target[idx++] = Utils.ClipValue(_prevPacketBuf[ch][_prevPacketStart], ref _hasClipped); + } + } + return idx - targetIndex; + } + + private int CopyBuffer(Span target, int targetIndex, int count) + { + var idx = targetIndex; + for (; count > 0; _prevPacketStart++, count--) + { + for (var ch = 0; ch < _channels; ch++) + { + target[idx++] = _prevPacketBuf[ch][_prevPacketStart]; + } + } + return idx - targetIndex; + } + + private bool ReadNextPacket(int bufferedSamples, out long? samplePosition) + { + // decode the next packet now so we can start overlapping with it + var curPacket = DecodeNextPacket(out var startIndex, out var validLen, out var totalLen, out var isEndOfStream, out samplePosition, out var bitsRead, out var bitsRemaining, out var containerOverheadBits); + _eosFound |= isEndOfStream; + if (curPacket == null) + { + _stats.AddPacket(0, bitsRead, bitsRemaining, containerOverheadBits); + return false; + } + + // if we get a max sample position, back off our valid length to match + if (samplePosition.HasValue && isEndOfStream) + { + var actualEnd = _currentPosition + bufferedSamples + validLen - startIndex; + var diff = (int)(samplePosition.Value - actualEnd); + if (diff < 0) + { + validLen += diff; + } + } + + // start overlapping (if we don't have an previous packet data, just loop and the previous packet logic will handle things appropriately) + if (_prevPacketEnd > 0) + { + // overlap the first samples in the packet with the previous packet, then loop + OverlapBuffers(_prevPacketBuf, curPacket, _prevPacketStart, _prevPacketStop, startIndex, _channels); + _prevPacketStart = startIndex; + } + else if (_prevPacketBuf == null) + { + // first packet, so it doesn't have any good data before the valid length + _prevPacketStart = validLen; + } + + // update stats + _stats.AddPacket(validLen - _prevPacketStart, bitsRead, bitsRemaining, containerOverheadBits); + + // keep the old buffer so the GC doesn't have to reallocate every packet + _nextPacketBuf = _prevPacketBuf; + + // save off our current packet's data for the next pass + _prevPacketEnd = validLen; + _prevPacketStop = totalLen; + _prevPacketBuf = curPacket; + return true; + } + + private float[][] DecodeNextPacket(out int packetStartindex, out int packetValidLength, out int packetTotalLength, out bool isEndOfStream, out long? samplePosition, out int bitsRead, out int bitsRemaining, out int containerOverheadBits) + { + IPacket packet = null; + try + { + if ((packet = _packetProvider.GetNextPacket()) == null) + { + // no packet? we're at the end of the stream + isEndOfStream = true; + } + else + { + // if the packet is flagged as the end of the stream, we can safely mark _eosFound + isEndOfStream = packet.IsEndOfStream; + + // resync... that means we've probably lost some data; pick up a new position + if (packet.IsResync) + { + _hasPosition = false; + } + + // grab the container overhead now, since the read won't affect it + containerOverheadBits = packet.ContainerOverheadBits; + + // make sure the packet starts with a 0 bit as per the spec + if (packet.ReadBit()) + { + bitsRemaining = packet.BitsRemaining + 1; + } + else + { + // if we get here, we should have a good packet; decode it and add it to the buffer + var mode = _modes[(int)packet.ReadBits(_modeFieldBits)]; + if (_nextPacketBuf == null) + { + _nextPacketBuf = new float[_channels][]; + for (var i = 0; i < _channels; i++) + { + _nextPacketBuf[i] = new float[_block1Size]; + } + } + if (mode.Decode(packet, _nextPacketBuf, out packetStartindex, out packetValidLength, out packetTotalLength)) + { + // per the spec, do not decode more samples than the last granulePosition + samplePosition = packet.GranulePosition; + bitsRead = packet.BitsRead; + bitsRemaining = packet.BitsRemaining; + return _nextPacketBuf; + } + bitsRemaining = packet.BitsRead + packet.BitsRemaining; + } + } + packetStartindex = 0; + packetValidLength = 0; + packetTotalLength = 0; + samplePosition = null; + bitsRead = 0; + bitsRemaining = 0; + containerOverheadBits = 0; + return null; + } + finally + { + packet?.Done(); + } + } + + private static void OverlapBuffers(float[][] previous, float[][] next, int prevStart, int prevLen, int nextStart, int channels) + { + for (; prevStart < prevLen; prevStart++, nextStart++) + { + for (var c = 0; c < channels; c++) + { + next[c][nextStart] += previous[c][prevStart]; + } + } + } + + #endregion + + #region Seeking + + /// + /// Seeks the stream by the specified duration. + /// + /// The relative time to seek to. + /// The reference point used to obtain the new position. + public void SeekTo(TimeSpan timePosition, SeekOrigin seekOrigin = SeekOrigin.Begin) + { + SeekTo((long)(SampleRate * timePosition.TotalSeconds), seekOrigin); + } + + /// + /// Seeks the stream by the specified sample count. + /// + /// The relative sample position to seek to. + /// The reference point used to obtain the new position. + public void SeekTo(long samplePosition, SeekOrigin seekOrigin = SeekOrigin.Begin) + { + if (_packetProvider == null) throw new ObjectDisposedException(nameof(StreamDecoder)); + if (!_packetProvider.CanSeek) throw new InvalidOperationException("Seek is not supported by the Contracts.IPacketProvider instance."); + + switch (seekOrigin) + { + case SeekOrigin.Begin: + // no-op + break; + case SeekOrigin.Current: + samplePosition = SamplePosition - samplePosition; + break; + case SeekOrigin.End: + samplePosition = TotalSamples - samplePosition; + break; + default: + throw new ArgumentOutOfRangeException(nameof(seekOrigin)); + } + + if (samplePosition < 0) throw new ArgumentOutOfRangeException(nameof(samplePosition)); + + int rollForward; + if (samplePosition == 0) + { + // short circuit for the looping case... + _packetProvider.SeekTo(0, 0, GetPacketGranules); + rollForward = 0; + } + else + { + // seek the stream to the correct position + var pos = _packetProvider.SeekTo(samplePosition, 1, GetPacketGranules); + rollForward = (int)(samplePosition - pos); + } + + // clear out old data + ResetDecoder(); + _hasPosition = true; + + // read the pre-roll packet + if (!ReadNextPacket(0, out _)) + { + // we'll use this to force ReadSamples to fail to read + _eosFound = true; + if (_packetProvider.GetGranuleCount() != samplePosition) + { + throw new InvalidOperationException("Could not read pre-roll packet! Try seeking again prior to reading more samples."); + } + _prevPacketStart = _prevPacketStop; + _currentPosition = samplePosition; + return; + } + + // read the actual packet + if (!ReadNextPacket(0, out _)) + { + ResetDecoder(); + // we'll use this to force ReadSamples to fail to read + _eosFound = true; + throw new InvalidOperationException("Could not read pre-roll packet! Try seeking again prior to reading more samples."); + } + + // adjust our indexes to match what we want + _prevPacketStart += rollForward; + _currentPosition = samplePosition; + } + + private int GetPacketGranules(IPacket curPacket) + { + // if it's a resync, there's not any audio data to return + if (curPacket.IsResync) return 0; + + // if it's not an audio packet, there's no audio data (seems obvious, though...) + if (curPacket.ReadBit()) return 0; + + // OK, let's ask the appropriate mode how long this packet actually is + + // first we need to know which mode... + var modeIdx = (int)curPacket.ReadBits(_modeFieldBits); + + // if we got an invalid mode value, we can't decode any audio data anyway... + if (modeIdx < 0 || modeIdx >= _modes.Length) return 0; + + return _modes[modeIdx].GetPacketSampleCount(curPacket); + } + + #endregion + + /// + /// Cleans up this instance. + /// + public void Dispose() + { + (_packetProvider as IDisposable)?.Dispose(); + _packetProvider = null; + } + + #region Properties + + /// + /// Gets the number of channels in the stream. + /// + public int Channels => _channels; + + /// + /// Gets the sample rate of the stream. + /// + public int SampleRate => _sampleRate; + + /// + /// Gets the upper bitrate limit for the stream, if specified. + /// + public int UpperBitrate { get; private set; } + + /// + /// Gets the nominal bitrate of the stream, if specified. May be calculated from and . + /// + public int NominalBitrate { get; private set; } + + /// + /// Gets the lower bitrate limit for the stream, if specified. + /// + public int LowerBitrate { get; private set; } + + /// + /// Gets the tag data from the stream's header. + /// + public ITagData Tags => _tags ?? (_tags = new TagData(_vendor, _comments)); + + /// + /// Gets the total duration of the decoded stream. + /// + public TimeSpan TotalTime => TimeSpan.FromSeconds((double)TotalSamples / _sampleRate); + + /// + /// Gets the total number of samples in the decoded stream. + /// + public long TotalSamples => _packetProvider?.GetGranuleCount() ?? throw new ObjectDisposedException(nameof(StreamDecoder)); + + /// + /// Gets or sets the current time position of the stream. + /// + public TimeSpan TimePosition + { + get => TimeSpan.FromSeconds((double)_currentPosition / _sampleRate); + set => SeekTo(value); + } + + /// + /// Gets or sets the current sample position of the stream. + /// + public long SamplePosition + { + get => _currentPosition; + set => SeekTo(value); + } + + /// + /// Gets or sets whether to clip samples returned by . + /// + public bool ClipSamples { get; set; } + + /// + /// Gets whether has returned any clipped samples. + /// + public bool HasClipped => _hasClipped; + + /// + /// Gets whether the decoder has reached the end of the stream. + /// + public bool IsEndOfStream => _eosFound && _prevPacketBuf == null; + + /// + /// Gets the instance for this stream. + /// + public IStreamStats Stats => _stats; + + #endregion + } +} diff --git a/Assets/Plugins/NVorbis/StreamDecoder.cs.meta b/Assets/Plugins/NVorbis/StreamDecoder.cs.meta new file mode 100644 index 000000000..f088d37d7 --- /dev/null +++ b/Assets/Plugins/NVorbis/StreamDecoder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7e392ecf197a38640a96fd87cb1a70d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/StreamStats.cs b/Assets/Plugins/NVorbis/StreamStats.cs new file mode 100644 index 000000000..fd73e003c --- /dev/null +++ b/Assets/Plugins/NVorbis/StreamStats.cs @@ -0,0 +1,123 @@ +using NVorbis.Contracts; + +namespace NVorbis +{ + class StreamStats : IStreamStats + { + private int _sampleRate; + + private readonly int[] _packetBits = new int[2]; + private readonly int[] _packetSamples = new int[2]; + private int _packetIndex; + + private long _totalSamples; + private long _audioBits; + private long _headerBits; + private long _containerBits; + private long _wasteBits; + + private object _lock = new object(); + private int _packetCount; + + public int EffectiveBitRate + { + get + { + long samples, bits; + lock (_lock) + { + samples = _totalSamples; + bits = _audioBits + _headerBits + _containerBits + _wasteBits; + } + if (samples > 0) + { + return (int)(((double)bits / samples) * _sampleRate); + } + return 0; + } + } + + public int InstantBitRate + { + get + { + int samples, bits; + lock (_lock) + { + bits = _packetBits[0] + _packetBits[1]; + samples = _packetSamples[0] + _packetSamples[1]; + } + if (samples > 0) + { + return (int)(((double)bits / samples) * _sampleRate); + } + return 0; + } + } + + public long ContainerBits => _containerBits; + + public long OverheadBits => _headerBits; + + public long AudioBits => _audioBits; + + public long WasteBits => _wasteBits; + + public int PacketCount => _packetCount; + + public void ResetStats() + { + lock (_lock) + { + _packetBits[0] = _packetBits[1] = 0; + _packetSamples[0] = _packetSamples[1] = 0; + _packetIndex = 0; + _packetCount = 0; + _audioBits = 0; + _totalSamples = 0; + _headerBits = 0; + _containerBits = 0; + _wasteBits = 0; + } + } + + internal void SetSampleRate(int sampleRate) + { + lock (_lock) + { + _sampleRate = sampleRate; + + ResetStats(); + } + } + + internal void AddPacket(int samples, int bits, int waste, int container) + { + lock (_lock) + { + if (samples >= 0) + { + // audio packet + _audioBits += bits; + _wasteBits += waste; + _containerBits += container; + _totalSamples += samples; + _packetBits[_packetIndex] = bits + waste; + _packetSamples[_packetIndex] = samples; + + if (++_packetIndex == 2) + { + _packetIndex = 0; + } + } + else + { + // header packet + _headerBits += bits; + _wasteBits += waste; + _containerBits += container; + } + } + } + } +} diff --git a/Assets/Plugins/NVorbis/StreamStats.cs.meta b/Assets/Plugins/NVorbis/StreamStats.cs.meta new file mode 100644 index 000000000..47eb18229 --- /dev/null +++ b/Assets/Plugins/NVorbis/StreamStats.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bc63f4b912466ce4ea9726530aa30f22 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/TagData.cs b/Assets/Plugins/NVorbis/TagData.cs new file mode 100644 index 000000000..eb11abad6 --- /dev/null +++ b/Assets/Plugins/NVorbis/TagData.cs @@ -0,0 +1,106 @@ +using NVorbis.Contracts; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace NVorbis +{ + internal class TagData : ITagData + { + static IReadOnlyList s_emptyList = new List(); + + Dictionary> _tags; + + public TagData(string vendor, string[] comments) + { + EncoderVendor = vendor; + + var tags = new Dictionary>(); + for (var i = 0; i < comments.Length; i++) + { + var parts = comments[i].Split('='); + if (parts.Length == 1) + { + parts = new[] { parts[0], string.Empty }; + } + + var bktIdx = parts[0].IndexOf('['); + if (bktIdx > -1) + { + parts[1] = parts[0].Substring(bktIdx + 1, parts[0].Length - bktIdx - 2) + .ToUpper(System.Globalization.CultureInfo.CurrentCulture) + + ": " + + parts[1]; + parts[0] = parts[0].Substring(0, bktIdx); + } + + if (tags.TryGetValue(parts[0].ToUpperInvariant(), out var list)) + { + ((List)list).Add(parts[1]); + } + else + { + tags.Add(parts[0].ToUpperInvariant(), new List { parts[1] }); + } + } + _tags = tags; + } + + public string GetTagSingle(string key, bool concatenate = false) + { + var values = GetTagMulti(key); + if (values.Count > 0) + { + if (concatenate) + { + return string.Join(Environment.NewLine, values.ToArray()); + } + return values[values.Count - 1]; + } + return string.Empty; + } + + public IReadOnlyList GetTagMulti(string key) + { + if (_tags.TryGetValue(key.ToUpperInvariant(), out var values)) + { + return values; + } + return s_emptyList; + } + + public IReadOnlyDictionary> All => _tags; + + public string EncoderVendor { get; } + + public string Title => GetTagSingle("TITLE"); + + public string Version => GetTagSingle("VERSION"); + + public string Album => GetTagSingle("ALBUM"); + + public string TrackNumber => GetTagSingle("TRACKNUMBER"); + + public string Artist => GetTagSingle("ARTIST"); + + public IReadOnlyList Performers => GetTagMulti("PERFORMER"); + + public string Copyright => GetTagSingle("COPYRIGHT"); + + public string License => GetTagSingle("LICENSE"); + + public string Organization => GetTagSingle("ORGANIZATION"); + + public string Description => GetTagSingle("DESCRIPTION"); + + public IReadOnlyList Genres => GetTagMulti("GENRE"); + + public IReadOnlyList Dates => GetTagMulti("DATE"); + + public IReadOnlyList Locations => GetTagMulti("LOCATION"); + + public string Contact => GetTagSingle("CONTACT"); + + public string Isrc => GetTagSingle("ISRC"); + } +} \ No newline at end of file diff --git a/Assets/Plugins/NVorbis/TagData.cs.meta b/Assets/Plugins/NVorbis/TagData.cs.meta new file mode 100644 index 000000000..e2686b0e3 --- /dev/null +++ b/Assets/Plugins/NVorbis/TagData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c104575be6f116b4c8e80bd43be659a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/Utils.cs b/Assets/Plugins/NVorbis/Utils.cs new file mode 100644 index 000000000..047dcb1df --- /dev/null +++ b/Assets/Plugins/NVorbis/Utils.cs @@ -0,0 +1,61 @@ +namespace NVorbis +{ + static class Utils + { + static internal int ilog(int x) + { + int cnt = 0; + while (x > 0) + { + ++cnt; + x >>= 1; // this is safe because we'll never get here if the sign bit is set + } + return cnt; + } + + static internal uint BitReverse(uint n) + { + return BitReverse(n, 32); + } + + static internal uint BitReverse(uint n, int bits) + { + n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); + n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); + n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); + n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); + return ((n >> 16) | (n << 16)) >> (32 - bits); + } + + static internal float ClipValue(float value, ref bool clipped) + { + if (value > .99999994f) + { + clipped = true; + return 0.99999994f; + } + if (value < -.99999994f) + { + clipped = true; + return -0.99999994f; + } + return value; + } + + static internal float ConvertFromVorbisFloat32(uint bits) + { + // do as much as possible with bit tricks in integer math + var sign = ((int)bits >> 31); // sign-extend to the full 32-bits + var exponent = (double)((int)((bits & 0x7fe00000) >> 21) - 788); // grab the exponent, remove the bias, store as double (for the call to System.Math.Pow(...)) + var mantissa = (float)(((bits & 0x1fffff) ^ sign) + (sign & 1)); // grab the mantissa and apply the sign bit. store as float + + // NB: We could use bit tricks to calc the exponent, but it can't be more than 63 in either direction. + // This creates an issue, since the exponent field allows for a *lot* more than that. + // On the flip side, larger exponent values don't seem to be used by the Vorbis codebooks... + // Either way, we'll play it safe and let the BCL calculate it. + + // now switch to single-precision and calc the return value + return mantissa * (float)System.Math.Pow(2.0, exponent); + } + } +} diff --git a/Assets/Plugins/NVorbis/Utils.cs.meta b/Assets/Plugins/NVorbis/Utils.cs.meta new file mode 100644 index 000000000..c81aee95f --- /dev/null +++ b/Assets/Plugins/NVorbis/Utils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c7a69c4842d3734aa9b09824e149a1b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/NVorbis/VorbisReader.cs b/Assets/Plugins/NVorbis/VorbisReader.cs new file mode 100644 index 000000000..b00b4b686 --- /dev/null +++ b/Assets/Plugins/NVorbis/VorbisReader.cs @@ -0,0 +1,373 @@ +using NVorbis.Contracts; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace NVorbis +{ + /// + /// Implements an easy to use wrapper around and . + /// + public sealed class VorbisReader : IVorbisReader + { + internal static Func CreateContainerReader { get; set; } = (s, cod) => new Ogg.ContainerReader(s, cod); + internal static Func CreateStreamDecoder { get; set; } = pp => new StreamDecoder(pp, new Factory()); + + private readonly List _decoders; + private readonly Contracts.IContainerReader _containerReader; + private readonly bool _closeOnDispose; + + private IStreamDecoder _streamDecoder; + + /// + /// Raised when a new stream has been encountered in the file or container. + /// + public event EventHandler NewStream; + + /// + /// Creates a new instance of reading from the specified file. + /// + /// The file to read from. + public VorbisReader(string fileName) + : this(File.OpenRead(fileName), true) + { + } + + /// + /// Creates a new instance of reading from the specified stream, optionally taking ownership of it. + /// + /// The to read from. + /// to take ownership and clean up the instance when disposed, otherwise . + public VorbisReader(Stream stream, bool closeOnDispose = true) + { + _decoders = new List(); + + var containerReader = CreateContainerReader(stream, closeOnDispose); + containerReader.NewStreamCallback = ProcessNewStream; + + if (!containerReader.TryInit() || _decoders.Count == 0) + { + containerReader.NewStreamCallback = null; + containerReader.Dispose(); + + if (closeOnDispose) + { + stream.Dispose(); + } + + throw new ArgumentException("Could not load the specified container!", nameof(containerReader)); + } + _closeOnDispose = closeOnDispose; + _containerReader = containerReader; + _streamDecoder = _decoders[0]; + } + +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member + [Obsolete("Use \"new StreamDecoder(Contracts.IPacketProvider)\" and the container's NewStreamCallback or Streams property instead.", true)] + public VorbisReader(Contracts.IContainerReader containerReader) => throw new NotSupportedException(); + + [Obsolete("Use \"new StreamDecoder(Contracts.IPacketProvider)\" instead.", true)] + public VorbisReader(Contracts.IPacketProvider packetProvider) => throw new NotSupportedException(); +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member + + private bool ProcessNewStream(Contracts.IPacketProvider packetProvider) + { + var decoder = CreateStreamDecoder(packetProvider); + decoder.ClipSamples = true; + + var ea = new NewStreamEventArgs(decoder); + NewStream?.Invoke(this, ea); + if (!ea.IgnoreStream) + { + _decoders.Add(decoder); + return true; + } + return false; + } + + /// + /// Cleans up this instance. + /// + public void Dispose() + { + if (_decoders != null) + { + foreach (var decoder in _decoders) + { + decoder.Dispose(); + } + _decoders.Clear(); + } + + if (_containerReader != null) + { + _containerReader.NewStreamCallback = null; + if (_closeOnDispose) + { + _containerReader.Dispose(); + } + } + } + + /// + /// Gets the list of instances associated with the loaded file / container. + /// + public IReadOnlyList Streams => _decoders; + + #region Convenience Helpers + + // Since most uses of VorbisReader are for single-stream audio files, we can make life simpler for users + // by exposing the first stream's properties and methods here. + + /// + /// Gets the number of channels in the stream. + /// + public int Channels => _streamDecoder.Channels; + + /// + /// Gets the sample rate of the stream. + /// + public int SampleRate => _streamDecoder.SampleRate; + + /// + /// Gets the upper bitrate limit for the stream, if specified. + /// + public int UpperBitrate => _streamDecoder.UpperBitrate; + + /// + /// Gets the nominal bitrate of the stream, if specified. May be calculated from and . + /// + public int NominalBitrate => _streamDecoder.NominalBitrate; + + /// + /// Gets the lower bitrate limit for the stream, if specified. + /// + public int LowerBitrate => _streamDecoder.LowerBitrate; + + /// + /// Gets the tag data from the stream's header. + /// + public ITagData Tags => _streamDecoder.Tags; + + /// + /// Gets the encoder's vendor string for the current selected Vorbis stream + /// + [Obsolete("Use .Tags.EncoderVendor instead.")] + public string Vendor => _streamDecoder.Tags.EncoderVendor; + + /// + /// Gets the comments in the current selected Vorbis stream + /// + [Obsolete("Use .Tags.All instead.")] + public string[] Comments => _streamDecoder.Tags.All.SelectMany(k => k.Value, (kvp, Item) => $"{kvp.Key}={Item}").ToArray(); + + /// + /// Gets whether the previous short sample count was due to a parameter change in the stream. + /// + [Obsolete("No longer supported. Will receive a new stream when parameters change.", true)] + public bool IsParameterChange => throw new NotSupportedException(); + + /// + /// Gets the number of bits read that are related to framing and transport alone. + /// + public long ContainerOverheadBits => _containerReader?.ContainerBits ?? 0; + + /// + /// Gets the number of bits skipped in the container due to framing, ignored streams, or sync loss. + /// + public long ContainerWasteBits => _containerReader?.WasteBits ?? 0; + + /// + /// Gets the currently-selected stream's index. + /// + public int StreamIndex => _decoders.IndexOf(_streamDecoder); + + /// + /// Returns the number of logical streams found so far in the physical container. + /// + [Obsolete("Use .Streams.Count instead.")] + public int StreamCount => _decoders.Count; + + /// + /// Gets or Sets the current timestamp of the decoder. Is the timestamp before the next sample to be decoded. + /// + [Obsolete("Use VorbisReader.TimePosition instead.")] + public TimeSpan DecodedTime + { + get => _streamDecoder.TimePosition; + set => TimePosition = value; + } + + /// + /// Gets or Sets the current position of the next sample to be decoded. + /// + [Obsolete("Use VorbisReader.SamplePosition instead.")] + public long DecodedPosition + { + get => _streamDecoder.SamplePosition; + set => SamplePosition = value; + } + + /// + /// Gets the total duration of the decoded stream. + /// + public TimeSpan TotalTime => _streamDecoder.TotalTime; + + /// + /// Gets the total number of samples in the decoded stream. + /// + public long TotalSamples => _streamDecoder.TotalSamples; + + /// + /// Gets or sets the current time position of the stream. + /// + public TimeSpan TimePosition + { + get => _streamDecoder.TimePosition; + set + { + _streamDecoder.TimePosition = value; + } + } + + /// + /// Gets or sets the current sample position of the stream. + /// + public long SamplePosition + { + get => _streamDecoder.SamplePosition; + set + { + _streamDecoder.SamplePosition = value; + } + } + + /// + /// Gets whether the current stream has ended. + /// + public bool IsEndOfStream => _streamDecoder.IsEndOfStream; + + /// + /// Gets or sets whether to clip samples returned by . + /// + public bool ClipSamples + { + get => _streamDecoder.ClipSamples; + set => _streamDecoder.ClipSamples = value; + } + + /// + /// Gets whether has returned any clipped samples. + /// + public bool HasClipped => _streamDecoder.HasClipped; + + /// + /// Gets the instance for this stream. + /// + public IStreamStats StreamStats => _streamDecoder.Stats; + + /// + /// Gtes stats from each decoder stream available. + /// + [Obsolete("Use Streams[*].Stats instead.", true)] + public IVorbisStreamStatus[] Stats => throw new NotSupportedException(); + + /// + /// Searches for the next stream in a concatenated file. Will raise for the found stream, and will add it to if not marked as ignored. + /// + /// if a new stream was found, otherwise . + public bool FindNextStream() + { + if (_containerReader == null) return false; + return _containerReader.FindNextStream(); + } + + /// + /// Switches to an alternate logical stream. + /// + /// The logical stream index to switch to + /// if the properties of the logical stream differ from those of the one previously being decoded. Otherwise, . + public bool SwitchStreams(int index) + { + if (index < 0 || index >= _decoders.Count) throw new ArgumentOutOfRangeException(nameof(index)); + + var newDecoder = _decoders[index]; + var oldDecoder = _streamDecoder; + if (newDecoder == oldDecoder) return false; + + // carry-through the clipping setting + newDecoder.ClipSamples = oldDecoder.ClipSamples; + + _streamDecoder = newDecoder; + + return newDecoder.Channels != oldDecoder.Channels || newDecoder.SampleRate != oldDecoder.SampleRate; + } + + /// + /// Seeks the stream by the specified duration. + /// + /// The relative time to seek to. + /// The reference point used to obtain the new position. + public void SeekTo(TimeSpan timePosition, SeekOrigin seekOrigin = SeekOrigin.Begin) + { + _streamDecoder.SeekTo(timePosition, seekOrigin); + } + + /// + /// Seeks the stream by the specified sample count. + /// + /// The relative sample position to seek to. + /// The reference point used to obtain the new position. + public void SeekTo(long samplePosition, SeekOrigin seekOrigin = SeekOrigin.Begin) + { + _streamDecoder.SeekTo(samplePosition, seekOrigin); + } + + /// + /// Reads samples into the specified buffer. + /// + /// The buffer to read the samples into. + /// The index to start reading samples into the buffer. + /// The number of samples that should be read into the buffer. + /// The number of floats read into the buffer. + /// Thrown when the buffer is too small or is less than zero. + /// The data populated into is interleaved by channel in normal PCM fashion: Left, Right, Left, Right, Left, Right + public int ReadSamples(float[] buffer, int offset, int count) + { + // don't allow non-aligned reads (always on a full sample boundary!) + count -= count % _streamDecoder.Channels; + if (count > 0) + { + return _streamDecoder.Read(buffer, offset, count); + } + return 0; + } + + /// + /// Reads samples into the specified buffer. + /// + /// The buffer to read the samples into. + /// The number of floats read into the buffer. + /// Thrown when the buffer is too small. + /// The data populated into is interleaved by channel in normal PCM fashion: Left, Right, Left, Right, Left, Right + public int ReadSamples(Span buffer) + { + // don't allow non-aligned reads (always on a full sample boundary!) + int count = buffer.Length - buffer.Length % _streamDecoder.Channels; + if (!buffer.IsEmpty) + { + return _streamDecoder.Read(buffer, 0, count); + } + return 0; + } + + /// + /// Acknowledges a parameter change as signalled by . + /// + [Obsolete("No longer needed.", true)] + public void ClearParameterChange() => throw new NotSupportedException(); + + #endregion + } +} diff --git a/Assets/Plugins/NVorbis/VorbisReader.cs.meta b/Assets/Plugins/NVorbis/VorbisReader.cs.meta new file mode 100644 index 000000000..4602c50e8 --- /dev/null +++ b/Assets/Plugins/NVorbis/VorbisReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4c3eec766dae8c8469acbf8b085510e6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/System.Buffers.dll b/Assets/Plugins/System.Buffers.dll new file mode 100644 index 000000000..f2d83c514 Binary files /dev/null and b/Assets/Plugins/System.Buffers.dll differ diff --git a/Assets/Plugins/System.Buffers.dll.meta b/Assets/Plugins/System.Buffers.dll.meta new file mode 100644 index 000000000..7c60abbce --- /dev/null +++ b/Assets/Plugins/System.Buffers.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 9d330b0ab55525a478dbe249c58b3966 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/System.Memory.dll b/Assets/Plugins/System.Memory.dll new file mode 100644 index 000000000..461719979 Binary files /dev/null and b/Assets/Plugins/System.Memory.dll differ diff --git a/Assets/Plugins/System.Memory.dll.meta b/Assets/Plugins/System.Memory.dll.meta new file mode 100644 index 000000000..0a5a3c4d0 --- /dev/null +++ b/Assets/Plugins/System.Memory.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 4dd031bcc1fe0df418101bfb3065e9fa +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll new file mode 100644 index 000000000..c5ba4e404 Binary files /dev/null and b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll differ diff --git a/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll.meta b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll.meta new file mode 100644 index 000000000..81e0fbd7c --- /dev/null +++ b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: fda680499a190b3449d1586c63dd628f +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.xml b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.xml new file mode 100644 index 000000000..9d794922c --- /dev/null +++ b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.xml @@ -0,0 +1,291 @@ + + + + System.Runtime.CompilerServices.Unsafe + + + + Contains generic, low-level functionality for manipulating pointers. + + + Adds an element offset to the given reference. + The reference to add the offset to. + The offset to add. + The type of reference. + A new reference that reflects the addition of offset to pointer. + + + Adds an element offset to the given reference. + The reference to add the offset to. + The offset to add. + The type of reference. + A new reference that reflects the addition of offset to pointer. + + + Adds an element offset to the given reference. + The reference to add the offset to. + The offset to add. + The type of reference. + A new reference that reflects the addition of offset to pointer. + + + Adds an element offset to the given void pointer. + The void pointer to add the offset to. + The offset to add. + The type of void pointer. + A new void pointer that reflects the addition of offset to the specified pointer. + + + Adds a byte offset to the given reference. + The reference to add the offset to. + The offset to add. + The type of reference. + A new reference that reflects the addition of byte offset to pointer. + + + Adds a byte offset to the given reference. + The reference to add the offset to. + The offset to add. + The type of reference. + A new reference that reflects the addition of byte offset to pointer. + + + Determines whether the specified references point to the same location. + The first reference to compare. + The second reference to compare. + The type of reference. + + if and point to the same location; otherwise, . + + + Casts the given object to the specified type. + The object to cast. + The type which the object will be cast to. + The original object, casted to the given type. + + + Reinterprets the given reference as a reference to a value of type . + The reference to reinterpret. + The type of reference to reinterpret. + The desired type of the reference. + A reference to a value of type . + + + Returns a pointer to the given by-ref parameter. + The object whose pointer is obtained. + The type of object. + A pointer to the given value. + + + Reinterprets the given read-only reference as a reference. + The read-only reference to reinterpret. + The type of reference. + A reference to a value of type . + + + Reinterprets the given location as a reference to a value of type . + The location of the value to reference. + The type of the interpreted location. + A reference to a value of type . + + + Determines the byte offset from origin to target from the given references. + The reference to origin. + The reference to target. + The type of reference. + Byte offset from origin to target i.e. - . + + + Copies a value of type to the given location. + The location to copy to. + A pointer to the value to copy. + The type of value to copy. + + + Copies a value of type to the given location. + The location to copy to. + A reference to the value to copy. + The type of value to copy. + + + Copies bytes from the source address to the destination address. + The destination address to copy to. + The source address to copy from. + The number of bytes to copy. + + + Copies bytes from the source address to the destination address. + The destination address to copy to. + The source address to copy from. + The number of bytes to copy. + + + Copies bytes from the source address to the destination address without assuming architecture dependent alignment of the addresses. + The destination address to copy to. + The source address to copy from. + The number of bytes to copy. + + + Copies bytes from the source address to the destination address without assuming architecture dependent alignment of the addresses. + The destination address to copy to. + The source address to copy from. + The number of bytes to copy. + + + Initializes a block of memory at the given location with a given initial value. + The address of the start of the memory block to initialize. + The value to initialize the block to. + The number of bytes to initialize. + + + Initializes a block of memory at the given location with a given initial value. + The address of the start of the memory block to initialize. + The value to initialize the block to. + The number of bytes to initialize. + + + Initializes a block of memory at the given location with a given initial value without assuming architecture dependent alignment of the address. + The address of the start of the memory block to initialize. + The value to initialize the block to. + The number of bytes to initialize. + + + Initializes a block of memory at the given location with a given initial value without assuming architecture dependent alignment of the address. + The address of the start of the memory block to initialize. + The value to initialize the block to. + The number of bytes to initialize. + + + Returns a value that indicates whether a specified reference is greater than another specified reference. + The first value to compare. + The second value to compare. + The type of the reference. + + if is greater than ; otherwise, . + + + Returns a value that indicates whether a specified reference is less than another specified reference. + The first value to compare. + The second value to compare. + The type of the reference. + + if is less than ; otherwise, . + + + Determines if a given reference to a value of type is a null reference. + The reference to check. + The type of the reference. + + if is a null reference; otherwise, . + + + Returns a reference to a value of type that is a null reference. + The type of the reference. + A reference to a value of type that is a null reference. + + + Reads a value of type from the given location. + The location to read from. + The type to read. + An object of type read from the given location. + + + Reads a value of type from the given location without assuming architecture dependent alignment of the addresses. + The location to read from. + The type to read. + An object of type read from the given location. + + + Reads a value of type from the given location without assuming architecture dependent alignment of the addresses. + The location to read from. + The type to read. + An object of type read from the given location. + + + Returns the size of an object of the given type parameter. + The type of object whose size is retrieved. + The size of an object of type . + + + Bypasses definite assignment rules for a given value. + The uninitialized object. + The type of the uninitialized object. + + + Subtracts an element offset from the given reference. + The reference to subtract the offset from. + The offset to subtract. + The type of reference. + A new reference that reflects the subtraction of offset from pointer. + + + Subtracts an element offset from the given reference. + The reference to subtract the offset from. + The offset to subtract. + The type of reference. + A new reference that reflects the subtraction of offset from pointer. + + + Subtracts an element offset from the given reference. + The reference to subtract the offset from. + The offset to subtract. + The type of reference. + A new reference that reflects the subraction of offset from pointer. + + + Subtracts an element offset from the given void pointer. + The void pointer to subtract the offset from. + The offset to subtract. + The type of the void pointer. + A new void pointer that reflects the subtraction of offset from the specified pointer. + + + Subtracts a byte offset from the given reference. + The reference to subtract the offset from. + The offset to subtract. + The type of reference. + A new reference that reflects the subtraction of byte offset from pointer. + + + Subtracts a byte offset from the given reference. + The reference to subtract the offset from. + The offset to subtract. + The type of reference. + A new reference that reflects the subraction of byte offset from pointer. + + + Returns a to a boxed value. + The value to unbox. + The type to be unboxed. + + is , and is a non-nullable value type. + + is not a boxed value type. + +-or- + + is not a boxed . + + cannot be found. + A to the boxed value . + + + Writes a value of type to the given location. + The location to write to. + The value to write. + The type of value to write. + + + Writes a value of type to the given location without assuming architecture dependent alignment of the addresses. + The location to write to. + The value to write. + The type of value to write. + + + Writes a value of type to the given location without assuming architecture dependent alignment of the addresses. + The location to write to. + The value to write. + The type of value to write. + + + \ No newline at end of file diff --git a/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.xml.meta b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.xml.meta new file mode 100644 index 000000000..bb46851cb --- /dev/null +++ b/Assets/Plugins/System.Runtime.CompilerServices.Unsafe.xml.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b54acb07d05cb084abd99e54178f5660 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_Graphics/Textures And Sprites/Mapper/UIMode/UIMode Title.mat b/Assets/_Graphics/Textures And Sprites/Mapper/UIMode/UIMode Title.mat index 32c687d0f..28fa1b2ba 100644 --- a/Assets/_Graphics/Textures And Sprites/Mapper/UIMode/UIMode Title.mat +++ b/Assets/_Graphics/Textures And Sprites/Mapper/UIMode/UIMode Title.mat @@ -82,9 +82,9 @@ Material: - _Color: {r: 0.5, g: 0.5, b: 0.5, a: 1} - _EmissionColor: {r: 0, g: 0, b: 0, a: 1} - _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1} - - _halfSize: {r: 35.54, g: 12.5, b: 0, a: 0} + - _halfSize: {r: 0, g: 12.5, b: 0, a: 0} - _r: {r: 18, g: 18, b: 0, a: 0} - - _rect2props: {r: 0.0000019073486, g: -9.000006, b: 27.605452, a: 27.605452} + - _rect2props: {r: -0.0000019073486, g: -9.000003, b: 2.474874, a: 2.474874} m_BuildTextureStacks: [] --- !u!114 &865370036408331707 MonoBehaviour: diff --git a/Assets/__Scripts/MapEditor/AudioTimeSyncController.cs b/Assets/__Scripts/MapEditor/AudioTimeSyncController.cs index a44b77c46..96fcbc2fe 100644 --- a/Assets/__Scripts/MapEditor/AudioTimeSyncController.cs +++ b/Assets/__Scripts/MapEditor/AudioTimeSyncController.cs @@ -4,6 +4,9 @@ using UnityEngine.InputSystem; using UnityEngine.Serialization; using UnityEngine.UI; +using NAudio.Wave; +using NAudio.Vorbis; +using System.IO; public class AudioTimeSyncController : MonoBehaviour, CMInput.IPlaybackActions, CMInput.ITimelineActions, CMInput.ITimelineNavigationActions { @@ -12,7 +15,7 @@ public class AudioTimeSyncController : MonoBehaviour, CMInput.IPlaybackActions, private static readonly int songTime = Shader.PropertyToID("_SongTime"); private const float cancelPlayInputDuration = 0.3f; - [FormerlySerializedAs("songAudioSource")] public AudioSource SongAudioSource; + //ELECAST TEST [FormerlySerializedAs("songAudioSource")] public AudioSource SongAudioSource; [SerializeField] private AudioSource waveformSource; [SerializeField] private GameObject moveables; @@ -98,12 +101,19 @@ private set } } - public float CurrentAudioSeconds => SongAudioSource.clip is null ? 0f : SongAudioSource.timeSamples / (float)SongAudioSource.clip.frequency; + //ELECAST TEST public float CurrentAudioSeconds => SongAudioSource.clip is null ? 0f : SongAudioSource.timeSamples / (float)SongAudioSource.clip.frequency; + + public float CurrentAudioSeconds => Vorbis is null ? 0f : IsPlaying ? CurrentSeconds : Vorbis.SamplePosition/sampleRate;//ELECAST TEST public float CurrentAudioBeats => GetBeatFromSeconds(CurrentAudioSeconds); public bool IsPlaying { get; private set; } + private int bytesPerSecond;//ELECAST TEST + private WaveOutEvent waveOut; //ELECAST TEST + public VorbisSampleProvider Vorbis; //ELECAST TEST + private int sampleRate; //ELECAST TEST + // Use this for initialization private void Start() { @@ -112,10 +122,18 @@ private void Start() //Init dat stuff clip = BeatSaberSongContainer.Instance.LoadedSong; Song = BeatSaberSongContainer.Instance.Song; + ResetTime(); IsPlaying = false; - SongAudioSource.clip = clip; - SongAudioSource.volume = Settings.Instance.SongVolume; + //ELECAST TEST SongAudioSource.clip = clip; + //ELECAST TEST SongAudioSource.volume = Settings.Instance.SongVolume; + + Vorbis = new VorbisSampleProvider(File.OpenRead(Song.Directory + "\\" + Song.SongFilename), true);//ELECAST TEST + bytesPerSecond = Vorbis.WaveFormat.AverageBytesPerSecond;//ELECAST TEST + sampleRate = Vorbis.WaveFormat.SampleRate;//ELECAST TEST + waveOut = new WaveOutEvent();//ELECAST TEST + waveOut.Init(Vorbis);//ELECAST TEST + waveformSource.clip = clip; UpdateMovables(); if (Settings.NonPersistentSettings.ContainsKey(PrecisionSnapName)) @@ -148,7 +166,8 @@ private void Update() // Sync correction var correction = time > 1 ? trackTime / time : 1f; - if (SongAudioSource.isPlaying) + if (waveOut.PlaybackState == PlaybackState.Playing) //ELECAST TEST + //if (SongAudioSource.isPlaying) { // Snap forward if we are more than a 2 frames out of sync as we're trying to make it one frame out? var frameTime = Mathf.Max(0.04f, Time.smoothDeltaTime * 2); @@ -306,9 +325,19 @@ public void OnMoveCursorBackward(InputAction.CallbackContext context) CurrentJsonTime -= (1f / gridMeasureSnapping); } - private void UpdateSongVolume(object obj) => SongAudioSource.volume = (float)obj; + //ELECAST TEST private void UpdateSongVolume(object obj) => SongAudioSource.volume = (float)obj; + private void UpdateSongVolume(object obj) => waveOut.Volume = (float)obj;//ELECAST TEST + + //ELECAST TEST private void UpdateSongSpeed(object obj) => songSpeed = (float)obj; + private void UpdateSongSpeed(object obj) //ELECAST TEST + { + songSpeed = (float)obj; + + + //TODO Add NAudio Support!! - private void UpdateSongSpeed(object obj) => songSpeed = (float)obj; + } + private void OnLevelLoaded() => levelLoaded = true; @@ -347,27 +376,36 @@ public void TogglePlaying() IsPlaying = !IsPlaying; if (IsPlaying) { - if (CurrentSeconds >= SongAudioSource.clip.length - 0.1f) + //ELECAST TEST if (CurrentSeconds >= SongAudioSource.clip.length - 0.1f) + if (CurrentSeconds >= GetTotalSeconds() - 0.1f)//ELECAST TEST { ResetTime(); } playStartTime = CurrentSeconds; - SongAudioSource.time = CurrentSeconds; - SongAudioSource.Play(); + //ELECAST TEST SongAudioSource.time = CurrentSeconds; + //ELECAST TEST SongAudioSource.Play(); + SetVorbisPosition((long)(CurrentSeconds * bytesPerSecond));//ELECAST TEST + waveOut.Play();//ELECAST TEST audioLatencyCompensationSeconds = Settings.Instance.AudioLatencyCompensation / 1000f; CurrentSeconds -= audioLatencyCompensationSeconds * (songSpeed / 10f); } else { - SongAudioSource.Stop(); + //ELECAST TEST SongAudioSource.Stop(); + waveOut.Stop();//ELECAST TEST SnapToGrid(); } PlayToggle?.Invoke(IsPlaying); } + public float GetTotalSeconds() + { + return (float)Vorbis.Length / sampleRate; + } + public void CancelPlaying() { if (!IsPlaying) return; @@ -381,7 +419,8 @@ public void SnapToGrid(float seconds) if (IsPlaying) return; var songBpmTime = GetBeatFromSeconds(seconds); UpdateCurrentTimes(songBpmTime); - SongAudioSource.time = CurrentSeconds; + //ELECAST TEST SongAudioSource.time = CurrentSeconds; + SetVorbisPosition((long)(CurrentSeconds * bytesPerSecond));//ELECAST TEST ValidatePosition(); UpdateMovables(); } @@ -406,7 +445,8 @@ public void MoveToTimeInSeconds(float seconds) { if (IsPlaying) return; CurrentSeconds = seconds; - SongAudioSource.time = CurrentSeconds; + //ELECAST TEST SongAudioSource.time = CurrentSeconds; + SetVorbisPosition((long)(CurrentSeconds * bytesPerSecond));//ELECAST TEST } [Obsolete("This is for existing dev plugin compatibility. Use MoveToSongBpmTime or MoveToJsonTime.", true)] @@ -415,14 +455,25 @@ public void MoveToSongBpmTime(float songBpmTime) { if (IsPlaying) return; CurrentSongBpmTime = songBpmTime; - SongAudioSource.time = CurrentSeconds; + //ELECAST TEST SongAudioSource.time = CurrentSeconds; + SetVorbisPosition((long)(CurrentSeconds * bytesPerSecond));//ELECAST TEST } public void MoveToJsonTime(float jsonTime) { if (IsPlaying) return; CurrentJsonTime = jsonTime; - SongAudioSource.time = CurrentSeconds; + //ELECAST TEST SongAudioSource.time = CurrentSeconds; + SetVorbisPosition((long)(CurrentSeconds * bytesPerSecond));//ELECAST TEST + } + + //ELECAST TEST + private void SetVorbisPosition(long value) + { + if (!Vorbis.CanSeek) throw new InvalidOperationException("Cannot seek!"); + if (value < 0 || value > Vorbis.Length * Vorbis.WaveFormat.BlockAlign) throw new ArgumentOutOfRangeException(nameof(value)); + + Vorbis.Seek(value / Vorbis.WaveFormat.BlockAlign); } public float FindRoundedBeatTime(float beat, float snap = -1) => bpmChangeGridContainer.FindRoundedBpmTime(beat, snap); diff --git a/Assets/__Scripts/MapEditor/UI/SongTimelineController.cs b/Assets/__Scripts/MapEditor/UI/SongTimelineController.cs index a4676dab0..0540311b7 100644 --- a/Assets/__Scripts/MapEditor/UI/SongTimelineController.cs +++ b/Assets/__Scripts/MapEditor/UI/SongTimelineController.cs @@ -9,7 +9,7 @@ public class SongTimelineController : MonoBehaviour, IPointerEnterHandler, IPoin [SerializeField] private AudioTimeSyncController atsc; [SerializeField] private Slider slider; [SerializeField] private TextMeshProUGUI timeMesh; - [SerializeField] private AudioSource mainAudioSource; + //ELECAST TEST [SerializeField] private AudioSource mainAudioSource; public bool IsClicked; private float lastSongTime; @@ -20,8 +20,10 @@ public class SongTimelineController : MonoBehaviour, IPointerEnterHandler, IPoin // Use this for initialization private IEnumerator Start() { - yield return new WaitUntil(() => mainAudioSource.clip != null); - songLength = mainAudioSource.clip.length; + //ELECAST TEST yield return new WaitUntil(() => mainAudioSource.clip != null); + //ELECAST TEST songLength = mainAudioSource.clip.length; + yield return new WaitUntil(() => atsc.Vorbis != null);//ELECAST TEST + songLength = atsc.GetTotalSeconds();//ELECAST TEST slider.value = 0; } diff --git a/ChroMapper.sln b/ChroMapper.sln index 7beee3c3f..6b469375f 100644 --- a/ChroMapper.sln +++ b/ChroMapper.sln @@ -1,51 +1,72 @@  -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Main", "Main.csproj", "{858c4f7a-1565-f78e-dcd9-8afd7f774a8d}" +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Main", "Main.csproj", "{5F38D385-41EB-CDED-AD43-EA25F3170559}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LiteNetLib", "LiteNetLib.csproj", "{70dbcc3d-468a-7b53-95c3-f388f6d81597}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LiteNetLib", "LiteNetLib.csproj", "{7E33E53E-21E1-2E91-7399-70C9C99EAD23}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests.csproj", "{2bbaf7f3-7fb3-9dad-56ed-d77c857e16e7}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests.csproj", "{A5B1949A-27E4-B8CA-6F2F-D17BCE52BE27}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Plugins", "Plugins.csproj", "{5a93d2e8-5187-efa6-e448-6343b5c9687f}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Plugins", "Plugins.csproj", "{BA95DD72-D2E3-6610-8917-028D9A433839}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nobi.UiRoundedCorners", "Nobi.UiRoundedCorners.csproj", "{e4748aaa-cc8b-9e27-641e-886d217d97e6}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nobi.UiRoundedCorners", "Nobi.UiRoundedCorners.csproj", "{8C18E31F-03EC-D379-2CE1-3042B474FA5A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Intersections", "Intersections.csproj", "{c68e6dcf-0176-53b3-2e66-5624eaf0b3b8}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Intersections", "Intersections.csproj", "{22B95BE8-B186-1785-0480-7C7117403D5F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileBrowser", "FileBrowser.csproj", "{ee244c23-861a-a61b-a99e-5237e7fc05bf}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileBrowser", "FileBrowser.csproj", "{12D5CFF0-A35E-FC72-45DD-790B2FEF2759}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Input", "Input.csproj", "{a7178795-02e4-f135-a039-a2f45fb223ce}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Input", "Input.csproj", "{F3B3F168-7D8D-E935-2413-3D3856079542}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Assembly-CSharp-Editor", "Assembly-CSharp-Editor.csproj", "{378e6a87-2aaa-7eb7-5f5c-a5091d2c7c51}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Assembly-CSharp-Editor", "Assembly-CSharp-Editor.csproj", "{4E73B77A-A174-FF88-766D-591F9626EBE8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestsEditMode", "TestsEditMode.csproj", "{102f0850-72d9-ea83-f592-cf9bfe5227fc}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestsEditMode", "TestsEditMode.csproj", "{6452B08F-79DB-1391-9520-B3A17C089382}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {858c4f7a-1565-f78e-dcd9-8afd7f774a8d}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {858c4f7a-1565-f78e-dcd9-8afd7f774a8d}.Debug|Any CPU.Build.0 = Debug|Any CPU - {70dbcc3d-468a-7b53-95c3-f388f6d81597}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {70dbcc3d-468a-7b53-95c3-f388f6d81597}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2bbaf7f3-7fb3-9dad-56ed-d77c857e16e7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2bbaf7f3-7fb3-9dad-56ed-d77c857e16e7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5a93d2e8-5187-efa6-e448-6343b5c9687f}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5a93d2e8-5187-efa6-e448-6343b5c9687f}.Debug|Any CPU.Build.0 = Debug|Any CPU - {e4748aaa-cc8b-9e27-641e-886d217d97e6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {e4748aaa-cc8b-9e27-641e-886d217d97e6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {c68e6dcf-0176-53b3-2e66-5624eaf0b3b8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {c68e6dcf-0176-53b3-2e66-5624eaf0b3b8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {ee244c23-861a-a61b-a99e-5237e7fc05bf}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {ee244c23-861a-a61b-a99e-5237e7fc05bf}.Debug|Any CPU.Build.0 = Debug|Any CPU - {a7178795-02e4-f135-a039-a2f45fb223ce}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {a7178795-02e4-f135-a039-a2f45fb223ce}.Debug|Any CPU.Build.0 = Debug|Any CPU - {378e6a87-2aaa-7eb7-5f5c-a5091d2c7c51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {378e6a87-2aaa-7eb7-5f5c-a5091d2c7c51}.Debug|Any CPU.Build.0 = Debug|Any CPU - {102f0850-72d9-ea83-f592-cf9bfe5227fc}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {102f0850-72d9-ea83-f592-cf9bfe5227fc}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5F38D385-41EB-CDED-AD43-EA25F3170559}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5F38D385-41EB-CDED-AD43-EA25F3170559}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5F38D385-41EB-CDED-AD43-EA25F3170559}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5F38D385-41EB-CDED-AD43-EA25F3170559}.Release|Any CPU.Build.0 = Release|Any CPU + {7E33E53E-21E1-2E91-7399-70C9C99EAD23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7E33E53E-21E1-2E91-7399-70C9C99EAD23}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7E33E53E-21E1-2E91-7399-70C9C99EAD23}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7E33E53E-21E1-2E91-7399-70C9C99EAD23}.Release|Any CPU.Build.0 = Release|Any CPU + {A5B1949A-27E4-B8CA-6F2F-D17BCE52BE27}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A5B1949A-27E4-B8CA-6F2F-D17BCE52BE27}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A5B1949A-27E4-B8CA-6F2F-D17BCE52BE27}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A5B1949A-27E4-B8CA-6F2F-D17BCE52BE27}.Release|Any CPU.Build.0 = Release|Any CPU + {BA95DD72-D2E3-6610-8917-028D9A433839}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BA95DD72-D2E3-6610-8917-028D9A433839}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BA95DD72-D2E3-6610-8917-028D9A433839}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BA95DD72-D2E3-6610-8917-028D9A433839}.Release|Any CPU.Build.0 = Release|Any CPU + {8C18E31F-03EC-D379-2CE1-3042B474FA5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8C18E31F-03EC-D379-2CE1-3042B474FA5A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8C18E31F-03EC-D379-2CE1-3042B474FA5A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8C18E31F-03EC-D379-2CE1-3042B474FA5A}.Release|Any CPU.Build.0 = Release|Any CPU + {22B95BE8-B186-1785-0480-7C7117403D5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {22B95BE8-B186-1785-0480-7C7117403D5F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {22B95BE8-B186-1785-0480-7C7117403D5F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {22B95BE8-B186-1785-0480-7C7117403D5F}.Release|Any CPU.Build.0 = Release|Any CPU + {12D5CFF0-A35E-FC72-45DD-790B2FEF2759}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {12D5CFF0-A35E-FC72-45DD-790B2FEF2759}.Debug|Any CPU.Build.0 = Debug|Any CPU + {12D5CFF0-A35E-FC72-45DD-790B2FEF2759}.Release|Any CPU.ActiveCfg = Release|Any CPU + {12D5CFF0-A35E-FC72-45DD-790B2FEF2759}.Release|Any CPU.Build.0 = Release|Any CPU + {F3B3F168-7D8D-E935-2413-3D3856079542}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F3B3F168-7D8D-E935-2413-3D3856079542}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F3B3F168-7D8D-E935-2413-3D3856079542}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F3B3F168-7D8D-E935-2413-3D3856079542}.Release|Any CPU.Build.0 = Release|Any CPU + {4E73B77A-A174-FF88-766D-591F9626EBE8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4E73B77A-A174-FF88-766D-591F9626EBE8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4E73B77A-A174-FF88-766D-591F9626EBE8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4E73B77A-A174-FF88-766D-591F9626EBE8}.Release|Any CPU.Build.0 = Release|Any CPU + {6452B08F-79DB-1391-9520-B3A17C089382}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6452B08F-79DB-1391-9520-B3A17C089382}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6452B08F-79DB-1391-9520-B3A17C089382}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6452B08F-79DB-1391-9520-B3A17C089382}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE