| | | 1 | | // author: https://github.com/pabloFuente |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Threading; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using LiveKit.Proto; |
| | | 8 | | using LiveKit.Rtc.Internal; |
| | | 9 | | |
| | | 10 | | namespace LiveKit.Rtc |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Represents a real-time audio source with an internal audio queue. |
| | | 14 | | /// The AudioSource class allows you to push audio frames into a real-time audio |
| | | 15 | | /// source, managing an internal queue of audio data. |
| | | 16 | | /// </summary> |
| | | 17 | | public class AudioSource : IDisposable |
| | | 18 | | { |
| | | 19 | | private readonly int _sampleRate; |
| | | 20 | | private readonly int _numChannels; |
| | | 21 | | private readonly FfiHandle _handle; |
| | 1273 | 22 | | private readonly Stopwatch _stopwatch = new Stopwatch(); |
| | | 23 | | |
| | | 24 | | private readonly int _queueSizeMs; |
| | | 25 | | |
| | | 26 | | // Playout bookkeeping, shared by CaptureFrameAsync, the drain timer and Dispose |
| | 1273 | 27 | | private readonly object _playoutLock = new object(); |
| | | 28 | | private double _lastCapture; |
| | | 29 | | private double _queueSize; |
| | | 30 | | private TaskCompletionSource<bool>? _playoutTcs; |
| | | 31 | | private CancellationTokenSource? _playoutCts; |
| | | 32 | | private bool _disposed; |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Initializes a new instance of the audio source. |
| | | 36 | | /// </summary> |
| | | 37 | | /// <param name="sampleRate">The sample rate of the audio source in Hz.</param> |
| | | 38 | | /// <param name="numChannels">The number of audio channels.</param> |
| | | 39 | | /// <param name="queueSizeMs">The buffer size of the audio queue in milliseconds. Defaults to 1000 ms.</param> |
| | 1273 | 40 | | public AudioSource(int sampleRate, int numChannels, int queueSizeMs = 1000) |
| | 1273 | 41 | | { |
| | 1273 | 42 | | _sampleRate = sampleRate; |
| | 1273 | 43 | | _numChannels = numChannels; |
| | 1273 | 44 | | _queueSizeMs = queueSizeMs; |
| | 1273 | 45 | | _stopwatch.Start(); |
| | | 46 | | |
| | 1273 | 47 | | var request = new FfiRequest |
| | 1273 | 48 | | { |
| | 1273 | 49 | | NewAudioSource = new NewAudioSourceRequest |
| | 1273 | 50 | | { |
| | 1273 | 51 | | Type = AudioSourceType.AudioSourceNative, |
| | 1273 | 52 | | SampleRate = (uint)sampleRate, |
| | 1273 | 53 | | NumChannels = (uint)numChannels, |
| | 1273 | 54 | | QueueSizeMs = (uint)queueSizeMs, |
| | 1273 | 55 | | }, |
| | 1273 | 56 | | }; |
| | | 57 | | |
| | 1273 | 58 | | var response = FfiClient.Instance.SendRequest(request); |
| | 1273 | 59 | | var sourceInfo = response.NewAudioSource.Source; |
| | 1273 | 60 | | _handle = new SourceHandle(sourceInfo.Handle.Id); |
| | 1273 | 61 | | } |
| | | 62 | | |
| | | 63 | | /// <summary> |
| | | 64 | | /// Gets the sample rate of the audio source in Hz. |
| | | 65 | | /// </summary> |
| | 9641 | 66 | | public int SampleRate => _sampleRate; |
| | | 67 | | |
| | | 68 | | /// <summary> |
| | | 69 | | /// Gets the number of audio channels. |
| | | 70 | | /// </summary> |
| | 41 | 71 | | public int NumChannels => _numChannels; |
| | | 72 | | |
| | | 73 | | /// <summary> |
| | | 74 | | /// Gets the internal FFI handle. |
| | | 75 | | /// </summary> |
| | 887 | 76 | | internal FfiHandle Handle => _handle; |
| | | 77 | | |
| | | 78 | | /// <summary> |
| | | 79 | | /// Gets the current duration (in seconds) of audio data queued for playback. |
| | | 80 | | /// </summary> |
| | | 81 | | public double QueuedDuration |
| | | 82 | | { |
| | | 83 | | get |
| | 2 | 84 | | { |
| | 2 | 85 | | double elapsed = _stopwatch.Elapsed.TotalSeconds; |
| | 2 | 86 | | return Math.Max(_queueSize - elapsed + _lastCapture, 0.0); |
| | 2 | 87 | | } |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <summary> |
| | | 91 | | /// Clears the internal audio queue, discarding all buffered audio data. |
| | | 92 | | /// </summary> |
| | | 93 | | public void ClearQueue() |
| | 222 | 94 | | { |
| | 222 | 95 | | var request = new FfiRequest |
| | 222 | 96 | | { |
| | 222 | 97 | | ClearAudioBuffer = new ClearAudioBufferRequest { SourceHandle = _handle.HandleId }, |
| | 222 | 98 | | }; |
| | | 99 | | |
| | 222 | 100 | | FfiClient.Instance.SendRequest(request); |
| | 221 | 101 | | ReleaseWaiter(); |
| | 221 | 102 | | } |
| | | 103 | | |
| | | 104 | | /// <summary> |
| | | 105 | | /// Captures an AudioFrame and queues it for playback. |
| | | 106 | | /// </summary> |
| | | 107 | | /// <param name="frame">The audio frame to capture and queue.</param> |
| | | 108 | | /// <param name="cancellationToken"> |
| | | 109 | | /// Cancels the wait for the native source to accept the frame, not the capture itself: the source |
| | | 110 | | /// keeps consuming the frame, and a capture made before it is done fails with |
| | | 111 | | /// <see cref="InvalidOperationException"/>. Await each capture before the next one. A token that is |
| | | 112 | | /// already cancelled throws before the frame is captured. |
| | | 113 | | /// </param> |
| | | 114 | | /// <returns>A task that completes once the native source has accepted the frame.</returns> |
| | | 115 | | public async Task CaptureFrameAsync( |
| | | 116 | | AudioFrame frame, |
| | | 117 | | CancellationToken cancellationToken = default |
| | | 118 | | ) |
| | 10482 | 119 | | { |
| | | 120 | | // Before the frame reaches the native source, which would keep consuming it |
| | 10482 | 121 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 10481 | 122 | | if (frame.SamplesPerChannel == 0 || _disposed) |
| | 1 | 123 | | return; |
| | | 124 | | |
| | 10480 | 125 | | var frameDuration = (double)frame.SamplesPerChannel / _sampleRate; |
| | | 126 | | CancellationTokenSource playoutCts; |
| | | 127 | | double drainDelaySeconds; |
| | 10480 | 128 | | lock (_playoutLock) |
| | 10480 | 129 | | { |
| | 10480 | 130 | | double now = _stopwatch.Elapsed.TotalSeconds; |
| | 10480 | 131 | | double elapsed = _lastCapture == 0.0 ? 0.0 : now - _lastCapture; |
| | 10480 | 132 | | _queueSize += frameDuration - elapsed; |
| | 10480 | 133 | | _lastCapture = now; |
| | | 134 | | |
| | | 135 | | // Restart the drain timer; anyone already waiting for the playout keeps waiting on |
| | | 136 | | // the same task (a new one per capture would strand earlier waiters) |
| | 10480 | 137 | | _playoutCts?.Cancel(); |
| | 10480 | 138 | | _playoutCts?.Dispose(); |
| | 10480 | 139 | | _playoutTcs ??= new TaskCompletionSource<bool>( |
| | 10480 | 140 | | TaskCreationOptions.RunContinuationsAsynchronously |
| | 10480 | 141 | | ); |
| | 10480 | 142 | | playoutCts = _playoutCts = new CancellationTokenSource(); |
| | 10480 | 143 | | drainDelaySeconds = Math.Max(0.0, Math.Min(_queueSize, int.MaxValue / 1000.0 - 1)); |
| | 10480 | 144 | | } |
| | | 145 | | |
| | 10480 | 146 | | _ = Task.Delay(TimeSpan.FromSeconds(drainDelaySeconds), playoutCts.Token) |
| | 11139 | 147 | | .ContinueWith(_ => ReleaseWaiter(), TaskContinuationOptions.OnlyOnRanToCompletion); |
| | | 148 | | |
| | | 149 | | // The FFI copies the samples before SendRequest returns. Keep them pinned |
| | | 150 | | // through request serialization and the native call, but not the callback wait. |
| | 10480 | 151 | | var response = frame.WithPinnedBuffer(buffer => |
| | 10480 | 152 | | FfiClient.Instance.SendRequest( |
| | 10480 | 153 | | new FfiRequest |
| | 10480 | 154 | | { |
| | 10480 | 155 | | CaptureAudioFrame = new CaptureAudioFrameRequest |
| | 10480 | 156 | | { |
| | 10480 | 157 | | SourceHandle = _handle.HandleId, |
| | 10480 | 158 | | Buffer = buffer, |
| | 10480 | 159 | | }, |
| | 10480 | 160 | | } |
| | 10480 | 161 | | ) |
| | 10480 | 162 | | ); |
| | 10480 | 163 | | var asyncId = response.CaptureAudioFrame.AsyncId; |
| | | 164 | | |
| | | 165 | | // The callback only arrives once the whole frame has been accepted into the native |
| | | 166 | | // queue, which for a long frame takes about its duration minus the queue size: wait |
| | | 167 | | // for that plus a margin instead of a fixed 10 s (which rejected 15 s clips). |
| | 10480 | 168 | | var timeout = |
| | 10480 | 169 | | TimeSpan.FromSeconds(10) |
| | 10480 | 170 | | + TimeSpan.FromSeconds(frameDuration) |
| | 10480 | 171 | | + TimeSpan.FromMilliseconds(_queueSizeMs); |
| | | 172 | | // Not resumed on the caller's context: CaptureFrame blocks on this method, which |
| | | 173 | | // would deadlock a UI thread |
| | 10480 | 174 | | var callbackEvent = await FfiClient |
| | 10480 | 175 | | .Instance.WaitForEventAsync( |
| | 10481261 | 176 | | e => e.CaptureAudioFrame?.AsyncId == asyncId, |
| | 10480 | 177 | | timeout, |
| | 10480 | 178 | | cancellationToken |
| | 10480 | 179 | | ) |
| | 10480 | 180 | | .ConfigureAwait(false); |
| | | 181 | | |
| | 10459 | 182 | | if (!string.IsNullOrEmpty(callbackEvent.CaptureAudioFrame?.Error)) |
| | 36 | 183 | | { |
| | 36 | 184 | | throw new InvalidOperationException( |
| | 36 | 185 | | $"Audio capture failed: {callbackEvent.CaptureAudioFrame.Error}" |
| | 36 | 186 | | ); |
| | | 187 | | } |
| | 10424 | 188 | | } |
| | | 189 | | |
| | | 190 | | /// <summary> |
| | | 191 | | /// Captures an AudioFrame and blocks the calling thread until the native source accepts it, which |
| | | 192 | | /// can take a while when the queue is full. Prefer <see cref="CaptureFrameAsync"/> in asynchronous |
| | | 193 | | /// code. |
| | | 194 | | /// </summary> |
| | | 195 | | /// <param name="frame">The audio frame to capture and queue.</param> |
| | | 196 | | public void CaptureFrame(AudioFrame frame) |
| | 205 | 197 | | { |
| | 205 | 198 | | CaptureFrameAsync(frame).GetAwaiter().GetResult(); |
| | 205 | 199 | | } |
| | | 200 | | |
| | | 201 | | /// <summary> |
| | | 202 | | /// Waits for the audio source to finish playing out all audio data. |
| | | 203 | | /// </summary> |
| | | 204 | | /// <param name="cancellationToken">Cancels this wait only; the queued audio keeps playing.</param> |
| | | 205 | | /// <returns>A task that completes when all queued audio has been played out.</returns> |
| | | 206 | | public async Task WaitForPlayoutAsync(CancellationToken cancellationToken = default) |
| | 5 | 207 | | { |
| | | 208 | | Task playout; |
| | 5 | 209 | | lock (_playoutLock) |
| | 5 | 210 | | { |
| | 5 | 211 | | if (_playoutTcs == null) |
| | 0 | 212 | | return; |
| | 5 | 213 | | playout = _playoutTcs.Task; |
| | 5 | 214 | | } |
| | | 215 | | |
| | 5 | 216 | | if (!cancellationToken.CanBeCanceled) |
| | 4 | 217 | | { |
| | 4 | 218 | | await playout.ConfigureAwait(false); |
| | 4 | 219 | | return; |
| | | 220 | | } |
| | | 221 | | |
| | | 222 | | // Cancel this wait only, not the shared playout task of the other waiters |
| | 1 | 223 | | var cancelled = new TaskCompletionSource<bool>( |
| | 1 | 224 | | TaskCreationOptions.RunContinuationsAsynchronously |
| | 1 | 225 | | ); |
| | 2 | 226 | | using (cancellationToken.Register(() => cancelled.TrySetCanceled(cancellationToken))) |
| | 1 | 227 | | { |
| | 1 | 228 | | var completed = await Task.WhenAny(playout, cancelled.Task).ConfigureAwait(false); |
| | 1 | 229 | | await completed.ConfigureAwait(false); |
| | 0 | 230 | | } |
| | 4 | 231 | | } |
| | | 232 | | |
| | | 233 | | private void ReleaseWaiter() |
| | 1835 | 234 | | { |
| | | 235 | | TaskCompletionSource<bool>? waiter; |
| | 1835 | 236 | | lock (_playoutLock) |
| | 1835 | 237 | | { |
| | 1835 | 238 | | waiter = _playoutTcs; |
| | 1835 | 239 | | _playoutTcs = null; |
| | 1835 | 240 | | _lastCapture = 0.0; |
| | 1835 | 241 | | _queueSize = 0.0; |
| | 1835 | 242 | | } |
| | 1835 | 243 | | waiter?.TrySetResult(true); |
| | 1835 | 244 | | } |
| | | 245 | | |
| | | 246 | | /// <summary> |
| | | 247 | | /// Creates a local audio track from this audio source. |
| | | 248 | | /// </summary> |
| | | 249 | | /// <param name="name">The name of the track.</param> |
| | | 250 | | /// <returns>A new LocalAudioTrack.</returns> |
| | | 251 | | public LocalAudioTrack CreateTrack(string name = "audio") |
| | 1 | 252 | | { |
| | 1 | 253 | | var request = new FfiRequest |
| | 1 | 254 | | { |
| | 1 | 255 | | CreateAudioTrack = new CreateAudioTrackRequest |
| | 1 | 256 | | { |
| | 1 | 257 | | Name = name, |
| | 1 | 258 | | SourceHandle = _handle.HandleId, |
| | 1 | 259 | | }, |
| | 1 | 260 | | }; |
| | | 261 | | |
| | 1 | 262 | | var response = FfiClient.Instance.SendRequest(request); |
| | 0 | 263 | | var trackInfo = response.CreateAudioTrack.Track; |
| | | 264 | | |
| | 0 | 265 | | return new LocalAudioTrack(FfiHandle.FromId(trackInfo.Handle.Id), trackInfo); |
| | 0 | 266 | | } |
| | | 267 | | |
| | | 268 | | /// <summary> |
| | | 269 | | /// Releases the native source. Queued audio is dropped and pending |
| | | 270 | | /// <see cref="WaitForPlayoutAsync"/> calls complete. |
| | | 271 | | /// </summary> |
| | | 272 | | public void Dispose() |
| | 1130 | 273 | | { |
| | 1130 | 274 | | if (_disposed) |
| | 175 | 275 | | return; |
| | 955 | 276 | | _disposed = true; |
| | | 277 | | |
| | | 278 | | // Nothing will play out anymore: do not leave WaitForPlayoutAsync callers hanging |
| | 955 | 279 | | lock (_playoutLock) |
| | 955 | 280 | | { |
| | 955 | 281 | | _playoutCts?.Cancel(); |
| | 955 | 282 | | _playoutCts?.Dispose(); |
| | 955 | 283 | | _playoutCts = null; |
| | 955 | 284 | | } |
| | 955 | 285 | | ReleaseWaiter(); |
| | 955 | 286 | | _handle.Dispose(); |
| | 1130 | 287 | | } |
| | | 288 | | |
| | | 289 | | // The native source (webrtc-sys AudioTrackSource) frees its queue before it stops the |
| | | 290 | | // 10 ms task that plays the queue out, and without the lock that task holds. A release |
| | | 291 | | // that lands while the task erases played samples leaves the task spinning forever, which |
| | | 292 | | // hangs the thread that released the source (it waits for the task's thread), or lets it |
| | | 293 | | // read the freed queue and crash the process. An empty queue leaves the task nothing to |
| | | 294 | | // erase, so every release, by Dispose or by the finalizer, first empties it under that |
| | | 295 | | // lock. Audio captured while the release runs can still refill it. |
| | | 296 | | private sealed class SourceHandle : FfiHandle |
| | | 297 | | { |
| | | 298 | | internal SourceHandle(ulong handleId) |
| | 3819 | 299 | | : base(handleId) { } |
| | | 300 | | |
| | | 301 | | protected override bool ReleaseHandle() |
| | 1273 | 302 | | { |
| | 1273 | 303 | | if (!IsInvalid && !FfiClient.Instance.IsDisposed) |
| | 1273 | 304 | | { |
| | | 305 | | try |
| | 1273 | 306 | | { |
| | 1273 | 307 | | FfiClient.Instance.SendRequest( |
| | 1273 | 308 | | new FfiRequest |
| | 1273 | 309 | | { |
| | 1273 | 310 | | ClearAudioBuffer = new ClearAudioBufferRequest |
| | 1273 | 311 | | { |
| | 1273 | 312 | | SourceHandle = HandleId, |
| | 1273 | 313 | | }, |
| | 1273 | 314 | | } |
| | 1273 | 315 | | ); |
| | 1273 | 316 | | } |
| | 0 | 317 | | catch (Exception) |
| | 0 | 318 | | { |
| | | 319 | | // The release itself must still happen |
| | 0 | 320 | | } |
| | 1273 | 321 | | } |
| | 1273 | 322 | | return base.ReleaseHandle(); |
| | 1273 | 323 | | } |
| | | 324 | | } |
| | | 325 | | } |
| | | 326 | | } |