oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import LiveKitWebRTC
3
4/// What a shared screen is for, which decides what WebRTC gives up first
5/// when the uplink or the encoder cannot carry everything.
6///
7/// A screencast source on its own keeps every pixel and drops frames, which
8/// is right for a document and exactly wrong for someone scrolling,
9/// dragging or playing video: the far side sees a slideshow of a screen
10/// that is moving ("the screenshare isn't keeping up", 2026-09-24).
11public enum ScreenShareMode: String, CaseIterable, Identifiable, Sendable {
12 /// Keeps it reasonably sharp while tracking motion. The default.
13 case balanced
14 /// Keeps full resolution and lets the frame rate fall: slides, code, text.
15 case detail
16 /// Keeps the frame rate and lets resolution fall, to 1280 at most.
17 case motion
18
19 public var id: String { rawValue }
20
21 public var title: String {
22 switch self {
23 case .balanced: return "Balanced"
24 case .detail: return "Text and detail"
25 case .motion: return "Motion and video"
26 }
27 }
28
29 public var explanation: String {
30 switch self {
31 case .balanced: return "Keeps up with scrolling and moving windows, at full sharpness when the connection allows."
32 case .detail: return "Keeps small text sharp. Movement may look jerky."
33 case .motion: return "Keeps movement smooth. Text may look softer."
34 }
35 }
36
37 static let key = "screenShareMode"
38
39 /// The remembered choice, balanced until someone picks another.
40 public static var remembered: ScreenShareMode {
41 get { UserDefaults.standard.string(forKey: key).flatMap(Self.init(rawValue:)) ?? .balanced }
42 set { UserDefaults.standard.set(newValue.rawValue, forKey: key) }
43 }
44}
45
46/// One sender's encoding, as the policy wants it. Nil means the encoder's
47/// own default, and applying nil puts that default back.
48struct EncodingPlan: Equatable {
49 enum Degradation: Equatable { case maintainResolution, maintainFramerate, balanced }
50
51 var maxBitrate: Int?
52 var maxFramerate: Int?
53 var scaleResolutionDownBy: Double?
54 /// WebRTC's bitrate priority: 1 is everyone's default, 4 is "high".
55 var bitratePriority = 1.0
56 var highPriority = false
57 var degradation: Degradation?
58 /// Whether the encoding sends at all (spec §15.30: a receiver that asked
59 /// for audio only gets no camera). True everywhere else.
60 var active = true
61}
62
63/// The sender parameters for a screen and for the camera beside it.
64///
65/// Measured on 2026-09-24 with the native/browser motion gate (a 1080p
66/// page scrolling at 30 fps with a window dragged across it, H.264 on the
67/// Mac's hardware encoder, received in Chromium), frames a second arriving
68/// with the uplink open / capped at 2.5 / 1.5 / 1.0 Mbit/s:
69///
70/// before (screencast, no parameters) 26 / 22 / 2 / 1 at 1920×1080
71/// detail (maintain resolution, 1920) 27 / 21 / 13 / 2 at 1920×1080
72/// balanced (maintain frame rate, 1920) 30 / 30 / 19 / 25 at 960–320 wide
73/// motion (not screencast, 1280) 30 / 30 / 30 / 23 at 640–320 wide
74///
75/// WebRTC's own "balanced" degradation gave 7 / 2 / 2 / 1.5 on the same
76/// source, which is why the balanced mode does not use it. The same page
77/// on software VP8 managed 2 fps even on the open link (80 ms a frame to
78/// encode), which is why the screen asks for H.264 first.
79///
80/// Sender parameters and nothing else, so none of it touches SDP: a mode
81/// changed mid-share, the camera capped and restored, all without a
82/// renegotiation for perfect negotiation to wobble over (see room.js's
83/// tuneAudioSender for the same reasoning on the browser side).
84public enum ScreenSendPolicy {
85 /// A screen longer than this on its long side is scaled down to it in
86 /// motion mode: 720p's worth of pixels is what 30 fps fits in.
87 static let motionLongestSide = 1280.0
88 /// And never sent larger than this in any mode (the Mac's capture is
89 /// already fitted to it; this holds for anything else that shares).
90 static let longestSide = 1920.0
91
92 /// The camera's ceiling while a screen is going out: the screen is what
93 /// everyone is looking at, and the camera is a thumbnail beside it.
94 static let sharingCameraBitrate = 500_000
95 static let sharingCameraHeight = 360.0
96
97 /// Whether the source is marked as a screencast. Motion is not: a
98 /// screencast is encoded as screen content, which is tuned for
99 /// sharpness, and in the measurement above the plain source held 30 fps
100 /// on a thinner link than the screencast did.
101 static func screencast(_ mode: ScreenShareMode) -> Bool { mode != .motion }
102
103 /// The most 16×16 blocks a frame from a source that is *not* marked as
104 /// a screencast may have: H.264 level 3.1's 3,600, which is 1280×720.
105 ///
106 /// Chromium answers every H.264 offer at level 3.1, and the Mac's
107 /// hardware encoder, as this build of WebRTC sets it up, holds a camera-
108 /// like stream to the level it negotiated: a larger frame is refused by
109 /// VideoToolbox (kVTParameterErr, -12902) and nothing is encoded at all.
110 /// A screencast source is set up another way and is not held to it —
111 /// measured 2026-09-28 at 1920×1246, steady. So this is the motion
112 /// mode's cap, and the cap for any mode on a share that *started* in
113 /// motion mode (its source cannot become a screencast later).
114 ///
115 /// It is Paul's freeze of 2026-09-28 ("after a while, my screen froze on
116 /// her end"): a 16:10 display in motion mode is 1280×830 at its 1280 cap,
117 /// 4,160 blocks. It went out at 960×620 while the link was still
118 /// ramping, and the moment WebRTC let it up to full size, the encoder
119 /// stopped — for eight or nine seconds at a time, until WebRTC's quality
120 /// scaler stepped it down again, over and over; and for good if the mode
121 /// was then switched to Text and detail, which does not let the size
122 /// fall. A 16:9 page at 1280×720 is exactly 3,600, which is why the
123 /// motion gate's synthetic 1080p page never met it.
124 static let realtimeMacroblocks = 3600
125 /// Off only for the gate, which measures 0.4.1's sizing against it.
126 @_spi(Fixtures) public static var levelCapped = true
127
128 /// The screen's encoding, for a source of the given size (zero while
129 /// it is not known yet, which leaves the scale alone). `screencast` is
130 /// whether the source was made as one (see `realtimeMacroblocks`).
131 ///
132 /// `negotiated` is the H.264 format the connection settled on, where
133 /// known (its fmtp parameters): a screencast sent in a High-family
134 /// profile is held to that level too (see `levelMacroblocks`).
135 static func screen(
136 _ mode: ScreenShareMode, width: Int = 0, height: Int = 0, screencast: Bool? = nil,
137 negotiated: [String: String]? = nil
138 ) -> EncodingPlan {
139 let longest = Double(max(width, height))
140 let limit: Int? = {
141 guard levelCapped, width > 0, height > 0 else { return nil }
142 if !(screencast ?? Self.screencast(mode)) { return Self.realtimeMacroblocks }
143 return negotiated.flatMap(levelMacroblocks)
144 }()
145 let capped = limit != nil
146 let blockLimit = limit ?? Self.realtimeMacroblocks
147 func fit(_ side: Double) -> Double? {
148 var scale = longest > side ? longest / side : 1
149 if capped {
150 // Down until the frame's blocks fit the level, as WebRTC will
151 // size it: each side divided by the scale, rounded down.
152 func blocks(_ s: Double) -> Int {
153 ((Int(Double(width) / s) + 15) / 16) * ((Int(Double(height) / s) + 15) / 16)
154 }
155 while blocks(scale) > blockLimit { scale *= 1.01 }
156 }
157 return scale > 1 ? scale : nil
158 }
159 switch mode {
160 case .detail:
161 return EncodingPlan(
162 maxBitrate: 3_500_000, maxFramerate: 30, scaleResolutionDownBy: fit(longestSide),
163 bitratePriority: 4, highPriority: true, degradation: .maintainResolution)
164 case .balanced:
165 // Full size while the link and the encoder can carry it, and a
166 // smaller picture rather than a slideshow when they cannot.
167 return EncodingPlan(
168 maxBitrate: 3_000_000, maxFramerate: 30, scaleResolutionDownBy: fit(longestSide),
169 bitratePriority: 4, highPriority: true, degradation: .maintainFramerate)
170 case .motion:
171 return EncodingPlan(
172 maxBitrate: 2_500_000, maxFramerate: 30, scaleResolutionDownBy: fit(motionLongestSide),
173 bitratePriority: 4, highPriority: true, degradation: .maintainFramerate)
174 }
175 }
176
177 /// The most 16×16 blocks a screencast may have in the H.264 format a
178 /// connection negotiated, or nil when it is not held to one.
179 ///
180 /// 2026-10-21, Paul sharing from the Mac app (0.4.10) to Farshad in
181 /// Safari: "screen sharing keeps getting interrupted". Safari answers the
182 /// screen in Constrained High at level 3.1 (640c1f) where Chromium answers
183 /// Constrained Baseline (42e01f), and this build of WebRTC sets a High
184 /// stream up on a VideoToolbox session that holds it to the level, as it
185 /// holds a source that is not a screencast: once the quality scaler let a
186 /// Balanced share up to 1440×930 (5,220 blocks), every frame was refused
187 /// (-12902, then -12911) and nothing at all was sent, until a rebuild
188 /// started a new encoder small — and twenty seconds later the scaler let
189 /// it up again (native-screen-receivers.mjs, `webkit` / `motion`).
190 /// Baseline at the same level was measured carrying 1920×1246 (§15.22),
191 /// so only the High family is held, at its level's MaxFS (H.264 Table
192 /// A-1).
193 static func levelMacroblocks(_ fmtp: [String: String]) -> Int? {
194 guard let id = fmtp["profile-level-id"]?.lowercased(), id.count == 6,
195 let profile = UInt8(id.prefix(2), radix: 16), let level = UInt8(id.suffix(2), radix: 16)
196 else { return nil }
197 // 0x42 Baseline (constrained or not) and 0x4d Main: not held.
198 guard profile != 0x42, profile != 0x4d else { return nil }
199 let maxFS: [UInt8: Int] = [
200 10: 99, 11: 396, 12: 396, 13: 396, 20: 396, 21: 792, 22: 1620, 30: 1620, 31: 3600, 32: 5120,
201 40: 8192, 41: 8192, 42: 8704, 50: 22080, 51: 36864, 52: 36864,
202 ]
203 return maxFS[level]
204 }
205
206 /// The sender's codecs with H.264 first, the rest after it in their own
207 /// order: Apple's hardware encoder where the far side can take H.264,
208 /// and everything else still on offer where it cannot, so a browser
209 /// without H.264 negotiates what it always did. Held on the screen's
210 /// transceiver so a renegotiation the far side offers keeps it.
211 ///
212 /// Among the H.264 formats, Constrained Baseline first, then the other
213 /// Baselines, then the rest, each in packetization mode 1 before 0
214 /// (2026-10-21): what Chromium settles on, and the one that carries a
215 /// full-size screencast. Safari, offered High first, took it and the
216 /// level that comes with it (see `levelMacroblocks`).
217 static func preferringH264(_ codecs: [RTCRtpCodecCapability]) -> [RTCRtpCodecCapability] {
218 let h264 = codecs.enumerated().filter { $0.element.name.uppercased() == "H264" }
219 .sorted { a, b in
220 let ra = h264Rank(a.element.parameters), rb = h264Rank(b.element.parameters)
221 return ra != rb ? ra < rb : a.offset < b.offset
222 }
223 .map(\.element)
224 return h264 + codecs.filter { $0.name.uppercased() != "H264" }
225 }
226
227 /// An H.264 format's place in the screen's preference, lowest first.
228 static func h264Rank(_ fmtp: [String: String]) -> Int {
229 let id = (fmtp["profile-level-id"] ?? "").lowercased()
230 let profile: Int
231 if id.hasPrefix("42e0") { profile = 0 } else if id.hasPrefix("42") { profile = 1 } else { profile = 2 }
232 return profile * 2 + (fmtp["packetization-mode"] == "1" ? 0 : 1)
233 }
234
235 /// The camera's encoding: capped while this app shares a screen, and
236 /// the encoder's own defaults again once it stops. `height` is the
237 /// camera's own frame height where known; the native camera is
238 /// captured nearest 640 wide, so 480 lines.
239 static func camera(sharing: Bool, height: Int = 480) -> EncodingPlan {
240 guard sharing else { return EncodingPlan() }
241 let scale = Double(height) > sharingCameraHeight ? Double(height) / sharingCameraHeight : nil
242 return EncodingPlan(maxBitrate: sharingCameraBitrate, scaleResolutionDownBy: scale)
243 }
244}
245
246extension RTCRtpSender {
247 /// Applies a plan to this sender's first encoding, and reports whether
248 /// anything changed. Reads the parameters fresh each time: WebRTC
249 /// refuses a set that did not come from the latest get.
250 @discardableResult func apply(_ plan: EncodingPlan) -> Bool {
251 let parameters = self.parameters
252 guard let encoding = parameters.encodings.first else { return false }
253 let before = describe(parameters)
254 encoding.maxBitrateBps = plan.maxBitrate.map { NSNumber(value: $0) }
255 encoding.maxFramerate = plan.maxFramerate.map { NSNumber(value: $0) }
256 encoding.scaleResolutionDownBy = NSNumber(value: plan.scaleResolutionDownBy ?? 1)
257 encoding.bitratePriority = plan.bitratePriority
258 encoding.networkPriority = plan.highPriority ? .high : .low
259 encoding.isActive = plan.active
260 switch plan.degradation {
261 case .maintainResolution?:
262 parameters.degradationPreference = NSNumber(value: RTCDegradationPreference.maintainResolution.rawValue)
263 case .maintainFramerate?:
264 parameters.degradationPreference = NSNumber(value: RTCDegradationPreference.maintainFramerate.rawValue)
265 case .balanced?:
266 parameters.degradationPreference = NSNumber(value: RTCDegradationPreference.balanced.rawValue)
267 case nil:
268 parameters.degradationPreference = nil
269 }
270 guard describe(parameters) != before else { return false }
271 self.parameters = parameters
272 return true
273 }
274
275 private func describe(_ parameters: RTCRtpParameters) -> String {
276 guard let e = parameters.encodings.first else { return "" }
277 return [
278 e.maxBitrateBps?.stringValue, e.maxFramerate?.stringValue, e.scaleResolutionDownBy?.stringValue,
279 String(e.bitratePriority), String(e.networkPriority.rawValue),
280 parameters.degradationPreference?.stringValue, String(e.isActive),
281 ].map { $0 ?? "-" }.joined(separator: ",")
282 }
283}
284