From 9f53d78735ab7eb7f5578e5b97385b0813ab1902 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=9C=E5=AE=87?= Date: Mon, 30 Nov 2026 17:47:30 +0800 Subject: [PATCH 1/2] Reduce RDP audio dropouts and bound playback backlog --- plugins/VelaShell.Plugin.Rdp/RdpSettings.cs | 6 +- src/VelaShell.Rdp/Audio/AudioOutput.cs | 126 +++++++++++++----- src/VelaShell.Rdp/Audio/AudioPlayoutTiming.cs | 21 ++- src/VelaShell.Rdp/Channels/RdpsndChannel.cs | 102 +++++++++++--- src/VelaShell.Rdp/RdpConnection.cs | 26 +++- src/VelaShell.Rdp/RdpManagedSession.Audio.cs | 34 +++-- src/VelaShell.Rdp/RdpManagedSession.cs | 5 +- .../AudioOutputTests.cs | 34 +++-- .../AudioPlayoutTimingTests.cs | 39 ++++++ .../RdpSettingsTests.cs | 4 +- .../RdpsndChannelTests.cs | 40 ++++++ 11 files changed, 356 insertions(+), 81 deletions(-) diff --git a/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs b/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs index 9845ec3..7d27b13 100644 --- a/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs +++ b/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs @@ -193,7 +193,7 @@ bool Flag(string key, bool fallback = false) // Experience toggles: each is phrased as "turn the feature on", so an unticked box (the default) // keeps the bandwidth-saving profile. Font smoothing is an enable bit; the rest are disable bits. - bool audio = Flag(AudioKey); + bool audio = Flag(AudioKey, true); RdpPerformanceFlags performance = RdpPerformanceFlags.None; if (!Flag(WallpaperKey)) { performance |= RdpPerformanceFlags.DisableWallpaper; } if (!Flag(WindowDragKey)) { performance |= RdpPerformanceFlags.DisableFullWindowDrag; } @@ -506,14 +506,14 @@ internal static IReadOnlyList Declare(Loc loc, IReadOnlyLi Page = ExperiencePage }); // Experience toggles live on their own page, like mstsc's "Experience" tab. All unticked by - // default: the responsiveness-first profile (no wallpaper, animations, themes or audio). + // default except audio, which plays on the local default output: the responsiveness-first profile (no wallpaper, animations, themes). foreach ((string key, string label) in new[] { (AudioKey, loc["ExpAudio"]), (WallpaperKey, loc["ExpWallpaper"]), (WindowDragKey, loc["ExpWindowDrag"]), (AnimationsKey, loc["ExpAnimations"]), (ThemesKey, loc["ExpThemes"]), (FontSmoothingKey, loc["ExpFontSmoothing"]) }) { - fields.Add(new() { Key = key, Label = label, Kind = ProtocolSettingKind.Boolean, DefaultValue = "false", Page = ExperiencePage }); + fields.Add(new() { Key = key, Label = label, Kind = ProtocolSettingKind.Boolean, DefaultValue = key == AudioKey ? "true" : "false", Page = ExperiencePage }); } fields.Add(new() { Key = "jumpSession", Label = loc["Jump"], Kind = ProtocolSettingKind.SshSession }); diff --git a/src/VelaShell.Rdp/Audio/AudioOutput.cs b/src/VelaShell.Rdp/Audio/AudioOutput.cs index 90ecdf9..34a813b 100644 --- a/src/VelaShell.Rdp/Audio/AudioOutput.cs +++ b/src/VelaShell.Rdp/Audio/AudioOutput.cs @@ -54,6 +54,7 @@ internal sealed class NativeAudioOutput : IAudioOutput private int _queuedCount; private long _queuedBytes; private double _queuedMilliseconds; + private TaskCompletionSource _budgetChanged = NewPulse(); private readonly Action? _log; @@ -84,41 +85,63 @@ format.BitsPerSample is not (8 or 16) || data.Length % format.BlockAlign != 0) var command = new Command(Volatile.Read(ref _generation), format, data, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously), Stopwatch.GetTimestamp(), ct); - lock (_budgetGate) + return EnqueueAsync(command); + } + + private async Task EnqueueAsync(Command command) + { + while (true) { - double duration = DurationMilliseconds(command); - if (_queuedCount >= 128 || _queuedBytes + data.Length > 1024 * 1024 || - (_queuedCount > 0 && _queuedMilliseconds + duration > 2000)) + Task wait; + lock (_budgetGate) { - return Task.FromException(new IOException("RDP audio output queue capacity exceeded.")); - } + if (command.Generation != Volatile.Read(ref _generation)) + { + throw new OperationCanceledException("RDP audio playback was closed.", command.Cancellation); + } - _queuedCount++; - _queuedBytes += data.Length; - _queuedMilliseconds += duration; - command.QueueAllowance = TimeSpan.FromMilliseconds(_queuedMilliseconds + 100); - if (!_commands.Writer.TryWrite(command)) - { - ReleaseBudget(command); - command.Result!.SetException(new IOException("RDP audio output queue is closed.")); + ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, nameof(NativeAudioOutput)); + double duration = DurationMilliseconds(command); + if (_queuedCount < 128 && _queuedBytes + command.Data!.Length <= 1024 * 1024 && + (_queuedCount == 0 || _queuedMilliseconds + duration <= 2000)) + { + _queuedCount++; + _queuedBytes += command.Data.Length; + _queuedMilliseconds += duration; + command._queueAllowance = TimeSpan.FromMilliseconds(_queuedMilliseconds + 100); + command._admittedAt = Stopwatch.GetTimestamp(); + if (!_commands.Writer.TryWrite(command)) + { + ReleaseBudget(command); + throw new IOException("RDP audio output queue is closed."); + } + break; + } + + wait = _budgetChanged.Task; } + + // A burst of server audio must apply backpressure instead of permanently stopping + // playback. The worker releases budget as native buffers finish. + await wait.WaitAsync(command.Cancellation).ConfigureAwait(false); } + // Keep the caller cancellable even if a system driver stalls inside a native call. Native // buffers remain owned by the worker until that call returns and cleanup is safe. - return WaitForPlaybackAsync(command); + await WaitForPlaybackAsync(command).ConfigureAwait(false); } private async Task WaitForPlaybackAsync(Command command) { try { - await command.Result!.Task.WaitAsync(_stallAllowance + command.QueueAllowance, command.Cancellation).ConfigureAwait(false); + await command.Result!.Task.WaitAsync(_stallAllowance + command._queueAllowance, command.Cancellation).ConfigureAwait(false); } catch (TimeoutException) { // The timer can expire just before the stopwatch deadline due to millisecond rounding. // Invalidate the command before the caller can unblock a stalled native operation. - Volatile.Write(ref command.TimedOut, 1); + Volatile.Write(ref command._timedOut, 1); throw; } } @@ -131,6 +154,7 @@ public void Close() } int generation = Interlocked.Increment(ref _generation); + PulseBudget(); // A full queue already wakes the worker, which also observes the generation change. _ = _commands.Writer.TryWrite(new Command(generation, default, null, null, 0, default)); } @@ -143,6 +167,7 @@ public void Dispose() } _ = Interlocked.Increment(ref _generation); + PulseBudget(); _ = _commands.Writer.TryComplete(); } @@ -155,11 +180,15 @@ private async Task RunAsync() var timing = new AudioPlayoutTiming(); double waitingMilliseconds = 0; long bufferingSince = 0; - long lastReport = 0; + long lastReport = 0, previousActivePoll = 0; + double maxPollGap = 0; + int drains = 0; + Task? readable = null; try { while (true) { + if (readable is { IsCompleted: true }) { readable = null; } while (_commands.Reader.TryRead(out Command? incoming)) { if (incoming.Result is null) @@ -184,6 +213,12 @@ private async Task RunAsync() opened = null; timing = new AudioPlayoutTiming(); } + long poll = Stopwatch.GetTimestamp(); + bool hadActive = active.Count != 0; + if (previousActivePoll != 0) + { + maxPollGap = Math.Max(maxPollGap, Stopwatch.GetElapsedTime(previousActivePoll, poll).TotalMilliseconds); + } // Reap completed buffers without draining the device. Later buffers keep playing. while (active.Count > 0 && _device.IsComplete()) { @@ -194,6 +229,7 @@ private async Task RunAsync() } if (active.Count == 0 && bufferingSince == 0) { + if (hadActive) { drains++; } bufferingSince = Stopwatch.GetTimestamp(); timing.ResetDrift(); } @@ -229,23 +265,26 @@ private async Task RunAsync() bufferingSince = Stopwatch.GetTimestamp(); CheckCancellation(next); } - if (!next.Observed) + if (!next._observed) { timing.ObserveArrival(next.EnqueuedAt * 1000.0 / Stopwatch.Frequency, DurationMilliseconds(next)); - next.Observed = true; + next._observed = true; } - if (active.Count == 0 && Stopwatch.GetElapsedTime(bufferingSince).TotalMilliseconds < timing.TargetMilliseconds) + double duration = DurationMilliseconds(next); + if (active.Count == 0 && duration < timing.TargetMilliseconds && + Stopwatch.GetElapsedTime(bufferingSince).TotalMilliseconds < timing.TargetMilliseconds) { break; } double deviceMilliseconds = _device.PendingFrames * 1000.0 / next.Format.SampleRate; - if (active.Count > 0 && deviceMilliseconds >= 120) + // Keep a successor ready for long server blocks, even with a coarse device clock. + double refillThreshold = Math.Clamp(duration + timing.TargetMilliseconds, 120, 250); + if (active.Count > 0 && deviceMilliseconds >= refillThreshold) { break; } - double duration = DurationMilliseconds(next); _ = timing.UpdateRate(deviceMilliseconds + waitingMilliseconds - duration, duration); _device.Start(timing.Resample(next.Format, next.Data)); _ = waiting.Dequeue(); @@ -256,13 +295,16 @@ private async Task RunAsync() lastReport = Stopwatch.GetTimestamp(); try { - _log($"playout; targetMs={timing.TargetMilliseconds:F1}; bufferedMs={deviceMilliseconds + waitingMilliseconds + duration:F1}; correctionPpm={timing.RateCorrection * 1000000:F0}; inFlight={active.Count}"); + _log($"playout; targetMs={timing.TargetMilliseconds:F1}; bufferedMs={deviceMilliseconds + waitingMilliseconds + duration:F1}; driftTargetMs={timing.DriftTarget(duration):F1}; correctionPpm={timing.RateCorrection * 1000000:F0}; inFlight={active.Count}; deviceBeforeWriteMs={deviceMilliseconds:F1}; drains={drains}; maxActivePollGapMs={maxPollGap:F1}; at={DateTimeOffset.Now:HH:mm:ss.fff}"); + drains = 0; + maxPollGap = 0; } catch { /* Diagnostics cannot interrupt native buffer ownership. */ } } bufferingSince = 0; submitting = null; } + previousActivePoll = active.Count == 0 ? 0 : poll; } catch (Exception error) { @@ -288,15 +330,23 @@ private async Task RunAsync() if (active.Count == 0 && waiting.Count == 0) { bufferingSince = 0; - if (!await _commands.Reader.WaitToReadAsync().ConfigureAwait(false)) + readable ??= _commands.Reader.WaitToReadAsync().AsTask(); + if (!await readable.ConfigureAwait(false)) { break; } } else { - // Only active playback needs clock checks; idle outputs sleep on the channel. - await Task.Delay(5).ConfigureAwait(false); + // A successor arriving just before the device drains should wake the worker without + // waiting for a (sometimes coarse) OS timer. Keep at most one pending channel read. + var pollDelay = Task.Delay(5); + if (waiting.Count == 0 && !_commands.Reader.Completion.IsCompleted) + { + readable ??= _commands.Reader.WaitToReadAsync().AsTask(); + await Task.WhenAny(readable, pollDelay).ConfigureAwait(false); + } + else { await pollDelay.ConfigureAwait(false); } } } } @@ -316,9 +366,20 @@ private void ReleaseBudget(Command command) _queuedCount--; _queuedBytes -= command.Data!.Length; _queuedMilliseconds -= DurationMilliseconds(command); + PulseBudget(); } } + private void PulseBudget() + { + TaskCompletionSource changed = _budgetChanged; + _budgetChanged = NewPulse(); + _ = changed.TrySetResult(); + } + + private static TaskCompletionSource NewPulse() => + new(TaskCreationOptions.RunContinuationsAsynchronously); + private void Finish(Command command, Exception? error = null) { ReleaseBudget(command); @@ -344,8 +405,8 @@ private void CheckCancellation(Command command) throw new OperationCanceledException("RDP audio playback was closed."); } - TimeSpan deadline = _stallAllowance + command.QueueAllowance; - if (Volatile.Read(ref command.TimedOut) != 0 || Stopwatch.GetElapsedTime(command.EnqueuedAt) >= deadline) + TimeSpan deadline = _stallAllowance + command._queueAllowance; + if (Volatile.Read(ref command._timedOut) != 0 || Stopwatch.GetElapsedTime(command._admittedAt) >= deadline) { throw new TimeoutException($"RDP audio device stalled for {deadline.TotalSeconds:F1} seconds."); } @@ -364,8 +425,9 @@ private void CloseDevice() private sealed record Command(int Generation, AudioFormat Format, byte[]? Data, TaskCompletionSource? Result, long EnqueuedAt, CancellationToken Cancellation) { - internal int TimedOut; - internal TimeSpan QueueAllowance; - internal bool Observed; + internal int _timedOut; + internal TimeSpan _queueAllowance; + internal long _admittedAt; + internal bool _observed; } } diff --git a/src/VelaShell.Rdp/Audio/AudioPlayoutTiming.cs b/src/VelaShell.Rdp/Audio/AudioPlayoutTiming.cs index f7a4397..6d90f39 100644 --- a/src/VelaShell.Rdp/Audio/AudioPlayoutTiming.cs +++ b/src/VelaShell.Rdp/Audio/AudioPlayoutTiming.cs @@ -30,11 +30,30 @@ internal void ObserveArrival(double arrivalMilliseconds, double durationMillisec internal void ResetDrift() => _filteredError = _integral = _fractionalFrames = RateCorrection = 0; + // Occupancy is measured BEFORE the next block is submitted. Do not speed through + // the last fraction of a long server block just to reach a short startup target. + internal double DriftTarget(double durationMilliseconds) => + Math.Max(TargetMilliseconds, Math.Min(180, 0.95 * durationMilliseconds)); + internal double UpdateRate(double bufferedMilliseconds, double durationMilliseconds) { // Device-clock occupancy is filtered over seconds: packet jitter must not modulate pitch. double seconds = Math.Min(durationMilliseconds / 1000, 0.25); - double error = Math.Clamp(bufferedMilliseconds - TargetMilliseconds, -100, 100); + double target = DriftTarget(durationMilliseconds); + double error = Math.Clamp(bufferedMilliseconds - target, -100, 100); + if (bufferedMilliseconds < target / 2) + { + // A previous burst may have saturated the controller. Its positive bias must not + // keep draining an already thin reserve while the slow filter catches up. + _filteredError = Math.Min(0, _filteredError); + _integral = Math.Min(0, _integral); + } + else if (target > TargetMilliseconds && bufferedMilliseconds >= 0.98 * durationMilliseconds) + { + // At almost a whole block of reserve the two-block window cannot absorb further slowdown. + _filteredError = Math.Max(0, _filteredError); + _integral = Math.Max(0, _integral); + } _filteredError += (error - _filteredError) * (1 - Math.Exp(-seconds / 5)); _integral = Math.Clamp(_integral + _filteredError * seconds * 0.000002, -0.004, 0.004); RateCorrection = Math.Clamp(_filteredError * 0.00005 + _integral, -0.005, 0.005); diff --git a/src/VelaShell.Rdp/Channels/RdpsndChannel.cs b/src/VelaShell.Rdp/Channels/RdpsndChannel.cs index 52d696a..6c08a03 100644 --- a/src/VelaShell.Rdp/Channels/RdpsndChannel.cs +++ b/src/VelaShell.Rdp/Channels/RdpsndChannel.cs @@ -9,8 +9,14 @@ internal sealed class RdpsndChannel(Func send, private readonly List _formats = []; private readonly CancellationTokenSource _stop = new(); private readonly TaskCompletionSource _failure = new(TaskCreationOptions.RunContinuationsAsynchronously); + // Owned by the serial PDU reader. Bound audio time as well as confirmation count: + // eight of the server's 32 KiB stereo blocks would already be 1.49 seconds. + private const double WindowMs = 420; + private const long StaleMs = 600; + private readonly Queue<(Task Confirmed, double Ms)> _window = new(); + private double _windowMs, _skippedMs; + private int _skippedBlocks; private Task _confirmations = Task.CompletedTask; - private int _inFlight; private bool _disposed; internal Task PlaybackFailure => _failure.Task; internal async Task DrainAsync() @@ -28,6 +34,13 @@ internal async Task DrainAsync() } } private long _playedBlocks; + private long? _previousReceive, _lastInputReport; + private double _previousDuration, _maxArrivalLate; + private long _maxDispatchDelay; + private ushort _previousStamp; + private int? _stampStepAtPeak; + private long? _assemblyAtPeak, _previousReadTicks; + private double? _readMsAtPeak; private bool _receivedWave; private bool _receivedNonSilentWave; private bool _initialized; @@ -36,7 +49,7 @@ internal async Task DrainAsync() private PendingWave? _pending; private sealed record PendingWave(ushort Timestamp, ushort Format, byte Block, int Length, byte[] Prefix); - internal async Task ProcessAsync(byte[] pdu, long receivedAt, CancellationToken ct) + internal async Task ProcessAsync(byte[] pdu, long receivedAt, CancellationToken ct, long? firstFragmentAt = null, long? readTicks = null) { ct.ThrowIfCancellationRequested(); _stop.Token.ThrowIfCancellationRequested(); @@ -52,7 +65,7 @@ internal async Task ProcessAsync(byte[] pdu, long receivedAt, CancellationToken Require(pdu.Length == pending.Length && pdu.Length >= 4, "Invalid Wave payload size."); byte[] data = (byte[])pdu.Clone(); pending.Prefix.CopyTo(data, 0); - await PlayAsync(pending.Timestamp, pending.Format, pending.Block, data, receivedAt, ct).ConfigureAwait(false); + await PlayAsync(pending.Timestamp, pending.Format, pending.Block, data, receivedAt, firstFragmentAt, readTicks, ct).ConfigureAwait(false); return; } @@ -80,7 +93,7 @@ internal async Task ProcessAsync(byte[] pdu, long receivedAt, CancellationToken _closed = true; await DrainAsync().WaitAsync(ct).ConfigureAwait(false); output?.Close(); - Log($"server closed output; playedBlocks={_playedBlocks}"); + Log($"server closed output; playedBlocks={_playedBlocks}; skippedBlocks={_skippedBlocks}; skippedMs={_skippedMs:F0}; closeAgeMs={Environment.TickCount64 - receivedAt}"); break; case 2: Require(!_closed && pdu.Length == 16 && bodySize >= 12, "Invalid WaveInfo PDU."); @@ -89,7 +102,7 @@ internal async Task ProcessAsync(byte[] pdu, long receivedAt, CancellationToken break; case 13: Require(!_closed && _version >= 8 && bodySize >= 12, "Invalid Wave2 PDU."); - await PlayAsync(U16(pdu, 4), U16(pdu, 6), pdu[8], pdu.AsSpan(16).ToArray(), receivedAt, ct).ConfigureAwait(false); + await PlayAsync(U16(pdu, 4), U16(pdu, 6), pdu[8], pdu.AsSpan(16).ToArray(), receivedAt, firstFragmentAt, readTicks, ct).ConfigureAwait(false); break; default: throw new RdpProtocolException($"Unsupported RDPSND message 0x{pdu[0]:X2}."); @@ -129,8 +142,15 @@ private async Task FormatsAsync(byte[] pdu, CancellationToken ct) _version = Math.Min((ushort)8, U16(pdu, 21)); _initialized = true; _closed = false; + _window.Clear(); + _windowMs = _skippedMs = 0; + _skippedBlocks = 0; _playedBlocks = 0; _receivedWave = _receivedNonSilentWave = false; + _previousReceive = _lastInputReport = _assemblyAtPeak = _previousReadTicks = null; + _readMsAtPeak = null; + _stampStepAtPeak = null; + _maxArrivalLate = _maxDispatchDelay = 0; Log($"formats received; serverVersion={U16(pdu, 21)}; offered={count}; accepted={formats.Count}; playback={output is not null}"); byte[] response = new byte[20 + accepted.Sum(f => f.Length)]; BinaryPrimitives.WriteUInt32LittleEndian(response, output is not null ? 1u : 0u); @@ -154,7 +174,7 @@ private async Task FormatsAsync(byte[] pdu, CancellationToken ct) } } - private Task PlayAsync(ushort timestamp, ushort index, byte block, byte[] data, long receivedAt, CancellationToken ct) + private async Task PlayAsync(ushort timestamp, ushort index, byte block, byte[] data, long receivedAt, long? firstFragmentAt, long? readTicks, CancellationToken ct) { ValidateFormat(index); AudioFormat format = _formats[index]; @@ -169,22 +189,67 @@ private Task PlayAsync(ushort timestamp, ushort index, byte block, byte[] data, _receivedNonSilentWave = !silent; } _receivedWave = true; - if (Volatile.Read(ref _inFlight) >= 128) + double duration = data.Length * 1000.0 / format.BlockAlign / format.SampleRate; + var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct, _stop.Token); + try + { + while (_window.TryPeek(out (Task Confirmed, double Ms) oldest)) + { + if (!oldest.Confirmed.IsCompleted) + { + if (_window.Count < 8 && _windowMs + duration <= Math.Max(WindowMs, 2 * duration)) { break; } + await Task.WhenAny(oldest.Confirmed, PlaybackFailure).WaitAsync(lifetime.Token).ConfigureAwait(false); + if (PlaybackFailure.IsCompletedSuccessfully) { throw new IOException("RDP audio playback failed.", PlaybackFailure.Result); } + } + _ = _window.Dequeue(); + _windowMs = _window.Count == 0 ? 0 : _windowMs - oldest.Ms; + } + lifetime.Token.ThrowIfCancellationRequested(); + long now = Environment.TickCount64; + bool stale = now - receivedAt > Math.Max(StaleMs, 2 * duration); + if (stale) { _skippedBlocks++; _skippedMs += duration; } + if (log is not null) + { + if (_previousReceive is long previous) + { + double late = receivedAt - previous - _previousDuration; + if (late > _maxArrivalLate) + { + _maxArrivalLate = late; + _assemblyAtPeak = receivedAt - firstFragmentAt; + _readMsAtPeak = (readTicks - _previousReadTicks) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; + _stampStepAtPeak = unchecked((ushort)(timestamp - _previousStamp)); + } + } + _previousStamp = timestamp; + _previousReceive = receivedAt; + _previousReadTicks = readTicks; + _previousDuration = duration; + _maxDispatchDelay = Math.Max(_maxDispatchDelay, now - receivedAt); + if (_lastInputReport is null || now - _lastInputReport >= 5000) + { + Log($"input; maxArrivalLateMs={_maxArrivalLate:F0}; serverStampStepAtPeakMs={_stampStepAtPeak}; fragmentSpanAtPeakMs={_assemblyAtPeak}; pumpReadAtPeakMs={_readMsAtPeak:F0}; maxDispatchMs={_maxDispatchDelay}; blockMs={_previousDuration:F1}; skippedBlocks={_skippedBlocks}; skippedMs={_skippedMs:F0}; at={DateTimeOffset.Now:HH:mm:ss.fff}"); + _lastInputReport = now; + _assemblyAtPeak = null; + _readMsAtPeak = null; + _stampStepAtPeak = null; + _maxArrivalLate = _maxDispatchDelay = 0; + } + } + Task playback = stale ? Task.CompletedTask : output!.PlayAsync(format, data, lifetime.Token); + _confirmations = ConfirmAsync(_confirmations, playback, timestamp, block, receivedAt, lifetime, !stale); + _window.Enqueue((_confirmations, stale ? 0 : duration)); + if (!stale) { _windowMs += duration; } + } + catch { - throw new IOException("RDP audio confirmation queue capacity exceeded."); + lifetime.Dispose(); + throw; } - - var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct, _stop.Token); - Task playback; - try { playback = output!.PlayAsync(format, data, lifetime.Token); } - catch { lifetime.Dispose(); throw; } - _ = Interlocked.Increment(ref _inFlight); - _confirmations = ConfirmAsync(_confirmations, playback, timestamp, block, receivedAt, lifetime); - return Task.CompletedTask; } private async Task ConfirmAsync(Task previous, Task playback, ushort timestamp, byte block, - long receivedAt, CancellationTokenSource lifetime) + long receivedAt, CancellationTokenSource lifetime, bool played) { try { @@ -201,7 +266,7 @@ private async Task ConfirmAsync(Task previous, Task playback, ushort timestamp, BinaryPrimitives.WriteUInt16LittleEndian(confirm, unchecked((ushort)(timestamp + Environment.TickCount64 - receivedAt))); confirm[2] = block; await send(Packet(5, confirm), lifetime.Token).ConfigureAwait(false); - if (Interlocked.Increment(ref _playedBlocks) == 1) { Log("first playback completed and confirmed"); } + if (played && Interlocked.Increment(ref _playedBlocks) == 1) { Log("first playback completed and confirmed"); } } catch (Exception error) { @@ -212,7 +277,6 @@ private async Task ConfirmAsync(Task previous, Task playback, ushort timestamp, } finally { - _ = Interlocked.Decrement(ref _inFlight); lifetime.Dispose(); } } diff --git a/src/VelaShell.Rdp/RdpConnection.cs b/src/VelaShell.Rdp/RdpConnection.cs index 22dc933..b432559 100644 --- a/src/VelaShell.Rdp/RdpConnection.cs +++ b/src/VelaShell.Rdp/RdpConnection.cs @@ -29,7 +29,10 @@ internal sealed record RdpConnectOptions( } /// Raised when a virtual channel delivers data to the managed session. -internal readonly record struct ChannelPayload(string ChannelName, byte[] Data, int TunnelType = 0); +internal readonly record struct ChannelPayload(string ChannelName, byte[] Data, int TunnelType = 0) +{ + internal long? FirstAudioFragmentAt { get; init; } +} /// /// Drives the full RDP connection sequence and the active-phase pump using only managed @@ -60,7 +63,7 @@ internal sealed partial class RdpConnection : IAsyncDisposable private readonly System.Collections.Concurrent.ConcurrentDictionary _channelWriteGates = new(); private readonly CancellationTokenSource _sendStop = new(); private readonly Dictionary _channelsById = []; - private readonly Dictionary _vcReassembly = []; + private readonly Dictionary _vcReassembly = []; /// Largest complete virtual-channel message accepted (cliprdr formats/file lists, rdpdr I/O). internal const uint MaxChannelMessage = 32 * 1024 * 1024; private const int ChannelChunkSize = 1600; @@ -387,8 +390,12 @@ private async Task HandleDemandActiveAsync(byte[] payload, CancellationToken ct) // ---- Active-phase pump ---- /// Reads and processes one PDU. Returns false when the server disconnects. + // Single pump; sampled synchronously on rdpsnd delivery, never from the audio worker. + internal long PumpReadTicks { get; private set; } + internal async Task PumpAsync(CancellationToken ct) { + long readStart = _options.AudioPlayback ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; RdpFramePdu pdu; try { pdu = await _transport.ReadPduAsync(ct).ConfigureAwait(false); } // A failing read is the network, not the protocol: reset, keep-alive timeout, a socket closed after a stalled @@ -399,6 +406,7 @@ internal async Task PumpAsync(CancellationToken ct) throw new RdpConnectionLostException(ex); } + if (readStart != 0) { PumpReadTicks += System.Diagnostics.Stopwatch.GetTimestamp() - readStart; } _autoDetect.Observe(pdu.Data.Length); if (pdu.FastPath) { @@ -907,14 +915,15 @@ internal void ReassembleChannel(ushort channelId, string name, byte[] payload) throw new RdpProtocolException("Virtual channel PDU too large."); } - _vcReassembly[channelId] = (new MemoryStream((int)Math.Min(totalLength, 64 * 1024)), totalLength); + _vcReassembly[channelId] = (new MemoryStream((int)Math.Min(totalLength, 64 * 1024)), totalLength, + name == "rdpsnd" ? Environment.TickCount64 : null); } else if (!_vcReassembly.ContainsKey(channelId)) { return; // a continuation whose start never came: nothing to attach it to } - (MemoryStream buffer, uint total) = _vcReassembly[channelId]; + (MemoryStream buffer, uint total, long? firstFragmentAt) = _vcReassembly[channelId]; if (buffer.Length + chunk.Length > total) { _ = _vcReassembly.Remove(channelId); @@ -927,7 +936,14 @@ internal void ReassembleChannel(ushort channelId, string name, byte[] payload) _ = _vcReassembly.Remove(channelId); if (buffer.Length == total) { - ChannelData?.Invoke(new ChannelPayload(name, buffer.ToArray())); + if (ChannelData is { } deliver) + { + // This stream is no longer reachable from the pump. Transfer its exact-sized array for sound + // instead of copying a full Wave; never expose unused capacity or a shared history buffer. + byte[] bytes = firstFragmentAt.HasValue && buffer.Capacity == buffer.Length + ? buffer.GetBuffer() : buffer.ToArray(); + deliver(new ChannelPayload(name, bytes) { FirstAudioFragmentAt = firstFragmentAt }); + } } } } diff --git a/src/VelaShell.Rdp/RdpManagedSession.Audio.cs b/src/VelaShell.Rdp/RdpManagedSession.Audio.cs index 62d4140..e8e05fc 100644 --- a/src/VelaShell.Rdp/RdpManagedSession.Audio.cs +++ b/src/VelaShell.Rdp/RdpManagedSession.Audio.cs @@ -13,7 +13,8 @@ public interface IRdpAudioSource public sealed partial class RdpManagedSession : IRdpAudioSource { - private Channel<(byte[] Data, long ReceivedAt)>? _audioQueue; + private readonly record struct AudioMessage(byte[] Data, long ReceivedAt, long? FirstFragmentAt, long ReadTicks); + private Channel? _audioQueue; private CancellationTokenSource? _audioStop; private Task? _audioWorker; private long _audioQueuedBytes; @@ -41,7 +42,7 @@ public event Action? AudioPlaybackFailed internal void EnableAudio(bool playback, Func? createOutput = null) { - _audioQueue = Channel.CreateBounded<(byte[], long)>(new BoundedChannelOptions(128) + _audioQueue = Channel.CreateBounded(new BoundedChannelOptions(128) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait @@ -67,10 +68,10 @@ internal void EnableAudio(bool playback, Func? createOutput = null break; } - while (_audioQueue.Reader.TryRead(out (byte[] Data, long ReceivedAt) message)) + while (_audioQueue.Reader.TryRead(out AudioMessage message)) { _ = Interlocked.Add(ref _audioQueuedBytes, -message.Data.Length); - await channel.ProcessAsync(message.Data, message.ReceivedAt, _audioStop.Token).ConfigureAwait(false); + await channel.ProcessAsync(message.Data, message.ReceivedAt, _audioStop.Token, message.FirstFragmentAt, message.ReadTicks).ConfigureAwait(false); } } await channel.DrainAsync().ConfigureAwait(false); @@ -79,7 +80,7 @@ internal void EnableAudio(bool playback, Func? createOutput = null catch (Exception ex) { FailAudio(ex); } finally { - while (_audioQueue.Reader.TryRead(out (byte[] Data, long ReceivedAt) pending)) + while (_audioQueue.Reader.TryRead(out AudioMessage pending)) { _ = Interlocked.Add(ref _audioQueuedBytes, -pending.Data.Length); } @@ -87,15 +88,32 @@ internal void EnableAudio(bool playback, Func? createOutput = null }); } - internal void ReceiveAudio(byte[] data) + internal void ReceiveAudio(byte[] data, long? firstFragmentAt = null) { if (_audioStop?.IsCancellationRequested != false) { return; } long queued = Interlocked.Add(ref _audioQueuedBytes, data.Length); - if (data.Length > ushort.MaxValue + 4 || queued > 1024 * 1024 - || _audioQueue?.Writer.TryWrite((data, Environment.TickCount64)) != true) + if (data.Length > ushort.MaxValue + 4 || queued > 1024 * 1024 || _audioQueue is null) { _ = Interlocked.Add(ref _audioQueuedBytes, -data.Length); FailAudio(new IOException("RDP audio queue capacity exceeded; reconnect to resume audio.")); + return; + } + + try + { + // The virtual-channel callback is synchronous. Blocking only when the bounded queue is + // full applies TCP backpressure and preserves RDPSND PDU order instead of dropping a wave. + var message = new AudioMessage(data, Environment.TickCount64, firstFragmentAt, Connection.PumpReadTicks); + if (!_audioQueue.Writer.TryWrite(message)) + { + _audioQueue.Writer.WriteAsync(message, _audioStop.Token) + .AsTask().GetAwaiter().GetResult(); + } + } + catch (Exception error) when (error is OperationCanceledException or ChannelClosedException) + { + _ = Interlocked.Add(ref _audioQueuedBytes, -data.Length); + if (!_audioStop.IsCancellationRequested) { FailAudio(error); } } } diff --git a/src/VelaShell.Rdp/RdpManagedSession.cs b/src/VelaShell.Rdp/RdpManagedSession.cs index 93c9da3..bf9e13c 100644 --- a/src/VelaShell.Rdp/RdpManagedSession.cs +++ b/src/VelaShell.Rdp/RdpManagedSession.cs @@ -396,7 +396,8 @@ internal static IReadOnlyList BuildChannels(RdpClientOptions options // Windows device redirection also needs the sound channel registered, even without playback. if (options.AudioPlayback || options.SmartCardRedirection || options.Drives.Count > 0 || options.Ports.Count > 0 || options.Printers.Count > 0) { - channels.Add(new ChannelDef("rdpsnd", 0xC0000000)); // INITIALIZED|ENCRYPT_RDP + // MS-RDPBCGR CHANNEL_OPTION_PRI_HIGH: request timely delivery under channel contention. + channels.Add(new ChannelDef("rdpsnd", options.AudioPlayback ? 0xC8000000u : 0xC0000000u)); } if (graphicsReady || ((options.DynamicResolution || options.MonitorLayout is not null) && options.RemoteApp is null) @@ -620,7 +621,7 @@ private void OnChannelData(ChannelPayload payload) } else if (payload.ChannelName == "rdpsnd") { - ReceiveAudio(payload.Data); + ReceiveAudio(payload.Data, payload.FirstAudioFragmentAt); } else if (payload.ChannelName == "rdpdr") { diff --git a/tests/VelaShell.Plugin.Rdp.Tests/AudioOutputTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/AudioOutputTests.cs index 25dad46..2cc4094 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/AudioOutputTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/AudioOutputTests.cs @@ -67,6 +67,20 @@ public async Task SubmitsMultipleBuffersBeforeCompletionAndPreservesCompletionOr await output.Completion.WaitAsync(TimeSpan.FromSeconds(2)); } + [TestMethod] + public async Task LongServerBlocksCanQueueASuccessorBeforeTheDeviceClockAdvances() + { + var device = new FakeDevice { _framesPerStart = 8192 }; + using var output = new NativeAudioOutput(device); + var format = new AudioFormat(2, 44100, 16); + Task first = output.PlayAsync(format, new byte[32768], default); + Task second = output.PlayAsync(format, new byte[32768], default); + await device._secondStarted.Task.WaitAsync(TimeSpan.FromSeconds(2)); + Assert.IsFalse(first.IsCompleted); + device._complete = true; + await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(2)); + } + [TestMethod] public async Task CloseCancelsAllInFlightBuffersAndReopensWithDifferentFormat() { @@ -110,19 +124,19 @@ public async Task FormatChangeWaitsUntilPreviouslySubmittedBuffersFinish() } [TestMethod] - public async Task QueueBudgetIncludesBuffersAlreadyTakenByWorker() + public async Task QueueBudgetWaitsForBuffersAlreadyTakenByWorker() { var device = new FakeDevice(); using var output = new NativeAudioOutput(device); Task[] playing = [.. Enumerable.Range(0, 3).Select(_ => output.PlayAsync(Stereo, new byte[3840], default))]; await device._multipleStarted.Task.WaitAsync(TimeSpan.FromSeconds(2)); - _ = await Assert.ThrowsExactlyAsync(() => output.PlayAsync(Stereo, new byte[384000], default)); + Task large = output.PlayAsync(Stereo, new byte[384000], default); + await Task.Delay(50); + Assert.IsFalse(large.IsCompleted); + device._complete = true; + await Task.WhenAll(playing).WaitAsync(TimeSpan.FromSeconds(2)); + await large.WaitAsync(TimeSpan.FromSeconds(2)); output.Dispose(); - foreach (Task task in playing) - { - _ = await Assert.ThrowsAsync(() => task); - } - await output.Completion.WaitAsync(TimeSpan.FromSeconds(2)); } @@ -453,7 +467,8 @@ private sealed class FakeDevice : IPcmDevice internal readonly List _opens = []; internal readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource _multipleStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); - internal int _permittedCompletions; + internal int _permittedCompletions, _framesPerStart; + internal readonly TaskCompletionSource _secondStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource _openEntered = new(TaskCreationOptions.RunContinuationsAsynchronously); internal readonly TaskCompletionSource _closed = new(TaskCreationOptions.RunContinuationsAsynchronously); internal volatile bool _complete; @@ -478,12 +493,13 @@ public void Start(byte[] data) _starts++; _ = _started.TrySetResult(); + if (_starts == 2) { _ = _secondStarted.TrySetResult(); } if (_starts >= 3) { _ = _multipleStarted.TrySetResult(); } } - public long PendingFrames => 0; + public long PendingFrames => _complete ? 0 : _starts * _framesPerStart; public bool IsComplete() { if (_complete) diff --git a/tests/VelaShell.Plugin.Rdp.Tests/AudioPlayoutTimingTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/AudioPlayoutTimingTests.cs index 28d75a7..771d242 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/AudioPlayoutTimingTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/AudioPlayoutTimingTests.cs @@ -53,6 +53,45 @@ public void DeviceClockFeedbackStabilizesTenMinutesOfClockDrift(double clockErro Assert.AreEqual(0, timing.RateCorrection); } + [TestMethod] + public void LongBlocksRetainEnoughHeadroomForAShortArrivalSlip() + { + const double block = 32768 * 1000.0 / (44100 * 4); + var timing = new AudioPlayoutTiming(); + double reserve = 160; + // Equal device/server clocks; after three minutes a single Wave arrives 100 ms late. + for (int i = 0; i < 970; i++) + { + double rate = timing.UpdateRate(reserve, block); + reserve += block / (1 + rate) - block; + } + Assert.IsGreaterThan(100.0, reserve, "The playout clock consumed the jitter reserve."); + Assert.IsLessThan(block, reserve, "Regular arrivals must not build a growing latency tail."); + for (int i = 0; i < 200; i++) { _ = timing.UpdateRate(300, block); } + Assert.IsGreaterThan(0.0, timing.RateCorrection); + Assert.IsLessThanOrEqualTo(0.0, timing.UpdateRate(35, block), "Do not accelerate after the reserve collapses."); + } + + [TestMethod] + public void LongWavePlaybackSurvivesObservedLanArrivalSlipsWithoutAddingAThirdBlock() + { + const double block = 32768 * 1000.0 / (44100 * 4); + var timing = new AudioPlayoutTiming(); + double reserve = 120, precedingSlip = 0; + for (int i = 0; i < 1350; i++) + { + // Three minutes of steady playback, then the two late Waves from the LAN trace. + // A late Wave is followed by an on-time Wave, not a permanent shift of the sender clock. + double slip = i switch { 970 => 158, 1051 => 146, _ => 0 }; + reserve += precedingSlip - slip; + Assert.IsGreaterThan(0.0, reserve, $"Device drained at Wave {i}."); + double rate = timing.UpdateRate(reserve, block); + reserve += block / (1 + rate) - block; + Assert.IsLessThan(2 * block, reserve + block, "Two submitted Waves must suffice."); + precedingSlip = slip; + } + } + [TestMethod] [DataRow(1, 8, 100)] [DataRow(2, 16, 100)] diff --git a/tests/VelaShell.Plugin.Rdp.Tests/RdpSettingsTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/RdpSettingsTests.cs index 41159dc..c98fc28 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/RdpSettingsTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/RdpSettingsTests.cs @@ -107,7 +107,7 @@ public void GatewayDoesNotSilentlyBypassAnSshJump() public void ExperienceTogglesDefaultToTheBandwidthSavingProfile() { var settings = RdpSettings.From(Request(), new("en")); - Assert.IsFalse(settings.Audio); + Assert.IsTrue(settings.Audio); Assert.AreEqual( RdpPerformanceFlags.DisableWallpaper | RdpPerformanceFlags.DisableFullWindowDrag | RdpPerformanceFlags.DisableMenuAnimations | RdpPerformanceFlags.DisableThemes, @@ -133,7 +133,7 @@ public void ExperienceFieldsLiveOnTheirOwnPage() { ProtocolSettingField field = fields.Single(f => f.Key == key); Assert.AreEqual(ProtocolSettingKind.Boolean, field.Kind); - Assert.AreEqual("false", field.DefaultValue); + Assert.AreEqual(key == "audio" ? "true" : "false", field.DefaultValue); Assert.AreEqual(RdpSettings.ExperiencePage, field.Page); } } diff --git a/tests/VelaShell.Plugin.Rdp.Tests/RdpsndChannelTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/RdpsndChannelTests.cs index 9bda53b..729e276 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/RdpsndChannelTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/RdpsndChannelTests.cs @@ -28,6 +28,16 @@ public void PlaybackRegistersBothChannelsWithoutRequiringDeviceMappings(bool dri names, "Windows does not send audio formats unless the companion RDPDR channel is advertised (MS-RDPEA 2.1)."); } + [TestMethod] + [DataRow(true)] + [DataRow(false)] + public void DeviceOnlySoundChannelDoesNotRequestPlaybackPriority(bool playback) + { + var options = new RdpClientOptions { Host = "localhost", AudioPlayback = playback, Drives = [new DriveMapping("work", Path.GetTempPath())] }; + ChannelDef sound = RdpManagedSession.BuildChannels(options).Single(c => c.Name == "rdpsnd"); + Assert.AreEqual(playback, (sound.Options & 0x08000000) != 0); + } + [TestMethod] public async Task NegotiationFiltersFormatsAndUsesClientIndicesAndTrainingEcho() { @@ -102,6 +112,36 @@ public async Task ReceivesMoreWavesAndTrainingWhilePlaybackIsPendingAndConfirmsI Assert.AreSequenceEqual(new byte[] { 255, 0 }, [.. sent.Where(static pdu => pdu[0] == 5).Select(static pdu => pdu[6])]); } + [TestMethod] + public async Task BurstOfLongWavesBoundsPlayoutSkipsStaleDataAndConfirmsInOrder() + { + var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var second = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var output = new RecordingOutput { Completions = new Queue([first.Task, second.Task, Task.CompletedTask]) }; + var sent = new List(); + using RdpsndChannel channel = Make(output, sent); + await Process(channel, Formats(8, Format())); + Task Wave(byte block, long ageMs) + { + byte[] wave = Wave2(0, new byte[32768]); + wave[8] = block; + return channel.ProcessAsync(wave, Environment.TickCount64 - ageMs, default); + } + await Wave(254, 0); + await Wave(255, 0); + Task backlogged = Wave(0, 3500); + Assert.IsFalse(backlogged.IsCompleted); + first.SetResult(); + await backlogged.WaitAsync(TimeSpan.FromSeconds(2)); + Assert.HasCount(2, output.Samples); + Assert.AreSequenceEqual(new byte[] { 254 }, [.. sent.Where(p => p[0] == 5).Select(p => p[6])]); + second.SetResult(); + await Wave(1, 0); + await channel.DrainAsync().WaitAsync(TimeSpan.FromSeconds(2)); + Assert.HasCount(3, output.Samples); + Assert.AreSequenceEqual(new byte[] { 254, 255, 0, 1 }, [.. sent.Where(p => p[0] == 5).Select(p => p[6])]); + } + [TestMethod] public async Task AsynchronousDeviceFailureIsObservableWithoutAnotherPacket() { From 9778493f0a787eadb8fb8cbe7585c7239b70d7cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=9C=E5=AE=87?= Date: Mon, 30 Nov 2026 17:52:24 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E5=B0=86=E5=BE=85=E5=A4=84=E7=90=86?= =?UTF-8?q?=E7=9A=84=20RDP=20=E9=87=8D=E5=AE=9A=E5=90=91=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E8=AE=BE=E4=B8=BA=E7=A7=81=E6=9C=89=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 统一使用 `_pendingRedirection` 存储和消费会话重定向信息,更新连接器、工作区文档及相关测试引用,保持一次性重定向与自动重连行为不变。 --- plugins/VelaShell.Plugin.Rdp/RdpConnector.cs | 2 +- plugins/VelaShell.Plugin.Rdp/RdpSettings.cs | 2 +- plugins/VelaShell.Plugin.Rdp/RdpWorkspaceDocument.cs | 2 +- tests/VelaShell.Plugin.Rdp.Tests/RdpRedirectionTests.cs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/plugins/VelaShell.Plugin.Rdp/RdpConnector.cs b/plugins/VelaShell.Plugin.Rdp/RdpConnector.cs index 75845b2..2495891 100644 --- a/plugins/VelaShell.Plugin.Rdp/RdpConnector.cs +++ b/plugins/VelaShell.Plugin.Rdp/RdpConnector.cs @@ -68,7 +68,7 @@ internal static async Task ConnectAsync(WorkspaceConnectRequest req { // A redirection that ended the previous session is followed by this one connection only: should the target // be unreachable, later attempts go back to the configured server, which (a broker) routes them again. - if (Interlocked.Exchange(ref settings.PendingRedirection, null) is { } redirection) + if (Interlocked.Exchange(ref settings._pendingRedirection, null) is { } redirection) { return await RdpManagedSession.ConnectRedirectedAsync(options, redirection, linked.Token).ConfigureAwait(false); } diff --git a/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs b/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs index 7d27b13..d4cb729 100644 --- a/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs +++ b/plugins/VelaShell.Plugin.Rdp/RdpSettings.cs @@ -18,7 +18,7 @@ internal sealed record RdpSettings(string Domain, int Width, int Height, int Tim internal AutoReconnectCookie? AutoReconnectCookie { get; set; } /// A redirection that ended the session; the next connection follows it once (mid-session, like mstsc). - internal RdpServerRedirectionException? PendingRedirection; + internal RdpServerRedirectionException? _pendingRedirection; internal IReadOnlyList Ports { get; init; } = []; internal IReadOnlyList Printers { get; init; } = []; internal RdpCameraDevice? Camera { get; init; } diff --git a/plugins/VelaShell.Plugin.Rdp/RdpWorkspaceDocument.cs b/plugins/VelaShell.Plugin.Rdp/RdpWorkspaceDocument.cs index 9d89221..d40f389 100644 --- a/plugins/VelaShell.Plugin.Rdp/RdpWorkspaceDocument.cs +++ b/plugins/VelaShell.Plugin.Rdp/RdpWorkspaceDocument.cs @@ -168,7 +168,7 @@ private void OnDisconnected(IRdpSession session, Exception? failure) string target = redirection.TargetFqdn ?? redirection.TargetNetAddress ?? _request?.Host ?? ""; _context.Log.Info($"RDP {_request?.Host}:{_request?.Port}: the server redirected the session to {target}; following it."); _settings.AutoReconnectCookie = null; - _settings.PendingRedirection = redirection; + _settings._pendingRedirection = redirection; StartAutoReconnect(session, immediate: true, loc => loc.Format("Redirecting", target)); return; } diff --git a/tests/VelaShell.Plugin.Rdp.Tests/RdpRedirectionTests.cs b/tests/VelaShell.Plugin.Rdp.Tests/RdpRedirectionTests.cs index 31e2a8a..bed673b 100644 --- a/tests/VelaShell.Plugin.Rdp.Tests/RdpRedirectionTests.cs +++ b/tests/VelaShell.Plugin.Rdp.Tests/RdpRedirectionTests.cs @@ -175,7 +175,7 @@ public async Task ARedirectionDuringTheSessionIsFollowedAtOnce() lock (sessions) { sessions.Add(session); - pending.Add(Interlocked.Exchange(ref settings.PendingRedirection, null)); + pending.Add(Interlocked.Exchange(ref settings._pendingRedirection, null)); } return Task.FromResult(session); });