Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

refactor: migrate to bounded channels, optimize file caching with MD5 hashing, and improve IINA/download performance

Samir Hossains02d45fad41f8
diff --git a/Cargo.lock b/Cargo.lock
index 6ca0b5c..f5e634b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1601,6 +1601,15 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+[[package]]
+name = "libmimalloc-sys"
+version = "0.1.49"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a45a52f43e1c16f667ccfe4dd8c85b7f7c204fd5e3bf46c5b0db9a5c3c0b8e9"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "libredox"
version = "0.1.18"
@@ -1761,6 +1770,15 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "mimalloc"
+version = "0.1.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d4139bb28d14ad1facf21d5eb8825051b326e172d216b39f6d31df53cc97862"
+dependencies = [
+ "libmimalloc-sys",
+]
+
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -1801,6 +1819,7 @@ dependencies = [
"image",
"lru",
"md-5",
+ "mimalloc",
"rand 0.10.2",
"ratatui",
"ratatui-image",
diff --git a/Cargo.toml b/Cargo.toml
index a52fddf..0c21c06 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -34,6 +34,7 @@ tokio = { version = "1.52.3", features = ["rt-multi-thread", "macros", "sync", "
url = "2.5.8"
unicode-segmentation = "1.12.0"
unicode-width = "0.2.0"
+mimalloc = "0.1.52"
[lib]
name = "moviebox_tui"
diff --git a/src/cache.rs b/src/cache.rs
index 4bceadc..d40f20a 100644
--- a/src/cache.rs
+++ b/src/cache.rs
@@ -62,6 +62,19 @@ pub fn get_cache_dir(subdir: &str) -> PathBuf {
get_provider_cache_dir(ProviderKind::MovieBox, subdir)
}
+fn hash_key(value: &str) -> String {
+ use md5::{Digest, Md5};
+ let mut hasher = Md5::new();
+ hasher.update(value.as_bytes());
+ let result = hasher.finalize();
+ let mut safe_query = String::with_capacity(32);
+ for b in result {
+ use std::fmt::Write;
+ let _ = write!(&mut safe_query, "{:02x}", b);
+ }
+ safe_query
+}
+
pub fn get_provider_cache_dir(provider: ProviderKind, subdir: &str) -> PathBuf {
let mut path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir);
path.push("moviebox-tui");
@@ -89,7 +102,8 @@ pub fn get_provider_stream_path(
} else {
""
};
- path.push(format!("{schema}{subject_id}_{season}_{episode}.json"));
+ let hashed_id = hash_key(subject_id);
+ path.push(format!("{schema}{hashed_id}_{season}_{episode}.json"));
path
}
@@ -131,7 +145,8 @@ pub fn get_provider_details_path(provider: ProviderKind, subject_id: &str) -> Pa
} else {
""
};
- path.push(format!("details_{schema}{subject_id}.json"));
+ let hashed_id = hash_key(subject_id);
+ path.push(format!("details_{schema}{hashed_id}.json"));
path
}
@@ -155,16 +170,8 @@ pub fn get_search_path(query: &str) -> PathBuf {
pub fn get_provider_search_path(provider: ProviderKind, query: &str) -> PathBuf {
let mut path = get_provider_cache_dir(provider, "search");
- use md5::{Digest, Md5};
- let mut hasher = Md5::new();
- hasher.update(query.as_bytes());
- let result = hasher.finalize();
- let mut safe_query = String::with_capacity(32);
- for b in result {
- use std::fmt::Write;
- let _ = write!(&mut safe_query, "{:02x}", b);
- }
- path.push(format!("search_{}.json", safe_query));
+ let hashed = hash_key(query);
+ path.push(format!("{hashed}.json"));
path
}
diff --git a/src/download.rs b/src/download.rs
index c74eecb..9d8244a 100644
--- a/src/download.rs
+++ b/src/download.rs
@@ -260,7 +260,7 @@ where
downloaded,
total: metadata.total,
bytes_per_second: if elapsed > 0.0 {
- downloaded as f64 / elapsed
+ downloaded.saturating_sub(offset) as f64 / elapsed
} else {
0.0
},
@@ -345,7 +345,7 @@ where
let downloaded = Arc::new(AtomicU64::new(initial));
let (progress_sender, mut progress_receiver) =
- tokio::sync::mpsc::unbounded_channel::<(u64, usize)>();
+ tokio::sync::mpsc::channel::<(u64, usize)>(64);
let mut tasks = tokio::task::JoinSet::new();
let validator = metadata.etag.clone().or(metadata.last_modified.clone());
@@ -473,7 +473,7 @@ async fn download_segment(
total: u64,
validator: Option<String>,
cancel: Arc<AtomicBool>,
- progress: tokio::sync::mpsc::UnboundedSender<(u64, usize)>,
+ progress: tokio::sync::mpsc::Sender<(u64, usize)>,
) -> Result<(), DownloadError> {
let expected = end - start + 1;
let mut last_error = None;
@@ -539,7 +539,7 @@ async fn download_segment(
let bytes = chunk.len().min(remaining as usize);
file.write_all(&chunk[..bytes]).await?;
written += bytes as u64;
- progress.send((bytes as u64, attempt)).ok();
+ let _ = progress.send((bytes as u64, attempt)).await;
if written == expected {
file.flush().await?;
file.sync_data().await?;
@@ -600,15 +600,19 @@ fn segment_path(destination: &Path, index: usize) -> PathBuf {
}
fn metadata_matches(previous: &ResumeMetadata, current: &ResumeMetadata) -> bool {
- previous.total == current.total
- && previous.segments == current.segments
- && match (&previous.etag, &current.etag) {
- (Some(previous), Some(current)) => previous == current,
- _ => match (&previous.last_modified, &current.last_modified) {
- (Some(previous), Some(current)) => previous == current,
- _ => true,
- },
- }
+ if previous.total != current.total || previous.segments != current.segments {
+ return false;
+ }
+
+ match (&previous.etag, &current.etag) {
+ (Some(a), Some(b)) => return a == b,
+ _ => {}
+ }
+
+ match (&previous.last_modified, &current.last_modified) {
+ (Some(a), Some(b)) => a == b,
+ _ => false,
+ }
}
async fn remove_segment_files(destination: &Path) {
diff --git a/src/main.rs b/src/main.rs
index bf96290..0402a0d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,5 +1,8 @@
use moviebox_tui::tui::app::App;
+#[global_allocator]
+static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
+
struct TerminalGuard;
impl Drop for TerminalGuard {
diff --git a/src/tui/event.rs b/src/tui/event.rs
index 306198d..3773277 100644
--- a/src/tui/event.rs
+++ b/src/tui/event.rs
@@ -4,14 +4,14 @@ use std::time::Duration;
use tokio::sync::mpsc;
pub struct EventHandler {
- receiver: mpsc::UnboundedReceiver<Action>,
+ receiver: mpsc::Receiver<Action>,
#[allow(dead_code)]
- sender: mpsc::UnboundedSender<Action>,
+ sender: mpsc::Sender<Action>,
}
impl EventHandler {
pub fn new(tick_rate: Duration) -> Self {
- let (sender, receiver) = mpsc::unbounded_channel();
+ let (sender, receiver) = mpsc::channel(128);
let event_sender = sender.clone();
let mut tick_interval = tokio::time::interval(tick_rate);
@@ -23,31 +23,31 @@ impl EventHandler {
loop {
tokio::select! {
_ = tick_interval.tick() => {
- let _ = event_sender.send(Action::Tick);
+ let _ = event_sender.try_send(Action::Tick);
}
Some(event) = reader.next() => {
match event {
Ok(CrosstermEvent::Key(key)) => {
let is_press = key.kind == KeyEventKind::Press;
- if is_press && event_sender.send(Action::Key(key)).is_err() {
+ if is_press && event_sender.send(Action::Key(key)).await.is_err() {
break;
}
}
Ok(CrosstermEvent::Mouse(mouse)) => {
match mouse.kind {
crossterm::event::MouseEventKind::ScrollUp => {
- let _ = event_sender.send(Action::Key(crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Up, crossterm::event::KeyModifiers::empty())));
+ let _ = event_sender.send(Action::Key(crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Up, crossterm::event::KeyModifiers::empty()))).await;
}
crossterm::event::MouseEventKind::ScrollDown => {
- let _ = event_sender.send(Action::Key(crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Down, crossterm::event::KeyModifiers::empty())));
+ let _ = event_sender.send(Action::Key(crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Down, crossterm::event::KeyModifiers::empty()))).await;
}
_ => {}
}
}
Ok(CrosstermEvent::FocusGained) => {
- let _ = event_sender.send(Action::FocusChange);
+ let _ = event_sender.send(Action::FocusChange).await;
}
- Ok(CrosstermEvent::Resize(w, h)) if event_sender.send(Action::Resize(w, h)).is_err() => {
+ Ok(CrosstermEvent::Resize(w, h)) if event_sender.send(Action::Resize(w, h)).await.is_err() => {
break;
}
_ => {}
diff --git a/src/tui/player.rs b/src/tui/player.rs
index 54f6a10..f3933ba 100644
--- a/src/tui/player.rs
+++ b/src/tui/player.rs
@@ -26,10 +26,7 @@ pub fn detect() -> Vec<PlayerKind> {
}
pub fn supports_headers(kind: PlayerKind, headers: &[(String, String)]) -> bool {
- kind != PlayerKind::Vlc
- || headers.iter().all(|(name, _)| {
- name.eq_ignore_ascii_case("referer") || name.eq_ignore_ascii_case("user-agent")
- })
+ kind != PlayerKind::Vlc || headers.is_empty()
}
pub fn command(
@@ -87,8 +84,13 @@ fn mpv_command(
#[cfg(target_os = "macos")]
fn iina_command(url: &str, subtitle: Option<&str>, headers: &[(String, String)]) -> Command {
- let mut command = Command::new("open");
- command.arg("-a").arg("IINA").arg("--args");
+ let mut command = if Path::new("/Applications/IINA.app").exists() {
+ let mut c = Command::new("open");
+ c.arg("-a").arg("IINA").arg("--args");
+ c
+ } else {
+ Command::new("iina")
+ };
let mpv = mpv_command(url, subtitle, headers, true);
command.args(mpv.get_args());
command