|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Runtime.InteropServices.JavaScript; |
| 4 | +using System.Text.Json; |
| 5 | +using System.Text.Json.Serialization; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using VoiceCraft.Client.Services; |
| 9 | + |
| 10 | +namespace VoiceCraft.Client.Browser.Audio; |
| 11 | + |
| 12 | +public sealed class BrowserAudioService : IVoiceCraftAudioService |
| 13 | +{ |
| 14 | + private readonly IEnumerable<RegisteredAudioPreprocessor> _preprocessors; |
| 15 | + private readonly IEnumerable<RegisteredAudioClipper> _clippers; |
| 16 | + |
| 17 | + public BrowserAudioService( |
| 18 | + IEnumerable<RegisteredAudioPreprocessor> preprocessors, |
| 19 | + IEnumerable<RegisteredAudioClipper> clippers) |
| 20 | + { |
| 21 | + _preprocessors = preprocessors; |
| 22 | + _clippers = clippers; |
| 23 | + } |
| 24 | + |
| 25 | + public IEnumerable<RegisteredAudioPreprocessor> RegisteredAudioPreprocessors => _preprocessors; |
| 26 | + public IEnumerable<RegisteredAudioClipper> RegisteredAudioClippers => _clippers; |
| 27 | + |
| 28 | + public RegisteredAudioPreprocessor? GetAudioPreprocessor(Guid id) |
| 29 | + { |
| 30 | + return id == Guid.Empty ? null : null; |
| 31 | + } |
| 32 | + |
| 33 | + public RegisteredAudioClipper? GetAudioClipper(Guid id) |
| 34 | + { |
| 35 | + return id == Guid.Empty ? null : null; |
| 36 | + } |
| 37 | + |
| 38 | + public IEnumerable<AudioDeviceInfo> GetInputDevices() |
| 39 | + { |
| 40 | + return ReadDevices(JsAudio.GetInputDevices(), "Default"); |
| 41 | + } |
| 42 | + |
| 43 | + public IEnumerable<AudioDeviceInfo> GetOutputDevices() |
| 44 | + { |
| 45 | + return ReadDevices(JsAudio.GetOutputDevices(), "Default"); |
| 46 | + } |
| 47 | + |
| 48 | + public IAudioCaptureSession InitializeCaptureSession( |
| 49 | + int sampleRate, |
| 50 | + int channels, |
| 51 | + uint frameSize, |
| 52 | + string inputDevice, |
| 53 | + bool hardwarePreprocessorsEnabled) |
| 54 | + { |
| 55 | + return new BrowserCaptureSession(sampleRate, channels, frameSize, inputDevice); |
| 56 | + } |
| 57 | + |
| 58 | + public IAudioPlaybackSession InitializePlaybackSession( |
| 59 | + int sampleRate, |
| 60 | + int channels, |
| 61 | + uint frameSize, |
| 62 | + string outputDevice, |
| 63 | + Func<Span<float>, int> read) |
| 64 | + { |
| 65 | + return new BrowserPlaybackSession(sampleRate, channels, frameSize, outputDevice, read); |
| 66 | + } |
| 67 | + |
| 68 | + public IAudioPlaybackSession InitializeTonePlaybackSession( |
| 69 | + int sampleRate, |
| 70 | + int channels, |
| 71 | + uint frameSize, |
| 72 | + string outputDevice, |
| 73 | + Func<Span<float>, int> read) |
| 74 | + { |
| 75 | + return new BrowserPlaybackSession(sampleRate, channels, frameSize, outputDevice, read); |
| 76 | + } |
| 77 | + |
| 78 | + private static IEnumerable<AudioDeviceInfo> ReadDevices(string json, string defaultDisplayName) |
| 79 | + { |
| 80 | + var devices = new List<AudioDeviceInfo> |
| 81 | + { |
| 82 | + new("Default", defaultDisplayName, true) |
| 83 | + }; |
| 84 | + |
| 85 | + try |
| 86 | + { |
| 87 | + foreach (var device in JsonSerializer.Deserialize(json, BrowserAudioJsonContext.Default.BrowserDeviceArray) ?? []) |
| 88 | + devices.Add(new AudioDeviceInfo(device.DeviceId, string.IsNullOrWhiteSpace(device.Label) ? device.DeviceId : device.Label, false)); |
| 89 | + } |
| 90 | + catch (Exception ex) |
| 91 | + { |
| 92 | + LogService.Log(ex); |
| 93 | + } |
| 94 | + |
| 95 | + return devices; |
| 96 | + } |
| 97 | + |
| 98 | + private sealed class BrowserCaptureSession(int sampleRate, int channels, uint frameSize, string inputDevice) |
| 99 | + : IAudioCaptureSession |
| 100 | + { |
| 101 | + private CancellationTokenSource? _cts; |
| 102 | + private readonly float[] _buffer = new float[frameSize * channels]; |
| 103 | + |
| 104 | + public bool IsRunning { get; private set; } |
| 105 | + public event AudioCaptureFrameHandler? OnAudioProcessed; |
| 106 | + |
| 107 | + public void Start() |
| 108 | + { |
| 109 | + if (IsRunning) return; |
| 110 | + JsAudio.StartCapture(sampleRate, channels, (int)frameSize, inputDevice == "Default" ? string.Empty : inputDevice); |
| 111 | + IsRunning = true; |
| 112 | + _cts = new CancellationTokenSource(); |
| 113 | + _ = PumpAsync(_cts.Token); |
| 114 | + } |
| 115 | + |
| 116 | + public void Stop() |
| 117 | + { |
| 118 | + if (!IsRunning) return; |
| 119 | + IsRunning = false; |
| 120 | + _cts?.Cancel(); |
| 121 | + _cts?.Dispose(); |
| 122 | + _cts = null; |
| 123 | + JsAudio.StopCapture(); |
| 124 | + } |
| 125 | + |
| 126 | + public void Dispose() |
| 127 | + { |
| 128 | + Stop(); |
| 129 | + } |
| 130 | + |
| 131 | + private async Task PumpAsync(CancellationToken cancellationToken) |
| 132 | + { |
| 133 | + while (!cancellationToken.IsCancellationRequested) |
| 134 | + { |
| 135 | + try |
| 136 | + { |
| 137 | + var samplesJson = JsAudio.PollCapture(); |
| 138 | + while (!string.IsNullOrEmpty(samplesJson)) |
| 139 | + { |
| 140 | + var samples = JsonSerializer.Deserialize(samplesJson, BrowserAudioJsonContext.Default.SingleArray) ?? []; |
| 141 | + samples.AsSpan(0, Math.Min(samples.Length, _buffer.Length)).CopyTo(_buffer); |
| 142 | + OnAudioProcessed?.Invoke(_buffer); |
| 143 | + samplesJson = JsAudio.PollCapture(); |
| 144 | + } |
| 145 | + } |
| 146 | + catch (Exception ex) |
| 147 | + { |
| 148 | + LogService.Log(ex); |
| 149 | + IsRunning = false; |
| 150 | + return; |
| 151 | + } |
| 152 | + |
| 153 | + await Task.Delay(5, cancellationToken); |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + private sealed class BrowserPlaybackSession( |
| 159 | + int sampleRate, |
| 160 | + int channels, |
| 161 | + uint frameSize, |
| 162 | + string outputDevice, |
| 163 | + Func<Span<float>, int> read) |
| 164 | + : IAudioPlaybackSession |
| 165 | + { |
| 166 | + private readonly float[] _buffer = new float[frameSize * channels]; |
| 167 | + |
| 168 | + public bool IsRunning { get; private set; } |
| 169 | + |
| 170 | + public void Start() |
| 171 | + { |
| 172 | + if (IsRunning) return; |
| 173 | + JsAudio.StartPlayback(sampleRate, channels, (int)frameSize, outputDevice == "Default" ? string.Empty : outputDevice); |
| 174 | + IsRunning = true; |
| 175 | + } |
| 176 | + |
| 177 | + public void Stop() |
| 178 | + { |
| 179 | + if (!IsRunning) return; |
| 180 | + IsRunning = false; |
| 181 | + JsAudio.StopPlayback(); |
| 182 | + } |
| 183 | + |
| 184 | + public void Pump() |
| 185 | + { |
| 186 | + if (!IsRunning) return; |
| 187 | + var readCount = read(_buffer); |
| 188 | + if (readCount > 0) |
| 189 | + JsAudio.EnqueuePlayback(JsonSerializer.Serialize(_buffer[..readCount], BrowserAudioJsonContext.Default.SingleArray)); |
| 190 | + } |
| 191 | + |
| 192 | + public void PlayTone(TimeSpan duration, float frequency) |
| 193 | + { |
| 194 | + JsAudio.PlayTone(duration.TotalMilliseconds, frequency); |
| 195 | + } |
| 196 | + |
| 197 | + public void Dispose() |
| 198 | + { |
| 199 | + Stop(); |
| 200 | + } |
| 201 | + } |
| 202 | +} |
| 203 | + |
| 204 | +internal sealed class BrowserDevice |
| 205 | +{ |
| 206 | + public string DeviceId { get; set; } = string.Empty; |
| 207 | + public string Label { get; set; } = string.Empty; |
| 208 | +} |
| 209 | + |
| 210 | +[JsonSerializable(typeof(BrowserDevice[]))] |
| 211 | +[JsonSerializable(typeof(float[]))] |
| 212 | +internal partial class BrowserAudioJsonContext : JsonSerializerContext; |
| 213 | + |
| 214 | +internal static partial class JsAudio |
| 215 | +{ |
| 216 | + [JSImport("getInputDevices", "audio.js")] |
| 217 | + internal static partial string GetInputDevices(); |
| 218 | + |
| 219 | + [JSImport("getOutputDevices", "audio.js")] |
| 220 | + internal static partial string GetOutputDevices(); |
| 221 | + |
| 222 | + [JSImport("startCapture", "audio.js")] |
| 223 | + internal static partial void StartCapture(int sampleRate, int channels, int frameSize, string deviceId); |
| 224 | + |
| 225 | + [JSImport("pollCapture", "audio.js")] |
| 226 | + internal static partial string PollCapture(); |
| 227 | + |
| 228 | + [JSImport("stopCapture", "audio.js")] |
| 229 | + internal static partial void StopCapture(); |
| 230 | + |
| 231 | + [JSImport("startPlayback", "audio.js")] |
| 232 | + internal static partial void StartPlayback(int sampleRate, int channels, int frameSize, string deviceId); |
| 233 | + |
| 234 | + [JSImport("enqueuePlayback", "audio.js")] |
| 235 | + internal static partial void EnqueuePlayback(string samplesJson); |
| 236 | + |
| 237 | + [JSImport("stopPlayback", "audio.js")] |
| 238 | + internal static partial void StopPlayback(); |
| 239 | + |
| 240 | + [JSImport("playTone", "audio.js")] |
| 241 | + internal static partial void PlayTone(double durationMs, float frequency); |
| 242 | +} |
0 commit comments