The camera preview is smooth. The encoder produces valid frames. The server accepts the connection and reports a healthy bitrate.
The viewer sees the presenter wave four seconds after it happened.
Every component is working according to its own contract. Capture is delivering frames on time, the encoder is compressing everything it is given, and the transport is sending everything it was handed. The product still fails, because the product's requirement, "the viewer sees it within a second", belongs to no single component. It is a property of the whole path, and it is lost in the queues between the stages, each of which holds a little time.
AVFoundation gives you excellent capture and playback primitives. A live pipeline needs more: explicit decisions about time, queues, drops, and recovery that no framework makes for you. This post goes through those decisions in the order a frame meets them.
Start with the delivery requirement
"Live video" describes at least four products:
| Product | Delay the viewer tolerates | What matters most |
|---|---|---|
| Two-way conversation | A few hundred milliseconds | Latency over quality; dropping is fine |
| Interactive broadcast with chat | One to a few seconds | Steady delay, quick recovery |
| One-way broadcast | Several seconds or more | Quality and continuity |
| Record now, upload later | None in real time | Completeness; no drops |
These lead to different architectures. A pipeline that drops old frames to stay current is correct for the first row and a defect for the last. So the requirement comes before the framework choice.
AVFoundation provides capture, and AVAssetWriter covers recording. VideoToolbox gives direct control of the encoder. Network.framework or a media library supplies the transport and packetization. Each additional layer is justified by a capability the requirement needs and the layer below does not offer. Adding layers because a "professional" pipeline seems to have many is how a three-second delay gets built.
Name the stages and measure the age of the work
A frame passes through capture, preprocessing, encoding, packetizing or muxing, the network, a server, the viewer's jitter buffer, decoding, and display. Wherever one stage can run faster than the next, there is a queue, written by you or hidden inside a library.
The number to watch on each queue is the age of its oldest item. Length misleads: ten queued frames at 60 frames per second are 167 milliseconds, and the same ten at 15 frames per second are two thirds of a second. Age is the quantity the viewer experiences.
| Stage | Evidence to collect |
|---|---|
| Capture | Timestamp gaps; dropped frames and the reason for each |
| Processing | Duration per frame; age of the oldest pending frame |
| Encoding | Time from input to output; actual bitrate; keyframe spacing |
| Transport | Bytes waiting to be sent; retransmissions or loss |
| Playback | Startup time; buffer depth; displayed media time against the capture clock |
Decide where each measurement starts and ends before adding numbers together. Intervals that overlap, or that were taken on different clocks, sum to something meaningless.
Media time is not wall-clock time
Every sample buffer carries a presentation timestamp as a CMTime, a rational number on a specific clock. That timestamp is the frame's identity in time, and it has to survive every stage intact.
The most damaging shortcut in pipeline code is restamping frames with the current time when they come out of a stage. Encode time varies from frame to frame, so restamped output has uneven spacing. The viewer sees judder, and audio, stamped separately, drifts from the picture.
Measuring age correctly means comparing a buffer's timestamp with the clock that produced it:
import AVFoundation
import CoreMedia
import VideoToolbox
import Synchronization
func captureAge(of sampleBuffer: CMSampleBuffer, on clock: CMClock) -> CMTime {
CMTimeSubtract(
CMClockGetTime(clock),
CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
)
}Pass the capture session's synchronizationClock. Do not use Date(): wall-clock time can jump when the system corrects it, and it has no defined relationship to the capture clock.
Three further rules about time:
- Audio and video must share a timeline. Inside one capture session they do. If audio comes from elsewhere, convert between clocks explicitly, for example with
CMSyncConvertTime, and test for drift over an hour, not a minute. - Encoded video has two timestamps per frame. With frame reordering enabled, decode order differs from presentation order, and a muxer needs both. Numbering frames 0, 1, 2 after the encoder is not a substitute.
- A timestamp from this device's clock means nothing on another device. End-to-end latency needs a shared reference, such as a timecode rendered into the picture and read back at the viewer.
Bound the work before the encoder
For a low-latency stream, a frame that has waited too long to be encoded is worth less than the frame that just arrived. The right queue in front of the encoder holds one item, and a newer frame replaces it.
The handoff happens on the capture queue, which must never block, so I use a lock held for a few nanoseconds in place of an actor hop:
struct CapturedFrame: @unchecked Sendable {
let sampleBuffer: CMSampleBuffer
}
final class LatestFrameMailbox<Frame: Sendable>: Sendable {
private let slot = Mutex<Frame?>(nil)
private let replaced = Mutex<Int>(0)
func offer(_ frame: Frame) {
let hadPending = slot.withLock { pending in
defer { pending = frame }
return pending != nil
}
if hadPending {
replaced.withLock { $0 += 1 }
}
}
func take() -> Frame? {
slot.withLock { pending in
defer { pending = nil }
return pending
}
}
var replacedCount: Int {
replaced.withLock { $0 }
}
}replacedCount is the pipeline telling you how often the encoder could not keep up. A value that grows steadily means the capture rate or resolution is too high for this device in its current thermal state, and the adaptation policy should react.
CapturedFrame is marked @unchecked Sendable deliberately, and it is the only such annotation in the pipeline. The SDK explicitly marks CMSampleBuffer as not Sendable. The wrapper is a written promise the compiler cannot verify: after the capture callback puts a buffer in the mailbox, exactly one consumer takes it, and nothing mutates it. If a second reader is ever added, that promise needs to be revisited.
For a recording product, this mailbox is the wrong tool. Dropping frames there violates the requirement, and the correct responses to overload are to lower the capture rate, to apply back-pressure, or to fail visibly.
What the capture output can and cannot bound
final class CaptureAdapter: NSObject,
AVCaptureVideoDataOutputSampleBufferDelegate, Sendable {
let mailbox = LatestFrameMailbox<CapturedFrame>()
private let dropReasons = Mutex<[String: Int]>([:])
func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
mailbox.offer(CapturedFrame(sampleBuffer: sampleBuffer))
}
func captureOutput(
_ output: AVCaptureOutput,
didDrop sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
let reason = CMGetAttachment(
sampleBuffer,
key: kCMSampleBufferAttachmentKey_DroppedFrameReason,
attachmentModeOut: nil
) as? String ?? "unknown"
dropReasons.withLock { $0[reason, default: 0] += 1 }
}
var dropSummary: [String: Int] {
dropReasons.withLock { $0 }
}
}alwaysDiscardsLateVideoFrames, which is on by default, makes the output drop a frame when the delegate is still busy with the previous one. That bounds exactly one queue: the one between the capture device and your callback.
It does nothing for what happens after the callback returns. The common mistake is a delegate method that starts a Task for each frame and returns immediately. The delegate now looks perfectly responsive, AVFoundation never discards anything, and the backlog has moved into the Swift runtime, where nothing bounds it and each waiting task holds a pixel buffer. The adapter above returns in microseconds as well, and it keeps at most one frame.
There is a second reason to hold few buffers. Capture buffers come from a fixed pool. If your code retains too many, the pool runs dry and capture stops delivering; the didDrop callback then reports an out-of-buffers reason. Recording drop reasons separately, as above, is what lets you tell "my callback was slow" from "I am holding buffers" from "the device is under load".
Configure the encoder for the requirement
A VTCompressionSession left at its defaults is tuned for quality. A live encoder needs to be told so:
func configureForLowLatency(
_ session: VTCompressionSession,
bitsPerSecond: Int,
framesPerSecond: Int,
keyframeIntervalSeconds: Int
) -> Bool {
let settings: [(CFString, CFTypeRef)] = [
(kVTCompressionPropertyKey_RealTime, kCFBooleanTrue),
(kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse),
(kVTCompressionPropertyKey_AverageBitRate, bitsPerSecond as CFNumber),
(kVTCompressionPropertyKey_ExpectedFrameRate, framesPerSecond as CFNumber),
(kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration,
keyframeIntervalSeconds as CFNumber)
]
return settings.allSatisfy { key, value in
VTSessionSetProperty(session, key: key, value: value) == noErr
}
}
func forcedKeyframeOptions() -> CFDictionary {
[kVTEncodeFrameOptionKey_ForceKeyFrame: true] as CFDictionary
}
func isKeyframe(_ encoded: CMSampleBuffer) -> Bool {
guard let attachments = CMSampleBufferGetSampleAttachmentsArray(
encoded, createIfNecessary: false
) as? [[CFString: Any]], let first = attachments.first else {
return true
}
return !(first[kCMSampleAttachmentKey_NotSync] as? Bool ?? false)
}Each setting is a statement about the product. RealTime tells the encoder not to trade delay for quality. Disabling frame reordering removes B-frames, which otherwise require the encoder to hold frames back before emitting anything. The keyframe interval sets how long a viewer who joins or recovers must wait for a decodable picture, and costs bitrate in exchange.
Check every return value. Not every encoder supports every property, and one that silently ignored RealTime behaves like one with a delay you cannot find. The function returns false instead of pretending.
Dropping encoded frames is a different decision
Raw frames are independent, so the mailbox could discard any of them. Encoded frames are not. With a keyframe every two seconds, the 59 frames after each keyframe (at 30 frames per second) are differences from earlier frames. Remove one from the middle, and every frame up to the next keyframe decodes to garbage, or the decoder stalls.
So when the send queue is too old, the choice is to drop a whole group and resume at a keyframe:
struct EncodedSendGate: Sendable {
let maximumQueueAge: Duration
private(set) var isWaitingForKeyframe = false
private(set) var droppedFrameCount = 0
init(maximumQueueAge: Duration) {
self.maximumQueueAge = maximumQueueAge
}
enum Decision: Equatable, Sendable {
case send
case drop(requestKeyframe: Bool)
}
mutating func decide(isKeyframe: Bool, queueAge: Duration) -> Decision {
if isWaitingForKeyframe {
guard isKeyframe, queueAge <= maximumQueueAge else {
droppedFrameCount += 1
return .drop(requestKeyframe: isKeyframe) // a stale keyframe: ask again
}
isWaitingForKeyframe = false
return .send
}
if queueAge > maximumQueueAge {
isWaitingForKeyframe = true
droppedFrameCount += 1
return .drop(requestKeyframe: true)
}
return .send
}
}Once the gate starts dropping, it drops everything until a keyframe arrives that is itself fresh enough, and it asks the encoder for one immediately (using forcedKeyframeOptions() on the next encode call) so the wait is one frame and not the rest of the interval. If that keyframe is itself stale by the time it reaches the gate, the gate asks again instead of waiting for the next natural one. The viewer sees a brief freeze followed by a current picture. Without the gate, the viewer sees a correct picture that falls further behind for the remainder of the stream.
A reconnection is the same situation. A new connection needs the codec's parameter sets (taken from the format description of the encoded output) and then a keyframe. Resuming with whichever packet is at the head of the buffer produces a black screen until the next natural keyframe.
Audio needs a separate policy. Dropping audio buffers arbitrarily produces audible clicks and moves audio out of sync with video. The usual approach is to keep audio continuous and let video absorb the loss.
Reconfiguration is a state transition
Switching camera, resolution, frame rate, or bitrate ladder mid-stream changes the format description, and may change timestamps and what the receiver must expect. It should be an explicit sequence: stop admitting frames, drain or discard what is in flight, apply the configuration, emit new parameter sets and a keyframe, resume.
Keep two values: the configuration the user asked for and the one currently in effect. A UI callback that changes encoder properties directly, while an output handler on another queue assumes the old format, is a crash that reproduces once a week.
The gap between requested and active is also where adaptation lives. A user may ask for 1080p at 60 on a device that is already hot, over a connection that can carry a third of the bitrate. The pipeline needs a policy for stepping down (frame rate first, then resolution, then bitrate, or whichever order suits the content) and for reporting which level is active. A send queue that keeps growing is not a policy.
A media library does not remove the integration work
FFmpeg and similar stacks bring codecs, muxers, filters, and protocols that the system frameworks lack. They also bring build configuration, binary size, a threading model of their own, and license terms that depend on which components were enabled in your build. "We use FFmpeg" does not describe a license position; the configure flags do. Integrate the smallest configuration that meets the requirement, and have the actual build reviewed.
For screen broadcasting, a ReplayKit broadcast upload extension runs in a separate process with a far lower memory ceiling than the app. Code that is comfortable in the main app, such as a queue of a few uncompressed 1080p frames, can get the extension terminated mid-broadcast. Measure memory in the extension itself.
Stream keys and ingest URLs are credentials. They do not belong in logs, crash report metadata, or analytics. Prefer short-lived, server-issued credentials over a long-lived key stored on the device.
Test duration and recovery
Thirty seconds of streaming in the office demonstrates the happy path. The pipeline's real properties appear later:
- an hour of continuous streaming, watching memory, device temperature, and audio/video offset;
- the network degraded with the Network Link Conditioner to a third of the configured bitrate, then restored;
- a connection drop and reconnect, measuring time to first decodable frame;
- an incoming call, a Bluetooth route change, and a camera switch mid-stream;
- the server rejecting the stream key.
For latency, film a millisecond clock with the sending device and photograph the viewer's screen next to the original clock. It is crude, and it measures the whole path including stages you cannot instrument. Record the device, the network, and the configuration with any figure you publish.
Keep local and end-to-end validation apart. A valid encoded file on the device shows the encoder works. It does not show that a viewer received or displayed anything.
What to ask of your own pipeline
- What delay does the product promise, in a number someone signed off?
- Where is every queue between capture and network, and what bounds each one?
- Does any stage replace a frame's timestamp?
- When the send queue is too old, what is dropped, and when is a keyframe requested?
- What does the pipeline do in the fiftieth minute, on a warm device, at a third of the bitrate?
The goal is a stream whose delay, recovery time, and resource use stay bounded under the conditions the product claims to support. AVFoundation is one large component of that. The system is the set of contracts you keep around it.
References
- AVFoundation: AVCaptureVideoDataOutput
- AVFoundation: alwaysDiscardsLateVideoFrames
- VideoToolbox: VTCompressionSession
- Core Media: CMTime
- Synchronization: Mutex
- ReplayKit: RPBroadcastSampleHandler
- FFmpeg: License and legal considerations
Related editions
- Edition 27 · A Fold Shouldn’t Restart Playback
- Edition 24 · Should the Music Stop When Analytics Fails?
- Edition 42 · Restoring Focus After Playback on tvOS
If this edition sharpened your next review, you can buy me a coffee.