avcodec/pgssubdec: emit an empty subtitle when the palette is missing #23851

Open
superuser404 wants to merge 1 commit from superuser404/FFmpeg:pgssub-epoch-continue into master
Contributor

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_EXPLODE this returns the empty subtitle instead. sub->pts is already set at that point and no rectangle has been allocated yet, so freeing the rectangle array leaves exactly the clearing form the object_count == 0 path 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 outside AV_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:

  • @cubicibo corrected the epoch continue model (a continue display set initializes a player entering at a seamless connection, so it re-conveys what it references) and pointed out the asymmetry that retention would create with acquisition point handling.
  • the review of 3cb4542fb8 then reproduced a regression I had missed: retained pre-connection objects occupy the fixed 64 entry object[] array, so a self-contained connection set conveying a new object id is rejected with Too many objects in epoch, a set the unpatched decoder renders. The count based rejection in parse_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:

$ ffprobe -hide_banner -show_frames -show_entries subtitle=pts_time,num_rects epoch_continue.sup
[SUBTITLE]
pts_time=1.000000
num_rects=1
[/SUBTITLE]
[pgssub @ ...] Invalid palette id 0

After:

[SUBTITLE]
pts_time=1.000000
num_rects=1
[/SUBTITLE]
[pgssub @ ...] Invalid palette id 0
[SUBTITLE]
pts_time=3.000000
num_rects=0
[/SUBTITLE]

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 explode the 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 !palette branch.

gen_pgs_epoch_continue.py
#!/usr/bin/env python3
import struct
import sys

def seg(pts_90k, seg_type, payload):
    return b"PG" + struct.pack(">IIBH", pts_90k, 0, seg_type, len(payload)) + payload

def pcs(comp_num, state, num_objs):
    p = struct.pack(">HHBHBBBB", 720, 480, 0x10, comp_num, state, 0x00, 0, num_objs)
    if num_objs:
        p += struct.pack(">HBBHH", 0, 0, 0x00, 100, 100)  # obj 0 in window 0 at (100,100)
    return p

def wds():
    return struct.pack(">BBHHHH", 1, 0, 100, 100, 8, 8)

def pds():
    entries = struct.pack(">BBBBB", 0, 0x00, 0x80, 0x80, 0x00)   # entry 0: transparent
    entries += struct.pack(">BBBBB", 1, 0xEB, 0x80, 0x80, 0xFF)  # entry 1: opaque white
    return struct.pack(">BB", 0, 0) + entries

def ods():
    rle = (b"\x01" * 8 + b"\x00\x00") * 8  # 8x8 solid color 1, one run per line
    data_len = 4 + len(rle)                # width + height fields + RLE payload
    return struct.pack(">HBB", 0, 0, 0xC0) + data_len.to_bytes(3, "big") + \
           struct.pack(">HH", 8, 8) + rle

out = b""
t1 = 90000   # display set 1: epoch start at 1s
out += seg(t1, 0x16, pcs(0, 0x80, 1))
out += seg(t1, 0x17, wds())
out += seg(t1, 0x14, pds())
out += seg(t1, 0x15, ods())
out += seg(t1, 0x80, b"")
t2 = 270000  # display set 2: epoch continue at 3s, bare PCS+WDS+END
out += seg(t2, 0x16, pcs(1, 0xC0, 1))
out += seg(t2, 0x17, wds())
out += seg(t2, 0x80, b"")

with open(sys.argv[1] if len(sys.argv) > 1 else "epoch_continue.sup", "wb") as f:
    f.write(out)

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.

`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_EXPLODE` this returns the empty subtitle instead. `sub->pts` is already set at that point and no rectangle has been allocated yet, so freeing the rectangle array leaves exactly the clearing form the `object_count == 0` path 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 outside `AV_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: - @cubicibo corrected the epoch continue model (a continue display set initializes a player entering at a seamless connection, so it re-conveys what it references) and pointed out the asymmetry that retention would create with acquisition point handling. - the review of 3cb4542fb8 then reproduced a regression I had missed: retained pre-connection objects occupy the fixed 64 entry `object[]` array, so a self-contained connection set conveying a new object id is rejected with `Too many objects in epoch`, a set the unpatched decoder renders. The count based rejection in `parse_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: ``` $ ffprobe -hide_banner -show_frames -show_entries subtitle=pts_time,num_rects epoch_continue.sup [SUBTITLE] pts_time=1.000000 num_rects=1 [/SUBTITLE] [pgssub @ ...] Invalid palette id 0 ``` After: ``` [SUBTITLE] pts_time=1.000000 num_rects=1 [/SUBTITLE] [pgssub @ ...] Invalid palette id 0 [SUBTITLE] pts_time=3.000000 num_rects=0 [/SUBTITLE] ``` 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 explode` the 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 `!palette` branch. <details> <summary>gen_pgs_epoch_continue.py</summary> ```python #!/usr/bin/env python3 import struct import sys def seg(pts_90k, seg_type, payload): return b"PG" + struct.pack(">IIBH", pts_90k, 0, seg_type, len(payload)) + payload def pcs(comp_num, state, num_objs): p = struct.pack(">HHBHBBBB", 720, 480, 0x10, comp_num, state, 0x00, 0, num_objs) if num_objs: p += struct.pack(">HBBHH", 0, 0, 0x00, 100, 100) # obj 0 in window 0 at (100,100) return p def wds(): return struct.pack(">BBHHHH", 1, 0, 100, 100, 8, 8) def pds(): entries = struct.pack(">BBBBB", 0, 0x00, 0x80, 0x80, 0x00) # entry 0: transparent entries += struct.pack(">BBBBB", 1, 0xEB, 0x80, 0x80, 0xFF) # entry 1: opaque white return struct.pack(">BB", 0, 0) + entries def ods(): rle = (b"\x01" * 8 + b"\x00\x00") * 8 # 8x8 solid color 1, one run per line data_len = 4 + len(rle) # width + height fields + RLE payload return struct.pack(">HBB", 0, 0, 0xC0) + data_len.to_bytes(3, "big") + \ struct.pack(">HH", 8, 8) + rle out = b"" t1 = 90000 # display set 1: epoch start at 1s out += seg(t1, 0x16, pcs(0, 0x80, 1)) out += seg(t1, 0x17, wds()) out += seg(t1, 0x14, pds()) out += seg(t1, 0x15, ods()) out += seg(t1, 0x80, b"") t2 = 270000 # display set 2: epoch continue at 3s, bare PCS+WDS+END out += seg(t2, 0x16, pcs(1, 0xC0, 1)) out += seg(t2, 0x17, wds()) out += seg(t2, 0x80, b"") with open(sys.argv[1] if len(sys.argv) > 1 else "epoch_continue.sup", "wb") as f: f.write(out) ``` </details> 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.
First-time contributor

Composition state 3 (epoch continue) however continues the previous epoch: when decoding linearly the retained palettes and objects stay valid [...]

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.

> Composition state 3 (epoch continue) however continues the previous epoch: **when decoding linearly the retained palettes and objects stay valid** [...] 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.
superuser404 force-pushed pgssub-epoch-continue from 1fa66ef502
Some checks failed
Backport / PR (pull_request_target) Has been skipped
Autolabel / Labeler (pull_request_target) Successful in 11s
Lint / Pre-Commit (pull_request) Has been cancelled
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Has been cancelled
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Has been cancelled
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Has been cancelled
Test / Fate (Full, wine) (pull_request) Has been cancelled
to 3cb4542fb8
All checks were successful
Backport / PR (pull_request_target) Has been skipped
Lint / Pre-Commit (pull_request) Successful in 27s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 8m15s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 12m28s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 17m31s
Test / Fate (Full, wine) (pull_request) Successful in 23m9s
Autolabel / Labeler (pull_request_target) Has been skipped
2026-07-21 09:30:28 +00:00
Compare
Author
Contributor

You 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.

You 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.
First-time contributor

This creates an asymmetry with the Acquisition Point implementation, where prior data can remain in the decoder, depending of the vendor implementation that is.

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

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.

This creates an asymmetry with the Acquisition Point implementation, where prior data can remain in the decoder, depending of the vendor implementation that is. > 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 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.
Member

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.sup sample, 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 preserves ctx->objects.count across state 3. New object IDs are inserted into the same fixed object[MAX_EPOCH_OBJECTS] array, and parse_object_segment() rejects a previously unseen ID once count == 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:

  • an epoch that conveys 64 valid objects with IDs 0–63 over 32 display sets, with at most two presentation objects in each set;
  • a state-3 connection display set that fully conveys its referenced palette and a valid 8×8 object with the new ID 64; and
  • 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 epoch and Invalid 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. Without AV_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 == 0 path:

if (avctx->err_recognition & AV_EF_EXPLODE) {
    avsubtitle_free(sub);
    return AVERROR_INVALIDDATA;
}
av_freep(&sub->rects);
return 1;

I reviewed this suggested recovery in the current merged source: sub->num_rects is 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.sup sample. 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 when object_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-request at ffmpeg dot org, and the expected decoded result should be stored under tests/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.

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.sup` sample, 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 253d0be6a1ec, 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](https://code.ffmpeg.org/FFmpeg/FFmpeg/src/commit/3cb4542fb86b7997352972aaf3c6a2f9fef58190/libavcodec/pgssubdec.c) preserves `ctx->objects.count` across state 3. New object IDs are inserted into the same fixed `object[MAX_EPOCH_OBJECTS]` array, and `parse_object_segment()` rejects a previously unseen ID once `count == 64`. The limit was introduced by [253d0be6a1ec](https://code.ffmpeg.org/FFmpeg/FFmpeg/commit/253d0be6a1ecc343d29ff8e1df0ddf961ab9c772) 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: - an epoch that conveys 64 valid objects with IDs 0–63 over 32 display sets, with at most two presentation objects in each set; - a state-3 connection display set that fully conveys its referenced palette and a valid 8×8 object with the new ID 64; and - `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 epoch` and `Invalid 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. Without `AV_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 == 0` path: if (avctx->err_recognition & AV_EF_EXPLODE) { avsubtitle_free(sub); return AVERROR_INVALIDDATA; } av_freep(&sub->rects); return 1; I reviewed this suggested recovery in the current merged source: `sub->num_rects` is 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.sup` sample. 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](https://code.videolan.org/videolan/libbluray/-/blob/master/src/libbluray/decoders/graphics_processor.c) reportedly clears its resource caches only on epoch start, while [MPC-BE’s PGS decoder](https://github.com/Aleksoid1978/MPC-BE/blob/master/src/Subtitles/HdmvSub.cpp) 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 when `object_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-request` at `ffmpeg` dot `org`, and the expected decoded result should be stored under `tests/ref/`. The overlapping condition in [#21109](https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/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](https://code.ffmpeg.org/FFmpeg/FFmpeg/src/branch/master/doc/developer.texi#L447-L453). The absent FATE test and malformed-input policy choice are worthwhile follow-ups, but the verdict rests on the reproduced capacity regression.
superuser404 force-pushed pgssub-epoch-continue from 3cb4542fb8
All checks were successful
Backport / PR (pull_request_target) Has been skipped
Lint / Pre-Commit (pull_request) Successful in 27s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 8m15s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 12m28s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 17m31s
Test / Fate (Full, wine) (pull_request) Successful in 23m9s
Autolabel / Labeler (pull_request_target) Has been skipped
to 9e5ebcc34f
All checks were successful
Lint / Pre-Commit (pull_request) Successful in 30s
Backport / PR (pull_request_target) Has been skipped
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 12m12s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 15m32s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 24m17s
Test / Fate (Full, wine) (pull_request) Successful in 29m30s
Autolabel / Labeler (pull_request_target) Successful in 12s
2026-08-10 07:04:35 +00:00
Compare
superuser404 changed title from avcodec/pgssubdec: keep cached palettes and objects on epoch continue to avcodec/pgssubdec: emit an empty subtitle when the palette is missing 2026-08-10 07:05:22 +00:00
Author
Contributor

Both points land, and this is a different patch now.

The reproduced regression is confirmed on my side as well: MAX_EPOCH_OBJECTS bounds a count, and parse_object_segment() rejects a previously unseen id once objects.count has 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.

9e5ebcc34f therefore drops the composition state 3 change entirely and applies the suggested recovery at the missing palette branch instead: outside AV_EF_EXPLODE, free the not yet populated rectangle array and return the empty subtitle, which keeps the PTS and closes the predecessor. Verified against 6bbc22dc09 with the same reproducer:

$ ffprobe -hide_banner -show_frames -show_entries subtitle=pts_time,num_rects epoch_continue.sup
[SUBTITLE]
pts_time=1.000000
num_rects=1
[/SUBTITLE]
[pgssub @ ...] Invalid palette id 0
[SUBTITLE]
pts_time=3.000000
num_rects=0
[/SUBTITLE]

The diagnostic stays and the damaged set renders nothing; it only stops the predecessor from outliving it. With -err_detect explode the 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 !palette branch.

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.

Both points land, and this is a different patch now. The reproduced regression is confirmed on my side as well: `MAX_EPOCH_OBJECTS` bounds a count, and `parse_object_segment()` rejects a previously unseen id once `objects.count` has 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. 9e5ebcc34f therefore drops the composition state 3 change entirely and applies the suggested recovery at the missing palette branch instead: outside `AV_EF_EXPLODE`, free the not yet populated rectangle array and return the empty subtitle, which keeps the PTS and closes the predecessor. Verified against 6bbc22dc09 with the same reproducer: ``` $ ffprobe -hide_banner -show_frames -show_entries subtitle=pts_time,num_rects epoch_continue.sup [SUBTITLE] pts_time=1.000000 num_rects=1 [/SUBTITLE] [pgssub @ ...] Invalid palette id 0 [SUBTITLE] pts_time=3.000000 num_rects=0 [/SUBTITLE] ``` The diagnostic stays and the damaged set renders nothing; it only stops the predecessor from outliving it. With `-err_detect explode` the 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 `!palette` branch. 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.
Forgejo_Fairy left a comment

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: 9e5ebcc34f no longer changes parse_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 in display_end_segment().

The new ownership and handoff are sound. At the branch, only the zeroed rectangle-pointer array has been allocated and sub->num_rects remains zero. av_freep(&sub->rects) therefore releases the complete allocation while retaining the initialized PTS and timing fields. Returning 1 sets got_sub_ptr, exposing the same zero-rectangle clearing shape as the existing object_count == 0 path. Under AV_EF_EXPLODE, avsubtitle_free() and AVERROR_INVALIDDATA retain the previous rejection behavior, including the cleanup performed by avcodec_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 for sub/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-request at ffmpeg dot org, naming the intended fate-suite path and #23851. A probeframes test selecting subtitle=pts_time,num_rects would 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 under tests/ref/fate/, rather than hard-coding expected values in test code. The default recovery case is the essential regression test; a separate AV_EF_EXPLODE case 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).

LLM-GPT-5.6-SOL — combined follow-up review of 9e5ebcc34f98. <!-- Scope GPT-5.6-SOL code review: Exhaustive review of the sole commit and changed hunk, the surrounding display-END runtime path, AVSubtitle ownership and decoder return semantics, all prior discussion, existing PGS FATE coverage, an arm64 build, the supplied malformed fixture, and sub/pgs_sub.sup. Scope GPT-5.6-SOL design review: Exhaustive review of every changed line, surrounding ownership and error paths, avcodec_decode_subtitle2() and avsubtitle_free(), the complete discussion and previous cache-capacity regression, PGS test coverage, malformed, strict-error, and conformant runtime cases, memory cleanup, portability, performance, and competing-decoder behavior. Scope GLM-5.3 code review: Exhaustive review of the single changed hunk, commit message, surrounding display_end_segment()/decode() paths, and avsubtitle_free() semantics; builds and before/after tests of the supplied and conformant fixtures and sub/pgs_sub.sup; valgrind runs on the new path and 134 corrupted variants; and all existing PGS FATE entries. Scope combiner: I inspected the sole commit, its parent, display_end_segment(), avsubtitle_free(), avcodec_decode_subtitle2(), the complete discussion, and current FATE structure and policy; I also built an arm64 ffprobe at the PR head and independently exercised the supplied 265-byte fixture in normal and AV_EF_EXPLODE modes. --> The revised patch can be approved. The previously reported cache-capacity regression does not apply to this version: 9e5ebcc34f98 no longer changes `parse_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 in [`display_end_segment()`](https://code.ffmpeg.org/FFmpeg/FFmpeg/src/commit/9e5ebcc34f9853d8f856db70423d8bb2fa120ecc/libavcodec/pgssubdec.c#L525-L542). The new ownership and handoff are sound. At the branch, only the zeroed rectangle-pointer array has been allocated and `sub->num_rects` remains zero. `av_freep(&sub->rects)` therefore releases the complete allocation while retaining the initialized PTS and timing fields. Returning 1 sets `got_sub_ptr`, exposing the same zero-rectangle clearing shape as the existing `object_count == 0` path. Under `AV_EF_EXPLODE`, `avsubtitle_free()` and `AVERROR_INVALIDDATA` retain the previous rejection behavior, including the cleanup performed by [`avcodec_decode_subtitle2()`](https://code.ffmpeg.org/FFmpeg/FFmpeg/src/commit/9e5ebcc34f9853d8f856db70423d8bb2fa120ecc/libavcodec/decode.c#L935-L997). 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 for `sub/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-request` at `ffmpeg` dot `org`, naming the intended fate-suite path and #23851. A `probeframes` test selecting `subtitle=pts_time,num_rects` would 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 under `tests/ref/fate/`, rather than hard-coding expected values in test code. The default recovery case is the essential regression test; a separate `AV_EF_EXPLODE` case 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](https://code.ffmpeg.org/FFmpeg/FFmpeg/src/branch/master/doc/developer.texi#L413-L423), [Patch submission checklist](https://code.ffmpeg.org/FFmpeg/FFmpeg/src/branch/master/doc/developer.texi#L962-L965)).
Author
Contributor

Thanks for the follow-up review.

The sample is on its way to samples-request as sub/pgs_missing_palette.sup (265 bytes, sha256 42ec9d5902dc6c40bd55609478cd9b5cbcea1906781e7b215e83078d361174a6), 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.mak had no ffprobe entry so far, so this gets its own variable wired into FATE_SAMPLES_FFPROBE rather than into FATE_SUBTITLES, which is bound to the ffmpeg binary and additionally filtered by CONFIG_PIPE_PROTOCOL:

fate-sub-pgs-missing-palette: CMD = probeframes -show_entries subtitle=pts_time,num_rects $(TARGET_SAMPLES)/sub/pgs_missing_palette.sup
FATE_SUBTITLES_FFPROBE-$(call DEMDEC, SUP, PGSSUB) += fate-sub-pgs-missing-palette

with tests/ref/fate/sub-pgs-missing-palette:

[SUBTITLE]
pts_time=1.000000
num_rects=1
[/SUBTITLE]
[SUBTITLE]
pts_time=3.000000
num_rects=0
[/SUBTITLE]

fate-sub-%: CMP = rawdiff applies through the name, which suits the text output.

It separates the two behaviors rather than only recording the current one. With libavcodec/pgssubdec.c reset to the parent and ffprobe rebuilt, the test fails on exactly the section the recovery adds:

--- ./tests/ref/fate/sub-pgs-missing-palette
+++ tests/data/fate/sub-pgs-missing-palette
@@ -2,7 +2,3 @@
 pts_time=1.000000
 num_rects=1
 [/SUBTITLE]
-[SUBTITLE]
-pts_time=3.000000
-num_rects=0
-[/SUBTITLE]

fate-sub-pgs-remux, fate-matroska-pgs-remux and fate-matroska-pgs-remux-durations pass unchanged alongside it. I left the AV_EF_EXPLODE case out as suggested, that path is not touched by the patch.

Thanks for the follow-up review. The sample is on its way to samples-request as `sub/pgs_missing_palette.sup` (265 bytes, sha256 `42ec9d5902dc6c40bd55609478cd9b5cbcea1906781e7b215e83078d361174a6`), 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.mak` had no ffprobe entry so far, so this gets its own variable wired into `FATE_SAMPLES_FFPROBE` rather than into `FATE_SUBTITLES`, which is bound to the ffmpeg binary and additionally filtered by `CONFIG_PIPE_PROTOCOL`: ```make fate-sub-pgs-missing-palette: CMD = probeframes -show_entries subtitle=pts_time,num_rects $(TARGET_SAMPLES)/sub/pgs_missing_palette.sup FATE_SUBTITLES_FFPROBE-$(call DEMDEC, SUP, PGSSUB) += fate-sub-pgs-missing-palette ``` with `tests/ref/fate/sub-pgs-missing-palette`: ``` [SUBTITLE] pts_time=1.000000 num_rects=1 [/SUBTITLE] [SUBTITLE] pts_time=3.000000 num_rects=0 [/SUBTITLE] ``` `fate-sub-%: CMP = rawdiff` applies through the name, which suits the text output. It separates the two behaviors rather than only recording the current one. With `libavcodec/pgssubdec.c` reset to the parent and ffprobe rebuilt, the test fails on exactly the section the recovery adds: ``` --- ./tests/ref/fate/sub-pgs-missing-palette +++ tests/data/fate/sub-pgs-missing-palette @@ -2,7 +2,3 @@ pts_time=1.000000 num_rects=1 [/SUBTITLE] -[SUBTITLE] -pts_time=3.000000 -num_rects=0 -[/SUBTITLE] ``` `fate-sub-pgs-remux`, `fate-matroska-pgs-remux` and `fate-matroska-pgs-remux-durations` pass unchanged alongside it. I left the `AV_EF_EXPLODE` case out as suggested, that path is not touched by the patch.
All checks were successful
Lint / Pre-Commit (pull_request) Successful in 30s
Required
Details
Backport / PR (pull_request_target) Has been skipped
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 12m12s
Required
Details
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 15m32s
Required
Details
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 24m17s
Required
Details
Test / Fate (Full, wine) (pull_request) Successful in 29m30s
Required
Details
Autolabel / Labeler (pull_request_target) Successful in 12s
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u 'pgssub-epoch-continue:superuser404-pgssub-epoch-continue'
git switch 'superuser404-pgssub-epoch-continue'
Sign in to join this conversation.
No reviewers
No milestone
No assignees
3 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
FFmpeg/FFmpeg!23851
No description provided.