| | | 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 | | |
| | | 10 | | namespace LiveKit.Rtc |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Interface for audio streams that can be mixed. |
| | | 14 | | /// </summary> |
| | | 15 | | public interface IAudioStreamSource |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Reads the next audio frame from the stream. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 21 | | /// <returns>The next audio frame, or null if the stream is complete.</returns> |
| | | 22 | | ValueTask<AudioFrame?> ReadAsync(CancellationToken cancellationToken = default); |
| | | 23 | | } |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Mixes multiple audio streams into a single output stream. |
| | | 27 | | /// Implements IAsyncEnumerable for modern async iteration patterns. |
| | | 28 | | /// </summary> |
| | | 29 | | public class AudioMixer : IAsyncDisposable, IDisposable, IAsyncEnumerable<AudioFrame> |
| | | 30 | | { |
| | | 31 | | private readonly uint _sampleRate; |
| | | 32 | | private readonly uint _numChannels; |
| | | 33 | | private readonly int _chunkSize; |
| | | 34 | | private readonly int _streamTimeoutMs; |
| | | 35 | | private readonly List<IAudioStreamSource> _streams; |
| | | 36 | | private readonly Dictionary<IAudioStreamSource, short[]> _buffers; |
| | | 37 | | private readonly Channel<AudioFrame> _outputChannel; |
| | | 38 | | private readonly CancellationTokenSource _cts; |
| | | 39 | | private readonly Task _mixerTask; |
| | 8 | 40 | | private readonly object _lock = new object(); |
| | | 41 | | private bool _ending; |
| | | 42 | | private bool _disposed; |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Initializes a new AudioMixer. |
| | | 46 | | /// </summary> |
| | | 47 | | /// <param name="sampleRate">The audio sample rate in Hz.</param> |
| | | 48 | | /// <param name="numChannels">The number of audio channels.</param> |
| | | 49 | | /// <param name="blockSize">The size of the audio block (in samples) for mixing. If 0, defaults to sampleRate/10 |
| | | 50 | | /// <param name="streamTimeoutMs">The maximum wait time in milliseconds for each stream to provide audio data.</ |
| | | 51 | | /// <param name="capacity">The maximum number of mixed frames to store in the output channel.</param> |
| | 8 | 52 | | public AudioMixer( |
| | 8 | 53 | | uint sampleRate, |
| | 8 | 54 | | uint numChannels, |
| | 8 | 55 | | int blockSize = 0, |
| | 8 | 56 | | int streamTimeoutMs = 100, |
| | 8 | 57 | | int capacity = 100 |
| | 8 | 58 | | ) |
| | 8 | 59 | | { |
| | 8 | 60 | | _sampleRate = sampleRate; |
| | 8 | 61 | | _numChannels = numChannels; |
| | 8 | 62 | | _chunkSize = blockSize > 0 ? blockSize : (int)(sampleRate / 10); |
| | 8 | 63 | | _streamTimeoutMs = streamTimeoutMs; |
| | 8 | 64 | | _streams = new List<IAudioStreamSource>(); |
| | 8 | 65 | | _buffers = new Dictionary<IAudioStreamSource, short[]>(); |
| | | 66 | | |
| | 8 | 67 | | _outputChannel = |
| | 8 | 68 | | capacity > 0 |
| | 8 | 69 | | ? Channel.CreateBounded<AudioFrame>( |
| | 8 | 70 | | new BoundedChannelOptions(capacity) |
| | 8 | 71 | | { |
| | 8 | 72 | | FullMode = BoundedChannelFullMode.Wait, |
| | 8 | 73 | | SingleReader = false, |
| | 8 | 74 | | SingleWriter = true, |
| | 8 | 75 | | } |
| | 8 | 76 | | ) |
| | 8 | 77 | | : Channel.CreateUnbounded<AudioFrame>( |
| | 8 | 78 | | new UnboundedChannelOptions { SingleReader = false, SingleWriter = true } |
| | 8 | 79 | | ); |
| | | 80 | | |
| | 8 | 81 | | _cts = new CancellationTokenSource(); |
| | 8 | 82 | | _mixerTask = Task.Run(MixerLoopAsync); |
| | 8 | 83 | | } |
| | | 84 | | |
| | | 85 | | /// <summary> |
| | | 86 | | /// Gets the sample rate. |
| | | 87 | | /// </summary> |
| | 1 | 88 | | public uint SampleRate => _sampleRate; |
| | | 89 | | |
| | | 90 | | /// <summary> |
| | | 91 | | /// Gets the number of channels. |
| | | 92 | | /// </summary> |
| | 1 | 93 | | public uint NumChannels => _numChannels; |
| | | 94 | | |
| | | 95 | | /// <summary> |
| | | 96 | | /// Gets the chunk size in samples. |
| | | 97 | | /// </summary> |
| | 1 | 98 | | public int ChunkSize => _chunkSize; |
| | | 99 | | |
| | | 100 | | /// <summary> |
| | | 101 | | /// Gets the current number of active streams. |
| | | 102 | | /// </summary> |
| | | 103 | | public int StreamCount |
| | | 104 | | { |
| | | 105 | | get |
| | 4 | 106 | | { |
| | 4 | 107 | | lock (_lock) |
| | 4 | 108 | | { |
| | 4 | 109 | | return _streams.Count; |
| | | 110 | | } |
| | 4 | 111 | | } |
| | | 112 | | } |
| | | 113 | | |
| | | 114 | | /// <summary> |
| | | 115 | | /// Adds an audio stream to the mixer. |
| | | 116 | | /// </summary> |
| | | 117 | | /// <param name="stream">The audio stream to add.</param> |
| | | 118 | | public void AddStream(IAudioStreamSource stream) |
| | 9 | 119 | | { |
| | 9 | 120 | | if (_ending) |
| | 1 | 121 | | throw new InvalidOperationException( |
| | 1 | 122 | | "Cannot add stream after mixer has been closed" |
| | 1 | 123 | | ); |
| | | 124 | | |
| | 8 | 125 | | lock (_lock) |
| | 8 | 126 | | { |
| | 8 | 127 | | if (!_streams.Contains(stream)) |
| | 7 | 128 | | { |
| | 7 | 129 | | _streams.Add(stream); |
| | 7 | 130 | | _buffers[stream] = Array.Empty<short>(); |
| | 7 | 131 | | } |
| | 8 | 132 | | } |
| | 8 | 133 | | } |
| | | 134 | | |
| | | 135 | | /// <summary> |
| | | 136 | | /// Removes an audio stream from the mixer. |
| | | 137 | | /// </summary> |
| | | 138 | | /// <param name="stream">The audio stream to remove.</param> |
| | | 139 | | public void RemoveStream(IAudioStreamSource stream) |
| | 2 | 140 | | { |
| | 2 | 141 | | lock (_lock) |
| | 2 | 142 | | { |
| | 2 | 143 | | _streams.Remove(stream); |
| | 2 | 144 | | _buffers.Remove(stream); |
| | 2 | 145 | | } |
| | 2 | 146 | | } |
| | | 147 | | |
| | | 148 | | /// <summary> |
| | | 149 | | /// Reads the next mixed audio frame. |
| | | 150 | | /// </summary> |
| | | 151 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 152 | | /// <returns>The next mixed audio frame, or null if the mixer is complete.</returns> |
| | | 153 | | public async ValueTask<AudioFrame?> ReadAsync(CancellationToken cancellationToken = default) |
| | 5 | 154 | | { |
| | | 155 | | try |
| | 5 | 156 | | { |
| | 5 | 157 | | using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource( |
| | 5 | 158 | | cancellationToken, |
| | 5 | 159 | | _cts.Token |
| | 5 | 160 | | ); |
| | 3 | 161 | | if ( |
| | 3 | 162 | | await _outputChannel |
| | 3 | 163 | | .Reader.WaitToReadAsync(linkedCts.Token) |
| | 3 | 164 | | .ConfigureAwait(false) |
| | 3 | 165 | | ) |
| | 2 | 166 | | { |
| | 2 | 167 | | if (_outputChannel.Reader.TryRead(out var frame)) |
| | 2 | 168 | | { |
| | 2 | 169 | | return frame; |
| | | 170 | | } |
| | 0 | 171 | | } |
| | 0 | 172 | | return null; |
| | | 173 | | } |
| | 1 | 174 | | catch (OperationCanceledException) |
| | 1 | 175 | | { |
| | 1 | 176 | | return null; |
| | | 177 | | } |
| | 0 | 178 | | catch (ChannelClosedException) |
| | 0 | 179 | | { |
| | 0 | 180 | | return null; |
| | | 181 | | } |
| | 3 | 182 | | } |
| | | 183 | | |
| | | 184 | | /// <summary> |
| | | 185 | | /// Tries to read the next mixed audio frame without blocking. |
| | | 186 | | /// </summary> |
| | | 187 | | /// <param name="frame">The frame if available.</param> |
| | | 188 | | /// <returns>True if a frame was available.</returns> |
| | | 189 | | public bool TryRead(out AudioFrame? frame) |
| | 2 | 190 | | { |
| | 2 | 191 | | if (_outputChannel.Reader.TryRead(out var f)) |
| | 1 | 192 | | { |
| | 1 | 193 | | frame = f; |
| | 1 | 194 | | return true; |
| | | 195 | | } |
| | 1 | 196 | | frame = null; |
| | 1 | 197 | | return false; |
| | 2 | 198 | | } |
| | | 199 | | |
| | | 200 | | /// <summary> |
| | | 201 | | /// Returns an async enumerator for iterating over mixed audio frames. |
| | | 202 | | /// </summary> |
| | | 203 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 204 | | /// <returns>An async enumerator of audio frames.</returns> |
| | | 205 | | public async IAsyncEnumerator<AudioFrame> GetAsyncEnumerator( |
| | | 206 | | CancellationToken cancellationToken = default |
| | | 207 | | ) |
| | 1 | 208 | | { |
| | 1 | 209 | | using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource( |
| | 1 | 210 | | cancellationToken, |
| | 1 | 211 | | _cts.Token |
| | 1 | 212 | | ); |
| | | 213 | | |
| | 1 | 214 | | await foreach ( |
| | 6 | 215 | | var frame in _outputChannel |
| | 1 | 216 | | .Reader.ReadAllAsync(linkedCts.Token) |
| | 1 | 217 | | .ConfigureAwait(false) |
| | | 218 | | ) |
| | 2 | 219 | | { |
| | 2 | 220 | | yield return frame; |
| | 2 | 221 | | } |
| | 1 | 222 | | } |
| | | 223 | | |
| | | 224 | | /// <summary> |
| | | 225 | | /// Signals that no more streams will be added. |
| | | 226 | | /// Existing streams will still be processed until exhausted. |
| | | 227 | | /// </summary> |
| | | 228 | | public void EndInput() |
| | 1 | 229 | | { |
| | 1 | 230 | | _ending = true; |
| | 1 | 231 | | } |
| | | 232 | | |
| | | 233 | | /// <summary> |
| | | 234 | | /// Stops mixing. Pending reads return null and later reads throw <see cref="ObjectDisposedException"/>. The add |
| | | 235 | | /// </summary> |
| | | 236 | | public void Dispose() |
| | 3 | 237 | | { |
| | 3 | 238 | | if (_disposed) |
| | 1 | 239 | | return; |
| | 2 | 240 | | _disposed = true; |
| | | 241 | | |
| | 2 | 242 | | _ending = true; |
| | 2 | 243 | | _cts.Cancel(); |
| | | 244 | | |
| | | 245 | | try |
| | 2 | 246 | | { |
| | 2 | 247 | | _mixerTask.Wait(TimeSpan.FromSeconds(1)); |
| | 2 | 248 | | } |
| | 0 | 249 | | catch (AggregateException) |
| | 0 | 250 | | { |
| | | 251 | | // Expected |
| | 0 | 252 | | } |
| | | 253 | | |
| | 2 | 254 | | _outputChannel.Writer.TryComplete(); |
| | 2 | 255 | | _cts.Dispose(); |
| | | 256 | | |
| | 2 | 257 | | GC.SuppressFinalize(this); |
| | 3 | 258 | | } |
| | | 259 | | |
| | | 260 | | /// <summary> |
| | | 261 | | /// Stops mixing and waits for the mixing loop to exit. Pending reads return null and later reads throw <see cre |
| | | 262 | | /// disposed. |
| | | 263 | | /// </summary> |
| | | 264 | | /// <returns>A task that completes once the mixing loop has stopped.</returns> |
| | | 265 | | public async ValueTask DisposeAsync() |
| | 7 | 266 | | { |
| | 7 | 267 | | if (_disposed) |
| | 1 | 268 | | return; |
| | 6 | 269 | | _disposed = true; |
| | | 270 | | |
| | 6 | 271 | | _ending = true; |
| | 6 | 272 | | _cts.Cancel(); |
| | | 273 | | |
| | | 274 | | try |
| | 6 | 275 | | { |
| | 6 | 276 | | await _mixerTask.ConfigureAwait(false); |
| | 6 | 277 | | } |
| | 0 | 278 | | catch (OperationCanceledException) |
| | 0 | 279 | | { |
| | | 280 | | // Expected |
| | 0 | 281 | | } |
| | | 282 | | |
| | 6 | 283 | | _outputChannel.Writer.TryComplete(); |
| | 6 | 284 | | _cts.Dispose(); |
| | | 285 | | |
| | 6 | 286 | | GC.SuppressFinalize(this); |
| | 7 | 287 | | } |
| | | 288 | | |
| | | 289 | | private async Task MixerLoopAsync() |
| | 8 | 290 | | { |
| | | 291 | | try |
| | 8 | 292 | | { |
| | 26 | 293 | | while (!_cts.Token.IsCancellationRequested) |
| | 23 | 294 | | { |
| | | 295 | | List<IAudioStreamSource> currentStreams; |
| | 23 | 296 | | lock (_lock) |
| | 23 | 297 | | { |
| | 23 | 298 | | if (_ending && _streams.Count == 0) |
| | 1 | 299 | | break; |
| | | 300 | | |
| | 22 | 301 | | currentStreams = new List<IAudioStreamSource>(_streams); |
| | 22 | 302 | | } |
| | | 303 | | |
| | 22 | 304 | | if (currentStreams.Count == 0) |
| | 2 | 305 | | { |
| | 2 | 306 | | await Task.Delay(10, _cts.Token).ConfigureAwait(false); |
| | 1 | 307 | | continue; |
| | | 308 | | } |
| | | 309 | | |
| | | 310 | | // Gather contributions from all streams |
| | 20 | 311 | | var contributions = new List<short[]>(); |
| | 20 | 312 | | var streamsToRemove = new List<IAudioStreamSource>(); |
| | 20 | 313 | | bool anyData = false; |
| | | 314 | | |
| | | 315 | | // Read every stream concurrently: N stalled streams must cost one timeout, |
| | | 316 | | // not N, or the output falls behind real time |
| | 20 | 317 | | var contributionTasks = |
| | 20 | 318 | | new List< |
| | 20 | 319 | | Task<(short[] data, short[] buffer, bool hadData, bool exhausted)> |
| | 20 | 320 | | >(); |
| | 104 | 321 | | foreach (var stream in currentStreams) |
| | 22 | 322 | | { |
| | 22 | 323 | | contributionTasks.Add(GetContributionAsync(stream).AsTask()); |
| | 22 | 324 | | } |
| | 20 | 325 | | var results = await Task.WhenAll(contributionTasks).ConfigureAwait(false); |
| | | 326 | | |
| | 84 | 327 | | for (int i = 0; i < currentStreams.Count; i++) |
| | 22 | 328 | | { |
| | 22 | 329 | | var stream = currentStreams[i]; |
| | 22 | 330 | | var (data, buffer, hadData, exhausted) = results[i]; |
| | | 331 | | |
| | 22 | 332 | | lock (_lock) |
| | 22 | 333 | | { |
| | 22 | 334 | | if (_buffers.ContainsKey(stream)) |
| | 22 | 335 | | { |
| | 22 | 336 | | _buffers[stream] = buffer; |
| | 22 | 337 | | } |
| | 22 | 338 | | } |
| | | 339 | | |
| | 22 | 340 | | contributions.Add(data); |
| | 22 | 341 | | if (hadData) |
| | 6 | 342 | | anyData = true; |
| | | 343 | | |
| | 22 | 344 | | if (exhausted && buffer.Length == 0) |
| | 1 | 345 | | streamsToRemove.Add(stream); |
| | 22 | 346 | | } |
| | | 347 | | |
| | 62 | 348 | | foreach (var stream in streamsToRemove) |
| | 1 | 349 | | { |
| | 1 | 350 | | RemoveStream(stream); |
| | 1 | 351 | | } |
| | | 352 | | |
| | 20 | 353 | | if (!anyData) |
| | 15 | 354 | | { |
| | 15 | 355 | | await Task.Delay(1, _cts.Token).ConfigureAwait(false); |
| | 12 | 356 | | continue; |
| | | 357 | | } |
| | | 358 | | |
| | | 359 | | // Mix all contributions |
| | 5 | 360 | | var mixed = MixAudio(contributions); |
| | 5 | 361 | | var frame = new AudioFrame( |
| | 5 | 362 | | mixed, |
| | 5 | 363 | | (int)_sampleRate, |
| | 5 | 364 | | (int)_numChannels, |
| | 5 | 365 | | _chunkSize |
| | 5 | 366 | | ); |
| | | 367 | | |
| | 5 | 368 | | await _outputChannel.Writer.WriteAsync(frame, _cts.Token).ConfigureAwait(false); |
| | 5 | 369 | | } |
| | 4 | 370 | | } |
| | 4 | 371 | | catch (OperationCanceledException) |
| | 4 | 372 | | { |
| | | 373 | | // Expected |
| | 4 | 374 | | } |
| | | 375 | | finally |
| | 8 | 376 | | { |
| | 8 | 377 | | _outputChannel.Writer.TryComplete(); |
| | 8 | 378 | | } |
| | 8 | 379 | | } |
| | | 380 | | |
| | | 381 | | private async ValueTask<( |
| | | 382 | | short[] data, |
| | | 383 | | short[] buffer, |
| | | 384 | | bool hadData, |
| | | 385 | | bool exhausted |
| | | 386 | | )> GetContributionAsync(IAudioStreamSource stream) |
| | 22 | 387 | | { |
| | | 388 | | short[] buffer; |
| | 22 | 389 | | lock (_lock) |
| | 22 | 390 | | { |
| | 22 | 391 | | buffer = _buffers.TryGetValue(stream, out var b) ? b : Array.Empty<short>(); |
| | 22 | 392 | | } |
| | | 393 | | |
| | 22 | 394 | | bool hadData = buffer.Length > 0; |
| | 22 | 395 | | bool exhausted = false; |
| | 22 | 396 | | int samplesNeeded = _chunkSize * (int)_numChannels; |
| | | 397 | | |
| | 27 | 398 | | while (buffer.Length < samplesNeeded && !exhausted) |
| | 22 | 399 | | { |
| | | 400 | | try |
| | 22 | 401 | | { |
| | 22 | 402 | | using var timeoutCts = new CancellationTokenSource(_streamTimeoutMs); |
| | 22 | 403 | | using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource( |
| | 22 | 404 | | timeoutCts.Token, |
| | 22 | 405 | | _cts.Token |
| | 22 | 406 | | ); |
| | | 407 | | |
| | 22 | 408 | | var frame = await stream.ReadAsync(linkedCts.Token).ConfigureAwait(false); |
| | 19 | 409 | | if (frame == null) |
| | 14 | 410 | | { |
| | | 411 | | // Sources that map cancellation to null (AudioStream.ReadAsync does) are |
| | | 412 | | // only stalled when our timeout fired, not finished: keep them in the mix |
| | 14 | 413 | | if (timeoutCts.IsCancellationRequested || _cts.IsCancellationRequested) |
| | 13 | 414 | | break; |
| | 1 | 415 | | exhausted = true; |
| | 1 | 416 | | break; |
| | | 417 | | } |
| | | 418 | | |
| | 5 | 419 | | var newData = frame.DataArray; |
| | 5 | 420 | | var combined = new short[buffer.Length + newData.Length]; |
| | 5 | 421 | | Array.Copy(buffer, 0, combined, 0, buffer.Length); |
| | 5 | 422 | | Array.Copy(newData, 0, combined, buffer.Length, newData.Length); |
| | 5 | 423 | | buffer = combined; |
| | 5 | 424 | | hadData = true; |
| | 5 | 425 | | } |
| | 3 | 426 | | catch (OperationCanceledException) |
| | 3 | 427 | | { |
| | 3 | 428 | | break; |
| | | 429 | | } |
| | 5 | 430 | | } |
| | | 431 | | |
| | | 432 | | short[] contribution; |
| | 22 | 433 | | if (buffer.Length >= samplesNeeded) |
| | 5 | 434 | | { |
| | 5 | 435 | | contribution = new short[samplesNeeded]; |
| | 5 | 436 | | Array.Copy(buffer, 0, contribution, 0, samplesNeeded); |
| | | 437 | | |
| | 5 | 438 | | var remaining = new short[buffer.Length - samplesNeeded]; |
| | 5 | 439 | | Array.Copy(buffer, samplesNeeded, remaining, 0, remaining.Length); |
| | 5 | 440 | | buffer = remaining; |
| | 5 | 441 | | } |
| | | 442 | | else |
| | 17 | 443 | | { |
| | | 444 | | // Pad with zeros |
| | 17 | 445 | | contribution = new short[samplesNeeded]; |
| | 17 | 446 | | Array.Copy(buffer, 0, contribution, 0, buffer.Length); |
| | 17 | 447 | | buffer = Array.Empty<short>(); |
| | 17 | 448 | | } |
| | | 449 | | |
| | 22 | 450 | | return (contribution, buffer, hadData, exhausted); |
| | 22 | 451 | | } |
| | | 452 | | |
| | | 453 | | private short[] MixAudio(List<short[]> contributions) |
| | 5 | 454 | | { |
| | 5 | 455 | | if (contributions.Count == 0) |
| | 0 | 456 | | return new short[_chunkSize * _numChannels]; |
| | | 457 | | |
| | 5 | 458 | | int length = contributions[0].Length; |
| | 5 | 459 | | var mixed = new int[length]; |
| | | 460 | | |
| | 27 | 461 | | foreach (var contribution in contributions) |
| | 6 | 462 | | { |
| | 52 | 463 | | for (int i = 0; i < Math.Min(length, contribution.Length); i++) |
| | 20 | 464 | | { |
| | 20 | 465 | | mixed[i] += contribution[i]; |
| | 20 | 466 | | } |
| | 6 | 467 | | } |
| | | 468 | | |
| | 5 | 469 | | var result = new short[length]; |
| | 42 | 470 | | for (int i = 0; i < length; i++) |
| | 16 | 471 | | { |
| | | 472 | | // Clip to int16 range |
| | 16 | 473 | | result[i] = (short)Math.Max(-32768, Math.Min(32767, mixed[i])); |
| | 16 | 474 | | } |
| | | 475 | | |
| | 5 | 476 | | return result; |
| | 5 | 477 | | } |
| | | 478 | | } |
| | | 479 | | } |