Skip to content

ASS support for webvtt/srt #233

Open

Description

@tresby

What should the engine do?

Been playing around with subtitles on my Rivulet build.

Trying to get some things like positioning, colour, font face etc working but these stylings seemed to be stripped.

Is there any chance to add the option to preserve this data from SRT and VTT subs abut like richText with dvb_teletext?

Also been playing around with some server side stuff with my dvb_teletext streams and thought I would mention I managed to get position working with dvb_teletext with -txt_page ass. Is that something that is easy to add to the dvb_teletext part?

Thanks as always

Motivating media or use case

VOD playback for text based subs with styling.

Live TV playback with vtt styling via a custom sub renderer.

Area

Codec / container support

Host app / integration context

Rivulet

Would you be willing to open a PR?

Maybe, with guidance

Activity

  1. added
    enhancement
    on Jul 27, 2026
  2. superuser404notfound commented on Jul 28, 2026

    @superuser404notfound
    Owner

    Thanks for this, and for the -txt_page ass note in particular, which turned out to be the thread that unpicks the rest.

    Short version: the styling you are asking for already reaches the engine on every one of these formats, and it gets thrown away in one place on our side. So this is smaller than it looks, and it is one piece of work rather than three.

    Everything already arrives as ASS

    libavcodec converts text subtitle formats into an ASS event line before we ever see them, so AVSubtitleRect.ass carries the markup already:

    • SRT goes through ff_htmlmarkup_to_ass (libavcodec/htmlsubtitles.c): <b>/<i>/<u>/<s> become {\b1}/{\i1}/{\u1}/{\s1}, <font color=...> becomes {\c&HBBGGRR&}, <font size=...> becomes {\fs<n>}, <font face=...> becomes {\fn<name>}, <br> becomes \N.
    • WebVTT (libavcodec/webvttdec.c) maps <i>, <b> and <u> to the same {\i1}/{\b1}/{\u1}.
    • dvb_teletext already runs with txt_format=ass here, which is exactly why its colours survive today.

    What discards it is our own parser. On the plain-text path SubtitleRectText.cleanASSBody strips every {...} block with a regex, and on the rich-text path coloredRuns(fromASSEventLine:) handles \c / \1c and says so in its own doc comment: "All other override tags are ignored".

    So there is no per-format parser to write. One ASS override-tag parser, and SRT, WebVTT, teletext and ASS all light up at once.

    The model has to grow first

    The thing you pointed at cannot carry what you want yet. SubtitleTextRun is currently colour and nothing else:

    public struct SubtitleTextRun: Sendable, Equatable {
        public let text: String
        public let color: SubtitleColor?
    }

    The shape to take it to:

    public struct SubtitleTextRun: Sendable, Equatable {
        public let text: String
        public let color: SubtitleColor?
        public let isBold: Bool
        public let isItalic: Bool
        public let isUnderlined: Bool
        public let isStruckThrough: Bool
        public let fontName: String?
        public let fontSize: Int?
    }

    New fields defaulted in the initializer so existing call sites keep compiling, plus a cue-level placement type on SubtitleCue for {\anN} and {\pos(x,y)}. Positions in a libavcodec-produced ASS line are in the default ASS play resolution (384x288, ASS_DEFAULT_PLAYRESX/Y in libavcodec/ass.h), so they want normalizing to [0, 1] before they reach a host, the way SubtitleImage.position already is.

    SubtitleRectText.teletextBody(fromASSEventLine:) already has the right result shape: rich text when a run carries an attribute, flattened plain text otherwise. Generalized to the full attribute set, unstyled cues stay .text and nothing regresses for hosts handling only that case.

    One part will not work, and it is worth knowing up front

    WebVTT cue settings (line, position, align, size, vertical) are not converted by FFmpeg at all. webvttdec.c says so at the top of the file:

     * @todo need to support extended markups and cue settings

    Only the inline tags are mapped. So VTT bold, italic and underline will work through the above, and VTT positioning will not, until webvttdec learns cue settings upstream. That is a genuine FFmpeg patch rather than something that can be done on this side.

    SRT positioning has a similar caveat: it arrives only when the demuxer supplies AV_PKT_DATA_SUBTITLE_POSITION side data, which most .srt files do not carry. A leading {\anN} written into the text does survive ff_htmlmarkup_to_ass, so that much works.

    If you want to take it

    The whole change is: extend SubtitleTextRun and add the placement type, generalize coloredRuns into a full override-tag parser in SubtitleRectText.swift, then route the text codecs to it in SubtitleDecoder (sidecar) and EmbeddedSubtitleDecoder (in-container). Tests go in Tests/AetherEngineTests/ against raw event lines, so the parser needs no fixture media.

    Happy to review as it goes, and equally happy to build it if you would rather just have it. The teletext positioning you asked about falls out of the same parser, since those lines carry the same tags.

  3. superuser404notfound commented on Jul 28, 2026

    @superuser404notfound
    Owner

    Built and shipped in 5.26.0 (#239), so no need to pick this up yourself.

    It went in as described above: one ASS override parser rather than one per format, so SRT, WebVTT, teletext and ASS all light up together.

    What a host gets now:

    public struct SubtitleTextRun: Sendable, Equatable {
        public let text: String
        public let color: SubtitleColor?
        public let isBold: Bool
        public let isItalic: Bool
        public let isUnderlined: Bool
        public let isStruckThrough: Bool
        public let fontName: String?
        public let fontSize: Int?
    }

    plus SubtitleCue.placement, a SubtitleTextPlacement carrying the ASS numpad alignment and, when the cue asks for one, an anchor normalized to [0, 1] against the video frame, the same convention SubtitleImage.position uses. \pos is normalized against a declared PlayResX/Y when the ASS header provides one and against libavcodec's 384x288 default otherwise, which is what the synthesised lines use.

    Two things worth knowing for Rivulet:

    • No option gates it. An unstyled cue still arrives as .text with the same string as before, so existing handling keeps working, and SubtitleCue.text still flattens either body. You only need new code for the cues you actually want styled.
    • The teletext positioning you asked about works, since those lines carry the same tags and the parser no longer discards them. \an and \pos land on the cue rather than splitting a run.

    Unchanged: preserveASSMarkup still hands over raw event lines and the script header, if you would rather drive libass yourself for a given track.

    Leaving this open for the WebVTT half. Cue settings (line, position, align, size, vertical) still do not reach the engine, because libavcodec does not convert them, and that is an upstream change rather than something this side can fix. VTT inline bold, italic and underline work today. If VTT positioning is what you actually need for the live path, say so and it can go on the FFmpeg patch queue.

    Thanks for the report, and for the -txt_page ass aside in particular. That was the detail that made it obvious the markup was already arriving and only being thrown away here.

  4. tresby commented on Jul 28, 2026

    @tresby
    Author

    Hey Vincent,

    Thanks for looking into this!

    Tested an SRT with colour and working great!

    For Webvtt - I was trying to get Rivulet to have all subtitles render through the custom renderer, rather than native subs which are less flexible - so would be good to be able to pass the webvtt subs through aether and displayed in the appropriate placement etc - but all good if its not something you want to do :)

    For dvb_teletext, I was having some trouble getting positioning to work the way it was with my hls webvtt ffmpeg command in my live tv proxy.

    Although I can't really explain it, I asked claude to explain it, I also made a fix for some missed 'tabbed' spaces that weren't being detected.

    Hopefully the following is helpful!

    Teletext: derive placement from the grid row, and widen the blank-row predicate

    Two related things on the 5.26.0 #233 placement work, both specific to libzvbi teletext. Line numbers are Sources/AetherEngine/Subtitles/SubtitleRectText.swift at 5.26.0.

    1. Teletext encodes vertical position as a row index, not as \an

    #233 derives placement from \an / \pos only:

    // line 168
    let placement = (alignment == nil && position == nil)
        ? nil : SubtitleTextPlacement(alignment: alignment, position: position)

    libzvbi doesn't generally emit \an. It sends a full 24-row page and encodes vertical position as which row the text starts on — expressed as leading \Ns. Some pages do carry an explicit alignment ({\an2}(COW MOOS) is a real example from AU FTA), but most don't, so placement comes back nil for the majority of broadcast captions and the positioning information is lost.

    That information is worth keeping: broadcasters move captions to the top of frame specifically to avoid covering on-screen graphics, so it's editorial intent rather than incidental layout.

    The engine already recognises this — edgeTrimmed's own comment (line 229) calls it "a row-positioning newline" — but treats it purely as a #107 rendering artefact and strips it.

    Where it fits

    Everything needed is already in scope at line 168, and edgeTrimmed doesn't discard it until line 170:

    var runs = pieces.map { $0.style.run($0.text) }
    let placement = ...                        // ← line 168: leading newlines still present
    guard let trimmed = edgeTrimmed(runs) else { return nil }   // ← line 170: gone

    The styled walker also already normalises both escapes that matter (lines 147-148): \N/\n → \n, and \h → space. So by line 168 the run sequence is exactly the newline-delimited grid the derivation needs.

    Must be teletext-gated, since styledRuns is shared with SRT / ASS / WebVTT where a leading newline is not row positioning. teletextBody is already the teletext-specific entry point.

    The algorithm (from a working implementation)

    This has been running in production in a Python HLS proxy (teletext → WebVTT) for a while, so the shape is field-tested:

    # split the ASS text into grid rows on \N / \n; blank rows are KEPT as rows,
    # because the row ORDINAL is the positioning information
    for i, chunk in enumerate(re.split(r'\\[Nn]', part)):
        if i: rows.append([])
        chunk = chunk.replace('\\h', ' ')      # hard-space padding → real spaces
        if chunk: rows[-1].append((colour, chunk))
    
    first_row = None
    for idx, runs in enumerate(rows):
        if not ''.join(t for _, t in runs).strip():
            continue                            # blank grid row: skipped for output,
                                                # but idx already counted it
        if first_row is None:
            first_row = idx                     # ← the identification
    
    # only when the page carried no explicit \anN
    if an is None and first_row is not None:
        if first_row < 24 // 2:                 # upper half of the 24-row page
            # → top of frame (equivalent to \an8)

    So: the ordinal index of the first non-blank row, upper half → top.

    Two things learned the hard way, both worth keeping:

    Deliberately coarse — top vs bottom only. Mapping each row to its own line:N% looked more faithful but made captions jitter vertically. Teletext bottom-anchors a block, so a two-row caption starts at row 19 and a one-row at row 21; consecutive cues then rendered at alternating heights and the text visibly jumped between them, which reads as a blink. Only "did the broadcaster move this to the top" carries meaning.

    \an present must win, including when it means bottom. An early version tested if not settings to decide whether to fall back to the grid row. {\an2} is explicitly bottom, correctly produces no cue settings, and that empty result was then mistaken for "no information" — promoting bottom-anchored captions to the top of frame. The fallback has to be gated on an is None, not on the derived output being empty.

    2. The styled path's blank/trim predicates are narrower than the plain path's

    Separate, smaller, and possibly the cause of stray blank lines on coloured cues.

    The plain path tests blankness with Unicode-aware trimming (lines 21, 66, 302):

    s.trimmingCharacters(in: .whitespacesAndNewlines)

    The styled path uses an explicit three-character test (edgeTrimmed, lines 240 and 247):

    let d = String(first.text.drop(while: { $0 == " " || $0 == "\t" || $0 == "\n" }))
    while let c = s.last, c == " " || c == "\t" || c == "\n" { s.removeLast() }

    and collapseInteriorBlankLines (line 266) uses #"\n(?:[ \t]*\n)+"#.

    CharacterSet.whitespaces covers Unicode general category Zs, which includes U+00A0 NO-BREAK SPACE; [ \t] does not. So a padding row made of anything other than literal space/tab/newline is trimmed on a plain cue and survives on a styled one — which is the "sub line / blank / sub line" artefact, and it would appear only on coloured pages.

    The ASS \h escape is already normalised to a plain space at line 148, so this only bites if libzvbi emits the character directly rather than the escape. Worth checking against a real page rather than assumed — but there's precedent for U+00A0 turning up in caption payloads in this codebase: CEA608Decoder.swift:253 explicitly maps \u{00A0} → " ".

    Cheapest fix is to make the styled predicates use the same .whitespacesAndNewlines / CharacterSet test the plain path already uses, so the two paths can't disagree.

    Why this matters downstream

    Blank rows and column padding sit inside the colour runs, e.g.

    {\c&HFFFF00&}\h\h\hWe want to figure out\h\h{\c&HFFFFFF&}\h
    

    so a host can't fix either of these itself: by the time cues arrive, the runs are trimmed and the row ordinals are gone. Both have to happen where the ASS line is still intact.

  5. superuser404notfound commented on Jul 28, 2026

    @superuser404notfound
    Owner

    Thanks for testing, and for the write-up. The teletext half turned out to be right about a case I would not have found on my own, and the WebVTT half turned out to be right about me being wrong, so all three parts landed.

    Teletext placement

    The premise is not quite what libzvbi does, but the conclusion holds for a case that does happen.

    gen_sub_ass already derives the vertical position from the grid row and emits it as \an:

    vertical_align = (2 - (av_clip(i + 1, 0, 23) / 8));
    av_bprintf(&buf, "{\\an%d}", alignment + vertical_align * 3);

    so thirds rather than halves, with the horizontal component coming from its own leading/trailing analysis. The engine has parsed that since 5.26.0 and hands it over as SubtitleCue.placement.

    What matters is that the whole block sits behind is_subtitle_page, and that flag comes from the row-0 header (libzvbi-teletextdec.c:617):

    // Check for disabled NEWSFLASH flag and enabled SUBTITLE and SUPRESS_HEADER flags
    ctx->subtitle_map[pgno] = (!(flags1 & 0x40) && flags1 & 0x80 && flags2 & 0x01);

    When a broadcaster does not set all three, or the header has not been seen yet, the else path writes the whole page instead: no \an, no per-row trim, one " \N" per grid row with the empty ones included. That is exactly when the row ordinal becomes the only carrier of the position, which is the case the Python implementation is handling, and the engine's edge trim was removing it before anything could read it.

    So it is in, gated on \an being absent and on teletext only, and it applies ffmpeg's own formula to the ordinal rather than a second scale, so the two paths cannot disagree about where a caption belongs. Both of the hard-won details survive: coarse bands only, and an \an that arrived always wins.

    One correction to the reasoning, worth recording because it is what makes the gate load-bearing: on a page libzvbi does flag, leading \Ns are not the grid row at all. They are the empty_lines / 2 filler gen_sub_ass writes to nudge the block inside its anchor, so reading them as an ordinal there would produce nonsense. The an is None check is carrying more weight than the row counting.

    The whitespace fix

    The predicate difference was real and it is fixed, but it cannot be what you are seeing on teletext. IS_TXT_SPACE catches U+00A0 explicitly:

    #define IS_TXT_SPACE(ch) ((ch).unicode < 0x0020 || (ch).unicode >= 0xe000 || (ch).unicode == 0x00a0 || ...)

    and every space it produces is written as the \h escape, which the parser already normalises to a plain space. So a literal NO-BREAK SPACE cannot reach the engine from libzvbi. The mismatch still needed fixing for SRT, WebVTT and ASS payloads, which can carry one, so the styled path now trims exactly what the plain path trims.

    For the blank lines themselves I found a different candidate and fixed that too. The interior blank-line fold worked per run and across one run boundary, which misses the shape the source produces most easily: the padding of an otherwise empty row carries the spacing attribute that changes colour, so the blank row lands in a whitespace-only run of its own and breaks the chain between the two text rows. It now folds the flattened text and re-splits along the run boundaries, so run structure cannot hide a blank row from it.

    If blank lines survive that, the fastest way to settle it is the ASS line itself. -loglevel debug makes the teletext decoder print every one it emits as subtext:...:txetbus, and one of those from an affected page tells us more than any amount of reasoning from the rendered output.

    WebVTT

    The "libavcodec does not convert them" note was a conclusion about the wrong layer, and pushing on it was the right call. The decoder does drop line / position / align. The demuxer keeps them: libavformat/webvttdec.c attaches the verbatim settings string to every packet as AV_PKT_DATA_WEBVTT_SETTINGS, and matroskadec.c propagates the same side data for WebVTT in Matroska. Nothing upstream was needed, only reading one layer up.

    They arrive as SubtitleCue.placement now. A percentage line becomes an anchor point plus the alignment row, anchored to the frame edge it is nearer, because the spec's default line alignment pins the box top and line:90% would otherwise hang a two-line cue off the frame. A line number keeps only the half of the frame it names, since line boxes need a rendered line height the engine does not have. align becomes the column. size and vertical have no equivalent in the placement model and are ignored, and a position without a line keeps only the column, because an anchor point needs both axes.

    While testing that I found something worse sitting underneath it: the standalone WebVTT demuxer was never compiled into the FFmpeg build, only the decoder. avformat_open_input rejected every .vtt file with AVERROR_INVALIDDATA, so external WebVTT subtitles never loaded at all, on any path. Same shape as a gap I fixed for raw PGS sidecars a while back, and it hid for the same reason: the codec was present, so the problem looked like it had to be somewhere else. That is fixed in the FFmpeg build this release pins.

    One boundary worth being explicit about, since it decides whether this covers what Rivulet needs. All of the above is the engine's own demux path. For a remote HLS source playing through the native bypass, the WebVTT rendition belongs to AVPlayer and the engine never demuxes it, so those cues do not reach subtitleCues and a custom renderer cannot draw them. For embedded tracks, including WebVTT in Matroska or MPEG-TS, selectSubtitleTrack(index:) is already the host-overlay path and is independent of the native renditions, so rendering everything yourself works there today. If the HLS rendition case is the one you need for the proxy, open a separate issue and I will look at what it takes.

    All of it is in 5.27.0.

  6. tresby commented on Jul 29, 2026

    @tresby
    Author

    Thanks again for the updates!

    Gave dvb_teletext a go and while trying to implement with claude it came up with this.

    Unsure if valid or I'm making a mistake

    5.28.0: SubtitleCue.placement is dropped before it reaches the host

    Tested teletext placement on 5.28.0 and no cue arrives with a placement. It isn't the teletext derivation — that part looks right. The cue-publishing layer rebuilds SubtitleCue and omits placement, so it is nil by the time a host sees it, on every format rather than just teletext.

    SubtitleCue.init defaults placement to nil (deliberately, for source compatibility), so these call sites compile silently rather than erroring.

    Where

    Sources/AetherEngine/AetherEngine+Subtitles.swift, three reconstructions, none passing placement:

    Line 764 — the id stamp on insert. This is the decisive one: every cue passes through it.

    let stamped = SubtitleCue(id: nextID, startTime: cue.startTime, endTime: cue.endTime, body: cue.body)

    Line 722 — trimTextCues (#107). Would drop it again on every teletext page transition even with the above fixed, since each page trims the previous open cue.

    cues[i] = SubtitleCue(
        id: cue.id,
        startTime: cue.startTime,
        endTime: trimAt,
        body: cue.body
    )

    Line 660 — the PGS trim. Harmless today (bitmap cues carry geometry on SubtitleImage), but the same shape.

    Supporting evidence: placement appears nowhere else in that file. The only match is line 622, which is about re-attaching WebVTT settings as packet side data before decode — a different thing, and it happens upstream of all three.

    Why it looks like it works

    The decoder is correct — EmbeddedSubtitleDecoder.swift:305 passes placement: cuePlacement, and the teletext/WebVTT derivations feeding it look right. A unit test against the decoder or against SubtitleRectText would pass. The loss happens between the decoder and $subtitleCues.

    Colour and the other run attributes are unaffected because they live in the cue body, which every reconstruction does preserve. Only the new cue-level field is lost, which is why 5.26.0's styling appears to work end to end while placement does not.

    Suggested fix

    Carry placement: cue.placement through all three, and consider whether the initializer parameter should stay defaulted now that the field is load-bearing — a required parameter would have caught this at compile time in all three places.

    Environment

    AetherEngine 5.28.0, FFmpegBuild 2.3.0, tvOS 26.5. Live DVB-T teletext (AU FTA, page 801) via the software path; same result on the loopback path.

  7. tresby commented on Jul 29, 2026

    @tresby
    Author

    Implemented Live TV HLS w/ WEBVTT through our custom sub renderer and it's honouring colour and position - very nice thank you!

    Just the teletext position I can't get working atm really.

  8. added a commit that references this issue on Jul 29, 2026
  9. superuser404notfound commented on Jul 29, 2026

    @superuser404notfound
    Owner

    Valid, and thanks for pushing on it. Both of those posts turned out to be one finding: the report is right, and the WebVTT success is what pins down the boundary.

    Fixed in 5.28.1 (#244).

    The report is correct, with one refinement

    Sources/AetherEngine/AetherEngine+Subtitles.swift:764 is the decisive call site, exactly as described. The refinement is the scope: not every format, every embedded track. Three publishing paths exist and only one goes through the retained store:

    Path Publishing placement
    Sidecar / external subtitle URL subtitleCues = result.cues survived
    Native rendition route route.store.appendCues survived
    Drained embedded track applyEventMutations -> insertCueSorted dropped

    That is why both observations are true at once rather than one of them being a measurement error. Teletext is an embedded track, so it went through the retained store and could not keep a placement; whichever of the other two rows the WebVTT took, it kept one. Worth knowing beyond this bug, since the same track can land on either side of that line depending on how it is fed in.

    The reasoning about why it looked like it worked was right too: colour lives in the cue body, which every rebuild did carry, so 5.26.0's styling worked end to end while the one cue-level field did not.

    What went in

    Five more sites than the three listed carried the same defect, all reached through the OCR and PGS paths: AetherEngine+ClosedCaptions.swift:195, SubtitleDecoder.swift:246, Issue100PGSStaleArrival.swift at three places, SubtitleImageOCR.swift:87 and SubtitleOCRPendingState.swift:24. Placement is nil by construction on all of them today, since they only handle bitmap and CEA-608 cues, but they are the same shape and would have started dropping real data the moment either grew a placement.

    On making the initializer parameter required: it would have caught all eight at compile time, which is the right instinct, but it is source-breaking for any host that constructs a SubtitleCue itself. Instead every rebuild now goes through one internal copy helper that carries whatever it is not asked to change, so the field cannot be dropped by forgetting to list it, including for whatever field the cue grows next.

    Tests assert the invariant on the store operations rather than on any one format, since the defect was never format-specific.

    Retest

    5.28.1 is the one to try. Teletext page 801 should now arrive with SubtitleCue.placement set, on the flagged and non-flagged page paths both. If it still comes through nil, the ASS line itself is the fastest way to settle it: -loglevel debug makes the teletext decoder print every line it emits as subtext:...:txetbus, and one of those from an affected page is worth more than reasoning from the rendered output.

    Good to hear the WebVTT path is honouring colour and position through the custom renderer. Thanks for the detailed write-ups on this one, three rounds of them have found things that were not reachable from this side.

  10. tresby commented on Jul 29, 2026

    @tresby
    Author

    Yeah this one seems too be honouring placement for dvb_teletext so that's awesome!!

    One more tiny one that I dealt with in my proxy. I'll attach some photos and let claude explain the circumstances. But I think once that is done - dvb_teletext (Australia anyway) would have full support IMO.

    Image Image

    5.28.2: teletext rows keep their column padding at interior line breaks

    Placement retention in 5.28.1 works — teletext positions now reach the host and
    render correctly. One thing from the proxy implementation didn't make it across
    though, and it shows up as stray spaces inside multi-row cues.

    Symptom

    A two-row caption arrives with padding on the inside edges: trailing spaces at
    the end of row 1, leading spaces at the start of row 2. On a renderer that
    centres each line, row 2 sits visibly off-centre and the cue's background box is
    wider than its visible text.

    Why

    Teletext pads every row out to the column width, and \h becomes a real space.
    Two passes handle whitespace today and neither covers an interior row boundary:

    • edgeTrimmed (SubtitleRectText.swift:252) trims the leading and trailing
      edges of the whole run sequence — the start of the first row and the end
      of the last.
    • collapseInteriorBlankLines (:290) removes horizontal whitespace only when
      it sits between two newlines: it scans from i + 1 and drops nothing unless
      lastNewline > i. A single \N between two populated rows leaves both sides
      untouched, and the scan never looks at the characters before a newline at
      all.

    So for the flattened row sequence

    "   Waxy, buttery potatoes with chicken  " \N "        and peas.   "
    

    edgeTrimmed removes the three leading spaces and the three trailing ones, and
    collapseInteriorBlankLines leaves the middle alone:

    Waxy, buttery potatoes with chicken␣␣
    ␣␣␣␣␣␣␣␣and peas.
    

    What the proxy did

    It worked row-wise rather than sequence-wise: split on \N / \n first,
    judge each row by its visible text only, drop rows that are blank, then trim
    padding off both ends of every row that survives — popping whole runs that are
    all-whitespace before lstrip/rstriping the survivors.

    The run-popping matters. The padding of a row often carries the spacing
    attribute that changes colour, so it lands in a whitespace-only run of its own —
    the same thing that made you flatten-and-re-split in
    collapseInteriorBlankLines rather than checking adjacent pairs.

    Suggested change

    The machinery is already there. In collapseInteriorBlankLines, alongside the
    blank-row fold, mark for removal the horizontal whitespace immediately preceding
    and immediately following every retained newline:

    // after the existing blank-row fold, for each newline kept:
    var back = i - 1
    while back >= 0, keep[back], chars[back].isWhitespace, !chars[back].isNewline {
        keep[back] = false; back -= 1
    }
    var fwd = lastNewline + 1
    while fwd < chars.count, chars[fwd].isWhitespace, !chars[fwd].isNewline {
        keep[fwd] = false; fwd += 1
    }

    Operating on the flattened sequence keeps it correct across run boundaries, and
    the existing owner map re-splits it. The function is arguably then doing two
    jobs and might read better as a row-trim pass composed after the fold — either
    way it stays teletext-only, which is right: interior indentation in an ASS or
    SRT cue can be deliberate, whereas a teletext row's is grid padding.

    Two notes

    This unlocks the column analysis you mention at :364. The comment there
    gives "the per-row trim that this path never ran" as the reason horizontal
    alignment stays at ffmpeg's default of 2. With the trim in place, the leading
    pad width per row becomes measurable, so gridPlacement could derive a real
    horizontal anchor instead of assuming centre.

    It does discard the only horizontal-position signal a host would see if it
    ignores placement.
    That seems right — position belongs in placement, which
    is exactly what 5.28.1 made reliable, and the proxy discarded the padding for
    the same reason. Worth being deliberate about it rather than incidental.

    Environment

    AetherEngine 5.28.2, FFmpegBuild 2.3.0, tvOS 26.5. Live DVB-T teletext (AU FTA,
    page 801) through the software path.

  11. added a commit that references this issue on Jul 30, 2026
  12. superuser404notfound commented on Jul 30, 2026

    @superuser404notfound
    Owner

    Correct on every point, and fixed in 6.1.3 (#258).

    The diagnosis needed no adjustment: edgeTrimmed reaches the outer edges of the whole run sequence, collapseInteriorBlankLines scans from i + 1 and drops nothing unless lastNewline > i, and neither ever looks at the characters before a newline. The one thing worth adding is the " \N" that gen_sub_ass appends after every row, so even a row that fills its columns exactly arrives with one trailing space.

    It went in as its own pass rather than inside the fold, which was the alternative in the report. Same machinery: flatten, mark, re-split along the original run boundaries, for exactly the reason given for the fold.

    One refinement, and it is the interesting half

    The trim cannot run unconditionally, because gen_sub_ass has two output forms and only one of them is a grid.

    On a page it does not flag, it dumps the raw grid: every row at full column width, empty rows included, the row ordinal as the only carrier of position. Every space in that is the grid.

    On a flagged page it curates, and then both of the things these passes remove are decisions:

    flagged page raw grid dump
    blank lines empty_lines / 2 fillers, vertical fine-positioning inside the block (:368) every skipped grid row, emitted
    residual padding relative indentation carrying the chosen alignment: leading = min_leading for left, trailing = min_trailing for right, both for its non-centrable centre case (:372-375) the grid, at full column width

    So the pass is gated, and the gate is one that already existed: no \an means the raw dump. The equivalence holds by construction rather than by observation, which is what makes it usable. gen_sub_ass emits {\anN} on the first row of a flagged page that holds any character (:361), and a flagged page holding none produces no cue at all, so an arriving alignment and a curated body are the same statement.

    That also surfaced something the report did not go looking for. The blank-line fold has been unconditional since #107, so on flagged pages it had been folding those empty_lines / 2 fillers away all along, which is the same defect in the other direction. It moved behind the same gate. A curated body is now passed through whole, down to the separator space.

    On the two notes

    The column analysis stays parked, and the comment at :364 now says why. The reason it gave was the missing per-row trim, which is stale as of this release: the leading and trailing pad of each row is measurable now. What blocks it is elsewhere. Where can_align_left / _right / _center leave more than one of the three viable, gen_sub_ass resolves the tie from last_ass_alignment, the answer it gave the previous cue. A stateless parser has to fall back to centre there, so an unambiguous left-aligned cue followed by an ambiguous one would jump, and that is the same blink the vertical derivation refuses on purpose. Reachable, but it needs the derivation to hold cross-cue state, which is a different shape from where this lives today.

    On discarding the horizontal signal: agreed, and deliberate. Position belongs in placement. Leaving grid pad in the body as a second, weaker channel for it means a host that reads both gets the offset applied twice.

    Retest

    6.1.3, page 801. A two-row caption should arrive with no padding on either side of the break, and the placement should be unchanged from 5.28.1, since the row ordinal is measured before any of this runs.

    Thanks for another one that was not reachable from this side. Four rounds in, the proxy comparison keeps finding the cases where the engine and a working implementation disagree by a detail, and the write-ups have landed on the right call site every time.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions