Skip to content

fix(software): AV1 through dav1d seeks onto the nearest keyframe - #943

Merged
superuser404notfound merged 1 commit into
superuser404notfound:mainfrom
chrws:fix/av1-keyframe-seeks
Oct 31, 2026
Merged

superuser404notfound merged 1 commit into
superuser404notfound:mainfrom
chrws:fix/av1-keyframe-seeks

Conversation

@chrws

@chrws chrws commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Summary

A seek into AV1 on the software host now lands on a keyframe, and a seek the packet cache serves starts on that keyframe itself. On an Apple TV 4K (A15) that took +30 s seeks into a 4K AV1 encode from holding the clock 2.5 to 4.6 s to 0.13 to 0.54 s. dav1d had to decode from a keyframe up to the target, and a cached seek started one keyframe earlier still, so with AV1's long GOPs (6.7 s from SvtAv1EncApp's default keyint) that was up to two GOPs of 4K decode before the picture came back.

What changed

  • SWKeyframeSnap (new): for a session of dav1d decoding AV1, a seek lands on the keyframe nearest its target, within 10 s and never on the other side of the playhead. Without a keyframe at or after the target it stays exact. SeekEvent.landed reports the keyframe's position, which its contract already allows ("keyframe granularity ... can put a few seconds off target").
  • The keyframes it snaps to are the packet cache's retained ones (SoftwarePacketReadAhead.retainedKeyframeSeconds, from the packets' own keyframe flags) plus the container's index. The index alone did not work on the device: a seek the cache serves never repositions the demuxer, so Matroska's Cues were never read, the index held only the keyframes read so far, and none of five +30 s seeks snapped. The cache's own list is current as the read-ahead moves, and it does not depend on the cues (CLAUDE.md: cues are not sync points).
  • The index is read off the main actor (BlockingWork), at open and after every landing, never at the seek: indexedKeyframes takes the demuxer's access lock, which readPacket holds across a slow remote read (SoftwarePlaybackHost.seek runs the deadline-free Demuxer.seek on the main actor — a remote source can block the main thread for seconds (field App Hangs) #254).
  • SoftwarePacketReadAhead.anchorsOnLastKeyframe, set for the same sessions: a cache hit restores to the last retained keyframe at or before the target instead of the one before it. The earlier keyframe is there for open-GOP and audio preroll; an AV1 keyframe opens on its own, and a forward key frame is flagged only when it refreshes every reference (AV1 playback failure #931). With snapping alone, hits onto a keyframe still held the clock 1.8 to 2.5 s while dav1d decoded the GOP before it; with this, 0.13 to 0.18 s. Every other codec keeps the earlier anchor.
  • AetherEngine.snapsAV1SeeksToKeyframes (@_spi(Diagnostics), default on) switches both off, for comparisons. Documented under "Public but not host API".
  • Docs: api.md (seek(to:), the switch), formats.md (software AV1), architecture.md (source map, cached seeks), CHANGELOG.md under Unreleased. The 10 s reach is pinned in DocumentedConstantsTests.

Test plan

  • Device / OS: Apple TV 4K (3rd generation, A15, no AV1 hardware), tvOS 27.2, HDMI into an LG CX. MacBook Pro (M5 Pro), macOS 27, for the suite.

  • Source media: a 4K AV1 encode (SvtAv1EncApp CRF 22, 10-bit, film grain synthesis, Dolby Vision 10.1, keyframes every 6.715 s) with DTS-HD MA, cut to 4.5 minutes with -c copy from the film's heaviest passage (19 Mbit/s), MKV, served over LAN HTTP.

  • Result, same build, snapsAV1SeeksToKeyframes set per launch: 15 s into playback, five seeks of +30 s, 12 s apart, in the order snapped, exact, exact, snapped. Clock hold is the [AudioOutput] preroll ready after time. Thermal state nominal in every sample, 0 dropped and 0 late frames in all four runs.

    Seek Exact (runs 2 / 3) Snapped (runs 1 / 4)
    1 3.28 / 3.29 s, cache hit 0.14 / 0.13 s, cache hit
    2 2.52 / 2.54 s, cache hit 0.54 / 0.50 s, cache miss (the keyframe lay past the read-ahead)
    3 2.76 / 2.77 s, cache hit 0.17 / 0.17 s, cache hit
    4 4.56 / 4.60 s, cache hit 0.18 / 0.18 s, cache hit
    5 3.58 / 3.59 s, cache hit 0.17 / 0.17 s, cache hit

    The snapped seeks landed 0.8 to 2.4 s from their target (+30 s became +28.6 to +32.4 s).

  • Unit tests: KeyframeSnappedSeekTests (nearest keyframe either side, never across the playhead, an index short of the target, a sparse index, the cache's keyframes beside the index, and a cache hit's first packet with and without anchorsOnLastKeyframe), plus the reach pin in DocumentedConstantsTests.

  • swift test: XCTest 814 tests, 0 failures. swift-testing 5,466 tests, 3 failures, the three that also failed on main on this machine when I last checked (Issue220SoftwareDecoderDrainTests, APACEncodePipelineTests' synchronous-encode test, and HLSLocalServerSlowPeerTests' LAN-peer test, which the macOS firewall here blocks).

  • swift build --enable-all-traits: builds.

One question: a host's chapter jump through seek(to:) now lands up to half a GOP (about 3.4 s here) from the chapter mark on this route. A resume through startPosition is not affected. If chapter seeks should stay exact, a per-call opt-out would be the place for it; I left that out until you say it is wanted.

Checklist

  • CHANGELOG.md updated
  • Commit messages follow Conventional Commits (feat(...), fix(...), chore(...))
  • The fix lives in the engine, not in a host-side workaround
  • Public API changes are intentional and documented

🤖 Generated with Claude Code

A seek decodes from a keyframe up to its target, and AV1 encodes run long GOPs (6.7 s from
SvtAv1EncApp's default keyint at 23.976 fps). A seek the packet cache served also started on the
keyframe before that one, so dav1d decoded up to two GOPs before the picture came back: on an
Apple TV 4K (3rd generation, A15), +30 s seeks into a 4K AV1 encode held the clock 2.5 to 4.6 s.

A session of dav1d decoding AV1 now lands a seek on the keyframe nearest its target
(`SWKeyframeSnap`), within 10 s and never on the other side of the playhead, and a cache hit
restores to that keyframe itself (`SoftwarePacketReadAhead.anchorsOnLastKeyframe`): an AV1
keyframe opens on its own, and a forward key frame is flagged only when it refreshes every
reference (superuser404notfound#931). The same seeks held the clock 0.13 to 0.18 s from the cache and 0.5 s from a
fresh reposition, 10 each way on the same build. `SeekEvent.landed` reports the keyframe's
position, which its contract allows.

The keyframes come from the packet cache's retained packets (their own keyframe flags) and from the
container's index. Without one at or after the target the seek stays exact: Matroska reads its Cues
only when the demuxer repositions, which a cached seek never does, so until then the index holds
only the keyframes read so far (a seek to 70 s from 11 s once landed on 13.4 s). The index is read
off the main actor, at open and after every landing, and the seek uses the list read last, because
`indexedKeyframes` takes the demuxer's access lock, which a slow remote read holds (superuser404notfound#254).

`AetherEngine.snapsAV1SeeksToKeyframes` (`@_spi(Diagnostics)`, default on) switches both off for
comparisons.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@quint-aether quint-aether Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review

Status: 🔴 Blocking. Serious defects, not mergeable as is.

The PR makes software-host AV1 seeks land on the nearest keyframe, and makes a cache hit start on that keyframe instead of the one before it. Fixing this in the engine is the right direction, and the device numbers are convincing. Two things need to change before the behaviour matches what the docs promise.

Findings

  • Blocking: The snap runs inside SoftwarePlaybackHost.seek(to:), so every internal reposition to the playhead goes through it: the AE#739 session rebuild, the flush-recovery .reposition, and the audio-delay re-anchor (AetherEngine+AudioDelay.swift:97). When the target equals the playhead, the rule lands on the keyframe behind it. Each of those now rewinds the viewer by up to half a GOP (about 3.4 s on the test file). (Sources/AetherEngine/Native/SoftwarePlaybackHost.swift:2369)
  • Blocking: The engine never learns where the host landed. AetherEngine.seek finalizes the software host on the requested target: clock.currentTime = target, applySeekFinalizeSourceTime(target:), then .landed(renderedTime: clock.sourceTime). So SeekEvent.landed reports the request, not the keyframe, which contradicts the new api.md text. Subtitle overlays are also re-anchored at a position that is not on screen. On a forward snap, the harvest anchor noted at the request makes [target, keyframe] count as read by the pump, which is the #416 hazard. (Sources/AetherEngine/Native/SoftwarePlaybackHost.swift:2376)
  • Should fix: No test covers the host-level wiring: that a snapped seek reports the keyframe, and that a playhead reposition stays exact. The pure-function tests would pass with both blocking issues in place.

Checklist: CHANGELOG yes, docs yes (the .landed sentence in api.md is not true yet), tests yes for the pure logic, no for the integration, traits both ways n.a.

Needs a device run: Once the landing is reported, check the clock-hold numbers on the Apple TV again. Also check that subtitles stay in sync after a forward snap and after an audio-delay nudge on AV1. On your chapter question: a per-call opt-out is a maintainer decision, but the internal-caller fix above needs the same kind of switch, so one parameter could serve both.

Thanks for the careful measurements and the thorough write-up.

Automated review by Quint (Claude) of 4c8f5d8. It reads the code, it does not build or run it; a maintainer reviews and merges.

sessionZeroSeconds: clockSessionZero
)
var seconds = seconds
if snapsSeeksToKeyframes, !isLive,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This snaps every call to seek(to:), not only user seeks. The host's own playhead repositions call it with the current time: recoverVideoSession() (await self?.seek(to: target) with target = currentTime), the flush-recovery .reposition case, and AetherEngine.setAudioDelay, which re-anchors through seek(to: position). With target == current, snappedSeconds takes the nearest < current branch and returns the keyframe behind the playhead, up to half a GOP back (about 3.4 s on the 6.7 s GOP). So after this PR, each audio-delay nudge, each background-return session rebuild and each flush recovery on software AV1 replays a few seconds. Recovery used to bring the picture back "on the frame the audio is at". Suggested fix: make snapping opt-in per call, for example seek(to:snapToKeyframe:), and pass true only from the engine's user and host transport seek. Alternatively, skip the snap when the target is within a small epsilon of the playhead. A test for the playhead case would pin it.

indexed: snapKeyframeSeconds)) {
EngineLog.emit("[SWHost] seek snapped to keyframe target_s=\(String(format: "%.3f", sourceSeconds)) "
+ "keyframe_s=\(String(format: "%.3f", snapped))", category: .swPlayback)
seconds += snapped - sourceSeconds

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The snapped position stays inside the host. AetherEngine.seek finalizes a software-host seek on the target it requested. landedDisplay is target when not nativeOnly, clock.currentTime = landedDisplay, and applySeekFinalizeSourceTime(target:) sets clock.sourceTime to the request. The ticket then closes with .landed(renderedTime: clock.sourceTime). So SeekEvent.landed reports the requested position, not the keyframe, which contradicts the new api.md sentence. reanchorSubtitleOverlays() also re-anchors at a position that is not on screen. There is a further problem on a forward snap. noteHarvestAnchor(.pump, at: clockTarget) is stated before the host seek, on the assumption that the demuxer lands at or before the target. The pump then reports progress from the keyframe, so the open run covers [target, keyframe] that nothing read (#416). Suggested fix: return the landing from the host (for example the snapped source seconds beside the RepositionOutcome). The engine should then publish that position, re-anchor subtitles there, and note the harvest anchor at min(target, landing) or after the landing. A test should assert that .landed carries the keyframe.

@superuser404notfound
superuser404notfound merged commit a0670dc into superuser404notfound:main Oct 31, 2026
4 of 5 checks passed
superuser404notfound pushed a commit that referenced this pull request Oct 31, 2026
- seek(to:exact:) lands exactly on the software AV1 route too, for a
  chapter mark or the end of an intro. A seek stashed during load keeps
  the flag.
- The engine decides the landing (SoftwarePlaybackHost.keyframeLanding)
  before it notes the subtitle harvest anchor and publishes the clock.
  The host used to snap inside its own seek, so the #416 ledger claimed
  [target, keyframe) as read and finalize published the requested
  position instead of the keyframe.
- A snap moves a seek by at most half its own distance: +10 s from 6.6 s
  with keyframes at 6.7 s and 30 s landed 0.1 s ahead.
- A keyframe both the packet cache and the index list keeps the cache's
  value. The index converts ticks as pts * (num / den) and sat one bit
  below the cache's pts * num / den for about one keyframe in five at
  1/24000, so the cache hit's exact comparison restored to the keyframe
  before it, the GOP decode the PR removes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SeT6NgupsgTSme7g6RFnE5
@superuser404notfound

Copy link
Copy Markdown
Owner

Thanks, merged (ba6f6e8 on main, unreleased for now). The same-build A/B with the exact/snapped/snapped/exact order made this an easy call, and finding that cache-served seeks never read the Matroska Cues was a good catch.

On your chapter question: yes, I want exact seeks to stay available, so the follow-up commit adds seek(to:exact:). seek(to:) keeps the keyframe landing, and Sodalite will pass exact: true for intro/outro segment ends and chapter marks, where landing a few seconds early brings the skip button back for the intro's tail. Three smaller changes in the same commit:

  • The engine now decides the landing (SoftwarePlaybackHost.keyframeLanding) before it notes the After a re-aimed restart, a PGS set whose clear is stranded below the producer floor overstays at the landing #416 subtitle harvest anchor and publishes the clock. With the snap inside the host's own seek, the ledger claimed [target, keyframe) as read, and finalize published the requested position instead of the keyframe.
  • A snap moves a seek by at most half its own distance, so +10 s from 6.6 s with keyframes at 6.7 s and 30 s no longer lands 0.1 s ahead.
  • candidates keeps the cache's value for a keyframe both lists hold. The index converts ticks as pts * (num / den), the cache as pts * num / den, and at a 1/24000 time base (common for 23.976 MP4) the index value sits one bit lower for about one keyframe in five. The cache hit's exact <= then restored to the keyframe before it. Your MKV at 1/1000 never hits this, which is why the device runs looked clean.

If you get a chance to rerun the five +30 s seeks on main, I'd expect the same numbers.

superuser404notfound pushed a commit that referenced this pull request Nov 1, 2026
selectChapter(id:) sought with seek(to:), which on the software host's AV1
route may snap to a keyframe seconds away since 7.54.0 (#943). A chapter
mark is the documented case for seek(to:exact:).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SeT6NgupsgTSme7g6RFnE5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants