| | | 1 | | // author: https://github.com/pabloFuente |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Runtime.CompilerServices; |
| | | 6 | | using System.Threading; |
| | | 7 | | using System.Threading.Channels; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | using LiveKit.Proto; |
| | | 10 | | using LiveKit.Rtc.Internal; |
| | | 11 | | |
| | | 12 | | namespace LiveKit.Rtc |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Represents an audio frame received event. |
| | | 16 | | /// </summary> |
| | | 17 | | public readonly struct AudioFrameEvent |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Gets the audio frame. |
| | | 21 | | /// </summary> |
| | | 22 | | public AudioFrame Frame { get; } |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// Initializes a new AudioFrameEvent. |
| | | 26 | | /// </summary> |
| | | 27 | | /// <param name="frame">The audio frame.</param> |
| | | 28 | | public AudioFrameEvent(AudioFrame frame) |
| | | 29 | | { |
| | | 30 | | Frame = frame ?? throw new ArgumentNullException(nameof(frame)); |
| | | 31 | | } |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Options for noise cancellation processing. |
| | | 36 | | /// </summary> |
| | | 37 | | public class NoiseCancellationOptions |
| | | 38 | | { |
| | | 39 | | /// <summary> |
| | | 40 | | /// Gets or sets the noise cancellation module ID. |
| | | 41 | | /// </summary> |
| | | 42 | | public string ModuleId { get; set; } = string.Empty; |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Gets or sets additional options as JSON. |
| | | 46 | | /// </summary> |
| | | 47 | | public string OptionsJson { get; set; } = string.Empty; |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// An audio stream for receiving audio frames from a remote track or participant. |
| | | 52 | | /// Implements IAsyncEnumerable for modern async iteration patterns. |
| | | 53 | | /// </summary> |
| | | 54 | | public class AudioStream : IAsyncDisposable, IDisposable, IAsyncEnumerable<AudioFrameEvent> |
| | | 55 | | { |
| | | 56 | | private readonly FfiHandle _handle; |
| | | 57 | | private readonly Track? _track; |
| | | 58 | | private readonly Participant? _participant; |
| | | 59 | | private readonly Proto.TrackSource? _trackSource; |
| | | 60 | | private readonly uint _sampleRate; |
| | | 61 | | private readonly uint _numChannels; |
| | | 62 | | private readonly uint? _frameSizeMs; |
| | | 63 | | private readonly NoiseCancellationOptions? _noiseCancellation; |
| | | 64 | | private readonly FrameProcessor<AudioFrame>? _frameProcessor; |
| | | 65 | | private readonly Channel<AudioFrameEvent> _channel; |
| | | 66 | | |
| | | 67 | | // With a frame processor, the frames go through it on a task of their own instead of on the |
| | | 68 | | // native thread that delivers them |
| | | 69 | | private readonly Channel<AudioFrame>? _processorInput; |
| | | 70 | | private readonly CancellationTokenSource _cts; |
| | | 71 | | private bool _disposed; |
| | | 72 | | |
| | | 73 | | /// <summary> |
| | | 74 | | /// Initializes a new AudioStream from a track. |
| | | 75 | | /// </summary> |
| | | 76 | | /// <param name="track">The audio track to stream from.</param> |
| | | 77 | | /// <param name="sampleRate">The sample rate in Hz (default 48000).</param> |
| | | 78 | | /// <param name="numChannels">The number of channels (default 1).</param> |
| | | 79 | | /// <param name="frameSizeMs">Optional frame size in milliseconds.</param> |
| | | 80 | | /// <param name="capacity">The capacity of the internal channel (0 for unbounded).</param> |
| | | 81 | | /// <param name="noiseCancellation">Optional noise cancellation options.</param> |
| | | 82 | | /// <param name="frameProcessor">Optional frame processor for custom audio processing.</param> |
| | 53 | 83 | | public AudioStream( |
| | 53 | 84 | | Track track, |
| | 53 | 85 | | uint sampleRate = 48000, |
| | 53 | 86 | | uint numChannels = 1, |
| | 53 | 87 | | uint? frameSizeMs = null, |
| | 53 | 88 | | int capacity = 0, |
| | 53 | 89 | | NoiseCancellationOptions? noiseCancellation = null, |
| | 53 | 90 | | FrameProcessor<AudioFrame>? frameProcessor = null |
| | 53 | 91 | | ) |
| | 53 | 92 | | { |
| | 53 | 93 | | _track = track ?? throw new ArgumentNullException(nameof(track)); |
| | 53 | 94 | | _sampleRate = sampleRate; |
| | 53 | 95 | | _numChannels = numChannels; |
| | 53 | 96 | | _frameSizeMs = frameSizeMs; |
| | 53 | 97 | | _noiseCancellation = noiseCancellation; |
| | 53 | 98 | | _frameProcessor = frameProcessor; |
| | | 99 | | |
| | 53 | 100 | | _channel = CreateChannel<AudioFrameEvent>(capacity); |
| | 53 | 101 | | if (frameProcessor != null) |
| | 6 | 102 | | _processorInput = CreateChannel<AudioFrame>(capacity); |
| | | 103 | | |
| | 53 | 104 | | _cts = new CancellationTokenSource(); |
| | | 105 | | |
| | | 106 | | OwnedAudioStream stream; |
| | 53 | 107 | | if (_participant != null && _trackSource.HasValue) |
| | 0 | 108 | | { |
| | 0 | 109 | | stream = CreateOwnedStreamFromParticipant(); |
| | 0 | 110 | | } |
| | | 111 | | else |
| | 53 | 112 | | { |
| | 53 | 113 | | stream = CreateOwnedStream(); |
| | 53 | 114 | | } |
| | | 115 | | |
| | 53 | 116 | | _handle = FfiHandle.FromId(stream.Handle.Id); |
| | 53 | 117 | | Start(); |
| | 53 | 118 | | } |
| | | 119 | | |
| | | 120 | | /// <summary> |
| | | 121 | | /// Private constructor for creating AudioStream from participant. |
| | | 122 | | /// </summary> |
| | 3 | 123 | | private AudioStream( |
| | 3 | 124 | | Participant participant, |
| | 3 | 125 | | Proto.TrackSource trackSource, |
| | 3 | 126 | | uint sampleRate, |
| | 3 | 127 | | uint numChannels, |
| | 3 | 128 | | uint? frameSizeMs, |
| | 3 | 129 | | int capacity, |
| | 3 | 130 | | NoiseCancellationOptions? noiseCancellation, |
| | 3 | 131 | | FrameProcessor<AudioFrame>? frameProcessor |
| | 3 | 132 | | ) |
| | 3 | 133 | | { |
| | 3 | 134 | | _participant = participant ?? throw new ArgumentNullException(nameof(participant)); |
| | 3 | 135 | | _trackSource = trackSource; |
| | 3 | 136 | | _sampleRate = sampleRate; |
| | 3 | 137 | | _numChannels = numChannels; |
| | 3 | 138 | | _frameSizeMs = frameSizeMs; |
| | 3 | 139 | | _noiseCancellation = noiseCancellation; |
| | 3 | 140 | | _frameProcessor = frameProcessor; |
| | | 141 | | |
| | 3 | 142 | | _channel = CreateChannel<AudioFrameEvent>(capacity); |
| | 3 | 143 | | if (frameProcessor != null) |
| | 1 | 144 | | _processorInput = CreateChannel<AudioFrame>(capacity); |
| | | 145 | | |
| | 3 | 146 | | _cts = new CancellationTokenSource(); |
| | | 147 | | |
| | | 148 | | OwnedAudioStream stream; |
| | 3 | 149 | | if (_participant != null && _trackSource.HasValue) |
| | 3 | 150 | | { |
| | 3 | 151 | | stream = CreateOwnedStreamFromParticipant(); |
| | 3 | 152 | | } |
| | | 153 | | else |
| | 0 | 154 | | { |
| | 0 | 155 | | stream = CreateOwnedStream(); |
| | 0 | 156 | | } |
| | | 157 | | |
| | 3 | 158 | | _handle = FfiHandle.FromId(stream.Handle.Id); |
| | 3 | 159 | | Start(); |
| | 3 | 160 | | } |
| | | 161 | | |
| | | 162 | | // Bounded for backpressure, keeping the latest audio like VideoStream and the Python SDK, or |
| | | 163 | | // unbounded for high throughput |
| | | 164 | | private static Channel<T> CreateChannel<T>(int capacity) => |
| | 63 | 165 | | capacity > 0 |
| | 63 | 166 | | ? Channel.CreateBounded<T>( |
| | 63 | 167 | | new BoundedChannelOptions(capacity) |
| | 63 | 168 | | { |
| | 63 | 169 | | FullMode = BoundedChannelFullMode.DropOldest, |
| | 63 | 170 | | SingleReader = false, |
| | 63 | 171 | | SingleWriter = true, |
| | 63 | 172 | | } |
| | 63 | 173 | | ) |
| | 63 | 174 | | : Channel.CreateUnbounded<T>( |
| | 63 | 175 | | new UnboundedChannelOptions { SingleReader = false, SingleWriter = true } |
| | 63 | 176 | | ); |
| | | 177 | | |
| | | 178 | | private void Start() |
| | 56 | 179 | | { |
| | 56 | 180 | | FfiClient.Instance.AddStreamHandler(_handle.HandleId, OnFfiEvent); |
| | 56 | 181 | | if (_frameProcessor != null && _processorInput != null) |
| | 7 | 182 | | { |
| | 7 | 183 | | var processor = _frameProcessor; |
| | 7 | 184 | | var input = _processorInput.Reader; |
| | 14 | 185 | | _ = Task.Run(() => RunFrameProcessorAsync(processor, input)); |
| | 7 | 186 | | } |
| | 56 | 187 | | } |
| | | 188 | | |
| | | 189 | | /// <summary> |
| | | 190 | | /// Creates an AudioStream from a participant's track source. |
| | | 191 | | /// </summary> |
| | | 192 | | /// <param name="participant">The participant.</param> |
| | | 193 | | /// <param name="trackSource">The track source type.</param> |
| | | 194 | | /// <param name="sampleRate">The sample rate in Hz (default 48000).</param> |
| | | 195 | | /// <param name="numChannels">The number of channels (default 1).</param> |
| | | 196 | | /// <param name="frameSizeMs">Optional frame size in milliseconds.</param> |
| | | 197 | | /// <param name="capacity">The capacity of the internal channel.</param> |
| | | 198 | | /// <param name="noiseCancellation">Optional noise cancellation options.</param> |
| | | 199 | | /// <param name="frameProcessor">Optional frame processor for custom audio processing.</param> |
| | | 200 | | /// <returns>A new AudioStream instance.</returns> |
| | | 201 | | public static AudioStream FromParticipant( |
| | | 202 | | Participant participant, |
| | | 203 | | Proto.TrackSource trackSource, |
| | | 204 | | uint sampleRate = 48000, |
| | | 205 | | uint numChannels = 1, |
| | | 206 | | uint? frameSizeMs = null, |
| | | 207 | | int capacity = 0, |
| | | 208 | | NoiseCancellationOptions? noiseCancellation = null, |
| | | 209 | | FrameProcessor<AudioFrame>? frameProcessor = null |
| | | 210 | | ) |
| | 3 | 211 | | { |
| | 3 | 212 | | return new AudioStream( |
| | 3 | 213 | | participant, |
| | 3 | 214 | | trackSource, |
| | 3 | 215 | | sampleRate, |
| | 3 | 216 | | numChannels, |
| | 3 | 217 | | frameSizeMs, |
| | 3 | 218 | | capacity, |
| | 3 | 219 | | noiseCancellation, |
| | 3 | 220 | | frameProcessor |
| | 3 | 221 | | ); |
| | 3 | 222 | | } |
| | | 223 | | |
| | | 224 | | /// <summary> |
| | | 225 | | /// Creates an AudioStream from an existing track. |
| | | 226 | | /// </summary> |
| | | 227 | | /// <param name="track">The track.</param> |
| | | 228 | | /// <param name="sampleRate">The sample rate in Hz (default 48000).</param> |
| | | 229 | | /// <param name="numChannels">The number of channels (default 1).</param> |
| | | 230 | | /// <param name="frameSizeMs">Optional frame size in milliseconds.</param> |
| | | 231 | | /// <param name="capacity">The capacity of the internal channel.</param> |
| | | 232 | | /// <param name="noiseCancellation">Optional noise cancellation options.</param> |
| | | 233 | | /// <param name="frameProcessor">Optional frame processor for custom audio processing.</param> |
| | | 234 | | /// <returns>A new AudioStream instance.</returns> |
| | | 235 | | public static AudioStream FromTrack( |
| | | 236 | | Track track, |
| | | 237 | | uint sampleRate = 48000, |
| | | 238 | | uint numChannels = 1, |
| | | 239 | | uint? frameSizeMs = null, |
| | | 240 | | int capacity = 0, |
| | | 241 | | NoiseCancellationOptions? noiseCancellation = null, |
| | | 242 | | FrameProcessor<AudioFrame>? frameProcessor = null |
| | | 243 | | ) |
| | 47 | 244 | | { |
| | 47 | 245 | | return new AudioStream( |
| | 47 | 246 | | track, |
| | 47 | 247 | | sampleRate, |
| | 47 | 248 | | numChannels, |
| | 47 | 249 | | frameSizeMs, |
| | 47 | 250 | | capacity, |
| | 47 | 251 | | noiseCancellation, |
| | 47 | 252 | | frameProcessor |
| | 47 | 253 | | ); |
| | 47 | 254 | | } |
| | | 255 | | |
| | | 256 | | /// <summary> |
| | | 257 | | /// Gets the internal handle. |
| | | 258 | | /// </summary> |
| | 1 | 259 | | internal FfiHandle Handle => _handle; |
| | | 260 | | |
| | | 261 | | /// <summary> |
| | | 262 | | /// Gets the sample rate. |
| | | 263 | | /// </summary> |
| | 3 | 264 | | public uint SampleRate => _sampleRate; |
| | | 265 | | |
| | | 266 | | /// <summary> |
| | | 267 | | /// Gets the number of channels. |
| | | 268 | | /// </summary> |
| | 2 | 269 | | public uint NumChannels => _numChannels; |
| | | 270 | | |
| | | 271 | | private OwnedAudioStream CreateOwnedStream() |
| | 53 | 272 | | { |
| | 53 | 273 | | if (_track == null) |
| | 0 | 274 | | throw new InvalidOperationException("Track is required for creating audio stream"); |
| | | 275 | | |
| | 53 | 276 | | var request = new FfiRequest |
| | 53 | 277 | | { |
| | 53 | 278 | | NewAudioStream = new NewAudioStreamRequest |
| | 53 | 279 | | { |
| | 53 | 280 | | TrackHandle = _track.Handle.HandleId, |
| | 53 | 281 | | SampleRate = _sampleRate, |
| | 53 | 282 | | NumChannels = _numChannels, |
| | 53 | 283 | | Type = AudioStreamType.AudioStreamNative, |
| | 53 | 284 | | // Unbounded native queue, like the Python SDK: the frames are dropped only by |
| | 53 | 285 | | // the channel of this stream, by its capacity, never while the managed side is |
| | 53 | 286 | | // paused (by a long garbage collection, for example) |
| | 53 | 287 | | QueueSizeFrames = 0, |
| | 53 | 288 | | }, |
| | 53 | 289 | | }; |
| | | 290 | | |
| | 53 | 291 | | if (_frameSizeMs.HasValue) |
| | 0 | 292 | | { |
| | 0 | 293 | | request.NewAudioStream.FrameSizeMs = _frameSizeMs.Value; |
| | 0 | 294 | | } |
| | | 295 | | |
| | 53 | 296 | | if (_noiseCancellation != null) |
| | 0 | 297 | | { |
| | 0 | 298 | | request.NewAudioStream.AudioFilterModuleId = _noiseCancellation.ModuleId; |
| | 0 | 299 | | if (!string.IsNullOrEmpty(_noiseCancellation.OptionsJson)) |
| | 0 | 300 | | { |
| | 0 | 301 | | request.NewAudioStream.AudioFilterOptions = _noiseCancellation.OptionsJson; |
| | 0 | 302 | | } |
| | 0 | 303 | | } |
| | | 304 | | |
| | 53 | 305 | | var response = FfiClient.Instance.SendRequest(request); |
| | 53 | 306 | | return response.NewAudioStream.Stream; |
| | 53 | 307 | | } |
| | | 308 | | |
| | | 309 | | private OwnedAudioStream CreateOwnedStreamFromParticipant() |
| | 3 | 310 | | { |
| | 3 | 311 | | if (_participant == null || !_trackSource.HasValue) |
| | 0 | 312 | | throw new InvalidOperationException( |
| | 0 | 313 | | "Participant and track source are required for creating audio stream" |
| | 0 | 314 | | ); |
| | | 315 | | |
| | 3 | 316 | | var request = new FfiRequest |
| | 3 | 317 | | { |
| | 3 | 318 | | AudioStreamFromParticipant = new AudioStreamFromParticipantRequest |
| | 3 | 319 | | { |
| | 3 | 320 | | ParticipantHandle = _participant.Handle.HandleId, |
| | 3 | 321 | | TrackSource = (Proto.TrackSource)_trackSource.Value, |
| | 3 | 322 | | SampleRate = _sampleRate, |
| | 3 | 323 | | NumChannels = _numChannels, |
| | 3 | 324 | | Type = AudioStreamType.AudioStreamNative, |
| | 3 | 325 | | QueueSizeFrames = 0, |
| | 3 | 326 | | }, |
| | 3 | 327 | | }; |
| | | 328 | | |
| | 3 | 329 | | if (_frameSizeMs.HasValue) |
| | 0 | 330 | | { |
| | 0 | 331 | | request.AudioStreamFromParticipant.FrameSizeMs = _frameSizeMs.Value; |
| | 0 | 332 | | } |
| | | 333 | | |
| | 3 | 334 | | if (_noiseCancellation != null) |
| | 0 | 335 | | { |
| | 0 | 336 | | request.AudioStreamFromParticipant.AudioFilterModuleId = |
| | 0 | 337 | | _noiseCancellation.ModuleId; |
| | 0 | 338 | | if (!string.IsNullOrEmpty(_noiseCancellation.OptionsJson)) |
| | 0 | 339 | | { |
| | 0 | 340 | | request.AudioStreamFromParticipant.AudioFilterOptions = |
| | 0 | 341 | | _noiseCancellation.OptionsJson; |
| | 0 | 342 | | } |
| | 0 | 343 | | } |
| | | 344 | | |
| | 3 | 345 | | var response = FfiClient.Instance.SendRequest(request); |
| | 3 | 346 | | return response.AudioStreamFromParticipant.Stream; |
| | 3 | 347 | | } |
| | | 348 | | |
| | | 349 | | private void OnFfiEvent(FfiEvent e) |
| | 985 | 350 | | { |
| | 985 | 351 | | if (e.MessageCase != FfiEvent.MessageOneofCase.AudioStreamEvent) |
| | 0 | 352 | | return; |
| | | 353 | | |
| | 985 | 354 | | var audioEvent = e.AudioStreamEvent; |
| | 985 | 355 | | if (audioEvent.StreamHandle != _handle.HandleId) |
| | 0 | 356 | | return; |
| | | 357 | | |
| | 985 | 358 | | if (audioEvent.MessageCase == AudioStreamEvent.MessageOneofCase.FrameReceived) |
| | 929 | 359 | | { |
| | 929 | 360 | | var ownedBuffer = audioEvent.FrameReceived.Frame; |
| | 929 | 361 | | if (_disposed) |
| | 0 | 362 | | { |
| | | 363 | | // The native task can still emit a few frames after the stream was closed: |
| | | 364 | | // release their buffers instead of leaking them |
| | 0 | 365 | | FfiHandle.FromId(ownedBuffer.Handle.Id).Dispose(); |
| | 0 | 366 | | return; |
| | | 367 | | } |
| | | 368 | | |
| | 929 | 369 | | var frame = AudioFrame.FromOwnedInfo(ownedBuffer); |
| | 929 | 370 | | if (_processorInput != null) |
| | 205 | 371 | | _processorInput.Writer.TryWrite(frame); |
| | | 372 | | else |
| | 724 | 373 | | _channel.Writer.TryWrite(new AudioFrameEvent(frame)); |
| | 929 | 374 | | } |
| | 56 | 375 | | else if (audioEvent.MessageCase == AudioStreamEvent.MessageOneofCase.Eos) |
| | 56 | 376 | | { |
| | | 377 | | // With a frame processor, its task completes the channel after the last frame |
| | 56 | 378 | | if (_processorInput != null) |
| | 7 | 379 | | _processorInput.Writer.TryComplete(); |
| | | 380 | | else |
| | 49 | 381 | | _channel.Writer.TryComplete(); |
| | | 382 | | // Nothing more will come for this handle |
| | 56 | 383 | | FfiClient.Instance.RemoveStreamHandler(_handle.HandleId); |
| | 56 | 384 | | } |
| | 985 | 385 | | } |
| | | 386 | | |
| | | 387 | | // One frame at a time, in order, on a thread pool thread: a slow processor only delays this |
| | | 388 | | // stream, not the native thread that also delivers the events of every other stream and room |
| | | 389 | | private async Task RunFrameProcessorAsync( |
| | | 390 | | FrameProcessor<AudioFrame> processor, |
| | | 391 | | ChannelReader<AudioFrame> input |
| | | 392 | | ) |
| | 7 | 393 | | { |
| | | 394 | | try |
| | 7 | 395 | | { |
| | 212 | 396 | | while (await input.WaitToReadAsync().ConfigureAwait(false)) |
| | 205 | 397 | | { |
| | 410 | 398 | | while (input.TryRead(out var frame)) |
| | 205 | 399 | | { |
| | 205 | 400 | | if (_disposed) |
| | 0 | 401 | | return; |
| | 205 | 402 | | _channel.Writer.TryWrite(new AudioFrameEvent(Process(processor, frame))); |
| | 205 | 403 | | } |
| | 205 | 404 | | } |
| | 7 | 405 | | } |
| | | 406 | | finally |
| | 7 | 407 | | { |
| | 7 | 408 | | _channel.Writer.TryComplete(); |
| | 7 | 409 | | } |
| | 7 | 410 | | } |
| | | 411 | | |
| | | 412 | | private static AudioFrame Process(FrameProcessor<AudioFrame> processor, AudioFrame frame) |
| | 205 | 413 | | { |
| | | 414 | | try |
| | 205 | 415 | | { |
| | 205 | 416 | | return processor.IsEnabled ? processor.Process(frame) ?? frame : frame; |
| | | 417 | | } |
| | 31 | 418 | | catch (Exception ex) |
| | 31 | 419 | | { |
| | 31 | 420 | | Console.Error.WriteLine( |
| | 31 | 421 | | $"[WARN] AudioStream: frame processor threw, passing the frame through: {ex}" |
| | 31 | 422 | | ); |
| | 31 | 423 | | return frame; |
| | | 424 | | } |
| | 205 | 425 | | } |
| | | 426 | | |
| | | 427 | | // Keep receiving (and releasing) the frames the native side may still emit after the |
| | | 428 | | // stream is closed, until its end-of-stream event; stop listening after a grace period in |
| | | 429 | | // case it never comes. |
| | | 430 | | private void StopListeningAfterEos() |
| | 55 | 431 | | { |
| | 55 | 432 | | _ = Task.Delay(TimeSpan.FromSeconds(5)) |
| | 55 | 433 | | .ContinueWith( |
| | 55 | 434 | | _ => FfiClient.Instance.RemoveStreamHandler(_handle.HandleId), |
| | 55 | 435 | | TaskScheduler.Default |
| | 55 | 436 | | ); |
| | 55 | 437 | | } |
| | | 438 | | |
| | | 439 | | /// <summary> |
| | | 440 | | /// Reads the next audio frame event from the stream. |
| | | 441 | | /// </summary> |
| | | 442 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 443 | | /// <returns>The next audio frame event, or null if the stream has ended.</returns> |
| | | 444 | | public async ValueTask<AudioFrameEvent?> ReadAsync( |
| | | 445 | | CancellationToken cancellationToken = default |
| | | 446 | | ) |
| | 222 | 447 | | { |
| | | 448 | | try |
| | 222 | 449 | | { |
| | 222 | 450 | | using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource( |
| | 222 | 451 | | cancellationToken, |
| | 222 | 452 | | _cts.Token |
| | 222 | 453 | | ); |
| | 221 | 454 | | if (await _channel.Reader.WaitToReadAsync(linkedCts.Token).ConfigureAwait(false)) |
| | 192 | 455 | | { |
| | 192 | 456 | | if (_channel.Reader.TryRead(out var frame)) |
| | 162 | 457 | | { |
| | 162 | 458 | | return frame; |
| | | 459 | | } |
| | 30 | 460 | | } |
| | 30 | 461 | | return null; |
| | | 462 | | } |
| | 29 | 463 | | catch (OperationCanceledException) |
| | 29 | 464 | | { |
| | 29 | 465 | | return null; |
| | | 466 | | } |
| | 0 | 467 | | catch (ChannelClosedException) |
| | 0 | 468 | | { |
| | 0 | 469 | | return null; |
| | | 470 | | } |
| | 221 | 471 | | } |
| | | 472 | | |
| | | 473 | | /// <summary> |
| | | 474 | | /// Tries to read the next audio frame event without blocking. |
| | | 475 | | /// </summary> |
| | | 476 | | /// <param name="frameEvent">The frame event if available.</param> |
| | | 477 | | /// <returns>True if a frame was available.</returns> |
| | | 478 | | public bool TryRead(out AudioFrameEvent frameEvent) |
| | 0 | 479 | | { |
| | 0 | 480 | | return _channel.Reader.TryRead(out frameEvent); |
| | 0 | 481 | | } |
| | | 482 | | |
| | | 483 | | /// <summary> |
| | | 484 | | /// Returns an async enumerator for iterating over audio frames. |
| | | 485 | | /// </summary> |
| | | 486 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 487 | | /// <returns>An async enumerator of audio frame events.</returns> |
| | | 488 | | public async IAsyncEnumerator<AudioFrameEvent> GetAsyncEnumerator( |
| | | 489 | | CancellationToken cancellationToken = default |
| | | 490 | | ) |
| | 13 | 491 | | { |
| | 13 | 492 | | using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource( |
| | 13 | 493 | | cancellationToken, |
| | 13 | 494 | | _cts.Token |
| | 13 | 495 | | ); |
| | | 496 | | |
| | 13 | 497 | | await foreach ( |
| | 907 | 498 | | var frame in _channel.Reader.ReadAllAsync(linkedCts.Token).ConfigureAwait(false) |
| | | 499 | | ) |
| | 447 | 500 | | { |
| | 447 | 501 | | yield return frame; |
| | 434 | 502 | | } |
| | 13 | 503 | | } |
| | | 504 | | |
| | | 505 | | /// <summary> |
| | | 506 | | /// Stops the stream, closes the frame processor and releases the native stream. Pending reads return null and l |
| | | 507 | | /// </summary> |
| | | 508 | | public void Dispose() |
| | 44 | 509 | | { |
| | 44 | 510 | | if (_disposed) |
| | 0 | 511 | | return; |
| | 44 | 512 | | _disposed = true; |
| | | 513 | | |
| | 44 | 514 | | _cts.Cancel(); |
| | 44 | 515 | | StopListeningAfterEos(); |
| | 44 | 516 | | _processorInput?.Writer.TryComplete(); |
| | 44 | 517 | | _channel.Writer.TryComplete(); |
| | 44 | 518 | | _frameProcessor?.Close(); |
| | 44 | 519 | | _handle.Dispose(); |
| | 44 | 520 | | _cts.Dispose(); |
| | | 521 | | |
| | 44 | 522 | | GC.SuppressFinalize(this); |
| | 44 | 523 | | } |
| | | 524 | | |
| | | 525 | | /// <summary> |
| | | 526 | | /// Stops the stream, closes the frame processor and releases the native stream. Pending reads return null and l |
| | | 527 | | /// </summary> |
| | | 528 | | /// <returns>A task that completes once the stream is released.</returns> |
| | | 529 | | public async ValueTask DisposeAsync() |
| | 11 | 530 | | { |
| | 11 | 531 | | if (_disposed) |
| | 0 | 532 | | return; |
| | 11 | 533 | | _disposed = true; |
| | | 534 | | |
| | 11 | 535 | | _cts.Cancel(); |
| | 11 | 536 | | StopListeningAfterEos(); |
| | 11 | 537 | | _processorInput?.Writer.TryComplete(); |
| | 11 | 538 | | _channel.Writer.TryComplete(); |
| | | 539 | | |
| | | 540 | | // Wait for any pending reads to complete |
| | 11 | 541 | | await Task.Yield(); |
| | | 542 | | |
| | 11 | 543 | | _frameProcessor?.Close(); |
| | 11 | 544 | | _handle.Dispose(); |
| | 11 | 545 | | _cts.Dispose(); |
| | | 546 | | |
| | 11 | 547 | | GC.SuppressFinalize(this); |
| | 11 | 548 | | } |
| | | 549 | | } |
| | | 550 | | } |