Port managed client audio and Windows application
This commit is contained in:
+20
-72
@@ -1,95 +1,43 @@
|
||||
# VoiceCat — Windows client
|
||||
# VoiceCat — Windows client
|
||||
|
||||
WinForms (.NET 10 LTS) UI over `voicecat.dll` (MinGW-built `libvoicecat` shared library).
|
||||
The WinForms .NET 10 client uses `VoiceCat.Core` for TLS, TOFU, protocol state and encrypted UDP, and `VoiceCat.Audio` for streams, jitter, Opus and mixing. Its only native runtime component is `voicecat_media.dll`, the narrow Opus/RNNoise C shim. The old `voicecat.dll` core is no longer loaded or published.
|
||||
|
||||
## Prerequisites
|
||||
## Build
|
||||
|
||||
| Tool | Version | Notes |
|
||||
|------|---------|-------|
|
||||
| .NET SDK | 10.0.x | `dotnet --version` should report `10.0.*` |
|
||||
| CMake | 3.25+ | For building the C++ DLL |
|
||||
| MinGW-w64 / MSYS2 UCRT64 | GCC 13+ | `C:\tools\msys64\ucrt64` is the expected location |
|
||||
| vcpkg | any | `VCPKG_ROOT` env var must point to a bootstrapped clone |
|
||||
|
||||
## Build order
|
||||
|
||||
### 1. Build the server (for testing)
|
||||
Stage the pinned native media dependencies once, then build the solution:
|
||||
|
||||
```powershell
|
||||
cmake --preset dev
|
||||
cmake --build --preset dev --target voicecat-server
|
||||
./dotnet/build-native.ps1
|
||||
dotnet restore clients/windows/VoiceCat.slnx --locked-mode
|
||||
dotnet build clients/windows/VoiceCat.slnx -c Release --no-restore
|
||||
```
|
||||
|
||||
### 2. Build the DLL
|
||||
The original `VoiceCat.Interop` project remains in the repository as a migration oracle. The app references `VoiceCat.Managed`, whose compatibility facade lets the existing accessible WinForms UI keep its event-pump shape while all networking and audio state live in the idiomatic managed libraries.
|
||||
|
||||
## Publish
|
||||
|
||||
```powershell
|
||||
cmake --preset windows-client
|
||||
cmake --build --preset windows-client
|
||||
./clients/windows/publish-client.ps1
|
||||
```
|
||||
|
||||
Output: `build/windows-client/bin/voicecat.dll`
|
||||
This produces a self-contained `win-x64` distribution in `dotnet/artifacts/client/win-x64`. The script requires `voicecat_media.dll` and fails if the legacy `voicecat.dll` appears.
|
||||
|
||||
**Verify no MinGW runtime dependencies remain:**
|
||||
```powershell
|
||||
& "C:\tools\msys64\ucrt64\bin\objdump.exe" -p build/windows-client/bin/voicecat.dll |
|
||||
Select-String "DLL Name"
|
||||
```
|
||||
Expected: only Windows system DLLs (`KERNEL32.dll`, `WS2_32.dll`, `BCRYPT.dll`, etc.).
|
||||
If `libgcc_s_seh-1.dll`, `libstdc++-6.dll`, or `libwinpthread-1.dll` appear, the
|
||||
`-static-libgcc -static-libstdc++ -static -lwinpthread` link flags in `core/CMakeLists.txt`
|
||||
are not taking effect — check the CMake log for the `VOICECAT_BUILD_SHARED+WIN32` branch.
|
||||
|
||||
### 3. Build the C# solution
|
||||
The noninteractive startup and real WASAPI device check is:
|
||||
|
||||
```powershell
|
||||
cd clients/windows
|
||||
dotnet build VoiceCat.slnx
|
||||
./dotnet/artifacts/client/win-x64/VoiceCat.App.exe --smoke-test --audio
|
||||
```
|
||||
|
||||
The app's `Directory.Build.props` copies `voicecat.dll` from `../../build/windows-client/bin/`
|
||||
into the output directory automatically on every build.
|
||||
`--smoke-test` constructs the real main form and pumps the managed client. `--audio` additionally opens the default WASAPI capture and render endpoints, moves PCM through both for three seconds, and fails if capture produces no samples.
|
||||
|
||||
## Running manually
|
||||
## Run manually
|
||||
|
||||
```powershell
|
||||
# Terminal 1 — start the server
|
||||
./build/dev/bin/voicecat-server.exe --name "My Server"
|
||||
# Terminal 1
|
||||
./dotnet/artifacts/server/win-x64/VoiceCat.Server.exe
|
||||
|
||||
# Terminal 2 — launch the client
|
||||
# Terminal 2
|
||||
dotnet run --project clients/windows/VoiceCat.App/VoiceCat.App.csproj
|
||||
```
|
||||
|
||||
On first connect to a new server:
|
||||
- Enter `127.0.0.1` as the host (not `localhost` — Windows resolves `localhost` to `::1`
|
||||
first, and while the server now dual-stacks, `127.0.0.1` is cleaner for local testing).
|
||||
- The server identity dialog will appear. The TLS leaf-cert SHA-256 fingerprint is shown;
|
||||
accept to pin it. Subsequent connects to the same server will be silent (MATCHED).
|
||||
|
||||
## M5 — Moderation & admin UI
|
||||
|
||||
The WinForms client now exposes all M5 operations through the main menu and context menus:
|
||||
|
||||
- **Admin → Server accounts…** — create, reset password, and delete server accounts
|
||||
(requires `can_admin_accounts`).
|
||||
- **Channel tree right-click** — create, edit, and delete channels. The edit dialog exposes the
|
||||
full per-channel Opus configuration: mono/stereo, sample rate, bitrate, frame size,
|
||||
application mode, FEC, expected packet loss, DTX, and complexity.
|
||||
- **User list right-click** — move, kick, ban, server mute/deafen, and set permissions
|
||||
(items are gated by your own permissions).
|
||||
- **Activity log** shows async `GenericResult` feedback for every moderation request.
|
||||
- **User list** shows text indicators for self-mute, self-deafen, server-mute, and
|
||||
server-deafen states.
|
||||
|
||||
These operations require an admin-provisioned account with the appropriate permissions; the
|
||||
connect dialog already supports username/password auth.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- **PTT is focus-scoped** — the push-to-talk key only works while the VoiceCat window has
|
||||
focus. A system-wide `WH_KEYBOARD_LL` hook is not used in v1 (permissions + AV risk).
|
||||
- **Receive-side noise reduction** checkbox in per-user tuning is wired end-to-end but is a
|
||||
passthrough no-op until a real APM/NS backend is built (no working Windows/MSVC port of
|
||||
`webrtc-audio-processing` upstream — see `docs/tech-stack.md §1`).
|
||||
- **TOFU pins the TLS leaf cert**, not the declared Ed25519 identity fingerprint. Both are
|
||||
shown in the identity dialog, but the cert fingerprint is the value that is actually
|
||||
verified on reconnect. See `docs/security.md §1.1`.
|
||||
Manual release validation still includes NVDA navigation and a ten-minute two-client listen test, as required by `docs/porting-to-dotnet.md`.
|
||||
|
||||
@@ -16,7 +16,7 @@ public sealed record InputDeviceInfo(string Id, string Name, bool IsDefault)
|
||||
/// the aux device is opened client-side and needs a WASAPI id, not a miniaudio one.</summary>
|
||||
public static class InputDeviceEnumerator
|
||||
{
|
||||
public static IReadOnlyList<InputDeviceInfo> List()
|
||||
public static IReadOnlyList<InputDeviceInfo> List(bool input = true)
|
||||
{
|
||||
var result = new List<InputDeviceInfo>();
|
||||
InputDeviceCapture.IMMDeviceEnumerator? enumerator = null;
|
||||
@@ -29,7 +29,7 @@ public static class InputDeviceEnumerator
|
||||
Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"))!)!;
|
||||
|
||||
// Resolve the default capture endpoint id so the picker can flag it.
|
||||
if (enumerator.GetDefaultAudioEndpoint(1 /*eCapture*/, 0 /*eConsole*/,
|
||||
if (enumerator.GetDefaultAudioEndpoint(input ? 1 : 0, 0 /*eConsole*/,
|
||||
out var defDev) == 0 && defDev != null)
|
||||
{
|
||||
try { if (defDev.GetId(out string id) == 0) defaultId = id; }
|
||||
@@ -37,7 +37,7 @@ public static class InputDeviceEnumerator
|
||||
}
|
||||
|
||||
// DEVICE_STATE_ACTIVE = 0x1 — only currently-usable endpoints.
|
||||
if (enumerator.EnumAudioEndpoints(1 /*eCapture*/, 0x1, out collectionPtr) != 0
|
||||
if (enumerator.EnumAudioEndpoints(input ? 1 : 0, 0x1, out collectionPtr) != 0
|
||||
|| collectionPtr == IntPtr.Zero)
|
||||
return result;
|
||||
|
||||
@@ -107,6 +107,7 @@ public sealed class InputDeviceCapture : IDisposable
|
||||
private const int FrameSamples = 960; // 20 ms
|
||||
|
||||
private readonly string? _deviceId; // null = system default capture endpoint
|
||||
private readonly bool _loopback;
|
||||
|
||||
private IAudioClient? _audioClient;
|
||||
private IAudioCaptureClient? _captureClient;
|
||||
@@ -123,8 +124,9 @@ public sealed class InputDeviceCapture : IDisposable
|
||||
// Init-done signal: Set() by the capture thread after activation completes.
|
||||
private readonly ManualResetEventSlim _initDone = new(false);
|
||||
private bool _initOk;
|
||||
private int _disposed;
|
||||
|
||||
public InputDeviceCapture(string? deviceId) => _deviceId = deviceId;
|
||||
public InputDeviceCapture(string? deviceId, bool loopback = false) { _deviceId = deviceId; _loopback = loopback; }
|
||||
|
||||
/// <summary>Starts capture. Blocks until WASAPI activation completes (typically <100 ms).
|
||||
/// Returns false if the device cannot be opened.</summary>
|
||||
@@ -148,15 +150,13 @@ public sealed class InputDeviceCapture : IDisposable
|
||||
{
|
||||
_running = false;
|
||||
_bufferEvent?.Set();
|
||||
_captureThread?.Join(500);
|
||||
try { _audioClient?.Stop(); } catch { /* device already gone */ }
|
||||
if (_captureThread is not null && !_captureThread.Join(5000)) throw new TimeoutException("Capture did not stop.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
Stop();
|
||||
if (_captureClient != null) { Marshal.ReleaseComObject(_captureClient); _captureClient = null; }
|
||||
if (_audioClient != null) { Marshal.ReleaseComObject(_audioClient); _audioClient = null; }
|
||||
_bufferEvent?.Dispose();
|
||||
_initDone.Dispose();
|
||||
}
|
||||
@@ -165,10 +165,19 @@ public sealed class InputDeviceCapture : IDisposable
|
||||
|
||||
private void CaptureThreadProc()
|
||||
{
|
||||
_initOk = ActivateAndStart();
|
||||
_initDone.Set();
|
||||
if (!_initOk) return;
|
||||
CaptureLoop();
|
||||
try
|
||||
{
|
||||
_initOk = ActivateAndStart();
|
||||
_initDone.Set();
|
||||
if (_initOk && _running) CaptureLoop();
|
||||
}
|
||||
catch { _initOk = false; _initDone.Set(); }
|
||||
finally
|
||||
{
|
||||
try { _audioClient?.Stop(); } catch { }
|
||||
if (_captureClient != null) { Marshal.ReleaseComObject(_captureClient); _captureClient = null; }
|
||||
if (_audioClient != null) { Marshal.ReleaseComObject(_audioClient); _audioClient = null; }
|
||||
}
|
||||
}
|
||||
|
||||
private bool ActivateAndStart()
|
||||
@@ -192,7 +201,7 @@ public sealed class InputDeviceCapture : IDisposable
|
||||
Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"))!)!;
|
||||
|
||||
int hr = _deviceId is null
|
||||
? enumerator.GetDefaultAudioEndpoint(1 /*eCapture*/, 0 /*eConsole*/, out device)
|
||||
? enumerator.GetDefaultAudioEndpoint(_loopback ? 0 : 1, 0 /*eConsole*/, out device)
|
||||
: enumerator.GetDevice(_deviceId, out device);
|
||||
if (hr != 0 || device == null) return false;
|
||||
|
||||
@@ -220,7 +229,7 @@ public sealed class InputDeviceCapture : IDisposable
|
||||
// AUDCLNT_STREAMFLAGS_EVENTCALLBACK = 0x00040000
|
||||
// AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM = 0x80000000
|
||||
// AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY = 0x08000000
|
||||
const uint streamFlags = 0x00040000u | 0x80000000u | 0x08000000u;
|
||||
uint streamFlags = 0x00040000u | 0x80000000u | 0x08000000u | (_loopback ? 0x00020000u : 0u);
|
||||
|
||||
foreach (int ch in new[] { 2, 1 })
|
||||
{
|
||||
@@ -327,9 +336,7 @@ public sealed class InputDeviceCapture : IDisposable
|
||||
|
||||
private void FlushFrame()
|
||||
{
|
||||
var copy = new short[_accumBuf.Length];
|
||||
_accumBuf.AsSpan().CopyTo(copy);
|
||||
PcmFrameReady?.Invoke(copy, FrameSamples, _channels);
|
||||
PcmFrameReady?.Invoke(_accumBuf, FrameSamples, _channels); // Borrowed until callback returns.
|
||||
_accumCount = 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,148 +1,85 @@
|
||||
using VoiceCat.Audio;
|
||||
using VoiceCat.Interop;
|
||||
|
||||
// Owns N ProcessLoopbackCapture instances, mixes their PCM every 20 ms, and feeds
|
||||
// the result to the core via vc_stream_feed_pcm. Used for per-app audio sharing.
|
||||
namespace VoiceCat.App.Audio;
|
||||
|
||||
// Capture threads own their ring producers; the mix thread alone consumes them.
|
||||
public sealed class ProcessAudioMixer : IDisposable
|
||||
{
|
||||
private const int SampleRate = 48000;
|
||||
private const int FrameSamples = 960;
|
||||
private const int Channels = 2; // stereo; captures fall back to mono if needed
|
||||
|
||||
private readonly List<ProcessLoopbackCapture> _captures = [];
|
||||
|
||||
// Per-capture latest frame, protected by _frameLock.
|
||||
private readonly object _frameLock = new();
|
||||
private List<short[]> _latestFrames = [];
|
||||
private int _activeChannels = Channels;
|
||||
|
||||
private Thread? _mixThread;
|
||||
private volatile bool _running;
|
||||
private VoiceCatClient? _client;
|
||||
private uint _streamId;
|
||||
|
||||
private sealed class Input
|
||||
{
|
||||
internal readonly PcmRing Ring = new(16384);
|
||||
private readonly short[] stereo = new short[1920];
|
||||
internal void Feed(short[] pcm, int channels)
|
||||
{
|
||||
if (channels == 2) { Ring.TryWrite(pcm); return; }
|
||||
if (channels != 1 || pcm.Length > 960) return;
|
||||
for (int i = 0; i < pcm.Length; i++) stereo[2 * i] = stereo[2 * i + 1] = pcm[i];
|
||||
Ring.TryWrite(stereo.AsSpan(0, pcm.Length * 2));
|
||||
}
|
||||
}
|
||||
private readonly List<ProcessLoopbackCapture> captures = [];
|
||||
private Input[] inputs = [];
|
||||
private Thread? thread;
|
||||
private volatile bool running;
|
||||
private VoiceCatClient? client;
|
||||
private uint streamId;
|
||||
public void Start(AppAudioScope scope, VoiceCatClient client, uint streamId)
|
||||
{
|
||||
if (_running) return;
|
||||
_client = client;
|
||||
_streamId = streamId;
|
||||
|
||||
if (running) return;
|
||||
this.client = client; this.streamId = streamId;
|
||||
var specs = ResolveCaptures(scope);
|
||||
if (specs.Count == 0)
|
||||
inputs = specs.Select(_ => new Input()).ToArray();
|
||||
try
|
||||
{
|
||||
// nothing to capture — scope resolved to empty set
|
||||
return;
|
||||
for (int i = 0; i < specs.Count; i++)
|
||||
{
|
||||
Input input = inputs[i]; var (pid, mode) = specs[i];
|
||||
var capture = new ProcessLoopbackCapture(pid, mode);
|
||||
capture.PcmFrameReady += (pcm, _, channels) => input.Feed(pcm, channels);
|
||||
captures.Add(capture);
|
||||
if (!capture.Start()) throw new InvalidOperationException("Process audio capture could not start.");
|
||||
}
|
||||
if (inputs.Length == 0) return;
|
||||
running = true;
|
||||
thread = new Thread(MixLoop) { IsBackground = true, Name = "ProcessAudioMixer" }; thread.Start();
|
||||
}
|
||||
|
||||
lock (_frameLock)
|
||||
{
|
||||
_latestFrames = new List<short[]>(new short[specs.Count][]);
|
||||
_activeChannels = Channels;
|
||||
}
|
||||
|
||||
for (int i = 0; i < specs.Count; i++)
|
||||
{
|
||||
int captureIndex = i;
|
||||
var (pid, mode) = specs[i];
|
||||
var cap = new ProcessLoopbackCapture(pid, mode);
|
||||
cap.PcmFrameReady += (pcm, spc, ch) => OnCaptureFrame(captureIndex, pcm, ch);
|
||||
_captures.Add(cap);
|
||||
}
|
||||
|
||||
foreach (var c in _captures) c.Start();
|
||||
|
||||
_running = true;
|
||||
_mixThread = new Thread(MixLoop) { IsBackground = true, Name = "ProcessAudioMixer" };
|
||||
_mixThread.Start();
|
||||
catch { Stop(); throw; }
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_running = false;
|
||||
_mixThread?.Join(500);
|
||||
foreach (var c in _captures) { c.Stop(); c.Dispose(); }
|
||||
_captures.Clear();
|
||||
running = false;
|
||||
if (thread is not null && !thread.Join(5000)) throw new TimeoutException("Process audio mixer did not stop.");
|
||||
foreach (var capture in captures) capture.Dispose();
|
||||
captures.Clear(); inputs = []; thread = null;
|
||||
}
|
||||
|
||||
public void Dispose() => Stop();
|
||||
|
||||
// ── Capture callback ──────────────────────────────────────────────────────
|
||||
|
||||
private void OnCaptureFrame(int index, short[] pcm, int channels)
|
||||
{
|
||||
lock (_frameLock)
|
||||
{
|
||||
// Upmix mono → stereo interleave if the capture fell back to mono.
|
||||
if (channels == 1 && _activeChannels == 2)
|
||||
pcm = MonoToStereo(pcm);
|
||||
if (index < _latestFrames.Count)
|
||||
_latestFrames[index] = pcm;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Mix loop (20 ms timer) ────────────────────────────────────────────────
|
||||
|
||||
private void MixLoop()
|
||||
{
|
||||
// Use a target period close to 20 ms; small under-shoot avoids accumulating drift.
|
||||
const int periodMs = 19;
|
||||
while (_running)
|
||||
var frame = new short[1920]; var mix = new short[1920]; var sums = new int[1920];
|
||||
long deadline = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
while (running)
|
||||
{
|
||||
Thread.Sleep(periodMs);
|
||||
if (!_running) break;
|
||||
|
||||
short[] mix;
|
||||
lock (_frameLock)
|
||||
sums.AsSpan().Clear();
|
||||
foreach (Input input in inputs)
|
||||
{
|
||||
int len = FrameSamples * _activeChannels;
|
||||
mix = new short[len];
|
||||
|
||||
foreach (var frame in _latestFrames)
|
||||
{
|
||||
if (frame == null) continue;
|
||||
int frameLen = Math.Min(frame.Length, len);
|
||||
for (int i = 0; i < frameLen; i++)
|
||||
{
|
||||
int sum = mix[i] + frame[i];
|
||||
mix[i] = (short)Math.Clamp(sum, short.MinValue, short.MaxValue);
|
||||
}
|
||||
}
|
||||
while (input.Ring.Count > 11520) input.Ring.Read(frame);
|
||||
frame.AsSpan().Clear(); input.Ring.Read(frame);
|
||||
for (int i = 0; i < frame.Length; i++) sums[i] += frame[i];
|
||||
}
|
||||
|
||||
_client?.StreamFeedPcm(_streamId, mix, FrameSamples, (uint)_activeChannels);
|
||||
for (int i = 0; i < mix.Length; i++) mix[i] = (short)Math.Clamp(sums[i], short.MinValue, short.MaxValue);
|
||||
client?.StreamFeedPcm(streamId, mix, 960, 2);
|
||||
deadline += System.Diagnostics.Stopwatch.Frequency / 50;
|
||||
double wait = (deadline - System.Diagnostics.Stopwatch.GetTimestamp()) * 1000.0 / System.Diagnostics.Stopwatch.Frequency;
|
||||
if (wait > 0) Thread.Sleep((int)Math.Ceiling(wait));
|
||||
else if (wait < -100) deadline = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
// Resolve the scope to the WASAPI captures to open:
|
||||
// OnlyApps → one INCLUDE capture per selected process tree.
|
||||
// AllExceptApps → one EXCLUDE capture of the single selected process tree, which
|
||||
// natively captures the whole system render mix minus that tree
|
||||
// (dynamic — apps launched later are included automatically).
|
||||
private static List<(int pid, ProcessLoopbackCapture.Mode mode)> ResolveCaptures(AppAudioScope scope)
|
||||
private static List<(int pid, ProcessLoopbackCapture.Mode mode)> ResolveCaptures(AppAudioScope scope) => scope switch
|
||||
{
|
||||
return scope switch
|
||||
{
|
||||
OnlyApps o => o.Pids.Select(p => (p, ProcessLoopbackCapture.Mode.Include)).ToList(),
|
||||
AllExceptApps a when a.Pids.Count > 0 =>
|
||||
[(a.Pids[0], ProcessLoopbackCapture.Mode.Exclude)],
|
||||
// Entire desktop minus VoiceCat itself: EXCLUDE our own process tree.
|
||||
EntireDesktop { ExcludeSelf: true } =>
|
||||
[(Environment.ProcessId, ProcessLoopbackCapture.Mode.Exclude)],
|
||||
_ => [],
|
||||
};
|
||||
}
|
||||
|
||||
private static short[] MonoToStereo(short[] mono)
|
||||
{
|
||||
var stereo = new short[mono.Length * 2];
|
||||
for (int i = 0; i < mono.Length; i++)
|
||||
{
|
||||
stereo[i * 2] = mono[i];
|
||||
stereo[i * 2 + 1] = mono[i];
|
||||
}
|
||||
return stereo;
|
||||
}
|
||||
OnlyApps o => o.Pids.Select(p => (p, ProcessLoopbackCapture.Mode.Include)).ToList(),
|
||||
AllExceptApps a when a.Pids.Count > 0 => [(a.Pids[0], ProcessLoopbackCapture.Mode.Exclude)],
|
||||
EntireDesktop { ExcludeSelf: true } => [(Environment.ProcessId, ProcessLoopbackCapture.Mode.Exclude)],
|
||||
_ => [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -64,15 +64,15 @@ public sealed class ProcessLoopbackCapture : IDisposable
|
||||
{
|
||||
_running = false;
|
||||
_bufferEvent?.Set();
|
||||
_captureThread?.Join(500);
|
||||
if (_audioClientPtr != IntPtr.Zero) AC_Stop(_audioClientPtr);
|
||||
if (_captureThread is not null && !_captureThread.Join(5000))
|
||||
throw new TimeoutException("Process capture did not stop.");
|
||||
}
|
||||
|
||||
private int _disposed;
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
Stop();
|
||||
ComRelease(ref _captureClientPtr);
|
||||
ComRelease(ref _audioClientPtr);
|
||||
_bufferEvent?.Dispose();
|
||||
_initDone.Dispose();
|
||||
}
|
||||
@@ -81,10 +81,23 @@ public sealed class ProcessLoopbackCapture : IDisposable
|
||||
|
||||
private void CaptureThreadProc()
|
||||
{
|
||||
_initOk = ActivateAndStart();
|
||||
_initDone.Set();
|
||||
if (!_initOk) return;
|
||||
CaptureLoop();
|
||||
try
|
||||
{
|
||||
_initOk = ActivateAndStart();
|
||||
_initDone.Set();
|
||||
if (_initOk && _running) CaptureLoop();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_initOk = false;
|
||||
_initDone.Set();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (_audioClientPtr != IntPtr.Zero) AC_Stop(_audioClientPtr);
|
||||
ComRelease(ref _captureClientPtr);
|
||||
ComRelease(ref _audioClientPtr);
|
||||
}
|
||||
}
|
||||
|
||||
private bool ActivateAndStart()
|
||||
@@ -274,9 +287,9 @@ public sealed class ProcessLoopbackCapture : IDisposable
|
||||
|
||||
private void FlushFrame()
|
||||
{
|
||||
var copy = new short[_accumBuf.Length];
|
||||
_accumBuf.AsSpan().CopyTo(copy);
|
||||
PcmFrameReady?.Invoke(copy, FrameSamples, _channels);
|
||||
// The callback borrows this buffer until it returns. This capture owner cannot
|
||||
// overwrite it concurrently, which avoids one allocation every 20 ms.
|
||||
PcmFrameReady?.Invoke(_accumBuf, FrameSamples, _channels);
|
||||
_accumCount = 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using VoiceCat.Audio;
|
||||
using static VoiceCat.App.Audio.InputDeviceCapture;
|
||||
|
||||
namespace VoiceCat.App.Audio;
|
||||
|
||||
public sealed class WasapiAudioBackend : IAudioDeviceBackend
|
||||
{
|
||||
public IReadOnlyList<AudioDeviceInfo> Enumerate(bool input) => InputDeviceEnumerator.List(input).Select(d => new AudioDeviceInfo(d.Id, d.Name, d.IsDefault)).ToArray();
|
||||
public IAudioCapture OpenCapture(string? deviceId, bool loopback, CapturePcmHandler handler)
|
||||
{
|
||||
var capture = new InputDeviceCapture(NormalizeDeviceId(deviceId), loopback);
|
||||
capture.PcmFrameReady += (pcm, _, channels) => handler(pcm, channels);
|
||||
if (!capture.Start()) { capture.Dispose(); throw new InvalidOperationException("WASAPI capture could not start."); }
|
||||
return new Capture(capture);
|
||||
}
|
||||
public IAudioPlayback OpenPlayback(string? deviceId = null) => new Playback(deviceId);
|
||||
// The old miniaudio ABI persisted its raw device union as hex. Its Windows member
|
||||
// is a null-terminated UTF-16 WASAPI endpoint id; preserve saved selections.
|
||||
internal static string? NormalizeDeviceId(string? id)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id)) return null;
|
||||
if (id.StartsWith('{')) return id;
|
||||
try
|
||||
{
|
||||
byte[] bytes = Convert.FromHexString(id);
|
||||
string decoded = System.Text.Encoding.Unicode.GetString(bytes).Split('\0')[0];
|
||||
return decoded.StartsWith('{') ? decoded : null;
|
||||
}
|
||||
catch (FormatException) { return id; }
|
||||
}
|
||||
private sealed class Capture(InputDeviceCapture capture) : IAudioCapture { public void Dispose() => capture.Dispose(); }
|
||||
|
||||
private sealed class Playback : IAudioPlayback
|
||||
{
|
||||
private readonly string? deviceId;
|
||||
private readonly PcmRing pcm = new(32768);
|
||||
private readonly ManualResetEventSlim initialized = new(false);
|
||||
private readonly Thread thread;
|
||||
private volatile bool running = true;
|
||||
private bool ready;
|
||||
private int disposed;
|
||||
internal Playback(string? deviceId)
|
||||
{
|
||||
this.deviceId = deviceId;
|
||||
thread = new Thread(Work) { IsBackground = true, Name = "VoiceCat WASAPI playback" };
|
||||
thread.Start();
|
||||
if (!initialized.Wait(5000) || !ready) { Dispose(); throw new InvalidOperationException("WASAPI playback could not start."); }
|
||||
}
|
||||
public void Write(ReadOnlySpan<short> stereoPcm) => pcm.TryWrite(stereoPcm);
|
||||
private unsafe void Work()
|
||||
{
|
||||
IMMDeviceEnumerator? enumerator = null; IMMDevice? device = null; IAudioClient? client = null; IAudioRenderClient? render = null;
|
||||
using var bufferReady = new AutoResetEvent(false);
|
||||
try
|
||||
{
|
||||
enumerator = (IMMDeviceEnumerator)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"))!)!;
|
||||
int result = deviceId is null ? enumerator.GetDefaultAudioEndpoint(0, 0, out device) : enumerator.GetDevice(deviceId, out device);
|
||||
if (result < 0 || device is null) return;
|
||||
Guid iid = typeof(IAudioClient).GUID;
|
||||
if (device.Activate(ref iid, 0x17, 0, out object audio) < 0) return;
|
||||
client = (IAudioClient)audio;
|
||||
WaveFormat format = new() { Format = 1, Channels = 2, Samples = 48000, Bytes = 192000, Align = 4, Bits = 16 };
|
||||
if (client.Initialize(0, 0x00040000u | 0x80000000u | 0x08000000u, 600000, 0, (nint)(&format), 0) < 0) return;
|
||||
if (client.GetBufferSize(out uint capacity) < 0 || client.SetEventHandle(bufferReady.SafeWaitHandle.DangerousGetHandle()) < 0) return;
|
||||
iid = typeof(IAudioRenderClient).GUID;
|
||||
if (client.GetService(ref iid, out object output) < 0) return;
|
||||
render = (IAudioRenderClient)output;
|
||||
if (client.Start() < 0) return;
|
||||
ready = true; initialized.Set();
|
||||
Span<short> discard = stackalloc short[1920];
|
||||
while (running)
|
||||
{
|
||||
bufferReady.WaitOne(20); // Scheduling wait is outside the buffer-fill cycle.
|
||||
if (!running || client.GetCurrentPadding(out uint padding) < 0) break;
|
||||
uint frames = capacity - Math.Min(capacity, padding);
|
||||
if (frames == 0) continue;
|
||||
if (render.GetBuffer(frames, out nint buffer) < 0) break;
|
||||
var destination = new Span<short>((void*)buffer, checked((int)frames * 2));
|
||||
// Keep queued playback bounded to ~120 ms, then fill underflow with silence.
|
||||
while (pcm.Count > 11520) pcm.Read(discard);
|
||||
int count = pcm.Read(destination); destination[count..].Clear();
|
||||
if (render.ReleaseBuffer(frames, 0) < 0) break;
|
||||
}
|
||||
}
|
||||
catch { ready = false; }
|
||||
finally
|
||||
{
|
||||
initialized.Set();
|
||||
try { client?.Stop(); } catch { }
|
||||
if (render is not null) Marshal.ReleaseComObject(render);
|
||||
if (client is not null) Marshal.ReleaseComObject(client);
|
||||
if (device is not null) Marshal.ReleaseComObject(device);
|
||||
if (enumerator is not null) Marshal.ReleaseComObject(enumerator);
|
||||
}
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref disposed, 1) != 0) return;
|
||||
running = false;
|
||||
if (!thread.Join(5000)) throw new TimeoutException("WASAPI playback did not stop.");
|
||||
initialized.Dispose();
|
||||
}
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 2)]
|
||||
private struct WaveFormat { internal ushort Format, Channels; internal uint Samples, Bytes; internal ushort Align, Bits, Extra; }
|
||||
[ComImport, Guid("F294ACFC-3146-4483-A7BF-ADDCA7C260E2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
private interface IAudioRenderClient
|
||||
{
|
||||
[PreserveSig] int GetBuffer(uint frames, out nint data);
|
||||
[PreserveSig] int ReleaseBuffer(uint frames, uint flags);
|
||||
}
|
||||
}
|
||||
@@ -119,7 +119,7 @@ public partial class ConnectDialog : Form
|
||||
Directory.CreateDirectory(tofuDir);
|
||||
|
||||
_client = new VoiceCatClient("VoiceCat-Windows", VoiceCatClient.VersionString,
|
||||
VcLogLevel.Info, ServerListStore.TofuStorePath);
|
||||
VcLogLevel.Info, ServerListStore.TofuStorePath, new VoiceCat.App.Audio.WasapiAudioBackend());
|
||||
_client.EventReceived += OnEvent;
|
||||
_identityDialogShown = false;
|
||||
_pumpTimer.Start();
|
||||
|
||||
@@ -5,7 +5,7 @@ namespace VoiceCat.App;
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
private static void Main()
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
// Surface exceptions that WinForms' default message-loop handling would otherwise
|
||||
// swallow silently (or crash with no visible cause).
|
||||
@@ -16,12 +16,37 @@ internal static class Program
|
||||
|
||||
ApplicationConfiguration.Initialize();
|
||||
|
||||
if (args.Contains("--smoke-test"))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var client = new VoiceCat.Interop.VoiceCatClient("Smoke", "test");
|
||||
using var form = new MainForm(client, 0, "Smoke", "Managed core");
|
||||
form.CreateControl();
|
||||
if (form.Controls.Count == 0 || string.IsNullOrEmpty(form.Text)) return 1;
|
||||
client.PumpEvents();
|
||||
if (args.Contains("--audio"))
|
||||
{
|
||||
var backend = new Audio.WasapiAudioBackend();
|
||||
using var playback = backend.OpenPlayback();
|
||||
int samples = 0;
|
||||
using var capture = backend.OpenCapture(null, false, (pcm, _) => Interlocked.Add(ref samples, pcm.Length));
|
||||
short[] silence = new short[1920];
|
||||
for (int i = 0; i < 150; i++) { playback.Write(silence); Thread.Sleep(20); }
|
||||
if (samples == 0) return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
catch { return 1; }
|
||||
}
|
||||
|
||||
using var connectDialog = new ConnectDialog();
|
||||
var result = connectDialog.ShowDialog();
|
||||
if (result != DialogResult.OK || connectDialog.ConnectedClient is null)
|
||||
return;
|
||||
return 0;
|
||||
|
||||
Application.Run(new MainForm(connectDialog.ConnectedClient, connectDialog.SelfUserId,
|
||||
connectDialog.Nickname, connectDialog.ServerName));
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\VoiceCat.Interop\VoiceCat.Interop.csproj" />
|
||||
<ProjectReference Include="..\VoiceCat.Managed\VoiceCat.Managed.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Prismatoid — .NET bindings for the Prism speech library, used for spoken event
|
||||
@@ -42,18 +42,6 @@
|
||||
as part of the Windows Desktop shared framework on net10.0-windows — no PackageReference
|
||||
needed (one was tried and NuGet flagged it as redundant/unprunable, NU1510). -->
|
||||
|
||||
<!-- voicecat.dll must exist (build the `windows-client` CMake preset first — see
|
||||
clients/windows/README.md). -->
|
||||
<ItemGroup>
|
||||
<Content Include="$(VoiceCatNativeDir)\voicecat.dll" Condition="Exists('$(VoiceCatNativeDir)\voicecat.dll')">
|
||||
<Link>voicecat.dll</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="VoiceCatCheckNativeDll" BeforeTargets="Build">
|
||||
<Error Condition="!Exists('$(VoiceCatNativeDir)\voicecat.dll')"
|
||||
Text="voicecat.dll not found at '$(VoiceCatNativeDir)'. Build it first: cmake --preset windows-client && cmake --build --preset windows-client (see clients/windows/README.md)." />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
{
|
||||
"version": 1,
|
||||
"dependencies": {
|
||||
"net10.0-windows7.0": {
|
||||
"Microsoft.NET.ILLink.Tasks": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.7, )",
|
||||
"resolved": "10.0.7",
|
||||
"contentHash": "AA/yhzFHNtQZXLdqjzujPy25G8EWwGWsAnxOE2zYSBoT/8QHP6ketN3CToD3DFreO653ipUwnKHo22B8AlBMCw=="
|
||||
},
|
||||
"Prismatoid": {
|
||||
"type": "Direct",
|
||||
"requested": "[0.3.0, )",
|
||||
"resolved": "0.3.0",
|
||||
"contentHash": "mUOgtmFtjbLxydrdAImkfP3u0U8qrYkvfx2NlQqdQQ8TB9qe59BobxBCcNDo21g8xSefkBJB1VdGPbVTfiE7zw=="
|
||||
},
|
||||
"BouncyCastle.Cryptography": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.6.2",
|
||||
"contentHash": "7oWOcvnntmMKNzDLsdxAYqApt+AjpRpP2CShjMfIa3umZ42UQMvH0tl1qAliYPNYO6vTdcGMqnRrCPmsfzTI1w=="
|
||||
},
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.36.1",
|
||||
"contentHash": "77AqPEoaY1ODE+syYBHti0jXiwQq0J/fUr/fRyYhNlc9oKtH5dZZEr/OLKtdKNVG83PRnCYB2r8B80ZrObzOGQ=="
|
||||
},
|
||||
"voicecat.audio": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"VoiceCat.Codec": "[1.0.0, )",
|
||||
"VoiceCat.Dsp": "[1.0.0, )",
|
||||
"VoiceCat.Protocol": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.codec": {
|
||||
"type": "Project"
|
||||
},
|
||||
"voicecat.core": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"VoiceCat.Audio": "[1.0.0, )",
|
||||
"VoiceCat.Crypto": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.crypto": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"BouncyCastle.Cryptography": "[2.6.2, )",
|
||||
"VoiceCat.Protocol": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.dsp": {
|
||||
"type": "Project"
|
||||
},
|
||||
"voicecat.managed": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"VoiceCat.Core": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.protocol": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "[3.36.1, )"
|
||||
}
|
||||
}
|
||||
},
|
||||
"net10.0-windows7.0/win-x64": {
|
||||
"Prismatoid": {
|
||||
"type": "Direct",
|
||||
"requested": "[0.3.0, )",
|
||||
"resolved": "0.3.0",
|
||||
"contentHash": "mUOgtmFtjbLxydrdAImkfP3u0U8qrYkvfx2NlQqdQQ8TB9qe59BobxBCcNDo21g8xSefkBJB1VdGPbVTfiE7zw=="
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -272,6 +272,8 @@ public sealed class VoiceCatClientSmokeTests : IDisposable
|
||||
Assert.Equal(VcResult.Ok, events.First(e => e.Type == VcEventType.AuthResult).Result);
|
||||
Assert.True(PumpUntil(client, () => events.Any(e => e.Type == VcEventType.ChannelList), 3000));
|
||||
|
||||
Assert.Equal(VcResult.Ok, client.JoinVoice());
|
||||
Assert.True(PumpUntil(client, () => events.Any(e => e.Type == VcEventType.VoiceState && e.U32a == 1), 5000));
|
||||
// Give the async UDP binding handshake a moment to land before announcing a stream
|
||||
// (mirrors vccli's 500ms sleep after auth).
|
||||
Thread.Sleep(500);
|
||||
@@ -340,6 +342,10 @@ public sealed class VoiceCatClientSmokeTests : IDisposable
|
||||
Assert.True(PumpUntil(b, () => eventsB.Any(e => e.Type == VcEventType.JoinResult), 5000),
|
||||
"B did not receive VC_EVENT_JOIN_RESULT");
|
||||
|
||||
Assert.Equal(VcResult.Ok, a.JoinVoice());
|
||||
Assert.Equal(VcResult.Ok, b.JoinVoice());
|
||||
Assert.True(PumpUntil(a, () => eventsA.Any(e => e.Type == VcEventType.VoiceState && e.U32a == 1), 5000));
|
||||
Assert.True(PumpUntil(b, () => eventsB.Any(e => e.Type == VcEventType.VoiceState && e.U32a == 1), 5000));
|
||||
// UDP binding handshake is async; give it a moment (mirrors ScreenAudio test).
|
||||
Thread.Sleep(500);
|
||||
|
||||
|
||||
@@ -9,5 +9,6 @@
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>VoiceCat.Interop</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup><InternalsVisibleTo Include="VoiceCat.Interop.Tests" /></ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using Voicecat.V1;
|
||||
|
||||
namespace VoiceCat.Interop;
|
||||
|
||||
public sealed partial class VoiceCatClient
|
||||
{
|
||||
public VcResult KickUser(uint id, string? reason = null) => Request(new() { Kick = new() { UserId = id, Reason = reason ?? "" } });
|
||||
public VcResult BanUser(uint id, string? reason = null, ulong expiresUnixMs = 0) => Request(new() { Ban = new() { UserId = id, Reason = reason ?? "", ExpiresUnixMs = expiresUnixMs } });
|
||||
public VcResult MoveUser(uint id, uint channelId) => Request(new() { MoveUser = new() { UserId = id, ChannelId = channelId } });
|
||||
public VcResult SetServerMute(uint id, bool muted, bool deafened) => Request(new() { ServerMute = new() { UserId = id, Muted = muted, Deafened = deafened } });
|
||||
public VcResult SetPermission(uint id, PermissionsInfo permissions) => Request(new() { SetPermission = new() { UserId = id, Permissions = new()
|
||||
{ IsAdmin = permissions.IsAdmin, CanCreateTempChannel = permissions.CanCreateTempChannel, CanAdminAccounts = permissions.CanAdminAccounts, CanBan = permissions.CanBan, CanKick = permissions.CanKick, CanMoveUsers = permissions.CanMoveUsers } } });
|
||||
public VcResult CreateAccount(string username, string password) => Request(new() { CreateAccount = new() { Username = username, Password = password } });
|
||||
public VcResult ResetPassword(string username, string password) => Request(new() { ResetPassword = new() { Username = username, NewPassword = password } });
|
||||
public VcResult DeleteAccount(string username) => Request(new() { DeleteAccount = new() { Username = username } });
|
||||
public VcResult RequestAccountList() => Request(new() { ListAccounts = new() });
|
||||
public VcResult CreateChannel(ChannelEditInfo info) => Request(new() { CreateChannel = new() { Channel = Channel(info), Password = info.Password ?? "" } });
|
||||
public VcResult EditChannel(ChannelEditInfo info) => Request(new() { EditChannel = new() { Channel = Channel(info), Password = info.Password ?? "" } });
|
||||
public VcResult DeleteChannel(uint id) => Request(new() { DeleteChannel = new() { ChannelId = id } });
|
||||
public VcResult SendText(VcTextScope scope, uint targetId, string body)
|
||||
{
|
||||
try { core.Send(new() { TextMessage = new() { Scope = (TextScope)scope, TargetId = targetId, Body = body, ClientMsgId = Guid.NewGuid().ToString("N") } }); return VcResult.Ok; }
|
||||
catch { return VcResult.NotConnected; }
|
||||
}
|
||||
private static Voicecat.V1.Channel Channel(ChannelEditInfo info) => new()
|
||||
{
|
||||
Id = info.Id, ParentId = info.ParentId, Name = info.Name, Topic = info.Topic, MaxUsers = info.MaxUsers, Order = unchecked((int)info.SortOrder),
|
||||
Audio = new() { Codec = info.Audio.Codec, Mode = info.Audio.Stereo ? ChannelMode.ModeStereo : ChannelMode.ModeMono, SampleRate = info.Audio.SampleRate,
|
||||
BitrateBps = info.Audio.BitrateBps, FrameMs = info.Audio.FrameMs, Application = (OpusApplication)info.Audio.Application, Complexity = info.Audio.Complexity,
|
||||
Fec = info.Audio.Fec, ExpectedPacketLoss = info.Audio.ExpectedPacketLoss, Dtx = info.Audio.Dtx, Dred = info.Audio.Dred }
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using VoiceCat.Audio;
|
||||
using Voicecat.V1;
|
||||
|
||||
namespace VoiceCat.Interop;
|
||||
|
||||
public sealed partial class VoiceCatClient
|
||||
{
|
||||
private sealed record PcmRegistration(nint Callback, nint User);
|
||||
private PcmRegistration? pcm;
|
||||
public (VcResult Result, uint StreamId) StartStream(VcStreamKind kind, string label) => Start(kind, label, false);
|
||||
public (VcResult Result, uint StreamId) StartStreamExternalFeed(VcStreamKind kind, string label) => Start(kind, label, true);
|
||||
private (VcResult, uint) Start(VcStreamKind kind, string label, bool external)
|
||||
{
|
||||
StreamInfo? stream = null;
|
||||
try
|
||||
{
|
||||
stream = core.StartStreamAsync((StreamKind)kind, label).GetAwaiter().GetResult();
|
||||
local[stream.StreamId] = new(stream, external);
|
||||
if (!external && backend is not null) captures[stream.StreamId] = Capture(stream);
|
||||
return (VcResult.Ok, stream.StreamId);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
if (stream is not null) { local.TryRemove(stream.StreamId, out _); core.StopStream(stream.StreamId); }
|
||||
Queue(new(VcEventType.Error, Result: VcResult.Audio, Text: exception.Message)); return (VcResult.Audio, 0);
|
||||
}
|
||||
}
|
||||
private IAudioCapture Capture(StreamInfo stream) => backend!.OpenCapture(devices.GetValueOrDefault(stream.StreamId), stream.Kind == StreamKind.StreamScreenAudio,
|
||||
(samples, channels) => StreamFeedPcm(stream.StreamId, samples, samples.Length / channels, (uint)channels));
|
||||
public VcResult StopStream(uint id)
|
||||
{
|
||||
if (captures.Remove(id, out var capture)) capture.Dispose();
|
||||
if (!local.TryRemove(id, out LocalStream? stream)) return VcResult.InvalidArg;
|
||||
try { core.StopStream(stream.Info.StreamId); return VcResult.Ok; } catch { return VcResult.NotConnected; }
|
||||
}
|
||||
public VcResult SetInputDevice(uint id, string? device)
|
||||
{
|
||||
devices[id] = device;
|
||||
if (!captures.Remove(id, out var previous)) return VcResult.Ok;
|
||||
previous.Dispose();
|
||||
try { var info = local[id].Info.Clone(); info.StreamId = id; captures[id] = Capture(info); return VcResult.Ok; }
|
||||
catch { return VcResult.Audio; }
|
||||
}
|
||||
public VcResult SetCaptureChannels(uint id, uint channels)
|
||||
{ try { LocalStream stream = local[id]; core.Audio.SetCaptureChannels(stream.Info.StreamId, checked((int)channels)); stream.CaptureChannels = (int)channels; return VcResult.Ok; } catch { return VcResult.InvalidArg; } }
|
||||
public VcResult AudioRestart()
|
||||
{
|
||||
foreach (uint id in captures.Keys.ToArray()) { VcResult result = SetInputDevice(id, devices.GetValueOrDefault(id)); if (result != VcResult.Ok) return result; }
|
||||
return VcResult.Ok;
|
||||
}
|
||||
public VcResult SetInputMode(VcInputMode mode) { if (!Enum.IsDefined(mode)) return VcResult.InvalidArg; core.Audio.InputMode = (AudioInputMode)mode; return VcResult.Ok; }
|
||||
public VcResult SetVadThreshold(float threshold) { if (!float.IsFinite(threshold) || threshold is < 0 or > 1) return VcResult.InvalidArg; core.Audio.VadThreshold = threshold; return VcResult.Ok; }
|
||||
public VcResult SetPushToTalk(bool active) { core.Audio.PushToTalk = active; return VcResult.Ok; }
|
||||
public VcResult SetSelfMute(bool muted, bool deafened) { core.Audio.MicMuted = muted; core.Audio.Deafened = deafened; return VcResult.Ok; }
|
||||
public VcResult SetOutputVolume(float gain) { if (!float.IsFinite(gain) || gain is < 0 or > 4) return VcResult.InvalidArg; core.Audio.OutputGain = gain; return VcResult.Ok; }
|
||||
public VcResult SetInputGain(float gain) { if (!float.IsFinite(gain) || gain is < 0 or > 4) return VcResult.InvalidArg; core.Audio.InputGain = gain; return VcResult.Ok; }
|
||||
public VcResult SetInputNoiseReduction(bool enabled) { core.Audio.InputNoiseReduction = enabled; return VcResult.Ok; }
|
||||
public VcResult SetRemoteStream(uint userId, uint streamId, float gain, bool muted, bool nr)
|
||||
{ try { core.Audio.SetRemotePlayback(userId, streamId, gain, muted, nr); return VcResult.Ok; } catch { return VcResult.InvalidArg; } }
|
||||
public (VcResult Result, RemoteStreamState? State) GetRemoteStream(uint userId, uint streamId)
|
||||
{
|
||||
var state = core.Audio.GetRemotePlayback(userId, streamId);
|
||||
return state is { } value ? (VcResult.Ok, new(value.Gain, value.Muted, value.NoiseReduction)) : (VcResult.InvalidArg, null);
|
||||
}
|
||||
public (VcResult Result, AudioConfigInfo? Config) GetStreamAudioConfig(uint userId, uint streamId)
|
||||
{
|
||||
var info = core.Users.FirstOrDefault(u => u.Id == userId)?.Streams.FirstOrDefault(s => s.StreamId == streamId);
|
||||
if (core.Authentication?.Self.Id == userId && local.TryGetValue(streamId, out LocalStream? own)) info = own.Info;
|
||||
return info is null ? (VcResult.InvalidArg, null) : (VcResult.Ok, Audio(info.Audio));
|
||||
}
|
||||
public VcResult StreamFeedPcm(uint id, ReadOnlySpan<short> samples, int samplesPerChannel, uint channels)
|
||||
{
|
||||
if (samplesPerChannel < 0 || channels is not (1 or 2) || samples.Length != (long)samplesPerChannel * channels) return VcResult.InvalidArg;
|
||||
if (!local.TryGetValue(id, out LocalStream? stream)) return VcResult.InvalidArg;
|
||||
core.Audio.FeedPcm(Volatile.Read(ref stream.Info).StreamId, samples, (int)channels); return VcResult.Ok; // A full real-time ring drops, never waits.
|
||||
}
|
||||
public VcResult SetPcmSink(nint callback, nint user) { Volatile.Write(ref pcm, callback == 0 ? null : new(callback, user)); return VcResult.Ok; }
|
||||
private unsafe void ForwardPcm(uint userId, uint streamId, ReadOnlySpan<short> samples, int channels)
|
||||
{
|
||||
var target = Volatile.Read(ref pcm); if (target is null) return;
|
||||
fixed (short* input = samples)
|
||||
((delegate* unmanaged[Cdecl]<nint, uint, uint, short*, nuint, uint, uint, void>)target.Callback)(target.User, userId, streamId, input, (nuint)(samples.Length / channels), (uint)channels, 48000);
|
||||
}
|
||||
|
||||
// Server-authoritative moves/edits stop old SSRCs. Reannounce with the new channel
|
||||
// configuration while keeping UI/external-feed ids stable; captures continue feeding
|
||||
// the alias and switch to the new audio owner only when negotiation completes.
|
||||
private void ReconcileStreams()
|
||||
{
|
||||
var active = core.LocalStreams;
|
||||
foreach (LocalStream stream in local.Values)
|
||||
if (!active.Any(s => s.StreamId == stream.Info.StreamId) && Interlocked.CompareExchange(ref stream.Restarting, 1, 0) == 0) _ = RestartAsync(stream);
|
||||
}
|
||||
private async Task RestartAsync(LocalStream stream)
|
||||
{
|
||||
try
|
||||
{
|
||||
StreamInfo previous = stream.Info;
|
||||
StreamInfo next = await core.StartStreamAsync(previous.Kind, previous.Label, stream.CaptureChannels).ConfigureAwait(false);
|
||||
if (!local.ContainsKey(stream.Alias)) core.StopStream(next.StreamId);
|
||||
else Volatile.Write(ref stream.Info, next);
|
||||
}
|
||||
catch (Exception exception) { Queue(new(VcEventType.Error, Result: VcResult.Audio, Text: exception.Message)); }
|
||||
finally { Volatile.Write(ref stream.Restarting, 0); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../dotnet/src/VoiceCat.Core/VoiceCat.Core.csproj" />
|
||||
<Compile Include="../VoiceCat.Interop/Enums.cs" Link="Enums.cs" />
|
||||
<Compile Include="../VoiceCat.Interop/Models.cs" Link="Models.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,193 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading.Channels;
|
||||
using System.Collections.Concurrent;
|
||||
using VoiceCat.Audio;
|
||||
using VoiceCat.Core;
|
||||
using VoiceCat.Crypto;
|
||||
using Voicecat.V1;
|
||||
using CoreClient = VoiceCat.Core.VoiceCatClient;
|
||||
|
||||
namespace VoiceCat.Interop;
|
||||
|
||||
// Preserves the shipped WinForms call/event surface while its implementation moves to
|
||||
// the async managed core. Events still reach controls only through PumpEvents on the UI thread.
|
||||
public sealed partial class VoiceCatClient : IDisposable
|
||||
{
|
||||
private readonly CoreClient core;
|
||||
private readonly IAudioDeviceBackend? backend;
|
||||
private readonly System.Threading.Channels.Channel<VoiceCatEvent> events = System.Threading.Channels.Channel.CreateUnbounded<VoiceCatEvent>();
|
||||
private readonly Dictionary<uint, IAudioCapture> captures = [];
|
||||
private readonly Dictionary<uint, string?> devices = [];
|
||||
private readonly Dictionary<uint, StreamSummary[]> remoteStreams = [];
|
||||
private readonly Dictionary<uint, bool> talkState = [];
|
||||
private sealed class LocalStream(StreamInfo info, bool external)
|
||||
{
|
||||
internal readonly uint Alias = info.StreamId;
|
||||
internal StreamInfo Info = info;
|
||||
internal readonly bool External = external;
|
||||
internal int CaptureChannels = 1;
|
||||
internal int Restarting;
|
||||
}
|
||||
private readonly ConcurrentDictionary<uint, LocalStream> local = new();
|
||||
private IAudioPlayback? playback;
|
||||
private Task connecting = Task.CompletedTask;
|
||||
private TaskCompletionSource<bool>? identity;
|
||||
private int disposed;
|
||||
private List<AccountInfo> accounts = [];
|
||||
private bool audioFailureReported;
|
||||
public event Action<VoiceCatEvent>? EventReceived;
|
||||
public event Action<uint, float>? LevelChanged;
|
||||
public CoreClient ManagedClient => core;
|
||||
|
||||
public VoiceCatClient(string clientName, string clientVersion, VcLogLevel logLevel = VcLogLevel.Info, string? tofuStorePath = null, IAudioDeviceBackend? audioBackend = null)
|
||||
{
|
||||
backend = audioBackend;
|
||||
core = new(clientName, clientVersion, tofuStorePath);
|
||||
core.ConnectionStateChanged += state =>
|
||||
{
|
||||
VcConnectionState mapped = state switch { ClientConnectionState.Connecting => VcConnectionState.Connecting, ClientConnectionState.VerifyingIdentity => VcConnectionState.VerifyingIdentity,
|
||||
ClientConnectionState.Authenticating => VcConnectionState.Authenticating, ClientConnectionState.Connected => VcConnectionState.Connected, _ => VcConnectionState.Disconnected };
|
||||
Queue(new(VcEventType.ConnectionState, ConnectionState: mapped));
|
||||
if (mapped == VcConnectionState.Disconnected) Queue(new(VcEventType.Disconnected));
|
||||
};
|
||||
core.Audio.MixedPcm += pcm => Volatile.Read(ref playback)?.Write(pcm);
|
||||
core.Audio.StreamPcm += ForwardPcm;
|
||||
}
|
||||
|
||||
private void Queue(VoiceCatEvent message) => events.Writer.TryWrite(message);
|
||||
public VcResult Connect(string host, ushort port)
|
||||
{
|
||||
if (!connecting.IsCompleted || core.State != ClientConnectionState.Disconnected) return VcResult.Already;
|
||||
connecting = ConnectAsync(host, port);
|
||||
return VcResult.Ok;
|
||||
}
|
||||
private async Task ConnectAsync(string host, ushort port)
|
||||
{
|
||||
try
|
||||
{
|
||||
await core.ConnectAsync(host, port, async (challenge, token) =>
|
||||
{
|
||||
identity = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
Queue(new(VcEventType.ServerIdentity, U32a: (uint)challenge.Status, Text: challenge.CertificateFingerprint));
|
||||
return await identity.Task.WaitAsync(token).ConfigureAwait(false);
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception) { Queue(new(VcEventType.Error, Result: VcResult.Io, Text: exception.Message)); }
|
||||
}
|
||||
public VcResult ConfirmServerIdentity(bool accept) { identity?.TrySetResult(accept); return VcResult.Ok; }
|
||||
public VcResult AuthenticateGuest(string nickname) { _ = AuthenticateAsync(() => core.AuthenticateGuestAsync(nickname)); return VcResult.Ok; }
|
||||
public VcResult AuthenticateUser(string username, string password) { _ = AuthenticateAsync(() => core.AuthenticateUserAsync(username, password)); return VcResult.Ok; }
|
||||
private async Task AuthenticateAsync(Func<Task<AuthResult>> authenticate)
|
||||
{
|
||||
try { await connecting.ConfigureAwait(false); await authenticate().ConfigureAwait(false); }
|
||||
catch (Exception exception) { Queue(new(VcEventType.AuthResult, Result: VcResult.AuthFailed, Text: exception.Message)); }
|
||||
}
|
||||
public VcResult Disconnect()
|
||||
{
|
||||
StopDevices(); core.DisconnectAsync().GetAwaiter().GetResult(); return VcResult.Ok;
|
||||
}
|
||||
public string GetServerIdentityDisplay() => core.ServerHello is { } hello ? Convert.ToHexString(hello.ServerIdentityFingerprint.Span) : "";
|
||||
|
||||
public void PumpEvents()
|
||||
{
|
||||
if (!audioFailureReported && core.Audio.Failure is { } failure) { audioFailureReported = true; Queue(new(VcEventType.Error, Result: VcResult.Audio, Text: failure.Message)); }
|
||||
while (core.TryReadEvent(out Envelope? message)) Translate(message!);
|
||||
while (events.Reader.TryRead(out VoiceCatEvent? message)) EventReceived?.Invoke(message);
|
||||
foreach (LocalStream stream in local.Values)
|
||||
{
|
||||
var info = Volatile.Read(ref stream.Info);
|
||||
var level = core.Audio.GetLocalLevel(info.StreamId); LevelChanged?.Invoke(stream.Alias, level.Level);
|
||||
if (talkState.GetValueOrDefault(stream.Alias) != level.Talking)
|
||||
{
|
||||
talkState[stream.Alias] = level.Talking;
|
||||
if (core.State == ClientConnectionState.Connected) core.Send(new() { StreamState = new() { StreamId = info.StreamId, Talking = level.Talking, Muted = core.Audio.MicMuted } });
|
||||
EventReceived?.Invoke(new(VcEventType.TalkState, UserId: core.Authentication?.Self.Id ?? 0, StreamId: stream.Alias, U32a: level.Talking ? 1U : 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Translate(Envelope message)
|
||||
{
|
||||
if (message.AuthResult is not null) Queue(new(VcEventType.AuthResult, Result: message.AuthResult.Ok ? VcResult.Ok : VcResult.AuthFailed, UserId: message.AuthResult.Self?.Id ?? 0, Text: message.AuthResult.Error));
|
||||
if (message.ServerState is not null) { remoteStreams.Clear(); foreach (User user in message.ServerState.Users) UpdateStreams(user); Queue(new(VcEventType.ChannelList)); }
|
||||
if (message.ChannelEvent is not null) Queue(new(VcEventType.ChannelList));
|
||||
if (message.UserEvent is not null)
|
||||
{
|
||||
var change = message.UserEvent;
|
||||
if (change.User is { VoiceSubscribed: true } self && self.Id == core.Authentication?.Self.Id) ReconcileStreams();
|
||||
if (change.User is not null) UpdateStreams(change.User);
|
||||
if (change.Kind == UserEvent.Types.Kind.Left) remoteStreams.Remove(change.LeftId);
|
||||
Queue(new(change.Kind switch { UserEvent.Types.Kind.Joined => VcEventType.UserJoined, UserEvent.Types.Kind.Left => VcEventType.UserLeft, _ => VcEventType.UserUpdated }, UserId: change.User?.Id ?? change.LeftId,
|
||||
ChannelId: change.User?.ChannelId ?? 0, Text: change.Kind == UserEvent.Types.Kind.Joined ? change.User?.Nickname : change.Reason));
|
||||
}
|
||||
if (message.JoinChannelResult is not null) Queue(new(VcEventType.JoinResult, Result: message.JoinChannelResult.Ok ? VcResult.Ok : VcResult.InvalidArg, ChannelId: message.JoinChannelResult.ChannelId, Text: message.JoinChannelResult.Error));
|
||||
if (message.VoiceSubscriptionResult is not null) Queue(new(VcEventType.VoiceState, U32a: message.VoiceSubscriptionResult.Subscribed ? 1U : 0));
|
||||
if (message.TextMessage is not null) Queue(new(VcEventType.TextMessage, UserId: message.TextMessage.SenderId, ChannelId: message.TextMessage.TargetId, TextScope: (VcTextScope)message.TextMessage.Scope, Text: message.TextMessage.Body, TimestampUnixMs: message.TextMessage.SentAtUnixMs));
|
||||
if (message.StreamState is not null) Queue(new(VcEventType.TalkState, UserId: message.StreamState.UserId, StreamId: message.StreamState.UserId == core.Authentication?.Self.Id ? local.Values.FirstOrDefault(s => s.Info.StreamId == message.StreamState.StreamId)?.Alias ?? message.StreamState.StreamId : message.StreamState.StreamId, U32a: message.StreamState.Talking ? 1U : 0));
|
||||
if (message.GenericResult is not null) Queue(new(VcEventType.GenericResult, Result: message.GenericResult.Ok ? VcResult.Ok : message.GenericResult.Code == 6 ? VcResult.PermissionDenied : VcResult.InvalidArg, U32a: message.GenericResult.Code, Text: message.GenericResult.Message));
|
||||
if (message.ListAccountsResult is not null)
|
||||
{
|
||||
accounts = message.ListAccountsResult.Accounts.Select(a => new AccountInfo(a.Username, a.IsAdmin, a.CreatedAtUnixMs, a.LastLoginUnixMs)).ToList();
|
||||
Queue(new(VcEventType.AccountList));
|
||||
}
|
||||
if (message.Disconnect is not null) Queue(new(VcEventType.Error, Result: VcResult.Io, Text: message.Disconnect.Reason));
|
||||
}
|
||||
|
||||
private void UpdateStreams(User user)
|
||||
{
|
||||
StreamSummary[] previous = remoteStreams.GetValueOrDefault(user.Id, []);
|
||||
StreamSummary[] next = user.Id == core.Authentication?.Self.Id ? ListUserStreams(user.Id).ToArray() : user.Streams.Select(s => new StreamSummary(s.StreamId, (VcStreamKind)s.Kind, s.Label)).ToArray();
|
||||
foreach (var stream in previous) if (!next.Any(s => s.StreamId == stream.StreamId)) Queue(new(VcEventType.StreamStopped, UserId: user.Id, StreamId: stream.StreamId));
|
||||
foreach (var stream in next) if (!previous.Any(s => s.StreamId == stream.StreamId)) Queue(new(VcEventType.StreamStarted, UserId: user.Id, StreamId: stream.StreamId, U32a: (uint)stream.Kind, Text: stream.Label));
|
||||
remoteStreams[user.Id] = next;
|
||||
}
|
||||
|
||||
private VcResult Request(Envelope request)
|
||||
{
|
||||
if (core.State != ClientConnectionState.Connected) return VcResult.NotConnected;
|
||||
try { _ = RequestAsync(request); return VcResult.Ok; }
|
||||
catch { return VcResult.NotConnected; }
|
||||
}
|
||||
private async Task RequestAsync(Envelope request)
|
||||
{
|
||||
try { await core.RequestAsync(request).ConfigureAwait(false); }
|
||||
catch (Exception exception) { Queue(new(VcEventType.Error, Result: VcResult.Io, Text: exception.Message)); }
|
||||
}
|
||||
public VcResult JoinChannel(uint id, string? password = null) => Request(new() { JoinChannel = new() { ChannelId = id, Password = password ?? "" } });
|
||||
public VcResult LeaveChannel() => Request(new() { LeaveChannel = new() });
|
||||
public VcResult JoinVoice()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (backend is not null && playback is null) playback = backend.OpenPlayback();
|
||||
var result = core.SubscribeVoiceAsync().GetAwaiter().GetResult();
|
||||
if (!result.Ok) { Interlocked.Exchange(ref playback, null)?.Dispose(); }
|
||||
return result.Ok ? VcResult.Ok : VcResult.Audio;
|
||||
}
|
||||
catch (Exception exception) { Queue(new(VcEventType.Error, Result: VcResult.Audio, Text: exception.Message)); return VcResult.Audio; }
|
||||
}
|
||||
public VcResult LeaveVoice() { StopDevices(); local.Clear(); return Request(new() { UnsubscribeVoice = new() }); }
|
||||
|
||||
public List<ChannelInfo> ListChannels() => core.Channels.Select(c => new ChannelInfo(c.Id, c.ParentId, c.Name, c.Topic, c.PasswordProtected, c.MaxUsers, unchecked((uint)c.Order), Audio(c.Audio))).ToList();
|
||||
public List<UserInfo> ListUsers() => core.Users.Select(u => new UserInfo(u.Id, u.Nickname, u.IsGuest, u.ChannelId, u.SelfMicMuted, u.SelfDeafened, u.ServerMuted, u.ServerDeafened, u.VoiceSubscribed)).ToList();
|
||||
public List<StreamSummary> ListUserStreams(uint id) => id == core.Authentication?.Self.Id
|
||||
? local.Values.Select(s => new StreamSummary(s.Alias, (VcStreamKind)s.Info.Kind, s.Info.Label)).ToList()
|
||||
: core.Users.FirstOrDefault(u => u.Id == id)?.Streams.Select(s => new StreamSummary(s.StreamId, (VcStreamKind)s.Kind, s.Label)).ToList() ?? [];
|
||||
public PermissionsInfo GetPermissions() { Permissions p = core.Authentication?.Permissions ?? new(); return new(p.CanCreateTempChannel, p.CanKick, p.CanBan, p.CanMoveUsers, p.CanAdminAccounts, p.IsAdmin); }
|
||||
public List<AccountInfo> ListAccounts() => accounts.ToList();
|
||||
public List<DeviceInfo> ListDevices(VcDeviceKind kind) => backend?.Enumerate(kind == VcDeviceKind.Input).Select(d => new DeviceInfo(d.Id, d.Name, d.IsDefault)).ToList() ?? [];
|
||||
public static string VersionString => "VoiceCat managed core 0.1.0 (protocol v2)";
|
||||
public static string ResultString(VcResult result) => result.ToString();
|
||||
private static AudioConfigInfo Audio(AudioConfig a) => new(a.Codec, a.Mode == ChannelMode.ModeStereo, a.SampleRate, a.BitrateBps, a.FrameMs, (uint)a.Application, a.Fec, a.ExpectedPacketLoss, a.Dtx, a.Complexity, a.Dred);
|
||||
|
||||
private void StopDevices()
|
||||
{
|
||||
foreach (var capture in captures.Values) capture.Dispose(); captures.Clear(); local.Clear();
|
||||
IAudioPlayback? previous = Interlocked.Exchange(ref playback, null); previous?.Dispose();
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref disposed, 1) != 0) return;
|
||||
identity?.TrySetResult(false); StopDevices(); core.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace VoiceCat.Interop;
|
||||
|
||||
// Compatibility event consumed by WinForms. The managed core owns protocol and audio;
|
||||
// this assembly contains no libvoicecat bindings or native handles.
|
||||
public sealed record VoiceCatEvent(VcEventType Type, VcConnectionState ConnectionState = VcConnectionState.Disconnected,
|
||||
VcResult Result = VcResult.Ok, uint UserId = 0, uint ChannelId = 0, uint StreamId = 0, VcTextScope TextScope = VcTextScope.Channel,
|
||||
uint U32a = 0, string? Text = null, ulong TimestampUnixMs = 0);
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"version": 1,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"BouncyCastle.Cryptography": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.6.2",
|
||||
"contentHash": "7oWOcvnntmMKNzDLsdxAYqApt+AjpRpP2CShjMfIa3umZ42UQMvH0tl1qAliYPNYO6vTdcGMqnRrCPmsfzTI1w=="
|
||||
},
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.36.1",
|
||||
"contentHash": "77AqPEoaY1ODE+syYBHti0jXiwQq0J/fUr/fRyYhNlc9oKtH5dZZEr/OLKtdKNVG83PRnCYB2r8B80ZrObzOGQ=="
|
||||
},
|
||||
"voicecat.audio": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"VoiceCat.Codec": "[1.0.0, )",
|
||||
"VoiceCat.Dsp": "[1.0.0, )",
|
||||
"VoiceCat.Protocol": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.codec": {
|
||||
"type": "Project"
|
||||
},
|
||||
"voicecat.core": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"VoiceCat.Audio": "[1.0.0, )",
|
||||
"VoiceCat.Crypto": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.crypto": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"BouncyCastle.Cryptography": "[2.6.2, )",
|
||||
"VoiceCat.Protocol": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.dsp": {
|
||||
"type": "Project"
|
||||
},
|
||||
"voicecat.protocol": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "[3.36.1, )"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"version": 1,
|
||||
"dependencies": {
|
||||
"net10.0": {
|
||||
"Microsoft.NET.ILLink.Tasks": {
|
||||
"type": "Direct",
|
||||
"requested": "[10.0.7, )",
|
||||
"resolved": "10.0.7",
|
||||
"contentHash": "AA/yhzFHNtQZXLdqjzujPy25G8EWwGWsAnxOE2zYSBoT/8QHP6ketN3CToD3DFreO653ipUwnKHo22B8AlBMCw=="
|
||||
},
|
||||
"BouncyCastle.Cryptography": {
|
||||
"type": "Transitive",
|
||||
"resolved": "2.6.2",
|
||||
"contentHash": "7oWOcvnntmMKNzDLsdxAYqApt+AjpRpP2CShjMfIa3umZ42UQMvH0tl1qAliYPNYO6vTdcGMqnRrCPmsfzTI1w=="
|
||||
},
|
||||
"Google.Protobuf": {
|
||||
"type": "Transitive",
|
||||
"resolved": "3.36.1",
|
||||
"contentHash": "77AqPEoaY1ODE+syYBHti0jXiwQq0J/fUr/fRyYhNlc9oKtH5dZZEr/OLKtdKNVG83PRnCYB2r8B80ZrObzOGQ=="
|
||||
},
|
||||
"voicecat.audio": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"VoiceCat.Codec": "[1.0.0, )",
|
||||
"VoiceCat.Dsp": "[1.0.0, )",
|
||||
"VoiceCat.Protocol": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.codec": {
|
||||
"type": "Project"
|
||||
},
|
||||
"voicecat.core": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"VoiceCat.Audio": "[1.0.0, )",
|
||||
"VoiceCat.Crypto": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.crypto": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"BouncyCastle.Cryptography": "[2.6.2, )",
|
||||
"VoiceCat.Protocol": "[1.0.0, )"
|
||||
}
|
||||
},
|
||||
"voicecat.dsp": {
|
||||
"type": "Project"
|
||||
},
|
||||
"voicecat.protocol": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Google.Protobuf": "[3.36.1, )"
|
||||
}
|
||||
}
|
||||
},
|
||||
"net10.0/win-x64": {}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
<Solution>
|
||||
<Folder Name="/Managed core/">
|
||||
<Project Path="../../dotnet/src/VoiceCat.Core/VoiceCat.Core.csproj" />
|
||||
<Project Path="../../dotnet/src/VoiceCat.Audio/VoiceCat.Audio.csproj" />
|
||||
<Project Path="../../dotnet/src/VoiceCat.Codec/VoiceCat.Codec.csproj" />
|
||||
<Project Path="../../dotnet/src/VoiceCat.Crypto/VoiceCat.Crypto.csproj" />
|
||||
<Project Path="../../dotnet/src/VoiceCat.Dsp/VoiceCat.Dsp.csproj" />
|
||||
<Project Path="../../dotnet/src/VoiceCat.Protocol/VoiceCat.Protocol.csproj" />
|
||||
</Folder>
|
||||
<Project Path="VoiceCat.App/VoiceCat.App.csproj" />
|
||||
<Project Path="VoiceCat.Interop.Tests/VoiceCat.Interop.Tests.csproj" />
|
||||
<Project Path="VoiceCat.Interop/VoiceCat.Interop.csproj" />
|
||||
<Project Path="VoiceCat.Managed/VoiceCat.Managed.csproj" />
|
||||
</Solution>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
param(
|
||||
[string]$RuntimeIdentifier = "win-x64",
|
||||
[string]$Output = ""
|
||||
)
|
||||
$ErrorActionPreference = "Stop"
|
||||
$repoRoot = (Resolve-Path "$PSScriptRoot/../..").Path
|
||||
if ([string]::IsNullOrWhiteSpace($Output)) { $Output = "$repoRoot/dotnet/artifacts/client/$RuntimeIdentifier" }
|
||||
dotnet publish "$PSScriptRoot/VoiceCat.App/VoiceCat.App.csproj" -c Release -r $RuntimeIdentifier --self-contained true `
|
||||
-p:PublishSingleFile=true -p:PublishTrimmed=false -p:IncludeNativeLibrariesForSelfExtract=false `
|
||||
-p:RestorePackagesWithLockFile=true -p:RestoreLockedMode=true `
|
||||
"-p:NuGetLockFilePath=packages.publish.$RuntimeIdentifier.lock.json" -o $Output
|
||||
if ($LASTEXITCODE -ne 0) { throw "Managed Windows client publish failed." }
|
||||
if (-not (Test-Path "$Output/voicecat_media.dll")) { throw "Managed media shim was not published." }
|
||||
if (Test-Path "$Output/voicecat.dll") { throw "Legacy VoiceCat native core must not be published." }
|
||||
Write-Host "Published managed Windows client to $Output"
|
||||
Reference in New Issue
Block a user