Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
fix(player): eliminate termux exit code 126 crash and harden intent openers
Samir Hossainsae4c2c4d9ade
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 770c8eb..b39495d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,11 @@- Added documentation build integrity validation step in CI hygiene pipeline (`.github/workflows/ci.yml`).### Fixed+- **Termux Android Player Exit Code 126 & Intent Bridge Resolution**:+ - Eliminated `Player Error: Crash code: 126 (/system/bin/am[11]: /data/data/com.termux/files/usr/bin/cmd: Permission denied)` crash in Termux on Android 10+ by prioritizing native Termux openers (`termux-open`, `termux-open-url`, `termux-am`) and strictly avoiding unprivileged `/system/bin/am` shell script calls.+ - Preserved `LD_PRELOAD` for Termux applet compatibility while prepending system paths (`/system/bin:/system/xbin`) for system command invocations.+ - Added actionable diagnostic notifications when player execution fails or when no player is detected in Termux, directing users to install `termux-tools termux-am` and verify an external Android player (VLC, Just Player, MX Player).+ - Updated universal installer (`install.sh`), README, and documentation guides with `termux-am` prerequisites and architecture details explaining external Android video player integration versus headless CLI `mpv`.- **Android Intent Player Stream Compatibility**:- Eliminated blanket player incompatibility errors on Android: unauthenticated streams (CircleFTP, DhakaFlix, IPTV, direct streams) and streams carrying standard `Referer`/`User-Agent` headers (4KHDHub) now dispatch directly to Android video players via `termux-open` or `am start`.- Added empty-header guard to `supports_headers`, ensuring streams without authentication requirements are never falsely rejected as incompatible.diff --git a/README.md b/README.mdindex f4066ad..e97ba3d 100644--- a/README.md+++ b/README.md@@ -25,7 +25,7 @@ MovieBox-TUI delegates video decoding to an external media player. Install at le| **mpv** *(Recommended)* | Linux, macOS, Windows | `brew install mpv` / `sudo apt install mpv` / `winget install mpv` || **IINA** | macOS (Native GUI) | `brew install --cask iina` || **VLC** | Cross-platform | `brew install --cask vlc` / `sudo apt install vlc` / `winget install VideoLAN.VLC` |-| **Android Player** | Android (Termux) | `pkg install termux-tools` *(launches VLC or Nova)* |+| **Android Player** | Android (Termux) | `pkg install -y termux-tools termux-am` *(launches external player)* |## Installation@@ -52,13 +52,15 @@ irm https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.ps1 | i### Android (Termux)-Install Termux tools, download the native precompiled Android ARM64 binary via the installer, and grant storage permissions:+Install Termux tools and the intent bridge, download the native precompiled Android ARM64 binary via the installer, and grant storage permissions:```bash-pkg update && pkg install -y curl tar termux-tools+pkg update && pkg install -y curl tar termux-tools termux-amcurl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh -o install.sh && bash install.shtermux-setup-storage```+> **Video Playback on Android**: Playback on Android is handled by external video player apps (**VLC**, **MX Player**, **Just Player**, or **MPV Android APK**) launched via Android Intent. Installing CLI `mpv` inside Termux (`pkg install mpv`) provides terminal/audio-only output because Android does not expose a desktop video surface to terminal sessions.+<details><summary><b>Manual & Developer Builds (Cargo)</b></summary>diff --git a/docs/README.md b/docs/README.mdindex 06d1115..162c410 100644--- a/docs/README.md+++ b/docs/README.md@@ -27,7 +27,7 @@ MovieBox-TUI delegates video decoding to an external media player. Install at le| **mpv** *(Recommended)* | Linux, macOS, Windows | `brew install mpv` / `sudo apt install mpv` / `winget install mpv` || **IINA** | macOS (Native GUI) | `brew install --cask iina` || **VLC** | Cross-platform | `brew install --cask vlc` / `sudo apt install vlc` / `winget install VideoLAN.VLC` |-| **Android Player** | Android (Termux) | `pkg install termux-tools` *(launches VLC or Nova)* |+| **Android Player** | Android (Termux) | `pkg install -y termux-tools termux-am` *(launches external player)* |---diff --git a/docs/cross-platform.md b/docs/cross-platform.mdindex 20f30d3..7f5dee1 100644--- a/docs/cross-platform.md+++ b/docs/cross-platform.md@@ -15,7 +15,7 @@ the release checks in [`release-checklist.md`](release-checklist.md).| macOS | IINA preferred player (via the installed IINA `iina-cli`); VLC/mpv `.app` paths detected. `process_group(0)` on spawn. || Windows | mpv/VLC detected via Program Files + `%LOCALAPPDATA%`; path-safe file stems; static MSVC CRT linking (`+crt-static`) for zero-dependency standalone binaries; handle-safe atomic download replacement (dropping file handles before renames); background update helper spawned with `CREATE_NO_WINDOW` (`0x08000000`). || Linux | Flatpak mpv/VLC supported (`flatpak run …`); xdg data/cache dirs. |-| Android (Termux) | Targets `aarch64-linux-android` linked against the Android NDK (Clang API 24+) and system Bionic `libc.so`, producing a native ELF executable with a valid `PT_PHDR` program header table and `/system/bin/linker64` dynamic loader. This eliminates `Could not find a PHDR: broken executable?` crashes and executes natively without on-device compilation. Includes a pure-Rust DNS resolver that reads system configuration and falls back to public resolvers (Cloudflare, Google, Quad9) for zero-config name resolution, and dynamically checks for `termux-open`, `termux-open-url`, `termux-am`, or in-terminal `mpv`; playback strips `LD_LIBRARY_PATH` and `LD_PRELOAD` before launching the chooser. Android intent playback supports unauthenticated streams (CircleFTP, DhakaFlix, IPTV) and standard CDN streams (4KHDHub); streams requiring signed CloudFront cookies (MovieBox) require in-terminal `mpv`. Real-device chooser behavior is a release prerequisite; Proot/Termux X11 behavior is unsupported unless separately tested. |+| Android (Termux) | Targets `aarch64-linux-android` linked against the Android NDK (Clang API 24+) and system Bionic `libc.so`, producing a native ELF executable with a valid `PT_PHDR` program header table and `/system/bin/linker64` dynamic loader. This eliminates `Could not find a PHDR: broken executable?` crashes and executes natively without on-device compilation. Includes a pure-Rust DNS resolver that reads system configuration and falls back to public resolvers (Cloudflare, Google, Quad9) for zero-config name resolution. Android playback delegates to external video players (VLC for Android, Just Player, MX Player, MPV Android) via Termux intent dispatchers (`termux-open`, `termux-open-url`, `termux-am`), requiring `pkg install -y termux-tools termux-am`. To protect against Android 10+ SELinux execute restrictions (exit code 126), system `/system/bin/am` fallbacks are strictly avoided in Termux; `LD_PRELOAD` is preserved for Termux applets while `PATH` is sanitized for system calls. Android intent playback supports unauthenticated streams (CircleFTP, DhakaFlix, IPTV) and standard CDN streams (4KHDHub). Real-device chooser behavior is a release prerequisite. |## Terminal capabilitiesdiff --git a/docs/installation.md b/docs/installation.mdindex 7a30ae2..54a7d48 100644--- a/docs/installation.md+++ b/docs/installation.md@@ -34,16 +34,18 @@ irm https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.ps1 | i## Android (Termux)-Install Termux tools, run the installer script to fetch the precompiled native Android ARM64 binary, and grant storage permissions:+Install Termux tools and the intent bridge, run the installer script to fetch the precompiled native Android ARM64 binary, and grant storage permissions:```bash-pkg update && pkg install -y curl tar termux-tools+pkg update && pkg install -y curl tar termux-tools termux-amcurl -fsSL https://raw.githubusercontent.com/mesamirh/MovieBox-Tui/main/install.sh -o install.sh && bash install.shtermux-setup-storage```The installer automatically downloads the native Android ARM64 release package (`MovieBox_Android_arm64.tar.gz`) built against the Android NDK and Bionic libc, requiring zero on-device compilation.+> **Media Player Requirements**: Android streams are rendered through external Android video players (such as **VLC for Android**, **MX Player**, **Just Player**, or **MPV Android APK**) triggered via `termux-open` or `termux-am`. Command-line `mpv` installed directly in Termux (`pkg install mpv`) runs without a video output surface unless an X11 desktop environment (like Termux:X11) is configured.+To compile from source on Termux:```bashdiff --git a/docs/players.md b/docs/players.mdindex ce34c07..0139bb2 100644--- a/docs/players.md+++ b/docs/players.md@@ -10,7 +10,7 @@ builds the exact command; `tui/app/playback.rs` spawns it.- macOS: IINA (if present), then mpv, then VLC (probing `/Applications`, `~/Applications`, Homebrew `/opt/homebrew/bin`, MacPorts `/opt/local/bin`, Nix profiles `~/.nix-profile/bin` and `/run/current-system/sw/bin`, and standard `/bin`).- Linux: mpv, then VLC (probing native `$PATH`, user `.local/bin`, Flathub/Flatpak user & system exports `org.videolan.VLC` / `io.mpv.Mpv`, Snap `/snap/bin/*`, Nix profiles, standard `/bin`, and `flatpak run`).- Windows: mpv, then VLC (probing executable-adjacent binaries, WinGet Links & Packages directory `%LOCALAPPDATA%\Microsoft\WinGet\Packages`, `%USERPROFILE%\Downloads` and `%USERPROFILE%\Desktop` extractions, `Program Files` including `mpv`, `mpv-player`, `mpv.net`, and `VideoLAN\VLC`, `LOCALAPPDATA\Programs`, portable drive roots `C:\mpv`, `C:\vlc`, `C:\tools`, Scoop shims & apps, Chocolatey, and Windows Registry `App Paths` and `Environment\Path`).-- Android/Termux: `mpv` (if installed via `pkg install mpv`), or Android intent chooser (`termux-open`, `termux-open-url`, `termux-am`, or `/system/bin/am`).+- Android/Termux: Android intent chooser (`termux-open`, `termux-open-url`, or `termux-am`). Streams play via external Android video players (VLC for Android, Just Player, MX Player, MPV Android APK).Resolution caches detected paths across runs while allowing newly installed players to be discovered dynamically when opening or navigating the Settings Hub (`/settings`), without requiring an application restart. A preferred player can be forced via `MOVIEBOX_PLAYER` env or `default_player` in config (e.g. `mpv`, `iina`, `vlc`, `android`), which reorders the list. The media player picker in the Settings Hub lists every detected player on your system and saves your selection to `config.json`. Playback launches directly using the preferred compatible player without intermediate modal dialogs.@@ -21,7 +21,7 @@ Resolution caches detected paths across runs while allowing newly installed play| 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. 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`. || 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>` only 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. When launched via `termux-am` or `am`, forwards `User-Agent`, `Referer`, and subtitles (`subtitles_location`/`subs`). |+| 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`. |Window size is derived from the live terminal size times the font cell size reportedby the image picker, then clamped to a fixed range.@@ -57,3 +57,14 @@ When launching media with in-progress watch history, the player command automatiprocess group (Unix) or no-console flag (Windows). A blocking task reads stderr andreports every non-zero process exit as a player error, including failures with nodiagnostic output. Watch progress is reconciled only after a successful exit.++## Android / Termux Playback Architecture++On Android (Termux), terminal sessions do not have access to an X11 or Wayland display server by default:++- **Command-Line `mpv` (`pkg install mpv`)**: Operates in headless/audio-only mode. Video output cannot be rendered to the terminal screen and will fail or produce audio without video.+- **External Player Intent Dispatch**: Video playback is designed to open in dedicated Android video player applications (**VLC for Android**, **Just Player**, **MX Player**, or **MPV Android APK**).+- **Prerequisites**: Termux requires `pkg install -y termux-tools termux-am`.+ - `termux-open` (from `termux-tools`) broadcasts an `android.intent.action.VIEW` intent to `TermuxOpenReceiver`, presenting Android's native app chooser.+ - `termux-am` (from `termux-am`) connects directly to `termux-app`'s local Unix domain socket (`am.sock`), allowing intent parameter passing (including `User-Agent`, `Referer`, and subtitles).+ - **SELinux & Exit Code 126 Protection**: On Android 10+, executing `/system/bin/am` directly from an unrooted Termux environment causes Android's system shell to call `cmd activity`, which is blocked by SELinux when executing Termux app data binaries (`Permission denied`, exit code 126). MovieBox-TUI detects Termux environments, prevents illegal system `am` invocations, preserves `LD_PRELOAD` for Termux applet compatibility, and surfaces actionable remediation notifications.diff --git a/install.sh b/install.shindex c73ff45..fa6a920 100755--- a/install.sh+++ b/install.sh@@ -624,8 +624,8 @@ elsePLAYER_DETECTED="mpv"elif command -v vlc >/dev/null 2>&1 || [ -f "$HOME/.local/share/flatpak/exports/bin/org.videolan.VLC" ] || [ -f "/var/lib/flatpak/exports/bin/org.videolan.VLC" ]; thenPLAYER_DETECTED="VLC"- elif command -v termux-open >/dev/null 2>&1; then- PLAYER_DETECTED="Android Player (termux-open)"+ elif command -v termux-open >/dev/null 2>&1 || command -v termux-am >/dev/null 2>&1; then+ PLAYER_DETECTED="Android Player (termux intent)"fifiprintf "\n"@@ -635,7 +635,7 @@ printf " %b•%b %bBinary:%b %b%s%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_REif [ -n "$PLAYER_DETECTED" ]; thenprintf " %b•%b %bPlayer:%b %b%s (ready)%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_RESET" "$C_GREEN" "$PLAYER_DETECTED" "$C_RESET"elif [ "$IS_TERMUX" -eq 1 ]; then- printf " %b•%b %bPlayer:%b %bNone detected (run 'pkg install termux-tools')%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_RESET" "$C_SAPPHIRE" "$C_RESET"+ printf " %b•%b %bPlayer:%b %bNone detected (run 'pkg install -y termux-tools termux-am')%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_RESET" "$C_SAPPHIRE" "$C_RESET"elseprintf " %b•%b %bPlayer:%b %bNone detected (mpv, VLC, or IINA recommended)%b\n" "$C_MUTED" "$C_RESET" "$C_MUTED" "$C_RESET" "$C_SAPPHIRE" "$C_RESET"fi@@ -650,10 +650,13 @@ printf " %b$ moviebox-tui%b\n\n" "$C_GREEN" "$C_RESET"if [ -z "$PLAYER_DETECTED" ]; thenif [ "$IS_TERMUX" -eq 1 ]; then- printf " %bℹ%b Note: Run %b'pkg install termux-tools'%b to enable video playback on Termux.\n\n" "$C_SAPPHIRE" "$C_RESET" "$C_BOLD" "$C_RESET"+ printf " %bℹ%b Note: Run %b'pkg install -y termux-tools termux-am'%b to enable video playback on Termux.\n" "$C_SAPPHIRE" "$C_RESET" "$C_BOLD" "$C_RESET"+ printf " Streams play via external Android players (VLC, MX Player, or Just Player).\n\n"elseprintf " %bℹ%b Note: A media player (mpv, VLC, or IINA) is recommended for video playback.\n\n" "$C_SAPPHIRE" "$C_RESET"fi+elif [ "$IS_TERMUX" -eq 1 ]; then+ printf " %bℹ%b Streams will open in your default Android video player (VLC, MX Player, or Just Player).\n\n" "$C_SAPPHIRE" "$C_RESET"fiif [ -n "$SHELL_MODIFIED" ]; thendiff --git a/src/player.rs b/src/player.rsindex 72b3bb7..88a4410 100644--- a/src/player.rs+++ b/src/player.rs@@ -134,7 +134,7 @@ fn probe_android_opener() -> Option<AndroidOpener> {if let Some(custom) = configured_executable("MOVIEBOX_ANDROID_PLAYER_PATH") {if custom.ends_with("termux-open-url") {return Some(AndroidOpener::TermuxOpenUrl(custom));- } else if custom.ends_with("termux-am") || custom.ends_with("/am") {+ } else if custom.ends_with("termux-am") {return Some(AndroidOpener::TermuxAm(custom));} else {return Some(AndroidOpener::TermuxOpen(custom));@@ -156,10 +156,6 @@ fn probe_android_opener() -> Option<AndroidOpener> {if Path::new(&termux_am).is_file() {return Some(AndroidOpener::TermuxAm(termux_am));}- let am_bin = format!("{prefix}/bin/am");- if Path::new(&am_bin).is_file() {- return Some(AndroidOpener::TermuxAm(am_bin));- }}let termux_open_static = "/data/data/com.termux/files/usr/bin/termux-open";@@ -176,10 +172,6 @@ fn probe_android_opener() -> Option<AndroidOpener> {if Path::new(termux_am_static).is_file() {return Some(AndroidOpener::TermuxAm(termux_am_static.to_string()));}- let termux_am_bin_static = "/data/data/com.termux/files/usr/bin/am";- if Path::new(termux_am_bin_static).is_file() {- return Some(AndroidOpener::TermuxAm(termux_am_bin_static.to_string()));- }if let Some(path) = find_in_path("termux-open") {return Some(AndroidOpener::TermuxOpen(path));@@ -244,7 +236,7 @@ fn android_intent_command(subtitle: Option<&str>,headers: &[(String, String)],) -> Command {- let mut command = match android_opener() {+ match android_opener() {Some(AndroidOpener::TermuxOpen(path)) => {let mut cmd = Command::new(path);cmd.arg("--chooser")@@ -282,6 +274,10 @@ fn android_intent_command(.arg("-t").arg("video/*");append_android_intent_extras(&mut cmd, subtitle, headers);+ let current_path = std::env::var("PATH").unwrap_or_default();+ cmd.env("PATH", format!("/system/bin:/system/xbin:{current_path}"));+ cmd.env_remove("LD_LIBRARY_PATH");+ cmd.env_remove("LD_PRELOAD");cmd}None => {@@ -292,12 +288,7 @@ fn android_intent_command(.arg(url);cmd}- };-- command.env_remove("LD_LIBRARY_PATH");- command.env_remove("LD_PRELOAD");-- command+ }}fn mpv_command(diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rsindex fb7411d..5f0e304 100644--- a/src/tui/app/playback.rs+++ b/src/tui/app/playback.rs@@ -151,11 +151,13 @@ impl App {PlaybackResolution::NoPlayersInstalled => {self.state.is_resolving_playback = false;self.state.pending_playback_source = None;- self.state.notify(- NotificationKind::Error,- "No Media Player Found",- "Install mpv, IINA, or VLC to enable video playback.",- );+ let message = if crate::updater::artifact::is_termux_environment() {+ "Install player intent tools: 'pkg install -y termux-tools termux-am' and ensure an Android player (VLC, MX Player, or Just Player) is installed."+ } else {+ "Install mpv, IINA, or VLC to enable video playback."+ };+ self.state+ .notify(NotificationKind::Error, "No Media Player Found", message);}}}@@ -713,11 +715,13 @@ impl App {let player = self.state.available_players.first().cloned();match player {None => {- self.state.notify(- NotificationKind::Error,- "Player Unavailable",- "Install mpv, IINA, or VLC to enable playback.",- );+ let message = if crate::updater::artifact::is_termux_environment() {+ "Install player intent tools: 'pkg install -y termux-tools termux-am' and ensure an Android player (VLC, MX Player, or Just Player) is installed."+ } else {+ "Install mpv, IINA, or VLC to enable playback."+ };+ self.state+ .notify(NotificationKind::Error, "Player Unavailable", message);}Some(kind) => {self.state.notify(@@ -800,22 +804,32 @@ impl App {.unwrap_or_else(|| "unknown".into());log::error!("player crashed (code {code_str}): {error_msg}");- let display_err = if error_msg.is_empty() {- "No error output provided by player.".to_string()+ let is_termux_perm_crash = crate::updater::artifact::is_termux_environment()+ && (code == Some(126)+ || error_msg.contains("Permission denied")+ || error_msg.contains("/system/bin/am")+ || error_msg.contains("termux-open"));++ let (title, message) = if is_termux_perm_crash {+ (+ "Termux Player Setup Required",+ "Install player intent tools: 'pkg install -y termux-tools termux-am' and ensure an Android player (VLC, MX Player, or Just Player) is installed.".to_string(),+ )} else {- error_msg.lines().last().unwrap_or(&error_msg).to_string()+ let display_err = if error_msg.is_empty() {+ "No error output provided by player.".to_string()+ } else {+ error_msg.lines().last().unwrap_or(&error_msg).to_string()+ };+ (+ "Player Error",+ format!("Crash code: {code_str}\n{display_err}"),+ )};- self.state.set_status(- format!("Player crashed (code {code_str}): {display_err}"),- 300,- );+ self.state.set_status(format!("{title}: {message}"), 300);- self.state.notify(- NotificationKind::Error,- "Player Error",- format!("Crash code: {code_str}\n{display_err}"),- );+ self.state.notify(NotificationKind::Error, title, message);}_ => return None,}@@ -998,4 +1012,32 @@ mod tests {});}++ #[tokio::test]+ async fn test_player_crashed_termux_actionable_notification() {+ let mut app = crate::tui::app::App::new();+ unsafe {+ std::env::set_var("TERMUX_VERSION", "0.118.0");+ }+ app.handle_playback(super::Action::PlayerCrashed(+ Some(126),+ "/system/bin/am[11]: /data/data/com.termux/files/usr/bin/cmd: Permission denied"+ .to_string(),+ ))+ .await;+ unsafe {+ std::env::remove_var("TERMUX_VERSION");+ }+ let last_notification = app+ .state+ .notifications+ .back()+ .expect("expected notification");+ assert_eq!(last_notification.title, "Termux Player Setup Required");+ assert!(+ last_notification+ .message+ .contains("pkg install -y termux-tools termux-am")+ );+ }}