// A video call in picture in picture (assets/design/chat/CONTRACT.md, "The // screens must draw"): when the person leaves the app during a live video // call, the call shrinks to the system's floating window, and nothing is // drawn in it but the other person's video. // // AVKit's video-call picture in picture (`AVPictureInPictureVideoCallViewController`) // takes a view of the app's own, not WebRTC's Metal view, so the remote // track is also drawn into an `AVSampleBufferDisplayLayer` by a renderer of // its own (`CallSampleRenderer`): each `RTCVideoFrame`'s pixel buffer (a // software-decoded I420 frame copied to NV12 first) made a `CMSampleBuffer` // shown at once, turned as the frame says. The controller starts by itself // when the app goes behind (`canStartPictureInPictureAutomaticallyFromInline`, // only while there is a remote video), from the call screen's own video as // its source, and ends when that screen goes. #if os(iOS) import AVFoundation import AVKit import CottonKit import CoreMedia import SwiftUI import UIKit import WebRTC /// The picture in picture of a video call: its window's content, the /// renderer feeding it, and AVKit's controller. @MainActor public final class CallPictureInPicture: NSObject { private let host = CallSampleHost() private let content = AVPictureInPictureVideoCallViewController() private var controller: AVPictureInPictureController? private weak var source: UIView? private var track: RTCVideoTrack? private lazy var renderer = CallSampleRenderer(view: host.display) { [weak self] size, turn in self?.shaped(size, turn: turn) } public override init() { super.init() host.frame = content.view.bounds host.autoresizingMask = [.flexibleWidth, .flexibleHeight] content.view.addSubview(host) content.preferredContentSize = CGSize(width: 9, height: 16) } /// The call screen's video stands at `view`: picture in picture may start from it. func attach(source view: UIView) { guard AVPictureInPictureController.isPictureInPictureSupported(), source !== view else { return } controller?.stopPictureInPicture() source = view let made = AVPictureInPictureController(contentSource: .init(activeVideoCallSourceView: view, contentViewController: content)) made.canStartPictureInPictureAutomaticallyFromInline = track != nil controller = made } /// The call screen's video went: no picture in picture from it. func detach(source view: UIView) { guard source === view else { return } controller?.stopPictureInPicture() controller = nil source = nil show(nil) } /// The other person's video, drawn into the window while there is one. func show(_ remote: RTCVideoTrack?) { guard remote !== track else { return } track?.remove(renderer) track = remote remote?.add(renderer) // No video, no window to start: a voice call never shrinks. controller?.canStartPictureInPictureAutomaticallyFromInline = remote != nil } /// The window takes the video's upright shape, and the display its turn. private func shaped(_ size: CGSize, turn: Int) { host.turn = turn if size.width > 0, size.height > 0 { content.preferredContentSize = size } } } /// The window's content: the display, turned as the frames say. final class CallSampleHost: UIView { let display = CallSampleView() /// The frames' rotation, degrees. var turn = 0 { didSet { if turn != oldValue { setNeedsLayout() } } } override init(frame: CGRect) { super.init(frame: frame) clipsToBounds = true addSubview(display) } required init?(coder: NSCoder) { nil } override func layoutSubviews() { super.layoutSubviews() display.transform = .identity let sideways = turn % 180 != 0 display.bounds = CGRect(x: 0, y: 0, width: sideways ? bounds.height : bounds.width, height: sideways ? bounds.width : bounds.height) display.center = CGPoint(x: bounds.midX, y: bounds.midY) display.transform = CGAffineTransform(rotationAngle: CGFloat(turn) * .pi / 180) } } /// A view whose layer is a sample buffer display layer. final class CallSampleView: UIView { override class var layerClass: AnyClass { AVSampleBufferDisplayLayer.self } var sampleLayer: AVSampleBufferDisplayLayer { layer as! AVSampleBufferDisplayLayer } override init(frame: CGRect) { super.init(frame: frame) sampleLayer.videoGravity = .resizeAspectFill } required init?(coder: NSCoder) { nil } } /// WebRTC's frames into the display layer. WebRTC calls it on its own /// decoding thread, so it holds nothing of the main actor's but the /// layer's video renderer it enqueues into, and says a change of shape on /// the main actor. final class CallSampleRenderer: NSObject, RTCVideoRenderer, @unchecked Sendable { private let lock = NSLock() private let output: AVSampleBufferVideoRenderer /// The video's upright size and rotation, said when they change. private let shape: @MainActor @Sendable (CGSize, Int) -> Void private var rotation = -1 private var size = CGSize.zero @MainActor init(view: CallSampleView, shape: @escaping @MainActor @Sendable (CGSize, Int) -> Void) { output = view.sampleLayer.sampleBufferRenderer self.shape = shape super.init() } func setSize(_ size: CGSize) {} func renderFrame(_ frame: RTCVideoFrame?) { guard let frame, let pixels = Self.pixels(of: frame.buffer), let sample = Self.sample(pixels, at: frame.timeStampNs) else { return } let turn = Int(frame.rotation.rawValue) let upright = turn % 180 != 0 ? CGSize(width: CGFloat(frame.height), height: CGFloat(frame.width)) : CGSize(width: CGFloat(frame.width), height: CGFloat(frame.height)) let changed: Bool = lock.withLock { let changed = rotation != turn || size != upright rotation = turn size = upright return changed } if output.status == .failed || output.requiresFlushToResumeDecoding { output.flush() } output.enqueue(sample) guard changed else { return } let shape = self.shape Task { @MainActor in shape(upright, turn) } } /// The frame's pixel buffer: a hardware-decoded frame's own, else the /// I420 planes copied into an NV12 buffer the layer can show. private static func pixels(of buffer: any RTCVideoFrameBuffer) -> CVPixelBuffer? { if let native = buffer as? RTCCVPixelBuffer { return native.pixelBuffer } let i420 = buffer.toI420() let width = Int(i420.width), height = Int(i420.height) var made: CVPixelBuffer? let attributes: [CFString: Any] = [kCVPixelBufferIOSurfacePropertiesKey: [CFString: Any]()] guard CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, attributes as CFDictionary, &made) == kCVReturnSuccess, let out = made else { return nil } CVPixelBufferLockBaseAddress(out, []) defer { CVPixelBufferUnlockBaseAddress(out, []) } guard let yBase = CVPixelBufferGetBaseAddressOfPlane(out, 0), let uvBase = CVPixelBufferGetBaseAddressOfPlane(out, 1) else { return nil } let yStride = CVPixelBufferGetBytesPerRowOfPlane(out, 0) let uvStride = CVPixelBufferGetBytesPerRowOfPlane(out, 1) let y = yBase.assumingMemoryBound(to: UInt8.self) let uv = uvBase.assumingMemoryBound(to: UInt8.self) for row in 0.. CMSampleBuffer? { var format: CMVideoFormatDescription? guard CMVideoFormatDescriptionCreateForImageBuffer(allocator: kCFAllocatorDefault, imageBuffer: pixels, formatDescriptionOut: &format) == noErr, let format else { return nil } var timing = CMSampleTimingInfo(duration: .invalid, presentationTimeStamp: CMTime(value: nanoseconds, timescale: 1_000_000_000), decodeTimeStamp: .invalid) var sample: CMSampleBuffer? guard CMSampleBufferCreateReadyWithImageBuffer(allocator: kCFAllocatorDefault, imageBuffer: pixels, formatDescription: format, sampleTiming: &timing, sampleBufferOut: &sample) == noErr, let sample else { return nil } if let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: true), CFArrayGetCount(attachments) > 0 { let first = unsafeBitCast(CFArrayGetValueAtIndex(attachments, 0), to: CFMutableDictionary.self) CFDictionarySetValue(first, Unmanaged.passUnretained(kCMSampleAttachmentKey_DisplayImmediately).toOpaque(), Unmanaged.passUnretained(kCFBooleanTrue).toOpaque()) } return sample } } /// Where picture in picture starts from: a view standing behind the call /// screen's remote video, handed to the controller while it is on screen. struct CallPictureInPictureSource: UIViewRepresentable { let pip: CallPictureInPicture let track: RTCVideoTrack? final class Coordinator { let pip: CallPictureInPicture init(pip: CallPictureInPicture) { self.pip = pip } } func makeCoordinator() -> Coordinator { Coordinator(pip: pip) } func makeUIView(context: Context) -> UIView { let view = UIView() view.isUserInteractionEnabled = false pip.attach(source: view) return view } func updateUIView(_ view: UIView, context: Context) { pip.show(track) } static func dismantleUIView(_ view: UIView, coordinator: Coordinator) { coordinator.pip.detach(source: view) } } #endif