From e26a142217a8912e2dc0664ba9c43e226f77da22 Mon Sep 17 00:00:00 2001 From: Evan Hu Date: Tue, 1 Dec 2026 10:22:02 +0900 Subject: [PATCH] fix(macos): stop per-frame environment refreshes and camera probes Probe the camera once and follow AVCaptureDevice connect and disconnect notifications instead of running AVFoundation device discovery twice on every environment refresh. Coalesce the refreshes that display parameter, screen, screen profile and backing scale notifications request in one run loop turn, and rate-limit environments that change only displays' HDR headroom to four a second, with a trailing refresh that publishes the settled value. Fixes #2813 --- changelog.d/macos-env-refresh.md | 3 + docs/public/en/services.md | 2 +- internal/platform/macos/camera.go | 88 +++++++++++++++ internal/platform/macos/camera_test.go | 69 ++++++++++++ internal/platform/macos/macos.go | 51 ++++++++- internal/platform/macos/refresh.go | 71 ++++++++++++ internal/platform/macos/refresh_test.go | 137 ++++++++++++++++++++++++ 7 files changed, 415 insertions(+), 6 deletions(-) create mode 100644 changelog.d/macos-env-refresh.md create mode 100644 internal/platform/macos/camera.go create mode 100644 internal/platform/macos/camera_test.go create mode 100644 internal/platform/macos/refresh.go create mode 100644 internal/platform/macos/refresh_test.go diff --git a/changelog.d/macos-env-refresh.md b/changelog.d/macos-env-refresh.md new file mode 100644 index 000000000..ce6938252 --- /dev/null +++ b/changelog.d/macos-env-refresh.md @@ -0,0 +1,3 @@ +### Fixed + +- Stop macOS apps re-rendering on every frame of a display brightness ramp and asking AVFoundation for the camera on every environment refresh: the camera is probed once and followed through device connect and disconnect notifications, display and backing-scale notifications arriving in one run loop turn refresh once, and a change of `HDRHeadroom` alone updates the environment at most four times a second, ending with the settled value (#2813 by @houko). diff --git a/docs/public/en/services.md b/docs/public/en/services.md index 7d20ca542..2164424bc 100644 --- a/docs/public/en/services.md +++ b/docs/public/en/services.md @@ -596,7 +596,7 @@ Use `audio.SetSoundLimits(cx, audio.SoundLimits{MaxSounds: 200, MaxDuration: 20 ## Displays -`cx.Env().Display()` returns the window's current `core.DisplayInfo` and updates bindings when the window moves to another display or display settings change. `cx.Env().Displays()` lists the displays the platform reports. `RefreshRate` and `MaxRefreshRate` are in Hz, with zero for an unavailable rate. `HDR` and `HDRSupported` report active and capable HDR output, with `HDRHeadroom` (peak relative to SDR white), `SDRWhiteLevel` (nits) and `MaxLuminance` (nits) where available on macOS, iOS, Windows and Wayland Linux. iOS reports the panel's maximum. HarmonyOS reports the window's display, its current rate and its highest supported rate. The web reports the current screen and marks its frame callback measurement with `RefreshRateEstimated`. In tests, set `Displays` and `DisplayID` through `nsgotest.Environment`. +`cx.Env().Display()` returns the window's current `core.DisplayInfo` and updates bindings when the window moves to another display or display settings change. `cx.Env().Displays()` lists the displays the platform reports. `RefreshRate` and `MaxRefreshRate` are in Hz, with zero for an unavailable rate. `HDR` and `HDRSupported` report active and capable HDR output, with `HDRHeadroom` (peak relative to SDR white), `SDRWhiteLevel` (nits) and `MaxLuminance` (nits) where available on macOS, iOS, Windows and Wayland Linux. iOS reports the panel's maximum. On macOS, a change of `HDRHeadroom` alone, as during a brightness ramp, updates the environment at most four times a second and ends with the value the display settles at. HarmonyOS reports the window's display, its current rate and its highest supported rate. The web reports the current screen and marks its frame callback measurement with `RefreshRateEstimated`. In tests, set `Displays` and `DisplayID` through `nsgotest.Environment`. ## Speaking text diff --git a/internal/platform/macos/camera.go b/internal/platform/macos/camera.go new file mode 100644 index 000000000..8bb379a8c --- /dev/null +++ b/internal/platform/macos/camera.go @@ -0,0 +1,88 @@ +//go:build darwin && !ios + +package macos + +import ( + "sync" + + "github.com/ebitengine/purego/objc" + + "github.com/nsgo-dev/nsgo/internal/platform/apple" +) + +// cameraProbe asks AVFoundation for the default video device, which runs its device discovery. +var cameraProbe = func() bool { return apple.ScanCamera() != 0 } + +// camera is Environment.Camera and ScanCode, which every environment refresh reads. +var camera = &cameraWatch{} + +// cameraWatch keeps whether the Mac has a camera: probed once, on first use, and again only when AVFoundation reports a device connected or disconnected, as device discovery is slow and logs on every call, and a refresh can run every frame (#2813). +type cameraWatch struct { + mu sync.Mutex + started bool + available bool + changed []func() + // probe and observe are cameraProbe and observeCameraDevices unless a test sets them; observe calls its function on the main thread whenever a device comes or goes. + probe func() bool + observe func(func()) +} + +// Available reports whether a camera is available. +func (c *cameraWatch) Available() bool { + c.mu.Lock() + if c.started { + defer c.mu.Unlock() + return c.available + } + c.started = true + observe := c.observe + if observe == nil { + observe = observeCameraDevices + } + c.mu.Unlock() + // Observed before the probe, so a device that comes in between is not missed. + observe(c.update) + available := c.probeNow() + c.mu.Lock() + defer c.mu.Unlock() + c.available = available + return available +} + +// OnChange calls fn on the main thread whenever the camera's availability changes. +func (c *cameraWatch) OnChange(fn func()) { + c.mu.Lock() + defer c.mu.Unlock() + c.changed = append(c.changed, fn) +} + +// update probes again after a device came or went, and tells the listeners when availability changed. +func (c *cameraWatch) update() { + available := c.probeNow() + c.mu.Lock() + changed := available != c.available + c.available = available + listeners := c.changed + c.mu.Unlock() + if changed { + for _, fn := range listeners { + fn() + } + } +} + +func (c *cameraWatch) probeNow() bool { + if c.probe != nil { + return c.probe() + } + return cameraProbe() +} + +// observeCameraDevices calls fn on the main thread when AVFoundation reports a capture device connected or disconnected, for the app's life. +func observeCameraDevices(fn func()) { + const avFoundation = "/System/Library/Frameworks/AVFoundation.framework/AVFoundation" + center := objc.ID(apple.Class("NSNotificationCenter")).Send(sel("defaultCenter")) + for _, name := range []string{"AVCaptureDeviceWasConnectedNotification", "AVCaptureDeviceWasDisconnectedNotification"} { + apple.Observe(center, apple.Global(avFoundation, name), func(objc.ID) { fn() }) + } +} diff --git a/internal/platform/macos/camera_test.go b/internal/platform/macos/camera_test.go new file mode 100644 index 000000000..a4b7faf0f --- /dev/null +++ b/internal/platform/macos/camera_test.go @@ -0,0 +1,69 @@ +//go:build darwin && !ios + +package macos + +import ( + "testing" + + "github.com/ebitengine/purego/objc" + + "github.com/nsgo-dev/nsgo/internal/platform/apple" +) + +// TestEnvironmentDoesNotProbeTheCameraPerCall checks that environment reads the camera's availability from what was probed once, not from AVFoundation's device discovery on every refresh (#2813). +func TestEnvironmentDoesNotProbeTheCameraPerCall(t *testing.T) { + probes := 0 + savedProbe, savedWatch := cameraProbe, camera + cameraProbe = func() bool { probes++; return true } + camera = &cameraWatch{observe: func(func()) {}} + defer func() { cameraProbe, camera = savedProbe, savedWatch }() + onMain(func() { + loadAppKit() + pool := objc.ID(apple.Class("NSAutoreleasePool")).Send(selNew) + defer pool.Send(sel("drain")) + s := newSurface(Options{Width: 160, Height: 100}, false) + defer func() { + delete(surfaces, s) + delete(views, s.native) + s.native.Send(selRelease) + }() + for range 10 { + s.environment() + } + }) + if probes != 1 { + t.Errorf("10 environments probed the camera %d times, want once", probes) + } +} + +// TestCameraWatchProbesOnceAndFollowsDevices checks that the camera's availability is probed on first use and again only when AVFoundation reports a device connected or disconnected, and that only a change tells the listeners. +func TestCameraWatchProbesOnceAndFollowsDevices(t *testing.T) { + probes, connected, observed := 0, true, 0 + var update func() + c := &cameraWatch{ + probe: func() bool { probes++; return connected }, + observe: func(fn func()) { observed++; update = fn }, + } + changes := 0 + c.OnChange(func() { changes++ }) + for range 5 { + if !c.Available() { + t.Fatal("camera unavailable, want available") + } + } + if probes != 1 || observed != 1 { + t.Fatalf("5 reads probed %d times and observed %d times, want once each", probes, observed) + } + update() // a device connected; the default one is unchanged + if changes != 0 || probes != 2 { + t.Fatalf("unchanged device: %d changes, %d probes, want 0 and 2", changes, probes) + } + connected = false + update() + if c.Available() || changes != 1 { + t.Fatalf("disconnected: available %v after %d changes, want false after 1", c.Available(), changes) + } + if probes != 3 { + t.Fatalf("probed %d times, want 3", probes) + } +} diff --git a/internal/platform/macos/macos.go b/internal/platform/macos/macos.go index e420226fb..7c2e2475c 100644 --- a/internal/platform/macos/macos.go +++ b/internal/platform/macos/macos.go @@ -263,6 +263,9 @@ type surface struct { // stops end the surface's observations as it closes. stops []func() closed bool + // refreshes coalesces the refreshes notifications request; headroom rate-limits the environments that change only displays' HDR headroom (refresh.go). + refreshes coalescer + headroom headroomGate // pointer is where the window takes the pointer (windowpointer.go). pointer windowPointer // appearance is the one the app forces, host the one an embedding @@ -555,12 +558,19 @@ func loadAppKit() { v.surface.refresh() } } + // A display's brightness ramp or scale change can call it on every frame. + requestRefresh := func(self objc.ID, cmd objc.SEL) { + apple.Super(self, cmd) + if v := views[self]; v != nil { + v.surface.requestRefresh() + } + } classSurface = register("NsgoSurface", nsView, nil, append(common, objc.MethodDef{Cmd: sel("setFrameSize:"), Fn: surfaceSetFrameSize}, objc.MethodDef{Cmd: sel("viewDidMoveToWindow"), Fn: surfaceMoved}, objc.MethodDef{Cmd: selApply, Fn: surfaceApply}, objc.MethodDef{Cmd: sel("viewDidChangeEffectiveAppearance"), Fn: refresh}, - objc.MethodDef{Cmd: sel("viewDidChangeBackingProperties"), Fn: refresh}, + objc.MethodDef{Cmd: sel("viewDidChangeBackingProperties"), Fn: requestRefresh}, objc.MethodDef{Cmd: sel("acceptsFirstResponder"), Fn: func(objc.ID, objc.SEL) bool { return true }}, // It holds selections, but Tab passes it by. objc.MethodDef{Cmd: sel("canBecomeKeyView"), Fn: func(objc.ID, objc.SEL) bool { return false }}, @@ -1250,6 +1260,7 @@ func (s *surface) environment() driver.Environment { thermal, lowPower := apple.ProcessPower() appearance := apple.GoString(s.native.Send(sel("effectiveAppearance")).Send(sel("name"))) displays, displayID := displaySnapshot(s.window.Send(sel("screen"))) + hasCamera := camera.Available() return driver.Environment{ DeviceName: deviceName, DeviceModel: deviceModel, @@ -1261,8 +1272,8 @@ func (s *surface) environment() driver.Environment { ScreenColor: true, DiscoverServices: true, - ScanCode: apple.ScanCamera() != 0, - Camera: apple.ScanCamera() != 0, + ScanCode: hasCamera, + Camera: hasCamera, Speech: apple.SpeechAvailable(), Speak: apple.SpeakAvailable(), Audio: apple.AudioAvailable(), @@ -1383,6 +1394,7 @@ func (s *surface) refresh() { if s == nil || s.engine == nil || s.settingPanelFrame { return } + s.refreshes.done() if lockedPointer.owner == s && !s.canHoldPointer() { s.releasePointer(true) } @@ -1390,6 +1402,15 @@ func (s *surface) refresh() { env := s.environment() s.reportFrameWindow(env) if !env.Equal(s.env) { + if wait, schedule := s.headroom.hold(s.env, env, time.Now()); wait > 0 { + if schedule { + s.later(wait, func() { + s.headroom.fired() + s.refresh() + }) + } + return + } rescale := env.PixelRatio != s.env.PixelRatio redock := s.dock.Edge != driver.WindowPlaceDefault && !slices.Equal(env.Displays, s.env.Displays) s.env = env @@ -1403,6 +1424,15 @@ func (s *surface) refresh() { } } +// requestRefresh refreshes the surface on the main queue's next turn, once however many requests arrive before then. Notifications that can come in storms request it rather than refresh at once: a display's change of parameters, profile or backing scale, and a camera coming or going. +func (s *surface) requestRefresh() { + s.refreshes.request(apple.OnMain, func() { + if !s.closed { + s.refresh() + } + }) +} + func (s *surface) reportFrameWindow(env driver.Environment) { s.devFrame.record(env) visible := s.window != 0 && s.kind != driver.SurfaceTrayIcon && env.Lifecycle != driver.LifecycleBackground @@ -1449,7 +1479,11 @@ func (s *surface) observe() { case "NSWindowDidEnterFullScreenNotification", "NSWindowDidExitFullScreenNotification": s.fullScreenEntering = false } - s.refresh() + if name == "NSWindowDidChangeScreenNotification" || name == "NSWindowDidChangeScreenProfileNotification" { + s.requestRefresh() + } else { + s.refresh() + } if name == "NSWindowDidEnterFullScreenNotification" || name == "NSWindowDidExitFullScreenNotification" { // AppKit lays the bar out again as it leaves full screen, after the notification. A surface closed by then may have let its window go. apple.OnMain(func() { @@ -1524,9 +1558,16 @@ func observeApp() { }) for _, name := range []string{"NSApplicationDidBecomeActiveNotification", "NSApplicationDidResignActiveNotification", "NSApplicationDidHideNotification", "NSApplicationDidUnhideNotification", - "NSApplicationDidChangeOcclusionStateNotification", "NSApplicationDidChangeScreenParametersNotification"} { + "NSApplicationDidChangeOcclusionStateNotification"} { apple.Observe(center, apple.Global(appKitPath, name), refresh) } + requestRefresh := func() { + for s := range surfaces { + s.requestRefresh() + } + } + apple.Observe(center, apple.Global(appKitPath, "NSApplicationDidChangeScreenParametersNotification"), func(objc.ID) { requestRefresh() }) + camera.OnChange(requestRefresh) appObserver = objc.ID(classObserver).Send(selNew) ws.Send(sel("addObserver:forKeyPath:options:context:"), appObserver, apple.NSString("voiceOverEnabled"), uint(0), uintptr(0)) } diff --git a/internal/platform/macos/refresh.go b/internal/platform/macos/refresh.go new file mode 100644 index 000000000..6efc95162 --- /dev/null +++ b/internal/platform/macos/refresh.go @@ -0,0 +1,71 @@ +//go:build darwin && !ios + +package macos + +import ( + "slices" + "time" + + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// coalescer runs a refresh once per turn of the main queue however many notifications request it in that turn, as a display change can post several of them for each window at once (#2813). +type coalescer struct { + pending bool +} + +// request has post run run on the main queue's next turn, unless a request is already waiting or a direct refresh satisfies it first (done). +func (c *coalescer) request(post func(func()), run func()) { + if c.pending { + return + } + c.pending = true + post(func() { + if c.pending { + c.pending = false + run() + } + }) +} + +// done tells the coalescer that a refresh ran, which satisfies a request still waiting. +func (c *coalescer) done() { c.pending = false } + +// headroomInterval is the least time between two environments that change only displays' HDR headroom. +const headroomInterval = 250 * time.Millisecond + +// headroomGate rate-limits environments that change only displays' HDR headroom. The headroom follows the panel's brightness and steps on every frame of a brightness ramp, and each new environment updates every view that reads the environment (#2813). A held change is published by a refresh scheduled for when the interval ends, so the value the display settles at is always published. +type headroomGate struct { + last time.Time // when the last headroom change was published + pending bool // a refresh is scheduled for when the interval ends +} + +// hold reports how long refresh should keep next from the engine, which already has prev: zero unless next changes only displays' headroom within headroomInterval of the last such change. schedule is whether the caller must refresh again after wait, false while a refresh is already scheduled. +func (g *headroomGate) hold(prev, next driver.Environment, now time.Time) (wait time.Duration, schedule bool) { + if !headroomOnly(prev, next) { + return 0, false + } + if wait = g.last.Add(headroomInterval).Sub(now); wait <= 0 { + g.last = now + return 0, false + } + schedule = !g.pending + g.pending = true + return wait, schedule +} + +// fired tells the gate that the refresh it had scheduled runs. +func (g *headroomGate) fired() { g.pending = false } + +// headroomOnly reports whether next differs from prev in displays' HDR headroom and nothing else, the same displays staying in HDR or out of it. +func headroomOnly(prev, next driver.Environment) bool { + if len(prev.Displays) != len(next.Displays) || prev.Equal(next) { + return false + } + same := next + same.Displays = slices.Clone(next.Displays) + for i := range same.Displays { + same.Displays[i].HDRHeadroom = prev.Displays[i].HDRHeadroom + } + return same.Equal(prev) +} diff --git a/internal/platform/macos/refresh_test.go b/internal/platform/macos/refresh_test.go new file mode 100644 index 000000000..320af6134 --- /dev/null +++ b/internal/platform/macos/refresh_test.go @@ -0,0 +1,137 @@ +//go:build darwin && !ios + +package macos + +import ( + "testing" + "time" + + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// TestCoalescerRunsOncePerTurn checks that requests arriving before the main queue's next turn run the refresh once, and that a refresh run directly in between satisfies them. +func TestCoalescerRunsOncePerTurn(t *testing.T) { + var queue []func() + post := func(fn func()) { queue = append(queue, fn) } + turn := func() { + fns := queue + queue = nil + for _, fn := range fns { + fn() + } + } + runs := 0 + run := func() { runs++ } + var c coalescer + for range 120 { + c.request(post, run) + } + if len(queue) != 1 { + t.Fatalf("120 requests posted %d turns, want 1", len(queue)) + } + turn() + if runs != 1 { + t.Fatalf("ran %d times, want 1", runs) + } + c.request(post, run) + c.request(post, run) + c.done() // a direct refresh ran before the turn + turn() + if runs != 1 { + t.Fatalf("ran %d times after a direct refresh satisfied the requests, want still 1", runs) + } + c.request(post, run) + turn() + if runs != 2 { + t.Fatalf("ran %d times, want 2", runs) + } +} + +func headroomEnv(headroom ...float32) driver.Environment { + env := driver.Environment{OS: driver.OSMacOS, PixelRatio: 2, DisplayID: "1"} + for i, h := range headroom { + env.Displays = append(env.Displays, driver.DisplayInfo{ID: string(rune('1' + i)), Scale: 2, HDRSupported: true, HDR: h > 1, HDRHeadroom: h, + Frame: driver.Bounds{Size: driver.Size{Width: 1512, Height: 982}}}) + } + return env +} + +// TestHeadroomOnlyChange checks which environment changes count as a brightness step: a change of displays' headroom alone, never one that changes anything else as well. +func TestHeadroomOnlyChange(t *testing.T) { + prev := headroomEnv(2, 1) + if headroomOnly(prev, prev) { + t.Error("equal environments count as a headroom change") + } + if !headroomOnly(prev, headroomEnv(2.1, 1)) { + t.Error("a headroom step does not count as a headroom change") + } + moved := headroomEnv(2.1, 1) + moved.Displays[0].Frame.Size.Width = 1800 + if headroomOnly(prev, moved) { + t.Error("a resized display counts as a headroom change") + } + dark := headroomEnv(2.1, 1) + dark.Dark = true + if headroomOnly(prev, dark) { + t.Error("an appearance change counts as a headroom change") + } + if headroomOnly(prev, headroomEnv(2)) { + t.Error("a removed display counts as a headroom change") + } + if headroomOnly(prev, headroomEnv(1, 1)) { + t.Error("leaving HDR counts as a headroom change") + } +} + +// TestHeadroomGateLimitsARamp checks that a brightness ramp stepping the headroom every frame at 120 Hz for a second publishes a few environments rather than one per frame, and that the value it settles at is published. +func TestHeadroomGateLimitsARamp(t *testing.T) { + var g headroomGate + start := time.Unix(1000, 0) + published := headroomEnv(1.5) + publishes := 0 + var trailing time.Time // when the scheduled refresh runs; zero when none is + refresh := func(now time.Time, next driver.Environment) { + if next.Equal(published) { + return + } + wait, schedule := g.hold(published, next, now) + if wait > 0 { + if schedule { + trailing = now.Add(wait) + } + return + } + published = next + publishes++ + } + const frames = 120 + var last driver.Environment + for i := range frames { + now := start.Add(time.Duration(i) * time.Second / frames) + if !trailing.IsZero() && !now.Before(trailing) { + trailing = time.Time{} + g.fired() + refresh(now, last) + } + last = headroomEnv(1.5 + float32(i+1)/frames*2.5) + refresh(now, last) + } + if publishes > 1+int(time.Second/headroomInterval) { + t.Errorf("a 1 s ramp at 120 Hz published %d environments, want at most %d", publishes, 1+int(time.Second/headroomInterval)) + } + if trailing.IsZero() { + t.Fatal("no refresh scheduled for the settled value") + } + g.fired() + refresh(trailing, last) + if !published.Equal(last) { + t.Errorf("settled at headroom %g, published %g", last.Displays[0].HDRHeadroom, published.Displays[0].HDRHeadroom) + } + + // Any other change goes through at once. + dark := last + dark.Dark = true + if wait, _ := g.hold(last, dark, trailing.Add(time.Millisecond)); wait != 0 { + t.Errorf("an appearance change waits %v, want none", wait) + } +}