oficina / meet Public

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

Plain git — no account needed to clone.

Download

Download this file

1@_spi(Fixtures) import CallsKit
2import SwiftUI
3import LiveKitWebRTC
4
5/// The delegate exists for one reason: Apple hands a device token to
6/// the application delegate and nowhere else, so a pure SwiftUI app has
7/// no way to receive one.
8final class CallsPhoneDelegate: NSObject, UIApplicationDelegate {
9 @MainActor static var model: CallsModel?
10
11 func application(
12 _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken token: Data
13 ) {
14 Task { @MainActor in CallsPhoneDelegate.model?.registerDevice(token: token) }
15 }
16
17 func application(
18 _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error
19 ) {
20 // Expected in the simulator and on any build without the push
21 // entitlement. Silent, for the same reason as on the Mac.
22 }
23}
24
25@main struct CallsPhoneApp: App {
26 @UIApplicationDelegateAdaptor(CallsPhoneDelegate.self) private var appDelegate
27 @StateObject private var model = CallsModel()
28 @Environment(\.scenePhase) private var scenePhase
29 var body: some Scene {
30 WindowGroup {
31 #if DEBUG
32 if let level = PhoneCallFixture.rimGallery {
33 WarmRimGallery(level: level).frame(maxWidth: .infinity, maxHeight: .infinity)
34 .background(Color.black).preferredColorScheme(.dark)
35 } else if let fixture = PhoneCallFixture.requested {
36 PhoneCallFixture(fixture: fixture)
37 } else {
38 home
39 }
40 #else
41 home
42 #endif
43 }
44 }
45
46 private var home: some View {
47 PhoneHome(model: model)
48 .onOpenURL { model.openMeetingURL($0) }
49 .onAppear {
50 CallsPhoneDelegate.model = model
51 // UI tests launch with this set so a sign-in kept by an earlier
52 // run, against a harness server long gone, cannot decide what
53 // the next run sees first. The simulator's Keychain outlives the
54 // app being reinstalled.
55 if UserDefaults.standard.bool(forKey: "CallsForgetSignIn") {
56 model.signOut()
57 } else {
58 model.restore()
59 }
60 }
61 .onChange(of: scenePhase) { _, phase in
62 // This milestone is foreground-only. Browser sign-in is kept alive;
63 // an active call leaves cleanly instead of silently sending audio.
64 // The one exception is a call sharing the whole screen, whose
65 // point is the other apps the person is about to go to.
66 if phase == .background && model.joining && !model.call.sharingScreen { model.leave() }
67 UIApplication.shared.isIdleTimerDisabled = phase == .active && model.joining
68 }
69 .onChange(of: model.joining) { _, joining in
70 UIApplication.shared.isIdleTimerDisabled = joining
71 }
72 }
73}
74
75struct PhoneHome: View {
76 @ObservedObject var model: CallsModel
77 @State private var showingSettings = false
78 var body: some View {
79 NavigationStack {
80 Group {
81 if model.joining {
82 PhoneCall(call: model.call, leave: model.leave)
83 } else {
84 CallsLobby(model: model, openSettings: { showingSettings = true })
85 }
86 }.tint(CallsAppearance.accent).navigationTitle("Calls").navigationBarTitleDisplayMode(.inline)
87 .toolbar {
88 // There is no Settings app entry: the gear is where the server
89 // setting lives, reachable from home and never during a call.
90 if !model.joining {
91 ToolbarItem(placement: .topBarTrailing) {
92 Button("Settings", systemImage: "gearshape") { showingSettings = true }
93 .accessibilityIdentifier("settings")
94 }
95 }
96 }
97 .sheet(isPresented: $showingSettings) {
98 ServerSettingsSheet(model: model) { showingSettings = false }
99 .presentationDetents([.medium, .large])
100 }
101 }
102 }
103}
104
105struct PhoneCall: View {
106 @ObservedObject var call: Call
107 let leave: () -> Void
108 @State var showingChat = false
109 @State var showingDevices = false
110 @State var showingMore = false
111 /// What the controls sheet was closed to do, done once it has gone:
112 /// one sheet at a time.
113 @State var afterMore: MoreAction?
114 @State var readChatCount = 0
115 @ObservedObject var arrangement: CallArrangement
116 @ObservedObject var speakerNow: SpeakerNow
117 /// A tile being dragged to a new place, and where every tile is.
118 @State var drag: TileDrag?
119 @State var tileFrames: [String: CGRect] = [:]
120 @State var dismissedNotices: Set<String> = []
121 @State var pipDrag: CGSize = .zero
122 /// Your own picture's shape, once it arrives: the self view takes it.
123 @State var selfShape: VideoShape?
124 @StateObject var draft = ChatDraft()
125 @StateObject var screenShare = PhoneScreenShare()
126 @StateObject var chrome: ControlsVisibilityModel
127 @AppStorage(CallLayoutStyle.key) private var layoutChoice = CallLayoutStyle.defaultStyle.rawValue
128 @AppStorage(PiPCorner.key) var pipCorner = PiPCorner.bottomTrailing.rawValue
129 /// A microphone button beside the controls menu, off by default: the
130 /// chosen layout is the menu and End call alone. Set from the command
131 /// line (`-CallsMicBesideMenu YES`) to try the other.
132 @AppStorage("CallsMicBesideMenu") var micBesideMenu = false
133 @Environment(\.accessibilityReduceMotion) var reduceMotion
134 @Environment(\.accessibilityVoiceOverEnabled) var voiceOver
135 @Environment(\.fixtureBackdrop) var fixtureBackdrop
136 @Environment(\.fixtureFeeds) var fixtureFeeds
137 private let style: CallLayoutStyle?
138
139 init(
140 call: Call, leave: @escaping () -> Void, style: CallLayoutStyle? = nil,
141 controlsShown: Bool? = nil, showingMore: Bool = false, grid: Bool? = nil
142 ) {
143 self.call = call
144 self.leave = leave
145 self.style = style
146 _showingMore = State(initialValue: showingMore)
147 if let grid { call.arrangement.show(grid ? .grid : .speaker) }
148 arrangement = call.arrangement
149 speakerNow = call.levels.speaker
150 _chrome = StateObject(wrappedValue: ControlsVisibilityModel(input: .touch, pinned: controlsShown))
151 }
152
153 var layout: CallLayoutStyle { style ?? CallLayoutStyle(rawValue: layoutChoice) ?? .defaultStyle }
154
155 var grid: Bool { arrangement.layout == .grid }
156 /// Everyone else, in this viewer's order.
157 var peers: [RosterPeer] {
158 let roster = call.state?.peers ?? []
159 return arrangement.others.compactMap { id in roster.first { $0.peer == id } }
160 }
161 /// What Speaker view's stage shows, and the filmstrip under it.
162 var focused: StageItem? { arrangement.stage(active: speakerNow.peer, screens: call.screens) }
163 var filmstrip: [StageItem] { arrangement.filmstrip(stage: focused, screens: call.screens) }
164 /// You float over the stage only when you would be all the filmstrip
165 /// holds (see Stage.selfFloats).
166 var selfFloats: Bool { Stage.selfFloats(filmstrip: filmstrip, me: arrangement.me) }
167 var gridItems: [StageItem] {
168 call.screens.reversed().map(StageItem.screen) + arrangement.people.map(StageItem.camera)
169 }
170
171 /// A tile for anything the call can show, as it is seen now.
172 func phoneTile(
173 _ item: StageItem, cornerRadius: CGFloat = 18, compact: Bool = false,
174 labelInsets: EdgeInsets = EdgeInsets(), backdrop: Color = .black, onStage: Bool = false,
175 iconOnly: Bool = false
176 ) -> PhoneVideoTile {
177 let pinned = onStage && arrangement.pinned == item
178 switch item {
179 case .screen(let peer):
180 return PhoneVideoTile(
181 track: call.remoteScreens[peer], label: screenCaption(call.name(of: peer)), screen: true,
182 cornerRadius: cornerRadius, compact: compact, labelInsets: labelInsets, backdrop: backdrop,
183 onStage: onStage, pinned: pinned, iconOnly: iconOnly)
184 case .camera(let peer) where peer == arrangement.me:
185 return PhoneVideoTile(
186 track: call.localTrack, label: "You", muted: call.muted, mirrored: true,
187 cameraOff: call.cameraOff, placeholder: call.selfPlaceholder, cornerRadius: cornerRadius,
188 compact: compact, labelInsets: labelInsets, backdrop: backdrop, audio: call.selfAudio,
189 onStage: onStage, pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds["me"])
190 case .camera(let peer):
191 return PhoneVideoTile(
192 track: call.remoteTracks[peer], label: call.name(of: peer), muted: call.isMuted(peer),
193 cameraOff: call.isCameraOff(peer), lowBandwidth: call.isLowBandwidth(peer),
194 videoPaused: call.isVideoPaused(peer) ? call.videoPausedWords(peer) : nil,
195 cornerRadius: cornerRadius, compact: compact,
196 labelInsets: labelInsets, backdrop: backdrop, audio: call.tileAudio(peer),
197 onStage: onStage, pinned: pinned, iconOnly: iconOnly, fixtureVideo: fixtureFeeds[peer])
198 }
199 }
200
201 func itemTitle(_ item: StageItem) -> String {
202 switch item {
203 case .screen(let peer): screenCaption(call.name(of: peer))
204 case .camera(let peer): peer == arrangement.me ? "You" : call.name(of: peer)
205 }
206 }
207
208 /// A tile of Grid or the filmstrip: a long press picks it up to move
209 /// it, a tap pins it (the filmstrip), and VoiceOver has both as actions.
210 func arrangeable(_ item: StageItem, tapToPin: Bool) -> ArrangeableTile {
211 ArrangeableTile(
212 item: item, title: itemTitle(item), arrangement: arrangement, drag: $drag,
213 frames: tileFrames, tapToPin: tapToPin, touch: true, reduceMotion: reduceMotion,
214 fixtureLift: item == .camera(arrangement.fixtureLift ?? "") ? CGSize(width: 24, height: -30) : nil)
215 }
216
217 var body: some View {
218 Group {
219 if layout == .classic {
220 classic
221 } else {
222 fullScreen
223 }
224 }
225 .overlay(alignment: .bottom) {
226 CallToast(call: call).padding(.bottom, 110)
227 }
228 .background {
229 // ⌘⇧I on an iPad's keyboard, as on the Mac: the invite link to the
230 // clipboard. A key command with no button to show for it.
231 Button(InviteLinkCopy.title) { Task { await call.copyInviteLink() } }
232 .keyboardShortcut(InviteLinkCopy.shortcut)
233 .opacity(0).frame(width: 0, height: 0).accessibilityHidden(true)
234 }
235 .task { await call.watchAudio() }
236 .onAppear { screenShare.listen(for: call, leave: leave) }
237 .onDisappear {
238 screenShare.stop()
239 call.stopSharingScreen()
240 }
241 .sheet(isPresented: $showingDevices) {
242 NavigationStack {
243 ScrollView { DevicePanel(call: call).frame(maxWidth: .infinity, alignment: .leading) }
244 .navigationTitle("Devices").navigationBarTitleDisplayMode(.inline)
245 .toolbar {
246 ToolbarItem(placement: .confirmationAction) {
247 Button("Done") { showingDevices = false }
248 }
249 }
250 }.presentationDetents([.medium, .large])
251 }
252 .sheet(isPresented: $showingChat, onDismiss: { readChatCount = call.receivedChatCount }) {
253 NavigationStack {
254 ChatView(call: call, draft: draft).padding()
255 .navigationTitle("Chat").navigationBarTitleDisplayMode(.inline)
256 .toolbar {
257 ToolbarItem(placement: .confirmationAction) { Button("Done") { showingChat = false } }
258 }
259 }.presentationDetents([.medium, .large])
260 }
261 .onChange(of: call.receivedChatCount) { _, count in
262 if showingChat { readChatCount = count }
263 }
264 .reportProblemSheet(call)
265 }
266
267 /// The call as it was before the full-screen layout: title and stage
268 /// in the page, controls always showing along the bottom.
269 private var classic: some View {
270 VStack(spacing: 12) {
271 HStack {
272 VStack(alignment: .leading, spacing: 4) {
273 Text(call.title).font(.headline).lineLimit(2)
274 Text(call.status).font(.caption).foregroundStyle(.secondary)
275 if call.sharingScreen {
276 Label("You are sharing your screen", systemImage: "rectangle.on.rectangle")
277 .font(.caption.bold()).foregroundStyle(.orange)
278 }
279 }
280 Spacer()
281 Menu {
282 LayoutChoices(call: call, arrangement: arrangement, title: itemTitle)
283 } label: {
284 Label(
285 "Video layout", systemImage: arrangement.layout.symbol
286 )
287 .labelStyle(.iconOnly).frame(width: 44, height: 44)
288 }.accessibilityIdentifier("videoLayout")
289 }
290 if call.floor {
291 Text("Direct connections only. Some networks may be unable to connect.")
292 .font(.footnote).foregroundStyle(.secondary)
293 }
294 if grid {
295 ScrollView {
296 LazyVGrid(columns: [GridItem(.adaptive(minimum: 240))], spacing: 12) {
297 ForEach(gridItems, id: \.self) { item in
298 phoneTile(item)
299 .aspectRatio(4 / 3, contentMode: .fit)
300 .modifier(arrangeable(item, tapToPin: false))
301 }
302 }
303 }
304 .coordinateSpace(name: arrangeSpace)
305 .onPreferenceChange(TileFramesKey.self) { tileFrames = $0 }
306 } else {
307 GeometryReader { geometry in
308 ZStack(alignment: .bottomTrailing) {
309 if let focused {
310 phoneTile(focused, onStage: true)
311 } else {
312 ContentUnavailableView(
313 "Waiting for others", systemImage: "person.2",
314 description: Text("Others will appear here when they join.")
315 )
316 .frame(maxWidth: .infinity, maxHeight: .infinity)
317 .background(CallsAppearance.background, in: RoundedRectangle(cornerRadius: 18))
318 }
319 phoneTile(.camera(arrangement.me ?? ""))
320 .frame(
321 width: min(160, geometry.size.width * 0.32),
322 height: min(120, geometry.size.height * 0.28)
323 )
324 .shadow(color: .black.opacity(0.25), radius: 6, y: 2).padding(12)
325 }
326 }
327 }
328 if !(call.state?.waiting.isEmpty ?? true) {
329 ScrollView {
330 ForEach(call.state?.waiting ?? []) { person in
331 HStack {
332 Text("\(person.name) is waiting")
333 Spacer()
334 Button("Let in") { call.admit(person.peer) }
335 }
336 }
337 }.frame(maxHeight: 90)
338 }
339 if call.state?.phase == "full" { Button("Try joining again") { call.retryJoin() } }
340 if call.state?.phase == "ended" { ReportProblemButton { call.reportProblem() }.buttonStyle(.bordered) }
341 }.padding(.horizontal, 16).padding(.top, 8)
342 .safeAreaInset(edge: .bottom) {
343 HStack(spacing: 14) {
344 Button(
345 call.muted ? "Unmute microphone" : "Mute microphone",
346 glyph: call.muted ? "mic.slash.fill" : "mic.fill"
347 ) { call.mute() }
348 // Space on a hardware keyboard (iPad, mostly). It is a
349 // UIKeyCommand without wantsPriorityOverSystemBehavior, so a
350 // text field being typed in and a control with keyboard focus
351 // keep their Space; only otherwise does it mute.
352 .keyboardShortcut(.space, modifiers: [])
353 .buttonStyle(
354 CallActionStyle(
355 color: call.muted ? Color(red: 0.65, green: 0.30, blue: 0.02) : CallsAppearance.accent,
356 emphasized: call.muted))
357 Button(
358 call.cameraOff ? "Turn camera on" : "Turn camera off",
359 glyph: call.cameraOff ? "video.slash.fill" : "video.fill"
360 ) { call.toggleCamera() }
361 .buttonStyle(CallActionStyle(color: .blue, emphasized: call.cameraOff))
362 if call.sharingScreen {
363 Button("Stop sharing your screen", glyph: "rectangle.on.rectangle.slash") {
364 call.stopSharingScreen()
365 }
366 .buttonStyle(CallActionStyle(color: .orange, emphasized: true))
367 .accessibilityIdentifier("shareScreen")
368 } else {
369 BroadcastButton().frame(width: 44, height: 44)
370 .disabled(call.state?.phase != "admitted")
371 .accessibilityIdentifier("shareScreen")
372 }
373 Button("Devices", glyph: "slider.horizontal.3") { showingDevices = true }
374 .buttonStyle(CallActionStyle(color: .teal))
375 .accessibilityIdentifier("devices")
376 MeetingShareButton(call: call).buttonStyle(CallActionStyle(color: .indigo))
377 Spacer(minLength: 0)
378 Button(chatButtonTitle, glyph: "bubble.left.and.bubble.right.fill") {
379 readChatCount = call.receivedChatCount
380 showingChat = true
381 }.buttonStyle(CallActionStyle(color: .purple)).accessibilityIdentifier("openChat")
382 .overlay(alignment: .topTrailing) {
383 if unread > 0 {
384 Text("\(unread)").font(.caption.bold()).foregroundStyle(.white)
385 .padding(4).background(.purple, in: Capsule()).accessibilityHidden(true)
386 }
387 }
388 Button("Leave meeting", glyph: "phone.down.fill", role: .destructive, action: leave)
389 .buttonStyle(CallActionStyle(color: .red, emphasized: true))
390 .accessibilityIdentifier("leave")
391 }.padding(16).background(.bar)
392 }
393 }
394 var unread: Int { max(0, call.receivedChatCount - readChatCount) }
395 var chatButtonTitle: String { unread == 0 ? "Chat" : "Chat (\(unread) new)" }
396}
397
398struct PhoneVideoTile: View {
399 let track: RTCVideoTrack?
400 let label: String
401 /// §15.19: the peer has said it is muted. False for unknown.
402 var muted = false
403 var mirrored = false
404 var cameraOff = false
405 /// Spec §15.30: this app is asking them for less video ("Low
406 /// bandwidth"), and, at audio only, the words in place of the picture.
407 var lowBandwidth = false
408 var videoPaused: String? = nil
409 /// A shared screen (§5.4), shown whole rather than cropped: on a phone
410 /// more than anywhere, cropping a laptop's screen to a portrait tile
411 /// would leave the middle third of it.
412 var screen = false
413 /// Your own tile: what the camera is doing, in place of a picture that
414 /// is not arriving (see `Call.selfPlaceholder`). Nil shows the video.
415 var placeholder: String? = nil
416 /// The full-screen call's look: as rounded as `cornerRadius` says
417 /// (square to the screen's edges for the stage), a smaller name with the
418 /// muted mark inside it, kept `labelInsets` clear of the safe area and
419 /// the controls.
420 var cornerRadius: CGFloat = 18
421 var compact = false
422 var labelInsets = EdgeInsets()
423 /// Behind a picture that is not there: a shade lighter than the stage
424 /// for a tile among others, so it reads as a tile.
425 var backdrop = Color.black
426 /// The sound on this tile (spec §15.20): your microphone's glow, or a
427 /// remote person's with "No sound from" and their notices. Nil for a
428 /// screen.
429 var audio: TileAudio? = nil
430 /// Speaker view's stage: VoiceOver hears "On stage: Ana", and whether
431 /// it was pinned there.
432 var onStage = false
433 var pinned = false
434 /// A filmstrip thumbnail: the symbol alone for a missing picture.
435 var iconOnly = false
436 /// A fixture's picture of this size in place of video, on any tile
437 /// (the snapshots of portrait and landscape feeds); nil in a real call.
438 var fixtureVideo: CGSize? = nil
439 /// Told the picture's shape as it arrives, for a self view that takes
440 /// its camera's shape.
441 var shaped: ((VideoShape) -> Void)? = nil
442 /// The height of the name label and what is over it, which the
443 /// placeholder keeps clear of.
444 @State private var labelBlock: CGFloat = 0
445 /// Whether the picture is shown whole rather than filling the tile
446 /// (`VideoPlacement`), as the video view last laid it out.
447 @State private var fitted = false
448 @Environment(\.fixtureStagePicture) private var fixturePicture
449 var body: some View {
450 TileAudioReader(audio) { info in tile(info) }
451 }
452 private func tile(_ info: TileAudioInfo?) -> some View {
453 ZStack {
454 backdrop
455 if let fixtureVideo, track == nil, !cameraOff {
456 FixtureVideo(picture: fixturePicture ?? .busy, video: fixtureVideo, screen: screen, backdrop: !screen || onStage)
457 .scaleEffect(x: mirrored ? -1 : 1, y: 1)
458 } else if let fixturePicture, onStage, track == nil, !cameraOff, placeholder == nil {
459 FixtureVideo(picture: fixturePicture, screen: screen)
460 } else if let track, !cameraOff, placeholder == nil, videoPaused == nil {
461 // A screen on the stage is fitted whole, and so is a camera of
462 // another shape than its tile (a landscape Mac on an upright
463 // phone); around it, the same picture soft and dimmed rather than
464 // bars. A fitted camera in the grid or the filmstrip has its
465 // backdrop while BackdropBudget has room.
466 if screen ? onStage : fitted {
467 ScreenBackdrop(track: track, budgeted: !onStage).transition(.opacity)
468 }
469 PhoneVideo(
470 track: track, screen: screen,
471 fitted: { now in withAnimation(Self.refit) { fitted = now } }, shaped: shaped
472 )
473 .scaleEffect(x: mirrored ? -1 : 1, y: 1)
474 } else {
475 TilePlaceholder(
476 symbol: cameraOff || videoPaused != nil
477 ? "video.slash" : screen ? "rectangle.on.rectangle" : "person.crop.circle",
478 words: cameraOff || iconOnly ? nil : videoPaused ?? placeholder, wordsFont: .caption, spacing: 6,
479 reserve: labelBlock)
480 }
481 }
482 .overlay(alignment: .bottomLeading) {
483 VStack(alignment: .leading, spacing: 4) {
484 TileAudioNotices(info)
485 HStack(spacing: 5) {
486 TileSpeakingName(label: label, muted: muted, compact: compact, glow: audio?.glow)
487 if lowBandwidth { LowBandwidthBadge(compact: compact) }
488 TileAudioStatus(info)
489 }
490 }
491 .padding(compact ? 6 : 8).padding(compact ? labelInsets : EdgeInsets())
492 // Room past the label's end for the rim's outer breath, when a long
493 // name has it truncating.
494 .padding(.trailing, 6)
495 .tileLabelBlock($labelBlock)
496 }
497 .overlay(alignment: .topLeading) { if muted, !compact { MutedBadge().padding(8) } }
498 .clipShape(RoundedRectangle(cornerRadius: cornerRadius))
499 .accessibilityElement(children: .ignore)
500 .accessibilityLabel(
501 stageLabel(
502 tileAccessibilityLabel(label, muted: muted, audio: info) + (lowBandwidth ? ", low bandwidth" : ""),
503 onStage: onStage, pinned: pinned))
504 .accessibilityHint(info?.detail ?? "")
505 .accessibilityValue(
506 cameraOff
507 ? "Camera off"
508 : videoPaused ?? placeholder
509 ?? (track == nil ? (screen ? "Waiting for the screen" : "Waiting for video") : "Video on"))
510 }
511}
512extension PhoneVideoTile {
513 /// The backdrop's fade when a picture turns between filling and
514 /// fitted; none under Reduce Motion.
515 static var refit: Animation? {
516 UIAccessibility.isReduceMotionEnabled ? nil : .easeInOut(duration: 0.3)
517 }
518}
519
520struct PhoneVideo: UIViewRepresentable {
521 let track: RTCVideoTrack
522 var screen = false
523 var fitted: (Bool) -> Void = { _ in }
524 var shaped: ((VideoShape) -> Void)? = nil
525 func makeCoordinator() -> Coordinator { Coordinator() }
526 func makeUIView(context: Context) -> PlacedVideoView {
527 let view = PlacedVideoView()
528 update(view)
529 context.coordinator.attach(track, to: view.renderer)
530 return view
531 }
532 func updateUIView(_ view: PlacedVideoView, context: Context) {
533 update(view)
534 context.coordinator.attach(track, to: view.renderer)
535 }
536 private func update(_ view: PlacedVideoView) {
537 view.screen = screen
538 view.fittedChanged = fitted
539 view.shapeChanged = shaped
540 }
541 static func dismantleUIView(_ view: PlacedVideoView, coordinator: Coordinator) {
542 coordinator.track?.remove(view.renderer)
543 }
544 final class Coordinator {
545 var track: RTCVideoTrack?
546 func attach(_ next: RTCVideoTrack, to view: RTCMTLVideoView) {
547 if track !== next {
548 track?.remove(view)
549 track = next
550 next.add(view)
551 }
552 }
553 }
554}
555
556/// The renderer at the size and place `PlacedPicture` gives it: a camera
557/// filling the tile with more of a crop taken from the bottom than the
558/// top, so heads are not cut; a screen, or a camera of another shape than
559/// the tile, fitted whole. The container clips.
560final class PlacedVideoView: UIView, RTCVideoViewDelegate {
561 let renderer = RTCMTLVideoView(frame: .zero)
562 private var picture = PlacedPicture()
563 private var fitted = false
564 private var placedOnce = false
565 private var placedIn = CGSize.zero
566 private var lastShape: VideoShape?
567 var fittedChanged: (Bool) -> Void = { _ in }
568 var shapeChanged: ((VideoShape) -> Void)?
569 var screen = false {
570 didSet { if screen != oldValue { picture.screen = screen; setNeedsLayout() } }
571 }
572 override init(frame: CGRect) {
573 super.init(frame: frame)
574 clipsToBounds = true
575 isUserInteractionEnabled = false
576 renderer.videoContentMode = .scaleToFill
577 renderer.delegate = self
578 addSubview(renderer)
579 }
580 required init?(coder: NSCoder) { nil }
581 /// The size as shown, rotation applied: WebRTC's adapter turns an
582 /// upright phone's sideways buffer before it reports it.
583 nonisolated func videoView(_ videoView: RTCVideoRenderer, didChangeVideoSize size: CGSize) {
584 DispatchQueue.main.async { [weak self] in
585 guard let self, size.width > 0, size.height > 0 else { return }
586 self.picture.update(video: size)
587 if self.picture.shape != self.lastShape {
588 self.lastShape = self.picture.shape
589 let shape = self.picture.shape
590 self.shapeChanged?(shape)
591 }
592 self.setNeedsLayout()
593 }
594 }
595 override func layoutSubviews() {
596 super.layoutSubviews()
597 let placed = picture.place(in: bounds.size)
598 // Eased only when the picture turned in a place that kept its size:
599 // a rotation of the phone itself lays out at its own pace.
600 let turned = placedOnce && placed.fitted != fitted && bounds.size == placedIn
601 placedIn = bounds.size
602 placedOnce = true
603 if turned, !UIAccessibility.isReduceMotionEnabled {
604 // A phone turned mid-call: the picture eases to its new place.
605 UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut, .beginFromCurrentState]) {
606 self.renderer.frame = placed.frame
607 }
608 } else {
609 renderer.frame = placed.frame
610 }
611 if placed.fitted != fitted {
612 fitted = placed.fitted
613 let now = fitted
614 DispatchQueue.main.async { [weak self] in self?.fittedChanged(now) }
615 }
616 }
617}
618
619/// Speaker or Grid, and what is pinned to Speaker view's stage: the
620/// iPhone's layout menu, in the classic call and the controls sheet.
621struct LayoutChoices: View {
622 @ObservedObject var call: Call
623 @ObservedObject var arrangement: CallArrangement
624 let title: (StageItem) -> String
625
626 var body: some View {
627 Picker(
628 "Video layout", selection: Binding(get: { arrangement.layout }, set: { arrangement.choose($0) })
629 ) {
630 ForEach(VideoLayout.allCases) { layout in
631 Label(layout.title, systemImage: layout.symbol).tag(layout)
632 }
633 }
634 if arrangement.people.count > 2 || !call.screens.isEmpty {
635 Section("On the stage") {
636 Button {
637 arrangement.pin(nil)
638 } label: {
639 Label("Whoever is speaking", systemImage: arrangement.pinned == nil ? "checkmark" : "waveform")
640 }
641 ForEach(call.screens.reversed(), id: \.self) { peer in choice(.screen(peer)) }
642 ForEach(arrangement.others, id: \.self) { peer in choice(.camera(peer)) }
643 }
644 }
645 }
646
647 private func choice(_ item: StageItem) -> some View {
648 Button {
649 arrangement.pin(item)
650 } label: {
651 Label(title(item), systemImage: arrangement.pinned == item ? "checkmark" : "pin")
652 }
653 }
654}
655