oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Accelerate
2import CoreGraphics
3import Foundation
4import LiveKitWebRTC
5import SwiftUI
6
7/// What surrounds a shared screen on the stage (2026-10-05, Paul: "Should
8/// the video view stay fullscreen even here?"). A screen is fitted whole,
9/// never cropped, so a window of another shape leaves bars beside or
10/// above it. Rather than black, they show the same picture enlarged, soft
11/// and dimmed, as FaceTime does.
12///
13/// Cheap by construction: twice a second, WebRTC scales one frame down to
14/// `width` × `height` (libyuv, from whatever buffer the decoder gave), it
15/// is converted and blurred at that size, and the picture is drawn
16/// enlarged, its smooth upscaling doing the rest of the blur. Nothing runs
17/// at the frame rate and nothing is blurred at the window's size.
18public struct ScreenBackdrop: View {
19 let track: RTCVideoTrack
20 /// A tile among others (the grid, the filmstrip): it takes one of
21 /// `BackdropBudget.limit` places, and with none left shows the dark
22 /// surface alone. The stage's backdrop always samples.
23 var budgeted = false
24 @StateObject private var sampler = BackdropSampler()
25 @ObservedObject private var budget = BackdropBudget.shared
26 @State private var place = UUID()
27
28 public init(track: RTCVideoTrack, budgeted: Bool = false) {
29 self.track = track
30 self.budgeted = budgeted
31 }
32
33 private var sampling: Bool { !budgeted || budget.granted(place) }
34
35 public var body: some View {
36 // The picture is an overlay of the surface, so it takes the place's
37 // size and never sets it: filling, an upright picture is far taller
38 // than a landscape place, and as the ZStack's own child it grew the
39 // tile with it (2026-10-21).
40 CallsAppearance.stageSurface
41 .overlay {
42 if let image = sampler.image {
43 Image(decorative: image, scale: 1)
44 .resizable()
45 .interpolation(.high)
46 .aspectRatio(contentMode: .fill)
47 // Past the edges a little: the blur's own edge is darker.
48 .scaleEffect(1.15)
49 .opacity(BackdropSampler.dimmed)
50 .transition(.opacity)
51 }
52 }
53 .clipped()
54 .animation(.easeInOut(duration: 0.4), value: sampler.image != nil)
55 .onAppear {
56 if budgeted { budget.claim(place) }
57 follow()
58 }
59 .onChange(of: ObjectIdentifier(track)) { follow() }
60 .onChange(of: sampling) { follow() }
61 .onDisappear {
62 sampler.detach()
63 if budgeted { budget.release(place) }
64 }
65 .accessibilityHidden(true)
66 }
67
68 private func follow() {
69 if sampling { sampler.attach(track) } else { sampler.detach() }
70 }
71}
72
73/// How many tiles' backdrops sample their pictures at once (2026-10-21):
74/// past `limit`, a fitted tile in the grid or the filmstrip has the dark
75/// stage surface behind it instead. Each sample is a 64 × 36 picture
76/// twice a second (see BackdropSampler), so the limit is about drawing
77/// many soft enlarged pictures at once more than about the sampling.
78@MainActor final class BackdropBudget: ObservableObject {
79 static let shared = BackdropBudget()
80 nonisolated static let limit = 8
81 /// Who asked, in order: the first `limit` sample.
82 @Published private(set) var holders: [UUID] = []
83
84 func claim(_ id: UUID) { if !holders.contains(id) { holders.append(id) } }
85 func release(_ id: UUID) { holders.removeAll { $0 == id } }
86 func granted(_ id: UUID) -> Bool {
87 guard let at = holders.firstIndex(of: id) else { return false }
88 return at < Self.limit
89 }
90}
91
92/// Takes frames from a track at `interval` and keeps the latest as a small
93/// blurred picture.
94@MainActor final class BackdropSampler: ObservableObject {
95 /// The picture's size, landscape: 16:9, enough for the colours and
96 /// their places. Upright pictures are sampled 36 × 64 (`size(for:)`).
97 nonisolated static let width = 64
98 nonisolated static let height = 36
99 /// How often a frame is taken.
100 nonisolated static let interval: TimeInterval = 0.5
101 /// How much of the picture shows over the dark surface behind it.
102 nonisolated static let dimmed: Double = 0.45
103
104 @Published private(set) var image: CGImage?
105 private var track: RTCVideoTrack?
106 private var renderer: Renderer?
107
108 /// Every sampler, for the gate's count of backdrops showing a picture.
109 static let live = NSHashTable<BackdropSampler>.weakObjects()
110 /// How many backdrops are sampling and have a picture to show.
111 static var showing: Int { live.allObjects.filter { $0.track != nil && $0.image != nil }.count }
112
113 init() { Self.live.add(self) }
114
115 func attach(_ next: RTCVideoTrack) {
116 guard track !== next else { return }
117 detach()
118 let renderer = Renderer { [weak self] image in
119 Task { @MainActor in self?.image = image }
120 }
121 next.add(renderer)
122 track = next
123 self.renderer = renderer
124 }
125
126 func detach() {
127 if let renderer { track?.remove(renderer) }
128 track = nil
129 renderer = nil
130 image = nil
131 }
132
133 /// WebRTC's side: called on its decoding thread for every frame, it
134 /// keeps one in `interval` and lets the rest go at once.
135 final class Renderer: NSObject, RTCVideoRenderer, @unchecked Sendable {
136 private let lock = NSLock()
137 private var last: TimeInterval = 0
138 private let deliver: (CGImage) -> Void
139 init(deliver: @escaping (CGImage) -> Void) { self.deliver = deliver }
140
141 func setSize(_ size: CGSize) {}
142
143 func renderFrame(_ frame: RTCVideoFrame?) {
144 guard let frame else { return }
145 let now = ProcessInfo.processInfo.systemUptime
146 lock.lock()
147 let due = now - last >= BackdropSampler.interval
148 if due { last = now }
149 lock.unlock()
150 guard due, let image = BackdropSampler.picture(of: frame) else { return }
151 deliver(image)
152 }
153 }
154
155 /// The backdrop picture's size for a picture of `displayed` size: 64 ×
156 /// 36 for a landscape one, 36 × 64 upright, 48 × 48 near square, so
157 /// the picture is not stretched before it is enlarged.
158 nonisolated static func size(for displayed: CGSize) -> (width: Int, height: Int) {
159 switch VideoShape.of(displayed) {
160 case .landscape: (width, height)
161 case .portrait: (height, width)
162 case .square: (48, 48)
163 }
164 }
165
166 /// One frame as the backdrop's picture: scaled down by WebRTC, then
167 /// converted, turned upright (a phone's camera arrives sideways, with a
168 /// rotation to apply) and blurred here.
169 nonisolated static func picture(of frame: RTCVideoFrame) -> CGImage? {
170 let source = frame.buffer
171 guard source.width > 0, source.height > 0 else { return nil }
172 let rotation = Int(frame.rotation.rawValue)
173 let shown = size(
174 for: VideoShape.displayed(
175 width: CGFloat(source.width), height: CGFloat(source.height), rotation: rotation))
176 // Sampled at the buffer's own orientation, then turned.
177 let quarter = rotation % 180 == 90
178 let (w, h) = quarter ? (shown.height, shown.width) : (shown.width, shown.height)
179 let small =
180 source.cropAndScale?(
181 with: 0, offsetY: 0, cropWidth: source.width, cropHeight: source.height,
182 scaleWidth: Int32(w), scaleHeight: Int32(h)) ?? source
183 let planes = small.toI420()
184 var rgba = rgbaFromI420(
185 width: Int(planes.width), height: Int(planes.height),
186 y: planes.dataY, strideY: Int(planes.strideY),
187 u: planes.dataU, strideU: Int(planes.strideU),
188 v: planes.dataV, strideV: Int(planes.strideV),
189 outWidth: w, outHeight: h)
190 let upright = rotate(rgba, width: w, height: h, rotation: rotation)
191 rgba = upright.pixels
192 boxBlur(&rgba, width: upright.width, height: upright.height, radius: 3, passes: 2)
193 return image(rgba, width: upright.width, height: upright.height)
194 }
195
196 /// RGBA turned clockwise by `rotation` (0, 90, 180 or 270), as WebRTC's
197 /// rotation says a frame is to be shown.
198 nonisolated static func rotate(_ rgba: [UInt8], width: Int, height: Int, rotation: Int)
199 -> (pixels: [UInt8], width: Int, height: Int)
200 {
201 let turn = ((rotation % 360) + 360) % 360
202 guard turn != 0, rgba.count == width * height * 4 else { return (rgba, width, height) }
203 let (ow, oh) = turn == 180 ? (width, height) : (height, width)
204 var out = [UInt8](repeating: 255, count: rgba.count)
205 for y in 0..<height {
206 for x in 0..<width {
207 let (nx, ny): (Int, Int)
208 switch turn {
209 case 90: (nx, ny) = (height - 1 - y, x)
210 case 180: (nx, ny) = (width - 1 - x, height - 1 - y)
211 default: (nx, ny) = (y, width - 1 - x) // 270
212 }
213 let from = (y * width + x) * 4
214 let to = (ny * ow + nx) * 4
215 out[to] = rgba[from]
216 out[to + 1] = rgba[from + 1]
217 out[to + 2] = rgba[from + 2]
218 }
219 }
220 return (out, ow, oh)
221 }
222
223 /// I420 to RGBA (BT.601, video range) at `outWidth` × `outHeight`,
224 /// sampling the nearest source pixel when the sizes differ. Integer
225 /// arithmetic (coefficients × 256) over raw buffers.
226 nonisolated static func rgbaFromI420(
227 width: Int, height: Int, y: UnsafePointer<UInt8>, strideY: Int,
228 u: UnsafePointer<UInt8>, strideU: Int, v: UnsafePointer<UInt8>, strideV: Int,
229 outWidth: Int, outHeight: Int
230 ) -> [UInt8] {
231 var out = [UInt8](repeating: 255, count: outWidth * outHeight * 4)
232 guard width > 0, height > 0 else { return out }
233 out.withUnsafeMutableBufferPointer { buffer in
234 let o = buffer.baseAddress!
235 var i = 0
236 for row in 0..<outHeight {
237 let sy = min(height - 1, row * height / outHeight)
238 let yRow = y + sy * strideY
239 let uRow = u + (sy >> 1) * strideU
240 let vRow = v + (sy >> 1) * strideV
241 for col in 0..<outWidth {
242 let sx = min(width - 1, col * width / outWidth)
243 let c = 298 * (Int(yRow[sx]) - 16) + 128
244 let d = Int(uRow[sx >> 1]) - 128
245 let e = Int(vRow[sx >> 1]) - 128
246 o[i] = clamp8((c + 409 * e) >> 8)
247 o[i + 1] = clamp8((c - 100 * d - 208 * e) >> 8)
248 o[i + 2] = clamp8((c + 516 * d) >> 8)
249 i += 4
250 }
251 }
252 }
253 return out
254 }
255
256 @inline(__always) nonisolated private static func clamp8(_ value: Int) -> UInt8 {
257 UInt8(truncatingIfNeeded: value < 0 ? 0 : value > 255 ? 255 : value)
258 }
259
260 /// A box blur, `passes` times (two is close to Gaussian), by
261 /// Accelerate's vImage: since several tiles can have a backdrop at once
262 /// (2026-10-21), the blur that was most of a picture's cost, done by
263 /// hand, is done by the library that is built for it. Edges extend, so
264 /// the border is not darkened.
265 nonisolated static func boxBlur(
266 _ pixels: inout [UInt8], width: Int, height: Int, radius: Int, passes: Int
267 ) {
268 guard radius > 0, width > 0, height > 0, pixels.count >= width * height * 4 else { return }
269 var scratch = pixels
270 let kernel = UInt32(radius * 2 + 1)
271 pixels.withUnsafeMutableBytes { a in
272 scratch.withUnsafeMutableBytes { b in
273 var one = vImage_Buffer(
274 data: a.baseAddress, height: vImagePixelCount(height), width: vImagePixelCount(width),
275 rowBytes: width * 4)
276 var two = vImage_Buffer(
277 data: b.baseAddress, height: vImagePixelCount(height), width: vImagePixelCount(width),
278 rowBytes: width * 4)
279 for _ in 0..<passes {
280 vImageBoxConvolve_ARGB8888(&one, &two, nil, 0, 0, kernel, kernel, nil, vImage_Flags(kvImageEdgeExtend))
281 vImageBoxConvolve_ARGB8888(&two, &one, nil, 0, 0, kernel, kernel, nil, vImage_Flags(kvImageEdgeExtend))
282 }
283 }
284 }
285 }
286
287 nonisolated static func image(_ rgba: [UInt8], width: Int, height: Int) -> CGImage? {
288 guard let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
289 return CGImage(
290 width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
291 space: CGColorSpaceCreateDeviceRGB(),
292 bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue),
293 provider: provider, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
294 }
295}
296
297/// Where a picture goes in its tile, top-down: a screen fitted whole and
298/// centred; a camera filling the tile, cropped evenly from the sides but,
299/// from top and bottom, more from the bottom (`headroom`), since a face
300/// is above the middle of the picture and a crop through the forehead
301/// reads worse than one through the chest. The web's stage and tiles do
302/// the same with object-position (calls.css).
303public enum VideoFrame {
304 /// The share of a vertical crop taken from the top: 0.5 would be even.
305 public static let headroom: CGFloat = 0.35
306
307 public static func place(video: CGSize, in bounds: CGSize, fit: Bool) -> CGRect {
308 guard video.width > 0, video.height > 0 else { return CGRect(origin: .zero, size: bounds) }
309 let across = bounds.width / video.width
310 let down = bounds.height / video.height
311 let scale = fit ? min(across, down) : max(across, down)
312 let size = CGSize(width: video.width * scale, height: video.height * scale)
313 let spare = bounds.height - size.height
314 // Spare room (a fitted screen) is shared evenly; a crop (negative)
315 // takes headroom of it from the top.
316 let top = spare >= 0 || fit ? spare / 2 : spare * headroom
317 return CGRect(x: (bounds.width - size.width) / 2, y: top, width: size.width, height: size.height)
318 }
319}
320