oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1#if os(macOS)
2 import AppKit
3 import SwiftUI
4 import LiveKitWebRTC
5
6 struct MacVideoTile: View {
7 let track: RTCVideoTrack?
8 let label: String
9 /// §15.19: the peer has said it is muted. False for unknown.
10 var muted = false
11 var mirrored = false
12 var cameraOff = false
13 /// Spec §15.30: this app is asking them for less video ("Low
14 /// bandwidth"), and, at audio only, the words in place of the picture.
15 var lowBandwidth = false
16 var videoPaused: String? = nil
17 /// A shared screen (§5.4). Shown whole rather than cropped to fill:
18 /// the edge of a screen is where its menu bar and its scroll bars are,
19 /// and a face survives losing its margins where a document does not.
20 var screen = false
21 /// Your own tile: what the camera is doing, in place of a picture that
22 /// is not arriving (see `Call.selfPlaceholder`). Nil shows the video.
23 var placeholder: String? = nil
24 /// The full-window call's look: square to the window's edges (or as
25 /// rounded as `cornerRadius` says), a smaller name and muted mark, and
26 /// the name lifted by `labelLift` clear of the controls.
27 var cornerRadius: CGFloat = 16
28 var compact = false
29 var labelLift: CGFloat = 0
30 /// What shows behind a picture that is not there, or around one that
31 /// does not fill the tile. A tile among others on the full-window
32 /// stage is a shade lighter than the stage, so it reads as a tile.
33 var backdrop = Color.black
34 /// The sound on this tile (spec §15.20): your microphone's glow, or a
35 /// remote person's with "No sound from" and their notices. Nil for a
36 /// screen.
37 var audio: TileAudio? = nil
38 /// Speaker view's stage: VoiceOver hears "On stage: Ana", and whether
39 /// it was pinned there.
40 var onStage = false
41 var pinned = false
42 /// A filmstrip thumbnail: a picture that is not there is its symbol
43 /// alone, since the words would sit under the name. VoiceOver still
44 /// hears them as the tile's value.
45 var iconOnly = false
46
47 /// A fixture's picture of this size in place of video, on any tile
48 /// (the snapshots of portrait feeds); nil in a real call.
49 var fixtureVideo: CGSize? = nil
50 /// Told the picture's shape as it arrives, for a self view that takes
51 /// its camera's shape.
52 var shaped: ((VideoShape) -> Void)? = nil
53
54 /// The height of the name label and what is over it, lift included,
55 /// which the placeholder keeps clear of.
56 @State private var labelBlock: CGFloat = 0
57 /// Whether the picture is shown whole rather than filling the tile
58 /// (`VideoPlacement`), as the video view last laid it out.
59 @State private var fitted = false
60 @Environment(\.fixtureStagePicture) private var fixturePicture
61
62 var body: some View {
63 TileAudioReader(audio) { info in tile(info) }
64 }
65
66 private func tile(_ info: TileAudioInfo?) -> some View {
67 ZStack {
68 backdrop
69 if let fixtureVideo, track == nil, !cameraOff {
70 FixtureVideo(picture: fixturePicture ?? .busy, video: fixtureVideo, screen: screen, backdrop: !screen || onStage)
71 .scaleEffect(x: mirrored ? -1 : 1, y: 1)
72 } else if let fixturePicture, onStage, track == nil, !cameraOff, placeholder == nil {
73 FixtureVideo(picture: fixturePicture, screen: screen)
74 } else if let track, !cameraOff, placeholder == nil, videoPaused == nil {
75 // A screen on the stage is fitted whole, and so is a camera of
76 // another shape than its tile (a phone held upright, in a
77 // landscape window); around it, the same picture soft and
78 // dimmed rather than bars. A screen in the filmstrip keeps its
79 // plain bars; a fitted camera there or in the grid has its
80 // backdrop while BackdropBudget has room.
81 if screen ? onStage : fitted {
82 ScreenBackdrop(track: track, budgeted: !onStage).transition(.opacity)
83 }
84 MacVideoView(
85 track: track, screen: screen,
86 fitted: { now in withAnimation(Self.refit) { fitted = now } }, shaped: shaped)
87 .scaleEffect(x: mirrored ? -1 : 1, y: 1)
88 } else {
89 TilePlaceholder(
90 symbol: cameraOff || videoPaused != nil
91 ? "video.slash" : screen ? "rectangle.on.rectangle" : "person.crop.circle",
92 words: iconOnly ? nil : waiting, iconFont: iconOnly ? .title2 : .largeTitle,
93 reserve: labelBlock)
94 }
95 }
96 .overlay(alignment: .bottomLeading) {
97 VStack(alignment: .leading, spacing: 6) {
98 TileAudioNotices(info)
99 HStack(spacing: 6) {
100 TileSpeakingName(label: label, muted: muted, compact: compact, glow: audio?.glow)
101 if lowBandwidth { LowBandwidthBadge(compact: compact) }
102 TileAudioStatus(info)
103 }
104 }
105 .padding(compact ? 8 : 10).padding(.bottom, compact ? labelLift : 0)
106 // Room past the label's end for the rim's outer breath, when a long
107 // name has it truncating.
108 .padding(.trailing, 6)
109 .tileLabelBlock($labelBlock)
110 }
111 .overlay(alignment: .topLeading) { if muted, !compact { MutedBadge().padding(10) } }
112 .clipShape(RoundedRectangle(cornerRadius: cornerRadius))
113 .accessibilityElement(children: .ignore)
114 .accessibilityLabel(
115 stageLabel(
116 tileAccessibilityLabel(label, muted: muted, audio: info) + (lowBandwidth ? ", low bandwidth" : ""),
117 onStage: onStage, pinned: pinned))
118 .accessibilityHint(info?.detail ?? "")
119 .accessibilityValue(
120 cameraOff ? "Camera off" : track == nil || placeholder != nil || videoPaused != nil ? waiting : "Video on")
121 }
122 /// The backdrop's fade when a picture turns between filling and
123 /// fitted; none under Reduce Motion.
124 static var refit: Animation? {
125 NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ? nil : .easeInOut(duration: 0.3)
126 }
127
128 private var waiting: String {
129 cameraOff
130 ? "Camera off"
131 : videoPaused ?? placeholder ?? (screen ? "Waiting for the screen" : "Waiting for video")
132 }
133 }
134
135 private struct MacVideoView: NSViewRepresentable {
136 let track: RTCVideoTrack
137 var screen = false
138 /// Told whenever the picture turns between filling its tile and
139 /// being fitted whole in it.
140 var fitted: (Bool) -> Void = { _ in }
141 var shaped: ((VideoShape) -> Void)? = nil
142 func makeNSView(context: Context) -> FillVideoView { FillVideoView() }
143 func updateNSView(_ view: FillVideoView, context: Context) {
144 view.screen = screen
145 view.fittedChanged = fitted
146 view.shapeChanged = shaped
147 view.attach(track)
148 }
149 static func dismantleNSView(_ view: FillVideoView, coordinator: ()) { view.detach() }
150 }
151
152 /// The renderer keeps its source aspect ratio while the container crops
153 /// overflow — or, for a screen or a camera of another shape than the
154 /// tile, shows it whole (`PlacedPicture`).
155 final class FillVideoView: NSView, RTCVideoViewDelegate {
156 private let renderer = RTCMTLNSVideoView(frame: .zero)
157 private var track: RTCVideoTrack?
158 private var picture = PlacedPicture()
159 private(set) var fitted = false
160 private var placedOnce = false
161 private var placedIn = CGSize.zero
162 private var lastShape: VideoShape?
163 /// How many times the picture has turned between filling and fitted,
164 /// and changed shape, for the gate: a phone turned once is once each.
165 private var fitChanges = 0
166 private var shapeChanges = 0
167 var fittedChanged: (Bool) -> Void = { _ in }
168 var shapeChanged: ((VideoShape) -> Void)?
169 var screen = false {
170 didSet { if screen != oldValue { picture.screen = screen; needsLayout = true } }
171 }
172
173 override init(frame: NSRect) {
174 super.init(frame: frame)
175 wantsLayer = true
176 layer?.masksToBounds = true
177 renderer.delegate = self
178 addSubview(renderer)
179 VideoPlacementProbe.views.add(self)
180 }
181 required init?(coder: NSCoder) { nil }
182
183 // A picture takes no clicks: they go to the SwiftUI view it is in, so
184 // a drag on it moves the window (WindowMove) or the self view, as a
185 // drag on a tile with no picture does, the click that brings the
186 // window forward included.
187 override func hitTest(_ point: NSPoint) -> NSView? { nil }
188
189 func attach(_ next: RTCVideoTrack) {
190 guard track !== next else { return }
191 detach()
192 track = next
193 next.add(renderer)
194 }
195 func detach() {
196 track?.remove(renderer)
197 track = nil
198 }
199
200 /// The size WebRTC reports is the frame's as shown, its rotation
201 /// applied: an upright phone's 1280 × 720 buffer turned 90° is 720 ×
202 /// 1280 here.
203 nonisolated func videoView(_ videoView: RTCVideoRenderer, didChangeVideoSize size: CGSize) {
204 DispatchQueue.main.async { [weak self] in
205 guard let self, size.width > 0, size.height > 0 else { return }
206 self.picture.update(video: size)
207 if self.picture.shape != self.lastShape {
208 if self.lastShape != nil { self.shapeChanges += 1 }
209 self.lastShape = self.picture.shape
210 let shape = self.picture.shape
211 self.shapeChanged?(shape)
212 }
213 self.needsLayout = true
214 }
215 }
216
217 /// The probe's view of it: the picture's size and shape, whether it is
218 /// fitted, and the renderer's frame in the view (top-down).
219 var placement: [String: Any] {
220 let frame = renderer.frame
221 return [
222 "video": [picture.video.width, picture.video.height], "shape": picture.shape.rawValue,
223 "fitted": fitted, "screen": screen, "fitChanges": fitChanges, "shapeChanges": shapeChanges,
224 "bounds": [bounds.width, bounds.height],
225 "frame": [frame.minX, bounds.height - frame.maxY, frame.width, frame.height],
226 ]
227 }
228
229 override func layout() {
230 super.layout()
231 let placed = picture.place(in: bounds.size)
232 // Bottom-left origin: VideoFrame works top down.
233 let frame = NSRect(
234 x: placed.frame.minX, y: bounds.height - placed.frame.maxY, width: placed.frame.width,
235 height: placed.frame.height)
236 // Eased only when the picture turned in a place that kept its size:
237 // a window being resized follows the pointer instead.
238 let turned = placedOnce && placed.fitted != fitted && bounds.size == placedIn
239 placedIn = bounds.size
240 placedOnce = true
241 if turned, !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
242 // A phone turned mid-call: the picture eases to its new place
243 // rather than jumping.
244 NSAnimationContext.runAnimationGroup { context in
245 context.duration = 0.3
246 context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
247 renderer.animator().frame = frame
248 }
249 } else {
250 renderer.frame = frame
251 }
252 if placed.fitted != fitted {
253 fitted = placed.fitted
254 fitChanges += 1
255 let now = fitted
256 // After this layout pass: SwiftUI's state is not changed from
257 // inside one.
258 DispatchQueue.main.async { [weak self] in self?.fittedChanged(now) }
259 }
260 }
261 }
262
263 /// Every live video view, for the gate's look at where each picture is
264 /// (`CallsInterop`'s `placement` command). Weak: it holds nothing up.
265 @_spi(Fixtures) @MainActor public enum VideoPlacementProbe {
266 static let views = NSHashTable<FillVideoView>.weakObjects()
267 public static var placements: [[String: Any]] {
268 views.allObjects.filter { $0.window != nil }.map(\.placement)
269 }
270 /// How many backdrops are sampling a picture and showing it.
271 public static var backdrops: Int { BackdropSampler.showing }
272 }
273#endif
274