Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion plugins/VelaShell.Plugin.Rdp/RdpConnector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ internal static async Task<IRdpSession> 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);
}
Expand Down
8 changes: 4 additions & 4 deletions plugins/VelaShell.Plugin.Rdp/RdpSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ internal sealed record RdpSettings(string Domain, int Width, int Height, int Tim
internal AutoReconnectCookie? AutoReconnectCookie { get; set; }

/// <summary>A redirection that ended the session; the next connection follows it once (mid-session, like mstsc).</summary>
internal RdpServerRedirectionException? PendingRedirection;
internal RdpServerRedirectionException? _pendingRedirection;
internal IReadOnlyList<PortMapping> Ports { get; init; } = [];
internal IReadOnlyList<PrinterMapping> Printers { get; init; } = [];
internal RdpCameraDevice? Camera { get; init; }
Expand Down Expand Up @@ -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; }
Expand Down Expand Up @@ -506,14 +506,14 @@ internal static IReadOnlyList<ProtocolSettingField> 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 });
Expand Down
2 changes: 1 addition & 1 deletion plugins/VelaShell.Plugin.Rdp/RdpWorkspaceDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
126 changes: 94 additions & 32 deletions src/VelaShell.Rdp/Audio/AudioOutput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string>? _log;

Expand Down Expand Up @@ -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;
}
}
Expand All @@ -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));
}
Expand All @@ -143,6 +167,7 @@ public void Dispose()
}

_ = Interlocked.Increment(ref _generation);
PulseBudget();
_ = _commands.Writer.TryComplete();
}

Expand All @@ -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<bool>? readable = null;
try
{
while (true)
{
if (readable is { IsCompleted: true }) { readable = null; }
while (_commands.Reader.TryRead(out Command? incoming))
{
if (incoming.Result is null)
Expand All @@ -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())
{
Expand All @@ -194,6 +229,7 @@ private async Task RunAsync()
}
if (active.Count == 0 && bufferingSince == 0)
{
if (hadActive) { drains++; }
bufferingSince = Stopwatch.GetTimestamp();
timing.ResetDrift();
}
Expand Down Expand Up @@ -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();
Expand All @@ -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)
{
Expand All @@ -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); }
}
}
}
Expand All @@ -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);
Expand All @@ -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.");
}
Expand All @@ -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;
}
}
21 changes: 20 additions & 1 deletion src/VelaShell.Rdp/Audio/AudioPlayoutTiming.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading