Decompiled source of ClearVoice v1.0.1

ClearVoice.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ClearVoice;

[BepInPlugin("local.clearvoice", "ClearVoice", "1.0.1")]
public class Plugin : BaseUnityPlugin
{
	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> On;

	internal static ConfigEntry<bool> Center;

	internal static ConfigEntry<bool> KeepBeeps;

	internal static ConfigEntry<bool> RemoveStatic;

	internal static ConfigEntry<bool> Gate;

	internal static ConfigEntry<float> Clarity;

	internal static ConfigEntry<float> WallClarity;

	internal static ConfigEntry<float> BeepVolume;

	internal static ConfigEntry<float> GateDb;

	private void Awake()
	{
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		//IL_0063: Expected O, but got Unknown
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e0: Expected O, but got Unknown
		//IL_0133: Unknown result type (might be due to invalid IL or missing references)
		//IL_013d: Expected O, but got Unknown
		//IL_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_019a: Expected O, but got Unknown
		//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		On = ((BaseUnityPlugin)this).Config.Bind<bool>("Walkie-talkie", "Enabled", true, "Turn the whole mod on or off.");
		Clarity = ((BaseUnityPlugin)this).Config.Bind<float>("Walkie-talkie", "Clarity", 0.85f, new ConfigDescription("How much of the radio effect to remove from walkie-talkie voices. 0 = vanilla radio sound, 1 = fully clear (full range, no resonant peak, no distortion).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
		Center = ((BaseUnityPlugin)this).Config.Bind<bool>("Walkie-talkie", "CenterVoice", true, "Play walkie-talkie voices in both ears equally (vanilla pans them to one side).");
		KeepBeeps = ((BaseUnityPlugin)this).Config.Bind<bool>("Walkie-talkie", "KeepBeeps", true, "Keep the click/beep when someone starts and stops talking on the walkie-talkie.");
		BeepVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Walkie-talkie", "BeepVolume", 0.6f, new ConfigDescription("Volume of those beeps (1 = vanilla).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
		RemoveStatic = ((BaseUnityPlugin)this).Config.Bind<bool>("Walkie-talkie", "RemoveStatic", true, "Don't play the garbled static that walkie-talkies lying around make while someone transmits.");
		WallClarity = ((BaseUnityPlugin)this).Config.Bind<float>("Voice chat", "ThroughWallClarity", 0.5f, new ConfigDescription("Normal (proximity) voices behind walls are muffled down to 900 Hz in vanilla. Raising this keeps more of the voice understandable. 0 = vanilla. Voices are still exactly as loud as before, and only voices you already hear are affected.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
		Gate = ((BaseUnityPlugin)this).Config.Bind<bool>("Voice chat", "NoiseGate", false, "Light noise gate on everyone's voice: very quiet background hiss between words is turned down.");
		GateDb = ((BaseUnityPlugin)this).Config.Bind<float>("Voice chat", "NoiseGateThresholdDb", -46f, new ConfigDescription("Sound quieter than this (dBFS) counts as background noise. Lower = gentler.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-80f, -20f), Array.Empty<object>()));
		new Harmony("local.clearvoice").PatchAll(typeof(Plugin).Assembly);
		Log.LogInfo((object)"ClearVoice loaded");
	}
}
[HarmonyPatch]
internal static class VoicePatches
{
	private static readonly Dictionary<int, float> hpOriginal = new Dictionary<int, float>();

	private static readonly Dictionary<int, float> distOriginal = new Dictionary<int, float>();

	internal static readonly HashSet<int> voiceOccluders = new HashSet<int>();

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

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

	private static readonly HashSet<int> beepClips = new HashSet<int>();

	[HarmonyPostfix]
	[HarmonyPatch(typeof(StartOfRound), "UpdatePlayerVoiceEffects")]
	private static void AfterVoiceEffects(StartOfRound __instance)
	{
		try
		{
			GameNetworkManager instance = GameNetworkManager.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.localPlayerController == (Object)null || __instance.allPlayerScripts == null)
			{
				return;
			}
			PlayerControllerB localPlayerController = instance.localPlayerController;
			PlayerControllerB val = ((localPlayerController.isPlayerDead && (Object)(object)localPlayerController.spectatedPlayerScript != (Object)null) ? localPlayerController.spectatedPlayerScript : localPlayerController);
			float num = (Plugin.On.Value ? Mathf.Clamp01(Plugin.Clarity.Value) : 0f);
			PlayerControllerB[] allPlayerScripts = __instance.allPlayerScripts;
			foreach (PlayerControllerB val2 in allPlayerScripts)
			{
				if ((Object)(object)val2 == (Object)null || (Object)(object)val2 == (Object)(object)localPlayerController)
				{
					continue;
				}
				AudioSource currentVoiceChatAudioSource = val2.currentVoiceChatAudioSource;
				if ((Object)(object)currentVoiceChatAudioSource == (Object)null)
				{
					continue;
				}
				OccludeAudio component = ((Component)currentVoiceChatAudioSource).GetComponent<OccludeAudio>();
				if ((Object)(object)component != (Object)null)
				{
					voiceOccluders.Add(((Object)component).GetInstanceID());
				}
				if (Plugin.On.Value && Plugin.Gate.Value && (Object)(object)((Component)currentVoiceChatAudioSource).GetComponent<NoiseGate>() == (Object)null)
				{
					((Component)currentVoiceChatAudioSource).gameObject.AddComponent<NoiseGate>();
				}
				if (val2.isPlayerDead)
				{
					continue;
				}
				bool flag = val2.speakingToWalkieTalkie && val.holdingWalkieTalkie && (Object)(object)val2 != (Object)(object)val;
				AudioHighPassFilter component2 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioHighPassFilter>();
				AudioLowPassFilter component3 = ((Component)currentVoiceChatAudioSource).GetComponent<AudioLowPassFilter>();
				if ((Object)(object)component2 != (Object)null)
				{
					int instanceID = ((Object)component2).GetInstanceID();
					if (!hpOriginal.TryGetValue(instanceID, out var value))
					{
						value = component2.cutoffFrequency;
						hpOriginal[instanceID] = value;
					}
					component2.cutoffFrequency = (flag ? Mathf.Lerp(value, 80f, num) : value);
				}
				AudioDistortionFilter[] components = ((Component)currentVoiceChatAudioSource).GetComponents<AudioDistortionFilter>();
				foreach (AudioDistortionFilter val3 in components)
				{
					int instanceID2 = ((Object)val3).GetInstanceID();
					if (!distOriginal.TryGetValue(instanceID2, out var value2))
					{
						value2 = val3.distortionLevel;
						distOriginal[instanceID2] = value2;
					}
					val3.distortionLevel = (flag ? (value2 * (1f - num)) : value2);
				}
				if (flag)
				{
					if ((Object)(object)component != (Object)null && !val2.voiceMuffledByEnemy)
					{
						component.lowPassOverride = Mathf.Lerp(4000f, 20000f, num);
					}
					if ((Object)(object)component3 != (Object)null)
					{
						component3.lowpassResonanceQ = Mathf.Lerp(3f, 1f, num);
					}
					if (Plugin.On.Value && Plugin.Center.Value)
					{
						currentVoiceChatAudioSource.panStereo = 0f;
					}
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Voice effects: " + ex.Message));
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(OccludeAudio), "Update")]
	private static void AfterOcclude(OccludeAudio __instance)
	{
		if (!Plugin.On.Value || Plugin.WallClarity.Value <= 0f || __instance.overridingLowPass || !occludedRef.Invoke(__instance) || !voiceOccluders.Contains(((Object)__instance).GetInstanceID()))
		{
			return;
		}
		AudioLowPassFilter val = lowPassRef.Invoke(__instance);
		if (!((Object)(object)val == (Object)null))
		{
			float num = Mathf.Lerp(900f, 6000f, Mathf.Clamp01(Plugin.WallClarity.Value));
			if (val.cutoffFrequency < num)
			{
				val.cutoffFrequency = num;
			}
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(WalkieTalkie), "Start")]
	private static void WalkieStart(WalkieTalkie __instance)
	{
		AudioClip[] startTransmissionSFX;
		if (__instance.startTransmissionSFX != null)
		{
			startTransmissionSFX = __instance.startTransmissionSFX;
			foreach (AudioClip val in startTransmissionSFX)
			{
				if ((Object)(object)val != (Object)null)
				{
					beepClips.Add(((Object)val).GetInstanceID());
				}
			}
		}
		if (__instance.stopTransmissionSFX == null)
		{
			return;
		}
		startTransmissionSFX = __instance.stopTransmissionSFX;
		foreach (AudioClip val2 in startTransmissionSFX)
		{
			if ((Object)(object)val2 != (Object)null)
			{
				beepClips.Add(((Object)val2).GetInstanceID());
			}
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(AudioSource), "PlayOneShot", new Type[]
	{
		typeof(AudioClip),
		typeof(float)
	})]
	private static bool OneShot(AudioClip __0, ref float __1)
	{
		if (!Plugin.On.Value || (Object)(object)__0 == (Object)null || beepClips.Count == 0 || !beepClips.Contains(((Object)__0).GetInstanceID()))
		{
			return true;
		}
		if (!Plugin.KeepBeeps.Value)
		{
			return false;
		}
		__1 *= Mathf.Clamp01(Plugin.BeepVolume.Value);
		return true;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(WalkieTalkie), "SendWalkieTalkieStartTransmissionSFX")]
	private static void AfterStartTransmission()
	{
		if (!Plugin.On.Value || !Plugin.RemoveStatic.Value)
		{
			return;
		}
		try
		{
			foreach (WalkieTalkie allWalkieTalky in WalkieTalkie.allWalkieTalkies)
			{
				if (!((Object)(object)allWalkieTalky == (Object)null) && !((Object)(object)allWalkieTalky.thisAudio == (Object)null) && !((Object)(object)allWalkieTalky.talkingOnWalkieTalkieNotHeldSFX == (Object)null) && allWalkieTalky.thisAudio.isPlaying && (Object)(object)allWalkieTalky.thisAudio.clip == (Object)(object)allWalkieTalky.talkingOnWalkieTalkieNotHeldSFX)
				{
					allWalkieTalky.thisAudio.Stop();
				}
			}
		}
		catch
		{
		}
	}
}
internal class NoiseGate : MonoBehaviour
{
	private volatile bool active = true;

	private volatile float threshold = 0.005f;

	private float gain = 1f;

	private float env;

	private int rate = 48000;

	private void Awake()
	{
		rate = ((AudioSettings.outputSampleRate > 0) ? AudioSettings.outputSampleRate : 48000);
	}

	private void Update()
	{
		active = Plugin.On.Value && Plugin.Gate.Value;
		threshold = Mathf.Pow(10f, Plugin.GateDb.Value / 20f);
	}

	private void OnAudioFilterRead(float[] data, int channels)
	{
		if (!active)
		{
			gain = 1f;
			return;
		}
		float num = threshold;
		float num2 = 1f - Mathf.Exp(-1f / (0.002f * (float)rate));
		float num3 = 1f - Mathf.Exp(-1f / (0.12f * (float)rate));
		for (int i = 0; i + channels - 1 < data.Length; i += channels)
		{
			float num4 = 0f;
			for (int j = 0; j < channels; j++)
			{
				float num5 = Math.Abs(data[i + j]);
				if (num5 > num4)
				{
					num4 = num5;
				}
			}
			env += (num4 - env) * ((num4 > env) ? 0.2f : 0.0005f);
			float num6 = ((env >= num) ? 1f : Mathf.Max(0.12f, env / num));
			gain += (num6 - gain) * ((num6 > gain) ? (num2 * 8f) : num3);
			for (int k = 0; k < channels; k++)
			{
				data[i + k] *= gain;
			}
		}
	}
}