avcodec/pgssubdec: emit an empty subtitle when the palette is missing #23851
No reviewers
Labels
No labels
avcodec
avdevice
avfilter
avformat
avutil
backport/release/4.3
backport/release/4.4
backport/release/5.0
backport/release/5.1
backport/release/6.0
backport/release/6.1
backport/release/7.0
backport/release/7.1
backport/release/8.0
backport/release/8.1
backport/release/9.0
backport/release/9.1
CLI
doc
Forgejo Fairy
swresample
swscale
vulkan
API
API major
bug
enhancement
fix/bug
fix/regression
GSoC
GSoC-Qualification
help wanted
important
LGTM
meta
needs backport
needs docs
needs fate test
needs info
needs sample
needs testing
new
question
regression
repro
flaky
repro
no
repro
no(env)
repro
yes
resolution
duplicate
resolution
external
resolution
fixed
resolution
invalid
resolution
wontfix
security
small
No milestone
No assignees
3 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
FFmpeg/FFmpeg!23851
Loading…
Reference in a new issue
No description provided.
Delete branch "superuser404/FFmpeg:pgssub-epoch-continue"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
display_end_segment()drops the whole display set when the palette the presentation references is not in the cache. PGS carries no end time, a cue is closed by the start of its successor, so dropping the set also removes the successor that would have closed the cue before it: the previous subtitle stays on screen past its authored end, until the next intact display set arrives.Outside
AV_EF_EXPLODEthis returns the empty subtitle instead.sub->ptsis already set at that point and no rectangle has been allocated yet, so freeing the rectangle array leaves exactly the clearing form theobject_count == 0path a few lines above returns. The damaged set renders nothing, which is all it conveys, but it closes its predecessor at the authored time. The missing object path below already follows this policy outsideAV_EF_EXPLODE.What changed since the first version
This started as a change to
parse_presentation_segment()that kept the palette and object caches across composition state 3. Both reviews retired that approach, and I agree with them:object[]array, so a self-contained connection set conveying a new object id is rejected withToo many objects in epoch, a set the unpatched decoder renders. The count based rejection inparse_object_segment()makes that unavoidable for any variant of the retention approach.What is left is the error resilience defect alone, and it is now handled where it happens instead of by keeping stale resources alive.
Reproducer
The generator below writes a minimal .sup: display set 1 (epoch start) defines a palette and an 8x8 object and presents it, display set 2 at 3s is a bare PCS + WDS + END referencing data it does not convey.
Before, on
6bbc22dc09:After:
The diagnostic stays, the stream is still damaged. What changes is that the cue starting at 1s is now closed at 3s instead of remaining on screen. With
-err_detect explodethe set is still rejected, unchanged from before. A conformant stream whose second display set conveys its own palette and object decodes identically with and without the patch (two cues, one rectangle each), which follows from the change sitting inside the!palettebranch.gen_pgs_epoch_continue.py
The fixture is a synthetic hostile stream, not a wild sample, and the report against my player that motivated this was explicit about that. The missing palette branch is reachable from any truncated or partially received display set, though, not only from an epoch continue, so the recovery is not tied to that fixture.
FATE
The review asked for decode side coverage, which the existing remux oriented PGS entries do not provide. I am happy to submit this fixture to samples-request and add a
tests/ref/entry if the shape above is acceptable.Note: this no longer touches the hunk that #21109 reworks, so the sequencing concern from the earlier version is gone.
This is not true. Epoch continue allows for graphics to be displayed contiguously to the one in display at a seamless connection of two AV clips. A player decoding only the second AV clip is initialized by the epoch continue display set, and every subsequent display sets in that epoch must not refer to data conveyed in the first AV clip. The "continue" aspect merely relates to the absence of a display disruption caused by the epoch start process, where every plane is forcefully blanked.
The epoch continue process is thoroughly explained in US patent 8369682.
1fa66ef5023cb4542fb8You are right about the model, and the rationale I wrote is not: the epoch continue display set exists so that a player entering playback at the connection of two seamlessly joined clips can be initialized from it, later display sets in the epoch may only reference data conveyed from that display set on, and the "continue" only buys the absence of the epoch start display reset. I have reworded the commit message, the code comment, and the description to that model (force-pushed, no code change).
A provenance correction on my side as well: I went back to the report against my player that motivated this, and the stream there was a deliberately synthetic, hostile fixture, not verified wild BD authoring. The description no longer claims in-the-wild sightings.
What remains is an error resilience argument, which the corrected model leaves intact: for a conformant stream, flushing at the continue PCS and keeping the cache produce identical output, since the display set re-conveys the palettes and objects it references (they overwrite the cached entries by id before the END segment resolves anything) and later display sets only reference data conveyed since the connection, which is cached either way. The two behaviors differ only on a non-conformant bare PCS + WDS + END continue set that relies on retained state: today the whole set is dropped with "Invalid palette id" and, since pgssub end times are closed by the successor cue, the previous subtitle overstays its authored end; with retention the decoder rides over the damage. If that robustness is not considered worth carrying without a confirmed wild sample, I am fine withdrawing this.
This creates an asymmetry with the Acquisition Point implementation, where prior data can remain in the decoder, depending of the vendor implementation that is.
Then I suggest to assert the palette index whenever the composition list of a PCS is not empty, and to proceed regardless if there are no composition objects. In that situation the decoder returns zero rectangle: it does not have to attach any palette.
LLM-GPT-5.6-SOL — combined review of 3cb4542fb86b.
Scope GPT-5.6-SOL code review: exhaustive review of the sole changed hunk, palette/object insertion and lookup, display-END handling, the complete discussion, #21109, a decoder build, and an exercised 64-object boundary fixture.
Scope GPT-5.6-SOL design review: exhaustive review of the sole commit and surrounding resource lifecycle, the complete discussion and #21109, a decoder build, comparison with independent implementations, and tests of the supplied malformed-stream reproducer against the parent and PR behavior.
Scope GLM-5.2 code review: review of the single commit with empirical tests of the supplied reproducer, a self-contained epoch-continue display set, the existing
sub/pgs_sub.supsample, and the cache’s memory-safety bounds.Scope combiner: I inspected the combined diff, current merged source, full #23851 discussion, #21109, the palette/object/display paths, the origin of the 64-object bound in
253d0be6a1, and existing PGS FATE coverage; I also built ffprobe and independently compared 3cb4542fb86b with the original state-3 flush using the reported 9,310-byte capacity-boundary stream.Blocking correctness regression
[GPT-5.6-SOL code review] Retained pre-connection objects consume all slots needed by a self-contained epoch-continue display set.
The new condition in
parse_presentation_segment()at 3cb4542fb86b preservesctx->objects.countacross state 3. New object IDs are inserted into the same fixedobject[MAX_EPOCH_OBJECTS]array, andparse_object_segment()rejects a previously unseen ID oncecount == 64. The limit was introduced by 253d0be6a1ec as support for “up to 64 currently valid objects”; the 16-bit object ID is not an index into a 64-value namespace.This invalidates the commit message’s general claim that retaining the cache is output-neutral for conformant/self-contained connections. That claim only holds when all data conveyed after the connection reuses IDs already present in the retained cache. A connection is also allowed, under the model agreed in this discussion, to initialize itself with newly conveyed data that no longer depends on the preceding clip.
I independently reproduced the code-review draft’s boundary result with a 9,310-byte SUP containing:
AV_EF_EXPLODE, so failure to retain the newly conveyed object is observable as a decoding failure rather than an empty rectangle.The decoder built successfully. With 3cb4542fb86b, ffprobe emitted 32 frames and diagnosed both
Too many objects in epochandInvalid object id 64. Restoring the original state-3 flush emitted all 33 frames without a decoder diagnostic. The data before the connection uses exactly the decoder’s 64-object limit, while the independently initialized connection uses one object; the rejection is caused solely by stale pre-connection entries retained by this patch. WithoutAV_EF_EXPLODE, the newly conveyed subtitle still cannot be rendered and becomes an empty rectangle, so the problem is not limited to strict error-recognition mode.Please either retain the state-3 flush or redesign the recovery storage so that pre-connection fallback resources cannot consume the new generation’s 64 current-object slots. A generation-aware design would also need bounded eviction: merely enlarging the array allows distinct IDs to accumulate over repeated continuation points.
If the narrower goal is to prevent a preceding subtitle from overstaying when a malformed, non-empty successor lacks its palette, that can be handled without treating pre-connection resources as current resources. At the existing missing-palette branch, before any individual rectangle has been allocated, the non-explode path can preserve the new subtitle PTS and return the same zero-rectangle clearing form already supported by the
object_count == 0path:I reviewed this suggested recovery in the current merged source:
sub->num_rectsis still zero at that point, freeing the allocated pointer array is sufficient, and returning 1 preserves the PTS-bearing empty subtitle. It deliberately closes the predecessor rather than inventing a rendering from resources that the malformed connection did not convey. The existing missing-object path already follows an analogous non-explode policy by returning an empty rectangle.Reconciliation of the other drafts and discussion
The GPT-5.6-SOL design review and GLM-5.2 correctly verified the supplied malformed fixture and a self-contained continuation that reused matching IDs. GLM-5.2 also reported identical output for the existing
sub/pgs_sub.supsample. Those checks remain useful, but none exercises a self-contained connection that introduces a new ID after a full preceding cache, so they do not establish output-neutrality generally. GLM-5.2’s statement that the fixed-array checks prevent memory corruption is also correct; the blocking issue is an avoidable output regression, not memory safety.The independent implementation comparisons are relevant design precedent: libbluray’s graphics processor reportedly clears its resource caches only on epoch start, while MPC-BE’s PGS decoder reportedly does not use the composition-state byte for eviction. They are not normative authorities, however, and do not establish that FFmpeg can safely retain an old generation in its existing fixed 64-entry array.
The policy question identified by GLM-5.2 also remains relevant but is no longer the only reason to wait: this PR is an error-resilience workaround for a deliberately malformed synthetic stream, not a conformance bugfix. Maintainers may reasonably choose either best-effort rendering or a clearing subtitle for that malformed input, but any such workaround must not reject an independently initialized connection that the original decoder handles. The asymmetry with acquisition-point handling raised by cubicibo should be resolved as part of that choice.
The latest discussion’s zero-object case is already handled:
display_end_segment()returns 1 before looking up a palette whenobject_count == 0, so an empty PCS closes the preceding cue. This PR’s motivating PCS is non-empty and therefore is not addressed by that existing path.Unverified conditional point from the GPT-5.6-SOL code review: palettes have the analogous storage shape: an eight-entry cache, an ID lookup, and rejection of a new ID when all retained entries are occupied. If palette IDs are arbitrary eight-bit identifiers with a limit of eight simultaneously valid palettes, eight stale IDs followed by a distinct connection palette would reproduce the same regression. I did not find an accessible normative source proving either that palette IDs are restricted to 0–7 or that they are not, so this is not part of the verdict. A normative reference establishing the palette-ID namespace would resolve it.
Regression coverage
[GPT-5.6-SOL code review, GPT-5.6-SOL design review, GLM-5.2] Please add decode-side FATE coverage with the revised recovery. The existing PGS entries are remux-oriented and do not cover this decoder lifecycle. The 9,310-byte capacity fixture is below 10 KiB and directly protects against this regression; the much smaller malformed fixture can separately protect whichever error-resilience policy maintainers select. A sample can be submitted to
samples-requestatffmpegdotorg, and the expected decoded result should be stored undertests/ref/. The overlapping condition in #21109 remains a sequencing/rebase concern, but it does not affect this finding.Classification justification
This is major_issues because 3cb4542fb86b introduces a confirmed, avoidable output regression: a fully self-contained connection that decodes with the original cache flush can lose its newly conveyed object solely because this patch lets obsolete entries occupy all current-object slots. That would make the decoder worse if merged and therefore meets the supplied classification rule that an avoidable regression is major; it also conflicts with the FFmpeg Development Policy requirement not to commit code that breaks FFmpeg. The absent FATE test and malformed-input policy choice are worthwhile follow-ups, but the verdict rests on the reproduced capacity regression.
3cb4542fb89e5ebcc34favcodec/pgssubdec: keep cached palettes and objects on epoch continueto avcodec/pgssubdec: emit an empty subtitle when the palette is missingBoth points land, and this is a different patch now.
The reproduced regression is confirmed on my side as well:
MAX_EPOCH_OBJECTSbounds a count, andparse_object_segment()rejects a previously unseen id onceobjects.counthas reached 64, so retained pre-connection entries can occupy every slot a self-contained connection needs. That is not repairable by a variant of the retention approach without generation aware storage and bounded eviction, which is far more machinery than the error resilience issue justifies. The palette namespace question flagged as unverified becomes moot with retention gone.@cubicibo, the asymmetry with acquisition point handling is gone with it. What remains for a non-empty composition whose palette was not conveyed is the zero rectangle outcome you described, not a rendering assembled from retained resources.
9e5ebcc34ftherefore drops the composition state 3 change entirely and applies the suggested recovery at the missing palette branch instead: outsideAV_EF_EXPLODE, free the not yet populated rectangle array and return the empty subtitle, which keeps the PTS and closes the predecessor. Verified against6bbc22dc09with the same reproducer:The diagnostic stays and the damaged set renders nothing; it only stops the predecessor from outliving it. With
-err_detect explodethe set is still rejected exactly as before. A conformant stream whose second display set conveys its own palette and object is unaffected, which follows from the change sitting inside the!palettebranch.The description is rewritten to match. Open item is the decode side FATE coverage: I can submit the fixture to samples-request and add a
tests/ref/entry if this direction is acceptable.LLM-GPT-5.6-SOL — combined follow-up review of
9e5ebcc34f.The revised patch can be approved. The previously reported cache-capacity regression does not apply to this version:
9e5ebcc34fno longer changesparse_presentation_segment()or cache lifetime, so pre-connection resources cannot consume the current epoch’s fixed object slots. The only change is now the missing-palette recovery indisplay_end_segment().The new ownership and handoff are sound. At the branch, only the zeroed rectangle-pointer array has been allocated and
sub->num_rectsremains zero.av_freep(&sub->rects)therefore releases the complete allocation while retaining the initialized PTS and timing fields. Returning 1 setsgot_sub_ptr, exposing the same zero-rectangle clearing shape as the existingobject_count == 0path. UnderAV_EF_EXPLODE,avsubtitle_free()andAVERROR_INVALIDDATAretain the previous rejection behavior, including the cleanup performed byavcodec_decode_subtitle2().This should be described as an FFmpeg error-resilience fix for damaged or truncated PGS display sets, not a conformance fix for valid PGS and not a workaround for another project. Its benefit is concrete: the damaged replacement still renders no pixels, but its timestamp closes the preceding cue instead of allowing that cue to overstay; strict error recognition continues rejecting the damaged set.
My arm64 build completed, and the supplied fixture produced
(1.000000, 1 rectangle)followed by(3.000000, 0 rectangles)in normal mode. With-err_detect explode, only the first subtitle was emitted and the missing-palette diagnostic remained. GPT-5.6-SOL’s design review additionally reports identical parent/head output for a conformant self-contained continuation and clean valgrind runs. GLM-5.3 reports identical output forsub/pgs_sub.sup, clean valgrind results on 134 truncated/corrupted variants, and all existing PGS FATE entries passing.[GPT-5.6-SOL code review, GPT-5.6-SOL design review, GLM-5.3] Non-blocking regression coverage
The proposed 265-byte fixture is suitable for decode-side FATE coverage and does not need trimming. Please submit it to
samples-requestatffmpegdotorg, naming the intended fate-suite path and #23851. Aprobeframestest selectingsubtitle=pts_time,num_rectswould directly protect the decoder contract demonstrated above; GLM-5.3’s verified sub2video/framecrc alternative would instead protect the visible clearing behavior. In either case, actual output should be compared with a reference undertests/ref/fate/, rather than hard-coding expected values in test code. The default recovery case is the essential regression test; a separateAV_EF_EXPLODEcase is optional because that behavior is unchanged.Classification justification
This is minor_issues_approve: the former avoidable regression has been removed, the remaining implementation is narrowly confined to damaged-input recovery, ownership and strict-error behavior are correct, and the only outstanding request is non-blocking regression coverage. That matches the supplied rule that minor or follow-up issues do not prevent approval. It is also consistent with FFmpeg’s policy that detected malformed-input handling is an implementation choice and should seek useful output, and with the checklist—which says to consider regression coverage while specifically requiring it for new modules, which this patch does not add (Development Policy, Patch submission checklist).
Thanks for the follow-up review.
The sample is on its way to samples-request as
sub/pgs_missing_palette.sup(265 bytes, sha25642ec9d5902dc6c40bd55609478cd9b5cbcea1906781e7b215e83078d361174a6), with the generator inline and #23851 named as the reason. I will push the test here once it appears in the suite, since a FATE entry pointing at a sample that is not there yet fails for everyone else.The test itself is written and measured.
subtitles.makhad no ffprobe entry so far, so this gets its own variable wired intoFATE_SAMPLES_FFPROBErather than intoFATE_SUBTITLES, which is bound to the ffmpeg binary and additionally filtered byCONFIG_PIPE_PROTOCOL:with
tests/ref/fate/sub-pgs-missing-palette:fate-sub-%: CMP = rawdiffapplies through the name, which suits the text output.It separates the two behaviors rather than only recording the current one. With
libavcodec/pgssubdec.creset to the parent and ffprobe rebuilt, the test fails on exactly the section the recovery adds:fate-sub-pgs-remux,fate-matroska-pgs-remuxandfate-matroska-pgs-remux-durationspass unchanged alongside it. I left theAV_EF_EXPLODEcase out as suggested, that path is not touched by the patch.View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.