Skip to content

metal: video routing (Syphon) - #2564

Closed
JoeMatt wants to merge 7 commits into
flyinghead:devfrom
Provenance-Emu:metal/pr-syphon
Closed

JoeMatt wants to merge 7 commits into
flyinghead:devfrom
Provenance-Emu:metal/pr-syphon

Conversation

@JoeMatt

@JoeMatt JoeMatt commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Syphon output for the Metal renderers, like the OpenGL and Vulkan renderers already have on macOS. It depends on #2563, so only the last commit is new.

How it works. MetalContext::EndFrame hands the drawable to os_VideoRoutingPublishFrameTexture() on the frame's command buffer, after the frame, the overlays and the UI are drawn and before presentDrawable.

The server.

  • osx-main.mm implements it with the SyphonMetalServer the Vulkan path already uses. That static and its create/term helpers moved out of #ifdef USE_VULKAN, so both renderers share them.
  • The server is recreated if the Metal device changes, and stopped when the option is turned off and when the renderer or the context is terminated.

Output.

  • The image is published flipped. That gives a client the same orientation it gets from the OpenGL renderer.
  • "Scale down before sending" renders the image into a texture of the requested size with linear filtering, then publishes that texture. That matches the OpenGL path's glBlitFramebuffer; the Vulkan path passes the target size as the image region, which crops instead.

Testing

Orientation and frame rate. Frames received with SyphonMetalClient show the same orientation as the OpenGL renderer gives the same client (rend=0), at about 60 fps on rend=7 and rend=8 (1280x960, BGRA8).

Scaled output. "Scale down before sending" at 480 lines gives a full 640x480 frame.

Validation. MTL_DEBUG_LAYER=1 clean with Syphon on, on both renderers (SA2, THPS2), on an M4 Max with macOS 27.

Builds. It compiles with USE_VULKAN=ON USE_METAL=ON and with neither.

Known gaps

  • Vulkan renderer's Syphon at runtime. The refactored Vulkan path compiles with USE_VULKAN=ON USE_METAL=ON but wasn't run.
  • Receivers. Only a small Syphon client CLI was used (SyphonMetalClient → newFrameImage → PNG), not OBS or another app.

🤖 Generated with Claude Code

JoeMatt and others added 4 commits October 15, 2026 22:34
Based on Isaac Marovitz's Metal backend draft, flyinghead#1787.

Adds the RenderType::Metal renderer type and the USE_METAL build option
(on by default for macOS, forced off for iOS and libretro), creates the
Metal graphics context from initRenderApi with an OpenGL fallback, and
adds a Metal choice to the video settings. The duplicate frames option
and the About page also handle Metal. The switcher is compiled as
Objective-C++ when Metal is enabled because the Metal context header
uses Objective-C types.

The SDL display metrics use SDL_Metal_GetDrawableSize for Metal windows.
mainui maps renderer types to graphics APIs with a helper so that
switching to or from Metal recreates the graphics context.

Adds the Dear ImGui Metal backend. It is the upstream v1.92.8 file
without the platform_io DrawCallback_* registrations, which the vendored
imgui 1.92.6 does not have.

The USE_METAL compile definition and the Metal sources are added with
the renderer in the next commit; until then this code is compiled out.

Also fixes two problems that kept the standalone macOS app from building
with a non-Xcode generator:

- ZLIB_LIBRARY is set to "-lz" for the Xcode generator. With Ninja the
  ZLIB::ZLIB imported target then lists "-lz" as a file dependency of the
  final link, which fails with "no known rule to make it". Only set it
  for the Xcode generator.

- Syphon declares its prefix header with target_precompile_headers
  PUBLIC, so it propagates to flycast. flycast then gets a C++-only
  precompiled header, and every .mm file fails with "Objective-C was
  disabled in precompiled file". Clear Syphon's interface precompiled
  headers; the prefix header is only meant for Syphon's own sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Native Metal renderer for the macOS SDL build, selectable as "Metal" in
the video settings. It follows the Vulkan renderer's structure: a Metal
graphics context that presents through the SDL window's CAMetalLayer,
screen and render-to-texture drawers, a pipeline and depth/stencil state
cache, a texture cache, and the Dear ImGui Metal backend for the UI.

Shaders are MSL compiled at runtime and specialised with function
constants, like the Vulkan shader variants. Framebuffer emulation and
render-to-texture readback write back to VRAM. With threaded rendering,
Render() waits for the GPU before returning, so the SH4 thread is not
released on RENDER_DONE while the frame is still being drawn. GPU waits
are bounded (200ms) so a missing completion signal drops a frame instead
of hanging the render and SH4 threads. Only a wait that actually timed
out quarantines the frame; the command buffer status switches to
Completed slightly after the shared event fires, so checking it after a
successful wait would quarantine most render-to-texture frames.

macOS specifics: constant buffer offsets are 256-byte aligned, the
packed 16-bit texture formats are expanded to RGBA8 on GPUs that don't
support them (anything that isn't an Apple GPU), and the context refuses
to start before macOS 12 (MTLSharedEvent timed waits), so initRenderApi
falls back to OpenGL there.

Apple's MacTypes.h and QuickDraw headers declare global Rect and RGBColor
types that clash with flycast's. metal_apple.h imports the Apple
frameworks with those names renamed and is included first by every Metal
header.

Resource lifetime: buffers and textures are released by dropping the
last reference. Command buffers retain what they reference, so memory is
freed once the GPU is done with it; resources are not set to
MTLPurgeableStateEmpty first, which the Metal validation layer rejects
while a command buffer still uses them. ImGui setup reads the attachment
pixel format from a 1x1 texture instead of holding one of the layer's
drawables, and the swap chain color space reference is released.

Not implemented yet: video routing (Syphon). The VMU and crosshair
overlay is added in a later commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of the Vulkan OIT renderer, selected with Metal + Per Pixel
transparent sorting (RenderType::Metal_OIT). Translucent fragments are
appended to per-pixel linked lists in a collect pass, then sorted and
blended over the opaque background in a resolve pass. Translucent
modifier volumes and two-volume polygons are supported.

The TA parser treats Metal_OIT as per-pixel, like the other OIT
renderers, so translucent polygons are not sorted per triangle.

The opaque background is copied to a texture between the collect and
resolve encoders instead of being read with [[color(0)]] framebuffer
fetch, which not every Metal implementation supports. The collect and
resolve passes use separate render encoders because Metal does not
order device-memory atomics against later draws in the same encoder.

The OIT frame is waited on before presenting: the renderer's command
pool and the context's present path use different command queues, which
Metal does not order, and without the wait the present could sample the
color attachment before the resolve finished.

Collect fragments are depth-tested in the shader before they are
appended. fs_main writes [[depth(any)]], so the hardware depth test runs
after the fragment function, when the a-buffer append (device atomics)
has already happened; relying on it let translucent geometry behind
opaque surfaces be collected and blended on top. As in the Vulkan OIT
shaders ("Manual depth testing"), the collect discards fragments that
fail GEqual against the opaque depth:

- On Apple GPUs (MTLGPUFamilyApple2 or later: programmable blending and
  memoryless render targets), the OIT pass has a second colour
  attachment, R32Float and memoryless, that the OP/PT pipelines write
  their fragment depth to; the collect reads it with [[color(1)]]
  framebuffer fetch. Every pipeline in that encoder declares the
  attachment (writeMask None where it must not write) and the resolve
  encoder detaches it. Passes after the first seed it with a full-screen
  draw from a depth copy blitted before the encoder opens.
- Elsewhere (Intel/AMD Macs), the encoder is ended after the OP/PT
  draws, the depth attachment is blitted to a sampled copy, and the
  collect reads that copy.

Two-volume translucent collects (stencil areas 1/2) use an
[[early_fragment_tests]] entry point with a depth-Always,
stencil-area-test state, so the stencil test runs before the append;
depth is still tested in the shader.

The translucent modifier volume marks, their inclusion/exclusion sums
and the resolve run in one render encoder and access the shaded pixel's
a-buffer list. Where Vulkan uses two by-region fragment-to-fragment
barriers, the shaders put the pixel buffer and head pointers in raster
order group 0 when the GPU supports raster order groups. Otherwise the
encoder uses a fragment memory barrier on Intel/AMD GPUs, where it is
valid, or is ended and reopened at each ordering point.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of VulkanOverlay. The overlay is drawn by the Metal context after
the frame and before ImGui, so both Metal renderers get it. A VMU texture
is recreated when its screen changes rather than updated in place, since
a frame still in flight may be sampling it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings October 16, 2026 21:37

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

With rend.EmulateFramebuffer on, Present() shows the frame read back from
VRAM (presentFramebuffer), but MetalOITScreenDrawer::EndFrame never wrote the
rendered frame there, so the per-pixel renderer presented black frames. The
regular Metal renderer was fine.

Do what Vulkan's OITScreenDrawer::EndFrame does: when emulating the
framebuffer, call scaleAndWriteFramebuffer on the attachment just rendered,
before the ping-pong index advances. scaleAndWriteFramebuffer and its cached
readback textures move from MetalScreenDrawer to MetalBaseDrawer (Vulkan keeps
it on BaseDrawer) so both screen drawers share it. The copies are now also
bounded by the source texture, since the OIT attachments are sized from the
drawer viewport rather than globClip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
JoeMatt and others added 2 commits October 16, 2026 19:14
OITMetalRenderer::Render never called resize(), so the OIT screen
drawer kept BaseMetalRenderer's 640x480 default viewport. Per-pixel
mode ignored rend.Resolution, and under EmulateFramebuffer a PVR
framebuffer that isn't 640x480 was rendered into 640x480.

Port OITVulkanRenderer::resize: Render() resizes to
framebufferWidth/Height, and the override grows the a-buffer (one
head pointer per pixel) and re-inits the screen drawer.

The screen drawer's attachments only ever grew, but it presents and
reads back the whole color attachment, so a smaller viewport now
drops them and MakeBuffers reallocates them at the exact size.

MakeBuffers grows the shared OIT buffers before its early return,
like Vulkan OITDrawer::MakeBuffers, and the first-frame head-pointer
clear covers the whole buffer instead of the current pass's w*h.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Publish the presented image to Syphon with the Metal renderers, like the
OpenGL and Vulkan renderers do on macOS.

MetalContext::EndFrame hands the drawable texture, after the frame, the
overlays and the UI are drawn, to os_VideoRoutingPublishFrameTexture()
on the frame's command buffer. The macOS shell implements it with a
SyphonMetalServer, shared with the Vulkan renderer, and recreates the
server if the Metal device changes. The image is published flipped,
which gives clients the same orientation as the OpenGL renderer.

"Scale down before sending" renders the image into a texture of the
requested size with linear filtering before publishing it, as the
OpenGL renderer does with glBlitFramebuffer.

The server is stopped when the option is turned off and when the
renderer or the context is terminated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@JoeMatt

JoeMatt commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

Folded into #2563 as a commit there, so it's one PR instead of three stacked ones.

@JoeMatt JoeMatt closed this Oct 17, 2026
@JoeMatt
JoeMatt deleted the metal/pr-syphon branch October 17, 2026 05:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants