This commit is contained in:
TinyHerm committed 2026-11-24 23:40:08 +03:00
commit 1c7a8cf25f
579 files changed
+83196

No files matched your search

+220
View File
@@ -0,0 +1,220 @@
using System;
using System.Threading;
using System.Threading.Tasks;
namespace VibranceHud.Audio;
public sealed class AudioEdgeService : IDisposable
{
public enum MeterState
{
Off,
NoReading,
Holding,
Clear
}
public const int TickMs = 30;
public const float ExternalChangeTolerance = 0.001f;
public const int HoldTicks = 20;
public const float WriteEpsilon = 0.002f;
private readonly IAudioOutput _output;
private CancellationTokenSource? _cts;
private float _restoreVolume = 1f;
private float _lastWritten = float.NaN;
private readonly float[] _recentPeaks = new float[20];
private int _nextPeak;
internal int WriteCount { get; private set; }
public float Threshold { get; set; } = 0.3f;
public bool IsRunning => _cts != null;
public float Peak => _output.Peak;
public float CurrentVolume => _output.Volume;
public float RestoreVolume => _restoreVolume;
public MeterState Meter
{
get
{
if (!IsRunning)
{
return MeterState.Off;
}
float currentVolume = CurrentVolume;
float restoreVolume = _restoreVolume;
if (float.IsNaN(currentVolume) || float.IsNaN(restoreVolume))
{
return MeterState.NoReading;
}
if (!(currentVolume < restoreVolume - 0.01f))
{
return MeterState.Clear;
}
return MeterState.Holding;
}
}
public event Action<float>? OnRestorePointCaptured;
public event Action? OnRestoreCompleted;
public AudioEdgeService(IAudioOutput output)
{
_output = output;
}
public void Start()
{
Start(runLoop: true);
}
internal void StartWithoutLoopForTest()
{
Start(runLoop: false);
}
private void Start(bool runLoop)
{
if (IsRunning)
{
return;
}
float f = (_restoreVolume = _output.Volume);
_lastWritten = float.NaN;
Array.Clear(_recentPeaks);
_nextPeak = 0;
if (!float.IsNaN(f))
{
OnRestorePointCaptured?.Invoke(_restoreVolume);
}
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
if (!runLoop)
{
return;
}
Task.Run(async () =>
{
try
{
while (!token.IsCancellationRequested)
{
Tick();
await Task.Delay(30, token);
}
}
catch (OperationCanceledException)
{
}
catch
{
}
finally
{
if (!float.IsNaN(_restoreVolume))
{
_output.Volume = _restoreVolume;
}
OnRestoreCompleted?.Invoke();
}
}, token);
}
public void ForceRestore(float volume)
{
_output.Volume = Math.Clamp(volume, 0f, 1f);
}
public void Tick()
{
float volume = _output.Volume;
if (float.IsNaN(volume))
{
return;
}
if (float.IsNaN(_restoreVolume))
{
_restoreVolume = volume;
_lastWritten = float.NaN;
OnRestorePointCaptured?.Invoke(_restoreVolume);
}
if (!float.IsNaN(_lastWritten))
{
float num = volume - _lastWritten;
if (MathF.Abs(num) > 0.001f)
{
_restoreVolume = Math.Clamp(_restoreVolume + num, 0.05f, 1f);
OnRestorePointCaptured?.Invoke(_restoreVolume);
}
}
_recentPeaks[_nextPeak] = _output.Peak;
_nextPeak = (_nextPeak + 1) % _recentPeaks.Length;
float num2 = 0f;
float[] recentPeaks = _recentPeaks;
foreach (float y in recentPeaks)
{
num2 = MathF.Max(num2, y);
}
float num3 = AudioLimiter.NextVolume(num2, Threshold, volume, _restoreVolume);
if (MathF.Abs(num3 - volume) > 0.002f)
{
float volume2 = _output.Volume;
if (!float.IsNaN(volume2))
{
if (MathF.Abs(volume2 - volume) > 0.001f)
{
_restoreVolume = Math.Clamp(_restoreVolume + (volume2 - volume), 0.05f, 1f);
_lastWritten = volume2;
OnRestorePointCaptured?.Invoke(_restoreVolume);
}
else
{
_output.Volume = num3;
_lastWritten = _output.Volume;
WriteCount++;
}
}
}
else
{
_lastWritten = volume;
}
}
public void Stop()
{
CancellationTokenSource cts = _cts;
_cts = null;
if (cts != null)
{
cts.Cancel();
cts.Dispose();
if (!float.IsNaN(_restoreVolume))
{
_output.Volume = _restoreVolume;
}
_lastWritten = float.NaN;
OnRestoreCompleted?.Invoke();
}
}
public void Dispose()
{
Stop();
(_output as IDisposable)?.Dispose();
}
}
+19
View File
@@ -0,0 +1,19 @@
using System;
namespace VibranceHud.Audio;
public static class AudioLimiter
{
public const float MinVolume = 0.05f;
public const float DefaultAttack = 0.5f;
public const float DefaultRelease = 0.3f;
public static float NextVolume(float peak, float threshold, float currentVolume, float maxVolume, float attack = 0.5f, float release = 0.3f)
{
float num = ((peak > 0.0001f) ? MathF.Min(maxVolume, threshold / peak) : maxVolume);
float num2 = ((num < currentVolume) ? attack : release);
return Math.Clamp(currentVolume + (num - currentVolume) * num2, 0.05f, maxVolume);
}
}
+27
View File
@@ -0,0 +1,27 @@
using System;
using System.Threading;
namespace VibranceHud.Audio;
internal static class AudioLoopDiagnostic
{
public static void RunAndPrint()
{
using WindowsAudioOutput windowsAudioOutput = new WindowsAudioOutput();
float volume = windowsAudioOutput.Volume;
try
{
float[] array = new float[3] { 1f, 0.5f, 0.25f };
for (int i = 0; i < array.Length; i++)
{
float value = (windowsAudioOutput.Volume = array[i]);
Thread.Sleep(500);
Console.WriteLine($"Volume {value:P0} -> Peak {windowsAudioOutput.Peak:F3}");
}
}
finally
{
windowsAudioOutput.Volume = volume;
}
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace VibranceHud.Audio;
public interface IAudioOutput
{
float Peak { get; }
float Volume { get; set; }
}
+110
View File
@@ -0,0 +1,110 @@
using System;
using System.Threading;
namespace VibranceHud.Audio;
internal sealed class RestorePointSaver
{
private readonly Action _save;
private readonly int _quietMs;
private readonly Func<int, Action, IDisposable> _startTimer;
private readonly object _gate = new object();
private IDisposable? _timer;
private int _generation;
private bool _dirty;
public RestorePointSaver(Action save, int quietMs = 400, Func<int, Action, IDisposable>? startTimer = null)
{
_save = save;
_quietMs = quietMs;
_startTimer = startTimer ?? new Func<int, Action, IDisposable>(DefaultTimer);
}
public void Captured(float volume, AppSettings settings)
{
lock (_gate)
{
settings.AudioEdgeRestoreVolume = volume;
if (!settings.AudioEdgeRestorePending)
{
settings.AudioEdgeRestorePending = true;
CancelTimer();
_dirty = false;
_save();
return;
}
_dirty = true;
if (_timer == null)
{
CancelTimer();
int gen = _generation;
_timer = _startTimer(_quietMs, () =>
{
OnDue(gen);
});
}
}
}
public void Completed(AppSettings settings)
{
lock (_gate)
{
CancelTimer();
_dirty = false;
settings.AudioEdgeRestorePending = false;
_save();
}
}
public void Flush()
{
lock (_gate)
{
CancelTimer();
if (_dirty)
{
_dirty = false;
_save();
}
}
}
private void OnDue(int generation)
{
lock (_gate)
{
if (generation == _generation)
{
_timer?.Dispose();
_timer = null;
if (_dirty)
{
_dirty = false;
_save();
}
}
}
}
private void CancelTimer()
{
_generation++;
_timer?.Dispose();
_timer = null;
}
private static IDisposable DefaultTimer(int delayMs, Action callback)
{
return new Timer((object? _) =>
{
callback();
}, null, delayMs, -1);
}
}
+149
View File
@@ -0,0 +1,149 @@
using System;
using System.Runtime.InteropServices;
namespace VibranceHud.Audio;
public sealed class WindowsAudioOutput : IAudioOutput, IDisposable
{
[ComImport]
[Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
private class MMDeviceEnumerator
{
}
[ComImport]
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDeviceEnumerator
{
[PreserveSig]
int EnumAudioEndpoints(int dataFlow, int stateMask, out nint devices);
[PreserveSig]
int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device);
}
[ComImport]
[Guid("D666063F-1587-4E43-81F1-B948E807363F")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDevice
{
[PreserveSig]
int Activate(ref Guid iid, int clsCtx, nint activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object iface);
}
[ComImport]
[Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAudioMeterInformation
{
[PreserveSig]
int GetPeakValue(out float peak);
}
[ComImport]
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAudioEndpointVolume
{
[PreserveSig]
int RegisterControlChangeNotify(nint notify);
[PreserveSig]
int UnregisterControlChangeNotify(nint notify);
[PreserveSig]
int GetChannelCount(out uint count);
[PreserveSig]
int SetMasterVolumeLevel(float level, ref Guid eventContext);
[PreserveSig]
int SetMasterVolumeLevelScalar(float level, ref Guid eventContext);
[PreserveSig]
int GetMasterVolumeLevel(out float level);
[PreserveSig]
int GetMasterVolumeLevelScalar(out float level);
}
private const int ERender = 0;
private const int EConsole = 0;
private const int ClsCtxAll = 23;
private static Guid _meterIid = new Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064");
private static Guid _volumeIid = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A");
private static Guid _noEvent = Guid.Empty;
private readonly IAudioMeterInformation _meter;
private readonly IAudioEndpointVolume _volume;
public float Peak
{
get
{
try
{
float peak;
return (_meter.GetPeakValue(out peak) == 0) ? peak : 0f;
}
catch
{
return 0f;
}
}
}
public float Volume
{
get
{
try
{
float level;
return (_volume.GetMasterVolumeLevelScalar(out level) == 0) ? level : float.NaN;
}
catch
{
return float.NaN;
}
}
set
{
try
{
_volume.SetMasterVolumeLevelScalar(Math.Clamp(value, 0f, 1f), ref _noEvent);
}
catch
{
}
}
}
public WindowsAudioOutput()
{
Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)new MMDeviceEnumerator()).GetDefaultAudioEndpoint(0, 0, out IMMDevice device));
Marshal.ThrowExceptionForHR(device.Activate(ref _meterIid, 23, IntPtr.Zero, out object iface));
Marshal.ThrowExceptionForHR(device.Activate(ref _volumeIid, 23, IntPtr.Zero, out object iface2));
_meter = (IAudioMeterInformation)iface;
_volume = (IAudioEndpointVolume)iface2;
}
public void Dispose()
{
if (Marshal.IsComObject(_meter))
{
Marshal.ReleaseComObject(_meter);
}
if (Marshal.IsComObject(_volume))
{
Marshal.ReleaseComObject(_volume);
}
}
}