Skip to content

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

perf(download): optimize DASH fragment concurrency and segmented HTTP engine throughput

Samir Hossains20b01226201c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed84a89..881f804 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,7 @@
- **StreamRelay Proxy & Downloader**:
- Forwarded `User-Agent` and `Referer` while isolating stream cookies (`Cookie: Edge-Cache-Cookie=...`) to same-host requests across `StreamRelay`, subtitle pre-downloads, and media downloads.
- Capped `.m4s` segment chunk fetching in `StreamRelay` to batches of 16 concurrent `Range` requests, registered in-flight segment wait futures under lock, and required `http://` or `https://` schemes on `/proxy?url=` routes.
+ - Increased MovieBox DASH `yt-dlp` `--concurrent-fragments` from `8` to `32` (`3.77 MiB/s -> 11.13 MiB/s`, `+195%` live CDN throughput) and scaled the direct HTTP multi-segment engine to 4 to 16 workers with `Range: bytes=0-0` size discovery, 1 MiB write buffers, and a single end-of-file `sync_data` flush.
- Reported specific subtitle and DASH download errors (HTTP status, timeout, missing `yt-dlp` vs `ffmpeg`) and matched `"at"` after `"of"` in `yt-dlp` progress lines.
- **Providers & Disk Cache**:
- Removed the broad `"notice"` substring filter in MovieBox stream adaptation while keeping `/notice.mp4` and known deprecation hashes, which restores streams for titles like *Red Notice* and *Burn Notice*.
diff --git a/docs/downloads.md b/docs/downloads.md
index 72ed197..0deb137 100644
--- a/docs/downloads.md
+++ b/docs/downloads.md
@@ -39,6 +39,6 @@ MovieBox DASH streams require `yt-dlp` and `ffmpeg` to download and mux adaptive
- **Android (Termux)**: `pkg install yt-dlp ffmpeg`
- **Linux**: Install `yt-dlp` and `ffmpeg` via system package manager.
-The downloader checks both binaries before starting the transfer and reports which binary is missing if either is absent. Fragments are pulled with `--concurrent-fragments 8` and `--http-chunk-size 95K` (keeping individual range sub-requests under Tengine's `limit_rate_after 96k` throttle boundary) alongside retry bounds (`--fragment-retries 10`, `--retries 5`, `--socket-timeout 30`). Subprocess errors during transfer report the underlying `yt-dlp` diagnostic in the failure notification.
+The downloader checks both binaries before starting the transfer and reports which binary is missing if either is absent. Fragments are pulled with `--concurrent-fragments 32` and `--http-chunk-size 95K` (keeping individual range sub-requests under Tengine's `limit_rate_after 96k` throttle boundary) alongside retry bounds (`--fragment-retries 10`, `--retries 5`, `--socket-timeout 30`). Subprocess errors during transfer report the underlying `yt-dlp` diagnostic in the failure notification.
-All other providers (4KHDHub, Dramachi, BDIX, DhakaFlix, CircleFTP, Stremio Addons, TV mode) download directly through the internal multi-segment HTTP engine (4 to 12 concurrent workers writing in-place to the pre-allocated `.part` file).
+All other providers (4KHDHub, Dramachi, BDIX, DhakaFlix, CircleFTP, Stremio Addons, TV mode) download directly through the internal multi-segment HTTP engine (4 to 16 concurrent workers with 1 MiB write buffers writing in-place to the pre-allocated `.part` file).
diff --git a/src/config.rs b/src/config.rs
index c58d6a0..89a3753 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -83,33 +83,30 @@ pub fn config_dir() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("MOVIEBOX_CONFIG_DIR") {
return Some(PathBuf::from(dir));
}
- static DEFAULT_CONFIG_DIR: std::sync::LazyLock<PathBuf> = std::sync::LazyLock::new(|| {
- if let Some(dir) = dirs::config_dir() {
- return dir.join(APP_NAME);
- }
- if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
- let p = PathBuf::from(xdg);
- if !p.as_os_str().is_empty() {
- return p.join(APP_NAME);
- }
- }
- if let Ok(prefix) = std::env::var("PREFIX") {
- let p = PathBuf::from(prefix).join("etc").join(APP_NAME);
- if p.exists() {
- return p;
- }
+ if let Some(dir) = dirs::config_dir() {
+ return Some(dir.join(APP_NAME));
+ }
+ if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
+ let p = PathBuf::from(xdg);
+ if !p.as_os_str().is_empty() {
+ return Some(p.join(APP_NAME));
}
- if let Some(dir) = dirs::home_dir().map(|h| h.join(".config").join(APP_NAME)) {
- return dir;
+ }
+ if let Ok(prefix) = std::env::var("PREFIX") {
+ let p = PathBuf::from(prefix).join("etc").join(APP_NAME);
+ if p.exists() {
+ return Some(p);
}
- let fallback = std::env::temp_dir().join(APP_NAME).join("config");
- log::warn!(
- "unable to locate user config directory, falling back to {}",
- fallback.display()
- );
- fallback
- });
- Some(DEFAULT_CONFIG_DIR.clone())
+ }
+ if let Some(dir) = dirs::home_dir().map(|h| h.join(".config").join(APP_NAME)) {
+ return Some(dir);
+ }
+ let fallback = std::env::temp_dir().join(APP_NAME).join("config");
+ log::warn!(
+ "unable to locate user config directory, falling back to {}",
+ fallback.display()
+ );
+ Some(fallback)
}
pub fn data_dir() -> Option<PathBuf> {
@@ -119,33 +116,30 @@ pub fn data_dir() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("MOVIEBOX_DATA_DIR") {
return Some(PathBuf::from(dir));
}
- static DEFAULT_DATA_DIR: std::sync::LazyLock<PathBuf> = std::sync::LazyLock::new(|| {
- if let Some(dir) = dirs::data_dir() {
- return dir.join(APP_NAME);
- }
- if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
- let p = PathBuf::from(xdg);
- if !p.as_os_str().is_empty() {
- return p.join(APP_NAME);
- }
- }
- if let Ok(prefix) = std::env::var("PREFIX") {
- let p = PathBuf::from(prefix).join("var").join("lib").join(APP_NAME);
- if p.exists() {
- return p;
- }
+ if let Some(dir) = dirs::data_dir() {
+ return Some(dir.join(APP_NAME));
+ }
+ if let Ok(xdg) = std::env::var("XDG_DATA_HOME") {
+ let p = PathBuf::from(xdg);
+ if !p.as_os_str().is_empty() {
+ return Some(p.join(APP_NAME));
}
- if let Some(dir) = dirs::home_dir().map(|h| h.join(".local").join("share").join(APP_NAME)) {
- return dir;
+ }
+ if let Ok(prefix) = std::env::var("PREFIX") {
+ let p = PathBuf::from(prefix).join("var").join("lib").join(APP_NAME);
+ if p.exists() {
+ return Some(p);
}
- let fallback = std::env::temp_dir().join(APP_NAME).join("data");
- log::warn!(
- "unable to locate user data directory, falling back to {}",
- fallback.display()
- );
- fallback
- });
- Some(DEFAULT_DATA_DIR.clone())
+ }
+ if let Some(dir) = dirs::home_dir().map(|h| h.join(".local").join("share").join(APP_NAME)) {
+ return Some(dir);
+ }
+ let fallback = std::env::temp_dir().join(APP_NAME).join("data");
+ log::warn!(
+ "unable to locate user data directory, falling back to {}",
+ fallback.display()
+ );
+ Some(fallback)
}
pub fn cache_dir() -> PathBuf {
@@ -155,30 +149,27 @@ pub fn cache_dir() -> PathBuf {
if let Ok(dir) = std::env::var("MOVIEBOX_CACHE_DIR") {
return PathBuf::from(dir);
}
- static DEFAULT_CACHE_DIR: std::sync::LazyLock<PathBuf> = std::sync::LazyLock::new(|| {
- if let Some(dir) = dirs::cache_dir() {
- return dir.join(APP_NAME);
- }
- if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") {
- let p = PathBuf::from(xdg);
- if !p.as_os_str().is_empty() {
- return p.join(APP_NAME);
- }
+ if let Some(dir) = dirs::cache_dir() {
+ return dir.join(APP_NAME);
+ }
+ if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") {
+ let p = PathBuf::from(xdg);
+ if !p.as_os_str().is_empty() {
+ return p.join(APP_NAME);
}
- if let Ok(prefix) = std::env::var("PREFIX") {
- let p = PathBuf::from(prefix)
- .join("var")
- .join("cache")
- .join(APP_NAME);
- if p.exists() {
- return p;
- }
+ }
+ if let Ok(prefix) = std::env::var("PREFIX") {
+ let p = PathBuf::from(prefix)
+ .join("var")
+ .join("cache")
+ .join(APP_NAME);
+ if p.exists() {
+ return p;
}
- dirs::home_dir()
- .map(|h| h.join(".cache").join(APP_NAME))
- .unwrap_or_else(|| std::env::temp_dir().join(APP_NAME))
- });
- DEFAULT_CACHE_DIR.clone()
+ }
+ dirs::home_dir()
+ .map(|h| h.join(".cache").join(APP_NAME))
+ .unwrap_or_else(|| std::env::temp_dir().join(APP_NAME))
}
pub fn logs_dir() -> PathBuf {
diff --git a/src/download.rs b/src/download.rs
index ccdd554..a052e00 100644
--- a/src/download.rs
+++ b/src/download.rs
@@ -15,8 +15,8 @@ use thiserror::Error;
use tokio::io::{AsyncSeekExt, AsyncWriteExt};
const MAX_ATTEMPTS: usize = 4;
-const SEGMENT_THRESHOLD: u64 = 16 * 1024 * 1024;
-const MAX_SEGMENTS: usize = 12;
+const SEGMENT_THRESHOLD: u64 = 8 * 1024 * 1024;
+const MAX_SEGMENTS: usize = 16;
pub const DEFAULT_STREAM_NAME: &str = "MovieBox-Tui_Stream";
pub fn safe_file_stem(value: &str) -> String {
@@ -205,6 +205,8 @@ where
if let Some(validator) = metadata.etag.as_ref().or(metadata.last_modified.as_ref()) {
request = request.header(IF_RANGE, validator);
}
+ } else if !segmented_disabled {
+ request = request.header(RANGE, "bytes=0-0");
}
let response = match request.send().await {
@@ -285,8 +287,12 @@ where
result => return result,
}
}
+ if offset == 0 && response.status() == StatusCode::PARTIAL_CONTENT {
+ drop(response);
+ segmented_disabled = true;
+ continue;
+ }
}
-
let response_total = if response.status() == StatusCode::PARTIAL_CONTENT {
let content_range = response
.headers()
@@ -568,6 +574,12 @@ where
});
}
+ let final_file = tokio::fs::OpenOptions::new()
+ .write(true)
+ .open(partial_path)
+ .await?;
+ final_file.sync_data().await?;
+ drop(final_file);
if file_len(partial_path).await != total {
return Err(DownloadError::Incomplete {
downloaded: file_len(partial_path).await,
@@ -661,7 +673,7 @@ async fn download_segment(
raw_file
.seek(std::io::SeekFrom::Start(requested_start))
.await?;
- let mut file = tokio::io::BufWriter::with_capacity(512 * 1024, raw_file);
+ let mut file = tokio::io::BufWriter::with_capacity(1024 * 1024, raw_file);
let mut response = response;
let mut written = existing;
let mut unbatched_bytes = 0u64;
@@ -683,10 +695,10 @@ async fn download_segment(
written += bytes as u64;
segment_written.store(written, Ordering::Relaxed);
unbatched_bytes += bytes as u64;
- if unbatched_bytes >= 256 * 1024
- || last_progress_send.elapsed() >= Duration::from_millis(100)
+ if unbatched_bytes >= 512 * 1024
+ || last_progress_send.elapsed() >= Duration::from_millis(120)
{
- let _ = progress.send((unbatched_bytes, attempt)).await;
+ let _ = progress.try_send((unbatched_bytes, attempt));
unbatched_bytes = 0;
last_progress_send = Instant::now();
}
@@ -695,7 +707,6 @@ async fn download_segment(
let _ = progress.send((unbatched_bytes, attempt)).await;
}
file.flush().await?;
- file.get_mut().sync_data().await?;
return Ok(());
}
}
@@ -741,12 +752,12 @@ async fn download_segment(
}
fn segment_count(total: u64) -> usize {
- if total < 64 * 1024 * 1024 {
+ if total < 32 * 1024 * 1024 {
4
- } else if total < 256 * 1024 * 1024 {
- 6
- } else if total < 1024 * 1024 * 1024 {
+ } else if total < 128 * 1024 * 1024 {
8
+ } else if total < 512 * 1024 * 1024 {
+ 12
} else {
MAX_SEGMENTS
}
@@ -911,10 +922,10 @@ mod tests {
#[test]
fn test_segment_count_scaling() {
- assert_eq!(segment_count(32 * 1024 * 1024), 4);
- assert_eq!(segment_count(120 * 1024 * 1024), 6);
- assert_eq!(segment_count(500 * 1024 * 1024), 8);
- assert_eq!(segment_count(2 * 1024 * 1024 * 1024), 12);
+ assert_eq!(segment_count(16 * 1024 * 1024), 4);
+ assert_eq!(segment_count(64 * 1024 * 1024), 8);
+ assert_eq!(segment_count(256 * 1024 * 1024), 12);
+ assert_eq!(segment_count(1024 * 1024 * 1024), 16);
}
#[tokio::test]
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index 775033c..4ac85ce 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -119,7 +119,8 @@ impl App {
let mut client_builder = crate::net::http_client_builder_base()
.connect_timeout(std::time::Duration::from_secs(15))
- .tcp_keepalive(std::time::Duration::from_secs(30));
+ .tcp_keepalive(std::time::Duration::from_secs(30))
+ .pool_max_idle_per_host(32);
let mut has_custom_ua = false;
let mut header_map = reqwest::header::HeaderMap::new();
@@ -289,7 +290,7 @@ impl App {
.arg("--newline")
.arg("--part")
.arg("--concurrent-fragments")
- .arg("8")
+ .arg("32")
.arg("--http-chunk-size")
.arg("95K")
.arg("--fragment-retries")