From 2d08cfec7b0409827f65daa9d2a29c7bdd982391 Mon Sep 17 00:00:00 2001 From: Arturo Mozzon Date: Sat, 13 Jun 2026 11:22:53 +0200 Subject: [PATCH] playback: fix panic when MP4 muxer flushes with no samples (#5867) Co-authored-by: Arturo2511 --- internal/playback/muxer_mp4.go | 2 +- internal/playback/muxer_mp4_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/internal/playback/muxer_mp4.go b/internal/playback/muxer_mp4.go index 1ff669b2..5a2f53bf 100644 --- a/internal/playback/muxer_mp4.go +++ b/internal/playback/muxer_mp4.go @@ -90,7 +90,7 @@ func (w *muxerMP4) writeFinalDTS(dts int64) { } func (w *muxerMP4) flush() error { - if len(w.curTrack.Samples) == 0 || w.curTrack.lastDTS < 0 { + if w.curTrack == nil || len(w.curTrack.Samples) == 0 || w.curTrack.lastDTS < 0 { return recordstore.ErrNoSegmentsFound } diff --git a/internal/playback/muxer_mp4_test.go b/internal/playback/muxer_mp4_test.go index 3727a588..51767d0e 100644 --- a/internal/playback/muxer_mp4_test.go +++ b/internal/playback/muxer_mp4_test.go @@ -6,6 +6,7 @@ import ( "github.com/bluenviron/mediacommon/v2/pkg/formats/fmp4" mcodecs "github.com/bluenviron/mediacommon/v2/pkg/formats/mp4/codecs" + "github.com/bluenviron/mediamtx/internal/recordstore" "github.com/bluenviron/mediamtx/internal/test" "github.com/stretchr/testify/require" ) @@ -57,3 +58,30 @@ func TestMuxerMP4EmptyTracks(t *testing.T) { require.Greater(t, buf.Len(), 0) } + +// Test that flushing without any written sample returns an error instead of panicking +func TestMuxerMP4NoSamples(t *testing.T) { + var buf bytes.Buffer + + mux := &muxerMP4{ + w: &buf, + } + + init := &fmp4.Init{ + Tracks: []*fmp4.InitTrack{ + { + ID: 1, + TimeScale: 90000, + Codec: &mcodecs.H264{ + SPS: test.FormatH264.SPS, + PPS: test.FormatH264.PPS, + }, + }, + }, + } + + mux.writeInit(init) + + err := mux.flush() + require.ErrorIs(t, err, recordstore.ErrNoSegmentsFound) +}