oficina / meet Public

Calls: the Mac and iPhone apps ask each sender for less video, and send less when asked (spec 15.30)

VideoAdapt is room.js's watch number for number, read from the quality
report's own counters once a second; a connection's camera and screen go
out at the level its peer asks, and Audio only sends no camera at all.
Devices gains Video quality; tiles say Low bandwidth, and Video paused to
keep audio clear at audio only; the sender is told who it sends less to;
the quality report carries the seconds at each level.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 6d3f9000d3f9826d88b05ad02c77b3b78f544691 parent 8c401ba
14 files changed, +986 −21
  • native/apple/Sources/CallsKit/Call.swift +152 −1
  • native/apple/Sources/CallsKit/DevicePanel.swift +20 −0
  • native/apple/Sources/CallsKit/InviteLinkCopy.swift +2 −2
  • native/apple/Sources/CallsKit/MacCallView.swift +3 −1
  • native/apple/Sources/CallsKit/MacVideoTile.swift +15 −5
  • native/apple/Sources/CallsKit/Media.swift +26 −2
  • native/apple/Sources/CallsKit/MiniWindow.swift +2 −0
  • native/apple/Sources/CallsKit/MutedBadge.swift +23 −0
  • native/apple/Sources/CallsKit/QualityReport.swift +30 −2
  • native/apple/Sources/CallsKit/ScreenSendPolicy.swift +5 −1
  • native/apple/Sources/CallsKit/VideoAdapt.swift +384 −0
  • native/apple/Sources/CallsKit/Wire.swift +23 −1
  • native/apple/Tests/CallsKitTests/VideoAdaptTests.swift +284 −0
  • native/ios/Sources/CallsPhone.swift +17 −6
diff --git a/native/apple/Sources/CallsKit/Call.swift b/native/apple/Sources/CallsKit/Call.swift
index beffa0a..e67e49d 100644
--- a/native/apple/Sources/CallsKit/Call.swift
+++ b/native/apple/Sources/CallsKit/Call.swift
@@ -2,6 +2,9 @@ import Combine
import Foundation
#if os(iOS)
import AVFoundation
+ import UIKit
+#else
+ import AppKit
#endif
// Go serializes this API with a mutex; Objective-C bindings carry no Sendable annotation.
@preconcurrency import CallsBridge
@@ -122,6 +125,29 @@ private final class Events: NSObject, BridgeListenerProtocol {
private var heardFrom: [String: (epoch: Int64, heard: Bool)] = [:]
private var ackedBy: [String: Int64] = [:]
private var reportedHearing: [String] = []
+ /// Spec §15.30: each sender's adaptive watch, the counters it last read
+ /// them from (per connection generation), when it last looked, and the
+ /// asks last reported.
+ private var adapt: [String: VideoAdapt] = [:]
+ private var adaptCounters: [String: (generation: Int64, counters: QualityCounters)] = [:]
+ private var adaptLookedAt: Double?
+ private var reportedVideo: [String: String] = [:]
+ /// What this app asks each person for, as the tiles show it: peer id to
+ /// level, only those below normal.
+ @Published public private(set) var videoAsks: [String: String] = [:]
+ /// The sender's notice while it lasts: "Sending reduced video to …".
+ @Published public private(set) var videoNotice = ""
+ /// The person's own Video quality (device panel), remembered.
+ @Published public var videoQuality: VideoQualitySetting = .remembered {
+ didSet {
+ guard videoQuality != oldValue else { return }
+ VideoQualitySetting.remembered = videoQuality
+ CallLog.info("video quality: \(videoQuality.rawValue)")
+ applyVideoQuality()
+ }
+ }
+ /// The watch's clean time before a probe up; the gate shortens it.
+ @_spi(Fixtures) public var adaptUpAfter = VideoAdapt.upAfter
/// Quality reports (spec §15.26): the notices tallied over the window,
/// the running totals the last report was taken from, the loop that
/// sends one every `qualityInterval`, and whether the server has said to
@@ -412,6 +438,7 @@ private final class Events: NSObject, BridgeListenerProtocol {
guard epoch == joiningEpoch, bridge === client else { throw CancellationError() }
localTrack = media.localVideo
cameraChanged()
+ media.ownAudioOnly = videoQuality == .audio
reportMedia()
media.audio.reduceNoise = reduceNoise
audioProcessing = media.audio.report()
@@ -515,7 +542,10 @@ private final class Events: NSObject, BridgeListenerProtocol {
/// each toggle and once the tracks exist, and nowhere else. No track at
/// all is muted, or off, as far as anyone listening can tell.
private func reportMedia() {
- try? bridge?.setMedia(muted || media.localAudio == nil, cameraOff: cameraOff || media.localVideo == nil)
+ // §15.30: Audio only sends no camera to anyone, so it is off.
+ try? bridge?.setMedia(
+ muted || media.localAudio == nil,
+ cameraOff: cameraOff || media.localVideo == nil || videoQuality == .audio)
}
/// A remote peer's reported state, or nil when it has not reported.
@@ -524,6 +554,19 @@ private final class Events: NSObject, BridgeListenerProtocol {
public func isMuted(_ peer: String) -> Bool { peerMedia(peer)?.muted ?? false }
/// Whether a remote peer has said its camera is off. Unknown is not off.
public func isCameraOff(_ peer: String) -> Bool { peerMedia(peer)?.cameraOff ?? false }
+ /// Spec §15.30: whether this app is asking a peer for less video — the
+ /// tile's "Low bandwidth" badge.
+ public func isLowBandwidth(_ peer: String) -> Bool { videoAsks[peer] != nil }
+ /// Whether a peer's picture is paused to keep their audio clear: this app
+ /// asks them for audio only, and their camera is not off anyway.
+ public func isVideoPaused(_ peer: String) -> Bool { videoAsks[peer] == VideoLevel.audio.wire && !isCameraOff(peer) }
+ /// What a paused tile says: the words, and for an app too old to send
+ /// less, that it is only hidden here.
+ public func videoPausedWords(_ peer: String) -> String {
+ let client = state?.peers.first { $0.peer == peer }?.client
+ return VideoAdapt.honours(client: client)
+ ? VideoAdapt.pausedWords : VideoAdapt.pausedWords + ". " + VideoAdapt.oldAppWords
+ }
nonisolated static func peerMedia(_ peer: String, in state: RoomState?) -> PeerMedia? {
state?.peers.first { $0.peer == peer }?.media
}
@@ -665,6 +708,7 @@ private final class Events: NSObject, BridgeListenerProtocol {
self.sampleMic(now: now)
if tick % 2 == 0 { await self.samplePeers(stats: tick % 10 == 0, now: now) }
if tick % 10 == 5 { await self.watchRemoteScreens(now: now) }
+ if tick % 10 == 7 { await self.watchAdapt(now: now) }
}
}
}
@@ -672,6 +716,12 @@ private final class Events: NSObject, BridgeListenerProtocol {
private func endLevelWatch() {
levelWatch?.cancel()
levelWatch = nil
+ adapt = [:]
+ adaptCounters = [:]
+ adaptLookedAt = nil
+ reportedVideo = [:]
+ videoAsks = [:]
+ videoNotice = ""
screenReceiveWatch = ScreenReceiveWatch()
reportedStalled = []
screenReceived = [:]
@@ -1031,6 +1081,8 @@ private final class Events: NSObject, BridgeListenerProtocol {
ice = nil
}
if let ice { media.reconcile(state: state, ice: ice) }
+ // §15.30: and what each of them asks of us now.
+ answerVideoAsks(state)
case "ice":
guard let config = event.ice else { return }
let renewing = ice != nil
@@ -1452,6 +1504,105 @@ private final class Events: NSObject, BridgeListenerProtocol {
}
}
+// ---------------------------------------------------------------
+// Adaptive video (§15.30)
+// ---------------------------------------------------------------
+
+extension Call {
+ /// One look by every sender's watch, once a second from the level watch:
+ /// the quality report's own reading of each connection, the second since
+ /// the last, a step of that sender's watch; then the asks this app makes,
+ /// reported on a change; and the seconds at each level, asked and sent,
+ /// for the next quality report.
+ fileprivate func watchAdapt(now: Double) async {
+ guard let state, state.phase == "admitted" || state.phase == "reconnecting" else { return }
+ let samples = await media.qualitySamples()
+ guard levelWatch != nil, let current = self.state else { return }
+ let dt = adaptLookedAt.map { min(max(now - $0, 0), 2) } ?? 0
+ adaptLookedAt = now
+ #if os(macOS)
+ let watching = NSApplication.shared.isActive || !NSApplication.shared.isHidden
+ #else
+ let watching = UIApplication.shared.applicationState == .active
+ #endif
+ for (id, sample) in samples where id != current.peer {
+ let counters = QualityCounters(sample)
+ let before = adaptCounters[id].flatMap { $0.generation == sample.generation ? $0.counters : nil }
+ adaptCounters[id] = (sample.generation, counters)
+ guard let before else { continue }
+ var watch = adapt[id] ?? VideoAdapt(upAfter: adaptUpAfter)
+ let was = watch.level
+ let cameraWatched = watching && !isCameraOff(id)
+ watch.observe(at: now, VideoAdapt.sample(counters, before, cameraWatched: cameraWatched))
+ adapt[id] = watch
+ if watch.level != was {
+ CallLog.info("video from \(id.prefix(6)): \(was.wire) -> \(watch.level.wire)\(watch.level < was ? " (probe)" : "")")
+ }
+ }
+ for id in Array(adapt.keys) where samples[id] == nil { adapt.removeValue(forKey: id) }
+ for id in Array(adaptCounters.keys) where samples[id] == nil { adaptCounters.removeValue(forKey: id) }
+ reportVideo()
+ answerVideoAsks(current)
+ let sent = media.sentLevels
+ qualityTally.videoSetting = videoQuality
+ for id in samples.keys where id != current.peer {
+ let asked = videoAsks[id].flatMap(VideoLevel.init(wire:)) ?? .normal
+ qualityTally.video(asked: asked, sent: sent[id] ?? .normal, seconds: dt, for: id)
+ }
+ }
+
+ /// The asks, from every watch's level and the person's own setting,
+ /// reported when they change (off the main thread, as the lists are).
+ fileprivate func reportVideo() {
+ let levels = adapt.mapValues(\.level).merging(
+ Dictionary(uniqueKeysWithValues: media.sentLevels.keys.map { ($0, VideoLevel.normal) })
+ ) { a, _ in a }
+ let asks = VideoAdapt.asks(levels, setting: videoQuality)
+ if videoAsks != asks { videoAsks = asks }
+ guard asks != reportedVideo, let client = bridge else { return }
+ reportedVideo = asks
+ let body = json(asks) ?? "{}"
+ noSoundQueue.async { try? client.setVideo(body) }
+ }
+
+ /// The sender's half: each connection's senders set to what that peer
+ /// last asked of us, and the notice when someone asks for less.
+ fileprivate func answerVideoAsks(_ state: RoomState) {
+ let me = state.peer
+ let before = media.sentLevels
+ var lowered = false
+ for person in state.peers where person.peer != me {
+ let level = VideoAdapt.asked(person.media, me: me)
+ let was = before[person.peer] ?? .normal
+ guard before[person.peer] != nil, level != was else { continue }
+ CallLog.info("\(person.peer.prefix(6)) asks for \(level.wire) video")
+ if level > was { lowered = true }
+ media.setSentLevel(person.peer, level)
+ }
+ let sent = media.sentLevels
+ let people = state.peers.compactMap { p -> (name: String, level: VideoLevel)? in
+ guard p.peer != me, let level = sent[p.peer], level > .normal else { return nil }
+ return (p.name, level)
+ }
+ let words = VideoAdapt.noticeWords(people)
+ if words.isEmpty {
+ videoNotice = ""
+ } else if lowered, words != videoNotice {
+ videoNotice = words
+ say(words, for: 8)
+ }
+ }
+
+ /// The person's choice taking effect: no camera to anyone at Audio only,
+ /// reported as off; the asks of everyone; and the tiles.
+ fileprivate func applyVideoQuality() {
+ guard bridge != nil else { return }
+ media.ownAudioOnly = videoQuality == .audio
+ reportMedia()
+ reportVideo()
+ }
+}
+
// ---------------------------------------------------------------
// Quality and problem reports (§15.26)
// ---------------------------------------------------------------
diff --git a/native/apple/Sources/CallsKit/DevicePanel.swift b/native/apple/Sources/CallsKit/DevicePanel.swift
index 0d11a2a..99faf96 100644
--- a/native/apple/Sources/CallsKit/DevicePanel.swift
+++ b/native/apple/Sources/CallsKit/DevicePanel.swift
@@ -60,6 +60,8 @@ import SwiftUI
AudioSelfTestButton(call: call).buttonStyle(.bordered)
+ videoQualitySection
+
screenSection
audioFoot
@@ -256,6 +258,24 @@ import SwiftUI
}
}
+ /// Spec §15.30: Auto, Low bandwidth or Audio only, remembered.
+ private var videoQualitySection: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ Picker("Video quality", selection: $call.videoQuality) {
+ ForEach(VideoQualitySetting.allCases) { setting in
+ Text(setting.title).tag(setting)
+ }
+ }
+ .accessibilityIdentifier("videoQuality")
+ #if os(macOS)
+ .pickerStyle(.menu)
+ #endif
+ Text(VideoQualitySetting.explanation)
+ .font(.footnote).foregroundStyle(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
/// "Optimise for", and while this app is sharing, one line saying how
/// the screen is actually leaving — the answer to "it isn't keeping up".
private var screenSection: some View {
diff --git a/native/apple/Sources/CallsKit/InviteLinkCopy.swift b/native/apple/Sources/CallsKit/InviteLinkCopy.swift
index aa6ab1e..c970cdf 100644
--- a/native/apple/Sources/CallsKit/InviteLinkCopy.swift
+++ b/native/apple/Sources/CallsKit/InviteLinkCopy.swift
@@ -64,13 +64,13 @@ extension Call {
}
/// A short message over the call that goes by itself: never a dialog.
- func say(_ text: String) {
+ func say(_ text: String, for seconds: Double = 2.5) {
toastSerial += 1
let serial = toastSerial
toast = text
AccessibilityNotification.Announcement(text).post()
Task { @MainActor [weak self] in
- try? await Task.sleep(for: .seconds(2.5))
+ try? await Task.sleep(for: .seconds(seconds))
guard let self, self.toastSerial == serial else { return }
self.toast = nil
}
diff --git a/native/apple/Sources/CallsKit/MacCallView.swift b/native/apple/Sources/CallsKit/MacCallView.swift
index d20f409..67e26fc 100644
--- a/native/apple/Sources/CallsKit/MacCallView.swift
+++ b/native/apple/Sources/CallsKit/MacCallView.swift
@@ -227,7 +227,9 @@
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,
+ cameraOff: call.isCameraOff(peer), lowBandwidth: call.isLowBandwidth(peer),
+ videoPaused: call.isVideoPaused(peer) ? call.videoPausedWords(peer) : nil,
+ cornerRadius: cornerRadius, compact: compact,
labelLift: labelLift, backdrop: backdrop, audio: call.tileAudio(peer), onStage: onStage,
pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds[peer])
}
diff --git a/native/apple/Sources/CallsKit/MacVideoTile.swift b/native/apple/Sources/CallsKit/MacVideoTile.swift
index 5880f6d..d0e27c4 100644
--- a/native/apple/Sources/CallsKit/MacVideoTile.swift
+++ b/native/apple/Sources/CallsKit/MacVideoTile.swift
@@ -10,6 +10,10 @@
var muted = false
var mirrored = false
var cameraOff = false
+ /// Spec §15.30: this app is asking them for less video ("Low
+ /// bandwidth"), and, at audio only, the words in place of the picture.
+ var lowBandwidth = false
+ var videoPaused: String? = nil
/// A shared screen (§5.4). Shown whole rather than cropped to fill:
/// the edge of a screen is where its menu bar and its scroll bars are,
/// and a face survives losing its margins where a document does not.
@@ -67,7 +71,7 @@
.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 {
+ } else if let track, !cameraOff, placeholder == nil, videoPaused == nil {
// 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
@@ -83,7 +87,7 @@
.scaleEffect(x: mirrored ? -1 : 1, y: 1)
} else {
TilePlaceholder(
- symbol: cameraOff
+ symbol: cameraOff || videoPaused != nil
? "video.slash" : screen ? "rectangle.on.rectangle" : "person.crop.circle",
words: iconOnly ? nil : waiting, iconFont: iconOnly ? .title2 : .largeTitle,
reserve: labelBlock)
@@ -94,6 +98,7 @@
TileAudioNotices(info)
HStack(spacing: 6) {
TileSpeakingName(label: label, muted: muted, compact: compact, glow: audio?.glow)
+ if lowBandwidth { LowBandwidthBadge(compact: compact) }
TileAudioStatus(info)
}
}
@@ -106,9 +111,13 @@
.overlay(alignment: .topLeading) { if muted, !compact { MutedBadge().padding(10) } }
.clipShape(RoundedRectangle(cornerRadius: cornerRadius))
.accessibilityElement(children: .ignore)
- .accessibilityLabel(stageLabel(tileAccessibilityLabel(label, muted: muted, audio: info), onStage: onStage, pinned: pinned))
+ .accessibilityLabel(
+ stageLabel(
+ tileAccessibilityLabel(label, muted: muted, audio: info) + (lowBandwidth ? ", low bandwidth" : ""),
+ onStage: onStage, pinned: pinned))
.accessibilityHint(info?.detail ?? "")
- .accessibilityValue(cameraOff ? "Camera off" : track == nil || placeholder != nil ? waiting : "Video on")
+ .accessibilityValue(
+ cameraOff ? "Camera off" : track == nil || placeholder != nil || videoPaused != nil ? waiting : "Video on")
}
/// The backdrop's fade when a picture turns between filling and
/// fitted; none under Reduce Motion.
@@ -118,7 +127,8 @@
private var waiting: String {
cameraOff
- ? "Camera off" : placeholder ?? (screen ? "Waiting for the screen" : "Waiting for video")
+ ? "Camera off"
+ : videoPaused ?? placeholder ?? (screen ? "Waiting for the screen" : "Waiting for video")
}
}
diff --git a/native/apple/Sources/CallsKit/Media.swift b/native/apple/Sources/CallsKit/Media.swift
index 31a1c74..7526fdf 100644
--- a/native/apple/Sources/CallsKit/Media.swift
+++ b/native/apple/Sources/CallsKit/Media.swift
@@ -24,6 +24,8 @@ import LiveKitWebRTC
didSet { applySendPolicy() }
}
private var screenSize = (width: 0, height: 0)
+ /// The screen's source size, for §15.30's minimal fit.
+ var screenSourceSize: (width: Int, height: Int) { screenSize }
/// The audio device module and processing behind the factory. See CallAudio.
let audio: CallAudio
@@ -240,6 +242,21 @@ import LiveKitWebRTC
func applySendPolicy() {
for peer in peers.values { peer.applySendPolicy() }
}
+
+ /// Spec §15.30: the level one peer asks of us, applied to that one
+ /// connection's senders. Kept on the peer, so a connection that settles
+ /// later is given it too.
+ func setSentLevel(_ peer: String, _ level: VideoLevel) {
+ guard let p = peers[peer], p.sentLevel != level else { return }
+ p.sentLevel = level
+ p.applySendPolicy()
+ }
+ /// What each connection is sending at, as asked.
+ var sentLevels: [String: VideoLevel] { peers.mapValues(\.sentLevel) }
+ /// The person's own Audio only: no camera to anyone.
+ var ownAudioOnly = false {
+ didSet { if ownAudioOnly != oldValue { applySendPolicy() } }
+ }
/// The screen's source size, as its statistics report it.
func screenSource(width: Int, height: Int) {
guard width > 0, height > 0, (width, height) != screenSize else { return }
@@ -580,6 +597,9 @@ struct PeerAudioReading: Equatable, Sendable {
// with it; and the mid, so the statistics can count the two video
// streams apart.
private var clues = ScreenClues()
+ /// Spec §15.30: what this peer asks of us, and so what this connection's
+ /// camera and screen are sent at.
+ var sentLevel = VideoLevel.normal
private var screenReceiver: String?
private var screenMid = ""
// Whether this connection carries a camera of ours: the classifier's
@@ -712,7 +732,11 @@ struct PeerAudioReading: Equatable, Sendable {
let plan = engine.screenPlanFor
let nudge = self.nudge
let cameraTrack = engine.localVideo
- let camera = ScreenSendPolicy.camera(sharing: screenTx != nil)
+ // §15.30: at the level this peer asks of us, and no camera at all while
+ // the person's own Video quality is Audio only.
+ let level = sentLevel
+ let size = engine.screenSourceSize
+ let camera = VideoAdapt.camera(engine.ownAudioOnly ? .audio : level, sharing: screenTx != nil)
AudioWork.post {
if let screen {
// The format this connection negotiated, which may hold the
@@ -720,7 +744,7 @@ struct PeerAudioReading: Equatable, Sendable {
let fmtp = screen.parameters.codecs.first.flatMap { codec -> [String: String]? in
codec.name.uppercased() == "H264" ? codec.parameters as? [String: String] : nil
}
- var screenPlan = plan(fmtp)
+ var screenPlan = VideoAdapt.screen(plan(fmtp), level, width: size.width, height: size.height)
if nudge > 1 { screenPlan.scaleResolutionDownBy = (screenPlan.scaleResolutionDownBy ?? 1) * nudge }
screen.apply(screenPlan)
}
diff --git a/native/apple/Sources/CallsKit/MiniWindow.swift b/native/apple/Sources/CallsKit/MiniWindow.swift
index 92b4921..2ff455c 100644
--- a/native/apple/Sources/CallsKit/MiniWindow.swift
+++ b/native/apple/Sources/CallsKit/MiniWindow.swift
@@ -546,6 +546,8 @@
MacVideoTile(
track: call.remoteTracks[peer], label: call.name(of: peer),
muted: call.isMuted(peer), cameraOff: call.isCameraOff(peer),
+ lowBandwidth: call.isLowBandwidth(peer),
+ videoPaused: call.isVideoPaused(peer) ? call.videoPausedWords(peer) : nil,
audio: call.tileAudio(peer), fixtureVideo: fixtureFeeds[peer])
case nil:
MacVideoTile(
diff --git a/native/apple/Sources/CallsKit/MutedBadge.swift b/native/apple/Sources/CallsKit/MutedBadge.swift
index 47af48a..5cae5ae 100644
--- a/native/apple/Sources/CallsKit/MutedBadge.swift
+++ b/native/apple/Sources/CallsKit/MutedBadge.swift
@@ -16,6 +16,29 @@ public struct MutedBadge: View {
}
}
+/// Spec §15.30: the quiet mark beside a person's name while this app asks
+/// them for less video. A word, never a colour; the tile's own label says
+/// "low bandwidth", so this hides itself from assistive technology.
+public struct LowBandwidthBadge: View {
+ var compact = false
+ public init(compact: Bool = false) { self.compact = compact }
+ public var body: some View {
+ Group {
+ if compact {
+ Image(systemName: "wifi.exclamationmark")
+ } else {
+ Label(VideoAdapt.badgeWord, systemImage: "wifi.exclamationmark")
+ }
+ }
+ .font(.caption.weight(.semibold)).foregroundStyle(.white)
+ .padding(.horizontal, 7).padding(.vertical, 3)
+ .callOverlaySurface(Capsule())
+ .help("Calls is asking for less video while the connection is weak")
+ .accessibilityHidden(true)
+ .accessibilityIdentifier("lowBandwidth")
+ }
+}
+
/// What a tile's accessibility label says: the name, and "muted" when it
/// is. Shared by the Mac and iPhone tiles so VoiceOver hears one phrase.
public func tileAccessibilityLabel(_ label: String, muted: Bool) -> String {
diff --git a/native/apple/Sources/CallsKit/QualityReport.swift b/native/apple/Sources/CallsKit/QualityReport.swift
index 1856d39..0e329c4 100644
--- a/native/apple/Sources/CallsKit/QualityReport.swift
+++ b/native/apple/Sources/CallsKit/QualityReport.swift
@@ -86,6 +86,9 @@ public struct QualityDevices: Encodable, Equatable, Sendable {
public struct QualityCallEvents: Encodable, Equatable, Sendable {
public var reconnecting: Double?
public var reconnectingSeconds: Double?
+ /// §15.30: "low" or "audio", the person's own Video quality; absent for
+ /// Auto.
+ public var videoSetting: String?
}
public struct QualityPeer: Encodable, Equatable, Sendable {
@@ -178,6 +181,11 @@ public struct QualityPeerEvents: Encodable, Equatable, Sendable {
/// §15.28: ICE restarts and rebuilds this app's recovery made.
public var autoRestarts: Double?
public var autoRebuilds: Double?
+ /// §15.30: seconds this app asked them for each level below normal
+ /// (reduced, minimal, audio), and seconds it sent them less because they
+ /// asked; three numbers, or absent.
+ public var askedSeconds: [Double]?
+ public var sentSeconds: [Double]?
}
// MARK: - The snapshot
@@ -270,6 +278,9 @@ struct QualityCounters: Equatable, Sendable {
var width: Double?
var height: Double?
var fps: Double?
+ /// PLIs and FIRs this side sent for it (spec §15.30's watch; not
+ /// reported).
+ var keyframeAsks: Double?
}
var outAudio: Out?
var outVideo: Out?
@@ -340,6 +351,9 @@ struct QualityCounters: Equatable, Sendable {
v.width = stat.numbers["frameWidth"]
v.height = stat.numbers["frameHeight"]
v.fps = stat.numbers["framesPerSecond"]
+ if stat.numbers["pliCount"] != nil || stat.numbers["firCount"] != nil {
+ v.keyframeAsks = (stat.numbers["pliCount"] ?? 0) + (stat.numbers["firCount"] ?? 0)
+ }
// Told apart by mid, as the statistics elsewhere are: a peer
// sharing its screen sends two video streams.
if !sample.screenMid.isEmpty, mid == sample.screenMid {
@@ -417,6 +431,7 @@ struct QualityCounters: Equatable, Sendable {
a.width = most(a.width, b.width)
a.height = most(a.height, b.height)
a.fps = most(a.fps, b.fps)
+ a.keyframeAsks = sum(a.keyframeAsks, b.keyframeAsks)
return a
}
}
@@ -486,6 +501,8 @@ public struct QualityEventTally: Equatable, Sendable {
/// The connection's own recovery (§15.28).
var autoRestarts = 0
var autoRebuilds = 0
+ /// §15.30's seconds at each level, asked and sent.
+ var video = VideoTime()
}
/// The longest a look is taken to cover: the level watch looks five
@@ -499,6 +516,8 @@ public struct QualityEventTally: Equatable, Sendable {
private(set) var callReconnecting = 0
private(set) var callSeconds = 0.0
private(set) var peers: [String: Peer] = [:]
+ /// §15.30: the person's own Video quality, when it is not Auto.
+ var videoSetting: VideoQualitySetting = .auto
public init() {}
@@ -528,6 +547,12 @@ public struct QualityEventTally: Equatable, Sendable {
for id in screenStalled { peers[id, default: Peer()].screenStalled = true }
}
+ /// §15.30: time at the levels asked of and sent to one peer.
+ mutating func video(asked: VideoLevel, sent: VideoLevel, seconds: Double, for peer: String) {
+ guard asked > .normal || sent > .normal, seconds > 0 else { return }
+ peers[peer, default: Peer()].video.add(asked: asked, sent: sent, seconds: seconds)
+ }
+
public mutating func count(_ step: Step, for peer: String) {
switch step {
case .keyframe: peers[peer, default: Peer()].keyframes += 1
@@ -597,10 +622,11 @@ public struct QualityReportBuilder: Equatable, Sendable {
var report = QualityReport(
isFinal: final ? true : nil, seconds: Self.bound(seconds, QualityBounds.seconds) ?? QualityBounds.seconds,
client: client, devices: devices)
- if events.callReconnecting > 0 || events.callSeconds > 0 {
+ if events.callReconnecting > 0 || events.callSeconds > 0 || events.videoSetting != .auto {
report.events = QualityCallEvents(
reconnecting: Self.steps(events.callReconnecting),
- reconnectingSeconds: events.callSeconds > 0 ? Self.bound(events.callSeconds, QualityBounds.seconds) : nil)
+ reconnectingSeconds: events.callSeconds > 0 ? Self.bound(events.callSeconds, QualityBounds.seconds) : nil,
+ videoSetting: events.videoSetting == .auto ? nil : events.videoSetting.rawValue)
}
let ids = Set(samples.keys).union(events.peers.keys).sorted()
var peers: [QualityPeer] = []
@@ -643,6 +669,8 @@ public struct QualityReportBuilder: Equatable, Sendable {
if e.screenStalled { events.screenStalled = true }
events.autoRestarts = steps(e.autoRestarts)
events.autoRebuilds = steps(e.autoRebuilds)
+ events.askedSeconds = VideoTime.seconds(e.video.asked)
+ events.sentSeconds = VideoTime.seconds(e.video.sent)
if events != QualityPeerEvents() { peer.events = events }
// The sharer's recovery steps toward this peer belong with the screen
// going out to them, even in a window where it sent nothing.
diff --git a/native/apple/Sources/CallsKit/ScreenSendPolicy.swift b/native/apple/Sources/CallsKit/ScreenSendPolicy.swift
index 5373be3..4471434 100644
--- a/native/apple/Sources/CallsKit/ScreenSendPolicy.swift
+++ b/native/apple/Sources/CallsKit/ScreenSendPolicy.swift
@@ -55,6 +55,9 @@ struct EncodingPlan: Equatable {
var bitratePriority = 1.0
var highPriority = false
var degradation: Degradation?
+ /// Whether the encoding sends at all (spec §15.30: a receiver that asked
+ /// for audio only gets no camera). True everywhere else.
+ var active = true
}
/// The sender parameters for a screen and for the camera beside it.
@@ -253,6 +256,7 @@ extension RTCRtpSender {
encoding.scaleResolutionDownBy = NSNumber(value: plan.scaleResolutionDownBy ?? 1)
encoding.bitratePriority = plan.bitratePriority
encoding.networkPriority = plan.highPriority ? .high : .low
+ encoding.isActive = plan.active
switch plan.degradation {
case .maintainResolution?:
parameters.degradationPreference = NSNumber(value: RTCDegradationPreference.maintainResolution.rawValue)
@@ -273,7 +277,7 @@ extension RTCRtpSender {
return [
e.maxBitrateBps?.stringValue, e.maxFramerate?.stringValue, e.scaleResolutionDownBy?.stringValue,
String(e.bitratePriority), String(e.networkPriority.rawValue),
- parameters.degradationPreference?.stringValue,
+ parameters.degradationPreference?.stringValue, String(e.isActive),
].map { $0 ?? "-" }.joined(separator: ",")
}
}
diff --git a/native/apple/Sources/CallsKit/VideoAdapt.swift b/native/apple/Sources/CallsKit/VideoAdapt.swift
new file mode 100644
index 0000000..e26c271
--- /dev/null
+++ b/native/apple/Sources/CallsKit/VideoAdapt.swift
@@ -0,0 +1,384 @@
+import Foundation
+
+/// Spec §15.30 (2026-10-28): adaptive video, room.js's `adapt*` twins
+/// number for number (test/browser/room-adapt.test.mjs and VideoAdaptTests
+/// hold both).
+///
+/// Paul, after a Dublin–London call whose guest was on café Wi-Fi, relayed,
+/// at 840–1300 ms round trips and up to seven freezes every thirty seconds:
+/// "Low-bandwidth with auto-switching up and down." It is a mesh, so every
+/// pair has its own sender, and the one who can see the trouble is the
+/// receiver. Each receiver watches what arrives from each sender and asks
+/// that sender, in its own media report, for one of these levels; the
+/// sender sets that one connection's sender parameters. Audio is never
+/// touched; a shared screen keeps its size, loses frame rate first, and is
+/// never paused, and while one is going the camera gives way first.
+public enum VideoLevel: Int, CaseIterable, Comparable, Sendable {
+ case normal, reduced, minimal, audio
+
+ /// The wire's word; normal is never sent (it is the absence of an entry).
+ public var wire: String {
+ switch self {
+ case .normal: return "normal"
+ case .reduced: return "reduced"
+ case .minimal: return "minimal"
+ case .audio: return "audio"
+ }
+ }
+
+ init?(wire: String) {
+ guard let level = Self.allCases.first(where: { $0.wire == wire }), level != .normal else { return nil }
+ self = level
+ }
+
+ public static func < (a: Self, b: Self) -> Bool { a.rawValue < b.rawValue }
+}
+
+/// The person's own "Video quality", in the device panel and remembered:
+/// Auto leaves it to the watch, Low bandwidth asks everyone for minimal,
+/// Audio only asks everyone for no video and sends no camera to anyone.
+public enum VideoQualitySetting: String, CaseIterable, Identifiable, Sendable {
+ case auto, low, audio
+
+ public var id: String { rawValue }
+
+ public var title: String {
+ switch self {
+ case .auto: return "Auto"
+ case .low: return "Low bandwidth"
+ case .audio: return "Audio only"
+ }
+ }
+
+ public static let explanation =
+ "Auto lowers video when a connection is weak and raises it again when it recovers. Low bandwidth asks everyone for small video. Audio only pauses video both ways, to keep sound clear."
+
+ /// The lowest level asked of anyone while this is chosen.
+ var floor: VideoLevel {
+ switch self {
+ case .auto: return .normal
+ case .low: return .minimal
+ case .audio: return .audio
+ }
+ }
+
+ static let key = "videoQuality"
+
+ /// The remembered choice, Auto until someone picks another.
+ public static var remembered: VideoQualitySetting {
+ get { UserDefaults.standard.string(forKey: key).flatMap(Self.init(rawValue:)) ?? .auto }
+ set { UserDefaults.standard.set(newValue.rawValue, forKey: key) }
+ }
+}
+
+/// One sender's watch, on the receiving side: down quickly, up slowly, and
+/// a probe up that fails doubling the wait before the next.
+struct VideoAdapt: Equatable, Sendable {
+ // The thresholds, as room.js has them (ADAPT_*).
+ static let window = 10.0 // s: the trouble window, and the time at a level before a step down
+ static let severeAfter = 5.0 // s: severe trouble steps two levels after this long
+ static let downFreezes = 2.0 // camera freezes in the window
+ static let downFreezeSeconds = 2.0 // seconds frozen in the window
+ static let downKeyframeAsks = 3.0 // PLIs and FIRs this side sent for the camera
+ static let downLoss = 0.05 // of all inbound packets
+ static let downRTT = 600.0 // ms, with at least one freeze
+ static let downJitterBuffer = 500.0 // ms, the audio jitter buffer's mean delay
+ static let downDropped = 0.25 // frames dropped, of decoded and dropped,
+ static let downDroppedMin = 10.0 // at least this many
+ static let severeFreezes = 5.0
+ static let severeFreezeSeconds = 4.0
+ static let severeLoss = 0.15
+ static let cleanLoss = 0.02 // a clean second: no freeze, loss at most this,
+ static let cleanRTT = 400.0 // a round trip under this,
+ static let cleanJitterBuffer = 300.0 // and the jitter buffer under this
+ static let upAfter = 45.0 // s clean at a level, then probe one up
+ static let probeWatch = 20.0 // trouble this soon after a probe steps back
+ static let probeJudge = 5.0 // judged on at least this much of it
+ static let upMax = 300.0 // the probe's wait doubles to at most this
+
+ /// One second of what arrived from the sender.
+ struct Sample: Equatable, Sendable {
+ var freezes = 0.0
+ var freezeSeconds = 0.0
+ var keyframeAsks = 0.0
+ var packets = 0.0
+ var lost = 0.0
+ var rtt: Double?
+ var jitterBufferMs: Double?
+ var decoded = 0.0
+ var dropped = 0.0
+ }
+
+ private(set) var level = VideoLevel.normal
+ private var since: Double?
+ private var samples: [(at: Double, sample: Sample)] = []
+ private var cleanSince: Double?
+ let upBase: Double
+ private(set) var upWait: Double
+ private var probeAt: Double?
+ private var probeFrom = VideoLevel.normal
+ private(set) var downs = 0
+ private(set) var ups = 0
+
+ init(upAfter: Double = Self.upAfter) {
+ upBase = upAfter
+ upWait = upAfter
+ }
+
+ static func == (a: Self, b: Self) -> Bool {
+ a.level == b.level && a.since == b.since && a.upWait == b.upWait && a.downs == b.downs && a.ups == b.ups
+ }
+
+ /// A window's sums: counts added, the round trip as their median (one
+ /// spike is not a slow link), the jitter buffer as their mean.
+ struct Window: Equatable {
+ var freezes = 0.0, freezeSeconds = 0.0, keyframeAsks = 0.0, packets = 0.0, lost = 0.0
+ var decoded = 0.0, dropped = 0.0
+ var rtt: Double?
+ var jitterBuffer: Double?
+ var loss: Double { packets + lost > 0 ? lost / (packets + lost) : 0 }
+ }
+
+ static func window(_ samples: [Sample]) -> Window {
+ var w = Window()
+ var rtts: [Double] = []
+ var jbs: [Double] = []
+ for x in samples {
+ w.freezes += x.freezes
+ w.freezeSeconds += x.freezeSeconds
+ w.keyframeAsks += x.keyframeAsks
+ w.packets += x.packets
+ w.lost += x.lost
+ w.decoded += x.decoded
+ w.dropped += x.dropped
+ if let r = x.rtt { rtts.append(r) }
+ if let j = x.jitterBufferMs { jbs.append(j) }
+ }
+ if !rtts.isEmpty { w.rtt = rtts.sorted()[rtts.count / 2] }
+ if !jbs.isEmpty { w.jitterBuffer = jbs.reduce(0, +) / Double(jbs.count) }
+ return w
+ }
+
+ enum Verdict: Equatable { case none, trouble, severe }
+
+ static func verdict(_ w: Window) -> Verdict {
+ if w.freezes >= severeFreezes || w.freezeSeconds >= severeFreezeSeconds || w.loss > severeLoss {
+ return .severe
+ }
+ if w.freezes >= downFreezes || w.freezeSeconds >= downFreezeSeconds || w.loss > downLoss
+ || w.keyframeAsks >= downKeyframeAsks
+ || (w.rtt.map { $0 >= downRTT } ?? false && w.freezes >= 1)
+ || (w.jitterBuffer.map { $0 >= downJitterBuffer } ?? false)
+ || (w.dropped >= downDroppedMin && w.dropped >= downDropped * (w.decoded + w.dropped))
+ {
+ return .trouble
+ }
+ return .none
+ }
+
+ static func clean(_ x: Sample) -> Bool {
+ let n = x.packets + x.lost
+ return x.freezes == 0 && x.freezeSeconds == 0 && x.keyframeAsks == 0 && (n == 0 || x.lost / n <= cleanLoss)
+ && (x.rtt.map { $0 < cleanRTT } ?? true) && (x.jitterBufferMs.map { $0 < cleanJitterBuffer } ?? true)
+ }
+
+ private mutating func move(to next: VideoLevel, at now: Double, up: Bool) {
+ if up { ups += 1 } else { downs += 1 }
+ level = next
+ since = now
+ samples = []
+ cleanSince = nil
+ if !up { probeAt = nil }
+ }
+
+ /// One look, about once a second (`now` in seconds), with that second's
+ /// sample or nil for none: a connection that is down is §15.28's to
+ /// mend and says nothing about the link. Returns the level.
+ @discardableResult mutating func observe(at now: Double, _ sample: Sample?) -> VideoLevel {
+ if since == nil { since = now }
+ guard let sample else { return level }
+ samples.append((now, sample))
+ samples.removeAll { $0.at <= now - Self.window }
+ let observed = now - (since ?? now)
+ let verdict = Self.verdict(Self.window(samples.map(\.sample)))
+ if Self.clean(sample) {
+ if cleanSince == nil { cleanSince = now }
+ } else {
+ cleanSince = nil
+ }
+ if let probeAt {
+ if now - probeAt < Self.probeWatch {
+ if verdict != .none, observed >= Self.probeJudge {
+ upWait = min(upWait * 2, Self.upMax)
+ move(to: probeFrom, at: now, up: false)
+ return level
+ }
+ } else {
+ self.probeAt = nil
+ upWait = upBase
+ }
+ }
+ if verdict == .severe, observed >= Self.severeAfter, level < .audio {
+ move(to: VideoLevel(rawValue: min(VideoLevel.audio.rawValue, level.rawValue + 2)) ?? .audio, at: now, up: false)
+ return level
+ }
+ if verdict != .none, observed >= Self.window, level < .audio, let next = VideoLevel(rawValue: level.rawValue + 1) {
+ move(to: next, at: now, up: false)
+ return level
+ }
+ if level > .normal, let cleanSince, now - cleanSince >= upWait, let next = VideoLevel(rawValue: level.rawValue - 1) {
+ let from = level
+ move(to: next, at: now, up: true)
+ probeAt = now
+ probeFrom = from
+ }
+ return level
+ }
+
+ // MARK: - What arrives, one second of it
+
+ /// One second from two readings of the quality report's counters: camera
+ /// freezes and keyframe asks only while the camera is watched (on, and
+ /// the app in front — a still screen's gaps and an unseen tile's frames
+ /// are not freezes), packets and loss across audio, camera and screen,
+ /// the round trip, the audio jitter buffer, and frames decoded and
+ /// dropped. Nil when nothing at all arrived and nothing was measured.
+ static func sample(_ now: QualityCounters, _ before: QualityCounters?, cameraWatched: Bool) -> Sample? {
+ func d(_ a: Double?, _ b: Double?) -> Double { QualityReportBuilder.delta(a, b) ?? 0 }
+ var s = Sample()
+ s.packets =
+ d(now.inAudio?.packets, before?.inAudio?.packets) + d(now.inVideo?.packets, before?.inVideo?.packets)
+ + d(now.inScreen?.packets, before?.inScreen?.packets)
+ s.lost =
+ d(now.inAudio?.lost, before?.inAudio?.lost) + d(now.inVideo?.lost, before?.inVideo?.lost)
+ + d(now.inScreen?.lost, before?.inScreen?.lost)
+ s.rtt = now.rtt
+ if s.packets + s.lost == 0, s.rtt == nil { return nil }
+ if cameraWatched {
+ s.freezes = d(now.inVideo?.freezes, before?.inVideo?.freezes)
+ s.freezeSeconds = d(now.inVideo?.freezeSeconds, before?.inVideo?.freezeSeconds)
+ s.keyframeAsks = d(now.inVideo?.keyframeAsks, before?.inVideo?.keyframeAsks)
+ }
+ if let delay = QualityReportBuilder.delta(now.inAudio?.bufferDelay, before?.inAudio?.bufferDelay),
+ let emitted = QualityReportBuilder.delta(now.inAudio?.emitted, before?.inAudio?.emitted), emitted > 0
+ {
+ s.jitterBufferMs = delay / emitted * 1000
+ }
+ s.decoded = d(now.inVideo?.decoded, before?.inVideo?.decoded) + d(now.inScreen?.decoded, before?.inScreen?.decoded)
+ s.dropped = d(now.inVideo?.dropped, before?.inVideo?.dropped) + d(now.inScreen?.dropped, before?.inScreen?.dropped)
+ return s
+ }
+
+ // MARK: - What is asked, and what is sent
+
+ /// The `video` report: every peer whose level — the watch's or the
+ /// setting's, whichever is lower — is below normal, at most fifteen.
+ static func asks(_ levels: [String: VideoLevel], setting: VideoQualitySetting) -> [String: String] {
+ var out: [String: String] = [:]
+ for (id, level) in levels.sorted(by: { $0.key < $1.key }) {
+ let at = max(level, setting.floor)
+ if at > .normal, out.count < 15 { out[id] = at.wire }
+ }
+ return out
+ }
+
+ /// What one peer's report asks of us.
+ static func asked(_ media: PeerMedia?, me: String) -> VideoLevel {
+ guard !me.isEmpty, let word = media?.video?[me] else { return .normal }
+ return VideoLevel(wire: word) ?? .normal
+ }
+
+ // The sender's half, as room.js has it (ADAPT_CAMERA, ADAPT_SCREEN).
+ static let reducedCamera = (bitrate: 350_000, fps: 15, long: 640.0, short: 360.0)
+ static let minimalCamera = (bitrate: 120_000, fps: 8, long: 320.0, short: 180.0)
+ static let reducedScreen = (bitrate: 1_200_000, fps: 10)
+ static let minimalScreen = (bitrate: 500_000, fps: 5, long: 1280.0)
+
+ /// The camera's encoding for one receiver at a level. While a screen
+ /// goes out the camera gives way first: normal is the cap beside the
+ /// screen (ScreenSendPolicy.camera), and every level below is one lower
+ /// for the camera, so a receiver at minimal gets the screen and no
+ /// camera. Fitted by the camera's long and short sides, so a portrait
+ /// camera is boxed the right way round.
+ static func camera(_ level: VideoLevel, sharing: Bool, width: Int = 640, height: Int = 480) -> EncodingPlan {
+ let at = sharing && level > .normal ? VideoLevel(rawValue: min(3, level.rawValue + 1)) ?? .audio : level
+ if at == .normal { return ScreenSendPolicy.camera(sharing: sharing, height: height) }
+ let c = at == .reduced ? reducedCamera : minimalCamera
+ let long = Double(max(width, height))
+ let short = Double(min(width, height))
+ let scale = max(1, long / c.long, short / c.short)
+ var plan = EncodingPlan(maxBitrate: c.bitrate, maxFramerate: c.fps, scaleResolutionDownBy: scale > 1 ? scale : nil)
+ plan.active = at != .audio
+ return plan
+ }
+
+ /// The screen's plan for one receiver at a level: frame rate and bitrate
+ /// lowered, the size kept, and only at minimal and below the long side
+ /// brought to 1280; resolution held under pressure from then on. Never
+ /// paused. The level-fit scale the plan carries (ScreenSendPolicy's H.264
+ /// rules) is kept whenever it is larger.
+ static func screen(_ plan: EncodingPlan, _ level: VideoLevel, width: Int, height: Int) -> EncodingPlan {
+ guard level > .normal else { return plan }
+ var out = plan
+ out.degradation = .maintainResolution
+ out.active = true
+ if level == .reduced {
+ out.maxFramerate = reducedScreen.fps
+ out.maxBitrate = min(plan.maxBitrate ?? reducedScreen.bitrate, reducedScreen.bitrate)
+ } else {
+ out.maxFramerate = minimalScreen.fps
+ out.maxBitrate = min(plan.maxBitrate ?? minimalScreen.bitrate, minimalScreen.bitrate)
+ let longest = Double(max(width, height))
+ let fit = longest > minimalScreen.long ? longest / minimalScreen.long : 1
+ let scale = max(plan.scaleResolutionDownBy ?? 1, fit)
+ out.scaleResolutionDownBy = scale > 1 ? scale : nil
+ }
+ return out
+ }
+
+ /// An app older than this ignores a request: its video can only be hidden
+ /// here, which saves this device's work and not the connection.
+ static let minNativeVersion = "0.4.14"
+
+ /// Whether a peer's client acts on a request: every browser (its page is
+ /// the server's own), and an app from `minNativeVersion` on.
+ static func honours(client: String?) -> Bool {
+ guard let client, !client.isEmpty else { return true }
+ let parts = client.split(separator: " ")
+ guard parts.count == 2, ["mac", "iphone", "ipad"].contains(String(parts[0])) else { return false }
+ return ClientVersion.compare(String(parts[1]), minNativeVersion) >= 0
+ }
+
+ /// The sender's quiet notice, for the people it is sending less to.
+ static func noticeWords(_ people: [(name: String, level: VideoLevel)]) -> String {
+ guard !people.isEmpty else { return "" }
+ let names = people.map(\.name)
+ let list = names.count == 1 ? names[0] : names.dropLast().joined(separator: ", ") + " and " + names[names.count - 1]
+ let weak = names.count == 1 ? "(their connection is weak)" : "(their connections are weak)"
+ if people.allSatisfy({ $0.level >= .audio }) { return "Sending only audio to \(list) \(weak)" }
+ return "Sending reduced video to \(list) \(weak)"
+ }
+
+ /// The tile's words at audio only.
+ static let pausedWords = "Video paused to keep audio clear"
+ static let oldAppWords = "Their app can’t send less video, so it’s only hidden here"
+ static let badgeWord = "Low bandwidth"
+}
+
+/// §15.30's seconds at each level below normal, asked of and sent to each
+/// peer, for the quality report.
+struct VideoTime: Equatable, Sendable {
+ var asked: [Double] = [0, 0, 0]
+ var sent: [Double] = [0, 0, 0]
+
+ mutating func add(asked a: VideoLevel, sent s: VideoLevel, seconds: Double) {
+ if a > .normal { asked[a.rawValue - 1] += seconds }
+ if s > .normal { sent[s.rawValue - 1] += seconds }
+ }
+
+ /// The report's arrays: three numbers, or nil when all are zero.
+ static func seconds(_ v: [Double]) -> [Double]? {
+ guard v.contains(where: { $0 > 0 }) else { return nil }
+ return v.map { QualityReportBuilder.bound($0, QualityBounds.seconds) ?? 0 }
+ }
+}
diff --git a/native/apple/Sources/CallsKit/Wire.swift b/native/apple/Sources/CallsKit/Wire.swift
index 7f4157a..6703aef 100644
--- a/native/apple/Sources/CallsKit/Wire.swift
+++ b/native/apple/Sources/CallsKit/Wire.swift
@@ -32,10 +32,16 @@ public struct PeerMedia: Decodable, Equatable, Sendable {
/// Nil (absent) is a client that does not say; empty is one that hears
/// nobody yet.
public let hearing: [String]?
+ /// What it asks each sender for (spec §15.30): peer id to "reduced",
+ /// "minimal" or "audio", only those below normal. Nil (absent) is normal
+ /// from everyone, which is also what a client from before it means. Read
+ /// leniently: a value of any other shape is taken as absent rather than
+ /// costing the roster its decode.
+ public let video: [String: String]?
public init(
muted: Bool, cameraOff: Bool, audioBlocked: Bool? = nil, noSoundFrom: [String]? = nil,
- screenStalled: [String]? = nil, hearing: [String]? = nil
+ screenStalled: [String]? = nil, hearing: [String]? = nil, video: [String: String]? = nil
) {
self.muted = muted
self.cameraOff = cameraOff
@@ -43,6 +49,22 @@ public struct PeerMedia: Decodable, Equatable, Sendable {
self.noSoundFrom = noSoundFrom
self.screenStalled = screenStalled
self.hearing = hearing
+ self.video = video
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case muted, cameraOff, audioBlocked, noSoundFrom, screenStalled, hearing, video
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ muted = try c.decode(Bool.self, forKey: .muted)
+ cameraOff = try c.decode(Bool.self, forKey: .cameraOff)
+ audioBlocked = try c.decodeIfPresent(Bool.self, forKey: .audioBlocked)
+ noSoundFrom = try c.decodeIfPresent([String].self, forKey: .noSoundFrom)
+ screenStalled = try c.decodeIfPresent([String].self, forKey: .screenStalled)
+ hearing = try c.decodeIfPresent([String].self, forKey: .hearing)
+ video = (try? c.decodeIfPresent([String: String].self, forKey: .video)) ?? nil
}
}
public struct RoomState: Decodable {
diff --git a/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift b/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift
new file mode 100644
index 0000000..189a71c
--- /dev/null
+++ b/native/apple/Tests/CallsKitTests/VideoAdaptTests.swift
@@ -0,0 +1,284 @@
+import Foundation
+import XCTest
+
+@testable import CallsKit
+
+/// Spec §15.30: the receiver's watch (down fast, up slow, a failed probe
+/// doubling the wait), what a sender sends at each level (the camera giving
+/// way before a shared screen, a screen never paused), the media report's
+/// `video`, and the quality report's seconds — on a fake clock. The twin of
+/// test/browser/room-adapt.test.mjs, number for number.
+final class VideoAdaptTests: XCTestCase {
+ typealias Sample = VideoAdapt.Sample
+
+ private func clean(
+ freezes: Double = 0, freezeSeconds: Double = 0, keyframeAsks: Double = 0, packets: Double = 100,
+ lost: Double = 0, rtt: Double? = 80, jitterBufferMs: Double? = 60, decoded: Double = 30, dropped: Double = 0
+ ) -> Sample {
+ Sample(
+ freezes: freezes, freezeSeconds: freezeSeconds, keyframeAsks: keyframeAsks, packets: packets, lost: lost,
+ rtt: rtt, jitterBufferMs: jitterBufferMs, decoded: decoded, dropped: dropped)
+ }
+
+ /// Trouble that is not severe: a freeze every four seconds.
+ private func freezing(_ t: Int) -> Sample { clean(freezes: t % 4 == 0 ? 1 : 0) }
+
+ /// Once a second from `from` to `to`; the seconds the level changed at.
+ @discardableResult
+ private func run(_ watch: inout VideoAdapt, _ from: Int, _ to: Int, _ at: (Int) -> Sample?) -> [[Int]] {
+ var changes: [[Int]] = []
+ for t in from...to {
+ let before = watch.level
+ watch.observe(at: Double(t), at(t))
+ if watch.level != before { changes.append([t, watch.level.rawValue]) }
+ }
+ return changes
+ }
+
+ func testTheNumbersAreTheApprovedOnes() {
+ XCTAssertEqual(VideoAdapt.upAfter, 45)
+ XCTAssertEqual(VideoAdapt.upMax, 300)
+ XCTAssertEqual(VideoAdapt.window, 10)
+ XCTAssertEqual(VideoAdapt.probeWatch, 20)
+ }
+
+ func testTroubleThatLastsStepsDownEveryTenSecondsToAudioOnly() {
+ var w = VideoAdapt()
+ XCTAssertEqual(run(&w, 0, 60, freezing), [[10, 1], [20, 2], [30, 3]])
+ XCTAssertEqual(w.level, .audio)
+ XCTAssertEqual(w.downs, 3)
+ }
+
+ func testSevereTroubleStepsTwoLevelsFiveSecondsIn() {
+ var w = VideoAdapt()
+ XCTAssertEqual(run(&w, 0, 12) { _ in self.clean(freezes: 2) }, [[5, 2], [10, 3]])
+ var lossy = VideoAdapt()
+ XCTAssertEqual(run(&lossy, 0, 6) { _ in self.clean(packets: 80, lost: 20) }, [[5, 2]])
+ }
+
+ func testOccasionalTroubleIsNotTrouble() {
+ var rare = VideoAdapt()
+ XCTAssertEqual(run(&rare, 0, 60) { t in self.clean(freezes: t % 11 == 0 ? 1 : 0) }, [])
+ var lossy = VideoAdapt()
+ XCTAssertEqual(run(&lossy, 0, 60) { _ in self.clean(packets: 97, lost: 3) }, [])
+ var slow = VideoAdapt()
+ XCTAssertEqual(run(&slow, 0, 60) { _ in self.clean(rtt: 900) }, [])
+ }
+
+ func testEachKindOfTroubleStepsDown() {
+ let kinds: [(String, (Int) -> Sample)] = [
+ ("loss", { _ in self.clean(packets: 94, lost: 6) }),
+ ("one freeze on a 700 ms round trip", { t in self.clean(freezes: t == 5 ? 1 : 0, rtt: 700) }),
+ ("the jitter buffer", { _ in self.clean(jitterBufferMs: 650) }),
+ ("frames dropped", { _ in self.clean(decoded: 20, dropped: 10) }),
+ ("one long freeze", { t in self.clean(freezes: t == 5 ? 1 : 0, freezeSeconds: t == 5 ? 2.5 : 0) }),
+ ("a keyframe asked for every three seconds", { t in self.clean(keyframeAsks: t % 3 == 0 ? 1 : 0) }),
+ ]
+ for (what, sample) in kinds {
+ var w = VideoAdapt()
+ XCTAssertEqual(run(&w, 0, 10, sample), [[10, 1]], what)
+ }
+ }
+
+ func testTheRoundTripIsTheMedian() {
+ var w = VideoAdapt()
+ XCTAssertEqual(
+ run(&w, 0, 30) { t in self.clean(freezes: t % 10 == 3 ? 1 : 0, rtt: t % 10 == 3 ? 2000 : 100) }, [])
+ }
+
+ func testNothingMeasuredIsNoNews() {
+ var w = VideoAdapt()
+ run(&w, 0, 9, freezing)
+ XCTAssertEqual(run(&w, 10, 40) { _ in nil }, [])
+ XCTAssertEqual(w.level, .normal)
+ XCTAssertNil(VideoAdapt.sample(QualityCounters(), QualityCounters(), cameraWatched: true))
+ }
+
+ func testFreezesCountOnlyWhileTheCameraIsWatched() {
+ var before = QualityCounters()
+ before.inAudio = .init(packets: 100, lost: 1, bufferDelay: 3000, emitted: 48000)
+ before.inVideo = .init(packets: 200, freezes: 1, freezeSeconds: 0.5, decoded: 100, dropped: 0, keyframeAsks: 1)
+ before.inScreen = .init(packets: 50, lost: 0, decoded: 10)
+ var now = before
+ now.inAudio = .init(packets: 150, lost: 2, bufferDelay: 6360, emitted: 96000)
+ now.inVideo = .init(packets: 290, freezes: 3, freezeSeconds: 2, decoded: 130, dropped: 1, keyframeAsks: 3)
+ now.inScreen = .init(packets: 60, lost: 1, decoded: 11)
+ now.rtt = 50
+ let s = VideoAdapt.sample(now, before, cameraWatched: true)
+ XCTAssertEqual(s?.freezes, 2)
+ XCTAssertEqual(s?.freezeSeconds, 1.5)
+ XCTAssertEqual(s?.keyframeAsks, 2)
+ XCTAssertEqual(s?.packets, 150)
+ XCTAssertEqual(s?.lost, 2)
+ XCTAssertEqual(s?.rtt, 50)
+ XCTAssertEqual(s?.jitterBufferMs ?? 0, 70, accuracy: 0.01)
+ XCTAssertEqual(s?.decoded, 31)
+ XCTAssertEqual(s?.dropped, 1)
+ let off = VideoAdapt.sample(now, before, cameraWatched: false)
+ XCTAssertEqual(off?.freezes, 0)
+ XCTAssertEqual(off?.keyframeAsks, 0)
+ XCTAssertEqual(off?.packets, 150)
+ }
+
+ func testCleanSecondsStepUpAfterFortyFiveAndAgain() {
+ var w = VideoAdapt()
+ run(&w, 0, 20, freezing)
+ XCTAssertEqual(w.level, .minimal)
+ XCTAssertEqual(run(&w, 21, 200) { _ in self.clean() }, [[66, 1], [112, 0]])
+ XCTAssertEqual(w.upWait, VideoAdapt.upAfter)
+ }
+
+ func testAKeyframeAskedForIsNotACleanSecond() {
+ var w = VideoAdapt()
+ run(&w, 0, 10, freezing)
+ XCTAssertEqual(run(&w, 11, 120) { t in self.clean(keyframeAsks: t == 30 ? 1 : 0) }, [[76, 0]])
+ }
+
+ func testOneBadSecondResetsTheCleanRun() {
+ var w = VideoAdapt()
+ run(&w, 0, 10, freezing)
+ XCTAssertEqual(run(&w, 11, 120) { t in self.clean(lost: t == 40 ? 10 : 0) }, [[86, 0]])
+ }
+
+ func testAFailedProbeStepsBackAndDoublesTheWaitToFiveMinutes() {
+ var w = VideoAdapt()
+ run(&w, 0, 10, freezing)
+ XCTAssertEqual(w.level, .reduced)
+ var changes: [[Int]] = []
+ for t in 11...1200 {
+ let before = w.level
+ w.observe(at: Double(t), w.level == .normal ? clean(freezes: 1) : clean())
+ if w.level != before { changes.append([t, w.level.rawValue]) }
+ }
+ XCTAssertEqual(changes.filter { $0[1] == 0 }.map { $0[0] }, [56, 152, 338, 644, 950])
+ XCTAssertEqual(changes.filter { $0[1] == 1 }.map { $0[0] }, [61, 157, 343, 649, 955])
+ XCTAssertEqual(w.upWait, VideoAdapt.upMax)
+ }
+
+ func testTroubleAfterTheProbeWatchIsAnOrdinaryStepDown() {
+ var w = VideoAdapt()
+ run(&w, 0, 10, freezing)
+ run(&w, 11, 56) { _ in self.clean() }
+ XCTAssertEqual(w.level, .normal)
+ XCTAssertEqual(run(&w, 57, 100) { t in t >= 80 ? self.freezing(t) : self.clean() }, [[84, 1], [94, 2]])
+ XCTAssertEqual(w.upWait, VideoAdapt.upAfter)
+ }
+
+ func testTheSettingIsAFloorAndOnlyLevelsBelowNormalAreAsked() {
+ let a = String(repeating: "a", count: 32)
+ let b = String(repeating: "b", count: 32)
+ XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .auto), [b: "reduced"])
+ XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .low), [a: "minimal", b: "minimal"])
+ XCTAssertEqual(VideoAdapt.asks([a: .audio], setting: .low), [a: "audio"])
+ XCTAssertEqual(VideoAdapt.asks([a: .normal, b: .reduced], setting: .audio), [a: "audio", b: "audio"])
+ XCTAssertEqual(VideoAdapt.asks([a: .normal], setting: .auto), [:])
+ var many: [String: VideoLevel] = [:]
+ for i in 0..<20 { many[String(format: "%032x", i)] = .minimal }
+ XCTAssertEqual(VideoAdapt.asks(many, setting: .auto).count, 15)
+ }
+
+ func testASenderReadsOnlyItsOwnIdAndTheWiresLevels() {
+ let me = String(repeating: "a", count: 32)
+ XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "minimal"]), me: me), .minimal)
+ XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "minimal"]), me: "b"), .normal)
+ XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false, video: [me: "tiny"]), me: me), .normal)
+ XCTAssertEqual(VideoAdapt.asked(PeerMedia(muted: false, cameraOff: false), me: me), .normal)
+ XCTAssertEqual(VideoAdapt.asked(nil, me: me), .normal)
+ }
+
+ func testTheCameraAtEachLevel() {
+ XCTAssertEqual(VideoAdapt.camera(.normal, sharing: false), EncodingPlan())
+ let reduced = VideoAdapt.camera(.reduced, sharing: false, width: 640, height: 480)
+ XCTAssertEqual(reduced.maxBitrate, 350_000)
+ XCTAssertEqual(reduced.maxFramerate, 15)
+ XCTAssertEqual(reduced.scaleResolutionDownBy ?? 0, 480.0 / 360, accuracy: 1e-9)
+ XCTAssertTrue(reduced.active)
+ XCTAssertEqual(VideoAdapt.camera(.reduced, sharing: false, width: 720, height: 1280).scaleResolutionDownBy, 2)
+ let minimal = VideoAdapt.camera(.minimal, sharing: false, width: 640, height: 480)
+ XCTAssertEqual(minimal.maxBitrate, 120_000)
+ XCTAssertEqual(minimal.maxFramerate, 8)
+ XCTAssertEqual(minimal.scaleResolutionDownBy ?? 0, 480.0 / 180, accuracy: 1e-9)
+ XCTAssertFalse(VideoAdapt.camera(.audio, sharing: false).active)
+ }
+
+ func testWhileSharingTheCameraGivesWayFirst() {
+ XCTAssertEqual(VideoAdapt.camera(.normal, sharing: true), ScreenSendPolicy.camera(sharing: true))
+ let reduced = VideoAdapt.camera(.reduced, sharing: true)
+ XCTAssertEqual(reduced.maxBitrate, 120_000)
+ XCTAssertTrue(reduced.active)
+ XCTAssertFalse(VideoAdapt.camera(.minimal, sharing: true).active)
+ XCTAssertFalse(VideoAdapt.camera(.audio, sharing: true).active)
+ }
+
+ func testAScreenKeepsItsSizeLosesFrameRateFirstAndIsNeverPaused() {
+ let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1080)
+ XCTAssertEqual(VideoAdapt.screen(plan, .normal, width: 1920, height: 1080), plan)
+ let reduced = VideoAdapt.screen(plan, .reduced, width: 1920, height: 1080)
+ XCTAssertEqual(reduced.maxFramerate, 10)
+ XCTAssertEqual(reduced.maxBitrate, 1_200_000)
+ XCTAssertEqual(reduced.scaleResolutionDownBy, plan.scaleResolutionDownBy, "the size is kept")
+ XCTAssertEqual(reduced.degradation, .maintainResolution)
+ let minimal = VideoAdapt.screen(plan, .minimal, width: 1920, height: 1080)
+ XCTAssertEqual(minimal.maxFramerate, 5)
+ XCTAssertEqual(minimal.maxBitrate, 500_000)
+ XCTAssertEqual(minimal.scaleResolutionDownBy, 1.5)
+ let audio = VideoAdapt.screen(plan, .audio, width: 1920, height: 1080)
+ XCTAssertEqual(audio, minimal)
+ XCTAssertTrue(audio.active)
+ // A level-fit scale larger than minimal's is kept (the H.264 rules).
+ let capped = ScreenSendPolicy.screen(.motion, width: 3840, height: 2160, screencast: false)
+ XCTAssertGreaterThanOrEqual(
+ VideoAdapt.screen(capped, .minimal, width: 3840, height: 2160).scaleResolutionDownBy ?? 0,
+ capped.scaleResolutionDownBy ?? 0)
+ }
+
+ func testBrowsersAndNewAppsHonourAnAsk() {
+ XCTAssertTrue(VideoAdapt.honours(client: nil))
+ XCTAssertTrue(VideoAdapt.honours(client: ""))
+ XCTAssertTrue(VideoAdapt.honours(client: "mac 0.4.14"))
+ XCTAssertTrue(VideoAdapt.honours(client: "iphone 0.5"))
+ XCTAssertFalse(VideoAdapt.honours(client: "mac 0.4.13"))
+ XCTAssertFalse(VideoAdapt.honours(client: "native"))
+ XCTAssertFalse(VideoAdapt.honours(client: "something else"))
+ }
+
+ func testTheSendersNotice() {
+ XCTAssertEqual(VideoAdapt.noticeWords([]), "")
+ XCTAssertEqual(
+ VideoAdapt.noticeWords([("David", .minimal)]), "Sending reduced video to David (their connection is weak)")
+ XCTAssertEqual(VideoAdapt.noticeWords([("David", .audio)]), "Sending only audio to David (their connection is weak)")
+ XCTAssertEqual(
+ VideoAdapt.noticeWords([("David", .reduced), ("Ana", .audio), ("Cy", .minimal)]),
+ "Sending reduced video to David, Ana and Cy (their connections are weak)")
+ }
+
+ func testTheMediaReportReadsTheAsksLeniently() throws {
+ let me = String(repeating: "a", count: 32)
+ let ok = try JSONDecoder().decode(
+ PeerMedia.self, from: Data(#"{"muted":false,"cameraOff":false,"video":{"\#(me)":"audio"}}"#.utf8))
+ XCTAssertEqual(ok.video, [me: "audio"])
+ let odd = try JSONDecoder().decode(
+ PeerMedia.self, from: Data(#"{"muted":true,"cameraOff":false,"video":["\#(me)"],"hearing":[]}"#.utf8))
+ XCTAssertNil(odd.video, "a video member of another shape is taken as absent")
+ XCTAssertEqual(odd.muted, true)
+ XCTAssertEqual(odd.hearing, [])
+ }
+
+ func testTheQualityReportCarriesTheSecondsAtEachLevel() throws {
+ var tally = QualityEventTally()
+ tally.videoSetting = .low
+ tally.video(asked: .minimal, sent: .normal, seconds: 1, for: "p")
+ tally.video(asked: .minimal, sent: .reduced, seconds: 1.04, for: "p")
+ tally.video(asked: .normal, sent: .normal, seconds: 1, for: "q")
+ var builder = QualityReportBuilder()
+ builder.start(at: 0)
+ let report = builder.build(
+ at: 30, samples: [:], events: &tally, client: QualityClient(app: "mac", version: "0.4.14"), devices: nil,
+ final: false)
+ let body = try XCTUnwrap(report.encoded())
+ XCTAssertTrue(body.contains(#""askedSeconds":[0,2,0]"#), body)
+ XCTAssertTrue(body.contains(#""sentSeconds":[1,0,0]"#), body)
+ XCTAssertTrue(body.contains(#""videoSetting":"low""#), body)
+ XCTAssertFalse(body.contains(#""peer":"q""#), "a peer at normal both ways says nothing")
+ }
+}
diff --git a/native/ios/Sources/CallsPhone.swift b/native/ios/Sources/CallsPhone.swift
index 8765504..258786a 100644
--- a/native/ios/Sources/CallsPhone.swift
+++ b/native/ios/Sources/CallsPhone.swift
@@ -190,7 +190,9 @@ struct PhoneCall: View {
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,
+ cameraOff: call.isCameraOff(peer), lowBandwidth: call.isLowBandwidth(peer),
+ videoPaused: call.isVideoPaused(peer) ? call.videoPausedWords(peer) : nil,
+ cornerRadius: cornerRadius, compact: compact,
labelInsets: labelInsets, backdrop: backdrop, audio: call.tileAudio(peer),
onStage: onStage, pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds[peer])
}
@@ -400,6 +402,10 @@ struct PhoneVideoTile: View {
var muted = false
var mirrored = false
var cameraOff = false
+ /// Spec §15.30: this app is asking them for less video ("Low
+ /// bandwidth"), and, at audio only, the words in place of the picture.
+ var lowBandwidth = false
+ var videoPaused: String? = nil
/// A shared screen (§5.4), shown whole rather than cropped: on a phone
/// more than anywhere, cropping a laptop's screen to a portrait tile
/// would leave the middle third of it.
@@ -451,7 +457,7 @@ struct PhoneVideoTile: View {
.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 {
+ } else if let track, !cameraOff, placeholder == nil, videoPaused == nil {
// 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
@@ -467,9 +473,9 @@ struct PhoneVideoTile: View {
.scaleEffect(x: mirrored ? -1 : 1, y: 1)
} else {
TilePlaceholder(
- symbol: cameraOff
+ symbol: cameraOff || videoPaused != nil
? "video.slash" : screen ? "rectangle.on.rectangle" : "person.crop.circle",
- words: cameraOff || iconOnly ? nil : placeholder, wordsFont: .caption, spacing: 6,
+ words: cameraOff || iconOnly ? nil : videoPaused ?? placeholder, wordsFont: .caption, spacing: 6,
reserve: labelBlock)
}
}
@@ -478,6 +484,7 @@ struct PhoneVideoTile: View {
TileAudioNotices(info)
HStack(spacing: 5) {
TileSpeakingName(label: label, muted: muted, compact: compact, glow: audio?.glow)
+ if lowBandwidth { LowBandwidthBadge(compact: compact) }
TileAudioStatus(info)
}
}
@@ -490,12 +497,16 @@ struct PhoneVideoTile: View {
.overlay(alignment: .topLeading) { if muted, !compact { MutedBadge().padding(8) } }
.clipShape(RoundedRectangle(cornerRadius: cornerRadius))
.accessibilityElement(children: .ignore)
- .accessibilityLabel(stageLabel(tileAccessibilityLabel(label, muted: muted, audio: info), onStage: onStage, pinned: pinned))
+ .accessibilityLabel(
+ stageLabel(
+ tileAccessibilityLabel(label, muted: muted, audio: info) + (lowBandwidth ? ", low bandwidth" : ""),
+ onStage: onStage, pinned: pinned))
.accessibilityHint(info?.detail ?? "")
.accessibilityValue(
cameraOff
? "Camera off"
- : placeholder ?? (track == nil ? (screen ? "Waiting for the screen" : "Waiting for video") : "Video on"))
+ : videoPaused ?? placeholder
+ ?? (track == nil ? (screen ? "Waiting for the screen" : "Waiting for video") : "Video on"))
}
}
extension PhoneVideoTile {