Decompiled source of ElevatorHelldiveTheme v1.0.0

plugins/ElevatorHelldiveTheme.dll

Decompiled 4 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using AK;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
namespace ElevatorHelldiveTheme
{
	[BepInPlugin("dev.kain.gtfo.elevatorhelldivetheme", "Elevator Helldive Theme", "1.1.0")]
	public sealed class ElevatorHelldiveThemePlugin : BasePlugin
	{
		private ElevatorThemeDriver? _driver;

		internal static ElevatorHelldiveThemePlugin? Instance { get; private set; }

		internal static ConfigEntry<bool>? Enabled { get; private set; }

		internal static ConfigEntry<float>? Volume { get; private set; }

		internal static ConfigEntry<float>? FadeInSeconds { get; private set; }

		internal static ConfigEntry<float>? FadeOutSeconds { get; private set; }

		internal static ConfigEntry<bool>? LoopTheme { get; private set; }

		internal static ConfigEntry<bool>? MuteOriginalElevatorAudio { get; private set; }

		internal static ConfigEntry<bool>? PlayDuringPreRelease { get; private set; }

		internal static ConfigEntry<bool>? LogSuppressedEvents { get; private set; }

		internal static bool IsEnabled => Enabled?.Value ?? false;

		internal static bool ShouldLoop => LoopTheme?.Value ?? true;

		internal static bool ShouldMuteOriginal => MuteOriginalElevatorAudio?.Value ?? true;

		internal static bool ShouldPlayDuringPreRelease => PlayDuringPreRelease?.Value ?? false;

		internal static bool ShouldLogSuppressedEvents => LogSuppressedEvents?.Value ?? false;

		public override void Load()
		{
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Expected O, but got Unknown
			Instance = this;
			Enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable the Helldive theme during elevator rides.");
			Volume = ((BasePlugin)this).Config.Bind<float>("Audio", "Volume", 0.65f, "Theme volume, from 0 to 1.");
			FadeInSeconds = ((BasePlugin)this).Config.Bind<float>("Audio", "FadeInSeconds", 0.25f, "Fade-in duration in seconds.");
			FadeOutSeconds = ((BasePlugin)this).Config.Bind<float>("Audio", "FadeOutSeconds", 0.5f, "Fade-out duration in seconds.");
			LoopTheme = ((BasePlugin)this).Config.Bind<bool>("Audio", "LoopTheme", true, "Loop the theme if the elevator ride lasts longer than the clip.");
			MuteOriginalElevatorAudio = ((BasePlugin)this).Config.Bind<bool>("Audio", "MuteOriginalElevatorAudio", true, "Suppress the elevator CellSoundPlayer while the replacement theme is playing.");
			PlayDuringPreRelease = ((BasePlugin)this).Config.Bind<bool>("Audio", "PlayDuringPreRelease", true, "Start the theme during the pre-release sequence instead of waiting for elevator motion.");
			LogSuppressedEvents = ((BasePlugin)this).Config.Bind<bool>("Diagnostics", "LogSuppressedEvents", false, "Log elevator sound event IDs suppressed by this plugin.");
			ElevatorThemeRuntime.Initialize(Path.GetDirectoryName(typeof(ElevatorHelldiveThemePlugin).Assembly.Location) ?? Paths.PluginPath);
			new Harmony("dev.kain.gtfo.elevatorhelldivetheme").PatchAll(typeof(ElevatorHelldiveThemePlugin).Assembly);
			_driver = ((BasePlugin)this).AddComponent<ElevatorThemeDriver>();
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(9, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("Elevator Helldive Theme");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("1.1.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded.");
			}
			log.LogInfo(val);
		}

		internal static void LogInfo(string message)
		{
			ElevatorHelldiveThemePlugin? instance = Instance;
			if (instance != null)
			{
				((BasePlugin)instance).Log.LogInfo((object)message);
			}
		}

		internal static void LogWarning(string message)
		{
			ElevatorHelldiveThemePlugin? instance = Instance;
			if (instance != null)
			{
				((BasePlugin)instance).Log.LogWarning((object)message);
			}
		}

		internal static void LogError(string message, Exception? exception = null)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			if (Instance == null)
			{
				return;
			}
			if (exception == null)
			{
				((BasePlugin)Instance).Log.LogError((object)message);
				return;
			}
			ManualLogSource log = ((BasePlugin)Instance).Log;
			bool flag = default(bool);
			BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(1, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(message);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(exception);
			}
			log.LogError(val);
		}

		internal static float GetVolume()
		{
			return Math.Clamp(Volume?.Value ?? 0.65f, 0f, 1f);
		}

		internal static float GetFadeInSeconds()
		{
			return Math.Max(0.01f, FadeInSeconds?.Value ?? 0.25f);
		}

		internal static float GetFadeOutSeconds()
		{
			return Math.Max(0.01f, FadeOutSeconds?.Value ?? 0.5f);
		}
	}
	public sealed class ElevatorThemeDriver : MonoBehaviour
	{
		public ElevatorThemeDriver(IntPtr pointer)
			: base(pointer)
		{
		}

		public void Update()
		{
			ElevatorThemeRuntime.Tick(Time.unscaledDeltaTime);
		}

		public void OnDestroy()
		{
			ElevatorThemeRuntime.Shutdown();
		}
	}
	[HarmonyPatch(typeof(ElevatorRide), "Awake")]
	internal static class ElevatorRide_Awake_Patch
	{
		private static void Postfix(ElevatorRide __instance)
		{
			ElevatorThemeRuntime.RegisterElevator(__instance);
		}
	}
	[HarmonyPatch(typeof(ElevatorRide), "StartElevatorRide")]
	internal static class ElevatorRide_StartElevatorRide_Patch
	{
		private static void Prefix()
		{
			ElevatorThemeRuntime.BeginRide();
		}
	}
	[HarmonyPatch(typeof(ElevatorRide), "Cleanup")]
	internal static class ElevatorRide_Cleanup_Patch
	{
		private static void Prefix()
		{
			ElevatorThemeRuntime.EndRide();
		}
	}
	[HarmonyPatch(typeof(ElevatorRide), "DropinElevatorExit")]
	internal static class ElevatorRide_DropinElevatorExit_Patch
	{
		private static void Prefix()
		{
			ElevatorThemeRuntime.EndRide();
		}
	}
	[HarmonyPatch(typeof(ElevatorRide), "StartPreReleaseSequence")]
	internal static class ElevatorRide_StartPreReleaseSequence_Patch
	{
		private static void Prefix()
		{
			if (ElevatorHelldiveThemePlugin.ShouldPlayDuringPreRelease)
			{
				ElevatorThemeRuntime.BeginRide();
			}
		}
	}
	[HarmonyPatch(typeof(CellSoundPlayer), "Post", new Type[]
	{
		typeof(uint),
		typeof(Vector3)
	})]
	internal static class CellSoundPlayer_Post_UInt32_Vector3_Patch
	{
		private static bool Prefix(CellSoundPlayer __instance, uint eventID)
		{
			return !ElevatorThemeRuntime.ShouldSuppress(__instance, eventID);
		}
	}
	[HarmonyPatch(typeof(CellSoundPlayer), "Post", new Type[]
	{
		typeof(string),
		typeof(Vector3)
	})]
	internal static class CellSoundPlayer_Post_String_Vector3_Patch
	{
		private static bool Prefix(CellSoundPlayer __instance, string eventName)
		{
			return !ElevatorThemeRuntime.ShouldSuppress(__instance, eventName);
		}
	}
	[HarmonyPatch(typeof(CellSoundPlayer), "Post", new Type[]
	{
		typeof(uint),
		typeof(bool)
	})]
	internal static class CellSoundPlayer_Post_UInt32_Bool_Patch
	{
		private static bool Prefix(CellSoundPlayer __instance, uint eventID)
		{
			return !ElevatorThemeRuntime.ShouldSuppress(__instance, eventID);
		}
	}
	[HarmonyPatch(typeof(CellSoundPlayer), "Post", new Type[]
	{
		typeof(string),
		typeof(bool)
	})]
	internal static class CellSoundPlayer_Post_String_Bool_Patch
	{
		private static bool Prefix(CellSoundPlayer __instance)
		{
			return !ElevatorThemeRuntime.ShouldSuppress(__instance, 0u);
		}
	}
	internal static class ElevatorThemeRuntime
	{
		private const string BundleFileName = "elevator_helldive_theme";

		private const string AudioClipAssetPath = "Assets/ElevatorTheme/helldive_theme.wav";

		private const string RawAudioFileName = "helldive_theme.wav";

		private static string _pluginDirectory = string.Empty;

		private static AssetBundle? _bundle;

		private static AudioClip? _clip;

		private static GameObject? _audioObject;

		private static AudioSource? _audioSource;

		private static AudioListener? _fallbackListener;

		private static ulong _elevatorSoundId;

		private static bool _rideActive;

		private static bool _stopRequested;

		private static bool _arrivalSubscribed;

		private static float _targetVolume;

		private static readonly Action ElevatorArrivedAction = Action.op_Implicit((Action)OnElevatorHasArrived);

		private static readonly HashSet<uint> LoggedEvents = new HashSet<uint>();

		private static readonly HashSet<uint> ElevatorEventIds = new HashSet<uint>
		{
			EVENTS.ELEVATOR_SWISH,
			EVENTS.ELEVATOR_BRAKE_LOOP_START,
			EVENTS.ELEVATOR_SWOOSHING_LOOP_START,
			EVENTS.ELEVATOR_WIND_AGGRESSIVE_LOOP_START,
			EVENTS.ELEVATOR_DEPLOYMENT_MOVE
		};

		internal static void Initialize(string pluginDirectory)
		{
			_pluginDirectory = pluginDirectory;
			SubscribeToElevatorArrival();
			LoadClip();
		}

		private static void SubscribeToElevatorArrival()
		{
			if (_arrivalSubscribed)
			{
				return;
			}
			try
			{
				ElevatorRide.OnElevatorHasArrived += ElevatorArrivedAction;
				_arrivalSubscribed = true;
				ElevatorHelldiveThemePlugin.LogInfo("Subscribed to ElevatorRide.OnElevatorHasArrived; theme will end when the elevator reaches the landing.");
			}
			catch (Exception exception)
			{
				ElevatorHelldiveThemePlugin.LogError("Failed to subscribe to ElevatorRide.OnElevatorHasArrived.", exception);
			}
		}

		private static void UnsubscribeFromElevatorArrival()
		{
			if (!_arrivalSubscribed)
			{
				return;
			}
			try
			{
				ElevatorRide.OnElevatorHasArrived -= ElevatorArrivedAction;
			}
			catch (Exception exception)
			{
				ElevatorHelldiveThemePlugin.LogError("Failed to unsubscribe from ElevatorRide.OnElevatorHasArrived.", exception);
			}
			finally
			{
				_arrivalSubscribed = false;
			}
		}

		private static void OnElevatorHasArrived()
		{
			if (_rideActive)
			{
				ElevatorHelldiveThemePlugin.LogInfo("ElevatorRide.OnElevatorHasArrived received; ending Helldive theme.");
				EndRide();
			}
		}

		internal static void RegisterElevator(ElevatorRide? elevator)
		{
			if ((Object)(object)elevator == (Object)null)
			{
				return;
			}
			try
			{
				CellSoundPlayer sound = elevator.m_sound;
				_elevatorSoundId = ((sound != null) ? sound.ID : 0);
				if (_elevatorSoundId != 0L)
				{
					ElevatorHelldiveThemePlugin.LogInfo($"Registered ElevatorRide sound player ID {_elevatorSoundId}.");
				}
			}
			catch (Exception exception)
			{
				ElevatorHelldiveThemePlugin.LogError("Failed to register ElevatorRide sound player.", exception);
			}
		}

		internal static void BeginRide()
		{
			if (!ElevatorHelldiveThemePlugin.IsEnabled || (Object)(object)_clip == (Object)null)
			{
				return;
			}
			SubscribeToElevatorArrival();
			if (_rideActive && (Object)(object)_audioSource != (Object)null && _audioSource.isPlaying)
			{
				_stopRequested = false;
				_targetVolume = ElevatorHelldiveThemePlugin.GetVolume();
				_audioSource.volume = _targetVolume;
				return;
			}
			_rideActive = true;
			_stopRequested = false;
			_targetVolume = ElevatorHelldiveThemePlugin.GetVolume();
			LoggedEvents.Clear();
			EnsureAudioSource();
			if (!((Object)(object)_audioSource == (Object)null))
			{
				_audioSource.clip = _clip;
				_audioSource.loop = ElevatorHelldiveThemePlugin.ShouldLoop;
				_audioSource.volume = _targetVolume;
				_audioSource.Play();
				ElevatorHelldiveThemePlugin.LogInfo($"Started Helldive theme for elevator ride (playing={_audioSource.isPlaying}, volume={_audioSource.volume:0.##}, listenerPaused={AudioListener.pause}).");
			}
		}

		internal static void EndRide()
		{
			if (_rideActive || (!((Object)(object)_audioSource == (Object)null) && _audioSource.isPlaying))
			{
				_rideActive = false;
				_stopRequested = true;
				_targetVolume = 0f;
			}
		}

		internal static bool ShouldSuppress(CellSoundPlayer? sound, uint eventId)
		{
			if (!_rideActive || !ElevatorHelldiveThemePlugin.ShouldMuteOriginal)
			{
				return false;
			}
			if (eventId != 0 && ElevatorEventIds.Contains(eventId))
			{
				if (ElevatorHelldiveThemePlugin.ShouldLogSuppressedEvents && LoggedEvents.Add(eventId))
				{
					ElevatorHelldiveThemePlugin.LogInfo($"Suppressed elevator event ID {eventId}.");
				}
				return true;
			}
			if (sound == null)
			{
				return false;
			}
			ulong iD;
			try
			{
				iD = sound.ID;
			}
			catch
			{
				return false;
			}
			if (_elevatorSoundId == 0L || iD != _elevatorSoundId)
			{
				return false;
			}
			if (ElevatorHelldiveThemePlugin.ShouldLogSuppressedEvents && LoggedEvents.Add(eventId))
			{
				ElevatorHelldiveThemePlugin.LogInfo($"Suppressed elevator sound event ID {eventId}.");
			}
			return true;
		}

		internal static bool ShouldSuppress(CellSoundPlayer? sound, string? eventName)
		{
			if (!_rideActive || !ElevatorHelldiveThemePlugin.ShouldMuteOriginal || string.IsNullOrWhiteSpace(eventName))
			{
				return false;
			}
			return eventName.IndexOf("ELEVATOR", StringComparison.OrdinalIgnoreCase) >= 0;
		}

		internal static void Tick(float deltaTime)
		{
			if (!((Object)(object)_audioSource == (Object)null))
			{
				RemoveFallbackListenerWhenGameListenerExists();
				float num = (_stopRequested ? ElevatorHelldiveThemePlugin.GetFadeOutSeconds() : ElevatorHelldiveThemePlugin.GetFadeInSeconds());
				float num2 = Mathf.Max(0.001f, deltaTime) / num;
				_audioSource.volume = Mathf.MoveTowards(_audioSource.volume, _targetVolume, num2);
				if (_stopRequested && _audioSource.volume <= 0.001f)
				{
					_audioSource.Stop();
					_audioSource.clip = null;
					_stopRequested = false;
					ElevatorHelldiveThemePlugin.LogInfo("Stopped Helldive theme after elevator ride.");
				}
			}
		}

		internal static void Shutdown()
		{
			UnsubscribeFromElevatorArrival();
			EndRide();
			if ((Object)(object)_audioSource != (Object)null)
			{
				_audioSource.Stop();
				_audioSource.clip = null;
			}
			if ((Object)(object)_audioObject != (Object)null)
			{
				Object.Destroy((Object)(object)_audioObject);
			}
			_audioSource = null;
			_fallbackListener = null;
			_audioObject = null;
			_clip = null;
			if ((Object)(object)_bundle != (Object)null)
			{
				try
				{
					_bundle.Unload(false);
				}
				catch (Exception exception)
				{
					ElevatorHelldiveThemePlugin.LogError("Failed to unload elevator theme bundle.", exception);
				}
				_bundle = null;
			}
		}

		private static void LoadClip()
		{
			string[] array = new string[2]
			{
				Path.Combine(_pluginDirectory, "AssetBundles", "elevator_helldive_theme"),
				Path.Combine(_pluginDirectory, "elevator_helldive_theme")
			};
			foreach (string text in array)
			{
				if (!File.Exists(text))
				{
					continue;
				}
				try
				{
					_bundle = AssetBundle.LoadFromFile(text);
					if (!((Object)(object)_bundle == (Object)null))
					{
						Object obj = _bundle.LoadAsset("Assets/ElevatorTheme/helldive_theme.wav");
						_clip = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<AudioClip>() : null);
						if ((Object)(object)_clip != (Object)null)
						{
							ElevatorHelldiveThemePlugin.LogInfo(string.Format("Loaded elevator theme '{0}' from {1} ({2:0.##}s).", "Assets/ElevatorTheme/helldive_theme.wav", text, _clip.length));
							return;
						}
						ElevatorHelldiveThemePlugin.LogWarning("Elevator theme asset was not found in bundle: Assets/ElevatorTheme/helldive_theme.wav");
					}
				}
				catch (Exception exception)
				{
					ElevatorHelldiveThemePlugin.LogError("Failed to load elevator theme bundle: " + text, exception);
				}
			}
			array = new string[2]
			{
				Path.Combine(_pluginDirectory, "Audio", "helldive_theme.wav"),
				Path.Combine(_pluginDirectory, "helldive_theme.wav")
			};
			foreach (string text2 in array)
			{
				if (File.Exists(text2))
				{
					_clip = LoadWavClip(text2);
					if ((Object)(object)_clip != (Object)null)
					{
						ElevatorHelldiveThemePlugin.LogInfo($"Loaded elevator theme WAV from {text2} ({_clip.length:0.##}s).");
						return;
					}
				}
			}
			ElevatorHelldiveThemePlugin.LogWarning("Missing elevator theme audio. Expected elevator_helldive_theme under '" + _pluginDirectory + "\\AssetBundles' or helldive_theme.wav under '" + _pluginDirectory + "\\Audio'.");
		}

		private static AudioClip? LoadWavClip(string path)
		{
			try
			{
				using FileStream fileStream = File.OpenRead(path);
				using BinaryReader binaryReader = new BinaryReader(fileStream);
				if (ReadFourCc(binaryReader) != "RIFF")
				{
					return null;
				}
				binaryReader.ReadUInt32();
				if (ReadFourCc(binaryReader) != "WAVE")
				{
					return null;
				}
				ushort num = 0;
				ushort num2 = 0;
				ushort num3 = 0;
				ushort num4 = 0;
				int num5 = 0;
				long num6 = -1L;
				int num7 = 0;
				while (fileStream.Position + 8 <= fileStream.Length)
				{
					string text = ReadFourCc(binaryReader);
					uint num8 = binaryReader.ReadUInt32();
					long position = fileStream.Position;
					if (text == "fmt ")
					{
						num = binaryReader.ReadUInt16();
						num2 = binaryReader.ReadUInt16();
						num5 = (int)binaryReader.ReadUInt32();
						binaryReader.ReadUInt32();
						num4 = binaryReader.ReadUInt16();
						num3 = binaryReader.ReadUInt16();
					}
					else if (text == "data")
					{
						num6 = fileStream.Position;
						num7 = (int)Math.Min(num8, fileStream.Length - fileStream.Position);
					}
					fileStream.Position = position + num8 + num8 % 2;
				}
				if (num != 1 || num2 == 0 || num5 <= 0 || num4 == 0 || num6 < 0 || num7 <= 0)
				{
					return null;
				}
				int num9 = num7 / num4;
				float[] array = new float[num9 * num2];
				fileStream.Position = num6;
				for (int i = 0; i < num9; i++)
				{
					for (int j = 0; j < num2; j++)
					{
						float[] array2 = array;
						int num10 = i * num2 + j;
						array2[num10] = num3 switch
						{
							8 => (float)(binaryReader.ReadByte() - 128) / 128f, 
							16 => (float)binaryReader.ReadInt16() / 32768f, 
							24 => (float)ReadInt24(binaryReader) / 8388608f, 
							32 => (float)binaryReader.ReadInt32() / 2.1474836E+09f, 
							_ => throw new InvalidDataException($"Unsupported PCM bit depth: {num3}"), 
						};
					}
					int num11 = num4 - num2 * Math.Max(1, num3 / 8);
					if (num11 > 0)
					{
						fileStream.Position += num11;
					}
				}
				AudioClip val = AudioClip.Create("ElevatorHelldiveTheme", num9, (int)num2, num5, false);
				Il2CppStructArray<float> val2 = new Il2CppStructArray<float>(array);
				try
				{
					if (!AudioClip.SetData(val, val2, array.Length, 0))
					{
						Object.Destroy((Object)(object)val);
						return null;
					}
					int num12 = Math.Min(array.Length, 2048);
					Il2CppStructArray<float> val3 = new Il2CppStructArray<float>((long)num12);
					bool data = AudioClip.GetData(val, val3, num12, 0);
					float num13 = 0f;
					for (int k = 0; k < ((Il2CppArrayBase<float>)(object)val3).Length; k++)
					{
						num13 = Math.Max(num13, Math.Abs(((Il2CppArrayBase<float>)(object)val3)[k]));
					}
					ElevatorHelldiveThemePlugin.LogInfo($"Decoded WAV samples: frames={num9}, channels={num2}, rate={num5}, peak={num13:0.####}, readback={data}.");
					GC.KeepAlive(val3);
				}
				finally
				{
					GC.KeepAlive(val2);
				}
				return val;
			}
			catch (Exception exception)
			{
				ElevatorHelldiveThemePlugin.LogError("Failed to load elevator theme WAV: " + path, exception);
				return null;
			}
		}

		private static string ReadFourCc(BinaryReader reader)
		{
			return Encoding.ASCII.GetString(reader.ReadBytes(4));
		}

		private static int ReadInt24(BinaryReader reader)
		{
			byte num = reader.ReadByte();
			byte b = reader.ReadByte();
			byte b2 = reader.ReadByte();
			int num2 = num | (b << 8) | (b2 << 16);
			if ((num2 & 0x800000) != 0)
			{
				num2 |= -16777216;
			}
			return num2;
		}

		private static void EnsureAudioSource()
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			if (!((Object)(object)_audioSource != (Object)null))
			{
				_audioObject = new GameObject("ElevatorHelldiveTheme.Audio");
				Object.DontDestroyOnLoad((Object)(object)_audioObject);
				EnsureAudioListener();
				_audioSource = _audioObject.AddComponent<AudioSource>();
				_audioSource.playOnAwake = false;
				_audioSource.loop = ElevatorHelldiveThemePlugin.ShouldLoop;
				_audioSource.ignoreListenerPause = true;
				_audioSource.bypassReverbZones = true;
				_audioSource.spatialBlend = 0f;
				_audioSource.volume = 0f;
			}
		}

		private static void EnsureAudioListener()
		{
			try
			{
				foreach (AudioListener item in Object.FindObjectsOfType<AudioListener>())
				{
					if ((Object)(object)item != (Object)null && ((Behaviour)item).enabled && ((Component)item).gameObject.activeInHierarchy)
					{
						return;
					}
				}
				GameObject? audioObject = _audioObject;
				_fallbackListener = ((audioObject != null) ? audioObject.AddComponent<AudioListener>() : null);
				if ((Object)(object)_fallbackListener != (Object)null)
				{
					ElevatorHelldiveThemePlugin.LogInfo("Added a temporary Unity AudioListener for the elevator theme.");
				}
			}
			catch (Exception ex)
			{
				ElevatorHelldiveThemePlugin.LogWarning("Could not create a fallback Unity AudioListener: " + ex.Message);
			}
		}

		private static void RemoveFallbackListenerWhenGameListenerExists()
		{
			if ((Object)(object)_fallbackListener == (Object)null)
			{
				return;
			}
			try
			{
				foreach (AudioListener item in Object.FindObjectsOfType<AudioListener>())
				{
					if ((Object)(object)item != (Object)null && (Object)(object)item != (Object)(object)_fallbackListener && ((Behaviour)item).enabled && ((Component)item).gameObject.activeInHierarchy)
					{
						Object.Destroy((Object)(object)_fallbackListener);
						_fallbackListener = null;
						ElevatorHelldiveThemePlugin.LogInfo("Removed the temporary Unity AudioListener after GTFO provided one.");
						break;
					}
				}
			}
			catch (Exception ex)
			{
				ElevatorHelldiveThemePlugin.LogWarning("Could not inspect Unity AudioListeners: " + ex.Message);
			}
		}
	}
	internal static class PluginInfo
	{
		internal const string Guid = "dev.kain.gtfo.elevatorhelldivetheme";

		internal const string Name = "Elevator Helldive Theme";

		internal const string Version = "1.1.0";
	}
}