oficina / meet Public

Clone
git clone https://amadan.net/oficina/meet

Plain git — no account needed to clone.

Download

Download this file

1import LiveKitWebRTC
2import XCTest
3
4@testable import CallsKit
5
6/// The screen's sending half: what each "Optimise for" mode asks of the
7/// sender, the camera capped beside a share and given back after it, and
8/// the statistics line that says how the screen is actually leaving.
9/// room-share.test.mjs holds the browser's sharePlan and cameraCap to the
10/// same numbers; a change here belongs there too.
11final class ScreenSendTests: XCTestCase {
12 // MARK: - Policy
13
14 func testDetailKeepsResolutionAtTheHighestCeiling() {
15 let plan = ScreenSendPolicy.screen(.detail, width: 1920, height: 1080)
16 XCTAssertEqual(plan.degradation, .maintainResolution)
17 XCTAssertEqual(plan.maxBitrate, 3_500_000)
18 XCTAssertEqual(plan.maxFramerate, 30)
19 XCTAssertNil(plan.scaleResolutionDownBy, "a 1080p screen is sent whole")
20 XCTAssertTrue(plan.highPriority)
21 XCTAssertEqual(plan.bitratePriority, 4)
22 }
23
24 func testMotionKeepsTheFrameRateAt1280() {
25 let plan = ScreenSendPolicy.screen(.motion, width: 1920, height: 1080)
26 XCTAssertEqual(plan.degradation, .maintainFramerate)
27 XCTAssertEqual(plan.maxFramerate, 30)
28 XCTAssertEqual(plan.scaleResolutionDownBy ?? 0, 1.5, accuracy: 0.0001, "1920 down to 1280")
29 XCTAssertTrue(plan.highPriority)
30 // A portrait window is scaled by its long side, too — and then a
31 // little further, to H.264 level 3.1's 3,600 blocks (see
32 // realtimeMacroblocks): 800×1280 would be 4,000.
33 let portrait = ScreenSendPolicy.screen(.motion, width: 1000, height: 1600).scaleResolutionDownBy ?? 0
34 XCTAssertGreaterThan(portrait, 1.25)
35 XCTAssertLessThanOrEqual(blocks(1000, 1600, portrait), 3600)
36 // Something already small enough is left alone.
37 XCTAssertNil(ScreenSendPolicy.screen(.motion, width: 1280, height: 720).scaleResolutionDownBy)
38 }
39
40 /// Paul's freeze of 2026-09-28: a 16:10 MacBook display in motion mode
41 /// was 1280×830 at its cap, over level 3.1's 3,600 blocks, and the Mac's
42 /// encoder refused every frame at that size. Motion now fits the level;
43 /// a screencast source (every other mode) is not held to it.
44 func testMotionFitsH264Level31() {
45 for (w, h) in [(3024, 1964), (1920, 1246), (2560, 1600), (1920, 1200), (1470, 956), (1920, 1080)] {
46 let scale = ScreenSendPolicy.screen(.motion, width: w, height: h).scaleResolutionDownBy ?? 1
47 XCTAssertLessThanOrEqual(blocks(w, h, scale), 3600, "\(w)×\(h) at 1/\(scale)")
48 XCTAssertGreaterThan(blocks(w, h, scale), 3200, "\(w)×\(h) is not shrunk further than it has to be")
49 }
50 // 1080p at 1280×720 is exactly the level, and unchanged.
51 XCTAssertEqual(ScreenSendPolicy.screen(.motion, width: 1920, height: 1080).scaleResolutionDownBy ?? 0, 1.5, accuracy: 0.0001)
52 // Balanced and detail are screencasts and keep their full size.
53 XCTAssertNil(ScreenSendPolicy.screen(.balanced, width: 1920, height: 1246).scaleResolutionDownBy)
54 XCTAssertNil(ScreenSendPolicy.screen(.detail, width: 1920, height: 1200).scaleResolutionDownBy)
55 // A share that started in motion keeps a camera-like source whatever
56 // the mode becomes, and stays within the level.
57 let switched = ScreenSendPolicy.screen(.detail, width: 1920, height: 1246, screencast: false)
58 XCTAssertLessThanOrEqual(blocks(1920, 1246, switched.scaleResolutionDownBy ?? 1), 3600)
59 }
60
61 private func blocks(_ w: Int, _ h: Int, _ scale: Double) -> Int {
62 ((Int(Double(w) / scale) + 15) / 16) * ((Int(Double(h) / scale) + 15) / 16)
63 }
64
65 func testBalancedIsTheDefaultAndKeepsTheFrameRateAtFullSize() {
66 XCTAssertEqual(ScreenShareMode.allCases.first, .balanced)
67 let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1080)
68 // Frames are held; resolution gives way only when it must, from full
69 // size rather than motion's 1280.
70 XCTAssertEqual(plan.degradation, .maintainFramerate)
71 XCTAssertNil(plan.scaleResolutionDownBy)
72 XCTAssertEqual(plan.maxBitrate, 3_000_000)
73 XCTAssertEqual(plan.maxFramerate, 30)
74 XCTAssertTrue(plan.highPriority)
75 XCTAssertTrue(ScreenSendPolicy.screencast(.balanced))
76 XCTAssertTrue(ScreenSendPolicy.screencast(.detail))
77 XCTAssertFalse(ScreenSendPolicy.screencast(.motion))
78 }
79
80 func testH264IsPreferredAndNothingIsDropped() {
81 let factory = RTCPeerConnectionFactory(
82 encoderFactory: RTCDefaultVideoEncoderFactory(), decoderFactory: RTCDefaultVideoDecoderFactory())
83 let codecs = factory.rtpSenderCapabilities(forKind: "video").codecs
84 let preferred = ScreenSendPolicy.preferringH264(codecs)
85 XCTAssertEqual(preferred.count, codecs.count, "every codec stays on offer")
86 XCTAssertEqual(preferred.first?.name, "H264")
87 XCTAssertTrue(preferred.contains { $0.name == "VP8" }, "a browser without H.264 still has VP8")
88 }
89
90 func testConstrainedBaselineIsOfferedFirstForTheScreen() {
91 // 2026-10-21: Safari, offered High first, answered Constrained High
92 // 3.1, and VideoToolbox refused a Balanced share there once it grew.
93 let factory = RTCPeerConnectionFactory(
94 encoderFactory: RTCDefaultVideoEncoderFactory(), decoderFactory: RTCDefaultVideoDecoderFactory())
95 let preferred = ScreenSendPolicy.preferringH264(factory.rtpSenderCapabilities(forKind: "video").codecs)
96 let first = preferred.first?.parameters ?? [:]
97 XCTAssertEqual(first["profile-level-id"]?.lowercased().prefix(4), "42e0")
98 XCTAssertEqual(first["packetization-mode"], "1")
99 XCTAssertLessThan(ScreenSendPolicy.h264Rank(["profile-level-id": "42e01f", "packetization-mode": "1"]),
100 ScreenSendPolicy.h264Rank(["profile-level-id": "640c1f", "packetization-mode": "1"]))
101 }
102
103 func testAHighProfileScreencastIsHeldToItsLevel() {
104 // Constrained High 3.1, as Safari answers it: 3,600 blocks at most.
105 let high = ["profile-level-id": "640c1f", "packetization-mode": "1"]
106 XCTAssertEqual(ScreenSendPolicy.levelMacroblocks(high), 3600)
107 let plan = ScreenSendPolicy.screen(.balanced, width: 1920, height: 1246, screencast: true, negotiated: high)
108 let scale = plan.scaleResolutionDownBy ?? 1
109 let blocks = ((Int(1920 / scale) + 15) / 16) * ((Int(1246 / scale) + 15) / 16)
110 XCTAssertLessThanOrEqual(blocks, 3600)
111 XCTAssertGreaterThan(blocks, 3400, "and no smaller than it needs to be")
112 // Baseline at the same level carries the full size (§15.22), and so
113 // does a level that holds it.
114 XCTAssertNil(ScreenSendPolicy.levelMacroblocks(["profile-level-id": "42e01f"]))
115 XCTAssertNil(ScreenSendPolicy.screen(.balanced, width: 1920, height: 1246, screencast: true,
116 negotiated: ["profile-level-id": "42e01f"]).scaleResolutionDownBy)
117 XCTAssertNil(ScreenSendPolicy.screen(.balanced, width: 1920, height: 1246, screencast: true,
118 negotiated: ["profile-level-id": "640c34"]).scaleResolutionDownBy)
119 }
120
121 func testAScreenLargerThan1920IsNeverSentLarger() {
122 for mode in ScreenShareMode.allCases {
123 let plan = ScreenSendPolicy.screen(mode, width: 3840, height: 2160)
124 XCTAssertGreaterThanOrEqual(plan.scaleResolutionDownBy ?? 1, 2, "\(mode)")
125 }
126 }
127
128 func testAnUnknownSizeLeavesTheScaleAlone() {
129 for mode in ScreenShareMode.allCases {
130 XCTAssertNil(ScreenSendPolicy.screen(mode).scaleResolutionDownBy, "\(mode)")
131 }
132 }
133
134 func testTheCameraIsCappedWhileSharingAndGivenBackAfter() {
135 let capped = ScreenSendPolicy.camera(sharing: true, height: 480)
136 XCTAssertEqual(capped.maxBitrate, 500_000)
137 XCTAssertEqual(capped.scaleResolutionDownBy ?? 0, 480.0 / 360.0, accuracy: 0.0001)
138 XCTAssertFalse(capped.highPriority)
139 XCTAssertNil(ScreenSendPolicy.camera(sharing: true, height: 360).scaleResolutionDownBy)
140 XCTAssertEqual(ScreenSendPolicy.camera(sharing: false), EncodingPlan(), "the encoder's own defaults")
141 }
142
143 func testTheModeIsRemembered() {
144 let defaults = UserDefaults.standard
145 let saved = defaults.object(forKey: ScreenShareMode.key)
146 defer { defaults.set(saved, forKey: ScreenShareMode.key) }
147 defaults.removeObject(forKey: ScreenShareMode.key)
148 XCTAssertEqual(ScreenShareMode.remembered, .balanced)
149 ScreenShareMode.remembered = .motion
150 XCTAssertEqual(ScreenShareMode.remembered, .motion)
151 defaults.set("nonsense", forKey: ScreenShareMode.key)
152 XCTAssertEqual(ScreenShareMode.remembered, .balanced)
153 }
154
155 // MARK: - Applying it to a real sender
156
157 /// The plan reaches a real WebRTC sender, and the camera's defaults
158 /// really come back: set, read back, restored. No call is placed.
159 func testAPlanIsAppliedToASenderAndRestored() throws {
160 let factory = RTCPeerConnectionFactory()
161 let configuration = RTCConfiguration()
162 configuration.sdpSemantics = .unifiedPlan
163 let pc = try XCTUnwrap(
164 factory.peerConnection(
165 with: configuration,
166 constraints: RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil),
167 delegate: nil))
168 defer { pc.close() }
169 let track = factory.videoTrack(with: factory.videoSource(), trackId: "camera")
170 let sender = try XCTUnwrap(pc.add(track, streamIds: ["calls"]))
171
172 XCTAssertTrue(sender.apply(ScreenSendPolicy.camera(sharing: true, height: 480)))
173 var encoding = try XCTUnwrap(sender.parameters.encodings.first)
174 XCTAssertEqual(encoding.maxBitrateBps?.intValue, 500_000)
175 XCTAssertEqual(encoding.scaleResolutionDownBy?.doubleValue ?? 0, 480.0 / 360.0, accuracy: 0.001)
176 XCTAssertFalse(
177 sender.apply(ScreenSendPolicy.camera(sharing: true, height: 480)), "the same plan twice is a no-op")
178
179 XCTAssertTrue(sender.apply(ScreenSendPolicy.camera(sharing: false)))
180 encoding = try XCTUnwrap(sender.parameters.encodings.first)
181 XCTAssertNil(encoding.maxBitrateBps)
182 XCTAssertEqual(encoding.scaleResolutionDownBy?.doubleValue ?? 1, 1, accuracy: 0.001)
183
184 XCTAssertTrue(sender.apply(ScreenSendPolicy.screen(.motion, width: 1920, height: 1080)))
185 let parameters = sender.parameters
186 encoding = try XCTUnwrap(parameters.encodings.first)
187 XCTAssertEqual(encoding.maxBitrateBps?.intValue, 2_500_000)
188 XCTAssertEqual(encoding.maxFramerate?.intValue, 30)
189 XCTAssertEqual(encoding.networkPriority, .high)
190 XCTAssertEqual(encoding.bitratePriority, 4)
191 XCTAssertEqual(
192 parameters.degradationPreference?.intValue, RTCDegradationPreference.maintainFramerate.rawValue)
193 }
194
195 // MARK: - The readout
196
197 private typealias Stats = [String: (type: String, values: [String: Any])]
198
199 private func stats(mid: String = "2", local: String = "host", remote: String = "host") -> Stats {
200 [
201 "OT1": (
202 "outbound-rtp",
203 [
204 "mid": mid, "frameWidth": 1920, "frameHeight": 1080, "framesPerSecond": 8.0,
205 "framesSent": 400, "framesEncoded": 400, "qualityLimitationReason": "bandwidth",
206 "qualityLimitationDurations": ["none": 2.0, "bandwidth": 30.0, "cpu": 0.0, "other": 0.0],
207 "targetBitrate": 1_200_000, "bytesSent": 5_000_000,
208 "encoderImplementation": "VideoToolbox", "totalEncodeTime": 8.0,
209 "mediaSourceId": "SV1", "codecId": "C1",
210 ]
211 ),
212 "OT0": ("outbound-rtp", ["mid": "1", "frameWidth": 640, "framesPerSecond": 30.0]),
213 "SV1": ("media-source", ["frames": 900, "framesPerSecond": 30.0, "width": 1920, "height": 1080]),
214 "C1": ("codec", ["mimeType": "video/H264"]),
215 "RI1": ("remote-inbound-rtp", ["localId": "OT1", "packetsLost": 12, "roundTripTime": 0.085]),
216 "T1": ("transport", ["selectedCandidatePairId": "P1"]),
217 "P1": ("candidate-pair", ["localCandidateId": "L1", "remoteCandidateId": "R1"]),
218 "L1": ("local-candidate", ["candidateType": local]),
219 "R1": ("remote-candidate", ["candidateType": remote]),
220 ]
221 }
222
223 func testTheScreensOwnStreamIsReadByMid() throws {
224 let r = try XCTUnwrap(ScreenSendReport.read(stats(), mid: "2"))
225 XCTAssertEqual(r.width, 1920)
226 XCTAssertEqual(r.height, 1080)
227 XCTAssertEqual(r.framesPerSecond, 8)
228 XCTAssertEqual(r.capturedPerSecond, 30, "the capture is fine; the sender is not keeping up")
229 XCTAssertEqual(r.framesCaptured, 900)
230 XCTAssertEqual(r.sourceWidth, 1920)
231 XCTAssertEqual(r.limitation, "bandwidth")
232 XCTAssertEqual(r.limitationSeconds["bandwidth"], 30)
233 XCTAssertEqual(r.targetBitrate, 1_200_000)
234 XCTAssertEqual(r.codec, "video/H264")
235 XCTAssertTrue(r.hardwareEncoder)
236 XCTAssertEqual(r.encodeMsPerFrame, 20, accuracy: 0.001)
237 XCTAssertEqual(r.packetsLost, 12)
238 XCTAssertEqual(r.roundTripTime, 0.085)
239 XCTAssertEqual(r.path, "host")
240 XCTAssertNil(ScreenSendReport.read(stats(), mid: "9"), "a stream not negotiated yet")
241 XCTAssertNil(ScreenSendReport.read(stats(), mid: ""))
242 }
243
244 func testARelayAtEitherEndIsTheRelay() {
245 XCTAssertEqual(ScreenSendReport.path(stats(local: "relay")), "relay")
246 XCTAssertEqual(ScreenSendReport.path(stats(remote: "relay")), "relay")
247 XCTAssertEqual(ScreenSendReport.path(stats(local: "srflx", remote: "host")), "srflx")
248 }
249
250 func testTheSummaryIsOneLine() throws {
251 var r = try XCTUnwrap(ScreenSendReport.read(stats(local: "relay"), mid: "2"))
252 XCTAssertEqual(
253 r.summary, "Screen: 1920×1080 at 8 fps, limited by bandwidth, 1.2 Mbit/s, relay (H264 hardware)")
254 var previous = r
255 previous.bytesSent = 4_900_000
256 previous.timestamp = 9
257 r.timestamp = 10
258 r = r.measured(since: previous)
259 XCTAssertEqual(r.sentBitrate, 800_000, "the rate actually sent wins over the target")
260 XCTAssertTrue(r.summary.contains("800 kbit/s"))
261 XCTAssertEqual(ScreenSendReport().summary, "Screen: starting…")
262 }
263
264 func testTheSlowestConnectionIsTheOneShown() {
265 var fast = ScreenSendReport()
266 fast.framesPerSecond = 29
267 var slow = ScreenSendReport()
268 slow.framesPerSecond = 4
269 XCTAssertEqual(ScreenSendReport.worst([fast, slow])?.framesPerSecond, 4)
270 XCTAssertNil(ScreenSendReport.worst([]))
271 }
272}
273