using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using Microsoft.CodeAnalysis;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
internal sealed class NullableAttribute : Attribute
{
public readonly byte[] NullableFlags;
public NullableAttribute(byte P_0)
{
NullableFlags = new byte[1] { P_0 };
}
public NullableAttribute(byte[] P_0)
{
NullableFlags = P_0;
}
}
[CompilerGenerated]
[Microsoft.CodeAnalysis.Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
internal sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte P_0)
{
Flag = P_0;
}
}
[CompilerGenerated]
[Microsoft.CodeAnalysis.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 PeakAudioFix
{
[BepInPlugin("patchnote.peakaudiofix", "Peak Audio Fix", "1.0.0")]
public sealed class PeakAudioFixPlugin : BaseUnityPlugin
{
private sealed class ParkedSource
{
internal AudioSource Source { get; }
internal float ParkedAt { get; }
internal float TimeWhenParked { get; }
internal ParkedSource(AudioSource source, float parkedAt, float timeWhenParked)
{
Source = source;
ParkedAt = parkedAt;
TimeWhenParked = timeWhenParked;
}
}
internal const string PluginGuid = "patchnote.peakaudiofix";
internal const string PluginName = "Peak Audio Fix";
internal const string PluginVersion = "1.0.0";
private const float SilentVolumeThreshold = 0.001f;
private const float ResumeVolumeThreshold = 0.01f;
private const float SilentSecondsBeforeParking = 2f;
private const float ScanIntervalSeconds = 0.5f;
private const int VoicePriority = 0;
private const int GlobalPriority = 20;
private const int NearWorldPriority = 80;
private const int FarWorldPriority = 220;
private readonly Dictionary<int, float> _silentSince = new Dictionary<int, float>();
private readonly Dictionary<int, ParkedSource> _parkedSources = new Dictionary<int, ParkedSource>();
private readonly List<int> _scratchIds = new List<int>();
private float _nextScanAt;
private int _totalParked;
private int _totalResumed;
private int _totalForgotten;
private int _totalPriorityChanges;
private void Awake()
{
((BaseUnityPlugin)this).Logger.LogInfo((object)"Loaded Peak Audio Fix.");
}
private void OnDestroy()
{
((BaseUnityPlugin)this).Logger.LogInfo((object)($"Peak Audio Fix summary: parked={_totalParked}, resumed={_totalResumed}, " + $"forgotten={_totalForgotten}, priorityChanges={_totalPriorityChanges}, " + $"currentlyParked={_parkedSources.Count}"));
}
private void Update()
{
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
float realtimeSinceStartup = Time.realtimeSinceStartup;
if (!(realtimeSinceStartup < _nextScanAt))
{
_nextScanAt = realtimeSinceStartup + 0.5f;
RefreshParkedSources(realtimeSinceStartup);
ScanPlayingSources(realtimeSinceStartup, GetListenerPosition());
}
}
private void ScanPlayingSources(float now, Vector3 listenerPosition)
{
//IL_004d: Unknown result type (might be due to invalid IL or missing references)
//IL_006d: Unknown result type (might be due to invalid IL or missing references)
AudioSource[] array = Object.FindObjectsByType<AudioSource>((FindObjectsInactive)0, (FindObjectsSortMode)0);
foreach (AudioSource val in array)
{
int instanceID = ((Object)val).GetInstanceID();
if (!_parkedSources.ContainsKey(instanceID))
{
float value;
if (!val.isPlaying)
{
_silentSince.Remove(instanceID);
}
else if (!IsLoopCandidate(val))
{
ApplyPriorityPolicy(val, listenerPosition);
_silentSince.Remove(instanceID);
}
else if (!IsSilent(val))
{
ApplyPriorityPolicy(val, listenerPosition);
_silentSince.Remove(instanceID);
}
else if (!_silentSince.TryGetValue(instanceID, out value))
{
_silentSince[instanceID] = now;
}
else if (now - value >= 2f)
{
ParkSource(val, instanceID, now);
}
}
}
}
private void RefreshParkedSources(float now)
{
_scratchIds.Clear();
foreach (int key in _parkedSources.Keys)
{
_scratchIds.Add(key);
}
foreach (int scratchId in _scratchIds)
{
ParkedSource parkedSource = _parkedSources[scratchId];
AudioSource source = parkedSource.Source;
if ((Object)(object)source == (Object)null)
{
ForgetParked(scratchId);
}
else if (!IsLoopCandidate(source))
{
ForgetParked(scratchId);
}
else if (source.isPlaying)
{
_parkedSources.Remove(scratchId);
_silentSince.Remove(scratchId);
}
else if (ShouldResume(source))
{
ResumeSource(source, parkedSource, scratchId, now);
}
}
}
private void ParkSource(AudioSource source, int id, float now)
{
ParkedSource value = new ParkedSource(source, now, TryGetSourceTime(source));
source.Pause();
_parkedSources[id] = value;
_silentSince.Remove(id);
_totalParked++;
}
private void ResumeSource(AudioSource source, ParkedSource parked, int id, float now)
{
RestoreSourceTime(source, parked, now);
source.UnPause();
if (!source.isPlaying)
{
source.Play();
}
_parkedSources.Remove(id);
_silentSince.Remove(id);
_totalResumed++;
}
private void ForgetParked(int id)
{
_parkedSources.Remove(id);
_silentSince.Remove(id);
_totalForgotten++;
}
private bool IsLoopCandidate(AudioSource source)
{
if (!source.loop || (Object)(object)source.clip == (Object)null)
{
return false;
}
return !string.Equals(((Object)source.clip).name, "UnityAudioOut", StringComparison.Ordinal);
}
private bool IsSilent(AudioSource source)
{
return source.volume <= 0.001f;
}
private bool ShouldResume(AudioSource source)
{
if (((Behaviour)source).enabled && ((Component)source).gameObject.activeInHierarchy && !source.mute)
{
return source.volume >= 0.01f;
}
return false;
}
private void ApplyPriorityPolicy(AudioSource source, Vector3 listenerPosition)
{
//IL_0011: Unknown result type (might be due to invalid IL or missing references)
if (!((Object)(object)source.clip == (Object)null))
{
int targetPriority = GetTargetPriority(source, listenerPosition);
if (source.priority != targetPriority)
{
source.priority = targetPriority;
_totalPriorityChanges++;
}
}
}
private int GetTargetPriority(AudioSource source, Vector3 listenerPosition)
{
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
//IL_002d: Unknown result type (might be due to invalid IL or missing references)
if (IsVoiceSource(source))
{
return 0;
}
if (IsGlobalSource(source))
{
return 20;
}
float num = Mathf.Max(1f, source.maxDistance);
float num2 = Mathf.Clamp01(Vector3.Distance(listenerPosition, ((Component)source).transform.position) / num);
return Mathf.RoundToInt(Mathf.Lerp(80f, 220f, num2));
}
private static bool IsVoiceSource(AudioSource source)
{
return string.Equals(((Object)source.clip).name, "UnityAudioOut", StringComparison.Ordinal);
}
private static bool IsGlobalSource(AudioSource source)
{
if (source.spatialBlend <= 0.05f)
{
return true;
}
if (((Object)source.clip).name.StartsWith("Music", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return ContainsPathSegment(((Component)source).transform, "Music");
}
private static bool ContainsPathSegment(Transform transform, string segment)
{
Transform val = transform;
while ((Object)(object)val != (Object)null)
{
if (string.Equals(((Object)val).name, segment, StringComparison.OrdinalIgnoreCase))
{
return true;
}
val = val.parent;
}
return false;
}
private static Vector3 GetListenerPosition()
{
//IL_0015: Unknown result type (might be due to invalid IL or missing references)
//IL_0036: 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)
Camera main = Camera.main;
if ((Object)(object)main != (Object)null)
{
return ((Component)main).transform.position;
}
AudioListener val = Object.FindFirstObjectByType<AudioListener>();
if (!((Object)(object)val != (Object)null))
{
return Vector3.zero;
}
return ((Component)val).transform.position;
}
private static float TryGetSourceTime(AudioSource source)
{
try
{
return source.time;
}
catch
{
return 0f;
}
}
private static void RestoreSourceTime(AudioSource source, ParkedSource parked, float now)
{
AudioClip clip = source.clip;
if ((Object)(object)clip == (Object)null || clip.length <= 0.01f)
{
return;
}
try
{
float num = Mathf.Max(0f, now - parked.ParkedAt);
float num2 = Mathf.Abs(source.pitch);
source.time = Mathf.Repeat(parked.TimeWhenParked + num * num2, clip.length);
}
catch
{
}
}
}
}