Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Camera and microphone use, Meet's automatic picture-in-picture and page media actions the way Arc gets them

Victor9344185fe9cb
diff --git a/Sources/Cra/Services/BrowserManager.swift b/Sources/Cra/Services/BrowserManager.swift
index bc0ea26..ce3c76c 100644
--- a/Sources/Cra/Services/BrowserManager.swift
+++ b/Sources/Cra/Services/BrowserManager.swift
@@ -671,43 +671,39 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
/// the key press that lends the page activation raced the page going
/// hidden, and PiP sometimes never opened.
///
- /// A page that registered its own `enterpictureinpicture` media session handler is asked
- /// first, the way Chrome's AutoPictureInPictureTabHelper asks it when such a tab is hidden.
- /// That is how Google Meet's "Automatic picture-in-picture" works: its handler opens a
- /// Document Picture in Picture window of the call, which no `<video>` request can (GitHub
- /// #198). Chrome also wants the camera or microphone in use or sound playing, but CEF doesn't
- /// report capture for Chrome-style pages (Chrome's own media UI takes the request), so the
- /// handler, which a site registers to opt in, is the condition. The page is asked whether it
- /// has one without a user gesture; only a page that does gets one, to run it. `video: false`
- /// skips the video request (a silent page when the window goes out of sight).
+ /// A call goes first through Chrome's own automatic Picture in Picture
+ /// (AutoPictureInPictureTabHelper, which Arc uses for Google Meet), driven by Cra's tab switch
+ /// since CEF has no tab strip for it to watch (`Cra.autoPictureInPicture`). A page that uses
+ /// the camera or microphone and registered an `enterpictureinpicture` media session handler
+ /// has it run, and Chromium lets it open its Picture in Picture window without a gesture:
+ /// Meet's "Automatic picture-in-picture" opens a Document Picture in Picture window of the
+ /// call, which no `<video>` request can (GitHub #198). Chrome's per-site permission for
+ /// automatic picture-in-picture applies. Any other page gets the video request; `video: false`
+ /// skips that (a silent page when the window goes out of sight).
private func leaveTab(_ tabID: UUID, video: Bool = true) {
guard store.settings.autoPictureInPicture, let rt = runtimes[tabID], !rt.browser.isInPictureInPicture else { return }
rt.pendingAutoPictureInPicture = true
- if rt.browser is WebKitBrowser {
+ guard rt.browser.isCapturingMedia, !(rt.browser is WebKitBrowser) else {
if video { requestPictureInPicture(tabID, automatic: true) }
return
}
- let query = """
- (() => {
- if (window.documentPictureInPicture?.window || document.pictureInPictureElement) return 'open';
- return window.__cra?.query().includes('enterpictureinpicture') ? 'handler' : 'none';
- })()
- """
- rt.browser.evaluate(inIsolatedWorld: PageScript.world, params: Self.evaluateParams(query, userGesture: false)) { [weak self, weak rt] result, _ in
+ let asked = clock.now
+ rt.browser.sendDevToolsMethod("Cra.autoPictureInPicture", params: #"{"tab":"hidden"}"#) { [weak self, weak rt] result, _ in
DispatchQueue.main.async {
- // Back on the tab before the page answered: nothing to open.
- guard let self, let rt, self.runtimes[tabID] === rt, rt.pendingAutoPictureInPicture else { return }
- switch Self.stringResult(result) {
- case "handler":
- rt.pendingAutoPictureInPicture = false
- rt.sessionPictureInPictureAt = self.clock.now
+ guard let self, let rt, self.runtimes[tabID] === rt else { return }
+ let answer = Self.jsonObject(result) ?? [:]
+ if answer["asked"] as? Bool == true {
self.log(tabID, "asks the page for Picture in Picture")
- let run = "window.__cra?.send('enterpictureinpicture')"
- rt.browser.evaluate(inIsolatedWorld: PageScript.world, params: Self.evaluateParams(run, userGesture: true)) { _, _ in }
- case "open":
+ rt.sessionPictureInPictureAt = asked
+ // Back on the tab before Chromium answered.
+ if !rt.pendingAutoPictureInPicture { self.returnToTab(rt) }
+ rt.pendingAutoPictureInPicture = false
+ } else if answer["pictureInPicture"] as? Bool == true {
+ rt.pendingAutoPictureInPicture = false
+ } else if video, rt.pendingAutoPictureInPicture {
+ self.requestPictureInPicture(tabID, automatic: true)
+ } else {
rt.pendingAutoPictureInPicture = false
- default:
- if video { self.requestPictureInPicture(tabID, automatic: true) } else { rt.pendingAutoPictureInPicture = false }
}
}
}
@@ -737,8 +733,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
/// the way a tab switch does (a four-finger swipe to another desktop, another app on top), and
/// the video comes back when the window is key again. Only pages playing sound get the video
/// request: it wants an unmuted video playing, and a page without one in its main frame gets
- /// the activation nudge, which an app switch shouldn't send to every page. Every page is asked,
- /// without a gesture, for its own `enterpictureinpicture` handler (a Meet call, #198).
+ /// the activation nudge, which an app switch shouldn't send to every page. A call (camera or
+ /// microphone in use) has its own `enterpictureinpicture` handler run (Meet, #198).
func windowVisibilityChanged(covered: Bool) {
guard covered != windowCovered else { return }
windowCovered = covered
@@ -748,8 +744,9 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
// A WebKit page's own fullscreen window covers this one: that is the video on
// screen, not out of sight. Asked then, WebKit's Picture in Picture got stuck in its
// transition and never opened for that video again.
- // A silent page is asked only for its own handler (a call: GitHub #198).
- if !PageEngines.isInOwnFullscreen(rt.browser) { leaveTab(id, video: rt.browser.isAudible) }
+ if rt.browser.isAudible || rt.browser.isCapturingMedia, !PageEngines.isInOwnFullscreen(rt.browser) {
+ leaveTab(id, video: rt.browser.isAudible)
+ }
} else if rt.autoPictureInPicture || rt.pendingAutoPictureInPicture || rt.sessionPictureInPictureAt != nil {
returnToTab(rt)
}
@@ -778,26 +775,21 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
if rt.browser.isInPictureInPicture { rt.browser.exitPictureInPicture() }
if let asked = rt.sessionPictureInPictureAt {
rt.sessionPictureInPictureAt = nil
- closeSessionPictureInPicture(rt, waiting: clock.now.timeIntervalSince(asked) < 2)
+ closeAutomaticPictureInPicture(rt, again: clock.now.timeIntervalSince(asked) < 2)
}
}
- /// Chrome closes an automatic Picture in Picture window when its tab is in front again, and
- /// the page takes its content back as the window goes (Meet's call returns to the tab). A
- /// window the page is still opening (the user came straight back) is closed as it opens.
- private func closeSessionPictureInPicture(_ rt: TabRuntime, waiting: Bool) {
- let js = """
- ((wait) => {
- const d = window.documentPictureInPicture;
- if (!d) return;
- if (d.window) return d.window.close();
- if (!wait) return;
- const opened = e => e.window.close();
- d.addEventListener('enter', opened, { once: true });
- setTimeout(() => d.removeEventListener('enter', opened), 2000);
- })(\(waiting))
- """
- rt.browser.sendDevToolsMethod("Runtime.evaluate", params: Self.evaluateParams(js, userGesture: false)) { _, _ in }
+ /// Chrome closes the window automatic Picture in Picture opened when its tab is in front
+ /// again, and the page takes its content back as the window goes (Meet's call returns to the
+ /// tab). A window the page was still opening (the user came straight back) is closed once it
+ /// is up, a second later, if the tab is still in front.
+ private func closeAutomaticPictureInPicture(_ rt: TabRuntime, again: Bool) {
+ rt.browser.sendDevToolsMethod("Cra.autoPictureInPicture", params: #"{"tab":"shown"}"#) { _, _ in }
+ guard again else { return }
+ clock.after(1) { [weak self, weak rt] in
+ guard let self, let rt, self.visibleTabIDs.contains(rt.tabID), !self.windowCovered else { return }
+ rt.browser.sendDevToolsMethod("Cra.autoPictureInPicture", params: #"{"tab":"shown"}"#) { _, _ in }
+ }
}
func browser(_ browser: CraBrowser, didChangePictureInPicture active: Bool) {
@@ -841,6 +833,7 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
func browser(_ browser: CraBrowser, didChangeMediaCapture capturing: Bool) {
guard let id = tabID(of: browser) else { return }
+ log(id, capturing ? "uses the camera or microphone" : "stopped using the camera and microphone")
delegate?.browserManagerDidUpdate(id)
}
@@ -861,8 +854,8 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
// MARK: Now playing
/// Play/pause, previous and next for the sidebar player. The page's own media session
- /// handlers go first (PageScript keeps them; YouTube, Spotify and SoundCloud skip tracks
- /// that way), else the page's media elements. Runs as a user gesture so play() is allowed.
+ /// handlers go first (YouTube, Spotify and SoundCloud skip tracks that way), else the page's
+ /// media elements.
func performNowPlaying(_ id: UUID, _ action: NowPlaying.Action) {
let op: String
switch action {
@@ -881,6 +874,51 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
case .toggleMute, .show: return
}
guard let rt = runtimes[id] else { nowPlaying?.remove(id); return }
+ if rt.browser is WebKitBrowser { return performWebKitNowPlaying(id, rt, op) }
+ // Chromium routes the page's own media session handlers (YouTube, Spotify and SoundCloud
+ // skip tracks that way), as Arc does: `Cra.mediaSession` runs the handler the way
+ // Chrome's media keys do, and a page without one has its media elements played or paused.
+ let run = { [weak self, weak rt] (op: String) in
+ guard let rt else { return }
+ rt.browser.sendDevToolsMethod("Cra.mediaSession", params: Self.jsonObjectString(["action": op])) { result, _ in
+ DispatchQueue.main.async {
+ guard let self else { return }
+ if Self.jsonObject(result)?["handled"] as? Bool == true {
+ if op == "play" || op == "pause" { self.nowPlaying?.update(id) { $0.playing = op == "play" } }
+ } else if op == "play" || op == "pause" {
+ self.mediaElements(id, rt, op)
+ }
+ }
+ }
+ }
+ guard op == "toggle" else { return run(op) }
+ mediaElements(id, rt, "state") { playing in run(playing ? "pause" : "play") }
+ }
+
+ /// The page's media elements: "state" reads whether any plays, "play" plays the one that
+ /// played last (or the first), "pause" pauses them all. No user gesture: the page has been
+ /// playing, so it already has its activation.
+ private func mediaElements(_ id: UUID, _ rt: TabRuntime, _ op: String, then: ((Bool) -> Void)? = nil) {
+ let js = """
+ ((op) => {
+ const media = [...document.querySelectorAll('video,audio')];
+ const playing = media.some(m => !m.paused && !m.ended);
+ if (op === 'pause') media.forEach(m => m.pause());
+ else if (op === 'play') (media.find(m => m.currentTime > 0 && !m.ended) ?? media[0])?.play();
+ return op === 'pause' ? 'paused' : op === 'play' || playing ? 'playing' : 'paused';
+ })(\(Self.jsonString(op)))
+ """
+ rt.browser.evaluate(inIsolatedWorld: PageScript.world, params: Self.evaluateParams(js, userGesture: false)) { [weak self] result, _ in
+ DispatchQueue.main.async {
+ guard let state = Self.stringResult(result) else { return }
+ if let then { return then(state == "playing") }
+ self?.nowPlaying?.update(id) { $0.playing = state == "playing" }
+ }
+ }
+ }
+
+ /// A WebKit page: its media session handlers through PageScript's wrapper.
+ private func performWebKitNowPlaying(_ id: UUID, _ rt: TabRuntime, _ op: String) {
let js = """
((op) => {
const cra = window.__cra, has = cra ? cra.query() : [];
@@ -931,18 +969,34 @@ final class BrowserManager: NSObject, @preconcurrency CraBrowserDelegate {
}
}
- /// Which track buttons the page answers (media session handlers).
+ /// Which track buttons the page answers (media session handlers), and whether it has a video.
private func refreshMediaControls(_ id: UUID) {
+ guard let browser = runtimes[id]?.browser else { return }
+ let webKit = browser is WebKitBrowser
let js = """
- (() => { const has = window.__cra?.query() ?? [];
+ (() => { const has = \(webKit ? "window.__cra?.query() ?? []" : "[]");
return (has.includes('previoustrack') ? 'p' : '') + (has.includes('nexttrack') ? 'n' : '') + (document.querySelector('video') ? 'v' : ''); })()
"""
- runtimes[id]?.browser.evaluate(inIsolatedWorld: PageScript.world, params: Self.evaluateParams(js, userGesture: false)) { [weak self] result, _ in
+ browser.evaluate(inIsolatedWorld: PageScript.world, params: Self.evaluateParams(js, userGesture: false)) { [weak self] result, _ in
DispatchQueue.main.async {
guard let has = Self.stringResult(result) else { return }
- self?.nowPlaying?.update(id) { $0.hasPrevious = has.contains("p"); $0.hasNext = has.contains("n"); $0.hasVideo = has.contains("v") }
+ self?.nowPlaying?.update(id) {
+ $0.hasVideo = has.contains("v")
+ if webKit { $0.hasPrevious = has.contains("p"); $0.hasNext = has.contains("n") }
+ }
}
}
+ guard !webKit else { return }
+ browser.sendDevToolsMethod("Cra.mediaSession", params: "{}") { [weak self] result, _ in
+ DispatchQueue.main.async {
+ guard let actions = Self.jsonObject(result)?["actions"] as? [String] else { return }
+ self?.nowPlaying?.update(id) { $0.hasPrevious = actions.contains("previoustrack"); $0.hasNext = actions.contains("nexttrack") }
+ }
+ }
+ }
+
+ private static func jsonObjectString(_ object: [String: Any]) -> String {
+ String(data: try! JSONSerialization.data(withJSONObject: object), encoding: .utf8)!
}
private static func evaluateParams(_ js: String, userGesture: Bool) -> String {
diff --git a/Sources/Cra/Services/PageScript.swift b/Sources/Cra/Services/PageScript.swift
index b1455b1..9e4bed8 100644
--- a/Sources/Cra/Services/PageScript.swift
+++ b/Sources/Cra/Services/PageScript.swift
@@ -8,11 +8,13 @@ import Foundation
/// - `typed`: fields the user typed into (trusted input events only, so values a framework sets
/// don't count), with the URL they were typed on. Tab sleeping keeps such a page awake.
/// - `volume`: the sidebar player's volume drawer; media that starts playing later gets it too.
-/// - `send(action)` / `handlers`: the page's media session handlers (YouTube, Spotify…), so the
-/// player can skip tracks. `setActionHandler` can't be called from outside and its handlers
-/// live in the page's world, so a small wrapper there keeps them in a closure and answers an
-/// event whose name is random per launch: nothing in the page's world names Cra. Leaving a
-/// call's tab sends `enterpictureinpicture` with Chrome's details (Google Meet, GitHub #198).
+/// - `send(action)` / `handlers`: a WebKit page's media session handlers (YouTube, Spotify…), so
+/// the player can skip tracks. `setActionHandler` can't be called from outside and its handlers
+/// live in the page's world, so a small wrapper there (`mediaSessionWrapper`) keeps them in a
+/// closure and answers an event whose name is random per launch: nothing in the page's world
+/// names Cra. Chromium pages don't get it: Chromium routes their handlers itself
+/// (`Cra.mediaSession`, like Arc), which also finds a handler the page registered before a
+/// wrapper could be in place (the first page of a new tab).
/// - `drm`: the page asked for Widevine (navigator.requestMediaKeySystemAccess): the Site Control
/// Center then offers to play the site in Safari's engine (docs/protected-media.md). A wrapper in
/// the page's world tells this world through the same per-launch event name.
@@ -24,8 +26,8 @@ enum PageScript {
static let world = "cra"
private static let channel = "c" + UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
- /// The page's world: only the media session wrapper.
- static let mainWorld = """
+ /// The page's world in WebKit: the media session wrapper.
+ static let mediaSessionWrapper = """
(() => {
const proto = window.MediaSession?.prototype, set = proto?.setActionHandler;
if (!set) return;
@@ -37,11 +39,13 @@ enum PageScript {
} }.setActionHandler });
addEventListener('\(channel)', e => {
if (e.detail === '?') return dispatchEvent(new CustomEvent('\(channel)r', { detail: Object.keys(handlers).join(',') }));
- const details = e.detail === 'enterpictureinpicture'
- ? { action: e.detail, enterPictureInPictureReason: 'contentoccluded' } : { action: e.detail };
- try { handlers[e.detail]?.(details); } catch {}
+ try { handlers[e.detail]?.({ action: e.detail }); } catch {}
});
})();
+ """
+
+ /// The page's world, in both engines: the Widevine request wrapper.
+ static let mainWorld = """
(() => {
const proto = window.Navigator?.prototype, request = proto?.requestMediaKeySystemAccess;
if (!request) return;
diff --git a/Sources/Cra/Services/WebKit/WebKitBrowser.swift b/Sources/Cra/Services/WebKit/WebKitBrowser.swift
index 5a713fb..035584b 100644
--- a/Sources/Cra/Services/WebKit/WebKitBrowser.swift
+++ b/Sources/Cra/Services/WebKit/WebKitBrowser.swift
@@ -88,7 +88,7 @@ final class WebKitBrowser: CraBrowser, WKNavigationDelegate, WKUIDelegate, WKDow
}
// A popup's configuration is its opener's copy: it gets its own scripts and handler.
let content = WKUserContentController()
- content.addUserScript(WKUserScript(source: PageScript.mainWorld, injectionTime: .atDocumentStart, forMainFrameOnly: false, in: .page))
+ content.addUserScript(WKUserScript(source: PageScript.mediaSessionWrapper + PageScript.mainWorld, injectionTime: .atDocumentStart, forMainFrameOnly: false, in: .page))
content.addUserScript(WKUserScript(source: PageScript.isolatedWorld + Self.isolatedAddOn, injectionTime: .atDocumentStart,
forMainFrameOnly: false, in: Self.world))
let proxy = ScriptMessageProxy(owner: self)
diff --git a/Sources/CraCEF/CraCEF.mm b/Sources/CraCEF/CraCEF.mm
index e99904e..d03507e 100644
--- a/Sources/CraCEF/CraCEF.mm
+++ b/Sources/CraCEF/CraCEF.mm
@@ -190,6 +190,11 @@ static CraClient* AsCraClient(CefClient* c) {
@property (nonatomic) BOOL isInPictureInPicture;
@property (nonatomic) BOOL isPictureInPicturePlaying;
@property (nonatomic) BOOL isCapturingMedia;
+/// Media access CEF's own permission flow granted (OnMediaAccessChange), and the camera or
+/// microphone Chrome's tab recording indicator counts ("Cra.capture"); isCapturingMedia is either.
+@property (nonatomic) BOOL cefMediaAccess;
+@property (nonatomic) BOOL chromeCapture;
+- (void)updateCapture;
@property (nonatomic) BOOL isAudible;
- (void)audibleChanged:(BOOL)audible;
- (void)requestPictureInPictureInFrame:(CefRefPtr<CefFrame>)frame automatic:(BOOL)automatic x:(int)x y:(int)y;
@@ -1426,11 +1431,8 @@ public:
void OnMediaAccessChange(CefRefPtr<CefBrowser> browser, bool has_video_access, bool has_audio_access) override {
CraBrowser* o = owner_;
if (!o) return;
- BOOL capturing = has_video_access || has_audio_access;
- if (capturing == o.isCapturingMedia) return;
- o.isCapturingMedia = capturing;
- if ([o.delegate respondsToSelector:@selector(browser:didChangeMediaCapture:)])
- [o.delegate browser:o didChangeMediaCapture:capturing];
+ o.cefMediaAccess = has_video_access || has_audio_access;
+ [o updateCapture];
}
// Chromium's audible state, which CEF has no callback for: the engine sends it as a
@@ -1445,6 +1447,18 @@ public:
if (o) [o audibleChanged:message->GetArgumentList()->GetBool(0)];
return true;
}
+ // Camera and microphone use as Chrome's tab recording indicator counts it, which a
+ // Chrome-style page's media never reaches OnMediaAccessChange with (Arc's
+ // didChangeCameraState / didChangeMicrophoneState; scripts/cef-patches/
+ // media-capture-and-session.patch).
+ if (message->GetName() == "Cra.capture") {
+ CefRefPtr<CefListValue> args = message->GetArgumentList();
+ if (o) {
+ o.chromeCapture = (args->GetSize() > 0 && args->GetBool(0)) || (args->GetSize() > 1 && args->GetBool(1));
+ [o updateCapture];
+ }
+ return true;
+ }
if (message->GetName() == "Cra.activate") {
CefRefPtr<CefListValue> args = message->GetArgumentList();
BOOL byPage = args->GetSize() > 0 && args->GetBool(0);
@@ -2038,6 +2052,14 @@ class CraDevToolsObserver : public CefDevToolsMessageObserver {
return _isIncognito ? IncognitoContext() : ProfileContext(_profilePath);
}
+- (void)updateCapture {
+ BOOL capturing = self.cefMediaAccess || self.chromeCapture;
+ if (capturing == self.isCapturingMedia) return;
+ self.isCapturingMedia = capturing;
+ if ([self.delegate respondsToSelector:@selector(browser:didChangeMediaCapture:)])
+ [self.delegate browser:self didChangeMediaCapture:capturing];
+}
+
- (CefRefPtr<CefBrowser>)cefBrowser { return _browser; }
- (CefRefPtr<CefClient>)cefClient { return _client; }
diff --git a/Sources/CraCEF/include/CraCEF.h b/Sources/CraCEF/include/CraCEF.h
index d997d48..566fcbd 100644
--- a/Sources/CraCEF/include/CraCEF.h
+++ b/Sources/CraCEF/include/CraCEF.h
@@ -196,7 +196,7 @@ typedef NS_ENUM(NSInteger, CraDownloadState) {
@property (nonatomic, readonly) BOOL isInPictureInPicture;
/// YES while that video is playing.
@property (nonatomic, readonly) BOOL isPictureInPicturePlaying;
-/// The page is using the camera or microphone (Chromium's media access state).
+/// The page is using the camera or microphone, as Chrome's tab recording indicator counts it.
@property (nonatomic, readonly) BOOL isCapturingMedia;
/// The page is playing sound, in any frame (Chromium's audible state). Like Chrome's tab
/// speaker it stays YES for 2 s after the page goes quiet. Muting the tab doesn't change it.
diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swift
index 4875054..be351ee 100644
--- a/Tests/BrowserManagerLifecycleTests.swift
+++ b/Tests/BrowserManagerLifecycleTests.swift
@@ -99,6 +99,7 @@ enum BrowserManagerLifecycleTests {
await splitCopySleepsPinnedTabCase()
await coveredWindowPictureInPictureCase()
await callPictureInPictureCase()
+ await playerMediaSessionCase()
pageColoursCase()
extensionPageRetryCase()
await sleepCase("malformed or missing replies cannot authorize sleeping", reply: nil) { _, _ in }
@@ -687,9 +688,7 @@ enum BrowserManagerLifecycleTests {
(nil, 1, "a page whose answer was lost")] as [(String?, Int, String)] {
let before = ra.browser.automaticPictureInPictureRequests
manager.show(b, focus: false)
- expect(ra.browser.lastIsolatedParams.contains(#""userGesture":false"#), "the page is first asked for its own handler, without a gesture")
- ra.browser.reply(to: "cra:Runtime.evaluate", with: #"{"result":{"type":"string","value":"none"}}"#)
- await drainMainQueue()
+ expect(!ra.browser.replies.contains { $0.method == "Cra.autoPictureInPicture" }, "a page that isn't capturing goes straight to the video request")
expect(ra.browser.lastParams.contains(#""userGesture":true"#), "leaving a video tab asks as a user gesture")
expect(ra.browser.lastParams.contains("})(true)"), "leaving a video tab takes only an audible, playing video")
let reply = answer.map { #"{"result":{"type":"string","value":"\#($0)"}}"# }
@@ -744,10 +743,10 @@ enum BrowserManagerLifecycleTests {
/// A call (Google Meet with "Automatic picture-in-picture" on) registers its own
/// `enterpictureinpicture` media session handler, which opens a Document Picture in Picture
- /// window of the call. Leaving its tab, or its window going out of sight, runs that handler as a
- /// user gesture, as Chrome does; coming back closes the window (GitHub #198). The page is asked
- /// whether it has the handler without a gesture, so a page without one never gets activation
- /// from an app switch, and a page without one gets the video request as before.
+ /// window of the call. Leaving its tab while it uses the camera or microphone, or its window
+ /// going out of sight, drives Chrome's automatic Picture in Picture (`Cra.autoPictureInPicture`),
+ /// as Chrome's tab strip and Arc do; coming back has Chrome close the window (GitHub #198).
+ /// A page Chrome doesn't ask gets the video request.
@MainActor
private static func callPictureInPictureCase() async {
let clock = ManualScheduler()
@@ -756,63 +755,123 @@ enum BrowserManagerLifecycleTests {
let a = store.createTab(url: "https://meet.example.test/abc").id, b = store.createTab(url: "https://example.test/other").id
let ra = manager.ensureRuntime(for: a)!
store.settings.autoPictureInPicture = true
+ ra.browser.isCapturingMedia = true
manager.show(a, focus: false)
- let answer = { (value: String) in #"{"result":{"type":"string","value":"\#(value)"}}"# }
+ let asked = #"{"asked":true,"pictureInPicture":false}"#, notAsked = #"{"asked":false,"pictureInPicture":false}"#
+ let hidden = #"{"tab":"hidden"}"#, shown = #"{"tab":"shown"}"#
let evaluations = { ra.browser.replies.filter { $0.method == "Runtime.evaluate" }.count }
- let isolated = { ra.browser.replies.filter { $0.method == "cra:Runtime.evaluate" }.count }
+ let calls = { ra.browser.replies.filter { $0.method == "Cra.autoPictureInPicture" }.count }
+ let settle = { while ra.browser.replies.contains(where: { $0.method == "Cra.autoPictureInPicture" }) {
+ ra.browser.reply(to: "Cra.autoPictureInPicture", with: "{}") } }
manager.show(b, focus: false)
- expect(ra.browser.lastIsolatedParams.contains("enterpictureinpicture") && ra.browser.lastIsolatedParams.contains(#""userGesture":false"#),
- "leaving the tab asks the page for its own handler, without a gesture")
- ra.browser.reply(to: "cra:Runtime.evaluate", with: answer("handler"))
+ expect(calls() == 1 && ra.browser.lastParams == hidden, "leaving a call's tab drives Chrome's automatic Picture in Picture")
+ ra.browser.reply(to: "Cra.autoPictureInPicture", with: asked)
await drainMainQueue()
- expect(isolated() == 1 && ra.browser.lastIsolatedParams.contains("send('enterpictureinpicture')")
- && ra.browser.lastIsolatedParams.contains(#""userGesture":true"#), "a page with the handler has it run, as a user gesture")
- ra.browser.reply(to: "cra:Runtime.evaluate", with: nil)
- expect(evaluations() == 0 && ra.browser.automaticPictureInPictureRequests == 0, "and gets no video request too")
+ expect(evaluations() == 0 && ra.browser.automaticPictureInPictureRequests == 0, "the page was asked: no video request too")
clock.advance(by: 30)
manager.show(a, focus: false)
- expect(evaluations() == 1 && ra.browser.lastParams.contains("documentPictureInPicture") && ra.browser.lastParams.contains("})(false)"),
- "back on the call's tab, its window closes")
- ra.browser.reply(to: "Runtime.evaluate", with: nil)
+ expect(calls() == 1 && ra.browser.lastParams == shown, "back on the call's tab, Chrome closes its window")
+ settle()
+ clock.advance(by: 2)
+ expect(calls() == 0, "once: the window was up long before")
manager.show(b, focus: false)
manager.show(a, focus: false)
- expect(evaluations() == 0, "coming back again closes nothing: the window it opened is gone")
- ra.browser.reply(to: "cra:Runtime.evaluate", with: answer("handler"))
+ expect(calls() == 1 && ra.browser.lastParams == hidden, "coming back again closes nothing: the window it opened is gone")
+ ra.browser.reply(to: "Cra.autoPictureInPicture", with: asked)
await drainMainQueue()
- expect(isolated() == 0, "back before the page answered: the handler isn't run")
+ expect(calls() == 1 && ra.browser.lastParams == shown, "back before Chromium answered: the window is closed")
+ settle()
+ clock.advance(by: 1)
+ expect(calls() == 1 && ra.browser.lastParams == shown, "and again a second later, in case it was still opening")
+ settle()
- // Back right after the handler ran: a window still opening is closed as it opens.
+ // A Picture in Picture window this page already has stays when the user comes back.
manager.show(b, focus: false)
- ra.browser.reply(to: "cra:Runtime.evaluate", with: answer("handler"))
+ ra.browser.reply(to: "Cra.autoPictureInPicture", with: #"{"asked":false,"pictureInPicture":true}"#)
await drainMainQueue()
- ra.browser.reply(to: "cra:Runtime.evaluate", with: nil)
manager.show(a, focus: false)
- expect(evaluations() == 1 && ra.browser.lastParams.contains("})(true)"), "a window still opening is closed as it opens")
- ra.browser.reply(to: "Runtime.evaluate", with: nil)
+ expect(calls() == 0 && evaluations() == 0 && ra.browser.automaticPictureInPictureRequests == 0, "a Picture in Picture already open is left alone")
- // A window the user opened from the call stays when they come back.
- manager.show(b, focus: false)
- ra.browser.reply(to: "cra:Runtime.evaluate", with: answer("open"))
- await drainMainQueue()
- manager.show(a, focus: false)
- expect(evaluations() == 0 && isolated() == 0 && ra.browser.automaticPictureInPictureRequests == 0, "a Picture in Picture already open is left alone")
+ // A page Chrome doesn't ask (no handler, no permission), or a Chromium without the method,
+ // gets the video request.
+ for reply in [notAsked, nil] {
+ manager.show(b, focus: false)
+ if let reply { ra.browser.reply(to: "Cra.autoPictureInPicture", with: reply) } else { ra.browser.fail("Cra.autoPictureInPicture", with: "not found") }
+ await drainMainQueue()
+ expect(evaluations() == 1 && ra.browser.lastParams.contains("})(true)"), "leaving its tab falls back to the video request")
+ ra.browser.reply(to: "Runtime.evaluate", with: #"{"result":{"type":"string","value":"none"}}"#)
+ await drainMainQueue()
+ manager.show(a, focus: false)
+ }
- // The window going out of sight: a silent page runs its handler, but never gets the video
- // request, which would send it the activation key.
+ // The window going out of sight: a silent call is asked through Chrome, and never gets the
+ // video request, which would send the page the activation key.
manager.windowVisibilityChanged(covered: true)
- ra.browser.reply(to: "cra:Runtime.evaluate", with: answer("none"))
+ ra.browser.reply(to: "Cra.autoPictureInPicture", with: notAsked)
await drainMainQueue()
- expect(evaluations() == 0, "a silent page without the handler gets no video request on an app switch")
+ expect(evaluations() == 0, "a silent call Chrome didn't ask gets no video request on an app switch")
manager.windowVisibilityChanged(covered: false)
manager.windowVisibilityChanged(covered: true)
- ra.browser.reply(to: "cra:Runtime.evaluate", with: answer("handler"))
+ ra.browser.reply(to: "Cra.autoPictureInPicture", with: asked)
await drainMainQueue()
- expect(ra.browser.lastIsolatedParams.contains(#""userGesture":true"#), "a call whose window goes out of sight runs its handler")
- ra.browser.reply(to: "cra:Runtime.evaluate", with: nil)
+ clock.advance(by: 30)
manager.windowVisibilityChanged(covered: false)
- expect(evaluations() == 1 && ra.browser.lastParams.contains("documentPictureInPicture"), "the window back in sight closes the call's window")
- ra.browser.reply(to: "Runtime.evaluate", with: nil)
+ expect(calls() == 1 && ra.browser.lastParams == shown, "the window back in sight closes the call's window")
+ settle()
+
+ ra.browser.isCapturingMedia = false
+ manager.show(b, focus: false)
+ expect(calls() == 0, "a page not using the camera or microphone isn't driven through Chrome")
+ manager.closeAll()
+ }
+
+ /// The sidebar player in a Chromium tab: Chromium runs the page's media session handlers
+ /// (`Cra.mediaSession`, like Arc's media actions) and reports which it has, however early the
+ /// page registered them; a page without a play/pause handler has its media elements played or
+ /// paused.
+ @MainActor
+ private static func playerMediaSessionCase() async {
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ let np = NowPlaying()
+ manager.nowPlaying = np
+ let a = store.createTab(url: "https://music.example.test/").id, b = store.createTab(url: "https://example.test/other").id
+ let ra = manager.ensureRuntime(for: a)!
+ manager.show(b, focus: false)
+ ra.browser.isAudible = true
+ manager.browser(ra.browser, didChangeAudible: true)
+ expect(ra.browser.replies.contains { $0.method == "Cra.mediaSession" } && ra.browser.lastParams == "{}",
+ "a page that starts playing is asked which media session actions it has")
+ ra.browser.reply(to: "Cra.mediaSession", with: #"{"actions":["play","pause","nexttrack"],"pictureInPicture":false}"#)
+ await drainMainQueue()
+ expect(np.entries.first?.hasNext == true && np.entries.first?.hasPrevious == false, "the card offers the track buttons the page answers")
+ ra.browser.replies.removeAll()
+
+ manager.performNowPlaying(a, .next)
+ expect(ra.browser.lastParams == #"{"action":"nexttrack"}"#, "next track runs the page's handler")
+ ra.browser.reply(to: "Cra.mediaSession", with: #"{"handled":true,"pictureInPicture":false}"#)
+ await drainMainQueue()
+ expect(!ra.browser.replies.contains { $0.method == "cra:Runtime.evaluate" }, "and nothing else")
+
+ manager.performNowPlaying(a, .togglePlayback)
+ expect(ra.browser.lastIsolatedParams.contains(#"(\"state\")"#), "play/pause first reads whether the page plays")
+ ra.browser.reply(to: "cra:Runtime.evaluate", with: #"{"result":{"type":"string","value":"playing"}}"#)
+ await drainMainQueue()
+ expect(ra.browser.lastParams == #"{"action":"pause"}"#, "a playing page is paused through its handler")
+ ra.browser.reply(to: "Cra.mediaSession", with: #"{"handled":true,"pictureInPicture":false}"#)
+ await drainMainQueue()
+ expect(np.entries.first?.playing == false && ra.browser.replies.isEmpty, "the card shows it paused")
+
+ manager.performNowPlaying(a, .togglePlayback)
+ ra.browser.reply(to: "cra:Runtime.evaluate", with: #"{"result":{"type":"string","value":"paused"}}"#)
+ await drainMainQueue()
+ ra.browser.reply(to: "Cra.mediaSession", with: #"{"handled":false,"pictureInPicture":false}"#)
+ await drainMainQueue()
+ expect(ra.browser.lastIsolatedParams.contains(#"(\"play\")"#), "without a handler the page's media elements play")
+ ra.browser.reply(to: "cra:Runtime.evaluate", with: #"{"result":{"type":"string","value":"playing"}}"#)
+ await drainMainQueue()
+ expect(np.entries.first?.playing == true, "the card shows it playing")
manager.closeAll()
}
@@ -830,15 +889,11 @@ enum BrowserManagerLifecycleTests {
manager.show(a, focus: false)
manager.windowVisibilityChanged(covered: true)
- ra.browser.reply(to: "cra:Runtime.evaluate", with: #"{"result":{"type":"string","value":"none"}}"#)
- await drainMainQueue()
- expect(!ra.browser.replies.contains { $0.method == "Runtime.evaluate" }, "a covered window doesn't send a silent page the video request")
+ expect(ra.browser.replies.isEmpty, "a covered window doesn't ask a silent page")
manager.windowVisibilityChanged(covered: false)
ra.browser.isAudible = true
manager.windowVisibilityChanged(covered: true)
- ra.browser.reply(to: "cra:Runtime.evaluate", with: #"{"result":{"type":"string","value":"none"}}"#)
- await drainMainQueue()
expect(ra.browser.lastParams.contains(#""userGesture":true"#) && ra.browser.lastParams.contains("})(true)"),
"a covered window asks its playing page for automatic Picture in Picture")
ra.browser.reply(to: "Runtime.evaluate", with: #"{"result":{"type":"string","value":"ok"}}"#)
diff --git a/docs/protected-media.md b/docs/protected-media.md
index 58491b9..2a11db5 100644
--- a/docs/protected-media.md
+++ b/docs/protected-media.md
@@ -75,10 +75,12 @@ It also answers the DevTools Protocol methods Cra calls from WebKit's own API:
| `Storage.clearDataForOrigin`, `Network.clearBrowserCache` | the profile's `WKWebsiteDataStore` |
| `Cra.setFreezingVote`, `Cra.load` | accepted; WebKit throttles hidden pages itself |
| `Cra.discard`, `Cra.getFreezingState`, `Target.*` | an error. Tab sleeping then closes the page, and it loads again when shown; extension actions don't apply. |
+| `Cra.mediaSession`, `Cra.autoPictureInPicture` | never sent: a WebKit page's media session handlers go through PageScript's wrapper, and leaving its tab asks its video for Picture in Picture |
-PageScript's two scripts run in WebKit as user scripts, in the page world and in a `cra`
-content world. With them come Cra's typed-text and long-task tracking, the sidebar player's
-media session buttons and its volume. A small addition in the `cra` world reports what Chromium
+PageScript's scripts run in WebKit as user scripts, in the page world and in a `cra` content
+world. With them come Cra's typed-text and long-task tracking, the sidebar player's media session
+buttons (through a wrapper around `setActionHandler` that only WebKit pages get; Chromium routes a
+page's handlers itself) and its volume. A small addition in the `cra` world reports what Chromium
tells CraCEF natively: media playing, Picture in Picture and link hovers (the status bubble).
WebKit's `_isPlayingAudio` drives the speaker when this macOS has it.
diff --git a/scripts/cef-patches/audible-state.patch b/scripts/cef-patches/audible-state.patch
index 6008518..498fc77 100644
--- a/scripts/cef-patches/audible-state.patch
+++ b/scripts/cef-patches/audible-state.patch
@@ -1,8 +1,32 @@
diff --git a/cef/libcef/browser/browser_contents_delegate.cc b/cef/libcef/browser/browser_contents_delegate.cc
-index 72dd7c5..15d995a 100644
+index 72dd7c5..12186c2 100644
--- a/cef/libcef/browser/browser_contents_delegate.cc
+++ b/cef/libcef/browser/browser_contents_delegate.cc
-@@ -613,6 +613,21 @@ void CefBrowserContentsDelegate::DidFinishLoad(
+@@ -11,6 +11,7 @@
+ #include "cef/libcef/browser/native/cursor_util.h"
+ #include "cef/libcef/common/api_version_util.h"
+ #include "cef/libcef/common/frame_util.h"
++#include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h"
+ #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
+ #include "chrome/common/chrome_result_codes.h"
+ #include "components/input/native_web_keyboard_event.h"
+@@ -86,7 +87,14 @@ class CefWidgetHostInterceptor
+
+ CefBrowserContentsDelegate::CefBrowserContentsDelegate(
+ scoped_refptr<CefBrowserInfo> browser_info)
+- : browser_info_(browser_info) {}
++ : browser_info_(browser_info) {
++ // Cra: Chrome's tab recording indicator. CEF's OnMediaAccessChange only
++ // fires for streams CEF's own permission flow allowed; Chrome-style pages
++ // that get the camera or microphone through Chrome's flow never report it.
++ capture_observation_.Observe(MediaCaptureDevicesDispatcher::GetInstance()
++ ->GetMediaStreamCaptureIndicator()
++ .get());
++}
+
+ void CefBrowserContentsDelegate::ObserveWebContents(
+ content::WebContents* new_contents) {
+@@ -613,6 +621,56 @@ void CefBrowserContentsDelegate::DidFinishLoad(
OnLoadEnd(frame, validated_url, http_status_code);
}
@@ -20,19 +44,95 @@ index 72dd7c5..15d995a 100644
+ message->GetArgumentList()->SetBool(0, audible);
+ c->OnProcessMessageReceived(b, b->GetMainFrame(), PID_BROWSER, message);
+}
++
++// Cra: whether the page uses the camera and the microphone, as Chrome's tab
++// recording indicator (MediaStreamCaptureIndicator) counts them. Delivered as a
++// "Cra.capture" message from PID_BROWSER with the camera and microphone states.
++void CefBrowserContentsDelegate::OnIsCapturingVideoChanged(
++ content::WebContents* web_contents,
++ bool is_capturing_video) {
++ if (web_contents == this->web_contents()) {
++ SendCaptureState();
++ }
++}
++
++void CefBrowserContentsDelegate::OnIsCapturingAudioChanged(
++ content::WebContents* web_contents,
++ bool is_capturing_audio) {
++ if (web_contents == this->web_contents()) {
++ SendCaptureState();
++ }
++}
++
++void CefBrowserContentsDelegate::SendCaptureState() {
++ auto c = client();
++ auto b = browser();
++ auto wc = web_contents();
++ if (!c || !b || !wc) {
++ return;
++ }
++ auto indicator =
++ MediaCaptureDevicesDispatcher::GetInstance()->GetMediaStreamCaptureIndicator();
++ CefRefPtr<CefProcessMessage> message =
++ CefProcessMessage::Create("Cra.capture");
++ message->GetArgumentList()->SetBool(0, indicator->IsCapturingVideo(wc));
++ message->GetArgumentList()->SetBool(1, indicator->IsCapturingAudio(wc));
++ c->OnProcessMessageReceived(b, b->GetMainFrame(), PID_BROWSER, message);
++}
+
void CefBrowserContentsDelegate::TitleWasSet(content::NavigationEntry* entry) {
// |entry| may be NULL if a popup is created via window.open and never
// navigated.
diff --git a/cef/libcef/browser/browser_contents_delegate.h b/cef/libcef/browser/browser_contents_delegate.h
-index ae50fee..3b7515e 100644
+index ae50fee..1e99f05 100644
--- a/cef/libcef/browser/browser_contents_delegate.h
+++ b/cef/libcef/browser/browser_contents_delegate.h
-@@ -134,6 +134,7 @@ class CefBrowserContentsDelegate : public content::WebContentsDelegate,
+@@ -10,7 +10,9 @@
+
+ #include "base/callback_list.h"
+ #include "base/observer_list.h"
++#include "base/scoped_observation.h"
+ #include "cef/libcef/browser/frame_host_impl.h"
++#include "chrome/browser/media/webrtc/media_stream_capture_indicator.h"
+ #include "content/public/browser/web_contents_delegate.h"
+ #include "content/public/browser/web_contents_observer.h"
+
+@@ -45,8 +47,10 @@ constexpr inline CefBrowserContentsState operator|(
+ // Tracks state and executes client callbacks based on WebContents callbacks.
+ // Includes functionality that is shared by Alloy and Chrome styles. Only
+ // accessed on the UI thread.
+-class CefBrowserContentsDelegate : public content::WebContentsDelegate,
+- public content::WebContentsObserver {
++class CefBrowserContentsDelegate
++ : public content::WebContentsDelegate,
++ public content::WebContentsObserver,
++ public MediaStreamCaptureIndicator::Observer {
+ public:
+ using State = CefBrowserContentsState;
+
+@@ -134,6 +138,14 @@ class CefBrowserContentsDelegate : public content::WebContentsDelegate,
void PrimaryMainDocumentElementAvailable() override;
void LoadProgressChanged(double progress) override;
void DidStopLoading() override;
+ void OnAudioStateChanged(bool audible) override;
++
++ // MediaStreamCaptureIndicator::Observer methods (Cra: camera and microphone
++ // use, see SendCaptureState).
++ void OnIsCapturingVideoChanged(content::WebContents* web_contents,
++ bool is_capturing_video) override;
++ void OnIsCapturingAudioChanged(content::WebContents* web_contents,
++ bool is_capturing_audio) override;
void DidFinishNavigation(
content::NavigationHandle* navigation_handle) override;
void DidFailLoad(content::RenderFrameHost* render_frame_host,
+@@ -177,6 +189,10 @@ class CefBrowserContentsDelegate : public content::WebContentsDelegate,
+ bool OnSetFocus(cef_focus_source_t source);
+
+ private:
++ void SendCaptureState();
++ base::ScopedObservation<MediaStreamCaptureIndicator,
++ MediaStreamCaptureIndicator::Observer>
++ capture_observation_{this};
+ CefRefPtr<CefClient> client() const;
+ CefRefPtr<CefBrowser> browser() const;
+ CefBrowserPlatformDelegate* platform_delegate() const;
diff --git a/scripts/cef-patches/auto-pip-tab-hidden.patch b/scripts/cef-patches/auto-pip-tab-hidden.patch
new file mode 100644
index 0000000..975f130
--- /dev/null
+++ b/scripts/cef-patches/auto-pip-tab-hidden.patch
@@ -0,0 +1,41 @@
+diff --git a/chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.cc b/chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.cc
+index 359dba00ed..0cf13e37c8 100644
+--- a/chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.cc
++++ b/chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.cc
+@@ -1063,6 +1063,18 @@ void AutoPictureInPictureTabHelper::OnUserClosedWindow() {
+ #endif // !BUILDFLAG(IS_ANDROID)
+ }
+
++bool AutoPictureInPictureTabHelper::CraOnTabHidden() {
++ // Only what qualifies now (a call: the camera or microphone in use). A page
++ // that only plays sound waits for a Safe Browsing check in Chrome; the
++ // embedder asks its video instead.
++ if (!IsEligibleForAutoPictureInPicture(
++ /*should_record_blocking_metrics=*/false)) {
++ return false;
++ }
++ MaybeEnterAutoPictureInPicture();
++ return true;
++}
++
+ void AutoPictureInPictureTabHelper::OnTabBecameActive() {
+ #if BUILDFLAG(IS_ANDROID)
+ if (hide_button_clicked_time_) {
+diff --git a/chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.h b/chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.h
+index 6510bdeb1b..fb9a719852 100644
+--- a/chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.h
++++ b/chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.h
+@@ -162,6 +162,13 @@ class AutoPictureInPictureTabHelper
+ // any auto-pip window we have open, though there might also not be one.
+ void OnTabBecameActive();
+
++ // Cra: the embedder hid this tab (CEF has no tab strip for this helper to
++ // observe). Does what a tab switch away from it does: if the tab is eligible,
++ // opens the window in which the browser authorizes the page's Picture in
++ // Picture and sends the page the enterpictureinpicture media session action.
++ // Returns whether the page was asked. OnTabBecameActive() closes the window.
++ bool CraOnTabHidden();
++
+ void set_clock_for_testing(const base::TickClock* testing_clock) {
+ clock_ = testing_clock;
+ }
diff --git a/scripts/cef-patches/freezing-vote.patch b/scripts/cef-patches/freezing-vote.patch
index a7ce008..371af73 100644
--- a/scripts/cef-patches/freezing-vote.patch
+++ b/scripts/cef-patches/freezing-vote.patch
@@ -11,10 +11,10 @@ index dd0a558c0..a54f79de4 100644
"//components/pref_registry",
"//components/printing/browser",
diff --git a/cef/libcef/browser/devtools/devtools_controller.cc b/cef/libcef/browser/devtools/devtools_controller.cc
-index c60f22d1a..d06000302 100644
+index c60f22d..3be66a2 100644
--- a/cef/libcef/browser/devtools/devtools_controller.cc
+++ b/cef/libcef/browser/devtools/devtools_controller.cc
-@@ -5,10 +5,149 @@
+@@ -5,10 +5,268 @@
#include "cef/libcef/browser/devtools/devtools_controller.h"
#include "base/json/json_reader.h"
@@ -25,9 +25,12 @@ index c60f22d1a..d06000302 100644
+#include "base/task/sequenced_task_runner.h"
#include "cef/libcef/browser/devtools/devtools_util.h"
#include "cef/libcef/browser/thread_util.h"
++#include "chrome/browser/picture_in_picture/auto_picture_in_picture_tab_helper.h"
++#include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
+#include "components/performance_manager/freezing/freezing_policy.h"
+#include "components/performance_manager/public/freezing/freezing.h"
+#include "components/performance_manager/public/performance_manager.h"
++#include "content/browser/media/session/media_session_impl.h"
#include "content/public/browser/devtools_agent_host.h"
+#include "content/public/browser/navigation_controller.h"
+#include "content/public/browser/render_frame_host.h"
@@ -58,6 +61,112 @@ index c60f22d1a..d06000302 100644
+ return list;
+}
+
++// Cra: the page's media session as Chromium routes it (the frame whose
++// navigator.mediaSession handlers answer), like Arc's media actions. Unlike a
++// wrapper around setActionHandler in the page, this sees every handler however
++// early the page registered it.
++struct CraMediaSessionActionName {
++ media_session::mojom::MediaSessionAction action;
++ const char* name;
++};
++constexpr CraMediaSessionActionName kCraMediaSessionActions[] = {
++ {media_session::mojom::MediaSessionAction::kPlay, "play"},
++ {media_session::mojom::MediaSessionAction::kPause, "pause"},
++ {media_session::mojom::MediaSessionAction::kPreviousTrack, "previoustrack"},
++ {media_session::mojom::MediaSessionAction::kNextTrack, "nexttrack"},
++ {media_session::mojom::MediaSessionAction::kSeekBackward, "seekbackward"},
++ {media_session::mojom::MediaSessionAction::kSeekForward, "seekforward"},
++ {media_session::mojom::MediaSessionAction::kSkipAd, "skipad"},
++ {media_session::mojom::MediaSessionAction::kStop, "stop"},
++ {media_session::mojom::MediaSessionAction::kToggleMicrophone,
++ "togglemicrophone"},
++ {media_session::mojom::MediaSessionAction::kToggleCamera, "togglecamera"},
++ {media_session::mojom::MediaSessionAction::kHangUp, "hangup"},
++ {media_session::mojom::MediaSessionAction::kPreviousSlide,
++ "previousslide"},
++ {media_session::mojom::MediaSessionAction::kNextSlide, "nextslide"},
++};
++
++// {"id":N,"method":"Cra.mediaSession"}: {"actions":[names],
++// "pictureInPicture":bool}, the actions the page has handlers for and whether
++// this page has the Picture in Picture window.
++// {"id":N,"method":"Cra.mediaSession","params":{"action":name}}: runs the
++// page's handler for it, as Chrome's media keys and global media controls do;
++// "handled" is false when the page has none.
++void HandleCraMediaSession(content::WebContents* contents,
++ const base::DictValue* params,
++ base::DictValue* result,
++ std::string* error) {
++ auto* session = static_cast<content::MediaSessionImpl*>(
++ content::MediaSession::GetIfExists(contents));
++ auto* pip = PictureInPictureWindowManager::GetInstance();
++ const bool has_pip = pip->GetWebContents() == contents;
++ result->Set("pictureInPicture", has_pip);
++ const std::string* name = params ? params->FindString("action") : nullptr;
++ if (!name) {
++ base::ListValue actions;
++ for (const auto& entry : kCraMediaSessionActions) {
++ if (session && session->ShouldRouteAction(entry.action)) {
++ actions.Append(entry.name);
++ }
++ }
++ result->Set("actions", std::move(actions));
++ return;
++ }
++ const CraMediaSessionActionName* found = nullptr;
++ for (const auto& entry : kCraMediaSessionActions) {
++ if (*name == entry.name) {
++ found = &entry;
++ }
++ }
++ if (!found) {
++ *error = "unknown media session action";
++ return;
++ }
++ const bool routed = session && session->ShouldRouteAction(found->action);
++ if (routed) {
++ session->DidReceiveAction(found->action);
++ }
++ result->Set("handled", routed);
++}
++
++// Cra: Chrome's automatic Picture in Picture (AutoPictureInPictureTabHelper),
++// which a tab strip drives in Chrome and the client drives here.
++// {"id":N,"method":"Cra.autoPictureInPicture","params":{"tab":"hidden"}}: the
++// tab went out of sight. A page that registered an enterpictureinpicture media
++// session handler and uses the camera or microphone (a Google Meet call) has it
++// run, with the reason "contentoccluded" and the browser's authorization to
++// open its Picture in Picture window; {"asked":bool}. Chrome's per-site
++// automatic picture-in-picture permission applies, and nothing replaces a
++// Picture in Picture window that is already open ({"pictureInPicture":true}
++// when this page has it).
++// {"id":N,"method":"Cra.autoPictureInPicture","params":{"tab":"shown"}}: the
++// tab is in front again, which closes the window automatic Picture in Picture
++// opened, as Chrome does.
++void HandleCraAutoPictureInPicture(content::WebContents* contents,
++ const base::DictValue* params,
++ base::DictValue* result,
++ std::string* error) {
++ auto* helper = AutoPictureInPictureTabHelper::FromWebContents(contents);
++ const std::string* tab = params ? params->FindString("tab") : nullptr;
++ if (!helper) {
++ *error = "no automatic Picture in Picture for this page";
++ return;
++ }
++ if (tab && *tab == "shown") {
++ helper->OnTabBecameActive();
++ return;
++ }
++ if (!tab || *tab != "hidden") {
++ *error = "tab must be hidden or shown";
++ return;
++ }
++ result->Set("pictureInPicture",
++ PictureInPictureWindowManager::GetInstance()->GetWebContents() ==
++ contents);
++ result->Set("asked", helper->CraOnTabHidden());
++}
++
+// {"id":N,"method":"Cra.setFreezingVote","params":{"vote":true|false}}: sets
+// or drops the vote. {"id":N,"method":"Cra.getFreezingState"}: whether the
+// page has Cra's vote, is frozen, and why the policy won't freeze it.
@@ -85,10 +194,20 @@ index c60f22d1a..d06000302 100644
+ std::optional<int> id = dict->FindInt("id");
+ if (!method || !id ||
+ (*method != "Cra.setFreezingVote" && *method != "Cra.getFreezingState" &&
-+ *method != "Cra.discard" && *method != "Cra.load")) {
++ *method != "Cra.discard" && *method != "Cra.load" &&
++ *method != "Cra.mediaSession" && *method != "Cra.autoPictureInPicture")) {
+ return false;
+ }
+ *message_id = *id;
++ if (*method == "Cra.autoPictureInPicture") {
++ HandleCraAutoPictureInPicture(contents, dict->FindDict("params"), result,
++ error);
++ return true;
++ }
++ if (*method == "Cra.mediaSession") {
++ HandleCraMediaSession(contents, dict->FindDict("params"), result, error);
++ return true;
++ }
+ if (*method == "Cra.load") {
+ // Does nothing unless the page was discarded and hasn't loaded since.
+ contents->GetController().LoadIfNecessary();
@@ -164,7 +283,7 @@ index c60f22d1a..d06000302 100644
CefDevToolsController::CefDevToolsController(
content::WebContents* inspected_contents)
-@@ -30,6 +169,36 @@ CefDevToolsController::~CefDevToolsController() {
+@@ -30,6 +288,36 @@ CefDevToolsController::~CefDevToolsController() {
bool CefDevToolsController::SendDevToolsMessage(
const std::string_view& message) {
CEF_REQUIRE_UIT();
diff --git a/scripts/fetch-cef.sh b/scripts/fetch-cef.sh
index c1f9660..5b4fa46 100755
--- a/scripts/fetch-cef.sh
+++ b/scripts/fetch-cef.sh
@@ -13,7 +13,7 @@ CEF_VERSION="${CEF_VERSION:-156.0.15+gcf671c0+chromium-156.0.8078.80}"
ARCH="${CEF_ARCH:-macosarm64}"
NAME="cef_binary_${CEF_VERSION}_${ARCH}_minimal"
# Bump the suffix (codecs2, …) when the build changes but CEF_VERSION does not.
-CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs12}"
+CEF_RELEASE="${CEF_RELEASE:-cef-${CEF_VERSION%%+*}-codecs13}"
URL="${CEF_URL:-https://github.com/VictorKildahl/cra/releases/download/${CEF_RELEASE}/cef_binary_${ARCH}_minimal.tar.bz2}"
mkdir -p vendor