another backup

This commit is contained in:
2026-02-16 22:34:22 -06:00
parent 62d408337e
commit 8c97c2911c
2 changed files with 251 additions and 105 deletions

View File

@@ -52,6 +52,34 @@ struct PlaylistItemsResponse {
total_record_count: Option<usize>, total_record_count: Option<usize>,
} }
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
struct PlaybackInfoDto<'a> {
user_id: Option<&'a str>,
max_streaming_bitrate: Option<i32>,
enable_direct_play: Option<bool>,
enable_direct_stream: Option<bool>,
enable_transcoding: Option<bool>,
allow_video_stream_copy: Option<bool>,
allow_audio_stream_copy: Option<bool>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct PlaybackInfoResponse {
media_sources: Vec<MediaSourceInfo>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
struct MediaSourceInfo {
transcoding_url: Option<String>,
// (We don't need more fields.)
}
impl JellyfinClient { impl JellyfinClient {
pub fn from_config(cfg: &Config) -> Result<Self, String> { pub fn from_config(cfg: &Config) -> Result<Self, String> {
let token = cfg let token = cfg
@@ -143,6 +171,54 @@ impl JellyfinClient {
false false
} }
pub fn playback_transcoding_url(
&self,
item_id: &str,
user_id: Option<&str>,
max_streaming_bitrate_bps: i32,
force_transcode: bool,
) -> Result<Option<String>, String> {
let url = format!("{}/Items/{}/PlaybackInfo", self.base_url.trim_end_matches('/'), item_id);
let body = if force_transcode {
PlaybackInfoDto {
user_id,
max_streaming_bitrate: Some(max_streaming_bitrate_bps),
enable_direct_play: Some(false),
enable_direct_stream: Some(false),
enable_transcoding: Some(true),
allow_video_stream_copy: Some(false),
allow_audio_stream_copy: Some(false),
}
} else {
PlaybackInfoDto {
user_id,
max_streaming_bitrate: Some(max_streaming_bitrate_bps),
enable_direct_play: None,
enable_direct_stream: None,
enable_transcoding: None,
allow_video_stream_copy: None,
allow_audio_stream_copy: None,
}
};
let resp: PlaybackInfoResponse = self
.client
.post(url)
// IMPORTANT: authenticated call
.header("X-Emby-Authorization", self.auth_header_value())
.json(&body)
.send()
.map_err(|e| format!("PlaybackInfo request failed: {e}"))?
.error_for_status()
.map_err(|e| format!("PlaybackInfo HTTP error: {e}"))?
.json()
.map_err(|e| format!("PlaybackInfo json parse failed: {e}"))?;
Ok(resp.media_sources.into_iter().find_map(|ms| ms.transcoding_url))
}
pub fn list_views(&self, user_id: &str) -> Result<Vec<JfItem>, String> { pub fn list_views(&self, user_id: &str) -> Result<Vec<JfItem>, String> {
let url = format!("{}/Users/{}/Views", self.base_url, user_id); let url = format!("{}/Users/{}/Views", self.base_url, user_id);

View File

@@ -793,17 +793,26 @@ fn handle_key(app: &mut App, code: KeyCode) {
let url = if let Some(p) = maybe_path.or(local) { let url = if let Some(p) = maybe_path.or(local) {
p.to_string_lossy().to_string() p.to_string_lossy().to_string()
} else { } else {
build_jellyfin_play_url(&cfg, maybe_item_id.as_deref().unwrap(), app.transcoding) let id = maybe_item_id.as_deref().unwrap();
if app.transcoding {
build_jellyfin_play_url_transcode_forced(&cfg, id)
.unwrap_or_else(|| build_jellyfin_play_url(&cfg, id, true))
} else {
build_jellyfin_play_url(&cfg, id, false)
}
}; };
// If mpv running -> replace, else spawn // If mpv running -> replace, else spawn
if let Some(mpv) = &app.mpv { if let Some(mpv) = &app.mpv {
match mpv_load_url(&cfg, mpv, &url) { // For local files, use mpv_load_local; otherwise mpv_load_url
let r = if url.starts_with('/') { mpv_load_local(mpv, &url) } else { mpv_load_url(&cfg, mpv, &url) };
match r {
Ok(_) => app.status = "mpv: loaded".into(), Ok(_) => app.status = "mpv: loaded".into(),
Err(e) => app.status = format!("mpv load failed: {e}"), Err(e) => app.status = format!("mpv load failed: {e}"),
} }
} else { } else {
match spawn_mpv_url(&cfg, &url) { let r = if url.starts_with('/') { spawn_mpv_local(&url) } else { spawn_mpv_url(&cfg, &url) };
match r {
Ok(mpv) => { Ok(mpv) => {
let rx = start_mpv_poller(mpv.socket_path.clone()); let rx = start_mpv_poller(mpv.socket_path.clone());
app.mpv_state_rx = Some(rx); app.mpv_state_rx = Some(rx);
@@ -813,9 +822,9 @@ fn handle_key(app: &mut App, code: KeyCode) {
Err(e) => app.status = format!("mpv spawn failed: {e}"), Err(e) => app.status = format!("mpv spawn failed: {e}"),
} }
} }
return; return;
} }
KeyCode::Char('P') => { KeyCode::Char('P') => {
let cfg = match &app.config { let cfg = match &app.config {
Some(c) => c.clone(), Some(c) => c.clone(),
@@ -848,8 +857,11 @@ fn handle_key(app: &mut App, code: KeyCode) {
let url = if let Some(p) = local { let url = if let Some(p) = local {
p.to_string_lossy().to_string() p.to_string_lossy().to_string()
} else if app.transcoding {
build_jellyfin_play_url_transcode_forced(&cfg, &item_id)
.unwrap_or_else(|| build_jellyfin_play_url(&cfg, &item_id, true))
} else { } else {
build_jellyfin_play_url(&cfg, &item_id, app.transcoding) build_jellyfin_play_url(&cfg, &item_id, false)
}; };
if let Some(mpv) = &app.mpv { if let Some(mpv) = &app.mpv {
@@ -928,8 +940,6 @@ fn handle_key(app: &mut App, code: KeyCode) {
} }
} }
} }
KeyCode::Char('r') => { KeyCode::Char('r') => {
app.autoplay = false; app.autoplay = false;
app.autoplay_next_index = None; app.autoplay_next_index = None;
@@ -954,7 +964,12 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.mpv_now_playing = Some(item_name); app.mpv_now_playing = Some(item_name);
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcoding); let url = if app.transcoding {
build_jellyfin_play_url_transcode_forced(&cfg, &item_id)
.unwrap_or_else(|| build_jellyfin_play_url(&cfg, &item_id, true))
} else {
build_jellyfin_play_url(&cfg, &item_id, false)
};
if let Some(mpv) = &app.mpv { if let Some(mpv) = &app.mpv {
match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) { match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) {
@@ -981,11 +996,15 @@ fn handle_key(app: &mut App, code: KeyCode) {
Err(e) => app.status = format!("mpv spawn failed: {e}"), Err(e) => app.status = format!("mpv spawn failed: {e}"),
} }
} }
return; return;
} }
KeyCode::Char('R') => { KeyCode::Char('R') => {
// resume + autoplay // resume + autoplay
let cfg = match &app.config { Some(c) => c.clone(), None => { app.status="No config".into(); return; } }; let cfg = match &app.config {
Some(c) => c.clone(),
None => { app.status = "No config".into(); return; }
};
let (item_id, item_name, selected, len, start_ticks) = match app.current_view() { let (item_id, item_name, selected, len, start_ticks) = match app.current_view() {
View::Library { items, selected, .. } if !items.is_empty() => { View::Library { items, selected, .. } if !items.is_empty() => {
@@ -1008,7 +1027,12 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.autoplay_next_index = if selected + 1 < len { Some(selected + 1) } else { None }; app.autoplay_next_index = if selected + 1 < len { Some(selected + 1) } else { None };
app.autoplay_eof_latched = false; app.autoplay_eof_latched = false;
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcoding); let url = if app.transcoding {
build_jellyfin_play_url_transcode_forced(&cfg, &item_id)
.unwrap_or_else(|| build_jellyfin_play_url(&cfg, &item_id, true))
} else {
build_jellyfin_play_url(&cfg, &item_id, false)
};
if let Some(mpv) = &app.mpv { if let Some(mpv) = &app.mpv {
match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) { match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) {
@@ -1035,6 +1059,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
Err(e) => app.status = format!("mpv spawn failed: {e}"), Err(e) => app.status = format!("mpv spawn failed: {e}"),
} }
} }
return; return;
} }
_ => {} _ => {}
@@ -2361,7 +2386,7 @@ fn autoplay_tick(app: &mut App) {
// Snapshot latest mpv state from poller thread // Snapshot latest mpv state from poller thread
let st = app.mpv_state.clone(); let st = app.mpv_state.clone();
// Optional: live debug in status (toggle with 'D') // Optional: live debug in status (toggle with 'M' in your keybinds)
if app.debug_mpv { if app.debug_mpv {
app.status = fmt_mpv_state(&st); app.status = fmt_mpv_state(&st);
} }
@@ -2417,126 +2442,151 @@ fn autoplay_tick(app: &mut App) {
} }
}; };
// Choose next target based on current view // Choose next target based on current view
enum NextTarget { enum NextTarget {
Online { id: String, name: String, len: usize }, Online { id: String, name: String, len: usize },
Offline { path: PathBuf, name: String, len: usize }, Offline { path: PathBuf, name: String, len: usize },
} }
let next = match app.current_view() { let next = match app.current_view() {
View::Library { items, .. } if next_i < items.len() => { View::Library { items, .. } if next_i < items.len() => NextTarget::Online {
NextTarget::Online { id: items[next_i].id.clone(),
id: items[next_i].id.clone(), name: items[next_i].name.clone(),
name: items[next_i].name.clone(), len: items.len(),
len: items.len(), },
}
}
View::OfflineLibrary { entries, .. } if next_i < entries.len() => {
// skip dirs: if next_i lands on a dir, find the next file
let mut j = next_i;
while j < entries.len() && entries[j].is_dir {
j += 1;
}
if j >= entries.len() {
// no more playable files
app.autoplay = false;
app.autoplay_next_index = None;
if !app.debug_mpv { app.status = "$".into(); }
return;
}
NextTarget::Offline { View::OfflineLibrary { entries, .. } if next_i < entries.len() => {
path: entries[j].path.clone(), // skip dirs: if next_i lands on a dir, find the next file
name: entries[j].name.clone(), let mut j = next_i;
len: entries.len(), while j < entries.len() && entries[j].is_dir {
} j += 1;
} }
_ => { if j >= entries.len() {
// no more playable files
app.autoplay = false; app.autoplay = false;
app.autoplay_next_index = None; app.autoplay_next_index = None;
if !app.debug_mpv { app.status = "$".into(); } if !app.debug_mpv {
app.status = "$".into();
}
return; return;
} }
};
match &next { NextTarget::Offline {
NextTarget::Online { name, .. } => app.mpv_now_playing = Some(name.clone()), path: entries[j].path.clone(),
NextTarget::Offline { name, .. } => app.mpv_now_playing = Some(name.clone()), name: entries[j].name.clone(),
len: entries.len(),
}
} }
// Move selection highlight in UI + compute following index _ => {
match app.view_stack.last_mut() { app.autoplay = false;
Some(View::Library { selected, .. }) => { app.autoplay_next_index = None;
*selected = next_i; if !app.debug_mpv {
app.status = "$".into();
} }
Some(View::OfflineLibrary { selected, entries, .. }) => { return;
// if we skipped dirs, move selection to actual file index
let mut j = next_i;
while j < entries.len() && entries[j].is_dir { j += 1; }
*selected = j;
}
_ => {}
} }
};
// compute next index (offline should skip dirs too later) // Update "now playing"
let len = match &next { match &next {
NextTarget::Online { len, .. } => *len, NextTarget::Online { name, .. } => app.mpv_now_playing = Some(name.clone()),
NextTarget::Offline { len, .. } => *len, NextTarget::Offline { name, .. } => app.mpv_now_playing = Some(name.clone()),
}; }
app.autoplay_next_index = if next_i + 1 < len { Some(next_i + 1) } else { None };
// Load next // Move selection highlight in UI
match next { match app.view_stack.last_mut() {
NextTarget::Online { id: next_id, .. } => { Some(View::Library { selected, .. }) => {
let cfg = match app.config.clone() { *selected = next_i;
Some(c) => c, }
None => { Some(View::OfflineLibrary {
app.autoplay = false; selected,
app.autoplay_next_index = None; entries,
app.status = "No config".into(); ..
return; }) => {
} // if we skipped dirs, move selection to actual file index
}; let mut j = next_i;
while j < entries.len() && entries[j].is_dir {
j += 1;
}
*selected = j;
}
_ => {}
}
// If offline, MUST be local // compute next index (offline skip-dirs happens on next tick too)
let local = crate::core::downloads::local_media_path_for_item_id(&next_id); let len = match &next {
if app.offline && local.is_none() { NextTarget::Online { len, .. } => *len,
NextTarget::Offline { len, .. } => *len,
};
app.autoplay_next_index = if next_i + 1 < len {
Some(next_i + 1)
} else {
None
};
// Load next
match next {
NextTarget::Online { id: next_id, .. } => {
let cfg = match app.config.clone() {
Some(c) => c,
None => {
app.autoplay = false; app.autoplay = false;
app.autoplay_next_index = None; app.autoplay_next_index = None;
app.status = "Offline: next item not downloaded".into(); app.status = "No config".into();
return; return;
} }
};
let url = if let Some(p) = local { // If offline, MUST be local
p.to_string_lossy().to_string() let local = crate::core::downloads::local_media_path_for_item_id(&next_id);
} else { if app.offline && local.is_none() {
build_jellyfin_play_url(&cfg, &next_id, app.transcoding) app.autoplay = false;
}; app.autoplay_next_index = None;
app.status = "Offline: next item not downloaded".into();
if let Err(e) = mpv_load_url(&cfg, mpv, &url) { return;
app.autoplay = false;
app.autoplay_next_index = None;
app.status = format!("autoplay load failed: {e}");
return;
}
} }
NextTarget::Offline { path, .. } => { let url = if let Some(p) = local {
let url = path.to_string_lossy().to_string(); p.to_string_lossy().to_string()
if let Err(e) = mpv_load_local(mpv, &url) { } else if app.transcoding {
app.autoplay = false; build_jellyfin_play_url_transcode_forced(&cfg, &next_id)
app.autoplay_next_index = None; .unwrap_or_else(|| build_jellyfin_play_url(&cfg, &next_id, true))
app.status = format!("offline autoplay load failed: {e}"); } else {
return; build_jellyfin_play_url(&cfg, &next_id, false)
} };
// Local vs remote loader
let r = if url.starts_with('/') {
mpv_load_local(mpv, &url)
} else {
mpv_load_url(&cfg, mpv, &url)
};
if let Err(e) = r {
app.autoplay = false;
app.autoplay_next_index = None;
app.status = format!("autoplay load failed: {e}");
return;
} }
} }
let _ = mpv_set_pause(mpv, false); NextTarget::Offline { path, .. } => {
app.autoplay_prev_time_pos = None; let url = path.to_string_lossy().to_string();
if !app.debug_mpv { if let Err(e) = mpv_load_local(mpv, &url) {
app.status = "$".into(); app.autoplay = false;
app.autoplay_next_index = None;
app.status = format!("offline autoplay load failed: {e}");
return;
}
} }
}
let _ = mpv_set_pause(mpv, false);
app.autoplay_prev_time_pos = None;
if !app.debug_mpv {
app.status = "$".into();
}
} }
fn mpv_set_pause(mpv: &MpvSession, paused: bool) -> Result<(), String> { fn mpv_set_pause(mpv: &MpvSession, paused: bool) -> Result<(), String> {
@@ -3542,3 +3592,23 @@ fn render_offline_library_dir(
right, right,
); );
} }
fn build_jellyfin_play_url_transcode_forced(
cfg: &core::config::Config,
item_id: &str,
) -> Option<String> {
let user_id = cfg.user_id.as_deref()?;
let client = core::jellyfin::JellyfinClient::from_config(cfg).ok()?;
let max_bps: i32 = (cfg.transcode_mbps.max(0.01) * 1_000_000.0) as i32;
let turl = client
.playback_transcoding_url(item_id, Some(user_id), max_bps, true)
.ok()??;
if turl.starts_with("http://") || turl.starts_with("https://") {
Some(turl)
} else {
Some(format!("{}{}", cfg.base_url.trim_end_matches('/'), turl))
}
}