Decompiled source of AirportMicFix v1.1.0

BepInEx\plugins\AirportMicFix\AirportMicFix.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using POpusCodec.Enums;
using Photon.Voice;
using Photon.Voice.Unity;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AirportMicFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("WebRTC Noise Suppression, High-Pass Filter, Noise Gate, Auto-Calibrate & Soft Limiter for Content Warning.")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("AirportMicFix")]
[assembly: AssemblyTitle("AirportMicFix")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AirportMicFix
{
	public sealed class AirportMicShortProcessor : IProcessor<short>, IDisposable
	{
		private readonly RnNoiseStreamProcessor _rnNoise;

		private float[] _workBuf = Array.Empty<float>();

		public volatile float LastPeakNormalized;

		public float LastVadProbability
		{
			get
			{
				RnNoiseStreamProcessor rnNoise = _rnNoise;
				if (rnNoise == null)
				{
					return 0f;
				}
				return rnNoise.LastVadProbability;
			}
		}

		public bool IsAiActive
		{
			get
			{
				if (_rnNoise != null)
				{
					return _rnNoise.IsNativeReady;
				}
				return false;
			}
		}

		public AirportMicShortProcessor(int sampleRate)
		{
			_rnNoise = new RnNoiseStreamProcessor(sampleRate);
		}

		public short[] Process(short[] buf)
		{
			if (buf == null || buf.Length == 0)
			{
				return buf;
			}
			if (!ModConfig.Enabled.Value)
			{
				float num = 0f;
				for (int i = 0; i < buf.Length; i++)
				{
					float num2 = Math.Abs((float)buf[i] * 3.0517578E-05f);
					if (num2 > num)
					{
						num = num2;
					}
				}
				LastPeakNormalized = num;
				return buf;
			}
			if (_workBuf.Length < buf.Length)
			{
				_workBuf = new float[buf.Length];
			}
			for (int j = 0; j < buf.Length; j++)
			{
				_workBuf[j] = (float)buf[j] * 3.0517578E-05f;
			}
			_rnNoise.ProcessInPlace(_workBuf, buf.Length);
			float value = ModConfig.MicGain.Value;
			bool value2 = ModConfig.SoftLimiterEnabled.Value;
			float num3 = Mathf.Clamp(ModConfig.LimiterCeiling.Value, 0.2f, 1f);
			float num4 = 0f;
			for (int k = 0; k < buf.Length; k++)
			{
				float num5 = _workBuf[k] * value;
				num5 = ((!value2) ? Mathf.Clamp(num5, -1f, 1f) : ((float)Math.Tanh(num5 / num3) * num3));
				int num6 = (int)Math.Round(num5 * 32767f);
				if (num6 > 32767)
				{
					num6 = 32767;
				}
				else if (num6 < -32768)
				{
					num6 = -32768;
				}
				buf[k] = (short)num6;
				float num7 = ((num5 < 0f) ? (0f - num5) : num5);
				if (num7 > num4)
				{
					num4 = num7;
				}
			}
			LastPeakNormalized = num4;
			return buf;
		}

		public void Dispose()
		{
			_rnNoise?.Dispose();
		}
	}
	public sealed class AirportMicFloatProcessor : IProcessor<float>, IDisposable
	{
		private readonly RnNoiseStreamProcessor _rnNoise;

		public volatile float LastPeakNormalized;

		public float LastVadProbability
		{
			get
			{
				RnNoiseStreamProcessor rnNoise = _rnNoise;
				if (rnNoise == null)
				{
					return 0f;
				}
				return rnNoise.LastVadProbability;
			}
		}

		public bool IsAiActive
		{
			get
			{
				if (_rnNoise != null)
				{
					return _rnNoise.IsNativeReady;
				}
				return false;
			}
		}

		public AirportMicFloatProcessor(int sampleRate)
		{
			_rnNoise = new RnNoiseStreamProcessor(sampleRate);
		}

		public float[] Process(float[] buf)
		{
			if (buf == null || buf.Length == 0)
			{
				return buf;
			}
			if (!ModConfig.Enabled.Value)
			{
				float num = 0f;
				for (int i = 0; i < buf.Length; i++)
				{
					float num2 = ((buf[i] < 0f) ? (0f - buf[i]) : buf[i]);
					if (num2 > num)
					{
						num = num2;
					}
				}
				LastPeakNormalized = num;
				return buf;
			}
			_rnNoise.ProcessInPlace(buf, buf.Length);
			float value = ModConfig.MicGain.Value;
			bool value2 = ModConfig.SoftLimiterEnabled.Value;
			float num3 = Mathf.Clamp(ModConfig.LimiterCeiling.Value, 0.2f, 1f);
			float num4 = 0f;
			for (int j = 0; j < buf.Length; j++)
			{
				float num5 = buf[j] * value;
				num5 = (buf[j] = ((!value2) ? Mathf.Clamp(num5, -1f, 1f) : ((float)Math.Tanh(num5 / num3) * num3)));
				float num6 = ((num5 < 0f) ? (0f - num5) : num5);
				if (num6 > num4)
				{
					num4 = num6;
				}
			}
			LastPeakNormalized = num4;
			return buf;
		}

		public void Dispose()
		{
			_rnNoise?.Dispose();
		}
	}
	public sealed class AirportMicProcessorComponent : MonoBehaviour
	{
		private AirportMicShortProcessor _shortProc;

		private AirportMicFloatProcessor _floatProc;

		public int ActiveSampleRate { get; private set; }

		public bool IsProcessorAttached
		{
			get
			{
				if (_shortProc == null)
				{
					return _floatProc != null;
				}
				return true;
			}
		}

		public bool IsAiActive
		{
			get
			{
				if (_shortProc == null || !_shortProc.IsAiActive)
				{
					if (_floatProc != null)
					{
						return _floatProc.IsAiActive;
					}
					return false;
				}
				return true;
			}
		}

		public float LastProcessedPeak
		{
			get
			{
				if (_shortProc != null)
				{
					return _shortProc.LastPeakNormalized;
				}
				if (_floatProc != null)
				{
					return _floatProc.LastPeakNormalized;
				}
				return 0f;
			}
		}

		public float LastVadProbability
		{
			get
			{
				if (_shortProc != null)
				{
					return _shortProc.LastVadProbability;
				}
				if (_floatProc != null)
				{
					return _floatProc.LastVadProbability;
				}
				return 0f;
			}
		}

		private void PhotonVoiceCreated(PhotonVoiceCreatedParams p)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			int num;
			if (p.Voice == null)
			{
				num = 48000;
			}
			else
			{
				VoiceInfo info = p.Voice.Info;
				num = ((VoiceInfo)(ref info)).SamplingRate;
			}
			int num2 = (ActiveSampleRate = num);
			LocalVoice voice = p.Voice;
			LocalVoiceAudioShort val = (LocalVoiceAudioShort)(object)((voice is LocalVoiceAudioShort) ? voice : null);
			if (val != null)
			{
				_shortProc?.Dispose();
				_floatProc?.Dispose();
				_shortProc = new AirportMicShortProcessor(num2);
				_floatProc = null;
				((LocalVoiceFramed<short>)(object)val).AddPostProcessor(new IProcessor<short>[1] { _shortProc });
				Plugin.Log.LogInfo((object)$"Attached RNNoise AI + Limiter to LocalVoiceAudioShort @ {num2} Hz (AI ready={_shortProc.IsAiActive}).");
				return;
			}
			LocalVoice voice2 = p.Voice;
			LocalVoiceAudioFloat val2 = (LocalVoiceAudioFloat)(object)((voice2 is LocalVoiceAudioFloat) ? voice2 : null);
			if (val2 != null)
			{
				_shortProc?.Dispose();
				_floatProc?.Dispose();
				_floatProc = new AirportMicFloatProcessor(num2);
				_shortProc = null;
				((LocalVoiceFramed<float>)(object)val2).AddPostProcessor(new IProcessor<float>[1] { _floatProc });
				Plugin.Log.LogInfo((object)$"Attached RNNoise AI + Limiter to LocalVoiceAudioFloat @ {num2} Hz (AI ready={_floatProc.IsAiActive}).");
			}
		}

		private void PhotonVoiceRemoved()
		{
			_shortProc?.Dispose();
			_floatProc?.Dispose();
			_shortProc = null;
			_floatProc = null;
		}

		private void OnDestroy()
		{
			PhotonVoiceRemoved();
		}
	}
	public sealed class MicFilterManager : MonoBehaviour
	{
		private readonly HashSet<int> _initializedRecorders = new HashSet<int>();

		private float _nextScanTime;

		public static MicFilterManager Instance { get; private set; }

		public Recorder ActiveRecorder { get; private set; }

		public WebRtcAudioDsp ActiveDsp { get; private set; }

		public AirportMicProcessorComponent ActiveProcessor { get; private set; }

		public bool IsCalibrating { get; private set; }

		public string StatusMessage { get; private set; } = "Waiting for voice lobby...";

		public bool LoopbackTestEnabled { get; private set; }

		private void Awake()
		{
			if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this)
			{
				Object.Destroy((Object)(object)this);
				return;
			}
			Instance = this;
			ModConfig.OnSettingsChanged += ApplySettingsToActiveRecorder;
			RnNoiseNative.EnsureLoaded();
		}

		private void OnDestroy()
		{
			ModConfig.OnSettingsChanged -= ApplySettingsToActiveRecorder;
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private void Update()
		{
			if (Time.unscaledTime >= _nextScanTime)
			{
				_nextScanTime = Time.unscaledTime + 0.5f;
				EnsureActiveRecorder();
			}
			if (!((Object)(object)ActiveRecorder != (Object)null) || IsCalibrating)
			{
				return;
			}
			bool flag = ModConfig.Enabled.Value && ModConfig.NoiseGateEnabled.Value;
			if (ActiveRecorder.VoiceDetection != flag)
			{
				ActiveRecorder.VoiceDetection = flag;
			}
			if (flag)
			{
				float value = ModConfig.GateThreshold.Value;
				if (Mathf.Abs(ActiveRecorder.VoiceDetectionThreshold - value) > 0.0005f)
				{
					ActiveRecorder.VoiceDetectionThreshold = value;
				}
				int value2 = ModConfig.GateHoldTimeMs.Value;
				if (ActiveRecorder.VoiceDetectionDelayMs != value2)
				{
					ActiveRecorder.VoiceDetectionDelayMs = value2;
				}
			}
		}

		public void RegisterRecorder(Recorder recorder)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Invalid comparison between Unknown and I4
			if ((Object)(object)recorder == (Object)null)
			{
				return;
			}
			bool num = (Object)(object)ActiveRecorder != (Object)(object)recorder || !_initializedRecorders.Contains(((Object)recorder).GetInstanceID());
			ActiveRecorder = recorder;
			if (!num)
			{
				ApplySettingsToActiveRecorder();
				return;
			}
			_initializedRecorders.Add(((Object)recorder).GetInstanceID());
			bool flag = false;
			if ((int)recorder.SamplingRate != 48000)
			{
				recorder.SamplingRate = (SamplingRate)48000;
				flag = true;
				Plugin.Log.LogInfo((object)"Set Photon Voice Recorder SamplingRate to 48000 Hz for native RNNoise AI.");
			}
			bool flag2 = false;
			AirportMicProcessorComponent airportMicProcessorComponent = ((Component)recorder).gameObject.GetComponent<AirportMicProcessorComponent>();
			if ((Object)(object)airportMicProcessorComponent == (Object)null)
			{
				airportMicProcessorComponent = ((Component)recorder).gameObject.AddComponent<AirportMicProcessorComponent>();
				flag2 = true;
			}
			ActiveProcessor = airportMicProcessorComponent;
			bool flag3 = false;
			WebRtcAudioDsp val = ((Component)recorder).gameObject.GetComponent<WebRtcAudioDsp>();
			if ((Object)(object)val == (Object)null)
			{
				val = ((Component)recorder).gameObject.AddComponent<WebRtcAudioDsp>();
				flag3 = true;
			}
			ActiveDsp = val;
			ApplySettingsToActiveRecorder();
			if ((flag2 || flag3 || flag) && recorder.RecordingEnabled)
			{
				try
				{
					recorder.RestartRecording();
					Plugin.Log.LogInfo((object)"Restarted Photon Voice Recorder to activate RNNoise AI audio pipeline.");
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Could not restart Recorder immediately: " + ex.Message));
				}
			}
			UpdateStatusMessage();
		}

		private void EnsureActiveRecorder()
		{
			if ((Object)(object)ActiveRecorder != (Object)null && (Object)(object)((Component)ActiveRecorder).gameObject != (Object)null)
			{
				if ((Object)(object)ActiveProcessor == (Object)null || (Object)(object)ActiveDsp == (Object)null)
				{
					RegisterRecorder(ActiveRecorder);
				}
				else if (ActiveRecorder.RecordingEnabled && !ActiveProcessor.IsProcessorAttached)
				{
					try
					{
						ActiveRecorder.RestartRecording();
					}
					catch
					{
					}
				}
				UpdateStatusMessage();
				return;
			}
			ActiveRecorder = null;
			ActiveDsp = null;
			ActiveProcessor = null;
			Recorder[] array = Object.FindObjectsByType<Recorder>((FindObjectsSortMode)0);
			if (array != null && array.Length != 0)
			{
				Recorder[] array2 = array;
				foreach (Recorder val in array2)
				{
					if ((Object)(object)val != (Object)null && ((Behaviour)val).isActiveAndEnabled)
					{
						RegisterRecorder(val);
						return;
					}
				}
			}
			StatusMessage = "Waiting for voice lobby...";
		}

		public void ApplySettingsToActiveRecorder()
		{
			if ((Object)(object)ActiveRecorder == (Object)null)
			{
				return;
			}
			bool value = ModConfig.Enabled.Value;
			if ((Object)(object)ActiveDsp != (Object)null)
			{
				try
				{
					bool flag = value && (ModConfig.WebRtcNoiseSuppression.Value || ModConfig.VoiceActivityDetection.Value || ModConfig.AutoGainControl.Value || ModConfig.EchoCancellation.Value);
					ActiveDsp.Bypass = !flag;
					ActiveDsp.NoiseSuppression = value && ModConfig.WebRtcNoiseSuppression.Value;
					ActiveDsp.HighPass = flag && ModConfig.HighPassFilter.Value;
					ActiveDsp.VAD = value && ModConfig.VoiceActivityDetection.Value;
					ActiveDsp.AGC = value && ModConfig.AutoGainControl.Value;
					ActiveDsp.AgcCompressionGain = ModConfig.AgcCompressionGain.Value;
					ActiveDsp.AgcTargetLevel = ModConfig.AgcTargetLevel.Value;
					ActiveDsp.AEC = value && ModConfig.EchoCancellation.Value;
					ActiveDsp.AecHighPass = value && ModConfig.EchoCancellation.Value;
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Error applying WebRtcAudioDsp settings: " + ex.Message));
				}
			}
			if (!IsCalibrating)
			{
				bool voiceDetection = value && ModConfig.NoiseGateEnabled.Value;
				ActiveRecorder.VoiceDetection = voiceDetection;
				ActiveRecorder.VoiceDetectionThreshold = ModConfig.GateThreshold.Value;
				ActiveRecorder.VoiceDetectionDelayMs = ModConfig.GateHoldTimeMs.Value;
			}
			UpdateStatusMessage();
		}

		private void UpdateStatusMessage()
		{
			if (IsCalibrating)
			{
				return;
			}
			if ((Object)(object)ActiveRecorder == (Object)null)
			{
				StatusMessage = "Waiting for voice lobby...";
			}
			else if (!ModConfig.Enabled.Value)
			{
				StatusMessage = "Bypassed (Original Mic Audio)";
			}
			else if (ModConfig.AiNoiseSuppression.Value)
			{
				if ((Object)(object)ActiveProcessor != (Object)null && ActiveProcessor.IsAiActive)
				{
					StatusMessage = $"RNNoise AI ACTIVE ({ActiveProcessor.ActiveSampleRate / 1000} kHz) + Noise Gate";
				}
				else if (!RnNoiseNative.IsAvailable)
				{
					StatusMessage = "RNNoise DLL error: " + RnNoiseNative.LoadError;
				}
				else
				{
					StatusMessage = "RNNoise ready — waiting for voice stream...";
				}
			}
			else
			{
				StatusMessage = "AI off — Noise Gate + High-Pass active";
			}
		}

		public void TriggerAutoCalibrate(int durationMs = 2000)
		{
			if ((Object)(object)ActiveRecorder == (Object)null || IsCalibrating)
			{
				return;
			}
			IsCalibrating = true;
			StatusMessage = "Calibrating... Stay quiet for 2 seconds!";
			Plugin.Log.LogInfo((object)"Starting 2-second noise floor calibration...");
			try
			{
				ActiveRecorder.VoiceDetectorCalibrate(durationMs, (Action<float>)delegate(float calibratedThreshold)
				{
					IsCalibrating = false;
					float num = Mathf.Clamp(calibratedThreshold * 1.15f + 0.004f, 0.005f, 0.25f);
					ModConfig.Enabled.Value = true;
					ModConfig.NoiseGateEnabled.Value = true;
					ModConfig.GateThreshold.Value = num;
					StatusMessage = $"Calibrated! Gate threshold set to {num:F3}";
					Plugin.Log.LogInfo((object)$"Noise gate calibrated: raw={calibratedThreshold:F4}, applied={num:F4}");
				});
			}
			catch (Exception ex)
			{
				IsCalibrating = false;
				StatusMessage = "Calibration failed: " + ex.Message;
				Plugin.Log.LogError((object)$"Calibration failed: {ex}");
			}
		}

		public void SetLoopbackTest(bool enabled)
		{
			LoopbackTestEnabled = enabled;
			if ((Object)(object)ActiveRecorder != (Object)null)
			{
				ActiveRecorder.DebugEchoMode = enabled;
			}
		}

		public float GetRawPeakLevel()
		{
			Recorder activeRecorder = ActiveRecorder;
			if (((activeRecorder != null) ? activeRecorder.LevelMeter : null) != null)
			{
				return Mathf.Clamp01(ActiveRecorder.LevelMeter.CurrentPeakAmp);
			}
			return 0f;
		}

		public float GetPostDspPeakLevel()
		{
			if (!((Object)(object)ActiveProcessor != (Object)null))
			{
				return 0f;
			}
			return Mathf.Clamp01(ActiveProcessor.LastProcessedPeak);
		}

		public float GetAiVadProbability()
		{
			if (!((Object)(object)ActiveProcessor != (Object)null))
			{
				return 0f;
			}
			return Mathf.Clamp01(ActiveProcessor.LastVadProbability);
		}

		public bool IsCurrentlyTransmitting()
		{
			if ((Object)(object)ActiveRecorder != (Object)null)
			{
				return ActiveRecorder.IsCurrentlyTransmitting;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Recorder), "StartRecording")]
	internal static class RecorderStartRecordingPatch
	{
		private static void Prefix(Recorder __instance)
		{
			MicFilterManager.Instance?.RegisterRecorder(__instance);
		}
	}
	[HarmonyPatch(typeof(NetworkVoiceHandler), "InitNetworkVoice")]
	internal static class NetworkVoiceHandlerPatch
	{
		private static void Postfix(NetworkVoiceHandler __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				object? obj = AccessTools.Field(typeof(NetworkVoiceHandler), "m_LocalRecorder")?.GetValue(__instance);
				Recorder val = (Recorder)((obj is Recorder) ? obj : null);
				if (val != null)
				{
					MicFilterManager.Instance?.RegisterRecorder(val);
				}
			}
		}
	}
	public sealed class MicFilterUI : MonoBehaviour
	{
		private bool _isOpen;

		private Rect _windowRect = new Rect(40f, 40f, 440f, 660f);

		private Vector2 _scrollPos;

		private float _smoothedLevel;

		private float _smoothedVad;

		private bool _showAdvancedWebRtc;

		private CursorLockMode _prevLockMode;

		private bool _prevCursorVisible;

		private Texture2D _bgTex;

		private Texture2D _barBgTex;

		private Texture2D _barGreenTex;

		private Texture2D _barYellowTex;

		private Texture2D _barRedTex;

		private Texture2D _barBlueTex;

		private Texture2D _thresholdTex;

		private GUIStyle _headerStyle;

		private GUIStyle _sectionStyle;

		private GUIStyle _statusStyle;

		private GUIStyle _smallLabelStyle;

		private bool _stylesInit;

		private void Update()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			if (Input.GetKeyDown(ModConfig.ToggleMenuKey.Value))
			{
				ToggleMenu();
			}
			if (_isOpen && Input.GetKeyDown((KeyCode)27))
			{
				CloseMenu();
			}
			MicFilterManager instance = MicFilterManager.Instance;
			float num = (((Object)(object)instance != (Object)null) ? Mathf.Max(instance.GetRawPeakLevel(), instance.GetPostDspPeakLevel()) : 0f);
			float num2 = ((num > _smoothedLevel) ? 25f : 8f);
			_smoothedLevel = Mathf.Lerp(_smoothedLevel, num, Time.unscaledDeltaTime * num2);
			float num3 = (((Object)(object)instance != (Object)null) ? instance.GetAiVadProbability() : 0f);
			_smoothedVad = Mathf.Lerp(_smoothedVad, num3, Time.unscaledDeltaTime * 15f);
		}

		private void ToggleMenu()
		{
			if (_isOpen)
			{
				CloseMenu();
			}
			else
			{
				OpenMenu();
			}
		}

		private void OpenMenu()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			_isOpen = true;
			_prevLockMode = Cursor.lockState;
			_prevCursorVisible = Cursor.visible;
			Cursor.lockState = (CursorLockMode)0;
			Cursor.visible = true;
		}

		private void CloseMenu()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			_isOpen = false;
			if ((Object)(object)MicFilterManager.Instance != (Object)null && MicFilterManager.Instance.LoopbackTestEnabled)
			{
				MicFilterManager.Instance.SetLoopbackTest(enabled: false);
			}
			Cursor.lockState = _prevLockMode;
			Cursor.visible = _prevCursorVisible;
		}

		private void OnDestroy()
		{
			DestroyTex(ref _bgTex);
			DestroyTex(ref _barBgTex);
			DestroyTex(ref _barGreenTex);
			DestroyTex(ref _barYellowTex);
			DestroyTex(ref _barRedTex);
			DestroyTex(ref _barBlueTex);
			DestroyTex(ref _thresholdTex);
		}

		private static void DestroyTex(ref Texture2D tex)
		{
			if ((Object)(object)tex != (Object)null)
			{
				Object.Destroy((Object)(object)tex);
				tex = null;
			}
		}

		private void InitStyles()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: 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_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Expected O, but got Unknown
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Expected O, but got Unknown
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Expected O, but got Unknown
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Expected O, but got Unknown
			if (!_stylesInit)
			{
				_bgTex = MakeTex(new Color(0.1f, 0.11f, 0.14f, 0.96f));
				_barBgTex = MakeTex(new Color(0.18f, 0.19f, 0.24f, 1f));
				_barGreenTex = MakeTex(new Color(0.22f, 0.82f, 0.45f, 1f));
				_barYellowTex = MakeTex(new Color(0.95f, 0.76f, 0.2f, 1f));
				_barRedTex = MakeTex(new Color(0.92f, 0.28f, 0.28f, 1f));
				_barBlueTex = MakeTex(new Color(0.28f, 0.68f, 1f, 1f));
				_thresholdTex = MakeTex(new Color(1f, 0.35f, 0.15f, 1f));
				GUIStyle val = new GUIStyle(GUI.skin.label)
				{
					fontSize = 14,
					fontStyle = (FontStyle)1
				};
				val.normal.textColor = new Color(0.95f, 0.96f, 0.98f);
				_headerStyle = val;
				GUIStyle val2 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 13,
					fontStyle = (FontStyle)1
				};
				val2.normal.textColor = new Color(0.45f, 0.82f, 1f);
				_sectionStyle = val2;
				GUIStyle val3 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 12,
					wordWrap = true
				};
				val3.normal.textColor = new Color(0.82f, 0.88f, 0.94f);
				_statusStyle = val3;
				GUIStyle val4 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 11
				};
				val4.normal.textColor = new Color(0.75f, 0.78f, 0.84f);
				_smallLabelStyle = val4;
				_stylesInit = true;
			}
		}

		private static Texture2D MakeTex(Color color)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			Texture2D val = new Texture2D(1, 1, (TextureFormat)4, false);
			val.SetPixel(0, 0, color);
			val.Apply();
			return val;
		}

		private void OnGUI()
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			InitStyles();
			if (!_isOpen)
			{
				if (ModConfig.ShowHudIndicator.Value)
				{
					DrawMiniHud();
				}
				return;
			}
			Cursor.lockState = (CursorLockMode)0;
			Cursor.visible = true;
			Color backgroundColor = GUI.backgroundColor;
			GUI.backgroundColor = new Color(0.14f, 0.16f, 0.2f, 0.98f);
			_windowRect = GUI.Window(948213, _windowRect, new WindowFunction(DrawWindow), string.Format("AirportMicFix v{0} (RNNoise AI)  [{1}]", "1.1.0", ModConfig.ToggleMenuKey.Value));
			GUI.backgroundColor = backgroundColor;
		}

		private void DrawMiniHud()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: 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_00fd: Unknown result type (might be due to invalid IL or missing references)
			MicFilterManager instance = MicFilterManager.Instance;
			if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.ActiveRecorder == (Object)null))
			{
				Rect val = default(Rect);
				((Rect)(ref val))..ctor(16f, (float)(Screen.height - 46), 185f, 30f);
				GUI.DrawTexture(val, (Texture)(object)_bgTex);
				bool flag = instance.IsCurrentlyTransmitting();
				Color color = (flag ? new Color(0.22f, 0.82f, 0.45f) : new Color(0.55f, 0.58f, 0.65f));
				Color color2 = GUI.color;
				GUI.color = color;
				GUI.Label(new Rect(((Rect)(ref val)).x + 8f, ((Rect)(ref val)).y + 5f, 76f, 20f), flag ? "AI MIC LIVE" : "GATED", _smallLabelStyle);
				GUI.color = color2;
				Rect rect = default(Rect);
				((Rect)(ref rect))..ctor(((Rect)(ref val)).x + 86f, ((Rect)(ref val)).y + 9f, 88f, 12f);
				DrawLevelBar(rect, _smoothedLevel, ModConfig.NoiseGateEnabled.Value ? ModConfig.GateThreshold.Value : (-1f), 0.35f, blueBar: false);
			}
		}

		private void DrawWindow(int id)
		{
			//IL_00c8: 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_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_07b9: Unknown result type (might be due to invalid IL or missing references)
			MicFilterManager instance = MicFilterManager.Instance;
			GUILayout.Space(4f);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			bool flag = GUILayout.Toggle(ModConfig.Enabled.Value, " Mod Enabled (Master Switch)", Array.Empty<GUILayoutOption>());
			if (flag != ModConfig.Enabled.Value)
			{
				ModConfig.Enabled.Value = flag;
			}
			GUILayout.FlexibleSpace();
			if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }))
			{
				CloseMenu();
			}
			GUILayout.EndHorizontal();
			GUILayout.Label(((Object)(object)instance != (Object)null) ? ("Status: " + instance.StatusMessage) : "Status: Initializing...", _statusStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Space(6f);
			DrawMeterSection(instance);
			GUILayout.Space(8f);
			_scrollPos = GUILayout.BeginScrollView(_scrollPos, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandHeight(true) });
			GUILayout.Label("Quick Presets", _sectionStyle, Array.Empty<GUILayoutOption>());
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Airport / Jet", Array.Empty<GUILayoutOption>()))
			{
				ModConfig.ApplyAirportPreset();
			}
			if (GUILayout.Button("Balanced", Array.Empty<GUILayoutOption>()))
			{
				ModConfig.ApplyBalancedPreset();
			}
			if (GUILayout.Button("Light", Array.Empty<GUILayoutOption>()))
			{
				ModConfig.ApplyLightPreset();
			}
			if (GUILayout.Button("Bypass", Array.Empty<GUILayoutOption>()))
			{
				ModConfig.ApplyBypassPreset();
			}
			GUILayout.EndHorizontal();
			GUILayout.Space(10f);
			GUILayout.Label("AI Noise Suppression (RNNoise Neural Network)", _sectionStyle, Array.Empty<GUILayoutOption>());
			bool flag2 = GUILayout.Toggle(ModConfig.AiNoiseSuppression.Value, " Enable AI Noise Suppression (kills airport WHILE talking!)", Array.Empty<GUILayoutOption>());
			if (flag2 != ModConfig.AiNoiseSuppression.Value)
			{
				ModConfig.AiNoiseSuppression.Value = flag2;
			}
			if (ModConfig.AiNoiseSuppression.Value)
			{
				GUILayout.Label($"AI Suppression Strength: {Mathf.RoundToInt(ModConfig.AiStrength.Value * 100f)}%", _smallLabelStyle, Array.Empty<GUILayoutOption>());
				float num = GUILayout.HorizontalSlider(ModConfig.AiStrength.Value, 0f, 1f, Array.Empty<GUILayoutOption>());
				if (Mathf.Abs(num - ModConfig.AiStrength.Value) > 0.01f)
				{
					ModConfig.AiStrength.Value = num;
				}
				bool flag3 = GUILayout.Toggle(ModConfig.AiSpeechGateEnabled.Value, " AI Speech Gate (smoothly mutes non-speech noise)", Array.Empty<GUILayoutOption>());
				if (flag3 != ModConfig.AiSpeechGateEnabled.Value)
				{
					ModConfig.AiSpeechGateEnabled.Value = flag3;
				}
				if (ModConfig.AiSpeechGateEnabled.Value)
				{
					GUILayout.Label($"AI Speech Confidence Threshold: {Mathf.RoundToInt(ModConfig.AiSpeechGateThreshold.Value * 100f)}% (orange line on AI bar)", _smallLabelStyle, Array.Empty<GUILayoutOption>());
					float num2 = GUILayout.HorizontalSlider(ModConfig.AiSpeechGateThreshold.Value, 0.05f, 0.9f, Array.Empty<GUILayoutOption>());
					if (Mathf.Abs(num2 - ModConfig.AiSpeechGateThreshold.Value) > 0.01f)
					{
						ModConfig.AiSpeechGateThreshold.Value = num2;
					}
				}
			}
			bool flag4 = GUILayout.Toggle(ModConfig.HighPassFilter.Value, " 85 Hz High-Pass Filter (cuts low rumble / wind / breathing)", Array.Empty<GUILayoutOption>());
			if (flag4 != ModConfig.HighPassFilter.Value)
			{
				ModConfig.HighPassFilter.Value = flag4;
			}
			GUILayout.Space(10f);
			GUILayout.Label("Noise Gate (Blocks Idle Noise)", _sectionStyle, Array.Empty<GUILayoutOption>());
			bool flag5 = GUILayout.Toggle(ModConfig.NoiseGateEnabled.Value, " Enable Photon Noise Gate", Array.Empty<GUILayoutOption>());
			if (flag5 != ModConfig.NoiseGateEnabled.Value)
			{
				ModConfig.NoiseGateEnabled.Value = flag5;
			}
			GUILayout.Label($"Gate Threshold: {ModConfig.GateThreshold.Value:F3}  (orange line on mic meter)", _smallLabelStyle, Array.Empty<GUILayoutOption>());
			float num3 = GUILayout.HorizontalSlider(ModConfig.GateThreshold.Value, 0f, 0.25f, Array.Empty<GUILayoutOption>());
			if (Mathf.Abs(num3 - ModConfig.GateThreshold.Value) > 0.0005f)
			{
				ModConfig.GateThreshold.Value = num3;
			}
			GUILayout.Label($"Gate Hold Time: {ModConfig.GateHoldTimeMs.Value} ms  (prevents cutting off words)", _smallLabelStyle, Array.Empty<GUILayoutOption>());
			int num4 = Mathf.RoundToInt(GUILayout.HorizontalSlider((float)ModConfig.GateHoldTimeMs.Value, 50f, 1200f, Array.Empty<GUILayoutOption>()));
			if (num4 != ModConfig.GateHoldTimeMs.Value)
			{
				ModConfig.GateHoldTimeMs.Value = num4;
			}
			GUILayout.Space(4f);
			GUI.enabled = (Object)(object)instance != (Object)null && (Object)(object)instance.ActiveRecorder != (Object)null && !instance.IsCalibrating;
			if (GUILayout.Button(((Object)(object)instance != (Object)null && instance.IsCalibrating) ? "Calibrating... Stay Quiet (2s)" : "Auto-Calibrate Noise Floor (Stay Quiet 2s)", Array.Empty<GUILayoutOption>()))
			{
				instance?.TriggerAutoCalibrate();
			}
			GUI.enabled = true;
			GUILayout.Space(10f);
			GUILayout.Label("Volume & Anti-Earrape Limiter", _sectionStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Label($"Mic Gain: {ModConfig.MicGain.Value:F2}x", _smallLabelStyle, Array.Empty<GUILayoutOption>());
			float num5 = GUILayout.HorizontalSlider(ModConfig.MicGain.Value, 0.1f, 2.5f, Array.Empty<GUILayoutOption>());
			if (Mathf.Abs(num5 - ModConfig.MicGain.Value) > 0.01f)
			{
				ModConfig.MicGain.Value = num5;
			}
			bool flag6 = GUILayout.Toggle(ModConfig.SoftLimiterEnabled.Value, " Anti-Earrape Soft Limiter (smooths screaming peaks)", Array.Empty<GUILayoutOption>());
			if (flag6 != ModConfig.SoftLimiterEnabled.Value)
			{
				ModConfig.SoftLimiterEnabled.Value = flag6;
			}
			if (ModConfig.SoftLimiterEnabled.Value)
			{
				GUILayout.Label($"Limiter Max Ceiling: {Mathf.RoundToInt(ModConfig.LimiterCeiling.Value * 100f)}%", _smallLabelStyle, Array.Empty<GUILayoutOption>());
				float num6 = GUILayout.HorizontalSlider(ModConfig.LimiterCeiling.Value, 0.25f, 1f, Array.Empty<GUILayoutOption>());
				if (Mathf.Abs(num6 - ModConfig.LimiterCeiling.Value) > 0.01f)
				{
					ModConfig.LimiterCeiling.Value = num6;
				}
			}
			GUILayout.Space(10f);
			if (GUILayout.Button(_showAdvancedWebRtc ? "▼ Advanced / Legacy WebRTC DSP (Optional)" : "► Advanced / Legacy WebRTC DSP (Optional)", Array.Empty<GUILayoutOption>()))
			{
				_showAdvancedWebRtc = !_showAdvancedWebRtc;
			}
			if (_showAdvancedWebRtc)
			{
				bool flag7 = GUILayout.Toggle(ModConfig.EchoCancellation.Value, " Echo Cancellation (AEC - only for speakers)", Array.Empty<GUILayoutOption>());
				if (flag7 != ModConfig.EchoCancellation.Value)
				{
					ModConfig.EchoCancellation.Value = flag7;
				}
				bool flag8 = GUILayout.Toggle(ModConfig.AutoGainControl.Value, " Auto Gain Control (AGC - warning: can boost noise)", Array.Empty<GUILayoutOption>());
				if (flag8 != ModConfig.AutoGainControl.Value)
				{
					ModConfig.AutoGainControl.Value = flag8;
				}
				bool flag9 = GUILayout.Toggle(ModConfig.WebRtcNoiseSuppression.Value, " Stack Legacy WebRTC Noise Suppression", Array.Empty<GUILayoutOption>());
				if (flag9 != ModConfig.WebRtcNoiseSuppression.Value)
				{
					ModConfig.WebRtcNoiseSuppression.Value = flag9;
				}
			}
			GUILayout.Space(10f);
			GUILayout.Label("Testing & HUD", _sectionStyle, Array.Empty<GUILayoutOption>());
			GUI.enabled = (Object)(object)instance != (Object)null && (Object)(object)instance.ActiveRecorder != (Object)null;
			bool flag10 = GUILayout.Toggle((Object)(object)instance != (Object)null && instance.LoopbackTestEnabled, " Test My Mic (Hear Yourself Live - auto-off on close)", Array.Empty<GUILayoutOption>());
			if ((Object)(object)instance != (Object)null && flag10 != instance.LoopbackTestEnabled)
			{
				instance.SetLoopbackTest(flag10);
			}
			GUI.enabled = true;
			bool flag11 = GUILayout.Toggle(ModConfig.ShowHudIndicator.Value, " Show mini Mic/Gate HUD in bottom-left", Array.Empty<GUILayoutOption>());
			if (flag11 != ModConfig.ShowHudIndicator.Value)
			{
				ModConfig.ShowHudIndicator.Value = flag11;
			}
			GUILayout.EndScrollView();
			GUI.DragWindow(new Rect(0f, 0f, 10000f, 24f));
		}

		private void DrawMeterSection(MicFilterManager mgr)
		{
			//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_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.Label("Live Mic Level", _headerStyle, Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			string text;
			Color color = default(Color);
			if ((Object)(object)mgr == (Object)null || (Object)(object)mgr.ActiveRecorder == (Object)null)
			{
				text = "NO LOBBY";
				((Color)(ref color))..ctor(0.65f, 0.65f, 0.7f);
			}
			else if (mgr.IsCalibrating)
			{
				text = "CALIBRATING...";
				((Color)(ref color))..ctor(0.95f, 0.78f, 0.2f);
			}
			else if (mgr.IsCurrentlyTransmitting())
			{
				text = "TRANSMITTING";
				((Color)(ref color))..ctor(0.25f, 0.88f, 0.45f);
			}
			else
			{
				text = "GATED (MUTED)";
				((Color)(ref color))..ctor(0.6f, 0.65f, 0.72f);
			}
			Color color2 = GUI.color;
			GUI.color = color;
			GUILayout.Label(text, _headerStyle, Array.Empty<GUILayoutOption>());
			GUI.color = color2;
			GUILayout.EndHorizontal();
			Rect rect = GUILayoutUtility.GetRect(10f, 18f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
			float thresholdMarker = ((ModConfig.Enabled.Value && ModConfig.NoiseGateEnabled.Value) ? ModConfig.GateThreshold.Value : (-1f));
			DrawLevelBar(rect, _smoothedLevel, thresholdMarker, 0.35f, blueBar: false);
			if (ModConfig.Enabled.Value && ModConfig.AiNoiseSuppression.Value)
			{
				GUILayout.Space(4f);
				GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
				GUILayout.Label("AI Speech Detection (RNNoise)", _smallLabelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
				GUILayout.Label($"{Mathf.RoundToInt(_smoothedVad * 100f)}%", _smallLabelStyle, Array.Empty<GUILayoutOption>());
				GUILayout.EndHorizontal();
				Rect rect2 = GUILayoutUtility.GetRect(10f, 12f, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(true) });
				float thresholdMarker2 = (ModConfig.AiSpeechGateEnabled.Value ? ModConfig.AiSpeechGateThreshold.Value : (-1f));
				DrawLevelBar(rect2, _smoothedVad, thresholdMarker2, 1f, blueBar: true);
			}
		}

		private void DrawLevelBar(Rect rect, float value, float thresholdMarker, float maxScale, bool blueBar)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			GUI.DrawTexture(rect, (Texture)(object)_barBgTex);
			float num = Mathf.Clamp01(value / maxScale);
			if (num > 0.001f)
			{
				Texture2D val = (blueBar ? _barBlueTex : ((num > 0.85f) ? _barRedTex : ((num > 0.55f) ? _barYellowTex : _barGreenTex)));
				GUI.DrawTexture(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width * num, ((Rect)(ref rect)).height), (Texture)(object)val);
			}
			if (thresholdMarker >= 0f)
			{
				float num2 = Mathf.Clamp01(thresholdMarker / maxScale);
				GUI.DrawTexture(new Rect(((Rect)(ref rect)).x + ((Rect)(ref rect)).width * num2 - 1f, ((Rect)(ref rect)).y - 2f, 3f, ((Rect)(ref rect)).height + 4f), (Texture)(object)_thresholdTex);
			}
		}
	}
	public static class ModConfig
	{
		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<KeyCode> ToggleMenuKey;

		public static ConfigEntry<bool> ShowHudIndicator;

		public static ConfigEntry<bool> AiNoiseSuppression;

		public static ConfigEntry<float> AiStrength;

		public static ConfigEntry<bool> AiSpeechGateEnabled;

		public static ConfigEntry<float> AiSpeechGateThreshold;

		public static ConfigEntry<bool> HighPassFilter;

		public static ConfigEntry<bool> WebRtcNoiseSuppression;

		public static ConfigEntry<bool> VoiceActivityDetection;

		public static ConfigEntry<bool> AutoGainControl;

		public static ConfigEntry<int> AgcCompressionGain;

		public static ConfigEntry<int> AgcTargetLevel;

		public static ConfigEntry<bool> EchoCancellation;

		public static ConfigEntry<bool> NoiseGateEnabled;

		public static ConfigEntry<float> GateThreshold;

		public static ConfigEntry<int> GateHoldTimeMs;

		public static ConfigEntry<float> MicGain;

		public static ConfigEntry<bool> SoftLimiterEnabled;

		public static ConfigEntry<float> LimiterCeiling;

		public static event Action OnSettingsChanged;

		public static void Init(ConfigFile config)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Expected O, but got Unknown
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Expected O, but got Unknown
			//IL_0221: Unknown result type (might be due to invalid IL or missing references)
			//IL_022b: Expected O, but got Unknown
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_0260: Expected O, but got Unknown
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0298: Expected O, but got Unknown
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02eb: Expected O, but got Unknown
			Enabled = config.Bind<bool>("1. General", "Enabled", true, "Master switch for AirportMicFix. Disable to pass raw mic audio through unchanged.");
			ToggleMenuKey = config.Bind<KeyCode>("1. General", "ToggleMenuKey", (KeyCode)289, "Key to open/close the in-game AirportMicFix tuning menu.");
			ShowHudIndicator = config.Bind<bool>("1. General", "ShowHudIndicator", false, "Show a compact mic level & gate status indicator in the bottom-left corner.");
			AiNoiseSuppression = config.Bind<bool>("2. AI Noise Suppression (RNNoise)", "AiNoiseSuppression", true, "Neural network noise suppression (RNNoise). Eliminates jet engine, fan, AC, keyboard, and static noise EVEN WHILE TALKING.");
			AiStrength = config.Bind<float>("2. AI Noise Suppression (RNNoise)", "AiStrength", 1f, new ConfigDescription("AI Noise Suppression strength (0.0 = off, 1.0 = maximum airport deletion).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			AiSpeechGateEnabled = config.Bind<bool>("2. AI Noise Suppression (RNNoise)", "AiSpeechGateEnabled", true, "Uses RNNoise's neural voice detector to smoothly mute non-speech sounds (fans, claps, typing).");
			AiSpeechGateThreshold = config.Bind<float>("2. AI Noise Suppression (RNNoise)", "AiSpeechGateThreshold", 0.35f, new ConfigDescription("Minimum AI speech confidence (0.05 - 0.90) to keep the mic open. Higher = stricter against loud non-speech noise.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 0.9f), Array.Empty<object>()));
			HighPassFilter = config.Bind<bool>("3. High-Pass & WebRTC DSP", "HighPassFilter", true, "85 Hz High-Pass Filter: cuts low-frequency rumble, wind, breathing, and desk thumps.");
			WebRtcNoiseSuppression = config.Bind<bool>("3. High-Pass & WebRTC DSP", "WebRtcNoiseSuppression", false, "Legacy WebRTC Noise Suppression (OFF by default because RNNoise AI works best on the raw unmangled spectrum).");
			VoiceActivityDetection = config.Bind<bool>("3. High-Pass & WebRTC DSP", "VoiceActivityDetection", false, "Legacy WebRTC Voice Activity Detection (optional extra stage).");
			AutoGainControl = config.Bind<bool>("3. High-Pass & WebRTC DSP", "AutoGainControl", false, "WebRTC Auto Gain Control (OFF by default because AGC can boost background noise).");
			AgcCompressionGain = config.Bind<int>("3. High-Pass & WebRTC DSP", "AgcCompressionGain", 9, new ConfigDescription("AGC compression gain in dB.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 30), Array.Empty<object>()));
			AgcTargetLevel = config.Bind<int>("3. High-Pass & WebRTC DSP", "AgcTargetLevel", 3, new ConfigDescription("AGC target peak level in dBFS below full scale.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 31), Array.Empty<object>()));
			EchoCancellation = config.Bind<bool>("3. High-Pass & WebRTC DSP", "EchoCancellation", false, "WebRTC Acoustic Echo Cancellation (AEC): enable only if using speakers instead of headphones.");
			NoiseGateEnabled = config.Bind<bool>("4. Noise Gate", "NoiseGateEnabled", true, "Enables Photon Voice's amplitude noise gate so the mic only transmits above the threshold.");
			GateThreshold = config.Bind<float>("4. Noise Gate", "GateThreshold", 0.025f, new ConfigDescription("Noise gate activation threshold (0.000 - 0.300). Higher = blocks louder background noise.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.3f), Array.Empty<object>()));
			GateHoldTimeMs = config.Bind<int>("4. Noise Gate", "GateHoldTimeMs", 350, new ConfigDescription("How long (ms) the gate stays open after you stop speaking so words don't cut off.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(50, 1500), Array.Empty<object>()));
			MicGain = config.Bind<float>("5. Gain and Limiter", "MicGain", 1.1f, new ConfigDescription("Output volume multiplier after AI denoising (0.1x - 3.0x).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 3f), Array.Empty<object>()));
			SoftLimiterEnabled = config.Bind<bool>("5. Gain and Limiter", "SoftLimiterEnabled", true, "Anti-Earrape Soft Limiter: smoothly compresses extreme peaks when screaming.");
			LimiterCeiling = config.Bind<float>("5. Gain and Limiter", "LimiterCeiling", 0.85f, new ConfigDescription("Maximum output ceiling for the soft limiter (0.20 - 1.00).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 1f), Array.Empty<object>()));
			config.SettingChanged += delegate
			{
				NotifyChanged();
			};
		}

		public static void NotifyChanged()
		{
			ModConfig.OnSettingsChanged?.Invoke();
		}

		public static void ApplyAirportPreset()
		{
			Enabled.Value = true;
			AiNoiseSuppression.Value = true;
			AiStrength.Value = 1f;
			AiSpeechGateEnabled.Value = true;
			AiSpeechGateThreshold.Value = 0.5f;
			HighPassFilter.Value = true;
			WebRtcNoiseSuppression.Value = false;
			VoiceActivityDetection.Value = false;
			AutoGainControl.Value = false;
			NoiseGateEnabled.Value = true;
			GateThreshold.Value = 0.035f;
			GateHoldTimeMs.Value = 350;
			MicGain.Value = 1.15f;
			SoftLimiterEnabled.Value = true;
			LimiterCeiling.Value = 0.8f;
			NotifyChanged();
		}

		public static void ApplyBalancedPreset()
		{
			Enabled.Value = true;
			AiNoiseSuppression.Value = true;
			AiStrength.Value = 1f;
			AiSpeechGateEnabled.Value = true;
			AiSpeechGateThreshold.Value = 0.3f;
			HighPassFilter.Value = true;
			WebRtcNoiseSuppression.Value = false;
			VoiceActivityDetection.Value = false;
			AutoGainControl.Value = false;
			NoiseGateEnabled.Value = true;
			GateThreshold.Value = 0.02f;
			GateHoldTimeMs.Value = 350;
			MicGain.Value = 1.1f;
			SoftLimiterEnabled.Value = true;
			LimiterCeiling.Value = 0.85f;
			NotifyChanged();
		}

		public static void ApplyLightPreset()
		{
			Enabled.Value = true;
			AiNoiseSuppression.Value = true;
			AiStrength.Value = 0.75f;
			AiSpeechGateEnabled.Value = false;
			HighPassFilter.Value = true;
			WebRtcNoiseSuppression.Value = false;
			VoiceActivityDetection.Value = false;
			AutoGainControl.Value = false;
			NoiseGateEnabled.Value = true;
			GateThreshold.Value = 0.012f;
			GateHoldTimeMs.Value = 400;
			MicGain.Value = 1f;
			SoftLimiterEnabled.Value = true;
			LimiterCeiling.Value = 0.9f;
			NotifyChanged();
		}

		public static void ApplyBypassPreset()
		{
			Enabled.Value = false;
			NotifyChanged();
		}
	}
	[BepInPlugin("AirportMicFix", "AirportMicFix", "1.1.0")]
	public sealed class Plugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			ModConfig.Init(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("AirportMicFix");
			_harmony.PatchAll();
			GameObject val = new GameObject("AirportMicFix_Controller");
			Object.DontDestroyOnLoad((Object)val);
			((Object)val).hideFlags = (HideFlags)61;
			val.AddComponent<MicFilterManager>();
			val.AddComponent<MicFilterUI>();
			Log.LogInfo((object)string.Format("{0} v{1} loaded! Press {2} in-game to open the Mic Filter menu.", "AirportMicFix", "1.1.0", ModConfig.ToggleMenuKey.Value));
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class RnNoiseNative
	{
		public const int FrameSize48k = 480;

		private static bool _initialized;

		private static readonly object _initLock = new object();

		public static bool IsAvailable { get; private set; }

		public static string LoadError { get; private set; } = string.Empty;

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

		[DllImport("rnnoise", CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr rnnoise_create(IntPtr model);

		[DllImport("rnnoise", CallingConvention = CallingConvention.Cdecl)]
		internal static extern void rnnoise_destroy(IntPtr state);

		[DllImport("rnnoise", CallingConvention = CallingConvention.Cdecl)]
		internal static extern float rnnoise_process_frame(IntPtr state, float[] dataOut, float[] dataIn);

		public static bool EnsureLoaded()
		{
			if (_initialized)
			{
				return IsAvailable;
			}
			lock (_initLock)
			{
				if (_initialized)
				{
					return IsAvailable;
				}
				_initialized = true;
				try
				{
					string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? string.Empty;
					string[] obj = new string[3]
					{
						Path.Combine(path, "rnnoise.dll"),
						Path.Combine(path, "native", "rnnoise.dll"),
						Path.Combine(path, "x64", "rnnoise.dll")
					};
					string text = null;
					string[] array = obj;
					foreach (string text2 in array)
					{
						if (File.Exists(text2))
						{
							if (LoadLibrary(text2) != IntPtr.Zero)
							{
								text = text2;
								break;
							}
							int lastWin32Error = Marshal.GetLastWin32Error();
							LoadError = $"LoadLibrary('{text2}') failed (Win32 error {lastWin32Error})";
						}
					}
					IntPtr intPtr = rnnoise_create(IntPtr.Zero);
					if (intPtr == IntPtr.Zero)
					{
						IsAvailable = false;
						if (string.IsNullOrEmpty(LoadError))
						{
							LoadError = "rnnoise_create returned null.";
						}
						Plugin.Log.LogError((object)("RNNoise failed to initialize: " + LoadError));
						return false;
					}
					rnnoise_destroy(intPtr);
					IsAvailable = true;
					LoadError = string.Empty;
					Plugin.Log.LogInfo((object)("RNNoise AI Noise Suppression loaded successfully (" + (text ?? "system PATH") + ")."));
					return true;
				}
				catch (Exception ex)
				{
					IsAvailable = false;
					LoadError = ex.Message;
					Plugin.Log.LogError((object)$"Failed to load rnnoise.dll: {ex}");
					return false;
				}
			}
		}
	}
	internal sealed class RnNoiseStreamProcessor : IDisposable
	{
		private readonly int _sampleRate;

		private IntPtr _state;

		private bool _disposed;

		private readonly float _b0;

		private readonly float _b1;

		private readonly float _b2;

		private readonly float _a1;

		private readonly float _a2;

		private float _x1;

		private float _x2;

		private float _y1;

		private float _y2;

		private readonly float[] _rnIn = new float[480];

		private readonly float[] _rnOut = new float[480];

		private readonly float[] _inFifo = new float[4096];

		private int _inFifoCount;

		private readonly float[] _outFifo = new float[4096];

		private int _outFifoCount;

		private float _vadGain = 1f;

		private int _vadHoldSamplesRemaining;

		public volatile float LastVadProbability;

		public bool IsNativeReady
		{
			get
			{
				if (_state != IntPtr.Zero)
				{
					return !_disposed;
				}
				return false;
			}
		}

		public RnNoiseStreamProcessor(int sampleRate)
		{
			_sampleRate = ((sampleRate > 0) ? sampleRate : 48000);
			if (RnNoiseNative.EnsureLoaded())
			{
				_state = RnNoiseNative.rnnoise_create(IntPtr.Zero);
			}
			double num = 85.0;
			double num2 = Math.Tan(Math.PI * num / (double)_sampleRate);
			double num3 = 1.0 / (1.0 + Math.Sqrt(2.0) * num2 + num2 * num2);
			_b0 = (float)(1.0 * num3);
			_b1 = (float)(-2.0 * num3);
			_b2 = (float)(1.0 * num3);
			_a1 = (float)(2.0 * (num2 * num2 - 1.0) * num3);
			_a2 = (float)((1.0 - Math.Sqrt(2.0) * num2 + num2 * num2) * num3);
		}

		public void ProcessInPlace(float[] samples, int count)
		{
			if (samples == null || count <= 0)
			{
				return;
			}
			bool value = ModConfig.HighPassFilter.Value;
			bool flag = ModConfig.AiNoiseSuppression.Value && IsNativeReady;
			if (value)
			{
				for (int i = 0; i < count; i++)
				{
					float num = samples[i];
					float num2 = _b0 * num + _b1 * _x1 + _b2 * _x2 - _a1 * _y1 - _a2 * _y2;
					_x2 = _x1;
					_x1 = num;
					_y2 = _y1;
					_y1 = num2;
					samples[i] = num2;
				}
			}
			if (!flag)
			{
				LastVadProbability = 1f;
			}
			else if (_sampleRate == 48000 && count % 480 == 0 && _inFifoCount == 0 && _outFifoCount == 0)
			{
				for (int j = 0; j < count; j += 480)
				{
					ProcessExact480Frame(samples, j);
				}
			}
			else
			{
				ProcessBufferedAndResampled(samples, count);
			}
		}

		private void ProcessExact480Frame(float[] buf, int offset)
		{
			for (int i = 0; i < 480; i++)
			{
				_rnIn[i] = buf[offset + i] * 32768f;
			}
			ApplyMixAndNeuralVad(vadProb: LastVadProbability = RnNoiseNative.rnnoise_process_frame(_state, _rnOut, _rnIn), dryAndDest: buf, offset: offset, rnOutPcm: _rnOut, fromPcm: 3.0517578E-05f);
		}

		private void ApplyMixAndNeuralVad(float[] dryAndDest, int offset, float[] rnOutPcm, float fromPcm, float vadProb)
		{
			float num = Math.Max(0f, Math.Min(1f, ModConfig.AiStrength.Value));
			bool value = ModConfig.AiSpeechGateEnabled.Value;
			float value2 = ModConfig.AiSpeechGateThreshold.Value;
			int vadHoldSamplesRemaining = (int)((float)ModConfig.GateHoldTimeMs.Value * 48f);
			if (!value || vadProb >= value2)
			{
				_vadHoldSamplesRemaining = vadHoldSamplesRemaining;
			}
			float num2 = ((!value || _vadHoldSamplesRemaining > 0) ? 1f : 0f);
			float num3 = 0.004166667f;
			float num4 = 0.00052083336f;
			for (int i = 0; i < 480; i++)
			{
				if (_vadHoldSamplesRemaining > 0)
				{
					_vadHoldSamplesRemaining--;
					num2 = 1f;
				}
				else if (value)
				{
					num2 = 0f;
				}
				if (_vadGain < num2)
				{
					_vadGain += num3;
					if (_vadGain > num2)
					{
						_vadGain = num2;
					}
				}
				else if (_vadGain > num2)
				{
					_vadGain -= num4;
					if (_vadGain < num2)
					{
						_vadGain = num2;
					}
				}
				float num5 = rnOutPcm[i] * fromPcm;
				float num6 = dryAndDest[offset + i];
				float num7 = num6 + (num5 - num6) * num;
				dryAndDest[offset + i] = num7 * _vadGain;
			}
		}

		private void ProcessBufferedAndResampled(float[] samples, int count)
		{
			double num = 48000.0 / (double)_sampleRate;
			int num2 = Math.Max(1, (int)Math.Round((double)count * num));
			if (_inFifoCount + num2 > _inFifo.Length)
			{
				_inFifoCount = 0;
				_outFifoCount = 0;
			}
			for (int i = 0; i < num2; i++)
			{
				double num3 = (double)i / num;
				int num4 = (int)num3;
				int num5 = Math.Min(num4 + 1, count - 1);
				float num6 = (float)(num3 - (double)num4);
				_inFifo[_inFifoCount++] = samples[num4] + (samples[num5] - samples[num4]) * num6;
			}
			while (_inFifoCount >= 480)
			{
				for (int j = 0; j < 480; j++)
				{
					_rnIn[j] = _inFifo[j] * 32768f;
				}
				ApplyMixAndNeuralVad(vadProb: LastVadProbability = RnNoiseNative.rnnoise_process_frame(_state, _rnOut, _rnIn), dryAndDest: _inFifo, offset: 0, rnOutPcm: _rnOut, fromPcm: 3.0517578E-05f);
				if (_outFifoCount + 480 <= _outFifo.Length)
				{
					Array.Copy(_inFifo, 0, _outFifo, _outFifoCount, 480);
					_outFifoCount += 480;
				}
				_inFifoCount -= 480;
				if (_inFifoCount > 0)
				{
					Array.Copy(_inFifo, 480, _inFifo, 0, _inFifoCount);
				}
			}
			if (_outFifoCount >= num2)
			{
				for (int k = 0; k < count; k++)
				{
					double num7 = (double)k * num;
					int num8 = Math.Min((int)num7, num2 - 1);
					int num9 = Math.Min(num8 + 1, num2 - 1);
					float num10 = (float)(num7 - (double)num8);
					samples[k] = _outFifo[num8] + (_outFifo[num9] - _outFifo[num8]) * num10;
				}
				_outFifoCount -= num2;
				if (_outFifoCount > 0)
				{
					Array.Copy(_outFifo, num2, _outFifo, 0, _outFifoCount);
				}
			}
			else
			{
				Array.Clear(samples, 0, count);
			}
		}

		public void Dispose()
		{
			if (!_disposed)
			{
				_disposed = true;
				if (_state != IntPtr.Zero)
				{
					RnNoiseNative.rnnoise_destroy(_state);
					_state = IntPtr.Zero;
				}
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "AirportMicFix";

		public const string PLUGIN_NAME = "AirportMicFix";

		public const string PLUGIN_VERSION = "1.1.0";
	}
}