Merge origin/main (1990f84: portrait video, iPhone self view, iPhone 0.4.11) into fix/safari-screen-stall-loop
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
27 files changed,
+2,326
−143
Makefile+5 −1internal/calls/static/calls.css+83 −0internal/calls/static/room.js+281 −19internal/callstest/browser_test.go+3 −0internal/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+119 −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+88 −17native/ios/Sources/PhoneCallFixture.swift+6 −0native/ios/Sources/PhoneFullScreenCall.swift+4 −2native/ios/UITests/CallsPhoneUITests.swift+44 −0native/ios/project.yml+1 −1test/browser/call.mjs+446 −1test/browser/native-portrait.mjs+119 −0test/browser/portrait-camera.mjs+55 −0test/browser/room-portrait.test.mjs+115 −0test/browser/room-self.test.mjs+187 −0
CI failed — run details
diff --git a/Makefile b/Makefile| index 5c24cbc..3ebbc25 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -159,11 +159,15 @@ browser: |
| node --test test/browser/room-lane.test.mjs |
| node --test test/browser/room-quality.test.mjs |
| node --test test/browser/room-wake.test.mjs |
| + node --test test/browser/room-portrait.test.mjs |
| + node --test test/browser/room-self.test.mjs |
| node --test test/browser/media.test.mjs |
| node --test test/browser/audio.test.mjs |
| node --test test/browser/devices.test.mjs |
| npm install --no-save playwright@1.62.1 |
| npx playwright install chromium |
| + # selfviewwebkit (2026-10-21) holds the self view in WebKit too. |
| + npx playwright install webkit |
| go test -tags browser -count=1 -timeout 20m -run TestCallInARealBrowser -v ./internal/callstest/ |
| # Native builds isolate gomobile's cgo bridge from the cgo-free server. |
| @@ -180,7 +184,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..f378f2e 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,15 @@ 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, |
| + 1.6 times as tall as a landscape self view (the filmstrip's height), |
| + rather than cropped to a landscape sliver (2026-10-21; PiPLayout in |
| + the apps). */ |
| +.calls-window #tiles[data-layout] > .calls-tile-pip[data-shape='portrait'] { |
| + block-size: calc(var(--calls-strip-h, 120px) * 1.6); |
| + inline-size: auto; |
| + 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; } |
| @@ -869,6 +920,38 @@ body:has(> .calls-window) { background: var(--rst-bg); } |
| .calls-tile-off .icon { inline-size: 2rem; block-size: 2rem; } |
| .calls-tile-camera-off .calls-tile-name { z-index: 1; } |
| +/* Our own preview, when the browser will not play it (room.js's |
| + self-view watch, 2026-10-21): never a black box with nothing said. |
| + The whole tile is the button, because the floating self view on a |
| + phone is too small for a sentence and a control in its caption. */ |
| +.calls-tile-paused { |
| + position: absolute; |
| + inset: 0; |
| + z-index: 1; |
| + display: flex; |
| + flex-direction: column; |
| + align-items: center; |
| + justify-content: center; |
| + gap: 4px; |
| + margin: 0; |
| + padding: 8px 8px 2rem; |
| + border: 0; |
| + border-radius: inherit; |
| + background: #212121; |
| + color: rgb(255 255 255 / 0.85); |
| + font: inherit; |
| + font-size: var(--rst-fs-sm); |
| + line-height: 1.25; |
| + text-align: center; |
| + cursor: pointer; |
| +} |
| +.calls-tile-paused[hidden] { display: none; } |
| +.calls-tile-paused-show { font-weight: 600; color: #fff; text-decoration: underline; } |
| +.calls-tile-self:has(.calls-tile-paused:not([hidden])) .calls-tile-name { z-index: 2; } |
| +@container (max-width: 15rem) { |
| + .calls-tile-paused { font-size: var(--rst-fs-xs); padding-block-end: 1.75rem; } |
| +} |
| + |
| /* What a tile says about its audio when the rim cannot: no sound, |
| sound blocked, a microphone picking nothing up. Words, with the |
| weight as a second cue, in the caption's own pill. The ⓘ is a native |
diff --git a/internal/calls/static/room.js b/internal/calls/static/room.js| index 0a935a5..66c2b9b 100644 |
| --- a/internal/calls/static/room.js |
| +++ b/internal/calls/static/room.js |
| @@ -224,6 +224,14 @@ |
| // Reading any advance at all as health let such a tile reset the |
| // budget below for ever and never earn its reset. |
| const RENDER_MOVED = 0.25; |
| + // The self view's own watch (2026-10-21: an iPhone in Safari showed |
| + // its own picture black for a whole call while sending it perfectly). |
| + // How long a live, enabled camera may sit in the self view without |
| + // its element's clock moving before the element is handed the stream |
| + // again and asked to play, and — that once — before the tile says so. |
| + const SELF_STUCK_MS = 2000; |
| + const SELF_PAUSED = 'Your camera preview is paused.'; |
| + const SELF_SHOW = 'Show it'; |
| // The ceiling studio audio asks for, in bits per second. Opus is |
| // transparent for speech well below it; the number is picked so a |
| // microphone someone turned the processing off for is not then |
| @@ -5902,20 +5910,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; |
| @@ -5923,7 +5946,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; |
| } |
| @@ -5933,6 +5956,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 |
| @@ -6600,6 +6704,9 @@ |
| if (t.play) t.play.hidden = true; |
| startPlaying(key, t); |
| } |
| + // The same gesture is the one a refused preview was waiting for. |
| + const me = tiles.get('self'); |
| + if (me && me.stream && me.video.paused) playSelf(me); |
| drawBanner(); |
| } |
| @@ -6801,6 +6908,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. |
| @@ -6874,14 +6982,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'); |
| @@ -6909,9 +7019,28 @@ |
| // §15.20's hearing parts go with them, on the same tiles and for |
| // the same reason: a screen carries no audio to meter. |
| const hear = marks ? hearingMarks() : null; |
| + // Ours has one more cover, over the camera-off one: the words for |
| + // a preview the browser will not play, as a button the size of |
| + // the tile, since a floating self view on a phone is too small |
| + // for a caption with a sentence and a control in it. |
| + let paused = null; |
| + if (isSelf) { |
| + paused = document.createElement('button'); |
| + paused.type = 'button'; |
| + paused.className = 'calls-tile-paused'; |
| + paused.hidden = true; |
| + const said = document.createElement('span'); |
| + said.textContent = SELF_PAUSED; |
| + const show = document.createElement('span'); |
| + show.className = 'calls-tile-paused-show'; |
| + show.textContent = SELF_SHOW; |
| + paused.append(said, show); |
| + paused.addEventListener('click', () => playSelf(t)); |
| + } |
| if (marks) { |
| nameEl.after(marks.muted); |
| figure.append(marks.off); |
| + if (paused) figure.append(paused); |
| // After Play, so the caption's buttons keep their order. |
| label.append(hear.box, hear.notice); |
| } |
| @@ -6928,9 +7057,18 @@ |
| // clock, the decoder's count, and how long the two have |
| // disagreed. |
| renderTime: -1, renderDecoded: -1, renderStalls: 0, renderReplays: 0, |
| + // judgeSelf's memory, on the self tile only. |
| + selfWatch: isSelf ? { time: -1, since: -1, tries: 0, said: false } : null, |
| + pausedCover: paused, |
| }; |
| 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 |
| @@ -6965,7 +7103,15 @@ |
| t.video.srcObject = stream || null; |
| t.stream = stream || null; |
| t.track = shown; |
| - if (shouldPlay(t, isSelf)) startPlaying(key, t); |
| + // Ours is asked to play on every binding, not left to `autoplay`: |
| + // the attribute is a request a browser may decline (Safari in Low |
| + // Power Mode does), and a declined one is a black tile with |
| + // nothing said. |
| + if (isSelf) { |
| + if (stream) playSelf(t); |
| + } else if (shouldPlay(t, isSelf)) { |
| + startPlaying(key, t); |
| + } |
| } |
| // The frame counter follows the stream, not the element: a tile |
| // whose track arrives after it was drawn must still be counted, and |
| @@ -6977,12 +7123,80 @@ |
| // One note element and one Retry beside it, whichever sentence the |
| // tile is carrying: `restartIce` is the handler for both, and it |
| // decides whether a retry means a bare ICE restart or a renewal. |
| + // Ours has no connection to retry, and its one sentence is the |
| + // self-view watch's cover, which a render must not take down. |
| + if (isSelf) { |
| + drawSelfNote(t); |
| + return; |
| + } |
| const show = !!noteText; |
| t.note.hidden = !show; |
| t.retry.hidden = !show; |
| t.note.textContent = noteText || ''; |
| } |
| + // playSelf asks our own element to play. Never startPlaying: a |
| + // refusal here is about the preview, not about sound, so it is not |
| + // §15.20's audioBlocked and puts up no banner — it puts the words on |
| + // our own tile instead, as a button that asks again, at once. |
| + function playSelf(t) { |
| + let attempt; |
| + try { |
| + attempt = t.video.play(); |
| + } catch { |
| + return; |
| + } |
| + if (!attempt || typeof attempt.then !== 'function') return; |
| + attempt.then(() => { |
| + if (tiles.get('self') === t && t.selfWatch.said) { |
| + t.selfWatch.said = false; |
| + drawSelfNote(t); |
| + } |
| + }, (err) => { |
| + if (!err || err.name !== 'NotAllowedError' || tiles.get('self') !== t) return; |
| + t.selfWatch.said = true; |
| + drawSelfNote(t); |
| + }); |
| + } |
| + |
| + // replaySelf is the watch's one repair: the stream handed over again, |
| + // which rebuilds the element's pipeline, and play asked for. |
| + function replaySelf(t) { |
| + if (!t.stream) return; |
| + try { |
| + t.video.srcObject = null; |
| + t.video.srcObject = t.stream; |
| + } catch { |
| + return; |
| + } |
| + playSelf(t); |
| + } |
| + |
| + function drawSelfNote(t) { |
| + const said = !!(t.selfWatch && t.selfWatch.said); |
| + t.note.hidden = true; |
| + t.note.textContent = ''; |
| + t.retry.hidden = true; |
| + t.play.hidden = true; |
| + if (t.pausedCover) t.pausedCover.hidden = !said; |
| + } |
| + |
| + // watchSelf runs judgeSelf over our tile, once a second. |
| + function watchSelf() { |
| + const t = tiles.get('self'); |
| + if (!t || !t.selfWatch) return; |
| + const track = (t.stream && t.stream.getVideoTracks && t.stream.getVideoTracks()[0]) || null; |
| + const verdict = judgeSelf(t.selfWatch, { |
| + live: !!(track && track.readyState === 'live' && track.enabled && !track.muted), |
| + visible: document.visibilityState === 'visible', |
| + paused: t.video.paused, |
| + time: t.video.currentTime || 0, |
| + now: Date.now(), |
| + }); |
| + if (verdict === 'replay') replaySelf(t); |
| + else if (verdict === 'say' || verdict === 'clear') drawSelfNote(t); |
| + } |
| + |
| // startPlaying asks the element to play and, if the browser refuses |
| // (an autoplay policy that wants a gesture first), offers the gesture |
| // rather than leaving a still frame nobody can explain. A refusal by |
| @@ -7438,7 +7652,13 @@ |
| }); |
| } |
| for (const [key, t] of tiles) { |
| - if (key !== 'self' && t.video && t.video.paused && shouldPlay(t, false)) startPlaying(key, t); |
| + if (key === 'self') { |
| + // Ours too (2026-10-21): the system pauses it along with the |
| + // rest, and it was the one tile nothing asked again. |
| + if (t.video && t.video.paused && t.stream) playSelf(t); |
| + continue; |
| + } |
| + if (t.video && t.video.paused && shouldPlay(t, false)) startPlaying(key, t); |
| } |
| } |
| @@ -7804,6 +8024,47 @@ |
| return !isSelf && !!t.stream && (!t.play || t.play.hidden); |
| } |
| + // judgeSelf is the self view's watch, asked once a second. The self |
| + // tile is outside every remote watch above — no decoder, no |
| + // connection, nothing to reset — and until 2026-10-21 that left it |
| + // outside every recovery too: autoplay was the only thing that ever |
| + // started it, so an element the system paused (iOS does, with the |
| + // page's media in the background, and leaves the camera running) or |
| + // never let start (Low Power Mode refuses autoplay) stayed black for |
| + // the rest of the call while the camera went on being sent. |
| + // |
| + // `w` is the tile's memory between polls; `s` is now: whether the |
| + // camera is live, enabled and unmuted, whether the tab is visible, |
| + // and the element's paused flag and clock. The answer is '' (nothing |
| + // to do), 'replay' (hand the element the stream again and play — once |
| + // per stall), 'say' (still stuck after that: put the words up, as a |
| + // button that asks again) or 'clear' (playing again, or nothing to show: take them |
| + // down). A camera that is off or muted is the off cover's business, |
| + // and a hidden tab is comeBack's. Pure, and lifted by name in the |
| + // node test. |
| + function judgeSelf(w, s) { |
| + const moving = !s.paused && s.time > w.time; |
| + w.time = s.time; |
| + if (!s.live || !s.visible || moving) { |
| + w.since = -1; |
| + w.tries = 0; |
| + if (!w.said) return ''; |
| + w.said = false; |
| + return 'clear'; |
| + } |
| + if (w.since < 0) { |
| + w.since = s.now; |
| + return ''; |
| + } |
| + if (s.now - w.since < SELF_STUCK_MS) return ''; |
| + w.since = s.now; |
| + w.tries += 1; |
| + if (w.tries === 1) return 'replay'; |
| + if (w.said) return ''; |
| + w.said = true; |
| + return 'say'; |
| + } |
| + |
| // freshStream gives a role a *new* MediaStream over the tracks it |
| // holds, and puts it back where the role keeps it — which is the half |
| // the first draft of the replay missed (Codex S4-13). A fresh object |
| @@ -7860,6 +8121,7 @@ |
| // callback was dropped is put back on the books (Codex S4-6's gate |
| // found one, and the counter is what every frames assertion reads). |
| rearmFrames(); |
| + watchSelf(); |
| // §15.21: every screen's decoded count, for the receiver's watch, and |
| // (§15.22) the rest of what its statistics say. |
| const screens = new Map(); |
diff --git a/internal/callstest/browser_test.go b/internal/callstest/browser_test.go| index 8851e48..52a08d4 100644 |
| --- a/internal/callstest/browser_test.go |
| +++ b/internal/callstest/browser_test.go |
| @@ -86,6 +86,7 @@ var scenarios = []string{ |
| "layout", |
| "glyphs", |
| "stage", |
| + "portrait", |
| "window", |
| "title", |
| "chrome", |
| @@ -128,6 +129,8 @@ var scenarios = []string{ |
| "autoplay", |
| "connecting", |
| "quality", |
| + "selfview", |
| + "selfviewwebkit", |
| "scriptless", |
| } |
diff --git a/internal/callstest/native_browser_test.go b/internal/callstest/native_browser_test.go| index 2cc5be7..2c8ed00 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 08c5066..9a3efcb 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..5880f6d 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,40 @@ |
| 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 placedIn = CGSize.zero |
| + 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 +166,7 @@ |
| layer?.masksToBounds = true |
| renderer.delegate = self |
| addSubview(renderer) |
| + VideoPlacementProbe.views.add(self) |
| } |
| required init?(coder: NSCoder) { nil } |
| @@ -141,20 +187,77 @@ |
| 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) |
| + // Eased only when the picture turned in a place that kept its size: |
| + // a window being resized follows the pointer instead. |
| + let turned = placedOnce && placed.fitted != fitted && bounds.size == placedIn |
| + placedIn = bounds.size |
| + 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..8765504 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,21 @@ 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 placedIn = CGSize.zero |
| + 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 +567,41 @@ 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) |
| + // Eased only when the picture turned in a place that kept its size: |
| + // a rotation of the phone itself lays out at its own pace. |
| + let turned = placedOnce && placed.fitted != fitted && bounds.size == placedIn |
| + placedIn = bounds.size |
| + 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/PhoneCallFixture.swift b/native/ios/Sources/PhoneCallFixture.swift| index f3e4284..6937fce 100644 |
| --- a/native/ios/Sources/PhoneCallFixture.swift |
| +++ b/native/ios/Sources/PhoneCallFixture.swift |
| @@ -21,6 +21,10 @@ |
| /// li,tom,me,ana`. `-CallsFixtureRimGallery silent|low|mid|high` shows, |
| /// in place of any call, the warm rim on a name at that level over the |
| /// pictures it has to read on (`WarmRimGallery`, 0.4.3). |
| + /// `-CallsFixtureFeeds ana=720x1280,li=1280x720` draws each peer's |
| + /// picture at that size on every tile it has (portrait video, |
| + /// 2026-10-21), and `-CallsFixtureFillEveryCamera YES` places them as |
| + /// 0.4.10 did, every camera filling, for the before pictures. |
| struct PhoneCallFixture: View { |
| static var requested: CallFixture? { |
| UserDefaults.standard.string(forKey: "CallsCallFixture").flatMap(CallFixture.init(rawValue:)) |
| @@ -50,11 +54,13 @@ |
| .environment( |
| \.fixtureStagePicture, |
| defaults.string(forKey: "CallsFixtureStagePicture").flatMap(FixtureBackdrop.init(rawValue:))) |
| + .environment(\.fixtureFeeds, FixtureFeeds.parse(defaults.string(forKey: "CallsFixtureFeeds") ?? "")) |
| .environment(\.callOverlayGlass, !defaults.bool(forKey: "CallsFixtureNoGlass")) |
| .preferredColorScheme(defaults.bool(forKey: "CallsFixtureDark") ? .dark : .light) |
| .onAppear { |
| guard !applied else { return } |
| applied = true |
| + FixtureVideo.fillsEveryCamera = defaults.bool(forKey: "CallsFixtureFillEveryCamera") |
| fixture.apply(to: call) |
| UserDefaults.standard.string(forKey: "CallsFixtureSelf") |
| .flatMap(FixtureSelf.init(rawValue:))?.apply(to: call) |
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/native/ios/UITests/CallsPhoneUITests.swift b/native/ios/UITests/CallsPhoneUITests.swift| index 7ef1c47..127c31a 100644 |
| --- a/native/ios/UITests/CallsPhoneUITests.swift |
| +++ b/native/ios/UITests/CallsPhoneUITests.swift |
| @@ -490,6 +490,50 @@ final class CallsPhoneUITests: XCTestCase { |
| } |
| } |
| + /// Portrait video (2026-10-21): an upright phone viewing a laptop's |
| + /// landscape camera (Li) and another phone's upright one (Ana), on the |
| + /// stage, in the filmstrip and in Grid; before (0.4.10's placement, |
| + /// every camera filling) and after (a camera of another shape than its |
| + /// tile shown whole, its picture soft behind it). |
| + @MainActor func testPortraitVideoSnapshots() throws { |
| + XCUIDevice.shared.orientation = .portrait |
| + let feeds = ["-CallsFixtureFeeds", "ana=720x1280,li=1280x720,me=720x1280"] |
| + let cases: [(String, [String])] = [ |
| + ("stage-landscape", ["-CallsFixtureLayout", "speaker", "-CallsFixtureSpeaker", "li"]), |
| + ("stage-portrait", ["-CallsFixtureLayout", "speaker", "-CallsFixtureSpeaker", "ana"]), |
| + ("grid", ["-CallsFixtureLayout", "grid"]), |
| + ] |
| + for before in [true, false] { |
| + for (name, extra) in cases { |
| + let app = launchCall( |
| + "grid", |
| + extra + feeds + ["-CallsFixtureControls", "hidden", "-CallsFixtureStagePicture", "busy", |
| + "-CallsFixtureFillEveryCamera", before ? "YES" : "NO"], |
| + dark: true) |
| + XCTAssertTrue(app.descendants(matching: .any)["callStage"].firstMatch.waitForExistence(timeout: 15)) |
| + Thread.sleep(forTimeInterval: 1) |
| + try snapshot(app, "portrait-video-\(name)-\(before ? "before" : "after")") |
| + } |
| + } |
| + // A call of two, Ana on a laptop filling the upright phone's stage before |
| + // and fitted after, and your own upright camera floating upright. |
| + for before in [true, false] { |
| + let app = launchCall( |
| + "focus", |
| + ["-CallsFixtureFeeds", "ana=1280x720,me=720x1280", "-CallsFixtureControls", "hidden", |
| + "-CallsFixtureFillEveryCamera", before ? "YES" : "NO"], |
| + dark: true) |
| + XCTAssertTrue(app.descendants(matching: .any)["callStage"].firstMatch.waitForExistence(timeout: 15)) |
| + Thread.sleep(forTimeInterval: 1) |
| + // The self view's shape is PiPLayout's, unit-tested there |
| + // (VideoShapeTests): the element's accessibility frame here is not |
| + // the drawn one (it reports 714 × 217 for a 112 × 150 view), so the |
| + // snapshot is the evidence. |
| + XCTAssertTrue(app.descendants(matching: .any)["selfView"].exists) |
| + try snapshot(app, "portrait-video-two-landscape-\(before ? "before" : "after")") |
| + } |
| + } |
| + |
| /// Landscape keeps both bar buttons on screen, clear of the Dynamic |
| /// Island's side. |
| @MainActor func testLandscapeKeepsTheBarOnScreen() throws { |
diff --git a/native/ios/project.yml b/native/ios/project.yml| index c4bd67d..df87a13 100644 |
| --- a/native/ios/project.yml |
| +++ b/native/ios/project.yml |
| @@ -10,7 +10,7 @@ settings: |
| base: |
| SWIFT_VERSION: '5.0' |
| CODE_SIGN_STYLE: Automatic |
| - MARKETING_VERSION: '0.4.10' |
| + MARKETING_VERSION: '0.4.11' |
| CURRENT_PROJECT_VERSION: '1' |
| # The App Group the app and its broadcast extension share: the socket |
| # the iPhone's screen crosses lives in its container. One setting |
diff --git a/test/browser/call.mjs b/test/browser/call.mjs| index 05a98ac..e9f0029 100644 |
| --- a/test/browser/call.mjs |
| +++ b/test/browser/call.mjs |
| @@ -32,10 +32,11 @@ |
| // to nobody; and --auto-accept-this-tab-capture answers getDisplayMedia |
| // with no picker, which the fake-ui flag does not cover (§5.4). |
| import { syntheticMedia } from './synthetic-media.mjs'; |
| +import { portraitCamera } from './portrait-camera.mjs'; |
| import { writeSync, mkdirSync, writeFileSync } from 'node:fs'; |
| import { inflateSync } from 'node:zlib'; |
| import { createInterface } from 'node:readline'; |
| -import { chromium } from 'playwright'; |
| +import { chromium, webkit } from 'playwright'; |
| const [origin, sqid, scenario] = process.argv.slice(2); |
| const cookieName = process.env.CALLS_COOKIE_NAME; |
| @@ -1273,6 +1274,127 @@ const refuseFirstPlay = () => { |
| }; |
| }; |
| +// ── the self view (2026-10-21) ─────────────────────────────────────── |
| +// |
| +// selfTile reads this tab's own tile: whether its <video> has the local |
| +// stream, whether that stream's camera is live, and whether the element |
| +// is actually playing it — its clock, its paused flag, its size — plus |
| +// what the tile says when it is not, and where the tile is (the floating |
| +// picture-in-picture, the stage or the filmstrip). |
| +function selfTile(page) { |
| + return page.evaluate(() => { |
| + const f = document.querySelector('#tiles figure.calls-tile-self'); |
| + if (!f) return null; |
| + const v = f.querySelector('video'); |
| + const s = v && v.srcObject; |
| + const track = s && s.getVideoTracks ? s.getVideoTracks()[0] : null; |
| + const cover = f.querySelector('.calls-tile-paused'); |
| + return { |
| + pip: f.classList.contains('calls-tile-pip'), |
| + stage: f.hasAttribute('data-stage'), |
| + hasStream: !!s, |
| + track: track ? track.readyState + (track.enabled ? '' : '/disabled') : 'none', |
| + paused: v.paused, |
| + time: Math.round(v.currentTime * 100) / 100, |
| + width: v.videoWidth, |
| + ready: v.readyState, |
| + cover: cover && !cover.hidden ? cover.textContent : '', |
| + }; |
| + }); |
| +} |
| + |
| +// selfAdvancing waits for the self view to be playing a live camera: |
| +// not paused, a picture with a size, and its clock moving between two |
| +// reads. Paused and a still clock is the black tile of 2026-10-21. |
| +async function selfAdvancing(page, ms = 12000) { |
| + return until(async () => { |
| + const one = await selfTile(page); |
| + if (!one || one.paused || !one.width || !one.track.startsWith('live')) return false; |
| + await sleep(600); |
| + const two = await selfTile(page); |
| + return two && !two.paused && two.time > one.time ? two : false; |
| + }, ms); |
| +} |
| + |
| +// selfPainted is whether the self view is a picture on screen and not a |
| +// black box: a screenshot of the middle of its <video>, and how much of |
| +// it is neither black nor the tile's own #212121. This is the half the |
| +// element's clock cannot answer — a compositor that draws a playing |
| +// video as black (WebKit and a backdrop-filter or a transform, say). |
| +async function selfPainted(page, which = '#tiles figure.calls-tile-self video') { |
| + const box = await page.locator(which).boundingBox(); |
| + if (!box || box.width < 20 || box.height < 20) return { lit: 0, box }; |
| + const clip = { x: box.x + box.width * 0.2, y: box.y + box.height * 0.15, width: box.width * 0.6, height: box.height * 0.5 }; |
| + const img = decodePNG(await shoot(page, { clip })); |
| + let lit = 0; |
| + for (let j = 0; j < img.height; j++) { |
| + for (let i = 0; i < img.width; i++) { |
| + const c = img.rgb(i, j); |
| + const far = (v) => Math.max(Math.abs(c[0] - v), Math.abs(c[1] - v), Math.abs(c[2] - v)) > 24; |
| + if (far(0) && far(33)) lit++; |
| + } |
| + } |
| + return { lit: Math.round((lit / (img.width * img.height)) * 100) / 100 }; |
| +} |
| + |
| +// shoot is page.screenshot for a page whose CSP the gate is watching. In |
| +// WebKit, Playwright's screenshot puts a stylesheet of its own into the |
| +// page, and WebKit holds that to the page's CSP and reports it — a |
| +// violation by the instrument, not by the page. Only those reports, and |
| +// only the ones that arrive while the screenshot is being taken, are |
| +// taken back off the books. |
| +const PLAYWRIGHT_STYLE = /^Refused to apply a stylesheet because its hash, its nonce, or 'unsafe-inline' does not appear in the style-src directive/; |
| +async function shoot(page, opts) { |
| + const csp = cspViolations.length; |
| + const errs = new Map(Array.from(consoleErrors, ([label, list]) => [label, list.length])); |
| + const img = await page.screenshot({ caret: 'initial', ...opts }); |
| + await sleep(200); |
| + const keep = (list, from, text) => { |
| + const tail = list.splice(from); |
| + list.push(...tail.filter((line) => !PLAYWRIGHT_STYLE.test(text(line)))); |
| + }; |
| + keep(cspViolations, csp, (line) => line.replace(/^[^:]*: /, '')); |
| + for (const [label, from] of errs) keep(consoleErrors.get(label), from, (line) => line); |
| + return img; |
| +} |
| + |
| +// gumTap keeps every stream the room opened, so a scenario can end its |
| +// tracks as the system would. |
| +const gumTap = () => { |
| + window.__gum = []; |
| + const md = navigator.mediaDevices; |
| + if (!md || !md.getUserMedia) return; |
| + const gum = md.getUserMedia.bind(md); |
| + md.getUserMedia = async (c) => { |
| + if (window.__noCamera && c && c.video) throw new DOMException('camera busy', 'NotReadableError'); |
| + const s = await gum(c); |
| + window.__gum.push(s); |
| + return s; |
| + }; |
| + window.__noCamera = !!sessionStorage.getItem('calls.test.noCamera'); |
| +}; |
| + |
| +// hideAndShow is the tab going to the background and coming back, the |
| +// way native-webkit.mjs plays it: visibilityState is the page's to |
| +// believe, and the event is what room.js listens for. `during` is what |
| +// the system does meanwhile. |
| +async function hideAndShow(page, during) { |
| + await page.evaluate((what) => { |
| + if (what.pauseAll) for (const v of document.querySelectorAll('video')) v.pause(); |
| + if (what.endTracks) for (const s of window.__gum) for (const t of s.getTracks()) t.stop(); |
| + let shown = 'hidden'; |
| + Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => shown }); |
| + Object.defineProperty(document, 'hidden', { configurable: true, get: () => shown === 'hidden' }); |
| + document.dispatchEvent(new Event('visibilitychange')); |
| + window.__show = () => { |
| + shown = 'visible'; |
| + document.dispatchEvent(new Event('visibilitychange')); |
| + }; |
| + }, during); |
| + await sleep(1000); |
| + await page.evaluate(() => window.__show()); |
| +} |
| + |
| // glowOf is the warm rim on a tile's name label as it is drawn (0.4.3): |
| // whether it is lit, its --lvl and --on, the shadow the browser computed |
| // for the label's ::after from them, and the most opaque of that shadow's |
| @@ -5330,6 +5452,170 @@ const run = { |
| await ctxB.close(); |
| }, |
| + // Portrait video (2026-10-21, Paul, after Farshad joined from an |
| + // iPhone held upright: "Can we detect vertical video and display it |
| + // appropriately?"). B's camera is upright (portrait-camera.mjs, 720 × |
| + // 1280, a red band across its top and a green one across its bottom). |
| + // On A's landscape stage it is fitted whole, both bands showing, with |
| + // its backdrop painted; in Grid and in the filmstrip, tiles keep their |
| + // 16:9 shape and B's is fitted in them; on an upright phone it fills; |
| + // B's own self view floats upright; a landscape camera on an upright |
| + // phone is fitted; and B turning the phone on its side mid-call makes |
| + // A's stage fill again, its shape and placement each changing once. |
| + // CALLS_PORTRAIT_SNAPSHOTS=<dir> keeps pictures, before (0.4.10's |
| + // fill, forced) and after. |
| + async portrait() { |
| + const out = process.env.CALLS_PORTRAIT_SNAPSHOTS; |
| + if (out) mkdirSync(out, { recursive: true }); |
| + const ctxA = await newContext('portrait A', { cookie: cookieA }); |
| + const ctxB = await newContext('portrait B', { cookie: cookieB }); |
| + await ctxB.addInitScript(portraitCamera); |
| + const pageA = await openRoom(ctxA); |
| + const pageB = await openRoom(ctxB); |
| + const pair = await assertPair(pageA, pageB, 'portrait A', 'portrait B'); |
| + if (!pair) throw new Error('portrait call did not connect'); |
| + const a = pair.a.peer; |
| + const b = pair.b.peer; |
| + for (const page of [pageA, pageB]) { |
| + await page.setViewportSize({ width: 1280, height: 800 }); |
| + await chooseLayout(page, 'speaker'); |
| + } |
| + const look = (page, key) => page.evaluate((k) => { |
| + const fig = document.querySelector('#tiles > figure[data-tile="' + k + '"]'); |
| + if (!fig) return null; |
| + const v = fig.querySelector('video'); |
| + const c = fig.querySelector('.calls-tile-backdrop'); |
| + const r = fig.getBoundingClientRect(); |
| + return { |
| + stage: fig.hasAttribute('data-stage'), pip: fig.classList.contains('calls-tile-pip'), |
| + fit: fig.dataset.fit || '', shape: fig.dataset.shape || '', plain: fig.dataset.backdrop === 'plain', |
| + video: [v.videoWidth, v.videoHeight], objectFit: getComputedStyle(v).objectFit, |
| + box: { x: r.x, y: r.y, width: r.width, height: r.height }, |
| + backdrop: c ? { shown: getComputedStyle(c).display !== 'none', painted: +(c.dataset.painted || 0), costMs: +(c.dataset.costMs || 0), size: [c.width, c.height] } : null, |
| + }; |
| + }, key); |
| + // Where the picture is drawn in its tile, from the element's box and |
| + // object-fit: what `contain` or `cover` makes of 720 × 1280. |
| + const content = (t) => { |
| + const [vw, vh] = t.video; |
| + const s = (t.objectFit === 'contain' ? Math.min : Math.max)(t.box.width / vw, t.box.height / vh); |
| + const w = vw * s; |
| + const h = vh * s; |
| + const y = t.objectFit === 'contain' ? (t.box.height - h) / 2 : (t.box.height - h) * 0.35; |
| + return { x: t.box.x + (t.box.width - w) / 2, y: t.box.y + y, width: w, height: h }; |
| + }; |
| + const red = (c) => c[0] > 180 && c[1] < 90 && c[2] < 90; |
| + const green = (c) => c[1] > 180 && c[0] < 110 && c[2] < 110; |
| + const bands = async (page, t) => { |
| + const midX = t.box.x + t.box.width / 2; |
| + const top = await sampleColour(page, midX, t.box.y + Math.max(4, t.box.height * 0.02)); |
| + const bottom = await sampleColour(page, midX, t.box.y + t.box.height - Math.max(4, t.box.height * 0.02)); |
| + return { top, bottom, whole: red(top) && green(bottom) }; |
| + }; |
| + const shoot = async (page, name) => { if (out) await page.screenshot({ path: out + '/web-' + name + '.png' }); }; |
| + const settle = async (page, key, want, ms = 15000) => until(async () => { |
| + const t = await look(page, key); |
| + return t && want(t) ? t : false; |
| + }, ms); |
| + await pageA.evaluate(() => window.callsChrome.pin(false)); |
| + await pageB.evaluate(() => window.callsChrome.pin(false)); |
| + |
| + // A's landscape stage, B upright on it. |
| + // Upright: its sender may scale it (720 × 1280 arrives as 540 × 960 |
| + // on a cold start) but never turn it. |
| + let t = await settle(pageA, b, (x) => x.stage && x.video[1] > x.video[0] * 1.5 && x.fit === '1' && x.backdrop.painted > 1); |
| + check(t, 'B\'s upright camera is on A\'s stage, fitted, its backdrop painted — ' + JSON.stringify(t || (await look(pageA, b)))); |
| + if (t) { |
| + check(t.shape === 'portrait' && t.objectFit === 'contain', 'it reads as portrait and is shown whole (' + t.shape + ', ' + t.objectFit + ')'); |
| + check(t.backdrop.shown && t.backdrop.size[0] === 36 && t.backdrop.size[1] === 64, 'its backdrop shows, sampled upright (' + t.backdrop.size.join(' × ') + ')'); |
| + const c = content(t); |
| + check(Math.abs(c.height - t.box.height) < 1 && c.width < t.box.width / 2, |
| + 'the whole frame is in the window: ' + c.width.toFixed(0) + ' × ' + c.height.toFixed(0) + ' in ' + t.box.width + ' × ' + t.box.height); |
| + await sleep(600); |
| + const seen = await bands(pageA, t); |
| + check(seen.whole, 'its top and bottom both show on screen: red ' + seen.top + ', green ' + seen.bottom); |
| + await shoot(pageA, 'desktop-stage-portrait-after'); |
| + // 0.4.10, for the record: forced back to fill, the bands are gone. |
| + await pageA.evaluate((k) => { document.querySelector('#tiles > figure[data-tile="' + k + '"]').dataset.fit = '0'; }, b); |
| + await sleep(400); |
| + const before = await bands(pageA, { ...t, objectFit: 'cover' }); |
| + check(!before.whole, 'as 0.4.10 filled it, neither band showed (red ' + before.top + ', green ' + before.bottom + ')'); |
| + await shoot(pageA, 'desktop-stage-portrait-before'); |
| + await pageA.evaluate((k) => { document.querySelector('#tiles > figure[data-tile="' + k + '"]').dataset.fit = '1'; }, b); |
| + } |
| + |
| + // B's own self view, floating: upright, as its camera is. |
| + const self = await settle(pageB, 'self', (x) => x.pip && x.shape === 'portrait'); |
| + check(self && self.box.height > self.box.width * 1.5, 'B\'s upright self view floats upright — ' + JSON.stringify(self && self.box)); |
| + // And A's landscape camera on B's landscape stage fills, as before. |
| + t = await settle(pageB, a, (x) => x.stage && x.video[0] > 0 && x.fit === '0'); |
| + check(t && t.objectFit === 'cover', 'A\'s landscape camera fills B\'s landscape stage (' + (t && t.objectFit) + ')'); |
| + await shoot(pageB, 'desktop-self-portrait-after'); |
| + |
| + // The filmstrip: A pins herself; B's tile keeps its 16:9 and is fitted. |
| + await openTileMenu(pageA, 'self'); |
| + await pageA.locator('#tile-menu [data-act="pin"]').click(); |
| + t = await settle(pageA, b, (x) => !x.stage && x.fit === '1' && x.backdrop.shown); |
| + check(t && Math.abs(t.box.width / t.box.height - 16 / 9) < 0.05, 'in the filmstrip B\'s tile stays 16:9 and is fitted with its backdrop — ' + JSON.stringify(t && t.box)); |
| + await shoot(pageA, 'desktop-filmstrip-portrait-after'); |
| + // Grid: the same, tiles uniform. |
| + await chooseLayout(pageA, 'grid'); |
| + t = await settle(pageA, b, (x) => x.fit === '1' && x.backdrop.shown); |
| + const self2 = await look(pageA, 'self'); |
| + check(t && self2 && Math.abs(t.box.width - self2.box.width) < 1 && Math.abs(t.box.height - self2.box.height) < 1, |
| + 'in Grid every tile is one shape, B\'s fitted in its own — ' + JSON.stringify([t && t.box, self2 && self2.box])); |
| + await shoot(pageA, 'desktop-grid-portrait-after'); |
| + await chooseLayout(pageA, 'speaker'); |
| + await openTileMenu(pageA, 'self'); |
| + await pageA.locator('#tile-menu [data-act="pin"]').click(); |
| + |
| + // Phones. A upright phone viewing B's upright camera: fills. |
| + await pageA.setViewportSize({ width: 390, height: 844 }); |
| + t = await settle(pageA, b, (x) => x.stage && x.fit === '0'); |
| + check(t && t.objectFit === 'cover', 'on an upright phone B\'s upright camera fills (' + (t && t.objectFit) + ')'); |
| + await shoot(pageA, 'phone-viewing-portrait-after'); |
| + // B on an upright phone viewing A's landscape camera: fitted. |
| + await pageB.setViewportSize({ width: 390, height: 844 }); |
| + t = await settle(pageB, a, (x) => x.stage && x.fit === '1' && x.backdrop.painted > 0); |
| + check(t && t.objectFit === 'contain', 'on an upright phone A\'s landscape camera is shown whole (' + (t && t.objectFit) + ')'); |
| + await sleep(600); |
| + await shoot(pageB, 'phone-viewing-landscape-after'); |
| + await pageB.evaluate((k) => { document.querySelector('#tiles > figure[data-tile="' + k + '"]').dataset.fit = '0'; }, a); |
| + await sleep(300); |
| + await shoot(pageB, 'phone-viewing-landscape-before'); |
| + await pageB.evaluate((k) => { document.querySelector('#tiles > figure[data-tile="' + k + '"]').dataset.fit = '1'; }, a); |
| + await pageB.setViewportSize({ width: 1280, height: 800 }); |
| + await pageA.setViewportSize({ width: 1280, height: 800 }); |
| + |
| + // B turns the phone on its side mid-call. |
| + t = await settle(pageA, b, (x) => x.stage && x.fit === '1'); |
| + check(t, 'B is back on A\'s landscape stage, fitted'); |
| + await pageA.evaluate((k) => { |
| + const fig = document.querySelector('#tiles > figure[data-tile="' + k + '"]'); |
| + window.__portraitChanges = { fit: 0, shape: 0 }; |
| + new MutationObserver((list) => { |
| + for (const m of list) { |
| + if (m.attributeName === 'data-fit') window.__portraitChanges.fit += 1; |
| + if (m.attributeName === 'data-shape') window.__portraitChanges.shape += 1; |
| + } |
| + }).observe(fig, { attributes: true, attributeFilter: ['data-fit', 'data-shape'] }); |
| + }, b); |
| + await pageB.evaluate(() => window.__turnCamera(1280, 720)); |
| + t = await settle(pageA, b, (x) => x.video[0] === 1280 && x.video[1] === 720); |
| + await sleep(2000); |
| + t = await look(pageA, b); |
| + const changes = await pageA.evaluate(() => window.__portraitChanges); |
| + check(t && t.fit === '0' && t.shape === 'landscape' && t.objectFit === 'cover', 'turned on its side, B fills A\'s stage again (' + JSON.stringify(t && [t.fit, t.shape, t.objectFit]) + ')'); |
| + check(changes.fit === 1 && changes.shape === 1, 'the turn switched once: placement ' + changes.fit + ', shape ' + changes.shape); |
| + const cost = t && t.backdrop ? t.backdrop.costMs : NaN; |
| + line('portrait: the backdrop\'s slowest paint was ' + cost + ' ms, twice a second'); |
| + check(cost < 8, 'a backdrop paint is cheap (' + cost + ' ms)'); |
| + await leaveRoom(pageA); |
| + await leaveRoom(pageB); |
| + await ctxA.close(); |
| + await ctxB.close(); |
| + }, |
| + |
| // The call window (2026-09-28). Paul asked for the web call to be |
| // more like the Mac's: the whole call in a rounded window inset from |
| // the viewport. So: the window is inset with rounded corners on a |
| @@ -6134,6 +6420,15 @@ const run = { |
| await ctxB.close(); |
| }, |
| + // The self view, in Chromium and in WebKit (2026-10-21: on an iPhone |
| + // in Safari the floating self view was black for a whole call while |
| + // the camera was being sent perfectly well). Every way the local |
| + // picture can be handed to its element, or taken from it, followed by |
| + // the one thing that matters: the element is playing a live camera. |
| + // A in a phone-sized window, so a call of two floats the self view. |
| + async selfview() { await selfView('chromium'); }, |
| + async selfviewwebkit() { await selfView('webkit'); }, |
| + |
| async scriptless() { |
| const ctx = await newContext('scriptless', { cookie: cookieA, javaScriptEnabled: false }); |
| const sentence = 'The call needs JavaScript to reach your camera and the other participants; everything else on this page works without it.'; |
| @@ -6172,6 +6467,156 @@ const run = { |
| }, |
| }; |
| +// selfView is both engines' scenario. B and the guest are Chromium |
| +// whichever engine A is in: only A's own tile is under test. |
| +async function selfView(engine) { |
| + const wk = engine === 'webkit' ? await webkit.launch({ headless: true }) : null; |
| + const options = { viewport: { width: 390, height: 844 } }; |
| + if (wk) options.permissions = ['camera', 'microphone']; |
| + try { |
| + const ctxA = await newContext('self A', { cookie: cookieA, via: wk || browser, options }); |
| + await ctxA.addInitScript(gumTap); |
| + const ctxB = await newContext('self B', { cookie: cookieB }); |
| + const ctxG = await newContext('self guest'); |
| + const pageA = await openRoom(ctxA); |
| + const pageB = await openRoom(ctxB); |
| + const pair = await assertPair(pageA, pageB, engine + ' A', 'B'); |
| + if (!pair) return; |
| + const say = async (what) => engine + ': ' + what + ' (' + JSON.stringify(await selfTile(pageA)) + ')'; |
| + |
| + const first = await selfAdvancing(pageA); |
| + check(first, await say('the self view plays in a call of two')); |
| + check(first && first.pip, await say('and floats, in a phone-sized window')); |
| + const painted = await until(async () => { |
| + const p = await selfPainted(pageA); |
| + return p.lit > 0.01 ? p : false; |
| + }, 5000); |
| + check(painted, engine + ': and is a picture on screen, not a black box (' + JSON.stringify(painted || (await selfPainted(pageA))) + |
| + '; the stage beside it: ' + JSON.stringify(await selfPainted(pageA, '#tiles > [data-stage] video')) + ')'); |
| + const shots = process.env.CALLS_SELF_SNAPSHOTS; |
| + if (shots) mkdirSync(shots, { recursive: true }); |
| + const shot = async (name) => { if (shots) await shoot(pageA, { path: shots + '/' + engine + '-' + name + '.png' }); }; |
| + await shot('pip'); |
| + |
| + // The camera off and on again: the track is disabled, not replaced, |
| + // and the picture has to come back with it. |
| + await pageA.evaluate(() => document.getElementById('camera').click()); |
| + await until(async () => (await selfTile(pageA)).track.endsWith('/disabled'), 5000); |
| + await pageA.evaluate(() => document.getElementById('camera').click()); |
| + check(await selfAdvancing(pageA), await say('the self view plays after the camera is turned off and on')); |
| + |
| + // The system pausing the page's media in the background and leaving |
| + // the tracks alone (iOS does this; Low Power Mode more readily). |
| + await hideAndShow(pageA, { pauseAll: true }); |
| + check(await selfAdvancing(pageA), await say('the self view plays again when the tab is back after its media was paused')); |
| + |
| + // The system ending the camera and microphone outright: comeBack |
| + // opens them again, and the new camera must reach the self view. |
| + await hideAndShow(pageA, { pauseAll: true, endTracks: true }); |
| + check(await selfAdvancing(pageA, 15000), await say('the self view plays the reopened camera when the tab is back')); |
| + |
| + // The element stopping with no event to say so: the self-view watch |
| + // has to notice by itself. |
| + await pageA.evaluate(() => document.querySelector('#tiles figure.calls-tile-self video').pause()); |
| + check(await selfAdvancing(pageA, 10000), await say('a self view paused behind the page’s back plays again by itself')); |
| + |
| + // A browser that will not play it at all (Low Power Mode refusing |
| + // autoplay): never a black box with nothing said. The tile says the |
| + // preview is paused, as a button, and the button brings it back. |
| + await pageA.evaluate(() => { |
| + const real = HTMLMediaElement.prototype.play; |
| + window.__realPlay = real; |
| + HTMLMediaElement.prototype.play = function play() { |
| + if (this.closest && this.closest('.calls-tile-self')) { |
| + this.pause(); |
| + return Promise.reject(new DOMException('preview refused', 'NotAllowedError')); |
| + } |
| + return real.apply(this, arguments); |
| + }; |
| + const v = document.querySelector('#tiles figure.calls-tile-self video'); |
| + v.autoplay = false; |
| + v.pause(); |
| + }); |
| + const said = await until(async () => { |
| + const t = await selfTile(pageA); |
| + return t && t.paused && t.cover ? t : false; |
| + }, 10000); |
| + check(said && said.cover === 'Your camera preview is paused.Show it', await say('a self view that will not play says so, as a button')); |
| + const cover = await pageA.locator('#tiles figure.calls-tile-self .calls-tile-paused').boundingBox(); |
| + const tileBox = await pageA.locator('#tiles figure.calls-tile-self').boundingBox(); |
| + check(cover && tileBox && Math.abs(cover.width - tileBox.width) < 1 && Math.abs(cover.height - tileBox.height) < 1, |
| + engine + ': the button covers the whole floating tile (' + JSON.stringify({ cover, tileBox }) + ')'); |
| + await shot('paused'); |
| + const s = await state(pageA); |
| + check(!s.audioBlocked && !s.soundBanner, 'and that is not mistaken for sound being blocked (' + JSON.stringify({ blocked: s.audioBlocked, banner: s.soundBanner }) + ')'); |
| + await pageA.evaluate(() => { HTMLMediaElement.prototype.play = window.__realPlay; }); |
| + await pageA.locator('#tiles figure.calls-tile-self .calls-tile-paused').click(); |
| + const back = await selfAdvancing(pageA); |
| + check(back && !back.cover, await say('the button brings the self view back and the words go')); |
| + |
| + // A third person: the self view leaves the corner for the filmstrip |
| + // and still plays. |
| + await signInAsGuest(ctxG); |
| + await openRoom(ctxG); |
| + check(await until(async () => (await pageA.locator('#knocks li').count()) >= 1 && await admitKnock(pageA, 'guest'), 20000), |
| + 'A lets the guest in (' + JSON.stringify(await queueNames(pageA)) + ')'); |
| + const three = await until(async () => ((await state(pageA)).peers.length === 2 ? true : false), 30000); |
| + check(three, engine + ': A is in a call of three'); |
| + const strip = await until(async () => { |
| + const t = await selfTile(pageA); |
| + return t && !t.pip ? t : false; |
| + }, 10000); |
| + check(strip, await say('in a call of three the self view is in the filmstrip, not floating')); |
| + check(await selfAdvancing(pageA), await say('and plays there')); |
| + check((await selfPainted(pageA)).lit > 0.01, engine + ': and is a picture there too (' + JSON.stringify(await selfPainted(pageA)) + ')'); |
| + await pageA.evaluate(() => document.getElementById('camera').click()); |
| + await until(async () => (await selfTile(pageA)).track.endsWith('/disabled'), 5000); |
| + await pageA.evaluate(() => document.getElementById('camera').click()); |
| + check(await selfAdvancing(pageA), await say('and after the camera is turned off and on there')); |
| + await hideAndShow(pageA, { pauseAll: true, endTracks: true }); |
| + check(await selfAdvancing(pageA, 15000), await say('and after the tab comes back with its camera reopened')); |
| + |
| + for (const page of ctxG.pages()) await leaveRoom(page); |
| + await leaveRoom(pageB); |
| + |
| + // Joining with no camera, which arrives later from the device panel: |
| + // the self view was drawn for a stream with no picture in it, and |
| + // the camera that comes later has to reach it. |
| + await leaveRoom(pageA); |
| + await pageA.evaluate(() => sessionStorage.setItem('calls.test.noCamera', '1')); |
| + await pageA.goto(origin + '/m/' + sqid, { waitUntil: 'domcontentloaded' }); |
| + await pageA.waitForFunction(() => !!window.meet, null, { timeout: 20000 }); |
| + const alone = await until(async () => { |
| + const t = await selfTile(pageA); |
| + return t && t.track === 'none' ? t : false; |
| + }, 15000); |
| + check(alone, await say('A joins with no camera')); |
| + await pageA.evaluate(() => { window.__noCamera = false; sessionStorage.removeItem('calls.test.noCamera'); }); |
| + // Through the picker's own change event: on a phone the Devices |
| + // panel is behind the controls sheet, and which button opens it is |
| + // not what this is about. |
| + const camera = await until(async () => await pageA.evaluate(() => { |
| + const pick = document.getElementById('pick-camera'); |
| + return pick && pick.options.length ? pick.options[0].value || ' ' : false; |
| + }), 10000); |
| + check(camera, 'the room lists a camera to choose'); |
| + await pageA.evaluate(() => { |
| + const pick = document.getElementById('pick-camera'); |
| + pick.value = pick.options[0].value; |
| + pick.dispatchEvent(new Event('change', { bubbles: true })); |
| + }); |
| + check(await selfAdvancing(pageA, 15000), await say('the camera chosen later plays in the self view')); |
| + |
| + check(errorsFor('self A') === '', 'no console errors in A (' + errorsFor('self A') + ')'); |
| + await leaveRoom(pageA); |
| + await ctxA.close(); |
| + await ctxB.close(); |
| + await ctxG.close(); |
| + } finally { |
| + if (wk) await wk.close(); |
| + } |
| +} |
| + |
| // ── run it ─────────────────────────────────────────────────────────── |
| const watchdog = setTimeout(() => { |
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); |
| + }; |
| +}; |
diff --git a/test/browser/room-portrait.test.mjs b/test/browser/room-portrait.test.mjs| new file mode 100644 |
| index 0000000..a8bb88e |
| --- /dev/null |
| +++ b/test/browser/room-portrait.test.mjs |
| @@ -0,0 +1,115 @@ |
| +// room-portrait.test.mjs — portrait video (2026-10-21), gated without a |
| +// browser: room.js's videoShape (the classifier, with hysteresis) and |
| +// videoFits (fill or fit), lifted out of the shipped file by name with |
| +// the constants they read. The native apps' VideoShapeTests hold |
| +// VideoShape, VideoShapeReading and VideoPlacement to the same table. |
| +// |
| +// node --test test/browser/room-portrait.test.mjs |
| +import { test } from 'node:test'; |
| +import assert from 'node:assert/strict'; |
| +import { readFileSync } from 'node:fs'; |
| +import { fileURLToPath } from 'node:url'; |
| + |
| +const roomJS = fileURLToPath(new URL('../../internal/calls/static/room.js', import.meta.url)); |
| +const src = readFileSync(roomJS, 'utf8'); |
| + |
| +function lift(name) { |
| + const start = src.indexOf('function ' + name + '('); |
| + assert.notEqual(start, -1, name + ' is not in room.js any more — this test is stale, not passing'); |
| + let depth = 0; |
| + for (let i = src.indexOf('{', start); i < src.length; i++) { |
| + if (src[i] === '{') depth += 1; |
| + else if (src[i] === '}') { |
| + depth -= 1; |
| + if (depth === 0) return src.slice(start, i + 1); |
| + } |
| + } |
| + assert.fail('unbalanced braces reading ' + name + ' out of room.js'); |
| +} |
| +function liftConst(name) { |
| + const m = src.match(new RegExp('const ' + name + ' = ([0-9.]+);')); |
| + assert.ok(m, name + ' is not a numeric const in room.js any more'); |
| + return 'const ' + name + ' = ' + m[1] + ';'; |
| +} |
| +const CONSTS = ['SHAPE_ENTER', 'SHAPE_HOLD', 'FIT_TOLERANCE'].map(liftConst).join('\n'); |
| +// eslint-disable-next-line no-new-func |
| +const { videoShape, videoFits } = new Function( |
| + CONSTS + '\n' + lift('videoShape') + '\n' + lift('videoFits') + '; return { videoShape, videoFits };')(); |
| + |
| +test('the thresholds: h > w × 1.1 is portrait, w > h × 1.1 landscape, square-ish between', () => { |
| + assert.equal(videoShape(720, 1280, ''), 'portrait'); |
| + assert.equal(videoShape(1280, 720, ''), 'landscape'); |
| + assert.equal(videoShape(640, 480, ''), 'landscape'); |
| + assert.equal(videoShape(500, 500, ''), 'square'); |
| + assert.equal(videoShape(1000, 1100, ''), 'square', 'exactly 1.1 is not yet portrait'); |
| + assert.equal(videoShape(1000, 1101, ''), 'portrait'); |
| + assert.equal(videoShape(1101, 1000, ''), 'landscape'); |
| + assert.equal(videoShape(0, 0, ''), 'landscape', 'nothing known is landscape, as 0.4.10'); |
| + assert.equal(videoShape(0, 0, 'portrait'), 'portrait', 'and nothing new keeps what was'); |
| +}); |
| + |
| +test('hysteresis holds a shape through the band, and lets go past it', () => { |
| + let s = videoShape(720, 1280, ''); |
| + assert.equal(s, 'portrait'); |
| + s = videoShape(1000, 1050, s); |
| + assert.equal(s, 'portrait', 'still taller than wide'); |
| + s = videoShape(1000, 1000, s); |
| + assert.equal(s, 'square', 'no longer taller than wide'); |
| + s = videoShape(1000, 1080, s); |
| + assert.equal(s, 'square', 'back into the band is not portrait again'); |
| + s = videoShape(1000, 1200, s); |
| + assert.equal(s, 'portrait'); |
| +}); |
| + |
| +test('a picture jittering about the threshold changes once, not every frame', () => { |
| + let s = videoShape(1000, 1000, ''); |
| + let changes = 0; |
| + for (let i = 0; i < 40; i++) { |
| + const next = videoShape(1000, i % 2 ? 1105 : 1095, s); |
| + if (next !== s) changes += 1; |
| + s = next; |
| + } |
| + assert.equal(changes, 1); |
| +}); |
| + |
| +test('a phone turned mid-call switches once, through resolution steps', () => { |
| + // videoWidth and videoHeight have the sender's rotation applied: an |
| + // upright iPhone arrives as 720 × 1280 whatever its buffer is. |
| + const sizes = [[1280, 720], [960, 540], [1280, 720], [720, 1280], [540, 960], [720, 1280]]; |
| + let s = ''; |
| + const seen = []; |
| + for (const [w, h] of sizes) { |
| + s = videoShape(w, h, s); |
| + if (seen[seen.length - 1] !== s) seen.push(s); |
| + } |
| + assert.deepEqual(seen, ['landscape', 'portrait']); |
| +}); |
| + |
| +test('fill or fit: the decision table', () => { |
| + const fits = (vw, vh, bw, bh, screen = false) => videoFits(vw, vh, videoShape(vw, vh, ''), bw, bh, screen); |
| + // A screen is always fitted. |
| + assert.equal(fits(1920, 1200, 1440, 900, true), true); |
| + // The same shape fills, however much it crops. |
| + assert.equal(fits(1280, 720, 1440, 900), false); |
| + assert.equal(fits(720, 1280, 393, 852), false); |
| + assert.equal(fits(2560, 1080, 320, 180), false, '21:9 in 16:9 crops 25% and fills'); |
| + assert.equal(fits(640, 480, 320, 180), false, '4:3 in a 16:9 tile fills'); |
| + // Another shape with a crop of 15% or less still fills. |
| + assert.equal(fits(1000, 1000, 1100, 1000), false); |
| + // Another shape with more is fitted. |
| + assert.equal(fits(720, 1280, 1440, 900), true, 'an upright phone on a landscape window'); |
| + assert.equal(fits(720, 1280, 320, 180), true, 'and in a grid or filmstrip tile'); |
| + assert.equal(fits(1280, 720, 393, 852), true, 'a laptop on an upright phone'); |
| + assert.equal(fits(720, 720, 1440, 900), true, 'a square picture in a 16:10 window'); |
| + assert.equal(fits(480, 640, 1080, 1000), true, 'portrait in a square-ish place, 31% cut'); |
| + // Nothing known yet: fill. |
| + assert.equal(videoFits(0, 0, 'portrait', 1440, 900, false), false); |
| + assert.equal(videoFits(720, 1280, 'portrait', 0, 0, false), false); |
| +}); |
| + |
| +test('the shape held by hysteresis is the one that decides', () => { |
| + // A picture that was portrait and is now 1000 × 1050 is still portrait, |
| + // so in a 16:9 tile it stays fitted rather than flipping to fill. |
| + assert.equal(videoFits(1000, 1050, 'portrait', 320, 180, false), true); |
| + assert.equal(videoFits(1000, 1050, 'square', 320, 180, false), true, 'square is another shape too'); |
| +}); |
diff --git a/test/browser/room-self.test.mjs b/test/browser/room-self.test.mjs| new file mode 100644 |
| index 0000000..03181d7 |
| --- /dev/null |
| +++ b/test/browser/room-self.test.mjs |
| @@ -0,0 +1,187 @@ |
| +// room-self.test.mjs — the self view is played, watched and, when the |
| +// browser will not play it, explained (2026-10-21: an iPhone in Safari |
| +// showed its own picture black for a whole call while sending it). |
| +// |
| +// node --test test/browser/room-self.test.mjs |
| +// |
| +// judgeSelf, playSelf and comeBack lifted out of the shipped room.js by |
| +// name, with the constants they read, as room-reconnect.test.mjs does. |
| +// The browser half is call.mjs's `selfview` and `selfviewwebkit`. |
| +import { test } from 'node:test'; |
| +import assert from 'node:assert/strict'; |
| +import { readFileSync } from 'node:fs'; |
| +import { fileURLToPath } from 'node:url'; |
| + |
| +const src = readFileSync(fileURLToPath(new URL('../../internal/calls/static/room.js', import.meta.url)), 'utf8'); |
| + |
| +function lift(name) { |
| + const start = src.indexOf('function ' + name + '('); |
| + assert.notEqual(start, -1, name + ' is not in room.js any more — this test is stale, not passing'); |
| + let depth = 0; |
| + for (let i = src.indexOf('{', start); i < src.length; i++) { |
| + if (src[i] === '{') depth += 1; |
| + else if (src[i] === '}') { |
| + depth -= 1; |
| + if (depth === 0) return src.slice(start, i + 1); |
| + } |
| + } |
| + assert.fail('unbalanced braces reading ' + name); |
| +} |
| +function liftConst(name) { |
| + const m = src.match(new RegExp('const ' + name + ' = ([0-9.]+);')); |
| + assert.ok(m, name + ' is not a numeric const in room.js any more'); |
| + return 'const ' + name + ' = ' + m[1] + ';'; |
| +} |
| + |
| +// eslint-disable-next-line no-new-func |
| +const judgeSelf = new Function(liftConst('SELF_STUCK_MS') + '\n' + lift('judgeSelf') + '; return judgeSelf;')(); |
| +const STUCK = Number(liftConst('SELF_STUCK_MS').match(/= ([0-9.]+)/)[1]); |
| + |
| +const fresh = () => ({ time: -1, since: -1, tries: 0, said: false }); |
| +const live = (now, time, paused = false) => ({ live: true, visible: true, paused, time, now }); |
| + |
| +// Once a second from `from` for `n` polls, the element's clock and paused |
| +// flag from `at(now)`; the verdicts that were not empty, with their times. |
| +function poll(w, from, n, at) { |
| + const out = []; |
| + for (let i = 0; i < n; i++) { |
| + const now = from + i * 1000; |
| + const v = judgeSelf(w, { live: true, visible: true, now, ...at(now) }); |
| + if (v) out.push([now, v]); |
| + } |
| + return out; |
| +} |
| + |
| +test('a self view that is playing is left alone', () => { |
| + const w = fresh(); |
| + assert.deepEqual(poll(w, 0, 10, (now) => ({ paused: false, time: now / 1000 })), []); |
| +}); |
| + |
| +test('a paused self view is replayed once, then said, two seconds apart', () => { |
| + const w = fresh(); |
| + const got = poll(w, 0, 8, () => ({ paused: true, time: 3 })); |
| + assert.deepEqual(got, [[STUCK, 'replay'], [2 * STUCK, 'say']]); |
| + assert.equal(w.said, true); |
| +}); |
| + |
| +test('a self view that is not paused but whose clock stands still counts as stuck', () => { |
| + const w = fresh(); |
| + const got = poll(w, 0, 6, () => ({ paused: false, time: 1.5 })); |
| + assert.deepEqual(got.map(([, v]) => v), ['replay', 'say']); |
| +}); |
| + |
| +test('the words come down as soon as the picture moves again, and the watch starts over', () => { |
| + const w = fresh(); |
| + poll(w, 0, 6, () => ({ paused: true, time: 3 })); |
| + assert.equal(w.said, true); |
| + assert.equal(judgeSelf(w, live(6000, 3.2)), 'clear'); |
| + assert.equal(w.said, false); |
| + assert.equal(w.tries, 0); |
| + // A second stall gets its own replay before anything is said. |
| + const again = poll(w, 7000, 6, () => ({ paused: true, time: 3.2 })); |
| + assert.deepEqual(again.map(([, v]) => v), ['replay', 'say']); |
| +}); |
| + |
| +test('a replay that works is never said', () => { |
| + const w = fresh(); |
| + let t = 2; |
| + const got = poll(w, 0, 10, (now) => (now <= STUCK ? { paused: true, time: t } : { paused: false, time: (t += 1) })); |
| + assert.deepEqual(got.map(([, v]) => v), ['replay']); |
| + assert.equal(w.said, false); |
| +}); |
| + |
| +test('a camera that is off, muted or ended, or a hidden tab, is not the watch’s business', () => { |
| + for (const s of [{ live: false, visible: true }, { live: true, visible: false }]) { |
| + const w = fresh(); |
| + for (let now = 0; now < 10000; now += 1000) { |
| + assert.equal(judgeSelf(w, { ...s, paused: true, time: 0, now }), ''); |
| + } |
| + assert.equal(w.tries, 0); |
| + } |
| + // And one that goes off while the words are up takes them down: the |
| + // camera-off cover says what there is to say. |
| + const w = fresh(); |
| + poll(w, 0, 6, () => ({ paused: true, time: 0 })); |
| + assert.equal(w.said, true); |
| + assert.equal(judgeSelf(w, { live: false, visible: true, paused: true, time: 0, now: 7000 }), 'clear'); |
| +}); |
| + |
| +test('a clock that went backwards (a new binding) is a start, not a stall cleared', () => { |
| + const w = fresh(); |
| + judgeSelf(w, live(0, 9)); |
| + // Rebinding resets the element's clock: not moving, so the watch starts |
| + // its two seconds rather than calling it playing. |
| + assert.equal(judgeSelf(w, live(1000, 0)), ''); |
| + assert.equal(judgeSelf(w, live(2000, 0.6)), ''); |
| + assert.equal(w.since, -1); |
| +}); |
| + |
| +// playSelf over a fake element: what a refusal and a success do to the |
| +// tile, and that neither is ever §15.20's sound refusal. |
| +function playHarness(result) { |
| + const drawn = []; |
| + const t = { |
| + video: { play: () => result }, |
| + selfWatch: { time: -1, since: -1, tries: 0, said: false }, |
| + }; |
| + const tiles = new Map([['self', t]]); |
| + // eslint-disable-next-line no-new-func |
| + const playSelf = new Function('tiles', 'drawSelfNote', 'soundRefused', 'startPlaying', |
| + lift('playSelf') + '; return playSelf;')(tiles, (x) => drawn.push(x.selfWatch.said), |
| + () => assert.fail('a self view is never a sound refusal'), |
| + () => assert.fail('a self view never goes through startPlaying')); |
| + return { t, drawn, playSelf }; |
| +} |
| + |
| +test('a refused preview is said at once, on the tile', async () => { |
| + const h = playHarness(Promise.reject(new DOMException('no', 'NotAllowedError'))); |
| + h.playSelf(h.t); |
| + await new Promise((r) => setTimeout(r, 0)); |
| + assert.equal(h.t.selfWatch.said, true); |
| + assert.deepEqual(h.drawn, [true]); |
| +}); |
| + |
| +test('a play that was only interrupted (AbortError) says nothing', async () => { |
| + const h = playHarness(Promise.reject(new DOMException('new load', 'AbortError'))); |
| + h.playSelf(h.t); |
| + await new Promise((r) => setTimeout(r, 0)); |
| + assert.equal(h.t.selfWatch.said, false); |
| + assert.deepEqual(h.drawn, []); |
| +}); |
| + |
| +test('a play that works takes the words down', async () => { |
| + const h = playHarness(Promise.resolve()); |
| + h.t.selfWatch.said = true; |
| + h.playSelf(h.t); |
| + await new Promise((r) => setTimeout(r, 0)); |
| + assert.equal(h.t.selfWatch.said, false); |
| + assert.deepEqual(h.drawn, [false]); |
| +}); |
| + |
| +// comeBack over fakes: the self tile is asked to play again along with |
| +// the remote ones — the line whose absence left it black. |
| +test('the tab coming back plays a paused self view, through playSelf', () => { |
| + const played = []; |
| + const started = []; |
| + const selfT = { video: { paused: true }, stream: {} }; |
| + const remote = { video: { paused: true }, stream: {}, play: { hidden: true } }; |
| + const tiles = new Map([['self', selfT], ['peer1', remote]]); |
| + const local = { getAudioTracks: () => [], getVideoTracks: () => [] }; |
| + // eslint-disable-next-line no-new-func |
| + const comeBack = new Function('state', 'local', 'lostKinds', 'prefs', 'switchDevice', 'tiles', 'shouldPlay', |
| + 'startPlaying', 'playSelf', lift('comeBack') + '; return comeBack;')( |
| + { stopped: false, leaveSent: false }, local, () => [], {}, () => Promise.resolve(), tiles, |
| + (t, isSelf) => !isSelf && !!t.stream, (key) => started.push(key), (t) => played.push(t)); |
| + comeBack(); |
| + assert.deepEqual(played, [selfT]); |
| + assert.deepEqual(started, ['peer1']); |
| +}); |
| + |
| +// The binding: tile() hands ours to playSelf whenever it binds a stream, |
| +// rather than trusting `autoplay`. tile() builds DOM and is not lifted; |
| +// this holds the one line in place. |
| +test('tile() asks the self view to play on every binding', () => { |
| + const body = lift('tile'); |
| + assert.match(body, /if \(isSelf\) \{\s*if \(stream\) playSelf\(t\);/); |
| + assert.match(lift('pollFrames'), /watchSelf\(\);/); |
| +}); |