-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudioRouter.cs
More file actions
511 lines (442 loc) · 19.3 KB
/
Copy pathAudioRouter.cs
File metadata and controls
511 lines (442 loc) · 19.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
using System.Buffers;
using NAudio.CoreAudioApi;
using NAudio.MediaFoundation;
using NAudio.Wave;
namespace MultiAudioRouter.Core;
/// <summary>
/// システム音声 (or 指定デバイス) のループバックキャプチャを取得し、
/// 必要ならデバイス毎にリサンプルした上で 1〜複数の出力先へ同時に流す。
/// </summary>
public sealed class AudioRouter : IDisposable
{
private static int _mfStarted;
private readonly DeviceEnumerator _enumerator;
private readonly bool _ownsEnumerator;
private ICaptureSource? _capture;
private MMDevice? _captureDevice;
private WaveFormat? _sourceFormat;
private List<Sink> _sinks = new();
private bool _running;
private bool _disposed;
private long _captureChunks;
private long _captureBytes;
private DateTime _lastStatsLogUtc;
private Timer? _statsTimer;
public IAudioLogger? Logger { get; set; }
public event EventHandler<Exception>? PipelineFaulted;
/// <summary>UI 表示向けの各出力シンクの瞬間スナップショット。</summary>
public sealed record SinkSnapshot(
string DeviceId,
string DeviceName,
double BufferedMs,
double FillPct,
int BufferedBytes,
int BufferLength,
string PlaybackState);
/// <summary>UI 表示向けの全シンクスナップショット (lock 取らずスレッドセーフ呼び出し可)。</summary>
public IReadOnlyList<SinkSnapshot> GetSinkSnapshots()
{
if (!_running) return Array.Empty<SinkSnapshot>();
var sinks = _sinks; // 参照スナップ
var result = new List<SinkSnapshot>(sinks.Count);
foreach (var s in sinks)
{
try
{
var b = s.Buffer;
var bufBytes = b.BufferedBytes;
var bufLen = b.BufferLength;
var pct = bufLen > 0 ? bufBytes * 100.0 / bufLen : 0;
result.Add(new SinkSnapshot(
s.Device.ID,
s.Device.FriendlyName,
b.BufferedDuration.TotalMilliseconds,
pct,
bufBytes,
bufLen,
s.Output.PlaybackState.ToString()));
}
catch { /* シンク dispose 直後は無視 */ }
}
return result;
}
/// <summary>指定 deviceId の出力音量を 0.0-1.0 で設定。動作中のみ反映。</summary>
public bool SetSinkVolume(string deviceId, float volume)
{
if (!_running) return false;
volume = Math.Clamp(volume, 0f, 1f);
foreach (var s in _sinks)
{
if (s.Device.ID == deviceId)
{
try
{
s.Output.Volume = volume;
return true;
}
catch { return false; }
}
}
return false;
}
/// <summary>ProcessLoopback 統計 (ProcessLoopback 使用時のみ非 null)。</summary>
public (long Real, long Padded, long Silent, long Discont)? GetProcessLoopbackStats()
{
if (_capture is ProcessLoopbackCaptureService plc)
return (Interlocked.Read(ref plc.RealBytes),
Interlocked.Read(ref plc.PaddedBytes),
Interlocked.Read(ref plc.SilentPacketCount),
Interlocked.Read(ref plc.DiscontinuityPacketCount));
return null;
}
public AudioRouter() : this(new DeviceEnumerator(), ownsEnumerator: true) { }
public AudioRouter(DeviceEnumerator enumerator, bool ownsEnumerator = false)
{
_enumerator = enumerator;
_ownsEnumerator = ownsEnumerator;
}
public bool IsRunning => _running;
public IReadOnlyList<string> OutputDeviceIds =>
_sinks.Select(s => s.Device.ID).ToList();
/// <summary>単一出力。Phase 1 互換。</summary>
public void Start(
string outputDeviceId,
int bufferMilliseconds = 2000,
int outputLatencyMs = 30,
int prerollMilliseconds = 0,
int maxBufferedMilliseconds = 0,
string? captureDeviceId = null,
ICaptureSource? customCapture = null)
=> Start(
new[] { outputDeviceId },
bufferMilliseconds,
outputLatencyMs,
prerollMilliseconds,
maxBufferedMilliseconds,
captureDeviceId,
customCapture);
/// <summary>複数出力同時。fan-out で各出力に同じキャプチャを配る。</summary>
/// <param name="customCapture">非 null なら、デバイス系ループバックではなくこのキャプチャ源を使う (Process Loopback 等)。</param>
public void Start(
IReadOnlyList<string> outputDeviceIds,
int bufferMilliseconds = 2000,
int outputLatencyMs = 30,
int prerollMilliseconds = 0,
int maxBufferedMilliseconds = 0,
string? captureDeviceId = null,
ICaptureSource? customCapture = null)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_running) throw new InvalidOperationException("既に動作中です。");
if (outputDeviceIds is null || outputDeviceIds.Count == 0)
throw new ArgumentException("少なくとも 1 つの出力先が必要です。", nameof(outputDeviceIds));
var distinctOuts = outputDeviceIds.Distinct().ToList();
if (distinctOuts.Count != outputDeviceIds.Count)
throw new ArgumentException("出力先に重複があります。", nameof(outputDeviceIds));
if (captureDeviceId is not null && distinctOuts.Contains(captureDeviceId))
throw new ArgumentException("キャプチャ元と同じデバイスが出力先に含まれています (フィードバックループ)。",
nameof(outputDeviceIds));
EnsureMediaFoundation();
// キャプチャ元
if (customCapture is not null)
{
_capture = customCapture;
Logger.Info("Capture", $"キャプチャ元: カスタム ({customCapture.GetType().Name})");
}
else
{
if (captureDeviceId is not null)
{
_captureDevice = _enumerator.GetDeviceById(captureDeviceId);
Logger.Info("Capture", $"キャプチャ元: {_captureDevice.FriendlyName} (ID={_captureDevice.ID})");
}
else
{
Logger.Info("Capture", "キャプチャ元: 既定の再生デバイス");
}
_capture = new LoopbackCaptureService(_captureDevice);
}
_capture.RecordingStopped += OnCaptureStopped;
_capture.Start();
_sourceFormat = _capture.WaveFormat
?? throw new InvalidOperationException("キャプチャの WaveFormat 取得に失敗しました。");
Logger.Info("Capture", $"フォーマット: {Describe(_sourceFormat)}");
// 各出力先のシンクを構築
foreach (var deviceId in distinctOuts)
{
var sink = BuildSink(deviceId, _sourceFormat, bufferMilliseconds, maxBufferedMilliseconds);
_sinks.Add(sink);
}
_capture.DataAvailable += OnCaptureData;
// プリロール: 全シンクのバッファに preroll 分が溜まるまで待ってから一斉再生開始
WaitPreroll(prerollMilliseconds);
// 全シンク再生開始
foreach (var sink in _sinks)
{
sink.Output.PlaybackStopped += OnPlaybackStopped;
sink.Output.Start(sink.Device, sink.PlaybackSource, outputLatencyMs);
Logger.Info("Output", $"再生開始 [{sink.Device.FriendlyName}] "
+ $"(latency={outputLatencyMs}ms, actual={Describe(sink.Output.OutputWaveFormat)})");
}
_lastStatsLogUtc = DateTime.UtcNow;
_statsTimer = new Timer(LogStats, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
_running = true;
Logger.Info("Router", $"起動完了: {_sinks.Count} 出力");
}
private Sink BuildSink(string deviceId, WaveFormat sourceFormat, int bufferMs, int maxBufferedMs)
{
var device = _enumerator.GetDeviceById(deviceId);
Logger.Info("Output", $"出力デバイス: {device.FriendlyName} (ID={device.ID})");
var buffer = new BufferedWaveProvider(sourceFormat)
{
BufferDuration = TimeSpan.FromMilliseconds(Math.Max(500, bufferMs)),
DiscardOnBufferOverflow = true,
ReadFully = true,
};
var maxBufferedBytes = maxBufferedMs > 0
? sourceFormat.AverageBytesPerSecond * maxBufferedMs / 1000
: 0;
var targetFormat = device.AudioClient.MixFormat;
Logger.Info("Output", $" ミックスフォーマット: {Describe(targetFormat)}");
IWaveProvider playbackSource = buffer;
MediaFoundationResampler? resampler = null;
if (!FormatsEqual(sourceFormat, targetFormat))
{
resampler = new MediaFoundationResampler(buffer, targetFormat) { ResamplerQuality = 60 };
playbackSource = resampler;
Logger.Info("Output", $" リサンプル: {Describe(sourceFormat)} -> {Describe(targetFormat)}");
}
else
{
Logger.Info("Output", " リサンプル: スキップ (compatible)");
}
return new Sink(device, buffer, resampler, new AudioOutputService(), playbackSource, maxBufferedBytes);
}
private void WaitPreroll(int prerollMilliseconds)
{
if (_sourceFormat is null) return;
if (prerollMilliseconds <= 0)
{
Logger.Info("Preroll", "スキップ (即時再生)");
return;
}
var prerollBytes = _sourceFormat.AverageBytesPerSecond * prerollMilliseconds / 1000;
var start = DateTime.UtcNow;
var deadline = start + TimeSpan.FromSeconds(2);
// 全シンクがある程度溜まるまで (1 つで十分: シンク間で同じ書き込み量のため)
var probe = _sinks.FirstOrDefault();
if (probe is null) return;
while (probe.Buffer.BufferedBytes < prerollBytes && DateTime.UtcNow < deadline)
Thread.Sleep(10);
var elapsed = (DateTime.UtcNow - start).TotalMilliseconds;
if (probe.Buffer.BufferedBytes < prerollBytes)
Logger.Warn("Preroll", $"タイムアウト ({elapsed:F0}ms): "
+ $"{probe.Buffer.BufferedBytes}/{prerollBytes} bytes — 音源無音 or デバイス無効?");
else
Logger.Info("Preroll", $"完了 ({elapsed:F0}ms): 目標 {prerollMilliseconds}ms / {prerollBytes} bytes");
}
public void Stop()
{
if (!_running) return;
_running = false;
Logger.Info("Router", "停止要求");
_statsTimer?.Dispose();
_statsTimer = null;
try { _capture?.Stop(); } catch (Exception ex) { Logger.Warn("Capture", $"停止時例外: {ex.Message}"); }
foreach (var sink in _sinks)
{
try { sink.Output.Stop(); }
catch (Exception ex) { Logger.Warn("Output", $"[{sink.Device.FriendlyName}] 停止時例外: {ex.Message}"); }
}
}
private void OnCaptureData(object? sender, WaveInEventArgs e)
{
try
{
Interlocked.Increment(ref _captureChunks);
Interlocked.Add(ref _captureBytes, e.BytesRecorded);
// 全シンクに同じデータを fan-out
foreach (var sink in _sinks)
{
var b = sink.Buffer;
if (b.BufferedBytes + e.BytesRecorded > b.BufferLength)
{
Logger.Warn("Buffer", $"[{sink.Device.FriendlyName}] オーバーフロー: "
+ $"受信 {e.BytesRecorded}B, 残容量 {b.BufferLength - b.BufferedBytes}B");
}
b.AddSamples(e.Buffer, 0, e.BytesRecorded);
// レイテンシキャップ (オプトイン): 緩やかに削って収束させる
if (sink.MaxBufferedBytes > 0 && b.BufferedBytes > sink.MaxBufferedBytes)
{
var overflow = b.BufferedBytes - sink.MaxBufferedBytes;
var dropBytes = Math.Min(overflow / 8 + b.WaveFormat.BlockAlign, e.BytesRecorded);
var align = b.WaveFormat.BlockAlign;
if (align > 0) dropBytes -= dropBytes % align;
if (dropBytes > 0)
{
var scratch = ArrayPool<byte>.Shared.Rent(dropBytes);
int actuallyRead;
try { actuallyRead = b.Read(scratch, 0, dropBytes); }
finally { ArrayPool<byte>.Shared.Return(scratch); }
Interlocked.Add(ref sink.TrimmedBytes, actuallyRead);
}
}
}
}
catch (Exception ex)
{
Logger.Error("Capture", $"DataAvailable 例外: {ex.GetType().Name}: {ex.Message}");
PipelineFaulted?.Invoke(this, ex);
}
}
private void LogStats(object? state)
{
if (!_running || _sourceFormat is null) return;
var chunks = Interlocked.Exchange(ref _captureChunks, 0);
var bytes = Interlocked.Exchange(ref _captureBytes, 0);
var now = DateTime.UtcNow;
var elapsedSec = Math.Max(0.001, (now - _lastStatsLogUtc).TotalSeconds);
_lastStatsLogUtc = now;
Logger.Debug("Stats",
$"capture={chunks}chunks/{bytes}B in {elapsedSec:F1}s ({bytes / elapsedSec / 1024:F0}KiB/s)");
// ProcessLoopback 限定の診断: Silent/Discontinuity/Padded を吸い出してログ
if (_capture is ProcessLoopbackCaptureService plc)
{
var silent = Interlocked.Exchange(ref plc.SilentPacketCount, 0);
var discont = Interlocked.Exchange(ref plc.DiscontinuityPacketCount, 0);
var padded = Interlocked.Exchange(ref plc.PaddedBytes, 0);
var real = Interlocked.Exchange(ref plc.RealBytes, 0);
var paddedMs = _sourceFormat.AverageBytesPerSecond > 0
? padded * 1000.0 / _sourceFormat.AverageBytesPerSecond : 0;
var level = (silent > 0 || discont > 0 || padded > 0) ? AudioLogLevel.Warn : AudioLogLevel.Debug;
Logger.Log(level, "Stats",
$"ProcLoopback: silent={silent}pkts, discont={discont}pkts, "
+ $"padded={paddedMs:F0}ms ({padded}B), real={real}B");
}
var bytesPerSec = _sourceFormat.AverageBytesPerSecond;
foreach (var sink in _sinks)
{
var b = sink.Buffer;
var bufferedBytes = b.BufferedBytes;
var bufferLen = b.BufferLength;
var fillPct = bufferLen > 0 ? bufferedBytes * 100.0 / bufferLen : 0;
var bufferedMs = b.BufferedDuration.TotalMilliseconds;
var trimmed = Interlocked.Exchange(ref sink.TrimmedBytes, 0);
var trimmedMs = bytesPerSec > 0 ? trimmed * 1000.0 / bytesPerSec : 0;
var playState = sink.Output.PlaybackState.ToString();
var level = AudioLogLevel.Debug;
if (fillPct < 1 || fillPct > 90 || trimmed > 0 || playState != "Playing")
level = AudioLogLevel.Warn;
Logger.Log(level, "Stats",
$"[{sink.Device.FriendlyName}] buffer={bufferedMs:F0}ms ({fillPct:F0}%, "
+ $"{bufferedBytes}/{bufferLen}B), trimmed={trimmedMs:F0}ms ({trimmed}B), "
+ $"playback={playState}");
}
}
private void OnCaptureStopped(object? sender, StoppedEventArgs e)
{
if (e.Exception is not null)
{
Logger.Error("Capture", $"異常停止: {e.Exception.GetType().Name}: {e.Exception.Message}");
PipelineFaulted?.Invoke(this, e.Exception);
}
else
{
Logger.Info("Capture", "正常停止");
}
}
private void OnPlaybackStopped(object? sender, StoppedEventArgs e)
{
if (e.Exception is not null)
{
Logger.Error("Output", $"異常停止: {e.Exception.GetType().Name}: {e.Exception.Message}");
PipelineFaulted?.Invoke(this, e.Exception);
}
else
{
Logger.Info("Output", "正常停止");
}
}
private static string Describe(WaveFormat? f)
{
if (f is null) return "(null)";
var sub = f is WaveFormatExtensible ex ? $" sub={SubtypeName(ex.SubFormat)}" : "";
return $"{f.Encoding} {f.SampleRate}Hz {f.Channels}ch {f.BitsPerSample}bit{sub}";
}
private static readonly Guid SubtypePcm = new("00000001-0000-0010-8000-00aa00389b71");
private static readonly Guid SubtypeIeeeFloat = new("00000003-0000-0010-8000-00aa00389b71");
private static string SubtypeName(Guid g) =>
g == SubtypeIeeeFloat ? "IEEE_FLOAT"
: g == SubtypePcm ? "PCM"
: g.ToString();
private static WaveFormatEncoding EffectiveEncoding(WaveFormat f)
{
if (f is WaveFormatExtensible ex)
{
if (ex.SubFormat == SubtypeIeeeFloat) return WaveFormatEncoding.IeeeFloat;
if (ex.SubFormat == SubtypePcm) return WaveFormatEncoding.Pcm;
}
return f.Encoding;
}
private static bool FormatsEqual(WaveFormat a, WaveFormat b) =>
a.SampleRate == b.SampleRate
&& a.Channels == b.Channels
&& a.BitsPerSample == b.BitsPerSample
&& EffectiveEncoding(a) == EffectiveEncoding(b);
private static void EnsureMediaFoundation()
{
if (Interlocked.Exchange(ref _mfStarted, 1) == 0)
MediaFoundationApi.Startup();
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_running = false;
_statsTimer?.Dispose();
_statsTimer = null;
if (_capture is not null)
{
_capture.DataAvailable -= OnCaptureData;
_capture.RecordingStopped -= OnCaptureStopped;
_capture.Dispose();
_capture = null;
}
foreach (var sink in _sinks)
{
sink.Output.PlaybackStopped -= OnPlaybackStopped;
sink.Dispose();
}
_sinks.Clear();
_captureDevice?.Dispose();
_captureDevice = null;
if (_ownsEnumerator)
_enumerator.Dispose();
}
/// <summary>
/// 1 つの出力先を構成する状態。
/// TrimmedBytes は Interlocked で更新するためフィールド (プロパティだと ref 不可)。
/// </summary>
private sealed class Sink(
MMDevice device,
BufferedWaveProvider buffer,
MediaFoundationResampler? resampler,
AudioOutputService output,
IWaveProvider playbackSource,
int maxBufferedBytes) : IDisposable
{
public MMDevice Device { get; } = device;
public BufferedWaveProvider Buffer { get; } = buffer;
public MediaFoundationResampler? Resampler { get; } = resampler;
public AudioOutputService Output { get; } = output;
public IWaveProvider PlaybackSource { get; } = playbackSource;
public int MaxBufferedBytes { get; } = maxBufferedBytes;
public long TrimmedBytes;
public void Dispose()
{
try { Output.Dispose(); } catch { }
try { Resampler?.Dispose(); } catch { }
try { Device.Dispose(); } catch { }
}
}
}