Skip to content

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

docs: complete the documentation set

Samir Hossainse61a544cca1c
diff --git a/docs/README.md b/docs/README.md
index 995f1fb..5dd8740 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -9,18 +9,18 @@ anchors that stay accurate as the code evolves.
| Document | What it covers | Status |
|---|---|---|
| [architecture.md](architecture.md) | Crate/module map, event loop, async model, data flow | current |
-| [modules.md](modules.md) | Crate/module tree with responsibilities | pending (lands with the app.rs split) |
-| [providers.md](providers.md) | MovieBox, 4KHDHub, BDIX protocols, signing, resolvers, errors | pending |
-| [players.md](players.md) | Player detection, mpv/VLC/IINA/AndroidIntent, headers, subtitles, window sizing | pending |
-| [cache.md](cache.md) | Cache layout, namespaces, TTLs, atomic writes, purge | pending |
-| [logging.md](logging.md) | File logging, `MOVIEBOX_LOG`, rotation, sanitization, sharing logs | pending |
-| [tv-mode.md](tv-mode.md) | User-owned M3U playlists, manager, search, playback, config | pending |
-| [config.md](config.md) | `config.json` fields and `MOVIEBOX_*` environment variables | pending |
-| [downloads.md](downloads.md) | Download engine: resume, ranges, segments, retry, cancel | pending |
-| [cross-platform.md](cross-platform.md) | OS support, terminal protocols, Termux, focus handling | pending |
-| [debugging.md](debugging.md) | Reproducing issues and what to include in GitHub reports | pending |
-| [contributing.md](contributing.md) | Build, lint gate, commit conventions | pending |
-| [known-issues.md](known-issues.md) | Known limitations and how they are tracked | pending |
+| [modules.md](modules.md) | Crate/module tree with responsibilities | current |
+| [providers.md](providers.md) | MovieBox, 4KHDHub, BDIX protocols, signing, resolvers, errors | current |
+| [players.md](players.md) | Player detection, mpv/VLC/IINA/AndroidIntent, headers, subtitles, window sizing | current |
+| [cache.md](cache.md) | Cache layout, namespaces, TTLs, atomic writes, purge | current |
+| [logging.md](logging.md) | File logging, `MOVIEBOX_LOG`, rotation, sanitization, sharing logs | current |
+| [tv-mode.md](tv-mode.md) | User-owned M3U playlists, manager, search, playback, config | current |
+| [config.md](config.md) | `config.json` fields and `MOVIEBOX_*` environment variables | current |
+| [downloads.md](downloads.md) | Download engine: resume, ranges, segments, retry, cancel | current |
+| [cross-platform.md](cross-platform.md) | OS support, terminal protocols, Termux, focus handling | current |
+| [debugging.md](debugging.md) | Reproducing issues and what to include in GitHub reports | current |
+| [contributing.md](contributing.md) | Build, lint gate, commit conventions | current |
+| [known-issues.md](known-issues.md) | Known limitations and how they are tracked | current |
-> Docs marked "pending" are written incrementally as the corresponding refactor lands, so they
-> always describe the current code rather than a planned state.
+> Keep this index accurate: when a behavior change lands, update the matching doc in
+> the same change and flip its status to current.
diff --git a/docs/cache.md b/docs/cache.md
new file mode 100644
index 0000000..e3f79a3
--- /dev/null
+++ b/docs/cache.md
@@ -0,0 +1,45 @@
+# Cache
+
+Disk caching lives in `cache.rs`; in-memory caches live in `AppState`.
+
+## Disk layout
+
+```
+<cache dir>/moviebox-tui/
+ <provider>/ moviebox, fourkhdhub, bdix_circleftp, bdix_dhakaflix
+ search/<hash>.json
+ details/details_<hash>.json
+ streams/v3_<hash>_<season>_<episode>.json (v3_ prefix only for 4KHD)
+ images/<md5>.img
+ moviebox/
+ homepage/<tab>_<page>.json
+ captions/captions_<hash>.json
+ tv_playlists/<md5>.m3u
+```
+
+The cache directory is `dirs::cache_dir()/moviebox-tui` (macOS
+`~/Library/Caches`, Windows `%LOCALAPPDATA%`, Linux `$XDG_CACHE_HOME`).
+
+## Properties
+
+- **Provider namespacing**: keys include `provider.cache_key()`, so results from
+ different providers never collide. Image caches are namespaced by provider (or
+ `iptv` for channel logos).
+- **TTL**: streams expire after 2h; search/details/captions/images after 24h;
+ homepage after 1h.
+- **Atomic writes**: data is written to a temp file then renamed, so a crash never
+ leaves a corrupt cache entry.
+- **Validation**: search/stream entries are only cached (and only served) if they
+ contain real results, so empty responses are never reused.
+- **Purge**: `clean_old_cache_background` (startup) deletes entries older than 7 days.
+ `ClearCache` (`/clear-cache`) removes the whole cache tree.
+
+## In-memory caches (AppState)
+
+- `image_cache` (10), `search_posters` (30), `search_poster_protocols` (30),
+ `preview_cache` (30): `lru::LruCache` for poster images and terminal image
+ protocols; `stream_pool`: resolved streams per subject.
+
+All disk access in async code is wrapped in `tokio::task::spawn_blocking` so the event
+loop never blocks. Failures are logged (see [logging.md](logging.md)) and treated as
+cache misses.
diff --git a/docs/config.md b/docs/config.md
new file mode 100644
index 0000000..1da6026
--- /dev/null
+++ b/docs/config.md
@@ -0,0 +1,39 @@
+# Configuration
+
+## `config.json`
+
+Written atomically under the config directory (`dirs::config_dir()/moviebox-tui/`;
+macOS `~/Library/Application Support/moviebox-tui`, Linux `~/.config/moviebox-tui`).
+
+| Field | Type | Meaning |
+|---|---|---|
+| `auto_update` | bool | Check for updates on startup (max once/hour). |
+| `last_update_check` | u64 | Epoch seconds of the last update check. |
+| `active_provider` | string | Last provider (`moviebox`, `fourkhdhub`, …). |
+| `active_theme` | string | Theme name. |
+| `bdix_enabled` | bool | Show BDIX providers (Bangladesh-only). |
+| `default_player` | string | Preferred player: `mpv`, `iina`, `vlc`, `android`. |
+
+## Other persisted files
+
+- `tv_config.json` — list of M3U playlist sources (see [tv-mode.md](tv-mode.md)).
+- `history.json` — watch history.
+- `tv_prefs.json`, `watched.json`, `iptv_cache/` — legacy/auxiliary data.
+
+## Environment variables
+
+| Variable | Purpose |
+|---|---|
+| `MOVIEBOX_LOG` | Log level: `off`, `warn`, `info`, `debug`, `trace`. See [logging.md](logging.md). |
+| `MOVIEBOX_PLAYER` | Preferred player (overrides `default_player`). |
+| `MOVIEBOX_MPV_PATH` | Custom mpv executable. |
+| `MOVIEBOX_VLC_PATH` | Custom VLC executable. |
+| `MOVIEBOX_IINA_PATH` | Custom IINA/iina-cli executable. |
+| `MOVIEBOX_FOURKHDHUB_URL` | Override the 4KHDHub base URL. |
+| `MOVIEBOX_THEME` | Force a theme (e.g. `Mocha`, `Latte`). |
+| `GITHUB_TOKEN` | Optional token for the update check (avoids rate limits). |
+
+## CLI
+
+- `moviebox-tui --version` prints the version and exits.
+- No other flags.
diff --git a/docs/contributing.md b/docs/contributing.md
new file mode 100644
index 0000000..6f7614d
--- /dev/null
+++ b/docs/contributing.md
@@ -0,0 +1,56 @@
+# Contributing
+
+## Requirements
+
+- Rust 1.90+ (`rust-version` in Cargo.toml).
+- `cargo` with `fmt` and `clippy` components.
+
+## Build
+
+```bash
+cargo build # debug
+cargo build --release # release (lto, strip)
+```
+
+## Development loop
+
+```bash
+cargo fmt # format
+cargo clippy --all-targets -- -D warnings # lint (must be clean)
+cargo build
+cargo test --lib
+```
+
+The repository's pre-commit hook runs `cargo fmt` and
+`cargo clippy --all-targets -- -D warnings`; a commit is rejected if either fails.
+
+## Running
+
+`moviebox-tui` needs an interactive terminal (raw mode + alternate screen). For logs,
+see [logging.md](logging.md); `MOVIEBOX_LOG=info` is handy during development.
+
+## Structure
+
+The crate is organized into focused modules; `docs/modules.md` and
+`docs/architecture.md` are the map. `tui/app/` holds the application object: `mod.rs`
+is the thin `handle_action` dispatcher, and each `handle_*` method lives in its own
+module (`requests`, `playback`, `download`, `navigation`, `tv`, `system`, `keyboard`).
+
+## Commit conventions
+
+- Conventional Commits: `feat(scope): …`, `fix(scope): …`, `refactor(scope): …`,
+ `docs(scope): …`, `chore(scope): …`.
+- Keep changes focused; one logical change per commit.
+- Refactors must be behavior-neutral (bodies moved verbatim) and pass the gate.
+- When a change surfaces an error, fix it in a follow-up commit rather than amending,
+ so the history documents the find and the fix.
+
+## Documentation
+
+- Keep `docs/` up to date with the code. Update the relevant topic doc in the same
+ change that alters behavior, and keep `docs/README.md`'s status column accurate.
+
+## CI
+
+`.github/workflows/ci.yml` runs fmt, clippy (`-D warnings`), `cargo audit`, and
+`cargo package` on macOS, Linux, and Windows.
diff --git a/docs/cross-platform.md b/docs/cross-platform.md
new file mode 100644
index 0000000..9b79e67
--- /dev/null
+++ b/docs/cross-platform.md
@@ -0,0 +1,32 @@
+# Cross-platform
+
+Supported: macOS, Linux, Windows, and Android (Termux). The codebase uses
+`crossterm` (all platforms), `ratatui`, and a couple of small per-OS branches.
+
+## OS notes
+
+| Platform | Notes |
+|---|---|
+| macOS | IINA preferred player (via bundled `iina-cli`); VLC/mpv `.app` paths detected. `process_group(0)` on spawn. |
+| Windows | mpv/VLC detected via Program Files + `%LOCALAPPDATA%`; players spawned with `CREATE_NO_WINDOW`; path-safe file stems. |
+| Linux | Flatpak mpv/VLC supported (`flatpak run …`); xdg data/cache dirs. |
+| Android (Termux) | `cfg(target_os = "android")`; playback falls back to `termux-open --chooser` (or `am start`), with `LD_LIBRARY_PATH` cleared. |
+
+## Terminal capabilities
+
+The app probes the terminal at startup via `ratatui_image`:
+
+- **Poster rendering**: Sixel / Kitty / iTerm2 / HalfBlocks per terminal support; the
+ image protocol is re-queried on resize and scroll, and focus changes use a soft
+ refresh so launching a player does not flash the screen.
+- **Terminal classification**: `TERM=dumb`/`linux` fall back to a basic UI.
+- Focus events (focus loss/gain) are used to re-render in place without clearing.
+
+## Things to verify per release
+
+- Player launch on each OS (mpv/VLC/IINA/Android intent) — window sizing, subtitles,
+ headers.
+- Poster rendering across Sixel (Windows Terminal, foot), Kitty, and half-block
+ terminals.
+- TV mode with a sample M3U playlist (URL and local file).
+- Termux: on-device check that Play opens the Android chooser and the stream plays.
diff --git a/docs/debugging.md b/docs/debugging.md
new file mode 100644
index 0000000..9b06599
--- /dev/null
+++ b/docs/debugging.md
@@ -0,0 +1,36 @@
+# Debugging
+
+The app writes a sanitized file log so full errors are available even though the TUI
+only shows a short status line. See [logging.md](logging.md) for location and settings.
+
+## Reproducing an issue
+
+1. Run with debug logging:
+ `MOVIEBOX_LOG=debug moviebox-tui`
+2. Reproduce the problem (search, open details, play, download, TV).
+3. Grab the current log file (path printed at startup, and in the log's session header):
+ - macOS: `~/Library/Application Support/moviebox-tui/logs/moviebox-tui_rCURRENT.log`
+ - Windows: `%APPDATA%\moviebox-tui\logs\...`
+ - Linux: `$XDG_DATA_HOME/moviebox-tui/logs/...`
+4. Include it when opening an issue.
+
+## What to include in a GitHub issue
+
+- The version (`moviebox-tui --version`).
+- Operating system and terminal (e.g. macOS + iTerm2, Windows + Windows Terminal,
+ Termux).
+- The player used, if the issue is playback.
+- The log file (sanitized — safe to share; URLs and paths are redacted).
+
+## Reading the log
+
+Each line is `[timestamp] LEVEL [module:line] message`. Focus on `ERROR` lines first;
+`WARN` lines explain recoverable fallbacks (e.g. a 4KHD mirror rejected, subtitles
+unavailable). With `MOVIEBOX_LOG=debug` you also get request context.
+
+## Known quick checks
+
+- "Player unavailable" → no mpv/VLC/IINA detected; set `MOVIEBOX_PLAYER` or install one.
+- "no playable mirrors" on 4KHD → all mirrors were rejected by the preflight; the log
+ lists each mirror and the reason.
+- TV mode "no channels" → playlists failed to load; the log names the failing source.
diff --git a/docs/downloads.md b/docs/downloads.md
new file mode 100644
index 0000000..10e3550
--- /dev/null
+++ b/docs/downloads.md
@@ -0,0 +1,35 @@
+# Downloads
+
+The download engine in `download.rs` streams a video URL to disk with resume, ranges,
+and optional segmentation. Orchestration lives in `app/download.rs`.
+
+## How it works
+
+- Single-episode downloads write to `<dest>.part` plus a `<dest>.part.json` metadata
+ sidecar (etag, last-modified, total size, segment count).
+- **Resume**: on a retry, the engine checks what is already in the `.part` file and
+ continues from there using `Range` requests.
+- **Segmentation**: files above a size threshold can be downloaded in parallel
+ segments (up to a capped count), then stitched.
+- **Retries**: a failed attempt is retried a limited number of times; 30s idle
+ timeouts apply to streaming reads.
+- **Cancel**: an `AtomicBool` cancel flag pauses/resumes cleanly, preserving the
+ partial file for a later resume.
+
+## File names
+
+`safe_file_stem` sanitizes titles for all platforms: control/whitespace/illegal
+characters are replaced, Windows reserved names (`CON`, `COM1`-`COM9`, …) are avoided,
+and length is capped. Files go to the user's download directory (on Android,
+`storage/downloads` when present).
+
+## Seasons
+
+A season download enqueues every episode (`download_queue`) and processes them one at a
+time, each resolving its stream and subtitle. Progress is reported through
+`Action::UpdateDownload` and the status bar; failures pause and preserve partial data.
+
+## Outcomes
+
+`DownloadCompleted` / `DownloadPaused` / `DownloadFailed` drive the UI status and
+notifications. `ClearCache` and stale-file cleanup do not touch in-progress downloads.
diff --git a/docs/known-issues.md b/docs/known-issues.md
new file mode 100644
index 0000000..9df77dd
--- /dev/null
+++ b/docs/known-issues.md
@@ -0,0 +1,31 @@
+# Known issues and limitations
+
+Tracked here so future work and issue reports reference the same facts.
+
+## Latent / by-design
+
+- **`supports_headers` gate is currently never triggered** — every `PlaybackSource`
+ today either carries no headers or only `referer`/`user-agent`. If a provider ever
+ adds other headers, the VLC path would reject them (by design) and the gate message
+ would matter. Keep `player.rs::supports_headers` in sync with `vlc_command`'s filter.
+- **BDIX clients use nested `if let Ok` pyramids** in search handling; they work and
+ are logged, but are harder to read. Flattening is deferred (behavior-neutral refactor
+ with moderate churn).
+- **MovieBox request signing** hardcodes an API secret and spoofs a device identity in
+ `crypto.rs`. This is inherent to the scraper; treat the module as one unit.
+- **Android intent playback** cannot attach subtitles (a `VIEW` intent has no subtitle
+ mechanism); subtitles are ignored for the Android player.
+
+## Environment-dependent
+
+- **4KHDHub mirrors rotate and can be region/rate limited.** A file whose only mirrors
+ are "probe trap" workers (which refuse real streaming ranges) reports
+ `no playable mirrors` with the reason in the log. Not fixable in-app.
+- **Termux playback needs the device confirmed** on each release: `termux-open` /
+ `am` availability and the Android chooser behavior.
+
+## Test coverage
+
+- There are no unit tests currently (per project decision); correctness is enforced by
+ the lint gate, type checking, and manual verification. CI runs `cargo audit` and
+ `cargo package`.
diff --git a/docs/logging.md b/docs/logging.md
new file mode 100644
index 0000000..f1e2f05
--- /dev/null
+++ b/docs/logging.md
@@ -0,0 +1,44 @@
+# Logging
+
+The app writes a file log so issues invisible in the TUI (full error text, URLs,
+statuses, content-types) are recorded and can be shared.
+
+## Location
+
+- macOS: `~/Library/Application Support/moviebox-tui/logs/`
+- Windows: `%APPDATA%\moviebox-tui\logs\`
+- Linux: `$XDG_DATA_HOME/moviebox-tui/logs/` (else `~/.local/share/moviebox-tui/logs/`)
+
+The active file is `moviebox-tui_rCURRENT.log`; rotated files are
+`moviebox-tui_r00000.log`, `…`.
+
+## Behavior
+
+- **Level** is controlled by `MOVIEBOX_LOG` (`off|warn|info|debug|trace`). Default is
+ `warn` in release builds, `info` in debug builds.
+- **Rotation**: rotates at 5MB and keeps 3 files, so it stays small automatically.
+- **File-only**: nothing is written to stdout/stderr (would corrupt the TUI).
+- **Session header**: version, OS, and the log path are written on startup.
+- **Panics**: the panic hook logs the payload to the file, then restores the terminal.
+- `--version` never creates a log file.
+
+## What is logged
+
+- `error`: hard failures (all-hosts exhausted, resolve failures, player spawn/crash,
+ download failures, panics) and every `Error:` status the UI shows.
+- `warn`: recoverable issues (mirror rejected, subtitle unavailable, cache write
+ failed, GitHub rate limit).
+- `info`: session start, playable mirror found, playback launch.
+- `debug`: full request context (enable with `MOVIEBOX_LOG=debug`).
+
+## Privacy / sharing
+
+Logs are sanitized so they can be pasted into a GitHub issue:
+
+- URLs are reduced to `scheme://host` — file tokens, filenames, and query params are
+ removed.
+- Absolute paths are rewritten to `~` so your username does not appear.
+- Headers, `Authorization`/`GITHUB_TOKEN`, search queries, and watch history are never
+ logged.
+
+Reproduce the problem, then attach the current log file. See [debugging.md](debugging.md).
diff --git a/docs/modules.md b/docs/modules.md
new file mode 100644
index 0000000..affa00a
--- /dev/null
+++ b/docs/modules.md
@@ -0,0 +1,85 @@
+# Modules
+
+The crate (`moviebox_tui`) is split into top-level modules and, inside `tui`, an `app`
+directory that holds the application object. Below is the full tree with each module's
+responsibility.
+
+```
+src/
+ main.rs Entry point. Logging init, panic hook, raw mode, alternate
+ screen, TerminalGuard, App::new + App::run.
+ lib.rs Crate root: declares pub mod cache/download/history/logging/
+ providers/tui.
+
+ cache.rs Disk cache: provider-namespaced directories, TTL expiry,
+ atomic temp-file writes, payload validation, background purge.
+
+ download.rs Download engine (pure, async): resume via .part files,
+ HTTP ranges, optional multi-segment download, retries, cancel
+ via an AtomicBool, Windows-safe file stems.
+
+ history.rs Watch history: read/write history.json, dedupe, cap 100.
+
+ logging.rs File logging: flexi_logger, rotation (5MB, keep 3),
+ MOVIEBOX_LOG level, URL/path sanitization for sharing.
+
+ providers/
+ mod.rs Module declarations.
+ models.rs Shared types: ProviderKind, CatalogItem, MediaDetails,
+ Release, PlaybackSource, RequestContext, SourceMirror.
+ moviebox/ Primary provider.
+ client.rs Async reqwest client with signed requests (anti-bot).
+ crypto.rs Request signing: HMAC-MD5 signature, client token,
+ spoofed device identity (by design of the scraper).
+ title.rs clean_moviebox_title: strip quality/site suffix noise.
+ fourkhdhub/ Secondary provider.
+ client.rs Search/details/stream resolution + preflight validation.
+ hubcloud.rs Mirror resolver: fetch drive pages, extract playable links.
+ parser.rs HTML parsing into typed CatalogItem/MediaDetails/Release,
+ plus moviebox-JSON adapters.
+ bdix/
+ circleftp/ BDIX CircleFTP provider (client + parser).
+ dhakaflix/ BDIX DhakaFlix provider (client + parser).
+ m3u.rs M3U playlist parser (http(s) URL or local file).
+
+ tui/
+ action.rs The Action enum: every UI event/message (input, network
+ results, downloads, playback, tv, system).
+ state.rs AppState: all UI state, LRU image/preview caches, and the
+ PlayerKind enum + label()/parse(), tv manager row model.
+ event.rs EventHandler: crossterm event stream + tick interval,
+ forwards to the action channel.
+ player.rs Player detection (OnceLock) and command construction for
+ mpv / VLC / IINA / Android intent, subtitle args, headers,
+ terminal-sized window.
+ overlay.rs Popups: notifications, pickers, confirmation, modal centering.
+ screens/
+ home.rs Home/startup + search list rendering (streaming and TV).
+ details.rs Details screen rendering.
+ help.rs Keybinding help (mode-aware).
+ startup.rs Startup splash.
+ terminal.rs Terminal capability probes (basic UI, image querying).
+ theme.rs Color themes + terminal color detection.
+ text.rs Grapheme-safe width/truncation helpers.
+ updater.rs GitHub release update check.
+
+ tui/app/ The application object (App) and all behavior.
+ mod.rs App struct, App::new, small helpers, handle_action
+ dispatcher (thin routing table over action groups).
+ run.rs App::run (event loop) and App::draw (rendering).
+ network.rs fetch_poster_bytes, decode_poster, provider_search,
+ provider_details.
+ requests.rs handle_requests: search/homepage/suggest/details/preview/
+ episode-streams/poster actions.
+ playback.rs handle_playback: play/subtitle/picker/launch/crash actions
+ + launch_player.
+ download.rs handle_download: download orchestration + start_resilient_download.
+ navigation.rs handle_navigation + provider/nav helpers.
+ keyboard.rs handle_key: raw key-event handling.
+ system.rs handle_system: tick/quit/focus/resize/help/refresh/cache/
+ theme/status/updates.
+ tv.rs handle_tv: playlist manager + TV actions.
+```
+
+See [architecture.md](architecture.md) for the event loop, async model and data flow,
+and the per-topic docs for details.
diff --git a/docs/players.md b/docs/players.md
new file mode 100644
index 0000000..68f795e
--- /dev/null
+++ b/docs/players.md
@@ -0,0 +1,52 @@
+# Players
+
+Playback is handed to an external player. `tui/player.rs` detects available players and
+builds the exact command; `tui/app/playback.rs` spawns it.
+
+## Detection
+
+`player::detect()` returns players in priority order:
+
+- macOS: IINA (if present), then mpv, then VLC.
+- Linux/Windows: mpv, then VLC.
+- Android/Termux: the Android intent fallback is always available last.
+
+Resolution runs once at startup and is cached (`OnceLock`). 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. Player picker (`Open with`) lists every
+detected player.
+
+## Command construction
+
+| Player | Invocation | Notes |
+|---|---|---|
+| mpv | `mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no [--referrer=..] [--user-agent=..] [--sub-file=..] <url>` | Window sized to the terminal. Flatpak mpv is launched via `flatpak run`. |
+| VLC | `vlc --width=W --height=H --play-and-exit [--http-referrer=..] [--http-user-agent=..] [--sub-file=..] <url>` | |
+| IINA | `iina-cli --keep-running --no-stdin --mpv-autofit=.. --mpv-<option> .. <url>` | Uses the bundled `iina-cli`; falls back to `open -a IINA <url>` only if the CLI is absent. |
+| Android | `termux-open --chooser --content-type video/* <url>` (or `am start` fallback) | Opens an app chooser on the device. |
+
+Window size is derived from the live terminal size times the real font cell size
+(reported by the image picker), clamped to a sane range.
+
+## Headers
+
+Playback sources (e.g. 4KHD) may carry `Referer`/`User-Agent` headers. mpv/IINA send
+them via their dedicated `--referrer`/`--user-agent` options (comma-safe); VLC uses
+`--http-referrer`/`--http-user-agent`. The `supports_headers` gate in `LaunchPlayback`
+warns when a player cannot satisfy a source's headers.
+
+## Subtitles
+
+- mpv receives the remote subtitle URL directly (`--sub-file=<url>`); mpv fetches it
+ with the stream headers applied.
+- VLC and IINA download the subtitle to a temp file first, preserving the URL's
+ extension (srt/vtt/ass/…), and pass the local path. The download applies the source
+ headers. On failure a status is shown and playback continues without subtitles.
+- Temp files are cleaned up after the player exits and purged at startup if stale.
+
+## Spawning
+
+`launch_player` spawns the player with null stdin/stdout, piped stderr, and its own
+process group (Unix) or no-console flag (Windows). A blocking task reads stderr and
+reports a crash if the process exits non-zero within a few seconds with output.
+Watch history is marked on launch.
diff --git a/docs/providers.md b/docs/providers.md
new file mode 100644
index 0000000..5175b52
--- /dev/null
+++ b/docs/providers.md
@@ -0,0 +1,63 @@
+# Providers
+
+MovieBox-Tui aggregates several movie/stream providers plus user M3U playlists. Each
+provider is an independent async client exposing a similar shape, normalized into the
+shared typed models in `providers/models.rs` and the moviebox JSON schema used by the UI.
+
+## Provider kinds
+
+| Kind | Module | Notes |
+|---|---|---|
+| `MovieBox` | `providers/moviebox` | Primary. Requires request signing (crypto). |
+| `FourKHdHub` | `providers/fourkhdhub` | 4K releases; hubcloud mirror resolver. |
+| `BdixCircleFtp` | `providers/bdix/circleftp` | BDIX FTP directory scrapes. |
+| `BdixDhakaFlix` | `providers/bdix/dhakaflix` | BDIX indexer. |
+
+BDIX sources are only reachable from supported Bangladeshi ISPs and are hidden by
+default (`bdix_enabled` in config; `/enable-bdix`).
+
+## Shared flow
+
+Search, details, and episode-streams are dispatched per provider in
+`app/network.rs` (`provider_search`, `provider_details`) and `app/requests.rs`.
+Each provider returns typed models; non-moviebox results are converted to the moviebox
+JSON schema by `fourkhdhub/parser.rs` adapters before reaching the UI.
+
+Playback resolves to a `PlaybackSource { provider, url, headers, subtitle, source_label }`,
+which `app/playback.rs::launch_player` feeds to the external player.
+
+## MovieBox
+
+- Base host pool + per-request HMAC-MD5 signature, client token, and a spoofed Android
+ device identity (`crypto.rs`) to satisfy the anti-bot gateway.
+- Hosts are retried; a shared runtime token is re-initialized when all hosts fail.
+- Title normalization lives in `moviebox/title.rs` (`clean_moviebox_title`).
+
+## 4KHDHub
+
+- `client.rs::resolve_release` walks the release's mirrors; each candidate goes through
+ `preflight` which validates the URL and issues an **open-range** probe
+ (`Range: bytes=0-`) so probe-only trap mirrors (which answer a tiny bounded range but
+ refuse real streaming) are rejected. The 4KHD referer and a browser user-agent are
+ attached so referer-gated CDNs stream in the player too.
+- `hubcloud.rs` resolves hubcloud/hubdrive pages into candidate playable links and
+ picks the best mirror by score.
+- Errors are surfaced as `FourKHdHubError`; mirror rejections and the final failure
+ reason are logged with the mirror label and a sanitized URL.
+
+## BDIX
+
+- `circleftp` and `dhakaflix` scrape FTP-style indexes; both are used behind the
+ Bangladesh-only gate.
+
+## M3U playlists (TV mode)
+
+`providers/m3u.rs` parses an M3U playlist from an `https://` URL or a local file path.
+Each channel yields `{ id, name, logo, group, stream_url }`; TV mode groups channels by
+`group-title` and dedupes by `stream_url`. See [tv-mode.md](tv-mode.md).
+
+## Error handling
+
+Each provider defines a `thiserror` enum (`ScraperError`, `FourKHdHubError`,
+`CircleFtpError`, `DhakaFlixError`). Errors bubble to `app/requests.rs` handlers, which
+surface them in the UI status bar and log the full detail (see [logging.md](logging.md)).
diff --git a/docs/tv-mode.md b/docs/tv-mode.md
new file mode 100644
index 0000000..be6f183
--- /dev/null
+++ b/docs/tv-mode.md
@@ -0,0 +1,41 @@
+# TV Mode
+
+TV mode streams live channels from **your own** M3U playlists — there is no bundled
+third-party feed. You add playlists by URL or local file path, and the app parses,
+groups, dedupes and lets you search and play them.
+
+## Entering TV mode
+
+- `Ctrl+T` toggles Streaming / TV mode.
+- On first entry with no playlists, the playlist manager opens automatically.
+- While in TV mode, type to filter channels by name or group, `Enter` to play,
+ `/list` for all channels, `/config` to manage playlists, `[r]` to reload.
+
+## Adding playlists
+
+1. `/config` opens the playlist manager, split into **URL playlists** and
+ **File playlists**.
+2. Select `[ Add URL ]` or `[ Add file ]`, type the source, `Enter` to add.
+ - URL example: `https://example.com/playlist.m3u`
+ - File example: `~/playlists/mine.m3u`
+3. Sources persist in `tv_config.json` (under the config dir) and are re-fetched on
+ every TV-mode entry.
+4. Highlight a source and press `d` (or `Enter`) to remove it; the list reloads.
+
+## Parsing and search
+
+`providers/m3u.rs` parses each source (http(s) or local file), extracting channel id,
+name, logo, `group-title`, and stream URL. Channels are **deduped by stream URL**
+across all playlists. The search box filters by name or group; the status bar reports
+how many channels were imported and which playlists failed.
+
+## Playback
+
+`Enter` on a channel launches the default player with the channel URL (via the same
+`launch_player` path as movies). Channel logos are cached under the `iptv` image
+namespace.
+
+## Commands in TV mode
+
+Only `/config` and `/list` are active. Other slash commands are streaming-mode only;
+the app tells you to switch modes instead of silently doing nothing.