|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System.Threading.Tasks.Dataflow; |
| 4 | +using Microsoft.Extensions.Logging; |
| 5 | +using Microsoft.Extensions.Options; |
| 6 | + |
| 7 | +public class VoiceChatPipeline : IDisposable |
| 8 | +{ |
| 9 | + // Pipeline configuration constants |
| 10 | + private const int MaxDegreeOfParallelism = 1; // Number of parallel operations in dataflow blocks |
| 11 | + private const int BoundedCapacity = 5; // Maximum capacity for dataflow block buffers |
| 12 | + private const bool EnsureOrdered = true; // Ensure order preservation in pipeline |
| 13 | + |
| 14 | + // Dataflow options fields - initialized inline |
| 15 | + private readonly ExecutionDataflowBlockOptions _executionOptions = new() |
| 16 | + { |
| 17 | + MaxDegreeOfParallelism = MaxDegreeOfParallelism, |
| 18 | + BoundedCapacity = BoundedCapacity, |
| 19 | + EnsureOrdered = EnsureOrdered |
| 20 | + }; |
| 21 | + |
| 22 | + private readonly DataflowLinkOptions _linkOptions = new() { PropagateCompletion = true }; |
| 23 | + private readonly ILogger<VoiceChatPipeline> _logger; |
| 24 | + private readonly AudioPlaybackService _audioPlaybackService; |
| 25 | + private readonly SpeechToTextService _speechToTextService; |
| 26 | + private readonly TextToSpeechService _textToSpeechService; |
| 27 | + private readonly ChatService _chatService; |
| 28 | + private readonly TurnManager _turnManager; |
| 29 | + private readonly VadService _vadService; |
| 30 | + private readonly AudioSourceService _audioSourceService; |
| 31 | + |
| 32 | + private CancellationTokenSource? _cancellationTokenSource; |
| 33 | + |
| 34 | + public VoiceChatPipeline( |
| 35 | + ILogger<VoiceChatPipeline> logger, |
| 36 | + AudioPlaybackService audioPlaybackService, |
| 37 | + SpeechToTextService speechToTextService, |
| 38 | + TextToSpeechService textToSpeechService, |
| 39 | + ChatService chatService, |
| 40 | + VadService vadService, |
| 41 | + AudioSourceService audioSourceService, |
| 42 | + TurnManager turnManager, |
| 43 | + IOptions<AudioOptions> audioOptions) |
| 44 | + { |
| 45 | + this._logger = logger; |
| 46 | + this._audioPlaybackService = audioPlaybackService; |
| 47 | + this._speechToTextService = speechToTextService; |
| 48 | + this._textToSpeechService = textToSpeechService; |
| 49 | + this._chatService = chatService; |
| 50 | + this._vadService = vadService; |
| 51 | + this._audioSourceService = audioSourceService; |
| 52 | + this._turnManager = turnManager; |
| 53 | + } |
| 54 | + |
| 55 | + public async Task RunAsync(CancellationToken cancellationToken = default) |
| 56 | + { |
| 57 | + this._cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); |
| 58 | + |
| 59 | + // Create pipeline blocks - VAD now accepts raw audio chunks directly |
| 60 | + var vadBlock = new TransformManyBlock<byte[], AudioEvent>(this._vadService.Transform, this._executionOptions); |
| 61 | + var sttBlock = new TransformBlock<AudioEvent, TranscriptionEvent>(this._speechToTextService.TransformAsync, this._executionOptions); |
| 62 | + var chatBlock = new TransformManyBlock<TranscriptionEvent, ChatEvent>(this._chatService.TransformAsync, this._executionOptions); |
| 63 | + var ttsBlock = new TransformBlock<ChatEvent, SpeechEvent>(this._textToSpeechService.TransformAsync, this._executionOptions); |
| 64 | + var playbackBlock = new ActionBlock<SpeechEvent>(this._audioPlaybackService.PipelineActionAsync, this._executionOptions); |
| 65 | + |
| 66 | + // Connect the blocks in the pipeline |
| 67 | + this.Link(vadBlock, sttBlock, "VAD", audioData => audioData.Data.Length > 0); |
| 68 | + this.Link(sttBlock, chatBlock, "STT", t => !string.IsNullOrEmpty(t)); |
| 69 | + this.Link(chatBlock, ttsBlock, "Chat", t => !string.IsNullOrEmpty(t)); |
| 70 | + this.Link(ttsBlock, playbackBlock, "TTS", t => t.Length > 0); |
| 71 | + |
| 72 | + this._logger.LogInformation("Voice Chat started. You can start conversation now, or press Ctrl+C to exit."); |
| 73 | + |
| 74 | + try |
| 75 | + { |
| 76 | + // Keep feeding audio chunks into the VAD pipeline block till RunAsync is not cancelled |
| 77 | + await foreach (var audioChunk in this._audioSourceService.GetAudioChunksAsync(this._cancellationTokenSource.Token)) |
| 78 | + { |
| 79 | + await vadBlock.SendAsync(audioChunk, this._cancellationTokenSource.Token); |
| 80 | + } |
| 81 | + } |
| 82 | + catch (OperationCanceledException) |
| 83 | + { |
| 84 | + this._logger.LogInformation("Voice Chat pipeline stopping due to cancellation..."); |
| 85 | + } |
| 86 | + finally |
| 87 | + { |
| 88 | + vadBlock.Complete(); |
| 89 | + await playbackBlock.Completion; |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + public void Dispose() |
| 94 | + { |
| 95 | + this._vadService?.Dispose(); |
| 96 | + this._cancellationTokenSource?.Dispose(); |
| 97 | + } |
| 98 | + |
| 99 | + // Generic filter methods for pipeline events |
| 100 | + private bool Filter<T>(PipelineEvent<T> evt, string blockName, Func<T, bool> predicate, IDataflowBlock block) |
| 101 | + { |
| 102 | + var valid = PipelineEvent<T>.IsValid(evt, this._turnManager.CurrentTurnId, predicate); |
| 103 | + if (!valid) |
| 104 | + { |
| 105 | + this._logger.LogWarning($"{blockName} block: Event filtered out due to cancellation or empty payload."); |
| 106 | + } |
| 107 | + return valid; |
| 108 | + } |
| 109 | + |
| 110 | + private bool FilterDiscarded<T>(PipelineEvent<T> evt, string blockName) |
| 111 | + { |
| 112 | + this._logger.LogWarning($"{blockName} block: Event filtered out due to cancellation or empty."); |
| 113 | + return true; |
| 114 | + } |
| 115 | + |
| 116 | + private void Link<T>( |
| 117 | + ISourceBlock<PipelineEvent<T>> source, |
| 118 | + ITargetBlock<PipelineEvent<T>> target, |
| 119 | + string blockName, |
| 120 | + Func<T, bool> predicate) |
| 121 | + { |
| 122 | + source.LinkTo(target, this._linkOptions, evt => this.Filter(evt, blockName, predicate, source)); |
| 123 | + this.DiscardFiltered(source, blockName); |
| 124 | + } |
| 125 | + |
| 126 | + private void DiscardFiltered<T>(ISourceBlock<PipelineEvent<T>> block, string blockName) => block.LinkTo(DataflowBlock.NullTarget<PipelineEvent<T>>(), this._linkOptions, evt => this.FilterDiscarded(evt, blockName)); |
| 127 | +} |
0 commit comments