Decompiled source of PataponThemeSelectionMenu v0.4.6

BepInEx/plugins/NAudio.Core.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using NAudio.Dmo;
using NAudio.Dsp;
using NAudio.FileFormats.Wav;
using NAudio.Utils;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Mark Heath")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Mark Heath 2023")]
[assembly: AssemblyFileVersion("2.2.1.0")]
[assembly: AssemblyInformationalVersion("2.2.1")]
[assembly: AssemblyProduct("NAudio.Core")]
[assembly: AssemblyTitle("NAudio.Core")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.2.1.0")]
[module: UnverifiableCode]
namespace NAudio
{
	public enum Manufacturers
	{
		Microsoft = 1,
		Creative = 2,
		Mediavision = 3,
		Fujitsu = 4,
		Artisoft = 20,
		TurtleBeach = 21,
		Ibm = 22,
		Vocaltec = 23,
		Roland = 24,
		DspSolutions = 25,
		Nec = 26,
		Ati = 27,
		Wanglabs = 28,
		Tandy = 29,
		Voyetra = 30,
		Antex = 31,
		IclPS = 32,
		Intel = 33,
		Gravis = 34,
		Val = 35,
		Interactive = 36,
		Yamaha = 37,
		Everex = 38,
		Echo = 39,
		Sierra = 40,
		Cat = 41,
		Apps = 42,
		DspGroup = 43,
		Melabs = 44,
		ComputerFriends = 45,
		Ess = 46,
		Audiofile = 47,
		Motorola = 48,
		Canopus = 49,
		Epson = 50,
		Truevision = 51,
		Aztech = 52,
		Videologic = 53,
		Scalacs = 54,
		Korg = 55,
		Apt = 56,
		Ics = 57,
		Iteratedsys = 58,
		Metheus = 59,
		Logitech = 60,
		Winnov = 61,
		Ncr = 62,
		Exan = 63,
		Ast = 64,
		Willowpond = 65,
		Sonicfoundry = 66,
		Vitec = 67,
		Moscom = 68,
		Siliconsoft = 69,
		Supermac = 73,
		Audiopt = 74,
		Speechcomp = 76,
		Ahead = 77,
		Dolby = 78,
		Oki = 79,
		Auravision = 80,
		Olivetti = 81,
		Iomagic = 82,
		Matsushita = 83,
		Controlres = 84,
		Xebec = 85,
		Newmedia = 86,
		Nms = 87,
		Lyrrus = 88,
		Compusic = 89,
		Opti = 90,
		Adlacc = 91,
		Compaq = 92,
		Dialogic = 93,
		Insoft = 94,
		Mptus = 95,
		Weitek = 96,
		LernoutAndHauspie = 97,
		Qciar = 98,
		Apple = 99,
		Digital = 100,
		Motu = 101,
		Workbit = 102,
		Ositech = 103,
		Miro = 104,
		Cirruslogic = 105,
		Isolution = 106,
		Horizons = 107,
		Concepts = 108,
		Vtg = 109,
		Radius = 110,
		Rockwell = 111,
		Xyz = 112,
		Opcode = 113,
		Voxware = 114,
		NorthernTelecom = 115,
		Apicom = 116,
		Grande = 117,
		Addx = 118,
		Wildcat = 119,
		Rhetorex = 120,
		Brooktree = 121,
		Ensoniq = 125,
		Fast = 126,
		Nvidia = 127,
		Oksori = 128,
		Diacoustics = 129,
		Gulbransen = 130,
		KayElemetrics = 131,
		Crystal = 132,
		SplashStudios = 133,
		Quarterdeck = 134,
		Tdk = 135,
		DigitalAudioLabs = 136,
		Seersys = 137,
		Picturetel = 138,
		AttMicroelectronics = 139,
		Osprey = 140,
		Mediatrix = 141,
		Soundesigns = 142,
		Aldigital = 143,
		SpectrumSignalProcessing = 144,
		Ecs = 145,
		Amd = 146,
		Coredynamics = 147,
		Canam = 148,
		Softsound = 149,
		Norris = 150,
		Ddd = 151,
		Euphonics = 152,
		Precept = 153,
		CrystalNet = 154,
		Chromatic = 155,
		Voiceinfo = 156,
		Viennasys = 157,
		Connectix = 158,
		Gadgetlabs = 159,
		Frontier = 160,
		Viona = 161,
		Casio = 162,
		Diamondmm = 163,
		S3 = 164,
		FraunhoferIis = 172
	}
	public class MmException : Exception
	{
		public MmResult Result { get; }

		public string Function { get; }

		public MmException(MmResult result, string function)
			: base(ErrorMessage(result, function))
		{
			Result = result;
			Function = function;
		}

		private static string ErrorMessage(MmResult result, string function)
		{
			return $"{result} calling {function}";
		}

		public static void Try(MmResult result, string function)
		{
			if (result != 0)
			{
				throw new MmException(result, function);
			}
		}
	}
	public enum MmResult
	{
		NoError = 0,
		UnspecifiedError = 1,
		BadDeviceId = 2,
		NotEnabled = 3,
		AlreadyAllocated = 4,
		InvalidHandle = 5,
		NoDriver = 6,
		MemoryAllocationError = 7,
		NotSupported = 8,
		BadErrorNumber = 9,
		InvalidFlag = 10,
		InvalidParameter = 11,
		HandleBusy = 12,
		InvalidAlias = 13,
		BadRegistryDatabase = 14,
		RegistryKeyNotFound = 15,
		RegistryReadError = 16,
		RegistryWriteError = 17,
		RegistryDeleteError = 18,
		RegistryValueNotFound = 19,
		NoDriverCallback = 20,
		MoreData = 21,
		WaveBadFormat = 32,
		WaveStillPlaying = 33,
		WaveHeaderUnprepared = 34,
		WaveSync = 35,
		AcmNotPossible = 512,
		AcmBusy = 513,
		AcmHeaderUnprepared = 514,
		AcmCancelled = 515,
		MixerInvalidLine = 1024,
		MixerInvalidControl = 1025,
		MixerInvalidValue = 1026
	}
}
namespace NAudio.CoreAudioApi
{
	public enum CaptureState
	{
		Stopped,
		Starting,
		Capturing,
		Stopping
	}
}
namespace NAudio.Dmo
{
	public class AudioMediaSubtypes
	{
		public static readonly Guid MEDIASUBTYPE_PCM = new Guid("00000001-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_PCMAudioObsolete = new Guid("e436eb8a-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_MPEG1Packet = new Guid("e436eb80-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_MPEG1Payload = new Guid("e436eb81-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_MPEG2_AUDIO = new Guid("e06d802b-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid MEDIASUBTYPE_DVD_LPCM_AUDIO = new Guid("e06d8032-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid MEDIASUBTYPE_DRM_Audio = new Guid("00000009-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_IEEE_FLOAT = new Guid("00000003-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_DOLBY_AC3 = new Guid("e06d802c-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid MEDIASUBTYPE_DOLBY_AC3_SPDIF = new Guid("00000092-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_RAW_SPORT = new Guid("00000240-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_SPDIF_TAG_241h = new Guid("00000241-0000-0010-8000-00aa00389b71");

		public static readonly Guid MEDIASUBTYPE_I420 = new Guid("30323449-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_IYUV = new Guid("56555949-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_RGB1 = new Guid("e436eb78-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB24 = new Guid("e436eb7d-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB32 = new Guid("e436eb7e-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB4 = new Guid("e436eb79-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB555 = new Guid("e436eb7c-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB565 = new Guid("e436eb7b-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_RGB8 = new Guid("e436eb7a-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_UYVY = new Guid("59565955-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_VIDEOIMAGE = new Guid("1d4a45f2-e5f6-4b44-8388-f0ae5c0e0c37");

		public static readonly Guid MEDIASUBTYPE_YUY2 = new Guid("32595559-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_YV12 = new Guid("31313259-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_YVU9 = new Guid("39555659-0000-0010-8000-00AA00389B71");

		public static readonly Guid MEDIASUBTYPE_YVYU = new Guid("55595659-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMFORMAT_MPEG2Video = new Guid("e06d80e3-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid WMFORMAT_Script = new Guid("5C8510F2-DEBE-4ca7-BBA5-F07A104F8DFF");

		public static readonly Guid WMFORMAT_VideoInfo = new Guid("05589f80-c356-11ce-bf01-00aa0055595a");

		public static readonly Guid WMFORMAT_WaveFormatEx = new Guid("05589f81-c356-11ce-bf01-00aa0055595a");

		public static readonly Guid WMFORMAT_WebStream = new Guid("da1e6b13-8359-4050-b398-388e965bf00c");

		public static readonly Guid WMMEDIASUBTYPE_ACELPnet = new Guid("00000130-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_Base = new Guid("00000000-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_DRM = new Guid("00000009-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MP3 = new Guid("00000055-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MP43 = new Guid("3334504D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MP4S = new Guid("5334504D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_M4S2 = new Guid("3253344D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_P422 = new Guid("32323450-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MPEG2_VIDEO = new Guid("e06d8026-db46-11cf-b4d1-00805f6cbbea");

		public static readonly Guid WMMEDIASUBTYPE_MSS1 = new Guid("3153534D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_MSS2 = new Guid("3253534D-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_PCM = new Guid("00000001-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WebStream = new Guid("776257d4-c627-41cb-8f81-7ac7ff1c40cc");

		public static readonly Guid WMMEDIASUBTYPE_WMAudio_Lossless = new Guid("00000163-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMAudioV2 = new Guid("00000161-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMAudioV7 = new Guid("00000161-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMAudioV8 = new Guid("00000161-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMAudioV9 = new Guid("00000162-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMSP1 = new Guid("0000000A-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMV1 = new Guid("31564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMV2 = new Guid("32564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMV3 = new Guid("33564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMVA = new Guid("41564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WMVP = new Guid("50564D57-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIASUBTYPE_WVP2 = new Guid("32505657-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIATYPE_Audio = new Guid("73647561-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIATYPE_FileTransfer = new Guid("D9E47579-930E-4427-ADFC-AD80F290E470");

		public static readonly Guid WMMEDIATYPE_Image = new Guid("34A50FD8-8AA5-4386-81FE-A0EFE0488E31");

		public static readonly Guid WMMEDIATYPE_Script = new Guid("73636d64-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMMEDIATYPE_Text = new Guid("9BBA1EA7-5AB2-4829-BA57-0940209BCF3E");

		public static readonly Guid WMMEDIATYPE_Video = new Guid("73646976-0000-0010-8000-00AA00389B71");

		public static readonly Guid WMSCRIPTTYPE_TwoStrings = new Guid("82f38a70-c29f-11d1-97ad-00a0c95ea850");

		public static readonly Guid MEDIASUBTYPE_WAVE = new Guid("e436eb8b-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_AU = new Guid("e436eb8c-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid MEDIASUBTYPE_AIFF = new Guid("e436eb8d-524f-11ce-9f53-0020af0ba770");

		public static readonly Guid[] AudioSubTypes = new Guid[13]
		{
			MEDIASUBTYPE_PCM, MEDIASUBTYPE_PCMAudioObsolete, MEDIASUBTYPE_MPEG1Packet, MEDIASUBTYPE_MPEG1Payload, MEDIASUBTYPE_MPEG2_AUDIO, MEDIASUBTYPE_DVD_LPCM_AUDIO, MEDIASUBTYPE_DRM_Audio, MEDIASUBTYPE_IEEE_FLOAT, MEDIASUBTYPE_DOLBY_AC3, MEDIASUBTYPE_DOLBY_AC3_SPDIF,
			MEDIASUBTYPE_RAW_SPORT, MEDIASUBTYPE_SPDIF_TAG_241h, WMMEDIASUBTYPE_MP3
		};

		public static readonly string[] AudioSubTypeNames = new string[13]
		{
			"PCM", "PCM Obsolete", "MPEG1Packet", "MPEG1Payload", "MPEG2_AUDIO", "DVD_LPCM_AUDIO", "DRM_Audio", "IEEE_FLOAT", "DOLBY_AC3", "DOLBY_AC3_SPDIF",
			"RAW_SPORT", "SPDIF_TAG_241h", "MP3"
		};

		public static string GetAudioSubtypeName(Guid subType)
		{
			for (int i = 0; i < AudioSubTypes.Length; i++)
			{
				if (subType == AudioSubTypes[i])
				{
					return AudioSubTypeNames[i];
				}
			}
			return subType.ToString();
		}
	}
}
namespace NAudio.Utils
{
	public static class BufferHelpers
	{
		public static byte[] Ensure(byte[] buffer, int bytesRequired)
		{
			if (buffer == null || buffer.Length < bytesRequired)
			{
				buffer = new byte[bytesRequired];
			}
			return buffer;
		}

		public static float[] Ensure(float[] buffer, int samplesRequired)
		{
			if (buffer == null || buffer.Length < samplesRequired)
			{
				buffer = new float[samplesRequired];
			}
			return buffer;
		}
	}
	public static class ByteArrayExtensions
	{
		public static bool IsEntirelyNull(byte[] buffer)
		{
			for (int i = 0; i < buffer.Length; i++)
			{
				if (buffer[i] != 0)
				{
					return false;
				}
			}
			return true;
		}

		public static string DescribeAsHex(byte[] buffer, string separator, int bytesPerLine)
		{
			StringBuilder stringBuilder = new StringBuilder();
			int num = 0;
			foreach (byte b in buffer)
			{
				stringBuilder.AppendFormat("{0:X2}{1}", b, separator);
				if (++num % bytesPerLine == 0)
				{
					stringBuilder.Append("\r\n");
				}
			}
			stringBuilder.Append("\r\n");
			return stringBuilder.ToString();
		}

		public static string DecodeAsString(byte[] buffer, int offset, int length, Encoding encoding)
		{
			for (int i = 0; i < length; i++)
			{
				if (buffer[offset + i] == 0)
				{
					length = i;
				}
			}
			return encoding.GetString(buffer, offset, length);
		}

		public static byte[] Concat(params byte[][] byteArrays)
		{
			int num = 0;
			byte[][] array = byteArrays;
			foreach (byte[] array2 in array)
			{
				num += array2.Length;
			}
			if (num <= 0)
			{
				return new byte[0];
			}
			byte[] array3 = new byte[num];
			int num2 = 0;
			array = byteArrays;
			foreach (byte[] array4 in array)
			{
				Array.Copy(array4, 0, array3, num2, array4.Length);
				num2 += array4.Length;
			}
			return array3;
		}
	}
	public class ByteEncoding : Encoding
	{
		public static readonly ByteEncoding Instance = new ByteEncoding();

		private ByteEncoding()
		{
		}

		public override int GetByteCount(char[] chars, int index, int count)
		{
			return count;
		}

		public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
		{
			for (int i = 0; i < charCount; i++)
			{
				bytes[byteIndex + i] = (byte)chars[charIndex + i];
			}
			return charCount;
		}

		public override int GetCharCount(byte[] bytes, int index, int count)
		{
			for (int i = 0; i < count; i++)
			{
				if (bytes[index + i] == 0)
				{
					return i;
				}
			}
			return count;
		}

		public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
		{
			for (int i = 0; i < byteCount; i++)
			{
				byte b = bytes[byteIndex + i];
				if (b == 0)
				{
					return i;
				}
				chars[charIndex + i] = (char)b;
			}
			return byteCount;
		}

		public override int GetMaxCharCount(int byteCount)
		{
			return byteCount;
		}

		public override int GetMaxByteCount(int charCount)
		{
			return charCount;
		}
	}
	public class ChunkIdentifier
	{
		public static int ChunkIdentifierToInt32(string s)
		{
			if (s.Length != 4)
			{
				throw new ArgumentException("Must be a four character string");
			}
			byte[] bytes = Encoding.UTF8.GetBytes(s);
			if (bytes.Length != 4)
			{
				throw new ArgumentException("Must encode to exactly four bytes");
			}
			return BitConverter.ToInt32(bytes, 0);
		}
	}
	public class CircularBuffer
	{
		private readonly byte[] buffer;

		private readonly object lockObject;

		private int writePosition;

		private int readPosition;

		private int byteCount;

		public int MaxLength => buffer.Length;

		public int Count
		{
			get
			{
				lock (lockObject)
				{
					return byteCount;
				}
			}
		}

		public CircularBuffer(int size)
		{
			buffer = new byte[size];
			lockObject = new object();
		}

		public int Write(byte[] data, int offset, int count)
		{
			lock (lockObject)
			{
				int num = 0;
				if (count > buffer.Length - byteCount)
				{
					count = buffer.Length - byteCount;
				}
				int num2 = Math.Min(buffer.Length - writePosition, count);
				Array.Copy(data, offset, buffer, writePosition, num2);
				writePosition += num2;
				writePosition %= buffer.Length;
				num += num2;
				if (num < count)
				{
					Array.Copy(data, offset + num, buffer, writePosition, count - num);
					writePosition += count - num;
					num = count;
				}
				byteCount += num;
				return num;
			}
		}

		public int Read(byte[] data, int offset, int count)
		{
			lock (lockObject)
			{
				if (count > byteCount)
				{
					count = byteCount;
				}
				int num = 0;
				int num2 = Math.Min(buffer.Length - readPosition, count);
				Array.Copy(buffer, readPosition, data, offset, num2);
				num += num2;
				readPosition += num2;
				readPosition %= buffer.Length;
				if (num < count)
				{
					Array.Copy(buffer, readPosition, data, offset + num, count - num);
					readPosition += count - num;
					num = count;
				}
				byteCount -= num;
				return num;
			}
		}

		public void Reset()
		{
			lock (lockObject)
			{
				ResetInner();
			}
		}

		private void ResetInner()
		{
			byteCount = 0;
			readPosition = 0;
			writePosition = 0;
		}

		public void Advance(int count)
		{
			lock (lockObject)
			{
				if (count >= byteCount)
				{
					ResetInner();
					return;
				}
				byteCount -= count;
				readPosition += count;
				readPosition %= MaxLength;
			}
		}
	}
	public class Decibels
	{
		private const double LOG_2_DB = 8.685889638065037;

		private const double DB_2_LOG = 0.11512925464970228;

		public static double LinearToDecibels(double lin)
		{
			return Math.Log(lin) * 8.685889638065037;
		}

		public static double DecibelsToLinear(double dB)
		{
			return Math.Exp(dB * 0.11512925464970228);
		}
	}
	[AttributeUsage(AttributeTargets.Field)]
	public class FieldDescriptionAttribute : Attribute
	{
		public string Description { get; }

		public FieldDescriptionAttribute(string description)
		{
			Description = description;
		}

		public override string ToString()
		{
			return Description;
		}
	}
	public static class FieldDescriptionHelper
	{
		public static string Describe(Type t, Guid guid)
		{
			FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);
			foreach (FieldInfo fieldInfo in fields)
			{
				if (!fieldInfo.IsPublic || !fieldInfo.IsStatic || !(fieldInfo.FieldType == typeof(Guid)) || !((Guid)fieldInfo.GetValue(null) == guid))
				{
					continue;
				}
				object[] customAttributes = fieldInfo.GetCustomAttributes(inherit: false);
				for (int j = 0; j < customAttributes.Length; j++)
				{
					if (customAttributes[j] is FieldDescriptionAttribute fieldDescriptionAttribute)
					{
						return fieldDescriptionAttribute.Description;
					}
				}
				return fieldInfo.Name;
			}
			return guid.ToString();
		}
	}
	public static class HResult
	{
		public const int S_OK = 0;

		public const int S_FALSE = 1;

		public const int E_INVALIDARG = -2147483645;

		private const int FACILITY_AAF = 18;

		private const int FACILITY_ACS = 20;

		private const int FACILITY_BACKGROUNDCOPY = 32;

		private const int FACILITY_CERT = 11;

		private const int FACILITY_COMPLUS = 17;

		private const int FACILITY_CONFIGURATION = 33;

		private const int FACILITY_CONTROL = 10;

		private const int FACILITY_DISPATCH = 2;

		private const int FACILITY_DPLAY = 21;

		private const int FACILITY_HTTP = 25;

		private const int FACILITY_INTERNET = 12;

		private const int FACILITY_ITF = 4;

		private const int FACILITY_MEDIASERVER = 13;

		private const int FACILITY_MSMQ = 14;

		private const int FACILITY_NULL = 0;

		private const int FACILITY_RPC = 1;

		private const int FACILITY_SCARD = 16;

		private const int FACILITY_SECURITY = 9;

		private const int FACILITY_SETUPAPI = 15;

		private const int FACILITY_SSPI = 9;

		private const int FACILITY_STORAGE = 3;

		private const int FACILITY_SXS = 23;

		private const int FACILITY_UMI = 22;

		private const int FACILITY_URT = 19;

		private const int FACILITY_WIN32 = 7;

		private const int FACILITY_WINDOWS = 8;

		private const int FACILITY_WINDOWS_CE = 24;

		public static int MAKE_HRESULT(int sev, int fac, int code)
		{
			return (sev << 31) | (fac << 16) | code;
		}

		public static int GetHResult(this COMException exception)
		{
			return exception.ErrorCode;
		}
	}
	public static class IEEE
	{
		private static double UnsignedToFloat(ulong u)
		{
			return (double)(long)(u - int.MaxValue - 1) + 2147483648.0;
		}

		private static double ldexp(double x, int exp)
		{
			return x * Math.Pow(2.0, exp);
		}

		private static double frexp(double x, out int exp)
		{
			exp = (int)Math.Floor(Math.Log(x) / Math.Log(2.0)) + 1;
			return 1.0 - (Math.Pow(2.0, exp) - x) / Math.Pow(2.0, exp);
		}

		private static ulong FloatToUnsigned(double f)
		{
			return (ulong)((long)(f - 2147483648.0) + int.MaxValue + 1);
		}

		public static byte[] ConvertToIeeeExtended(double num)
		{
			int num2;
			if (num < 0.0)
			{
				num2 = 32768;
				num *= -1.0;
			}
			else
			{
				num2 = 0;
			}
			ulong num4;
			ulong num5;
			int num3;
			if (num == 0.0)
			{
				num3 = 0;
				num4 = 0uL;
				num5 = 0uL;
			}
			else
			{
				double num6 = frexp(num, out num3);
				if (num3 > 16384 || !(num6 < 1.0))
				{
					num3 = num2 | 0x7FFF;
					num4 = 0uL;
					num5 = 0uL;
				}
				else
				{
					num3 += 16382;
					if (num3 < 0)
					{
						num6 = ldexp(num6, num3);
						num3 = 0;
					}
					num3 |= num2;
					num6 = ldexp(num6, 32);
					double num7 = Math.Floor(num6);
					num4 = FloatToUnsigned(num7);
					num6 = ldexp(num6 - num7, 32);
					num7 = Math.Floor(num6);
					num5 = FloatToUnsigned(num7);
				}
			}
			return new byte[10]
			{
				(byte)(num3 >> 8),
				(byte)num3,
				(byte)(num4 >> 24),
				(byte)(num4 >> 16),
				(byte)(num4 >> 8),
				(byte)num4,
				(byte)(num5 >> 24),
				(byte)(num5 >> 16),
				(byte)(num5 >> 8),
				(byte)num5
			};
		}

		public static double ConvertFromIeeeExtended(byte[] bytes)
		{
			if (bytes.Length != 10)
			{
				throw new Exception("Incorrect length for IEEE extended.");
			}
			int num = ((bytes[0] & 0x7F) << 8) | bytes[1];
			uint num2 = (uint)((bytes[2] << 24) | (bytes[3] << 16) | (bytes[4] << 8) | bytes[5]);
			uint num3 = (uint)((bytes[6] << 24) | (bytes[7] << 16) | (bytes[8] << 8) | bytes[9]);
			double num4;
			if (num == 0 && num2 == 0 && num3 == 0)
			{
				num4 = 0.0;
			}
			else if (num == 32767)
			{
				num4 = double.NaN;
			}
			else
			{
				num -= 16383;
				num4 = ldexp(UnsignedToFloat(num2), num -= 31);
				num4 += ldexp(UnsignedToFloat(num3), num -= 32);
			}
			if ((bytes[0] & 0x80) == 128)
			{
				return 0.0 - num4;
			}
			return num4;
		}
	}
	public class IgnoreDisposeStream : Stream
	{
		public Stream SourceStream { get; private set; }

		public bool IgnoreDispose { get; set; }

		public override bool CanRead => SourceStream.CanRead;

		public override bool CanSeek => SourceStream.CanSeek;

		public override bool CanWrite => SourceStream.CanWrite;

		public override long Length => SourceStream.Length;

		public override long Position
		{
			get
			{
				return SourceStream.Position;
			}
			set
			{
				SourceStream.Position = value;
			}
		}

		public IgnoreDisposeStream(Stream sourceStream)
		{
			SourceStream = sourceStream;
			IgnoreDispose = true;
		}

		public override void Flush()
		{
			SourceStream.Flush();
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			return SourceStream.Read(buffer, offset, count);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			return SourceStream.Seek(offset, origin);
		}

		public override void SetLength(long value)
		{
			SourceStream.SetLength(value);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			SourceStream.Write(buffer, offset, count);
		}

		protected override void Dispose(bool disposing)
		{
			if (!IgnoreDispose)
			{
				SourceStream.Dispose();
				SourceStream = null;
			}
		}
	}
	public static class NativeMethods
	{
		[DllImport("kernel32.dll")]
		public static extern IntPtr LoadLibrary(string dllToLoad);

		[DllImport("kernel32.dll")]
		public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

		[DllImport("kernel32.dll")]
		public static extern bool FreeLibrary(IntPtr hModule);
	}
	public static class WavePositionExtensions
	{
		public static TimeSpan GetPositionTimeSpan(this IWavePosition @this)
		{
			return TimeSpan.FromMilliseconds((double)(@this.GetPosition() / (@this.OutputWaveFormat.Channels * @this.OutputWaveFormat.BitsPerSample / 8)) * 1000.0 / (double)@this.OutputWaveFormat.SampleRate);
		}
	}
}
namespace NAudio.FileFormats.Wav
{
	public class WaveFileChunkReader
	{
		private WaveFormat waveFormat;

		private long dataChunkPosition;

		private long dataChunkLength;

		private List<RiffChunk> riffChunks;

		private readonly bool strictMode;

		private bool isRf64;

		private readonly bool storeAllChunks;

		private long riffSize;

		public WaveFormat WaveFormat => waveFormat;

		public long DataChunkPosition => dataChunkPosition;

		public long DataChunkLength => dataChunkLength;

		public List<RiffChunk> RiffChunks => riffChunks;

		public WaveFileChunkReader()
		{
			storeAllChunks = true;
			strictMode = false;
		}

		public void ReadWaveHeader(Stream stream)
		{
			dataChunkPosition = -1L;
			waveFormat = null;
			riffChunks = new List<RiffChunk>();
			dataChunkLength = 0L;
			BinaryReader binaryReader = new BinaryReader(stream);
			ReadRiffHeader(binaryReader);
			riffSize = binaryReader.ReadUInt32();
			if (binaryReader.ReadInt32() != ChunkIdentifier.ChunkIdentifierToInt32("WAVE"))
			{
				throw new FormatException("Not a WAVE file - no WAVE header");
			}
			if (isRf64)
			{
				ReadDs64Chunk(binaryReader);
			}
			int num = ChunkIdentifier.ChunkIdentifierToInt32("data");
			int num2 = ChunkIdentifier.ChunkIdentifierToInt32("fmt ");
			long num3 = Math.Min(riffSize + 8, stream.Length);
			while (stream.Position <= num3 - 8)
			{
				int num4 = binaryReader.ReadInt32();
				uint num5 = binaryReader.ReadUInt32();
				if (num4 == num)
				{
					dataChunkPosition = stream.Position;
					if (!isRf64)
					{
						dataChunkLength = num5;
					}
					stream.Position += num5;
				}
				else if (num4 == num2)
				{
					if (num5 > int.MaxValue)
					{
						throw new InvalidDataException($"Format chunk length must be between 0 and {int.MaxValue}.");
					}
					waveFormat = WaveFormat.FromFormatChunk(binaryReader, (int)num5);
				}
				else
				{
					if (num5 > stream.Length - stream.Position)
					{
						if (!strictMode)
						{
						}
						break;
					}
					if (storeAllChunks)
					{
						if (num5 > int.MaxValue)
						{
							throw new InvalidDataException($"RiffChunk chunk length must be between 0 and {int.MaxValue}.");
						}
						riffChunks.Add(GetRiffChunk(stream, num4, (int)num5));
					}
					stream.Position += num5;
				}
				if (num5 % 2 != 0 && binaryReader.PeekChar() == 0)
				{
					stream.Position++;
				}
			}
			if (waveFormat == null)
			{
				throw new FormatException("Invalid WAV file - No fmt chunk found");
			}
			if (dataChunkPosition == -1)
			{
				throw new FormatException("Invalid WAV file - No data chunk found");
			}
		}

		private void ReadDs64Chunk(BinaryReader reader)
		{
			int num = ChunkIdentifier.ChunkIdentifierToInt32("ds64");
			if (reader.ReadInt32() != num)
			{
				throw new FormatException("Invalid RF64 WAV file - No ds64 chunk found");
			}
			int num2 = reader.ReadInt32();
			riffSize = reader.ReadInt64();
			dataChunkLength = reader.ReadInt64();
			reader.ReadInt64();
			reader.ReadBytes(num2 - 24);
		}

		private static RiffChunk GetRiffChunk(Stream stream, int chunkIdentifier, int chunkLength)
		{
			return new RiffChunk(chunkIdentifier, chunkLength, stream.Position);
		}

		private void ReadRiffHeader(BinaryReader br)
		{
			int num = br.ReadInt32();
			if (num == ChunkIdentifier.ChunkIdentifierToInt32("RF64"))
			{
				isRf64 = true;
			}
			else if (num != ChunkIdentifier.ChunkIdentifierToInt32("RIFF"))
			{
				throw new FormatException("Not a WAVE file - no RIFF header");
			}
		}
	}
}
namespace NAudio.SoundFont
{
	public class Generator
	{
		public GeneratorEnum GeneratorType { get; set; }

		public ushort UInt16Amount { get; set; }

		public short Int16Amount
		{
			get
			{
				return (short)UInt16Amount;
			}
			set
			{
				UInt16Amount = (ushort)value;
			}
		}

		public byte LowByteAmount
		{
			get
			{
				return (byte)(UInt16Amount & 0xFFu);
			}
			set
			{
				UInt16Amount &= 65280;
				UInt16Amount += value;
			}
		}

		public byte HighByteAmount
		{
			get
			{
				return (byte)((UInt16Amount & 0xFF00) >> 8);
			}
			set
			{
				UInt16Amount &= 255;
				UInt16Amount += (ushort)(value << 8);
			}
		}

		public Instrument Instrument { get; set; }

		public SampleHeader SampleHeader { get; set; }

		public override string ToString()
		{
			if (GeneratorType == GeneratorEnum.Instrument)
			{
				return "Generator Instrument " + Instrument.Name;
			}
			if (GeneratorType == GeneratorEnum.SampleID)
			{
				return $"Generator SampleID {SampleHeader}";
			}
			return $"Generator {GeneratorType} {UInt16Amount}";
		}
	}
	internal class GeneratorBuilder : StructureBuilder<Generator>
	{
		public override int Length => 4;

		public Generator[] Generators => data.ToArray();

		public override Generator Read(BinaryReader br)
		{
			Generator generator = new Generator();
			generator.GeneratorType = (GeneratorEnum)br.ReadUInt16();
			generator.UInt16Amount = br.ReadUInt16();
			data.Add(generator);
			return generator;
		}

		public override void Write(BinaryWriter bw, Generator o)
		{
		}

		public void Load(Instrument[] instruments)
		{
			Generator[] generators = Generators;
			foreach (Generator generator in generators)
			{
				if (generator.GeneratorType == GeneratorEnum.Instrument)
				{
					generator.Instrument = instruments[generator.UInt16Amount];
				}
			}
		}

		public void Load(SampleHeader[] sampleHeaders)
		{
			Generator[] generators = Generators;
			foreach (Generator generator in generators)
			{
				if (generator.GeneratorType == GeneratorEnum.SampleID)
				{
					generator.SampleHeader = sampleHeaders[generator.UInt16Amount];
				}
			}
		}
	}
	public enum GeneratorEnum
	{
		StartAddressOffset,
		EndAddressOffset,
		StartLoopAddressOffset,
		EndLoopAddressOffset,
		StartAddressCoarseOffset,
		ModulationLFOToPitch,
		VibratoLFOToPitch,
		ModulationEnvelopeToPitch,
		InitialFilterCutoffFrequency,
		InitialFilterQ,
		ModulationLFOToFilterCutoffFrequency,
		ModulationEnvelopeToFilterCutoffFrequency,
		EndAddressCoarseOffset,
		ModulationLFOToVolume,
		Unused1,
		ChorusEffectsSend,
		ReverbEffectsSend,
		Pan,
		Unused2,
		Unused3,
		Unused4,
		DelayModulationLFO,
		FrequencyModulationLFO,
		DelayVibratoLFO,
		FrequencyVibratoLFO,
		DelayModulationEnvelope,
		AttackModulationEnvelope,
		HoldModulationEnvelope,
		DecayModulationEnvelope,
		SustainModulationEnvelope,
		ReleaseModulationEnvelope,
		KeyNumberToModulationEnvelopeHold,
		KeyNumberToModulationEnvelopeDecay,
		DelayVolumeEnvelope,
		AttackVolumeEnvelope,
		HoldVolumeEnvelope,
		DecayVolumeEnvelope,
		SustainVolumeEnvelope,
		ReleaseVolumeEnvelope,
		KeyNumberToVolumeEnvelopeHold,
		KeyNumberToVolumeEnvelopeDecay,
		Instrument,
		Reserved1,
		KeyRange,
		VelocityRange,
		StartLoopAddressCoarseOffset,
		KeyNumber,
		Velocity,
		InitialAttenuation,
		Reserved2,
		EndLoopAddressCoarseOffset,
		CoarseTune,
		FineTune,
		SampleID,
		SampleModes,
		Reserved3,
		ScaleTuning,
		ExclusiveClass,
		OverridingRootKey,
		Unused5,
		UnusedEnd
	}
	public class InfoChunk
	{
		public SFVersion SoundFontVersion { get; }

		public string WaveTableSoundEngine { get; set; }

		public string BankName { get; set; }

		public string DataROM { get; set; }

		public string CreationDate { get; set; }

		public string Author { get; set; }

		public string TargetProduct { get; set; }

		public string Copyright { get; set; }

		public string Comments { get; set; }

		public string Tools { get; set; }

		public SFVersion ROMVersion { get; set; }

		internal InfoChunk(RiffChunk chunk)
		{
			bool flag = false;
			bool flag2 = false;
			if (chunk.ReadChunkID() != "INFO")
			{
				throw new InvalidDataException("Not an INFO chunk");
			}
			RiffChunk nextSubChunk;
			while ((nextSubChunk = chunk.GetNextSubChunk()) != null)
			{
				switch (nextSubChunk.ChunkID)
				{
				case "ifil":
					flag = true;
					SoundFontVersion = nextSubChunk.GetDataAsStructure(new SFVersionBuilder());
					break;
				case "isng":
					WaveTableSoundEngine = nextSubChunk.GetDataAsString();
					break;
				case "INAM":
					flag2 = true;
					BankName = nextSubChunk.GetDataAsString();
					break;
				case "irom":
					DataROM = nextSubChunk.GetDataAsString();
					break;
				case "iver":
					ROMVersion = nextSubChunk.GetDataAsStructure(new SFVersionBuilder());
					break;
				case "ICRD":
					CreationDate = nextSubChunk.GetDataAsString();
					break;
				case "IENG":
					Author = nextSubChunk.GetDataAsString();
					break;
				case "IPRD":
					TargetProduct = nextSubChunk.GetDataAsString();
					break;
				case "ICOP":
					Copyright = nextSubChunk.GetDataAsString();
					break;
				case "ICMT":
					Comments = nextSubChunk.GetDataAsString();
					break;
				case "ISFT":
					Tools = nextSubChunk.GetDataAsString();
					break;
				default:
					throw new InvalidDataException("Unknown chunk type " + nextSubChunk.ChunkID);
				}
			}
			if (!flag)
			{
				throw new InvalidDataException("Missing SoundFont version information");
			}
			if (!flag2)
			{
				throw new InvalidDataException("Missing SoundFont name information");
			}
		}

		public override string ToString()
		{
			return string.Format("Bank Name: {0}\r\nAuthor: {1}\r\nCopyright: {2}\r\nCreation Date: {3}\r\nTools: {4}\r\nComments: {5}\r\nSound Engine: {6}\r\nSoundFont Version: {7}\r\nTarget Product: {8}\r\nData ROM: {9}\r\nROM Version: {10}", BankName, Author, Copyright, CreationDate, Tools, "TODO-fix comments", WaveTableSoundEngine, SoundFontVersion, TargetProduct, DataROM, ROMVersion);
		}
	}
	public class Instrument
	{
		internal ushort startInstrumentZoneIndex;

		internal ushort endInstrumentZoneIndex;

		public string Name { get; set; }

		public Zone[] Zones { get; set; }

		public override string ToString()
		{
			return Name;
		}
	}
	internal class InstrumentBuilder : StructureBuilder<Instrument>
	{
		private Instrument lastInstrument;

		public override int Length => 22;

		public Instrument[] Instruments => data.ToArray();

		public override Instrument Read(BinaryReader br)
		{
			Instrument instrument = new Instrument();
			string text = Encoding.UTF8.GetString(br.ReadBytes(20), 0, 20);
			if (text.IndexOf('\0') >= 0)
			{
				text = text.Substring(0, text.IndexOf('\0'));
			}
			instrument.Name = text;
			instrument.startInstrumentZoneIndex = br.ReadUInt16();
			if (lastInstrument != null)
			{
				lastInstrument.endInstrumentZoneIndex = (ushort)(instrument.startInstrumentZoneIndex - 1);
			}
			data.Add(instrument);
			lastInstrument = instrument;
			return instrument;
		}

		public override void Write(BinaryWriter bw, Instrument instrument)
		{
		}

		public void LoadZones(Zone[] zones)
		{
			for (int i = 0; i < data.Count - 1; i++)
			{
				Instrument instrument = data[i];
				instrument.Zones = new Zone[instrument.endInstrumentZoneIndex - instrument.startInstrumentZoneIndex + 1];
				Array.Copy(zones, instrument.startInstrumentZoneIndex, instrument.Zones, 0, instrument.Zones.Length);
			}
			data.RemoveAt(data.Count - 1);
		}
	}
	public enum TransformEnum
	{
		Linear
	}
	public class Modulator
	{
		public ModulatorType SourceModulationData { get; set; }

		public GeneratorEnum DestinationGenerator { get; set; }

		public short Amount { get; set; }

		public ModulatorType SourceModulationAmount { get; set; }

		public TransformEnum SourceTransform { get; set; }

		public override string ToString()
		{
			return $"Modulator {SourceModulationData} {DestinationGenerator} {Amount} {SourceModulationAmount} {SourceTransform}";
		}
	}
	internal class ModulatorBuilder : StructureBuilder<Modulator>
	{
		public override int Length => 10;

		public Modulator[] Modulators => data.ToArray();

		public override Modulator Read(BinaryReader br)
		{
			Modulator modulator = new Modulator();
			modulator.SourceModulationData = new ModulatorType(br.ReadUInt16());
			modulator.DestinationGenerator = (GeneratorEnum)br.ReadUInt16();
			modulator.Amount = br.ReadInt16();
			modulator.SourceModulationAmount = new ModulatorType(br.ReadUInt16());
			modulator.SourceTransform = (TransformEnum)br.ReadUInt16();
			data.Add(modulator);
			return modulator;
		}

		public override void Write(BinaryWriter bw, Modulator o)
		{
		}
	}
	public enum ControllerSourceEnum
	{
		NoController = 0,
		NoteOnVelocity = 2,
		NoteOnKeyNumber = 3,
		PolyPressure = 10,
		ChannelPressure = 13,
		PitchWheel = 14,
		PitchWheelSensitivity = 16
	}
	public enum SourceTypeEnum
	{
		Linear,
		Concave,
		Convex,
		Switch
	}
	public class ModulatorType
	{
		private bool polarity;

		private bool direction;

		private bool midiContinuousController;

		private ControllerSourceEnum controllerSource;

		private SourceTypeEnum sourceType;

		private ushort midiContinuousControllerNumber;

		internal ModulatorType(ushort raw)
		{
			polarity = (raw & 0x200) == 512;
			direction = (raw & 0x100) == 256;
			midiContinuousController = (raw & 0x80) == 128;
			sourceType = (SourceTypeEnum)((raw & 0xFC00) >> 10);
			controllerSource = (ControllerSourceEnum)(raw & 0x7F);
			midiContinuousControllerNumber = (ushort)(raw & 0x7Fu);
		}

		public override string ToString()
		{
			if (midiContinuousController)
			{
				return $"{sourceType} CC{midiContinuousControllerNumber}";
			}
			return $"{sourceType} {controllerSource}";
		}
	}
	public class Preset
	{
		internal ushort startPresetZoneIndex;

		internal ushort endPresetZoneIndex;

		internal uint library;

		internal uint genre;

		internal uint morphology;

		public string Name { get; set; }

		public ushort PatchNumber { get; set; }

		public ushort Bank { get; set; }

		public Zone[] Zones { get; set; }

		public override string ToString()
		{
			return $"{Bank}-{PatchNumber} {Name}";
		}
	}
	internal class PresetBuilder : StructureBuilder<Preset>
	{
		private Preset lastPreset;

		public override int Length => 38;

		public Preset[] Presets => data.ToArray();

		public override Preset Read(BinaryReader br)
		{
			Preset preset = new Preset();
			string text = Encoding.UTF8.GetString(br.ReadBytes(20), 0, 20);
			if (text.IndexOf('\0') >= 0)
			{
				text = text.Substring(0, text.IndexOf('\0'));
			}
			preset.Name = text;
			preset.PatchNumber = br.ReadUInt16();
			preset.Bank = br.ReadUInt16();
			preset.startPresetZoneIndex = br.ReadUInt16();
			preset.library = br.ReadUInt32();
			preset.genre = br.ReadUInt32();
			preset.morphology = br.ReadUInt32();
			if (lastPreset != null)
			{
				lastPreset.endPresetZoneIndex = (ushort)(preset.startPresetZoneIndex - 1);
			}
			data.Add(preset);
			lastPreset = preset;
			return preset;
		}

		public override void Write(BinaryWriter bw, Preset preset)
		{
		}

		public void LoadZones(Zone[] presetZones)
		{
			for (int i = 0; i < data.Count - 1; i++)
			{
				Preset preset = data[i];
				preset.Zones = new Zone[preset.endPresetZoneIndex - preset.startPresetZoneIndex + 1];
				Array.Copy(presetZones, preset.startPresetZoneIndex, preset.Zones, 0, preset.Zones.Length);
			}
			data.RemoveAt(data.Count - 1);
		}
	}
	public class PresetsChunk
	{
		private PresetBuilder presetHeaders = new PresetBuilder();

		private ZoneBuilder presetZones = new ZoneBuilder();

		private ModulatorBuilder presetZoneModulators = new ModulatorBuilder();

		private GeneratorBuilder presetZoneGenerators = new GeneratorBuilder();

		private InstrumentBuilder instruments = new InstrumentBuilder();

		private ZoneBuilder instrumentZones = new ZoneBuilder();

		private ModulatorBuilder instrumentZoneModulators = new ModulatorBuilder();

		private GeneratorBuilder instrumentZoneGenerators = new GeneratorBuilder();

		private SampleHeaderBuilder sampleHeaders = new SampleHeaderBuilder();

		public Preset[] Presets => presetHeaders.Presets;

		public Instrument[] Instruments => instruments.Instruments;

		public SampleHeader[] SampleHeaders => sampleHeaders.SampleHeaders;

		internal PresetsChunk(RiffChunk chunk)
		{
			string text = chunk.ReadChunkID();
			if (text != "pdta")
			{
				throw new InvalidDataException($"Not a presets data chunk ({text})");
			}
			RiffChunk nextSubChunk;
			while ((nextSubChunk = chunk.GetNextSubChunk()) != null)
			{
				switch (nextSubChunk.ChunkID)
				{
				case "phdr":
				case "PHDR":
					nextSubChunk.GetDataAsStructureArray(presetHeaders);
					break;
				case "pbag":
				case "PBAG":
					nextSubChunk.GetDataAsStructureArray(presetZones);
					break;
				case "pmod":
				case "PMOD":
					nextSubChunk.GetDataAsStructureArray(presetZoneModulators);
					break;
				case "pgen":
				case "PGEN":
					nextSubChunk.GetDataAsStructureArray(presetZoneGenerators);
					break;
				case "inst":
				case "INST":
					nextSubChunk.GetDataAsStructureArray(instruments);
					break;
				case "ibag":
				case "IBAG":
					nextSubChunk.GetDataAsStructureArray(instrumentZones);
					break;
				case "imod":
				case "IMOD":
					nextSubChunk.GetDataAsStructureArray(instrumentZoneModulators);
					break;
				case "igen":
				case "IGEN":
					nextSubChunk.GetDataAsStructureArray(instrumentZoneGenerators);
					break;
				case "shdr":
				case "SHDR":
					nextSubChunk.GetDataAsStructureArray(sampleHeaders);
					break;
				default:
					throw new InvalidDataException($"Unknown chunk type {nextSubChunk.ChunkID}");
				}
			}
			instrumentZoneGenerators.Load(sampleHeaders.SampleHeaders);
			instrumentZones.Load(instrumentZoneModulators.Modulators, instrumentZoneGenerators.Generators);
			instruments.LoadZones(instrumentZones.Zones);
			presetZoneGenerators.Load(instruments.Instruments);
			presetZones.Load(presetZoneModulators.Modulators, presetZoneGenerators.Generators);
			presetHeaders.LoadZones(presetZones.Zones);
			sampleHeaders.RemoveEOS();
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("Preset Headers:\r\n");
			Preset[] presets = presetHeaders.Presets;
			foreach (Preset arg in presets)
			{
				stringBuilder.AppendFormat("{0}\r\n", arg);
			}
			stringBuilder.Append("Instruments:\r\n");
			Instrument[] array = instruments.Instruments;
			foreach (Instrument arg2 in array)
			{
				stringBuilder.AppendFormat("{0}\r\n", arg2);
			}
			return stringBuilder.ToString();
		}
	}
	internal class RiffChunk
	{
		private string chunkID;

		private BinaryReader riffFile;

		public string ChunkID
		{
			get
			{
				return chunkID;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("ChunkID may not be null");
				}
				if (value.Length != 4)
				{
					throw new ArgumentException("ChunkID must be four characters");
				}
				chunkID = value;
			}
		}

		public uint ChunkSize { get; private set; }

		public long DataOffset { get; private set; }

		public static RiffChunk GetTopLevelChunk(BinaryReader file)
		{
			RiffChunk riffChunk = new RiffChunk(file);
			riffChunk.ReadChunk();
			return riffChunk;
		}

		private RiffChunk(BinaryReader file)
		{
			riffFile = file;
			chunkID = "????";
			ChunkSize = 0u;
			DataOffset = 0L;
		}

		public string ReadChunkID()
		{
			byte[] array = riffFile.ReadBytes(4);
			if (array.Length != 4)
			{
				throw new InvalidDataException("Couldn't read Chunk ID");
			}
			return ByteEncoding.Instance.GetString(array, 0, array.Length);
		}

		private void ReadChunk()
		{
			chunkID = ReadChunkID();
			ChunkSize = riffFile.ReadUInt32();
			DataOffset = riffFile.BaseStream.Position;
		}

		public RiffChunk GetNextSubChunk()
		{
			if (riffFile.BaseStream.Position + 8 < DataOffset + ChunkSize)
			{
				RiffChunk riffChunk = new RiffChunk(riffFile);
				riffChunk.ReadChunk();
				return riffChunk;
			}
			return null;
		}

		public byte[] GetData()
		{
			riffFile.BaseStream.Position = DataOffset;
			byte[] array = riffFile.ReadBytes((int)ChunkSize);
			if (array.Length != ChunkSize)
			{
				throw new InvalidDataException($"Couldn't read chunk's data Chunk: {this}, read {array.Length} bytes");
			}
			return array;
		}

		public string GetDataAsString()
		{
			byte[] data = GetData();
			if (data == null)
			{
				return null;
			}
			return ByteEncoding.Instance.GetString(data, 0, data.Length);
		}

		public T GetDataAsStructure<T>(StructureBuilder<T> s)
		{
			riffFile.BaseStream.Position = DataOffset;
			if (s.Length != ChunkSize)
			{
				throw new InvalidDataException($"Chunk size is: {ChunkSize} so can't read structure of: {s.Length}");
			}
			return s.Read(riffFile);
		}

		public T[] GetDataAsStructureArray<T>(StructureBuilder<T> s)
		{
			riffFile.BaseStream.Position = DataOffset;
			if (ChunkSize % s.Length != 0L)
			{
				throw new InvalidDataException($"Chunk size is: {ChunkSize} not a multiple of structure size: {s.Length}");
			}
			int num = (int)(ChunkSize / s.Length);
			T[] array = new T[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = s.Read(riffFile);
			}
			return array;
		}

		public override string ToString()
		{
			return $"RiffChunk ID: {ChunkID} Size: {ChunkSize} Data Offset: {DataOffset}";
		}
	}
	internal class SampleDataChunk
	{
		public byte[] SampleData { get; private set; }

		public SampleDataChunk(RiffChunk chunk)
		{
			string text = chunk.ReadChunkID();
			if (text != "sdta")
			{
				throw new InvalidDataException("Not a sample data chunk (" + text + ")");
			}
			SampleData = chunk.GetData();
		}
	}
	public class SampleHeader
	{
		public string SampleName;

		public uint Start;

		public uint End;

		public uint StartLoop;

		public uint EndLoop;

		public uint SampleRate;

		public byte OriginalPitch;

		public sbyte PitchCorrection;

		public ushort SampleLink;

		public SFSampleLink SFSampleLink;

		public override string ToString()
		{
			return SampleName;
		}
	}
	internal class SampleHeaderBuilder : StructureBuilder<SampleHeader>
	{
		public override int Length => 46;

		public SampleHeader[] SampleHeaders => data.ToArray();

		public override SampleHeader Read(BinaryReader br)
		{
			SampleHeader sampleHeader = new SampleHeader();
			byte[] array = br.ReadBytes(20);
			sampleHeader.SampleName = ByteEncoding.Instance.GetString(array, 0, array.Length);
			sampleHeader.Start = br.ReadUInt32();
			sampleHeader.End = br.ReadUInt32();
			sampleHeader.StartLoop = br.ReadUInt32();
			sampleHeader.EndLoop = br.ReadUInt32();
			sampleHeader.SampleRate = br.ReadUInt32();
			sampleHeader.OriginalPitch = br.ReadByte();
			sampleHeader.PitchCorrection = br.ReadSByte();
			sampleHeader.SampleLink = br.ReadUInt16();
			sampleHeader.SFSampleLink = (SFSampleLink)br.ReadUInt16();
			data.Add(sampleHeader);
			return sampleHeader;
		}

		public override void Write(BinaryWriter bw, SampleHeader sampleHeader)
		{
		}

		internal void RemoveEOS()
		{
			data.RemoveAt(data.Count - 1);
		}
	}
	public enum SampleMode
	{
		NoLoop,
		LoopContinuously,
		ReservedNoLoop,
		LoopAndContinue
	}
	public enum SFSampleLink : ushort
	{
		MonoSample = 1,
		RightSample = 2,
		LeftSample = 4,
		LinkedSample = 8,
		RomMonoSample = 32769,
		RomRightSample = 32770,
		RomLeftSample = 32772,
		RomLinkedSample = 32776
	}
	public class SFVersion
	{
		public short Major { get; set; }

		public short Minor { get; set; }
	}
	internal class SFVersionBuilder : StructureBuilder<SFVersion>
	{
		public override int Length => 4;

		public override SFVersion Read(BinaryReader br)
		{
			SFVersion sFVersion = new SFVersion();
			sFVersion.Major = br.ReadInt16();
			sFVersion.Minor = br.ReadInt16();
			data.Add(sFVersion);
			return sFVersion;
		}

		public override void Write(BinaryWriter bw, SFVersion v)
		{
			bw.Write(v.Major);
			bw.Write(v.Minor);
		}
	}
	public class SoundFont
	{
		private InfoChunk info;

		private PresetsChunk presetsChunk;

		private SampleDataChunk sampleData;

		public InfoChunk FileInfo => info;

		public Preset[] Presets => presetsChunk.Presets;

		public Instrument[] Instruments => presetsChunk.Instruments;

		public SampleHeader[] SampleHeaders => presetsChunk.SampleHeaders;

		public byte[] SampleData => sampleData.SampleData;

		public SoundFont(string fileName)
			: this(new FileStream(fileName, FileMode.Open, FileAccess.Read))
		{
		}

		public SoundFont(Stream sfFile)
		{
			using (sfFile)
			{
				RiffChunk topLevelChunk = RiffChunk.GetTopLevelChunk(new BinaryReader(sfFile));
				if (topLevelChunk.ChunkID == "RIFF")
				{
					string text = topLevelChunk.ReadChunkID();
					if (text != "sfbk")
					{
						throw new InvalidDataException($"Not a SoundFont ({text})");
					}
					RiffChunk nextSubChunk = topLevelChunk.GetNextSubChunk();
					if (nextSubChunk.ChunkID == "LIST")
					{
						info = new InfoChunk(nextSubChunk);
						RiffChunk nextSubChunk2 = topLevelChunk.GetNextSubChunk();
						sampleData = new SampleDataChunk(nextSubChunk2);
						nextSubChunk2 = topLevelChunk.GetNextSubChunk();
						presetsChunk = new PresetsChunk(nextSubChunk2);
						return;
					}
					throw new InvalidDataException($"Not info list found ({nextSubChunk.ChunkID})");
				}
				throw new InvalidDataException("Not a RIFF file");
			}
		}

		public override string ToString()
		{
			return $"Info Chunk:\r\n{info}\r\nPresets Chunk:\r\n{presetsChunk}";
		}
	}
	internal abstract class StructureBuilder<T>
	{
		protected List<T> data;

		public abstract int Length { get; }

		public T[] Data => data.ToArray();

		public StructureBuilder()
		{
			Reset();
		}

		public abstract T Read(BinaryReader br);

		public abstract void Write(BinaryWriter bw, T o);

		public void Reset()
		{
			data = new List<T>();
		}
	}
	public class Zone
	{
		internal ushort generatorIndex;

		internal ushort modulatorIndex;

		internal ushort generatorCount;

		internal ushort modulatorCount;

		public Modulator[] Modulators { get; set; }

		public Generator[] Generators { get; set; }

		public override string ToString()
		{
			return $"Zone {generatorCount} Gens:{generatorIndex} {modulatorCount} Mods:{modulatorIndex}";
		}
	}
	internal class ZoneBuilder : StructureBuilder<Zone>
	{
		private Zone lastZone;

		public Zone[] Zones => data.ToArray();

		public override int Length => 4;

		public override Zone Read(BinaryReader br)
		{
			Zone zone = new Zone();
			zone.generatorIndex = br.ReadUInt16();
			zone.modulatorIndex = br.ReadUInt16();
			if (lastZone != null)
			{
				lastZone.generatorCount = (ushort)(zone.generatorIndex - lastZone.generatorIndex);
				lastZone.modulatorCount = (ushort)(zone.modulatorIndex - lastZone.modulatorIndex);
			}
			data.Add(zone);
			lastZone = zone;
			return zone;
		}

		public override void Write(BinaryWriter bw, Zone zone)
		{
		}

		public void Load(Modulator[] modulators, Generator[] generators)
		{
			for (int i = 0; i < data.Count - 1; i++)
			{
				Zone zone = data[i];
				zone.Generators = new Generator[zone.generatorCount];
				Array.Copy(generators, zone.generatorIndex, zone.Generators, 0, zone.generatorCount);
				zone.Modulators = new Modulator[zone.modulatorCount];
				Array.Copy(modulators, zone.modulatorIndex, zone.Modulators, 0, zone.modulatorCount);
			}
			data.RemoveAt(data.Count - 1);
		}
	}
}
namespace NAudio.Wave
{
	public enum ChannelMode
	{
		Stereo,
		JointStereo,
		DualChannel,
		Mono
	}
	public class Id3v2Tag
	{
		private long tagStartPosition;

		private long tagEndPosition;

		private byte[] rawData;

		public byte[] RawData => rawData;

		public static Id3v2Tag ReadTag(Stream input)
		{
			try
			{
				return new Id3v2Tag(input);
			}
			catch (FormatException)
			{
				return null;
			}
		}

		public static Id3v2Tag Create(IEnumerable<KeyValuePair<string, string>> tags)
		{
			return ReadTag(CreateId3v2TagStream(tags));
		}

		private static byte[] FrameSizeToBytes(int n)
		{
			byte[] bytes = BitConverter.GetBytes(n);
			Array.Reverse((Array)bytes);
			return bytes;
		}

		private static byte[] CreateId3v2Frame(string key, string value)
		{
			if (string.IsNullOrEmpty(key))
			{
				throw new ArgumentNullException("key");
			}
			if (string.IsNullOrEmpty(value))
			{
				throw new ArgumentNullException("value");
			}
			if (key.Length != 4)
			{
				throw new ArgumentOutOfRangeException("key", "key " + key + " must be 4 characters long");
			}
			byte[] array = new byte[2] { 255, 254 };
			byte[] array2 = new byte[3];
			byte[] array3 = new byte[2];
			byte[] array4 = ((!(key == "COMM")) ? ByteArrayExtensions.Concat(new byte[1] { 1 }, array, Encoding.Unicode.GetBytes(value)) : ByteArrayExtensions.Concat(new byte[1] { 1 }, array2, array3, array, Encoding.Unicode.GetBytes(value)));
			return ByteArrayExtensions.Concat(Encoding.UTF8.GetBytes(key), FrameSizeToBytes(array4.Length), new byte[2], array4);
		}

		private static byte[] GetId3TagHeaderSize(int size)
		{
			byte[] array = new byte[4];
			for (int num = array.Length - 1; num >= 0; num--)
			{
				array[num] = (byte)(size % 128);
				size /= 128;
			}
			return array;
		}

		private static byte[] CreateId3v2TagHeader(IEnumerable<byte[]> frames)
		{
			int num = 0;
			foreach (byte[] frame in frames)
			{
				num += frame.Length;
			}
			return ByteArrayExtensions.Concat(Encoding.UTF8.GetBytes("ID3"), new byte[2] { 3, 0 }, new byte[1], GetId3TagHeaderSize(num));
		}

		private static Stream CreateId3v2TagStream(IEnumerable<KeyValuePair<string, string>> tags)
		{
			List<byte[]> list = new List<byte[]>();
			foreach (KeyValuePair<string, string> tag in tags)
			{
				list.Add(CreateId3v2Frame(tag.Key, tag.Value));
			}
			byte[] array = CreateId3v2TagHeader(list);
			MemoryStream memoryStream = new MemoryStream();
			memoryStream.Write(array, 0, array.Length);
			foreach (byte[] item in list)
			{
				memoryStream.Write(item, 0, item.Length);
			}
			memoryStream.Position = 0L;
			return memoryStream;
		}

		private Id3v2Tag(Stream input)
		{
			tagStartPosition = input.Position;
			BinaryReader binaryReader = new BinaryReader(input);
			byte[] array = binaryReader.ReadBytes(10);
			if (array.Length >= 3 && array[0] == 73 && array[1] == 68 && array[2] == 51)
			{
				if ((array[5] & 0x40) == 64)
				{
					byte[] array2 = binaryReader.ReadBytes(4);
					_ = array2[0] * 2097152 + array2[1] * 16384 + array2[2] * 128;
					_ = array2[3];
				}
				int num = array[6] * 2097152;
				num += array[7] * 16384;
				num += array[8] * 128;
				num += array[9];
				binaryReader.ReadBytes(num);
				if ((array[5] & 0x10) == 16)
				{
					binaryReader.ReadBytes(10);
				}
				tagEndPosition = input.Position;
				input.Position = tagStartPosition;
				rawData = binaryReader.ReadBytes((int)(tagEndPosition - tagStartPosition));
				return;
			}
			input.Position = tagStartPosition;
			throw new FormatException("Not an ID3v2 tag");
		}
	}
	public interface IMp3FrameDecompressor : IDisposable
	{
		WaveFormat OutputFormat { get; }

		int DecompressFrame(Mp3Frame frame, byte[] dest, int destOffset);

		void Reset();
	}
	public class Mp3Frame
	{
		private static readonly int[,,] bitRates = new int[2, 3, 15]
		{
			{
				{
					0, 32, 64, 96, 128, 160, 192, 224, 256, 288,
					320, 352, 384, 416, 448
				},
				{
					0, 32, 48, 56, 64, 80, 96, 112, 128, 160,
					192, 224, 256, 320, 384
				},
				{
					0, 32, 40, 48, 56, 64, 80, 96, 112, 128,
					160, 192, 224, 256, 320
				}
			},
			{
				{
					0, 32, 48, 56, 64, 80, 96, 112, 128, 144,
					160, 176, 192, 224, 256
				},
				{
					0, 8, 16, 24, 32, 40, 48, 56, 64, 80,
					96, 112, 128, 144, 160
				},
				{
					0, 8, 16, 24, 32, 40, 48, 56, 64, 80,
					96, 112, 128, 144, 160
				}
			}
		};

		private static readonly int[,] samplesPerFrame = new int[2, 3]
		{
			{ 384, 1152, 1152 },
			{ 384, 1152, 576 }
		};

		private static readonly int[] sampleRatesVersion1 = new int[3] { 44100, 48000, 32000 };

		private static readonly int[] sampleRatesVersion2 = new int[3] { 22050, 24000, 16000 };

		private static readonly int[] sampleRatesVersion25 = new int[3] { 11025, 12000, 8000 };

		private const int MaxFrameLength = 16384;

		public int SampleRate { get; private set; }

		public int FrameLength { get; private set; }

		public int BitRate { get; private set; }

		public byte[] RawData { get; private set; }

		public MpegVersion MpegVersion { get; private set; }

		public MpegLayer MpegLayer { get; private set; }

		public ChannelMode ChannelMode { get; private set; }

		public int SampleCount { get; private set; }

		public int ChannelExtension { get; private set; }

		public int BitRateIndex { get; private set; }

		public bool Copyright { get; private set; }

		public bool CrcPresent { get; private set; }

		public long FileOffset { get; private set; }

		public static Mp3Frame LoadFromStream(Stream input)
		{
			return LoadFromStream(input, readData: true);
		}

		public static Mp3Frame LoadFromStream(Stream input, bool readData)
		{
			Mp3Frame mp3Frame = new Mp3Frame();
			mp3Frame.FileOffset = input.Position;
			byte[] array = new byte[4];
			if (input.Read(array, 0, array.Length) < array.Length)
			{
				return null;
			}
			while (!IsValidHeader(array, mp3Frame))
			{
				array[0] = array[1];
				array[1] = array[2];
				array[2] = array[3];
				if (input.Read(array, 3, 1) < 1)
				{
					return null;
				}
				mp3Frame.FileOffset++;
			}
			int num = mp3Frame.FrameLength - 4;
			if (readData)
			{
				mp3Frame.RawData = new byte[mp3Frame.FrameLength];
				Array.Copy(array, mp3Frame.RawData, 4);
				if (input.Read(mp3Frame.RawData, 4, num) < num)
				{
					throw new EndOfStreamException("Unexpected end of stream before frame complete");
				}
			}
			else
			{
				input.Position += num;
			}
			return mp3Frame;
		}

		private Mp3Frame()
		{
		}

		private static bool IsValidHeader(byte[] headerBytes, Mp3Frame frame)
		{
			if (headerBytes[0] == byte.MaxValue && (headerBytes[1] & 0xE0) == 224)
			{
				frame.MpegVersion = (MpegVersion)((headerBytes[1] & 0x18) >> 3);
				if (frame.MpegVersion == MpegVersion.Reserved)
				{
					return false;
				}
				frame.MpegLayer = (MpegLayer)((headerBytes[1] & 6) >> 1);
				if (frame.MpegLayer == MpegLayer.Reserved)
				{
					return false;
				}
				int num = ((frame.MpegLayer != MpegLayer.Layer1) ? ((frame.MpegLayer == MpegLayer.Layer2) ? 1 : 2) : 0);
				frame.CrcPresent = (headerBytes[1] & 1) == 0;
				frame.BitRateIndex = (headerBytes[2] & 0xF0) >> 4;
				if (frame.BitRateIndex == 15)
				{
					return false;
				}
				int num2 = ((frame.MpegVersion != MpegVersion.Version1) ? 1 : 0);
				frame.BitRate = bitRates[num2, num, frame.BitRateIndex] * 1000;
				if (frame.BitRate == 0)
				{
					return false;
				}
				int num3 = (headerBytes[2] & 0xC) >> 2;
				if (num3 == 3)
				{
					return false;
				}
				if (frame.MpegVersion == MpegVersion.Version1)
				{
					frame.SampleRate = sampleRatesVersion1[num3];
				}
				else if (frame.MpegVersion == MpegVersion.Version2)
				{
					frame.SampleRate = sampleRatesVersion2[num3];
				}
				else
				{
					frame.SampleRate = sampleRatesVersion25[num3];
				}
				bool flag = (headerBytes[2] & 2) == 2;
				_ = headerBytes[2];
				frame.ChannelMode = (ChannelMode)((headerBytes[3] & 0xC0) >> 6);
				frame.ChannelExtension = (headerBytes[3] & 0x30) >> 4;
				if (frame.ChannelExtension != 0 && frame.ChannelMode != ChannelMode.JointStereo)
				{
					return false;
				}
				frame.Copyright = (headerBytes[3] & 8) == 8;
				_ = headerBytes[3];
				_ = headerBytes[3];
				int num4 = (flag ? 1 : 0);
				frame.SampleCount = samplesPerFrame[num2, num];
				int num5 = frame.SampleCount / 8;
				if (frame.MpegLayer == MpegLayer.Layer1)
				{
					frame.FrameLength = (num5 * frame.BitRate / frame.SampleRate + num4) * 4;
				}
				else
				{
					frame.FrameLength = num5 * frame.BitRate / frame.SampleRate + num4;
				}
				if (frame.FrameLength > 16384)
				{
					return false;
				}
				return true;
			}
			return false;
		}
	}
	public enum MpegLayer
	{
		Reserved,
		Layer3,
		Layer2,
		Layer1
	}
	public enum MpegVersion
	{
		Version25,
		Reserved,
		Version2,
		Version1
	}
	public class XingHeader
	{
		[Flags]
		private enum XingHeaderOptions
		{
			Frames = 1,
			Bytes = 2,
			Toc = 4,
			VbrScale = 8
		}

		private static int[] sr_table = new int[4] { 44100, 48000, 32000, 99999 };

		private int vbrScale = -1;

		private int startOffset;

		private int endOffset;

		private int tocOffset = -1;

		private int framesOffset = -1;

		private int bytesOffset = -1;

		private Mp3Frame frame;

		public int Frames
		{
			get
			{
				if (framesOffset == -1)
				{
					return -1;
				}
				return ReadBigEndian(frame.RawData, framesOffset);
			}
			set
			{
				if (framesOffset == -1)
				{
					throw new InvalidOperationException("Frames flag is not set");
				}
				WriteBigEndian(frame.RawData, framesOffset, value);
			}
		}

		public int Bytes
		{
			get
			{
				if (bytesOffset == -1)
				{
					return -1;
				}
				return ReadBigEndian(frame.RawData, bytesOffset);
			}
			set
			{
				if (framesOffset == -1)
				{
					throw new InvalidOperationException("Bytes flag is not set");
				}
				WriteBigEndian(frame.RawData, bytesOffset, value);
			}
		}

		public int VbrScale => vbrScale;

		public Mp3Frame Mp3Frame => frame;

		private static int ReadBigEndian(byte[] buffer, int offset)
		{
			return (((((buffer[offset] << 8) | buffer[offset + 1]) << 8) | buffer[offset + 2]) << 8) | buffer[offset + 3];
		}

		private void WriteBigEndian(byte[] buffer, int offset, int value)
		{
			byte[] bytes = BitConverter.GetBytes(value);
			for (int i = 0; i < 4; i++)
			{
				buffer[offset + 3 - i] = bytes[i];
			}
		}

		public static XingHeader LoadXingHeader(Mp3Frame frame)
		{
			XingHeader xingHeader = new XingHeader();
			xingHeader.frame = frame;
			int num = 0;
			if (frame.MpegVersion == MpegVersion.Version1)
			{
				num = ((frame.ChannelMode == ChannelMode.Mono) ? 21 : 36);
			}
			else
			{
				if (frame.MpegVersion != MpegVersion.Version2)
				{
					return null;
				}
				num = ((frame.ChannelMode == ChannelMode.Mono) ? 13 : 21);
			}
			if (frame.RawData[num] == 88 && frame.RawData[num + 1] == 105 && frame.RawData[num + 2] == 110 && frame.RawData[num + 3] == 103)
			{
				xingHeader.startOffset = num;
				num += 4;
			}
			else
			{
				if (frame.RawData[num] != 73 || frame.RawData[num + 1] != 110 || frame.RawData[num + 2] != 102 || frame.RawData[num + 3] != 111)
				{
					return null;
				}
				xingHeader.startOffset = num;
				num += 4;
			}
			int num2 = ReadBigEndian(frame.RawData, num);
			num += 4;
			if (((uint)num2 & (true ? 1u : 0u)) != 0)
			{
				xingHeader.framesOffset = num;
				num += 4;
			}
			if (((uint)num2 & 2u) != 0)
			{
				xingHeader.bytesOffset = num;
				num += 4;
			}
			if (((uint)num2 & 4u) != 0)
			{
				xingHeader.tocOffset = num;
				num += 100;
			}
			if (((uint)num2 & 8u) != 0)
			{
				xingHeader.vbrScale = ReadBigEndian(frame.RawData, num);
				num += 4;
			}
			xingHeader.endOffset = num;
			return xingHeader;
		}

		private XingHeader()
		{
		}
	}
	public static class WaveExtensionMethods
	{
		public static ISampleProvider ToSampleProvider(this IWaveProvider waveProvider)
		{
			return SampleProviderConverters.ConvertWaveProviderIntoSampleProvider(waveProvider);
		}

		public static void Init(this IWavePlayer wavePlayer, ISampleProvider sampleProvider, bool convertTo16Bit = false)
		{
			IWaveProvider waveProvider2;
			if (!convertTo16Bit)
			{
				IWaveProvider waveProvider = new SampleToWaveProvider(sampleProvider);
				waveProvider2 = waveProvider;
			}
			else
			{
				IWaveProvider waveProvider = new SampleToWaveProvider16(sampleProvider);
				waveProvider2 = waveProvider;
			}
			IWaveProvider waveProvider3 = waveProvider2;
			wavePlayer.Init(waveProvider3);
		}

		public static WaveFormat AsStandardWaveFormat(this WaveFormat waveFormat)
		{
			if (!(waveFormat is WaveFormatExtensible waveFormatExtensible))
			{
				return waveFormat;
			}
			return waveFormatExtensible.ToStandardWaveFormat();
		}

		public static IWaveProvider ToWaveProvider(this ISampleProvider sampleProvider)
		{
			return new SampleToWaveProvider(sampleProvider);
		}

		public static IWaveProvider ToWaveProvider16(this ISampleProvider sampleProvider)
		{
			return new SampleToWaveProvider16(sampleProvider);
		}

		public static ISampleProvider FollowedBy(this ISampleProvider sampleProvider, ISampleProvider next)
		{
			return new ConcatenatingSampleProvider(new ISampleProvider[2] { sampleProvider, next });
		}

		public static ISampleProvider FollowedBy(this ISampleProvider sampleProvider, TimeSpan silenceDuration, ISampleProvider next)
		{
			OffsetSampleProvider offsetSampleProvider = new OffsetSampleProvider(sampleProvider)
			{
				LeadOut = silenceDuration
			};
			return new ConcatenatingSampleProvider(new ISampleProvider[2] { offsetSampleProvider, next });
		}

		public static ISampleProvider Skip(this ISampleProvider sampleProvider, TimeSpan skipDuration)
		{
			return new OffsetSampleProvider(sampleProvider)
			{
				SkipOver = skipDuration
			};
		}

		public static ISampleProvider Take(this ISampleProvider sampleProvider, TimeSpan takeDuration)
		{
			return new OffsetSampleProvider(sampleProvider)
			{
				Take = takeDuration
			};
		}

		public static ISampleProvider ToMono(this ISampleProvider sourceProvider, float leftVol = 0.5f, float rightVol = 0.5f)
		{
			if (sourceProvider.WaveFormat.Channels == 1)
			{
				return sourceProvider;
			}
			return new StereoToMonoSampleProvider(sourceProvider)
			{
				LeftVolume = leftVol,
				RightVolume = rightVol
			};
		}

		public static ISampleProvider ToStereo(this ISampleProvider sourceProvider, float leftVol = 1f, float rightVol = 1f)
		{
			if (sourceProvider.WaveFormat.Channels == 2)
			{
				return sourceProvider;
			}
			return new MonoToStereoSampleProvider(sourceProvider)
			{
				LeftVolume = leftVol,
				RightVolume = rightVol
			};
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class AdpcmWaveFormat : WaveFormat
	{
		private short samplesPerBlock;

		private short numCoeff;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 14)]
		private short[] coefficients;

		public int SamplesPerBlock => samplesPerBlock;

		public int NumCoefficients => numCoeff;

		public short[] Coefficients => coefficients;

		private AdpcmWaveFormat()
			: this(8000, 1)
		{
		}

		public AdpcmWaveFormat(int sampleRate, int channels)
			: base(sampleRate, 0, channels)
		{
			waveFormatTag = WaveFormatEncoding.Adpcm;
			extraSize = 32;
			switch (base.sampleRate)
			{
			case 8000:
			case 11025:
				blockAlign = 256;
				break;
			case 22050:
				blockAlign = 512;
				break;
			default:
				blockAlign = 1024;
				break;
			}
			bitsPerSample = 4;
			samplesPerBlock = (short)((blockAlign - 7 * channels) * 8 / (bitsPerSample * channels) + 2);
			averageBytesPerSecond = base.SampleRate * blockAlign / samplesPerBlock;
			numCoeff = 7;
			coefficients = new short[14]
			{
				256, 0, 512, -256, 0, 0, 192, 64, 240, 0,
				460, -208, 392, -232
			};
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			writer.Write(samplesPerBlock);
			writer.Write(numCoeff);
			short[] array = coefficients;
			foreach (short value in array)
			{
				writer.Write(value);
			}
		}

		public override string ToString()
		{
			return $"Microsoft ADPCM {base.SampleRate} Hz {channels} channels {bitsPerSample} bits per sample {samplesPerBlock} samples per block";
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class Gsm610WaveFormat : WaveFormat
	{
		private readonly short samplesPerBlock;

		public short SamplesPerBlock => samplesPerBlock;

		public Gsm610WaveFormat()
		{
			waveFormatTag = WaveFormatEncoding.Gsm610;
			channels = 1;
			averageBytesPerSecond = 1625;
			bitsPerSample = 0;
			blockAlign = 65;
			sampleRate = 8000;
			extraSize = 2;
			samplesPerBlock = 320;
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			writer.Write(samplesPerBlock);
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class ImaAdpcmWaveFormat : WaveFormat
	{
		private short samplesPerBlock;

		private ImaAdpcmWaveFormat()
		{
		}

		public ImaAdpcmWaveFormat(int sampleRate, int channels, int bitsPerSample)
		{
			waveFormatTag = WaveFormatEncoding.DviAdpcm;
			base.sampleRate = sampleRate;
			base.channels = (short)channels;
			base.bitsPerSample = (short)bitsPerSample;
			extraSize = 2;
			blockAlign = 0;
			averageBytesPerSecond = 0;
			samplesPerBlock = 0;
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class Mp3WaveFormat : WaveFormat
	{
		public Mp3WaveFormatId id;

		public Mp3WaveFormatFlags flags;

		public ushort blockSize;

		public ushort framesPerBlock;

		public ushort codecDelay;

		private const short Mp3WaveFormatExtraBytes = 12;

		public Mp3WaveFormat(int sampleRate, int channels, int blockSize, int bitRate)
		{
			waveFormatTag = WaveFormatEncoding.MpegLayer3;
			base.channels = (short)channels;
			averageBytesPerSecond = bitRate / 8;
			bitsPerSample = 0;
			blockAlign = 1;
			base.sampleRate = sampleRate;
			extraSize = 12;
			id = Mp3WaveFormatId.Mpeg;
			flags = Mp3WaveFormatFlags.PaddingIso;
			this.blockSize = (ushort)blockSize;
			framesPerBlock = 1;
			codecDelay = 0;
		}
	}
	[Flags]
	public enum Mp3WaveFormatFlags
	{
		PaddingIso = 0,
		PaddingOn = 1,
		PaddingOff = 2
	}
	public enum Mp3WaveFormatId : ushort
	{
		Unknown,
		Mpeg,
		ConstantFrameSize
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	internal class OggWaveFormat : WaveFormat
	{
		public uint dwVorbisACMVersion;

		public uint dwLibVorbisVersion;
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class TrueSpeechWaveFormat : WaveFormat
	{
		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
		private short[] unknown;

		public TrueSpeechWaveFormat()
		{
			waveFormatTag = WaveFormatEncoding.DspGroupTrueSpeech;
			channels = 1;
			averageBytesPerSecond = 1067;
			bitsPerSample = 1;
			blockAlign = 32;
			sampleRate = 8000;
			extraSize = 32;
			unknown = new short[16];
			unknown[0] = 1;
			unknown[1] = 240;
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			short[] array = unknown;
			foreach (short value in array)
			{
				writer.Write(value);
			}
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class WaveFormat
	{
		protected WaveFormatEncoding waveFormatTag;

		protected short channels;

		protected int sampleRate;

		protected int averageBytesPerSecond;

		protected short blockAlign;

		protected short bitsPerSample;

		protected short extraSize;

		public WaveFormatEncoding Encoding => waveFormatTag;

		public int Channels => channels;

		public int SampleRate => sampleRate;

		public int AverageBytesPerSecond => averageBytesPerSecond;

		public virtual int BlockAlign => blockAlign;

		public int BitsPerSample => bitsPerSample;

		public int ExtraSize => extraSize;

		public WaveFormat()
			: this(44100, 16, 2)
		{
		}

		public WaveFormat(int sampleRate, int channels)
			: this(sampleRate, 16, channels)
		{
		}

		public int ConvertLatencyToByteSize(int milliseconds)
		{
			int num = (int)((double)AverageBytesPerSecond / 1000.0 * (double)milliseconds);
			if (num % BlockAlign != 0)
			{
				num = num + BlockAlign - num % BlockAlign;
			}
			return num;
		}

		public static WaveFormat CreateCustomFormat(WaveFormatEncoding tag, int sampleRate, int channels, int averageBytesPerSecond, int blockAlign, int bitsPerSample)
		{
			return new WaveFormat
			{
				waveFormatTag = tag,
				channels = (short)channels,
				sampleRate = sampleRate,
				averageBytesPerSecond = averageBytesPerSecond,
				blockAlign = (short)blockAlign,
				bitsPerSample = (short)bitsPerSample,
				extraSize = 0
			};
		}

		public static WaveFormat CreateALawFormat(int sampleRate, int channels)
		{
			return CreateCustomFormat(WaveFormatEncoding.ALaw, sampleRate, channels, sampleRate * channels, channels, 8);
		}

		public static WaveFormat CreateMuLawFormat(int sampleRate, int channels)
		{
			return CreateCustomFormat(WaveFormatEncoding.MuLaw, sampleRate, channels, sampleRate * channels, channels, 8);
		}

		public WaveFormat(int rate, int bits, int channels)
		{
			if (channels < 1)
			{
				throw new ArgumentOutOfRangeException("channels", "Channels must be 1 or greater");
			}
			waveFormatTag = WaveFormatEncoding.Pcm;
			this.channels = (short)channels;
			sampleRate = rate;
			bitsPerSample = (short)bits;
			extraSize = 0;
			blockAlign = (short)(channels * (bits / 8));
			averageBytesPerSecond = sampleRate * blockAlign;
		}

		public static WaveFormat CreateIeeeFloatWaveFormat(int sampleRate, int channels)
		{
			WaveFormat waveFormat = new WaveFormat();
			waveFormat.waveFormatTag = WaveFormatEncoding.IeeeFloat;
			waveFormat.channels = (short)channels;
			waveFormat.bitsPerSample = 32;
			waveFormat.sampleRate = sampleRate;
			waveFormat.blockAlign = (short)(4 * channels);
			waveFormat.averageBytesPerSecond = sampleRate * waveFormat.blockAlign;
			waveFormat.extraSize = 0;
			return waveFormat;
		}

		public static WaveFormat MarshalFromPtr(IntPtr pointer)
		{
			WaveFormat waveFormat = Marshal.PtrToStructure<WaveFormat>(pointer);
			switch (waveFormat.Encoding)
			{
			case WaveFormatEncoding.Pcm:
				waveFormat.extraSize = 0;
				break;
			case WaveFormatEncoding.Extensible:
				waveFormat = Marshal.PtrToStructure<WaveFormatExtensible>(pointer);
				break;
			case WaveFormatEncoding.Adpcm:
				waveFormat = Marshal.PtrToStructure<AdpcmWaveFormat>(pointer);
				break;
			case WaveFormatEncoding.Gsm610:
				waveFormat = Marshal.PtrToStructure<Gsm610WaveFormat>(pointer);
				break;
			default:
				if (waveFormat.ExtraSize > 0)
				{
					waveFormat = Marshal.PtrToStructure<WaveFormatExtraData>(pointer);
				}
				break;
			}
			return waveFormat;
		}

		public static IntPtr MarshalToPtr(WaveFormat format)
		{
			IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(format));
			Marshal.StructureToPtr(format, intPtr, fDeleteOld: false);
			return intPtr;
		}

		public static WaveFormat FromFormatChunk(BinaryReader br, int formatChunkLength)
		{
			WaveFormatExtraData waveFormatExtraData = new WaveFormatExtraData();
			waveFormatExtraData.ReadWaveFormat(br, formatChunkLength);
			waveFormatExtraData.ReadExtraData(br);
			return waveFormatExtraData;
		}

		private void ReadWaveFormat(BinaryReader br, int formatChunkLength)
		{
			if (formatChunkLength < 16)
			{
				throw new InvalidDataException("Invalid WaveFormat Structure");
			}
			waveFormatTag = (WaveFormatEncoding)br.ReadUInt16();
			channels = br.ReadInt16();
			sampleRate = br.ReadInt32();
			averageBytesPerSecond = br.ReadInt32();
			blockAlign = br.ReadInt16();
			bitsPerSample = br.ReadInt16();
			if (formatChunkLength > 16)
			{
				extraSize = br.ReadInt16();
				if (extraSize != formatChunkLength - 18)
				{
					extraSize = (short)(formatChunkLength - 18);
				}
			}
		}

		public WaveFormat(BinaryReader br)
		{
			int formatChunkLength = br.ReadInt32();
			ReadWaveFormat(br, formatChunkLength);
		}

		public override string ToString()
		{
			switch (waveFormatTag)
			{
			case WaveFormatEncoding.Pcm:
			case WaveFormatEncoding.Extensible:
				return $"{bitsPerSample} bit PCM: {sampleRate}Hz {channels} channels";
			case WaveFormatEncoding.IeeeFloat:
				return $"{bitsPerSample} bit IEEFloat: {sampleRate}Hz {channels} channels";
			default:
				return waveFormatTag.ToString();
			}
		}

		public override bool Equals(object obj)
		{
			if (obj is WaveFormat waveFormat)
			{
				if (waveFormatTag == waveFormat.waveFormatTag && channels == waveFormat.channels && sampleRate == waveFormat.sampleRate && averageBytesPerSecond == waveFormat.averageBytesPerSecond && blockAlign == waveFormat.blockAlign)
				{
					return bitsPerSample == waveFormat.bitsPerSample;
				}
				return false;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return (int)waveFormatTag ^ (int)channels ^ sampleRate ^ averageBytesPerSecond ^ blockAlign ^ bitsPerSample;
		}

		public virtual void Serialize(BinaryWriter writer)
		{
			writer.Write(18 + extraSize);
			writer.Write((short)Encoding);
			writer.Write((short)Channels);
			writer.Write(SampleRate);
			writer.Write(AverageBytesPerSecond);
			writer.Write((short)BlockAlign);
			writer.Write((short)BitsPerSample);
			writer.Write(extraSize);
		}
	}
	public sealed class WaveFormatCustomMarshaler : ICustomMarshaler
	{
		private static WaveFormatCustomMarshaler marshaler;

		public static ICustomMarshaler GetInstance(string cookie)
		{
			if (marshaler == null)
			{
				marshaler = new WaveFormatCustomMarshaler();
			}
			return marshaler;
		}

		public void CleanUpManagedData(object ManagedObj)
		{
		}

		public void CleanUpNativeData(IntPtr pNativeData)
		{
			Marshal.FreeHGlobal(pNativeData);
		}

		public int GetNativeDataSize()
		{
			throw new NotImplementedException();
		}

		public IntPtr MarshalManagedToNative(object ManagedObj)
		{
			return WaveFormat.MarshalToPtr((WaveFormat)ManagedObj);
		}

		public object MarshalNativeToManaged(IntPtr pNativeData)
		{
			return WaveFormat.MarshalFromPtr(pNativeData);
		}
	}
	public enum WaveFormatEncoding : ushort
	{
		Unknown = 0,
		Pcm = 1,
		Adpcm = 2,
		IeeeFloat = 3,
		Vselp = 4,
		IbmCvsd = 5,
		ALaw = 6,
		MuLaw = 7,
		Dts = 8,
		Drm = 9,
		WmaVoice9 = 10,
		OkiAdpcm = 16,
		DviAdpcm = 17,
		ImaAdpcm = 17,
		MediaspaceAdpcm = 18,
		SierraAdpcm = 19,
		G723Adpcm = 20,
		DigiStd = 21,
		DigiFix = 22,
		DialogicOkiAdpcm = 23,
		MediaVisionAdpcm = 24,
		CUCodec = 25,
		YamahaAdpcm = 32,
		SonarC = 33,
		DspGroupTrueSpeech = 34,
		EchoSpeechCorporation1 = 35,
		AudioFileAf36 = 36,
		Aptx = 37,
		AudioFileAf10 = 38,
		Prosody1612 = 39,
		Lrc = 40,
		DolbyAc2 = 48,
		Gsm610 = 49,
		MsnAudio = 50,
		AntexAdpcme = 51,
		ControlResVqlpc = 52,
		DigiReal = 53,
		DigiAdpcm = 54,
		ControlResCr10 = 55,
		WAVE_FORMAT_NMS_VBXADPCM = 56,
		WAVE_FORMAT_CS_IMAADPCM = 57,
		WAVE_FORMAT_ECHOSC3 = 58,
		WAVE_FORMAT_ROCKWELL_ADPCM = 59,
		WAVE_FORMAT_ROCKWELL_DIGITALK = 60,
		WAVE_FORMAT_XEBEC = 61,
		WAVE_FORMAT_G721_ADPCM = 64,
		WAVE_FORMAT_G728_CELP = 65,
		WAVE_FORMAT_MSG723 = 66,
		Mpeg = 80,
		WAVE_FORMAT_RT24 = 82,
		WAVE_FORMAT_PAC = 83,
		MpegLayer3 = 85,
		WAVE_FORMAT_LUCENT_G723 = 89,
		WAVE_FORMAT_CIRRUS = 96,
		WAVE_FORMAT_ESPCM = 97,
		WAVE_FORMAT_VOXWARE = 98,
		WAVE_FORMAT_CANOPUS_ATRAC = 99,
		WAVE_FORMAT_G726_ADPCM = 100,
		WAVE_FORMAT_G722_ADPCM = 101,
		WAVE_FORMAT_DSAT_DISPLAY = 103,
		WAVE_FORMAT_VOXWARE_BYTE_ALIGNED = 105,
		WAVE_FORMAT_VOXWARE_AC8 = 112,
		WAVE_FORMAT_VOXWARE_AC10 = 113,
		WAVE_FORMAT_VOXWARE_AC16 = 114,
		WAVE_FORMAT_VOXWARE_AC20 = 115,
		WAVE_FORMAT_VOXWARE_RT24 = 116,
		WAVE_FORMAT_VOXWARE_RT29 = 117,
		WAVE_FORMAT_VOXWARE_RT29HW = 118,
		WAVE_FORMAT_VOXWARE_VR12 = 119,
		WAVE_FORMAT_VOXWARE_VR18 = 120,
		WAVE_FORMAT_VOXWARE_TQ40 = 121,
		WAVE_FORMAT_SOFTSOUND = 128,
		WAVE_FORMAT_VOXWARE_TQ60 = 129,
		WAVE_FORMAT_MSRT24 = 130,
		WAVE_FORMAT_G729A = 131,
		WAVE_FORMAT_MVI_MVI2 = 132,
		WAVE_FORMAT_DF_G726 = 133,
		WAVE_FORMAT_DF_GSM610 = 134,
		WAVE_FORMAT_ISIAUDIO = 136,
		WAVE_FORMAT_ONLIVE = 137,
		WAVE_FORMAT_SBC24 = 145,
		WAVE_FORMAT_DOLBY_AC3_SPDIF = 146,
		WAVE_FORMAT_MEDIASONIC_G723 = 147,
		WAVE_FORMAT_PROSODY_8KBPS = 148,
		WAVE_FORMAT_ZYXEL_ADPCM = 151,
		WAVE_FORMAT_PHILIPS_LPCBB = 152,
		WAVE_FORMAT_PACKED = 153,
		WAVE_FORMAT_MALDEN_PHONYTALK = 160,
		Gsm = 161,
		G729 = 162,
		G723 = 163,
		Acelp = 164,
		RawAac = 255,
		WAVE_FORMAT_RHETOREX_ADPCM = 256,
		WAVE_FORMAT_IRAT = 257,
		WAVE_FORMAT_VIVO_G723 = 273,
		WAVE_FORMAT_VIVO_SIREN = 274,
		WAVE_FORMAT_DIGITAL_G723 = 291,
		WAVE_FORMAT_SANYO_LD_ADPCM = 293,
		WAVE_FORMAT_SIPROLAB_ACEPLNET = 304,
		WAVE_FORMAT_SIPROLAB_ACELP4800 = 305,
		WAVE_FORMAT_SIPROLAB_ACELP8V3 = 306,
		WAVE_FORMAT_SIPROLAB_G729 = 307,
		WAVE_FORMAT_SIPROLAB_G729A = 308,
		WAVE_FORMAT_SIPROLAB_KELVIN = 309,
		WAVE_FORMAT_G726ADPCM = 320,
		WAVE_FORMAT_QUALCOMM_PUREVOICE = 336,
		WAVE_FORMAT_QUALCOMM_HALFRATE = 337,
		WAVE_FORMAT_TUBGSM = 341,
		WAVE_FORMAT_MSAUDIO1 = 352,
		WindowsMediaAudio = 353,
		WindowsMediaAudioProfessional = 354,
		WindowsMediaAudioLosseless = 355,
		WindowsMediaAudioSpdif = 356,
		WAVE_FORMAT_UNISYS_NAP_ADPCM = 368,
		WAVE_FORMAT_UNISYS_NAP_ULAW = 369,
		WAVE_FORMAT_UNISYS_NAP_ALAW = 370,
		WAVE_FORMAT_UNISYS_NAP_16K = 371,
		WAVE_FORMAT_CREATIVE_ADPCM = 512,
		WAVE_FORMAT_CREATIVE_FASTSPEECH8 = 514,
		WAVE_FORMAT_CREATIVE_FASTSPEECH10 = 515,
		WAVE_FORMAT_UHER_ADPCM = 528,
		WAVE_FORMAT_QUARTERDECK = 544,
		WAVE_FORMAT_ILINK_VC = 560,
		WAVE_FORMAT_RAW_SPORT = 576,
		WAVE_FORMAT_ESST_AC3 = 577,
		WAVE_FORMAT_IPI_HSX = 592,
		WAVE_FORMAT_IPI_RPELP = 593,
		WAVE_FORMAT_CS2 = 608,
		WAVE_FORMAT_SONY_SCX = 624,
		WAVE_FORMAT_FM_TOWNS_SND = 768,
		WAVE_FORMAT_BTV_DIGITAL = 1024,
		WAVE_FORMAT_QDESIGN_MUSIC = 1104,
		WAVE_FORMAT_VME_VMPCM = 1664,
		WAVE_FORMAT_TPC = 1665,
		WAVE_FORMAT_OLIGSM = 4096,
		WAVE_FORMAT_OLIADPCM = 4097,
		WAVE_FORMAT_OLICELP = 4098,
		WAVE_FORMAT_OLISBC = 4099,
		WAVE_FORMAT_OLIOPR = 4100,
		WAVE_FORMAT_LH_CODEC = 4352,
		WAVE_FORMAT_NORRIS = 5120,
		WAVE_FORMAT_SOUNDSPACE_MUSICOMPRESS = 5376,
		MPEG_ADTS_AAC = 5632,
		MPEG_RAW_AAC = 5633,
		MPEG_LOAS = 5634,
		NOKIA_MPEG_ADTS_AAC = 5640,
		NOKIA_MPEG_RAW_AAC = 5641,
		VODAFONE_MPEG_ADTS_AAC = 5642,
		VODAFONE_MPEG_RAW_AAC = 5643,
		MPEG_HEAAC = 5648,
		WAVE_FORMAT_DVM = 8192,
		Vorbis1 = 26447,
		Vorbis2 = 26448,
		Vorbis3 = 26449,
		Vorbis1P = 26479,
		Vorbis2P = 26480,
		Vorbis3P = 26481,
		Extensible = 65534,
		WAVE_FORMAT_DEVELOPMENT = ushort.MaxValue
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class WaveFormatExtensible : WaveFormat
	{
		private short wValidBitsPerSample;

		private int dwChannelMask;

		private Guid subFormat;

		public Guid SubFormat => subFormat;

		private WaveFormatExtensible()
		{
		}

		public WaveFormatExtensible(int rate, int bits, int channels)
			: base(rate, bits, channels)
		{
			waveFormatTag = WaveFormatEncoding.Extensible;
			extraSize = 22;
			wValidBitsPerSample = (short)bits;
			for (int i = 0; i < channels; i++)
			{
				dwChannelMask |= 1 << i;
			}
			if (bits == 32)
			{
				subFormat = AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT;
			}
			else
			{
				subFormat = AudioMediaSubtypes.MEDIASUBTYPE_PCM;
			}
		}

		public WaveFormat ToStandardWaveFormat()
		{
			if (subFormat == AudioMediaSubtypes.MEDIASUBTYPE_IEEE_FLOAT && bitsPerSample == 32)
			{
				return WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channels);
			}
			if (subFormat == AudioMediaSubtypes.MEDIASUBTYPE_PCM)
			{
				return new WaveFormat(sampleRate, bitsPerSample, channels);
			}
			return this;
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			writer.Write(wValidBitsPerSample);
			writer.Write(dwChannelMask);
			byte[] array = subFormat.ToByteArray();
			writer.Write(array, 0, array.Length);
		}

		public override string ToString()
		{
			return "WAVE_FORMAT_EXTENSIBLE " + AudioMediaSubtypes.GetAudioSubtypeName(subFormat) + " " + $"{base.SampleRate}Hz {base.Channels} channels {base.BitsPerSample} bit";
		}
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	public class WaveFormatExtraData : WaveFormat
	{
		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
		private byte[] extraData = new byte[100];

		public byte[] ExtraData => extraData;

		internal WaveFormatExtraData()
		{
		}

		public WaveFormatExtraData(BinaryReader reader)
			: base(reader)
		{
			ReadExtraData(reader);
		}

		internal void ReadExtraData(BinaryReader reader)
		{
			if (extraSize > 0)
			{
				reader.Read(extraData, 0, extraSize);
			}
		}

		public override void Serialize(BinaryWriter writer)
		{
			base.Serialize(writer);
			if (extraSize > 0)
			{
				writer.Write(extraData, 0, extraSize);
			}
		}
	}
	public interface IWaveIn : IDisposable
	{
		WaveFormat WaveFormat { get; set; }

		event EventHandler<WaveInEventArgs> DataAvailable;

		event EventHandler<StoppedEventArgs> RecordingStopped;

		void StartRecording();

		void StopRecording();
	}
	public class WaveInEventArgs : EventArgs
	{
		private byte[] buffer;

		private int bytes;

		public byte[] Buffer => buffer;

		public int BytesRecorded => bytes;

		public WaveInEventArgs(byte[] buffer, int bytes)
		{
			this.buffer = buffer;
			this.bytes = bytes;
		}
	}
	public class AiffFileWriter : Stream
	{
		private Stream outStream;

		private BinaryWriter writer;

		private long dataSizePos;

		private long commSampleCountPos;

		private long dataChunkSize = 8L;

		private WaveFormat format;

		private string filename;

		private byte[] value24 = new byte[3];

		public string Filename => filename;

		public override long Length => dataChunkSize;

		public WaveFormat WaveFormat => format;

		public override bool CanRead => false;

		public override bool CanWrite => true;

		public override bool CanSeek => false;

		public override long Position
		{
			get
			{
				return dataChunkSize;
			}
			set
			{
				throw new InvalidOperationException("Repositioning an AiffFileWriter is not supported");
			}
		}

		public static void CreateAiffFile(string filename, WaveStream sourceProvider)
		{
			using AiffFileWriter aiffFileWriter = new AiffFileWriter(filename, sourceProvider.WaveFormat);
			byte[] array = new byte[16384];
			while (sourceProvider.Position < sourceProvider.Length)
			{
				int count = Math.Min((int)(sourceProvider.Length - sourceProvider.Position), array.Length);
				int num = sourceProvider.Read(array, 0, count);
				if (num == 0)
				{
					break;
				}
				aiffFileWriter.Write(array, 0, num);
			}
		}

		public AiffFileWriter(Stream outStream, WaveFormat format)
		{
			this.outStream = outStream;
			this.format = format;
			writer = new BinaryWriter(outStream, Encoding.UTF8);
			writer.Write(Encoding.UTF8.GetBytes("FORM"));
			writer.Write(0);
			writer.Write(Encoding.UTF8.GetBytes("AIFF"));
			CreateCommChunk();
			WriteSsndChunkHeader();
		}

		public AiffFileWriter(string filename, WaveFormat format)
			: this(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read), format)
		{
			this.filename = filename;
		}

		private void WriteSsndChunkHeader()
		{
			writer.Write(Encoding.UTF8.GetBytes("SSND"));
			dataSizePos = outStream.Position;
			writer.Write(0);
			writer.Write(0);
			writer.Write(SwapEndian(format.BlockAlign));
		}

		private byte[] SwapEndian(short n)
		{
			return new byte[2]
			{
				(byte)(n >> 8),
				(byte)((uint)n & 0xFFu)
			};
		}

		private byte[] SwapEndian(int n)
		{
			return new byte[4]
			{
				(byte)((uint)(n >> 24) & 0xFFu),
				(byte)((uint)(n >> 16) & 0xFFu),
				(byte)((uint)(n >> 8) & 0xFFu),
				(byte)((uint)n & 0xFFu)
			};
		}

		private void CreateCommChunk()
		{
			writer.Write(Encoding.UTF8.GetBytes("COMM"));
			writer.Write(SwapEndian(18));
			writer.Write(SwapEndian((short)format.Channels));
			commSampleCountPos = outStream.Position;
			writer.Write(0);
			writer.Write(SwapEndian((short)format.BitsPerSample));
			writer.Write(IEEE.ConvertToIeeeExtended(format.SampleRate));
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			throw new InvalidOperationException("Cannot read from an AiffFileWriter");
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new InvalidOperationException("Cannot seek within an AiffFileWriter");
		}

		public override void SetLength(long value)
		{
			throw new InvalidOperationException("Cannot set length of an AiffFileWriter");
		}

		public override void Write(byte[] data, int offset, int count)
		{
			byte[] array = new byte[data.Length];
			int num = format.BitsPerSample / 8;
			for (int i = 0; i < data.Length; i++)
			{
				int num2 = (int)Math.Floor((double)i / (double)num) * num + (num - i % num - 1);
				array[i] = data[num2];
			}
			outStream.Write(array, offset, count);
			dataChunkSize += count;
		}

		public void WriteSample(float sample)
		{
			if (WaveFormat.BitsPerSample == 16)
			{
				writer.Write(SwapEndian((short)(32767f * sample)));
				dataChunkSize += 2L;
			}
			else if (WaveFormat.BitsPerSample == 24)
			{
				byte[] bytes = BitConverter.GetBytes((int)(2.1474836E+09f * sample));
				value24[2] = bytes[1];
				value24[1] = bytes[2];
				value24[0] = bytes[3];
				writer.Write(value24);
				dataChunkSize += 3L;
			}
			else
			{
				if (WaveFormat.BitsPerSample != 32 || WaveFormat.Encoding != WaveFormatEncoding.Extensible)
				{
					throw new InvalidOperationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported");
				}
				writer.Write(SwapEndian(65535 * (int)sample));
				dataChunkSize += 4L;
			}
		}

		public void WriteSamples(float[] samples, int offset, int count)
		{
			for (int i = 0; i < count; i++)
			{
				WriteSample(samples[offset + i]);
			}
		}

		public void WriteSamples(short[] samples, int offset, int count)
		{
			if (WaveFormat.BitsPerSample == 16)
			{
				for (int i = 0; i < count; i++)
				{
					writer.Write(SwapEndian(samples[i + offset]));
				}
				dataChunkSize += count * 2;
			}
			else if (WaveFormat.BitsPerSample == 24)
			{
				for (int j = 0; j < count; j++)
				{
					byte[] bytes = BitConverter.GetBytes(65535 * samples[j + offset]);
					value24[2] = bytes[1];
					value24[1] = bytes[2];
					value24[0] = bytes[3];
					writer.Write(value24);
				}
				dataChunkSize += count * 3;
			}
			else
			{
				if (WaveFormat.BitsPerSample != 32 || WaveFormat.Encoding != WaveFormatEncoding.Extensible)
				{
					throw new InvalidOperationException("Only 16, 24 or 32 bit PCM audio data supported");
				}
				for (int k = 0; k < count; k++)
				{
					writer.Write(SwapEndian(65535 * samples[k + offset]));
				}
				dataChunkSize += count * 4;
			}
		}

		public override void Flush()
		{
			writer.Flush();
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && outStream != null)
			{
				try
				{
					UpdateHeader(writer);
				}
				finally
				{
					outStream.Dispose();
					outStream = null;
				}
			}
		}

		protected virtual void UpdateHeader(BinaryWriter writer)
		{
			Flush();
			writer.Seek(4, SeekOrigin.Begin);
			writer.Write(SwapEndian((int)(outStream.Length - 8)));
			UpdateCommChunk(writer);
			UpdateSsndChunk(writer);
		}

		private void UpdateCommChunk(BinaryWriter writer)
		{
			writer.Seek((int)commSampleCountPos, SeekOrigin.Begin);
			writer.Write(SwapEndian((int)(dataChunkSize * 8 / format.BitsPerSample / format.Channels)));
		}

		private void UpdateSsndChunk(BinaryWriter writer)
		{
			writer.Seek((int)dataSizePos, SeekOrigin.Begin);
			writer.Write(SwapEndian((int)dataChunkSize));
		}

		~AiffFileWriter()
		{
			Dispose(disposing: false);
		}
	}
	public class BextChunkInfo
	{
		public string Description { get; set; }

		public string Originator { get; set; }

		public string OriginatorReference { get; set; }

		public DateTime OriginationDateTime { get; set; }

		public string OriginationDate => OriginationDateTime.ToString("yyyy-MM-dd");

		public string OriginationTime => OriginationDateTime.ToString("HH:mm:ss");

		public long TimeReference { get; set; }

		public ushort Version => 1;

		public string UniqueMaterialIdentifier { get; set; }

		public byte[] Reserved { get; }

		public string CodingHistory { get; set; }

		public BextChunkInfo()
		{
			Reserved = new byte[190];
		}
	}
	public class BwfWriter : IDisposable
	{
		private readonly WaveFormat format;

		private readonly BinaryWriter writer;

		private readonly long dataChunkSizePosition;

		private long dataLength;

		private bool isDisposed;

		public BwfWriter(string filename, WaveFormat format, BextChunkInfo bextChunkInfo)
		{
			this.format = format;
			writer = new BinaryWriter(File.OpenWrite(filename));
			writer.Write(Encoding.UTF8.GetBytes("RIFF"));
			writer.Write(0);
			writer.Write(Encoding.UTF8.GetBytes("WAVE"));
			writer.Write(Encoding.UTF8.GetBytes("JUNK"));
			writer.Write(28);
			writer.Write(0L);
			writer.Write(0L);
			writer.Write(0L);
			writer.Write(0);
			writer.Write(Encoding.UTF8.GetBytes("bext"));
			byte[] bytes = Encoding.ASCII.GetBytes(bextChunkInfo.CodingHistory ?? "");
			int num = 602 + bytes.Length;
			if (num % 2 != 0)
			{
				num++;
			}
			writer.Write(num);
			_ = writer.BaseStream.Position;
			writer.Write(GetAsBytes(bextChunkInfo.Description, 256));
			writer.Write(GetAsBytes(bextChunkInfo.Originator, 32));
			writer.Write(GetAsBytes(bextChunkInfo.OriginatorReference, 32));
			writer.Write(GetAsBytes(bextChunkInfo.OriginationDate, 10));
			writer.Write(GetAsBytes(bextChunkInfo.OriginationTime, 8));
			writer.Write(bextChunkInfo.TimeReference);
			writer.Write(bextChunkInfo.Version);
			writer.Write(GetAsBytes(bextChunkInfo.UniqueMaterialIdentifier, 64));
			writer.Write(bextChunkInfo.Reserved);
			writer.Write(bytes);
			if (bytes.Length % 2 != 0)
			{
				writer.Write((byte)0);
			}
			writer.Write(Encoding.UTF8.GetBytes("fmt "));
			format.Serialize(writer);
			writer.Write(Encoding.UTF8.GetBytes("data"));
			dataChunkSizePosition = writer.BaseStream.Position;
			writer.Write(-1);
		}

		public void Write(byte[] buffer, int offset, int count)
		{
			if (isDisposed)
			{
				throw new ObjectDisposedException("This BWF Writer already disposed");
			}
			writer.Write(buffer, offset, count);
			dataLength += count;
		}

		public void Flush()
		{
			if (isDisposed)
			{
				throw new ObjectDisposedException("This BWF Writer already disposed");
			}
			writer.Flush();
			FixUpChunkSizes(restorePosition: true);
		}

		private void FixUpChunkSizes(bool restorePosition)
		{
			long position = writer.BaseStream.Position;
			bool num = dataLength > int.MaxValue;
			long num2 = writer.BaseStream.Length - 8;
			if (num)
			{
				int num3 = format.BitsPerSample / 8 * format.Channels;
				writer.BaseStream.Position = 0L;
				writer.Write(Encoding.UTF8.GetBytes("RF64"));
				writer.Write(-1);
				writer.BaseStream.Position += 4L;
				writer.Write(Encoding.UTF8.GetBytes("ds64"));
				writer.BaseStream.Position += 4L;
				writer.Write(num2);
				writer.Write(dataLength);
				writer.Write(dataLength / num3);
			}
			else
			{
				writer.BaseStream.Position = 4L;
				writer.Write((uint)num2);
				writer.BaseStream.Position = dataChunkSizePosition;
				writer.Write((uint)dataLength);
			}
			if (restorePosition)
			{
				writer.BaseStream.Position = position;
			}
		}

		public void Dispose()
		{
			if (!isDisposed)
			{
				FixUpChunkSizes(restorePosition: false);
				writer.Dispose();
				isDisposed = true;
			}
		}

		private static byte[] GetAsBytes(string message, int byteSize)
		{
			byte[] array = new byte[byteSize];
			byte[] bytes = Encoding.ASCII.GetBytes(message ?? "");
			Array.Copy(bytes, array, Math.Min(bytes.Length, byteSize));
			return array;
		}
	}
	public class CueWaveFileWriter : WaveFileWriter
	{
		private CueList cues;

		public CueWaveFileWriter(string fileName, WaveFormat waveFormat)
			: base(fileName, waveFormat)
		{
		}

		public void AddCue(int position, string label)
		{
			if (cues == null)
			{
				cues = new CueList();
			}
			cues.Add(new Cue(position, label));
		}

		private void WriteCues(BinaryWriter w)
		{
			if (cues != null)
			{
				int count = cues.GetRiffChunks().Length;
				w.Seek(0, SeekOrigin.End);
				if (w.BaseStream.Length % 2 == 1)
				{
					w.Write((byte)0);
				}
				w.Write(cues.GetRiffChunks(), 0, count);
				w.Seek(4, SeekOrigin.Begin);
				w.Write((int)(w.BaseStream.Length - 8));
			}
		}

		protected override void UpdateHeader(BinaryWriter writer)
		{
			base.UpdateHeader(writer);
			WriteCues(writer);
		}
	}
	public class DirectSoundOut : IWavePlayer, IDisposable
	{
		[StructLayout(LayoutKind.Sequential, Pack = 2)]
		internal class BufferDescription
		{
			public int dwSize;

			[MarshalAs(UnmanagedType.U4)]
			public DirectSoundBufferCaps dwFlags;

			public uint dwBufferBytes;

			public int dwReserved;

			public IntPtr lpwfxFormat;

			public Guid guidAlgo;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 2)]
		internal class BufferCaps
		{
			public int dwSize;

			public int dwFlags;

			public int dwBufferBytes;

			public int dwUnlockTransferRate;

			public int dwPlayCpuOverhead;
		}

		internal enum DirectSoundCooperativeLevel : uint
		{
			DSSCL_NORMAL = 1u,
			DSSCL_PRIORITY,
			DSSCL_EXCLUSIVE,
			DSSCL_WRITEPRIMARY
		}

		[Flags]
		internal enum DirectSoundPlayFlags : uint
		{
			DSBPLAY_LOOPING = 1u,
			DSBPLAY_LOCHARDWARE = 2u,
			DSBPLAY_LOCSOFTWARE = 4u,
			DSBPLAY_TERMINATEBY_TIME = 8u,
			DSBPLAY_TERMINATEBY_DISTANCE = 0x10u,
			DSBPLAY_TERMINATEBY_PRIORITY = 0x20u
		}

		internal enum DirectSoundBufferLockFlag : uint
		{
			None,
			FromWriteCursor,
			EntireBuffer
		}

		[Flags]
		internal enum DirectSoundBufferStatus : uint
		{
			DSBSTATUS_PLAYING = 1u,
			DSBSTATUS_BUFFERLOST = 2u,
			DSBSTATUS_LOOPING = 4u,
			DSBSTATUS_LOCHARDWARE = 8u,
			DSBSTATUS_LOCSOFTWARE = 0x10u,
			DSBSTATUS_TERMINATED = 0x20u
		}

		[Flags]
		internal enum DirectSoundBufferCaps : uint
		{
			DSBCAPS_PRIMARYBUFFER = 1u,
			DSBCAPS_STATIC = 2u,
			DSBCAPS_LOCHARDWARE = 4u,
			DSBCAPS_LOCSOFTWARE = 8u,
			DSBCAPS_CTRL3D = 0x10u,
			DSBCAPS_CTRLFREQUENCY = 0x20u,
			DSBCAPS_CTRLPAN = 0x40u,
			DSBCAPS_CTRLVOLUME = 0x80u,
			DSBCAPS_CTRLPOSITIONNOTIFY = 0x100u,
			DSBCAPS_CTRLFX = 0x200u,
			DSBCAPS_STICKYFOCUS = 0x4000u,
			DSBCAPS_GLOBALFOCUS = 0x8000u,
			DSBCAPS_GETCURRENTPOSITION2 = 0x10000u,
			DSBCAPS_MUTE3DATMAXDISTANCE = 0x20000u,
			DSBCAPS_LOCDEFER = 0x40000u
		}

		internal struct DirectSoundBufferPositionNotify
		{
			public uint dwOffset;

			public IntPtr hEventNotify;
		}

		[ComImport]
		[Guid("279AFA83-4981-11CE-A521-0020AF0BE560")]
		[SuppressUnmanagedCodeSecurity]
		[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
		internal interface IDirectSound
		{
			void CreateSoundBuffer([In] BufferDescription desc, [MarshalAs(UnmanagedType.Interface)] out object dsDSoundBuffer, IntPtr pUnkOuter);

			void GetCaps(IntPtr caps);

			void DuplicateSoundBuffer([In][MarshalAs(UnmanagedType.Interface)] IDirectSoundBuffer bufferOriginal, [In][MarshalAs(UnmanagedType.Interface)] IDirectSoundBuffer bufferDuplicate);

			void SetCooperativeLevel(IntPtr HWND, [In][MarshalAs(UnmanagedType.U4)] DirectSoundCooperativeLevel dwLevel);

			void Compact();

			void GetSpeakerConfig(IntPtr pdwSpeakerConfig);

			void SetSpeakerConfig(uint pdwSpeakerConfig);

			void Initialize([In][MarshalAs(UnmanagedType.LPStruct)] Guid guid);
		}

		[ComImport]
		[Guid("279AFA85-4981-11CE-A521-0020AF0BE560")]
		[SuppressUnmanagedCodeSecurity]
		[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
		internal interface IDirectSoundBuffer
		{
			void GetCaps([MarshalAs(UnmanagedType.LPStruct)] BufferCaps pBufferCaps);

			void GetCurrentPosition(out uint currentPlayCursor, out uint currentWriteCursor);

			void GetFormat();

			[return: MarshalAs(UnmanagedType.I4)]
			int GetVolume();

			void GetPan(out uint pan);

			[return: MarshalAs(UnmanagedType.I4)]
			int GetFrequency();

			[return: MarshalAs(UnmanagedType.U4)]
			DirectSoundBufferStatus GetStatus();

			void Initialize([In][MarshalAs(UnmanagedType.Interface)] IDirectSound directSound, [In] BufferDescription desc);

			void Lock(int dwOffset, uint dwBytes, out IntPtr audioPtr1, out int audioBytes1, out IntPtr audioPtr2, out int audioBytes2, [MarshalAs(UnmanagedType.U4)] DirectSoundBufferLockFlag dwFlags);

			void Play(uint dwReserved1, uint dwPriority, [In][MarshalAs(UnmanagedType.U4)] DirectSoundPlayFlags dwFlags);

			void SetCurrentPosition(uint dwNewPosition);

			void SetFormat([In] WaveFormat pcfxFormat);

			void SetVolume(int volume);

			void SetPan(uint pan);

			void SetFrequency(uint frequency);

			void Stop();

			void Unlock(IntPtr pvAudioPtr1, int dwAudioBytes1, IntPtr pvAudioPtr2, int dwAudioBytes2);

			void Restore();
		}

		[ComImport]
		[Guid("b0210783-89cd-11d0-af08-00a0c925cd16")]
		[SuppressUnmanagedCodeSecurity]
		[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
		internal interface IDirectSoundNotify
		{
			void SetNotificationPositions(uint dwPositionNotifies, [In][MarshalAs(UnmanagedType.LPArray)] DirectSoundBufferPositionNotify[] pcPositionNotifies);
		}

		private delegate bool DSEnumCallback(IntPtr lpGuid, IntPtr lpcstrDescription, IntPtr lpcstrModule, IntPtr lpContext);

		private PlaybackState playbackState;

		private WaveFormat waveFormat;

		private int samplesTotalSize;

		private int samplesFrameSize;

		private int nextSamplesWriteIndex;

		private int desiredLatency;

		private Guid device;

		private byte[] samples;

		private IWaveProvider waveStream;

		private IDirectSound directSound;

		private IDirectSoundBuffer primarySoundBuffer;

		private IDirectSoundBuffer sec

BepInEx/plugins/NAudio.WinMM.dll

Decompiled a month ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using Microsoft.Win32;
using NAudio.CoreAudioApi;
using NAudio.Mixer;
using NAudio.Utils;
using NAudio.Wave.Compression;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("NAudio.WinMM")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Mark Heath 2023")]
[assembly: AssemblyFileVersion("2.2.1.0")]
[assembly: AssemblyInformationalVersion("2.2.1")]
[assembly: AssemblyProduct("NAudio.WinMM")]
[assembly: AssemblyTitle("NAudio.WinMM")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/naudio/NAudio")]
[assembly: AssemblyVersion("2.2.1.0")]
namespace NAudio.Mixer
{
	public class BooleanMixerControl : MixerControl
	{
		private MixerInterop.MIXERCONTROLDETAILS_BOOLEAN boolDetails;

		public bool Value
		{
			get
			{
				GetControlDetails();
				return boolDetails.fValue == 1;
			}
			set
			{
				//IL_0055: Unknown result type (might be due to invalid IL or missing references)
				boolDetails.fValue = (value ? 1 : 0);
				mixerControlDetails.paDetails = Marshal.AllocHGlobal(Marshal.SizeOf(boolDetails));
				Marshal.StructureToPtr(boolDetails, mixerControlDetails.paDetails, fDeleteOld: false);
				MmException.Try(MixerInterop.mixerSetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType), "mixerSetControlDetails");
				Marshal.FreeHGlobal(mixerControlDetails.paDetails);
			}
		}

		internal BooleanMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
			boolDetails = Marshal.PtrToStructure<MixerInterop.MIXERCONTROLDETAILS_BOOLEAN>(pDetails);
		}
	}
	public class CustomMixerControl : MixerControl
	{
		internal CustomMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
		}
	}
	public class ListTextMixerControl : MixerControl
	{
		internal ListTextMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
		}
	}
	public class Mixer
	{
		private MixerInterop.MIXERCAPS caps;

		private IntPtr mixerHandle;

		private MixerFlags mixerHandleType;

		public static int NumberOfDevices => MixerInterop.mixerGetNumDevs();

		public int DestinationCount => (int)caps.cDestinations;

		public string Name => caps.szPname;

		public Manufacturers Manufacturer => (Manufacturers)caps.wMid;

		public int ProductID => caps.wPid;

		public IEnumerable<MixerLine> Destinations
		{
			get
			{
				for (int destination = 0; destination < DestinationCount; destination++)
				{
					yield return GetDestination(destination);
				}
			}
		}

		public static IEnumerable<Mixer> Mixers
		{
			get
			{
				for (int device = 0; device < NumberOfDevices; device++)
				{
					yield return new Mixer(device);
				}
			}
		}

		public Mixer(int mixerIndex)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (mixerIndex < 0 || mixerIndex >= NumberOfDevices)
			{
				throw new ArgumentOutOfRangeException("mixerID");
			}
			caps = default(MixerInterop.MIXERCAPS);
			MmException.Try(MixerInterop.mixerGetDevCaps((IntPtr)mixerIndex, ref caps, Marshal.SizeOf(caps)), "mixerGetDevCaps");
			mixerHandle = (IntPtr)mixerIndex;
			mixerHandleType = MixerFlags.Mixer;
		}

		public MixerLine GetDestination(int destinationIndex)
		{
			if (destinationIndex < 0 || destinationIndex >= DestinationCount)
			{
				throw new ArgumentOutOfRangeException("destinationIndex");
			}
			return new MixerLine(mixerHandle, destinationIndex, mixerHandleType);
		}
	}
	public abstract class MixerControl
	{
		internal MixerInterop.MIXERCONTROL mixerControl;

		internal MixerInterop.MIXERCONTROLDETAILS mixerControlDetails;

		protected IntPtr mixerHandle;

		protected int nChannels;

		protected MixerFlags mixerHandleType;

		public string Name => mixerControl.szName;

		public MixerControlType ControlType => mixerControl.dwControlType;

		public bool IsBoolean => IsControlBoolean(mixerControl.dwControlType);

		public bool IsListText => IsControlListText(mixerControl.dwControlType);

		public bool IsSigned => IsControlSigned(mixerControl.dwControlType);

		public bool IsUnsigned => IsControlUnsigned(mixerControl.dwControlType);

		public bool IsCustom => IsControlCustom(mixerControl.dwControlType);

		public static IList<MixerControl> GetMixerControls(IntPtr mixerHandle, MixerLine mixerLine, MixerFlags mixerHandleType)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			List<MixerControl> list = new List<MixerControl>();
			if (mixerLine.ControlsCount > 0)
			{
				int num = Marshal.SizeOf<MixerInterop.MIXERCONTROL>();
				MixerInterop.MIXERLINECONTROLS mixerLineControls = default(MixerInterop.MIXERLINECONTROLS);
				IntPtr intPtr = Marshal.AllocHGlobal(num * mixerLine.ControlsCount);
				mixerLineControls.cbStruct = Marshal.SizeOf(mixerLineControls);
				mixerLineControls.dwLineID = mixerLine.LineId;
				mixerLineControls.cControls = mixerLine.ControlsCount;
				mixerLineControls.pamxctrl = intPtr;
				mixerLineControls.cbmxctrl = Marshal.SizeOf<MixerInterop.MIXERCONTROL>();
				try
				{
					MmResult val = MixerInterop.mixerGetLineControls(mixerHandle, ref mixerLineControls, MixerFlags.Mixer | mixerHandleType);
					if ((int)val != 0)
					{
						throw new MmException(val, "mixerGetLineControls");
					}
					for (int i = 0; i < mixerLineControls.cControls; i++)
					{
						MixerInterop.MIXERCONTROL mIXERCONTROL = Marshal.PtrToStructure<MixerInterop.MIXERCONTROL>((IntPtr)(intPtr.ToInt64() + num * i));
						MixerControl item = GetMixerControl(mixerHandle, mixerLine.LineId, mIXERCONTROL.dwControlID, mixerLine.Channels, mixerHandleType);
						list.Add(item);
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
				}
			}
			return list;
		}

		public static MixerControl GetMixerControl(IntPtr mixerHandle, int nLineId, int controlId, int nChannels, MixerFlags mixerFlags)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			MixerInterop.MIXERLINECONTROLS mixerLineControls = default(MixerInterop.MIXERLINECONTROLS);
			MixerInterop.MIXERCONTROL structure = default(MixerInterop.MIXERCONTROL);
			IntPtr intPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(structure));
			mixerLineControls.cbStruct = Marshal.SizeOf(mixerLineControls);
			mixerLineControls.cControls = 1;
			mixerLineControls.dwControlID = controlId;
			mixerLineControls.cbmxctrl = Marshal.SizeOf(structure);
			mixerLineControls.pamxctrl = intPtr;
			mixerLineControls.dwLineID = nLineId;
			MmResult val = MixerInterop.mixerGetLineControls(mixerHandle, ref mixerLineControls, MixerFlags.ListText | mixerFlags);
			if ((int)val != 0)
			{
				Marshal.FreeCoTaskMem(intPtr);
				throw new MmException(val, "mixerGetLineControls");
			}
			structure = Marshal.PtrToStructure<MixerInterop.MIXERCONTROL>(mixerLineControls.pamxctrl);
			Marshal.FreeCoTaskMem(intPtr);
			if (IsControlBoolean(structure.dwControlType))
			{
				return new BooleanMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			if (IsControlSigned(structure.dwControlType))
			{
				return new SignedMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			if (IsControlUnsigned(structure.dwControlType))
			{
				return new UnsignedMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			if (IsControlListText(structure.dwControlType))
			{
				return new ListTextMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			if (IsControlCustom(structure.dwControlType))
			{
				return new CustomMixerControl(structure, mixerHandle, mixerFlags, nChannels);
			}
			throw new InvalidOperationException($"Unknown mixer control type {structure.dwControlType}");
		}

		protected void GetControlDetails()
		{
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			mixerControlDetails.cbStruct = Marshal.SizeOf(mixerControlDetails);
			mixerControlDetails.dwControlID = mixerControl.dwControlID;
			if (IsCustom)
			{
				mixerControlDetails.cChannels = 0;
			}
			else if ((mixerControl.fdwControl & (true ? 1u : 0u)) != 0)
			{
				mixerControlDetails.cChannels = 1;
			}
			else
			{
				mixerControlDetails.cChannels = nChannels;
			}
			if ((mixerControl.fdwControl & 2u) != 0)
			{
				mixerControlDetails.hwndOwner = (IntPtr)mixerControl.cMultipleItems;
			}
			else if (IsCustom)
			{
				mixerControlDetails.hwndOwner = IntPtr.Zero;
			}
			else
			{
				mixerControlDetails.hwndOwner = IntPtr.Zero;
			}
			if (IsBoolean)
			{
				mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_BOOLEAN>();
			}
			else if (IsListText)
			{
				mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_LISTTEXT>();
			}
			else if (IsSigned)
			{
				mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_SIGNED>();
			}
			else if (IsUnsigned)
			{
				mixerControlDetails.cbDetails = Marshal.SizeOf<MixerInterop.MIXERCONTROLDETAILS_UNSIGNED>();
			}
			else
			{
				mixerControlDetails.cbDetails = mixerControl.Metrics.customData;
			}
			int num = mixerControlDetails.cbDetails * mixerControlDetails.cChannels;
			if ((mixerControl.fdwControl & 2u) != 0)
			{
				num *= (int)mixerControl.cMultipleItems;
			}
			IntPtr intPtr = Marshal.AllocCoTaskMem(num);
			mixerControlDetails.paDetails = intPtr;
			MmResult val = MixerInterop.mixerGetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType);
			if ((int)val == 0)
			{
				GetDetails(mixerControlDetails.paDetails);
			}
			Marshal.FreeCoTaskMem(intPtr);
			if ((int)val != 0)
			{
				throw new MmException(val, "mixerGetControlDetails");
			}
		}

		protected abstract void GetDetails(IntPtr pDetails);

		private static bool IsControlBoolean(MixerControlType controlType)
		{
			switch (controlType)
			{
			case MixerControlType.BooleanMeter:
			case MixerControlType.Boolean:
			case MixerControlType.OnOff:
			case MixerControlType.Mute:
			case MixerControlType.Mono:
			case MixerControlType.Loudness:
			case MixerControlType.StereoEnhance:
			case MixerControlType.Button:
			case MixerControlType.SingleSelect:
			case MixerControlType.Mux:
			case MixerControlType.MultipleSelect:
			case MixerControlType.Mixer:
				return true;
			default:
				return false;
			}
		}

		private static bool IsControlListText(MixerControlType controlType)
		{
			if (controlType == MixerControlType.Equalizer || (uint)(controlType - 1879113728) <= 1u || (uint)(controlType - 1895890944) <= 1u)
			{
				return true;
			}
			return false;
		}

		private static bool IsControlSigned(MixerControlType controlType)
		{
			switch (controlType)
			{
			case MixerControlType.SignedMeter:
			case MixerControlType.PeakMeter:
			case MixerControlType.Signed:
			case MixerControlType.Decibels:
			case MixerControlType.Slider:
			case MixerControlType.Pan:
			case MixerControlType.QSoundPan:
				return true;
			default:
				return false;
			}
		}

		private static bool IsControlUnsigned(MixerControlType controlType)
		{
			switch (controlType)
			{
			case MixerControlType.UnsignedMeter:
			case MixerControlType.Unsigned:
			case MixerControlType.Percent:
			case MixerControlType.Fader:
			case MixerControlType.Volume:
			case MixerControlType.Bass:
			case MixerControlType.Treble:
			case MixerControlType.Equalizer:
			case MixerControlType.MicroTime:
			case MixerControlType.MilliTime:
				return true;
			default:
				return false;
			}
		}

		private static bool IsControlCustom(MixerControlType controlType)
		{
			return controlType == MixerControlType.Custom;
		}

		public override string ToString()
		{
			return $"{Name} {ControlType}";
		}
	}
	[Flags]
	internal enum MixerControlClass
	{
		Custom = 0,
		Meter = 0x10000000,
		Switch = 0x20000000,
		Number = 0x30000000,
		Slider = 0x40000000,
		Fader = 0x50000000,
		Time = 0x60000000,
		List = 0x70000000,
		Mask = 0x70000000
	}
	[Flags]
	internal enum MixerControlSubclass
	{
		SwitchBoolean = 0,
		SwitchButton = 0x1000000,
		MeterPolled = 0,
		TimeMicrosecs = 0,
		TimeMillisecs = 0x1000000,
		ListSingle = 0,
		ListMultiple = 0x1000000,
		Mask = 0xF000000
	}
	[Flags]
	internal enum MixerControlUnits
	{
		Custom = 0,
		Boolean = 0x10000,
		Signed = 0x20000,
		Unsigned = 0x30000,
		Decibels = 0x40000,
		Percent = 0x50000,
		Mask = 0xFF0000
	}
	public enum MixerControlType
	{
		Custom = 0,
		BooleanMeter = 268500992,
		SignedMeter = 268566528,
		PeakMeter = 268566529,
		UnsignedMeter = 268632064,
		Boolean = 536936448,
		OnOff = 536936449,
		Mute = 536936450,
		Mono = 536936451,
		Loudness = 536936452,
		StereoEnhance = 536936453,
		Button = 553713664,
		Decibels = 805568512,
		Signed = 805437440,
		Unsigned = 805502976,
		Percent = 805634048,
		Slider = 1073872896,
		Pan = 1073872897,
		QSoundPan = 1073872898,
		Fader = 1342373888,
		Volume = 1342373889,
		Bass = 1342373890,
		Treble = 1342373891,
		Equalizer = 1342373892,
		SingleSelect = 1879113728,
		Mux = 1879113729,
		MultipleSelect = 1895890944,
		Mixer = 1895890945,
		MicroTime = 1610809344,
		MilliTime = 1627586560
	}
	[Flags]
	public enum MixerFlags
	{
		Handle = int.MinValue,
		Mixer = 0,
		MixerHandle = int.MinValue,
		WaveOut = 0x10000000,
		WaveOutHandle = -1879048192,
		WaveIn = 0x20000000,
		WaveInHandle = -1610612736,
		MidiOut = 0x30000000,
		MidiOutHandle = -1342177280,
		MidiIn = 0x40000000,
		MidiInHandle = -1073741824,
		Aux = 0x50000000,
		Value = 0,
		ListText = 1,
		QueryMask = 0xF,
		All = 0,
		OneById = 1,
		OneByType = 2,
		GetLineInfoOfDestination = 0,
		GetLineInfoOfSource = 1,
		GetLineInfoOfLineId = 2,
		GetLineInfoOfComponentType = 3,
		GetLineInfoOfTargetType = 4,
		GetLineInfoOfQueryMask = 0xF
	}
	internal class MixerInterop
	{
		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
		public struct MIXERCONTROLDETAILS
		{
			public int cbStruct;

			public int dwControlID;

			public int cChannels;

			public IntPtr hwndOwner;

			public int cbDetails;

			public IntPtr paDetails;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERCAPS
		{
			public ushort wMid;

			public ushort wPid;

			public uint vDriverVersion;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
			public string szPname;

			public uint fdwSupport;

			public uint cDestinations;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERLINECONTROLS
		{
			public int cbStruct;

			public int dwLineID;

			public int dwControlID;

			public int cControls;

			public int cbmxctrl;

			public IntPtr pamxctrl;
		}

		[Flags]
		public enum MIXERLINE_LINEF
		{
			MIXERLINE_LINEF_ACTIVE = 1,
			MIXERLINE_LINEF_DISCONNECTED = 0x8000,
			MIXERLINE_LINEF_SOURCE = int.MinValue
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERLINE
		{
			public int cbStruct;

			public int dwDestination;

			public int dwSource;

			public int dwLineID;

			public MIXERLINE_LINEF fdwLine;

			public IntPtr dwUser;

			public MixerLineComponentType dwComponentType;

			public int cChannels;

			public int cConnections;

			public int cControls;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
			public string szShortName;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
			public string szName;

			public uint dwType;

			public uint dwDeviceID;

			public ushort wMid;

			public ushort wPid;

			public uint vDriverVersion;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
			public string szPname;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct Bounds
		{
			public int minimum;

			public int maximum;

			public int reserved2;

			public int reserved3;

			public int reserved4;

			public int reserved5;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct Metrics
		{
			public int step;

			public int customData;

			public int reserved2;

			public int reserved3;

			public int reserved4;

			public int reserved5;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERCONTROL
		{
			public uint cbStruct;

			public int dwControlID;

			public MixerControlType dwControlType;

			public uint fdwControl;

			public uint cMultipleItems;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
			public string szShortName;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
			public string szName;

			public Bounds Bounds;

			public Metrics Metrics;
		}

		public struct MIXERCONTROLDETAILS_BOOLEAN
		{
			public int fValue;
		}

		public struct MIXERCONTROLDETAILS_SIGNED
		{
			public int lValue;
		}

		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		public struct MIXERCONTROLDETAILS_LISTTEXT
		{
			public uint dwParam1;

			public uint dwParam2;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
			public string szName;
		}

		public struct MIXERCONTROLDETAILS_UNSIGNED
		{
			public uint dwValue;
		}

		public const uint MIXERCONTROL_CONTROLF_UNIFORM = 1u;

		public const uint MIXERCONTROL_CONTROLF_MULTIPLE = 2u;

		public const uint MIXERCONTROL_CONTROLF_DISABLED = 2147483648u;

		public const int MAXPNAMELEN = 32;

		public const int MIXER_SHORT_NAME_CHARS = 16;

		public const int MIXER_LONG_NAME_CHARS = 64;

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern int mixerGetNumDevs();

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerOpen(out IntPtr hMixer, int uMxId, IntPtr dwCallback, IntPtr dwInstance, MixerFlags dwOpenFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerClose(IntPtr hMixer);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetControlDetails(IntPtr hMixer, ref MIXERCONTROLDETAILS mixerControlDetails, MixerFlags dwDetailsFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetDevCaps(IntPtr nMixerID, ref MIXERCAPS mixerCaps, int mixerCapsSize);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetID(IntPtr hMixer, out int mixerID, MixerFlags dwMixerIDFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetLineControls(IntPtr hMixer, ref MIXERLINECONTROLS mixerLineControls, MixerFlags dwControlFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerGetLineInfo(IntPtr hMixer, ref MIXERLINE mixerLine, MixerFlags dwInfoFlags);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerMessage(IntPtr hMixer, uint nMessage, IntPtr dwParam1, IntPtr dwParam2);

		[DllImport("winmm.dll", CharSet = CharSet.Ansi)]
		public static extern MmResult mixerSetControlDetails(IntPtr hMixer, ref MIXERCONTROLDETAILS mixerControlDetails, MixerFlags dwDetailsFlags);
	}
	public class MixerLine
	{
		private MixerInterop.MIXERLINE mixerLine;

		private IntPtr mixerHandle;

		private MixerFlags mixerHandleType;

		public string Name => mixerLine.szName;

		public string ShortName => mixerLine.szShortName;

		public int LineId => mixerLine.dwLineID;

		public MixerLineComponentType ComponentType => mixerLine.dwComponentType;

		public string TypeDescription => mixerLine.dwComponentType switch
		{
			MixerLineComponentType.DestinationUndefined => "Undefined Destination", 
			MixerLineComponentType.DestinationDigital => "Digital Destination", 
			MixerLineComponentType.DestinationLine => "Line Level Destination", 
			MixerLineComponentType.DestinationMonitor => "Monitor Destination", 
			MixerLineComponentType.DestinationSpeakers => "Speakers Destination", 
			MixerLineComponentType.DestinationHeadphones => "Headphones Destination", 
			MixerLineComponentType.DestinationTelephone => "Telephone Destination", 
			MixerLineComponentType.DestinationWaveIn => "Wave Input Destination", 
			MixerLineComponentType.DestinationVoiceIn => "Voice Recognition Destination", 
			MixerLineComponentType.SourceUndefined => "Undefined Source", 
			MixerLineComponentType.SourceDigital => "Digital Source", 
			MixerLineComponentType.SourceLine => "Line Level Source", 
			MixerLineComponentType.SourceMicrophone => "Microphone Source", 
			MixerLineComponentType.SourceSynthesizer => "Synthesizer Source", 
			MixerLineComponentType.SourceCompactDisc => "Compact Disk Source", 
			MixerLineComponentType.SourceTelephone => "Telephone Source", 
			MixerLineComponentType.SourcePcSpeaker => "PC Speaker Source", 
			MixerLineComponentType.SourceWaveOut => "Wave Out Source", 
			MixerLineComponentType.SourceAuxiliary => "Auxiliary Source", 
			MixerLineComponentType.SourceAnalog => "Analog Source", 
			_ => "Invalid Component Type", 
		};

		public int Channels => mixerLine.cChannels;

		public int SourceCount => mixerLine.cConnections;

		public int ControlsCount => mixerLine.cControls;

		public bool IsActive => (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_ACTIVE) != 0;

		public bool IsDisconnected => (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_DISCONNECTED) != 0;

		public bool IsSource => (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_SOURCE) != 0;

		public IEnumerable<MixerControl> Controls => MixerControl.GetMixerControls(mixerHandle, this, mixerHandleType);

		public IEnumerable<MixerLine> Sources
		{
			get
			{
				for (int source = 0; source < SourceCount; source++)
				{
					yield return GetSource(source);
				}
			}
		}

		public string TargetName => mixerLine.szPname;

		public MixerLine(IntPtr mixerHandle, int destinationIndex, MixerFlags mixerHandleType)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			this.mixerHandle = mixerHandle;
			this.mixerHandleType = mixerHandleType;
			mixerLine = default(MixerInterop.MIXERLINE);
			mixerLine.cbStruct = Marshal.SizeOf(mixerLine);
			mixerLine.dwDestination = destinationIndex;
			MmException.Try(MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.Mixer), "mixerGetLineInfo");
		}

		public MixerLine(IntPtr mixerHandle, int destinationIndex, int sourceIndex, MixerFlags mixerHandleType)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			this.mixerHandle = mixerHandle;
			this.mixerHandleType = mixerHandleType;
			mixerLine = default(MixerInterop.MIXERLINE);
			mixerLine.cbStruct = Marshal.SizeOf(mixerLine);
			mixerLine.dwDestination = destinationIndex;
			mixerLine.dwSource = sourceIndex;
			MmException.Try(MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.ListText), "mixerGetLineInfo");
		}

		public static int GetMixerIdForWaveIn(int waveInDevice)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			int mixerID = -1;
			MmException.Try(MixerInterop.mixerGetID((IntPtr)waveInDevice, out mixerID, MixerFlags.WaveIn), "mixerGetID");
			return mixerID;
		}

		public MixerLine GetSource(int sourceIndex)
		{
			if (sourceIndex < 0 || sourceIndex >= SourceCount)
			{
				throw new ArgumentOutOfRangeException("sourceIndex");
			}
			return new MixerLine(mixerHandle, mixerLine.dwDestination, sourceIndex, mixerHandleType);
		}

		public override string ToString()
		{
			return $"{Name} {TypeDescription} ({ControlsCount} controls, ID={mixerLine.dwLineID})";
		}
	}
	public enum MixerLineComponentType
	{
		DestinationUndefined = 0,
		DestinationDigital = 1,
		DestinationLine = 2,
		DestinationMonitor = 3,
		DestinationSpeakers = 4,
		DestinationHeadphones = 5,
		DestinationTelephone = 6,
		DestinationWaveIn = 7,
		DestinationVoiceIn = 8,
		SourceUndefined = 4096,
		SourceDigital = 4097,
		SourceLine = 4098,
		SourceMicrophone = 4099,
		SourceSynthesizer = 4100,
		SourceCompactDisc = 4101,
		SourceTelephone = 4102,
		SourcePcSpeaker = 4103,
		SourceWaveOut = 4104,
		SourceAuxiliary = 4105,
		SourceAnalog = 4106
	}
	public class SignedMixerControl : MixerControl
	{
		private MixerInterop.MIXERCONTROLDETAILS_SIGNED signedDetails;

		public int Value
		{
			get
			{
				GetControlDetails();
				return signedDetails.lValue;
			}
			set
			{
				//IL_0052: Unknown result type (might be due to invalid IL or missing references)
				signedDetails.lValue = value;
				mixerControlDetails.paDetails = Marshal.AllocHGlobal(Marshal.SizeOf(signedDetails));
				Marshal.StructureToPtr(signedDetails, mixerControlDetails.paDetails, fDeleteOld: false);
				MmException.Try(MixerInterop.mixerSetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType), "mixerSetControlDetails");
				Marshal.FreeHGlobal(mixerControlDetails.paDetails);
			}
		}

		public int MinValue => mixerControl.Bounds.minimum;

		public int MaxValue => mixerControl.Bounds.maximum;

		public double Percent
		{
			get
			{
				return 100.0 * (double)(Value - MinValue) / (double)(MaxValue - MinValue);
			}
			set
			{
				Value = (int)((double)MinValue + value / 100.0 * (double)(MaxValue - MinValue));
			}
		}

		internal SignedMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
			signedDetails = Marshal.PtrToStructure<MixerInterop.MIXERCONTROLDETAILS_SIGNED>(mixerControlDetails.paDetails);
		}

		public override string ToString()
		{
			return $"{base.ToString()} {Percent}%";
		}
	}
	public class UnsignedMixerControl : MixerControl
	{
		private MixerInterop.MIXERCONTROLDETAILS_UNSIGNED[] unsignedDetails;

		public uint Value
		{
			get
			{
				GetControlDetails();
				return unsignedDetails[0].dwValue;
			}
			set
			{
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				int num = Marshal.SizeOf(unsignedDetails[0]);
				mixerControlDetails.paDetails = Marshal.AllocHGlobal(num * nChannels);
				for (int i = 0; i < nChannels; i++)
				{
					unsignedDetails[i].dwValue = value;
					long num2 = mixerControlDetails.paDetails.ToInt64() + num * i;
					Marshal.StructureToPtr(unsignedDetails[i], (IntPtr)num2, fDeleteOld: false);
				}
				MmException.Try(MixerInterop.mixerSetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Mixer | mixerHandleType), "mixerSetControlDetails");
				Marshal.FreeHGlobal(mixerControlDetails.paDetails);
			}
		}

		public uint MinValue => (uint)mixerControl.Bounds.minimum;

		public uint MaxValue => (uint)mixerControl.Bounds.maximum;

		public double Percent
		{
			get
			{
				return 100.0 * (double)(Value - MinValue) / (double)(MaxValue - MinValue);
			}
			set
			{
				Value = (uint)((double)MinValue + value / 100.0 * (double)(MaxValue - MinValue));
			}
		}

		internal UnsignedMixerControl(MixerInterop.MIXERCONTROL mixerControl, IntPtr mixerHandle, MixerFlags mixerHandleType, int nChannels)
		{
			base.mixerControl = mixerControl;
			base.mixerHandle = mixerHandle;
			base.mixerHandleType = mixerHandleType;
			base.nChannels = nChannels;
			mixerControlDetails = default(MixerInterop.MIXERCONTROLDETAILS);
			GetControlDetails();
		}

		protected override void GetDetails(IntPtr pDetails)
		{
			unsignedDetails = new MixerInterop.MIXERCONTROLDETAILS_UNSIGNED[nChannels];
			for (int i = 0; i < nChannels; i++)
			{
				unsignedDetails[i] = Marshal.PtrToStructure<MixerInterop.MIXERCONTROLDETAILS_UNSIGNED>(mixerControlDetails.paDetails);
			}
		}

		public override string ToString()
		{
			return $"{base.ToString()} {Percent}%";
		}
	}
}
namespace NAudio.Wave
{
	internal enum AcmMetrics
	{
		CountDrivers = 1,
		CountCodecs = 2,
		CountConverters = 3,
		CountFilters = 4,
		CountDisabled = 5,
		CountHardware = 6,
		CountLocalDrivers = 20,
		CountLocalCodecs = 21,
		CountLocalConverters = 22,
		CountLocalFilters = 23,
		CountLocalDisabled = 24,
		HardwareWaveInput = 30,
		HardwareWaveOutput = 31,
		MaxSizeFormat = 50,
		MaxSizeFilter = 51,
		DriverSupport = 100,
		DriverPriority = 101
	}
	[Flags]
	internal enum AcmStreamConvertFlags
	{
		BlockAlign = 4,
		Start = 0x10,
		End = 0x20
	}
	[StructLayout(LayoutKind.Explicit)]
	public struct MmTime
	{
		public const int TIME_MS = 1;

		public const int TIME_SAMPLES = 2;

		public const int TIME_BYTES = 4;

		[FieldOffset(0)]
		public uint wType;

		[FieldOffset(4)]
		public uint ms;

		[FieldOffset(4)]
		public uint sample;

		[FieldOffset(4)]
		public uint cb;

		[FieldOffset(4)]
		public uint ticks;

		[FieldOffset(4)]
		public byte smpteHour;

		[FieldOffset(5)]
		public byte smpteMin;

		[FieldOffset(6)]
		public byte smpteSec;

		[FieldOffset(7)]
		public byte smpteFrame;

		[FieldOffset(8)]
		public byte smpteFps;

		[FieldOffset(9)]
		public byte smpteDummy;

		[FieldOffset(10)]
		public byte smptePad0;

		[FieldOffset(11)]
		public byte smptePad1;

		[FieldOffset(4)]
		public uint midiSongPtrPos;
	}
	public enum WaveCallbackStrategy
	{
		FunctionCallback,
		NewWindow,
		ExistingWindow,
		Event
	}
	[StructLayout(LayoutKind.Sequential)]
	public sealed class WaveHeader
	{
		public IntPtr dataBuffer;

		public int bufferLength;

		public int bytesRecorded;

		public IntPtr userData;

		public WaveHeaderFlags flags;

		public int loops;

		public IntPtr next;

		public IntPtr reserved;
	}
	[Flags]
	public enum WaveHeaderFlags
	{
		BeginLoop = 4,
		Done = 1,
		EndLoop = 8,
		InQueue = 0x10,
		Prepared = 2
	}
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
	public struct WaveInCapabilities
	{
		private short manufacturerId;

		private short productId;

		private int driverVersion;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		private string productName;

		private SupportedWaveFormat supportedFormats;

		private short channels;

		private short reserved;

		private Guid manufacturerGuid;

		private Guid productGuid;

		private Guid nameGuid;

		private const int MaxProductNameLength = 32;

		public int Channels => channels;

		public string ProductName => productName;

		public Guid NameGuid => nameGuid;

		public Guid ProductGuid => productGuid;

		public Guid ManufacturerGuid => manufacturerGuid;

		public bool SupportsWaveFormat(SupportedWaveFormat waveFormat)
		{
			return (supportedFormats & waveFormat) == waveFormat;
		}
	}
	public static class WaveCapabilitiesHelpers
	{
		public static readonly Guid MicrosoftDefaultManufacturerId = new Guid("d5a47fa8-6d98-11d1-a21a-00a0c9223196");

		public static readonly Guid DefaultWaveOutGuid = new Guid("E36DC310-6D9A-11D1-A21A-00A0C9223196");

		public static readonly Guid DefaultWaveInGuid = new Guid("E36DC311-6D9A-11D1-A21A-00A0C9223196");

		public static string GetNameFromGuid(Guid guid)
		{
			string result = null;
			using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\MediaCategories"))
			{
				using RegistryKey registryKey2 = registryKey.OpenSubKey(guid.ToString("B"));
				if (registryKey2 != null)
				{
					result = registryKey2.GetValue("Name") as string;
				}
			}
			return result;
		}
	}
	public class WaveInterop
	{
		[Flags]
		public enum WaveInOutOpenFlags
		{
			CallbackNull = 0,
			CallbackFunction = 0x30000,
			CallbackEvent = 0x50000,
			CallbackWindow = 0x10000,
			CallbackThread = 0x20000
		}

		public enum WaveMessage
		{
			WaveInOpen = 958,
			WaveInClose = 959,
			WaveInData = 960,
			WaveOutClose = 956,
			WaveOutDone = 957,
			WaveOutOpen = 955
		}

		public delegate void WaveCallback(IntPtr hWaveOut, WaveMessage message, IntPtr dwInstance, WaveHeader wavhdr, IntPtr dwReserved);

		[DllImport("winmm.dll")]
		public static extern int mmioStringToFOURCC([MarshalAs(UnmanagedType.LPStr)] string s, int flags);

		[DllImport("winmm.dll")]
		public static extern int waveOutGetNumDevs();

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutPrepareHeader(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutUnprepareHeader(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutWrite(IntPtr hWaveOut, WaveHeader lpWaveOutHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutOpen(out IntPtr hWaveOut, IntPtr uDeviceID, WaveFormat lpFormat, WaveCallback dwCallback, IntPtr dwInstance, WaveInOutOpenFlags dwFlags);

		[DllImport("winmm.dll", EntryPoint = "waveOutOpen")]
		public static extern MmResult waveOutOpenWindow(out IntPtr hWaveOut, IntPtr uDeviceID, WaveFormat lpFormat, IntPtr callbackWindowHandle, IntPtr dwInstance, WaveInOutOpenFlags dwFlags);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutReset(IntPtr hWaveOut);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutClose(IntPtr hWaveOut);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutPause(IntPtr hWaveOut);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutRestart(IntPtr hWaveOut);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutGetPosition(IntPtr hWaveOut, ref MmTime mmTime, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutSetVolume(IntPtr hWaveOut, int dwVolume);

		[DllImport("winmm.dll")]
		public static extern MmResult waveOutGetVolume(IntPtr hWaveOut, out int dwVolume);

		[DllImport("winmm.dll", CharSet = CharSet.Auto)]
		public static extern MmResult waveOutGetDevCaps(IntPtr deviceID, out WaveOutCapabilities waveOutCaps, int waveOutCapsSize);

		[DllImport("winmm.dll")]
		public static extern int waveInGetNumDevs();

		[DllImport("winmm.dll", CharSet = CharSet.Auto)]
		public static extern MmResult waveInGetDevCaps(IntPtr deviceID, out WaveInCapabilities waveInCaps, int waveInCapsSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInAddBuffer(IntPtr hWaveIn, WaveHeader pwh, int cbwh);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInClose(IntPtr hWaveIn);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInOpen(out IntPtr hWaveIn, IntPtr uDeviceID, WaveFormat lpFormat, WaveCallback dwCallback, IntPtr dwInstance, WaveInOutOpenFlags dwFlags);

		[DllImport("winmm.dll", EntryPoint = "waveInOpen")]
		public static extern MmResult waveInOpenWindow(out IntPtr hWaveIn, IntPtr uDeviceID, WaveFormat lpFormat, IntPtr callbackWindowHandle, IntPtr dwInstance, WaveInOutOpenFlags dwFlags);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInPrepareHeader(IntPtr hWaveIn, WaveHeader lpWaveInHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInUnprepareHeader(IntPtr hWaveIn, WaveHeader lpWaveInHdr, int uSize);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInReset(IntPtr hWaveIn);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInStart(IntPtr hWaveIn);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInStop(IntPtr hWaveIn);

		[DllImport("winmm.dll")]
		public static extern MmResult waveInGetPosition(IntPtr hWaveIn, out MmTime mmTime, int uSize);
	}
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
	public struct WaveOutCapabilities
	{
		private short manufacturerId;

		private short productId;

		private int driverVersion;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		private string productName;

		private SupportedWaveFormat supportedFormats;

		private short channels;

		private short reserved;

		private WaveOutSupport support;

		private Guid manufacturerGuid;

		private Guid productGuid;

		private Guid nameGuid;

		private const int MaxProductNameLength = 32;

		public int Channels => channels;

		public bool SupportsPlaybackRateControl => (support & WaveOutSupport.PlaybackRate) == WaveOutSupport.PlaybackRate;

		public string ProductName => productName;

		public Guid NameGuid => nameGuid;

		public Guid ProductGuid => productGuid;

		public Guid ManufacturerGuid => manufacturerGuid;

		public bool SupportsWaveFormat(SupportedWaveFormat waveFormat)
		{
			return (supportedFormats & waveFormat) == waveFormat;
		}
	}
	[Flags]
	public enum SupportedWaveFormat
	{
		WAVE_FORMAT_1M08 = 1,
		WAVE_FORMAT_1S08 = 2,
		WAVE_FORMAT_1M16 = 4,
		WAVE_FORMAT_1S16 = 8,
		WAVE_FORMAT_2M08 = 0x10,
		WAVE_FORMAT_2S08 = 0x20,
		WAVE_FORMAT_2M16 = 0x40,
		WAVE_FORMAT_2S16 = 0x80,
		WAVE_FORMAT_4M08 = 0x100,
		WAVE_FORMAT_4S08 = 0x200,
		WAVE_FORMAT_4M16 = 0x400,
		WAVE_FORMAT_4S16 = 0x800,
		WAVE_FORMAT_44M08 = 0x100,
		WAVE_FORMAT_44S08 = 0x200,
		WAVE_FORMAT_44M16 = 0x400,
		WAVE_FORMAT_44S16 = 0x800,
		WAVE_FORMAT_48M08 = 0x1000,
		WAVE_FORMAT_48S08 = 0x2000,
		WAVE_FORMAT_48M16 = 0x4000,
		WAVE_FORMAT_48S16 = 0x8000,
		WAVE_FORMAT_96M08 = 0x10000,
		WAVE_FORMAT_96S08 = 0x20000,
		WAVE_FORMAT_96M16 = 0x40000,
		WAVE_FORMAT_96S16 = 0x80000
	}
	[Flags]
	internal enum WaveOutSupport
	{
		Pitch = 1,
		PlaybackRate = 2,
		Volume = 4,
		LRVolume = 8,
		Sync = 0x10,
		SampleAccurate = 0x20
	}
	public class AcmMp3FrameDecompressor : IMp3FrameDecompressor, IDisposable
	{
		private readonly AcmStream conversionStream;

		private readonly WaveFormat pcmFormat;

		private bool disposed;

		public WaveFormat OutputFormat => pcmFormat;

		public AcmMp3FrameDecompressor(WaveFormat sourceFormat)
		{
			pcmFormat = AcmStream.SuggestPcmFormat(sourceFormat);
			try
			{
				conversionStream = new AcmStream(sourceFormat, pcmFormat);
			}
			catch (Exception)
			{
				disposed = true;
				GC.SuppressFinalize(this);
				throw;
			}
		}

		public int DecompressFrame(Mp3Frame frame, byte[] dest, int destOffset)
		{
			if (frame == null)
			{
				throw new ArgumentNullException("frame", "You must provide a non-null Mp3Frame to decompress");
			}
			Array.Copy(frame.RawData, conversionStream.SourceBuffer, frame.FrameLength);
			int sourceBytesConverted;
			int num = conversionStream.Convert(frame.FrameLength, out sourceBytesConverted);
			if (sourceBytesConverted != frame.FrameLength)
			{
				throw new InvalidOperationException($"Couldn't convert the whole MP3 frame (converted {sourceBytesConverted}/{frame.FrameLength})");
			}
			Array.Copy(conversionStream.DestBuffer, 0, dest, destOffset, num);
			return num;
		}

		public void Reset()
		{
			conversionStream.Reposition();
		}

		public void Dispose()
		{
			if (!disposed)
			{
				disposed = true;
				if (conversionStream != null)
				{
					conversionStream.Dispose();
				}
				GC.SuppressFinalize(this);
			}
		}

		~AcmMp3FrameDecompressor()
		{
			Dispose();
		}
	}
	public class WaveFormatConversionProvider : IWaveProvider, IDisposable
	{
		private readonly AcmStream conversionStream;

		private readonly IWaveProvider sourceProvider;

		private readonly int preferredSourceReadSize;

		private int leftoverDestBytes;

		private int leftoverDestOffset;

		private int leftoverSourceBytes;

		private bool isDisposed;

		public WaveFormat WaveFormat { get; }

		public WaveFormatConversionProvider(WaveFormat targetFormat, IWaveProvider sourceProvider)
		{
			this.sourceProvider = sourceProvider;
			WaveFormat = targetFormat;
			conversionStream = new AcmStream(sourceProvider.WaveFormat, targetFormat);
			preferredSourceReadSize = Math.Min(sourceProvider.WaveFormat.AverageBytesPerSecond, conversionStream.SourceBuffer.Length);
			preferredSourceReadSize -= preferredSourceReadSize % sourceProvider.WaveFormat.BlockAlign;
		}

		public void Reposition()
		{
			leftoverDestBytes = 0;
			leftoverDestOffset = 0;
			leftoverSourceBytes = 0;
			conversionStream.Reposition();
		}

		public int Read(byte[] buffer, int offset, int count)
		{
			int i = 0;
			if (count % WaveFormat.BlockAlign != 0)
			{
				count -= count % WaveFormat.BlockAlign;
			}
			int num5;
			for (; i < count; i += num5)
			{
				int num = Math.Min(count - i, leftoverDestBytes);
				if (num > 0)
				{
					Array.Copy(conversionStream.DestBuffer, leftoverDestOffset, buffer, offset + i, num);
					leftoverDestOffset += num;
					leftoverDestBytes -= num;
					i += num;
				}
				if (i >= count)
				{
					break;
				}
				int num2 = Math.Min(preferredSourceReadSize, conversionStream.SourceBuffer.Length - leftoverSourceBytes);
				int num3 = sourceProvider.Read(conversionStream.SourceBuffer, leftoverSourceBytes, num2) + leftoverSourceBytes;
				if (num3 == 0)
				{
					break;
				}
				int sourceBytesConverted;
				int num4 = conversionStream.Convert(num3, out sourceBytesConverted);
				if (sourceBytesConverted == 0)
				{
					break;
				}
				leftoverSourceBytes = num3 - sourceBytesConverted;
				if (leftoverSourceBytes > 0)
				{
					Buffer.BlockCopy(conversionStream.SourceBuffer, sourceBytesConverted, conversionStream.SourceBuffer, 0, leftoverSourceBytes);
				}
				if (num4 <= 0)
				{
					break;
				}
				int val = count - i;
				num5 = Math.Min(num4, val);
				if (num5 < num4)
				{
					leftoverDestBytes = num4 - num5;
					leftoverDestOffset = num5;
				}
				Array.Copy(conversionStream.DestBuffer, 0, buffer, i + offset, num5);
			}
			return i;
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!isDisposed)
			{
				isDisposed = true;
				conversionStream?.Dispose();
			}
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		~WaveFormatConversionProvider()
		{
			Dispose(disposing: false);
		}
	}
	public class WaveFormatConversionStream : WaveStream
	{
		private readonly WaveFormatConversionProvider conversionProvider;

		private readonly WaveFormat targetFormat;

		private readonly long length;

		private long position;

		private readonly WaveStream sourceStream;

		private bool isDisposed;

		public override long Position
		{
			get
			{
				return position;
			}
			set
			{
				value -= value % ((WaveStream)this).BlockAlign;
				long num = EstimateDestToSource(value);
				((Stream)(object)sourceStream).Position = num;
				position = EstimateSourceToDest(((Stream)(object)sourceStream).Position);
				conversionProvider.Reposition();
			}
		}

		public override long Length => length;

		public override WaveFormat WaveFormat => targetFormat;

		public WaveFormatConversionStream(WaveFormat targetFormat, WaveStream sourceStream)
		{
			this.sourceStream = sourceStream;
			this.targetFormat = targetFormat;
			conversionProvider = new WaveFormatConversionProvider(targetFormat, (IWaveProvider)(object)sourceStream);
			length = EstimateSourceToDest((int)((Stream)(object)sourceStream).Length);
			position = 0L;
		}

		public static WaveStream CreatePcmStream(WaveStream sourceStream)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Invalid comparison between Unknown and I4
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between Unknown and I4
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			if ((int)sourceStream.WaveFormat.Encoding == 1)
			{
				return sourceStream;
			}
			WaveFormat val = AcmStream.SuggestPcmFormat(sourceStream.WaveFormat);
			if (val.SampleRate < 8000)
			{
				if ((int)sourceStream.WaveFormat.Encoding != 163)
				{
					throw new InvalidOperationException("Invalid suggested output format, please explicitly provide a target format");
				}
				val = new WaveFormat(8000, 16, 1);
			}
			return (WaveStream)(object)new WaveFormatConversionStream(val, sourceStream);
		}

		[Obsolete("can be unreliable, use of this method not encouraged")]
		public int SourceToDest(int source)
		{
			return (int)EstimateSourceToDest(source);
		}

		private long EstimateSourceToDest(long source)
		{
			long num = source * targetFormat.AverageBytesPerSecond / sourceStream.WaveFormat.AverageBytesPerSecond;
			return num - num % targetFormat.BlockAlign;
		}

		private long EstimateDestToSource(long dest)
		{
			long num = dest * sourceStream.WaveFormat.AverageBytesPerSecond / targetFormat.AverageBytesPerSecond;
			return (int)(num - num % sourceStream.WaveFormat.BlockAlign);
		}

		[Obsolete("can be unreliable, use of this method not encouraged")]
		public int DestToSource(int dest)
		{
			return (int)EstimateDestToSource(dest);
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			int num = conversionProvider.Read(buffer, offset, count);
			position += num;
			return num;
		}

		protected override void Dispose(bool disposing)
		{
			if (!isDisposed)
			{
				isDisposed = true;
				if (disposing)
				{
					((Stream)(object)sourceStream).Dispose();
					conversionProvider.Dispose();
				}
			}
			((Stream)this).Dispose(disposing);
		}
	}
	public class WaveInBuffer : IDisposable
	{
		private readonly WaveHeader header;

		private readonly int bufferSize;

		private readonly byte[] buffer;

		private GCHandle hBuffer;

		private IntPtr waveInHandle;

		private GCHandle hHeader;

		private GCHandle hThis;

		public byte[] Data => buffer;

		public bool Done => (header.flags & WaveHeaderFlags.Done) == WaveHeaderFlags.Done;

		public bool InQueue => (header.flags & WaveHeaderFlags.InQueue) == WaveHeaderFlags.InQueue;

		public int BytesRecorded => header.bytesRecorded;

		public int BufferSize => bufferSize;

		public WaveInBuffer(IntPtr waveInHandle, int bufferSize)
		{
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			this.bufferSize = bufferSize;
			buffer = new byte[bufferSize];
			hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
			this.waveInHandle = waveInHandle;
			header = new WaveHeader();
			hHeader = GCHandle.Alloc(header, GCHandleType.Pinned);
			header.dataBuffer = hBuffer.AddrOfPinnedObject();
			header.bufferLength = bufferSize;
			header.loops = 1;
			hThis = GCHandle.Alloc(this);
			header.userData = (IntPtr)hThis;
			MmException.Try(WaveInterop.waveInPrepareHeader(waveInHandle, header, Marshal.SizeOf(header)), "waveInPrepareHeader");
		}

		public void Reuse()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			MmException.Try(WaveInterop.waveInUnprepareHeader(waveInHandle, header, Marshal.SizeOf(header)), "waveUnprepareHeader");
			MmException.Try(WaveInterop.waveInPrepareHeader(waveInHandle, header, Marshal.SizeOf(header)), "waveInPrepareHeader");
			MmException.Try(WaveInterop.waveInAddBuffer(waveInHandle, header, Marshal.SizeOf(header)), "waveInAddBuffer");
		}

		~WaveInBuffer()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		protected void Dispose(bool disposing)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (waveInHandle != IntPtr.Zero)
			{
				WaveInterop.waveInUnprepareHeader(waveInHandle, header, Marshal.SizeOf(header));
				waveInHandle = IntPtr.Zero;
			}
			if (hHeader.IsAllocated)
			{
				hHeader.Free();
			}
			if (hBuffer.IsAllocated)
			{
				hBuffer.Free();
			}
			if (hThis.IsAllocated)
			{
				hThis.Free();
			}
		}
	}
	public class WaveInEvent : IWaveIn, IDisposable
	{
		private readonly AutoResetEvent callbackEvent;

		private readonly SynchronizationContext syncContext;

		private IntPtr waveInHandle;

		private volatile CaptureState captureState;

		private WaveInBuffer[] buffers;

		public static int DeviceCount => WaveInterop.waveInGetNumDevs();

		public int BufferMilliseconds { get; set; }

		public int NumberOfBuffers { get; set; }

		public int DeviceNumber { get; set; }

		public WaveFormat WaveFormat { get; set; }

		public event EventHandler<WaveInEventArgs> DataAvailable;

		public event EventHandler<StoppedEventArgs> RecordingStopped;

		public WaveInEvent()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			callbackEvent = new AutoResetEvent(initialState: false);
			syncContext = SynchronizationContext.Current;
			DeviceNumber = 0;
			WaveFormat = new WaveFormat(8000, 16, 1);
			BufferMilliseconds = 100;
			NumberOfBuffers = 3;
			captureState = (CaptureState)0;
		}

		public static WaveInCapabilities GetCapabilities(int devNumber)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			WaveInCapabilities waveInCaps = default(WaveInCapabilities);
			int waveInCapsSize = Marshal.SizeOf(waveInCaps);
			MmException.Try(WaveInterop.waveInGetDevCaps((IntPtr)devNumber, out waveInCaps, waveInCapsSize), "waveInGetDevCaps");
			return waveInCaps;
		}

		private void CreateBuffers()
		{
			int num = BufferMilliseconds * WaveFormat.AverageBytesPerSecond / 1000;
			if (num % WaveFormat.BlockAlign != 0)
			{
				num -= num % WaveFormat.BlockAlign;
			}
			buffers = new WaveInBuffer[NumberOfBuffers];
			for (int i = 0; i < buffers.Length; i++)
			{
				buffers[i] = new WaveInBuffer(waveInHandle, num);
			}
		}

		private void OpenWaveInDevice()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			CloseWaveInDevice();
			MmException.Try(WaveInterop.waveInOpenWindow(out waveInHandle, (IntPtr)DeviceNumber, WaveFormat, callbackEvent.SafeWaitHandle.DangerousGetHandle(), IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackEvent), "waveInOpen");
			CreateBuffers();
		}

		public void StartRecording()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			if ((int)captureState != 0)
			{
				throw new InvalidOperationException("Already recording");
			}
			OpenWaveInDevice();
			MmException.Try(WaveInterop.waveInStart(waveInHandle), "waveInStart");
			captureState = (CaptureState)1;
			ThreadPool.QueueUserWorkItem(delegate
			{
				RecordThread();
			}, null);
		}

		private void RecordThread()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Exception e = null;
			try
			{
				DoRecording();
			}
			catch (Exception ex)
			{
				e = ex;
			}
			finally
			{
				captureState = (CaptureState)0;
				RaiseRecordingStoppedEvent(e);
			}
		}

		private void DoRecording()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Invalid comparison between Unknown and I4
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Invalid comparison between Unknown and I4
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			captureState = (CaptureState)2;
			WaveInBuffer[] array = buffers;
			foreach (WaveInBuffer waveInBuffer in array)
			{
				if (!waveInBuffer.InQueue)
				{
					waveInBuffer.Reuse();
				}
			}
			while ((int)captureState == 2)
			{
				if (!callbackEvent.WaitOne())
				{
					continue;
				}
				array = buffers;
				foreach (WaveInBuffer waveInBuffer2 in array)
				{
					if (waveInBuffer2.Done)
					{
						if (waveInBuffer2.BytesRecorded > 0)
						{
							this.DataAvailable?.Invoke(this, new WaveInEventArgs(waveInBuffer2.Data, waveInBuffer2.BytesRecorded));
						}
						if ((int)captureState == 2)
						{
							waveInBuffer2.Reuse();
						}
					}
				}
			}
		}

		private void RaiseRecordingStoppedEvent(Exception e)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			EventHandler<StoppedEventArgs> handler = this.RecordingStopped;
			if (handler == null)
			{
				return;
			}
			if (syncContext == null)
			{
				handler(this, new StoppedEventArgs(e));
				return;
			}
			syncContext.Post(delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				handler(this, new StoppedEventArgs(e));
			}, null);
		}

		public void StopRecording()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			if ((int)captureState != 0)
			{
				captureState = (CaptureState)3;
				MmException.Try(WaveInterop.waveInStop(waveInHandle), "waveInStop");
				MmException.Try(WaveInterop.waveInReset(waveInHandle), "waveInReset");
				callbackEvent.Set();
			}
		}

		public long GetPosition()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			MmTime mmTime = default(MmTime);
			mmTime.wType = 4u;
			MmException.Try(WaveInterop.waveInGetPosition(waveInHandle, out mmTime, Marshal.SizeOf(mmTime)), "waveInGetPosition");
			if (mmTime.wType != 4)
			{
				throw new Exception($"waveInGetPosition: wType -> Expected {4}, Received {mmTime.wType}");
			}
			return mmTime.cb;
		}

		protected virtual void Dispose(bool disposing)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			if (disposing)
			{
				if ((int)captureState != 0)
				{
					StopRecording();
				}
				CloseWaveInDevice();
			}
		}

		private void CloseWaveInDevice()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			WaveInterop.waveInReset(waveInHandle);
			if (buffers != null)
			{
				for (int i = 0; i < buffers.Length; i++)
				{
					buffers[i].Dispose();
				}
				buffers = null;
			}
			WaveInterop.waveInClose(waveInHandle);
			waveInHandle = IntPtr.Zero;
		}

		public MixerLine GetMixerLine()
		{
			if (waveInHandle != IntPtr.Zero)
			{
				return new MixerLine(waveInHandle, 0, MixerFlags.WaveInHandle);
			}
			return new MixerLine((IntPtr)DeviceNumber, 0, MixerFlags.WaveIn);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}
	}
	public class WaveOutBuffer : IDisposable
	{
		private readonly WaveHeader header;

		private readonly int bufferSize;

		private readonly byte[] buffer;

		private readonly IWaveProvider waveStream;

		private readonly object waveOutLock;

		private GCHandle hBuffer;

		private IntPtr hWaveOut;

		private GCHandle hHeader;

		private GCHandle hThis;

		public bool InQueue => (header.flags & WaveHeaderFlags.InQueue) == WaveHeaderFlags.InQueue;

		public int BufferSize => bufferSize;

		public WaveOutBuffer(IntPtr hWaveOut, int bufferSize, IWaveProvider bufferFillStream, object waveOutLock)
		{
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			this.bufferSize = bufferSize;
			buffer = new byte[bufferSize];
			hBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
			this.hWaveOut = hWaveOut;
			waveStream = bufferFillStream;
			this.waveOutLock = waveOutLock;
			header = new WaveHeader();
			hHeader = GCHandle.Alloc(header, GCHandleType.Pinned);
			header.dataBuffer = hBuffer.AddrOfPinnedObject();
			header.bufferLength = bufferSize;
			header.loops = 1;
			hThis = GCHandle.Alloc(this);
			header.userData = (IntPtr)hThis;
			lock (waveOutLock)
			{
				MmException.Try(WaveInterop.waveOutPrepareHeader(hWaveOut, header, Marshal.SizeOf(header)), "waveOutPrepareHeader");
			}
		}

		~WaveOutBuffer()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		protected void Dispose(bool disposing)
		{
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			if (hHeader.IsAllocated)
			{
				hHeader.Free();
			}
			if (hBuffer.IsAllocated)
			{
				hBuffer.Free();
			}
			if (hThis.IsAllocated)
			{
				hThis.Free();
			}
			if (hWaveOut != IntPtr.Zero)
			{
				lock (waveOutLock)
				{
					WaveInterop.waveOutUnprepareHeader(hWaveOut, header, Marshal.SizeOf(header));
				}
				hWaveOut = IntPtr.Zero;
			}
		}

		public bool OnDone()
		{
			int num;
			lock (waveStream)
			{
				num = waveStream.Read(buffer, 0, buffer.Length);
			}
			if (num == 0)
			{
				return false;
			}
			for (int i = num; i < buffer.Length; i++)
			{
				buffer[i] = 0;
			}
			WriteToWaveOut();
			return true;
		}

		private void WriteToWaveOut()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			MmResult val;
			lock (waveOutLock)
			{
				val = WaveInterop.waveOutWrite(hWaveOut, header, Marshal.SizeOf(header));
			}
			if ((int)val != 0)
			{
				throw new MmException(val, "waveOutWrite");
			}
			GC.KeepAlive(this);
		}
	}
	public class WaveOutEvent : IWavePlayer, IDisposable, IWavePosition
	{
		private readonly object waveOutLock;

		private readonly SynchronizationContext syncContext;

		private IntPtr hWaveOut;

		private WaveOutBuffer[] buffers;

		private IWaveProvider waveStream;

		private volatile PlaybackState playbackState;

		private AutoResetEvent callbackEvent;

		public int DesiredLatency { get; set; }

		public int NumberOfBuffers { get; set; }

		public int DeviceNumber { get; set; } = -1;


		public WaveFormat OutputWaveFormat => waveStream.WaveFormat;

		public PlaybackState PlaybackState => playbackState;

		public float Volume
		{
			get
			{
				return WaveOutUtils.GetWaveOutVolume(hWaveOut, waveOutLock);
			}
			set
			{
				WaveOutUtils.SetWaveOutVolume(value, hWaveOut, waveOutLock);
			}
		}

		public event EventHandler<StoppedEventArgs> PlaybackStopped;

		public WaveOutEvent()
		{
			syncContext = SynchronizationContext.Current;
			if (syncContext != null && (syncContext.GetType().Name == "LegacyAspNetSynchronizationContext" || syncContext.GetType().Name == "AspNetSynchronizationContext"))
			{
				syncContext = null;
			}
			DesiredLatency = 300;
			NumberOfBuffers = 2;
			waveOutLock = new object();
		}

		public void Init(IWaveProvider waveProvider)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState != 0)
			{
				throw new InvalidOperationException("Can't re-initialize during playback");
			}
			if (hWaveOut != IntPtr.Zero)
			{
				DisposeBuffers();
				CloseWaveOut();
			}
			callbackEvent = new AutoResetEvent(initialState: false);
			waveStream = waveProvider;
			int bufferSize = waveProvider.WaveFormat.ConvertLatencyToByteSize((DesiredLatency + NumberOfBuffers - 1) / NumberOfBuffers);
			MmResult val;
			lock (waveOutLock)
			{
				val = WaveInterop.waveOutOpenWindow(out hWaveOut, (IntPtr)DeviceNumber, waveStream.WaveFormat, callbackEvent.SafeWaitHandle.DangerousGetHandle(), IntPtr.Zero, WaveInterop.WaveInOutOpenFlags.CallbackEvent);
			}
			MmException.Try(val, "waveOutOpen");
			buffers = new WaveOutBuffer[NumberOfBuffers];
			playbackState = (PlaybackState)0;
			for (int i = 0; i < NumberOfBuffers; i++)
			{
				buffers[i] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock);
			}
		}

		public void Play()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Invalid comparison between Unknown and I4
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (buffers == null || waveStream == null)
			{
				throw new InvalidOperationException("Must call Init first");
			}
			if ((int)playbackState == 0)
			{
				playbackState = (PlaybackState)1;
				callbackEvent.Set();
				ThreadPool.QueueUserWorkItem(delegate
				{
					PlaybackThread();
				}, null);
			}
			else if ((int)playbackState == 2)
			{
				Resume();
				callbackEvent.Set();
			}
		}

		private void PlaybackThread()
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			Exception e = null;
			try
			{
				DoPlayback();
			}
			catch (Exception ex)
			{
				e = ex;
			}
			finally
			{
				playbackState = (PlaybackState)0;
				RaisePlaybackStoppedEvent(e);
			}
		}

		private void DoPlayback()
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			while ((int)playbackState != 0)
			{
				if (!callbackEvent.WaitOne(DesiredLatency))
				{
					_ = playbackState;
					_ = 1;
				}
				if ((int)playbackState != 1)
				{
					continue;
				}
				int num = 0;
				WaveOutBuffer[] array = buffers;
				foreach (WaveOutBuffer waveOutBuffer in array)
				{
					if (waveOutBuffer.InQueue || waveOutBuffer.OnDone())
					{
						num++;
					}
				}
				if (num == 0)
				{
					playbackState = (PlaybackState)0;
					callbackEvent.Set();
				}
			}
		}

		public void Pause()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState == 1)
			{
				playbackState = (PlaybackState)2;
				MmResult val;
				lock (waveOutLock)
				{
					val = WaveInterop.waveOutPause(hWaveOut);
				}
				if ((int)val != 0)
				{
					throw new MmException(val, "waveOutPause");
				}
			}
		}

		private void Resume()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Invalid comparison between Unknown and I4
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState == 2)
			{
				MmResult val;
				lock (waveOutLock)
				{
					val = WaveInterop.waveOutRestart(hWaveOut);
				}
				if ((int)val != 0)
				{
					throw new MmException(val, "waveOutRestart");
				}
				playbackState = (PlaybackState)1;
			}
		}

		public void Stop()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if ((int)playbackState != 0)
			{
				playbackState = (PlaybackState)0;
				MmResult val;
				lock (waveOutLock)
				{
					val = WaveInterop.waveOutReset(hWaveOut);
				}
				if ((int)val != 0)
				{
					throw new MmException(val, "waveOutReset");
				}
				callbackEvent.Set();
			}
		}

		public long GetPosition()
		{
			return WaveOutUtils.GetPositionBytes(hWaveOut, waveOutLock);
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		protected void Dispose(bool disposing)
		{
			Stop();
			if (disposing)
			{
				DisposeBuffers();
			}
			CloseWaveOut();
		}

		private void CloseWaveOut()
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			if (callbackEvent != null)
			{
				callbackEvent.Close();
				callbackEvent = null;
			}
			lock (waveOutLock)
			{
				if (hWaveOut != IntPtr.Zero)
				{
					WaveInterop.waveOutClose(hWaveOut);
					hWaveOut = IntPtr.Zero;
				}
			}
		}

		private void DisposeBuffers()
		{
			if (buffers != null)
			{
				WaveOutBuffer[] array = buffers;
				for (int i = 0; i < array.Length; i++)
				{
					array[i].Dispose();
				}
				buffers = null;
			}
		}

		~WaveOutEvent()
		{
			Dispose(disposing: false);
		}

		private void RaisePlaybackStoppedEvent(Exception e)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			EventHandler<StoppedEventArgs> handler = this.PlaybackStopped;
			if (handler == null)
			{
				return;
			}
			if (syncContext == null)
			{
				handler(this, new StoppedEventArgs(e));
				return;
			}
			syncContext.Post(delegate
			{
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				handler(this, new StoppedEventArgs(e));
			}, null);
		}
	}
	public static class WaveOutUtils
	{
		public static float GetWaveOutVolume(IntPtr hWaveOut, object lockObject)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			MmResult val;
			int dwVolume;
			lock (lockObject)
			{
				val = WaveInterop.waveOutGetVolume(hWaveOut, out dwVolume);
			}
			MmException.Try(val, "waveOutGetVolume");
			return (float)(dwVolume & 0xFFFF) / 65535f;
		}

		public static void SetWaveOutVolume(float value, IntPtr hWaveOut, object lockObject)
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			if (value < 0f)
			{
				throw new ArgumentOutOfRangeException("value", "Volume must be between 0.0 and 1.0");
			}
			if (value > 1f)
			{
				throw new ArgumentOutOfRangeException("value", "Volume must be between 0.0 and 1.0");
			}
			int dwVolume = (int)(value * 65535f) + ((int)(value * 65535f) << 16);
			MmResult val;
			lock (lockObject)
			{
				val = WaveInterop.waveOutSetVolume(hWaveOut, dwVolume);
			}
			MmException.Try(val, "waveOutSetVolume");
		}

		public static long GetPositionBytes(IntPtr hWaveOut, object lockObject)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			lock (lockObject)
			{
				MmTime mmTime = default(MmTime);
				mmTime.wType = 4u;
				MmException.Try(WaveInterop.waveOutGetPosition(hWaveOut, ref mmTime, Marshal.SizeOf(mmTime)), "waveOutGetPosition");
				if (mmTime.wType != 4)
				{
					throw new Exception($"waveOutGetPosition: wType -> Expected {4}, Received {mmTime.wType}");
				}
				return mmTime.cb;
			}
		}
	}
}
namespace NAudio.Wave.Compression
{
	public class AcmDriver : IDisposable
	{
		private static List<AcmDriver> drivers;

		private AcmDriverDetails details;

		private IntPtr driverId;

		private IntPtr driverHandle;

		private List<AcmFormatTag> formatTags;

		private List<AcmFormat> tempFormatsList;

		private IntPtr localDllHandle;

		public int MaxFormatSize
		{
			get
			{
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				MmException.Try(AcmInterop.acmMetrics(driverHandle, AcmMetrics.MaxSizeFormat, out var output), "acmMetrics");
				return output;
			}
		}

		public string ShortName => details.shortName;

		public string LongName => details.longName;

		public IntPtr DriverId => driverId;

		public IEnumerable<AcmFormatTag> FormatTags
		{
			get
			{
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				if (formatTags == null)
				{
					if (driverHandle == IntPtr.Zero)
					{
						throw new InvalidOperationException("Driver must be opened first");
					}
					formatTags = new List<AcmFormatTag>();
					AcmFormatTagDetails formatTagDetails = default(AcmFormatTagDetails);
					formatTagDetails.structureSize = Marshal.SizeOf(formatTagDetails);
					MmException.Try(AcmInterop.acmFormatTagEnum(driverHandle, ref formatTagDetails, AcmFormatTagEnumCallback, IntPtr.Zero, 0), "acmFormatTagEnum");
				}
				return formatTags;
			}
		}

		public static bool IsCodecInstalled(string shortName)
		{
			foreach (AcmDriver item in EnumerateAcmDrivers())
			{
				if (item.ShortName == shortName)
				{
					return true;
				}
			}
			return false;
		}

		public static AcmDriver AddLocalDriver(string driverFile)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			IntPtr intPtr = NativeMethods.LoadLibrary(driverFile);
			if (intPtr == IntPtr.Zero)
			{
				throw new ArgumentException("Failed to load driver file");
			}
			IntPtr procAddress = NativeMethods.GetProcAddress(intPtr, "DriverProc");
			if (procAddress == IntPtr.Zero)
			{
				NativeMethods.FreeLibrary(intPtr);
				throw new ArgumentException("Failed to discover DriverProc");
			}
			IntPtr hAcmDriver;
			MmResult val = AcmInterop.acmDriverAdd(out hAcmDriver, intPtr, procAddress, 0, AcmDriverAddFlags.Function);
			if ((int)val != 0)
			{
				NativeMethods.FreeLibrary(intPtr);
				throw new MmException(val, "acmDriverAdd");
			}
			AcmDriver acmDriver = new AcmDriver(hAcmDriver);
			if (string.IsNullOrEmpty(acmDriver.details.longName))
			{
				acmDriver.details.longName = "Local driver: " + Path.GetFileName(driverFile);
				acmDriver.localDllHandle = intPtr;
			}
			return acmDriver;
		}

		public static void RemoveLocalDriver(AcmDriver localDriver)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (localDriver.localDllHandle == IntPtr.Zero)
			{
				throw new ArgumentException("Please pass in the AcmDriver returned by the AddLocalDriver method");
			}
			MmResult val = AcmInterop.acmDriverRemove(localDriver.driverId, 0);
			NativeMethods.FreeLibrary(localDriver.localDllHandle);
			MmException.Try(val, "acmDriverRemove");
		}

		public static bool ShowFormatChooseDialog(IntPtr ownerWindowHandle, string windowTitle, AcmFormatEnumFlags enumFlags, WaveFormat enumFormat, out WaveFormat selectedFormat, out string selectedFormatDescription, out string selectedFormatTagDescription)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Invalid comparison between Unknown and I4
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Invalid comparison between Unknown and I4
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			AcmFormatChoose formatChoose = default(AcmFormatChoose);
			formatChoose.structureSize = Marshal.SizeOf(formatChoose);
			formatChoose.styleFlags = AcmFormatChooseStyleFlags.None;
			formatChoose.ownerWindowHandle = ownerWindowHandle;
			int num = 200;
			formatChoose.selectedWaveFormatPointer = Marshal.AllocHGlobal(num);
			formatChoose.selectedWaveFormatByteSize = num;
			formatChoose.title = windowTitle;
			formatChoose.name = null;
			formatChoose.formatEnumFlags = enumFlags;
			formatChoose.waveFormatEnumPointer = IntPtr.Zero;
			if (enumFormat != null)
			{
				IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf<WaveFormat>(enumFormat));
				Marshal.StructureToPtr<WaveFormat>(enumFormat, intPtr, fDeleteOld: false);
				formatChoose.waveFormatEnumPointer = intPtr;
			}
			formatChoose.instanceHandle = IntPtr.Zero;
			formatChoose.templateName = null;
			MmResult val = AcmInterop.acmFormatChoose(ref formatChoose);
			selectedFormat = null;
			selectedFormatDescription = null;
			selectedFormatTagDescription = null;
			if ((int)val == 0)
			{
				selectedFormat = WaveFormat.MarshalFromPtr(formatChoose.selectedWaveFormatPointer);
				selectedFormatDescription = formatChoose.formatDescription;
				selectedFormatTagDescription = formatChoose.formatTagDescription;
			}
			Marshal.FreeHGlobal(formatChoose.waveFormatEnumPointer);
			Marshal.FreeHGlobal(formatChoose.selectedWaveFormatPointer);
			if ((int)val != 515 && (int)val != 0)
			{
				throw new MmException(val, "acmFormatChoose");
			}
			return (int)val == 0;
		}

		public static AcmDriver FindByShortName(string shortName)
		{
			foreach (AcmDriver item in EnumerateAcmDrivers())
			{
				if (item.ShortName == shortName)
				{
					return item;
				}
			}
			return null;
		}

		public static IEnumerable<AcmDriver> EnumerateAcmDrivers()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			drivers = new List<AcmDriver>();
			MmException.Try(AcmInterop.acmDriverEnum(DriverEnumCallback, IntPtr.Zero, (AcmDriverEnumFlags)0), "acmDriverEnum");
			return drivers;
		}

		private static bool DriverEnumCallback(IntPtr hAcmDriver, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags)
		{
			drivers.Add(new AcmDriver(hAcmDriver));
			return true;
		}

		private AcmDriver(IntPtr hAcmDriver)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			driverId = hAcmDriver;
			details = default(AcmDriverDetails);
			details.structureSize = Marshal.SizeOf(details);
			MmException.Try(AcmInterop.acmDriverDetails(hAcmDriver, ref details, 0), "acmDriverDetails");
		}

		public override string ToString()
		{
			return LongName;
		}

		public IEnumerable<AcmFormat> GetFormats(AcmFormatTag formatTag)
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected I4, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			if (driverHandle == IntPtr.Zero)
			{
				throw new InvalidOperationException("Driver must be opened first");
			}
			tempFormatsList = new List<AcmFormat>();
			AcmFormatDetails formatDetails = default(AcmFormatDetails);
			formatDetails.structSize = Marshal.SizeOf(formatDetails);
			formatDetails.waveFormatByteSize = 1024;
			formatDetails.waveFormatPointer = Marshal.AllocHGlobal(formatDetails.waveFormatByteSize);
			formatDetails.formatTag = (int)formatTag.FormatTag;
			MmResult val = AcmInterop.acmFormatEnum(driverHandle, ref formatDetails, AcmFormatEnumCallback, IntPtr.Zero, AcmFormatEnumFlags.None);
			Marshal.FreeHGlobal(formatDetails.waveFormatPointer);
			MmException.Try(val, "acmFormatEnum");
			return tempFormatsList;
		}

		public void Open()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			if (driverHandle == IntPtr.Zero)
			{
				MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, DriverId, 0), "acmDriverOpen");
			}
		}

		public void Close()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			if (driverHandle != IntPtr.Zero)
			{
				MmException.Try(AcmInterop.acmDriverClose(driverHandle, 0), "acmDriverClose");
				driverHandle = IntPtr.Zero;
			}
		}

		private bool AcmFormatTagEnumCallback(IntPtr hAcmDriverId, ref AcmFormatTagDetails formatTagDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags)
		{
			formatTags.Add(new AcmFormatTag(formatTagDetails));
			return true;
		}

		private bool AcmFormatEnumCallback(IntPtr hAcmDriverId, ref AcmFormatDetails formatDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags)
		{
			tempFormatsList.Add(new AcmFormat(formatDetails));
			return true;
		}

		public void Dispose()
		{
			if (driverHandle != IntPtr.Zero)
			{
				Close();
				GC.SuppressFinalize(this);
			}
		}
	}
	internal enum AcmDriverAddFlags
	{
		Local = 0,
		Global = 8,
		Function = 3,
		NotifyWindowHandle = 4
	}
	[StructLayout(LayoutKind.Sequential, Pack = 2)]
	internal struct AcmDriverDetails
	{
		public int structureSize;

		public uint fccType;

		public uint fccComp;

		public ushort manufacturerId;

		public ushort productId;

		public uint acmVersion;

		public uint driverVersion;

		public AcmDriverDetailsSupportFlags supportFlags;

		public int formatTagsCount;

		public int filterTagsCount;

		public IntPtr hicon;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
		public string shortName;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string longName;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
		public string copyright;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string licensing;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 512)]
		public string features;

		private const int ShortNameChars = 32;

		private const int LongNameChars = 128;

		private const int CopyrightChars = 80;

		private const int LicensingChars = 128;

		private const int FeaturesChars = 512;
	}
	[Flags]
	public enum AcmDriverDetailsSupportFlags
	{
		Codec = 1,
		Converter = 2,
		Filter = 4,
		Hardware = 8,
		Async = 0x10,
		Local = 0x40000000,
		Disabled = int.MinValue
	}
	[Flags]
	internal enum AcmDriverEnumFlags
	{
		NoLocal = 0x40000000,
		Disabled = int.MinValue
	}
	public class AcmFormat
	{
		private readonly AcmFormatDetails formatDetails;

		public int FormatIndex => formatDetails.formatIndex;

		public WaveFormatEncoding FormatTag => (WaveFormatEncoding)(ushort)formatDetails.formatTag;

		public AcmDriverDetailsSupportFlags SupportFlags => formatDetails.supportFlags;

		public WaveFormat WaveFormat { get; private set; }

		public int WaveFormatByteSize => formatDetails.waveFormatByteSize;

		public string FormatDescription => formatDetails.formatDescription;

		internal AcmFormat(AcmFormatDetails formatDetails)
		{
			this.formatDetails = formatDetails;
			WaveFormat = WaveFormat.MarshalFromPtr(formatDetails.waveFormatPointer);
		}
	}
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
	internal struct AcmFormatChoose
	{
		public int structureSize;

		public AcmFormatChooseStyleFlags styleFlags;

		public IntPtr ownerWindowHandle;

		public IntPtr selectedWaveFormatPointer;

		public int selectedWaveFormatByteSize;

		[MarshalAs(UnmanagedType.LPTStr)]
		public string title;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 48)]
		public string formatTagDescription;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string formatDescription;

		[MarshalAs(UnmanagedType.LPTStr)]
		public string name;

		public int nameByteSize;

		public AcmFormatEnumFlags formatEnumFlags;

		public IntPtr waveFormatEnumPointer;

		public IntPtr instanceHandle;

		[MarshalAs(UnmanagedType.LPTStr)]
		public string templateName;

		public IntPtr customData;

		public AcmInterop.AcmFormatChooseHookProc windowCallbackFunction;
	}
	[Flags]
	internal enum AcmFormatChooseStyleFlags
	{
		None = 0,
		ShowHelp = 4,
		EnableHook = 8,
		EnableTemplate = 0x10,
		EnableTemplateHandle = 0x20,
		InitToWfxStruct = 0x40,
		ContextHelp = 0x80
	}
	[StructLayout(LayoutKind.Sequential, Pack = 4)]
	internal struct AcmFormatDetails
	{
		public int structSize;

		public int formatIndex;

		public int formatTag;

		public AcmDriverDetailsSupportFlags supportFlags;

		public IntPtr waveFormatPointer;

		public int waveFormatByteSize;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
		public string formatDescription;

		public const int FormatDescriptionChars = 128;
	}
	[Flags]
	public enum AcmFormatEnumFlags
	{
		None = 0,
		Convert = 0x100000,
		Hardware = 0x400000,
		Input = 0x800000,
		Channels = 0x20000,
		SamplesPerSecond = 0x40000,
		Output = 0x1000000,
		Suggest = 0x200000,
		BitsPerSample = 0x80000,
		FormatTag = 0x10000
	}
	[Flags]
	internal enum AcmFormatSuggestFlags
	{
		FormatTag = 0x10000,
		Channels = 0x20000,
		SamplesPerSecond = 0x40000,
		BitsPerSample = 0x80000,
		TypeMask = 0xFF0000
	}
	public class AcmFormatTag
	{
		private AcmFormatTagDetails formatTagDetails;

		public int FormatTagIndex => formatTagDetails.formatTagIndex;

		public WaveFormatEncoding FormatTag => (WaveFormatEncoding)(ushort)formatTagDetails.formatTag;

		public int FormatSize => formatTagDetails.formatSize;

		public AcmDriverDetailsSupportFlags SupportFlags => formatTagDetails.supportFlags;

		public int StandardFormatsCount => formatTagDetails.standardFormatsCount;

		public string FormatDescription => formatTagDetails.formatDescription;

		internal AcmFormatTag(AcmFormatTagDetails formatTagDetails)
		{
			this.formatTagDetails = formatTagDetails;
		}
	}
	internal struct AcmFormatTagDetails
	{
		public int structureSize;

		public int formatTagIndex;

		public int formatTag;

		public int formatSize;

		public AcmDriverDetailsSupportFlags supportFlags;

		public int standardFormatsCount;

		[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 48)]
		public string formatDescription;

		public const int FormatTagDescriptionChars = 48;
	}
	internal class AcmInterop
	{
		public delegate bool AcmDriverEnumCallback(IntPtr hAcmDriverId, IntPtr instance, AcmDriverDetailsSupportFlags flags);

		public delegate bool AcmFormatEnumCallback(IntPtr hAcmDriverId, ref AcmFormatDetails formatDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags);

		public delegate bool AcmFormatTagEnumCallback(IntPtr hAcmDriverId, ref AcmFormatTagDetails formatTagDetails, IntPtr dwInstance, AcmDriverDetailsSupportFlags flags);

		public delegate bool AcmFormatChooseHookProc(IntPtr windowHandle, int message, IntPtr wParam, IntPtr lParam);

		[DllImport("msacm32.dll")]
		public static extern MmResult acmDriverAdd(out IntPtr driverHandle, IntPtr driverModule, IntPtr driverFunctionAddress, int priority, AcmDriverAddFlags flags);

		[DllImport("msacm32.dll")]
		public static extern MmResult acmDriverRemove(IntPtr driverHandle, int removeFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmDriverClose(IntPtr hAcmDriver, int closeFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmDriverEnum(AcmDriverEnumCallback fnCallback, IntPtr dwInstance, AcmDriverEnumFlags flags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmDriverDetails(IntPtr hAcmDriver, ref AcmDriverDetails driverDetails, int reserved);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmDriverOpen(out IntPtr pAcmDriver, IntPtr hAcmDriverId, int openFlags);

		[DllImport("Msacm32.dll", EntryPoint = "acmFormatChooseW")]
		public static extern MmResult acmFormatChoose(ref AcmFormatChoose formatChoose);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmFormatEnum(IntPtr hAcmDriver, ref AcmFormatDetails formatDetails, AcmFormatEnumCallback callback, IntPtr instance, AcmFormatEnumFlags flags);

		[DllImport("Msacm32.dll", EntryPoint = "acmFormatSuggest")]
		public static extern MmResult acmFormatSuggest2(IntPtr hAcmDriver, IntPtr sourceFormatPointer, IntPtr destFormatPointer, int sizeDestFormat, AcmFormatSuggestFlags suggestFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmFormatTagEnum(IntPtr hAcmDriver, ref AcmFormatTagDetails formatTagDetails, AcmFormatTagEnumCallback callback, IntPtr instance, int reserved);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmMetrics(IntPtr hAcmObject, AcmMetrics metric, out int output);

		[DllImport("Msacm32.dll", EntryPoint = "acmStreamOpen")]
		public static extern MmResult acmStreamOpen2(out IntPtr hAcmStream, IntPtr hAcmDriver, IntPtr sourceFormatPointer, IntPtr destFormatPointer, [In] WaveFilter waveFilter, IntPtr callback, IntPtr instance, AcmStreamOpenFlags openFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamClose(IntPtr hAcmStream, int closeFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamConvert(IntPtr hAcmStream, [In][Out] AcmStreamHeaderStruct streamHeader, AcmStreamConvertFlags streamConvertFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamPrepareHeader(IntPtr hAcmStream, [In][Out] AcmStreamHeaderStruct streamHeader, int prepareFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamReset(IntPtr hAcmStream, int resetFlags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamSize(IntPtr hAcmStream, int inputBufferSize, out int outputBufferSize, AcmStreamSizeFlags flags);

		[DllImport("Msacm32.dll")]
		public static extern MmResult acmStreamUnprepareHeader(IntPtr hAcmStream, [In][Out] AcmStreamHeaderStruct streamHeader, int flags);
	}
	public class AcmStream : IDisposable
	{
		private IntPtr streamHandle;

		private IntPtr driverHandle;

		private AcmStreamHeader streamHeader;

		private readonly WaveFormat sourceFormat;

		public byte[] SourceBuffer => streamHeader.SourceBuffer;

		public byte[] DestBuffer => streamHeader.DestBuffer;

		public AcmStream(WaveFormat sourceFormat, WaveFormat destFormat)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				streamHandle = IntPtr.Zero;
				this.sourceFormat = sourceFormat;
				int num = Math.Max(65536, sourceFormat.AverageBytesPerSecond);
				num -= num % sourceFormat.BlockAlign;
				IntPtr intPtr = WaveFormat.MarshalToPtr(sourceFormat);
				IntPtr intPtr2 = WaveFormat.MarshalToPtr(destFormat);
				try
				{
					MmException.Try(AcmInterop.acmStreamOpen2(out streamHandle, IntPtr.Zero, intPtr, intPtr2, null, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen");
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
					Marshal.FreeHGlobal(intPtr2);
				}
				int destBufferLength = SourceToDest(num);
				streamHeader = new AcmStreamHeader(streamHandle, num, destBufferLength);
				driverHandle = IntPtr.Zero;
			}
			catch
			{
				Dispose();
				throw;
			}
		}

		public AcmStream(IntPtr driverId, WaveFormat sourceFormat, WaveFilter waveFilter)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			int num = Math.Max(16384, sourceFormat.AverageBytesPerSecond);
			this.sourceFormat = sourceFormat;
			num -= num % sourceFormat.BlockAlign;
			MmException.Try(AcmInterop.acmDriverOpen(out driverHandle, driverId, 0), "acmDriverOpen");
			IntPtr intPtr = WaveFormat.MarshalToPtr(sourceFormat);
			try
			{
				MmException.Try(AcmInterop.acmStreamOpen2(out streamHandle, driverHandle, intPtr, intPtr, waveFilter, IntPtr.Zero, IntPtr.Zero, AcmStreamOpenFlags.NonRealTime), "acmStreamOpen");
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
			streamHeader = new AcmStreamHeader(streamHandle, num, SourceToDest(num));
		}

		public int SourceToDest(int source)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (source == 0)
			{
				return 0;
			}
			MmException.Try(AcmInterop.acmStreamSize(streamHandle, source, out var outputBufferSize, AcmStreamSizeFlags.Source), "acmStreamSize");
			return outputBufferSize;
		}

		public int DestToSource(int dest)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			if (dest == 0)
			{
				return 0;
			}
			MmException.Try(AcmInterop.acmStreamSize(streamHandle, dest, out var outputBufferSize, AcmStreamSizeFlags.Destination), "acmStreamSize");
			return outputBufferSize;
		}

		public static WaveFormat SuggestPcmFormat(WaveFormat compressedFormat)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			WaveFormat val = new WaveFormat(compressedFormat.SampleRate, 16, compressedFormat.Channels);
			IntPtr intPtr = WaveFormat.MarshalToPtr(val);
			IntPtr intPtr2 = WaveFormat.MarshalToPtr(compressedFormat);
			try
			{
				MmResult val2 = AcmInterop.acmFormatSuggest2(IntPtr.Zero, intPtr2, intPtr, Marshal.SizeOf<WaveFormat>(val), AcmFormatSuggestFlags.FormatTag);
				val = WaveFormat.MarshalFromPtr(intPtr);
				MmException.Try(val2, "acmFormatSuggest");
				return val;
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
				Marshal.FreeHGlobal(intPtr2);
			}
		}

		public void Reposition()
		{
			streamHeader.Reposition();
		}

		public int Convert(int bytesToConvert, out int sourceBytesConverted)
		{
			if (bytesToConvert % sourceFormat.BlockAlign != 0)
			{
				bytesToConvert -= bytesToConvert % sourceFormat.BlockAlign;
			}
			return streamHeader.Convert(bytesToConvert, out sourceBytesConverted);
		}

		[Obsolete("Call the version returning sourceBytesConverted instead")]
		public int Convert(int bytesToConvert)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			int sourceBytesConverted;
			int result = Convert(bytesToConvert, out sourceBytesConverted);
			if (sourceBytesConverted != bytesToConvert)
			{
				throw new MmException((MmResult)8, "AcmStreamHeader.Convert didn't convert everything");
			}
			return result;
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			if (disposing && streamHeader != null)
			{
				streamHeader.Dispose();
				streamHeader = null;
			}
			if (streamHandle != IntPtr.Zero)
			{
				MmResult val = AcmInterop.acmStreamClose(streamHandle, 0);
				streamHandle = IntPtr.Zero;
				if ((int)val != 0)
				{
					throw new MmException(val, "acmStreamClose");
				}
			}
			if (driverHandle != IntPtr.Zero)
			{
				AcmInterop.acmDriverClose(driverHandle, 0);
				driverHandle = IntPtr.Zero;
			}
		}

		~AcmStream()
		{
			Dispose(disposing: false);
		}
	}
	internal class AcmStreamHeader : IDisposable
	{
		private AcmStreamHeaderStruct streamHeader;

		private GCHandle hSourceBuffer;

		private GCHandle hDestBuffer;

		private IntPtr streamHandle;

		private bool firstTime;

		private bool disposed;

		public byte[] SourceBuffer { get; private set; }

		public byte[] DestBuffer { get; private set; }

		public AcmStreamHeader(IntPtr streamHandle, int sourceBufferLength, int destBufferLength)
		{
			streamHeader = new AcmStreamHeaderStruct();
			SourceBuffer = new byte[sourceBufferLength];
			hSourceBuffer = GCHandle.Alloc(SourceBuffer, GCHandleType.Pinned);
			DestBuffer = new byte[destBufferLength];
			hDestBuffer = GCHandle.Alloc(DestBuffer, GCHandleType.Pinned);
			this.streamHandle = streamHandle;
			firstTime = true;
		}

		private void Prepare()
		{
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			streamHeader.cbStruct = Marshal.SizeOf(streamHeader);
			streamHeader.sourceBufferLength = SourceBuffer.Length;
			streamHeader.sourceBufferPointer = hSourceBuffer.AddrOfPinnedObject();
			streamHeader.destBufferLength = DestBuffer.Length;
			streamHeader.destBufferPointer = hDestBuffer.AddrOfPinnedObject();
			MmException.Try(AcmInterop.acmStreamPrepareHeader(streamHandle, streamHeader, 0), "acmStreamPrepareHeader");
		}

		private void Unprepare()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			streamHeader.sourceBufferLength = SourceBuffer.Length;
			streamHeader.sourceBufferPointer = hSourceBuffer.AddrOfPinnedObject();
			streamHeader.destBufferLength = DestBuffer.Length;
			streamHeader.destBufferPointer = hDestBuffer.AddrOfPinnedObject();
			MmResult val = AcmInterop.acmStreamUnprepareHeader(streamHandle, streamHeader, 0);
			if ((int)val != 0)
			{
				throw new MmException(val, "acmStreamUnprepareHeader");
			}
		}

		public void Reposition()
		{
			firstTime = true;
		}

		public int Convert(int bytesToConvert, out int sourceBytesConverted)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			Prepare();
			try
			{
				streamHeader.sourceBufferLength = bytesToConvert;
				streamHeader.sourceBufferLengthUsed = bytesToConvert;
				AcmStreamConvertFlags streamConvertFlags = (firstTime ? (AcmStreamConvertFlags.BlockAlign | AcmStreamConvertFlags.Start) : AcmStreamConvertFlags.BlockAlign);
				MmException.Try(AcmInterop.acmStreamConvert(streamHandle, streamHeader, streamConvertFlags), "acmStreamConvert");
				firstTime = false;
				sourceBytesConverted = streamHeader.sourceBufferLengthUsed;
			}
			finally
			{
				Unprepare();
			}
			return streamHeader.destBufferLengthUsed;
		}

		public void Dispose()
		{
			GC.SuppressFinalize(this);
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposed)
			{
				SourceBuffer = null;
				DestBuffer = null;
				hSourceBuffer.Free();
				hDestBuffer.Free();
			}
			disposed = true;
		}

		~AcmStreamHeader()
		{
			Dispose(disposing: false);
		}
	}
	[Flags]
	internal enum AcmStreamHeaderStatusFlags
	{
		Done = 0x10000,
		Prepared = 0x20000,
		InQueue = 0x100000
	}
	[StructLayout(LayoutKind.Sequential, Size = 128)]
	internal class AcmStreamHeaderStruct
	{
		public int cbStruct;

		public AcmStreamHeaderStatusFlags fdwStatus;

		public IntPtr userData;

		public IntPtr sourceBufferPointer;

		public int sourceBufferLength;

		public int sourceBufferLengthUsed;

		public IntPtr sourceUserData;

		public IntPtr destBufferPointer;

		public int destBufferLength;

		public int destBufferLengthUsed;

		public IntPtr destUserData;
	}
	[Flags]
	internal enum AcmStreamOpenFlags
	{
		Query = 1,
		Async = 2,
		NonRealTime = 4,
		CallbackTypeMask = 0x70000,
		CallbackNull = 0,
		CallbackWindow = 0x10000,
		CallbackTask = 0x20000,
		CallbackFunction = 0x30000,
		CallbackThread = 0x20000,
		CallbackEvent = 0x50000
	}
	internal enum AcmStreamSizeFlags
	{
		Source,
		Destination
	}
	[StructLayout(LayoutKind.Sequential)]
	public class WaveFilter
	{
		public int StructureSize = Marshal.SizeOf(typeof(WaveFilter));

		public int FilterTag;

		public int Filter;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
		public int[] Reserved;
	}
}

BepInEx/plugins/NVorbis.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using NVorbis.Contracts;
using NVorbis.Contracts.Ogg;
using NVorbis.Ogg;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Andrew Ward")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © Andrew Ward 2021")]
[assembly: AssemblyDescription("A fully managed implementation of a Xiph.org Foundation Ogg Vorbis decoder.")]
[assembly: AssemblyFileVersion("0.10.5.0")]
[assembly: AssemblyInformationalVersion("0.10.5")]
[assembly: AssemblyProduct("NVorbis")]
[assembly: AssemblyTitle("NVorbis")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/NVorbis/NVorbis")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion("0.10.5.0")]
namespace NVorbis
{
	internal class Codebook : ICodebook
	{
		private class FastRange : IReadOnlyList<int>, IEnumerable<int>, IEnumerable, IReadOnlyCollection<int>
		{
			[ThreadStatic]
			private static FastRange _cachedRange;

			private int _start;

			private int _count;

			public int this[int index]
			{
				get
				{
					if (index > _count)
					{
						throw new ArgumentOutOfRangeException();
					}
					return _start + index;
				}
			}

			public int Count => _count;

			internal static FastRange Get(int start, int count)
			{
				FastRange obj = _cachedRange ?? (_cachedRange = new FastRange());
				obj._start = start;
				obj._count = count;
				return obj;
			}

			private FastRange()
			{
			}

			public IEnumerator<int> GetEnumerator()
			{
				throw new NotSupportedException();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private int[] _lengths;

		private float[] _lookupTable;

		private IReadOnlyList<HuffmanListNode> _overflowList;

		private IReadOnlyList<HuffmanListNode> _prefixList;

		private int _prefixBitLength;

		private int _maxBits;

		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; }

		public void Init(IPacket packet, IHuffman huffman)
		{
			if (packet.ReadBits(24) != 5653314)
			{
				throw new InvalidDataException("Book header had invalid signature!");
			}
			Dimensions = (int)packet.ReadBits(16);
			Entries = (int)packet.ReadBits(24);
			_lengths = new int[Entries];
			InitTree(packet, huffman);
			InitLookupTable(packet);
		}

		private void InitTree(IPacket packet, IHuffman huffman)
		{
			int num = 0;
			bool flag;
			int num5;
			if (packet.ReadBit())
			{
				int num2 = (int)packet.ReadBits(5) + 1;
				int num3 = 0;
				while (num3 < Entries)
				{
					int num4 = (int)packet.ReadBits(Utils.ilog(Entries - num3));
					while (--num4 >= 0)
					{
						_lengths[num3++] = num2;
					}
					num2++;
				}
				num = 0;
				flag = false;
				num5 = num2;
			}
			else
			{
				num5 = -1;
				flag = packet.ReadBit();
				for (int i = 0; i < Entries; i++)
				{
					if (!flag || packet.ReadBit())
					{
						_lengths[i] = (int)packet.ReadBits(5) + 1;
						num++;
					}
					else
					{
						_lengths[i] = -1;
					}
					if (_lengths[i] > num5)
					{
						num5 = _lengths[i];
					}
				}
			}
			if ((_maxBits = num5) > -1)
			{
				int[] array = null;
				if (flag && num >= Entries >> 2)
				{
					array = new int[Entries];
					Array.Copy(_lengths, array, Entries);
					flag = false;
				}
				int num6 = (flag ? num : 0);
				int[] array2 = null;
				int[] array3 = null;
				if (!flag)
				{
					array3 = new int[Entries];
				}
				else if (num6 != 0)
				{
					array = new int[num6];
					array3 = new int[num6];
					array2 = new int[num6];
				}
				if (!ComputeCodewords(flag, array3, array, _lengths, Entries, array2))
				{
					throw new InvalidDataException();
				}
				IReadOnlyList<int> readOnlyList = array2;
				IReadOnlyList<int> value = readOnlyList ?? FastRange.Get(0, array3.Length);
				huffman.GenerateTable(value, array ?? _lengths, array3);
				_prefixList = huffman.PrefixTree;
				_prefixBitLength = huffman.TableBits;
				_overflowList = huffman.OverflowList;
			}
		}

		private bool ComputeCodewords(bool sparse, int[] codewords, int[] codewordLengths, int[] len, int n, int[] values)
		{
			int num = 0;
			uint[] array = new uint[32];
			int i;
			for (i = 0; i < n && len[i] <= 0; i++)
			{
			}
			if (i == n)
			{
				return true;
			}
			AddEntry(sparse, codewords, codewordLengths, 0u, i, num++, len[i], values);
			for (int j = 1; j <= len[i]; j++)
			{
				array[j] = (uint)(1 << 32 - j);
			}
			for (int j = i + 1; j < n; j++)
			{
				int num2 = len[j];
				if (num2 <= 0)
				{
					continue;
				}
				while (num2 > 0 && array[num2] == 0)
				{
					num2--;
				}
				if (num2 == 0)
				{
					return false;
				}
				uint num3 = array[num2];
				array[num2] = 0u;
				AddEntry(sparse, codewords, codewordLengths, Utils.BitReverse(num3), j, num++, len[j], values);
				if (num2 != len[j])
				{
					for (int num4 = len[j]; num4 > num2; num4--)
					{
						array[num4] = num3 + (uint)(1 << 32 - num4);
					}
				}
			}
			return true;
		}

		private 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;
			}
			float num = Utils.ConvertFromVorbisFloat32((uint)packet.ReadBits(32));
			float num2 = Utils.ConvertFromVorbisFloat32((uint)packet.ReadBits(32));
			int count = (int)packet.ReadBits(4) + 1;
			bool flag = packet.ReadBit();
			int num3 = Entries * Dimensions;
			float[] array = new float[num3];
			if (MapType == 1)
			{
				num3 = lookup1_values();
			}
			uint[] array2 = new uint[num3];
			for (int i = 0; i < num3; i++)
			{
				array2[i] = (uint)packet.ReadBits(count);
			}
			if (MapType == 1)
			{
				for (int j = 0; j < Entries; j++)
				{
					double num4 = 0.0;
					int num5 = 1;
					for (int k = 0; k < Dimensions; k++)
					{
						int num6 = j / num5 % num3;
						double num7 = (double)((float)array2[num6] * num2 + num) + num4;
						array[j * Dimensions + k] = (float)num7;
						if (flag)
						{
							num4 = num7;
						}
						num5 *= num3;
					}
				}
			}
			else
			{
				for (int l = 0; l < Entries; l++)
				{
					double num8 = 0.0;
					int num9 = l * Dimensions;
					for (int m = 0; m < Dimensions; m++)
					{
						double num10 = (double)((float)array2[num9] * num2 + num) + num8;
						array[l * Dimensions + m] = (float)num10;
						if (flag)
						{
							num8 = num10;
						}
						num9++;
					}
				}
			}
			_lookupTable = array;
		}

		private int lookup1_values()
		{
			int num = (int)Math.Floor(Math.Exp(Math.Log(Entries) / (double)Dimensions));
			if (Math.Floor(Math.Pow(num + 1, Dimensions)) <= (double)Entries)
			{
				num++;
			}
			return num;
		}

		public int DecodeScalar(IPacket packet)
		{
			int index = (int)packet.TryPeekBits(_prefixBitLength, out var bitsRead);
			if (bitsRead == 0)
			{
				return -1;
			}
			HuffmanListNode huffmanListNode = _prefixList[index];
			if (huffmanListNode != null)
			{
				packet.SkipBits(huffmanListNode.Length);
				return huffmanListNode.Value;
			}
			index = (int)packet.TryPeekBits(_maxBits, out var _);
			for (int i = 0; i < _overflowList.Count; i++)
			{
				huffmanListNode = _overflowList[i];
				if (huffmanListNode.Bits == (index & huffmanListNode.Mask))
				{
					packet.SkipBits(huffmanListNode.Length);
					return huffmanListNode.Value;
				}
			}
			return -1;
		}
	}
	public abstract class DataPacket : IPacket
	{
		[Flags]
		protected enum PacketFlags : byte
		{
			IsResync = 1,
			IsEndOfStream = 2,
			IsShort = 4,
			User0 = 8,
			User1 = 0x10,
			User2 = 0x20,
			User3 = 0x40,
			User4 = 0x80
		}

		private ulong _bitBucket;

		private int _bitCount;

		private byte _overflowBits;

		private PacketFlags _packetFlags;

		private int _readBits;

		public int ContainerOverheadBits { get; set; }

		public long? GranulePosition { get; set; }

		public bool IsResync
		{
			get
			{
				return GetFlag(PacketFlags.IsResync);
			}
			set
			{
				SetFlag(PacketFlags.IsResync, value);
			}
		}

		public bool IsShort
		{
			get
			{
				return GetFlag(PacketFlags.IsShort);
			}
			private set
			{
				SetFlag(PacketFlags.IsShort, value);
			}
		}

		public bool IsEndOfStream
		{
			get
			{
				return GetFlag(PacketFlags.IsEndOfStream);
			}
			set
			{
				SetFlag(PacketFlags.IsEndOfStream, value);
			}
		}

		public int BitsRead => _readBits;

		public int BitsRemaining => TotalBits - _readBits;

		protected abstract int TotalBits { get; }

		private bool GetFlag(PacketFlags flag)
		{
			return _packetFlags.HasFlag(flag);
		}

		private void SetFlag(PacketFlags flag, bool value)
		{
			if (value)
			{
				_packetFlags |= flag;
			}
			else
			{
				_packetFlags &= (PacketFlags)(byte)(~(int)flag);
			}
		}

		protected abstract int ReadNextByte();

		public virtual void Done()
		{
		}

		public virtual void Reset()
		{
			_bitBucket = 0uL;
			_bitCount = 0;
			_overflowBits = 0;
			_readBits = 0;
		}

		ulong IPacket.ReadBits(int count)
		{
			if (count == 0)
			{
				return 0uL;
			}
			int bitsRead;
			ulong result = TryPeekBits(count, out bitsRead);
			SkipBits(count);
			return result;
		}

		public ulong TryPeekBits(int count, out int bitsRead)
		{
			switch (count)
			{
			default:
				throw new ArgumentOutOfRangeException("count");
			case 0:
				bitsRead = 0;
				return 0uL;
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
			case 8:
			case 9:
			case 10:
			case 11:
			case 12:
			case 13:
			case 14:
			case 15:
			case 16:
			case 17:
			case 18:
			case 19:
			case 20:
			case 21:
			case 22:
			case 23:
			case 24:
			case 25:
			case 26:
			case 27:
			case 28:
			case 29:
			case 30:
			case 31:
			case 32:
			case 33:
			case 34:
			case 35:
			case 36:
			case 37:
			case 38:
			case 39:
			case 40:
			case 41:
			case 42:
			case 43:
			case 44:
			case 45:
			case 46:
			case 47:
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
			case 58:
			case 59:
			case 60:
			case 61:
			case 62:
			case 63:
			case 64:
				break;
			}
			while (_bitCount < count)
			{
				int num = ReadNextByte();
				if (num == -1)
				{
					bitsRead = _bitCount;
					return _bitBucket;
				}
				_bitBucket = (ulong)((long)(num & 0xFF) << _bitCount) | _bitBucket;
				_bitCount += 8;
				if (_bitCount > 64)
				{
					_overflowBits = (byte)(num >> 72 - _bitCount);
				}
			}
			ulong num2 = _bitBucket;
			if (count < 64)
			{
				num2 &= (ulong)((1L << count) - 1);
			}
			bitsRead = count;
			return num2;
		}

		public void SkipBits(int count)
		{
			if (count <= 0)
			{
				return;
			}
			if (_bitCount > count)
			{
				if (count > 63)
				{
					_bitBucket = 0uL;
				}
				else
				{
					_bitBucket >>= count;
				}
				if (_bitCount > 64)
				{
					int num = _bitCount - 64;
					_bitBucket |= (ulong)_overflowBits << _bitCount - count - num;
					if (num > count)
					{
						_overflowBits = (byte)(_overflowBits >> count);
					}
				}
				_bitCount -= count;
				_readBits += count;
				return;
			}
			if (_bitCount == count)
			{
				_bitBucket = 0uL;
				_bitCount = 0;
				_readBits += count;
				return;
			}
			count -= _bitCount;
			_readBits += _bitCount;
			_bitCount = 0;
			_bitBucket = 0uL;
			while (count > 8)
			{
				if (ReadNextByte() == -1)
				{
					count = 0;
					IsShort = true;
					break;
				}
				count -= 8;
				_readBits += 8;
			}
			if (count > 0)
			{
				int num2 = ReadNextByte();
				if (num2 == -1)
				{
					IsShort = true;
					return;
				}
				_bitBucket = (ulong)(num2 >> count);
				_bitCount = 8 - count;
				_readBits += count;
			}
		}
	}
	public static class Extensions
	{
		public static int Read(this IPacket packet, byte[] buffer, int index, int count)
		{
			if (index < 0 || index >= buffer.Length)
			{
				throw new ArgumentOutOfRangeException("index");
			}
			if (count < 0 || index + count > buffer.Length)
			{
				throw new ArgumentOutOfRangeException("count");
			}
			for (int i = 0; i < count; i++)
			{
				int bitsRead;
				byte b = (byte)packet.TryPeekBits(8, out bitsRead);
				if (bitsRead == 0)
				{
					return i;
				}
				buffer[index++] = b;
				packet.SkipBits(8);
			}
			return count;
		}

		public static byte[] ReadBytes(this IPacket packet, int count)
		{
			byte[] array = new byte[count];
			int num = packet.Read(array, 0, count);
			if (num < count)
			{
				byte[] array2 = new byte[num];
				Buffer.BlockCopy(array, 0, array2, 0, num);
				return array2;
			}
			return array;
		}

		public static bool ReadBit(this IPacket packet)
		{
			return packet.ReadBits(1) == 1;
		}

		public static byte PeekByte(this IPacket packet)
		{
			int bitsRead;
			return (byte)packet.TryPeekBits(8, out bitsRead);
		}

		public static byte ReadByte(this IPacket packet)
		{
			return (byte)packet.ReadBits(8);
		}

		public static short ReadInt16(this IPacket packet)
		{
			return (short)packet.ReadBits(16);
		}

		public static int ReadInt32(this IPacket packet)
		{
			return (int)packet.ReadBits(32);
		}

		public static long ReadInt64(this IPacket packet)
		{
			return (long)packet.ReadBits(64);
		}

		public static ushort ReadUInt16(this IPacket packet)
		{
			return (ushort)packet.ReadBits(16);
		}

		public static uint ReadUInt32(this IPacket packet)
		{
			return (uint)packet.ReadBits(32);
		}

		public static ulong ReadUInt64(this IPacket packet)
		{
			return packet.ReadBits(64);
		}

		public static void SkipBytes(this IPacket packet, int count)
		{
			packet.SkipBits(count * 8);
		}
	}
	internal 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)
		{
			return (int)packet.ReadBits(16) switch
			{
				0 => new Floor0(), 
				1 => new Floor1(), 
				_ => throw new InvalidDataException("Invalid floor type!"), 
			};
		}

		public IMapping CreateMapping(IPacket packet)
		{
			if (packet.ReadBits(16) != 0L)
			{
				throw new InvalidDataException("Invalid mapping type!");
			}
			return new Mapping();
		}

		public IMode CreateMode()
		{
			return new Mode();
		}

		public IResidue CreateResidue(IPacket packet)
		{
			return (int)packet.ReadBits(16) switch
			{
				0 => new Residue0(), 
				1 => new Residue1(), 
				2 => new Residue2(), 
				_ => throw new InvalidDataException("Invalid residue type!"), 
			};
		}
	}
	internal class Floor0 : IFloor
	{
		private class Data : IFloorData
		{
			internal float[] Coeff;

			internal float Amp;

			public bool ExecuteChannel
			{
				get
				{
					if (ForceEnergy || Amp > 0f)
					{
						return !ForceNoEnergy;
					}
					return false;
				}
			}

			public bool ForceEnergy { get; set; }

			public bool ForceNoEnergy { get; set; }
		}

		private int _order;

		private int _rate;

		private int _bark_map_size;

		private int _ampBits;

		private int _ampOfs;

		private int _ampDiv;

		private ICodebook[] _books;

		private int _bookBits;

		private Dictionary<int, float[]> _wMap;

		private Dictionary<int, int[]> _barkMaps;

		public void Init(IPacket packet, int channels, int block0Size, int block1Size, ICodebook[] codebooks)
		{
			_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++)
			{
				int num = (int)packet.ReadBits(8);
				if (num < 0 || num >= codebooks.Length)
				{
					throw new InvalidDataException();
				}
				ICodebook codebook = codebooks[num];
				if (codebook.MapType == 0 || codebook.Dimensions < 1)
				{
					throw new InvalidDataException();
				}
				_books[i] = codebook;
			}
			_bookBits = Utils.ilog(_books.Length);
			_barkMaps = new Dictionary<int, int[]>
			{
				[block0Size] = SynthesizeBarkCurve(block0Size / 2),
				[block1Size] = SynthesizeBarkCurve(block1Size / 2)
			};
			_wMap = new Dictionary<int, float[]>
			{
				[block0Size] = SynthesizeWDelMap(block0Size / 2),
				[block1Size] = SynthesizeWDelMap(block1Size / 2)
			};
		}

		private int[] SynthesizeBarkCurve(int n)
		{
			float num = (float)_bark_map_size / toBARK(_rate / 2);
			int[] array = new int[n + 1];
			for (int i = 0; i < n - 1; i++)
			{
				array[i] = Math.Min(_bark_map_size - 1, (int)Math.Floor(toBARK((float)_rate / 2f / (float)n * (float)i) * num));
			}
			array[n] = -1;
			return array;
		}

		private static float toBARK(double lsp)
		{
			return (float)(13.1 * Math.Atan(0.00074 * lsp) + 2.24 * Math.Atan(1.85E-08 * lsp * lsp) + 0.0001 * lsp);
		}

		private float[] SynthesizeWDelMap(int n)
		{
			float num = (float)(Math.PI / (double)_bark_map_size);
			float[] array = new float[n];
			for (int i = 0; i < n; i++)
			{
				array[i] = 2f * (float)Math.Cos(num * (float)i);
			}
			return array;
		}

		public IFloorData Unpack(IPacket packet, int blockSize, int channel)
		{
			Data data = new Data
			{
				Coeff = new float[_order + 1]
			};
			data.Amp = packet.ReadBits(_ampBits);
			if (data.Amp > 0f)
			{
				Array.Clear(data.Coeff, 0, data.Coeff.Length);
				data.Amp = data.Amp / (float)_ampDiv * (float)_ampOfs;
				uint num = (uint)packet.ReadBits(_bookBits);
				if (num >= _books.Length)
				{
					data.Amp = 0f;
					return data;
				}
				ICodebook codebook = _books[num];
				int i = 0;
				while (i < _order)
				{
					int num2 = codebook.DecodeScalar(packet);
					if (num2 == -1)
					{
						data.Amp = 0f;
						return data;
					}
					int num3 = 0;
					for (; i < _order; i++)
					{
						if (num3 >= codebook.Dimensions)
						{
							break;
						}
						data.Coeff[i] = codebook[num2, num3];
						num3++;
					}
				}
				float num4 = 0f;
				int num5 = 0;
				while (num5 < _order)
				{
					int num6 = 0;
					while (num5 < _order && num6 < codebook.Dimensions)
					{
						data.Coeff[num5] += num4;
						num5++;
						num6++;
					}
					num4 = data.Coeff[num5 - 1];
				}
			}
			return data;
		}

		public void Apply(IFloorData floorData, int blockSize, float[] residue)
		{
			if (!(floorData is Data data))
			{
				throw new ArgumentException("Incorrect packet data!");
			}
			int num = blockSize / 2;
			if (data.Amp > 0f)
			{
				int[] array = _barkMaps[blockSize];
				float[] array2 = _wMap[blockSize];
				int num2 = 0;
				for (num2 = 0; num2 < _order; num2++)
				{
					data.Coeff[num2] = 2f * (float)Math.Cos(data.Coeff[num2]);
				}
				num2 = 0;
				while (num2 < num)
				{
					int num3 = array[num2];
					float num4 = 0.5f;
					float num5 = 0.5f;
					float num6 = array2[num3];
					int i;
					for (i = 1; i < _order; i += 2)
					{
						num5 *= num6 - data.Coeff[i - 1];
						num4 *= num6 - data.Coeff[i];
					}
					if (i == _order)
					{
						num5 *= num6 - data.Coeff[i - 1];
						num4 *= num4 * (4f - num6 * num6);
						num5 *= num5;
					}
					else
					{
						num4 *= num4 * (2f - num6);
						num5 *= num5 * (2f + num6);
					}
					num5 = data.Amp / (float)Math.Sqrt(num4 + num5) - (float)_ampOfs;
					num5 = (float)Math.Exp(num5 * 0.11512925f);
					residue[num2] *= num5;
					while (array[++num2] == num3)
					{
						residue[num2] *= num5;
					}
				}
			}
			else
			{
				Array.Clear(residue, 0, num);
			}
		}
	}
	internal class Floor1 : IFloor
	{
		private class Data : IFloorData
		{
			internal int[] Posts = new int[64];

			internal int PostCount;

			public bool ExecuteChannel
			{
				get
				{
					if (ForceEnergy || PostCount > 0)
					{
						return !ForceNoEnergy;
					}
					return false;
				}
			}

			public bool ForceEnergy { get; set; }

			public bool ForceNoEnergy { get; set; }
		}

		private int[] _partitionClass;

		private int[] _classDimensions;

		private int[] _classSubclasses;

		private int[] _xList;

		private int[] _classMasterBookIndex;

		private int[] _hNeigh;

		private int[] _lNeigh;

		private int[] _sortIdx;

		private int _multiplier;

		private int _range;

		private int _yBits;

		private ICodebook[] _classMasterbooks;

		private ICodebook[][] _subclassBooks;

		private int[][] _subclassBookIndex;

		private static readonly int[] _rangeLookup = new int[4] { 256, 128, 86, 64 };

		private static readonly int[] _yBitsLookup = new int[4] { 8, 7, 7, 6 };

		private static readonly float[] inverse_dB_table = new float[256]
		{
			1.0649863E-07f, 1.1341951E-07f, 1.2079015E-07f, 1.2863978E-07f, 1.369995E-07f, 1.459025E-07f, 1.5538409E-07f, 1.6548181E-07f, 1.7623574E-07f, 1.8768856E-07f,
			1.998856E-07f, 2.128753E-07f, 2.2670913E-07f, 2.4144197E-07f, 2.5713223E-07f, 2.7384212E-07f, 2.9163792E-07f, 3.1059022E-07f, 3.307741E-07f, 3.5226967E-07f,
			3.7516213E-07f, 3.995423E-07f, 4.255068E-07f, 4.5315863E-07f, 4.8260745E-07f, 5.1397E-07f, 5.4737063E-07f, 5.829419E-07f, 6.208247E-07f, 6.611694E-07f,
			7.041359E-07f, 7.4989464E-07f, 7.98627E-07f, 8.505263E-07f, 9.057983E-07f, 9.646621E-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.053526E-06f, 2.1869757E-06f, 2.3290977E-06f,
			2.4804558E-06f, 2.6416496E-06f, 2.813319E-06f, 2.9961443E-06f, 3.1908505E-06f, 3.39821E-06f, 3.619045E-06f, 3.8542307E-06f, 4.1047006E-06f, 4.371447E-06f,
			4.6555283E-06f, 4.958071E-06f, 5.280274E-06f, 5.623416E-06f, 5.988857E-06f, 6.3780467E-06f, 6.7925284E-06f, 7.2339453E-06f, 7.704048E-06f, 8.2047E-06f,
			8.737888E-06f, 9.305725E-06f, 9.910464E-06f, 1.0554501E-05f, 1.1240392E-05f, 1.1970856E-05f, 1.2748789E-05f, 1.3577278E-05f, 1.4459606E-05f, 1.5399271E-05f,
			1.6400005E-05f, 1.7465769E-05f, 1.8600793E-05f, 1.9809577E-05f, 2.1096914E-05f, 2.2467912E-05f, 2.3928002E-05f, 2.5482977E-05f, 2.7139005E-05f, 2.890265E-05f,
			3.078091E-05f, 3.2781227E-05f, 3.4911533E-05f, 3.718028E-05f, 3.9596467E-05f, 4.2169668E-05f, 4.491009E-05f, 4.7828602E-05f, 5.0936775E-05f, 5.424693E-05f,
			5.7772202E-05f, 6.152657E-05f, 6.552491E-05f, 6.9783084E-05f, 7.4317984E-05f, 7.914758E-05f, 8.429104E-05f, 8.976875E-05f, 9.560242E-05f, 0.00010181521f,
			0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820454f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
			0.00020351382f, 0.0002167393f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881275f, 0.00029693157f, 0.00031622787f, 0.00033677815f, 0.00035866388f,
			0.00038197188f, 0.00040679457f, 0.00043323037f, 0.0004613841f, 0.0004913675f, 0.00052329927f, 0.0005573062f, 0.0005935231f, 0.0006320936f, 0.0006731706f,
			0.000716917f, 0.0007635063f, 0.00081312325f, 0.00086596457f, 0.00092223985f, 0.0009821722f, 0.0010459992f, 0.0011139743f, 0.0011863665f, 0.0012634633f,
			0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632196f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
			0.0025254795f, 0.0026895993f, 0.0028643848f, 0.0030505287f, 0.003248769f, 0.0034598925f, 0.0036847359f, 0.0039241905f, 0.0041792067f, 0.004450795f,
			0.004740033f, 0.005048067f, 0.0053761187f, 0.005725489f, 0.0060975635f, 0.0064938175f, 0.0069158226f, 0.0073652514f, 0.007843887f, 0.008353627f,
			0.008896492f, 0.009474637f, 0.010090352f, 0.01074608f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f,
			0.016697686f, 0.017782796f, 0.018938422f, 0.020169148f, 0.021479854f, 0.022875736f, 0.02436233f, 0.025945531f, 0.027631618f, 0.029427277f,
			0.031339627f, 0.03337625f, 0.035545226f, 0.037855156f, 0.0403152f, 0.042935107f, 0.045725275f, 0.048696756f, 0.05186135f, 0.05523159f,
			0.05882085f, 0.062643364f, 0.06671428f, 0.07104975f, 0.075666964f, 0.08058423f, 0.08582105f, 0.09139818f, 0.097337745f, 0.1036633f,
			0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201812f, 0.15124726f, 0.16107617f, 0.1715438f, 0.18269168f, 0.19456401f,
			0.20720787f, 0.22067343f, 0.23501402f, 0.25028655f, 0.26655158f, 0.28387362f, 0.3023213f, 0.32196787f, 0.34289113f, 0.36517414f,
			0.3889052f, 0.41417846f, 0.44109413f, 0.4697589f, 0.50028646f, 0.53279793f, 0.5674221f, 0.6042964f, 0.64356697f, 0.6853896f,
			0.72993004f, 0.777365f, 0.8278826f, 0.88168305f, 0.9389798f, 1f
		};

		public void Init(IPacket packet, int channels, int block0Size, int block1Size, ICodebook[] codebooks)
		{
			int num = -1;
			_partitionClass = new int[(uint)packet.ReadBits(5)];
			for (int i = 0; i < _partitionClass.Length; i++)
			{
				_partitionClass[i] = (int)packet.ReadBits(4);
				if (_partitionClass[i] > num)
				{
					num = _partitionClass[i];
				}
			}
			_classDimensions = new int[++num];
			_classSubclasses = new int[num];
			_classMasterbooks = new ICodebook[num];
			_classMasterBookIndex = new int[num];
			_subclassBooks = new ICodebook[num][];
			_subclassBookIndex = new int[num][];
			for (int j = 0; j < num; j++)
			{
				_classDimensions[j] = (int)packet.ReadBits(3) + 1;
				_classSubclasses[j] = (int)packet.ReadBits(2);
				if (_classSubclasses[j] > 0)
				{
					_classMasterBookIndex[j] = (int)packet.ReadBits(8);
					_classMasterbooks[j] = codebooks[_classMasterBookIndex[j]];
				}
				_subclassBooks[j] = new ICodebook[1 << _classSubclasses[j]];
				_subclassBookIndex[j] = new int[_subclassBooks[j].Length];
				for (int k = 0; k < _subclassBooks[j].Length; k++)
				{
					int num2 = (int)packet.ReadBits(8) - 1;
					if (num2 >= 0)
					{
						_subclassBooks[j][k] = codebooks[num2];
					}
					_subclassBookIndex[j][k] = num2;
				}
			}
			_multiplier = (int)packet.ReadBits(2);
			_range = _rangeLookup[_multiplier];
			_yBits = _yBitsLookup[_multiplier];
			_multiplier++;
			int num3 = (int)packet.ReadBits(4);
			List<int> list = new List<int>();
			list.Add(0);
			list.Add(1 << num3);
			for (int l = 0; l < _partitionClass.Length; l++)
			{
				int num4 = _partitionClass[l];
				for (int m = 0; m < _classDimensions[num4]; m++)
				{
					list.Add((int)packet.ReadBits(num3));
				}
			}
			_xList = list.ToArray();
			_lNeigh = new int[list.Count];
			_hNeigh = new int[list.Count];
			_sortIdx = new int[list.Count];
			_sortIdx[0] = 0;
			_sortIdx[1] = 1;
			for (int n = 2; n < _lNeigh.Length; n++)
			{
				_lNeigh[n] = 0;
				_hNeigh[n] = 1;
				_sortIdx[n] = n;
				for (int num5 = 2; num5 < n; num5++)
				{
					int num6 = _xList[num5];
					if (num6 < _xList[n])
					{
						if (num6 > _xList[_lNeigh[n]])
						{
							_lNeigh[n] = num5;
						}
					}
					else if (num6 < _xList[_hNeigh[n]])
					{
						_hNeigh[n] = num5;
					}
				}
			}
			for (int num7 = 0; num7 < _sortIdx.Length - 1; num7++)
			{
				for (int num8 = num7 + 1; num8 < _sortIdx.Length; num8++)
				{
					if (_xList[num7] == _xList[num8])
					{
						throw new InvalidDataException();
					}
					if (_xList[_sortIdx[num7]] > _xList[_sortIdx[num8]])
					{
						int num9 = _sortIdx[num7];
						_sortIdx[num7] = _sortIdx[num8];
						_sortIdx[num8] = num9;
					}
				}
			}
		}

		public IFloorData Unpack(IPacket packet, int blockSize, int channel)
		{
			Data data = new Data();
			if (packet.ReadBit())
			{
				int num = 2;
				data.Posts[0] = (int)packet.ReadBits(_yBits);
				data.Posts[1] = (int)packet.ReadBits(_yBits);
				for (int i = 0; i < _partitionClass.Length; i++)
				{
					int num2 = _partitionClass[i];
					int num3 = _classDimensions[num2];
					int num4 = _classSubclasses[num2];
					int num5 = (1 << num4) - 1;
					uint num6 = 0u;
					if (num4 > 0 && (num6 = (uint)_classMasterbooks[num2].DecodeScalar(packet)) == uint.MaxValue)
					{
						num = 0;
						break;
					}
					for (int j = 0; j < num3; j++)
					{
						ICodebook codebook = _subclassBooks[num2][num6 & num5];
						num6 >>= num4;
						if (codebook != null && (data.Posts[num] = codebook.DecodeScalar(packet)) == -1)
						{
							num = 0;
							i = _partitionClass.Length;
							break;
						}
						num++;
					}
				}
				data.PostCount = num;
			}
			return data;
		}

		public void Apply(IFloorData floorData, int blockSize, float[] residue)
		{
			if (!(floorData is Data data))
			{
				throw new ArgumentException("Incorrect packet data!", "packetData");
			}
			int num = blockSize / 2;
			if (data.PostCount > 0)
			{
				bool[] array = UnwrapPosts(data);
				int num2 = 0;
				int num3 = data.Posts[0] * _multiplier;
				for (int i = 1; i < data.PostCount; i++)
				{
					int num4 = _sortIdx[i];
					if (array[num4])
					{
						int num5 = _xList[num4];
						int num6 = data.Posts[num4] * _multiplier;
						if (num2 < num)
						{
							RenderLineMulti(num2, num3, Math.Min(num5, num), num6, residue);
						}
						num2 = num5;
						num3 = num6;
					}
					if (num2 >= num)
					{
						break;
					}
				}
				if (num2 < num)
				{
					RenderLineMulti(num2, num3, num, num3, residue);
				}
			}
			else
			{
				Array.Clear(residue, 0, num);
			}
		}

		private bool[] UnwrapPosts(Data data)
		{
			bool[] array = new bool[64];
			array[0] = true;
			array[1] = true;
			int[] array2 = new int[64];
			array2[0] = data.Posts[0];
			array2[1] = data.Posts[1];
			for (int i = 2; i < data.PostCount; i++)
			{
				int num = _lNeigh[i];
				int num2 = _hNeigh[i];
				int num3 = RenderPoint(_xList[num], array2[num], _xList[num2], array2[num2], _xList[i]);
				int num4 = data.Posts[i];
				int num5 = _range - num3;
				int num6 = num3;
				int num7 = ((num5 >= num6) ? (num6 * 2) : (num5 * 2));
				if (num4 != 0)
				{
					array[num] = true;
					array[num2] = true;
					array[i] = true;
					if (num4 >= num7)
					{
						if (num5 > num6)
						{
							array2[i] = num4 - num6 + num3;
						}
						else
						{
							array2[i] = num3 - num4 + num5 - 1;
						}
					}
					else if (num4 % 2 == 1)
					{
						array2[i] = num3 - (num4 + 1) / 2;
					}
					else
					{
						array2[i] = num3 + num4 / 2;
					}
				}
				else
				{
					array[i] = false;
					array2[i] = num3;
				}
			}
			for (int j = 0; j < data.PostCount; j++)
			{
				data.Posts[j] = array2[j];
			}
			return array;
		}

		private int RenderPoint(int x0, int y0, int x1, int y1, int X)
		{
			int num = y1 - y0;
			int num2 = x1 - x0;
			int num3 = Math.Abs(num) * (X - x0) / num2;
			if (num < 0)
			{
				return y0 - num3;
			}
			return y0 + num3;
		}

		private void RenderLineMulti(int x0, int y0, int x1, int y1, float[] v)
		{
			int num = y1 - y0;
			int num2 = x1 - x0;
			int num3 = Math.Abs(num);
			int num4 = 1 - ((num >> 31) & 1) * 2;
			int num5 = num / num2;
			int num6 = x0;
			int num7 = y0;
			int num8 = -num2;
			v[x0] *= inverse_dB_table[y0];
			num3 -= Math.Abs(num5) * num2;
			while (++num6 < x1)
			{
				num7 += num5;
				num8 += num3;
				if (num8 >= 0)
				{
					num8 -= num2;
					num7 += num4;
				}
				v[num6] *= inverse_dB_table[num7];
			}
		}
	}
	internal class Huffman : IHuffman, IComparer<HuffmanListNode>
	{
		private const int MAX_TABLE_BITS = 10;

		public int TableBits { get; private set; }

		public IReadOnlyList<HuffmanListNode> PrefixTree { get; private set; }

		public IReadOnlyList<HuffmanListNode> OverflowList { get; private set; }

		public void GenerateTable(IReadOnlyList<int> values, int[] lengthList, int[] codeList)
		{
			HuffmanListNode[] array = new HuffmanListNode[lengthList.Length];
			int num = 0;
			for (int i = 0; i < array.Length; i++)
			{
				array[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 && num < lengthList[i])
				{
					num = lengthList[i];
				}
			}
			Array.Sort(array, 0, array.Length, this);
			int num2 = ((num > 10) ? 10 : num);
			List<HuffmanListNode> list = new List<HuffmanListNode>(1 << num2);
			List<HuffmanListNode> list2 = null;
			for (int j = 0; j < array.Length && array[j].Length < 99999; j++)
			{
				int length = array[j].Length;
				if (length > num2)
				{
					list2 = new List<HuffmanListNode>(array.Length - j);
					for (; j < array.Length && array[j].Length < 99999; j++)
					{
						list2.Add(array[j]);
					}
					continue;
				}
				int num3 = 1 << num2 - length;
				HuffmanListNode huffmanListNode = array[j];
				for (int k = 0; k < num3; k++)
				{
					int num4 = (k << length) | huffmanListNode.Bits;
					while (list.Count <= num4)
					{
						list.Add(null);
					}
					list[num4] = huffmanListNode;
				}
			}
			while (list.Count < 1 << num2)
			{
				list.Add(null);
			}
			TableBits = num2;
			PrefixTree = list;
			OverflowList = list2;
		}

		int IComparer<HuffmanListNode>.Compare(HuffmanListNode x, HuffmanListNode y)
		{
			int num = x.Length - y.Length;
			if (num == 0)
			{
				return x.Bits - y.Bits;
			}
			return num;
		}
	}
	[Obsolete("Moved to NVorbis.Contracts.IContainerReader", true)]
	public interface IContainerReader : NVorbis.Contracts.IContainerReader, IDisposable
	{
		[Obsolete("Use Streams.Select(s => s.StreamSerial).ToArray() instead.", true)]
		int[] StreamSerials { get; }

		[Obsolete("No longer supported.", true)]
		int PagesRead { get; }

		[Obsolete("Moved to NewStreamCallback.", true)]
		event EventHandler<NewStreamEventArgs> NewStream;

		[Obsolete("Renamed to TryInit().", true)]
		bool Init();

		[Obsolete("No longer supported.", true)]
		int GetTotalPageCount();
	}
	[Obsolete("Moved to NVorbis.Contracts.IPacketProvider", true)]
	public interface IPacketProvider : NVorbis.Contracts.IPacketProvider
	{
		[Obsolete("Moved to per-stream IStreamStats instance on IStreamDecoder.Stats or VorbisReader.Stats.", true)]
		long ContainerBits { get; }

		[Obsolete("No longer supported.", true)]
		event EventHandler ParameterChange;

		[Obsolete("No longer supported.", true)]
		int GetTotalPageCount();

		[Obsolete("Getting a packet by index is no longer supported.", true)]
		DataPacket GetPacket(int packetIndex);

		[Obsolete("Moved to long SeekTo(long, int, GetPacketGranuleCount)", true)]
		DataPacket FindPacket(long granulePos, Func<DataPacket, DataPacket, int> packetGranuleCountCallback);

		[Obsolete("Seeking to a specified packet is no longer supported.  See SeekTo(...) instead.", true)]
		void SeekToPacket(DataPacket packet, int preRoll);
	}
	[Obsolete("Moved to NVorbis.Contracts.IStreamStats", true)]
	public interface IVorbisStreamStatus : IStreamStats
	{
		[Obsolete("No longer supported.", true)]
		TimeSpan PageLatency { get; }

		[Obsolete("No longer supported.", true)]
		TimeSpan PacketLatency { get; }

		[Obsolete("No longer supported.", true)]
		TimeSpan SecondLatency { get; }

		[Obsolete("No longer supported.", true)]
		int PagesRead { get; }

		[Obsolete("No longer supported.", true)]
		int TotalPages { get; }

		[Obsolete("Use IStreamDecoder.HasClipped instead.  VorbisReader.HasClipped will return the same value for the stream it is handling.", true)]
		bool Clipped { get; }
	}
	internal class Mapping : IMapping
	{
		private IMdct _mdct;

		private int[] _couplingAngle;

		private int[] _couplingMangitude;

		private IFloor[] _submapFloor;

		private IResidue[] _submapResidue;

		private IFloor[] _channelFloor;

		private IResidue[] _channelResidue;

		public void Init(IPacket packet, int channels, IFloor[] floors, IResidue[] residues, IMdct mdct)
		{
			int num = 1;
			if (packet.ReadBit())
			{
				num += (int)packet.ReadBits(4);
			}
			int num2 = 0;
			if (packet.ReadBit())
			{
				num2 = (int)packet.ReadBits(8) + 1;
			}
			int count = Utils.ilog(channels - 1);
			_couplingAngle = new int[num2];
			_couplingMangitude = new int[num2];
			for (int i = 0; i < num2; i++)
			{
				int num3 = (int)packet.ReadBits(count);
				int num4 = (int)packet.ReadBits(count);
				if (num3 == num4 || num3 > channels - 1 || num4 > channels - 1)
				{
					throw new InvalidDataException("Invalid magnitude or angle in mapping header!");
				}
				_couplingAngle[i] = num4;
				_couplingMangitude[i] = num3;
			}
			if (packet.ReadBits(2) != 0L)
			{
				throw new InvalidDataException("Reserved bits not 0 in mapping header.");
			}
			int[] array = new int[channels];
			if (num > 1)
			{
				for (int j = 0; j < channels; j++)
				{
					array[j] = (int)packet.ReadBits(4);
					if (array[j] > num)
					{
						throw new InvalidDataException("Invalid channel mux submap index in mapping header!");
					}
				}
			}
			_submapFloor = new IFloor[num];
			_submapResidue = new IResidue[num];
			for (int k = 0; k < num; k++)
			{
				packet.SkipBits(8);
				int num5 = (int)packet.ReadBits(8);
				if (num5 >= floors.Length)
				{
					throw new InvalidDataException("Invalid floor number in mapping header!");
				}
				int num6 = (int)packet.ReadBits(8);
				if (num6 >= residues.Length)
				{
					throw new InvalidDataException("Invalid residue number in mapping header!");
				}
				_submapFloor[k] = floors[num5];
				_submapResidue[k] = residues[num6];
			}
			_channelFloor = new IFloor[channels];
			_channelResidue = new IResidue[channels];
			for (int l = 0; l < channels; l++)
			{
				_channelFloor[l] = _submapFloor[array[l]];
				_channelResidue[l] = _submapResidue[array[l]];
			}
			_mdct = mdct;
		}

		public void DecodePacket(IPacket packet, int blockSize, int channels, float[][] buffer)
		{
			int num = blockSize >> 1;
			IFloorData[] array = new IFloorData[_channelFloor.Length];
			bool[] array2 = new bool[_channelFloor.Length];
			for (int i = 0; i < _channelFloor.Length; i++)
			{
				array[i] = _channelFloor[i].Unpack(packet, blockSize, i);
				array2[i] = !array[i].ExecuteChannel;
				Array.Clear(buffer[i], 0, num);
			}
			for (int j = 0; j < _couplingAngle.Length; j++)
			{
				if (array[_couplingAngle[j]].ExecuteChannel || array[_couplingMangitude[j]].ExecuteChannel)
				{
					array[_couplingAngle[j]].ForceEnergy = true;
					array[_couplingMangitude[j]].ForceEnergy = true;
				}
			}
			for (int k = 0; k < _submapFloor.Length; k++)
			{
				for (int l = 0; l < _channelFloor.Length; l++)
				{
					if (_submapFloor[k] != _channelFloor[l] || _submapResidue[k] != _channelResidue[l])
					{
						array[l].ForceNoEnergy = true;
					}
				}
				_submapResidue[k].Decode(packet, array2, blockSize, buffer);
			}
			for (int num2 = _couplingAngle.Length - 1; num2 >= 0; num2--)
			{
				if (array[_couplingAngle[num2]].ExecuteChannel || array[_couplingMangitude[num2]].ExecuteChannel)
				{
					float[] array3 = buffer[_couplingMangitude[num2]];
					float[] array4 = buffer[_couplingAngle[num2]];
					for (int m = 0; m < num; m++)
					{
						float num3 = array3[m];
						float num4 = array4[m];
						float num5;
						float num6;
						if (num3 > 0f)
						{
							if (num4 > 0f)
							{
								num5 = num3;
								num6 = num3 - num4;
							}
							else
							{
								num6 = num3;
								num5 = num3 + num4;
							}
						}
						else if (num4 > 0f)
						{
							num5 = num3;
							num6 = num3 + num4;
						}
						else
						{
							num6 = num3;
							num5 = num3 - num4;
						}
						array3[m] = num5;
						array4[m] = num6;
					}
				}
			}
			for (int n = 0; n < _channelFloor.Length; n++)
			{
				if (array[n].ExecuteChannel)
				{
					_channelFloor[n].Apply(array[n], blockSize, buffer[n]);
					_mdct.Reverse(buffer[n], blockSize);
				}
				else
				{
					Array.Clear(buffer[n], num, num);
				}
			}
		}
	}
	internal class Mdct : IMdct
	{
		private class MdctImpl
		{
			private readonly int _n;

			private readonly int _n2;

			private readonly int _n4;

			private readonly int _n8;

			private readonly int _ld;

			private readonly float[] _a;

			private readonly float[] _b;

			private readonly float[] _c;

			private readonly ushort[] _bitrev;

			public MdctImpl(int n)
			{
				_n = n;
				_n2 = n >> 1;
				_n4 = _n2 >> 1;
				_n8 = _n4 >> 1;
				_ld = Utils.ilog(n) - 1;
				_a = new float[_n2];
				_b = new float[_n2];
				_c = new float[_n4];
				int num;
				int num2 = (num = 0);
				while (num2 < _n4)
				{
					_a[num] = (float)Math.Cos((float)(4 * num2) * MathF.PI / (float)n);
					_a[num + 1] = (float)(0.0 - Math.Sin((float)(4 * num2) * MathF.PI / (float)n));
					_b[num] = (float)Math.Cos((float)(num + 1) * MathF.PI / (float)n / 2f) * 0.5f;
					_b[num + 1] = (float)Math.Sin((float)(num + 1) * MathF.PI / (float)n / 2f) * 0.5f;
					num2++;
					num += 2;
				}
				num2 = (num = 0);
				while (num2 < _n8)
				{
					_c[num] = (float)Math.Cos((float)(2 * (num + 1)) * MathF.PI / (float)n);
					_c[num + 1] = (float)(0.0 - Math.Sin((float)(2 * (num + 1)) * MathF.PI / (float)n));
					num2++;
					num += 2;
				}
				_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[] array = new float[_n2];
				int num = _n2 - 2;
				int num2 = 0;
				int i = 0;
				for (int n = _n2; i != n; i += 4)
				{
					array[num + 1] = buffer[i] * _a[num2] - buffer[i + 2] * _a[num2 + 1];
					array[num] = buffer[i] * _a[num2 + 1] + buffer[i + 2] * _a[num2];
					num -= 2;
					num2 += 2;
				}
				i = _n2 - 3;
				while (num >= 0)
				{
					array[num + 1] = (0f - buffer[i + 2]) * _a[num2] - (0f - buffer[i]) * _a[num2 + 1];
					array[num] = (0f - buffer[i + 2]) * _a[num2 + 1] + (0f - buffer[i]) * _a[num2];
					num -= 2;
					num2 += 2;
					i -= 4;
				}
				float[] array2 = array;
				int num3 = _n2 - 8;
				int num4 = _n4;
				int num5 = 0;
				int num6 = _n4;
				int num7 = 0;
				while (num3 >= 0)
				{
					float num8 = array2[num4 + 1] - array2[num5 + 1];
					float num9 = array2[num4] - array2[num5];
					buffer[num6 + 1] = array2[num4 + 1] + array2[num5 + 1];
					buffer[num6] = array2[num4] + array2[num5];
					buffer[num7 + 1] = num8 * _a[num3 + 4] - num9 * _a[num3 + 5];
					buffer[num7] = num9 * _a[num3 + 4] + num8 * _a[num3 + 5];
					num8 = array2[num4 + 3] - array2[num5 + 3];
					num9 = array2[num4 + 2] - array2[num5 + 2];
					buffer[num6 + 3] = array2[num4 + 3] + array2[num5 + 3];
					buffer[num6 + 2] = array2[num4 + 2] + array2[num5 + 2];
					buffer[num7 + 3] = num8 * _a[num3] - num9 * _a[num3 + 1];
					buffer[num7 + 2] = num9 * _a[num3] + num8 * _a[num3 + 1];
					num3 -= 8;
					num6 += 4;
					num7 += 4;
					num4 += 4;
					num5 += 4;
				}
				int n2 = _n >> 4;
				int num10 = _n2 - 1;
				_ = _n4;
				step3_iter0_loop(n2, buffer, num10 - 0, -_n8);
				step3_iter0_loop(_n >> 4, buffer, _n2 - 1 - _n4, -_n8);
				int lim = _n >> 5;
				int num11 = _n2 - 1;
				_ = _n8;
				step3_inner_r_loop(lim, buffer, num11 - 0, -(_n >> 4), 16);
				step3_inner_r_loop(_n >> 5, buffer, _n2 - 1 - _n8, -(_n >> 4), 16);
				step3_inner_r_loop(_n >> 5, buffer, _n2 - 1 - _n8 * 2, -(_n >> 4), 16);
				step3_inner_r_loop(_n >> 5, buffer, _n2 - 1 - _n8 * 3, -(_n >> 4), 16);
				int j;
				for (j = 2; j < _ld - 3 >> 1; j++)
				{
					int num12 = _n >> j + 2;
					int num13 = num12 >> 1;
					int num14 = 1 << j + 1;
					for (int k = 0; k < num14; k++)
					{
						step3_inner_r_loop(_n >> j + 4, buffer, _n2 - 1 - num12 * k, -num13, 1 << j + 3);
					}
				}
				for (; j < _ld - 6; j++)
				{
					int num15 = _n >> j + 2;
					int num16 = 1 << j + 3;
					int num17 = num15 >> 1;
					int num18 = _n >> j + 6;
					int n3 = 1 << j + 1;
					int num19 = _n2 - 1;
					int num20 = 0;
					for (int num21 = num18; num21 > 0; num21--)
					{
						step3_inner_s_loop(n3, buffer, num19, -num17, num20, num16, num15);
						num20 += num16 * 4;
						num19 -= 8;
					}
				}
				step3_inner_s_loop_ld654(_n >> 5, buffer, _n2 - 1, _n);
				int num22 = 0;
				int num23 = _n4 - 4;
				int num24 = _n2 - 4;
				while (num23 >= 0)
				{
					int num25 = _bitrev[num22];
					array2[num24 + 3] = buffer[num25];
					array2[num24 + 2] = buffer[num25 + 1];
					array2[num23 + 3] = buffer[num25 + 2];
					array2[num23 + 2] = buffer[num25 + 3];
					num25 = _bitrev[num22 + 1];
					array2[num24 + 1] = buffer[num25];
					array2[num24] = buffer[num25 + 1];
					array2[num23 + 1] = buffer[num25 + 2];
					array2[num23] = buffer[num25 + 3];
					num23 -= 4;
					num24 -= 4;
					num22 += 2;
				}
				int num26 = 0;
				int num27 = 0;
				int num28 = _n2 - 4;
				while (num27 < num28)
				{
					float num29 = array2[num27] - array2[num28 + 2];
					float num30 = array2[num27 + 1] + array2[num28 + 3];
					float num31 = _c[num26 + 1] * num29 + _c[num26] * num30;
					float num32 = _c[num26 + 1] * num30 - _c[num26] * num29;
					float num33 = array2[num27] + array2[num28 + 2];
					float num34 = array2[num27 + 1] - array2[num28 + 3];
					array2[num27] = num33 + num31;
					array2[num27 + 1] = num34 + num32;
					array2[num28 + 2] = num33 - num31;
					array2[num28 + 3] = num32 - num34;
					num29 = array2[num27 + 2] - array2[num28];
					num30 = array2[num27 + 3] + array2[num28 + 1];
					num31 = _c[num26 + 3] * num29 + _c[num26 + 2] * num30;
					num32 = _c[num26 + 3] * num30 - _c[num26 + 2] * num29;
					num33 = array2[num27 + 2] + array2[num28];
					num34 = array2[num27 + 3] - array2[num28 + 1];
					array2[num27 + 2] = num33 + num31;
					array2[num27 + 3] = num34 + num32;
					array2[num28] = num33 - num31;
					array2[num28 + 1] = num32 - num34;
					num26 += 4;
					num27 += 4;
					num28 -= 4;
				}
				int num35 = _n2 - 8;
				int num36 = _n2 - 8;
				int num37 = 0;
				int num38 = _n2 - 4;
				int num39 = _n2;
				int num40 = _n - 4;
				while (num36 >= 0)
				{
					float num41 = array[num36 + 6] * _b[num35 + 7] - array[num36 + 7] * _b[num35 + 6];
					float num42 = (0f - array[num36 + 6]) * _b[num35 + 6] - array[num36 + 7] * _b[num35 + 7];
					buffer[num37] = num41;
					buffer[num38 + 3] = 0f - num41;
					buffer[num39] = num42;
					buffer[num40 + 3] = num42;
					float num43 = array[num36 + 4] * _b[num35 + 5] - array[num36 + 5] * _b[num35 + 4];
					float num44 = (0f - array[num36 + 4]) * _b[num35 + 4] - array[num36 + 5] * _b[num35 + 5];
					buffer[num37 + 1] = num43;
					buffer[num38 + 2] = 0f - num43;
					buffer[num39 + 1] = num44;
					buffer[num40 + 2] = num44;
					num41 = array[num36 + 2] * _b[num35 + 3] - array[num36 + 3] * _b[num35 + 2];
					num42 = (0f - array[num36 + 2]) * _b[num35 + 2] - array[num36 + 3] * _b[num35 + 3];
					buffer[num37 + 2] = num41;
					buffer[num38 + 1] = 0f - num41;
					buffer[num39 + 2] = num42;
					buffer[num40 + 1] = num42;
					num43 = array[num36] * _b[num35 + 1] - array[num36 + 1] * _b[num35];
					num44 = (0f - array[num36]) * _b[num35] - array[num36 + 1] * _b[num35 + 1];
					buffer[num37 + 3] = num43;
					buffer[num38] = 0f - num43;
					buffer[num39 + 3] = num44;
					buffer[num40] = num44;
					num35 -= 8;
					num36 -= 8;
					num37 += 4;
					num39 += 4;
					num38 -= 4;
					num40 -= 4;
				}
			}

			private void step3_iter0_loop(int n, float[] e, int i_off, int k_off)
			{
				int num = i_off;
				int num2 = num + k_off;
				int num3 = 0;
				for (int num4 = n >> 2; num4 > 0; num4--)
				{
					float num5 = e[num] - e[num2];
					float num6 = e[num - 1] - e[num2 - 1];
					e[num] += e[num2];
					e[num - 1] += e[num2 - 1];
					e[num2] = num5 * _a[num3] - num6 * _a[num3 + 1];
					e[num2 - 1] = num6 * _a[num3] + num5 * _a[num3 + 1];
					num3 += 8;
					num5 = e[num - 2] - e[num2 - 2];
					num6 = e[num - 3] - e[num2 - 3];
					e[num - 2] += e[num2 - 2];
					e[num - 3] += e[num2 - 3];
					e[num2 - 2] = num5 * _a[num3] - num6 * _a[num3 + 1];
					e[num2 - 3] = num6 * _a[num3] + num5 * _a[num3 + 1];
					num3 += 8;
					num5 = e[num - 4] - e[num2 - 4];
					num6 = e[num - 5] - e[num2 - 5];
					e[num - 4] += e[num2 - 4];
					e[num - 5] += e[num2 - 5];
					e[num2 - 4] = num5 * _a[num3] - num6 * _a[num3 + 1];
					e[num2 - 5] = num6 * _a[num3] + num5 * _a[num3 + 1];
					num3 += 8;
					num5 = e[num - 6] - e[num2 - 6];
					num6 = e[num - 7] - e[num2 - 7];
					e[num - 6] += e[num2 - 6];
					e[num - 7] += e[num2 - 7];
					e[num2 - 6] = num5 * _a[num3] - num6 * _a[num3 + 1];
					e[num2 - 7] = num6 * _a[num3] + num5 * _a[num3 + 1];
					num3 += 8;
					num -= 8;
					num2 -= 8;
				}
			}

			private void step3_inner_r_loop(int lim, float[] e, int d0, int k_off, int k1)
			{
				int num = d0;
				int num2 = num + k_off;
				int num3 = 0;
				for (int num4 = lim >> 2; num4 > 0; num4--)
				{
					float num5 = e[num] - e[num2];
					float num6 = e[num - 1] - e[num2 - 1];
					e[num] += e[num2];
					e[num - 1] += e[num2 - 1];
					e[num2] = num5 * _a[num3] - num6 * _a[num3 + 1];
					e[num2 - 1] = num6 * _a[num3] + num5 * _a[num3 + 1];
					num3 += k1;
					num5 = e[num - 2] - e[num2 - 2];
					num6 = e[num - 3] - e[num2 - 3];
					e[num - 2] += e[num2 - 2];
					e[num - 3] += e[num2 - 3];
					e[num2 - 2] = num5 * _a[num3] - num6 * _a[num3 + 1];
					e[num2 - 3] = num6 * _a[num3] + num5 * _a[num3 + 1];
					num3 += k1;
					num5 = e[num - 4] - e[num2 - 4];
					num6 = e[num - 5] - e[num2 - 5];
					e[num - 4] += e[num2 - 4];
					e[num - 5] += e[num2 - 5];
					e[num2 - 4] = num5 * _a[num3] - num6 * _a[num3 + 1];
					e[num2 - 5] = num6 * _a[num3] + num5 * _a[num3 + 1];
					num3 += k1;
					num5 = e[num - 6] - e[num2 - 6];
					num6 = e[num - 7] - e[num2 - 7];
					e[num - 6] += e[num2 - 6];
					e[num - 7] += e[num2 - 7];
					e[num2 - 6] = num5 * _a[num3] - num6 * _a[num3 + 1];
					e[num2 - 7] = num6 * _a[num3] + num5 * _a[num3 + 1];
					num3 += k1;
					num -= 8;
					num2 -= 8;
				}
			}

			private void step3_inner_s_loop(int n, float[] e, int i_off, int k_off, int a, int a_off, int k0)
			{
				float num = _a[a];
				float num2 = _a[a + 1];
				float num3 = _a[a + a_off];
				float num4 = _a[a + a_off + 1];
				float num5 = _a[a + a_off * 2];
				float num6 = _a[a + a_off * 2 + 1];
				float num7 = _a[a + a_off * 3];
				float num8 = _a[a + a_off * 3 + 1];
				int num9 = i_off;
				int num10 = num9 + k_off;
				for (int num11 = n; num11 > 0; num11--)
				{
					float num12 = e[num9] - e[num10];
					float num13 = e[num9 - 1] - e[num10 - 1];
					e[num9] += e[num10];
					e[num9 - 1] += e[num10 - 1];
					e[num10] = num12 * num - num13 * num2;
					e[num10 - 1] = num13 * num + num12 * num2;
					num12 = e[num9 - 2] - e[num10 - 2];
					num13 = e[num9 - 3] - e[num10 - 3];
					e[num9 - 2] += e[num10 - 2];
					e[num9 - 3] += e[num10 - 3];
					e[num10 - 2] = num12 * num3 - num13 * num4;
					e[num10 - 3] = num13 * num3 + num12 * num4;
					num12 = e[num9 - 4] - e[num10 - 4];
					num13 = e[num9 - 5] - e[num10 - 5];
					e[num9 - 4] += e[num10 - 4];
					e[num9 - 5] += e[num10 - 5];
					e[num10 - 4] = num12 * num5 - num13 * num6;
					e[num10 - 5] = num13 * num5 + num12 * num6;
					num12 = e[num9 - 6] - e[num10 - 6];
					num13 = e[num9 - 7] - e[num10 - 7];
					e[num9 - 6] += e[num10 - 6];
					e[num9 - 7] += e[num10 - 7];
					e[num10 - 6] = num12 * num7 - num13 * num8;
					e[num10 - 7] = num13 * num7 + num12 * num8;
					num9 -= k0;
					num10 -= k0;
				}
			}

			private void step3_inner_s_loop_ld654(int n, float[] e, int i_off, int base_n)
			{
				int num = base_n >> 3;
				float num2 = _a[num];
				int num3 = i_off;
				int num4 = num3 - 16 * n;
				while (num3 > num4)
				{
					float num5 = e[num3] - e[num3 - 8];
					float num6 = e[num3 - 1] - e[num3 - 9];
					e[num3] += e[num3 - 8];
					e[num3 - 1] += e[num3 - 9];
					e[num3 - 8] = num5;
					e[num3 - 9] = num6;
					num5 = e[num3 - 2] - e[num3 - 10];
					num6 = e[num3 - 3] - e[num3 - 11];
					e[num3 - 2] += e[num3 - 10];
					e[num3 - 3] += e[num3 - 11];
					e[num3 - 10] = (num5 + num6) * num2;
					e[num3 - 11] = (num6 - num5) * num2;
					num5 = e[num3 - 12] - e[num3 - 4];
					num6 = e[num3 - 5] - e[num3 - 13];
					e[num3 - 4] += e[num3 - 12];
					e[num3 - 5] += e[num3 - 13];
					e[num3 - 12] = num6;
					e[num3 - 13] = num5;
					num5 = e[num3 - 14] - e[num3 - 6];
					num6 = e[num3 - 7] - e[num3 - 15];
					e[num3 - 6] += e[num3 - 14];
					e[num3 - 7] += e[num3 - 15];
					e[num3 - 14] = (num5 + num6) * num2;
					e[num3 - 15] = (num5 - num6) * num2;
					iter_54(e, num3);
					iter_54(e, num3 - 8);
					num3 -= 16;
				}
			}

			private void iter_54(float[] e, int z)
			{
				float num = e[z] - e[z - 4];
				float num2 = e[z] + e[z - 4];
				float num3 = e[z - 2] + e[z - 6];
				float num4 = e[z - 2] - e[z - 6];
				e[z] = num2 + num3;
				e[z - 2] = num2 - num3;
				float num5 = e[z - 3] - e[z - 7];
				e[z - 4] = num + num5;
				e[z - 6] = num - num5;
				float num6 = e[z - 1] - e[z - 5];
				float num7 = e[z - 1] + e[z - 5];
				float num8 = e[z - 3] + e[z - 7];
				e[z - 1] = num7 + num8;
				e[z - 3] = num7 - num8;
				e[z - 5] = num6 - num4;
				e[z - 7] = num6 + num4;
			}
		}

		private const float M_PI = MathF.PI;

		private Dictionary<int, MdctImpl> _setupCache = new Dictionary<int, MdctImpl>();

		public void Reverse(float[] samples, int sampleCount)
		{
			if (!_setupCache.TryGetValue(sampleCount, out var value))
			{
				value = new MdctImpl(sampleCount);
				_setupCache[sampleCount] = value;
			}
			value.CalcReverse(samples);
		}
	}
	internal class Mode : IMode
	{
		private struct OverlapInfo
		{
			public int PacketStartIndex;

			public int PacketTotalLength;

			public int PacketValidLength;
		}

		private const float M_PI2 = MathF.PI / 2f;

		private int _channels;

		private bool _blockFlag;

		private int _blockSize;

		private IMapping _mapping;

		private float[][] _windows;

		private OverlapInfo[] _overlapInfo;

		public void Init(IPacket packet, int channels, int block0Size, int block1Size, IMapping[] mappings)
		{
			_channels = channels;
			_blockFlag = packet.ReadBit();
			if (packet.ReadBits(32) != 0L)
			{
				throw new InvalidDataException("Mode header had invalid window or transform type!");
			}
			int num = (int)packet.ReadBits(8);
			if (num >= mappings.Length)
			{
				throw new InvalidDataException("Mode header had invalid mapping index!");
			}
			_mapping = mappings[num];
			if (_blockFlag)
			{
				_blockSize = block1Size;
				_windows = new float[4][]
				{
					CalcWindow(block0Size, block1Size, block0Size),
					CalcWindow(block1Size, block1Size, block0Size),
					CalcWindow(block0Size, block1Size, block1Size),
					CalcWindow(block1Size, block1Size, block1Size)
				};
				_overlapInfo = new OverlapInfo[4]
				{
					CalcOverlap(block0Size, block1Size, block0Size),
					CalcOverlap(block1Size, block1Size, block0Size),
					CalcOverlap(block0Size, block1Size, block1Size),
					CalcOverlap(block1Size, block1Size, block1Size)
				};
			}
			else
			{
				_blockSize = block0Size;
				_windows = new float[1][] { CalcWindow(block0Size, block0Size, block0Size) };
			}
		}

		private static float[] CalcWindow(int prevBlockSize, int blockSize, int nextBlockSize)
		{
			float[] array = new float[blockSize];
			int num = prevBlockSize / 2;
			int num2 = nextBlockSize / 2;
			int num3 = blockSize / 4 - num / 2;
			int num4 = blockSize - blockSize / 4 - num2 / 2;
			for (int i = 0; i < num; i++)
			{
				float num5 = (float)Math.Sin(((double)i + 0.5) / (double)num * 1.5707963705062866);
				num5 *= num5;
				array[num3 + i] = (float)Math.Sin(num5 * (MathF.PI / 2f));
			}
			for (int j = num3 + num; j < num4; j++)
			{
				array[j] = 1f;
			}
			for (int k = 0; k < num2; k++)
			{
				float num6 = (float)Math.Sin(((double)(num2 - k) - 0.5) / (double)num2 * 1.5707963705062866);
				num6 *= num6;
				array[num4 + k] = (float)Math.Sin(num6 * (MathF.PI / 2f));
			}
			return array;
		}

		private static OverlapInfo CalcOverlap(int prevBlockSize, int blockSize, int nextBlockSize)
		{
			int num = prevBlockSize / 4;
			int num2 = nextBlockSize / 4;
			int packetStartIndex = blockSize / 4 - num;
			int num3 = blockSize / 4 * 3 + num2;
			int packetValidLength = num3 - num2 * 2;
			OverlapInfo result = default(OverlapInfo);
			result.PacketStartIndex = packetStartIndex;
			result.PacketValidLength = packetValidLength;
			result.PacketTotalLength = num3;
			return result;
		}

		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)
			{
				bool flag = packet.ReadBit();
				bool flag2 = packet.ReadBit();
				windowIndex = (flag ? 1 : 0) + (flag2 ? 2 : 0);
				OverlapInfo 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);
				float[] array = _windows[windowIndex];
				for (int i = 0; i < _blockSize; i++)
				{
					for (int j = 0; j < _channels; j++)
					{
						buffer[j][i] *= array[i];
					}
				}
				return true;
			}
			return false;
		}

		public int GetPacketSampleCount(IPacket packet)
		{
			GetPacketInfo(packet, out var _, out var packetStartIndex, out var packetValidLength, out var _);
			return packetValidLength - packetStartIndex;
		}
	}
	[Serializable]
	public class NewStreamEventArgs : EventArgs
	{
		public IStreamDecoder StreamDecoder { get; }

		public bool IgnoreStream { get; set; }

		public NewStreamEventArgs(IStreamDecoder streamDecoder)
		{
			StreamDecoder = streamDecoder ?? throw new ArgumentNullException("streamDecoder");
		}
	}
	internal class Residue0 : IResidue
	{
		private int _channels;

		private int _begin;

		private int _end;

		private int _partitionSize;

		private int _classifications;

		private int _maxStages;

		private ICodebook[][] _books;

		private ICodebook _classBook;

		private int[] _cascade;

		private int[][] _decodeMap;

		private static int icount(int v)
		{
			int num = 0;
			while (v != 0)
			{
				num += v & 1;
				v >>= 1;
			}
			return num;
		}

		public virtual void Init(IPacket packet, int channels, ICodebook[] codebooks)
		{
			_begin = (int)packet.ReadBits(24);
			_end = (int)packet.ReadBits(24);
			_partitionSize = (int)packet.ReadBits(24) + 1;
			_classifications = (int)packet.ReadBits(6) + 1;
			_classBook = codebooks[(uint)packet.ReadBits(8)];
			_cascade = new int[_classifications];
			int num = 0;
			for (int i = 0; i < _classifications; i++)
			{
				int num2 = (int)packet.ReadBits(3);
				if (packet.ReadBit())
				{
					_cascade[i] = ((int)packet.ReadBits(5) << 3) | num2;
				}
				else
				{
					_cascade[i] = num2;
				}
				num += icount(_cascade[i]);
			}
			int[] array = new int[num];
			for (int j = 0; j < num; j++)
			{
				array[j] = (int)packet.ReadBits(8);
				if (codebooks[array[j]].MapType == 0)
				{
					throw new InvalidDataException();
				}
			}
			int entries = _classBook.Entries;
			int num3 = _classBook.Dimensions;
			int num4 = 1;
			while (num3 > 0)
			{
				num4 *= _classifications;
				if (num4 > entries)
				{
					throw new InvalidDataException();
				}
				num3--;
			}
			_books = new ICodebook[_classifications][];
			num = 0;
			int num5 = 0;
			for (int k = 0; k < _classifications; k++)
			{
				int num6 = Utils.ilog(_cascade[k]);
				_books[k] = new ICodebook[num6];
				if (num6 <= 0)
				{
					continue;
				}
				num5 = Math.Max(num5, num6);
				for (int l = 0; l < num6; l++)
				{
					if ((_cascade[k] & (1 << l)) > 0)
					{
						_books[k][l] = codebooks[array[num++]];
					}
				}
			}
			_maxStages = num5;
			_decodeMap = new int[num4][];
			for (int m = 0; m < num4; m++)
			{
				int num7 = m;
				int num8 = num4 / _classifications;
				_decodeMap[m] = new int[_classBook.Dimensions];
				for (int n = 0; n < _classBook.Dimensions; n++)
				{
					int num9 = num7 / num8;
					num7 -= num9 * num8;
					num8 /= _classifications;
					_decodeMap[m][n] = num9;
				}
			}
			_channels = channels;
		}

		public virtual void Decode(IPacket packet, bool[] doNotDecodeChannel, int blockSize, float[][] buffer)
		{
			int num = ((_end < blockSize / 2) ? _end : (blockSize / 2)) - _begin;
			if (num <= 0 || Array.IndexOf(doNotDecodeChannel, value: false) == -1)
			{
				return;
			}
			int num2 = num / _partitionSize;
			int num3 = (num2 + _classBook.Dimensions - 1) / _classBook.Dimensions;
			int[,][] array = new int[_channels, num3][];
			for (int i = 0; i < _maxStages; i++)
			{
				int j = 0;
				int num4 = 0;
				while (j < num2)
				{
					if (i == 0)
					{
						for (int k = 0; k < _channels; k++)
						{
							int num5 = _classBook.DecodeScalar(packet);
							if (num5 >= 0 && num5 < _decodeMap.Length)
							{
								array[k, num4] = _decodeMap[num5];
								continue;
							}
							j = num2;
							i = _maxStages;
							break;
						}
					}
					int num6 = 0;
					for (; j < num2; j++)
					{
						if (num6 >= _classBook.Dimensions)
						{
							break;
						}
						int offset = _begin + j * _partitionSize;
						for (int l = 0; l < _channels; l++)
						{
							int num7 = array[l, num4][num6];
							if ((_cascade[num7] & (1 << i)) != 0)
							{
								ICodebook codebook = _books[num7][i];
								if (codebook != null && WriteVectors(codebook, packet, buffer, l, offset, _partitionSize))
								{
									j = num2;
									i = _maxStages;
									break;
								}
							}
						}
						num6++;
					}
					num4++;
				}
			}
		}

		protected virtual bool WriteVectors(ICodebook codebook, IPacket packet, float[][] residue, int channel, int offset, int partitionSize)
		{
			float[] array = residue[channel];
			int num = partitionSize / codebook.Dimensions;
			int[] array2 = new int[num];
			for (int i = 0; i < num; i++)
			{
				if ((array2[i] = codebook.DecodeScalar(packet)) == -1)
				{
					return true;
				}
			}
			for (int j = 0; j < codebook.Dimensions; j++)
			{
				int num2 = 0;
				while (num2 < num)
				{
					array[offset] += codebook[array2[num2], j];
					num2++;
					offset++;
				}
			}
			return false;
		}
	}
	internal class Residue1 : Residue0
	{
		protected override bool WriteVectors(ICodebook codebook, IPacket packet, float[][] residue, int channel, int offset, int partitionSize)
		{
			float[] array = residue[channel];
			int num = 0;
			while (num < partitionSize)
			{
				int num2 = codebook.DecodeScalar(packet);
				if (num2 == -1)
				{
					return true;
				}
				for (int i = 0; i < codebook.Dimensions; i++)
				{
					array[offset + num] += codebook[num2, i];
					num++;
				}
			}
			return false;
		}
	}
	internal class Residue2 : Residue0
	{
		private 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)
		{
			base.Decode(packet, doNotDecodeChannel, blockSize * _channels, buffer);
		}

		protected override bool WriteVectors(ICodebook codebook, IPacket packet, float[][] residue, int channel, int offset, int partitionSize)
		{
			int num = 0;
			offset /= _channels;
			int num2 = 0;
			while (num2 < partitionSize)
			{
				int num3 = codebook.DecodeScalar(packet);
				if (num3 == -1)
				{
					return true;
				}
				int num4 = 0;
				while (num4 < codebook.Dimensions)
				{
					residue[num][offset] += codebook[num3, num4];
					if (++num == _channels)
					{
						num = 0;
						offset++;
					}
					num4++;
					num2++;
				}
			}
			return false;
		}
	}
	public sealed class StreamDecoder : IStreamDecoder, IDisposable
	{
		private NVorbis.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;

		private static readonly byte[] PacketSignatureStream = new byte[11]
		{
			1, 118, 111, 114, 98, 105, 115, 0, 0, 0,
			0
		};

		private static readonly byte[] PacketSignatureComments = new byte[7] { 3, 118, 111, 114, 98, 105, 115 };

		private static readonly byte[] PacketSignatureBooks = new byte[7] { 5, 118, 111, 114, 98, 105, 115 };

		internal static Func<IFactory> CreateFactory { get; set; } = () => new Factory();


		public int Channels => _channels;

		public int SampleRate => _sampleRate;

		public int UpperBitrate { get; private set; }

		public int NominalBitrate { get; private set; }

		public int LowerBitrate { get; private set; }

		public ITagData Tags => _tags ?? (_tags = new TagData(_vendor, _comments));

		public TimeSpan TotalTime => TimeSpan.FromSeconds((double)TotalSamples / (double)_sampleRate);

		public long TotalSamples => (_packetProvider ?? throw new ObjectDisposedException("StreamDecoder")).GetGranuleCount();

		public TimeSpan TimePosition
		{
			get
			{
				return TimeSpan.FromSeconds((double)_currentPosition / (double)_sampleRate);
			}
			set
			{
				SeekTo(value);
			}
		}

		public long SamplePosition
		{
			get
			{
				return _currentPosition;
			}
			set
			{
				SeekTo(value);
			}
		}

		public bool ClipSamples { get; set; }

		public bool HasClipped => _hasClipped;

		public bool IsEndOfStream
		{
			get
			{
				if (_eosFound)
				{
					return _prevPacketBuf == null;
				}
				return false;
			}
		}

		public IStreamStats Stats => _stats;

		public StreamDecoder(NVorbis.Contracts.IPacketProvider packetProvider)
			: this(packetProvider, new Factory())
		{
		}

		internal StreamDecoder(NVorbis.Contracts.IPacketProvider packetProvider, IFactory factory)
		{
			_packetProvider = packetProvider ?? throw new ArgumentNullException("packetProvider");
			_factory = factory ?? throw new ArgumentNullException("factory");
			_stats = new StreamStats();
			_currentPosition = 0L;
			ClipSamples = true;
			IPacket packet = _packetProvider.PeekNextPacket();
			if (!ProcessHeaderPackets(packet))
			{
				_packetProvider = null;
				packet.Reset();
				throw GetInvalidStreamException(packet);
			}
		}

		private static Exception GetInvalidStreamException(IPacket packet)
		{
			try
			{
				ulong num = packet.ReadBits(64);
				if (num == 7233173838382854223L)
				{
					return new ArgumentException("Found OPUS bitstream.");
				}
				if ((num & 0xFF) == 127)
				{
					return new ArgumentException("Found FLAC bitstream.");
				}
				switch (num)
				{
				case 2314885909937746003uL:
					return new ArgumentException("Found Speex bitstream.");
				case 28254585843050854uL:
					return new ArgumentException("Found Skeleton metadata bitstream.");
				default:
					if ((num & 0xFFFFFFFFFFFF00L) == 27428895509214208L)
					{
						return new ArgumentException("Found Theora bitsream.");
					}
					return new ArgumentException("Could not find Vorbis data to decode.");
				}
			}
			finally
			{
				packet.Reset();
			}
		}

		private bool ProcessHeaderPackets(IPacket packet)
		{
			if (!ProcessHeaderPacket(packet, LoadStreamHeader, delegate
			{
				_packetProvider.GetNextPacket().Done();
			}))
			{
				return false;
			}
			if (!ProcessHeaderPacket(_packetProvider.GetNextPacket(), LoadComments, delegate(IPacket pkt)
			{
				pkt.Done();
			}))
			{
				return false;
			}
			if (!ProcessHeaderPacket(_packetProvider.GetNextPacket(), LoadBooks, delegate(IPacket pkt)
			{
				pkt.Done();
			}))
			{
				return false;
			}
			_currentPosition = 0L;
			ResetDecoder();
			return true;
		}

		private static bool ProcessHeaderPacket(IPacket packet, Func<IPacket, bool> processAction, Action<IPacket> doneAction)
		{
			if (packet != null)
			{
				try
				{
					return processAction(packet);
				}
				finally
				{
					doneAction(packet);
				}
			}
			return false;
		}

		private static bool ValidateHeader(IPacket packet, byte[] expected)
		{
			for (int i = 0; i < expected.Length; i++)
			{
				if (expected[i] != packet.ReadBits(8))
				{
					return false;
				}
			}
			return true;
		}

		private static string ReadString(IPacket packet)
		{
			int num = (int)packet.ReadBits(32);
			if (num == 0)
			{
				return string.Empty;
			}
			byte[] array = new byte[num];
			if (packet.Read(array, 0, num) < num)
			{
				throw new InvalidDataException("Could not read full string!");
			}
			return Encoding.UTF8.GetString(array);
		}

		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 (int 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;
			}
			IMdct mdct = _factory.CreateMdct();
			IHuffman huffman = _factory.CreateHuffman();
			ICodebook[] array = new ICodebook[packet.ReadBits(8) + 1];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = _factory.CreateCodebook();
				array[i].Init(packet, huffman);
			}
			int num = (int)packet.ReadBits(6) + 1;
			packet.SkipBits(16 * num);
			IFloor[] array2 = new IFloor[packet.ReadBits(6) + 1];
			for (int j = 0; j < array2.Length; j++)
			{
				array2[j] = _factory.CreateFloor(packet);
				array2[j].Init(packet, _channels, _block0Size, _block1Size, array);
			}
			IResidue[] array3 = new IResidue[packet.ReadBits(6) + 1];
			for (int k = 0; k < array3.Length; k++)
			{
				array3[k] = _factory.CreateResidue(packet);
				array3[k].Init(packet, _channels, array);
			}
			IMapping[] array4 = new IMapping[packet.ReadBits(6) + 1];
			for (int l = 0; l < array4.Length; l++)
			{
				array4[l] = _factory.CreateMapping(packet);
				array4[l].Init(packet, _channels, array2, array3, mdct);
			}
			_modes = new IMode[packet.ReadBits(6) + 1];
			for (int m = 0; m < _modes.Length; m++)
			{
				_modes[m] = _factory.CreateMode();
				_modes[m].Init(packet, _channels, _block0Size, _block1Size, array4);
			}
			if (!packet.ReadBit())
			{
				throw new InvalidDataException("Book packet did not end on correct bit!");
			}
			_modeFieldBits = Utils.ilog(_modes.Length - 1);
			_stats.AddPacket(-1, packet.BitsRead, packet.BitsRemaining, packet.ContainerOverheadBits);
			return true;
		}

		private void ResetDecoder()
		{
			_prevPacketBuf = null;
			_prevPacketStart = 0;
			_prevPacketEnd = 0;
			_prevPacketStop = 0;
			_nextPacketBuf = null;
			_eosFound = false;
			_hasClipped = false;
			_hasPosition = false;
		}

		public int Read(Span<float> buffer, int offset, int count)
		{
			if (buffer == null)
			{
				throw new ArgumentNullException("buffer");
			}
			if (offset < 0 || offset + count > buffer.Length)
			{
				throw new ArgumentOutOfRangeException("offset");
			}
			if (count % _channels != 0)
			{
				throw new ArgumentOutOfRangeException("count", "Must be a multiple of Channels!");
			}
			if (_packetProvider == null)
			{
				throw new ObjectDisposedException("StreamDecoder");
			}
			if (count == 0)
			{
				return 0;
			}
			int num = offset;
			int num2 = offset + count;
			while (num < num2)
			{
				if (_prevPacketStart == _prevPacketEnd)
				{
					if (_eosFound)
					{
						_nextPacketBuf = null;
						_prevPacketBuf = null;
						break;
					}
					if (!ReadNextPacket((num - offset) / _channels, out var samplePosition))
					{
						_prevPacketEnd = _prevPacketStop;
					}
					if (samplePosition.HasValue && !_hasPosition)
					{
						_hasPosition = true;
						_currentPosition = samplePosition.Value - (_prevPacketEnd - _prevPacketStart) - (num - offset) / _channels;
					}
				}
				int num3 = Math.Min((num2 - num) / _channels, _prevPacketEnd - _prevPacketStart);
				if (num3 > 0)
				{
					num = ((!ClipSamples) ? (num + CopyBuffer(buffer, num, num3)) : (num + ClippingCopyBuffer(buffer, num, num3)));
				}
			}
			count = num - offset;
			_currentPosition += count / _channels;
			return count;
		}

		private int ClippingCopyBuffer(Span<float> target, int targetIndex, int count)
		{
			int num = targetIndex;
			while (count > 0)
			{
				for (int i = 0; i < _channels; i++)
				{
					target[num++] = Utils.ClipValue(_prevPacketBuf[i][_prevPacketStart], ref _hasClipped);
				}
				_prevPacketStart++;
				count--;
			}
			return num - targetIndex;
		}

		private int CopyBuffer(Span<float> target, int targetIndex, int count)
		{
			int num = targetIndex;
			while (count > 0)
			{
				for (int i = 0; i < _channels; i++)
				{
					target[num++] = _prevPacketBuf[i][_prevPacketStart];
				}
				_prevPacketStart++;
				count--;
			}
			return num - targetIndex;
		}

		private bool ReadNextPacket(int bufferedSamples, out long? samplePosition)
		{
			int packetStartindex;
			int packetValidLength;
			int packetTotalLength;
			bool isEndOfStream;
			int bitsRead;
			int bitsRemaining;
			int containerOverheadBits;
			float[][] array = DecodeNextPacket(out packetStartindex, out packetValidLength, out packetTotalLength, out isEndOfStream, out samplePosition, out bitsRead, out bitsRemaining, out containerOverheadBits);
			_eosFound |= isEndOfStream;
			if (array == null)
			{
				_stats.AddPacket(0, bitsRead, bitsRemaining, containerOverheadBits);
				return false;
			}
			if (samplePosition.HasValue && isEndOfStream)
			{
				long num = _currentPosition + bufferedSamples + packetValidLength - packetStartindex;
				int num2 = (int)(samplePosition.Value - num);
				if (num2 < 0)
				{
					packetValidLength += num2;
				}
			}
			if (_prevPacketEnd > 0)
			{
				OverlapBuffers(_prevPacketBuf, array, _prevPacketStart, _prevPacketStop, packetStartindex, _channels);
				_prevPacketStart = packetStartindex;
			}
			else if (_prevPacketBuf == null)
			{
				_prevPacketStart = packetValidLength;
			}
			_stats.AddPacket(packetValidLength - _prevPacketStart, bitsRead, bitsRemaining, containerOverheadBits);
			_nextPacketBuf = _prevPacketBuf;
			_prevPacketEnd = packetValidLength;
			_prevPacketStop = packetTotalLength;
			_prevPacketBuf = array;
			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)
				{
					isEndOfStream = true;
				}
				else
				{
					isEndOfStream = packet.IsEndOfStream;
					if (packet.IsResync)
					{
						_hasPosition = false;
					}
					containerOverheadBits = packet.ContainerOverheadBits;
					if (packet.ReadBit())
					{
						bitsRemaining = packet.BitsRemaining + 1;
					}
					else
					{
						IMode mode = _modes[(uint)packet.ReadBits(_modeFieldBits)];
						if (_nextPacketBuf == null)
						{
							_nextPacketBuf = new float[_channels][];
							for (int i = 0; i < _channels; i++)
							{
								_nextPacketBuf[i] = new float[_block1Size];
							}
						}
						if (mode.Decode(packet, _nextPacketBuf, out packetStartindex, out packetValidLength, out packetTotalLength))
						{
							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)
		{
			while (prevStart < prevLen)
			{
				for (int i = 0; i < channels; i++)
				{
					next[i][nextStart] += previous[i][prevStart];
				}
				prevStart++;
				nextStart++;
			}
		}

		public void SeekTo(TimeSpan timePosition, SeekOrigin seekOrigin = SeekOrigin.Begin)
		{
			SeekTo((long)((double)SampleRate * timePosition.TotalSeconds), seekOrigin);
		}

		public void SeekTo(long samplePosition, SeekOrigin seekOrigin = SeekOrigin.Begin)
		{
			if (_packetProvider == null)
			{
				throw new ObjectDisposedException("StreamDecoder");
			}
			if (!_packetProvider.CanSeek)
			{
				throw new InvalidOperationException("Seek is not supported by the Contracts.IPacketProvider instance.");
			}
			switch (seekOrigin)
			{
			case SeekOrigin.Current:
				samplePosition = SamplePosition - samplePosition;
				break;
			case SeekOrigin.End:
				samplePosition = TotalSamples - samplePosition;
				break;
			default:
				throw new ArgumentOutOfRangeException("seekOrigin");
			case SeekOrigin.Begin:
				break;
			}
			if (samplePosition < 0)
			{
				throw new ArgumentOutOfRangeException("samplePosition");
			}
			int num;
			if (samplePosition == 0L)
			{
				_packetProvider.SeekTo(0L, 0, GetPacketGranules);
				num = 0;
			}
			else
			{
				long num2 = _packetProvider.SeekTo(samplePosition, 1, GetPacketGranules);
				num = (int)(samplePosition - num2);
			}
			ResetDecoder();
			_hasPosition = true;
			if (!ReadNextPacket(0, out var samplePosition2))
			{
				_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;
			}
			if (!ReadNextPacket(0, out samplePosition2))
			{
				ResetDecoder();
				_eosFound = true;
				throw new InvalidOperationException("Could not read pre-roll packet!  Try seeking again prior to reading more samples.");
			}
			_prevPacketStart += num;
			_currentPosition = samplePosition;
		}

		private int GetPacketGranules(IPacket curPacket)
		{
			if (curPacket.IsResync)
			{
				return 0;
			}
			if (curPacket.ReadBit())
			{
				return 0;
			}
			int num = (int)curPacket.ReadBits(_modeFieldBits);
			if (num < 0 || num >= _modes.Length)
			{
				return 0;
			}
			return _modes[num].GetPacketSampleCount(curPacket);
		}

		public void Dispose()
		{
			(_packetProvider as IDisposable)?.Dispose();
			_packetProvider = null;
		}
	}
	internal 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 totalSamples;
				long num;
				lock (_lock)
				{
					totalSamples = _totalSamples;
					num = _audioBits + _headerBits + _containerBits + _wasteBits;
				}
				if (totalSamples > 0)
				{
					return (int)((double)num / (double)totalSamples * (double)_sampleRate);
				}
				return 0;
			}
		}

		public int InstantBitRate
		{
			get
			{
				int num;
				int num2;
				lock (_lock)
				{
					num = _packetBits[0] + _packetBits[1];
					num2 = _packetSamples[0] + _packetSamples[1];
				}
				if (num2 > 0)
				{
					return (int)((double)num / (double)num2 * (double)_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 = 0L;
				_totalSamples = 0L;
				_headerBits = 0L;
				_containerBits = 0L;
				_wasteBits = 0L;
			}
		}

		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)
				{
					_audioBits += bits;
					_wasteBits += waste;
					_containerBits += container;
					_totalSamples += samples;
					_packetBits[_packetIndex] = bits + waste;
					_packetSamples[_packetIndex] = samples;
					if (++_packetIndex == 2)
					{
						_packetIndex = 0;
					}
				}
				else
				{
					_headerBits += bits;
					_wasteBits += waste;
					_containerBits += container;
				}
			}
		}
	}
	internal class TagData : ITagData
	{
		private static IReadOnlyList<string> s_emptyList = new List<string>();

		private Dictionary<string, IReadOnlyList<string>> _tags;

		public IReadOnlyDictionary<string, IReadOnlyList<string>> 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<string> 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<string> Genres => GetTagMulti("GENRE");

		public IReadOnlyList<string> Dates => GetTagMulti("DATE");

		public IReadOnlyList<string> Locations => GetTagMulti("LOCATION");

		public string Contact => GetTagSingle("CONTACT");

		public string Isrc => GetTagSingle("ISRC");

		public TagData(string vendor, string[] comments)
		{
			EncoderVendor = vendor;
			Dictionary<string, IReadOnlyList<string>> dictionary = new Dictionary<string, IReadOnlyList<string>>();
			for (int i = 0; i < comments.Length; i++)
			{
				string[] array = comments[i].Split(new char[1] { '=' });
				if (array.Length == 1)
				{
					array = new string[2]
					{
						array[0],
						string.Empty
					};
				}
				int num = array[0].IndexOf('[');
				if (num > -1)
				{
					array[1] = array[0].Substring(num + 1, array[0].Length - num - 2).ToUpper(CultureInfo.CurrentCulture) + ": " + array[1];
					array[0] = array[0].Substring(0, num);
				}
				if (dictionary.TryGetValue(array[0].ToUpperInvariant(), out var value))
				{
					((List<string>)value).Add(array[1]);
					continue;
				}
				dictionary.Add(array[0].ToUpperInvariant(), new List<string> { array[1] });
			}
			_tags = dictionary;
		}

		public string GetTagSingle(string key, bool concatenate = false)
		{
			IReadOnlyList<string> tagMulti = GetTagMulti(key);
			if (tagMulti.Count > 0)
			{
				if (concatenate)
				{
					return string.Join(Environment.NewLine, tagMulti.ToArray());
				}
				return tagMulti[tagMulti.Count - 1];
			}
			return string.Empty;
		}

		public IReadOnlyList<string> GetTagMulti(string key)
		{
			if (_tags.TryGetValue(key.ToUpperInvariant(), out var value))
			{
				return value;
			}
			return s_emptyList;
		}
	}
	internal static class Utils
	{
		internal static int ilog(int x)
		{
			int num = 0;
			while (x > 0)
			{
				num++;
				x >>= 1;
			}
			return num;
		}

		internal static uint BitReverse(uint n)
		{
			return BitReverse(n, 32);
		}

		internal static uint BitReverse(uint n, int bits)
		{
			n = ((n & 0xAAAAAAAAu) >> 1) | ((n & 0x55555555) << 1);
			n = ((n & 0xCCCCCCCCu) >> 2) | ((n & 0x33333333) << 2);
			n = ((n & 0xF0F0F0F0u) >> 4) | ((n & 0xF0F0F0F) << 4);
			n = ((n & 0xFF00FF00u) >> 8) | ((n & 0xFF00FF) << 8);
			return ((n >> 16) | (n << 16)) >> 32 - bits;
		}

		internal static float ClipValue(float value, ref bool clipped)
		{
			if (value > MathF.PI * 113f / 355f)
			{
				clipped = true;
				return MathF.PI * 113f / 355f;
			}
			if (value < MathF.PI * -113f / 355f)
			{
				clipped = true;
				return MathF.PI * -113f / 355f;
			}
			return value;
		}

		internal static float ConvertFromVorbisFloat32(uint bits)
		{
			int num = (int)bits >> 31;
			double y = (int)(((bits & 0x7FE00000) >> 21) - 788);
			return (float)(((bits & 0x1FFFFF) ^ num) + (num & 1)) * (float)Math.Pow(2.0, y);
		}
	}
	public sealed class VorbisReader : IVorbisReader, IDisposable
	{
		private readonly List<IStreamDecoder> _decoders;

		private readonly NVorbis.Contracts.IContainerReader _containerReader;

		private readonly bool _closeOnDispose;

		private IStreamDecoder _streamDecoder;

		internal static Func<Stream, bool, NVorbis.Contracts.IContainerReader> CreateContainerReader { get; set; } = (Stream s, bool cod) => new ContainerReader(s, cod);


		internal static Func<NVorbis.Contracts.IPacketProvider, IStreamDecoder> CreateStreamDecoder { get; set; } = (NVorbis.Contracts.IPacketProvider pp) => new StreamDecoder(pp, new Factory());


		public IReadOnlyList<IStreamDecoder> Streams => _decoders;

		public int Channels => _streamDecoder.Channels;

		public int SampleRate => _streamDecoder.SampleRate;

		public int UpperBitrate => _streamDecoder.UpperBitrate;

		public int NominalBitrate => _streamDecoder.NominalBitrate;

		public int LowerBitrate => _streamDecoder.LowerBitrate;

		public ITagData Tags => _streamDecoder.Tags;

		[Obsolete("Use .Tags.EncoderVendor instead.")]
		public string Vendor => _streamDecoder.Tags.EncoderVendor;

		[Obsolete("Use .Tags.All instead.")]
		public string[] Comments => _streamDecoder.Tags.All.SelectMany((KeyValuePair<string, IReadOnlyList<string>> k) => k.Value, (KeyValuePair<string, IReadOnlyList<string>> kvp, string Item) => kvp.Key + "=" + Item).ToArray();

		[Obsolete("No longer supported.  Will receive a new stream when parameters change.", true)]
		public bool IsParameterChange
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public long ContainerOverheadBits => _containerReader?.ContainerBits ?? 0;

		public long ContainerWasteBits => _containerReader?.WasteBits ?? 0;

		public int StreamIndex => _decoders.IndexOf(_streamDecoder);

		[Obsolete("Use .Streams.Count instead.")]
		public int StreamCount => _decoders.Count;

		[Obsolete("Use VorbisReader.TimePosition instead.")]
		public TimeSpan DecodedTime
		{
			get
			{
				return _streamDecoder.TimePosition;
			}
			set
			{
				TimePosition = value;
			}
		}

		[Obsolete("Use VorbisReader.SamplePosition instead.")]
		public long DecodedPosition
		{
			get
			{
				return _streamDecoder.SamplePosition;
			}
			set
			{
				SamplePosition = value;
			}
		}

		public TimeSpan TotalTime => _streamDecoder.TotalTime;

		public long TotalSamples => _streamDecoder.TotalSamples;

		public TimeSpan TimePosition
		{
			get
			{
				return _streamDecoder.TimePosition;
			}
			set
			{
				_streamDecoder.TimePosition = value;
			}
		}

		public long SamplePosition
		{
			get
			{
				return _streamDecoder.SamplePosition;
			}
			set
			{
				_streamDecoder.SamplePosition = value;
			}
		}

		public bool IsEndOfStream => _streamDecoder.IsEndOfStream;

		public bool ClipSamples
		{
			get
			{
				return _streamDecoder.ClipSamples;
			}
			set
			{
				_streamDecoder.ClipSamples = value;
			}
		}

		public bool HasClipped => _streamDecoder.HasClipped;

		public IStreamStats StreamStats => _streamDecoder.Stats;

		[Obsolete("Use Streams[*].Stats instead.", true)]
		public IVorbisStreamStatus[] Stats
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public event EventHandler<NewStreamEventArgs> NewStream;

		public VorbisReader(string fileName)
			: this(File.OpenRead(fileName))
		{
		}

		public VorbisReader(Stream stream, bool closeOnDispose = true)
		{
			_decoders = new List<IStreamDecoder>();
			NVorbis.Contracts.IContainerReader 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!", "containerReader");
			}
			_closeOnDispose = closeOnDispose;
			_containerReader = containerReader;
			_streamDecoder = _decoders[0];
		}

		[Obsolete("Use \"new StreamDecoder(Contracts.IPacketProvider)\" and the container's NewStreamCallback or Streams property instead.", true)]
		public VorbisReader(NVorbis.Contracts.IContainerReader containerReader)
		{
			throw new NotSupportedException();
		}

		[Obsolete("Use \"new StreamDecoder(Contracts.IPacketProvider)\" instead.", true)]
		public VorbisReader(NVorbis.Contracts.IPacketProvider packetProvider)
		{
			throw new NotSupportedException();
		}

		private bool ProcessNewStream(NVorbis.Contracts.IPacketProvider packetProvider)
		{
			IStreamDecoder streamDecoder = CreateStreamDecoder(packetProvider);
			streamDecoder.ClipSamples = true;
			NewStreamEventArgs newStreamEventArgs = new NewStreamEventArgs(streamDecoder);
			this.NewStream?.Invoke(this, newStreamEventArgs);
			if (!newStreamEventArgs.IgnoreStream)
			{
				_decoders.Add(streamDecoder);
				return true;
			}
			return false;
		}

		public void Dispose()
		{
			if (_decoders != null)
			{
				foreach (IStreamDecoder decoder in _decoders)
				{
					decoder.Dispose();
				}
				_decoders.Clear();
			}
			if (_containerReader != null)
			{
				_containerReader.NewStreamCallback = null;
				if (_closeOnDispose)
				{
					_containerReader.Dispose();
				}
			}
		}

		public bool FindNextStream()
		{
			if (_containerReader == null)
			{
				return false;
			}
			return _containerReader.FindNextStream();
		}

		public bool SwitchStreams(int index)
		{
			if (index < 0 || index >= _decoders.Count)
			{
				throw new ArgumentOutOfRangeException("index");
			}
			IStreamDecoder streamDecoder = _decoders[index];
			IStreamDecoder streamDecoder2 = _streamDecoder;
			if (streamDecoder == streamDecoder2)
			{
				return false;
			}
			streamDecoder.ClipSamples = streamDecoder2.ClipSamples;
			_streamDecoder = streamDecoder;
			if (streamDecoder.Channels == streamDecoder2.Channels)
			{
				return streamDecoder.SampleRate != streamDecoder2.SampleRate;
			}
			return true;
		}

		public void SeekTo(TimeSpan timePosition, SeekOrigin seekOrigin = SeekOrigin.Begin)
		{
			_streamDecoder.SeekTo(timePosition, seekOrigin);
		}

		public void SeekTo(long samplePosition, SeekOrigin seekOrigin = SeekOrigin.Begin)
		{
			_streamDecoder.SeekTo(samplePosition, seekOrigin);
		}

		public int ReadSamples(float[] buffer, int offset, int count)
		{
			count -= count % _streamDecoder.Channels;
			if (count > 0)
			{
				return _streamDecoder.Read(buffer, offset, count);
			}
			return 0;
		}

		public int ReadSamples(Span<float> buffer)
		{
			int count = buffer.Length - buffer.Length % _streamDecoder.Channels;
			if (!buffer.IsEmpty)
			{
				return _streamDecoder.Read(buffer, 0, count);
			}
			return 0;
		}

		[Obsolete("No longer needed.", true)]
		public void ClearParameterChange()
		{
			throw new NotSupportedException();
		}
	}
}
namespace NVorbis.Ogg
{
	public sealed class ContainerReader : NVorbis.Contracts.IContainerReader, IDisposable
	{
		private IPageReader _reader;

		private List<WeakReference<NVorbis.Contracts.IPacketProvider>> _packetProviders;

		private bool _foundStream;

		internal static Func<Stream, bool, Func<NVorbis.Contracts.IPacketProvider, bool>, IPageReader> CreatePageReader { get; set; } = (Stream s, bool cod, Func<NVorbis.Contracts.IPacketProvider, bool> cb) => new PageReader(s, cod, cb);


		internal static Func<Stream, bool, Func<NVorbis.Contracts.IPacketProvider, bool>, IPageReader> CreateForwardOnlyPageReader { get; set; } = (Stream s, bool cod, Func<NVorbis.Contracts.IPacketProvider, bool> cb) => new ForwardOnlyPageReader(s, cod, cb);


		public NewStreamHandler NewStreamCallback { get; set; }

		public bool CanSeek { get; }

		public long WasteBits => _reader.WasteBits;

		public long ContainerBits => _reader.ContainerBits;

		public IReadOnlyList<NVorbis.Contracts.IPacketProvider> GetStreams()
		{
			List<NVorbis.Contracts.IPacketProvider> list = new List<NVorbis.Contracts.IPacketProvider>(_packetProviders.Count);
			for (int i = 0; i < _packetProviders.Count; i++)
			{
				if (_packetProviders[i].TryGetTarget(out var target))
				{
					list.Add(target);
					continue;
				}
				list.RemoveAt(i);
				i--;
			}
			return list;
		}

		public ContainerReader(Stream stream, bool closeOnDispose)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			_packetProviders = new List<WeakReference<NVorbis.Contracts.IPacketProvider>>();
			if (stream.CanSeek)
			{
				_reader = CreatePageReader(stream, closeOnDispose, ProcessNewStream);
				CanSeek = true;
			}
			else
			{
				_reader = CreateForwardOnlyPageReader(stream, closeOnDispose, ProcessNewStream);
			}
		}

		public bool TryInit()
		{
			return FindNextStream();
		}

		public bool FindNextStream()
		{
			_reader.Lock();
			try
			{
				_foundStream = false;
				while (_reader.ReadNextPage())
				{
					if (_foundStream)
					{
						return true;
					}
				}
				return false;
			}
			finally
			{
				_reader.Release();
			}
		}

		private bool ProcessNewStream(NVorbis.Contracts.IPacketProvider packetProvider)
		{
			bool flag = _reader.Release();
			try
			{
				NewStreamHandler newStreamCallback = NewStreamCallback;
				if (newStreamCallback == null || newStreamCallback(packetProvider))
				{
					_packetProviders.Add(new WeakReference<NVorbis.Contracts.IPacketProvider>(packetProvider));
					_foundStream = true;
					return true;
				}
				return false;
			}
			finally
			{
				if (flag)
				{
					_reader.Lock();
				}
			}
		}

		public void Dispose()
		{
			_reader?.Dispose();
			_reader = null;
		}
	}
	internal class Crc : ICrc
	{
		private const uint CRC32_POLY = 79764919u;

		private static readonly uint[] s_crcTable;

		private uint _crc;

		static Crc()
		{
			s_crcTable = new uint[256];
			for (uint num = 0u; num < 256; num++)
			{
				uint num2 = num << 24;
				for (int i = 0; i < 8; i++)
				{
					num2 = (num2 << 1) ^ ((num2 >= 2147483648u) ? 79764919u : 0u);
				}
				s_crcTable[num] = num2;
			}
		}

		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;
		}
	}
	internal class ForwardOnlyPacketProvider : DataPacket, IForwardOnlyPacketProvider, NVorbis.Contracts.IPacketProvider
	{
		private int _lastSeqNo;

		private readonly Queue<(byte[] buf, bool isResync)> _pageQueue = new Queue<(byte[], bool)>();

		private readonly IPageReader _reader;

		private byte[] _pageBuf;

		private int _packetIndex;

		private bool _isEndOfStream;

		private int _dataStart;

		private bool _lastWasPeek;

		private Memory<byte> _packetBuf;

		private int _dataIndex;

		public bool CanSeek => false;

		public int StreamSerial { get; }

		protected override int TotalBits => _packetBuf.Length * 8;

		public ForwardOnlyPacketProvider(IPageReader reader, int streamSerial)
		{
			_reader = reader;
			StreamSerial = streamSerial;
			_packetIndex = int.MaxValue;
		}

		public bool AddPage(byte[] buf, bool isResync)
		{
			if ((buf[5] & 2u) != 0)
			{
				if (_isEndOfStream)
				{
					return false;
				}
				isResync = true;
				_lastSeqNo = BitConverter.ToInt32(buf, 18);
			}
			else
			{
				int num = BitConverter.ToInt32(buf, 18);
				isResync |= num != _lastSeqNo + 1;
				_lastSeqNo = num;
			}
			int num2 = 0;
			for (int i = 0; i < buf[26]; i++)
			{
				num2 += buf[27 + i];
			}
			if (num2 == 0)
			{
				return false;
			}
			_pageQueue.Enqueue((buf, isResync));
			return true;
		}

		public void SetEndOfStream()
		{
			_isEndOfStream = true;
		}

		public IPacket GetNextPacket()
		{
			if (_packetBuf.Length > 0)
			{
				if (!_lastWasPeek)
				{
					throw new InvalidOperationException("Must call Done() on previous packet first.");
				}
				_lastWasPeek = false;
				return this;
			}
			_lastWasPeek = false;
			if (GetPacket())
			{
				return this;
			}
			return null;
		}

		public IPacket PeekNextPacket()
		{
			if (_packetBuf.Length > 0)
			{
				if (!_lastWasPeek)
				{
					throw new InvalidOperationException("Must call Done() on previous packet first.");
				}
				return this;
			}
			_lastWasPeek = true;
			if (GetPacket())
			{
				return this;
			}
			return null;
		}

		private bool GetPacket()
		{
			byte[] pageBuf;
			bool isResync;
			int packetIndex;
			bool isContinuation;
			bool isContinued;
			int dataStart;
			if (_pageBuf != null && _packetIndex < 27 + _pageBuf[26])
			{
				pageBuf = _pageBuf;
				isResync = false;
				dataStart = _dataStart;
				packetIndex = _packetIndex;
				isContinuation = false;
				isContinued = pageBuf[26 + pageBuf[26]] == byte.MaxValue;
			}
			else if (!ReadNextPage(out pageBuf, out isResync, out dataStart, out packetIndex, out isContinuation, out isContinued))
			{
				return false;
			}
			int num = dataStart;
			bool flag = packetIndex == 27;
			if (isContinuation && flag)
			{
				isResync = true;
				num += GetPacketLength(pageBuf, ref packetIndex);
				if (packetIndex == 27 + pageBuf[26])
				{
					return GetPacket();
				}
			}
			if (!flag)
			{
				num = 0;
			}
			int packetLength = GetPacketLength(pageBuf, ref packetIndex);
			Memory<byte> memory = new Memory<byte>(pageBuf, dataStart, packetLength);
			dataStart += packetLength;
			bool flag2 = packetIndex == 27 + pageBuf[26];
			if (isContinued)
			{
				if (flag2)
				{
					flag2 = false;
				}
				else
				{
					int packetIndex2 = packetIndex;
					GetPacketLength(pageBuf, ref packetIndex2);
					flag2 = packetIndex2 == 27 + pageBuf[26];
				}
			}
			bool flag3 = false;
			long? granulePosition = null;
			if (flag2)
			{
				granulePosition = BitConverter.ToInt64(pageBuf, 6);
				if ((pageBuf[5] & 4u) != 0 || (_isEndOfStream && _pageQueue.Count == 0))
				{
					flag3 = true;
				}
			}
			else
			{
				while (isContinued && packetIndex == 27 + pageBuf[26] && ReadNextPage(out pageBuf, out isResync, out dataStart, out packetIndex, out isContinuation, out isContinued) && !isResync && isContinuation)
				{
					num += 27 + pageBuf[26];
					Memory<byte> memory2 = memory;
					int packetLength2 = GetPacketLength(pageBuf, ref packetIndex);
					memory = new Memory<byte>(new byte[memory2.Length + packetLength2]);
					memory2.CopyTo(memory);
					new Memory<byte>(pageBuf, dataStart, packetLength2).CopyTo(memory.Slice(memory2.Length));
					dataStart += packetLength2;
				}
			}
			base.IsResync = isResync;
			base.GranulePosition = granulePosition;
			base.IsEndOfStream = flag3;
			base.ContainerOverheadBits = num * 8;
			_pageBuf = pageBuf;
			_dataStart = dataStart;
			_packetIndex = packetIndex;
			_packetBuf = memory;
			_isEndOfStream |= flag3;
			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())
				{
					pageBuf = null;
					isResync = false;
					dataStart = 0;
					packetIndex = 0;
					isContinuation = false;
					isContinued = false;
					return false;
				}
			}
			(byte[], bool) tuple = _pageQueue.Dequeue();
			pageBuf = tuple.Item1;
			isResync = tuple.Item2;
			dataStart = pageBuf[26] + 27;
			packetIndex = 27;
			isContinuation = (pageBuf[5] & 1) != 0;
			isContinued = pageBuf[26 + pageBuf[26]] == byte.MaxValue;
			return true;
		}

		private int GetPacketLength(byte[] pageBuf, ref int packetIndex)
		{
			int num = 0;
		

BepInEx/plugins/PataponMusicMenuManualMood.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Microsoft.CodeAnalysis;
using NAudio.Wave;
using NVorbis;
using P1.Sound;
using P1.System.Sound;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("PataponMusicMenuManualMood")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("PataponMusicMenuManualMood")]
[assembly: AssemblyTitle("PataponMusicMenuManualMood")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace PataponMusicMenuManualMood
{
	internal sealed class RuntimeSetting<T>
	{
		private T _value;

		private readonly ConfigEntry<T>? _entry;

		public T Value
		{
			get
			{
				return (_entry != null) ? _entry.Value : _value;
			}
			set
			{
				_value = value;
				if (_entry != null)
				{
					_entry.Value = value;
				}
			}
		}

		public RuntimeSetting(T value)
		{
			_value = value;
		}

		public RuntimeSetting(ConfigEntry<T> entry)
		{
			_entry = entry;
			_value = entry.Value;
		}
	}
	[BepInPlugin("juras.patapon.musicmenu.manualmood", "Patapon Music Menu Manual Mood Prototype", "0.4.6")]
	public sealed class Plugin : BasePlugin
	{
		public const string PluginGuid = "juras.patapon.musicmenu.manualmood";

		public const string PluginName = "Patapon Music Menu Manual Mood Prototype";

		public const string PluginVersion = "0.4.6";

		internal static ManualLogSource L = null;

		internal static Harmony H = null;

		private static Plugin? _instance;

		internal static RuntimeSetting<int> Enable = null;

		internal static RuntimeSetting<int> Trace = null;

		internal static RuntimeSetting<int> P1StartSessionOnStartPlayGame = null;

		internal static RuntimeSetting<int> P1StartSessionOnHelperRhythmPlayMidi = null;

		internal static RuntimeSetting<int> P1StartSessionOnBattleAddMidi = null;

		internal static RuntimeSetting<int> P1MuteHelperCategoryFromDirectorPlayMidi = null;

		internal static RuntimeSetting<int> P1MuteBgmCategoryFromDirectorPlayMidi = null;

		internal static RuntimeSetting<int> P1MuteUnknownMidi0CategoriesFromDirectorPlayMidi = null;

		internal static RuntimeSetting<int> P1OnlyMuteMidiIndex0 = null;

		internal static RuntimeSetting<int> P1MuteAddMidiResults = null;

		internal static RuntimeSetting<int> P1MuteAddMidiBgmCategory = null;

		internal static RuntimeSetting<int> P1MuteAddMidiRhythmCategory = null;

		internal static RuntimeSetting<int> P1MuteAddMidiOnlyWhenBattleOrMissionFilename = null;

		internal static RuntimeSetting<int> P1ReapplyMuteOnRhythmUpdate = null;

		internal static RuntimeSetting<int> P1MaxAddMidiTraceLogs = null;

		internal static RuntimeSetting<int> P1ZeroCriPlayDirectRhythmMissionKaesi = null;

		internal static RuntimeSetting<int> P1ZeroCriPlayDirectAllRhythm = null;

		internal static RuntimeSetting<int> P1TraceCriPlayDirectRhythm = null;

		internal static RuntimeSetting<int> P1MaxCriPlayDirectTraceLogs = null;

		internal static RuntimeSetting<int> ThemeEnable = null;

		internal static RuntimeSetting<string> ThemeDirectory = null;

		internal static RuntimeSetting<int> ThemeUseNumberedThemeFolders = null;

		internal static RuntimeSetting<string> ThemeLibraryRootDirectory = null;

		internal static RuntimeSetting<int> ThemeSelectedThemeNumber = null;

		internal static RuntimeSetting<string> ThemePartsFolderSuffix = null;

		internal static RuntimeSetting<string> ThemeVoicesFolderSuffix = null;

		internal static RuntimeSetting<float> ThemeVolume = null;

		internal static RuntimeSetting<float> ThemeMasterVolumeScale = null;

		internal static RuntimeSetting<int> ThemeTrace = null;

		internal static RuntimeSetting<int> ThemeAutoStartMood0OnBattleStart = null;

		internal static RuntimeSetting<double> ThemeInitialDelaySeconds = null;

		internal static RuntimeSetting<double> ThemeScheduleLookAheadSeconds = null;

		internal static RuntimeSetting<int> ThemeLoadAudioAtPluginStart = null;

		internal static RuntimeSetting<int> ThemePartsPerLoadFrame = null;

		internal static RuntimeSetting<int> ThemeTraceBeforeEachPartLoad = null;

		internal static RuntimeSetting<int> ThemeUseDecodeTimeout = null;

		internal static RuntimeSetting<double> ThemeDecodeTimeoutSeconds = null;

		internal static RuntimeSetting<string> ThemeSkipPartNames = null;

		internal static RuntimeSetting<int> ThemeUseFixedPartWindow = null;

		internal static RuntimeSetting<int> ThemeAnchorFixedWindowClock = null;

		internal static RuntimeSetting<int> ThemeTraceFixedWindowClock = null;

		internal static RuntimeSetting<int> ThemeResyncOnP1RhythmBoundary = null;

		internal static RuntimeSetting<int> ThemeTraceRhythmBoundaryResync = null;

		internal static RuntimeSetting<int> ThemeFrameStallCompensation = null;

		internal static RuntimeSetting<double> ThemeFrameStallThresholdSeconds = null;

		internal static RuntimeSetting<double> ThemeFrameStallMaxCompensationSeconds = null;

		internal static RuntimeSetting<int> ThemeTraceFrameStallCompensation = null;

		internal static RuntimeSetting<double> ThemeFixedPartWindowSeconds = null;

		internal static RuntimeSetting<double> ThemeFixedWindowPhaseOffsetSeconds = null;

		internal static RuntimeSetting<int> ThemeUseSeparateHelperPhaseOffset = null;

		internal static RuntimeSetting<double> ThemeHelperPhaseOffsetSeconds = null;

		internal static RuntimeSetting<int> ThemeKeepHelperLoopRunningMuted = null;

		internal static RuntimeSetting<int> ThemeHelperStartsAfterIntroWindow = null;

		internal static RuntimeSetting<int> ThemeAutoMoodFromP1Rhythm = null;

		internal static RuntimeSetting<int> ThemeAutoMoodImmediateSwitch = null;

		internal static RuntimeSetting<int> ThemeHighMoodMapsTo = null;

		internal static RuntimeSetting<int> ThemeTraceAutoMood = null;

		internal static RuntimeSetting<int> ThemeMoodLossSwitchToHelper = null;

		internal static RuntimeSetting<int> ThemeDetectMoodLossFromRhythmUpdate = null;

		internal static RuntimeSetting<int> ThemeTraceRhythmUpdateMoodLoss = null;

		internal static RuntimeSetting<int> ThemeMaxRhythmUpdateMoodLossTraceLogs = null;

		internal static RuntimeSetting<int> ThemeStopOnFailedPlayGame = null;

		internal static RuntimeSetting<int> ThemeStopOnStopBattleBgm = null;

		internal static RuntimeSetting<int> ResponseEnable = null;

		internal static RuntimeSetting<int> ResponseMuteOriginalRhythmVoice = null;

		internal static RuntimeSetting<int> ResponsePlayCustomResponses = null;

		internal static RuntimeSetting<int> ResponsePlayFirstLoadedAsFallback = null;

		internal static RuntimeSetting<int> ResponseSuppressUnmappedFallback = null;

		internal static RuntimeSetting<string> ResponseTestCueName = null;

		internal static RuntimeSetting<float> ResponseVolume = null;

		internal static RuntimeSetting<float> ResponseMasterVolumeScale = null;

		internal static RuntimeSetting<float> ExternalAudioGameVolumeFactor = null;

		private static CriSoundManager? _cachedCriSoundManager;

		private static float _cachedGameMasterVolume = 1f;

		private static double _lastGameMasterVolumeSampleTime = -9999.0;

		internal static RuntimeSetting<double> ResponseDebounceSeconds = null;

		internal static RuntimeSetting<double> ResponseDelaySeconds = null;

		internal static RuntimeSetting<int> ResponseTraceOriginalRhythmVoice = null;

		internal static RuntimeSetting<int> ResponseMaxTraceLogs = null;

		internal static RuntimeSetting<string> ResponseMiscVoicesDirectory = null;

		internal static RuntimeSetting<string> ResponseMiscVoiceNumberPrefix = null;

		internal static RuntimeSetting<int> ResponseUseCommandDetection = null;

		internal static RuntimeSetting<double> ResponseCommandMaxAgeSeconds = null;

		internal static RuntimeSetting<int> ResponseTraceCommandDetection = null;

		internal static RuntimeSetting<int> ResponseMaxCommandTraceLogs = null;

		internal static RuntimeSetting<int> ResponseCommandSummaryMaxChars = null;

		internal static RuntimeSetting<string> ResponseP1EvadeMapsTo = null;

		internal static RuntimeSetting<int> PerformanceReduceLogSpam = null;

		internal static RuntimeSetting<int> PerformanceForceGameplayQuietMode = null;

		internal static bool Enabled => Enable.Value != 0;

		internal static bool TraceEnabled => Enabled && Trace.Value != 0;

		internal static bool StartP1SessionOnStartPlayGame => Enabled && P1StartSessionOnStartPlayGame.Value != 0;

		internal static bool StartP1SessionOnHelperRhythmPlayMidi => Enabled && P1StartSessionOnHelperRhythmPlayMidi.Value != 0;

		internal static bool StartP1SessionOnBattleAddMidi => Enabled && P1StartSessionOnBattleAddMidi.Value != 0;

		internal static bool MuteP1HelperCategoryFromDirectorPlayMidi => Enabled && P1MuteHelperCategoryFromDirectorPlayMidi.Value != 0;

		internal static bool MuteP1BgmCategoryFromDirectorPlayMidi => Enabled && P1MuteBgmCategoryFromDirectorPlayMidi.Value != 0;

		internal static bool MuteP1UnknownMidi0CategoriesFromDirectorPlayMidi => Enabled && P1MuteUnknownMidi0CategoriesFromDirectorPlayMidi.Value != 0;

		internal static bool OnlyMuteMidiIndex0 => P1OnlyMuteMidiIndex0.Value != 0;

		internal static bool MuteP1AddMidiResults => Enabled && P1MuteAddMidiResults.Value != 0;

		internal static bool MuteP1AddMidiBgmCategory => Enabled && P1MuteAddMidiBgmCategory.Value != 0;

		internal static bool MuteP1AddMidiRhythmCategory => Enabled && P1MuteAddMidiRhythmCategory.Value != 0;

		internal static bool MuteP1AddMidiOnlyWhenBattleOrMissionFilename => Enabled && P1MuteAddMidiOnlyWhenBattleOrMissionFilename.Value != 0;

		internal static bool ReapplyP1MuteOnRhythmUpdate => Enabled && P1ReapplyMuteOnRhythmUpdate.Value != 0;

		internal static int MaxP1AddMidiTraceLogs => Math.Max(0, P1MaxAddMidiTraceLogs.Value);

		internal static bool ZeroP1CriPlayDirectRhythmMissionKaesi => Enabled && P1ZeroCriPlayDirectRhythmMissionKaesi.Value != 0;

		internal static bool ZeroP1CriPlayDirectAllRhythm => Enabled && P1ZeroCriPlayDirectAllRhythm.Value != 0;

		internal static bool TraceP1CriPlayDirectRhythm => TraceEnabled && P1TraceCriPlayDirectRhythm.Value != 0;

		internal static int MaxP1CriPlayDirectTraceLogs => Math.Max(0, P1MaxCriPlayDirectTraceLogs.Value);

		internal static bool ExternalThemeEnabled => Enabled && ThemeEnable.Value != 0;

		internal static bool ExternalThemeTraceEnabled => ExternalThemeEnabled && ThemeTrace.Value != 0 && !ReduceLogSpam;

		internal static bool ExternalThemeAutoStartMood0 => ExternalThemeEnabled && ThemeAutoStartMood0OnBattleStart.Value != 0;

		internal static string ExternalThemeDirectory => ThemePathResolver.ResolvePartsDirectory();

		internal static string ExternalThemeLegacyDirectory => ThemeDirectory.Value ?? string.Empty;

		internal static bool ExternalThemeUseNumberedThemeFolders => ExternalThemeEnabled && ThemeUseNumberedThemeFolders.Value != 0;

		internal static string ExternalThemeLibraryRootDirectory => ThemeLibraryRootDirectory.Value ?? string.Empty;

		internal static int ExternalThemeSelectedThemeNumber => Math.Max(0, ThemeSelectedThemeNumber.Value);

		internal static string ExternalThemePartsFolderSuffix => ThemePartsFolderSuffix.Value ?? "Parts";

		internal static string ExternalThemeVoicesFolderSuffix => ThemeVoicesFolderSuffix.Value ?? "Voices";

		internal static string ExternalThemeVoicesDirectory => ThemePathResolver.ResolveVoicesDirectory();

		internal static float ExternalGameScaledVolume => GetCurrentGameMasterVolume() * Math.Max(0f, ExternalAudioGameVolumeFactor.Value);

		internal static float ExternalThemeVolume => ExternalGameScaledVolume * Math.Max(0f, ThemeVolume.Value) * Math.Max(0f, ThemeMasterVolumeScale.Value);

		internal static double ExternalThemeInitialDelaySeconds => Math.Max(0.01, ThemeInitialDelaySeconds.Value);

		internal static double ExternalThemeScheduleLookAheadSeconds => Math.Max(0.02, ThemeScheduleLookAheadSeconds.Value);

		internal static bool ExternalThemeLoadAudioAtPluginStart => ThemeLoadAudioAtPluginStart.Value != 0;

		internal static int ExternalThemePartsPerLoadFrame => Math.Clamp(ThemePartsPerLoadFrame.Value, 1, 28);

		internal static bool ExternalThemeTraceBeforeEachPartLoad => ThemeTraceBeforeEachPartLoad.Value != 0;

		internal static bool ExternalThemeUseDecodeTimeout => ExternalThemeEnabled && ThemeUseDecodeTimeout.Value != 0;

		internal static double ExternalThemeDecodeTimeoutSeconds => Math.Clamp(ThemeDecodeTimeoutSeconds.Value, 0.25, 30.0);

		internal static string ExternalThemeSkipPartNames => ThemeSkipPartNames.Value ?? string.Empty;

		internal static bool ExternalThemeUseFixedPartWindow => ExternalThemeEnabled && ThemeUseFixedPartWindow.Value != 0;

		internal static bool ExternalThemeAnchorFixedWindowClock => ExternalThemeUseFixedPartWindow && ThemeAnchorFixedWindowClock.Value != 0;

		internal static bool ExternalThemeTraceFixedWindowClock => ExternalThemeUseFixedPartWindow && ThemeTraceFixedWindowClock.Value != 0 && !ReduceLogSpam;

		internal static bool ExternalThemeResyncOnP1RhythmBoundary => ExternalThemeUseFixedPartWindow && ThemeResyncOnP1RhythmBoundary.Value != 0;

		internal static bool ExternalThemeTraceRhythmBoundaryResync => ExternalThemeUseFixedPartWindow && ThemeTraceRhythmBoundaryResync.Value != 0 && !ReduceLogSpam;

		internal static bool ExternalThemeFrameStallCompensation => ExternalThemeUseFixedPartWindow && ThemeFrameStallCompensation.Value != 0;

		internal static double ExternalThemeFrameStallThresholdSeconds => Math.Clamp(ThemeFrameStallThresholdSeconds.Value, 0.03, 2.0);

		internal static double ExternalThemeFrameStallMaxCompensationSeconds => Math.Clamp(ThemeFrameStallMaxCompensationSeconds.Value, 0.0, 5.0);

		internal static bool ExternalThemeTraceFrameStallCompensation => ExternalThemeUseFixedPartWindow && ThemeTraceFrameStallCompensation.Value != 0 && !ReduceLogSpam;

		internal static double ExternalThemeFixedPartWindowSeconds => Math.Max(0.25, ThemeFixedPartWindowSeconds.Value);

		internal static double ExternalThemeFixedWindowPhaseOffsetSeconds => Math.Max(0.0, ThemeFixedWindowPhaseOffsetSeconds.Value);

		internal static bool ExternalThemeUseSeparateHelperPhaseOffset => ExternalThemeEnabled && ThemeUseSeparateHelperPhaseOffset.Value != 0;

		internal static double ExternalThemeHelperPhaseOffsetSeconds => Math.Max(0.0, ThemeHelperPhaseOffsetSeconds.Value);

		internal static bool ExternalThemeKeepHelperLoopRunningMuted => ExternalThemeEnabled && ThemeKeepHelperLoopRunningMuted.Value != 0;

		internal static bool ExternalThemeHelperStartsAfterIntroWindow => ExternalThemeEnabled && ThemeHelperStartsAfterIntroWindow.Value != 0;

		internal static bool ExternalThemeAutoMoodFromP1Rhythm => ExternalThemeEnabled && ThemeAutoMoodFromP1Rhythm.Value != 0;

		internal static bool ExternalThemeAutoMoodImmediateSwitch => ThemeAutoMoodImmediateSwitch.Value != 0;

		internal static int ExternalThemeHighMoodMapsTo => Math.Clamp(ThemeHighMoodMapsTo.Value, 0, 3);

		internal static bool ExternalThemeTraceAutoMood => ExternalThemeEnabled && ThemeTraceAutoMood.Value != 0 && !ReduceLogSpam;

		internal static bool ExternalThemeMoodLossSwitchToHelper => ExternalThemeEnabled && ThemeMoodLossSwitchToHelper.Value != 0;

		internal static bool ExternalThemeDetectMoodLossFromRhythmUpdate => ExternalThemeEnabled && ThemeDetectMoodLossFromRhythmUpdate.Value != 0;

		internal static bool ExternalThemeTraceRhythmUpdateMoodLoss => ExternalThemeEnabled && ThemeTraceRhythmUpdateMoodLoss.Value != 0 && !ReduceLogSpam;

		internal static int ExternalThemeMaxRhythmUpdateMoodLossTraceLogs => Math.Max(0, ThemeMaxRhythmUpdateMoodLossTraceLogs.Value);

		internal static bool ExternalThemeStopOnFailedPlayGame => ExternalThemeEnabled && ThemeStopOnFailedPlayGame.Value != 0;

		internal static bool ExternalThemeStopOnStopBattleBgm => ExternalThemeEnabled && ThemeStopOnStopBattleBgm.Value != 0;

		internal static bool ExternalResponsesEnabled => Enabled && ResponseEnable.Value != 0;

		internal static bool MuteOriginalRhythmVoiceResponses => ExternalResponsesEnabled && ResponseMuteOriginalRhythmVoice.Value != 0;

		internal static bool PlayCustomResponses => ExternalResponsesEnabled && ResponsePlayCustomResponses.Value != 0;

		internal static bool ResponsePlayFirstLoadedAsFallbackEnabled => ExternalResponsesEnabled && ResponsePlayFirstLoadedAsFallback.Value != 0;

		internal static bool ExternalResponseSuppressUnmappedFallback => ExternalResponsesEnabled && ResponseSuppressUnmappedFallback.Value != 0;

		internal static string ResponseTestCueNameText => ResponseTestCueName.Value ?? string.Empty;

		internal static float ExternalResponseVolume => ExternalGameScaledVolume * Math.Max(0f, ResponseVolume.Value) * Math.Max(0f, ResponseMasterVolumeScale.Value);

		internal static double ExternalResponseDebounceSeconds => Math.Max(0.0, ResponseDebounceSeconds.Value);

		internal static double ExternalResponseDelaySeconds => Math.Clamp(ResponseDelaySeconds.Value, 0.0, 2.0);

		internal static bool TraceOriginalRhythmVoiceResponses => ExternalResponsesEnabled && ResponseTraceOriginalRhythmVoice.Value != 0 && !ReduceLogSpam;

		internal static int MaxResponseTraceLogs => Math.Max(0, ResponseMaxTraceLogs.Value);

		internal static string ExternalResponseMiscVoicesDirectoryText => ResponseMiscVoicesDirectory.Value ?? string.Empty;

		internal static string ExternalResponseMiscVoicesDirectory => ThemePathResolver.ResolveMiscVoicesDirectory();

		internal static string ExternalResponseMiscVoiceNumberPrefix => string.IsNullOrWhiteSpace(ResponseMiscVoiceNumberPrefix.Value) ? "00" : ResponseMiscVoiceNumberPrefix.Value.Trim();

		internal static bool ExternalResponseCommandDetectionEnabled => ExternalResponsesEnabled && ResponseUseCommandDetection.Value != 0;

		internal static double ExternalResponseCommandMaxAgeSeconds => Math.Clamp(ResponseCommandMaxAgeSeconds.Value, 0.1, 30.0);

		internal static bool ExternalResponseTraceCommandDetection => ExternalResponsesEnabled && ResponseTraceCommandDetection.Value != 0 && !ReduceLogSpam;

		internal static int ExternalResponseMaxCommandTraceLogs => Math.Max(0, ResponseMaxCommandTraceLogs.Value);

		internal static int ExternalResponseCommandSummaryMaxChars => Math.Clamp(ResponseCommandSummaryMaxChars.Value, 1000, 20000);

		internal static string ExternalResponseP1EvadeCommandMapsTo
		{
			get
			{
				string text = (ResponseP1EvadeMapsTo.Value ?? "Defend").Trim();
				return text.Equals("Retreat", StringComparison.OrdinalIgnoreCase) ? "Retreat" : "Defend";
			}
		}

		internal static bool ReduceLogSpam => PerformanceReduceLogSpam.Value != 0 || PerformanceForceGameplayQuietMode.Value != 0;

		public override void Load()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Expected O, but got Unknown
			L = ((BasePlugin)this).Log;
			_instance = this;
			try
			{
				BindConfig();
				ManualLogSource l = L;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(8, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Patapon Music Menu Manual Mood Prototype");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("0.4.6");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded");
				}
				l.LogInfo(val);
				LogConfig();
				ExternalThemeSequencer.Initialize();
				H = new Harmony("juras.patapon.musicmenu.manualmood");
				H.PatchAll(Assembly.GetExecutingAssembly());
				LogPatchedMethods();
			}
			catch (Exception ex)
			{
				L.LogError((object)"Plugin load failed:");
				L.LogError((object)ex);
			}
		}

		private void BindConfig()
		{
			string text = Path.Combine(Paths.PluginPath, "PataponMusicMenu", "Themes");
			string value = Path.Combine(text, "Default");
			ThemeLibraryRootDirectory = BindVisible("ExternalTheme.ThemeSelection", "ThemeLibraryRootDirectory", text, "Root folder containing numbered theme folders, e.g. Themes/36ThemeName/36Parts and Themes/36ThemeName/36Voices.");
			ThemeSelectedThemeNumber = BindVisible("ExternalTheme.ThemeSelection", "SelectedThemeNumber", 36, "Theme number to load. Numbers below 10 are zero-padded, so 2 means 02ThemeName/02Parts/02Voices.");
			ExternalAudioGameVolumeFactor = BindVisible("ExternalAudio", "GameVolumeFactor", 0.1f, "External audio multiplier applied to the current in-game master volume. Example: game volume 0.5 and factor 0.1 => external volume 0.05.");
			ThemeVolume = BindVisible("ExternalTheme", "Volume", 1f, "Extra multiplier for external theme music after the game volume factor.");
			ResponseVolume = BindVisible("ExternalResponses", "Volume", 1f, "Extra multiplier for custom response voices after the game volume factor.");
			ThemeMasterVolumeScale = Fixed(1f);
			ResponseMasterVolumeScale = Fixed(1f);
			Enable = Fixed(1);
			Trace = Fixed(0);
			P1StartSessionOnStartPlayGame = Fixed(0);
			P1StartSessionOnHelperRhythmPlayMidi = Fixed(1);
			P1StartSessionOnBattleAddMidi = Fixed(1);
			P1MuteHelperCategoryFromDirectorPlayMidi = Fixed(1);
			P1MuteBgmCategoryFromDirectorPlayMidi = Fixed(1);
			P1MuteUnknownMidi0CategoriesFromDirectorPlayMidi = Fixed(0);
			P1OnlyMuteMidiIndex0 = Fixed(1);
			P1MuteAddMidiResults = Fixed(1);
			P1MuteAddMidiBgmCategory = Fixed(1);
			P1MuteAddMidiRhythmCategory = Fixed(1);
			P1MuteAddMidiOnlyWhenBattleOrMissionFilename = Fixed(1);
			P1ReapplyMuteOnRhythmUpdate = Fixed(0);
			P1MaxAddMidiTraceLogs = Fixed(0);
			P1ZeroCriPlayDirectRhythmMissionKaesi = Fixed(1);
			P1ZeroCriPlayDirectAllRhythm = Fixed(0);
			P1TraceCriPlayDirectRhythm = Fixed(0);
			P1MaxCriPlayDirectTraceLogs = Fixed(0);
			ThemeEnable = Fixed(1);
			ThemeDirectory = Fixed(value);
			ThemeUseNumberedThemeFolders = Fixed(1);
			ThemePartsFolderSuffix = Fixed("Parts");
			ThemeVoicesFolderSuffix = Fixed("Voices");
			ThemeTrace = Fixed(0);
			ThemeAutoStartMood0OnBattleStart = Fixed(1);
			ThemeInitialDelaySeconds = Fixed(0.1);
			ThemeScheduleLookAheadSeconds = Fixed(0.2);
			ThemeLoadAudioAtPluginStart = Fixed(0);
			ThemePartsPerLoadFrame = Fixed(1);
			ThemeTraceBeforeEachPartLoad = Fixed(0);
			ThemeUseDecodeTimeout = Fixed(1);
			ThemeDecodeTimeoutSeconds = Fixed(2.5);
			ThemeSkipPartNames = Fixed("");
			ThemeUseFixedPartWindow = Fixed(1);
			ThemeAnchorFixedWindowClock = Fixed(1);
			ThemeTraceFixedWindowClock = Fixed(0);
			ThemeResyncOnP1RhythmBoundary = Fixed(1);
			ThemeTraceRhythmBoundaryResync = Fixed(0);
			ThemeFrameStallCompensation = Fixed(1);
			ThemeFrameStallThresholdSeconds = Fixed(0.12);
			ThemeFrameStallMaxCompensationSeconds = Fixed(0.5);
			ThemeTraceFrameStallCompensation = Fixed(0);
			ThemeFixedPartWindowSeconds = Fixed(4.0);
			ThemeFixedWindowPhaseOffsetSeconds = Fixed(0.05);
			ThemeUseSeparateHelperPhaseOffset = Fixed(1);
			ThemeHelperPhaseOffsetSeconds = Fixed(0.4);
			ThemeKeepHelperLoopRunningMuted = Fixed(1);
			ThemeHelperStartsAfterIntroWindow = Fixed(1);
			ThemeAutoMoodFromP1Rhythm = Fixed(1);
			ThemeAutoMoodImmediateSwitch = Fixed(1);
			ThemeHighMoodMapsTo = Fixed(3);
			ThemeTraceAutoMood = Fixed(0);
			ThemeMoodLossSwitchToHelper = Fixed(1);
			ThemeDetectMoodLossFromRhythmUpdate = Fixed(1);
			ThemeTraceRhythmUpdateMoodLoss = Fixed(0);
			ThemeMaxRhythmUpdateMoodLossTraceLogs = Fixed(0);
			ThemeStopOnFailedPlayGame = Fixed(1);
			ThemeStopOnStopBattleBgm = Fixed(1);
			ResponseEnable = Fixed(1);
			ResponseMuteOriginalRhythmVoice = Fixed(1);
			ResponsePlayCustomResponses = Fixed(1);
			ResponsePlayFirstLoadedAsFallback = Fixed(1);
			ResponseSuppressUnmappedFallback = Fixed(1);
			ResponseTestCueName = Fixed("");
			ResponseDebounceSeconds = Fixed(0.12);
			ResponseDelaySeconds = Fixed(0.05);
			ResponseTraceOriginalRhythmVoice = Fixed(0);
			ResponseMaxTraceLogs = Fixed(0);
			ResponseMiscVoicesDirectory = Fixed("");
			ResponseMiscVoiceNumberPrefix = Fixed("00");
			ResponseUseCommandDetection = Fixed(1);
			ResponseCommandMaxAgeSeconds = Fixed(6.0);
			ResponseTraceCommandDetection = Fixed(0);
			ResponseMaxCommandTraceLogs = Fixed(0);
			ResponseCommandSummaryMaxChars = Fixed(6000);
			ResponseP1EvadeMapsTo = Fixed("Retreat");
			PerformanceReduceLogSpam = Fixed(1);
			PerformanceForceGameplayQuietMode = Fixed(1);
			PruneOldConfigEntries();
		}

		private void PruneOldConfigEntries()
		{
			try
			{
				object obj = ((object)((BasePlugin)this).Config).GetType().GetProperty("OrphanedEntries")?.GetValue(((BasePlugin)this).Config);
				if (obj is IDictionary dictionary && dictionary.Count > 0)
				{
					dictionary.Clear();
					((BasePlugin)this).Config.Save();
				}
			}
			catch
			{
			}
		}

		private RuntimeSetting<T> BindVisible<T>(string section, string key, T defaultValue, string description)
		{
			return new RuntimeSetting<T>(((BasePlugin)this).Config.Bind<T>(section, key, defaultValue, description));
		}

		private static RuntimeSetting<T> Fixed<T>(T value)
		{
			return new RuntimeSetting<T>(value);
		}

		private static void LogConfig()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			ManualLogSource l = L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(27, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ThemeLibraryRootDirectory: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ThemeLibraryRootDirectory.Value);
			}
			l.LogInfo(val);
			ManualLogSource l2 = L;
			val = new BepInExInfoLogInterpolatedStringHandler(21, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("SelectedThemeNumber: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(ThemeSelectedThemeNumber.Value);
			}
			l2.LogInfo(val);
			ManualLogSource l3 = L;
			val = new BepInExInfoLogInterpolatedStringHandler(32, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ExternalAudio.GameVolumeFactor: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(ExternalAudioGameVolumeFactor.Value);
			}
			l3.LogInfo(val);
			ManualLogSource l4 = L;
			val = new BepInExInfoLogInterpolatedStringHandler(22, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ExternalTheme.Volume: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(ThemeVolume.Value);
			}
			l4.LogInfo(val);
			ManualLogSource l5 = L;
			val = new BepInExInfoLogInterpolatedStringHandler(26, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("ExternalResponses.Volume: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(ResponseVolume.Value);
			}
			l5.LogInfo(val);
		}

		private static void LogPatchedMethods()
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			if (H == null)
			{
				return;
			}
			int num = 0;
			foreach (MethodBase patchedMethod in H.GetPatchedMethods())
			{
				T("Patched method: " + patchedMethod.DeclaringType?.FullName + "." + patchedMethod.Name);
				num++;
			}
			ManualLogSource l = L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(27, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Harmony patches owned by ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("juras.patapon.musicmenu.manualmood");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
			}
			l.LogInfo(val);
		}

		internal static void SetSelectedThemeNumber(int number)
		{
			number = Math.Clamp(number, 1, 99);
			ThemeSelectedThemeNumber.Value = number;
			try
			{
				Plugin? instance = _instance;
				if (instance != null)
				{
					((BasePlugin)instance).Config.Save();
				}
			}
			catch
			{
			}
		}

		private static float GetCurrentGameMasterVolume()
		{
			double num = 0.0;
			try
			{
				num = Time.realtimeSinceStartup;
			}
			catch
			{
			}
			if (num > 0.0 && num - _lastGameMasterVolumeSampleTime < 0.25)
			{
				return _cachedGameMasterVolume;
			}
			_lastGameMasterVolumeSampleTime = num;
			try
			{
				CriSoundManager val = _cachedCriSoundManager;
				if ((Object)(object)val == (Object)null)
				{
					val = Object.FindObjectOfType<CriSoundManager>();
					if ((Object)(object)val != (Object)null)
					{
						_cachedCriSoundManager = val;
					}
				}
				if ((Object)(object)val != (Object)null)
				{
					float masterVolume = val.MasterVolume;
					if (!float.IsNaN(masterVolume) && !float.IsInfinity(masterVolume))
					{
						_cachedGameMasterVolume = Math.Clamp(masterVolume, 0f, 1f);
					}
				}
			}
			catch
			{
			}
			return _cachedGameMasterVolume;
		}

		internal static void T(string message)
		{
			if (TraceEnabled)
			{
				L.LogInfo((object)message);
			}
		}

		internal static void ThemeT(string message)
		{
			if (ExternalThemeTraceEnabled)
			{
				L.LogInfo((object)message);
			}
		}

		internal static void W(string message)
		{
			L.LogWarning((object)message);
		}
	}
	internal static class P1OriginalThemeMuteState
	{
		public const uint MuteMask = uint.MaxValue;

		private static readonly List<BgmPlayer> CapturedPlayers = new List<BgmPlayer>();

		private static BgmPlayer? OriginalHelperPlayer;

		private static bool _originalHelperCaptured;

		private static bool _originalHelperHasPlayed;

		private static double _lastOriginalHelperPlayingTime = -999.0;

		private static bool _lastOriginalHelperPollWasPlaying;

		private const double OriginalHelperInactiveGraceSeconds = 0.35;

		public static bool BattleActive { get; private set; }

		public static bool OriginalHelperAllowsExternalAudio
		{
			get
			{
				if (!BattleActive)
				{
					return false;
				}
				if (!_originalHelperCaptured || OriginalHelperPlayer == null)
				{
					return true;
				}
				if (ObserveOriginalHelperPlayback("helper gate poll"))
				{
					return true;
				}
				if (!_originalHelperHasPlayed)
				{
					return true;
				}
				double num = Time.realtimeSinceStartup;
				return num - _lastOriginalHelperPlayingTime <= 0.35;
			}
		}

		public static void StartBattle(string source)
		{
			if (BattleActive)
			{
				Plugin.T("[P1 THEME MUTE] start ignored because already active from " + source);
				ReapplyMute(source + " already-active start");
			}
			else
			{
				BattleActive = true;
				Plugin.T("[P1 THEME MUTE] mute session active from " + source);
				ExternalThemeSequencer.OnBattleStart(source);
			}
		}

		public static void Reset(string source)
		{
			if (CapturedPlayers.Count > 0)
			{
				foreach (BgmPlayer capturedPlayer in CapturedPlayers)
				{
					try
					{
						if (capturedPlayer != null)
						{
							capturedPlayer.setMute(0u);
						}
					}
					catch (Exception ex)
					{
						Plugin.W("[P1 THEME MUTE] unmute failed during reset from " + source + ": " + ex.Message);
					}
				}
			}
			CapturedPlayers.Clear();
			OriginalHelperPlayer = null;
			_originalHelperCaptured = false;
			_originalHelperHasPlayed = false;
			_lastOriginalHelperPlayingTime = -999.0;
			_lastOriginalHelperPollWasPlaying = false;
			BattleActive = false;
			Plugin.T("[P1 THEME MUTE] reset from " + source);
			ExternalThemeSequencer.OnBattleEnd(source);
		}

		public static void CaptureAndMute(BgmPlayer? player, string slot, string source)
		{
			if (!BattleActive)
			{
				return;
			}
			if (player == null)
			{
				Plugin.W($"[P1 THEME MUTE] wanted to mute {slot} from {source}, but player is null");
				return;
			}
			try
			{
				if (!CapturedPlayers.Contains(player))
				{
					CapturedPlayers.Add(player);
				}
				player.setMute(uint.MaxValue);
				Plugin.T($"[P1 THEME MUTE] MUTED {slot} from {source}; " + DescribePlayer(player));
			}
			catch (Exception value)
			{
				Plugin.W($"[P1 THEME MUTE] failed to mute {slot} from {source}: {value}");
			}
		}

		public static void CaptureAndMuteHelper(BgmPlayer? player, string slot, string source)
		{
			if (player != null)
			{
				OriginalHelperPlayer = player;
				_originalHelperCaptured = true;
				ObserveOriginalHelperPlayback(source + " helper capture");
				ExternalThemeSequencer.OnOriginalHelperPlaybackAnchor(source + " helper capture");
			}
			CaptureAndMute(player, slot, source);
		}

		private static bool ObserveOriginalHelperPlayback(string source)
		{
			try
			{
				BgmPlayer originalHelperPlayer = OriginalHelperPlayer;
				if (originalHelperPlayer == null)
				{
					return false;
				}
				bool flag = originalHelperPlayer.isPlay();
				if (flag)
				{
					_originalHelperHasPlayed = true;
					_lastOriginalHelperPlayingTime = Time.realtimeSinceStartup;
					if (!_lastOriginalHelperPollWasPlaying)
					{
						ExternalThemeSequencer.OnOriginalHelperPlaybackAnchor(source + " helper resumed");
					}
				}
				_lastOriginalHelperPollWasPlaying = flag;
				return flag;
			}
			catch (Exception ex)
			{
				Plugin.T("[P1 THEME MUTE] helper playback poll failed from " + source + ": " + ex.Message);
				return true;
			}
		}

		public static void CaptureAndMuteObject(object? obj, string slot, string source)
		{
			if (!BattleActive || obj == null)
			{
				return;
			}
			BgmPlayer val = (BgmPlayer)((obj is BgmPlayer) ? obj : null);
			if (val != null)
			{
				CaptureAndMute(val, slot, source);
				return;
			}
			try
			{
				Type type = obj.GetType();
				string text = type.FullName ?? type.Name;
				if (text.IndexOf("Sound", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Player", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Bgm", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Rhythm", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					MethodInfo methodInfo = FindSetMuteMethod(type);
					if (!(methodInfo == null))
					{
						object obj2 = ((methodInfo.GetParameters()[0].ParameterType == typeof(int)) ? ((object)(-1)) : ((object)uint.MaxValue));
						methodInfo.Invoke(obj, new object[1] { obj2 });
						Plugin.T($"[P1 THEME MUTE] MUTED generic {slot} from {source}; objectType={text}, method={methodInfo.Name}");
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.W($"[P1 THEME MUTE] generic mute failed for {slot} from {source}: {ex.Message}");
			}
		}

		private static MethodInfo? FindSetMuteMethod(Type t)
		{
			try
			{
				MethodInfo[] methods = t.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (!string.Equals(methodInfo.Name, "setMute", StringComparison.Ordinal))
					{
						continue;
					}
					ParameterInfo[] parameters = methodInfo.GetParameters();
					if (parameters.Length == 1)
					{
						Type parameterType = parameters[0].ParameterType;
						if (parameterType == typeof(uint) || parameterType == typeof(int))
						{
							return methodInfo;
						}
					}
				}
			}
			catch
			{
			}
			return null;
		}

		public static void ReapplyMute(string source)
		{
			if (!BattleActive || CapturedPlayers.Count == 0)
			{
				return;
			}
			foreach (BgmPlayer capturedPlayer in CapturedPlayers)
			{
				try
				{
					if (capturedPlayer != null)
					{
						capturedPlayer.setMute(uint.MaxValue);
					}
				}
				catch (Exception ex)
				{
					Plugin.W("[P1 THEME MUTE] reapply failed from " + source + ": " + ex.Message);
				}
			}
		}

		public static string DescribePlayer(BgmPlayer? player)
		{
			if (player == null)
			{
				return "player=null";
			}
			try
			{
				return $"playId={player.playId_}, rid={player.getRID()}, vol={player.getVolumeValue()}, targetVol={player.getTargetVolume()}, isPlay={player.isPlay()}";
			}
			catch (Exception ex)
			{
				return "player-info-failed=" + ex.Message;
			}
		}
	}
	[HarmonyPatch(typeof(Director), "startPlayGame")]
	internal static class P1ThemeMuteStartPlayGamePatch
	{
		private static void Prefix(Director __instance)
		{
			if (Plugin.StartP1SessionOnStartPlayGame)
			{
				P1OriginalThemeMuteState.StartBattle("Director.startPlayGame");
			}
		}
	}
	[HarmonyPatch(typeof(Director), "exitPlayGame")]
	internal static class P1ThemeMuteExitPlayGamePatch
	{
		private static void Prefix()
		{
			if (Plugin.Enabled)
			{
				P1OriginalThemeMuteState.Reset("Director.exitPlayGame");
			}
		}
	}
	[HarmonyPatch(typeof(Director), "playMidi")]
	internal static class P1ThemeMutePlayMidiPatch
	{
		private static void Postfix(Director __instance, int midiIndex, MixingCategory cate, float fadeTime)
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Invalid comparison between Unknown and I4
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Invalid comparison between Unknown and I4
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0226: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Enabled)
			{
				return;
			}
			try
			{
				string value = P1OriginalThemeMuteState.DescribePlayer(__instance.curPlayer_);
				Plugin.T($"[P1 THEME MUTE] playMidi observed: battleActive={P1OriginalThemeMuteState.BattleActive}, midiIndex={midiIndex}, cate={cate}, fadeTime={fadeTime}, {value}");
				bool flag = (int)cate == 4;
				bool flag2 = (int)cate == 3;
				if (Plugin.OnlyMuteMidiIndex0 && midiIndex != 0)
				{
					return;
				}
				if (!P1OriginalThemeMuteState.BattleActive && Plugin.StartP1SessionOnHelperRhythmPlayMidi && midiIndex == 0 && flag)
				{
					P1OriginalThemeMuteState.StartBattle($"Director.playMidi({midiIndex}, {cate}) helper/Rhythm auto-start");
				}
				if (P1OriginalThemeMuteState.BattleActive)
				{
					if (flag && Plugin.MuteP1HelperCategoryFromDirectorPlayMidi)
					{
						P1OriginalThemeMuteState.CaptureAndMuteHelper(__instance.curPlayer_, "Director.playMidi helper/Rhythm category", $"Director.playMidi({midiIndex}, {cate})");
					}
					else if (flag2 && Plugin.MuteP1BgmCategoryFromDirectorPlayMidi)
					{
						P1OriginalThemeMuteState.CaptureAndMute(__instance.curPlayer_, "Director.playMidi mood/BGM category", $"Director.playMidi({midiIndex}, {cate})");
					}
					else if (midiIndex == 0 && !flag && !flag2 && Plugin.MuteP1UnknownMidi0CategoriesFromDirectorPlayMidi)
					{
						P1OriginalThemeMuteState.CaptureAndMute(__instance.curPlayer_, "Director.playMidi unknown midiIndex 0 category", $"Director.playMidi({midiIndex}, {cate})");
					}
				}
			}
			catch (Exception value2)
			{
				Plugin.W($"[P1 THEME MUTE] Director.playMidi postfix failed: {value2}");
			}
		}
	}
	[HarmonyPatch(typeof(Rhythm), "update")]
	internal static class P1ThemeMuteRhythmUpdatePatch
	{
		private static void Postfix(Rhythm __instance)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (Plugin.ReapplyP1MuteOnRhythmUpdate)
			{
				P1OriginalThemeMuteState.ReapplyMute("Rhythm.update");
			}
			if (!Plugin.ExternalThemeDetectMoodLossFromRhythmUpdate || !P1OriginalThemeMuteState.BattleActive)
			{
				return;
			}
			try
			{
				string lastMoodText;
				try
				{
					object obj;
					if (__instance == null)
					{
						obj = null;
					}
					else
					{
						Mood lastMood_ = __instance.lastMood_;
						obj = ((object)(Mood)(ref lastMood_)).ToString();
					}
					if (obj == null)
					{
						obj = "rhythm=null";
					}
					lastMoodText = (string)obj;
				}
				catch (Exception ex)
				{
					lastMoodText = "lastMood-error=" + ex.Message;
				}
				uint playCount;
				try
				{
					playCount = ((__instance != null) ? __instance.playCount_ : 0u);
				}
				catch
				{
					playCount = 0u;
				}
				uint playSeIndex;
				try
				{
					playSeIndex = ((__instance != null) ? __instance.playSEIndex_ : uint.MaxValue);
				}
				catch
				{
					playSeIndex = uint.MaxValue;
				}
				bool isPlay;
				try
				{
					isPlay = __instance != null && __instance.isPlay_;
				}
				catch
				{
					isPlay = false;
				}
				ExternalThemeSequencer.OnP1RhythmUpdateObserved(lastMoodText, playCount, playSeIndex, isPlay, "P1.Sound.Rhythm.update");
			}
			catch (Exception ex2)
			{
				Plugin.W("[EXT THEME AUTO] Rhythm.update observer failed: " + ex2.Message);
			}
		}
	}
	[HarmonyPatch]
	[HarmonyPriority(0)]
	internal static class P1BgmPlayersAddMidiMutePatch
	{
		private sealed class AddMidiInfo
		{
			public MixingCategory? Category;

			public string BgmTypeText = "";

			public string FilenameText = "";

			public string ArgsText = "";

			public string MidiIdText = "";

			public string SubGameTypeText = "";

			public bool IsBattleType => BgmTypeText.IndexOf("Battle", StringComparison.OrdinalIgnoreCase) >= 0;

			public bool IsMissionFilename
			{
				get
				{
					string text = FilenameText.Trim().ToLowerInvariant();
					return text.StartsWith("missionid_") || text.Contains("/missionid_");
				}
			}

			public bool IsSubGameMidiCandidate
			{
				get
				{
					if (MidiIdText.IndexOf("SubGame", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						return true;
					}
					if (ArgsText.IndexOf("MidiId_SubGame", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						return true;
					}
					return SubGameTypeText.IndexOf("SubGameType_", StringComparison.OrdinalIgnoreCase) >= 0 && SubGameTypeText.IndexOf("SubGameType_None", StringComparison.OrdinalIgnoreCase) < 0;
				}
			}

			public bool HasBattleMetadata => !string.IsNullOrWhiteSpace(BgmTypeText) || !string.IsNullOrWhiteSpace(FilenameText);

			public bool IsNonBattleBgmWithMetadata => (int)Category.GetValueOrDefault() == 3 && HasBattleMetadata && !IsBattleType && !IsMissionFilename;

			public static AddMidiInfo From(MethodBase method, object[] args)
			{
				//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
				//IL_0102: Unknown result type (might be due to invalid IL or missing references)
				AddMidiInfo addMidiInfo = new AddMidiInfo();
				ParameterInfo[] parameters = method.GetParameters();
				List<string> list = new List<string>();
				for (int i = 0; i < args.Length; i++)
				{
					object obj = args[i];
					string text = ((i < parameters.Length) ? (parameters[i].Name ?? $"arg{i}") : $"arg{i}");
					string text2 = ((i < parameters.Length) ? (parameters[i].ParameterType.FullName ?? parameters[i].ParameterType.Name) : (obj?.GetType().FullName ?? "unknown"));
					string text3 = SafeToString(obj);
					list.Add(text + "=" + text3);
					if (obj is MixingCategory value)
					{
						addMidiInfo.Category = value;
					}
					if (text2.IndexOf("BgmType", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						addMidiInfo.BgmTypeText = text3;
					}
					if (text2.IndexOf("MidiId", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						addMidiInfo.MidiIdText = text3;
					}
					if (text2.IndexOf("SubGameType", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						addMidiInfo.SubGameTypeText = text3;
					}
					if (obj is string filenameText)
					{
						addMidiInfo.FilenameText = filenameText;
					}
				}
				addMidiInfo.ArgsText = string.Join(", ", list);
				return addMidiInfo;
			}

			public override string ToString()
			{
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(63, 6);
				defaultInterpolatedStringHandler.AppendLiteral("cate=");
				object value;
				if (!Category.HasValue)
				{
					value = "<none>";
				}
				else
				{
					MixingCategory value2 = Category.Value;
					value = ((object)(MixingCategory)(ref value2)).ToString();
				}
				defaultInterpolatedStringHandler.AppendFormatted((string?)value);
				defaultInterpolatedStringHandler.AppendLiteral(", ");
				defaultInterpolatedStringHandler.AppendLiteral("type='");
				defaultInterpolatedStringHandler.AppendFormatted(Escape(BgmTypeText));
				defaultInterpolatedStringHandler.AppendLiteral("', midiId='");
				defaultInterpolatedStringHandler.AppendFormatted(Escape(MidiIdText));
				defaultInterpolatedStringHandler.AppendLiteral("', ");
				defaultInterpolatedStringHandler.AppendLiteral("subGameType='");
				defaultInterpolatedStringHandler.AppendFormatted(Escape(SubGameTypeText));
				defaultInterpolatedStringHandler.AppendLiteral("', filename='");
				defaultInterpolatedStringHandler.AppendFormatted(Escape(FilenameText));
				defaultInterpolatedStringHandler.AppendLiteral("', ");
				defaultInterpolatedStringHandler.AppendLiteral("args=[");
				defaultInterpolatedStringHandler.AppendFormatted(ArgsText);
				defaultInterpolatedStringHandler.AppendLiteral("]");
				return defaultInterpolatedStringHandler.ToStringAndClear();
			}

			private static string SafeToString(object? value)
			{
				if (value == null)
				{
					return "null";
				}
				try
				{
					return value.ToString() ?? "";
				}
				catch
				{
					return "<ToString failed>";
				}
			}

			private static string Escape(string value)
			{
				return (value ?? "").Replace("\r", "\\r").Replace("\n", "\\n");
			}
		}

		[CompilerGenerated]
		private sealed class <TargetMethods>d__1 : IEnumerable<MethodBase>, IEnumerable, IEnumerator<MethodBase>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private MethodBase <>2__current;

			private int <>l__initialThreadId;

			private Type <type>5__1;

			private MethodInfo[] <>s__2;

			private int <>s__3;

			private MethodInfo <method>5__4;

			MethodBase IEnumerator<MethodBase>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <TargetMethods>d__1(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<type>5__1 = null;
				<>s__2 = null;
				<method>5__4 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				int num = <>1__state;
				if (num != 0)
				{
					if (num != 1)
					{
						return false;
					}
					<>1__state = -1;
					goto IL_0096;
				}
				<>1__state = -1;
				<type>5__1 = typeof(BgmPlayers);
				<>s__2 = <type>5__1.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				<>s__3 = 0;
				goto IL_00ac;
				IL_0096:
				<method>5__4 = null;
				<>s__3++;
				goto IL_00ac;
				IL_00ac:
				if (<>s__3 < <>s__2.Length)
				{
					<method>5__4 = <>s__2[<>s__3];
					if (<method>5__4.Name == "addMidi")
					{
						<>2__current = <method>5__4;
						<>1__state = 1;
						return true;
					}
					goto IL_0096;
				}
				<>s__2 = null;
				return false;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<MethodBase> IEnumerable<MethodBase>.GetEnumerator()
			{
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					return this;
				}
				return new <TargetMethods>d__1(0);
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<MethodBase>)this).GetEnumerator();
			}
		}

		private static int _traceCount;

		[IteratorStateMachine(typeof(<TargetMethods>d__1))]
		private static IEnumerable<MethodBase> TargetMethods()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <TargetMethods>d__1(-2);
		}

		private static void Postfix(MethodBase __originalMethod, object? __result, object[] __args)
		{
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Invalid comparison between Unknown and I4
			if (!Plugin.Enabled)
			{
				return;
			}
			try
			{
				AddMidiInfo addMidiInfo = AddMidiInfo.From(__originalMethod, __args);
				BgmPlayer val = (BgmPlayer)((__result is BgmPlayer) ? __result : null);
				TraceAddMidi(__originalMethod, addMidiInfo, val, __result);
				if (addMidiInfo.IsSubGameMidiCandidate)
				{
					if (P1OriginalThemeMuteState.BattleActive)
					{
						P1OriginalThemeMuteState.Reset($"BgmPlayers.addMidi subgame MIDI; {addMidiInfo}");
					}
					return;
				}
				if (P1OriginalThemeMuteState.BattleActive && addMidiInfo.IsNonBattleBgmWithMetadata)
				{
					P1OriginalThemeMuteState.Reset($"BgmPlayers.addMidi non-battle BGM; {addMidiInfo}");
					return;
				}
				bool flag = ShouldMute(addMidiInfo);
				if (!P1OriginalThemeMuteState.BattleActive && Plugin.StartP1SessionOnBattleAddMidi && flag && ShouldStartBattleFromAddMidi(addMidiInfo))
				{
					P1OriginalThemeMuteState.StartBattle($"BgmPlayers.addMidi battle marker before Director.playMidi; {addMidiInfo}");
				}
				if (Plugin.MuteP1AddMidiResults && P1OriginalThemeMuteState.BattleActive && flag)
				{
					if (val == null)
					{
						Plugin.W($"[P1 THEME MUTE] addMidi candidate matched but result is not P1.System.Sound.BgmPlayer; resultType={__result?.GetType().FullName ?? "null"}; {addMidiInfo}");
					}
					else if ((int)addMidiInfo.Category.GetValueOrDefault() == 4)
					{
						P1OriginalThemeMuteState.CaptureAndMuteHelper(val, "BgmPlayers.addMidi helper/Rhythm result", $"{DescribeMethod(__originalMethod)}; {addMidiInfo}");
					}
					else
					{
						P1OriginalThemeMuteState.CaptureAndMute(val, "BgmPlayers.addMidi result", $"{DescribeMethod(__originalMethod)}; {addMidiInfo}");
					}
				}
			}
			catch (Exception value)
			{
				Plugin.W($"[P1 THEME MUTE] BgmPlayers.addMidi postfix failed: {value}");
			}
		}

		private static bool ShouldStartBattleFromAddMidi(AddMidiInfo info)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Invalid comparison between Unknown and I4
			if (info.IsSubGameMidiCandidate)
			{
				return false;
			}
			if (info.IsMissionFilename)
			{
				return true;
			}
			return (int)info.Category.GetValueOrDefault() == 4 && info.IsBattleType;
		}

		private static bool ShouldMute(AddMidiInfo info)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Invalid comparison between Unknown and I4
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between Unknown and I4
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Invalid comparison between Unknown and I4
			if (info.IsSubGameMidiCandidate)
			{
				return false;
			}
			if (((int)info.Category.GetValueOrDefault() != 3 || !Plugin.MuteP1AddMidiBgmCategory) && ((int)info.Category.GetValueOrDefault() != 4 || !Plugin.MuteP1AddMidiRhythmCategory))
			{
				return false;
			}
			if (!Plugin.MuteP1AddMidiOnlyWhenBattleOrMissionFilename)
			{
				return true;
			}
			if ((int)info.Category.GetValueOrDefault() == 3)
			{
				return info.IsMissionFilename;
			}
			return info.IsBattleType || info.IsMissionFilename;
		}

		private static void TraceAddMidi(MethodBase method, AddMidiInfo info, BgmPlayer? player, object? rawResult)
		{
			if (Plugin.TraceEnabled && _traceCount < Plugin.MaxP1AddMidiTraceLogs)
			{
				_traceCount++;
				string value = ((player != null) ? P1OriginalThemeMuteState.DescribePlayer(player) : ("resultType=" + (rawResult?.GetType().FullName ?? "null")));
				Plugin.T($"[P1 THEME MUTE] addMidi observed: battleActive={P1OriginalThemeMuteState.BattleActive}, method={DescribeMethod(method)}, {info}, {value}");
			}
		}

		private static string DescribeMethod(MethodBase method)
		{
			try
			{
				ParameterInfo[] parameters = method.GetParameters();
				return method.DeclaringType?.FullName + "." + method.Name + "(" + string.Join(", ", parameters.Select((ParameterInfo p) => p.ParameterType.Name + " " + p.Name)) + ")";
			}
			catch
			{
				return method.DeclaringType?.FullName + "." + method.Name;
			}
		}
	}
	[HarmonyPatch]
	[HarmonyPriority(800)]
	internal static class P1CriPlayDirectMutePatch
	{
		private static int _traceCount;

		private static MethodBase TargetMethod()
		{
			return AccessTools.DeclaredMethod(typeof(CriSoundManager), "playDirect", new Type[12]
			{
				typeof(SoundGameFileType),
				typeof(MixingCategory),
				typeof(string),
				typeof(string),
				typeof(uint),
				typeof(int),
				typeof(int),
				typeof(int),
				typeof(float),
				typeof(float),
				typeof(float),
				typeof(bool)
			}, (Type[])null);
		}

		private static void Prefix(SoundGameFileType fileType, MixingCategory category, string acbFilePath, string key, uint incrementGlobalCounter, int prog, int rgndCueId, int waveRefIndex, float pitch, float pan, ref float volume, bool loop)
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Invalid comparison between Unknown and I4
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Enabled)
			{
				return;
			}
			try
			{
				if (!P1OriginalThemeMuteState.BattleActive)
				{
					return;
				}
				string text = acbFilePath ?? string.Empty;
				string text2 = key ?? string.Empty;
				float num = volume;
				if (IsRhythmVoiceCategory(category))
				{
					ExternalResponseSequencer.OnOriginalRhythmVoice(((object)(SoundGameFileType)(ref fileType)).ToString(), ((object)(MixingCategory)(ref category)).ToString(), text, text2, incrementGlobalCounter, prog, rgndCueId, waveRefIndex, pitch, pan, num, loop);
					if (Plugin.MuteOriginalRhythmVoiceResponses)
					{
						volume = 0f;
					}
				}
				else if ((int)category == 4)
				{
					string text3 = text + "|" + text2;
					bool flag = text3.IndexOf("missionid_", StringComparison.OrdinalIgnoreCase) >= 0 && text3.IndexOf("kaesi", StringComparison.OrdinalIgnoreCase) >= 0;
					bool flag2 = Plugin.ZeroP1CriPlayDirectAllRhythm || (Plugin.ZeroP1CriPlayDirectRhythmMissionKaesi && flag);
					if (flag2)
					{
						volume = 0f;
					}
					if (Plugin.TraceP1CriPlayDirectRhythm && _traceCount < Plugin.MaxP1CriPlayDirectTraceLogs)
					{
						_traceCount++;
						Plugin.T($"[P1 CRI PLAYDIRECT MUTE] category={category}, fileType={fileType}, key={text2}, path={text}, prog={prog}, rgndCueId={rgndCueId}, waveRefIndex={waveRefIndex}, pitch={pitch}, pan={pan}, loop={loop}, looksLikeMissionKaesi={flag}, zeroed={flag2}, volume {num} -> {volume}");
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.W("[P1 CRI PLAYDIRECT MUTE] prefix failed: " + ex.Message);
			}
		}

		private static bool IsRhythmVoiceCategory(MixingCategory category)
		{
			try
			{
				return ((object)(MixingCategory)(ref category)).ToString().IndexOf("RhythmVoice", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			catch
			{
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(Rhythm), "playRhythm")]
	internal static class P1RhythmAutoMoodPatch
	{
		private static void Postfix(Rhythm __instance, PlayRequest rhythmPlayRequest, bool __result)
		{
			if (!__result || !Plugin.ExternalThemeAutoMoodFromP1Rhythm || !P1OriginalThemeMuteState.BattleActive)
			{
				return;
			}
			try
			{
				string text = SafeRequestMoodText(rhythmPlayRequest);
				string text2 = SafeLastMoodText(__instance);
				uint num = SafePlaySeIndex(__instance);
				uint value = SafePlayCount(__instance);
				bool value2 = SafeIsPlay(__instance);
				ExternalResponseSequencer.OnP1RhythmCommandObserved(rhythmPlayRequest, $"P1 Rhythm.playRhythm requestMood={text}, lastMood={text2}, playCount={value}, playSEIndex={num}");
				if (!TryMapMood(text, text2, num, out int mood, out string reason))
				{
					if (Plugin.ExternalThemeTraceAutoMood)
					{
						Plugin.ThemeT($"[EXT THEME AUTO] unable to map P1 rhythm mood; requestMood={text}, lastMood={text2}, playCount={value}, playSEIndex={num}, isPlay={value2}");
					}
					return;
				}
				if (Plugin.ExternalThemeTraceAutoMood)
				{
					Plugin.ThemeT($"[EXT THEME AUTO] detected P1 rhythm mood={mood}; reason={reason}; requestMood={text}, lastMood={text2}, playCount={value}, playSEIndex={num}, isPlay={value2}");
				}
				ExternalThemeSequencer.OnP1RhythmMoodDetected(mood, $"P1 Rhythm.playRhythm requestMood={text}, lastMood={text2}, playCount={value}, playSEIndex={num}");
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT THEME AUTO] P1 Rhythm.playRhythm mood detection failed: " + ex.Message);
			}
		}

		private static bool TryMapMood(string requestMoodText, string lastMoodText, uint playSeIndex, out int mood, out string reason)
		{
			string text = ((requestMoodText ?? string.Empty) + " " + (lastMoodText ?? string.Empty)).ToLowerInvariant();
			if (text.Contains("high") || text.Contains("fever"))
			{
				mood = 3;
				reason = "P1 rhythm enum Mood_High/Fever -> external mood 3";
				return true;
			}
			if (text.Contains("mid"))
			{
				mood = 2;
				reason = "P1 rhythm enum Mood_Mid -> external mood 2";
				return true;
			}
			if (text.Contains("low"))
			{
				mood = 1;
				reason = "P1 rhythm enum Mood_Low -> external mood 1";
				return true;
			}
			if (text.Contains("none") || text.Contains("begin") || text.Contains("zero") || text.Contains("default"))
			{
				mood = 0;
				reason = "P1 rhythm enum looks like reset/begin -> external mood 0";
				return true;
			}
			if (playSeIndex >= 720907 && playSeIndex < 720999)
			{
				mood = 3;
				reason = "fallback high/fever playSEIndex >= 720907 -> external mood 3";
				return true;
			}
			if (playSeIndex >= 720902 && playSeIndex < 720907)
			{
				mood = 2;
				reason = "fallback mid playSEIndex 720902..720906 -> external mood 2";
				return true;
			}
			if (playSeIndex >= 720897 && playSeIndex < 720902)
			{
				mood = 1;
				reason = "fallback low playSEIndex 720897..720901 -> external mood 1";
				return true;
			}
			mood = 0;
			reason = "unmapped";
			return false;
		}

		private static string SafeRequestMoodText(PlayRequest? request)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				object obj;
				if (request == null)
				{
					obj = null;
				}
				else
				{
					Mood rhythmMood = request.rhythmMood;
					obj = ((object)(Mood)(ref rhythmMood)).ToString();
				}
				if (obj == null)
				{
					obj = "request=null";
				}
				return (string)obj;
			}
			catch (Exception ex)
			{
				return "requestMood-error=" + ex.Message;
			}
		}

		private static string SafeLastMoodText(Rhythm? rhythm)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				object obj;
				if (rhythm == null)
				{
					obj = null;
				}
				else
				{
					Mood lastMood_ = rhythm.lastMood_;
					obj = ((object)(Mood)(ref lastMood_)).ToString();
				}
				if (obj == null)
				{
					obj = "rhythm=null";
				}
				return (string)obj;
			}
			catch (Exception ex)
			{
				return "lastMood-error=" + ex.Message;
			}
		}

		private static uint SafePlaySeIndex(Rhythm? rhythm)
		{
			try
			{
				return (rhythm != null) ? rhythm.playSEIndex_ : uint.MaxValue;
			}
			catch
			{
				return uint.MaxValue;
			}
		}

		private static uint SafePlayCount(Rhythm? rhythm)
		{
			try
			{
				return (rhythm != null) ? rhythm.playCount_ : 0u;
			}
			catch
			{
				return 0u;
			}
		}

		private static bool SafeIsPlay(Rhythm? rhythm)
		{
			try
			{
				return rhythm != null && rhythm.isPlay_;
			}
			catch
			{
				return false;
			}
		}
	}
	[HarmonyPatch]
	internal static class P1CommandEventResponsePatch
	{
		[CompilerGenerated]
		private sealed class <TargetMethods>d__0 : IEnumerable<MethodBase>, IEnumerable, IEnumerator<MethodBase>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private MethodBase <>2__current;

			private int <>l__initialThreadId;

			private MethodInfo <onFix>5__1;

			private MethodInfo <onExec>5__2;

			MethodBase IEnumerator<MethodBase>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <TargetMethods>d__0(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<onFix>5__1 = null;
				<onExec>5__2 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<onFix>5__1 = AccessTools.DeclaredMethod(typeof(Director), "onFixCommand", (Type[])null, (Type[])null);
					if (<onFix>5__1 != null)
					{
						<>2__current = <onFix>5__1;
						<>1__state = 1;
						return true;
					}
					goto IL_0076;
				case 1:
					<>1__state = -1;
					goto IL_0076;
				case 2:
					{
						<>1__state = -1;
						break;
					}
					IL_0076:
					<onExec>5__2 = AccessTools.DeclaredMethod(typeof(Director), "onExecCommand", (Type[])null, (Type[])null);
					if (<onExec>5__2 != null)
					{
						<>2__current = <onExec>5__2;
						<>1__state = 2;
						return true;
					}
					break;
				}
				return false;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<MethodBase> IEnumerable<MethodBase>.GetEnumerator()
			{
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					return this;
				}
				return new <TargetMethods>d__0(0);
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<MethodBase>)this).GetEnumerator();
			}
		}

		[IteratorStateMachine(typeof(<TargetMethods>d__0))]
		private static IEnumerable<MethodBase> TargetMethods()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <TargetMethods>d__0(-2);
		}

		private static void Prefix(object __0, MethodBase __originalMethod)
		{
			if (!Plugin.ExternalResponsesEnabled || !Plugin.ExternalResponseCommandDetectionEnabled || !P1OriginalThemeMuteState.BattleActive)
			{
				return;
			}
			try
			{
				ExternalResponseSequencer.OnP1CommandEventObserved(__0, "P1.Director." + __originalMethod.Name);
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT RESP CMD] Director command hook failed: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(Director), "failedPlayGame")]
	internal static class P1ExternalThemeStopOnFailedPlayGamePatch
	{
		private static void Prefix()
		{
			if (!Plugin.ExternalThemeStopOnFailedPlayGame)
			{
				return;
			}
			try
			{
				P1OriginalThemeMuteState.Reset("Director.failedPlayGame");
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT THEME] failedPlayGame stop hook failed: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(Director), "stopBattleBgm")]
	internal static class P1ExternalThemeStopOnStopBattleBgmPatch
	{
		private static void Prefix()
		{
			if (!Plugin.ExternalThemeStopOnStopBattleBgm)
			{
				return;
			}
			try
			{
				P1OriginalThemeMuteState.Reset("Director.stopBattleBgm");
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT THEME] stopBattleBgm stop hook failed: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(Director), "moodDown")]
	internal static class P1ExternalThemeMoodDownToHelperPatch
	{
		private static void Postfix()
		{
			try
			{
				ExternalThemeSequencer.OnP1MoodLossToHelperDetected("Director.moodDown");
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT THEME AUTO] moodDown helper hook failed: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(Rhythm), "clearPlayCount")]
	internal static class P1ExternalThemeClearPlayCountToHelperPatch
	{
		private static void Postfix()
		{
			try
			{
				ExternalThemeSequencer.OnP1MoodLossToHelperDetected("Rhythm.clearPlayCount");
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT THEME AUTO] clearPlayCount helper hook failed: " + ex.Message);
			}
		}
	}
	[HarmonyPatch(typeof(Rhythm), "resetPlayCount")]
	internal static class P1ExternalThemeResetPlayCountToHelperPatch
	{
		private static void Postfix()
		{
			try
			{
				ExternalThemeSequencer.OnP1MoodLossToHelperDetected("Rhythm.resetPlayCount");
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT THEME AUTO] resetPlayCount helper hook failed: " + ex.Message);
			}
		}
	}
	internal static class ExternalThemeSequencer
	{
		private static readonly string[] Mood0Loop = new string[1] { "Begin-02" };

		private static readonly string[] Mood1Loop = new string[4] { "Combo-01", "Combo-02", "Combo-03", "Combo-04" };

		private static readonly string[] Mood2Loop = new string[4] { "Combo-06", "Combo-07", "Combo-08", "Combo-09" };

		private static readonly string[] Mood3Loop = (from i in Enumerable.Range(1, 16)
			select $"Fever-{i:00}").ToArray();

		private static readonly Dictionary<string, AudioPart> Parts = new Dictionary<string, AudioPart>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> MissingPartWarnings = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static GameObject? _root;

		private static readonly ManagedNaudioPlayer MainPlayer = new ManagedNaudioPlayer();

		private static readonly ManagedNaudioPlayer HelperPlayer = new ManagedNaudioPlayer();

		private static bool _initialized;

		private static bool _loadAttempted;

		private static bool _loadComplete;

		private static bool _loadedAny;

		private static bool _loadRequested;

		private static int _loadDelayFrames;

		private static string _loadRequestReason = string.Empty;

		private static bool _loggedOggExceptionDetails;

		private static bool _incrementalLoadActive;

		private static string[] _loadPartQueue = Array.Empty<string>();

		private static int _loadPartIndex;

		private static string _loadDirectory = string.Empty;

		private static Dictionary<string, string> _loadWavByNormalizedStem = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		private static Dictionary<string, string> _loadOggByNormalizedStem = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		private static bool _battleActive;

		private static bool _originalHelperGateOpen = true;

		private static bool _hasLastUpdateTime;

		private static double _lastUpdateTime;

		private static double _lastP1RhythmBoundaryResyncTime;

		private static double _lastOriginalHelperAnchorResyncTime;

		private static double _lastP1RhythmBoundaryTime;

		private static double _lastMainWindowStartTime;

		private static double _helperParallelAnchorTime;

		private static double _pendingInitialOriginalHelperAnchorTime;

		private static bool _hasLastRhythmUpdateState;

		private static uint _lastRhythmUpdatePlayCount;

		private static bool _lastRhythmUpdateIsPlay;

		private static string _lastRhythmUpdateMoodText = string.Empty;

		private static uint _lastRhythmUpdatePlaySeIndex = uint.MaxValue;

		private static bool _rhythmUpdateLossAlreadyHandled;

		private static int _rhythmUpdateLossTraceCount;

		private static bool _mainPlaying;

		private static bool _mainWaitingForStartDelay;

		private static double _mainStartDelayEndTime;

		private static bool _mainStopAfterMood0Intro;

		private static double _mainNextFixedBoundaryTime;

		private static bool _helperRunning;

		private static bool _helperWaitingForStartDelay;

		private static double _helperStartDelayEndTime;

		private static bool _helperAudible;

		private static string _helperCurrentPart = string.Empty;

		private static string _helperScheduleSource = string.Empty;

		private static double _helperNextFixedBoundaryTime;

		private static bool _startWhenLoaded;

		private static int _startWhenLoadedMood;

		private static bool _startWhenLoadedIncludeMissionIntro;

		private static string _startWhenLoadedSource = string.Empty;

		private static int _currentMood;

		private static int _pendingMood;

		private static bool _pendingIncludeMissionIntro;

		private static bool _hasPendingMood;

		private static bool _beginIntroPlayedThisBattle;

		private static string[] _loopParts = Array.Empty<string>();

		private static int _loopIndex;

		private static readonly Queue<string> OneShotQueue = new Queue<string>();

		private static string _currentPart = string.Empty;

		public static int CurrentMood => _currentMood;

		public static string CurrentMainPart => _currentPart;

		public static bool BattleActive => _battleActive;

		public static void Initialize()
		{
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			if (_initialized)
			{
				return;
			}
			_initialized = true;
			try
			{
				ClassInjector.RegisterTypeInIl2Cpp<ThemeSequencerBehaviour>();
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT THEME] ClassInjector registration warning: " + ex.Message);
			}
			try
			{
				_root = new GameObject("PataponMusicMenu_ManualMoodSequencer");
				Object.DontDestroyOnLoad((Object)(object)_root);
				((Object)_root).hideFlags = (HideFlags)61;
				_root.AddComponent<ThemeSequencerBehaviour>();
				if (Plugin.ExternalThemeLoadAudioAtPluginStart)
				{
					RequestLoad("plugin start", 8);
				}
				ExternalResponseSequencer.Initialize();
				Plugin.ThemeT("[EXT THEME] sequencer initialized using managed NAudio playback backend");
			}
			catch (Exception value)
			{
				Plugin.W($"[EXT THEME] Initialize failed: {value}");
			}
		}

		public static bool SelectThemeFromMenu(int themeNumber, string source)
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			if (!Plugin.ExternalThemeEnabled)
			{
				return false;
			}
			if (_battleActive)
			{
				Plugin.W("[THEME MENU] theme selection is disabled during an active battle; finish/leave the mission first.");
				return false;
			}
			themeNumber = Math.Clamp(themeNumber, 1, 99);
			Plugin.SetSelectedThemeNumber(themeNumber);
			ThemePathResolver.ClearCache();
			UnloadLoadedAudio("theme menu selection (" + source + ")");
			RequestLoad($"theme menu selected {themeNumber:00}", 0);
			ManualLogSource l = Plugin.L;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(24, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[THEME MENU] selected ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(themeNumber, "00");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ThemePathResolver.SelectedThemeTitle);
			}
			l.LogInfo(val);
			return true;
		}

		public static void OnBattleStart(string source)
		{
			if (Plugin.ExternalThemeEnabled)
			{
				_battleActive = true;
				_originalHelperGateOpen = true;
				_hasLastUpdateTime = false;
				_lastP1RhythmBoundaryResyncTime = 0.0;
				_lastOriginalHelperAnchorResyncTime = 0.0;
				_lastP1RhythmBoundaryTime = 0.0;
				_lastMainWindowStartTime = 0.0;
				_helperParallelAnchorTime = 0.0;
				_pendingInitialOriginalHelperAnchorTime = 0.0;
				ResetRhythmUpdateLossState();
				ExternalResponseSequencer.OnBattleStart(source);
				RequestLoad("battle start", 1);
				if (Plugin.ExternalThemeAutoStartMood0)
				{
					Plugin.ThemeT("[EXT THEME] battle start from " + source + "; auto-start mood 0");
					SetMood(0, immediate: true, "battle start from " + source, !_beginIntroPlayedThisBattle);
				}
			}
		}

		public static void OnBattleEnd(string source)
		{
			if (_battleActive || _mainPlaying || _helperRunning || _helperWaitingForStartDelay)
			{
				Plugin.ThemeT("[EXT THEME] battle end from " + source + "; stopping external theme");
				_battleActive = false;
				_originalHelperGateOpen = true;
				_hasLastUpdateTime = false;
				_lastP1RhythmBoundaryResyncTime = 0.0;
				_lastOriginalHelperAnchorResyncTime = 0.0;
				_lastP1RhythmBoundaryTime = 0.0;
				_lastMainWindowStartTime = 0.0;
				_helperParallelAnchorTime = 0.0;
				_pendingInitialOriginalHelperAnchorTime = 0.0;
				ResetRhythmUpdateLossState();
				ExternalResponseSequencer.OnBattleEnd(source);
				_beginIntroPlayedThisBattle = false;
				Stop("battle end");
				UnloadLoadedAudio("battle end from " + source);
			}
		}

		public static void Update()
		{
			if (!_initialized || !Plugin.ExternalThemeEnabled)
			{
				return;
			}
			try
			{
				ProcessDeferredLoad();
				ProcessIncrementalLoad();
				double now = NowSeconds();
				ApplyFrameStallCompensation(now);
				UpdateOriginalHelperGate();
				RefreshRuntimeVolumes();
				UpdateHelper(now);
				UpdateMain(now);
				ExternalResponseSequencer.Update(now);
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT THEME] Update failed: " + ex.Message);
			}
		}

		private static void RefreshRuntimeVolumes()
		{
			try
			{
				MainPlayer.SetVolume(GateThemeVolume(Plugin.ExternalThemeVolume));
				HelperPlayer.SetVolume(_helperAudible ? GateThemeVolume(Plugin.ExternalThemeVolume) : 0f);
				ExternalResponseSequencer.RefreshRuntimeVolume();
			}
			catch
			{
			}
		}

		private static void UpdateOriginalHelperGate()
		{
			bool flag = !_battleActive || P1OriginalThemeMuteState.OriginalHelperAllowsExternalAudio;
			if (_originalHelperGateOpen == flag)
			{
				return;
			}
			_originalHelperGateOpen = flag;
			if (!flag)
			{
				MainPlayer.SetVolume(0f);
				HelperPlayer.SetVolume(0f);
				if (_battleActive && (_currentMood > 0 || _mainPlaying || _mainWaitingForStartDelay || _hasPendingMood))
				{
					SwitchToHelperNow("original helper gate closed");
				}
			}
			else
			{
				AlignHelperWindowToBestKnownAnchor("original helper gate reopened", _currentMood == 0);
				MainPlayer.SetVolume(Plugin.ExternalThemeVolume);
				HelperPlayer.SetVolume(_helperAudible ? Plugin.ExternalThemeVolume : 0f);
			}
			ExternalResponseSequencer.SetExternalAudioGate(flag);
			Plugin.ThemeT("[EXT THEME HELPER GATE] original helper " + (flag ? "playing/resumed" : "not playing") + "; external theme audio " + (flag ? "unmuted" : "muted"));
		}

		private static float GateThemeVolume(float volume)
		{
			return _originalHelperGateOpen ? volume : 0f;
		}

		public static void OnOriginalHelperPlaybackAnchor(string source)
		{
			if (!Plugin.ExternalThemeEnabled || !_battleActive)
			{
				return;
			}
			double num = NowSeconds();
			if (_currentMood == 0 && _lastMainWindowStartTime <= 0.0001 && !_hasPendingMood && !_beginIntroPlayedThisBattle)
			{
				if (!_loadedAny)
				{
					_pendingInitialOriginalHelperAnchorTime = num;
					return;
				}
				_pendingInitialOriginalHelperAnchorTime = 0.0;
				StartMissionIntroAtOriginalHelperAnchor(num, source + " initial original helper anchor");
			}
			else if (_currentMood == 0 && !_mainPlaying && !_mainWaitingForStartDelay && !_hasPendingMood)
			{
				AlignHelperWindowToBestKnownAnchor(source, makeAudible: true);
			}
		}

		private static void ResyncHelperWindowToOriginalHelperAnchor(string source, bool useHelperPhaseDelay)
		{
			double desiredFirstStartTime = NowSeconds() + (useHelperPhaseDelay ? GetPhaseOffsetForMood(0) : 0.0);
			AlignHelperWindowToAbsoluteStart(desiredFirstStartTime, source, makeAudible: true, force: true);
		}

		private static bool StartMissionIntroAtOriginalHelperAnchor(double anchorTime, string source)
		{
			if (!Plugin.ExternalThemeEnabled || !_battleActive)
			{
				return false;
			}
			if (!Parts.TryGetValue("Begin-01", out AudioPart value) || value == null)
			{
				if (!Parts.TryGetValue("Begin-02", out value) || value == null)
				{
					WarnMissingPart("Begin-01");
					_pendingInitialOriginalHelperAnchorTime = anchorTime;
					return false;
				}
				WarnMissingPart("Begin-01");
				Plugin.ThemeT("[EXT THEME] Begin-01 missing at original-helper anchor; using Begin-02 once as mission intro fallback");
			}
			double num = NowSeconds();
			double num2 = GetEffectivePartWindowSeconds(value);
			if (num2 <= 0.0001)
			{
				num2 = Plugin.ExternalThemeFixedPartWindowSeconds;
			}
			double num3 = ((anchorTime > 0.0001) ? anchorTime : num);
			if (num - num3 > Math.Min(0.5, num2 * 0.25))
			{
				num3 = num;
			}
			double num4;
			for (num4 = num3 + num2; num4 <= num + 0.02; num4 = num3 + num2)
			{
				num3 += num2;
			}
			StopMainPlayerOnly();
			StopHelperPlayerOnly();
			_helperRunning = false;
			_helperWaitingForStartDelay = false;
			_helperCurrentPart = string.Empty;
			_currentMood = 0;
			_pendingMood = 0;
			_hasPendingMood = false;
			_pendingIncludeMissionIntro = false;
			_loopParts = Array.Empty<string>();
			_loopIndex = 0;
			OneShotQueue.Clear();
			_mainStopAfterMood0Intro = true;
			_beginIntroPlayedThisBattle = true;
			_mainPlaying = true;
			_mainWaitingForStartDelay = false;
			_mainNextFixedBoundaryTime = num3;
			_lastMainWindowStartTime = 0.0;
			_lastP1RhythmBoundaryResyncTime = 0.0;
			double num5 = Math.Max(0.0, num - num3);
			if (num5 >= num2)
			{
				num5 = 0.0;
			}
			MainPlayer.PlayUntil(value, GateThemeVolume(Plugin.ExternalThemeVolume), num, num4, num5);
			_currentPart = (value.Name.Equals("Begin-02", StringComparison.OrdinalIgnoreCase) ? "Begin-02" : "Begin-01");
			ScheduleHelperWindowAt(num4, source + " -> Begin-02 after Begin-01", audible: true);
			Plugin.ThemeT($"[EXT THEME] mission intro anchored to original helper: playing {_currentPart}; phase={num5:F4}s, endIn={num4 - num:F4}s, source={source}");
			return true;
		}

		private static void ScheduleHelperWindowAt(double startTime, string source, bool audible)
		{
			if (!Plugin.ExternalThemeKeepHelperLoopRunningMuted || !Plugin.ExternalThemeEnabled || !_battleActive)
			{
				return;
			}
			if (!Parts.ContainsKey("Begin-02"))
			{
				WarnMissingPart("Begin-02");
				return;
			}
			double num = NowSeconds();
			_helperAudible = audible;
			_helperScheduleSource = source;
			_helperParallelAnchorTime = startTime;
			_helperNextFixedBoundaryTime = startTime;
			_lastOriginalHelperAnchorResyncTime = 0.0;
			HelperPlayer.Stop();
			_helperRunning = false;
			_helperCurrentPart = string.Empty;
			if (num + 0.0001 < startTime)
			{
				_helperWaitingForStartDelay = true;
				_helperStartDelayEndTime = startTime;
				HelperPlayer.SetVolume(0f);
				Plugin.ThemeT($"[EXT THEME HELPER] scheduled Begin-02 after mission intro from {source}; startIn={startTime - num:F4}s, audible={audible}");
			}
			else
			{
				_helperWaitingForStartDelay = false;
				AlignHelperWindowToParallelClock(source, audible, force: true);
			}
		}

		private static bool AlignHelperWindowToBestKnownAnchor(string source, bool makeAudible)
		{
			if (!Plugin.ExternalThemeKeepHelperLoopRunningMuted || !Plugin.ExternalThemeEnabled || !_battleActive)
			{
				return false;
			}
			EnsureHelperParallelAnchorFromBestKnownWindow(source);
			return AlignHelperWindowToParallelClock(source, makeAudible, force: true);
		}

		private static void SyncMutedHelperToMainWindowStart(double mainWindowStartTime, string source)
		{
			if (_battleActive && !_helperAudible)
			{
				SetHelperParallelAnchorFromMainWindowStart(mainWindowStartTime, source);
				AlignHelperWindowToParallelClock(source, makeAudible: false, force: true);
			}
		}

		private static bool AlignHelperWindowToAbsoluteStart(double desiredFirstStartTime, string source, bool makeAudible, bool force)
		{
			if (desiredFirstStartTime > 0.0001)
			{
				_helperParallelAnchorTime = desiredFirstStartTime;
			}
			return AlignHelperWindowToParallelClock(source, makeAudible, force);
		}

		private static void EnsureHelperParallelAnchorFromBestKnownWindow(string source)
		{
			if (!(_helperParallelAnchorTime > 0.0001))
			{
				if (_lastMainWindowStartTime > 0.0001)
				{
					SetHelperParallelAnchorFromMainWindowStart(_lastMainWindowStartTime, source);
				}
				else if (_lastP1RhythmBoundaryTime > 0.0001)
				{
					_helperParallelAnchorTime = _lastP1RhythmBoundaryTime + GetPhaseOffsetForMood(Math.Max(1, _currentMood));
				}
				else
				{
					_helperParallelAnchorTime = NowSeconds() + GetPhaseOffsetForMood(0);
				}
			}
		}

		private static void SetHelperParallelAnchorFromMainWindowStart(double mainWindowStartTime, string source)
		{
			if (!(mainWindowStartTime <= 0.0001))
			{
				_helperParallelAnchorTime = mainWindowStartTime;
			}
		}

		private static bool AlignHelperWindowToParallelClock(string source, bool makeAudible, bool force)
		{
			if (!Plugin.ExternalThemeKeepHelperLoopRunningMuted || !Plugin.ExternalThemeEnabled || !_battleActive)
			{
				return false;
			}
			if (!Parts.TryGetValue("Begin-02", out AudioPart value) || value == null)
			{
				return false;
			}
			double num = NowSeconds();
			if (!force && _lastOriginalHelperAnchorResyncTime > 0.0001 && num - _lastOriginalHelperAnchorResyncTime < 0.35)
			{
				return false;
			}
			EnsureHelperParallelAnchorFromBestKnownWindow(source);
			double num2 = GetEffectivePartWindowSeconds(value);
			if (num2 <= 0.0001)
			{
				num2 = Plugin.ExternalThemeFixedPartWindowSeconds;
			}
			double num3 = _helperParallelAnchorTime;
			if (num3 <= 0.0001)
			{
				num3 = (_helperParallelAnchorTime = num);
			}
			if (num >= num3)
			{
				double num4 = Math.Floor((num - num3) / num2);
				if (num4 > 0.0)
				{
					num3 += num4 * num2;
				}
			}
			double num5;
			for (num5 = num3 + num2; num5 <= num + 0.02; num5 = num3 + num2)
			{
				num3 += num2;
			}
			_lastOriginalHelperAnchorResyncTime = num;
			_helperAudible = makeAudible;
			_helperScheduleSource = source;
			_helperNextFixedBoundaryTime = num5;
			if (num + 0.0001 < num3)
			{
				HelperPlayer.Stop();
				_helperRunning = false;
				_helperWaitingForStartDelay = true;
				_helperStartDelayEndTime = num3;
				_helperCurrentPart = string.Empty;
				Plugin.ThemeT($"[EXT THEME HELPER] parallel Begin-02 from {source}; scheduledStartIn={num3 - num:F4}s, audible={_helperAudible}");
				return true;
			}
			if (!force && _helperRunning && !_helperWaitingForStartDelay && Math.Abs(_helperNextFixedBoundaryTime - num5) < 0.03)
			{
				HelperPlayer.SetVolume(_helperAudible ? GateThemeVolume(Plugin.ExternalThemeVolume) : 0f);
				return true;
			}
			double num6 = Math.Max(0.0, num - num3);
			if (num6 >= num2)
			{
				num6 = 0.0;
			}
			float volume = (_helperAudible ? GateThemeVolume(Plugin.ExternalThemeVolume) : 0f);
			HelperPlayer.PlayUntil(value, volume, num, num5, num6);
			_helperRunning = true;
			_helperWaitingForStartDelay = false;
			_helperCurrentPart = "Begin-02";
			Plugin.ThemeT($"[EXT THEME HELPER] parallel Begin-02 from {source}; phase={num6:F4}s, endIn={num5 - num:F4}s, audible={_helperAudible}");
			return true;
		}

		private static double GetHelperRelativeToMainOffsetSeconds()
		{
			return 0.0;
		}

		private static void ApplyFrameStallCompensation(double now)
		{
			if (!_hasLastUpdateTime)
			{
				_hasLastUpdateTime = true;
				_lastUpdateTime = now;
				return;
			}
			double num = now - _lastUpdateTime;
			_lastUpdateTime = now;
			if (!Plugin.ExternalThemeFrameStallCompensation || !_battleActive)
			{
				return;
			}
			double externalThemeFrameStallThresholdSeconds = Plugin.ExternalThemeFrameStallThresholdSeconds;
			if (num <= externalThemeFrameStallThresholdSeconds)
			{
				return;
			}
			double num2 = Math.Min(num, Plugin.ExternalThemeFrameStallMaxCompensationSeconds);
			if (num2 <= 0.0001)
			{
				return;
			}
			bool flag = false;
			if (_mainWaitingForStartDelay)
			{
				_mainStartDelayEndTime += num2;
				if (_mainNextFixedBoundaryTime > 0.0001)
				{
					_mainNextFixedBoundaryTime += num2;
				}
				flag = true;
			}
			else if (_mainPlaying)
			{
				flag |= MainPlayer.DelayExpectedEnd(num2);
				if (_mainNextFixedBoundaryTime > 0.0001)
				{
					_mainNextFixedBoundaryTime += num2;
				}
			}
			if (flag && Plugin.ExternalThemeTraceFrameStallCompensation)
			{
				Plugin.ThemeT($"[EXT THEME CLOCK] frame stall compensation: updateDelta={num:F4}s, threshold={externalThemeFrameStallThresholdSeconds:F4}s, appliedDelay={num2:F4}s, currentMood={_currentMood}, mainPart={_currentPart}, helperAudible={_helperAudible}");
			}
		}

		private static void UpdateMain(double now)
		{
			if (!_mainPlaying)
			{
				return;
			}
			MainPlayer.SetVolume(GateThemeVolume(Plugin.ExternalThemeVolume));
			if (_mainWaitingForStartDelay)
			{
				if (now >= _mainStartDelayEndTime)
				{
					_mainWaitingForStartDelay = false;
					ArmMainFixedBoundary(_mainStartDelayEndTime);
					PlayNextMainPart("initial delay elapsed");
				}
			}
			else if (MainPlayer.HasReachedEnd(now))
			{
				PlayNextMainPart("previous part ended (" + _currentPart + ")");
			}
		}

		private static void UpdateHelper(double now)
		{
			if (!_battleActive || !Plugin.ExternalThemeKeepHelperLoopRunningMuted)
			{
				return;
			}
			if (_helperWaitingForStartDelay)
			{
				if (now >= _helperStartDelayEndTime)
				{
					_helperWaitingForStartDelay = false;
					ArmHelperFixedBoundary(_helperStartDelayEndTime);
					PlayHelperWindow("helper start delay elapsed (" + _helperScheduleSource + ")");
				}
			}
			else if (_helperRunning)
			{
				HelperPlayer.SetVolume(_helperAudible ? GateThemeVolume(Plugin.ExternalThemeVolume) : 0f);
				if (HelperPlayer.HasReachedEnd(now))
				{
					PlayHelperWindow("previous helper window ended (" + _helperCurrentPart + ")");
				}
			}
		}

		public static void OnP1RhythmMoodDetected(int detectedMood, string source)
		{
			if (!Plugin.ExternalThemeAutoMoodFromP1Rhythm || !Plugin.ExternalThemeEnabled || !_battleActive)
			{
				return;
			}
			detectedMood = Math.Clamp(detectedMood, 0, 3);
			_lastP1RhythmBoundaryTime = NowSeconds();
			RequestLoad($"auto mood {detectedMood} from {source}", 1);
			if (!_loadedAny)
			{
				if (!_loadComplete)
				{
					_startWhenLoaded = true;
					_startWhenLoadedMood = detectedMood;
					_startWhenLoadedIncludeMissionIntro = false;
					_startWhenLoadedSource = source;
					Plugin.ThemeT($"[EXT THEME AUTO] queued detected mood {detectedMood} from {source}; waiting for OGG/WAV loading to finish");
				}
			}
			else if (!_mainPlaying && detectedMood > 0)
			{
				SwitchMoodAtGameBoundary(detectedMood, source, includeMissionIntro: false);
			}
			else if (!_hasPendingMood && detectedMood == _currentMood)
			{
				ResyncCurrentMainWindowToP1RhythmBoundary(detectedMood, source);
			}
			else if (Plugin.ExternalThemeAutoMoodImmediateSwitch)
			{
				SwitchMoodAtGameBoundary(detectedMood, source, includeMissionIntro: false);
			}
			else
			{
				SetMood(detectedMood, immediate: false, source);
			}
		}

		public static void OnP1RhythmUpdateObserved(string lastMoodText, uint playCount, uint playSeIndex, bool isPlay, string source)
		{
			if (!Plugin.ExternalThemeDetectMoodLossFromRhythmUpdate || !Plugin.ExternalThemeEnabled || !_battleActive)
			{
				return;
			}
			try
			{
				if (!_hasLastRhythmUpdateState)
				{
					_hasLastRhythmUpdateState = true;
					_lastRhythmUpdateMoodText = lastMoodText ?? string.Empty;
					_lastRhythmUpdatePlayCount = playCount;
					_lastRhythmUpdatePlaySeIndex = playSeIndex;
					_lastRhythmUpdateIsPlay = isPlay;
					return;
				}
				bool flag = _currentMood > 0 || _mainPlaying;
				bool flag2 = _lastRhythmUpdatePlayCount != 0 || _lastRhythmUpdateIsPlay;
				bool flag3 = playCount == 0 && !isPlay;
				if (Plugin.ExternalThemeTraceRhythmUpdateMoodLoss && _rhythmUpdateLossTraceCount < Plugin.ExternalThemeMaxRhythmUpdateMoodLossTraceLogs)
				{
					_rhythmUpdateLossTraceCount++;
					Plugin.ThemeT($"[EXT THEME AUTO] Rhythm.update poll: mainMoodActive={flag}, currentMood={_currentMood}, lastMood={_lastRhythmUpdateMoodText}->{lastMoodText}, playCount={_lastRhythmUpdatePlayCount}->{playCount}, playSEIndex={_lastRhythmUpdatePlaySeIndex}->{playSeIndex}, isPlay={_lastRhythmUpdateIsPlay}->{isPlay}, lostCandidate={flag3 && flag2}");
				}
				if (!_rhythmUpdateLossAlreadyHandled && flag && flag2 && flag3)
				{
					_rhythmUpdateLossAlreadyHandled = true;
					Plugin.ThemeT($"[EXT THEME AUTO] Rhythm.update mood loss detected from {source}; lastMood={_lastRhythmUpdateMoodText}->{lastMoodText}, playCount={_lastRhythmUpdatePlayCount}->0, playSEIndex={_lastRhythmUpdatePlaySeIndex}->{playSeIndex}, isPlay={_lastRhythmUpdateIsPlay}->{isPlay}; switching to helper immediately");
					SwitchToHelperNow("Rhythm.update loss detector (" + source + ")");
				}
				else if (playCount != 0 || isPlay)
				{
					_rhythmUpdateLossAlreadyHandled = false;
				}
				_lastRhythmUpdateMoodText = lastMoodText ?? string.Empty;
				_lastRhythmUpdatePlayCount = playCount;
				_lastRhythmUpdatePlaySeIndex = playSeIndex;
				_lastRhythmUpdateIsPlay = isPlay;
			}
			catch (Exception ex)
			{
				Plugin.W("[EXT THEME AUTO] Rhythm.update mood-loss detector failed: " + ex.Message);
			}
		}

		public static void OnP1MoodLossToHelperDetected(string source)
		{
			if (!Plugin.ExternalThemeMoodLossSwitchToHelper || !Plugin.ExternalThemeEnabled || !_battleActive)
			{
				return;
			}
			RequestLoad("mood loss helper switch from " + source, 1);
			if (!_loadedAny)
			{
				if (!_loadComplete)
				{
					_startWhenLoaded = true;
					_startWhenLoadedMood = 0;
					_startWhenLoadedIncludeMissionIntro = false;
					_startWhenLoadedSource = source;
					Plugin.ThemeT("[EXT THEME AUTO] queued mood-loss helper switch from " + source + "; waiting for OGG/WAV loading to finish");
				}
			}
			else
			{
				SwitchToHelperNow("mood loss hook " + source);
			}
		}

		private static void ResyncCurrentMainWindowToP1RhythmBoundary(int detectedMood, string source)
		{
			if (!Plugin.ExternalThemeResyncOnP1RhythmBoundary || !_battleActive || !_mainPlaying || _mainWaitingForStartDelay || detectedMood <= 0 || detectedMood != _currentMood)
			{
				return;
			}
			double num = NowSeconds();
			if (_lastP1RhythmBoundaryResyncTime > 0.0001 && num - _lastP1RhythmBoundaryResyncTime < 0.75)
			{
				return;
			}
			_lastP1RhythmBoundaryResyncTime = num;
			double phaseOffsetForMood = GetPhaseOffsetForMood(detectedMood);
			double num2 = num + phaseOffsetForMood;
			if (MainPlayer.AdjustExpectedEnd(num2))
			{
				_mainNextFixedBoundaryTime = num2;
				double mainWindowStartTime = (_lastMainWindowStartTime = num2 - Plugin.ExternalThemeFixedPartWindowSeconds);
				if (_currentMood > 0 && !_helperAudible)
				{
					SetHelperParallelAnchorFromMainWindowStart(mainWindowStartTime, "rhythm-boundary resync " + source);
					AlignHelperWindowToParallelClock("rhythm-boundary resync " + source, makeAudible: false, force: true);
				}
				if (Plugin.ExternalThemeTraceRhythmBoundaryResync || Plugin.ExternalThemeTraceFixedWindowClock)
				{
					Plugin.ThemeT($"[EXT THEME CLOCK] rhythm-boundary resync: mood={detectedMood}, currentPart={_currentPart}, source={source}, nextPartStartIn={phaseOffsetForMood:F4}s, secondsUntilEnd={MainPlayer.SecondsUntilExpectedEnd(num):F4}s");
				}
			}
		}

		private static void SwitchMoodAtGameBoundary(int mood, string source, bool includeMissionIntro)
		{
			mood = Math.Clamp(mood, 0, 3);
			if (mood == 0)
			{
				SwitchToHelperNow("game rhythm boundary (" + source + ")");
				return;
			}
			SetHelperAudible(audible: false, $"switching to mood {mood} from {source}");
			StopMainPlayerOnly();
			ApplyMood(mood);
			_mainPlaying = true;
			double phaseOffsetForMood = GetPhaseOffsetForMood(mood);
			if (phaseOffsetForMood > 0.0001)
			{
				_mainWaitingForStartDelay = true;
				_mainStartDelayEndTime = NowSeconds() + phaseOffsetForMood;
				_mainNextFixedBoundaryTime = _mainStartDelayEndTime;
				SetHelperParallelAnchorFromMainWindowStart(_mainStartDelayEndTime, "game rhythm boundary " + source);
				AlignHelperWindowToParallelClock("game rhythm boundary " + source, makeAudible: false, force: true);
				Plugin.ThemeT($"[EXT THEME AUTO] switching to mood {mood} at game rhythm boundary from {source}; delayed by phase offset {phaseOffsetForMood:F3}s");
			}
			else
			{
				_mainWaitingForStartDelay = false;
				ArmMainFixedBoundary(NowSeconds());
				Plugin.ThemeT($"[EXT THEME AUTO] switching immediately to mood {mood} at game rhythm boundary from {source}");
				PlayNextMainPart("game rhythm boundary (" + source + ")");
			}
		}

		private static void SwitchToHelperNow(string source)
		{
			_currentMood = 0;
			_rhythmUpdateLossAlreadyHandled = true;
			_pendingMood = 0;
			_hasPendingMood = false;
			_mainStopAfterMood0Intro = false;
			_mainNextFixedBoundaryTime = 0.0;
			_helperNextFixedBoundaryTime = 0.0;
			_lastP1RhythmBoundaryResyncTime = 0.0;
			_lastOriginalHelperAnchorResyncTime = 0.0;
			OneShotQueue.Clear();
			_loopParts = Array.Empty<string>();
			StopMainPlayerOnly();
			if (!AlignHelperWindowToBestKnownAnchor(source, makeAudible: true))
			{
				EnsureHelperLoopScheduled(includeMissionIntroWindow: false, source, allowImmediateStartIfMissing: true);
				if (!_helperRunning && Parts.ContainsKey("Begin-02"))
				{
					_helperWaitingForStartDelay = false;
					PlayHelperWindow("helper forced immediate start (" + source + ")");
				}
				SetHelperAudible(audible: true, source);
			}
			Plugin.ThemeT("[EXT THEME AUTO] switched to helper immediately from " + source + "; helper aligned to main window when available, otherwise mission-start helper phase");
		}

		private static void SetMood(int mood, bool immediate, string source, bool includeMissionIntro = false)
		{
			if (!Plugin.ExternalThemeEnabled)
			{
				return;
			}
			mood = Math.Clamp(mood, 0, 3);
			RequestLoad($"mood {mood} request from {source}", 1);
			if (!_loadedAny)
			{
				if (!_loadComplete)
				{
					_startWhenLoaded = true;
					_startWhenLoadedMood = mood;
					_startWhenLoadedIncludeMissionIntro = includeMissionIntro;
					_startWhenLoadedSource = source;
					Plugin.ThemeT($"[EXT THEME] queued mood {mood} from {source}; waiting for OGG/WAV loading to finish");
				}
				else
				{
					Plugin.W("[EXT THEME] cannot start: no OGG/WAV files loaded");
				}
			}
			else if (mood == 0 && !includeMissionIntro)
			{
				if (immediate || !_mainPlaying)
				{
					SwitchToHelperNow(source);
					return;
				}
				_pendingMood = 0;
				_pendingIncludeMissionIntro = false;
				_hasPendingMood = true;
				Plugin.ThemeT("[EXT THEME] pending helper mood 0 from " + source + "; will unmute helper on next main part boundary");
			}
			else if (immediate || !_mainPlaying)
			{
				StopMainPlayerOnly();
				ApplyMood(mood, includeMissionIntro);
				_mainPlaying = true;
				_mainWaitingForStartDelay = true;
				if (mood == 0)
				{
					EnsureHelperLoopScheduled(includeMissionIntro, source, allowImmediateStartIfMissing: false);
					SetHelperAudible(audible: true, source);
				}
				else
				{
					SetHelperAudible(audible: false, source);
				}
				double phaseOffsetForMood = GetPhaseOffsetForMood(mood);
				double num = Plugin.ExternalThemeInitialDelaySeconds + phaseOffsetForMood;
				_mainStartDelayEndTime = NowSeconds() + num;
				_mainNextFixedBoundaryTime = _mainStartDelayEndTime;
				if (mood > 0)
				{
					SetHelperParallelAnchorFromMainWindowStart(_mainStartDelayEndTime, $"scheduled main mood {mood} from {source}");
					AlignHelperWindowToParallelClock($"scheduled main mood {mood} from {source}", makeAudible: false, force: true);
				}
				Plugin.ThemeT($"[EXT THEME] mood {mood} armed from {source}; starting after {num:F3}s delay (initial={Plugin.ExternalThemeInitialDelaySeconds:F3}s, phaseOffset={phaseOffsetForMood:F3}s)");
			}
			else
			{
				_pendingMood = mood;
				_pendingIncludeMissionIntro = includeMissionIntro;
				_hasPendingMood = true;
				Plugin.ThemeT($"[EXT THEME] pending mood {mood} from {source}; will switch on next main part boundary");
			}
		}

		private static void ApplyMood(int mood, bool includeMissionIntro = false)
		{
			_currentMood = mood;
			if (mood > 0)
			{
				_rhythmUpdateLossAlreadyHandled = false;
			}
			_pendingMood = mood;
			_hasPendingMood = false;
			_loopIndex = 0;
			_mainStopAfterMood0Intro = false;
			_mainNextFixedBoundaryTime = 0.0;
			_helperNextFixedBoundaryTime = 0.0;
			_lastP1RhythmBoundaryResyncTime = 0.0;
			_lastP1RhythmBoundaryTime = 0.0;
			_lastMainWindowStartTime = 0.0;
			OneShotQueue.Clear();
			switch (mood)
			{
			case 0:
				if (includeMissionIntro && !_beginIntroPlayedThisBattle)
				{
					OneShotQueue.Enqueue("Begin-01");
					_beginIntroPlayedThisBattle = true;
					_mainStopAfterMood0Intro = true;
				}
				_loopParts = Array.Empty<string>();
				break;
			case 1:
				_loopParts = Mood1Loop;
				break;
			case 2:
				OneShotQueue.Enqueue("Combo-05");
				_loopParts = Mood2Loop;
				break;
			case 3:
				OneShotQueue.Enqueue("Combo-10");
				_loopParts = Mood3Loop;
				break;
			default:
				_loopParts = Array.Empty<string>();
				break;
			}
			Plugin.ThemeT($"[EXT THEME] applied main mood {mood}; loop=[{string.Join(", ", _loopParts)}], oneShots={OneShotQueue.Count}, helperAudible={_helperAudible}");
		}

		private static void PlayNextMainPart(string source)
		{
			if (!_mainPlaying)
			{
				return;
			}
			if (_hasPendingMood)
			{
				if (_pendingMood == 0 && !_pendingIncludeMissionIntro)
				{
					SwitchToHelperNow("pending mood 0 at main boundary; source=" + source);
					return;
				}
				if (_pendingMood > 0)
				{
					SetHelperAudible(audible: false, $"pending mood {_pendingMood} applied at main boundary");
				}
				ApplyMood(_pendingMood, _pendingIncludeMissionIntro);
			}
			int num = 0;
			while (num < 64)
			{
				string text = GetNextMainPartName();
				if (text == null)
				{
					if (_currentMood == 0 || _mainStopAfterMood0Intro)
					{
						StopMainPlayerOnly();
						_mainStopAfterMood0Intro = false;
						Plugin.ThemeT("[EXT THEME] main mood 0 intro finished from " + source + "; helper loop remains active/audible");
					}
					else
					{
						Stop("no sequence parts available");
					}
					return;
				}
				if (!Parts.TryGetValue(text, out AudioPart value) || value == null)
				{
					if (!text.Equals("Begin-01", StringComp