Skip to content

Report per-frame presentation times on both the source and item axes (native path) #260

Open

Description

@edde746

What should the engine do?

Report, per muxed video frame on the native path, that frame's presentation time on both axes: the demuxed source PTS, and the value written into the segment (what AVPlayerItem.timebase reads).

Motivating media or use case

Frame-accurate libass (ASS/SSA) subtitles rendered by the host. The host must rasterise at the right media instant and stamp its overlay sample so the compositor pairs it with that frame, so it needs both numbers for the same frame.

Measured on Fixtures/restart-witness-av.mp4 (H.264 -bf 3 + AAC, 24fps, 288 frames):

source - item   -0.083333 s, constant across the epoch
                == HLSVideoEngine.playlistShiftSeconds

So the item axis is two frames ahead of source on frame 0, before any seek. Nothing currently exposed closes that:

Surface Why it falls short
Assume the axes agree 2 frames out immediately
Add playlistShiftSeconds Correct only until the next producer restart — the engine holds one shift while AVPlayer may still present frames muxed under the previous one (frameAhead)
clock.sourceTime ~10 Hz, and a clock reading is not a frame boundary: a frame's PTS sits up to a frame duration below it
Segment.startPts/startSeconds A genuine pair, but ~6 s granular
a53CaptionObserver Per-frame, but emits only one axis

Area

Public API surface

Would you be willing to open a PR?

Yes — written and tested against the witness fixture, happy to reshape first.

Proposed shape

public struct MuxedVideoFrameTime: Sendable, Equatable {
    public let source: CMTime      // demuxed PTS
    public let item: CMTime        // as written to the segment: AVPlayerItem.timebase
    public let segmentIndex: Int   // so a consumer can evict alongside segment bytes
    public let isKeyframe: Bool
}

public func setNativeVideoFrameTimeObserver(
    _ observer: (@Sendable (MuxedVideoFrameTime) -> Void)?
)

From finalizeAndWriteVideo, the one place holding both numbers, emitted after writePacket so item is the sanitized value. Plumbed like a53CaptionObserver, re-threaded onto restart producers. Timestamps only — no layer, sample buffer or clock, so presentation stays with the host. Two fields rather than one timestamp plus a convention, deliberately: #259 is what the convention cost.

Questions

  • CMTime, or ticks plus AVRational? We avoided AVRational as a Libavutil type not otherwise public.
  • Publish AVPlayerItem too? Items are swapped in place without republishing the player, so a host holding a timebase gets no signal; we KVO currentItem today.
  • Would you prefer the engine retain the table with a query API, over callbacks a host must buffer and sort?
  • Is the discontinuity case in scope for a first cut? We cannot verify it.

Activity

  1. superuser404notfound commented on Jul 30, 2026

    @superuser404notfound
    Owner

    Built this out on feat/issue260-frame-axis (#263). It went in as two pieces rather than one, and the shape differs from the proposal in two places worth naming.

    The axis relation, published as what it is. The shift is constant inside a producer epoch and steps at the edge, so it is a step function of item time, not a scalar. PresentationAxisMap publishes exactly that, converting both ways (sourceSeconds(forItemSeconds:), itemSeconds(forSourceSeconds:)) and readable off the main actor. That also meant fixing what feeds it: a VOD restart used to rebuild the shift history as a single entry covering the whole timeline, so content the previous producer muxed, which AVPlayer can still be presenting out of its buffer, folded with the incoming shift. It now records a seam at the item-axis position the new producer starts writing from, and a backward restart drops only the seams it actually rewrites. Your "correct only until the next producer restart" was the visible end of that.

    Per-frame times. setNativeVideoFrameTimeObserver reports NativeVideoFrameTime: source, item, segmentIndex, isKeyframe, and a producer epoch so a consumer can drop entries whose segments a restart has since rewritten. Emitted from finalizeAndWriteVideo, threaded onto restart producers, resolved per frame through a provider so installing an observer mid-session reaches the running producer.

    Two things the proposed shape would have hit:

    1. Emitting after writePacket reads a blank packet. av_interleaved_write_frame takes ownership and returns it "as if returned from av_packet_alloc(), even on error", so pts is AV_NOPTS_VALUE at that point. The written value now comes back out of writePacket instead. Wanting the sanitized value was right, though: the final-stage sanitizer moves timestamps on SSAI splices, so a rescale of the source value is genuinely a different number.
    2. Delivery is decode order, so source is not monotonic under B-frames. That is documented rather than sorted, since sorting would mean buffering inside the pump.

    On the questions:

    • CMTime, not ticks plus AVRational. AVRational is a Libavutil type and does not belong in the published surface.
    • AVPlayerItem is published, as currentAVPlayerItem, for the reason given: items are swapped in place, so currentAVPlayer never fires for it. Not as a field on the frame struct.
    • A retained table with a query API is unnecessary once the map exists. It would also put an eviction policy in the engine that only a host can decide.
    • The discontinuity case is in scope, and it is the reason the map exists rather than only the callbacks. Across a restart two frame-time entries can carry the same item value, and a host cannot tell which epoch is on screen. The engine can, so that answer belongs here and not in a consumer's buffer.

    Both surfaces return nil when no axis has been established, rather than defaulting the shift to zero: at the call site a defaulted shift is indistinguishable from a measured one, which is what #259 cost.

    Tested against restart-witness-av.mp4, whose two-frame reorder is what makes the axes distinguishable, with a non-zero shift required before anything is asserted so a clip where they coincide fails the witness instead of passing vacuously. One thing that surprised me: the first muxed frame does not sit at item time 0 but at +0.083333, because the tfdt anchors on the DTS while the reported time is the PTS.

    Thanks for the measurement, it named the gap precisely.

  2. superuser404notfound commented on Jul 30, 2026

    @superuser404notfound
    Owner

    Shipped in 6.2.0. presentationAxisMap for arbitrary positions, setNativeVideoFrameTimeObserver for the frames themselves, and currentAVPlayerItem for the in-place item swap.

    Leaving this open for your retest against a real libass host, since everything here was verified against a synthetic fixture and a device pass of my own.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions