@aivin-labs/cli 1.0.8 → 1.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -0
- package/bin/assets/aivin-mascot.png +0 -0
- package/bin/cli.mjs +1979 -1780
- package/bin/lib/browserAutomation.mjs +232 -469
- package/bin/lib/localBrowser.mjs +345 -0
- package/bin/lib/remote/activityLog.mjs +1 -1
- package/bin/lib/remote/autoStart.mjs +174 -14
- package/bin/lib/remote/browserTunnel.mjs +187 -37
- package/bin/lib/remote/callLedger.mjs +74 -15
- package/bin/lib/remote/cdpPolicy.mjs +14 -1
- package/bin/lib/remote/client.mjs +174 -11
- package/bin/lib/remote/clipboard.mjs +138 -0
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +293 -0
- package/bin/lib/remote/constants.mjs +78 -0
- package/bin/lib/remote/dailyBrowser.mjs +9 -3
- package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
- package/bin/lib/remote/desktop/index.mjs +309 -0
- package/bin/lib/remote/desktop/linux.mjs +144 -0
- package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
- package/bin/lib/remote/desktop/mac.mjs +187 -0
- package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
- package/bin/lib/remote/desktop/strings.mjs +74 -0
- package/bin/lib/remote/desktop/traySource.mjs +541 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +86 -1
- package/bin/lib/remote/fileIndexer.mjs +757 -399
- package/bin/lib/remote/folderRules.mjs +140 -0
- package/bin/lib/remote/gui/index.mjs +208 -18
- package/bin/lib/remote/gui/windowsHost.mjs +9 -2
- package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
- package/bin/lib/remote/idempotency.mjs +50 -21
- package/bin/lib/remote/localPolicy.mjs +17 -4
- package/bin/lib/remote/mascot/adpcm.mjs +70 -0
- package/bin/lib/remote/mascot/ask.mjs +768 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
- package/bin/lib/remote/mascot/assets.mjs +825 -216
- package/bin/lib/remote/mascot/bot.mjs +397 -0
- package/bin/lib/remote/mascot/hostSource.mjs +500 -103
- package/bin/lib/remote/mascot/hotkey.mjs +66 -0
- package/bin/lib/remote/mascot/index.mjs +199 -28
- package/bin/lib/remote/mascot/labels.mjs +2 -3
- package/bin/lib/remote/mascot/rigSource.mjs +614 -0
- package/bin/lib/remote/mascot/strings.mjs +204 -18
- package/bin/lib/remote/mascot/ui.mjs +104 -0
- package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
- package/bin/lib/remote/meeting/index.mjs +415 -0
- package/bin/lib/remote/meeting/recorder.mjs +109 -0
- package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
- package/bin/lib/remote/meeting/transcribe.mjs +259 -0
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tabGroups.mjs +209 -0
- package/bin/lib/remote/toolHandlers.mjs +788 -726
- package/bin/lib/remoteControl.mjs +26 -26
- package/docs/AIVIN_MASCOT.md +130 -0
- package/docs/CLI.md +1504 -1353
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +71 -71
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Nói chuyện realtime với linh vật, phía cửa sổ (29/10/2026) — mã C# biên dịch trong host.ps1 (cùng khối Add-Type với AivinMascot.Input,
|
|
3
|
+
* hostSource.mjs ghép vào), chạy luồng nền riêng, không qua PowerShell:
|
|
4
|
+
* - Mic: mỗi ~100 ms một dòng `{"t":"voice_audio","audio":"<base64>"}` (PCM16 mono, tần số BE báo) ra stdout (qua Output — chung khoá với
|
|
5
|
+
* Send của PowerShell nên dòng không lẫn nhau). Ưu tiên bộ khử tiếng vọng của Windows (Voice Capture DSP, `Aec`: tự mở micro + nghe lại loa
|
|
6
|
+
* mặc định, trừ tiếng bot khỏi mic) → nói chen bằng giọng được. Máy không mở được DSP thì waveIn, và lúc bot đang phát (+ 350 ms đuôi) bỏ
|
|
7
|
+
* đoạn mic — không thì loa lọt vào mic, model tự nghe chính nó và tự ngắt lời; muốn ngắt lời bot thì bấm mic.
|
|
8
|
+
* - Loa: waveOut theo tần số BE báo; dòng `voice_play` / `voice_flush` trên stdin được Input chặn lại đưa thẳng vào đây (không chờ nhịp 80 ms
|
|
9
|
+
* của UI), `voice_flush` = bỏ hết phần chưa phát (người dùng nói chen / bấm ngắt lời).
|
|
10
|
+
* - Mic im quá 2 s (rút ra, Bluetooth rớt, đổi mic mặc định) → mở lại trên mic mặc định hiện tại; hỏng 3 lần liền → `voice_mic_lost`.
|
|
11
|
+
* - Loa: đầu mỗi câu trả lời đợi đủ ~150 ms tiếng (hoặc 300 ms) rồi mới phát — mạng chập chờn không làm mất / giật mấy chữ đầu.
|
|
12
|
+
* Bộ đệm + WAVEHDR nằm ở bộ nhớ không quản lý, luồng nền hỏi cờ WHDR_DONE (không dùng callback của winmm). Giữ toàn ASCII.
|
|
13
|
+
*/
|
|
14
|
+
export const VOICE_CS = String.raw`
|
|
15
|
+
public static class Output {
|
|
16
|
+
static readonly object Gate = new object();
|
|
17
|
+
static StreamWriter w;
|
|
18
|
+
public static void Line(string s) {
|
|
19
|
+
lock (Gate) {
|
|
20
|
+
try {
|
|
21
|
+
if (w == null) { w = new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(false)); w.AutoFlush = true; }
|
|
22
|
+
w.WriteLine(s);
|
|
23
|
+
} catch { }
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("59eff8b9-938c-4a26-82f2-95cb84cdc837")]
|
|
28
|
+
public interface IMediaBuffer {
|
|
29
|
+
[PreserveSig] int SetLength(int length);
|
|
30
|
+
[PreserveSig] int GetMaxLength(out int max);
|
|
31
|
+
[PreserveSig] int GetBufferAndLength(IntPtr ppBuffer, IntPtr pcbLength);
|
|
32
|
+
}
|
|
33
|
+
[StructLayout(LayoutKind.Sequential)] public struct DmoMediaType {
|
|
34
|
+
public Guid Major, Sub; public int FixedSize, Temporal; public uint SampleSize; public Guid FormatType; public IntPtr Unk; public uint FormatSize; public IntPtr Format;
|
|
35
|
+
}
|
|
36
|
+
[StructLayout(LayoutKind.Sequential)] public struct PropertyKey { public Guid Fmtid; public uint Pid; }
|
|
37
|
+
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("d8ad0f58-5494-4102-97c5-ec798e59bcf4")]
|
|
38
|
+
public interface IMediaObject {
|
|
39
|
+
[PreserveSig] int GetStreamCount(out uint inputs, out uint outputs);
|
|
40
|
+
[PreserveSig] int GetInputStreamInfo(uint index, out uint flags);
|
|
41
|
+
[PreserveSig] int GetOutputStreamInfo(uint index, out uint flags);
|
|
42
|
+
[PreserveSig] int GetInputType(uint index, uint type, IntPtr mt);
|
|
43
|
+
[PreserveSig] int GetOutputType(uint index, uint type, IntPtr mt);
|
|
44
|
+
[PreserveSig] int SetInputType(uint index, IntPtr mt, uint flags);
|
|
45
|
+
[PreserveSig] int SetOutputType(uint index, ref DmoMediaType mt, uint flags);
|
|
46
|
+
[PreserveSig] int GetInputCurrentType(uint index, IntPtr mt);
|
|
47
|
+
[PreserveSig] int GetOutputCurrentType(uint index, IntPtr mt);
|
|
48
|
+
[PreserveSig] int GetInputSizeInfo(uint index, out uint size, out uint lookahead, out uint align);
|
|
49
|
+
[PreserveSig] int GetOutputSizeInfo(uint index, out uint size, out uint align);
|
|
50
|
+
[PreserveSig] int GetInputMaxLatency(uint index, out long latency);
|
|
51
|
+
[PreserveSig] int SetInputMaxLatency(uint index, long latency);
|
|
52
|
+
[PreserveSig] int Flush();
|
|
53
|
+
[PreserveSig] int Discontinuity(uint index);
|
|
54
|
+
[PreserveSig] int AllocateStreamingResources();
|
|
55
|
+
[PreserveSig] int FreeStreamingResources();
|
|
56
|
+
[PreserveSig] int GetInputStatus(uint index, out uint flags);
|
|
57
|
+
[PreserveSig] int ProcessInput(uint index, IMediaBuffer buffer, uint flags, long time, long length);
|
|
58
|
+
[PreserveSig] int ProcessOutput(uint flags, uint count, IntPtr buffers, out uint status);
|
|
59
|
+
[PreserveSig] int Lock(int locked);
|
|
60
|
+
}
|
|
61
|
+
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99")]
|
|
62
|
+
public interface IPropertyStore {
|
|
63
|
+
[PreserveSig] int GetCount(out uint count);
|
|
64
|
+
[PreserveSig] int GetAt(uint index, out PropertyKey key);
|
|
65
|
+
[PreserveSig] int GetValue(ref PropertyKey key, IntPtr value);
|
|
66
|
+
[PreserveSig] int SetValue(ref PropertyKey key, IntPtr value);
|
|
67
|
+
[PreserveSig] int Commit();
|
|
68
|
+
}
|
|
69
|
+
[ComVisible(true)] public sealed class MediaBuffer : IMediaBuffer {
|
|
70
|
+
public readonly IntPtr Data; public readonly int Max; public int Length;
|
|
71
|
+
public MediaBuffer(int max) { Max = max; Data = Marshal.AllocHGlobal(max); }
|
|
72
|
+
public int SetLength(int length) { if (length < 0 || length > Max) return unchecked((int)0x80070057); Length = length; return 0; }
|
|
73
|
+
public int GetMaxLength(out int max) { max = Max; return 0; }
|
|
74
|
+
public int GetBufferAndLength(IntPtr ppBuffer, IntPtr pcbLength) {
|
|
75
|
+
if (ppBuffer != IntPtr.Zero) Marshal.WriteIntPtr(ppBuffer, Data);
|
|
76
|
+
if (pcbLength != IntPtr.Zero) Marshal.WriteInt32(pcbLength, Length);
|
|
77
|
+
return 0;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Windows' own echo canceller (Voice Capture DSP, the one Teams / Skype use) in source mode: it opens the default mic and listens back to
|
|
81
|
+
the default speaker itself, and hands out mic audio with the speaker's sound taken out. Runs on its own thread; Start waits for it. */
|
|
82
|
+
public sealed class Aec {
|
|
83
|
+
static readonly Guid Clsid = new Guid("745057C7-F353-4F2D-A7EE-58434477730E");
|
|
84
|
+
static readonly Guid SystemModeKey = new Guid("6f52c567-0360-4bd2-9617-ccbf1421c939");
|
|
85
|
+
static readonly Guid AudioType = new Guid("73647561-0000-0010-8000-00AA00389B71"), PcmType = new Guid("00000001-0000-0010-8000-00AA00389B71");
|
|
86
|
+
static readonly Guid WaveFormatType = new Guid("05589f81-c356-11ce-bf01-00aa0055595a");
|
|
87
|
+
const uint INCOMPLETE = 0x01000000;
|
|
88
|
+
public readonly int Rate;
|
|
89
|
+
readonly Action<byte[]> sink;
|
|
90
|
+
/** The DSP stopped working mid-way (device unplugged, driver error): the caller switches to plain capture. */
|
|
91
|
+
public Action Failed;
|
|
92
|
+
readonly ManualResetEvent started = new ManualResetEvent(false);
|
|
93
|
+
volatile bool running = true, ok;
|
|
94
|
+
public string Error;
|
|
95
|
+
|
|
96
|
+
Aec(int rate, Action<byte[]> sink) { Rate = rate; this.sink = sink; }
|
|
97
|
+
|
|
98
|
+
/** null = the DSP is not usable on this computer (caller falls back to plain capture). rate: 8000 / 11025 / 16000 / 22050. */
|
|
99
|
+
public static Aec Start(int rate, Action<byte[]> sink, out string error) {
|
|
100
|
+
var a = new Aec(rate, sink);
|
|
101
|
+
var t = new Thread(a.Run); t.IsBackground = true; t.SetApartmentState(ApartmentState.MTA); t.Start();
|
|
102
|
+
bool done = a.started.WaitOne(2000);
|
|
103
|
+
error = done ? a.Error : "timed out";
|
|
104
|
+
if (!done || !a.ok) { a.running = false; return null; }
|
|
105
|
+
return a;
|
|
106
|
+
}
|
|
107
|
+
public void Stop() { running = false; }
|
|
108
|
+
|
|
109
|
+
void Run() {
|
|
110
|
+
IMediaObject dmo = null; IntPtr fmt = IntPtr.Zero, pv = IntPtr.Zero, outs = IntPtr.Zero, pbuf = IntPtr.Zero;
|
|
111
|
+
try {
|
|
112
|
+
dmo = (IMediaObject)Activator.CreateInstance(Type.GetTypeFromCLSID(Clsid));
|
|
113
|
+
// MFPKEY_WMAAECMA_SYSTEM_MODE = SINGLE_CHANNEL_AEC (0): mic + loopback of the default devices, echo cancelled.
|
|
114
|
+
var key = new PropertyKey { Fmtid = SystemModeKey, Pid = 2 };
|
|
115
|
+
pv = Marshal.AllocHGlobal(24); for (int i = 0; i < 24; i++) Marshal.WriteByte(pv, i, 0);
|
|
116
|
+
Marshal.WriteInt16(pv, 0, 3); Marshal.WriteInt32(pv, 8, 0);
|
|
117
|
+
int hr = ((IPropertyStore)dmo).SetValue(ref key, pv);
|
|
118
|
+
if (hr != 0) throw new Exception("system mode " + hr.ToString("x"));
|
|
119
|
+
fmt = Marshal.AllocHGlobal(18);
|
|
120
|
+
Marshal.WriteInt16(fmt, 0, 1); Marshal.WriteInt16(fmt, 2, 1); Marshal.WriteInt32(fmt, 4, Rate); Marshal.WriteInt32(fmt, 8, Rate * 2);
|
|
121
|
+
Marshal.WriteInt16(fmt, 12, 2); Marshal.WriteInt16(fmt, 14, 16); Marshal.WriteInt16(fmt, 16, 0);
|
|
122
|
+
var mt = new DmoMediaType { Major = AudioType, Sub = PcmType, FixedSize = 1, Temporal = 0, SampleSize = 2, FormatType = WaveFormatType, FormatSize = 18, Format = fmt };
|
|
123
|
+
hr = dmo.SetOutputType(0, ref mt, 0);
|
|
124
|
+
if (hr != 0) throw new Exception("output type " + hr.ToString("x"));
|
|
125
|
+
hr = dmo.AllocateStreamingResources();
|
|
126
|
+
if (hr != 0) throw new Exception("allocate " + hr.ToString("x"));
|
|
127
|
+
var buf = new MediaBuffer(Rate * 2);
|
|
128
|
+
// DMO_OUTPUT_DATA_BUFFER { IMediaBuffer* pBuffer; DWORD dwStatus; REFERENCE_TIME rtTimestamp, rtTimelength } built by hand.
|
|
129
|
+
outs = Marshal.AllocHGlobal(32); for (int i = 0; i < 32; i++) Marshal.WriteByte(outs, i, 0);
|
|
130
|
+
pbuf = Marshal.GetComInterfaceForObject(buf, typeof(IMediaBuffer)); Marshal.WriteIntPtr(outs, 0, pbuf);
|
|
131
|
+
int statusAt = IntPtr.Size;
|
|
132
|
+
// It only counts as working once real mic audio comes out (some audio devices make it fail after a second of empty reads).
|
|
133
|
+
uint status;
|
|
134
|
+
while (running) {
|
|
135
|
+
bool got = false;
|
|
136
|
+
do {
|
|
137
|
+
buf.Length = 0; Marshal.WriteInt32(outs, statusAt, 0);
|
|
138
|
+
hr = dmo.ProcessOutput(0, 1, outs, out status);
|
|
139
|
+
if (hr < 0) { Error = "read " + hr.ToString("x"); if (ok && running && Failed != null) Failed(); running = false; break; }
|
|
140
|
+
if (buf.Length > 0) {
|
|
141
|
+
if (!ok) { ok = true; started.Set(); }
|
|
142
|
+
var b = new byte[buf.Length]; Marshal.Copy(buf.Data, b, 0, buf.Length); sink(b); got = true;
|
|
143
|
+
}
|
|
144
|
+
} while (running && ((uint)Marshal.ReadInt32(outs, statusAt) & INCOMPLETE) != 0);
|
|
145
|
+
if (!got) Thread.Sleep(10);
|
|
146
|
+
}
|
|
147
|
+
} catch (Exception e) { Error = e.Message; }
|
|
148
|
+
finally {
|
|
149
|
+
started.Set();
|
|
150
|
+
try { if (dmo != null) { dmo.FreeStreamingResources(); Marshal.ReleaseComObject(dmo); } } catch { }
|
|
151
|
+
if (fmt != IntPtr.Zero) Marshal.FreeHGlobal(fmt);
|
|
152
|
+
if (pv != IntPtr.Zero) Marshal.FreeHGlobal(pv);
|
|
153
|
+
if (outs != IntPtr.Zero) Marshal.FreeHGlobal(outs);
|
|
154
|
+
if (pbuf != IntPtr.Zero) Marshal.Release(pbuf);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorCo { }
|
|
159
|
+
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")]
|
|
160
|
+
interface IMMDeviceEnumerator {
|
|
161
|
+
[PreserveSig] int EnumAudioEndpoints(int flow, int mask, out IntPtr devices);
|
|
162
|
+
[PreserveSig] int GetDefaultAudioEndpoint(int flow, int role, out IMMDevice device);
|
|
163
|
+
}
|
|
164
|
+
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("D666063F-1587-4E43-81F1-B948E807363F")]
|
|
165
|
+
interface IMMDevice {
|
|
166
|
+
[PreserveSig] int Activate(ref Guid iid, int ctx, IntPtr p, [MarshalAs(UnmanagedType.IUnknown)] out object o);
|
|
167
|
+
}
|
|
168
|
+
[StructLayout(LayoutKind.Sequential)] struct AudioClientProperties { public uint Size; public int Offload; public int Category; public int Options; }
|
|
169
|
+
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("726778CD-F60A-4eda-82DE-E47610CD78AA")]
|
|
170
|
+
interface IAudioClient2 {
|
|
171
|
+
[PreserveSig] int Initialize(int shareMode, uint flags, long duration, long period, IntPtr format, IntPtr session);
|
|
172
|
+
[PreserveSig] int GetBufferSize(out uint frames);
|
|
173
|
+
[PreserveSig] int GetStreamLatency(out long latency);
|
|
174
|
+
[PreserveSig] int GetCurrentPadding(out uint frames);
|
|
175
|
+
[PreserveSig] int IsFormatSupported(int shareMode, IntPtr format, out IntPtr closest);
|
|
176
|
+
[PreserveSig] int GetMixFormat(out IntPtr format);
|
|
177
|
+
[PreserveSig] int GetDevicePeriod(out long def, out long min);
|
|
178
|
+
[PreserveSig] int Start();
|
|
179
|
+
[PreserveSig] int Stop();
|
|
180
|
+
[PreserveSig] int Reset();
|
|
181
|
+
[PreserveSig] int SetEventHandle(IntPtr h);
|
|
182
|
+
[PreserveSig] int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object o);
|
|
183
|
+
[PreserveSig] int IsOffloadCapable(int category, out int capable);
|
|
184
|
+
[PreserveSig] int SetClientProperties(ref AudioClientProperties p);
|
|
185
|
+
}
|
|
186
|
+
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317")]
|
|
187
|
+
interface IAudioCaptureClient {
|
|
188
|
+
[PreserveSig] int GetBuffer(out IntPtr data, out uint frames, out uint flags, out ulong pos, out ulong qpc);
|
|
189
|
+
[PreserveSig] int ReleaseBuffer(uint frames);
|
|
190
|
+
[PreserveSig] int GetNextPacketSize(out uint frames);
|
|
191
|
+
}
|
|
192
|
+
/** Windows 11 voice processing: a mic stream opened as "Communications" gets the system's own echo canceller (and noise suppression)
|
|
193
|
+
when the device / Voice Clarity provides one - the same path Teams uses on Windows 11. Shared mode converts to PCM16 mono for us. */
|
|
194
|
+
public sealed class CommsMic {
|
|
195
|
+
static readonly Guid AudioClient2Id = new Guid("726778CD-F60A-4eda-82DE-E47610CD78AA");
|
|
196
|
+
static readonly Guid CaptureClientId = new Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317");
|
|
197
|
+
static readonly Guid AecControlId = new Guid("f4ae25b5-aaa3-437d-b6b3-dbbe2d0e9549");
|
|
198
|
+
public readonly int Rate;
|
|
199
|
+
public bool EchoCancelled;
|
|
200
|
+
public string Error;
|
|
201
|
+
readonly Action<byte[]> sink;
|
|
202
|
+
readonly ManualResetEvent started = new ManualResetEvent(false);
|
|
203
|
+
volatile bool running = true; bool ok;
|
|
204
|
+
public Action Failed;
|
|
205
|
+
|
|
206
|
+
CommsMic(int rate, Action<byte[]> sink) { Rate = rate; this.sink = sink; }
|
|
207
|
+
|
|
208
|
+
/** null = could not open; requireAec: also null when the system has no echo canceller for this mic. */
|
|
209
|
+
public static CommsMic Start(int rate, Action<byte[]> sink, bool requireAec, out string error) {
|
|
210
|
+
var m = new CommsMic(rate, sink);
|
|
211
|
+
var t = new Thread(m.Run); t.IsBackground = true; t.SetApartmentState(ApartmentState.MTA); t.Start();
|
|
212
|
+
bool done = m.started.WaitOne(3000);
|
|
213
|
+
error = done ? m.Error : "timed out";
|
|
214
|
+
if (!done || !m.ok || (requireAec && !m.EchoCancelled)) { m.running = false; if (done && m.ok && error == null) error = "no echo canceller"; return null; }
|
|
215
|
+
return m;
|
|
216
|
+
}
|
|
217
|
+
public void Stop() { running = false; }
|
|
218
|
+
|
|
219
|
+
void Run() {
|
|
220
|
+
IAudioClient2 client = null; IntPtr fmt = IntPtr.Zero;
|
|
221
|
+
try {
|
|
222
|
+
var en = (IMMDeviceEnumerator)new MMDeviceEnumeratorCo();
|
|
223
|
+
IMMDevice dev;
|
|
224
|
+
// eCapture (1), eCommunications (2): the mic Windows uses for calls.
|
|
225
|
+
int hr = en.GetDefaultAudioEndpoint(1, 2, out dev);
|
|
226
|
+
if (hr != 0) throw new Exception("no mic " + hr.ToString("x"));
|
|
227
|
+
object o; var iid = AudioClient2Id;
|
|
228
|
+
hr = dev.Activate(ref iid, 0x17, IntPtr.Zero, out o);
|
|
229
|
+
if (hr != 0) throw new Exception("activate " + hr.ToString("x"));
|
|
230
|
+
client = (IAudioClient2)o;
|
|
231
|
+
var props = new AudioClientProperties { Size = 16, Offload = 0, Category = 3, Options = 0 };
|
|
232
|
+
hr = client.SetClientProperties(ref props);
|
|
233
|
+
if (hr != 0) throw new Exception("comms category " + hr.ToString("x"));
|
|
234
|
+
fmt = Marshal.AllocHGlobal(18);
|
|
235
|
+
Marshal.WriteInt16(fmt, 0, 1); Marshal.WriteInt16(fmt, 2, 1); Marshal.WriteInt32(fmt, 4, Rate); Marshal.WriteInt32(fmt, 8, Rate * 2);
|
|
236
|
+
Marshal.WriteInt16(fmt, 12, 2); Marshal.WriteInt16(fmt, 14, 16); Marshal.WriteInt16(fmt, 16, 0);
|
|
237
|
+
// Shared, AUTOCONVERTPCM | SRC_DEFAULT_QUALITY, 100 ms buffer.
|
|
238
|
+
hr = client.Initialize(0, 0x88000000, 1000000, 0, fmt, IntPtr.Zero);
|
|
239
|
+
if (hr != 0) throw new Exception("initialize " + hr.ToString("x"));
|
|
240
|
+
object aec; var aid = AecControlId;
|
|
241
|
+
EchoCancelled = client.GetService(ref aid, out aec) == 0 && aec != null;
|
|
242
|
+
object cc; var cid = CaptureClientId;
|
|
243
|
+
hr = client.GetService(ref cid, out cc);
|
|
244
|
+
if (hr != 0) throw new Exception("capture client " + hr.ToString("x"));
|
|
245
|
+
var cap = (IAudioCaptureClient)cc;
|
|
246
|
+
hr = client.Start();
|
|
247
|
+
if (hr != 0) throw new Exception("start " + hr.ToString("x"));
|
|
248
|
+
ok = true; started.Set();
|
|
249
|
+
while (running) {
|
|
250
|
+
uint frames;
|
|
251
|
+
hr = cap.GetNextPacketSize(out frames);
|
|
252
|
+
if (hr < 0) { Error = "read " + hr.ToString("x"); if (running && Failed != null) Failed(); break; }
|
|
253
|
+
if (frames == 0) { Thread.Sleep(10); continue; }
|
|
254
|
+
IntPtr data; uint flags; ulong pos, qpc;
|
|
255
|
+
hr = cap.GetBuffer(out data, out frames, out flags, out pos, out qpc);
|
|
256
|
+
if (hr < 0) { Error = "buffer " + hr.ToString("x"); if (running && Failed != null) Failed(); break; }
|
|
257
|
+
var b = new byte[frames * 2];
|
|
258
|
+
if ((flags & 2) == 0) Marshal.Copy(data, b, 0, b.Length);
|
|
259
|
+
cap.ReleaseBuffer(frames);
|
|
260
|
+
if (b.Length > 0) sink(b);
|
|
261
|
+
}
|
|
262
|
+
client.Stop();
|
|
263
|
+
} catch (Exception e) { Error = e.Message; }
|
|
264
|
+
finally {
|
|
265
|
+
started.Set();
|
|
266
|
+
if (fmt != IntPtr.Zero) Marshal.FreeHGlobal(fmt);
|
|
267
|
+
try { if (client != null) Marshal.ReleaseComObject(client); } catch { }
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
public static class Voice {
|
|
272
|
+
[StructLayout(LayoutKind.Sequential)] struct WaveFormat { public ushort Tag, Channels; public uint Rate, BytesPerSec; public ushort Align, Bits, Extra; }
|
|
273
|
+
[StructLayout(LayoutKind.Sequential)] struct WaveHdr { public IntPtr Data; public uint Length, Recorded; public IntPtr User; public uint Flags, Loops; public IntPtr Next, Reserved; }
|
|
274
|
+
[DllImport("winmm.dll")] static extern int waveInOpen(out IntPtr h, uint dev, ref WaveFormat f, IntPtr cb, IntPtr inst, uint flags);
|
|
275
|
+
[DllImport("winmm.dll")] static extern int waveInPrepareHeader(IntPtr h, IntPtr hdr, int size);
|
|
276
|
+
[DllImport("winmm.dll")] static extern int waveInUnprepareHeader(IntPtr h, IntPtr hdr, int size);
|
|
277
|
+
[DllImport("winmm.dll")] static extern int waveInAddBuffer(IntPtr h, IntPtr hdr, int size);
|
|
278
|
+
[DllImport("winmm.dll")] static extern int waveInStart(IntPtr h);
|
|
279
|
+
[DllImport("winmm.dll")] static extern int waveInReset(IntPtr h);
|
|
280
|
+
[DllImport("winmm.dll")] static extern int waveInClose(IntPtr h);
|
|
281
|
+
[DllImport("winmm.dll")] static extern int waveOutOpen(out IntPtr h, uint dev, ref WaveFormat f, IntPtr cb, IntPtr inst, uint flags);
|
|
282
|
+
[DllImport("winmm.dll")] static extern int waveOutPrepareHeader(IntPtr h, IntPtr hdr, int size);
|
|
283
|
+
[DllImport("winmm.dll")] static extern int waveOutUnprepareHeader(IntPtr h, IntPtr hdr, int size);
|
|
284
|
+
[DllImport("winmm.dll")] static extern int waveOutWrite(IntPtr h, IntPtr hdr, int size);
|
|
285
|
+
[DllImport("winmm.dll")] static extern int waveOutReset(IntPtr h);
|
|
286
|
+
[DllImport("winmm.dll")] static extern int waveOutClose(IntPtr h);
|
|
287
|
+
const uint WAVE_MAPPER = 0xFFFFFFFF, DONE = 1, PREPARED = 2;
|
|
288
|
+
const int IN_BUFFERS = 4, OUT_BUFFERS = 12, OUT_CAPACITY = 64 * 1024, TAIL_MS = 350;
|
|
289
|
+
static readonly int HdrSize = Marshal.SizeOf(typeof(WaveHdr));
|
|
290
|
+
static readonly int FlagsAt = (int)Marshal.OffsetOf(typeof(WaveHdr), "Flags");
|
|
291
|
+
static readonly int LengthAt = (int)Marshal.OffsetOf(typeof(WaveHdr), "Length");
|
|
292
|
+
static readonly int RecordedAt = (int)Marshal.OffsetOf(typeof(WaveHdr), "Recorded");
|
|
293
|
+
static readonly object Gate = new object();
|
|
294
|
+
static readonly ConcurrentQueue<byte[]> playQueue = new ConcurrentQueue<byte[]>();
|
|
295
|
+
static readonly AutoResetEvent playSignal = new AutoResetEvent(false);
|
|
296
|
+
static IntPtr hIn = IntPtr.Zero, hOut = IntPtr.Zero;
|
|
297
|
+
static IntPtr[] inHdrs = new IntPtr[0], outHdrs = new IntPtr[0];
|
|
298
|
+
static bool[] outUsed = new bool[0];
|
|
299
|
+
static int outRate = 24000;
|
|
300
|
+
static volatile bool live;
|
|
301
|
+
static long playingUntil;
|
|
302
|
+
static Aec aec;
|
|
303
|
+
static CommsMic comms;
|
|
304
|
+
static int inRate = 16000;
|
|
305
|
+
/** Mic audio from the echo canceller, gathered into ~100 ms pieces at the rate the server wants. */
|
|
306
|
+
static readonly MemoryStream pendingMic = new MemoryStream();
|
|
307
|
+
/** Bot audio waiting to be played (bytes) and when the first piece of a new reply arrived: start a reply only with ~150 ms in hand (or
|
|
308
|
+
after 300 ms), so a slow network does not chop the first words. */
|
|
309
|
+
static long queuedBytes, firstQueuedAt;
|
|
310
|
+
const int PREBUFFER_MS = 150, PREBUFFER_WAIT_MS = 300, MIC_STALL_MS = 2000, MIC_REOPENS = 3;
|
|
311
|
+
static volatile int session, flushes;
|
|
312
|
+
|
|
313
|
+
static WaveFormat Format(int rate) {
|
|
314
|
+
return new WaveFormat { Tag = 1, Channels = 1, Rate = (uint)rate, BytesPerSec = (uint)(rate * 2), Align = 2, Bits = 16, Extra = 0 };
|
|
315
|
+
}
|
|
316
|
+
static IntPtr NewHdr(int capacity) {
|
|
317
|
+
IntPtr data = Marshal.AllocHGlobal(capacity), hdr = Marshal.AllocHGlobal(HdrSize);
|
|
318
|
+
Marshal.StructureToPtr(new WaveHdr { Data = data, Length = (uint)capacity }, hdr, false);
|
|
319
|
+
return hdr;
|
|
320
|
+
}
|
|
321
|
+
static void FreeHdr(IntPtr hdr) {
|
|
322
|
+
if (hdr == IntPtr.Zero) return;
|
|
323
|
+
Marshal.FreeHGlobal(Marshal.ReadIntPtr(hdr)); Marshal.FreeHGlobal(hdr);
|
|
324
|
+
}
|
|
325
|
+
static uint Flags(IntPtr hdr) { return (uint)Marshal.ReadInt32(hdr, FlagsAt); }
|
|
326
|
+
static long Now() { return Stopwatch.GetTimestamp() * 1000 / Stopwatch.Frequency; }
|
|
327
|
+
public static bool Live { get { return live; } }
|
|
328
|
+
/** The mic goes through the echo canceller (talking over the bot works). */
|
|
329
|
+
public static bool EchoCancelled { get { return live && (aec != null || comms != null); } }
|
|
330
|
+
/** Loudness 0..1 of the mic (last ~100 ms) and of what the speaker plays now: the ask box's level bars. */
|
|
331
|
+
static double micLevel, outLevel;
|
|
332
|
+
static long outLevelAt;
|
|
333
|
+
public static double MicLevel { get { return live ? micLevel : 0; } }
|
|
334
|
+
public static double OutLevel { get { return Playing && Now() - Interlocked.Read(ref outLevelAt) < 400 ? outLevel : 0; } }
|
|
335
|
+
static double Loudness(byte[] pcm, int offset, int count) {
|
|
336
|
+
int n = count / 2; if (n == 0) return 0;
|
|
337
|
+
double sum = 0;
|
|
338
|
+
for (int i = 0; i < n; i++) { double v = BitConverter.ToInt16(pcm, offset + i * 2) / 32768.0; sum += v * v; }
|
|
339
|
+
return Math.Min(1, Math.Sqrt(sum / n) * 6);
|
|
340
|
+
}
|
|
341
|
+
/** Why the echo canceller could not start (debug log). */
|
|
342
|
+
public static string AecError;
|
|
343
|
+
/** The echo canceller already failed in this window: do not make the user wait for it again. */
|
|
344
|
+
static bool aecBroken;
|
|
345
|
+
/** Bot's voice is (still) coming out of the speaker. */
|
|
346
|
+
public static bool Playing { get { return live && Now() < Interlocked.Read(ref playingUntil); } }
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Open the default mic + speaker and start streaming. echoCancel: try Windows' echo canceller first (falls back to plain capture).
|
|
350
|
+
* false = no usable mic (nothing left open).
|
|
351
|
+
*/
|
|
352
|
+
public static bool Begin(int rate, int outputRate, bool echoCancel) {
|
|
353
|
+
End();
|
|
354
|
+
if (rate < 8000 || rate > 48000) rate = 16000;
|
|
355
|
+
if (outputRate < 8000 || outputRate > 48000) outputRate = 24000;
|
|
356
|
+
// Echo-free mic, best first: Windows 11 voice processing on a "Communications" stream (quick, any rate), then the older Voice
|
|
357
|
+
// Capture DSP (8 / 11.025 / 16 / 22.05 kHz: the server's rate when it is one of those, else 16 kHz resampled), else plain capture.
|
|
358
|
+
Aec started = null; CommsMic commsStarted = null; AecError = null;
|
|
359
|
+
int me = session + 1;
|
|
360
|
+
if (echoCancel) {
|
|
361
|
+
string err;
|
|
362
|
+
commsStarted = CommsMic.Start(rate, (pcm) => OnAecAudio(me, pcm, rate), true, out err);
|
|
363
|
+
if (commsStarted == null) AecError = "comms: " + err;
|
|
364
|
+
}
|
|
365
|
+
if (echoCancel && commsStarted == null && !aecBroken) {
|
|
366
|
+
int dspRate = rate == 8000 || rate == 11025 || rate == 16000 || rate == 22050 ? rate : 16000;
|
|
367
|
+
string err;
|
|
368
|
+
started = Aec.Start(dspRate, (pcm) => OnAecAudio(me, pcm, dspRate), out err);
|
|
369
|
+
AecError += "; dsp: " + err;
|
|
370
|
+
if (started == null) aecBroken = true;
|
|
371
|
+
}
|
|
372
|
+
lock (Gate) {
|
|
373
|
+
inRate = rate;
|
|
374
|
+
if (started == null && commsStarted == null && !OpenWaveIn(rate)) return false;
|
|
375
|
+
var fout = Format(outputRate); outRate = outputRate;
|
|
376
|
+
if (waveOutOpen(out hOut, WAVE_MAPPER, ref fout, IntPtr.Zero, IntPtr.Zero, 0) != 0) hOut = IntPtr.Zero;
|
|
377
|
+
outHdrs = new IntPtr[OUT_BUFFERS]; outUsed = new bool[OUT_BUFFERS];
|
|
378
|
+
for (int i = 0; i < OUT_BUFFERS; i++) outHdrs[i] = NewHdr(OUT_CAPACITY);
|
|
379
|
+
aec = started; comms = commsStarted;
|
|
380
|
+
lock (pendingMic) pendingMic.SetLength(0);
|
|
381
|
+
live = true; Interlocked.Exchange(ref playingUntil, 0);
|
|
382
|
+
session = me;
|
|
383
|
+
if (aec != null) aec.Failed = () => OnAecFailed(me);
|
|
384
|
+
else if (comms != null) comms.Failed = () => OnAecFailed(me);
|
|
385
|
+
else StartCapture(me);
|
|
386
|
+
var play = new Thread(() => PlayLoop(me)); play.IsBackground = true; play.Start();
|
|
387
|
+
return true;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
static bool OpenWaveIn(int rate) {
|
|
392
|
+
var fin = Format(rate);
|
|
393
|
+
if (waveInOpen(out hIn, WAVE_MAPPER, ref fin, IntPtr.Zero, IntPtr.Zero, 0) != 0) { hIn = IntPtr.Zero; return false; }
|
|
394
|
+
int chunk = rate / 10 * 2;
|
|
395
|
+
inHdrs = new IntPtr[IN_BUFFERS];
|
|
396
|
+
for (int i = 0; i < IN_BUFFERS; i++) {
|
|
397
|
+
inHdrs[i] = NewHdr(chunk);
|
|
398
|
+
waveInPrepareHeader(hIn, inHdrs[i], HdrSize); waveInAddBuffer(hIn, inHdrs[i], HdrSize);
|
|
399
|
+
}
|
|
400
|
+
if (waveInStart(hIn) == 0) return true;
|
|
401
|
+
CloseWaveIn();
|
|
402
|
+
return false;
|
|
403
|
+
}
|
|
404
|
+
/** Only the mic: the speaker may still be playing. */
|
|
405
|
+
static void CloseWaveIn() {
|
|
406
|
+
if (hIn == IntPtr.Zero) return;
|
|
407
|
+
waveInReset(hIn);
|
|
408
|
+
foreach (var h in inHdrs) { waveInUnprepareHeader(hIn, h, HdrSize); FreeHdr(h); }
|
|
409
|
+
waveInClose(hIn); hIn = IntPtr.Zero; inHdrs = new IntPtr[0];
|
|
410
|
+
}
|
|
411
|
+
static void StartCapture(int me) { var cap = new Thread(() => CaptureLoop(me)); cap.IsBackground = true; cap.Start(); }
|
|
412
|
+
|
|
413
|
+
/** The echo canceller died mid-conversation: keep talking on plain capture (with the mic dropped while the bot talks). */
|
|
414
|
+
static void OnAecFailed(int me) {
|
|
415
|
+
lock (Gate) {
|
|
416
|
+
if (!live || session != me || (aec == null && comms == null)) return;
|
|
417
|
+
AecError = aec != null ? aec.Error : comms.Error;
|
|
418
|
+
if (aec != null) aecBroken = true;
|
|
419
|
+
aec = null; comms = null;
|
|
420
|
+
if (OpenWaveIn(inRate)) StartCapture(me);
|
|
421
|
+
else Output.Line("{\"t\":\"voice_mic_lost\"}");
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
static void OnAecAudio(int me, byte[] pcm, int srcRate) {
|
|
426
|
+
if (!live || session != me || (aec == null && comms == null)) return;
|
|
427
|
+
byte[] piece = null;
|
|
428
|
+
lock (pendingMic) {
|
|
429
|
+
byte[] at = srcRate == inRate ? pcm : Resample(pcm, srcRate, inRate);
|
|
430
|
+
pendingMic.Write(at, 0, at.Length);
|
|
431
|
+
if (pendingMic.Length >= inRate / 10 * 2) { piece = pendingMic.ToArray(); pendingMic.SetLength(0); }
|
|
432
|
+
}
|
|
433
|
+
if (piece != null) SendMic(piece);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** Linear resampling of PCM16 mono (the DSP's 16 kHz -> a provider that wants 24 kHz). */
|
|
437
|
+
public static byte[] Resample(byte[] pcm, int from, int to) {
|
|
438
|
+
int n = pcm.Length / 2; if (n == 0 || from == to) return pcm;
|
|
439
|
+
int m = (int)((long)n * to / from);
|
|
440
|
+
var outp = new byte[m * 2];
|
|
441
|
+
for (int i = 0; i < m; i++) {
|
|
442
|
+
double pos = (double)i * from / to; int j = (int)pos; double f = pos - j;
|
|
443
|
+
short a = BitConverter.ToInt16(pcm, Math.Min(j, n - 1) * 2), b = BitConverter.ToInt16(pcm, Math.Min(j + 1, n - 1) * 2);
|
|
444
|
+
short v = (short)Math.Round(a + (b - a) * f);
|
|
445
|
+
outp[i * 2] = (byte)(v & 0xff); outp[i * 2 + 1] = (byte)((v >> 8) & 0xff);
|
|
446
|
+
}
|
|
447
|
+
return outp;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
static void SendMic(byte[] pcm) {
|
|
451
|
+
micLevel = Loudness(pcm, 0, pcm.Length);
|
|
452
|
+
Output.Line("{\"t\":\"voice_audio\",\"audio\":\"" + Convert.ToBase64String(pcm) + "\"}");
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
public static void End() {
|
|
456
|
+
lock (Gate) {
|
|
457
|
+
live = false; session++;
|
|
458
|
+
if (aec != null) { aec.Stop(); aec = null; }
|
|
459
|
+
if (comms != null) { comms.Stop(); comms = null; }
|
|
460
|
+
byte[] drop; while (playQueue.TryDequeue(out drop)) { }
|
|
461
|
+
Interlocked.Exchange(ref queuedBytes, 0);
|
|
462
|
+
playSignal.Set();
|
|
463
|
+
CloseDevices();
|
|
464
|
+
Interlocked.Exchange(ref playingUntil, 0);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
static void CloseDevices() {
|
|
469
|
+
if (hIn != IntPtr.Zero) {
|
|
470
|
+
waveInReset(hIn);
|
|
471
|
+
foreach (var h in inHdrs) { waveInUnprepareHeader(hIn, h, HdrSize); FreeHdr(h); }
|
|
472
|
+
waveInClose(hIn); hIn = IntPtr.Zero;
|
|
473
|
+
}
|
|
474
|
+
if (hOut != IntPtr.Zero) {
|
|
475
|
+
waveOutReset(hOut);
|
|
476
|
+
foreach (var h in outHdrs) { if ((Flags(h) & PREPARED) != 0) waveOutUnprepareHeader(hOut, h, HdrSize); FreeHdr(h); }
|
|
477
|
+
waveOutClose(hOut); hOut = IntPtr.Zero;
|
|
478
|
+
} else foreach (var h in outHdrs) FreeHdr(h);
|
|
479
|
+
inHdrs = new IntPtr[0]; outHdrs = new IntPtr[0]; outUsed = new bool[0];
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Plain capture. A mic that stops giving audio for 2 s (unplugged, Bluetooth gone, default device switched) is reopened on the current
|
|
484
|
+
* default mic; after 3 failed reopens the window is told (voice_mic_lost) and the conversation ends.
|
|
485
|
+
*/
|
|
486
|
+
static void CaptureLoop(int me) {
|
|
487
|
+
long lastAudio = Now(); int reopens = 0;
|
|
488
|
+
while (live && session == me) {
|
|
489
|
+
bool any = false;
|
|
490
|
+
lock (Gate) {
|
|
491
|
+
if (session != me || hIn == IntPtr.Zero) return;
|
|
492
|
+
if (Now() - lastAudio > MIC_STALL_MS) {
|
|
493
|
+
CloseWaveIn();
|
|
494
|
+
if (reopens++ >= MIC_REOPENS || !OpenWaveIn(inRate)) { Output.Line("{\"t\":\"voice_mic_lost\"}"); return; }
|
|
495
|
+
lastAudio = Now();
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
foreach (var h in inHdrs) {
|
|
499
|
+
if ((Flags(h) & DONE) == 0) continue;
|
|
500
|
+
any = true;
|
|
501
|
+
int n = Marshal.ReadInt32(h, RecordedAt);
|
|
502
|
+
if (n > 0) { lastAudio = Now(); reopens = 0; }
|
|
503
|
+
// Gated while the bot talks (no echo canceller): the bars show the mic as quiet then.
|
|
504
|
+
if (n > 0 && Playing) micLevel = 0;
|
|
505
|
+
// No echo canceller here: drop the mic while the bot talks, or it hears itself and interrupts itself.
|
|
506
|
+
if (n > 0 && !Playing) {
|
|
507
|
+
var buf = new byte[n]; Marshal.Copy(Marshal.ReadIntPtr(h), buf, 0, n);
|
|
508
|
+
SendMic(buf);
|
|
509
|
+
}
|
|
510
|
+
waveInAddBuffer(hIn, h, HdrSize);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (!any) Thread.Sleep(15);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
static void PlayLoop(int me) {
|
|
518
|
+
byte[] pending = null; int offset = 0, seenFlush = flushes;
|
|
519
|
+
while (live && session == me) {
|
|
520
|
+
if (seenFlush != flushes) { seenFlush = flushes; pending = null; }
|
|
521
|
+
if (pending == null) {
|
|
522
|
+
bool idle = Now() >= Interlocked.Read(ref playingUntil) - TAIL_MS;
|
|
523
|
+
if (idle && !playQueue.IsEmpty && Interlocked.Read(ref queuedBytes) < (long)outRate * 2 * PREBUFFER_MS / 1000
|
|
524
|
+
&& Now() - Interlocked.Read(ref firstQueuedAt) < PREBUFFER_WAIT_MS) { Thread.Sleep(10); continue; }
|
|
525
|
+
if (!playQueue.TryDequeue(out pending)) { playSignal.WaitOne(50); continue; }
|
|
526
|
+
Interlocked.Add(ref queuedBytes, -pending.Length);
|
|
527
|
+
offset = 0;
|
|
528
|
+
}
|
|
529
|
+
bool wrote = false;
|
|
530
|
+
lock (Gate) {
|
|
531
|
+
if (session != me) return;
|
|
532
|
+
if (hOut == IntPtr.Zero || seenFlush != flushes) { pending = null; continue; }
|
|
533
|
+
for (int i = 0; i < outHdrs.Length && pending != null; i++) {
|
|
534
|
+
var h = outHdrs[i];
|
|
535
|
+
if (outUsed[i] && (Flags(h) & DONE) == 0) continue;
|
|
536
|
+
if ((Flags(h) & PREPARED) != 0) waveOutUnprepareHeader(hOut, h, HdrSize);
|
|
537
|
+
int n = Math.Min(OUT_CAPACITY, pending.Length - offset);
|
|
538
|
+
Marshal.Copy(pending, offset, Marshal.ReadIntPtr(h), n);
|
|
539
|
+
outLevel = Loudness(pending, offset, Math.Min(n, outRate / 5 * 2)); Interlocked.Exchange(ref outLevelAt, Now());
|
|
540
|
+
Marshal.WriteInt32(h, LengthAt, n); Marshal.WriteInt32(h, FlagsAt, 0);
|
|
541
|
+
waveOutPrepareHeader(hOut, h, HdrSize); waveOutWrite(hOut, h, HdrSize); outUsed[i] = true;
|
|
542
|
+
long ms = n * 1000L / (outRate * 2);
|
|
543
|
+
long until = Math.Max(Now(), Interlocked.Read(ref playingUntil) - TAIL_MS) + ms + TAIL_MS;
|
|
544
|
+
Interlocked.Exchange(ref playingUntil, until);
|
|
545
|
+
offset += n; wrote = true;
|
|
546
|
+
if (offset >= pending.Length) pending = null;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
if (!wrote) Thread.Sleep(10);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** Drop what the bot has not said yet (the user talks over it / clicks to interrupt). */
|
|
554
|
+
public static void Flush() {
|
|
555
|
+
lock (Gate) {
|
|
556
|
+
flushes++;
|
|
557
|
+
byte[] drop; while (playQueue.TryDequeue(out drop)) { }
|
|
558
|
+
Interlocked.Exchange(ref queuedBytes, 0);
|
|
559
|
+
if (hOut != IntPtr.Zero) waveOutReset(hOut);
|
|
560
|
+
Interlocked.Exchange(ref playingUntil, 0);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** stdin line for the voice (handled here, off the UI thread) -> true; anything else -> false. */
|
|
565
|
+
public static bool Take(string line) {
|
|
566
|
+
if (line == null || !line.StartsWith("{\"t\":\"voice_")) return false;
|
|
567
|
+
if (line.StartsWith("{\"t\":\"voice_flush\"")) { Flush(); return true; }
|
|
568
|
+
if (!line.StartsWith("{\"t\":\"voice_play\"")) return false;
|
|
569
|
+
const string key = "\"audio\":\"";
|
|
570
|
+
int a = line.IndexOf(key, StringComparison.Ordinal);
|
|
571
|
+
if (a < 0 || !live) return true;
|
|
572
|
+
a += key.Length;
|
|
573
|
+
int b = line.IndexOf('"', a);
|
|
574
|
+
if (b <= a) return true;
|
|
575
|
+
try {
|
|
576
|
+
var pcm = Convert.FromBase64String(line.Substring(a, b - a));
|
|
577
|
+
if (playQueue.IsEmpty && Now() >= Interlocked.Read(ref playingUntil) - TAIL_MS) Interlocked.Exchange(ref firstQueuedAt, Now());
|
|
578
|
+
Interlocked.Add(ref queuedBytes, pcm.Length);
|
|
579
|
+
playQueue.Enqueue(pcm); playSignal.Set();
|
|
580
|
+
} catch { }
|
|
581
|
+
return true;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
`;
|