Repository navigation
Conversation
…ys on the picture Some sources encode a 2.39:1 image inside a 1920x1080 frame — Disney+ and Netflix WEB-DLs routinely do. The container, the video track and every metadata field then describe a full-height 16:9 video, and only the pixels reveal the black bars. A client anchoring subtitles to the bottom of that frame draws them inside the bar instead of over the image, which is exactly what Silo's TV client does today. Measure the bars with ffmpeg cropdetect and publish them on the plan's source descriptor as fractions of the frame height, so a client can inset an overlay without knowing the frame's dimensions. Sampling is what makes this trustworthy. One frame cannot tell a bar from the content: a fade to black, a night exterior, or titles over black all look identical to a letterbox. Four samples spread across the runtime are intersected by keeping the SMALLER bar per edge, which is the one present in every frame. Measured on a real 2.39:1 episode, the four samples were 12.78% /13.52%/12.78%/12.78% and the intersection lands on 12.78% — matching (1080 - 1920/2.39) / 2 / 1080 exactly, with the dark-scene sample discarded. Detection never blocks a playback start: a start reads whatever has already been measured and warms the rest in the background, so the first play of a file plans exactly as it does today and later plays carry the geometry. Failure, an unmeasurable source, and "no bars" are all the same absent value, so nothing regresses when ffmpeg is unavailable. Bars below 2% are rounding noise and above 25% are likelier a bad read than a real letterbox; both are refused rather than acted on. Additive per the v1 API rules: new omitempty fields on an existing response, no field renamed, removed or retyped. Follow-up: silo-apple needs the same client-side inset to benefit.
Verifying the feature end to end needs to tell 'measured, no bars' apart from 'never measured'. One line per source, at Info: it fires once per file for the process lifetime, and it carries the fractions and how long the measurement took (580ms on a 1080p WEB-DL over network storage).
The v3 plan already carries the baked-in letterbox on its source descriptor, but the Apple clients do not speak v3 — they decode `playbackSessionResponse`. Without the fractions there, tvOS keys its subtitle overlay to `AVPlayerLayer.videoRect`, which covers the full frame on a 2.39:1-inside-1080p source, and cues land in the black bar. Additive fields on an existing response, omitted when nothing was measured, so older clients are unaffected. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
Two problems with keying measurements on the file path alone. Replacing a file in place — a release upgrade, a re-encode — keeps the path, so the old file's bars would be served forever with nothing a user could do to clear them. The key now includes the file size, which changes on any real replacement. And the map grew one entry per file ever played, which on a long-lived server with a large library is a slow leak. Bounded at 4096 entries, evicted oldest-first: the cost of a wrong eviction is one re-measurement of something nobody has watched in a long time. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
📝 WalkthroughWalkthroughAdds FFmpeg-based letterbox detection with asynchronous caching, then propagates measured top and bottom bar fractions through v3 planning and legacy playback responses. ChangesLetterbox playback integration
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant PlaybackHandler
participant LetterboxCache
participant DetectLetterbox
participant FFmpeg
Client->>PlaybackHandler: Start playback
PlaybackHandler->>LetterboxCache: Lookup media path and size
LetterboxCache->>DetectLetterbox: Warm cache miss asynchronously
DetectLetterbox->>FFmpeg: Run cropdetect samples
DetectLetterbox-->>LetterboxCache: Store measured fractions
PlaybackHandler->>PlaybackHandler: Plan playback with letterbox geometry
PlaybackHandler-->>Client: Return playback source and fractions
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/playback/letterbox_detect.go (1)
270-320: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winBackground measurement is untethered from shutdown and unguarded against panics.
Warm()'s goroutine derives its context fromcontext.Background()(line 291), so background ffmpeg processes are never cancelled on server shutdown/restart — a rolling deploy could leave orphaned ffmpeg child processes behind. There's also norecover()around the goroutine body: an unhandled panic here (e.g. from a future edge case in parsing orexec) terminates the entire process, not just this goroutine, since it runs detached in the background for every uniquely-sized file played.Consider accepting a caller-supplied lifecycle context (so the handler can plumb through an app-shutdown context) and adding a
recover()to keepinflightcleanup safe and the process alive.♻️ Suggested hardening
-func (c *LetterboxCache) Warm(key, inputPath string, durationSeconds float64, frameHeight int) { +func (c *LetterboxCache) Warm(ctx context.Context, key, inputPath string, durationSeconds float64, frameHeight int) { if c == nil || strings.TrimSpace(inputPath) == "" || durationSeconds <= 0 || frameHeight <= 0 { return } ... go func() { + defer func() { + if r := recover(); r != nil { + slog.Error("letterbox measurement panicked", "component", "playback", "input", inputPath, "panic", r) + } + }() // Detached from the request that triggered it: the answer is for the // NEXT play, so a client disconnecting must not cancel the measurement. - ctx, cancel := context.WithTimeout(context.Background(), sampleTimeout*sampleCount) + detachedCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), sampleTimeout*sampleCount) defer cancel() ... - value := DetectLetterbox(ctx, inputPath, durationSeconds, frameHeight, ffmpegPath) + value := DetectLetterbox(detachedCtx, inputPath, durationSeconds, frameHeight, ffmpegPath)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/playback/letterbox_detect.go` around lines 270 - 320, Update LetterboxCache.Warm to accept and use a caller-supplied lifecycle context instead of context.Background(), preserving the timeout while allowing shutdown cancellation. Add panic recovery around the background goroutine so inflight cleanup always occurs and a panic is logged without terminating the process; ensure the key is removed from c.inflight on both normal completion and panic.internal/playback/letterbox_detect_test.go (1)
170-180: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThis test doesn't exercise the planner it describes.
The comment states "the planner must pass a measurement through to the client contract verbatim," but the test only assigns fields directly on a bare
SourceDescriptorV3{}and reads them back — that's tautological (Go field assignment), not a check ofPlanPlaybackV3's actual wiring atplan_v3.golines 90-91. Consider replacing this with a test that callsPlanPlaybackV3with aPlannerInputV3.Letterboxset and asserts the resultingresult.Plan.Sourcefields.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/playback/letterbox_detect_test.go` around lines 170 - 180, The test TestPlannerPublishesLetterboxOnTheSource currently verifies only direct field assignment instead of planner wiring. Replace it with a call to PlanPlaybackV3 using PlannerInputV3.Letterbox populated with the top and bottom measurements, then assert result.Plan.Source preserves both values verbatim.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/playback/letterbox_detect_test.go`:
- Around line 170-180: The test TestPlannerPublishesLetterboxOnTheSource
currently verifies only direct field assignment instead of planner wiring.
Replace it with a call to PlanPlaybackV3 using PlannerInputV3.Letterbox
populated with the top and bottom measurements, then assert result.Plan.Source
preserves both values verbatim.
In `@internal/playback/letterbox_detect.go`:
- Around line 270-320: Update LetterboxCache.Warm to accept and use a
caller-supplied lifecycle context instead of context.Background(), preserving
the timeout while allowing shutdown cancellation. Add panic recovery around the
background goroutine so inflight cleanup always occurs and a panic is logged
without terminating the process; ensure the key is removed from c.inflight on
both normal completion and panic.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c93c9dd5-96f6-433d-9bb4-375f0180d1a9
📒 Files selected for processing (6)
internal/api/handlers/playback.gointernal/api/handlers/playback_v3.gointernal/playback/letterbox_detect.gointernal/playback/letterbox_detect_test.gointernal/playback/plan_v3.gointernal/playback/protocol_v3.go
The background measurement deleted its inflight key only on the success path. Any early return or panic left the key behind, and Warm treats a present key as "already running" — so that file would never be measured again for the life of the process. Released in a defer instead. An unrecovered panic there would also take the server down: the goroutine is detached, so nothing upstream would catch it. A subtitle overlay is not worth that. Also replaces a tautological planner test — it assigned struct fields and read them back — with one that calls PlanPlaybackV3 and asserts the plan carries the measurement. Verified it fails when the wiring in plan_v3.go is removed. Adds a companion test that an unmeasured source omits the fields from the wire entirely, so "not measured" stays distinguishable from a real zero. Reported by CodeRabbit on Silo-Server#483. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK
|
Both nitpicks were fair. Addressed in e338f9e. 1. Background goroutine — fixed, and there was a worse bug underneath it than the one reported. The inflight key was deleted only on the success path. Any early return or panic left it behind, and Added the 2. Shutdown context — skipped, with a reason. The suggested Meanwhile the exposure is bounded: each 3. Tautological test — replaced. Correct, that test asserted Go's assignment operator works. It now calls Added a companion test that an unmeasured source omits the fields from the wire entirely, so a client can distinguish "not measured" from a real zero without a sentinel.
|
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/catalog/provider_id_repo.go (1)
102-116: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winDetect slug-form IDs during cross-item ownership checks.
The local comparisons now accept
1931-slug, but the owner query still requirestmdb_id = "1931". A second item can therefore be assigned1931while another item retains1931-slug, creating duplicate logical ownership.
internal/catalog/provider_id_repo.go#L102-L116: make the owner lookup recognize the same normalized numeric ID (or canonicalize legacy values before enforcing ownership).internal/catalog/provider_id_tmdb_match_test.go#L9-L41: add a repository-level regression creating another item with1931-slugand assert that attaching1931fails without mutation.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/catalog/provider_id_repo.go` around lines 102 - 116, Update the owner lookup in the repository method around sameTMDBID so it compares the normalized numeric TMDB ID, allowing slug-form values such as 1931-slug to conflict with 1931; preserve transactional failure without mutation. In internal/catalog/provider_id_tmdb_match_test.go lines 9-41, add a repository-level regression that creates a second item with 1931-slug, attempts to attach 1931, and asserts the operation fails and makes no mutation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@internal/catalog/provider_id_repo.go`:
- Around line 102-116: Update the owner lookup in the repository method around
sameTMDBID so it compares the normalized numeric TMDB ID, allowing slug-form
values such as 1931-slug to conflict with 1931; preserve transactional failure
without mutation. In internal/catalog/provider_id_tmdb_match_test.go lines 9-41,
add a repository-level regression that creates a second item with 1931-slug,
attempts to attach 1931, and asserts the operation fails and makes no mutation.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 79a15730-bf0a-47ff-b8ec-e56d06290f8d
📒 Files selected for processing (4)
internal/catalog/provider_id_repo.gointernal/catalog/provider_id_tmdb_match_test.gointernal/playback/letterbox_detect.gointernal/playback/letterbox_detect_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/playback/letterbox_detect_test.go
- internal/playback/letterbox_detect.go
5e87027 to
e338f9e
Compare
|
Force-pushed to trim this branch back to the letterbox concern only. Two unrelated fixes had accumulated on it while I was testing against my own deployment; they are now separate PRs:
No letterbox commits changed; the previously reviewed content is intact. |
|
Wondering how this will work for sources where the letterbox changes mid-video? There are multiple occasions where letterbox is used as a visual tool in the media itself. There are others, such as ones filmed in IMAX that have certain scenes that expand to fill the 16x9 frame while other scenes remain 2.39. |
|
Also want to ensure that this only affects Lower Third placement and not Bottom placement |
|
Closing after review because baked-in matte detection should be client-owned. Clients can inspect the actual decoded frames, handle changing aspect ratios, and apply platform-specific video and subtitle layout without adding a lazy process-local server probe or API contract. Android already follows that model; Apple work should do the same. Thanks for exploring and documenting the case. |
Problem
A 2.39:1 image mastered inside a 1920x1080 frame — routine on WEB-DL sources — is a 16:9 video as far as the container, the probe,
SourceDescriptorV3.Width/Height, and every client's video layer are all concerned. The black bars are pixels, not geometry anyone declares.The consequence lands on subtitles: a client anchors cues to the bottom of the video rect, the video rect covers the full frame, and the cues render inside the baked-in bar instead of over the picture. There is no client-side fix, because nothing the client can see distinguishes this source from a genuine 16:9 one.
Approach
Measure it server-side and publish it.
internal/playback/letterbox_detect.goruns ffmpeg'scropdetectat four points spread across the runtime and intersects the results, keeping the smaller bar per edge — one frame cannot tell a bar from a fade to black, a night exterior, or titles over black, but a real baked-in bar is in every frame, so the minimum converges on the truth while transient dark frames drop out. Each edge is measured independently; symmetry is not assumed.Results are published as fractions of frame height, so a client insets its overlay without knowing the frame's dimensions:
SourceDescriptorV3.letterbox_top_fraction/letterbox_bottom_fraction(v3 plan)playbackSessionResponse— the Apple clients do not speak v3, and this is the response they decodeBoth are additive and
omitempty. Absent means "not measured", which is exactly what a failed measurement reports, so every existing client keeps doing what it already did.Guardrails
LetterboxCachereturns what is already known and warms the measurement in the background, detached from the request context so a client disconnect cannot cancel it. The first play of a file plans without geometry — today's behavior — and later plays carry it.PlannerInputV3.Letterboxis supplied by the caller; nothing underinternal/playbackplanning shells out.Known limits / follow-up
Testing
internal/playback/letterbox_detect_test.gocovering the parse (including malformed and self-contradictory output), the intersection, the sanitising thresholds, sample placement, cache-key invalidation, eviction, and the nil/unmeasurable-input paths.go test ./internal/playback/ ./internal/api/handlers/green apart from three pre-existing NVENC-probe failures that also fail on a cleanmain(they probe for NVIDIA hardware and this is a Mac).make lintandmake verify-local-pathsclean for the touched files.(1080 − 1920/2.39) / 2 / 1080— and the subtitles moved off the bar and onto the picture.Client side
mainin my fork).AI-use disclosure
Written by Claude Opus 5 (Claude Code) working with @RXWatcher, who directed the approach, reviewed the change, and ran the end-to-end verification described above.
Summary by CodeRabbit
New Features
Bug Fixes
Maintainer remediation AI disclosure
gpt-5.6-solVerification evidence for the maintainer-assisted commit:
Maintainer merge-conflict resolution AI disclosure
gpt-5.6-solDVRPUStrippableplusLetterboxin all planner calls, andVideoCopyUnsafeplus both letterbox fields inSourceDescriptorV3. No new Standards or Spec finding was introduced; the six prior report-only Standards observations remain unchanged.Verification evidence for merge commits
4c3b636danda95766e2: