Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 71 additions & 15 deletions Sources/LumeEngineCore/Render/SystemRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ public final class SystemRenderer: @unchecked Sendable {
// default QoS they get descheduled on loaded devices (see Demuxer.start).
private let videoQueue = DispatchQueue(label: "engine.lume.render.video", qos: .userInteractive)
private let audioQueue = DispatchQueue(label: "engine.lume.render.audio", qos: .userInteractive)
/// How long a starved pump waits before asking for data again. This is
/// the only latency a frame that lands in an empty channel picks up, so
/// keep it well under a frame interval at 50/60 fps.
private let starvationRetryMilliseconds = 10

// Guarded by `lock`.
private let lock = NSLock()
Expand All @@ -35,6 +39,9 @@ public final class SystemRenderer: @unchecked Sendable {
private var videoPumpScheduled = false
private var audioPumpScheduled = false
private var stopped = false
// How often each pump has run. Read through `pumpCounts`.
private var videoPumpCount = 0
private var audioPumpCount = 0

// Queue-confined format caches.
private var videoFormatCache: CMVideoFormatDescription?
Expand Down Expand Up @@ -100,9 +107,7 @@ public final class SystemRenderer: @unchecked Sendable {
lock.lock()
videoObservation = observation
lock.unlock()
videoRenderer.requestMediaDataWhenReady(on: videoQueue) { [weak self] in
self?.pumpVideo()
}
videoQueue.async { [weak self] in self?.armVideo() }
}

if audio != nil {
Expand All @@ -115,9 +120,7 @@ public final class SystemRenderer: @unchecked Sendable {
lock.lock()
audioObservation = observation
lock.unlock()
audioRenderer.requestMediaDataWhenReady(on: audioQueue) { [weak self] in
self?.pumpAudio()
}
audioQueue.async { [weak self] in self?.armAudio() }
} else if audioWasAttached {
detachAudioRenderer()
}
Expand Down Expand Up @@ -259,19 +262,67 @@ public final class SystemRenderer: @unchecked Sendable {

// MARK: Pumps (render queues)

/// Feeds the video renderer. `requestMediaDataWhenReady` only re-fires on
/// readiness transitions, so on starvation we self-schedule a retry — the
/// pump never silently stops (the classic "spinner stuck forever" failure, PLAN.md §3.3).
// `requestMediaDataWhenReady` is not edge-triggered: for as long as the
// renderer stays ready, AVFoundation calls the block again the moment it
// returns. A pump that returns early because it has nothing to enqueue
// would therefore spin — millions of calls a second, a whole core per lane
// at userInteractive. Live TV is that state almost all the time: frames
// arrive in real time, so the renderer never fills up. So a starved pump
// stops requesting and its retry re-arms, and a pump with no lane
// (detached or shut down) stops requesting without re-arming.
//
// Arming always happens on the lane's queue, the queue the pump stops
// requesting on. That orders the two: a track switch that detaches and
// re-attaches audio can't have its fresh request cancelled by a pump that
// was still running against the old, detached lane.

/// Lane-queue-confined.
private func armVideo() {
lock.lock()
let live = videoLaneAttached && !stopped
lock.unlock()
guard live else { return }
videoRenderer.requestMediaDataWhenReady(on: videoQueue) { [weak self] in
self?.pumpVideo()
}
}

/// Lane-queue-confined.
private func armAudio() {
lock.lock()
let live = audioLaneAttached && !stopped
lock.unlock()
guard live else { return }
audioRenderer.requestMediaDataWhenReady(on: audioQueue) { [weak self] in
self?.pumpAudio()
}
}

/// How many times each pump has run — what a starvation spin inflates.
var pumpCounts: (video: Int, audio: Int) {
lock.lock()
defer { lock.unlock() }
return (videoPumpCount, audioPumpCount)
}

/// Feeds the video renderer. On starvation it stops requesting and
/// self-schedules a re-arm, so the pump never silently stops (the classic
/// "spinner stuck forever" failure, PLAN.md §3.3) and never spins either.
private func pumpVideo() {
lock.lock()
let input = videoInput
let serial = acceptedSerial
let isStopped = stopped
videoPumpCount += 1
lock.unlock()
guard let input, !isStopped else { return }
guard let input, !isStopped else {
videoRenderer.stopRequestingMediaData()
return
}

while videoRenderer.isReadyForMoreMediaData {
guard let frame = input.tryReceive() else {
videoRenderer.stopRequestingMediaData()
scheduleVideoRetry()
return
}
Expand All @@ -294,11 +345,16 @@ public final class SystemRenderer: @unchecked Sendable {
let input = audioInput
let serial = acceptedSerial
let isStopped = stopped
audioPumpCount += 1
lock.unlock()
guard let input, !isStopped else { return }
guard let input, !isStopped else {
audioRenderer.stopRequestingMediaData()
return
}

while audioRenderer.isReadyForMoreMediaData {
guard let frame = input.tryReceive() else {
audioRenderer.stopRequestingMediaData()
scheduleAudioRetry()
return
}
Expand Down Expand Up @@ -326,12 +382,12 @@ public final class SystemRenderer: @unchecked Sendable {
if shouldSchedule { videoPumpScheduled = true }
lock.unlock()
guard shouldSchedule else { return }
videoQueue.asyncAfter(deadline: .now() + .milliseconds(30)) { [weak self] in
videoQueue.asyncAfter(deadline: .now() + .milliseconds(starvationRetryMilliseconds)) { [weak self] in
guard let self else { return }
self.lock.lock()
self.videoPumpScheduled = false
self.lock.unlock()
self.pumpVideo()
self.armVideo()
}
}

Expand All @@ -341,12 +397,12 @@ public final class SystemRenderer: @unchecked Sendable {
if shouldSchedule { audioPumpScheduled = true }
lock.unlock()
guard shouldSchedule else { return }
audioQueue.asyncAfter(deadline: .now() + .milliseconds(30)) { [weak self] in
audioQueue.asyncAfter(deadline: .now() + .milliseconds(starvationRetryMilliseconds)) { [weak self] in
guard let self else { return }
self.lock.lock()
self.audioPumpScheduled = false
self.lock.unlock()
self.pumpAudio()
self.armAudio()
}
}
}
56 changes: 56 additions & 0 deletions Tests/LumeEngineCoreTests/SystemRendererTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import CoreVideo
import Foundation
import Testing
@testable import LumeEngineCore

/// The render pumps against a live renderer with empty decode channels — the
/// steady state of live TV, where frames arrive in real time and the
/// renderer never fills up.
@Suite("SystemRenderer")
struct SystemRendererTests {
/// `requestMediaDataWhenReady` calls its block straight back while the
/// renderer is ready, so a pump that just returned on an empty channel ran
/// millions of times a second — a core per lane, pegged.
@Test func starvedPumpsIdleOnTheirRetry() async throws {
let renderer = SystemRenderer(muted: true)
defer { renderer.shutdown() }
renderer.attach(video: Channel<VideoFrame>(capacity: 8), audio: Channel<AudioFrame>(capacity: 8))

try await Task.sleep(for: .milliseconds(500))

let counts = renderer.pumpCounts
// The 10 ms retry is ~50 runs per lane here; the spin was millions.
#expect(counts.video < 250)
#expect(counts.audio < 250)
}

/// Idling must not mean dead: a frame that lands after the pump went quiet
/// still reaches the renderer (PLAN.md §3.3, the stuck-spinner failure).
@Test func starvedVideoPumpPicksUpALateFrame() async throws {
let renderer = SystemRenderer(muted: true)
defer { renderer.shutdown() }
let video = Channel<VideoFrame>(capacity: 8)
renderer.attach(video: video, audio: nil)

try await Task.sleep(for: .milliseconds(200))
#expect(renderer.enqueuedHighWaterMark.video == MediaTime.noTimestamp)

let frame = try #require(Self.blackFrame(pts: 40_000))
try video.send(frame)

let deadline = ContinuousClock.now + .seconds(2)
while renderer.enqueuedHighWaterMark.video != frame.pts, ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10))
}
#expect(renderer.enqueuedHighWaterMark.video == frame.pts)
}

private static func blackFrame(pts: Int64) -> VideoFrame? {
var buffer: CVPixelBuffer?
let attributes = [kCVPixelBufferIOSurfacePropertiesKey: [:]] as CFDictionary
guard CVPixelBufferCreate(nil, 64, 64, kCVPixelFormatType_32BGRA, attributes, &buffer) == kCVReturnSuccess,
let buffer
else { return nil }
return VideoFrame(pixelBuffer: buffer, pts: pts, duration: 40_000, serial: 0, isHardwareDecoded: false)
}
}
Loading