-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
265 lines (237 loc) · 8.8 KB
/
Copy pathProgram.cs
File metadata and controls
265 lines (237 loc) · 8.8 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
using System.Diagnostics;
using MultiAudioRouter.Core;
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("=== MultiAudioRouter (Phase 3) ===");
Console.WriteLine("システム / プロセス単位のキャプチャを、複数の出力先へ流します。");
Console.WriteLine();
using var enumerator = new DeviceEnumerator();
IReadOnlyList<AudioDeviceInfo> devices;
try
{
devices = enumerator.GetRenderDevices();
}
catch (Exception ex)
{
Console.Error.WriteLine($"デバイス一覧の取得に失敗しました: {ex.Message}");
return 1;
}
if (devices.Count == 0)
{
Console.Error.WriteLine("有効な再生デバイスが見つかりません。");
return 1;
}
Console.WriteLine("利用可能なデバイス:");
for (var i = 0; i < devices.Count; i++)
{
Console.WriteLine($" [{i}] {devices[i]}");
}
Console.WriteLine();
// 1. キャプチャモード: デバイス系ループバック or プロセス系ループバック
Console.WriteLine("キャプチャモードを選択:");
Console.WriteLine(" [0] デバイスのループバック (再生デバイスに鳴っている全部)");
Console.WriteLine(" [1] プロセス単位 (指定アプリの音だけ拾う・Windows 11)");
var modeIdx = AskDeviceIndex(2, "モード");
if (modeIdx < 0) return 0;
Console.WriteLine();
ICaptureSource? customCapture = null;
AudioDeviceInfo? captureSelected = null;
int captureIdx = -1;
if (modeIdx == 0)
{
// デバイスループバック
Console.WriteLine("キャプチャ元 (この音を拾います):");
captureIdx = AskDeviceIndex(devices.Count, "キャプチャ元");
if (captureIdx < 0) return 0;
captureSelected = devices[captureIdx];
Console.WriteLine($" → {captureSelected.FriendlyName}");
Console.WriteLine();
}
else
{
// プロセスループバック
var procs = ListAudioCandidateProcesses();
if (procs.Count == 0)
{
Console.Error.WriteLine("候補プロセスが見つかりません。");
return 1;
}
Console.WriteLine("プロセス一覧 (画面ありのみ):");
for (var i = 0; i < procs.Count; i++)
{
var p = procs[i];
Console.WriteLine($" [{i,3}] PID={p.Pid,-6} {p.Name}{(string.IsNullOrEmpty(p.Title) ? "" : $" — {p.Title}")}");
}
Console.WriteLine();
Console.Write($" プロセス番号 [0-{procs.Count - 1}] (q で中止): ");
var procInput = Console.ReadLine()?.Trim();
if (procInput is null || procInput.Equals("q", StringComparison.OrdinalIgnoreCase)) return 0;
if (!int.TryParse(procInput, out var procIdx) || procIdx < 0 || procIdx >= procs.Count)
{
Console.Error.WriteLine("無効な番号です。");
return 1;
}
var picked = procs[procIdx];
Console.WriteLine($" → PID={picked.Pid} {picked.Name}");
Console.Write(" ツリーモード [0=Include / 1=Exclude] (Enter=0): ");
var modeInput = Console.ReadLine()?.Trim();
var excludeMode = modeInput == "1";
customCapture = new ProcessLoopbackCaptureService((uint)picked.Pid, excludeMode);
Console.WriteLine($" プロセスループバック準備: {(excludeMode ? "EXCLUDE" : "INCLUDE")} ツリー");
Console.WriteLine();
}
// 2. 出力先: 複数指定可 (カンマ/スペース区切り)
Console.WriteLine("出力先 (複数指定可・カンマ or スペース区切り。例: 0,2):");
List<int> outputIndices;
while (true)
{
outputIndices = AskDeviceIndices(devices.Count, "出力先");
if (outputIndices.Count == 0) return 0;
if (captureIdx >= 0 && outputIndices.Contains(captureIdx))
{
Console.WriteLine(" キャプチャ元と同じデバイスは出力先に含められません (フィードバックループ)。");
continue;
}
if (outputIndices.Distinct().Count() != outputIndices.Count)
{
Console.WriteLine(" 出力先に重複があります。");
continue;
}
break;
}
var outputSelected = outputIndices.Select(i => devices[i]).ToList();
Console.WriteLine(" → " + string.Join(", ", outputSelected.Select(d => d.FriendlyName)));
Console.WriteLine();
var minLevel = ParseLogLevel(Environment.GetEnvironmentVariable("MAR_LOG")) ?? AudioLogLevel.Info;
using var router = new AudioRouter(enumerator, ownsEnumerator: false)
{
Logger = new DelegateAudioLogger(entry =>
{
if (entry.Level < minLevel) return;
var local = entry.TimestampUtc.ToLocalTime();
var color = entry.Level switch
{
AudioLogLevel.Error => ConsoleColor.Red,
AudioLogLevel.Warn => ConsoleColor.Yellow,
AudioLogLevel.Debug => ConsoleColor.DarkGray,
_ => ConsoleColor.Gray,
};
var line = $"[{local:HH:mm:ss.fff}] [{entry.Level,-5}] [{entry.Source,-9}] {entry.Message}";
var prev = Console.ForegroundColor;
try
{
Console.ForegroundColor = color;
if (entry.Level >= AudioLogLevel.Warn)
Console.Error.WriteLine(line);
else
Console.WriteLine(line);
}
finally
{
Console.ForegroundColor = prev;
}
})
};
router.PipelineFaulted += (_, ex) =>
Console.Error.WriteLine($"[パイプライン異常] {ex.GetType().Name}: {ex.Message}");
// Ctrl+C での綺麗な停止
using var stopSignal = new ManualResetEventSlim(false);
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
stopSignal.Set();
};
try
{
// Level 1: 高い閾値 (1.5s) のレイテンシキャップ + 頭出し用の preroll。
// 通常時はキャップに触れず、長時間ドリフトが累積した場合だけ間引いて防護。
router.Start(
outputSelected.Select(d => d.Id).ToList(),
bufferMilliseconds: 2000,
outputLatencyMs: 50,
prerollMilliseconds: 200,
maxBufferedMilliseconds: 1500,
captureDeviceId: captureSelected?.Id,
customCapture: customCapture);
}
catch (Exception ex)
{
Console.Error.WriteLine($"開始に失敗しました: {ex.Message}");
return 1;
}
Console.WriteLine("再生中です。Enter または Ctrl+C で停止します。");
// Enter キー監視を別スレッドで
var enterTask = Task.Run(() =>
{
try { Console.ReadLine(); } catch { /* 入力リダイレクト時 */ }
stopSignal.Set();
});
stopSignal.Wait();
Console.WriteLine("停止中...");
try { router.Stop(); } catch { /* ignore */ }
// ReadLine が掴んでいる場合は素直に抜ける
await Task.WhenAny(enterTask, Task.Delay(200));
Console.WriteLine("終了しました。");
return 0;
static AudioLogLevel? ParseLogLevel(string? raw) =>
Enum.TryParse<AudioLogLevel>(raw, ignoreCase: true, out var lv) ? lv : null;
static List<ProcInfo> ListAudioCandidateProcesses()
{
var list = new List<ProcInfo>();
foreach (var p in Process.GetProcesses())
{
try
{
// 画面のあるユーザー向けプロセスを優先候補に
if (p.MainWindowHandle == IntPtr.Zero) continue;
list.Add(new ProcInfo(p.Id, p.ProcessName, p.MainWindowTitle));
}
catch { /* アクセス不可は無視 */ }
finally { p.Dispose(); }
}
return list.OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase).ToList();
}
static int AskDeviceIndex(int count, string label)
{
while (true)
{
Console.Write($" {label} 番号 [0-{count - 1}] (q で中止): ");
var input = Console.ReadLine();
if (input is null) return -1;
input = input.Trim();
if (input.Equals("q", StringComparison.OrdinalIgnoreCase)) return -1;
if (int.TryParse(input, out var idx) && idx >= 0 && idx < count)
return idx;
Console.WriteLine(" 無効な入力です。");
}
}
static List<int> AskDeviceIndices(int count, string label)
{
while (true)
{
Console.Write($" {label} 番号 (カンマ/スペース区切り) [0-{count - 1}] (q で中止): ");
var input = Console.ReadLine();
if (input is null) return new List<int>();
input = input.Trim();
if (input.Equals("q", StringComparison.OrdinalIgnoreCase)) return new List<int>();
var tokens = input.Split(new[] { ',', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length == 0)
{
Console.WriteLine(" 少なくとも 1 つ指定してください。");
continue;
}
var result = new List<int>(tokens.Length);
var ok = true;
foreach (var t in tokens)
{
if (!int.TryParse(t, out var idx) || idx < 0 || idx >= count)
{
Console.WriteLine($" 無効な値: '{t}'");
ok = false;
break;
}
result.Add(idx);
}
if (ok) return result;
}
}
internal sealed record ProcInfo(int Pid, string Name, string Title);