Skip to content
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ the public-API contract.

- `setSoftwareSubtitleDelay(_:)` applies a persistent, caller-selected subtitle offset to both channels in software PiP without changing the playback clock. Native renditions remain unchanged.
- `needsForegroundVideoRestore` exposes actual background video teardown so a host can rebuild through the existing reload API before resuming.
- **`LoadOptions.progressiveSegmentDelivery` serves VOD loopback segments while they are written.** Off by default. The muxer flushes a fragment about every 0.5 s instead of holding up to 8 s, the segment cache tracks the segment being written, and the loopback server sends each fragment as it lands over a chunked response, so AVPlayer shows and starts on a segment's first fragments instead of waiting for its cut. A segment the producer abandons ends its connection without the final chunk, and each chunk sent counts as fetch activity for the #65 wedge watchdog, which otherwise reads a long transfer as AVPlayer no longer fetching. `aetherctl play --progressive-segments` drives it. Measured on a Mac over a 6 Mbit/s origin with 1080p HEVC at 2.7 Mbit/s: first frame 0.9 s instead of 2.2 s, playing 1.7 s instead of 2.3 s, one rebuffer instead of three to four in the first 30 s, and seeks outside the buffer landing in 0.56 s / 1.27 s instead of 1.20 s / 2.25 s.

### Fixed

Expand Down
1 change: 1 addition & 0 deletions Sources/AetherEngine/AetherEngine+Loading.swift
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,7 @@ extension AetherEngine {
)
// AE#464: every producer this session builds reads it off the session. Set before start().
session.audioDelaySeconds = loadedOptions.audioDelaySeconds
session.servesSegmentsProgressively = loadedOptions.progressiveSegmentDelivery
// #240: the pump claims the source link through this gate while it is fetching, so the
// subtitle side readers can stay out of its way. Set before start().
session.sideReaderLinkGate = sideReaderLinkGate
Expand Down
2 changes: 1 addition & 1 deletion Sources/AetherEngine/AetherEngine+ReloadWithOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ enum SessionOptionCorrection {
"preserveASSMarkup", "prepareNativeSubtitles", "eagerNativeSubtitleReaders", "serveIFramePlaylist", "confirmAtmos",
"nativeSubtitlePreferredLanguages", "sequentialOrigin", "maxConcurrentSourceRequests", "heldSourceConnection",
"declaredDurationSeconds", "probesize", "maxAnalyzeDuration", "preferredAudioLanguages",
"preferredSubtitleLanguages", "externalSubtitles", "forwardBufferSegments", "autoplay",
"preferredSubtitleLanguages", "externalSubtitles", "forwardBufferSegments", "progressiveSegmentDelivery", "autoplay",
"audioDelaySeconds", "teletextPage", "deinterlaceMode", "deinterlaceFieldRate", "preferredDecodePath",
"escalatesToSoftwarePath", "sharedOutputRole", "isLiveRejoin", "subtitleSessionCarryover",
]
Expand Down
63 changes: 62 additions & 1 deletion Sources/AetherEngine/Network/HLSLocalServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ protocol HLSSegmentProvider: AnyObject {
/// Default forwards to `mediaSegment(at:)` without ever signalling.
func mediaSegment(at index: Int, onSlow: (@Sendable () -> Void)?) -> Data?

/// As above, but a VOD segment that is still being written may come back as a reader over it,
/// which the server sends chunk by chunk (`LoadOptions.progressiveSegmentDelivery`). Default
/// wraps `mediaSegment(at:onSlow:)`.
func mediaSegmentSource(at index: Int, onSlow: (@Sendable () -> Void)?) -> SegmentSource?

/// Optional file URL for disk-backed segments (cache adopt path). Server streams file -> socket bypassing Foundation Data; sendfile(2) was tried but SIGSYS'd on tvOS sandbox.
/// Must name a file that exists: the server stats and opens it afterwards, and a URL whose file
/// has gone is answered with an error response rather than the bytes the bookkeeping promised.
Expand All @@ -28,6 +33,10 @@ protocol HLSSegmentProvider: AnyObject {
/// request needs to know whether that request was answered. Default ignores it.
func didServeMediaSegment(index: Int, delivered: Bool)

/// One more chunk of a progressively delivered segment left the server: the request-counting
/// wedge watchdog's evidence that AVPlayer is still reading. Default ignores it.
func didDeliverProgressiveChunk(index: Int)

var segmentCount: Int { get }
func segmentDuration(at index: Int) -> Double

Expand Down Expand Up @@ -143,8 +152,12 @@ protocol HLSSegmentProvider: AnyObject {

extension HLSSegmentProvider {
func mediaSegment(at index: Int, onSlow: (@Sendable () -> Void)?) -> Data? { mediaSegment(at: index) }
func mediaSegmentSource(at index: Int, onSlow: (@Sendable () -> Void)?) -> SegmentSource? {
mediaSegment(at: index, onSlow: onSlow).map { .data($0) }
}
func mediaSegmentURL(at index: Int) -> URL? { nil }
func didServeMediaSegment(index: Int, delivered: Bool) {}
func didDeliverProgressiveChunk(index: Int) {}
var staticMasterPlaylistBody: String? { nil }
var firstVisibleSegmentIndex: Int { 0 }
func segmentIsDiscontinuous(at index: Int) -> Bool { false }
Expand Down Expand Up @@ -1209,7 +1222,7 @@ final class HLSLocalServer: @unchecked Sendable {
// ~3.5 s time-to-first-byte watchdog logs -12889 per silent request and three
// strikes fail the item (failedToPlayToEndTime, terminal from the couch).
let early = EarlyHeaderState()
let data = provider?.mediaSegment(at: index, onSlow: { [weak self] in
let source = provider?.mediaSegmentSource(at: index, onSlow: { [weak self] in
guard let self, early.markSentOnce() else { return }
EngineLog.emit(
"[HLSLocalServer] seg\(index): slow serve, sending early chunked header",
Expand All @@ -1218,6 +1231,23 @@ final class HLSLocalServer: @unchecked Sendable {
data: Self.chunkedResponseHeader(contentType: "video/mp4"),
path: "\(normalizedPath) [early header]")
})
// A segment being written: commit the chunked header (unless the slow-serve
// signal already did) and send each fragment as it lands. An abandoned segment
// ends the connection without the final chunk, so AVPlayer retries it rather
// than taking the partial bytes for a whole segment.
if case .progressive(let reader) = source {
if early.markSentOnce() {
guard writeAll(fd: fd, data: Self.chunkedResponseHeader(contentType: "video/mp4"),
path: "\(normalizedPath) [progressive header]") else {
return refused(false)
}
}
return delivered(sendProgressiveBody(fd: fd, path: normalizedPath, reader: reader))
}
let data: Data? = {
if case .data(let d) = source { return d }
return nil
}()
if early.wasSent {
guard let data, !data.isEmpty else {
// Headers are committed; abort so AVPlayer sees a truncated transfer
Expand Down Expand Up @@ -1296,6 +1326,37 @@ final class HLSLocalServer: @unchecked Sendable {

/// Body for an early-header serve: the whole segment as one chunk. Four separate send()
/// calls so mmap-backed segment Data is never copied into a Swift heap buffer.
/// Body for a progressively delivered segment: one chunk per read (usually the fragment the muxer
/// just flushed), the final chunk once the sealed segment is read to its end. Returns false
/// without the final chunk when the producer abandons the segment.
private func sendProgressiveBody(fd: Int32, path: String, reader: ProgressiveSegmentReader) -> Bool {
let provider = self.provider
var sent = 0
while true {
switch reader.next() {
case .bytes(let data):
guard writeAll(fd: fd, data: Self.chunkFrameHeader(size: data.count), path: "\(path) [chunk size]"),
writeAll(fd: fd, data: data, path: path),
writeAll(fd: fd, data: Self.chunkFrameTrailer, path: "\(path) [chunk trailer]") else {
return false
}
sent += data.count
provider?.didDeliverProgressiveChunk(index: reader.index)
case .finished:
EngineLog.emit(
"[HLSLocalServer] -> 200 \(path) bytes=\(sent) type=video/mp4 [progressive]",
category: .hlsServer, level: .verbose)
return writeAll(fd: fd, data: Self.chunkedFinal, path: "\(path) [chunk final]")
case .abandoned:
EngineLog.emit(
"[HLSLocalServer] \(path): the producer abandoned this segment after \(sent) B sent; "
+ "closing so AVPlayer asks for it again",
category: .hlsServer)
return false
}
}
}

private func sendChunkedBody(fd: Int32, path: String, data: Data) -> Bool {
EngineLog.emit(
"[HLSLocalServer] -> 200 \(path) bytes=\(data.count) type=video/mp4 [chunked, early header]",
Expand Down
12 changes: 12 additions & 0 deletions Sources/AetherEngine/PlayerState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,16 @@ public struct LoadOptions: Sendable, Equatable {
/// remote server directly.
public var forwardBufferSegments: Int?

/// Serve each VOD loopback segment while it is being written instead of after its cut. The
/// muxer flushes a fragment about every half second and the loopback server sends each one as
/// it lands, so AVPlayer can show and start on the first fragments of a segment rather than
/// waiting for all of it. On a fast or local source a segment is cut long before AVPlayer asks
/// for it and nothing changes; on a slow link it is the difference between waiting for a whole
/// segment (seconds of a long GOP at the link's rate) and waiting for its first fragment.
/// Default false. VOD only: live keeps its own window and blocking-reload contracts. Ignored for
/// `nativeRemoteHLS` and on the software path, which serve no loopback segments.
public var progressiveSegmentDelivery: Bool = false

/// Autostart at load completion. Default `true`: every load path ends in `host.play()` and a
/// `.playing` state (current behavior, byte-identical). Set `false` to mount PAUSED: a host that
/// holds a pause at mount (synchronized-start lobby that loads several devices and starts them on
Expand Down Expand Up @@ -912,6 +922,7 @@ public struct LoadOptions: Sendable, Equatable {
preferredSubtitleLanguages: [String] = [],
externalSubtitles: [ExternalSubtitleTrack] = [],
forwardBufferSegments: Int? = nil,
progressiveSegmentDelivery: Bool = false,
autoplay: Bool = true,
teletextPage: Int? = nil,
audioDelaySeconds: Double = 0,
Expand Down Expand Up @@ -957,6 +968,7 @@ public struct LoadOptions: Sendable, Equatable {
self.preferredSubtitleLanguages = preferredSubtitleLanguages
self.externalSubtitles = externalSubtitles
self.forwardBufferSegments = forwardBufferSegments
self.progressiveSegmentDelivery = progressiveSegmentDelivery
self.autoplay = autoplay
self.teletextPage = teletextPage
self.audioDelaySeconds = audioDelaySeconds
Expand Down
33 changes: 32 additions & 1 deletion Sources/AetherEngine/Video/HLSSegmentProducer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,15 @@ final class HLSSegmentProducer: @unchecked Sendable {
/// AE#464: the host's audio offset this producer's muxers write. Fixed for the producer's life;
/// a new value arrives as a new producer (see `MP4SegmentMuxer.audioDelaySeconds`).
private let audioDelaySeconds: Double
/// `LoadOptions.progressiveSegmentDelivery`: register each VOD segment with the cache as it is
/// opened, and flush fragments every `progressiveFragmentSeconds` so the loopback server has
/// something to send while the segment is still being cut.
private let servesSegmentsProgressively: Bool
/// The fragment cadence inside a progressively delivered segment. Measured with `aetherctl play`
/// on a Mac over a 6 Mbit/s origin (1080p HEVC at 2.7 Mbit/s, 3-9 s GOPs): playing after 1.9 s at
/// 1 s fragments and 1.7 s at 0.5 s, against 2.3 s without progressive delivery. Each fragment
/// costs a moof of a few hundred bytes.
static let progressiveFragmentSeconds: Double = 0.5

/// #65 stall diag: only log a park once it exceeds ~2 segment durations of zero playback progress, so normal
/// backpressure (releases within one segment) stays silent and a real wedge surfaces its frozen tuple.
Expand Down Expand Up @@ -1474,9 +1483,11 @@ final class HLSSegmentProducer: @unchecked Sendable {
audioMoovPrimeFrame: [UInt8]? = nil,
audioMoovPrimeKnownUnobtainable: Bool = false,
audioDelaySeconds: Double = 0,
servesSegmentsProgressively: Bool = false,
epoch: UInt64 = 0
) throws {
self.epoch = epoch
self.servesSegmentsProgressively = servesSegmentsProgressively
self.audioDelaySeconds = audioDelaySeconds
self.audioMoovPrimeFrame = audioMoovPrimeFrame
self.audioMoovPrimeKnownUnobtainable = audioMoovPrimeKnownUnobtainable
Expand Down Expand Up @@ -2138,7 +2149,8 @@ final class HLSSegmentProducer: @unchecked Sendable {
// audio stream that decodes to nothing can't buffer the whole span and fill the disk (#64).
// Floored at 8s (the historical 2 x 4s value): a sub-second fastZap cut target (AE#195)
// must not shrink the cap below typical TS A/V interleave skew.
maxBufferedFragmentSeconds: max(8.0, 2 * targetSegmentDurationSeconds),
maxBufferedFragmentSeconds: servesProgressively
? Self.progressiveFragmentSeconds : max(8.0, 2 * targetSegmentDurationSeconds),
// AE#222 + mid-session rotation: the last frame a muxer accepted, or the host's
// construction-time prime while no muxer has accepted one yet.
audioMoovPrimeFrame: audioMoovPrimeFrame,
Expand Down Expand Up @@ -2166,6 +2178,7 @@ final class HLSSegmentProducer: @unchecked Sendable {
// outgoing muxer's totals have to be folded before the reference goes.
self.installMuxer(muxer)
self.currentMuxerSegmentIndex = initialSegmentIndex
self.noteSegmentInProgress(initialSegmentIndex, muxer: muxer)
return muxer
} catch {
EngineLog.emit(
Expand Down Expand Up @@ -2430,6 +2443,7 @@ final class HLSSegmentProducer: @unchecked Sendable {
return nil
case .failed:
// Failed cut: muxer has no open staging fd, every byte is silently discarded. Fatal.
abandonSegmentInProgress(currentMuxerSegmentIndex)
EngineLog.emit(
"[HLSSegmentProducer] seg-\(currentMuxerSegmentIndex).m4s cut FAILED; "
+ "muxer is wedged, ending pump",
Expand Down Expand Up @@ -2458,6 +2472,7 @@ final class HLSSegmentProducer: @unchecked Sendable {
)
}
currentMuxerSegmentIndex = newIdx
noteSegmentInProgress(newIdx, muxer: muxer)
if isLive {
// Live is source-paced: the pump only runs ahead of real time while draining the join
// backlog, and the sliding window (notePlaylistBuild -> evictBelow) bounds resident
Expand Down Expand Up @@ -2600,6 +2615,19 @@ final class HLSSegmentProducer: @unchecked Sendable {
return .syncAt(offsetSeconds: offset)
}

/// Progressive delivery is VOD only: live keeps its own window and blocking-reload contracts.
private var servesProgressively: Bool { !isLive && servesSegmentsProgressively }

private func noteSegmentInProgress(_ index: Int, muxer: MP4SegmentMuxer) {
guard servesProgressively else { return }
cache.beginInProgress(index: index, stagingPath: muxer.stagingURL)
}

private func abandonSegmentInProgress(_ index: Int) {
guard servesProgressively, index != .min else { return }
cache.abandonInProgress(index: index)
}

private func finalizeSessionMuxerAndAdopt() {
guard let muxer = currentMuxer else { return }
let idx = currentMuxerSegmentIndex
Expand All @@ -2617,6 +2645,7 @@ final class HLSSegmentProducer: @unchecked Sendable {
reportSequentialSegmentFinalized(index: idx, isFinal: true)
}
} else {
abandonSegmentInProgress(idx)
EngineLog.emit(
"[HLSSegmentProducer] seg-\(idx).m4s final finalize failed; not adopted",
category: .session
Expand All @@ -2631,6 +2660,8 @@ final class HLSSegmentProducer: @unchecked Sendable {
private func discardSessionMuxer() {
guard let muxer = currentMuxer else { return }
let idx = currentMuxerSegmentIndex
// The partial segment is not adopted; a reader draining it is told before the file goes.
abandonSegmentInProgress(idx)
if let result = muxer.finalize() {
try? FileManager.default.removeItem(at: result.path)
EngineLog.emit(
Expand Down
6 changes: 6 additions & 0 deletions Sources/AetherEngine/Video/HLSVideoEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,10 @@ public final class HLSVideoEngine: @unchecked Sendable {
/// what actually replaces the segments and the item holding them.
public var audioDelaySeconds: Double = 0

/// `LoadOptions.progressiveSegmentDelivery`, handed to the provider and to every producer this
/// session builds. Set before `start()`.
var servesSegmentsProgressively = false

/// Serializes restart requests among themselves. Held across waits (unlike `restartLock`);
/// only other restarts contend on it.
private let restartGate = NSLock()
Expand Down Expand Up @@ -1954,6 +1958,7 @@ public final class HLSVideoEngine: @unchecked Sendable {
sourceBitrate: sourceBitrate,
audioLanguage: servedAudioLanguage,
isLive: isLiveSession,
servesSegmentsProgressively: servesSegmentsProgressively,
// Sequential archives: playlist grows with the producer's REAL cut durations. The
// static plan's uniform EXTINF lies whenever the archive's GOP cadence does not
// divide the cut target (1.92 s GOPs vs a 4.0 s plan put every segment's media up
Expand Down Expand Up @@ -2800,6 +2805,7 @@ public final class HLSVideoEngine: @unchecked Sendable {
// AE#464: read here rather than pushed, so every producer this session builds (seek
// restart, live reopen, #99 revive) cuts with the offset currently in force.
audioDelaySeconds: audioDelaySeconds,
servesSegmentsProgressively: servesSegmentsProgressively,
epoch: producerEpoch
)
// #240: threaded onto every producer (initial + restart), like the wedge-detector providers
Expand Down
3 changes: 3 additions & 0 deletions Sources/AetherEngine/Video/MP4SegmentMuxer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,9 @@ final class MP4SegmentMuxer {
/// Same volume as cache adopt target so rename is metadata-only.
private let sessionDir: URL
private var currentStagingPath: URL
/// The current segment's staging file. Only appended to, then renamed as it stands on adoption,
/// which is what lets progressive delivery read it while it is written.
var stagingURL: URL { currentStagingPath }
private var fd: Int32 = -1
private var formatContext: UnsafeMutablePointer<AVFormatContext>?
private var pb: UnsafeMutablePointer<AVIOContext>?
Expand Down
Loading
Loading