-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
423 lines (347 loc) · 14.3 KB
/
Program.cs
File metadata and controls
423 lines (347 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
using OpenTK.Graphics.OpenGL4;
using OpenTK.Mathematics;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;
using OpenTK.Windowing.GraphicsLibraryFramework;
using NAudio.Wave;
using MathNet.Numerics;
using MathNet.Numerics.IntegralTransforms;
using System.Runtime.InteropServices;
using CAudioVisualizer.Core;
using CAudioVisualizer.GUI;
using CAudioVisualizer.Configuration;
using CAudioVisualizer.Visualizers;
namespace CAudioVisualizer;
internal static class NativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern uint SetThreadExecutionState(uint esFlags);
public const uint ES_CONTINUOUS = 0x80000000;
public const uint ES_DISPLAY_REQUIRED = 0x00000002;
}
public class AudioVisualizerWindow : GameWindow
{
private IWaveIn? _capture;
private readonly List<float> _audioBuffer = new();
private readonly object _bufferLock = new();
private const int BUFFER_SIZE = 2048;
private float[] _waveformData = new float[BUFFER_SIZE];
private Complex32[] _fftBuffer = new Complex32[BUFFER_SIZE];
private float[] _fftData = new float[BUFFER_SIZE / 2]; // Only need first half of FFT
private static readonly float[] HannWindow = CreateHannWindow(BUFFER_SIZE);
private VisualizerManager _visualizerManager = null!;
private ImGuiController _imGuiController = null!;
private ConfigurationGui _configGui = null!;
private AppConfig _appConfig = null!;
private bool _showConfigWindow = false;
private WindowState _lastWindowState = WindowState.Normal;
public AudioVisualizerWindow(GameWindowSettings gameWindowSettings, NativeWindowSettings nativeWindowSettings)
: base(gameWindowSettings, nativeWindowSettings)
{
}
public void SwitchToMonitor(int monitorIndex)
{
var monitors = Monitors.GetMonitors();
if (_appConfig?.SpanAllMonitors == true && monitors.Count > 1)
{
int minX = monitors.Min(m => m.ClientArea.Min.X);
int minY = monitors.Min(m => m.ClientArea.Min.Y);
int maxX = monitors.Max(m => m.ClientArea.Max.X);
int maxY = monitors.Max(m => m.ClientArea.Max.Y);
Location = new Vector2i(minX, minY);
ClientSize = new Vector2i(maxX - minX, maxY - minY);
GL.Viewport(0, 0, ClientSize.X, ClientSize.Y);
_imGuiController?.WindowResized(ClientSize.X, ClientSize.Y);
}
else if (monitorIndex >= 0 && monitorIndex < monitors.Count)
{
var selectedMonitor = monitors[monitorIndex];
Location = new Vector2i(selectedMonitor.WorkArea.Min.X, selectedMonitor.WorkArea.Min.Y);
ClientSize = new Vector2i(selectedMonitor.HorizontalResolution, selectedMonitor.VerticalResolution);
GL.Viewport(0, 0, ClientSize.X, ClientSize.Y);
_imGuiController?.WindowResized(ClientSize.X, ClientSize.Y);
}
}
protected override void OnLoad()
{
base.OnLoad();
NativeMethods.SetThreadExecutionState(
NativeMethods.ES_CONTINUOUS | NativeMethods.ES_DISPLAY_REQUIRED);
GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f);
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
_imGuiController = new ImGuiController(ClientSize.X, ClientSize.Y);
_appConfig = new AppConfig();
_appConfig.LoadConfiguration(AppConfig.GetConfigFilePath());
// Initialize audio device name if not set
if (string.IsNullOrEmpty(_appConfig.SelectedAudioDeviceName))
{
_appConfig.SelectedAudioDeviceName = AudioDeviceManager.GetDeviceName(_appConfig.SelectedAudioDeviceId);
}
_visualizerManager = new VisualizerManager(ClientSize);
_visualizerManager.LoadVisualizerConfigurations(_appConfig.VisualizerConfigs, _appConfig.EnabledVisualizers);
_configGui = new ConfigurationGui(_visualizerManager, _appConfig, ApplyConfigurationSettings, this);
SetupAudioCapture();
ApplyConfigurationSettings();
}
private void ApplyConfigurationSettings()
{
// Set FPS: 0 means unlimited in OpenTK
UpdateFrequency = _appConfig.UnlimitedFPS ? 0 : _appConfig.TargetFPS;
VSync = _appConfig.EnableVSync ? VSyncMode.On : VSyncMode.Off;
}
private void SetupAudioCapture()
{
try
{
_capture = AudioDeviceManager.CreateAudioCapture(_appConfig.SelectedAudioDeviceId);
string audioDeviceInfo =
$"Audio Device: {_appConfig.SelectedAudioDeviceName}\n" +
$"Sample Rate: {_capture.WaveFormat.SampleRate} Hz\n" +
$"Channels: {_capture.WaveFormat.Channels}\n" +
$"Bits Per Sample: {_capture.WaveFormat.BitsPerSample}\n" +
$"Bytes Per Second: {_capture.WaveFormat.AverageBytesPerSecond}";
Console.WriteLine(audioDeviceInfo.Replace("\n", Environment.NewLine));
_visualizerManager.SetAudioDeviceInfo(audioDeviceInfo);
_capture.DataAvailable += OnDataAvailable;
_capture.RecordingStopped += (s, e) => Console.WriteLine("Recording stopped");
_capture.StartRecording();
}
catch (Exception ex)
{
Console.WriteLine($"Failed to initialize audio capture: {ex.Message}");
}
}
public void ChangeAudioDevice(string deviceId, string deviceName)
{
try
{
if (_capture != null)
{
_capture.StopRecording();
_capture.DataAvailable -= OnDataAvailable;
_capture.Dispose();
_capture = null;
}
_appConfig.SelectedAudioDeviceId = deviceId;
_appConfig.SelectedAudioDeviceName = deviceName;
lock (_bufferLock)
{
_audioBuffer.Clear();
}
_waveformData = new float[BUFFER_SIZE];
_fftData = new float[BUFFER_SIZE / 2];
SetupAudioCapture();
Console.WriteLine($"Switched to audio device: {deviceName}");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to change audio device: {ex.Message}");
}
}
private void OnDataAvailable(object? sender, WaveInEventArgs e)
{
lock (_bufferLock)
{
// Convert byte array to float array more efficiently
int sampleCount = e.BytesRecorded / 4; // 4 bytes per float sample
for (int i = 0; i < sampleCount; i++)
{
float sample = BitConverter.ToSingle(e.Buffer, i * 4);
_audioBuffer.Add(sample);
}
if (_audioBuffer.Count > BUFFER_SIZE * 2)
{
int samplesToRemove = _audioBuffer.Count - BUFFER_SIZE * 2;
_audioBuffer.RemoveRange(0, samplesToRemove);
}
}
}
private static float[] CreateHannWindow(int size)
{
var window = new float[size];
for (int i = 0; i < size; i++)
{
float t = (float)i / (size - 1);
window[i] = 0.5f - 0.5f * MathF.Cos(2 * MathF.PI * t);
}
return window;
}
private void ProcessAudioData()
{
lock (_bufferLock)
{
if (_audioBuffer.Count < BUFFER_SIZE) return;
int startIndex = _audioBuffer.Count - BUFFER_SIZE;
for (int i = 0; i < BUFFER_SIZE; i++)
{
_waveformData[i] = _audioBuffer[startIndex + i];
}
}
// If waveform is silent, set FFT data to zero
bool isSilent = _waveformData.All(x => MathF.Abs(x) < 0.0001f);
int fftLen = BUFFER_SIZE / 2;
if (isSilent)
{
_fftData = new float[fftLen];
return;
}
// Apply Hann window to waveform data before FFT
for (int i = 0; i < BUFFER_SIZE; i++)
{
_fftBuffer[i] = new Complex32(_waveformData[i] * HannWindow[i], 0);
}
// Perform FFT
Fourier.Forward(_fftBuffer, FourierOptions.Matlab);
// // Extract magnitudes for first half (avoid mirroring)
// for (int i = 0; i < BUFFER_SIZE / 2; i++)
// {
// _fftData[i] = _fftBuffer[i].Magnitude;
// // _fftData[i] = MathF.Sqrt(_fftBuffer[i].Magnitude);
// }
// cut out silent mid frequencies ...
int belowThreshold = Enumerable.Range(0, fftLen)
.Count(i => _fftBuffer[i].Magnitude < 0.005f);
float cutFraction = Math.Min(0.25f, (float)belowThreshold / fftLen);
int cutLen = (int)(cutFraction * fftLen);
int midStart = (fftLen - cutLen) / 2;
int midEnd = midStart + cutLen;
_fftData = [.. Enumerable.Range(0, fftLen)
.Where(i => i < midStart || i >= midEnd)
.Select(i => _fftBuffer[i].Magnitude)];
}
protected override void OnRenderFrame(FrameEventArgs e)
{
base.OnRenderFrame(e);
ProcessAudioData();
_imGuiController.Update(this, (float)e.Time);
var projection = Matrix4.CreateOrthographicOffCenter(0, ClientSize.X, ClientSize.Y, 0, -1, 1);
// Update and render all visualizers (including background & post-processing)
_visualizerManager.UpdateVisualizers(_waveformData, _fftData, e.Time);
_visualizerManager.RenderVisualizers(projection, ClientSize);
if (_showConfigWindow)
{
_configGui.Render();
}
_imGuiController.Render();
SwapBuffers();
}
protected override void OnUpdateFrame(FrameEventArgs e)
{
base.OnUpdateFrame(e);
if (KeyboardState.IsKeyPressed(Keys.Escape))
{
Close();
}
if (KeyboardState.IsKeyPressed(Keys.F3))
{
_showConfigWindow = !_showConfigWindow;
}
}
protected override void OnResize(ResizeEventArgs e)
{
Console.WriteLine($"Window resized: {e.Width}x{e.Height}");
base.OnResize(e);
if (WindowState != WindowState.Minimized)
{
Console.WriteLine($"Window restored: {ClientSize.X}x{ClientSize.Y}");
if (_lastWindowState == WindowState.Minimized)
{
Console.WriteLine("Restoring visualizers after minimize...");
// Re-initialize all visualizers to restore them after minimize
_visualizerManager.LoadVisualizerConfigurations(_appConfig.VisualizerConfigs, _appConfig.EnabledVisualizers);
}
GL.Viewport(0, 0, ClientSize.X, ClientSize.Y);
_imGuiController?.WindowResized(ClientSize.X, ClientSize.Y);
}
_lastWindowState = WindowState;
}
protected override void OnTextInput(TextInputEventArgs e)
{
base.OnTextInput(e);
_imGuiController?.PressChar((char)e.Unicode);
}
protected override void OnKeyDown(KeyboardKeyEventArgs e)
{
base.OnKeyDown(e);
_imGuiController?.OnKeyDown(e.Key);
}
protected override void OnKeyUp(KeyboardKeyEventArgs e)
{
base.OnKeyUp(e);
_imGuiController?.OnKeyUp(e.Key);
}
protected override void OnMouseWheel(MouseWheelEventArgs e)
{
base.OnMouseWheel(e);
_imGuiController?.MouseScroll(e.Offset);
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
// Force ImGui to save its settings before shutdown
ImGuiNET.ImGui.SaveIniSettingsToDisk(CAudioVisualizer.Configuration.AppConfig.GetImGuiConfigPath());
if (_appConfig != null && _visualizerManager != null)
{
_visualizerManager.SaveVisualizerConfigurations(_appConfig.VisualizerConfigs, _appConfig.EnabledVisualizers);
_appConfig.SaveConfiguration(CAudioVisualizer.Configuration.AppConfig.GetConfigFilePath());
}
}
protected override void OnUnload()
{
base.OnUnload();
NativeMethods.SetThreadExecutionState(NativeMethods.ES_CONTINUOUS);
_capture?.StopRecording();
_capture?.Dispose();
_visualizerManager?.Dispose();
_imGuiController?.Dispose();
}
}
static class Program
{
static void Main()
{
var tempConfig = new CAudioVisualizer.Configuration.AppConfig();
tempConfig.LoadConfiguration(CAudioVisualizer.Configuration.AppConfig.GetConfigFilePath());
var gameWindowSettings = GameWindowSettings.Default;
var monitors = Monitors.GetMonitors();
NativeWindowSettings nativeWindowSettings;
if (tempConfig.SpanAllMonitors && monitors.Count > 1)
{
int minX = monitors.Min(m => m.ClientArea.Min.X);
int minY = monitors.Min(m => m.ClientArea.Min.Y);
int maxX = monitors.Max(m => m.ClientArea.Max.X);
int maxY = monitors.Max(m => m.ClientArea.Max.Y);
nativeWindowSettings = new NativeWindowSettings()
{
Title = "Audio Visualizer - Made by Silas Kraume (Multi-Monitor)",
Flags = ContextFlags.ForwardCompatible,
Profile = ContextProfile.Core,
APIVersion = new Version(4, 6),
WindowBorder = WindowBorder.Hidden,
WindowState = WindowState.Normal,
ClientSize = new Vector2i(maxX - minX, maxY - minY),
Location = new Vector2i(minX, minY)
};
}
else
{
var selectedMonitor = monitors.Count > tempConfig.SelectedMonitorIndex && tempConfig.SelectedMonitorIndex >= 0
? monitors[tempConfig.SelectedMonitorIndex]
: Monitors.GetPrimaryMonitor();
nativeWindowSettings = new NativeWindowSettings()
{
Title = "Audio Visualizer - Made by Silas Kraume",
Flags = ContextFlags.ForwardCompatible,
Profile = ContextProfile.Core,
APIVersion = new Version(4, 6),
WindowBorder = WindowBorder.Hidden,
WindowState = WindowState.Normal,
ClientSize = new Vector2i(selectedMonitor.HorizontalResolution, selectedMonitor.VerticalResolution),
Location = new Vector2i(selectedMonitor.WorkArea.Min.X, selectedMonitor.WorkArea.Min.Y)
};
}
using var window = new AudioVisualizerWindow(gameWindowSettings, nativeWindowSettings);
window.Run();
}
}