Skip to content

feat(embeddedsub): read embedded subtitle tracks through the file's index - #3270

Closed
Quick104 wants to merge 7 commits into
mainfrom
feat/subtitle-cue-reader
Closed

Quick104 wants to merge 7 commits into
mainfrom
feat/subtitle-cue-reader

Conversation

@Quick104

@Quick104 Quick104 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #1406
Validation tasks: none

Serving one embedded subtitle track today means FFmpeg reads the whole source file, because the track's packets are spread through it. On network storage that is slow: a cold extraction of one SubRip track from a 3 GB episode took 116 s, and players gave up before the first cue arrived (#1406 has more cases). Matroska and MP4 files already record where every subtitle packet is, in their Cues and sample tables. This pull request adds a reader that uses that index to read only one track's packets, and passes them to FFmpeg so the converted output is byte-for-byte what a full extraction produces. Nothing serves through it yet.

This is the first of four stacked pull requests:

  1. This one: the reader.
  2. feat(playback): honor native subtitle limitations and mark switchable tracks #3271: native subtitle limitations and stream identity in the subtitle inventory. Independent, based on main.
  3. feat(playback): keep embedded subtitle tracks and serve sidecars through the index #3272: keep tracks read whole in blob storage and serve every embedded sidecar through them. Based on this branch, and contains feat(playback): honor native subtitle limitations and mark switchable tracks #3271.
  4. feat(playback): list every embedded text track as an on-demand HLS rendition #3273: list every embedded text track as an on-demand HLS subtitle rendition. Based on feat(playback): keep embedded subtitle tracks and serve sidecars through the index #3272.

Approach

  • internal/embeddedsub reads a file's subtitle tracks from its Matroska header, seek heads, Info, Tracks, Tags and Cues, or from its MP4/MOV moov box, without reading media data (ReadIndex). It rates each track's index as complete, unknown, incomplete or absent, using the NUMBER_OF_FRAMES tag where there is one. ReadPackets reads one track's packets in a time window or whole, with up to 16 reads in flight.
  • WriteStream writes those packets as a subtitle-only Matroska or MP4 stream, and ExtractSubtitlePacketsWithFormat feeds it on stdin to the same FFmpeg conversion, offset by the source's start time. Silo keeps using FFmpeg for SubRip, ASS, WebVTT and PGS conversion; only the read changes.
  • Whatever the reader can't handle comes back as an error that means "demux the source as today": no index for the track (mkvmerge before 6.2 and some HandBrake builds wrote no subtitle cues), an incomplete one, fragmented MP4, other MP4 sample entries or edit lists, and damaged files (ErrMalformed, DamagedError). One read holds at most 256 MiB of packets, and one block or sample at most 16 MiB.
  • An LRU Cache keeps indexes in memory, keyed by path, size and modification time.
  • internal/matroska now holds the EBML parsing that mediaprobe and playback/keyframes each had a copy of, and the reader uses it as well. Their behavior is unchanged, except that an element ID longer than four bytes, which Matroska doesn't allow, now reads as malformed in keyframes too.
  • docs/architecture/embedded-subtitle-index.md describes what is read, how completeness is rated, and the invariants that keep the output equal to a full extraction.
How much the index covers, and what reads cost
  • Survey of 246 Matroska files from a large library on network storage: every file had Cues, and 1,378 of 1,390 text subtitle tracks were indexed. The 12 that weren't came from mkvmerge before version 6 and one HandBrake build. Reading the header and Cues took 0.23 s at the median and 0.98 s at p90.
  • A 118 MB Matroska file with 200 SubRip cues: the index took 3 reads (97 KB), the whole track 400 reads (833 KB), and a 6 s window 4 reads (8 KB).
  • A prototype of the same reads, on 13 cold files on that storage: a 6 s window took 0.07–0.13 s (one at 2.1 s), and a 30 s window 0.09–0.38 s for 12 of 14 windows. A whole track still took 17.7–60.6 s, because some reads stall for seconds on that storage. That is why feat(playback): keep embedded subtitle tracks and serve sidecars through the index #3272 keeps a track once it has been read whole.

Validation

  • Output equality: tests compare the converted bytes with FFmpeg's own extraction from the source, for SubRip to WebVTT and SubRip, ASS to ASS and WebVTT, PGS to SUP, and mov_text in MP4, faststart MP4, MP4 with a later start time, and MOV. Hand-built files cover zlib, bzlib and header-stripping compression, Xiph, EBML and fixed lacing, cues without CueRelativePosition, a later start time, truncated files, and files without Cues.
  • Not covered: files written by mkvmerge itself. mkvmerge wasn't available, so those layouts are hand-built.
  • Fuzzing during the independent review (about 23 million inputs to the readers): no panics.
  • go build ./... and go vet ./... on this branch: pass. Cross-compiles for darwin and windows.
  • Full pre-PR gate from CONTRIBUTING.md, run on the top of the stack (feat(playback): list every embedded text track as an on-demand HLS rendition #3273), which contains this branch: pass, with three exceptions. Two jellycompat tests fail on main too (TestPlaybackInfoWithoutStripOrToneMapStillHasNoRoute, TestPlaybackInfoSkipsStripWhenRPUCannotBeStripped). make verify-actionlint rejects the local binary's version string; actionlint itself passes.

Evidence

Evidence: https://evidence.siloserver.org/r/silo-server/pr-3270/

Risks

Nothing calls the reader until #3272, so running servers see no change from it. The internal/matroska move does change the code mediaprobe and keyframe planning run on every Matroska file; their existing tests pass.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code in T3 Code
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: Fully AI-generated, human verified. The reader has no runtime path of its own; it ran end to end through feat(playback): keep embedded subtitle tracks and serve sidecars through the index #3272 and feat(playback): list every embedded text track as an on-demand HLS rendition #3273 on a TCL Roku TV (Roku OS 15.3.4). Apple and Android clients were not device-tested with this stack.
  • Adversarial review: a separate Claude Code agent (claude-opus-5-5) reviewed the reader on its own, fuzzing it and comparing its output with FFmpeg's. It found no panics and no output differences, and six gaps, all fixed in this branch: one read could hold unbounded packet data; a window could split a laced block, which changes the text FFmpeg makes of it; offsets near the integer limits overflowed into failed reads instead of reporting damage; damaged metadata came back as plain errors a caller couldn't tell from a failed read; a panic in a read job, the index cache or the stdin writer could crash the process or leave cache callers waiting; and arithmetic on crafted duration and timestamp-scale values was unchecked.

🤖 Generated with Claude Code

Note

Add indexed embedded subtitle reading for Matroska and MP4 tracks

  • Adds the embeddedsub package: it reads subtitle indexes from Matroska and MP4/MOV files, then reads packets through the file's cue/sample index instead of scanning the whole file. ReadPackets supports whole-track and time-window reads with configurable concurrency, lookback, and a shared byte budget.
  • Adds a concurrent LRU index cache (NewCache, Cache.Index) keyed by path, size, and modification time, with shared in-flight loads.
  • Adds packet-based subtitle extraction: SubtitlePacketInput feeds a serialized subtitle stream to FFmpeg's stdin, so extraction no longer requires reading the source media file.
  • Consolidates duplicated EBML/Matroska parsing from internal/playback/keyframes and internal/mediaprobe into a shared internal/matroska package.
  • Documents the design in embedded-subtitle-index.md.
  • Risk: parseInfo in matroska.go now ignores timestamp-scale values above math.MaxInt64 instead of truncating them; malformed Matroska cues clear all tracks' cues; unsupported containers and edit-list layouts return ErrNotSupportedContainer/unsupported-track errors.

Macroscope summarized 3f73be5.

Quick104 and others added 4 commits October 29, 2026 18:10
mediaprobe and playback/keyframes each carried their own copy of the EBML
vint, element-header, child-walk and seek-head helpers. Move them into
internal/matroska with the element IDs, a cue-point walker that reports
every CueTrackPositions field, a TrackEntry parser and the element
writers, so the cue-indexed subtitle reader can use the same code.

Behavior is unchanged except that an element ID longer than four bytes,
which Matroska doesn't allow, now reads as malformed in keyframes too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Extracting an embedded subtitle track runs FFmpeg over the whole source
file, which takes minutes on network storage. A Matroska file's Cues point
at every subtitle block in nearly every file FFmpeg or mkvmerge 6.2+ wrote,
so the track can be read with a few small reads per packet instead.

internal/embeddedsub reads a file's subtitle tracks from its EBML header,
seek heads, Info, Tracks, Tags and Cues without touching a cluster
(ReadIndex), rates each track's cues against its NUMBER_OF_FRAMES tag, and
reads one track's packets in a time window or whole (ReadPackets): a
cluster head and a block per cue, issued together with up to 16 reads in
flight and POSIX_FADV_RANDOM on the file. It handles SimpleBlock and
BlockGroup, Xiph, EBML and fixed lacing, zlib, bzlib and header-stripping
compression, and cues without CueRelativePosition by walking that one
cluster. Unreadable blocks come back as a DamagedError alongside the
packets that were read. An LRU Cache keyed by path, size and mtime keeps
indexes in memory, and HasOverrideTags finds ASS override blocks in text.

WriteMKS writes the packets back out as a subtitle-only Matroska stream,
and playback's StreamExtractSubtitle and ExtractSubtitlePacketsWithFormat
take it on stdin (StreamExtractOpts.Packets) and run the same conversion,
offset by the source's start time, so the output bytes match today's. The
tests check that against FFmpeg's own extraction from the source for
SubRip to WebVTT and SubRip, ASS to ASS and WebVTT, and PGS to SUP. MP4
text tracks follow in the next change.

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

MP4 and MOV mov_text tracks have the same problem as Matroska ones:
FFmpeg reads the whole file to extract one. Their sample tables say where
every sample is, so ReadIndex now also reads an MP4 or MOV file's moov box
and expands each tx3g or QuickTime text track's stsd, stts, stsc, stsz and
stco/co64, mapping a leading empty edit and one normal edit to presentation
times. ReadPackets reads the samples a window needs, merging neighbors into
one read.

WriteStream writes them back as a one-track MP4, moov first for a pipe,
copying the source's ftyp, mvhd, tkhd, edts, mdhd, hdlr and stsd boxes so
FFmpeg applies the same edit list and decoder setup, and filling gaps with
empty samples so a window keeps its times. The FFmpeg comparison covers
MP4, faststart MP4, MP4 with a later start time, and MOV, to WebVTT and
SubRip. Fragmented files, composition offsets, other sample entries and
other edit lists report Track.Unsupported.

docs/architecture/embedded-subtitle-index.md records what the reader reads,
how completeness is rated, and the invariants that keep the output equal to
today's extraction.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An independent review of the reader found no panics under fuzzing and no
output differences from FFmpeg, but these gaps:

- A read held every decompressed packet with no total limit, so a small
  crafted file could make one call hold a gigabyte. ReadOptions.MaxBytes
  (256 MiB by default) now bounds the packet data and the blocks in flight,
  returning ErrTooLarge; a Matroska block is capped at 16 MiB and an MP4
  sample over 16 MiB makes the track unsupported.
- A window could split a laced block, which changes the text FFmpeg makes
  of its frames. The frames of a laced block are now kept together, and the
  lookback widens by the whole block's span rather than one frame's.
- An MP4 chunk offset near the int64 limit, or a Matroska cue position past
  the segment, overflowed into a failed read. Both are now damage.
- Structural problems in Matroska or MP4 metadata came back as plain errors
  a caller couldn't tell from a failed read; they now match ErrMalformed.
- A panic in a read job, a cluster-head read, the cache's index read or the
  ffmpeg stdin writer would have crashed the process or left cache callers
  waiting. Each now fails only its own call, and every cache caller can
  give up on a shared index read.
- Duration and timestamp arithmetic on crafted DefaultDuration and
  TimestampScale values is now checked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@silo-triage silo-triage Bot added the size/XXXL 3000+ added + deleted lines (all files); change volume, not priority. label Oct 30, 2026
@silo-kody

silo-kody Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-31T20:10:35.367727Z 3f73be5 New commits
🔒 Security Review ✅ Completed 2026-10-31T20:10:05.158684Z 3f73be5 New commits

Security findings

Advisory findings (1)

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

This change adds indexing and time-window packet reading for embedded Matroska and MP4/MOV subtitles. It also adds packet-stream writers, FFmpeg packet-input support, and shared Matroska parsing helpers used by existing media-probe and keyframe code.

Changes: Embedded Subtitle Processing

Layer / File(s) Summary
Shared Matroska parsing
internal/matroska/*, internal/mediaprobe/matroska.go, internal/playback/keyframes/*
Adds shared EBML and Matroska parsing, track and cue helpers, and encoders. Existing media-probe and keyframe parsing now use the shared helpers.
Subtitle index and cache
internal/embeddedsub/embeddedsub.go, internal/embeddedsub/matroska_index.go, internal/embeddedsub/mp4.go, internal/embeddedsub/cache.go, internal/embeddedsub/file.go, internal/embeddedsub/fadvise_*, docs/architecture/embedded-subtitle-index.md
Adds index and track types, Matroska and MP4/MOV index construction, file-version checks, and a concurrent byte-budgeted LRU cache. Tests cover index metadata, cue completeness, and cache behavior.
Bounded packet reading and decoding
internal/embeddedsub/block.go, internal/embeddedsub/read.go, internal/embeddedsub/matroska_read.go, internal/embeddedsub/mp4.go, internal/embeddedsub/*_test.go, internal/embeddedsub/fixture_test.go, internal/embeddedsub/export_test.go, internal/embeddedsub/tags.go, docs/architecture/embedded-subtitle-index.md
Adds Matroska block parsing and decompression, plus time-window packet reads for Matroska and MP4/MOV. Reads enforce concurrency and byte limits and report recoverable damage alongside readable packets. Tests compare extraction results with FFmpeg and cover windows, malformed data, and read limits.
Packet serialization and FFmpeg input
internal/embeddedsub/mks.go, internal/embeddedsub/mp4_write.go, internal/playback/subtitle_packets.go, internal/playback/subtitle_stream.go, internal/playback/subtitles.go, internal/playback/*subtitle*test.go, docs/architecture/embedded-subtitle-index.md
Adds Matroska and MP4 stream writers. Playback can pass serialized subtitle packets to FFmpeg, and extraction helpers share command startup and error handling.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant ExtractSubtitlePacketsWithFormat
  participant startSubtitleCommand
  participant FFmpeg
  Caller->>ExtractSubtitlePacketsWithFormat: provide packet input and output format
  ExtractSubtitlePacketsWithFormat->>startSubtitleCommand: start extraction with packet input
  startSubtitleCommand->>FFmpeg: write serialized subtitle stream to stdin
  FFmpeg-->>ExtractSubtitlePacketsWithFormat: return extraction output and process status
  ExtractSubtitlePacketsWithFormat-->>Caller: return extracted subtitle bytes or error
Loading

Possibly related issues

Merge Risk: Low · up to 3f73b

Indexed reads can select incorrect cues or exceed configured memory limits on uncommon inputs. Address these limitations before enabling the reader in playback.

Security architecture risk: Low · up to 3f73b

The new processing path is not yet used by playback requests, which limits immediate exposure. However, compressed subtitle data can exceed the configured memory allowance before rejection, so that allowance is not yet a reliable containment boundary.

Retained concerns

  • Low · security · observed: The new packet reader allocates decompressed payloads before charging their size to MaxBytes. Compressed media can therefore exceed the advertised per-call packet-memory allowance before ErrTooLarge is returned, with concurrent workers amplifying the transient excess. This is a latent availability-control gap in the new API, not a demonstrated attack through current playback requests.
Security review details

Security Blast Radius

  • inferred — If a caller invokes the new reader on attacker-influenced media, excess allocations affect the calling process's memory and availability. Current production callers do not establish that exposure through subtitle-serving requests, and the inspection established no tenant, credential, or cross-service authority expansion.

Security Findings and Attack Paths

  • observed — The resource-control gap follows compressed frame data through payload decompression into an allocation, then into budget.take. ErrTooLarge rejects retained output only after the candidate exists. The per-packet decompression limit mitigates individual expansion but does not enforce the configured aggregate allowance before allocation.

Trust Boundaries and Controls

  • observed — The new reader processes media bytes in process, using file access through the existing fspath abstraction. It checks index freshness using size and modification time and rejects cue blocks belonging to another track. These are parsing and consistency controls, not a newly introduced authorization boundary.

Resilience and Maintainability Implications

  • observed — Worker execution is limited to the configured concurrency, and normal completion waits for workers. Cancellation returns without waiting for already-started work, as documented. Positive caller-supplied concurrency has no fixed maximum, so the default of 16 is not a universal resource ceiling.

Hardening Proposals

  • proposed — Before enabling request-driven use, make decompression reserve or incrementally charge the shared memory allowance before growing output buffers. Define the allowance's treatment of temporary buffers and concurrent candidates so callers can rely on it for containment.
Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 58.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the main change: reading embedded subtitle tracks through their file index.
Description check Passed The description directly explains the indexed Matroska and MP4/MOV subtitle reader, packet extraction, caching, validation, and fallback behavior described by the changeset.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 58.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 155 functions across 32 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@silo-triage silo-triage Bot added enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish triaged High-confidence review completed; does not mean fixed, validated, or accepted for release. labels Oct 30, 2026
@macroscopeapp

macroscopeapp Bot commented Oct 30, 2026

Copy link
Copy Markdown

The packet reader is not used by an application request path in this PR, and existing extraction remains source-file based, so no user-visible change is introduced. The current Evidence line says evidence will be published later; please replace it with:

Evidence: none, no user-visible change

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 703e431d04

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread internal/embeddedsub/embeddedsub.go Outdated
Comment on lines +276 to +277
if t.mp4 != nil {
n += int64(len(t.mp4.samples))*sampleSize + int64(len(t.mp4.stsd)+len(t.mp4.edts)+len(t.mp4.tkhd)+len(t.mp4.mvhd))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Account for the retained MP4 moov allocation in the cache budget

For MP4 files, the retained header boxes (mvhd, tkhd, stsd, etc.) are slices into the original moov buffer, so even a small subtitle index keeps the entire movie index alive, including the video and audio sample tables. This estimate counts only the lengths of a few subtitle boxes, and Cache.add uses it to enforce eviction. Consequently, caching files with large movie indexes and relatively few subtitle samples can retain many times the configured memory budget. Clone the boxes that must survive parsing, or account for the shared backing allocation once per index.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛡️ Codex Security Review · Automatically triggered

Here are some automated security review suggestions for this pull request.

Reviewed commit: 703e431d04

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

case IDContentEncodings:
Children(v, func(id uint64, v []byte) {
if id == IDContentEncoding {
t.Encodings = append(t.Encodings, parseContentEncoding(v))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛡️ Codex Security Review · Automatically triggered

P2 Badge Security: Bound nested content encodings before parsing track metadata

When an attacker-controlled MKV reaches a library scan or startup backfill, bound nested ContentEncoding entries before appending them. mediaprobe discards these fields, but a direct ReadMatroskaTracks test with a 2 MiB element and 699,050 empty entries grew the heap by 100 MiB and allocated 202 MiB. The allowed 16 MiB element can retain about 299 MiB in this slice alone, before growth copies; the backfill processes four files concurrently, making process OOM plausible. Use a lightweight track parser or enforce a small entry/allocation limit.

Useful? React with 👍 / 👎.

Comment thread internal/embeddedsub/embeddedsub.go Outdated
Comment on lines +276 to +277
if t.mp4 != nil {
n += int64(len(t.mp4.samples))*sampleSize + int64(len(t.mp4.stsd)+len(t.mp4.edts)+len(t.mp4.tkhd)+len(t.mp4.mvhd))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Performance high

MP4 cache accounting counts selected box lengths, but those subslices retain the entire moov backing allocation returned by readBox, so movies with large audio/video sample tables and small subtitle tables can substantially exceed Cache.maxBytes. Clone the retained boxes into independent allocations or account for the shared backing allocation once per index.

Prompt for LLM

File internal/embeddedsub/embeddedsub.go:

Line 276 to 277:

MP4 cache accounting counts selected box lengths, but those subslices retain the entire moov backing allocation returned by readBox, so movies with large audio/video sample tables and small subtitle tables can substantially exceed Cache.maxBytes. Clone the retained boxes into independent allocations or account for the shared backing allocation once per index.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment thread internal/embeddedsub/matroska_read.go Outdated
Comment on lines +577 to +580
ps, err := s.m.blockPackets(e, at, s.h, &cue)
if err != nil {
s.damage = append(s.damage, err)
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug medium

Error misclassification in clusterScan.match converts ErrTooLarge from blockPackets into DamagedError, causing cues without relative positions to return partial subtitles instead of the documented memory-limit failure. Propagate non-corruption errors through match and step, reserving s.damage for errors matching errCorrupt, as matroskaRead.do already does for direct cue reads.

Prompt for LLM

File internal/embeddedsub/matroska_read.go:

Line 577 to 580:

Error misclassification in clusterScan.match converts ErrTooLarge from blockPackets into DamagedError, causing cues without relative positions to return partial subtitles instead of the documented memory-limit failure. Propagate non-corruption errors through match and step, reserving s.damage for errors matching errCorrupt, as matroskaRead.do already does for direct cue reads.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment on lines +95 to +99
case IDContentEncodings:
Children(v, func(id uint64, v []byte) {
if id == IDContentEncoding {
t.Encodings = append(t.Encodings, parseContentEncoding(v))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Performance high

Unbounded ContentEncoding materialization expands a Tracks element within the existing 16 MiB input limit into hundreds of megabytes of allocations because each three-byte empty ContentEncoding appends a 56-byte record. The mediaprobe refactor now incurs this allocation during scanner track identification despite discarding Encodings; enforce an encoding-count or allocation budget before appending and reject oversized metadata.

Prompt for LLM

File internal/matroska/tracks.go:

Line 95 to 99:

Unbounded ContentEncoding materialization expands a Tracks element within the existing 16 MiB input limit into hundreds of megabytes of allocations because each three-byte empty ContentEncoding appends a 56-byte record. The mediaprobe refactor now incurs this allocation during scanner track identification despite discarding Encodings; enforce an encoding-count or allocation budget before appending and reject oversized metadata.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9bc9f543-1178-41a3-a12e-662e65a1ed7a
Commits

Reviewing files that changed from the base of the PR and between 0225a05 and 703e431.

Files selected for processing: 33
  • docs/architecture/embedded-subtitle-index.md
  • internal/embeddedsub/block.go
  • internal/embeddedsub/cache.go
  • internal/embeddedsub/embeddedsub.go
  • internal/embeddedsub/export_test.go
  • internal/embeddedsub/fadvise_linux.go
  • internal/embeddedsub/fadvise_other.go
  • internal/embeddedsub/file.go
  • internal/embeddedsub/fixture_test.go
  • internal/embeddedsub/golden_test.go
  • internal/embeddedsub/matroska_index.go
  • internal/embeddedsub/matroska_read.go
  • internal/embeddedsub/mks.go
  • internal/embeddedsub/mp4.go
  • internal/embeddedsub/mp4_test.go
  • internal/embeddedsub/mp4_write.go
  • internal/embeddedsub/read.go
  • internal/embeddedsub/read_test.go
  • internal/embeddedsub/tags.go
  • internal/matroska/ebml.go
  • internal/matroska/ids.go
  • internal/matroska/index.go
  • internal/matroska/matroska_test.go
  • internal/matroska/tracks.go
  • internal/matroska/write.go
  • internal/mediaprobe/matroska.go
  • internal/playback/keyframes/coverage.go
  • internal/playback/keyframes/matroska.go
  • internal/playback/keyframes/matroska_test.go
  • internal/playback/subtitle_packets.go
  • internal/playback/subtitle_packets_test.go
  • internal/playback/subtitle_stream.go
  • internal/playback/subtitles.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment thread internal/embeddedsub/mp4.go Resolved
Quick104 and others added 3 commits October 31, 2026 15:29
…allocate

ParseTrackEntry appended every ContentEncoding of an entry, so a Tracks
element within the 16 MiB read limit, made of empty three-byte
encodings, grew into hundreds of megabytes of records, now during
mediaprobe's track scan as well. It keeps the first
MaxContentEncodings (8): real files chain at most two, and the subtitle
reader treats any chain as unsupported.

The subtitle index reader had no bound on TrackEntries either. A Tracks
element with more than 1,000 is malformed there, as in mediaprobe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
An MP4 track's kept boxes (ftyp, mvhd, tkhd, edts, mdhd, hdlr, the media
header, dinf, stsd) were slices of the moov buffer, so a cached index
kept every other track's sample tables alive while the cache counted
only a few small boxes. ReadIndex now copies the boxes a text track
keeps, and the cache counts all of them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… of reporting damage

A cue without a relative position makes the reader walk its cluster for
the block. When that block's packets went over the read's memory limit,
the walk recorded ErrTooLarge as damage, so the read returned the
packets before it with a DamagedError rather than refusing. It now ends
the read with the error, as a block a cue points at directly does; only
damaged blocks count as damage.

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

silo-kody Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3f73be5bc8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if a.ClusterPosition != b.ClusterPosition || a.RelativePosition != b.RelativePosition {
return false
}
return a.RelativePosition >= 0 || a.Time == b.Time

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve distinct simultaneous cues without relative positions

When two subtitle blocks in the same cluster start at the same time and their cues use CueBlockNumber instead of CueRelativePosition, this predicate treats them as duplicates. collectCues discards the block numbers and compacts the two entries into one, so the cluster scan stops after reading the first block. Without a NUMBER_OF_FRAMES tag, the track remains readable and extraction silently drops the second subtitle, such as a simultaneous ASS dialogue or sign. A fixture with two such blocks reproduces one returned packet with no error. Preserve the block number when identifying and matching these cues, or refuse ambiguous entries so callers can fall back.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

Minor · Claim the decompressed frame's budget before allocating it. · matroska_read.go:391-460

internal/embeddedsub/matroska_read.go:391-460
Minor · Stability & Availability · Quick win

Claim the decompressed frame's budget before allocating it.

blockPackets decompresses each frame before it checks the shared budget. payload calls decompress, and readDecompressed can allocate up to maxPacketSize+1 bytes (16 MiB + 1) for one frame. Only after that does m.budget.take(len(data)) run. With a small MaxBytes, a single large zlib frame can allocate far more than MaxBytes before the read returns ErrTooLarge. Concurrent reads can each hold such a transient buffer.

The fix should bound the decompression output by the budget that remains, so the limit applies while the frame is read rather than after it is fully allocated.

Minor · Apply the MP4 edit end to window selection. · mp4.go:420-465

internal/embeddedsub/mp4.go:420-465
Minor · Functional Correctness · Quick win

Apply the MP4 edit end to window selection.

ReadPackets promises packets that show in [from, to). parseEditList discards the normal-rate edit duration, so readMP4Packets can return samples after a finite edit for a window after the edit ends. Whole-track reads intentionally return every packet.

writeMP4 preserves edts, so FFmpeg clips those samples during conversion. This prevents a converted-output mismatch, but it does not make the indexed window result obey its documented contract. Track the edit end and exclude samples outside it for non-whole reads.


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5a90dc8c-979e-4174-a3c1-35a3fc1f6d1e
Commits

Reviewing files that changed from the base of the PR and between 703e431 and 3f73be5.

Files selected for processing: 7
  • internal/embeddedsub/embeddedsub.go
  • internal/embeddedsub/matroska_index.go
  • internal/embeddedsub/matroska_read.go
  • internal/embeddedsub/mp4.go
  • internal/embeddedsub/read_test.go
  • internal/matroska/matroska_test.go
  • internal/matroska/tracks.go
Files skipped from review as they are similar to previous changes: 2
  • internal/embeddedsub/mp4.go
  • internal/embeddedsub/embeddedsub.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

@Quick104

Copy link
Copy Markdown
Contributor Author

Superseded by #3331, which combines this change with the rest of the stack for review.

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

Labels

enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/XXXL 3000+ added + deleted lines (all files); change volume, not priority. triaged High-confidence review completed; does not mean fixed, validated, or accepted for release.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant