Decompiled source of DynamicMusicInMeeting v1.3.0

DanganronpaVotes.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using HarmonyLib;
using Il2CppInterop.Runtime.Attributes;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using NVorbis;
using NVorbis.Contracts;
using NVorbis.Contracts.Ogg;
using NVorbis.Ogg;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Events;
using UnityEngine.SceneManagement;

[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: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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 DanganronpaVotes
{
	[BepInPlugin("com.kris.danganronpavotes", "DanganronpaVotes", "1.3.0")]
	public class DanganronpaVotesPlugin : BasePlugin
	{
		private enum Tier
		{
			Calm,
			Tense,
			Climax
		}

		private sealed class DecodedAudio
		{
			public float[] Samples;

			public int Channels;

			public int SampleRate;

			public string Format;

			public string Error;

			public string FileName;

			public long Milliseconds;
		}

		private sealed class ClipBuildJob
		{
			public string Track;

			public bool Muffled;

			public float[] Samples;

			public int Channels;

			public int SampleRate;

			public AudioClip Clip;

			public bool Started;

			public int TotalFrames;

			public int FrameOffset;

			public Il2CppStructArray<float> Buf;
		}

		private sealed class MuffleStreamJob
		{
			public string Track;

			public AudioClip Source;

			public AudioClip Dest;

			public int Channels;

			public int SampleRate;

			public int TotalFrames;

			public int FrameOffset;

			public float Alpha;

			public float[] Prev;

			public Il2CppStructArray<float> InBuf;

			public Il2CppStructArray<float> OutBuf;
		}

		public const string PluginGuid = "com.kris.danganronpavotes";

		public const string PluginName = "DanganronpaVotes";

		public const string PluginVersion = "1.3.0";

		private static readonly string[] CrewmateTrackFiles = new string[3] { "trial_calm.wav", "trial_tense.wav", "trial_climax.wav" };

		private static readonly string[] ImpostorTrackFiles = new string[3] { "trial_impostor_calm.wav", "trial_impostor_tense.wav", "trial_impostor_climax.wav" };

		private const float FadeInSeconds = 2f;

		private const float FadeOutSeconds = 1f;

		private const float CrossfadeSeconds = 1.5f;

		private const float BaseTargetVolume = 0.8f;

		private static readonly bool UseGameMusicVolume = true;

		private static float _gameMusicVolume = 1f;

		private static Func<float> _gameMusicVolumeReader;

		private static bool _gameMusicVolumeSearched;

		private const float MuffledCutoffFrequency = 800f;

		private const float MuffleTransitionSeconds = 0.4f;

		private const string MainMenuSceneName = "MainMenu";

		private static AudioSource _sourceA;

		private static AudioSource _sourceB;

		private static bool _usingA = true;

		private static DanganronpaVotesRunner _runner;

		private static string _currentTrackName;

		private static bool _isMuffled;

		private static bool _pendingLocalVoteMuffle;

		private static bool _meetingActive;

		private static bool _isFirstMeetingOfMatch = true;

		private static bool _anyDeathObservedThisMatch;

		private static bool _matchTotalsCaptured;

		private static int _matchTotalImpostors;

		private static int _matchTotalCrewmates;

		private static readonly Dictionary<string, AudioClip> _cleanClipCache = new Dictionary<string, AudioClip>();

		private static readonly Dictionary<string, Task<DecodedAudio>> _pendingLoadTasks = new Dictionary<string, Task<DecodedAudio>>();

		private static readonly HashSet<string> _failedLoadTracks = new HashSet<string>();

		private static string _wantedTrack;

		private static readonly Queue<string> _preloadQueue = new Queue<string>();

		private static bool _roleTracksQueued;

		private static bool _queuedForImpostor;

		private static bool _wasInMatch;

		private const int ClipChunkFrames = 16384;

		private const double ClipWorkBudgetMs = 2.0;

		private const double ClipWorkBudgetWaitingMs = 12.0;

		private static readonly Queue<ClipBuildJob> _clipBuildQueue = new Queue<ClipBuildJob>();

		private static readonly Queue<MuffleStreamJob> _muffleJobs = new Queue<MuffleStreamJob>();

		private static bool _gcPending;

		private static readonly HashSet<string> _buildingClean = new HashSet<string>();

		private static readonly HashSet<string> _buildingMuffled = new HashSet<string>();

		private static readonly Dictionary<string, AudioClip> _muffledClipCache = new Dictionary<string, AudioClip>();

		private static readonly Dictionary<string, Task<float[]>> _pendingMuffleTasks = new Dictionary<string, Task<float[]>>();

		private static readonly Dictionary<string, (int channels, int sampleRate)> _pendingMuffleInfo = new Dictionary<string, (int, int)>();

		internal static ManualLogSource Log;

		private static AudioMixerGroup _fallbackMusicGroup;

		private static bool _fallbackDumped;

		private static float _nextFallbackSearch;

		private const BindingFlags AnyMember = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;

		private static string _lastVolumeLog;

		private static readonly string[] MixerParamCandidates = new string[10] { "MusicVolume", "Music Volume", "musicVolume", "MusicVol", "Music", "MasterVolume", "SFXVolume", "SfxVolume", "AmbienceVolume", "Volume" };

		private static string _audioDir;

		private static Task _audioDownloadTask;

		private const string AudioReleaseBaseUrl = "https://github.com/BdeBrunoDR/dynamicmeetingsaudio/releases/download/audio-v1/";

		private const int FirstMeetingMarginBonus = 2;

		private static float TargetVolume => 0.8f * _gameMusicVolume;

		internal static float CurrentTargetVolume => TargetVolume;

		private static AudioSource ActiveSource => _usingA ? _sourceA : _sourceB;

		private static AudioSource InactiveSource => _usingA ? _sourceB : _sourceA;

		private static Tier BaseTierForMargin(int margin)
		{
			if (margin >= 5)
			{
				return Tier.Calm;
			}
			if (margin >= 3)
			{
				return Tier.Tense;
			}
			return Tier.Climax;
		}

		public static bool IsLocalPlayerImpostor()
		{
			PlayerControl localPlayer = PlayerControl.LocalPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)localPlayer.Data == (Object)null || (Object)(object)localPlayer.Data.Role == (Object)null)
			{
				return false;
			}
			return localPlayer.Data.Role.IsImpostor;
		}

		public static bool IsLocalPlayerGhost()
		{
			PlayerControl localPlayer = PlayerControl.LocalPlayer;
			if ((Object)(object)localPlayer == (Object)null || (Object)(object)localPlayer.Data == (Object)null)
			{
				return false;
			}
			return localPlayer.Data.IsDead;
		}

		public static (int aliveImpostors, int aliveCrewmates, int totalImpostors, int totalCrewmates) CountRoles()
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			Enumerator<NetworkedPlayerInfo> enumerator = GameData.Instance.AllPlayers.GetEnumerator();
			while (enumerator.MoveNext())
			{
				NetworkedPlayerInfo current = enumerator.Current;
				if (current.Disconnected)
				{
					continue;
				}
				if ((Object)(object)current.Role != (Object)null && current.Role.IsImpostor)
				{
					num3++;
					if (!current.IsDead)
					{
						num++;
					}
				}
				else
				{
					num4++;
					if (!current.IsDead)
					{
						num2++;
					}
				}
			}
			return (aliveImpostors: num, aliveCrewmates: num2, totalImpostors: num3, totalCrewmates: num4);
		}

		public static string PickTrackForVote(int aliveImpostors, int aliveCrewmates, int totalImpostors, bool isLocalImpostor, bool forceCalmBase = false, int marginBonus = 0)
		{
			int num = aliveCrewmates - aliveImpostors;
			Tier tier = ((!forceCalmBase) ? BaseTierForMargin(num + marginBonus) : Tier.Calm);
			if (!isLocalImpostor)
			{
				return CrewmateTrackFiles[(int)tier];
			}
			Tier tier2;
			if (totalImpostors <= 1)
			{
				tier2 = tier;
			}
			else
			{
				bool flag = aliveImpostors <= 1;
				tier2 = ((num <= 1) ? Tier.Climax : ((Tier)((!flag) ? Math.Min(1, (int)tier) : Math.Min(2, (int)(tier + 1)))));
			}
			return ImpostorTrackFiles[(int)tier2];
		}

		private static void NormalizeAudioState()
		{
			if (!((Object)(object)_runner == (Object)null) && !((Object)(object)_sourceA == (Object)null) && !((Object)(object)_sourceB == (Object)null))
			{
				_runner.CancelFade();
				if (ActiveSource.isPlaying)
				{
					ActiveSource.volume = TargetVolume;
				}
				if (InactiveSource.isPlaying)
				{
					_runner.StopAndSilenceImmediate(InactiveSource);
				}
			}
		}

		public override void Load()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			Log = ((BasePlugin)this).Log;
			ClassInjector.RegisterTypeInIl2Cpp<DanganronpaVotesRunner>();
			Harmony val = new Harmony("com.kris.danganronpavotes");
			val.PatchAll(Assembly.GetExecutingAssembly());
			StartAudioDownloads();
			SceneManager.activeSceneChanged += UnityAction<Scene, Scene>.op_Implicit((Action<Scene, Scene>)OnActiveSceneChanged);
			Log.LogInfo((object)"DanganronpaVotes loaded successfully (IL2CPP).");
			try
			{
				ManualLogSource log = Log;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(19, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Paths.PluginPath = ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(Paths.PluginPath);
				}
				log.LogInfo(val2);
			}
			catch
			{
			}
		}

		private static void OnActiveSceneChanged(Scene oldScene, Scene newScene)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			if (((Scene)(ref newScene)).name == "MainMenu")
			{
				Log.LogInfo((object)"Returned to the main menu; stopping music immediately.");
				StopVoteMusicImmediate();
			}
			try
			{
				if ((Object)(object)SoundManager.Instance != (Object)null)
				{
					EnsureAudioSetup();
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Log;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(44, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Failed to prepare audio after scene change: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
				}
				log.LogError(val);
			}
		}

		private static void EnsureAudioSetup()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			if (!((Object)(object)_sourceA != (Object)null) || !((Object)(object)_sourceB != (Object)null))
			{
				GameObject val = new GameObject("DanganronpaVotesAudio");
				Object.DontDestroyOnLoad((Object)(object)val);
				_sourceA = val.AddComponent<AudioSource>();
				_sourceA.playOnAwake = false;
				_sourceA.loop = true;
				_sourceA.volume = 0f;
				_sourceB = val.AddComponent<AudioSource>();
				_sourceB.playOnAwake = false;
				_sourceB.loop = true;
				_sourceB.volume = 0f;
				TryRouteToMusicChannel(logResult: true);
				_usingA = true;
				_runner = val.AddComponent<DanganronpaVotesRunner>();
				Log.LogInfo((object)"Audio object created or recreated.");
			}
		}

		private static bool TryRouteToMusicChannel(bool logResult)
		{
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Expected O, but got Unknown
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			bool flag2 = default(bool);
			try
			{
				if ((Object)(object)_sourceA == (Object)null || (Object)(object)_sourceB == (Object)null)
				{
					return false;
				}
				AudioMixerGroup val = (((Object)(object)SoundManager.Instance != (Object)null) ? SoundManager.Instance.MusicChannel : null);
				if ((Object)(object)val == (Object)null)
				{
					val = FindMusicGroupFallback();
				}
				if ((Object)(object)val == (Object)null)
				{
					if (logResult)
					{
						Log.LogWarning((object)"SoundManager.Instance.MusicChannel is still null; will retry automatically.");
					}
					return false;
				}
				bool flag = false;
				if ((Object)(object)_sourceA.outputAudioMixerGroup != (Object)(object)val)
				{
					_sourceA.outputAudioMixerGroup = val;
					flag = true;
				}
				if ((Object)(object)_sourceB.outputAudioMixerGroup != (Object)(object)val)
				{
					_sourceB.outputAudioMixerGroup = val;
					flag = true;
				}
				if (flag || logResult)
				{
					ManualLogSource log = Log;
					BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(76, 1, ref flag2);
					if (flag2)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("AudioSources routed to mixer group '");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)val).name);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("': the volume slider should affect them.");
					}
					log.LogInfo(val2);
				}
				return true;
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Log;
				BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(38, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Failed to route to the music channel: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(ex.Message);
				}
				log2.LogError(val3);
				return false;
			}
		}

		private static AudioMixerGroup FindMusicGroupFallback()
		{
			//IL_03e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ea: Expected O, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			//IL_037b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0382: Expected O, but got Unknown
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Expected O, but got Unknown
			bool flag2 = default(bool);
			try
			{
				if ((Object)(object)_fallbackMusicGroup != (Object)null)
				{
					return _fallbackMusicGroup;
				}
				if (Time.realtimeSinceStartup < _nextFallbackSearch)
				{
					return null;
				}
				_nextFallbackSearch = Time.realtimeSinceStartup + 2f;
				bool flag = !_fallbackDumped;
				AudioMixerGroup val = null;
				string text = null;
				SoundManager instance = SoundManager.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					PropertyInfo[] properties = typeof(SoundManager).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					foreach (PropertyInfo propertyInfo in properties)
					{
						if (propertyInfo.PropertyType != typeof(AudioMixerGroup) || propertyInfo.GetIndexParameters().Length != 0)
						{
							continue;
						}
						AudioMixerGroup val2 = null;
						try
						{
							object? value = propertyInfo.GetValue(instance);
							val2 = (AudioMixerGroup)((value is AudioMixerGroup) ? value : null);
						}
						catch
						{
						}
						if (flag)
						{
							ManualLogSource log = Log;
							BepInExInfoLogInterpolatedStringHandler val3 = new BepInExInfoLogInterpolatedStringHandler(34, 2, ref flag2);
							if (flag2)
							{
								((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("SoundManager.");
								((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(propertyInfo.Name);
								((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(" (AudioMixerGroup) = ");
								((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(((Object)(object)val2 != (Object)null) ? ((Object)val2).name : "null");
							}
							log.LogInfo(val3);
						}
						if ((Object)(object)val == (Object)null && (Object)(object)val2 != (Object)null && propertyInfo.Name.IndexOf("music", StringComparison.OrdinalIgnoreCase) >= 0)
						{
							val = val2;
							text = "SoundManager." + propertyInfo.Name;
						}
					}
				}
				Il2CppArrayBase<AudioMixer> val4 = Resources.FindObjectsOfTypeAll<AudioMixer>();
				if (val4 != null && val4.Length > 0)
				{
					foreach (AudioMixer item in val4)
					{
						if ((Object)(object)item == (Object)null)
						{
							continue;
						}
						Il2CppReferenceArray<AudioMixerGroup> val5 = item.FindMatchingGroups("Master");
						if (val5 == null || ((Il2CppArrayBase<AudioMixerGroup>)(object)val5).Length == 0)
						{
							val5 = item.FindMatchingGroups(string.Empty);
						}
						if (val5 == null)
						{
							continue;
						}
						foreach (AudioMixerGroup item2 in (Il2CppArrayBase<AudioMixerGroup>)(object)val5)
						{
							if ((Object)(object)item2 == (Object)null)
							{
								continue;
							}
							if (flag)
							{
								ManualLogSource log2 = Log;
								BepInExInfoLogInterpolatedStringHandler val3 = new BepInExInfoLogInterpolatedStringHandler(25, 2, ref flag2);
								if (flag2)
								{
									((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("AudioMixer '");
									((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(((Object)item).name);
									((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("' -> group '");
									((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(((Object)item2).name);
									((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("'");
								}
								log2.LogInfo(val3);
							}
							if ((Object)(object)val == (Object)null && ((Object)item2).name.IndexOf("music", StringComparison.OrdinalIgnoreCase) >= 0)
							{
								val = item2;
								text = "AudioMixer '" + ((Object)item).name + "'";
							}
						}
					}
					_fallbackDumped = true;
				}
				if ((Object)(object)val != (Object)null)
				{
					_fallbackMusicGroup = val;
					ManualLogSource log3 = Log;
					BepInExInfoLogInterpolatedStringHandler val3 = new BepInExInfoLogInterpolatedStringHandler(45, 2, ref flag2);
					if (flag2)
					{
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Alternative music group found: '");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(((Object)val).name);
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("' (source: ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(text);
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral(").");
					}
					log3.LogInfo(val3);
				}
				return val;
			}
			catch (Exception ex)
			{
				ManualLogSource log4 = Log;
				BepInExErrorLogInterpolatedStringHandler val6 = new BepInExErrorLogInterpolatedStringHandler(54, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("Error while searching for an alternative music group: ");
					((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<string>(ex.Message);
				}
				log4.LogError(val6);
				return null;
			}
		}

		private static object ReadMember(object target, Type type, string name)
		{
			PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
			if (property != null && property.GetIndexParameters().Length == 0)
			{
				MethodInfo getMethod = property.GetGetMethod(nonPublic: true);
				if (getMethod != null)
				{
					return property.GetValue(getMethod.IsStatic ? null : target);
				}
			}
			FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
			if (field != null)
			{
				return field.GetValue(field.IsStatic ? null : target);
			}
			return null;
		}

		private static Type[] SafeGetTypes(Assembly asm)
		{
			try
			{
				return asm.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				List<Type> list = new List<Type>();
				Type[] types = ex.Types;
				foreach (Type type in types)
				{
					if (type != null)
					{
						list.Add(type);
					}
				}
				return list.ToArray();
			}
		}

		private static Func<float> BuildGameMusicVolumeReader()
		{
			Type dm = null;
			Type[] array = SafeGetTypes(typeof(SoundManager).Assembly);
			foreach (Type type in array)
			{
				if (type.Name == "DataManager")
				{
					dm = type;
					break;
				}
			}
			if (dm == null)
			{
				return null;
			}
			Func<float> func = delegate
			{
				object obj = ReadMember(null, dm, "Settings");
				if (obj == null)
				{
					return -1f;
				}
				object obj2 = ReadMember(obj, obj.GetType(), "Audio");
				if (obj2 == null)
				{
					return -1f;
				}
				object obj3 = ReadMember(obj2, obj2.GetType(), "MusicVolume");
				return (obj3 == null) ? (-1f) : Convert.ToSingle(obj3);
			};
			return (func() >= 0f) ? func : null;
		}

		private static AudioMixer GetMusicMixer()
		{
			try
			{
				SoundManager instance = SoundManager.Instance;
				if ((Object)(object)instance != (Object)null && (Object)(object)instance.MusicChannel != (Object)null)
				{
					return instance.MusicChannel.audioMixer;
				}
				if ((Object)(object)_fallbackMusicGroup != (Object)null)
				{
					return _fallbackMusicGroup.audioMixer;
				}
			}
			catch
			{
			}
			return null;
		}

		private static float ReadSliderValue(out float rawStatic, out float rawSettings)
		{
			rawStatic = float.NaN;
			rawSettings = float.NaN;
			try
			{
				rawStatic = SoundManager.MusicVolume;
			}
			catch
			{
			}
			try
			{
				if (_gameMusicVolumeReader == null && !_gameMusicVolumeSearched)
				{
					_gameMusicVolumeSearched = true;
					_gameMusicVolumeReader = BuildGameMusicVolumeReader();
				}
				if (_gameMusicVolumeReader != null)
				{
					rawSettings = _gameMusicVolumeReader();
				}
			}
			catch
			{
			}
			if (rawSettings >= 0f && rawSettings <= 1f)
			{
				return rawSettings;
			}
			return -1f;
		}

		private static void UpdateLiveMusicVolume()
		{
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			if (!UseGameMusicVolume || Time.frameCount % 10 != 0 || (Object)(object)_sourceA == (Object)null || (Object)(object)_sourceB == (Object)null)
			{
				return;
			}
			bool flag = default(bool);
			try
			{
				float targetVolume = TargetVolume;
				RefreshGameMusicVolume(logAlways: false, quiet: true);
				float targetVolume2 = TargetVolume;
				if (Math.Abs(targetVolume2 - targetVolume) < 0.001f)
				{
					return;
				}
				AudioSource[] array = (AudioSource[])(object)new AudioSource[2] { _sourceA, _sourceB };
				AudioSource[] array2 = array;
				foreach (AudioSource val in array2)
				{
					if (val.isPlaying && Math.Abs(val.volume - targetVolume) < 0.01f)
					{
						val.volume = targetVolume2;
					}
				}
				ManualLogSource log = Log;
				BepInExDebugLogInterpolatedStringHandler val2 = new BepInExDebugLogInterpolatedStringHandler(45, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Music slider changed live: target volume ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(targetVolume, "F2");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" -> ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(targetVolume2, "F2");
				}
				log.LogDebug(val2);
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Log;
				BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(29, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Error adjusting volume live: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(ex.Message);
				}
				log2.LogError(val3);
			}
		}

		private static void RefreshGameMusicVolume(bool logAlways = false, bool quiet = false)
		{
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Expected O, but got Unknown
			if (!UseGameMusicVolume)
			{
				return;
			}
			try
			{
				float rawStatic;
				float rawSettings;
				float num = ReadSliderValue(out rawStatic, out rawSettings);
				float num2 = float.NaN;
				AudioMixer musicMixer = GetMusicMixer();
				if ((Object)(object)musicMixer != (Object)null && !musicMixer.GetFloat("MusicVolume", ref num2))
				{
					num2 = float.NaN;
				}
				bool flag = !float.IsNaN(num2) && num2 < -0.5f;
				float num3 = ((num >= 0f && !flag) ? num : 1f);
				string value = (flag ? "applied by the mixer" : ((num >= 0f) ? "applied by the plugin" : "slider could not be read"));
				string value2 = (float.IsNaN(num2) ? "?" : (num2.ToString("F1") + " dB"));
				string text = $"Music slider: SoundManager.MusicVolume={rawStatic:F2}, Settings.Audio.MusicVolume={rawSettings:F2}; MusicVolume mixer={value2} -> {value}, factor={num3:F2}";
				if (!quiet && (logAlways || text != _lastVolumeLog))
				{
					Log.LogInfo((object)text);
					_lastVolumeLog = text;
				}
				_gameMusicVolume = num3;
			}
			catch (Exception ex)
			{
				ManualLogSource log = Log;
				bool flag2 = default(bool);
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(37, 1, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error reading the game music volume: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				log.LogError(val);
			}
		}

		private static void LogVolumeDiagnostics()
		{
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Expected O, but got Unknown
			//IL_02b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b8: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Expected O, but got Unknown
			bool flag = default(bool);
			try
			{
				Il2CppArrayBase<AudioMixer> val = Resources.FindObjectsOfTypeAll<AudioMixer>();
				BepInExInfoLogInterpolatedStringHandler val2;
				if (val != null)
				{
					float value = default(float);
					foreach (AudioMixer item in val)
					{
						if ((Object)(object)item == (Object)null)
						{
							continue;
						}
						StringBuilder stringBuilder = new StringBuilder();
						string[] mixerParamCandidates = MixerParamCandidates;
						foreach (string text in mixerParamCandidates)
						{
							if (item.GetFloat(text, ref value))
							{
								StringBuilder stringBuilder2 = stringBuilder;
								StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(6, 2, stringBuilder2);
								handler.AppendFormatted(text);
								handler.AppendLiteral("=");
								handler.AppendFormatted(value, "F1");
								handler.AppendLiteral(" dB; ");
								stringBuilder2.Append(ref handler);
							}
						}
						ManualLogSource log = Log;
						val2 = new BepInExInfoLogInterpolatedStringHandler(21, 2, ref flag);
						if (flag)
						{
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Mixer parameters '");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)item).name);
							((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("': ");
							((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>((stringBuilder.Length > 0) ? stringBuilder.ToString() : "none of the tested names exist");
						}
						log.LogInfo(val2);
					}
				}
				Il2CppArrayBase<AudioSource> val3 = Resources.FindObjectsOfTypeAll<AudioSource>();
				int num = 0;
				if (val3 != null)
				{
					foreach (AudioSource item2 in val3)
					{
						if ((Object)(object)item2 == (Object)null || (Object)(object)item2 == (Object)(object)_sourceA || (Object)(object)item2 == (Object)(object)_sourceB)
						{
							continue;
						}
						AudioMixerGroup outputAudioMixerGroup = item2.outputAudioMixerGroup;
						if (!((Object)(object)outputAudioMixerGroup == (Object)null) && !(((Object)outputAudioMixerGroup).name != "Music"))
						{
							ManualLogSource log2 = Log;
							val2 = new BepInExInfoLogInterpolatedStringHandler(53, 3, ref flag);
							if (flag)
							{
								((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Game AudioSource in 'Music': clip=");
								((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(((Object)(object)item2.clip != (Object)null) ? ((Object)item2.clip).name : "-");
								((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", volume=");
								((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<float>(item2.volume, "F2");
								((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", playing=");
								((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<bool>(item2.isPlaying);
							}
							log2.LogInfo(val2);
							if (++num >= 6)
							{
								break;
							}
						}
					}
				}
				ManualLogSource log3 = Log;
				val2 = new BepInExInfoLogInterpolatedStringHandler(30, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Game AudioSources in 'Music': ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(num);
				}
				log3.LogInfo(val2);
			}
			catch (Exception ex)
			{
				ManualLogSource log4 = Log;
				BepInExWarningLogInterpolatedStringHandler val4 = new BepInExWarningLogInterpolatedStringHandler(27, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val4).AppendLiteral("Volume diagnostics failed: ");
					((BepInExLogInterpolatedStringHandler)val4).AppendFormatted<string>(ex.Message);
				}
				log4.LogWarning(val4);
			}
		}

		public static void PlayVoteMusic()
		{
			EnsureAudioSetup();
			TryRouteToMusicChannel(logResult: false);
			RefreshGameMusicVolume(logAlways: true);
			LogVolumeDiagnostics();
			_meetingActive = true;
			_pendingLocalVoteMuffle = false;
			UpdateVoteMusic("Voting started");
		}

		private static void StartAudioDownloads()
		{
			if (_audioDownloadTask != null)
			{
				return;
			}
			try
			{
				string audioDir = ResolveAudioDirectory();
				if (string.IsNullOrEmpty(audioDir))
				{
					Log.LogWarning((object)"Could not determine the audio folder; skipping automatic download.");
					return;
				}
				Directory.CreateDirectory(audioDir);
				Log.LogInfo((object)("Checking for OGG files from GitHub in: " + audioDir));
				_audioDownloadTask = Task.Run(delegate
				{
					DownloadMissingAudioFiles(audioDir);
				});
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Failed to start audio downloads: " + ex));
			}
		}

		private static void DownloadMissingAudioFiles(string audioDir)
		{
			List<string> list = new List<string>();
			list.AddRange(CrewmateTrackFiles);
			list.AddRange(ImpostorTrackFiles);
			foreach (string item in list)
			{
				string text = Path.GetFileNameWithoutExtension(item) + ".ogg";
				string text2 = Path.Combine(audioDir, text);
				string text3 = text2 + ".download";
				if (File.Exists(text2))
				{
					Log.LogInfo((object)("Audio already downloaded: " + text));
					continue;
				}
				try
				{
					string requestUriString = "https://github.com/BdeBrunoDR/dynamicmeetingsaudio/releases/download/audio-v1/" + Uri.EscapeDataString(text);
					HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUriString);
					httpWebRequest.Method = "GET";
					httpWebRequest.UserAgent = "DanganronpaVotes/1.3.0";
					httpWebRequest.AllowAutoRedirect = true;
					httpWebRequest.Timeout = 20000;
					httpWebRequest.ReadWriteTimeout = 20000;
					using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
					{
						using Stream stream = httpWebResponse.GetResponseStream();
						using FileStream fileStream = new FileStream(text3, FileMode.Create, FileAccess.Write, FileShare.None);
						if (httpWebResponse.ContentLength > 104857600)
						{
							throw new InvalidDataException("The file exceeds the 100 MB limit.");
						}
						byte[] array = new byte[81920];
						long num = 0L;
						int num2;
						while ((num2 = stream.Read(array, 0, array.Length)) > 0)
						{
							num += num2;
							if (num > 104857600)
							{
								throw new InvalidDataException("The download exceeds the 100 MB limit.");
							}
							fileStream.Write(array, 0, num2);
						}
					}
					byte[] array2 = new byte[4];
					using (FileStream fileStream2 = new FileStream(text3, FileMode.Open, FileAccess.Read, FileShare.Read))
					{
						if (fileStream2.Length < 4 || fileStream2.Read(array2, 0, 4) != 4 || array2[0] != 79 || array2[1] != 103 || array2[2] != 103 || array2[3] != 83)
						{
							throw new InvalidDataException("The response does not look like a valid OGG file.");
						}
					}
					if (!File.Exists(text2))
					{
						File.Move(text3, text2);
					}
					else
					{
						File.Delete(text3);
					}
					Log.LogInfo((object)("Audio downloaded successfully: " + text));
				}
				catch (Exception ex)
				{
					try
					{
						if (File.Exists(text3))
						{
							File.Delete(text3);
						}
					}
					catch
					{
					}
					Log.LogWarning((object)("Failed to download " + text + " from GitHub: " + ex.Message));
				}
			}
			Log.LogInfo((object)"Audio download check completed.");
		}

		private static string ResolveAudioDirectory()
		{
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Expected O, but got Unknown
			if (_audioDir != null)
			{
				return _audioDir;
			}
			List<string> list = new List<string>();
			try
			{
				list.Add(Path.Combine(Paths.PluginPath, "DanganronpaVotes", "Audio"));
			}
			catch
			{
			}
			try
			{
				string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
				if (!string.IsNullOrEmpty(directoryName))
				{
					list.Add(Path.Combine(directoryName, "DanganronpaVotes", "Audio"));
					list.Add(Path.Combine(directoryName, "Audio"));
				}
			}
			catch
			{
			}
			try
			{
				string environmentVariable = Environment.GetEnvironmentVariable("STAR_DATA_PATH");
				if (!string.IsNullOrEmpty(environmentVariable))
				{
					list.Add(Path.Combine(environmentVariable, "DanganronpaVotes", "Audio"));
				}
			}
			catch
			{
			}
			try
			{
				list.Add(Path.Combine(Application.persistentDataPath, "DanganronpaVotes", "Audio"));
			}
			catch
			{
			}
			bool flag = default(bool);
			foreach (string item in list)
			{
				if (Directory.Exists(item))
				{
					_audioDir = item;
					ManualLogSource log = Log;
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(14, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Audio folder: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(item);
					}
					log.LogInfo(val);
					return item;
				}
			}
			Log.LogWarning((object)("No audio folder exists. Paths checked: " + string.Join(" | ", list)));
			return (list.Count > 0) ? list[0] : null;
		}

		private static AudioClip GetOrLoadCleanClip(string track)
		{
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Expected O, but got Unknown
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Expected O, but got Unknown
			bool flag = default(bool);
			if (_cleanClipCache.TryGetValue(track, out var value))
			{
				if ((Object)(object)value != (Object)null)
				{
					return value;
				}
				_cleanClipCache.Remove(track);
				ManualLogSource log = Log;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(81, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Cached clean clip '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(track);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' is no longer valid (released by Unity); reloading from disk.");
				}
				log.LogInfo(val);
			}
			string text = ResolveAudioDirectory();
			string text2 = ResolveTrackPath(text, track);
			if (text2 == null)
			{
				ManualLogSource log2 = Log;
				BepInExWarningLogInterpolatedStringHandler val2 = new BepInExWarningLogInterpolatedStringHandler(61, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Audio file for '");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(track);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("' (searching for .ogg [Vorbis] and .wav) in: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(text ?? "(audio folder not found)");
				}
				log2.LogWarning(val2);
				return null;
			}
			if (!string.Equals(Path.GetExtension(text2), ".wav", StringComparison.OrdinalIgnoreCase))
			{
				QueueBackgroundLoad(track, text2);
				return null;
			}
			try
			{
				byte[] fileBytes = File.ReadAllBytes(text2);
				if (!WavUtility.TryParse(fileBytes, out var samples, out var channels, out var sampleRate))
				{
					ManualLogSource log3 = Log;
					BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(43, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Could not decode WAV (unsupported format): ");
						((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(text2);
					}
					log3.LogError(val3);
					return null;
				}
				AudioClip val4 = WavUtility.CreateClip(track, samples, channels, sampleRate);
				_cleanClipCache[track] = val4;
				return val4;
			}
			catch (Exception ex)
			{
				ManualLogSource log4 = Log;
				BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(21, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Error loading audio: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Exception>(ex);
				}
				log4.LogError(val3);
				return null;
			}
		}

		private static bool IsInMatch()
		{
			try
			{
				return (Object)(object)ShipStatus.Instance != (Object)null;
			}
			catch
			{
				return false;
			}
		}

		private static void PumpPreload()
		{
			bool flag = IsInMatch();
			if (flag != _wasInMatch)
			{
				_wasInMatch = flag;
				if (!flag)
				{
					_roleTracksQueued = false;
					_preloadQueue.Clear();
					ReleaseClips(CrewmateTrackFiles);
					ReleaseClips(ImpostorTrackFiles);
					Log.LogInfo((object)"Match ended: tracks released from memory.");
				}
			}
			if (Time.frameCount % 30 == 0)
			{
				if (flag)
				{
					TryQueueRoleTracks();
				}
				ReleaseUnusedMuffled();
				TryRouteToMusicChannel(logResult: false);
				CollectGarbageWhenIdle();
			}
			if (_preloadQueue.Count == 0 || _pendingLoadTasks.Count > 0)
			{
				return;
			}
			while (_preloadQueue.Count > 0)
			{
				string text = _preloadQueue.Dequeue();
				if (!_failedLoadTracks.Contains(text) && !_buildingClean.Contains(text) && (!_cleanClipCache.TryGetValue(text, out var value) || !((Object)(object)value != (Object)null)))
				{
					string text2 = ResolveTrackPath(ResolveAudioDirectory(), text);
					if (text2 != null)
					{
						QueueBackgroundLoad(text, text2);
						break;
					}
				}
			}
		}

		private static void TryQueueRoleTracks()
		{
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Expected O, but got Unknown
			bool flag = default(bool);
			try
			{
				PlayerControl localPlayer = PlayerControl.LocalPlayer;
				if ((Object)(object)localPlayer == (Object)null || (Object)(object)localPlayer.Data == (Object)null || (Object)(object)localPlayer.Data.Role == (Object)null)
				{
					return;
				}
				bool isImpostor = localPlayer.Data.Role.IsImpostor;
				if (!_roleTracksQueued || isImpostor != _queuedForImpostor)
				{
					if (_roleTracksQueued)
					{
						_preloadQueue.Clear();
						ReleaseClips(_queuedForImpostor ? ImpostorTrackFiles : CrewmateTrackFiles);
					}
					_roleTracksQueued = true;
					_queuedForImpostor = isImpostor;
					string[] array = (isImpostor ? ImpostorTrackFiles : CrewmateTrackFiles);
					foreach (string item in array)
					{
						_preloadQueue.Enqueue(item);
					}
					ManualLogSource log = Log;
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(60, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Role assigned (");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(isImpostor ? "Impostor" : "Crewmate");
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("): preloading its 3 tracks in the background.");
					}
					log.LogInfo(val);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Log;
				BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(36, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Error checking role for preloading: ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex);
				}
				log2.LogError(val2);
			}
		}

		private static void CollectGarbageWhenIdle()
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			if (!_gcPending || _meetingActive || _pendingLoadTasks.Count > 0 || _clipBuildQueue.Count > 0 || _muffleJobs.Count > 0 || _preloadQueue.Count > 0)
			{
				return;
			}
			_gcPending = false;
			try
			{
				GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
				GC.Collect();
			}
			catch (Exception ex)
			{
				ManualLogSource log = Log;
				bool flag = default(bool);
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(36, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not force garbage collection: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				log.LogWarning(val);
			}
		}

		private static void ReleaseClips(string[] tracks)
		{
			foreach (string text in tracks)
			{
				if (_meetingActive && text == _currentTrackName)
				{
					continue;
				}
				if (_cleanClipCache.TryGetValue(text, out var value))
				{
					_cleanClipCache.Remove(text);
					if ((Object)(object)value != (Object)null)
					{
						Object.Destroy((Object)(object)value);
					}
				}
				if (_muffledClipCache.TryGetValue(text, out var value2))
				{
					_muffledClipCache.Remove(text);
					if ((Object)(object)value2 != (Object)null)
					{
						Object.Destroy((Object)(object)value2);
					}
				}
				_failedLoadTracks.Remove(text);
			}
			_gcPending = true;
		}

		private static string ResolveTrackPath(string audioDir, string track)
		{
			if (audioDir == null)
			{
				return null;
			}
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(track);
			string[] supportedExtensions = AudioDecoder.SupportedExtensions;
			foreach (string text in supportedExtensions)
			{
				string text2 = Path.Combine(audioDir, fileNameWithoutExtension + text);
				if (File.Exists(text2))
				{
					return text2;
				}
			}
			return null;
		}

		private static void QueueBackgroundLoad(string track, string path)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			if (!_failedLoadTracks.Contains(track) && !_pendingLoadTasks.ContainsKey(track) && !_buildingClean.Contains(track))
			{
				ManualLogSource log = Log;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(74, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Decoding '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Path.GetFileName(path));
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' in the background (music will start when decoding finishes)...");
				}
				log.LogInfo(val);
				_pendingLoadTasks[track] = Task.Run(() => DecodeFileInBackground(path));
			}
		}

		private static DecodedAudio DecodeFileInBackground(string path)
		{
			DecodedAudio decodedAudio = new DecodedAudio
			{
				FileName = Path.GetFileName(path)
			};
			Stopwatch stopwatch = Stopwatch.StartNew();
			try
			{
				byte[] fileBytes = File.ReadAllBytes(path);
				if (AudioDecoder.TryDecode(fileBytes, out var samples, out var channels, out var sampleRate, out var format, out var error))
				{
					AudioDecoder.ReduceForMemory(ref samples, ref channels, ref sampleRate);
					decodedAudio.Samples = samples;
					decodedAudio.Channels = channels;
					decodedAudio.SampleRate = sampleRate;
					decodedAudio.Format = format;
				}
				else
				{
					decodedAudio.Format = format;
					decodedAudio.Error = error;
				}
			}
			catch (Exception ex)
			{
				decodedAudio.Error = ex.ToString();
			}
			decodedAudio.Milliseconds = stopwatch.ElapsedMilliseconds;
			return decodedAudio;
		}

		internal static void PollPendingAudioLoads()
		{
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Expected O, but got Unknown
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0287: Expected O, but got Unknown
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Expected O, but got Unknown
			UpdateLiveMusicVolume();
			PumpPreload();
			PumpMuffleJobs();
			PumpClipBuilds();
			if (_pendingLoadTasks.Count == 0)
			{
				return;
			}
			List<string> list = null;
			foreach (KeyValuePair<string, Task<DecodedAudio>> pendingLoadTask in _pendingLoadTasks)
			{
				if (pendingLoadTask.Value.IsCompleted)
				{
					(list ?? (list = new List<string>())).Add(pendingLoadTask.Key);
				}
			}
			if (list == null)
			{
				return;
			}
			bool flag = default(bool);
			foreach (string item in list)
			{
				Task<DecodedAudio> task = _pendingLoadTasks[item];
				_pendingLoadTasks.Remove(item);
				if (task.IsFaulted)
				{
					_failedLoadTracks.Add(item);
					ManualLogSource log = Log;
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(19, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error decoding '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(item);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("': ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<AggregateException>(task.Exception);
					}
					log.LogError(val);
					continue;
				}
				DecodedAudio result = task.Result;
				if (result.Samples == null)
				{
					_failedLoadTracks.Add(item);
					ManualLogSource log2 = Log;
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 3, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not decode '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(result.FileName);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' (format: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(result.Format);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("): ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(result.Error);
					}
					log2.LogError(val);
					continue;
				}
				BepInExInfoLogInterpolatedStringHandler val2;
				if (!IsTrackWantedForRole(item))
				{
					ManualLogSource log3 = Log;
					val2 = new BepInExInfoLogInterpolatedStringHandler(32, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("'");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(result.FileName);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("' discarded: not for your role.");
					}
					log3.LogInfo(val2);
					result.Samples = null;
					_gcPending = true;
					continue;
				}
				double num = (double)result.Samples.Length / (double)result.Channels / (double)result.SampleRate;
				ManualLogSource log4 = Log;
				val2 = new BepInExInfoLogInterpolatedStringHandler(67, 6, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("'");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(result.FileName);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("' decoded (");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(result.Format);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(result.Channels);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" channels, ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(result.SampleRate);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" Hz, ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<double>(num, "F1");
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("s) in ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<long>(result.Milliseconds);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" ms. Building clip in chunks...");
				}
				log4.LogInfo(val2);
				QueueClipBuild(item, muffled: false, result.Samples, result.Channels, result.SampleRate);
			}
		}

		private static void EnsureMuffledClipQueued(string track, float[] samples, int channels, int sampleRate)
		{
			if (_muffledClipCache.TryGetValue(track, out var value))
			{
				if ((Object)(object)value != (Object)null)
				{
					return;
				}
				_muffledClipCache.Remove(track);
			}
			if (!_pendingMuffleTasks.ContainsKey(track) && !_buildingMuffled.Contains(track))
			{
				_pendingMuffleInfo[track] = (channels, sampleRate);
				_pendingMuffleTasks[track] = Task.Run(() => WavUtility.ApplyLowPassInPlace(samples, channels, sampleRate, 800f));
			}
		}

		internal static void PollPendingMuffleClips()
		{
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			if (_pendingMuffleTasks.Count == 0)
			{
				return;
			}
			List<string> list = null;
			foreach (KeyValuePair<string, Task<float[]>> pendingMuffleTask in _pendingMuffleTasks)
			{
				if (pendingMuffleTask.Value.IsCompleted)
				{
					(list ?? (list = new List<string>())).Add(pendingMuffleTask.Key);
				}
			}
			if (list == null)
			{
				return;
			}
			bool flag = default(bool);
			foreach (string item in list)
			{
				Task<float[]> task = _pendingMuffleTasks[item];
				_pendingMuffleTasks.Remove(item);
				var (channels, sampleRate) = _pendingMuffleInfo[item];
				_pendingMuffleInfo.Remove(item);
				if (task.IsFaulted)
				{
					ManualLogSource log = Log;
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(40, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error generating muffled version of '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(item);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("': ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<AggregateException>(task.Exception);
					}
					log.LogError(val);
				}
				else
				{
					QueueClipBuild(item, muffled: true, task.Result, channels, sampleRate);
				}
			}
		}

		private static bool TryApplyMuffle()
		{
			if ((Object)(object)_runner == (Object)null || _currentTrackName == null)
			{
				return false;
			}
			NormalizeAudioState();
			if ((Object)(object)ActiveSource == (Object)null || !ActiveSource.isPlaying || _isMuffled)
			{
				return false;
			}
			if (!_muffledClipCache.TryGetValue(_currentTrackName, out var value))
			{
				return false;
			}
			if ((Object)(object)value == (Object)null)
			{
				_muffledClipCache.Remove(_currentTrackName);
				return false;
			}
			AudioSource activeSource = ActiveSource;
			AudioSource inactiveSource = InactiveSource;
			inactiveSource.clip = value;
			inactiveSource.time = activeSource.time % value.length;
			inactiveSource.volume = 0f;
			inactiveSource.Play();
			_runner.StartCrossfade(activeSource, inactiveSource, 0.4f, TargetVolume);
			_usingA = !_usingA;
			_isMuffled = true;
			return true;
		}

		public static void OnLocalVoteCast()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			Log.LogInfo((object)"OnLocalVoteCast() invoked.");
			if (IsLocalPlayerGhost())
			{
				return;
			}
			if (!TryApplyMuffle())
			{
				_pendingLocalVoteMuffle = true;
				ManualLogSource log = Log;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(159, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("OnLocalVoteCast: not applied yet (runner or track is null, nothing is playing, already muffled, or the muffled version of '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(_currentTrackName);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' is not ready); queued until ready.");
				}
				log.LogInfo(val);
			}
			else
			{
				Log.LogInfo((object)"Vote cast: muffling the music.");
			}
		}

		public static void OnPlayerLeft()
		{
			if (!((Object)(object)_sourceA == (Object)null) && !((Object)(object)_sourceB == (Object)null) && _meetingActive)
			{
				Log.LogInfo((object)"A player left the match; recalculating tension level.");
				UpdateVoteMusic("Recalculation after a player left");
			}
		}

		private static void UpdateVoteMusic(string reason)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Expected O, but got Unknown
			(int aliveImpostors, int aliveCrewmates, int totalImpostors, int totalCrewmates) tuple = CountRoles();
			int item = tuple.aliveImpostors;
			int item2 = tuple.aliveCrewmates;
			int item3 = tuple.totalImpostors;
			int item4 = tuple.totalCrewmates;
			int num = item2 - item;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val;
			if (!_matchTotalsCaptured)
			{
				_matchTotalImpostors = item3;
				_matchTotalCrewmates = item4;
				_matchTotalsCaptured = true;
				ManualLogSource log = Log;
				val = new BepInExInfoLogInterpolatedStringHandler(53, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Match snapshot set: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_matchTotalImpostors);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" impostors / ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_matchTotalCrewmates);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" starting crewmates.");
				}
				log.LogInfo(val);
			}
			if (item2 < _matchTotalCrewmates || item < _matchTotalImpostors)
			{
				_anyDeathObservedThisMatch = true;
			}
			bool flag2 = !_anyDeathObservedThisMatch;
			bool flag3 = _isFirstMeetingOfMatch && flag2;
			int num2 = ((_isFirstMeetingOfMatch && !flag2) ? 2 : 0);
			bool flag4 = IsLocalPlayerImpostor();
			string text = PickTrackForVote(item, item2, _matchTotalImpostors, flag4, flag3, num2);
			ManualLogSource log2 = Log;
			val = new BepInExInfoLogInterpolatedStringHandler(159, 10, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("[");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(reason);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("] Alive impostors: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(item);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (of ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_matchTotalImpostors);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" starting) | Alive crewmates: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(item2);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (of ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_matchTotalCrewmates);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" starting) | Margin: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" | First meeting with no deaths: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<bool>(flag3);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" | First meeting bonus: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(num2);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" -> role: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(flag4 ? "Impostor" : "Crewmate");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" -> track: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(text);
			}
			log2.LogInfo(val);
			SwitchToTrack(text);
			if (IsLocalPlayerGhost() && TryApplyMuffle())
			{
				Log.LogInfo((object)"You are a ghost: music is muffled from the start of the meeting.");
			}
		}

		private static void SwitchToTrack(string track)
		{
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Expected O, but got Unknown
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			_wantedTrack = track;
			RefreshGameMusicVolume();
			NormalizeAudioState();
			bool isPlaying = ActiveSource.isPlaying;
			if (isPlaying && _currentTrackName == track)
			{
				return;
			}
			AudioClip orLoadCleanClip = GetOrLoadCleanClip(track);
			if ((Object)(object)orLoadCleanClip == (Object)null)
			{
				return;
			}
			bool flag = default(bool);
			if (!isPlaying)
			{
				TryRouteToMusicChannel(logResult: false);
				ActiveSource.clip = orLoadCleanClip;
				ActiveSource.volume = 0f;
				ActiveSource.Play();
				ManualLogSource log = Log;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(36, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Play: group=");
					BepInExInfoLogInterpolatedStringHandler obj = val;
					AudioMixerGroup outputAudioMixerGroup = ActiveSource.outputAudioMixerGroup;
					((BepInExLogInterpolatedStringHandler)obj).AppendFormatted<string>(((outputAudioMixerGroup != null) ? ((Object)outputAudioMixerGroup).name : null) ?? "NULL");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", track=");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(track);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", target volume=");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(TargetVolume, "F2");
				}
				log.LogInfo(val);
				_runner.StartFadeIn(ActiveSource, 2f, TargetVolume);
			}
			else
			{
				TryRouteToMusicChannel(logResult: false);
				AudioSource activeSource = ActiveSource;
				AudioSource inactiveSource = InactiveSource;
				inactiveSource.clip = orLoadCleanClip;
				inactiveSource.volume = 0f;
				inactiveSource.Play();
				ManualLogSource log2 = Log;
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(48, 3, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Play (crossfade): group=");
					BepInExInfoLogInterpolatedStringHandler obj2 = val;
					AudioMixerGroup outputAudioMixerGroup2 = inactiveSource.outputAudioMixerGroup;
					((BepInExLogInterpolatedStringHandler)obj2).AppendFormatted<string>(((outputAudioMixerGroup2 != null) ? ((Object)outputAudioMixerGroup2).name : null) ?? "NULL");
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", track=");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(track);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", target volume=");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<float>(TargetVolume, "F2");
				}
				log2.LogInfo(val);
				_runner.StartCrossfade(activeSource, inactiveSource, 1.5f, TargetVolume);
				_usingA = !_usingA;
			}
			_currentTrackName = track;
			_isMuffled = false;
			RequestMuffledForCurrent();
		}

		private static void RequestMuffledForCurrent()
		{
			//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Expected O, but got Unknown
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Expected O, but got Unknown
			bool flag = default(bool);
			try
			{
				string currentTrackName = _currentTrackName;
				if (currentTrackName == null || !_meetingActive || (_muffledClipCache.TryGetValue(currentTrackName, out var value) && (Object)(object)value != (Object)null) || _buildingMuffled.Contains(currentTrackName) || !_cleanClipCache.TryGetValue(currentTrackName, out var value2) || (Object)(object)value2 == (Object)null)
				{
					return;
				}
				int channels = value2.channels;
				int samples = value2.samples;
				int frequency = value2.frequency;
				if (channels > 0 && samples > 0 && frequency > 0)
				{
					float num = 1f / (MathF.PI * 2f * Mathf.Max(800f, 10f));
					float num2 = 1f / (float)Mathf.Max(frequency, 1);
					AudioClip val = AudioClip.Create(currentTrackName + "_muffled", samples, channels, frequency, false);
					((Object)val).hideFlags = (HideFlags)32;
					_buildingMuffled.Add(currentTrackName);
					_muffleJobs.Enqueue(new MuffleStreamJob
					{
						Track = currentTrackName,
						Source = value2,
						Dest = val,
						Channels = channels,
						SampleRate = frequency,
						TotalFrames = samples,
						Alpha = num2 / (num + num2),
						Prev = new float[channels]
					});
					ManualLogSource log = Log;
					BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(64, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Generating muffled version of '");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(currentTrackName);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("' (current track only, streamed).");
					}
					log.LogInfo(val2);
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Log;
				BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(33, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Error preparing muffled version: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Exception>(ex);
				}
				log2.LogError(val3);
			}
		}

		private static void PumpMuffleJobs()
		{
			//IL_026a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Expected O, but got Unknown
			if (_muffleJobs.Count == 0)
			{
				return;
			}
			Stopwatch stopwatch = Stopwatch.StartNew();
			bool flag = default(bool);
			while (_muffleJobs.Count > 0 && stopwatch.Elapsed.TotalMilliseconds < 2.0)
			{
				MuffleStreamJob muffleStreamJob = _muffleJobs.Peek();
				try
				{
					if ((Object)(object)muffleStreamJob.Source == (Object)null || (Object)(object)muffleStreamJob.Dest == (Object)null)
					{
						_muffleJobs.Dequeue();
						_buildingMuffled.Remove(muffleStreamJob.Track);
						if ((Object)(object)muffleStreamJob.Dest != (Object)null)
						{
							Object.Destroy((Object)(object)muffleStreamJob.Dest);
						}
						continue;
					}
					int channels = muffleStreamJob.Channels;
					int num = Math.Min(16384, muffleStreamJob.TotalFrames - muffleStreamJob.FrameOffset);
					int num2 = num * channels;
					if (muffleStreamJob.InBuf == null || ((Il2CppArrayBase<float>)(object)muffleStreamJob.InBuf).Length != num2)
					{
						muffleStreamJob.InBuf = new Il2CppStructArray<float>((long)num2);
						muffleStreamJob.OutBuf = new Il2CppStructArray<float>((long)num2);
					}
					if (!muffleStreamJob.Source.GetData(muffleStreamJob.InBuf, muffleStreamJob.FrameOffset))
					{
						throw new InvalidOperationException("GetData returned false");
					}
					float alpha = muffleStreamJob.Alpha;
					float[] prev = muffleStreamJob.Prev;
					for (int i = 0; i < num; i++)
					{
						int num3 = i * channels;
						for (int j = 0; j < channels; j++)
						{
							prev[j] += alpha * (((Il2CppArrayBase<float>)(object)muffleStreamJob.InBuf)[num3 + j] - prev[j]);
							((Il2CppArrayBase<float>)(object)muffleStreamJob.OutBuf)[num3 + j] = prev[j];
						}
					}
					muffleStreamJob.Dest.SetData(muffleStreamJob.OutBuf, muffleStreamJob.FrameOffset);
					muffleStreamJob.FrameOffset += num;
					if (muffleStreamJob.FrameOffset >= muffleStreamJob.TotalFrames)
					{
						_muffleJobs.Dequeue();
						_buildingMuffled.Remove(muffleStreamJob.Track);
						_gcPending = true;
						FinishMuffled(muffleStreamJob.Track, muffleStreamJob.Dest);
					}
				}
				catch (Exception ex)
				{
					_muffleJobs.Dequeue();
					_buildingMuffled.Remove(muffleStreamJob.Track);
					if ((Object)(object)muffleStreamJob.Dest != (Object)null)
					{
						Object.Destroy((Object)(object)muffleStreamJob.Dest);
					}
					ManualLogSource log = Log;
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(40, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Error generating muffled version of '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(muffleStreamJob.Track);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("': ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					log.LogError(val);
				}
			}
		}

		private static bool IsTrackWantedForRole(string track)
		{
			if (_meetingActive && track == _wantedTrack)
			{
				return true;
			}
			if (!_roleTracksQueued)
			{
				return true;
			}
			return Array.IndexOf(_queuedForImpostor ? ImpostorTrackFiles : CrewmateTrackFiles, track) >= 0;
		}

		private static bool PrioritizeWantedBuild()
		{
			if (!_meetingActive || _wantedTrack == null || _clipBuildQueue.Count == 0)
			{
				return false;
			}
			ClipBuildJob clipBuildJob = null;
			foreach (ClipBuildJob item in _clipBuildQueue)
			{
				if (!item.Muffled && item.Track == _wantedTrack)
				{
					clipBuildJob = item;
					break;
				}
			}
			if (clipBuildJob == null)
			{
				return false;
			}
			if (_clipBuildQueue.Peek() != clipBuildJob)
			{
				List<ClipBuildJob> list = new List<ClipBuildJob>(_clipBuildQueue);
				_clipBuildQueue.Clear();
				_clipBuildQueue.Enqueue(clipBuildJob);
				foreach (ClipBuildJob item2 in list)
				{
					if (item2 != clipBuildJob)
					{
						_clipBuildQueue.Enqueue(item2);
					}
				}
			}
			return true;
		}

		private static void QueueClipBuild(string track, bool muffled, float[] samples, int channels, int sampleRate)
		{
			(muffled ? _buildingMuffled : _buildingClean).Add(track);
			_clipBuildQueue.Enqueue(new ClipBuildJob
			{
				Track = track,
				Muffled = muffled,
				Samples = samples,
				Channels = channels,
				SampleRate = sampleRate
			});
		}

		private static void PumpClipBuilds()
		{
			//IL_02e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f0: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			if (_clipBuildQueue.Count == 0)
			{
				return;
			}
			double num = (PrioritizeWantedBuild() ? 12.0 : 2.0);
			Stopwatch stopwatch = Stopwatch.StartNew();
			bool flag = default(bool);
			while (_clipBuildQueue.Count > 0 && stopwatch.Elapsed.TotalMilliseconds < num)
			{
				ClipBuildJob clipBuildJob = _clipBuildQueue.Peek();
				if (!clipBuildJob.Muffled && !IsTrackWantedForRole(clipBuildJob.Track))
				{
					_clipBuildQueue.Dequeue();
					_buildingClean.Remove(clipBuildJob.Track);
					if ((Object)(object)clipBuildJob.Clip != (Object)null)
					{
						Object.Destroy((Object)(object)clipBuildJob.Clip);
					}
					clipBuildJob.Samples = null;
					_gcPending = true;
					ManualLogSource log = Log;
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(37, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Clip '");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(clipBuildJob.Track);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' discarded: not for your role.");
					}
					log.LogInfo(val);
					continue;
				}
				try
				{
					int channels = clipBuildJob.Channels;
					if (!clipBuildJob.Started)
					{
						clipBuildJob.TotalFrames = clipBuildJob.Samples.Length / channels;
						clipBuildJob.Clip = AudioClip.Create(clipBuildJob.Muffled ? (clipBuildJob.Track + "_muffled") : clipBuildJob.Track, clipBuildJob.TotalFrames, channels, clipBuildJob.SampleRate, false);
						((Object)clipBuildJob.Clip).hideFlags = (HideFlags)32;
						clipBuildJob.Started = true;
					}
					int num2 = Math.Min(16384, clipBuildJob.TotalFrames - clipBuildJob.FrameOffset);
					int num3 = num2 * channels;
					if (clipBuildJob.Buf == null || ((Il2CppArrayBase<float>)(object)clipBuildJob.Buf).Length != num3)
					{
						clipBuildJob.Buf = new Il2CppStructArray<float>((long)num3);
					}
					int num4 = clipBuildJob.FrameOffset * channels;
					for (int i = 0; i < num3; i++)
					{
						((Il2CppArrayBase<float>)(object)clipBuildJob.Buf)[i] = clipBuildJob.Samples[num4 + i];
					}
					clipBuildJob.Clip.SetData(clipBuildJob.Buf, clipBuildJob.FrameOffset);
					clipBuildJob.FrameOffset += num2;
					if (clipBuildJob.FrameOffset >= clipBuildJob.TotalFrames)
					{
						_clipBuildQueue.Dequeue();
						(clipBuildJob.Muffled ? _buildingMuffled : _buildingClean).Remove(clipBuildJob.Track);
						clipBuildJob.Samples = null;
						_gcPending = true;
						FinishClipBuild(clipBuildJob);
					}
				}
				catch (Exception ex)
				{
					_clipBuildQueue.Dequeue();
					(clipBuildJob.Muffled ? _buildingMuffled : _buildingClean).Remove(clipBuildJob.Track);
					if (!clipBuildJob.Muffled)
					{
						_failedLoadTracks.Add(clipBuildJob.Track);
					}
					ManualLogSource log2 = Log;
					BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(24, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Error building clip '");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(clipBuildJob.Track);
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("': ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex);
					}
					log2.LogError(val2);
				}
			}
		}

		private static void FinishClipBuild(ClipBuildJob job)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			string track = job.Track;
			if (!job.Muffled)
			{
				_cleanClipCache[track] = job.Clip;
				ManualLogSource log = Log;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(17, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Clip '");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(track);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' is ready.");
				}
				log.LogInfo(val);
				if (_meetingActive && track == _wantedTrack)
				{
					SwitchToTrack(track);
				}
			}
			else
			{
				FinishMuffled(track, job.Clip);
			}
		}

		private static void FinishMuffled(string track, AudioClip clip)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			_muffledClipCache[track] = clip;
			ManualLogSource log = Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(31, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Muffled version of '");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(track);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("' is ready.");
			}
			log.LogInfo(val);
			bool flag2 = IsLocalPlayerGhost();
			bool pendingLocalVoteMuffle = _pendingLocalVoteMuffle;
			if (track == _currentTrackName && !_isMuffled && (flag2 || pendingLocalVoteMuffle) && TryApplyMuffle())
			{
				_pendingLocalVoteMuffle = false;
				Log.LogInfo((object)(flag2 ? "You are a ghost: music muffled as soon as processing finished." : "Pending vote: music muffled as soon as processing finished (vote came in late)."));
			}
		}

		private static bool IsClipPlaying(AudioClip clip)
		{
			if ((Object)(object)clip == (Object)null)
			{
				return false;
			}
			return ((Object)(object)_sourceA != (Object)null && _sourceA.isPlaying && (Object)(object)_sourceA.clip == (Object)(object)clip) || ((Object)(object)_sourceB != (Object)null && _sourceB.isPlaying && (Object)(object)_sourceB.clip == (Object)(object)clip);
		}

		private static void ReleaseUnusedMuffled()
		{
			if (_muffledClipCache.Count == 0)
			{
				return;
			}
			List<string> list = null;
			foreach (KeyValuePair<string, AudioClip> item in _muffledClipCache)
			{
				if ((!_meetingActive || !(item.Key == _currentTrackName)) && !IsClipPlaying(item.Value))
				{
					(list ?? (list = new List<string>())).Add(item.Key);
				}
			}
			if (list == null)
			{
				return;
			}
			foreach (string item2 in list)
			{
				AudioClip val = _muffledClipCache[item2];
				_muffledClipCache.Remove(item2);
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
			}
			_gcPending = true;
		}

		public static void StopVoteMusic()
		{
			if (!((Object)(object)_sourceA == (Object)null) && !((Object)(object)_sourceB == (Object)null))
			{
				_meetingActive = false;
				_wantedTrack = null;
				_pendingLocalVoteMuffle = false;
				_isFirstMeetingOfMatch = false;
				if (ActiveSource.isPlaying)
				{
					_runner.StartFadeOut(ActiveSource, 1f);
				}
				if (InactiveSource.isPlaying)
				{
					_runner.StopAndSilenceImmediate(InactiveSource);
				}
			}
		}

		public static void StopVoteMusicImmediate()
		{
			if (!((Object)(object)_sourceA == (Object)null) && !((Object)(object)_sourceB == (Object)null))
			{
				_meetingActive = false;
				_wantedTrack = null;
				_pendingLocalVoteMuffle = false;
				_runner?.CancelFade();
				_runner?.StopAndSilenceImmediate(_sourceA);
				_runner?.StopAndSilenceImmediate(_sourceB);
				_currentTrackName = null;
				_isMuffled = false;
				_isFirstMeetingOfMatch = true;
				_anyDeathObservedThisMatch = false;
				_matchTotalsCaptured = false;
				_matchTotalImpostors = 0;
				_matchTotalCrewmates = 0;
			}
		}
	}
	public class DanganronpaVotesRunner : MonoBehaviour
	{
		private Coroutine _activeFade;

		public DanganronpaVotesRunner(IntPtr ptr)
			: base(ptr)
		{
		}

		public void Update()
		{
			DanganronpaVotesPlugin.PollPendingAudioLoads();
			DanganronpaVotesPlugin.PollPendingMuffleClips();
		}

		public void StartFadeIn(AudioSource source, float duration, float targetVolume)
		{
			CancelFade();
			_activeFade = ((MonoBehaviour)this).StartCoroutine(CollectionExtensions.WrapToIl2Cpp(FadeInRoutine(source, duration, targetVolume)));
		}

		public void StartFadeOut(AudioSource source, float duration)
		{
			CancelFade();
			_activeFade = ((MonoBehaviour)this).StartCoroutine(CollectionExtensions.WrapToIl2Cpp(FadeOutRoutine(source, duration)));
		}

		public void StartCrossfade(AudioSource outSource, AudioSource inSource, float duration, float targetVolume)
		{
			CancelFade();
			_activeFade = ((MonoBehaviour)this).StartCoroutine(CollectionExtensions.WrapToIl2Cpp(CrossfadeRoutine(outSource, inSource, duration, targetVolume)));
		}

		public void StopAndSilenceImmediate(AudioSource source)
		{
			if (!((Object)(object)source == (Object)null))
			{
				if (source.isPlaying)
				{
					source.Stop();
				}
				source.volume = 0f;
			}
		}

		public void CancelFade()
		{
			if (_activeFade != null)
			{
				((MonoBehaviour)this).StopCoroutine(_activeFade);
				_activeFade = null;
			}
		}

		[HideFromIl2Cpp]
		private IEnumerator FadeInRoutine(AudioSource source, float duration, float targetVolume)
		{
			float elapsed = 0f;
			float startVolume = source.volume;
			while (elapsed < duration)
			{
				elapsed += Time.deltaTime;
				source.volume = Mathf.Lerp(startVolume, DanganronpaVotesPlugin.CurrentTargetVolume, elapsed / duration);
				yield return null;
			}
			source.volume = DanganronpaVotesPlugin.CurrentTargetVolume;
			_activeFade = null;
		}

		[HideFromIl2Cpp]
		private IEnumerator FadeOutRoutine(AudioSource source, float duration)
		{
			float elapsed = 0f;
			float startVolume = source.volume;
			while (elapsed < duration)
			{
				elapsed += Time.deltaTime;
				source.volume = Mathf.Lerp(startVolume, 0f, elapsed / duration);
				yield return null;
			}
			source.volume = 0f;
			source.Stop();
			_activeFade = null;
		}

		[HideFromIl2Cpp]
		private IEnumerator CrossfadeRoutine(AudioSource outSource, AudioSource inSource, float duration, float targetVolume)
		{
			float elapsed = 0f;
			float outStartVolume = outSource.volume;
			float inStartVolume = inSource.volume;
			while (elapsed < duration)
			{
				elapsed += Time.deltaTime;
				float t = elapsed / duration;
				outSource.volume = Mathf.Lerp(outStartVolume, 0f, t);
				inSource.volume = Mathf.Lerp(inStartVolume, DanganronpaVotesPlugin.CurrentTargetVolume, t);
				yield return null;
			}
			outSource.volume = 0f;
			outSource.Stop();
			inSource.volume = DanganronpaVotesPlugin.CurrentTargetVolume;
			_activeFade = null;
		}
	}
	public static class AudioDecoder
	{
		private sealed class SampleBuffer
		{
			private float[] _data;

			public int Count;

			public SampleBuffer(int capacity)
			{
				_data = new float[Math.Max(capacity, 4096)];
			}

			private void EnsureRoom(int extra)
			{
				int num = Count + extra;
				if (num > _data.Length)
				{
					Array.Resize(ref _data, Math.Max(num, _data.Length + _data.Length / 2));
				}
			}

			public void Append(float[] src, int n)
			{
				EnsureRoom(n);
				Array.Copy(src, 0, _data, Count, n);
				Count += n;
			}

			public float[] ToArray()
			{
				if (_data.Length != Count)
				{
					Array.Resize(ref _data, Count);
				}
				return _data;
			}
		}

		public const bool DownmixToMono = false;

		public const bool HalveHighSampleRates = true;

		public static readonly string[] SupportedExtensions = new string[2] { ".ogg", ".wav" };

		public static void ReduceForMemory(ref float[] samples, ref int channels, ref int sampleRate)
		{
			bool flag = false;
			if (sampleRate < 44100 || channels < 1)
			{
				return;
			}
			int num = channels;
			int num2 = samples.Length / num / 2;
			float[] array = new float[num2 * num];
			for (int i = 0; i < num2; i++)
			{
				int num3 = 2 * i * num;
				int num4 = (2 * i + 1) * num;
				for (int j = 0; j < num; j++)
				{
					array[i * num + j] = (samples[num3 + j] + samples[num4 + j]) * 0.5f;
				}
			}
			samples = array;
			sampleRate /= 2;
		}

		public static bool TryDecode(byte[] fileBytes, out float[] samples, out int channels, out int sampleRate, out string format, out string error)
		{
			samples = null;
			channels = 0;
			sampleRate = 0;
			format = "unknown";
			error = null;
			try
			{
				if (fileBytes == null || fileBytes.Length < 12)
				{
					error = "file is empty or too small";
					return false;
				}
				if (StartsWithAscii(fileBytes, "RIFF"))
				{
					format = "wav";
					if (WavUtility.TryParse(fileBytes, out samples, out channels, out sampleRate))
					{
						return true;
					}
					error = "unsupported WAV (use 8, 16 or 32-bit PCM)";
					return false;
				}
				if (StartsWithAscii(fileBytes, "OggS"))
				{
					int limit = Math.Min(fileBytes.Length, 512);
					if (IndexOfAscii(fileBytes, "\u0001vorbis", limit) >= 0)
					{
						format = "vorbis";
						return TryDecodeVorbis(fileBytes, out samples, out channels, out sampleRate, out error);
					}
					error = "Invalid audio file type. Use .ogg (Vorbis) or .wav.";
					return false;
				}
				error = "Invalid audio file type. Use .ogg (Vorbis) or .wav.";
				return false;
			}
			catch (Exception ex)
			{
				samples = null;
				error = ex.GetType().Name + ": " + ex.Message;
				return false;
			}
		}

		private static bool TryDecodeVorbis(byte[] data, out float[] samples, out int channels, out int sampleRate, out string error)
		{
			samples = null;
			error = null;
			using MemoryStream stream = new MemoryStream(data, writable: false);
			using VorbisReader vorbisReader = new VorbisReader(stream, closeOnDispose: false);
			channels = vorbisReader.Channels;
			sampleRate = vorbisReader.SampleRate;
			if (channels <= 0 || sampleRate <= 0)
			{
				error = "invalid Vorbis header";
				return false;
			}
			long totalSamples = vorbisReader.TotalSamples;
			bool flag = totalSamples > 0 && totalSamples <= (long)sampleRate * 3600L;
			int num = (flag ? checked((int)(totalSamples * channels)) : int.MaxValue);
			SampleBuffer sampleBuffer = new SampleBuffer(flag ? num : (sampleRate * channels * 30));
			float[] array = new float[channels * 4096];
			while (sampleBuffer.Count < num)
			{
				int num2 = Math.Min(array.Length, num - sampleBuffer.Count);
				num2 -= num2 % channels;
				if (num2 <= 0)
				{
					break;
				}
				int num3 = vorbisReader.ReadSamples(array, 0, num2);
				if (num3 <= 0)
				{
					break;
				}
				sampleBuffer.Append(array, num3);
			}
			if (sampleBuffer.Count == 0)
			{
				error = "no samples were decoded";
				return false;
			}
			if (flag && num - sampleBuffer.Count > sampleRate / 10 * channels)
			{
				error = $"incomplete or corrupted file (expected {(double)totalSamples / (double)sampleRate:F1}s but only got {(double)sampleBuffer.Count / (double)channels / (double)sampleRate:F1}s)";
				return false;
			}
			samples = sampleBuffer.ToArray();
			return true;
		}

		private static bool StartsWithAscii(byte[] d, string s)
		{
			if (d.Length < s.Length)
			{
				return false;
			}
			for (int i = 0; i < s.Length; i++)
			{
				if (d[i] != (byte)s[i])
				{
					return false;
				}
			}
			return true;
		}

		private static int IndexOfAscii(byte[] d, string s, int limit)
		{
			int num = Math.Min(limit, d.Length) - s.Length;
			for (int i = 0; i <= num; i++)
			{
				int j;
				for (j = 0; j < s.Length && d[i + j] == (byte)s[j]; j++)
				{
				}
				if (j == s.Length)
				{
					return i;
				}
			}
			return -1;
		}
	}
	public static class WavUtility
	{
		public static bool TryParse(byte[] fileBytes, out float[] samples, out int channels, out int sampleRate)
		{
			samples = null;
			channels = 0;
			sampleRate = 0;
			if (fileBytes.Length < 44)
			{
				return false;
			}
			string text = Encoding.ASCII.GetString(fileBytes, 0, 4);
			string text2 = Encoding.ASCII.GetString(fileBytes, 8, 4);
			if (text != "RIFF" || text2 != "WAVE")
			{
				return false;
			}
			int num = 0;
			int num2 = -1;
			int num3 = 0;
			int num4 = 12;
			while (num4 + 8 <= fileBytes.Length)
			{
				string text3 = Encoding.ASCII.GetString(fileBytes, num4, 4);
				int num5 = BitConverter.ToInt32(fileBytes, num4 + 4);
				int num6 = num4 + 8;
				if (text3 == "fmt ")
				{
					channels = BitConverter.ToInt16(fileBytes, num6 + 2);
					sampleRate = BitConverter.ToInt32(fileBytes, num6 + 4);
					num = BitConverter.ToInt16(fileBytes, num6 + 14);
				}
				else if (text3 == "data")
				{
					num2 = num6;
					num3 = ((num5 >= 0 && num6 + num5 <= fileBytes.Length) ? num5 : (fileBytes.Length - num6));
					break;
				}
				if (num5 < 0 || num6 + num5 > fileBytes.Length)
				{
					break;
				}
				num4 = num6 + num5 + num5 % 2;
			}
			if (num2 < 0 || channels <= 0 || sampleRate <= 0 || num <= 0)
			{
				return false;
			}
			int num7 = num / 8;
			if (num7 <= 0 || num2 + num3 > fileBytes.Length)
			{
				return false;
			}
			int num8 = num3 / num7;
			samples = new float[num8];
			switch (num)
			{
			case 16:
			{
				for (int j = 0; j < num8; j++)
				{
					short num10 = BitConverter.ToInt16(fileBytes, num2 + j * 2);
					samples[j] = (float)num10 / 32768f;
				}
				break;
			}
			case 8:
			{
				for (int k = 0; k < num8; k++)
				{
					samples[k] = (float)(fileBytes[num2 + k] - 128) / 128f;
				}
				break;
			}
			case 32:
			{
				for (int i = 0; i < num8; i++)
				{
					int num9 = BitConverter.ToInt32(fileBytes, num2 + i * 4);
					samples[i] = (float)num9 / 2.1474836E+09f;
				}
				break;
			}
			default:
				return false;
			}
			return true;
		}

		public static AudioClip CreateClip(string name, float[] samples, int channels, int sampleRate)
		{
			int num = samples.Length / channels;
			AudioClip val = AudioClip.Create(name, num, channels, sampleRate, false);
			val.SetData(Il2CppStructArray<float>.op_Implicit(samples), 0);
			((Object)val).hideFlags = (HideFlags)32;
			return val;
		}

		public static float[] ApplyLowPassInPlace(float[] samples, int channels, int sampleRate, float cutoffHz)
		{
			float num = 1f / (MathF.PI * 2f * Mathf.Max(cutoffHz, 10f));
			float num2 = 1f / (float)Mathf.Max(sampleRate, 1);
			float num3 = num2 / (num + num2);
			for (int i = 0; i < channels; i++)
			{
				float num4 = 0f;
				for (int j = i; j < samples.Length; j += channels)
				{
					num4 = (samples[j] = num4 + num3 * (samples[j] - num4));
				}
			}
			return samples;
		}

		public static float[] ApplyLowPass(float[] samples, int channels, int sampleRate, float cutoffHz)
		{
			float[] array = new float[samples.Length];
			float num = 1f / (MathF.PI * 2f * Mathf.Max(cutoffHz, 10f));
			float num2 = 1f / (float)Mathf.Max(sampleRate, 1);
			float num3 = num2 / (num + num2);
			for (int i = 0; i < channels; i++)
			{
				float num4 = 0f;
				for (int j = i; j < samples.Length; j += channels)
				{
					num4 = (array[j] = num4 + num3 * (samples[j] - num4));
				}
			}
			return array;
		}
	}
	[HarmonyPatch(typeof(MeetingHud), "Start")]
	public static class MeetingHudStartPatch
	{
		public static void Postfix(MeetingHud __instance)
		{
			DanganronpaVotesPlugin.PlayVoteMusic();
		}
	}
	[HarmonyPatch(typeof(MeetingHud), "Close")]
	public static class MeetingHudClosePatch
	{
		public static void Postfix(MeetingHud __instance)
		{
			DanganronpaVotesPlugin.StopVoteMusic();
		}
	}
	[HarmonyPatch(typeof(MeetingHud), "VotingComplete")]
	public static class MeetingHudVotingCompletePatch
	{
		public static void Postfix()
		{
			DanganronpaVotesPlugin.Log.LogInfo((object)"VotingComplete triggered: results screen started; stopping music.");
			DanganronpaVotesPlugin.StopVoteMusic();
		}
	}
	[HarmonyPatch(typeof(AmongUsClient), "OnPlayerLeft")]
	public static class AmongUsClientOnPlayerLeftPatch
	{
		public static void Postfix()
		{
			DanganronpaVotesPlugin.OnPlayerLeft();
		}
	}
	[HarmonyPatch(typeof(PlayerVoteArea), "VoteForMe")]
	public static class PlayerVoteAreaVoteForMePatch
	{
		public static void Postfix(PlayerVoteArea __instance)
		{
			DanganronpaVotesPlugin.Log.LogInfo((object)"VoteForMe postfix triggered: local vote confirmed.");
			DanganronpaVotesPlugin.OnLocalVoteCast();
		}
	}
}
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;
		}
	}
	internal 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;
			}
		}
	}
	internal static class Extensions
	{
		public static int Read(this IPacket packet, byte[] buffer, int index, int count)
		{
			if (index < 0 || index >= buffer.Length)