Decompiled source of BetterVoice v1.0.1

BepInEx\plugins\BetterVoice\BetterVoice.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BetterVoice.Networking;
using BetterVoice.Patches;
using Dissonance;
using Dissonance.Audio.Capture;
using Dissonance.Config;
using Dissonance.Integrations.Unity_NFGO;
using Dissonance.Networking;
using GameNetcodeStuff;
using HarmonyLib;
using LethalConfig;
using LethalConfig.ConfigItems;
using LethalConfig.ConfigItems.Options;
using Microsoft.CodeAnalysis;
using Netcode.Transports.Facepunch;
using Steamworks;
using Steamworks.Data;
using Unity.Netcode;
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("BetterVoice")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+c5f9c4c5eac54548849ef393bb8a24d48db3f849")]
[assembly: AssemblyProduct("BetterVoice")]
[assembly: AssemblyTitle("BetterVoice")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BetterVoice
{
	internal static class LethalConfigCompat
	{
		[Serializable]
		[CompilerGenerated]
		private sealed class <>c
		{
			public static readonly <>c <>9 = new <>c();

			public static GenericButtonHandler <>9__0_0;

			internal void <Register>b__0_0()
			{
				SteamP2PVoiceManager.Instance?.ForceRefreshConnections();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal static void Register()
		{
			//IL_001f: 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_002c: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Expected O, but got Unknown
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00bb: 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_00cb: Expected O, but got Unknown
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Expected O, but got Unknown
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Expected O, but got Unknown
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Expected O, but got Unknown
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			//IL_011f: 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_012f: Expected O, but got Unknown
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Expected O, but got Unknown
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Expected O, but got Unknown
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Expected O, but got Unknown
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Expected O, but got Unknown
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_017e: Expected O, but got Unknown
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Expected O, but got Unknown
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Expected O, but got Unknown
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Expected O, but got Unknown
			//IL_01a5: 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_01b6: Expected O, but got Unknown
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bc: Expected O, but got Unknown
			//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_01d2: Expected O, but got Unknown
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Expected O, but got Unknown
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Expected O, but got Unknown
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Expected O, but got Unknown
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Expected O, but got Unknown
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Expected O, but got Unknown
			//IL_020b: 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)
			//IL_021c: Expected O, but got Unknown
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Expected O, but got Unknown
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0238: Expected O, but got Unknown
			//IL_0233: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Expected O, but got Unknown
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Expected O, but got Unknown
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_026b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Expected O, but got Unknown
			Assembly assembly = typeof(Plugin).Assembly;
			LethalConfigManager.SetModDescription("Fixes Lethal Company voice chat quality, delayed/missing player voice binding, hitch mic resets, transport Nagle buffering, and optionally routes voice directly over Steam SDR P2P between modded peers.");
			ConfigEntry<int> opusBitrateKbps = Plugin.OpusBitrateKbps;
			IntSliderOptions val = new IntSliderOptions();
			((BaseRangeOptions<int>)val).Min = 16;
			((BaseRangeOptions<int>)val).Max = 96;
			((BaseOptions)val).RequiresRestart = false;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new IntSliderConfigItem(opusBitrateKbps, val), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)new EnumDropDownConfigItem<VoiceFrameSizeOption>(Plugin.FrameSize, new EnumDropDownOptions
			{
				RequiresRestart = false
			}), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(Plugin.ForwardErrorCorrection, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)(object)new EnumDropDownConfigItem<NoiseSuppressionLevels>(Plugin.NoiseSuppression, new EnumDropDownOptions
			{
				RequiresRestart = false
			}), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(Plugin.BackgroundNoiseRemovalRNNoise, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}), assembly);
			ConfigEntry<float> backgroundNoiseRemovalStrength = Plugin.BackgroundNoiseRemovalStrength;
			FloatSliderOptions val2 = new FloatSliderOptions();
			((BaseRangeOptions<float>)val2).Min = 0f;
			((BaseRangeOptions<float>)val2).Max = 1f;
			((BaseOptions)val2).RequiresRestart = false;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatSliderConfigItem(backgroundNoiseRemovalStrength, val2), assembly);
			ConfigEntry<float> clearVoiceHighCutoffHz = Plugin.ClearVoiceHighCutoffHz;
			FloatSliderOptions val3 = new FloatSliderOptions();
			((BaseRangeOptions<float>)val3).Min = 10000f;
			((BaseRangeOptions<float>)val3).Max = 22000f;
			((BaseOptions)val3).RequiresRestart = false;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatSliderConfigItem(clearVoiceHighCutoffHz, val3), assembly);
			ConfigEntry<float> wallOcclusionIntensity = Plugin.WallOcclusionIntensity;
			FloatSliderOptions val4 = new FloatSliderOptions();
			((BaseRangeOptions<float>)val4).Min = 0f;
			((BaseRangeOptions<float>)val4).Max = 1f;
			((BaseOptions)val4).RequiresRestart = false;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new FloatSliderConfigItem(wallOcclusionIntensity, val4), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(Plugin.DisableFacilityVoiceReverb, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(Plugin.FixVoiceBindingAndRejoin, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(Plugin.PreventHitchMicReset, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(Plugin.DisableTransportNagle, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(Plugin.EnableSteamP2PVoice, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}), assembly);
			ConfigEntry<int> p2PVirtualPort = Plugin.P2PVirtualPort;
			IntSliderOptions val5 = new IntSliderOptions();
			((BaseRangeOptions<int>)val5).Min = 1;
			((BaseRangeOptions<int>)val5).Max = 255;
			((BaseOptions)val5).RequiresRestart = false;
			LethalConfigManager.AddConfigItem((BaseConfigItem)new IntSliderConfigItem(p2PVirtualPort, val5), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(Plugin.P2PImmediateSend, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}), assembly);
			LethalConfigManager.AddConfigItem((BaseConfigItem)new BoolCheckBoxConfigItem(Plugin.LogP2PEvents, new BoolCheckBoxOptions
			{
				RequiresRestart = false
			}), assembly);
			object obj = <>c.<>9__0_0;
			if (obj == null)
			{
				GenericButtonHandler val6 = delegate
				{
					SteamP2PVoiceManager.Instance?.ForceRefreshConnections();
				};
				<>c.<>9__0_0 = val6;
				obj = (object)val6;
			}
			LethalConfigManager.AddConfigItem((BaseConfigItem)new GenericButtonConfigItem("4. Steam P2P Voice", "Reconnect P2P Peers", "Re-scans the current Steam lobby and refreshes direct P2P voice tunnels.", "Reconnect", (GenericButtonHandler)obj), assembly);
		}
	}
	public enum VoiceFrameSizeOption
	{
		Tiny_10ms,
		Small_20ms,
		Medium_40ms_Vanilla,
		Large_60ms
	}
	[BepInPlugin("BetterVoice", "BetterVoice", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal const string LethalConfigGuid = "ainavt.lc.lethalconfig";

		private Harmony _harmony;

		internal static ManualLogSource Logger { get; private set; }

		internal static ConfigEntry<int> OpusBitrateKbps { get; private set; }

		internal static ConfigEntry<VoiceFrameSizeOption> FrameSize { get; private set; }

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

		internal static ConfigEntry<NoiseSuppressionLevels> NoiseSuppression { get; private set; }

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

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

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

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

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

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

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

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

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

		internal static ConfigEntry<int> P2PVirtualPort { get; private set; }

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

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

		private void Awake()
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			BindConfig();
			if (Chainloader.PluginInfos.ContainsKey("ainavt.lc.lethalconfig"))
			{
				try
				{
					LethalConfigCompat.Register();
				}
				catch (Exception ex)
				{
					Logger.LogWarning((object)("Failed to register LethalConfig entries: " + ex.Message));
				}
			}
			SteamP2PVoiceManager.EnsureInitialized();
			_harmony = new Harmony("BetterVoice");
			AudioQualityPatches.ApplyPatches(_harmony);
			AudioFilterPatches.ApplyPatches(_harmony);
			CapturePatches.ApplyPatches(_harmony);
			TransportPatches.ApplyPatches(_harmony);
			VoiceBindingPatches.ApplyPatches(_harmony);
			DissonanceP2PPatches.ApplyPatches(_harmony);
			int num = 0;
			foreach (MethodBase patchedMethod in _harmony.GetPatchedMethods())
			{
				num++;
				Logger.LogDebug((object)("Patched: " + patchedMethod.DeclaringType?.Name + "." + patchedMethod.Name));
			}
			Logger.LogInfo((object)string.Format("{0} v{1} loaded ({2} patched methods).", "BetterVoice", "1.0.0", num));
		}

		private void BindConfig()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Expected O, but got Unknown
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Expected O, but got Unknown
			//IL_015c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Expected O, but got Unknown
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			OpusBitrateKbps = ((BaseUnityPlugin)this).Config.Bind<int>("1. Audio Quality", "OpusBitrateKbps", 48, new ConfigDescription("Outgoing Opus voice bitrate in kbps (Vanilla Medium = 17, High = 24). Takes effect immediately and is compatible with vanilla players.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(16, 96), Array.Empty<object>()));
			FrameSize = ((BaseUnityPlugin)this).Config.Bind<VoiceFrameSizeOption>("1. Audio Quality", "FrameSize", VoiceFrameSizeOption.Small_20ms, "Opus frame duration. Smaller frames (20ms) reduce voice latency compared to vanilla (40ms). Applies when joining or hosting a lobby.");
			ForwardErrorCorrection = ((BaseUnityPlugin)this).Config.Bind<bool>("1. Audio Quality", "ForwardErrorCorrection", true, "Enables Opus in-band Forward Error Correction (FEC) to recover from occasional dropped voice packets.");
			NoiseSuppression = ((BaseUnityPlugin)this).Config.Bind<NoiseSuppressionLevels>("1. Audio Quality", "NoiseSuppression", (NoiseSuppressionLevels)1, "WebRTC microphone noise suppression level. Lower or disable if your voice sounds robotic.");
			BackgroundNoiseRemovalRNNoise = ((BaseUnityPlugin)this).Config.Bind<bool>("1. Audio Quality", "BackgroundNoiseRemovalRNNoise", false, "Enables Dissonance's built-in RNNoise neural background sound suppression (fans, keyboard noise).");
			BackgroundNoiseRemovalStrength = ((BaseUnityPlugin)this).Config.Bind<float>("1. Audio Quality", "BackgroundNoiseRemovalStrength", 0.65f, new ConfigDescription("Wet mix for RNNoise background removal when enabled (0 = bypass, 1 = full suppression).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			ClearVoiceHighCutoffHz = ((BaseUnityPlugin)this).Config.Bind<float>("2. Filters & Immersion", "ClearVoiceHighCutoffHz", 20000f, new ConfigDescription("Low-pass filter cutoff frequency (Hz) for unoccluded nearby player voices (Vanilla = 10000 Hz).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10000f, 22000f), Array.Empty<object>()));
			WallOcclusionIntensity = ((BaseUnityPlugin)this).Config.Bind<float>("2. Filters & Immersion", "WallOcclusionIntensity", 0.75f, new ConfigDescription("How strongly walls/geometry muffle voices (1.0 = vanilla occlusion, 0.0 = no wall muffling).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			DisableFacilityVoiceReverb = ((BaseUnityPlugin)this).Config.Bind<bool>("2. Filters & Immersion", "DisableFacilityVoiceReverb", false, "Disables the indoor AudioReverbFilter on player voices inside the facility.");
			FixVoiceBindingAndRejoin = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Stability & Binding Fixes", "FixVoiceBindingAndRejoin", true, "Fixes StartOfRound's 12-second voice delay, playback object linking skip bug, and stale disconnect references that leave random players unheard.");
			PreventHitchMicReset = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Stability & Binding Fixes", "PreventHitchMicReset", true, "Prevents Dissonance's FrameSkipDetector from resetting your microphone capture during FPS hitches or level loading (< 2s stalls).");
			DisableTransportNagle = ((BaseUnityPlugin)this).Config.Bind<bool>("3. Stability & Binding Fixes", "DisableTransportNagle", true, "Forces FacepunchTransport to flush unreliable Netcode/voice packets with SendType.NoNagle instead of buffering them.");
			EnableSteamP2PVoice = ((BaseUnityPlugin)this).Config.Bind<bool>("4. Steam P2P Voice", "EnableSteamP2PVoice", true, "Uses Valve's Steam Datagram Relay (SteamNetworkingSockets) to send voice directly between modded peers in the lobby (no external server). Automatically falls back to the vanilla host relay for unmodded players.");
			P2PVirtualPort = ((BaseUnityPlugin)this).Config.Bind<int>("4. Steam P2P Voice", "P2PVirtualPort", 77, new ConfigDescription("SteamNetworkingSockets virtual port for direct P2P voice (vanilla Netcode uses 0). Modded peers must match.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 255), Array.Empty<object>()));
			P2PImmediateSend = ((BaseUnityPlugin)this).Config.Bind<bool>("4. Steam P2P Voice", "P2PImmediateSend", true, "Uses SendType.NoNagle | SendType.NoDelay for direct P2P voice packets to minimize latency.");
			LogP2PEvents = ((BaseUnityPlugin)this).Config.Bind<bool>("4. Steam P2P Voice", "LogP2PEvents", false, "Logs Steam P2P peer connections, handshakes, and fallback status to the BepInEx console.");
			OpusBitrateKbps.SettingChanged += delegate
			{
				AudioQualityPatches.ApplyLiveVoiceSettings();
			};
			FrameSize.SettingChanged += delegate
			{
				AudioQualityPatches.ApplyLiveVoiceSettings();
			};
			ForwardErrorCorrection.SettingChanged += delegate
			{
				AudioQualityPatches.ApplyLiveVoiceSettings();
			};
			NoiseSuppression.SettingChanged += delegate
			{
				AudioQualityPatches.ApplyLiveVoiceSettings();
			};
			BackgroundNoiseRemovalRNNoise.SettingChanged += delegate
			{
				AudioQualityPatches.ApplyLiveVoiceSettings();
			};
			BackgroundNoiseRemovalStrength.SettingChanged += delegate
			{
				AudioQualityPatches.ApplyLiveVoiceSettings();
			};
			EnableSteamP2PVoice.SettingChanged += delegate
			{
				SteamP2PVoiceManager.Instance?.OnConfigChanged();
			};
			P2PVirtualPort.SettingChanged += delegate
			{
				SteamP2PVoiceManager.Instance?.OnPortChanged();
			};
		}

		internal static FrameSize ToDissonanceFrameSize(VoiceFrameSizeOption option)
		{
			//IL_0019: 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_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: 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_0029: Unknown result type (might be due to invalid IL or missing references)
			return (FrameSize)(option switch
			{
				VoiceFrameSizeOption.Tiny_10ms => -1, 
				VoiceFrameSizeOption.Small_20ms => 0, 
				VoiceFrameSizeOption.Medium_40ms_Vanilla => 1, 
				VoiceFrameSizeOption.Large_60ms => 2, 
				_ => 0, 
			});
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "BetterVoice";

		public const string PLUGIN_NAME = "BetterVoice";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace BetterVoice.Patches
{
	internal static class AudioFilterPatches
	{
		private sealed class CachedVoiceFlags
		{
			public bool IsPlayerVoice;
		}

		private static readonly ConditionalWeakTable<OccludeAudio, CachedVoiceFlags> VoiceCache = new ConditionalWeakTable<OccludeAudio, CachedVoiceFlags>();

		private static readonly FieldRef<OccludeAudio, AudioLowPassFilter> LowPassFilterRef = AccessTools.FieldRefAccess<OccludeAudio, AudioLowPassFilter>("lowPassFilter");

		private static readonly FieldRef<OccludeAudio, AudioReverbFilter> ReverbFilterRef = AccessTools.FieldRefAccess<OccludeAudio, AudioReverbFilter>("reverbFilter");

		private static readonly FieldRef<OccludeAudio, bool> OccludedRef = AccessTools.FieldRefAccess<OccludeAudio, bool>("occluded");

		private static readonly FieldRef<OccludeAudio, AudioSource> ThisAudioRef = AccessTools.FieldRefAccess<OccludeAudio, AudioSource>("thisAudio");

		internal static void ApplyPatches(Harmony harmony)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Expected O, but got Unknown
			//IL_0054: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(OccludeAudio), "Update", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(AudioFilterPatches), "OccludeAudioUpdatePrefix", (Type[])null), new HarmonyMethod(typeof(AudioFilterPatches), "OccludeAudioUpdatePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool IsPlayerVoice(OccludeAudio instance)
		{
			if (VoiceCache.TryGetValue(instance, out var value))
			{
				return value.IsPlayerVoice;
			}
			bool flag = (Object)(object)((Component)instance).GetComponent<PlayerVoiceIngameSettings>() != (Object)null;
			VoiceCache.Add(instance, new CachedVoiceFlags
			{
				IsPlayerVoice = flag
			});
			return flag;
		}

		private static void OccludeAudioUpdatePrefix(OccludeAudio __instance, out float __state)
		{
			__state = -1f;
			if (!((Object)(object)__instance == (Object)null) && IsPlayerVoice(__instance))
			{
				AudioLowPassFilter val = LowPassFilterRef.Invoke(__instance);
				if ((Object)(object)val != (Object)null)
				{
					__state = val.cutoffFrequency;
				}
			}
		}

		private static void OccludeAudioUpdatePostfix(OccludeAudio __instance, float __state)
		{
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || __state < 0f || !IsPlayerVoice(__instance))
			{
				return;
			}
			AudioSource val = ThisAudioRef.Invoke(__instance);
			if ((Object)(object)val != (Object)null && val.isVirtual)
			{
				return;
			}
			if (Plugin.DisableFacilityVoiceReverb.Value && __instance.useReverb)
			{
				AudioReverbFilter val2 = ReverbFilterRef.Invoke(__instance);
				if ((Object)(object)val2 != (Object)null)
				{
					((Behaviour)val2).enabled = false;
				}
			}
			if (__instance.overridingLowPass)
			{
				return;
			}
			AudioLowPassFilter val3 = LowPassFilterRef.Invoke(__instance);
			if ((Object)(object)val3 == (Object)null)
			{
				return;
			}
			float value = Plugin.ClearVoiceHighCutoffHz.Value;
			if (!OccludedRef.Invoke(__instance))
			{
				if (value > 10001f)
				{
					val3.cutoffFrequency = Mathf.Lerp(__state, value, Time.deltaTime * 8f);
				}
				return;
			}
			float value2 = Plugin.WallOcclusionIntensity.Value;
			if (value2 < 0.999f && (Object)(object)StartOfRound.Instance != (Object)null && (Object)(object)StartOfRound.Instance.audioListener != (Object)null && (Object)(object)val != (Object)null)
			{
				float num = Vector3.Distance(((Component)StartOfRound.Instance.audioListener).transform.position, ((Component)__instance).transform.position) / Mathf.Max(0.01f, val.maxDistance / 2f);
				float num2 = ((num > 0.0001f) ? Mathf.Clamp(2500f / num, 900f, 4000f) : 4000f);
				float num3 = Mathf.Lerp(value, num2, value2);
				val3.cutoffFrequency = Mathf.Lerp(__state, num3, Time.deltaTime * 8f);
			}
		}
	}
	internal static class AudioQualityPatches
	{
		private static readonly Type OpusEncoderType = AccessTools.TypeByName("Dissonance.Audio.Codecs.Opus.OpusEncoder");

		private static readonly Type CodecSettingsLoaderType = AccessTools.TypeByName("Dissonance.CodecSettingsLoader");

		private static readonly FieldInfo OpusNativeEncoderField = ((OpusEncoderType != null) ? AccessTools.Field(OpusEncoderType, "_encoder") : null);

		private static readonly PropertyInfo NativeBitrateProperty = ((OpusNativeEncoderField != null) ? AccessTools.Property(OpusNativeEncoderField.FieldType, "Bitrate") : null);

		private static readonly List<WeakReference<object>> ActiveEncoders = new List<WeakReference<object>>();

		internal static void ApplyPatches(Harmony harmony)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Expected O, but got Unknown
			if (OpusEncoderType != null)
			{
				MethodInfo methodInfo = AccessTools.Method(OpusEncoderType, "GetTargetBitrate", new Type[1] { typeof(AudioQuality) }, (Type[])null);
				if (methodInfo != null)
				{
					harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(AudioQualityPatches), "GetTargetBitratePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				ConstructorInfo constructorInfo = AccessTools.Constructor(OpusEncoderType, new Type[3]
				{
					typeof(AudioQuality),
					typeof(FrameSize),
					typeof(bool)
				}, false);
				if (constructorInfo != null)
				{
					harmony.Patch((MethodBase)constructorInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(AudioQualityPatches), "OpusEncoderCtorPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			else
			{
				Plugin.Logger.LogWarning((object)"Could not find Dissonance OpusEncoder type; bitrate patch skipped.");
			}
			if (CodecSettingsLoaderType != null)
			{
				MethodInfo methodInfo2 = AccessTools.Method(CodecSettingsLoaderType, "Start", (Type[])null, (Type[])null);
				if (methodInfo2 != null)
				{
					harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(AudioQualityPatches), "CodecSettingsLoaderStartPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			else
			{
				Plugin.Logger.LogWarning((object)"Could not find Dissonance CodecSettingsLoader type; frame size/FEC patch skipped.");
			}
		}

		internal static void ApplyLiveVoiceSettings()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				VoiceSettings instance = VoiceSettings.Instance;
				instance.Quality = (AudioQuality)2;
				instance.FrameSize = Plugin.ToDissonanceFrameSize(Plugin.FrameSize.Value);
				instance.ForwardErrorCorrection = Plugin.ForwardErrorCorrection.Value;
				instance.DenoiseAmount = Plugin.NoiseSuppression.Value;
				instance.BackgroundSoundRemovalEnabled = Plugin.BackgroundNoiseRemovalRNNoise.Value;
				instance.BackgroundSoundRemovalAmount = Plugin.BackgroundNoiseRemovalStrength.Value;
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)("Failed to apply VoiceSettings: " + ex.Message));
			}
			UpdateActiveOpusEncoders();
		}

		private static void UpdateActiveOpusEncoders()
		{
			if (OpusNativeEncoderField == null || NativeBitrateProperty == null)
			{
				return;
			}
			int num = Plugin.OpusBitrateKbps.Value * 1000;
			lock (ActiveEncoders)
			{
				for (int num2 = ActiveEncoders.Count - 1; num2 >= 0; num2--)
				{
					if (!ActiveEncoders[num2].TryGetTarget(out var target) || target == null)
					{
						ActiveEncoders.RemoveAt(num2);
					}
					else
					{
						try
						{
							object value = OpusNativeEncoderField.GetValue(target);
							if (value != null)
							{
								NativeBitrateProperty.SetValue(value, num);
							}
						}
						catch
						{
							ActiveEncoders.RemoveAt(num2);
						}
					}
				}
			}
		}

		private static void CodecSettingsLoaderStartPrefix()
		{
			ApplyLiveVoiceSettings();
		}

		private static void GetTargetBitratePostfix(ref int __result)
		{
			__result = Plugin.OpusBitrateKbps.Value * 1000;
		}

		private static void OpusEncoderCtorPostfix(object __instance)
		{
			if (__instance != null)
			{
				lock (ActiveEncoders)
				{
					ActiveEncoders.Add(new WeakReference<object>(__instance));
				}
				UpdateActiveOpusEncoders();
			}
		}
	}
	internal static class CapturePatches
	{
		private static readonly Type FrameSkipDetectorType = AccessTools.TypeByName("Dissonance.FrameSkipDetector");

		internal static void ApplyPatches(Harmony harmony)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			if (FrameSkipDetectorType == null)
			{
				Plugin.Logger.LogWarning((object)"Could not find Dissonance.FrameSkipDetector; hitch mic-reset patch skipped.");
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(FrameSkipDetectorType, "IsFrameSkip", new Type[1] { typeof(float) }, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(CapturePatches), "IsFrameSkipPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool IsFrameSkipPrefix(float deltaTime, ref bool __result)
		{
			if (Plugin.PreventHitchMicReset.Value && deltaTime < 2f)
			{
				__result = false;
				return false;
			}
			return true;
		}
	}
	internal static class DissonanceP2PPatches
	{
		private static readonly Type BaseClientType = typeof(BaseClient<NfgoServer, NfgoClient, NfgoConn>);

		internal static void ApplyPatches(Harmony harmony)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Expected O, but got Unknown
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Expected O, but got Unknown
			//IL_0210: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Expected O, but got Unknown
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(NfgoClient), "Connect", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(DissonanceP2PPatches), "NfgoClientConnectPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(NfgoClient), "Disconnect", (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(DissonanceP2PPatches), "NfgoClientDisconnectPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo3 = AccessTools.Method(BaseClientType, "OnServerAssignedSessionId", new Type[2]
			{
				typeof(uint),
				typeof(ushort)
			}, (Type[])null);
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(DissonanceP2PPatches), "OnServerAssignedSessionIdPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo4 = AccessTools.Method(BaseClientType, "SendUnreliableP2P", new Type[2]
			{
				typeof(List<ClientInfo<NfgoConn?>>),
				typeof(ArraySegment<byte>)
			}, (Type[])null);
			if (methodInfo4 != null)
			{
				harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(DissonanceP2PPatches), "SendUnreliableP2PPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo5 = AccessTools.Method(BaseClientType, "SendReliableP2P", new Type[2]
			{
				typeof(List<ClientInfo<NfgoConn?>>),
				typeof(ArraySegment<byte>)
			}, (Type[])null);
			if (methodInfo5 != null)
			{
				harmony.Patch((MethodBase)methodInfo5, new HarmonyMethod(typeof(DissonanceP2PPatches), "SendReliableP2PPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo6 = AccessTools.Method(typeof(GameNetworkManager), "LeaveCurrentSteamLobby", (Type[])null, (Type[])null);
			if (methodInfo6 != null)
			{
				harmony.Patch((MethodBase)methodInfo6, new HarmonyMethod(typeof(DissonanceP2PPatches), "LeaveLobbyPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo7 = AccessTools.Method(typeof(GameNetworkManager), "StartDisconnect", (Type[])null, (Type[])null);
			if (methodInfo7 != null)
			{
				harmony.Patch((MethodBase)methodInfo7, (HarmonyMethod)null, new HarmonyMethod(typeof(DissonanceP2PPatches), "StartDisconnectPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo8 = AccessTools.Method(typeof(GameNetworkManager), "Disconnect", (Type[])null, (Type[])null);
			if (methodInfo8 != null)
			{
				harmony.Patch((MethodBase)methodInfo8, (HarmonyMethod)null, new HarmonyMethod(typeof(DissonanceP2PPatches), "StartDisconnectPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static void NfgoClientConnectPostfix(NfgoClient __instance)
		{
			SteamP2PVoiceManager.EnsureInitialized();
			SteamP2PVoiceManager.Instance?.OnClientConnected(__instance);
		}

		private static void NfgoClientDisconnectPrefix(NfgoClient __instance)
		{
			SteamP2PVoiceManager.Instance?.OnClientDisconnected(__instance);
		}

		private static void OnServerAssignedSessionIdPostfix(object __instance, uint session, ushort id)
		{
			NfgoClient val = (NfgoClient)((__instance is NfgoClient) ? __instance : null);
			if (val != null)
			{
				SteamP2PVoiceManager.EnsureInitialized();
				SteamP2PVoiceManager.Instance?.SetDissonanceSession(val, session, id);
			}
		}

		private static bool SendUnreliableP2PPrefix(object __instance, List<ClientInfo<NfgoConn?>> destinations, ArraySegment<byte> packet)
		{
			NfgoClient val = (NfgoClient)((__instance is NfgoClient) ? __instance : null);
			if (val != null && (Object)(object)SteamP2PVoiceManager.Instance != (Object)null)
			{
				return !SteamP2PVoiceManager.Instance.TrySendP2P(val, destinations, packet, reliable: false);
			}
			return true;
		}

		private static bool SendReliableP2PPrefix(object __instance, List<ClientInfo<NfgoConn?>> destinations, ArraySegment<byte> packet)
		{
			NfgoClient val = (NfgoClient)((__instance is NfgoClient) ? __instance : null);
			if (val != null && (Object)(object)SteamP2PVoiceManager.Instance != (Object)null)
			{
				return !SteamP2PVoiceManager.Instance.TrySendP2P(val, destinations, packet, reliable: true);
			}
			return true;
		}

		private static void LeaveLobbyPrefix()
		{
			SteamP2PVoiceManager.Instance?.OnLobbyLeftOrDisconnected();
		}

		private static void StartDisconnectPostfix()
		{
			SteamP2PVoiceManager.Instance?.OnLobbyLeftOrDisconnected();
		}
	}
	internal static class TransportPatches
	{
		internal static void ApplyPatches(Harmony harmony)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(FacepunchTransport), "NetworkDeliveryToSendType", new Type[1] { typeof(NetworkDelivery) }, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(TransportPatches), "NetworkDeliveryToSendTypePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			else
			{
				Plugin.Logger.LogWarning((object)"Could not find FacepunchTransport.NetworkDeliveryToSendType; NoNagle patch skipped.");
			}
		}

		private static void NetworkDeliveryToSendTypePostfix(NetworkDelivery delivery, ref SendType __result)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			if (Plugin.DisableTransportNagle.Value && ((int)delivery == 0 || (int)delivery == 1))
			{
				__result = (SendType)1;
			}
		}
	}
	internal static class VoiceBindingPatches
	{
		private static readonly FieldRef<StartOfRound, float> UpdateVoiceIntervalRef = AccessTools.FieldRefAccess<StartOfRound, float>("updatePlayerVoiceInterval");

		private static float _nextUnboundRefreshTime;

		internal static void ApplyPatches(Harmony harmony)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Expected O, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Expected O, but got Unknown
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Expected O, but got Unknown
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(StartOfRound), "RefreshPlayerVoicePlaybackObjects", (Type[])null, (Type[])null);
			if (methodInfo != null)
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(VoiceBindingPatches), "RefreshPlayerVoicePlaybackObjectsPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(StartOfRound), "OnPlayerDC", (Type[])null, (Type[])null);
			if (methodInfo2 != null)
			{
				harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(VoiceBindingPatches), "OnPlayerDCPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo3 = AccessTools.Method(typeof(StartOfRound), "LateUpdate", (Type[])null, (Type[])null);
			if (methodInfo3 != null)
			{
				harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(VoiceBindingPatches), "StartOfRoundLateUpdatePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo4 = AccessTools.Method(typeof(StartOfRound), "UpdatePlayerVoiceEffectsOnDelay", (Type[])null, (Type[])null);
			if (methodInfo4 != null)
			{
				harmony.Patch((MethodBase)methodInfo4, new HarmonyMethod(typeof(VoiceBindingPatches), "UpdateEffectsOnDelayPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo5 = AccessTools.Method(typeof(NfgoPlayer), "StartTracking", (Type[])null, (Type[])null);
			if (methodInfo5 != null)
			{
				harmony.Patch((MethodBase)methodInfo5, (HarmonyMethod)null, new HarmonyMethod(typeof(VoiceBindingPatches), "NfgoPlayerStartTrackingPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			MethodInfo methodInfo6 = AccessTools.Method(typeof(NfgoPlayerModified), "StartTracking", (Type[])null, (Type[])null);
			if (methodInfo6 != null)
			{
				harmony.Patch((MethodBase)methodInfo6, (HarmonyMethod)null, new HarmonyMethod(typeof(VoiceBindingPatches), "NfgoPlayerStartTrackingPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
		}

		private static bool RefreshPlayerVoicePlaybackObjectsPrefix(StartOfRound __instance)
		{
			if (!Plugin.FixVoiceBindingAndRejoin.Value)
			{
				return true;
			}
			if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
			{
				return false;
			}
			PlayerVoiceIngameSettings[] array = Object.FindObjectsOfType<PlayerVoiceIngameSettings>(true);
			PlayerControllerB[] allPlayerScripts = __instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if ((Object)(object)val == (Object)null || (!val.isPlayerControlled && !val.isPlayerDead))
				{
					continue;
				}
				IDissonancePlayer componentInChildren = ((Component)val).gameObject.GetComponentInChildren<IDissonancePlayer>();
				string text = ((componentInChildren != null) ? componentInChildren.PlayerId : null);
				if (string.IsNullOrEmpty(text))
				{
					continue;
				}
				foreach (PlayerVoiceIngameSettings val2 in array)
				{
					if ((Object)(object)val2 == (Object)null || !((Behaviour)val2).isActiveAndEnabled)
					{
						continue;
					}
					if (val2._playerState == null)
					{
						val2.FindPlayerIfNull();
					}
					if (val2._playerState != null && !(val2._playerState.Name != text))
					{
						if ((Object)(object)val2.voiceAudio == (Object)null)
						{
							val2.InitializeComponents();
						}
						val.voicePlayerState = val2._playerState;
						val.currentVoiceChatAudioSource = val2.voiceAudio;
						val.currentVoiceChatIngameSettings = val2;
						if ((Object)(object)val2.voiceAudio != (Object)null && (Object)(object)SoundManager.Instance != (Object)null && SoundManager.Instance.playerVoiceMixers != null && val.playerClientId < (ulong)SoundManager.Instance.playerVoiceMixers.Length)
						{
							val2.voiceAudio.outputAudioMixerGroup = SoundManager.Instance.playerVoiceMixers[val.playerClientId];
						}
						break;
					}
				}
			}
			return false;
		}

		private static void OnPlayerDCPostfix(StartOfRound __instance, int playerObjectNumber)
		{
			if (Plugin.FixVoiceBindingAndRejoin.Value && __instance.allPlayerScripts != null && playerObjectNumber >= 0 && playerObjectNumber < __instance.allPlayerScripts.Length)
			{
				PlayerControllerB val = __instance.allPlayerScripts[playerObjectNumber];
				if ((Object)(object)val != (Object)null)
				{
					val.voicePlayerState = null;
					val.currentVoiceChatAudioSource = null;
					val.currentVoiceChatIngameSettings = null;
					val.voiceMuffledByEnemy = false;
				}
			}
		}

		private static void StartOfRoundLateUpdatePostfix(StartOfRound __instance)
		{
			if (!Plugin.FixVoiceBindingAndRejoin.Value || (Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null || __instance.allPlayerScripts == null || UpdateVoiceIntervalRef.Invoke(__instance) > 5f || Time.unscaledTime < _nextUnboundRefreshTime)
			{
				return;
			}
			PlayerControllerB localPlayerController = GameNetworkManager.Instance.localPlayerController;
			for (int i = 0; i < __instance.allPlayerScripts.Length; i++)
			{
				PlayerControllerB val = __instance.allPlayerScripts[i];
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)localPlayerController) && (val.isPlayerControlled || val.isPlayerDead) && (val.voicePlayerState == null || (Object)(object)val.currentVoiceChatAudioSource == (Object)null || (Object)(object)val.currentVoiceChatIngameSettings == (Object)null || val.currentVoiceChatIngameSettings._playerState == null))
				{
					_nextUnboundRefreshTime = Time.unscaledTime + 0.5f;
					UpdateVoiceIntervalRef.Invoke(__instance) = 5.01f;
					break;
				}
			}
		}

		private static void UpdateEffectsOnDelayPrefix(StartOfRound __instance)
		{
			if (Plugin.FixVoiceBindingAndRejoin.Value && !((Object)(object)__instance == (Object)null))
			{
				__instance.RefreshPlayerVoicePlaybackObjects();
				__instance.UpdatePlayerVoiceEffects();
			}
		}

		private static void NfgoPlayerStartTrackingPostfix()
		{
			if (Plugin.FixVoiceBindingAndRejoin.Value && !((Object)(object)StartOfRound.Instance == (Object)null))
			{
				StartOfRound.Instance.RefreshPlayerVoicePlaybackObjects();
				StartOfRound.Instance.UpdatePlayerVoiceEffects();
			}
		}
	}
}
namespace BetterVoice.Networking
{
	internal sealed class SteamP2PVoiceManager : MonoBehaviour
	{
		private sealed class OutgoingPeerState
		{
			public SteamId SteamId;

			public VoiceConnectionManager Manager;

			public int Attempts;

			public float NextAttemptTime;

			public bool IsConnected
			{
				get
				{
					if (Manager != null)
					{
						return ((ConnectionManager)Manager).Connected;
					}
					return false;
				}
			}

			public bool IsConnecting
			{
				get
				{
					if (Manager != null && ((ConnectionManager)Manager).Connecting)
					{
						return !((ConnectionManager)Manager).Connected;
					}
					return false;
				}
			}
		}

		private struct HelloInfo
		{
			public SteamId SteamId;

			public uint SessionId;

			public ushort DissonanceId;
		}

		private sealed class VoiceSocketManager : SocketManager
		{
			public override void OnConnecting(Connection connection, ConnectionInfo info)
			{
				//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_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_0048: Unknown result type (might be due to invalid IL or missing references)
				//IL_0054: 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_0026: Unknown result type (might be due to invalid IL or missing references)
				SteamId realRemoteSteamId = GetRealRemoteSteamId(in info);
				if (!IsSteamIdInCurrentLobby(realRemoteSteamId))
				{
					if (Plugin.LogP2PEvents.Value)
					{
						Plugin.Logger.LogWarning((object)$"Rejected P2P voice connection from {realRemoteSteamId} (not in current lobby).");
					}
					((Connection)(ref connection)).Close(false, 0, "Not in lobby");
				}
				else
				{
					((Connection)(ref connection)).Accept();
					if (!base.Connecting.Contains(connection))
					{
						base.Connecting.Add(connection);
					}
				}
			}

			public override void OnConnected(Connection connection, ConnectionInfo info)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: 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_0015: Unknown result type (might be due to invalid IL or missing references)
				((SocketManager)this).OnConnected(connection, info);
				Instance?.OnIncomingConnected(connection, GetRealRemoteSteamId(in info));
			}

			public override void OnDisconnected(Connection connection, ConnectionInfo info)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				((SocketManager)this).OnDisconnected(connection, info);
				Instance?.OnConnectionClosed(((Connection)(ref connection)).Id, GetRealRemoteSteamId(in info), isOutgoing: false, ((ConnectionInfo)(ref info)).EndReason, GetEndDebug(in info));
			}

			public override void OnMessage(Connection connection, NetIdentity identity, IntPtr data, int size, long messageNum, long recvTime, int channel)
			{
				//IL_000a: 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)
				Instance?.HandleRawMessage(connection, ((NetIdentity)(ref identity)).SteamId, data, size);
			}
		}

		private sealed class VoiceConnectionManager : ConnectionManager
		{
			public SteamId TargetSteamId;

			private bool _disconnectNotified;

			public override void OnConnected(ConnectionInfo info)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				((ConnectionManager)this).OnConnected(info);
				_disconnectNotified = false;
				SteamId realRemoteSteamId = GetRealRemoteSteamId(in info);
				SteamId peerId = ((TargetSteamId.Value != 0L) ? TargetSteamId : realRemoteSteamId);
				Instance?.OnOutgoingConnected(base.Connection, peerId);
			}

			public override void OnDisconnected(ConnectionInfo info)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0035: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				((ConnectionManager)this).OnDisconnected(info);
				if (!_disconnectNotified)
				{
					_disconnectNotified = true;
					SteamId realRemoteSteamId = GetRealRemoteSteamId(in info);
					SteamId peerId = ((TargetSteamId.Value != 0L) ? TargetSteamId : realRemoteSteamId);
					Instance?.OnConnectionClosed(((Connection)(ref base.Connection)).Id, peerId, isOutgoing: true, ((ConnectionInfo)(ref info)).EndReason, GetEndDebug(in info));
				}
			}

			public override void OnMessage(IntPtr data, int size, long messageNum, long recvTime, int channel)
			{
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: 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_0034: Unknown result type (might be due to invalid IL or missing references)
				SteamId senderId = ((TargetSteamId.Value != 0L) ? TargetSteamId : GetRealRemoteSteamId(((ConnectionManager)this).ConnectionInfo));
				Instance?.HandleRawMessage(base.Connection, senderId, data, size);
			}
		}

		private const byte PacketTypeHello = 1;

		private const byte PacketTypeDissonance = 2;

		private const float LobbyScanIntervalSeconds = 1.5f;

		private const float RetryBackoffSeconds = 6f;

		private const int MaxConnectRetriesPerPeer = 2;

		private static readonly FieldInfo ConnectionInfoIdentityField = AccessTools.Field(typeof(ConnectionInfo), "identity");

		private static readonly FieldInfo ConnectionInfoEndDebugField = AccessTools.Field(typeof(ConnectionInfo), "endDebug");

		private VoiceSocketManager _listenSocket;

		private int _activePort = -1;

		private ulong _activeLobbyId;

		private float _nextLobbyScanTime;

		private NfgoClient _activeClient;

		private bool _hasDissonanceSession;

		private uint _currentSessionId;

		private ushort _currentLocalId;

		private readonly Dictionary<ulong, OutgoingPeerState> _outgoingBySteamId = new Dictionary<ulong, OutgoingPeerState>();

		private readonly Dictionary<ulong, Connection> _incomingBySteamId = new Dictionary<ulong, Connection>();

		private readonly Dictionary<uint, HelloInfo> _helloByConnId = new Dictionary<uint, HelloInfo>();

		private readonly Dictionary<ushort, Connection> _dissonanceIdToConn = new Dictionary<ushort, Connection>();

		private readonly List<ClientInfo<NfgoConn?>> _relayFallbackScratch = new List<ClientInfo<NfgoConn?>>();

		private byte[] _sendScratch = new byte[2048];

		private byte[] _recvScratch = new byte[2048];

		internal static SteamP2PVoiceManager Instance { get; private set; }

		private static SteamId GetRealRemoteSteamId(in ConnectionInfo info)
		{
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: 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)
			if (ConnectionInfoIdentityField != null && ConnectionInfoIdentityField.GetValue(info) is NetIdentity val && ((NetIdentity)(ref val)).SteamId.Value != 0L)
			{
				return ((NetIdentity)(ref val)).SteamId;
			}
			ConnectionInfo val2 = info;
			NetIdentity identity = ((ConnectionInfo)(ref val2)).Identity;
			return ((NetIdentity)(ref identity)).SteamId;
		}

		private static string GetEndDebug(in ConnectionInfo info)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return (ConnectionInfoEndDebugField?.GetValue(info) as string) ?? string.Empty;
			}
			catch
			{
				return string.Empty;
			}
		}

		internal static void EnsureInitialized()
		{
			//IL_0013: 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_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			if (!((Object)(object)Instance != (Object)null))
			{
				GameObject val = new GameObject("BetterVoice_SteamP2PManager")
				{
					hideFlags = (HideFlags)61
				};
				Object.DontDestroyOnLoad((Object)val);
				Instance = val.AddComponent<SteamP2PVoiceManager>();
			}
		}

		private void Awake()
		{
			if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
			else
			{
				Instance = this;
			}
		}

		private void OnDestroy()
		{
			ShutdownP2P();
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		internal void OnConfigChanged()
		{
			if (!Plugin.EnableSteamP2PVoice.Value)
			{
				ShutdownP2P();
			}
			else
			{
				_nextLobbyScanTime = 0f;
			}
		}

		internal void OnPortChanged()
		{
			ShutdownP2P();
			_nextLobbyScanTime = 0f;
		}

		internal void ForceRefreshConnections()
		{
			ShutdownP2P();
			_nextLobbyScanTime = 0f;
			if (Plugin.LogP2PEvents.Value)
			{
				Plugin.Logger.LogInfo((object)"P2P peer refresh requested.");
			}
		}

		internal void OnClientConnected(NfgoClient client)
		{
			_activeClient = client;
			_nextLobbyScanTime = 0f;
		}

		internal void OnClientDisconnected(NfgoClient client)
		{
			if (_activeClient == client)
			{
				ClearDissonanceSession();
				_activeClient = null;
			}
		}

		internal void SetDissonanceSession(NfgoClient client, uint sessionId, ushort localId)
		{
			_activeClient = client;
			_currentSessionId = sessionId;
			_currentLocalId = localId;
			_hasDissonanceSession = true;
			RebuildDissonanceBindingsFromHellos();
			BroadcastHelloToAllConnected();
			if (Plugin.LogP2PEvents.Value)
			{
				Plugin.Logger.LogInfo((object)$"Dissonance session ready: Session={sessionId}, LocalId={localId}");
			}
		}

		internal void ClearDissonanceSession()
		{
			_hasDissonanceSession = false;
			_currentSessionId = 0u;
			_currentLocalId = 0;
			_dissonanceIdToConn.Clear();
		}

		internal void OnLobbyLeftOrDisconnected()
		{
			ClearDissonanceSession();
			_activeClient = null;
			ShutdownP2P();
		}

		private void Update()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: 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)
			if (!Plugin.EnableSteamP2PVoice.Value || !IsSteamLobbyActive(out var lobby))
			{
				if (_listenSocket != null || _outgoingBySteamId.Count > 0)
				{
					ShutdownP2P();
				}
				return;
			}
			if (_activeLobbyId != ((Lobby)(ref lobby)).Id.Value || _activePort != Plugin.P2PVirtualPort.Value)
			{
				ShutdownP2P();
				_activeLobbyId = ((Lobby)(ref lobby)).Id.Value;
				StartListenSocket();
				_nextLobbyScanTime = 0f;
			}
			else if (_listenSocket == null)
			{
				StartListenSocket();
			}
			PollMessages();
			if (Time.unscaledTime >= _nextLobbyScanTime)
			{
				_nextLobbyScanTime = Time.unscaledTime + 1.5f;
				SyncLobbyPeers(lobby);
			}
		}

		private void StartListenSocket()
		{
			if (!SteamClient.IsValid)
			{
				return;
			}
			int value = Plugin.P2PVirtualPort.Value;
			try
			{
				_listenSocket = SteamNetworkingSockets.CreateRelaySocket<VoiceSocketManager>(value);
				_activePort = value;
				if (Plugin.LogP2PEvents.Value)
				{
					Plugin.Logger.LogInfo((object)$"Opened Steam SDR P2P voice socket on virtual port {value}.");
				}
			}
			catch (Exception ex)
			{
				Plugin.Logger.LogWarning((object)$"Failed to open Steam SDR P2P voice socket on port {value}: {ex.Message}");
				_listenSocket = null;
				_activePort = -1;
			}
		}

		private void PollMessages()
		{
			try
			{
				VoiceSocketManager listenSocket = _listenSocket;
				if (listenSocket != null)
				{
					((SocketManager)listenSocket).Receive(64);
				}
			}
			catch (Exception ex)
			{
				if (Plugin.LogP2PEvents.Value)
				{
					Plugin.Logger.LogWarning((object)("P2P listen socket Receive error: " + ex.Message));
				}
			}
			if (_outgoingBySteamId.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<ulong, OutgoingPeerState> item in _outgoingBySteamId)
			{
				VoiceConnectionManager manager = item.Value.Manager;
				if (manager == null || !((ConnectionManager)manager).Connected)
				{
					continue;
				}
				try
				{
					((ConnectionManager)manager).Receive(64);
				}
				catch (Exception ex2)
				{
					if (Plugin.LogP2PEvents.Value)
					{
						Plugin.Logger.LogWarning((object)$"P2P outgoing Receive error ({item.Key}): {ex2.Message}");
					}
				}
			}
		}

		private void SyncLobbyPeers(Lobby lobby)
		{
			//IL_0008: 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_0030: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			if (!SteamClient.IsValid)
			{
				return;
			}
			ulong value = SteamClient.SteamId.Value;
			HashSet<ulong> hashSet = new HashSet<ulong>();
			foreach (Friend member in ((Lobby)(ref lobby)).Members)
			{
				ulong value2 = member.Id.Value;
				if (value2 != 0L && value2 != value)
				{
					hashSet.Add(value2);
					if (value < value2)
					{
						EnsureOutgoingConnection(member.Id);
					}
				}
			}
			List<ulong> list = new List<ulong>();
			foreach (KeyValuePair<ulong, OutgoingPeerState> item in _outgoingBySteamId)
			{
				if (!hashSet.Contains(item.Key))
				{
					list.Add(item.Key);
				}
			}
			foreach (ulong item2 in list)
			{
				CloseOutgoingPeer(item2);
			}
			List<ulong> list2 = new List<ulong>();
			foreach (KeyValuePair<ulong, Connection> item3 in _incomingBySteamId)
			{
				if (!hashSet.Contains(item3.Key))
				{
					list2.Add(item3.Key);
				}
			}
			foreach (ulong item4 in list2)
			{
				if (_incomingBySteamId.TryGetValue(item4, out var value3))
				{
					RemoveConnectionMappings(((Connection)(ref value3)).Id);
					TryCloseConnection(value3);
					_incomingBySteamId.Remove(item4);
				}
			}
		}

		private void EnsureOutgoingConnection(SteamId peerId)
		{
			//IL_0006: 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)
			//IL_00fb: 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_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: 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_009f: 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)
			if (_incomingBySteamId.ContainsKey(peerId.Value))
			{
				return;
			}
			if (!_outgoingBySteamId.TryGetValue(peerId.Value, out var value))
			{
				value = new OutgoingPeerState
				{
					SteamId = peerId
				};
				_outgoingBySteamId[peerId.Value] = value;
			}
			if (value.IsConnected || value.IsConnecting || value.Attempts >= 2 || Time.unscaledTime < value.NextAttemptTime)
			{
				return;
			}
			try
			{
				value.Attempts++;
				value.NextAttemptTime = Time.unscaledTime + 6f;
				VoiceConnectionManager voiceConnectionManager = SteamNetworkingSockets.ConnectRelay<VoiceConnectionManager>(peerId, _activePort);
				voiceConnectionManager.TargetSteamId = peerId;
				value.Manager = voiceConnectionManager;
				if (Plugin.LogP2PEvents.Value)
				{
					Plugin.Logger.LogInfo((object)$"Connecting Steam SDR P2P voice to {peerId} (attempt {value.Attempts}/{2}).");
				}
			}
			catch (Exception ex)
			{
				if (Plugin.LogP2PEvents.Value)
				{
					Plugin.Logger.LogWarning((object)$"ConnectRelay failed for {peerId}: {ex.Message}");
				}
				value.Manager = null;
			}
		}

		private void OnIncomingConnected(Connection conn, SteamId peerId)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: 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_004c: 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_003a: Unknown result type (might be due to invalid IL or missing references)
			if (peerId.Value != 0L)
			{
				if (_incomingBySteamId.TryGetValue(peerId.Value, out var value) && ((Connection)(ref value)).Id != ((Connection)(ref conn)).Id)
				{
					RemoveConnectionMappings(((Connection)(ref value)).Id);
					TryCloseConnection(value);
				}
				_incomingBySteamId[peerId.Value] = conn;
			}
			if (_hasDissonanceSession)
			{
				SendHello(conn);
			}
			if (Plugin.LogP2PEvents.Value)
			{
				Plugin.Logger.LogInfo((object)$"Accepted incoming P2P voice connection from {peerId} (ConnId={((Connection)(ref conn)).Id}).");
			}
		}

		private void OnOutgoingConnected(Connection conn, SteamId peerId)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if (_outgoingBySteamId.TryGetValue(peerId.Value, out var value))
			{
				value.Attempts = 0;
			}
			if (_hasDissonanceSession)
			{
				SendHello(conn);
			}
			if (Plugin.LogP2PEvents.Value)
			{
				Plugin.Logger.LogInfo((object)$"Established outgoing P2P voice connection to {peerId} (ConnId={((Connection)(ref conn)).Id}).");
			}
		}

		private void OnConnectionClosed(uint connId, SteamId peerId, bool isOutgoing, NetConnectionEnd endReason, string endDebug)
		{
			//IL_0057: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: 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)
			RemoveConnectionMappings(connId);
			bool flag = false;
			Connection value2;
			if (isOutgoing)
			{
				if (_outgoingBySteamId.TryGetValue(peerId.Value, out var value) && value.Manager != null && ((Connection)(ref ((ConnectionManager)value.Manager).Connection)).Id == connId)
				{
					Connection connection = ((ConnectionManager)value.Manager).Connection;
					value.Manager = null;
					TryCloseConnection(connection);
					flag = true;
				}
			}
			else if (peerId.Value != 0L && _incomingBySteamId.TryGetValue(peerId.Value, out value2) && ((Connection)(ref value2)).Id == connId)
			{
				_incomingBySteamId.Remove(peerId.Value);
				flag = true;
			}
			if (flag && Plugin.LogP2PEvents.Value)
			{
				Plugin.Logger.LogInfo((object)$"Closed P2P voice connection (SteamId={peerId}, ConnId={connId}, Reason={endReason} {endDebug}).");
			}
		}

		private void RemoveConnectionMappings(uint connId)
		{
			if (_helloByConnId.TryGetValue(connId, out var value))
			{
				if (_dissonanceIdToConn.TryGetValue(value.DissonanceId, out var value2) && ((Connection)(ref value2)).Id == connId)
				{
					_dissonanceIdToConn.Remove(value.DissonanceId);
				}
				_helloByConnId.Remove(connId);
			}
		}

		private void BroadcastHelloToAllConnected()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			if (!_hasDissonanceSession)
			{
				return;
			}
			foreach (KeyValuePair<ulong, Connection> item in _incomingBySteamId)
			{
				SendHello(item.Value);
			}
			foreach (KeyValuePair<ulong, OutgoingPeerState> item2 in _outgoingBySteamId)
			{
				if (item2.Value.IsConnected)
				{
					SendHello(((ConnectionManager)item2.Value.Manager).Connection);
				}
			}
		}

		private void SendHello(Connection conn)
		{
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			if (!SteamClient.IsValid || ((Connection)(ref conn)).Id == 0)
			{
				return;
			}
			byte[] array = new byte[7] { 1, 0, 0, 0, 0, 0, 0 };
			uint currentSessionId = _currentSessionId;
			array[1] = (byte)(currentSessionId & 0xFF);
			array[2] = (byte)((currentSessionId >> 8) & 0xFF);
			array[3] = (byte)((currentSessionId >> 16) & 0xFF);
			array[4] = (byte)((currentSessionId >> 24) & 0xFF);
			ushort currentLocalId = _currentLocalId;
			array[5] = (byte)(currentLocalId & 0xFF);
			array[6] = (byte)((currentLocalId >> 8) & 0xFF);
			try
			{
				((Connection)(ref conn)).SendMessage(array, (SendType)8);
			}
			catch (Exception ex)
			{
				if (Plugin.LogP2PEvents.Value)
				{
					Plugin.Logger.LogWarning((object)$"Failed to send P2P Hello on ConnId={((Connection)(ref conn)).Id}: {ex.Message}");
				}
			}
		}

		private unsafe void HandleRawMessage(Connection conn, SteamId senderId, IntPtr data, int size)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			if (size <= 1 || data == IntPtr.Zero)
			{
				return;
			}
			byte* ptr = (byte*)data.ToPointer();
			switch (*ptr)
			{
			case 1:
			{
				if (size < 7)
				{
					break;
				}
				uint num2 = (uint)(ptr[1] | (ptr[2] << 8) | (ptr[3] << 16) | (ptr[4] << 24));
				ushort num3 = (ushort)(ptr[5] | (ptr[6] << 8));
				_helloByConnId[((Connection)(ref conn)).Id] = new HelloInfo
				{
					SteamId = senderId,
					SessionId = num2,
					DissonanceId = num3
				};
				if (_hasDissonanceSession && num2 == _currentSessionId)
				{
					_dissonanceIdToConn[num3] = conn;
					if (Plugin.LogP2PEvents.Value)
					{
						Plugin.Logger.LogInfo((object)$"Bound P2P voice peer: SteamId={senderId} <-> DissonanceId={num3}");
					}
				}
				break;
			}
			case 2:
				if (_activeClient != null && _hasDissonanceSession)
				{
					int num = size - 1;
					if (_recvScratch.Length < num)
					{
						_recvScratch = new byte[Math.Max(_recvScratch.Length * 2, num)];
					}
					fixed (byte* recvScratch = _recvScratch)
					{
						Buffer.MemoryCopy(ptr + 1, recvScratch, _recvScratch.Length, num);
					}
					((BaseClient<NfgoServer, NfgoClient, NfgoConn>)(object)_activeClient).NetworkReceivedPacket(new ArraySegment<byte>(_recvScratch, 0, num));
				}
				break;
			}
		}

		private void RebuildDissonanceBindingsFromHellos()
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			_dissonanceIdToConn.Clear();
			if (!_hasDissonanceSession)
			{
				return;
			}
			foreach (KeyValuePair<uint, HelloInfo> item in _helloByConnId)
			{
				if (item.Value.SessionId == _currentSessionId && TryFindActiveConnection(item.Key, out var conn))
				{
					_dissonanceIdToConn[item.Value.DissonanceId] = conn;
				}
			}
		}

		private bool TryFindActiveConnection(uint connId, out Connection conn)
		{
			//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_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			foreach (KeyValuePair<ulong, Connection> item in _incomingBySteamId)
			{
				Connection value = item.Value;
				if (((Connection)(ref value)).Id == connId)
				{
					conn = item.Value;
					return true;
				}
			}
			foreach (KeyValuePair<ulong, OutgoingPeerState> item2 in _outgoingBySteamId)
			{
				if (item2.Value.IsConnected && ((Connection)(ref ((ConnectionManager)item2.Value.Manager).Connection)).Id == connId)
				{
					conn = ((ConnectionManager)item2.Value.Manager).Connection;
					return true;
				}
			}
			conn = default(Connection);
			return false;
		}

		internal bool TrySendP2P(NfgoClient client, List<ClientInfo<NfgoConn?>> destinations, ArraySegment<byte> packet, bool reliable)
		{
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Invalid comparison between Unknown and I4
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.EnableSteamP2PVoice.Value || !SteamClient.IsValid || client != _activeClient || !_hasDissonanceSession || destinations == null || destinations.Count == 0 || packet.Array == null || packet.Count <= 0 || _dissonanceIdToConn.Count == 0)
			{
				return false;
			}
			int num = packet.Count + 1;
			if (_sendScratch.Length < num)
			{
				_sendScratch = new byte[Math.Max(_sendScratch.Length * 2, num)];
			}
			_sendScratch[0] = 2;
			Buffer.BlockCopy(packet.Array, packet.Offset, _sendScratch, 1, packet.Count);
			SendType val = (SendType)(reliable ? 8 : ((!Plugin.P2PImmediateSend.Value) ? 1 : 5));
			_relayFallbackScratch.Clear();
			int num2 = 0;
			for (int i = 0; i < destinations.Count; i++)
			{
				ClientInfo<NfgoConn?> val2 = destinations[i];
				if (_dissonanceIdToConn.TryGetValue(val2.PlayerId, out var value) && ((Connection)(ref value)).Id != 0)
				{
					try
					{
						if ((int)((Connection)(ref value)).SendMessage(_sendScratch, 0, num, val) == 1)
						{
							num2++;
							continue;
						}
					}
					catch
					{
					}
				}
				_relayFallbackScratch.Add(val2);
			}
			if (num2 == 0)
			{
				return false;
			}
			if (_relayFallbackScratch.Count == 0)
			{
				return true;
			}
			destinations.Clear();
			destinations.AddRange(_relayFallbackScratch);
			_relayFallbackScratch.Clear();
			return false;
		}

		private void CloseOutgoingPeer(ulong steamId)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			if (_outgoingBySteamId.TryGetValue(steamId, out var value))
			{
				if (value.Manager != null)
				{
					RemoveConnectionMappings(((Connection)(ref ((ConnectionManager)value.Manager).Connection)).Id);
					TryCloseConnection(((ConnectionManager)value.Manager).Connection);
					value.Manager = null;
				}
				_outgoingBySteamId.Remove(steamId);
			}
		}

		private void ShutdownP2P()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			_dissonanceIdToConn.Clear();
			_helloByConnId.Clear();
			foreach (KeyValuePair<ulong, OutgoingPeerState> item in _outgoingBySteamId)
			{
				if (item.Value.Manager != null)
				{
					TryCloseConnection(((ConnectionManager)item.Value.Manager).Connection);
					item.Value.Manager = null;
				}
			}
			_outgoingBySteamId.Clear();
			foreach (KeyValuePair<ulong, Connection> item2 in _incomingBySteamId)
			{
				TryCloseConnection(item2.Value);
			}
			_incomingBySteamId.Clear();
			if (_listenSocket != null)
			{
				try
				{
					if (SteamClient.IsValid)
					{
						((SocketManager)_listenSocket).Close();
					}
				}
				catch
				{
				}
				_listenSocket = null;
			}
			_activePort = -1;
			_activeLobbyId = 0uL;
		}

		private static void TryCloseConnection(Connection conn)
		{
			if (!SteamClient.IsValid || ((Connection)(ref conn)).Id == 0)
			{
				return;
			}
			try
			{
				((Connection)(ref conn)).Close(false, 0, "BetterVoice closing");
			}
			catch
			{
			}
		}

		private static bool IsSteamLobbyActive(out Lobby lobby)
		{
			//IL_004f: 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_0047: Unknown result type (might be due to invalid IL or missing references)
			if (SteamClient.IsValid && (Object)(object)GameNetworkManager.Instance != (Object)null && !GameNetworkManager.Instance.disableSteam && GameNetworkManager.Instance.currentLobby.HasValue)
			{
				lobby = GameNetworkManager.Instance.currentLobby.Value;
				return true;
			}
			lobby = default(Lobby);
			return false;
		}

		private static bool IsSteamIdInCurrentLobby(SteamId remoteId)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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)
			if (remoteId.Value == 0L || !IsSteamLobbyActive(out var lobby))
			{
				return false;
			}
			foreach (Friend member in ((Lobby)(ref lobby)).Members)
			{
				if (member.Id.Value == remoteId.Value)
				{
					return true;
				}
			}
			return false;
		}
	}
}