< Summary

Information
Line coverage
95%
Covered lines: 264
Uncovered lines: 12
Coverable lines: 276
Total lines: 479
Line coverage: 95.6%
Branch coverage
92%
Covered branches: 61
Total branches: 66
Branch coverage: 92.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)75%44100%
get_SampleRate()100%11100%
get_NumChannels()100%11100%
get_ChunkSize()100%11100%
get_StreamCount()100%11100%
AddStream(...)100%44100%
RemoveStream(...)100%11100%
ReadAsync()50%4479.16%
TryRead(...)100%22100%
GetAsyncEnumerator()100%22100%
EndInput()100%11100%
Dispose()100%2281.25%
DisposeAsync()100%2281.25%
MixerLoopAsync()100%2424100%
GetContributionAsync()92.85%1414100%
MixAudio(...)87.5%8894.73%

File(s)

/home/runner/work/livekit-server-sdk-dotnet/livekit-server-sdk-dotnet/LivekitRtc/AudioMixer.cs

#LineLine coverage
 1// author: https://github.com/pabloFuente
 2
 3using System;
 4using System.Collections.Generic;
 5using System.Runtime.CompilerServices;
 6using System.Threading;
 7using System.Threading.Channels;
 8using System.Threading.Tasks;
 9
 10namespace 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;
 840        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>
 852        public AudioMixer(
 853            uint sampleRate,
 854            uint numChannels,
 855            int blockSize = 0,
 856            int streamTimeoutMs = 100,
 857            int capacity = 100
 858        )
 859        {
 860            _sampleRate = sampleRate;
 861            _numChannels = numChannels;
 862            _chunkSize = blockSize > 0 ? blockSize : (int)(sampleRate / 10);
 863            _streamTimeoutMs = streamTimeoutMs;
 864            _streams = new List<IAudioStreamSource>();
 865            _buffers = new Dictionary<IAudioStreamSource, short[]>();
 66
 867            _outputChannel =
 868                capacity > 0
 869                    ? Channel.CreateBounded<AudioFrame>(
 870                        new BoundedChannelOptions(capacity)
 871                        {
 872                            FullMode = BoundedChannelFullMode.Wait,
 873                            SingleReader = false,
 874                            SingleWriter = true,
 875                        }
 876                    )
 877                    : Channel.CreateUnbounded<AudioFrame>(
 878                        new UnboundedChannelOptions { SingleReader = false, SingleWriter = true }
 879                    );
 80
 881            _cts = new CancellationTokenSource();
 882            _mixerTask = Task.Run(MixerLoopAsync);
 883        }
 84
 85        /// <summary>
 86        /// Gets the sample rate.
 87        /// </summary>
 188        public uint SampleRate => _sampleRate;
 89
 90        /// <summary>
 91        /// Gets the number of channels.
 92        /// </summary>
 193        public uint NumChannels => _numChannels;
 94
 95        /// <summary>
 96        /// Gets the chunk size in samples.
 97        /// </summary>
 198        public int ChunkSize => _chunkSize;
 99
 100        /// <summary>
 101        /// Gets the current number of active streams.
 102        /// </summary>
 103        public int StreamCount
 104        {
 105            get
 4106            {
 4107                lock (_lock)
 4108                {
 4109                    return _streams.Count;
 110                }
 4111            }
 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)
 9119        {
 9120            if (_ending)
 1121                throw new InvalidOperationException(
 1122                    "Cannot add stream after mixer has been closed"
 1123                );
 124
 8125            lock (_lock)
 8126            {
 8127                if (!_streams.Contains(stream))
 7128                {
 7129                    _streams.Add(stream);
 7130                    _buffers[stream] = Array.Empty<short>();
 7131                }
 8132            }
 8133        }
 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)
 2140        {
 2141            lock (_lock)
 2142            {
 2143                _streams.Remove(stream);
 2144                _buffers.Remove(stream);
 2145            }
 2146        }
 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)
 5154        {
 155            try
 5156            {
 5157                using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 5158                    cancellationToken,
 5159                    _cts.Token
 5160                );
 3161                if (
 3162                    await _outputChannel
 3163                        .Reader.WaitToReadAsync(linkedCts.Token)
 3164                        .ConfigureAwait(false)
 3165                )
 2166                {
 2167                    if (_outputChannel.Reader.TryRead(out var frame))
 2168                    {
 2169                        return frame;
 170                    }
 0171                }
 0172                return null;
 173            }
 1174            catch (OperationCanceledException)
 1175            {
 1176                return null;
 177            }
 0178            catch (ChannelClosedException)
 0179            {
 0180                return null;
 181            }
 3182        }
 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)
 2190        {
 2191            if (_outputChannel.Reader.TryRead(out var f))
 1192            {
 1193                frame = f;
 1194                return true;
 195            }
 1196            frame = null;
 1197            return false;
 2198        }
 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        )
 1208        {
 1209            using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 1210                cancellationToken,
 1211                _cts.Token
 1212            );
 213
 1214            await foreach (
 6215                var frame in _outputChannel
 1216                    .Reader.ReadAllAsync(linkedCts.Token)
 1217                    .ConfigureAwait(false)
 218            )
 2219            {
 2220                yield return frame;
 2221            }
 1222        }
 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()
 1229        {
 1230            _ending = true;
 1231        }
 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()
 3237        {
 3238            if (_disposed)
 1239                return;
 2240            _disposed = true;
 241
 2242            _ending = true;
 2243            _cts.Cancel();
 244
 245            try
 2246            {
 2247                _mixerTask.Wait(TimeSpan.FromSeconds(1));
 2248            }
 0249            catch (AggregateException)
 0250            {
 251                // Expected
 0252            }
 253
 2254            _outputChannel.Writer.TryComplete();
 2255            _cts.Dispose();
 256
 2257            GC.SuppressFinalize(this);
 3258        }
 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()
 7266        {
 7267            if (_disposed)
 1268                return;
 6269            _disposed = true;
 270
 6271            _ending = true;
 6272            _cts.Cancel();
 273
 274            try
 6275            {
 6276                await _mixerTask.ConfigureAwait(false);
 6277            }
 0278            catch (OperationCanceledException)
 0279            {
 280                // Expected
 0281            }
 282
 6283            _outputChannel.Writer.TryComplete();
 6284            _cts.Dispose();
 285
 6286            GC.SuppressFinalize(this);
 7287        }
 288
 289        private async Task MixerLoopAsync()
 8290        {
 291            try
 8292            {
 26293                while (!_cts.Token.IsCancellationRequested)
 23294                {
 295                    List<IAudioStreamSource> currentStreams;
 23296                    lock (_lock)
 23297                    {
 23298                        if (_ending && _streams.Count == 0)
 1299                            break;
 300
 22301                        currentStreams = new List<IAudioStreamSource>(_streams);
 22302                    }
 303
 22304                    if (currentStreams.Count == 0)
 2305                    {
 2306                        await Task.Delay(10, _cts.Token).ConfigureAwait(false);
 1307                        continue;
 308                    }
 309
 310                    // Gather contributions from all streams
 20311                    var contributions = new List<short[]>();
 20312                    var streamsToRemove = new List<IAudioStreamSource>();
 20313                    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
 20317                    var contributionTasks =
 20318                        new List<
 20319                            Task<(short[] data, short[] buffer, bool hadData, bool exhausted)>
 20320                        >();
 104321                    foreach (var stream in currentStreams)
 22322                    {
 22323                        contributionTasks.Add(GetContributionAsync(stream).AsTask());
 22324                    }
 20325                    var results = await Task.WhenAll(contributionTasks).ConfigureAwait(false);
 326
 84327                    for (int i = 0; i < currentStreams.Count; i++)
 22328                    {
 22329                        var stream = currentStreams[i];
 22330                        var (data, buffer, hadData, exhausted) = results[i];
 331
 22332                        lock (_lock)
 22333                        {
 22334                            if (_buffers.ContainsKey(stream))
 22335                            {
 22336                                _buffers[stream] = buffer;
 22337                            }
 22338                        }
 339
 22340                        contributions.Add(data);
 22341                        if (hadData)
 6342                            anyData = true;
 343
 22344                        if (exhausted && buffer.Length == 0)
 1345                            streamsToRemove.Add(stream);
 22346                    }
 347
 62348                    foreach (var stream in streamsToRemove)
 1349                    {
 1350                        RemoveStream(stream);
 1351                    }
 352
 20353                    if (!anyData)
 15354                    {
 15355                        await Task.Delay(1, _cts.Token).ConfigureAwait(false);
 12356                        continue;
 357                    }
 358
 359                    // Mix all contributions
 5360                    var mixed = MixAudio(contributions);
 5361                    var frame = new AudioFrame(
 5362                        mixed,
 5363                        (int)_sampleRate,
 5364                        (int)_numChannels,
 5365                        _chunkSize
 5366                    );
 367
 5368                    await _outputChannel.Writer.WriteAsync(frame, _cts.Token).ConfigureAwait(false);
 5369                }
 4370            }
 4371            catch (OperationCanceledException)
 4372            {
 373                // Expected
 4374            }
 375            finally
 8376            {
 8377                _outputChannel.Writer.TryComplete();
 8378            }
 8379        }
 380
 381        private async ValueTask<(
 382            short[] data,
 383            short[] buffer,
 384            bool hadData,
 385            bool exhausted
 386        )> GetContributionAsync(IAudioStreamSource stream)
 22387        {
 388            short[] buffer;
 22389            lock (_lock)
 22390            {
 22391                buffer = _buffers.TryGetValue(stream, out var b) ? b : Array.Empty<short>();
 22392            }
 393
 22394            bool hadData = buffer.Length > 0;
 22395            bool exhausted = false;
 22396            int samplesNeeded = _chunkSize * (int)_numChannels;
 397
 27398            while (buffer.Length < samplesNeeded && !exhausted)
 22399            {
 400                try
 22401                {
 22402                    using var timeoutCts = new CancellationTokenSource(_streamTimeoutMs);
 22403                    using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
 22404                        timeoutCts.Token,
 22405                        _cts.Token
 22406                    );
 407
 22408                    var frame = await stream.ReadAsync(linkedCts.Token).ConfigureAwait(false);
 19409                    if (frame == null)
 14410                    {
 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
 14413                        if (timeoutCts.IsCancellationRequested || _cts.IsCancellationRequested)
 13414                            break;
 1415                        exhausted = true;
 1416                        break;
 417                    }
 418
 5419                    var newData = frame.DataArray;
 5420                    var combined = new short[buffer.Length + newData.Length];
 5421                    Array.Copy(buffer, 0, combined, 0, buffer.Length);
 5422                    Array.Copy(newData, 0, combined, buffer.Length, newData.Length);
 5423                    buffer = combined;
 5424                    hadData = true;
 5425                }
 3426                catch (OperationCanceledException)
 3427                {
 3428                    break;
 429                }
 5430            }
 431
 432            short[] contribution;
 22433            if (buffer.Length >= samplesNeeded)
 5434            {
 5435                contribution = new short[samplesNeeded];
 5436                Array.Copy(buffer, 0, contribution, 0, samplesNeeded);
 437
 5438                var remaining = new short[buffer.Length - samplesNeeded];
 5439                Array.Copy(buffer, samplesNeeded, remaining, 0, remaining.Length);
 5440                buffer = remaining;
 5441            }
 442            else
 17443            {
 444                // Pad with zeros
 17445                contribution = new short[samplesNeeded];
 17446                Array.Copy(buffer, 0, contribution, 0, buffer.Length);
 17447                buffer = Array.Empty<short>();
 17448            }
 449
 22450            return (contribution, buffer, hadData, exhausted);
 22451        }
 452
 453        private short[] MixAudio(List<short[]> contributions)
 5454        {
 5455            if (contributions.Count == 0)
 0456                return new short[_chunkSize * _numChannels];
 457
 5458            int length = contributions[0].Length;
 5459            var mixed = new int[length];
 460
 27461            foreach (var contribution in contributions)
 6462            {
 52463                for (int i = 0; i < Math.Min(length, contribution.Length); i++)
 20464                {
 20465                    mixed[i] += contribution[i];
 20466                }
 6467            }
 468
 5469            var result = new short[length];
 42470            for (int i = 0; i < length; i++)
 16471            {
 472                // Clip to int16 range
 16473                result[i] = (short)Math.Max(-32768, Math.Min(32767, mixed[i]));
 16474            }
 475
 5476            return result;
 5477        }
 478    }
 479}