YouTube 2.0.0: native client without ads
All checks were successful
release / release (push) Successful in 10m13s

Replaces the web app (youtube.com/tv in Chromium) with a native Rust +
Slint client on sf-ui, built on Netflex TV's page engine.

- InnerTube: web client for public pages, the TV client with the
  account's OAuth token for personal ones, visionOS (direct URLs) for
  streams, the TV client with yt-dlp's ejs solver (QuickJS) as fallback.
- One version, no ads: ad breaks are never requested, ad renderers are
  skipped in feeds. SponsorBlock skips sponsored parts.
- Sign-in with a QR code / youtube.com/activate (OAuth device flow).
- Signed out: subscriptions and history on the TV; a home filled with
  this week's popular Hungarian videos when YouTube's is empty.
- Playback: one-quality DASH manifest for GStreamer, H.264 up to 1080p
  or AV1 up to 4K, captions, quality switching, up next, resume.
- Release builds for x86-64 and the Raspberry Pi (aarch64).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tamas Csikel
2026-11-02 16:27:41 +01:00
parent 645fd1c6fe
commit 9875d435e1
40 changed files with 15776 additions and 37 deletions

View File

@@ -1,8 +1,11 @@
# On a tag (v1.2.3): build the two store assets and publish them as a release. # On a tag (v1.2.3): build the app and publish a release with the store
# assets: app.toml, the x86-64 package and the aarch64 one (Raspberry Pi,
# docs/store.md in Fennec OS). sf-ui and sf-pack come from the Fennec SDK (public).
# #
# Runner hygiene (shared host, little disk): runs in the runner image that is # Runner hygiene (shared host, little disk): runs in the runner image that is
# already on the host (no image pull), uses no `uses:` actions (no action # already on the host (no image pull), uses no `uses:` actions (no action
# cache), and deletes everything it made at the end. # cache), and deletes everything it made at the end. The image is Ubuntu
# 24.04: its glibc is older than the TV's (Debian trixie), so the binary runs.
name: release name: release
on: on:
push: push:
@@ -17,8 +20,9 @@ jobs:
CARGO_HOME: /tmp/fennec-youtube/cargo CARGO_HOME: /tmp/fennec-youtube/cargo
RUSTUP_HOME: /tmp/fennec-youtube/rustup RUSTUP_HOME: /tmp/fennec-youtube/rustup
CARGO_TARGET_DIR: /tmp/fennec-youtube/target CARGO_TARGET_DIR: /tmp/fennec-youtube/target
CARGO_INCREMENTAL: "0"
SDK_GIT: https://gitea.bluefox.support/fennec/sdk SDK_GIT: https://gitea.bluefox.support/fennec/sdk
SDK_TAG: v0.1.0 SDK_TAG: v0.1.2
steps: steps:
- name: Checkout - name: Checkout
run: | run: |
@@ -27,21 +31,45 @@ jobs:
"${GITHUB_SERVER_URL%%://*}://oauth2:${{ secrets.GITHUB_TOKEN }}@${GITHUB_SERVER_URL#*://}/${GITHUB_REPOSITORY}.git" "$W/src" "${GITHUB_SERVER_URL%%://*}://oauth2:${{ secrets.GITHUB_TOKEN }}@${GITHUB_SERVER_URL#*://}/${GITHUB_REPOSITORY}.git" "$W/src"
v=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$W/src/app.toml" | head -1) v=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$W/src/app.toml" | head -1)
[ "v$v" = "$GITHUB_REF_NAME" ] || { echo "tag $GITHUB_REF_NAME, but app.toml says $v" >&2; exit 1; } [ "v$v" = "$GITHUB_REF_NAME" ] || { echo "tag $GITHUB_REF_NAME, but app.toml says $v" >&2; exit 1; }
- name: sf-pack - name: Toolchain
run: | run: |
curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path export DEBIAN_FRONTEND=noninteractive
# arm64 libraries for the Raspberry Pi build (package.sh --arm):
# Ubuntu serves them from ports.ubuntu.com, the main mirror is amd64 only.
. /etc/os-release
dpkg --add-architecture arm64
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
sed -i '/^Architectures:/d; /^Types:/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
fi
[ -f /etc/apt/sources.list ] && sed -i 's/^deb \(http\)/deb [arch=amd64] \1/' /etc/apt/sources.list
printf 'Types: deb\nURIs: http://ports.ubuntu.com/ubuntu-ports/\nSuites: %s %s-updates %s-security\nComponents: main universe\nArchitectures: arm64\nSigned-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n' \
"$VERSION_CODENAME" "$VERSION_CODENAME" "$VERSION_CODENAME" >/etc/apt/sources.list.d/arm64-ports.sources
apt-get update -qq
# Multiarch dev packages for both architectures; for arm64 only the
# GStreamer runtime libraries: its dev packages can't be installed for
# two architectures at once (package.sh --arm links the libraries).
libs="libfontconfig1-dev libfreetype-dev libxkbcommon-dev libglib2.0-dev"
apt-get install -y -qq --no-install-recommends build-essential pkg-config \
gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross \
$libs $(for l in $libs; do printf '%s:arm64 ' "$l"; done) \
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
libgstreamer1.0-0:arm64 libgstreamer-plugins-base1.0-0:arm64
rm -rf /var/lib/apt/lists/*
curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path --target aarch64-unknown-linux-gnu
"$CARGO_HOME/bin/cargo" install -q --locked --git "$SDK_GIT" --tag "$SDK_TAG" sf-pack "$CARGO_HOME/bin/cargo" install -q --locked --git "$SDK_GIT" --tag "$SDK_TAG" sf-pack
- name: Build - name: Build
run: | run: |
export PATH="$CARGO_HOME/bin:$PATH" export PATH="$CARGO_HOME/bin:$PATH"
"$W/src/package.sh" "$W/src/package.sh"
"$W/src/package.sh" --arm
- name: Release - name: Release
env: env:
TOKEN: ${{ secrets.GITHUB_TOKEN }} TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: | run: |
api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/releases" api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/releases"
id=$(curl -fsS -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \ id=$(curl -fsS -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d "{\"tag_name\":\"$GITHUB_REF_NAME\",\"name\":\"$GITHUB_REF_NAME\"}" "$api" | grep -o "\"id\":[0-9]*" | head -1 | cut -d: -f2) -d "{\"tag_name\":\"$GITHUB_REF_NAME\",\"name\":\"$GITHUB_REF_NAME\"}" "$api" \
| grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
for f in "$W"/src/dist/*; do for f in "$W"/src/dist/*; do
curl -fsS -H "Authorization: token $TOKEN" -F "attachment=@$f" "$api/$id/assets?name=$(basename "$f")" >/dev/null curl -fsS -H "Authorization: token $TOKEN" -F "attachment=@$f" "$api/$id/assets?name=$(basename "$f")" >/dev/null
done done

2
.gitignore vendored
View File

@@ -1,2 +1,4 @@
/target
/pkg /pkg
/dist /dist
/dist-arm

50
AGENTS.md Normal file
View File

@@ -0,0 +1,50 @@
# Notes for AI agents working on YouTube for Fennec OS
Read first (Fennec SDK, https://gitea.bluefox.support/fennec/sdk):
- `docs/store-app-guide.md`: what a Fennec OS store app must be (manifest, sandbox, remote, packaging, release).
- `docs/sf-ui.md`: the UI kit. Liquid Glass model, components, focus, dev tools, pitfalls.
## Layout
```
app.toml store manifest (id support.bluefox.youtube; permissions network, gpu, audio)
src/main.rs window, glass layer (lists every exported [GlassRect]), images, controller
src/app.rs Controller: screen stack, keys, QR sign-in overlay, toast, backdrop
src/page.rs the line-based page engine (from Netflex TV): lines and chips -> layout, focus, scroll, lazy images
src/screens/mod.rs sections, cards (v:/c:/p:/m: ids), Load<T>, Paged (feeds with continuations), opening a card
src/screens/*.rs home, subs, library, search, settings, channel, playlist
src/player.rs video id -> yt::stream -> MPD -> sf_ui::video::Player; captions, quality, SponsorBlock, up next
src/yt/mod.rs InnerTube client: client profiles, browse/search/next/player, account
src/yt/parse.rs the tree walker: any answer -> shelves of videos/channels/playlists (skips ads)
src/yt/auth.rs OAuth device flow (youtube.com/activate), refresh, revoke
src/yt/stream.rs player answer -> formats -> one-quality DASH manifest; TV client signatures
src/yt/jsc.rs yt-dlp's ejs solver in QuickJS (n / sig challenges), player script cache
src/yt/extras.rs SponsorBlock, channel RSS, captions (json3), mark watched
src/config.rs settings.toml, account.toml, library.json (history, local subscriptions)
ejs/ yt-dlp ejs 0.8.0 solver scripts (Unlicense), embedded with include_str!
ui/app.slint root: screens, one FocusScope -> Rust `key`, glass exports
ui/{page,player,link,overlays,types}.slint
```
## Rules of this codebase
- **Rust owns state and focus.** Slint only draws. Every key goes to `Controller::key`, except while the search keyboard has the focus.
- **Short borrows:** never hold `state.borrow_mut()` while calling `images.load*` or anything that may call back.
- **Glass:** new glass elements need their `glass` listed in a root `out property <[GlassRect]>`, and that array added in `main.rs`.
- **A new page** is a `Screen`: `spec` returns lines, `activate` gets (line id, card/chip id). Feeds use `Paged` (continuations).
- **YouTube changes often.** Don't hard-code one layout: add renderers to `parse::walk`, keep tests with small JSON samples. Client versions follow yt-dlp's `_base.py`; the stream client order follows its `_DEFAULT_CLIENTS`.
- **One quality per manifest:** GStreamer's adaptive DASH starts at 144p; `Playable::uri` writes only the chosen height.
- **No ads:** never request ad endpoints, keep ad renderers in `parse::SKIP`.
- **Texts are Hungarian** (the client asks YouTube with hl=hu, gl=HU, so YouTube's own texts are Hungarian too).
## Check your change
```sh
cargo test
cargo test live -- --ignored --nocapture # real YouTube: search, stream formats, channel, solver
HOME=/tmp/ythome SF_UI_SIZE=1920x1080 SF_UI_KEYS="wait wait wait wait down enter" SF_UI_SNAPSHOT=/tmp/shot.png cargo run
```
- **Playback** needs Linux (GStreamer). WSL with WSLg works (software decoding, Material look).
- A written manifest can be tried alone: `gst-launch-1.0 playbin uri=file:///tmp/youtube-<id>.mpd`.
- Too many requests in a row get HTTP 429 from YouTube for a while.

7199
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

42
Cargo.toml Normal file
View File

@@ -0,0 +1,42 @@
[package]
name = "youtube-tv"
description = "YouTube for Fennec OS: native TV client with Liquid Glass, no ads, QR sign-in"
version = "2.0.0"
edition = "2024"
# sf-ui (and Slint) are GPL-3.0 on a TV box.
license = "GPL-3.0-only"
publish = false
[dependencies]
# The Fennec OS UI kit (Fennec SDK): Liquid Glass, TV components, images.
sf-ui = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.2" }
slint = "1.18"
anyhow = "1"
log = "0.4"
env_logger = "0.11"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
toml = "0.9"
ureq = { version = "3", features = ["json"] }
# Runs yt-dlp's challenge solver (ejs/) on YouTube's player script.
rquickjs = "0.14"
qrcode = { version = "0.14", default-features = false }
sha2 = "0.10"
# Video playback (GStreamer) only on Linux, the TV.
[target.'cfg(target_os = "linux")'.dependencies]
sf-ui = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.2", features = ["video"] }
[build-dependencies]
slint-build = "1.18"
[profile.release]
lto = "thin"
strip = true
# Keep debug builds snappy for UI iteration.
[profile.dev.package."*"]
opt-level = 2
# Its own workspace (not part of any checkout around it).
[workspace]

View File

@@ -1,16 +1,58 @@
# YouTube for Fennec OS # YouTube for Fennec OS
A YouTube TV-s felülete (`youtube.com/tv`) Fennec OS store appként. Telefonról a YouTube app cast gombjával is indítható (DIAL). Natív YouTube kliens Fennec OS-re (store app, `support.bluefox.youtube`), **reklámok nélkül**. A 2.0 előtti verziók a `youtube.com/tv` webes felületét nyitották meg; a 2.0 ezt váltja le.
- **Típus:** web app. A csomagban csak az `app.toml` és az ikon van; a TV a beépített Chromiumban nyitja meg. - **Felület:** Rust + Slint az sf-ui Liquid Glass-ával. Az oldalmotor és a vezérlő a Netflex TV-ből jön.
- **Engedélyek:** a web appok alapengedélyei (hálózat, grafika, hang), és `dial`: a telefon castolhat ide. - **Képernyők:** Kezdőlap (Folytatás, a YouTube ajánlásai), Feliratkozások, Könyvtár (ezen a TV-n nézett videók; bejelentkezve Később megnézendő, Kedvelt videók, YouTube-előzmények, lejátszási listák), Keresés képernyő-billentyűzettel, csatorna- és lejátszásilista-oldal, Beállítások.
- **Telepítés a TV-n:** a Fennec katalógusból jön (`fennec/store`). Kézzel: Store → Források → `https://gitea.bluefox.support/fennec/youtube`. - **Bejelentkezés:** QR-kóddal, mint a hivatalos TV-appban: a telefonon a youtube.com/activate oldalon kell megerősíteni. A TV csak a refresh tokent tárolja (`$HOME/.config/youtube/account.toml`).
- **Bejelentkezés nélkül:** feliratkozni ezen a TV-n lehet (a csatornák RSS-éből jönnek a friss videók). Ha a YouTube üres kezdőlapot ad, a TV maga tölti meg: a feliratkozások friss videói, „Mert megnézted…”, és a hét népszerű videói néhány témában.
- **Lejátszás:** GStreamer, hardveres dekódolással. A videó és a hang külön jön a YouTube-tól; az app egy DASH-leírót (MPD) ír belőlük, azt játssza a GStreamer. H.264 1080p-ig (a Raspberry Pi is hardveresen dekódolja), vagy AV1 4K-ig. Folytatás onnan, ahol abbahagytad, felirat, minőségváltás lejátszás közben, „Következő” visszaszámlálással (a lista következő videója vagy a YouTube ajánlása), SponsorBlock.
- **Reklám:** a hirdetéseket az app nem kéri le és nem játssza le, a hirdetéskártyákat a feedekből kiszűri.
## Hogyan beszél a YouTube-bal
A YouTube saját belső API-ját (InnerTube) használja, ahogy a yt-dlp is (2026-os állapot):
| Mire | Kliens |
|---|---|
| Nyilvános oldalak (keresés, csatornák, listák, kapcsolódó videók) | `WEB`, kijelentkezve |
| Személyes oldalak (kezdőlap, feliratkozások, előzmények, saját listák) | `TVHTML5` a fiók OAuth tokenjével |
| Stream | `VISIONOS` (közvetlen URL-ek, JS nélkül), tartaléknak `TVHTML5` (Tizen) a JS-megoldóval |
A TV-kliens stream-URL-jeinek aláírását és `n` paraméterét a yt-dlp megoldója számolja ki (`ejs/`, [yt-dlp/ejs](https://github.com/yt-dlp/ejs) 0.8.0, Unlicense), beágyazott QuickJS-ben. A lejátszó-szkript előfeldolgozott változata a `$HOME/.cache/youtube`-ba kerül, így csak az első videó lassú.
**Ha a YouTube változtat** (és ez rendszeresen megtörténik): először a yt-dlp aktuális `yt_dlp/extractor/youtube/_base.py` (kliensverziók) és `_video.py` (`_DEFAULT_CLIENTS`) fájljait érdemes összevetni a `src/yt/mod.rs` profiljaival, a megoldónál pedig frissíteni az `ejs/` két fájlját az ejs legújabb release-éből.
**Nem tudja:** telefonról castolni (a YouTube lounge-protokollja nincs megírva; a webes app ezt a DIAL-lal tudta), és a gépi feliratfordítást (a YouTube 2026 óta PO tokent kér hozzá).
## Fejlesztés
Az sf-ui a [Fennec SDK](https://gitea.bluefox.support/fennec/sdk)-ból jön, git-függőségként (tag). Ha az sf-ui-t is fejleszted mellette, tedd a `.cargo/config.toml` fájlba (ne commitold):
```toml
[patch."https://gitea.bluefox.support/fennec/sdk"]
sf-ui = { path = "../sdk/sf-ui" }
```
```sh
YOUTUBE_WINDOWED=1 cargo run
cargo test # parser, manifest, feliratok, oldalmotor
cargo test live -- --ignored --nocapture # élőben a YouTube ellen: keresés, stream, megoldó
```
- **Windowson:** a felület fejleszthető, de videó nincs (a GStreamer csak Linuxon van bekötve).
- **Linuxon** (Debian trixie / WSL) kell még: `libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev gstreamer1.0-plugins-good gstreamer1.0-plugins-bad gstreamer1.0-libav gstreamer1.0-pipewire`. A DASH-hoz a `dashdemux2` kell (plugins-good).
- **Pillanatkép ember nélkül:** `SF_UI_SIZE=1920x1080 SF_UI_KEYS="wait wait down enter" SF_UI_SNAPSHOT=out.png cargo run` (az SDK `docs/sf-ui.md` 11. fejezete).
## Kiadás ## Kiadás
1. Emeld a `version`-t az `app.toml`-ban, és commitold.
2. Tegyél rá egy `v<verzió>` taget, és pushold.
3. A `.gitea/workflows/release.yml` megépíti a két release-fájlt (`sf-pack`, Fennec SDK), és release-t csinál belőlük.
Helyben: `./package.sh` (kell hozzá az `sf-pack`, lásd a script fejlécét). Az eredmény a `dist/` mappába kerül. 1. Emeld a `version` értékét az `app.toml`-ban és a `Cargo.toml`-ban.
2. `git tag v2.0.1 && git push --tags`.
3. A Gitea CI (`.gitea/workflows/release.yml`) megépíti x86-64-re és Raspberry Pi-ra (aarch64), és release-t csinál a store-fájlokkal. Secret nem kell hozzá.
Az app leírása: [Fennec SDK, store-app-guide.md](https://gitea.bluefox.support/fennec/sdk/src/branch/main/docs/store-app-guide.md). Helyben: `./package.sh` és `./package.sh --arm` (a feltételek a script fejlécében).
A TV-n: a Fennec katalógusból jön (`fennec/store`). Kézzel: Store → Források → `https://gitea.bluefox.support/fennec/youtube`.
## Licenc
GPL-3.0-only (az sf-ui és a Slint miatt). Az `ejs/` fájljai Unlicense alatt állnak.

View File

@@ -1,23 +1,19 @@
# Fennec OS store app manifest (docs/store-app-guide.md in the Fennec SDK). # Fennec OS store app manifest (docs/store-app-guide.md in the Fennec SDK).
id = "support.bluefox.youtube" id = "support.bluefox.youtube"
name = "YouTube" name = "YouTube"
# Release versions only (1.2.3). Bump it for every release. # Release versions only (1.2.3). Bump it (and Cargo.toml) for every release.
version = "1.0.0" version = "2.0.0"
kind = "web" kind = "exec"
category = "Videó · Castolható" category = "Videó"
description = "A YouTube TV-s felülete. Telefonról a YouTube appban a cast ikonnal küldhetsz ide videót." description = "Natív YouTube, reklámok nélkül: kezdőlap, feliratkozások, keresés, csatornák és listák, bejelentkezés QR-kóddal, hardveres videódekódolás."
author = "Bluefox" author = "Bluefox"
license = "MIT" license = "GPL-3.0-only"
homepage = "https://gitea.bluefox.support/fennec/youtube" homepage = "https://gitea.bluefox.support/fennec/youtube"
url = "https://www.youtube.com/tv" exec = ["bin/youtube-tv"]
icon = "icon.svg" icon = "icon.svg"
accent = "#FF2D2D" accent = "#FF2D2D"
palette = ["#ff6a5c", "#a3121c", "#16070a"] palette = ["#ff6a5c", "#a3121c", "#16070a"]
[web] [sandbox]
# A Cobalt (TV) user agent makes YouTube serve its leanback UI. # network: YouTube; gpu: glass and hardware video decoding; audio: sound.
user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0 Safari/537.36 Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (Fennec OS, SF1, Wired)" permissions = ["network", "gpu", "audio"]
# The YouTube app on a phone casts here (asks for the `dial` permission).
[dial]
name = "YouTube"

7
build.rs Normal file
View File

@@ -0,0 +1,7 @@
fn main() {
// sf-ui's build script publishes where its Slint library is ("@sf-ui").
let sf_ui = std::env::var("DEP_SF_UI_UI_DIR").expect("sf-ui must be a direct dependency");
let config = slint_build::CompilerConfiguration::new()
.with_library_paths(std::collections::HashMap::from([("sf-ui".to_string(), sf_ui.into())]));
slint_build::compile_with_config("ui/app.slint", config).expect("compiling ui/app.slint");
}

24
ejs/LICENSE Normal file
View File

@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org/>

5
ejs/yt.solver.core.min.js vendored Normal file

File diff suppressed because one or more lines are too long

52
ejs/yt.solver.lib.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,12 +1,70 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Builds the two store release assets into dist/: app.toml and # Builds the store release assets into dist/:
# support.bluefox.youtube-<version>.tar.zst. Needs sf-pack (Fennec SDK): #
# cargo install --locked --git https://gitea.bluefox.support/fennec/sdk --tag v0.1.0 sf-pack # ./package.sh app.toml and support.bluefox.youtube-<version>.tar.zst
# (x86-64; dist/ is emptied first)
# ./package.sh --arm adds support.bluefox.youtube-<version>-aarch64.tar.zst
# (Raspberry Pi, cross-compiled)
#
# Build on Debian trixie or older (the TV's glibc), with the GStreamer dev
# packages (libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev) and
# sf-pack from the Fennec SDK:
# cargo install --locked --git https://gitea.bluefox.support/fennec/sdk --tag v0.1.2 sf-pack
# --arm also needs gcc-aarch64-linux-gnu, the arm64 (multiarch) dev packages
# of fontconfig, freetype, xkbcommon and glib, and the arm64 GStreamer
# runtime libraries (libgstreamer1.0-0:arm64 libgstreamer-plugins-base1.0-0:arm64).
# Not the GStreamer dev packages: they can't be installed for two
# architectures at once, so the build links the runtime libraries directly.
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")" cd "$(dirname "$0")"
rm -rf pkg dist target="${CARGO_TARGET_DIR:-target}"
mkdir -p pkg id=$(sed -n 's/^id *= *"\(.*\)".*/\1/p' app.toml | head -1)
cp app.toml icon.svg pkg/ version=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' app.toml | head -1)
sf-pack build pkg dist
sf-pack verify dist # pack <binary> <out dir>: the package with this binary.
pack() {
rm -rf pkg
mkdir -p pkg/bin
cp app.toml icon.svg pkg/
install -m755 "$1" pkg/bin/youtube-tv
sf-pack build pkg "$2"
sf-pack verify "$2"
rm -rf pkg
}
if [ "${1:-}" != --arm ]; then
cargo build --release --locked
rm -rf dist
pack "$target/release/youtube-tv" dist
else
t=aarch64-unknown-linux-gnu
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
export CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++
export PKG_CONFIG_ALLOW_CROSS=1 PKG_CONFIG_SYSROOT_DIR=/
export PKG_CONFIG_PATH=/usr/lib/aarch64-linux-gnu/pkgconfig:/usr/share/pkgconfig
rustup target list --installed | grep -qx "$t" || rustup target add "$t"
# GStreamer without pkg-config (system-deps): link the runtime libraries
# through a folder of unversioned names.
mkdir -p "$target"
gst="$(cd "$target" && pwd)/arm-gstreamer"
rm -rf "$gst" && mkdir -p "$gst"
# system-deps key (the pkg-config name) and the library it stands for.
for pair in GSTREAMER_1_0:gstreamer-1.0 GSTREAMER_BASE_1_0:gstbase-1.0 \
GSTREAMER_APP_1_0:gstapp-1.0 GSTREAMER_VIDEO_1_0:gstvideo-1.0; do
key=${pair%%:*} lib=${pair#*:}
so=/usr/lib/aarch64-linux-gnu/lib$lib.so.0
[ -e "$so" ] || { echo "missing $so (install the arm64 GStreamer runtime libraries)" >&2; exit 1; }
ln -s "$so" "$gst/lib$lib.so"
export "SYSTEM_DEPS_${key}_NO_PKG_CONFIG=1" "SYSTEM_DEPS_${key}_LIB=$lib" "SYSTEM_DEPS_${key}_SEARCH_NATIVE=$gst"
done
cargo build --release --locked --target "$t"
rm -rf dist-arm
pack "$target/$t/release/youtube-tv" dist-arm
# Fennec OS on ARM looks for <id>-<version>-aarch64.tar.zst (docs/store.md).
mkdir -p dist
mv "dist-arm/$id-$version.tar.zst" "dist/$id-$version-aarch64.tar.zst"
[ -f dist/app.toml ] || mv dist-arm/app.toml dist/
rm -rf dist-arm
fi
ls -l dist

959
src/app.rs Normal file
View File

@@ -0,0 +1,959 @@
//! The controller: the screen stack, keys, overlays (QR sign-in, toast),
//! the backdrop. (Its page and screen model comes from Netflex TV.)
//!
//! Browsing screens implement `Screen`: they describe their page as lines
//! (`spec`) and react to activation. While one of their methods runs it is
//! taken out of the stack, so methods may freely start tasks and request
//! effects (push, play...), which run when the method returns.
use std::any::Any;
use std::cell::{Cell, Ref, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use std::time::{Duration, Instant};
use slint::platform::Key;
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use crate::config::{self, Account, Library, Settings};
use crate::page::{Focus, Kind, Spec, View};
use crate::yt::{self, Client};
use crate::{App, player, screens, task};
/// A remote / keyboard key, as screens see it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
Up,
Down,
Left,
Right,
Ok,
Back,
PlayPause,
}
fn action(text: &str) -> Option<Action> {
let is = |k: Key| text == SharedString::from(k).as_str();
Some(if is(Key::UpArrow) {
Action::Up
} else if is(Key::DownArrow) {
Action::Down
} else if is(Key::LeftArrow) {
Action::Left
} else if is(Key::RightArrow) {
Action::Right
} else if is(Key::Return) {
Action::Ok
} else if is(Key::Escape) || is(Key::Backspace) || is(Key::Back) {
Action::Back
} else if text == " " {
Action::PlayPause
} else {
return None;
})
}
/// Top navigation sections.
pub const SECTIONS: [&str; 5] = ["Kezdőlap", "Feliratkozások", "Könyvtár", "Keresés", "Beállítások"];
pub const SETTINGS: usize = 4;
pub const PALETTE: [&str; 3] = ["#ff6a5c", "#a3121c", "#16070a"];
/// A browsing screen.
pub trait Screen: Any {
/// The page: lines and frame.
fn spec(&mut self, cx: &Cx) -> Spec;
/// OK on an element of a line.
fn activate(&mut self, cx: &Cx, line: &str, item: &str);
/// The focus moved (backdrop...).
fn focus(&mut self, _cx: &Cx, _line: &str, _item: &str) {}
/// Back; true = handled (the screen stays).
fn back(&mut self, _cx: &Cx) -> bool {
false
}
/// The focus is near the end of list `list`.
fn more(&mut self, _cx: &Cx, _list: &str) {}
/// On top again (back from a child or the player).
fn shown(&mut self, _cx: &Cx) {}
/// Settings side list: tab `i`.
fn side(&mut self, _cx: &Cx, _i: usize) {}
/// The search keyboard's text changed (`submit`: the search key).
fn query(&mut self, _cx: &Cx, _text: &str, _submit: bool) {}
fn as_any(&mut self) -> &mut dyn Any;
}
enum Effect {
Push(Box<dyn Screen>),
Refresh,
Play(player::Request),
}
struct Entry {
id: u64,
screen: Option<Box<dyn Screen>>,
view: View,
}
pub struct State {
pub client: Client,
pub account: Account,
pub settings: Settings,
pub library: Library,
stack: Vec<Entry>,
next_id: u64,
/// "page", "player"
pub screen: &'static str,
pub player: Option<player::Player>,
/// The QR sign-in running (its generation).
link: Option<u64>,
}
pub struct Inner {
pub ui: slint::Weak<App>,
pub glass: sf_ui::Glass,
pub images: sf_ui::images::Images,
pub state: RefCell<State>,
effects: RefCell<Vec<Effect>>,
toast_timer: slint::Timer,
backdrop_timer: slint::Timer,
backdrop_key: RefCell<String>,
pub colours: Rc<RefCell<HashMap<String, slint::Color>>>,
search_timer: slint::Timer,
link_timer: slint::Timer,
link_polling: Cell<bool>,
link_gen: Cell<u64>,
}
/// Cheap to clone; every callback holds one.
#[derive(Clone)]
pub struct Controller(pub Rc<Inner>);
impl std::ops::Deref for Controller {
type Target = Inner;
fn deref(&self) -> &Inner {
&self.0
}
}
/// What a screen's methods get: the controller and the screen's own id.
pub struct Cx<'a> {
pub c: &'a Controller,
pub id: u64,
}
/// How the backdrop picture shows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Look {
/// Channel pages: sharp, dark towards the left and bottom.
Sharp,
/// Browsing: blurred and dim behind the rows.
Soft,
}
impl<'a> Cx<'a> {
pub fn client(&self) -> Client {
self.c.client()
}
pub fn signed_in(&self) -> bool {
self.c.state.borrow().account.signed_in()
}
pub fn settings(&self) -> Settings {
self.c.state.borrow().settings.clone()
}
pub fn set_settings(&self, s: Settings) {
s.save();
self.c.state.borrow_mut().settings = s;
}
pub fn account(&self) -> Account {
self.c.state.borrow().account.clone()
}
pub fn library(&self) -> Ref<'_, Library> {
Ref::map(self.c.state.borrow(), |s| &s.library)
}
/// Changes the library and saves it.
pub fn update_library<R>(&self, f: impl FnOnce(&mut Library) -> R) -> R {
self.c.update_library(f)
}
/// Runs `work` on a thread; `done` gets this screen back (if it still
/// exists) on the UI thread. The page is rebuilt afterwards.
pub fn spawn<T: Screen, R: Send + 'static>(&self, work: impl FnOnce() -> R + Send + 'static, done: impl FnOnce(&mut T, &Cx, R) + 'static) {
let c = self.c.clone();
let id = self.id;
task::spawn(work, move |r| c.with::<T>(id, move |s, cx| done(s, cx, r)));
}
/// Fire and forget, then rebuild this screen's page (and run `then`).
pub fn call<T: Screen>(&self, what: &'static str, work: impl FnOnce() -> anyhow::Result<()> + Send + 'static, then: impl FnOnce(&mut T, &Cx, bool) + 'static) {
self.spawn::<T, _>(work, move |s, cx, r| {
let ok = r.is_ok();
if let Err(e) = r {
cx.error(what, &e);
}
then(s, cx, ok);
});
}
/// Shows an error (or signs out when the account's token is gone).
pub fn error(&self, what: &str, e: &anyhow::Error) {
self.c.error(what, e);
}
pub fn push(&self, s: Box<dyn Screen>) {
self.c.effects.borrow_mut().push(Effect::Push(s));
}
pub fn refresh(&self) {
self.c.effects.borrow_mut().push(Effect::Refresh);
}
pub fn play(&self, r: player::Request) {
self.c.effects.borrow_mut().push(Effect::Play(r));
}
pub fn toast(&self, text: &str) {
self.c.toast(text, false);
}
pub fn backdrop(&self, url: &str, look: Look, key: &str) {
self.c.backdrop(url, look, key);
}
}
impl Controller {
pub fn new(ui: &App, glass: sf_ui::Glass, images: sf_ui::images::Images) -> Controller {
let account = Account::load();
let settings = Settings::load();
let client = Client::new(account.signed_in().then(|| account.refresh_token.clone()));
let state = State {
client,
account,
settings,
library: Library::load(),
stack: Vec::new(),
next_id: 1,
screen: "page",
player: None,
link: None,
};
let c = Controller(Rc::new(Inner {
ui: ui.as_weak(),
glass,
images,
state: RefCell::new(state),
effects: RefCell::default(),
toast_timer: slint::Timer::default(),
backdrop_timer: slint::Timer::default(),
backdrop_key: RefCell::default(),
colours: Rc::default(),
search_timer: slint::Timer::default(),
link_timer: slint::Timer::default(),
link_polling: Cell::new(false),
link_gen: Cell::new(0),
}));
config::apply_look(&c.glass, &c.state.borrow().settings.glass);
let k = c.clone();
ui.on_key(move |text, repeat| match action(&text) {
Some(a) => {
k.key(a, repeat);
true
}
None => false,
});
let k = c.clone();
ui.on_search_submitted(move |t| k.search(t.to_string(), true));
let k = c.clone();
ui.on_search_changed(move |t| k.search(t.to_string(), false));
let k = c.clone();
ui.on_search_exit_down(move || k.leave_keyboard(true));
let k = c.clone();
ui.on_search_exit_up(move || k.leave_keyboard(false));
let k = c.clone();
ui.on_search_cancelled(move || k.leave_keyboard(false));
ui.set_page_nav_items(ModelRc::new(VecModel::from(SECTIONS.iter().map(|s| SharedString::from(*s)).collect::<Vec<_>>())));
c
}
pub fn ui(&self) -> Option<App> {
self.ui.upgrade()
}
pub fn px(&self) -> f32 {
self.ui()
.map(|ui| {
let s = ui.window().size();
(s.width as f32 / 1920.0).min(s.height as f32 / 1080.0).max(0.5)
})
.unwrap_or(1.0)
}
pub fn client(&self) -> Client {
self.state.borrow().client.clone()
}
pub fn update_library<R>(&self, f: impl FnOnce(&mut Library) -> R) -> R {
let mut st = self.state.borrow_mut();
let r = f(&mut st.library);
st.library.save();
r
}
pub fn show(&self, screen: &'static str) {
self.state.borrow_mut().screen = screen;
if let Some(ui) = self.ui() {
ui.set_screen(screen.into());
}
}
pub fn start(&self) {
self.account_label();
self.section_now(0);
if self.state.borrow().account.signed_in() {
// The name may have changed; this also checks the token.
let client = self.client();
let c = self.clone();
task::spawn(move || client.account(), move |r| match r {
Ok((name, photo)) if !name.is_empty() => {
let mut st = c.state.borrow_mut();
st.account.name = name;
st.account.photo = photo;
st.account.save();
drop(st);
c.account_label();
}
Ok(_) => {}
Err(e) => c.error("account", &e),
});
}
}
pub fn shutdown(&self) {
player::stop(self, true);
}
/// Shows an error; a lost sign-in signs out.
pub fn error(&self, what: &str, e: &anyhow::Error) {
let lost = e.chain().any(|c| c.downcast_ref::<yt::YtError>().is_some_and(|y| y.status == 401)) && self.state.borrow().account.signed_in();
if lost {
let c = self.clone();
slint::Timer::single_shot(Duration::from_millis(1), move || c.signed_out(true));
return;
}
log::warn!("{what}: {e:#}");
self.toast(&yt::describe(e), true);
}
fn account_label(&self) {
let (on, name) = {
let st = self.state.borrow();
(st.account.signed_in(), st.account.name.clone())
};
if let Some(ui) = self.ui() {
ui.set_page_account_label(if on { (if name.is_empty() { "Bejelentkezve".to_string() } else { name }).into() } else { "".into() });
ui.set_page_account_ok(on);
}
}
// ---- QR sign-in ----
/// Shows a code and a QR code; the user confirms on a phone.
pub fn sign_in(&self) {
let generation = self.link_gen.get() + 1;
self.link_gen.set(generation);
self.state.borrow_mut().link = Some(generation);
self.link_timer.stop();
self.link_polling.set(false);
if let Some(ui) = self.ui() {
ui.set_link_code("".into());
ui.set_link_url("".into());
ui.set_link_qr(Default::default());
ui.set_link_status("Kód kérése a YouTube-tól…".into());
ui.set_link_busy(true);
ui.set_link_open(true);
}
let client = self.client();
let c = self.clone();
task::spawn(move || yt::auth::start(&client.agent), move |r| {
if c.state.borrow().link != Some(generation) {
return;
}
match r {
Ok(code) => c.link_show(generation, code),
Err(e) => c.link_status(&format!("{} · OK: újra", yt::describe(&e)), false),
}
});
}
fn link_status(&self, text: &str, busy: bool) {
if let Some(ui) = self.ui() {
ui.set_link_status(text.into());
ui.set_link_busy(busy);
}
}
fn link_show(&self, generation: u64, code: yt::auth::DeviceCode) {
if let Some(ui) = self.ui() {
ui.set_link_code(code.user_code.clone().into());
ui.set_link_url(code.url.trim_start_matches("https://").trim_start_matches("www.").into());
ui.set_link_qr(crate::qr::image(&code.qr_link()));
}
self.link_status("Várakozás a megerősítésre…", true);
let deadline = Instant::now() + Duration::from_secs(code.expires_in);
let code = Rc::new(code);
let c = self.clone();
self.link_timer.start(slint::TimerMode::Repeated, Duration::from_secs(code.interval), move || {
if c.state.borrow().link != Some(generation) || c.link_polling.get() {
return;
}
if Instant::now() >= deadline {
return c.sign_in();
}
c.link_polling.set(true);
let client = c.client();
let code2 = (*code).clone();
let c2 = c.clone();
task::spawn(move || yt::auth::poll(&client.agent, &code2), move |r| {
c2.link_polling.set(false);
if c2.state.borrow().link != Some(generation) {
return;
}
match r {
Ok(yt::auth::Poll::Pending | yt::auth::Poll::SlowDown) => {}
Ok(yt::auth::Poll::Done { refresh, access, expires_in }) => c2.signed_in(refresh, access, expires_in),
Ok(yt::auth::Poll::Expired) => c2.sign_in(),
Ok(yt::auth::Poll::Denied) => {
c2.link_timer.stop();
c2.link_status("A bejelentkezést elutasítottad. · OK: új kód", false);
}
Err(e) => log::warn!("sign-in poll: {e:#}"),
}
});
});
}
fn signed_in(&self, refresh: String, access: String, expires_in: u64) {
self.link_timer.stop();
self.link_status("Bejelentkezés…", true);
let client = {
let mut st = self.state.borrow_mut();
st.account = Account { refresh_token: refresh.clone(), ..Account::default() };
st.account.save();
st.client.set_session(Some(yt::Session { refresh_token: refresh, access_token: access, expires: yt::now() + expires_in }));
st.client.clone()
};
let c = self.clone();
task::spawn(move || client.account(), move |r| {
let name = match r {
Ok((name, photo)) => {
let mut st = c.state.borrow_mut();
st.account.name = name.clone();
st.account.photo = photo;
st.account.save();
name
}
Err(e) => {
log::warn!("account: {e:#}");
String::new()
}
};
c.link_close();
c.account_label();
c.toast(&if name.is_empty() { "Bejelentkeztél".to_string() } else { format!("Bejelentkeztél: {name}") }, false);
c.section_now(0);
});
}
fn link_close(&self) {
self.state.borrow_mut().link = None;
self.link_timer.stop();
if let Some(ui) = self.ui() {
ui.set_link_open(false);
}
}
fn link_key(&self, a: Action) {
let busy = self.ui().is_some_and(|ui| ui.get_link_busy());
match a {
Action::Back => self.link_close(),
Action::Ok if !busy => self.sign_in(),
_ => {}
}
}
/// Signs out (Beállítások → Fiók); `lost`: the token stopped working.
pub fn signed_out(&self, lost: bool) {
let (client, token) = {
let mut st = self.state.borrow_mut();
let token = std::mem::take(&mut st.account.refresh_token);
st.account = Account::default();
st.account.save();
st.client.set_session(None);
(st.client.clone(), token)
};
if !lost && !token.is_empty() {
task::background("revoke", move || {
yt::auth::revoke(&client.agent, &token);
Ok(())
});
}
self.account_label();
self.toast(if lost { "A YouTube-bejelentkezés lejárt, jelentkezz be újra." } else { "Kijelentkeztél" }, lost);
let n = self.state.borrow().stack.first().and_then(|e| e.view.frame.nav).unwrap_or(0);
self.section_now(n);
}
// ---- toast ----
pub fn toast(&self, text: &str, bad: bool) {
let Some(ui) = self.ui() else { return };
ui.set_toast_text(text.into());
ui.set_toast_bad(bad);
let w = self.ui.clone();
self.toast_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(if bad { 5000 } else { 2600 }), move || {
if let Some(ui) = w.upgrade() {
ui.set_toast_text("".into());
}
});
}
// ---- backdrop ----
/// The backdrop picture `url` (after the focus settles), or the gradient.
pub fn backdrop(&self, url: &str, look: Look, key: &str) {
if *self.backdrop_key.borrow() == key && !key.is_empty() {
return;
}
*self.backdrop_key.borrow_mut() = key.to_string();
if let Some(col) = self.colours.borrow().get(key).copied() {
self.glass.set_palette(sf_ui::Palette::from_color(col));
}
if url.is_empty() {
self.backdrop_timer.stop();
self.glass.set_backdrop(None);
return;
}
let (c, url, key) = (self.clone(), url.to_string(), key.to_string());
self.backdrop_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(350), move || {
let px = c.px();
let size = if look == Look::Soft { ((960.0 * px) as u32, (540.0 * px) as u32) } else { ((1920.0 * px) as u32, (1080.0 * px) as u32) };
let c2 = c.clone();
let key2 = key.clone();
c.images.load_pixels(&url, size, move |pixels| {
if *c2.backdrop_key.borrow() != key2 || c2.state.borrow().screen == "player" {
return;
}
c2.colours.borrow_mut().insert(key2.clone(), sf_ui::images::average_color(pixels));
if let Some(col) = c2.colours.borrow().get(&key2).copied() {
c2.glass.set_palette(sf_ui::Palette::from_color(col));
}
let b = sf_ui::Backdrop::new(pixels.clone());
let b = match look {
Look::Sharp => b.dim(0.3).fade_left(1.0).fade_bottom(0.9).align(0.6, 0.2),
Look::Soft => b.dim(0.6).fade_left(0.6).fade_bottom(0.8).soft(),
};
c2.glass.set_backdrop(Some(b));
});
});
}
pub fn clear_backdrop(&self) {
self.backdrop_key.borrow_mut().clear();
self.backdrop_timer.stop();
self.glass.set_backdrop(None);
}
// ---- the screen stack ----
/// Runs `f` on screen `id` (if it still exists), then the effects and a
/// rebuild of the top page.
pub fn with<T: Screen>(&self, id: u64, f: impl FnOnce(&mut T, &Cx)) {
let taken = {
let mut st = self.state.borrow_mut();
st.stack.iter_mut().find(|e| e.id == id).and_then(|e| e.screen.take())
};
let Some(mut screen) = taken else { return };
{
let cx = Cx { c: self, id };
if let Some(s) = screen.as_any().downcast_mut::<T>() {
f(s, &cx);
}
}
{
let mut st = self.state.borrow_mut();
if let Some(e) = st.stack.iter_mut().find(|e| e.id == id) {
e.screen = Some(screen);
}
}
let top = self.state.borrow().stack.last().map(|e| e.id);
if top == Some(id) {
self.effects.borrow_mut().push(Effect::Refresh);
}
self.run_effects();
}
/// Runs a `Screen` method on the top screen.
fn top<R>(&self, f: impl FnOnce(&mut dyn Screen, &Cx) -> R) -> Option<R> {
let (id, taken) = {
let mut st = self.state.borrow_mut();
let e = st.stack.last_mut()?;
(e.id, e.screen.take())
};
let mut screen = taken?;
let r = {
let cx = Cx { c: self, id };
f(screen.as_mut(), &cx)
};
{
let mut st = self.state.borrow_mut();
if let Some(e) = st.stack.iter_mut().find(|e| e.id == id) {
e.screen = Some(screen);
}
}
Some(r)
}
fn run_effects(&self) {
loop {
let effects: Vec<Effect> = std::mem::take(&mut *self.effects.borrow_mut());
if effects.is_empty() {
break;
}
let mut refresh = false;
for e in effects {
match e {
Effect::Push(s) => self.push_now(s),
Effect::Refresh => refresh = true,
Effect::Play(r) => player::play(self, r),
}
}
if refresh && self.state.borrow().screen == "page" {
self.rebuild();
}
}
}
fn push_now(&self, s: Box<dyn Screen>) {
{
let mut st = self.state.borrow_mut();
let id = st.next_id;
st.next_id += 1;
st.stack.push(Entry { id, screen: Some(s), view: View::default() });
}
self.clear_backdrop();
self.attach();
self.rebuild();
self.after_focus();
}
fn pop_now(&self) {
{
let mut st = self.state.borrow_mut();
if st.stack.len() > 1 {
st.stack.pop();
}
}
self.clear_backdrop();
self.attach();
self.top(|s, cx| s.shown(cx));
self.rebuild();
self.after_focus();
}
/// Replaces the stack with a section's screen.
pub fn section_now(&self, n: usize) {
let keep_nav = self.state.borrow().stack.last().is_some_and(|e| e.view.focus == Focus::Nav);
self.state.borrow_mut().stack.clear();
let screen = screens::section(n);
{
let mut st = self.state.borrow_mut();
let id = st.next_id;
st.next_id += 1;
let mut view = View::default();
view.nav_index = n;
if keep_nav {
view.focus = Focus::Nav;
}
st.stack.push(Entry { id, screen: Some(screen), view });
}
self.clear_backdrop();
self.glass.set_palette(sf_ui::Palette::from_hex(PALETTE));
self.attach();
self.rebuild();
self.after_focus();
}
/// Points Slint at the top view's model and shows the page.
fn attach(&self) {
let model = self.state.borrow().stack.last().map(|e| e.view.model());
if let (Some(ui), Some(m)) = (self.ui(), model) {
ui.set_page_lines(m);
}
if self.state.borrow().screen != "player" {
self.show("page");
}
}
/// Rebuilds the top page from its screen.
pub fn rebuild(&self) {
let spec = self.top(|s, cx| s.spec(cx));
let Some(spec) = spec else { return };
let px = self.px();
{
let mut st = self.state.borrow_mut();
if let Some(e) = st.stack.last_mut() {
e.view.set(spec, &self.images, px);
}
}
self.sync();
}
/// Focus, scroll and frame to Slint; pictures around the focus.
fn sync(&self) {
let Some(ui) = self.ui() else { return };
let px = self.px();
let mut st = self.state.borrow_mut();
let Some(e) = st.stack.last_mut() else { return };
let v = &mut e.view;
v.sync_cols();
ui.set_page_focus(if v.focus == Focus::Line { v.line as i32 } else { -1 });
ui.set_page_scroll(v.scroll);
ui.set_page_show_nav(v.frame.nav.is_some());
ui.set_page_nav_index(v.frame.nav.unwrap_or(0) as i32);
ui.set_page_nav_focused(v.focus == Focus::Nav);
match &v.frame.side {
Some((title, items, cur)) => {
ui.set_page_side_title(title.clone().into());
ui.set_page_side_items(ModelRc::new(VecModel::from(items.iter().map(|s| SharedString::from(s.as_str())).collect::<Vec<_>>())));
ui.set_page_side_index(*cur as i32);
ui.set_page_side_focus(if v.focus == Focus::Side { v.side_focus as i32 } else { -1 });
}
None => {
ui.set_page_side_items(ModelRc::default());
ui.set_page_side_focus(-1);
}
}
let kb_line = v.lines.iter().position(|l| l.kind == Kind::Keyboard);
match (kb_line, &v.frame.keyboard) {
(Some(i), Some(ph)) => {
ui.set_page_kb_y(v.line_y(i));
ui.set_page_kb_placeholder(ph.clone().into());
ui.set_page_kb_focused(v.focus == Focus::Line && v.line == i);
}
_ => {
ui.set_page_kb_y(-1.0);
ui.set_page_kb_focused(false);
}
}
v.load_images(&self.images, px);
}
fn after_focus(&self) {
let target = {
let st = self.state.borrow();
st.stack.last().map(|e| (e.view.target(), e.view.near_end(), e.view.focus.clone()))
};
let Some(((line, item), near, focus)) = target else { return };
if focus == Focus::Line {
self.top(|s, cx| s.focus(cx, &line, &item));
if let Some(list) = near {
self.top(|s, cx| s.more(cx, &list));
}
}
self.run_effects();
}
// ---- keys ----
fn key(&self, a: Action, repeat: bool) {
if self.state.borrow().link.is_some() {
return self.link_key(a);
}
let screen = self.state.borrow().screen;
if screen == "player" {
return player::key(self, a, repeat);
}
self.page_key(a);
}
fn page_key(&self, a: Action) {
enum Then {
Moved,
Activate(String, String),
Back,
Section(usize),
Side(usize),
Nothing,
Quit,
}
let then = {
let mut st = self.state.borrow_mut();
let Some(e) = st.stack.last_mut() else { return };
let v = &mut e.view;
let has_side = v.frame.side.is_some();
let has_nav = v.frame.nav.is_some();
match v.focus {
Focus::Nav => match a {
Action::Left if v.frame.nav.unwrap_or(0) > 0 => Then::Section(v.frame.nav.unwrap() - 1),
Action::Right if v.frame.nav.unwrap_or(0) + 1 < SECTIONS.len() => Then::Section(v.frame.nav.unwrap() + 1),
Action::Down | Action::Ok => {
if v.has_lines() && v.lines.iter().any(|l| matches!(l.kind, Kind::Chips | Kind::Cards | Kind::Item | Kind::Hero | Kind::Keyboard)) {
v.focus = if has_side { Focus::Side } else { Focus::Line };
v.clamp_scroll();
Then::Moved
} else {
Then::Nothing
}
}
Action::Back if v.frame.nav.unwrap_or(0) != 0 => Then::Section(0),
Action::Back => Then::Quit,
_ => Then::Nothing,
},
Focus::Side => {
let n = v.frame.side.as_ref().map(|s| s.1.len()).unwrap_or(0);
match a {
Action::Up if v.side_focus > 0 => {
v.side_focus -= 1;
Then::Side(v.side_focus)
}
Action::Up if has_nav => {
v.focus = Focus::Nav;
Then::Moved
}
Action::Down if v.side_focus + 1 < n => {
v.side_focus += 1;
Then::Side(v.side_focus)
}
Action::Right | Action::Ok => {
if v.lines.iter().any(|l| matches!(l.kind, Kind::Chips | Kind::Cards | Kind::Item | Kind::Hero)) {
v.focus = Focus::Line;
v.clamp_scroll();
}
Then::Moved
}
Action::Back => Then::Back,
_ => Then::Nothing,
}
}
Focus::Line => match a {
Action::Up => {
if !v.vertical(false) {
if has_side {
v.focus = Focus::Side;
} else if has_nav {
v.focus = Focus::Nav;
v.scroll = 0.0;
}
}
Then::Moved
}
Action::Down => {
v.vertical(true);
Then::Moved
}
Action::Left => {
if !v.horizontal(false) && has_side {
v.focus = Focus::Side;
}
Then::Moved
}
Action::Right => {
v.horizontal(true);
Then::Moved
}
Action::Ok | Action::PlayPause => {
let (l, i) = v.target();
Then::Activate(l, i)
}
Action::Back => Then::Back,
},
}
};
match then {
Then::Nothing => {}
Then::Quit => {
let _ = slint::quit_event_loop();
}
Then::Moved => {
self.sync();
self.after_focus();
}
Then::Section(n) => self.section_now(n),
Then::Side(i) => {
self.top(|s, cx| s.side(cx, i));
self.rebuild();
self.run_effects();
}
Then::Activate(l, i) => {
self.top(|s, cx| s.activate(cx, &l, &i));
self.effects.borrow_mut().push(Effect::Refresh);
self.run_effects();
self.after_focus();
}
Then::Back => {
let handled = self.top(|s, cx| s.back(cx)).unwrap_or(false);
if handled {
self.effects.borrow_mut().push(Effect::Refresh);
self.run_effects();
return;
}
let depth = self.state.borrow().stack.len();
if depth > 1 {
self.pop_now();
} else {
let mut st = self.state.borrow_mut();
if let Some(e) = st.stack.last_mut() {
if e.view.frame.nav.is_some() {
e.view.focus = Focus::Nav;
e.view.scroll = 0.0;
} else if e.view.frame.side.is_some() {
e.view.focus = Focus::Side;
}
}
drop(st);
self.sync();
}
}
}
}
// ---- search keyboard ----
fn search(&self, text: String, submit: bool) {
if submit {
self.search_timer.stop();
self.top(|s, cx| s.query(cx, &text, true));
self.run_effects();
return;
}
let c = self.clone();
self.search_timer.start(slint::TimerMode::SingleShot, Duration::from_millis(600), move || {
c.top(|s, cx| s.query(cx, &text, false));
c.run_effects();
});
}
fn leave_keyboard(&self, down: bool) {
{
let mut st = self.state.borrow_mut();
let Some(e) = st.stack.last_mut() else { return };
let v = &mut e.view;
if !v.vertical(down) && !down && v.frame.nav.is_some() {
v.focus = Focus::Nav;
}
}
self.sync();
self.after_focus();
}
/// Opens a screen from outside the screens (the player's channel button).
pub fn push_screen(&self, s: Box<dyn Screen>) {
self.effects.borrow_mut().push(Effect::Push(s));
self.run_effects();
}
/// Back from the player.
pub fn player_closed(&self) {
self.clear_backdrop();
self.attach();
self.top(|s, cx| s.shown(cx));
self.rebuild();
self.after_focus();
}
}

210
src/config.rs Normal file
View File

@@ -0,0 +1,210 @@
//! What the app remembers, in `$HOME/.config/youtube/` (on the TV, $HOME is
//! the app's own data folder inside the sandbox):
//!
//! - `settings.toml`: playback and look (Beállítások);
//! - `account.toml`: the signed-in account (refresh token, name, picture);
//! - `library.json`: this TV's watch history and, signed out, its
//! subscriptions.
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::yt::Video;
fn dir() -> PathBuf {
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("APPDATA")).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
home.join(".config").join("youtube")
}
fn load<T: for<'de> Deserialize<'de> + Default>(name: &str) -> T {
let text = std::fs::read_to_string(dir().join(name)).ok();
let parsed = text.and_then(|t| if name.ends_with(".json") { serde_json::from_str(&t).ok() } else { toml::from_str(&t).ok() });
parsed.unwrap_or_default()
}
fn save<T: Serialize>(name: &str, value: &T) {
let p = dir().join(name);
let result = (|| -> anyhow::Result<()> {
std::fs::create_dir_all(dir())?;
let text = if name.ends_with(".json") { serde_json::to_string(value)? } else { toml::to_string(value)? };
let tmp = p.with_extension("tmp");
std::fs::write(&tmp, text)?;
std::fs::rename(&tmp, &p)?;
Ok(())
})();
if let Err(e) = result {
log::warn!("saving {}: {e:#}", p.display());
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Settings {
/// Highest video quality (height); 0: automatic (up to 1080p, adaptive).
pub quality: u64,
/// "h264" | "av1"
pub codec: String,
/// Captions: "" off, "hu", "en"; Hungarian may be machine-translated.
pub captions: String,
/// Skip sponsored parts (SponsorBlock).
pub sponsorblock: bool,
/// Play the next video when one ends.
pub autoplay: bool,
/// Show Shorts shelves.
pub shorts: bool,
/// "auto" | "full" | "light" | "off" (Material)
pub glass: String,
}
impl Default for Settings {
fn default() -> Self {
Settings { quality: 0, codec: "h264".into(), captions: String::new(), sponsorblock: true, autoplay: true, shorts: true, glass: "auto".into() }
}
}
impl Settings {
pub fn load() -> Settings {
load("settings.toml")
}
pub fn save(&self) {
save("settings.toml", self)
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Account {
pub refresh_token: String,
pub name: String,
pub photo: String,
}
impl Account {
pub fn load() -> Account {
load("account.toml")
}
pub fn save(&self) {
save("account.toml", self)
}
pub fn signed_in(&self) -> bool {
!self.refresh_token.is_empty()
}
}
/// A video this TV played.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Watched {
pub id: String,
pub title: String,
pub channel: String,
pub channel_id: String,
pub thumb: String,
pub position: f64,
pub duration: f64,
/// Unix seconds.
pub at: u64,
}
impl Watched {
/// Where to start again: from the beginning when (nearly) finished.
pub fn resume_at(&self) -> f64 {
if self.duration > 0.0 && (self.position > self.duration - 20.0 || self.position / self.duration > 0.95) || self.position < 10.0 {
0.0
} else {
self.position
}
}
pub fn unfinished(&self) -> bool {
self.resume_at() > 0.0
}
pub fn video(&self) -> Video {
Video {
id: self.id.clone(),
title: self.title.clone(),
channel: self.channel.clone(),
channel_id: self.channel_id.clone(),
thumb: self.thumb.clone(),
progress: if self.duration > 0.0 { (self.position / self.duration).clamp(0.0, 1.0) as f32 } else { -1.0 },
..Video::default()
}
}
}
/// A channel followed on this TV (signed out).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Sub {
pub id: String,
pub title: String,
pub thumb: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Library {
/// Newest first.
pub history: Vec<Watched>,
pub subs: Vec<Sub>,
}
const HISTORY_MAX: usize = 300;
impl Library {
pub fn load() -> Library {
load("library.json")
}
pub fn save(&self) {
save("library.json", self)
}
pub fn find(&self, id: &str) -> Option<&Watched> {
self.history.iter().find(|w| w.id == id)
}
/// Records (or moves to the top) a played video.
pub fn watched(&mut self, w: Watched) {
self.history.retain(|x| x.id != w.id);
self.history.insert(0, w);
self.history.truncate(HISTORY_MAX);
}
pub fn is_sub(&self, id: &str) -> bool {
self.subs.iter().any(|s| s.id == id)
}
pub fn toggle_sub(&mut self, sub: Sub) -> bool {
if self.is_sub(&sub.id) {
self.subs.retain(|s| s.id != sub.id);
false
} else {
self.subs.push(sub);
true
}
}
}
/// Applies the glass look. "auto": sf-ui measures the GPU and picks full,
/// light or the matte Material style; "off" (shown as "Matt") is Material.
pub fn apply_look(glass: &sf_ui::Glass, look: &str) {
match look {
"full" => glass.set_quality(sf_ui::Quality::Full),
"light" => glass.set_quality(sf_ui::Quality::Light),
"off" => glass.set_quality(sf_ui::Quality::Material),
_ => glass.set_auto_quality(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resume_rules() {
let w = |position: f64, duration: f64| Watched { position, duration, ..Watched::default() };
assert_eq!(w(5.0, 600.0).resume_at(), 0.0, "barely started");
assert_eq!(w(300.0, 600.0).resume_at(), 300.0);
assert_eq!(w(590.0, 600.0).resume_at(), 0.0, "finished");
}
}

52
src/format.rs Normal file
View File

@@ -0,0 +1,52 @@
//! Hungarian texts. (YouTube's own texts already come in Hungarian: the
//! client asks with hl=hu.)
/// "1:02:03", "4:05"
pub fn time(s: f64) -> String {
let s = s.max(0.0).round() as i64;
let (h, m, sec) = (s / 3600, s / 60 % 60, s % 60);
if h > 0 { format!("{h}:{m:02}:{sec:02}") } else { format!("{m}:{sec:02}") }
}
/// "1080p", "4K"
pub fn quality(h: u64) -> String {
match h {
4320.. => "8K".into(),
2160.. => "4K".into(),
1440.. => "1440p".into(),
_ => format!("{h}p"),
}
}
/// "1 234 567" -> "1,2 M megtekintés"
pub fn views(count: &str) -> String {
let Ok(n) = count.parse::<u64>() else { return String::new() };
let short = |v: f64, unit: &str| {
let t = if v < 10.0 { format!("{:.1}", v).replace('.', ",") } else { format!("{}", v.floor()) };
format!("{} {unit}", t.trim_end_matches(",0"))
};
let text = match n {
0..=999 => n.to_string(),
1_000..=999_999 => short(n as f64 / 1e3, "E"),
1_000_000..=999_999_999 => short(n as f64 / 1e6, "M"),
_ => short(n as f64 / 1e9, "Mrd"),
};
format!("{text} megtekintés")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn texts() {
assert_eq!(time(3723.0), "1:02:03");
assert_eq!(time(65.4), "1:05");
assert_eq!(quality(2160), "4K");
assert_eq!(quality(720), "720p");
assert_eq!(views("1234567"), "1,2 M megtekintés");
assert_eq!(views("15300"), "15 E megtekintés");
assert_eq!(views("2000000"), "2 M megtekintés");
assert_eq!(views("12"), "12 megtekintés");
}
}

58
src/main.rs Normal file
View File

@@ -0,0 +1,58 @@
//! YouTube for Fennec OS: a native TV client, without ads.
//!
//! - UI: Slint (ui/*.slint) on sf-ui's Liquid Glass layer; the page engine
//! and controller come from Netflex TV (src/page.rs, src/app.rs).
//! - YouTube: src/yt (InnerTube; QR sign-in; streams as DASH manifests).
//! - Playback: sf-ui's GStreamer player (Linux, hardware decoding).
// Without a player (Windows, for UI work) some playback code sits unused.
#![cfg_attr(not(target_os = "linux"), allow(dead_code, unused_imports))]
mod app;
mod config;
mod format;
mod page;
mod player;
mod qr;
mod screens;
mod task;
mod yt;
use slint::{ComponentHandle, Model};
slint::include_modules!();
sf_ui::glue!(App);
fn main() -> anyhow::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
sf_ui::init()?;
#[cfg(target_os = "linux")]
if let Err(e) = sf_ui::video::init() {
log::error!("video: {e:#}");
}
let ui = App::new()?;
ui.sf_ui_setup();
if std::env::var_os("SF_UI_SIZE").is_none() && std::env::var_os("YOUTUBE_WINDOWED").is_none() {
ui.window().set_fullscreen(true);
}
let glass = sf_ui::Glass::install(&ui, |ui, p| {
p.extend(ui.get_glass_page().iter());
p.extend(ui.get_glass_page_keyboard().iter());
p.extend(ui.get_glass_player().iter());
p.extend(ui.get_glass_player_subs().iter());
p.extend(ui.get_glass_player_quality().iter());
p.extend(ui.get_glass_link().iter());
p.extend(ui.get_glass_toast().iter());
})?;
glass.set_palette(sf_ui::Palette::from_hex(app::PALETTE));
let images = sf_ui::images::Images::new(384 << 20);
let app = app::Controller::new(&ui, glass, images);
app.start();
ui.run()?;
app.shutdown();
Ok(())
}

955
src/page.rs Normal file
View File

@@ -0,0 +1,955 @@
//! The page engine (from Netflex TV; some of its line kinds are unused here). Every browsing screen describes itself as a list of
//! lines (`L`): hero, headings, texts, notices, chip rows, card rows, list
//! items, checks. This module lays them out on the 1920x1080 grid, owns the
//! focus and the scroll position, loads the pictures that are about to show,
//! and hands the result to ui/page.slint.
//!
//! Navigation is generic: up/down between focusable lines (and between the
//! rows of a wrapped chip line), left/right inside a line, the top nav above
//! the first line, the settings side list left of the content.
#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use slint::{Model, ModelRc, VecModel};
use crate::{Card, Check, Chip, Line};
/// Width of the content on a page without the side list (design px).
pub const CONTENT_W: f32 = 1728.0;
pub const SIDE_W: f32 = 1224.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Hero,
Heading,
Text,
Notice,
Chips,
Cards,
Item,
Checks,
Keyboard,
}
impl Kind {
fn name(self) -> &'static str {
match self {
Kind::Hero => "hero",
Kind::Heading => "heading",
Kind::Text => "text",
Kind::Notice => "notice",
Kind::Chips => "chips",
Kind::Cards => "cards",
Kind::Item => "item",
Kind::Checks => "checks",
Kind::Keyboard => "keyboard",
}
}
}
/// A chip (button, choice, text field).
#[derive(Debug, Clone, Default)]
pub struct Ch {
pub id: String,
pub text: String,
pub icon: String,
pub active: bool,
pub tone: &'static str,
pub enabled: bool,
/// Fixed width (design px); else from the text.
pub w: Option<f32>,
}
impl Ch {
pub fn new(id: impl Into<String>, text: impl Into<String>) -> Ch {
Ch { id: id.into(), text: text.into(), enabled: true, ..Ch::default() }
}
pub fn icon(mut self, icon: &str) -> Ch {
self.icon = icon.into();
self
}
pub fn active(mut self, on: bool) -> Ch {
self.active = on;
self
}
pub fn tone(mut self, tone: &'static str) -> Ch {
self.tone = tone;
self
}
pub fn enabled(mut self, on: bool) -> Ch {
self.enabled = on;
self
}
pub fn width(mut self, w: f32) -> Ch {
self.w = Some(w);
self
}
/// A text field: shows `value` (or the placeholder), opens the keyboard.
pub fn field(id: impl Into<String>, value: &str, placeholder: &str, icon: &str) -> Ch {
let text = if value.is_empty() { placeholder.to_string() } else { value.to_string() };
Ch { id: id.into(), text, icon: icon.into(), tone: "field", enabled: true, w: Some(900.0), ..Ch::default() }
}
fn width_of(&self) -> f32 {
if let Some(w) = self.w {
return w;
}
// Onest 23/600: about 13.4 px per character (measured on the TV
// screenshots); capitals and wide letters more, narrow ones less.
let chars: f32 = self
.text
.chars()
.map(|c| match c {
'i' | 'l' | 'í' | 'j' | '.' | ',' | ':' | '·' | '(' | ')' | ' ' => 7.5,
'm' | 'w' | 'M' | 'W' => 20.0,
c if c.is_uppercase() || c.is_ascii_digit() => 16.0,
_ => 13.4,
})
.sum::<f32>()
+ 6.0;
if self.text.is_empty() {
return 64.0;
}
let icon = if self.icon.is_empty() { 0.0 } else { 38.0 };
(chars + icon + if self.icon.is_empty() { 52.0 } else { 46.0 }).max(88.0)
}
fn height_of(&self) -> f32 {
if self.tone == "field" { 80.0 } else { 64.0 }
}
}
/// A card.
#[derive(Debug, Clone, Default)]
pub struct C {
pub id: String,
pub title: String,
pub caption: String,
pub detail: String,
pub image: String,
pub progress: f32,
pub badge: String,
pub badge_tone: &'static str,
pub mark: &'static str,
pub big: String,
pub current: bool,
/// Bottom-right label (a video's length).
pub corner: String,
/// A round picture (a channel).
pub round: bool,
}
impl C {
pub fn new(id: impl Into<String>, title: impl Into<String>, image: impl Into<String>) -> C {
C { id: id.into(), title: title.into(), image: image.into(), progress: -1.0, ..C::default() }
}
}
/// One line of a page, as screens describe it.
#[derive(Debug, Clone)]
pub struct L {
pub id: String,
pub kind: Kind,
pub title: String,
pub subtitle: String,
pub meta: String,
pub extra: String,
pub text: String,
pub note: String,
pub style: String,
pub tone: String,
pub icon: String,
pub image: String,
pub logo: String,
pub progress: f32,
pub captions: bool,
/// Grids keep the column when moving between their lines.
pub grid: bool,
pub cards: Vec<C>,
pub chips: Vec<Ch>,
pub checks: Vec<(i32, String, String)>,
/// Fixed height (design px).
pub h: Option<f32>,
pub indent: f32,
}
impl L {
pub fn new(id: impl Into<String>, kind: Kind) -> L {
L {
id: id.into(),
kind,
title: String::new(),
subtitle: String::new(),
meta: String::new(),
extra: String::new(),
text: String::new(),
note: String::new(),
style: String::new(),
tone: String::new(),
icon: String::new(),
image: String::new(),
logo: String::new(),
progress: -1.0,
captions: false,
grid: false,
cards: Vec::new(),
chips: Vec::new(),
checks: Vec::new(),
h: None,
indent: 0.0,
}
}
pub fn heading(id: impl Into<String>, title: impl Into<String>) -> L {
let mut l = L::new(id, Kind::Heading);
l.title = title.into();
l
}
/// A page title (56 px).
pub fn page_title(id: impl Into<String>, title: impl Into<String>, subtitle: impl Into<String>) -> L {
let mut l = L::heading(id, title);
l.style = "big".into();
l.subtitle = subtitle.into();
l
}
pub fn text(id: impl Into<String>, text: impl Into<String>, style: &str) -> L {
let mut l = L::new(id, Kind::Text);
l.text = text.into();
l.style = style.into();
l
}
pub fn notice(id: impl Into<String>, tone: &str, title: impl Into<String>, text: impl Into<String>) -> L {
let mut l = L::new(id, Kind::Notice);
l.tone = tone.into();
l.title = title.into();
l.text = text.into();
l
}
pub fn chips(id: impl Into<String>, label: impl Into<String>, chips: Vec<Ch>) -> L {
let mut l = L::new(id, Kind::Chips);
l.title = label.into();
l.chips = chips;
l
}
pub fn cards(id: impl Into<String>, title: impl Into<String>, style: &str, cards: Vec<C>) -> L {
let mut l = L::new(id, Kind::Cards);
l.title = title.into();
l.style = style.into();
l.cards = cards;
l
}
pub fn item(id: impl Into<String>, title: impl Into<String>, meta: impl Into<String>, text: impl Into<String>, chips: Vec<Ch>) -> L {
let mut l = L::new(id, Kind::Item);
l.title = title.into();
l.meta = meta.into();
l.text = text.into();
l.chips = chips;
l
}
pub fn checks(id: impl Into<String>, checks: Vec<(i32, String, String)>) -> L {
let mut l = L::new(id, Kind::Checks);
l.checks = checks;
l
}
pub fn sub(mut self, s: impl Into<String>) -> L {
self.subtitle = s.into();
self
}
pub fn image(mut self, url: impl Into<String>) -> L {
self.image = url.into();
self.style = "image".into();
self
}
pub fn captions(mut self) -> L {
self.captions = true;
self
}
pub fn grid(mut self) -> L {
self.grid = true;
self
}
fn focusable(&self) -> bool {
match self.kind {
Kind::Chips | Kind::Item | Kind::Hero => self.chips.iter().any(|c| c.enabled) || (self.kind == Kind::Item && !self.chips.is_empty()),
Kind::Cards => !self.cards.is_empty(),
Kind::Keyboard => true,
_ => false,
}
}
fn len(&self) -> usize {
if self.kind == Kind::Cards { self.cards.len() } else { self.chips.len() }
}
}
/// Splits a list into grid lines of `n` cards.
pub fn grid_lines(id: &str, title: &str, style: &str, cards: Vec<C>, n: usize) -> Vec<L> {
let mut out = Vec::new();
let mut it = cards.into_iter().peekable();
let mut i = 0;
while it.peek().is_some() {
let chunk: Vec<C> = it.by_ref().take(n).collect();
out.push(L::cards(format!("{id}#{i}"), if i == 0 { title } else { "" }, style, chunk).captions().grid());
i += 1;
}
out
}
/// What a screen shows besides its lines.
#[derive(Debug, Clone, Default)]
pub struct Frame {
/// The top navigation with this section lit.
pub nav: Option<usize>,
/// Settings: (title, items, current).
pub side: Option<(String, Vec<String>, usize)>,
/// The embedded search keyboard's placeholder (its line has kind Keyboard).
pub keyboard: Option<String>,
}
pub struct Spec {
pub lines: Vec<L>,
pub frame: Frame,
}
/// Where the focus is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Focus {
Nav,
Side,
Line,
}
#[derive(Debug, Clone, Default)]
struct Laid {
y: f32,
h: f32,
x: f32,
w: f32,
/// Chips: (x, y, w, h, row).
chips: Vec<(f32, f32, f32, f32, usize)>,
}
/// The page on screen: its lines laid out, the focus, the Slint models.
pub struct View {
pub lines: Vec<L>,
laid: Vec<Laid>,
pub frame: Frame,
pub focus: Focus,
pub line: usize,
cols: HashMap<String, usize>,
pub side_focus: usize,
pub nav_index: usize,
pub scroll: f32,
total: f32,
model: Rc<VecModel<Line>>,
card_models: Vec<Option<Rc<VecModel<Card>>>>,
shown: HashSet<String>,
}
impl Default for View {
fn default() -> Self {
View {
lines: Vec::new(),
laid: Vec::new(),
frame: Frame::default(),
focus: Focus::Line,
line: 0,
cols: HashMap::new(),
side_focus: 0,
nav_index: 0,
scroll: 0.0,
total: 0.0,
model: Rc::new(VecModel::default()),
card_models: Vec::new(),
shown: HashSet::new(),
}
}
}
/// Lines' heights and positions on the grid.
fn layout(lines: &[L], side: bool) -> (Vec<Laid>, f32) {
let (x0, w) = if side { (0.0, SIDE_W) } else { (0.0, CONTENT_W) };
let mut y = if side { 184.0 } else { 150.0 };
let mut out = Vec::with_capacity(lines.len());
let est = |text: &str, char_w: f32, width: f32, line_h: f32| -> f32 {
if text.is_empty() {
return 0.0;
}
let per_line = (width / char_w).max(10.0);
let n: f32 = text.split('\n').map(|p| (p.chars().count() as f32 / per_line).ceil().max(1.0)).sum();
n * line_h
};
for (i, l) in lines.iter().enumerate() {
let lw = w - l.indent;
let mut chips = Vec::new();
let h = match l.kind {
Kind::Hero => {
for (ci, c) in l.chips.iter().enumerate() {
let cw = c.width_of();
let cx = chips.last().map(|p: &(f32, f32, f32, f32, usize)| p.0 + p.2 + 20.0).unwrap_or(0.0);
let _ = ci;
chips.push((cx, 520.0, cw, 72.0, 0));
}
l.h.unwrap_or(640.0)
}
Kind::Heading => {
if l.style == "big" { 96.0 + if l.subtitle.is_empty() { 0.0 } else { 34.0 } } else { 58.0 + if l.subtitle.is_empty() { 0.0 } else { 34.0 } }
}
Kind::Text => {
let (cw, lh) = match l.style.as_str() {
"caption" => (10.6, 30.0),
"label" => (11.8, 34.0),
_ => (12.6, 38.0),
};
est(&l.text, cw, lw, lh) + 4.0
}
Kind::Notice => 48.0 + est(&l.text, 11.2, lw - 56.0, 32.0),
Kind::Checks => ((l.checks.len() + 1) / 2) as f32 * 84.0,
Kind::Chips => {
let top = if l.title.is_empty() { 0.0 } else { 38.0 };
let (mut cx, mut row, mut ry) = (0.0f32, 0usize, top);
let mut row_h = 0.0f32;
for c in &l.chips {
let (cw, ch) = (c.width_of().min(lw), c.height_of());
if cx > 0.0 && cx + cw > lw {
cx = 0.0;
row += 1;
ry += row_h + 14.0;
row_h = 0.0;
}
chips.push((cx, ry, cw, ch, row));
cx += cw + 14.0;
row_h = row_h.max(ch);
}
ry + row_h
}
Kind::Cards => {
let ch = match l.style.as_str() {
"landscape" => 225.0,
"season" => 252.0,
_ => 294.0,
};
(if l.title.is_empty() { 0.0 } else { 56.0 }) + ch + if l.captions { 80.0 } else { 0.0 } + 10.0
}
Kind::Item => {
let tx = if l.style == "image" { 288.0 } else { 0.0 };
let mut ty = 6.0 + 36.0 + if l.meta.is_empty() { 0.0 } else { 32.0 };
if !l.text.is_empty() {
ty += est(&l.text, 10.0, (lw - tx).min(1100.0), 29.0).min(58.0) + 6.0;
}
let mut cx = tx;
for c in &l.chips {
let cw = c.width_of();
chips.push((cx, ty + 4.0, cw, 60.0, 0));
cx += cw + 12.0;
}
let mut h = ty + if l.chips.is_empty() { 8.0 } else { 74.0 };
if l.style == "image" {
h = h.max(162.0);
}
if l.progress >= 0.0 && l.style != "image" {
h += 14.0;
}
h
}
Kind::Keyboard => 540.0,
};
let h = l.h.unwrap_or(h);
out.push(Laid { y, h, x: x0 + l.indent, w: lw, chips });
let next = lines.get(i + 1).map(|n| n.kind);
let gap = match (l.kind, next) {
(Kind::Heading, _) => 14.0,
(Kind::Cards, Some(Kind::Cards)) if l.grid => 18.0,
(Kind::Item, Some(Kind::Item)) => 14.0,
(Kind::Hero, _) => 24.0,
(_, Some(Kind::Heading)) => 44.0,
_ => 28.0,
};
y += h + gap;
}
(out, y)
}
impl View {
pub fn model(&self) -> ModelRc<Line> {
ModelRc::from(self.model.clone())
}
/// Shows new lines, keeping the focus on the same line (by id) and item.
pub fn set(&mut self, spec: Spec, images: &sf_ui::images::Images, px: f32) {
let old_id = self.lines.get(self.line).map(|l| l.id.clone());
if let Some(l) = self.lines.get(self.line) {
let c = self.col();
self.cols.insert(l.id.clone(), c);
}
let side = spec.frame.side.is_some();
self.lines = spec.lines;
self.frame = spec.frame;
let (laid, total) = layout(&self.lines, side);
self.laid = laid;
self.total = total;
self.line = match old_id.and_then(|id| self.lines.iter().position(|l| l.id == id)) {
Some(i) => i,
None => self.first_focusable().unwrap_or(0),
};
if !self.lines.get(self.line).is_some_and(L::focusable) {
self.line = self.nearest_focusable(self.line).unwrap_or(0);
}
if let Some((_, items, cur)) = &self.frame.side {
if self.focus != Focus::Side {
self.side_focus = *cur;
}
self.side_focus = self.side_focus.min(items.len().saturating_sub(1));
}
if self.focus == Focus::Nav && self.frame.nav.is_none() {
self.focus = Focus::Line;
}
if self.focus == Focus::Line && self.first_focusable().is_none() {
if self.frame.nav.is_some() {
self.focus = Focus::Nav;
} else if self.frame.side.is_some() {
self.focus = Focus::Side;
}
}
self.shown.clear();
self.card_models = vec![None; self.lines.len()];
let rows: Vec<Line> = (0..self.lines.len()).map(|i| self.slint_line(i, images, px)).collect();
self.model.set_vec(rows);
self.clamp_scroll();
}
/// Line `i`'s top (design px).
pub fn line_y(&self, i: usize) -> f32 {
self.laid.get(i).map(|l| l.y).unwrap_or(0.0)
}
pub fn has_lines(&self) -> bool {
!self.lines.is_empty()
}
fn first_focusable(&self) -> Option<usize> {
self.lines.iter().position(L::focusable)
}
fn nearest_focusable(&self, from: usize) -> Option<usize> {
(from..self.lines.len()).find(|&i| self.lines[i].focusable()).or_else(|| (0..from).rev().find(|&i| self.lines[i].focusable()))
}
pub fn col(&self) -> usize {
let Some(l) = self.lines.get(self.line) else { return 0 };
let c = self.cols.get(&l.id).copied().unwrap_or(0);
c.min(l.len().saturating_sub(1))
}
fn set_col(&mut self, c: usize) {
if let Some(l) = self.lines.get(self.line) {
self.cols.insert(l.id.clone(), c);
}
}
/// Sets the focus on line `id` (and item index), if it exists.
pub fn focus_on(&mut self, id: &str, col: usize) {
if let Some(i) = self.lines.iter().position(|l| l.id == id) {
self.line = i;
self.focus = Focus::Line;
self.set_col(col);
self.clamp_scroll();
}
}
/// The focused line's id and item id ("" if none).
pub fn target(&self) -> (String, String) {
let Some(l) = self.lines.get(self.line) else { return (String::new(), String::new()) };
let c = self.col();
let item = match l.kind {
Kind::Cards => l.cards.get(c).map(|c| c.id.clone()),
_ => l.chips.get(c).map(|c| c.id.clone()),
};
(l.id.clone(), item.unwrap_or_default())
}
/// Center x of the focused element (for spatial up/down).
fn focus_x(&self) -> f32 {
let Some(l) = self.lines.get(self.line) else { return 0.0 };
let c = self.col();
match l.kind {
Kind::Cards => {
let step = card_step(&l.style);
let fit = ((CONTENT_W + 32.0) / step).floor() as usize;
let scroll = c.saturating_sub(1).min(l.cards.len().saturating_sub(fit));
(c - scroll) as f32 * step + step / 2.0
}
_ => self.laid[self.line].chips.get(c).map(|p| p.0 + p.2 / 2.0).unwrap_or(0.0),
}
}
fn nearest_in(&self, li: usize, x: f32, row: Option<usize>) -> usize {
let l = &self.lines[li];
match l.kind {
Kind::Cards => {
let step = card_step(&l.style);
((x / step).floor() as usize).min(l.cards.len().saturating_sub(1))
}
_ => {
let chips = &self.laid[li].chips;
let mut best = (f32::MAX, 0usize);
for (i, p) in chips.iter().enumerate() {
if let Some(r) = row {
if p.4 != r {
continue;
}
}
if !l.chips[i].enabled {
continue;
}
let d = (p.0 + p.2 / 2.0 - x).abs();
if d < best.0 {
best = (d, i);
}
}
best.1
}
}
}
/// Up/down. Returns false at the edges (the caller may move to the nav).
pub fn vertical(&mut self, down: bool) -> bool {
let Some(l) = self.lines.get(self.line) else { return false };
let x = self.focus_x();
// Inside a wrapped chip line first.
if l.kind == Kind::Chips {
let row = self.laid[self.line].chips.get(self.col()).map(|p| p.4).unwrap_or(0);
let rows = self.laid[self.line].chips.iter().map(|p| p.4).max().unwrap_or(0);
let next = if down { (row < rows).then_some(row + 1) } else { row.checked_sub(1) };
if let Some(r) = next {
let c = self.nearest_in(self.line, x, Some(r));
self.set_col(c);
self.clamp_scroll();
return true;
}
}
let grid_col = if l.grid { Some(self.col()) } else { None };
let mut i = self.line as isize;
loop {
i += if down { 1 } else { -1 };
if i < 0 || i as usize >= self.lines.len() {
return false;
}
if self.lines[i as usize].focusable() {
break;
}
}
let prev = self.line;
self.line = i as usize;
let nl = &self.lines[self.line];
match nl.kind {
Kind::Cards if nl.grid && grid_col.is_some() => self.set_col(grid_col.unwrap().min(nl.cards.len().saturating_sub(1))),
Kind::Cards => {}
Kind::Chips | Kind::Item | Kind::Hero => {
let rows = self.laid[self.line].chips.iter().map(|p| p.4).max().unwrap_or(0);
let row = if down { 0 } else { rows };
let c = self.nearest_in(self.line, x, Some(row));
self.set_col(c);
}
_ => {}
}
let _ = prev;
self.clamp_scroll();
true
}
/// Left/right inside the line. Returns false at the edges.
pub fn horizontal(&mut self, right: bool) -> bool {
let Some(l) = self.lines.get(self.line) else { return false };
let n = l.len();
let c = self.col();
let mut next = c as isize;
loop {
next += if right { 1 } else { -1 };
if next < 0 || next as usize >= n {
return false;
}
let ok = match l.kind {
Kind::Cards => true,
_ => l.chips[next as usize].enabled,
};
if ok {
break;
}
}
self.set_col(next as usize);
true
}
/// Scrolls so the focused line sits comfortably on screen.
pub fn clamp_scroll(&mut self) {
let Some(laid) = self.laid.get(self.line) else {
self.scroll = 0.0;
return;
};
let top_margin = if self.frame.side.is_some() { 184.0 } else { 150.0 };
let mut target = if self.line == 0 || laid.y - top_margin < 120.0 {
0.0
} else {
laid.y - 230.0
};
// Tall lines (the keyboard) and wrapped chip rows: keep the focused row visible.
if let Some(l) = self.lines.get(self.line) {
if l.kind == Kind::Chips {
if let Some(p) = laid.chips.get(self.col()) {
if laid.y + p.1 + p.3 - target > 1000.0 {
target = laid.y + p.1 + p.3 - 1000.0;
}
}
}
}
let max = (self.total - 1000.0).max(0.0);
self.scroll = target.clamp(0.0, max.max(0.0)).max(0.0);
if self.focus == Focus::Nav {
self.scroll = 0.0;
}
}
/// Slint's struct for line `i`.
fn slint_line(&mut self, i: usize, images: &sf_ui::images::Images, px: f32) -> Line {
let l = &self.lines[i];
let laid = &self.laid[i];
let chips: Vec<Chip> = l
.chips
.iter()
.zip(laid.chips.iter())
.map(|(c, p)| Chip {
id: c.id.clone().into(),
text: c.text.clone().into(),
icon: c.icon.clone().into(),
x: p.0,
y: p.1,
w: p.2,
h: p.3,
active: c.active,
tone: c.tone.into(),
enabled: c.enabled,
})
.collect();
let (cw, ch) = card_size(&l.style);
let size = ((cw * px * 1.1) as u32, (ch * px * 1.1) as u32);
let cards: Vec<Card> = l
.cards
.iter()
.map(|c| Card {
id: c.id.clone().into(),
title: c.title.clone().into(),
caption: c.caption.clone().into(),
detail: c.detail.clone().into(),
image: images.cached(&c.image, size).unwrap_or_default(),
progress: c.progress,
badge: c.badge.clone().into(),
badge_tone: c.badge_tone.into(),
mark: c.mark.into(),
big: c.big.clone().into(),
current: c.current,
corner: c.corner.clone().into(),
round: c.round,
})
.collect();
let card_model = Rc::new(VecModel::from(cards));
let checks: Vec<Check> = l.checks.iter().map(|(s, a, b)| Check { state: *s, label: a.clone().into(), detail: b.clone().into() }).collect();
let logo_size = ((620.0 * px) as u32, (190.0 * px) as u32);
let item_size = ((256.0 * px * 1.1) as u32, (144.0 * px * 1.1) as u32);
let line = Line {
id: l.id.clone().into(),
kind: l.kind.name().into(),
y: laid.y,
h: laid.h,
x: laid.x,
w: laid.w,
title: l.title.clone().into(),
subtitle: l.subtitle.clone().into(),
meta: l.meta.clone().into(),
extra: l.extra.clone().into(),
text: l.text.clone().into(),
note: l.note.clone().into(),
style: l.style.clone().into(),
tone: l.tone.clone().into(),
icon: l.icon.clone().into(),
image: if l.image.is_empty() { Default::default() } else { images.cached(&l.image, item_size).unwrap_or_default() },
logo: if l.logo.is_empty() { Default::default() } else { images.cached(&l.logo, logo_size).unwrap_or_default() },
progress: l.progress,
col: self.cols.get(&l.id).copied().unwrap_or(0).min(l.len().saturating_sub(1)) as i32,
captions: l.captions,
cards: ModelRc::from(card_model.clone()),
chips: ModelRc::new(VecModel::from(chips)),
checks: ModelRc::new(VecModel::from(checks)),
};
self.card_models[i] = Some(card_model);
line
}
/// Sends the focus (column, line, scroll) to Slint's models.
pub fn sync_cols(&self) {
for (i, l) in self.lines.iter().enumerate() {
let want = self.cols.get(&l.id).copied().unwrap_or(0).min(l.len().saturating_sub(1)) as i32;
if let Some(mut row) = self.model.row_data(i) {
if row.col != want {
row.col = want;
self.model.set_row_data(i, row);
}
}
}
}
/// Loads the pictures of the lines around the focus (cached ones were
/// set when building).
pub fn load_images(&mut self, images: &sf_ui::images::Images, px: f32) {
let view_top = self.scroll - 400.0;
let view_bottom = self.scroll + 1080.0 + 900.0;
for i in 0..self.lines.len() {
let laid = &self.laid[i];
if laid.y + laid.h < view_top || laid.y > view_bottom {
continue;
}
let l = &self.lines[i];
if !l.logo.is_empty() && self.shown.insert(format!("{}#logo", l.id)) {
let model = self.model.clone();
let id = l.id.clone();
images.load(&l.logo, ((620.0 * px) as u32, (190.0 * px) as u32), move |img| {
if let Some(idx) = (0..model.row_count()).find(|&k| model.row_data(k).is_some_and(|r| r.id == id)) {
let mut row = model.row_data(idx).unwrap();
row.logo = img;
model.set_row_data(idx, row);
}
});
}
if !l.image.is_empty() && self.shown.insert(format!("{}#image", l.id)) {
let model = self.model.clone();
let id = l.id.clone();
images.load(&l.image, ((256.0 * px * 1.1) as u32, (144.0 * px * 1.1) as u32), move |img| {
if let Some(idx) = (0..model.row_count()).find(|&k| model.row_data(k).is_some_and(|r| r.id == id)) {
let mut row = model.row_data(idx).unwrap();
row.image = img;
model.set_row_data(idx, row);
}
});
}
if l.kind != Kind::Cards || l.cards.is_empty() {
continue;
}
let col = self.cols.get(&l.id).copied().unwrap_or(0);
let step = card_step(&l.style);
let fit = ((CONTENT_W + 32.0) / step).floor() as usize;
let start = col.saturating_sub(2);
let end = (col + fit + 3).min(l.cards.len());
let (cw, ch) = card_size(&l.style);
let size = ((cw * px * 1.1) as u32, (ch * px * 1.1) as u32);
let Some(Some(model)) = self.card_models.get(i).cloned() else { continue };
for ci in start..end {
let c = &l.cards[ci];
if c.image.is_empty() || !self.shown.insert(format!("{}#{}", l.id, c.id)) {
continue;
}
let model = model.clone();
let card_id = c.id.clone();
images.load(&c.image, size, move |img| {
if let Some(mut row) = model.row_data(ci) {
if row.id == card_id && row.image.size().width == 0 {
row.image = img;
model.set_row_data(ci, row);
}
}
});
}
}
}
/// Lines whose end is near the focus (infinite lists ask for more).
pub fn near_end(&self) -> Option<String> {
let l = self.lines.get(self.line)?;
if l.grid {
// The last grid line of this list is close.
let prefix = l.id.split('#').next().unwrap_or("");
let last = self.lines.iter().rposition(|x| x.id.starts_with(&format!("{prefix}#")))?;
if last <= self.line + 2 {
return Some(prefix.to_string());
}
} else if l.kind == Kind::Cards && self.col() + 6 >= l.cards.len() {
return Some(l.id.clone());
}
None
}
}
pub fn card_size(style: &str) -> (f32, f32) {
match style {
"landscape" => (400.0, 225.0),
"season" => (168.0, 252.0),
_ => (196.0, 294.0),
}
}
fn card_step(style: &str) -> f32 {
card_size(style).0 + 32.0
}
/// Cards per grid line: posters, and landscape thumbnails (400 px + gap).
#[allow(dead_code)]
pub const GRID: usize = 8;
pub const GRID_YT: usize = 4;
#[cfg(test)]
mod tests {
use super::*;
fn chips_line(n: usize) -> L {
L::chips("c", "Műfaj", (0..n).map(|i| Ch::new(format!("g{i}"), format!("Műfaj {i}"))).collect())
}
#[test]
fn wraps_chips_and_moves_by_rows() {
let lines = vec![chips_line(40), L::cards("r", "Sor", "poster", (0..20).map(|i| C::new(format!("{i}"), "x", "")).collect())];
let (laid, _) = layout(&lines, false);
let rows = laid[0].chips.iter().map(|p| p.4).max().unwrap();
assert!(rows >= 2, "40 chips wrap");
assert!(laid[0].chips.iter().all(|p| p.0 + p.2 <= CONTENT_W + 0.1));
let mut v = View { lines: lines.clone(), laid, ..View::default() };
v.total = 2000.0;
assert!(v.vertical(true));
assert_eq!(v.line, 0, "first down stays in the chip line (next row)");
let row = v.laid[0].chips[v.col()].4;
assert_eq!(row, 1);
for _ in 0..rows {
v.vertical(true);
}
assert_eq!(v.line, 1, "then the cards");
assert!(!v.vertical(true), "nothing below");
}
#[test]
fn grids_keep_the_column() {
let cards: Vec<C> = (0..20).map(|i| C::new(format!("{i}"), "x", "")).collect();
let lines = grid_lines("g", "Rács", "poster", cards, 8);
assert_eq!(lines.len(), 3);
let (laid, total) = layout(&lines, false);
let mut v = View { lines, laid, total, ..View::default() };
v.set_col(5);
v.vertical(true);
assert_eq!((v.line, v.col()), (1, 5));
v.vertical(true);
assert_eq!((v.line, v.col()), (2, 3), "clamped to the short last line");
assert_eq!(v.near_end().as_deref(), Some("g"));
}
#[test]
fn skips_disabled_chips() {
let line = L::chips("c", "", vec![Ch::new("a", "A"), Ch::new("b", "B").enabled(false), Ch::new("c", "C")]);
let (laid, total) = layout(std::slice::from_ref(&line), false);
let mut v = View { lines: vec![line], laid, total, ..View::default() };
assert!(v.horizontal(true));
assert_eq!(v.target().1, "c");
assert!(!v.horizontal(true));
}
}

868
src/player.rs Normal file
View File

@@ -0,0 +1,868 @@
//! Playback: video id -> formats (yt::stream) -> a DASH manifest ->
//! sf_ui::video::Player (GStreamer, hardware decoding). No ads: YouTube's
//! ad breaks are never requested or played.
//!
//! The video is the glass backdrop, so the controls are glass over it.
//! Captions are drawn by Slint from YouTube's timed text (json3).
//!
//! Remote, controls hidden: OK = play/pause, left/right = seek (held:
//! faster), up = captions and quality, down = buttons, Back = leave.
//! Controls shown: the seek bar (left/right seeks) or the button row
//! (play, -10, +10, next, channel, captions and quality); Back hides them.
//! At the end: the next video (the queue, or YouTube's "up next") with a
//! countdown when autoplay is on.
use std::collections::HashSet;
use std::time::{Duration, Instant};
use slint::{ModelRc, VecModel};
use crate::app::{Action, Controller};
use crate::config::Watched;
use crate::yt::extras::{self, Cue, Segment};
use crate::yt::stream::{self, Codec, Playable};
use crate::yt::{self, Video};
use crate::{MenuItem, format, screens, task};
/// Videos kept after the one playing (a list, a row of cards).
pub const QUEUE_MAX: usize = 50;
#[derive(Debug, Clone)]
pub struct Request {
pub video: Video,
/// Plays after this one, in order.
pub queue: Vec<Video>,
/// A mix (RD…): up next comes from it.
pub mix: Option<String>,
/// Start here; None: where this TV stopped last time.
pub resume: Option<f64>,
/// Picked in the player (height, 0 = automatic); None: the setting.
pub quality: Option<u64>,
}
impl Request {
pub fn new(video: Video, queue: Vec<Video>) -> Request {
Request { video, queue, mix: None, resume: None, quality: None }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stage {
Prep,
Play,
Error,
}
/// Everything the prep task finds out.
struct Prepared {
playable: Playable,
uri: String,
height: u64,
/// One quality picked (else adaptive).
fixed: bool,
resume: f64,
segments: Vec<Segment>,
/// Up next when the queue is empty (YouTube's suggestion / the mix).
related: Vec<Video>,
/// Captions on start: (menu index, cues).
captions: Option<(usize, Vec<Cue>)>,
}
/// A captions menu entry: one of the video's tracks.
#[derive(Debug, Clone)]
struct CaptionChoice {
label: String,
track: usize,
lang: String,
auto: bool,
}
const OSD: Duration = Duration::from_secs(5);
const SAVE_EVERY: Duration = Duration::from_secs(10);
const NEXT_COUNTDOWN: u64 = 8;
#[cfg(target_os = "linux")]
type Gst = sf_ui::video::Player;
/// No player off Linux (UI work on Windows): playback stops at an error.
#[cfg(not(target_os = "linux"))]
struct Gst;
#[cfg(not(target_os = "linux"))]
impl Gst {
fn toggle(&mut self) -> bool {
false
}
fn seek(&mut self, _: f64, _: bool) {}
}
pub struct Player {
req: Request,
generation: u64,
stage: Stage,
prep: Option<Prepared>,
video: Option<Gst>,
timer: slint::Timer,
osd_until: Instant,
/// 0 = seek bar, 1 = buttons.
area: i32,
button: i32,
seek_target: Option<f64>,
seek_commit: Instant,
/// 0 = closed, 1 = captions, 2 = quality.
panel: i32,
focus: [usize; 2],
position: f64,
duration: Option<f64>,
last_save: Instant,
ended: bool,
countdown_until: Option<Instant>,
choices: Vec<CaptionChoice>,
/// The captions menu's checked entry (0 = off).
caption_on: usize,
cues: Vec<Cue>,
skipped: HashSet<i64>,
}
static GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
fn codec(c: &Controller) -> Codec {
Codec::from_key(&c.state.borrow().settings.codec)
}
/// Starts playing `req` (replacing whatever plays).
pub fn play(c: &Controller, req: Request) {
stop(c, true);
let generation = GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let now = Instant::now();
let (settings, saved) = {
let st = c.state.borrow();
(st.settings.clone(), st.library.find(&req.video.id).map(|w| w.resume_at()))
};
c.state.borrow_mut().player = Some(Player {
req: req.clone(),
generation,
stage: Stage::Prep,
prep: None,
video: None,
timer: slint::Timer::default(),
osd_until: now,
area: 0,
button: 0,
seek_target: None,
seek_commit: now,
panel: 0,
focus: [0; 2],
position: 0.0,
duration: None,
last_save: now,
ended: false,
countdown_until: None,
choices: Vec::new(),
caption_on: 0,
cues: Vec::new(),
skipped: HashSet::new(),
});
if let Some(ui) = c.ui() {
ui.set_player_stage("prep".into());
ui.set_player_title(req.video.title.clone().into());
ui.set_player_heading(req.video.channel.clone().into());
ui.set_player_info("".into());
ui.set_player_caption("".into());
ui.set_player_next_label("".into());
ui.set_player_skip_label("".into());
ui.set_player_panel(0);
ui.set_player_osd(false);
}
c.show("player");
if !req.video.thumb.is_empty() {
c.backdrop(&req.video.thumb, crate::app::Look::Sharp, &format!("player:{}", req.video.id));
}
let client = c.client();
let id = req.video.id.clone();
let mix = req.mix.clone();
let want_related = req.queue.is_empty();
let resume = req.resume.or(saved).unwrap_or(0.0);
let quality = req.quality.unwrap_or(settings.quality);
let fixed = quality != 0;
let codec = Codec::from_key(&settings.codec);
let sponsor = settings.sponsorblock;
let captions = settings.captions.clone();
let signed_in = client.signed_in();
task::spawn(
move || -> anyhow::Result<Prepared> {
let playable = stream::fetch(&client, &id)?;
let (uri, height) = playable.uri(quality, codec)?;
let segments = if sponsor && !playable.details.live { extras::sponsor_segments(&client, &id).unwrap_or_default() } else { Vec::new() };
let related: Vec<Video> = if want_related || mix.is_some() {
client.related(&id, mix.as_deref()).map(|f| f.videos().filter(|v| !v.live && !v.short).take(QUEUE_MAX).cloned().collect()).unwrap_or_default()
} else {
Vec::new()
};
let choices = caption_choices(&playable);
let captions = pick_captions(&choices, &captions).and_then(|i| {
let ch = &choices[i];
extras::captions(&client, &playable.captions[ch.track]).ok().map(|cues| (i + 1, cues))
});
if signed_in {
let (client, id) = (client.clone(), id.clone());
task::background("history", move || extras::mark_watched(&client, &id));
}
Ok(Prepared { playable, uri, height, fixed, resume, segments, related, captions })
},
{
let c = c.clone();
move |r| {
if c.state.borrow().player.as_ref().map(|p| p.generation) != Some(generation) {
return;
}
match r {
Ok(prep) => start(&c, prep),
Err(e) => {
log::warn!("play: {e:#}");
fail(&c, &yt::describe(&e));
}
}
}
},
);
}
fn caption_choices(p: &Playable) -> Vec<CaptionChoice> {
p.captions
.iter()
.enumerate()
.map(|(i, t)| CaptionChoice {
label: if t.auto && !t.name.contains('(') { format!("{} (automatikus)", t.name) } else { t.name.clone() },
track: i,
lang: t.lang.clone(),
auto: t.auto,
})
.collect()
}
/// The captions to show on start for the setting ("", "hu", "en"): a
/// manual track in that language, else an automatic one. (YouTube's machine
/// translation needs a PO token since 2026, so it isn't offered.)
fn pick_captions(choices: &[CaptionChoice], lang: &str) -> Option<usize> {
if lang.is_empty() {
return None;
}
let of = |c: &CaptionChoice| c.lang.starts_with(lang);
choices.iter().position(|c| of(c) && !c.auto).or_else(|| choices.iter().position(of))
}
fn fail(c: &Controller, text: &str) {
if let Some(p) = c.state.borrow_mut().player.as_mut() {
p.stage = Stage::Error;
p.timer.stop();
p.video = None;
}
c.glass.set_video(None);
if let Some(ui) = c.ui() {
ui.set_player_stage("error".into());
ui.set_player_error_text(text.into());
}
}
fn start(c: &Controller, prep: Prepared) {
let d = prep.playable.details.clone();
if let Some(ui) = c.ui() {
ui.set_player_title(d.title.clone().into());
ui.set_player_heading(d.channel.clone().into());
}
let generation = {
let mut st = c.state.borrow_mut();
let Some(p) = st.player.as_mut() else { return };
p.position = if d.live { 0.0 } else { prep.resume };
p.duration = (d.length > 0.0).then_some(d.length);
p.choices = caption_choices(&prep.playable);
if let Some((i, cues)) = &prep.captions {
p.caption_on = *i;
p.cues = cues.clone();
}
// Fill in what the card didn't know (for the history).
if p.req.video.title.is_empty() {
p.req.video.title = d.title.clone();
}
if p.req.video.channel.is_empty() {
p.req.video.channel = d.channel.clone();
}
if p.req.video.channel_id.is_empty() {
p.req.video.channel_id = d.channel_id.clone();
}
if p.req.video.thumb.is_empty() {
p.req.video.thumb = yt::parse::video_thumb(&d.id);
}
p.prep = Some(prep);
p.generation
};
remember(c, None);
open_video(c, generation);
}
#[cfg(not(target_os = "linux"))]
fn open_video(c: &Controller, _generation: u64) {
let uri = c.state.borrow().player.as_ref().and_then(|p| p.prep.as_ref()).map(|p| p.uri.clone()).unwrap_or_default();
log::info!("would play {uri}");
fail(c, "Ezen a gépen nincs lejátszó: a videó a TV-n (Linux, GStreamer) játszik.");
}
#[cfg(target_os = "linux")]
fn open_video(c: &Controller, generation: u64) {
let (uri, opts) = {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
let Some(prep) = p.prep.as_ref() else { return };
let opts = sf_ui::video::PlayerOptions { start: p.position, subtitles: false, user_agent: Some(prep.playable.user_agent.into()), ..Default::default() };
(prep.uri.clone(), opts)
};
match Gst::new(&uri, opts) {
Ok(v) => {
c.clear_backdrop();
c.glass.set_video(Some(v.video()));
{
let mut st = c.state.borrow_mut();
let Some(p) = st.player.as_mut() else { return };
let now = Instant::now();
p.video = Some(v);
p.stage = Stage::Play;
p.osd_until = now + OSD;
p.last_save = now;
let k = c.clone();
p.timer.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || tick(&k, generation));
}
if let Some(ui) = c.ui() {
ui.set_player_stage("play".into());
ui.set_player_buffering(true);
ui.set_player_osd(true);
}
menus(c);
}
Err(e) => fail(c, &format!("A lejátszó nem indult: {e:#}")),
}
}
fn osd_visible(p: &Player, now: Instant) -> bool {
#[cfg(target_os = "linux")]
let paused = p.video.as_ref().is_some_and(|v| !v.is_playing() && v.is_ready());
#[cfg(not(target_os = "linux"))]
let paused = false;
p.panel > 0 || p.area == 1 || paused || now < p.osd_until
}
/// The SponsorBlock segment at the position, not skipped yet.
fn segment_now(p: &Player) -> Option<&Segment> {
let pos = p.position;
p.prep.as_ref()?.segments.iter().find(|s| pos >= s.start && pos < s.end - 1.0 && !p.skipped.contains(&(s.start as i64)))
}
#[cfg(target_os = "linux")]
fn tick(c: &Controller, generation: u64) {
use sf_ui::video::Event;
enum End {
No,
Finished,
Failed(String),
}
let mut end = End::No;
let mut save = false;
let mut go_next = false;
let mut skipped: Option<String> = None;
{
let mut st = c.state.borrow_mut();
let Some(p) = st.player.as_mut().filter(|p| p.generation == generation) else { return };
let Some(v) = p.video.as_mut() else { return };
for ev in v.poll() {
match ev {
Event::Ready { duration } => {
if duration.is_some() {
p.duration = duration;
}
}
Event::Buffering(_) | Event::Playing(_) | Event::Seeked => {}
Event::Eos => end = End::Finished,
Event::Error(e) => end = End::Failed(e),
}
}
let now = Instant::now();
if let Some(t) = p.seek_target {
if now >= p.seek_commit {
v.seek(t, false);
p.seek_target = None;
p.position = t;
}
} else if let Some(pos) = v.position() {
p.position = pos;
}
if let Some(d) = v.duration() {
p.duration = Some(d);
}
let playing = v.is_playing();
let ready = v.is_ready();
let buffering_now = v.is_buffering();
if playing && now.duration_since(p.last_save) >= SAVE_EVERY {
p.last_save = now;
save = true;
}
// SponsorBlock: jump over the segment once.
if p.seek_target.is_none() && playing {
if let Some(s) = segment_now(p).cloned() {
p.skipped.insert(s.start as i64);
if let Some(v) = p.video.as_mut() {
v.seek(s.end, false);
}
p.position = s.end;
skipped = Some(format!("{} átugorva", extras::segment_label(&s.category)));
}
}
if let Some(until) = p.countdown_until {
if now >= until {
p.countdown_until = None;
go_next = true;
}
}
if let Some(ui) = c.ui() {
let shown = p.seek_target.unwrap_or(p.position);
let dur = p.duration.unwrap_or(0.0);
let live = p.prep.as_ref().is_some_and(|x| x.playable.details.live);
ui.set_player_progress(if dur > 0.0 && !live { (shown / dur).clamp(0.0, 1.0) as f32 } else { 0.0 });
ui.set_player_time_text(if live { "ÉLŐ".into() } else { format::time(shown).into() });
ui.set_player_remaining_text(if dur > 0.0 && !live { format!("−{}", format::time((dur - shown).max(0.0))).into() } else { "".into() });
ui.set_player_seeking(p.seek_target.is_some());
if let Some(t) = p.seek_target {
let delta = t - p.position;
ui.set_player_seek_text(format::time(t).into());
ui.set_player_seek_delta(format!("{}{}", if delta < 0.0 { "−" } else { "+" }, format::time(delta.abs())).into());
ui.set_player_seek_back(delta < 0.0);
}
ui.set_player_buffering(buffering_now && !matches!(end, End::Failed(_)) && !p.ended);
ui.set_player_paused(!playing && ready);
let osd = osd_visible(p, now) && !p.ended;
ui.set_player_osd(osd);
ui.set_player_osd_area(p.area);
ui.set_player_osd_button(p.button);
ui.set_player_caption(if p.caption_on > 0 && !p.ended { extras::cue_at(&p.cues, shown).into() } else { "".into() });
let next = next_video(p).map(|v| v.title.clone());
match (p.ended, next) {
(true, Some(label)) => {
ui.set_player_next_label(label.into());
ui.set_player_next_text(match p.countdown_until {
Some(u) => format!("Indul {} mp múlva · OK: most", u.saturating_duration_since(now).as_secs() + 1).into(),
None => "OK: indítás · Vissza: kilépés".into(),
});
}
_ => ui.set_player_next_label("".into()),
}
}
}
if save {
remember(c, None);
}
if let Some(text) = skipped {
c.toast(&text, false);
}
if go_next {
return step(c);
}
match end {
End::No => {}
End::Finished => finished(c),
End::Failed(e) => fail(c, &format!("Lejátszási hiba: {e}")),
}
}
/// Up next: the queue, else YouTube's suggestion (or the mix).
fn next_video(p: &Player) -> Option<&Video> {
p.req.queue.first().or_else(|| p.prep.as_ref()?.related.iter().find(|v| v.id != p.req.video.id))
}
fn info_text(p: &Player) -> String {
let mut info: Vec<String> = Vec::new();
if let Some(prep) = &p.prep {
if prep.playable.details.live {
info.push("Élő adás".into());
} else if prep.height > 0 {
let auto = !prep.fixed;
info.push(format!("{}{}", format::quality(prep.height), if auto { " (automatikus)" } else { "" }));
}
if !prep.playable.details.views.is_empty() {
info.push(format::views(&prep.playable.details.views));
}
if !prep.segments.is_empty() {
info.push(format!("SponsorBlock: {} rész", prep.segments.len()));
}
}
if p.caption_on > 0 {
if let Some(ch) = p.choices.get(p.caption_on - 1) {
info.push(format!("Felirat: {}", ch.label));
}
}
info.join(" · ")
}
fn qualities(c: &Controller, p: &Player) -> Vec<u64> {
let mut q = vec![0];
if let Some(prep) = &p.prep {
q.extend(prep.playable.heights(codec(c)));
}
q
}
fn menus(c: &Controller) {
let Some(ui) = c.ui() else { return };
let quals = {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
qualities(c, p)
};
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
let mut caps = vec![MenuItem { text: "Kikapcsolva".into(), detail: "".into(), checked: p.caption_on == 0 }];
caps.extend(p.choices.iter().enumerate().map(|(i, ch)| MenuItem { text: ch.label.clone().into(), detail: "".into(), checked: p.caption_on == i + 1 }));
let current = p.req.quality.unwrap_or(st.settings.quality);
let qual: Vec<MenuItem> = quals
.iter()
.map(|h| MenuItem {
text: if *h == 0 { "Automatikus".into() } else { format::quality(*h).into() },
detail: "".into(),
checked: *h == current,
})
.collect();
ui.set_player_subs(ModelRc::new(VecModel::from(caps)));
ui.set_player_quality(ModelRc::new(VecModel::from(qual)));
ui.set_player_panel(p.panel);
ui.set_player_subs_focus(p.focus[0] as i32);
ui.set_player_quality_focus(p.focus[1] as i32);
ui.set_player_has_next(next_video(p).is_some());
ui.set_player_has_channel(!p.req.video.channel_id.is_empty() || p.prep.as_ref().is_some_and(|x| !x.playable.details.channel_id.is_empty()));
ui.set_player_info(info_text(p).into());
}
/// Remembers the position on this TV; `at`: instead of the current one.
fn remember(c: &Controller, at: Option<f64>) {
let w = {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
let Some(prep) = p.prep.as_ref() else { return };
if prep.playable.details.live {
return;
}
let v = &p.req.video;
Watched {
id: v.id.clone(),
title: v.title.clone(),
channel: v.channel.clone(),
channel_id: v.channel_id.clone(),
thumb: v.thumb.clone(),
position: at.unwrap_or(p.seek_target.unwrap_or(p.position)),
duration: p.duration.unwrap_or(0.0),
at: yt::now(),
}
};
c.update_library(|l| l.watched(w));
}
/// The end of the video: up next (with a countdown), or back.
fn finished(c: &Controller) {
let (has_next, auto) = {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
(next_video(p).is_some(), st.settings.autoplay)
};
let duration = c.state.borrow().player.as_ref().and_then(|p| p.duration);
if let Some(d) = duration {
remember(c, Some(d));
}
if !has_next {
return leave(c);
}
if let Some(p) = c.state.borrow_mut().player.as_mut() {
p.ended = true;
p.panel = 0;
p.area = 0;
p.countdown_until = auto.then(|| Instant::now() + Duration::from_secs(NEXT_COUNTDOWN));
}
menus(c);
}
/// The next video.
fn step(c: &Controller) {
let req = {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
let Some(next) = next_video(p).cloned() else { return };
let queue: Vec<Video> = if p.req.queue.first().is_some_and(|q| q.id == next.id) { p.req.queue[1..].to_vec() } else { Vec::new() };
Request { video: next, queue, mix: p.req.mix.clone(), resume: None, quality: p.req.quality }
};
play(c, req);
}
/// Stops playback; `save`: remember the position.
pub fn stop(c: &Controller, save: bool) {
let playing = c.state.borrow().player.as_ref().is_some_and(|p| p.stage == Stage::Play && !p.ended);
if save && playing {
remember(c, None);
}
let old = c.state.borrow_mut().player.take();
if let Some(p) = old {
p.timer.stop();
drop(p);
c.glass.set_video(None);
}
}
fn leave(c: &Controller) {
stop(c, true);
c.show("page");
c.player_closed();
}
fn seek_by(p: &mut Player, delta: f64, now: Instant, wait: Duration) {
if p.prep.as_ref().is_some_and(|x| x.playable.details.live) {
return;
}
let base = p.seek_target.unwrap_or(p.position);
let max = p.duration.map(|d| (d - 2.0).max(0.0)).unwrap_or(f64::MAX);
p.seek_target = Some((base + delta).clamp(0.0, max));
p.seek_commit = now + wait;
// Seeking back into a skipped segment: the user wants to see it.
let target = p.seek_target.unwrap_or(0.0);
if let Some(prep) = &p.prep {
for s in &prep.segments {
if target >= s.start && target < s.end {
p.skipped.insert(s.start as i64);
}
}
}
}
/// Buttons in the row, in order (3 next and 4 channel only when they exist).
fn buttons(p: &Player) -> Vec<i32> {
let mut b = vec![0, 1, 2];
if next_video(p).is_some() {
b.push(3);
}
if !p.req.video.channel_id.is_empty() {
b.push(4);
}
b.push(5);
b
}
pub fn key(c: &Controller, a: Action, repeat: bool) {
let stage = c.state.borrow().player.as_ref().map(|p| p.stage);
match stage {
Some(Stage::Play) => {}
Some(_) => {
if a == Action::Back || a == Action::Ok {
leave(c);
}
return;
}
None => return,
}
enum Then {
Nothing,
Menus,
Leave,
Next,
Channel,
Captions(usize),
Quality(u64),
}
let quals = {
let st = c.state.borrow();
st.player.as_ref().map(|p| qualities(c, p)).unwrap_or_default()
};
let settings_quality = c.state.borrow().settings.quality;
let open_panel = |p: &mut Player| {
p.panel = 1;
let current = p.req.quality.unwrap_or(settings_quality);
p.focus = [p.caption_on, quals.iter().position(|h| *h == current).unwrap_or(0)];
};
let then = {
let mut st = c.state.borrow_mut();
let Some(p) = st.player.as_mut() else { return };
let now = Instant::now();
if p.ended {
match a {
Action::Ok | Action::PlayPause => Then::Next,
Action::Back if p.countdown_until.is_some() => {
p.countdown_until = None;
Then::Nothing
}
Action::Back => Then::Leave,
_ => Then::Nothing,
}
} else if p.panel > 0 {
p.osd_until = now + OSD;
let col = (p.panel - 1) as usize;
let len = if col == 0 { p.choices.len() + 1 } else { quals.len() };
match a {
Action::Up => {
p.focus[col] = p.focus[col].saturating_sub(1);
Then::Menus
}
Action::Down => {
p.focus[col] = (p.focus[col] + 1).min(len.saturating_sub(1));
Then::Menus
}
Action::Left => {
p.panel = 1;
Then::Menus
}
Action::Right => {
p.panel = 2;
Then::Menus
}
Action::Back => {
p.panel = 0;
Then::Menus
}
Action::Ok | Action::PlayPause => {
let i = p.focus[col];
if col == 0 {
Then::Captions(i)
} else {
let q = quals.get(i).copied().unwrap_or(0);
if q != p.req.quality.unwrap_or(settings_quality) { Then::Quality(q) } else { Then::Nothing }
}
}
}
} else {
let visible = osd_visible(p, now);
let timer_on = now < p.osd_until;
p.osd_until = now + OSD;
let row = buttons(p);
match a {
// OK presses the focused button; play/pause always plays or pauses.
Action::Ok if p.area == 1 && visible => match p.button {
0 => {
toggle(p);
Then::Nothing
}
1 | 2 => {
seek_by(p, if p.button == 1 { -10.0 } else { 10.0 }, now, Duration::from_millis(500));
Then::Nothing
}
3 => Then::Next,
4 => Then::Channel,
_ => {
open_panel(p);
Then::Menus
}
},
Action::Ok | Action::PlayPause => {
toggle(p);
Then::Nothing
}
Action::Left | Action::Right if p.area == 1 && visible => {
let i = row.iter().position(|b| *b == p.button).unwrap_or(0);
let j = if a == Action::Left { i.saturating_sub(1) } else { (i + 1).min(row.len() - 1) };
p.button = row[j];
Then::Nothing
}
Action::Left | Action::Right => {
let step = if repeat { 30.0 } else { 10.0 };
seek_by(p, if a == Action::Left { -step } else { step }, now, Duration::from_millis(if repeat { 900 } else { 700 }));
Then::Nothing
}
Action::Up if p.area == 1 => {
p.area = 0;
Then::Nothing
}
Action::Up if visible => {
open_panel(p);
Then::Menus
}
Action::Up => Then::Nothing,
Action::Down => {
if visible && p.area == 0 {
p.area = 1;
if !row.contains(&p.button) {
p.button = 0;
}
}
Then::Nothing
}
Action::Back => {
if p.seek_target.is_some() {
p.seek_target = None;
Then::Nothing
} else if visible && (p.area == 1 || timer_on) {
p.area = 0;
p.osd_until = now;
Then::Nothing
} else {
Then::Leave
}
}
}
}
};
match then {
Then::Nothing => {}
Then::Menus => menus(c),
Then::Leave => leave(c),
Then::Next => step(c),
Then::Channel => {
let (id, title) = {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
(p.req.video.channel_id.clone(), p.req.video.channel.clone())
};
leave(c);
c.push_screen(Box::new(screens::channel::ChannelPage::new(&id, &title)));
}
Then::Captions(i) => set_captions(c, i),
Then::Quality(q) => {
let req = {
let st = c.state.borrow();
let Some(p) = st.player.as_ref() else { return };
let mut r = p.req.clone();
r.quality = Some(q);
r.resume = Some(p.seek_target.unwrap_or(p.position));
r
};
play(c, req);
}
}
}
/// Captions menu entry `i` (0 = off): loads the track.
fn set_captions(c: &Controller, i: usize) {
let job = {
let mut st = c.state.borrow_mut();
let Some(p) = st.player.as_mut() else { return };
p.caption_on = i;
p.cues.clear();
if i == 0 {
None
} else {
p.choices.get(i - 1).cloned().and_then(|ch| Some((p.generation, p.prep.as_ref()?.playable.captions.get(ch.track)?.clone())))
}
};
menus(c);
let Some((generation, track)) = job else { return };
let client = c.client();
let k = c.clone();
task::spawn(move || extras::captions(&client, &track), move |r| {
let mut st = k.state.borrow_mut();
let Some(p) = st.player.as_mut().filter(|p| p.generation == generation && p.caption_on == i) else { return };
match r {
Ok(cues) => p.cues = cues,
Err(e) => {
drop(st);
k.toast(&format!("A felirat nem töltődött be: {}", yt::describe(&e)), true);
}
}
});
}
fn toggle(p: &mut Player) {
if let Some(v) = p.video.as_mut() {
v.toggle();
}
}

21
src/qr.rs Normal file
View File

@@ -0,0 +1,21 @@
//! A QR code as a Slint picture (black on white, with the quiet zone).
use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
pub fn image(text: &str) -> Image {
let Ok(code) = qrcode::QrCode::new(text.as_bytes()) else { return Image::default() };
let n = code.width();
let colors = code.to_colors();
const SCALE: usize = 10;
const QUIET: usize = 3;
let side = (n + 2 * QUIET) * SCALE;
let mut buf = SharedPixelBuffer::<Rgba8Pixel>::new(side as u32, side as u32);
let px = buf.make_mut_slice();
for (i, p) in px.iter_mut().enumerate() {
let (x, y) = (i % side / SCALE, i / side / SCALE);
let dark = x >= QUIET && y >= QUIET && x < n + QUIET && y < n + QUIET && colors[(y - QUIET) * n + (x - QUIET)] == qrcode::Color::Dark;
let v = if dark { 0 } else { 255 };
*p = Rgba8Pixel { r: v, g: v, b: v, a: 255 };
}
Image::from_rgba8(buf)
}

121
src/screens/channel.rs Normal file
View File

@@ -0,0 +1,121 @@
//! A channel: its name, subscribers, Feliratkozás, and its videos (newest
//! first, more as the focus nears the end). Signed in, Feliratkozás follows
//! the channel with the account; signed out, on this TV.
use std::any::Any;
use crate::app::{Cx, Look, Screen};
use crate::config::Sub;
use crate::page::{Ch, Frame, L, Spec};
use crate::screens::{self, Paged};
pub struct ChannelPage {
id: String,
title: String,
feed: Paged,
/// Signed in: the account follows it (None: not known yet).
subscribed: Option<bool>,
asked: bool,
}
impl ChannelPage {
pub fn new(id: &str, title: &str) -> ChannelPage {
ChannelPage { id: id.into(), title: title.into(), feed: Paged::new("ch", false, false), subscribed: None, asked: false }
}
fn paged(s: &mut ChannelPage) -> &mut Paged {
&mut s.feed
}
fn following(&self, cx: &Cx) -> bool {
if cx.signed_in() { self.subscribed.unwrap_or(false) } else { cx.library().is_sub(&self.id) }
}
}
impl Screen for ChannelPage {
fn spec(&mut self, cx: &Cx) -> Spec {
let client = cx.client();
let id = self.id.clone();
self.feed.start::<ChannelPage>(cx, ChannelPage::paged, move || client.channel(&id));
if cx.signed_in() && !self.asked {
self.asked = true;
let client = cx.client();
let id = self.id.clone();
cx.spawn::<ChannelPage, _>(move || client.is_subscribed(&id), |s, _cx, r| s.subscribed = r.ok().flatten());
}
let header = self.feed.feed().and_then(|f| f.header.clone()).unwrap_or_default();
if !header.title.is_empty() {
self.title = header.title.clone();
}
if let Some(h) = self.feed.feed().and_then(|f| f.header.as_ref()) {
if !h.thumb.is_empty() {
cx.backdrop(&h.thumb, Look::Soft, &format!("ch:{}", self.id));
}
}
let mut lines = vec![L::page_title("title", self.title.clone(), header.meta.clone())];
let on = self.following(cx);
let known = !cx.signed_in() || self.subscribed.is_some();
lines.push(L::chips(
"actions",
"",
vec![
Ch::new("sub", if on { "Feliratkozva" } else { "Feliratkozás" }).icon(if on { "check" } else { "plus" }).tone(if on { "" } else { "primary" }).active(on).enabled(known),
Ch::new("play", "Lejátszás").icon("play"),
],
));
lines.extend(self.feed.lines("Videók", cx.settings().shorts));
if self.feed.feed().is_some_and(|f| f.is_empty()) {
lines.push(L::notice("none", "info", "Nincs videó", "Ezen a csatornán nincs nyilvános videó."));
}
Spec { lines, frame: Frame::default() }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
match (line, key) {
("actions", "sub") => {
let on = !self.following(cx);
if cx.signed_in() {
let client = cx.client();
let id = self.id.clone();
self.subscribed = Some(on);
cx.call::<ChannelPage>("subscribe", move || client.subscribe(&id, on), move |s, cx, ok| {
if ok {
cx.toast(if on { "Feliratkoztál" } else { "Leiratkoztál" });
} else {
s.subscribed = Some(!on);
}
});
} else {
let thumb = self.feed.feed().and_then(|f| f.header.as_ref()).map(|h| h.thumb.clone()).unwrap_or_default();
let sub = Sub { id: self.id.clone(), title: self.title.clone(), thumb };
let now = cx.update_library(|l| l.toggle_sub(sub));
cx.toast(if now { "Feliratkoztál ezen a TV-n" } else { "Leiratkoztál" });
}
}
("actions", "play") => {
let Some(f) = self.feed.feed() else { return };
let mut videos = f.videos().filter(|v| !v.live && !v.short).cloned();
if let Some(first) = videos.next() {
cx.play(crate::player::Request::new(first, videos.take(crate::player::QUEUE_MAX).collect()));
}
}
_ => {
screens::open_card(cx, key, self.feed.find(key), self.feed.queue(line, key));
}
}
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
if let Some(item) = self.feed.find(key) {
screens::focus_backdrop(cx, Some(&item), key);
}
}
fn more(&mut self, cx: &Cx, list: &str) {
self.feed.more::<ChannelPage>(cx, list, ChannelPage::paged);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

190
src/screens/home.rs Normal file
View File

@@ -0,0 +1,190 @@
//! Kezdőlap: "Folytatás" (this TV's unfinished videos), then YouTube's home
//! feed (personal when signed in). A signed-out home can come back empty
//! (YouTube shows nothing without a history): then this TV fills it with
//! its subscriptions' latest videos, videos related to what it played last,
//! and this week's most watched videos of a few topics (Hungarian queries,
//! so the rows are local).
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{Frame, L, Spec};
use crate::screens::{self, Load, Paged, cards, video_card};
use crate::yt::{Item, Video};
/// Rows of a signed-out home: (title, search).
const TOPICS: [(&str, &str); 5] = [
("Zene · népszerű a héten", "magyar zene"),
("Hírek", "híradó"),
("Film-előzetesek", "film előzetes"),
("Gaming", "gaming"),
("Sport", "sport összefoglaló"),
];
pub struct Home {
feed: Paged,
extra: Option<Load<Vec<(String, Vec<Item>)>>>,
}
impl Home {
pub fn new() -> Home {
Home { feed: Paged::new("home", false, true), extra: None }
}
fn paged(s: &mut Home) -> &mut Paged {
&mut s.feed
}
fn needs_extra(&self) -> bool {
match &self.feed.load {
Load::Ready(f) => f.is_empty(),
Load::Failed(_) => true,
Load::Loading => false,
}
}
fn load_extra(&mut self, cx: &Cx) {
if self.extra.is_some() {
return;
}
self.extra = Some(Load::Loading);
let client = cx.client();
let subs: Vec<String> = cx.library().subs.iter().take(15).map(|s| s.id.clone()).collect();
let last: Vec<(String, String)> = cx.library().history.iter().take(2).map(|w| (w.id.clone(), w.title.clone())).collect();
cx.spawn::<Home, _>(
move || {
let mut rows: Vec<(String, Vec<Item>)> = Vec::new();
let mut latest: Vec<(String, Video)> = Vec::new();
let handles: Vec<_> = subs
.into_iter()
.map(|id| {
let c = client.clone();
std::thread::spawn(move || crate::yt::extras::channel_feed(&c, &id).unwrap_or_default())
})
.collect();
for h in handles {
latest.extend(h.join().unwrap_or_default().into_iter().filter(|(_, v)| !v.short).take(6));
}
latest.sort_by(|a, b| b.0.cmp(&a.0));
if !latest.is_empty() {
rows.push(("Feliratkozásaid".into(), latest.into_iter().take(30).map(|(_, v)| Item::Video(v)).collect()));
}
let watched: Vec<_> = last
.into_iter()
.map(|(id, title)| {
let c = client.clone();
std::thread::spawn(move || (format!("Mert megnézted: {title}"), c.related(&id, None).map(|f| videos(&f))))
})
.collect();
let topics: Vec<_> = TOPICS
.iter()
.map(|(title, q)| {
let c = client.clone();
let (title, q) = (title.to_string(), q.to_string());
std::thread::spawn(move || (title, c.popular_this_week(&q).map(|f| videos(&f))))
})
.collect();
let handles: Vec<_> = watched.into_iter().chain(topics).collect();
let mut err = None;
for h in handles {
if let Ok((title, r)) = h.join() {
match r {
Ok(items) if !items.is_empty() => rows.push((title, items)),
Ok(_) => {}
Err(e) => err = Some(e),
}
}
}
match (rows.is_empty(), err) {
(true, Some(e)) => Err(e),
_ => Ok(rows),
}
},
|s, cx, r| s.extra = Some(Load::from(r, cx)),
);
}
fn item(&self, cx: &Cx, key: &str) -> Option<Item> {
if let Some(i) = self.feed.find(key) {
return Some(i);
}
if let Some(Load::Ready(rows)) = &self.extra {
let id = key.split(':').nth(1).unwrap_or_default();
if let Some(i) = rows.iter().flat_map(|r| r.1.iter()).find(|i| i.id() == id) {
return Some(i.clone());
}
}
let id = key.strip_prefix("v:")?;
cx.library().find(id).map(|w| Item::Video(w.video()))
}
}
/// A feed's videos for a row: no Shorts, no live streams.
fn videos(f: &crate::yt::Feed) -> Vec<Item> {
f.videos().filter(|v| !v.short && !v.live).take(24).cloned().map(Item::Video).collect()
}
impl Screen for Home {
fn spec(&mut self, cx: &Cx) -> Spec {
let client = cx.client();
self.feed.start::<Home>(cx, Home::paged, move || client.home());
let shorts = cx.settings().shorts;
let mut lines = Vec::new();
let unfinished: Vec<_> = cx.library().history.iter().filter(|w| w.unfinished()).take(20).map(|w| video_card(&w.video())).collect();
if !unfinished.is_empty() {
lines.push(L::cards("continue", "Folytatás", "landscape", unfinished).captions());
}
let main = if cx.signed_in() { "Neked ajánljuk" } else { "Ajánlott" };
let feed_lines = self.feed.lines(main, shorts);
let feed_failed = matches!(self.feed.load, Load::Failed(_));
if self.needs_extra() {
self.load_extra(cx);
if feed_failed {
lines.extend(feed_lines);
}
match &self.extra {
Some(Load::Ready(rows)) => {
for (i, (title, items)) in rows.iter().enumerate() {
lines.push(L::cards(format!("extra-{i}"), title.clone(), "landscape", cards(items, shorts)).captions());
}
if rows.is_empty() {
lines.push(L::notice("empty", "info", "Itt még üres", "Keress rá valamire, vagy jelentkezz be a Beállításokban."));
}
}
Some(other) => lines.extend(other.status("extra-status")),
None => {}
}
} else {
lines.extend(feed_lines);
}
Spec { lines, frame: Frame { nav: Some(0), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
let item = self.item(cx, key);
let queue = if let Some(i) = line.strip_prefix("extra-").and_then(|n| n.parse::<usize>().ok()) {
match &self.extra {
Some(Load::Ready(rows)) => rows.get(i).map(|r| screens::queue_after(&r.1, key)).unwrap_or_default(),
_ => Vec::new(),
}
} else if line == "continue" {
Vec::new()
} else {
self.feed.queue(line, key)
};
screens::open_card(cx, key, item, queue);
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
let item = self.item(cx, key);
screens::focus_backdrop(cx, item.as_ref(), key);
}
fn more(&mut self, cx: &Cx, list: &str) {
self.feed.more::<Home>(cx, list, Home::paged);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

119
src/screens/library.rs Normal file
View File

@@ -0,0 +1,119 @@
//! Könyvtár: what this TV watched, and signed in, the account's lists:
//! YouTube history, Később megnézendő, Kedvelt videók, own playlists.
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{Ch, Frame, L, Spec};
use crate::screens::{self, Load, cards, video_card};
use crate::yt::{Feed, Item};
/// The account's rows: (line id, title, what to load).
const ROWS: [(&str, &str, &str); 4] = [("wl", "Később megnézendő", "WL"), ("ll", "Kedvelt videók", "LL"), ("yth", "YouTube-előzmények", "history"), ("lists", "Lejátszási listáid", "library")];
pub struct Library {
rows: Vec<Load<Vec<Item>>>,
started: bool,
}
impl Library {
pub fn new() -> Library {
Library { rows: ROWS.iter().map(|_| Load::Loading).collect(), started: false }
}
fn start(&mut self, cx: &Cx) {
if self.started || !cx.signed_in() {
return;
}
self.started = true;
for (i, (_, _, what)) in ROWS.iter().enumerate() {
let client = cx.client();
let what = what.to_string();
cx.spawn::<Library, _>(
move || -> anyhow::Result<Vec<Item>> {
let f: Feed = match what.as_str() {
"history" => client.history()?,
"library" => client.library()?,
id => client.playlist(id, true)?,
};
let items = f.flat();
// The library page lists playlists; the others videos.
Ok(if what == "library" { items.into_iter().filter(|i| matches!(i, Item::Playlist(_))).collect() } else { items })
},
move |s, cx, r| s.rows[i] = Load::from(r, cx),
);
}
}
fn row_items(&self, line: &str) -> Vec<Item> {
ROWS.iter().position(|r| r.0 == line).and_then(|i| self.rows[i].ready().cloned()).unwrap_or_default()
}
fn local_items(cx: &Cx) -> Vec<Item> {
cx.library().history.iter().take(60).map(|w| Item::Video(w.video())).collect()
}
}
impl Screen for Library {
fn spec(&mut self, cx: &Cx) -> Spec {
self.start(cx);
let mut lines = Vec::new();
let local: Vec<_> = cx.library().history.iter().take(60).map(|w| video_card(&w.video())).collect();
if local.is_empty() {
lines.push(L::page_title("title", "Könyvtár", "Amit ezen a TV-n nézel, itt jelenik meg."));
} else {
lines.push(L::cards("local", "Ezen a TV-n nézted", "landscape", local).captions());
}
if cx.signed_in() {
for (i, (id, title, _)) in ROWS.iter().enumerate() {
match &self.rows[i] {
Load::Ready(items) if items.is_empty() => {}
Load::Ready(items) => {
let row = cards(items, true);
lines.push(L::cards(*id, *title, "landscape", row).captions());
}
Load::Loading => lines.push(L::text(format!("{id}-status"), format!("{title}: betöltés…"), "caption")),
Load::Failed(e) => lines.push(L::notice(format!("{id}-status"), "bad", format!("{title}: nem sikerült betölteni"), e.clone())),
}
}
if ROWS.iter().enumerate().all(|(i, _)| self.rows[i].ready().is_some_and(|r| r.is_empty())) {
lines.push(L::notice("empty", "info", "A fiókod listái üresek", "A Később megnézendő, a kedvelt videók és a lejátszási listáid jelennek meg itt."));
}
} else {
lines.push(L::notice(
"signin-note",
"info",
"Jelentkezz be a listáidért",
"Bejelentkezve itt vannak a Később megnézendő videóid, a kedvelt videók, a YouTube-előzményeid és a lejátszási listáid.",
));
lines.push(L::chips("signin", "", vec![Ch::new("signin", "Bejelentkezés QR-kóddal").icon("user").tone("primary")]));
}
Spec { lines, frame: Frame { nav: Some(2), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
if line == "signin" {
cx.c.sign_in();
return;
}
let items = if line == "local" { Library::local_items(cx) } else { self.row_items(line) };
let id = key.split(':').nth(1).unwrap_or_default();
let item = items.iter().find(|i| i.id() == id).cloned();
// Opening the account's own list (WL, LL) from the row title isn't a
// card; videos play with the rest of the row after them.
screens::open_card(cx, key, item, if line == "local" { Vec::new() } else { screens::queue_after(&items, key) });
}
fn focus(&mut self, cx: &Cx, line: &str, key: &str) {
let items = if line == "local" { Library::local_items(cx) } else { self.row_items(line) };
let id = key.split(':').nth(1).unwrap_or_default();
let item = items.into_iter().find(|i| i.id() == id);
screens::focus_backdrop(cx, item.as_ref(), key);
}
fn shown(&mut self, _cx: &Cx) {}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

349
src/screens/mod.rs Normal file
View File

@@ -0,0 +1,349 @@
//! The browsing screens. Each one describes its page as lines (src/page.rs)
//! and reacts to OK; see app::Screen.
//!
//! Card ids: "v:<video>", "c:<channel>", "p:<playlist>", "m:<mix>:<video>".
pub mod channel;
pub mod home;
pub mod library;
pub mod playlist;
pub mod search;
pub mod settings;
pub mod subs;
use crate::app::{Cx, Look, Screen};
use crate::page::{C, GRID_YT, L, grid_lines};
use crate::player::{self, Request};
use crate::yt::{Feed, Item, Shelf, Video};
/// The screen of a top navigation section.
pub fn section(n: usize) -> Box<dyn Screen> {
match n {
1 => Box::new(subs::Subs::new()),
2 => Box::new(library::Library::new()),
3 => Box::new(search::Search::new()),
4 => Box::new(settings::Settings::new()),
_ => Box::new(home::Home::new()),
}
}
/// Data that loads.
#[derive(Debug, Clone, Default)]
pub enum Load<T> {
#[default]
Loading,
Ready(T),
Failed(String),
}
impl<T> Load<T> {
pub fn ready(&self) -> Option<&T> {
match self {
Load::Ready(t) => Some(t),
_ => None,
}
}
pub fn ready_mut(&mut self) -> Option<&mut T> {
match self {
Load::Ready(t) => Some(t),
_ => None,
}
}
pub fn from(r: anyhow::Result<T>, cx: &Cx) -> Load<T> {
match r {
Ok(t) => Load::Ready(t),
Err(e) => {
if e.chain().any(|c| c.downcast_ref::<crate::yt::YtError>().is_some_and(|y| y.status == 401)) {
cx.error("", &e);
}
log::warn!("load: {e:#}");
Load::Failed(crate::yt::describe(&e))
}
}
}
/// The loading / error line, or None when ready.
pub fn status(&self, id: &str) -> Option<L> {
match self {
Load::Loading => Some(L::text(id, "Betöltés…", "caption")),
Load::Failed(e) => Some(L::notice(id, "bad", "Nem sikerült betölteni", e.clone())),
Load::Ready(_) => None,
}
}
}
pub fn video_card(v: &Video) -> C {
let mut c = C::new(format!("v:{}", v.id), v.title.clone(), v.thumb.clone());
c.caption = v.title.clone();
c.detail = [v.channel.as_str(), v.meta.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::<Vec<_>>().join(" · ");
c.progress = v.progress;
if v.live {
c.badge = "ÉLŐ".into();
c.badge_tone = "accent";
} else if v.short {
c.badge = "Shorts".into();
}
c.corner = v.duration.clone();
c
}
pub fn item_card(i: &Item) -> C {
match i {
Item::Video(v) => video_card(v),
Item::Channel(ch) => {
let mut c = C::new(format!("c:{}", ch.id), ch.title.clone(), ch.thumb.clone());
c.caption = ch.title.clone();
c.detail = if ch.meta.is_empty() { "Csatorna".into() } else { format!("Csatorna · {}", ch.meta) };
c.round = true;
c
}
Item::Playlist(p) => {
let id = if p.id.starts_with("RD") && !p.first_video.is_empty() { format!("m:{}:{}", p.id, p.first_video) } else { format!("p:{}", p.id) };
let mut c = C::new(id, p.title.clone(), p.thumb.clone());
c.caption = p.title.clone();
c.detail = p.meta.clone();
c.badge = if p.id.starts_with("RD") { "Mix".into() } else { "Lista".into() };
c
}
}
}
/// Items as cards; `shorts`: keep Shorts.
pub fn cards(items: &[Item], shorts: bool) -> Vec<C> {
items.iter().filter(|i| shorts || !matches!(i, Item::Video(v) if v.short)).map(item_card).collect()
}
/// A feed as lines: titled shelves as rows, the untitled main list as a
/// grid named `main`. `id`: prefix of the line ids.
pub fn feed_lines(id: &str, feed: &Feed, main: &str, shorts: bool) -> Vec<L> {
let mut out = Vec::new();
for (i, s) in feed.shelves.iter().enumerate() {
if !shorts && is_shorts(s) {
continue;
}
let cards = cards(&s.items, shorts);
if cards.is_empty() {
continue;
}
if s.title.is_empty() {
// Shorts mixed into the main list get a row of their own after it.
let (shorts_cards, rest): (Vec<C>, Vec<C>) = cards.into_iter().partition(|c| c.badge == "Shorts");
out.extend(grid_lines(&format!("{id}-grid"), main, "landscape", rest, GRID_YT));
if !shorts_cards.is_empty() {
out.push(L::cards(format!("{id}-shorts{i}"), "Shorts", "landscape", shorts_cards).captions());
}
} else {
out.push(L::cards(format!("{id}-{i}"), s.title.clone(), "landscape", cards).captions());
}
}
out
}
fn is_shorts(s: &Shelf) -> bool {
s.title.to_lowercase().contains("shorts") || (!s.items.is_empty() && s.items.iter().all(|i| matches!(i, Item::Video(v) if v.short)))
}
/// Finds an item by card id in feeds.
pub fn find<'a>(feeds: impl IntoIterator<Item = &'a Feed>, key: &str) -> Option<Item> {
let id = key.split(':').nth(1)?;
feeds.into_iter().flat_map(|f| f.items()).find(|i| i.id() == id).cloned()
}
/// Backdrop for a focused card: its picture, soft.
pub fn focus_backdrop(cx: &Cx, item: Option<&Item>, key: &str) {
match item {
Some(Item::Video(v)) => cx.backdrop(&v.thumb, Look::Soft, key),
Some(Item::Playlist(p)) => cx.backdrop(&p.thumb, Look::Soft, key),
_ => cx.backdrop("", Look::Soft, ""),
}
}
/// Opens a card: plays a video (with `queue` after it), opens a channel or
/// a playlist. True if it was a card.
pub fn open_card(cx: &Cx, key: &str, item: Option<Item>, queue: Vec<Video>) -> bool {
let mut parts = key.splitn(3, ':');
let (kind, id) = (parts.next().unwrap_or_default(), parts.next().unwrap_or_default());
match kind {
"v" => {
let video = match item {
Some(Item::Video(v)) => v,
_ => Video { id: id.to_string(), ..Video::default() },
};
cx.play(Request::new(video, queue));
true
}
"c" => {
let title = item.map(|i| i.title().to_string()).unwrap_or_default();
cx.push(Box::new(channel::ChannelPage::new(id, &title)));
true
}
"p" => {
let title = item.map(|i| i.title().to_string()).unwrap_or_default();
cx.push(Box::new(playlist::PlaylistPage::new(id, &title)));
true
}
"m" => {
let first = parts.next().unwrap_or_default();
let mut r = Request::new(Video { id: first.to_string(), ..Video::default() }, Vec::new());
r.mix = Some(id.to_string());
cx.play(r);
true
}
_ => false,
}
}
/// The videos after `key` in `items` (the queue when one of them plays).
pub fn queue_after(items: &[Item], key: &str) -> Vec<Video> {
let id = key.split(':').nth(1).unwrap_or_default();
let pos = items.iter().position(|i| i.id() == id).map(|p| p + 1).unwrap_or(items.len());
items[pos..]
.iter()
.filter_map(|i| match i {
Item::Video(v) if !v.live => Some(v.clone()),
_ => None,
})
.take(player::QUEUE_MAX)
.collect()
}
/// Items of the line holding `key` (for the queue).
pub fn line_items(feed: &Feed, line: &str) -> Vec<Item> {
// Grid lines ("x-grid#3") all belong to the untitled main list.
if line.contains("-grid") {
return feed.shelves.iter().filter(|s| s.title.is_empty()).flat_map(|s| s.items.clone()).collect();
}
if let Some(i) = line.rsplit('-').next().and_then(|n| n.strip_prefix("shorts")).and_then(|n| n.parse::<usize>().ok()) {
return feed.shelves.get(i).map(|s| s.items.iter().filter(|i| matches!(i, Item::Video(v) if v.short)).cloned().collect()).unwrap_or_default();
}
let i: Option<usize> = line.rsplit('-').next().and_then(|n| n.parse().ok());
i.and_then(|i| feed.shelves.get(i)).map(|s| s.items.clone()).unwrap_or_default()
}
/// A feed on a page with its continuations: the main list grows as a grid,
/// titled shelves grow sideways, and more shelves come at the end.
pub struct Paged {
pub load: Load<Feed>,
prefix: String,
search: bool,
personal: bool,
started: bool,
busy: std::collections::HashSet<String>,
}
impl Paged {
/// `prefix`: line ids; `search`: continuations go to the search
/// endpoint; `personal`: with the account (signed in).
pub fn new(prefix: &str, search: bool, personal: bool) -> Paged {
Paged { load: Load::Loading, prefix: prefix.into(), search, personal, started: false, busy: Default::default() }
}
/// Loads the first page once.
pub fn start<T: Screen>(&mut self, cx: &Cx, get: fn(&mut T) -> &mut Paged, work: impl FnOnce() -> anyhow::Result<Feed> + Send + 'static) {
if self.started {
return;
}
self.started = true;
self.load = Load::Loading;
cx.spawn::<T, _>(work, move |s, cx, r| get(s).load = Load::from(r, cx));
}
/// Marks the first page as loading (the caller loads it).
pub fn begin(&mut self) {
self.started = true;
self.load = Load::Loading;
}
pub fn feed(&self) -> Option<&Feed> {
self.load.ready()
}
/// The feed's lines (or its loading / error line).
pub fn lines(&self, main: &str, shorts: bool) -> Vec<L> {
match &self.load {
Load::Ready(f) => feed_lines(&self.prefix, f, main, shorts),
other => other.status(&format!("{}-status", self.prefix)).into_iter().collect(),
}
}
/// The focus is near the end of `list`: loads more of it (and more
/// shelves after the last one).
pub fn more<T: Screen>(&mut self, cx: &Cx, list: &str, get: fn(&mut T) -> &mut Paged) {
let Some(f) = self.load.ready() else { return };
let Some(rest) = list.strip_prefix(&format!("{}-", self.prefix)) else { return };
let mut jobs: Vec<(Option<usize>, String)> = Vec::new();
if rest.starts_with("grid") {
if let Some(t) = &f.more {
jobs.push((None, t.clone()));
}
} else if let Ok(i) = rest.parse::<usize>() {
if let Some(t) = f.shelves.get(i).and_then(|s| s.more.clone()) {
jobs.push((Some(i), t));
}
let last = f.shelves.iter().rposition(|s| !s.title.is_empty());
if last.is_some_and(|l| i + 1 >= l) {
if let Some(t) = &f.more {
jobs.push((None, t.clone()));
}
}
}
for (target, token) in jobs {
if !self.busy.insert(token.clone()) {
continue;
}
let client = cx.client();
let (search, personal) = (self.search, self.personal);
cx.spawn::<T, _>(move || client.more(&token, search, personal), move |s, _cx, r| match r {
Ok(m) => get(s).append(target, m),
Err(e) => log::warn!("more: {e:#}"),
});
}
}
fn append(&mut self, target: Option<usize>, more: Feed) {
let Some(f) = self.load.ready_mut() else { return };
match target {
Some(i) => {
let next = more.more.clone().or_else(|| more.shelves.iter().find_map(|s| s.more.clone()));
if let Some(s) = f.shelves.get_mut(i) {
for it in more.flat() {
if !s.items.iter().any(|x| x.id() == it.id()) {
s.items.push(it);
}
}
s.more = next;
}
}
None => {
for s in more.shelves {
if s.title.is_empty() {
let main = match f.shelves.iter().position(|x| x.title.is_empty()) {
Some(i) => i,
None => {
f.shelves.insert(0, Shelf::default());
0
}
};
let m = &mut f.shelves[main];
for it in s.items {
if !m.items.iter().any(|x| x.id() == it.id()) {
m.items.push(it);
}
}
} else {
f.shelves.push(s);
}
}
f.more = more.more;
}
}
}
pub fn find(&self, key: &str) -> Option<Item> {
find(self.feed(), key)
}
/// The videos after `key` on its line.
pub fn queue(&self, line: &str, key: &str) -> Vec<Video> {
self.feed().map(|f| queue_after(&line_items(f, line), key)).unwrap_or_default()
}
}

104
src/screens/playlist.rs Normal file
View File

@@ -0,0 +1,104 @@
//! A playlist: Lejátszás (in order), Keverve (shuffled), and its videos.
//! The account's own lists (WL, LL, private ones) load with the account.
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{Ch, Frame, L, Spec};
use crate::player::{QUEUE_MAX, Request};
use crate::screens::{self, Paged};
use crate::yt::Video;
pub struct PlaylistPage {
id: String,
title: String,
feed: Paged,
}
impl PlaylistPage {
pub fn new(id: &str, title: &str) -> PlaylistPage {
let personal = matches!(id, "WL" | "LL");
PlaylistPage { id: id.into(), title: title.into(), feed: Paged::new("pl", false, personal) }
}
fn paged(s: &mut PlaylistPage) -> &mut Paged {
&mut s.feed
}
fn videos(&self) -> Vec<Video> {
self.feed.feed().map(|f| f.videos().filter(|v| !v.live).cloned().collect()).unwrap_or_default()
}
}
/// A cheap shuffle (no rand crate): sorts by a hash of the id and the time.
fn shuffle(v: &mut [Video]) {
use std::hash::{Hash, Hasher};
let seed = crate::yt::now();
v.sort_by_cached_key(|x| {
let mut h = std::collections::hash_map::DefaultHasher::new();
(seed, &x.id).hash(&mut h);
h.finish()
});
}
impl Screen for PlaylistPage {
fn spec(&mut self, cx: &Cx) -> Spec {
let client = cx.client();
let id = self.id.clone();
let personal = matches!(id.as_str(), "WL" | "LL");
let signed_in = cx.signed_in();
self.feed.start::<PlaylistPage>(cx, PlaylistPage::paged, move || {
let f = client.playlist(&id, personal)?;
// A private list of the account: only with it.
if f.is_empty() && signed_in && !personal { client.playlist(&id, true) } else { Ok(f) }
});
let header = self.feed.feed().and_then(|f| f.header.clone()).unwrap_or_default();
if !header.title.is_empty() {
self.title = header.title.clone();
}
let n = self.videos().len();
let mut lines = vec![L::page_title("title", self.title.clone(), if header.meta.is_empty() && n > 0 { format!("{n} videó") } else { header.meta.clone() })];
if n > 0 {
lines.push(L::chips("actions", "", vec![Ch::new("play", "Lejátszás").icon("play").tone("primary"), Ch::new("shuffle", "Keverve").icon("refresh")]));
}
lines.extend(self.feed.lines("Videók", true));
if self.feed.feed().is_some_and(|f| f.is_empty()) {
lines.push(L::notice("none", "info", "A lista üres", "Ebben a listában nincs lejátszható videó."));
}
Spec { lines, frame: Frame::default() }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
match (line, key) {
("actions", "play" | "shuffle") => {
let mut v = self.videos();
if key == "shuffle" {
shuffle(&mut v);
}
if v.is_empty() {
return;
}
let first = v.remove(0);
v.truncate(QUEUE_MAX);
cx.play(Request::new(first, v));
}
_ => {
screens::open_card(cx, key, self.feed.find(key), self.feed.queue(line, key));
}
}
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
if let Some(item) = self.feed.find(key) {
screens::focus_backdrop(cx, Some(&item), key);
}
}
fn more(&mut self, cx: &Cx, list: &str) {
self.feed.more::<PlaylistPage>(cx, list, PlaylistPage::paged);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

91
src/screens/search.rs Normal file
View File

@@ -0,0 +1,91 @@
//! Keresés: the on-screen keyboard and the results (videos, channels,
//! playlists), more as the focus nears the end.
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{Frame, Kind, L, Spec};
use crate::screens::{self, Load, Paged};
pub struct Search {
searched: String,
result: Option<Paged>,
}
impl Search {
pub fn new() -> Search {
Search { searched: String::new(), result: None }
}
fn paged(s: &mut Search) -> &mut Paged {
s.result.get_or_insert_with(|| Paged::new("res", true, false))
}
}
impl Screen for Search {
fn spec(&mut self, cx: &Cx) -> Spec {
let shorts = cx.settings().shorts;
let mut lines = vec![L::page_title("title", "Keresés", "Videók, csatornák és lejátszási listák."), L::new("kb", Kind::Keyboard)];
match &self.result {
None => lines.push(L::notice("hint", "info", "Kezdj el gépelni", "A találatok gépelés közben jönnek; a Keresés gomb azonnal keres.")),
Some(p) => {
let res = p.lines(&format!("Találatok · {}", self.searched), shorts);
if p.feed().is_some_and(|f| f.is_empty()) {
lines.push(L::notice("none", "info", "Erre nincs találat", "Próbáld másképp írni."));
} else {
lines.extend(res);
}
}
}
Spec { lines, frame: Frame { nav: Some(3), keyboard: Some("Mit keresel?".into()), ..Frame::default() } }
}
fn query(&mut self, cx: &Cx, text: &str, submit: bool) {
let q = text.trim().to_string();
if q.chars().count() < 2 {
if !submit {
self.result = None;
self.searched.clear();
cx.refresh();
}
return;
}
if q == self.searched {
return;
}
self.searched = q.clone();
let mut p = Paged::new("res", true, false);
p.begin();
self.result = Some(p);
let client = cx.client();
cx.spawn::<Search, _>(move || (client.search(&q), q), |s, cx, (r, q)| {
// Only the latest search counts.
if s.searched == q {
if let Some(p) = s.result.as_mut() {
p.load = Load::from(r, cx);
}
}
});
cx.refresh();
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
let Some(p) = &self.result else { return };
screens::open_card(cx, key, p.find(key), p.queue(line, key));
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
let item = self.result.as_ref().and_then(|p| p.find(key));
screens::focus_backdrop(cx, item.as_ref(), key);
}
fn more(&mut self, cx: &Cx, list: &str) {
if let Some(p) = self.result.as_mut() {
p.more::<Search>(cx, list, Search::paged);
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

154
src/screens/settings.rs Normal file
View File

@@ -0,0 +1,154 @@
//! Beállítások: Fiók (QR sign-in), Lejátszás, Megjelenés, Adatok, Névjegy.
use std::any::Any;
use crate::app::{Cx, SETTINGS, Screen};
use crate::config;
use crate::page::{Ch, Frame, L, Spec};
const TABS: [&str; 5] = ["Fiók", "Lejátszás", "Megjelenés", "Adatok", "Névjegy"];
pub struct Settings {
tab: usize,
}
impl Settings {
pub fn new() -> Settings {
Settings { tab: 0 }
}
}
fn choice<T: PartialEq + Copy>(line: &str, label: &str, options: &[(T, &str)], current: T, key: impl Fn(T) -> String) -> L {
L::chips(line, label, options.iter().map(|(v, text)| Ch::new(key(*v), *text).active(*v == current)).collect())
}
fn on_off(line: &str, label: &str, on: bool) -> L {
choice(line, label, &[(true, "Bekapcsolva"), (false, "Kikapcsolva")], on, |v| if v { "on".into() } else { "off".into() })
}
impl Screen for Settings {
fn spec(&mut self, cx: &Cx) -> Spec {
let s = cx.settings();
let mut lines = Vec::new();
match self.tab {
0 => {
let a = cx.account();
if a.signed_in() {
lines.push(L::page_title("title", "Fiók", if a.name.is_empty() { "Bejelentkezve".to_string() } else { a.name.clone() }));
lines.push(L::notice(
"on",
"good",
"Bejelentkezve a YouTube-fiókoddal",
"A kezdőlap a fiókod ajánlásai, a Feliratkozások és a Könyvtár a fiókod adatai. Amit itt nézel, bekerül a YouTube-előzményeidbe.",
));
lines.push(L::chips("account", "", vec![Ch::new("signout", "Kijelentkezés").icon("close").tone("danger")]));
} else {
lines.push(L::page_title("title", "Fiók", "Nincs bejelentkezve"));
lines.push(L::notice(
"off",
"info",
"Bejelentkezés telefonnal",
"A TV egy kódot és egy QR-kódot mutat. Olvasd be a telefonoddal (vagy nyisd meg a youtube.com/activate oldalt), és erősítsd meg a fiókodat. Jelszót nem kell beírni a TV-n.",
));
lines.push(L::chips("account", "", vec![Ch::new("signin", "Bejelentkezés QR-kóddal").icon("user").tone("primary")]));
}
}
1 => {
lines.push(L::page_title("title", "Lejátszás", "Minden videóra érvényes; a lejátszóban videónként is állítható."));
lines.push(choice(
"quality",
"Legjobb minőség",
&[(0u64, "Automatikus"), (480, "480p"), (720, "720p"), (1080, "1080p"), (1440, "1440p"), (2160, "4K")],
s.quality,
|v| v.to_string(),
));
lines.push(L::text("quality-note", "Automatikus: legfeljebb 1080p, a hálózathoz igazítva. A 1440p és a 4K csak AV1 kodekkel érhető el.", "caption"));
lines.push(choice("codec", "Kodek", &[("h264", "H.264 · minden TV-n"), ("av1", "AV1 · újabb hardveren")], s.codec.as_str(), |v| v.to_string()));
lines.push(choice("captions", "Felirat", &[("", "Kikapcsolva"), ("hu", "Magyar"), ("en", "Angol")], s.captions.as_str(), |v| if v.is_empty() { "off".into() } else { v.to_string() }));
lines.push(L::text("captions-note", "A videó saját feliratát mutatja ezen a nyelven (kézit, ha van, különben az automatikusat). A lejátszóban bármelyik felirat választható.", "caption"));
lines.push(on_off("sponsorblock", "Szponzorált részek átugrása (SponsorBlock)", s.sponsorblock));
lines.push(on_off("autoplay", "Következő videó automatikusan", s.autoplay));
lines.push(choice("shorts", "Shorts", &[(true, "Megjelenik"), (false, "Elrejtve")], s.shorts, |v| if v { "on".into() } else { "off".into() }));
}
2 => {
lines.push(L::page_title("title", "Megjelenés", "Az üveghatás erőssége ezen a TV-n."));
lines.push(choice(
"glass",
"Üveg",
&[("auto", "Automatikus"), ("full", "Teljes"), ("light", "Könnyű"), ("off", "Matt")],
s.glass.as_str(),
|v| v.to_string(),
));
lines.push(L::text("glass-note", "Automatikus: a TV a grafikus chip alapján választ. Gyengébb gépen a Matt a leggyorsabb.", "caption"));
}
3 => {
let (history, subs) = {
let l = cx.library();
(l.history.len(), l.subs.len())
};
lines.push(L::page_title("title", "Adatok", "Amit az app ezen a TV-n tárol."));
lines.push(L::item("history", "Előzmények ezen a TV-n", format!("{history} videó"), "A Folytatás sorhoz és a Könyvtárhoz.", vec![Ch::new("clear", "Törlés").icon("delete").enabled(history > 0)]));
lines.push(L::item(
"subs",
"Feliratkozások ezen a TV-n",
format!("{subs} csatorna"),
"Bejelentkezés nélkül ezek a csatornák látszanak a Feliratkozásokban.",
vec![Ch::new("clear", "Törlés").icon("delete").enabled(subs > 0)],
));
}
_ => {
lines.push(L::page_title("title", "YouTube", format!("Fennec OS · {}. verzió", env!("CARGO_PKG_VERSION"))));
lines.push(L::notice(
"ads",
"good",
"Reklámok nélkül",
"Az app a YouTube saját felületéről kéri a videókat, de a hirdetéseket nem kéri le és nem játssza le, a hirdetéskártyákat pedig kihagyja.",
));
lines.push(L::text(
"credits",
"Videók: YouTube (InnerTube). Az aláírások megoldása: yt-dlp ejs (Unlicense), QuickJS-ben. Szponzorált részek: SponsorBlock (sponsor.ajay.app).",
"caption",
));
}
}
Spec { lines, frame: Frame { nav: Some(SETTINGS), side: Some(("Beállítások".into(), TABS.iter().map(|t| t.to_string()).collect(), self.tab)), ..Frame::default() } }
}
fn side(&mut self, _cx: &Cx, i: usize) {
self.tab = i;
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
let mut s = cx.settings();
match line {
"account" if key == "signin" => return cx.c.sign_in(),
"account" if key == "signout" => return cx.c.signed_out(false),
"quality" => s.quality = key.parse().unwrap_or(0),
"codec" => s.codec = key.into(),
"captions" => s.captions = if key == "off" { String::new() } else { key.into() },
"sponsorblock" => s.sponsorblock = key == "on",
"autoplay" => s.autoplay = key == "on",
"shorts" => s.shorts = key == "on",
"glass" => {
s.glass = key.into();
config::apply_look(&cx.c.glass, key);
}
"history" => {
cx.update_library(|l| l.history.clear());
cx.toast("Előzmények törölve");
return;
}
"subs" => {
cx.update_library(|l| l.subs.clear());
cx.toast("Feliratkozások törölve");
return;
}
_ => return,
}
cx.set_settings(s);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

164
src/screens/subs.rs Normal file
View File

@@ -0,0 +1,164 @@
//! Feliratkozások. Signed in: the account's subscriptions feed. Signed out:
//! the channels followed on this TV and their latest videos (from each
//! channel's RSS feed, newest first).
use std::any::Any;
use crate::app::{Cx, Screen};
use crate::page::{C, Frame, GRID_YT, L, Spec, grid_lines};
use crate::screens::{self, Load, Paged, video_card};
use crate::yt::{Item, Video};
pub struct Subs {
feed: Paged,
local: Option<Load<Vec<Video>>>,
}
impl Subs {
pub fn new() -> Subs {
Subs { feed: Paged::new("subs", false, true), local: None }
}
fn paged(s: &mut Subs) -> &mut Paged {
&mut s.feed
}
fn load_local(&mut self, cx: &Cx) {
if self.local.is_some() {
return;
}
let ids: Vec<String> = cx.library().subs.iter().map(|s| s.id.clone()).collect();
if ids.is_empty() {
self.local = Some(Load::Ready(Vec::new()));
return;
}
self.local = Some(Load::Loading);
let client = cx.client();
cx.spawn::<Subs, _>(
move || {
let mut all: Vec<(String, Video)> = Vec::new();
let mut err = None;
// A few channels at a time.
for chunk in ids.chunks(8) {
let handles: Vec<_> = chunk
.iter()
.map(|id| {
let (c, id) = (client.clone(), id.clone());
std::thread::spawn(move || crate::yt::extras::channel_feed(&c, &id))
})
.collect();
for h in handles {
match h.join() {
Ok(Ok(v)) => all.extend(v),
Ok(Err(e)) => err = Some(e),
Err(_) => {}
}
}
}
if all.is_empty() {
if let Some(e) = err {
return Err(e);
}
}
all.sort_by(|a, b| b.0.cmp(&a.0));
Ok(all.into_iter().map(|(_, v)| v).take(120).collect())
},
|s, cx, r| s.local = Some(Load::from(r, cx)),
);
}
fn local_items(&self) -> Vec<Item> {
match &self.local {
Some(Load::Ready(v)) => v.iter().cloned().map(Item::Video).collect(),
_ => Vec::new(),
}
}
}
impl Screen for Subs {
fn spec(&mut self, cx: &Cx) -> Spec {
let shorts = cx.settings().shorts;
let mut lines = Vec::new();
if cx.signed_in() {
let client = cx.client();
self.feed.start::<Subs>(cx, Subs::paged, move || client.subscriptions());
lines.extend(self.feed.lines("Legújabb videók", shorts));
if self.feed.feed().is_some_and(|f| f.is_empty()) {
lines.push(L::notice("none", "info", "Nincs új videó", "A fiókod feliratkozásainak videói jelennek meg itt."));
}
} else {
self.load_local(cx);
let subs = cx.library().subs.clone();
if subs.is_empty() {
lines.push(L::page_title("title", "Feliratkozások", "Ezen a TV-n még nem iratkoztál fel egy csatornára sem."));
lines.push(L::notice(
"how",
"info",
"Így iratkozhatsz fel",
"Nyiss meg egy csatornát (egy videó alatt vagy a keresőben), és nyomd meg a Feliratkozás gombot. Ha bejelentkezel, a fiókod feliratkozásai látszanak itt.",
));
lines.push(L::chips("signin", "", vec![crate::page::Ch::new("signin", "Bejelentkezés QR-kóddal").icon("user").tone("primary")]));
} else {
let channels: Vec<C> = subs
.iter()
.map(|s| {
let mut c = C::new(format!("c:{}", s.id), s.title.clone(), s.thumb.clone());
c.caption = s.title.clone();
c.round = true;
c
})
.collect();
lines.push(L::cards("channels", "Csatornáid", "landscape", channels).captions());
match &self.local {
Some(Load::Ready(v)) => {
let cards = v.iter().filter(|v| shorts || !v.short).map(video_card).collect();
lines.extend(grid_lines("subs-grid", "Legújabb videók", "landscape", cards, GRID_YT));
}
Some(other) => lines.extend(other.status("local-status")),
None => {}
}
}
}
Spec { lines, frame: Frame { nav: Some(1), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, key: &str) {
if line == "signin" {
cx.c.sign_in();
return;
}
if cx.signed_in() {
screens::open_card(cx, key, self.feed.find(key), self.feed.queue(line, key));
} else {
let items = self.local_items();
let id = key.split(':').nth(1).unwrap_or_default();
let item = items.iter().find(|i| i.id() == id).cloned();
let title = cx.library().subs.iter().find(|s| s.id == id).map(|s| s.title.clone());
let item = item.or_else(|| title.map(|t| Item::Channel(crate::yt::parse::Channel { id: id.into(), title: t, ..Default::default() })));
screens::open_card(cx, key, item, screens::queue_after(&items, key));
}
}
fn focus(&mut self, cx: &Cx, _line: &str, key: &str) {
let item = if cx.signed_in() { self.feed.find(key) } else { self.local_items().into_iter().find(|i| key.ends_with(i.id())) };
screens::focus_backdrop(cx, item.as_ref(), key);
}
fn more(&mut self, cx: &Cx, list: &str) {
self.feed.more::<Subs>(cx, list, Subs::paged);
}
fn shown(&mut self, cx: &Cx) {
// Followed or dropped a channel meanwhile.
if !cx.signed_in() {
let have = matches!(&self.local, Some(Load::Ready(_)));
if have {
self.local = None;
}
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

49
src/task.rs Normal file
View File

@@ -0,0 +1,49 @@
//! Blocking work (HTTP calls) on a thread, its result back on the UI thread.
//!
//! `done` runs on the Slint event loop, so it may touch the UI and `Rc`
//! state; it is kept in a thread-local table while the work runs.
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
type Done = Box<dyn FnOnce(Box<dyn std::any::Any + Send>)>;
thread_local! {
static WAITING: RefCell<HashMap<u64, Done>> = RefCell::new(HashMap::new());
}
static NEXT: AtomicU64 = AtomicU64::new(1);
/// Runs `work` on a new thread; `done(result)` runs on the UI thread. Call it
/// from the UI thread.
pub fn spawn<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static, done: impl FnOnce(T) + 'static) {
let id = NEXT.fetch_add(1, Ordering::Relaxed);
WAITING.with(|w| {
w.borrow_mut().insert(
id,
Box::new(move |any: Box<dyn std::any::Any + Send>| {
if let Ok(v) = any.downcast::<T>() {
done(*v);
}
}),
)
});
std::thread::spawn(move || {
let result: Box<dyn std::any::Any + Send> = Box::new(work());
let _ = slint::invoke_from_event_loop(move || {
if let Some(done) = WAITING.with(|w| w.borrow_mut().remove(&id)) {
done(result);
}
});
});
}
/// Fire and forget (saving progress...): errors are only logged.
pub fn background(what: &'static str, work: impl FnOnce() -> anyhow::Result<()> + Send + 'static) {
std::thread::spawn(move || {
if let Err(e) = work() {
log::warn!("{what}: {e:#}");
}
});
}

130
src/yt/auth.rs Normal file
View File

@@ -0,0 +1,130 @@
//! Sign-in the way YouTube's own TV app does it: the TV shows a code (and a
//! QR code), the user confirms it on a phone at youtube.com/activate, the
//! TV polls until it gets the tokens. OAuth 2.0 device flow with the TV
//! app's client, so the token works with the TV client (`Kind::Tv`).
//!
//! Only the refresh token is stored (`config::Account`); access tokens are
//! fetched when needed (`Client::bearer`).
use std::io::Read;
use anyhow::{Result, bail};
use serde_json::{Value, json};
/// The YouTube TV app's OAuth client (public: it is in youtube.com/tv's script).
const CLIENT_ID: &str = "861556708454-d6dlm3lh05idd8npek18k6be8ba3oc68.apps.googleusercontent.com";
const CLIENT_SECRET: &str = "SboVhoG9s0rNafixCSGGKXAT";
const SCOPE: &str = "http://gdata.youtube.com https://www.googleapis.com/auth/youtube";
const CODE_URL: &str = "https://www.youtube.com/o/oauth2/device/code";
const TOKEN_URL: &str = "https://www.youtube.com/o/oauth2/token";
const REVOKE_URL: &str = "https://oauth2.googleapis.com/revoke";
#[derive(Debug, Clone)]
pub struct DeviceCode {
pub device_code: String,
/// What the user types: "ABC-DEF-GHI".
pub user_code: String,
/// "https://www.youtube.com/activate"
pub url: String,
/// Seconds between polls.
pub interval: u64,
/// Seconds the code is valid.
pub expires_in: u64,
}
impl DeviceCode {
/// What the QR code opens: the activation page with the code filled in.
pub fn qr_link(&self) -> String {
format!("{}?user_code={}", self.url, self.user_code)
}
}
#[derive(Debug, Clone)]
pub enum Poll {
/// Not confirmed yet.
Pending,
/// Poll slower.
SlowDown,
/// Signed in: (refresh token, access token, expires in seconds).
Done { refresh: String, access: String, expires_in: u64 },
/// The user said no on the phone.
Denied,
/// The code ran out: ask for a new one.
Expired,
}
fn post(agent: &ureq::Agent, url: &str, body: Value) -> Result<(u16, Value)> {
let resp = agent.post(url).header("User-Agent", super::Kind::Tv.profile().user_agent).send_json(&body)?;
let status = resp.status().as_u16();
let mut text = String::new();
resp.into_body().into_reader().take(1 << 20).read_to_string(&mut text)?;
Ok((status, serde_json::from_str(&text).unwrap_or(Value::Null)))
}
/// A random id for this TV (the TV app sends one per sign-in).
fn device_id() -> String {
use std::hash::{BuildHasher, Hasher};
let mut out = String::new();
for i in 0..2 {
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
h.write_u64(super::now() ^ (i << 32) ^ std::process::id() as u64);
out.push_str(&format!("{:016x}", h.finish()));
}
out
}
/// Asks for a code to show.
pub fn start(agent: &ureq::Agent) -> Result<DeviceCode> {
let (status, v) = post(agent, CODE_URL, json!({ "client_id": CLIENT_ID, "scope": SCOPE, "device_id": device_id(), "device_model": "ytlr::" }))?;
let (Some(device), Some(user)) = (v["device_code"].as_str(), v["user_code"].as_str()) else {
bail!("A YouTube nem adott bejelentkezési kódot ({status}): {}", v["error"].as_str().unwrap_or("ismeretlen hiba"));
};
Ok(DeviceCode {
device_code: device.into(),
user_code: user.into(),
url: v["verification_url"].as_str().unwrap_or("https://www.youtube.com/activate").into(),
interval: v["interval"].as_u64().unwrap_or(5).max(2),
expires_in: v["expires_in"].as_u64().unwrap_or(1800),
})
}
/// Has the user confirmed the code yet?
pub fn poll(agent: &ureq::Agent, code: &DeviceCode) -> Result<Poll> {
let (status, v) = post(
agent,
TOKEN_URL,
json!({ "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "code": code.device_code, "grant_type": "http://oauth.net/grant_type/device/1.0" }),
)?;
if let (Some(refresh), Some(access)) = (v["refresh_token"].as_str(), v["access_token"].as_str()) {
return Ok(Poll::Done { refresh: refresh.into(), access: access.into(), expires_in: v["expires_in"].as_u64().unwrap_or(3600) });
}
Ok(match v["error"].as_str().unwrap_or_default() {
"authorization_pending" => Poll::Pending,
"slow_down" => Poll::SlowDown,
"access_denied" => Poll::Denied,
"expired_token" => Poll::Expired,
e => bail!("Bejelentkezési hiba ({status}): {e}"),
})
}
/// A new access token: (token, expires in seconds).
pub fn refresh(agent: &ureq::Agent, refresh_token: &str) -> Result<(String, u64)> {
let (status, v) = post(
agent,
TOKEN_URL,
json!({ "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "refresh_token": refresh_token, "grant_type": "refresh_token" }),
)?;
match v["access_token"].as_str() {
Some(t) => Ok((t.to_string(), v["expires_in"].as_u64().unwrap_or(3600))),
None => Err(super::YtError {
status: if v["error"].as_str() == Some("invalid_grant") { 401 } else { status },
message: "A YouTube-bejelentkezés lejárt, jelentkezz be újra.".into(),
}
.into()),
}
}
/// Signs this TV out at Google too (best effort).
pub fn revoke(agent: &ureq::Agent, refresh_token: &str) {
let _ = agent.post(&format!("{REVOKE_URL}?token={refresh_token}")).send_empty();
}

195
src/yt/extras.rs Normal file
View File

@@ -0,0 +1,195 @@
//! Around the videos: SponsorBlock segments, channel RSS feeds (the
//! subscriptions of a signed-out TV), captions, and marking a video watched
//! in the account's history.
use anyhow::Result;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use super::parse::Video;
use super::stream::{Caption, enc};
use super::{Client, Kind};
const UA: &str = concat!("FennecYouTube/", env!("CARGO_PKG_VERSION"), " (Fennec OS)");
/// A part of a video to skip (SponsorBlock): start, end (s) and kind.
#[derive(Debug, Clone, PartialEq)]
pub struct Segment {
pub start: f64,
pub end: f64,
pub category: String,
}
pub const SPONSOR_CATEGORIES: [&str; 4] = ["sponsor", "selfpromo", "interaction", "music_offtopic"];
/// The video's skippable segments. Asks by a hash prefix, so the service
/// doesn't learn which video plays.
pub fn sponsor_segments(client: &Client, video: &str) -> Result<Vec<Segment>> {
let hash = Sha256::digest(video.as_bytes());
let prefix: String = hash.iter().take(2).map(|b| format!("{b:02x}")).collect();
let cats = serde_json::to_string(&SPONSOR_CATEGORIES)?;
let url = format!("https://sponsor.ajay.app/api/skipSegments/{prefix}?categories={}", enc(&cats));
let text = match client.get_text(&url, UA) {
Ok(t) => t,
// 404: nothing for this prefix.
Err(e) if e.downcast_ref::<super::YtError>().is_some_and(|y| y.status == 404) => return Ok(Vec::new()),
Err(e) => return Err(e),
};
let v: Value = serde_json::from_str(&text)?;
let mut out = Vec::new();
for entry in v.as_array().into_iter().flatten().filter(|e| e["videoID"].as_str() == Some(video)) {
for s in entry["segments"].as_array().into_iter().flatten() {
if s["actionType"].as_str().is_some_and(|a| a != "skip") {
continue;
}
let (Some(a), Some(b)) = (s["segment"][0].as_f64(), s["segment"][1].as_f64()) else { continue };
if b - a >= 1.0 {
out.push(Segment { start: a, end: b, category: s["category"].as_str().unwrap_or_default().into() });
}
}
}
out.sort_by(|a, b| a.start.total_cmp(&b.start));
Ok(out)
}
pub fn segment_label(category: &str) -> &'static str {
match category {
"sponsor" => "Szponzorált rész",
"selfpromo" => "Önreklám",
"interaction" => "Feliratkozásra buzdítás",
"music_offtopic" => "Nem zenei rész",
_ => "Kihagyható rész",
}
}
fn between<'a>(s: &'a str, a: &str, b: &str) -> Option<&'a str> {
let i = s.find(a)? + a.len();
let j = s[i..].find(b)? + i;
Some(&s[i..j])
}
fn unxml(s: &str) -> String {
s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#39;", "'").replace("&apos;", "'").replace("&amp;", "&")
}
/// A channel's latest videos from its RSS feed, newest first, with their
/// publication time (RFC 3339) for sorting.
pub fn channel_feed(client: &Client, channel: &str) -> Result<Vec<(String, Video)>> {
let text = client.get_text(&format!("https://www.youtube.com/feeds/videos.xml?channel_id={channel}"), UA)?;
let author = between(&text, "<author>", "</author>").and_then(|a| between(a, "<name>", "</name>")).map(unxml).unwrap_or_default();
let mut out = Vec::new();
for entry in text.split("<entry>").skip(1) {
let Some(id) = between(entry, "<yt:videoId>", "</yt:videoId>") else { continue };
let published = between(entry, "<published>", "</published>").unwrap_or_default().to_string();
let title = between(entry, "<title>", "</title>").map(unxml).unwrap_or_default();
// Shorts show up as /shorts/ links.
let short = entry.contains("/shorts/");
out.push((
published,
Video {
id: id.to_string(),
title,
channel: author.clone(),
channel_id: channel.to_string(),
thumb: super::parse::video_thumb(id),
progress: -1.0,
short,
..Video::default()
},
));
}
Ok(out)
}
/// One line of captions.
#[derive(Debug, Clone, PartialEq)]
pub struct Cue {
pub start: f64,
pub end: f64,
pub text: String,
}
/// The captions of a track.
pub fn captions(client: &Client, track: &Caption) -> Result<Vec<Cue>> {
let url = format!("{}&fmt=json3", track.url);
let v: Value = serde_json::from_str(&client.get_text(&url, Kind::Web.profile().user_agent)?)?;
Ok(cues(&v))
}
fn cues(v: &Value) -> Vec<Cue> {
let mut out: Vec<Cue> = Vec::new();
for e in v["events"].as_array().into_iter().flatten() {
let Some(segs) = e["segs"].as_array() else { continue };
let text: String = segs.iter().filter_map(|s| s["utf8"].as_str()).collect();
let text = text.trim().to_string();
if text.is_empty() {
continue;
}
let start = e["tStartMs"].as_f64().unwrap_or(0.0) / 1000.0;
let end = start + e["dDurationMs"].as_f64().unwrap_or(3000.0) / 1000.0;
out.push(Cue { start, end, text });
}
// Automatic captions overlap (rolling lines): end each at the next start.
for i in 1..out.len() {
if out[i - 1].end > out[i].start {
out[i - 1].end = out[i].start.max(out[i - 1].start);
}
}
out
}
/// The caption text at `t` (s).
pub fn cue_at(cues: &[Cue], t: f64) -> &str {
let i = cues.partition_point(|c| c.start <= t);
match i.checked_sub(1).map(|i| &cues[i]) {
Some(c) if t < c.end => &c.text,
_ => "",
}
}
/// Signed in: puts the video into the account's watch history (what the
/// official apps do when playback starts).
pub fn mark_watched(client: &Client, video: &str) -> Result<()> {
let v = client.post("player", Kind::Tv, true, json!({ "videoId": video, "contentCheckOk": true, "racyCheckOk": true }))?;
let Some(url) = v["playbackTracking"]["videostatsPlaybackUrl"]["baseUrl"].as_str() else { return Ok(()) };
const CPN: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
let seed = super::now() ^ (std::process::id() as u64) << 20;
let cpn: String = (0..16).map(|i| CPN[((seed >> (i * 3)) as usize + i * 7) % CPN.len()] as char).collect();
let url = format!("{url}&ver=2&cpn={cpn}");
let mut req = client.agent.get(&url).header("User-Agent", Kind::Tv.profile().user_agent);
let bearer = client.bearer()?;
if let Some(b) = &bearer {
req = req.header("Authorization", &format!("Bearer {b}"));
}
req.call()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn caption_cues() {
let v = json!({ "events": [
{ "tStartMs": 0, "dDurationMs": 4000, "segs": [{ "utf8": "Helló" }, { "utf8": " világ" }] },
{ "tStartMs": 2000, "dDurationMs": 3000, "segs": [{ "utf8": "\n" }] },
{ "tStartMs": 3000, "dDurationMs": 2000, "segs": [{ "utf8": "Második" }] }
] });
let c = cues(&v);
assert_eq!(c.len(), 2);
assert_eq!(c[0].end, 3.0, "ends where the next starts");
assert_eq!(cue_at(&c, 1.0), "Helló világ");
assert_eq!(cue_at(&c, 3.5), "Második");
assert_eq!(cue_at(&c, 9.0), "");
}
#[test]
fn rss_entries() {
let xml = "<feed><author><name>Csatorna &amp; Co</name></author><entry><yt:videoId>abc</yt:videoId><title>Első &quot;rész&quot;</title><published>2026-10-01T10:00:00+00:00</published><link href=\"https://www.youtube.com/watch?v=abc\"/></entry></feed>";
let author = between(xml, "<author>", "</author>").and_then(|a| between(a, "<name>", "</name>")).map(unxml);
assert_eq!(author.as_deref(), Some("Csatorna & Co"));
let entry = xml.split("<entry>").nth(1).unwrap();
assert_eq!(between(entry, "<title>", "</title>").map(unxml).as_deref(), Some("Első \"rész\""));
}
}

143
src/yt/jsc.rs Normal file
View File

@@ -0,0 +1,143 @@
//! YouTube's "JS challenges": some clients (the TV app) get stream URLs
//! whose `n` parameter and signature must be transformed by functions in
//! YouTube's player script, or the download is throttled / refused.
//!
//! Like yt-dlp, this runs yt-dlp's solver (ejs/, Unlicense, from
//! github.com/yt-dlp/ejs) on the player script, here in an embedded QuickJS.
//! The script is preprocessed once per player version and cached in
//! `$HOME/.cache/youtube`, so later videos solve quickly.
//!
//! Only a fallback: the visionOS client gets direct URLs (see `stream`).
use std::collections::HashMap;
use std::path::PathBuf;
use anyhow::{Context as _, Result, anyhow, bail};
use serde_json::{Value, json};
use super::Client;
const LIB: &str = include_str!("../../ejs/yt.solver.lib.min.js");
const CORE: &str = include_str!("../../ejs/yt.solver.core.min.js");
const PAGE_UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
fn cache_dir() -> PathBuf {
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("LOCALAPPDATA")).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."));
home.join(".cache").join("youtube")
}
/// The current player version ("1a2b3c4d"), from the iframe API script.
pub fn player_id(client: &Client) -> Result<String> {
let page = client.get_text("https://www.youtube.com/iframe_api", PAGE_UA)?;
let page = page.replace("\\/", "/");
let at = page.find("/s/player/").map(|i| i + "/s/player/".len()).or_else(|| page.find("player/").map(|i| i + "player/".len()));
let id: String = at.map(|i| page[i..].chars().take_while(|c| c.is_ascii_hexdigit()).collect()).unwrap_or_default();
if id.len() < 8 {
bail!("nem található a YouTube lejátszó verziója");
}
Ok(id)
}
fn script(client: &Client, id: &str) -> Result<String> {
let path = cache_dir().join(format!("player-{id}.js"));
if let Ok(s) = std::fs::read_to_string(&path) {
return Ok(s);
}
let url = format!("https://www.youtube.com/s/player/{id}/player_ias.vflset/en_US/base.js");
let js = client.get_text(&url, PAGE_UA)?;
let _ = std::fs::create_dir_all(cache_dir());
// Old players are of no use: keep only this one.
if let Ok(dir) = std::fs::read_dir(cache_dir()) {
for e in dir.flatten() {
let n = e.file_name().to_string_lossy().to_string();
if (n.starts_with("player-") || n.starts_with("pre-")) && !n.contains(id) {
let _ = std::fs::remove_file(e.path());
}
}
}
let _ = std::fs::write(&path, &js);
Ok(js)
}
/// The player's signature timestamp (sent with TV player requests).
pub fn sts(client: &Client, id: &str) -> Result<u64> {
let js = script(client, id)?;
for key in ["signatureTimestamp", "sts"] {
let mut from = 0;
while let Some(i) = js[from..].find(key) {
let rest = js[from + i + key.len()..].trim_start();
if let Some(rest) = rest.strip_prefix(':') {
let digits: String = rest.trim_start().chars().take_while(char::is_ascii_digit).collect();
if digits.len() == 5 {
return Ok(digits.parse()?);
}
}
from += i + key.len();
}
}
bail!("nem található a lejátszó aláírás-időbélyege")
}
/// Solved challenges: input -> output, for `n` and for signatures.
#[derive(Debug, Default)]
pub struct Solved {
pub n: HashMap<String, String>,
pub sig: HashMap<String, String>,
}
/// Solves `n` and `sig` challenges with player `id`.
pub fn solve(client: &Client, id: &str, n: &[String], sig: &[String]) -> Result<Solved> {
if n.is_empty() && sig.is_empty() {
return Ok(Solved::default());
}
let pre_path = cache_dir().join(format!("pre-{id}.js"));
let requests = json!([{ "type": "n", "challenges": n }, { "type": "sig", "challenges": sig }]);
let input = match std::fs::read_to_string(&pre_path) {
Ok(pre) => json!({ "type": "preprocessed", "preprocessed_player": pre, "requests": requests }),
Err(_) => json!({ "type": "player", "player": script(client, id)?, "requests": requests, "output_preprocessed": true }),
};
let input = serde_json::to_string(&input)?;
// The parser recurses deeply: a thread with a big stack.
let out = std::thread::Builder::new()
.name("jsc".into())
.stack_size(64 << 20)
.spawn(move || run(&input))
.context("starting the solver")?
.join()
.map_err(|_| anyhow!("a megoldó összeomlott"))??;
let v: Value = serde_json::from_str(&out).context("the solver's answer")?;
if v["type"].as_str() == Some("error") {
bail!("a megoldó hibát adott: {}", v["error"].as_str().unwrap_or_default());
}
if let Some(pre) = v["preprocessed_player"].as_str() {
let _ = std::fs::write(&pre_path, pre);
}
let mut solved = Solved::default();
for (i, r) in v["responses"].as_array().into_iter().flatten().enumerate() {
if r["type"].as_str() != Some("result") {
log::warn!("jsc: {}", r["error"].as_str().unwrap_or_default());
continue;
}
let map: HashMap<String, String> = r["data"].as_object().map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect()).unwrap_or_default();
if i == 0 { solved.n = map } else { solved.sig = map }
}
Ok(solved)
}
fn run(input: &str) -> Result<String> {
use rquickjs::{CatchResultExt, Context, Runtime};
let rt = Runtime::new()?;
rt.set_memory_limit(1 << 30);
rt.set_max_stack_size(60 << 20);
let ctx = Context::full(&rt)?;
ctx.with(|ctx| -> Result<String> {
let err = |e: rquickjs::CaughtError| anyhow!("JS: {e}");
ctx.eval::<(), _>(LIB).catch(&ctx).map_err(err)?;
ctx.eval::<(), _>("Object.assign(globalThis, lib);").catch(&ctx).map_err(err)?;
ctx.eval::<(), _>(CORE).catch(&ctx).map_err(err)?;
ctx.globals().set("__fennecInput", input.to_string())?;
let out: String = ctx.eval("JSON.stringify(jsc(JSON.parse(__fennecInput)))").catch(&ctx).map_err(err)?;
Ok(out)
})
}

421
src/yt/mod.rs Normal file
View File

@@ -0,0 +1,421 @@
//! A YouTube client: YouTube's own internal API (InnerTube, the one its apps
//! use), no API key and no ads.
//!
//! - `parse`: turns any browse / search / next answer into shelves of cards.
//! - `auth`: sign-in with a code on another device (youtube.com/activate).
//! - `stream`: the video's formats -> a DASH manifest for GStreamer.
//! - `jsc`: yt-dlp's challenge solver (QuickJS) for clients that need it.
//! - `extras`: SponsorBlock, channel RSS feeds, captions.
//!
//! Every call blocks: run them off the UI thread (`task::spawn`).
//!
//! Which client asks what (as yt-dlp does in 2026, see `stream`):
//! - signed in: personal pages (home, subscriptions, history, own lists)
//! with the TV client (TVHTML5) and the account's OAuth token;
//! - public pages (search, channels, playlists, related videos) with the
//! web client, signed out;
//! - streams: the visionOS client (direct URLs), else the TV client with
//! the challenge solver.
pub mod auth;
pub mod extras;
pub mod jsc;
pub mod parse;
pub mod stream;
use std::io::Read;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use serde_json::{Value, json};
pub use parse::{Feed, Item, Shelf, Video};
const API: &str = "https://www.youtube.com/youtubei/v1";
/// An InnerTube client profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
/// The desktop web site (public pages).
Web,
/// The TV app (youtube.com/tv); takes the OAuth token.
Tv,
/// Apple Vision: stream URLs need no JavaScript.
VisionOs,
/// An older TV app (Samsung Tizen): streams with the challenge solver.
TvSamsung,
}
pub struct Profile {
pub name: &'static str,
pub id: u32,
pub version: &'static str,
pub user_agent: &'static str,
pub extra: &'static [(&'static str, &'static str)],
}
impl Kind {
pub fn profile(self) -> Profile {
match self {
Kind::Web => Profile {
name: "WEB",
id: 1,
version: "2.20260708.00.00",
user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36,gzip(gfe)",
extra: &[],
},
Kind::Tv => Profile {
name: "TVHTML5",
id: 7,
version: "7.20260707.07.00",
user_agent: "Mozilla/5.0 (ChromiumStylePlatform) Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (Unknown, Unknown)",
extra: &[],
},
Kind::VisionOs => Profile {
name: "VISIONOS",
id: 101,
version: "1.02",
user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.0 Safari/605.1.15",
extra: &[("deviceMake", "Apple"), ("deviceModel", "RealityDevice17,1"), ("osName", "visionOS"), ("osVersion", "26.5.23O471")],
},
Kind::TvSamsung => Profile {
name: "TVHTML5",
id: 7,
version: "5.20260707",
user_agent: "Mozilla/5.0 (SMART-TV; Linux; Tizen 2.4.0) AppleWebKit/538.1 (KHTML, like Gecko) Version/2.4.0 TV Safari/538.1",
extra: &[("deviceMake", "Samsung"), ("deviceModel", "UKS9800"), ("osName", "Tizen"), ("osVersion", "2.4.0")],
},
}
}
/// Takes the account's OAuth token.
fn authed(self) -> bool {
matches!(self, Kind::Tv | Kind::TvSamsung)
}
}
/// An error YouTube answered with.
#[derive(Debug)]
pub struct YtError {
pub status: u16,
pub message: String,
}
impl std::fmt::Display for YtError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "YouTube: {} ({})", self.message, self.status)
}
}
impl std::error::Error for YtError {}
/// A short Hungarian text for an error.
pub fn describe(e: &anyhow::Error) -> String {
if let Some(y) = e.downcast_ref::<YtError>() {
return match y.status {
401 | 403 if y.message.is_empty() => "A YouTube elutasította a kérést.".into(),
429 => "A YouTube most túl sok kérést kapott innen. Próbáld újra kicsit később.".into(),
_ if !y.message.is_empty() => y.message.clone(),
s => format!("A YouTube hibát jelzett ({s})."),
};
}
for cause in e.chain() {
if let Some(u) = cause.downcast_ref::<ureq::Error>() {
return match u {
ureq::Error::Timeout(_) => "A YouTube nem válaszolt időben.".into(),
ureq::Error::Io(_) | ureq::Error::ConnectionFailed | ureq::Error::HostNotFound => {
"Nincs internetkapcsolat, vagy a YouTube nem érhető el.".into()
}
other => format!("Hálózati hiba: {other}"),
};
}
}
format!("{e:#}")
}
/// The signed-in account's tokens.
#[derive(Debug, Clone, Default)]
pub struct Session {
pub refresh_token: String,
pub access_token: String,
/// Unix seconds.
pub expires: u64,
}
pub fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// Cheap to clone; usable from any thread.
#[derive(Clone)]
pub struct Client {
pub agent: ureq::Agent,
session: Arc<Mutex<Option<Session>>>,
visitor: Arc<Mutex<String>>,
/// Interface language and region ("hu", "HU").
pub hl: String,
pub gl: String,
}
impl Client {
pub fn new(refresh_token: Option<String>) -> Client {
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(30)))
.timeout_connect(Some(Duration::from_secs(8)))
.http_status_as_error(false)
.build()
.into();
let session = refresh_token.filter(|t| !t.is_empty()).map(|t| Session { refresh_token: t, ..Session::default() });
Client { agent, session: Arc::new(Mutex::new(session)), visitor: Arc::default(), hl: "hu".into(), gl: "HU".into() }
}
pub fn signed_in(&self) -> bool {
self.session.lock().unwrap().is_some()
}
pub fn set_session(&self, s: Option<Session>) {
*self.session.lock().unwrap() = s;
}
/// A valid access token (refreshed when old), or None when signed out.
pub fn bearer(&self) -> Result<Option<String>> {
let s = self.session.lock().unwrap().clone();
let Some(s) = s else { return Ok(None) };
if !s.access_token.is_empty() && s.expires > now() + 60 {
return Ok(Some(s.access_token));
}
let (token, expires_in) = auth::refresh(&self.agent, &s.refresh_token)?;
let mut guard = self.session.lock().unwrap();
if let Some(cur) = guard.as_mut() {
cur.access_token = token.clone();
cur.expires = now() + expires_in;
}
Ok(Some(token))
}
fn context(&self, kind: Kind) -> Value {
let p = kind.profile();
let mut client = json!({
"clientName": p.name,
"clientVersion": p.version,
"hl": self.hl,
"gl": self.gl,
"userAgent": p.user_agent,
});
for (k, v) in p.extra {
client[*k] = json!(v);
}
let visitor = self.visitor.lock().unwrap().clone();
if !visitor.is_empty() {
client["visitorData"] = json!(visitor);
}
json!({ "client": client, "user": { "lockedSafetyMode": false } })
}
/// POST youtubei/v1/`endpoint` as `kind`. `auth`: with the account's
/// token (when signed in and the client takes it).
pub fn post(&self, endpoint: &str, kind: Kind, auth: bool, body: Value) -> Result<Value> {
let p = kind.profile();
let mut body = body;
body["context"] = self.context(kind);
let bearer = if auth && kind.authed() { self.bearer()? } else { None };
let url = format!("{API}/{endpoint}?prettyPrint=false");
let mut req = self
.agent
.post(&url)
.header("User-Agent", p.user_agent)
.header("X-YouTube-Client-Name", &p.id.to_string())
.header("X-YouTube-Client-Version", p.version)
.header("Origin", "https://www.youtube.com");
let visitor = self.visitor.lock().unwrap().clone();
if !visitor.is_empty() {
req = req.header("X-Goog-Visitor-Id", &visitor);
}
if let Some(b) = &bearer {
req = req.header("Authorization", &format!("Bearer {b}"));
}
let resp = req.send_json(&body).with_context(|| endpoint.to_string())?;
let status = resp.status().as_u16();
let mut text = String::new();
resp.into_body().into_reader().take(48 << 20).read_to_string(&mut text)?;
let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
if !(200..300).contains(&status) {
let message = v["error"]["message"].as_str().unwrap_or_default().to_string();
if status == 401 && bearer.is_some() {
// The token was revoked or expired early: refresh once.
if let Some(s) = self.session.lock().unwrap().as_mut() {
s.access_token.clear();
}
}
return Err(YtError { status, message }.into());
}
if let Some(vd) = v["responseContext"]["visitorData"].as_str() {
let mut cur = self.visitor.lock().unwrap();
if cur.is_empty() {
*cur = vd.to_string();
}
}
Ok(v)
}
/// GET a page as text (feeds, captions, the player script).
pub fn get_text(&self, url: &str, user_agent: &str) -> Result<String> {
let resp = self.agent.get(url).header("User-Agent", user_agent).call().with_context(|| url.to_string())?;
let status = resp.status().as_u16();
let mut text = String::new();
resp.into_body().into_reader().take(32 << 20).read_to_string(&mut text)?;
if !(200..300).contains(&status) {
return Err(YtError { status, message: String::new() }.into());
}
Ok(text)
}
// ---- pages ----
fn browse_as(&self, id: &str, params: Option<&str>, personal: bool) -> Result<Feed> {
let kind = if personal && self.signed_in() { Kind::Tv } else { Kind::Web };
let mut body = json!({ "browseId": id });
if let Some(p) = params {
body["params"] = json!(p);
}
Ok(parse::feed(&self.post("browse", kind, personal, body)?))
}
/// The home feed (personal when signed in).
pub fn home(&self) -> Result<Feed> {
self.browse_as("FEwhat_to_watch", None, true)
}
/// Signed in: the subscriptions feed.
pub fn subscriptions(&self) -> Result<Feed> {
self.browse_as("FEsubscriptions", None, true)
}
/// Signed in: the account's watch history.
pub fn history(&self) -> Result<Feed> {
self.browse_as("FEhistory", None, true)
}
/// Signed in: the account's playlists (the TV's "Könyvtár").
pub fn library(&self) -> Result<Feed> {
match self.browse_as("FEmy_youtube", None, true) {
Ok(f) if !f.is_empty() => Ok(f),
_ => self.browse_as("FElibrary", None, true),
}
}
/// A playlist. `personal`: the account's own (WL, LL, private ones).
pub fn playlist(&self, id: &str, personal: bool) -> Result<Feed> {
self.browse_as(&format!("VL{id}"), None, personal)
}
/// A channel's videos (newest first).
pub fn channel(&self, id: &str) -> Result<Feed> {
// The "Videos" tab.
let mut f = self.browse_as(id, Some("EgZ2aWRlb3PyBgQKAjoA"), false)?;
if f.is_empty() {
f = self.browse_as(id, None, false)?;
}
Ok(f)
}
/// Signed in: whether the account follows `channel`.
pub fn is_subscribed(&self, channel: &str) -> Result<Option<bool>> {
if !self.signed_in() {
return Ok(None);
}
let v = self.post("browse", Kind::Tv, true, json!({ "browseId": channel }))?;
Ok(parse::find_key(&v, "subscribed").and_then(Value::as_bool))
}
pub fn subscribe(&self, channel: &str, on: bool) -> Result<()> {
let endpoint = if on { "subscription/subscribe" } else { "subscription/unsubscribe" };
self.post(endpoint, Kind::Tv, true, json!({ "channelIds": [channel] }))?;
Ok(())
}
pub fn search(&self, query: &str) -> Result<Feed> {
Ok(parse::feed(&self.post("search", Kind::Web, false, json!({ "query": query }))?))
}
/// This week's most watched videos for `query` (rows of a signed-out home).
pub fn popular_this_week(&self, query: &str) -> Result<Feed> {
// Sort: view count; filters: this week, videos.
Ok(parse::feed(&self.post("search", Kind::Web, false, json!({ "query": query, "params": "CAMSBAgDEAE%3D" }))?))
}
/// More of a feed: `token` from `Feed::more` or `Shelf::more`.
pub fn more(&self, token: &str, search: bool, personal: bool) -> Result<Feed> {
let kind = if personal && self.signed_in() { Kind::Tv } else { Kind::Web };
let endpoint = if search { "search" } else { "browse" };
Ok(parse::feed(&self.post(endpoint, kind, personal, json!({ "continuation": token }))?))
}
/// Videos to watch after `video` (the watch page's side list).
pub fn related(&self, video: &str, playlist: Option<&str>) -> Result<Feed> {
let mut body = json!({ "videoId": video });
if let Some(p) = playlist {
body["playlistId"] = json!(p);
}
let mut f = parse::feed(&self.post("next", Kind::Web, false, body)?);
for s in &mut f.shelves {
s.items.retain(|i| i.id() != video);
}
Ok(f)
}
/// Signed in: the account's name and picture.
pub fn account(&self) -> Result<(String, String)> {
let v = self.post("account/accounts_list", Kind::Tv, true, json!({}))?;
let name = parse::find_key(&v, "accountName").map(parse::text).unwrap_or_default();
let photo = parse::find_key(&v, "accountPhoto").map(parse::thumb).unwrap_or_default();
Ok((name, photo))
}
}
/// Against the real YouTube: `cargo test live -- --ignored --nocapture`.
#[cfg(test)]
mod live {
use super::*;
#[test]
#[ignore]
fn live_search_stream_and_solver() {
let c = Client::new(None);
let f = c.search("Kurzgesagt").unwrap();
let videos: Vec<&Video> = f.videos().filter(|v| !v.live && !v.short).collect();
println!("search: {} items, {} videos, more: {}", f.flat().len(), videos.len(), f.more.is_some());
for v in videos.iter().take(3) {
println!(" {} | {} | {} | {} | {}", v.id, v.title, v.channel, v.duration, v.meta);
}
let v = videos.first().expect("a video");
let p = stream::fetch(&c, &v.id).unwrap();
println!("stream: {} formats, H.264 {:?}, AV1 {:?}, captions {}", p.formats.len(), p.heights(stream::Codec::H264), p.heights(stream::Codec::Av1), p.captions.len());
for t in p.captions.iter().take(3) {
println!(" caption {} {} auto={}", t.lang, t.name, t.auto);
}
match extras::captions(&c, &p.captions[0]) {
Ok(cues) => println!("captions: {} cues, e.g. {:?}", cues.len(), cues.get(5).map(|c| &c.text)),
Err(e) => println!("captions: {e}"),
}
let seg = extras::sponsor_segments(&c, &v.id).unwrap();
println!("sponsorblock: {seg:?}");
let (uri, h) = p.uri(0, stream::Codec::H264).unwrap();
println!("uri {uri} ({h}p)");
let more = c.more(f.more.as_deref().unwrap(), true, false).unwrap();
println!("search page 2: {} items", more.flat().len());
let ch = c.channel(&v.channel_id).unwrap();
println!("channel: {:?}, {} videos", ch.header.as_ref().map(|h| (&h.title, &h.meta)), ch.videos().count());
let rel = c.related(&v.id, None).unwrap();
println!("related: {}", rel.videos().count());
let home = c.home().unwrap();
println!("home (signed out): {} shelves, {} items", home.shelves.len(), home.flat().len());
let pid = jsc::player_id(&c).unwrap();
let sts = jsc::sts(&c, &pid).unwrap();
let t = std::time::Instant::now();
let solved = jsc::solve(&c, &pid, &["ZdbaEdhagwAnBCO1".into()], &[]).unwrap();
println!("player {pid}, sts {sts}, n solved in {:?}: {:?}", t.elapsed(), solved.n);
}
}

831
src/yt/parse.rs Normal file
View File

@@ -0,0 +1,831 @@
//! Turns InnerTube answers into shelves of videos, channels and playlists.
//!
//! YouTube reshuffles its page layouts often and every client has its own
//! (web: videoRenderer / lockupViewModel; TV: tileRenderer). So instead of
//! following one layout, this walks the whole JSON tree: every known item
//! renderer becomes an item, every titled shelf around them becomes a
//! shelf, and continuation tokens are kept where they were found. Ad
//! renderers are skipped, so no ad ever shows up as a card.
use serde_json::Value;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Video {
pub id: String,
pub title: String,
pub channel: String,
pub channel_id: String,
pub thumb: String,
/// "12:34" (empty for live streams and premieres).
pub duration: String,
/// "1,2 E megtekintés · 3 napja"
pub meta: String,
/// Watched part (0..1), negative: unknown.
pub progress: f32,
pub live: bool,
pub short: bool,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Channel {
pub id: String,
pub title: String,
pub thumb: String,
pub meta: String,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Playlist {
pub id: String,
pub title: String,
pub thumb: String,
pub meta: String,
/// Mixes (RD…) have no playlist page: they start from this video.
pub first_video: String,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Item {
Video(Video),
Channel(Channel),
Playlist(Playlist),
}
impl Item {
pub fn id(&self) -> &str {
match self {
Item::Video(v) => &v.id,
Item::Channel(c) => &c.id,
Item::Playlist(p) => &p.id,
}
}
pub fn title(&self) -> &str {
match self {
Item::Video(v) => &v.title,
Item::Channel(c) => &c.title,
Item::Playlist(p) => &p.title,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Shelf {
pub title: String,
pub items: Vec<Item>,
/// Continuation token for more of this shelf.
pub more: Option<String>,
}
/// A channel's or playlist's own data.
#[derive(Debug, Clone, Default)]
pub struct Header {
pub title: String,
pub thumb: String,
pub meta: String,
}
#[derive(Debug, Clone, Default)]
pub struct Feed {
pub shelves: Vec<Shelf>,
/// Continuation token for more shelves / more of the main grid.
pub more: Option<String>,
pub header: Option<Header>,
}
impl Feed {
pub fn is_empty(&self) -> bool {
self.shelves.iter().all(|s| s.items.is_empty())
}
pub fn items(&self) -> impl Iterator<Item = &Item> {
self.shelves.iter().flat_map(|s| s.items.iter())
}
pub fn videos(&self) -> impl Iterator<Item = &Video> {
self.items().filter_map(|i| match i {
Item::Video(v) => Some(v),
_ => None,
})
}
/// Every item in one list (search results, a playlist), in order, once.
pub fn flat(&self) -> Vec<Item> {
let mut out: Vec<Item> = Vec::new();
for i in self.items() {
if !out.iter().any(|o| o.id() == i.id()) {
out.push(i.clone());
}
}
out
}
}
// ---------------------------------------------------------------------------- helpers
/// The text of a YouTube text object: a string, simpleText, runs, or a view
/// model's content.
pub fn text(v: &Value) -> String {
if let Some(s) = v.as_str() {
return s.to_string();
}
if let Some(s) = v["simpleText"].as_str() {
return s.to_string();
}
if let Some(runs) = v["runs"].as_array() {
return runs.iter().filter_map(|r| r["text"].as_str()).collect();
}
if let Some(s) = v["content"].as_str() {
return s.to_string();
}
if v["text"].is_object() || v["text"].is_string() {
return text(&v["text"]);
}
String::new()
}
/// The best picture of a thumbnail list (`{thumbnails: […]}`, `{sources:
/// […]}` or the list itself): the smallest one at least 400 px wide, else
/// the largest.
pub fn thumb(v: &Value) -> String {
let list = v["thumbnails"].as_array().or_else(|| v["sources"].as_array()).or_else(|| v["image"]["sources"].as_array()).or_else(|| v.as_array());
let Some(list) = list else { return String::new() };
let w = |t: &Value| t["width"].as_u64().unwrap_or(0);
let pick = list.iter().filter(|t| w(t) >= 400).min_by_key(|t| w(t)).or_else(|| list.iter().max_by_key(|t| w(t)));
let url = pick.and_then(|t| t["url"].as_str()).unwrap_or_default();
if let Some(rest) = url.strip_prefix("//") { format!("https://{rest}") } else { url.to_string() }
}
/// A video's picture when the answer has none.
pub fn video_thumb(id: &str) -> String {
format!("https://i.ytimg.com/vi/{id}/mqdefault.jpg")
}
/// The first value under `key`, anywhere below `v` (depth first).
pub fn find_key<'a>(v: &'a Value, key: &str) -> Option<&'a Value> {
match v {
Value::Object(m) => {
if let Some(x) = m.get(key) {
return Some(x);
}
m.values().find_map(|x| find_key(x, key))
}
Value::Array(a) => a.iter().find_map(|x| find_key(x, key)),
_ => None,
}
}
/// Every value under `key` below `v`.
pub fn find_all<'a>(v: &'a Value, key: &str, out: &mut Vec<&'a Value>) {
match v {
Value::Object(m) => {
for (k, x) in m {
if k == key {
out.push(x);
} else {
find_all(x, key, out);
}
}
}
Value::Array(a) => a.iter().for_each(|x| find_all(x, key, out)),
_ => {}
}
}
/// "12:34", "1:02:03"
pub fn is_time(s: &str) -> bool {
let s = s.trim();
s.contains(':') && s.chars().all(|c| c.is_ascii_digit() || c == ':') && s.len() <= 9
}
fn join(parts: &[String]) -> String {
parts.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ")
}
/// The first channel id (UC…) in a browse endpoint below `v`.
fn channel_id_in(v: &Value) -> String {
let mut all = Vec::new();
find_all(v, "browseEndpoint", &mut all);
all.iter().filter_map(|e| e["browseId"].as_str()).find(|id| id.starts_with("UC")).unwrap_or_default().to_string()
}
/// Duration, live flag and watched part from thumbnail overlays.
fn overlays(v: &Value) -> (String, bool, f32) {
let mut duration = String::new();
let mut live = false;
let mut status = Vec::new();
find_all(v, "thumbnailOverlayTimeStatusRenderer", &mut status);
for s in status {
let t = text(&s["text"]);
if s["style"].as_str() == Some("LIVE") {
live = true;
} else if duration.is_empty() && is_time(&t) {
duration = t;
}
}
let mut badges = Vec::new();
find_all(v, "thumbnailBadgeViewModel", &mut badges);
for b in badges {
let t = b["text"].as_str().unwrap_or_default().to_string();
let style = b["badgeStyle"].as_str().unwrap_or_default();
if style.contains("LIVE") || b["icon"].to_string().contains("LIVE") {
live = true;
} else if duration.is_empty() && is_time(&t) {
duration = t;
}
}
let progress = find_key(v, "percentDurationWatched")
.and_then(Value::as_f64)
.or_else(|| find_key(v, "startPercent").and_then(Value::as_f64))
.map(|p| (p / 100.0).clamp(0.0, 1.0) as f32)
.unwrap_or(-1.0);
(duration, live, progress)
}
// ---------------------------------------------------------------------------- item renderers
/// videoRenderer, gridVideoRenderer, compactVideoRenderer, playlistVideoRenderer…
fn classic_video(r: &Value) -> Option<Video> {
let id = r["videoId"].as_str()?.to_string();
let title = [&r["title"], &r["headline"]].iter().map(|t| text(t)).find(|t| !t.is_empty()).unwrap_or_default();
let byline = [&r["ownerText"], &r["shortBylineText"], &r["longBylineText"]].into_iter().find(|b| !text(b).is_empty()).cloned().unwrap_or(Value::Null);
let (mut duration, mut live, progress) = overlays(&r["thumbnailOverlays"]);
if duration.is_empty() {
let t = text(&r["lengthText"]);
if is_time(&t) {
duration = t;
}
}
let mut badges = Vec::new();
find_all(&r["badges"], "style", &mut badges);
if badges.iter().any(|b| b.as_str() == Some("BADGE_STYLE_TYPE_LIVE_NOW")) {
live = true;
}
let views = [&r["shortViewCountText"], &r["viewCountText"]].iter().map(|t| text(t)).find(|t| !t.is_empty()).unwrap_or_default();
let mut meta = join(&[views, text(&r["publishedTimeText"])]);
if meta.is_empty() {
meta = text(&r["videoInfo"]).replace(" • ", " · ");
}
let thumb = Some(thumb(&r["thumbnail"])).filter(|t| !t.is_empty()).unwrap_or_else(|| video_thumb(&id));
Some(Video {
channel: text(&byline),
channel_id: byline["runs"][0]["navigationEndpoint"]["browseEndpoint"]["browseId"].as_str().unwrap_or_default().to_string(),
id,
title,
thumb,
duration,
meta,
progress,
live,
short: false,
})
}
fn reel(r: &Value) -> Option<Video> {
let id = r["videoId"].as_str()?.to_string();
Some(Video {
title: text(&r["headline"]),
meta: text(&r["viewCountText"]),
thumb: Some(thumb(&r["thumbnail"])).filter(|t| !t.is_empty()).unwrap_or_else(|| video_thumb(&id)),
id,
progress: -1.0,
short: true,
..Video::default()
})
}
fn shorts_lockup(r: &Value) -> Option<Video> {
let id = find_key(r, "reelWatchEndpoint")
.and_then(|e| e["videoId"].as_str())
.or_else(|| r["entityId"].as_str().and_then(|e| e.strip_prefix("shorts-shelf-item-")))?
.to_string();
Some(Video {
title: text(&r["overlayMetadata"]["primaryText"]),
meta: text(&r["overlayMetadata"]["secondaryText"]),
thumb: Some(thumb(&r["thumbnail"])).filter(|t| !t.is_empty()).unwrap_or_else(|| video_thumb(&id)),
id,
progress: -1.0,
short: true,
..Video::default()
})
}
/// The TV app's tiles.
fn tile(r: &Value) -> Option<Item> {
let kind = r["contentType"].as_str().unwrap_or_default();
let md = &r["metadata"]["tileMetadataRenderer"];
let title = text(&md["title"]);
let lines: Vec<String> = md["lines"]
.as_array()
.map(|ls| {
ls.iter()
.map(|l| {
let parts: Vec<String> = l["lineRenderer"]["items"].as_array().map(|it| it.iter().map(|i| text(&i["lineItemRenderer"]["text"])).collect()).unwrap_or_default();
parts.into_iter().map(|p| p.trim().to_string()).filter(|p| !p.is_empty() && p != "•").collect::<Vec<_>>().join(" · ")
})
.filter(|l| !l.is_empty())
.collect()
})
.unwrap_or_default();
let header = &r["header"]["tileHeaderRenderer"];
let pic = thumb(&header["thumbnail"]);
let select = &r["onSelectCommand"];
match kind {
"TILE_CONTENT_TYPE_CHANNEL" => {
let id = select["browseEndpoint"]["browseId"].as_str().or_else(|| r["contentId"].as_str())?.to_string();
Some(Item::Channel(Channel { id, title, thumb: pic, meta: join(&lines) }))
}
"TILE_CONTENT_TYPE_PLAYLIST" => {
let id = select["watchEndpoint"]["playlistId"]
.as_str()
.or_else(|| select["browseEndpoint"]["browseId"].as_str().map(|b| b.strip_prefix("VL").unwrap_or(b)))
.or_else(|| r["contentId"].as_str())?
.to_string();
let first = select["watchEndpoint"]["videoId"].as_str().unwrap_or_default().to_string();
Some(Item::Playlist(Playlist { id, title, thumb: pic, meta: join(&lines), first_video: first }))
}
_ => {
let id = r["contentId"].as_str().or_else(|| select["watchEndpoint"]["videoId"].as_str())?.to_string();
if select["browseEndpoint"].is_object() && select["watchEndpoint"].is_null() && !kind.contains("VIDEO") && !kind.contains("SHORTS") {
return None;
}
let (duration, live, progress) = overlays(&header["thumbnailOverlays"]);
let mut lines = lines.into_iter();
Some(Item::Video(Video {
thumb: if pic.is_empty() { video_thumb(&id) } else { pic },
id,
title,
channel: lines.next().unwrap_or_default(),
channel_id: channel_id_in(&r["menu"]),
meta: lines.collect::<Vec<_>>().join(" · "),
duration,
progress,
live,
short: kind.contains("SHORTS"),
}))
}
}
}
/// The web's newer lockups (videos, playlists, mixes).
fn lockup(r: &Value) -> Option<Item> {
let kind = r["contentType"].as_str().unwrap_or_default();
let id = r["contentId"].as_str()?.to_string();
let md = &r["metadata"]["lockupMetadataViewModel"];
let title = text(&md["title"]);
let rows: Vec<String> = md["metadata"]["contentMetadataViewModel"]["metadataRows"]
.as_array()
.map(|rows| {
rows.iter()
.map(|row| {
let parts: Vec<String> = row["metadataParts"].as_array().map(|ps| ps.iter().map(|p| text(&p["text"])).collect()).unwrap_or_default();
join(&parts)
})
.filter(|r| !r.is_empty())
.collect()
})
.unwrap_or_default();
let image = &r["contentImage"];
let pic_node = if image["collectionThumbnailViewModel"].is_object() {
&image["collectionThumbnailViewModel"]["primaryThumbnail"]["thumbnailViewModel"]["image"]
} else {
&image["thumbnailViewModel"]["image"]
};
let pic = thumb(pic_node);
let (duration, live, progress) = overlays(image);
if kind.contains("PLAYLIST") || kind.contains("ALBUM") || kind.contains("PODCAST") || kind.contains("MIX") {
let mut badges = Vec::new();
find_all(image, "thumbnailBadgeViewModel", &mut badges);
let count = badges.iter().filter_map(|b| b["text"].as_str()).find(|t| !is_time(t)).unwrap_or_default().to_string();
let first = find_key(&r["rendererContext"], "watchEndpoint").and_then(|w| w["videoId"].as_str()).unwrap_or_default().to_string();
let mut meta = rows.clone();
meta.insert(0, count);
return Some(Item::Playlist(Playlist { id, title, thumb: pic, meta: join(&meta), first_video: first }));
}
if !kind.is_empty() && !kind.contains("VIDEO") {
return None;
}
let mut rows = rows.into_iter();
Some(Item::Video(Video {
thumb: if pic.is_empty() { video_thumb(&id) } else { pic },
id,
title,
channel: rows.next().unwrap_or_default(),
channel_id: channel_id_in(md),
meta: rows.collect::<Vec<_>>().join(" · "),
duration,
progress,
live,
short: false,
}))
}
fn channel(r: &Value) -> Option<Item> {
let id = r["channelId"].as_str()?.to_string();
let meta = [&r["videoCountText"], &r["subscriberCountText"]].iter().map(|t| text(t)).filter(|t| !t.is_empty()).collect::<Vec<_>>();
Some(Item::Channel(Channel { id, title: text(&r["title"]), thumb: thumb(&r["thumbnail"]), meta: join(&meta) }))
}
fn playlist(r: &Value) -> Option<Item> {
let id = r["playlistId"].as_str()?.to_string();
let pic = [&r["thumbnail"], &r["thumbnails"][0]].iter().map(|t| thumb(t)).find(|t| !t.is_empty()).or_else(|| find_key(r, "thumbnails").map(|t| thumb(&serde_json::json!({ "thumbnails": t })))).unwrap_or_default();
let count = [&r["videoCountText"], &r["videoCountShortText"]].iter().map(|t| text(t)).find(|t| !t.is_empty()).or_else(|| r["videoCount"].as_str().map(|c| format!("{c} videó"))).unwrap_or_default();
let first = find_key(&r["navigationEndpoint"], "videoId").and_then(Value::as_str).unwrap_or_default().to_string();
let by = text(&r["shortBylineText"]);
Some(Item::Playlist(Playlist { id, title: text(&r["title"]), thumb: pic, meta: join(&[count, by]), first_video: first }))
}
// ---------------------------------------------------------------------------- the walk
/// Never walked: ads, menus and page furniture.
const SKIP: &[&str] = &[
"adSlotRenderer",
"adSlotAndLayoutMetadata",
"promotedSparklesWebRenderer",
"promotedVideoRenderer",
"compactPromotedVideoRenderer",
"searchPyvRenderer",
"inFeedAdLayoutRenderer",
"bannerPromoRenderer",
"statementBannerRenderer",
"brandVideoShelfRenderer",
"brandVideoSingletonRenderer",
"carouselAdRenderer",
"displayAdRenderer",
"adPlacements",
"playerAds",
"topbar",
"sidebar",
"header",
"microformat",
"metadata",
"frameworkUpdates",
"engagementPanels",
"playerOverlays",
"overlay",
"menu",
"autoplay",
"conversationBar",
"responseContext",
];
/// Containers that start a shelf when they have a title.
const SHELVES: &[&str] = &[
"shelfRenderer",
"richShelfRenderer",
"reelShelfRenderer",
"gridRenderer",
"itemSectionRenderer",
"horizontalCardListRenderer",
"expandedShelfContentsRenderer",
];
#[derive(Default)]
struct Builder {
shelves: Vec<Shelf>,
open: Vec<usize>,
loose: Option<usize>,
more: Option<String>,
}
impl Builder {
fn current(&mut self) -> usize {
if let Some(&i) = self.open.last() {
return i;
}
match self.loose {
Some(i) => i,
None => {
self.shelves.push(Shelf::default());
let i = self.shelves.len() - 1;
self.loose = Some(i);
i
}
}
}
fn push(&mut self, item: Item) {
if item.id().is_empty() {
return;
}
let i = self.current();
let s = &mut self.shelves[i];
if !s.items.iter().any(|x| x.id() == item.id()) {
s.items.push(item);
}
}
fn token(&mut self, t: &str) {
if t.is_empty() {
return;
}
match self.open.last() {
Some(&i) => {
if self.shelves[i].more.is_none() {
self.shelves[i].more = Some(t.to_string());
}
}
None => {
if self.more.is_none() {
self.more = Some(t.to_string());
}
}
}
}
}
fn shelf_title(r: &Value) -> String {
let t = text(&r["title"]);
if !t.is_empty() {
return t;
}
for h in [&r["header"], &r["headerRenderer"]] {
if let Some(t) = find_key(h, "title").map(text).filter(|t| !t.is_empty()) {
return t;
}
}
String::new()
}
fn walk(v: &Value, b: &mut Builder) {
match v {
Value::Array(a) => a.iter().for_each(|x| walk(x, b)),
Value::Object(m) => {
for (k, x) in m {
let k = k.as_str();
if SKIP.contains(&k) {
continue;
}
match k {
"videoRenderer" | "gridVideoRenderer" | "compactVideoRenderer" | "playlistVideoRenderer" | "playlistPanelVideoRenderer" | "videoWithContextRenderer" => {
if let Some(v) = classic_video(x) {
b.push(Item::Video(v));
}
}
"reelItemRenderer" => {
if let Some(v) = reel(x) {
b.push(Item::Video(v));
}
}
"shortsLockupViewModel" => {
if let Some(v) = shorts_lockup(x) {
b.push(Item::Video(v));
}
}
"tileRenderer" => {
if let Some(i) = tile(x) {
b.push(i);
}
}
"lockupViewModel" => {
if let Some(i) = lockup(x) {
b.push(i);
}
}
"channelRenderer" | "gridChannelRenderer" | "compactChannelRenderer" => {
if let Some(i) = channel(x) {
b.push(i);
}
}
"playlistRenderer" | "gridPlaylistRenderer" | "compactPlaylistRenderer" | "radioRenderer" | "compactRadioRenderer" => {
if let Some(i) = playlist(x) {
b.push(i);
}
}
"continuationItemRenderer" => {
if let Some(t) = find_key(x, "continuationCommand").and_then(|c| c["token"].as_str()) {
b.token(t);
}
}
"nextContinuationData" => {
if let Some(t) = x["continuation"].as_str() {
b.token(t);
}
}
k if SHELVES.contains(&k) => {
let title = shelf_title(x);
if title.is_empty() {
walk(x, b);
} else {
b.shelves.push(Shelf { title, ..Shelf::default() });
b.open.push(b.shelves.len() - 1);
b.loose = None;
walk(x, b);
b.open.pop();
b.loose = None;
}
}
_ => walk(x, b),
}
}
}
_ => {}
}
}
fn header(v: &Value) -> Option<Header> {
let md = &v["metadata"];
let mut h = if let Some(c) = find_key(md, "channelMetadataRenderer") {
Header { title: text(&c["title"]), thumb: thumb(&c["avatar"]), meta: String::new() }
} else if let Some(p) = find_key(md, "playlistMetadataRenderer") {
Header { title: text(&p["title"]), ..Header::default() }
} else {
let hd = &v["header"];
let title = find_key(hd, "title").map(text).unwrap_or_default();
if title.is_empty() {
return None;
}
Header { title, ..Header::default() }
};
// Subscribers, video count: the header's metadata rows (any layout).
let hd = &v["header"];
let mut parts: Vec<String> = Vec::new();
for key in ["subscriberCountText", "videosCountText", "numVideosText", "stats"] {
if let Some(t) = find_key(hd, key) {
let t = if t.is_array() { t.as_array().unwrap().iter().map(text).collect::<Vec<_>>().join(" · ") } else { text(t) };
if !t.is_empty() {
parts.push(t);
}
}
}
if parts.is_empty() {
let mut rows = Vec::new();
find_all(hd, "metadataParts", &mut rows);
for r in rows {
for p in r.as_array().into_iter().flatten() {
let t = text(&p["text"]);
if !t.is_empty() && !t.starts_with('@') {
parts.push(t);
}
}
}
}
if h.thumb.is_empty() {
if let Some(a) = find_key(hd, "avatarViewModel") {
h.thumb = thumb(&a["image"]);
}
}
h.meta = join(&parts);
Some(h)
}
/// Any browse / search / next answer (or a continuation of one).
pub fn feed(v: &Value) -> Feed {
let mut b = Builder::default();
walk(v, &mut b);
// Untitled bits (a grid interrupted by a shelf) become one list.
let mut shelves: Vec<Shelf> = Vec::new();
let mut loose: Option<usize> = None;
for s in b.shelves.into_iter().filter(|s| !s.items.is_empty()) {
if s.title.is_empty() {
match loose {
Some(i) => {
let main: &mut Shelf = &mut shelves[i];
for it in s.items {
if !main.items.iter().any(|x| x.id() == it.id()) {
main.items.push(it);
}
}
if main.more.is_none() {
main.more = s.more;
}
}
None => {
loose = Some(shelves.len());
shelves.push(s);
}
}
} else {
shelves.push(s);
}
}
Feed { shelves, more: b.more, header: header(v) }
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn web_search_without_ads() {
let v = json!({
"contents": { "twoColumnSearchResultsRenderer": { "primaryContents": { "sectionListRenderer": { "contents": [
{ "itemSectionRenderer": { "contents": [
{ "adSlotRenderer": { "content": { "videoRenderer": { "videoId": "AD" } } } },
{ "videoRenderer": {
"videoId": "abc",
"title": { "runs": [{ "text": "Egy videó" }] },
"ownerText": { "runs": [{ "text": "Csatorna", "navigationEndpoint": { "browseEndpoint": { "browseId": "UCx" } } }] },
"lengthText": { "simpleText": "12:34" },
"viewCountText": { "simpleText": "1,2 E megtekintés" },
"publishedTimeText": { "simpleText": "3 napja" },
"thumbnail": { "thumbnails": [{ "url": "https://i.ytimg.com/a.jpg", "width": 360 }, { "url": "https://i.ytimg.com/b.jpg", "width": 720 }] }
} },
{ "channelRenderer": { "channelId": "UCy", "title": { "simpleText": "Másik" }, "thumbnail": { "thumbnails": [{ "url": "//yt3.ggpht.com/x", "width": 88 }] } } }
] } },
{ "continuationItemRenderer": { "continuationEndpoint": { "continuationCommand": { "token": "NEXT" } } } }
] } } } }
});
let f = feed(&v);
let items = f.flat();
assert_eq!(items.len(), 2, "the ad is gone");
let Item::Video(vid) = &items[0] else { panic!() };
assert_eq!(vid.title, "Egy videó");
assert_eq!(vid.channel_id, "UCx");
assert_eq!(vid.duration, "12:34");
assert_eq!(vid.meta, "1,2 E megtekintés · 3 napja");
assert_eq!(vid.thumb, "https://i.ytimg.com/b.jpg");
let Item::Channel(ch) = &items[1] else { panic!() };
assert_eq!(ch.thumb, "https://yt3.ggpht.com/x");
assert_eq!(f.more.as_deref(), Some("NEXT"));
}
#[test]
fn tv_shelves_and_tiles() {
let tile = |id: &str| {
json!({ "tileRenderer": {
"contentId": id, "contentType": "TILE_CONTENT_TYPE_VIDEO",
"header": { "tileHeaderRenderer": {
"thumbnail": { "thumbnails": [{ "url": "https://i.ytimg.com/t.jpg", "width": 480 }] },
"thumbnailOverlays": [
{ "thumbnailOverlayTimeStatusRenderer": { "text": { "simpleText": "4:05" }, "style": "DEFAULT" } },
{ "thumbnailOverlayResumePlaybackRenderer": { "percentDurationWatched": 50 } }
] } },
"metadata": { "tileMetadataRenderer": {
"title": { "simpleText": format!("Videó {id}") },
"lines": [
{ "lineRenderer": { "items": [{ "lineItemRenderer": { "text": { "runs": [{ "text": "Csatorna" }] } } }] } },
{ "lineRenderer": { "items": [
{ "lineItemRenderer": { "text": { "simpleText": "10 E megtekintés" } } },
{ "lineItemRenderer": { "text": { "simpleText": "•" } } },
{ "lineItemRenderer": { "text": { "simpleText": "1 hete" } } }
] } }
] } },
"onSelectCommand": { "watchEndpoint": { "videoId": id } }
} })
};
let v = json!({ "contents": { "tvBrowseRenderer": { "content": { "tvSurfaceContentRenderer": { "content": { "sectionListRenderer": {
"contents": [
{ "shelfRenderer": {
"headerRenderer": { "shelfHeaderRenderer": { "title": { "runs": [{ "text": "Ajánlott" }] } } },
"content": { "horizontalListRenderer": { "items": [tile("a"), tile("b")], "continuations": [{ "nextContinuationData": { "continuation": "MORE-A" } }] } }
} },
{ "shelfRenderer": {
"headerRenderer": { "shelfHeaderRenderer": { "title": { "simpleText": "Zene" } } },
"content": { "horizontalListRenderer": { "items": [tile("c")] } }
} }
],
"continuations": [{ "nextContinuationData": { "continuation": "MORE-SHELVES" } }]
} } } } } } });
let f = feed(&v);
assert_eq!(f.shelves.len(), 2);
assert_eq!(f.shelves[0].title, "Ajánlott");
assert_eq!(f.shelves[0].more.as_deref(), Some("MORE-A"));
assert_eq!(f.more.as_deref(), Some("MORE-SHELVES"));
let Item::Video(a) = &f.shelves[0].items[0] else { panic!() };
assert_eq!((a.channel.as_str(), a.meta.as_str(), a.duration.as_str()), ("Csatorna", "10 E megtekintés · 1 hete", "4:05"));
assert_eq!(a.progress, 0.5);
}
#[test]
fn lockups() {
let v = json!({ "contents": { "richGridRenderer": { "contents": [
{ "richItemRenderer": { "content": { "lockupViewModel": {
"contentId": "vid1", "contentType": "LOCKUP_CONTENT_TYPE_VIDEO",
"contentImage": { "thumbnailViewModel": {
"image": { "sources": [{ "url": "https://i.ytimg.com/l.jpg", "width": 480 }] },
"overlays": [{ "thumbnailBottomOverlayViewModel": { "badges": [{ "thumbnailBadgeViewModel": { "text": "1:02:03" } }] } }]
} },
"metadata": { "lockupMetadataViewModel": {
"title": { "content": "Hosszú videó" },
"metadata": { "contentMetadataViewModel": { "metadataRows": [
{ "metadataParts": [{ "text": { "content": "Csatorna", "commandRuns": [{ "onTap": { "innertubeCommand": { "browseEndpoint": { "browseId": "UCz" } } } }] } }] },
{ "metadataParts": [{ "text": { "content": "5 M megtekintés" } }, { "text": { "content": "2 éve" } }] }
] } }
} }
} } } },
{ "richSectionRenderer": { "content": { "richShelfRenderer": { "title": { "runs": [{ "text": "Shorts" }] }, "contents": [
{ "richItemRenderer": { "content": { "shortsLockupViewModel": {
"entityId": "shorts-shelf-item-s1",
"overlayMetadata": { "primaryText": { "content": "Rövid" }, "secondaryText": { "content": "1 M megtekintés" } }
} } } }
] } } } },
{ "richItemRenderer": { "content": { "lockupViewModel": {
"contentId": "PLx", "contentType": "LOCKUP_CONTENT_TYPE_PLAYLIST",
"contentImage": { "collectionThumbnailViewModel": { "primaryThumbnail": { "thumbnailViewModel": {
"image": { "sources": [{ "url": "https://i.ytimg.com/p.jpg", "width": 480 }] },
"overlays": [{ "thumbnailOverlayBadgeViewModel": { "thumbnailBadges": [{ "thumbnailBadgeViewModel": { "text": "25 videó" } }] } }]
} } } },
"metadata": { "lockupMetadataViewModel": { "title": { "content": "Lista" } } },
"rendererContext": { "commandContext": { "onTap": { "innertubeCommand": { "watchEndpoint": { "videoId": "first", "playlistId": "PLx" } } } } }
} } } }
] } } });
let f = feed(&v);
assert_eq!(f.shelves.len(), 2, "the grid around the Shorts shelf is one list");
assert_eq!(f.shelves[0].items.len(), 2);
let Item::Video(a) = &f.shelves[0].items[0] else { panic!() };
assert_eq!((a.channel_id.as_str(), a.duration.as_str(), a.meta.as_str()), ("UCz", "1:02:03", "5 M megtekintés · 2 éve"));
let Item::Playlist(p) = &f.shelves[0].items[1] else { panic!() };
assert_eq!((p.meta.as_str(), p.first_video.as_str()), ("25 videó", "first"));
assert_eq!(f.shelves[1].title, "Shorts");
let Item::Video(s) = &f.shelves[1].items[0] else { panic!() };
assert!(s.short && s.id == "s1");
}
}

515
src/yt/stream.rs Normal file
View File

@@ -0,0 +1,515 @@
//! From a video id to something GStreamer plays.
//!
//! YouTube serves video and audio separately (adaptive formats). For a
//! normal video this writes a small DASH manifest (MPD) next to the app,
//! with the chosen video quality(ies) and one audio track, each pointing at
//! its googlevideo URL with byte ranges (SegmentBase); GStreamer's
//! dashdemux plays it. Live streams play their HLS playlist directly.
//!
//! Which client (as yt-dlp's defaults in 2026):
//! 1. visionOS: direct URLs, no JavaScript, no PO token;
//! 2. else the TV app (Samsung Tizen), signed in when the user is, with the
//! challenge solver (`jsc`) for the URLs' signature and `n` parameter.
//!
//! Ads: the player answer lists them separately (adPlacements); they are
//! simply never played.
use std::collections::HashSet;
use std::fmt::Write as _;
use anyhow::{Result, bail};
use serde_json::{Value, json};
use super::{Client, Kind, jsc, parse};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Codec {
/// H.264: hardware-decoded everywhere (the Raspberry Pi too), up to 1080p.
H264,
/// AV1: up to 4K/8K, needs a newer GPU.
Av1,
}
impl Codec {
pub fn from_key(k: &str) -> Codec {
if k == "av1" { Codec::Av1 } else { Codec::H264 }
}
fn prefix(self) -> &'static str {
match self {
Codec::H264 => "avc1",
Codec::Av1 => "av01",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Format {
pub itag: u64,
pub url: String,
/// "video/mp4"
pub mime: String,
/// "avc1.640028"
pub codecs: String,
pub bitrate: u64,
pub width: u64,
pub height: u64,
pub fps: u64,
pub init: Option<(u64, u64)>,
pub index: Option<(u64, u64)>,
pub audio: bool,
pub default_audio: bool,
pub audio_track: String,
pub drc: bool,
pub sample_rate: u64,
pub channels: u64,
/// Signature challenge and its query parameter (signatureCipher).
s: Option<(String, String)>,
}
#[derive(Debug, Clone)]
pub struct Caption {
pub lang: String,
pub name: String,
pub url: String,
/// Automatic (speech recognition).
pub auto: bool,
}
#[derive(Debug, Clone, Default)]
pub struct Details {
pub id: String,
pub title: String,
pub channel: String,
pub channel_id: String,
pub length: f64,
pub views: String,
pub live: bool,
}
#[derive(Debug, Clone)]
pub struct Playable {
pub details: Details,
pub formats: Vec<Format>,
pub hls: Option<String>,
pub captions: Vec<Caption>,
pub user_agent: &'static str,
}
fn context_body(id: &str, sts: Option<u64>) -> Value {
let mut ctx = json!({ "html5Preference": "HTML5_PREF_WANTS" });
if let Some(s) = sts {
ctx["signatureTimestamp"] = json!(s);
}
json!({
"videoId": id,
"playbackContext": { "contentPlaybackContext": ctx },
"contentCheckOk": true,
"racyCheckOk": true,
})
}
/// The video's details and formats.
pub fn fetch(client: &Client, id: &str) -> Result<Playable> {
let mut why = String::new();
match client.post("player", Kind::VisionOs, false, context_body(id, None)) {
Ok(v) => match parse_player(&v, Kind::VisionOs) {
Ok(p) if p.usable() => return Ok(p),
Ok(_) => why = "nincs lejátszható formátum".into(),
Err(e) => why = e,
},
Err(e) => log::warn!("visionos player: {e:#}"),
}
log::info!("visionos client: {why}; trying the TV client");
let pid = jsc::player_id(client)?;
let sts = jsc::sts(client, &pid).ok();
let v = client.post("player", Kind::TvSamsung, true, context_body(id, sts))?;
let mut p = match parse_player(&v, Kind::TvSamsung) {
Ok(p) => p,
Err(e) => bail!(if e.is_empty() { why } else { e }),
};
solve(client, &pid, &mut p)?;
if !p.usable() {
bail!("Ehhez a videóhoz nem kaptunk lejátszható formátumot.");
}
Ok(p)
}
impl Playable {
fn usable(&self) -> bool {
self.hls.is_some() && self.details.live || (self.formats.iter().any(|f| !f.audio && !f.url.is_empty()) && self.formats.iter().any(|f| f.audio && !f.url.is_empty()))
}
/// Heights (descending) of `codec`'s video formats.
pub fn heights(&self, codec: Codec) -> Vec<u64> {
let mut h: Vec<u64> = self.video(codec).iter().map(|f| f.height).collect();
h.sort_unstable_by(|a, b| b.cmp(a));
h.dedup();
h
}
/// `codec`'s playable video formats, else H.264's.
fn video(&self, codec: Codec) -> Vec<&Format> {
let of = |c: Codec| -> Vec<&Format> {
self.formats.iter().filter(|f| !f.audio && f.mime == "video/mp4" && f.codecs.starts_with(c.prefix()) && f.init.is_some() && f.index.is_some() && !f.url.is_empty()).collect()
};
let v = of(codec);
if v.is_empty() && codec != Codec::H264 { of(Codec::H264) } else { v }
}
fn audio(&self) -> Option<&Format> {
let list: Vec<&Format> = self.formats.iter().filter(|f| f.audio && f.mime == "audio/mp4" && f.init.is_some() && f.index.is_some() && !f.url.is_empty()).collect();
// The original language (not a dub), without dynamic range compression.
let original = |f: &Format| f.audio_track.is_empty() || f.default_audio;
let best = |keep: &dyn Fn(&Format) -> bool| list.iter().copied().filter(|f| keep(f)).max_by_key(|f| f.bitrate);
best(&|f| original(f) && !f.drc).or_else(|| best(&|f| original(f))).or_else(|| best(&|_| true))
}
/// What to give GStreamer: the best quality up to `max_height` (0: up
/// to 1080p). One quality only: GStreamer's adaptive DASH starts at the
/// lowest one (144p) and climbs slowly. Returns the URI and the height.
pub fn uri(&self, max_height: u64, codec: Codec) -> Result<(String, u64)> {
if self.details.live {
if let Some(h) = &self.hls {
return Ok((h.clone(), 0));
}
}
let max = if max_height == 0 { 1080 } else { max_height };
let all = self.video(codec);
if all.is_empty() {
match &self.hls {
Some(h) => return Ok((h.clone(), 0)),
None => bail!("Nincs lejátszható videóformátum."),
}
}
// One format per height: the highest bitrate (60 fps when there is).
let mut by_height: Vec<&Format> = Vec::new();
let mut sorted = all.clone();
sorted.sort_by(|a, b| b.height.cmp(&a.height).then(b.fps.cmp(&a.fps)).then(b.bitrate.cmp(&a.bitrate)));
let mut seen = HashSet::new();
for f in sorted {
if seen.insert(f.height) {
by_height.push(f);
}
}
let fit: Vec<&Format> = by_height.iter().filter(|f| f.height <= max).copied().collect();
let fit = if fit.is_empty() { vec![*by_height.last().unwrap()] } else { fit };
let chosen: Vec<&Format> = vec![fit[0]];
let audio = self.audio().ok_or_else(|| anyhow::anyhow!("Nincs hangsáv."))?;
let mpd = mpd(&chosen, audio, self.details.length);
let path = std::env::temp_dir().join(format!("youtube-{}.mpd", self.details.id));
std::fs::write(&path, mpd)?;
let p = path.to_string_lossy().replace('\\', "/");
let uri = if p.starts_with('/') { format!("file://{p}") } else { format!("file:///{p}") };
Ok((uri, chosen[0].height))
}
}
fn xml(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
fn mpd(video: &[&Format], audio: &Format, length: f64) -> String {
let dur = format!("PT{:.3}S", length.max(1.0));
let mut s = String::new();
let _ = writeln!(s, r#"<?xml version="1.0" encoding="UTF-8"?>"#);
let _ = writeln!(
s,
r#"<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011" type="static" mediaPresentationDuration="{dur}" minBufferTime="PT2S">"#
);
let _ = writeln!(s, r#"<Period id="0" start="PT0S" duration="{dur}">"#);
let _ = writeln!(s, r#"<AdaptationSet id="0" contentType="video" mimeType="video/mp4" subsegmentAlignment="true" subsegmentStartsWithSAP="1">"#);
for f in video {
let fps = if f.fps > 0 { format!(r#" frameRate="{}""#, f.fps) } else { String::new() };
let _ = writeln!(s, r#"<Representation id="{}" codecs="{}" bandwidth="{}" width="{}" height="{}"{fps}>"#, f.itag, xml(&f.codecs), f.bitrate.max(1), f.width, f.height);
rep_body(&mut s, f);
}
let _ = writeln!(s, "</AdaptationSet>");
let _ = writeln!(s, r#"<AdaptationSet id="1" contentType="audio" mimeType="audio/mp4" subsegmentAlignment="true" subsegmentStartsWithSAP="1">"#);
let _ = writeln!(
s,
r#"<Representation id="{}" codecs="{}" bandwidth="{}" audioSamplingRate="{}">"#,
audio.itag,
xml(&audio.codecs),
audio.bitrate.max(1),
if audio.sample_rate > 0 { audio.sample_rate } else { 44100 }
);
let _ = writeln!(
s,
r#"<AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="{}"/>"#,
if audio.channels > 0 { audio.channels } else { 2 }
);
rep_body(&mut s, audio);
let _ = writeln!(s, "</AdaptationSet>\n</Period>\n</MPD>");
s
}
fn rep_body(s: &mut String, f: &Format) {
let (i0, i1) = f.init.unwrap_or_default();
let (x0, x1) = f.index.unwrap_or_default();
let _ = writeln!(s, "<BaseURL>{}</BaseURL>", xml(&f.url));
let _ = writeln!(s, r#"<SegmentBase indexRange="{x0}-{x1}" indexRangeExact="true"><Initialization range="{i0}-{i1}"/></SegmentBase>"#);
let _ = writeln!(s, "</Representation>");
}
fn range(v: &Value) -> Option<(u64, u64)> {
let a = v["start"].as_str()?.parse().ok()?;
let b = v["end"].as_str()?.parse().ok()?;
Some((a, b))
}
/// The player answer: details, formats, captions; Err(reason) when YouTube
/// won't play the video for this client.
fn parse_player(v: &Value, kind: Kind) -> std::result::Result<Playable, String> {
let status = v["playabilityStatus"]["status"].as_str().unwrap_or_default();
if status != "OK" {
let reason = parse::text(&v["playabilityStatus"]["reason"]);
let sub = parse::find_key(&v["playabilityStatus"], "subreason").map(parse::text).unwrap_or_default();
let msg = match status {
"LOGIN_REQUIRED" if reason.is_empty() => "Ehhez a videóhoz be kell jelentkezni.".to_string(),
"UNPLAYABLE" | "ERROR" | "LOGIN_REQUIRED" | "AGE_CHECK_REQUIRED" | "CONTENT_CHECK_REQUIRED" => [reason, sub].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" "),
_ => reason,
};
return Err(if msg.is_empty() { format!("A videó nem játszható le ({status}).") } else { msg });
}
let d = &v["videoDetails"];
let id = d["videoId"].as_str().unwrap_or_default().to_string();
let details = Details {
title: d["title"].as_str().unwrap_or_default().into(),
channel: d["author"].as_str().unwrap_or_default().into(),
channel_id: d["channelId"].as_str().unwrap_or_default().into(),
length: d["lengthSeconds"].as_str().and_then(|s| s.parse().ok()).unwrap_or(0.0),
views: d["viewCount"].as_str().unwrap_or_default().into(),
live: d["isLive"].as_bool().unwrap_or(false),
id,
};
let sd = &v["streamingData"];
let mut formats = Vec::new();
for f in sd["adaptiveFormats"].as_array().into_iter().flatten() {
if f["drmFamilies"].is_array() {
continue;
}
let mime_full = f["mimeType"].as_str().unwrap_or_default();
let (mime, codecs) = match mime_full.split_once(';') {
Some((m, rest)) => (m.trim().to_string(), rest.trim().trim_start_matches("codecs=").trim_matches('"').to_string()),
None => (mime_full.to_string(), String::new()),
};
let mut url = f["url"].as_str().unwrap_or_default().to_string();
let mut s = None;
if url.is_empty() {
if let Some(cipher) = f["signatureCipher"].as_str().or_else(|| f["cipher"].as_str()) {
let q = query(cipher);
let get = |k: &str| q.iter().find(|(a, _)| a == k).map(|(_, b)| b.clone());
url = get("url").unwrap_or_default();
if let Some(sig) = get("s") {
s = Some((sig, get("sp").unwrap_or_else(|| "signature".into())));
}
}
}
let audio = mime.starts_with("audio/");
let track = &f["audioTrack"];
formats.push(Format {
itag: f["itag"].as_u64().unwrap_or(0),
url,
mime,
codecs,
bitrate: f["bitrate"].as_u64().or_else(|| f["averageBitrate"].as_u64()).unwrap_or(0),
width: f["width"].as_u64().unwrap_or(0),
height: f["height"].as_u64().unwrap_or(0),
fps: f["fps"].as_u64().unwrap_or(0),
init: range(&f["initRange"]),
index: range(&f["indexRange"]),
audio,
default_audio: track["audioIsDefault"].as_bool().unwrap_or(false),
audio_track: track["id"].as_str().unwrap_or_default().into(),
drc: f["isDrc"].as_bool().unwrap_or(false),
sample_rate: f["audioSampleRate"].as_str().and_then(|s| s.parse().ok()).unwrap_or(0),
channels: f["audioChannels"].as_u64().unwrap_or(0),
s,
});
}
let mut details = details;
if details.length <= 0.0 {
details.length = sd["adaptiveFormats"][0]["approxDurationMs"].as_str().and_then(|s| s.parse::<f64>().ok()).map(|ms| ms / 1000.0).unwrap_or(0.0);
}
let captions = v["captions"]["playerCaptionsTracklistRenderer"]["captionTracks"]
.as_array()
.into_iter()
.flatten()
.filter_map(|t| {
Some(Caption {
url: t["baseUrl"].as_str()?.to_string(),
lang: t["languageCode"].as_str().unwrap_or_default().into(),
name: parse::text(&t["name"]),
auto: t["kind"].as_str() == Some("asr"),
})
})
.collect();
let user_agent = kind.profile().user_agent;
Ok(Playable { details, formats, hls: sd["hlsManifestUrl"].as_str().map(str::to_string), captions, user_agent })
}
/// Solves the formats' signatures and `n` parameters (TV client).
fn solve(client: &Client, player: &str, p: &mut Playable) -> Result<()> {
let mut ns = Vec::new();
let mut sigs = Vec::new();
for f in &p.formats {
if let Some((s, _)) = &f.s {
sigs.push(s.clone());
}
if let Some(n) = param(&f.url, "n") {
ns.push(n);
}
}
ns.sort();
ns.dedup();
sigs.sort();
sigs.dedup();
if ns.is_empty() && sigs.is_empty() {
return Ok(());
}
let solved = jsc::solve(client, player, &ns, &sigs)?;
for f in &mut p.formats {
if let Some((s, sp)) = f.s.take() {
match solved.sig.get(&s) {
Some(out) => f.url = format!("{}&{sp}={}", f.url, enc(out)),
None => f.url.clear(),
}
}
if let Some(n) = param(&f.url, "n") {
match solved.n.get(&n) {
Some(out) => f.url = set_param(&f.url, "n", out),
None => log::warn!("n challenge not solved; the download may be slow"),
}
}
}
Ok(())
}
// ---------------------------------------------------------------------------- URL helpers
pub fn enc(s: &str) -> String {
let mut out = String::new();
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
pub fn dec(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
match b[i] {
b'%' if i + 2 < b.len() => match u8::from_str_radix(&s[i + 1..i + 3], 16) {
Ok(v) => {
out.push(v);
i += 3;
continue;
}
Err(_) => out.push(b'%'),
},
b'+' => out.push(b' '),
c => out.push(c),
}
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// "a=1&b=2" -> [(a, 1), (b, 2)], decoded.
pub fn query(q: &str) -> Vec<(String, String)> {
q.split('&').filter(|p| !p.is_empty()).map(|p| match p.split_once('=') {
Some((k, v)) => (dec(k), dec(v)),
None => (dec(p), String::new()),
}).collect()
}
fn param(url: &str, key: &str) -> Option<String> {
let q = url.split_once('?')?.1;
query(q).into_iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
fn set_param(url: &str, key: &str, value: &str) -> String {
let Some((base, q)) = url.split_once('?') else { return url.to_string() };
let parts: Vec<String> = q
.split('&')
.map(|p| match p.split_once('=') {
Some((k, _)) if dec(k) == key => format!("{k}={}", enc(value)),
_ => p.to_string(),
})
.collect();
format!("{base}?{}", parts.join("&"))
}
#[cfg(test)]
mod tests {
use super::*;
fn fmt(itag: u64, mime: &str, codecs: &str, h: u64, br: u64) -> Format {
Format {
itag,
url: format!("https://rr1.googlevideo.com/videoplayback?itag={itag}&n=abc&x=1"),
mime: mime.into(),
codecs: codecs.into(),
bitrate: br,
height: h,
width: h * 16 / 9,
fps: 30,
init: Some((0, 740)),
index: Some((741, 1500)),
audio: mime.starts_with("audio"),
..Format::default()
}
}
fn playable() -> Playable {
Playable {
details: Details { id: "test-mpd".into(), length: 212.5, ..Details::default() },
formats: vec![
fmt(137, "video/mp4", "avc1.640028", 1080, 4_000_000),
fmt(136, "video/mp4", "avc1.4d401f", 720, 2_000_000),
fmt(401, "video/mp4", "av01.0.12M.08", 2160, 18_000_000),
fmt(248, "video/webm", "vp9", 1080, 3_000_000),
fmt(140, "audio/mp4", "mp4a.40.2", 0, 130_000),
fmt(251, "audio/webm", "opus", 0, 160_000),
],
hls: None,
captions: Vec::new(),
user_agent: "",
}
}
#[test]
fn picks_formats_and_writes_a_manifest() {
let p = playable();
assert_eq!(p.heights(Codec::H264), vec![1080, 720]);
assert_eq!(p.heights(Codec::Av1), vec![2160]);
let (uri, h) = p.uri(720, Codec::H264).unwrap();
assert_eq!(h, 720);
let path = uri.trim_start_matches("file://").trim_start_matches('/');
let path = if cfg!(windows) { path.to_string() } else { format!("/{path}") };
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains(r#"<Representation id="136""#) && !text.contains(r#"id="137""#));
assert!(text.contains("itag=136&amp;n=abc"), "URLs are escaped");
assert!(text.contains(r#"id="140""#) && !text.contains("opus"));
assert!(text.contains(r#"indexRange="741-1500""#));
let (_, h) = p.uri(0, Codec::H264).unwrap();
assert_eq!(h, 1080, "automatic: up to 1080p");
let (_, h) = p.uri(2160, Codec::Av1).unwrap();
assert_eq!(h, 2160);
}
#[test]
fn url_params() {
let u = "https://x/videoplayback?a=1&n=Zz%2Fq&b=2";
assert_eq!(param(u, "n").as_deref(), Some("Zz/q"));
assert_eq!(set_param(u, "n", "new/v"), "https://x/videoplayback?a=1&n=new%2Fv&b=2");
let q = query("s=AB%3DC&sp=sig&url=https%3A%2F%2Fr%2Fv%3Fa%3D1");
assert_eq!(q[0], ("s".into(), "AB=C".into()));
assert_eq!(q[2].1, "https://r/v?a=1");
}
}

154
ui/app.slint Normal file
View File

@@ -0,0 +1,154 @@
// YouTube for Fennec OS: the root window.
//
// Screens: "page" (every browsing screen: a LinePage built by src/page.rs)
// and "player". Over them: the QR sign-in and the toast.
//
// Rust owns state and focus: every key goes to the `key` callback, except
// while the search keyboard has the focus.
import { TvWindow, Tv, SfText, GlassRect, MenuItem } from "@sf-ui/sf-ui.slint";
import { Line, Chip, Card, Check } from "types.slint";
import { LinePage } from "page.slint";
import { PlayerScreen } from "player.slint";
import { LinkScreen } from "link.slint";
import { Toast } from "overlays.slint";
export { Tv, SfText, MenuItem, Line, Chip, Card, Check }
export component App inherits TvWindow {
title: "YouTube";
forward-focus: keys;
// "page", "player"
in property <string> screen: "page";
// The key text (Slint's Key codes) and whether it repeats; true = handled.
callback key(string, bool) -> bool;
out property <float> page-t: self.screen == "page" ? 1 : 0;
animate page-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> player-t: self.screen == "player" ? 1 : 0;
animate player-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> link-t: self.link-open ? 1 : 0;
animate link-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
// Whatever an overlay would cover goes away first.
property <float> under: max(0, 1 - 1.6 * self.link-t);
// The outgoing screen goes first, the incoming one follows.
function vis(t: float) -> float {
clamp(t * 2 - 1, 0, 1)
}
keys := FocusScope {
key-pressed(event) => {
if root.screen == "page" && root.page-kb-focused && !root.link-open {
return page.kb-key(event);
}
if root.key(event.text, event.repeat) {
return accept;
}
reject
}
}
// ---- page ----
in property <[Line]> page-lines <=> page.lines;
in property <int> page-focus <=> page.focus-line;
in property <float> page-scroll <=> page.scroll;
in property <bool> page-show-nav <=> page.show-nav;
in property <[string]> page-nav-items <=> page.nav-items;
in property <int> page-nav-index <=> page.nav-index;
in property <bool> page-nav-focused <=> page.nav-focused;
in property <string> page-account-label <=> page.account-label;
in property <bool> page-account-ok <=> page.account-ok;
in property <string> page-side-title <=> page.side-title;
in property <[string]> page-side-items <=> page.side-items;
in property <int> page-side-index <=> page.side-index;
in property <int> page-side-focus <=> page.side-focus;
in property <float> page-kb-y <=> page.kb-y;
in property <bool> page-kb-focused <=> page.kb-focused;
in property <string> page-kb-placeholder <=> page.kb-placeholder;
in-out property <string> page-query <=> page.query;
callback search-submitted(string);
callback search-changed(string);
changed page-query => {
root.search-changed(self.page-query);
}
callback search-exit-down();
callback search-exit-up();
callback search-cancelled();
public function page-kb-reset() {
page.kb-reset();
}
page := LinePage {
alpha: root.vis(root.page-t) * root.under;
visible: root.page-t > 0.001;
search-submitted(t) => { root.search-submitted(t); }
search-exit-down => { root.search-exit-down(); }
search-exit-up => { root.search-exit-up(); }
search-cancelled => { root.search-cancelled(); }
}
// ---- player ----
in property <string> player-stage <=> player.stage;
in property <string> player-title <=> player.title;
in property <string> player-heading <=> player.heading;
in property <string> player-info <=> player.info;
in property <string> player-caption <=> player.caption;
in property <string> player-stage-text <=> player.stage-text;
in property <string> player-detail-text <=> player.detail-text;
in property <string> player-error-text <=> player.error-text;
in property <bool> player-osd <=> player.osd;
in property <bool> player-paused <=> player.paused;
in property <bool> player-buffering <=> player.buffering;
in property <string> player-buffer-text <=> player.buffer-text;
in property <float> player-progress <=> player.progress;
in property <float> player-buffered <=> player.buffered;
in property <string> player-time-text <=> player.time-text;
in property <string> player-remaining-text <=> player.remaining-text;
in property <bool> player-seeking <=> player.seeking;
in property <string> player-seek-text <=> player.seek-text;
in property <string> player-seek-delta <=> player.seek-delta;
in property <bool> player-seek-back <=> player.seek-back;
in property <int> player-osd-area <=> player.osd-area;
in property <int> player-osd-button <=> player.osd-button;
in property <bool> player-has-next <=> player.has-next;
in property <bool> player-has-channel <=> player.has-channel;
in property <int> player-panel <=> player.panel;
in property <[MenuItem]> player-subs <=> player.subs;
in property <[MenuItem]> player-quality <=> player.quality;
in property <int> player-subs-focus <=> player.subs-focus;
in property <int> player-quality-focus <=> player.quality-focus;
in property <string> player-skip-label <=> player.skip-label;
in property <string> player-next-label <=> player.next-label;
in property <string> player-next-text <=> player.next-text;
player := PlayerScreen {
alpha: root.vis(root.player-t) * root.under;
visible: root.player-t > 0.001;
stage-text: "Betöltés…";
}
// ---- QR sign-in ----
in property <bool> link-open;
in property <image> link-qr <=> link.qr;
in property <string> link-code <=> link.code;
in property <string> link-url <=> link.url;
in property <string> link-status <=> link.status;
in-out property <bool> link-busy <=> link.busy;
link := LinkScreen {
alpha: root.vis(root.link-t);
visible: root.link-t > 0.001;
}
// ---- toast ----
in property <string> toast-text <=> toast.text;
in property <bool> toast-bad <=> toast.bad;
toast := Toast { }
// ---- glass, in drawing order (listed by src/main.rs) ----
out property <[GlassRect]> glass-page: page.glass;
out property <[GlassRect]> glass-page-keyboard: page.glass-keyboard;
out property <[GlassRect]> glass-player: player.glass;
out property <[GlassRect]> glass-player-subs: player.glass-subs;
out property <[GlassRect]> glass-player-quality: player.glass-quality;
out property <[GlassRect]> glass-link: link.glass;
out property <[GlassRect]> glass-toast: toast.glass;
}

99
ui/link.slint Normal file
View File

@@ -0,0 +1,99 @@
// Sign-in with a phone: a QR code and the code to type at
// youtube.com/activate, on a modal glass pane. Rust polls YouTube until the
// user confirms (src/app.rs, sign_in). Back cancels; OK asks for a new code
// after an error.
import { Tv, GlassRect, GlassPane, Spinner, Title, Label, Caption, Icon } from "@sf-ui/sf-ui.slint";
export component LinkScreen inherits Rectangle {
in property <float> alpha: 1;
in property <image> qr;
in property <string> code;
in property <string> url;
in property <string> status;
in property <bool> busy;
pane := GlassPane {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2;
width: 1500 * Tv.u;
height: 700 * Tv.u;
radius: 56 * Tv.u;
frost: 3.8;
tint: Tv.smoke.with-alpha(0.5);
glow: #ff0033;
alpha: root.alpha;
// The QR code on a white card (Slint over glass is fine: it sits on
// the pane, nothing glass is under it).
Rectangle {
x: 80 * Tv.u;
y: (parent.height - self.height) / 2;
width: 460 * Tv.u;
height: 460 * Tv.u;
border-radius: 28 * Tv.u;
background: #ffffff;
opacity: root.alpha;
if root.qr.width > 0: Image {
width: parent.width - 40 * Tv.u;
height: parent.height - 40 * Tv.u;
source: root.qr;
image-rendering: pixelated;
}
if root.qr.width == 0: Spinner { size: 64 * Tv.u; }
}
VerticalLayout {
x: 620 * Tv.u;
y: 96 * Tv.u;
width: parent.width - 700 * Tv.u;
height: parent.height - 160 * Tv.u;
spacing: 22 * Tv.u;
alignment: start;
opacity: root.alpha;
Title { text: "Bejelentkezés a YouTube-ba"; }
Label {
text: "1. Olvasd be a QR-kódot a telefonoddal, vagy nyisd meg ezt az oldalt:";
wrap: word-wrap;
color: Tv.text-secondary;
}
Text {
text: root.url == "" ? "youtube.com/activate" : root.url;
font-size: 34 * Tv.u;
font-weight: 700;
color: Tv.text;
}
Label {
text: "2. Írd be ezt a kódot, és válaszd ki a fiókodat:";
wrap: word-wrap;
color: Tv.text-secondary;
}
Text {
text: root.code == "" ? "…" : root.code;
font-size: 72 * Tv.u;
font-weight: 800;
letter-spacing: 6 * Tv.u;
color: #ffffff;
}
HorizontalLayout {
spacing: 16 * Tv.u;
alignment: start;
if root.busy: Spinner { size: 36 * Tv.u; }
if !root.busy: Icon { name: "warning"; size: 34 * Tv.u; ink: Tv.warn-ink; }
Caption {
vertical-alignment: center;
text: root.status;
wrap: word-wrap;
}
}
}
Caption {
x: 620 * Tv.u;
y: parent.height - 72 * Tv.u;
text: "Vissza: mégse";
opacity: root.alpha;
}
}
out property <[GlassRect]> glass: [pane.glass];
}

45
ui/overlays.slint Normal file
View File

@@ -0,0 +1,45 @@
// The toast over any page.
import { Tv, GlassRect, GlassPane, Icon } from "@sf-ui/sf-ui.slint";
// A short message at the bottom ("Elmentve", errors).
export component Toast inherits Rectangle {
in property <string> text;
in property <bool> bad;
out property <float> t: self.text != "" ? 1 : 0;
animate t { duration: 300ms; easing: cubic-bezier(0.3, 1.18, 0.4, 1); }
pane := GlassPane {
x: (root.width - self.width) / 2;
y: root.height - (64 + 96 * root.t) * Tv.u;
width: min(1400 * Tv.u, label.preferred-width + 140 * Tv.u);
height: 80 * Tv.u;
radius: self.height / 2;
frost: 2.4;
tint: Tv.smoke.with-alpha(0.5);
glow: root.bad ? Tv.danger : #ffffff;
lit: 0.3;
alpha: root.t;
HorizontalLayout {
padding-left: 36 * Tv.u;
padding-right: 36 * Tv.u;
spacing: 14 * Tv.u;
alignment: center;
opacity: root.t;
Icon {
y: (parent.height - self.height) / 2;
name: root.bad ? "warning" : "check";
size: 30 * Tv.u;
ink: root.bad ? Tv.danger-ink : Tv.ok-ink;
}
label := Text {
vertical-alignment: center;
text: root.text;
font-size: 25 * Tv.u;
font-weight: 600;
color: Tv.text;
overflow: elide;
}
}
}
out property <[GlassRect]> glass: [pane.glass];
}

810
ui/page.slint Normal file
View File

@@ -0,0 +1,810 @@
// The page renderer: every screen except the player and the sign-in is a
// list of Lines built by Rust (src/page.rs), which also owns the focus and
// the scroll position. This file draws them and their glass:
// - the top navigation capsule (main sections) or the settings side list,
// - hero buttons (glass at rest),
// - one focus pill that glides to the focused chip on any other line,
// - the search keyboard's pane.
// Everything else (cards, texts, unfocused chips) is plain Slint over the
// backdrop, so nothing Slint draws sits under glass.
import { Tv, GlassRect, GlassPane, Keyboard, Icon, Spinner, Display, Headline, Title, SectionTitle, Body, Item, Label, Caption } from "@sf-ui/sf-ui.slint";
import { Line, Chip, Card, Check } from "types.slint";
// A poster, landscape artwork or season card.
component NfCard inherits Rectangle {
in property <Card> card;
in property <bool> focused;
in property <length> art-h;
in property <bool> captions;
out property <float> f: self.focused ? 1 : 0;
animate f { duration: 260ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
art := Rectangle {
y: 0;
height: root.art-h;
transform-scale: 1 + 0.08 * root.f;
Rectangle {
border-radius: 20 * Tv.u;
background: #1b1d24;
drop-shadow-blur: (14 + 22 * root.f) * Tv.u;
drop-shadow-offset-y: (8 + 12 * root.f) * Tv.u;
drop-shadow-color: #00000090;
}
Rectangle {
border-radius: 20 * Tv.u;
clip: true;
if root.card.image.width == 0: Text {
x: 20 * Tv.u;
width: parent.width - 40 * Tv.u;
horizontal-alignment: center;
vertical-alignment: center;
text: root.card.big != "" ? "" : root.card.title;
font-size: 24 * Tv.u;
font-weight: 600;
color: Tv.text-tertiary;
wrap: word-wrap;
}
if !root.card.round: Image {
width: 100%;
height: 100%;
source: root.card.image;
image-fit: cover;
}
// A channel: its round picture in the middle.
if root.card.round: Rectangle {
width: parent.height * 0.78;
height: self.width;
border-radius: self.width / 2;
clip: true;
Image {
width: 100%;
height: 100%;
source: root.card.image;
image-fit: cover;
}
}
if root.card.big != "": Rectangle {
background: #00000070;
Text {
text: root.card.big;
font-size: 68 * Tv.u;
font-weight: 700;
letter-spacing: -2 * Tv.u;
color: Tv.text;
}
}
Rectangle {
background: #000000;
opacity: 0.22 * (1 - root.f);
}
if root.card.progress >= 0: Rectangle {
x: 12 * Tv.u;
y: parent.height - 18 * Tv.u;
width: parent.width - 24 * Tv.u;
height: 6 * Tv.u;
border-radius: self.height / 2;
background: #ffffff40;
Rectangle {
x: 0;
width: parent.width * clamp(root.card.progress, 0, 1);
border-radius: self.height / 2;
background: root.card.progress >= 0.999 ? Tv.ok : #ff0033;
}
}
}
if root.card.badge != "": Rectangle {
x: 12 * Tv.u;
y: 12 * Tv.u;
width: badge-text.preferred-width + 22 * Tv.u;
height: 34 * Tv.u;
border-radius: self.height / 2;
background: root.card.badge-tone == "dub" ? #1f7a4dd8 : root.card.badge-tone == "sub" ? #2b5fa8d8 : root.card.badge-tone == "accent" ? #ff0033d8 : #000000b8;
badge-text := Text {
text: root.card.badge;
font-size: 19 * Tv.u;
font-weight: 700;
color: Tv.text;
}
}
// The length of a video, bottom right.
if root.card.corner != "": Rectangle {
x: parent.width - self.width - 12 * Tv.u;
y: parent.height - self.height - (root.card.progress >= 0 ? 30 : 12) * Tv.u;
width: corner-text.preferred-width + 18 * Tv.u;
height: 32 * Tv.u;
border-radius: 8 * Tv.u;
background: #000000c8;
corner-text := Text {
text: root.card.corner;
font-size: 19 * Tv.u;
font-weight: 700;
color: Tv.text;
}
}
if root.card.mark == "check": Rectangle {
x: parent.width - self.width - 12 * Tv.u;
y: 12 * Tv.u;
width: 36 * Tv.u;
height: 36 * Tv.u;
border-radius: self.height / 2;
background: #000000b8;
Icon {
name: "check";
size: 22 * Tv.u;
ink: Tv.ok-ink;
}
}
if root.card.current: Rectangle {
border-radius: 20 * Tv.u;
border-width: 4 * Tv.u;
border-color: #ff0033;
}
}
// Clipped: right-to-left titles may not elide inside the card.
if root.captions: Rectangle {
x: 0;
y: root.art-h + 14 * Tv.u;
width: root.width;
height: 74 * Tv.u;
clip: true;
Text {
x: 0;
y: 4 * Tv.u;
width: parent.width;
text: root.card.caption;
font-size: 24 * Tv.u;
font-weight: 600;
color: root.focused ? Tv.text : #ffffffd0;
overflow: elide;
}
Text {
x: 0;
y: 38 * Tv.u;
width: parent.width;
text: root.card.detail;
font-size: 20 * Tv.u;
color: Tv.text-tertiary;
overflow: elide;
}
}
}
// A chip drawn by Slint. Focused chips get the page's glass pill underneath,
// hero chips are glass all the time: neither draws a background then.
component NfChip inherits Rectangle {
in property <Chip> chip;
in property <bool> focused;
in property <bool> on-glass;
property <bool> plain: root.focused || root.on-glass;
property <color> ink: root.focused && root.chip.tone != "primary" ? Tv.ink
: root.chip.tone == "include" ? Tv.ok-ink
: root.chip.tone == "exclude" || root.chip.tone == "danger" ? Tv.danger-ink
: root.chip.active || root.on-glass || root.chip.tone == "primary" ? Tv.text
: #ffffffd0;
x: root.chip.x * Tv.u;
y: root.chip.y * Tv.u;
width: root.chip.w * Tv.u;
height: root.chip.h * Tv.u;
opacity: root.chip.enabled ? 1 : 0.42;
Rectangle {
visible: !root.plain;
border-radius: root.chip.tone == "field" ? 22 * Tv.u : self.height / 2;
background: root.chip.tone == "field" ? #ffffff10
: root.chip.tone == "primary" ? #ff003380
: root.chip.tone == "include" ? #34c75938
: root.chip.tone == "exclude" ? #ff453a38
: root.chip.active ? #ffffff2c
: #ffffff12;
border-width: root.chip.tone == "field" ? 1.5 * Tv.u : 0;
border-color: #ffffff38;
}
HorizontalLayout {
padding-left: root.chip.tone == "field" ? 28 * Tv.u : root.chip.text == "" ? (root.height - 30 * Tv.u) / 2 : (root.chip.icon == "" ? 26 : 20) * Tv.u;
padding-right: root.chip.tone == "field" ? 28 * Tv.u : root.chip.text == "" ? (root.height - 30 * Tv.u) / 2 : 26 * Tv.u;
spacing: 10 * Tv.u;
alignment: root.chip.tone == "field" ? start : center;
if root.chip.icon != "": Icon {
y: (parent.height - self.height) / 2;
name: root.chip.icon;
size: 28 * Tv.u;
ink: root.ink;
}
if root.chip.text != "": Text {
vertical-alignment: center;
horizontal-stretch: root.chip.tone == "field" ? 1 : 0;
text: root.chip.text;
font-size: (root.chip.tone == "field" ? 26 : 23) * Tv.u;
font-weight: root.chip.active || root.focused || root.chip.tone == "primary" ? 700 : 600;
color: root.ink;
overflow: elide;
}
}
}
export component LinePage inherits Rectangle {
in property <float> alpha: 1;
in property <[Line]> lines;
in property <int> focus-line: -1;
// Vertical scroll position (design px), animated here.
in property <float> scroll;
// Top navigation (main sections).
in property <bool> show-nav;
in property <[string]> nav-items;
in property <int> nav-index;
in property <bool> nav-focused;
in property <string> account-label;
in property <bool> account-ok;
// Settings side list.
in property <string> side-title;
in property <[string]> side-items;
in property <int> side-index;
in property <int> side-focus: -1;
// Embedded search keyboard: its top (design px, page coordinates; < 0 = none).
in property <float> kb-y: -1;
in property <bool> kb-focused;
in property <string> kb-placeholder;
in property <string> kb-submit-label: "Keresés";
in-out property <string> query;
callback search-submitted(string);
callback search-exit-down();
callback search-exit-up();
callback search-cancelled();
public function kb-key(event: KeyEvent) -> EventResult {
kb.key(event)
}
public function kb-reset() {
kb.reset();
}
property <bool> side: self.side-items.length > 0;
// Content left edge (design px).
property <float> cx: self.side ? 600 : 96;
out property <float> scroll-anim: self.scroll;
animate scroll-anim { duration: 380ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
property <bool> content-focus: !self.nav-focused && self.side-focus < 0 && !self.kb-focused;
// ---- lines ----
for line[li] in root.lines: Rectangle {
property <float> ty: line.y - root.scroll-anim;
property <bool> lf: li == root.focus-line && root.content-focus;
x: (root.cx + line.x) * Tv.u;
y: self.ty * Tv.u;
width: line.w * Tv.u;
height: line.h * Tv.u;
visible: self.ty + line.h > -40 && self.ty < 1120;
opacity: root.alpha;
// hero
if line.kind == "hero": Rectangle {
if line.logo.width > 0: Image {
x: 0;
y: 40 * Tv.u;
width: 620 * Tv.u;
height: 190 * Tv.u;
source: line.logo;
image-fit: contain;
horizontal-alignment: left;
vertical-alignment: bottom;
}
if line.logo.width == 0: Display {
x: 0;
y: 90 * Tv.u;
width: 1300 * Tv.u;
text: line.title;
font-size: (line.title.character-count > 24 ? 64 : 88) * Tv.u;
}
if line.style != "": Text {
x: 0;
y: 12 * Tv.u;
text: line.style;
font-size: 20 * Tv.u;
font-weight: 700;
letter-spacing: 3 * Tv.u;
color: Tv.text-secondary;
}
Caption {
x: 0;
y: 242 * Tv.u;
width: 1300 * Tv.u;
text: line.subtitle;
}
Label {
x: 0;
y: 274 * Tv.u;
width: 1500 * Tv.u;
text: line.meta;
color: Tv.text;
}
Label {
x: 0;
y: 312 * Tv.u;
width: 1500 * Tv.u;
text: line.extra;
color: #ff8a8a;
font-weight: 600;
}
Body {
x: 0;
y: (line.extra == "" ? 316 : 352) * Tv.u;
width: 1100 * Tv.u;
height: (line.extra == "" ? 152 : 116) * Tv.u;
text: line.text;
font-size: 26 * Tv.u;
}
for chip[ci] in line.chips: NfChip {
chip: chip;
focused: lf && line.col == ci;
on-glass: true;
}
if line.progress >= 0: Rectangle {
x: 0;
y: (line.h - 22) * Tv.u;
width: 360 * Tv.u;
height: 6 * Tv.u;
border-radius: self.height / 2;
background: #ffffff33;
Rectangle {
x: 0;
width: parent.width * clamp(line.progress, 0, 1);
border-radius: self.height / 2;
background: #ff0033;
}
}
if line.note != "": Caption {
x: 380 * Tv.u;
y: (line.h - 34) * Tv.u;
text: line.note;
}
}
// heading
if line.kind == "heading": Rectangle {
Text {
x: 0;
y: 4 * Tv.u;
text: line.title;
font-size: (line.style == "big" ? 56 : 38) * Tv.u;
font-weight: 700;
letter-spacing: (line.style == "big" ? -1 : -0.4) * Tv.u;
color: Tv.text;
}
Caption {
x: 0;
y: (line.style == "big" ? 76 : 54) * Tv.u;
width: parent.width;
text: line.subtitle;
}
}
// text
if line.kind == "text": Text {
x: 0;
y: 0;
width: parent.width;
height: parent.height;
text: line.text;
wrap: word-wrap;
vertical-alignment: top;
font-size: (line.style == "caption" ? 22 : line.style == "label" ? 24 : 26) * Tv.u;
font-weight: line.style == "label" ? 600 : 400;
color: line.style == "warn" ? Tv.warn-ink : line.style == "bad" ? Tv.danger-ink : line.style == "good" ? Tv.ok-ink : line.style == "caption" ? Tv.text-tertiary : Tv.text-secondary;
}
// notice
if line.kind == "notice": Rectangle {
Icon {
x: 0;
y: 4 * Tv.u;
size: 36 * Tv.u;
name: line.icon != "" ? line.icon : line.tone == "good" ? "check" : line.tone == "info" ? "info" : "warning";
ink: line.tone == "good" ? Tv.ok-ink : line.tone == "bad" ? Tv.danger-ink : line.tone == "warn" ? Tv.warn-ink : Tv.text-secondary;
}
Item {
x: 56 * Tv.u;
y: 4 * Tv.u;
width: parent.width - 56 * Tv.u;
text: line.title;
font-size: 27 * Tv.u;
}
Text {
x: 56 * Tv.u;
y: 44 * Tv.u;
width: parent.width - 56 * Tv.u;
height: parent.height - 44 * Tv.u;
text: line.text;
wrap: word-wrap;
font-size: 23 * Tv.u;
color: Tv.text-secondary;
}
}
// checks
if line.kind == "checks": Rectangle {
for c[i] in line.checks: Rectangle {
x: mod(i, 2) * parent.width / 2;
y: floor(i / 2) * 84 * Tv.u;
width: parent.width / 2 - 24 * Tv.u;
height: 80 * Tv.u;
Icon {
x: 0;
y: 2 * Tv.u;
size: 28 * Tv.u;
name: c.state == 1 ? "check" : c.state == 0 ? "close" : "info";
ink: c.state == 1 ? Tv.ok-ink : c.state == 0 ? Tv.danger-ink : Tv.warn-ink;
}
Text {
x: 44 * Tv.u;
y: 0;
width: parent.width - 44 * Tv.u;
text: c.label;
font-size: 23 * Tv.u;
font-weight: 600;
color: Tv.text;
overflow: elide;
}
Text {
x: 44 * Tv.u;
y: 32 * Tv.u;
width: parent.width - 44 * Tv.u;
height: 48 * Tv.u;
text: c.detail;
font-size: 20 * Tv.u;
color: Tv.text-tertiary;
wrap: word-wrap;
overflow: elide;
}
}
}
// chips
if line.kind == "chips": Rectangle {
if line.title != "": Text {
x: 0;
y: 0;
text: line.title;
font-size: 22 * Tv.u;
font-weight: 600;
letter-spacing: 1 * Tv.u;
color: Tv.text-tertiary;
}
for chip[ci] in line.chips: NfChip {
chip: chip;
focused: lf && line.col == ci;
}
}
// item
if line.kind == "item": Rectangle {
property <bool> pic: line.style == "image";
property <length> tx: (self.pic ? 288 : 0) * Tv.u;
if self.pic: Rectangle {
x: 0;
y: 8 * Tv.u;
width: 256 * Tv.u;
height: 144 * Tv.u;
border-radius: 16 * Tv.u;
clip: true;
background: #1b1d24;
Image {
width: 100%;
height: 100%;
source: line.image;
image-fit: cover;
}
if line.progress >= 0: Rectangle {
x: 10 * Tv.u;
y: parent.height - 16 * Tv.u;
width: parent.width - 20 * Tv.u;
height: 6 * Tv.u;
border-radius: self.height / 2;
background: #ffffff40;
Rectangle {
x: 0;
width: parent.width * clamp(line.progress, 0, 1);
border-radius: self.height / 2;
background: line.progress >= 0.999 ? Tv.ok : #ff0033;
}
}
}
if !self.pic && line.progress >= 0: Rectangle {
x: 0;
y: parent.height - 12 * Tv.u;
width: 900 * Tv.u;
height: 6 * Tv.u;
border-radius: self.height / 2;
background: #ffffff26;
Rectangle {
x: 0;
width: parent.width * clamp(line.progress, 0, 1);
border-radius: self.height / 2;
background: line.tone == "warn" ? Tv.warn : line.tone == "good" ? Tv.ok : #4f8cff;
}
}
Text {
x: parent.tx;
y: 6 * Tv.u;
width: parent.width - parent.tx;
text: line.title;
font-size: 26 * Tv.u;
font-weight: 600;
color: line.tone == "dim" ? Tv.text-tertiary : Tv.text;
overflow: elide;
}
Text {
x: parent.tx;
y: 42 * Tv.u;
width: parent.width - parent.tx;
text: line.meta;
font-size: 21 * Tv.u;
font-weight: 500;
color: line.tone == "bad" ? Tv.danger-ink : line.tone == "warn" ? Tv.warn-ink : Tv.text-tertiary;
overflow: elide;
}
Text {
x: parent.tx;
y: 74 * Tv.u;
width: min(parent.width - parent.tx, 1100 * Tv.u);
height: 58 * Tv.u;
text: line.text;
font-size: 21 * Tv.u;
color: Tv.text-secondary;
wrap: word-wrap;
overflow: elide;
}
for chip[ci] in line.chips: NfChip {
chip: chip;
focused: lf && line.col == ci;
}
}
// cards
if line.kind == "cards": Rectangle {
property <float> cw: line.style == "landscape" ? 400 : line.style == "season" ? 168 : 196;
property <float> ch: line.style == "landscape" ? 225 : line.style == "season" ? 252 : 294;
property <float> step: self.cw + 32;
property <float> head: line.title != "" ? 56 : 0;
property <int> fit: floor((line.w + 32) / self.step);
property <float> scroll-to: clamp(line.col - 1, 0, max(0, line.cards.length - self.fit));
property <float> sc: self.scroll-to;
animate sc { duration: 320ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
if line.title != "": Text {
x: 0;
y: 0;
text: line.title;
font-size: 32 * Tv.u;
font-weight: 600;
color: lf ? Tv.text : #ffffffc8;
}
if line.subtitle != "": Caption {
x: title-w.preferred-width + 20 * Tv.u;
y: 10 * Tv.u;
text: line.subtitle;
}
title-w := Text {
visible: false;
text: line.title;
font-size: 32 * Tv.u;
font-weight: 600;
}
for card[ci] in line.cards: NfCard {
x: (ci - parent.sc) * parent.step * Tv.u;
y: parent.head * Tv.u;
width: parent.cw * Tv.u;
height: (parent.ch + (line.captions ? 80 : 0)) * Tv.u;
art-h: parent.ch * Tv.u;
visible: ci >= parent.sc - 2 && ci < parent.sc + parent.fit + 2;
card: card;
captions: line.captions;
focused: lf && line.col == ci;
}
}
}
// ---- embedded keyboard (search) ----
kb-pane := GlassPane {
x: (root.width - self.width) / 2;
y: (root.kb-y - root.scroll-anim) * Tv.u;
width: 1720 * Tv.u;
height: 508 * Tv.u;
radius: 48 * Tv.u;
frost: 3.4;
tint: Tv.smoke.with-alpha(0.44);
alpha: root.kb-y >= 0 ? root.alpha : 0;
visible: root.kb-y >= 0;
kb := Keyboard {
x: 0;
y: 40 * Tv.u;
width: parent.width;
compact: true;
placeholder: root.kb-placeholder;
submit-label: root.kb-submit-label;
min-length: 2;
max-length: 60;
active: root.kb-focused;
alpha: root.kb-y >= 0 ? root.alpha : 0;
text <=> root.query;
submitted(t) => { root.search-submitted(t); }
cancelled => { root.search-cancelled(); }
exit-down => { root.search-exit-down(); }
exit-up => { root.search-exit-up(); }
}
}
// ---- settings side list ----
// Under the top nav its own tab already names the page.
if root.side && !root.show-nav: Headline {
x: Tv.safe-x;
y: 56 * Tv.u;
text: root.side-title;
opacity: root.alpha;
}
for item[i] in root.side-items: Text {
x: (96 + 28) * Tv.u;
y: (184 + i * 80) * Tv.u;
width: (440 - 56) * Tv.u;
height: 72 * Tv.u;
vertical-alignment: center;
text: item;
font-size: 26 * Tv.u;
font-weight: 600;
color: i == root.side-focus ? Tv.ink : i == root.side-index ? Tv.text : Tv.text-secondary;
opacity: root.alpha;
}
// ---- top navigation ----
property <length> tab-w: 232 * Tv.u;
property <float> nav-a: root.show-nav ? root.alpha * (root.nav-focused ? 1 : clamp(1 - root.scroll-anim / 120, 0, 1)) : 0;
nav := GlassPane {
x: (root.width - self.width) / 2;
y: 40 * Tv.u;
width: root.nav-items.length * root.tab-w + 16 * Tv.u;
height: 80 * Tv.u;
radius: self.height / 2;
frost: 1.6;
tint: #ffffff0a;
alpha: root.nav-a;
visible: root.show-nav;
for t[i] in root.nav-items: Text {
x: 8 * Tv.u + i * root.tab-w;
width: root.tab-w;
height: parent.height;
horizontal-alignment: center;
vertical-alignment: center;
text: t;
font-size: 25 * Tv.u;
font-weight: 600;
color: i == root.nav-index ? (root.nav-focused ? Tv.ink : Tv.text) : Tv.text-secondary;
opacity: root.nav-a;
}
}
if root.show-nav && root.account-label != "": HorizontalLayout {
x: nav.x + nav.width + 28 * Tv.u;
y: nav.y;
height: nav.height;
spacing: 10 * Tv.u;
opacity: root.nav-a;
Rectangle {
width: 12 * Tv.u;
Rectangle {
y: (parent.height - self.height) / 2;
height: 12 * Tv.u;
border-radius: self.height / 2;
background: root.account-ok ? Tv.ok : Tv.danger;
}
}
Text {
vertical-alignment: center;
text: root.account-label;
font-size: 22 * Tv.u;
font-weight: 600;
color: root.account-ok ? Tv.ok-ink : Tv.danger-ink;
}
}
out property <float> tab-pos: self.nav-index;
animate tab-pos { duration: 260ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> nav-t: self.nav-focused ? 1 : 0;
animate nav-t { duration: 220ms; easing: ease-out; }
out property <float> side-pos: self.side-index;
animate side-pos { duration: 260ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> side-fpos: max(0, self.side-focus);
animate side-fpos { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
// ---- glass ----
property <Line> fl: root.focus-line >= 0 && root.focus-line < root.lines.length ? root.lines[root.focus-line] : root.lines[0];
property <Chip> fc: root.fl.chips[max(0, root.fl.col)];
property <bool> pill-on: root.content-focus && root.focus-line >= 0 && root.fl.kind != "hero" && root.fl.kind != "cards" && root.fc.w > 0;
out property <float> pill-x: root.cx + root.fl.x + root.fc.x;
animate pill-x { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> pill-w: root.fc.w;
animate pill-w { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> pill-y: root.fl.y + root.fc.y;
animate pill-y { duration: 300ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> pill-a: root.pill-on ? 1 : 0;
animate pill-a { duration: 160ms; easing: ease-out; }
property <Line> hero: root.lines.length > 0 && root.lines[0].kind == "hero" ? root.lines[0] : root.fl;
property <bool> has-hero: root.lines.length > 0 && root.lines[0].kind == "hero";
pure function hero-rect(i: int) -> GlassRect {
let c = root.hero.chips[i];
let f = root.has-hero && root.focus-line == 0 && root.content-focus && root.hero.col == i ? 1 : 0;
let s = 1 + 0.05 * f;
{
x: (root.cx + root.hero.x + c.x) * Tv.u - c.w * Tv.u * (s - 1) / 2,
y: (root.hero.y + c.y - root.scroll-anim) * Tv.u - c.h * Tv.u * (s - 1) / 2,
w: c.w * Tv.u * s,
h: c.h * Tv.u * s,
r: c.h * Tv.u * s / 2,
focus: f,
alpha: root.has-hero && c.w > 0 && i < root.hero.chips.length ? root.alpha * (c.enabled ? 1 : 0.5) : 0,
blur: 1.4,
glow: c.tone == "primary" ? #ff0033 : #ffffff,
tint: c.tone == "primary" ? #ff0033.with-alpha(0.42 + 0.4 * f) : #ffffff.with-alpha((c.active ? 0.16 : 0.07) + 0.8 * f),
group: 0,
}
}
out property <[GlassRect]> glass: [
nav.glass,
{
x: nav.absolute-position.x + 8 * Tv.u + root.tab-pos * root.tab-w,
y: nav.absolute-position.y + 8 * Tv.u,
w: root.tab-w,
h: nav.height - 16 * Tv.u,
r: (nav.height - 16 * Tv.u) / 2,
focus: root.nav-t,
alpha: root.nav-a,
blur: -1,
glow: #ffffff,
tint: #ffffff.with-alpha(0.12 + 0.76 * root.nav-t),
group: 0,
},
{
x: 96 * Tv.u,
y: (184 + root.side-pos * 80) * Tv.u,
w: 440 * Tv.u,
h: 72 * Tv.u,
r: 36 * Tv.u,
focus: 0,
alpha: root.side ? root.alpha * (root.side-focus == root.side-index ? 0 : 1) : 0,
blur: 1.2,
glow: #ffffff,
tint: #ffffff14,
group: 0,
},
{
x: 96 * Tv.u,
y: (184 + root.side-fpos * 80) * Tv.u,
w: 440 * Tv.u,
h: 72 * Tv.u,
r: 36 * Tv.u,
focus: 1,
alpha: root.side && root.side-focus >= 0 ? root.alpha : 0,
blur: 1.2,
glow: #ffffff,
tint: #ffffffe0,
group: 0,
},
root.hero-rect(0),
root.hero-rect(1),
root.hero-rect(2),
root.hero-rect(3),
root.hero-rect(4),
root.hero-rect(5),
{
x: root.pill-x * Tv.u,
y: (root.pill-y - root.scroll-anim) * Tv.u,
w: root.pill-w * Tv.u,
h: root.fc.h * Tv.u,
r: root.fc.tone == "field" ? 22 * Tv.u : root.fc.h * Tv.u / 2,
focus: 1,
alpha: root.alpha * root.pill-a,
blur: 1.2,
glow: root.fc.tone == "primary" ? #ff0033 : #ffffff,
tint: root.fc.tone == "primary" ? #ff0033.with-alpha(0.85) : #ffffff.with-alpha(root.fc.tone == "field" ? 0.82 : 0.88),
group: 0,
},
kb-pane.glass,
];
out property <[GlassRect]> glass-keyboard: kb.glass;
}

341
ui/player.slint Normal file
View File

@@ -0,0 +1,341 @@
// Playback. The video itself is the glass backdrop (Rust: glass.set_video),
// so the controls are glass that refracts the picture. (From Netflex TV.)
//
// Stages: "prep" (asking YouTube for the formats), "play", "error". With
// the controls hidden the remote drives playback directly (OK =
// play/pause, left/right = seek); shown, up/down moves between the seek
// bar and the buttons. All focus state is Rust's.
import { Tv, GlassRect, GlassPane, GlassButton, GlassMenu, MenuItem, ProgressBar, Spinner, Title, Label, Caption, Item, Icon } from "@sf-ui/sf-ui.slint";
export component PlayerScreen inherits Rectangle {
in property <float> alpha: 1;
in property <string> stage: "prep";
in property <string> title;
// The channel, above the title.
in property <string> heading;
// "1080p · 1,2 M megtekintés · Felirat: Magyar"
in property <string> info;
// The caption line at the current position.
in property <string> caption;
in property <string> stage-text;
in property <string> detail-text;
in property <string> error-text;
// Playing.
in property <bool> osd;
in property <bool> paused;
in property <bool> buffering;
in property <string> buffer-text;
in property <float> progress;
in property <float> buffered;
in property <string> time-text;
in property <string> remaining-text;
in property <string> downloaded-text;
// Seeking with left/right: the target and how far it is.
in property <bool> seeking;
in property <string> seek-text;
in property <string> seek-delta;
in property <bool> seek-back;
// Controls: 0 = seek bar, 1 = buttons; which button.
in property <int> osd-area;
in property <int> osd-button;
in property <bool> has-next;
in property <bool> has-channel;
// Panel: 0 = closed, 1 = captions focused, 2 = quality focused.
in property <int> panel;
in property <[MenuItem]> subs;
in property <[MenuItem]> quality;
in property <int> subs-focus;
in property <int> quality-focus;
// Unused (kept for the shared layout).
in property <string> skip-label;
// The end: "Következik" card.
in property <string> next-label;
in property <string> next-text;
out property <float> osd-t: self.stage == "play" && (self.osd || self.paused || self.panel > 0) ? 1 : 0;
animate osd-t { duration: 320ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
out property <float> panel-t: self.panel > 0 ? 1 : 0;
animate panel-t { duration: 360ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
property <float> prep-a: self.alpha * (self.stage == "play" ? 0 : 1);
property <float> osd-a: self.alpha * self.osd-t;
property <bool> buttons: self.osd-t > 0.5 && self.osd-area == 1 && self.panel == 0;
// Darkens the film behind the controls (Slint over video is fine).
Rectangle {
y: root.height * 0.5;
height: root.height * 0.5;
background: @linear-gradient(180deg, #00000000 0%, #000000b8 100%);
opacity: root.osd-a;
}
// ---- preparing / error ----
VerticalLayout {
x: Tv.safe-x;
width: root.width - 2 * Tv.safe-x;
y: 330 * Tv.u;
height: 460 * Tv.u;
spacing: 24 * Tv.u;
alignment: start;
opacity: root.prep-a;
if root.stage == "prep": HorizontalLayout {
alignment: center;
Spinner { size: 72 * Tv.u; }
}
if root.stage == "error": HorizontalLayout {
alignment: center;
Icon { name: "warning"; size: 64 * Tv.u; ink: Tv.danger-ink; }
}
Title {
horizontal-alignment: center;
text: root.stage == "error" ? "Nem sikerült elindítani" : root.heading == "" ? root.title : root.title + " · " + root.heading;
}
Label {
horizontal-alignment: center;
text: root.stage == "error" ? root.error-text : root.stage-text;
wrap: word-wrap;
color: Tv.text-secondary;
}
Caption {
horizontal-alignment: center;
text: root.stage == "error" ? "Vissza: vissza a listához" : root.detail-text;
wrap: word-wrap;
}
}
// ---- buffering ----
buf := GlassPane {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2;
width: 620 * Tv.u;
height: 190 * Tv.u;
radius: 40 * Tv.u;
frost: 3.2;
tint: Tv.smoke.with-alpha(0.4);
alpha: root.stage == "play" && root.buffering && !root.seeking ? root.alpha : 0;
VerticalLayout {
padding: 32 * Tv.u;
spacing: 20 * Tv.u;
alignment: center;
opacity: parent.alpha;
HorizontalLayout {
alignment: center;
Spinner { size: 56 * Tv.u; }
}
Label {
horizontal-alignment: center;
text: root.buffer-text == "" ? "Betöltés…" : root.buffer-text;
overflow: elide;
}
}
}
if root.stage == "play" && root.paused && !root.buffering && root.panel == 0 && !root.seeking && root.next-label == "": Icon {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2 - 60 * Tv.u;
name: "pause";
size: 96 * Tv.u;
opacity: 0.85 * root.alpha;
}
// ---- seek preview ----
seek := GlassPane {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2 - 60 * Tv.u;
width: 520 * Tv.u;
height: 108 * Tv.u;
radius: self.height / 2;
frost: 3.0;
tint: Tv.smoke.with-alpha(0.4);
alpha: root.stage == "play" && root.seeking ? root.alpha : 0;
HorizontalLayout {
alignment: center;
spacing: 18 * Tv.u;
opacity: parent.alpha;
Icon {
y: (parent.height - self.height) / 2;
name: root.seek-back ? "rewind" : "fast-forward";
size: 40 * Tv.u;
}
Text {
vertical-alignment: center;
text: root.seek-text;
font-size: 44 * Tv.u;
font-weight: 700;
color: Tv.text;
}
Text {
vertical-alignment: center;
text: root.seek-delta;
font-size: 26 * Tv.u;
color: Tv.text-secondary;
}
}
}
// ---- captions (Slint over the video, above the controls when shown) ----
if root.stage == "play" && root.caption != "": Rectangle {
property <length> bottom: (root.osd-t > 0.5 ? 400 : 90) * Tv.u;
x: (root.width - self.width) / 2;
y: root.height - self.bottom - self.height;
width: min(1500 * Tv.u, cap.preferred-width + 48 * Tv.u);
height: cap.preferred-height + 20 * Tv.u;
border-radius: 12 * Tv.u;
background: #000000b0;
animate y { duration: 220ms; easing: ease-out; }
cap := Text {
width: min(1452 * Tv.u, self.preferred-width);
text: root.caption;
font-size: 38 * Tv.u;
font-weight: 600;
color: #ffffff;
horizontal-alignment: center;
wrap: word-wrap;
}
}
// ---- up next ----
upnext := GlassPane {
x: root.width - Tv.safe-x - self.width;
y: root.height - 380 * Tv.u;
width: 620 * Tv.u;
height: 168 * Tv.u;
radius: 40 * Tv.u;
frost: 3.2;
tint: Tv.smoke.with-alpha(0.42);
alpha: root.next-label != "" ? root.alpha : 0;
VerticalLayout {
padding: 32 * Tv.u;
spacing: 6 * Tv.u;
opacity: parent.alpha;
Caption { text: "KÖVETKEZIK"; letter-spacing: 2 * Tv.u; }
Title { text: root.next-label; font-size: 30 * Tv.u; overflow: elide; }
Label { text: root.next-text; }
}
}
// ---- controls ----
Rectangle {
x: Tv.safe-x;
y: root.height - 360 * Tv.u + (1 - root.osd-t) * 30 * Tv.u;
width: root.width - 2 * Tv.safe-x;
height: 300 * Tv.u;
opacity: root.osd-a;
Text {
x: 0;
y: 0;
text: root.heading;
font-size: 24 * Tv.u;
font-weight: 700;
color: #ff8a8a;
width: parent.width - 420 * Tv.u;
overflow: elide;
}
Text {
x: 0;
y: 34 * Tv.u;
width: parent.width - 420 * Tv.u;
text: root.title;
font-size: 44 * Tv.u;
font-weight: 700;
letter-spacing: -0.8 * Tv.u;
color: Tv.text;
overflow: elide;
}
Caption {
x: 0;
y: 96 * Tv.u;
width: parent.width - 420 * Tv.u;
text: root.info;
color: Tv.text-secondary;
}
Caption {
x: parent.width - 400 * Tv.u;
y: 96 * Tv.u;
width: 400 * Tv.u;
horizontal-alignment: right;
text: root.downloaded-text;
}
Text {
x: 0;
y: 172 * Tv.u;
text: root.time-text;
font-size: 24 * Tv.u;
font-weight: 600;
color: Tv.text;
}
Text {
x: parent.width - 300 * Tv.u;
y: 172 * Tv.u;
width: 300 * Tv.u;
horizontal-alignment: right;
text: root.remaining-text;
font-size: 24 * Tv.u;
font-weight: 600;
color: Tv.text-secondary;
}
}
bar := ProgressBar {
x: Tv.safe-x;
y: root.height - 222 * Tv.u + (1 - root.osd-t) * 30 * Tv.u;
width: root.width - 2 * Tv.safe-x;
height: (root.osd-area == 0 && root.panel == 0 ? 14 : 10) * Tv.u;
value: root.progress;
buffered: root.buffered;
fill: root.seeking ? #ff0033 : Tv.text;
nested: false;
alpha: root.osd-a;
}
HorizontalLayout {
x: Tv.safe-x;
y: root.height - 146 * Tv.u + (1 - root.osd-t) * 30 * Tv.u;
height: 72 * Tv.u;
spacing: 20 * Tv.u;
alignment: start;
b0 := GlassButton { icon: root.paused ? "play" : "pause"; focused: root.buttons && root.osd-button == 0; alpha: root.osd-a; }
b1 := GlassButton { icon: "rewind"; text: "10 mp"; focused: root.buttons && root.osd-button == 1; alpha: root.osd-a; }
b2 := GlassButton { icon: "fast-forward"; text: "10 mp"; focused: root.buttons && root.osd-button == 2; alpha: root.osd-a; }
b3 := GlassButton { icon: "next"; text: "Következő"; enabled: root.has-next; focused: root.buttons && root.osd-button == 3; alpha: root.has-next ? root.osd-a : 0; visible: root.has-next; }
b4 := GlassButton { icon: "user"; text: "Csatorna"; enabled: root.has-channel; focused: root.buttons && root.osd-button == 4; alpha: root.has-channel ? root.osd-a : 0; visible: root.has-channel; }
}
b5 := GlassButton {
width: self.preferred-width;
x: root.width - Tv.safe-x - self.width;
y: root.height - 146 * Tv.u + (1 - root.osd-t) * 30 * Tv.u;
icon: "subtitles";
text: "Felirat és minőség";
focused: root.buttons && root.osd-button == 5;
alpha: root.osd-a;
}
// ---- captions and quality panel ----
property <length> col-w: 600 * Tv.u;
property <length> panel-y: root.height - 400 * Tv.u;
m-subs := GlassMenu {
x: Tv.safe-x;
y: root.panel-y - self.height + (1 - root.panel-t) * 30 * Tv.u;
width: root.col-w;
title: "Felirat";
items: root.subs;
focused-index: root.subs-focus;
active: root.panel == 1;
alpha: root.alpha * root.panel-t;
accent: #ff0033;
visible-rows: 6;
}
m-quality := GlassMenu {
x: Tv.safe-x + root.col-w + 28 * Tv.u;
y: root.panel-y - self.height + (1 - root.panel-t) * 30 * Tv.u;
width: 400 * Tv.u;
title: "Minőség";
items: root.quality;
focused-index: root.quality-focus;
active: root.panel == 2;
alpha: root.alpha * root.panel-t;
accent: #ff0033;
visible-rows: 7;
}
out property <[GlassRect]> glass: [buf.glass, seek.glass, bar.glass, b0.glass, b1.glass, b2.glass, b3.glass, b4.glass, b5.glass, upnext.glass];
out property <[GlassRect]> glass-subs: m-subs.glass;
out property <[GlassRect]> glass-quality: m-quality.glass;
}

86
ui/types.slint Normal file
View File

@@ -0,0 +1,86 @@
// Data the Rust side fills in. Every page is a list of Lines (src/page.rs);
// all lengths here are design px (1920x1080 grid), multiplied by Tv.u.
// A button / choice / text field on a line. x, y relative to the line.
export struct Chip {
id: string,
text: string,
icon: string,
x: float,
y: float,
w: float,
h: float,
// Selected (a choice, the current tab).
active: bool,
// "" | "primary" (accent glass) | "include" | "exclude" | "danger" | "field" (text field)
tone: string,
enabled: bool,
}
// A card in a cards line.
export struct Card {
id: string,
title: string,
// Under the card (cards lines with captions).
caption: string,
detail: string,
image: image,
// 0..1 watched; negative = no bar.
progress: float,
// Small pill over the top-left corner, and its tone ("dub", "sub", "accent", "").
badge: string,
badge-tone: string,
// "check" = watched mark (top-right).
mark: string,
// Big number over a dimmed picture (a season without its own poster).
big: string,
// Highlighted (the video playing now).
current: bool,
// Bottom-right label (a video's length).
corner: string,
// A round picture in the middle (a channel's avatar).
round: bool,
}
// One line of a checks list: state 1 = ok, 0 = failed, -1 = unknown.
export struct Check {
state: int,
label: string,
detail: string,
}
// One line of a page.
// hero big title block with buttons (detail pages, spotlight)
// heading section title (+ subtitle)
// text paragraph (style "body" | "caption" | "label" | "warn" | "bad" | "good")
// notice icon + title + text, toned ("good" | "bad" | "warn" | "info")
// chips a row of chips (title = label above them)
// cards a row of cards (style "poster" | "landscape" | "season"; captions under them)
// item list row: optional picture, title, meta, text, progress, chips
// checks two columns of check rows
// keyboard room for the page's on-screen keyboard
export struct Line {
id: string,
kind: string,
y: float,
h: float,
x: float,
w: float,
title: string,
subtitle: string,
meta: string,
extra: string,
text: string,
note: string,
style: string,
tone: string,
icon: string,
image: image,
logo: image,
progress: float,
col: int,
captions: bool,
cards: [Card],
chips: [Chip],
checks: [Check],
}