Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions internal/api/handlers/playback.go
Original file line number Diff line number Diff line change
Expand Up @@ -786,6 +786,8 @@ func identityRecipeCard(s *playback.Session) playback.RecipeCard {
// Carried so a session reconstructed after a restart re-encodes at the
// layout the client declared instead of silently dropping to stereo.
card.MaxAudioChannels = s.MaxAudioChannels
// And so it does not switch containers mid-stream on reconstruct.
card.RemuxContainer = s.RemuxContainer
return card
default:
return playback.NewDirectRecipeCard(s.ID, s.UserID, s.ProfileID, s.MediaFileID)
Expand Down Expand Up @@ -1983,6 +1985,11 @@ func (h *PlaybackHandler) handleStartPlaybackLegacy(w http.ResponseWriter, r *ht
// Carried onto the session because the progressive remux encodes audio at
// serve time, long after this request. Absent (0) keeps the stereo downmix.
session.MaxAudioChannels = req.MaxAudioChannels
// Same reason, and decided here for the same reason: the client's declared
// container list exists only on this request.
if effectiveFile != nil {
session.RemuxContainer = playback.RemuxOutputContainer(effectiveFile.Container, req.Containers)
}
h.persistSeriesPlaybackPreference(r.Context(), userID, profileID, effectiveFile)

if req.StartPosition != nil {
Expand Down
6 changes: 5 additions & 1 deletion internal/api/handlers/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,11 @@ func (h *StreamHandler) HandleStream(w http.ResponseWriter, r *http.Request) {
session.MaxAudioChannels,
playback.AudioTrackCodecAt(file.AudioTracks, session.AudioTrackIndex),
)
if err := playback.ServeRemuxWithDVMode(w, r, file.FilePath, "mp4", seekSeconds, session.TranscodeAudio, session.AudioTrackIndex, file.PrimaryDVProfile(), session.RemuxDVMode, h.ffmpegPath(), audioChannels); err != nil {
// The container was chosen at /playback/start, where the client's declared
// list was in hand; an empty value is a session that predates the choice
// (or a reconstruct from an older token) and keeps the MP4 default.
remuxFormat := playback.RemuxFFmpegFormat(session.RemuxContainer)
if err := playback.ServeRemuxWithDVMode(w, r, file.FilePath, remuxFormat, seekSeconds, session.TranscodeAudio, session.AudioTrackIndex, file.PrimaryDVProfile(), session.RemuxDVMode, h.ffmpegPath(), audioChannels); err != nil {
h.handleTransportStartFailure(r.Context(), session, file, err)
}

Expand Down
7 changes: 6 additions & 1 deletion internal/playback/recipecard.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,10 @@ type RecipeCard struct {
// MaxAudioChannels mirrors Session.MaxAudioChannels. Without it a remux
// session reconstructed after a restart would silently fall back to the
// stereo default, quietly losing surround the client had declared.
MaxAudioChannels int `json:"max_audio_channels,omitempty"`
MaxAudioChannels int `json:"max_audio_channels,omitempty"`
// RemuxContainer mirrors Session.RemuxContainer. Without it a reconstructed
// remux would switch containers mid-stream, which no player survives.
RemuxContainer string `json:"remux_container,omitempty"`
TargetBitrateKbps int `json:"target_bitrate_kbps,omitempty"`
TotalDuration float64 `json:"total_duration"`
FastStart bool `json:"fast_start,omitempty"`
Expand Down Expand Up @@ -206,6 +209,7 @@ func (c RecipeCard) ToClaims() streamtoken.Claims {
PlayMethod: string(c.PlayMethod),
TranscodeAudio: c.TranscodeAudio,
MaxAudioChannels: c.MaxAudioChannels,
RemuxContainer: c.RemuxContainer,
RemuxDVMode: string(c.RemuxDVMode),
TranscodeNode: c.TranscodeNodeURL,
TranscodeTransportID: c.TranscodeTransportID,
Expand Down Expand Up @@ -254,6 +258,7 @@ func RecipeCardFromClaims(c *streamtoken.Claims) RecipeCard {
PlayMethod: method,
TranscodeAudio: c.TranscodeAudio,
MaxAudioChannels: c.MaxAudioChannels,
RemuxContainer: c.RemuxContainer,
RemuxDVMode: RemuxDVMode(c.RemuxDVMode),
InputPath: c.MediaPath,
OutputSubdir: c.OutputSubdir,
Expand Down
23 changes: 17 additions & 6 deletions internal/playback/remux.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,13 +194,24 @@ func buildRemuxArgs(filePath, outputFormat string, seekSeconds float64, transcod
args = append(args,
"-avoid_negative_ts", "make_zero",
"-f", outputFormat,
// delay_moov lets the MP4 muxer inspect the first audio packet before
// writing codec configuration. empty_moov fails immediately for copied
// E-AC-3/Atmos tracks because their frame size is not known at header time.
"-movflags", "frag_keyframe+delay_moov+default_base_moof",
"pipe:1",
)

// Fragmentation is an MP4 requirement, not a general one. MP4 keeps its
// index in a moov box that a normal write patches at the end, which a
// non-seekable pipe cannot do -- so streaming MP4 means fragmenting it.
// Matroska is streamable as written and needs none of these flags; passing
// movflags to its muxer would just be ignored, but stating the distinction
// keeps the reason visible.
//
// delay_moov lets the MP4 muxer inspect the first audio packet before
// writing codec configuration. empty_moov fails immediately for copied
// E-AC-3/Atmos tracks because their frame size is not known at header time.
if outputFormat == "mp4" {
args = append(args, "-movflags", "frag_keyframe+delay_moov+default_base_moof")
}

args = append(args, "pipe:1")

return args
}

Expand Down Expand Up @@ -323,7 +334,7 @@ func containerMIME(format string) string {
return "video/mp4"
case "webm":
return "video/webm"
case "matroska":
case "matroska", "mkv":
return "video/x-matroska"
case "mpegts":
return "video/mp2t"
Expand Down
85 changes: 85 additions & 0 deletions internal/playback/remux_container.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package playback

import "strings"

// Remux output containers. These are the only formats the progressive remux
// will write, because each has to satisfy two constraints at once: FFmpeg must
// be able to mux it to a non-seekable pipe, and it must carry the codecs a
// remux copies without re-encoding.
const (
RemuxContainerMP4 = "mp4"
RemuxContainerMKV = "mkv"
)

// DefaultRemuxContainer is the fallback when the client's declared containers
// give us nothing better to go on. MP4 is the safest default because every
// client that can play video at all can play it.
const DefaultRemuxContainer = RemuxContainerMP4

// normalizeRemuxContainer maps the spellings clients and probes use onto our
// two canonical names, returning "" for anything we will not write.
//
// webm is deliberately absent. It is a Matroska subset restricted to VP8/VP9/AV1
// plus Vorbis/Opus, so it cannot carry the AC-3 or H.264 a remux copies, and
// choosing it would turn a stream copy into a re-encode.
func normalizeRemuxContainer(container string) string {
switch strings.ToLower(strings.TrimSpace(container)) {
case "mp4", "m4v", "mov", "isom":
return RemuxContainerMP4
case "mkv", "matroska", "x-matroska":
return RemuxContainerMKV
default:
return ""
}
}

// RemuxFFmpegFormat is the `-f` argument for a canonical container name.
// Matroska's muxer is spelled "matroska", not "mkv". An unrecognized or empty
// name yields the MP4 default, so a session predating the container choice --
// or reconstructed from an older token -- behaves exactly as it did before.
func RemuxFFmpegFormat(container string) string {
if normalizeRemuxContainer(container) == RemuxContainerMKV {
return "matroska"
}
return "mp4"
}

// RemuxOutputContainer chooses the container the progressive remux writes.
//
// It prefers to keep the source container when the client declared support for
// it, and falls back to MP4 otherwise. That single rule covers both reasons a
// session remuxes at all:
//
// - The client cannot play the source container. It is therefore not in the
// declared list, so this returns MP4 -- which is what such a session needed
// in the first place.
// - The client can play the container but we still have to rewrite, typically
// to map a specific audio track that direct play cannot select. Here the
// source container is declared, so it is kept.
//
// Keeping the source container in that second case matters beyond tidiness.
// Rewriting into MP4 is not free: MP4 must be fragmented to stream over a pipe
// (it has no seekable moov to patch), and several codecs a remux copies are
// spec-legal in MP4 but unreliable in practice -- AC-3, E-AC-3, DTS and TrueHD
// all sit in that category, which is why remuxAudioCopySafe treats a bare codec
// claim as insufficient evidence for them. Matroska has neither problem: it
// streams unfragmented and carries those codecs unambiguously. So when the
// client has already told us it can demux the source container, changing
// containers only adds failure modes.
//
// Trusting the declared list adds no new trust: Resolve already serves that
// exact container byte-for-byte via direct play when the client claims it (see
// containerOK in Case 1). A client that over-claims a container is already
// broken for direct play, and this does not make it more so.
func RemuxOutputContainer(sourceContainer string, declaredContainers []string) string {
source := normalizeRemuxContainer(sourceContainer)
if source == "" {
return DefaultRemuxContainer
}
for _, declared := range declaredContainers {
if normalizeRemuxContainer(declared) == source {
return source
}
}
return DefaultRemuxContainer
}
100 changes: 100 additions & 0 deletions internal/playback/remux_container_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package playback

import (
"strings"
"testing"
)

func TestRemuxOutputContainer(t *testing.T) {
cases := []struct {
name string
source string
declared []string
want string
}{
// The case this exists for: the client can demux the source container, so
// the remux keeps it instead of rewriting into fragmented MP4. The Tizen
// client declares exactly this list.
{"keeps mkv when declared", "mkv", []string{"mp4", "mpegts", "hls", "mkv"}, RemuxContainerMKV},
// The other reason to remux -- container unsupported -- still gets MP4,
// which is what such a session needed in the first place.
{"mp4 when source container not declared", "mkv", []string{"mp4"}, RemuxContainerMP4},
{"mp4 source stays mp4", "mp4", []string{"mp4", "mkv"}, RemuxContainerMP4},
// A client that declares nothing gets the historical default.
{"no declarations falls back", "mkv", nil, RemuxContainerMP4},
{"empty declarations falls back", "mkv", []string{}, RemuxContainerMP4},
// Spelling differences between probes and clients must not decide this.
{"matroska spelling matches mkv", "matroska", []string{"mkv"}, RemuxContainerMKV},
{"mkv source matches matroska claim", "mkv", []string{"matroska"}, RemuxContainerMKV},
{"case and space tolerant", " MKV ", []string{"MkV"}, RemuxContainerMKV},
{"m4v normalizes to mp4", "m4v", []string{"mp4"}, RemuxContainerMP4},
// Containers we will not write fall back rather than being passed through.
{"avi source falls back", "avi", []string{"avi"}, RemuxContainerMP4},
{"unknown source falls back", "", []string{"mkv"}, RemuxContainerMP4},
// webm is a Matroska subset that cannot carry AC-3 or H.264, so declaring
// it must never redirect an mkv source into it.
{"webm claim does not match mkv source", "mkv", []string{"webm"}, RemuxContainerMP4},
{"webm source falls back", "webm", []string{"webm"}, RemuxContainerMP4},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := RemuxOutputContainer(tc.source, tc.declared); got != tc.want {
t.Errorf("RemuxOutputContainer(%q, %v) = %q, want %q", tc.source, tc.declared, got, tc.want)
}
})
}
}

func TestRemuxFFmpegFormat(t *testing.T) {
if got := RemuxFFmpegFormat(RemuxContainerMKV); got != "matroska" {
t.Errorf("RemuxFFmpegFormat(mkv) = %q, want matroska (the muxer name)", got)
}
if got := RemuxFFmpegFormat(RemuxContainerMP4); got != "mp4" {
t.Errorf("RemuxFFmpegFormat(mp4) = %q, want mp4", got)
}
// An empty container is a session predating the choice, or a reconstruct from
// an older token. It must behave exactly as before.
if got := RemuxFFmpegFormat(""); got != "mp4" {
t.Errorf("RemuxFFmpegFormat(\"\") = %q, want mp4 (back-compat default)", got)
}
if got := RemuxFFmpegFormat("nonsense"); got != "mp4" {
t.Errorf("RemuxFFmpegFormat(nonsense) = %q, want mp4", got)
}
}

// Fragmentation is an MP4 workaround for writing to a pipe. Matroska streams as
// written, and carrying the flags over would misdescribe what we emit.
func TestBuildRemuxArgsFragmentsOnlyMP4(t *testing.T) {
mp4 := strings.Join(buildRemuxArgs("/m.mkv", "mp4", 0, false, 0, 0, false, 2), " ")
if !strings.Contains(mp4, "-movflags frag_keyframe+delay_moov+default_base_moof") {
t.Errorf("MP4 must stay fragmented to stream over a pipe: %s", mp4)
}
if !strings.Contains(mp4, "-f mp4") {
t.Errorf("want -f mp4: %s", mp4)
}

mkv := strings.Join(buildRemuxArgs("/m.mkv", "matroska", 0, false, 0, 0, false, 2), " ")
if strings.Contains(mkv, "-movflags") {
t.Errorf("Matroska needs no fragmentation flags: %s", mkv)
}
if !strings.Contains(mkv, "-f matroska") {
t.Errorf("want -f matroska: %s", mkv)
}
// Both still end at the pipe -- the container choice does not change delivery.
for _, args := range []string{mp4, mkv} {
if !strings.HasSuffix(args, "pipe:1") {
t.Errorf("output must remain pipe:1: %s", args)
}
}
}

func TestContainerMIMEMatroska(t *testing.T) {
for _, name := range []string{"matroska", "mkv"} {
if got := containerMIME(name); got != "video/x-matroska" {
t.Errorf("containerMIME(%q) = %q, want video/x-matroska", name, got)
}
}
if got := containerMIME("mp4"); got != "video/mp4" {
t.Errorf("containerMIME(mp4) = %q, want video/mp4", got)
}
}
6 changes: 6 additions & 0 deletions internal/playback/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ type Session struct {
// because the progressive remux encodes audio at serve time, long after the
// request that declared it. 0 keeps the stereo downmix.
MaxAudioChannels int
// RemuxContainer is the container the progressive remux writes, chosen at
// /playback/start from the source container and the client's declared list.
// Carried for the same reason as MaxAudioChannels: the remux runs at serve
// time, long after the request that declared the capability. Empty means the
// MP4 default.
RemuxContainer string

StreamBitrateKbps int // currently delivered bitrate, when known
TargetResolution string // requested output resolution for transcodes
Expand Down
1 change: 1 addition & 0 deletions internal/playback/transcode_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,7 @@ func (m *TranscodeManager) ReconstructSession(ctx context.Context, sessionID str
TranscodeTransportID: card.TranscodeTransportID,
AudioTrackIndex: card.AudioTrackIndex,
MaxAudioChannels: card.MaxAudioChannels,
RemuxContainer: card.RemuxContainer,
TranscodeAudio: card.TranscodeAudio,
RemuxDVMode: card.RemuxDVMode,
TargetResolution: card.TargetResolution,
Expand Down
8 changes: 7 additions & 1 deletion internal/proxy/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,13 @@ func (s *Server) handleRemux(w http.ResponseWriter, r *http.Request) {
// Stereo: the stream token's recipe carries no channel ceiling, so a
// reconstructed proxy stream keeps the historical downmix rather than
// guessing a layout the client never declared.
_ = playback.ServeRemuxWithDVMode(w, r, claims.MediaPath, "mp4", seekSeconds, claims.TranscodeAudio, claims.AudioTrackIndex, claims.DVProfile, playback.RemuxDVMode(claims.RemuxDVMode), s.watcher.Config().Playback.FFmpegPath, 2)
//
// The container comes from the claims so that the same token yields the same
// container here as on the origin. Serving MP4 for a session the origin
// decided to keep as Matroska would make delivery depend on which server
// answered, which is exactly the kind of difference a mid-stream reconnect
// exposes.
_ = playback.ServeRemuxWithDVMode(w, r, claims.MediaPath, playback.RemuxFFmpegFormat(claims.RemuxContainer), seekSeconds, claims.TranscodeAudio, claims.AudioTrackIndex, claims.DVProfile, playback.RemuxDVMode(claims.RemuxDVMode), s.watcher.Config().Playback.FFmpegPath, 2)
}

func (s *Server) handleTranscodeManifest(w http.ResponseWriter, r *http.Request) {
Expand Down
4 changes: 4 additions & 0 deletions internal/streamtoken/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ type Claims struct {
// MaxAudioChannels is the client's declared channel ceiling, carried so a
// reconstructed remux keeps the layout instead of defaulting to stereo.
MaxAudioChannels int `json:"mac,omitempty"`
// RemuxContainer is the chosen progressive-remux container, carried so a
// reconstructed remux does not silently switch containers mid-stream.
// Empty means the MP4 default.
RemuxContainer string `json:"rmc,omitempty"`
// DVProfile is the file's Dolby Vision profile (0 = none); remux nodes
// use it to strip dangling profile 7 RPUs. Absent in older tokens, which
// decodes as 0 (no strip — the pre-existing behavior).
Expand Down