Repository navigation
feat(macos): add HDR10 streaming support via ScreenCaptureKit and VideoToolbox - #6209
fwordnvidia wants to merge 4 commits into
Conversation
…eoToolbox - Detect HDR displays via NSScreen EDR headroom (gated to Apple Silicon + macOS 15+ with @autoreleasepool) and populate Rec. 2020 PQ static HDR metadata. - Configure SCCapture for HDR10 using SCCaptureDynamicRangeHDRCanonicalDisplay, kCGColorSpaceITUR_2100_PQ, and kCVImageBufferYCbCrMatrix_ITU_R_2020. - Keep capture, VideoToolbox, and Moonlight HDR state synchronized via snapshotted metadata, one-shot SDR fallback in sckit::backend_policy_t, and mid-stream SDR<->HDR transition reinit. - Pass static HDR10 Mastering Display Color Volume (GBR big-endian) and Content Light Level Info metadata to native VideoToolbox VTCompressionSession. - Document macOS experimental HDR support and add unit tests covering metadata encoding, capture fallback policy, and hardware HEVC Main10 HDR encoding.
ReenigneArcher
left a comment
There was a problem hiding this comment.
Requesting changes for the shared capture/client HDR mismatch and the missing HDR-output assertions in the hardware regression test. The inline feedback also covers the required formatting and documentation updates.
Validation on fa049d02f5aa2e4638a194f96c73bc4858eb93a8:
- All 41 focused DisplayHelpers, SCCaptureLoop, and VTEncoder tests passed on Apple Silicon, including hardware HEVC encoding. These ran in an isolated harness that rebuilt the PR sources/tests, reused cached dependency/test-support libraries, and supplied minimal configuration globals.
- All six changed production translation units and three changed test translation units passed syntax checks with
-Werrorand a macOS 15 deployment target.git diff --checkpassed. - The SDR-first/HDR-second state reproduction failed on the current code and passed with the suggested guard.
- Removing the encoder's HDR-metadata application block still allowed the new hardware test to pass.
- The locked clang-format 23.1.0 check failed in two changed files.
The latest retrieved SonarCloud, documentation, and Semantic PR checks succeeded; no macOS build/test check was available on this head. A complete CMake build, end-to-end Moonlight streaming, and both live multi-client arrival orders were not run locally. The PR is currently reported mergeable against master; no conflicts were confirmed.
Review completed by Codex | Model: gpt-6.1-sol | Thinking: xhigh
|
|
||
| if (hwdevice_type == platf::mem_type_e::videotoolbox) { | ||
| const auto pixel_format {videotoolbox_pixel_format(config)}; | ||
| if (!hdr_fallback) { |
There was a problem hiding this comment.
[P2] Keep shared capture and client HDR state consistent
With multiple streaming channels enabled, captureThread() creates the shared display from the first client's configuration. If an SDR client connects first on an HDR-capable screen, this block still populates hdr_metadata, although hdrEnabled is false. A later HDR client shares that display, sees is_hdr() == true, and selects PQ encoding and enables mail::hdr for SDR-captured pixels. I reproduced that mismatch with a fake HDR screen and the real display() factory.
Only snapshot HDR metadata when capture is actually configured for HDR. This change makes the SDR-first reproduction pass:
| if (!hdr_fallback) { | |
| if (!hdr_fallback && config.dynamicRange > 0) { |
Please also cover both client arrival orders: an SDR client joining an HDR capture currently receives the retained PQ pixel buffer through vt_encode_device::convert() without tone mapping. Mixed modes need separate capture groups or per-session conversion so each encoder receives pixels matching its advertised colorspace. The suggested guard was tested locally; the full multi-client streaming path was not.
Review completed by Codex | Model: gpt-6.1-sol | Thinking: xhigh
| EXPECT_EQ(frame.data[2], 0); | ||
| EXPECT_EQ(frame.data[3], 1); | ||
| // Leading NAL unit on an HEVC IDR frame must be VPS (type 32). | ||
| EXPECT_EQ((frame.data[4] >> 1) & 0x3f, 32); |
There was a problem hiding this comment.
[P2] Assert the encoded HDR metadata in this regression test
The assertions only require an IDR beginning with VPS, so an ordinary HEVC frame passes even when mastering metadata never reaches the output. I removed the entire HDR-metadata application block from apply_colorspace() in a temporary encoder copy and this hardware test still passed. The unmodified test fixture's encoded frame also contained only NAL types 32, 33, 34, and 20 on this Apple Silicon host.
Please inspect the encoded SEI payload and compare the mastering-display values, and exercise nonzero content-light metadata as well. For example, append the following assertion here to check that the serialized mastering payload is present after removing emulation-prevention bytes; a complete test should additionally validate the enclosing prefix-SEI NAL and VUI Main10/BT.2020/PQ fields.
| EXPECT_EQ((frame.data[4] >> 1) & 0x3f, 32); | |
| EXPECT_EQ((frame.data[4] >> 1) & 0x3f, 32); | |
| std::vector<std::uint8_t> unescaped; | |
| unsigned zero_count = 0; | |
| for (const auto byte : frame.data) { | |
| if (zero_count >= 2 && byte == 3) { | |
| zero_count = 0; | |
| continue; | |
| } | |
| unescaped.push_back(byte); | |
| zero_count = byte == 0 ? zero_count + 1 : 0; | |
| } | |
| const auto mdcv = platf::vt::encode_mastering_display_color_volume(metadata); | |
| std::vector<std::uint8_t> expected_sei {137, 24}; | |
| expected_sei.insert(expected_sei.end(), mdcv.begin(), mdcv.end()); | |
| EXPECT_NE(std::search(unescaped.begin(), unescaped.end(), expected_sei.begin(), expected_sei.end()), unescaped.end()); |
Add #include <algorithm> to this file's standard include group for std::search. The mutation experiment and emitted-NAL inspection were run locally; this proposed assertion has not been compiled. Focused command: ./cmake-build-<name>/tests/test_sunshine --gtest_filter=VTEncoder.EncodesHevcMain10HdrFrameWithMasteringMetadata.
Review completed by Codex | Model: gpt-6.1-sol | Thinking: xhigh
| // frames, so report Rec. 2020 primaries and D65 white point (scaled by 50000). | ||
| metadata.displayPrimaries[0].x = 35400; // 0.708 | ||
| metadata.displayPrimaries[0].y = 14600; // 0.292 | ||
| metadata.displayPrimaries[1].x = 8500; // 0.170 |
There was a problem hiding this comment.
[P3] Apply the repository's pinned formatter to the new code
The locked clang-format 23.1.0 check fails on this new block and on the expected-byte array in tests/unit/platform/macos/test_vt_encoder.mm. The manual spacing before these comments is rejected, and the byte array is reformatted by the current configuration. Run uv run --locked lb-update-clang-format and inspect the resulting diff before committing.
For the assignments at lines 161–169, the formatter's output is:
metadata.displayPrimaries[0].x = 35400; // 0.708
metadata.displayPrimaries[0].y = 14600; // 0.292
metadata.displayPrimaries[1].x = 8500; // 0.170
metadata.displayPrimaries[1].y = 39850; // 0.797
metadata.displayPrimaries[2].x = 6550; // 0.131
metadata.displayPrimaries[2].y = 2300; // 0.046
metadata.whitePoint.x = 15635; // 0.3127
metadata.whitePoint.y = 16450; // 0.3290Verified with the pinned formatter's --dry-run --Werror check.
Review completed by Codex | Model: gpt-6.1-sol | Thinking: xhigh
| @@ -29,6 +31,18 @@ | |||
| namespace { | |||
| using namespace std::literals; | |||
|
|
|||
There was a problem hiding this comment.
[P3] Document the new byte-writing helpers
The newly added write_be16() and write_be32() functions have no Doxygen documentation. New functions need primary comments describing their purpose and parameters, including the writable size required for dst. Add this before write_be16() and the equivalent four-byte comment before write_be32():
| /** | |
| * @brief Write a 16-bit value in big-endian byte order. | |
| * | |
| * @param dst Destination with space for at least two bytes. | |
| * @param value Value to serialize. | |
| */ | |
| void write_be16(std::uint8_t *dst, std::uint16_t value) { |
The new sc_frame_source_t::hdr_state_changed() accessor in display.mm also needs a primary comment with its return semantics. Documentation-only suggestion; no runtime testing required.
Review completed by Codex | Model: gpt-6.1-sol | Thinking: xhigh
|
Thanks for the thorough review! Addressed all feedback in 7d98a66:
|
ReenigneArcher
left a comment
There was a problem hiding this comment.
The earlier SDR-first mismatch is fixed, and the hardware test now checks the encoded Main10, BT.2020, PQ, and HDR10 metadata. The previously reported formatting and documentation issues are addressed. I’m requesting changes for two remaining cases: an unrelated prefix SEI can hide missing HDR metadata, and another display initialization can consume the pending SDR fallback. Both reproduced locally.
On 7d98a66c, all 43 focused macOS tests passed, including both hardware VideoToolbox tests. Syntax checks with -Werror passed for arm64 and x86_64, and the locked clang-format check and diff whitespace check passed. The earlier SDR-first repro also passed on this head. The new fallback repro passed with the suggested guard.
GitHub reports the PR is behind master and mergeable. The GitHub Actions CI run requires maintainer action and has no completed build or test jobs. Local verification used an isolated focused harness, and did not include a full CMake build or live Moonlight streaming.
Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh
| break; | ||
| } | ||
| const int nal_type = (static_cast<uint8_t>(data[scan_offset]) >> 1) & 0x3f; | ||
| if (nal_type == 39) { |
There was a problem hiding this comment.
[P2] Check which HDR payloads are already present
A prefix SEI can carry unrelated messages, such as unregistered user data, or only one of the two HDR10 payloads. This early exit then suppresses every missing HDR payload, even when VideoToolbox provides it on the format description. I reproduced this with a sample containing a type 5 prefix-SEI message and a CLLI format extension. The resulting Annex B frame retained type 5 and dropped CLLI.
Scan the SEI messages by payload type and track MDCV (137) and CLLI (144) independently. Append each missing payload and preserve existing messages. Add this regression case in tests/unit/platform/macos/test_vt_encoder.mm, using the existing HEVC parameter sets to create format with a four-byte kCMFormatDescriptionExtension_ContentLightLevelInfo value of {0x03, 0xe8, 0x01, 0x90}:
bytes_t unrelated {0x4e, 0x01, 5, 17};
unrelated.insert(unrelated.end(), 17, 0x11);
unrelated.push_back(0x80);
const bytes_t expected_clli {0x4e, 0x01, 144, 4, 0x03, 0xe8, 0x01, 0x90, 0x80};
auto sample = make_sample(format.get(), avcc({unrelated, hevc_idr_slice}));
bytes_t out;
ASSERT_TRUE(platf::vt::append_annexb(sample.get(), true, out));
const auto nalus = split_annexb_nalus(out);
EXPECT_NE(std::find(nalus.begin(), nalus.end(), unrelated), nalus.end());
EXPECT_NE(std::find(nalus.begin(), nalus.end(), expected_clli), nalus.end());The second expectation fails on this head. If the fix merges payloads into the existing prefix NAL, assert both payloads after parsing that NAL instead. Also have the SDR encode test check for the absence of HDR payload types specifically, since an SDR frame may carry unrelated prefix SEI messages.
Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh
| if (sckit::backend_policy().take_stream_start_failure()) { | ||
| BOOST_LOG(info) << "SCCapture stream failed to start; using AVFoundation for this display"sv; | ||
| } else if ([SCCapture isAvailable]) { | ||
| const bool hdr_fallback {sckit::backend_policy().take_hdr_capture_failure()}; |
There was a problem hiding this comment.
[P2] Keep the SDR retry attached to the failed HDR capture
The process-wide one-shot flag is consumed by every ScreenCaptureKit display creation, including SDR and software capture. If another capture group creates an SDR display during an HDR restart, it can clear the flag and send the failing stream straight back into the rejected HDR configuration. I reproduced this by recording an HDR start failure, creating an SDR display, and then rebuilding the HDR display through the real factory using a fake HDR screen. The retry still enabled HDR.
This guard fixes the reproduced SDR case:
| const bool hdr_fallback {sckit::backend_policy().take_hdr_capture_failure()}; | |
| const bool hdr_fallback { | |
| hwdevice_type == platf::mem_type_e::videotoolbox && | |
| config.dynamicRange > 0 && | |
| sckit::backend_policy().take_hdr_capture_failure() | |
| }; |
Keep the retry state with the failing capture group across rebuilds so another HDR display or an encoder probe cannot take it either. Add a regression test that interleaves an unrelated display initialization between a failed HDR start and its rebuild. The suggested guard passed the local SDR interleaving test. Capture group scoping was not tested.
Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh
| } | ||
|
|
||
| private: | ||
| bool ensure_session(const video::sunshine_colorspace_t &colorspace) { |
There was a problem hiding this comment.
[P3] Document the new private conversion helpers
The previously flagged byte writers and HDR accessor now have Doxygen comments. The new converter adds undocumented helpers. Please document ensure_session() and ensure_pool(), including parameters and success conditions, and describe the ownership released by release_converted_buffer() and clear_retained_frames().
| bool ensure_session(const video::sunshine_colorspace_t &colorspace) { | |
| /** | |
| * @brief Create a pixel transfer session or update its destination colorimetry. | |
| * | |
| * @param colorspace Destination colorimetry for the converted frame. | |
| * @return True when a transfer session is available. | |
| */ | |
| bool ensure_session(const video::sunshine_colorspace_t &colorspace) { |
Documentation-only suggestion.
Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh
|
|
Addressed the remaining review feedback in d975646:
|
ReenigneArcher
left a comment
There was a problem hiding this comment.
The code changes in d975646c address my previous findings. The encoder now checks for the two HDR10 SEI payloads independently, and the SDR retry survives unrelated display creation. The requested Doxygen comments are in place. I found no remaining code changes to request.
Please update the PR description using the official template before merge. Keep the template headings and comments, move the existing summary under Description and the latest verification under Testing, and complete Type of Change, Checklist, and AI Usage as applicable. The AI Usage section is currently missing. Please check its box if AI tools were used while preparing the PR, or leave it unchecked if none were used. PR template · Contribution guide · AI disclosure policy
All 47 focused macOS tests passed on Apple Silicon, including both hardware VideoToolbox tests. The two display-factory reproductions passed as well. Arm64 and x86_64 syntax checks with -Werror, the locked clang-format check, and git diff --check passed. Local verification used a focused test harness and did not include a full CMake build or live Moonlight streaming. GitHub reports the PR is mergeable and behind master. The hosted CI run requires maintainer action and has no build or test jobs. CI run
Review completed by Codex | Model: gpt-6.2-sol | Thinking: xhigh
|
Updated the PR description to follow the official template (keeping all template headings/comments, moving the summary under Description and |



Description
Adds experimental HDR10 streaming support on macOS (Apple Silicon, macOS 15.0+) using
ScreenCaptureKitand nativeVideoToolboxHEVC Main10.Key Changes
src/platform/macos/display_helpers.{h,mm}):supports_hdr_capture()) and capture selection (should_capture_hdr()) cleanly so Apple Silicon (macOS 15.0+) builds support HDR while keepingx86_64builds clean under-DBUILD_WERROR=ON.NSScreen.maximumPotentialExtendedDynamicRangeColorComponentValue > 1.0inside@autoreleasepool(safe for non-ARC C++ worker threads) and populate Rec. 2020 + D65 static HDR10 metadata from EDR headroom.src/platform/macos/sc_capture.{h,mm}):SCCaptureDynamicRangeHDRCanonicalDisplay,kCGColorSpaceITUR_2100_PQ, andkCVImageBufferYCbCrMatrix_ITU_R_2020when HDR is active.hdrStartFailed) if HDR stream creation is rejected rather than silently capturing SDR frames underneath an HDR session.src/platform/macos/sc_capture_loop.{h,cpp},src/platform/macos/display.mm):hdr_metadatasnapshotting on actual HDR capture (should_capture_hdr) and guardsc_capturereconfiguration after capture starts so shared SDR/HDR client arrival orders stay consistent.sckit::backend_policy()per capture/probe thread (thread_local) and guard HDR retry consumption viatake_hdr_capture_failure_for(hwdevice_type, dynamic_range)so unrelated SDR/software display initializations, other capture groups, or concurrent encoder probes do not consume a pending HDR-to-SDR retry.capture_e::reiniton SDR <-> HDR toggles.src/platform/common.h,src/video.cpp,src/platform/macos/vt_encoder.{h,mm}):vt_encode_device_t::set_hdr_metadata()and pass display HDR10 metadata frommake_vt_encode_session().VTCompressionSession, and scan/append missing HDR10PREFIX_SEI_NUTpayloads (137MDCV /144CLLI) per payload type on HEVC IDR frames while preserving any existing prefix SEI messages.vt_pixel_converter_t(VTPixelTransferSessionRef+CVPixelBufferPoolRef) invt_encode_device::convert()so SDR clients joining an HDR capture receive hardware tone-mapped SDR frames.docs/getting_started.md,tests/unit/platform/macos/test_*.mm):docs/getting_started.md.backend_policySDR retry isolation, VideoToolbox HEVC Main10 BT.2020 PQ + HDR10 SEI output, and HDR-to-SDR session conversion.Screenshot
Issues Fixed or Closed
Roadmap Issues
Testing
Latest verification on
d975646c:arm64,cmake --build build -j --target test_sunshine sunshine): Succeeded../build/tests/test_sunshine --gtest_filter="*DisplayHelpers*:*SCCaptureLoop*:*VTEncoder*:*EncodeDevice*"): 50/50 passed (0 failures, 0 skipped), including:VTEncoder.EncodesHevcMain10HdrFrameWithMasteringMetadata(verifying 10-bit HEVC Main10, BT.2020, SMPTE ST 2084 PQ VUI tags, andPREFIX_SEI_NUTMDCV + CLLI payloads)VTEncoder.ConvertsHdrPqFrameForSdrClientSession(verifying 10-bit PQ input tone-mapped to 8-bit Rec. 709 without HDR SEI payloads)HevcIdrAppendsMissingHdrSeiAlongsideUnrelatedPrefixSei,HevcIdrAppendsOnlyMissingHdrPayloadAndAvoidsDuplicates) and interleaved/per-thread SDR fallback policy preservation (HdrFailureSurvivesInterleavedSdrAndSoftwareRequests,BackendPolicyIsScopedPerCaptureThread)-Werrorsyntax checks (-fsyntax-only -Werrorwith CMakecompile_commands.jsonflags on macOS 15.0 deployment target): Passed (rc=0) for botharm64andx86_64ondisplay.mm,display_helpers.mm,sc_capture_loop.cpp, andvt_encoder.mm, and onarm64fortest_display_helpers.mm,test_sc_capture_loop.mm, andtest_vt_encoder.mm..venv/bin/clang-format(23.1.0)--dry-run --Werroracross all 14 PR C++/ObjC++ files andgit diff --checkpassed.Color coding: HDR (Rec. 2020 + SMPTE 2084 PQ),Color depth: 10-bit,hevc_vt, andSCCapture stream configured: 2388x1668 @ 120 fps (HDR)during live HDR video playback. Live multi-client Moonlight streaming ond975646cand maintainer-approved GitHub Actions CI workflows were not run locally.Type of Change
Checklist
AI Usage
See our AI usage policy.
AI coding assistants were used to help draft and refine the ScreenCaptureKit/VideoToolbox HDR10 implementation, write unit/hardware regression tests, and address review feedback; all changes were compiled, formatted, and verified locally on Apple Silicon.