Skip to content

fix(macOS): keep cg device ids stable across display id changes - #332

Open
dave-atx wants to merge 3 commits into
LizardByte:masterfrom
dave-atx:fix/macos-stable-cg-device-id
Open

dave-atx wants to merge 3 commits into
LizardByte:masterfrom
dave-atx:fix/macos-stable-cg-device-id

Conversation

@dave-atx

@dave-atx dave-atx commented Nov 22, 2026 •

Copy link
Copy Markdown

Description

On Apple Silicon, MacApiLayer::getDeviceId() falls through to the macos-cg-* id for most displays: there are no IODisplayConnect services, so neither the EDID nor the IOKit metadata path matches, and every virtual display ends up there too. That id hashes the CGDirectDisplayID and unit number along with vendor, model and serial (mac_api_layer.cpp#L591-L597). macOS hands out a new display id when a display reconnects and every time a virtual display is created, so the device id changes with it and a saved id stops matching. With a CGVirtualDisplay recreated per stream I saw display ids 9, 10, ... 30 over one day, each with a different device id.

The display id and unit number are now left out of the hash only when vendor, model and serial identify the display on their own:

Otherwise the identity is the same as on master, so identical panels sharing a serial are still both enumerated and each id resolves to its own display. The rule lives in mac_utils::makeCgDeviceIdentity() so it can be tested without real displays.

Because the form depends on what else is online, a display that stays connected switches forms when a twin is plugged in or unplugged. Lookup handles that: getDisplayId() matches the current id first, then the display's other form (getDeviceIdAlias()), but only if exactly one online display has it. So an id saved while a twin was online still resolves after the twin is unplugged, and a serial-only id saved before a twin was plugged in matches both and is left unresolved (with a warning) rather than handed to one of them.

Upgrade note: a saved macos-cg-* id for a display with a usable, unique serial changes once. The old id no longer resolves; in Sunshine, map_output_name() then returns an empty name and capture falls back to the main display without a warning, so the display has to be picked again from Sunshine's display list. Numeric output_name values (what Sunshine's docs tell macOS users to set) don't go through this and aren't affected. Displays without a usable serial keep their ids.

SunshineStream/Sunshine#6023 works around the same instability by accepting display UUIDs in output_name. This complements it rather than replacing it: zero-serial displays (some virtual display tools create those) still get a new id on every reconnect.

Screenshot

N/A

Issues Fixed or Closed

Roadmap Issues

Testing

  • MacApiUtils.IsUsableCgSerial: 0 and 0xFFFFFFFF are rejected.

  • MacApiUtils.MakeCgDeviceIdentity: a unique serial gives the same identity across display id / unit changes; no usable serial, or a second online display with the same vendor / model / serial, keeps the display id and unit; once the twin is gone the stable identity comes back.

  • MacDisplayDeviceMocked.EnumAvailableDevices_IdenticalSerialsStayDistinct: two displays with identical serials go through enumAvailableDevices() and getDisplayName(); both are listed and each id resolves to its own display. With the duplicate check removed, this test and MakeCgDeviceIdentity fail (one device listed).

  • MacApiUtils.MakeCgDeviceIdentityAlias: after a twin is plugged in, both displays have the old serial-only identity as their alias; after it's unplugged, the remaining display's alias is the identity it had while the twin was online, and only it has it.

  • MacDisplayDeviceMocked.GetDisplayName_ResolvesUniqueAlias / GetDisplayName_AmbiguousAliasUnresolved, and SetDisplayModes_InactiveDisplay now also covers an alias belonging to an inactive display. All three fail with the previous getDisplayId().

  • test_libdisplaydevice: all 185 tests pass (macOS 27.2.1, M3 Pro).

  • Hotplug with real CGVirtualDisplays: A's id saved from enumAvailableDevices(), then resolved with getDisplayName() after the change. WindowServer won't create a second virtual display with the same vendor / product / serial, so B is created with serial + 1 and the test reports it as A's serial to the library; hotplug, display ids and unit numbers are real.

    A saved Then 9ebc7d9 this branch
    alone B plugged in unresolved unresolved, with a warning
    with B online B unplugged unresolved A
    with B online A unplugged unresolved unresolved
    alone A reconnects (new display id) A A

    A kept its display id and unit number when B was unplugged, which is why the second row resolves.

  • Real displays, getDeviceId() printed from master and from this branch on the same Mac (all three have nonzero, unique serials):

    Display Serial master this branch
    LG external 492262 macos-cg-8bc5173d321a7649 macos-cg-ef298961686314ee
    Built-in 4251086178 macos-cg-f6d2a85c90531058 macos-cg-818c4426e52a57eb
    CGVirtualDisplay (display id 24) 1398099505 macos-cg-414eb810b4214452 macos-cg-8362b26f6b4599bd

    The virtual display's id on this branch is the same one it had at display ids 9 - 30 earlier.

  • I don't have two identical panels, so the duplicate-serial case is covered by the mocked tests and the virtual-display test above.

  • Formatted with clang-format 23.1.0 (the version pinned in lizardbyte-common).

Type of Change

  • feat: New feature (non-breaking change which adds functionality)
  • fix: Bug fix (non-breaking change which fixes an issue)
  • docs: Documentation only changes
  • style: Changes that do not affect the meaning of the code (white-space, formatting, missing semicolons, etc.)
  • refactor: Code change that neither fixes a bug nor adds a feature
  • perf: Code change that improves performance
  • test: Adding missing tests or correcting existing tests
  • build: Changes that affect the build system or external dependencies
  • ci: Changes to CI configuration files and scripts
  • chore: Other changes that don't modify src or test files
  • revert: Reverts a previous commit
  • BREAKING CHANGE: Introduces a breaking change (can be combined with any type above)

Checklist

  • Code follows the style guidelines of this project
  • Code has been self-reviewed
  • Code has been commented, particularly in hard-to-understand areas
  • Code docstring/documentation-blocks for new or existing methods/components have been added or updated
  • Tests have been added or updated for new or modified functionality, including regression tests for bug fixes

AI Usage

See our AI usage policy.

  • AI tools were used while preparing this PR

On Apple Silicon there are no IODisplayConnect services, so displays without an EDID (most of them, and every virtual display) get a macos-cg-* id. Its hash included the CGDirectDisplayID and unit number, which macOS reassigns when a display reconnects or a virtual display is recreated, so the device id changed with them. Leave both out when the display reports a nonzero serial; vendor, model and serial identify it.
@CLAassistant

CLAassistant commented Nov 22, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Copy link
Copy Markdown
Member

I’d hold this revision until the CoreGraphics fallback handles ambiguous serials. makeCgDeviceIdentity() drops the unit and display ID for every nonzero serial. If two online fallback displays report the same vendor/model/serial, they now get one ID. Enumeration skips the second, and lookup returns the first match. Also, Apple documents 0xFFFFFFFF as an exception value, not a usable serial. I compiled the identity helper in isolation to confirm both collision cases; I haven’t reproduced this on a Mac.

Could you treat both 0 and 0xFFFFFFFF as unavailable and keep simultaneously connected displays distinguishable when a candidate identity is duplicated? A mocked enumeration and lookup test with two identical serials would catch both the hidden display and the wrong match. Please also verify what happens to an existing saved macos-cg-* ID after upgrading, and document the reselection step if the old ID won’t resolve.

This leaves zero-serial reconnects unchanged, so I wouldn’t consider it a replacement for Sunshine #6023 without a zero-serial virtual-display reconnect test.

Review completed by Codex | Model: unavailable | Thinking: unavailable

Treat 0xFFFFFFFF, which Apple documents as an exception value, like 0: neither identifies a display. When another online display reports the same vendor, model and serial, keep the display id and unit number in the identity as before, so both displays are still enumerated and each id resolves to its own display. Only a display with a usable, unique serial gets the stable id.
@dave-atx

Copy link
Copy Markdown
Author

Thanks, both are right. Pushed 9ebc7d9:

  • 0 and 0xFFFFFFFF both count as no serial now (mac_utils::isUsableCgSerial()).
  • The display id and unit are only left out when the serial is usable and no other online display reports the same vendor / model / serial. Identical panels keep master's identity, so both are enumerated and each id resolves to its own display.
  • New mocked test MacDisplayDeviceMocked.EnumAvailableDevices_IdenticalSerialsStayDistinct runs two identical-serial displays through enumAvailableDevices() and getDisplayName(). With the duplicate check removed it fails (one device listed), and so does the extended MacApiUtils.MakeCgDeviceIdentity.

On upgrades, I printed getDeviceId() from master and from this branch on my Mac (built-in panel, an LG, and a CGVirtualDisplay, all with unique nonzero serials). All three ids change once, e.g. macos-cg-8bc5173d321a7649 → macos-cg-ef298961686314ee for the LG. The old id then doesn't resolve: Sunshine's map_output_name() gets an empty name and captures the main display without a warning, so the display has to be picked again from the list. Numeric output_name values, which Sunshine's docs tell macOS users to set, aren't affected. The table and the reselection step are in the description now.

Agreed on #6023. Zero-serial displays still change id on reconnect, so this complements it rather than replacing it.

Copy link
Copy Markdown
Member

Thanks, Dave. 9ebc7d9 addresses the exception serial and keeps both displays distinguishable when they’re online together. There’s a separate saved-selection issue after the one-time upgrade: the same display can change ID even though it hasn’t disconnected. If A is saved while it’s the only display with that serial tuple, connecting matching B makes A’s serial-only ID stop resolving. If A is saved while both are online, unplugging B makes A’s qualified ID stop resolving instead. I verified both transitions by compiling the identity helper in isolation, not on a Mac.

In Sunshine, the unresolved ID maps to an empty selector, so it can capture a different display without warning. Before updating Sunshine’s pin, could we test saving A in both configurations, then plugging or unplugging B while A stays connected? The selection should either keep resolving to A or be reported as unresolved; a serial-only ID should not be assigned arbitrarily to one of two matches. At minimum Sunshine should warn before falling back from an explicit selection. I’d keep Sunshine #6023 separate for the zero-serial UUID test.

Review completed by Codex | Model: unavailable | Thinking: unavailable

…lugged

Whether a macos-cg-* id includes the display id and unit number depends on whether another online display reports the same vendor, model and serial, so a display that stays connected switches between the two forms when such a display is plugged in or unplugged, and an id saved under the other form stopped resolving.

getDisplayId() still matches the current id first. If nothing matches, it compares against each online display's other form (getDeviceIdAlias()) and accepts it only if exactly one online display has it. A serial-only id saved before an identical display was plugged in matches both, so it is logged and left unresolved rather than handed to one of them.

Verified with CGVirtualDisplay hotplug on macOS 27.2.1: an id saved while a twin was online now resolves after the twin is unplugged, an id saved alone is unresolved (with a warning) once a twin is plugged in, and an id is never resolved to the other display.
@dave-atx

Copy link
Copy Markdown
Author

Thanks, you're right. The description already said a remaining twin "moves to the stable id once the twin is gone," and I didn't follow that through to what it does to a saved id.

I reproduced both transitions with real CGVirtualDisplay hotplug on my Mac (M3 Pro, macOS 27.2.1). WindowServer refuses to create a second virtual display with the same vendor / product / serial, so the harness creates B with serial + 1 and reports it as A's serial to the library; hotplug, display ids and unit numbers are all real. Saving A's id from enumAvailableDevices(), then resolving it with getDisplayName():

A saved Then 9ebc7d9 58d1e8b
alone B plugged in unresolved unresolved, with a warning
with B online B unplugged unresolved A
with B online A unplugged unresolved unresolved
alone A reconnects (new display id) A A

58d1e8b keeps the ids as they are and changes the lookup. getDisplayId() still matches the current id first. If nothing matches, it compares against each online display's other form of the id (getDeviceIdAlias(): serial-only when a twin is online, display id + unit when it isn't) and accepts it only if exactly one online display has it. With two it logs a warning and returns nothing, so a serial-only id is never handed to one of two matches. When B was unplugged, A kept its display id and unit, which is why the second row resolves.

New tests: MacApiUtils.MakeCgDeviceIdentityAlias covers both transitions on the identity text; MacDisplayDeviceMocked.GetDisplayName_ResolvesUniqueAlias / GetDisplayName_AmbiguousAliasUnresolved cover the lookup, and both fail with the old getDisplayId(). All 185 tests pass.

Agreed on warning in Sunshine before falling back from an explicit output_name; I'll send that as its own small PR. And agreed on keeping #6023 separate for the zero-serial case.

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
1 New issue
8.5% Duplication on New Code (required ≤ 2%)
2 Duplicated Blocks on New Code (required ≤ 0)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

This branch has not been deployed

No deployments
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.

3 participants