Decompiled source of DieForTheMusic v1.0.0

BepInEx/plugins/BiliBiliMOXL-DieForTheMusic/DieForTheMusic.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dissonance;
using HarmonyLib;
using MOXL.DieForTheMusic.CorpseMusic;
using Microsoft.CodeAnalysis;
using NAudio.Wave;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("DieForTheMusic")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("DieForTheMusic")]
[assembly: AssemblyTitle("DieForTheMusic")]
[assembly: AssemblyVersion("1.1.0.0")]
[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 MOXL.DieForTheMusic
{
	[BepInPlugin("MOXL.DieForTheMusic", "DieForTheMusic", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class DieForTheMusicPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "MOXL.DieForTheMusic";

		public const string PluginName = "DieForTheMusic";

		public const string PluginVersion = "1.1.0";

		public const string LethalConfigGuid = "ainavt.lc.lethalconfig";

		public const string ConfigFileName = "DieForTheMusic.cfg";

		internal const string SectionCorpseMusic = "团灭音乐";

		internal const string PlayModePauseOnNewRun = "档位一:新开一局就暂停";

		internal const string PlayModePlayToEnd = "档位二:不论是否新开一局都播完才结束";

		internal static ManualLogSource Log;

		internal static ConfigFile Cfg;

		internal static ConfigEntry<bool> CorpseMusicEnabled;

		internal static ConfigEntry<string> CorpseMusicTrack;

		internal static ConfigEntry<bool> CorpseMusicMuteMic;

		internal static ConfigEntry<bool> CorpseMusicLocalPlay;

		internal static ConfigEntry<float> CorpseMusicLocalVolume;

		internal static ConfigEntry<float> CorpseMusicUplinkVolume;

		internal static ConfigEntry<string> CorpseMusicPlayMode;

		internal static ConfigEntry<string> CorpseMusicLanguage;

		internal static bool MusicEnabled;

		internal static bool LocalPlayEnabled;

		internal static float LocalVolume = 0.7f;

		internal static float UplinkVolume = 0.7f;

		internal static bool PlayToEndMode;

		private Harmony _harmony;

		internal static string PluginDirectory
		{
			get
			{
				try
				{
					string location = typeof(DieForTheMusicPlugin).Assembly.Location;
					if (!string.IsNullOrEmpty(location))
					{
						string directoryName = Path.GetDirectoryName(location);
						if (!string.IsNullOrEmpty(directoryName))
						{
							return directoryName;
						}
					}
				}
				catch (Exception)
				{
				}
				return Paths.PluginPath;
			}
		}

		private void Awake()
		{
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Expected O, but got Unknown
			//IL_0185: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Expected O, but got Unknown
			//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f5: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			ApplyConfigFileName();
			CorpseMusicLanguage = Cfg.Bind<string>("团灭音乐", "界面语言", "auto", "auto = 按 Steam / 系统语言自动匹配;也可填 Lang 文件夹里的语言文件名(不含 .txt),例如 zh-CN、en。");
			Localization.Initialize(PluginDirectory, CorpseMusicLanguage.Value);
			CorpseMusicEnabled = Cfg.Bind<bool>("团灭音乐", "启用团灭音乐", true, Localization.L("cfg.enabled.desc"));
			string[] array = TrackLibrary.Scan();
			string text = ((array.Length != 0) ? array[0] : "(未找到可用曲目)");
			CorpseMusicTrack = Cfg.Bind<string>("团灭音乐", "团灭音乐曲目", text, Localization.L("cfg.track.desc"));
			NormalizeSelectedTrack(array);
			CorpseMusicMuteMic = Cfg.Bind<bool>("团灭音乐", "播放时屏蔽房主麦克风", false, Localization.L("cfg.muteMic.desc"));
			CorpseMusicLocalPlay = Cfg.Bind<bool>("团灭音乐", "房主本地也播放(自己也能听到)", true, Localization.L("cfg.localPlay.desc"));
			CorpseMusicLocalVolume = Cfg.Bind<float>("团灭音乐", "房主本地播放音量", 0.7f, new ConfigDescription(Localization.L("cfg.localVolume.desc"), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			CorpseMusicUplinkVolume = Cfg.Bind<float>("团灭音乐", "其他玩家听到的音量", 0.7f, new ConfigDescription(Localization.L("cfg.uplinkVolume.desc"), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			CorpseMusicPlayMode = Cfg.Bind<string>("团灭音乐", "播放模式", "档位一:新开一局就暂停", Localization.L("cfg.playMode.desc"));
			SyncRuntimeSettings();
			CorpseMusicEnabled.SettingChanged += delegate
			{
				MusicEnabled = CorpseMusicEnabled.Value;
			};
			CorpseMusicMuteMic.SettingChanged += delegate
			{
				VoiceUplinkPump.MuteLocalMic = CorpseMusicMuteMic.Value;
			};
			CorpseMusicLocalPlay.SettingChanged += delegate
			{
				LocalPlayEnabled = CorpseMusicLocalPlay.Value;
			};
			CorpseMusicPlayMode.SettingChanged += delegate
			{
				PlayToEndMode = EvaluatePlayToEnd();
			};
			CorpseMusicLanguage.SettingChanged += delegate
			{
				Log.LogInfo((object)("[Lang] UI language changed to: " + CorpseMusicLanguage.Value + " (restart the game to apply)."));
				Notify(Localization.L("notify.prefix") + Localization.L("notify.languageChanged", CorpseMusicLanguage.Value));
			};
			CorpseMusicLocalVolume.SettingChanged += delegate
			{
				LocalVolume = CorpseMusicLocalVolume.Value;
				LocalMusicPlayer instance = LocalMusicPlayer.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.Volume = LocalVolume;
				}
			};
			CorpseMusicUplinkVolume.SettingChanged += delegate
			{
				UplinkVolume = CorpseMusicUplinkVolume.Value;
				VoiceUplinkPump.Music.Gain = UplinkVolume;
				Log.LogInfo((object)("[CorpseMusic] Uplink volume for other players set to: " + UplinkVolume.ToString("0.00")));
			};
			_harmony = new Harmony("MOXL.DieForTheMusic");
			WipeFlightPatch.Install(_harmony, Log);
			((Component)this).gameObject.AddComponent<CorpseMusicLoader>();
			((Component)this).gameObject.AddComponent<LocalMusicPlayer>();
			((Component)this).gameObject.AddComponent<CorpseMusicController>();
			LethalConfigBridge.Register(array);
			CorpseMusicTrack.SettingChanged += OnTrackChanged;
			((MonoBehaviour)this).StartCoroutine(AttachUplinkPump());
			Log.LogInfo((object)("DieForTheMusic 1.1.0 loaded: wipe music (host only; clients do not need this mod). UI language: " + Localization.LanguageCode + ", language directory: " + Localization.LanguageDirectory));
		}

		private void ApplyConfigFileName()
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			try
			{
				string text = Path.Combine(Paths.ConfigPath, "MOXL.DieForTheMusic.cfg");
				string text2 = Path.Combine(Paths.ConfigPath, "DieForTheMusic.cfg");
				if (!File.Exists(text2) && File.Exists(text) && HasConfigEntries(text))
				{
					File.Copy(text, text2, overwrite: false);
					Log.LogInfo((object)("[Config] Migrated settings from " + text + " to " + text2 + " (old file kept)."));
				}
				Cfg = new ConfigFile(text2, true);
				if (!TryRedirectBaseConfig(Cfg))
				{
					Log.LogWarning((object)("[Config] BaseUnityPlugin.Config was not redirected; the plugin uses " + text2 + " through its own handle."));
				}
				if (File.Exists(text) && !HasConfigEntries(text))
				{
					try
					{
						File.Delete(text);
						Log.LogInfo((object)("[Config] Removed empty legacy config shell: " + text));
					}
					catch (Exception ex)
					{
						Log.LogWarning((object)("[Config] Could not remove empty legacy config shell " + text + ": " + ex.Message));
					}
				}
				Log.LogInfo((object)("[Config] Config file in use: " + Cfg.ConfigFilePath));
			}
			catch (Exception ex2)
			{
				Log.LogError((object)("[Config] Failed to switch config file name to DieForTheMusic.cfg: " + ex2));
				if (Cfg == null)
				{
					Cfg = ((BaseUnityPlugin)this).Config;
				}
			}
		}

		private bool TryRedirectBaseConfig(ConfigFile configFile)
		{
			try
			{
				Type typeFromHandle = typeof(BaseUnityPlugin);
				PropertyInfo property = typeFromHandle.GetProperty("Config", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				MethodInfo methodInfo = ((property == null) ? null : property.GetSetMethod(nonPublic: true));
				if (methodInfo != null)
				{
					methodInfo.Invoke(this, new object[1] { configFile });
					if (((BaseUnityPlugin)this).Config == configFile)
					{
						return true;
					}
				}
				FieldInfo field = typeFromHandle.GetField("<Config>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
				if (field != null)
				{
					field.SetValue(this, configFile);
					if (((BaseUnityPlugin)this).Config == configFile)
					{
						return true;
					}
				}
				return false;
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[Config] Reflecting BaseUnityPlugin.Config failed: " + ex.Message));
				return false;
			}
		}

		private static bool HasConfigEntries(string path)
		{
			try
			{
				string[] array = File.ReadAllLines(path);
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					if (text.Length != 0 && text[0] != '#' && text[0] != ';')
					{
						return true;
					}
				}
			}
			catch (Exception)
			{
			}
			return false;
		}

		private static void SyncRuntimeSettings()
		{
			MusicEnabled = CorpseMusicEnabled.Value;
			LocalPlayEnabled = CorpseMusicLocalPlay.Value;
			LocalVolume = CorpseMusicLocalVolume.Value;
			UplinkVolume = CorpseMusicUplinkVolume.Value;
			PlayToEndMode = EvaluatePlayToEnd();
			VoiceUplinkPump.MuteLocalMic = CorpseMusicMuteMic.Value;
			VoiceUplinkPump.Music.Gain = UplinkVolume;
		}

		private static bool EvaluatePlayToEnd()
		{
			if (CorpseMusicPlayMode != null)
			{
				return string.Equals(CorpseMusicPlayMode.Value, "档位二:不论是否新开一局都播完才结束", StringComparison.Ordinal);
			}
			return false;
		}

		private void NormalizeSelectedTrack(string[] tracks)
		{
			string value = CorpseMusicTrack.Value;
			if (!string.IsNullOrEmpty(value) && !string.Equals(value, "(未找到可用曲目)", StringComparison.Ordinal) && TrackLibrary.Resolve(value) == null)
			{
				string text = ((tracks != null && tracks.Length != 0) ? tracks[0] : "(未找到可用曲目)");
				Log.LogWarning((object)("[CorpseMusic] Configured track is no longer valid: " + value + ", falling back to: " + text));
				CorpseMusicTrack.Value = text;
			}
		}

		internal static string ResolveSelectedTrack()
		{
			if (CorpseMusicTrack != null)
			{
				return TrackLibrary.Resolve(CorpseMusicTrack.Value);
			}
			return null;
		}

		internal static void Notify(string message)
		{
			try
			{
				HUDManager instance = HUDManager.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.AddTextToChatOnServer(message, -1);
				}
			}
			catch (Exception)
			{
			}
		}

		private void OnTrackChanged(object sender, EventArgs e)
		{
			try
			{
				CorpseMusicController instance = CorpseMusicController.Instance;
				if ((Object)(object)instance != (Object)null && instance.IsSessionActive)
				{
					instance.StopSession("track switched in the config UI");
				}
				CorpseMusicLoader instance2 = CorpseMusicLoader.Instance;
				if ((Object)(object)instance2 != (Object)null)
				{
					instance2.Invalidate(null);
				}
				Log.LogInfo((object)("[CorpseMusic] Track switched to: " + CorpseMusicTrack.Value));
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("[CorpseMusic] Failed to handle track switch: " + ex.Message));
			}
		}

		private IEnumerator AttachUplinkPump()
		{
			for (int attempt = 0; attempt < 30; attempt++)
			{
				if (VoiceUplinkPump.TryAttach(_harmony, Log))
				{
					yield break;
				}
				yield return (object)new WaitForSecondsRealtime(2f);
			}
			Log.LogError((object)"[CorpseMusic] Dissonance uplink injection patch not attached within 60s; wipe music cannot be broadcast through the microphone.");
		}

		private void OnDestroy()
		{
			CorpseMusicController instance = CorpseMusicController.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				instance.Shutdown();
			}
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
		}
	}
	internal static class LethalConfigBridge
	{
		private static Assembly _lethalConfig;

		private static MethodInfo _addConfigItem;

		private static Type _boolItemType;

		private static Type _boolOptionsType;

		private static Type _sliderItemType;

		private static Type _sliderOptionsType;

		private static Type _dropDownItemType;

		private static Type _dropDownOptionsType;

		private static Type _buttonItemType;

		private static Type _buttonHandlerType;

		private static readonly Dictionary<string, PropertyInfo> OptionProperties = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);

		private static readonly Dictionary<string, FieldInfo> OptionFields = new Dictionary<string, FieldInfo>(StringComparer.Ordinal);

		private static bool _resolved;

		private static string SectionTitle => Localization.L("section.corpseMusic");

		internal static void Register(string[] tracks)
		{
			try
			{
				if (Resolve())
				{
					Assembly executingAssembly = Assembly.GetExecutingAssembly();
					int num = 0;
					if (AddBool(executingAssembly, DieForTheMusicPlugin.CorpseMusicEnabled, Localization.L("cfg.enabled.name"), Localization.L("cfg.enabled.desc")))
					{
						num++;
					}
					if (AddDropDown(executingAssembly, DieForTheMusicPlugin.CorpseMusicTrack, Localization.L("cfg.track.name"), Localization.L("cfg.track.desc"), tracks))
					{
						num++;
					}
					if (AddButton(executingAssembly, Localization.L("btn.pause.name"), Localization.L("btn.pause.desc"), Localization.L("btn.pause.label"), "OnPauseButton"))
					{
						num++;
					}
					if (AddButton(executingAssembly, Localization.L("btn.test.name"), Localization.L("btn.test.desc"), Localization.L("btn.test.label"), "OnPlayTestButton"))
					{
						num++;
					}
					if (AddButton(executingAssembly, Localization.L("btn.clear.name"), Localization.L("btn.clear.desc"), Localization.L("btn.clear.label"), "OnClearProgressButton"))
					{
						num++;
					}
					if (AddBool(executingAssembly, DieForTheMusicPlugin.CorpseMusicMuteMic, Localization.L("cfg.muteMic.name"), Localization.L("cfg.muteMic.desc")))
					{
						num++;
					}
					if (AddBool(executingAssembly, DieForTheMusicPlugin.CorpseMusicLocalPlay, Localization.L("cfg.localPlay.name"), Localization.L("cfg.localPlay.desc")))
					{
						num++;
					}
					if (AddFloatSlider(executingAssembly, DieForTheMusicPlugin.CorpseMusicLocalVolume, Localization.L("cfg.localVolume.name"), Localization.L("cfg.localVolume.desc"), 0f, 1f))
					{
						num++;
					}
					if (AddFloatSlider(executingAssembly, DieForTheMusicPlugin.CorpseMusicUplinkVolume, Localization.L("cfg.uplinkVolume.name"), Localization.L("cfg.uplinkVolume.desc"), 0f, 1f))
					{
						num++;
					}
					if (AddDropDown(executingAssembly, DieForTheMusicPlugin.CorpseMusicPlayMode, Localization.L("cfg.playMode.name"), Localization.L("cfg.playMode.desc"), new string[2] { "档位一:新开一局就暂停", "档位二:不论是否新开一局都播完才结束" }))
					{
						num++;
					}
					if (AddDropDown(executingAssembly, DieForTheMusicPlugin.CorpseMusicLanguage, Localization.L("cfg.language.name"), Localization.L("cfg.language.desc"), Localization.ListAvailableLanguages(), requiresRestart: true))
					{
						num++;
					}
					DieForTheMusicPlugin.Log.LogInfo((object)("[ConfigMenu] Registered " + num + " UI items with LethalConfig."));
				}
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[ConfigMenu] LethalConfig registration failed (functionality unaffected): " + ex));
			}
		}

		private static bool Resolve()
		{
			if (_resolved)
			{
				return _addConfigItem != null;
			}
			_resolved = true;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				if (!(assembly == null) && !(assembly.GetName().Name != "LethalConfig"))
				{
					_lethalConfig = assembly;
					break;
				}
			}
			if (_lethalConfig == null)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)"[ConfigMenu] LethalConfig not detected; skipping menu registration (config file still works).");
				return false;
			}
			Type type = _lethalConfig.GetType("LethalConfig.LethalConfigManager");
			if (type != null)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.Name == "AddConfigItem" && methodInfo.GetParameters().Length == 2)
					{
						_addConfigItem = methodInfo;
						break;
					}
				}
			}
			if (_addConfigItem == null)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)"[ConfigMenu] LethalConfigManager.AddConfigItem(BaseConfigItem, Assembly) not found.");
				return false;
			}
			_boolItemType = _lethalConfig.GetType("LethalConfig.ConfigItems.BoolCheckBoxConfigItem");
			_boolOptionsType = _lethalConfig.GetType("LethalConfig.ConfigItems.Options.BoolCheckBoxOptions") ?? _lethalConfig.GetType("LethalConfig.ConfigItems.Options.CheckBoxOptions");
			_sliderItemType = _lethalConfig.GetType("LethalConfig.ConfigItems.FloatSliderConfigItem");
			_sliderOptionsType = _lethalConfig.GetType("LethalConfig.ConfigItems.Options.FloatSliderOptions");
			_dropDownItemType = _lethalConfig.GetType("LethalConfig.ConfigItems.TextDropDownConfigItem");
			_dropDownOptionsType = _lethalConfig.GetType("LethalConfig.ConfigItems.Options.TextDropDownOptions");
			_buttonItemType = _lethalConfig.GetType("LethalConfig.ConfigItems.GenericButtonConfigItem");
			Type type2 = _lethalConfig.GetType("LethalConfig.ConfigItems.Options.GenericButtonOptions");
			_buttonHandlerType = ((type2 == null) ? null : type2.GetNestedType("GenericButtonHandler", BindingFlags.Public | BindingFlags.NonPublic));
			return true;
		}

		private static bool AddBool(Assembly self, ConfigEntry<bool> entry, string name, string description)
		{
			if (entry == null || _boolItemType == null || _boolOptionsType == null)
			{
				WarnMissing("BoolCheckBoxConfigItem / BoolCheckBoxOptions");
				return false;
			}
			object obj = Activator.CreateInstance(_boolOptionsType);
			ApplyOptions(obj, name, description);
			return AddItem(_boolItemType, new object[2] { entry, obj }, self);
		}

		private static bool AddFloatSlider(Assembly self, ConfigEntry<float> entry, string name, string description, float min, float max)
		{
			if (entry == null || _sliderItemType == null || _sliderOptionsType == null)
			{
				WarnMissing("FloatSliderConfigItem / FloatSliderOptions");
				return false;
			}
			object obj = Activator.CreateInstance(_sliderOptionsType);
			ApplyOptions(obj, name, description);
			SetMember(obj, "Min", min);
			SetMember(obj, "Max", max);
			return AddItem(_sliderItemType, new object[2] { entry, obj }, self);
		}

		private static bool AddDropDown(Assembly self, ConfigEntry<string> entry, string name, string description, string[] values, bool requiresRestart = false)
		{
			if (entry == null || _dropDownItemType == null || _dropDownOptionsType == null)
			{
				WarnMissing("TextDropDownConfigItem / TextDropDownOptions");
				return false;
			}
			if (values == null || values.Length == 0)
			{
				values = new string[1] { "(未找到可用曲目)" };
			}
			object obj = Activator.CreateInstance(_dropDownOptionsType, new object[1] { values });
			ApplyOptions(obj, name, description, requiresRestart);
			return AddItem(_dropDownItemType, new object[2] { entry, obj }, self);
		}

		private static bool AddButton(Assembly self, string name, string description, string buttonText, string handlerName)
		{
			if (_buttonItemType == null || _buttonHandlerType == null)
			{
				WarnMissing("GenericButtonConfigItem / GenericButtonHandler");
				return false;
			}
			MethodInfo method = typeof(LethalConfigBridge).GetMethod(handlerName, BindingFlags.Static | BindingFlags.NonPublic);
			if (method == null)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[ConfigMenu] Button callback not found: " + handlerName));
				return false;
			}
			Delegate obj = Delegate.CreateDelegate(_buttonHandlerType, method);
			object obj2 = Activator.CreateInstance(_buttonItemType, SectionTitle, name, description, buttonText, obj);
			return AddItem(_buttonItemType, new object[1] { obj2 }, self, obj2);
		}

		private static bool AddItem(Type itemType, object[] arguments, Assembly self, object presets = null)
		{
			try
			{
				object obj = presets ?? Activator.CreateInstance(itemType, arguments);
				_addConfigItem.Invoke(null, new object[2] { obj, self });
				return true;
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[ConfigMenu] Failed to register item (" + itemType.Name + "): " + ex.Message));
				return false;
			}
		}

		private static void WarnMissing(string what)
		{
			DieForTheMusicPlugin.Log.LogWarning((object)("[ConfigMenu] Missing " + what + "; skipping this item."));
		}

		private static void ApplyOptions(object options, string name, string description, bool requiresRestart = false)
		{
			SetMember(options, "Name", name);
			SetMember(options, "Description", description);
			SetMember(options, "Section", SectionTitle);
			SetMember(options, "RequiresRestart", requiresRestart);
		}

		private static void SetMember(object target, string member, object value)
		{
			if (target == null)
			{
				return;
			}
			Type type = target.GetType();
			string key = type.FullName + "|" + member;
			if (OptionProperties.TryGetValue(key, out var value2))
			{
				if (value2 != null)
				{
					value2.SetValue(target, value, null);
				}
				return;
			}
			if (OptionFields.TryGetValue(key, out var value3))
			{
				if (value3 != null)
				{
					value3.SetValue(target, value);
				}
				return;
			}
			value2 = type.GetProperty(member, BindingFlags.Instance | BindingFlags.Public);
			if (value2 != null && value2.CanWrite)
			{
				OptionProperties[key] = value2;
				value2.SetValue(target, value, null);
				return;
			}
			OptionProperties[key] = null;
			value3 = type.GetField(member, BindingFlags.Instance | BindingFlags.Public);
			OptionFields[key] = value3;
			if (value3 != null)
			{
				value3.SetValue(target, value);
			}
		}

		private static void OnPauseButton()
		{
			try
			{
				CorpseMusicController instance = CorpseMusicController.Instance;
				string text = (((Object)(object)instance != (Object)null) ? instance.TogglePause() : Localization.L("notify.noSession"));
				DieForTheMusicPlugin.Notify(Localization.L("notify.prefix") + text);
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[ConfigMenu] Pause button error: " + ex.Message));
			}
		}

		private static void OnPlayTestButton()
		{
			try
			{
				CorpseMusicController instance = CorpseMusicController.Instance;
				if ((Object)(object)instance == (Object)null)
				{
					DieForTheMusicPlugin.Notify(Localization.L("notify.prefix") + Localization.L("notify.controllerNotReady"));
				}
				else
				{
					DieForTheMusicPlugin.Notify(instance.BeginSession("test play from the config UI", manual: true) ? (Localization.L("notify.prefix") + Localization.L("notify.testStarted")) : (Localization.L("notify.prefix") + Localization.L("notify.testFailed")));
				}
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[ConfigMenu] Test-play button error: " + ex.Message));
			}
		}

		private static void OnClearProgressButton()
		{
			try
			{
				CorpseMusicController instance = CorpseMusicController.Instance;
				string text = (((Object)(object)instance != (Object)null) ? instance.ClearProgress() : Localization.L("notify.controllerNotReadyClear"));
				DieForTheMusicPlugin.Notify(Localization.L("notify.prefix") + text);
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[ConfigMenu] Reset progress button error: " + ex.Message));
			}
		}
	}
	internal static class Localization
	{
		internal const string AutoCode = "auto";

		internal const string FallbackCode = "zh-CN";

		internal const string LangFolderName = "Lang";

		private const string FileExtension = ".txt";

		private static readonly Dictionary<string, string> Texts = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, string> BuiltinChinese = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
		{
			{ "section.corpseMusic", "团灭音乐" },
			{ "cfg.enabled.name", "启用团灭音乐" },
			{ "cfg.enabled.desc", "开启后,一旦检测到全员死亡,房主就会通过自己的麦克风为所有人播放下面选定的曲目。" },
			{ "cfg.track.name", "团灭音乐曲目" },
			{ "cfg.track.desc", "选择团灭时播放的歌曲。[模组音乐] 来自 BepInEx 下名字含 DieForTheMusic 的文件夹(含一层子文件夹),[本模组] 来自插件目录 Music 文件夹。新增歌曲后需重启游戏。" },
			{ "cfg.language.name", "界面语言" },
			{ "cfg.language.desc", "auto = 按 Steam / 系统语言自动匹配中文或英文;也可以直接填 Lang 文件夹里的语言文件名(不含 .txt),例如 zh-CN、en。文本内容由你自己准备,缺文件时使用模组内置的中文文案。修改后需重启游戏。" },
			{ "cfg.muteMic.name", "播放时屏蔽房主麦克风" },
			{ "cfg.muteMic.desc", "关闭:音乐与房主说话声一起传出;开启:播放团灭音乐期间只传出音乐,屏蔽房主真实麦克风。" },
			{ "cfg.localPlay.name", "房主本地也播放(自己也能听到)" },
			{ "cfg.localPlay.desc", "开启后,播放团灭音乐时房主自己的音响/耳机里也会出声(与其他玩家听到的是同一首)。关闭则只有其他玩家能听到。" },
			{ "cfg.localVolume.name", "房主本地播放音量" },
			{ "cfg.localVolume.desc", "房主本机听到的团灭音乐音量(0 = 静音,1 = 原始音量),不影响传给其他玩家的音量。" },
			{ "cfg.uplinkVolume.name", "其他玩家听到的音量" },
			{ "cfg.uplinkVolume.desc", "其他玩家(客户端)听到的团灭音乐音量(0 = 静音,1 = 原始音量)。只影响其他玩家,不影响房主本机音量。" },
			{ "cfg.playMode.name", "播放模式" },
			{ "cfg.playMode.desc", "档位一:新开一局就暂停——玩家复活或进入新一局时立即停止本次团灭音乐。档位二:不论是否新开一局都播完才结束——即使已经进入新一局,也会把整首播完再停止。" },
			{ "btn.pause.name", "暂停或继续本次团灭音乐" },
			{ "btn.pause.desc", "点击一次暂停本次团灭音乐,再点一次继续播放。仅在团灭音乐播放期间有效。" },
			{ "btn.pause.label", "暂停 / 继续" },
			{ "btn.test.name", "试播团灭音乐" },
			{ "btn.test.desc", "不需要等到团灭,立即用当前选定曲目试播一次,方便验证其他人能否听到。" },
			{ "btn.test.label", "立即试播" },
			{ "btn.clear.name", "清空播放进度" },
			{ "btn.clear.desc", "暂停本次团灭音乐并把播放进度清零。清空后本局不会再自动播放,等到下一次全员死亡团灭时才从头播放。" },
			{ "btn.clear.label", "清空进度" },
			{ "notify.prefix", "【团灭音乐】" },
			{ "notify.wipe", "检测到团灭!开始播放【{0}】" },
			{ "notify.unknownTrack", "未知曲目" },
			{ "notify.noSession", "当前没有正在播放的团灭音乐,无需暂停。" },
			{ "notify.paused", "已暂停本次团灭音乐,再点一次可继续播放。" },
			{ "notify.resumed", "已继续播放本次团灭音乐,再点一次可暂停。" },
			{ "notify.clearedPaused", "已暂停并清空本次团灭音乐的播放进度,下一次团灭会从头播放。" },
			{ "notify.cleared", "播放进度已清空,下一次团灭会从头播放。" },
			{ "notify.controllerNotReady", "控制器未就绪,请稍后再试。" },
			{ "notify.controllerNotReadyClear", "控制器未就绪,播放进度未清空。" },
			{ "notify.testStarted", "开始试播当前曲目,其他玩家应能通过房主麦克风听到。" },
			{ "notify.testFailed", "试播失败:曲目未就绪或未找到可用曲目。" },
			{ "notify.languageChanged", "界面语言已改为 {0},重启游戏后生效。" }
		};

		private static string _langDirectory;

		private static bool _initialized;

		internal static string LanguageCode { get; private set; }

		internal static string LanguageDirectory => _langDirectory;

		internal static void Initialize(string pluginDirectory, string preferred)
		{
			if (_initialized)
			{
				return;
			}
			_initialized = true;
			_langDirectory = Path.Combine(pluginDirectory ?? string.Empty, "Lang");
			foreach (KeyValuePair<string, string> item in BuiltinChinese)
			{
				Texts[item.Key] = item.Value;
			}
			LanguageCode = ResolveLanguageCode(preferred);
			MergeFile("zh-CN");
			if (!string.Equals(LanguageCode, "zh-CN", StringComparison.OrdinalIgnoreCase))
			{
				MergeFile(LanguageCode);
			}
		}

		internal static string L(string key, params object[] args)
		{
			string value = key;
			if (!string.IsNullOrEmpty(key) && (!Texts.TryGetValue(key, out value) || value == null))
			{
				value = key;
			}
			if (args == null || args.Length == 0 || value.Length == 0)
			{
				return value ?? string.Empty;
			}
			try
			{
				return string.Format(value, args);
			}
			catch (FormatException)
			{
				return value;
			}
		}

		internal static string[] ListAvailableLanguages()
		{
			List<string> list = new List<string> { "auto" };
			try
			{
				if (!string.IsNullOrEmpty(_langDirectory) && Directory.Exists(_langDirectory))
				{
					string[] files = Directory.GetFiles(_langDirectory, "*.txt");
					for (int i = 0; i < files.Length; i++)
					{
						string code = Path.GetFileNameWithoutExtension(files[i]);
						if (!string.IsNullOrEmpty(code) && !code.Equals("auto", StringComparison.OrdinalIgnoreCase) && !list.Exists((string a) => string.Equals(a, code, StringComparison.OrdinalIgnoreCase)))
						{
							list.Add(code);
						}
					}
				}
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[Lang] Failed to enumerate language files: " + ex.Message));
			}
			if (!string.IsNullOrEmpty(LanguageCode) && !list.Exists((string a) => string.Equals(a, LanguageCode, StringComparison.OrdinalIgnoreCase)))
			{
				list.Add(LanguageCode);
			}
			for (int num = 0; num < list.Count; num++)
			{
				if (string.Equals(list[num], LanguageCode, StringComparison.OrdinalIgnoreCase))
				{
					if (num != 0)
					{
						string item = list[num];
						list.RemoveAt(num);
						list.Insert(1, item);
					}
					break;
				}
			}
			return list.ToArray();
		}

		private static string ResolveLanguageCode(string preferred)
		{
			string text = NormalizeCode(preferred);
			if (!string.IsNullOrEmpty(text) && !string.Equals(text, "auto", StringComparison.OrdinalIgnoreCase))
			{
				return text;
			}
			string text2 = NormalizeCode(TryGetSteamGameLanguage());
			if (!string.IsNullOrEmpty(text2))
			{
				return text2;
			}
			string text3 = NormalizeCode(TryGetSystemLanguage());
			if (!string.IsNullOrEmpty(text3))
			{
				return text3;
			}
			return "zh-CN";
		}

		private static string TryGetSteamGameLanguage()
		{
			try
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly in assemblies)
				{
					if (assembly == null || assembly.GetName().Name.IndexOf("steamworks", StringComparison.OrdinalIgnoreCase) < 0)
					{
						continue;
					}
					Type type = assembly.GetType("Steamworks.SteamApps", throwOnError: false);
					if (!(type == null))
					{
						PropertyInfo property = type.GetProperty("GameLanguage", BindingFlags.Static | BindingFlags.Public);
						if (property == null)
						{
							return null;
						}
						string text = property.GetValue(null, null) as string;
						return string.IsNullOrEmpty(text) ? null : text;
					}
				}
			}
			catch (Exception)
			{
			}
			return null;
		}

		private static string TryGetSystemLanguage()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return ((object)Application.systemLanguage/*cast due to .constrained prefix*/).ToString();
			}
			catch (Exception)
			{
				return null;
			}
		}

		private static string NormalizeCode(string raw)
		{
			if (string.IsNullOrEmpty(raw))
			{
				return null;
			}
			string text = raw.Trim();
			if (text.Length == 0)
			{
				return null;
			}
			string text2 = text.ToLowerInvariant();
			switch (text2)
			{
			case "auto":
				return "auto";
			case "english":
			case "en":
			case "en-us":
			case "en_us":
			case "en-gb":
			case "en_gb":
				return "en";
			case "zh-hans":
			case "chinese":
			case "zh":
			case "zh-cn":
			case "schinese":
			case "chinesesimplified":
				return "zh-CN";
			case "zh-hant":
			case "zh-tw":
			case "zh-hk":
			case "tchinese":
			case "chinesetraditional":
				return "zh-TW";
			case "japanese":
				return "ja";
			case "koreana":
			case "korean":
				return "ko";
			case "russian":
				return "ru";
			case "french":
				return "fr";
			case "german":
				return "de";
			case "spanish":
				return "es";
			case "latam":
				return "es-419";
			case "portuguese":
				return "pt-BR";
			case "brazilian":
				return "pt-BR";
			case "italian":
				return "it";
			case "polish":
				return "pl";
			case "turkish":
				return "tr";
			case "ukrainian":
				return "uk";
			case "czech":
				return "cs";
			case "dutch":
				return "nl";
			case "finnish":
				return "fi";
			case "danish":
				return "da";
			case "swedish":
				return "sv";
			case "norwegian":
				return "no";
			case "hungarian":
				return "hu";
			case "romanian":
				return "ro";
			case "thai":
				return "th";
			case "vietnamese":
				return "vi";
			case "indonesian":
				return "id";
			default:
				if (text2.StartsWith("zh", StringComparison.Ordinal))
				{
					return "zh-CN";
				}
				try
				{
					return CultureInfo.GetCultureInfo(text).Name.ToLowerInvariant();
				}
				catch (Exception)
				{
					return text2;
				}
			}
		}

		private static void MergeFile(string code)
		{
			string text = ResolveFile(code);
			if (text != null && TryReadFile(text, out var applied))
			{
				DieForTheMusicPlugin.Log.LogInfo((object)("[Lang] Loaded text: " + text + " (" + applied + " entries)."));
			}
		}

		private static string ResolveFile(string code)
		{
			if (string.IsNullOrEmpty(code) || string.IsNullOrEmpty(_langDirectory))
			{
				return null;
			}
			try
			{
				if (!Directory.Exists(_langDirectory))
				{
					return null;
				}
				string text = Path.Combine(_langDirectory, code + ".txt");
				if (File.Exists(text))
				{
					return text;
				}
				string[] files = Directory.GetFiles(_langDirectory, "*.txt");
				for (int i = 0; i < files.Length; i++)
				{
					if (string.Equals(Path.GetFileNameWithoutExtension(files[i]), code, StringComparison.OrdinalIgnoreCase))
					{
						return files[i];
					}
				}
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[Lang] Failed to locate language file (" + code + "): " + ex.Message));
			}
			return null;
		}

		private static bool TryReadFile(string path, out int applied)
		{
			applied = 0;
			try
			{
				string[] array = File.ReadAllLines(path);
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i];
					if (text == null)
					{
						continue;
					}
					text = text.Trim().TrimStart(new char[1] { '\ufeff' });
					if (text.Length == 0 || text[0] == '#' || text[0] == ';')
					{
						continue;
					}
					int num = text.IndexOf('=');
					if (num > 0)
					{
						string text2 = text.Substring(0, num).Trim();
						if (text2.Length != 0)
						{
							string text3 = text.Substring(num + 1).Trim();
							Texts[text2] = text3.Replace("\\n", "\n");
							applied++;
						}
					}
				}
				return true;
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[Lang] Failed to read language file: " + path + " → " + ex.Message));
				return false;
			}
		}
	}
}
namespace MOXL.DieForTheMusic.CorpseMusic
{
	internal sealed class CorpseMusicController : MonoBehaviour
	{
		private const float PollInterval = 0.25f;

		private const float PrewarmInterval = 1f;

		private const float ChannelGuardInterval = 0.5f;

		private static CorpseMusicController _instance;

		private float _nextPoll;

		private float _nextChannelGuard;

		private float _nextPrewarm;

		private bool _sessionActive;

		private bool _manualSession;

		private bool _triggeredForThisLeave;

		private float _sessionStartAt;

		private bool _warnedNoInjection;

		private string _pendingTrackPath;

		internal static CorpseMusicController Instance => _instance;

		internal bool IsSessionActive => _sessionActive;

		private void Awake()
		{
			_instance = this;
		}

		private void Update()
		{
			try
			{
				Tick();
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogError((object)("[CorpseMusic] Scheduler exception: " + ex));
			}
		}

		private void Tick()
		{
			float unscaledTime = Time.unscaledTime;
			if (_sessionActive)
			{
				MaintainSession(unscaledTime);
			}
			else
			{
				Prewarm(unscaledTime);
			}
			if (!(unscaledTime < _nextPoll))
			{
				_nextPoll = unscaledTime + 0.25f;
				PollWipe();
			}
		}

		private void Prewarm(float now)
		{
			if (now < _nextPrewarm || !DieForTheMusicPlugin.MusicEnabled)
			{
				return;
			}
			_nextPrewarm = now + 1f;
			CorpseMusicLoader instance = CorpseMusicLoader.Instance;
			if ((Object)(object)instance == (Object)null || instance.IsLoading)
			{
				return;
			}
			string text = DieForTheMusicPlugin.ResolveSelectedTrack();
			if (string.IsNullOrEmpty(text))
			{
				return;
			}
			if (_pendingTrackPath != null && !string.Equals(_pendingTrackPath, text, StringComparison.OrdinalIgnoreCase))
			{
				instance.Invalidate(_pendingTrackPath);
			}
			_pendingTrackPath = text;
			DecodedTrack orRequest = instance.GetOrRequest(text);
			if (orRequest != null && DieForTheMusicPlugin.LocalPlayEnabled)
			{
				LocalMusicPlayer instance2 = LocalMusicPlayer.Instance;
				if ((Object)(object)instance2 != (Object)null)
				{
					instance2.Prepare(orRequest);
				}
			}
		}

		private void PollWipe()
		{
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				if (!instance.allPlayersDead)
				{
					_triggeredForThisLeave = false;
				}
				else if (!_triggeredForThisLeave && !_sessionActive && DieForTheMusicPlugin.MusicEnabled && ((NetworkBehaviour)instance).IsServer)
				{
					_triggeredForThisLeave = BeginSession("all-dead wipe detected", manual: false);
				}
			}
		}

		internal bool BeginSession(string reason, bool manual)
		{
			if (_sessionActive)
			{
				DieForTheMusicPlugin.Log.LogInfo((object)("[CorpseMusic] Already playing; ignoring duplicate trigger: " + reason));
				return true;
			}
			string text = DieForTheMusicPlugin.ResolveSelectedTrack();
			if (string.IsNullOrEmpty(text))
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] No usable track found. Put audio files into " + TrackLibrary.MusicRoot + " or any folder under BepInEx whose name contains DieForTheMusic, then restart the game."));
				return false;
			}
			CorpseMusicLoader instance = CorpseMusicLoader.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			DecodedTrack orRequest = instance.GetOrRequest(text);
			if (orRequest == null)
			{
				DieForTheMusicPlugin.Log.LogInfo((object)("[CorpseMusic] Track still decoding; skipping this playback: " + reason));
				return false;
			}
			VoiceUplinkPump.Music.Play(orRequest.Samples, orRequest.Rate);
			if (DieForTheMusicPlugin.LocalPlayEnabled)
			{
				LocalMusicPlayer instance2 = LocalMusicPlayer.Instance;
				if ((Object)(object)instance2 != (Object)null)
				{
					float volume = (instance2.Volume = DieForTheMusicPlugin.LocalVolume);
					instance2.Play(orRequest, volume);
				}
				else
				{
					DieForTheMusicPlugin.Log.LogWarning((object)"[CorpseMusic] Local player not ready; the host will not hear the music locally.");
				}
			}
			else
			{
				DieForTheMusicPlugin.Log.LogInfo((object)"[CorpseMusic] Host local playback disabled by config; only other players will hear it.");
			}
			_sessionActive = true;
			_manualSession = manual;
			_sessionStartAt = Time.unscaledTime;
			_warnedNoInjection = false;
			_nextChannelGuard = 0f;
			DieForTheMusicPlugin.Log.LogInfo((object)$"[CorpseMusic] Playback started ({reason}): {Path.GetFileName(text)}, duration {orRequest.Duration:0.0}s");
			DieForTheMusicPlugin.Notify(Localization.L("notify.wipe", TrackDisplayName(text)));
			VoiceUplinkPump.EnsureChannelOpen(DieForTheMusicPlugin.Log);
			return true;
		}

		private static string TrackDisplayName(string path)
		{
			try
			{
				string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path);
				return string.IsNullOrEmpty(fileNameWithoutExtension) ? Localization.L("notify.unknownTrack") : fileNameWithoutExtension;
			}
			catch (Exception)
			{
				return Localization.L("notify.unknownTrack");
			}
		}

		private static void StopPlayback()
		{
			VoiceUplinkPump.Music.Stop();
			LocalMusicPlayer instance = LocalMusicPlayer.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				instance.Stop();
			}
			VoiceUplinkPump.RestoreChannel(DieForTheMusicPlugin.Log);
		}

		internal void StopSession(string reason)
		{
			if (_sessionActive)
			{
				StopPlayback();
				_sessionActive = false;
				_manualSession = false;
				DieForTheMusicPlugin.Log.LogInfo((object)("[CorpseMusic] Playback stopped: " + reason));
			}
		}

		internal string ClearProgress()
		{
			StopPlayback();
			bool sessionActive = _sessionActive;
			_sessionActive = false;
			_manualSession = false;
			_triggeredForThisLeave = true;
			DieForTheMusicPlugin.Log.LogInfo((object)"[CorpseMusic] Playback progress cleared; waiting for the next wipe.");
			if (!sessionActive)
			{
				return Localization.L("notify.cleared");
			}
			return Localization.L("notify.clearedPaused");
		}

		private void MaintainSession(float now)
		{
			if (!VoiceUplinkPump.Music.IsPlaying)
			{
				StopSession("track finished");
				return;
			}
			if (!_manualSession && !DieForTheMusicPlugin.PlayToEndMode)
			{
				StartOfRound instance = StartOfRound.Instance;
				if ((Object)(object)instance != (Object)null && !instance.allPlayersDead)
				{
					StopSession("player revived or a new round started (play mode 1)");
					return;
				}
			}
			if (now < _nextChannelGuard)
			{
				return;
			}
			_nextChannelGuard = now + 0.5f;
			if (!VoiceUplinkPump.Patched)
			{
				StopSession("voice uplink patch not ready");
				return;
			}
			if (!VoiceUplinkPump.EnsureChannelOpen(DieForTheMusicPlugin.Log) && now - _sessionStartAt > 3f && !_warnedNoInjection)
			{
				_warnedNoInjection = true;
				DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Local voice channel not detected; other players cannot hear the music. State: " + VoiceUplinkPump.DescribeUplink()));
			}
			if (now - _sessionStartAt > 4f && VoiceUplinkPump.InjectedFrames == 0L && !_warnedNoInjection)
			{
				_warnedNoInjection = true;
				DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Uplink patch attached but no samples reached the encoder; players may not hear the music. State: " + VoiceUplinkPump.DescribeUplink()));
			}
		}

		internal string TogglePause()
		{
			if (!_sessionActive)
			{
				return Localization.L("notify.noSession");
			}
			bool? flag = VoiceUplinkPump.Music.TogglePause();
			if (!flag.HasValue)
			{
				return Localization.L("notify.noSession");
			}
			LocalMusicPlayer instance = LocalMusicPlayer.Instance;
			if (flag.Value)
			{
				if ((Object)(object)instance != (Object)null)
				{
					instance.Pause();
				}
				DieForTheMusicPlugin.Log.LogInfo((object)"[CorpseMusic] Wipe music paused from the config UI.");
				return Localization.L("notify.paused");
			}
			if ((Object)(object)instance != (Object)null)
			{
				instance.Resume();
			}
			DieForTheMusicPlugin.Log.LogInfo((object)"[CorpseMusic] Wipe music resumed from the config UI.");
			return Localization.L("notify.resumed");
		}

		internal void Shutdown()
		{
			StopSession("mod unloaded or scene changed");
			_triggeredForThisLeave = false;
		}
	}
	internal sealed class DecodedTrack
	{
		internal float[] Samples;

		internal int Rate;

		internal string Path;

		internal float Duration
		{
			get
			{
				if (Rate <= 0)
				{
					return 0f;
				}
				return (float)Samples.Length / (float)Rate;
			}
		}
	}
	internal sealed class CorpseMusicLoader : MonoBehaviour
	{
		internal static CorpseMusicLoader Instance;

		private DecodedTrack _cached;

		private string _loadingPath;

		internal bool IsLoading => _loadingPath != null;

		private void Awake()
		{
			Instance = this;
		}

		internal DecodedTrack GetOrRequest(string path)
		{
			if (string.IsNullOrEmpty(path) || !File.Exists(path))
			{
				return null;
			}
			if (_cached != null && string.Equals(_cached.Path, path, StringComparison.OrdinalIgnoreCase))
			{
				return _cached;
			}
			if (_loadingPath == null)
			{
				((MonoBehaviour)this).StartCoroutine(Load(path));
			}
			return null;
		}

		internal void Invalidate(string path)
		{
			if (_cached != null && (string.IsNullOrEmpty(path) || string.Equals(_cached.Path, path, StringComparison.OrdinalIgnoreCase)))
			{
				_cached = null;
			}
		}

		private IEnumerator Load(string path)
		{
			_loadingPath = path;
			DieForTheMusicPlugin.Log.LogInfo((object)("[CorpseMusic] Decoding track: " + path));
			string tempClip = null;
			if (!TryBuildUri(path, out var uri))
			{
				tempClip = MirrorToAscii(path);
				if (tempClip == null || !TryBuildUri(tempClip, out uri))
				{
					DieForTheMusicPlugin.Log.LogError((object)("[CorpseMusic] Cannot build local file URL: " + path));
					_loadingPath = null;
					yield break;
				}
			}
			AudioType type = GuessType(path);
			UnityWebRequest request = CreateAudioRequest(uri, type);
			yield return request.SendWebRequest();
			AudioClip clip = null;
			if ((int)request.result == 1)
			{
				clip = DownloadHandlerAudioClip.GetContent(request);
			}
			else
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Decode failed (" + request.error + "), retrying with an ASCII mirror: " + path));
				string mirror = tempClip ?? MirrorToAscii(path);
				if (mirror != null && TryBuildUri(mirror, out uri))
				{
					UnityWebRequest retry = CreateAudioRequest(uri, type);
					yield return retry.SendWebRequest();
					if ((int)retry.result == 1)
					{
						clip = DownloadHandlerAudioClip.GetContent(retry);
					}
					else
					{
						DieForTheMusicPlugin.Log.LogError((object)("[CorpseMusic] Mirror decode also failed: " + retry.error));
					}
					retry.Dispose();
					tempClip = mirror;
				}
			}
			float[] array = null;
			int num = 0;
			if ((Object)(object)clip != (Object)null)
			{
				num = clip.frequency;
				int num2 = Math.Max(1, clip.channels);
				float[] array2 = new float[clip.samples * num2];
				if (!clip.GetData(array2, 0))
				{
					DieForTheMusicPlugin.Log.LogError((object)("[CorpseMusic] Failed to read PCM data: " + path));
				}
				else
				{
					array = ((num2 == 1) ? array2 : Downmix(array2, num2));
				}
				Object.Destroy((Object)(object)clip);
			}
			request.Dispose();
			if (tempClip != null && File.Exists(tempClip))
			{
				try
				{
					File.Delete(tempClip);
				}
				catch (Exception)
				{
				}
			}
			if (array != null && array.Length != 0 && num > 0)
			{
				_cached = new DecodedTrack
				{
					Samples = array,
					Rate = num,
					Path = path
				};
				DieForTheMusicPlugin.Log.LogInfo((object)$"[CorpseMusic] Decoded: {Path.GetFileName(path)} ({num} Hz, {_cached.Duration:0.0}s)");
			}
			_loadingPath = null;
		}

		private static UnityWebRequest CreateAudioRequest(string uri, AudioType type)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip(uri, type);
			DisableStreaming(audioClip);
			return audioClip;
		}

		private static void DisableStreaming(UnityWebRequest request)
		{
			DownloadHandler downloadHandler = request.downloadHandler;
			DownloadHandlerAudioClip val = (DownloadHandlerAudioClip)(object)((downloadHandler is DownloadHandlerAudioClip) ? downloadHandler : null);
			if (val != null)
			{
				val.streamAudio = false;
				val.compressed = false;
			}
		}

		private static float[] Downmix(float[] interleaved, int channels)
		{
			int num = interleaved.Length / channels;
			float[] array = new float[num];
			float num2 = 1f / (float)channels;
			for (int i = 0; i < num; i++)
			{
				float num3 = 0f;
				int num4 = i * channels;
				for (int j = 0; j < channels; j++)
				{
					num3 += interleaved[num4 + j];
				}
				array[i] = num3 * num2;
			}
			return array;
		}

		private static AudioType GuessType(string path)
		{
			string extension = Path.GetExtension(path);
			if (!string.Equals(extension, ".wav", StringComparison.OrdinalIgnoreCase))
			{
				if (!string.Equals(extension, ".ogg", StringComparison.OrdinalIgnoreCase))
				{
					return (AudioType)13;
				}
				return (AudioType)14;
			}
			return (AudioType)20;
		}

		private static bool TryBuildUri(string path, out string uri)
		{
			uri = null;
			if (string.IsNullOrEmpty(path))
			{
				return false;
			}
			string s;
			try
			{
				s = Path.GetFullPath(path).Replace('\\', '/');
			}
			catch (Exception)
			{
				return false;
			}
			byte[] bytes = Encoding.UTF8.GetBytes(s);
			StringBuilder stringBuilder = new StringBuilder(bytes.Length + 16);
			stringBuilder.Append("file:///");
			for (int i = 0; i < bytes.Length; i++)
			{
				byte b = bytes[i];
				if ((b >= 65 && b <= 90) || (b >= 97 && b <= 122) || (b >= 48 && b <= 57) || b == 45 || b == 46 || b == 95 || b == 126 || b == 47 || b == 58)
				{
					stringBuilder.Append((char)b);
				}
				else
				{
					stringBuilder.Append('%').Append(bytes[i].ToString("X2"));
				}
			}
			uri = stringBuilder.ToString();
			return true;
		}

		private static string MirrorToAscii(string sourcePath)
		{
			try
			{
				FileInfo fileInfo = new FileInfo(sourcePath);
				long length = fileInfo.Length;
				string text = Path.Combine(Application.persistentDataPath, "DieForTheMusicCache");
				Directory.CreateDirectory(text);
				string text2 = Fnv(sourcePath + "|" + length);
				string text3 = Path.Combine(text, "track_" + text2 + Path.GetExtension(sourcePath).ToLowerInvariant());
				FileInfo fileInfo2 = new FileInfo(text3);
				if (!fileInfo2.Exists || fileInfo2.Length != length)
				{
					fileInfo.CopyTo(text3, overwrite: true);
				}
				return text3;
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Failed to create ASCII mirror: " + ex.Message));
				return null;
			}
		}

		private static string Fnv(string text)
		{
			uint num = 2166136261u;
			byte[] bytes = Encoding.UTF8.GetBytes(text);
			for (int i = 0; i < bytes.Length; i++)
			{
				num ^= bytes[i];
				num *= 16777619;
			}
			return num.ToString("x8");
		}
	}
	internal sealed class LocalMusicPlayer : MonoBehaviour
	{
		private static LocalMusicPlayer _instance;

		private AudioSource _source;

		private AudioClip _clip;

		private string _clipKey;

		private DecodedTrack _clipTrack;

		internal static LocalMusicPlayer Instance => _instance;

		internal float Volume
		{
			get
			{
				if (!((Object)(object)_source != (Object)null))
				{
					return 0f;
				}
				return _source.volume;
			}
			set
			{
				if ((Object)(object)_source != (Object)null)
				{
					_source.volume = Mathf.Clamp01(value);
				}
			}
		}

		private void Awake()
		{
			_instance = this;
			_source = ((Component)this).gameObject.AddComponent<AudioSource>();
			_source.playOnAwake = false;
			_source.loop = false;
			_source.spatialBlend = 0f;
			_source.volume = 0.7f;
			_source.mute = false;
			_source.bypassEffects = true;
			_source.bypassListenerEffects = true;
			_source.bypassReverbZones = true;
			_source.priority = 0;
		}

		internal bool Prepare(DecodedTrack track)
		{
			if (!IsUsable(track))
			{
				return false;
			}
			return EnsureClip(track);
		}

		internal bool Play(DecodedTrack track, float volume)
		{
			if (!IsUsable(track))
			{
				DieForTheMusicPlugin.Log.LogWarning((object)"[CorpseMusic] Local playback skipped: track data unavailable.");
				return false;
			}
			if ((Object)(object)_source == (Object)null)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)"[CorpseMusic] Local playback skipped: AudioSource not ready.");
				return false;
			}
			if (!EnsureClip(track))
			{
				return false;
			}
			_source.Stop();
			_source.clip = _clip;
			_source.volume = Mathf.Clamp01(volume);
			_source.time = 0f;
			_source.Play();
			bool isPlaying = _source.isPlaying;
			DieForTheMusicPlugin.Log.LogInfo((object)string.Format("[CorpseMusic] Local playback started: {0}, volume {1:0.00}, state={2}", Path.GetFileName(track.Path), _source.volume, isPlaying ? "playing" : "silent"));
			return isPlaying;
		}

		internal void Pause()
		{
			if ((Object)(object)_source != (Object)null && _source.isPlaying)
			{
				_source.Pause();
			}
		}

		internal void Resume()
		{
			if ((Object)(object)_source != (Object)null && (Object)(object)_source.clip != (Object)null && !_source.isPlaying)
			{
				_source.UnPause();
			}
		}

		internal void Stop()
		{
			if ((Object)(object)_source != (Object)null && _source.isPlaying)
			{
				_source.Stop();
			}
		}

		private static bool IsUsable(DecodedTrack track)
		{
			if (track != null && track.Samples != null && track.Samples.Length != 0)
			{
				return track.Rate > 0;
			}
			return false;
		}

		private bool EnsureClip(DecodedTrack track)
		{
			if ((Object)(object)_clip != (Object)null && _clipTrack == track && string.Equals(_clipKey, track.Path, StringComparison.Ordinal))
			{
				return true;
			}
			if ((Object)(object)_clip != (Object)null && _clipKey != null && string.Equals(_clipKey, track.Path, StringComparison.Ordinal))
			{
				_clipTrack = track;
				return true;
			}
			try
			{
				if ((Object)(object)_clip != (Object)null)
				{
					Object.Destroy((Object)(object)_clip);
					_clip = null;
				}
				_clip = AudioClip.Create("DieForTheMusic_CorpseMusic_" + track.Samples.Length, track.Samples.Length, 1, track.Rate, false);
				if ((Object)(object)_clip == (Object)null)
				{
					DieForTheMusicPlugin.Log.LogWarning((object)"[CorpseMusic] Failed to create local AudioClip.");
					return false;
				}
				if (!_clip.SetData(track.Samples, 0))
				{
					DieForTheMusicPlugin.Log.LogWarning((object)"[CorpseMusic] Failed to fill local AudioClip samples.");
					return false;
				}
				_clipKey = track.Path;
				_clipTrack = track;
				DieForTheMusicPlugin.Log.LogInfo((object)$"[CorpseMusic] AudioClip prepared for local playback: {track.Rate} Hz, {track.Duration:0.0}s");
				return true;
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Local AudioClip preparation failed: " + ex.Message));
				return false;
			}
		}
	}
	internal static class TrackLibrary
	{
		internal const string ModPrefix = "[本模组] ";

		internal const string PluginMusicPrefix = "[模组音乐] ";

		internal const string EmptyPlaceholder = "(未找到可用曲目)";

		private static readonly HashSet<string> Extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".mp3", ".wav", ".ogg", ".flac", ".m4a", ".aac", ".aiff", ".aif" };

		private static readonly Dictionary<string, string> Map = new Dictionary<string, string>(StringComparer.Ordinal);

		private static readonly HashSet<string> Seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static string _pluginDir;

		private static string _musicRoot;

		private static string _cachedName;

		private static string _cachedPath;

		private static int _cachedVerifyStamp;

		private const int CachedVerifyIntervalMs = 30000;

		internal static string MusicRoot
		{
			get
			{
				if (_musicRoot == null)
				{
					_musicRoot = Path.Combine(PluginDir, "Music");
				}
				return _musicRoot;
			}
		}

		private static string PluginDir
		{
			get
			{
				if (_pluginDir == null)
				{
					try
					{
						_pluginDir = Path.GetDirectoryName(typeof(TrackLibrary).Assembly.Location) ?? string.Empty;
					}
					catch (Exception)
					{
						_pluginDir = string.Empty;
					}
				}
				return _pluginDir;
			}
		}

		internal static string[] Scan()
		{
			Map.Clear();
			Seen.Clear();
			_cachedName = null;
			_cachedPath = null;
			List<string> list = new List<string>(16);
			CollectFromPluginsRoot(list);
			CollectLevel1(MusicRoot, "[本模组] ", list);
			list.Sort(StringComparer.OrdinalIgnoreCase);
			if (list.Count == 0)
			{
				list.Add("(未找到可用曲目)");
			}
			return list.ToArray();
		}

		private static void CollectFromPluginsRoot(List<string> display)
		{
			string text = FindBepInExRoot();
			if (text == null || !Directory.Exists(text))
			{
				return;
			}
			try
			{
				HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
				string[] directories = Directory.GetDirectories(text);
				foreach (string text2 in directories)
				{
					string fileName = Path.GetFileName(text2);
					if (fileName.IndexOf("dieforthemusic", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						hashSet.Add(text2);
					}
					else
					{
						if (!string.Equals(fileName, "plugins", StringComparison.OrdinalIgnoreCase))
						{
							continue;
						}
						try
						{
							string[] directories2 = Directory.GetDirectories(text2);
							foreach (string text3 in directories2)
							{
								if (Path.GetFileName(text3).IndexOf("dieforthemusic", StringComparison.OrdinalIgnoreCase) >= 0)
								{
									hashSet.Add(text3);
								}
							}
						}
						catch (Exception ex)
						{
							DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Failed to scan the plugins subdirectory: " + ex.Message));
						}
					}
				}
				foreach (string item in hashSet)
				{
					CollectLevel1(item, "[模组音乐] ", display);
				}
			}
			catch (Exception ex2)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Failed to scan the mod music directory: " + text + " → " + ex2.Message));
			}
		}

		private static void CollectLevel1(string root, string prefix, List<string> display)
		{
			if (!string.IsNullOrEmpty(root) && Directory.Exists(root))
			{
				AddFiles(root, root, prefix, display);
				string[] directories;
				try
				{
					directories = Directory.GetDirectories(root);
				}
				catch (Exception ex)
				{
					DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Failed to scan the track subdirectory: " + root + " → " + ex.Message));
					return;
				}
				for (int i = 0; i < directories.Length; i++)
				{
					AddFiles(directories[i], root, prefix, display);
				}
			}
		}

		private static void AddFiles(string dir, string root, string prefix, List<string> display)
		{
			string[] files;
			try
			{
				files = Directory.GetFiles(dir, "*", SearchOption.TopDirectoryOnly);
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Failed to scan the track directory: " + dir + " → " + ex.Message));
				return;
			}
			foreach (string text in files)
			{
				if (Extensions.Contains(Path.GetExtension(text)) && Seen.Add(text))
				{
					string text2 = text.Substring(root.Length).TrimStart('\\', '/');
					string text3 = prefix + text2;
					if (!Map.ContainsKey(text3))
					{
						Map[text3] = text;
						display.Add(text3);
					}
				}
			}
		}

		private static string FindBepInExRoot()
		{
			string directoryName = Path.GetDirectoryName(PluginDir);
			int num = 0;
			while (directoryName != null && directoryName.Length > 0 && num < 5)
			{
				string? fileName = Path.GetFileName(directoryName);
				if (fileName != null && fileName.Equals("BepInEx", StringComparison.OrdinalIgnoreCase))
				{
					break;
				}
				directoryName = Path.GetDirectoryName(directoryName);
				num++;
			}
			return directoryName ?? string.Empty;
		}

		internal static string Resolve(string display)
		{
			if (string.IsNullOrEmpty(display))
			{
				return null;
			}
			if (string.Equals(_cachedName, display, StringComparison.Ordinal) && _cachedPath != null)
			{
				if (Environment.TickCount - _cachedVerifyStamp < 30000)
				{
					return _cachedPath;
				}
				if (File.Exists(_cachedPath))
				{
					_cachedVerifyStamp = Environment.TickCount;
					return _cachedPath;
				}
			}
			if (Map.Count == 0)
			{
				Scan();
			}
			if (Map.TryGetValue(display, out var value) && File.Exists(value))
			{
				_cachedName = display;
				_cachedPath = value;
				_cachedVerifyStamp = Environment.TickCount;
				return value;
			}
			string b = StripPrefix(display);
			foreach (KeyValuePair<string, string> item in Map)
			{
				if (string.Equals(StripPrefix(item.Key), b, StringComparison.OrdinalIgnoreCase) && File.Exists(item.Value))
				{
					_cachedName = display;
					_cachedPath = item.Value;
					_cachedVerifyStamp = Environment.TickCount;
					return item.Value;
				}
			}
			return null;
		}

		private static string StripPrefix(string text)
		{
			if (text.StartsWith("[本模组] ", StringComparison.Ordinal))
			{
				return text.Substring("[本模组] ".Length);
			}
			if (text.StartsWith("[模组音乐] ", StringComparison.Ordinal))
			{
				return text.Substring("[模组音乐] ".Length);
			}
			return text;
		}
	}
	internal sealed class UplinkMusicPlayer
	{
		private readonly object _lock = new object();

		private float[] _source;

		private int _sourceRate;

		private double _srcPos;

		private int _outputRate;

		private double _ratio = 1.0;

		private volatile bool _playing;

		private volatile bool _paused;

		internal float Gain = 0.7f;

		internal bool IsPlaying => _playing;

		internal bool IsPaused => _paused;

		internal void Play(float[] samples, int sampleRate)
		{
			if (samples == null || samples.Length == 0 || sampleRate <= 0)
			{
				return;
			}
			lock (_lock)
			{
				_source = samples;
				_sourceRate = sampleRate;
				_srcPos = 0.0;
				_outputRate = 0;
				_ratio = 1.0;
				_paused = false;
				_playing = true;
			}
		}

		internal void Pause()
		{
			lock (_lock)
			{
				if (_playing)
				{
					_paused = true;
				}
			}
		}

		internal void Resume()
		{
			lock (_lock)
			{
				if (_playing)
				{
					_paused = false;
				}
			}
		}

		internal bool? TogglePause()
		{
			lock (_lock)
			{
				if (!_playing)
				{
					return null;
				}
				_paused = !_paused;
				return _paused;
			}
		}

		internal void Stop()
		{
			lock (_lock)
			{
				_playing = false;
				_paused = false;
				_srcPos = 0.0;
			}
		}

		internal int Inject(ArraySegment<float> samples, int channels, int rate)
		{
			if (!_playing || _paused || channels <= 0 || rate <= 0)
			{
				return 0;
			}
			if (samples.Array == null || samples.Count <= 0)
			{
				return 0;
			}
			int num = samples.Count / channels;
			if (num <= 0)
			{
				return 0;
			}
			lock (_lock)
			{
				if (!_playing || _paused)
				{
					return 0;
				}
				float[] source = _source;
				if (source == null || source.Length == 0)
				{
					_playing = false;
					return 0;
				}
				if (_outputRate != rate)
				{
					_outputRate = rate;
					_ratio = (double)_sourceRate / (double)rate;
				}
				float[] array = samples.Array;
				int offset = samples.Offset;
				int num2 = Math.Min(offset + samples.Count, array.Length);
				int num3 = source.Length - 1;
				float gain = Gain;
				double ratio = _ratio;
				double num4 = _srcPos;
				int num5 = offset;
				int num6 = 0;
				for (int i = 0; i < num; i++)
				{
					if (num5 >= num2)
					{
						break;
					}
					if (num4 >= (double)num3)
					{
						_playing = false;
						break;
					}
					int num7 = (int)num4;
					float num8 = (float)(num4 - (double)num7);
					float num9 = source[num7];
					float num10 = source[(num7 < num3) ? (num7 + 1) : num3];
					float num11 = (num9 + (num10 - num9) * num8) * gain;
					num4 += ratio;
					int num12 = num5 + channels;
					if (num12 > num2)
					{
						num12 = num2;
					}
					if (channels == 1)
					{
						float num13 = array[num5] + num11;
						if (num13 > 1f)
						{
							num13 = 1f;
						}
						else if (num13 < -1f)
						{
							num13 = -1f;
						}
						array[num5] = num13;
					}
					else
					{
						for (int j = num5; j < num12; j++)
						{
							float num14 = array[j] + num11;
							if (num14 > 1f)
							{
								num14 = 1f;
							}
							else if (num14 < -1f)
							{
								num14 = -1f;
							}
							array[j] = num14;
						}
					}
					num5 = num12;
					num6++;
				}
				_srcPos = num4;
				return num6;
			}
		}
	}
	internal static class VoiceUplinkPump
	{
		private const float CacheSearchInterval = 1f;

		private static readonly UplinkMusicPlayer Player = new UplinkMusicPlayer();

		private static VoiceBroadcastTrigger _trigger;

		private static MethodInfo _openChannelMethod;

		private static CommActivationMode _savedMode = (CommActivationMode)1;

		private static bool _channelOpen;

		private static float _nextTriggerSearch;

		private static Type _pipelineType;

		private static DissonanceComms _comms;

		private static float _nextCommsSearch;

		private static bool _restoreMuted;

		private static bool _mutedForced;

		private static bool _loggedMicForced;

		private static long _injectedFrames;

		internal static volatile bool MuteLocalMic;

		internal static UplinkMusicPlayer Music => Player;

		internal static bool Patched => _pipelineType != null;

		internal static long InjectedFrames => Interlocked.Read(in _injectedFrames);

		internal static bool TryAttach(Harmony harmony, ManualLogSource log)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Expected O, but got Unknown
			if (_pipelineType != null)
			{
				return true;
			}
			try
			{
				Type type = AccessTools.TypeByName("Dissonance.Audio.Capture.EncoderPipeline");
				if (type == null)
				{
					return false;
				}
				MethodInfo methodInfo = AccessTools.Method(type, "ReceiveMicrophoneData", new Type[2]
				{
					typeof(ArraySegment<float>),
					typeof(WaveFormat)
				}, (Type[])null);
				if (methodInfo == null)
				{
					log.LogWarning((object)"[CorpseMusic] EncoderPipeline.ReceiveMicrophoneData(ArraySegment<float>, WaveFormat) not found");
					return false;
				}
				MethodInfo method = typeof(VoiceUplinkPump).GetMethod("Prefix", BindingFlags.Static | BindingFlags.NonPublic);
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				_pipelineType = type;
				log.LogInfo((object)("[CorpseMusic] Voice uplink injection patch attached: " + type.FullName + "." + methodInfo.Name));
				return true;
			}
			catch (Exception ex)
			{
				log.LogError((object)("[CorpseMusic] Failed to attach voice uplink patch: " + ex));
				return false;
			}
		}

		private static void Prefix(ArraySegment<float> __0, WaveFormat __1)
		{
			try
			{
				if (Player.IsPlaying && !Player.IsPaused && __1 != null)
				{
					if (MuteLocalMic && __0.Array != null && __0.Count > 0 && __0.Offset >= 0 && __0.Offset + __0.Count <= __0.Array.Length)
					{
						Array.Clear(__0.Array, __0.Offset, __0.Count);
					}
					int num = Player.Inject(__0, __1.Channels, __1.SampleRate);
					if (num > 0)
					{
						Interlocked.Add(ref _injectedFrames, num);
					}
				}
			}
			catch (Exception)
			{
			}
		}

		internal static bool EnsureChannelOpen(ManualLogSource log)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Invalid comparison between Unknown and I4
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			EnsureMicCaptureAlive(log);
			VoiceBroadcastTrigger trigger = GetTrigger();
			if ((Object)(object)trigger == (Object)null)
			{
				return false;
			}
			try
			{
				if (!_channelOpen)
				{
					_savedMode = trigger.Mode;
					_channelOpen = true;
				}
				if ((int)trigger.Mode != 3)
				{
					trigger.Mode = (CommActivationMode)3;
				}
				if (!trigger.IsTransmitting)
				{
					if (_openChannelMethod == null)
					{
						_openChannelMethod = AccessTools.Method(typeof(VoiceBroadcastTrigger), "OpenChannel", (Type[])null, (Type[])null);
					}
					if (_openChannelMethod != null)
					{
						_openChannelMethod.Invoke(trigger, null);
					}
				}
				return trigger.IsTransmitting;
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("[CorpseMusic] Failed to open the voice channel: " + ex.Message));
				return false;
			}
		}

		internal static void RestoreChannel(ManualLogSource log)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Invalid comparison between Unknown and I4
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			RestoreMute(log);
			if (!_channelOpen)
			{
				return;
			}
			try
			{
				VoiceBroadcastTrigger trigger = GetTrigger();
				if ((Object)(object)trigger != (Object)null && (int)trigger.Mode == 3)
				{
					trigger.Mode = _savedMode;
				}
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("[CorpseMusic] Failed to restore voice mode: " + ex.Message));
			}
			_channelOpen = false;
		}

		private static void RestoreMute(ManualLogSource log)
		{
			if (!_mutedForced)
			{
				return;
			}
			_mutedForced = false;
			_loggedMicForced = false;
			try
			{
				DissonanceComms comms = GetComms();
				if ((Object)(object)comms != (Object)null && _restoreMuted)
				{
					comms.IsMuted = true;
				}
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("[CorpseMusic] Failed to restore microphone mute state: " + ex.Message));
			}
		}

		internal static bool EnsureMicCaptureAlive(ManualLogSource log)
		{
			try
			{
				DissonanceComms comms = GetComms();
				if ((Object)(object)comms == (Object)null)
				{
					return false;
				}
				if (comms.IsMuted)
				{
					if (!_mutedForced)
					{
						_mutedForced = true;
						_restoreMuted = true;
					}
					comms.IsMuted = false;
					if (!_loggedMicForced)
					{
						_loggedMicForced = true;
						log.LogInfo((object)"[CorpseMusic] Host voice mute temporarily lifted (the in-game microphone was off); it will be restored after playback.");
					}
				}
				if (comms.MicrophoneCapture == null)
				{
					comms.ResetMicrophoneCapture();
					log.LogInfo((object)"[CorpseMusic] Microphone capture object missing; requested a single capture restart.");
				}
				return !comms.IsMuted && comms.MicrophoneCapture != null;
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("[CorpseMusic] Failed to force-enable microphone capture: " + ex.Message));
				return false;
			}
		}

		internal static string DescribeUplink()
		{
			try
			{
				DissonanceComms comms = GetComms();
				if ((Object)(object)comms == (Object)null)
				{
					return "Dissonance not ready";
				}
				VoiceBroadcastTrigger trigger = GetTrigger();
				return string.Format("muted={0}, micCapture={1}, channelSend={2}, injectedFrames={3}", comms.IsMuted ? "yes" : "no", (comms.MicrophoneCapture == null) ? "missing" : "ok", ((Object)(object)trigger != (Object)null && trigger.IsTransmitting) ? "yes" : "no", InjectedFrames);
			}
			catch (Exception)
			{
				return "diagnostics unavailable";
			}
		}

		private static bool TryBeginSceneSearch(ref float nextSearchAt)
		{
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime < nextSearchAt)
			{
				return false;
			}
			nextSearchAt = unscaledTime + 1f;
			return true;
		}

		private static DissonanceComms GetComms()
		{
			if ((Object)(object)_comms != (Object)null)
			{
				return _comms;
			}
			if (!TryBeginSceneSearch(ref _nextCommsSearch))
			{
				return null;
			}
			try
			{
				_comms = Object.FindObjectOfType<DissonanceComms>();
			}
			catch (Exception)
			{
				_comms = null;
			}
			return _comms;
		}

		private static VoiceBroadcastTrigger GetTrigger()
		{
			if ((Object)(object)_trigger != (Object)null)
			{
				return _trigger;
			}
			if (!TryBeginSceneSearch(ref _nextTriggerSearch))
			{
				return null;
			}
			try
			{
				string text = null;
				try
				{
					DissonanceComms comms = GetComms();
					if ((Object)(object)comms != (Object)null)
					{
						text = comms.LocalPlayerName;
					}
				}
				catch (Exception)
				{
				}
				VoiceBroadcastTrigger val = null;
				VoiceBroadcastTrigger[] array = Object.FindObjectsOfType<VoiceBroadcastTrigger>();
				foreach (VoiceBroadcastTrigger val2 in array)
				{
					if (!((Object)(object)val2 == (Object)null))
					{
						if (!string.IsNullOrEmpty(text) && string.Equals(val2.PlayerId, text, StringComparison.Ordinal))
						{
							val = val2;
							break;
						}
						if ((Object)(object)val == (Object)null && ((Behaviour)val2).enabled)
						{
							val = val2;
						}
					}
				}
				_trigger = val;
			}
			catch (Exception)
			{
				_trigger = null;
			}
			return _trigger;
		}
	}
	internal static class WipeFlightPatch
	{
		internal static bool Install(Harmony harmony, ManualLogSource log)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			try
			{
				MethodInfo methodInfo = AccessTools.Method(typeof(StartOfRound), "ShipLeaveAutomatically", new Type[1] { typeof(bool) }, (Type[])null);
				if (methodInfo == null)
				{
					log.LogWarning((object)"[CorpseMusic] StartOfRound.ShipLeaveAutomatically(bool) not found; falling back to polling for wipes.");
					return false;
				}
				MethodInfo method = typeof(WipeFlightPatch).GetMethod("Postfix", BindingFlags.Static | BindingFlags.NonPublic);
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(method), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				log.LogInfo((object)("[CorpseMusic] Wipe departure patch attached: " + methodInfo.Name + "(bool)"));
				return true;
			}
			catch (Exception ex)
			{
				log.LogWarning((object)("[CorpseMusic] Failed to attach wipe departure patch; falling back to polling: " + ex.Message));
				return false;
			}
		}

		private static void Postfix(StartOfRound __instance, bool leavingOnMidnight)
		{
			try
			{
				if (!((Object)(object)__instance == (Object)null || leavingOnMidnight) && __instance.allPlayersDead)
				{
					DieForTheMusicPlugin.Log.LogInfo((object)"[CorpseMusic] Automatic ship departure triggered by an all-dead wipe detected.");
				}
			}
			catch (Exception ex)
			{
				DieForTheMusicPlugin.Log.LogWarning((object)("[CorpseMusic] Wipe departure detection failed: " + ex.Message));
			}
		}
	}
}