Streaming an AR experience
At a glance
| Item | Summary |
|---|---|
| Purpose | Stream one device’s AR screen to a nearby peer as HEVC video and let the peer tap the video to place a marker back in the sender’s AR scene. |
| App architecture | UIKit storyboard app. SceneDelegate adds a transparent overlay window. ViewController runs the ARView, owns the codec and networking helpers, and wires them together. OverlayViewController owns a Metal Renderer that draws the remote peer’s video. |
| Main patterns | View-controller organization, a small RenderDestination protocol, and delegate callbacks from MultipeerConnectivity, MetalKit, and ARKit |
| Project style | One app target. Feature helpers sit at the top level, the Metal renderer is in Renderer/, and serializable value types are in Utilities/. |
| Execution model | ReplayKit, VideoToolbox, and MultipeerConnectivity callbacks feed a serial frameQueue in Renderer. UI work is sent to DispatchQueue.main. There is no Swift concurrency. |
| State/event model | Closure handlers and framework delegate callbacks. Network messages are Codable values encoded as JSON. |
| Key frameworks/packages | ARKit, RealityKit, ReplayKit, VideoToolbox, MultipeerConnectivity, MetalKit, Metal |
Project structure
StreamingARFramesLocally/
├── AppDelegate.swift // @main, ARKit support check, scene configuration
├── SceneDelegate.swift // creates the overlay window
├── ViewController.swift // ARView, capture → compress → send, receive → decode/raycast
├── OverlayViewController.swift // picture-in-picture MTKView, tap → Ray
├── MultipeerSession.swift // MCSession wrapper with closure handlers
├── VideoProcessor.swift // VTCompressionSession / VTDecompressionSession
├── VideoFrameData.swift // Codable form of a compressed CMSampleBuffer
├── Renderer/
│ ├── Renderer.swift // frame queue + MTKViewDelegate drawing
│ ├── PipelineStates.swift, DepthStencilStates.swift, VertexDescriptors.swift
│ ├── Shaders.metal, ShaderTypes.h
│ └── Utilities/ // BufferView, MetalUtils, RenderDestination
└── Utilities/ // Matrix, Ray (Codable), SIMD+Extensions
Structure observations
- Each network message is one
Codabletype, eitherVideoFrameDataorRay.Matrixis a serializable wrapper forsimd_float4x4(StreamingARFramesLocally/Utilities/Matrix.swift:8). - The Metal code is all in
Renderer/. Shared C structures cross into Swift through the bridging header (StreamingARFramesLocally/SteamingARFramesLocally-Bridging-Header.h:8). - Each device runs the same code as both sender and receiver.
ViewControllerboth captures and sends frames, and it also handles incoming frames and rays (StreamingARFramesLocally/ViewController.swift:61,StreamingARFramesLocally/ViewController.swift:105).
Overall architecture
flowchart LR
Scene["SceneDelegate"] --> Overlay["OverlayViewController"]
VC["ViewController"] --> Capture["RPScreenRecorder"]
VC --> Codec["VideoProcessor"]
VC --> Net["MultipeerSession"]
VC -->|weak| Overlay
Overlay --> Renderer["Renderer"]
Overlay -->|weak| Net
Net --> MC["MCSession"]
VC --> AR["ARView session"]
Reference code
StreamingARFramesLocally/ViewController.swift:56 — ViewController.viewDidLoad
override func viewDidLoad() {
// ...
guard let sceneDelegate = UIApplication.shared.connectedScenes
.compactMap({ ($0 as? UIWindowScene)?.delegate as? SceneDelegate })
.first else {
fatalError("Make sure that the scene delegate is of type SceneDelegate")
}
overlayViewController = sceneDelegate.overlayWindow?.rootViewController as? OverlayViewController
overlayViewController?.multipeerSession = multipeerSession
// ...
}Interpretation
ViewController is the composition point. It finds the overlay controller through the connected SceneDelegate and passes its own MultipeerSession to it, so taps in the overlay go out over the same session. The overlay window is a separate UIWindow that sits one level above the main window (StreamingARFramesLocally/SceneDelegate.swift:29). Inference: this keeps the picture-in-picture view out of the main window, which helps keep it out of the ReplayKit capture of the AR view. The source does not state this reason.
Ownership and state
classDiagram
SceneDelegate *-- UIWindow : overlayWindow
ViewController *-- MultipeerSession : lazy multipeerSession
ViewController *-- VideoProcessor : videoProcessor
ViewController *-- AnchorEntity : marker
ViewController o-- OverlayViewController : weak
OverlayViewController *-- Renderer : renderer
OverlayViewController o-- MultipeerSession : weak
MultipeerSession *-- MCSession : session
Renderer *-- Frame : frames
Ownership evidence
StreamingARFramesLocally/ViewController.swift:23 — ViewController stored properties
class ViewController: UIViewController, ARSessionDelegate {
// ...
// A weak reference to the root view controller of the overlay window.
weak var overlayViewController: OverlayViewController?
// Manages the multipeer connectivity session.
lazy var multipeerSession = MultipeerSession(receivedDataHandler: receivedData,
peerDiscoveredHandler: peerDiscovered)
// Video compressor/decompressor.
let videoProcessor = VideoProcessor()
// ...
}StreamingARFramesLocally/OverlayViewController.swift:39 — renderer creation and delegate wiring
override func viewDidLoad() {
// ...
// Configure the renderer to render to the pipView.
renderer = Renderer(device: device, renderDestination: pipView)
renderer.mtkView(pipView, drawableSizeWillChange: pipView.bounds.size)
pipView.delegate = renderer
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
SceneDelegate |
overlayWindow and its storyboard-instantiated root controller |
Creates and stores (StreamingARFramesLocally/SceneDelegate.swift:19) |
SceneDelegate |
ViewController |
multipeerSession, videoProcessor, marker |
Creates and stores | ViewController |
ViewController |
overlayViewController |
Weak reference found through the scene delegate | Set once in viewDidLoad |
ViewController |
trackedRaycast |
Private. Replaced on each received Ray (StreamingARFramesLocally/ViewController.swift:131) |
ViewController |
OverlayViewController |
renderer |
Creates and stores, then sets it as the MTKView delegate |
OverlayViewController |
OverlayViewController |
multipeerSession |
Weak, injected by ViewController (StreamingARFramesLocally/OverlayViewController.swift:19) |
ViewController |
MultipeerSession |
MCSession, advertiser, browser, handlers |
Creates in init, all private |
MultipeerSession |
Renderer |
frames, lastDrawnPTS, last-drawn matrices |
Stores. Mutated inside frameQueue.sync |
Renderer |
VideoProcessor |
compression and decompression sessions | Created lazily on first use, private |
VideoProcessor |
Inference: multipeerSession is created with method references (receivedData, peerDiscovered) that capture ViewController strongly, so the controller and the session keep each other alive. In this single-screen app they both last as long as the app.
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Main-queue scheduling | DispatchQueue.main.async |
Applies the PiP size constraints that a decode callback requests | StreamingARFramesLocally/OverlayViewController.swift:98 |
| Main-queue scheduling | DispatchQueue.main.async |
Handles a received Ray by stopping the old tracked raycast and starting a new one |
StreamingARFramesLocally/ViewController.swift:125 |
| Main-queue scheduling | DispatchQueue.main.async |
Presents the AR-session failure alert | StreamingARFramesLocally/ViewController.swift:89 |
| Framework callbacks | RPScreenRecorder.startCapture, VTCompressionSessionEncodeFrame, VTDecompressionSessionDecodeFrame output handlers |
Capture → encode → send and decode → enqueue run inside framework callbacks. The source does not set a callback queue. | StreamingARFramesLocally/ViewController.swift:61, StreamingARFramesLocally/VideoProcessor.swift:64, StreamingARFramesLocally/VideoProcessor.swift:120 |
| Shared-state safety | Serial DispatchQueue(label: "frameQueue") with sync |
Protects frames and the lastDrawn* fields in enqueueFrame and draw(in:) |
StreamingARFramesLocally/Renderer/Renderer.swift:24, StreamingARFramesLocally/Renderer/Renderer.swift:57, StreamingARFramesLocally/Renderer/Renderer.swift:127 |
| Unsynchronized read | Direct property read | tapped(_:) reads lastDrawnInverseProjectionMatrix and lastDrawnInverseViewMatrix outside frameQueue |
StreamingARFramesLocally/OverlayViewController.swift:54 |
| GPU lifetime | addCompletedHandler |
Keeps the popped Frame and its textures alive until the command buffer completes |
StreamingARFramesLocally/Renderer/Renderer.swift:133 |
| Backpressure | Queue-depth check | Clears all queued frames when more than maxFramesInQueue (15) are waiting, and drops frames older than the last one drawn |
StreamingARFramesLocally/Renderer/Renderer.swift:61 |
Nothing in the source stops the ReplayKit capture. The only explicit cancellation is trackedRaycast?.stopTracking() before each replacement (StreamingARFramesLocally/ViewController.swift:128).
Reference code
StreamingARFramesLocally/Renderer/Renderer.swift:57 — Renderer.enqueueFrame
func enqueueFrame(pixelBuffer: CVPixelBuffer, presentationTimeStamp: CMTime, inverseProjectionMatrix: Matrix, inverseViewMatrix: Matrix) {
frameQueue.sync {
/* Frames can back up in the queue due to network conditions.
If the queue experiences significant backup, the system removes all frames from the queue so that it remains close to live. */
if frames.count > maxFramesInQueue {
frames.removeAll()
}
/* There is no purpose for frames that have an earlier presentation
time than a previously drawn frame, so the system doesn’t add it to the queue of frames.*/
guard presentationTimeStamp > lastDrawnPTS else { return }
// ...
}
}State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| State propagation | Closure handlers | MultipeerSession forwards received data and peer-discovery decisions to closures supplied by ViewController |
StreamingARFramesLocally/MultipeerSession.swift:65, StreamingARFramesLocally/MultipeerSession.swift:89 |
| State propagation | Completion closures | VideoProcessor returns encoded Data through sendHandler and decoded images through decompressionHandler |
StreamingARFramesLocally/VideoProcessor.swift:84, StreamingARFramesLocally/VideoProcessor.swift:127 |
| Wire format | Codable + JSONEncoder |
Video frames and tap rays are sent as JSON. The receiver tells them apart by trying to decode each type in turn. | StreamingARFramesLocally/ViewController.swift:107, StreamingARFramesLocally/ViewController.swift:124 |
| Framework import | ReplayKit, RealityKit, ARKit |
Imported by the capturing and AR controller | StreamingARFramesLocally/ViewController.swift:11 |
| Framework import | VideoToolbox |
Imported for HEVC compression and decompression | StreamingARFramesLocally/VideoProcessor.swift:8 |
| Framework import | MultipeerConnectivity |
Imported by the session wrapper | StreamingARFramesLocally/MultipeerSession.swift:8 |
| Framework import | Metal, MetalKit |
Imported by the renderer | StreamingARFramesLocally/Renderer/Renderer.swift:9 |
| Local header | ShaderTypes.h |
Bridged into Swift and included by the Metal shaders | StreamingARFramesLocally/Renderer/Shaders.metal:12 |
Platform boundary
The project targets iPhone and iPad (TARGETED_DEVICE_FAMILY = "1,2", AR-Stream.xcodeproj/project.pbxproj:426). On iOS 27, tap matrices use ARSession.viewRotationAngle. Earlier versions fall back to a fixed .landscapeRight orientation (StreamingARFramesLocally/VideoFrameData.swift:44).
Class and protocol design
classDiagram
class RenderDestination {
<<protocol>>
colorPixelFormat
depthStencilPixelFormat
}
MTKView ..|> RenderDestination
Renderer --> RenderDestination : init
Renderer ..|> MTKViewDelegate
MultipeerSession ..|> MCSessionDelegate
MultipeerSession ..|> MCNearbyServiceBrowserDelegate
MultipeerSession ..|> MCNearbyServiceAdvertiserDelegate
ViewController ..|> ARSessionDelegate
Reference code
StreamingARFramesLocally/Renderer/Utilities/RenderDestination.swift:13 — RenderDestination
protocol RenderDestination {
var colorPixelFormat: MTLPixelFormat { get set }
var depthStencilPixelFormat: MTLPixelFormat { get set }
}
extension MTKView: RenderDestination { }| Type | Responsibility | Depends on |
|---|---|---|
ViewController |
AR session, capture-to-network pipeline, incoming-message dispatch | ARView, RPScreenRecorder, VideoProcessor, MultipeerSession |
OverlayViewController |
Shows the peer’s video and turns taps into Ray messages |
Renderer, MultipeerSession |
MultipeerSession |
Advertise, browse, invite, and send or receive Data |
MCSession, closure handlers |
VideoProcessor |
HEVC encode and decode with lazily created VT sessions | VideoToolbox, VideoFrameData |
VideoFrameData |
Serializable compressed sample buffer plus inverse camera matrices | CoreMedia, ARFrame |
Renderer |
Orders decoded frames by timestamp and draws the newest one | MTLCommandQueue, RenderDestination |
Renderer.init asks only for the pixel formats it needs through RenderDestination (StreamingARFramesLocally/Renderer/Renderer.swift:37). MTKView gets that conformance from an empty extension.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
MultipeerSession.session, serviceAdvertiser, serviceBrowser |
private |
Only the session wrapper can reach the MC objects. Callers use sendToAllPeers and connectedPeers. |
Inference: hides MultipeerConnectivity behind a small API |
MultipeerSession.receivedDataHandler, peerDiscoveredHandler |
private let |
Set once in init and never changed |
Inference: fixed callbacks for the lifetime of the session |
VideoProcessor.compressionSession, decompressionSession |
private var |
Created lazily and replaced only inside VideoProcessor |
Inference: keeps codec session lifetime internal |
VideoProcessor.compressAndSend(imageBuffer:...) |
private |
Only the CMSampleBuffer overload is visible to callers |
Inference: narrows the public entry point |
ViewController.trackedRaycast |
private |
Only ViewController can replace or stop the raycast |
Inference: one active raycast at a time |
Renderer.frames, lastDrawnInverse*Matrix |
implicit internal |
Code anywhere in the module can read them without frameQueue, and OverlayViewController does read the matrices directly |
Inference: convenience over strict encapsulation |
Reference code
StreamingARFramesLocally/MultipeerSession.swift:14 — MultipeerSession private state
class MultipeerSession: NSObject {
static let serviceType = "ar-stream"
private let myPeerID = MCPeerID(displayName: UIDevice.current.name)
private var session: MCSession!
private var serviceAdvertiser: MCNearbyServiceAdvertiser!
private var serviceBrowser: MCNearbyServiceBrowser!
private let receivedDataHandler: (Data, MCPeerID) -> Void
private let peerDiscoveredHandler: (MCPeerID) -> Bool
// ...
}Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Peer admission (at most one connected peer) | ViewController.peerDiscovered |
MultipeerSession asks this handler before inviting, so the policy stays with the app controller (StreamingARFramesLocally/ViewController.swift:149) |
| Encode, serialize, decode | VideoProcessor, VideoFrameData |
Codec and wire format are kept apart from UI and networking |
| Screen-point → world ray | OverlayViewController.makeRay |
Uses the matrices of the frame that was last drawn, so the ray matches what the user saw |
| Raycast and marker placement | ViewController |
Runs on the device that owns the ARSession |
| Frame ordering and drop policy | Renderer.enqueueFrame |
Applied before drawing so playback stays close to live |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| View-controller organization | StreamingARFramesLocally/ViewController.swift:23, StreamingARFramesLocally/ViewController.swift:27 |
ViewController creates and wires the codec, networking, and overlay. It is simple, but the controller ends up holding all pipeline coordination. |
| Protocol-oriented abstraction | StreamingARFramesLocally/Renderer/Utilities/RenderDestination.swift:13 |
Renderer needs only the pixel formats it asks for, not a concrete MTKView |
| Delegate or data-source callbacks | StreamingARFramesLocally/MultipeerSession.swift:58, StreamingARFramesLocally/Renderer/Renderer.swift:116 |
MC delegate callbacks are turned into closure handlers. MTKViewDelegate drives drawing. |
Main application flow
sequenceDiagram
participant VC as ViewController
participant VP as VideoProcessor
participant MS as MultipeerSession
participant Peer as Peer ViewController
participant R as Peer Renderer
VC->>VP: compressAndSend(sampleBuffer)
VP-->>VC: sendHandler(data)
VC->>MS: sendToAllPeers(data)
MS-->>Peer: receivedDataHandler(data)
Peer->>R: enqueueFrame(after decompress)
Reference code
StreamingARFramesLocally/ViewController.swift:69 — capture callback compresses and sends
RPScreenRecorder.shared().startCapture {
[self] (sampleBuffer, type, error) in
if type == .video {
guard let currentFrame = arView.session.currentFrame else { return }
var viewRotationAngle: CGFloat?
if #available(iOS 27.0, *) {
viewRotationAngle = arView.session.viewRotationAngle
}
videoProcessor.compressAndSend(sampleBuffer, arFrame: currentFrame, viewRotationAngle: viewRotationAngle) {
[self] (data) in
multipeerSession.sendToAllPeers(data, reliably: true)
}
}
}StreamingARFramesLocally/MultipeerSession.swift:65 — delegate callback forwards to the handler
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
receivedDataHandler(data, peerID)
}StreamingARFramesLocally/ViewController.swift:118 — receiver decodes and enqueues
func receivedData(_ data: Data, from peer: MCPeerID) {
// ...
if let videoFrameData = try? JSONDecoder().decode(VideoFrameData.self,
from: data) {
// Reconstruct a sample buffer of the compressed video frame data.
let sampleBuffer = videoFrameData.makeSampleBuffer()
// Decompress the sample buffer and enqueue it for rendering.
videoProcessor.decompress(sampleBuffer) { [self] imageBuffer, presentationTimeStamp in
// ...
overlayViewController?.renderer.enqueueFrame(
pixelBuffer: imageBuffer,
presentationTimeStamp: presentationTimeStamp,
inverseProjectionMatrix: videoFrameData.inverseProjectionMatrix,
inverseViewMatrix: videoFrameData.inverseViewMatrix)
}
// ...
}
}Naming conventions
- Types: role suffixes match what the types do.
VideoProcessorencodes and decodes,Rendererdraws, andMultipeerSessionwraps anMCSession. Wire values use plain nouns:VideoFrameData,Ray,Matrix. - Protocols:
RenderDestinationnames a capability the renderer requires. - Methods: verb phrases name what happens, such as
compressAndSend,decompress,enqueueFrame,sendToAllPeers, andmakeRay. Handler properties end inHandler. - Files and extensions: one primary type per file. Delegate conformances are grouped in
extensionblocks with// MARK:comments (StreamingARFramesLocally/Renderer/Renderer.swift:115).
Architecture takeaways
- A JSON-encoded
Codablevalue per message type makes a simple two-message protocol. Telling messages apart by trial decoding works here, but it would not scale well to more message types. - The receive path guards against network backlog with three explicit rules: order frames by presentation time, drop frames older than the last one drawn, and clear the queue past a fixed depth.
- Each frame carries its own camera matrices. Because of this, the remote tap is projected against exactly the frame the viewer saw, not the latest one.
- A serial queue protects the renderer’s frame list. The last-drawn matrices are still read outside that queue, so check every access path when you claim something is synchronized.
MultipeerSessionturns delegate callbacks into closures thatViewControllerinjects, which keeps peer-admission policy out of the networking wrapper.
Source map
| Source file | Relevant symbols |
|---|---|
StreamingARFramesLocally/AppDelegate.swift |
AppDelegate, ARWorldTrackingConfiguration.isSupported, UISceneConfiguration |
StreamingARFramesLocally/SceneDelegate.swift |
SceneDelegate, overlayWindow |
StreamingARFramesLocally/ViewController.swift |
ViewController, viewDidLoad, receivedData, peerDiscovered, trackedRaycast |
StreamingARFramesLocally/OverlayViewController.swift |
OverlayViewController, tapped, makeRay, setPipViewConstraints |
StreamingARFramesLocally/MultipeerSession.swift |
MultipeerSession, sendToAllPeers, MC delegate extensions |
StreamingARFramesLocally/VideoProcessor.swift |
VideoProcessor, compressAndSend, decompress |
StreamingARFramesLocally/VideoFrameData.swift |
VideoFrameData, makeSampleBuffer, TimingInfo |
StreamingARFramesLocally/Renderer/Renderer.swift |
Renderer, enqueueFrame, draw(in:), frameQueue, Frame |
StreamingARFramesLocally/Renderer/Utilities/RenderDestination.swift |
RenderDestination |
StreamingARFramesLocally/Renderer/Shaders.metal |
Video stream shaders |
StreamingARFramesLocally/Utilities/Matrix.swift |
Matrix |
StreamingARFramesLocally/Utilities/Ray.swift |
Ray |
StreamingARFramesLocally/Info.plist |
UIApplicationSceneManifest |
StreamingARFramesLocally/SteamingARFramesLocally-Bridging-Header.h |
ShaderTypes.h import |
AR-Stream.xcodeproj/project.pbxproj |
TARGETED_DEVICE_FAMILY |