Repository navigation
feat(deinterlace): inverse telecine for hard-telecined NTSC film (#853) - #1105
Conversation
…eruser404notfound#853) A load samples SD NTSC MPEG-2 whose frames decode interlaced before it writes the display criteria: fieldmatch + idet, and the repeated frame of each five at a steady phase, judged by the worst 16x16 block. On film the deinterlace graph becomes fieldmatch, the deinterlacer for frames left combed, then decimate, and the display is asked for 23.976 Hz. True interlaced video, live, HD and PAL keep today's path. - LoadOptions.inverseTelecine (.auto, .off, .force); VideoDeinterlace.inverseTelecine and outputFrameRateFactor - the buffer source declares frame_rate for decimate; a timestamp gap re-anchors it; the GPU chain keeps fieldmatch + decimate on the CPU before the upload; scrub stills keep the plain deinterlacer - the session keeps the decision through seeks, audio switches, reloads and background restores; a correction via reloadAtCurrentPosition(applying:) is reported as the load's - TelecineCadenceProbe samples from the start position; one window at the middle of the file was measured against it over throttled HTTP and dropped (slower on every link) - aetherctl play --inverse-telecine, scrubpreview --inverse-telecine - tests on synthetic 3:2 frames and embedded MPEG-2 clips; docs and measurements Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Automated review
Status: 🟠 Needs changes. Real issues to fix before merge.
The PR adds load-time inverse telecine for hard-telecined NTSC MPEG-2 film: it samples with fieldmatch + idet plus a five-frame repeat check, then runs fieldmatch/decimate around the deinterlacer and asks the display for 23.976 Hz. The direction is right. The fix lives in the engine and does not depend on the host. It is scoped tightly, falls back to today's deinterlacer whenever the sample is unsure, and is backed by real measurements. The problems are in how the session-kept decision interacts with the existing reload paths.
Findings
- Should fix: If a host's foreground restore after a background teardown changes only
inverseTelecine, the call now returnsrebuilt: falseand never rebuilds the torn-down session, so no picture comes back. The comment above that early return says the #357 resume can never reach it, and this PR makes that possible. (Sources/AetherEngine/AetherEngine+ReloadWithOptions.swift:224) - Should fix:
inverseTelecineCarryoverstays inloadedOptionsafter the load that used it.subtitleSessionCarryoveris cleared atAetherEngine.swift:5043for exactly this reason (#170). After one URLreloadAtCurrentPosition, a laterselectTitle(or the ingest reroute) reloads fromloadedOptions. The new title then skips the sample and inherits the old title's decision and display rate. (Sources/AetherEngine/AetherEngine.swift:6906) - Should fix:
selectTitleon a custom disc source (an ISO over SMB, the very DVD case this targets) goes throughreloadWithAudioOverride. There,preservedInverseTelecinecarries the outgoing title's decision onto a different title. The deinterlace warmup a few lines below is explicitly re-derived whentitleToReopen != outgoingDiscTitleID. With this PR, a video-shot extra after a film title would lose one frame in five. (Sources/AetherEngine/AetherEngine+Loading.swift:2689) - Should fix (docs):
docs/api.md› "What the call returns" (around line 422) still sayssessionOwnedholds "the fields the session owns". It should now also say that a correction ofinverseTelecinecomes back insessionOwnedwithrebuiltfalse, is not installed into the session, and only applies when a laterload()passes it. At present this contract appears only in a bullet informats.md.
Checklist: CHANGELOG yes, docs yes (one gap above), tests yes (none for the title switch or the background-resume correction), traits both ways n.a.
Needs a device run: these need checking on an Apple TV:
- The 23.976 Hz mode switch and the frame pacing of the decimated output.
- CPU headroom of
fieldmatchwith comb scores on tvOS. - Hybrid soft/hard-telecine discs. Repeat-field frames later in the file land right at the 1.5-frame gap threshold in
breaksInverseTelecineCadence, which could rebuild the graph every few frames.
Thank you for a carefully measured and well-documented contribution.
Automated review by Quint (Claude) of 18bfb0e. It reads the code, it does not build or run it; a maintainer reviews and merges.
| // here. `changed.isEmpty` is NOT this case and keeps rebuilding: a correction that changed | ||
| // nothing is a documented way to ask for the rebuild itself. | ||
| if applied.isEmpty, !sessionOwned.isEmpty { | ||
| if applied.isEmpty, !sessionOwned.isEmpty || !loadDecided.isEmpty { |
There was a problem hiding this comment.
This early return now runs on the background-teardown resume too. partitionChanges pulls inverseTelecine into loadDecided even when sessionOwnsTransport is false. Scenario: the app returns to the foreground with needsForegroundVideoRestore == true, and the host restores with reloadAtCurrentPosition { $0.inverseTelecine = .off }. applied is empty and loadDecided is not, so the call returns rebuilt: false and the torn-down session is never rebuilt. The comment above (lines 215-223) relies on that resume never reaching this branch. Suggested fix: take the no-rebuild exit only when backgroundTeardownSelection == nil, for example if applied.isEmpty, backgroundTeardownSelection == nil || !sessionOwned.isEmpty, ..., or simply require sessionOwnsTransport for the loadDecided-only case. The resume rebuild then still reports inverseTelecine as not applied. A test next to the existing partitionChanges one should pin this.
| options.subtitleSessionCarryover = carryover | ||
| // #853: the rebuilt session keeps the inverse telecine decision (and with it the display rate) | ||
| // instead of sampling again. | ||
| options.inverseTelecineCarryover = selection.inverseTelecine |
There was a problem hiding this comment.
load() stores these options as loadedOptions (line 5019). Unlike subtitleSessionCarryover, which is cleared at line 5043 so that a later reload cannot replay a stale snapshot (#170), inverseTelecineCarryover stays there. Every later load built from loadedOptions then skips the gate and the sample. One case is selectTitle on a URL disc (line 8886), which re-runs the display handshake for a different title. The other is rerouteRemoteHLSOntoLiveIngest. Scenario: a film title, one reloadAtCurrentPosition(), then selectTitle to a video-shot extra. The extra runs inverse telecine at 23.976 without being sampled. Suggested fix: add loadedOptions.inverseTelecineCarryover = nil next to line 5043.
| restoredDeinterlaceWarmupDecision ?? lastRequiresDeinterlaceWarmup | ||
| // #853: the session's inverse telecine decision. This rebuild keeps the display mode, so it keeps | ||
| // the decision that chose it too; it never samples again. | ||
| let preservedInverseTelecine = restoredInverseTelecine ?? lastInverseTelecine |
There was a problem hiding this comment.
On a custom-source title switch (selectTitle calls reloadWithAudioOverride(discTitleIDOverride:) with no restoredInverseTelecine), this falls back to lastInverseTelecine, so the new title inherits the outgoing title's decision. The warmup decision at line 2845 deliberately drops saved evidence when titleToReopen != outgoingDiscTitleID ("only a different title invalidates the saved probe evidence"). A DVD ISO read through an IOReader is the main target of this feature. Switching from the main film to a video-shot extra would run decimate on true video and drop one frame in five. Suggested fix: apply the same rule. For a different title, either sample customPreopened (the gate and TelecineCadenceProbe.run only need the demuxer and stream) or fall back to false.
48fa628
into
superuser404notfound:main
… title switch (#1105 review) Quint's review of PR #1105 found three paths where the session-kept decision went wrong: - A restore after a background teardown that only corrected inverseTelecine returned without a rebuild, so no picture came back. A load-decided field now skips the rebuild only while a session is up. - inverseTelecineCarryover stayed in loadedOptions after the load that used it, so a later selectTitle or ingest reroute inherited the old title's decision and display rate. Cleared like subtitleSessionCarryover. - A custom-source title switch carried the outgoing title's decision onto the new title. A different title now falls back to the deinterlacer. Docs: api.md says how a correction of inverseTelecine comes back, formats.md what a title switch does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SeT6NgMt1vv32kPBhUmsUz
…efore the rate (#1105 review) From the /code-review of the merge: - A custom-source disc title switch dropped inverse telecine outright, which deinterlaced the next episode of a film-shot series on a 23.976 Hz panel. The new title is now sampled like a fresh load. - The cadence-gap threshold sat exactly on a repeat-field frame (1.5 frames, 4504 or 4505 ticks at 90 kHz), so soft-telecined stretches rebuilt the graph on every other frame. Now 1.75; one missing frame is 2. - An audioOnly load ran the sample for a decision nothing reads. - A correction of inverseTelecine without a rebuild never reached loadedOptions, so a later title switch ignored it. - The decision (and with it the display rate) is made only when the graph can run: fieldmatch and decimate linked and a stated stream rate. - .force's doc named H.264 as covered; the gate excludes codecs with a native route. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SeT6NgMt1vv32kPBhUmsUz
|
Merged, thank you. This is a lot of careful work, and the measurements in the PR made it easy to review. The cadence check on the worst 16x16 block, the one that tells motion-interpolated video apart from film, is a nice find. I merged main in first (no conflicts) and added two follow-up commits on top. 6e2764c, from Quint's review
3820c49, from my own review
Tests for each of these are in Still open, nothing for you to do unless you want to:
It ships with the next engine release. I'll test it on my Apple TV with a few NTSC discs once it's in a build. |
|
@superuser404notfound thank you for the quick merge and fixes. It would be nice to revisit it and improve it further for video and film mixed content using VRR if and when it's going to be available on tvOS. |
|
Agreed. Mixed content is where a fixed 23.976 or 29.97 mode always loses something. tvOS has no VRR output today, so the engine can only pick one display rate per title. If Apple adds it, this is the first place I'd look again. Independent of VRR, the next step on my side is letting repeat-field frames bypass |
Summary
Hard-telecined NTSC film (24p film put on 29.97i MPEG-2 with the 3:2 pulldown baked into the pictures, the usual DVD of a film-shot series) now plays as its original film frames at 23.976 fps instead of being deinterlaced. A short sample at load time decides. Anything short of a clear film verdict keeps today's deinterlacer, so true interlaced video plays as before.
Closes #853
What changed
TelecineCadenceProbe,AetherEngine+InverseTelecine.swift). Before the display criteria are written, a load that passes the gate decodes from its start position throughfieldmatch+idetand looks for the repeated frame of each five at a steady phase. On film the session runs inverse telecine and asks the display for 23.976 Hz. The probe demuxer is rewound to the head afterwards, as the Field-order routing sends progressive-in-interlaced-carriage (PsF) H.264 to software for no visual benefit — #220 reprices the stated cost #232 probe does.DeinterlaceFilter). Software:fieldmatch,bwdif,decimate. GPU:fieldmatch,decimateon the CPU, then the upload and the VideoToolbox deinterlacer. Both deinterlace only the framesfieldmatchcould not match (deint=interlaced, at frame rate): titles and credits made at video rate. An inverse telecine graph declares the stream's frame rate on its buffer source, whichdecimateneeds.decimatestamps its output from the graph's first frame plus one tick per frame. A seek rebuilds the graph already. The decoder now also drains and rebuilds it on a timestamp gap (a missing frame or a step back), so the pictures never drift against the audio.reloadAtCurrentPosition(URL and custom sources) and the return from background reuse the first load's decision. The display rate never moves mid-session, and the sample is paid once. A change ofinverseTelecinethroughreloadAtCurrentPosition(applying:)is reported as not applied, next to the session-owned fields, and takes effect at the next load.InverseTelecineMode(.autoby default,.off,.force),LoadOptions.inverseTelecine,VideoDeinterlace.inverseTelecineandVideoDeinterlace.outputFrameRateFactor(0.8 under inverse telecine, for a host that shows the output rate). A host needs no change to play it.play --inverse-telecine auto|off|force, andscrubpreview --inverse-telecinefor stills.formats.md(new "Inverse telecine"),measurements.md(new "Inverse telecine (Inverse telecine (IVTC) for hard-telecined content #853)"),api.md,architecture-software.md,features.md,cli.md,source-map.md.CHANGELOG.mdunder Added.InverseTelecineChainTests: the graph returns film frames once each at 23.976, releases its partial cycle at EOF, re-anchors after a seek and after a gap; forced video neither stalls nor fails; the GPU chain.TelecineCadenceAnalyzerTests: the decision on synthetic sample streams (openings, fades, edits, still video, interpolated video, both early exits).TelecineCadenceProbeTests: the gate, the sampler on exact frames, the whole probe on MPEG-2 clips, the budgets, the start position.InverseTelecineLoadDecisionTests: load, rebuilds,.off,.force, progressive, the option correction.DocumentedConstantsTestspin for the numbers informats.md.The points from the issue thread
FFmpegBuild. Nothing to add. This builds on main with FFmpegBuild 3.17.0, and
Package.resolvedis unchanged. A build withoutfieldmatch/decimate, or a stream that states no frame rate, logsinverse telecine unavailable (...)once and deinterlaces as before.Probe budget. One window at the start position, bounded like
InterlaceProbe: 300 frames, 3000 packets or 2 s of wall clock, the seek included. Expiry is inconclusive and keeps today's deinterlacer. Two changes from the ~120-frame plan, both measured:idetalone does not separate film from video at the head of an episode. The first 120 frames read 67-71% progressive (a second of black, then a fade made at field rate). True video reads 18-100% progressive, because its still stretches match trivially. A second signal separates them: the repeated frame of each five at a steady phase, judged by the worst 16x16 block. Judged by the frame mean, motion-interpolated video kept a five-frame rhythm and read as film in 10 of 13 samples.EOF. Main already drains the deinterlace graph at end of stream (126cbb8, DEC-203). This PR pins it for
decimate: 7 frames in, 6 out, the partial cycle released without a drop. The same drain runs mid-stream on a timestamp gap, before the graph is rebuilt.Seek and scrub stills, the IVTC chain against the plain deinterlacer (S01E05, release
aetherctl, M1 Pro):[AudioOutput] preroll ready after N ms) took 69-77 ms median with inverse telecine and 43-45 ms without. The graph rebuilds in about 1 ms either way.decimateneeds about five frames before its first picture.scrubpreview --stills, five positions): 2-10 ms each, with and without, because stills keep the plain deinterlacer.Scope, as agreed.
.autosamples only VOD, seekable, 29.97 / 30 fps MPEG-2 of 576 lines or fewer whose frames decode interlaced. Live, HD, PAL 2:2 (a follow-up) and other codecs keep the deinterlacer. Soft telecine already decodes to film frames and is left alone..forceskips the sample on any NTSC-rate interlaced source of a codec that always decodes in software (VC-1, HD MPEG-2). No field-rate output while inverse telecine runs: the output is 23.976 fps whateverdeinterlaceFieldRatesays. The decision line is logged before the[AetherEngine] loadline, whoserate=is the rate asked of the display. Releaseaetherctlon a Friends episode, a motion-interpolated Friends scene and a PAL clip:The second one is why
idetalone is not enough: true video can read mostly progressive, and only the cadence (0%) tells it apart.Fixtures. Three 96x64 MPEG-2 clips (film through
telecine, true interlaced video throughtinterlace, progressive), made offline with the FFmpeg 9.0.2 CLI. They are embedded as base64 inTests/AetherEngineTests/Support/TelecineCadenceFixtures.swift, like the other media tests, with the commands and SHA-256 in the comments. Nothing GPL is needed at build or test time.Measurements
Method and the full tables:
docs/measurements.md, "Inverse telecine (#853)".Detection, final thresholds:
testsrc2)Time to first frame over
Scripts/slowrange.py(S01E05,FIRSTFRAMEofaetherctl play, median of 3 runs, the sample with its rewind in brackets):Playback. The output runs at 24 frames a second (
--frame-timesreadsft=24, the[SWDiag]linesdpts=41.7/41.7), with no frame lost in a CLI run. CPU per SD frame on one M1 Pro core (FFmpeg CLI, decode included): 4.5 ms, against 0.46 ms forbwdifalone. That is about 14% of one core at 29.97 frames in.Test plan
swift test, releaseaetherctl.interlaced_frame=1andrepeat_pict=0; AC-3 5.0 and 2.0; SDR.minterpolate), or a pan, a zoom and a still shot with one moving box at a true 60 Hz, interleaved to 29.97i (tinterlace) and coded as MPEG-2 again. Plus synthetictestsrc2at 59.94 fields and a synthetic PAL 25i clip.swift test, default traits: XCTest 856 tests, 1 skipped, 0 failures. Swift Testing 6,558 tests in 882 suites with 1 issue:SubtitleCaptionStyleTests, "the default style renders the same overlay as before styles existed" (a golden pixel count). It fails the same way on a clean checkout of main on this Mac.swift test --enable-all-traits: XCTest 861 tests, 1 skipped, 0 failures. Swift Testing 7,055 tests in 931 suites with 2 issues: the same subtitle golden, andItemSwapStillTests, "a playing native item hands over the frame on screen", once. That one is a native-route test this PR does not touch (the gate skips native codecs before any work), and its comments note it is sensitive to a starved runner. It passed 3 of 3 reruns.xcodebuild build-for-testing -scheme AetherEngineTestspasses.check-test-hygiene.py,check-doc-links.pyandcheck-source-map.pypass.Checklist
CHANGELOG.mdupdatedfeat(...),fix(...),chore(...))InverseTelecineMode,LoadOptions.inverseTelecine,VideoDeinterlace.inverseTelecine,VideoDeinterlace.outputFrameRateFactor, all indocs/api.md)🤖 Generated with Claude Code