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
9 changes: 8 additions & 1 deletion docs/jellycompat-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,14 @@ advertised as playable.
| `GET /Playback/BitrateTest` | Returns the requested bounded byte count; default 102,400 bytes. |

Text subtitles support `EndPositionTicks`, `CopyTimestamps`, and
`AddVttTimeMap`. JSON track events apply the same clipping and timestamp
`AddVttTimeMap`. The VTT time map follows the segment container of the play
session's HLS route. MPEG-TS segments (encoded H.264, `remux-ts-v1`, and
copied MPEG-2 video) carry the muxer's shift of twice `-max_delay` (10 s): with
`CopyTimestamps=true` the map is `MPEGTS:900000`, as in Jellyfin, and otherwise
the start position plus that shift. fMP4 segments (`remux-v1`, `remux-dv-v1`,
`hevc-v1`, and other copied-video routes) keep the source clock, so the map is
`MPEGTS:0` or the start position. Direct play and progressive remux have no
HLS segments and get the same map as fMP4. JSON track events apply the same clipping and timestamp
rebasing; an empty timing window returns `TrackEvents: []`. Raw ASS requests requiring conversion or time-window rewriting
return 406. There is no fallback-font service, external/downloaded subtitle
burn-in, or subtitle HLS playlist implementation. Changing a subtitle filter
Expand Down
116 changes: 109 additions & 7 deletions internal/jellycompat/playback_contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,13 +202,115 @@ func TestSubtitleTimingRequestTransformsOutput(t *testing.T) {
route.URLParams.Add("routeStartPositionTicks", "20000000")
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, route))
rr := httptest.NewRecorder()
(&PlaybackHandler{}).deliverSubtitle(rr, r, "vtt", []byte("WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nfirst\n\n00:00:03.500 --> 00:00:06.000\nsecond\n\n00:00:07.000 --> 00:00:08.000\nlast\n"))
(&PlaybackHandler{}).deliverSubtitle(rr, r, "vtt", []byte("WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nfirst\n\n00:00:03.500 --> 00:00:06.000\nsecond\n\n00:00:07.000 --> 00:00:08.000\nlast\n"), playback.HLSMPEGTSTimestampOffset90k)
body := rr.Body.String()
if rr.Code != 200 || !strings.Contains(body, "MPEGTS:180000") || !strings.Contains(body, "00:00:00.000 --> 00:00:01.000") || !strings.Contains(body, "00:00:01.500 --> 00:00:02.000") || strings.Contains(body, "last") {
// 2 s start plus the MPEG-TS muxer's 10 s shift, in 90 kHz ticks.
if rr.Code != 200 || !strings.Contains(body, "MPEGTS:1080000") || !strings.Contains(body, "00:00:00.000 --> 00:00:01.000") || !strings.Contains(body, "00:00:01.500 --> 00:00:02.000") || strings.Contains(body, "last") {
t.Fatalf("status=%d body=%s", rr.Code, body)
}
}

// Copied timestamps keep cues on the source clock, so the map only carries
// the 10 s the MPEG-TS muxer adds to every HLS segment PTS (2 x -max_delay
// 5000000). Jellyfin writes the same MPEGTS:900000.
func TestSubtitleTimeMapMatchesMPEGTSMuxerShiftWithCopiedTimestamps(t *testing.T) {
r := httptest.NewRequest("GET", "/subtitle?EndPositionTicks=40000000&CopyTimestamps=true&AddVttTimeMap=true", nil)
route := chi.NewRouteContext()
route.URLParams.Add("routeFormat", "vtt")
route.URLParams.Add("routeStartPositionTicks", "20000000")
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, route))
rr := httptest.NewRecorder()
(&PlaybackHandler{}).deliverSubtitle(rr, r, "vtt", []byte("WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nfirst\n\n00:00:03.500 --> 00:00:06.000\nsecond\n"), playback.HLSMPEGTSTimestampOffset90k)
body := rr.Body.String()
if rr.Code != 200 || !strings.Contains(body, "X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:900000\n") || !strings.Contains(body, "00:00:02.000 --> 00:00:03.000") || !strings.Contains(body, "00:00:03.500 --> 00:00:04.000") {
t.Fatalf("status=%d body=%s", rr.Code, body)
}
}

// fMP4 segments keep the source clock in tfdt, so their map carries no
// muxer shift: MPEGTS:0 with copied timestamps and the start otherwise.
func TestSubtitleTimeMapHasNoShiftForFMP4Segments(t *testing.T) {
for _, tc := range []struct {
copyTimestamps bool
want string
}{
{copyTimestamps: true, want: "X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:0\n"},
{copyTimestamps: false, want: "X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:180000\n"},
} {
t.Run(strconv.FormatBool(tc.copyTimestamps), func(t *testing.T) {
r := httptest.NewRequest("GET", "/subtitle?EndPositionTicks=40000000&AddVttTimeMap=true&CopyTimestamps="+strconv.FormatBool(tc.copyTimestamps), nil)
route := chi.NewRouteContext()
route.URLParams.Add("routeFormat", "vtt")
route.URLParams.Add("routeStartPositionTicks", "20000000")
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, route))
rr := httptest.NewRecorder()
(&PlaybackHandler{}).deliverSubtitle(rr, r, "vtt", []byte("WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nfirst\n"), 0)
if body := rr.Body.String(); rr.Code != 200 || !strings.Contains(body, tc.want) {
t.Fatalf("status=%d body=%s, want %q", rr.Code, body, tc.want)
}
})
}
}

// The subtitle route reads the segment container from the play session's
// source: MPEG-TS sessions get the muxer shift, fMP4 sessions do not. Direct
// play and progressive remux have no HLS segments, so they get no shift either.
func TestHandleSubtitleStreamTimeMapFollowsSegmentContainer(t *testing.T) {
subtitlePath := filepath.Join(t.TempDir(), "movie.en.vtt")
if err := os.WriteFile(subtitlePath, []byte("WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nHello\n"), 0o600); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
videoCodec string
playMethod string
source PlaybackMediaSource
notHLS bool
want string
}{
{name: "h264 transcode", videoCodec: "h264", source: PlaybackMediaSource{}, want: "MPEGTS:900000"},
{name: "remux-ts-v1", videoCodec: "hevc", source: PlaybackMediaSource{HLSRemux: true, HLSRemuxMPEGTS: true}, want: "MPEGTS:900000"},
{name: "mpeg2 copy", videoCodec: "mpeg2video", source: PlaybackMediaSource{HLSRemux: true}, want: "MPEGTS:900000"},
{name: "remux-v1", videoCodec: "h264", source: PlaybackMediaSource{HLSRemux: true}, want: "MPEGTS:0"},
{name: "copy video with audio transcode", videoCodec: "h264", source: PlaybackMediaSource{HLSRemux: true, TranscodeAudio: true}, want: "MPEGTS:0"},
{name: "remux-dv-v1", videoCodec: "hevc", source: PlaybackMediaSource{HLSRemux: true, DVStripToHDR10: true}, want: "MPEGTS:0"},
{name: "hevc-v1", videoCodec: "h264", source: PlaybackMediaSource{TargetVideoCodec: "hevc"}, want: "MPEGTS:0"},
{name: "started h264 transcode", videoCodec: "h264", playMethod: "transcode", want: "MPEGTS:900000"},
{name: "direct play", videoCodec: "h264", playMethod: "direct", want: "MPEGTS:0"},
{name: "progressive remux", videoCodec: "h264", playMethod: "remux", want: "MPEGTS:0"},
{name: "not started without transcoding", videoCodec: "h264", notHLS: true, want: "MPEGTS:0"},
} {
t.Run(tc.name, func(t *testing.T) {
file := &models.MediaFile{
ID: 42, FilePath: "/media/movie.mkv", CodecVideo: tc.videoCodec,
ExternalSubtitles: []models.ExternalSubtitle{{Path: subtitlePath, Language: "eng", Format: "vtt"}},
}
source := tc.source
source.ID, source.FileID, source.SupportsTranscoding = "source-42", file.ID, !tc.notHLS
store := NewPlaybackSessionStore(time.Hour, nil)
store.Put(PlaybackSession{ID: "play-1", CompatToken: "token-1", RouteItemID: "item-1", UpstreamPlayMethod: tc.playMethod, MediaSources: []PlaybackMediaSource{source}})
handler := &PlaybackHandler{playbackStore: store, fileResolver: testCompatFileResolver{file: file}}

request := httptest.NewRequest("GET", "/subtitle?PlaySessionId=play-1&CopyTimestamps=true&AddVttTimeMap=true", nil)
routeCtx := chi.NewRouteContext()
routeCtx.URLParams.Add("routeItemId", "item-1")
routeCtx.URLParams.Add("routeMediaSourceId", source.ID)
routeCtx.URLParams.Add("routeIndex", strconv.Itoa(externalSubtitleRouteIndex(file, 0)))
routeCtx.URLParams.Add("routeFormat", "vtt")
ctx := context.WithValue(t.Context(), chi.RouteCtxKey, routeCtx)
ctx = context.WithValue(ctx, compatSessionKey, &Session{Token: "token-1", StreamAppUserID: 7})
recorder := httptest.NewRecorder()

handler.HandleSubtitleStream(recorder, request.WithContext(ctx))

want := "X-TIMESTAMP-MAP=LOCAL:00:00:00.000," + tc.want + "\n"
if body := recorder.Body.String(); recorder.Code != 200 || !strings.Contains(body, want) {
t.Fatalf("status=%d body=%q, want %q", recorder.Code, body, want)
}
})
}
}

func TestSubtitleDeliveryMarksLTRAuthoredText(t *testing.T) {
const srt = "1\n00:00:01,000 --> 00:00:02,000\nماذا حدث للتو؟ -\n\n" +
"2\n00:00:03,000 --> 00:00:04,000\n...لأنه بالنسبة إليهم\n\n" +
Expand All @@ -219,7 +321,7 @@ func TestSubtitleDeliveryMarksLTRAuthoredText(t *testing.T) {
route.URLParams.Add("routeFormat", format)
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, route))
rr := httptest.NewRecorder()
(&PlaybackHandler{}).deliverSubtitle(rr, r, "srt", []byte(srt))
(&PlaybackHandler{}).deliverSubtitle(rr, r, "srt", []byte(srt), 0)
if body := rr.Body.String(); rr.Code != 200 || strings.Count(body, "\u200e") != 3 || !strings.Contains(body, "\u200eلقد انفجر -") {
t.Fatalf("%s: status=%d body=%q", format, rr.Code, body)
}
Expand Down Expand Up @@ -319,7 +421,7 @@ func TestJSONSubtitleTimingWindow(t *testing.T) {
route.URLParams.Add("routeStartPositionTicks", "20000000")
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, route))
rr := httptest.NewRecorder()
(&PlaybackHandler{}).deliverSubtitle(rr, r, "vtt", []byte("WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nfirst\n\n00:00:03.500 --> 00:00:06.000\nsecond\n\n00:00:07.000 --> 00:00:08.000\nlast\n"))
(&PlaybackHandler{}).deliverSubtitle(rr, r, "vtt", []byte("WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nfirst\n\n00:00:03.500 --> 00:00:06.000\nsecond\n\n00:00:07.000 --> 00:00:08.000\nlast\n"), 0)
var response struct {
TrackEvents []struct {
Text string
Expand Down Expand Up @@ -348,7 +450,7 @@ func TestWindowedSRTSubtitleKeepsAlignmentTag(t *testing.T) {
route.URLParams.Add("routeFormat", "srt")
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, route))
rr := httptest.NewRecorder()
(&PlaybackHandler{}).deliverSubtitle(rr, r, "srt", []byte("1\n00:00:01,000 --> 00:00:02,000\nEarly\n\n2\n00:00:05,000 --> 00:00:06,000\n{\\an8}Later top\n"))
(&PlaybackHandler{}).deliverSubtitle(rr, r, "srt", []byte("1\n00:00:01,000 --> 00:00:02,000\nEarly\n\n2\n00:00:05,000 --> 00:00:06,000\n{\\an8}Later top\n"), 0)
if want := "1\n00:00:02,000 --> 00:00:03,000\n{\\an8}Later top\n\n"; rr.Code != 200 || rr.Body.String() != want {
t.Fatalf("status=%d body=%q, want %q", rr.Code, rr.Body.String(), want)
}
Expand All @@ -362,7 +464,7 @@ func TestWindowedSRTSubtitleKeepsArrowCueText(t *testing.T) {
route.URLParams.Add("routeFormat", "srt")
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, route))
rr := httptest.NewRecorder()
(&PlaybackHandler{}).deliverSubtitle(rr, r, "srt", []byte("1\n00:00:01,000 --> 00:00:02,000\nMeet at 10:30. --> go now\n"))
(&PlaybackHandler{}).deliverSubtitle(rr, r, "srt", []byte("1\n00:00:01,000 --> 00:00:02,000\nMeet at 10:30. --> go now\n"), 0)
if want := "1\n00:00:00,500 --> 00:00:01,500\nMeet at 10:30. --> go now\n\n"; rr.Code != 200 || rr.Body.String() != want {
t.Fatalf("status=%d body=%q, want %q", rr.Code, rr.Body.String(), want)
}
Expand All @@ -374,7 +476,7 @@ func TestJSONSubtitleTimingEmptyWindow(t *testing.T) {
route.URLParams.Add("routeFormat", "js")
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, route))
rr := httptest.NewRecorder()
(&PlaybackHandler{}).deliverSubtitle(rr, r, "vtt", []byte("WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nfirst\n"))
(&PlaybackHandler{}).deliverSubtitle(rr, r, "vtt", []byte("WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nfirst\n"), 0)
if rr.Code != 200 || strings.TrimSpace(rr.Body.String()) != `{"TrackEvents":[]}` {
t.Fatalf("status=%d body=%s", rr.Code, rr.Body.String())
}
Expand Down
17 changes: 9 additions & 8 deletions internal/jellycompat/streams.go
Original file line number Diff line number Diff line change
Expand Up @@ -1556,6 +1556,7 @@ func (h *PlaybackHandler) HandleSubtitleStream(w http.ResponseWriter, r *http.Re
// a missing subtitle then record an outcome on a real session, which is
// correct: they are failures by an already-authorized principal.
attachCompatStream(r.Context(), session, playSession, source.FileID)
segmentPTSOffset := compatSubtitleSegmentPTSOffset90k(playSession.UpstreamPlayMethod, *source, file)

routeIndex := chiURLParam(r, "routeIndex")
trackIndex, parseErr := strconv.Atoi(routeIndex)
Expand All @@ -1580,7 +1581,7 @@ func (h *PlaybackHandler) HandleSubtitleStream(w http.ResponseWriter, r *http.Re
return
}
h.subtitlePlayed(r, subtitles.SyncTarget{MediaFileID: file.ID, ExternalPath: sub.Path})
h.deliverTextSubtitle(w, r, sub.Format, data, requestedFormat)
h.deliverTextSubtitle(w, r, sub.Format, data, requestedFormat, segmentPTSOffset)
return
}
// Serve ASS/SSA as raw data when requested.
Expand All @@ -1590,7 +1591,7 @@ func (h *PlaybackHandler) HandleSubtitleStream(w http.ResponseWriter, r *http.Re
writeError(w, http.StatusInternalServerError, "ServerError", "Failed to load subtitle")
return
}
h.deliverSubtitle(w, r, "ass", data)
h.deliverSubtitle(w, r, "ass", data, segmentPTSOffset)
return
}
if requestedFormat == "srt" && subtitleCanServeSRT(sub.Format) {
Expand All @@ -1599,15 +1600,15 @@ func (h *PlaybackHandler) HandleSubtitleStream(w http.ResponseWriter, r *http.Re
writeError(w, http.StatusInternalServerError, "ServerError", "Failed to load subtitle")
return
}
h.deliverSubtitle(w, r, requestedFormat, data)
h.deliverSubtitle(w, r, requestedFormat, data, segmentPTSOffset)
return
}
data, subErr := playback.LoadExternalSubtitleAsVTT(r.Context(), sub.Path, sub.Format, h.FFmpegPath)
if subErr != nil {
writeError(w, http.StatusInternalServerError, "ServerError", "Failed to load subtitle")
return
}
h.deliverSubtitle(w, r, "vtt", data)
h.deliverSubtitle(w, r, "vtt", data, segmentPTSOffset)
return
}
}
Expand Down Expand Up @@ -1635,7 +1636,7 @@ func (h *PlaybackHandler) HandleSubtitleStream(w http.ResponseWriter, r *http.Re
// The correction can change behind the same URL.
w.Header().Set("Cache-Control", "private, no-cache")
h.subtitlePlayed(r, subtitles.SyncTarget{MediaFileID: file.ID, StoredID: dl.ID})
h.deliverTextSubtitle(w, r, string(dl.Format), data, requestedFormat)
h.deliverTextSubtitle(w, r, string(dl.Format), data, requestedFormat, segmentPTSOffset)
return
}
}
Expand All @@ -1657,7 +1658,7 @@ func (h *PlaybackHandler) HandleSubtitleStream(w http.ResponseWriter, r *http.Re
writeError(w, http.StatusInternalServerError, "ServerError", "Failed to extract subtitle")
return
}
h.deliverSubtitle(w, r, "ass", data)
h.deliverSubtitle(w, r, "ass", data, segmentPTSOffset)
return
}

Expand All @@ -1668,15 +1669,15 @@ func (h *PlaybackHandler) HandleSubtitleStream(w http.ResponseWriter, r *http.Re
}
format := "srt"
if requestedFormat == "srt" && subtitleCanServeSRT(format) {
h.deliverSubtitle(w, r, requestedFormat, data)
h.deliverSubtitle(w, r, requestedFormat, data, segmentPTSOffset)
return
}
vttData, convErr := playback.ConvertToVTT(data, format)
if convErr != nil {
writeError(w, http.StatusInternalServerError, "ServerError", "Failed to convert subtitle")
return
}
h.deliverSubtitle(w, r, "vtt", vttData)
h.deliverSubtitle(w, r, "vtt", vttData, segmentPTSOffset)
}

func findEmbeddedSubtitle(file *models.MediaFile, routeIndex int) (int, models.SubtitleTrack) {
Expand Down
Loading
Loading