Skip to content
Open
1 change: 1 addition & 0 deletions Models/SessionInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,7 @@ public int SshMonitorRefreshIntervalSeconds
/// the pipeline still connect - the bridge retries once without EGFX.
/// </summary>
public bool RdpGraphicsPipelineEnabled { get; set; } = true;
public bool RdpH264Enabled { get; set; }
public bool RdpRedirectDrives { get; set; }
public string RdpDriveName { get; set; } = "CxShell";
public string RdpDrivePath { get; set; } = string.Empty;
Expand Down
4 changes: 4 additions & 0 deletions Services/LocalizationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@ public sealed class LocalizationService : INotifyPropertyChanged
["SessionEdit.RdpSyncLockKeysHint"] = "Automatically synchronize local lock key states to the remote session on connect.",
["SessionEdit.RdpEnableClipboardLock"] = "Enable clipboard large file locking (LockClipboardData)",
["SessionEdit.RdpEnableClipboardLockHint"] = "Lock clipboard file snapshots during large file transfers so copying other content does not abort transfers.",
["SessionEdit.RdpH264"] = "H.264 / AVC444 acceleration",
["SessionEdit.RdpH264Hint"] = "Requests H.264 and AVC444 video codecs over EGFX for smoother video and scrolling on high-latency links. Requires EGFX graphics pipeline and server/decoder support.",
["SessionEdit.SshHost"] = "SSH Host",
["SessionEdit.SshPort"] = "SSH Port",
["SessionEdit.SshUsername"] = "SSH Username",
Expand Down Expand Up @@ -540,6 +542,8 @@ public sealed class LocalizationService : INotifyPropertyChanged
["SessionEdit.RdpSyncLockKeysHint"] = "连接时把本地的大小写、小键盘、滚动锁定状态同步给远端会话。",
["SessionEdit.RdpEnableClipboardLock"] = "启用剪贴板大文件锁定 (LockClipboardData)",
["SessionEdit.RdpEnableClipboardLockHint"] = "通过剪贴板传输大文件时锁定快照,防止中途复制其他内容导致传输中断。",
["SessionEdit.RdpH264"] = "启用 H.264 / AVC444 视频加速",
["SessionEdit.RdpH264Hint"] = "在 EGFX 图形管道上请求 H.264 与 AVC444 编码,以提升高延迟或视频/滚动场景流畅度。需同时开启 EGFX 图形管道且服务端与本地解码器支持。",
["SessionEdit.SshHost"] = "SSH 主机",
["SessionEdit.SshPort"] = "SSH 端口",
["SessionEdit.SshUsername"] = "SSH 用户",
Expand Down
162 changes: 138 additions & 24 deletions Services/RdpBridgeClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,15 @@ public RdpFramebufferEventArgs(
int stride,
byte[] pixels,
int? pixelLength = null,
Action? release = null)
Action? release = null,
RdpFrameDirtyRect? dirtyRect = null)
{
Width = width;
Height = height;
Stride = stride;
Pixels = pixels;
PixelLength = pixelLength ?? pixels.Length;
DirtyRect = dirtyRect;
_release = release;
}

Expand All @@ -57,6 +59,12 @@ public RdpFramebufferEventArgs(
public int Stride { get; }
public byte[] Pixels { get; }

/// <summary>
/// Optional dirty region (already unioned with the previous frame for
/// double-buffered targets). Null means the entire framebuffer must be copied.
/// </summary>
public RdpFrameDirtyRect? DirtyRect { get; }

/// <summary>
/// Valid byte count in <see cref="Pixels"/>. A pooled array may be larger
/// than the frame, so callers must use this instead of Pixels.Length.
Expand Down Expand Up @@ -92,6 +100,7 @@ public sealed class RdpBridgeClient : IDisposable
private const uint DirtyRectCapability = 0x00000400;
private const uint GfxApiVersion = 11;
private const uint GfxCapability = 0x00000800;
private const uint GfxH264Capability = 0x00080000;
private const uint SyncLockKeysApiVersion = 12;
private const uint SyncLockKeysCapability = 0x00001000;
private const uint PointerShapeApiVersion = 13;
Expand Down Expand Up @@ -145,6 +154,9 @@ public sealed class RdpBridgeClient : IDisposable
private int _previousFrameHeight;
private int _previousFrameStride;
private string _dirtyRectSource = "none";
private bool _pendingFullFrameCopy = true;
private RdpFrameDirtyRect? _pendingCopyDirtyRect;
private RdpFrameDirtyRect? _lastPresentedDirtyRect;
// Input arrives on the UI thread. Only a single atomic write is done there;
// the presentation timer folds it into the composer under _frameSync, so
// sending a mouse event never has to wait for a frame-copy lock.
Expand Down Expand Up @@ -316,6 +328,15 @@ public void Connect(
var gfxResult = NativeMethods.cxrdp_set_graphics_pipeline(_handle, gfxRequested ? 1 : 0);
DebugLog($"graphics pipeline requested={gfxRequested} session={session.RdpGraphicsPipelineEnabled} env={GraphicsPipelineForcedOn} result={gfxResult}");
});
if ((nativeCapabilities & GfxH264Capability) != 0)
{
var h264Requested = gfxRequested && session.RdpH264Enabled;
TryInvokeOptionalNative("cxrdp_set_h264_enabled", () =>
{
var h264Result = NativeMethods.cxrdp_set_h264_enabled(_handle, h264Requested ? 1 : 0);
DebugLog($"graphics pipeline h264 requested={h264Requested} result={h264Result}");
});
}
}
else
{
Expand Down Expand Up @@ -587,6 +608,7 @@ private void TryPresentFrame(object? state)
bool interactive;
bool settling;
bool logFrame;
RdpFrameDirtyRect? copyRect;

lock (_frameSync)
{
Expand All @@ -610,11 +632,29 @@ private void TryPresentFrame(object? state)
wave = _frameComposer.InRepaintWave;
collectMs = (long)_frameComposer.FirstFrameAge(now).TotalMilliseconds;
dirtySource = _dirtyRectSource;
snapshot = ArrayPool<byte>.Shared.Rent(length);
Buffer.BlockCopy(_frameBuffer, 0, snapshot, 0, length);
width = _frameWidth;
height = _frameHeight;
stride = _frameStride;
snapshot = ArrayPool<byte>.Shared.Rent(length);

var currentDirty = _pendingFullFrameCopy ? null : _pendingCopyDirtyRect;
if (currentDirty.HasValue && _lastPresentedDirtyRect.HasValue)
{
copyRect = ClampDirtyRect(UnionDirtyRect(currentDirty.Value, _lastPresentedDirtyRect.Value), width, height);
}
else
{
copyRect = null;
}

if (copyRect.HasValue)
CopyDirtyRectManaged(_frameBuffer, snapshot, stride, copyRect.Value);
else
Buffer.BlockCopy(_frameBuffer, 0, snapshot, 0, length);

_lastPresentedDirtyRect = currentDirty;
_pendingFullFrameCopy = false;
_pendingCopyDirtyRect = null;
_frameDirty = false;
interactive = _frameComposer.IsInteractive(now);
settling = _frameComposer.InSettlingWindow(now);
Expand Down Expand Up @@ -649,7 +689,8 @@ private void TryPresentFrame(object? state)
stride,
snapshot,
length,
() => ArrayPool<byte>.Shared.Return(snapshot));
() => ArrayPool<byte>.Shared.Return(snapshot),
copyRect);

try
{
Expand Down Expand Up @@ -1198,33 +1239,59 @@ private void OnFrame(IntPtr userData, int width, int height, int stride, IntPtr
_previousFrameWidth = width;
_previousFrameHeight = height;
_previousFrameStride = stride;
_pendingFullFrameCopy = true;
_pendingCopyDirtyRect = null;
_lastPresentedDirtyRect = null;
}

Marshal.Copy(data, _frameBuffer, 0, length);

// Most Windows servers leave FreeRDP's GDI invalid region empty on
// the legacy bitmap-update path. Diffing against the previous batch
// gives a server-independent dirty region: the first batch only
// covers the strip that was actually painted, so the composer can
// hold the frame until the whole desktop has arrived.
// Wave classification is only needed for the first frame and the
// settling window. In interactive/settled mode every snapshot is
// published as-is, so skip the sampled full-surface diff (thousands
// of cache-missing reads per mouse-move batch).
if (dirty is null && classifyWave && FrameCoverageEnabled && FrameCoalescingEnabled)
var clampedDirty = dirty.HasValue ? ClampDirtyRect(dirty.Value, width, height) : null;
var canPartialCopy = !sizeChanged &&
!classifyWave &&
clampedDirty.HasValue &&
stride >= width * 4;
if (canPartialCopy)
{
var diff = ComputeDirtyRectFromDiff(width, height, stride);
if (diff.HasValue)
var rect = clampedDirty!.Value;
CopyDirtyRectFromNative(data, _frameBuffer, stride, rect);
CopyDirtyRectManaged(_frameBuffer, _previousFrameBuffer, stride, rect);
if (!_pendingFullFrameCopy)
{
dirty = diff;
dirtySource = "diff";
_pendingCopyDirtyRect = _pendingCopyDirtyRect.HasValue
? UnionDirtyRect(_pendingCopyDirtyRect.Value, rect)
: rect;
}
}
else
{
Marshal.Copy(data, _frameBuffer, 0, length);

// Most Windows servers leave FreeRDP's GDI invalid region empty on
// the legacy bitmap-update path. Diffing against the previous batch
// gives a server-independent dirty region: the first batch only
// covers the strip that was actually painted, so the composer can
// hold the frame until the whole desktop has arrived.
// Wave classification is only needed for the first frame and the
// settling window. In interactive/settled mode every snapshot is
// published as-is, so skip the sampled full-surface diff (thousands
// of cache-missing reads per mouse-move batch).
if (dirty is null && classifyWave && FrameCoverageEnabled && FrameCoalescingEnabled)
{
var diff = ComputeDirtyRectFromDiff(width, height, stride);
if (diff.HasValue)
{
dirty = diff;
dirtySource = "diff";
}
}

// Keep the diff baseline fresh even when classification is idle,
// so switching back to wave mode never sees a stale full-screen
// difference. This is a plain sequential copy and stays cheap.
Buffer.BlockCopy(_frameBuffer, 0, _previousFrameBuffer, 0, length);
_pendingFullFrameCopy = true;
_pendingCopyDirtyRect = null;
}

// Keep the diff baseline fresh even when classification is idle,
// so switching back to wave mode never sees a stale full-screen
// difference. This is a plain sequential copy and stays cheap.
Buffer.BlockCopy(_frameBuffer, 0, _previousFrameBuffer, 0, length);
_dirtyRectSource = dirtySource;
_frameWidth = width;
_frameHeight = height;
Expand Down Expand Up @@ -1298,6 +1365,50 @@ private void OnFrame(IntPtr userData, int width, int height, int stride, IntPtr
return new RdpFrameDirtyRect(left, top, Math.Max(1, right - left), Math.Max(1, bottom - top));
}

private static RdpFrameDirtyRect? ClampDirtyRect(RdpFrameDirtyRect rect, int width, int height)
{
var x = Math.Clamp(rect.X, 0, width);
var y = Math.Clamp(rect.Y, 0, height);
var right = Math.Clamp(rect.X + rect.Width, 0, width);
var bottom = Math.Clamp(rect.Y + rect.Height, 0, height);
var w = right - x;
var h = bottom - y;
if (w <= 0 || h <= 0)
return null;
return new RdpFrameDirtyRect(x, y, w, h);
}

private static RdpFrameDirtyRect UnionDirtyRect(RdpFrameDirtyRect a, RdpFrameDirtyRect b)
{
var x = Math.Min(a.X, b.X);
var y = Math.Min(a.Y, b.Y);
var right = Math.Max(a.X + a.Width, b.X + b.Width);
var bottom = Math.Max(a.Y + a.Height, b.Y + b.Height);
return new RdpFrameDirtyRect(x, y, right - x, bottom - y);
}

private static void CopyDirtyRectFromNative(IntPtr source, byte[] destination, int stride, RdpFrameDirtyRect rect)
{
var rowBytes = rect.Width * 4;
var xBytes = rect.X * 4;
for (var row = 0; row < rect.Height; row++)
{
var offset = (rect.Y + row) * stride + xBytes;
Marshal.Copy(IntPtr.Add(source, offset), destination, offset, rowBytes);
}
}

private static void CopyDirtyRectManaged(byte[] source, byte[] destination, int stride, RdpFrameDirtyRect rect)
{
var rowBytes = rect.Width * 4;
var xBytes = rect.X * 4;
for (var row = 0; row < rect.Height; row++)
{
var offset = (rect.Y + row) * stride + xBytes;
Buffer.BlockCopy(source, offset, destination, offset, rowBytes);
}
}

private void OnStatus(IntPtr userData, IntPtr message)
{
var text = message == IntPtr.Zero ? string.Empty : Marshal.PtrToStringUTF8(message) ?? string.Empty;
Expand Down Expand Up @@ -1723,6 +1834,9 @@ public static extern int cxrdp_get_frame_dirty_rect(
[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)]
public static extern int cxrdp_set_graphics_pipeline(IntPtr handle, int enabled);

[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)]
public static extern int cxrdp_set_h264_enabled(IntPtr handle, int enabled);

[DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr cxrdp_get_last_error(IntPtr handle);
}
Expand Down
8 changes: 5 additions & 3 deletions Services/RdpDisplaySizeResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ public static class RdpDisplaySizeResolver

private static RdpDesktopSize Clamp(int width, int height)
{
return new RdpDesktopSize(
Math.Clamp(width, MinimumWidth, MaximumWidth),
Math.Clamp(height, MinimumHeight, MaximumHeight));
// MS-RDPEDISP (DISPLAYCONTROL_MONITOR_LAYOUT) requires an even width;
// Windows servers silently reject odd widths.
var clampedWidth = Math.Clamp(width, MinimumWidth, MaximumWidth) & ~1;
var clampedHeight = Math.Clamp(height, MinimumHeight, MaximumHeight);
return new RdpDesktopSize(clampedWidth, clampedHeight);
}

private static double NormalizeRenderScaling(double renderScaling)
Expand Down
Loading
Loading