Rendering stereoscopic video with RealityKit
At a glance
| Item | Summary |
|---|---|
| Purpose | Decode a side-by-side packed video, split each frame into left-eye and right-eye tagged buffers, and play the result in a loop through AVSampleBufferVideoRenderer and RealityKit’s VideoPlayerComponent. |
| App architecture | RealityKitPlaybackApp owns a @MainActor @Observable PlayerModel and injects it into ContentView. PlayerModel owns a @MainActor LoopingVideoPlayer, which owns the synchronizer, renderer, and receiver and creates one SerialProcessor actor per loop. The actor reads the asset and produces stereo sample buffers. |
| Main patterns | A small observable state owner injected through the environment; a per-loop actor that owns all reader and pixel-transfer state; a main-actor pull loop that drains the actor into the renderer’s receiver. |
| Project style | Single visionOS target with Models/ (player, looping player, processor, stereo metadata) and Views/ (one ContentView). |
| Execution model | The target sets SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; the player types are also annotated @MainActor. SerialProcessor is an actor; StereoMetadata opts out with nonisolated. LoopingVideoPlayer stores and cancels one looping task. |
| State/event model | Observation (@Observable model read through @Environment(PlayerModel.self)), onChange(of:) for readiness and scene phase, a boundary time observer for looping, and async pulls from the processor. |
| Key frameworks/packages | AVFoundation, CoreMedia, CoreVideo, VideoToolbox, RealityKit, SwiftUI. No Swift package is declared. |
Project structure
RealityKit-Playback-AVSampleBufferVideoRenderer.xcodeproj/ one visionOS application target
RealityKit-Playback-AVSampleBufferVideoRenderer/
├── RealityKitPlaybackApp.swift @main; owns PlayerModel; plain, content-sized window
├── Models/
│ ├── PlayerModel.swift @MainActor @Observable; load/play/stop; exposes videoRenderer
│ ├── LoopingVideoPlayer.swift @MainActor; synchronizer, renderer, receiver, loop task
│ ├── SerialProcessor.swift actor; AVAssetReader, VTPixelTransferSession, pixel pool
│ └── StereoMetadata.swift nonisolated value type: frame packing and crop offsets
└── Views/
└── ContentView.swift RealityView + VideoPlayerComponent; triggers load/play/stop
Structure observations
- Media work is layered by file:
PlayerModelis the UI-facing state,LoopingVideoPlayerowns AVFoundation playback objects, andSerialProcessorowns decoding and frame transformation (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:43,RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:14,RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:25). - The only view,
ContentView, never sees the processor; it readsplayer.videoRendererand callsload(),play(), andstop()(RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:28,RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:51). - The target supports
xros xrsimulatorand sets anXROS_DEPLOYMENT_TARGETof 27.0, while the DocC record lists visionOS 26.0 (RealityKit-Playback-AVSampleBufferVideoRenderer.xcodeproj/project.pbxproj:183,RealityKit-Playback-AVSampleBufferVideoRenderer.xcodeproj/project.pbxproj:285).
Overall architecture
flowchart LR
App["RealityKitPlaybackApp"] --> Model["PlayerModel (@MainActor @Observable)"]
App --> View["ContentView"]
View --> Model
View --> Component["VideoPlayerComponent(videoRenderer:)"]
Model --> Looper["LoopingVideoPlayer (@MainActor)"]
Looper --> Sync["AVSampleBufferRenderSynchronizer + Receiver"]
Looper -- "one per loop" --> Processor["SerialProcessor (actor)"]
Processor --> Reader["AVAssetReader + VTPixelTransferSession"]
Component --> Renderer["AVSampleBufferVideoRenderer"]
Sync --> Renderer
Reference code
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:12 — LoopingVideoPlayer stored state
final class LoopingVideoPlayer {
/// The synchronizer that controls the underlying video renderer.
private let synchronizer = AVSampleBufferRenderSynchronizer()
/// The video renderer that enqueues individual frames for playback.
let videoRenderer = AVSampleBufferVideoRenderer()
/// A representation of the video asset that the app plays.
private let asset: AVURLAsset
/// The receiver used to enqueue frames, obtained by adding the renderer to the synchronizer.
private var receiver: AVSampleBufferVideoRenderer.Receiver?
/// A reference to the boundary time observer that drives looping.
private var timeObserver: Any?
/// A reference to the current looping task.
private var loopingTask: Task<Void, Never>?
/// A reference to the processor that the system uses during the next playback loop.
private var nextProcessor: SerialProcessor?
// ...
}Interpretation
Observed: one AVSampleBufferVideoRenderer is shared by two consumers. RealityKit displays it through VideoPlayerComponent(videoRenderer:) (RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:28), and LoopingVideoPlayer feeds it through the receiver it obtained when adding the renderer to the synchronizer (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:46). The processor receives only the asset and the renderer’s recommended pixel-buffer attributes, not the renderer (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:144).
Inference: keeping the renderer out of the actor means the processor is a pure “next stereo buffer” source, and every enqueue decision stays with the main-actor player that owns the receiver.
Ownership and state
classDiagram
RealityKitPlaybackApp *-- PlayerModel : @State private
ContentView o-- PlayerModel : @Environment
PlayerModel *-- LoopingVideoPlayer : private let
LoopingVideoPlayer *-- AVSampleBufferRenderSynchronizer : private let
LoopingVideoPlayer *-- AVSampleBufferVideoRenderer : let
LoopingVideoPlayer *-- Receiver : private var
LoopingVideoPlayer *-- SerialProcessor : nextProcessor, one per loop
LoopingVideoPlayer *-- LoopingTask : private var loopingTask
SerialProcessor *-- AVAssetReader : private var
SerialProcessor *-- VTPixelTransferSession : private var
SerialProcessor o-- StereoMetadata : let, default side-by-side
Ownership evidence
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:14 — SerialProcessor state
actor SerialProcessor {
/// The video asset to be processed.
private let asset: AVURLAsset
/// The prevailing stereo metadata.
private let stereoMetadata: StereoMetadata
/// Pixel buffer attributes the renderer recommends for optimal display.
private let recommendedPixelBufferAttributes: CVPixelBufferAttributes
/// The asset reader, available after `start()`.
private var assetReader: AVAssetReader?
/// The output provider for the video track, available after `start()`.
private var videoTrackOutputProvider: AVAssetReaderOutput.Provider<CMReadySampleBuffer<CMSampleBuffer.DynamicContent>>?
/// The pixel transfer session used to crop each eye's frame.
private var transferSession: VTPixelTransferSession?
/// The pool that vends pixel buffers for transformed frames.
private var pixelBufferPool: CVMutablePixelBuffer.Pool?
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
RealityKitPlaybackApp |
PlayerModel |
Creates it in @State private var and injects it with .environment(player) (RealityKit-Playback-AVSampleBufferVideoRenderer/RealityKitPlaybackApp.swift:14, RealityKit-Playback-AVSampleBufferVideoRenderer/RealityKitPlaybackApp.swift:19) |
PlayerModel methods |
PlayerModel |
state: PlayerState, LoopingVideoPlayer |
private var state, private let player created in init (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:40, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:54) |
Only PlayerModel; views read isReadyToPlay |
LoopingVideoPlayer |
Synchronizer, renderer, receiver, time observer, looping task | Creates them in stored properties and init/load() (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:46, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:55) |
Only LoopingVideoPlayer, on the main actor |
LoopingVideoPlayer |
nextProcessor: SerialProcessor? |
Creates a fresh processor for the next loop in enqueueProcessor(); the running one is captured by the looping task (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:143, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:157) |
LoopingVideoPlayer |
SerialProcessor |
Reader, output provider, transfer session, pixel pool | Assigned at the end of start() and cleared in finish() (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:112, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:54) |
Only the actor |
ContentView |
Root Entity with VideoPlayerComponent |
private let entity (RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:23) |
The view’s RealityView make closure |
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 |
|---|---|---|---|
| Default isolation | SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor, SWIFT_APPROACHABLE_CONCURRENCY = YES, Swift 6 |
Undecorated declarations default to the main actor | RealityKit-Playback-AVSampleBufferVideoRenderer.xcodeproj/project.pbxproj:184, RealityKit-Playback-AVSampleBufferVideoRenderer.xcodeproj/project.pbxproj:185, RealityKit-Playback-AVSampleBufferVideoRenderer.xcodeproj/project.pbxproj:188 |
| Main-actor isolation | Explicit @MainActor on PlayerModel and LoopingVideoPlayer |
Player state, the receiver, and the loop bookkeeping are main-actor isolated | RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:12, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:11 |
| Actor isolation | actor SerialProcessor |
Reader, transfer session, and pool are mutated only inside the actor; the main actor reaches it with await processor.start(), nextSampleBuffer(), and finish(). The actor’s executor is not customized, so no specific thread is established. |
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:14, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:173, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:135 |
| Explicit opt-out | nonisolated struct StereoMetadata and nonisolated extension |
Lets the actor use the metadata value without crossing to the main actor | RealityKit-Playback-AVSampleBufferVideoRenderer/Models/StereoMetadata.swift:12, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/StereoMetadata.swift:85 |
| Retained, cancellable task | loopingTask = Task { ... } in process(with:); loopingTask.cancel() in stop() |
The task inherits main-actor isolation, drains the processor, and always awaits processor.finish(); cancellation is checked each iteration |
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:171, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:86, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:133 |
| Framework callback | addBoundaryTimeObserver(forTimes:queue: nil) { [weak self] in Task { @MainActor in ... } } |
At the asset-duration boundary the callback hops to the main actor and calls loop(rate:); the observer token is removed in stop() |
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:55, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:81 |
| Backpressure | try await receiver.enqueue(sampleBuffer) |
The drain loop awaits each enqueue and stops on flush or error results | RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:137, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:138 |
| SwiftUI-managed task | .task { await player.load() } |
Load runs for the view’s lifetime | RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:50 |
Reference code
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:167 — the retained looping task
private func process(with processor: SerialProcessor) {
guard let receiver else { return }
receiver.flush()
loopingTask = Task {
do {
try await processor.start()
try await drainSampleBuffers(from: processor, into: receiver)
} catch is CancellationError {
// Expected when `stop()` cancels the looping task; fall through to tear-down.
} catch {
debugPrint("\(#function) — error encountered during processing: \(error.localizedDescription)")
stop()
}
await processor.finish()
}
}Interpretation: the actor is the synchronization boundary for decoder resources, and the main actor is the boundary for playback control. Teardown is structured so that cancellation and errors both reach finish(), which cancels reading and invalidates the transfer session. Not established by source: whether a previous loop’s task is cancelled when a new loop starts; loop(rate:) overwrites loopingTask without cancelling it (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:158), Inference: the earlier task stops when its processor runs out of samples or when the next loop’s receiver.flush() produces a .cancelledDueToFlush result, which continuesDraining treats as a stop.
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 | @Observable PlayerModel + .environment(player) / @Environment(PlayerModel.self) |
ContentView reads isReadyToPlay and videoRenderer |
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:13, RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:20 |
| Event trigger | onChange(of: player.isReadyToPlay) and onChange(of: scenePhase) |
Starts playback once loaded; stops it when the scene goes to the background | RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:38, RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:44 |
| Media pipeline | AVAssetReader.outputProvider(for:) → VTPixelTransferSessionTransferImage → CMTaggedDynamicBuffer per eye → CMReadySampleBuffer |
Each source frame becomes one stereo sample buffer tagged with layer ID and stereo view | RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:109, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:181, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:185 |
| Framework import | AVFoundation, CoreMedia, CoreVideo, VideoToolbox |
Reader, sample buffers, pixel buffers, pixel transfer | RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:8, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:11 |
| Framework import | RealityKit, SwiftUI |
RealityView and VideoPlayerComponent |
RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:8 |
| Package declaration | None | The single application target lists no package product | RealityKit-Playback-AVSampleBufferVideoRenderer.xcodeproj/project.pbxproj:104 |
No Combine import appears in the source.
Class and protocol design
classDiagram
class PlayerModel {
<<MainActor, Observable>>
load()
play()
stop()
}
class LoopingVideoPlayer {
<<MainActor>>
load()
play()
stop()
}
class SerialProcessor {
<<actor>>
start()
nextSampleBuffer()
finish()
}
PlayerModel *-- LoopingVideoPlayer
LoopingVideoPlayer --> SerialProcessor : await
SerialProcessor --> StereoMetadata
Reference code
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:119 — the actor’s pull API
func nextSampleBuffer() async throws -> CMReadySampleBuffer<CMSampleBuffer.DynamicContent>? {
guard let videoTrackOutputProvider, let transferSession, let pixelBufferPool else {
fatalError("nextSampleBuffer() called before start()")
}
guard let sourceSampleBuffer = try await videoTrackOutputProvider.next() else {
return nil
}
return try transform(
from: sourceSampleBuffer,
with: pixelBufferPool,
in: transferSession
)
}| Type | Responsibility | Depends on |
|---|---|---|
PlayerModel |
UI-facing playback state machine (loading, loadingFailed, loaded, playing, stopped) |
LoopingVideoPlayer |
LoopingVideoPlayer |
Synchronizer and receiver ownership, loop scheduling, draining processors into the receiver | AVSampleBufferRenderSynchronizer, SerialProcessor |
SerialProcessor |
Per-loop reader setup, frame-by-frame stereo transformation, teardown | AVAssetReader, VTPixelTransferSession, StereoMetadata |
StereoMetadata |
Frame-packing math: eye size scale and crop offset per layer | CoreVideo |
ContentView |
Hosts the renderer in RealityKit and triggers load, play, and stop | PlayerModel |
Observed: the sample declares no protocol of its own. The three playback types expose matching verb sets (load/play/stop on the player types; start/nextSampleBuffer/finish on the processor), and each layer calls only the layer below it.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
PlayerModel.state, player, isPlaying (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:40, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:93) |
private |
Views see only isReadyToPlay, videoRenderer, and the commands |
Inference: the view cannot bypass the state checks in play(). |
LoopingVideoPlayer.videoRenderer (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:17) |
implicit internal let |
Readable by PlayerModel, which re-exposes it to the view |
Inference: RealityKit needs the renderer, but not the synchronizer. |
synchronizer, asset, receiver, timeObserver, loopingTask, nextProcessor (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:14) |
private |
Only the looping player schedules loops and enqueues frames | Inference: the receiver is the single enqueue path. |
continuesDraining, drainSampleBuffers, enqueueProcessor, loop, process (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:98, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:152) |
private |
Loop mechanics are hidden behind load, play, stop |
Inference: callers control playback, not looping. |
SerialProcessor stored properties and transform(from:with:in:) (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:16, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:142) |
private (plus actor isolation) |
Decoder resources are reachable only through start, nextSampleBuffer, finish |
Inference: enforces the start-before-pull order checked by the fatalError guard. |
StereoMetadata.isSideBySide (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/StereoMetadata.swift:78) |
private |
Callers use horizontalScale, verticalScale, apertureOffset |
Inference: packing details stay inside the value type. |
Reference code
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:14 — private state behind a small API
final class PlayerModel {
// ...
/// The current state of the player.
private var state = PlayerState.default
/// An instance of a looping video player.
private let player: LoopingVideoPlayer
/// The underlying video renderer.
var videoRenderer: AVSampleBufferVideoRenderer {
player.videoRenderer
}
// ...
}No declaration is public or open; undecorated declarations are Swift’s implicit internal within the single app module.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Load, play, stop gating | PlayerModel |
play() checks isReadyToPlay and !isPlaying before delegating (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:70). |
| Loop timing | LoopingVideoPlayer.load() / loop(rate:) |
A boundary time observer at the asset duration restarts the next processor at time zero (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:55, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:159). |
| Pre-building the next loop | LoopingVideoPlayer.enqueueProcessor() |
A new SerialProcessor is created right after each loop starts, so the next loop has one ready (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:161). |
| Enqueue result handling | LoopingVideoPlayer.continuesDraining(after:with:) |
Logs decode failures, stops on flush or error, and flushes when the receiver requires it (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:102). |
| Reader and transfer setup | SerialProcessor.start() |
Sizes the per-eye pool from frame packing and merges the renderer’s recommended attributes (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:87, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:96). |
| Stereo split | SerialProcessor.transform(from:with:in:) |
Crops the clean aperture for each eye and builds tagged buffers (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:157). |
| Packing math | StereoMetadata |
Pure value computations, nonisolated so the actor can call them directly. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Observable state owner | @MainActor @Observable final class PlayerModel with private var state (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:13, RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift:40) |
One owner for playback state; views observe isReadyToPlay and issue commands. |
| SwiftUI environment injection | .environment(player) and @Environment(PlayerModel.self) (RealityKit-Playback-AVSampleBufferVideoRenderer/RealityKitPlaybackApp.swift:19, RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift:20) |
The app-level model reaches the view without an initializer parameter. |
| Actor isolation | actor SerialProcessor owning reader, transfer session, and pool (RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift:14) |
Decoder resources are protected by the actor and accessed only with await; a fresh actor per loop keeps loops independent. |
The type named SerialProcessor processes frames one at a time through a pull API; no pipeline or Strategy label is claimed beyond the actor boundary that the source establishes.
Main application flow
sequenceDiagram
participant Observer as Boundary time observer
participant Looper as LoopingVideoPlayer
participant Processor as SerialProcessor
participant Receiver as Renderer receiver
Observer->>Looper: Task @MainActor loop(rate:)
Looper->>Receiver: flush()
Looper->>Processor: await start()
loop until nil or stop
Looper->>Processor: await nextSampleBuffer()
Processor-->>Looper: stereo CMReadySampleBuffer
Looper->>Receiver: await enqueue(sampleBuffer)
Receiver-->>Looper: EnqueueResult
end
Looper->>Processor: await finish()
Reference code
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:55 — boundary observer drives each loop
func load() async throws {
// Determine the duration of the underlying video asset.
let duration = try await asset.load(.duration)
// Use the asset duration as the boundary period with which to loop.
timeObserver = synchronizer.addBoundaryTimeObserver(forTimes: [NSValue(time: duration)], queue: nil) { [weak self] in
Task { @MainActor in
guard let self else { return }
self.loop(rate: self.synchronizer.rate)
}
}
// Prepare the processor that the app uses for the initial playback loop.
enqueueProcessor()
}RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:152 — one loop uses the prepared processor
private func loop(rate: Float) {
guard isLooping, let nextProcessor else {
return
}
let currentProcessor = nextProcessor
process(with: currentProcessor)
synchronizer.setRate(rate, time: .zero)
enqueueProcessor()
loopCount += 1
}RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift:128 — the drain loop
private func drainSampleBuffers(
from processor: SerialProcessor,
into receiver: AVSampleBufferVideoRenderer.Receiver
) async throws {
while true {
try Task.checkCancellation()
guard let sampleBuffer = try await processor.nextSampleBuffer() else { return }
let result = try await receiver.enqueue(sampleBuffer)
guard continuesDraining(after: result, with: receiver) else { return }
}
}Observed: the first loop is started by play() calling loop(rate: 1), and later loops come from the boundary observer. Each loop flushes the receiver, starts a new processor, and resets the synchronizer to time zero, so the drain is paced by receiver.enqueue rather than by a readiness callback.
Naming conventions
- Types: role nouns:
PlayerModel(observable state),LoopingVideoPlayer(playback engine),SerialProcessor(one-at-a-time frame producer),StereoMetadata(value description). Enums are nested in their owner (PlayerModel.PlayerState,StereoMetadata.FramePacking) with astatic let default. - Protocols: none declared locally.
- Methods: lifecycle verbs per layer (
load/play/stop,start/finish), a noun-returning pull (nextSampleBuffer()), and a Boolean-returning predicate phrased as a sentence (continuesDraining(after:with:)). Computed Booleans useis…(isReadyToPlay,isSideBySide). - Files and extensions: one type per file, named after it;
// MARK: Internal behaviorand// MARK: Private behaviorsplit each type.
Architecture takeaways
- Separate the UI-facing state machine (
PlayerModel) from the engine that owns AVFoundation objects (LoopingVideoPlayer) and from the actor that owns decoder resources (SerialProcessor). - Pass a resource-owning actor only the data it needs (asset, recommended attributes), and keep the output sink (the receiver) with the main-actor owner that controls playback.
- A per-loop actor with explicit
start/finishmakes teardown deterministic, and the looping task reachesfinish()on success, cancellation, or error. - Awaiting
receiver.enqueuegives natural backpressure; enqueue results decide whether to keep pulling. nonisolatedon a pure value type is what lets it be used from inside an actor when the target defaults to main-actor isolation.
Source map
| Source file | Relevant symbols |
|---|---|
RealityKit-Playback-AVSampleBufferVideoRenderer/RealityKitPlaybackApp.swift |
RealityKitPlaybackApp |
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/PlayerModel.swift |
PlayerModel, PlayerState, load(), play(), stop(), isReadyToPlay, videoRenderer |
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/LoopingVideoPlayer.swift |
LoopingVideoPlayer, load(), play(), stop(), continuesDraining(after:with:), drainSampleBuffers(from:into:), enqueueProcessor(), loop(rate:), process(with:) |
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/SerialProcessor.swift |
SerialProcessor, start(), nextSampleBuffer(), finish(), transform(from:with:in:) |
RealityKit-Playback-AVSampleBufferVideoRenderer/Models/StereoMetadata.swift |
StereoMetadata, FramePacking, apertureOffset(for:layerID:), horizontalScale, verticalScale |
RealityKit-Playback-AVSampleBufferVideoRenderer/Views/ContentView.swift |
ContentView, VideoPlayerComponent |
RealityKit-Playback-AVSampleBufferVideoRenderer.xcodeproj/project.pbxproj |
SWIFT_DEFAULT_ACTOR_ISOLATION, SUPPORTED_PLATFORMS, XROS_DEPLOYMENT_TARGET |