Files
jellytau/src-tauri/src/player/state.rs
T
dtourolle 109700b949 feat(playback): let Rust decide what stream to play, and say so
Playing a video meant asking the server to re-encode it, always. That
decision was made nowhere and written down nowhere, so whoever needed it
re-derived it downstream — the player worked out whether it had been handed
a playlist by looking for ".m3u8" in the URL, in two places. A viewer paid
for a transcode of a file their device could have played untouched, and the
app could not tell them which it was.

One negotiation now produces one self-describing StreamSelection — direct
play, remux or transcode; over a playlist, a plain HTTP file, or a local one
— and every renderer consumes that same answer.

Measured against the development server (Jellyfin 10.11.5), 400 items
sampled for codec mix and 40 put through a real PlaybackInfo negotiation
per profile:

  Linux / WebKitGTK (h264 only, 2ch)          3/40 —  7% direct play
  Android / ExoPlayer (hevc, ac3/eac3, 6ch)  34/40 — 85% direct play

The library is ~80% hevc, which is why the two diverge so hard. The payoff
is overwhelmingly Android, where 85% of plays were starting a transcode
nobody needed. Linux stays near 7% until libmpv decodes the picture — the
h264-only profile is a WebKitGTK constraint, not a JellyTau choice.

DR-219  StreamSelection: url + tagged Transport (hls/progressive/localFile)
        + PlaybackKind (directPlay/directStream/transcode) + the negotiated
        rendition + this source's ladder + a needs_transcoding flag derived
        in Rust so the rule is answered once. Both enums are serde-tagged
        so the frontend matches a discriminant, not a substring. The paths
        that never negotiate get the same shape from Rust rather than
        assembling one — media_local_selection for a downloaded file,
        LiveStreamInfo.transport for a live channel — so there is no second
        place where a transport is decided.

DR-220  The ceiling becomes two levels: a durable device default (Settings,
        persisted) and a per-playback override the in-player picker sets.
        The picker had called itself a "this film, this connection" control
        since it was written but wrote the process-wide default, so dropping
        one awkward film to 2 Mbps silently capped every video played
        afterwards for the rest of the process, with Settings still showing
        the old value. The override is cleared whenever playback moves to a
        new item, which stops it surviving into an autoplayed next episode.
        effective_streaming_quality() is the single resolution point.

DR-221  The quality picker is filled from what this media source can offer.
        Rust marks a rung exceeds_source when its ceiling is at or above the
        source's own bitrate — such a rung is another way to spell Original
        — and the frontend does not draw those. Original is never marked; a
        source whose bitrate the server does not report marks nothing, which
        keeps every rung offered.

DR-222  Direct play and direct stream are negotiated, with two client-side
        overrides on top because the server's answer is right about the file
        and wrong about what this app will do with it: undecodable audio
        (Jellyfin 10.11.5 honours a DirectPlayProfile's container and video
        codec but ignores its audio codec, so it offers direct play for an
        E-AC-3 track the webview renders in silence) and a viewer-pinned
        audio track the file does not default to. A direct stream is a remux
        and is deliberately not counted as transcoding.

DR-223  Dropped on measurement, not deferred. A master playlist from this
        server carries exactly one EXT-X-STREAM-INF: Jellyfin builds it from
        the single rendition the request asked for rather than publishing a
        ladder. So there is no adaptation for hls.js to be preserving and
        none mpv would lose — the claim that there was, in
        playback-backend-unification.md, does not hold. Recorded rather than
        deleted because it is a measurement: a server that does publish a
        ladder would change the answer.

DR-224  Every backend consumes the same selection. The queue item carries
        the transport, so player_seek_video picks its seek strategy from the
        backend's decision instead of the last stream_url.contains(".m3u8")
        in the codebase. Items queued by a path that never negotiated carry
        None and fall back to needs_transcoding, which is exact rather than
        a guess because every transcode this app requests is HLS (DR-140).

The frontend loader decision moves to streamTransport.ts so it can be
tested: the two cases that pin it are the ones that failed against the old
implementation — a progressive stream whose URL contains ".m3u8" must not
get an HLS loader, and an HLS stream whose URL contains none must.

Also verified the URL the direct-play branch builds actually serves playable
bytes: 206, video/mp4, valid ISO-BMFF, and a mid-file range works, so
seeking a direct play works.

The spec is folded into docs/architecture/{01,02,03} and deleted, per the
rule that docs/specs holds only work that has not shipped. DR-121 leaves
read-through-media-cache.md with a pointer; that spec keeps its capture half.

Not verified: real playback on a device. Direct play changes what actually
gets played, and neither fixtures nor curl prove the WebKitGTK and ExoPlayer
paths render it.
2026-08-22 13:45:03 +02:00

350 lines
9.8 KiB
Rust

use serde::{Deserialize, Serialize};
use super::media::MediaItem;
/// Tracks why playback ended to determine autoplay behavior
///
/// TRACES: UR-005 | DR-001
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EndReason {
/// Track played to completion (natural end) - trigger autoplay
Finished,
/// User pressed next/previous - already handled, don't autoplay
UserSkip,
/// User stopped playback - don't autoplay
UserStop,
/// Playback error - don't autoplay
Error,
/// User selected a different track - don't autoplay
NewTrackLoaded,
}
/// Player state machine (6 states: Idle, Loading, Playing, Paused, Seeking, Error)
///
/// TRACES: UR-005 | DR-001
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum PlayerState {
#[default]
/// No media loaded
Idle,
/// Media is being loaded/buffered
Loading { media: MediaItem },
/// Media is playing
Playing {
media: MediaItem,
/// Current position in seconds
position: f64,
/// Total duration in seconds
duration: f64,
},
/// Media is paused
Paused {
media: MediaItem,
/// Current position in seconds
position: f64,
/// Total duration in seconds
duration: f64,
},
/// Seeking to a new position
Seeking {
media: MediaItem,
/// Target position in seconds
target: f64,
},
/// An error occurred
Error {
media: Option<MediaItem>,
error: String,
},
}
impl PlayerState {
/// Get the current playback position if available.
///
/// Note: this is the position snapshot embedded in the state at the last
/// state transition, not the live backend position. For an up-to-date
/// value use `PlayerController::position()`.
#[allow(dead_code)]
pub fn position(&self) -> Option<f64> {
match self {
PlayerState::Playing { position, .. } => Some(*position),
PlayerState::Paused { position, .. } => Some(*position),
_ => None,
}
}
/// Check if the player is currently playing
pub fn is_playing(&self) -> bool {
matches!(self, PlayerState::Playing { .. })
}
/// Check if the player is currently paused
#[allow(dead_code)]
pub fn is_paused(&self) -> bool {
matches!(self, PlayerState::Paused { .. })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_end_reason_finished() {
let reason = EndReason::Finished;
let json = serde_json::to_string(&reason);
assert!(json.is_ok());
let serialized = json.unwrap();
assert!(serialized.contains("finished"));
}
#[test]
fn test_end_reason_user_skip() {
let reason = EndReason::UserSkip;
let json = serde_json::to_string(&reason);
assert!(json.is_ok());
let serialized = json.unwrap();
assert!(serialized.contains("userskip"));
}
#[test]
fn test_end_reason_user_stop() {
let reason = EndReason::UserStop;
let json = serde_json::to_string(&reason).unwrap();
assert!(json.contains("userstop"));
}
#[test]
fn test_end_reason_error() {
let reason = EndReason::Error;
let json = serde_json::to_string(&reason).unwrap();
assert!(json.contains("error"));
}
#[test]
fn test_end_reason_new_track_loaded() {
let reason = EndReason::NewTrackLoaded;
let json = serde_json::to_string(&reason).unwrap();
assert!(json.contains("newtrackloa"));
}
#[test]
fn test_end_reason_all_variants() {
let reasons = vec![
EndReason::Finished,
EndReason::UserSkip,
EndReason::UserStop,
EndReason::Error,
EndReason::NewTrackLoaded,
];
for reason in reasons {
let json = serde_json::to_string(&reason);
assert!(json.is_ok());
}
}
#[test]
fn test_end_reason_equality() {
let reason1 = EndReason::Finished;
let reason2 = EndReason::Finished;
assert_eq!(reason1, reason2);
let reason3 = EndReason::UserSkip;
assert_ne!(reason1, reason3);
}
#[test]
fn test_end_reason_clone() {
let reason = EndReason::Finished;
// Deliberately exercising the derived `Clone` impl, not a plain copy:
// `EndReason` is also `Copy`, so clippy flags the call as redundant.
#[allow(clippy::clone_on_copy)]
let cloned = reason.clone();
assert_eq!(reason, cloned);
}
#[test]
fn test_player_state_idle_default() {
let state = PlayerState::default();
assert!(matches!(state, PlayerState::Idle));
}
#[test]
fn test_player_state_idle_serialization() {
let state = PlayerState::Idle;
let json = serde_json::to_string(&state);
assert!(json.is_ok());
let serialized = json.unwrap();
assert!(serialized.contains("idle"));
}
#[test]
fn test_player_state_position_when_idle() {
let state = PlayerState::Idle;
assert_eq!(state.position(), None);
}
#[test]
fn test_player_state_is_playing_when_idle() {
let state = PlayerState::Idle;
assert!(!state.is_playing());
}
#[test]
fn test_player_state_is_paused_when_idle() {
let state = PlayerState::Idle;
assert!(!state.is_paused());
}
#[test]
fn test_player_state_loading() {
let media = create_test_media_item("item-1", "Test Item");
let state = PlayerState::Loading {
media: media.clone(),
};
assert!(matches!(state, PlayerState::Loading { .. }));
assert_eq!(state.position(), None);
assert!(!state.is_playing());
}
#[test]
fn test_player_state_playing_position() {
let media = create_test_media_item("item-2", "Playing Item");
let state = PlayerState::Playing {
media,
position: 45.5,
duration: 180.0,
};
assert!(state.is_playing());
assert!(!state.is_paused());
assert_eq!(state.position(), Some(45.5));
}
#[test]
fn test_player_state_paused_position() {
let media = create_test_media_item("item-3", "Paused Item");
let state = PlayerState::Paused {
media,
position: 123.75,
duration: 300.0,
};
assert!(state.is_paused());
assert!(!state.is_playing());
assert_eq!(state.position(), Some(123.75));
}
#[test]
fn test_player_state_seeking() {
let media = create_test_media_item("item-4", "Seeking Item");
let state = PlayerState::Seeking {
media,
target: 60.0,
};
assert!(!state.is_playing());
assert!(!state.is_paused());
assert_eq!(state.position(), None);
}
#[test]
fn test_player_state_error_with_media() {
let media = create_test_media_item("item-5", "Error Item");
let state = PlayerState::Error {
media: Some(media),
error: "Playback failed".to_string(),
};
assert!(!state.is_playing());
assert_eq!(state.position(), None);
}
#[test]
fn test_player_state_error_without_media() {
let state = PlayerState::Error {
media: None,
error: "Connection lost".to_string(),
};
assert!(!state.is_playing());
assert_eq!(state.position(), None);
}
#[test]
fn test_player_state_clone() {
let state = PlayerState::Idle;
let cloned = state.clone();
assert!(matches!(cloned, PlayerState::Idle));
}
#[test]
fn test_player_state_playing_serialization() {
let media = create_test_media_item("item-6", "Serial Item");
let state = PlayerState::Playing {
media,
position: 30.0,
duration: 120.0,
};
let json = serde_json::to_string(&state);
assert!(json.is_ok());
let serialized = json.unwrap();
assert!(serialized.contains("playing"));
assert!(serialized.contains("30"));
}
#[test]
fn test_player_state_multiple_positions() {
let positions = vec![0.0, 45.5, 100.0, 999.99];
for pos in positions {
let media = create_test_media_item("item-test", "Test");
let state = PlayerState::Playing {
media,
position: pos,
duration: 1000.0,
};
assert_eq!(state.position(), Some(pos));
}
}
// Helper function to create test MediaItem instances
fn create_test_media_item(id: &str, title: &str) -> MediaItem {
MediaItem {
// Audio and direct-URL items never negotiate a transport.
transport: None,
id: id.to_string(),
title: title.to_string(),
name: None,
artist: None,
album: None,
album_name: None,
album_id: None,
artist_items: None,
artists: None,
primary_image_tag: None,
image_id: None,
item_type: Some("Video".to_string()),
playlist_id: None,
duration: Some(100.0),
artwork_url: None,
media_type: super::super::media::MediaType::Video,
source: super::super::media::MediaSource::DirectUrl {
url: "http://example.com/media".to_string(),
},
video_codec: None,
needs_transcoding: false,
video_width: None,
video_height: None,
subtitles: vec![],
series_id: None,
server_id: None,
}
}
}