From 90251b44f870fa18fae8023761c38a67868eaef7 Mon Sep 17 00:00:00 2001 From: kuba Date: Tue, 17 Nov 2026 13:42:10 +0000 Subject: [PATCH] [Metal] Present a copy of each flip's frame taken in the stream at the flip The window thread sampled the guest's display image on its own queue, unordered against the guest's GPU work. A double-buffered title that starts its next frame in the buffer still on screen (its safe-for-rendering wait is answered once that buffer's own flip was shown) then had its half-drawn, cleared frame presented: Poppy Playtime's title menu went black in ~10% of window captures. Every flip, GPU or CPU, now blits its frame into a presenter-owned texture in the same command buffer as the flip, fenced after the passes that drew it and before anything the guest records after the flip (the copy SHARPEMU_FLIP_AHEAD already used). The frame is promoted only once that command buffer completed, and a pool texture is reused only when it is not presented, queued or being encoded and its last presentation finished, so the window thread never samples a copy being written. The guest is not held back; the cost is one blit per flip. SHARPEMU_METAL_V2_PRESENT_SNAPSHOT=0 presents the display image live. Poppy title, 160 window shots each: 0/160 black with the snapshot, 31/160 with it off. --- docs/macos/configuration.md | 1 + .../V2/MetalCommandStream.cs | 17 +++++-- .../V2/MetalFlipCopyPool.cs | 9 ++-- .../V2/MetalRenderHost.FlipCopy.cs | 23 +++++++-- .../V2/MetalV2Diagnostics.cs | 12 +++++ .../SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs | 12 ++--- .../MetalFlipCopyTests.cs | 49 ++++++++++++++++++- 7 files changed, 103 insertions(+), 20 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 98c053ff..adb32c9e 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -43,6 +43,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_TITLE_SCENE_RESOLUTION` | unset | Demon's Souls only (known build). Caps the game's internal scene size below the display: `900p`, `720p`, `540p` (any `p`, 16:9) or `WIDTHxHEIGHT`, at least 640x360. The game renders the scene at that size and upscales it itself; the output, display buffers and UI keep their sizes. Lowers image quality for frame time: on a base M4 at a 1080p display, about 78 ms per frame uncapped, 69 ms at `900p`, 63 ms at `720p`, 55 ms at `540p`. Below `540p` the picture breaks and nothing more is gained. | | `SHARPEMU_STALL_WATCHDOG_SECONDS` | `20` | Seconds without import progress before the stall watchdog acts. `0` disables it. | | `SHARPEMU_FLIP_AHEAD` | off | Experimental. `1` tells the game a GPU flip is done once the flip is recorded and the flip before it has really finished on the GPU, instead of when the frame is shown, so the game can build its next frame while the GPU draws this one (at most one flip ahead). Each such frame is copied in the GPU stream into a presenter-owned texture (up to 7 textures the size of the display buffer), so what is shown is unchanged; a flip whose frame cannot be copied keeps the usual timing, and the refusal is logged once. Pacing, interrupts and labels are unchanged. Counters: `[VIDEOOUT][FLIP-AHEAD]` and the `flip_copy*` fields of `[METAL-PRESENT]`. | +| `SHARPEMU_METAL_V2_PRESENT_SNAPSHOT` | on | `0` presents a flipped display buffer directly instead of a copy of it. By default each flip's frame is copied in the GPU stream, at the flip, into a presenter-owned texture (one blit per flip; up to 7 textures the size of the display buffer, 4 in use on a 60 fps title), so a game that starts drawing its next frame into the buffer still on screen cannot show a half-drawn (black) frame. A frame that cannot be copied is presented directly and the refusal is logged once. | ## Metal memory diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 0acb8b6e..d194e09a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -3172,11 +3172,17 @@ private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, l if (_dumpThisFlip) { DumpTexture(image.Texture, "flip-after-refresh"); } SampleFlipLuma(image.Texture); var texture = PresentationViewOf(imageIdentifier, image, in request); - // SHARPEMU_FLIP_AHEAD: the presenter gets a copy taken here, in the stream, instead of - // the display image the guest may render into once it hears of the flip. + // The presenter gets a copy taken here, in the stream, instead of the display image the + // guest may render into while it is on screen (MetalRenderHost.FlipCopy.cs). var presented = texture; - var copied = MetalV2Diagnostics.FlipAhead && gpuQueued && _flipTarget is not null && texture != 0 && - TryCopyFlipFrame(texture, out presented); + var copied = false; + if (_flipTarget is not null && texture != 0) + { + presented = FlipFrameForPresenter(texture, gpuQueued, out copied); + } + + // The serial of the command buffer holding the copy: the presenter promotes the frame + // only once it completed, so it never samples a copy still being written. var serial = SubmissionSerial; FlushCommandBuffer(PassEndCause.Present); if (_flipTarget is null || texture == 0) @@ -3209,7 +3215,8 @@ private void CaptureFlip(int handle, int index, ulong requestId, int flipMode, l VideoOutBackendServices.IsHdrPixelFormat(displayBuffer.PixelFormat)); if (MetalV2Diagnostics.FlipAhead) { - NoteFlipFrameCaptured(requestId, copied); + // Only GPU flips are published ahead; a CPU flip counts as live, as before the snapshot. + NoteFlipFrameCaptured(requestId, copied && gpuQueued); } VideoOutBackendServices.TraceGpuFlip( diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs index 29123fd1..dd39baab 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs @@ -6,10 +6,11 @@ namespace SharpEmu.Gpu.Metal.V2; /// -/// SHARPEMU_FLIP_AHEAD: the presenter-owned textures a GPU flip's frame is copied into, in the -/// stream at the flip (MetalRenderHost.FlipCopy.cs). Without the copy the presenter samples the -/// display image's own texture until the next frame replaces it, so a guest told of flip N before -/// N is shown could render the next frame into the buffer still on screen. +/// The presenter-owned textures a flip's frame is copied into, in the stream at the flip +/// (MetalRenderHost.FlipCopy.cs; SHARPEMU_METAL_V2_PRESENT_SNAPSHOT, and SHARPEMU_FLIP_AHEAD for GPU +/// flips). Without the copy the presenter samples the display image's own texture until the next +/// frame replaces it, so a guest that renders into the buffer still on screen (told it is safe once +/// its flip was shown, or of flip N before N is shown) has its half-drawn frame presented. /// A texture goes back to the pool only once the presenter can no longer read it: it is not /// the presented frame, not queued, not being encoded by a presentation, and the last /// presentation command buffer that sampled it has completed. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs index 4471f3f9..3af004b4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs @@ -5,8 +5,9 @@ namespace SharpEmu.Gpu.Metal.V2; -// SHARPEMU_FLIP_AHEAD: a GPU flip's frame is copied, in the stream at the flip, into a texture -// only the presenter reads (MetalFlipCopyPool), and video-out is told once the flip is recorded +// A flip's frame is copied, in the stream at the flip, into a texture only the presenter reads +// (MetalFlipCopyPool; SHARPEMU_METAL_V2_PRESENT_SNAPSHOT, default on). SHARPEMU_FLIP_AHEAD needs +// that copy for GPU flips, and video-out is told once the flip is recorded // and the buffer carrying it committed, so it may publish the flip to the guest before the GPU // finishes it (VideoOutExports.FlipAhead.cs). internal sealed partial class MetalRenderHost @@ -24,6 +25,19 @@ internal sealed partial class MetalRenderHost // frame is promoted: the guest must not hear of that next flip before it is shown. private bool _previousFlipFrameCopied = true; + // The frame a flip hands the presenter. With the snapshot (SHARPEMU_METAL_V2_PRESENT_SNAPSHOT, + // any flip) or flip-ahead (GPU flips) it is a pool copy blitted here, in the stream, after the + // passes that drew the frame and before anything the guest records after the flip, so a later + // redraw of the display buffer cannot reach what the window thread samples. Otherwise, or when + // the copy is refused, it is the display image itself. + internal nint FlipFrameForPresenter(nint texture, bool gpuQueued, out bool copied) + { + var presented = texture; + copied = (MetalV2Diagnostics.PresentSnapshot || (MetalV2Diagnostics.FlipAhead && gpuQueued)) && + TryCopyFlipFrame(texture, out presented); + return presented; + } + // Copies the flip's presented view into a pool texture at this point of the stream. False // (refused, logged once and counted) leaves the frame to be presented live, as today. internal bool TryCopyFlipFrame(nint source, out nint presented) @@ -103,8 +117,9 @@ private static bool RefuseFlipCopy(MetalFlipCopyPool.Refusal refusal, string det MetalFlipCopyPool.NoteRefusal(refusal); MetalV2Diagnostics.WarnOnce( $"flip-copy-{MetalFlipCopyPool.RefusalName(refusal)}", - $"Flip ahead: a flip's frame could not be copied for the presenter ({MetalFlipCopyPool.RefusalName(refusal)}: " + - $"{detail}); it is presented live and published to the guest at presentation, as without the switch."); + $"A flip's frame could not be copied for the presenter ({MetalFlipCopyPool.RefusalName(refusal)}: " + + $"{detail}); the display image is presented live, so a guest redraw of it while on screen can show, " + + $"and under flip-ahead the flip is published to the guest at presentation."); return false; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs index 78aadd6a..8e42d174 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs @@ -160,6 +160,18 @@ private static HashSet ParseHashes(string? text) public static readonly bool FlipAhead = Environment.GetEnvironmentVariable("SHARPEMU_FLIP_AHEAD") == "1" || SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled; + // SHARPEMU_METAL_V2_PRESENT_SNAPSHOT=0 (default on): every flip, GPU or CPU, hands the presenter + // a copy of its frame blitted in the stream at the flip (MetalFlipCopyPool), not the display + // image itself. The guest may render into a display buffer while it is still on screen (its + // safe-for-rendering wait is answered once the buffer's own flip was shown), and the window + // thread samples on its own queue, unordered against that rendering: a present landing after + // the redraw began showed the half-drawn (cleared) frame. 0 presents the display image live. + public static readonly bool PresentSnapshot = + !string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_PRESENT_SNAPSHOT"), "0", StringComparison.Ordinal); + + // Whether flips may hand the presenter pool copies, so the presenter tracks what it samples. + public static readonly bool FlipCopies = PresentSnapshot || FlipAhead; + public static readonly int EarlyLabelProbe = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_EARLY_LABEL_PROBE") switch { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs index 6121dcb1..e53e53c6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs @@ -711,7 +711,7 @@ private static void PresentFrame() if (presented != 0) { MetalNative.Send(presented, MetalNative.Selector("retain")); - if (MetalV2Diagnostics.FlipAhead) + if (MetalV2Diagnostics.FlipCopies) { // A flip copy being encoded is not handed back to the pool (IsFlipCopyHeld). _encodingTexture = presented; @@ -787,7 +787,7 @@ private static void PresentFrame() MetalNative.SendVoid(commandBuffer, MetalNative.Selector("presentDrawable:"), drawable); MetalMemoryTelemetry.Commits.Add(); MetalNative.SendVoid(commandBuffer, MetalNative.Selector("commit")); - if (MetalV2Diagnostics.FlipAhead && presented != 0 && texture == presented) + if (MetalV2Diagnostics.FlipCopies && presented != 0 && texture == presented) { MetalFlipCopyPool.NoteSampled(presented, commandBuffer); } @@ -800,7 +800,7 @@ private static void PresentFrame() { if (presented != 0) { - if (MetalV2Diagnostics.FlipAhead) + if (MetalV2Diagnostics.FlipCopies) { lock (_frameGate) { @@ -836,11 +836,11 @@ private static void AdoptPendingFrame() private static readonly AutoResetEvent _flipPacerSignal = new(false); - // SHARPEMU_FLIP_AHEAD: the presented frame PresentFrame is encoding outside the frame gate. + // Flip copies (snapshot or flip-ahead): the presented frame PresentFrame is encoding outside the frame gate. private static nint _encodingTexture; /// - /// SHARPEMU_FLIP_AHEAD: whether the presenter may still read this flip copy from the CPU + /// Flip copies (snapshot or flip-ahead): whether the presenter may still read this flip copy from the CPU /// side: it is the presented frame, a queued one, or the one a presentation is encoding. /// The pool checks the presentation command buffers that sampled it itself. /// @@ -1339,7 +1339,7 @@ private static void ReportPresentationStatistics(bool presented = true) $"flip_attempts={flips.Attempts} flip_no_buffer={flips.WithoutBuffer} " + $"flip_discarded={flips.Discarded} flip_published={flips.Published} " + $"flip_refreshed={flips.Refreshed} {DescribeGpuMemory()}" + - (MetalV2Diagnostics.FlipAhead ? " " + MetalFlipCopyPool.TakeReport() : "")); + (MetalV2Diagnostics.FlipCopies ? " " + MetalFlipCopyPool.TakeReport() : "")); } private static readonly nint SelCurrentAllocatedSize = MetalNative.Selector("currentAllocatedSize"); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs index a5173cc2..77beebc1 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs @@ -10,7 +10,7 @@ namespace SharpEmu.Gpu.Metal.Tests; /// -/// SHARPEMU_FLIP_AHEAD: the frame a flip hands the presenter is a copy taken in the stream at the +/// SHARPEMU_METAL_V2_PRESENT_SNAPSHOT / SHARPEMU_FLIP_AHEAD: the frame a flip hands the presenter is a copy taken in the stream at the /// flip, so a draw into the display image recorded after the flip does not reach it. /// public sealed class MetalFlipCopyTests(ITestOutputHelper output) @@ -57,6 +57,53 @@ public void ADrawIntoTheDisplayImageRecordedAfterTheFlipDoesNotChangeTheCaptured } } + // SHARPEMU_METAL_V2_PRESENT_SNAPSHOT (default on): any flip, a CPU flip too, hands the presenter + // a copy, so the guest redrawing the buffer still on screen does not reach the presented frame. + [Fact] + public void TheSnapshotHandsThePresenterAFrameARedrawOfTheDisplayBufferDoesNotChange() + { + if (!RequireDevice()) return; + if (!MetalV2Diagnostics.PresentSnapshot) + { + output.WriteLine("SHARPEMU_METAL_V2_PRESENT_SNAPSHOT=0: flips are presented live."); + return; + } + + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + var formats = new[] { GpuFormat.R8G8B8A8Unorm }; + var red = rig.Pipeline(formats, ["1.0f, 0.0f, 0.0f, 1.0f"]); + var green = rig.Pipeline(formats, ["0.0f, 1.0f, 0.0f, 1.0f"]); + var target = rig.MakeTarget(Address, GpuFormat.R8G8B8A8Unorm, Side, Side); + + using (host.BeginPreparation()) + { + rig.Draw(red, [target]); + host.EndRendering(); + } + + var display = host.ImageCache.GetImage(target.State.Image).Texture; + var presented = host.FlipFrameForPresenter(display, gpuQueued: false, out var copied); + Assert.True(copied); + Assert.NotEqual(display, presented); + + using (host.BeginPreparation()) + { + rig.Draw(green, [target]); + host.EndRendering(); + } + + host.FlushAndWaitForGpu(MetalWaitReason.Synchronize); + var frame = ReadTexture(Device.Value, presented); + var next = ReadTexture(Device.Value, host.ImageCache.GetImage(target.State.Image).Texture); + output.WriteLine($"presented=0x{BitConverter.ToUInt32(frame, 0):X8} display=0x{BitConverter.ToUInt32(next, 0):X8}"); + for (var texel = 0; texel < frame.Length; texel += 4) + { + Assert.Equal([0xFF, 0x00, 0x00, 0xFF], frame.AsSpan(texel, 4).ToArray()); + Assert.Equal([0x00, 0xFF, 0x00, 0xFF], next.AsSpan(texel, 4).ToArray()); + } + } + private static byte[] ReadTexture(nint device, nint texture) { const nuint bytes = Side * Side * 4;