Repository navigation
fix(playback): select a playable audio track instead of re-encoding - #151
Conversation
Three related audio fixes, all pointing the same way: prefer choosing the right track over re-encoding the wrong one. Selecting a playable track adjustPlaybackForSelectedAudio promoted direct play to remux when the selected track's codec was undecodable, then re-encoded that track. On a Blu-ray remux whose default is TrueHD 7.1 that meant a lossless->AAC encode and a stereo downmix, while the same file carried an AC-3 5.1 companion in the same language sitting unused. Copying the companion beats re-encoding on every axis: no CPU, no quality loss, and surround survives. SelectClientPlayableAudioTrack picks the best decodable track, preferring claimed codecs, then the originally selected language, then the most channels within the client's declared ceiling, then lowest index for determinism. Re-encoding remains the fallback when nothing qualifies. It never overrides an instruction. An explicit audio_track_index is the user's choice, and silently playing different audio than they asked for is worse than re-encoding what they picked -- so re-selection only fills in for a default the client cannot decode. Two existing tests caught an earlier version of this that did override an explicit selection; the guard keys off whether audio_track_index was sent at all. AC-3 family copies on a plain claim #148 required declared sink passthrough before copying AC-3/E-AC-3 into MP4. That was over-restrictive: Samsung reports AC-3 on all models and E-AC-3 on 2018+, and Apple platforms handle both, so a plain codecs_audio claim is evidence enough and the gate only forced needless re-encodes -- including of the very companion track the selector now picks. DTS and TrueHD stay evidence-gated: Tizen reports no DTS decode, and TrueHD in MP4 is unsupported essentially everywhere. E-AC-3 is never an encode target Tizen accepts E-AC-3 for direct play but not for transcode. A source E-AC-3 track still passes through untouched via the copy path, which is that direct-play route, but an eac3 *target* now emits AC-3 instead: same channel layout, broader hardware decode support, and no risk of silent audio on the devices that asked for surround. Two of my own tests from #148/#149 asserted the over-restrictive behavior and were recalibrated rather than worked around, with DTS standing in for the fragile set.
|
Bugbot is not enabled for your account, so this pull request was not reviewed. Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs. |
|
Warning Review limit reached
Next review available in: 30 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (7)
📝 WalkthroughWalkthroughPlayback now selects client-decodable audio tracks when permitted, propagates updated track indices through playback resolution, refines remux safety by codec family, and encodes E-AC-3 targets as AC-3. ChangesAudio playback compatibility
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant PlaybackHandler
participant SelectClientPlayableAudioTrack
participant PlaybackResolver
Client->>PlaybackHandler: request playback with capabilities
PlaybackHandler->>SelectClientPlayableAudioTrack: provide audio tracks and codec claims
SelectClientPlayableAudioTrack-->>PlaybackHandler: return selected audio track index
PlaybackHandler->>PlaybackResolver: resolve playback method and audio handling
PlaybackResolver-->>PlaybackHandler: return remux or transcode decision
PlaybackHandler-->>Client: start playback with resolved audio selection
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
internal/playback/audio_select.go (1)
260-261: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueLocal
langMatchshadows the package-levellangMatchfunction.
langMatch := preferredLang == "" || track.Language == "" || langMatch(track.Language, preferredLang)declares a local bool that shadowsfunc langMatch(line 24). This compiles correctly — Go's short-var-decl scoping means the RHS call still resolves to the outer function — but it's confusing on a re-read since the same identifier means two different things a few lines apart.♻️ Suggested rename for clarity
- langMatch := preferredLang == "" || track.Language == "" || + langMatchesPreferred := preferredLang == "" || track.Language == "" || langMatch(track.Language, preferredLang) if best < 0 || - (langMatch && !bestLangMatch) || - (langMatch == bestLangMatch && track.Channels > bestChannels) { - best, bestLangMatch, bestChannels = i, langMatch, track.Channels + (langMatchesPreferred && !bestLangMatch) || + (langMatchesPreferred == bestLangMatch && track.Channels > bestChannels) { + best, bestLangMatch, bestChannels = i, langMatchesPreferred, track.Channels }🤖 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/audio_select.go` around lines 260 - 261, Rename the local boolean declared in the track-selection logic to avoid shadowing the package-level langMatch function, and update its uses in the surrounding condition accordingly. Keep the function call resolving to the existing package-level langMatch unchanged.internal/api/handlers/playback.go (1)
1145-1166: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDead store:
selectedTrackreassigned at line 1163 but never read again.After the reselection block updates
selectedTrack = file.AudioTracks[idx], nothing downstream in the function readsselectedTrackagain (onlyaudioSupported/audioTrackIndexare used). Harmless today, but worth removing to avoid confusion or a future accidental reliance on a value that looks meaningful but isn't used.♻️ Suggested cleanup
if idx, ok := playback.SelectClientPlayableAudioTrack( file.AudioTracks, audioTrackIndex, req.CodecsAudio, req.MaxAudioChannels, ); ok { audioTrackIndex = idx - selectedTrack = file.AudioTracks[idx] audioSupported = true }🤖 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/api/handlers/playback.go` around lines 1145 - 1166, Remove the dead reassignment of selectedTrack inside the SelectClientPlayableAudioTrack success branch. Keep updating audioTrackIndex and audioSupported as currently required, and leave the initial selectedTrack assignment unchanged for the earlier codec-support check.
🤖 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.
Inline comments:
In `@internal/api/handlers/playback.go`:
- Around line 1183-1188: Update the default branch of the playback
method-selection logic to return !audioSupported instead of the stale
transcodeAudio parameter, matching the PlayRemux branch after audio-track
reselection. Preserve the existing method and audioTrackIndex returns.
In `@internal/playback/transcode_hevc_tag_test.go`:
- Around line 116-128: Strengthen TestEAC3IsNeverAnEncodeTarget by asserting
that the AC-3 fallback also emits the intended supported channel limit for the
8-channel TrueHD fixture. If the limit is missing, update appendAudioArgs to add
the AC-3 channel cap while preserving the existing codec-selection assertions.
In `@internal/playback/transcode.go`:
- Around line 805-814: Cap the AC-3 fallback in the audio encoding branch of
internal/playback/transcode.go:805-814 to six channels using the existing
channel-handling convention, while preserving the AC-3 codec and bitrate. Update
the 8-channel case in internal/playback/transcode_hevc_tag_test.go:116-128 to
assert that the emitted ffmpeg arguments include this six-channel cap.
---
Nitpick comments:
In `@internal/api/handlers/playback.go`:
- Around line 1145-1166: Remove the dead reassignment of selectedTrack inside
the SelectClientPlayableAudioTrack success branch. Keep updating audioTrackIndex
and audioSupported as currently required, and leave the initial selectedTrack
assignment unchanged for the earlier codec-support check.
In `@internal/playback/audio_select.go`:
- Around line 260-261: Rename the local boolean declared in the track-selection
logic to avoid shadowing the package-level langMatch function, and update its
uses in the surrounding condition accordingly. Keep the function call resolving
to the existing package-level langMatch unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 3f5e2a43-80d5-42de-974c-5f29943f7d28
📒 Files selected for processing (7)
internal/api/handlers/playback.gointernal/playback/audio_select.gointernal/playback/audio_select_internal_test.gointernal/playback/resolver.gointernal/playback/resolver_test.gointernal/playback/transcode.gointernal/playback/transcode_hevc_tag_test.go
selectedTrack was only ever read for the codec-support check that runs before the re-selection block, so reassigning it after switching tracks was dead -- golangci-lint's wastedassign caught it. Collapse the variable into the one call that uses it. No behavior change: audioTrackIndex and audioSupported already carry the re-selection result into the switch below. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…hannels Two related channel-layout bugs on the audio encode path. SourceAudioChannels was declared on TranscodeOpts and read by EffectiveAudioChannels, but never assigned anywhere in production code -- so it was always 0. That silently disabled the "never exceed the source" rule: a stereo track played by a client declaring max_audio_channels=6 was upmixed into 5.1 AAC, inventing four channels and spending bitrate to say nothing. It is now threaded from the probed track on both the legacy and v3 transcode paths, local and remote, with a matching additive field on the transcode-node request. The AC-3 branch emitted "-c:a ac3 -b:a 448k" with no channel argument at all, so it honored neither the source count nor the client's declared ceiling -- the same max_audio_channels contract the AAC path implements. A device reporting a stereo sink got 5.1, and a stereo source got a 448k bitstream sized for surround. EffectiveAC3Channels now caps at the source, the client ceiling, and the encoder's own limit, and the bitrate follows the layout. That encoder limit is measured, not assumed: `ffmpeg -h encoder=ac3` in our own image lists 5.1 as the widest supported layout, with no 6.1 or 7.1 mode. Worth recording what does *not* happen -- an 8-channel input does not fail. FFmpeg's filter-graph negotiation already downmixes it to 5.1(side) at 448k, verified by encoding a synthetic 7.1 source and probing the result. The cap is still worth stating explicitly, because relying on negotiation is relying on it staying put, and negotiation cannot know the client's ceiling. Where we know enough to choose the layout we choose it; where we do not, EffectiveAC3Channels returns 0 and omits -ac so negotiation still handles it -- naming 5.1 on an unknown source would upmix one that turns out to be stereo. EffectiveAC3Channels deliberately does not reuse EffectiveAudioChannels: that function's fragile-lossless rule collapses TrueHD to stereo, which is right for AAC (the stall it guards is in the TrueHD->AAC path) and wrong here, where an AC-3 target exists precisely to carry surround to a receiver. Not addressed, and pre-existing: RecipeCard mirrors the byte-affecting TranscodeOpts fields but carries neither source audio codec nor channel count, so a session reconstructed after a restart loses both the layout decision and the TrueHD stereo safety. Fixing it means either growing every segment JWT or re-deriving from the media file; the deferred path keeps today's behavior (channels 0 -> negotiation), so this change does not make it worse. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Three related audio fixes, all pointing the same way: prefer choosing the right track over re-encoding the wrong one.
Selecting a playable track
adjustPlaybackForSelectedAudiopromoted direct play → remux when the selected track's codec was undecodable, then re-encoded that track:On the file under test that meant a lossless TrueHD 7.1 → AAC encode and a stereo downmix, while the same file carried an unused AC-3 5.1 companion in the same language:
Copying track 2 beats re-encoding track 0 on every axis: no CPU, no quality loss, and 5.1 survives instead of collapsing to stereo.
SelectClientPlayableAudioTrackprefers, strongest first: codecs the client claims → the originally selected language → most channels within the declared ceiling → lowest index for determinism. Re-encoding stays the fallback when nothing qualifies.It never overrides an instruction. An explicit
audio_track_indexis the user's choice, and silently playing different audio than they asked for is worse than re-encoding what they picked — so re-selection only fills in for a default the client cannot decode. Two existing tests (ExplicitDirectPromotesSelectedAudio…,AutoDirectIgnoresApplePreserveFlag…) caught an earlier version of this that did override an explicit selection; the guard now keys off whetheraudio_track_indexwas sent at all.AC-3 family copies on a plain claim
#148 required declared sink passthrough before copying AC-3/E-AC-3 into MP4. That was over-restrictive — Samsung reports AC-3 on all models and E-AC-3 on 2018+, Apple handles both — so a plain
codecs_audioclaim is evidence enough. The old gate forced needless re-encodes, including of the very companion track the selector now picks.DTS and TrueHD stay evidence-gated: Tizen reports no DTS decode, and TrueHD in MP4 is unsupported essentially everywhere.
E-AC-3 is never an encode target
Tizen accepts E-AC-3 for direct play but not for transcode. A source E-AC-3 track still passes through untouched via the
copypath — that's the direct-play route — but aneac3target now emits AC-3: same channel layout, broader hardware decode, and no risk of silent audio on precisely the devices that asked for surround.Test recalibration
Two of my own tests from #148/#149 asserted the over-restrictive AC-3 behaviour. They're recalibrated rather than worked around, with DTS standing in for the fragile set.
internal/playbackfully green;api,middleware,proxy,jellycompatgreen.go vet,gofmt,misspellclean. The singleinternal/api/handlersfailure (TestHandleReplanPlaybackV3SeekFailureRecoveryNeverChangesMediaVersion) is pre-existing onmain.🤖 Generated with Claude Code
Summary by CodeRabbit