Repository navigation
Conversation
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 Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsAdvisory findings (1)ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Walkthrough
Merge Risk:
|
|
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:
Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
There was a problem hiding this comment.
💡 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".
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
🛡️ 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)) |
There was a problem hiding this comment.
🛡️ Codex Security Review · Automatically triggered
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 👍 / 👎.
| 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)) |
There was a problem hiding this comment.
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.
| ps, err := s.m.blockPackets(e, at, s.h, &cue) | ||
| if err != nil { | ||
| s.damage = append(s.damage, err) | ||
| return |
There was a problem hiding this comment.
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.
| case IDContentEncodings: | ||
| Children(v, func(id uint64, v []byte) { | ||
| if id == IDContentEncoding { | ||
| t.Encodings = append(t.Encodings, parseContentEncoding(v)) | ||
| } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
Files selected for processing: 33-
docs/architecture/embedded-subtitle-index.mdinternal/embeddedsub/block.gointernal/embeddedsub/cache.gointernal/embeddedsub/embeddedsub.gointernal/embeddedsub/export_test.gointernal/embeddedsub/fadvise_linux.gointernal/embeddedsub/fadvise_other.gointernal/embeddedsub/file.gointernal/embeddedsub/fixture_test.gointernal/embeddedsub/golden_test.gointernal/embeddedsub/matroska_index.gointernal/embeddedsub/matroska_read.gointernal/embeddedsub/mks.gointernal/embeddedsub/mp4.gointernal/embeddedsub/mp4_test.gointernal/embeddedsub/mp4_write.gointernal/embeddedsub/read.gointernal/embeddedsub/read_test.gointernal/embeddedsub/tags.gointernal/matroska/ebml.gointernal/matroska/ids.gointernal/matroska/index.gointernal/matroska/matroska_test.gointernal/matroska/tracks.gointernal/matroska/write.gointernal/mediaprobe/matroska.gointernal/playback/keyframes/coverage.gointernal/playback/keyframes/matroska.gointernal/playback/keyframes/matroska_test.gointernal/playback/subtitle_packets.gointernal/playback/subtitle_packets_test.gointernal/playback/subtitle_stream.gointernal/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.
-
…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 — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

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.
blockPacketsdecompresses each frame before it checks the shared budget.payloadcallsdecompress, andreadDecompressedcan allocate up tomaxPacketSize+1bytes (16 MiB + 1) for one frame. Only after that doesm.budget.take(len(data))run. With a smallMaxBytes, a single large zlib frame can allocate far more thanMaxBytesbefore the read returnsErrTooLarge. 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.
ReadPacketspromises packets that show in[from, to).parseEditListdiscards the normal-rate edit duration, soreadMP4Packetscan return samples after a finite edit for a window after the edit ends. Whole-track reads intentionally return every packet.
writeMP4preservesedts, 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
Files selected for processing: 7-
internal/embeddedsub/embeddedsub.gointernal/embeddedsub/matroska_index.gointernal/embeddedsub/matroska_read.gointernal/embeddedsub/mp4.gointernal/embeddedsub/read_test.gointernal/matroska/matroska_test.gointernal/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.
-
|
Superseded by #3331, which combines this change with the rest of the stack for review. |
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:
main.Approach
internal/embeddedsubreads a file's subtitle tracks from its Matroska header, seek heads, Info, Tracks, Tags and Cues, or from its MP4/MOVmoovbox, without reading media data (ReadIndex). It rates each track's index as complete, unknown, incomplete or absent, using theNUMBER_OF_FRAMEStag where there is one.ReadPacketsreads one track's packets in a time window or whole, with up to 16 reads in flight.WriteStreamwrites those packets as a subtitle-only Matroska or MP4 stream, andExtractSubtitlePacketsWithFormatfeeds 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.ErrMalformed,DamagedError). One read holds at most 256 MiB of packets, and one block or sample at most 16 MiB.Cachekeeps indexes in memory, keyed by path, size and modification time.internal/matroskanow holds the EBML parsing thatmediaprobeandplayback/keyframeseach 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.mddescribes 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
Validation
CueRelativePosition, a later start time, truncated files, and files without Cues.go build ./...andgo vet ./...on this branch: pass. Cross-compiles for darwin and windows.maintoo (TestPlaybackInfoWithoutStripOrToneMapStillHasNoRoute,TestPlaybackInfoSkipsStripWhenRPUCannotBeStripped).make verify-actionlintrejects the local binary's version string;actionlintitself 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/matroskamove does change the codemediaprobeand keyframe planning run on every Matroska file; their existing tests pass.Checklist
AI Disclosure
🤖 Generated with Claude Code
Note
Add indexed embedded subtitle reading for Matroska and MP4 tracks
embeddedsubpackage: 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.ReadPacketssupports whole-track and time-window reads with configurable concurrency, lookback, and a shared byte budget.NewCache,Cache.Index) keyed by path, size, and modification time, with shared in-flight loads.SubtitlePacketInputfeeds a serialized subtitle stream to FFmpeg's stdin, so extraction no longer requires reading the source media file.internal/playback/keyframesandinternal/mediaprobeinto a sharedinternal/matroskapackage.parseInfoin matroska.go now ignores timestamp-scale values abovemath.MaxInt64instead of truncating them; malformed Matroska cues clear all tracks' cues; unsupported containers and edit-list layouts returnErrNotSupportedContainer/unsupported-track errors.Macroscope summarized 3f73be5.