Decompiled source of QualityOfLifeMod v1.2.0

plugins\CW Audio Video and QoL\CW.AudioVideoQoL.dll

Decompiled 8 hours 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.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CurvedUI;
using DefaultNamespace;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Photon.Voice;
using Photon.Voice.Unity;
using PlayEveryWare.VideoEncoding;
using TMPro;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;
using Zorro.Core;
using Zorro.Recorder;
using Zorro.Settings;
using Zorro.Settings.UI;
using Zorro.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CW.AudioVideoQoL")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.12.0")]
[assembly: AssemblyInformationalVersion("1.2.12")]
[assembly: AssemblyProduct("CW.AudioVideoQoL")]
[assembly: AssemblyTitle("CW.AudioVideoQoL")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.12.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
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;
		}
	}
	[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 CW_NativeOptionsAudioVideo
{
	public abstract class ActionButtonSetting : BoolSetting, IExposedSetting, IModSettingTooltip
	{
		protected abstract string DisplayName { get; }

		protected virtual string? TooltipText => null;

		protected virtual SettingCategory Category => (SettingCategory)1;

		internal virtual string ButtonLabel => "OPEN";

		public string? Tooltip => TooltipText;

		protected abstract void Run();

		public SettingCategory GetSettingCategory()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return Category;
		}

		public string GetDisplayName()
		{
			return DisplayName;
		}

		protected override bool GetDefaultValue()
		{
			return false;
		}

		public override void Load(ISettingsSaveLoad loader)
		{
			((BoolSetting)this).Value = false;
		}

		public override void Save(ISettingsSaveLoad saver)
		{
		}

		public override void ApplyValue()
		{
			if (!((BoolSetting)this).Value)
			{
				return;
			}
			((BoolSetting)this).Value = false;
			try
			{
				Run();
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)(DisplayName + ": " + ex.Message));
			}
		}
	}
	[ContentWarningSetting]
	public class OpenRadioFolderSetting : ActionButtonSetting
	{
		protected override string DisplayName => "Custom Radio Audio: Browse Folder";

		protected override string TooltipText => "Opens CustomAudio/Radio in File Explorer. Drop .wav, .ogg, or .mp3 files here and click Reload Files.";

		protected override void Run()
		{
			NativeOptionsAudioVideoPlugin.OpenFolder(NativeOptionsAudioVideoPlugin.Instance.RadioDir);
		}
	}
	[ContentWarningSetting]
	public class OpenSfxFolderSetting : ActionButtonSetting
	{
		protected override string DisplayName => "Custom SFX: Browse Folder";

		protected override string TooltipText => "Opens CustomAudio/SFX in File Explorer. Name files after the AudioClip or SFX_Instance name (use 'Log Sound Names' to find them).";

		protected override void Run()
		{
			NativeOptionsAudioVideoPlugin.OpenFolder(NativeOptionsAudioVideoPlugin.Instance.SfxDir);
		}
	}
	[ContentWarningSetting]
	public class OpenSoundboardFolderSetting : ActionButtonSetting
	{
		protected override string DisplayName => "Custom Soundboard: Browse Folder";

		protected override string TooltipText => "Opens CustomAudio/Soundboard in File Explorer. Name files 01_Name.mp3..24_Name.mp3 to replace slots, or any name to append extra sounds, then click Reload Files.";

		protected override void Run()
		{
			NativeOptionsAudioVideoPlugin.OpenFolder(NativeOptionsAudioVideoPlugin.Instance.SoundboardDir);
		}
	}
	[ContentWarningSetting]
	public class ReloadCustomAudioSetting : ActionButtonSetting
	{
		protected override string DisplayName => "Custom Audio: Reload Files";

		protected override string TooltipText => "Unloads previous custom clips and reloads Radio, Soundboard, and SFX folders live without restarting the game.";

		internal override string ButtonLabel => "RELOAD";

		protected override void Run()
		{
			NativeOptionsAudioVideoPlugin.Instance.ReloadAllCustomAudio();
		}
	}
	[ContentWarningSetting]
	public class PickVideoSaveFolderSetting : ActionButtonSetting
	{
		protected override string DisplayName => "Saved Videos: Choose Folder";

		protected override SettingCategory Category => (SettingCategory)100;

		internal override string ButtonLabel => "PICK";

		protected override string TooltipText => "Opens a Windows folder picker to choose where final saved .webm videos are stored.";

		protected override void Run()
		{
			CameraManager.PickVideoSaveFolder();
		}
	}
	[ContentWarningSetting]
	public class OpenVideoSaveFolderSetting : ActionButtonSetting
	{
		protected override string DisplayName => "Saved Videos: Open Folder";

		protected override SettingCategory Category => (SettingCategory)100;

		protected override string TooltipText => "Opens the current final videos folder in File Explorer (defaults to Videos\\Content Warning).";

		protected override void Run()
		{
			NativeOptionsAudioVideoPlugin.OpenFolder(CameraManager.GetFinalVideoSaveDir());
		}
	}
	[ContentWarningSetting]
	public class PickClipsFolderSetting : ActionButtonSetting
	{
		protected override string DisplayName => "Raw Clips: Choose Folder";

		protected override SettingCategory Category => (SettingCategory)100;

		internal override string ButtonLabel => "PICK";

		protected override string TooltipText => "Opens a folder picker for the dedicated TempClips staging folder (outside %TEMP%). A TempClips subfolder is used automatically to protect your other files.";

		protected override void Run()
		{
			CameraManager.PickClipsFolder();
		}
	}
	[ContentWarningSetting]
	public class OpenClipsFolderSetting : ActionButtonSetting
	{
		protected override string DisplayName => "Raw Clips: Open Folder";

		protected override SettingCategory Category => (SettingCategory)100;

		protected override string TooltipText => "Opens the dedicated TempClips staging folder where raw clips are stored until compiled into a full video.";

		protected override void Run()
		{
			NativeOptionsAudioVideoPlugin.OpenFolder(CameraManager.GetClipsStagingDir());
		}
	}
	[ContentWarningSetting]
	public class ViewPointsGuideAction : ActionButtonSetting
	{
		protected override string DisplayName => "Monster & Action Points Guide";

		protected override SettingCategory Category => (SettingCategory)101;

		internal override string ButtonLabel => "VIEW";

		protected override string TooltipText => "Opens an in-game guide listing the exact filming score and estimated views for every monster and player action (read live from the game's BigNumbers data).";

		protected override void Run()
		{
			PointsGuideOverlay.Open();
		}
	}
	[ContentWarningSetting]
	public class ResetAllModSettingsAction : ActionButtonSetting
	{
		protected override string DisplayName => "Reset All Mod Settings to Default";

		protected override SettingCategory Category => (SettingCategory)101;

		internal override string ButtonLabel => "RESET";

		protected override string TooltipText => "Restores every setting in CW Audio, Video and QoL (Audio, Camera, Graphics, QoL) back to its default value immediately.";

		protected override void Run()
		{
			NativeOptionsAudioVideoPlugin.Instance.ResetAllSettingsToDefaults();
		}
	}
	internal static class MicMuteController
	{
		public static volatile bool IsMuted;

		private static AudioSource? _sfxSource;

		private static AudioClip? _muteClip;

		private static AudioClip? _unmuteClip;

		public static void SetMuted(bool muted, bool playSound = false)
		{
			if (IsMuted != muted)
			{
				IsMuted = muted;
				HudOverlay.RefreshVisibility();
				if (playSound)
				{
					PlayChime(muted);
				}
			}
		}

		private static void PlayChime(bool muted)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			try
			{
				if ((Object)(object)_sfxSource == (Object)null)
				{
					GameObject val = new GameObject("CWMod_MicMuteAudio");
					Object.DontDestroyOnLoad((Object)val);
					_sfxSource = val.AddComponent<AudioSource>();
					_sfxSource.playOnAwake = false;
					_sfxSource.spatialBlend = 0f;
					_sfxSource.ignoreListenerPause = true;
					_sfxSource.bypassListenerEffects = true;
					_sfxSource.volume = 0.28f;
				}
				if ((Object)(object)_muteClip == (Object)null)
				{
					_muteClip = BuildTwoToneClip("CWMod_MuteChime", 560f, 390f);
				}
				if ((Object)(object)_unmuteClip == (Object)null)
				{
					_unmuteClip = BuildTwoToneClip("CWMod_UnmuteChime", 400f, 600f);
				}
				_sfxSource.PlayOneShot(muted ? _muteClip : _unmuteClip);
			}
			catch
			{
			}
		}

		private static AudioClip BuildTwoToneClip(string name, float freqA, float freqB)
		{
			int num = 2998;
			int num2 = 793;
			int num3 = num * 2 + num2;
			float[] array = new float[num3];
			WriteTone(array, 0, num, 44100, freqA);
			WriteTone(array, num + num2, num, 44100, freqB);
			AudioClip obj = AudioClip.Create(name, num3, 1, 44100, false);
			obj.SetData(array, 0);
			((Object)obj).hideFlags = (HideFlags)61;
			return obj;
		}

		private static void WriteTone(float[] dst, int offset, int count, int sr, float freq)
		{
			float num = MathF.PI * 2f * freq / (float)sr;
			for (int i = 0; i < count; i++)
			{
				float num2 = (float)i / (float)count;
				float num3 = Mathf.Min(num2 * 14f, 1f) * Mathf.Pow(1f - num2, 1.35f);
				float num4 = Mathf.Sin((float)i * num) * 0.85f + Mathf.Sin((float)i * num * 2f) * 0.15f;
				dst[offset + i] = num4 * num3 * 0.8f;
			}
		}

		public static void Tick()
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			if (ModConfig.QuickMicMuteEnabled == null || !ModConfig.QuickMicMuteEnabled.Value)
			{
				return;
			}
			KeyCode val = (KeyCode)((ModConfig.MicMuteKey == null) ? 109 : ((int)ModConfig.MicMuteKey.Value));
			if ((int)val == 0 || !Input.GetKeyDown(val) || Cursor.visible)
			{
				return;
			}
			Player localPlayer = Player.localPlayer;
			if ((Object)(object)localPlayer == (Object)null || localPlayer.HasLockedInput())
			{
				return;
			}
			EventSystem current = EventSystem.current;
			if ((Object)(object)current != (Object)null && (Object)(object)current.currentSelectedGameObject != (Object)null)
			{
				GameObject currentSelectedGameObject = current.currentSelectedGameObject;
				if ((Object)(object)currentSelectedGameObject.GetComponent<TMP_InputField>() != (Object)null || (Object)(object)currentSelectedGameObject.GetComponent<InputField>() != (Object)null)
				{
					return;
				}
			}
			SetMuted(!IsMuted, playSound: true);
		}
	}
	internal struct NoiseGateState
	{
		private float _envelope;

		private int _holdFrames;

		public float Evaluate(float peak, float threshold)
		{
			if (threshold <= 0.0001f)
			{
				_envelope = 1f;
				return 1f;
			}
			if (peak >= threshold)
			{
				_holdFrames = 6;
				_envelope = Mathf.Min(1f, _envelope + 0.35f);
			}
			else if (_holdFrames > 0)
			{
				_holdFrames--;
			}
			else
			{
				_envelope = Mathf.Max(0f, _envelope - 0.12f);
			}
			return _envelope;
		}
	}
	internal sealed class MicGainFloatProcessor : IProcessor<float>, IDisposable
	{
		private NoiseGateState _gate;

		public float[] Process(float[] buf)
		{
			if (buf == null || buf.Length == 0)
			{
				return buf;
			}
			bool flag = ModConfig.ShowMicMeter != null && ModConfig.ShowMicMeter.Value;
			if (MicMuteController.IsMuted)
			{
				Array.Clear(buf, 0, buf.Length);
				if (flag)
				{
					HudOverlay.ReportMicPeak(0f);
				}
				return buf;
			}
			float value = ModConfig.MicGain.Value;
			float value2 = ModConfig.MicNoiseGate.Value;
			bool value3 = ModConfig.MicSoftLimiter.Value;
			if (!flag && value2 <= 0.0001f && Mathf.Approximately(value, 1f))
			{
				return buf;
			}
			float num = 1f;
			if (value2 > 0.0001f)
			{
				float num2 = 0f;
				for (int i = 0; i < buf.Length; i++)
				{
					float num3 = ((buf[i] < 0f) ? (0f - buf[i]) : buf[i]);
					if (num3 > num2)
					{
						num2 = num3;
					}
				}
				num = _gate.Evaluate(num2, value2);
			}
			float num4 = value * num;
			float num5 = 0f;
			bool flag2 = !Mathf.Approximately(num4, 1f) || value3;
			for (int j = 0; j < buf.Length; j++)
			{
				float num6 = buf[j];
				if (flag2)
				{
					num6 *= num4;
					if (value3)
					{
						num6 = (float)Math.Tanh(num6);
					}
					num6 = (buf[j] = Mathf.Clamp(num6, -1f, 1f));
				}
				if (flag)
				{
					float num7 = ((num6 < 0f) ? (0f - num6) : num6);
					if (num7 > num5)
					{
						num5 = num7;
					}
				}
			}
			if (flag)
			{
				HudOverlay.ReportMicPeak(num5);
			}
			return buf;
		}

		public void Dispose()
		{
		}
	}
	internal sealed class MicGainShortProcessor : IProcessor<short>, IDisposable
	{
		private NoiseGateState _gate;

		public short[] Process(short[] buf)
		{
			if (buf == null || buf.Length == 0)
			{
				return buf;
			}
			bool flag = ModConfig.ShowMicMeter != null && ModConfig.ShowMicMeter.Value;
			if (MicMuteController.IsMuted)
			{
				Array.Clear(buf, 0, buf.Length);
				if (flag)
				{
					HudOverlay.ReportMicPeak(0f);
				}
				return buf;
			}
			float value = ModConfig.MicGain.Value;
			float value2 = ModConfig.MicNoiseGate.Value;
			bool value3 = ModConfig.MicSoftLimiter.Value;
			if (!flag && value2 <= 0.0001f && Mathf.Approximately(value, 1f))
			{
				return buf;
			}
			float num = 1f;
			if (value2 > 0.0001f)
			{
				float num2 = 0f;
				for (int i = 0; i < buf.Length; i++)
				{
					float num3 = Mathf.Abs((float)buf[i] / 32767f);
					if (num3 > num2)
					{
						num2 = num3;
					}
				}
				num = _gate.Evaluate(num2, value2);
			}
			float num4 = value * num;
			float num5 = 0f;
			bool flag2 = !Mathf.Approximately(num4, 1f) || value3;
			for (int j = 0; j < buf.Length; j++)
			{
				float num6 = (float)buf[j] / 32767f;
				if (flag2)
				{
					num6 *= num4;
					if (value3)
					{
						num6 = (float)Math.Tanh(num6);
					}
					num6 = Mathf.Clamp(num6, -1f, 1f);
					buf[j] = (short)(num6 * 32767f);
				}
				if (flag)
				{
					float num7 = ((num6 < 0f) ? (0f - num6) : num6);
					if (num7 > num5)
					{
						num5 = num7;
					}
				}
			}
			if (flag)
			{
				HudOverlay.ReportMicPeak(num5);
			}
			return buf;
		}

		public void Dispose()
		{
		}
	}
	[HarmonyPatch(typeof(Recorder), "CreateLocalVoiceAudioAndSource")]
	internal static class PhotonLocalVoiceCreatedPatch
	{
		private static void Postfix(LocalVoice __result)
		{
			try
			{
				LocalVoiceAudioFloat val = (LocalVoiceAudioFloat)(object)((__result is LocalVoiceAudioFloat) ? __result : null);
				if (val != null)
				{
					((LocalVoiceFramed<float>)(object)val).AddPostProcessor(new IProcessor<float>[1]
					{
						new MicGainFloatProcessor()
					});
					return;
				}
				LocalVoiceAudioShort val2 = (LocalVoiceAudioShort)(object)((__result is LocalVoiceAudioShort) ? __result : null);
				if (val2 != null)
				{
					((LocalVoiceFramed<short>)(object)val2).AddPostProcessor(new IProcessor<short>[1]
					{
						new MicGainShortProcessor()
					});
				}
				else if (__result != null)
				{
					NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("LocalVoice no soportado para boost: " + ((object)__result).GetType().Name));
				}
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("No se pudo enganchar procesador de mic: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(RecordingSession), "PushMicAudio")]
	internal static class RecordingSessionMicBoostPatch
	{
		private static readonly FieldRef<RecordingSession, float>? AmplitudeRef = TryGetAmpRef();

		[ThreadStatic]
		private static float[]? _scratch;

		[ThreadStatic]
		private static NoiseGateState _gate;

		private static FieldRef<RecordingSession, float>? TryGetAmpRef()
		{
			try
			{
				return AccessTools.FieldRefAccess<RecordingSession, float>("amplitude");
			}
			catch
			{
				return null;
			}
		}

		private static void Prefix(RecordingSession __instance, ref float[] data)
		{
			if (data == null || data.Length == 0 || __instance == null)
			{
				return;
			}
			if (_scratch == null || _scratch.Length != data.Length)
			{
				_scratch = new float[data.Length];
			}
			if (MicMuteController.IsMuted)
			{
				Array.Clear(_scratch, 0, _scratch.Length);
				data = _scratch;
				return;
			}
			float num = ModConfig.RecordingMicGain.Value;
			float value = ModConfig.MicNoiseGate.Value;
			bool value2 = ModConfig.MicSoftLimiter.Value;
			if (AmplitudeRef != null)
			{
				AmplitudeRef.Invoke(__instance) = 1f;
			}
			else
			{
				num /= 1.5f;
			}
			float num2 = 1f;
			if (value > 0.0001f)
			{
				float num3 = 0f;
				for (int i = 0; i < data.Length; i++)
				{
					float num4 = ((data[i] < 0f) ? (0f - data[i]) : data[i]);
					if (num4 > num3)
					{
						num3 = num4;
					}
				}
				num2 = _gate.Evaluate(num3, value);
			}
			float num5 = num * num2;
			for (int j = 0; j < data.Length; j++)
			{
				float num6 = data[j] * num5;
				if (value2)
				{
					num6 = (float)Math.Tanh(num6);
				}
				_scratch[j] = Mathf.Clamp(num6, -1f, 1f);
			}
			data = _scratch;
		}
	}
	[HarmonyPatch(typeof(RecordingSession), "PushAudio")]
	internal static class RecordingSessionGameAudioPatch
	{
		[ThreadStatic]
		private static float[]? _scratch;

		private static void Prefix(ref float[] data)
		{
			if (data == null || data.Length == 0)
			{
				return;
			}
			float value = ModConfig.RecordingGameAudioGain.Value;
			if (!Mathf.Approximately(value, 1f))
			{
				if (_scratch == null || _scratch.Length != data.Length)
				{
					_scratch = new float[data.Length];
				}
				for (int i = 0; i < data.Length; i++)
				{
					_scratch[i] = Mathf.Clamp(data[i] * value, -1f, 1f);
				}
				data = _scratch;
			}
		}
	}
	internal static class VolumeCurveHelper
	{
		public static bool TryApply(float rawValue, AudioMixerGroup? grp, string paramName)
		{
			if (!ModConfig.SmoothVolumeCurves.Value || (Object)(object)grp == (Object)null || (Object)(object)grp.audioMixer == (Object)null)
			{
				return false;
			}
			float num = Mathf.Clamp(ModConfig.VolumeFloor.Value, 0.0005f, 0.03f);
			float num2 = ((!(rawValue <= num)) ? Mathf.Clamp(Mathf.Log10(Mathf.Max(Mathf.Pow(Mathf.InverseLerp(num, 1f, Mathf.Clamp01(rawValue)), 1.75f), 0.0001f)) * 20f, -80f, 0f) : (-80f));
			grp.audioMixer.SetFloat(paramName, num2);
			return true;
		}

		public static void ReapplyNativeVolumes()
		{
			try
			{
				GameHandler instance = GameHandler.Instance;
				SettingsHandler val = ((instance != null) ? instance.SettingsHandler : null);
				if (val != null)
				{
					MasterVolumeSetting setting = val.GetSetting<MasterVolumeSetting>();
					if (setting != null)
					{
						((Setting)setting).ApplyValue();
					}
					SFXVolumeSetting setting2 = val.GetSetting<SFXVolumeSetting>();
					if (setting2 != null)
					{
						((Setting)setting2).ApplyValue();
					}
					VoiceVolumeSetting setting3 = val.GetSetting<VoiceVolumeSetting>();
					if (setting3 != null)
					{
						((Setting)setting3).ApplyValue();
					}
				}
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("ReapplyNativeVolumes: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(MasterVolumeSetting), "ApplyValue")]
	internal static class MasterVolumeCurvePatch
	{
		private static bool Prefix(MasterVolumeSetting __instance)
		{
			if (__instance != null)
			{
				return !VolumeCurveHelper.TryApply(((FloatSetting)__instance).Value, __instance.mixerGroup, "MasterVolume");
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(SFXVolumeSetting), "ApplyValue")]
	internal static class SfxVolumeCurvePatch
	{
		private static bool Prefix(SFXVolumeSetting __instance)
		{
			if (__instance != null)
			{
				return !VolumeCurveHelper.TryApply(((FloatSetting)__instance).Value, __instance.mixerGroup, "SFXVolume");
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(VoiceVolumeSetting), "ApplyValue")]
	internal static class VoiceVolumeCurvePatch
	{
		private static bool Prefix(VoiceVolumeSetting __instance)
		{
			if (__instance != null)
			{
				return !VolumeCurveHelper.TryApply(((FloatSetting)__instance).Value, __instance.mixerGroup, "VoiceVolume");
			}
			return true;
		}
	}
	internal static class RadioInjector
	{
		private sealed class FloatBox
		{
			public float Value;
		}

		private static readonly ConditionalWeakTable<AudioLoop, FloatBox> BaseVolumes = new ConditionalWeakTable<AudioLoop, FloatBox>();

		private static float GetBaseVolume(AudioLoop loop)
		{
			if (BaseVolumes.TryGetValue(loop, out FloatBox value))
			{
				return value.Value;
			}
			value = new FloatBox
			{
				Value = loop.volume
			};
			BaseVolumes.Add(loop, value);
			return value.Value;
		}

		public static void ApplyVolume(ArtifactRadio radio)
		{
			if ((Object)(object)radio == (Object)null)
			{
				return;
			}
			float value = ModConfig.RadioVolume.Value;
			AudioLoop[] components = ((Component)radio).GetComponents<AudioLoop>();
			for (int i = 0; i < components.Length; i++)
			{
				if (!((Object)(object)components[i] == (Object)null))
				{
					components[i].volume = GetBaseVolume(components[i]) * value;
				}
			}
		}

		public static void ApplyRadioVolumeToScene()
		{
			ArtifactRadio[] array = Object.FindObjectsByType<ArtifactRadio>((FindObjectsSortMode)0);
			for (int i = 0; i < array.Length; i++)
			{
				ApplyVolume(array[i]);
			}
		}

		public static void AddCustomLoops(ArtifactRadio radio)
		{
			NativeOptionsAudioVideoPlugin instance = NativeOptionsAudioVideoPlugin.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)radio == (Object)null || !ModConfig.CustomRadio.Value || instance.RadioClips.Count == 0)
			{
				return;
			}
			AudioLoop[] components = ((Component)radio).GetComponents<AudioLoop>();
			if (components.Length == 0)
			{
				return;
			}
			AudioLoop val = components[0];
			float baseVolume = GetBaseVolume(val);
			for (int i = 0; i < instance.RadioClips.Count; i++)
			{
				AudioClip val2 = instance.RadioClips[i];
				if (!((Object)(object)val2 == (Object)null) && !HasLoopWithClip(components, val2))
				{
					AudioLoop val3 = ((Component)radio).gameObject.AddComponent<AudioLoop>();
					((Behaviour)val3).enabled = false;
					val3.clip = val2;
					val3.mixerGroup = val.mixerGroup;
					val3.volume = baseVolume;
					BaseVolumes.Add(val3, new FloatBox
					{
						Value = baseVolume
					});
					val3.pitch = val.pitch;
					val3.minDistance = val.minDistance;
					val3.maxDistance = val.maxDistance;
					val3.obstrability = val.obstrability;
					val3.blend = val.blend;
					instance.InjectedLoops.Add(val3);
				}
			}
		}

		public static void ReloadOnRadio(ArtifactRadio radio)
		{
			if (!((Object)(object)radio == (Object)null))
			{
				AddCustomLoops(radio);
				AudioLoop[] components = ((Component)radio).GetComponents<AudioLoop>();
				if (components.Length != 0 && ((Object)(object)radio.music == (Object)null || (Object)(object)radio.music.clip == (Object)null))
				{
					AudioLoop music = components[Random.Range(0, components.Length)];
					radio.music = music;
				}
				ApplyVolume(radio);
			}
		}

		private static bool HasLoopWithClip(AudioLoop[] loops, AudioClip clip)
		{
			for (int i = 0; i < loops.Length; i++)
			{
				if ((Object)(object)loops[i] != (Object)null && (Object)(object)loops[i].clip == (Object)(object)clip)
				{
					return true;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(ArtifactRadio), "ConfigItem")]
	internal static class RadioAudioLoopPatch
	{
		private static void Prefix(ArtifactRadio __instance)
		{
			try
			{
				RadioInjector.AddCustomLoops(__instance);
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("Radio Prefix: " + ex.Message));
			}
		}

		private static void Postfix(ArtifactRadio __instance)
		{
			try
			{
				if ((Object)(object)__instance == (Object)null)
				{
					return;
				}
				AudioLoop[] components = ((Component)__instance).GetComponents<AudioLoop>();
				for (int i = 0; i < components.Length; i++)
				{
					if ((Object)(object)components[i] != (Object)null && (Object)(object)components[i] != (Object)(object)__instance.music && ((Behaviour)components[i]).enabled)
					{
						((Behaviour)components[i]).enabled = false;
					}
				}
				RadioInjector.ApplyVolume(__instance);
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("Radio Postfix: " + ex.Message));
			}
		}
	}
	internal static class SfxOverrideHelper
	{
		private static readonly HashSet<string> LoggedKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		public static bool IsActive
		{
			get
			{
				if (ModConfig.LogSfxNames == null || !ModConfig.LogSfxNames.Value)
				{
					if (ModConfig.CustomSfx != null && ModConfig.CustomSfx.Value && (Object)(object)NativeOptionsAudioVideoPlugin.Instance != (Object)null)
					{
						return NativeOptionsAudioVideoPlugin.Instance.SfxByName.Count > 0;
					}
					return false;
				}
				return true;
			}
		}

		public static void ClearLoggedNames()
		{
			LoggedKeys.Clear();
		}

		public static AudioClip? Resolve(string? instanceName, AudioClip? original)
		{
			if ((Object)(object)original == (Object)null)
			{
				return null;
			}
			bool flag = ModConfig.LogSfxNames != null && ModConfig.LogSfxNames.Value;
			bool flag2 = ModConfig.CustomSfx != null && ModConfig.CustomSfx.Value;
			if (!flag && !flag2)
			{
				return original;
			}
			string name = ((Object)original).name;
			if (flag)
			{
				string item = (string.IsNullOrEmpty(instanceName) ? name : (instanceName + "|" + name));
				if (LoggedKeys.Add(item))
				{
					if (string.IsNullOrEmpty(instanceName))
					{
						NativeOptionsAudioVideoPlugin.Log.LogInfo((object)("[SFX] Clip='" + name + "'"));
					}
					else
					{
						NativeOptionsAudioVideoPlugin.Log.LogInfo((object)("[SFX] Instance='" + instanceName + "' | Clip='" + name + "'"));
					}
				}
			}
			if (!flag2)
			{
				return original;
			}
			NativeOptionsAudioVideoPlugin instance = NativeOptionsAudioVideoPlugin.Instance;
			if ((Object)(object)instance == (Object)null || instance.SfxByName.Count == 0)
			{
				return original;
			}
			if (!string.IsNullOrEmpty(name) && instance.SfxByName.TryGetValue(name, out AudioClip value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (!string.IsNullOrEmpty(instanceName) && instance.SfxByName.TryGetValue(instanceName, out AudioClip value2) && (Object)(object)value2 != (Object)null)
			{
				return value2;
			}
			return original;
		}
	}
	[HarmonyPatch(typeof(SFX_Instance), "GetClip")]
	internal static class SfxInstanceGetClipPatch
	{
		private static void Postfix(SFX_Instance __instance, ref AudioClip __result)
		{
			if (!((Object)(object)__result == (Object)null) && SfxOverrideHelper.IsActive)
			{
				AudioClip val = SfxOverrideHelper.Resolve(((Object)(object)__instance != (Object)null) ? ((Object)__instance).name : null, __result);
				if ((Object)(object)val != (Object)null)
				{
					__result = val;
				}
			}
		}
	}
	[HarmonyPatch(typeof(AudioSource), "PlayOneShot", new Type[]
	{
		typeof(AudioClip),
		typeof(float)
	})]
	internal static class AudioSourcePlayOneShotPatch
	{
		private static void Prefix(ref AudioClip clip)
		{
			if (!((Object)(object)clip == (Object)null) && SfxOverrideHelper.IsActive)
			{
				AudioClip val = SfxOverrideHelper.Resolve(null, clip);
				if ((Object)(object)val != (Object)null)
				{
					clip = val;
				}
			}
		}
	}
	[HarmonyPatch(typeof(AudioSource), "Play", new Type[] { })]
	internal static class AudioSourcePlayPatch
	{
		private static void Prefix(AudioSource __instance)
		{
			if ((Object)(object)__instance == (Object)null || !SfxOverrideHelper.IsActive)
			{
				return;
			}
			AudioClip clip = __instance.clip;
			if (!((Object)(object)clip == (Object)null))
			{
				AudioClip val = SfxOverrideHelper.Resolve(null, clip);
				if ((Object)(object)val != (Object)null && (Object)(object)val != (Object)(object)clip)
				{
					__instance.clip = val;
				}
			}
		}
	}
	internal static class SoundboardInjector
	{
		private static readonly FieldInfo? SelectionEntryField = AccessTools.Field(typeof(SoundPlayerItem), "selectionEntry");

		private static readonly ConditionalWeakTable<SoundPlayerItem, SFX_Instance[]> BaseSounds = new ConditionalWeakTable<SoundPlayerItem, SFX_Instance[]>();

		private static void SyncSelectionRange(SoundPlayerItem item)
		{
			object? obj = SelectionEntryField?.GetValue(item);
			IntRangeEntry val = (IntRangeEntry)((obj is IntRangeEntry) ? obj : null);
			if (val != null)
			{
				val.maxValue = item.sounds.Length;
				val.selectedValue = Mathf.Clamp(val.selectedValue, 0, Mathf.Max(0, item.sounds.Length - 1));
			}
		}

		public static void Apply(SoundPlayerItem item)
		{
			NativeOptionsAudioVideoPlugin instance = NativeOptionsAudioVideoPlugin.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)item == (Object)null || item.sounds == null || item.sounds.Length == 0)
			{
				return;
			}
			if (!BaseSounds.TryGetValue(item, out SFX_Instance[] value))
			{
				value = (SFX_Instance[])item.sounds.Clone();
				BaseSounds.Add(item, value);
			}
			if (!ModConfig.CustomSoundboard.Value || instance.SoundboardClips.Count == 0)
			{
				item.sounds = (SFX_Instance[])value.Clone();
				SyncSelectionRange(item);
				return;
			}
			SFX_Instance val = value[0];
			List<SFX_Instance> list = new List<SFX_Instance>(value);
			for (int i = 0; i < instance.SoundboardClips.Count; i++)
			{
				AudioClip val2 = instance.SoundboardClips[i];
				if (!((Object)(object)val2 == (Object)null))
				{
					ParseSlotAndLabel(((Object)val2).name, out int zeroBasedSlot, out string label);
					SFX_Instance val3 = Object.Instantiate<SFX_Instance>(val);
					((Object)val3).name = label;
					val3.clips = (AudioClip[])(object)new AudioClip[1] { val2 };
					((Object)val3).hideFlags = (HideFlags)52;
					instance.CreatedSoundboardSfx.Add(val3);
					if (zeroBasedSlot >= 0 && zeroBasedSlot < list.Count)
					{
						list[zeroBasedSlot] = val3;
					}
					else
					{
						list.Add(val3);
					}
				}
			}
			item.sounds = list.ToArray();
			SyncSelectionRange(item);
		}

		private static void ParseSlotAndLabel(string rawName, out int zeroBasedSlot, out string label)
		{
			zeroBasedSlot = -1;
			label = rawName;
			if (string.IsNullOrEmpty(rawName))
			{
				return;
			}
			int i;
			for (i = 0; i < rawName.Length && char.IsDigit(rawName[i]); i++)
			{
			}
			if (i <= 0 || i > 2 || !int.TryParse(rawName.Substring(0, i), out var result) || result < 1 || result > 24)
			{
				return;
			}
			if (i == rawName.Length)
			{
				zeroBasedSlot = result - 1;
				label = $"Custom {result}";
				return;
			}
			char c = rawName[i];
			if (c == '_' || c == '-' || c == ' ' || c == '.')
			{
				zeroBasedSlot = result - 1;
				string text = rawName.Substring(i).TrimStart('_', '-', ' ', '.');
				label = (string.IsNullOrEmpty(text) ? $"Custom {result}" : text);
			}
		}
	}
	[HarmonyPatch(typeof(SoundPlayerItem), "ConfigItem")]
	internal static class SoundPlayerItemConfigPatch
	{
		private static void Prefix(SoundPlayerItem __instance)
		{
			try
			{
				SoundboardInjector.Apply(__instance);
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("Soundboard: " + ex.Message));
			}
		}
	}
	internal static class TvAudioDucking
	{
		private static readonly FieldRef<UploadCompleteUI, VideoPlayer?> VideoPlayerRef = AccessTools.FieldRefAccess<UploadCompleteUI, VideoPlayer>("m_videoPlayer");

		internal static VideoPlayer? ActiveTvPlayer;

		public static void Track(UploadCompleteUI? ui)
		{
			if ((Object)(object)ui != (Object)null)
			{
				ActiveTvPlayer = VideoPlayerRef.Invoke(ui);
			}
		}

		public static void Clear()
		{
			ActiveTvPlayer = null;
		}
	}
	[HarmonyPatch(typeof(UploadCompleteUI), "PlayVideo")]
	internal static class TvTrackPlayVideoPatch
	{
		private static void Postfix(UploadCompleteUI __instance)
		{
			TvAudioDucking.Track(__instance);
		}
	}
	[HarmonyPatch(typeof(UploadCompleteUI), "PlayVideos")]
	internal static class TvTrackPlayVideosPatch
	{
		private static void Postfix(UploadCompleteUI __instance)
		{
			TvAudioDucking.Track(__instance);
		}
	}
	[HarmonyPatch(typeof(UploadCompleteUI), "RPCA_Replay")]
	internal static class TvTrackReplayPatch
	{
		private static void Postfix(UploadCompleteUI __instance)
		{
			TvAudioDucking.Track(__instance);
		}
	}
	[HarmonyPatch(typeof(AudioLoopHandler), "LateUpdate")]
	internal static class TvMuteAmbientLoopsPatch
	{
		private static readonly FieldRef<AudioLoopHandler, Dictionary<AudioLoop, AudioSource>?> AudioSourcesRef = AccessTools.FieldRefAccess<AudioLoopHandler, Dictionary<AudioLoop, AudioSource>>("audioSources");

		private static void Postfix(AudioLoopHandler __instance)
		{
			if (ModConfig.MuteAmbientOnTv == null || !ModConfig.MuteAmbientOnTv.Value || !LobbyHelper.IsInSurfaceLobby())
			{
				return;
			}
			VideoPlayer activeTvPlayer = TvAudioDucking.ActiveTvPlayer;
			if ((Object)(object)activeTvPlayer == (Object)null || !activeTvPlayer.isPlaying)
			{
				return;
			}
			Dictionary<AudioLoop, AudioSource> dictionary = AudioSourcesRef.Invoke(__instance);
			if (dictionary == null || dictionary.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<AudioLoop, AudioSource> item in dictionary)
			{
				if ((Object)(object)item.Value != (Object)null)
				{
					item.Value.volume = 0f;
				}
			}
		}
	}
	[HarmonyPatch(typeof(MaxFramerateSetting), "ApplyValue")]
	internal static class MaxFramerateDebouncePatch
	{
		private static bool Prefix(MaxFramerateSetting __instance)
		{
			if (Deferred.FlushingFps)
			{
				return true;
			}
			Deferred.RequestFps(__instance);
			return false;
		}
	}
	internal static class CameraManager
	{
		private static string? _lastSavedFolderName;

		private static string? _lastSavedFileName;

		private static float _lastSavedTime = -10f;

		private static readonly int[] ResolutionPresets = new int[5] { 420, 512, 640, 720, 960 };

		private static readonly FieldInfo? RcRenderW = AccessTools.Field(typeof(RecordingConstants), "VIDEO_RENDER_TEXTURE_WIDTH");

		private static readonly FieldInfo? RcRenderH = AccessTools.Field(typeof(RecordingConstants), "VIDEO_RENDER_TEXTURE_HEIGHT");

		private static readonly FieldInfo? RcOutW = AccessTools.Field(typeof(RecordingConstants), "VIDEO_OUTPUT_WIDTH");

		private static readonly FieldInfo? RcOutH = AccessTools.Field(typeof(RecordingConstants), "VIDEO_OUTPUT_HEIGHT");

		private static readonly FieldInfo? CamCameraField = AccessTools.Field(typeof(VideoCamera), "m_camera");

		private static readonly MethodInfo? CamCreateRtMethod = AccessTools.Method(typeof(VideoCamera), "CreateRenderTexture", (Type[])null, (Type[])null);

		public static string DefaultVideosRoot
		{
			get
			{
				string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
				if (string.IsNullOrEmpty(folderPath))
				{
					folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
				}
				return Path.Combine(folderPath, "Content Warning");
			}
		}

		private static string FallbackPersistentRoot => Path.Combine(Application.persistentDataPath, "CW_Videos");

		private static bool TryEnsureWritableDir(string dir)
		{
			if (string.IsNullOrWhiteSpace(dir))
			{
				return false;
			}
			try
			{
				Directory.CreateDirectory(dir);
				return Directory.Exists(dir);
			}
			catch
			{
				return false;
			}
		}

		public static string GetFinalVideoSaveDir()
		{
			string text = ModConfig.VideoSaveFolder?.Value?.Trim();
			if (!string.IsNullOrEmpty(text) && TryEnsureWritableDir(text))
			{
				return text;
			}
			if (TryEnsureWritableDir(DefaultVideosRoot))
			{
				return DefaultVideosRoot;
			}
			string text2 = Path.Combine(FallbackPersistentRoot, "SavedVideos");
			TryEnsureWritableDir(text2);
			NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("No se pudo usar la carpeta de videos por defecto; usando respaldo seguro: '" + text2 + "'."));
			return text2;
		}

		public static string GetClipsStagingDir()
		{
			string text = ModConfig.ClipsFolder?.Value?.Trim();
			string text2 = (string.IsNullOrEmpty(text) ? Path.Combine(DefaultVideosRoot, "TempClips") : text);
			string text3 = NormalizePath(GetFinalVideoSaveDir());
			string text4 = NormalizePath(text2);
			if (string.Equals(text3, text4, StringComparison.OrdinalIgnoreCase) || text3.StartsWith(text4 + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
			{
				text2 = Path.Combine(text2, "TempClips");
			}
			if (TryEnsureWritableDir(text2))
			{
				return text2;
			}
			string text5 = Path.Combine(FallbackPersistentRoot, "TempClips");
			TryEnsureWritableDir(text5);
			NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("No se pudo crear carpeta de clips '" + text2 + "'; usando respaldo seguro: '" + text5 + "'."));
			return text5;
		}

		public static void RecordSavedVideoBanner(string fullTargetDir, string fileName)
		{
			string text = fullTargetDir.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
			_lastSavedFolderName = Path.GetFileName(text);
			if (string.IsNullOrEmpty(_lastSavedFolderName))
			{
				_lastSavedFolderName = text;
			}
			_lastSavedFileName = fileName;
			_lastSavedTime = Time.unscaledTime;
		}

		public static bool ConsumeSavedVideoBanner(out string folderName, out string fileName)
		{
			if (_lastSavedFolderName != null && Time.unscaledTime - _lastSavedTime < 1.5f)
			{
				folderName = _lastSavedFolderName;
				fileName = _lastSavedFileName ?? string.Empty;
				_lastSavedFolderName = null;
				_lastSavedFileName = null;
				return true;
			}
			folderName = string.Empty;
			fileName = string.Empty;
			return false;
		}

		public static byte GetConfiguredFps()
		{
			return (byte)Mathf.Clamp((ModConfig.CameraFps != null) ? ModConfig.CameraFps.Value : 24, 15, 60);
		}

		public static int GetConfiguredResolution()
		{
			int num = ((ModConfig.CameraResolution != null) ? ModConfig.CameraResolution.Value : 0);
			num = Mathf.Clamp(num, 0, ResolutionPresets.Length - 1);
			return ResolutionPresets[num];
		}

		public static void ApplyCameraFps()
		{
		}

		public static void ApplyCameraResolution(VideoCamera? specificCam = null)
		{
			int configuredResolution = GetConfiguredResolution();
			try
			{
				RcRenderW?.SetValue(null, configuredResolution);
				RcRenderH?.SetValue(null, configuredResolution);
				RcOutW?.SetValue(null, configuredResolution);
				RcOutH?.SetValue(null, configuredResolution);
				ResizeCapturePool(configuredResolution);
				if ((Object)(object)specificCam != (Object)null)
				{
					ResizeVideoCameraRt(specificCam, configuredResolution);
					return;
				}
				VideoCamera[] array = Object.FindObjectsByType<VideoCamera>((FindObjectsSortMode)0);
				for (int i = 0; i < array.Length; i++)
				{
					ResizeVideoCameraRt(array[i], configuredResolution);
				}
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)$"ApplyCameraResolution({configuredResolution}): {ex.Message}");
			}
		}

		private static void ResizeCapturePool(int res)
		{
			VideoCaptureSRPFeatureData data = VideoCaptureSRPFeature.Data;
			if (data == null || data.RegistrationManager == null || !(AccessTools.Field(((object)data.RegistrationManager).GetType(), "m_registeredCameras")?.GetValue(data.RegistrationManager) is Array array))
			{
				return;
			}
			FieldInfo fieldInfo = null;
			FieldInfo fieldInfo2 = null;
			bool flag = default(bool);
			for (int i = 0; i < array.Length; i++)
			{
				object value = array.GetValue(i);
				if (value == null)
				{
					continue;
				}
				if ((object)fieldInfo == null)
				{
					fieldInfo = AccessTools.Field(value.GetType(), "isValid");
				}
				if ((object)fieldInfo2 == null)
				{
					fieldInfo2 = AccessTools.Field(value.GetType(), "texturePool");
				}
				object obj = fieldInfo?.GetValue(value);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				if (((uint)num & (flag ? 1u : 0u)) != 0 || !(fieldInfo2?.GetValue(value) is YuvTextureTriplet[] array2))
				{
					continue;
				}
				for (int j = 0; j < array2.Length; j++)
				{
					YuvTextureTriplet val = array2[j];
					int num2 = res / 2;
					if (val == null || !((Object)(object)val.Y != (Object)null) || ((Texture)val.Y).width != res || ((Texture)val.Y).height != res || !((Object)(object)val.U != (Object)null) || ((Texture)val.U).width != num2 || ((Texture)val.U).height != num2 || !((Object)(object)val.V != (Object)null) || ((Texture)val.V).width != num2 || ((Texture)val.V).height != num2)
					{
						if (val != null)
						{
							ReleaseRt(val.Y);
							ReleaseRt(val.U);
							ReleaseRt(val.V);
						}
						array2[j] = CreateSizedTriplet(res);
					}
				}
			}
		}

		internal static YuvTextureTriplet CreateSizedTriplet(int res)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			//IL_0010: Expected O, but got Unknown
			YuvTextureTriplet val = new YuvTextureTriplet(res, res);
			EnsureChromaSize(val, res, res);
			return val;
		}

		internal static void EnsureChromaSize(YuvTextureTriplet? triplet, int width, int height)
		{
			if (triplet != null && !((Object)(object)triplet.Y == (Object)null))
			{
				int num = Math.Max(2, width / 2);
				int num2 = Math.Max(2, height / 2);
				if ((Object)(object)triplet.U == (Object)null || ((Texture)triplet.U).width != num || ((Texture)triplet.U).height != num2)
				{
					ReleaseRt(triplet.U);
					triplet.U = ClonePlaneRt(triplet.Y, num, num2);
				}
				if ((Object)(object)triplet.V == (Object)null || ((Texture)triplet.V).width != num || ((Texture)triplet.V).height != num2)
				{
					ReleaseRt(triplet.V);
					triplet.V = ClonePlaneRt(triplet.Y, num, num2);
				}
			}
		}

		private static RenderTexture ClonePlaneRt(RenderTexture templateY, int w, int h)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			RenderTextureDescriptor descriptor = templateY.descriptor;
			((RenderTextureDescriptor)(ref descriptor)).width = w;
			((RenderTextureDescriptor)(ref descriptor)).height = h;
			RenderTexture val = new RenderTexture(descriptor)
			{
				enableRandomWrite = true,
				antiAliasing = 1,
				useMipMap = false,
				autoGenerateMips = false
			};
			val.Create();
			return val;
		}

		private static void ResizeVideoCameraRt(VideoCamera? cam, int res)
		{
			if ((Object)(object)cam == (Object)null || cam.recording)
			{
				return;
			}
			object? obj = CamCameraField?.GetValue(cam);
			Camera val = (Camera)((obj is Camera) ? obj : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			RenderTexture targetTexture = val.targetTexture;
			if (!((Object)(object)targetTexture != (Object)null) || ((Texture)targetTexture).width != res || ((Texture)targetTexture).height != res)
			{
				CamCreateRtMethod?.Invoke(cam, null);
				if ((Object)(object)targetTexture != (Object)null && (Object)(object)val.targetTexture != (Object)(object)targetTexture)
				{
					ReleaseRt(targetTexture);
				}
			}
		}

		private static void ReleaseRt(RenderTexture? rt)
		{
			if ((Object)(object)rt == (Object)null)
			{
				return;
			}
			try
			{
				if (rt.IsCreated())
				{
					rt.Release();
				}
				Object.Destroy((Object)(object)rt);
			}
			catch
			{
			}
		}

		public static void ApplyVeConfig(ref ve_config cfg)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			byte configuredFps = GetConfiguredFps();
			int num = (int)(cfg.height = (cfg.width = (uint)GetConfiguredResolution()));
			cfg.fps = configuredFps;
			cfg.kf_max_dist = ((num > 420) ? (configuredFps * 2) : configuredFps);
			cfg.video_quality = (ve_video_codec_quality)0;
			cfg.num_threads = (byte)Mathf.Clamp(Environment.ProcessorCount, 2, 8);
			if (num >= 960)
			{
				cfg.cpu_used = 10;
			}
			else if (num >= 640)
			{
				cfg.cpu_used = 8;
			}
			else if (num >= 512)
			{
				cfg.cpu_used = 6;
			}
			switch ((ModConfig.CameraQuality != null) ? ModConfig.CameraQuality.Value : 0)
			{
			case 1:
				cfg.target_bitrate = 800u;
				cfg.min_quantizer = 14;
				cfg.max_quantizer = 38;
				break;
			case 2:
				cfg.target_bitrate = 1800u;
				cfg.min_quantizer = 10;
				cfg.max_quantizer = 30;
				break;
			case 3:
				cfg.target_bitrate = 3600u;
				cfg.min_quantizer = 6;
				cfg.max_quantizer = 22;
				break;
			}
		}

		public static void PickVideoSaveFolder()
		{
			string finalVideoSaveDir = GetFinalVideoSaveDir();
			string text = FolderPicker.PickFolder("Select folder for saved Content Warning videos", finalVideoSaveDir);
			if (!string.IsNullOrWhiteSpace(text))
			{
				Directory.CreateDirectory(text);
				ModConfig.VideoSaveFolder.Value = text;
				Deferred.MarkConfigDirty();
				NativeOptionsAudioVideoPlugin.Log.LogInfo((object)("Carpeta de videos guardados cambiada a: " + text));
			}
		}

		public static void PickClipsFolder()
		{
			string clipsStagingDir = GetClipsStagingDir();
			string text = FolderPicker.PickFolder("Select working folder for raw camera clips (not %TEMP%)", clipsStagingDir);
			if (!string.IsNullOrWhiteSpace(text))
			{
				string text2 = (Path.GetFileName(text.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)).Equals("TempClips", StringComparison.OrdinalIgnoreCase) ? text : Path.Combine(text, "TempClips"));
				Directory.CreateDirectory(text2);
				ModConfig.ClipsFolder.Value = text2;
				Deferred.MarkConfigDirty();
				NativeOptionsAudioVideoPlugin.Log.LogInfo((object)("Carpeta de clips cambiada a: " + text2 + " (toma efecto en la proxima partida)."));
			}
		}

		private static string NormalizePath(string p)
		{
			try
			{
				return Path.GetFullPath(p).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
			}
			catch
			{
				return p.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
			}
		}
	}
	[HarmonyPatch(typeof(VideoRecorder), "Start")]
	internal static class VideoRecorderFpsPatch
	{
		private static readonly FieldInfo? FrameTimeField = AccessTools.Field(typeof(VideoRecorder), "frameTime");

		private static void Postfix(VideoRecorder __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				byte configuredFps = CameraManager.GetConfiguredFps();
				FrameTimeField?.SetValue(__instance, 1f / (float)(int)configuredFps);
			}
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	internal static class LibVeEncoderFpsPatch
	{
		private static void Prefix(ref byte framerate)
		{
			framerate = CameraManager.GetConfiguredFps();
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	internal static class YuvTextureTripletChromaFixPatch
	{
		private static void Postfix(YuvTextureTriplet __instance, int textureWidth, int textureHeight)
		{
			CameraManager.EnsureChromaSize(__instance, textureWidth, textureHeight);
		}
	}
	[HarmonyPatch(typeof(LibVEInitializer), "GetNewVeConfig")]
	internal static class LibVeConfigFpsPatch
	{
		private static void Postfix(ref ve_config __result)
		{
			CameraManager.ApplyVeConfig(ref __result);
		}
	}
	[HarmonyPatch(typeof(RecordingsHandler), "GetDirectory")]
	internal static class RecordingsHandlerDirectoryPatch
	{
		private static bool Prefix(ref string __result)
		{
			if (ModConfig.UseCustomClipsFolder == null || !ModConfig.UseCustomClipsFolder.Value)
			{
				return true;
			}
			__result = CameraManager.GetClipsStagingDir();
			return false;
		}
	}
	[HarmonyPatch(typeof(RecordingsHandler), "DeleteDirectory")]
	internal static class RecordingsHandlerKeepClipsPatch
	{
		private static bool Prefix(DirectoryInfo directory)
		{
			if (directory == null)
			{
				return false;
			}
			if (ModConfig.KeepClipsOnExit != null && ModConfig.KeepClipsOnExit.Value)
			{
				NativeOptionsAudioVideoPlugin.Log.LogInfo((object)("Conservando carpeta de clips: " + directory.FullName));
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(CameraRecording), "SaveToDesktop")]
	internal static class CameraRecordingSavePatch
	{
		private static bool Prefix(CameraRecording __instance, out string videoFileName, ref bool __result)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			videoFileName = string.Empty;
			if (ModConfig.UseCustomVideoSaveFolder == null || !ModConfig.UseCustomVideoSaveFolder.Value)
			{
				return true;
			}
			if ((Object)(object)__instance == (Object)null)
			{
				__result = false;
				return false;
			}
			try
			{
				string text = default(string);
				if (!RecordingsHandler.TryGetRecordingPath(__instance.videoHandle, ref text) || string.IsNullOrEmpty(text) || !File.Exists(text))
				{
					NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("SaveToDesktop: archivo origen no encontrado ('" + text + "')."));
					__result = false;
					return false;
				}
				string finalVideoSaveDir = CameraManager.GetFinalVideoSaveDir();
				string text2 = (ModConfig.TimestampVideoNames.Value ? $"CW_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}" : ("content_warning_" + GuidExtensions.ToShortString(__instance.videoHandle.id)));
				string text3 = Path.Combine(finalVideoSaveDir, text2 + ".webm");
				int num = 1;
				while (ModConfig.TimestampVideoNames.Value && File.Exists(text3))
				{
					text3 = Path.Combine(finalVideoSaveDir, $"{text2}_{num++}.webm");
				}
				File.Copy(text, text3, overwrite: true);
				videoFileName = Path.GetFileName(text3);
				CameraManager.RecordSavedVideoBanner(finalVideoSaveDir, videoFileName);
				__result = true;
				NativeOptionsAudioVideoPlugin.Log.LogInfo((object)("Video guardado en: " + text3));
				return false;
			}
			catch (Exception arg)
			{
				NativeOptionsAudioVideoPlugin.Log.LogError((object)$"Error guardando video en carpeta personalizada: {arg}");
				__result = false;
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(Modal), "Show", new Type[]
	{
		typeof(string),
		typeof(string),
		typeof(ModalOption[]),
		typeof(Action)
	})]
	internal static class SaveVideoModalTextPatch
	{
		private static void Prefix(ref string __1)
		{
			if (CameraManager.ConsumeSavedVideoBanner(out string folderName, out string fileName))
			{
				__1 = "Video saved in '" + folderName + "':\n" + fileName;
			}
		}
	}
	[HarmonyPatch(typeof(VideoCamera), "StartRecording", new Type[] { typeof(Clip) })]
	internal static class VideoCameraRecordingPatch
	{
		private static readonly FieldInfo? BleepField = AccessTools.Field(typeof(VideoCamera), "bleepInterval");

		private static readonly FieldInfo? FrameTimeField = AccessTools.Field(typeof(VideoRecorder), "frameTime");

		private static void Prefix(VideoCamera __instance)
		{
			if ((Object)(object)__instance != (Object)null)
			{
				CameraManager.ApplyCameraResolution(__instance);
			}
		}

		private static void Postfix(VideoCamera __instance, Clip clip)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			try
			{
				BleepField?.SetValue(__instance, ModConfig.CameraBleepInterval.Value);
				VideoRecorder val = ((clip != null) ? clip.GetRecorder() : null);
				if ((Object)(object)val != (Object)null)
				{
					val.m_recordMicrophone = ModConfig.CameraRecordMic.Value;
					FrameTimeField?.SetValue(val, 1f / (float)(int)CameraManager.GetConfiguredFps());
				}
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("VideoCamera.StartRecording postfix: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(VideoCamera), "StopRecording")]
	internal static class VideoCameraStopCleanupPatch
	{
		private static readonly FieldInfo? ClipField = AccessTools.Field(typeof(VideoCamera), "m_clip");

		private static readonly FieldInfo? ContentBufField = AccessTools.Field(typeof(VideoCamera), "contentBuffer");

		private static readonly FieldInfo? CamField = AccessTools.Field(typeof(VideoCamera), "m_camera");

		private static bool Prefix(VideoCamera __instance)
		{
			if (ModConfig.SafeRecorderCleanup == null || !ModConfig.SafeRecorderCleanup.Value || (Object)(object)__instance == (Object)null)
			{
				return true;
			}
			try
			{
				object? obj = ClipField?.GetValue(__instance);
				object? obj2 = ((obj is Clip) ? obj : null);
				VideoRecorder val = ((obj2 != null) ? ((Clip)obj2).GetRecorder() : null);
				object obj3 = ContentBufField?.GetValue(__instance);
				object? obj4 = CamField?.GetValue(__instance);
				Camera val2 = (Camera)((obj4 is Camera) ? obj4 : null);
				RecorderAudioListener instance = Singleton<RecorderAudioListener>.Instance;
				if (obj2 != null && (Object)(object)val != (Object)null && obj3 != null && (Object)(object)val2 != (Object)null && (Object)(object)instance != (Object)null)
				{
					return true;
				}
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)"VideoCamera.StopRecording: se detecto referencia nula, aplicando limpieza segura anti-crash.");
				ContentBufField?.SetValue(__instance, null);
				if ((Object)(object)val2 != (Object)null && !((ItemInstanceBehaviour)__instance).isHeldByMe)
				{
					((Component)val2).gameObject.SetActive(false);
				}
				if ((Object)(object)val != (Object)null)
				{
					val.m_record = false;
					if ((Object)(object)instance != (Object)null)
					{
						instance.RemoveRecorder(val);
					}
				}
				return false;
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("VideoCamera.StopRecording safe prefix: " + ex.Message));
				return true;
			}
		}

		private static Exception? Finalizer(Exception? __exception, VideoCamera __instance)
		{
			if (__exception == null || ModConfig.SafeRecorderCleanup == null || !ModConfig.SafeRecorderCleanup.Value)
			{
				return __exception;
			}
			NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("VideoCamera.StopRecording atrapo excepcion para evitar crash: " + __exception.Message));
			try
			{
				object? obj = ClipField?.GetValue(__instance);
				object? obj2 = ((obj is Clip) ? obj : null);
				VideoRecorder val = ((obj2 != null) ? ((Clip)obj2).GetRecorder() : null);
				if ((Object)(object)val != (Object)null)
				{
					val.m_record = false;
					RecorderAudioListener instance = Singleton<RecorderAudioListener>.Instance;
					if (instance != null)
					{
						instance.RemoveRecorder(val);
					}
				}
			}
			catch
			{
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(VideoCamera), "OnDestroy")]
	internal static class VideoCameraOnDestroyPatch
	{
		private static readonly FieldInfo? ClipField = AccessTools.Field(typeof(VideoCamera), "m_clip");

		private static void Prefix(VideoCamera __instance)
		{
			if (ModConfig.SafeRecorderCleanup == null || !ModConfig.SafeRecorderCleanup.Value || (Object)(object)__instance == (Object)null)
			{
				return;
			}
			try
			{
				object? obj = ClipField?.GetValue(__instance);
				object? obj2 = ((obj is Clip) ? obj : null);
				VideoRecorder val = ((obj2 != null) ? ((Clip)obj2).GetRecorder() : null);
				if ((Object)(object)val != (Object)null)
				{
					val.m_record = false;
					if ((Object)(object)Singleton<RecorderAudioListener>.Instance != (Object)null)
					{
						Singleton<RecorderAudioListener>.Instance.RemoveRecorder(val);
					}
				}
			}
			catch
			{
			}
		}
	}
	internal static class Deferred
	{
		private const float Delay = 0.4f;

		private static float _deadline = -1f;

		private static bool _graphics;

		private static bool _cfgDirty;

		private static MaxFramerateSetting? _fps;

		internal static bool FlushingFps;

		public static void RequestGraphics()
		{
			_graphics = true;
			_cfgDirty = true;
			Bump();
		}

		public static void RequestFps(MaxFramerateSetting s)
		{
			_fps = s;
			Bump();
		}

		public static void MarkConfigDirty()
		{
			_cfgDirty = true;
			Bump();
		}

		private static void Bump()
		{
			_deadline = Time.unscaledTime + 0.4f;
		}

		public static void Tick()
		{
			if (!(_deadline < 0f) && !(Time.unscaledTime < _deadline))
			{
				_deadline = -1f;
				Flush();
			}
		}

		public static void Flush()
		{
			if (_graphics)
			{
				_graphics = false;
				GraphicsManager.Apply();
			}
			if (_fps != null)
			{
				MaxFramerateSetting fps = _fps;
				_fps = null;
				FlushingFps = true;
				try
				{
					((Setting)fps).ApplyValue();
				}
				catch (Exception ex)
				{
					NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("FPS diferido: " + ex.Message));
				}
				finally
				{
					FlushingFps = false;
				}
			}
			if (_cfgDirty)
			{
				_cfgDirty = false;
				NativeOptionsAudioVideoPlugin.Instance.SaveConfigNow();
			}
		}
	}
	internal static class FolderPicker
	{
		[ComImport]
		[Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
		[ClassInterface(ClassInterfaceType.None)]
		private class FileOpenDialogRCW
		{
		}

		[ComImport]
		[Guid("42f85136-db7e-439c-85f1-e4075d135fc8")]
		[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
		private interface IFileOpenDialog
		{
			[PreserveSig]
			int Show(IntPtr hwndOwner);

			void SetFileTypes(uint cFileTypes, IntPtr rgFilterSpec);

			void SetFileTypeIndex(uint iFileType);

			void GetFileTypeIndex(out uint piFileType);

			void Advise(IntPtr pfde, out uint pdwCookie);

			void Unadvise(uint dwCookie);

			void SetOptions(uint fos);

			void GetOptions(out uint pfos);

			void SetDefaultFolder(IShellItem psi);

			void SetFolder(IShellItem psi);

			void GetFolder(out IShellItem ppsi);

			void GetCurrentSelection(out IShellItem ppsi);

			void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);

			void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);

			void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);

			void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);

			void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);

			void GetResult(out IShellItem ppsi);

			void AddPlace(IShellItem psi, int fdap);

			void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);

			void Close(int hr);

			void SetClientGuid(ref Guid guid);

			void ClearClientData();

			void SetFilter(IntPtr pFilter);

			void GetResults(out IntPtr ppenum);

			void GetSelectedItems(out IntPtr ppsai);
		}

		[ComImport]
		[Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")]
		[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
		private interface IShellItem
		{
			void BindToHandler(IntPtr pbc, ref Guid bhid, ref Guid riid, out IntPtr ppv);

			void GetParent(out IShellItem ppsi);

			void GetDisplayName(uint sigdnName, out IntPtr ppszName);

			void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);

			void Compare(IShellItem psi, uint hint, out int piOrder);
		}

		private const uint FOS_PICKFOLDERS = 32u;

		private const uint FOS_FORCEFILESYSTEM = 64u;

		private const uint FOS_NOCHANGEDIR = 8u;

		private const uint SIGDN_FILESYSPATH = 2147844096u;

		public static string? PickFolder(string title, string? initialDir = null)
		{
			IFileOpenDialog fileOpenDialog = null;
			IShellItem ppv = null;
			IShellItem ppsi = null;
			IntPtr ppszName = IntPtr.Zero;
			try
			{
				fileOpenDialog = (IFileOpenDialog)new FileOpenDialogRCW();
				fileOpenDialog.GetOptions(out var pfos);
				fileOpenDialog.SetOptions(pfos | 0x20 | 0x40 | 8);
				fileOpenDialog.SetTitle(title);
				if (!string.IsNullOrWhiteSpace(initialDir) && Directory.Exists(initialDir))
				{
					Guid riid = typeof(IShellItem).GUID;
					if (SHCreateItemFromParsingName(initialDir, IntPtr.Zero, ref riid, out ppv) == 0 && ppv != null)
					{
						fileOpenDialog.SetFolder(ppv);
					}
				}
				IntPtr activeWindow = GetActiveWindow();
				if (fileOpenDialog.Show(activeWindow) != 0)
				{
					return null;
				}
				fileOpenDialog.GetResult(out ppsi);
				if (ppsi == null)
				{
					return null;
				}
				ppsi.GetDisplayName(2147844096u, out ppszName);
				return (ppszName != IntPtr.Zero) ? Marshal.PtrToStringUni(ppszName) : null;
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("FolderPicker error: " + ex.Message));
				return null;
			}
			finally
			{
				if (ppszName != IntPtr.Zero)
				{
					Marshal.FreeCoTaskMem(ppszName);
				}
				if (ppsi != null)
				{
					Marshal.ReleaseComObject(ppsi);
				}
				if (ppv != null)
				{
					Marshal.ReleaseComObject(ppv);
				}
				if (fileOpenDialog != null)
				{
					Marshal.ReleaseComObject(fileOpenDialog);
				}
			}
		}

		[DllImport("user32.dll")]
		private static extern IntPtr GetActiveWindow();

		[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
		private static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
	}
	internal static class GpuMonitor
	{
		private enum Backend
		{
			None,
			AmdAdl,
			NvidiaNvml
		}

		private delegate IntPtr AdlAllocDelegate(int size);

		private struct AdapterInfo
		{
			public int iSize;

			public int iAdapterIndex;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string strUDID;

			public int iBusNumber;

			public int iDeviceNumber;

			public int iFunctionNumber;

			public int iVendorID;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string strAdapterName;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string strDisplayName;

			public int iPresent;

			public int iExist;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string strDriverPath;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string strDriverPathExt;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string strPNPString;

			public int iOSDisplayIndex;
		}

		private struct ADLSingleSensorData
		{
			public int supported;

			public int value;
		}

		private struct ADLPMLogDataOutput
		{
			public int size;

			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
			public ADLSingleSensorData[] sensors;
		}

		private struct NvmlUtilization
		{
			public uint gpu;

			public uint memory;
		}

		private struct NvmlTemperature
		{
			public uint version;

			public uint sensorType;

			public int temperature;
		}

		private static Backend _backend = Backend.None;

		private static bool _initialized;

		private static Timer? _timer;

		public static volatile bool Available;

		public static volatile int UsagePercent;

		public static volatile int TempCelsius;

		private static readonly AdlAllocDelegate AdlAllocCallback = (int size) => Marshal.AllocHGlobal(size);

		private static IntPtr _adlContext;

		private static int _adlAdapterIndex = -1;

		private static IntPtr _nvmlDevice;

		private static bool _nvmlUseTempV;

		public static void EnsureStarted()
		{
			if (_initialized)
			{
				return;
			}
			_initialized = true;
			try
			{
				string text = SystemInfo.graphicsDeviceVendor ?? string.Empty;
				string text2 = SystemInfo.graphicsDeviceName ?? string.Empty;
				if (text.IndexOf("NVIDIA", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("NVIDIA", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("GeForce", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("RTX", StringComparison.OrdinalIgnoreCase) >= 0 || text2.IndexOf("GTX", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					if (TryInitNvidia(text2))
					{
						_backend = Backend.NvidiaNvml;
					}
					else if (TryInitAmd())
					{
						_backend = Backend.AmdAdl;
					}
				}
				else if (TryInitAmd())
				{
					_backend = Backend.AmdAdl;
				}
				else if (TryInitNvidia(text2))
				{
					_backend = Backend.NvidiaNvml;
				}
				if (_backend != Backend.None)
				{
					PollOnce(null);
					_timer = new Timer(PollOnce, null, 1000, 1000);
					NativeOptionsAudioVideoPlugin.Log.LogInfo((object)$"GpuMonitor activo ({_backend} | '{text2}').");
					return;
				}
				NativeOptionsAudioVideoPlugin.Log.LogInfo((object)("GpuMonitor: sin sensores disponibles para '" + text2 + "' (" + text + "). Mostrando FPS + ms."));
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("GpuMonitor init: " + ex.Message));
				_backend = Backend.None;
			}
		}

		public static void Shutdown()
		{
			try
			{
				_timer?.Dispose();
			}
			catch
			{
			}
			_timer = null;
			try
			{
				if (_backend == Backend.AmdAdl && _adlContext != IntPtr.Zero)
				{
					ADL2_Main_Control_Destroy(_adlContext);
					_adlContext = IntPtr.Zero;
				}
				else if (_backend == Backend.NvidiaNvml)
				{
					nvmlShutdown();
				}
			}
			catch
			{
			}
			_backend = Backend.None;
			Available = false;
			_initialized = false;
		}

		private static bool TryInitAmd()
		{
			try
			{
				if (ADL2_Main_Control_Create(AdlAllocCallback, 1, out var context) != 0 || context == IntPtr.Zero)
				{
					return false;
				}
				if (ADL2_Adapter_NumberOfAdapters_Get(context, out var numAdapters) != 0 || numAdapters <= 0)
				{
					ADL2_Main_Control_Destroy(context);
					return false;
				}
				int num = Marshal.SizeOf<AdapterInfo>();
				IntPtr intPtr = Marshal.AllocHGlobal(num * numAdapters);
				int num2 = -1;
				int num3 = -1;
				try
				{
					if (ADL2_Adapter_AdapterInfo_Get(context, intPtr, num * numAdapters) == 0)
					{
						for (int i = 0; i < numAdapters; i++)
						{
							AdapterInfo adapterInfo = Marshal.PtrToStructure<AdapterInfo>(IntPtr.Add(intPtr, i * num));
							if ((adapterInfo.iVendorID != 1002 && adapterInfo.iVendorID != 4098) || ADL2_New_QueryPMLogData_Get(context, adapterInfo.iAdapterIndex, out var lpPMLogDataOutput) != 0 || lpPMLogDataOutput.sensors == null)
							{
								continue;
							}
							bool flag = lpPMLogDataOutput.sensors[8].supported != 0;
							bool flag2 = lpPMLogDataOutput.sensors[19].supported != 0;
							if (flag || flag2)
							{
								int num4 = (flag ? 2 : 0) + (flag2 ? 2 : 0);
								string text = adapterInfo.strAdapterName ?? "";
								if (text.IndexOf("RX ", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("XT", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("PRO", StringComparison.OrdinalIgnoreCase) >= 0)
								{
									num4 += 10;
								}
								if (num4 > num3)
								{
									num3 = num4;
									num2 = adapterInfo.iAdapterIndex;
								}
							}
						}
					}
				}
				finally
				{
					Marshal.FreeHGlobal(intPtr);
				}
				if (num2 < 0)
				{
					ADL2_Main_Control_Destroy(context);
					return false;
				}
				_adlContext = context;
				_adlAdapterIndex = num2;
				return true;
			}
			catch
			{
				return false;
			}
		}

		private static bool PreloadNvmlDll()
		{
			if (LoadLibrary("nvml.dll") != IntPtr.Zero)
			{
				return true;
			}
			string text = Path.Combine(Environment.SystemDirectory, "nvml.dll");
			if (File.Exists(text) && LoadLibrary(text) != IntPtr.Zero)
			{
				return true;
			}
			string text2 = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "NVIDIA Corporation", "NVSMI", "nvml.dll");
			if (File.Exists(text2) && LoadLibrary(text2) != IntPtr.Zero)
			{
				return true;
			}
			return false;
		}

		private static bool TryInitNvidia(string expectedGpuName)
		{
			try
			{
				if (!PreloadNvmlDll())
				{
					return false;
				}
				int num = nvmlInit_v2();
				if (num != 0)
				{
					num = nvmlInit();
				}
				if (num != 0)
				{
					NativeOptionsAudioVideoPlugin.Log.LogWarning((object)$"GpuMonitor NVML init fallo (rc={num}).");
					return false;
				}
				uint num2 = 1u;
				if (nvmlDeviceGetCount_v2(out var deviceCount) == 0 && deviceCount != 0)
				{
					num2 = deviceCount;
				}
				IntPtr intPtr = IntPtr.Zero;
				StringBuilder stringBuilder = new StringBuilder(96);
				for (uint num3 = 0u; num3 < num2; num3++)
				{
					if (nvmlDeviceGetHandleByIndex_v2(num3, out var device) != 0 || device == IntPtr.Zero)
					{
						continue;
					}
					if (intPtr == IntPtr.Zero)
					{
						intPtr = device;
					}
					if (string.IsNullOrEmpty(expectedGpuName))
					{
						continue;
					}
					stringBuilder.Clear();
					if (nvmlDeviceGetName(device, stringBuilder, (uint)stringBuilder.Capacity) == 0)
					{
						string text = stringBuilder.ToString();
						if (expectedGpuName.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf(expectedGpuName, StringComparison.OrdinalIgnoreCase) >= 0)
						{
							intPtr = device;
							break;
						}
					}
				}
				if (intPtr == IntPtr.Zero)
				{
					nvmlShutdown();
					return false;
				}
				_nvmlDevice = intPtr;
				_nvmlUseTempV = false;
				return true;
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("GpuMonitor NVML: " + ex.Message));
				return false;
			}
		}

		private static void PollOnce(object? _)
		{
			try
			{
				if (_backend == Backend.AmdAdl && _adlContext != IntPtr.Zero && _adlAdapterIndex >= 0)
				{
					if (ADL2_New_QueryPMLogData_Get(_adlContext, _adlAdapterIndex, out var lpPMLogDataOutput) == 0 && lpPMLogDataOutput.sensors != null)
					{
						if (lpPMLogDataOutput.sensors[8].supported != 0)
						{
							TempCelsius = lpPMLogDataOutput.sensors[8].value;
						}
						if (lpPMLogDataOutput.sensors[19].supported != 0)
						{
							UsagePercent = lpPMLogDataOutput.sensors[19].value;
						}
						Available = lpPMLogDataOutput.sensors[8].supported != 0 || lpPMLogDataOutput.sensors[19].supported != 0;
					}
				}
				else
				{
					if (_backend != Backend.NvidiaNvml || !(_nvmlDevice != IntPtr.Zero))
					{
						return;
					}
					bool available = false;
					if (!_nvmlUseTempV && nvmlDeviceGetTemperature(_nvmlDevice, 0u, out var temp) == 0)
					{
						TempCelsius = (int)temp;
						available = true;
					}
					else
					{
						NvmlTemperature temp2 = new NvmlTemperature
						{
							version = 16777228u,
							sensorType = 0u,
							temperature = 0
						};
						try
						{
							if (nvmlDeviceGetTemperatureV(_nvmlDevice, ref temp2) == 0)
							{
								_nvmlUseTempV = true;
								TempCelsius = temp2.temperature;
								available = true;
							}
						}
						catch
						{
						}
					}
					if (nvmlDeviceGetUtilizationRates(_nvmlDevice, out var utilization) == 0)
					{
						UsagePercent = (int)utilization.gpu;
						available = true;
					}
					Available = available;
				}
			}
			catch
			{
			}
		}

		[DllImport("atiadlxx.dll")]
		private static extern int ADL2_Main_Control_Create(AdlAllocDelegate cb, int enumConnectedAdapters, out IntPtr context);

		[DllImport("atiadlxx.dll")]
		private static extern int ADL2_Main_Control_Destroy(IntPtr context);

		[DllImport("atiadlxx.dll")]
		private static extern int ADL2_Adapter_NumberOfAdapters_Get(IntPtr context, out int numAdapters);

		[DllImport("atiadlxx.dll")]
		private static extern int ADL2_Adapter_AdapterInfo_Get(IntPtr context, IntPtr lpInfo, int iInputSize);

		[DllImport("atiadlxx.dll")]
		private static extern int ADL2_New_QueryPMLogData_Get(IntPtr context, int iAdapterIndex, out ADLPMLogDataOutput lpPMLogDataOutput);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		private static extern IntPtr LoadLibrary(string lpFileName);

		[DllImport("nvml.dll")]
		private static extern int nvmlInit_v2();

		[DllImport("nvml.dll")]
		private static extern int nvmlInit();

		[DllImport("nvml.dll")]
		private static extern int nvmlShutdown();

		[DllImport("nvml.dll")]
		private static extern int nvmlDeviceGetCount_v2(out uint deviceCount);

		[DllImport("nvml.dll")]
		private static extern int nvmlDeviceGetHandleByIndex_v2(uint index, out IntPtr device);

		[DllImport("nvml.dll", CharSet = CharSet.Ansi)]
		private static extern int nvmlDeviceGetName(IntPtr device, StringBuilder name, uint length);

		[DllImport("nvml.dll")]
		private static extern int nvmlDeviceGetTemperature(IntPtr device, uint sensorType, out uint temp);

		[DllImport("nvml.dll")]
		private static extern int nvmlDeviceGetTemperatureV(IntPtr device, ref NvmlTemperature temp);

		[DllImport("nvml.dll")]
		private static extern int nvmlDeviceGetUtilizationRates(IntPtr device, out NvmlUtilization utilization);
	}
	internal static class GraphicsManager
	{
		private static readonly int[] MsaaSamples = new int[4] { 1, 2, 4, 8 };

		private static bool _sceneDefaultFog;

		private static bool _hasSceneFog;

		private static bool _shadowsDisabledByUs;

		private static bool _applyingShadowsFromNative;

		private static bool _applyingPreset;

		private static float _baseNativeShadowDistance = 75f;

		private static int _baseNativeShadowCascades = 1;

		internal static bool IsApplyingPreset => _applyingPreset;

		public static void OnSceneLoaded()
		{
			_sceneDefaultFog = RenderSettings.fog;
			_hasSceneFog = true;
			Apply();
		}

		public static void MarkManualGraphicsChange()
		{
			if (!_applyingPreset && ModConfig.GraphicsPreset != null && ModConfig.GraphicsPreset.Value != 0)
			{
				ModConfig.GraphicsPreset.Value = 0;
			}
		}

		public static void ApplyPreset(int preset)
		{
			if (preset <= 0 || _applyingPreset)
			{
				return;
			}
			_applyingPreset = true;
			try
			{
				switch (preset)
				{
				case 1:
					ModConfig.RenderScale.Value = 1f;
					ModConfig.UseFsr1.Value = false;
					ModConfig.FsrSharpness.Value = 0.8f;
					ModConfig.DisableShadows.Value = false;
					ModConfig.ShadowDistanceScale.Value = 1f;
					ModConfig.MaxAdditionalLights.Value = 8;
					ModConfig.MsaaMode.Value = 2;
					ModConfig.MipmapLimit.Value = 0;
					ModConfig.DisableFog.Value = false;
					break;
				case 2:
					ModConfig.RenderScale.Value = 0.85f;
					ModConfig.UseFsr1.Value = true;
					ModConfig.FsrSharpness.Value = 0.92f;
					ModConfig.DisableShadows.Value = false;
					ModConfig.ShadowDistanceScale.Value = 0.75f;
					ModConfig.MaxAdditionalLights.Value = 4;
					ModConfig.MsaaMode.Value = 1;
					ModConfig.MipmapLimit.Value = 0;
					ModConfig.DisableFog.Value = false;
					break;
				case 3:
					ModConfig.RenderScale.Value = 0.65f;
					ModConfig.UseFsr1.Value = true;
					ModConfig.FsrSharpness.Value = 1.1f;
					ModConfig.DisableShadows.Value = true;
					ModConfig.ShadowDistanceScale.Value = 0.25f;
					ModConfig.MaxAdditionalLights.Value = 1;
					ModConfig.MsaaMode.Value = 0;
					ModConfig.MipmapLimit.Value = 1;
					ModConfig.DisableFog.Value = true;
					break;
				}
				Deferred.MarkConfigDirty();
				Apply();
				RefreshGraphicsTabIfOpen();
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)$"ApplyPreset({preset}): {ex.Message}");
			}
			finally
			{
				_applyingPreset = false;
			}
		}

		private static void RefreshGraphicsTabIfOpen()
		{
			try
			{
				SettingsMenu instance = Singleton<SettingsMenu>.Instance;
				if ((Object)(object)instance != (Object)null && ((Behaviour)instance).isActiveAndEnabled && ((Component)instance).gameObject.activeInHierarchy)
				{
					instance.SelectCategory((SettingCategory)0);
				}
			}
			catch
			{
			}
		}

		public static void OnNativeShadowQualityApplied()
		{
			if (!_applyingShadowsFromNative)
			{
				RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
				UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
				if (val != null)
				{
					_baseNativeShadowDistance = val.shadowDistance;
					_baseNativeShadowCascades = val.shadowCascadeCount;
				}
				ApplyShadowCoordination();
			}
		}

		public static void Apply()
		{
			if (ModConfig.EnableVideoTweaks == null || !ModConfig.EnableVideoTweaks.Value)
			{
				return;
			}
			try
			{
				QualitySettings.vSyncCount = (ModConfig.VSync.Value ? 1 : 0);
				QualitySettings.globalTextureMipmapLimit = Mathf.Clamp(ModConfig.MipmapLimit.Value, 0, 3);
				if (ModConfig.DisableFog.Value)
				{
					RenderSettings.fog = false;
				}
				else if (_hasSceneFog)
				{
					RenderSettings.fog = _sceneDefaultFog;
				}
				RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
				UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
				if (val != null)
				{
					val.renderScale = Mathf.Clamp(ModConfig.RenderScale.Value, 0.5f, 1f);
					if (ModConfig.UseFsr1.Value)
					{
						val.upscalingFilter = (UpscalingFilterSelection)3;
						val.fsrOverrideSharpness = true;
						val.fsrSharpness = Mathf.Clamp(ModConfig.FsrSharpness.Value, 0f, 2f);
					}
					else
					{
						val.upscalingFilter = (UpscalingFilterSelection)0;
						val.fsrOverrideSharpness = false;
					}
					int num = Mathf.Clamp(ModConfig.MsaaMode.Value, 0, MsaaSamples.Length - 1);
					int num2 = (val.msaaSampleCount = MsaaSamples[num]);
					QualitySettings.antiAliasing = ((num2 > 1) ? num2 : 0);
					val.maxAdditionalLightsCount = Mathf.Clamp(ModConfig.MaxAdditionalLights.Value, 0, 8);
				}
				ApplyCameraAntiAliasing();
				ApplyShadowCoordination();
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("GraphicsManager.Apply: " + ex.Message));
			}
		}

		internal static void ApplyCameraAntiAliasing(Camera? targetCam = null)
		{
			if (ModConfig.EnableVideoTweaks == null || !ModConfig.EnableVideoTweaks.Value)
			{
				return;
			}
			Camera val = (Camera)(((Object)(object)targetCam != (Object)null) ? ((object)targetCam) : ((object)(((Object)(object)MainCamera.instance != (Object)null) ? MainCamera.instance.Cam : null)));
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			int num = Mathf.Clamp((ModConfig.MsaaMode == null) ? 1 : ModConfig.MsaaMode.Value, 0, MsaaSamples.Length - 1);
			val.allowMSAA = num > 0;
			UniversalAdditionalCameraData universalAdditionalCameraData = CameraExtensions.GetUniversalAdditionalCameraData(val);
			if (!((Object)(object)universalAdditionalCameraData == (Object)null))
			{
				switch (num)
				{
				case 0:
					universalAdditionalCameraData.antialiasing = (AntialiasingMode)0;
					break;
				case 1:
					universalAdditionalCameraData.antialiasing = (AntialiasingMode)1;
					break;
				case 2:
					universalAdditionalCameraData.antialiasing = (AntialiasingMode)2;
					universalAdditionalCameraData.antialiasingQuality = (AntialiasingQuality)1;
					break;
				default:
					universalAdditionalCameraData.antialiasing = (AntialiasingMode)2;
					universalAdditionalCameraData.antialiasingQuality = (AntialiasingQuality)2;
					break;
				}
			}
		}

		private static void ApplyShadowCoordination()
		{
			RenderPipelineAsset currentRenderPipeline = GraphicsSettings.currentRenderPipeline;
			UniversalRenderPipelineAsset val = (UniversalRenderPipelineAsset)(object)((currentRenderPipeline is UniversalRenderPipelineAsset) ? currentRenderPipeline : null);
			if (val == null)
			{
				return;
			}
			if (ModConfig.DisableShadows.Value)
			{
				if (!_shadowsDisabledByUs && val.shadowDistance > 1f)
				{
					_baseNativeShadowDistance = val.shadowDistance;
					_baseNativeShadowCascades = val.shadowCascadeCount;
				}
				_shadowsDisabledByUs = true;
				QualitySettings.shadows = (ShadowQuality)0;
				val.shadowDistance = 0f;
				val.shadowCascadeCount = 1;
				return;
			}
			if (_shadowsDisabledByUs)
			{
				_shadowsDisabledByUs = false;
				QualitySettings.shadows = (ShadowQuality)2;
				GameHandler instance = GameHandler.Instance;
				object obj;
				if (instance == null)
				{
					obj = null;
				}
				else
				{
					SettingsHandler settingsHandler = instance.SettingsHandler;
					obj = ((settingsHandler != null) ? settingsHandler.GetSetting<ShadowQualitySetting>() : null);
				}
				ShadowQualitySetting val2 = (ShadowQualitySetting)obj;
				if (val2 != null)
				{
					_applyingShadowsFromNative = true;
					try
					{
						((Setting)val2).ApplyValue();
						_baseNativeShadowDistance = val.shadowDistance;
						_baseNativeShadowCascades = val.shadowCascadeCount;
					}
					finally
					{
						_applyingShadowsFromNative = false;
					}
				}
				else
				{
					val.shadowDistance = _baseNativeShadowDistance;
					val.shadowCascadeCount = Mathf.Clamp(_baseNativeShadowCascades, 1, 4);
				}
			}
			float num = Mathf.Clamp(ModConfig.ShadowDistanceScale.Value, 0.25f, 1f);
			if (_baseNativeShadowDistance > 1f)
			{
				val.shadowDistance = _baseNativeShadowDistance * num;
			}
		}
	}
	[HarmonyPatch(typeof(ShadowQualitySetting), "ApplyValue")]
	internal static class ShadowQualityCoordinationPatch
	{
		private static void Postfix()
		{
			try
			{
				GraphicsManager.OnNativeShadowQualityApplied();
			}
			catch (Exception ex)
			{
				NativeOptionsAudioVideoPlugin.Log.LogWarning((object)("ShadowQuality coord: " + ex.Message));
			}
		}
	}
	[HarmonyPatch(typeof(MainCamera), "Awake")]
	internal static class MainCameraAntiAliasingPatch
	{
		private static void Postfix(MainCamera __instance)
		{
			if ((Object)(object)__instance != (Object)null && (Object)(object)__instance.Cam != (Object)null)
			{
				GraphicsManager.ApplyCameraAntiAliasing(__instance.Cam);
			}
		}
	}
	[HarmonyPatch(typeof(RenderFeatureHandler), "Start")]
	internal static class RenderFeatureHandlerStartFixPatch
	{
		private static readonly FieldInfo? HighField = AccessTools.Field(typeof(RenderFeatureHandler), "m_HighFidelity");

		private static bool Prefix(RenderFeatureHandler __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return false;
			}
			return HighField?.GetValue(__instance) != null;
		}
	}
	[HarmonyPatch(typeof(RenderFeatureHandler), "OnDisable")]
	internal static class RenderFeatureHandlerOnDisableFixPatch
	{
		private static readonly FieldInfo? JellyField = AccessTools.Field(typeof(RenderFeatureHandler), "jelly");

		private static bool Prefix(RenderFeatureHandler __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return false;
			}
			return JellyField?.GetValue(__instance) != null;
		}
	}
	internal sealed class HudOverlay : MonoBehaviour
	{
		private static HudOverlay? _instance;

		private static volatile float _pendingMicPeak;

		private static volatile float _pendingLoudPeak;

		private float _fpsSumDt;

		private int _fpsFrameCount;

		private float _fpsRefreshTimer;

		private readonly StringBuilder _sb = new StringBuilder(64);

		private float _micDisplay;

		private float _micClipHold;

		private float _loudHold;

		private GameObject _fpsPanel;

		private TMP_Text _fpsText;

		private GameObject _micPanel;

		private Image _micFill;

		private TMP_Text _micLabel;

		private GameObject _loudPanel;

		private Image _loudBg;

		private TMP_Text _loudText;

		private GameObject _mutedPanel;

		private TMP_Text _mutedText;

		private static readonly FieldRef<UserInterface, HotbarUI?> HotbarUiRef = AccessTools.FieldRefAccess<UserInterface, HotbarUI>("hotbarUI");

		private static readonly FieldRef<HotbarUI, HotbarSlotUI[]?> HotbarSlotsRef = AccessTools.FieldRefAccess<HotbarUI, HotbarSlotUI[]>("slots");

		private static readonly FieldRef<HotbarSlotUI, TextMeshProUGUI?> SlotKeybindRef = AccessTools.FieldRefAccess<HotbarSlotUI, TextMeshProUGUI>("m_keybind");

		private static readonly FieldRef<HotbarSlotUI, Image?> SlotIconRef = AccessTools.FieldRefAccess<HotbarSlotUI, Image>("m_icon");

		private GameObject? _shoulderPanel;

		private Image? _shoulderBorder;

		private TMP_Text? _shoulderLabel;

		private CurvedUITMP? _shoulderCurvedTmp;

		private HotbarUI? _shoulderAttachedHotbar;

		private Color _shoulderBaseColor = new Color(0.98f, 0.86f, 0.42f, 1f);

		private int _lastShoulderPct = -1;

		private bool _lastShoulderOn;

		private bool _lastShoulderCharging;

		private KeyCode _lastShoulderKey;

		private static readonly Color MicGreen = new Color(0.2f, 0.82f, 0.42f, 1f);

		private static readonly Color MicYellow = new Color(0.95f, 0.78f, 0.18f, 1f);

		private static readonly Color MicRed = new Color(0.95f, 0.25f, 0.22f, 1f);

		private static readonly Color ChargeCyan = new Color(0.35f, 0.92f, 0.78f, 1f);

		public static void ReportMicPeak(float peak)
		{
			if (peak > _pendingMicPeak)
			{
				_pendingMicPeak = peak;
			}
		}

		public static void ReportMasterPeak(float peak)
		{
			if (peak > _pendingLoudPeak)
			{
				_pendingLoudPeak = peak;
			}
		}

		public static void RefreshVisibility()
		{
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			bool flag = ModConfig.ShowFpsHud != null && ModConfig.ShowFpsHud.Value;
			bool flag2 = ModConfig.ShowMicMeter != null && ModConfig.ShowMicMeter.Value;
			bool flag3 = ModConfig.ShowLoudSoundAlert != null && ModConfig.ShowLoudSoundAlert.Value;
			bool flag4 = ModConfig.ShowShoulderBatteryHud != null && ModConfig.ShowShoulderBatteryHud.Value && ShoulderFlashlight.HasMounted;
			bool isMuted = MicMuteController.IsMuted;
			bool flag5 = flag || flag2 || flag3 || flag4;
			if (!flag5 && !isMuted)
			{
				if ((Object)(object)_instance != (Object)null)
				{
					_instance._fpsPanel.SetActive(false);
					_instance._micPanel.SetActive(false);
					_instance._loudPanel.SetActive(false);
					_instance._mutedPanel.SetActive(false);
					if ((Object)(object)_instance._shoulderPanel != (Object)null)
					{
						_instance._shoulderPanel.SetActive(false);
					}
					((Behaviour)_instance).enabled = false;
				}
				return;
			}
			EnsureInstance();
			if ((Object)(object)_instance == (Object)null)
			{
				return;
			}
			if (flag)
			{
				GpuMonitor.EnsureStarted();
			}
			_instance._fpsPanel.SetActive(flag);
			_instance._micPanel.SetActive(flag2);
			if (flag4)
			{
				_instance._lastShoulderPct = -1;
				_instance.EnsureShoulderBadgeAttached();
				if ((Object)(object)_instance._shoulderPanel != (Object)null)
				{
					_instance._shoulderPanel.SetActive(true);
				}
			}
			else if ((Object)(object)_instance._shoulderPanel != (Object)null)
			{
				_instance._shoulderPanel.SetActive(false);
			}
			if (!flag3)
			{
				_instance._loudPanel.SetActive(false);
			}
			_instance._mutedPanel.SetActive(isMuted);
			if (isMuted)
			{
				KeyCode val = (KeyCode)((ModConfig.MicMuteKey == null) ? 109 : ((int)ModConfig.MicMuteKey.Value));
				_instance._mutedText.SetText($"MIC MUTED [{val}]");
				((RectTransform)_instance._mutedPanel.transform).anchoredPosition = new Vector2(18f, flag2 ? 58f : 18f);
			}
			((Behaviour)_instance).enabled = flag5;
		}

		private static void EnsureInstance()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_instance != (Object)null))
			{
				GameObject val = new GameObject("CWMod_HudCanvas", new Type[1] { typeof(RectTransform) });
				Object.DontDestroyOnLoad((Object)(object)val);
				Canvas obj = val.AddComponent<Canvas>();
				obj.renderMode = (RenderMode)0;
				obj.sortingOrder = 1000;
				CanvasScaler obj2 = val.AddComponent<CanvasScaler>();
				obj2.uiScaleMode = (ScaleMode)1;
				obj2.referenceResolution = new Vector2(1920f, 1080f);
				obj2.matchWidthOrHeight = 0.5f;
				HudOverlay hudOverlay = val.AddComponent<HudOverlay>();
				hudOverlay.BuildFpsWidget(val.transform);
				hudOverlay.BuildMicWidget(val.transform);
				hudOverlay.BuildLoudAlertWidget(val.transform);
				hudOverlay.BuildMicMutedWidget(val.transform);
				_instance = hudOverlay;
			}
		}

		private void BuildFpsWidget(Transform root)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			_fpsPanel = CreatePillPanel("FpsPanel", root, new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(0f, 1f), new Vector2(16f, -16f), new Vector2(290f, 34f), new Color(0.06f, 0.07f, 0.1f, 0.78f));
			GameObject val = new GameObject("Text", new Type[1] { typeof(RectTransform) });
			val.transform.SetParent(_fpsPanel.transform, false);
			RectTransform val2 = (RectTransform)val.transform;
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.one;
			val2.offsetMin = new Vector2(12f, 0f);
			val2.offsetMax = new Vector2(-12f, 0f);
			_fpsText = (TMP_Text)(object)val.AddComponent<TextMeshProUGUI>();
			_fpsText.fontSize = 16f;
			_fpsText.fontStyle = (FontStyles)1;
			_fpsText.alignment = (TextAlignmentOptions)4097;
			((Graphic)_fpsText).color = new Color(0.92f, 0.96f, 1f, 0.96f);
			((Graphic)_fpsText).raycastTarget = false;
			_fpsText.SetText("FPS --");
			_fpsPanel.SetActive(false);
		}

		private void BuildMicWidget(Transform root)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Expected O, but got Unknown
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Expected O, but got Unknown
			//IL_029b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: Unknown result type (might be due to invalid IL or missing references)
			_micPanel = CreatePillPanel("MicPanel", root, new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(18f, 18f), new Vector2(220f, 34f), new Color(0.06f, 0.07f, 0.1f, 0.78f));
			GameObject val = new GameObject("Label", new Type[1] { typeof(RectTransform) });
			val.transform.SetParent(_micPanel.transform, false);
			RectTransform val2 = (RectTransform)val.transform;
			val2.anchorMin = new Vector2(0f, 0f);
			val2.anchorMax = new Vector2(0f, 1f);
			val2.pivot = new Vector2(0f, 0.5f);
			val2.anchoredPosition = new Vector2(10f, 0f);
			val2.sizeDelta = new Vector2(46f, 0f);
			_micLabel = (TMP_Text)(object)val.AddComponent<TextMeshProUGUI>();
			_micLabel.fontSize = 14f;
			_micLabel.fontStyle = (FontStyles)1;
			_micLabel.alignment = (TextAlignmentOptions)4097;
			((Graphic)_micLabel).color = new Color(0.9f, 0.93f, 0.98f, 1f);
			((Graphic)_micLabel).raycastTarget = false;
			_micLabel.SetText("MIC");
			GameObject val3 = new GameObject("Track", new Type[1] { typeof(RectTransform) });
			val3.transform.SetParent(_micPanel.transform, false);
			RectTransform val4 = (RectTransform)val3.transform;
			val4.anchorMin = new Vector2(0f, 0.5f);
			val4.anchorMax = new Vector2(1f, 0.5f);
			val4.offsetMin = new Vector2(58f, -6f);
			val4.offsetMax = new Vector2(-12f, 6f);
			Image obj = val3.AddComponent<Image>();
			obj.sprite = SwitchSprites.Pill;
			obj.type = (Type)1;
			((Graphic)obj).color = new Color(0.22f, 0.24f, 0.28f, 1f);
			((Graphic)obj).raycastTarget = false;
			GameObject val5 = new GameObject("Fill", new Type[1] { typeof(RectTransform) });
			val5.transform.SetParent(val3.transform, false);
			RectTransform val6 = (RectTransform)val5.transform;
			val6.anchorMin = Vector2.zero;
			val6.anchorMax = new Vector2(0f, 1f);
			val6.offsetMin = Vector2.zero;
			val6.offsetMax = Vector2.zero;
			_micFill = val5.AddComponent<Image>();
			_micFill.sprite = SwitchSprites.Pill;
			_micFill.type = (Type)1;
			((Graphic)_micFill).color = MicGreen;
			((Graphic)_micFill).raycastTarget = false;
			_micPanel.SetActive(false);
		}

		private void BuildLoudAlertWidget(Transform root)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			_loudPanel = CreatePillPanel("LoudAlertPanel", root, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, -18f), new Vector2(210f, 34f), new Color(0.85f, 0.28f, 0.14f, 0.88f));
			_loudBg = _loudPanel.GetComponent<Image>();
			GameObject val = new GameObject("Text", new Type[1] { typeof(RectTransform) });
			val.transform.SetParent(_loudPanel.transform, false);
			RectTransform val2 = (RectTransform)val.transform;
			val2.anchorMin = Vector2.zero;
			val2.anchorMax = Vector2.one;
			val2.offsetMin = Vector2.zero;
			val2.offsetMax = Vector2.zero;
			_loudText = (TMP_Text)(object)val.AddComponent<TextMeshProUGUI>();
			_loudText.fontSize = 15f;
			_loudText.fontStyle = (FontStyles)1;
			_loudText.alignment = (TextAlignmentOptions)514;
			((Graphic)_loudText).color = Color.white;
			((Graphic)_loudText).raycastTarget = false;
			_loudText.SetText("! LOUD SOUND !");
			_loudPanel.SetActive(false);
		}

		private void BuildMicMutedWidget(Transform root)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			//IL_00b0: U