diff --git a/src/core/config.rs b/src/core/config.rs index fbb8a0b..fa5b873 100644 --- a/src/core/config.rs +++ b/src/core/config.rs @@ -7,9 +7,9 @@ pub struct Config { pub base_url: String, pub access_token: Option, pub user_id: Option, - pub transcode_mbps: f32, } + #[derive(Debug)] pub enum ConfigError { NotFound(PathBuf), @@ -45,7 +45,6 @@ fn parse_config(s: &str) -> Result { let mut base_url: Option = None; let mut access_token: Option = None; let mut user_id: Option = None; - let mut transcode_mbps: Option = None; for (i, line) in s.lines().enumerate() { let line = line.trim(); @@ -69,12 +68,6 @@ fn parse_config(s: &str) -> Result { "base_url" => base_url = Some(val), "access_token" => access_token = Some(val), "user_id" => user_id = Some(val), - "transcode_mbps" => { - // allow raw numbers or quoted numbers - if let Ok(n) = val.parse::() { - transcode_mbps = Some(n); - } - } _ => {} } } @@ -85,7 +78,6 @@ fn parse_config(s: &str) -> Result { base_url, access_token, user_id, - transcode_mbps: transcode_mbps.unwrap_or(5.0), }) } @@ -108,8 +100,6 @@ pub fn save_config(cfg: &Config) -> Result<(), ConfigError> { out.push_str(&format!("user_id = \"{}\"\n", u)); } - out.push_str(&format!("transcode_mbps = {}\n", cfg.transcode_mbps)); - std::fs::write(path, out)?; Ok(()) } diff --git a/src/core/jellyfin.rs b/src/core/jellyfin.rs index 042cf38..733a5e9 100644 --- a/src/core/jellyfin.rs +++ b/src/core/jellyfin.rs @@ -52,34 +52,6 @@ struct PlaylistItemsResponse { total_record_count: Option, } -#[derive(Debug, Serialize)] -#[serde(rename_all = "PascalCase")] -struct PlaybackInfoDto<'a> { - user_id: Option<&'a str>, - max_streaming_bitrate: Option, - - enable_direct_play: Option, - enable_direct_stream: Option, - enable_transcoding: Option, - - allow_video_stream_copy: Option, - allow_audio_stream_copy: Option, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "PascalCase")] -struct PlaybackInfoResponse { - media_sources: Vec, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "PascalCase")] -struct MediaSourceInfo { - transcoding_url: Option, - // (We don't need more fields.) -} - - impl JellyfinClient { pub fn from_config(cfg: &Config) -> Result { let token = cfg @@ -171,54 +143,6 @@ impl JellyfinClient { false } - pub fn playback_transcoding_url( - &self, - item_id: &str, - user_id: Option<&str>, - max_streaming_bitrate_bps: i32, - force_transcode: bool, - ) -> Result, 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, String> { let url = format!("{}/Users/{}/Views", self.base_url, user_id); diff --git a/src/main.rs b/src/main.rs index ee082bd..9ee9ca9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -185,7 +185,6 @@ struct App { login_focus: LoginFocus, login_error: Option, offline: bool, - transcoding: bool, search: Option, mpv: Option, @@ -272,7 +271,6 @@ impl Default for App { downloads_selected: 0, downloaded_ids: downloads::scan_downloaded_ids().unwrap_or_default(), last_download_message: None, - transcoding: false, } } @@ -600,23 +598,7 @@ fn handle_key(app: &mut App, code: KeyCode) { } return; } - // Toggle transcoding (affects remote playback URL selection only). - if matches!(code, KeyCode::Char('t')) { - app.transcoding = !app.transcoding; - let mbps = app - .config - .as_ref() - .map(|c| c.transcode_mbps) - .unwrap_or(5.0); - - app.status = if app.transcoding { - format!("transcoding: ON ({} Mbps)", mbps) - } else { - "transcoding: OFF".into() - }; - return; - } // -------------------- // Downloads Focus Modal @@ -793,26 +775,17 @@ fn handle_key(app: &mut App, code: KeyCode) { let url = if let Some(p) = maybe_path.or(local) { p.to_string_lossy().to_string() } else { - 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) - } + build_jellyfin_play_url(&cfg, maybe_item_id.as_deref().unwrap()) }; // If mpv running -> replace, else spawn if let Some(mpv) = &app.mpv { - // 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 { + match mpv_load_url(&cfg, mpv, &url) { Ok(_) => app.status = "mpv: loaded".into(), Err(e) => app.status = format!("mpv load failed: {e}"), } } else { - let r = if url.starts_with('/') { spawn_mpv_local(&url) } else { spawn_mpv_url(&cfg, &url) }; - match r { + match spawn_mpv_url(&cfg, &url) { Ok(mpv) => { let rx = start_mpv_poller(mpv.socket_path.clone()); app.mpv_state_rx = Some(rx); @@ -822,9 +795,9 @@ fn handle_key(app: &mut App, code: KeyCode) { Err(e) => app.status = format!("mpv spawn failed: {e}"), } } - return; } + KeyCode::Char('P') => { let cfg = match &app.config { Some(c) => c.clone(), @@ -857,11 +830,8 @@ fn handle_key(app: &mut App, code: KeyCode) { let url = if let Some(p) = local { 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 { - build_jellyfin_play_url(&cfg, &item_id, false) + build_jellyfin_play_url(&cfg, &item_id) }; if let Some(mpv) = &app.mpv { @@ -940,6 +910,8 @@ fn handle_key(app: &mut App, code: KeyCode) { } } } + + KeyCode::Char('r') => { app.autoplay = false; app.autoplay_next_index = None; @@ -964,12 +936,7 @@ fn handle_key(app: &mut App, code: KeyCode) { app.mpv_now_playing = Some(item_name); - 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) - }; + let url = build_jellyfin_play_url(&cfg, &item_id); if let Some(mpv) = &app.mpv { match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) { @@ -996,15 +963,11 @@ fn handle_key(app: &mut App, code: KeyCode) { Err(e) => app.status = format!("mpv spawn failed: {e}"), } } - return; } KeyCode::Char('R') => { // 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() { View::Library { items, selected, .. } if !items.is_empty() => { @@ -1027,12 +990,7 @@ 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 = 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) - }; + let url = build_jellyfin_play_url(&cfg, &item_id); if let Some(mpv) = &app.mpv { match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) { @@ -1059,7 +1017,6 @@ fn handle_key(app: &mut App, code: KeyCode) { Err(e) => app.status = format!("mpv spawn failed: {e}"), } } - return; } _ => {} @@ -1068,45 +1025,6 @@ fn handle_key(app: &mut App, code: KeyCode) { // downloads focus overrides normal navigation // downloads focus overrides normal navigation -/* //come back - let mut handled_by_downloads = false; - - if app.downloads_focus { - if let Some(dm) = &app.downloads { - let idx = app.downloads_selected; - - if idx == 0 { - dm.send(downloads::DownloadCommand::Cancel { index: 0 }); - app.status = "download: cancel active".into(); - } else { - dm.send(downloads::DownloadCommand::RemoveQueued { index: idx }); - app.status = "download: removed".into(); - } - - // Clamp selection immediately to avoid focus navigation glitches - let len = dm - .state - .lock() - .ok() - .map(|st| st.queue.len()) - .unwrap_or(0); - - if len == 0 { - app.downloads_selected = 0; - } else if app.downloads_selected >= len { - app.downloads_selected = len - 1; - } - } else { - app.status = "downloads not available".into(); - } - return; - } - - // If downloads handled the key, skip normal navigation handling - if handled_by_downloads { - return; - } -*/ match code { KeyCode::Char('d') => { @@ -1119,19 +1037,17 @@ fn handle_key(app: &mut App, code: KeyCode) { None => { app.status = "No user_id (login first)".into(); return; } }; - let (it, playlist_name, playlist_index) = match app.current_view() { + let (selected_item, playlist_ctx, selected_index) = match app.current_view() { View::Library { items, selected, playlist_ctx, .. } if !items.is_empty() => { - let it = items[*selected].clone(); - let pname = playlist_ctx.as_ref().map(|p| p.name.clone()); - (it, pname, *selected) + (items[*selected].clone(), playlist_ctx.clone(), *selected) } _ => { app.status = "Nothing to download here".into(); return; } }; + // ensure DM let dm = match &app.downloads { Some(dm) => dm, None => { - // try start downloads now if we have a token if cfg.access_token.is_some() { app.downloads = Some(downloads::DownloadManager::start(cfg.clone())); app.downloads.as_ref().unwrap() @@ -1142,14 +1058,17 @@ fn handle_key(app: &mut App, code: KeyCode) { } }; - let jf = match core::jellyfin::JellyfinClient::from_config(&cfg) { + let client = match core::jellyfin::JellyfinClient::from_config(&cfg) { Ok(c) => c, Err(e) => { app.status = format!("downloads: {e}"); return; } }; - if let Some(pname) = playlist_name { - // only allow direct playables from playlists - let ty = it.item_type.as_deref().unwrap_or(""); + let ty = selected_item.item_type.as_deref().unwrap_or(""); + + // ------------------------- + // CASE 1: We are INSIDE a playlist view (already works) + // ------------------------- + if let Some(pctx) = playlist_ctx { let playable = matches!(ty, "Movie" | "Episode" | "Audio"); if !playable { app.status = "Playlist downloads only support Movie/Episode/Audio".into(); @@ -1157,15 +1076,53 @@ fn handle_key(app: &mut App, code: KeyCode) { } dm.send(downloads::DownloadCommand::EnqueuePlaylistItem { - item: it, - playlist_name: pname, - playlist_index, + item: selected_item, + playlist_name: pctx.name, + playlist_index: selected_index, }); app.status = "queued 1 (playlist)".into(); return; } - match downloads::expand_for_enqueue(&jf, user_id, &it) { + // ------------------------- + // CASE 2: We are on the PLAYLIST LIST and selected item IS a playlist + // -> enqueue via playlist-aware path so we get hardlinks/order + // ------------------------- + if ty == "Playlist" { + app.status = format!("Fetching playlist… {}", selected_item.name); + + match client.playlist_items(user_id, &selected_item.id, 0, 200) { + Ok(page) => { + let pname = selected_item.name.clone(); + let mut n = 0usize; + + for (i, it) in page.items.into_iter().enumerate() { + let it_ty = it.item_type.as_deref().unwrap_or(""); + let playable = matches!(it_ty, "Movie" | "Episode" | "Audio"); + if !playable { continue; } + + dm.send(downloads::DownloadCommand::EnqueuePlaylistItem { + item: it, + playlist_name: pname.clone(), + playlist_index: i, + }); + n += 1; + } + + app.status = format!("queued {n} (playlist)"); + } + Err(e) => { + app.status = format!("Playlist load failed: {e}"); + } + } + + return; + } + + // ------------------------- + // CASE 3: Normal (non-playlist-container) download behavior + // ------------------------- + match downloads::expand_for_enqueue(&client, user_id, &selected_item) { Ok(items) => { let n = items.len(); dm.send(downloads::DownloadCommand::Enqueue(items)); @@ -1176,6 +1133,7 @@ fn handle_key(app: &mut App, code: KeyCode) { return; } + KeyCode::Char('q') => app.should_exit = true, //Enter code Block @@ -1878,20 +1836,8 @@ fn ui(frame: &mut Frame, app: &App) { .map(|c| c.base_url.as_str()) .unwrap_or("-"); - let mbps = app - .config - .as_ref() - .map(|c| c.transcode_mbps) - .unwrap_or(5.0); - - let transcode_line = if app.transcoding { - format!("Transcoding On ({}Mbps)", mbps) - } else { - "Transcoding Off".to_string() - }; - let right_text = format!( - "{connected}\n{transcode_line}\np/P: play/autoplay + "{connected}\n\np/P: play/autoplay r/R: resume/autoplay d: download / cancel q: quit @@ -2385,7 +2331,7 @@ fn autoplay_tick(app: &mut App) { // Snapshot latest mpv state from poller thread let st = app.mpv_state.clone(); - // Optional: live debug in status (toggle with 'M' in your keybinds) + // Optional: live debug in status (toggle with 'D') if app.debug_mpv { app.status = fmt_mpv_state(&st); } @@ -2441,151 +2387,126 @@ fn autoplay_tick(app: &mut App) { } }; - // Choose next target based on current view - enum NextTarget { - Online { id: String, name: String, len: usize }, - Offline { path: PathBuf, name: String, len: usize }, - } + // Choose next target based on current view + enum NextTarget { + Online { id: String, name: String, len: usize }, + Offline { path: PathBuf, name: String, len: usize }, + } - let next = match app.current_view() { - View::Library { items, .. } if next_i < items.len() => NextTarget::Online { - id: items[next_i].id.clone(), - name: items[next_i].name.clone(), - 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(); + let next = match app.current_view() { + View::Library { items, .. } if next_i < items.len() => { + NextTarget::Online { + id: items[next_i].id.clone(), + name: items[next_i].name.clone(), + len: items.len(), } - return; } - - NextTarget::Offline { - path: entries[j].path.clone(), - name: entries[j].name.clone(), - len: entries.len(), - } - } - - _ => { - app.autoplay = false; - app.autoplay_next_index = None; - if !app.debug_mpv { - app.status = "$".into(); - } - return; - } - }; - - // Update "now playing" - match &next { - NextTarget::Online { name, .. } => app.mpv_now_playing = Some(name.clone()), - NextTarget::Offline { name, .. } => app.mpv_now_playing = Some(name.clone()), - } - - // Move selection highlight in UI - match app.view_stack.last_mut() { - Some(View::Library { selected, .. }) => { - *selected = next_i; - } - Some(View::OfflineLibrary { - selected, - entries, - .. - }) => { - // 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 skip-dirs happens on next tick too) - let len = match &next { - 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 => { + 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; - app.status = "No config".into(); + if !app.debug_mpv { app.status = "$".into(); } return; } - }; - // If offline, MUST be local - let local = crate::core::downloads::local_media_path_for_item_id(&next_id); - if app.offline && local.is_none() { + NextTarget::Offline { + path: entries[j].path.clone(), + name: entries[j].name.clone(), + len: entries.len(), + } + } + _ => { app.autoplay = false; app.autoplay_next_index = None; - app.status = "Offline: next item not downloaded".into(); + if !app.debug_mpv { app.status = "$".into(); } return; } + }; - let url = if let Some(p) = local { - p.to_string_lossy().to_string() - } else if app.transcoding { - build_jellyfin_play_url_transcode_forced(&cfg, &next_id) - .unwrap_or_else(|| build_jellyfin_play_url(&cfg, &next_id, true)) - } else { - build_jellyfin_play_url(&cfg, &next_id, false) - }; + match &next { + NextTarget::Online { name, .. } => app.mpv_now_playing = Some(name.clone()), + NextTarget::Offline { name, .. } => app.mpv_now_playing = Some(name.clone()), + } - // Local vs remote loader - let r = if url.starts_with('/') { - mpv_load_local(mpv, &url) - } else { - mpv_load_url(&cfg, mpv, &url) - }; + // Move selection highlight in UI + compute following index + match app.view_stack.last_mut() { + Some(View::Library { selected, .. }) => { + *selected = next_i; + } + Some(View::OfflineLibrary { selected, entries, .. }) => { + // 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 let Err(e) = r { - app.autoplay = false; - app.autoplay_next_index = None; - app.status = format!("autoplay load failed: {e}"); - return; + // compute next index (offline should skip dirs too later) + let len = match &next { + 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_next_index = None; + app.status = "No config".into(); + return; + } + }; + + // If offline, MUST be local + let local = crate::core::downloads::local_media_path_for_item_id(&next_id); + if app.offline && local.is_none() { + app.autoplay = false; + app.autoplay_next_index = None; + app.status = "Offline: next item not downloaded".into(); + return; + } + + let url = if let Some(p) = local { + p.to_string_lossy().to_string() + } else { + build_jellyfin_play_url(&cfg, &next_id) + }; + + if let Err(e) = mpv_load_url(&cfg, mpv, &url) { + app.autoplay = false; + app.autoplay_next_index = None; + app.status = format!("autoplay load failed: {e}"); + return; + } + } + + NextTarget::Offline { path, .. } => { + let url = path.to_string_lossy().to_string(); + if let Err(e) = mpv_load_local(mpv, &url) { + app.autoplay = false; + app.autoplay_next_index = None; + app.status = format!("offline autoplay load failed: {e}"); + return; + } } } - NextTarget::Offline { path, .. } => { - let url = path.to_string_lossy().to_string(); - if let Err(e) = mpv_load_local(mpv, &url) { - 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(); } - } - - 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> { @@ -3308,22 +3229,9 @@ fn clamp_mbps_to_bps(mbps: u32) -> u32 { mbps.saturating_mul(1_000_000) // Mb/s -> bits/s } -fn build_jellyfin_play_url(cfg: &core::config::Config, item_id: &str, transcoding_on: bool) -> String { +fn build_jellyfin_play_url(cfg: &core::config::Config, item_id: &str) -> String { let base = cfg.base_url.trim_end_matches('/'); - - // Transcoding OFF => keep existing behavior exactly. - if !transcoding_on { - return format!("{}/Items/{}/Download", base, item_id); - } - - // Transcoding ON => use HLS "main" (does NOT require mediaSourceId) - // videoBitRate expects bits/sec, e.g. 5_000_000 - let max_bps: u64 = (cfg.transcode_mbps.max(0.01) * 1_000_000.0) as u64; - - format!( - "{}/Videos/{}/main.m3u8?videoBitRate={}&static=false", - base, item_id, max_bps - ) + format!("{}/Items/{}/Download", base, item_id) } fn mpv_cmd_reply(socket: &PathBuf, cmd: &str) -> Result { @@ -3478,7 +3386,6 @@ fn categories_for_mode(offline: bool) -> Vec { if offline { vec![ "Downloaded".into(), - "Settings".into(), ] } else { vec![ @@ -3490,7 +3397,6 @@ fn categories_for_mode(offline: bool) -> Vec { "Libraries".into(), "Continue Watching".into(), "Recently Added".into(), - "Settings".into(), ] } } @@ -3593,23 +3499,3 @@ fn render_offline_library_dir( right, ); } - -fn build_jellyfin_play_url_transcode_forced( - cfg: &core::config::Config, - item_id: &str, -) -> Option { - 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)) - } -}