diff --git a/conf/configuration.go b/conf/configuration.go index efa9cbf9a..03fc9978d 100644 --- a/conf/configuration.go +++ b/conf/configuration.go @@ -161,6 +161,7 @@ type configOptions struct { DevExternalArtistFetchMultiplier float64 DevPreserveUnicodeInExternalCalls bool DevEnableMediaFileProbe bool + DevMatchEstimatedContentLength bool DevAPIv1 bool } @@ -1152,6 +1153,7 @@ func setViperDefaults() { viper.SetDefault("devexternalartistfetchmultiplier", 1.5) viper.SetDefault("devpreserveunicodeinexternalcalls", false) viper.SetDefault("devenablemediafileprobe", true) + viper.SetDefault("devmatchestimatedcontentlength", true) } func init() { diff --git a/core/stream/media_streamer.go b/core/stream/media_streamer.go index c250b0c4e..2430f2a52 100644 --- a/core/stream/media_streamer.go +++ b/core/stream/media_streamer.go @@ -80,7 +80,7 @@ func (ms *mediaStreamer) NewStream(ctx context.Context, mf *model.MediaFile, req format = "raw" bitRate = 0 } - s := &Stream{ctx: ctx, mf: mf, format: format, bitRate: bitRate} + s := &Stream{ctx: ctx, mf: mf, format: format, bitRate: bitRate, offset: req.Offset} filePath := mf.AbsolutePath() if format == "raw" { @@ -137,6 +137,7 @@ type Stream struct { mf *model.MediaFile bitRate int format string + offset int io.ReadCloser io.Seeker } @@ -146,16 +147,24 @@ func (s *Stream) Duration() float32 { return s.mf.Duration } func (s *Stream) ContentType() string { return mime.TypeByExtension("." + s.format) } func (s *Stream) Name() string { return s.mf.Title + "." + s.format } func (s *Stream) ModTime() time.Time { return s.mf.UpdatedAt } -func (s *Stream) EstimatedContentLength() int { - return int(s.mf.Duration * float32(s.bitRate) / 8 * 1024) + +// EstimatedContentLength returns the expected size of the transcoded output, from the part of the track +// after the requested offset. It returns 0 when the track has no duration left to estimate from. +func (s *Stream) EstimatedContentLength() int64 { + remaining := max(float64(s.mf.Duration)-float64(max(s.offset, 0)), 0) + return int64(remaining * float64(s.bitRate) * 1000 / 8) } // Serve writes the stream to the HTTP response. For seekable streams it uses http.ServeContent // (supporting range requests). For non-seekable streams it writes directly and logs any errors. -// Returns the number of bytes written and an error only when it fails with 0 bytes written +// Returns the number of bytes written, or -1 when it does not count them (http.ServeContent and HEAD +// requests), and an error only when it fails with 0 bytes written // (meaning the HTTP 200 status has not been flushed yet and the caller can still send an error response). // Once bytes are on the wire it panics with http.ErrAbortHandler instead, aborting the response. // Empty output (0 bytes, no error) is logged but not treated as an error. +// With estimateContentLength=true, a non-seekable stream declares an estimated Content-Length. With +// DevMatchEstimatedContentLength, the body is also cut or zero-padded to match it, so clients never +// see a body that disagrees with the header. func (s *Stream) Serve(ctx context.Context, w http.ResponseWriter, r *http.Request) (int64, error) { if s.Seekable() { http.ServeContent(w, r, s.Name(), s.ModTime(), s) @@ -165,19 +174,31 @@ func (s *Stream) Serve(ctx context.Context, w http.ResponseWriter, r *http.Reque w.Header().Set("Accept-Ranges", "none") w.Header().Set("Content-Type", s.ContentType()) + // limit > 0 only when the body must match the declared Content-Length. + var limit int64 if req.Params(r).BoolOr("estimateContentLength", false) { - length := strconv.Itoa(s.EstimatedContentLength()) - log.Trace(ctx, "Estimated content-length", "contentLength", length) - w.Header().Set("Content-Length", length) + length := s.EstimatedContentLength() + if conf.Server.DevMatchEstimatedContentLength { + limit = length + } + if length > 0 { + log.Trace(ctx, "Estimated content-length", "contentLength", length) + w.Header().Set("Content-Length", strconv.FormatInt(length, 10)) + } } if r.Method == http.MethodHead { go func() { _, _ = io.Copy(io.Discard, s) }() - return 0, nil + return -1, nil + } + + var src io.Reader = s + if limit > 0 { + src = io.LimitReader(s, limit) } id := s.mf.ID - c, err := io.Copy(w, s) + c, err := io.Copy(w, src) if err != nil { log.Error(ctx, "Error sending transcoded file", "id", id, err) if c == 0 { @@ -188,15 +209,41 @@ func (s *Stream) Serve(ctx context.Context, w http.ResponseWriter, r *http.Reque panic(http.ErrAbortHandler) } if c == 0 { + // Nothing is sent yet, so drop the estimate instead of padding a body that holds no audio. + w.Header().Del("Content-Length") log.Error(ctx, "Transcoding returned empty output, ffmpeg may have failed. "+ "Check that ffmpeg supports the requested codec. Enable Trace logging for ffmpeg stderr details", "id", id, "format", s.ContentType()) - } else { - log.Trace(ctx, "Success sending transcoded file", "id", id, "size", c) + return 0, nil } + switch { + case c < limit: + padding, err := io.CopyN(w, zeroReader{}, limit-c) + if err != nil { + log.Debug(ctx, "Error padding transcoded file to the estimated length", "id", id, err) + } + c += padding + case limit > 0: + // The body is complete. Send it now, then read the rest, so a transcode tied to this request + // can finish and complete its cache entry. That only holds while the client keeps the + // connection open: a hang-up cancels the request, and cutBytes is then a lower bound. + _ = http.NewResponseController(w).Flush() + if cut, _ := io.Copy(io.Discard, s); cut > 0 { + log.Warn(ctx, "Transcoded output is longer than the estimated length, the end of the file was cut", + "id", id, "estimatedLength", limit, "cutBytes", cut) + } + } + log.Trace(ctx, "Success sending transcoded file", "id", id, "size", c) return c, nil } +type zeroReader struct{} + +func (zeroReader) Read(p []byte) (int, error) { + clear(p) + return len(p), nil +} + // NewStream creates a non-seekable Stream from the given components. func NewStream(mf *model.MediaFile, format string, bitRate int, r io.ReadCloser) *Stream { return &Stream{ diff --git a/core/stream/media_streamer_test.go b/core/stream/media_streamer_test.go index 5a4bcd480..8d29d7f69 100644 --- a/core/stream/media_streamer_test.go +++ b/core/stream/media_streamer_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "os" + "strconv" "testing/iotest" "time" @@ -183,6 +184,119 @@ var _ = Describe("MediaStreamer", func() { _, err = io.ReadAll(resp.Body) Expect(err).To(HaveOccurred()) }) + + Context("with estimateContentLength=true", func() { + // 10s at 128kbps, where a kbps is 1000 bits per second. + const estimate = 10 * 128 * 1000 / 8 + + BeforeEach(func() { + mf.Duration = 10 + }) + + newStream := func(src []byte) *stream.Stream { + return stream.NewStream(mf, "mp3", 128, io.NopCloser(bytes.NewReader(src))) + } + serve := func(s *stream.Stream) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodGet, "/?estimateContentLength=true", nil) + _, err := s.Serve(ctx, w, r) + Expect(err).ToNot(HaveOccurred()) + return w + } + declaredLength := func(w *httptest.ResponseRecorder) int { + declared, err := strconv.Atoi(w.Header().Get("Content-Length")) + Expect(err).ToNot(HaveOccurred(), "Content-Length must be declared") + return declared + } + + It("pads output shorter than the estimate with zeros up to the declared length", func() { + src := bytes.Repeat([]byte("a"), 1000) + w := serve(newStream(src)) + + declared, body := declaredLength(w), w.Body.Bytes() + Expect(body).To(HaveLen(declared)) + Expect(body[:len(src)]).To(Equal(src)) + Expect(body[len(src):]).To(Equal(make([]byte, declared-len(src)))) + }) + + It("truncates output longer than the estimate at the declared length", func() { + src := bytes.Repeat([]byte("a"), 2*estimate) + w := serve(newStream(src)) + + declared := declaredLength(w) + Expect(declared).To(BeNumerically("<", len(src))) + Expect(w.Body.Bytes()).To(Equal(src[:declared])) + }) + + It("reads the rest of output longer than the estimate, so a transcode tied to the request can finish", func() { + src := bytes.NewReader(bytes.Repeat([]byte("a"), 2*estimate)) + serve(stream.NewStream(mf, "mp3", 128, io.NopCloser(src))) + + Expect(src.Len()).To(BeZero()) + }) + + It("declares duration times bitrate, with no headroom", func() { + w := serve(newStream(bytes.Repeat([]byte("a"), 1000))) + + Expect(declaredLength(w)).To(Equal(estimate)) + }) + + It("estimates only the part of the track after the requested offset", func() { + full, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 128}) + Expect(err).ToNot(HaveOccurred()) + DeferCleanup(full.Close) + half, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 128, Offset: 5}) + Expect(err).ToNot(HaveOccurred()) + DeferCleanup(half.Close) + + Expect(half.EstimatedContentLength()).To(BeNumerically("~", full.EstimatedContentLength()/2, 1)) + }) + + It("estimates the whole track for a negative offset, as the transcode starts from the beginning", func() { + s, err := streamer.NewStream(ctx, mf, stream.Request{Format: "mp3", BitRate: 128, Offset: -1000000000}) + Expect(err).ToNot(HaveOccurred()) + DeferCleanup(s.Close) + + Expect(s.EstimatedContentLength()).To(Equal(int64(estimate))) + }) + + It("does not declare a Content-Length when the track has no duration", func() { + mf.Duration = 0 + src := []byte("some audio") + w := serve(newStream(src)) + + Expect(w.Header().Values("Content-Length")).To(BeEmpty()) + Expect(w.Body.Bytes()).To(Equal(src)) + }) + + It("drops the declared length when the transcoder produces no output", func() { + w := serve(newStream(nil)) + + Expect(w.Header().Values("Content-Length")).To(BeEmpty()) + Expect(w.Body.Len()).To(BeZero()) + }) + + Context("with DevMatchEstimatedContentLength=false", func() { + BeforeEach(func() { + conf.Server.DevMatchEstimatedContentLength = false + }) + + It("declares the estimate and sends shorter output as is, without padding", func() { + src := bytes.Repeat([]byte("a"), 1000) + w := serve(newStream(src)) + + Expect(declaredLength(w)).To(Equal(estimate)) + Expect(w.Body.Bytes()).To(Equal(src)) + }) + + It("does not cut output longer than the estimate", func() { + src := bytes.Repeat([]byte("a"), 2*estimate) + w := serve(newStream(src)) + + Expect(w.Body.Bytes()).To(Equal(src)) + }) + }) + }) }) }) diff --git a/server/public/handle_streams_test.go b/server/public/handle_streams_test.go index 965bc7e05..e8badbae8 100644 --- a/server/public/handle_streams_test.go +++ b/server/public/handle_streams_test.go @@ -3,8 +3,10 @@ package public import ( "context" "errors" + "io" "net/http" "net/http/httptest" + "strings" "time" "github.com/go-chi/jwtauth/v5" @@ -17,13 +19,17 @@ import ( ) type mockStreamer struct { - req stream.Request - called bool + req stream.Request + called bool + newStream func(*model.MediaFile) *stream.Stream } -func (m *mockStreamer) NewStream(_ context.Context, _ *model.MediaFile, r stream.Request) (*stream.Stream, error) { +func (m *mockStreamer) NewStream(_ context.Context, mf *model.MediaFile, r stream.Request) (*stream.Stream, error) { m.called = true m.req = r + if m.newStream != nil { + return m.newStream(mf), nil + } return nil, errors.New("mock: not implemented") } @@ -211,6 +217,24 @@ var _ = Describe("handleStream", func() { Expect(streamer.called).To(BeTrue()) }) + It("returns 200 on HEAD for a transcode that is not cached yet", func() { + shareOwnedBy( + model.User{ID: "owner1", UserName: "owner1", IsAdmin: true}, + model.MediaFile{ID: "mf-123", Title: "Test Song"}, + ) + streamer.newStream = func(mf *model.MediaFile) *stream.Stream { + return stream.NewStream(mf, "mp3", 192, io.NopCloser(strings.NewReader("transcoded audio"))) + } + + claims := auth.Claims{ID: "mf-123", Format: "mp3", BitRate: 192, ShareID: "share123"} + token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims) + r := httptest.NewRequest(http.MethodHead, "/public/s/token?%3Aid="+token, nil) + w := httptest.NewRecorder() + pub.handleStream(w, r) + + Expect(w.Code).To(Equal(http.StatusOK)) + }) + It("returns 400 for an expired token", func() { claims := auth.Claims{ID: "mf-123", ShareID: "share123"} token, _ := auth.CreateExpiringPublicToken(time.Now().Add(-time.Hour), claims) diff --git a/server/subsonic/transcode_test.go b/server/subsonic/transcode_test.go index 1f2fdfcef..821fd423d 100644 --- a/server/subsonic/transcode_test.go +++ b/server/subsonic/transcode_test.go @@ -5,9 +5,11 @@ import ( "context" "errors" "fmt" + "io" "io/fs" "net/http" "net/http/httptest" + "strconv" "github.com/navidrome/navidrome/core/ffmpeg" "github.com/navidrome/navidrome/core/stream" @@ -546,6 +548,60 @@ var _ = Describe("Transcode endpoints", func() { Expect(fakeStreamer.captured.Channels).To(Equal(2)) Expect(fakeStreamer.captured.Offset).To(Equal(10)) }) + + Describe("serving the stream", func() { + transcoded := []byte("transcoded audio") + + serve := func(method string, newStream func(*model.MediaFile) *stream.Stream, params ...string) { + router = New(ds, nil, &fakeMediaStreamer{newStream: newStream}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, mockTD, nil) + mockMFRepo.SetData(model.MediaFiles{{ID: "song-1", Title: "Song", Duration: 10}}) + mockTD.resolvedReq = stream.Request{Format: "mp3", BitRate: 128} + r := newGetRequest(append([]string{"mediaId=song-1", "mediaType=song", "transcodeParams=valid-token"}, params...)...) + r.Method = method + _, _ = router.GetTranscodeStream(w, r) + } + inProgress := func(mf *model.MediaFile) *stream.Stream { + return stream.NewStream(mf, "mp3", 128, io.NopCloser(bytes.NewReader(transcoded))) + } + completed := func(mf *model.MediaFile) *stream.Stream { + rs := bytes.NewReader(transcoded) + s := stream.NewStream(mf, "mp3", 128, io.NopCloser(rs)) + s.Seeker = rs + return s + } + + It("returns 200 on HEAD for a transcode that is not cached yet", func() { + serve(http.MethodHead, inProgress) + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(w.Header().Get("Content-Type")).To(Equal("audio/mpeg")) + Expect(w.Body.Len()).To(BeZero()) + }) + + It("declares the estimated length on HEAD for a transcode not cached yet, when asked", func() { + serve(http.MethodHead, inProgress, "estimateContentLength=true") + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(w.Header().Get("Content-Length")).ToNot(BeEmpty()) + }) + + // Guards the seekable path, which must keep answering HEAD with 200 and the real length. + It("returns 200 with the real length on HEAD for a transcode completed in the cache", func() { + serve(http.MethodHead, completed) + + Expect(w.Code).To(Equal(http.StatusOK)) + Expect(w.Header().Get("Content-Length")).To(Equal(strconv.Itoa(len(transcoded)))) + Expect(w.Header().Get("Accept-Ranges")).To(Equal("bytes")) + }) + + It("still returns 500 on GET when the transcoder produces no output", func() { + serve(http.MethodGet, func(mf *model.MediaFile) *stream.Stream { + return stream.NewStream(mf, "mp3", 128, io.NopCloser(bytes.NewReader(nil))) + }) + + Expect(w.Code).To(Equal(http.StatusInternalServerError)) + }) + }) }) Describe("bpsToKbps", func() { @@ -642,15 +698,20 @@ func (m *mockTranscodeDecision) ResolveRequestFromToken(_ context.Context, _ str return req, nil } -// fakeMediaStreamer captures the StreamRequest and returns a sentinel error, -// allowing tests to verify parameter passing without constructing a real Stream. +// fakeMediaStreamer captures the StreamRequest. Without newStream it returns a sentinel error, +// allowing tests to verify parameter passing without constructing a real Stream. With newStream +// it hands the handler a real Stream, so tests can check what Serve writes. var errStreamCaptured = errors.New("stream request captured") type fakeMediaStreamer struct { - captured *stream.Request + captured *stream.Request + newStream func(*model.MediaFile) *stream.Stream } -func (f *fakeMediaStreamer) NewStream(_ context.Context, _ *model.MediaFile, req stream.Request) (*stream.Stream, error) { +func (f *fakeMediaStreamer) NewStream(_ context.Context, mf *model.MediaFile, req stream.Request) (*stream.Stream, error) { f.captured = &req + if f.newStream != nil { + return f.newStream(mf), nil + } return nil, errStreamCaptured }