Calls: portrait video — fit a camera of another shape than its place, with its backdrop (WIP)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
20 files changed,
+1,319
−139
Makefile+1 −1internal/calls/static/calls.css+49 −0internal/calls/static/room.js+122 −17internal/callstest/native_browser_test.go+41 −0native/apple/Sources/CallsInterop/Interop.swift+25 −0native/apple/Sources/CallsInterop/PortraitProbe.swift+39 −0native/apple/Sources/CallsInterop/StageSnapshots.swift+55 −0native/apple/Sources/CallsKit/CallChrome.swift+12 −3native/apple/Sources/CallsKit/CallFixtures.swift+106 −16native/apple/Sources/CallsKit/MacCallView.swift+6 −2native/apple/Sources/CallsKit/MacFullWindowCall.swift+4 −2native/apple/Sources/CallsKit/MacVideoTile.swift+115 −16native/apple/Sources/CallsKit/MiniWindow.swift+4 −1native/apple/Sources/CallsKit/ScreenBackdrop.swift+142 −62native/apple/Sources/CallsKit/VideoShape.swift+131 −0native/apple/Tests/CallsKitTests/VideoShapeTests.swift+205 −0native/ios/Sources/CallsPhone.swift+84 −17native/ios/Sources/PhoneFullScreenCall.swift+4 −2test/browser/native-portrait.mjs+119 −0test/browser/portrait-camera.mjs+55 −0
diff --git a/Makefile b/Makefile| index 976b7e1..662fb97 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -180,7 +180,7 @@ native-browser: native-mac |
| # The gate runs CallsInterop, which native-mac does not build; without |
| # this it runs whatever binary a previous build left behind. |
| swift build --package-path native/apple --product CallsInterop |
| - CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CGO_ENABLED=0 go test -tags browser -count=1 -timeout 25m -run 'TestNative(MacBarLayout|MacCallsBrowser|MacChat|MacScreenMotion|MacScreenRecovery|BrowserAuthentication|BrowserAppLink|MacAudioSelfTest|MacAudioStartStall)' -v ./internal/callstest/ |
| + CALLS_DEEPFILTER_MODEL=$(CURDIR)/native/build/DeepFilterNet3_onnx.tar.gz CGO_ENABLED=0 go test -tags browser -count=1 -timeout 25m -run 'TestNative(MacBarLayout|MacCallsBrowser|MacChat|MacScreenMotion|MacScreenRecovery|MacPortraitVideo|BrowserAuthentication|BrowserAppLink|MacAudioSelfTest|MacAudioStartStall)' -v ./internal/callstest/ |
| # The Mac app in a call with Playwright's WebKit (not iOS Safari; see |
| # test/browser/native-webkit.mjs): codecs, Opus FEC, a thin path, and the |
diff --git a/internal/calls/static/calls.css b/internal/calls/static/calls.css| index d22ccfc..d102ff9 100644 |
| --- a/internal/calls/static/calls.css |
| +++ b/internal/calls/static/calls.css |
| @@ -660,6 +660,48 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| } |
| .calls-window #tiles > [data-stage].calls-tile-share video { background: transparent; } |
| +/* Portrait video (2026-10-21): a camera of another shape than its tile |
| + or window — a phone held upright on a landscape stage, a laptop on an |
| + upright phone — is shown whole and centred rather than cropped to a |
| + slice, with its own picture soft and dimmed around it, as a screen on |
| + the stage is. room.js's placeTile decides (data-fit, from videoFits: |
| + a crop of 15% or less still fills) and paintBackdrops draws the |
| + canvas, for at most eight tiles; past that a fitted tile has the dark |
| + surface alone (data-backdrop="plain"). The tile keeps its shape, so |
| + the grid and the filmstrip stay tidy. */ |
| +.calls-tile[data-fit='1'] { background: #0b0b0c; } |
| +.calls-tile[data-fit='1'] video { |
| + position: relative; |
| + object-fit: contain; |
| + object-position: 50% 50%; |
| +} |
| +.calls-tile[data-fit='1'] > .calls-tile-backdrop { |
| + display: block; |
| + position: absolute; |
| + inset: -8%; |
| + inline-size: 116%; |
| + block-size: 116%; |
| + filter: blur(10px); |
| + opacity: 0.45; |
| + pointer-events: none; |
| +} |
| +.calls-window #tiles > [data-stage][data-fit='1'] > .calls-tile-backdrop { filter: blur(18px); } |
| +.calls-tile[data-fit='1'][data-backdrop='plain'] > .calls-tile-backdrop { display: none; } |
| +/* A turn mid-call eases: the picture comes up from dim into its new |
| + place, and its backdrop with it. Nothing moves under reduced motion. */ |
| +@media (prefers-reduced-motion: no-preference) { |
| + .calls-tile[data-refit] video { animation: calls-refit 0.3s ease-out; } |
| + .calls-tile[data-refit='1'] > .calls-tile-backdrop { animation: calls-backdrop-in 0.4s ease-out; } |
| +} |
| +@keyframes calls-refit { |
| + from { opacity: 0.4; } |
| + to { opacity: 1; } |
| +} |
| +@keyframes calls-backdrop-in { |
| + from { opacity: 0; } |
| + to { opacity: 0.45; } |
| +} |
| + |
| /* Speaker view (0.4.0): the stage fills the whole window, edge to edge, |
| as FaceTime's does, and the filmstrip floats over its bottom — tiles a |
| sixth of the window high, 72 to 120px, centred while they fit and |
| @@ -748,6 +790,13 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| .calls-window:has(.calls-chat-overlay:not([hidden])) #tiles:not([data-corner='top-left'], [data-corner='bottom-left']) > .calls-tile-pip { |
| inset-inline-end: calc(12px + min(320px, 100cqw - 24px) + 12px); |
| } |
| +/* An upright camera (a phone held upright, yours) floats upright: 9:16 |
| + at the height a landscape self view would have times 1.6, rather than |
| + cropped to a landscape sliver (2026-10-21; PiPLayout in the apps). */ |
| +.calls-window #tiles > .calls-tile-pip[data-shape='portrait'] { |
| + inline-size: clamp(90px, 10.125cqw, 132px); |
| + aspect-ratio: 9 / 16; |
| +} |
| .calls-window #tiles > .calls-tile-pip.calls-tile-dragging { transition: none; z-index: 4; cursor: grabbing; } |
| .calls-window #tiles > .calls-tile-pip .calls-tile-name { inset-block-end: 6px; inset-inline-start: 6px; } |
diff --git a/internal/calls/static/room.js b/internal/calls/static/room.js| index 4fd5382..c25da76 100644 |
| --- a/internal/calls/static/room.js |
| +++ b/internal/calls/static/room.js |
| @@ -5830,20 +5830,35 @@ |
| } |
| const wake = screenWake(navigator, document); |
| - // paintBackdrops draws the shared screen on the stage, if there is one, |
| - // into its 64 × 36 backdrop canvas: what calls.css enlarges, blurs and |
| - // dims around the fitted screen instead of black bars (2026-10-05, as |
| - // FaceTime; the native apps' ScreenBackdrop). Twice a second, and only |
| - // for the screen on the stage in a visible tab: one small drawImage, |
| - // whose cost is kept on the canvas (data-cost-ms, the slowest so far) |
| - // for the browser gate to report. |
| + // paintBackdrops draws each fitted picture into its tile's small |
| + // backdrop canvas: what calls.css enlarges, blurs and dims around it |
| + // instead of bars (2026-10-05, as FaceTime; the native apps' |
| + // ScreenBackdrop). The shared screen on the stage, and since 2026-10-21 |
| + // every camera fitted whole because it is another shape than its tile |
| + // (placeTile). Twice a second, in a visible tab, the stage first and at |
| + // most BACKDROP_LIMIT of them; a fitted tile past the limit is marked |
| + // data-backdrop="plain" and keeps the dark surface alone. Each paint is |
| + // one small drawImage, whose cost is kept on the canvas (data-cost-ms, |
| + // the slowest so far) for the browser gate to report. |
| const BACKDROP_W = 64; |
| const BACKDROP_H = 36; |
| const BACKDROP_EVERY = 500; |
| + const BACKDROP_LIMIT = 8; |
| function paintBackdrops() { |
| if (document.visibilityState !== 'visible') return; |
| - const fig = document.querySelector('#tiles > [data-stage].calls-tile-share'); |
| - if (!fig) return; |
| + const figs = Array.from(document.querySelectorAll( |
| + '#tiles > [data-stage].calls-tile-share, #tiles > [data-fit="1"]')); |
| + figs.sort((a, b) => (b.hasAttribute('data-stage') ? 1 : 0) - (a.hasAttribute('data-stage') ? 1 : 0)); |
| + figs.forEach((fig, i) => { |
| + const plain = i >= BACKDROP_LIMIT; |
| + if (plain !== (fig.dataset.backdrop === 'plain')) { |
| + if (plain) fig.dataset.backdrop = 'plain'; |
| + else delete fig.dataset.backdrop; |
| + } |
| + if (!plain) paintBackdrop(fig); |
| + }); |
| + } |
| + function paintBackdrop(fig) { |
| const video = fig.querySelector('video'); |
| const canvas = fig.querySelector('.calls-tile-backdrop'); |
| if (!video || !canvas || video.readyState < 2 || !video.videoWidth) return; |
| @@ -5851,7 +5866,7 @@ |
| if (!ctx) return; |
| const t0 = performance.now(); |
| try { |
| - ctx.drawImage(video, 0, 0, BACKDROP_W, BACKDROP_H); |
| + ctx.drawImage(video, 0, 0, canvas.width, canvas.height); |
| } catch (err) { |
| return; |
| } |
| @@ -5861,6 +5876,87 @@ |
| canvas.dataset.painted = String((parseInt(canvas.dataset.painted || '0', 10) || 0) + 1); |
| } |
| + // Portrait video (2026-10-21, Paul, after Farshad joined from an |
| + // iPhone held upright: "Can we detect vertical video and display it |
| + // appropriately?"). Since 0.4.10 a camera on the stage fills the |
| + // window, which cut a 9:16 face to a thin slice of a landscape window. |
| + // The native apps' VideoShape, VideoShapeReading and VideoPlacement |
| + // decide the same way, with the same numbers. |
| + // |
| + // videoShape is a picture's shape as displayed (the element's |
| + // videoWidth and videoHeight have the sender's rotation applied): |
| + // portrait when h > w × 1.1, landscape when w > h × 1.1, square-ish |
| + // between. `was` is its shape so far, held until the picture is no |
| + // longer taller (or wider) than it is long — hysteresis, so a phone |
| + // turned mid-call switches once and a picture near square never flaps. |
| + const SHAPE_ENTER = 1.1; |
| + const SHAPE_HOLD = 1.0; |
| + const FIT_TOLERANCE = 0.15; |
| + function videoShape(w, h, was) { |
| + if (!(w > 0) || !(h > 0)) return was || 'landscape'; |
| + if (was === 'portrait' && h > w * SHAPE_HOLD) return 'portrait'; |
| + if (was === 'landscape' && w > h * SHAPE_HOLD) return 'landscape'; |
| + if (h > w * SHAPE_ENTER) return 'portrait'; |
| + if (w > h * SHAPE_ENTER) return 'landscape'; |
| + return 'square'; |
| + } |
| + |
| + // videoFits is fill or fit: a screen is always shown whole; a camera |
| + // of the same shape as its tile or window fills it, as in 0.4.10; one |
| + // of another shape is shown whole, centred, over its own picture soft |
| + // and dimmed — unless filling would cut no more than FIT_TOLERANCE of |
| + // a dimension, when the bars are not worth it and it fills anyway. |
| + function videoFits(vw, vh, shape, bw, bh, screen) { |
| + if (screen) return true; |
| + if (!(vw > 0) || !(vh > 0) || !(bw > 0) || !(bh > 0)) return false; |
| + const across = bw / vw; |
| + const down = bh / vh; |
| + const crop = 1 - Math.min(across, down) / Math.max(across, down); |
| + if (crop <= FIT_TOLERANCE) return false; |
| + return shape !== videoShape(bw, bh, ''); |
| + } |
| + |
| + // placeTile applies both to one tile, whenever its picture or its box |
| + // changes size (the element's resize event, and tileBoxes below): |
| + // data-shape for calls.css's upright self view, data-fit for a camera |
| + // shown whole with its backdrop, and data-refit for a moment when a |
| + // turn changes that, so the change eases rather than jumps. |
| + function placeTile(t) { |
| + if (!t || !t.video || !t.figure) return; |
| + const fig = t.figure; |
| + const vw = t.video.videoWidth; |
| + const vh = t.video.videoHeight; |
| + if (!vw || !vh) return; |
| + t.shape = videoShape(vw, vh, t.shape); |
| + if (fig.dataset.shape !== t.shape) fig.dataset.shape = t.shape; |
| + if (fig.classList.contains('calls-tile-share')) return; |
| + const canvas = fig.querySelector('.calls-tile-backdrop'); |
| + if (canvas) { |
| + const w = t.shape === 'portrait' ? BACKDROP_H : t.shape === 'square' ? 48 : BACKDROP_W; |
| + const h = t.shape === 'portrait' ? BACKDROP_W : t.shape === 'square' ? 48 : BACKDROP_H; |
| + if (canvas.width !== w) canvas.width = w; |
| + if (canvas.height !== h) canvas.height = h; |
| + } |
| + const fit = videoFits(vw, vh, t.shape, fig.clientWidth, fig.clientHeight, false) ? '1' : '0'; |
| + if (fig.dataset.fit === fit) return; |
| + const turned = fig.dataset.fit !== undefined; |
| + fig.dataset.fit = fit; |
| + if (fit === '1') paintBackdrop(fig); |
| + if (turned) { |
| + fig.dataset.refit = fit; |
| + clearTimeout(t.refitTimer); |
| + t.refitTimer = setTimeout(() => { delete fig.dataset.refit; }, 400); |
| + } |
| + } |
| + // One observer for every tile's box: the window resized, the layout |
| + // changed, a tile moved onto the stage or into the filmstrip. |
| + const tileOf = new WeakMap(); |
| + const tileBoxes = typeof ResizeObserver === 'function' |
| + ? new ResizeObserver((entries) => { |
| + for (const entry of entries) placeTile(tileOf.get(entry.target)); |
| + }) |
| + : null; |
| + |
| // tileMarks builds one tile's pair of marks from the server's |
| // templates: the muted badge beside the name, and the camera-off cover |
| // over the video. The cover sits over the element rather than hiding |
| @@ -6729,6 +6825,7 @@ |
| } |
| for (const key of Array.from(tiles.keys())) { |
| if (!wanted.includes(key)) { |
| + if (tileBoxes) tileBoxes.unobserve(tiles.get(key).figure); |
| tiles.get(key).figure.remove(); |
| tiles.delete(key); |
| // A tile that has gone cannot be blocked any more. |
| @@ -6802,14 +6899,16 @@ |
| // screen into the tile instead of cropping it to fill. |
| if (key.slice(-SHARE_SUFFIX.length) === SHARE_SUFFIX) { |
| figure.classList.add('calls-tile-share'); |
| - // What surrounds the fitted screen on the stage (paintBackdrops). |
| - const backdrop = document.createElement('canvas'); |
| - backdrop.className = 'calls-tile-backdrop'; |
| - backdrop.width = BACKDROP_W; |
| - backdrop.height = BACKDROP_H; |
| - backdrop.setAttribute('aria-hidden', 'true'); |
| - figure.append(backdrop); |
| } |
| + // What surrounds a fitted picture: the screen on the stage, or a |
| + // camera of another shape than its tile (paintBackdrops). Under the |
| + // video, which comes after it. |
| + const backdrop = document.createElement('canvas'); |
| + backdrop.className = 'calls-tile-backdrop'; |
| + backdrop.width = BACKDROP_W; |
| + backdrop.height = BACKDROP_H; |
| + backdrop.setAttribute('aria-hidden', 'true'); |
| + figure.append(backdrop); |
| const label = document.createElement('figcaption'); |
| label.className = 'calls-tile-name'; |
| const nameEl = document.createElement('span'); |
| @@ -6859,6 +6958,12 @@ |
| }; |
| tiles.set(key, t); |
| if (!isSelf) applySink(video); |
| + // Portrait video: the picture's own size changes on a turn or a |
| + // resolution step, the tile's with the layout. |
| + video.addEventListener('resize', () => placeTile(t)); |
| + video.addEventListener('loadedmetadata', () => placeTile(t)); |
| + tileOf.set(figure, t); |
| + if (tileBoxes) tileBoxes.observe(figure); |
| } |
| t.nameEl.textContent = isSelf ? name + ' (you)' : name; |
| // call-layout.js keeps this viewer's order by name, which survives a |
diff --git a/internal/callstest/native_browser_test.go b/internal/callstest/native_browser_test.go| index e51c3d3..0d75c56 100644 |
| --- a/internal/callstest/native_browser_test.go |
| +++ b/internal/callstest/native_browser_test.go |
| @@ -427,6 +427,47 @@ func TestNativeMacScreenMotion(t *testing.T) { |
| } |
| } |
| +// TestNativeMacPortraitVideo is portrait video on the Mac (2026-10-21, |
| +// after Farshad joined from an iPhone held upright and the 0.4.10 stage |
| +// cropped him to a slice): the browser's camera is upright, and the app's |
| +// real full-window call, live and off screen, must show it whole with a |
| +// backdrop, fill again once it is turned on its side, switching once, and |
| +// fit a landscape picture in an upright window. test/browser/native-portrait.mjs |
| +// has the steps. |
| +func TestNativeMacPortraitVideo(t *testing.T) { |
| + rig := newBrowserRig(t) |
| + room, _ := rig.createMeeting(t) |
| + root, err := filepath.Abs("../..") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + binary := filepath.Join(root, "native/apple/.build/debug/CallsInterop") |
| + if _, err := os.Stat(binary); err != nil { |
| + t.Fatal("build native interop executable with make native-mac first") |
| + } |
| + ctx, cancel := context.WithTimeout(t.Context(), 180*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, "node", filepath.Join(root, "test/browser/native-portrait.mjs"), rig.origin, room, binary) |
| + cookies, _ := json.Marshal([]map[string]string{{"name": rig.cookieName, "value": rig.cookieB}}) |
| + input, _ := json.Marshal(map[string]string{"origin": rig.origin, "room": room, "cookies": string(cookies)}) |
| + cmd.Env = append(os.Environ(), "CALLS_COOKIE_NAME="+rig.cookieName, "CALLS_COOKIE_A="+rig.cookieA, "CALLS_NATIVE_INPUT="+string(input)) |
| + out, err := cmd.StdoutPipe() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cmd.Stderr = cmd.Stdout |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + scanner := bufio.NewScanner(out) |
| + for scanner.Scan() { |
| + t.Log(scanner.Text()) |
| + } |
| + if err := cmd.Wait(); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| // TestNativeMacScreenRecovery is Paul's report of 2026-09-28 — "after a |
| // while, my screen froze on her end … I had to stop and re-share" — held |
| // as a gate: the app shares its screen to a browser while the call is |
diff --git a/native/apple/Sources/CallsInterop/Interop.swift b/native/apple/Sources/CallsInterop/Interop.swift| index 3a61045..2c3c2a0 100644 |
| --- a/native/apple/Sources/CallsInterop/Interop.swift |
| +++ b/native/apple/Sources/CallsInterop/Interop.swift |
| @@ -19,6 +19,7 @@ struct Input: Decodable { |
| @MainActor static var display: DisplayCapture? |
| @MainActor static var webrtcLogger: LKRTCCallbackLogger? |
| @MainActor static let cameras = SyntheticCameras() |
| + @MainActor static var stage: StagePreview? |
| // A defaults domain of its own, so the gate's camera choices are never |
| // remembered into anyone's real preferences. |
| @MainActor static let camera = ManagedCamera( |
| @@ -74,6 +75,14 @@ struct Input: Decodable { |
| } catch { exit(1) } |
| return |
| } |
| + if CommandLine.arguments.count >= 3, CommandLine.arguments[1] == "--portrait-snapshots" { |
| + do { |
| + try await PortraitSnapshots.save( |
| + to: URL(fileURLWithPath: CommandLine.arguments[2]), |
| + before: CommandLine.arguments.dropFirst(3).contains("before")) |
| + } catch { exit(1) } |
| + return |
| + } |
| if CommandLine.arguments.count == 3, CommandLine.arguments[1] == "--bar-layout" { |
| exit(await BarLayoutHarness.run(to: URL(fileURLWithPath: CommandLine.arguments[2])) ? 0 : 1) |
| } |
| @@ -138,6 +147,22 @@ struct Input: Decodable { |
| print("{\"muted\":\(await call.muted)}") |
| fflush(stdout) |
| } |
| + // Portrait video (2026-10-21): the full-window call, live, off |
| + // screen, and where its pictures are placed. |
| + if command.hasPrefix("stage-open") { |
| + let dims = command.split(separator: " ").dropFirst().compactMap { Double($0) } |
| + let size = dims.count == 2 ? NSSize(width: dims[0], height: dims[1]) : NSSize(width: 1000, height: 640) |
| + await MainActor.run { |
| + if let stage = Interop.stage { stage.resize(size) } else { Interop.stage = StagePreview(call: call, size: size) } |
| + } |
| + print("{\"stageOpen\":true}") |
| + fflush(stdout) |
| + } |
| + if command == "placement" { |
| + let line = await MainActor.run { Interop.stage?.placements() ?? "{}" } |
| + print(line) |
| + fflush(stdout) |
| + } |
| if command == "chat" { |
| await call.sendChat("native chat probe") |
| print("{\"chatCommandHandled\":true}") |
diff --git a/native/apple/Sources/CallsInterop/PortraitProbe.swift b/native/apple/Sources/CallsInterop/PortraitProbe.swift| new file mode 100644 |
| index 0000000..a98b115 |
| --- /dev/null |
| +++ b/native/apple/Sources/CallsInterop/PortraitProbe.swift |
| @@ -0,0 +1,39 @@ |
| +import AppKit |
| +@_spi(Fixtures) import CallsKit |
| +import SwiftUI |
| + |
| +/// The real full-window call, live, in a window off screen, for the |
| +/// portrait gate (test/browser/native-portrait.mjs): where each picture is |
| +/// placed, read back from the video views themselves (VideoPlacementProbe), |
| +/// not from a fixture. Opened by the `stage-open` command. |
| +@MainActor final class StagePreview { |
| + let window: NSWindow |
| + let view: NSHostingView<AnyView> |
| + init(call: Call, size: NSSize) { |
| + NSApplication.shared.setActivationPolicy(.prohibited) |
| + view = NSHostingView( |
| + rootView: AnyView( |
| + MacCallView(call: call, grid: false, style: .fullWindow, controlsShown: false, leave: {}, rejoin: {}) |
| + .environment(\.colorScheme, .dark))) |
| + window = NSWindow( |
| + contentRect: NSRect(x: -4000, y: -4000, width: size.width, height: size.height), |
| + styleMask: [.borderless], backing: .buffered, defer: false) |
| + window.isReleasedWhenClosed = false |
| + window.contentView = view |
| + window.orderFront(nil) |
| + } |
| + |
| + /// Every picture's placement, after a layout pass, as one JSON line. |
| + func placements() -> String { |
| + view.layoutSubtreeIfNeeded() |
| + let report: [String: Any] = [ |
| + "placements": VideoPlacementProbe.placements, "backdrops": VideoPlacementProbe.backdrops, |
| + ] |
| + guard let data = try? JSONSerialization.data(withJSONObject: report), |
| + let line = String(data: data, encoding: .utf8) |
| + else { return "{}" } |
| + return line |
| + } |
| + |
| + func resize(_ size: NSSize) { window.setContentSize(size) } |
| +} |
diff --git a/native/apple/Sources/CallsInterop/StageSnapshots.swift b/native/apple/Sources/CallsInterop/StageSnapshots.swift| index 5b61f45..bbf2c38 100644 |
| --- a/native/apple/Sources/CallsInterop/StageSnapshots.swift |
| +++ b/native/apple/Sources/CallsInterop/StageSnapshots.swift |
| @@ -64,3 +64,58 @@ import SwiftUI |
| try await LobbySnapshots.render(content, scheme: .dark, size: size, to: file) |
| } |
| } |
| + |
| +/// Portrait video (2026-10-21), before and after: a phone held upright |
| +/// (Ana, 720 × 1280) and a laptop (Li, 1280 × 720) as the stage, in the |
| +/// filmstrip, in Grid and in the mini window. `before` draws 0.4.10's |
| +/// placement, every camera filling; after, a camera of another shape than |
| +/// its tile is fitted whole with its picture soft behind it. After also |
| +/// has an upright self view, floating upright. |
| +@MainActor enum PortraitSnapshots { |
| + static func save(to folder: URL, before: Bool) async throws { |
| + NSApplication.shared.setActivationPolicy(.prohibited) |
| + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
| + FixtureVideo.fillsEveryCamera = before |
| + defer { FixtureVideo.fillsEveryCamera = false } |
| + let tag = before ? "before" : "after" |
| + let feeds = FixtureFeeds.parse("ana=720x1280,li=1280x720,me=1280x720") |
| + func shot( |
| + _ name: String, _ fixture: CallFixture = .grid, grid: Bool = false, speaker: String?, |
| + feeds: [String: CGSize] = feeds, size: CGSize = CGSize(width: 1000, height: 640) |
| + ) async throws { |
| + let call = Call(playAudio: false) |
| + fixture.apply(to: call) |
| + call.levels.speaker.showFixture(speaker) |
| + try await LobbySnapshots.render( |
| + MacCallView( |
| + call: call, grid: grid, style: .fullWindow, controlsShown: false, leave: {}, rejoin: {} |
| + ) |
| + .tint(CallsAppearance.accent) |
| + .environment(\.fixtureStagePicture, .busy) |
| + .environment(\.fixtureFeeds, feeds), |
| + scheme: .dark, size: size, to: folder.appendingPathComponent("mac-\(name)-\(tag).png")) |
| + } |
| + // The stage: Ana's upright phone, with Li's laptop in the filmstrip; |
| + // then Li's laptop on the stage, with Ana in the filmstrip. |
| + try await shot("stage-portrait", speaker: "ana") |
| + try await shot("stage-landscape-filmstrip-portrait", speaker: "li") |
| + try await shot("grid", grid: true, speaker: "ana") |
| + // A call of two: Ana fills the window's stage, and you float. |
| + try await shot("stage-portrait-two", .focus, speaker: "ana") |
| + if !before { |
| + var upright = feeds |
| + upright["me"] = CGSize(width: 720, height: 1280) |
| + try await shot("self-portrait", .focus, speaker: "ana", feeds: upright) |
| + } |
| + for (who, label) in [("ana", "portrait"), ("li", "landscape")] { |
| + let call = Call(playAudio: false) |
| + CallFixture.grid.apply(to: call) |
| + call.levels.speaker.showFixture(who) |
| + try await LobbySnapshots.render( |
| + MiniWindowSnapshot.window(call: call, hovering: false).environment(\.fixtureFeeds, feeds), |
| + scheme: .dark, |
| + size: CGSize(width: MiniWindowRules.size.width, height: MiniWindowRules.size.width / MiniWindowRules.aspect), |
| + to: folder.appendingPathComponent("mac-mini-\(label)-\(tag).png")) |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/CallsKit/CallChrome.swift b/native/apple/Sources/CallsKit/CallChrome.swift| index 5d73ac6..dc7be65 100644 |
| --- a/native/apple/Sources/CallsKit/CallChrome.swift |
| +++ b/native/apple/Sources/CallsKit/CallChrome.swift |
| @@ -273,13 +273,22 @@ public enum PiPLayout { |
| /// The self view's size in a stage of `container`: about a fifth of the |
| /// width on a Mac (16:9), a little over a quarter on a phone, upright |
| - /// in portrait since that is how a phone's camera sees you. |
| - public static func size(in container: CGSize, touch: Bool) -> CGSize { |
| + /// in portrait since that is how a phone's camera sees you. `shape` is |
| + /// your own picture's, once it is known (2026-10-21): a camera that |
| + /// sends upright floats upright, wherever it is, rather than cropped to |
| + /// a landscape sliver, and a phone's turned camera turns its view. |
| + public static func size(in container: CGSize, touch: Bool, shape: VideoShape? = nil) -> CGSize { |
| if touch { |
| - let portrait = container.height >= container.width |
| + let portrait = shape.map { $0 == .portrait } ?? (container.height >= container.width) |
| let width = min(max(container.width * (portrait ? 0.28 : 0.2), 88), 150) |
| return CGSize(width: width, height: (width * (portrait ? 4 / 3 : 3 / 4)).rounded()) |
| } |
| + if shape == .portrait { |
| + // The same height a landscape one would have at this window's |
| + // width, upright: 9:16, at least 90 wide. |
| + let height = (min(max(container.width * 0.2, 150), 260) * 9 / 16 * 1.6).rounded() |
| + return CGSize(width: max(90, (height * 9 / 16).rounded()), height: height) |
| + } |
| let width = min(max(container.width * 0.2, 150), 260) |
| return CGSize(width: width, height: (width * 9 / 16).rounded()) |
| } |
diff --git a/native/apple/Sources/CallsKit/CallFixtures.swift b/native/apple/Sources/CallsKit/CallFixtures.swift| index 09e8543..83375a8 100644 |
| --- a/native/apple/Sources/CallsKit/CallFixtures.swift |
| +++ b/native/apple/Sources/CallsKit/CallFixtures.swift |
| @@ -171,38 +171,128 @@ extension EnvironmentValues { |
| } |
| } |
| -/// A fixture's frame drawn as a tile draws video: placed by `VideoFrame` |
| -/// (a camera's 16:9 picture filling the tile with headroom, a screen's |
| -/// 16:10 fitted whole) and, around a screen, the same frame soft and |
| -/// dimmed as `ScreenBackdrop` draws it. |
| +private struct FixtureFeedsKey: EnvironmentKey { |
| + static let defaultValue: [String: CGSize] = [:] |
| +} |
| + |
| +extension EnvironmentValues { |
| + /// Each fixture peer's picture size as displayed ("ana": 720 × 1280 for |
| + /// a phone held upright), drawn in place of video on every tile that |
| + /// peer has; "me" is your own. Empty in a real call. |
| + @_spi(Fixtures) public var fixtureFeeds: [String: CGSize] { |
| + get { self[FixtureFeedsKey.self] } |
| + set { self[FixtureFeedsKey.self] = newValue } |
| + } |
| +} |
| + |
| +@_spi(Fixtures) public enum FixtureFeeds { |
| + /// "ana=720x1280,li=1280x720", as the iPhone's launch argument and the |
| + /// snapshot harness give them. |
| + public static func parse(_ text: String) -> [String: CGSize] { |
| + var feeds: [String: CGSize] = [:] |
| + for pair in text.split(separator: ",") { |
| + let parts = pair.split(separator: "=") |
| + guard parts.count == 2 else { continue } |
| + let dims = parts[1].split(separator: "x").compactMap { Double($0) } |
| + guard dims.count == 2, dims[0] > 0, dims[1] > 0 else { continue } |
| + feeds[String(parts[0])] = CGSize(width: dims[0], height: dims[1]) |
| + } |
| + return feeds |
| + } |
| +} |
| + |
| +/// A fixture's frame drawn as a tile draws video: placed by |
| +/// `PlacedPicture` (a camera's 16:9 picture filling the tile with |
| +/// headroom, a screen's 16:10 fitted whole, and a camera of another shape |
| +/// than the tile — `video`, a phone's 720 × 1280 — fitted whole too) and, |
| +/// around a fitted picture, the same frame soft and dimmed as |
| +/// `ScreenBackdrop` draws it. A picture of its own size is the busy |
| +/// frame with a person in it, so the snapshots show what a crop cuts. |
| @_spi(Fixtures) public struct FixtureVideo: View { |
| let picture: FixtureBackdrop |
| + let video: CGSize? |
| let screen: Bool |
| - public init(picture: FixtureBackdrop, screen: Bool) { |
| + let backdrop: Bool |
| + public init(picture: FixtureBackdrop, video: CGSize? = nil, screen: Bool, backdrop: Bool = true) { |
| self.picture = picture |
| + self.video = video |
| self.screen = screen |
| + self.backdrop = backdrop |
| } |
| public var body: some View { |
| GeometryReader { geometry in |
| let bounds = geometry.size |
| - let video = screen ? CGSize(width: 16, height: 10) : CGSize(width: 16, height: 9) |
| - let placed = VideoFrame.place(video: video, in: bounds, fit: screen) |
| + let size = video ?? (screen ? CGSize(width: 16, height: 10) : CGSize(width: 16, height: 9)) |
| + let placed = Self.placement(video: size, screen: screen, in: bounds) |
| ZStack(alignment: .topLeading) { |
| - if screen { |
| + if placed.fitted { |
| CallsAppearance.stageSurface |
| - picture.view |
| - .frame(width: bounds.width, height: bounds.height) |
| - .scaleEffect(1.15) |
| - .blur(radius: 24) |
| - .opacity(BackdropSampler.dimmed) |
| + if backdrop { |
| + // As ScreenBackdrop draws it: the picture filling the place, |
| + // a little past its edges, soft (its 64-wide sample enlarged) |
| + // and dimmed. |
| + let filled = VideoFrame.place(video: size, in: bounds, fit: false) |
| + frame |
| + .frame(width: filled.width, height: filled.height) |
| + .offset(x: filled.minX, y: filled.minY) |
| + .scaleEffect(1.15) |
| + .blur(radius: max(bounds.width, bounds.height) / 40) |
| + .opacity(BackdropSampler.dimmed) |
| + } |
| } |
| - picture.view |
| - .frame(width: placed.width, height: placed.height) |
| - .offset(x: placed.minX, y: placed.minY) |
| + frame |
| + .frame(width: placed.frame.width, height: placed.frame.height) |
| + .offset(x: placed.frame.minX, y: placed.frame.minY) |
| } |
| } |
| .clipped() |
| } |
| + |
| + @ViewBuilder private var frame: some View { |
| + if video != nil { |
| + ZStack { |
| + picture.view |
| + FixturePerson() |
| + } |
| + } else { |
| + picture.view |
| + } |
| + } |
| + |
| + /// Whether to place as 0.4.10 did, every camera filling: for the |
| + /// before-and-after snapshots of portrait video (2026-10-21). |
| + @MainActor public static var fillsEveryCamera = false |
| + |
| + @MainActor static func placement(video: CGSize, screen: Bool, in bounds: CGSize) -> (frame: CGRect, fitted: Bool) { |
| + if fillsEveryCamera, !screen { |
| + return (VideoFrame.place(video: video, in: bounds, fit: false), false) |
| + } |
| + var placed = PlacedPicture(screen: screen) |
| + placed.update(video: video) |
| + return placed.place(in: bounds) |
| + } |
| +} |
| + |
| +/// A head and shoulders, centred a little above the middle of whatever |
| +/// frame it is in, as a camera sees a person: the part a crop must keep. |
| +private struct FixturePerson: View { |
| + var body: some View { |
| + GeometryReader { geometry in |
| + let size = geometry.size |
| + let unit = min(size.width, size.height) |
| + ZStack { |
| + Ellipse().fill(Color(red: 0.24, green: 0.27, blue: 0.36)) |
| + .frame(width: unit * 0.9, height: unit * 0.55) |
| + .position(x: size.width / 2, y: size.height * 0.4 + unit * 0.5) |
| + Circle().fill(Color(red: 0.87, green: 0.68, blue: 0.55)) |
| + .frame(width: unit * 0.42) |
| + .position(x: size.width / 2, y: size.height * 0.4) |
| + Capsule().fill(Color(white: 0.15)) |
| + .frame(width: unit * 0.16, height: unit * 0.035) |
| + .position(x: size.width / 2, y: size.height * 0.4 + unit * 0.1) |
| + } |
| + } |
| + } |
| } |
| /// The warm rim on a tile's name at one level, over each kind of picture |
diff --git a/native/apple/Sources/CallsKit/MacCallView.swift b/native/apple/Sources/CallsKit/MacCallView.swift| index a3c042e..d20f409 100644 |
| --- a/native/apple/Sources/CallsKit/MacCallView.swift |
| +++ b/native/apple/Sources/CallsKit/MacCallView.swift |
| @@ -31,6 +31,10 @@ |
| @Environment(\.accessibilityReduceMotion) var reduceMotion |
| @Environment(\.accessibilityVoiceOverEnabled) var voiceOver |
| @Environment(\.fixtureBackdrop) var fixtureBackdrop |
| + @Environment(\.fixtureFeeds) var fixtureFeeds |
| + /// Your own picture's shape, once it arrives: the floating self view |
| + /// takes it (a Continuity Camera held upright floats upright). |
| + @State var selfShape: VideoShape? |
| private let style: CallLayoutStyle? |
| /// - Parameters: |
| @@ -219,13 +223,13 @@ |
| track: call.localTrack, label: "You", muted: call.muted, mirrored: true, |
| cameraOff: call.cameraOff, placeholder: call.selfPlaceholder, cornerRadius: cornerRadius, |
| compact: compact, labelLift: labelLift, backdrop: backdrop, audio: call.selfAudio, |
| - onStage: onStage, pinned: pinned, iconOnly: iconOnly) |
| + onStage: onStage, pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds["me"]) |
| case .camera(let peer): |
| return MacVideoTile( |
| track: call.remoteTracks[peer], label: call.name(of: peer), muted: call.isMuted(peer), |
| cameraOff: call.isCameraOff(peer), cornerRadius: cornerRadius, compact: compact, |
| labelLift: labelLift, backdrop: backdrop, audio: call.tileAudio(peer), onStage: onStage, |
| - pinned: pinned, iconOnly: iconOnly) |
| + pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds[peer]) |
| } |
| } |
diff --git a/native/apple/Sources/CallsKit/MacFullWindowCall.swift b/native/apple/Sources/CallsKit/MacFullWindowCall.swift| index d5f38e3..03a0f9d 100644 |
| --- a/native/apple/Sources/CallsKit/MacFullWindowCall.swift |
| +++ b/native/apple/Sources/CallsKit/MacFullWindowCall.swift |
| @@ -267,12 +267,14 @@ |
| /// Muted shows on it whether or not the controls do. |
| private func selfView(in size: CGSize) -> some View { |
| let corner = PiPCorner(rawValue: pipCorner) ?? .bottomTrailing |
| - let pip = PiPLayout.size(in: size, touch: false) |
| + let pip = PiPLayout.size( |
| + in: size, touch: false, shape: selfShape ?? fixtureFeeds["me"].map(VideoShape.of)) |
| let frame = PiPLayout.frame(corner: corner, size: pip, in: size, insets: selfInsets(in: size)) |
| return MacVideoTile( |
| track: call.localTrack, label: "You", muted: call.muted, mirrored: true, |
| cameraOff: call.cameraOff, placeholder: call.selfPlaceholder, cornerRadius: 10, |
| - compact: true, backdrop: Self.tileBackdrop, audio: call.selfAudio |
| + compact: true, backdrop: Self.tileBackdrop, audio: call.selfAudio, |
| + fixtureVideo: fixtureFeeds["me"], shaped: { selfShape = $0 } |
| ) |
| .frame(width: pip.width, height: pip.height) |
| .shadow(color: .black.opacity(0.35), radius: 8, y: 3) |
diff --git a/native/apple/Sources/CallsKit/MacVideoTile.swift b/native/apple/Sources/CallsKit/MacVideoTile.swift| index 2ba3e22..0e0efbf 100644 |
| --- a/native/apple/Sources/CallsKit/MacVideoTile.swift |
| +++ b/native/apple/Sources/CallsKit/MacVideoTile.swift |
| @@ -40,9 +40,19 @@ |
| /// hears them as the tile's value. |
| var iconOnly = false |
| + /// A fixture's picture of this size in place of video, on any tile |
| + /// (the snapshots of portrait feeds); nil in a real call. |
| + var fixtureVideo: CGSize? = nil |
| + /// Told the picture's shape as it arrives, for a self view that takes |
| + /// its camera's shape. |
| + var shaped: ((VideoShape) -> Void)? = nil |
| + |
| /// The height of the name label and what is over it, lift included, |
| /// which the placeholder keeps clear of. |
| @State private var labelBlock: CGFloat = 0 |
| + /// Whether the picture is shown whole rather than filling the tile |
| + /// (`VideoPlacement`), as the video view last laid it out. |
| + @State private var fitted = false |
| @Environment(\.fixtureStagePicture) private var fixturePicture |
| var body: some View { |
| @@ -52,13 +62,25 @@ |
| private func tile(_ info: TileAudioInfo?) -> some View { |
| ZStack { |
| backdrop |
| - if let fixturePicture, onStage, track == nil, !cameraOff, placeholder == nil { |
| + if let fixtureVideo, track == nil, !cameraOff { |
| + FixtureVideo(picture: fixturePicture ?? .busy, video: fixtureVideo, screen: screen, backdrop: !screen || onStage) |
| + .scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| + } else if let fixturePicture, onStage, track == nil, !cameraOff, placeholder == nil { |
| FixtureVideo(picture: fixturePicture, screen: screen) |
| } else if let track, !cameraOff, placeholder == nil { |
| - // A screen on the stage is fitted whole; around it, the same |
| - // picture soft and dimmed rather than black bars. |
| - if screen, onStage { ScreenBackdrop(track: track) } |
| - MacVideoView(track: track, fit: screen).scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| + // A screen on the stage is fitted whole, and so is a camera of |
| + // another shape than its tile (a phone held upright, in a |
| + // landscape window); around it, the same picture soft and |
| + // dimmed rather than bars. A screen in the filmstrip keeps its |
| + // plain bars; a fitted camera there or in the grid has its |
| + // backdrop while BackdropBudget has room. |
| + if screen ? onStage : fitted { |
| + ScreenBackdrop(track: track, budgeted: !onStage).transition(.opacity) |
| + } |
| + MacVideoView( |
| + track: track, screen: screen, |
| + fitted: { now in withAnimation(Self.refit) { fitted = now } }, shaped: shaped) |
| + .scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| } else { |
| TilePlaceholder( |
| symbol: cameraOff |
| @@ -88,6 +110,12 @@ |
| .accessibilityHint(info?.detail ?? "") |
| .accessibilityValue(cameraOff ? "Camera off" : track == nil || placeholder != nil ? waiting : "Video on") |
| } |
| + /// The backdrop's fade when a picture turns between filling and |
| + /// fitted; none under Reduce Motion. |
| + static var refit: Animation? { |
| + NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ? nil : .easeInOut(duration: 0.3) |
| + } |
| + |
| private var waiting: String { |
| cameraOff |
| ? "Camera off" : placeholder ?? (screen ? "Waiting for the screen" : "Waiting for video") |
| @@ -96,23 +124,39 @@ |
| private struct MacVideoView: NSViewRepresentable { |
| let track: RTCVideoTrack |
| - var fit = false |
| + var screen = false |
| + /// Told whenever the picture turns between filling its tile and |
| + /// being fitted whole in it. |
| + var fitted: (Bool) -> Void = { _ in } |
| + var shaped: ((VideoShape) -> Void)? = nil |
| func makeNSView(context: Context) -> FillVideoView { FillVideoView() } |
| func updateNSView(_ view: FillVideoView, context: Context) { |
| - view.fit = fit |
| + view.screen = screen |
| + view.fittedChanged = fitted |
| + view.shapeChanged = shaped |
| view.attach(track) |
| } |
| static func dismantleNSView(_ view: FillVideoView, coordinator: ()) { view.detach() } |
| } |
| /// The renderer keeps its source aspect ratio while the container crops |
| - /// overflow — or, for a screen, letterboxes it. |
| - private final class FillVideoView: NSView, RTCVideoViewDelegate { |
| + /// overflow — or, for a screen or a camera of another shape than the |
| + /// tile, shows it whole (`PlacedPicture`). |
| + final class FillVideoView: NSView, RTCVideoViewDelegate { |
| private let renderer = RTCMTLNSVideoView(frame: .zero) |
| private var track: RTCVideoTrack? |
| - private var videoSize = NSSize(width: 16, height: 9) |
| - var fit = false { |
| - didSet { if fit != oldValue { needsLayout = true } } |
| + private var picture = PlacedPicture() |
| + private(set) var fitted = false |
| + private var placedOnce = false |
| + private var lastShape: VideoShape? |
| + /// How many times the picture has turned between filling and fitted, |
| + /// and changed shape, for the gate: a phone turned once is once each. |
| + private var fitChanges = 0 |
| + private var shapeChanges = 0 |
| + var fittedChanged: (Bool) -> Void = { _ in } |
| + var shapeChanged: ((VideoShape) -> Void)? |
| + var screen = false { |
| + didSet { if screen != oldValue { picture.screen = screen; needsLayout = true } } |
| } |
| override init(frame: NSRect) { |
| @@ -121,6 +165,7 @@ |
| layer?.masksToBounds = true |
| renderer.delegate = self |
| addSubview(renderer) |
| + VideoPlacementProbe.views.add(self) |
| } |
| required init?(coder: NSCoder) { nil } |
| @@ -141,20 +186,74 @@ |
| track = nil |
| } |
| + /// The size WebRTC reports is the frame's as shown, its rotation |
| + /// applied: an upright phone's 1280 × 720 buffer turned 90° is 720 × |
| + /// 1280 here. |
| nonisolated func videoView(_ videoView: RTCVideoRenderer, didChangeVideoSize size: CGSize) { |
| DispatchQueue.main.async { [weak self] in |
| guard let self, size.width > 0, size.height > 0 else { return } |
| - self.videoSize = size |
| + self.picture.update(video: size) |
| + if self.picture.shape != self.lastShape { |
| + if self.lastShape != nil { self.shapeChanges += 1 } |
| + self.lastShape = self.picture.shape |
| + let shape = self.picture.shape |
| + self.shapeChanged?(shape) |
| + } |
| self.needsLayout = true |
| } |
| } |
| + /// The probe's view of it: the picture's size and shape, whether it is |
| + /// fitted, and the renderer's frame in the view (top-down). |
| + var placement: [String: Any] { |
| + let frame = renderer.frame |
| + return [ |
| + "video": [picture.video.width, picture.video.height], "shape": picture.shape.rawValue, |
| + "fitted": fitted, "screen": screen, "fitChanges": fitChanges, "shapeChanges": shapeChanges, |
| + "bounds": [bounds.width, bounds.height], |
| + "frame": [frame.minX, bounds.height - frame.maxY, frame.width, frame.height], |
| + ] |
| + } |
| + |
| override func layout() { |
| super.layout() |
| + let placed = picture.place(in: bounds.size) |
| // Bottom-left origin: VideoFrame works top down. |
| - let placed = VideoFrame.place(video: videoSize, in: bounds.size, fit: fit) |
| - renderer.frame = NSRect( |
| - x: placed.minX, y: bounds.height - placed.maxY, width: placed.width, height: placed.height) |
| + let frame = NSRect( |
| + x: placed.frame.minX, y: bounds.height - placed.frame.maxY, width: placed.frame.width, |
| + height: placed.frame.height) |
| + let turned = placedOnce && placed.fitted != fitted |
| + placedOnce = true |
| + if turned, !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion { |
| + // A phone turned mid-call: the picture eases to its new place |
| + // rather than jumping. |
| + NSAnimationContext.runAnimationGroup { context in |
| + context.duration = 0.3 |
| + context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) |
| + renderer.animator().frame = frame |
| + } |
| + } else { |
| + renderer.frame = frame |
| + } |
| + if placed.fitted != fitted { |
| + fitted = placed.fitted |
| + fitChanges += 1 |
| + let now = fitted |
| + // After this layout pass: SwiftUI's state is not changed from |
| + // inside one. |
| + DispatchQueue.main.async { [weak self] in self?.fittedChanged(now) } |
| + } |
| + } |
| + } |
| + |
| + /// Every live video view, for the gate's look at where each picture is |
| + /// (`CallsInterop`'s `placement` command). Weak: it holds nothing up. |
| + @_spi(Fixtures) @MainActor public enum VideoPlacementProbe { |
| + static let views = NSHashTable<FillVideoView>.weakObjects() |
| + public static var placements: [[String: Any]] { |
| + views.allObjects.filter { $0.window != nil }.map(\.placement) |
| } |
| + /// How many backdrops are sampling a picture and showing it. |
| + public static var backdrops: Int { BackdropSampler.showing } |
| } |
| #endif |
diff --git a/native/apple/Sources/CallsKit/MiniWindow.swift b/native/apple/Sources/CallsKit/MiniWindow.swift| index ed55282..92b4921 100644 |
| --- a/native/apple/Sources/CallsKit/MiniWindow.swift |
| +++ b/native/apple/Sources/CallsKit/MiniWindow.swift |
| @@ -511,6 +511,7 @@ |
| @ObservedObject var speakerNow: SpeakerNow |
| let showingControls: Bool |
| let actions: MiniWindowActions |
| + @Environment(\.fixtureFeeds) private var fixtureFeeds |
| /// What Speaker view's stage shows (0.4.0): what the person pinned, |
| /// or else the newest shared screen, since a person who shares is |
| @@ -540,10 +541,12 @@ |
| track: call.remoteScreens[peer], label: screenCaption(call.name(of: peer)), |
| screen: true) |
| case .camera(let peer): |
| + // On the stage: fitted with its backdrop when its shape and |
| + // the window's differ, as on the call window's stage. |
| MacVideoTile( |
| track: call.remoteTracks[peer], label: call.name(of: peer), |
| muted: call.isMuted(peer), cameraOff: call.isCameraOff(peer), |
| - audio: call.tileAudio(peer)) |
| + audio: call.tileAudio(peer), fixtureVideo: fixtureFeeds[peer]) |
| case nil: |
| MacVideoTile( |
| track: call.localTrack, label: "You", mirrored: true, cameraOff: call.cameraOff, |
diff --git a/native/apple/Sources/CallsKit/ScreenBackdrop.swift b/native/apple/Sources/CallsKit/ScreenBackdrop.swift| index aefb084..90a6f57 100644 |
| --- a/native/apple/Sources/CallsKit/ScreenBackdrop.swift |
| +++ b/native/apple/Sources/CallsKit/ScreenBackdrop.swift |
| @@ -1,3 +1,4 @@ |
| +import Accelerate |
| import CoreGraphics |
| import Foundation |
| import LiveKitWebRTC |
| @@ -16,37 +17,83 @@ import SwiftUI |
| /// at the frame rate and nothing is blurred at the window's size. |
| public struct ScreenBackdrop: View { |
| let track: RTCVideoTrack |
| + /// A tile among others (the grid, the filmstrip): it takes one of |
| + /// `BackdropBudget.limit` places, and with none left shows the dark |
| + /// surface alone. The stage's backdrop always samples. |
| + var budgeted = false |
| @StateObject private var sampler = BackdropSampler() |
| + @ObservedObject private var budget = BackdropBudget.shared |
| + @State private var place = UUID() |
| - public init(track: RTCVideoTrack) { self.track = track } |
| + public init(track: RTCVideoTrack, budgeted: Bool = false) { |
| + self.track = track |
| + self.budgeted = budgeted |
| + } |
| + |
| + private var sampling: Bool { !budgeted || budget.granted(place) } |
| public var body: some View { |
| - ZStack { |
| - CallsAppearance.stageSurface |
| - if let image = sampler.image { |
| - Image(decorative: image, scale: 1) |
| - .resizable() |
| - .interpolation(.high) |
| - .aspectRatio(contentMode: .fill) |
| - // Past the edges a little: the blur's own edge is darker. |
| - .scaleEffect(1.15) |
| - .opacity(BackdropSampler.dimmed) |
| - .transition(.opacity) |
| + // The picture is an overlay of the surface, so it takes the place's |
| + // size and never sets it: filling, an upright picture is far taller |
| + // than a landscape place, and as the ZStack's own child it grew the |
| + // tile with it (2026-10-21). |
| + CallsAppearance.stageSurface |
| + .overlay { |
| + if let image = sampler.image { |
| + Image(decorative: image, scale: 1) |
| + .resizable() |
| + .interpolation(.high) |
| + .aspectRatio(contentMode: .fill) |
| + // Past the edges a little: the blur's own edge is darker. |
| + .scaleEffect(1.15) |
| + .opacity(BackdropSampler.dimmed) |
| + .transition(.opacity) |
| + } |
| } |
| - } |
| - .clipped() |
| + .clipped() |
| .animation(.easeInOut(duration: 0.4), value: sampler.image != nil) |
| - .onAppear { sampler.attach(track) } |
| - .onChange(of: ObjectIdentifier(track)) { sampler.attach(track) } |
| - .onDisappear { sampler.detach() } |
| + .onAppear { |
| + if budgeted { budget.claim(place) } |
| + follow() |
| + } |
| + .onChange(of: ObjectIdentifier(track)) { follow() } |
| + .onChange(of: sampling) { follow() } |
| + .onDisappear { |
| + sampler.detach() |
| + if budgeted { budget.release(place) } |
| + } |
| .accessibilityHidden(true) |
| } |
| + |
| + private func follow() { |
| + if sampling { sampler.attach(track) } else { sampler.detach() } |
| + } |
| +} |
| + |
| +/// How many tiles' backdrops sample their pictures at once (2026-10-21): |
| +/// past `limit`, a fitted tile in the grid or the filmstrip has the dark |
| +/// stage surface behind it instead. Each sample is a 64 × 36 picture |
| +/// twice a second (see BackdropSampler), so the limit is about drawing |
| +/// many soft enlarged pictures at once more than about the sampling. |
| +@MainActor final class BackdropBudget: ObservableObject { |
| + static let shared = BackdropBudget() |
| + nonisolated static let limit = 8 |
| + /// Who asked, in order: the first `limit` sample. |
| + @Published private(set) var holders: [UUID] = [] |
| + |
| + func claim(_ id: UUID) { if !holders.contains(id) { holders.append(id) } } |
| + func release(_ id: UUID) { holders.removeAll { $0 == id } } |
| + func granted(_ id: UUID) -> Bool { |
| + guard let at = holders.firstIndex(of: id) else { return false } |
| + return at < Self.limit |
| + } |
| } |
| /// Takes frames from a track at `interval` and keeps the latest as a small |
| /// blurred picture. |
| @MainActor final class BackdropSampler: ObservableObject { |
| - /// The picture's size: 16:9, enough for the colours and their places. |
| + /// The picture's size, landscape: 16:9, enough for the colours and |
| + /// their places. Upright pictures are sampled 36 × 64 (`size(for:)`). |
| nonisolated static let width = 64 |
| nonisolated static let height = 36 |
| /// How often a frame is taken. |
| @@ -58,6 +105,13 @@ public struct ScreenBackdrop: View { |
| private var track: RTCVideoTrack? |
| private var renderer: Renderer? |
| + /// Every sampler, for the gate's count of backdrops showing a picture. |
| + static let live = NSHashTable<BackdropSampler>.weakObjects() |
| + /// How many backdrops are sampling and have a picture to show. |
| + static var showing: Int { live.allObjects.filter { $0.track != nil && $0.image != nil }.count } |
| + |
| + init() { Self.live.add(self) } |
| + |
| func attach(_ next: RTCVideoTrack) { |
| guard track !== next else { return } |
| detach() |
| @@ -98,24 +152,72 @@ public struct ScreenBackdrop: View { |
| } |
| } |
| + /// The backdrop picture's size for a picture of `displayed` size: 64 × |
| + /// 36 for a landscape one, 36 × 64 upright, 48 × 48 near square, so |
| + /// the picture is not stretched before it is enlarged. |
| + nonisolated static func size(for displayed: CGSize) -> (width: Int, height: Int) { |
| + switch VideoShape.of(displayed) { |
| + case .landscape: (width, height) |
| + case .portrait: (height, width) |
| + case .square: (48, 48) |
| + } |
| + } |
| + |
| /// One frame as the backdrop's picture: scaled down by WebRTC, then |
| - /// converted and blurred here. |
| + /// converted, turned upright (a phone's camera arrives sideways, with a |
| + /// rotation to apply) and blurred here. |
| nonisolated static func picture(of frame: RTCVideoFrame) -> CGImage? { |
| let source = frame.buffer |
| guard source.width > 0, source.height > 0 else { return nil } |
| + let rotation = Int(frame.rotation.rawValue) |
| + let shown = size( |
| + for: VideoShape.displayed( |
| + width: CGFloat(source.width), height: CGFloat(source.height), rotation: rotation)) |
| + // Sampled at the buffer's own orientation, then turned. |
| + let quarter = rotation % 180 == 90 |
| + let (w, h) = quarter ? (shown.height, shown.width) : (shown.width, shown.height) |
| let small = |
| source.cropAndScale?( |
| with: 0, offsetY: 0, cropWidth: source.width, cropHeight: source.height, |
| - scaleWidth: Int32(width), scaleHeight: Int32(height)) ?? source |
| + scaleWidth: Int32(w), scaleHeight: Int32(h)) ?? source |
| let planes = small.toI420() |
| var rgba = rgbaFromI420( |
| width: Int(planes.width), height: Int(planes.height), |
| y: planes.dataY, strideY: Int(planes.strideY), |
| u: planes.dataU, strideU: Int(planes.strideU), |
| v: planes.dataV, strideV: Int(planes.strideV), |
| - outWidth: width, outHeight: height) |
| - boxBlur(&rgba, width: width, height: height, radius: 3, passes: 2) |
| - return image(rgba, width: width, height: height) |
| + outWidth: w, outHeight: h) |
| + let upright = rotate(rgba, width: w, height: h, rotation: rotation) |
| + rgba = upright.pixels |
| + boxBlur(&rgba, width: upright.width, height: upright.height, radius: 3, passes: 2) |
| + return image(rgba, width: upright.width, height: upright.height) |
| + } |
| + |
| + /// RGBA turned clockwise by `rotation` (0, 90, 180 or 270), as WebRTC's |
| + /// rotation says a frame is to be shown. |
| + nonisolated static func rotate(_ rgba: [UInt8], width: Int, height: Int, rotation: Int) |
| + -> (pixels: [UInt8], width: Int, height: Int) |
| + { |
| + let turn = ((rotation % 360) + 360) % 360 |
| + guard turn != 0, rgba.count == width * height * 4 else { return (rgba, width, height) } |
| + let (ow, oh) = turn == 180 ? (width, height) : (height, width) |
| + var out = [UInt8](repeating: 255, count: rgba.count) |
| + for y in 0..<height { |
| + for x in 0..<width { |
| + let (nx, ny): (Int, Int) |
| + switch turn { |
| + case 90: (nx, ny) = (height - 1 - y, x) |
| + case 180: (nx, ny) = (width - 1 - x, height - 1 - y) |
| + default: (nx, ny) = (y, width - 1 - x) // 270 |
| + } |
| + let from = (y * width + x) * 4 |
| + let to = (ny * ow + nx) * 4 |
| + out[to] = rgba[from] |
| + out[to + 1] = rgba[from + 1] |
| + out[to + 2] = rgba[from + 2] |
| + } |
| + } |
| + return (out, ow, oh) |
| } |
| /// I420 to RGBA (BT.601, video range) at `outWidth` × `outHeight`, |
| @@ -155,52 +257,30 @@ public struct ScreenBackdrop: View { |
| UInt8(truncatingIfNeeded: value < 0 ? 0 : value > 255 ? 255 : value) |
| } |
| - /// A separable box blur, `passes` times (two is close to Gaussian), |
| - /// with running sums, so each pass is linear in the pixels. |
| + /// A box blur, `passes` times (two is close to Gaussian), by |
| + /// Accelerate's vImage: since several tiles can have a backdrop at once |
| + /// (2026-10-21), the blur that was most of a picture's cost, done by |
| + /// hand, is done by the library that is built for it. Edges extend, so |
| + /// the border is not darkened. |
| nonisolated static func boxBlur( |
| _ pixels: inout [UInt8], width: Int, height: Int, radius: Int, passes: Int |
| ) { |
| - guard radius > 0, width > 0, height > 0 else { return } |
| + guard radius > 0, width > 0, height > 0, pixels.count >= width * height * 4 else { return } |
| var scratch = pixels |
| - pixels.withUnsafeMutableBufferPointer { a in |
| - scratch.withUnsafeMutableBufferPointer { b in |
| + let kernel = UInt32(radius * 2 + 1) |
| + pixels.withUnsafeMutableBytes { a in |
| + scratch.withUnsafeMutableBytes { b in |
| + var one = vImage_Buffer( |
| + data: a.baseAddress, height: vImagePixelCount(height), width: vImagePixelCount(width), |
| + rowBytes: width * 4) |
| + var two = vImage_Buffer( |
| + data: b.baseAddress, height: vImagePixelCount(height), width: vImagePixelCount(width), |
| + rowBytes: width * 4) |
| for _ in 0..<passes { |
| - blurLines(a.baseAddress!, b.baseAddress!, count: height, length: width, step: 4, lineStep: width * 4, radius: radius) |
| - blurLines(b.baseAddress!, a.baseAddress!, count: width, length: height, step: width * 4, lineStep: 4, radius: radius) |
| - } |
| - } |
| - } |
| - } |
| - |
| - nonisolated private static func blurLines( |
| - _ source: UnsafeMutablePointer<UInt8>, _ out: UnsafeMutablePointer<UInt8>, count: Int, |
| - length: Int, step: Int, lineStep: Int, radius: Int |
| - ) { |
| - for line in 0..<count { |
| - let base = line * lineStep |
| - for channel in 0..<3 { |
| - var sum = 0 |
| - var n = 0 |
| - // The window [at - radius, at + radius], clipped to the line. |
| - for k in 0...min(length - 1, radius) { |
| - sum += Int(source[base + k * step + channel]) |
| - n += 1 |
| - } |
| - for at in 0..<length { |
| - out[base + at * step + channel] = UInt8(truncatingIfNeeded: sum / n) |
| - let leaving = at - radius |
| - let entering = at + radius + 1 |
| - if leaving >= 0 { |
| - sum -= Int(source[base + leaving * step + channel]) |
| - n -= 1 |
| - } |
| - if entering < length { |
| - sum += Int(source[base + entering * step + channel]) |
| - n += 1 |
| - } |
| + vImageBoxConvolve_ARGB8888(&one, &two, nil, 0, 0, kernel, kernel, nil, vImage_Flags(kvImageEdgeExtend)) |
| + vImageBoxConvolve_ARGB8888(&two, &one, nil, 0, 0, kernel, kernel, nil, vImage_Flags(kvImageEdgeExtend)) |
| } |
| } |
| - for at in 0..<length { out[base + at * step + 3] = 255 } |
| } |
| } |
diff --git a/native/apple/Sources/CallsKit/VideoShape.swift b/native/apple/Sources/CallsKit/VideoShape.swift| new file mode 100644 |
| index 0000000..178424f |
| --- /dev/null |
| +++ b/native/apple/Sources/CallsKit/VideoShape.swift |
| @@ -0,0 +1,131 @@ |
| +import CoreGraphics |
| +import Foundation |
| + |
| +/// Which way up a picture is, as it is displayed: rotation applied |
| +/// (2026-10-21, Paul, after Farshad joined from an iPhone held upright: |
| +/// "Can we detect vertical video and display it appropriately?"). Since |
| +/// 0.4.10 a camera on the stage fills the window, which cut a 9:16 face |
| +/// to a thin slice of a 16:10 Mac window. |
| +public enum VideoShape: String, Sendable, Equatable { |
| + case portrait, landscape, square |
| + |
| + /// How much longer one side must be than the other for a picture to |
| + /// count as portrait or landscape: h > w × 1.1 is portrait. |
| + public static let enter: CGFloat = 1.1 |
| + /// How far it must come back before it stops counting as that: a |
| + /// portrait picture stays portrait until it is no taller than it is |
| + /// wide. The band between this and `enter` is what keeps a picture near |
| + /// square, or a resolution step on the way, from flapping. |
| + public static let hold: CGFloat = 1.0 |
| + |
| + /// A size's shape with no history: what a window or a tile is. |
| + public static func of(_ size: CGSize) -> VideoShape { |
| + guard size.width > 0, size.height > 0 else { return .landscape } |
| + if size.height > size.width * enter { return .portrait } |
| + if size.width > size.height * enter { return .landscape } |
| + return .square |
| + } |
| + |
| + /// A frame's size as it is shown: WebRTC carries a phone's camera |
| + /// sideways with a rotation to apply (90 or 270 for one held upright), |
| + /// so its buffer's width is the picture's height. |
| + public static func displayed(width: CGFloat, height: CGFloat, rotation: Int) -> CGSize { |
| + let quarter = ((rotation % 360) + 360) % 180 == 90 |
| + return quarter ? CGSize(width: height, height: width) : CGSize(width: width, height: height) |
| + } |
| +} |
| + |
| +/// A picture's shape over time, with hysteresis: a phone turned mid-call |
| +/// switches once, at the turn, and a picture that sits near square or |
| +/// passes through it on a resolution change does not flap. |
| +public struct VideoShapeReading: Sendable, Equatable { |
| + public private(set) var shape: VideoShape? |
| + |
| + public init() {} |
| + |
| + /// Takes the picture's newest displayed size and says its shape. |
| + @discardableResult public mutating func read(_ size: CGSize) -> VideoShape { |
| + guard size.width > 0, size.height > 0 else { return shape ?? .landscape } |
| + let fresh = VideoShape.of(size) |
| + switch shape { |
| + case .portrait? where size.height > size.width * VideoShape.hold: |
| + break // Still taller than wide: stays portrait. |
| + case .landscape? where size.width > size.height * VideoShape.hold: |
| + break // Still wider than tall: stays landscape. |
| + default: |
| + shape = fresh |
| + } |
| + return shape ?? fresh |
| + } |
| +} |
| + |
| +/// Fill or fit: whether a picture is cropped to fill its tile or window |
| +/// (0.4.10's way for every camera), or shown whole, centred, with the same |
| +/// picture soft and dimmed around it (`ScreenBackdrop`). |
| +/// |
| +/// | picture | its place | crop to fill | shown | |
| +/// |--------------------|----------------------------|--------------|--------| |
| +/// | a shared screen | anything | any | fit | |
| +/// | a camera | the same shape | any | fill | |
| +/// | a camera | another shape | ≤ 15% | fill | |
| +/// | a camera | another shape | > 15% | fit | |
| +/// |
| +/// "The same shape" is `VideoShape`: a portrait phone on a landscape Mac |
| +/// window, a landscape Mac on an upright phone, and a square-ish picture |
| +/// in a 16:9 tile are each another shape. A small crop is never worth the |
| +/// bars, so a 4:3 camera in a 16:9 tile, or a 16:9 one in a 16:10 window, |
| +/// fills as it always did. The web's room.js decides the same way |
| +/// (`videoFits`). |
| +public enum VideoPlacement { |
| + /// The most of a dimension filling may cut before a mismatched picture |
| + /// is fitted instead. |
| + public static let tolerance: CGFloat = 0.15 |
| + |
| + /// How much of its overflowing dimension a picture loses to fill |
| + /// `bounds`: 0 for the same aspect, 0.4375 for 16:9 in a 9:16 tile. |
| + public static func crop(video: CGSize, in bounds: CGSize) -> CGFloat { |
| + guard video.width > 0, video.height > 0, bounds.width > 0, bounds.height > 0 else { return 0 } |
| + let across = bounds.width / video.width |
| + let down = bounds.height / video.height |
| + return 1 - min(across, down) / max(across, down) |
| + } |
| + |
| + /// Whether the picture is fitted whole. `shape` is the picture's shape |
| + /// as a `VideoShapeReading` holds it, so a rotation decides once. |
| + public static func fits(video: CGSize, shape: VideoShape, in bounds: CGSize, screen: Bool) -> Bool { |
| + if screen { return true } |
| + guard video.width > 0, video.height > 0, bounds.width > 0, bounds.height > 0 else { |
| + return false |
| + } |
| + if crop(video: video, in: bounds) <= tolerance { return false } |
| + return shape != VideoShape.of(bounds) |
| + } |
| +} |
| + |
| +/// One renderer's picture and where it goes: what the Mac's and the |
| +/// iPhone's video views keep, told each new size the renderer reports |
| +/// and asked where to put it at every layout. |
| +public struct PlacedPicture: Sendable, Equatable { |
| + /// A shared screen: always fitted. |
| + public var screen = false |
| + /// The picture's size as displayed, rotation applied; 16:9 until the |
| + /// first frame says otherwise, which fills as 0.4.10 did. |
| + public private(set) var video = CGSize(width: 16, height: 9) |
| + public private(set) var reading = VideoShapeReading() |
| + |
| + public init(screen: Bool = false) { self.screen = screen } |
| + |
| + public var shape: VideoShape { reading.shape ?? VideoShape.of(video) } |
| + |
| + public mutating func update(video size: CGSize) { |
| + guard size.width > 0, size.height > 0 else { return } |
| + video = size |
| + reading.read(size) |
| + } |
| + |
| + /// Whether the picture is fitted in `bounds`, and its frame there. |
| + public func place(in bounds: CGSize) -> (frame: CGRect, fitted: Bool) { |
| + let fitted = VideoPlacement.fits(video: video, shape: shape, in: bounds, screen: screen) |
| + return (VideoFrame.place(video: video, in: bounds, fit: fitted), fitted) |
| + } |
| +} |
diff --git a/native/apple/Tests/CallsKitTests/VideoShapeTests.swift b/native/apple/Tests/CallsKitTests/VideoShapeTests.swift| new file mode 100644 |
| index 0000000..d4d7538 |
| --- /dev/null |
| +++ b/native/apple/Tests/CallsKitTests/VideoShapeTests.swift |
| @@ -0,0 +1,205 @@ |
| +import CoreGraphics |
| +import XCTest |
| + |
| +@testable import CallsKit |
| + |
| +/// Portrait video (2026-10-21): which way up a picture is, and whether it |
| +/// fills its place or is shown whole. |
| +final class VideoShapeTests: XCTestCase { |
| + private func size(_ w: CGFloat, _ h: CGFloat) -> CGSize { CGSize(width: w, height: h) } |
| + |
| + // MARK: The classifier |
| + |
| + func testThresholds() { |
| + XCTAssertEqual(VideoShape.of(size(720, 1280)), .portrait) |
| + XCTAssertEqual(VideoShape.of(size(1280, 720)), .landscape) |
| + XCTAssertEqual(VideoShape.of(size(640, 480)), .landscape, "4:3 is landscape") |
| + XCTAssertEqual(VideoShape.of(size(480, 640)), .portrait) |
| + XCTAssertEqual(VideoShape.of(size(500, 500)), .square) |
| + // h > w × 1.1 is portrait; exactly 1.1 is not yet. |
| + XCTAssertEqual(VideoShape.of(size(1000, 1100)), .square) |
| + XCTAssertEqual(VideoShape.of(size(1000, 1101)), .portrait) |
| + XCTAssertEqual(VideoShape.of(size(1101, 1000)), .landscape) |
| + XCTAssertEqual(VideoShape.of(size(0, 0)), .landscape, "nothing known is today's landscape") |
| + } |
| + |
| + func testRotationIsApplied() { |
| + // An iPhone held upright sends its 1280 × 720 buffer turned 90°. |
| + XCTAssertEqual(VideoShape.displayed(width: 1280, height: 720, rotation: 90), size(720, 1280)) |
| + XCTAssertEqual(VideoShape.displayed(width: 1280, height: 720, rotation: 270), size(720, 1280)) |
| + XCTAssertEqual(VideoShape.displayed(width: 1280, height: 720, rotation: 180), size(1280, 720)) |
| + XCTAssertEqual(VideoShape.displayed(width: 1280, height: 720, rotation: 0), size(1280, 720)) |
| + XCTAssertEqual(VideoShape.of(VideoShape.displayed(width: 1280, height: 720, rotation: 90)), .portrait) |
| + } |
| + |
| + func testHysteresisHoldsAShapeThroughTheBand() { |
| + var reading = VideoShapeReading() |
| + XCTAssertEqual(reading.read(size(720, 1280)), .portrait) |
| + // Still taller than wide, inside the band: stays portrait. |
| + XCTAssertEqual(reading.read(size(1000, 1050)), .portrait) |
| + XCTAssertEqual(reading.read(size(1000, 1001)), .portrait) |
| + // No taller than wide: let go, to what it now is. |
| + XCTAssertEqual(reading.read(size(1000, 1000)), .square) |
| + // Back up into the band is not enough to be portrait again. |
| + XCTAssertEqual(reading.read(size(1000, 1080)), .square) |
| + XCTAssertEqual(reading.read(size(1000, 1200)), .portrait) |
| + } |
| + |
| + func testNearSquareDoesNotFlap() { |
| + // A picture jittering about 1.1 from square never changes once. |
| + var reading = VideoShapeReading() |
| + var changes = 0 |
| + var last = reading.read(size(1000, 1000)) |
| + for step in 0..<40 { |
| + let h: CGFloat = step.isMultiple(of: 2) ? 1095 : 1105 |
| + let now = reading.read(size(1000, h)) |
| + if now != last { changes += 1 } |
| + last = now |
| + } |
| + XCTAssertEqual(changes, 1, "into portrait once, then held there") |
| + } |
| + |
| + func testARotationMidCallSwitchesOnce() { |
| + // A phone turned: landscape, the steps a resolution ladder may report |
| + // on the way, then upright, with no flapping between. |
| + var reading = VideoShapeReading() |
| + let sizes = [ |
| + size(1280, 720), size(960, 540), size(1280, 720), // landscape, adapting |
| + size(720, 1280), size(540, 960), size(720, 1280), // turned upright |
| + ] |
| + var shapes: [VideoShape] = [] |
| + for s in sizes { |
| + let shape = reading.read(s) |
| + if shapes.last != shape { shapes.append(shape) } |
| + } |
| + XCTAssertEqual(shapes, [.landscape, .portrait]) |
| + } |
| + |
| + // MARK: Fill or fit |
| + |
| + func testCrop() { |
| + XCTAssertEqual(VideoPlacement.crop(video: size(1280, 720), in: size(1600, 900)), 0, accuracy: 1e-6) |
| + // 16:9 in 16:10 cuts a tenth of its width. |
| + XCTAssertEqual(VideoPlacement.crop(video: size(16, 9), in: size(16, 10)), 0.1, accuracy: 1e-6) |
| + // 9:16 in 16:10: all but 9/16 × 10/16 of its height goes. |
| + XCTAssertEqual( |
| + VideoPlacement.crop(video: size(9, 16), in: size(16, 10)), 1 - (9.0 / 16) * (10.0 / 16), accuracy: 1e-6) |
| + } |
| + |
| + /// The decision table in VideoPlacement's comment, row by row. |
| + func testDecisionTable() { |
| + let mac = size(1440, 900) // 16:10 |
| + let phone = size(393, 852) // an upright iPhone |
| + let tile = size(320, 180) // a grid or filmstrip tile, 16:9 |
| + let phoneTile = size(99, 132) // the iPhone's filmstrip, 3:4 |
| + func fits(_ v: CGSize, _ b: CGSize, screen: Bool = false) -> Bool { |
| + var reading = VideoShapeReading() |
| + return VideoPlacement.fits(video: v, shape: reading.read(v), in: b, screen: screen) |
| + } |
| + // A screen is always fitted. |
| + XCTAssertTrue(fits(size(1920, 1200), mac, screen: true)) |
| + XCTAssertTrue(fits(size(1440, 900), mac, screen: true)) |
| + // The same shape fills, however much it crops. |
| + XCTAssertFalse(fits(size(1280, 720), mac)) |
| + XCTAssertFalse(fits(size(720, 1280), phone)) |
| + XCTAssertFalse(fits(size(2560, 1080), tile), "21:9 in 16:9 crops 25% and still fills") |
| + // Another shape with a small crop fills. |
| + XCTAssertFalse(fits(size(1000, 1000), size(1100, 1000)), "square in a near-square place") |
| + XCTAssertFalse(fits(size(1050, 1000), size(1000, 1080))) |
| + // Another shape with a big crop is fitted. |
| + XCTAssertTrue(fits(size(720, 1280), mac), "Farshad's iPhone on a Mac window") |
| + XCTAssertTrue(fits(size(720, 1280), tile), "and in a grid or filmstrip tile") |
| + XCTAssertTrue(fits(size(1280, 720), phone), "a Mac on an upright phone") |
| + XCTAssertTrue(fits(size(1280, 720), phoneTile), "and in the phone's 3:4 filmstrip") |
| + XCTAssertTrue(fits(size(720, 720), mac), "a square picture in a 16:10 window") |
| + // The 15% line: 4:3 into 16:9 (25%) is the same shape and fills. |
| + XCTAssertFalse(fits(size(640, 480), tile)) |
| + // A portrait 3:4 into a square-ish 1.08:1 place cuts 31%: fitted. |
| + XCTAssertTrue(fits(size(480, 640), size(1080, 1000))) |
| + // Nothing known yet: fill, as 0.4.10. |
| + XCTAssertFalse(VideoPlacement.fits(video: .zero, shape: .portrait, in: mac, screen: false)) |
| + } |
| + |
| + func testPlacedPictureFitsCentredAndFillsWithHeadroom() { |
| + var picture = PlacedPicture() |
| + let mac = size(1600, 1000) |
| + // Before the first frame: 16:9, filling. |
| + XCTAssertFalse(picture.place(in: mac).fitted) |
| + picture.update(video: size(720, 1280)) |
| + let placed = picture.place(in: mac) |
| + XCTAssertTrue(placed.fitted) |
| + XCTAssertEqual(placed.frame.height, 1000, accuracy: 1e-6, "the whole height shown") |
| + XCTAssertEqual(placed.frame.width, 562.5, accuracy: 1e-6) |
| + XCTAssertEqual(placed.frame.midX, 800, accuracy: 1e-6, "centred") |
| + // Turned back to landscape: fills again, cropped with headroom. |
| + picture.update(video: size(1280, 720)) |
| + let filled = picture.place(in: mac) |
| + XCTAssertFalse(filled.fitted) |
| + XCTAssertGreaterThanOrEqual(filled.frame.width, 1600) |
| + XCTAssertGreaterThanOrEqual(filled.frame.height, 1000 - 1e-6) |
| + } |
| + |
| + // MARK: The self view |
| + |
| + func testAnUprightSelfFloatsUpright() { |
| + let mac = size(1200, 800) |
| + let landscape = PiPLayout.size(in: mac, touch: false) |
| + XCTAssertGreaterThan(landscape.width, landscape.height) |
| + let upright = PiPLayout.size(in: mac, touch: false, shape: .portrait) |
| + XCTAssertGreaterThan(upright.height, upright.width) |
| + XCTAssertEqual(upright.width / upright.height, 9.0 / 16, accuracy: 0.02) |
| + // A phone: its own picture's shape wins over the screen's. |
| + let phone = size(393, 852) |
| + XCTAssertGreaterThan(PiPLayout.size(in: phone, touch: true).height, PiPLayout.size(in: phone, touch: true).width) |
| + let turned = PiPLayout.size(in: phone, touch: true, shape: .landscape) |
| + XCTAssertGreaterThan(turned.width, turned.height) |
| + } |
| + |
| + // MARK: The backdrop's picture |
| + |
| + func testBackdropPictureTakesThePicturesShape() { |
| + XCTAssertTrue(BackdropSampler.size(for: size(1280, 720)) == (64, 36)) |
| + XCTAssertTrue(BackdropSampler.size(for: size(720, 1280)) == (36, 64)) |
| + XCTAssertTrue(BackdropSampler.size(for: size(500, 500)) == (48, 48)) |
| + } |
| + |
| + func testBackdropPictureIsTurnedUpright() { |
| + // 3 × 2, each pixel's red its index: turned 90° clockwise it is 2 × 3 |
| + // with the bottom-left pixel first. |
| + let w = 3 |
| + let h = 2 |
| + var rgba = [UInt8](repeating: 255, count: w * h * 4) |
| + for i in 0..<(w * h) { rgba[i * 4] = UInt8(i) } |
| + let turned = BackdropSampler.rotate(rgba, width: w, height: h, rotation: 90) |
| + XCTAssertEqual(turned.width, 2) |
| + XCTAssertEqual(turned.height, 3) |
| + XCTAssertEqual(stride(from: 0, to: 6, by: 1).map { turned.pixels[$0 * 4] }, [3, 0, 4, 1, 5, 2]) |
| + let back = BackdropSampler.rotate(turned.pixels, width: 2, height: 3, rotation: 270) |
| + XCTAssertEqual(back.pixels, rgba) |
| + let half = BackdropSampler.rotate(rgba, width: w, height: h, rotation: 180) |
| + XCTAssertEqual(stride(from: 0, to: 6, by: 1).map { half.pixels[$0 * 4] }, [5, 4, 3, 2, 1, 0]) |
| + } |
| + |
| + /// The cost of several fitted tiles' backdrops: each takes a real |
| + /// 1280 × 720 frame through WebRTC's scale, the conversion, the blur and |
| + /// the CGImage, twice a second. Printed for the record; held well under |
| + /// a frame's time for the whole budget at once. |
| + func testSeveralBackdropsAreCheap() { |
| + let source = RTCI420Buffer(width: 1280, height: 720) |
| + let upright = RTCVideoFrame(buffer: source, rotation: ._90, timeStampNs: 0) |
| + let level = RTCVideoFrame(buffer: source, rotation: ._0, timeStampNs: 0) |
| + _ = BackdropSampler.picture(of: upright) |
| + let runs = 20 |
| + let start = Date() |
| + for _ in 0..<runs { |
| + for tile in 0..<BackdropBudget.limit { |
| + XCTAssertNotNil(BackdropSampler.picture(of: tile.isMultiple(of: 2) ? upright : level)) |
| + } |
| + } |
| + let each = Date().timeIntervalSince(start) / Double(runs) * 1000 |
| + print( |
| + "backdrop: \(String(format: "%.3f", each)) ms for \(BackdropBudget.limit) tiles' pictures, " |
| + + "twice a second (\(String(format: "%.3f", each * 2 / 10)) % of one core)") |
| + XCTAssertLessThan(each, 16) |
| + } |
| +} |
diff --git a/native/ios/Sources/CallsPhone.swift b/native/ios/Sources/CallsPhone.swift| index 9b21a5c..b14cb8f 100644 |
| --- a/native/ios/Sources/CallsPhone.swift |
| +++ b/native/ios/Sources/CallsPhone.swift |
| @@ -119,6 +119,8 @@ struct PhoneCall: View { |
| @State var tileFrames: [String: CGRect] = [:] |
| @State var dismissedNotices: Set<String> = [] |
| @State var pipDrag: CGSize = .zero |
| + /// Your own picture's shape, once it arrives: the self view takes it. |
| + @State var selfShape: VideoShape? |
| @StateObject var draft = ChatDraft() |
| @StateObject var screenShare = PhoneScreenShare() |
| @StateObject var chrome: ControlsVisibilityModel |
| @@ -131,6 +133,7 @@ struct PhoneCall: View { |
| @Environment(\.accessibilityReduceMotion) var reduceMotion |
| @Environment(\.accessibilityVoiceOverEnabled) var voiceOver |
| @Environment(\.fixtureBackdrop) var fixtureBackdrop |
| + @Environment(\.fixtureFeeds) var fixtureFeeds |
| private let style: CallLayoutStyle? |
| init( |
| @@ -183,13 +186,13 @@ struct PhoneCall: View { |
| track: call.localTrack, label: "You", muted: call.muted, mirrored: true, |
| cameraOff: call.cameraOff, placeholder: call.selfPlaceholder, cornerRadius: cornerRadius, |
| compact: compact, labelInsets: labelInsets, backdrop: backdrop, audio: call.selfAudio, |
| - onStage: onStage, pinned: pinned, iconOnly: iconOnly) |
| + onStage: onStage, pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds["me"]) |
| case .camera(let peer): |
| return PhoneVideoTile( |
| track: call.remoteTracks[peer], label: call.name(of: peer), muted: call.isMuted(peer), |
| cameraOff: call.isCameraOff(peer), cornerRadius: cornerRadius, compact: compact, |
| labelInsets: labelInsets, backdrop: backdrop, audio: call.tileAudio(peer), |
| - onStage: onStage, pinned: pinned, iconOnly: iconOnly) |
| + onStage: onStage, pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds[peer]) |
| } |
| } |
| @@ -424,9 +427,18 @@ struct PhoneVideoTile: View { |
| var pinned = false |
| /// A filmstrip thumbnail: the symbol alone for a missing picture. |
| var iconOnly = false |
| + /// A fixture's picture of this size in place of video, on any tile |
| + /// (the snapshots of portrait and landscape feeds); nil in a real call. |
| + var fixtureVideo: CGSize? = nil |
| + /// Told the picture's shape as it arrives, for a self view that takes |
| + /// its camera's shape. |
| + var shaped: ((VideoShape) -> Void)? = nil |
| /// The height of the name label and what is over it, which the |
| /// placeholder keeps clear of. |
| @State private var labelBlock: CGFloat = 0 |
| + /// Whether the picture is shown whole rather than filling the tile |
| + /// (`VideoPlacement`), as the video view last laid it out. |
| + @State private var fitted = false |
| @Environment(\.fixtureStagePicture) private var fixturePicture |
| var body: some View { |
| TileAudioReader(audio) { info in tile(info) } |
| @@ -434,13 +446,25 @@ struct PhoneVideoTile: View { |
| private func tile(_ info: TileAudioInfo?) -> some View { |
| ZStack { |
| backdrop |
| - if let fixturePicture, onStage, track == nil, !cameraOff, placeholder == nil { |
| + if let fixtureVideo, track == nil, !cameraOff { |
| + FixtureVideo(picture: fixturePicture ?? .busy, video: fixtureVideo, screen: screen, backdrop: !screen || onStage) |
| + .scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| + } else if let fixturePicture, onStage, track == nil, !cameraOff, placeholder == nil { |
| FixtureVideo(picture: fixturePicture, screen: screen) |
| } else if let track, !cameraOff, placeholder == nil { |
| - // A screen on the stage is fitted whole; around it, the same |
| - // picture soft and dimmed rather than black bars. |
| - if screen, onStage { ScreenBackdrop(track: track) } |
| - PhoneVideo(track: track, fit: screen).scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| + // A screen on the stage is fitted whole, and so is a camera of |
| + // another shape than its tile (a landscape Mac on an upright |
| + // phone); around it, the same picture soft and dimmed rather than |
| + // bars. A fitted camera in the grid or the filmstrip has its |
| + // backdrop while BackdropBudget has room. |
| + if screen ? onStage : fitted { |
| + ScreenBackdrop(track: track, budgeted: !onStage).transition(.opacity) |
| + } |
| + PhoneVideo( |
| + track: track, screen: screen, |
| + fitted: { now in withAnimation(Self.refit) { fitted = now } }, shaped: shaped |
| + ) |
| + .scaleEffect(x: mirrored ? -1 : 1, y: 1) |
| } else { |
| TilePlaceholder( |
| symbol: cameraOff |
| @@ -474,20 +498,35 @@ struct PhoneVideoTile: View { |
| : placeholder ?? (track == nil ? (screen ? "Waiting for the screen" : "Waiting for video") : "Video on")) |
| } |
| } |
| +extension PhoneVideoTile { |
| + /// The backdrop's fade when a picture turns between filling and |
| + /// fitted; none under Reduce Motion. |
| + static var refit: Animation? { |
| + UIAccessibility.isReduceMotionEnabled ? nil : .easeInOut(duration: 0.3) |
| + } |
| +} |
| + |
| struct PhoneVideo: UIViewRepresentable { |
| let track: RTCVideoTrack |
| - var fit = false |
| + var screen = false |
| + var fitted: (Bool) -> Void = { _ in } |
| + var shaped: ((VideoShape) -> Void)? = nil |
| func makeCoordinator() -> Coordinator { Coordinator() } |
| func makeUIView(context: Context) -> PlacedVideoView { |
| let view = PlacedVideoView() |
| - view.fit = fit |
| + update(view) |
| context.coordinator.attach(track, to: view.renderer) |
| return view |
| } |
| func updateUIView(_ view: PlacedVideoView, context: Context) { |
| - view.fit = fit |
| + update(view) |
| context.coordinator.attach(track, to: view.renderer) |
| } |
| + private func update(_ view: PlacedVideoView) { |
| + view.screen = screen |
| + view.fittedChanged = fitted |
| + view.shapeChanged = shaped |
| + } |
| static func dismantleUIView(_ view: PlacedVideoView, coordinator: Coordinator) { |
| coordinator.track?.remove(view.renderer) |
| } |
| @@ -503,14 +542,20 @@ struct PhoneVideo: UIViewRepresentable { |
| } |
| } |
| -/// The renderer at the size and place `VideoFrame` gives it: a camera |
| +/// The renderer at the size and place `PlacedPicture` gives it: a camera |
| /// filling the tile with more of a crop taken from the bottom than the |
| -/// top, so heads are not cut; a screen fitted whole. The container clips. |
| +/// top, so heads are not cut; a screen, or a camera of another shape than |
| +/// the tile, fitted whole. The container clips. |
| final class PlacedVideoView: UIView, RTCVideoViewDelegate { |
| let renderer = RTCMTLVideoView(frame: .zero) |
| - private var videoSize = CGSize(width: 16, height: 9) |
| - var fit = false { |
| - didSet { if fit != oldValue { setNeedsLayout() } } |
| + private var picture = PlacedPicture() |
| + private var fitted = false |
| + private var placedOnce = false |
| + private var lastShape: VideoShape? |
| + var fittedChanged: (Bool) -> Void = { _ in } |
| + var shapeChanged: ((VideoShape) -> Void)? |
| + var screen = false { |
| + didSet { if screen != oldValue { picture.screen = screen; setNeedsLayout() } } |
| } |
| override init(frame: CGRect) { |
| super.init(frame: frame) |
| @@ -521,16 +566,38 @@ final class PlacedVideoView: UIView, RTCVideoViewDelegate { |
| addSubview(renderer) |
| } |
| required init?(coder: NSCoder) { nil } |
| + /// The size as shown, rotation applied: WebRTC's adapter turns an |
| + /// upright phone's sideways buffer before it reports it. |
| nonisolated func videoView(_ videoView: RTCVideoRenderer, didChangeVideoSize size: CGSize) { |
| DispatchQueue.main.async { [weak self] in |
| guard let self, size.width > 0, size.height > 0 else { return } |
| - self.videoSize = size |
| + self.picture.update(video: size) |
| + if self.picture.shape != self.lastShape { |
| + self.lastShape = self.picture.shape |
| + let shape = self.picture.shape |
| + self.shapeChanged?(shape) |
| + } |
| self.setNeedsLayout() |
| } |
| } |
| override func layoutSubviews() { |
| super.layoutSubviews() |
| - renderer.frame = VideoFrame.place(video: videoSize, in: bounds.size, fit: fit) |
| + let placed = picture.place(in: bounds.size) |
| + let turned = placedOnce && placed.fitted != fitted |
| + placedOnce = true |
| + if turned, !UIAccessibility.isReduceMotionEnabled { |
| + // A phone turned mid-call: the picture eases to its new place. |
| + UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut, .beginFromCurrentState]) { |
| + self.renderer.frame = placed.frame |
| + } |
| + } else { |
| + renderer.frame = placed.frame |
| + } |
| + if placed.fitted != fitted { |
| + fitted = placed.fitted |
| + let now = fitted |
| + DispatchQueue.main.async { [weak self] in self?.fittedChanged(now) } |
| + } |
| } |
| } |
diff --git a/native/ios/Sources/PhoneFullScreenCall.swift b/native/ios/Sources/PhoneFullScreenCall.swift| index 242703e..c5040ce 100644 |
| --- a/native/ios/Sources/PhoneFullScreenCall.swift |
| +++ b/native/ios/Sources/PhoneFullScreenCall.swift |
| @@ -218,7 +218,8 @@ extension PhoneCall { |
| /// since the Mute button is a tap away inside the menu. |
| private func selfView(in size: CGSize, safe: EdgeInsets) -> some View { |
| let corner = PiPCorner(rawValue: pipCorner) ?? .bottomTrailing |
| - let pip = PiPLayout.size(in: size, touch: true) |
| + let pip = PiPLayout.size( |
| + in: size, touch: true, shape: selfShape ?? fixtureFeeds["me"].map(VideoShape.of)) |
| let insets = EdgeInsets( |
| top: safe.top, leading: safe.leading, |
| bottom: safe.bottom + (chrome.visible ? Self.barHeight : 0), trailing: safe.trailing) |
| @@ -226,7 +227,8 @@ extension PhoneCall { |
| return PhoneVideoTile( |
| track: call.localTrack, label: "You", muted: call.muted, mirrored: true, |
| cameraOff: call.cameraOff, placeholder: call.selfPlaceholder, cornerRadius: 14, |
| - compact: true, backdrop: Self.tileBackdrop, audio: call.selfAudio |
| + compact: true, backdrop: Self.tileBackdrop, audio: call.selfAudio, |
| + fixtureVideo: fixtureFeeds["me"], shaped: { selfShape = $0 } |
| ) |
| .frame(width: pip.width, height: pip.height) |
| .shadow(color: .black.opacity(0.35), radius: 8, y: 3) |
diff --git a/test/browser/native-portrait.mjs b/test/browser/native-portrait.mjs| new file mode 100644 |
| index 0000000..36a6909 |
| --- /dev/null |
| +++ b/test/browser/native-portrait.mjs |
| @@ -0,0 +1,119 @@ |
| +// native-portrait.mjs — portrait video on the Mac app (2026-10-21). The |
| +// browser's camera is held upright (portrait-camera.mjs, 720 × 1280); the |
| +// app shows its full-window call, live, off screen (CallsInterop's |
| +// `stage-open`), and reads back where the real video view put the picture |
| +// (`placement`, from VideoPlacementProbe): |
| +// |
| +// upright, on a 1000 × 640 window's stage: fitted — the whole height of |
| +// the window, narrower than it, centred — with a backdrop sampling it |
| +// turned on its side (1280 × 720): fills the window, as 0.4.10 did, and |
| +// the turn changed its shape once and its placement once |
| +// a portrait window (500 × 900) with the landscape picture: fitted again |
| +// |
| +// Run by TestNativeMacPortraitVideo (make native-browser). |
| +import { portraitCamera } from './portrait-camera.mjs'; |
| +import { chromium } from 'playwright'; |
| +import { spawn } from 'node:child_process'; |
| +import { createInterface } from 'node:readline'; |
| + |
| +const [origin, room, binary] = process.argv.slice(2); |
| +const browser = await chromium.launch({ headless: true, args: [ |
| + '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', |
| + '--autoplay-policy=no-user-gesture-required', '--disable-features=WebRtcHideLocalIpsWithMdns', |
| + '--mute-audio', |
| +] }); |
| +const context = await browser.newContext({ permissions: ['camera', 'microphone'] }); |
| +await context.addInitScript(portraitCamera); |
| +await context.addCookies([{ name: process.env.CALLS_COOKIE_NAME, value: process.env.CALLS_COOKIE_A, url: origin }]); |
| +const page = await context.newPage(); |
| +let native; |
| +let failed = false; |
| +const check = (ok, what) => { |
| + console.log((ok ? 'PASS ' : 'FAIL ') + what); |
| + if (!ok) failed = true; |
| +}; |
| +try { |
| + await page.goto(`${origin}/m/${room}`); |
| + await page.waitForFunction(() => !!window.meet); |
| + native = spawn(binary, [], { stdio: ['pipe', 'pipe', 'pipe'] }); |
| + native.stdin.write(process.env.CALLS_NATIVE_INPUT + '\n'); |
| + let sample = null; |
| + let placed = null; |
| + let exited = false; |
| + native.on('exit', () => { exited = true; }); |
| + createInterface({ input: native.stdout }).on('line', (line) => { |
| + try { |
| + const value = JSON.parse(line); |
| + if (value.stats) sample = value; |
| + if (value.placements) placed = value; |
| + } catch {} |
| + }); |
| + native.stderr.resume(); |
| + const wait = async (predicate, label, seconds = 40) => { |
| + const until = Date.now() + seconds * 1000; |
| + while (Date.now() < until) { |
| + if (exited) throw new Error('native executable exited'); |
| + if (await predicate()) return true; |
| + await new Promise((r) => setTimeout(r, 250)); |
| + } |
| + throw new Error(label + ': ' + JSON.stringify({ stats: sample && sample.stats, placed })); |
| + }; |
| + // The camera's picture on the stage: the one view with a camera's size |
| + // that is not the app's own (the app's synthetic camera is 16:9 at most). |
| + const ask = async () => { |
| + placed = null; |
| + native.stdin.write('placement\n'); |
| + const until = Date.now() + 5000; |
| + while (!placed && Date.now() < until) await new Promise((r) => setTimeout(r, 50)); |
| + return placed; |
| + }; |
| + const stagePicture = (p, bounds) => (p ? p.placements : []).find((v) => |
| + !v.screen && Math.abs(v.bounds[0] - bounds[0]) < 2 && Math.abs(v.bounds[1] - bounds[1]) < 2); |
| + |
| + await wait(() => sample?.peer && sample?.stats.framesDecoded > 15, 'the app decodes the browser’s camera'); |
| + console.log('PASS the app is in the call and decoding the browser’s camera'); |
| + native.stdin.write('stage-open 1000 640\n'); |
| + let picture = null; |
| + await wait(async () => { |
| + picture = stagePicture(await ask(), [1000, 640]); |
| + return picture && picture.video[0] === 720 && picture.video[1] === 1280 && placed.backdrops > 0; |
| + }, 'the stage shows the upright picture with a backdrop'); |
| + const [x, y, w, h] = picture.frame; |
| + check(picture.shape === 'portrait', `the upright camera reads as portrait (${picture.video.join(' × ')})`); |
| + check(picture.fitted, 'it is fitted, not cropped to fill the landscape window'); |
| + check(Math.abs(h - 640) < 1 && Math.abs(y) < 1, `the whole frame is shown: its full height in the window (${h.toFixed(1)} of 640, from ${y.toFixed(1)})`); |
| + check(Math.abs(w - 360) < 1 && Math.abs(x + w / 2 - 500) < 1, `centred, 9:16 (${w.toFixed(1)} wide at ${x.toFixed(1)})`); |
| + check(placed.backdrops > 0, `a backdrop is sampling the picture around it (${placed.backdrops})`); |
| + const before = { fit: picture.fitChanges, shape: picture.shapeChanges }; |
| + |
| + // A phone turned on its side mid-call. |
| + await page.evaluate(() => window.__turnCamera(1280, 720)); |
| + await wait(async () => { |
| + picture = stagePicture(await ask(), [1000, 640]); |
| + return picture && picture.video[0] === 1280 && picture.video[1] === 720; |
| + }, 'the stage sees the camera turned'); |
| + await new Promise((r) => setTimeout(r, 1500)); |
| + picture = stagePicture(await ask(), [1000, 640]); |
| + check(picture.shape === 'landscape' && !picture.fitted, 'turned on its side, it fills the landscape window as before'); |
| + const [, ly, lw, lh] = picture.frame; |
| + check(lw >= 1000 - 0.5 && lh >= 640 - 0.5 && ly <= 0.5, `filling: ${lw.toFixed(1)} × ${lh.toFixed(1)} over 1000 × 640`); |
| + check(picture.fitChanges - before.fit === 1 && picture.shapeChanges - before.shape === 1, |
| + `the turn switched once: placement ${picture.fitChanges - before.fit}, shape ${picture.shapeChanges - before.shape}`); |
| + |
| + // The mirror case: a landscape picture in a portrait window. |
| + native.stdin.write('stage-open 500 900\n'); |
| + await wait(async () => { |
| + picture = stagePicture(await ask(), [500, 900]); |
| + return picture && picture.fitted; |
| + }, 'a landscape picture in a portrait window is fitted'); |
| + check(Math.abs(picture.frame[2] - 500) < 1, `a landscape camera in an upright window is fitted across it (${picture.frame[2].toFixed(1)} × ${picture.frame[3].toFixed(1)})`); |
| + native.stdin.write('leave\n'); |
| + await new Promise((r) => setTimeout(r, 1000)); |
| +} catch (err) { |
| + failed = true; |
| + console.log('FAIL ' + err.message); |
| +} finally { |
| + native?.kill('SIGTERM'); |
| + await browser.close(); |
| +} |
| +if (failed) process.exit(1); |
diff --git a/test/browser/portrait-camera.mjs b/test/browser/portrait-camera.mjs| new file mode 100644 |
| index 0000000..4c15c77 |
| --- /dev/null |
| +++ b/test/browser/portrait-camera.mjs |
| @@ -0,0 +1,55 @@ |
| +// portraitCamera is an init script for the portrait-video gates |
| +// (2026-10-21): the page's camera is a canvas held upright, 720 × 1280 — |
| +// a phone's camera as a receiver sees it, rotation applied — with a red |
| +// band across its top and a green one across its bottom, so a receiver |
| +// that shows the whole frame shows both and one that crops to fill shows |
| +// neither. window.__turnCamera(w, h) turns it (1280 × 720 is a phone |
| +// turned on its side); the captured track follows the canvas's size. The |
| +// microphone is still Chromium's fake one. |
| +export const portraitCamera = () => { |
| + const md = navigator.mediaDevices; |
| + if (!md) return; |
| + const original = md.getUserMedia.bind(md); |
| + const canvas = document.createElement('canvas'); |
| + canvas.width = 720; |
| + canvas.height = 1280; |
| + const g = canvas.getContext('2d'); |
| + let t = 0; |
| + const draw = () => { |
| + const w = canvas.width; |
| + const h = canvas.height; |
| + const sky = g.createLinearGradient(0, 0, w, h); |
| + sky.addColorStop(0, '#6d8fb3'); |
| + sky.addColorStop(1, '#2f3d2a'); |
| + g.fillStyle = sky; |
| + g.fillRect(0, 0, w, h); |
| + const u = Math.min(w, h); |
| + g.fillStyle = '#c99a78'; |
| + g.beginPath(); g.arc(w / 2, h * 0.42, u * 0.2, 0, Math.PI * 2); g.fill(); |
| + g.fillStyle = '#7a3b2e'; |
| + g.beginPath(); g.ellipse(w / 2, h * 0.42 + u * 0.55, u * 0.42, u * 0.3, 0, 0, Math.PI * 2); g.fill(); |
| + g.fillStyle = '#ff0000'; |
| + g.fillRect(0, 0, w, Math.round(h * 0.06)); |
| + g.fillStyle = '#00ff00'; |
| + g.fillRect(0, h - Math.round(h * 0.06), w, Math.round(h * 0.06)); |
| + g.fillStyle = '#ffffff'; |
| + g.fillRect((t * 7) % w, h * 0.5, 40, 4); |
| + t += 1; |
| + }; |
| + draw(); |
| + setInterval(draw, 50); |
| + window.__turnCamera = (w, h) => { |
| + canvas.width = w; |
| + canvas.height = h; |
| + draw(); |
| + }; |
| + md.getUserMedia = async (c = {}) => { |
| + const tracks = []; |
| + if (c.audio) { |
| + const mic = await original({ audio: c.audio }); |
| + tracks.push(...mic.getAudioTracks()); |
| + } |
| + if (c.video) tracks.push(canvas.captureStream(20).getVideoTracks()[0]); |
| + return new MediaStream(tracks); |
| + }; |
| +}; |