Skip to main content

jellytau_lib/repository/
device_profile.rs

1//! Device-profile policy: turning what a device *reports* about its audio
2//! output into the constraints we send Jellyfin.
3//!
4//! The platform layer reports raw facts (what `MediaCodecList` enumerates, how
5//! many channels the current audio route accepts); deciding what those facts
6//! mean for a `DeviceProfile` is domain logic and lives here, on the Rust side
7//! of the boundary, where it is testable without a device.
8
9/// Channel count assumed when the platform cannot tell us — every audio route
10/// can voice stereo, so it is the only safe floor.
11const FALLBACK_AUDIO_CHANNELS: u32 = 2;
12
13/// Upper bound we are willing to claim. Jellyfin profiles top out at 7.1, and a
14/// nonsense reading from a driver should not become a nonsense profile.
15const MAX_SUPPORTED_AUDIO_CHANNELS: u32 = 8;
16
17/// Decide the `MaxAudioChannels` to advertise, given what the current audio
18/// route reported.
19///
20/// Without this constraint Jellyfin is free to direct-play a 5.1 or 7.1 track to
21/// a sink that only has two channels. What the user hears then is device
22/// dependent and rarely correct — a failed `AudioSink` configuration (silence),
23/// or centre-channel dialogue folded away to near-inaudibility. Naming the real
24/// channel count makes the server downmix instead, which is always audible.
25///
26/// A missing or zero reading means "route not established yet", not "no audio":
27/// fall back to stereo rather than claiming a capability we have not seen.
28///
29/// TRACES: UR-004 | DR-141 | UT-141
30pub fn clamp_max_audio_channels(reported: Option<u32>) -> u32 {
31    match reported {
32        Some(channels) if channels >= 1 => channels.min(MAX_SUPPORTED_AUDIO_CHANNELS),
33        _ => FALLBACK_AUDIO_CHANNELS,
34    }
35}
36
37/// The channel cap for this device, reading the platform's report where one
38/// exists.
39///
40/// TRACES: UR-004 | DR-141 | UT-141
41pub fn max_audio_channels() -> u32 {
42    #[cfg(target_os = "android")]
43    let reported = crate::player::get_detected_codecs().and_then(|(_, _, channels)| channels);
44
45    // Desktop plays video through the WebKitGTK HTML5 <video> element, which we
46    // do not interrogate for a channel count; stereo is the safe assumption.
47    #[cfg(not(target_os = "android"))]
48    let reported: Option<u32> = None;
49
50    clamp_max_audio_channels(reported)
51}
52
53/// Audio codecs the webview's `<video>` element can decode.
54///
55/// Deliberately narrower than what the platform reports: see
56/// [`video_audio_codecs`].
57const WEBVIEW_AUDIO_CODECS: &[&str] = &["aac", "mp3", "opus", "vorbis", "flac"];
58
59/// The codec claimed when a device reports nothing we can use. Every renderer
60/// decodes AAC, and claiming *something* is what makes the server transcode to
61/// it rather than give up.
62const FALLBACK_AUDIO_CODEC: &str = "aac";
63
64/// Jellyfin's sentinel for "negotiate no subtitle stream at all".
65///
66/// Omitting `SubtitleStreamIndex` does **not** mean this: the server then applies
67/// the source's default/forced flags and picks a track itself. See
68/// [`playback_subtitle_stream_index`] for why that is never what we want.
69pub const NO_SUBTITLE_STREAM: i32 = -1;
70
71/// Subtitle formats we can render ourselves, delivered as an external sidecar
72/// track rather than painted into the video.
73///
74/// Every entry here is *text*. Image-based subtitles (PGS, DVD, DVB) are
75/// deliberately absent: they are bitmaps, so the only way a server can show them
76/// on a client that cannot composite them is to burn them into the picture.
77const EXTERNAL_SUBTITLE_FORMATS: &[&str] = &["srt", "subrip", "ass", "ssa", "vtt"];
78
79/// The `SubtitleProfile` entries to advertise, as `(format, method)`.
80///
81/// All `External`: the app fetches subtitle tracks itself and renders them over
82/// the video (UR-020), so it never needs the server to composite them.
83///
84/// TRACES: UR-020 | DR-176 | UT-168
85pub fn subtitle_profiles() -> Vec<(&'static str, &'static str)> {
86    EXTERNAL_SUBTITLE_FORMATS
87        .iter()
88        .map(|format| (*format, "External"))
89        .collect()
90}
91
92/// Whether asking the server to serve this subtitle codec forces it to burn the
93/// subtitle into the picture.
94///
95/// Burn-in is not a subtitle cost — it is a *video* cost. It rules out remuxing
96/// the video stream, so a source we would otherwise have passed through untouched
97/// gets fully re-encoded frame by frame.
98///
99/// TRACES: UR-020 | DR-176 | UT-168
100pub fn subtitle_forces_burn_in(codec: &str) -> bool {
101    !EXTERNAL_SUBTITLE_FORMATS
102        .iter()
103        .any(|format| format.eq_ignore_ascii_case(codec.trim()))
104}
105
106/// The `SubtitleStreamIndex` to negotiate with: always "none".
107///
108/// The reported bug: a source with an E-AC-3 track and a **PGSSUB** default
109/// subtitle track. Sending no index let the server honour that default, and since
110/// PGS cannot go out as a sidecar it chose `SubtitleMethod=Encode` — burn-in.
111/// That turned an audio-only transcode (the HEVC video was directly supported)
112/// into a full HEVC→h264 re-encode, which the server could not sustain in real
113/// time: the buffer never grew beyond one segment and playback stalled every few
114/// seconds, taking seeking down with it.
115///
116/// Asking for no subtitle stream costs nothing, because the app never wanted the
117/// server's composited version — it fetches the text tracks separately and
118/// renders them itself (UR-020).
119///
120/// TRACES: UR-020, UR-004 | DR-176 | UT-168
121pub fn playback_subtitle_stream_index() -> i32 {
122    NO_SUBTITLE_STREAM
123}
124
125/// Query keys through which a stream URL can carry a subtitle decision.
126///
127/// Jellyfin binds query keys case-insensitively, so the match has to be too —
128/// the server itself mixes casing (`SubtitleStreamIndex` but
129/// `alwaysBurnInSubtitleWhenTranscoding`).
130const SUBTITLE_QUERY_KEYS: &[&str] = &[
131    "subtitlestreamindex",
132    "subtitlemethod",
133    "subtitlecodec",
134    "alwaysburninsubtitlewhentranscoding",
135];
136
137/// Rewrite a stream URL so it asks for no subtitle, whoever built it.
138///
139/// [`playback_subtitle_stream_index`] only governs the URLs *this app* builds.
140/// When `PlaybackInfo` answers with a `TranscodingUrl`, the URL was built by the
141/// server from its own subtitle verdict, and we play it verbatim — so a server
142/// that picked a track anyway (a live channel opened without an index, a source
143/// whose default is image-based) hands us `SubtitleMethod=Encode`, and the
144/// burn-in the negotiation just declined comes back through the URL. Burn-in is
145/// a *video* cost: it rules out remuxing and forces a full re-encode.
146///
147/// Stripping the keys is not enough on its own — an absent index is not "none",
148/// it is "you choose" — so the sentinel is always appended.
149///
150/// TRACES: UR-020, UR-004 | DR-176 | UT-168
151pub fn without_server_chosen_subtitle(url: &str) -> String {
152    let (path, query) = match url.split_once('?') {
153        Some((path, query)) => (path, query),
154        None => (url, ""),
155    };
156
157    let mut kept: Vec<&str> = query
158        .split('&')
159        .filter(|param| !param.is_empty())
160        .filter(|param| {
161            let key = param.split_once('=').map_or(*param, |(key, _)| key);
162            !SUBTITLE_QUERY_KEYS
163                .iter()
164                .any(|subtitle_key| key.eq_ignore_ascii_case(subtitle_key))
165        })
166        .collect();
167
168    let sentinel = format!("SubtitleStreamIndex={}", NO_SUBTITLE_STREAM);
169    kept.push(&sentinel);
170
171    format!("{}?{}", path, kept.join("&"))
172}
173
174/// Whether a subtitle in this format can reach the app as a sidecar it draws
175/// itself — the same verdict as [`subtitle_forces_burn_in`], from the reader's
176/// side, and the one a subtitle picker needs.
177///
178/// Since the app asks for burn-in nowhere (see
179/// [`playback_subtitle_stream_index`]), a format that only burn-in could deliver
180/// is one it can never display. An unnamed format is treated as undeliverable
181/// rather than guessed at: offering a track and drawing nothing is worse than
182/// not offering it.
183///
184/// TRACES: UR-020 | DR-176 | UT-168
185pub fn subtitle_supports_external_delivery(codec: Option<&str>) -> bool {
186    codec.is_some_and(|codec| !subtitle_forces_burn_in(codec))
187}
188
189/// Narrow a detected audio-codec list to what the renderer that will actually
190/// play the **video** can decode.
191///
192/// The platform list comes from `MediaCodecList`, which describes ExoPlayer —
193/// but the webview `<video>` element may be what renders the video, and
194/// Chromium/WebKit decode a much smaller set than the platform does. Advertising
195/// the raw list makes Jellyfin direct-play a track the webview cannot decode, and
196/// the user gets picture with no sound.
197///
198/// Which renderer gets it is not fixed: Linux is always the element, and Android
199/// follows `experimentalNativeVideo`, which took ExoPlayer as its default in
200/// DR-161 but is a user setting either way. So the *narrow* list is the only one
201/// that holds on both sides of that switch. The cost is a Dolby-licensed Android
202/// device transcoding an E-AC-3 track its ExoPlayer could have direct-played;
203/// the alternative is silence for everyone the switch lands the other way, which
204/// is the bug this exists to prevent.
205///
206/// The gap is widest on devices whose vendor licenses Dolby: a phone with
207/// `c2.dolby.eac3.decoder` reports `eac3`, so it — and only it — gets a silent
208/// direct play where a leaner device is transcoded to AAC and plays fine.
209///
210/// This applies to the *video* direct-play profile only. Audio-only playback
211/// really is ExoPlayer's, so its profile keeps the full platform list.
212///
213/// TRACES: UR-004 | DR-148 | UT-142
214pub fn video_audio_codecs(detected: &str) -> String {
215    let kept: Vec<&str> = detected
216        .split(',')
217        .filter_map(|codec| {
218            let codec = codec.trim();
219            // Match case-insensitively but emit our own spelling: the platform
220            // list is assembled from MIME strings and its casing is not ours to
221            // forward to the server.
222            WEBVIEW_AUDIO_CODECS
223                .iter()
224                .copied()
225                .find(|supported| supported.eq_ignore_ascii_case(codec))
226        })
227        .collect();
228
229    if kept.is_empty() {
230        FALLBACK_AUDIO_CODEC.to_string()
231    } else {
232        kept.join(",")
233    }
234}
235
236/// Whether the webview `<video>` element can decode this audio codec.
237///
238/// TRACES: UR-004 | DR-149 | UT-148
239pub fn webview_can_decode_audio(codec: &str) -> bool {
240    WEBVIEW_AUDIO_CODECS
241        .iter()
242        .any(|supported| supported.eq_ignore_ascii_case(codec.trim()))
243}
244
245/// Decide whether we must transcode *regardless of what the server negotiated*,
246/// given the source's audio streams as `(codec, is_default)` in source order.
247///
248/// Advertising a narrow profile ([`video_audio_codecs`]) is necessary but not
249/// sufficient: Jellyfin 10.11.5 enforces a `DirectPlayProfile`'s container and
250/// video codec but **ignores its audio codec** — an E-AC-3 track is offered for
251/// direct play even when the profile lists only AAC, and neither a `VideoAudio`
252/// `CodecProfile` nor `MaxAudioChannels` changes that. So the client cannot
253/// delegate this decision; it knows what its own renderer can decode and must
254/// apply that itself.
255///
256/// The track that matters is the one the server will actually serve (see
257/// [`served_audio_codec`]). An unknown codec is left alone — forcing a transcode
258/// on a guess would burn server CPU for files that play.
259///
260/// TRACES: UR-004 | DR-149 | UT-148
261pub fn audio_forces_transcode(streams: &[(Option<&str>, bool)]) -> bool {
262    match served_audio_codec(streams) {
263        Some(codec) => !webview_can_decode_audio(codec),
264        // No audio at all, or a codec the server did not name: leave it alone.
265        None => false,
266    }
267}
268
269/// The codec of the audio track the server will actually serve, given the
270/// source's audio streams as `(codec, is_default)` in source order: the default,
271/// or the first when none is marked.
272///
273/// `None` means "nothing to judge" — no audio streams, or the server named no
274/// codec for the one it would serve. Both callers of this rule treat that as
275/// leave-well-alone, never as a licence to assume compatibility.
276///
277/// TRACES: UR-004, UR-071 | DR-149, DR-171 | UT-148, UT-166
278pub fn served_audio_codec<'a>(streams: &[(Option<&'a str>, bool)]) -> Option<&'a str> {
279    streams
280        .iter()
281        .find(|(_, is_default)| *is_default)
282        .or_else(|| streams.first())
283        .and_then(|(codec, _)| *codec)
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    /// The reported bug, at the level it was decided: a source whose default
291    /// subtitle track is PGSSUB must not drag the video into a re-encode.
292    ///
293    /// TRACES: UR-020 | DR-176 | UT-168
294    #[test]
295    fn no_subtitle_stream_is_negotiated_so_the_server_never_burns_one_in() {
296        assert_eq!(playback_subtitle_stream_index(), NO_SUBTITLE_STREAM);
297        // Not `None`/omitted: that is what let the server pick the PGS track.
298        assert_eq!(playback_subtitle_stream_index(), -1);
299    }
300
301    /// A transcode URL the *server* built carries the server's own subtitle
302    /// verdict. Adopting it verbatim re-introduces the burn-in
303    /// [`playback_subtitle_stream_index`] exists to prevent — the negotiation
304    /// asks for no subtitle, and then we play a URL that asks for one anyway.
305    ///
306    /// TRACES: UR-020, UR-004 | DR-176 | UT-168
307    #[test]
308    fn a_server_built_transcode_url_has_its_burn_in_stripped() {
309        // Shape taken from Jellyfin's `StreamInfo.ToUrl`: it appends
310        // `SubtitleStreamIndex` and `SubtitleMethod` whenever it picked a track.
311        let served = "/videos/abc/master.m3u8?DeviceId=jt&MediaSourceId=src1\
312             &VideoCodec=h264&SubtitleMethod=Encode&SubtitleStreamIndex=2\
313             &PlaySessionId=xyz";
314
315        let url = without_server_chosen_subtitle(served);
316
317        assert!(
318            url.contains("SubtitleStreamIndex=-1"),
319            "the adopted URL must ask for no subtitle: {url}"
320        );
321        assert!(
322            !url.contains("SubtitleStreamIndex=2"),
323            "the server's chosen track must not survive: {url}"
324        );
325        assert!(
326            !url.contains("SubtitleMethod"),
327            "burn-in must not be requested: {url}"
328        );
329        // Everything else identifies the job and must survive untouched.
330        for kept in [
331            "DeviceId=jt",
332            "MediaSourceId=src1",
333            "VideoCodec=h264",
334            "PlaySessionId=xyz",
335        ] {
336            assert!(url.contains(kept), "{kept} must survive: {url}");
337        }
338    }
339
340    /// The server may also be told to burn in unconditionally
341    /// (`alwaysBurnInSubtitleWhenTranscoding`), which is appended to the URL
342    /// rather than expressed as a method — and its keys are not PascalCase.
343    ///
344    /// TRACES: UR-020, UR-004 | DR-176 | UT-168
345    #[test]
346    fn an_unconditional_burn_in_flag_is_stripped_whatever_its_casing() {
347        let url = without_server_chosen_subtitle(
348            "/videos/abc/master.m3u8?api_key=k&alwaysBurnInSubtitleWhenTranscoding=true\
349             &subtitlestreamindex=3&SubtitleCodec=ass",
350        );
351
352        assert!(!url.to_lowercase().contains("alwaysburnin"), "{url}");
353        assert!(!url.to_lowercase().contains("subtitlecodec"), "{url}");
354        assert!(!url.contains("subtitlestreamindex=3"), "{url}");
355        assert!(url.contains("SubtitleStreamIndex=-1"), "{url}");
356        assert!(url.contains("api_key=k"), "{url}");
357    }
358
359    /// A URL the server built without any subtitle in it still has to *say* so:
360    /// omitting the index is what makes the server apply the source's default.
361    ///
362    /// TRACES: UR-020, UR-004 | DR-176 | UT-168
363    #[test]
364    fn a_url_with_no_subtitle_params_is_still_made_to_ask_for_none() {
365        let url = without_server_chosen_subtitle("/videos/abc/master.m3u8?api_key=k");
366        assert_eq!(
367            url,
368            "/videos/abc/master.m3u8?api_key=k&SubtitleStreamIndex=-1"
369        );
370
371        // A bare URL is rare but must not come out malformed.
372        let bare = without_server_chosen_subtitle("/videos/abc/master.m3u8");
373        assert_eq!(bare, "/videos/abc/master.m3u8?SubtitleStreamIndex=-1");
374    }
375
376    /// TRACES: UR-020 | DR-176 | UT-168
377    #[test]
378    fn text_subtitles_are_advertised_as_external_sidecars() {
379        let profiles = subtitle_profiles();
380        for format in ["srt", "subrip", "ass", "ssa", "vtt"] {
381            let entry = profiles.iter().find(|(f, _)| *f == format);
382            assert!(
383                entry.is_some(),
384                "{format} must be advertised or the server burns it into the picture"
385            );
386            assert_eq!(entry.unwrap().1, "External");
387        }
388    }
389
390    /// TRACES: UR-020 | DR-176 | UT-168
391    #[test]
392    fn text_subtitles_never_force_burn_in_but_image_ones_do() {
393        // Text: deliverable as a sidecar, so the video can still be remuxed.
394        assert!(!subtitle_forces_burn_in("subrip"));
395        assert!(!subtitle_forces_burn_in("ASS"));
396        assert!(!subtitle_forces_burn_in("ssa"));
397        // Image formats are bitmaps — the server can only composite them.
398        assert!(subtitle_forces_burn_in("PGSSUB"));
399        assert!(subtitle_forces_burn_in("dvdsub"));
400    }
401
402    #[test]
403    fn an_undecodable_default_track_forces_a_transcode() {
404        // The reported bug: one E-AC-3 track, which the webview cannot decode.
405        assert!(audio_forces_transcode(&[(Some("eac3"), false)]));
406        assert!(audio_forces_transcode(&[(Some("ac3"), true)]));
407    }
408
409    #[test]
410    fn a_decodable_track_is_left_to_direct_play() {
411        // Never spend server CPU on a file that already plays.
412        assert!(!audio_forces_transcode(&[(Some("aac"), true)]));
413        assert!(!audio_forces_transcode(&[(Some("mp3"), false)]));
414    }
415
416    #[test]
417    fn the_default_track_decides_not_the_first() {
418        // The webview plays the default track, so that is the one that has to be
419        // decodable — a supported track further down does not save us.
420        assert!(audio_forces_transcode(&[
421            (Some("aac"), false),
422            (Some("eac3"), true)
423        ]));
424        assert!(!audio_forces_transcode(&[
425            (Some("eac3"), false),
426            (Some("aac"), true)
427        ]));
428    }
429
430    #[test]
431    fn with_no_default_marked_the_first_track_decides() {
432        // Jellyfin leaves IsDefault false on every stream for some files; the
433        // server then serves the first, so judge that one.
434        assert!(audio_forces_transcode(&[
435            (Some("eac3"), false),
436            (Some("aac"), false)
437        ]));
438    }
439
440    #[test]
441    fn a_source_with_no_audio_is_not_transcoded() {
442        // Nothing to rescue, and a transcode would not create audio.
443        assert!(!audio_forces_transcode(&[]));
444    }
445
446    #[test]
447    fn an_unknown_codec_is_not_second_guessed() {
448        // The server did not tell us the codec; assuming the worst would
449        // transcode files that play perfectly.
450        assert!(!audio_forces_transcode(&[(None, true)]));
451    }
452
453    /// The download path needs the codec itself, not just the verdict, so it can
454    /// tell the server what to re-encode. It picks the same track the streaming
455    /// verdict is formed from — one rule, one place.
456    ///
457    /// TRACES: UR-071 | DR-171 | UT-166
458    #[test]
459    fn the_served_codec_is_the_one_the_verdict_is_formed_from() {
460        assert_eq!(
461            served_audio_codec(&[(Some("aac"), false), (Some("eac3"), true)]),
462            Some("eac3")
463        );
464        assert_eq!(
465            served_audio_codec(&[(Some("eac3"), false), (Some("aac"), false)]),
466            Some("eac3")
467        );
468        assert_eq!(served_audio_codec(&[]), None);
469        assert_eq!(served_audio_codec(&[(None, true)]), None);
470    }
471
472    #[test]
473    fn a_dolby_device_does_not_advertise_dolby_for_video() {
474        // The bug: a Motorola reporting c2.dolby.eac3.decoder direct-played
475        // E-AC-3 into a webview that cannot decode it — silent video, on that
476        // device only.
477        let codecs = video_audio_codecs("aac,ac3,amrnb,amrwb,eac3,flac,mp3,opus,pcm,vorbis");
478        assert_eq!(codecs, "aac,flac,mp3,opus,vorbis");
479    }
480
481    #[test]
482    fn codecs_the_webview_cannot_decode_are_dropped() {
483        // AMR and raw PCM come from the AOSP set, so this is not a Dolby-only
484        // problem — it is just rarer content.
485        assert_eq!(video_audio_codecs("amrnb,amrwb,pcm,aac"), "aac");
486        assert_eq!(video_audio_codecs("dts,truehd,mp3"), "mp3");
487    }
488
489    #[test]
490    fn a_list_the_webview_fully_supports_is_untouched() {
491        assert_eq!(
492            video_audio_codecs("aac,mp3,opus,vorbis,flac"),
493            "aac,mp3,opus,vorbis,flac"
494        );
495    }
496
497    #[test]
498    fn nothing_decodable_still_claims_aac() {
499        // Claiming an empty list invites the server to give up rather than
500        // transcode. AAC is universally decodable, so ask for it.
501        assert_eq!(video_audio_codecs("eac3,dts"), "aac");
502        assert_eq!(video_audio_codecs(""), "aac");
503    }
504
505    #[test]
506    fn spacing_and_case_in_the_platform_list_are_tolerated() {
507        // The list is assembled from MediaCodecList strings; do not let
508        // whitespace decide whether the user gets sound.
509        assert_eq!(video_audio_codecs("aac, EAC3 , Mp3"), "aac,mp3");
510    }
511
512    #[test]
513    fn an_unknown_route_falls_back_to_stereo() {
514        // Codec detection has not run yet, or the platform has no answer. Never
515        // claim surround we have not seen — every sink can do stereo.
516        assert_eq!(clamp_max_audio_channels(None), 2);
517    }
518
519    #[test]
520    fn a_zero_reading_is_not_a_capability() {
521        // A route that has not been established reports 0; taking that literally
522        // would advertise a device with no audio at all.
523        assert_eq!(clamp_max_audio_channels(Some(0)), 2);
524    }
525
526    #[test]
527    fn a_stereo_sink_is_reported_as_stereo() {
528        // The phone speaker / Bluetooth headset case: the server must downmix
529        // 5.1 rather than direct-play it.
530        assert_eq!(clamp_max_audio_channels(Some(2)), 2);
531    }
532
533    #[test]
534    fn a_surround_route_keeps_its_channels() {
535        // HDMI to an AVR: 5.1 and 7.1 direct play stay available.
536        assert_eq!(clamp_max_audio_channels(Some(6)), 6);
537        assert_eq!(clamp_max_audio_channels(Some(8)), 8);
538    }
539
540    #[test]
541    fn an_absurd_reading_is_capped_rather_than_forwarded() {
542        // Some drivers report the AudioTrack maximum rather than the route's.
543        assert_eq!(clamp_max_audio_channels(Some(32)), 8);
544    }
545
546    #[test]
547    fn a_mono_route_is_taken_at_its_word() {
548        assert_eq!(clamp_max_audio_channels(Some(1)), 1);
549    }
550}