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
1 change: 1 addition & 0 deletions docs/macos/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<height>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

Expand Down
17 changes: 12 additions & 5 deletions src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down
9 changes: 5 additions & 4 deletions src/graphics/SharpEmu.Gpu.Metal/V2/MetalFlipCopyPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@
namespace SharpEmu.Gpu.Metal.V2;

/// <summary>
/// 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.
/// <para>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.</para>
Expand Down
23 changes: 19 additions & 4 deletions src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.FlipCopy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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;
}

Expand Down
12 changes: 12 additions & 0 deletions src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Diagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,18 @@ private static HashSet<ulong> 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
{
Expand Down
12 changes: 6 additions & 6 deletions src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
Expand All @@ -800,7 +800,7 @@ private static void PresentFrame()
{
if (presented != 0)
{
if (MetalV2Diagnostics.FlipAhead)
if (MetalV2Diagnostics.FlipCopies)
{
lock (_frameGate)
{
Expand Down Expand Up @@ -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;

/// <summary>
/// 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.
/// </summary>
Expand Down Expand Up @@ -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");
Expand Down
49 changes: 48 additions & 1 deletion tests/SharpEmu.Gpu.Metal.Tests/MetalFlipCopyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
namespace SharpEmu.Gpu.Metal.Tests;

/// <summary>
/// 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.
/// </summary>
public sealed class MetalFlipCopyTests(ITestOutputHelper output)
Expand Down Expand Up @@ -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<byte>([0xFF, 0x00, 0x00, 0xFF], frame.AsSpan(texel, 4).ToArray());
Assert.Equal<byte>([0x00, 0xFF, 0x00, 0xFF], next.AsSpan(texel, 4).ToArray());
}
}

private static byte[] ReadTexture(nint device, nint texture)
{
const nuint bytes = Side * Side * 4;
Expand Down
Loading