Skip to content

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

feat(stream): prioritize high-quality streams and fix resolution sorting

Samir Hossains420b5461e510
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f4fb955..fd23134 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,14 @@
- Prevented blank audio track gap in episode details by mapping standalone `"Dub"` version tags to `"English Dub"` in `clean_language_name` (`src/tui/screens/details.rs`).
- Added native `540p` resolution badge mapping in `src/tui/widgets/badge.rs` to distinguish true `540p` media encodes from `480p`.
- Deduplicated episode entries in `src/providers/dramachi/client.rs` across multi-resolution manifests, preventing duplicate episode rows while sorting available streams in descending resolution priority.
+- **4KHDHub Resolution Detection & Numeric Sorting**:
+ - Expanded `detect_quality` in `src/providers/fourkhdhub/parser.rs` to detect `4K`, `UHD`, `2160`, `1080`, `FHD`, `720`, `HD`, and `480` tokens.
+ - Replaced ASCII string sorting with numeric resolution sorting (`resolution_u64()` descending, then `size_bytes` descending) in `parse_releases`, ensuring 4K UHD BluRay REMUXes prioritize ahead of lower-resolution streams.
+- **MovieBox High-Bitrate Server Catalog Merging**:
+ - Merged mobile DASH manifests (`/subject-api/play-info/v2`) and full-bitrate server files (`/subject-api/resource`) concurrently in `MovieBoxClient::episode_streams` (`src/providers/moviebox/mod.rs`), deduplicating stream links and sorting releases by numeric resolution and size.
+- **External Player Adaptive Quality Optimization**:
+ - Added `--ytdl-format=bestvideo+bestaudio/best` and `--hls-bitrate=max` to `mpv` command invocation in `src/player.rs` to prevent adaptive demuxers from locking into low-bitrate streams.
+ - Added `--adaptive-logic=highest` to VLC invocation in `src/player.rs`.
### Changed
- **Minimalist Addon Manager Modal Redesign & Balanced Geometry**:
- Streamlined Addon Manager popup into a content-fitted modal matching the provider popup design language, eliminating empty right-side letterboxing and arbitrary vertical blank gaps.
diff --git a/docs/players.md b/docs/players.md
index 2f25554..faab7fe 100644
--- a/docs/players.md
+++ b/docs/players.md
@@ -18,8 +18,8 @@ Resolution caches detected paths across runs while allowing newly installed play
| Player | Invocation | Notes |
| :--- | :--- | :--- |
-| mpv | `mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no [--start=..] [--script=..] [--script-opts=..] [--http-header-fields=..] [--sub-file=..] <url>` | Window sized to the terminal. Injects `moviebox_tracker.lua` for position tracking and resume. Each non-UA, non-Referer header is passed as a separate `--http-header-fields` argument. Flatpak mpv is launched via `flatpak run`. |
-| VLC | `vlc --width=W --height=H --play-and-exit [--start-time=..] [--http-referrer=..] [--http-user-agent=..] [--sub-file=..] <url>` | Supports start time resume via `--start-time`. For CloudFront cookie-gated streams (MovieBox DASH), the URL is replaced by a loopback sidecar proxy address (`http://127.0.0.1:<port>/https/<host>/path`) that injects all auth headers server-side before forwarding chunks to VLC. |
+| mpv | `mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no --ytdl-format=bestvideo+bestaudio/best --hls-bitrate=max [--start=..] [--script=..] [--script-opts=..] [--http-header-fields=..] [--sub-file=..] <url>` | Window sized to the terminal. Injects `moviebox_tracker.lua` for position tracking and resume. Sets maximum adaptive stream bitrate and best video/audio format selection. Each non-UA, non-Referer header is passed as a separate `--http-header-fields` argument. Flatpak mpv is launched via `flatpak run`. |
+| VLC | `vlc --width=W --height=H --play-and-exit --adaptive-logic=highest [--start-time=..] [--http-referrer=..] [--http-user-agent=..] [--sub-file=..] <url>` | Sets adaptive logic to highest representation. Supports start time resume via `--start-time`. For CloudFront cookie-gated streams (MovieBox DASH), the URL is replaced by a loopback sidecar proxy address (`http://127.0.0.1:<port>/https/<host>/path`) that injects all auth headers server-side before forwarding chunks to VLC. |
| IINA | `iina-cli --keep-running --no-stdin --mpv-autofit=.. [--mpv-start=..] [--mpv-http-header-fields=..] [--mpv-sub-files=..] <url>` | Uses the installed IINA `iina-cli`; falls back to `open -a IINA <url>` with an informational status warning if the CLI is absent. |
| Android / Termux | `termux-open --chooser --content-type video/* <url>` (or `termux-open-url` / `termux-am`) | Opens an app chooser on the device, delegating playback to external apps (VLC, MX Player, Just Player, MPV Android). Requires `pkg install -y termux-tools termux-am`. Forwards `User-Agent`, `Referer`, and subtitles when using `termux-am`. |
diff --git a/docs/providers.md b/docs/providers.md
index e6193ed..3c3b330 100644
--- a/docs/providers.md
+++ b/docs/providers.md
@@ -65,9 +65,7 @@ Adding a new streaming or BDIX provider to MovieBox TUI takes 3 simple steps:
- Hosts are retried; a shared runtime token is re-initialized when all hosts fail.
- Mobile `User-Agent` generated by the crypto module is forwarded through playback and download
pipelines to satisfy CDN anti-bot checks.
-- Stream resolution in `providers/moviebox/mod.rs` resolves directly through `play-info/v2` with
- automatic deprecation notice URL filtering (`is_deprecation_notice_url`), preventing obsolete
- CDN placeholder videos from leaking into the stream selector when episodes lack valid streams.
+- Stream resolution in `providers/moviebox/mod.rs` merges mobile DASH manifests (`play-info/v2`) and high-bitrate community/server releases (`/subject-api/resource`) with automatic deprecation notice URL filtering (`is_deprecation_notice_url`), deduplicating stream links and sorting releases by descending numeric quality and byte size.
- Multi-resolution discovery (`fetch_collection_resolutions`) dynamically discovers available
stream resolutions with descending quality sorting.
- Multi-resolution DASH manifests (`index.mpd`) and adaptive streams are labeled with a distinct
@@ -76,8 +74,9 @@ Adding a new streaming or BDIX provider to MovieBox TUI takes 3 simple steps:
- **DASH Manifest Playback & Downloads**: Media streams are hosted on CloudFront as segmented MPEG-DASH manifests (`index.mpd`) protected by signed policy cookies. Stream playback forwards `Cookie`, `Referer`, and `User-Agent` headers to external players (`mpv`, `IINA`). Local downloads utilize `yt-dlp` with forwarded authentication headers to demux and assemble audio/video streams into `.mp4`.
## 4KHDHub
+- Quality detection in `parser.rs::detect_quality` normalizes `4K`, `UHD`, `2160`, `1080`, `FHD`, `720`, `HD`, and `480` tokens, ensuring 4K/2160p releases are never treated as unknown resolution.
+- Releases in `parser.rs::parse_releases` sort by numeric resolution (`resolution_u64()`) descending and file size descending, prioritizing 4K UHD BluRay REMUXes over lower-resolution encodes.
- `client.rs::resolve_release` resolves release mirrors concurrently using bounded-concurrency probing (`select_ok` in batches of 3) with a 3.5s per-probe timeout.
-- Direct links undergo automatic path percent-encoding normalization (`validate_playback_url`) to handle filenames containing unencoded spaces, brackets, and special characters.
- Preflight probes issue a bounded range probe (`Range: bytes=0-8191`) and inspect response bodies for expired mirror errors (`"Failed to extract link"`, `"Token Expired"`, `"404"`) to fail fast on expired torrents.
- `hubcloud.rs` scores and prioritizes candidate streams based on `ResolutionIntent`:
- **Playback (`ResolutionIntent::Playback`)**: Prioritizes seekable multi-connection streaming CDNs (`pixel.hubcloud.` -> Google Video CDN, Cloudflare R2, PixelDrain API) while deprioritizing single-use download workers (`workers.dev`) to prevent HTTP 403 token-burn and player authentication popups.
diff --git a/src/player.rs b/src/player.rs
index 8f2a8ff..a419ca6 100644
--- a/src/player.rs
+++ b/src/player.rs
@@ -410,7 +410,8 @@ fn mpv_command(
if !iina {
command.arg("--idle=no").arg("--keep-open=no");
}
-
+ command.arg(format!("{prefix}ytdl-format=bestvideo+bestaudio/best"));
+ command.arg(format!("{prefix}hls-bitrate=max"));
if let Some(start) = resume_seconds {
if start > 0 {
command.arg(format!("{prefix}start={start}"));
@@ -627,7 +628,7 @@ fn vlc_command(
.arg(format!("--height={height}"));
}
command.arg("--play-and-exit");
-
+ command.arg("--adaptive-logic=highest");
if let Some(start) = resume_seconds {
if start > 0 {
command.arg(format!("--start-time={start}"));
diff --git a/src/providers/fourkhdhub/parser.rs b/src/providers/fourkhdhub/parser.rs
index 928805f..7b2b0b2 100644
--- a/src/providers/fourkhdhub/parser.rs
+++ b/src/providers/fourkhdhub/parser.rs
@@ -225,7 +225,12 @@ pub fn parse_releases(
}
}
let mut releases = grouped.into_values().collect::<Vec<_>>();
- releases.sort_by(|left, right| right.quality.cmp(&left.quality));
+ releases.sort_by(|left, right| {
+ right
+ .resolution_u64()
+ .cmp(&left.resolution_u64())
+ .then_with(|| right.size_bytes.cmp(&left.size_bytes))
+ });
Ok(releases)
}
@@ -390,14 +395,22 @@ fn parse_size_bytes(value: &str) -> Option<u64> {
}
fn detect_quality(value: &str) -> Option<String> {
- ["2160p", "1080p", "720p", "480p"]
- .into_iter()
- .find(|quality| {
- value
- .to_ascii_lowercase()
- .contains(&quality.to_ascii_lowercase())
- })
- .map(str::to_string)
+ let lower = value.to_ascii_lowercase();
+ if lower.contains("2160p")
+ || lower.contains("2160")
+ || lower.contains("4k")
+ || lower.contains("uhd")
+ {
+ Some("2160p".to_string())
+ } else if lower.contains("1080p") || lower.contains("1080") || lower.contains("fhd") {
+ Some("1080p".to_string())
+ } else if lower.contains("720p") || lower.contains("720") || lower.contains("hd") {
+ Some("720p".to_string())
+ } else if lower.contains("480p") || lower.contains("480") || lower.contains("sd") {
+ Some("480p".to_string())
+ } else {
+ None
+ }
}
fn detect_codec(value: &str) -> Option<String> {
@@ -578,4 +591,27 @@ mod tests {
assert_eq!(strip_trailing_year("12345"), "12345");
assert_eq!(strip_trailing_year("123456"), "123456");
}
+ #[test]
+ fn test_detect_quality_tokens() {
+ use super::detect_quality;
+ assert_eq!(
+ detect_quality("Inception (2010) 4K UHD BluRay REMUX").as_deref(),
+ Some("2160p")
+ );
+ assert_eq!(
+ detect_quality("Movie.2160p.HDR.x265").as_deref(),
+ Some("2160p")
+ );
+ assert_eq!(
+ detect_quality("Show.S01E01.FHD.1080p.mkv").as_deref(),
+ Some("1080p")
+ );
+ assert_eq!(
+ detect_quality("Video.1080.WEB-DL").as_deref(),
+ Some("1080p")
+ );
+ assert_eq!(detect_quality("Film.720p.HD.x264").as_deref(), Some("720p"));
+ assert_eq!(detect_quality("Old.Show.480p.SD").as_deref(), Some("480p"));
+ assert_eq!(detect_quality("Unknown.Release.Title"), None);
+ }
}
diff --git a/src/providers/moviebox/mod.rs b/src/providers/moviebox/mod.rs
index e21d369..ecc06da 100644
--- a/src/providers/moviebox/mod.rs
+++ b/src/providers/moviebox/mod.rs
@@ -62,16 +62,74 @@ impl crate::providers::ReleaseProvider for client::MovieBoxClient {
season: usize,
episode: usize,
) -> Result<Vec<crate::providers::models::Release>, ProviderError> {
- let json = self
- .get_play_info(id, season, episode)
- .await
- .map_err(ProviderError::from)?;
- Ok(adapt::moviebox_play_info_json_to_releases(
- &json,
- season,
- episode,
- self.user_agent(),
- ))
+ let (play_info_res, resources_res) = tokio::join!(
+ self.get_play_info(id, season, episode),
+ self.get_resources(
+ id,
+ season,
+ episode,
+ if episode > 0 {
+ (episode - 1) / 20 + 1
+ } else {
+ 1
+ },
+ None,
+ 20,
+ )
+ );
+
+ let mut releases = Vec::new();
+ let mut seen_urls = std::collections::HashSet::new();
+
+ if let Ok(json) = play_info_res {
+ for rel in adapt::moviebox_play_info_json_to_releases(
+ &json,
+ season,
+ episode,
+ self.user_agent(),
+ ) {
+ if let Some(url) = rel.direct_url() {
+ let base = url.split('?').next().unwrap_or(url).to_string();
+ if !base.is_empty() {
+ seen_urls.insert(base);
+ }
+ }
+ releases.push(rel);
+ }
+ }
+
+ if let Ok(res_json) = resources_res {
+ for rel in adapt::moviebox_resource_json_to_releases(&res_json) {
+ if let Some(url) = rel.direct_url() {
+ let base = url.split('?').next().unwrap_or(url).to_string();
+ if !base.is_empty() && seen_urls.contains(&base) {
+ continue;
+ }
+ seen_urls.insert(base);
+ }
+ if (season == 0 && episode == 0)
+ || (rel.season == Some(season) && rel.episode == Some(episode))
+ || (rel.season.is_none() && rel.episode.is_none())
+ {
+ releases.push(rel);
+ }
+ }
+ }
+
+ if releases.is_empty() {
+ return Err(ProviderError::Unavailable(
+ "No stream sources available".to_string(),
+ ));
+ }
+
+ releases.sort_by(|left, right| {
+ right
+ .resolution_u64()
+ .cmp(&left.resolution_u64())
+ .then_with(|| right.size_bytes.cmp(&left.size_bytes))
+ });
+
+ Ok(releases)
}
}