not there yet but has potential

This commit is contained in:
2026-02-16 01:37:57 -06:00
parent aa4c4fc8e6
commit dfcf3fcf2a
7 changed files with 3425 additions and 78 deletions

View File

@@ -190,6 +190,9 @@ impl JellyfinClient {
if let Some(term) = query.search_term.as_deref() {
req = req.query(&[("SearchTerm", term)]);
}
if let Some(filters) = query.filters.as_deref() {
req = req.query(&[("Filters", filters)]);
}
let resp = req.send().map_err(|e| format!("request failed: {e}"))?;
@@ -209,7 +212,28 @@ impl JellyfinClient {
})
}
pub fn playlist_items(
/// Returns true if there exists at least one resumable Episode under the given parent (Series or Season).
/// This is used to mark Series/Season rows as "in progress" even when Jellyfin doesn't populate
/// PlayedPercentage on those container types.
pub fn has_resumable_under(
&self,
user_id: &str,
parent_id: &str,
) -> Result<bool, String> {
// Series -> Season -> Episode, so this MUST be recursive for Series.
// Recursive=true is also fine for Season.
let mut q = LibraryQuery::all()
.with_parent(parent_id.to_string())
.with_item_types("Episode")
.with_filters("IsResumable");
q.recursive = true;
let page = self.list_items(user_id, q, 0, 1)?;
Ok(page.total > 0)
}
pub fn playlist_items(
&self,
user_id: &str,
playlist_id: &str,
@@ -255,6 +279,7 @@ pub struct LibraryQuery {
pub parent_id: Option<String>, // e.g. Some(series_id)
pub search_term: Option<String>, // e.g. Some("matrix".into())
pub recursive: bool, // true for big lists, false for drilldown
pub filters: Option<String>, // e.g. Some("IsResumable".into())
}
impl LibraryQuery {
@@ -264,6 +289,7 @@ impl LibraryQuery {
parent_id: None,
search_term: None,
recursive: true,
filters: None,
}
}
pub fn shows() -> Self {
@@ -272,6 +298,7 @@ impl LibraryQuery {
parent_id: None,
search_term: None,
recursive: true,
filters: None,
}
}
pub fn music() -> Self {
@@ -280,6 +307,7 @@ impl LibraryQuery {
parent_id: None,
search_term: None,
recursive: true,
filters: None,
}
}
@@ -290,6 +318,7 @@ impl LibraryQuery {
parent_id: None,
search_term: None,
recursive: true,
filters: None,
}
}
@@ -308,6 +337,11 @@ impl LibraryQuery {
self.include_item_types = Some(types.into());
self
}
pub fn with_filters(mut self, filters: impl Into<String>) -> Self {
self.filters = Some(filters.into());
self
}
}

View File

@@ -185,6 +185,9 @@ struct App {
transcode_on: bool,
transcode_mbps: u32,
// Cache: container item id -> has resumable episode under it
parent_progress: std::collections::HashMap<String, bool>,
}
#[derive(Debug)]
@@ -262,6 +265,7 @@ impl Default for App {
autoplay_prev_time_pos: None,
transcode_on: default_on,
transcode_mbps: default_mbps,
parent_progress: std::collections::HashMap::new(),
}
}
}
@@ -465,6 +469,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
match client.list_items(user_id, query.clone(), 0, PAGE_SIZE) {
Ok(page) => {
update_parent_progress_cache(app, &client, user_id, &page.items);
app.view_stack.push(View::Library {
title,
query,
@@ -602,13 +607,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.mpv_now_playing = Some(item_name);
// If mpv running -> replace, else spawn
let url = build_jellyfin_play_url(
&cfg,
&item_id,
None,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcode_on, app.transcode_mbps);
if let Some(mpv) = &app.mpv {
match mpv_load_url(&cfg, mpv, &url) {
@@ -647,13 +646,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.autoplay_next_index = if selected + 1 < len { Some(selected + 1) } else { None };
// load/replace or spawn
let url = build_jellyfin_play_url(
&cfg,
&item_id,
None,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcode_on, app.transcode_mbps);
if let Some(mpv) = &app.mpv {
match mpv_load_url(&cfg, mpv, &url) {
@@ -706,17 +699,16 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.mpv_now_playing = Some(item_name);
let url = build_jellyfin_play_url(
&cfg,
&item_id,
start_ticks,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcode_on, app.transcode_mbps);
if let Some(mpv) = &app.mpv {
match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) {
Ok(_) => app.status = "mpv: resumed".into(),
Ok(_) => {
if let Some(t) = start_ticks {
let _ = mpv_seek_absolute(&mpv.socket_path, ticks_to_seconds(t));
}
app.status = "mpv: resumed".into();
}
Err(e) => app.status = format!("mpv resume failed: {e}"),
}
} else {
@@ -724,7 +716,11 @@ fn handle_key(app: &mut App, code: KeyCode) {
Ok(mpv) => {
let rx = start_mpv_poller(mpv.socket_path.clone());
app.mpv_state_rx = Some(rx);
let sock = mpv.socket_path.clone();
app.mpv = Some(mpv);
if let Some(t) = start_ticks {
let _ = mpv_seek_absolute(&sock, ticks_to_seconds(t));
}
app.status = "mpv: resumed".into();
}
Err(e) => app.status = format!("mpv spawn failed: {e}"),
@@ -757,17 +753,16 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.autoplay_next_index = if selected + 1 < len { Some(selected + 1) } else { None };
app.autoplay_eof_latched = false;
let url = build_jellyfin_play_url(
&cfg,
&item_id,
start_ticks,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcode_on, app.transcode_mbps);
if let Some(mpv) = &app.mpv {
match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) {
Ok(_) => app.status = "mpv: resumed (autoplay)".into(),
Ok(_) => {
if let Some(t) = start_ticks {
let _ = mpv_seek_absolute(&mpv.socket_path, ticks_to_seconds(t));
}
app.status = "mpv: resumed (autoplay)".into();
}
Err(e) => app.status = format!("mpv resume failed: {e}"),
}
} else {
@@ -775,7 +770,11 @@ fn handle_key(app: &mut App, code: KeyCode) {
Ok(mpv) => {
let rx = start_mpv_poller(mpv.socket_path.clone());
app.mpv_state_rx = Some(rx);
let sock = mpv.socket_path.clone();
app.mpv = Some(mpv);
if let Some(t) = start_ticks {
let _ = mpv_seek_absolute(&sock, ticks_to_seconds(t));
}
app.status = "mpv: resumed (autoplay)".into();
}
Err(e) => app.status = format!("mpv spawn failed: {e}"),
@@ -849,6 +848,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
match client.list_items(user_id, query.clone(), 0, PAGE_SIZE) {
Ok(page) => {
update_parent_progress_cache(app, &client, user_id, &page.items);
app.view_stack.push(View::Library {
title: cat,
query,
@@ -928,6 +928,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
match client.playlist_items(user_id, &it.id, 0, PAGE_SIZE) {
Ok(page) => {
update_parent_progress_cache(app, &client, user_id, &page.items);
app.view_stack.push(View::Library {
title: format!("{} > {}", title, it.name),
// store a query placeholder; playlist paging could be done later if you want
@@ -1087,6 +1088,8 @@ fn load_next_library_page(app: &mut App) {
Err(e) => { app.status = format!("Fetch failed: {e}"); finish_loading(app); return; }
};
update_parent_progress_cache(app, &client, user_id, &page.items);
if let Some(View::Library { items, total, .. }) = app.view_stack.last_mut() {
items.extend(page.items);
*total = page.total;
@@ -1101,6 +1104,33 @@ fn finish_loading(app: &mut App) {
}
}
fn update_parent_progress_cache(
app: &mut App,
client: &core::jellyfin::JellyfinClient,
user_id: &str,
new_items: &[core::jellyfin::JfItem],
) {
for it in new_items {
let ty = it.item_type.as_deref().unwrap_or("");
if ty != "Series" && ty != "Season" {
continue;
}
if app.parent_progress.contains_key(&it.id) {
continue;
}
match client.has_resumable_under(user_id, &it.id) {
Ok(has) => {
app.parent_progress.insert(it.id.clone(), has);
}
Err(_) => {
// If the server rejects the query, just leave it unknown.
}
}
}
}
fn maybe_prefetch(app: &mut App) {
const PREFETCH_ROWS: usize = 0;
@@ -1356,6 +1386,7 @@ fn ui(frame: &mut Frame, app: &App) {
render_library(
frame,
app,
title,
*start_index,
*total,
@@ -1496,6 +1527,7 @@ fn render_placeholder(frame: &mut Frame, name: &str, left: Rect, right: Rect) {
fn render_library(
frame: &mut Frame,
app: &App,
title: &str,
start_index: usize,
total: usize,
@@ -1552,7 +1584,7 @@ fn render_library(
true
})
.map(|it| {
let emoji = emoji_prefix_for(it);
let emoji = emoji_prefix_for(app, it);
let prefix = left_number_prefix(it, show_audio_track_numbers);
let year = if show_year_for(it.item_type.as_deref()) {
it.production_year.map(|y| format!(" ({y})")).unwrap_or_default()
@@ -1610,6 +1642,7 @@ fn open_children(app: &mut App, title: String, query: core::jellyfin::LibraryQue
match client.list_items(user_id, query.clone(), 0, PAGE_SIZE) {
Ok(page) => {
update_parent_progress_cache(app, &client, user_id, &page.items);
app.view_stack.push(View::Library {
title,
query,
@@ -1708,6 +1741,35 @@ fn mpv_cmd(socket: &PathBuf, cmd: &str) -> Result<(), String> {
mpv_send(socket, &format!("{cmd}\n"))
}
fn ticks_to_seconds(ticks: u64) -> f64 {
// Jellyfin ticks are 10,000,000 per second
(ticks as f64) / 10_000_000.0
}
fn mpv_seek_absolute(socket: &PathBuf, seconds: f64) -> Result<(), String> {
// Wait until mpv has loaded something real (duration becomes available),
// then issue a seek and REQUIRE a success reply.
let seek_cmd = format!(r#"{{"command":["seek",{}, "absolute"]}}"#, seconds);
let start = Instant::now();
while start.elapsed() < Duration::from_millis(2500) {
// duration being Some is a good signal that the file is actually ready
let dur = mpv_get_f64_jtui(socket, "duration", 1).ok().flatten();
if dur.is_some() {
// seek, but only accept success
if mpv_cmd_reply(socket, &seek_cmd).is_ok() {
return Ok(());
}
}
thread::sleep(Duration::from_millis(50));
}
Err("mpv seek failed (mpv never became ready or rejected seek)".into())
}
fn spawn_mpv(cfg: &core::config::Config, first_item_id: &str) -> Result<MpvSession, String> {
let token = cfg
.access_token
@@ -1972,13 +2034,7 @@ fn autoplay_tick(app: &mut App) {
};
// Load next item
let url = build_jellyfin_play_url(
&cfg,
&next_id,
None,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &next_id, app.transcode_on, app.transcode_mbps);
if let Err(e) = mpv_load_url(&cfg, mpv, &url) {
app.autoplay = false;
@@ -2384,28 +2440,68 @@ fn is_played(it: &core::jellyfin::JfItem) -> bool {
if it.user_data.as_ref().and_then(|u| u.played) == Some(true) {
return true;
}
// seasons/series often use percentage
match it.user_data.as_ref().and_then(|u| u.played_percentage) {
Some(p) if p >= 99.9 => true,
_ => false,
// If Jellyfin provides played percentage
if let Some(p) = it.user_data.as_ref().and_then(|u| u.played_percentage) {
if p >= 99.9 {
return true;
}
}
// Series/Season often only has UnplayedItemCount
if matches!(it.item_type.as_deref(), Some("Series" | "Season")) {
if it.user_data.as_ref().and_then(|u| u.unplayed_item_count) == Some(0) {
return true;
}
}
false
}
fn is_in_progress(it: &core::jellyfin::JfItem) -> bool {
if is_played(it) { return false; }
fn is_in_progress_with_cache(app: &App, it: &core::jellyfin::JfItem) -> bool {
if is_played(it) {
return false;
}
// movies/episodes
if playback_position_ticks(it).is_some() {
return true;
}
// seasons/series (some servers expose %)
// series/seasons: ask cache first (based on resumable episodes)
if matches!(it.item_type.as_deref(), Some("Series") | Some("Season")) {
if let Some(v) = app.parent_progress.get(&it.id) {
return *v;
}
}
// fallback: percentage-based if server provides it
match it.user_data.as_ref().and_then(|u| u.played_percentage) {
Some(p) if p > 0.1 && p < 99.9 => true,
_ => false,
}
}
fn is_in_progress(it: &core::jellyfin::JfItem) -> bool {
if is_played(it) {
return false;
}
// movies/episodes
if playback_position_ticks(it).is_some() {
return true;
}
// series/seasons (percentage-based)
match it.user_data.as_ref().and_then(|u| u.played_percentage) {
Some(p) if p > 0.1 && p < 99.9 => true,
_ => false,
}
}
fn playback_position_ticks(it: &core::jellyfin::JfItem) -> Option<u64> {
it.user_data
.as_ref()
@@ -2413,26 +2509,24 @@ fn playback_position_ticks(it: &core::jellyfin::JfItem) -> Option<u64> {
.and_then(|v| if v > 0 { Some(v as u64) } else { None })
}
fn emoji_prefix_for(it: &core::jellyfin::JfItem) -> &'static str {
// user asked: no emoji for music
fn emoji_prefix_for(app: &App, it: &core::jellyfin::JfItem) -> &'static str {
// no emoji for music
if is_music_item(it) {
return "";
}
let dl = is_downloaded(it);
let played = is_played(it);
let prog = is_in_progress(it);
let prog = is_in_progress_with_cache(app, it);
match (dl, played, prog) {
(true, true, _) => "💾",
(true, false, true) => "💾▶ ",
(true, false, false) => "💾 ",
(false, true, _) => "",
(false, false, true) => "",
(false, false, false) => "",
match (played, prog) {
(true, _) => "",
(false, true) => "🟠 ", // orange in-progress
(false, false) => "",
}
}
// --- transcoding + resume URL builder (Approach B) ---
fn clamp_mbps_to_bps(mbps: u32) -> u32 {
mbps.saturating_mul(1_000_000) // Mb/s -> bits/s
@@ -2441,39 +2535,51 @@ fn clamp_mbps_to_bps(mbps: u32) -> u32 {
fn build_jellyfin_play_url(
cfg: &core::config::Config,
item_id: &str,
start_ticks: Option<u64>,
transcode_on: bool,
transcode_mbps: u32,
) -> String {
let base = cfg.base_url.trim_end_matches('/');
if !transcode_on {
return format!("{}/Items/{}/Download", base, item_id);
}
let token = cfg
.access_token
.as_deref()
.unwrap_or(""); // if empty, server likely rejects anyway
let bps = clamp_mbps_to_bps(transcode_mbps);
// Use maxStreamingBitrate (what Jellyfin UIs commonly use)
// Use static=false (lets server do normal streaming behavior)
let mut url = format!("{}/Videos/{}/stream?static=false", base, item_id);
if !transcode_on {
// Direct stream.
//
// We intentionally keep this "static=true" so mpv can see the full timeline/duration
// (many servers provide Content-Length only for static streams).
//
// Resume is implemented via mpv seeking (not startTimeTicks in the URL) to avoid the
// Jellyfin behavior where startTimeTicks may be ignored for static streams.
return format!(
"{}/Videos/{}/stream?static=true&api_key={}",
base, item_id, token
);
}
// Transcoded stream via HLS (fixes "duration == buffered" + enables seeking).
//
// IMPORTANT: Use Jellyfin's documented query param names:
// - videoBitRate (capital R)
// - segmentContainer
//
// Resume is implemented via mpv seeking (not startTimeTicks in the URL).
let mut url = format!(
"{}/Videos/{}/master.m3u8?api_key={}&static=false",
base, item_id, token
);
url.push_str(&format!("&maxStreamingBitrate={}", bps));
// IMPORTANT:
// - enableAutoStreamCopy=true = will NOT transcode if it can direct stream
// - set to false to FORCE transcode behavior (good for testing)
//
// For now: force it so you can verify it works.
url.push_str(&format!("&videoBitrate={}", bps)); // NOTE: lower-case 'r' matches your working version
url.push_str(&format!("&audioBitrate={}", bps));
url.push_str("&enableAutoStreamCopy=false");
// Make transcode more likely / deterministic:
url.push_str("&videoCodec=h264");
url.push_str("&audioCodec=aac");
url.push_str("&transcodingContainer=mp4");
if let Some(t) = start_ticks {
url.push_str(&format!("&startTimeTicks={}", t));
}
url.push_str("&transcodingContainer=ts"); // NOTE: this is what your working build used
url
}
@@ -2481,7 +2587,6 @@ fn build_jellyfin_play_url(
fn reload_config(app: &mut App) {
if let Ok(cfg) = core::config::load_config() {
app.transcode_mbps = cfg.transcode_mbps.unwrap_or(5);
@@ -2493,8 +2598,36 @@ fn reload_config(app: &mut App) {
}
}
fn mpv_cmd_reply(socket: &PathBuf, cmd: &str) -> Result<Value, String> {
let mut stream = UnixStream::connect(socket)
.map_err(|e| format!("mpv ipc connect failed: {e}"))?;
let _ = stream.set_write_timeout(Some(Duration::from_millis(500)));
let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
stream
.write_all(format!("{cmd}\n").as_bytes())
.map_err(|e| format!("mpv ipc write failed: {e}"))?;
let mut reader = BufReader::new(stream);
let mut line = String::new();
reader
.read_line(&mut line)
.map_err(|e| format!("mpv ipc read failed: {e}"))?;
if line.trim().is_empty() {
return Err("mpv ipc: empty response".into());
}
let v: Value = serde_json::from_str(line.trim())
.map_err(|e| format!("mpv json parse failed: {e} ({})", line.trim()))?;
if v.get("error").and_then(|e| e.as_str()) != Some("success") {
return Err(format!("mpv command failed: {}", line.trim()));
}
Ok(v)
}