first commit
build / test (push) Canceled after 0s
build / deb (amd64) (push) Canceled after 0s
build / deb (arm64) (push) Canceled after 0s
build / deb (armhf) (push) Canceled after 0s

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-16 16:19:21 +01:00
commit c30064b531
93 files changed
+26367

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
target
.git
dist
*.deb
.cache
+45
View File
@@ -0,0 +1,45 @@
# Gitea Actions (GitHub Actions compatible): tests + .deb packages for amd64, arm64 and armhf.
name: build
on:
push:
branches: [main, master]
tags: ["v*"]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
container: rust:1-trixie
steps:
- uses: actions/checkout@v4
- run: apt-get update && apt-get install -y --no-install-recommends nodejs
- run: rustup component add rustfmt clippy
- run: ./dev.sh check
- run: cargo test --locked --all-targets
deb:
needs: test
runs-on: ubuntu-latest
container: rust:1-trixie
strategy:
matrix:
arch: [amd64, arm64, armhf]
steps:
- uses: actions/checkout@v4
- name: Cross-compilation tools
run: |
apt-get update && apt-get install -y --no-install-recommends python3-pip
pip3 install --break-system-packages ziglang
cargo install cargo-deb cargo-zigbuild --locked
rustup target add x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu armv7-unknown-linux-gnueabihf
- name: Build .deb
# the job already runs in a rust container – build directly (no Docker-in-Docker)
env:
BUILD_IN_DOCKER: "0"
BUILD_METHOD: zigbuild
run: scripts/build-deb.sh ${{ matrix.arch }}
- uses: actions/upload-artifact@v3
with:
name: simply-dvb-${{ matrix.arch }}
path: dist/*.deb
+5
View File
@@ -0,0 +1,5 @@
/target
/dist
*.deb
/data
/.cache
BIN
View File
Binary file not shown.
Generated
+3135
View File
File diff suppressed because it is too large. Load diff
+94
View File
@@ -0,0 +1,94 @@
[package]
name = "simply-dvb"
version = "0.1.5"
edition = "2021"
rust-version = "1.85"
description = "simply-dvb - lightweight DVB-T/T2/C server: scanning, HLS, M3U, EPG/XMLTV, recording and a web panel"
authors = ["Mateusz Gruszczyński"]
license = "AGPL-3.0-or-later"
readme = "README.md"
publish = false
[[bin]]
name = "simply-dvb"
path = "src/main.rs"
[lib]
name = "simply_dvb"
path = "src/lib.rs"
[dependencies]
anyhow = "1.0"
thiserror = "2"
argon2 = "0.5"
axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "form"] }
base64 = "0.22"
bytes = "1.10"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
clap = { version = "4.5", features = ["derive", "env"] }
encoding_rs = "0.8"
flate2 = "1.1"
futures-util = "0.3"
getrandom = "0.3"
ipnet = { version = "2.11", features = ["serde"] }
libc = "0.2"
quick-xml = "0.38"
regex = "1"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "gzip"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha1 = "0.10"
url = "2"
sha2 = "0.10"
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "migrate", "macros"] }
subtle = "2.6"
tokio = { version = "1.45", features = ["macros", "rt-multi-thread", "net", "signal", "time", "sync", "fs", "io-util", "process"] }
tokio-stream = { version = "0.1", features = ["sync"] }
tokio-util = { version = "0.7", features = ["io"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt", "registry"] }
unicode-normalization = "0.1"
sysinfo = { version = "0.36.1", default-features = false, features = ["system", "network", "component"] }
[build-dependencies]
serde_json = "1.0"
sha2 = "0.10"
[dev-dependencies]
tempfile = "3.19"
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"
[profile.release]
lto = "thin"
codegen-units = 1
strip = "debuginfo"
[package.metadata.deb]
maintainer = "Mateusz Gruszczyński"
copyright = "Mateusz Gruszczyński"
section = "video"
priority = "optional"
depends = "libc6 (>= 2.31), adduser"
recommends = "ffmpeg"
extended-description = """\
Lightweight DVB-T/T2/C television server written in Rust. It scans multiplexes, \
serves channels as HLS, MPEG-TS and M3U playlists (tvheadend-compatible URLs), \
collects EPG from the broadcast (EIT) or XMLTV sources and publishes it as XMLTV, \
records programmes and provides a web panel with an in-browser player."""
maintainer-scripts = "packaging/debian/"
conf-files = ["/etc/default/simply-dvb"]
assets = [
["target/release/simply-dvb", "usr/bin/", "755"],
["packaging/simply-dvb.default", "etc/default/simply-dvb", "644"],
["README.md", "usr/share/doc/simply-dvb/README.md", "644"],
["scripts/import-tvheadend.py", "usr/share/simply-dvb/import-tvheadend.py", "755"],
]
[package.metadata.deb.systemd-units]
unit-name = "simply-dvb"
unit-scripts = "packaging/systemd/"
enable = true
start = true
# restart the service when the package is upgraded (new binary takes effect immediately)
restart-after-upgrade = true
+36
View File
@@ -0,0 +1,36 @@
# syntax=docker/dockerfile:1
FROM rust:1-trixie AS build
WORKDIR /build
COPY Cargo.toml Cargo.lock build.rs ./
COPY migrations ./migrations
COPY langs ./langs
COPY src ./src
COPY web ./web
RUN cargo build --locked --release && strip target/release/simply-dvb
FROM debian:trixie-slim AS runtime
# ffmpeg – optional transcoding profiles (audio→AAC, HEVC→H.264) for browsers
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates ffmpeg tzdata \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd --system --gid 10001 simply-dvb \
&& useradd --system --uid 10001 --gid simply-dvb --home /var/lib/simply-dvb --shell /usr/sbin/nologin simply-dvb \
&& install -d -o simply-dvb -g simply-dvb -m 0750 /var/lib/simply-dvb
COPY --from=build /build/target/release/simply-dvb /usr/local/bin/simply-dvb
# Set TZ to your local zone (e.g. -e TZ=Europe/Berlin) so EPG times and recordings match.
ENV RUST_LOG=simply_dvb=info,warn \
SIMPLY_DVB_DATA_DIR=/var/lib/simply-dvb \
SIMPLY_DVB_LISTEN=0.0.0.0:9980 \
SIMPLY_DVB_STREAM_LISTEN=0.0.0.0:9981 \
SIMPLY_DVB_HTSP_LISTEN=0.0.0.0:9982 \
TZ=Etc/UTC
# Access to /dev/dvb needs the host's "video" group: docker run --group-add $(getent group video | cut -d: -f3)
USER simply-dvb:simply-dvb
VOLUME ["/var/lib/simply-dvb"]
EXPOSE 9980 9981 9982
HEALTHCHECK --interval=30s --timeout=5s CMD ["/bin/sh", "-c", "exec 3<>/dev/tcp/127.0.0.1/9980 && printf 'GET /healthz HTTP/1.0\\r\\n\\r\\n' >&3 && grep -q ok <&3"]
ENTRYPOINT ["/usr/local/bin/simply-dvb"]
CMD ["serve"]
+315
View File
@@ -0,0 +1,315 @@
# simply-dvb
[Polski](README.pl.md)
> Formerly *simple-dvbt* – renamed because it handles more than DVB-T (DVB-T2 and DVB-C too).
> Moving from an old install: `sudo systemctl disable --now simple-dvbt && sudo apt remove simple-dvbt`,
> install `simply-dvb`, stop it and copy the data: `sudo cp -a /var/lib/simple-dvbt/. /var/lib/simply-dvb/ && sudo chown -R simply-dvb: /var/lib/simply-dvb`.
> The `simple-dvbt.db` database is taken over automatically and channel identifiers (UUIDs) do not change.
A lightweight **DVB-T / DVB-T2 / DVB-C** television server written in Rust – a simple alternative to tvheadend that is
**compatible with its HTTP URLs** (it can replace it 1:1 in client apps). It scans multiplexes, serves channels as **HLS**,
**MPEG-TS** and **M3U** playlists, collects **EPG** from the broadcast and publishes it as **XMLTV**, **records** to disk and has
a fast web panel with an in-browser player. A single binary with no runtime dependencies
(ffmpeg is optional – only for transcoding for browsers).
Tested with **Silicon Labs Si2168** (DVB-T/T2/C) cards + Si2157 tuner.
![Overview](docs/images/overview.png)
| TV | TV guide |
|---|---|
| ![TV](docs/images/tv.png) | ![EPG](docs/images/epg.png) |
| ![Channels](docs/images/channels.png) | ![Tuners](docs/images/tuners.png) |
## Features
| Area | What you get |
|---|---|
| Tuners | Native Linux DVB API v5 (ioctl, no `dvbv5-zap`/`w_scan`), multiple adapters, signal strength (dBm/%), SNR (dB), error counter, one multiplex shared by many clients, priorities (recordings > watching > background EPG), virtual adapter from `.ts` files |
| Scanning | DVB-T, DVB-T2 (PLP), DVB-C (symbol rate, QAM). Lists: Europe UHF 21–48 (after the 700 MHz refarming) and 21–69, VHF III + UHF, Italy, Australia (7 MHz), New Zealand, cable 114–858 MHz, custom list, rescan of saved muxes. **NIT discovery** (muxes announced by the network are queued automatically), LCN, automatic channel creation, **background scan** of saved muxes on an idle adapter (every 24 h by default; it gives way immediately when someone starts watching or recording); DVB text in every character table (ISO 6937, ISO 8859-1…16, UTF-8, UCS-2, GB2312, Big5) |
| Channels | Drag-and-drop ordering, numbering, groups, enable/disable, icons (automatic lookup in logo repositories in the background, upload, URL), manual service binding; filters (type, group, enabled, hide scrambled/broken, without icon/EPG) with bulk enable/disable/delete of the filtered list |
| Streams | Live HLS (segmented on keyframes, H.264/HEVC/MPEG-2), continuous MPEG-TS (starting at a keyframe), ffmpeg profiles: `pass` (original), `aac` (audio → AAC), `h264` (HEVC/MPEG-2 → H.264 720p) |
| M3U / XMLTV | `/playlist.m3u` with `tvg-id`, `tvg-chno`, `tvg-logo`, `group-title`, `url-tvg`; `/epg.xml`; **tvheadend paths**: `/playlist`, `/stream/channelid/<id>`, `/xmltv/channels`, `/imagecache/<id>` |
| Ports | Panel/API on **9980**, separate stream port **9981** (like tvheadend's HTTP, no panel – safe to expose), **HTSP on 9982** (like tvheadend: Kodi HTSP client, TVHClient, PVR apps) |
| EPG | Over the air (EIT p/f + schedule, including other muxes), periodic walk over all muxes, **XMLTV import from a URL** (e.g. `https://epg.ovh/pl.xml`, `.xml`/`.xml.gz`), channel matching by id or name, id suggestions from imported sources |
| Browser | hls.js player, automatic profile selection based on the codecs the browser supports (HEVC, AC-3, MP2…) with fallback on errors, EPG grid, one-click recording |
| Sharing | Public link to a single channel (`/watch/<token>`) – a player page without access to other channels |
| Security | Panel login (argon2, HttpOnly sessions, CSRF protection, rate limit), *administrator* / *viewer* roles, ACL: networks with token-free stream access, networks allowed to reach the panel, access tokens (optionally limited to networks), trusted reverse proxies. ACL entries may be networks, addresses or **DDNS host names** (for a dynamic public IP; re-resolved every minute) |
| Recording | From the EPG (with padding) or manual; **series rules** (title fragment or regex, optional channel – like tvheadend's autorec) with a preview of matching programmes; `.ts` file + index, in-browser playback (HLS VOD with byte ranges), download, resume after restart; automatic cleanup (age, minimum free space); **schedule** view per day with **tuner-conflict detection** |
| Player | Keyboard shortcuts: ↑/↓ channel, digits – channel number, F – fullscreen, P – picture-in-picture, M – mute, space – pause, ? – help; OSD with channel number and name |
| Monitoring | Live charts on the overview (15 min history): CPU (system and process), memory, process RSS, streaming throughput, network, clients/HLS sessions, temperature, load; per tuner: mux bitrate, signal strength (%/dBm), SNR, uncorrected blocks. `/metrics` in Prometheus format. Active clients with protocol, device (from the User-Agent / HTSP client name), address, access, duration and rate |
| Logs | *Logs* page with categories (application, tuners & devices, streaming, access, EPG, recording, system), level filter, search, live follow and download; logins, denied requests, tokens and HTSP sessions are logged under *access* |
| Backup | Configuration export/import (muxes, services, channels, rules, tokens, settings) as JSON |
| Interface | English by default, Polish included, **any number of languages** (`langs/<locale>.json` files, picker in the top bar); playback in the browser or **VLC** (single-channel playlist); themes: dark (default), midnight (OLED), light, system; 7 accent colours, density, scale, pinned sidebar, start page, default player profile, EPG grid zoom, clock, logos/programme progress, animations – stored in the browser (*Settings → Appearance*) |
| Distribution | `.deb` package with a (hardened) systemd service, Docker image, `compose.yml` |
## Quick start
### .deb package (Debian / Ubuntu / Raspberry Pi OS)
One script per architecture (also meant for CI):
```bash
scripts/build-deb-amd64.sh # x86_64 (PC, server, NAS) -> dist/simply-dvb_<version>-1_amd64.deb
scripts/build-deb-arm64.sh # Raspberry Pi 3/4/5, 64-bit OS -> dist/simply-dvb_<version>-1_arm64.deb
scripts/build-deb-armhf.sh # Raspberry Pi, 32-bit RPi OS -> dist/simply-dvb_<version>-1_armhf.deb
scripts/build-deb-all.sh # all three
```
All of them call `scripts/build-deb.sh <arch>`. **The build itself runs in a Docker container**
(image `scripts/docker/builder.Dockerfile`: Rust + targets, zig, cargo-zigbuild, cargo-deb), so the host only needs
Docker. The builder image is created on the first run (cached afterwards); crates and build artefacts live in
`.cache/` and `target/docker/`, and the packages land in `dist/` owned by the current user. Cross-compiling with zig
gives a fixed glibc 2.31 baseline, so the packages run on Debian 11+, Ubuntu 20.04+ and RPi OS bullseye+.
Variables: `BUILD_IN_DOCKER=0` (build directly on the host/in CI – then the tools from the builder image are
needed), `BUILDER_IMAGE`, `DOCKER_ARGS`, `DOCKER_BUILD_ARGS` (e.g. `--network host` behind a proxy),
`GLIBC` (default 2.31), `OUT_DIR` (default `dist`).
Install:
```bash
sudo apt install ./dist/simply-dvb_*_$(dpkg --print-architecture).deb
sudo cat /var/lib/simply-dvb/initial-admin-password.txt
```
Panel: `http://<server>:9980/`, streams: `http://<server>:9981/playlist`. Service configuration: `/etc/default/simply-dvb`,
logs: `journalctl -u simply-dvb -f`. The `simply-dvb` user is added to the `video` group.
### Docker
The image builds natively on x86_64 and ARM (also `docker buildx build --platform linux/amd64,linux/arm64 .`).
```bash
docker compose up -d --build # compose.yml: /dev/dvb, video group, host networking
docker logs simply-dvb | grep password
```
The `video` group must have the same GID as on the host: `VIDEO_GID=$(getent group video | cut -d: -f3) docker compose up -d`.
Set `TZ` (e.g. `TZ=Europe/Berlin`) so EPG times and recordings use your local time.
### From source
```bash
cargo build --release
./target/release/simply-dvb --data-dir ./data serve --listen 0.0.0.0:9980 --stream-listen 0.0.0.0:9981
```
Without a DVB card (demo, UI testing):
```bash
./dev.sh demo # generates 2 muxes with a test picture and EPG, runs the virtual adapter
```
## First steps
1. **Tuners** → check that the card is visible (e.g. *Silicon Labs Si2168*, DVB-T / DVB-T2 / DVB-C).
2. **Scanning** → pick the frequency list for your region (e.g. “Europe – UHF 21–48”) → *Start scan*. Channels are created automatically (LCN numbers).
3. **Channels** → reorder by dragging, “Find icons”.
4. **Access** → copy the M3U and EPG URLs into the IPTV app on your TV.
5. **TV** → watch in the browser.
### TV (e.g. Sony / Android TV)
In an IPTV app (e.g. *Kodi + PVR IPTV Simple Client*, *TiviMate*, *IPTV Smarters*, *OTT Navigator*):
* playlist: `http://<server>:9981/playlist` (tvheadend format) or `http://<server>:9981/playlist.m3u` (`?format=hls` for HLS),
* EPG: `http://<server>:9981/xmltv/channels` (or `/epg.xml`).
No token is needed on the local network (private networks are open by default – change it in *Access → ACL*).
From outside the LAN create a token and use `…/playlist.m3u?token=<token>` – the token is appended to
every URL in the playlist and EPG automatically.
## tvheadend compatibility and ports
simply-dvb implements the **tvheadend HTTP interface** used by IPTV apps, Kodi (IPTV Simple), VLC and TVs.
After scanning and arranging the list you only need to change the server address in the app:
| tvheadend | simply-dvb | Notes |
|---|---|---|
| `http://host:9981/playlist` (`/playlist/channels`, `.m3u`, `/playlist/auth/channels`) | same, line for line | `#EXTINF:-1 tvg-logo=… tvg-id=<uuid> tvg-chno=…,Name` |
| `/stream/channelid/<id>`, `/stream/channelnumber/<n>`, `/stream/channelname/<name>`, `/stream/channel/<uuid>` | same | continuous MPEG-TS |
| `/playlist/channelid/<id>` | same | single-channel playlist – e.g. “Open in VLC” |
| `/xmltv`, `/xmltv/channels` | same | channel ids = `tvg-id` from the playlist |
| `/imagecache/<id>` | same | channel logo |
| JSON API `/api/serverinfo`, `/api/channel/grid`, `/api/channeltag/grid`, `/api/epg/events/grid`, `/api/dvr/entry/*`, `/dvrfile/<uuid>` | same (on the stream port) | used by PVR Live, Sparkle TV and other Android TV “Live Channels” sources |
| `?auth=<code>`, `?ticket=<ticket>`, HTTP Basic (login/password) | access token as `auth`/`ticket`; Basic: a panel user's login and password, or a token as the password | |
| `?profile=pass`, `webtv-h264-aac-mpegts` … | `pass`; webtv profiles → `h264`; unknown → `pass` | |
| port 9981 (HTTP) | **9981 – separate stream port** (no panel or API) | panel on **9980** |
| port 9982 (HTSP) | **9982 – HTSP server** | Kodi “Tvheadend HTSP Client”, TVHClient, PVR apps |
Things worth knowing:
* **HTSP (9982)** – tvheadend's binary protocol. Apps configured with a server address and port 9981 that then
stream over 9982 (Kodi “Tvheadend HTSP Client”, TVHClient, PVR apps on Android/Google/Sony TV) use it.
Supported: channels and tags, EPG (async updates, queries), live streaming (frames as `muxpkt`, signal and
queue status), recordings (list, schedule, cancel, delete, playback over HTSP), disk space, tickets for HTTP.
Not supported: timeshift (pause/rewind of live TV) and recording rules over HTSP (use the panel).
Authentication: open networks need no login; elsewhere enter any user name and an **access token as the
password** (HTSP digests cannot be checked against stored panel passwords).
* While tvheadend still holds port **9981** (or **9982**), simply-dvb keeps running: streams are served on the panel port
and the stream port is taken over automatically (checked every 15 s) as soon as tvheadend is stopped –
no restart needed, and TV apps keep their `:9981` URLs.
* The stream port only serves playlists, streams (TS/HLS), EPG, icons, public `/watch/…` links and metrics –
no panel and no API. You can expose it via your router/reverse proxy and keep the panel on the LAN
(see also *Access → ACL*). All of these paths also work on the panel port.
### Moving the channel list from tvheadend
After scanning, `scripts/import-tvheadend.py` copies the channel numbers (and optionally names, groups from tags
and the enabled state) from tvheadend. Channels are matched in passes: by service (ONID/TSID/SID, or SID + frequency),
by name, by a loose name without quality/test/prefix words (“Zet” = “Radio ZET em.test.”) and by a similar name;
tvheadend duplicates (two channels for one service) are listed and skipped.
It runs a dry run first and changes nothing without `--apply`; only the Python 3 standard library is needed
(the .deb installs it as `/usr/share/simply-dvb/import-tvheadend.py`).
```bash
# tvheadend still running (HTTP API, admin user)
scripts/import-tvheadend.py --tvh http://<server>:9981 --tvh-user admin --url http://<server>:9980 --user admin
# or from tvheadend's configuration directory (also works when tvheadend is stopped)
sudo scripts/import-tvheadend.py --tvh-config /var/lib/tvheadend --url http://localhost:9980 --user admin \
--names --groups --enabled --apply
```
Options: `--names` (only names set by hand in tvheadend; `--names all` copies every name – these may be stale
after a broadcaster renamed a channel), `--reset-names` (back to the current broadcast names), `--groups`, `--enabled`,
`--fuzzy 0.86` (similarity threshold, `1` = exact names only), `--create` (create channels for services that have none yet),
`--unmatched keep|after|disable` (what to do with simply-dvb channels tvheadend does not have; default: number them
after the imported ones). Both can run side by side during the migration (tvheadend on 9981, simply-dvb's panel on its own port);
after stopping tvheadend, simply-dvb takes over 9981 by itself.
## HTTP endpoints
| URL | Description |
|---|---|
| `/playlist.m3u` | Playlist. Parameters: `format=ts\|hls`, `profile=pass\|aac\|h264`, `token=` |
| `/epg.xml` | XMLTV for enabled channels |
| `/stream/<id>.ts` | Continuous MPEG-TS of a channel (optional `profile=`) |
| `/hls/<id>/index.m3u8` | Live HLS of a channel (optional `profile=`) |
| `/watch/<share>` | Public player page (share link) |
| `/icons/<id>.png` | Channel icon |
| `/recordings/<id>/index.m3u8`, `/recordings/<id>/file` | Recording: HLS VOD / file (`Range` supported) |
| `/api/*` | Panel API (JSON, needs a session; state-changing requests need the `X-Requested-With: simply-dvb` header) |
| `/metrics` | Prometheus metrics (access like streams: local network, token, session) |
| `/healthz` | Health check |
Stream access is checked in this order: `token=` → `share=` (single channel only) → client address in
“networks without a token” → panel session → HTTP Basic (password = token).
## Browser playback and profiles
The original stream (`pass`) is played without any transcoding whenever the browser can decode it –
hls.js repackages MPEG-TS (H.264, **HEVC**, MPEG audio/MP2, AAC, AC-3) in the browser, the server does no work.
What a browser can decode depends on the browser and the GPU:
| Codec | Chrome / Edge | Firefox | Safari |
|---|---|---|---|
| H.264, MP2, AAC | yes | yes | yes |
| HEVC (H.265) | only with hardware decoding (Windows/macOS/Android; Linux: VA-API) | Windows/macOS (hardware), Linux 137+ with VA-API | yes |
| AC-3 / E-AC-3 | no | no | yes |
Many DVB-T2 networks (e.g. Poland: HEVC video, MP2 + E-AC-3 audio) are fine in Safari and in Chrome/Edge with
hardware HEVC decoding: the player picks the MP2 track automatically. On Chrome for Linux, HEVC needs a VA-API
capable GPU (Intel/AMD) – check `chrome://gpu` (“Video Decode: Hardware accelerated”).
When the browser cannot decode a codec, the player switches to a transcoding profile – **this needs ffmpeg
on the server** (`apt install ffmpeg`). Without ffmpeg the player always tries the original stream and, if it
fails, explains why and offers *Open in VLC*. The TV page shows which codecs the current browser supports.
* `pass` – unchanged,
* `aac` – video unchanged, audio transcoded to AAC (lightweight),
* `h264` – full transcoding to H.264 720p (CPU-heavy; arguments in *Settings → ffmpeg*,
VAAPI can be enabled, e.g. `-vaapi_device /dev/dri/renderD128 -vf 'format=nv12,hwupload,scale_vaapi=w=-2:h=720' -c:v h264_vaapi`).
A profile can also be forced in the player or with the `profile=` URL parameter. TVs, VLC and Kodi decode
HEVC/E-AC-3 themselves, so the M3U playlists always use the original stream.
## Languages
The interface, server messages and logs are in English; translations are JSON files in `langs/`
(same layout as RustProxy). The English text doubles as the translation key.
```json
{
"meta": { "locale": "pl_PL", "name": "Polish", "native_name": "Polski", "direction": "ltr" },
"translations": { "Channels": "Kanały", "Recording scheduled": "Zaplanowano nagranie" },
"patterns": [ { "match": "^Found (\\d+) icons$", "replace": "Znaleziono $1 ikon" } ]
}
```
* `langs/en_US.json` is required (default language and the full key catalogue); `langs/pl_PL.json` is Polish.
* **Adding a language = adding a file.** Every `langs/*.json` found at build time is embedded and shows up
automatically in the language picker (top bar and *Settings → Appearance*) – no code changes.
* `node scripts/i18n-missing.js --new de_DE "Deutsch" "German"` creates a pack with all keys; empty values fall
back to English, so a language can be translated gradually.
* `node scripts/i18n-missing.js pl_PL` lists missing entries, `node scripts/i18n-missing.js --sources` lists panel texts
without an entry in `en_US.json`.
* `patterns` handle texts with values: `$1` inserts a group as-is, `$t1` translates it again.
* `build.rs` validates the files (valid JSON, `meta.locale` = file name) and embeds them in the JS bundle.
## EPG over the air and from the internet
* **Over the air (EIT)** – collected while watching and periodically from every mux (*Settings → EPG*).
* **From an XMLTV URL** – e.g. `https://epg.ovh/pl.xml` (or any other provider; `.xml` and `.xml.gz` supported).
Channels are matched by name; when names differ, pick the id in the channel's *EPG ID* field
(suggestions come from the imported sources). XMLTV data takes precedence over EIT.
## Si2168 tips
* Firmware: `firmware-linux-nonfree` (Debian) / `linux-firmware` – the `dvb-demod-si2168-*.fw` files.
No firmware = no lock; check `dmesg | grep -i si2168`.
* Command-line test (without starting the server):
```bash
simply-dvb adapters
simply-dvb tune --freq 538 --system dvbt2
simply-dvb tune --freq 346 --system dvbc --symbol-rate 6900 --modulation qam256
```
* Signal strength is reported by the Si2157 tuner in dBm, SNR by the Si2168 in dB.
* DVB-T2 with multiple PLPs: set the PLP when adding a mux manually.
## Architecture
```
/dev/dvb/adapterN ──► reader thread (frontend+demux+dvr, full TS) ──► broadcast
│ │
EIT → SI collector → EPG (SQLite) ├─► service filter (PAT/PMT) ─► client TS
├─► [ffmpeg] ─► HLS segmenter ─► HLS session
└─► segmenter ─► recording file + index
```
* `src/dvb` – Linux DVB ioctls, virtual adapter, scanning,
* `src/ts` – MPEG-TS: packets, PSI/SI sections with CRC, PAT/PMT/SDT/NIT/EIT/TDT, DVB text, PES, test generator,
* `src/stream` – service filter and HLS segmenter,
* `src/tuner.rs` – tuner allocation, sharing, preemption, statistics,
* `src/hls.rs`, `src/pipeline.rs`, `src/recorder.rs`, `src/epg.rs`, `src/scanjob.rs`,
* `src/web` – axum: API, streams, panel.
Panel (like RustProxy): the sources in `web/css/*.css`, `web/js/*.js` and `langs/*.json` (+ `web/vendor/hls.min.js`) are
combined at build time (`build.rs`) into **one CSS and one JS file with unique names** (`app.<hash>.css`,
`app.<hash>.js`), embedded in the binary and served with `Cache-Control: immutable`.
Data: `<data-dir>/simply-dvb.db` (SQLite), `icons/`, `recordings/`.
## Development
```bash
./dev.sh check # fmt, clippy -D warnings, JS syntax, language packs
./dev.sh test # unit + end-to-end tests (virtual adapter: scan, HLS, TS, EPG, ACL, recording)
./dev.sh run # development server (./data)
./dev.sh docker # Docker image
./dev.sh deb-all # .deb for amd64, arm64 and armhf
./dev.sh dist # check + test + all .deb + docker
```
Runtime options (also as environment variables): `--data-dir` (`SIMPLY_DVB_DATA_DIR`),
`--dev-root` (`SIMPLY_DVB_DEV_ROOT`), `--virtual-dir` (`SIMPLY_DVB_VIRTUAL_DIR`, a directory with
`<MHz>.ts` files), `serve --listen` (`SIMPLY_DVB_LISTEN`, panel, default 9980), `serve --stream-listen`
(`SIMPLY_DVB_STREAM_LISTEN`, stream port, default 9981, `off` disables it). Users from the command line:
`simply-dvb user add <login> --role admin|viewer`, `simply-dvb user passwd <login>`.
Translations: engine in `web/js/10-i18n.js`, packs in `langs/*.json`. New UI text (in English) needs an entry in
`langs/en_US.json` and translations in the other packs (or a `patterns` entry for texts with values).
Code comments, logs and messages are English.
The player uses [hls.js](https://github.com/video-dev/hls.js) (Apache-2.0, `web/vendor/`).
+310
View File
@@ -0,0 +1,310 @@
# simply-dvb
[English](README.md) · dokumentacja główna jest po angielsku; to jest wersja polska.
> Wcześniej: *simple-dvbt*. Nazwa zmieniona, bo projekt obsługuje nie tylko DVB-T (także DVB-T2 i DVB-C).
> Przejście ze starej instalacji: `sudo systemctl disable --now simple-dvbt && sudo apt remove simple-dvbt`,
> zainstaluj `simply-dvb`, zatrzymaj go i skopiuj dane: `sudo cp -a /var/lib/simple-dvbt/. /var/lib/simply-dvb/ && sudo chown -R simply-dvb: /var/lib/simply-dvb`.
> Baza `simple-dvbt.db` zostanie przejęta automatycznie, identyfikatory kanałów (UUID) się nie zmieniają.
Lekki serwer telewizji **DVB-T / DVB-T2 / DVB-C** napisany w Rust – prosta alternatywa dla tvheadend,
**zgodna z jego adresami HTTP** (można go podmienić 1:1 w aplikacjach): skanuje multipleksy, udostępnia kanały jako **HLS**, **MPEG-TS** i playlistę **M3U**,
zbiera **EPG** z sygnału i publikuje je jako **XMLTV**, **nagrywa** na dysk i ma szybki panel WWW
z odtwarzaczem w przeglądarce. Jeden plik binarny, bez zależności w czasie działania
(ffmpeg jest opcjonalny – tylko do transkodowania dla przeglądarek).
Testowany z kartami na **Silicon Labs Si2168** (DVB-T/T2/C) + tuner Si2157.
![Przegląd](docs/images/overview.png)
| Telewizja | Program TV |
|---|---|
| ![Telewizja](docs/images/tv.png) | ![EPG](docs/images/epg.png) |
| ![Kanały](docs/images/channels.png) | ![Tunery](docs/images/tuners.png) |
## Możliwości
| Obszar | Co jest |
|---|---|
| Tunery | Natywne Linux DVB API v5 (ioctl, bez `dvbv5-zap`/`w_scan`), wiele adapterów, siła sygnału (dBm/%), SNR (dB), licznik błędów, współdzielenie multipleksu przez wielu klientów, priorytety (nagrania > oglądanie > EPG w tle), adapter wirtualny z plików `.ts` |
| Skanowanie | DVB-T, DVB-T2 (PLP), DVB-C (symbol rate, QAM). Listy: Europa UHF 21–48 (po refarmingu 700 MHz) i 21–69, VHF III + UHF, Włochy, Australia (7 MHz), Nowa Zelandia, kablówka 114–858 MHz, własna lista, ponowne skanowanie zapisanych. **Odkrywanie przez NIT** (multipleksy ogłaszane przez sieć dopisywane do kolejki), LCN, automatyczne tworzenie kanałów, **skanowanie w tle** zapisanych multipleksów na wolnym adapterze (domyślnie co 24 h; ustępuje od razu, gdy ktoś zaczyna oglądać lub nagrywać); teksty DVB we wszystkich tablicach znaków (ISO 6937, ISO 8859-1…16, UTF-8, UCS-2, GB2312, Big5) |
| Kanały | Lista z przeciąganiem (kolejność), numeracja, grupy, włącz/wyłącz, ikony (automatyczne wyszukiwanie w tle, wgrywanie, URL), ręczne powiązanie z usługą; filtry (typ, grupa, włączone, ukryj kodowane/uszkodzone, bez ikony/EPG) i zbiorcze włącz/wyłącz/usuń przefiltrowanej listy |
| Strumienie | HLS live (segmentacja na klatkach kluczowych, H.264/HEVC/MPEG-2), ciągły MPEG-TS (start od klatki kluczowej), profile ffmpeg: `pass` (oryginał), `aac` (audio → AAC), `h264` (HEVC/MPEG-2 → H.264 720p) |
| M3U / XMLTV | `/playlist.m3u` z `tvg-id`, `tvg-chno`, `tvg-logo`, `group-title`, `url-tvg`; `/epg.xml`; **ścieżki tvheadend**: `/playlist`, `/stream/channelid/<id>`, `/xmltv/channels`, `/imagecache/<id>` |
| Porty | Panel/API na **9980**, osobny port strumieni **9981**, **HTSP na 9982** (jak HTTP tvheadend, bez panelu – można go wystawić na zewnątrz) |
| EPG | Z eteru (EIT p/f + harmonogram, także z innych multipleksów), okresowe przechodzenie po multipleksach, **import XMLTV z linku** (np. `https://epg.ovh/pl.xml`, `.xml`/`.xml.gz`), dopasowanie kanałów po ID lub nazwie, podpowiedzi identyfikatorów z zaimportowanych źródeł |
| Przeglądarka | Odtwarzacz hls.js, automatyczny dobór profilu wg kodeków obsługiwanych przez przeglądarkę (HEVC, AC-3, MP2…) z przełączaniem w razie błędu, siatka EPG, nagrywanie jednym kliknięciem |
| Udostępnianie | Publiczny link do pojedynczego kanału (`/watch/<token>`) – strona z odtwarzaczem, bez dostępu do innych kanałów |
| Bezpieczeństwo | Logowanie do panelu (argon2, sesje HttpOnly, ochrona CSRF, limit prób), role *administrator* / *widz*, ACL: sieci z dostępem do strumieni bez tokenu, sieci z dostępem do panelu, tokeny dostępu (z opcjonalnym ograniczeniem do sieci), zaufane reverse proxy. Wpisy ACL mogą być sieciami, adresami lub **nazwami hostów DDNS** (dla zmiennego publicznego IP; odświeżane co minutę) |
| Nagrywanie | Z EPG (z marginesami) lub ręcznie; **reguły seryjne** (fragment tytułu lub regex, opcjonalnie kanał – jak autorec w tvheadend) z podglądem pasujących audycji; plik `.ts` + indeks, odtwarzanie w przeglądarce (HLS VOD z byte-range), pobieranie, wznowienie po restarcie; automatyczne porządkowanie (wiek, minimalne wolne miejsce) |
| Odtwarzacz | Skróty klawiszowe: ↑/↓ zmiana kanału, cyfry – numer kanału, F – pełny ekran, P – obraz w obrazie, M – wycisz, spacja – pauza, ? – pomoc; OSD z numerem i nazwą kanału |
| Logi | Zakładka *Logi* z kategoriami (aplikacja, tunery i urządzenia, strumieniowanie, dostęp, EPG, nagrywanie, system), filtrem poziomu, wyszukiwaniem, śledzeniem na żywo i pobieraniem; logowania, odrzucone żądania, tokeny i sesje HTSP trafiają do kategorii *dostęp*. Aktywni klienci: protokół, urządzenie (z User-Agent / nazwy klienta HTSP), adres, dostęp, czas, przepływność; harmonogram nagrań z wykrywaniem konfliktów tunerów |
| Monitoring | Wykresy na żywo w przeglądzie (historia 15 min): CPU (system i proces), pamięć, RSS procesu, przepustowość strumieni, sieć, klienci/sesje HLS, temperatura, obciążenie; dla tunera: przepływność, siła sygnału (%/dBm), SNR, bloki z błędami. `/metrics` w formacie Prometheus |
| Kopia zapasowa | Eksport/import konfiguracji (multipleksy, usługi, kanały, reguły, tokeny, ustawienia) jako JSON |
| Interfejs | Angielski (domyślnie) i polski, **dowolna liczba języków** (pliki `langs/<locale>.json` – każdy plik pojawia się po zbudowaniu w liście wyboru języka); odtwarzanie w przeglądarce lub **VLC** (playlista jednego kanału); motywy: ciemny (domyślny), północ (OLED), jasny, systemowy; 7 kolorów akcentu, gęstość, skala, przypięty pasek boczny, strona startowa, domyślny profil odtwarzacza, powiększenie siatki EPG, zegar, logotypy/postęp audycji, animacje – zapisywane w przeglądarce (*Ustawienia → Wygląd*) |
| Dystrybucja | Paczka `.deb` z usługą systemd (utwardzoną), obraz Docker, `compose.yml` |
## Szybki start
### Paczka .deb (Debian / Ubuntu / Raspberry Pi OS)
Osobne skrypty dla każdej architektury (do użycia także w CI):
```bash
scripts/build-deb-amd64.sh # x86_64 (PC, serwer, NAS) -> dist/simply-dvb_<wersja>-1_amd64.deb
scripts/build-deb-arm64.sh # Raspberry Pi 3/4/5, 64-bit OS -> dist/simply-dvb_<wersja>-1_arm64.deb
scripts/build-deb-armhf.sh # Raspberry Pi, 32-bit RPi OS -> dist/simply-dvb_<wersja>-1_armhf.deb
scripts/build-deb-all.sh # wszystkie trzy
```
Wszystkie wywołują `scripts/build-deb.sh <arch>`. **Sama budowa odbywa się w kontenerze Docker**
(obraz `scripts/docker/builder.Dockerfile`: Rust + targety, zig, cargo-zigbuild, cargo-deb), więc na hoście
potrzebny jest tylko Docker. Obraz budujący tworzy się automatycznie przy pierwszym uruchomieniu
(później z cache); crates i kompilacja są trzymane w `.cache/` i `target/docker/`, a gotowe paczki trafiają do
`dist/` z uprawnieniami bieżącego użytkownika. Kompilacja skrośna przez zig daje stałą bazę glibc 2.31,
więc paczki działają na Debianie 11+, Ubuntu 20.04+ i RPi OS bullseye+.
Zmienne: `BUILD_IN_DOCKER=0` (budowa bezpośrednio na hoście/w CI – wtedy potrzebne narzędzia jak
w obrazie budującym), `BUILDER_IMAGE`, `DOCKER_ARGS`, `DOCKER_BUILD_ARGS` (np. `--network host` za proxy),
`GLIBC` (domyślnie 2.31), `OUT_DIR` (domyślnie `dist`).
Instalacja:
```bash
sudo apt install ./dist/simply-dvb_*_$(dpkg --print-architecture).deb
sudo cat /var/lib/simply-dvb/initial-admin-password.txt
```
Panel: `http://<serwer>:9980/`, strumienie: `http://<serwer>:9981/playlist`. Konfiguracja usługi: `/etc/default/simply-dvb`,
logi: `journalctl -u simply-dvb -f`. Użytkownik `simply-dvb` jest dodawany do grupy `video`.
### Docker
Obraz buduje się natywnie na x86_64 i ARM (także `docker buildx build --platform linux/amd64,linux/arm64 .`).
```bash
docker compose up -d --build # compose.yml: /dev/dvb, grupa video, sieć hosta
docker logs simply-dvb | grep hasłem
```
Grupa `video` musi mieć ten sam GID co na hoście: `VIDEO_GID=$(getent group video | cut -d: -f3) docker compose up -d`.
### Ze źródeł
```bash
cargo build --release
./target/release/simply-dvb --data-dir ./data serve --listen 0.0.0.0:9980 --stream-listen 0.0.0.0:9981
```
Bez karty DVB (demo, testy interfejsu):
```bash
./dev.sh demo # generuje 2 multipleksy z obrazem testowym i EPG, uruchamia adapter wirtualny
```
## Pierwsze kroki
1. **Tunery** → sprawdź, czy karta jest widoczna (np. *Silicon Labs Si2168*, DVB-T / DVB-T2).
2. **Skanowanie** → lista dla Twojego regionu (np. „Europa – UHF 21–48”) → *Rozpocznij skanowanie*. Kanały tworzą się automatycznie (numery LCN).
3. **Kanały** → ułóż kolejność przeciąganiem, „Szukaj ikon”.
4. **Dostęp** → skopiuj adres M3U i EPG do aplikacji IPTV w telewizorze.
5. **Telewizja** → oglądanie w przeglądarce.
### Telewizor (np. Sony / Android TV)
W aplikacji IPTV (np. *Kodi + PVR IPTV Simple Client*, *TiviMate*, *IPTV Smarters*, *OTT Navigator*):
* playlista: `http://<serwer>:9981/playlist` (format tvheadend) albo `http://<serwer>:9981/playlist.m3u` (`?format=hls` dla HLS),
* EPG: `http://<serwer>:9981/xmltv/channels` (lub `/epg.xml`).
W sieci lokalnej token nie jest potrzebny (domyślnie otwarte są sieci prywatne – zmienisz w *Dostęp → ACL*).
Spoza LAN utwórz token i użyj `…/playlist.m3u?token=<token>` – token jest automatycznie doklejany do
wszystkich adresów w playliście i EPG.
## Zgodność z tvheadend i porty
simply-dvb odtwarza **interfejs HTTP tvheadend**, z którego korzystają aplikacje IPTV, Kodi (IPTV Simple),
VLC i telewizory. Po zeskanowaniu i ułożeniu listy wystarczy w aplikacji zmienić tylko adres serwera:
| tvheadend | simply-dvb | Uwagi |
|---|---|---|
| `http://host:9981/playlist` (`/playlist/channels`, `.m3u`, `/playlist/auth/channels`) | to samo, linia w linię | `#EXTINF:-1 tvg-logo=… tvg-id=<uuid> tvg-chno=…,Nazwa` |
| `/stream/channelid/<id>`, `/stream/channelnumber/<n>`, `/stream/channelname/<nazwa>`, `/stream/channel/<uuid>` | to samo | ciągły MPEG-TS |
| `/playlist/channelid/<id>` | to samo | playlista jednego kanału – np. „Otwórz w VLC” |
| `/xmltv`, `/xmltv/channels` | to samo | identyfikatory kanałów = `tvg-id` z playlisty |
| `/imagecache/<id>` | to samo | logo kanału |
| JSON API `/api/serverinfo`, `/api/channel/grid`, `/api/channeltag/grid`, `/api/epg/events/grid`, `/api/dvr/entry/*`, `/dvrfile/<uuid>` | to samo (na porcie strumieni) | używa go PVR Live, Sparkle TV i inne źródła „Kanały na żywo” w Android TV |
| `?auth=<kod>`, `?ticket=<bilet>`, HTTP Basic (login/hasło) | token dostępu jako `auth`/`ticket`; Basic: login i hasło użytkownika panelu albo token jako hasło | |
| `?profile=pass`, `webtv-h264-aac-mpegts` … | `pass`; profile webtv → `h264`; nieznane → `pass` | |
| port 9981 (HTTP) | **9981 – osobny port strumieni** (bez panelu i API) | panel na **9980** |
| port 9982 (HTSP) | **9982 – serwer HTSP** | Kodi „Tvheadend HTSP Client”, TVHClient, aplikacje PVR |
Warto wiedzieć:
* **HTSP (9982)** – binarny protokół tvheadend. Używają go aplikacje, w których podaje się adres serwera i port 9981,
a obraz idzie przez 9982 (Kodi „Tvheadend HTSP Client”, TVHClient, aplikacje PVR na Android/Google/Sony TV).
Obsługiwane: kanały i tagi, EPG (aktualizacje na żywo, wyszukiwanie), oglądanie na żywo (ramki jako `muxpkt`,
stan sygnału i kolejki), nagrania (lista, planowanie, anulowanie, usuwanie, odtwarzanie przez HTSP), miejsce na
dysku, bilety HTTP. Bez obsługi: timeshift (pauza/cofanie na żywo) i reguły nagrań przez HTSP (są w panelu).
Logowanie: w sieciach otwartych niepotrzebne; z innych podaj dowolną nazwę użytkownika i **token dostępu jako
hasło** (skrótów HTSP nie da się sprawdzić względem zapisanych haseł panelu).
* Dopóki tvheadend zajmuje port **9981** (lub **9982**), simply-dvb działa dalej: strumienie są dostępne na porcie panelu,
a port strumieni zostaje przejęty automatycznie (sprawdzane co 15 s), gdy tylko zatrzymasz tvheadend –
bez restartu, a aplikacje w telewizorach zachowują adresy `:9981`.
* Na porcie strumieni dostępne są tylko playlisty, strumienie (TS/HLS), EPG, ikony, publiczne linki
`/watch/…` i metryki – bez panelu i API. Można go wystawić przez router/reverse proxy, a panel zostawić
w LAN (dodatkowo *Dostęp → ACL*). Wszystkie te ścieżki działają też na porcie panelu.
### Przeniesienie listy kanałów z tvheadend
Po skanowaniu `scripts/import-tvheadend.py` kopiuje numery kanałów (opcjonalnie też nazwy, grupy z tagów i stan
włączenia) z tvheadend. Dopasowanie w kilku przebiegach: po usłudze (ONID/TSID/SID albo SID + częstotliwość), po
nazwie, po nazwie bez słów jakości/testu/przedrostków („Zet” = „Radio ZET em.test.”) i po nazwie podobnej; duplikaty
w tvheadend (dwa kanały na jedną usługę) są wypisywane i pomijane. Najpierw pokazuje
plan i bez `--apply` niczego nie zmienia; wymaga tylko Pythona 3 (paczka .deb instaluje go jako
`/usr/share/simply-dvb/import-tvheadend.py`).
```bash
# tvheadend nadal działa (API HTTP, użytkownik z uprawnieniami admina)
scripts/import-tvheadend.py --tvh http://<serwer>:9981 --tvh-user admin --url http://<serwer>:9980 --user admin
# albo z katalogu konfiguracji tvheadend (działa też przy zatrzymanym tvheadend)
sudo scripts/import-tvheadend.py --tvh-config /var/lib/tvheadend --url http://localhost:9980 --user admin \
--names --groups --enabled --apply
```
Opcje: `--names` (tylko nazwy nadane ręcznie w tvheadend; `--names all` kopiuje wszystkie – mogą być nieaktualne,
gdy nadawca zmienił nazwę kanału), `--reset-names` (powrót do bieżących nazw z sygnału), `--groups`, `--enabled`,
`--fuzzy 0.86` (próg podobieństwa, `1` = tylko dokładne nazwy), `--create` (tworzy kanały dla usług, które ich jeszcze nie mają),
`--unmatched keep|after|disable` (co zrobić z kanałami simply-dvb, których tvheadend nie ma; domyślnie numeracja za
importowanymi). Na czas migracji oba mogą działać obok siebie (tvheadend na 9981, panel simply-dvb na własnym porcie);
po zatrzymaniu tvheadend simply-dvb sam przejmie port 9981.
## Punkty dostępu (HTTP)
| Adres | Opis |
|---|---|
| `/playlist.m3u` | Playlista. Parametry: `format=ts\|hls`, `profile=pass\|aac\|h264`, `token=` |
| `/epg.xml` | XMLTV dla włączonych kanałów |
| `/stream/<id>.ts` | Ciągły MPEG-TS kanału (`profile=` opcjonalnie) |
| `/hls/<id>/index.m3u8` | HLS live kanału (`profile=` opcjonalnie) |
| `/watch/<share>` | Publiczna strona z odtwarzaczem (link udostępnienia) |
| `/icons/<id>.png` | Ikona kanału |
| `/recordings/<id>/index.m3u8`, `/recordings/<id>/file` | Nagranie: HLS VOD / plik (obsługa `Range`) |
| `/api/*` | API panelu (JSON, wymaga sesji; zapytania zmieniające stan wymagają nagłówka `X-Requested-With: simply-dvb`) |
| `/metrics` | Metryki Prometheus (dostęp jak do strumieni: sieć lokalna, token, sesja) |
| `/healthz` | Kontrola działania |
Dostęp do strumieni (w tej kolejności): `token=` → `share=` (tylko jeden kanał) → adres klienta w
„sieciach bez tokenu” → sesja panelu → HTTP Basic (hasło = token).
## Odtwarzanie w przeglądarce i profile
Oryginalny strumień (`pass`) jest odtwarzany bez transkodowania zawsze, gdy przeglądarka umie go zdekodować –
hls.js przepakowuje MPEG-TS (H.264, **HEVC**, MPEG audio/MP2, AAC, AC-3) w przeglądarce, serwer nic nie liczy.
| Kodek | Chrome / Edge | Firefox | Safari |
|---|---|---|---|
| H.264, MP2, AAC | tak | tak | tak |
| HEVC (H.265) | tylko z dekodowaniem sprzętowym (Windows/macOS/Android; Linux: VA-API) | Windows/macOS (sprzętowo), Linux 137+ z VA-API | tak |
| AC-3 / E-AC-3 | nie | nie | tak |
Polskie DVB-T2 to HEVC + dźwięk MP2 i E-AC-3: działa w Safari oraz w Chrome/Edge ze sprzętowym dekodowaniem HEVC
(odtwarzacz sam wybiera ścieżkę MP2). W Chrome na Linuksie HEVC wymaga karty z VA-API (Intel/AMD) – sprawdź
`chrome://gpu` („Video Decode: Hardware accelerated”).
Gdy przeglądarka nie obsługuje kodeka, odtwarzacz przełącza się na profil z transkodowaniem – **to wymaga
ffmpeg na serwerze** (`apt install ffmpeg`). Bez ffmpeg odtwarzacz zawsze próbuje oryginału, a gdy się nie uda,
wyjaśnia przyczynę i proponuje *Otwórz w VLC*. Strona Telewizja pokazuje, które kodeki obsługuje bieżąca przeglądarka.
* `pass` – bez zmian,
* `aac` – obraz bez zmian, dźwięk przekodowany do AAC (lekkie),
* `h264` – pełne transkodowanie do H.264 720p (obciąża CPU; argumenty w *Ustawienia → ffmpeg*,
można włączyć VAAPI, np. `-vaapi_device /dev/dri/renderD128 -vf 'format=nv12,hwupload,scale_vaapi=w=-2:h=720' -c:v h264_vaapi`).
Telewizory, VLC i Kodi same dekodują HEVC/E-AC-3, więc playlisty M3U zawsze podają oryginalny strumień.
## Języki
Interfejs, komunikaty serwera i logi są po angielsku; tłumaczenia to pliki JSON w katalogu `langs/`
(format jak w RustProxy). Angielski tekst jest jednocześnie kluczem tłumaczenia.
```json
{
"meta": { "locale": "pl_PL", "name": "Polish", "native_name": "Polski", "direction": "ltr" },
"translations": { "Channels": "Kanały", "Recording scheduled": "Zaplanowano nagranie" },
"patterns": [ { "match": "^Found (\\d+) icons$", "replace": "Znaleziono $1 ikon" } ]
}
```
* `langs/en_US.json` – wymagany (domyślny język i pełny katalog kluczy), `langs/pl_PL.json` – polski,
* nowy język: `node scripts/i18n-missing.js --new de_DE "Deutsch" "German"` tworzy plik ze wszystkimi kluczami;
puste wartości są brane z angielskiego, więc można tłumaczyć stopniowo,
* `node scripts/i18n-missing.js pl_PL` – brakujące wpisy, `node scripts/i18n-missing.js --sources` – teksty panelu bez wpisu w `en_US.json`,
* `patterns` obsługują teksty z wartościami: `$1` – wstawia grupę bez zmian, `$t1` – tłumaczy ją ponownie,
* `build.rs` sprawdza pliki (poprawny JSON, `meta.locale` = nazwa pliku) i wbudowuje je w paczkę JS;
język pojawia się automatycznie w przełączniku w górnym pasku i w *Ustawienia → Wygląd*.
## EPG z eteru i z internetu
* **Z eteru (EIT)** – zbierane podczas oglądania i okresowo z każdego multipleksu (*Ustawienia → EPG*).
* **Z linku XMLTV** – np. `https://epg.ovh/pl.xml` (lub inny dostawca; obsługiwane `.xml` i `.xml.gz`).
Kanały dopasowują się po nazwie; gdy nazwa się różni, wybierz identyfikator w polu *Identyfikator EPG*
kanału (podpowiedzi pochodzą z zaimportowanych źródeł). Dane XMLTV mają pierwszeństwo przed EIT.
## Si2168 – wskazówki
* Firmware: pakiet `firmware-linux-nonfree` (Debian) / `linux-firmware` – pliki `dvb-demod-si2168-*.fw`.
Brak firmware = brak locka; sprawdź `dmesg | grep -i si2168`.
* Test z linii poleceń (bez uruchamiania serwera):
```bash
simply-dvb adapters
simply-dvb tune --freq 538 --system dvbt2
simply-dvb tune --freq 346 --system dvbc --symbol-rate 6900 --modulation qam256
```
* Siła sygnału jest raportowana przez tuner Si2157 w dBm, SNR przez Si2168 w dB.
* DVB-T2 z wieloma PLP: PLP ustawisz przy ręcznym dodawaniu multipleksu.
## Architektura
```
/dev/dvb/adapterN ──► wątek odczytu (frontend+demux+dvr, pełny TS) ──► broadcast
│ │
EIT → kolektor SI → EPG (SQLite) ├─► filtr usługi (PAT/PMT) ─► TS klienta
├─► [ffmpeg] ─► segmenter HLS ─► sesja HLS
└─► segmenter ─► plik nagrania + indeks
```
* `src/dvb` – ioctl Linux DVB, adapter wirtualny, skanowanie,
* `src/ts` – MPEG-TS: pakiety, sekcje PSI/SI z CRC, PAT/PMT/SDT/NIT/EIT/TDT, teksty DVB, PES, generator testowy,
* `src/stream` – filtr usługi i segmenter HLS,
* `src/tuner.rs` – przydział tunerów, współdzielenie, wywłaszczanie, statystyki,
* `src/hls.rs`, `src/pipeline.rs`, `src/recorder.rs`, `src/epg.rs`, `src/scanjob.rs`,
* `src/web` – axum: API, strumienie, panel.
Panel (jak w RustProxy): źródła w `web/css/*.css`, `web/js/*.js` i `langs/*.json` (+ `web/vendor/hls.min.js`) są przy
kompilacji (`build.rs`) łączone w **jeden plik CSS i jeden JS o unikalnych nazwach** (`app.<hash>.css`,
`app.<hash>.js`), wbudowywane w binarkę i serwowane z `Cache-Control: immutable`.
Dane: `<data-dir>/simply-dvb.db` (SQLite), `icons/`, `recordings/`.
## Rozwój
```bash
./dev.sh check # fmt, clippy -D warnings, składnia JS
./dev.sh test # testy jednostkowe + end-to-end (adapter wirtualny: skan, HLS, TS, EPG, ACL, nagrywanie)
./dev.sh run # serwer deweloperski (./data)
./dev.sh docker # obraz Docker
./dev.sh deb-all # .deb dla amd64, arm64 i armhf
./dev.sh dist # check + test + wszystkie .deb + docker
```
Opcje uruchomienia (także jako zmienne środowiskowe): `--data-dir` (`SIMPLY_DVB_DATA_DIR`),
`--dev-root` (`SIMPLY_DVB_DEV_ROOT`), `--virtual-dir` (`SIMPLY_DVB_VIRTUAL_DIR`, katalog z plikami
`<MHz>.ts`), `serve --listen` (`SIMPLY_DVB_LISTEN`, panel, domyślnie 9980), `serve --stream-listen`
(`SIMPLY_DVB_STREAM_LISTEN`, port strumieni, domyślnie 9981, `off` wyłącza). Użytkownicy z linii poleceń:
`simply-dvb user add <login> --role admin|viewer`, `simply-dvb user passwd <login>`.
Tłumaczenia: silnik w `web/js/10-i18n.js`, pakiety w `langs/*.json`. Nowy tekst w interfejsie (po angielsku)
wymaga wpisu w `langs/en_US.json` i tłumaczeń w pozostałych plikach (lub wzorca w `patterns` dla tekstów z wartościami).
Odtwarzacz korzysta z [hls.js](https://github.com/video-dev/hls.js) (Apache-2.0, `web/vendor/`).
+176
View File
@@ -0,0 +1,176 @@
//! Panel asset build (like RustProxy): all CSS from `web/css` and JS from `web/js`
//! (preceded by hls.js and the `langs/*.json` language packs) are concatenated into single,
//! uniquely named `app.<hash>.css` / `app.<hash>.js` files embedded in the binary and served
//! with a long-lived cache.
use sha2::{Digest, Sha256};
use std::fs;
use std::path::{Path, PathBuf};
fn sorted_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
let mut v: Vec<PathBuf> = fs::read_dir(dir)
.unwrap_or_else(|e| panic!("{}: {e}", dir.display()))
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().and_then(|x| x.to_str()) == Some(ext))
.collect();
v.sort();
v
}
/// Light CSS minification: strips comments and redundant whitespace (UTF-8 safe).
fn minify_css(src: &str) -> String {
let chars: Vec<char> = src.chars().collect();
let mut out = String::with_capacity(src.len());
let mut i = 0;
let mut pending_space = false;
let mut in_str: Option<char> = None;
while i < chars.len() {
let c = chars[i];
if let Some(q) = in_str {
out.push(c);
if c == q {
in_str = None;
}
i += 1;
continue;
}
if c == '/' && chars.get(i + 1) == Some(&'*') {
i += 2;
while i + 1 < chars.len() && !(chars[i] == '*' && chars[i + 1] == '/') {
i += 1;
}
i += 2;
continue;
}
if c.is_whitespace() {
pending_space = true;
i += 1;
continue;
}
let tight = |x: char| matches!(x, '{' | '}' | ';' | ',' | '>');
if pending_space && !out.is_empty() && !tight(c) && !out.ends_with(tight) {
out.push(' ');
}
pending_space = false;
if c == '"' || c == '\'' {
in_str = Some(c);
}
out.push(c);
i += 1;
}
out
}
/// Loads and validates `langs/*.json` and returns them as a minified JSON array.
///
/// Each pack: `{"meta": {"locale", "name", "native_name", "direction"},
/// "translations": {english: translated}, "patterns": [{"match", "replace"}]}`.
/// The file name must equal `meta.locale` (e.g. `pl_PL.json`) and `en_US.json` is required,
/// because English is both the source text and the fallback.
fn language_packs(dir: &Path) -> String {
println!("cargo:rerun-if-changed=langs");
let mut packs = Vec::new();
let mut have_en = false;
for f in sorted_files(dir, "json") {
let name = f.file_stem().unwrap().to_string_lossy().to_string();
let src = fs::read_to_string(&f).unwrap();
let v: serde_json::Value = serde_json::from_str(&src)
.unwrap_or_else(|e| panic!("{}: invalid JSON: {e}", f.display()));
let locale = v["meta"]["locale"]
.as_str()
.unwrap_or_else(|| panic!("{}: meta.locale is missing", f.display()));
assert_eq!(
locale,
name,
"{}: meta.locale must match the file name",
f.display()
);
assert!(
v["meta"]["name"].is_string(),
"{}: meta.name is missing",
f.display()
);
let tr = v["translations"]
.as_object()
.unwrap_or_else(|| panic!("{}: translations must be an object", f.display()));
for (k, val) in tr {
assert!(
val.is_string(),
"{}: translation of {k:?} must be a string",
f.display()
);
}
if let Some(p) = v.get("patterns") {
for x in p
.as_array()
.unwrap_or_else(|| panic!("{}: patterns must be an array", f.display()))
{
assert!(
x["match"].is_string() && x["replace"].is_string(),
"{}: every pattern needs string \"match\" and \"replace\"",
f.display()
);
}
}
have_en |= name == "en_US";
packs.push(v);
}
assert!(have_en, "langs/en_US.json is required (default language)");
serde_json::to_string(&packs).unwrap()
}
fn hash8(data: &[u8]) -> String {
let d = Sha256::digest(data);
d.iter()
.take(5)
.map(|b| format!("{b:02x}"))
.collect::<String>()[..10]
.to_string()
}
fn main() {
let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let web = root.join("web");
println!("cargo:rerun-if-changed=web");
println!("cargo:rerun-if-changed=migrations");
let mut css = String::new();
for f in sorted_files(&web.join("css"), "css") {
let s = fs::read_to_string(&f).unwrap();
css.push_str(&format!(
"/* {} */\n",
f.file_name().unwrap().to_string_lossy()
));
css.push_str(&s);
css.push('\n');
}
let css = minify_css(&css);
let mut js = String::new();
js.push_str(&fs::read_to_string(web.join("vendor/hls.min.js")).unwrap());
js.push_str("\n;\n");
js.push_str("window.SDVB_LANGS = ");
js.push_str(&language_packs(&root.join("langs")));
js.push_str(";\n");
for f in sorted_files(&web.join("js"), "js") {
js.push_str(&format!(
"/* ---- {} ---- */\n",
f.file_name().unwrap().to_string_lossy()
));
js.push_str(&fs::read_to_string(&f).unwrap());
js.push_str("\n;\n");
}
let out = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let css_name = format!("app.{}.css", hash8(css.as_bytes()));
let js_name = format!("app.{}.js", hash8(js.as_bytes()));
fs::write(out.join("app.css"), &css).unwrap();
fs::write(out.join("app.js"), &js).unwrap();
fs::write(
out.join("asset_names.rs"),
format!(
"pub const CSS_NAME: &str = {css_name:?};\npub const JS_NAME: &str = {js_name:?};\n"
),
)
.unwrap();
}
+31
View File
@@ -0,0 +1,31 @@
services:
simply-dvb:
build: .
image: simply-dvb:latest
container_name: simply-dvb
restart: unless-stopped
# Host networking makes the server easy to reach for TVs on the LAN and keeps real client addresses (ACL).
# Alternatively remove network_mode and uncomment "ports".
network_mode: host
# ports:
# - "9980:9980" # panel
# - "9981:9981" # streams (tvheadend-compatible)
# - "9982:9982" # HTSP
devices:
- /dev/dvb:/dev/dvb
# - /dev/dri:/dev/dri # ffmpeg hardware acceleration (VAAPI)
group_add:
# GID of the "video" group on the host (check: getent group video)
- "${VIDEO_GID:-44}"
environment:
TZ: ${TZ:-Etc/UTC}
RUST_LOG: simply_dvb=info,warn
SIMPLY_DVB_LISTEN: 0.0.0.0:9980
SIMPLY_DVB_STREAM_LISTEN: 0.0.0.0:9981
SIMPLY_DVB_HTSP_LISTEN: 0.0.0.0:9982
volumes:
- simply-dvb-data:/var/lib/simply-dvb
# - /srv/recordings:/recordings # set the recordings directory in the panel to /recordings
volumes:
simply-dvb-data:
Executable
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Helper script: ./dev.sh <command>
set -euo pipefail
cd "$(dirname "$0")"
VERSION=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)
case "${1:-help}" in
check)
cargo fmt --check
cargo clippy --all-targets -- -D warnings
for f in web/js/*.js scripts/*.js; do node --check "$f"; done
python3 -m py_compile scripts/*.py
for f in langs/*.json; do node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$f"; done
;;
test)
cargo test --all-targets
;;
run)
# Panel at http://127.0.0.1:9980, streams at :9981, data in ./data
mkdir -p data
cargo run -- --data-dir ./data serve --listen 127.0.0.1:9980 --stream-listen 127.0.0.1:9981
;;
demo)
# Without a DVB card: generates sample multiplexes and runs the virtual adapter
mkdir -p data/demo
cargo run --release -- gen-demo --out data/demo
cargo run --release -- --data-dir ./data --virtual-dir ./data/demo serve --listen 127.0.0.1:9980 --stream-listen 127.0.0.1:9981
;;
release)
cargo build --release --locked
ls -la target/release/simply-dvb
;;
deb)
# package for the host architecture
case "$(uname -m)" in x86_64) a=amd64 ;; aarch64) a=arm64 ;; *) a=armhf ;; esac
scripts/build-deb.sh "$a"
;;
deb-amd64|deb-arm64|deb-armhf)
scripts/build-deb.sh "${1#deb-}"
;;
deb-all)
scripts/build-deb-all.sh
;;
docker)
docker build -t "simply-dvb:${VERSION}" -t simply-dvb:latest .
;;
dist)
"$0" check && "$0" test && "$0" deb-all && "$0" docker
;;
*)
echo "Usage: $0 {check|test|run|demo|release|deb|deb-amd64|deb-arm64|deb-armhf|deb-all|docker|dist}"
;;
esac
Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

+629
View File
@@ -0,0 +1,629 @@
{
"meta": {
"locale": "en_US",
"name": "English",
"native_name": "English",
"direction": "ltr"
},
"translations": {
"(change it in Settings). Add": "(change it in Settings). Add",
") and membership in group": ") and membership in group",
"+ Add from services": "+ Add from services",
"+ Add manually": "+ Add manually",
"+ New recording": "+ New recording",
"+ New rule": "+ New rule",
"+ New token": "+ New token",
"+ New user": "+ New user",
", and for transcoding": ", and for transcoding",
", the driver and firmware (for Si2168:": ", the driver and firmware (for Si2168:",
".": ".",
"0 = never": "0 = never",
"0 = only while watching": "0 = only while watching",
"A rule schedules recordings of every EPG programme (next 48 h) whose title matches the pattern – a title fragment or a regular expression.": "A rule schedules recordings of every EPG programme (next 48 h) whose title matches the pattern – a title fragment or a regular expression.",
"a scan is already running": "a scan is already running",
"A token allows playing streams from outside the local network (e.g. a TV at your family’s place). It can be limited to selected addresses/networks.": "A token allows playing streams from outside the local network (e.g. a TV at your family’s place). It can be limited to selected addresses/networks.",
"Accent colour": "Accent colour",
"Access": "Access",
"Access & sharing": "Access & sharing",
"Access control (ACL)": "Access control (ACL)",
"Access tokens": "Access tokens",
"Access: logins, tokens, allowed and denied requests": "Access: logins, tokens, allowed and denied requests",
"ACL saved": "ACL saved",
"active": "active",
"Active": "Active",
"Active clients": "Active clients",
"active tuners": "active tuners",
"active:": "active:",
"Adapter": "Adapter",
"Adapters": "Adapters",
"Add": "Add",
"Add channels from services": "Add channels from services",
"Add radio stations": "Add radio stations",
"Add scrambled channels": "Add scrambled channels",
"Add selected": "Add selected",
"Added – use “Rescan: saved muxes” to read its services": "Added – use “Rescan: saved muxes” to read its services",
"Address": "Address",
"administrator": "administrator",
"Administrators only.": "Administrators only.",
"Age": "Age",
"all": "all",
"All": "All",
"All groups": "All groups",
"All levels": "All levels",
"All services already have channels.": "All services already have channels.",
"All types": "All types",
"Allowed networks (optional)": "Allowed networks (optional)",
"Always expanded": "Always expanded",
"Amber": "Amber",
"Animations": "Animations",
"Appearance": "Appearance",
"Application": "Application",
"Application: start-up, settings, panel, API": "Application: start-up, settings, panel, API",
"Arts & culture": "Arts & culture",
"Arts / Culture": "Arts / Culture",
"Assign numbers 1..n in the current order?": "Assign numbers 1..n in the current order?",
"Audio → AAC": "Audio → AAC",
"Australia – VHF 6–12 + UHF 28–51 (7 MHz)": "Australia – VHF 6–12 + UHF 28–51 (7 MHz)",
"automatic": "automatic",
"Automatic": "Automatic",
"available": "available",
"background": "background",
"Background scan every (h)": "Background scan every (h)",
"Background scan of saved muxes when tuners are idle: every": "Background scan of saved muxes when tuners are idle: every",
"background scan stopped – the adapter is needed": "background scan stopped – the adapter is needed",
"Background scan: create channels for new services": "Background scan: create channels for new services",
"Background scan: follow the NIT to new muxes": "Background scan: follow the NIT to new muxes",
"Background scanning is off (Settings → Scanning).": "Background scanning is off (Settings → Scanning).",
"Backup": "Backup",
"Backup restored": "Backup restored",
"Bandwidth": "Bandwidth",
"Bandwidth (MHz)": "Bandwidth (MHz)",
"bandwidth: 5, 6, 7 or 8 MHz": "bandwidth: 5, 6, 7 or 8 MHz",
"Below this threshold the oldest recordings are deleted; 0 = disabled": "Below this threshold the oldest recordings are deleted; 0 = disabled",
"bitrate": "bitrate",
"Blue": "Blue",
"Browser": "Browser",
"Buffering…": "Buffering…",
"Cable DVB-C – 114–858 MHz": "Cable DVB-C – 114–858 MHz",
"Cancel": "Cancel",
"cancelled": "cancelled",
"cancelled by user": "cancelled by user",
"Change": "Change",
"Change my password": "Change my password",
"Change password": "Change password",
"Changes apply immediately (to new stream sessions).": "Changes apply immediately (to new stream sessions).",
"Channel": "Channel",
"channel does not exist": "channel does not exist",
"channel has no service assigned": "channel has no service assigned",
"Channel icons": "Channel icons",
"Channel list": "Channel list",
"channel name must be 1–120 characters": "channel name must be 1–120 characters",
"channel number must be 0–99999": "channel number must be 0–99999",
"channel service does not exist": "channel service does not exist",
"Channels": "Channels",
"Channels are matched by the channel’s “EPG ID” or by name. A line starting with # is disabled. XMLTV data takes precedence over EIT.": "Channels are matched by the channel’s “EPG ID” or by name. A line starting with # is disabled. XMLTV data takes precedence over EIT.",
"Children": "Children",
"Children's / Youth": "Children's / Youth",
"choose a channel": "choose a channel",
"Clear view": "Clear view",
"Click ▶ to play": "Click ▶ to play",
"Client": "Client",
"Clients": "Clients",
"clients": "clients",
"Clients & sessions": "Clients & sessions",
"Close": "Close",
"Close idle HLS session after (s)": "Close idle HLS session after (s)",
"Codecs": "Codecs",
"Collect EPG from the broadcast (EIT)": "Collect EPG from the broadcast (EIT)",
"Collecting data…": "Collecting data…",
"Comfortable": "Comfortable",
"Compact": "Compact",
"completed": "completed",
"Configuration": "Configuration",
"conflict": "conflict",
"Conflict: not enough tuners": "Conflict: not enough tuners",
"conflicts:": "conflicts:",
"Connected to server": "Connected to server",
"CONTROL ROOM": "CONTROL ROOM",
"Copied to clipboard": "Copied to clipboard",
"Copy": "Copy",
"Copy failed": "Copy failed",
"Copy link": "Copy link",
"Copy token": "Copy token",
"Could not play the stream": "Could not play the stream",
"CPU": "CPU",
"Create": "Create",
"Create channels automatically": "Create channels automatically",
"Created": "Created",
"Current password": "Current password",
"current password is incorrect": "current password is incorrect",
"Custom frequency list": "Custom frequency list",
"Cut on keyframes – actual length depends on the broadcaster’s GOP": "Cut on keyframes – actual length depends on the broadcaster’s GOP",
"Dark": "Dark",
"database migrations": "database migrations",
"decompressing gzip": "decompressing gzip",
"Default M3U format": "Default M3U format",
"Default M3U format:": "Default M3U format:",
"Default player profile": "Default player profile",
"Delete": "Delete",
"Delete channel": "Delete channel",
"Delete recordings older than (days)": "Delete recordings older than (days)",
"Delete shown": "Delete shown",
"Delete the mux with its services? Channels will lose their source.": "Delete the mux with its services? Channels will lose their source.",
"Delete the recording together with its file?": "Delete the recording together with its file?",
"Delete the rule? Recordings scheduled by it will be cancelled.": "Delete the rule? Recordings scheduled by it will be cancelled.",
"Delete the token? Devices using it will lose access.": "Delete the token? Devices using it will lose access.",
"Delete the user?": "Delete the user?",
"Density": "Density",
"Detect adapters": "Detect adapters",
"Device": "Device",
"Diagnostics": "Diagnostics",
"Disable shown": "Disable shown",
"disabled": "disabled",
"Disabled only": "Disabled only",
"Download": "Download",
"downloading XMLTV": "downloading XMLTV",
"Drag rows to reorder. Numbers can also be typed in.": "Drag rows to reorder. Numbers can also be typed in.",
"Duration": "Duration",
"DVB-T/T2/C cards (e.g. Si2168), frequency scanning and saved muxes.": "DVB-T/T2/C cards (e.g. Si2168), frequency scanning and saved muxes.",
"e.g. https://tv.example.com – empty = from the Host header": "e.g. https://tv.example.com – empty = from the Host header",
"e.g. Living room Sony TV": "e.g. Living room Sony TV",
"e.g. Teleexpress or ^News$": "e.g. Teleexpress or ^News$",
"Each bar is one recording (padding included); colours mark the multiplex – recordings on the same multiplex share one tuner.": "Each bar is one recording (padding included); colours mark the multiplex – recordings on the same multiplex share one tuner.",
"Edit": "Edit",
"Edit rule": "Edit rule",
"Education": "Education",
"Education / Science / Factual topics": "Education / Science / Factual topics",
"EIT (broadcast)": "EIT (broadcast)",
"Electronic programme guide": "Electronic programme guide",
"empty = automatic match by name": "empty = automatic match by name",
"empty frequency list": "empty frequency list",
"Enable shown": "Enable shown",
"Enabled": "Enabled",
"Enabled and disabled": "Enabled and disabled",
"Enabled only": "Enabled only",
"End": "End",
"end must be after start": "end must be after start",
"enter a title pattern (1–200 characters)": "enter a title pattern (1–200 characters)",
"enter a token name (e.g. Living room TV)": "enter a token name (e.g. Living room TV)",
"Entertainment": "Entertainment",
"entries": "entries",
"EPG": "EPG",
"EPG from the broadcast (EIT) and external XMLTV sources.": "EPG from the broadcast (EIT) and external XMLTV sources.",
"EPG grabbing will start when tuners are free": "EPG grabbing will start when tuners are free",
"EPG grid": "EPG grid",
"EPG grid zoom": "EPG grid zoom",
"EPG ID (XMLTV)": "EPG ID (XMLTV)",
"EPG – upcoming programmes": "EPG – upcoming programmes",
"EPG: over-the-air grabbing, XMLTV imports": "EPG: over-the-air grabbing, XMLTV imports",
"error": "error",
"Errors (UNC)": "Errors (UNC)",
"errors only": "errors only",
"Europe – UHF 21–48 (474–690 MHz, after 700 MHz refarming: PL, DE, FR, UK, CZ…)": "Europe – UHF 21–48 (474–690 MHz, after 700 MHz refarming: PL, DE, FR, UK, CZ…)",
"Europe – UHF 21–48 (474–690 MHz, after the 700 MHz refarming: PL, DE, FR, UK, CZ…)": "Europe – UHF 21–48 (474–690 MHz, after the 700 MHz refarming: PL, DE, FR, UK, CZ…)",
"Europe – UHF 21–69 (474–858 MHz)": "Europe – UHF 21–69 (474–858 MHz)",
"Europe – VHF III (7 MHz) + UHF 21–69": "Europe – VHF III (7 MHz) + UHF 21–69",
"Expand on hover": "Expand on hover",
"Failed / cancelled": "Failed / cancelled",
"Faster zapping between channels of the same mux": "Faster zapping between channels of the same mux",
"ffmpeg path": "ffmpeg path",
"Find automatically": "Find automatically",
"Find further muxes via NIT": "Find further muxes via NIT",
"Find icons": "Find icons",
"Finding icons…": "Finding icons…",
"Finished": "Finished",
"Follow": "Follow",
"Follow further muxes from the NIT": "Follow further muxes from the NIT",
"For apps that speak tvheadend’s HTSP protocol (Kodi “Tvheadend HTSP Client”, TVHClient, PVR apps on Android/Sony TV): server = this address, HTSP port as above, HTTP port = the stream port. On the local network no login is needed; from elsewhere use any user name and an access token as the password.": "For apps that speak tvheadend’s HTSP protocol (Kodi “Tvheadend HTSP Client”, TVHClient, PVR apps on Android/Sony TV): server = this address, HTSP port as above, HTTP port = the stream port. On the local network no login is needed; from elsewhere use any user name and an access token as the password.",
"Frequencies (MHz, comma separated)": "Frequencies (MHz, comma separated)",
"Frequency": "Frequency",
"Frequency (MHz)": "Frequency (MHz)",
"Frequency list": "Frequency list",
"frequency out of range 40–900 MHz": "frequency out of range 40–900 MHz",
"Friday": "Friday",
"From a rule": "From a rule",
"frontend is busy or permission denied (video group?)": "frontend is busy or permission denied (video group?)",
"Full transcoding to H.264 720p + AAC": "Full transcoding to H.264 720p + AAC",
"Fullscreen": "Fullscreen",
"General": "General",
"Genre": "Genre",
"Grab all muxes every (h)": "Grab all muxes every (h)",
"Grab EPG now": "Grab EPG now",
"Grab time per mux (s)": "Grab time per mux (s)",
"Green": "Green",
"Group": "Group",
"H.264 profile arguments": "H.264 profile arguments",
"Hardware & muxes": "Hardware & muxes",
"Hide broken": "Hide broken",
"Hide scrambled": "Hide scrambled",
"HLS (m3u8)": "HLS (m3u8)",
"HLS segment length (s)": "HLS segment length (s)",
"HLS segment length must be 1–10 s": "HLS segment length must be 1–10 s",
"HLS sessions": "HLS sessions",
"HLS window must be 3–60 segments": "HLS window must be 3–60 segments",
"https://… or upload a file below": "https://… or upload a file below",
"icon file is too large (max. 2 MiB)": "icon file is too large (max. 2 MiB)",
"Icon found": "Icon found",
"Icon URL": "Icon URL",
"Icon URL templates": "Icon URL templates",
"icon: http(s) URL or empty": "icon: http(s) URL or empty",
"idle": "idle",
"Import XMLTV every (h)": "Import XMLTV every (h)",
"Import XMLTV now": "Import XMLTV now",
"Imported": "Imported",
"in": "in",
"Information": "Information",
"Install ffmpeg on the server to enable transcoding, or open the channel in VLC.": "Install ffmpeg on the server to enable transcoding, or open the channel in VLC.",
"Interface preferences are stored in this browser.": "Interface preferences are stored in this browser.",
"Interface preferences reset": "Interface preferences reset",
"Interface scale": "Interface scale",
"invalid recording time (max. 12 h)": "invalid recording time (max. 12 h)",
"invalid username": "invalid username",
"invalid username or password": "invalid username or password",
"is still taken (tvheadend?). The links below use the panel port; simply-dvb takes the stream port over automatically once it is free.": "is still taken (tvheadend?). The links below use the panel port; simply-dvb takes the stream port over automatically once it is free.",
"Italy – VHF D–H2 + UHF 21–48": "Italy – VHF D–H2 + UHF 21–48",
"Keep past programmes (h)": "Keep past programmes (h)",
"Keep tuner after last client (s)": "Keep tuner after last client (s)",
"Keyboard shortcuts": "Keyboard shortcuts",
"Language": "Language",
"Last scan": "Last scan",
"Last used": "Last used",
"Last XMLTV import:": "Last XMLTV import:",
"last:": "last:",
"Leisure": "Leisure",
"Leisure hobbies": "Leisure hobbies",
"Light": "Light",
"Light / dark theme": "Light / dark theme",
"Link inactive": "Link inactive",
"LIVE": "LIVE",
"Live": "Live",
"Live broadcast": "Live broadcast",
"load": "load",
"Load average (1 min)": "Load average (1 min)",
"Loading recording…": "Loading recording…",
"local network": "local network",
"Local network (no token)": "Local network (no token)",
"Lock timeout (ms)": "Lock timeout (ms)",
"Login": "Login",
"login required": "login required",
"Logos in the channel list": "Logos in the channel list",
"Logs": "Logs",
"M3U format: hls or ts": "M3U format: hls or ts",
"Manual recording": "Manual recording",
"Matching programmes (48 h)": "Matching programmes (48 h)",
"max": "max",
"Memory": "Memory",
"Midnight (OLED)": "Midnight (OLED)",
"Minimum free space (GiB)": "Minimum free space (GiB)",
"missing X-Requested-With header": "missing X-Requested-With header",
"Modulation": "Modulation",
"Modulation (DVB-C)": "Modulation (DVB-C)",
"Monday": "Monday",
"Movie": "Movie",
"Movie / Drama": "Movie / Drama",
"Movies": "Movies",
"MPEG-TS (continuous stream)": "MPEG-TS (continuous stream)",
"Multiplex bitrate": "Multiplex bitrate",
"Music": "Music",
"Music / Ballet / Dance": "Music / Ballet / Dance",
"Mute": "Mute",
"Mux": "Mux",
"mux does not exist": "mux does not exist",
"mux is disabled": "mux is disabled",
"Mux services": "Mux services",
"Muxes": "Muxes",
"Muxes found:": "Muxes found:",
"Muxes, services, channels (order, groups, links), recording rules, tokens and settings. Without user accounts, EPG, icons and recording files.": "Muxes, services, channels (order, groups, links), recording rules, tokens and settings. Without user accounts, EPG, icons and recording files.",
"Name": "Name",
"Narrow": "Narrow",
"needs ffmpeg": "needs ffmpeg",
"Network": "Network",
"Networks": "Networks",
"Networks allowed to reach the panel": "Networks allowed to reach the panel",
"Networks with token-free access to streams, M3U and EPG": "Networks with token-free access to streams, M3U and EPG",
"New mux": "New mux",
"New password": "New password",
"New password (min. 8 characters):": "New password (min. 8 characters):",
"New recording": "New recording",
"New rule": "New rule",
"New token": "New token",
"New user": "New user",
"New Zealand – UHF 25–48": "New Zealand – UHF 25–48",
"News": "News",
"News / Current affairs": "News / Current affairs",
"Next:": "Next:",
"no adapter available": "no adapter available",
"No channels match the filters.": "No channels match the filters.",
"No channels – run a scan on the Tuners page.": "No channels – run a scan on the Tuners page.",
"No channels.": "No channels.",
"No channels. Run a scan on the": "No channels. Run a scan on the",
"no data": "no data",
"no data from the stream (timed out)": "no data from the stream (timed out)",
"no data from the tuner for 15 s": "no data from the tuner for 15 s",
"no DVB adapters configured": "no DVB adapters configured",
"No DVB adapters detected. Check /dev/dvb and permissions (group": "No DVB adapters detected. Check /dev/dvb and permissions (group",
"No DVB cards detected. Check": "No DVB cards detected. Check",
"no enabled XMLTV sources in settings": "no enabled XMLTV sources in settings",
"No entries match.": "No entries match.",
"No EPG data for this moment.": "No EPG data for this moment.",
"No EPG yet. Data appears after EIT is collected from the mux or XMLTV is imported.": "No EPG yet. Data appears after EIT is collected from the mux or XMLTV is imported.",
"No matching programmes in the EPG.": "No matching programmes in the EPG.",
"No muxes – run a scan.": "No muxes – run a scan.",
"No recordings in this category.": "No recordings in this category.",
"No rules. Add e.g. “Teleexpress” or “^News$”.": "No rules. Add e.g. “Teleexpress” or “^News$”.",
"no service": "no service",
"no signal": "no signal",
"No tokens.": "No tokens.",
"No.": "No.",
"Nobody is watching right now.": "Nobody is watching right now.",
"Normal": "Normal",
"not installed": "not installed",
"not started before the programme ended": "not started before the programme ended",
"Not supported by this browser": "Not supported by this browser",
"Nothing scheduled. Pick a programme in the TV guide or add a rule.": "Nothing scheduled. Pick a programme in the TV guide or add a rule.",
"Now": "Now",
"Number": "Number",
"Off = new services only appear in “Add from services”": "Off = new services only appear in “Add from services”",
"only scheduled or running recordings can be changed": "only scheduled or running recordings can be changed",
"Only without EPG now": "Only without EPG now",
"Only without icon": "Only without icon",
"opening the SQLite database": "opening the SQLite database",
"or": "or",
"Orange": "Orange",
"Order saved": "Order saved",
"Original": "Original",
"Original (no transcoding)": "Original (no transcoding)",
"Other / data": "Other / data",
"out": "out",
"Overview": "Overview",
"Padding after (min)": "Padding after (min)",
"Padding before (min)": "Padding before (min)",
"page.": "page.",
"panel not available from this network": "panel not available from this network",
"Panel session lifetime (h)": "Panel session lifetime (h)",
"Panel users": "Panel users",
"Password": "Password",
"Password changed": "Password changed",
"Password changed – please sign in again": "Password changed – please sign in again",
"password must be at least 8 characters": "password must be at least 8 characters",
"Pattern": "Pattern",
"Pause / resume": "Pause / resume",
"per 2 s": "per 2 s",
"permission denied": "permission denied",
"Personalization": "Personalization",
"Pick a channel from the list": "Pick a channel from the list",
"Picture-in-picture": "Picture-in-picture",
"Picture-in-picture (P)": "Picture-in-picture (P)",
"playback error": "playback error",
"Playlists & EPG": "Playlists & EPG",
"Playlists for TVs, tokens, access control (ACL) and panel accounts.": "Playlists for TVs, tokens, access control (ACL) and panel accounts.",
"PLP (DVB-T2, optional)": "PLP (DVB-T2, optional)",
"Poland – UHF 21–48 (474–690 MHz)": "Poland – UHF 21–48 (474–690 MHz)",
"port taken (tvheadend?)": "port taken (tvheadend?)",
"Previous / next channel": "Previous / next channel",
"Process memory (RSS)": "Process memory (RSS)",
"Profile": "Profile",
"programme does not exist": "programme does not exist",
"Programme progress in the channel list": "Programme progress in the channel list",
"programmes in database:": "programmes in database:",
"Prometheus metrics": "Prometheus metrics",
"Protocol": "Protocol",
"Provider": "Provider",
"public link": "public link",
"Public link": "Public link",
"Public link enabled and copied": "Public link enabled and copied",
"Public URL (for links)": "Public URL (for links)",
"public URL must start with http:// or https://": "public URL must start with http:// or https://",
"radio": "radio",
"Radio": "Radio",
"Rate": "Rate",
"Record": "Record",
"recording": "recording",
"Recording": "Recording",
"RECORDING": "RECORDING",
"recording does not exist": "recording does not exist",
"recording index missing": "recording index missing",
"Recording scheduled": "Recording scheduled",
"Recording: schedule, running recordings, cleanup": "Recording: schedule, running recordings, cleanup",
"Recordings": "Recordings",
"recordings": "recordings",
"Recordings directory": "Recordings directory",
"Recordings disk": "Recordings disk",
"recordings scheduled:": "recordings scheduled:",
"Red": "Red",
"Remove icon": "Remove icon",
"Renumber 1..n": "Renumber 1..n",
"Rescan: saved muxes": "Rescan: saved muxes",
"Rescans saved muxes (and the NIT) on an idle adapter; stops as soon as someone starts watching or recording. 0 = off": "Rescans saved muxes (and the NIT) on an idle adapter; stops as soon as someone starts watching or recording. 0 = off",
"Reset to defaults": "Reset to defaults",
"Restore configuration from the backup? Current channels, muxes, rules and tokens will be replaced.": "Restore configuration from the backup? Current channels, muxes, rules and tokens will be replaced.",
"Role": "Role",
"Role changed": "Role changed",
"role: admin or viewer": "role: admin or viewer",
"RSS": "RSS",
"Rule saved": "Rule saved",
"Rules (series)": "Rules (series)",
"running": "running",
"Saturday": "Saturday",
"Save": "Save",
"Save ACL": "Save ACL",
"Save settings": "Save settings",
"Saved": "Saved",
"Scan channels": "Scan channels",
"Scan started": "Scan started",
"scanning": "scanning",
"Scanning": "Scanning",
"Schedule": "Schedule",
"Schedule from the EPG or manually. Play finished recordings in the browser or download them as .ts.": "Schedule from the EPG or manually. Play finished recordings in the browser or download them as .ts.",
"Schedule recording": "Schedule recording",
"scheduled": "scheduled",
"Scheduled": "Scheduled",
"Scheduled & running": "Scheduled & running",
"scrambled": "scrambled",
"Search channel…": "Search channel…",
"Searching for channel icons…": "Searching for channel icons…",
"Search…": "Search…",
"Security": "Security",
"segment unavailable": "segment unavailable",
"Segments in playlist": "Segments in playlist",
"Select channel by number": "Select channel by number",
"Sent": "Sent",
"Server connection": "Server connection",
"Server name": "Server name",
"Service (source)": "Service (source)",
"service does not exist": "service does not exist",
"Services": "Services",
"Services without a channel:": "Services without a channel:",
"session ended": "session ended",
"Session expired – please sign in again": "Session expired – please sign in again",
"session expired – reload the playlist": "session expired – reload the playlist",
"set the end time": "set the end time",
"Settings": "Settings",
"Settings saved": "Settings saved",
"Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.": "Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.",
"Show / Game show": "Show / Game show",
"Show clock in the top bar": "Show clock in the top bar",
"Si2168 usually locks DVB-T2 within ~1–2 s": "Si2168 usually locks DVB-T2 within ~1–2 s",
"Sidebar": "Sidebar",
"Sign in": "Sign in",
"Sign out": "Sign out",
"Signal level": "Signal level",
"Signal strength": "Signal strength",
"signal, no lock": "signal, no lock",
"simply-dvb · panel": "simply-dvb · panel",
"Since": "Since",
"Size": "Size",
"Social": "Social",
"Social / Political issues / Economics": "Social / Political issues / Economics",
"Source": "Source",
"Space": "Space",
"Special": "Special",
"Special characteristics": "Special characteristics",
"Sport": "Sport",
"Start": "Start",
"Start after all tuners are idle for (min)": "Start after all tuners are idle for (min)",
"Start page": "Start page",
"Start scan": "Start scan",
"Starts": "Starts",
"Status": "Status",
"Stop": "Stop",
"Stream": "Stream",
"stream ended": "stream ended",
"stream interrupted": "stream interrupted",
"Stream port": "Stream port",
"Stream port: /playlist, /playlist.m3u, /xmltv, /epg.xml, /stream/channelid/<id>, /hls/<id>/index.m3u8": "Stream port: /playlist, /playlist.m3u, /xmltv, /epg.xml, /stream/channelid/<id>, /hls/<id>/index.m3u8",
"Streaming": "Streaming",
"Streaming (HLS / TS)": "Streaming (HLS / TS)",
"Streaming throughput": "Streaming throughput",
"Streaming: HLS, MPEG-TS, HTSP, transcoding, clients": "Streaming: HLS, MPEG-TS, HTSP, transcoding, clients",
"Streams": "Streams",
"Strength": "Strength",
"Sunday": "Sunday",
"Supported by this browser": "Supported by this browser",
"Symbol rate (kS/s)": "Symbol rate (kS/s)",
"Symbol rate (kS/s, DVB-C)": "Symbol rate (kS/s, DVB-C)",
"System": "System",
"system": "system",
"System default": "System default",
"system: dvbt or dvbt2": "system: dvbt or dvbt2",
"system: dvbt, dvbt2 or dvbc": "system: dvbt, dvbt2 or dvbc",
"System: HTTP server, libraries": "System: HTTP server, libraries",
"Teal": "Teal",
"Television, in focus.": "Television, in focus.",
"Temperature": "Temperature",
"the programme has already ended": "the programme has already ended",
"the recording’s channel was deleted": "the recording’s channel was deleted",
"the stream": "the stream",
"The “Automatic” profile checks which codecs your browser supports (e.g. HEVC, AC-3) and enables ffmpeg transcoding when needed.": "The “Automatic” profile checks which codecs your browser supports (e.g. HEVC, AC-3) and enables ffmpeg transcoding when needed.",
"Theme": "Theme",
"This browser does not support HLS": "This browser does not support HLS",
"This browser reports no HEVC (H.265) support. Chrome/Edge decode it only with hardware acceleration (on Linux: VA-API); Safari plays it natively.": "This browser reports no HEVC (H.265) support. Chrome/Edge decode it only with hardware acceleration (on Linux: VA-API); Safari plays it natively.",
"This help": "This help",
"this is not a simply-dvb backup": "this is not a simply-dvb backup",
"This stream link has expired or was disabled.": "This stream link has expired or was disabled.",
"Thursday": "Thursday",
"Time": "Time",
"Title": "Title",
"Title pattern": "Title pattern",
"to clients": "to clients",
"too many failed attempts, try again in a few minutes": "too many failed attempts, try again in a few minutes",
"Transcoding (ffmpeg)": "Transcoding (ffmpeg)",
"Trusted reverse proxies": "Trusted reverse proxies",
"TS – lightest for TVs, HLS – for apps that require HLS": "TS – lightest for TVs, HLS – for apps that require HLS",
"Tuesday": "Tuesday",
"Tuner is waiting for clients.": "Tuner is waiting for clients.",
"Tuners": "Tuners",
"Tuners & devices": "Tuners & devices",
"Tuners & scanning": "Tuners & scanning",
"Tuners and devices: adapters, tuning, lock, scanning": "Tuners and devices: adapters, tuning, lock, scanning",
"Tuners, streams, clients and EPG in one place.": "Tuners, streams, clients and EPG in one place.",
"Tuners:": "Tuners:",
"Tuning and buffering…": "Tuning and buffering…",
"tuning timed out": "tuning timed out",
"tv": "tv",
"TV": "TV",
"TV guide": "TV guide",
"TVH = tvheadend-compatible URLs (stream port, 9981 by default): /playlist, /xmltv/channels, /stream/channelid/<id>, /imagecache/<id>, auth= / ticket= parameters and HTTP Basic login. An app configured for tvheadend works after changing just the server address.": "TVH = tvheadend-compatible URLs (stream port, 9981 by default): /playlist, /xmltv/channels, /stream/channelid/<id>, /imagecache/<id>, auth= / ticket= parameters and HTTP Basic login. An app configured for tvheadend works after changing just the server address.",
"Type": "Type",
"UHF channel": "UHF channel",
"Uncorrected blocks": "Uncorrected blocks",
"unknown": "unknown",
"unknown profile": "unknown profile",
"unsupported image format (PNG, JPEG, GIF, WebP, SVG)": "unsupported image format (PNG, JPEG, GIF, WebP, SVG)",
"Updated channels:": "Updated channels:",
"used": "used",
"Used by the “h264” profile (e.g. HEVC in browsers without a hardware decoder). Hardware acceleration can be added: -c:v h264_vaapi etc.": "Used by the “h264” profile (e.g. HEVC in browsers without a hardware decoder). Hardware acceleration can be added: -c:v h264_vaapi etc.",
"user already exists": "user already exists",
"Username": "Username",
"Video recorder": "Video recorder",
"Video unchanged, audio → AAC (browsers)": "Video unchanged, audio → AAC (browsers)",
"viewer": "viewer",
"viewer (watch only)": "viewer (watch only)",
"Violet": "Violet",
"Waiting for first results…": "Waiting for first results…",
"warnings and errors": "warnings and errors",
"Wednesday": "Wednesday",
"What the server is doing: tuners, streams, access, EPG and recordings. The last 4000 entries are kept in memory.": "What the server is doing: tuners, streams, access, EPG and recordings. The last 4000 entries are kept in memory.",
"While watching and periodically from every mux": "While watching and periodically from every mux",
"Wide": "Wide",
"Without ffmpeg on the server use VLC or a browser/device that decodes these codecs.": "Without ffmpeg on the server use VLC or a browser/device that decodes these codecs.",
"X-Forwarded-For / X-Forwarded-Proto are honoured only from these addresses (e.g. RustProxy).": "X-Forwarded-For / X-Forwarded-Proto are honoured only from these addresses (e.g. RustProxy).",
"XMLTV file too large": "XMLTV file too large",
"XMLTV sources (one URL per line, .xml or .xml.gz)": "XMLTV sources (one URL per line, .xml or .xml.gz)",
"yes": "yes",
"you": "you",
"you cannot delete your own account": "you cannot delete your own account",
"you cannot remove your own administrator role": "you cannot remove your own administrator role",
"{slug} is replaced with the channel name, e.g. “tvp-1”, “polsat-news”. First hit wins; icons are stored locally.": "{slug} is replaced with the channel name, e.g. “tvp-1”, “polsat-news”. First hit wins; icons are stored locally.",
"· new channels:": "· new channels:",
"· services:": "· services:",
"— none —": "— none —",
"⎋ Sign out": "⎋ Sign out",
"■ Stop": "■ Stop",
"▶ Open in VLC": "▶ Open in VLC",
"▶ Play": "▶ Play",
"▶ Watch": "▶ Watch",
"▶ Watch channel": "▶ Watch channel",
"● Record": "● Record",
"● Record programme": "● Record programme",
"⛶ Fullscreen": "⛶ Fullscreen",
"⤒ Restore from file": "⤒ Restore from file",
"⤓ Download": "⤓ Download",
"⤓ Download backup (JSON)": "⤓ Download backup (JSON)",
"One entry per line: a network (192.168.0.0/16), an address or a DDNS host name (myhome.ddns.net, re-resolved every minute). Empty = a token or panel session is always required.": "One entry per line: a network (192.168.0.0/16), an address or a DDNS host name (myhome.ddns.net, re-resolved every minute). Empty = a token or panel session is always required.",
"e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net": "e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net",
"Networks, addresses or DDNS host names. Empty = panel reachable from anywhere (login still required).": "Networks, addresses or DDNS host names. Empty = panel reachable from anywhere (login still required).",
"DDNS host names now resolve to:": "DDNS host names now resolve to:",
"not resolved": "not resolved",
"Start playback when opening the TV page": "Start playback when opening the TV page",
"Play": "Play",
"streams unknown": "streams unknown",
"The scan did not see this service's stream list in time. It is filled in when the channel is played or with “Detect streams”.": "The scan did not see this service's stream list in time. It is filled in when the channel is played or with “Detect streams”.",
"Detect streams": "Detect streams",
"Stream detection is already running": "Stream detection is already running",
"Detecting streams of": "Detecting streams of",
"channels on": "channels on",
"muxes…": "muxes…"
},
"patterns": []
}
+830
View File
@@ -0,0 +1,830 @@
{
"meta": {
"locale": "pl_PL",
"name": "Polish",
"native_name": "Polski",
"direction": "ltr"
},
"translations": {
"(change it in Settings). Add": "(zmienisz w Ustawieniach). Dodaj",
") and membership in group": ") oraz członkostwo w grupie",
"+ Add from services": "+ Dodaj z usług",
"+ Add manually": "+ Dodaj ręcznie",
"+ New recording": "+ Nowe nagranie",
"+ New rule": "+ Nowa reguła",
"+ New token": "+ Nowy token",
"+ New user": "+ Nowy użytkownik",
", and for transcoding": ", a dla transkodowania",
", the driver and firmware (for Si2168:": ", sterownik i firmware (dla Si2168:",
".": ".",
"0 = never": "0 = nigdy",
"0 = only while watching": "0 = tylko podczas oglądania",
"A rule schedules recordings of every EPG programme (next 48 h) whose title matches the pattern – a title fragment or a regular expression.": "Reguła planuje nagrania wszystkich audycji z EPG (najbliższe 48 h), których tytuł pasuje do wzorca – fragmentu tytułu lub wyrażenia regularnego.",
"a scan is already running": "skanowanie już trwa",
"A token allows playing streams from outside the local network (e.g. a TV at your family’s place). It can be limited to selected addresses/networks.": "Token pozwala odtwarzać strumienie spoza sieci lokalnej (np. TV u rodziny). Można go ograniczyć do wybranych adresów/sieci.",
"Accent colour": "Kolor akcentu",
"Access": "Dostęp",
"Access & sharing": "Dostęp i udostępnianie",
"Access control (ACL)": "Kontrola dostępu (ACL)",
"Access tokens": "Tokeny dostępu",
"Access: logins, tokens, allowed and denied requests": "Dostęp: logowania, tokeny, dozwolone i odrzucone żądania",
"ACL saved": "Zapisano ACL",
"active": "aktywny",
"Active": "Aktywny",
"Active clients": "Aktywni klienci",
"active tuners": "aktywne tunery",
"active:": "aktywny:",
"Adapter": "Adapter",
"Adapters": "Adaptery",
"Add": "Dodaj",
"Add channels from services": "Dodaj kanały z usług",
"Add radio stations": "Dodawaj stacje radiowe",
"Add scrambled channels": "Dodawaj kanały kodowane",
"Add selected": "Dodaj zaznaczone",
"Added – use “Rescan: saved muxes” to read its services": "Dodano – użyj „Ponownie: zapisane multipleksy”, aby odczytać usługi",
"Address": "Adres",
"administrator": "administrator",
"Administrators only.": "Tylko administrator.",
"Age": "Wiek",
"all": "wszystkie",
"All": "Wszystkie",
"All groups": "Wszystkie grupy",
"All levels": "Wszystkie poziomy",
"All services already have channels.": "Wszystkie usługi mają już kanały.",
"All types": "Wszystkie typy",
"Allowed networks (optional)": "Dozwolone sieci (opcjonalnie)",
"Always expanded": "Zawsze rozwinięty",
"Amber": "Bursztynowy",
"Animations": "Animacje",
"Appearance": "Wygląd",
"Application": "Aplikacja",
"Application: start-up, settings, panel, API": "Aplikacja: start, ustawienia, panel, API",
"Arts & culture": "Kultura",
"Arts / Culture": "Kultura",
"Assign numbers 1..n in the current order?": "Nadać numery 1..n według bieżącej kolejności?",
"Audio → AAC": "Audio → AAC",
"Australia – VHF 6–12 + UHF 28–51 (7 MHz)": "Australia – VHF 6–12 + UHF 28–51 (7 MHz)",
"automatic": "automatycznie",
"Automatic": "Automatyczny",
"available": "dostępny",
"background": "w tle",
"Background scan every (h)": "Skanowanie w tle co (h)",
"Background scan of saved muxes when tuners are idle: every": "Skanowanie zapisanych multipleksów w tle, gdy tunery są wolne: co",
"background scan stopped – the adapter is needed": "skanowanie w tle przerwane – adapter jest potrzebny",
"Background scan: create channels for new services": "Skanowanie w tle: twórz kanały dla nowych usług",
"Background scan: follow the NIT to new muxes": "Skanowanie w tle: szukaj nowych multipleksów w NIT",
"Background scanning is off (Settings → Scanning).": "Skanowanie w tle jest wyłączone (Ustawienia → Skanowanie).",
"Backup": "Kopia zapasowa",
"Backup restored": "Przywrócono kopię",
"Bandwidth": "Szerokość",
"Bandwidth (MHz)": "Szerokość (MHz)",
"bandwidth: 5, 6, 7 or 8 MHz": "szerokość kanału: 5, 6, 7 lub 8 MHz",
"Below this threshold the oldest recordings are deleted; 0 = disabled": "Poniżej progu usuwane są najstarsze nagrania; 0 = wyłączone",
"bitrate": "przepływność",
"Blue": "Niebieski",
"Browser": "Przeglądarka",
"Buffering…": "Buforowanie…",
"Cable DVB-C – 114–858 MHz": "Kablówka DVB-C – 114–858 MHz",
"Cancel": "Anuluj",
"cancelled": "anulowane",
"cancelled by user": "przerwano przez użytkownika",
"Change": "Zmień",
"Change my password": "Zmień moje hasło",
"Change password": "Zmiana hasła",
"Changes apply immediately (to new stream sessions).": "Zmiany obowiązują od razu (nowe sesje strumieni).",
"Channel": "Kanał",
"channel does not exist": "kanał nie istnieje",
"channel has no service assigned": "kanał nie ma przypisanej usługi",
"Channel icons": "Ikony kanałów",
"Channel list": "Lista kanałów",
"channel name must be 1–120 characters": "nazwa kanału 1–120 znaków",
"channel number must be 0–99999": "numer kanału 0–99999",
"channel service does not exist": "usługa kanału nie istnieje",
"Channels": "Kanały",
"Channels are matched by the channel’s “EPG ID” or by name. A line starting with # is disabled. XMLTV data takes precedence over EIT.": "Kanały dopasowywane są po „Identyfikatorze EPG” kanału lub nazwie. Linia zaczynająca się od # = wyłączone. Dane XMLTV mają pierwszeństwo przed EIT.",
"Children": "Dla dzieci",
"Children's / Youth": "Dla dzieci",
"choose a channel": "podaj kanał",
"Clear view": "Wyczyść widok",
"Click ▶ to play": "Kliknij ▶, aby odtworzyć",
"Client": "Klient",
"Clients": "Klienci",
"clients": "klienci",
"Clients & sessions": "Klienci i sesje",
"Close": "Zamknij",
"Close idle HLS session after (s)": "Zamknij sesję HLS po bezczynności (s)",
"Codecs": "Kodeki",
"Collect EPG from the broadcast (EIT)": "Zbieraj EPG z sygnału (EIT)",
"Collecting data…": "Zbieranie danych…",
"Comfortable": "Wygodna",
"Compact": "Kompaktowa",
"completed": "gotowe",
"Configuration": "Konfiguracja",
"conflict": "konflikt",
"Conflict: not enough tuners": "Konflikt: za mało tunerów",
"conflicts:": "konflikty:",
"Connected to server": "Połączono z serwerem",
"CONTROL ROOM": "STEROWNIA",
"Copied to clipboard": "Skopiowano do schowka",
"Copy": "Kopiuj",
"Copy failed": "Nie udało się skopiować",
"Copy link": "Kopiuj link",
"Copy token": "Kopiuj token",
"Could not play the stream": "Nie udało się odtworzyć strumienia",
"CPU": "CPU",
"Create": "Utwórz",
"Create channels automatically": "Twórz kanały automatycznie",
"Created": "Utworzony",
"Current password": "Obecne hasło",
"current password is incorrect": "obecne hasło jest nieprawidłowe",
"Custom frequency list": "Własna lista częstotliwości",
"Cut on keyframes – actual length depends on the broadcaster’s GOP": "Cięcie na klatkach kluczowych – rzeczywista długość zależy od GOP nadawcy",
"Dark": "Ciemny",
"database migrations": "migracje bazy",
"decompressing gzip": "rozpakowanie gzip",
"Default M3U format": "Domyślny format M3U",
"Default M3U format:": "Domyślny format M3U:",
"Default player profile": "Domyślny profil odtwarzacza",
"Delete": "Usuń",
"Delete channel": "Usuń kanał",
"Delete recordings older than (days)": "Usuwaj nagrania starsze niż (dni)",
"Delete shown": "Usuń widoczne",
"Delete the mux with its services? Channels will lose their source.": "Usunąć multipleks wraz z usługami? Kanały stracą źródło.",
"Delete the recording together with its file?": "Usunąć nagranie wraz z plikiem z dysku?",
"Delete the rule? Recordings scheduled by it will be cancelled.": "Usunąć regułę? Zaplanowane z niej nagrania zostaną anulowane.",
"Delete the token? Devices using it will lose access.": "Usunąć token? Urządzenia z nim stracą dostęp.",
"Delete the user?": "Usunąć użytkownika?",
"Density": "Gęstość",
"Detect adapters": "Wykryj adaptery",
"Device": "Urządzenie",
"Diagnostics": "Diagnostyka",
"Disable shown": "Wyłącz widoczne",
"disabled": "wyłączony",
"Disabled only": "Tylko wyłączone",
"Download": "Pobierz",
"downloading XMLTV": "pobieranie XMLTV",
"Drag rows to reorder. Numbers can also be typed in.": "Przeciągnij wiersze, aby ułożyć kolejność. Numery można też wpisać ręcznie.",
"Duration": "Czas trwania",
"DVB-T/T2/C cards (e.g. Si2168), frequency scanning and saved muxes.": "Karty DVB-T/T2/C (np. Si2168), skanowanie częstotliwości i zapisane multipleksy.",
"e.g. https://tv.example.com – empty = from the Host header": "np. https://tv.example.pl – puste = z nagłówka Host",
"e.g. Living room Sony TV": "np. Sony TV salon",
"e.g. Teleexpress or ^News$": "np. Teleexpress lub ^Fakty$",
"Each bar is one recording (padding included); colours mark the multiplex – recordings on the same multiplex share one tuner.": "Każdy pasek to jedno nagranie (z marginesami); kolory oznaczają multipleks – nagrania z tego samego multipleksu dzielą jeden tuner.",
"Edit": "Edytuj",
"Edit rule": "Edycja reguły",
"Education": "Edukacja",
"Education / Science / Factual topics": "Edukacja",
"EIT (broadcast)": "EIT (sygnał)",
"Electronic programme guide": "Elektroniczny przewodnik",
"empty = automatic match by name": "puste = automatyczne dopasowanie po nazwie",
"empty frequency list": "pusta lista częstotliwości",
"Enable shown": "Włącz widoczne",
"Enabled": "Włączony",
"Enabled and disabled": "Włączone i wyłączone",
"Enabled only": "Tylko włączone",
"End": "Koniec",
"end must be after start": "koniec musi być po początku",
"enter a title pattern (1–200 characters)": "podaj wzorzec tytułu (1–200 znaków)",
"enter a token name (e.g. Living room TV)": "podaj nazwę tokenu (np. Telewizor salon)",
"Entertainment": "Rozrywka",
"entries": "wpisów",
"EPG": "EPG",
"EPG from the broadcast (EIT) and external XMLTV sources.": "EPG z sygnału (EIT) oraz zewnętrznych źródeł XMLTV.",
"EPG grabbing will start when tuners are free": "Zbieranie EPG rozpocznie się, gdy tunery będą wolne",
"EPG grid": "Siatka EPG",
"EPG grid zoom": "Powiększenie siatki EPG",
"EPG ID (XMLTV)": "Identyfikator EPG (XMLTV)",
"EPG – upcoming programmes": "EPG – przyszłe audycje",
"EPG: over-the-air grabbing, XMLTV imports": "EPG: zbieranie z eteru, importy XMLTV",
"error": "błąd",
"Errors (UNC)": "Błędy (UNC)",
"errors only": "tylko błędy",
"Europe – UHF 21–48 (474–690 MHz, after 700 MHz refarming: PL, DE, FR, UK, CZ…)": "Europa – UHF 21–48 (474–690 MHz, po refarmingu 700 MHz: PL, DE, FR, UK, CZ…)",
"Europe – UHF 21–48 (474–690 MHz, after the 700 MHz refarming: PL, DE, FR, UK, CZ…)": "Europa – UHF 21–48 (474–690 MHz, po refarmingu 700 MHz: PL, DE, FR, UK, CZ…)",
"Europe – UHF 21–69 (474–858 MHz)": "Europa – UHF 21–69 (474–858 MHz)",
"Europe – VHF III (7 MHz) + UHF 21–69": "Europa – VHF III (7 MHz) + UHF 21–69",
"Expand on hover": "Rozwijany po najechaniu",
"Failed / cancelled": "Nieudane / anulowane",
"Faster zapping between channels of the same mux": "Szybsze przełączanie między kanałami z tego samego multipleksu",
"ffmpeg path": "Ścieżka do ffmpeg",
"Find automatically": "Szukaj automatycznie",
"Find further muxes via NIT": "Szukaj kolejnych multipleksów w NIT",
"Find icons": "Szukaj ikon",
"Finding icons…": "Szukanie ikon…",
"Finished": "Gotowe",
"Follow": "Śledź",
"Follow further muxes from the NIT": "Szukaj kolejnych multipleksów w NIT",
"For apps that speak tvheadend’s HTSP protocol (Kodi “Tvheadend HTSP Client”, TVHClient, PVR apps on Android/Sony TV): server = this address, HTSP port as above, HTTP port = the stream port. On the local network no login is needed; from elsewhere use any user name and an access token as the password.": "Dla aplikacji używających protokołu HTSP z tvheadend (Kodi „Tvheadend HTSP Client”, TVHClient, aplikacje PVR na Android/Sony TV): serwer = ten adres, port HTSP jak wyżej, port HTTP = port strumieni. W sieci lokalnej logowanie nie jest potrzebne; z zewnątrz podaj dowolną nazwę użytkownika i token dostępu jako hasło.",
"Frequencies (MHz, comma separated)": "Częstotliwości (MHz, oddzielone przecinkami)",
"Frequency": "Częstotliwość",
"Frequency (MHz)": "Częstotliwość (MHz)",
"Frequency list": "Lista częstotliwości",
"frequency out of range 40–900 MHz": "częstotliwość poza zakresem 40–900 MHz",
"Friday": "Piątek",
"From a rule": "Z reguły",
"frontend is busy or permission denied (video group?)": "frontend jest zajęty lub brak uprawnień (grupa video?)",
"Full transcoding to H.264 720p + AAC": "Pełne transkodowanie do H.264 720p + AAC",
"Fullscreen": "Pełny ekran",
"General": "Ogólne",
"Genre": "Gatunek",
"Grab all muxes every (h)": "Co ile godzin przechodzić po multipleksach",
"Grab EPG now": "Zbierz EPG teraz",
"Grab time per mux (s)": "Czas zbierania na multipleks (s)",
"Green": "Zielony",
"Group": "Grupa",
"H.264 profile arguments": "Argumenty profilu H.264",
"Hardware & muxes": "Sprzęt i multipleksy",
"Hide broken": "Ukryj uszkodzone",
"Hide scrambled": "Ukryj kodowane",
"HLS (m3u8)": "HLS (m3u8)",
"HLS segment length (s)": "Długość segmentu HLS (s)",
"HLS segment length must be 1–10 s": "długość segmentu HLS musi być w zakresie 1–10 s",
"HLS sessions": "sesje HLS",
"HLS window must be 3–60 segments": "okno HLS musi mieć 3–60 segmentów",
"https://… or upload a file below": "https://… lub wgraj plik poniżej",
"icon file is too large (max. 2 MiB)": "plik ikony jest za duży (maks. 2 MiB)",
"Icon found": "Znaleziono ikonę",
"Icon URL": "Adres ikony",
"Icon URL templates": "Szablony adresów ikon",
"icon: http(s) URL or empty": "ikona: adres http(s) lub pusta",
"idle": "wolny",
"Import XMLTV every (h)": "Import XMLTV co (h)",
"Import XMLTV now": "Importuj XMLTV teraz",
"Imported": "Zaimportowano",
"in": "odbierane",
"Information": "Informacje",
"Install ffmpeg on the server to enable transcoding, or open the channel in VLC.": "Zainstaluj ffmpeg na serwerze, aby włączyć transkodowanie, albo otwórz kanał w VLC.",
"Interface preferences are stored in this browser.": "Ustawienia interfejsu są zapisywane w tej przeglądarce.",
"Interface preferences reset": "Przywrócono domyślne ustawienia interfejsu",
"Interface scale": "Skala interfejsu",
"invalid recording time (max. 12 h)": "nieprawidłowy czas nagrania (maks. 12 h)",
"invalid username": "nieprawidłowa nazwa użytkownika",
"invalid username or password": "nieprawidłowy login lub hasło",
"is still taken (tvheadend?). The links below use the panel port; simply-dvb takes the stream port over automatically once it is free.": "jest nadal zajęty (tvheadend?). Linki poniżej używają portu panelu; simply-dvb przejmie port strumieni automatycznie, gdy się zwolni.",
"Italy – VHF D–H2 + UHF 21–48": "Włochy – VHF D–H2 + UHF 21–48",
"Keep past programmes (h)": "Przechowuj przeszłe audycje (h)",
"Keep tuner after last client (s)": "Trzymaj tuner po ostatnim kliencie (s)",
"Keyboard shortcuts": "Skróty klawiszowe",
"Language": "Język",
"Last scan": "Ostatni skan",
"Last used": "Użyty",
"Last XMLTV import:": "Ostatni import XMLTV:",
"last:": "ostatnio:",
"Leisure": "Hobby",
"Leisure hobbies": "Hobby",
"Light": "Jasny",
"Light / dark theme": "Jasny / ciemny motyw",
"Link inactive": "Link nieaktywny",
"LIVE": "NA ŻYWO",
"Live": "Na żywo",
"Live broadcast": "Transmisja na żywo",
"load": "obciążenie",
"Load average (1 min)": "Średnie obciążenie (1 min)",
"Loading recording…": "Wczytywanie nagrania…",
"local network": "sieć lokalna",
"Local network (no token)": "Sieć lokalna (bez tokenu)",
"Lock timeout (ms)": "Czas oczekiwania na lock (ms)",
"Login": "Login",
"login required": "wymagane logowanie",
"Logos in the channel list": "Logotypy na liście kanałów",
"Logs": "Logi",
"M3U format: hls or ts": "format M3U: hls lub ts",
"Manual recording": "Nagranie ręczne",
"Matching programmes (48 h)": "Pasujące audycje (48 h)",
"max": "maks.",
"Memory": "Pamięć",
"Midnight (OLED)": "Północ (OLED)",
"Minimum free space (GiB)": "Minimalne wolne miejsce (GiB)",
"missing X-Requested-With header": "brak nagłówka X-Requested-With",
"Modulation": "Modulacja",
"Modulation (DVB-C)": "Modulacja (DVB-C)",
"Monday": "Poniedziałek",
"Movie": "Film",
"Movie / Drama": "Film",
"Movies": "Filmy",
"MPEG-TS (continuous stream)": "MPEG-TS (ciągły strumień)",
"Multiplex bitrate": "Przepływność multipleksu",
"Music": "Muzyka",
"Music / Ballet / Dance": "Muzyka",
"Mute": "Wycisz",
"Mux": "Multipleks",
"mux does not exist": "multipleks nie istnieje",
"mux is disabled": "multipleks jest wyłączony",
"Mux services": "Usługi multipleksu",
"Muxes": "Multipleksy",
"Muxes found:": "Znaleziono multipleksów:",
"Muxes, services, channels (order, groups, links), recording rules, tokens and settings. Without user accounts, EPG, icons and recording files.": "Multipleksy, usługi, kanały (kolejność, grupy, linki), reguły nagrań, tokeny i ustawienia. Bez kont użytkowników, EPG, ikon i plików nagrań.",
"Name": "Nazwa",
"Narrow": "Zwarte",
"needs ffmpeg": "wymaga ffmpeg",
"Network": "Sieć",
"Networks": "Sieci",
"Networks allowed to reach the panel": "Sieci z dostępem do panelu",
"Networks with token-free access to streams, M3U and EPG": "Sieci z dostępem do strumieni, M3U i EPG bez tokenu",
"New mux": "Nowy multipleks",
"New password": "Nowe hasło",
"New password (min. 8 characters):": "Nowe hasło (min. 8 znaków):",
"New recording": "Nowe nagranie",
"New rule": "Nowa reguła",
"New token": "Nowy token",
"New user": "Nowy użytkownik",
"New Zealand – UHF 25–48": "Nowa Zelandia – UHF 25–48",
"News": "Wiadomości",
"News / Current affairs": "Wiadomości",
"Next:": "Następnie:",
"no adapter available": "brak dostępnego adaptera",
"No channels match the filters.": "Żaden kanał nie pasuje do filtrów.",
"No channels – run a scan on the Tuners page.": "Brak kanałów – uruchom skanowanie w zakładce Tunery.",
"No channels.": "Brak kanałów.",
"No channels. Run a scan on the": "Brak kanałów. Uruchom skanowanie w zakładce",
"no data": "brak danych",
"no data from the stream (timed out)": "brak danych ze strumienia (przekroczono czas oczekiwania)",
"no data from the tuner for 15 s": "brak danych z tunera od 15 s",
"no DVB adapters configured": "brak skonfigurowanych adapterów DVB",
"No DVB adapters detected. Check /dev/dvb and permissions (group": "Nie wykryto adapterów DVB. Sprawdź /dev/dvb i uprawnienia (grupa",
"No DVB cards detected. Check": "Nie wykryto kart DVB. Sprawdź",
"no enabled XMLTV sources in settings": "brak włączonych źródeł XMLTV w ustawieniach",
"No entries match.": "Brak pasujących wpisów.",
"No EPG data for this moment.": "Brak danych EPG dla tej chwili.",
"No EPG yet. Data appears after EIT is collected from the mux or XMLTV is imported.": "Brak EPG. Dane pojawią się po zebraniu EIT z multipleksu lub imporcie XMLTV.",
"No matching programmes in the EPG.": "Brak pasujących audycji w EPG.",
"No muxes – run a scan.": "Brak multipleksów – uruchom skanowanie.",
"No recordings in this category.": "Brak nagrań w tej kategorii.",
"No rules. Add e.g. “Teleexpress” or “^News$”.": "Brak reguł. Dodaj np. „Teleexpress” albo „^Wiadomości$”.",
"no service": "brak usługi",
"no signal": "brak sygnału",
"No tokens.": "Brak tokenów.",
"No.": "Nr",
"Nobody is watching right now.": "Nikt teraz nie ogląda.",
"Normal": "Normalne",
"not installed": "nie zainstalowany",
"not started before the programme ended": "nie rozpoczęto przed końcem audycji",
"Not supported by this browser": "Nieobsługiwane przez tę przeglądarkę",
"Nothing scheduled. Pick a programme in the TV guide or add a rule.": "Nic nie zaplanowano. Wybierz audycję w przewodniku TV albo dodaj regułę.",
"Now": "Teraz",
"Number": "Numer",
"Off = new services only appear in “Add from services”": "Wyłączone = nowe usługi pojawią się tylko w „Dodaj z usług”",
"only scheduled or running recordings can be changed": "można zmieniać tylko zaplanowane lub trwające nagrania",
"Only without EPG now": "Tylko bez bieżącego EPG",
"Only without icon": "Tylko bez ikony",
"opening the SQLite database": "otwarcie bazy SQLite",
"or": "lub",
"Orange": "Pomarańczowy",
"Order saved": "Zapisano kolejność",
"Original": "Oryginał",
"Original (no transcoding)": "Oryginał (bez transkodowania)",
"Other / data": "Inne / dane",
"out": "wysyłane",
"Overview": "Przegląd",
"Padding after (min)": "Margines po (min)",
"Padding before (min)": "Margines przed (min)",
"page.": ".",
"panel not available from this network": "panel niedostępny z tej sieci",
"Panel session lifetime (h)": "Czas sesji panelu (h)",
"Panel users": "Użytkownicy panelu",
"Password": "Hasło",
"Password changed": "Zmieniono hasło",
"Password changed – please sign in again": "Hasło zmienione – zaloguj się ponownie",
"password must be at least 8 characters": "hasło musi mieć co najmniej 8 znaków",
"Pattern": "Wzorzec",
"Pause / resume": "Pauza / wznów",
"per 2 s": "na 2 s",
"permission denied": "brak uprawnień",
"Personalization": "Personalizacja",
"Pick a channel from the list": "Wybierz kanał z listy",
"Picture-in-picture": "Obraz w obrazie",
"Picture-in-picture (P)": "Obraz w obrazie (P)",
"playback error": "błąd odtwarzania",
"Playlists & EPG": "Playlisty i EPG",
"Playlists for TVs, tokens, access control (ACL) and panel accounts.": "Playlisty dla telewizorów, tokeny, kontrola dostępu (ACL) i konta panelu.",
"PLP (DVB-T2, optional)": "PLP (DVB-T2, opcjonalnie)",
"Poland – UHF 21–48 (474–690 MHz)": "Polska – UHF 21–48 (474–690 MHz)",
"port taken (tvheadend?)": "port zajęty (tvheadend?)",
"Previous / next channel": "Poprzedni / następny kanał",
"Process memory (RSS)": "Pamięć procesu (RSS)",
"Profile": "Profil",
"programme does not exist": "audycja nie istnieje",
"Programme progress in the channel list": "Postęp audycji na liście kanałów",
"programmes in database:": "audycji w bazie:",
"Prometheus metrics": "Metryki Prometheus",
"Protocol": "Protokół",
"Provider": "Dostawca",
"public link": "link publiczny",
"Public link": "Publiczny link",
"Public link enabled and copied": "Link publiczny włączony i skopiowany",
"Public URL (for links)": "Publiczny adres (dla linków)",
"public URL must start with http:// or https://": "publiczny adres musi zaczynać się od http:// lub https://",
"radio": "radio",
"Radio": "Radio",
"Rate": "Przepływność",
"Record": "Nagraj",
"recording": "nagrywanie",
"Recording": "Nagrywanie",
"RECORDING": "NAGRANIE",
"recording does not exist": "nagranie nie istnieje",
"recording index missing": "brak indeksu nagrania",
"Recording scheduled": "Zaplanowano nagranie",
"Recording: schedule, running recordings, cleanup": "Nagrywanie: harmonogram, trwające nagrania, sprzątanie",
"Recordings": "Nagrania",
"recordings": "nagrania",
"Recordings directory": "Katalog nagrań",
"Recordings disk": "Dysk nagrań",
"recordings scheduled:": "zaplanowano nagrań:",
"Red": "Czerwony",
"Remove icon": "Usuń ikonę",
"Renumber 1..n": "Numeruj 1..n",
"Rescan: saved muxes": "Ponownie: zapisane multipleksy",
"Rescans saved muxes (and the NIT) on an idle adapter; stops as soon as someone starts watching or recording. 0 = off": "Ponownie skanuje zapisane multipleksy (i NIT) na wolnym adapterze; przerywa, gdy tylko ktoś zacznie oglądać lub nagrywać. 0 = wyłączone",
"Reset to defaults": "Przywróć domyślne",
"Restore configuration from the backup? Current channels, muxes, rules and tokens will be replaced.": "Przywrócić konfigurację z kopii? Obecne kanały, multipleksy, reguły i tokeny zostaną zastąpione.",
"Role": "Rola",
"Role changed": "Zmieniono rolę",
"role: admin or viewer": "rola: admin lub viewer",
"RSS": "RSS",
"Rule saved": "Zapisano regułę",
"Rules (series)": "Reguły (seriale)",
"running": "trwa",
"Saturday": "Sobota",
"Save": "Zapisz",
"Save ACL": "Zapisz ACL",
"Save settings": "Zapisz ustawienia",
"Saved": "Zapisano",
"Scan channels": "Skanuj kanały",
"Scan started": "Skanowanie rozpoczęte",
"scanning": "skanowanie",
"Scanning": "Skanowanie",
"Schedule": "Program",
"Schedule from the EPG or manually. Play finished recordings in the browser or download them as .ts.": "Planuj z EPG lub ręcznie. Gotowe nagrania odtworzysz w przeglądarce albo pobierzesz jako .ts.",
"Schedule recording": "Zaplanuj",
"scheduled": "zaplanowane",
"Scheduled": "Zaplanowano",
"Scheduled & running": "Zaplanowane i trwające",
"scrambled": "kodowany",
"Search channel…": "Szukaj kanału…",
"Searching for channel icons…": "Szukam ikon kanałów…",
"Search…": "Szukaj…",
"Security": "Bezpieczeństwo",
"segment unavailable": "segment niedostępny",
"Segments in playlist": "Segmentów w playliście",
"Select channel by number": "Wybór kanału po numerze",
"Sent": "Przesłano",
"Server connection": "Połączenie z serwerem",
"Server name": "Nazwa serwera",
"Service (source)": "Usługa (źródło)",
"service does not exist": "usługa nie istnieje",
"Services": "Usługi",
"Services without a channel:": "Usługi bez przypisanego kanału:",
"session ended": "sesja zakończona",
"Session expired – please sign in again": "Sesja wygasła – zaloguj się ponownie",
"session expired – reload the playlist": "sesja wygasła – odśwież playlistę",
"set the end time": "podaj czas zakończenia",
"Settings": "Ustawienia",
"Settings saved": "Zapisano ustawienia",
"Shortcuts: ↑/↓ channel, digits – number, F – fullscreen, P – picture-in-picture, M – mute, ? – help.": "Skróty: ↑/↓ kanał, cyfry – numer, F – pełny ekran, P – obraz w obrazie, M – wycisz, ? – pomoc.",
"Show / Game show": "Rozrywka",
"Show clock in the top bar": "Pokaż zegar w górnym pasku",
"Si2168 usually locks DVB-T2 within ~1–2 s": "Si2168 zwykle synchronizuje DVB-T2 w ~1–2 s",
"Sidebar": "Pasek boczny",
"Sign in": "Zaloguj się",
"Sign out": "Wyloguj",
"Signal level": "Poziom sygnału",
"Signal strength": "Siła sygnału",
"signal, no lock": "sygnał bez locka",
"simply-dvb · panel": "simply-dvb · panel",
"Since": "Od",
"Size": "Rozmiar",
"Social": "Społeczeństwo",
"Social / Political issues / Economics": "Społeczeństwo",
"Source": "Źródło",
"Space": "Spacja",
"Special": "Specjalne",
"Special characteristics": "Specjalne",
"Sport": "Sport",
"Start": "Start",
"Start after all tuners are idle for (min)": "Start po bezczynności wszystkich tunerów przez (min)",
"Start page": "Strona startowa",
"Start scan": "Rozpocznij skanowanie",
"Starts": "Początek",
"Status": "Status",
"Stop": "Przerwij",
"Stream": "Strumień",
"stream ended": "strumień zakończony",
"stream interrupted": "strumień przerwany",
"Stream port": "Port strumieni",
"Stream port: /playlist, /playlist.m3u, /xmltv, /epg.xml, /stream/channelid/<id>, /hls/<id>/index.m3u8": "Port strumieni: /playlist, /playlist.m3u, /xmltv, /epg.xml, /stream/channelid/<id>, /hls/<id>/index.m3u8",
"Streaming": "Strumieniowanie",
"Streaming (HLS / TS)": "Strumieniowanie (HLS / TS)",
"Streaming throughput": "Przepustowość strumieni",
"Streaming: HLS, MPEG-TS, HTSP, transcoding, clients": "Strumieniowanie: HLS, MPEG-TS, HTSP, transkodowanie, klienci",
"Streams": "Strumienie",
"Strength": "Siła",
"Sunday": "Niedziela",
"Supported by this browser": "Obsługiwane przez tę przeglądarkę",
"Symbol rate (kS/s)": "Symbol rate (kS/s)",
"Symbol rate (kS/s, DVB-C)": "Symbol rate (kS/s, DVB-C)",
"System": "System",
"system": "system",
"System default": "Systemowy",
"system: dvbt or dvbt2": "system: dvbt lub dvbt2",
"system: dvbt, dvbt2 or dvbc": "system: dvbt, dvbt2 lub dvbc",
"System: HTTP server, libraries": "System: serwer HTTP, biblioteki",
"Teal": "Turkusowy",
"Television, in focus.": "Telewizja, w skupieniu.",
"Temperature": "Temperatura",
"the programme has already ended": "audycja już się zakończyła",
"the recording’s channel was deleted": "kanał nagrania został usunięty",
"the stream": "strumienia",
"The “Automatic” profile checks which codecs your browser supports (e.g. HEVC, AC-3) and enables ffmpeg transcoding when needed.": "Profil „Automatyczny” sprawdza kodeki obsługiwane przez przeglądarkę (np. HEVC, AC-3) i w razie potrzeby włącza transkodowanie ffmpeg.",
"Theme": "Motyw",
"This browser does not support HLS": "Ta przeglądarka nie obsługuje HLS",
"This browser reports no HEVC (H.265) support. Chrome/Edge decode it only with hardware acceleration (on Linux: VA-API); Safari plays it natively.": "Przeglądarka zgłasza brak obsługi HEVC (H.265). Chrome/Edge dekodują go tylko sprzętowo (w Linuksie: VA-API); Safari odtwarza go natywnie.",
"This help": "Ta pomoc",
"this is not a simply-dvb backup": "to nie jest kopia zapasowa simply-dvb",
"This stream link has expired or was disabled.": "Ten link do transmisji wygasł lub został wyłączony.",
"Thursday": "Czwartek",
"Time": "Czas",
"Title": "Tytuł",
"Title pattern": "Wzorzec tytułu",
"to clients": "do klientów",
"too many failed attempts, try again in a few minutes": "zbyt wiele nieudanych prób, spróbuj za kilka minut",
"Transcoding (ffmpeg)": "Transkodowanie (ffmpeg)",
"Trusted reverse proxies": "Zaufane reverse proxy",
"TS – lightest for TVs, HLS – for apps that require HLS": "TS – najlżejszy dla telewizorów, HLS – dla aplikacji wymagających HLS",
"Tuesday": "Wtorek",
"Tuner is waiting for clients.": "Tuner czeka na klientów.",
"Tuners": "Tunery",
"Tuners & devices": "Tunery i urządzenia",
"Tuners & scanning": "Tunery i skanowanie",
"Tuners and devices: adapters, tuning, lock, scanning": "Tunery i urządzenia: adaptery, strojenie, synchronizacja, skanowanie",
"Tuners, streams, clients and EPG in one place.": "Tunery, strumienie, klienci i EPG w jednym miejscu.",
"Tuners:": "Tunery:",
"Tuning and buffering…": "Strojenie tunera i buforowanie…",
"tuning timed out": "przekroczono czas strojenia",
"tv": "tv",
"TV": "Telewizja",
"TV guide": "Program TV",
"TVH = tvheadend-compatible URLs (stream port, 9981 by default): /playlist, /xmltv/channels, /stream/channelid/<id>, /imagecache/<id>, auth= / ticket= parameters and HTTP Basic login. An app configured for tvheadend works after changing just the server address.": "TVH = adresy zgodne z tvheadend (port strumieni, domyślnie 9981): /playlist, /xmltv/channels, /stream/channelid/<id>, /imagecache/<id>, parametry auth= / ticket= i login HTTP Basic. Aplikacja skonfigurowana pod tvheadend działa po zmianie samego adresu serwera.",
"Type": "Typ",
"UHF channel": "Kanał UHF",
"Uncorrected blocks": "Bloki z błędami",
"unknown": "nieznane",
"unknown profile": "nieznany profil",
"unsupported image format (PNG, JPEG, GIF, WebP, SVG)": "nieobsługiwany format obrazu (PNG, JPEG, GIF, WebP, SVG)",
"Updated channels:": "Zmienione kanały:",
"used": "zajęte",
"Used by the “h264” profile (e.g. HEVC in browsers without a hardware decoder). Hardware acceleration can be added: -c:v h264_vaapi etc.": "Używane przez profil „h264” (np. dla HEVC w przeglądarkach bez sprzętowego dekodera). Można dodać akcelerację: -c:v h264_vaapi itp.",
"user already exists": "użytkownik już istnieje",
"Username": "Użytkownik",
"Video recorder": "Magnetowid",
"Video unchanged, audio → AAC (browsers)": "Wideo bez zmian, audio → AAC (przeglądarki)",
"viewer": "widz",
"viewer (watch only)": "widz (tylko oglądanie)",
"Violet": "Fioletowy",
"Waiting for first results…": "Czekam na pierwsze wyniki…",
"warnings and errors": "ostrzeżenia i błędy",
"Wednesday": "Środa",
"What the server is doing: tuners, streams, access, EPG and recordings. The last 4000 entries are kept in memory.": "Co robi serwer: tunery, strumienie, dostęp, EPG i nagrania. W pamięci trzymane jest ostatnie 4000 wpisów.",
"While watching and periodically from every mux": "Podczas oglądania i okresowo z każdego multipleksu",
"Wide": "Szerokie",
"Without ffmpeg on the server use VLC or a browser/device that decodes these codecs.": "Bez ffmpeg na serwerze użyj VLC albo przeglądarki/urządzenia, które dekoduje te kodeki.",
"X-Forwarded-For / X-Forwarded-Proto are honoured only from these addresses (e.g. RustProxy).": "Tylko od tych adresów brane są X-Forwarded-For / X-Forwarded-Proto (np. RustProxy).",
"XMLTV file too large": "plik XMLTV za duży",
"XMLTV sources (one URL per line, .xml or .xml.gz)": "Źródła XMLTV (adres w linii, .xml lub .xml.gz)",
"yes": "tak",
"you": "ty",
"you cannot delete your own account": "nie możesz usunąć własnego konta",
"you cannot remove your own administrator role": "nie możesz odebrać sobie roli administratora",
"{slug} is replaced with the channel name, e.g. “tvp-1”, “polsat-news”. First hit wins; icons are stored locally.": "{slug} zostanie zastąpione nazwą kanału, np. „tvp-1”, „polsat-news”. Pierwsze trafienie wygrywa; ikony są zapisywane lokalnie.",
"· new channels:": "· nowych kanałów:",
"· services:": "· usług:",
"— none —": "— brak —",
"⎋ Sign out": "⎋ Wyloguj",
"■ Stop": "■ Zatrzymaj",
"▶ Open in VLC": "▶ Otwórz w VLC",
"▶ Play": "▶ Odtwórz",
"▶ Watch": "▶ Oglądaj",
"▶ Watch channel": "▶ Oglądaj kanał",
"● Record": "● Nagraj",
"● Record programme": "● Nagraj audycję",
"⛶ Fullscreen": "⛶ Pełny ekran",
"⤒ Restore from file": "⤒ Przywróć z pliku",
"⤓ Download": "⤓ Pobierz",
"⤓ Download backup (JSON)": "⤓ Pobierz kopię (JSON)",
"One entry per line: a network (192.168.0.0/16), an address or a DDNS host name (myhome.ddns.net, re-resolved every minute). Empty = a token or panel session is always required.": "Jeden wpis w linii: sieć (192.168.0.0/16), adres lub nazwa hosta DDNS (mojdom.ddns.net, odświeżana co minutę). Puste = zawsze wymagany token lub sesja panelu.",
"e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net": "np. 83.1.2.3, 10.8.0.0/24, mojdom.ddns.net",
"Networks, addresses or DDNS host names. Empty = panel reachable from anywhere (login still required).": "Sieci, adresy lub nazwy hostów DDNS. Puste = panel dostępny zewsząd (nadal wymaga logowania).",
"DDNS host names now resolve to:": "Nazwy hostów DDNS wskazują teraz na:",
"not resolved": "nie rozwiązano",
"Start playback when opening the TV page": "Zacznij odtwarzanie po otwarciu strony TV",
"Play": "Odtwórz",
"streams unknown": "strumienie nieznane",
"The scan did not see this service's stream list in time. It is filled in when the channel is played or with “Detect streams”.": "Skan nie zdążył odczytać listy strumieni tej usługi. Uzupełni się przy odtworzeniu kanału lub przez „Wykryj strumienie”.",
"Detect streams": "Wykryj strumienie",
"Stream detection is already running": "Wykrywanie strumieni już trwa",
"Detecting streams of": "Wykrywanie strumieni",
"channels on": "kanałów na",
"muxes…": "muksach…"
},
"patterns": [
{
"match": "^(\\d+) entries$",
"replace": "$1 wpisów"
},
{
"match": "^Stream port (\\d+) is still taken \\(tvheadend\\?\\)\\. ([\\s\\S]*)$",
"replace": "Port strumieni $1 jest nadal zajęty (tvheadend?). Linki poniżej używają portu panelu; simply-dvb przejmie port strumieni automatycznie, gdy się zwolni."
},
{
"match": "^(\\d+) services · (\\d+) muxes$",
"replace": "$1 usług · $2 multipleksów"
},
{
"match": "^last grab: (.*)$",
"replace": "ostatnie zbieranie: $1"
},
{
"match": "^(\\d+) scheduled · (\\d+) total$",
"replace": "$1 zaplanowanych · $2 łącznie"
},
{
"match": "^free · load (.*) · up (.*)$",
"replace": "wolne · obciążenie $1 · działa $2"
},
{
"match": "^(\\d+) · priority (.*)$",
"replace": "$1 · priorytet $2"
},
{
"match": "^Last error: ([\\s\\S]*)$",
"replace": "Ostatni błąd: $t1"
},
{
"match": "^user (.*)$",
"replace": "użytkownik $1"
},
{
"match": "^(.*) · viewer$",
"replace": "$1 · widz"
},
{
"match": "^Recording scheduled: (.*)$",
"replace": "Zaplanowano nagranie: $1"
},
{
"match": "^Channel: (.*)$",
"replace": "Kanał: $1"
},
{
"match": "^Delete channel “(.*)”\\? \\(the service stays in the database\\)$",
"replace": "Usunąć kanał „$1”? (usługa pozostanie w bazie)"
},
{
"match": "^No icon found for “(.*)”$",
"replace": "Nie znaleziono ikony dla „$1”"
},
{
"match": "^Found (\\d+) icons\\nWithout icon: ([\\s\\S]*)$",
"replace": "Znaleziono $1 ikon\nBez ikony: $2"
},
{
"match": "^Found (\\d+) icons$",
"replace": "Znaleziono $1 ikon"
},
{
"match": "^Added (\\d+) channels$",
"replace": "Dodano $1 kanałów"
},
{
"match": "^Adapters detected: (\\d+)$",
"replace": "Wykryto adapterów: $1"
},
{
"match": "^finished (.*)$",
"replace": "zakończono $1"
},
{
"match": "^Virtual adapter \\((.*)\\)$",
"replace": "Adapter wirtualny ($1)"
},
{
"match": "^(DVB-[TC]2?) (.*?): (\\d+) services(, SNR [\\d.]+ dB)? – (.*)$",
"replace": "$1 $2: $3 usług$4 – $5"
},
{
"match": "^NIT: new mux (.*)$",
"replace": "NIT: nowy multipleks $1"
},
{
"match": "^(DVB-[TC]2?) (.*?): error ([\\s\\S]*)$",
"replace": "$1 $2: błąd $t3"
},
{
"match": "^Could not play: ([\\s\\S]*)$",
"replace": "Nie udało się odtworzyć: $t1"
},
{
"match": "^Browser lacks the codec – switching to the “(.*)” profile…$",
"replace": "Przeglądarka nie obsługuje kodeka – przełączam na profil „$1”…"
},
{
"match": "^Connection problem – retrying \\((\\d+)\\)…$",
"replace": "Problem z połączeniem – ponawiam ($1)…"
},
{
"match": "^Signed in as (.*)\\.$",
"replace": "Zalogowany jako $1."
},
{
"match": "^Empty = (.*)$",
"replace": "Puste = $t1"
},
{
"match": "^(.*): (\\d+) channels, (\\d+) programmes$",
"replace": "$1: $2 kanałów, $3 audycji"
},
{
"match": "^Shared by (.*)$",
"replace": "Udostępnione przez $1"
},
{
"match": "^no free tuner for (.*)$",
"replace": "brak wolnego tunera dla $1"
},
{
"match": "^no lock on (.*)$",
"replace": "brak synchronizacji (lock) na $1"
},
{
"match": "^adapter (.*) is busy \\(watching/recording\\)$",
"replace": "adapter $1 jest zajęty (oglądanie/nagrywanie)"
},
{
"match": "^unknown frequency list: (.*)$",
"replace": "nieznana lista częstotliwości: $1"
},
{
"match": "^invalid address/network: (.*)$",
"replace": "nieprawidłowy adres/sieć: $1"
},
{
"match": "^invalid XMLTV URL: (.*)$",
"replace": "nieprawidłowy adres XMLTV: $1"
},
{
"match": "^starting ffmpeg \\((.*)\\) – install ffmpeg or change its path in settings([\\s\\S]*)$",
"replace": "uruchomienie ffmpeg ($1) – zainstaluj ffmpeg lub zmień ścieżkę w ustawieniach$2"
},
{
"match": "^Service (\\d+)$",
"replace": "Usługa $1"
},
{
"match": "^unknown profile: (.*)$",
"replace": "nieznany profil: $1"
},
{
"match": "^tuning (.*)$",
"replace": "strojenie $1"
},
{
"match": "^reading dvr0: ([\\s\\S]*)$",
"replace": "odczyt dvr0: $1"
},
{
"match": "^unknown adapter type: (.*)$",
"replace": "nieznany typ adaptera: $1"
},
{
"match": "^This browser reports no support for (.*) video\\.$",
"replace": "Przeglądarka zgłasza brak obsługi obrazu $1."
},
{
"match": "^This browser reports no support for any audio track \\((.*)\\)\\.$",
"replace": "Przeglądarka zgłasza brak obsługi wszystkich ścieżek dźwiękowych ($1)."
},
{
"match": "^Delete (\\d+) channels\\? \\(services stay in the database\\)$",
"replace": "Usunąć $1 kanałów? (usługi pozostaną w bazie)"
},
{
"match": "^Finding icons… (\\d+)/(\\d+)$",
"replace": "Szukanie ikon… $1/$2"
},
{
"match": "^ffmpeg is not installed on the server – the “(.*)” transcoding profile is unavailable; play the original stream \\(pass\\) or install ffmpeg$",
"replace": "ffmpeg nie jest zainstalowany na serwerze – profil transkodowania „$1” jest niedostępny; odtwórz oryginalny strumień (pass) albo zainstaluj ffmpeg"
},
{
"match": "^background scan of saved muxes on (.*)$",
"replace": "skanowanie w tle zapisanych multipleksów na $1"
},
{
"match": "^(\\d+) min$",
"replace": "$1 min"
},
{
"match": "^(.*): error ([\\s\\S]*)$",
"replace": "$1: błąd $t2"
}
]
}
+117
View File
@@ -0,0 +1,117 @@
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'admin',
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
ip TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS adapters (
id TEXT PRIMARY KEY,
enabled INTEGER NOT NULL DEFAULT 1,
priority INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS muxes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
delsys TEXT NOT NULL,
frequency_hz INTEGER NOT NULL UNIQUE,
bandwidth_hz INTEGER NOT NULL DEFAULT 8000000,
plp_id INTEGER,
onid INTEGER,
ts_id INTEGER,
network_name TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 1,
last_scan INTEGER,
last_epg INTEGER
);
CREATE TABLE IF NOT EXISTS services (
id INTEGER PRIMARY KEY AUTOINCREMENT,
mux_id INTEGER NOT NULL REFERENCES muxes(id) ON DELETE CASCADE,
sid INTEGER NOT NULL,
name TEXT NOT NULL,
provider TEXT NOT NULL DEFAULT '',
service_type INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'tv',
lcn INTEGER,
pmt_pid INTEGER NOT NULL,
pcr_pid INTEGER NOT NULL DEFAULT 8191,
streams TEXT NOT NULL DEFAULT '[]',
scrambled INTEGER NOT NULL DEFAULT 0,
last_seen INTEGER NOT NULL,
UNIQUE (mux_id, sid)
);
CREATE TABLE IF NOT EXISTS channels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
number INTEGER NOT NULL,
name TEXT NOT NULL,
service_id INTEGER REFERENCES services(id) ON DELETE SET NULL,
enabled INTEGER NOT NULL DEFAULT 1,
grp TEXT NOT NULL DEFAULT '',
icon TEXT NOT NULL DEFAULT '',
epg_id TEXT NOT NULL DEFAULT '',
share_token TEXT UNIQUE,
share_enabled INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS channels_number ON channels(number);
CREATE TABLE IF NOT EXISTS epg_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id INTEGER NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
start INTEGER NOT NULL,
stop INTEGER NOT NULL,
title TEXT NOT NULL,
summary TEXT NOT NULL DEFAULT '',
description TEXT NOT NULL DEFAULT '',
genre TEXT NOT NULL DEFAULT '',
rating INTEGER,
source TEXT NOT NULL DEFAULT 'ota',
UNIQUE (channel_id, start)
);
CREATE INDEX IF NOT EXISTS epg_channel_stop ON epg_events(channel_id, stop);
CREATE INDEX IF NOT EXISTS epg_stop ON epg_events(stop);
CREATE TABLE IF NOT EXISTS recordings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id INTEGER REFERENCES channels(id) ON DELETE SET NULL,
channel_name TEXT NOT NULL DEFAULT '',
title TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
start INTEGER NOT NULL,
stop INTEGER NOT NULL,
pre_padding INTEGER NOT NULL DEFAULT 0,
post_padding INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'scheduled',
error TEXT NOT NULL DEFAULT '',
file TEXT NOT NULL DEFAULT '',
size INTEGER NOT NULL DEFAULT 0,
duration REAL NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS recordings_status ON recordings(status, start);
CREATE TABLE IF NOT EXISTS access_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
token TEXT NOT NULL UNIQUE,
allow_cidrs TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
last_used INTEGER
);
+10
View File
@@ -0,0 +1,10 @@
CREATE TABLE IF NOT EXISTS autorec (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
pattern TEXT NOT NULL,
channel_id INTEGER REFERENCES channels(id) ON DELETE CASCADE,
enabled INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL
);
ALTER TABLE recordings ADD COLUMN autorec_id INTEGER;
+32
View File
@@ -0,0 +1,32 @@
-- DVB-C: symbol rate i modulacja; unikalność częstotliwości w obrębie medium (naziemne / kablowe).
-- Tabela muxes jest przebudowywana. Ponieważ migracja działa w transakcji (PRAGMA foreign_keys
-- nie działa wewnątrz transakcji), usługi i powiązania kanałów są zachowywane w kopiach.
CREATE TABLE _services_bak AS SELECT * FROM services;
CREATE TABLE _channel_map AS SELECT id, service_id FROM channels;
CREATE TABLE muxes_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
delsys TEXT NOT NULL,
medium TEXT NOT NULL DEFAULT 'terrestrial',
frequency_hz INTEGER NOT NULL,
bandwidth_hz INTEGER NOT NULL DEFAULT 8000000,
plp_id INTEGER,
symbol_rate INTEGER,
modulation TEXT,
onid INTEGER,
ts_id INTEGER,
network_name TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 1,
last_scan INTEGER,
last_epg INTEGER,
UNIQUE (medium, frequency_hz)
);
INSERT INTO muxes_new (id, delsys, medium, frequency_hz, bandwidth_hz, plp_id, onid, ts_id, network_name, enabled, last_scan, last_epg)
SELECT id, delsys, 'terrestrial', frequency_hz, bandwidth_hz, plp_id, onid, ts_id, network_name, enabled, last_scan, last_epg FROM muxes;
DROP TABLE muxes;
ALTER TABLE muxes_new RENAME TO muxes;
INSERT INTO services SELECT * FROM _services_bak;
UPDATE channels SET service_id = (SELECT m.service_id FROM _channel_map m WHERE m.id = channels.id);
DROP TABLE _services_bak;
DROP TABLE _channel_map;
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
set -e
if [ "$1" = "configure" ]; then
if ! getent group simply-dvb >/dev/null; then
addgroup --system simply-dvb >/dev/null
fi
if ! getent passwd simply-dvb >/dev/null; then
adduser --system --ingroup simply-dvb --home /var/lib/simply-dvb \
--no-create-home --shell /usr/sbin/nologin \
--gecos "simply-dvb" simply-dvb >/dev/null
fi
for g in video render; do
if getent group "$g" >/dev/null; then
adduser simply-dvb "$g" >/dev/null 2>&1 || true
fi
done
install -d -o simply-dvb -g simply-dvb -m 0750 /var/lib/simply-dvb
if [ ! -f /var/lib/simply-dvb/simply-dvb.db ]; then
echo "simply-dvb: after the first start the 'admin' account password is in"
echo " /var/lib/simply-dvb/initial-admin-password.txt (or: journalctl -u simply-dvb)"
echo "Panel: http://<server-address>:9980/ Streams (tvheadend-compatible): http://<server-address>:9981/playlist"
fi
fi
#DEBHELPER#
exit 0
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -e
#DEBHELPER#
if [ "$1" = "purge" ]; then
rm -rf /var/lib/simply-dvb
if getent passwd simply-dvb >/dev/null; then
deluser --system simply-dvb >/dev/null 2>&1 || true
fi
if getent group simply-dvb >/dev/null; then
delgroup --system simply-dvb >/dev/null 2>&1 || true
fi
fi
exit 0
+17
View File
@@ -0,0 +1,17 @@
# simply-dvb service configuration (systemd: EnvironmentFile)
# One VARIABLE=value per line; put comments on their own lines (systemd keeps "# ..." after a value).
# Web panel + API (streams are available here too)
SIMPLY_DVB_LISTEN=0.0.0.0:9980
# Separate tvheadend-compatible stream/playlist/EPG port (no panel). "off" = disabled.
# While tvheadend still holds this port, simply-dvb waits and takes it over once tvheadend is stopped.
SIMPLY_DVB_STREAM_LISTEN=0.0.0.0:9981
# HTSP (tvheadend binary protocol: Kodi HTSP client, TVHClient, PVR apps). "off" = disabled.
SIMPLY_DVB_HTSP_LISTEN=0.0.0.0:9982
# Data directory (database, icons, recordings). If changed, also add it to ReadWritePaths (systemctl edit simply-dvb).
SIMPLY_DVB_DATA_DIR=/var/lib/simply-dvb
# DVB device directory
SIMPLY_DVB_DEV_ROOT=/dev/dvb
# Virtual adapter with .ts files (testing without a card), e.g. /var/lib/simply-dvb/virtual
#SIMPLY_DVB_VIRTUAL_DIR=
# Log level
#RUST_LOG=simply_dvb=debug,warn
+42
View File
@@ -0,0 +1,42 @@
[Unit]
Description=simply-dvb – DVB-T/T2/C server (HLS, M3U, EPG)
Documentation=file:///usr/share/doc/simply-dvb/README.md
Wants=network-online.target
After=network-online.target systemd-udev-settle.service
[Service]
Type=simple
User=simply-dvb
Group=simply-dvb
SupplementaryGroups=video
EnvironmentFile=-/etc/default/simply-dvb
Environment=RUST_LOG=simply_dvb=info,warn
ExecStart=/usr/bin/simply-dvb serve
Restart=on-failure
RestartSec=3
StateDirectory=simply-dvb
StateDirectoryMode=0750
WorkingDirectory=/var/lib/simply-dvb
UMask=0027
# Access only to DVB devices (and DRM – ffmpeg/VAAPI acceleration)
DevicePolicy=closed
DeviceAllow=char-DVB rw
DeviceAllow=char-drm rw
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/simply-dvb
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
RestrictSUIDSGID=true
RestrictNamespaces=true
RestrictRealtime=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
LockPersonality=true
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
# All architectures: amd64, arm64, armhf -> dist/
set -euo pipefail
for a in amd64 arm64 armhf; do
"$(dirname "$0")/build-deb.sh" "$a"
done
ls -la "${OUT_DIR:-dist}"
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# .deb package for x86_64 (PC, server, NAS).
exec "$(dirname "$0")/build-deb.sh" amd64 "$@"
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# .deb package for Raspberry Pi 3/4/5 with a 64-bit OS (Raspberry Pi OS 64-bit, Debian, Ubuntu).
exec "$(dirname "$0")/build-deb.sh" arm64 "$@"
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# .deb package for Raspberry Pi with 32-bit Raspberry Pi OS (armv7).
exec "$(dirname "$0")/build-deb.sh" armhf "$@"
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env bash
# Builds the simply-dvb .deb package for the selected architecture.
#
# scripts/build-deb.sh amd64 # PC / x86_64 server
# scripts/build-deb.sh arm64 # Raspberry Pi 3/4/5 with 64-bit Raspberry Pi OS / Debian / Ubuntu
# scripts/build-deb.sh armhf # Raspberry Pi 2/3/4 with 32-bit Raspberry Pi OS
#
# By default the build itself runs in a Docker container (image scripts/docker/builder.Dockerfile),
# so the host only needs Docker – no Rust, zig or cargo-deb. The result lands in dist/ on the host.
# BUILD_IN_DOCKER=0 build directly on the host (e.g. in CI that already runs in a container)
# BUILDER_IMAGE=... builder image name (default simply-dvb-builder:1)
# DOCKER_ARGS="..." extra arguments for `docker run` (e.g. --network host)
# DOCKER_BUILD_ARGS="..." extra arguments for `docker build` of the builder image
#
# Build method inside (BUILD_METHOD variable):
# auto (default) – zigbuild (fixed glibc 2.31 baseline for all architectures), otherwise
# native (when host = target), cross or cross-gcc
# native – cargo build on the same architecture (e.g. directly on an RPi)
# zigbuild – cargo-zigbuild (zig as the linker, selectable glibc version: GLIBC=2.31)
# cross – cross-rs (Docker containers with ready-made toolchains)
# gcc – system cross-gcc (aarch64-linux-gnu-gcc / arm-linux-gnueabihf-gcc)
#
# Other variables:
# GLIBC=2.31 minimum glibc version for zigbuild (2.31 = Debian 11 / RPi OS bullseye and newer)
# OUT_DIR=dist output directory
set -euo pipefail
cd "$(dirname "$0")/.."
ARCH="${1:-}"
case "$ARCH" in
amd64|x86_64) DEB_ARCH=amd64; TARGET=x86_64-unknown-linux-gnu; GCC_PREFIX=x86_64-linux-gnu ;;
arm64|aarch64) DEB_ARCH=arm64; TARGET=aarch64-unknown-linux-gnu; GCC_PREFIX=aarch64-linux-gnu ;;
armhf|armv7) DEB_ARCH=armhf; TARGET=armv7-unknown-linux-gnueabihf; GCC_PREFIX=arm-linux-gnueabihf ;;
*) echo "Usage: $0 {amd64|arm64|armhf}" >&2; exit 2 ;;
esac
have() { command -v "$1" >/dev/null 2>&1; }
# ---------------------------------------------------------------- build in a container
if [ -z "${SIMPLY_DVB_IN_DOCKER:-}" ] && [ "${BUILD_IN_DOCKER:-1}" != 0 ]; then
have docker || { echo "Docker not found. Install it or run with BUILD_IN_DOCKER=0." >&2; exit 1; }
IMAGE="${BUILDER_IMAGE:-simply-dvb-builder:1}"
echo "==> builder image $IMAGE"
# shellcheck disable=SC2086
docker build ${DOCKER_BUILD_ARGS:-} -t "$IMAGE" -f scripts/docker/builder.Dockerfile scripts/docker
OUT="${OUT_DIR:-dist}"
mkdir -p .cache/cargo .cache/home "$OUT"
echo "==> building $ARCH in a container"
# Output files belong to the current user; crate and build caches stay in .cache/ and target/docker/.
# shellcheck disable=SC2086
exec docker run --rm \
--user "$(id -u):$(id -g)" \
-v "$PWD:/src" -w /src \
-e HOME=/src/.cache/home \
-e CARGO_HOME=/src/.cache/cargo \
-e CARGO_TARGET_DIR=/src/target/docker \
-e ZIG_GLOBAL_CACHE_DIR=/src/.cache/home/zig \
-e BUILD_METHOD="${BUILD_METHOD:-zigbuild}" \
-e GLIBC="${GLIBC:-2.31}" \
-e OUT_DIR="$OUT" \
-e HTTP_PROXY -e HTTPS_PROXY -e NO_PROXY -e http_proxy -e https_proxy -e no_proxy \
${DOCKER_ARGS:-} \
"$IMAGE" scripts/build-deb.sh "$ARCH"
fi
METHOD="${BUILD_METHOD:-auto}"
GLIBC="${GLIBC:-2.31}"
OUT_DIR="${OUT_DIR:-dist}"
VERSION=$(grep -m1 '^version' Cargo.toml | cut -d'"' -f2)
host_arch() {
case "$(uname -m)" in
x86_64) echo amd64 ;;
aarch64|arm64) echo arm64 ;;
armv7l|armv6l) echo armhf ;;
*) uname -m ;;
esac
}
if [ "$METHOD" = auto ]; then
if have cargo-zigbuild && (have zig || python3 -c 'import ziglang' 2>/dev/null); then METHOD=zigbuild
elif [ "$(host_arch)" = "$DEB_ARCH" ]; then METHOD=native
elif have cross; then METHOD=cross
elif have "${GCC_PREFIX}-gcc"; then METHOD=gcc
else
echo "No cross-compilation tools for $DEB_ARCH. Install one of:" >&2
echo " cargo install cargo-zigbuild && pip install ziglang (recommended)" >&2
echo " cargo install cross (requires Docker)" >&2
echo " apt install gcc-${GCC_PREFIX} (cross-gcc)" >&2
exit 1
fi
fi
echo "==> simply-dvb $VERSION · $DEB_ARCH ($TARGET) · method: $METHOD"
have cargo-deb || cargo install cargo-deb --locked
if [ -z "${SIMPLY_DVB_IN_DOCKER:-}" ] && [ "$METHOD" != native ] && [ "$METHOD" != cross ] && have rustup; then
rustup target add "$TARGET" >/dev/null
fi
case "$METHOD" in
native)
cargo build --release --locked --target "$TARGET"
;;
zigbuild)
cargo zigbuild --release --locked --target "${TARGET}.${GLIBC}"
;;
cross)
cross build --release --locked --target "$TARGET"
;;
gcc)
upper=$(echo "$TARGET" | tr 'a-z-' 'A-Z_')
export "CARGO_TARGET_${upper}_LINKER=${GCC_PREFIX}-gcc"
export "CC_${TARGET//-/_}=${GCC_PREFIX}-gcc"
export "AR_${TARGET//-/_}=${GCC_PREFIX}-ar"
cargo build --release --locked --target "$TARGET"
;;
*) echo "Unknown method: $METHOD" >&2; exit 2 ;;
esac
TARGET_DIR="${CARGO_TARGET_DIR:-target}"
BIN="$TARGET_DIR/$TARGET/release/simply-dvb"
[ -x "$BIN" ] || { echo "Missing file $BIN" >&2; exit 1; }
# cargo-deb: the binary is already built; target/release/* paths are mapped to target/<triple>/release/*
DEB=$(cargo deb --no-build --no-strip --target "$TARGET" 2>&1 | tail -n1)
mkdir -p "$OUT_DIR"
cp "$DEB" "$OUT_DIR/"
echo "==> $(ls -1 "$OUT_DIR"/simply-dvb_*_"$DEB_ARCH".deb)"
dpkg-deb -f "$OUT_DIR/$(basename "$DEB")" Package Version Architecture Depends 2>/dev/null || true
+17
View File
@@ -0,0 +1,17 @@
# Builder image for simply-dvb .deb packages (amd64, arm64, armhf) – used by scripts/build-deb.sh.
# Contains: Rust + targets, zig (cross-compilation with a fixed glibc baseline), cargo-zigbuild, cargo-deb.
FROM rust:1-bookworm
RUN apt-get update \
&& apt-get install -y --no-install-recommends python3-pip dpkg-dev \
&& rm -rf /var/lib/apt/lists/* \
&& pip3 install --no-cache-dir --break-system-packages ziglang \
&& printf '#!/bin/sh\nexec python3 -m ziglang "$@"\n' > /usr/local/bin/zig \
&& chmod 755 /usr/local/bin/zig \
&& rustup target add x86_64-unknown-linux-gnu aarch64-unknown-linux-gnu armv7-unknown-linux-gnueabihf \
&& cargo install --locked cargo-deb cargo-zigbuild \
&& rm -rf /usr/local/cargo/registry /usr/local/cargo/git \
&& chmod -R a+rX /usr/local/cargo /usr/local/rustup
ENV SIMPLY_DVB_IN_DOCKER=1
WORKDIR /src
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env node
// Language pack helper (langs/<locale>.json).
// node scripts/i18n-missing.js pl_PL – keys from en_US.json missing in langs/pl_PL.json
// node scripts/i18n-missing.js --sources – UI texts found in web/ that are not in en_US.json
// node scripts/i18n-missing.js --new de_DE "Deutsch" "German"
// – creates langs/de_DE.json with all keys (empty values)
// Empty values fall back to English at runtime, so a pack can be translated incrementally.
'use strict';
const fs = require('fs');
const path = require('path');
const root = path.join(__dirname, '..');
const langsDir = path.join(root, 'langs');
const load = (code) => JSON.parse(fs.readFileSync(path.join(langsDir, code + '.json'), 'utf8'));
const en = load('en_US');
const arg = process.argv[2] || '--sources';
if (arg === '--new') {
const [code, nativeName, name] = process.argv.slice(3);
if (!code || !/^[a-z]{2,3}_[A-Z]{2}$/.test(code)) { console.error('usage: --new xx_YY "Native name" "English name"'); process.exit(2); }
const file = path.join(langsDir, code + '.json');
if (fs.existsSync(file)) { console.error(`${file} already exists`); process.exit(1); }
const tr = {};
for (const k of Object.keys(en.translations)) tr[k] = '';
const pack = { meta: { locale: code, name: name || code, native_name: nativeName || name || code, direction: 'ltr' }, translations: tr, patterns: [] };
fs.writeFileSync(file, JSON.stringify(pack, null, 2) + '\n');
console.error(`created ${file} (${Object.keys(tr).length} keys); see langs/pl_PL.json for pattern examples`);
process.exit(0);
}
let missing;
if (arg === '--sources') {
// Heuristic: human-readable fragments of string literals / HTML text in the panel sources.
const files = fs.readdirSync(path.join(root, 'web', 'js')).filter((f) => /\.js$/.test(f) && !/^10-/.test(f))
.map((f) => path.join(root, 'web', 'js', f)).concat([path.join(root, 'web', 'index.html')]);
const src = files.map((f) => fs.readFileSync(f, 'utf8')).join('\n');
const found = new Set();
for (const m of src.matchAll(/'((?:[^'\\\n]|\\.)*)'|>([^<>{}\n]+)</g)) {
for (const part of (m[1] || m[2] || '').replace(/<[^>]*>/g, '\n').split('\n')) {
const t = part.replace(/\\'/g, "'").trim();
if (/[A-Za-z]{3,}.*\s.*[A-Za-z]/.test(t) && !/[{}=;$]|^[\w-]+(\s[\w-]+)*=|https?:|\/api\//.test(t)) found.add(t);
}
}
missing = [...found].filter((k) => !(k in en.translations));
} else {
const pack = load(arg);
missing = Object.keys(en.translations).filter((k) => !pack.translations[k]);
}
missing.forEach((k) => console.log(k));
console.error(`${arg}: missing entries: ${missing.length}`);
+518
View File
@@ -0,0 +1,518 @@
#!/usr/bin/env python3
"""Copy the channel list layout from tvheadend to simply-dvb.
Reads tvheadend channels (number, name, enabled, tags) either from a running tvheadend
(HTTP API) or from its configuration directory, matches them with simply-dvb channels and
applies numbers – optionally also names, groups (from tags) and the enabled state.
Matching runs in passes, most reliable first (a weaker match never takes a channel that a
stronger one would get):
1. service by network ids: ONID + TSID + SID (works even if the transmitter frequency differs),
2. service: SID on the same frequency (±1 MHz),
3. exact channel/service name (case, diacritics, spaces, "HD"/"SD" ignored),
4. loose name without quality/test/prefix words ("Zet" = "Radio ZET", "PR1" = "PR1 emisja testowa"),
5. similar name (typos, spacing; --fuzzy threshold, numbers must agree: "PR1" never "PR2"),
6. SID alone when it is unique.
tvheadend duplicates (two tvh channels for one service) are listed separately and skipped.
Nothing is changed without --apply (dry run prints the plan).
Examples:
# tvheadend still running (stop it later, or run simply-dvb's stream port elsewhere)
scripts/import-tvheadend.py --tvh http://192.168.1.10:9981 --tvh-user admin \\
--url http://192.168.1.10:9980 --user admin
# tvheadend already stopped: read its configuration directory
sudo scripts/import-tvheadend.py --tvh-config /var/lib/tvheadend --url http://localhost:9980 --user admin
# apply, including names, groups and enabled/disabled state; disable channels tvheadend did not have
scripts/import-tvheadend.py --tvh-config ~/tvh-backup --user admin --names --groups --enabled \\
--unmatched disable --apply
Passwords: --tvh-pass / --password, the TVH_PASSWORD / SIMPLY_DVB_PASSWORD environment
variables, or an interactive prompt. Only the Python 3 standard library is needed.
"""
import argparse
import getpass
import gzip
import http.cookiejar
import json
import os
import re
import sys
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
import zlib
# ---------------------------------------------------------------- helpers
def norm_name(s):
"""Same normalization as simply-dvb's XMLTV matching: "TVP 1 HD" == "tvp1"."""
s = unicodedata.normalize("NFKD", (s or "").lower().replace("ł", "l"))
s = "".join(c for c in s if c.isalnum() and not unicodedata.combining(c))
for suf in ("uhd", "fhd", "hd", "sd", "pl"):
if len(s) > len(suf) + 1 and s.endswith(suf):
s = s[: -len(suf)]
break
return s
def to_number(v):
try:
n = float(v)
except (TypeError, ValueError):
return 0
return int(round(n)) if n > 0 else 0
def mhz(hz):
try:
return round(float(hz) / 1e6)
except (TypeError, ValueError):
return None
def die(msg):
print("error: " + msg, file=sys.stderr)
sys.exit(1)
# ---------------------------------------------------------------- tvheadend sources
class Tvh:
"""tvheadend data: channels [{name, number, enabled, tags:[names], services:[(sid, mhz, name)]}]."""
def __init__(self):
self.channels = []
def tvh_from_api(base, user, password):
base = base.rstrip("/")
handlers = []
if user:
mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, base, user, password)
# tvheadend uses digest or basic auth depending on its configuration
handlers += [urllib.request.HTTPDigestAuthHandler(mgr), urllib.request.HTTPBasicAuthHandler(mgr)]
opener = urllib.request.build_opener(*handlers)
def grid(path):
url = base + path + ("&" if "?" in path else "?") + "start=0&limit=999999"
try:
with opener.open(url, timeout=30) as r:
return json.load(r).get("entries", [])
except urllib.error.HTTPError as e:
if e.code in (401, 403):
die(f"tvheadend refused {path} (HTTP {e.code}) – check --tvh-user/--tvh-pass and the user's admin rights")
die(f"tvheadend {path}: HTTP {e.code}")
except urllib.error.URLError as e:
die(f"cannot reach tvheadend at {base}: {e.reason}")
tags = {t["uuid"]: t.get("name", "") for t in grid("/api/channeltag/grid")}
muxes = {m["uuid"]: m for m in grid("/api/mpegts/mux/grid")}
services = {}
for s in grid("/api/mpegts/service/grid"):
m = muxes.get(s.get("multiplex_uuid"), {})
services[s["uuid"]] = (s.get("sid"), mhz(m.get("frequency")), s.get("svcname", ""), m.get("onid"), m.get("tsid"))
t = Tvh()
for c in grid("/api/channel/grid"):
t.channels.append({
"name": c.get("name", ""),
"number": to_number(c.get("number")),
"enabled": bool(c.get("enabled", True)),
"autoname": bool(c.get("autoname", False)),
"tags": [tags[x] for x in c.get("tags", []) if tags.get(x)],
"services": [services[x] for x in c.get("services", []) if x in services],
})
return t
def read_tvh_file(path):
"""tvheadend config files are JSON, optionally compressed ("\\xff\\xffGZIP0x" header)."""
with open(path, "rb") as f:
data = f.read()
if data.startswith(b"\xff\xffGZIP"):
body = data[12:]
try:
data = gzip.decompress(body)
except OSError:
data = zlib.decompress(body)
try:
return json.loads(data.decode("utf-8"))
except ValueError:
return None
def tvh_from_config(root):
root = os.path.expanduser(root)
if not os.path.isdir(os.path.join(root, "channel", "config")):
die(f"{root}/channel/config not found – point --tvh-config to tvheadend's configuration directory "
"(usually /var/lib/tvheadend or ~hts/.hts/tvheadend)")
tags = {}
tag_dir = os.path.join(root, "channel", "tag")
if os.path.isdir(tag_dir):
for u in os.listdir(tag_dir):
j = read_tvh_file(os.path.join(tag_dir, u))
if j:
tags[u] = j.get("name", "")
services = {}
nets = os.path.join(root, "input", "dvb", "networks")
if os.path.isdir(nets):
for net in os.listdir(nets):
mdir = os.path.join(nets, net, "muxes")
if not os.path.isdir(mdir):
continue
for mux in os.listdir(mdir):
mcfg = read_tvh_file(os.path.join(mdir, mux, "config")) or {}
freq = mhz(mcfg.get("frequency"))
onid, tsid = mcfg.get("onid"), mcfg.get("tsid")
sdir = os.path.join(mdir, mux, "services")
if not os.path.isdir(sdir):
continue
for svc in os.listdir(sdir):
j = read_tvh_file(os.path.join(sdir, svc)) or {}
services[svc] = (j.get("sid"), freq, j.get("svcname", ""), onid, tsid)
t = Tvh()
cdir = os.path.join(root, "channel", "config")
for u in os.listdir(cdir):
c = read_tvh_file(os.path.join(cdir, u))
if not c:
continue
t.channels.append({
"name": c.get("name", ""),
"number": to_number(c.get("number")),
"enabled": bool(c.get("enabled", True)),
"autoname": bool(c.get("autoname", False)),
"tags": [tags[x] for x in c.get("tags", []) if tags.get(x)],
"services": [services[x] for x in c.get("services", []) if x in services],
})
return t
# ---------------------------------------------------------------- simply-dvb API
class SimplyDvb:
def __init__(self, base, user, password):
self.base = base.rstrip("/")
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
self.call("POST", "/api/login", {"username": user, "password": password})
def call(self, method, path, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(self.base + path, data=data, method=method)
req.add_header("X-Requested-With", "simply-dvb")
if data is not None:
req.add_header("Content-Type", "application/json")
try:
with self.opener.open(req, timeout=60) as r:
txt = r.read().decode()
return json.loads(txt) if txt else None
except urllib.error.HTTPError as e:
msg = e.read().decode(errors="replace")
try:
msg = json.loads(msg).get("error", msg)
except ValueError:
pass
die(f"simply-dvb {method} {path}: HTTP {e.code} {msg}")
except urllib.error.URLError as e:
die(f"cannot reach simply-dvb at {self.base}: {e.reason}")
# ---------------------------------------------------------------- matching
# words that do not identify a channel (quality, test transmissions, prefixes)
NOISE = re.compile(
r"\b(u?hd|fhd|sd|4k|pl|polska|poland|tv|telewizja|radio|polskie|kanal|channel|"
r"emisja|testowa|test|em|testowy|eksperymentalna|plus)\b"
)
def loose_name(s):
"""Name reduced to its identifying part: "Radio ZET em.test." -> "zet", "TVN 24 HD" -> "tvn24"."""
s = unicodedata.normalize("NFKD", (s or "").lower().replace("ł", "l"))
s = "".join(c for c in s if not unicodedata.combining(c))
s = s.replace("+", " plus ").replace("&", " and ")
s = re.sub(r"[^a-z0-9]+", " ", s)
s = NOISE.sub(" ", s)
s = re.sub(r"\s+", "", s)
return s or norm_name(s)
def digits(s):
"""Numbers in a name must agree: "PR1" never matches "PR2", "TVP3" never "TVP".."""
return re.findall(r"\d+", unicodedata.normalize("NFKD", s or ""))
def similar(a, b):
from difflib import SequenceMatcher
la, lb = loose_name(a), loose_name(b)
if not la or not lb or digits(a) != digits(b):
return 0.0
if la == lb:
return 1.0
return SequenceMatcher(None, la, lb).ratio()
def build_plan(tvh, channels, services, muxes, fuzzy=0.86):
"""Matches tvheadend channels with simply-dvb channels in passes, most reliable first,
so a weaker match can never take a channel that a stronger one would get."""
mux = {m["id"]: m for m in muxes}
chans = [c for c in channels]
used = {} # simply-dvb channel id -> tvheadend channel
result = {} # id(tvh channel) -> (simply-dvb channel, how)
def svc_of(c):
s = c.get("service") or {}
m = mux.get(s.get("mux_id"), {})
return s, m
def assign(t, c, how):
used[c["id"]] = t
result[id(t)] = (c, how)
order = sorted(tvh.channels, key=lambda x: (x["number"] == 0, x["number"], x["name"].lower()))
def run(match, how):
for t in order:
if id(t) in result:
continue
c = match(t)
if c is not None and c["id"] not in used:
assign(t, c, how)
# 1. network identity: ONID + TSID + SID (independent of the transmitter frequency)
def by_triplet(t):
for sid, _, _, onid, tsid in t["services"]:
if sid is None or onid is None or tsid is None:
continue
for c in chans:
s, m = svc_of(c)
if c["id"] not in used and s.get("sid") == sid and m.get("onid") == onid and m.get("ts_id") == tsid:
return c
return None
# 2. SID on the same frequency (±1 MHz)
def by_sid_freq(t):
for sid, f, *_ in t["services"]:
for c in chans:
s, m = svc_of(c)
cf = mhz(m.get("frequency_hz"))
if c["id"] not in used and s.get("sid") == sid and f is not None and cf is not None and abs(cf - f) <= 1:
return c
return None
# 3. exact (normalized) channel or service name
def by_name(t):
keys = {norm_name(t["name"])} | {norm_name(x[2]) for x in t["services"] if x[2]}
for c in chans:
if c["id"] in used:
continue
s, _ = svc_of(c)
if norm_name(c["name"]) in keys or (s.get("name") and norm_name(s["name"]) in keys):
return c
return None
# 4. loose name: without quality/test/prefix words ("Zet" == "Radio ZET", "PR1" == "PR1 emisja testowa")
def by_loose(t):
keys = {loose_name(t["name"])} | {loose_name(x[2]) for x in t["services"] if x[2]}
keys.discard("")
hits = [c for c in chans if c["id"] not in used and
(loose_name(c["name"]) in keys or loose_name((c.get("service") or {}).get("name", "")) in keys)
and digits(c["name"]) == digits(t["name"])]
return hits[0] if len(hits) == 1 else None
# 5. similar name (typos, spacing) – only a clear single best candidate
def by_similar(t):
if fuzzy >= 1:
return None
best, best_score, second = None, 0.0, 0.0
for c in chans:
if c["id"] in used:
continue
sc = max(similar(t["name"], c["name"]), similar(t["name"], (c.get("service") or {}).get("name", "")))
if sc > best_score:
best, best_score, second = c, sc, best_score
elif sc > second:
second = sc
return best if best_score >= fuzzy and best_score - second >= 0.05 else None
# 6. SID alone when it is unique in simply-dvb (frequency changed, no NIT ids in tvheadend)
def by_sid(t):
for sid, *_ in t["services"]:
hits = [c for c in chans if (c.get("service") or {}).get("sid") == sid]
if len(hits) == 1 and hits[0]["id"] not in used and similar(t["name"], hits[0]["name"]) >= 0.5:
return hits[0]
return None
run(by_triplet, "service (network ids)")
run(by_sid_freq, "service (SID + frequency)")
run(by_name, "name")
run(by_loose, "similar name")
run(by_similar, "similar name")
run(by_sid, "service (SID)")
# services without a channel (can be created with --create)
free = [s for s in services if s.get("channel_id") is None]
plan, missing, dups = [], [], []
for t in order:
if id(t) in result:
c, how = result[id(t)]
plan.append((t, c, how))
continue
# a tvheadend duplicate: same service or name as a channel already taken by another tvh channel
twin = None
for c in chans:
s, m = svc_of(c)
same_svc = any(s.get("sid") == sid and (f is None or abs((mhz(m.get("frequency_hz")) or 0) - f) <= 1)
for sid, f, *_ in t["services"])
if c["id"] in used and (same_svc or similar(t["name"], c["name"]) >= 0.95):
twin = c
break
if twin is not None:
dups.append((t, twin, used[twin["id"]]))
continue
create = None
for sid, f, *_ in t["services"]:
for sv in free:
if sv.get("sid") == sid and abs((mhz(mux.get(sv.get("mux_id"), {}).get("frequency_hz")) or 0) - (f or 0)) <= 1:
create = sv
break
if create:
break
if not create:
for sv in free:
if similar(t["name"], sv.get("name", "")) >= fuzzy:
create = sv
break
if create:
free.remove(create)
plan.append((t, None, "create", create))
else:
missing.append(t)
return plan, missing, dups, set(used)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
src = ap.add_mutually_exclusive_group(required=True)
src.add_argument("--tvh", metavar="URL", help="tvheadend address, e.g. http://192.168.1.10:9981")
src.add_argument("--tvh-config", metavar="DIR", help="tvheadend configuration directory (e.g. /var/lib/tvheadend)")
ap.add_argument("--tvh-user", help="tvheadend user (admin rights needed for the API)")
ap.add_argument("--tvh-pass", help="tvheadend password (or TVH_PASSWORD)")
ap.add_argument("--url", default="http://127.0.0.1:9980", help="simply-dvb panel address (default %(default)s)")
ap.add_argument("--user", default="admin", help="simply-dvb administrator (default %(default)s)")
ap.add_argument("--password", help="simply-dvb password (or SIMPLY_DVB_PASSWORD)")
ap.add_argument("--names", nargs="?", const="custom", choices=["custom", "all"],
help="copy channel names: 'custom' (default for --names) only names set by hand in "
"tvheadend (autoname off), 'all' every name – note tvheadend names may be stale "
"when a broadcaster renamed a channel")
ap.add_argument("--reset-names", action="store_true",
help="set every simply-dvb channel name back to its current broadcast (service) name")
ap.add_argument("--fuzzy", type=float, default=0.86,
help="similarity threshold 0–1 for similar names (default %(default)s, 1 = exact names only)")
ap.add_argument("--groups", action="store_true", help="set the group from the first tvheadend tag")
ap.add_argument("--enabled", action="store_true", help="copy the enabled/disabled state")
ap.add_argument("--create", action="store_true",
help="create channels for tvheadend channels whose service exists in simply-dvb but has no channel")
ap.add_argument("--unmatched", choices=["keep", "after", "disable"], default="after",
help="simply-dvb channels tvheadend does not have: keep numbers, number them after the "
"imported ones (default), or disable them (also numbered after)")
ap.add_argument("--apply", action="store_true", help="make the changes (default: dry run)")
a = ap.parse_args()
if a.tvh:
tpass = a.tvh_pass or os.environ.get("TVH_PASSWORD")
if a.tvh_user and tpass is None:
tpass = getpass.getpass(f"tvheadend password for {a.tvh_user}: ")
tvh = tvh_from_api(a.tvh, a.tvh_user, tpass or "")
else:
tvh = tvh_from_config(a.tvh_config)
if not tvh.channels:
die("no channels found in tvheadend")
pw = a.password or os.environ.get("SIMPLY_DVB_PASSWORD") or getpass.getpass(f"simply-dvb password for {a.user}: ")
sd = SimplyDvb(a.url, a.user, pw)
channels = sd.call("GET", "/api/channels")
services = sd.call("GET", "/api/services")
muxes = sd.call("GET", "/api/muxes")
plan, missing, dups, used = build_plan(tvh, channels, services, muxes, a.fuzzy)
print(f"tvheadend: {len(tvh.channels)} channels · simply-dvb: {len(channels)} channels, {len(services)} services\n")
print(f"{'tvh no.':>7} {'tvheadend name':<28} {'→':1} {'simply-dvb':<28} match")
print("-" * 82)
for item in plan:
t, c, how = item[0], item[1], item[2]
target = c["name"] if c else f"(new) {item[3]['name']}"
note = ""
if c and how.startswith("service") and similar(t["name"], c["name"]) < 0.6:
note = " (renamed by the broadcaster?)"
print(f"{t['number'] or '-':>7} {t['name'][:28]:<28} → {target[:28]:<28} {how}{note}")
if dups:
print("\nDuplicates in tvheadend (same service/name as a channel above – skipped):")
for t, c, first in dups:
print(f"{t['number'] or '-':>7} {t['name'][:28]:<28} = #{first['number']} {first['name']} → {c['name']}")
if missing:
print("\nNot found in simply-dvb (not received by the scan, or a different service):")
for t in missing:
print(f"{t['number'] or '-':>7} {t['name'][:28]:<28} ✗")
rest = [c for c in channels if c["id"] not in used]
if rest:
print(f"\nsimply-dvb channels without a tvheadend counterpart ({a.unmatched}): " +
", ".join(c["name"] for c in sorted(rest, key=lambda c: c["number"])))
if not a.apply:
print("\nDry run – nothing changed. Add --apply to make the changes.")
return
# imported channels keep tvheadend numbers; channels without a number go after the highest one
top = max([t["number"] for t, *_ in plan] + [0])
changed = created = 0
for item in plan:
t, c = item[0], item[1]
number = t["number"]
if not number:
top += 1
number = top
if c is None:
r = sd.call("POST", "/api/channels", {"service_ids": [item[3]["id"]]})
ids = (r or {}).get("ids") or []
if not ids:
print(f" could not create a channel for {t['name']}")
continue
c = {"id": ids[0], "service": item[3]}
created += 1
body = {"number": number}
if a.names and t["name"] and not t["name"].startswith("{") and (a.names == "all" or not t.get("autoname")):
body["name"] = t["name"]
elif a.reset_names and c.get("service", {}).get("name"):
body["name"] = c["service"]["name"]
if a.groups and t["tags"]:
body["grp"] = t["tags"][0]
if a.enabled:
body["enabled"] = t["enabled"]
sd.call("PUT", f"/api/channels/{c['id']}", body)
changed += 1
if a.unmatched != "keep":
for c in sorted(rest, key=lambda c: c["number"]):
top += 1
body = {"number": top}
if a.reset_names and (c.get("service") or {}).get("name"):
body["name"] = c["service"]["name"]
if a.unmatched == "disable":
body["enabled"] = False
sd.call("PUT", f"/api/channels/{c['id']}", body)
print(f"\nDone: {changed} channels updated ({created} created), {len(dups)} duplicates skipped, {len(missing)} not found"
+ (f", {len(rest)} others {'disabled and ' if a.unmatched == 'disable' else ''}numbered from {top - len(rest) + 1}"
if rest and a.unmatched != "keep" else "") + ".")
if __name__ == "__main__":
main()
+230
View File
@@ -0,0 +1,230 @@
//! Access-list entries: networks (`10.0.0.0/8`), single addresses (`1.2.3.4`) and host
//! names (`home.example.ddns.net`) for dynamic IPs. Host names are resolved in the
//! background every minute; a request is allowed when its address matches one of the
//! currently resolved addresses.
use ipnet::IpNet;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::{OnceLock, RwLock};
use std::time::Duration;
#[derive(Debug, Clone, PartialEq)]
pub enum AclEntry {
Net(IpNet),
Host(String),
}
impl AclEntry {
pub fn parse(s: &str) -> Result<AclEntry, String> {
let s = s.trim();
if let Ok(n) = s.parse::<IpNet>() {
return Ok(AclEntry::Net(n));
}
if let Ok(a) = s.parse::<IpAddr>() {
return Ok(AclEntry::Net(IpNet::from(a)));
}
let h = s.trim_end_matches('.').to_ascii_lowercase();
let valid = !h.is_empty()
&& h.len() <= 253
&& h.contains('.')
&& h.split('.').all(|l| {
!l.is_empty()
&& l.len() <= 63
&& !l.starts_with('-')
&& !l.ends_with('-')
&& l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
})
&& !h
.split('.')
.next_back()
.unwrap_or("")
.chars()
.all(|c| c.is_ascii_digit());
if valid {
Ok(AclEntry::Host(h))
} else {
Err(format!("invalid address/network/host name: {s}"))
}
}
pub fn matches(&self, ip: IpAddr) -> bool {
let ip = normalize(ip);
match self {
AclEntry::Net(n) => n.contains(&ip),
AclEntry::Host(h) => cache()
.read()
.unwrap()
.get(h)
.is_some_and(|ips| ips.contains(&ip)),
}
}
}
impl std::fmt::Display for AclEntry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AclEntry::Net(n) => write!(f, "{n}"),
AclEntry::Host(h) => write!(f, "{h}"),
}
}
}
impl Serialize for AclEntry {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for AclEntry {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
AclEntry::parse(&s).map_err(serde::de::Error::custom)
}
}
fn normalize(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V6(v6) => v6
.to_ipv4_mapped()
.map(IpAddr::V4)
.unwrap_or(IpAddr::V6(v6)),
v4 => v4,
}
}
/// Parses a list separated by commas, spaces or new lines.
pub fn parse_list(s: &str) -> Result<Vec<AclEntry>, String> {
s.split(|c: char| c == ',' || c.is_whitespace())
.filter(|x| !x.is_empty())
.map(AclEntry::parse)
.collect()
}
pub fn allows(list: &[AclEntry], ip: IpAddr) -> bool {
list.iter().any(|e| e.matches(ip))
}
/// Resolved host names (shared by all lists).
fn cache() -> &'static RwLock<HashMap<String, Vec<IpAddr>>> {
static C: OnceLock<RwLock<HashMap<String, Vec<IpAddr>>>> = OnceLock::new();
C.get_or_init(|| RwLock::new(HashMap::new()))
}
/// Currently resolved addresses of a host (for the panel).
pub fn resolved(host: &str) -> Option<Vec<IpAddr>> {
cache().read().unwrap().get(host).cloned()
}
/// Resolves the given host names and updates the cache, logging address changes.
pub async fn refresh<I: IntoIterator<Item = String>>(hosts: I) {
let mut wanted: Vec<String> = hosts.into_iter().collect();
wanted.sort();
wanted.dedup();
for h in wanted {
let res = tokio::time::timeout(
Duration::from_secs(5),
tokio::net::lookup_host(format!("{h}:0")),
)
.await;
match res {
Ok(Ok(addrs)) => {
let mut ips: Vec<IpAddr> = addrs.map(|a| normalize(a.ip())).collect();
ips.sort();
ips.dedup();
let old = cache().write().unwrap().insert(h.clone(), ips.clone());
if old.as_ref() != Some(&ips) {
tracing::info!(
target: "access",
"ACL host {h} resolves to {}",
ips.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ")
);
}
}
// keep the last known addresses when a lookup fails temporarily
Ok(Err(e)) => tracing::warn!(target: "access", "ACL host {h}: lookup failed ({e})"),
Err(_) => tracing::warn!(target: "access", "ACL host {h}: lookup timed out"),
}
}
}
/// Host names used anywhere in the access rules (settings and tokens).
pub async fn all_hosts(state: &crate::app::State) -> Vec<String> {
let s = state.settings();
let mut out: Vec<String> = s
.stream_open_cidrs
.iter()
.chain(s.panel_allow_cidrs.iter())
.filter_map(|e| match e {
AclEntry::Host(h) => Some(h.clone()),
_ => None,
})
.collect();
for t in state.db.tokens().await.unwrap_or_default() {
for e in parse_list(&t.allow_cidrs).unwrap_or_default() {
if let AclEntry::Host(h) = e {
out.push(h);
}
}
}
out
}
/// Re-resolves all ACL host names every minute (dynamic IPs / DDNS).
pub async fn resolver_task(state: crate::app::State) {
loop {
let hosts = all_hosts(&state).await;
if !hosts.is_empty() {
refresh(hosts).await;
}
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(60)) => {}
_ = state.acl_refresh.notified() => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_entries() {
assert_eq!(
AclEntry::parse("10.0.0.0/8").unwrap(),
AclEntry::Net("10.0.0.0/8".parse().unwrap())
);
assert_eq!(
AclEntry::parse("1.2.3.4").unwrap(),
AclEntry::Net("1.2.3.4/32".parse().unwrap())
);
assert_eq!(
AclEntry::parse("Home.Example.DDNS.net.").unwrap(),
AclEntry::Host("home.example.ddns.net".into())
);
assert!(AclEntry::parse("bad").is_err());
assert!(AclEntry::parse("1.2.3.999").is_err());
assert!(AclEntry::parse("a..b").is_err());
let l = parse_list("192.168.0.0/16, my.dyndns.org\n2001:db8::/32").unwrap();
assert_eq!(l.len(), 3);
// JSON form stays a plain string list (compatible with stored settings)
assert_eq!(
serde_json::to_string(&l).unwrap(),
r#"["192.168.0.0/16","my.dyndns.org","2001:db8::/32"]"#
);
}
#[tokio::test]
async fn host_matching_uses_resolved_addresses() {
let e = AclEntry::parse("localhost.localdomain.test").unwrap();
assert!(!e.matches("127.0.0.1".parse().unwrap()));
cache().write().unwrap().insert(
"localhost.localdomain.test".into(),
vec!["127.0.0.1".parse().unwrap()],
);
assert!(e.matches("127.0.0.1".parse().unwrap()));
assert!(e.matches("::ffff:127.0.0.1".parse().unwrap()));
assert!(!e.matches("127.0.0.2".parse().unwrap()));
}
}
+238
View File
@@ -0,0 +1,238 @@
//! Application state shared by the web server and background tasks.
use crate::clients::Clients;
use crate::db::Db;
use crate::dvb::{self, AdapterInfo, DeliverySystem};
use crate::hls::HlsManager;
use crate::scanjob::ScanState;
use crate::settings::Settings;
use crate::ts::si::EpgItem;
use crate::tuner::TunerManager;
use anyhow::Result;
use std::collections::HashMap;
use std::net::IpAddr;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, Notify};
pub type State = Arc<AppState>;
#[derive(Debug, Clone)]
pub struct Options {
pub data_dir: PathBuf,
pub dev_root: String,
pub virtual_dirs: Vec<String>,
/// Stream port (tvheadend-compatible), if enabled.
pub stream_port: Option<u16>,
/// HTSP port, if enabled.
pub htsp_port: Option<u16>,
}
#[derive(Default, Clone, serde::Serialize)]
pub struct EpgStatus {
pub last_grab: Option<i64>,
pub grabbing_mux: Option<i64>,
pub last_xmltv: Option<i64>,
pub xmltv_result: String,
pub ota_events_written: u64,
}
pub struct AppState {
pub db: Db,
pub settings: RwLock<Settings>,
pub opts: Options,
pub tuners: Arc<TunerManager>,
pub hls: HlsManager,
pub clients: Arc<Clients>,
pub scan: ScanState,
pub started: Instant,
pub http: reqwest::Client,
pub login_failures: Mutex<HashMap<IpAddr, (u32, Instant)>>,
pub recordings_running: Mutex<HashMap<i64, Arc<AtomicBool>>>,
pub epg_status: Mutex<EpgStatus>,
pub epg_wakeup: Notify,
pub xmltv_wakeup: Notify,
pub rec_wakeup: Notify,
pub shutting_down: AtomicBool,
pub stats: crate::stats::Stats,
/// The separate stream port is bound (it may wait for tvheadend to release it).
pub stream_port_active: AtomicBool,
pub htsp_port_active: AtomicBool,
pub icon_job: Mutex<crate::icons::IconJob>,
/// `ffmpeg -version` first line, or None when ffmpeg is not available.
pub ffmpeg: Mutex<Option<String>>,
/// Wakes the ACL host-name resolver (settings/tokens changed).
pub acl_refresh: Notify,
/// A stream detection (probe) of channels without known streams is running.
pub probing: AtomicBool,
}
impl AppState {
pub async fn new(
db: Db,
opts: Options,
) -> Result<(State, mpsc::UnboundedReceiver<(i64, Vec<EpgItem>)>)> {
let mut settings: Settings = match db.get_setting("config").await? {
Some(s) => serde_json::from_str(&s).unwrap_or_default(),
None => Settings::default(),
};
// default server name from before the project was renamed
if settings.server_name == "simple-dvbt" {
settings.server_name = "simply-dvb".into();
}
let (epg_tx, epg_rx) = mpsc::unbounded_channel();
let tuners = TunerManager::new(epg_tx);
let (pmt_tx, mut pmt_rx) = mpsc::unbounded_channel::<(i64, Vec<crate::ts::tables::Pmt>)>();
*tuners.pmt_tx.lock().unwrap() = Some(pmt_tx);
{
let db = db.clone();
tokio::spawn(async move {
while let Some((mux_id, pmts)) = pmt_rx.recv().await {
for p in pmts {
match db.update_service_pmt(mux_id, &p).await {
Ok(true) => tracing::info!(
"service {} on mux {mux_id}: streams updated from PMT ({})",
p.program,
p.streams
.iter()
.map(|s| s.kind.label())
.collect::<Vec<_>>()
.join(", ")
),
Ok(false) => {}
Err(e) => tracing::warn!("updating service streams: {e:#}"),
}
}
}
});
}
tuners
.epg_enabled
.store(settings.epg_ota_enabled, Ordering::Relaxed);
*tuners.linger.lock().unwrap() = Duration::from_secs(settings.tuner_linger_seconds as u64);
let http = reqwest::Client::builder()
.user_agent(concat!("simply-dvb/", env!("CARGO_PKG_VERSION")))
.timeout(Duration::from_secs(120))
.connect_timeout(Duration::from_secs(15))
.build()?;
let state = Arc::new(AppState {
db,
settings: RwLock::new(settings),
opts,
tuners,
hls: HlsManager::default(),
clients: Arc::new(Clients::default()),
scan: ScanState::default(),
started: Instant::now(),
http,
login_failures: Mutex::new(HashMap::new()),
recordings_running: Mutex::new(HashMap::new()),
epg_status: Mutex::new(EpgStatus::default()),
epg_wakeup: Notify::new(),
xmltv_wakeup: Notify::new(),
rec_wakeup: Notify::new(),
shutting_down: AtomicBool::new(false),
stats: crate::stats::Stats::default(),
stream_port_active: AtomicBool::new(false),
htsp_port_active: AtomicBool::new(false),
icon_job: Mutex::new(crate::icons::IconJob::default()),
ffmpeg: Mutex::new(None),
acl_refresh: Notify::new(),
probing: AtomicBool::new(false),
});
state.detect_ffmpeg().await;
state.refresh_adapters().await?;
Ok((state, epg_rx))
}
/// Checks whether the configured ffmpeg can be started (transcoding profiles need it).
pub async fn detect_ffmpeg(&self) {
let path = self.settings().ffmpeg_path;
let out = tokio::process::Command::new(&path)
.arg("-version")
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.await;
let v = match out {
Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
.lines()
.next()
.map(|l| l.chars().take(120).collect()),
_ => None,
};
match &v {
Some(v) => tracing::info!("ffmpeg: {v}"),
None => tracing::warn!(
"ffmpeg not found ({path}) – browser transcoding profiles (aac, h264) are unavailable"
),
}
*self.ffmpeg.lock().unwrap() = v;
}
pub fn has_ffmpeg(&self) -> bool {
self.ffmpeg.lock().unwrap().is_some()
}
pub fn settings(&self) -> Settings {
self.settings.read().unwrap().clone()
}
pub async fn save_settings(&self, s: Settings) -> Result<()> {
self.db
.set_setting("config", &serde_json::to_string(&s)?)
.await?;
self.tuners
.epg_enabled
.store(s.epg_ota_enabled, Ordering::Relaxed);
*self.tuners.linger.lock().unwrap() = Duration::from_secs(s.tuner_linger_seconds as u64);
let ffmpeg_changed = self.settings.read().unwrap().ffmpeg_path != s.ffmpeg_path;
*self.settings.write().unwrap() = s;
self.acl_refresh.notify_one();
if ffmpeg_changed {
self.detect_ffmpeg().await;
}
Ok(())
}
/// Discovers adapters (Linux DVB + virtual) and updates the tuner manager.
pub async fn refresh_adapters(&self) -> Result<Vec<AdapterInfo>> {
let dev_root = self.opts.dev_root.clone();
let mut found = tokio::task::spawn_blocking(move || dvb::discover(&dev_root)).await?;
for (i, dir) in self.opts.virtual_dirs.iter().enumerate() {
found.push(AdapterInfo {
id: format!("virtual{i}"),
name: format!("Virtual adapter ({dir})"),
kind: "virtual".into(),
path: dir.clone(),
delivery_systems: vec![
DeliverySystem::Dvbt,
DeliverySystem::Dvbt2,
DeliverySystem::Dvbc,
],
});
}
let mut list = Vec::new();
for a in &found {
let (en, prio) = self.db.adapter_config(&a.id).await?;
list.push((a.clone(), en, prio));
}
self.tuners.set_adapters(list);
Ok(found)
}
pub fn data_path(&self, name: &str) -> PathBuf {
self.opts.data_dir.join(name)
}
pub fn recordings_dir(&self) -> PathBuf {
let s = self.settings();
if s.recordings_dir.trim().is_empty() {
self.data_path("recordings")
} else {
PathBuf::from(s.recordings_dir.trim())
}
}
}
+276
View File
@@ -0,0 +1,276 @@
//! Panel authentication (sessions, argon2) and stream access control (ACL).
use crate::app::State;
use crate::db::{AccessToken, User};
use crate::settings::{ip_in, parse_cidrs};
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
use argon2::Argon2;
use axum::http::{header, HeaderMap};
use base64::Engine;
use sha2::{Digest, Sha256};
use std::net::{IpAddr, SocketAddr};
use std::time::{Duration, Instant};
pub const SESSION_COOKIE: &str = "sdvb_session";
pub fn random_token(bytes: usize) -> String {
let mut buf = vec![0u8; bytes];
getrandom::fill(&mut buf).expect("getrandom");
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf)
}
pub fn hash_password(pw: &str) -> anyhow::Result<String> {
let mut salt = [0u8; 16];
getrandom::fill(&mut salt).map_err(|e| anyhow::anyhow!("{e}"))?;
let salt = SaltString::encode_b64(&salt).map_err(|e| anyhow::anyhow!("{e}"))?;
Ok(Argon2::default()
.hash_password(pw.as_bytes(), &salt)
.map_err(|e| anyhow::anyhow!("{e}"))?
.to_string())
}
pub fn verify_password(pw: &str, hash: &str) -> bool {
match PasswordHash::new(hash) {
Ok(h) => Argon2::default().verify_password(pw.as_bytes(), &h).is_ok(),
Err(_) => false,
}
}
pub fn token_hash(token: &str) -> String {
let d = Sha256::digest(token.as_bytes());
d.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn constant_eq(a: &str, b: &str) -> bool {
use subtle::ConstantTimeEq;
a.len() == b.len() && bool::from(a.as_bytes().ct_eq(b.as_bytes()))
}
/// Client address, honouring trusted proxies.
pub fn client_ip(state: &State, peer: SocketAddr, headers: &HeaderMap) -> IpAddr {
let peer_ip = peer.ip();
let s = state.settings.read().unwrap();
if s.trusted_proxies.is_empty() || !ip_in(&s.trusted_proxies, peer_ip) {
return peer_ip;
}
if let Some(xff) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()) {
// last address outside the trusted proxies (from the right)
for part in xff.split(',').rev() {
if let Ok(ip) = part.trim().parse::<IpAddr>() {
if !ip_in(&s.trusted_proxies, ip) {
return ip;
}
}
}
}
if let Some(ip) = headers
.get("x-real-ip")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.trim().parse().ok())
{
return ip;
}
peer_ip
}
/// Server base URL (for links in M3U/XMLTV).
pub fn base_url(state: &State, peer: SocketAddr, headers: &HeaderMap) -> String {
let s = state.settings.read().unwrap();
if !s.public_url.is_empty() {
return s.public_url.clone();
}
let trusted = !s.trusted_proxies.is_empty() && ip_in(&s.trusted_proxies, peer.ip());
let proto = if trusted {
headers
.get("x-forwarded-proto")
.and_then(|v| v.to_str().ok())
.unwrap_or("http")
.to_string()
} else {
"http".to_string()
};
let host = trusted
.then(|| {
headers
.get("x-forwarded-host")
.and_then(|v| v.to_str().ok())
})
.flatten()
.or_else(|| headers.get(header::HOST).and_then(|v| v.to_str().ok()))
.unwrap_or("localhost")
.to_string();
let host: String = host
.chars()
.filter(|c| c.is_ascii_alphanumeric() || ".-:[]_".contains(*c))
.collect();
format!("{proto}://{host}")
}
pub fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
for v in headers.get_all(header::COOKIE) {
let Ok(s) = v.to_str() else { continue };
for part in s.split(';') {
if let Some((k, val)) = part.trim().split_once('=') {
if k == name {
return Some(val.to_string());
}
}
}
}
None
}
pub async fn session_user(state: &State, headers: &HeaderMap) -> Option<User> {
let token = cookie_value(headers, SESSION_COOKIE)?;
state
.db
.session_user(&token_hash(&token))
.await
.ok()
.flatten()
}
/// Login rate limit: 8 failures per 5 minutes per address.
pub fn login_allowed(state: &State, ip: IpAddr) -> bool {
let mut m = state.login_failures.lock().unwrap();
m.retain(|_, (_, t)| t.elapsed() < Duration::from_secs(300));
m.get(&ip).is_none_or(|(n, _)| *n < 8)
}
pub fn login_failed(state: &State, ip: IpAddr) {
let mut m = state.login_failures.lock().unwrap();
let e = m.entry(ip).or_insert((0, Instant::now()));
e.0 += 1;
e.1 = Instant::now();
}
/// Who obtained access to a stream.
#[derive(Debug, Clone)]
pub enum StreamAccess {
Network,
Session(User),
Token(AccessToken),
Share(i64),
}
impl StreamAccess {
pub fn who(&self) -> String {
match self {
StreamAccess::Network => "local network".into(),
StreamAccess::Session(u) => format!("user {}", u.username),
StreamAccess::Token(t) => format!("token {}", t.name),
StreamAccess::Share(_) => "public link".into(),
}
}
/// Parameters appended to links (token/share) so the client keeps access.
pub fn query(&self) -> String {
match self {
StreamAccess::Token(t) => format!("token={}", t.token),
_ => String::new(),
}
}
pub fn allows_channel(&self, channel_id: i64) -> bool {
match self {
StreamAccess::Share(c) => *c == channel_id,
_ => true,
}
}
}
#[derive(Debug, Default, serde::Deserialize, Clone)]
pub struct AuthQuery {
pub token: Option<String>,
pub share: Option<String>,
}
async fn check_token(state: &State, t: &str, ip: IpAddr) -> Option<AccessToken> {
let tok = state.db.token_by_value(t).await.ok().flatten()?;
let ok = tok.allow_cidrs.trim().is_empty()
|| parse_cidrs(&tok.allow_cidrs)
.map(|n| ip_in(&n, ip))
.unwrap_or(false);
if !ok {
return None;
}
let _ = state.db.touch_token(tok.id).await;
Some(tok)
}
/// Checks access to streams / M3U / EPG.
pub async fn stream_access(
state: &State,
ip: IpAddr,
headers: &HeaderMap,
q: &AuthQuery,
) -> Option<StreamAccess> {
if let Some(t) = q.token.as_deref().filter(|t| !t.is_empty()) {
return check_token(state, t, ip).await.map(StreamAccess::Token);
}
if let Some(s) = q.share.as_deref().filter(|s| !s.is_empty()) {
return match state.db.channel_by_share(s).await {
Ok(Some(c)) => Some(StreamAccess::Share(c.id)),
_ => None,
};
}
if ip_in(&state.settings.read().unwrap().stream_open_cidrs, ip) {
return Some(StreamAccess::Network);
}
if let Some(u) = session_user(state, headers).await {
return Some(StreamAccess::Session(u));
}
// HTTP Basic: password = access token or a panel user's login/password
if let Some(v) = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
{
if let Some(b) = v.strip_prefix("Basic ") {
if let Ok(dec) = base64::engine::general_purpose::STANDARD.decode(b.trim()) {
let cred = String::from_utf8_lossy(&dec).to_string();
if let Some((user, pw)) = cred.split_once(':') {
if let Some(t) = check_token(state, pw, ip).await {
return Some(StreamAccess::Token(t));
}
// like tvheadend: user login and password (e.g. Kodi, TVHGuide, IPTV apps)
if !login_allowed(state, ip) {
return None;
}
if let Ok(Some(u)) = state.db.user_by_name(user).await {
if verify_password(pw, &u.password_hash) {
return Some(StreamAccess::Session(u));
}
}
login_failed(state, ip);
}
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn password_roundtrip() {
let h = hash_password("secret-password").unwrap();
assert!(verify_password("secret-password", &h));
assert!(!verify_password("inne", &h));
assert!(!verify_password("x", "not-a-hash"));
assert_eq!(random_token(24).len(), 32);
assert!(constant_eq("abc", "abc"));
assert!(!constant_eq("abc", "abd"));
}
#[test]
fn cookies() {
let mut h = HeaderMap::new();
h.insert(
header::COOKIE,
"a=1; sdvb_session=xyz; b=2".parse().unwrap(),
);
assert_eq!(cookie_value(&h, SESSION_COOKIE).as_deref(), Some("xyz"));
}
}
+246
View File
@@ -0,0 +1,246 @@
//! Registry of active stream clients (TS, HLS, recordings) shown in the panel.
use crate::db::now;
use serde::Serialize;
use std::collections::HashMap;
use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
#[derive(Serialize)]
pub struct ClientEntry {
pub id: u64,
pub kind: String,
pub channel_id: i64,
pub channel_name: String,
pub ip: String,
pub user_agent: String,
pub who: String,
pub profile: String,
pub started: i64,
pub bytes: AtomicU64,
pub last_seen: AtomicI64,
#[serde(skip)]
key: String,
}
#[derive(Default)]
pub struct Clients {
map: Mutex<HashMap<u64, Arc<ClientEntry>>>,
next: AtomicU64,
/// Total bytes sent to stream clients since start (for throughput charts).
sent: AtomicU64,
/// Total bytes written by recordings since start.
recorded: AtomicU64,
}
pub struct ClientGuard {
clients: Arc<ClientEntry>,
owner: Arc<Clients>,
}
impl ClientGuard {
pub fn add_bytes(&self, n: u64) {
self.clients.bytes.fetch_add(n, Ordering::Relaxed);
self.owner.count(&self.clients.kind, n);
self.clients.last_seen.store(now(), Ordering::Relaxed);
}
}
impl Drop for ClientGuard {
fn drop(&mut self) {
self.owner.map.lock().unwrap().remove(&self.clients.id);
}
}
pub struct NewClient<'a> {
pub kind: &'a str,
pub channel_id: i64,
pub channel_name: &'a str,
pub ip: &'a str,
pub user_agent: &'a str,
pub who: &'a str,
pub profile: &'a str,
}
impl Clients {
fn count(&self, kind: &str, n: u64) {
if kind == "recording" {
self.recorded.fetch_add(n, Ordering::Relaxed);
} else {
self.sent.fetch_add(n, Ordering::Relaxed);
}
}
/// (bytes sent to clients, bytes recorded) since start.
pub fn totals(&self) -> (u64, u64) {
(
self.sent.load(Ordering::Relaxed),
self.recorded.load(Ordering::Relaxed),
)
}
fn make(&self, c: &NewClient, key: String) -> Arc<ClientEntry> {
let id = self.next.fetch_add(1, Ordering::Relaxed) + 1;
Arc::new(ClientEntry {
id,
kind: c.kind.into(),
channel_id: c.channel_id,
channel_name: c.channel_name.into(),
ip: c.ip.into(),
user_agent: c.user_agent.chars().take(160).collect(),
who: c.who.into(),
profile: c.profile.into(),
started: now(),
bytes: AtomicU64::new(0),
last_seen: AtomicI64::new(now()),
key,
})
}
/// Client whose lifetime is bound to a guard (TS, recording).
pub fn register(self: &Arc<Self>, c: NewClient) -> ClientGuard {
let e = self.make(&c, String::new());
self.map.lock().unwrap().insert(e.id, e.clone());
ClientGuard {
clients: e,
owner: self.clone(),
}
}
/// HLS client identified by (channel, profile, IP, UA); expires when idle.
pub fn touch_hls(&self, c: NewClient, bytes: u64) {
let key = format!("{}|{}|{}|{}", c.channel_id, c.profile, c.ip, c.user_agent);
self.sent.fetch_add(bytes, Ordering::Relaxed);
let mut map = self.map.lock().unwrap();
if let Some(e) = map.values().find(|e| e.kind == "hls" && e.key == key) {
e.bytes.fetch_add(bytes, Ordering::Relaxed);
e.last_seen.store(now(), Ordering::Relaxed);
return;
}
let e = self.make(&c, key);
e.bytes.fetch_add(bytes, Ordering::Relaxed);
map.insert(e.id, e);
}
pub fn reap(&self, hls_idle: i64) {
let t = now();
self.map
.lock()
.unwrap()
.retain(|_, e| e.kind != "hls" || t - e.last_seen.load(Ordering::Relaxed) <= hls_idle);
}
pub fn list(&self) -> Vec<Arc<ClientEntry>> {
let mut v: Vec<_> = self.map.lock().unwrap().values().cloned().collect();
v.sort_by_key(|e| e.started);
v
}
}
/// Friendly device/app name derived from a User-Agent (or HTSP client name).
pub fn device_name(ua: &str) -> String {
let u = ua.trim();
if u.is_empty() {
return "unknown".into();
}
let l = u.to_lowercase();
let pick = |name: &str| -> String {
// version after the product name when present ("Kodi/21.0", "VLC/3.0.20")
let ver = l
.find(&name.to_lowercase())
.map(|i| &u[i + name.len()..])
.and_then(|rest| {
let rest = rest.trim_start_matches(['/', ' ']);
let v: String = rest
.chars()
.take_while(|c| c.is_ascii_digit() || *c == '.')
.collect();
(!v.is_empty()).then_some(v)
});
match ver {
Some(v) => format!("{name} {v}"),
None => name.to_string(),
}
};
let apps = [
("kodi", "Kodi"),
("tivimate", "TiviMate"),
("ott navigator", "OTT Navigator"),
("iptv smarters", "IPTV Smarters"),
("tvhclient", "TVHClient"),
("vlc", "VLC"),
("mpv", "mpv"),
("ffmpeg", "ffmpeg"),
("lavf", "ffmpeg"),
("exoplayer", "ExoPlayer"),
("stagefright", "Android media player"),
("bravia", "Sony Bravia"),
("smarttv", "Smart TV"),
("tizen", "Samsung Tizen"),
("web0s", "LG webOS"),
("roku", "Roku"),
("appletv", "Apple TV"),
("gstreamer", "GStreamer"),
("plex", "Plex"),
("jellyfin", "Jellyfin"),
("emby", "Emby"),
("curl", "curl"),
("wget", "wget"),
("python", "Python"),
("okhttp", "Android app"),
("dalvik", "Android app"),
("cfnetwork", "iOS/macOS app"),
];
for (needle, name) in apps {
if l.contains(needle) {
return pick(name);
}
}
if l.contains("mozilla") || l.contains("safari") || l.contains("firefox") {
let browser = if l.contains("edg/") {
"Edge"
} else if l.contains("opr/") {
"Opera"
} else if l.contains("firefox") {
"Firefox"
} else if l.contains("chrome") || l.contains("crios") {
"Chrome"
} else if l.contains("safari") {
"Safari"
} else {
"browser"
};
let os = if l.contains("android") {
" · Android"
} else if l.contains("iphone") || l.contains("ipad") {
" · iOS"
} else if l.contains("windows") {
" · Windows"
} else if l.contains("mac os") {
" · macOS"
} else if l.contains("linux") {
" · Linux"
} else {
""
};
return format!("{browser}{os}");
}
u.split(['/', ' ', '(']).next().unwrap_or(u).to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn device_names() {
assert_eq!(device_name("Kodi/21.0 (Linux; Android 12)"), "Kodi 21.0");
assert_eq!(device_name("VLC/3.0.20 LibVLC/3.0.20"), "VLC 3.0.20");
assert!(device_name("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36").starts_with("Chrome"));
assert_eq!(
device_name("Dalvik/2.1.0 (Linux; U; Android 10; BRAVIA 4K UR2 Build/QTG2.200305.002)"),
"Sony Bravia"
);
assert_eq!(device_name(""), "unknown");
}
}
+1060
View File
File diff suppressed because it is too large. Load diff
+446
View File
@@ -0,0 +1,446 @@
//! Native Linux DVB API v5 support (frontend, demux, dvr) via ioctl.
//! Tested hardware: Silicon Labs Si2168 (DVB-T/T2/C) with an Si2157 tuner.
use super::{DeliverySystem, SignalStatus, Source, TuneParams};
use anyhow::{bail, Context, Result};
use std::ffi::CString;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::time::{Duration, Instant};
// ioctl numbers verified against linux/dvb headers (generic _IOC encoding:
// x86_64, aarch64, armv7). The size of struct dtv_properties depends on pointer width.
const FE_GET_INFO: u64 = 0x80a8_6f3d;
const FE_READ_STATUS: u64 = 0x8004_6f45;
#[cfg(target_pointer_width = "64")]
const FE_SET_PROPERTY: u64 = 0x4010_6f52;
#[cfg(target_pointer_width = "64")]
const FE_GET_PROPERTY: u64 = 0x8010_6f53;
#[cfg(target_pointer_width = "32")]
const FE_SET_PROPERTY: u64 = 0x4008_6f52;
#[cfg(target_pointer_width = "32")]
const FE_GET_PROPERTY: u64 = 0x8008_6f53;
const DMX_STOP: u64 = 0x6f2a;
const DMX_SET_PES_FILTER: u64 = 0x4014_6f2c;
const BATCH_BYTES: usize = 188 * 256;
const BATCH_WAIT: Duration = Duration::from_millis(15);
const DMX_SET_BUFFER_SIZE: u64 = 0x6f2d;
const DTV_TUNE: u32 = 1;
const DTV_CLEAR: u32 = 2;
const DTV_FREQUENCY: u32 = 3;
const DTV_MODULATION: u32 = 4;
const DTV_BANDWIDTH_HZ: u32 = 5;
const DTV_INVERSION: u32 = 6;
const DTV_DELIVERY_SYSTEM: u32 = 17;
const DTV_CODE_RATE_HP: u32 = 36;
const DTV_CODE_RATE_LP: u32 = 37;
const DTV_GUARD_INTERVAL: u32 = 38;
const DTV_TRANSMISSION_MODE: u32 = 39;
const DTV_HIERARCHY: u32 = 40;
const DTV_STREAM_ID: u32 = 42;
const DTV_ENUM_DELSYS: u32 = 44;
const DTV_STAT_SIGNAL_STRENGTH: u32 = 62;
const DTV_STAT_CNR: u32 = 63;
const DTV_STAT_ERROR_BLOCK_COUNT: u32 = 68;
const SYS_DVBC_ANNEX_A: u32 = 1;
const SYS_DVBT: u32 = 3;
const SYS_DVBT2: u32 = 16;
const DTV_SYMBOL_RATE: u32 = 8;
const DTV_INNER_FEC: u32 = 9;
const FEC_AUTO: u32 = 9;
const QAM_AUTO: u32 = 6;
const TRANSMISSION_MODE_AUTO: u32 = 2;
const GUARD_INTERVAL_AUTO: u32 = 4;
const HIERARCHY_AUTO: u32 = 4;
const INVERSION_AUTO: u32 = 2;
const NO_STREAM_ID_FILTER: u32 = u32::MAX;
const FE_HAS_SIGNAL: u32 = 0x01;
const FE_HAS_CARRIER: u32 = 0x02;
const FE_HAS_LOCK: u32 = 0x10;
const FE_SCALE_DECIBEL: u8 = 1;
const FE_SCALE_RELATIVE: u8 = 2;
const FE_SCALE_COUNTER: u8 = 3;
/// Size of union `u` in struct dtv_property: {u8[32], u32, u32[3], void*} aligned to pointer size.
#[cfg(target_pointer_width = "64")]
const DTV_U_SIZE: usize = 56;
#[cfg(target_pointer_width = "32")]
const DTV_U_SIZE: usize = 52;
#[repr(C, packed)]
#[derive(Clone, Copy)]
struct DtvProperty {
cmd: u32,
reserved: [u32; 3],
u: [u8; DTV_U_SIZE],
result: i32,
}
#[cfg(target_pointer_width = "64")]
const _: () = assert!(std::mem::size_of::<DtvProperty>() == 76);
#[cfg(target_pointer_width = "32")]
const _: () = assert!(std::mem::size_of::<DtvProperty>() == 72);
const _: () = assert!(std::mem::size_of::<DtvProperties>() == 2 * std::mem::size_of::<usize>());
impl DtvProperty {
fn new(cmd: u32, data: u32) -> Self {
let mut u = [0u8; DTV_U_SIZE];
u[0..4].copy_from_slice(&data.to_ne_bytes());
DtvProperty {
cmd,
reserved: [0; 3],
u,
result: 0,
}
}
}
#[repr(C)]
struct DtvProperties {
num: u32,
props: *mut DtvProperty,
}
#[repr(C)]
struct DmxPesFilterParams {
pid: u16,
input: u32,
output: u32,
pes_type: u32,
flags: u32,
}
const _: () = assert!(std::mem::size_of::<DmxPesFilterParams>() == 20);
#[repr(C)]
struct FeInfo {
name: [u8; 128],
rest: [u32; 10],
}
const _: () = assert!(std::mem::size_of::<FeInfo>() == 168);
fn open_dev(path: &str, flags: i32) -> Result<OwnedFd> {
let c = CString::new(path)?;
let fd = unsafe { libc::open(c.as_ptr(), flags | libc::O_CLOEXEC) };
if fd < 0 {
return Err(std::io::Error::last_os_error()).with_context(|| format!("open {path}"));
}
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}
unsafe fn ioctl<T>(fd: &OwnedFd, req: u64, arg: *mut T) -> std::io::Result<()> {
let r = libc::ioctl(fd.as_raw_fd(), req as _, arg);
if r < 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(())
}
}
fn set_props(fd: &OwnedFd, props: &mut [DtvProperty]) -> std::io::Result<()> {
let mut p = DtvProperties {
num: props.len() as u32,
props: props.as_mut_ptr(),
};
unsafe { ioctl(fd, FE_SET_PROPERTY, &mut p) }
}
fn get_props(fd: &OwnedFd, props: &mut [DtvProperty]) -> std::io::Result<()> {
let mut p = DtvProperties {
num: props.len() as u32,
props: props.as_mut_ptr(),
};
unsafe { ioctl(fd, FE_GET_PROPERTY, &mut p) }
}
fn read_status(fd: &OwnedFd) -> u32 {
let mut st: u32 = 0;
if unsafe { ioctl(fd, FE_READ_STATUS, &mut st) }.is_err() {
return 0;
}
st
}
fn frontend_name(fd: &OwnedFd) -> Result<String> {
let mut info = FeInfo {
name: [0; 128],
rest: [0; 10],
};
unsafe { ioctl(fd, FE_GET_INFO, &mut info) }.context("FE_GET_INFO")?;
let end = info.name.iter().position(|&b| b == 0).unwrap_or(128);
Ok(String::from_utf8_lossy(&info.name[..end])
.trim()
.to_string())
}
fn enum_delsys(fd: &OwnedFd) -> Vec<DeliverySystem> {
let mut props = [DtvProperty::new(DTV_ENUM_DELSYS, 0)];
if get_props(fd, &mut props).is_err() {
return vec![];
}
let u = props[0].u;
let len = u32::from_ne_bytes([u[32], u[33], u[34], u[35]]).min(32) as usize;
let mut out = Vec::new();
for &d in &u[..len] {
match d as u32 {
SYS_DVBT => out.push(DeliverySystem::Dvbt),
SYS_DVBT2 => out.push(DeliverySystem::Dvbt2),
SYS_DVBC_ANNEX_A => out.push(DeliverySystem::Dvbc),
_ => {}
}
}
out
}
/// Reads the frontend name and supported delivery systems.
pub fn probe(adapter_path: &str) -> Result<(String, Vec<DeliverySystem>)> {
let fd = open_dev(
&format!("{adapter_path}/frontend0"),
libc::O_RDONLY | libc::O_NONBLOCK,
)?;
let name = frontend_name(&fd)?;
Ok((name, enum_delsys(&fd)))
}
pub struct LinuxSource {
path: String,
fe: OwnedFd,
demux: Option<OwnedFd>,
dvr: Option<OwnedFd>,
overflows: u64,
}
impl LinuxSource {
pub fn open(adapter_path: &str) -> Result<Self> {
let fe = open_dev(
&format!("{adapter_path}/frontend0"),
libc::O_RDWR | libc::O_NONBLOCK,
)
.context("frontend is busy or permission denied (video group?)")?;
Ok(Self {
path: adapter_path.to_string(),
fe,
demux: None,
dvr: None,
overflows: 0,
})
}
fn start_demux(&mut self) -> Result<()> {
if self.demux.is_some() {
return Ok(());
}
let dmx = open_dev(
&format!("{}/demux0", self.path),
libc::O_RDWR | libc::O_NONBLOCK,
)?;
unsafe {
// An 8 MiB kernel buffer reduces the risk of overflow (EOVERFLOW).
let _ = libc::ioctl(
dmx.as_raw_fd(),
DMX_SET_BUFFER_SIZE as _,
8 * 1024 * 1024 as libc::c_ulong,
);
}
let mut f = DmxPesFilterParams {
pid: 0x2000,
input: 0,
output: 2,
pes_type: 20,
flags: 4,
};
unsafe { ioctl(&dmx, DMX_SET_PES_FILTER, &mut f) }
.context("DMX_SET_PES_FILTER (full TS)")?;
let dvr = open_dev(
&format!("{}/dvr0", self.path),
libc::O_RDONLY | libc::O_NONBLOCK,
)?;
unsafe {
// room for batched reads (the DVR ring buffer defaults to ~1.9 MiB)
let _ = libc::ioctl(
dvr.as_raw_fd(),
DMX_SET_BUFFER_SIZE as _,
8 * 1024 * 1024 as libc::c_ulong,
);
}
self.demux = Some(dmx);
self.dvr = Some(dvr);
Ok(())
}
}
impl Drop for LinuxSource {
fn drop(&mut self) {
if let Some(d) = &self.demux {
unsafe {
let _ = libc::ioctl(d.as_raw_fd(), DMX_STOP as _);
}
}
}
}
impl Source for LinuxSource {
fn tune(&mut self, p: &TuneParams, timeout: Duration) -> Result<bool> {
let mut clear = [DtvProperty::new(DTV_CLEAR, 0)];
set_props(&self.fe, &mut clear).context("DTV_CLEAR")?;
if p.delsys == DeliverySystem::Dvbc {
let modulation = match p
.modulation
.as_deref()
.unwrap_or("auto")
.to_ascii_lowercase()
.as_str()
{
"qam16" => 1,
"qam32" => 2,
"qam64" => 3,
"qam128" => 4,
"qam256" => 5,
_ => QAM_AUTO,
};
let mut props = vec![
DtvProperty::new(DTV_DELIVERY_SYSTEM, SYS_DVBC_ANNEX_A),
DtvProperty::new(DTV_FREQUENCY, p.frequency_hz as u32),
DtvProperty::new(DTV_SYMBOL_RATE, p.symbol_rate.unwrap_or(6_900_000)),
DtvProperty::new(DTV_MODULATION, modulation),
DtvProperty::new(DTV_INNER_FEC, FEC_AUTO),
DtvProperty::new(DTV_INVERSION, INVERSION_AUTO),
DtvProperty::new(DTV_TUNE, 0),
];
set_props(&self.fe, &mut props).with_context(|| format!("tuning {}", p.describe()))?;
return self.wait_lock(timeout);
}
let sys = match p.delsys {
DeliverySystem::Dvbt => SYS_DVBT,
_ => SYS_DVBT2,
};
let mut props = vec![
DtvProperty::new(DTV_DELIVERY_SYSTEM, sys),
DtvProperty::new(DTV_FREQUENCY, p.frequency_hz as u32),
DtvProperty::new(DTV_BANDWIDTH_HZ, p.bandwidth_hz),
DtvProperty::new(DTV_INVERSION, INVERSION_AUTO),
DtvProperty::new(DTV_MODULATION, QAM_AUTO),
DtvProperty::new(DTV_CODE_RATE_HP, FEC_AUTO),
DtvProperty::new(DTV_CODE_RATE_LP, FEC_AUTO),
DtvProperty::new(DTV_GUARD_INTERVAL, GUARD_INTERVAL_AUTO),
DtvProperty::new(DTV_TRANSMISSION_MODE, TRANSMISSION_MODE_AUTO),
];
if p.delsys == DeliverySystem::Dvbt {
props.push(DtvProperty::new(DTV_HIERARCHY, HIERARCHY_AUTO));
} else {
props.push(DtvProperty::new(
DTV_STREAM_ID,
p.plp_id.unwrap_or(NO_STREAM_ID_FILTER),
));
}
props.push(DtvProperty::new(DTV_TUNE, 0));
set_props(&self.fe, &mut props).with_context(|| format!("tuning {}", p.describe()))?;
self.wait_lock(timeout)
}
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
self.read_dvr(buf)
}
fn status(&mut self) -> SignalStatus {
self.read_status_full()
}
}
impl LinuxSource {
fn wait_lock(&mut self, timeout: Duration) -> Result<bool> {
let start = Instant::now();
while start.elapsed() < timeout {
std::thread::sleep(Duration::from_millis(50));
if read_status(&self.fe) & FE_HAS_LOCK != 0 {
self.start_demux()?;
return Ok(true);
}
}
Ok(false)
}
fn read_dvr(&mut self, buf: &mut [u8]) -> Result<usize> {
let Some(dvr) = &self.dvr else {
std::thread::sleep(Duration::from_millis(100));
return Ok(0);
};
let mut pfd = libc::pollfd {
fd: dvr.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
};
let r = unsafe { libc::poll(&mut pfd, 1, 500) };
if r <= 0 {
return Ok(0);
}
let n = unsafe { libc::read(dvr.as_raw_fd(), buf.as_mut_ptr() as *mut _, buf.len()) };
if n < 0 {
let e = std::io::Error::last_os_error();
match e.raw_os_error() {
Some(libc::EAGAIN) | Some(libc::EINTR) => return Ok(0),
Some(libc::EOVERFLOW) => {
self.overflows += 1;
if self.overflows % 50 == 1 {
tracing::warn!("{}: DVR buffer overflow ({}x)", self.path, self.overflows);
}
return Ok(0);
}
_ => bail!("reading dvr0: {e}"),
}
}
// Read in batches: poll() wakes up as soon as a few packets are queued, which
// means thousands of tiny reads (and subscriber wake-ups) per second. Letting the
// kernel buffer fill for a moment cuts the CPU use several times; ~15 ms of data
// is far below the DVR buffer even on a 50 Mbit/s mux.
if (n as usize) < BATCH_BYTES {
std::thread::sleep(BATCH_WAIT);
}
Ok(n as usize)
}
fn read_status_full(&mut self) -> SignalStatus {
let st = read_status(&self.fe);
let mut s = SignalStatus {
locked: st & FE_HAS_LOCK != 0,
has_signal: st & FE_HAS_SIGNAL != 0,
has_carrier: st & FE_HAS_CARRIER != 0,
..Default::default()
};
let mut props = [
DtvProperty::new(DTV_STAT_SIGNAL_STRENGTH, 0),
DtvProperty::new(DTV_STAT_CNR, 0),
DtvProperty::new(DTV_STAT_ERROR_BLOCK_COUNT, 0),
];
if get_props(&self.fe, &mut props).is_ok() {
for (i, p) in props.iter().enumerate() {
let u = p.u;
if u[0] == 0 {
continue;
}
let scale = u[1];
let raw = u64::from_ne_bytes([u[2], u[3], u[4], u[5], u[6], u[7], u[8], u[9]]);
match (i, scale) {
(0, FE_SCALE_DECIBEL) => s.strength_dbm = Some(raw as i64 as f64 / 1000.0),
(0, FE_SCALE_RELATIVE) => s.strength_pct = Some(raw as f64 * 100.0 / 65535.0),
(1, FE_SCALE_DECIBEL) => s.snr_db = Some(raw as i64 as f64 / 1000.0),
(1, FE_SCALE_RELATIVE) => s.snr_pct = Some(raw as f64 * 100.0 / 65535.0),
(2, FE_SCALE_COUNTER) => s.uncorrected = Some(raw),
_ => {}
}
}
}
if s.strength_pct.is_none() {
if let Some(dbm) = s.strength_dbm {
// approximation: -90 dBm = 0%, -30 dBm = 100%
s.strength_pct = Some(((dbm + 90.0) / 60.0 * 100.0).clamp(0.0, 100.0));
}
}
s
}
}
+196
View File
@@ -0,0 +1,196 @@
//! DVB stream sources: Linux DVB cards (e.g. Silicon Labs Si2168) and a virtual adapter.
pub mod linux;
pub mod scan;
pub mod virt;
use serde::{Deserialize, Serialize};
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum DeliverySystem {
Dvbt,
#[default]
Dvbt2,
/// DVB-C (Annex A, Europa)
Dvbc,
}
impl DeliverySystem {
pub fn as_str(self) -> &'static str {
match self {
DeliverySystem::Dvbt => "dvbt",
DeliverySystem::Dvbt2 => "dvbt2",
DeliverySystem::Dvbc => "dvbc",
}
}
pub fn parse(s: &str) -> Option<Self> {
match s.to_ascii_lowercase().replace(['-', '_', '/'], "").as_str() {
"dvbt" => Some(DeliverySystem::Dvbt),
"dvbt2" => Some(DeliverySystem::Dvbt2),
"dvbc" | "dvbca" | "dvbcannexa" => Some(DeliverySystem::Dvbc),
_ => None,
}
}
pub fn is_cable(self) -> bool {
self == DeliverySystem::Dvbc
}
pub fn label(self) -> &'static str {
match self {
DeliverySystem::Dvbt => "DVB-T",
DeliverySystem::Dvbt2 => "DVB-T2",
DeliverySystem::Dvbc => "DVB-C",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct TuneParams {
pub delsys: DeliverySystem,
pub frequency_hz: u64,
pub bandwidth_hz: u32,
#[serde(default)]
pub plp_id: Option<u32>,
/// DVB-C: symbol rate (symbols/s), e.g. 6_900_000
#[serde(default)]
pub symbol_rate: Option<u32>,
/// DVB-C: "qam64", "qam128", "qam256", "auto"
#[serde(default)]
pub modulation: Option<String>,
}
impl TuneParams {
pub fn describe(&self) -> String {
if self.delsys.is_cable() {
return format!(
"DVB-C {:.1} MHz / {} kS/s / {}",
self.frequency_hz as f64 / 1e6,
self.symbol_rate.unwrap_or(6_900_000) / 1000,
self.modulation.as_deref().unwrap_or("auto").to_uppercase()
);
}
format!(
"{} {:.1} MHz / {} MHz{}",
self.delsys.label(),
self.frequency_hz as f64 / 1e6,
self.bandwidth_hz / 1_000_000,
self.plp_id.map(|p| format!(" PLP {p}")).unwrap_or_default()
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SignalStatus {
pub locked: bool,
pub has_signal: bool,
pub has_carrier: bool,
/// Signal strength in percent (0-100), if the driver reports it.
pub strength_pct: Option<f64>,
/// Signal strength in dBm (e.g. Si2157 tuner behind an Si2168 demodulator).
pub strength_dbm: Option<f64>,
/// Signal-to-noise ratio in dB.
pub snr_db: Option<f64>,
pub snr_pct: Option<f64>,
/// Uncorrected block counter.
pub uncorrected: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AdapterInfo {
/// Stable identifier, e.g. "adapter0" or "virtual0".
pub id: String,
pub name: String,
pub kind: String,
pub path: String,
pub delivery_systems: Vec<DeliverySystem>,
}
/// Stream source interface (one tuner).
pub trait Source: Send {
/// Tunes and waits for lock. Returns `true` when locked.
fn tune(&mut self, params: &TuneParams, timeout: Duration) -> anyhow::Result<bool>;
/// Reads TS data (blocking with a short timeout). 0 = no data.
fn read(&mut self, buf: &mut [u8]) -> anyhow::Result<usize>;
fn status(&mut self) -> SignalStatus;
}
/// Opens the source for the given adapter.
pub fn open(info: &AdapterInfo) -> anyhow::Result<Box<dyn Source>> {
match info.kind.as_str() {
"linux" => Ok(Box::new(linux::LinuxSource::open(&info.path)?)),
"virtual" => Ok(Box::new(virt::VirtualSource::new(&info.path))),
other => anyhow::bail!("unknown adapter type: {other}"),
}
}
/// Discovers DVB adapters in the system (`/dev/dvb/adapterN/frontendM`).
pub fn discover(dev_root: &str) -> Vec<AdapterInfo> {
let mut out = Vec::new();
let Ok(rd) = std::fs::read_dir(dev_root) else {
return out;
};
let mut dirs: Vec<_> = rd.filter_map(|e| e.ok()).map(|e| e.path()).collect();
dirs.sort();
for dir in dirs {
let Some(name) = dir.file_name().and_then(|n| n.to_str()).map(str::to_string) else {
continue;
};
let Some(num) = name.strip_prefix("adapter") else {
continue;
};
let fe = dir.join("frontend0");
if !fe.exists() {
continue;
}
let path = dir.to_string_lossy().to_string();
match linux::probe(&path) {
Ok((fe_name, delsys)) => {
if delsys.is_empty() {
tracing::info!("{path}: {fe_name} supports no DVB-T/T2/C, skipping");
continue;
}
out.push(AdapterInfo {
id: format!("adapter{num}"),
name: fe_name,
kind: "linux".into(),
path,
delivery_systems: delsys,
});
}
Err(e) => tracing::warn!("{path}: cannot read frontend: {e:#}"),
}
}
out
}
/// UHF channels (Europe, 8 MHz raster): channel -> centre frequency.
pub fn uhf_channel_hz(ch: u32) -> u64 {
(306 + 8 * ch as u64) * 1_000_000
}
/// VHF band III channels (Europe, 7 MHz): channels 5–12.
pub fn vhf3_channel_hz(ch: u32) -> u64 {
177_500_000 + (ch as u64 - 5) * 7_000_000
}
pub fn uhf_channel_of(freq_hz: u64) -> Option<u32> {
let mhz = freq_hz / 1_000_000;
if mhz < 474 || (mhz - 306) % 8 != 0 {
return None;
}
Some(((mhz - 306) / 8) as u32)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uhf_mapping() {
assert_eq!(uhf_channel_hz(21), 474_000_000);
assert_eq!(uhf_channel_hz(48), 690_000_000);
assert_eq!(uhf_channel_of(690_000_000), Some(48));
assert_eq!(DeliverySystem::parse("DVB-T2"), Some(DeliverySystem::Dvbt2));
}
}
+351
View File
@@ -0,0 +1,351 @@
//! Multiplex scanning: tune, lock, read PAT/PMT/SDT/NIT.
use super::{uhf_channel_hz, DeliverySystem, SignalStatus, Source, TuneParams};
use crate::ts::packet::Aligner;
use crate::ts::si::SiCollector;
use crate::ts::tables::{service_kind, PmtStream};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FoundService {
pub sid: u16,
pub name: String,
pub provider: String,
pub service_type: u8,
pub kind: String,
pub lcn: Option<u16>,
pub pmt_pid: u16,
pub pcr_pid: u16,
pub streams: Vec<PmtStream>,
pub scrambled: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct FoundMux {
pub params: TuneParams,
pub onid: u16,
pub ts_id: u16,
pub network_name: String,
pub services: Vec<FoundService>,
pub signal: SignalStatus,
/// Multiplexes discovered in the NIT (appended to the scan queue automatically).
pub discovered: Vec<ScanEntry>,
}
/// Scan list entry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ScanEntry {
pub frequency_hz: u64,
pub bandwidth_hz: u32,
/// Forced delivery system (e.g. DVB-C for cable lists); None = user's choice.
pub delsys: Option<DeliverySystem>,
#[serde(default)]
pub symbol_rate: Option<u32>,
#[serde(default)]
pub modulation: Option<String>,
#[serde(default)]
pub plp_id: Option<u32>,
}
impl ScanEntry {
pub fn terrestrial(hz: u64, bw_mhz: u32) -> Self {
ScanEntry {
frequency_hz: hz,
bandwidth_hz: bw_mhz * 1_000_000,
delsys: None,
symbol_rate: None,
modulation: None,
plp_id: None,
}
}
pub fn cable(hz: u64) -> Self {
ScanEntry {
frequency_hz: hz,
bandwidth_hz: 8_000_000,
delsys: Some(DeliverySystem::Dvbc),
symbol_rate: None,
modulation: None,
plp_id: None,
}
}
/// Duplicate detection key (medium + frequency rounded to 1 MHz).
pub fn key(&self) -> (bool, u64) {
(
self.delsys == Some(DeliverySystem::Dvbc),
(self.frequency_hz + 500_000) / 1_000_000,
)
}
}
fn mhz(f: f64) -> u64 {
(f * 1_000_000.0).round() as u64
}
/// VHF band III, 7 MHz raster (Europe: channels 5–12, 177.5–226.5 MHz).
fn vhf3_eu() -> Vec<ScanEntry> {
(5..=12)
.map(|ch| ScanEntry::terrestrial(mhz(177.5 + 7.0 * (ch - 5) as f64), 7))
.collect()
}
fn uhf(from: u32, to: u32) -> Vec<ScanEntry> {
(from..=to)
.map(|ch| ScanEntry::terrestrial(uhf_channel_hz(ch), 8))
.collect()
}
/// Predefined frequency lists (id → list).
pub fn preset(name: &str) -> Option<Vec<ScanEntry>> {
Some(match name {
// Europe after the 700 MHz band clearance (PL, DE, FR, UK, CZ, SK, ES, ...): UHF 21–48
"uhf-21-48" | "pl" => uhf(21, 48),
// Full UHF band 21–69 (older plans, countries without refarming)
"uhf-21-69" | "eu-uhf" => uhf(21, 69),
// VHF III (7 MHz) + UHF 21–69 (8 MHz) – Europe with VHF transmitters (NL, CH, AT, Scandinavia, ...)
"vhf-uhf" => {
let mut v = vhf3_eu();
v.extend(uhf(21, 69));
v
}
// Italy: VHF channels D–H2 (7 MHz) + UHF 21–48
"italy" => {
let mut v: Vec<ScanEntry> = [177.5, 186.0, 194.5, 203.5, 212.5, 219.5, 226.5]
.iter()
.map(|f| ScanEntry::terrestrial(mhz(*f), 7))
.collect();
v.extend(uhf(21, 48));
v
}
// Australia: VHF 6–12 (incl. 9A) and UHF 28–51, 7 MHz raster
"australia" => {
let mut v: Vec<ScanEntry> = [177.5, 184.5, 191.5, 198.5, 205.5, 212.5, 219.5, 226.5]
.iter()
.map(|f| ScanEntry::terrestrial(mhz(*f), 7))
.collect();
v.extend(
(28..=51).map(|ch| ScanEntry::terrestrial(mhz(529.5 + 7.0 * (ch - 28) as f64), 7)),
);
v
}
// New Zealand: UHF 25–48 (8 MHz)
"new-zealand" => uhf(25, 48),
// DVB-C: 114–858 MHz every 8 MHz (typical European cable network plan)
"dvbc-eu" => (0..=93)
.map(|i| ScanEntry::cable((114 + 8 * i) * 1_000_000))
.collect(),
_ => return None,
})
}
/// Preset list: (id, description). Descriptions are English; the panel translates them.
pub fn presets() -> Vec<(&'static str, &'static str)> {
vec![
(
"uhf-21-48",
"Europe – UHF 21–48 (474–690 MHz, after 700 MHz refarming: PL, DE, FR, UK, CZ…)",
),
("uhf-21-69", "Europe – UHF 21–69 (474–858 MHz)"),
("vhf-uhf", "Europe – VHF III (7 MHz) + UHF 21–69"),
("italy", "Italy – VHF D–H2 + UHF 21–48"),
("australia", "Australia – VHF 6–12 + UHF 28–51 (7 MHz)"),
("new-zealand", "New Zealand – UHF 25–48"),
("dvbc-eu", "Cable DVB-C – 114–858 MHz"),
("custom", "Custom frequency list"),
]
}
/// Tunes one frequency and reads its services.
pub fn scan_frequency(
src: &mut dyn Source,
params: &TuneParams,
lock_timeout: Duration,
si_timeout: Duration,
cancel: &AtomicBool,
) -> anyhow::Result<Option<FoundMux>> {
if !src.tune(params, lock_timeout)? {
return Ok(None);
}
let signal = src.status();
let mut si = SiCollector::new(false);
let mut aligner = Aligner::new();
let mut buf = vec![0u8; 188 * 256];
let start = Instant::now();
let mut basic_at: Option<Instant> = None;
while start.elapsed() < si_timeout && !cancel.load(Ordering::Relaxed) {
let n = src.read(&mut buf)?;
if n > 0 {
aligner.push(&buf[..n], |p| si.push(p));
}
if si.basic_complete() {
let t = *basic_at.get_or_insert_with(Instant::now);
// NIT (LCN) is often sent less frequently – wait for it up to 3 s
if si.nit_complete() || t.elapsed() > Duration::from_secs(3) {
break;
}
}
}
let Some(pat) = si.pat.clone() else {
return Ok(None);
};
let ts_id = si.sdt_ts_id.unwrap_or(pat.ts_id);
let onid = si.sdt_onid.unwrap_or(0);
let mut services = Vec::new();
for &(prog, pmt_pid) in &pat.programs {
if prog == 0 {
continue;
}
let sdt = si.sdt_services().find(|s| s.service_id == prog).cloned();
let pmt = si.pmts.get(&prog);
let (stype, name, provider, free_ca) = match &sdt {
Some(s) => (
s.service_type,
s.name.clone(),
s.provider.clone(),
s.free_ca,
),
None => (0, String::new(), String::new(), false),
};
let streams = pmt.map(|p| p.streams.clone()).unwrap_or_default();
let mut kind = service_kind(stype).to_string();
if kind == "other" {
if streams.iter().any(|s| s.kind.is_video()) {
kind = "tv".into();
} else if streams.iter().any(|s| s.kind.is_audio()) {
kind = "radio".into();
}
}
services.push(FoundService {
sid: prog,
name: if name.is_empty() {
format!("Service {prog}")
} else {
name
},
provider,
service_type: stype,
kind,
lcn: si.lcn(ts_id, prog),
pmt_pid,
pcr_pid: pmt.map(|p| p.pcr_pid).unwrap_or(0x1FFF),
streams,
scrambled: free_ca || pmt.map(|p| p.scrambled).unwrap_or(false),
});
}
let network_name = si
.nit
.as_ref()
.map(|n| n.network_name.clone())
.unwrap_or_default();
let discovered: Vec<ScanEntry> = si
.nit_transports
.iter()
.filter_map(|t| {
let f = t.frequency_hz?;
Some(match &t.cable {
Some((sr, m)) => ScanEntry {
frequency_hz: f,
bandwidth_hz: 8_000_000,
delsys: Some(DeliverySystem::Dvbc),
symbol_rate: Some(*sr),
modulation: m.map(|x| x.to_string()),
plp_id: None,
},
None if params.delsys.is_cable() => return None,
None => ScanEntry::terrestrial(
f,
t.bandwidth_hz.unwrap_or(params.bandwidth_hz) / 1_000_000,
),
})
})
.filter(|e| e.frequency_hz > 40_000_000 && e.frequency_hz < 1_000_000_000)
.collect();
Ok(Some(FoundMux {
params: params.clone(),
onid,
ts_id,
network_name,
services,
signal,
discovered,
}))
}
/// Order in which delivery systems are tried for a frequency.
pub fn systems_order(
supported: &[DeliverySystem],
wanted: &[DeliverySystem],
) -> Vec<DeliverySystem> {
let mut v: Vec<DeliverySystem> = wanted
.iter()
.copied()
.filter(|d| supported.contains(d))
.collect();
// DVB-T2 first (newer networks), then DVB-T, DVB-C last
v.sort_by_key(|d| match d {
DeliverySystem::Dvbt2 => 0,
DeliverySystem::Dvbt => 1,
DeliverySystem::Dvbc => 2,
});
v.dedup();
v
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dvb::virt::VirtualSource;
use crate::ts::testgen::GenMux;
#[test]
fn scan_virtual_mux() {
let dir = tempfile::tempdir().unwrap();
let mux = GenMux::sample(7, 0x100, &["TVP Info", "Radio Test"], 1_700_000_000);
std::fs::write(dir.path().join("538.ts"), mux.generate(2)).unwrap();
std::env::set_var("SIMPLY_DVB_VIRTUAL_SPEED", "50");
let mut src = VirtualSource::new(dir.path().to_str().unwrap());
let p = TuneParams {
delsys: DeliverySystem::Dvbt2,
frequency_hz: 538_000_000,
bandwidth_hz: 8_000_000,
plp_id: None,
..Default::default()
};
let cancel = AtomicBool::new(false);
let found = scan_frequency(
&mut src,
&p,
Duration::from_secs(1),
Duration::from_secs(10),
&cancel,
)
.unwrap()
.unwrap();
assert_eq!(found.ts_id, 7);
assert_eq!(found.services.len(), 2);
assert_eq!(found.services[0].name, "TVP Info");
assert_eq!(found.services[0].lcn, Some(1));
assert_eq!(found.services[0].kind, "tv");
let p2 = TuneParams {
frequency_hz: 546_000_000,
..p
};
assert!(scan_frequency(
&mut src,
&p2,
Duration::from_secs(1),
Duration::from_secs(1),
&cancel
)
.unwrap()
.is_none());
assert_eq!(preset("pl").unwrap().len(), 28);
assert_eq!(preset("australia").unwrap()[0].bandwidth_hz, 7_000_000);
assert_eq!(
preset("dvbc-eu").unwrap().last().unwrap().frequency_hz,
858_000_000
);
assert_eq!(preset("vhf-uhf").unwrap()[7].frequency_hz, 226_500_000);
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Virtual adapter: plays `.ts` files from a directory as if they were multiplexes.
//! The file for 474 MHz may be named `474.ts`, `474000000.ts`
//! or `ch21.ts`. Playback is paced by the PCR (real time).
use super::{uhf_channel_of, SignalStatus, Source, TuneParams};
use crate::ts::packet;
use anyhow::Result;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
pub struct VirtualSource {
dir: PathBuf,
file: Option<File>,
speed: f64,
pcr_pid: Option<u16>,
base: Option<(u64, Instant)>,
locked: bool,
}
impl VirtualSource {
pub fn new(dir: &str) -> Self {
let speed = std::env::var("SIMPLY_DVB_VIRTUAL_SPEED")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(1.0f64);
Self {
dir: PathBuf::from(dir),
file: None,
speed: speed.max(0.01),
pcr_pid: None,
base: None,
locked: false,
}
}
pub fn file_for(dir: &Path, freq_hz: u64) -> Option<PathBuf> {
let mut c = vec![
format!("{}.ts", freq_hz),
format!("{}.ts", freq_hz / 1_000_000),
];
if let Some(ch) = uhf_channel_of(freq_hz) {
c.push(format!("ch{ch}.ts"));
}
c.into_iter().map(|n| dir.join(n)).find(|p| p.is_file())
}
fn pace(&mut self, chunk: &[u8]) {
for pkt in chunk.chunks_exact(packet::TS_SIZE) {
if pkt[0] != packet::SYNC {
continue;
}
let Some(pcr) = packet::pcr(pkt) else {
continue;
};
let pid = packet::pid(pkt);
match self.pcr_pid {
None => self.pcr_pid = Some(pid),
Some(p) if p != pid => continue,
_ => {}
}
match self.base {
None => self.base = Some((pcr, Instant::now())),
Some((b, t0)) => {
if pcr < b || pcr - b > 27_000_000 * 3600 {
self.base = Some((pcr, Instant::now()));
continue;
}
let target =
Duration::from_secs_f64((pcr - b) as f64 / 27_000_000.0 / self.speed);
let el = t0.elapsed();
if target > el {
let wait = target - el;
if wait > Duration::from_secs(5) {
self.base = Some((pcr, Instant::now()));
} else {
std::thread::sleep(wait);
}
}
}
}
}
}
}
impl Source for VirtualSource {
fn tune(&mut self, p: &TuneParams, _timeout: Duration) -> Result<bool> {
self.file = None;
self.base = None;
self.pcr_pid = None;
self.locked = false;
if let Some(path) = Self::file_for(&self.dir, p.frequency_hz) {
self.file = Some(File::open(path)?);
self.locked = true;
}
Ok(self.locked)
}
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let Some(f) = self.file.as_mut() else {
std::thread::sleep(Duration::from_millis(100));
return Ok(0);
};
let want = (buf.len() / packet::TS_SIZE).clamp(1, 64) * packet::TS_SIZE;
let mut n = f.read(&mut buf[..want])?;
if n == 0 {
f.seek(SeekFrom::Start(0))?;
self.base = None;
n = f.read(&mut buf[..want])?;
}
let chunk = buf[..n].to_vec();
self.pace(&chunk);
Ok(n)
}
fn status(&mut self) -> SignalStatus {
SignalStatus {
locked: self.locked,
has_signal: self.locked,
has_carrier: self.locked,
strength_pct: self.locked.then_some(87.0),
strength_dbm: self.locked.then_some(-38.0),
snr_db: self.locked.then_some(28.5),
snr_pct: None,
uncorrected: self.locked.then_some(0),
}
}
}
+599
View File
@@ -0,0 +1,599 @@
//! EPG: storing EIT from the broadcast, periodically walking the muxes (grabber),
//! importing external XMLTV sources and exporting XMLTV.
use crate::app::State;
use crate::db::{now, Channel, NewEpg};
use crate::ts::si::EpgItem;
use crate::ts::tables::genre_name;
use crate::tuner::Priority;
use anyhow::{bail, Context, Result};
use quick_xml::events::Event;
use quick_xml::Reader;
use std::collections::HashMap;
use std::io::Read;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
/// Stores EIT events in the database (service -> channel mapping).
pub async fn writer_task(state: State, mut rx: mpsc::UnboundedReceiver<(i64, Vec<EpgItem>)>) {
let mut map: HashMap<(i64, i64, i64), Vec<i64>> = HashMap::new();
let mut loaded = Instant::now() - Duration::from_secs(3600);
while let Some((_mux, items)) = rx.recv().await {
if loaded.elapsed() > Duration::from_secs(30) {
if let Ok(rows) = state.db.service_channel_map().await {
map.clear();
for (onid, tsid, sid, ch) in rows {
map.entry((onid, tsid, sid)).or_default().push(ch);
}
loaded = Instant::now();
}
}
let mut out = Vec::new();
for it in items {
let key = (it.onid as i64, it.ts_id as i64, it.service_id as i64);
let Some(chs) = map.get(&key).or_else(|| {
// some broadcasters send a different ONID in the EIT – match on TSID+SID
map.iter()
.find(|((_, t, s), _)| *t == key.1 && *s == key.2)
.map(|(_, v)| v)
}) else {
continue;
};
let e = &it.event;
if e.duration <= 0 || e.start + e.duration < now() - 3600 {
continue;
}
for &ch in chs {
out.push(NewEpg {
channel_id: ch,
start: e.start,
stop: e.start + e.duration,
title: e.title.clone(),
summary: e.summary.clone(),
description: e.description.clone(),
genre: e.genre.and_then(genre_name).unwrap_or("").to_string(),
rating: e.rating.map(|r| r as i64),
});
}
}
if out.is_empty() {
continue;
}
match state.db.upsert_epg(&out, "ota").await {
Ok(n) => state.epg_status.lock().unwrap().ota_events_written += n as u64,
Err(e) => tracing::warn!("storing EPG: {e:#}"),
}
}
}
/// Periodic EPG grabbing: tunes successive muxes while tuners are free.
pub async fn grabber_task(state: State) {
let mut last_cleanup = Instant::now();
loop {
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(60)) => {}
_ = state.epg_wakeup.notified() => {}
}
let s = state.settings();
if last_cleanup.elapsed() > Duration::from_secs(3600) {
let _ = state
.db
.epg_cleanup(s.epg_keep_past_hours as i64 * 3600)
.await;
last_cleanup = Instant::now();
}
if !s.epg_ota_enabled || s.epg_grab_interval_hours == 0 {
continue;
}
let Ok(muxes) = state.db.muxes().await else {
continue;
};
let interval = s.epg_grab_interval_hours as i64 * 3600;
for mux in muxes.into_iter().filter(|m| m.enabled) {
if state
.shutting_down
.load(std::sync::atomic::Ordering::Relaxed)
{
return;
}
if mux.last_epg.is_some_and(|t| now() - t < interval) {
continue;
}
if state.tuners.is_tuned(mux.id) {
// already tuned – EIT is collected in the background
let _ = state.db.set_mux_epg_time(mux.id).await;
continue;
}
if !state.tuners.has_free_adapter() || state.scan.progress.lock().unwrap().running {
break;
}
state.epg_status.lock().unwrap().grabbing_mux = Some(mux.id);
match state.tuners.subscribe(&mux, Priority::Background).await {
Ok(mut sub) => {
tracing::info!("EPG: grabbing from {}", mux.params().describe());
let until = Instant::now() + Duration::from_secs(s.epg_grab_seconds as u64);
while Instant::now() < until {
if let Ok(None) =
tokio::time::timeout(Duration::from_secs(2), sub.recv()).await
{
break;
}
}
let _ = state.db.set_mux_epg_time(mux.id).await;
}
Err(e) => tracing::info!("EPG: skipped {}: {e:#}", mux.params().describe()),
}
let mut st = state.epg_status.lock().unwrap();
st.grabbing_mux = None;
st.last_grab = Some(now());
}
}
}
/// Periodic XMLTV import.
pub async fn xmltv_task(state: State) {
let mut last: Option<Instant> = None;
loop {
let s = state.settings();
let due = s.xmltv_interval_hours > 0
&& !s.xmltv_sources.iter().all(|x| !x.enabled)
&& last.is_none_or(|t| {
t.elapsed() > Duration::from_secs(s.xmltv_interval_hours as u64 * 3600)
});
if due {
last = Some(Instant::now());
import_all(&state).await;
}
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(300)) => {}
_ = state.xmltv_wakeup.notified() => { last = None; }
}
}
}
pub async fn import_all(state: &State) {
let sources = state.settings().xmltv_sources;
let mut results = Vec::new();
for src in sources.iter().filter(|s| s.enabled) {
match import_url(state, &src.url).await {
Ok((ch, ev)) => results.push(format!("{}: {ch} channels, {ev} programmes", src.url)),
Err(e) => results.push(format!("{}: error {e:#}", src.url)),
}
}
let mut st = state.epg_status.lock().unwrap();
st.last_xmltv = Some(now());
st.xmltv_result = results.join("\n");
}
pub async fn import_url(state: &State, url: &str) -> Result<(usize, usize)> {
let resp = state
.http
.get(url)
.send()
.await
.context("downloading XMLTV")?;
if !resp.status().is_success() {
bail!("HTTP {}", resp.status());
}
let body = resp.bytes().await?;
if body.len() > 200 * 1024 * 1024 {
bail!("XMLTV file too large");
}
let xml = if body.starts_with(&[0x1F, 0x8B]) {
let mut s = String::new();
flate2::read::MultiGzDecoder::new(&body[..])
.read_to_string(&mut s)
.context("decompressing gzip")?;
s
} else {
String::from_utf8_lossy(&body).into_owned()
};
import_xml(state, &xml).await
}
#[derive(Debug, Default)]
pub struct XmltvData {
pub channels: Vec<(String, Vec<String>)>,
pub programmes: Vec<XmltvProgramme>,
}
#[derive(Debug, Default, Clone)]
pub struct XmltvProgramme {
pub channel: String,
pub start: i64,
pub stop: i64,
pub title: String,
pub desc: String,
pub sub_title: String,
pub category: String,
}
/// XMLTV time format: "YYYYMMDDHHMMSS +HHMM".
pub fn parse_xmltv_time(s: &str) -> Option<i64> {
let s = s.trim();
let (dt, off) = match s.split_once(' ') {
Some((a, b)) => (a, Some(b.trim())),
None => (s, None),
};
let dt = if dt.len() >= 14 {
&dt[..14]
} else if dt.len() == 12 {
dt
} else {
return None;
};
let fmt = if dt.len() == 14 {
"%Y%m%d%H%M%S"
} else {
"%Y%m%d%H%M"
};
let naive = chrono::NaiveDateTime::parse_from_str(dt, fmt).ok()?;
let mut t = naive.and_utc().timestamp();
if let Some(o) = off {
let (sign, digits) = match o.as_bytes().first() {
Some(b'+') => (1, &o[1..]),
Some(b'-') => (-1, &o[1..]),
_ => (1, o),
};
if digits.len() == 4 {
let h: i64 = digits[..2].parse().ok()?;
let m: i64 = digits[2..].parse().ok()?;
t -= sign * (h * 3600 + m * 60);
}
}
Some(t)
}
pub fn parse_xmltv(xml: &str) -> Result<XmltvData> {
let mut r = Reader::from_str(xml);
let mut data = XmltvData::default();
let mut cur_chan: Option<(String, Vec<String>)> = None;
let mut cur_prog: Option<XmltvProgramme> = None;
let mut field: Option<String> = None;
let mut text = String::new();
loop {
match r.read_event()? {
Event::Start(e) if e.name().as_ref() == b"channel" => {
cur_chan = Some((attr(&e, b"id").unwrap_or_default(), vec![]));
}
Event::Start(e) if e.name().as_ref() == b"programme" => {
let mut p = XmltvProgramme {
channel: attr(&e, b"channel").unwrap_or_default(),
..Default::default()
};
p.start = attr(&e, b"start")
.and_then(|s| parse_xmltv_time(&s))
.unwrap_or(0);
p.stop = attr(&e, b"stop")
.and_then(|s| parse_xmltv_time(&s))
.unwrap_or(0);
cur_prog = Some(p);
}
Event::Start(e) => {
field = Some(String::from_utf8_lossy(e.name().as_ref()).into_owned());
text.clear();
}
Event::Text(t) => {
if field.is_some() {
text.push_str(&t.decode().unwrap_or_default());
}
}
Event::CData(t) => {
if field.is_some() {
text.push_str(&String::from_utf8_lossy(&t));
}
}
Event::GeneralRef(g) => {
if field.is_some() {
if let Ok(Some(c)) = g.resolve_char_ref() {
text.push(c);
} else if let Some(v) = g
.decode()
.ok()
.and_then(|n| quick_xml::escape::resolve_predefined_entity(&n))
{
text.push_str(v);
}
}
}
Event::End(e) => match e.name().as_ref() {
b"channel" => {
if let Some(c) = cur_chan.take() {
data.channels.push(c);
}
}
b"programme" => {
if let Some(p) = cur_prog.take() {
if p.start > 0 && p.stop > p.start && !p.title.is_empty() {
data.programmes.push(p);
}
}
}
_ => {
let txt = text.trim().to_string();
match (field.as_deref(), &mut cur_chan, &mut cur_prog) {
(Some("display-name"), Some(c), _) => c.1.push(txt),
(Some("title"), _, Some(p)) if p.title.is_empty() => p.title = txt,
(Some("sub-title"), _, Some(p)) if p.sub_title.is_empty() => {
p.sub_title = txt
}
(Some("desc"), _, Some(p)) if p.desc.is_empty() => p.desc = txt,
(Some("category"), _, Some(p)) if p.category.is_empty() => p.category = txt,
_ => {}
}
field = None;
text.clear();
}
},
Event::Eof => break,
_ => {}
}
}
Ok(data)
}
fn attr(e: &quick_xml::events::BytesStart, name: &[u8]) -> Option<String> {
e.attributes()
.flatten()
.find(|a| a.key.as_ref() == name)
.and_then(|a| a.unescape_value().ok().map(|v| v.into_owned()))
}
/// Channel name normalization for comparisons ("TVP 1 HD" == "tvp1").
pub fn norm_name(s: &str) -> String {
let lower = s.to_lowercase();
let mut t: String = lower
.chars()
.map(|c| match c {
'ą' => 'a',
'ć' => 'c',
'ę' => 'e',
'ł' => 'l',
'ń' => 'n',
'ó' => 'o',
'ś' => 's',
'ź' | 'ż' => 'z',
c => c,
})
.filter(|c| c.is_alphanumeric())
.collect();
for suf in ["uhd", "fhd", "hd", "sd", "pl"] {
if t.len() > suf.len() + 1 && t.ends_with(suf) {
t.truncate(t.len() - suf.len());
break;
}
}
t
}
pub fn map_xmltv_channels(
channels: &[Channel],
xml_channels: &[(String, Vec<String>)],
) -> HashMap<String, Vec<i64>> {
let mut map: HashMap<String, Vec<i64>> = HashMap::new();
for c in channels {
if !c.epg_id.is_empty() {
map.entry(c.epg_id.clone()).or_default().push(c.id);
continue;
}
let n = norm_name(&c.name);
if let Some((id, _)) = xml_channels
.iter()
.find(|(id, names)| names.iter().any(|x| norm_name(x) == n) || norm_name(id) == n)
{
map.entry(id.clone()).or_default().push(c.id);
}
}
map
}
/// Remembers the channel list from XMLTV imports (suggestions for "EPG ID" in the panel).
async fn remember_channels(state: &State, chans: &[(String, Vec<String>)]) {
let mut all: Vec<(String, Vec<String>)> = state
.db
.get_setting("xmltv_channels")
.await
.ok()
.flatten()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
for (id, names) in chans {
match all.iter_mut().find(|(i, _)| i == id) {
Some(e) => e.1 = names.clone(),
None => all.push((id.clone(), names.clone())),
}
}
all.sort_by_key(|a| a.0.to_lowercase());
all.truncate(20_000);
if let Ok(j) = serde_json::to_string(&all) {
let _ = state.db.set_setting("xmltv_channels", &j).await;
}
}
pub async fn xmltv_channels(state: &State) -> Vec<(String, Vec<String>)> {
state
.db
.get_setting("xmltv_channels")
.await
.ok()
.flatten()
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default()
}
pub async fn import_xml(state: &State, xml: &str) -> Result<(usize, usize)> {
let data = parse_xmltv(xml)?;
remember_channels(state, &data.channels).await;
let channels = state.db.channels().await?;
let map = map_xmltv_channels(&channels, &data.channels);
let horizon = now() - 6 * 3600;
let mut events = Vec::new();
for p in &data.programmes {
if p.stop < horizon {
continue;
}
let Some(ids) = map.get(&p.channel) else {
continue;
};
for &ch in ids {
events.push(NewEpg {
channel_id: ch,
start: p.start,
stop: p.stop,
title: p.title.clone(),
summary: p.sub_title.clone(),
description: p.desc.clone(),
genre: p.category.clone(),
rating: None,
});
}
}
let matched: usize = map.values().map(|v| v.len()).sum();
let n = events.len();
for chunk in events.chunks(2000) {
state.db.upsert_epg(chunk, "xmltv").await?;
}
Ok((matched, n))
}
fn xml_escape(s: &str) -> String {
let mut o = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => o.push_str("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
'\'' => o.push_str("&apos;"),
c if (c as u32) < 0x20 && c != '\n' && c != '\t' => {}
c => o.push(c),
}
}
o
}
fn xmltv_time(t: i64) -> String {
chrono::DateTime::from_timestamp(t, 0)
.map(|d| d.format("%Y%m%d%H%M%S +0000").to_string())
.unwrap_or_default()
}
/// Generates XMLTV for enabled channels.
pub async fn export_xmltv(state: &State, base: &str, query: &str) -> Result<String> {
let channels: Vec<Channel> = state
.db
.channels()
.await?
.into_iter()
.filter(|c| c.enabled)
.collect();
let events = state
.db
.epg_range(None, now() - 3 * 3600, now() + 14 * 86400)
.await?;
let mut out = String::with_capacity(64 * 1024 + events.len() * 300);
out.push_str(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE tv SYSTEM \"xmltv.dtd\">\n",
);
out.push_str("<tv generator-info-name=\"simply-dvb\">\n");
for c in &channels {
out.push_str(&format!(
" <channel id=\"{}\">\n <display-name>{}</display-name>\n",
xml_escape(&c.xmltv_id()),
xml_escape(&c.name)
));
out.push_str(&format!(" <display-name>{}</display-name>\n", c.number));
if !c.icon.is_empty() {
out.push_str(&format!(
" <icon src=\"{}\"/>\n",
xml_escape(&format!("{base}/icons/{}.png{query}", c.id))
));
}
out.push_str(" </channel>\n");
}
let by_id: HashMap<i64, &Channel> = channels.iter().map(|c| (c.id, c)).collect();
for e in &events {
let Some(c) = by_id.get(&e.channel_id) else {
continue;
};
out.push_str(&format!(
" <programme start=\"{}\" stop=\"{}\" channel=\"{}\">\n <title lang=\"pl\">{}</title>\n",
xmltv_time(e.start),
xmltv_time(e.stop),
xml_escape(&c.xmltv_id()),
xml_escape(&e.title)
));
if !e.summary.is_empty() && e.summary != e.title {
if e.description.is_empty() {
out.push_str(&format!(
" <desc lang=\"pl\">{}</desc>\n",
xml_escape(&e.summary)
));
} else {
out.push_str(&format!(
" <sub-title lang=\"pl\">{}</sub-title>\n",
xml_escape(&e.summary)
));
}
}
if !e.description.is_empty() {
out.push_str(&format!(
" <desc lang=\"pl\">{}</desc>\n",
xml_escape(&e.description)
));
}
if !e.genre.is_empty() {
out.push_str(&format!(
" <category lang=\"pl\">{}</category>\n",
xml_escape(&e.genre)
));
}
if let Some(r) = e.rating {
out.push_str(&format!(
" <rating system=\"DVB\"><value>{r}</value></rating>\n"
));
}
out.push_str(" </programme>\n");
}
out.push_str("</tv>\n");
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn xmltv_time_parsing() {
assert_eq!(
parse_xmltv_time("20240101120000 +0100"),
Some(1_704_106_800)
);
assert_eq!(
parse_xmltv_time("20240101110000 +0000"),
Some(1_704_106_800)
);
assert_eq!(parse_xmltv_time("202401011100"), Some(1_704_106_800));
assert_eq!(parse_xmltv_time("bad"), None);
}
#[test]
fn xmltv_parse_and_names() {
let xml = r#"<?xml version="1.0"?><tv>
<channel id="TVP1.pl"><display-name>TVP 1 HD</display-name></channel>
<programme start="20300101060000 +0100" stop="20300101070000 +0100" channel="TVP1.pl">
<title lang="pl">Kawa &amp; herbata</title><desc>Opis</desc><category>Magazyn</category></programme>
</tv>"#;
let d = parse_xmltv(xml).unwrap();
assert_eq!(
d.channels,
vec![("TVP1.pl".to_string(), vec!["TVP 1 HD".to_string()])]
);
assert_eq!(d.programmes.len(), 1);
assert_eq!(d.programmes[0].title, "Kawa & herbata");
assert_eq!(d.programmes[0].stop - d.programmes[0].start, 3600);
assert_eq!(norm_name("TVP 1 HD"), norm_name("tvp1"));
assert_eq!(norm_name("Polsat Śląsk"), "polsatslask");
assert_eq!(xml_escape("a<b>&\"'"), "a&lt;b&gt;&amp;&quot;&apos;");
}
}
+245
View File
@@ -0,0 +1,245 @@
//! Live HLS sessions: one session per (channel, profile), shared by viewers.
use crate::app::State;
use crate::pipeline::open_service;
use crate::stream::filter::ServiceFilter;
use crate::stream::segmenter::{Segment, Segmenter};
use crate::ts::packet::Aligner;
use crate::tuner::Priority;
use anyhow::{anyhow, Result};
use bytes::Bytes;
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::Notify;
pub struct HlsSession {
pub channel_id: i64,
pub profile: String,
segs: Mutex<VecDeque<Segment>>,
notify: Notify,
last_access: Mutex<Instant>,
pub error: Mutex<Option<String>>,
pub done: AtomicBool,
pub started: Instant,
pub adapter: Mutex<String>,
}
impl HlsSession {
pub fn touch(&self) {
*self.last_access.lock().unwrap() = Instant::now();
}
fn idle_for(&self) -> Duration {
self.last_access.lock().unwrap().elapsed()
}
pub fn segment(&self, seq: u64) -> Option<Bytes> {
self.segs
.lock()
.unwrap()
.iter()
.find(|s| s.seq == seq)
.map(|s| s.data.clone())
}
pub fn has_segments(&self) -> bool {
!self.segs.lock().unwrap().is_empty()
}
pub fn last_seq(&self) -> Option<u64> {
self.segs.lock().unwrap().back().map(|s| s.seq)
}
/// Waits for the first segment / an error.
pub async fn wait_ready(&self, timeout: Duration) -> Result<()> {
let deadline = Instant::now() + timeout;
loop {
let notified = self.notify.notified();
if self.has_segments() {
return Ok(());
}
if let Some(e) = self.error.lock().unwrap().clone() {
return Err(anyhow!(e));
}
if self.done.load(Ordering::Relaxed) {
return Err(anyhow!("session ended"));
}
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err(anyhow!("no data from the stream (timed out)"));
}
let _ = tokio::time::timeout(left.min(Duration::from_millis(500)), notified).await;
}
}
/// Waits until the segment with the given number is available.
pub async fn wait_segment(&self, seq: u64, timeout: Duration) -> Option<Bytes> {
let deadline = Instant::now() + timeout;
loop {
let notified = self.notify.notified();
if let Some(b) = self.segment(seq) {
return Some(b);
}
if self.last_seq().is_some_and(|l| l >= seq) || self.done.load(Ordering::Relaxed) {
return None;
}
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
return None;
}
let _ = tokio::time::timeout(left.min(Duration::from_millis(500)), notified).await;
}
}
/// Live playlist. `suffix` (e.g. "?token=...") is appended to segment URLs.
pub fn playlist(&self, suffix: &str) -> String {
let segs = self.segs.lock().unwrap();
let target = segs
.iter()
.map(|s| s.duration)
.fold(1.0f64, f64::max)
.ceil() as u64;
let first = segs.front().map(|s| s.seq).unwrap_or(0);
let mut out = format!("#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:{target}\n#EXT-X-MEDIA-SEQUENCE:{first}\n");
for s in segs.iter() {
out.push_str(&format!(
"#EXTINF:{:.3},\n{}.ts{}\n",
s.duration, s.seq, suffix
));
}
out
}
}
#[derive(Default)]
pub struct HlsManager {
sessions: Mutex<HashMap<(i64, String), Arc<HlsSession>>>,
}
impl HlsManager {
pub fn get(&self, channel_id: i64, profile: &str) -> Option<Arc<HlsSession>> {
self.sessions
.lock()
.unwrap()
.get(&(channel_id, profile.to_string()))
.cloned()
}
/// Returns an existing session or starts a new one.
pub fn get_or_start(&self, state: &State, channel_id: i64, profile: &str) -> Arc<HlsSession> {
let mut map = self.sessions.lock().unwrap();
let key = (channel_id, profile.to_string());
if let Some(s) = map.get(&key) {
if !s.done.load(Ordering::Relaxed) {
s.touch();
return s.clone();
}
}
let sess = Arc::new(HlsSession {
channel_id,
profile: profile.to_string(),
segs: Mutex::new(VecDeque::new()),
notify: Notify::new(),
last_access: Mutex::new(Instant::now()),
error: Mutex::new(None),
done: AtomicBool::new(false),
started: Instant::now(),
adapter: Mutex::new(String::new()),
});
map.insert(key, sess.clone());
let st = state.clone();
let s2 = sess.clone();
tokio::spawn(async move {
if let Err(e) = run_session(&st, &s2).await {
tracing::warn!("HLS channel {}: {e:#}", s2.channel_id);
*s2.error.lock().unwrap() = Some(format!("{e:#}"));
}
s2.done.store(true, Ordering::Relaxed);
s2.notify.notify_waiters();
});
sess
}
pub fn reap(&self) {
self.sessions.lock().unwrap().retain(|_, s| {
!s.done.load(Ordering::Relaxed) || s.idle_for() < Duration::from_secs(5)
});
}
pub fn list(&self) -> Vec<Arc<HlsSession>> {
self.sessions.lock().unwrap().values().cloned().collect()
}
pub fn stop_all(&self) {
for s in self.sessions.lock().unwrap().values() {
*s.last_access.lock().unwrap() = Instant::now() - Duration::from_secs(3600);
}
}
}
async fn run_session(state: &State, sess: &Arc<HlsSession>) -> Result<()> {
let settings = state.settings();
let idle = Duration::from_secs(settings.hls_idle_seconds as u64);
let window = settings.hls_window as usize;
let mut stream = open_service(state, sess.channel_id, &sess.profile, Priority::Normal).await?;
*sess.adapter.lock().unwrap() = stream.adapter.clone();
tracing::info!(
"HLS: starting channel {} ({}) profile {}",
stream.source.channel.name,
stream.adapter,
sess.profile
);
let mut segmenter = Segmenter::new(
ServiceFilter::new(None, None),
settings.hls_segment_seconds as f64,
0,
);
let mut aligner = Aligner::new();
let mut last_data = Instant::now();
loop {
if sess.idle_for() > idle {
tracing::info!(
"HLS: session for channel {} ended (no viewers)",
stream.source.channel.name
);
return Ok(());
}
match tokio::time::timeout(Duration::from_secs(1), stream.rx.recv()).await {
Ok(Some(chunk)) => {
last_data = Instant::now();
let mut new = Vec::new();
aligner.push(&chunk, |p| {
if let Some(s) = segmenter.push(p) {
new.push(s);
}
});
if !new.is_empty() {
let mut segs = sess.segs.lock().unwrap();
for s in new {
segs.push_back(s);
}
while segs.len() > window {
segs.pop_front();
}
drop(segs);
sess.notify.notify_waiters();
}
}
Ok(None) => {
let e = stream.error.lock().unwrap().clone();
return Err(anyhow!(if e.is_empty() {
"stream ended".to_string()
} else {
e
}));
}
Err(_) => {
if last_data.elapsed() > Duration::from_secs(15) {
return Err(anyhow!("no data from the tuner for 15 s"));
}
}
}
}
}
+267
View File
@@ -0,0 +1,267 @@
//! Splitting audio PES payloads into single frames (HTSP delivers one frame per packet)
//! and the frame durations needed for their timestamps.
use crate::ts::tables::EsKind;
/// One audio frame inside a PES payload.
#[derive(Debug, Clone, PartialEq)]
pub struct Frame {
pub start: usize,
pub len: usize,
/// Frame duration in 90 kHz units.
pub duration: u64,
pub sample_rate: u32,
pub channels: u32,
}
/// Parses the frame at the start of `b`; `None` when there is no valid header.
pub fn parse(kind: EsKind, b: &[u8]) -> Option<Frame> {
match kind {
EsKind::MpegAudio => mpeg_audio(b),
EsKind::Ac3 | EsKind::Eac3 => ac3(b),
EsKind::Aac => adts(b),
_ => None,
}
}
fn dur90k(samples: u64, rate: u32) -> u64 {
if rate == 0 {
0
} else {
samples * 90_000 / rate as u64
}
}
fn mpeg_audio(b: &[u8]) -> Option<Frame> {
if b.len() < 4 || b[0] != 0xFF || b[1] & 0xE0 != 0xE0 {
return None;
}
let version = (b[1] >> 3) & 3; // 3 = MPEG-1, 2 = MPEG-2, 0 = MPEG-2.5
let layer = (b[1] >> 1) & 3; // 3 = I, 2 = II, 1 = III
let br_idx = (b[2] >> 4) as usize;
let sr_idx = ((b[2] >> 2) & 3) as usize;
let pad = ((b[2] >> 1) & 1) as u32;
if version == 1 || layer == 0 || br_idx == 0 || br_idx == 15 || sr_idx == 3 {
return None;
}
const V1L1: [u32; 15] = [
0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,
];
const V1L2: [u32; 15] = [
0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,
];
const V1L3: [u32; 15] = [
0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
];
const V2L1: [u32; 15] = [
0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,
];
const V2L23: [u32; 15] = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
let v1 = version == 3;
let br = match (v1, layer) {
(true, 3) => V1L1[br_idx],
(true, 2) => V1L2[br_idx],
(true, _) => V1L3[br_idx],
(false, 3) => V2L1[br_idx],
(false, _) => V2L23[br_idx],
} * 1000;
let sr = [
[11025, 12000, 8000],
[0, 0, 0],
[22050, 24000, 16000],
[44100, 48000, 32000],
][version as usize][sr_idx];
let (len, samples) = match layer {
3 => ((12 * br / sr + pad) * 4, 384),
2 => (144 * br / sr + pad, 1152),
_ if v1 => (144 * br / sr + pad, 1152),
_ => (72 * br / sr + pad, 576),
};
let channels = if (b[3] >> 6) == 3 { 1 } else { 2 };
Some(Frame {
start: 0,
len: len as usize,
duration: dur90k(samples, sr),
sample_rate: sr,
channels,
})
}
fn ac3(b: &[u8]) -> Option<Frame> {
if b.len() < 7 || b[0] != 0x0B || b[1] != 0x77 {
return None;
}
let bsid = b[5] >> 3;
if bsid <= 10 {
// AC-3
let fscod = b[4] >> 6;
let frmsizecod = (b[4] & 0x3F) as usize;
const RATES: [u32; 19] = [
32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640,
];
let kbps = *RATES.get(frmsizecod / 2)?;
let (sr, words) = match fscod {
0 => (48_000, kbps * 2),
1 => (44_100, kbps * 320 / 147 + (frmsizecod as u32 & 1)),
2 => (32_000, kbps * 3),
_ => return None,
};
let acmod = b[6] >> 5;
let channels = [2, 1, 2, 3, 3, 4, 4, 5][acmod as usize];
Some(Frame {
start: 0,
len: words as usize * 2,
duration: dur90k(1536, sr),
sample_rate: sr,
channels,
})
} else {
// E-AC-3
let frmsiz = (((b[2] & 7) as usize) << 8) | b[3] as usize;
let fscod = b[4] >> 6;
let (sr, blocks) = if fscod == 3 {
([24_000, 22_050, 16_000, 0][((b[4] >> 4) & 3) as usize], 6)
} else {
(
[48_000, 44_100, 32_000][fscod as usize],
[1, 2, 3, 6][((b[4] >> 4) & 3) as usize],
)
};
if sr == 0 {
return None;
}
let acmod = (b[4] >> 1) & 7;
let channels = [2, 1, 2, 3, 3, 4, 4, 5][acmod as usize];
Some(Frame {
start: 0,
len: (frmsiz + 1) * 2,
duration: dur90k(blocks * 256, sr),
sample_rate: sr,
channels,
})
}
}
/// E-AC-3 dependent substream (belongs to the preceding independent frame).
pub fn is_eac3_dependent(b: &[u8]) -> bool {
b.len() > 5 && b[0] == 0x0B && b[1] == 0x77 && (b[5] >> 3) > 10 && (b[2] >> 6) == 1
}
fn adts(b: &[u8]) -> Option<Frame> {
if b.len() < 7 || b[0] != 0xFF || b[1] & 0xF6 != 0xF0 {
return None;
}
const SR: [u32; 13] = [
96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350,
];
let sr = *SR.get(((b[2] >> 2) & 0x0F) as usize)?;
let channels = (((b[2] & 1) << 2) | (b[3] >> 6)) as u32;
let len = (((b[3] & 3) as usize) << 11) | ((b[4] as usize) << 3) | (b[5] as usize >> 5);
let blocks = (b[6] & 3) as u64 + 1;
if len < 7 {
return None;
}
Some(Frame {
start: 0,
len,
duration: dur90k(1024 * blocks, sr),
sample_rate: sr,
channels: channels.max(1),
})
}
/// Splits an audio payload into frames. Bytes before the first valid header are skipped;
/// an incomplete frame at the end is returned as the remainder.
pub fn split(kind: EsKind, data: &[u8]) -> (Vec<Frame>, usize) {
let mut out: Vec<Frame> = Vec::new();
let mut i = 0;
while i < data.len() {
match parse(kind, &data[i..]) {
Some(f) if f.len > 0 => {
if i + f.len > data.len() {
return (out, i);
}
if kind == EsKind::Eac3 && is_eac3_dependent(&data[i..]) {
if let Some(last) = out.last_mut() {
if last.start + last.len == i {
last.len += f.len;
i += f.len;
continue;
}
}
}
out.push(Frame { start: i, ..f });
i += f.len;
}
// too short to hold a header: keep it for the next PES
_ if data.len() - i < 8 => return (out, i),
_ => i += 1,
}
}
(out, data.len())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mpeg1_layer2_48k_192kbps() {
// FF FD: MPEG-1 Layer II no CRC; C4 = 192 kbps, 48 kHz, no padding
let mut f = vec![0xFF, 0xFD, 0xA4, 0x00];
f.resize(576, 0);
let fr = parse(EsKind::MpegAudio, &f).unwrap();
assert_eq!(fr.len, 576);
assert_eq!(fr.duration, 2160); // 1152 samples @ 48 kHz = 24 ms
assert_eq!(fr.sample_rate, 48_000);
}
#[test]
fn ac3_and_split() {
// 48 kHz, frmsizecod 0x14 = 192 kbps -> 384 words = 768 bytes, bsid 8, acmod 2 (stereo)
let mut a = vec![0x0B, 0x77, 0, 0, 0x14, 8 << 3, 2 << 5];
a.resize(768, 0);
let fr = parse(EsKind::Ac3, &a).unwrap();
assert_eq!(fr.len, 768);
assert_eq!(fr.duration, 2880); // 1536 samples = 32 ms
let mut two = a.clone();
two.extend_from_slice(&a);
two.extend_from_slice(&[0x0B, 0x77]);
let (frames, rest) = split(EsKind::Ac3, &two);
assert_eq!(frames.len(), 2);
assert_eq!(frames[1].start, 768);
assert_eq!(rest, 1536);
}
#[test]
fn eac3_frame() {
// frmsiz 383 -> 768 bytes, fscod 0 (48 kHz), numblkscod 3 (6 blocks), bsid 16
let mut e = vec![0x0B, 0x77, 0x01, 0x7F, 0x34, 16 << 3];
e.resize(768, 0);
let fr = parse(EsKind::Eac3, &e).unwrap();
assert_eq!(fr.len, 768);
assert_eq!(fr.duration, 2880);
}
#[test]
fn adts_frame() {
// 48 kHz (idx 3), 2 channels, frame length 300
let len = 300usize;
let f = [
0xFF,
0xF1,
(1 << 6) | (3 << 2),
(2 << 6) | ((len >> 11) as u8 & 3),
(len >> 3) as u8,
((len & 7) << 5) as u8 | 0x1F,
0xFC,
];
let mut b = f.to_vec();
b.resize(len, 0);
let fr = parse(EsKind::Aac, &b).unwrap();
assert_eq!(
(fr.len, fr.sample_rate, fr.channels, fr.duration),
(300, 48_000, 2, 1920)
);
}
}
+1387
View File
File diff suppressed because it is too large. Load diff
+253
View File
@@ -0,0 +1,253 @@
//! HTSMSG binary format used by HTSP.
//!
//! A message is a 4-byte big-endian length (not counting itself) followed by fields:
//! `type:u8 namelen:u8 datalen:u32be name data`. Integers (S64) are little-endian with
//! leading zero bytes dropped; maps and lists nest the same field encoding (list members
//! have empty names).
use anyhow::{bail, Result};
const T_MAP: u8 = 1;
const T_S64: u8 = 2;
const T_STR: u8 = 3;
const T_BIN: u8 = 4;
const T_LIST: u8 = 5;
const T_DBL: u8 = 6;
const T_BOOL: u8 = 7;
const T_UUID: u8 = 8;
/// Largest message accepted from a client.
pub const MAX_MESSAGE: usize = 16 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq)]
pub enum Val {
Map(Msg),
S64(i64),
Str(String),
Bin(Vec<u8>),
List(Vec<Val>),
Dbl(f64),
Bool(bool),
}
/// An HTSMSG map (field order is preserved).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Msg(pub Vec<(String, Val)>);
impl Msg {
pub fn new() -> Self {
Self::default()
}
pub fn method(name: &str) -> Self {
Self::new().str("method", name)
}
pub fn set(mut self, k: &str, v: Val) -> Self {
self.0.push((k.to_string(), v));
self
}
pub fn int(self, k: &str, v: i64) -> Self {
self.set(k, Val::S64(v))
}
pub fn str(self, k: &str, v: &str) -> Self {
self.set(k, Val::Str(v.to_string()))
}
pub fn bin(self, k: &str, v: Vec<u8>) -> Self {
self.set(k, Val::Bin(v))
}
pub fn map(self, k: &str, v: Msg) -> Self {
self.set(k, Val::Map(v))
}
pub fn list(self, k: &str, v: Vec<Val>) -> Self {
self.set(k, Val::List(v))
}
/// Adds an optional string field only when it is not empty.
pub fn str_opt(self, k: &str, v: &str) -> Self {
if v.is_empty() {
self
} else {
self.str(k, v)
}
}
pub fn get(&self, k: &str) -> Option<&Val> {
self.0.iter().find(|(n, _)| n == k).map(|(_, v)| v)
}
pub fn get_i64(&self, k: &str) -> Option<i64> {
match self.get(k)? {
Val::S64(v) => Some(*v),
Val::Bool(b) => Some(*b as i64),
Val::Str(s) => s.trim().parse().ok(),
Val::Dbl(d) => Some(*d as i64),
_ => None,
}
}
pub fn get_str(&self, k: &str) -> Option<&str> {
match self.get(k)? {
Val::Str(s) => Some(s),
_ => None,
}
}
pub fn get_bin(&self, k: &str) -> Option<&[u8]> {
match self.get(k)? {
Val::Bin(b) => Some(b),
Val::Str(s) => Some(s.as_bytes()),
_ => None,
}
}
/// Encodes the message including the 4-byte length prefix.
pub fn encode(&self) -> Vec<u8> {
let mut body = Vec::with_capacity(64);
encode_fields(&self.0, &mut body);
let mut out = Vec::with_capacity(body.len() + 4);
out.extend_from_slice(&(body.len() as u32).to_be_bytes());
out.extend_from_slice(&body);
out
}
/// Decodes a message body (without the length prefix).
pub fn decode(body: &[u8]) -> Result<Msg> {
Ok(Msg(decode_fields(body, false)?
.into_iter()
.map(|(k, v)| (k.unwrap_or_default(), v))
.collect()))
}
}
fn s64_bytes(v: i64) -> Vec<u8> {
let b = v.to_le_bytes();
let mut n = 8;
while n > 0 && b[n - 1] == 0 {
n -= 1;
}
b[..n].to_vec()
}
fn encode_value(v: &Val) -> (u8, Vec<u8>) {
match v {
Val::Map(m) => {
let mut d = Vec::new();
encode_fields(&m.0, &mut d);
(T_MAP, d)
}
Val::S64(i) => (T_S64, s64_bytes(*i)),
Val::Str(s) => (T_STR, s.as_bytes().to_vec()),
Val::Bin(b) => (T_BIN, b.clone()),
Val::List(l) => {
let mut d = Vec::new();
for item in l {
push_field(&mut d, "", item);
}
(T_LIST, d)
}
// tvheadend sends doubles as their text representation
Val::Dbl(f) => (T_DBL, format!("{f}").into_bytes()),
Val::Bool(b) => (T_BOOL, if *b { vec![1] } else { vec![] }),
}
}
fn push_field(out: &mut Vec<u8>, name: &str, v: &Val) {
let (t, data) = encode_value(v);
let name = &name.as_bytes()[..name.len().min(255)];
out.push(t);
out.push(name.len() as u8);
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(name);
out.extend_from_slice(&data);
}
fn encode_fields(fields: &[(String, Val)], out: &mut Vec<u8>) {
for (k, v) in fields {
push_field(out, k, v);
}
}
fn decode_fields(mut b: &[u8], list: bool) -> Result<Vec<(Option<String>, Val)>> {
let mut out = Vec::new();
while !b.is_empty() {
if b.len() < 6 {
bail!("truncated HTSMSG field");
}
let t = b[0];
let nl = b[1] as usize;
let dl = u32::from_be_bytes([b[2], b[3], b[4], b[5]]) as usize;
if b.len() < 6 + nl + dl {
bail!("truncated HTSMSG field data");
}
let name = String::from_utf8_lossy(&b[6..6 + nl]).to_string();
let data = &b[6 + nl..6 + nl + dl];
b = &b[6 + nl + dl..];
let v = match t {
T_MAP => Val::Map(Msg(decode_fields(data, false)?
.into_iter()
.map(|(k, v)| (k.unwrap_or_default(), v))
.collect())),
T_S64 => {
if data.len() > 8 {
bail!("S64 longer than 8 bytes");
}
let mut buf = [0u8; 8];
buf[..data.len()].copy_from_slice(data);
Val::S64(i64::from_le_bytes(buf))
}
T_STR => Val::Str(String::from_utf8_lossy(data).to_string()),
T_BIN | T_UUID => Val::Bin(data.to_vec()),
T_LIST => Val::List(
decode_fields(data, true)?
.into_iter()
.map(|(_, v)| v)
.collect(),
),
T_DBL => {
let s = String::from_utf8_lossy(data);
match s.trim().parse::<f64>() {
Ok(f) => Val::Dbl(f),
Err(_) if data.len() == 8 => {
Val::Dbl(f64::from_le_bytes(data.try_into().unwrap()))
}
Err(_) => Val::Dbl(0.0),
}
}
T_BOOL => Val::Bool(data.first().is_some_and(|x| *x != 0)),
other => bail!("unknown HTSMSG type {other}"),
};
out.push(((!list).then_some(name), v));
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn s64_encoding_matches_spec() {
// examples from the HTSMSG documentation
assert_eq!(s64_bytes(100), vec![0x64]);
assert_eq!(s64_bytes(1337), vec![0x39, 0x05]);
assert_eq!(s64_bytes(0), Vec::<u8>::new());
assert_eq!(s64_bytes(-1), vec![0xff; 8]);
}
#[test]
fn roundtrip() {
let m = Msg::method("hello")
.int("htspversion", 34)
.int("neg", -5)
.bin("challenge", vec![1, 2, 3])
.list("caps", vec![Val::Str("a".into()), Val::S64(7)])
.map("inner", Msg::new().str("x", "zażółć"));
let enc = m.encode();
assert_eq!(
u32::from_be_bytes(enc[..4].try_into().unwrap()) as usize,
enc.len() - 4
);
let d = Msg::decode(&enc[4..]).unwrap();
assert_eq!(d, m);
assert_eq!(d.get_i64("htspversion"), Some(34));
assert_eq!(d.get_i64("neg"), Some(-5));
// field layout: type, namelen, datalen (big-endian), name, data
assert_eq!(&enc[4..10], &[T_STR, 6, 0, 0, 0, 5]);
assert_eq!(&enc[10..21], b"methodhello");
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Channel icons: lookup in logo repositories, uploads, local cache.
use crate::app::State;
use crate::db::Channel;
use anyhow::{bail, Result};
use std::path::PathBuf;
/// "slug" variants of a channel name, e.g. "TVP1 HD" -> ["tvp1", "tvp-1", "tvp1-hd", ...].
pub fn slug_candidates(name: &str) -> Vec<String> {
let lower: String = name
.to_lowercase()
.chars()
.map(|c| match c {
'ą' => 'a',
'ć' => 'c',
'ę' => 'e',
'ł' => 'l',
'ń' => 'n',
'ó' => 'o',
'ś' => 's',
'ź' | 'ż' => 'z',
'+' => ' ',
c if c.is_alphanumeric() => c,
_ => ' ',
})
.collect();
let words: Vec<&str> = lower.split_whitespace().collect();
let strip: Vec<&str> = words
.iter()
.copied()
.filter(|w| !matches!(*w, "hd" | "sd" | "uhd" | "fhd" | "4k"))
.collect();
let mut out: Vec<String> = Vec::new();
fn push(out: &mut Vec<String>, s: String) {
if !s.is_empty() && !out.contains(&s) {
out.push(s);
}
}
for base in [&strip, &words] {
let joined = base.join("-");
push(&mut out, joined.clone());
// split letters from digits: "tvp1" -> "tvp-1"
let mut sep = String::new();
let mut prev: Option<char> = None;
for c in joined.chars() {
if let Some(p) = prev {
if (p.is_ascii_alphabetic() && c.is_ascii_digit())
|| (p.is_ascii_digit() && c.is_ascii_alphabetic())
{
sep.push('-');
}
}
sep.push(c);
prev = Some(c);
}
push(&mut out, sep);
push(&mut out, base.concat());
}
for w in ["plus", "hd"] {
if let Some(x) = out.first().cloned() {
push(&mut out, format!("{x}-{w}"));
}
}
out
}
pub fn icon_path(state: &State, channel_id: i64) -> PathBuf {
state.data_path("icons").join(format!("{channel_id}.img"))
}
pub fn sniff_image(data: &[u8]) -> Option<&'static str> {
if data.starts_with(b"\x89PNG") {
Some("image/png")
} else if data.starts_with(&[0xFF, 0xD8, 0xFF]) {
Some("image/jpeg")
} else if data.starts_with(b"GIF8") {
Some("image/gif")
} else if data.len() > 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
Some("image/webp")
} else {
let head = String::from_utf8_lossy(&data[..data.len().min(512)]).to_lowercase();
if head.contains("<svg") {
Some("image/svg+xml")
} else {
None
}
}
}
pub async fn save_icon(state: &State, channel: &mut Channel, data: &[u8]) -> Result<()> {
if data.len() > 2 * 1024 * 1024 {
bail!("icon file is too large (max. 2 MiB)");
}
if sniff_image(data).is_none() {
bail!("unsupported image format (PNG, JPEG, GIF, WebP, SVG)");
}
let path = icon_path(state, channel.id);
tokio::fs::create_dir_all(path.parent().unwrap()).await?;
tokio::fs::write(&path, data).await?;
channel.icon = "local".into();
state.db.update_channel(channel).await?;
Ok(())
}
/// Progress of a background icon search started from the channel list.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct IconJob {
pub running: bool,
pub total: usize,
pub done: usize,
pub found: Vec<String>,
pub missing: Vec<String>,
}
/// Looks up an icon for a channel in the configured sources. Returns the URL it was fetched from.
pub async fn find_icon(state: &State, channel: &mut Channel) -> Result<Option<String>> {
let templates = state.settings().icon_sources;
for t in templates {
for slug in slug_candidates(&channel.name) {
let url = t.replace("{slug}", &slug).replace("{name}", &channel.name);
let Ok(resp) = state
.http
.get(&url)
.timeout(std::time::Duration::from_secs(10))
.send()
.await
else {
continue;
};
if !resp.status().is_success() {
continue;
}
let Ok(body) = resp.bytes().await else {
continue;
};
if sniff_image(&body).is_some() {
save_icon(state, channel, &body).await?;
return Ok(Some(url));
}
}
}
Ok(None)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slugs() {
let s = slug_candidates("TVP1 HD");
assert_eq!(s[0], "tvp1");
assert!(s.contains(&"tvp-1".to_string()));
assert!(s.contains(&"tvp1-hd".to_string()));
let p = slug_candidates("Polsat Śląsk");
assert_eq!(p[0], "polsat-slask");
let q = slug_candidates("TVN24 BiS");
assert!(q.contains(&"tvn-24-bis".to_string()));
assert_eq!(sniff_image(b"\x89PNG\r\n"), Some("image/png"));
assert_eq!(sniff_image(b"<?xml?><svg xmlns"), Some("image/svg+xml"));
assert_eq!(sniff_image(b"hello"), None);
}
}
+22
View File
@@ -0,0 +1,22 @@
//! simply-dvb – lightweight DVB-T/T2/C television server.
pub mod acl;
pub mod app;
pub mod auth;
pub mod clients;
pub mod db;
pub mod dvb;
pub mod epg;
pub mod hls;
pub mod htsp;
pub mod icons;
pub mod logbuf;
pub mod m3u;
pub mod pipeline;
pub mod recorder;
pub mod scanjob;
pub mod settings;
pub mod stats;
pub mod stream;
pub mod ts;
pub mod tuner;
pub mod web;
+262
View File
@@ -0,0 +1,262 @@
//! In-memory log buffer for the panel's "Logs" page.
//!
//! A `tracing` layer keeps the last few thousand events in a ring buffer, each tagged with
//! a category derived from its target (module path or an explicit `target:`), so the panel
//! can show application, tuner, streaming, access, EPG and recording logs separately.
use serde::Serialize;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use tracing::field::{Field, Visit};
use tracing::{Event, Level, Subscriber};
use tracing_subscriber::layer::Context;
use tracing_subscriber::Layer;
/// Entries kept in memory.
pub const KEEP: usize = 4000;
#[derive(Debug, Clone, Serialize)]
pub struct Entry {
/// Monotonic sequence number (clients fetch entries newer than the last one they saw).
pub seq: u64,
/// Unix time with milliseconds.
pub t_ms: i64,
pub level: &'static str,
pub category: &'static str,
pub target: String,
pub message: String,
}
#[derive(Default)]
pub struct LogBuffer {
entries: Mutex<VecDeque<Entry>>,
seq: AtomicU64,
}
static GLOBAL: OnceLock<LogBuffer> = OnceLock::new();
/// The process-wide buffer (installed by [`layer`]).
pub fn global() -> &'static LogBuffer {
GLOBAL.get_or_init(LogBuffer::default)
}
/// Category names in display order with a short description.
pub const CATEGORIES: &[(&str, &str)] = &[
("app", "Application: start-up, settings, panel, API"),
(
"tuner",
"Tuners and devices: adapters, tuning, lock, scanning",
),
(
"stream",
"Streaming: HLS, MPEG-TS, HTSP, transcoding, clients",
),
(
"access",
"Access: logins, tokens, allowed and denied requests",
),
("epg", "EPG: over-the-air grabbing, XMLTV imports"),
(
"recorder",
"Recording: schedule, running recordings, cleanup",
),
("system", "System: HTTP server, libraries"),
];
/// Maps a tracing target to a category.
pub fn category(target: &str) -> &'static str {
let t = target.strip_prefix("simply_dvb::").unwrap_or(target);
let head = t.split("::").next().unwrap_or(t);
match head {
"access" | "auth" => "access",
"dvb" | "tuner" | "scanjob" | "scan" => "tuner",
"hls" | "pipeline" | "htsp" | "clients" | "stream" => "stream",
"epg" | "icons" => "epg",
"recorder" => "recorder",
"simply_dvb" | "app" | "web" | "settings" | "db" | "main" | "stats" => "app",
_ if target.starts_with("simply_dvb") => "app",
_ => "system",
}
}
impl LogBuffer {
pub fn push(&self, level: Level, target: &str, message: String) {
let seq = self.seq.fetch_add(1, Ordering::Relaxed) + 1;
let e = Entry {
seq,
t_ms: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0),
level: match level {
Level::ERROR => "error",
Level::WARN => "warn",
Level::INFO => "info",
Level::DEBUG => "debug",
Level::TRACE => "trace",
},
category: category(target),
target: target.to_string(),
message,
};
let mut g = self.entries.lock().unwrap();
g.push_back(e);
while g.len() > KEEP {
g.pop_front();
}
}
/// Entries after `since` (0 = all), optionally filtered; newest last, at most `limit`.
pub fn query(
&self,
since: u64,
category: Option<&str>,
min_level: Option<&str>,
text: Option<&str>,
limit: usize,
) -> Vec<Entry> {
let rank = |l: &str| match l {
"error" => 4,
"warn" => 3,
"info" => 2,
"debug" => 1,
_ => 0,
};
let min = min_level.map(rank).unwrap_or(0);
let text = text.map(|t| t.to_lowercase()).filter(|t| !t.is_empty());
let g = self.entries.lock().unwrap();
let mut out: Vec<Entry> = g
.iter()
.rev()
.filter(|e| e.seq > since)
.filter(|e| category.is_none_or(|c| c == e.category))
.filter(|e| rank(e.level) >= min)
.filter(|e| {
text.as_ref().is_none_or(|t| {
e.message.to_lowercase().contains(t) || e.target.contains(t.as_str())
})
})
.take(limit)
.cloned()
.collect();
out.reverse();
out
}
/// Number of entries per category and the latest sequence number.
pub fn summary(&self) -> (Vec<(&'static str, usize, usize)>, u64) {
let g = self.entries.lock().unwrap();
let counts = CATEGORIES
.iter()
.map(|(c, _)| {
let all = g.iter().filter(|e| e.category == *c).count();
let bad = g
.iter()
.filter(|e| e.category == *c && (e.level == "warn" || e.level == "error"))
.count();
(*c, all, bad)
})
.collect();
(counts, self.seq.load(Ordering::Relaxed))
}
/// Plain-text dump (for the download button).
pub fn dump(&self) -> String {
let g = self.entries.lock().unwrap();
let mut s = String::with_capacity(g.len() * 100);
for e in g.iter() {
let t = chrono::DateTime::from_timestamp_millis(e.t_ms)
.map(|d| {
d.with_timezone(&chrono::Local)
.format("%Y-%m-%d %H:%M:%S%.3f")
.to_string()
})
.unwrap_or_default();
s.push_str(&format!(
"{t} {:5} [{}] {}: {}\n",
e.level.to_uppercase(),
e.category,
e.target,
e.message
));
}
s
}
}
struct MessageVisitor {
message: String,
fields: Vec<String>,
}
impl Visit for MessageVisitor {
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
if field.name() == "message" {
self.message = format!("{value:?}");
} else {
self.fields.push(format!("{}={value:?}", field.name()));
}
}
fn record_str(&mut self, field: &Field, value: &str) {
if field.name() == "message" {
self.message = value.to_string();
} else {
self.fields.push(format!("{}={value}", field.name()));
}
}
}
/// The tracing layer feeding the buffer.
pub struct BufferLayer;
impl<S: Subscriber> Layer<S> for BufferLayer {
fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
let mut v = MessageVisitor {
message: String::new(),
fields: Vec::new(),
};
event.record(&mut v);
let mut msg = v.message;
if !v.fields.is_empty() {
if !msg.is_empty() {
msg.push(' ');
}
msg.push_str(&v.fields.join(" "));
}
global().push(*event.metadata().level(), event.metadata().target(), msg);
}
}
/// Creates the layer (call once when installing the subscriber).
pub fn layer() -> BufferLayer {
BufferLayer
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn categories_and_query() {
assert_eq!(category("simply_dvb::tuner"), "tuner");
assert_eq!(category("simply_dvb::dvb::linux"), "tuner");
assert_eq!(category("access"), "access");
assert_eq!(category("simply_dvb::htsp"), "stream");
assert_eq!(category("hyper_util::client"), "system");
assert_eq!(category("simply_dvb"), "app");
let b = LogBuffer::default();
b.push(Level::INFO, "simply_dvb::epg", "import done".into());
b.push(Level::WARN, "simply_dvb::tuner", "no lock".into());
b.push(Level::INFO, "access", "signed in admin".into());
assert_eq!(b.query(0, None, None, None, 100).len(), 3);
assert_eq!(b.query(0, Some("tuner"), None, None, 100).len(), 1);
assert_eq!(b.query(0, None, Some("warn"), None, 100).len(), 1);
assert_eq!(b.query(0, None, None, Some("ADMIN"), 100).len(), 1);
assert_eq!(b.query(2, None, None, None, 100).len(), 1);
let (counts, last) = b.summary();
assert_eq!(last, 3);
assert_eq!(counts.iter().find(|c| c.0 == "tuner").unwrap().2, 1);
assert!(b.dump().contains("[access]"));
}
}
+128
View File
@@ -0,0 +1,128 @@
//! M3U playlist (format compatible with IPTV apps: tvg-id, tvg-logo, group-title).
use crate::db::Channel;
pub struct M3uOptions<'a> {
pub base: &'a str,
/// "hls" or "ts"
pub format: &'a str,
pub profile: &'a str,
/// Authentication parameters appended to URLs (e.g. "token=abc").
pub auth: &'a str,
}
fn attr(s: &str) -> String {
s.replace('"', "'").replace(['\n', '\r'], " ")
}
pub fn build(channels: &[Channel], o: &M3uOptions) -> String {
let q = |extra: &[(&str, &str)]| -> String {
let mut parts: Vec<String> = Vec::new();
for (k, v) in extra {
if !v.is_empty() {
parts.push(format!("{k}={v}"));
}
}
if !o.auth.is_empty() {
parts.push(o.auth.to_string());
}
if parts.is_empty() {
String::new()
} else {
format!("?{}", parts.join("&"))
}
};
let mut out = format!(
"#EXTM3U url-tvg=\"{0}/epg.xml{1}\" x-tvg-url=\"{0}/epg.xml{1}\"\n",
o.base,
q(&[])
);
let profile = if o.profile == "pass" { "" } else { o.profile };
for c in channels.iter().filter(|c| c.enabled) {
let logo = if c.icon.is_empty() {
String::new()
} else {
format!(" tvg-logo=\"{}/icons/{}.png{}\"", o.base, c.id, q(&[]))
};
let group = if c.grp.is_empty() {
String::new()
} else {
format!(" group-title=\"{}\"", attr(&c.grp))
};
out.push_str(&format!(
"#EXTINF:-1 tvg-id=\"{}\" tvg-chno=\"{}\" tvg-name=\"{}\"{}{},{}\n",
attr(&c.xmltv_id()),
c.number,
attr(&c.name),
logo,
group,
c.name.replace(['\n', '\r'], " ")
));
let url = if o.format == "hls" {
format!(
"{}/hls/{}/index.m3u8{}",
o.base,
c.id,
q(&[("profile", profile)])
)
} else {
format!(
"{}/stream/{}.ts{}",
o.base,
c.id,
q(&[("profile", profile)])
)
};
out.push_str(&url);
out.push('\n');
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn ch(id: i64, n: i64, name: &str) -> Channel {
Channel {
id,
number: n,
name: name.into(),
service_id: None,
enabled: true,
grp: "TV".into(),
icon: "local".into(),
epg_id: String::new(),
share_token: None,
share_enabled: false,
created_at: 0,
}
}
#[test]
fn m3u_output() {
let chans = vec![ch(5, 1, "TVP1 HD"), ch(6, 2, "Polsat \"News\"")];
let s = build(
&chans,
&M3uOptions {
base: "http://tv:9982",
format: "hls",
profile: "pass",
auth: "token=abc",
},
);
assert!(s.starts_with("#EXTM3U url-tvg=\"http://tv:9982/epg.xml?token=abc\""));
assert!(s.contains("tvg-chno=\"1\" tvg-name=\"TVP1 HD\" tvg-logo=\"http://tv:9982/icons/5.png?token=abc\" group-title=\"TV\",TVP1 HD\nhttp://tv:9982/hls/5/index.m3u8?token=abc\n"));
assert!(s.contains("tvg-name=\"Polsat 'News'\""));
let t = build(
&chans,
&M3uOptions {
base: "http://tv",
format: "ts",
profile: "aac",
auth: "",
},
);
assert!(t.contains("http://tv/stream/5.ts?profile=aac\n"));
}
}
+613
View File
@@ -0,0 +1,613 @@
use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use simply_dvb::app::{AppState, Options};
use simply_dvb::db::Db;
use simply_dvb::{auth, dvb, epg, recorder, web};
use std::io::{BufRead, Write};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
#[derive(Parser)]
#[command(
name = "simply-dvb",
version,
about = "Lightweight DVB-T/T2/C server: HLS, M3U, EPG/XMLTV, recording and a web panel"
)]
struct Cli {
/// Data directory (database, icons, recordings)
#[arg(
long,
env = "SIMPLY_DVB_DATA_DIR",
default_value = "/var/lib/simply-dvb",
global = true
)]
data_dir: PathBuf,
/// DVB device directory
#[arg(
long,
env = "SIMPLY_DVB_DEV_ROOT",
default_value = "/dev/dvb",
global = true
)]
dev_root: String,
/// Directory(ies) with .ts files acting as a virtual adapter (tests, demo)
#[arg(
long = "virtual-dir",
env = "SIMPLY_DVB_VIRTUAL_DIR",
value_delimiter = ',',
global = true
)]
virtual_dirs: Vec<String>,
#[command(subcommand)]
cmd: Option<Cmd>,
}
#[derive(Subcommand)]
enum Cmd {
/// Runs the server (default)
Serve {
/// Address of the web panel and API (streams are available here too)
#[arg(long, env = "SIMPLY_DVB_LISTEN", default_value = "0.0.0.0:9980")]
listen: String,
/// Separate stream/playlist/EPG port without the panel – 9981 by default, like tvheadend's HTTP port
/// ("off" disables it)
#[arg(long, env = "SIMPLY_DVB_STREAM_LISTEN", default_value = "0.0.0.0:9981")]
stream_listen: String,
/// HTSP port (tvheadend's binary protocol for Kodi, TVHClient, PVR apps) – 9982 by default
/// ("off" disables it)
#[arg(long, env = "SIMPLY_DVB_HTSP_LISTEN", default_value = "0.0.0.0:9982")]
htsp_listen: String,
},
/// Manage panel users
User {
#[command(subcommand)]
cmd: UserCmd,
},
/// List detected DVB adapters
Adapters,
/// Quick tuner test: tune a frequency and list its services
Tune {
/// Frequency in MHz
#[arg(long)]
freq: f64,
/// dvbt, dvbt2 or dvbc
#[arg(long, default_value = "dvbt2")]
system: String,
/// Channel bandwidth (MHz) – DVB-T/T2
#[arg(long, default_value_t = 8)]
bandwidth: u32,
/// DVB-T2: PLP id
#[arg(long)]
plp: Option<u32>,
/// DVB-C: symbol rate in kS/s
#[arg(long, default_value_t = 6900)]
symbol_rate: u32,
/// DVB-C: auto, qam64, qam128, qam256
#[arg(long)]
modulation: Option<String>,
/// Adapter id (e.g. adapter0)
#[arg(long)]
adapter: Option<String>,
},
/// Generates sample multiplexes (.ts) for the virtual adapter
GenDemo {
#[arg(long)]
out: PathBuf,
},
}
#[derive(Subcommand)]
enum UserCmd {
/// Adds a user (password read from standard input)
Add {
name: String,
#[arg(long, default_value = "admin")]
role: String,
},
/// Changes a user's password (password read from standard input)
Passwd { name: String },
/// List users
List,
}
fn read_password() -> Result<String> {
eprint!("Password: ");
std::io::stderr().flush().ok();
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line)?;
let pw = line.trim_end_matches(['\r', '\n']).to_string();
if pw.chars().count() < 8 {
bail!("password must be at least 8 characters");
}
Ok(pw)
}
#[tokio::main]
async fn main() -> Result<()> {
{
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "simply_dvb=info,access=info,warn".into());
// console output + the in-memory buffer shown on the panel's Logs page
tracing_subscriber::registry()
.with(filter)
.with(tracing_subscriber::fmt::layer())
.with(simply_dvb::logbuf::layer())
.init();
}
let cli = Cli::parse();
let opts = Options {
data_dir: cli.data_dir.clone(),
dev_root: cli.dev_root.clone(),
virtual_dirs: cli.virtual_dirs.clone(),
stream_port: None,
htsp_port: None,
};
let default_listen =
std::env::var("SIMPLY_DVB_LISTEN").unwrap_or_else(|_| "0.0.0.0:9980".into());
let default_stream =
std::env::var("SIMPLY_DVB_STREAM_LISTEN").unwrap_or_else(|_| "0.0.0.0:9981".into());
let default_htsp =
std::env::var("SIMPLY_DVB_HTSP_LISTEN").unwrap_or_else(|_| "0.0.0.0:9982".into());
let mut opts = opts;
match cli.cmd.unwrap_or(Cmd::Serve {
listen: default_listen,
stream_listen: default_stream,
htsp_listen: default_htsp,
}) {
Cmd::Serve {
listen,
stream_listen,
htsp_listen,
} => {
// values come from /etc/default (systemd does not strip "# comments" after a value)
let clean = |v: &str| {
v.split('#')
.next()
.unwrap_or("")
.trim()
.trim_matches('"')
.to_string()
};
let optional = |v: &str, name: &str| -> Result<Option<SocketAddr>> {
Ok(match clean(v).as_str() {
"" | "off" | "none" | "0" => None,
v => Some(v.parse::<SocketAddr>().with_context(|| {
format!(
"invalid --{name} / SIMPLY_DVB_{}: “{v}” (expected e.g. 0.0.0.0:9981)",
match name {
"listen" => "LISTEN",
"stream-listen" => "STREAM_LISTEN",
_ => "HTSP_LISTEN",
}
)
})?),
})
};
let listen = optional(&listen, "listen")?
.context("the panel address (SIMPLY_DVB_LISTEN) cannot be off")?;
let stream = optional(&stream_listen, "stream-listen")?;
let htsp = optional(&htsp_listen, "htsp-listen")?;
opts.stream_port = stream.map(|a| a.port());
opts.htsp_port = htsp.map(|a| a.port());
serve(opts, listen, stream, htsp).await
}
Cmd::User { cmd } => {
let db = open_db(&opts).await?;
match cmd {
UserCmd::Add { name, role } => {
if role != "admin" && role != "viewer" {
bail!("role: admin or viewer");
}
let pw = read_password()?;
db.create_user(&name, &auth::hash_password(&pw)?, &role)
.await?;
println!("User {name} added ({role})");
}
UserCmd::Passwd { name } => {
let u = db.user_by_name(&name).await?.context("no such user")?;
let pw = read_password()?;
db.update_user(u.id, Some(&auth::hash_password(&pw)?), None)
.await?;
println!("Password changed for user {name}");
}
UserCmd::List => {
for u in db.users().await? {
println!("{}\t{}", u.username, u.role);
}
}
}
Ok(())
}
Cmd::Adapters => {
let list = dvb::discover(&opts.dev_root);
if list.is_empty() {
println!("No DVB adapters detected in {}", opts.dev_root);
}
for a in list {
let sys: Vec<_> = a.delivery_systems.iter().map(|d| d.label()).collect();
println!("{}\t{}\t{}\t{}", a.id, a.name, a.path, sys.join(", "));
}
Ok(())
}
Cmd::Tune {
freq,
system,
bandwidth,
adapter,
plp,
symbol_rate,
modulation,
} => {
let mut list = dvb::discover(&opts.dev_root);
for (i, d) in opts.virtual_dirs.iter().enumerate() {
list.push(dvb::AdapterInfo {
id: format!("virtual{i}"),
name: "wirtualny".into(),
kind: "virtual".into(),
path: d.clone(),
delivery_systems: vec![
dvb::DeliverySystem::Dvbt,
dvb::DeliverySystem::Dvbt2,
dvb::DeliverySystem::Dvbc,
],
});
}
let info = list
.into_iter()
.find(|a| adapter.as_deref().is_none_or(|id| id == a.id))
.context("adapter not found")?;
let delsys =
dvb::DeliverySystem::parse(&system).context("system: dvbt / dvbt2 / dvbc")?;
let params = dvb::TuneParams {
delsys,
frequency_hz: (freq * 1e6).round() as u64,
bandwidth_hz: bandwidth * 1_000_000,
plp_id: plp,
symbol_rate: delsys.is_cable().then_some(symbol_rate * 1000),
modulation: modulation.filter(|m| m != "auto"),
};
println!("{}: strojenie {}", info.id, params.describe());
let found = tokio::task::spawn_blocking(move || -> Result<_> {
let mut src = dvb::open(&info)?;
let cancel = AtomicBool::new(false);
dvb::scan::scan_frequency(
src.as_mut(),
&params,
Duration::from_secs(5),
Duration::from_secs(15),
&cancel,
)
})
.await??;
match found {
None => println!("No lock."),
Some(m) => {
println!(
"LOCK network: {} ONID {} TSID {}",
m.network_name, m.onid, m.ts_id
);
println!("Signal: {:?}", m.signal);
for s in m.services {
let codecs: Vec<_> = s.streams.iter().map(|x| x.kind.label()).collect();
println!(
" {:>5} {:<4} LCN {:<4} {:<30} [{}]{}",
s.sid,
s.kind,
s.lcn.map(|l| l.to_string()).unwrap_or_default(),
s.name,
codecs.join(", "),
if s.scrambled { " (kodowany)" } else { "" }
);
}
}
}
Ok(())
}
Cmd::GenDemo { out } => {
std::fs::create_dir_all(&out)?;
let t = chrono::Utc::now().timestamp();
let muxes: [(u32, u16, u16, [&str; 2]); 2] = [
(538, 0x0001, 0x0101, ["Demo Jeden HD", "Demo Info"]),
(554, 0x0002, 0x0201, ["Demo Sport HD", "Demo Kino"]),
];
let has_ffmpeg = std::process::Command::new("ffmpeg")
.arg("-version")
.output()
.is_ok_and(|o| o.status.success());
for (idx, (mhz, tsid, sid, names)) in muxes.into_iter().enumerate() {
let m = simply_dvb::ts::testgen::GenMux::sample(tsid, sid, &names, t);
let path = out.join(format!("{mhz}.ts"));
let data = if has_ffmpeg {
println!("{}: generating ffmpeg test picture…", path.display());
demo_ffmpeg(&m, idx)?
} else {
println!(
"{}: ffmpeg not found – synthetic stream (no picture)",
path.display()
);
m.generate(30)
};
std::fs::write(&path, data)?;
}
println!("Run: simply-dvb --virtual-dir {} serve", out.display());
Ok(())
}
}
}
/// Demo multiplex with real video (ffmpeg) and simply-dvb NIT/EIT tables.
fn demo_ffmpeg(m: &simply_dvb::ts::testgen::GenMux, idx: usize) -> Result<Vec<u8>> {
let a = &m.services[0];
let b = &m.services[1];
let src = if idx == 0 { "testsrc2" } else { "smptehdbars" };
let args: Vec<String> = vec![
"-hide_banner".into(),
"-loglevel".into(),
"error".into(),
"-f".into(),
"lavfi".into(),
"-i".into(),
format!("{src}=size=1280x720:rate=25"),
"-f".into(),
"lavfi".into(),
"-i".into(),
"sine=frequency=440:sample_rate=48000".into(),
"-f".into(),
"lavfi".into(),
"-i".into(),
"testsrc=size=720x576:rate=25".into(),
"-f".into(),
"lavfi".into(),
"-i".into(),
"sine=frequency=660:sample_rate=48000".into(),
"-t".into(),
"60".into(),
"-map".into(),
"0:v".into(),
"-map".into(),
"1:a".into(),
"-map".into(),
"2:v".into(),
"-map".into(),
"3:a".into(),
"-c:v".into(),
"libx264".into(),
"-preset".into(),
"veryfast".into(),
"-g".into(),
"25".into(),
"-b:v".into(),
"2M".into(),
"-c:a:0".into(),
"aac".into(),
"-c:a:1".into(),
"mp2".into(),
"-b:a".into(),
"128k".into(),
"-program".into(),
format!("title={}:program_num={}:st=0:st=1", a.name, a.sid),
"-program".into(),
format!("title={}:program_num={}:st=2:st=3", b.name, b.sid),
"-metadata".into(),
"service_provider=Demo".into(),
"-mpegts_transport_stream_id".into(),
m.ts_id.to_string(),
"-mpegts_original_network_id".into(),
m.onid.to_string(),
"-f".into(),
"mpegts".into(),
"pipe:1".into(),
];
let o = std::process::Command::new("ffmpeg").args(&args).output()?;
if !o.status.success() {
bail!("ffmpeg: {}", String::from_utf8_lossy(&o.stderr));
}
Ok(m.inject_si(&o.stdout, 2000))
}
async fn open_db(opts: &Options) -> Result<Db> {
std::fs::create_dir_all(&opts.data_dir)
.with_context(|| format!("creating directory {}", opts.data_dir.display()))?;
let path = opts.data_dir.join("simply-dvb.db");
// Database created before the project was renamed (simple-dvbt): take it over once.
let legacy = opts.data_dir.join("simple-dvbt.db");
if !path.exists() && legacy.exists() {
for ext in ["", "-wal", "-shm"] {
let from = PathBuf::from(format!("{}{ext}", legacy.display()));
if from.exists() {
std::fs::rename(&from, format!("{}{ext}", path.display()))
.with_context(|| format!("renaming {}", from.display()))?;
}
}
tracing::info!("renamed legacy database simple-dvbt.db to simply-dvb.db");
}
Db::open(&path).await
}
async fn serve(
opts: Options,
listen: SocketAddr,
stream_listen: Option<SocketAddr>,
htsp_listen: Option<SocketAddr>,
) -> Result<()> {
let db = open_db(&opts).await?;
if db.user_count().await? == 0 {
let pw = auth::random_token(12);
db.create_user("admin", &auth::hash_password(&pw)?, "admin")
.await?;
let path = opts.data_dir.join("initial-admin-password.txt");
let _ = std::fs::write(&path, format!("admin\n{pw}\n"));
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
}
tracing::warn!(
"Created account 'admin' with password: {pw} (also saved in {})",
path.display()
);
}
let (state, epg_rx) = AppState::new(db, opts).await?;
let adapters = state.tuners.adapters();
if adapters.is_empty() {
tracing::warn!("no DVB adapters detected – check /dev/dvb and permissions (video group)");
}
for a in &adapters {
tracing::info!("adapter {}: {} ({})", a.id, a.name, a.path);
}
tokio::spawn(epg::writer_task(state.clone(), epg_rx));
tokio::spawn(epg::grabber_task(state.clone()));
tokio::spawn(epg::xmltv_task(state.clone()));
tokio::spawn(recorder::scheduler_task(state.clone()));
tokio::spawn(simply_dvb::stats::sampler_task(state.clone()));
tokio::spawn(simply_dvb::scanjob::idle_scan_task(state.clone()));
tokio::spawn(simply_dvb::acl::resolver_task(state.clone()));
{
let st = state.clone();
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
st.tuners.reap();
st.hls.reap();
st.clients.reap(st.settings().hls_idle_seconds as i64);
}
});
}
let app = web::router(state.clone());
let listener = tokio::net::TcpListener::bind(listen)
.await
.with_context(|| format!("listening on {listen}"))?;
tracing::info!(
"simply-dvb {} – panel: http://{listen}/",
env!("CARGO_PKG_VERSION")
);
let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
let mut servers = tokio::task::JoinSet::new();
if let Some(addr) = stream_listen {
if addr == listen {
anyhow::bail!("the stream port must differ from the panel port");
}
let app = web::stream_router(state.clone());
let mut rx = stop_rx.clone();
let st = state.clone();
servers.spawn(async move {
// The port may still be used by tvheadend during a migration: keep the panel running
// (streams are served on the panel port too) and take the port over once it is free.
let mut warned = false;
let l = loop {
match tokio::net::TcpListener::bind(addr).await {
Ok(l) => break l,
Err(e) => {
if !warned {
tracing::warn!(
"stream port {addr} unavailable ({e}) – is tvheadend still running? \
Streams stay available on the panel port; retrying every 15 s"
);
warned = true;
}
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(15)) => {}
_ = rx.wait_for(|v| *v) => return Ok(()),
}
}
}
};
st.stream_port_active.store(true, Ordering::Relaxed);
tracing::info!(
"streams (tvheadend-compatible): http://{addr}/playlist · http://{addr}/xmltv"
);
axum::serve(l, app.into_make_service_with_connect_info::<SocketAddr>())
.with_graceful_shutdown(async move {
let _ = rx.wait_for(|v| *v).await;
})
.await
});
}
// a port can only serve one protocol: catch configurations where two of them collide
let htsp_listen = match htsp_listen {
Some(a)
if a.port() == listen.port() || Some(a.port()) == stream_listen.map(|s| s.port()) =>
{
tracing::error!(
"HTSP port {} is the same as the {} port – HTSP disabled. Set SIMPLY_DVB_HTSP_LISTEN to a free port \
(tvheadend layout: panel 9990, streams 9981, HTSP 9982)",
a.port(),
if a.port() == listen.port() { "panel" } else { "stream" }
);
None
}
other => other,
};
if let Some(addr) = htsp_listen {
let mut rx = stop_rx.clone();
let st = state.clone();
servers.spawn(async move {
// like the stream port: wait for tvheadend to release 9982 during a migration
let mut warned = false;
let l = loop {
match tokio::net::TcpListener::bind(addr).await {
Ok(l) => break l,
Err(e) => {
if !warned {
tracing::warn!(
"HTSP port {addr} unavailable ({e}) – is tvheadend still running? Retrying every 15 s"
);
warned = true;
}
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(15)) => {}
_ = rx.wait_for(|v| *v) => return Ok(()),
}
}
}
};
st.htsp_port_active.store(true, Ordering::Relaxed);
tracing::info!("HTSP (Kodi, TVHClient, PVR apps): {addr}");
simply_dvb::htsp::serve(st, l, rx).await;
Ok(())
});
}
{
let mut rx = stop_rx.clone();
servers.spawn(async move {
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(async move {
let _ = rx.wait_for(|v| *v).await;
})
.await
});
}
let st = state.clone();
tokio::spawn(async move {
let ctrl_c = tokio::signal::ctrl_c();
#[cfg(unix)]
let term = async {
if let Ok(mut s) =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
{
s.recv().await;
}
};
#[cfg(not(unix))]
let term = std::future::pending::<()>();
tokio::select! { _ = ctrl_c => {}, _ = term => {} }
tracing::info!("shutting down…");
st.shutting_down.store(true, Ordering::Relaxed);
st.hls.stop_all();
let _ = stop_tx.send(true);
});
while let Some(r) = servers.join_next().await {
r??;
}
state.tuners.shutdown();
Ok(())
}
+365
View File
@@ -0,0 +1,365 @@
//! Single-service stream: tuner subscription -> service filter -> (optionally ffmpeg).
use crate::app::State;
use crate::db::{Channel, Mux, Service};
use crate::stream::filter::ServiceFilter;
use crate::ts::packet::Aligner;
use crate::tuner::Priority;
use anyhow::{anyhow, bail, Context, Result};
use bytes::Bytes;
use std::process::Stdio;
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
pub const PROFILES: &[(&str, &str)] = &[
("pass", "Original (no transcoding)"),
("aac", "Video unchanged, audio → AAC (browsers)"),
("h264", "Full transcoding to H.264 720p + AAC"),
];
pub fn valid_profile(p: &str) -> bool {
PROFILES.iter().any(|(n, _)| *n == p)
}
/// Maps tvheadend (and own) profile names to simply-dvb profiles.
/// Unknown names → "pass" (compatibility with tvheadend clients that send their own profiles).
pub fn normalize_profile(p: &str) -> &'static str {
let p = p.trim().to_ascii_lowercase();
match p.as_str() {
"aac" | "audio-aac" | "webtv-aac" => "aac",
"h264"
| "webtv-h264-aac-mpegts"
| "webtv-h264-aac-matroska"
| "webtv-vp8-vorbis-webm"
| "webtv-h264"
| "h264-aac" => "h264",
_ => "pass",
}
}
#[derive(Clone)]
pub struct ChannelSource {
pub channel: Channel,
pub service: Service,
pub mux: Mux,
}
pub async fn resolve(state: &State, channel_id: i64) -> Result<ChannelSource> {
let channel = state
.db
.channel(channel_id)
.await?
.ok_or_else(|| anyhow!("channel does not exist"))?;
let sid = channel
.service_id
.ok_or_else(|| anyhow!("channel has no service assigned"))?;
let service = state
.db
.service(sid)
.await?
.ok_or_else(|| anyhow!("channel service does not exist"))?;
let mux = state
.db
.mux(service.mux_id)
.await?
.ok_or_else(|| anyhow!("mux does not exist"))?;
if !mux.enabled {
bail!("mux is disabled");
}
Ok(ChannelSource {
channel,
service,
mux,
})
}
/// Saves the stream list of the played service once its PMT is seen, so the channel
/// list shows codecs even when the scan timed out before the PMT arrived.
struct PmtLearner {
state: Option<State>,
service_id: i64,
known: String,
}
impl PmtLearner {
fn new(state: &State, service_id: i64, known: &str) -> Self {
Self {
state: Some(state.clone()),
service_id,
known: known.to_string(),
}
}
fn check(&mut self, filter: &ServiceFilter) {
let Some(pmt) = filter.pmt.as_ref() else {
return;
};
let Some(state) = self.state.take() else {
return;
};
if pmt.streams.is_empty()
|| serde_json::to_string(&pmt.streams).ok().as_deref() == Some(self.known.as_str())
{
return;
}
let (pmt, id) = (pmt.clone(), self.service_id);
tokio::spawn(async move {
match state.db.set_service_streams(id, &pmt).await {
Ok(true) => tracing::info!(
"service #{id}: streams learned while playing ({})",
pmt.streams
.iter()
.map(|s| s.kind.label())
.collect::<Vec<_>>()
.join(", ")
),
Ok(false) => {}
Err(e) => tracing::warn!("saving streams of service #{id}: {e:#}"),
}
});
}
}
struct AbortOnDrop(Vec<JoinHandle<()>>);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
for h in &self.0 {
h.abort();
}
}
}
pub struct ServiceStream {
pub rx: mpsc::Receiver<Bytes>,
pub source: ChannelSource,
pub adapter: String,
pub error: Arc<Mutex<String>>,
_tasks: AbortOnDrop,
}
fn ffmpeg_args(profile: &str, h264_args: &str) -> Vec<String> {
let mut a: Vec<String> = [
"-hide_banner",
"-nostdin",
"-loglevel",
"error",
"-fflags",
"+genpts+discardcorrupt",
"-analyzeduration",
"3000000",
"-probesize",
"3000000",
"-f",
"mpegts",
"-i",
"pipe:0",
"-map",
"0:v:0?",
"-map",
"0:a:0?",
"-sn",
"-dn",
]
.iter()
.map(|s| s.to_string())
.collect();
match profile {
"aac" => a.extend(["-c:v", "copy"].iter().map(|s| s.to_string())),
_ => a.extend(shell_split(h264_args)),
}
a.extend(
[
"-c:a",
"aac",
"-b:a",
"160k",
"-ac",
"2",
"-f",
"mpegts",
"-mpegts_flags",
"+resend_headers",
"-muxdelay",
"0",
"pipe:1",
]
.iter()
.map(|s| s.to_string()),
);
a
}
/// Simple argument splitting with single- and double-quote support.
pub fn shell_split(s: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut quote: Option<char> = None;
let mut has = false;
for c in s.chars() {
match quote {
Some(q) if c == q => quote = None,
Some(_) => cur.push(c),
None if c == '\'' || c == '"' => {
quote = Some(c);
has = true;
}
None if c.is_whitespace() => {
if has || !cur.is_empty() {
out.push(std::mem::take(&mut cur));
has = false;
}
}
None => cur.push(c),
}
}
if has || !cur.is_empty() {
out.push(cur);
}
out
}
/// Opens the MPEG-TS stream of the selected channel.
pub async fn open_service(
state: &State,
channel_id: i64,
profile: &str,
prio: Priority,
) -> Result<ServiceStream> {
if !valid_profile(profile) {
bail!("unknown profile: {profile}");
}
if profile != "pass" && !state.has_ffmpeg() {
// ffmpeg may have been installed after start – check again before giving up
state.detect_ffmpeg().await;
if !state.has_ffmpeg() {
bail!(
"ffmpeg is not installed on the server – the “{profile}” transcoding profile is unavailable; play the original stream (pass) or install ffmpeg"
);
}
}
let source = resolve(state, channel_id).await?;
let mut sub = state.tuners.subscribe(&source.mux, prio).await?;
let adapter = sub.adapter.clone();
let (tx, rx) = mpsc::channel::<Bytes>(512);
let sid = source.service.sid as u16;
let pmt_pid = source.service.pmt_pid as u16;
let error = Arc::new(Mutex::new(String::new()));
let learn = PmtLearner::new(state, source.service.id, &source.service.streams);
if profile == "pass" {
let task = tokio::spawn(async move {
let mut filter = ServiceFilter::new(Some(sid), Some(pmt_pid)).start_at_keyframe();
let mut aligner = Aligner::new();
let mut out = Vec::with_capacity(188 * 400);
let mut learn = learn;
while let Some(chunk) = sub.recv().await {
aligner.push(&chunk, |p| filter.push(p, &mut out));
learn.check(&filter);
if !out.is_empty() {
let b = Bytes::from(std::mem::replace(&mut out, Vec::with_capacity(188 * 400)));
if tx.send(b).await.is_err() {
break;
}
}
}
});
return Ok(ServiceStream {
rx,
source,
adapter,
error,
_tasks: AbortOnDrop(vec![task]),
});
}
let s = state.settings();
let mut child = tokio::process::Command::new(&s.ffmpeg_path)
.args(ffmpeg_args(profile, &s.ffmpeg_h264_args))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.with_context(|| {
format!(
"starting ffmpeg ({}) – install ffmpeg or change its path in settings",
s.ffmpeg_path
)
})?;
let mut stdin = child.stdin.take().unwrap();
let mut stdout = child.stdout.take().unwrap();
let mut stderr = child.stderr.take().unwrap();
let writer = tokio::spawn(async move {
let mut filter = ServiceFilter::new(Some(sid), Some(pmt_pid)).start_at_keyframe();
let mut aligner = Aligner::new();
let mut out = Vec::with_capacity(188 * 400);
let mut learn = learn;
while let Some(chunk) = sub.recv().await {
aligner.push(&chunk, |p| filter.push(p, &mut out));
learn.check(&filter);
if !out.is_empty() {
if stdin.write_all(&out).await.is_err() {
break;
}
out.clear();
}
}
});
let err2 = error.clone();
let reader = tokio::spawn(async move {
let mut buf = vec![0u8; 188 * 256];
loop {
match stdout.read(&mut buf).await {
Ok(0) | Err(_) => break,
Ok(n) => {
if tx.send(Bytes::copy_from_slice(&buf[..n])).await.is_err() {
break;
}
}
}
}
drop(child);
});
let stderr_task = tokio::spawn(async move {
let mut s = String::new();
let _ = stderr.read_to_string(&mut s).await;
if !s.trim().is_empty() {
tracing::warn!("ffmpeg: {}", s.trim());
let t = s.trim();
let tail: String = t
.chars()
.rev()
.take(500)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
*err2.lock().unwrap() = tail;
}
});
Ok(ServiceStream {
rx,
source,
adapter,
error,
_tasks: AbortOnDrop(vec![writer, reader, stderr_task]),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_args() {
assert_eq!(
shell_split("-vf scale=-2:'min(720,ih)' -crf 23"),
vec!["-vf", "scale=-2:min(720,ih)", "-crf", "23"]
);
assert_eq!(shell_split(" a \"b c\" ''"), vec!["a", "b c", ""]);
assert!(ffmpeg_args("aac", "").contains(&"copy".to_string()));
}
}
+455
View File
@@ -0,0 +1,455 @@
//! Recording: scheduling, writing segments to a single .ts file with an index
//! (played back in the browser as HLS VOD with EXT-X-BYTERANGE).
use crate::app::State;
use crate::clients::NewClient;
use crate::db::{now, Recording};
use crate::pipeline::open_service;
use crate::stream::filter::ServiceFilter;
use crate::stream::segmenter::Segmenter;
use crate::ts::packet::Aligner;
use crate::tuner::Priority;
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RecIndex {
/// (offset, length, duration)
pub segments: Vec<(u64, u64, f64)>,
pub complete: bool,
}
pub fn index_path(file: &Path) -> PathBuf {
let mut p = file.as_os_str().to_owned();
p.push(".idx.json");
PathBuf::from(p)
}
pub fn sanitize(s: &str) -> String {
let t: String = s
.chars()
.map(|c| {
if c.is_alphanumeric() || c == '-' || c == '_' || c == '.' {
c
} else {
'_'
}
})
.collect();
let t = t.trim_matches('_').to_string();
t.chars().take(80).collect()
}
/// Recording scheduler loop.
pub async fn scheduler_task(state: State) {
// recordings interrupted by a restart
if let Ok(list) = state.db.recordings_by_status("recording").await {
for r in list {
let _ = state.db.set_recording_status(r.id, "scheduled", "").await;
}
}
let mut n: u64 = 0;
loop {
if n % 12 == 0 {
if let Err(e) = run_autorec(&state).await {
tracing::warn!("recording rules: {e:#}");
}
}
if n % 720 == 5 {
if let Err(e) = retention(&state).await {
tracing::warn!("recording cleanup: {e:#}");
}
}
if let Err(e) = tick(&state).await {
tracing::warn!("recording scheduler: {e:#}");
}
n += 1;
tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(5)) => {}
_ = state.rec_wakeup.notified() => {}
}
}
}
/// Compiles a rule pattern: a regular expression or (if invalid) a plain title fragment.
pub fn compile_pattern(p: &str) -> regex::Regex {
regex::RegexBuilder::new(p.trim())
.case_insensitive(true)
.size_limit(1 << 20)
.build()
.unwrap_or_else(|_| {
regex::RegexBuilder::new(&regex::escape(p.trim()))
.case_insensitive(true)
.build()
.unwrap()
})
}
/// Series recording rules: schedules matching programmes within the next 48 h.
pub async fn run_autorec(state: &State) -> Result<usize> {
let rules: Vec<_> = state
.db
.autorecs()
.await?
.into_iter()
.filter(|r| r.enabled && !r.pattern.trim().is_empty())
.collect();
if rules.is_empty() {
return Ok(0);
}
let t = now();
let events = state.db.epg_range(None, t, t + 48 * 3600).await?;
let s = state.settings();
let mut created = 0;
for rule in rules {
let re = compile_pattern(&rule.pattern);
for e in events
.iter()
.filter(|e| e.start > t && rule.channel_id.is_none_or(|c| c == e.channel_id))
{
if !re.is_match(&e.title) || state.db.recording_exists(e.channel_id, e.start).await? {
continue;
}
let Some(ch) = state.db.channel(e.channel_id).await? else {
continue;
};
if !ch.enabled {
continue;
}
let desc = if e.description.is_empty() {
&e.summary
} else {
&e.description
};
let id = state
.db
.create_recording(
&ch,
&e.title,
desc,
e.start,
e.stop,
s.recording_pre_padding_min as i64 * 60,
s.recording_post_padding_min as i64 * 60,
)
.await?;
state.db.set_recording_autorec(id, rule.id).await?;
tracing::info!("rule “{}”: scheduled {} ({})", rule.name, e.title, ch.name);
created += 1;
}
}
Ok(created)
}
/// Deletes old recordings (by age) and the oldest ones when space runs low.
pub async fn retention(state: &State) -> Result<usize> {
let s = state.settings();
if s.recordings_keep_days == 0 && s.recordings_min_free_gb == 0 {
return Ok(0);
}
let mut done: Vec<Recording> = state.db.recordings_by_status("completed").await?;
done.sort_by_key(|r| r.start);
let mut removed = 0;
let cutoff = now() - s.recordings_keep_days as i64 * 86400;
let mut remaining = Vec::new();
for r in done {
if s.recordings_keep_days > 0 && r.stop < cutoff {
remove_recording(state, &r).await?;
removed += 1;
} else {
remaining.push(r);
}
}
if s.recordings_min_free_gb > 0 {
let need = s.recordings_min_free_gb as u64 * 1024 * 1024 * 1024;
for r in remaining.into_iter().take(100) {
match free_space(&state.recordings_dir()) {
Some(free) if free < need => {
remove_recording(state, &r).await?;
removed += 1;
}
_ => break,
}
}
}
if removed > 0 {
tracing::info!("cleanup: deleted {removed} recordings");
}
Ok(removed)
}
/// Deletes a recording's files and its database row (stop it first).
pub async fn remove_recording(state: &State, r: &Recording) -> Result<()> {
if !r.file.is_empty() {
let p = Path::new(&r.file);
let _ = tokio::fs::remove_file(p).await;
let _ = tokio::fs::remove_file(index_path(p)).await;
}
state.db.delete_recording(r.id).await
}
/// Free space (bytes) on the directory's file system.
pub fn free_space(path: &Path) -> Option<u64> {
let mut p = path.to_path_buf();
while !p.exists() {
if !p.pop() {
return None;
}
}
let c = std::ffi::CString::new(p.to_string_lossy().as_bytes()).ok()?;
let mut st: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c.as_ptr(), &mut st) } != 0 {
return None;
}
Some(st.f_bavail as u64 * st.f_frsize as u64)
}
async fn tick(state: &State) -> Result<()> {
let t = now();
for r in state.db.recordings_by_status("scheduled").await? {
let begin = r.start - r.pre_padding;
let end = r.stop + r.post_padding;
if t >= end {
state
.db
.set_recording_status(r.id, "failed", "not started before the programme ended")
.await?;
continue;
}
if t >= begin && !state.recordings_running.lock().unwrap().contains_key(&r.id) {
let stop = Arc::new(AtomicBool::new(false));
state
.recordings_running
.lock()
.unwrap()
.insert(r.id, stop.clone());
state.db.set_recording_status(r.id, "recording", "").await?;
let st = state.clone();
tokio::spawn(async move {
let id = r.id;
let res = record(&st, r, stop).await;
st.recordings_running.lock().unwrap().remove(&id);
match res {
Ok(status) => {
let _ = st.db.set_recording_status(id, &status, "").await;
}
Err(e) => {
tracing::warn!("recording {id}: {e:#}");
let _ = st
.db
.set_recording_status(id, "failed", &format!("{e:#}"))
.await;
}
}
});
}
}
Ok(())
}
/// Stops a running recording.
pub fn stop_recording(state: &State, id: i64) -> bool {
if let Some(f) = state.recordings_running.lock().unwrap().get(&id) {
f.store(true, Ordering::Relaxed);
return true;
}
false
}
async fn record(state: &State, r: Recording, stop: Arc<AtomicBool>) -> Result<String> {
let channel_id = r
.channel_id
.ok_or_else(|| anyhow!("the recording’s channel was deleted"))?;
let end = r.stop + r.post_padding;
let dir = state.recordings_dir();
tokio::fs::create_dir_all(&dir).await?;
let when = chrono::DateTime::from_timestamp(r.start, 0)
.map(|d| {
d.with_timezone(&chrono::Local)
.format("%Y-%m-%d_%H%M")
.to_string()
})
.unwrap_or_default();
let file = dir.join(format!(
"{}_{}_{}_{}.ts",
when,
sanitize(&r.channel_name),
sanitize(&r.title),
r.id
));
let mut out = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&file)
.await?;
let mut offset = out.metadata().await?.len();
let idx_path = index_path(&file);
let mut index: RecIndex = match tokio::fs::read(&idx_path).await {
Ok(b) => serde_json::from_slice(&b).unwrap_or_default(),
Err(_) => RecIndex::default(),
};
// keep the index consistent with the file after a restart
let indexed: u64 = index.segments.last().map(|(o, l, _)| o + l).unwrap_or(0);
if indexed != offset {
out.set_len(indexed).await?;
offset = indexed;
}
state
.db
.set_recording_file(
r.id,
&file.to_string_lossy(),
offset as i64,
index.segments.iter().map(|s| s.2).sum(),
)
.await?;
let mut last_err = String::new();
while now() < end && !stop.load(Ordering::Relaxed) {
let mut stream = match open_service(state, channel_id, "pass", Priority::Recording).await {
Ok(s) => s,
Err(e) => {
last_err = format!("{e:#}");
tracing::warn!("recording {}: {last_err}, retrying in 20 s", r.id);
state
.db
.set_recording_status(r.id, "recording", &last_err)
.await?;
tokio::time::sleep(Duration::from_secs(20)).await;
continue;
}
};
let guard = state.clients.register(NewClient {
kind: "recording",
channel_id,
channel_name: &r.channel_name,
ip: "-",
user_agent: &r.title,
who: "recording",
profile: "pass",
});
let mut seg = Segmenter::new(
ServiceFilter::new(None, None),
6.0,
index.segments.len() as u64,
);
let mut aligner = Aligner::new();
let mut dirty = 0;
loop {
if now() >= end || stop.load(Ordering::Relaxed) {
break;
}
let chunk = match tokio::time::timeout(Duration::from_secs(2), stream.rx.recv()).await {
Ok(Some(c)) => c,
Ok(None) => break,
Err(_) => continue,
};
let mut segs = Vec::new();
aligner.push(&chunk, |p| {
if let Some(s) = seg.push(p) {
segs.push(s);
}
});
for s in segs {
out.write_all(&s.data).await?;
index
.segments
.push((offset, s.data.len() as u64, s.duration));
offset += s.data.len() as u64;
guard.add_bytes(s.data.len() as u64);
dirty += 1;
}
if dirty >= 1 {
out.flush().await?;
tokio::fs::write(&idx_path, serde_json::to_vec(&index)?).await?;
state
.db
.set_recording_file(
r.id,
&file.to_string_lossy(),
offset as i64,
index.segments.iter().map(|s| s.2).sum(),
)
.await?;
dirty = 0;
}
}
if let Some(s) = seg.flush() {
out.write_all(&s.data).await?;
index
.segments
.push((offset, s.data.len() as u64, s.duration));
offset += s.data.len() as u64;
}
drop(guard);
if now() < end && !stop.load(Ordering::Relaxed) {
last_err = "stream interrupted".into();
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
out.flush().await?;
index.complete = true;
tokio::fs::write(&idx_path, serde_json::to_vec(&index)?).await?;
let dur: f64 = index.segments.iter().map(|s| s.2).sum();
state
.db
.set_recording_file(r.id, &file.to_string_lossy(), offset as i64, dur)
.await?;
if index.segments.is_empty() {
return Err(anyhow!(if last_err.is_empty() {
"no data".to_string()
} else {
last_err
}));
}
Ok("completed".to_string())
}
/// VOD playlist (HLS with byte ranges) for a recording.
pub async fn vod_playlist(rec: &Recording, file_url: &str) -> Result<String> {
let idx: RecIndex = match tokio::fs::read(index_path(Path::new(&rec.file))).await {
Ok(b) => serde_json::from_slice(&b)?,
Err(_) => return Err(anyhow!("recording index missing")),
};
let target = idx
.segments
.iter()
.map(|s| s.2)
.fold(1.0f64, f64::max)
.ceil() as u64;
let finished = idx.complete || rec.status != "recording";
let mut out = format!(
"#EXTM3U\n#EXT-X-VERSION:4\n#EXT-X-TARGETDURATION:{target}\n#EXT-X-MEDIA-SEQUENCE:0\n#EXT-X-PLAYLIST-TYPE:{}\n",
if finished { "VOD" } else { "EVENT" }
);
for (off, len, dur) in &idx.segments {
out.push_str(&format!(
"#EXTINF:{dur:.3},\n#EXT-X-BYTERANGE:{len}@{off}\n{file_url}\n"
));
}
if finished {
out.push_str("#EXT-X-ENDLIST\n");
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanitize_names() {
assert_eq!(
sanitize("Wiadomości: 19:30 / TVP1"),
"Wiadomości__19_30___TVP1"
);
assert_eq!(
index_path(Path::new("/r/a.ts")),
PathBuf::from("/r/a.ts.idx.json")
);
}
}
+487
View File
@@ -0,0 +1,487 @@
//! Scan job started from the panel.
use crate::app::State;
use crate::dvb::scan::{preset, scan_frequency, systems_order, ScanEntry};
use crate::dvb::{self, DeliverySystem, TuneParams};
use anyhow::{anyhow, bail, Result};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use std::time::Duration;
#[derive(Debug, Clone, Deserialize)]
pub struct ScanRequest {
#[serde(default)]
pub adapter: Option<String>,
/// "uhf-21-48", "dvbc-eu", ... (see dvb::scan::presets), "known" (saved muxes) or "custom".
#[serde(default = "default_preset")]
pub preset: String,
/// For "custom": frequencies in MHz.
#[serde(default)]
pub frequencies_mhz: Vec<f64>,
#[serde(default = "default_systems")]
pub systems: Vec<DeliverySystem>,
#[serde(default = "default_bw")]
pub bandwidth_mhz: u32,
/// Append muxes found in the NIT (the broadcaster's network knows its frequencies).
#[serde(default = "yes")]
pub follow_nit: bool,
/// DVB-C: symbol rates to try (kS/s).
#[serde(default = "default_sr")]
pub symbol_rates_ksps: Vec<u32>,
/// DVB-C: modulations to try ("auto", "qam64", "qam128", "qam256").
#[serde(default = "default_mods")]
pub modulations: Vec<String>,
}
fn yes() -> bool {
true
}
fn default_sr() -> Vec<u32> {
vec![6900, 6875]
}
fn default_mods() -> Vec<String> {
vec!["auto".into()]
}
/// Tuning parameters to try for a list entry.
pub fn candidates(
e: &ScanEntry,
req: &ScanRequest,
supported: &[DeliverySystem],
) -> Vec<TuneParams> {
let systems: Vec<DeliverySystem> = match e.delsys {
Some(DeliverySystem::Dvbc) => vec![DeliverySystem::Dvbc],
Some(d) => {
let mut v = vec![d];
v.extend(
req.systems
.iter()
.copied()
.filter(|x| *x != d && !x.is_cable()),
);
v
}
None => req.systems.clone(),
};
let systems = systems_order(supported, &systems);
let mut out = Vec::new();
for sys in systems {
if sys.is_cable() {
let srs: Vec<u32> = match e.symbol_rate {
Some(sr) => vec![sr],
None => req.symbol_rates_ksps.iter().map(|k| k * 1000).collect(),
};
let mods: Vec<Option<String>> = match &e.modulation {
Some(m) => vec![Some(m.clone())],
None => req
.modulations
.iter()
.map(|m| if m == "auto" { None } else { Some(m.clone()) })
.collect(),
};
for sr in &srs {
for m in &mods {
out.push(TuneParams {
delsys: sys,
frequency_hz: e.frequency_hz,
bandwidth_hz: 8_000_000,
plp_id: None,
symbol_rate: Some(*sr),
modulation: m.clone(),
});
}
}
} else {
out.push(TuneParams {
delsys: sys,
frequency_hz: e.frequency_hz,
bandwidth_hz: e.bandwidth_hz,
plp_id: e.plp_id,
..Default::default()
});
}
}
out
}
fn default_preset() -> String {
"pl".into()
}
fn default_systems() -> Vec<DeliverySystem> {
vec![DeliverySystem::Dvbt2, DeliverySystem::Dvbt]
}
fn default_bw() -> u32 {
8
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ScanProgress {
pub running: bool,
pub adapter: String,
pub total: usize,
pub done: usize,
pub current: String,
pub muxes_found: usize,
pub services_found: usize,
pub channels_created: usize,
pub log: Vec<String>,
pub error: String,
pub started: i64,
pub finished: Option<i64>,
/// Background scan started automatically on an idle adapter.
pub idle: bool,
}
#[derive(Default)]
pub struct ScanState {
pub progress: Mutex<ScanProgress>,
pub cancel: AtomicBool,
}
impl ScanState {
fn log(&self, msg: String) {
tracing::info!("scan: {msg}");
let mut p = self.progress.lock().unwrap();
p.log.push(msg);
if p.log.len() > 300 {
p.log.remove(0);
}
}
}
pub async fn start(state: &State, req: ScanRequest) -> Result<()> {
let idle_running = {
let p = state.scan.progress.lock().unwrap();
if p.running && !p.idle {
bail!("a scan is already running");
}
p.running
};
if idle_running {
// a manual scan replaces a background one
state.tuners.cancel_scans();
for _ in 0..200 {
if !state.scan.progress.lock().unwrap().running {
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
let guard = state.tuners.reserve_for_scan(req.adapter.as_deref())?;
let create = state.settings().scan_create_channels;
run(state, req, guard, false, create).await
}
/// Stops the running scan (manual or background).
pub fn stop(state: &State) {
state.scan.cancel.store(true, Ordering::Relaxed);
state.tuners.cancel_scans();
}
/// Runs a scan on a reserved adapter.
async fn run(
state: &State,
req: ScanRequest,
guard: crate::tuner::ScanGuard,
idle: bool,
create: bool,
) -> Result<()> {
let st = state.clone();
let handle = tokio::runtime::Handle::current();
let freqs: Vec<ScanEntry> = match req.preset.as_str() {
"custom" => req
.frequencies_mhz
.iter()
.map(|f| ScanEntry::terrestrial((f * 1_000_000.0).round() as u64, req.bandwidth_mhz))
.collect(),
"known" => st
.db
.muxes()
.await?
.iter()
.map(|m| {
let p = m.params();
ScanEntry {
frequency_hz: p.frequency_hz,
bandwidth_hz: p.bandwidth_hz,
delsys: Some(p.delsys),
symbol_rate: p.symbol_rate,
modulation: p.modulation,
plp_id: p.plp_id,
}
})
.collect(),
p => preset(p).ok_or_else(|| anyhow!("unknown frequency list: {p}"))?,
};
if freqs.is_empty() {
bail!("empty frequency list");
}
state.scan.cancel.store(false, Ordering::Relaxed);
*state.scan.progress.lock().unwrap() = ScanProgress {
running: true,
adapter: guard.0.info.id.clone(),
total: freqs.len(),
started: crate::db::now(),
idle,
..Default::default()
};
if idle {
state.scan.log(format!(
"background scan of saved muxes on {}",
guard.0.info.id
));
}
let settings = state.settings();
let lock_timeout = Duration::from_millis(settings.scan_lock_timeout_ms as u64);
tokio::task::spawn_blocking(move || {
let res = (|| -> Result<()> {
guard.0.join_thread();
let mut src = dvb::open(&guard.0.info)?;
let supported = guard.0.info.delivery_systems.clone();
let mut queue: std::collections::VecDeque<ScanEntry> = freqs.into_iter().collect();
let mut seen: std::collections::HashSet<(bool, u64)> =
queue.iter().map(|e| e.key()).collect();
let mut done = 0usize;
while let Some(entry) = queue.pop_front() {
if guard.0.scan_cancel.load(Ordering::Relaxed) {
st.scan.cancel.store(true, Ordering::Relaxed);
}
if st.scan.cancel.load(Ordering::Relaxed) {
st.scan.log(if idle {
"background scan stopped – the adapter is needed".into()
} else {
"cancelled by user".into()
});
break;
}
{
let mut p = st.scan.progress.lock().unwrap();
p.done = done;
p.total = done + queue.len() + 1;
p.current = format!("{:.1} MHz", entry.frequency_hz as f64 / 1e6);
}
done += 1;
for params in candidates(&entry, &req, &supported) {
if guard.0.scan_cancel.load(Ordering::Relaxed) {
st.scan.cancel.store(true, Ordering::Relaxed);
break;
}
match scan_frequency(
src.as_mut(),
&params,
lock_timeout,
Duration::from_secs(12),
&guard.0.scan_cancel,
) {
Ok(Some(found)) => {
let names: Vec<String> =
found.services.iter().map(|s| s.name.clone()).collect();
let sig = found
.signal
.snr_db
.map(|s| format!(", SNR {s:.1} dB"))
.unwrap_or_default();
st.scan.log(format!(
"{}: {} services{} – {}",
params.describe(),
found.services.len(),
sig,
names.join(", ")
));
if req.follow_nit {
for d in &found.discovered {
if seen.insert(d.key()) {
st.scan.log(format!(
"NIT: new mux {:.1} MHz",
d.frequency_hz as f64 / 1e6
));
queue.push_back(d.clone());
}
}
}
let created = handle.block_on(store_and_create(&st, &found, create))?;
let mut p = st.scan.progress.lock().unwrap();
p.muxes_found += 1;
p.services_found += found.services.len();
p.channels_created += created;
break;
}
Ok(None) => {}
Err(e) => st.scan.log(format!("{}: error {e:#}", params.describe())),
}
}
}
Ok(())
})();
let mut p = st.scan.progress.lock().unwrap();
p.running = false;
p.done = p.total;
p.current.clear();
p.finished = Some(crate::db::now());
if let Err(e) = res {
p.error = format!("{e:#}");
tracing::warn!("scan: {e:#}");
}
drop(guard);
});
Ok(())
}
/// Stores a multiplex and creates channels automatically.
pub async fn store_and_create(
state: &State,
found: &crate::dvb::scan::FoundMux,
create: bool,
) -> Result<usize> {
let (_, services) = state.db.store_scan(found).await?;
let s = state.settings();
if !create {
return Ok(0);
}
let existing = state.db.channels().await?;
let mut used: std::collections::HashSet<i64> = existing.iter().map(|c| c.number).collect();
let mut created = 0;
let mut services = services;
services.sort_by_key(|(_, f)| f.lcn.unwrap_or(9999));
for (sid, f) in services {
let ok_kind = f.kind == "tv" || (f.kind == "radio" && s.scan_include_radio);
if !ok_kind || (f.scrambled && !s.scan_include_scrambled) {
continue;
}
if state.db.channel_for_service(sid).await?.is_some() {
continue;
}
let number = match f.lcn.map(|l| l as i64) {
Some(l) if l > 0 && !used.contains(&l) => l,
_ => {
let base = if f.kind == "radio" { 100 } else { 1 };
let mut n = base;
while used.contains(&n) {
n += 1;
}
n
}
};
used.insert(number);
let grp = if f.kind == "radio" { "Radio" } else { "TV" };
state
.db
.create_channel(number, &f.name, Some(sid), grp)
.await?;
created += 1;
}
Ok(created)
}
/// Settings key holding the time of the last background scan.
const IDLE_SCAN_KEY: &str = "idle_scan_last";
/// Background scanning: when an adapter has been idle long enough, rescans the saved
/// muxes (and follows the NIT) so new or changed services show up without a manual scan.
/// The scan stops as soon as the adapter is needed for watching or recording.
pub async fn idle_scan_task(state: State) {
let mut idle_since: Option<std::time::Instant> = None;
loop {
tokio::time::sleep(Duration::from_secs(30)).await;
let s = state.settings();
if s.idle_scan_hours == 0 || state.scan.progress.lock().unwrap().running {
idle_since = None;
continue;
}
let quiet = state
.tuners
.status()
.iter()
.all(|t| t.active.is_none() && !t.busy)
&& state.recordings_running.lock().unwrap().is_empty();
if !quiet {
idle_since = None;
continue;
}
// wait for a few quiet minutes so zapping or a short pause does not trigger it
let since = *idle_since.get_or_insert_with(std::time::Instant::now);
if since.elapsed() < Duration::from_secs(s.idle_scan_quiet_minutes as u64 * 60) {
continue;
}
let last: i64 = state
.db
.get_setting(IDLE_SCAN_KEY)
.await
.ok()
.flatten()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
let now = crate::db::now();
if now - last < s.idle_scan_hours as i64 * 3600 {
continue;
}
if state.db.muxes().await.map(|m| m.is_empty()).unwrap_or(true) {
continue;
}
let Some(guard) = state.tuners.reserve_for_idle_scan() else {
continue;
};
let _ = state.db.set_setting(IDLE_SCAN_KEY, &now.to_string()).await;
let req = ScanRequest {
adapter: Some(guard.0.info.id.clone()),
preset: "known".into(),
frequencies_mhz: Vec::new(),
systems: default_systems(),
bandwidth_mhz: 8,
follow_nit: s.idle_scan_follow_nit,
symbol_rates_ksps: default_sr(),
modulations: default_mods(),
};
if let Err(e) = run(&state, req, guard, true, s.idle_scan_create_channels).await {
tracing::warn!("background scan: {e:#}");
}
idle_since = None;
}
}
/// Time of the last background scan (unix seconds), if any.
pub async fn last_idle_scan(state: &State) -> Option<i64> {
state
.db
.get_setting(IDLE_SCAN_KEY)
.await
.ok()
.flatten()
.and_then(|v| v.parse().ok())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scan_candidates() {
let req: ScanRequest = serde_json::from_str(r#"{"preset":"custom","systems":["dvbt2","dvbt","dvbc"],"modulations":["qam256","qam64"]}"#).unwrap();
let all = [
DeliverySystem::Dvbt,
DeliverySystem::Dvbt2,
DeliverySystem::Dvbc,
];
// terrestrial entry: T2, T, then C (2 SR × 2 modulations)
let c = candidates(&ScanEntry::terrestrial(538_000_000, 8), &req, &all);
assert_eq!(c.len(), 2 + 4);
assert_eq!(c[0].delsys, DeliverySystem::Dvbt2);
assert_eq!(c[2].symbol_rate, Some(6_900_000));
assert_eq!(c[2].modulation.as_deref(), Some("qam256"));
// cable entry from the NIT: exact parameters
let mut e = ScanEntry::cable(330_000_000);
e.symbol_rate = Some(6_875_000);
e.modulation = Some("qam64".into());
let c = candidates(&e, &req, &all);
assert_eq!(c.len(), 1);
assert!(c[0].describe().starts_with("DVB-C 330.0 MHz"));
// tuner without DVB-C
let c = candidates(
&ScanEntry::cable(330_000_000),
&req,
&[DeliverySystem::Dvbt2],
);
assert!(c.is_empty());
}
}
+224
View File
@@ -0,0 +1,224 @@
//! Application settings edited in the panel (stored in the database as JSON).
pub use crate::acl::AclEntry;
use ipnet::IpNet;
use serde::{Deserialize, Serialize};
use std::net::IpAddr;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct XmltvSource {
pub url: String,
#[serde(default = "yes")]
pub enabled: bool,
}
fn yes() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Settings {
/// Server name shown in the panel.
pub server_name: String,
/// Public base URL (e.g. https://tv.example.com). Empty = from the Host header.
pub public_url: String,
/// Networks/hosts from which streams, M3U and EPG are available without a token.
/// Host names (DDNS) are resolved every minute.
pub stream_open_cidrs: Vec<AclEntry>,
/// Networks/hosts allowed to reach the panel (empty = all).
pub panel_allow_cidrs: Vec<AclEntry>,
/// Trusted reverse proxies (for X-Forwarded-For / X-Forwarded-Proto).
pub trusted_proxies: Vec<IpNet>,
/// Panel session lifetime (hours).
pub session_hours: u32,
/// Target HLS segment length (seconds).
pub hls_segment_seconds: u32,
/// Number of segments in the live playlist.
pub hls_window: u32,
/// Idle seconds after which an HLS session is closed.
pub hls_idle_seconds: u32,
/// How many seconds a tuner stays tuned after the last client leaves.
pub tuner_linger_seconds: u32,
/// Default M3U format: "hls" or "ts".
pub m3u_format: String,
/// Path to ffmpeg (transcoding profiles for browsers).
pub ffmpeg_path: String,
/// H.264 profile parameters (video).
pub ffmpeg_h264_args: String,
pub epg_ota_enabled: bool,
/// Interval in hours for walking all muxes to collect EPG (0 = disabled).
pub epg_grab_interval_hours: u32,
/// Seconds spent collecting EPG on one mux.
pub epg_grab_seconds: u32,
/// Hours of past EPG to keep.
pub epg_keep_past_hours: u32,
pub xmltv_sources: Vec<XmltvSource>,
pub xmltv_interval_hours: u32,
/// Icon URL templates: {slug} – the channel name as e.g. "tvp-1-hd".
pub icon_sources: Vec<String>,
pub recordings_dir: String,
pub recording_pre_padding_min: u32,
pub recording_post_padding_min: u32,
/// Delete finished recordings older than N days (0 = never).
pub recordings_keep_days: u32,
/// Delete the oldest recordings when free space drops below N GiB (0 = disabled).
pub recordings_min_free_gb: u32,
pub scan_create_channels: bool,
pub scan_include_radio: bool,
pub scan_include_scrambled: bool,
pub scan_lock_timeout_ms: u32,
/// Background scan of saved muxes on an idle adapter every N hours (0 = off).
pub idle_scan_hours: u32,
/// Minutes all tuners must be idle before a background scan starts.
pub idle_scan_quiet_minutes: u32,
/// Background scan follows the NIT to find new muxes.
pub idle_scan_follow_nit: bool,
/// Background scan creates channels for new services (otherwise they only appear in "Add from services").
pub idle_scan_create_channels: bool,
}
impl Default for Settings {
fn default() -> Self {
let private = [
"127.0.0.0/8",
"::1/128",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fc00::/7",
"fe80::/10",
];
Settings {
server_name: "simply-dvb".into(),
public_url: String::new(),
stream_open_cidrs: private
.iter()
.map(|s| AclEntry::Net(s.parse().unwrap()))
.collect(),
panel_allow_cidrs: vec![],
trusted_proxies: vec![],
session_hours: 24 * 14,
hls_segment_seconds: 2,
hls_window: 8,
hls_idle_seconds: 30,
tuner_linger_seconds: 8,
m3u_format: "ts".into(),
ffmpeg_path: "ffmpeg".into(),
ffmpeg_h264_args: "-vf yadif=0:-1:1,scale=-2:720 -c:v libx264 -preset veryfast -tune zerolatency -crf 23 -g 50 -bf 0 -pix_fmt yuv420p".into(),
epg_ota_enabled: true,
epg_grab_interval_hours: 6,
epg_grab_seconds: 45,
epg_keep_past_hours: 12,
xmltv_sources: vec![],
xmltv_interval_hours: 12,
icon_sources: vec![
"https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/poland/{slug}-pl.png".into(),
"https://raw.githubusercontent.com/tv-logo/tv-logos/main/countries/international/{slug}-int.png".into(),
],
recordings_dir: String::new(),
recording_pre_padding_min: 2,
recording_post_padding_min: 5,
recordings_keep_days: 0,
recordings_min_free_gb: 0,
scan_create_channels: true,
scan_include_radio: true,
scan_include_scrambled: false,
scan_lock_timeout_ms: 2500,
idle_scan_hours: 24,
idle_scan_quiet_minutes: 10,
idle_scan_follow_nit: true,
idle_scan_create_channels: false,
}
}
}
impl Settings {
pub fn validate(&mut self) -> Result<(), String> {
if !(1..=10).contains(&self.hls_segment_seconds) {
return Err("HLS segment length must be 1–10 s".into());
}
if !(3..=60).contains(&self.hls_window) {
return Err("HLS window must be 3–60 segments".into());
}
self.hls_idle_seconds = self.hls_idle_seconds.clamp(10, 600);
self.session_hours = self.session_hours.clamp(1, 24 * 365);
self.epg_grab_seconds = self.epg_grab_seconds.clamp(10, 600);
self.scan_lock_timeout_ms = self.scan_lock_timeout_ms.clamp(500, 15_000);
self.idle_scan_hours = self.idle_scan_hours.min(24 * 30);
self.idle_scan_quiet_minutes = self.idle_scan_quiet_minutes.clamp(1, 24 * 60);
if self.m3u_format != "hls" && self.m3u_format != "ts" {
return Err("M3U format: hls or ts".into());
}
self.public_url = self.public_url.trim().trim_end_matches('/').to_string();
if !self.public_url.is_empty()
&& !(self.public_url.starts_with("http://") || self.public_url.starts_with("https://"))
{
return Err("public URL must start with http:// or https://".into());
}
for s in &self.xmltv_sources {
if !(s.url.starts_with("http://") || s.url.starts_with("https://")) {
return Err(format!("invalid XMLTV URL: {}", s.url));
}
}
Ok(())
}
}
/// Anything an address can be checked against (networks or ACL entries incl. host names).
pub trait IpMatch {
fn matches_ip(&self, ip: IpAddr) -> bool;
}
impl IpMatch for IpNet {
fn matches_ip(&self, ip: IpAddr) -> bool {
AclEntry::Net(*self).matches(ip)
}
}
impl IpMatch for AclEntry {
fn matches_ip(&self, ip: IpAddr) -> bool {
self.matches(ip)
}
}
pub fn ip_in<T: IpMatch>(list: &[T], ip: IpAddr) -> bool {
list.iter().any(|e| e.matches_ip(ip))
}
/// Parses an access list separated by commas/spaces: networks, single addresses
/// (= /32 or /128) and host names (DDNS, resolved in the background).
pub fn parse_cidrs(s: &str) -> Result<Vec<AclEntry>, String> {
crate::acl::parse_list(s)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults_validate_and_acl() {
let mut s = Settings::default();
assert!(s.validate().is_ok());
assert!(ip_in(&s.stream_open_cidrs, "192.168.1.20".parse().unwrap()));
assert!(ip_in(
&s.stream_open_cidrs,
"::ffff:10.1.2.3".parse().unwrap()
));
assert!(!ip_in(&s.stream_open_cidrs, "8.8.8.8".parse().unwrap()));
let nets = parse_cidrs("1.2.3.4, 10.0.0.0/8").unwrap();
assert!(ip_in(&nets, "1.2.3.4".parse().unwrap()));
assert!(parse_cidrs("zly").is_err());
assert!(parse_cidrs("tv.example.ddns.net").is_ok());
// missing JSON fields are filled with defaults
let p: Settings = serde_json::from_str(r#"{"server_name":"x"}"#).unwrap();
assert_eq!(p.hls_window, 8);
}
}
+327
View File
@@ -0,0 +1,327 @@
//! Live statistics for the overview charts: a sampler task stores a short history
//! (ring buffer) of system, streaming and per-tuner metrics.
use crate::app::State;
use serde::Serialize;
use std::collections::{HashMap, VecDeque};
use std::sync::Mutex;
use std::time::Duration;
/// Sampling interval in seconds.
pub const INTERVAL: u64 = 2;
/// Number of samples kept (15 minutes).
pub const KEEP: usize = 450;
#[derive(Debug, Clone, Serialize, Default)]
pub struct Sample {
pub t: i64,
/// System CPU usage (all cores), percent.
pub cpu: Option<f64>,
/// CPU used by this process, percent of one core.
pub proc_cpu: Option<f64>,
/// Used memory, percent of total.
pub mem: Option<f64>,
/// Resident memory of this process, bytes.
pub rss: Option<u64>,
/// Highest thermal zone temperature, °C.
pub temp: Option<f64>,
pub load1: Option<f64>,
/// Bytes/s sent to stream clients (TS + HLS).
pub out_bps: f64,
/// Bytes/s written by recordings.
pub rec_bps: f64,
/// Network interfaces (without lo), bytes/s.
pub net_rx: Option<f64>,
pub net_tx: Option<f64>,
pub clients: usize,
pub hls_sessions: usize,
pub tuners_active: usize,
}
#[derive(Debug, Clone, Serialize, Default)]
pub struct TunerSample {
pub t: i64,
pub bitrate: u64,
pub strength: Option<f64>,
pub strength_dbm: Option<f64>,
pub snr: Option<f64>,
/// Uncorrected blocks since the previous sample.
pub unc: Option<u64>,
pub clients: usize,
pub locked: bool,
}
#[derive(Default)]
pub struct Stats {
inner: Mutex<Inner>,
}
#[derive(Default)]
struct Inner {
samples: VecDeque<Sample>,
tuners: HashMap<String, VecDeque<TunerSample>>,
}
#[derive(Serialize)]
pub struct History {
pub interval: u64,
pub samples: Vec<Sample>,
pub tuners: HashMap<String, Vec<TunerSample>>,
}
impl Stats {
/// Samples newer than `since` (unix seconds); everything when `since` is 0.
pub fn history(&self, since: i64) -> History {
let g = self.inner.lock().unwrap();
History {
interval: INTERVAL,
samples: g.samples.iter().filter(|s| s.t > since).cloned().collect(),
tuners: g
.tuners
.iter()
.map(|(k, v)| {
(
k.clone(),
v.iter().filter(|s| s.t > since).cloned().collect(),
)
})
.collect(),
}
}
fn push(&self, s: Sample, tuners: Vec<(String, TunerSample)>) {
let mut g = self.inner.lock().unwrap();
g.samples.push_back(s);
while g.samples.len() > KEEP {
g.samples.pop_front();
}
for (id, ts) in tuners {
let q = g.tuners.entry(id).or_default();
q.push_back(ts);
while q.len() > KEEP {
q.pop_front();
}
}
}
}
/// System metrics through the `sysinfo` crate (portable, no hand-parsed /proc files).
struct SysProbe {
sys: sysinfo::System,
nets: sysinfo::Networks,
comps: sysinfo::Components,
pid: Option<sysinfo::Pid>,
}
impl SysProbe {
fn new() -> Self {
let mut p = SysProbe {
sys: sysinfo::System::new(),
nets: sysinfo::Networks::new_with_refreshed_list(),
comps: sysinfo::Components::new_with_refreshed_list(),
pid: sysinfo::get_current_pid().ok(),
};
// first refresh = baseline for the CPU/network deltas
p.refresh();
p
}
fn refresh(&mut self) {
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate};
self.sys.refresh_cpu_usage();
self.sys.refresh_memory();
if let Some(pid) = self.pid {
self.sys.refresh_processes_specifics(
ProcessesToUpdate::Some(&[pid]),
false,
ProcessRefreshKind::nothing().with_cpu().with_memory(),
);
}
self.nets.refresh(true);
self.comps.refresh(false);
}
/// Whole-system CPU use (%).
fn cpu(&self) -> Option<f64> {
Some(self.sys.global_cpu_usage() as f64).filter(|v| v.is_finite())
}
/// CPU use of this process (% of one core).
fn proc_cpu(&self) -> Option<f64> {
self.pid
.and_then(|p| self.sys.process(p))
.map(|p| p.cpu_usage() as f64)
}
fn rss(&self) -> Option<u64> {
self.pid
.and_then(|p| self.sys.process(p))
.map(|p| p.memory())
}
fn mem_used_pct(&self) -> Option<f64> {
let total = self.sys.total_memory() as f64;
let avail = self.sys.available_memory() as f64;
(total > 0.0).then(|| (total - avail) * 100.0 / total)
}
/// Hottest sensor (°C).
fn temperature(&self) -> Option<f64> {
self.comps
.iter()
.filter_map(|c| c.temperature())
.map(|t| t as f64)
.filter(|c| (0.0..150.0).contains(c))
.fold(None, |best: Option<f64>, c| {
Some(best.map_or(c, |b| b.max(c)))
})
}
/// Bytes (rx, tx) of all interfaces except loopback since the previous refresh.
fn net_delta(&self) -> (u64, u64) {
self.nets
.iter()
.filter(|(name, _)| name.as_str() != "lo")
.fold((0, 0), |(r, t), (_, d)| {
(r + d.received(), t + d.transmitted())
})
}
}
/// 1-minute load average (None where the OS has none).
pub fn load_average() -> Option<[f64; 3]> {
let l = sysinfo::System::load_average();
(l.one > 0.0 || l.five > 0.0 || l.fifteen > 0.0).then_some([l.one, l.five, l.fifteen])
}
/// Sampler loop (runs for the lifetime of the server).
pub async fn sampler_task(state: State) {
let mut probe = SysProbe::new();
let (mut prev_out, mut prev_rec) = state.clients.totals();
let mut prev_unc: HashMap<String, u64> = HashMap::new();
let mut prev_t = std::time::Instant::now();
// HLS clients fetch whole segments, so raw per-interval throughput is spiky: average 3 intervals
let mut out_win: VecDeque<f64> = VecDeque::new();
let mut rec_win: VecDeque<f64> = VecDeque::new();
let smooth = |w: &mut VecDeque<f64>, v: f64| {
w.push_back(v);
if w.len() > 3 {
w.pop_front();
}
w.iter().sum::<f64>() / w.len() as f64
};
loop {
tokio::time::sleep(Duration::from_secs(INTERVAL)).await;
let dt = prev_t.elapsed().as_secs_f64().max(0.001);
prev_t = std::time::Instant::now();
probe.refresh();
let (rx, tx) = probe.net_delta();
let (net_rx, net_tx) = (Some(rx as f64 / dt), Some(tx as f64 / dt));
let (out, rec) = state.clients.totals();
let out_bps = smooth(&mut out_win, out.saturating_sub(prev_out) as f64 / dt);
let rec_bps = smooth(&mut rec_win, rec.saturating_sub(prev_rec) as f64 / dt);
prev_out = out;
prev_rec = rec;
let t = crate::db::now();
let tuner_status = state.tuners.status();
let mut tuners = Vec::new();
let mut active = 0;
for s in &tuner_status {
let ts = match &s.active {
Some(a) => {
active += 1;
let unc = a.signal.uncorrected.map(|u| {
let d = prev_unc
.get(&s.id)
.map(|p| u.saturating_sub(*p))
.unwrap_or(0);
prev_unc.insert(s.id.clone(), u);
d
});
TunerSample {
t,
bitrate: a.bitrate_bps,
strength: a.signal.strength_pct,
strength_dbm: a.signal.strength_dbm,
snr: a.signal.snr_db,
unc,
clients: a.subscribers,
locked: a.state == "locked",
}
}
None => {
prev_unc.remove(&s.id);
TunerSample {
t,
..Default::default()
}
}
};
tuners.push((s.id.clone(), ts));
}
let sample = Sample {
t,
cpu: probe.cpu(),
proc_cpu: probe.proc_cpu(),
mem: probe.mem_used_pct(),
rss: probe.rss(),
temp: probe.temperature(),
load1: load_average().map(|l| l[0]),
out_bps,
rec_bps,
net_rx,
net_tx,
clients: state
.clients
.list()
.iter()
.filter(|c| c.kind != "recording")
.count(),
hls_sessions: state
.hls
.list()
.iter()
.filter(|s| !s.done.load(std::sync::atomic::Ordering::Relaxed))
.count(),
tuners_active: active,
};
state.stats.push(sample, tuners);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn history_window_and_since() {
let s = Stats::default();
for t in 1..=(KEEP as i64 + 10) {
s.push(
Sample {
t,
..Default::default()
},
vec![(
"a0".into(),
TunerSample {
t,
..Default::default()
},
)],
);
}
let h = s.history(0);
assert_eq!(h.samples.len(), KEEP);
assert_eq!(h.tuners["a0"].len(), KEEP);
let h = s.history(KEEP as i64 + 8);
assert_eq!(h.samples.len(), 2);
// system metrics come from sysinfo (the sampler tolerates their absence)
let p = SysProbe::new();
assert!(p.cpu().is_some());
assert!(p.mem_used_pct().is_some_and(|m| (0.0..=100.0).contains(&m)));
assert!(p.rss().is_some_and(|r| r > 0));
}
}
+235
View File
@@ -0,0 +1,235 @@
//! Extracts a single service (program) from a full multiplex stream.
//! Emits its own PAT (single program) and PMT with a continuous CC counter.
use crate::ts::packet::{self, Packetizer};
use crate::ts::psi::{build_section_flags, SectionAssembler};
use crate::ts::tables::{parse_pat, parse_pmt, EsKind, Pmt, PID_PAT};
use std::collections::HashSet;
pub struct ServiceFilter {
/// None = first program in the PAT (e.g. ffmpeg output).
sid: Option<u16>,
pmt_pid: Option<u16>,
ts_id: u16,
pat_asm: SectionAssembler,
pmt_asm: SectionAssembler,
pmt_section: Option<Vec<u8>>,
pub pmt: Option<Pmt>,
pids: HashSet<u16>,
pat_out: Packetizer,
pmt_out: Packetizer,
/// Emit PSI only on every n-th PAT to avoid flooding the stream.
psi_tick: u32,
/// Hold ES data until the first keyframe (clean start for TS clients).
gate: bool,
}
impl ServiceFilter {
pub fn new(sid: Option<u16>, pmt_pid: Option<u16>) -> Self {
Self {
sid,
pmt_pid,
ts_id: 1,
pat_asm: SectionAssembler::new(),
pmt_asm: SectionAssembler::new(),
pmt_section: None,
pmt: None,
pids: HashSet::new(),
pat_out: Packetizer::new(PID_PAT),
pmt_out: Packetizer::new(pmt_pid.unwrap_or(0x1000)),
psi_tick: 0,
gate: false,
}
}
/// The stream will start at a keyframe (PSI passes through immediately).
pub fn start_at_keyframe(mut self) -> Self {
self.gate = true;
self
}
pub fn program(&self) -> Option<u16> {
self.sid.or(self.pmt.as_ref().map(|p| p.program))
}
/// Main video stream (PID, codec), or the first audio stream for radio.
pub fn primary(&self) -> Option<(u16, EsKind)> {
let pmt = self.pmt.as_ref()?;
pmt.streams
.iter()
.find(|s| s.kind.is_video())
.or_else(|| pmt.streams.iter().find(|s| s.kind.is_audio()))
.map(|s| (s.pid, s.kind))
}
pub fn ready(&self) -> bool {
self.pmt_section.is_some()
}
/// Writes a fresh PAT + PMT (e.g. at the start of an HLS segment).
pub fn write_psi(&mut self, out: &mut Vec<u8>) {
let (Some(sid), Some(pmt_pid), Some(pmt)) =
(self.program(), self.pmt_pid, self.pmt_section.clone())
else {
return;
};
let body = [
(sid >> 8) as u8,
sid as u8,
0xE0 | (pmt_pid >> 8) as u8,
pmt_pid as u8,
];
let pat = build_section_flags(0x00, false, self.ts_id, 0, 0, 0, &body);
self.pat_out.psi(&pat, out);
self.pmt_out.psi(&pmt, out);
}
/// Processes a source packet; packets belonging to the service go to `out`.
pub fn push(&mut self, pkt: &[u8], out: &mut Vec<u8>) {
let pid = packet::pid(pkt);
if pid == PID_PAT {
for s in self.pat_asm.push(pkt) {
if let Some(pat) = parse_pat(&s) {
self.ts_id = pat.ts_id;
let found = pat
.programs
.iter()
.find(|(p, _)| *p != 0 && self.sid.is_none_or(|sid| sid == *p));
if let Some(&(prog, ppid)) = found {
if self.pmt_pid != Some(ppid) {
self.pmt_pid = Some(ppid);
self.pmt_out = Packetizer::new(ppid);
self.pmt_asm = SectionAssembler::new();
}
if self.sid.is_none()
&& self.pmt.as_ref().is_some_and(|p| p.program != prog)
{
self.pmt = None;
self.pmt_section = None;
}
}
// Send PAT/PMT on ~every 4th source PAT (typically 100 ms -> 400 ms)
self.psi_tick = self.psi_tick.wrapping_add(1);
if self.psi_tick % 4 == 1 {
self.write_psi(out);
}
}
}
return;
}
if Some(pid) == self.pmt_pid {
for s in self.pmt_asm.push(pkt) {
if let Some(pmt) = parse_pmt(&s) {
if self.sid.is_some_and(|sid| sid != pmt.program) {
continue;
}
let changed = self.pmt.as_ref() != Some(&pmt);
if changed {
self.pids.clear();
self.pids.insert(pmt.pcr_pid);
for st in &pmt.streams {
self.pids.insert(st.pid);
}
self.pmt = Some(pmt);
self.pmt_section = Some(s.raw.clone());
self.write_psi(out);
}
}
}
return;
}
if self.pids.contains(&pid) {
if self.gate {
match self.primary() {
Some((ppid, kind)) if ppid == pid && packet::pusi(pkt) => {
let key = !kind.is_video()
|| packet::random_access(pkt)
|| packet::payload(pkt)
.is_some_and(|pl| crate::ts::pes::is_keyframe(kind, pl));
if !key {
return;
}
self.gate = false;
}
_ => return,
}
}
out.extend_from_slice(pkt);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ts::si::SiCollector;
use crate::ts::testgen::GenMux;
#[test]
fn filter_extracts_single_service() {
let mux = GenMux::sample(1, 0x10, &["A", "B", "C"], 1_700_000_000);
let ts = mux.generate(2);
let b = &mux.services[1];
let mut f = ServiceFilter::new(Some(b.sid), Some(b.pmt_pid));
let mut out = Vec::new();
for p in ts.chunks(188) {
f.push(p, &mut out);
}
assert!(f.ready());
assert_eq!(f.primary().unwrap().0, b.video_pid);
let mut si = SiCollector::new(false);
let mut pids = HashSet::new();
for p in out.chunks(188) {
pids.insert(packet::pid(p));
si.push(p);
}
let pat = si.pat.unwrap();
assert_eq!(pat.programs, vec![(b.sid, b.pmt_pid)]);
let expect: HashSet<u16> = [0, b.pmt_pid, b.video_pid, b.audio_pid]
.into_iter()
.collect();
assert_eq!(pids, expect);
// CC continuity for the PAT
let mut last = None;
for p in out.chunks(188).filter(|p| packet::pid(p) == 0) {
let cc = packet::continuity(p);
if let Some(l) = last {
assert_eq!(cc, (l + 1) & 15);
}
last = Some(cc);
}
}
#[test]
fn keyframe_gate_starts_on_idr() {
let mux = GenMux::sample(1, 0x10, &["A"], 1_700_000_000);
let ts = mux.generate(3);
// skip the beginning to land mid-GOP
let start = 188 * 120;
let mut f =
ServiceFilter::new(Some(0x10), Some(mux.services[0].pmt_pid)).start_at_keyframe();
let mut out = Vec::new();
for p in ts[start..].chunks(188) {
f.push(p, &mut out);
}
let first_es = out
.chunks(188)
.find(|p| packet::pid(p) != 0 && packet::pid(p) != mux.services[0].pmt_pid)
.unwrap();
assert_eq!(packet::pid(first_es), mux.services[0].video_pid);
assert!(packet::random_access(first_es));
}
#[test]
fn auto_program_mode() {
let mux = GenMux::sample(1, 0x20, &["Only"], 1_700_000_000);
let ts = mux.generate(1);
let mut f = ServiceFilter::new(None, None);
let mut out = Vec::new();
for p in ts.chunks(188) {
f.push(p, &mut out);
}
assert_eq!(f.program(), Some(0x20));
assert!(!out.is_empty());
}
}
+3
View File
@@ -0,0 +1,3 @@
//! Stream processing: service filter, HLS segmenter, HLS sessions, ffmpeg.
pub mod filter;
pub mod segmenter;
+198
View File
@@ -0,0 +1,198 @@
//! Splits a service stream into HLS (MPEG-TS) segments on keyframe boundaries.
use super::filter::ServiceFilter;
use crate::ts::packet;
use crate::ts::pes;
use bytes::Bytes;
use std::time::Instant;
#[derive(Clone, Debug)]
pub struct Segment {
pub seq: u64,
pub duration: f64,
pub data: Bytes,
/// Segment end time (for bitrate measurement).
pub created: Instant,
}
pub struct Segmenter {
pub filter: ServiceFilter,
target_90k: u64,
max_90k: u64,
buf: Vec<u8>,
start_pts: Option<u64>,
last_pts: Option<u64>,
wall_start: Instant,
started: bool,
next_seq: u64,
scratch: Vec<u8>,
}
impl Segmenter {
pub fn new(filter: ServiceFilter, target_secs: f64, first_seq: u64) -> Self {
let target_90k = (target_secs * 90_000.0) as u64;
Self {
filter,
target_90k,
max_90k: target_90k * 6 + 90_000 * 4,
buf: Vec::with_capacity(2 * 1024 * 1024),
start_pts: None,
last_pts: None,
wall_start: Instant::now(),
started: false,
next_seq: first_seq,
scratch: Vec::with_capacity(188 * 64),
}
}
/// Processes a multiplex packet, returns a finished segment (if any).
pub fn push(&mut self, pkt: &[u8]) -> Option<Segment> {
self.scratch.clear();
let mut scratch = std::mem::take(&mut self.scratch);
self.filter.push(pkt, &mut scratch);
let mut result = None;
for p in scratch.chunks_exact(packet::TS_SIZE) {
if let Some(seg) = self.push_filtered(p) {
result = Some(seg);
}
}
self.scratch = scratch;
result
}
fn push_filtered(&mut self, p: &[u8]) -> Option<Segment> {
let pid = packet::pid(p);
let primary = self.filter.primary();
let mut out = None;
if let Some((ppid, kind)) = primary {
if pid == ppid && packet::pusi(p) {
if let Some(pl) = packet::payload(p) {
let pts = pes::pts(pl);
let key = if kind.is_video() {
packet::random_access(p) || pes::is_keyframe(kind, pl)
} else {
true
};
if let Some(pts) = pts {
self.last_pts = Some(pts);
}
if key {
if !self.started {
self.started = true;
self.begin(pts);
} else {
let elapsed = match (self.start_pts, pts) {
(Some(s), Some(e)) => pes::pts_diff(s, e).max(0) as u64,
_ => (self.wall_start.elapsed().as_secs_f64() * 90_000.0) as u64,
};
if elapsed >= self.target_90k {
out = self.finish(elapsed);
self.begin(pts);
}
}
} else if self.started {
// guard against very long GOPs / missing flags
if let (Some(s), Some(e)) = (self.start_pts, pts) {
let el = pes::pts_diff(s, e).max(0) as u64;
if el > self.max_90k {
out = self.finish(el);
self.begin(Some(e));
}
}
}
}
}
}
if self.started {
self.buf.extend_from_slice(p);
}
out
}
fn begin(&mut self, pts: Option<u64>) {
self.buf.clear();
self.filter.write_psi(&mut self.buf);
self.start_pts = pts;
self.wall_start = Instant::now();
}
fn finish(&mut self, elapsed_90k: u64) -> Option<Segment> {
if self.buf.is_empty() {
return None;
}
let data = Bytes::from(std::mem::replace(
&mut self.buf,
Vec::with_capacity(2 * 1024 * 1024),
));
let seq = self.next_seq;
self.next_seq += 1;
Some(Segment {
seq,
duration: elapsed_90k as f64 / 90_000.0,
data,
created: Instant::now(),
})
}
/// Closes the current segment (e.g. at the end of a recording).
pub fn flush(&mut self) -> Option<Segment> {
if !self.started || self.buf.is_empty() {
return None;
}
let el = match (self.start_pts, self.last_pts) {
(Some(s), Some(e)) => pes::pts_diff(s, e).max(0) as u64,
_ => (self.wall_start.elapsed().as_secs_f64() * 90_000.0) as u64,
};
let seg = self.finish(el.max(1));
self.started = false;
seg
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ts::testgen::GenMux;
fn run(hevc_index: usize, target: f64) -> Vec<Segment> {
let mux = GenMux::sample(1, 0x10, &["A", "B"], 1_700_000_000);
let ts = mux.generate(9);
let s = &mux.services[hevc_index];
let mut seg = Segmenter::new(ServiceFilter::new(Some(s.sid), Some(s.pmt_pid)), target, 0);
let mut out = Vec::new();
for p in ts.chunks(188) {
if let Some(x) = seg.push(p) {
out.push(x);
}
}
out.extend(seg.flush());
out
}
#[test]
fn segments_on_keyframes_h264_and_hevc() {
for idx in [0, 1] {
let segs = run(idx, 2.0);
assert!(segs.len() >= 3, "{}", segs.len());
for (i, s) in segs.iter().enumerate() {
assert_eq!(s.seq, i as u64);
assert_eq!(s.data.len() % 188, 0);
// every segment starts with a PAT
assert_eq!(packet::pid(&s.data[..188]), 0);
if i + 1 < segs.len() {
assert!((s.duration - 2.0).abs() < 0.05, "dur {}", s.duration);
}
}
}
}
#[test]
fn segment_is_valid_standalone_ts() {
let segs = run(0, 1.0);
let mut si = crate::ts::si::SiCollector::new(false);
for p in segs[1].data.chunks(188) {
si.push(p);
}
assert!(si.pmts_complete());
}
}
+8
View File
@@ -0,0 +1,8 @@
//! MPEG-TS stream handling and DVB SI tables.
pub mod packet;
pub mod pes;
pub mod psi;
pub mod si;
pub mod tables;
pub mod testgen;
pub mod text;
+286
View File
@@ -0,0 +1,286 @@
//! Low-level operations on MPEG-TS packets (188 B).
pub const TS_SIZE: usize = 188;
pub const SYNC: u8 = 0x47;
pub const NULL_PID: u16 = 0x1FFF;
#[inline]
pub fn pid(p: &[u8]) -> u16 {
(((p[1] & 0x1F) as u16) << 8) | p[2] as u16
}
#[inline]
pub fn pusi(p: &[u8]) -> bool {
p[1] & 0x40 != 0
}
#[inline]
pub fn transport_error(p: &[u8]) -> bool {
p[1] & 0x80 != 0
}
#[inline]
pub fn scrambled(p: &[u8]) -> bool {
p[3] & 0xC0 != 0
}
#[inline]
pub fn adaptation_control(p: &[u8]) -> u8 {
(p[3] >> 4) & 0x03
}
#[inline]
pub fn continuity(p: &[u8]) -> u8 {
p[3] & 0x0F
}
/// Returns the packet payload (after the header and adaptation field).
pub fn payload(p: &[u8]) -> Option<&[u8]> {
let afc = adaptation_control(p);
if afc & 1 == 0 {
return None;
}
let mut off = 4usize;
if afc & 2 != 0 {
off += 1 + p[4] as usize;
}
if off >= TS_SIZE {
return None;
}
Some(&p[off..TS_SIZE])
}
/// random_access_indicator flag from the adaptation field.
pub fn random_access(p: &[u8]) -> bool {
adaptation_control(p) & 2 != 0 && p[4] > 0 && p[5] & 0x40 != 0
}
/// PCR in 27 MHz units.
pub fn pcr(p: &[u8]) -> Option<u64> {
if adaptation_control(p) & 2 == 0 || p[4] < 7 || p[5] & 0x10 == 0 {
return None;
}
let b = &p[6..12];
let base = ((b[0] as u64) << 25)
| ((b[1] as u64) << 17)
| ((b[2] as u64) << 9)
| ((b[3] as u64) << 1)
| ((b[4] as u64) >> 7);
let ext = (((b[4] & 1) as u64) << 8) | b[5] as u64;
Some(base * 300 + ext)
}
/// Sets the continuity counter of the packet.
#[inline]
pub fn set_continuity(p: &mut [u8], cc: u8) {
p[3] = (p[3] & 0xF0) | (cc & 0x0F);
}
/// Buffer aligning an arbitrary byte stream to TS packets.
#[derive(Default)]
pub struct Aligner {
buf: Vec<u8>,
}
impl Aligner {
pub fn new() -> Self {
Self {
buf: Vec::with_capacity(TS_SIZE * 64),
}
}
/// Appends data and calls `f` for every complete, synchronized packet.
pub fn push<F: FnMut(&[u8])>(&mut self, data: &[u8], mut f: F) {
// Fast path: empty buffer and aligned data.
if self.buf.is_empty()
&& data.len() % TS_SIZE == 0
&& data.chunks(TS_SIZE).all(|c| c[0] == SYNC)
{
for c in data.chunks(TS_SIZE) {
f(c);
}
return;
}
self.buf.extend_from_slice(data);
let mut i = 0usize;
while i + TS_SIZE <= self.buf.len() {
if self.buf[i] != SYNC {
i += 1;
continue;
}
// verify the next sync byte, if available
if i + TS_SIZE < self.buf.len() && self.buf[i + TS_SIZE] != SYNC {
i += 1;
continue;
}
f(&self.buf[i..i + TS_SIZE]);
i += TS_SIZE;
}
self.buf.drain(..i);
if self.buf.len() > TS_SIZE * 1024 {
self.buf.clear();
}
}
}
/// Builds TS packets carrying the given payload (e.g. a PSI section or PES).
/// `pusi_first` sets PUSI in the first packet. The last packet is
/// padded with an adaptation field (stuffing), as required for PES,
/// or with 0xFF bytes (for PSI, when `psi_stuffing`).
pub struct Packetizer {
pub pid: u16,
pub cc: u8,
}
impl Packetizer {
pub fn new(pid: u16) -> Self {
Self { pid, cc: 0 }
}
fn header(&mut self, pusi: bool, afc: u8) -> [u8; 4] {
let h = [
SYNC,
(if pusi { 0x40 } else { 0 }) | ((self.pid >> 8) as u8 & 0x1F),
(self.pid & 0xFF) as u8,
(afc << 4) | (self.cc & 0x0F),
];
self.cc = (self.cc + 1) & 0x0F;
h
}
/// PSI section: pointer_field = 0, 0xFF padding.
pub fn psi(&mut self, section: &[u8], out: &mut Vec<u8>) {
let mut data = Vec::with_capacity(section.len() + 1);
data.push(0);
data.extend_from_slice(section);
let mut first = true;
for chunk in data.chunks(TS_SIZE - 4) {
let h = self.header(first, 1);
out.extend_from_slice(&h);
out.extend_from_slice(chunk);
out.extend(std::iter::repeat_n(0xFF, TS_SIZE - 4 - chunk.len()));
first = false;
}
}
/// PES with optional PCR and random access flag in the first packet.
pub fn pes(&mut self, pes: &[u8], pcr: Option<u64>, rai: bool, out: &mut Vec<u8>) {
let mut off = 0usize;
let mut first = true;
while off < pes.len() {
let mut af: Vec<u8> = Vec::new();
if first && (pcr.is_some() || rai) {
let mut flags = 0u8;
if rai {
flags |= 0x40;
}
af.push(flags);
if let Some(pcr) = pcr {
af[0] |= 0x10;
let base = pcr / 300;
let ext = pcr % 300;
af.push((base >> 25) as u8);
af.push((base >> 17) as u8);
af.push((base >> 9) as u8);
af.push((base >> 1) as u8);
af.push((((base & 1) << 7) as u8) | 0x7E | ((ext >> 8) as u8 & 1));
af.push((ext & 0xFF) as u8);
}
}
let remaining = pes.len() - off;
let mut room = TS_SIZE - 4 - if af.is_empty() { 0 } else { 1 + af.len() };
if remaining < room {
// stuffing needed in the adaptation field
let need = room - remaining;
if af.is_empty() {
// adaptation field: length byte (+ flags if need > 1)
if need == 1 {
// length=0 only
let h = self.header(first, 3);
out.extend_from_slice(&h);
out.push(0);
out.extend_from_slice(&pes[off..]);
return;
}
af.push(0);
af.extend(std::iter::repeat_n(0xFF, need - 2));
} else {
af.extend(std::iter::repeat_n(0xFF, need));
}
room = remaining;
}
let afc = if af.is_empty() { 1 } else { 3 };
let h = self.header(first, afc);
out.extend_from_slice(&h);
if !af.is_empty() {
out.push(af.len() as u8);
out.extend_from_slice(&af);
}
out.extend_from_slice(&pes[off..off + room]);
off += room;
first = false;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn packetizer_pes_roundtrip_sizes() {
let mut p = Packetizer::new(0x100);
let mut out = Vec::new();
let pes: Vec<u8> = (0..1000u32).map(|i| i as u8).collect();
p.pes(&pes, Some(27_000_000), true, &mut out);
assert_eq!(out.len() % TS_SIZE, 0);
let mut collected = Vec::new();
for (i, pkt) in out.chunks(TS_SIZE).enumerate() {
assert_eq!(pkt[0], SYNC);
assert_eq!(pid(pkt), 0x100);
assert_eq!(pusi(pkt), i == 0);
if i == 0 {
assert!(random_access(pkt));
assert_eq!(pcr(pkt), Some(27_000_000));
}
collected.extend_from_slice(payload(pkt).unwrap());
}
assert_eq!(collected, pes);
}
#[test]
fn packetizer_handles_all_tail_sizes() {
for len in 1..400usize {
let mut p = Packetizer::new(0x101);
let mut out = Vec::new();
let pes = vec![0xABu8; len];
p.pes(&pes, None, false, &mut out);
assert_eq!(out.len() % TS_SIZE, 0, "len {len}");
let total: usize = out
.chunks(TS_SIZE)
.map(|c| payload(c).map_or(0, |p| p.len()))
.sum();
assert_eq!(total, len, "len {len}");
}
}
#[test]
fn aligner_resyncs() {
let mut p = Packetizer::new(0x42);
let mut ts = Vec::new();
for _ in 0..5 {
p.pes(&[1u8; 100], None, false, &mut ts);
}
let mut data = vec![0x00, 0x13, 0x47];
data.extend_from_slice(&ts);
let mut a = Aligner::new();
let mut n = 0;
for chunk in data.chunks(77) {
a.push(chunk, |pkt| {
assert_eq!(pid(pkt), 0x42);
n += 1;
});
}
assert!(n >= 4);
}
}
+165
View File
@@ -0,0 +1,165 @@
//! PES headers: PTS and keyframe detection.
use super::tables::EsKind;
/// PTS (90 kHz) from the PES start, if present.
pub fn pts(pes: &[u8]) -> Option<u64> {
if pes.len() < 14 || pes[0] != 0 || pes[1] != 0 || pes[2] != 1 {
return None;
}
let sid = pes[3];
// streams without the extended header
if matches!(sid, 0xBC | 0xBE | 0xBF | 0xF0 | 0xF1 | 0xFF | 0xF2 | 0xF8) {
return None;
}
if pes[7] & 0x80 == 0 {
return None;
}
let p = &pes[9..14];
Some(
(((p[0] >> 1) & 0x07) as u64) << 30
| (p[1] as u64) << 22
| ((p[2] >> 1) as u64) << 15
| (p[3] as u64) << 7
| (p[4] >> 1) as u64,
)
}
/// DTS (90 kHz) from the PES start, if present (otherwise the PTS is the DTS).
pub fn dts(pes: &[u8]) -> Option<u64> {
if pes.len() < 19 || pes[0] != 0 || pes[1] != 0 || pes[2] != 1 || pes[7] & 0xC0 != 0xC0 {
return None;
}
let p = &pes[14..19];
Some(
(((p[0] >> 1) & 0x07) as u64) << 30
| (p[1] as u64) << 22
| ((p[2] >> 1) as u64) << 15
| (p[3] as u64) << 7
| (p[4] >> 1) as u64,
)
}
/// PES header length (ES data offset).
pub fn header_len(pes: &[u8]) -> Option<usize> {
if pes.len() < 9 || pes[0] != 0 || pes[1] != 0 || pes[2] != 1 {
return None;
}
Some(9 + pes[8] as usize)
}
/// Checks whether the first PES fragment contains the start of a keyframe.
pub fn is_keyframe(kind: EsKind, pes: &[u8]) -> bool {
let Some(h) = header_len(pes) else {
return false;
};
if h >= pes.len() {
return false;
}
let es = &pes[h..];
let mut i = 0usize;
while i + 4 <= es.len() {
if es[i] == 0 && es[i + 1] == 0 && es[i + 2] == 1 {
let b = es[i + 3];
match kind {
EsKind::H264 => {
let t = b & 0x1F;
if t == 5 || t == 7 {
return true;
}
}
EsKind::Hevc => {
let t = (b >> 1) & 0x3F;
if (16..=21).contains(&t) || (32..=34).contains(&t) {
return true;
}
}
EsKind::Mpeg2Video => {
if b == 0xB3 {
return true;
}
}
_ => return false,
}
i += 3;
} else {
i += 1;
}
}
false
}
/// Encodes a PTS/DTS timestamp (5 bytes).
pub fn encode_ts(prefix: u8, ts: u64) -> [u8; 5] {
[
(prefix << 4) | ((((ts >> 30) & 0x07) as u8) << 1) | 1,
((ts >> 22) & 0xFF) as u8,
((((ts >> 15) & 0x7F) as u8) << 1) | 1,
((ts >> 7) & 0xFF) as u8,
(((ts & 0x7F) as u8) << 1) | 1,
]
}
/// Builds a PES with PTS only.
pub fn build_pes(stream_id: u8, pts: u64, es: &[u8]) -> Vec<u8> {
let mut v = vec![0, 0, 1, stream_id];
let len = 3 + 5 + es.len();
let l = if len > 0xFFFF || (0xE0..=0xEF).contains(&stream_id) {
0
} else {
len
};
v.extend_from_slice(&(l as u16).to_be_bytes());
v.push(0x80);
v.push(0x80);
v.push(5);
v.extend_from_slice(&encode_ts(0x2, pts));
v.extend_from_slice(es);
v
}
/// PTS difference accounting for 33-bit wraparound.
pub fn pts_diff(a: u64, b: u64) -> i64 {
const WRAP: i64 = 1 << 33;
let mut d = b as i64 - a as i64;
if d < -WRAP / 2 {
d += WRAP;
} else if d > WRAP / 2 {
d -= WRAP;
}
d
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pts_roundtrip() {
for v in [0u64, 1, 90_000, (1 << 33) - 1, 123_456_789] {
let pes = build_pes(0xE0, v, &[0, 0, 0, 1, 0x65]);
assert_eq!(pts(&pes), Some(v));
}
}
#[test]
fn keyframes() {
let idr = build_pes(0xE0, 0, &[0, 0, 0, 1, 0x09, 0xF0, 0, 0, 0, 1, 0x67, 0x42]);
assert!(is_keyframe(EsKind::H264, &idr));
let p = build_pes(0xE0, 0, &[0, 0, 0, 1, 0x09, 0xF0, 0, 0, 0, 1, 0x41, 0x9A]);
assert!(!is_keyframe(EsKind::H264, &p));
// HEVC: AUD (35) + VPS (32)
let h = build_pes(
0xE0,
0,
&[0, 0, 0, 1, 0x46, 0x01, 0x10, 0, 0, 0, 1, 0x40, 0x01],
);
assert!(is_keyframe(EsKind::Hevc, &h));
}
#[test]
fn wrap_diff() {
assert_eq!(pts_diff((1 << 33) - 100, 50), 150);
assert_eq!(pts_diff(100, 50), -50);
}
}
+276
View File
@@ -0,0 +1,276 @@
//! PSI/SI section assembly from TS packets and CRC32/MPEG-2.
use super::packet;
const fn make_crc_table() -> [u32; 256] {
let mut table = [0u32; 256];
let mut i = 0;
while i < 256 {
let mut c = (i as u32) << 24;
let mut j = 0;
while j < 8 {
c = if c & 0x8000_0000 != 0 {
(c << 1) ^ 0x04C1_1DB7
} else {
c << 1
};
j += 1;
}
table[i] = c;
i += 1;
}
table
}
static CRC_TABLE: [u32; 256] = make_crc_table();
pub fn crc32_mpeg(data: &[u8]) -> u32 {
let mut crc = 0xFFFF_FFFFu32;
for &b in data {
crc = (crc << 8) ^ CRC_TABLE[(((crc >> 24) as u8) ^ b) as usize];
}
crc
}
/// Parsed section header with the data field (without CRC).
#[derive(Debug, Clone)]
pub struct Section {
pub table_id: u8,
pub syntax: bool,
pub ext: u16,
pub version: u8,
pub current: bool,
pub number: u8,
pub last_number: u8,
pub raw: Vec<u8>,
}
impl Section {
/// Data between the long header (8 B) and the CRC.
pub fn body(&self) -> &[u8] {
if self.syntax {
&self.raw[8..self.raw.len() - 4]
} else {
&self.raw[3..]
}
}
pub fn parse(raw: Vec<u8>) -> Option<Section> {
if raw.len() < 3 {
return None;
}
let table_id = raw[0];
let syntax = raw[1] & 0x80 != 0;
let len = (((raw[1] & 0x0F) as usize) << 8) | raw[2] as usize;
if raw.len() != len + 3 {
return None;
}
if syntax {
if raw.len() < 12 || crc32_mpeg(&raw) != 0 {
return None;
}
Some(Section {
table_id,
syntax,
ext: ((raw[3] as u16) << 8) | raw[4] as u16,
version: (raw[5] >> 1) & 0x1F,
current: raw[5] & 1 != 0,
number: raw[6],
last_number: raw[7],
raw,
})
} else {
Some(Section {
table_id,
syntax,
ext: 0,
version: 0,
current: true,
number: 0,
last_number: 0,
raw,
})
}
}
}
/// Assembles sections from consecutive packets of one PID.
#[derive(Default)]
pub struct SectionAssembler {
buf: Vec<u8>,
active: bool,
last_cc: Option<u8>,
}
const MAX_SECTION: usize = 4096 + 3;
impl SectionAssembler {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, pkt: &[u8]) -> Vec<Section> {
let mut out = Vec::new();
if packet::transport_error(pkt) {
self.reset();
return out;
}
let Some(pl) = packet::payload(pkt) else {
return out;
};
let cc = packet::continuity(pkt);
if let Some(last) = self.last_cc {
if last == cc {
return out; // duplikat
}
if (last + 1) & 0x0F != cc {
self.reset();
}
}
self.last_cc = Some(cc);
if packet::pusi(pkt) {
let ptr = pl[0] as usize;
if 1 + ptr > pl.len() {
self.reset();
return out;
}
if self.active {
self.buf.extend_from_slice(&pl[1..1 + ptr]);
self.drain(&mut out);
}
self.buf.clear();
self.buf.extend_from_slice(&pl[1 + ptr..]);
self.active = true;
self.drain(&mut out);
} else if self.active {
self.buf.extend_from_slice(pl);
self.drain(&mut out);
}
out
}
fn reset(&mut self) {
self.buf.clear();
self.active = false;
}
fn drain(&mut self, out: &mut Vec<Section>) {
loop {
if !self.active || self.buf.is_empty() {
return;
}
if self.buf[0] == 0xFF {
self.reset();
return;
}
if self.buf.len() < 3 {
return;
}
let len = ((((self.buf[1] & 0x0F) as usize) << 8) | self.buf[2] as usize) + 3;
if len > MAX_SECTION {
self.reset();
return;
}
if self.buf.len() < len {
return;
}
let raw: Vec<u8> = self.buf.drain(..len).collect();
if let Some(s) = Section::parse(raw) {
out.push(s);
}
}
}
}
/// Builds a section with a long header and CRC.
pub fn build_section(
table_id: u8,
ext: u16,
version: u8,
number: u8,
last: u8,
body: &[u8],
) -> Vec<u8> {
build_section_flags(table_id, true, ext, version, number, last, body)
}
pub fn build_section_flags(
table_id: u8,
private_bit: bool,
ext: u16,
version: u8,
number: u8,
last: u8,
body: &[u8],
) -> Vec<u8> {
let len = 5 + body.len() + 4;
let mut s = Vec::with_capacity(len + 3);
s.push(table_id);
s.push(0x80 | if private_bit { 0x40 } else { 0 } | 0x30 | ((len >> 8) as u8 & 0x0F));
s.push((len & 0xFF) as u8);
s.push((ext >> 8) as u8);
s.push((ext & 0xFF) as u8);
s.push(0xC0 | ((version & 0x1F) << 1) | 1);
s.push(number);
s.push(last);
s.extend_from_slice(body);
let crc = crc32_mpeg(&s);
s.extend_from_slice(&crc.to_be_bytes());
s
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ts::packet::Packetizer;
#[test]
fn crc_known_value() {
// PAT with one program (1 -> PID 0x100), ts_id 1
let s = build_section_flags(0x00, false, 1, 0, 0, 0, &[0x00, 0x01, 0xE1, 0x00]);
assert_eq!(crc32_mpeg(&s), 0);
assert_eq!(crc32_mpeg(b"123456789"), 0x0376_E6E7);
}
#[test]
fn assemble_long_section_across_packets() {
let body: Vec<u8> = (0..1000u32).map(|i| (i % 251) as u8).collect();
let sec = build_section(0x50, 0x1234, 3, 0, 0, &body);
let mut ts = Vec::new();
let mut p = Packetizer::new(0x12);
p.psi(&sec, &mut ts);
p.psi(&sec, &mut ts);
let mut a = SectionAssembler::new();
let mut got = Vec::new();
for pkt in ts.chunks(188) {
got.extend(a.push(pkt));
}
assert_eq!(got.len(), 2);
assert_eq!(got[0].ext, 0x1234);
assert_eq!(got[0].version, 3);
assert_eq!(got[0].body(), &body[..]);
}
#[test]
fn cc_discontinuity_drops_partial() {
let body = vec![7u8; 400];
let sec = build_section(0x42, 1, 0, 0, 0, &body);
let mut ts = Vec::new();
let mut p = Packetizer::new(0x11);
p.psi(&sec, &mut ts);
let mut a = SectionAssembler::new();
let pkts: Vec<&[u8]> = ts.chunks(188).collect();
// skip the middle packet
let mut got = Vec::new();
got.extend(a.push(pkts[0]));
got.extend(a.push(pkts[2]));
assert!(got.is_empty());
}
#[test]
fn corrupted_crc_rejected() {
let mut sec = build_section(0x42, 1, 0, 0, 0, &[1, 2, 3, 4]);
sec[9] ^= 0xFF;
assert!(Section::parse(sec).is_none());
}
}
+294
View File
@@ -0,0 +1,294 @@
//! PSI/SI table collector for a full multiplex stream.
use super::packet;
use super::psi::SectionAssembler;
use super::tables::*;
use std::collections::{BTreeMap, HashMap, HashSet};
/// EPG event together with its service id.
#[derive(Debug, Clone)]
pub struct EpgItem {
pub onid: u16,
pub ts_id: u16,
pub service_id: u16,
pub event: EitEvent,
}
#[derive(Default)]
pub struct SiCollector {
asm: HashMap<u16, SectionAssembler>,
pub pat: Option<Pat>,
pub pmts: HashMap<u16, Pmt>,
/// PMT PID -> programs announced on it (several programs may share one PMT PID).
pmt_pids: HashMap<u16, Vec<u16>>,
sdt_services: BTreeMap<u16, SdtService>,
sdt_sections: HashSet<u8>,
sdt_last: Option<u8>,
pub sdt_onid: Option<u16>,
pub sdt_ts_id: Option<u16>,
pub nit: Option<Nit>,
/// Transports (with frequencies) from NIT actual/other – used for mux discovery.
pub nit_transports: Vec<NitTs>,
nit_sections: HashSet<u8>,
nit_last: Option<u8>,
pub collect_eit: bool,
eit_seen: HashSet<(u8, u16, u16, u8, u8)>,
pub epg: Vec<EpgItem>,
pub time: Option<i64>,
/// Last CRC per (pid, table, ext, section) – PAT/PMT/SDT/NIT repeat many times a
/// second and are only parsed again when they change.
seen_crc: HashMap<(u16, u8, u16, u8), u32>,
}
impl SiCollector {
pub fn new(collect_eit: bool) -> Self {
Self {
collect_eit,
..Default::default()
}
}
fn wants(&self, pid: u16) -> bool {
pid == PID_PAT
|| pid == PID_SDT
|| pid == PID_NIT
|| pid == PID_TDT
|| (self.collect_eit && pid == PID_EIT)
|| self.pmt_pids.contains_key(&pid)
}
pub fn push(&mut self, pkt: &[u8]) {
let pid = packet::pid(pkt);
if !self.wants(pid) {
return;
}
let secs = self.asm.entry(pid).or_default().push(pkt);
for s in secs {
if pid != PID_EIT && pid != PID_TDT && s.raw.len() >= 4 {
let n = s.raw.len();
let crc =
u32::from_be_bytes([s.raw[n - 4], s.raw[n - 3], s.raw[n - 2], s.raw[n - 1]]);
if self
.seen_crc
.insert((pid, s.table_id, s.ext, s.number), crc)
== Some(crc)
{
continue;
}
}
match pid {
PID_PAT => {
if let Some(pat) = parse_pat(&s) {
if self.pat.as_ref() != Some(&pat) {
self.pmt_pids.clear();
// programs may come back with unchanged PMTs – parse them again
self.seen_crc.retain(|k, _| k.0 == PID_PAT);
for &(prog, ppid) in &pat.programs {
if prog != 0 {
self.pmt_pids.entry(ppid).or_default().push(prog);
}
}
self.pmts
.retain(|k, _| pat.programs.iter().any(|(p, _)| p == k));
self.pat = Some(pat);
}
}
}
PID_SDT => {
if let Some(sdt) = parse_sdt(&s) {
if sdt.actual {
self.sdt_onid = Some(sdt.onid);
self.sdt_ts_id = Some(sdt.ts_id);
self.sdt_last = Some(s.last_number);
self.sdt_sections.insert(s.number);
for svc in sdt.services {
self.sdt_services.insert(svc.service_id, svc);
}
}
}
}
PID_NIT => {
if s.table_id == 0x40 || s.table_id == 0x41 {
if let Some(n) = parse_nit(&s) {
for t in n.transports {
if t.frequency_hz.is_some()
&& !self
.nit_transports
.iter()
.any(|x| x.frequency_hz == t.frequency_hz)
{
self.nit_transports.push(t);
}
}
}
}
if s.table_id == 0x40 {
if let Some(n) = parse_nit(&s) {
self.nit_last = Some(s.last_number);
self.nit_sections.insert(s.number);
match &mut self.nit {
None => self.nit = Some(n),
Some(cur) => {
if cur.network_name.is_empty() {
cur.network_name = n.network_name;
}
for t in n.transports {
if !cur
.transports
.iter()
.any(|x| x.ts_id == t.ts_id && x.onid == t.onid)
{
cur.transports.push(t);
}
}
}
}
}
}
}
PID_TDT => {
if let Some(t) = parse_tdt(&s) {
self.time = Some(t);
}
}
PID_EIT => {
let key = (
s.table_id,
s.ext,
if s.raw.len() > 10 {
((s.raw[8] as u16) << 8) | s.raw[9] as u16
} else {
0
},
s.version,
s.number,
);
if self.eit_seen.contains(&key) {
continue;
}
if self.eit_seen.len() > 100_000 {
self.eit_seen.clear();
}
self.eit_seen.insert(key);
if let Some(eit) = parse_eit(&s) {
for ev in eit.events {
if ev.start > 0 && !ev.title.is_empty() {
self.epg.push(EpgItem {
onid: eit.onid,
ts_id: eit.ts_id,
service_id: eit.service_id,
event: ev,
});
}
}
}
}
_ => {
if let Some(progs) = self.pmt_pids.get(&pid) {
if let Some(pmt) = parse_pmt(&s) {
if progs.contains(&pmt.program) {
self.pmts.insert(pmt.program, pmt);
}
}
}
}
}
}
}
pub fn sdt_complete(&self) -> bool {
matches!(self.sdt_last, Some(l) if (0..=l).all(|n| self.sdt_sections.contains(&n)))
}
pub fn nit_complete(&self) -> bool {
matches!(self.nit_last, Some(l) if (0..=l).all(|n| self.nit_sections.contains(&n)))
}
pub fn pmts_complete(&self) -> bool {
self.pat.is_some()
&& self
.pmt_pids
.values()
.flatten()
.all(|p| self.pmts.contains_key(p))
}
/// PAT, all PMTs and the SDT are complete.
pub fn basic_complete(&self) -> bool {
self.pmts_complete() && self.sdt_complete()
}
pub fn sdt_services(&self) -> impl Iterator<Item = &SdtService> {
self.sdt_services.values()
}
pub fn take_epg(&mut self) -> Vec<EpgItem> {
std::mem::take(&mut self.epg)
}
/// LCN for a service, if the NIT provides one.
pub fn lcn(&self, ts_id: u16, sid: u16) -> Option<u16> {
let nit = self.nit.as_ref()?;
nit.transports
.iter()
.filter(|t| t.ts_id == ts_id)
.flat_map(|t| t.lcn.iter())
.find(|(s, l, _)| *s == sid && *l > 0)
.map(|(_, l, _)| *l)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ts::testgen::GenMux;
#[test]
fn collects_everything_from_generated_mux() {
let mux = GenMux::sample(0x0003, 0x0451, &["TVP1 HD", "Polsat Śląsk"], 1_700_000_000);
let ts = mux.generate(2);
let mut c = SiCollector::new(true);
for p in ts.chunks(188) {
c.push(p);
}
assert!(c.basic_complete());
assert!(c.nit_complete());
let names: Vec<_> = c.sdt_services().map(|s| s.name.clone()).collect();
assert_eq!(names, vec!["TVP1 HD", "Polsat Śląsk"]);
assert_eq!(c.lcn(3, 0x0452), Some(2));
let pmt = &c.pmts[&0x0451];
assert_eq!(pmt.streams.len(), 2);
assert_eq!(pmt.streams[0].kind, EsKind::H264);
assert_eq!(pmt.streams[1].lang.as_deref(), Some("pol"));
assert_eq!(c.pmts[&0x0452].streams[0].kind, EsKind::Hevc);
let epg = c.take_epg();
// 2 services x (2 p/f + 4 schedule)
assert_eq!(epg.len(), 12);
assert!(epg
.iter()
.any(|e| e.event.title == "Polsat Śląsk - audycja 1"));
assert_eq!(epg[0].event.summary, "Opis wydarzenia: zażółć gęślą jaźń");
assert_eq!(c.nit.as_ref().unwrap().network_name, "Testowa sieć");
assert_eq!(c.time, Some(1_700_000_001));
}
#[test]
fn programs_sharing_one_pmt_pid() {
// e.g. Polish DVB-T multiplexes carry several PMTs on a single PID
let mut mux = GenMux::sample(0x0003, 0x0451, &["TVN HD", "TVN 7"], 1_700_000_000);
mux.services[1].pmt_pid = mux.services[0].pmt_pid;
let ts = mux.generate(2);
let mut c = SiCollector::new(false);
let mut early = false;
for p in ts.chunks(188) {
c.push(p);
if c.pmts_complete() && c.pmts.len() < 2 {
early = true;
}
}
assert!(!early, "PMTs reported complete before both were read");
assert!(c.pmts_complete());
assert_eq!(c.pmts[&0x0451].streams.len(), 2);
assert_eq!(c.pmts[&0x0452].streams.len(), 2);
}
}
+639
View File
@@ -0,0 +1,639 @@
//! PSI/SI tables: PAT, PMT, SDT, NIT, EIT, TDT/TOT.
use super::psi::Section;
use super::text;
use serde::{Deserialize, Serialize};
pub const PID_PAT: u16 = 0x0000;
pub const PID_NIT: u16 = 0x0010;
pub const PID_SDT: u16 = 0x0011;
pub const PID_EIT: u16 = 0x0012;
pub const PID_TDT: u16 = 0x0014;
pub type Descriptor = (u8, Vec<u8>);
pub fn descriptors(mut d: &[u8]) -> Vec<Descriptor> {
let mut out = Vec::new();
while d.len() >= 2 {
let tag = d[0];
let len = d[1] as usize;
if d.len() < 2 + len {
break;
}
out.push((tag, d[2..2 + len].to_vec()));
d = &d[2 + len..];
}
out
}
fn u16be(b: &[u8]) -> u16 {
((b[0] as u16) << 8) | b[1] as u16
}
// ---------------------------------------------------------------- PAT
#[derive(Debug, Clone, PartialEq)]
pub struct Pat {
pub ts_id: u16,
/// (program_number, pmt_pid); program 0 = NIT
pub programs: Vec<(u16, u16)>,
}
pub fn parse_pat(s: &Section) -> Option<Pat> {
if s.table_id != 0x00 {
return None;
}
let programs = s
.body()
.chunks_exact(4)
.map(|c| (u16be(c), u16be(&c[2..]) & 0x1FFF))
.collect();
Some(Pat {
ts_id: s.ext,
programs,
})
}
// ---------------------------------------------------------------- PMT
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EsKind {
Mpeg2Video,
H264,
Hevc,
MpegAudio,
Aac,
AacLatm,
Ac3,
Eac3,
Subtitle,
Teletext,
Other,
}
impl EsKind {
pub fn is_video(self) -> bool {
matches!(self, EsKind::Mpeg2Video | EsKind::H264 | EsKind::Hevc)
}
pub fn is_audio(self) -> bool {
matches!(
self,
EsKind::MpegAudio | EsKind::Aac | EsKind::AacLatm | EsKind::Ac3 | EsKind::Eac3
)
}
pub fn label(self) -> &'static str {
match self {
EsKind::Mpeg2Video => "MPEG-2",
EsKind::H264 => "H.264",
EsKind::Hevc => "HEVC",
EsKind::MpegAudio => "MP2",
EsKind::Aac => "AAC",
EsKind::AacLatm => "AAC-LATM",
EsKind::Ac3 => "AC-3",
EsKind::Eac3 => "E-AC-3",
EsKind::Subtitle => "DVB-SUB",
EsKind::Teletext => "Teletext",
EsKind::Other => "other",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PmtStream {
pub stream_type: u8,
pub pid: u16,
pub kind: EsKind,
pub lang: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Pmt {
pub program: u16,
pub pcr_pid: u16,
pub streams: Vec<PmtStream>,
pub scrambled: bool,
}
fn classify(stream_type: u8, descs: &[Descriptor]) -> EsKind {
match stream_type {
0x01 | 0x02 => EsKind::Mpeg2Video,
0x1B => EsKind::H264,
0x24 => EsKind::Hevc,
0x03 | 0x04 => EsKind::MpegAudio,
0x0F => EsKind::Aac,
0x11 => EsKind::AacLatm,
0x81 => EsKind::Ac3,
0x87 => EsKind::Eac3,
0x06 => {
for (tag, _) in descs {
match tag {
0x6A => return EsKind::Ac3,
0x7A => return EsKind::Eac3,
0x7C => return EsKind::Aac,
0x59 => return EsKind::Subtitle,
0x56 => return EsKind::Teletext,
_ => {}
}
}
EsKind::Other
}
_ => EsKind::Other,
}
}
pub fn parse_pmt(s: &Section) -> Option<Pmt> {
if s.table_id != 0x02 {
return None;
}
let b = s.body();
if b.len() < 4 {
return None;
}
let pcr_pid = u16be(b) & 0x1FFF;
let pil = (u16be(&b[2..]) & 0x0FFF) as usize;
if b.len() < 4 + pil {
return None;
}
let mut scrambled = descriptors(&b[4..4 + pil]).iter().any(|(t, _)| *t == 0x09);
let mut d = &b[4 + pil..];
let mut streams = Vec::new();
while d.len() >= 5 {
let st = d[0];
let pid = u16be(&d[1..]) & 0x1FFF;
let il = (u16be(&d[3..]) & 0x0FFF) as usize;
if d.len() < 5 + il {
break;
}
let descs = descriptors(&d[5..5 + il]);
if descs.iter().any(|(t, _)| *t == 0x09) {
scrambled = true;
}
let lang = descs
.iter()
.find(|(t, v)| *t == 0x0A && v.len() >= 3)
.map(|(_, v)| String::from_utf8_lossy(&v[0..3]).to_string())
.or_else(|| {
descs
.iter()
.find(|(t, v)| (*t == 0x59 || *t == 0x56) && v.len() >= 3)
.map(|(_, v)| String::from_utf8_lossy(&v[0..3]).to_string())
});
streams.push(PmtStream {
stream_type: st,
pid,
kind: classify(st, &descs),
lang,
});
d = &d[5 + il..];
}
Some(Pmt {
program: s.ext,
pcr_pid,
streams,
scrambled,
})
}
// ---------------------------------------------------------------- SDT
#[derive(Debug, Clone, PartialEq)]
pub struct SdtService {
pub service_id: u16,
pub service_type: u8,
pub provider: String,
pub name: String,
pub free_ca: bool,
pub eit_schedule: bool,
pub eit_pf: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Sdt {
pub actual: bool,
pub ts_id: u16,
pub onid: u16,
pub services: Vec<SdtService>,
}
pub fn parse_sdt(s: &Section) -> Option<Sdt> {
if s.table_id != 0x42 && s.table_id != 0x46 {
return None;
}
let b = s.body();
if b.len() < 3 {
return None;
}
let onid = u16be(b);
let mut d = &b[3..];
let mut services = Vec::new();
while d.len() >= 5 {
let sid = u16be(d);
let eit_schedule = d[2] & 0x02 != 0;
let eit_pf = d[2] & 0x01 != 0;
let free_ca = d[3] & 0x10 != 0;
let dl = (u16be(&d[3..]) & 0x0FFF) as usize;
if d.len() < 5 + dl {
break;
}
let mut svc = SdtService {
service_id: sid,
service_type: 0,
provider: String::new(),
name: String::new(),
free_ca,
eit_schedule,
eit_pf,
};
for (tag, v) in descriptors(&d[5..5 + dl]) {
if tag == 0x48 && v.len() >= 3 {
svc.service_type = v[0];
let pl = v[1] as usize;
if v.len() > 2 + pl {
svc.provider = text::decode(&v[2..2 + pl]);
let nl = v[2 + pl] as usize;
let start = 3 + pl;
if v.len() >= start + nl {
svc.name = text::decode(&v[start..start + nl]);
}
}
}
}
services.push(svc);
d = &d[5 + dl..];
}
Some(Sdt {
actual: s.table_id == 0x42,
ts_id: s.ext,
onid,
services,
})
}
/// DVB service type classification.
pub fn service_kind(service_type: u8) -> &'static str {
match service_type {
0x01 | 0x11 | 0x16 | 0x19 | 0x1F | 0x20 => "tv",
0x02 | 0x0A => "radio",
0x0C | 0x10 => "data",
_ => "other",
}
}
// ---------------------------------------------------------------- NIT
#[derive(Debug, Clone, PartialEq, Default)]
pub struct NitTs {
pub ts_id: u16,
pub onid: u16,
/// (service_id, lcn, visible)
pub lcn: Vec<(u16, u16, bool)>,
pub frequency_hz: Option<u64>,
pub bandwidth_hz: Option<u32>,
pub t2_plp: Option<u8>,
/// DVB-C: (symbol rate sym/s, modulation e.g. "qam256")
pub cable: Option<(u32, Option<&'static str>)>,
}
/// BCD number of `digits` digits (most significant first).
pub fn bcd_digits(b: &[u8], digits: usize) -> u64 {
let mut v = 0u64;
for i in 0..digits {
let byte = b[i / 2];
let d = if i % 2 == 0 { byte >> 4 } else { byte & 0x0F };
v = v * 10 + (d.min(9)) as u64;
}
v
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Nit {
pub network_id: u16,
pub network_name: String,
pub transports: Vec<NitTs>,
}
pub fn parse_nit(s: &Section) -> Option<Nit> {
if s.table_id != 0x40 && s.table_id != 0x41 {
return None;
}
let b = s.body();
if b.len() < 2 {
return None;
}
let mut nit = Nit {
network_id: s.ext,
..Default::default()
};
let ndl = (u16be(b) & 0x0FFF) as usize;
if b.len() < 2 + ndl + 2 {
return None;
}
for (tag, v) in descriptors(&b[2..2 + ndl]) {
if tag == 0x40 {
nit.network_name = text::decode(&v);
}
}
let tll = (u16be(&b[2 + ndl..]) & 0x0FFF) as usize;
let mut d = &b[4 + ndl..(4 + ndl + tll).min(b.len())];
while d.len() >= 6 {
let ts_id = u16be(d);
let onid = u16be(&d[2..]);
let tdl = (u16be(&d[4..]) & 0x0FFF) as usize;
if d.len() < 6 + tdl {
break;
}
let mut t = NitTs {
ts_id,
onid,
..Default::default()
};
for (tag, v) in descriptors(&d[6..6 + tdl]) {
match tag {
0x83 | 0x87 => {
if tag == 0x87 {
// LCN v2: channel_list_id, name, country, loop
if v.len() < 2 {
continue;
}
let nl = v[1] as usize;
let off = 2 + nl + 3 + 1;
if v.len() < off {
continue;
}
for c in v[off..].chunks_exact(4) {
t.lcn
.push((u16be(c), u16be(&c[2..]) & 0x03FF, c[2] & 0x80 != 0));
}
} else {
for c in v.chunks_exact(4) {
t.lcn
.push((u16be(c), u16be(&c[2..]) & 0x03FF, c[2] & 0x80 != 0));
}
}
}
0x5A if v.len() >= 5 => {
let f = u32::from_be_bytes([v[0], v[1], v[2], v[3]]) as u64;
t.frequency_hz = Some(f * 10);
t.bandwidth_hz = Some(match v[4] >> 5 {
0 => 8_000_000,
1 => 7_000_000,
2 => 6_000_000,
3 => 5_000_000,
_ => 8_000_000,
});
}
0x44 if v.len() >= 11 => {
// cable_delivery_system_descriptor: frequency XXXX.XXXX MHz, SR XXX.XXXX Msym/s
t.frequency_hz = Some(bcd_digits(&v[0..4], 8) * 100);
let sr = bcd_digits(&v[7..11], 7) * 100;
let m = match v[6] {
1 => Some("qam16"),
2 => Some("qam32"),
3 => Some("qam64"),
4 => Some("qam128"),
5 => Some("qam256"),
_ => None,
};
t.cable = Some((sr as u32, m));
t.bandwidth_hz = Some(8_000_000);
}
0x7F if v.len() >= 2 && v[0] == 0x04 => {
t.t2_plp = Some(v[1]);
}
_ => {}
}
}
nit.transports.push(t);
d = &d[6 + tdl..];
}
Some(nit)
}
// ---------------------------------------------------------------- EIT
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EitEvent {
pub event_id: u16,
pub start: i64,
pub duration: i64,
pub title: String,
pub summary: String,
pub description: String,
pub lang: String,
pub genre: Option<u8>,
pub rating: Option<u8>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Eit {
pub table_id: u8,
pub service_id: u16,
pub ts_id: u16,
pub onid: u16,
pub events: Vec<EitEvent>,
}
fn bcd(b: u8) -> i64 {
((b >> 4) as i64) * 10 + (b & 0x0F) as i64
}
/// MJD + BCD (UTC) -> seconds since the Unix epoch.
pub fn mjd_bcd_to_unix(b: &[u8]) -> Option<i64> {
if b.len() < 5 || b.iter().all(|&x| x == 0xFF) {
return None;
}
let mjd = u16be(b) as i64;
let days = mjd - 40587;
Some(days * 86400 + bcd(b[2]) * 3600 + bcd(b[3]) * 60 + bcd(b[4]))
}
pub fn bcd_duration(b: &[u8]) -> i64 {
bcd(b[0]) * 3600 + bcd(b[1]) * 60 + bcd(b[2])
}
pub fn parse_eit(s: &Section) -> Option<Eit> {
if !(0x4E..=0x6F).contains(&s.table_id) {
return None;
}
let b = s.body();
if b.len() < 6 {
return None;
}
let ts_id = u16be(b);
let onid = u16be(&b[2..]);
let mut d = &b[6..];
let mut events = Vec::new();
while d.len() >= 12 {
let event_id = u16be(d);
let start = mjd_bcd_to_unix(&d[2..7]);
let duration = bcd_duration(&d[7..10]);
let dl = (u16be(&d[10..]) & 0x0FFF) as usize;
if d.len() < 12 + dl {
break;
}
let mut ev = EitEvent {
event_id,
start: start.unwrap_or(0),
duration,
title: String::new(),
summary: String::new(),
description: String::new(),
lang: String::new(),
genre: None,
rating: None,
};
let mut ext_text: Vec<u8> = Vec::new();
let mut ext_items: Vec<(String, String)> = Vec::new();
for (tag, v) in descriptors(&d[12..12 + dl]) {
match tag {
0x4D if v.len() >= 5 => {
if ev.lang.is_empty() || ev.title.is_empty() {
ev.lang = String::from_utf8_lossy(&v[0..3]).to_string();
}
let nl = v[3] as usize;
if v.len() > 4 + nl {
let title = text::decode(&v[4..4 + nl]);
let tl = v[4 + nl] as usize;
let st = 5 + nl;
let summary = if v.len() >= st + tl {
text::decode(&v[st..st + tl])
} else {
String::new()
};
if ev.title.is_empty() {
ev.title = title;
ev.summary = summary;
}
}
}
0x4E if v.len() >= 6 => {
let il = v[4] as usize;
if v.len() < 5 + il + 1 {
continue;
}
let mut items = &v[5..5 + il];
while items.len() >= 2 {
let dl = items[0] as usize;
if items.len() < 1 + dl + 1 {
break;
}
let desc = text::decode(&items[1..1 + dl]);
let il2 = items[1 + dl] as usize;
if items.len() < 2 + dl + il2 {
break;
}
let item = text::decode(&items[2 + dl..2 + dl + il2]);
ext_items.push((desc, item));
items = &items[2 + dl + il2..];
}
let tl = v[5 + il] as usize;
let ts = 6 + il;
if v.len() >= ts + tl {
// Join text fragments raw (the encoding selector is only in the first one)
let chunk = &v[ts..ts + tl];
if ext_text.is_empty() {
ext_text.extend_from_slice(chunk);
} else {
let skip = selector_len(chunk);
ext_text.extend_from_slice(&chunk[skip..]);
}
}
}
0x54 if !v.is_empty() => {
ev.genre = Some(v[0]);
}
0x55 if v.len() >= 4 => {
let r = v[3];
if (1..=0x0F).contains(&r) {
ev.rating = Some(r + 3);
}
}
_ => {}
}
}
let mut desc = text::decode(&ext_text);
for (k, v) in ext_items {
if !desc.is_empty() {
desc.push('\n');
}
desc.push_str(&format!("{k}: {v}"));
}
ev.description = desc;
events.push(ev);
d = &d[12 + dl..];
}
Some(Eit {
table_id: s.table_id,
service_id: s.ext,
ts_id,
onid,
events,
})
}
fn selector_len(b: &[u8]) -> usize {
match b.first() {
Some(0x10) => 3.min(b.len()),
Some(0x1F) => 2.min(b.len()),
Some(x) if *x < 0x20 => 1,
_ => 0,
}
}
/// EPG genre name (ETSI EN 300 468, table 29) – XMLTV category.
pub fn genre_name(g: u8) -> Option<&'static str> {
Some(match g >> 4 {
0x1 => "Movie / Drama",
0x2 => "News / Current affairs",
0x3 => "Show / Game show",
0x4 => "Sport",
0x5 => "Children's / Youth",
0x6 => "Music / Ballet / Dance",
0x7 => "Arts / Culture",
0x8 => "Social / Political issues / Economics",
0x9 => "Education / Science / Factual topics",
0xA => "Leisure hobbies",
0xB => "Special characteristics",
_ => return None,
})
}
// ---------------------------------------------------------------- TDT/TOT
pub fn parse_tdt(s: &Section) -> Option<i64> {
if s.table_id != 0x70 && s.table_id != 0x73 {
return None;
}
mjd_bcd_to_unix(&s.raw[3..])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mjd_conversion() {
// ETSI example: 93/10/13 12:45:00 -> MJD 0xC079
let t = mjd_bcd_to_unix(&[0xC0, 0x79, 0x12, 0x45, 0x00]).unwrap();
assert_eq!(t, 750_516_300);
assert_eq!(bcd_duration(&[0x01, 0x45, 0x30]), 6330);
}
#[test]
fn cable_delivery_descriptor() {
// 346,000 MHz, QAM-256, 6,900 Msym/s
let d = [
0x03, 0x46, 0x00, 0x00, 0xFF, 0xF0, 0x05, 0x00, 0x69, 0x00, 0x0F,
];
assert_eq!(bcd_digits(&d[0..4], 8) * 100, 346_000_000);
assert_eq!(bcd_digits(&d[7..11], 7) * 100, 6_900_000);
}
#[test]
fn service_kinds() {
assert_eq!(service_kind(0x19), "tv");
assert_eq!(service_kind(0x1F), "tv");
assert_eq!(service_kind(0x02), "radio");
}
}
+386
View File
@@ -0,0 +1,386 @@
//! Synthetic DVB multiplex generator (for tests and demo mode).
//! Produces a structurally valid stream: PAT, PMT, SDT, NIT (LCN), EIT p/f
//! and schedule, TDT, plus video PES (H.264/HEVC with an IDR every second) and audio.
use super::packet::Packetizer;
use super::pes::build_pes;
use super::psi::{build_section, build_section_flags};
#[derive(Clone, Debug)]
pub struct GenService {
pub sid: u16,
pub name: String,
pub provider: String,
pub lcn: u16,
pub pmt_pid: u16,
pub video_pid: u16,
pub audio_pid: u16,
pub hevc: bool,
pub radio: bool,
}
#[derive(Clone, Debug)]
pub struct GenEvent {
pub sid: u16,
pub event_id: u16,
pub start: i64,
pub duration: i64,
pub title: String,
pub summary: String,
}
#[derive(Clone, Debug)]
pub struct GenMux {
pub ts_id: u16,
pub onid: u16,
pub network_name: String,
pub services: Vec<GenService>,
pub events: Vec<GenEvent>,
pub start_time: i64,
/// Other network multiplexes announced in the NIT: (ts_id, frequency Hz).
pub other_muxes: Vec<(u16, u64)>,
}
impl GenMux {
/// Sample multiplex resembling a terrestrial mux.
pub fn sample(ts_id: u16, base_sid: u16, names: &[&str], start_time: i64) -> Self {
let mut services = Vec::new();
let mut events = Vec::new();
for (i, n) in names.iter().enumerate() {
let sid = base_sid + i as u16;
let base_pid = 0x100 + (i as u16) * 0x10;
services.push(GenService {
sid,
name: n.to_string(),
provider: "Test".into(),
lcn: (i + 1) as u16,
pmt_pid: base_pid,
video_pid: base_pid + 1,
audio_pid: base_pid + 2,
hevc: i % 2 == 1,
radio: false,
});
let hour = start_time - start_time % 3600;
for k in 0..4i64 {
events.push(GenEvent {
sid,
event_id: (100 + k) as u16,
start: hour + k * 3600,
duration: 3600,
title: format!("{n} - audycja {}", k + 1),
summary: "Opis wydarzenia: zażółć gęślą jaźń".into(),
});
}
}
GenMux {
ts_id,
onid: 0x22D4,
network_name: "Testowa sieć".into(),
other_muxes: vec![],
services,
events,
start_time,
}
}
/// Generates `seconds` seconds of stream.
pub fn generate(&self, seconds: u32) -> Vec<u8> {
let mut out = Vec::new();
let mut pat = Packetizer::new(0x0000);
let mut sdt = Packetizer::new(0x0011);
let mut nit = Packetizer::new(0x0010);
let mut eit = Packetizer::new(0x0012);
let mut tdt = Packetizer::new(0x0014);
// one packetizer per PMT PID (programs may share a PID, CC must stay continuous)
let mut pmts: std::collections::BTreeMap<u16, Packetizer> = self
.services
.iter()
.map(|s| (s.pmt_pid, Packetizer::new(s.pmt_pid)))
.collect();
let mut vids: Vec<Packetizer> = self
.services
.iter()
.map(|s| Packetizer::new(s.video_pid))
.collect();
let mut auds: Vec<Packetizer> = self
.services
.iter()
.map(|s| Packetizer::new(s.audio_pid))
.collect();
let pat_sec = self.pat();
let pmt_secs: Vec<Vec<u8>> = self.services.iter().map(|s| self.pmt(s)).collect();
let sdt_sec = self.sdt();
let nit_sec = self.nit();
let eit_secs = self.eit();
let fps = 25u64;
let frames = seconds as u64 * fps;
for f in 0..frames {
let t90 = 90_000 + f * 3600; // 90 kHz
if f % 5 == 0 {
pat.psi(&pat_sec, &mut out);
for (i, s) in self.services.iter().enumerate() {
pmts.get_mut(&s.pmt_pid)
.unwrap()
.psi(&pmt_secs[i], &mut out);
}
sdt.psi(&sdt_sec, &mut out);
}
if f % fps == 0 {
nit.psi(&nit_sec, &mut out);
for e in &eit_secs {
eit.psi(e, &mut out);
}
let now = self.start_time + (f / fps) as i64;
tdt.psi(&tdt_section(now), &mut out);
}
let key = f % fps == 0;
for (i, s) in self.services.iter().enumerate() {
if !s.radio {
let es = video_frame(s.hevc, key, f);
let pes = build_pes(0xE0, t90 + 3600, &es);
vids[i].pes(&pes, Some(t90 * 300), key, &mut out);
}
let mut aes = vec![0xFF, 0xF1, 0x50, 0x80, 0x10, 0x1F, 0xFC];
aes.extend(std::iter::repeat_n((f & 0xFF) as u8, 120));
let apes = build_pes(0xC0, t90 + 3600, &aes);
let pcr = if s.radio { Some(t90 * 300) } else { None };
auds[i].pes(&apes, pcr, s.radio, &mut out);
}
}
out
}
/// Injects this configuration's NIT (LCN) and EIT into an existing TS stream
/// (e.g. one generated by ffmpeg) every `every` packets.
pub fn inject_si(&self, ts: &[u8], every: usize) -> Vec<u8> {
let mut nit = Packetizer::new(0x0010);
let mut eit = Packetizer::new(0x0012);
let nit_sec = self.nit();
let eit_secs = self.eit();
let mut out = Vec::with_capacity(ts.len() + ts.len() / 20);
for (i, p) in ts.chunks_exact(188).enumerate() {
if i % every.max(1) == 0 {
nit.psi(&nit_sec, &mut out);
for e in &eit_secs {
eit.psi(e, &mut out);
}
}
out.extend_from_slice(p);
}
out
}
fn pat(&self) -> Vec<u8> {
let mut body = vec![0x00, 0x00, 0xE0, 0x10];
for s in &self.services {
body.extend_from_slice(&s.sid.to_be_bytes());
body.extend_from_slice(&(0xE000 | s.pmt_pid).to_be_bytes());
}
build_section_flags(0x00, false, self.ts_id, 1, 0, 0, &body)
}
fn pmt(&self, s: &GenService) -> Vec<u8> {
let pcr = if s.radio { s.audio_pid } else { s.video_pid };
let mut body = Vec::new();
body.extend_from_slice(&(0xE000 | pcr).to_be_bytes());
body.extend_from_slice(&0xF000u16.to_be_bytes());
if !s.radio {
body.push(if s.hevc { 0x24 } else { 0x1B });
body.extend_from_slice(&(0xE000 | s.video_pid).to_be_bytes());
body.extend_from_slice(&0xF000u16.to_be_bytes());
}
body.push(0x0F);
body.extend_from_slice(&(0xE000 | s.audio_pid).to_be_bytes());
let lang = [0x0A, 4, b'p', b'o', b'l', 0];
body.extend_from_slice(&(0xF000 | lang.len() as u16).to_be_bytes());
body.extend_from_slice(&lang);
build_section_flags(0x02, false, s.sid, 1, 0, 0, &body)
}
fn sdt(&self) -> Vec<u8> {
let mut body = Vec::new();
body.extend_from_slice(&self.onid.to_be_bytes());
body.push(0xFF);
for s in &self.services {
let mut d = Vec::new();
let prov = dvb_str(&s.provider);
let name = dvb_str(&s.name);
d.push(0x48);
d.push((3 + prov.len() + name.len()) as u8);
d.push(if s.radio {
0x02
} else if s.hevc {
0x1F
} else {
0x19
});
d.push(prov.len() as u8);
d.extend_from_slice(&prov);
d.push(name.len() as u8);
d.extend_from_slice(&name);
body.extend_from_slice(&s.sid.to_be_bytes());
body.push(0xFC | 0x03);
body.extend_from_slice(&(0x8000 | d.len() as u16).to_be_bytes());
body.extend_from_slice(&d);
}
build_section(0x42, self.ts_id, 1, 0, 0, &body)
}
fn nit(&self) -> Vec<u8> {
let mut body = Vec::new();
let nn = dvb_str(&self.network_name);
let mut nd = vec![0x40, nn.len() as u8];
nd.extend_from_slice(&nn);
body.extend_from_slice(&(0xF000 | nd.len() as u16).to_be_bytes());
body.extend_from_slice(&nd);
let mut lcn = vec![0x83, (self.services.len() * 4) as u8];
for s in &self.services {
lcn.extend_from_slice(&s.sid.to_be_bytes());
lcn.extend_from_slice(&(0xFC00 | s.lcn).to_be_bytes());
}
let mut ts = Vec::new();
ts.extend_from_slice(&self.ts_id.to_be_bytes());
ts.extend_from_slice(&self.onid.to_be_bytes());
ts.extend_from_slice(&(0xF000 | lcn.len() as u16).to_be_bytes());
ts.extend_from_slice(&lcn);
for (tsid, hz) in &self.other_muxes {
let f = (hz / 10) as u32;
let mut d = vec![0x5A, 11];
d.extend_from_slice(&f.to_be_bytes());
d.extend_from_slice(&[0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
ts.extend_from_slice(&tsid.to_be_bytes());
ts.extend_from_slice(&self.onid.to_be_bytes());
ts.extend_from_slice(&(0xF000 | d.len() as u16).to_be_bytes());
ts.extend_from_slice(&d);
}
body.extend_from_slice(&(0xF000 | ts.len() as u16).to_be_bytes());
body.extend_from_slice(&ts);
build_section(0x40, 0x3001, 1, 0, 0, &body)
}
fn eit(&self) -> Vec<Vec<u8>> {
let mut out = Vec::new();
for s in &self.services {
let evs: Vec<&GenEvent> = self.events.iter().filter(|e| e.sid == s.sid).collect();
// p/f: the first two events
for (num, e) in evs.iter().take(2).enumerate() {
out.push(eit_section(
0x4E,
s.sid,
self.ts_id,
self.onid,
num as u8,
1,
&[e],
));
}
if !evs.is_empty() {
out.push(eit_section(0x50, s.sid, self.ts_id, self.onid, 0, 0, &evs));
}
}
out
}
}
fn dvb_str(s: &str) -> Vec<u8> {
// Non-ASCII text is encoded as ISO-8859-2 (selector 0x10 0x00 0x02), as many broadcasters do.
if s.is_ascii() {
return s.as_bytes().to_vec();
}
let (enc, _, _) = encoding_rs::ISO_8859_2.encode(s);
let mut v = vec![0x10, 0x00, 0x02];
v.extend_from_slice(&enc);
v
}
fn to_bcd(v: i64) -> u8 {
(((v / 10) << 4) | (v % 10)) as u8
}
fn mjd_bcd(t: i64) -> [u8; 5] {
let days = t.div_euclid(86400);
let secs = t.rem_euclid(86400);
let mjd = (days + 40587) as u16;
[
(mjd >> 8) as u8,
mjd as u8,
to_bcd(secs / 3600),
to_bcd((secs / 60) % 60),
to_bcd(secs % 60),
]
}
fn eit_section(
tid: u8,
sid: u16,
tsid: u16,
onid: u16,
num: u8,
last: u8,
evs: &[&GenEvent],
) -> Vec<u8> {
let mut body = Vec::new();
body.extend_from_slice(&tsid.to_be_bytes());
body.extend_from_slice(&onid.to_be_bytes());
body.push(last); // segment_last_section_number
body.push(tid);
for e in evs {
let title = dvb_str(&e.title);
let summary = dvb_str(&e.summary);
let mut d = vec![
0x4D,
(5 + title.len() + summary.len()) as u8,
b'p',
b'o',
b'l',
title.len() as u8,
];
d.extend_from_slice(&title);
d.push(summary.len() as u8);
d.extend_from_slice(&summary);
d.extend_from_slice(&[0x54, 2, 0x41, 0x00]);
body.extend_from_slice(&e.event_id.to_be_bytes());
body.extend_from_slice(&mjd_bcd(e.start));
body.extend_from_slice(&[
to_bcd(e.duration / 3600),
to_bcd((e.duration / 60) % 60),
to_bcd(e.duration % 60),
]);
body.extend_from_slice(&(0x8000 | d.len() as u16).to_be_bytes());
body.extend_from_slice(&d);
}
build_section(tid, sid, 1, num, last, &body)
}
fn tdt_section(t: i64) -> Vec<u8> {
let mut s = vec![0x70, 0x70, 0x05];
s.extend_from_slice(&mjd_bcd(t));
s
}
fn video_frame(hevc: bool, key: bool, f: u64) -> Vec<u8> {
let mut es = Vec::new();
if hevc {
es.extend_from_slice(&[0, 0, 0, 1, 0x46, 0x01, 0x50]); // AUD
if key {
es.extend_from_slice(&[0, 0, 0, 1, 0x40, 0x01, 0x0C]); // VPS
es.extend_from_slice(&[0, 0, 0, 1, 0x42, 0x01, 0x01]); // SPS
es.extend_from_slice(&[0, 0, 0, 1, 0x26, 0x01, 0xAF]); // IDR_W_RADL
} else {
es.extend_from_slice(&[0, 0, 0, 1, 0x02, 0x01, 0xD0]); // TRAIL_R
}
} else {
es.extend_from_slice(&[0, 0, 0, 1, 0x09, 0xF0]); // AUD
if key {
es.extend_from_slice(&[0, 0, 0, 1, 0x67, 0x64, 0x00, 0x28]); // SPS
es.extend_from_slice(&[0, 0, 0, 1, 0x68, 0xEE, 0x3C, 0x80]); // PPS
es.extend_from_slice(&[0, 0, 0, 1, 0x65, 0x88, 0x84]); // IDR
} else {
es.extend_from_slice(&[0, 0, 0, 1, 0x41, 0x9A, 0x02]);
}
}
let size = if key { 1500 } else { 400 };
es.extend(std::iter::repeat_n((f & 0x7F) as u8 | 1, size));
es
}
+266
View File
@@ -0,0 +1,266 @@
//! DVB string decoding (ETSI EN 300 468, annex A).
use unicode_normalization::UnicodeNormalization;
/// Decodes a DVB string to UTF-8.
pub fn decode(bytes: &[u8]) -> String {
if bytes.is_empty() {
return String::new();
}
let b = bytes[0];
let s = match b {
0x20..=0xFF => iso6937(bytes),
0x01..=0x0B => iso8859(4 + b as u16, &bytes[1..]),
0x10 => {
if bytes.len() < 3 {
return String::new();
}
let n = ((bytes[1] as u16) << 8) | bytes[2] as u16;
iso8859(n, &bytes[3..])
}
0x11 => ucs2(&bytes[1..]),
0x13 => encoding_rs::GBK
.decode_without_bom_handling(&bytes[1..])
.0
.into_owned(),
0x14 => encoding_rs::BIG5
.decode_without_bom_handling(&bytes[1..])
.0
.into_owned(),
0x15 => utf8(&bytes[1..]),
0x1F => {
if bytes.len() < 2 {
String::new()
} else {
iso6937(&bytes[2..])
}
}
_ => iso6937(&bytes[1..]),
};
clean(&s)
}
fn clean(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'\u{86}' | '\u{87}' | '\u{E086}' | '\u{E087}' => {}
'\u{8A}' | '\u{E08A}' => out.push('\n'),
'\u{80}'..='\u{9F}' | '\u{E080}'..='\u{E09F}' => {}
'\0' => {}
_ => out.push(c),
}
}
out.trim().to_string()
}
fn utf8(b: &[u8]) -> String {
String::from_utf8_lossy(b).into_owned()
}
fn ucs2(b: &[u8]) -> String {
let units: Vec<u16> = b
.chunks_exact(2)
.map(|c| ((c[0] as u16) << 8) | c[1] as u16)
.collect();
String::from_utf16_lossy(&units)
}
fn iso8859(n: u16, b: &[u8]) -> String {
// Control codes 0x80-0x9F are kept as-is (clean() removes them).
let enc = match n {
1 => None,
2 => Some(encoding_rs::ISO_8859_2),
3 => Some(encoding_rs::ISO_8859_3),
4 => Some(encoding_rs::ISO_8859_4),
5 => Some(encoding_rs::ISO_8859_5),
6 => Some(encoding_rs::ISO_8859_6),
7 => Some(encoding_rs::ISO_8859_7),
8 => Some(encoding_rs::ISO_8859_8),
9 => Some(encoding_rs::WINDOWS_1254),
10 => Some(encoding_rs::ISO_8859_10),
11 => Some(encoding_rs::WINDOWS_874),
13 => Some(encoding_rs::ISO_8859_13),
14 => Some(encoding_rs::ISO_8859_14),
15 => Some(encoding_rs::ISO_8859_15),
16 => Some(encoding_rs::ISO_8859_16),
_ => None,
};
match enc {
None => b.iter().map(|&c| c as char).collect(),
Some(e) => {
let mut out = String::with_capacity(b.len());
// decode in chunks to preserve the 0x80-0x9F control bytes
let mut start = 0;
for (i, &c) in b.iter().enumerate() {
if (0x80..=0x9F).contains(&c) {
out.push_str(&e.decode_without_bom_handling(&b[start..i]).0);
out.push(c as char);
start = i + 1;
}
}
out.push_str(&e.decode_without_bom_handling(&b[start..]).0);
out
}
}
}
fn iso6937_upper(c: u8) -> Option<char> {
Some(match c {
0xA0 => '\u{A0}',
0xA1 => '¡',
0xA2 => '¢',
0xA3 => '£',
0xA4 => '€',
0xA5 => '¥',
0xA7 => '§',
0xA8 => '¤',
0xA9 => '‘',
0xAA => '“',
0xAB => '«',
0xAC => '←',
0xAD => '↑',
0xAE => '→',
0xAF => '↓',
0xB0 => '°',
0xB1 => '±',
0xB2 => '²',
0xB3 => '³',
0xB4 => '×',
0xB5 => 'µ',
0xB6 => '¶',
0xB7 => '·',
0xB8 => '÷',
0xB9 => '’',
0xBA => '”',
0xBB => '»',
0xBC => '¼',
0xBD => '½',
0xBE => '¾',
0xBF => '¿',
0xD0 => '―',
0xD1 => '¹',
0xD2 => '®',
0xD3 => '©',
0xD4 => '™',
0xD5 => '♪',
0xD6 => '¬',
0xD7 => '¦',
0xDC => '⅛',
0xDD => '⅜',
0xDE => '⅝',
0xDF => '⅞',
0xE0 => 'Ω',
0xE1 => 'Æ',
0xE2 => 'Đ',
0xE3 => 'ª',
0xE4 => 'Ħ',
0xE6 => 'IJ',
0xE7 => 'Ŀ',
0xE8 => 'Ł',
0xE9 => 'Ø',
0xEA => 'Œ',
0xEB => 'º',
0xEC => 'Þ',
0xED => 'Ŧ',
0xEE => 'Ŋ',
0xEF => 'ʼn',
0xF0 => 'ĸ',
0xF1 => 'æ',
0xF2 => 'đ',
0xF3 => 'ð',
0xF4 => 'ħ',
0xF5 => 'ı',
0xF6 => 'ij',
0xF7 => 'ŀ',
0xF8 => 'ł',
0xF9 => 'ø',
0xFA => 'œ',
0xFB => 'ß',
0xFC => 'þ',
0xFD => 'ŧ',
0xFE => 'ŋ',
0xFF => '\u{AD}',
_ => return None,
})
}
fn combining(c: u8) -> Option<char> {
Some(match c {
0xC1 => '\u{300}',
0xC2 => '\u{301}',
0xC3 => '\u{302}',
0xC4 => '\u{303}',
0xC5 => '\u{304}',
0xC6 => '\u{306}',
0xC7 => '\u{307}',
0xC8 => '\u{308}',
0xCA => '\u{30A}',
0xCB => '\u{327}',
0xCD => '\u{30B}',
0xCE => '\u{328}',
0xCF => '\u{30C}',
_ => return None,
})
}
fn iso6937(b: &[u8]) -> String {
let mut out = String::with_capacity(b.len());
let mut pending: Option<char> = None;
for &c in b {
if let Some(m) = combining(c) {
pending = Some(m);
continue;
}
let ch = if c <= 0x9F {
c as char // ASCII and 0x80-0x9F control codes (removed later)
} else {
match iso6937_upper(c) {
Some(x) => x,
None => continue,
}
};
out.push(ch);
if let Some(m) = pending.take() {
out.push(m);
}
}
out.nfc().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn iso6937_polish() {
// "Łódź" = E8, C2 'o', 'd', C2 'z'
let b = [0xE8, 0xC2, b'o', b'd', 0xC2, b'z'];
assert_eq!(decode(&b), "Łódź");
// "ąę" via the ogonek diacritic
assert_eq!(decode(&[0xCE, b'a', 0xCE, b'e']), "ąę");
}
#[test]
fn iso8859_2() {
// 0x10 0x00 0x02 + "Wiadomości" (ś = 0xB6 in ISO-8859-2)
let mut b = vec![0x10, 0x00, 0x02];
b.extend_from_slice(b"Wiadomo\xB6ci");
assert_eq!(decode(&b), "Wiadomości");
}
#[test]
fn utf8_and_controls() {
let mut b = vec![0x15];
b.extend_from_slice("Zażółć".as_bytes());
assert_eq!(decode(&b), "Zażółć");
let b2 = [b'A', 0x86, b'B', 0x87, 0x8A, b'C'];
assert_eq!(decode(&b2), "AB\nC");
}
#[test]
fn single_byte_table_selector() {
// 0x01 -> ISO-8859-5 (Cyrillic): 0xB0 = 'А'
assert_eq!(decode(&[0x01, 0xB0]), "А");
}
}
+636
View File
@@ -0,0 +1,636 @@
//! Tuner manager: adapter allocation, sharing a multiplex between many clients,
//! preempting background jobs (EPG) and collecting EIT.
use crate::db::Mux;
use crate::dvb::{self, AdapterInfo, SignalStatus, TuneParams};
use crate::ts::packet::Aligner;
use crate::ts::si::{EpgItem, SiCollector};
use anyhow::{anyhow, bail, Result};
use bytes::Bytes;
use serde::Serialize;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use tokio::sync::{broadcast, mpsc, watch};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Priority {
Background,
Normal,
Recording,
}
#[derive(Debug, Clone, PartialEq)]
enum TuneState {
Tuning,
Locked,
Failed(String),
}
pub struct Active {
pub mux_id: i64,
pub params: TuneParams,
tx: broadcast::Sender<Bytes>,
stop: AtomicBool,
subs: Mutex<HashMap<u64, Priority>>,
idle_since: Mutex<Option<Instant>>,
signal: Mutex<SignalStatus>,
bitrate: AtomicU64,
started: Instant,
state: watch::Receiver<TuneState>,
}
impl Active {
fn max_priority(&self) -> Option<Priority> {
self.subs.lock().unwrap().values().copied().max()
}
pub fn is_stopped(&self) -> bool {
self.stop.load(Ordering::Relaxed)
}
}
pub struct Slot {
pub info: AdapterInfo,
pub enabled: AtomicBool,
pub priority: AtomicU64,
active: Mutex<Option<Arc<Active>>>,
thread: Mutex<Option<JoinHandle<()>>>,
last_error: Mutex<String>,
/// Adapter taken by a scan.
pub busy: AtomicBool,
/// The scan holding this adapter is a background (idle) scan that may be preempted.
pub idle_scan: AtomicBool,
/// Asks the scan holding this adapter to stop.
pub scan_cancel: AtomicBool,
}
impl Slot {
/// Waits for the reader thread to finish (device released). Blocking call.
pub fn join_thread(&self) {
if let Some(t) = self.thread.lock().unwrap().take() {
let _ = t.join();
}
}
}
/// Adapter reservation for the duration of a scan.
pub struct ScanGuard(pub Arc<Slot>);
impl Drop for ScanGuard {
fn drop(&mut self) {
self.0.idle_scan.store(false, Ordering::Relaxed);
self.0.scan_cancel.store(false, Ordering::Relaxed);
self.0.busy.store(false, Ordering::Relaxed);
}
}
/// Subscription to a multiplex stream. Dropping it decrements the client count.
pub struct Subscription {
pub active: Arc<Active>,
id: u64,
rx: broadcast::Receiver<Bytes>,
pub adapter: String,
lagged: u64,
}
impl Subscription {
/// Next chunk of TS data; `None` when the tuner has been stopped.
pub async fn recv(&mut self) -> Option<Bytes> {
loop {
if self.active.is_stopped() {
return None;
}
match tokio::time::timeout(Duration::from_secs(1), self.rx.recv()).await {
Ok(Ok(b)) => return Some(b),
Ok(Err(broadcast::error::RecvError::Lagged(n))) => {
self.lagged += n;
tracing::debug!("client is lagging, skipped {n} chunks");
}
Ok(Err(broadcast::error::RecvError::Closed)) => return None,
Err(_) => {}
}
}
}
}
impl Drop for Subscription {
fn drop(&mut self) {
let mut subs = self.active.subs.lock().unwrap();
subs.remove(&self.id);
if subs.is_empty() {
*self.active.idle_since.lock().unwrap() = Some(Instant::now());
}
}
}
#[derive(Serialize)]
pub struct SlotStatus {
pub id: String,
pub name: String,
pub kind: String,
pub path: String,
pub delivery_systems: Vec<String>,
pub enabled: bool,
pub busy: bool,
pub priority: u64,
pub last_error: String,
pub active: Option<ActiveStatus>,
}
#[derive(Serialize)]
pub struct ActiveStatus {
pub mux_id: i64,
pub tuning: String,
pub state: String,
pub subscribers: usize,
pub top_priority: Option<Priority>,
pub signal: SignalStatus,
pub bitrate_bps: u64,
pub uptime_secs: u64,
}
/// Channel for PMTs seen while streaming: (mux id, PMTs).
pub type PmtSender = mpsc::UnboundedSender<(i64, Vec<crate::ts::tables::Pmt>)>;
pub struct TunerManager {
slots: Mutex<Vec<Arc<Slot>>>,
next_id: AtomicU64,
epg_tx: mpsc::UnboundedSender<(i64, Vec<EpgItem>)>,
pub epg_enabled: AtomicBool,
pub linger: Mutex<Duration>,
/// Receives the PMTs seen while streaming (mux id, PMTs) so service stream
/// lists stay current even when a scan timed out before a PMT arrived.
pub pmt_tx: Mutex<Option<PmtSender>>,
}
impl TunerManager {
pub fn new(epg_tx: mpsc::UnboundedSender<(i64, Vec<EpgItem>)>) -> Arc<Self> {
Arc::new(Self {
slots: Mutex::new(Vec::new()),
next_id: AtomicU64::new(1),
epg_tx,
epg_enabled: AtomicBool::new(true),
linger: Mutex::new(Duration::from_secs(8)),
pmt_tx: Mutex::new(None),
})
}
/// Sets the adapter list (keeping active streams of existing ones).
pub fn set_adapters(&self, adapters: Vec<(AdapterInfo, bool, i64)>) {
let mut slots = self.slots.lock().unwrap();
let mut new = Vec::new();
for (info, enabled, prio) in adapters {
if let Some(existing) = slots.iter().find(|s| s.info.id == info.id) {
existing.enabled.store(enabled, Ordering::Relaxed);
existing
.priority
.store(prio.max(0) as u64, Ordering::Relaxed);
new.push(existing.clone());
} else {
new.push(Arc::new(Slot {
info,
enabled: AtomicBool::new(enabled),
priority: AtomicU64::new(prio.max(0) as u64),
active: Mutex::new(None),
thread: Mutex::new(None),
last_error: Mutex::new(String::new()),
busy: AtomicBool::new(false),
idle_scan: AtomicBool::new(false),
scan_cancel: AtomicBool::new(false),
}));
}
}
*slots = new;
}
pub fn adapters(&self) -> Vec<AdapterInfo> {
self.slots
.lock()
.unwrap()
.iter()
.map(|s| s.info.clone())
.collect()
}
pub fn status(&self) -> Vec<SlotStatus> {
self.slots
.lock()
.unwrap()
.iter()
.map(|s| {
let active = s.active.lock().unwrap().as_ref().map(|a| {
let subscribers = a.subs.lock().unwrap().len();
let top_priority = a.max_priority();
let signal = a.signal.lock().unwrap().clone();
ActiveStatus {
mux_id: a.mux_id,
tuning: a.params.describe(),
state: match &*a.state.borrow() {
TuneState::Tuning => "tuning".into(),
TuneState::Locked => "locked".into(),
TuneState::Failed(e) => format!("failed: {e}"),
},
subscribers,
top_priority,
signal,
bitrate_bps: a.bitrate.load(Ordering::Relaxed),
uptime_secs: a.started.elapsed().as_secs(),
}
});
SlotStatus {
id: s.info.id.clone(),
name: s.info.name.clone(),
kind: s.info.kind.clone(),
path: s.info.path.clone(),
delivery_systems: s
.info
.delivery_systems
.iter()
.map(|d| d.label().to_string())
.collect(),
enabled: s.enabled.load(Ordering::Relaxed),
busy: s.busy.load(Ordering::Relaxed),
priority: s.priority.load(Ordering::Relaxed),
last_error: s.last_error.lock().unwrap().clone(),
active,
}
})
.collect()
}
/// Whether the multiplex is currently tuned.
pub fn is_tuned(&self, mux_id: i64) -> bool {
self.slots.lock().unwrap().iter().any(|s| {
s.active
.lock()
.unwrap()
.as_ref()
.is_some_and(|a| a.mux_id == mux_id && !a.is_stopped())
})
}
/// Whether there is a free adapter (without an active stream).
pub fn has_free_adapter(&self) -> bool {
self.slots
.lock()
.unwrap()
.iter()
.any(|s| s.enabled.load(Ordering::Relaxed) && s.active.lock().unwrap().is_none())
}
/// Exclusive adapter access (e.g. scanning): stops it and returns the slot.
pub fn reserve_for_scan(&self, adapter_id: Option<&str>) -> Result<ScanGuard> {
self.reserve(adapter_id, false)
}
/// Reserves a completely idle adapter (no stream at all) for a background scan.
pub fn reserve_for_idle_scan(&self) -> Option<ScanGuard> {
let slots = self.slots.lock().unwrap();
let slot = slots.iter().find(|s| {
s.enabled.load(Ordering::Relaxed)
&& !s.busy.load(Ordering::Relaxed)
&& s.active.lock().unwrap().is_none()
})?;
slot.scan_cancel.store(false, Ordering::Relaxed);
slot.idle_scan.store(true, Ordering::Relaxed);
slot.busy.store(true, Ordering::Relaxed);
Some(ScanGuard(slot.clone()))
}
/// Asks every running scan to stop.
pub fn cancel_scans(&self) {
for s in self.slots.lock().unwrap().iter() {
if s.busy.load(Ordering::Relaxed) {
s.scan_cancel.store(true, Ordering::Relaxed);
}
}
}
/// Stops background scans on adapters able to tune `delsys`; returns true if any was asked to stop.
fn preempt_idle_scans(&self, delsys: dvb::DeliverySystem) -> bool {
let mut any = false;
for s in self.slots.lock().unwrap().iter() {
if s.busy.load(Ordering::Relaxed)
&& s.idle_scan.load(Ordering::Relaxed)
&& s.info.delivery_systems.contains(&delsys)
{
s.scan_cancel.store(true, Ordering::Relaxed);
any = true;
}
}
any
}
fn reserve(&self, adapter_id: Option<&str>, _idle: bool) -> Result<ScanGuard> {
let slots = self.slots.lock().unwrap();
let mut cands: Vec<&Arc<Slot>> = slots
.iter()
.filter(|s| {
s.enabled.load(Ordering::Relaxed)
&& !s.busy.load(Ordering::Relaxed)
&& adapter_id.is_none_or(|id| id == s.info.id)
})
.collect();
cands.sort_by_key(|s| {
let a = s.active.lock().unwrap();
match &*a {
None => 0,
Some(x) if x.subs.lock().unwrap().is_empty() => 1,
Some(x) if x.max_priority() == Some(Priority::Background) => 2,
_ => 3,
}
});
let slot = cands
.first()
.ok_or_else(|| anyhow!("no adapter available"))?;
{
let mut a = slot.active.lock().unwrap();
if let Some(x) = a.as_ref() {
if x.max_priority() > Some(Priority::Background) {
bail!("adapter {} is busy (watching/recording)", slot.info.id);
}
x.stop.store(true, Ordering::Relaxed);
}
*a = None;
}
slot.scan_cancel.store(false, Ordering::Relaxed);
slot.idle_scan.store(false, Ordering::Relaxed);
slot.busy.store(true, Ordering::Relaxed);
Ok(ScanGuard((*slot).clone()))
}
/// Joins a multiplex (sharing) or tunes a free adapter.
pub async fn subscribe(self: &Arc<Self>, mux: &Mux, prio: Priority) -> Result<Subscription> {
let params = mux.params();
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
// A background scan gives way to anything a user (or a recording) asked for.
if prio > Priority::Background
&& !self.has_slot_for(&params)
&& self.preempt_idle_scans(params.delsys)
{
for _ in 0..150 {
if self.has_slot_for(&params) {
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
let (active, slot_id) = {
let slots = self.slots.lock().unwrap();
// 1. already tuned
let mut found = None;
for s in slots.iter() {
let a = s.active.lock().unwrap();
if let Some(x) = a.as_ref() {
if x.mux_id == mux.id
&& x.params == params
&& !x.is_stopped()
&& !matches!(&*x.state.borrow(), TuneState::Failed(_))
{
x.subs.lock().unwrap().insert(id, prio);
*x.idle_since.lock().unwrap() = None;
found = Some((x.clone(), s.info.id.clone()));
break;
}
}
}
match found {
Some(f) => f,
None => {
let slot = self.pick_slot(&slots, &params, prio)?;
let active = self.start(&slot, mux.id, params.clone());
active.subs.lock().unwrap().insert(id, prio);
(active, slot.info.id.clone())
}
}
};
let rx = active.tx.subscribe();
let sub = Subscription {
active: active.clone(),
id,
rx,
adapter: slot_id,
lagged: 0,
};
let mut state = active.state.clone();
let res = tokio::time::timeout(
Duration::from_secs(15),
state.wait_for(|s| *s != TuneState::Tuning),
)
.await;
match res {
Ok(Ok(s)) => match &*s {
TuneState::Locked => Ok(sub),
TuneState::Failed(e) => Err(anyhow!("{e}")),
TuneState::Tuning => unreachable!(),
},
_ => Err(anyhow!("tuning timed out")),
}
}
/// Whether some adapter could take `params` right now without preempting a scan.
fn has_slot_for(&self, params: &TuneParams) -> bool {
self.slots.lock().unwrap().iter().any(|s| {
s.enabled.load(Ordering::Relaxed)
&& !s.busy.load(Ordering::Relaxed)
&& s.info.delivery_systems.contains(&params.delsys)
})
}
fn pick_slot(
&self,
slots: &[Arc<Slot>],
params: &TuneParams,
prio: Priority,
) -> Result<Arc<Slot>> {
let mut cands: Vec<(u8, u64, Arc<Slot>)> = Vec::new();
for s in slots {
if !s.enabled.load(Ordering::Relaxed)
|| s.busy.load(Ordering::Relaxed)
|| !s.info.delivery_systems.contains(&params.delsys)
{
continue;
}
let a = s.active.lock().unwrap();
let rank = match &*a {
None => 0,
Some(x) if x.is_stopped() => 0,
Some(x) if x.subs.lock().unwrap().is_empty() => 1,
Some(x) if matches!(&*x.state.borrow(), TuneState::Failed(_)) => 1,
Some(x)
if x.max_priority()
.is_some_and(|p| p < prio && p == Priority::Background) =>
{
2
}
_ => continue,
};
cands.push((
rank,
u64::MAX - s.priority.load(Ordering::Relaxed),
s.clone(),
));
}
cands.sort_by_key(|(r, p, _)| (*r, *p));
let Some((_, _, slot)) = cands.into_iter().next() else {
if slots.is_empty() {
bail!("no DVB adapters configured");
}
bail!("no free tuner for {}", params.describe());
};
if let Some(old) = slot.active.lock().unwrap().take() {
old.stop.store(true, Ordering::Relaxed);
}
Ok(slot)
}
fn start(self: &Arc<Self>, slot: &Arc<Slot>, mux_id: i64, params: TuneParams) -> Arc<Active> {
let (tx, _) = broadcast::channel::<Bytes>(2048);
let (state_tx, state_rx) = watch::channel(TuneState::Tuning);
let active = Arc::new(Active {
mux_id,
params: params.clone(),
tx,
stop: AtomicBool::new(false),
subs: Mutex::new(HashMap::new()),
idle_since: Mutex::new(None),
signal: Mutex::new(SignalStatus::default()),
bitrate: AtomicU64::new(0),
started: Instant::now(),
state: state_rx,
});
*slot.active.lock().unwrap() = Some(active.clone());
let prev = slot.thread.lock().unwrap().take();
let info = slot.info.clone();
let a = active.clone();
let epg_tx = self.epg_tx.clone();
let collect_eit = self.epg_enabled.load(Ordering::Relaxed);
let pmt_tx = self.pmt_tx.lock().unwrap().clone();
let slot2 = slot.clone();
let handle = std::thread::Builder::new()
.name(format!("dvb-{}", info.id))
.spawn(move || {
if let Some(p) = prev {
let _ = p.join();
}
let r = reader_thread(&info, &a, &state_tx, epg_tx, pmt_tx, collect_eit);
if let Err(e) = r {
let msg = format!("{e:#}");
tracing::warn!("{}: {}", info.id, msg);
*slot2.last_error.lock().unwrap() = msg.clone();
let _ = state_tx.send(TuneState::Failed(msg));
a.stop.store(true, Ordering::Relaxed);
let mut cur = slot2.active.lock().unwrap();
if cur.as_ref().is_some_and(|x| Arc::ptr_eq(x, &a)) {
*cur = None;
}
}
})
.expect("tuner thread");
*slot.thread.lock().unwrap() = Some(handle);
active
}
/// Periodically releases unused tuners.
pub fn reap(&self) {
let linger = *self.linger.lock().unwrap();
for s in self.slots.lock().unwrap().iter() {
let mut a = s.active.lock().unwrap();
let stop = match a.as_ref() {
Some(x) if x.is_stopped() => true,
Some(x) => {
x.subs.lock().unwrap().is_empty()
&& x.idle_since
.lock()
.unwrap()
.is_some_and(|t| t.elapsed() >= linger)
}
None => false,
};
if stop {
if let Some(x) = a.take() {
x.stop.store(true, Ordering::Relaxed);
tracing::info!("{}: released tuner ({})", s.info.id, x.params.describe());
}
}
}
}
pub fn shutdown(&self) {
for s in self.slots.lock().unwrap().iter() {
if let Some(x) = s.active.lock().unwrap().take() {
x.stop.store(true, Ordering::Relaxed);
}
}
}
}
fn reader_thread(
info: &AdapterInfo,
a: &Arc<Active>,
state: &watch::Sender<TuneState>,
epg_tx: mpsc::UnboundedSender<(i64, Vec<EpgItem>)>,
pmt_tx: Option<PmtSender>,
collect_eit: bool,
) -> Result<()> {
let mut src = dvb::open(info)?;
tracing::info!("{}: tuning {}", info.id, a.params.describe());
if !src.tune(&a.params, Duration::from_secs(5))? {
*a.signal.lock().unwrap() = src.status();
bail!("no lock on {}", a.params.describe());
}
*a.signal.lock().unwrap() = src.status();
let _ = state.send(TuneState::Locked);
let mut buf = vec![0u8; 188 * 348];
let mut si = SiCollector::new(collect_eit);
let mut aligner = Aligner::new();
let mut last_stat = Instant::now();
let mut pmts_sent: std::collections::HashMap<u16, crate::ts::tables::Pmt> = Default::default();
let mut bytes = 0u64;
while !a.stop.load(Ordering::Relaxed) {
let n = src.read(&mut buf)?;
if n > 0 {
bytes += n as u64;
aligner.push(&buf[..n], |p| si.push(p));
let _ = a.tx.send(Bytes::copy_from_slice(&buf[..n]));
}
let el = last_stat.elapsed();
if el >= Duration::from_secs(2) {
a.bitrate.store(
(bytes as f64 * 8.0 / el.as_secs_f64()) as u64,
Ordering::Relaxed,
);
bytes = 0;
last_stat = Instant::now();
*a.signal.lock().unwrap() = src.status();
let items = si.take_epg();
if !items.is_empty() {
let _ = epg_tx.send((a.mux_id, items));
}
if let Some(tx) = &pmt_tx {
let changed: Vec<_> = si
.pmts
.values()
.filter(|p| pmts_sent.get(&p.program) != Some(*p))
.cloned()
.collect();
if !changed.is_empty() {
for p in &changed {
pmts_sent.insert(p.program, p.clone());
}
let _ = tx.send((a.mux_id, changed));
}
}
}
}
let items = si.take_epg();
if !items.is_empty() {
let _ = epg_tx.send((a.mux_id, items));
}
tracing::debug!("{}: reader thread finished", info.id);
Ok(())
}
+1625
View File
File diff suppressed because it is too large. Load diff
+138
View File
@@ -0,0 +1,138 @@
//! Panel assets embedded in the binary.
use crate::app::State;
use axum::extract::Path;
use axum::http::{header, StatusCode};
use axum::response::{Html, IntoResponse, Response};
use axum::routing::get;
use axum::Router;
// Single CSS/JS files with unique names (content hash) – see build.rs.
include!(concat!(env!("OUT_DIR"), "/asset_names.rs"));
const INDEX: &str = include_str!("../../web/index.html");
const CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/app.css"));
const JS: &str = include_str!(concat!(env!("OUT_DIR"), "/app.js"));
const FAVICON: &str = include_str!("../../web/favicon.svg");
fn head_assets() -> String {
format!(
r#"<link rel="stylesheet" href="/assets/{CSS_NAME}"><script defer src="/assets/{JS_NAME}"></script>"#
)
}
/// Assets for the stream port: player files (/watch page) and an info page at "/".
pub fn stream_routes() -> Router<State> {
Router::new()
.route("/", get(|| async {
Html(message_page(
"simply-dvb",
"Stream port: /playlist, /playlist.m3u, /xmltv, /epg.xml, /stream/channelid/<id>, /hls/<id>/index.m3u8",
))
}))
.route("/assets/{file}", get(asset))
.route("/favicon.ico", get(|| async { svg(FAVICON) }))
}
pub fn routes() -> Router<State> {
Router::new()
.route("/", get(index))
.route("/assets/{file}", get(asset))
.route("/favicon.ico", get(|| async { svg(FAVICON) }))
}
fn svg(s: &'static str) -> Response {
(
[
(header::CONTENT_TYPE, "image/svg+xml"),
(header::CACHE_CONTROL, "public, max-age=86400"),
],
s,
)
.into_response()
}
async fn index() -> Response {
(
[
(header::CACHE_CONTROL, "no-cache"),
(
header::HeaderName::from_static("content-security-policy"),
csp(),
),
],
Html(INDEX.replace("__ASSETS__", &head_assets())),
)
.into_response()
}
fn csp() -> &'static str {
"default-src 'self'; img-src 'self' data: https: http:; media-src 'self' blob:; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; frame-ancestors 'self'"
}
async fn asset(Path(file): Path<String>) -> Response {
let (ct, body) = if file == CSS_NAME {
("text/css; charset=utf-8", CSS)
} else if file == JS_NAME {
("application/javascript; charset=utf-8", JS)
} else if file == "favicon.svg" {
return svg(FAVICON);
} else {
return (StatusCode::NOT_FOUND, "").into_response();
};
(
[
(header::CONTENT_TYPE, ct),
(header::CACHE_CONTROL, "public, max-age=31536000, immutable"),
],
body,
)
.into_response()
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&#39;")
}
pub fn message_page(title: &str, msg: &str) -> String {
format!(
r#"<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{t}</title>{a}</head>
<body class="bare"><main class="message"><div class="brand-mark">s/d</div><h1>{t}</h1><p>{m}</p></main></body></html>"#,
t = esc(title),
m = esc(msg),
a = head_assets()
)
}
/// Public single-channel player page (share link).
pub fn watch_page(
channel_id: i64,
name: &str,
token: &str,
video: &str,
audio: &str,
server: &str,
transcode: bool,
) -> String {
format!(
r#"<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>{n} – {s}</title><link rel="icon" href="/assets/favicon.svg">{a}</head>
<body class="bare watch">
<header class="watch-head"><div class="brand-mark">s/d</div><div><div class="eyebrow">Live broadcast</div><h1>{n}</h1></div></header>
<main class="watch-main"><div id="player" class="player" data-channel="{id}" data-share="{tok}" data-video="{vc}" data-audio="{ac}" data-transcode="{tc}"></div>
<p class="muted small">Shared by {s}</p></main>
</body></html>"#,
n = esc(name),
s = esc(server),
a = head_assets(),
id = channel_id,
tok = esc(token),
vc = esc(video),
ac = esc(audio),
tc = if transcode { 1 } else { 0 }
)
}
+308
View File
@@ -0,0 +1,308 @@
//! HTTP server: panel (SPA), JSON API and public stream endpoints.
pub mod api;
pub mod assets;
pub mod public;
pub mod tvh;
mod tvhapi;
use crate::app::State;
use crate::auth;
use crate::db::User;
use crate::settings::ip_in;
use axum::extract::{ConnectInfo, Request, State as AxState};
use axum::http::{Method, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post, put};
use axum::{Json, Router};
use std::net::SocketAddr;
#[derive(Debug)]
pub struct ApiError(pub StatusCode, pub String);
impl ApiError {
pub fn bad(msg: impl Into<String>) -> Self {
ApiError(StatusCode::BAD_REQUEST, msg.into())
}
pub fn not_found(msg: impl Into<String>) -> Self {
ApiError(StatusCode::NOT_FOUND, msg.into())
}
pub fn forbidden() -> Self {
ApiError(StatusCode::FORBIDDEN, "permission denied".into())
}
}
impl From<anyhow::Error> for ApiError {
fn from(e: anyhow::Error) -> Self {
ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}"))
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
(self.0, Json(serde_json::json!({ "error": self.1 }))).into_response()
}
}
pub type ApiResult<T> = Result<Json<T>, ApiError>;
/// Signed-in user (inserted by middleware).
#[derive(Clone)]
pub struct CurrentUser(pub User);
async fn api_guard(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
mut req: Request,
next: Next,
) -> Response {
let ip = auth::client_ip(&state, peer, req.headers());
{
let s = state.settings.read().unwrap();
if !s.panel_allow_cidrs.is_empty() && !ip_in(&s.panel_allow_cidrs, ip) {
return ApiError(
StatusCode::FORBIDDEN,
"panel not available from this network".into(),
)
.into_response();
}
}
let path = req.uri().path().to_string();
let method = req.method().clone();
let mutating = !matches!(method, Method::GET | Method::HEAD | Method::OPTIONS);
// CSRF protection: state-changing requests must carry a header that only the panel JS sets.
if mutating
&& req
.headers()
.get("x-requested-with")
.and_then(|v| v.to_str().ok())
!= Some("simply-dvb")
{
return ApiError(
StatusCode::FORBIDDEN,
"missing X-Requested-With header".into(),
)
.into_response();
}
if path == "/api/login" || path == "/api/info" {
return next.run(req).await;
}
let Some(user) = auth::session_user(&state, req.headers()).await else {
return ApiError(StatusCode::UNAUTHORIZED, "login required".into()).into_response();
};
let viewer_ok = path == "/api/logout" || path == "/api/me/password";
if mutating && user.role != "admin" && !viewer_ok {
return ApiError::forbidden().into_response();
}
req.extensions_mut().insert(CurrentUser(user));
next.run(req).await
}
/// Logs every request on the stream port (category "access"), so it is visible what a
/// TV or app asks for – including paths simply-dvb does not provide.
async fn request_log(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
req: Request,
next: Next,
) -> Response {
let method = req.method().clone();
let uri = req.uri().clone();
let ip = auth::client_ip(&state, peer, req.headers());
let ua: String = req
.headers()
.get(axum::http::header::USER_AGENT)
.and_then(|v| v.to_str().ok())
.unwrap_or("-")
.chars()
.take(120)
.collect();
let started = std::time::Instant::now();
let res = next.run(req).await;
let status = res.status();
let path = uri.path();
// hide tokens in the logged query string
let query = uri
.query()
.map(|q| {
url::form_urlencoded::parse(q.as_bytes())
.map(|(k, v)| {
if matches!(&*k, "token" | "auth" | "ticket") {
format!("{k}=***")
} else {
format!("{k}={v}")
}
})
.collect::<Vec<_>>()
.join("&")
})
.filter(|q| !q.is_empty())
.map(|q| format!("?{q}"))
.unwrap_or_default();
let ms = started.elapsed().as_millis();
let noisy = path.starts_with("/hls/")
|| path.starts_with("/imagecache/")
|| path.starts_with("/icons/")
|| path == "/healthz"
|| path == "/metrics";
if status.is_client_error() || status.is_server_error() {
tracing::warn!(target: "access", "{ip} {method} {path}{query} → {} ({ms} ms) · {ua}", status.as_u16());
} else if noisy {
tracing::debug!(target: "access", "{ip} {method} {path}{query} → {} ({ms} ms) · {ua}", status.as_u16());
} else {
tracing::info!(target: "access", "{ip} {method} {path}{query} → {} ({ms} ms) · {ua}", status.as_u16());
}
res
}
async fn security_headers(req: Request, next: Next) -> Response {
let mut res = next.run(req).await;
let h = res.headers_mut();
h.entry("x-content-type-options")
.or_insert("nosniff".parse().unwrap());
h.entry("referrer-policy")
.or_insert("same-origin".parse().unwrap());
res
}
pub fn router(state: State) -> Router {
let api = Router::new()
.route("/api/info", get(api::info))
.route("/api/login", post(api::login))
.route("/api/logout", post(api::logout))
.route("/api/me", get(api::me))
.route("/api/me/password", post(api::change_password))
.route("/api/status", get(api::status))
.route("/api/stats", get(api::stats))
.route("/api/logs", get(api::logs))
.route("/api/logs/download", get(api::logs_download))
.route("/api/recordings/schedule", get(api::recordings_schedule))
.route("/api/adapters", get(api::adapters))
.route("/api/adapters/refresh", post(api::adapters_refresh))
.route("/api/adapters/{id}", put(api::adapter_update))
.route("/api/muxes", get(api::muxes).post(api::mux_create))
.route(
"/api/muxes/{id}",
put(api::mux_update).delete(api::mux_delete),
)
.route("/api/services", get(api::services))
.route(
"/api/scan",
get(api::scan_status)
.post(api::scan_start)
.delete(api::scan_cancel),
)
.route("/api/scan/presets", get(api::scan_presets))
.route(
"/api/channels",
get(api::channels).post(api::channel_create),
)
.route("/api/channels/order", post(api::channels_order))
.route("/api/channels/probe", post(api::channels_probe))
.route(
"/api/channels/icons/search",
post(api::icons_search).get(api::icons_search_status),
)
.route(
"/api/channels/{id}",
put(api::channel_update).delete(api::channel_delete),
)
.route("/api/channels/{id}/share", post(api::channel_share))
.route(
"/api/channels/{id}/icon",
post(api::channel_icon_upload).delete(api::channel_icon_delete),
)
.route("/api/epg", get(api::epg))
.route("/api/epg/grab", post(api::epg_grab))
.route("/api/epg/xmltv", post(api::epg_xmltv))
.route("/api/epg/status", get(api::epg_status))
.route("/api/epg/xmltv/channels", get(api::xmltv_channels))
.route(
"/api/recordings",
get(api::recordings).post(api::recording_create),
)
.route(
"/api/recordings/{id}",
put(api::recording_update).delete(api::recording_delete),
)
.route("/api/recordings/{id}/stop", post(api::recording_stop))
.route("/api/autorec", get(api::autorecs).post(api::autorec_create))
.route("/api/autorec/preview", get(api::autorec_preview))
.route(
"/api/autorec/{id}",
put(api::autorec_update).delete(api::autorec_delete),
)
.route("/api/backup", get(api::backup))
.route("/api/restore", post(api::restore))
.route(
"/api/settings",
get(api::settings_get).put(api::settings_put),
)
.route("/api/users", get(api::users).post(api::user_create))
.route(
"/api/users/{id}",
put(api::user_update).delete(api::user_delete),
)
.route("/api/tokens", get(api::tokens).post(api::token_create))
.route(
"/api/tokens/{id}",
put(api::token_update).delete(api::token_delete),
)
.route("/api/clients", get(api::clients))
.route("/api/links", get(api::links))
.layer(axum::extract::DefaultBodyLimit::max(16 * 1024 * 1024))
.layer(middleware::from_fn_with_state(state.clone(), api_guard));
// streams and the tvheadend JSON API work on the panel port as well (tvheadend serves both on
// one port, so apps keep working whichever port they are pointed at); requests are logged
let shared = public_routes()
.merge(tvhapi::routes())
.layer(middleware::from_fn_with_state(state.clone(), request_log));
Router::new()
.merge(api)
.merge(shared)
.merge(assets::routes())
.layer(middleware::from_fn(security_headers))
.with_state(state)
}
/// Stream, playlist and EPG endpoints – shared by the panel port and the stream port.
fn public_routes() -> Router<State> {
Router::new()
// natywne
.route("/playlist.m3u", get(public::playlist))
.route("/playlist.m3u8", get(public::playlist))
.route("/epg.xml", get(public::epg_xml))
.route("/hls/{ch}/index.m3u8", get(public::hls_playlist))
.route("/hls/{ch}/{seg}", get(public::hls_segment))
.route("/stream/{ch}", get(public::ts_stream))
.route("/icons/{id}", get(public::icon))
.route("/watch/{token}", get(public::watch_page))
.route(
"/recordings/{id}/index.m3u8",
get(public::recording_playlist),
)
.route("/recordings/{id}/file", get(public::recording_file))
.route("/metrics", get(public::metrics))
.route("/healthz", get(|| async { "ok" }))
// tvheadend-compatible
.route("/playlist", get(tvh::playlist_all))
.route("/playlist/{a}", get(tvh::playlist_all_sub))
.route("/playlist/{kind}/{key}", get(tvh::playlist_one))
.route("/stream/{kind}/{key}", get(tvh::stream))
.route("/xmltv", get(public::epg_xml))
.route("/xmltv/{a}", get(public::epg_xml))
.route("/imagecache/{id}", get(public::icon))
}
/// Stream port router (9981 by default, like tvheadend's HTTP): no panel and no API.
pub fn stream_router(state: State) -> Router {
Router::new()
.merge(public_routes())
.merge(tvhapi::routes())
.merge(assets::stream_routes())
.layer(middleware::from_fn(security_headers))
.layer(middleware::from_fn_with_state(state.clone(), request_log))
.with_state(state)
}
+792
View File
@@ -0,0 +1,792 @@
#![allow(clippy::result_large_err)]
//! Public endpoints: M3U, XMLTV, HLS, MPEG-TS, icons, sharing, recordings.
use super::ApiError;
use crate::app::State;
use crate::auth::{self, AuthQuery, StreamAccess};
use crate::clients::NewClient;
use crate::pipeline;
use crate::tuner::Priority;
use axum::body::Body;
use axum::extract::{ConnectInfo, Path, Query, State as AxState};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::{Html, IntoResponse, Redirect, Response};
use futures_util::StreamExt;
use serde::Deserialize;
use std::net::SocketAddr;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio_util::io::ReaderStream;
#[derive(Deserialize, Default)]
pub struct StreamQuery {
token: Option<String>,
/// tvheadend: persistent authentication code (`?auth=`)
auth: Option<String>,
/// tvheadend: ticket (`?ticket=`)
ticket: Option<String>,
share: Option<String>,
profile: Option<String>,
format: Option<String>,
}
impl StreamQuery {
pub(crate) fn auth(&self) -> AuthQuery {
AuthQuery {
token: self
.token
.clone()
.or_else(|| self.auth.clone())
.or_else(|| self.ticket.clone()),
share: self.share.clone(),
}
}
pub(crate) fn profile(&self) -> Result<String, ApiError> {
Ok(pipeline::normalize_profile(self.profile.as_deref().unwrap_or("pass")).to_string())
}
}
pub(crate) fn unauthorized() -> Response {
(
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Basic realm=\"simply-dvb\"")],
"access denied – use a token (?token=...) or the local network",
)
.into_response()
}
pub struct Ctx {
pub(crate) access: StreamAccess,
ip: String,
ua: String,
}
#[allow(clippy::result_large_err)]
pub(crate) async fn access(
state: &State,
peer: SocketAddr,
headers: &HeaderMap,
q: &StreamQuery,
) -> Result<Ctx, Response> {
let ip = auth::client_ip(state, peer, headers);
let ua = headers
.get(header::USER_AGENT)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let a = match auth::stream_access(state, ip, headers, &q.auth()).await {
Some(a) => a,
None => {
tracing::warn!(target: "access", "stream access denied for {ip} ({ua}) – no token, outside open networks");
return Err(unauthorized());
}
};
if !matches!(a, auth::StreamAccess::Network) {
tracing::debug!(target: "access", "stream access for {ip}: {}", a.who());
}
Ok(Ctx {
access: a,
ip: ip.to_string(),
ua: ua.to_string(),
})
}
fn strip_ext(s: &str) -> &str {
s.split('.').next().unwrap_or(s)
}
#[allow(clippy::result_large_err)]
fn parse_id(s: &str) -> Result<i64, Response> {
strip_ext(s)
.parse()
.map_err(|_| (StatusCode::NOT_FOUND, "not found").into_response())
}
// ------------------------------------------------------------ M3U / XMLTV
pub async fn playlist(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Query(q): Query<StreamQuery>,
) -> Response {
let ctx = match access(&state, peer, &headers, &q).await {
Ok(c) => c,
Err(r) => return r,
};
if matches!(ctx.access, StreamAccess::Share(_)) {
return unauthorized();
}
let s = state.settings();
let base = auth::base_url(&state, peer, &headers);
let format = q.format.clone().unwrap_or(s.m3u_format.clone());
let profile = match q.profile() {
Ok(p) => p,
Err(e) => return e.into_response(),
};
let channels = match state.db.channels().await {
Ok(c) => c,
Err(e) => return ApiError::from(e).into_response(),
};
let auth_q = ctx.access.query();
let body = crate::m3u::build(
&channels,
&crate::m3u::M3uOptions {
base: &base,
format: if format == "hls" { "hls" } else { "ts" },
profile: &profile,
auth: &auth_q,
},
);
(
[
(header::CONTENT_TYPE, "audio/x-mpegurl; charset=utf-8"),
(
header::CONTENT_DISPOSITION,
"inline; filename=\"simply-dvb.m3u\"",
),
(header::CACHE_CONTROL, "no-cache"),
],
body,
)
.into_response()
}
pub async fn epg_xml(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Query(q): Query<StreamQuery>,
) -> Response {
let ctx = match access(&state, peer, &headers, &q).await {
Ok(c) => c,
Err(r) => return r,
};
if matches!(ctx.access, StreamAccess::Share(_)) {
return unauthorized();
}
let base = auth::base_url(&state, peer, &headers);
let aq = ctx.access.query();
let query = if aq.is_empty() {
String::new()
} else {
format!("?{aq}")
};
match crate::epg::export_xmltv(&state, &base, &query).await {
Ok(x) => (
[
(header::CONTENT_TYPE, "application/xml; charset=utf-8"),
(header::CACHE_CONTROL, "no-cache"),
],
x,
)
.into_response(),
Err(e) => ApiError::from(e).into_response(),
}
}
// ------------------------------------------------------------ HLS
fn hls_suffix(ctx: &Ctx, q: &StreamQuery, profile: &str) -> String {
let mut parts = Vec::new();
if profile != "pass" {
parts.push(format!("profile={profile}"));
}
match &ctx.access {
StreamAccess::Token(t) => parts.push(format!("token={}", t.token)),
StreamAccess::Share(_) => {
parts.push(format!("share={}", q.share.clone().unwrap_or_default()))
}
_ => {}
}
if parts.is_empty() {
String::new()
} else {
format!("?{}", parts.join("&"))
}
}
pub async fn hls_playlist(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path(ch): Path<String>,
Query(q): Query<StreamQuery>,
) -> Response {
let ctx = match access(&state, peer, &headers, &q).await {
Ok(c) => c,
Err(r) => return r,
};
let id = match parse_id(&ch) {
Ok(i) => i,
Err(r) => return r,
};
if !ctx.access.allows_channel(id) {
return unauthorized();
}
let profile = match q.profile() {
Ok(p) => p,
Err(e) => return e.into_response(),
};
let sess = state.hls.get_or_start(&state, id, &profile);
sess.touch();
if let Err(e) = sess.wait_ready(Duration::from_secs(25)).await {
return (
StatusCode::SERVICE_UNAVAILABLE,
[(header::RETRY_AFTER, "3")],
format!("{e:#}"),
)
.into_response();
}
let name = state
.db
.channel(id)
.await
.ok()
.flatten()
.map(|c| c.name)
.unwrap_or_default();
state.clients.touch_hls(
NewClient {
kind: "hls",
channel_id: id,
channel_name: &name,
ip: &ctx.ip,
user_agent: &ctx.ua,
who: &ctx.access.who(),
profile: &profile,
},
0,
);
let body = sess.playlist(&hls_suffix(&ctx, &q, &profile));
(
[
(header::CONTENT_TYPE, "application/vnd.apple.mpegurl"),
(header::CACHE_CONTROL, "no-cache, no-store"),
(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"),
],
body,
)
.into_response()
}
pub async fn hls_segment(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path((ch, seg)): Path<(String, String)>,
Query(q): Query<StreamQuery>,
) -> Response {
let ctx = match access(&state, peer, &headers, &q).await {
Ok(c) => c,
Err(r) => return r,
};
let id = match parse_id(&ch) {
Ok(i) => i,
Err(r) => return r,
};
if !ctx.access.allows_channel(id) {
return unauthorized();
}
let Ok(seq) = strip_ext(&seg).parse::<u64>() else {
return (StatusCode::NOT_FOUND, "not found").into_response();
};
let profile = match q.profile() {
Ok(p) => p,
Err(e) => return e.into_response(),
};
let Some(sess) = state.hls.get(id, &profile) else {
return (
StatusCode::NOT_FOUND,
"session expired – reload the playlist",
)
.into_response();
};
sess.touch();
let Some(data) = sess.wait_segment(seq, Duration::from_secs(12)).await else {
return (StatusCode::NOT_FOUND, "segment unavailable").into_response();
};
let name = state
.db
.channel(id)
.await
.ok()
.flatten()
.map(|c| c.name)
.unwrap_or_default();
state.clients.touch_hls(
NewClient {
kind: "hls",
channel_id: id,
channel_name: &name,
ip: &ctx.ip,
user_agent: &ctx.ua,
who: &ctx.access.who(),
profile: &profile,
},
data.len() as u64,
);
(
[
(header::CONTENT_TYPE, "video/mp2t"),
(header::CACHE_CONTROL, "max-age=60"),
(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*"),
],
data,
)
.into_response()
}
// ------------------------------------------------------------ MPEG-TS
pub async fn ts_stream(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path(ch): Path<String>,
Query(q): Query<StreamQuery>,
) -> Response {
let id = match parse_id(&ch) {
Ok(i) => i,
Err(r) => return r,
};
ts_stream_id(&state, peer, &headers, id, &q).await
}
/// Continuous MPEG-TS of the given channel id (shared by native and tvheadend paths).
pub(crate) async fn ts_stream_id(
state: &State,
peer: SocketAddr,
headers: &HeaderMap,
id: i64,
q: &StreamQuery,
) -> Response {
let state = state.clone();
let ctx = match access(&state, peer, headers, q).await {
Ok(c) => c,
Err(r) => return r,
};
if !ctx.access.allows_channel(id) {
return unauthorized();
}
let profile = match q.profile() {
Ok(p) => p,
Err(e) => return e.into_response(),
};
let stream = match pipeline::open_service(&state, id, &profile, Priority::Normal).await {
Ok(s) => s,
Err(e) => return (StatusCode::SERVICE_UNAVAILABLE, format!("{e:#}")).into_response(),
};
let guard = state.clients.register(NewClient {
kind: "ts",
channel_id: id,
channel_name: &stream.source.channel.name,
ip: &ctx.ip,
user_agent: &ctx.ua,
who: &ctx.access.who(),
profile: &profile,
});
tracing::info!(
"TS: {} -> {} ({})",
stream.source.channel.name,
ctx.ip,
ctx.access.who()
);
let name = stream.source.channel.name.clone();
let body = futures_util::stream::unfold((stream, guard), |(mut s, g)| async move {
let b = s.rx.recv().await?;
g.add_bytes(b.len() as u64);
Some((Ok::<_, std::io::Error>(b), (s, g)))
});
let mut res = Response::new(Body::from_stream(body.boxed()));
let h = res.headers_mut();
h.insert(header::CONTENT_TYPE, HeaderValue::from_static("video/mp2t"));
h.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("no-cache, no-store"),
);
if let Ok(v) = HeaderValue::from_str(&format!(
"inline; filename=\"{}.ts\"",
crate::recorder::sanitize(&name)
)) {
h.insert(header::CONTENT_DISPOSITION, v);
}
res
}
// ------------------------------------------------------------ ikony
pub async fn icon(AxState(state): AxState<State>, Path(id): Path<String>) -> Response {
let id = match parse_id(&id) {
Ok(i) => i,
Err(r) => return r,
};
let Ok(Some(c)) = state.db.channel(id).await else {
return (StatusCode::NOT_FOUND, "").into_response();
};
if c.icon == "local" {
match tokio::fs::read(crate::icons::icon_path(&state, id)).await {
Ok(data) => {
let ct = crate::icons::sniff_image(&data).unwrap_or("application/octet-stream");
(
[
(header::CONTENT_TYPE, ct),
(header::CACHE_CONTROL, "public, max-age=3600"),
],
data,
)
.into_response()
}
Err(_) => (StatusCode::NOT_FOUND, "").into_response(),
}
} else if c.icon.starts_with("http") {
Redirect::temporary(&c.icon).into_response()
} else {
(StatusCode::NOT_FOUND, "").into_response()
}
}
// ------------------------------------------------------------ public player
pub async fn watch_page(AxState(state): AxState<State>, Path(token): Path<String>) -> Response {
let Ok(Some(c)) = state.db.channel_by_share(&token).await else {
return (
StatusCode::NOT_FOUND,
Html(super::assets::message_page(
"Link inactive",
"This stream link has expired or was disabled.",
)),
)
.into_response();
};
let codec = match c.service_id {
Some(sid) => state.db.service(sid).await.ok().flatten().map(|s| {
let st = s.streams();
(
st.iter()
.find(|x| x.kind.is_video())
.map(|x| x.kind.label().to_string())
.unwrap_or_default(),
st.iter()
.filter(|x| x.kind.is_audio())
.map(|x| x.kind.label().to_string())
.collect::<Vec<_>>()
.join("|"),
)
}),
None => None,
}
.unwrap_or_default();
Html(super::assets::watch_page(
c.id,
&c.name,
&token,
&codec.0,
&codec.1,
&state.settings().server_name,
state.has_ffmpeg(),
))
.into_response()
}
// ------------------------------------------------------------ recordings
async fn recording_access(
state: &State,
peer: SocketAddr,
headers: &HeaderMap,
q: &StreamQuery,
) -> Result<(), Response> {
let ctx = access(state, peer, headers, q).await?;
if matches!(ctx.access, StreamAccess::Share(_)) {
return Err(unauthorized());
}
Ok(())
}
pub async fn recording_playlist(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path(id): Path<i64>,
Query(q): Query<StreamQuery>,
) -> Response {
if let Err(r) = recording_access(&state, peer, &headers, &q).await {
return r;
}
let Ok(Some(rec)) = state.db.recording(id).await else {
return (StatusCode::NOT_FOUND, "").into_response();
};
let url = match &q.token {
Some(t) => format!("file?token={t}"),
None => "file".to_string(),
};
match crate::recorder::vod_playlist(&rec, &url).await {
Ok(p) => (
[
(header::CONTENT_TYPE, "application/vnd.apple.mpegurl"),
(header::CACHE_CONTROL, "no-cache"),
],
p,
)
.into_response(),
Err(e) => (StatusCode::NOT_FOUND, format!("{e:#}")).into_response(),
}
}
/// Recording file with Range header support (HLS byte-range, download, VLC).
pub async fn recording_file(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path(id): Path<i64>,
Query(q): Query<StreamQuery>,
) -> Response {
recording_file_inner(&state, peer, &headers, id, &q).await
}
/// Recording file for the tvheadend `/dvrfile/<uuid>` path (raw query string).
pub async fn recording_file_by_id(
state: &State,
peer: SocketAddr,
headers: &HeaderMap,
id: i64,
raw_query: Option<String>,
) -> Response {
let q: StreamQuery = serde_urlencoded_query(raw_query.as_deref().unwrap_or(""));
recording_file_inner(state, peer, headers, id, &q).await
}
fn serde_urlencoded_query(q: &str) -> StreamQuery {
let m: std::collections::HashMap<String, String> = url::form_urlencoded::parse(q.as_bytes())
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
serde_json::from_value(serde_json::json!(m)).unwrap_or_default()
}
async fn recording_file_inner(
state: &State,
peer: SocketAddr,
headers: &HeaderMap,
id: i64,
q: &StreamQuery,
) -> Response {
let state = state.clone();
let headers = headers.clone();
if let Err(r) = recording_access(&state, peer, &headers, q).await {
return r;
}
let Ok(Some(rec)) = state.db.recording(id).await else {
return (StatusCode::NOT_FOUND, "").into_response();
};
let Ok(mut f) = tokio::fs::File::open(&rec.file).await else {
return (StatusCode::NOT_FOUND, "file missing").into_response();
};
let Ok(meta) = f.metadata().await else {
return (StatusCode::NOT_FOUND, "").into_response();
};
let size = meta.len();
let range = headers
.get(header::RANGE)
.and_then(|v| v.to_str().ok())
.and_then(|r| parse_range(r, size));
let fname = std::path::Path::new(&rec.file)
.file_name()
.map(|f| f.to_string_lossy().to_string())
.unwrap_or_default();
let disp = HeaderValue::from_str(&format!("inline; filename=\"{}\"", fname.replace('"', "")))
.unwrap_or(HeaderValue::from_static("inline"));
match range {
Some((start, end)) => {
if f.seek(std::io::SeekFrom::Start(start)).await.is_err() {
return (StatusCode::RANGE_NOT_SATISFIABLE, "").into_response();
}
let len = end - start + 1;
let body = Body::from_stream(ReaderStream::new(f.take(len)));
let mut res = Response::new(body);
*res.status_mut() = StatusCode::PARTIAL_CONTENT;
let h = res.headers_mut();
h.insert(header::CONTENT_TYPE, HeaderValue::from_static("video/mp2t"));
h.insert(header::CONTENT_LENGTH, HeaderValue::from(len));
h.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
h.insert(
header::CONTENT_RANGE,
HeaderValue::from_str(&format!("bytes {start}-{end}/{size}")).unwrap(),
);
h.insert(header::CONTENT_DISPOSITION, disp);
res
}
None if headers.contains_key(header::RANGE) => (
[(header::CONTENT_RANGE, format!("bytes */{size}"))],
StatusCode::RANGE_NOT_SATISFIABLE,
)
.into_response(),
None => {
let mut res = Response::new(Body::from_stream(ReaderStream::new(f)));
let h = res.headers_mut();
h.insert(header::CONTENT_TYPE, HeaderValue::from_static("video/mp2t"));
h.insert(header::CONTENT_LENGTH, HeaderValue::from(size));
h.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
h.insert(header::CONTENT_DISPOSITION, disp);
res
}
}
}
/// Pojedynczy zakres "bytes=a-b" / "bytes=a-" / "bytes=-n".
pub fn parse_range(h: &str, size: u64) -> Option<(u64, u64)> {
let r = h.trim().strip_prefix("bytes=")?;
if r.contains(',') || size == 0 {
return None;
}
let (a, b) = r.split_once('-')?;
let (start, end) = if a.is_empty() {
let n: u64 = b.parse().ok()?;
(size.saturating_sub(n), size - 1)
} else {
let s: u64 = a.parse().ok()?;
let e: u64 = if b.is_empty() {
size - 1
} else {
b.parse::<u64>().ok()?.min(size - 1)
};
(s, e)
};
(start <= end && start < size).then_some((start, end))
}
// ------------------------------------------------------------ Prometheus
/// Prometheus metrics (access like streams: local network, token or session).
pub async fn metrics(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Query(q): Query<StreamQuery>,
) -> Response {
if let Err(r) = recording_access(&state, peer, &headers, &q).await {
return r;
}
use std::fmt::Write;
let mut o = String::new();
let lbl = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\"");
let _ = writeln!(o, "# HELP simply_dvb_info Wersja serwera\n# TYPE simply_dvb_info gauge\nsimply_dvb_info{{version=\"{}\"}} 1", env!("CARGO_PKG_VERSION"));
let _ = writeln!(
o,
"# TYPE simply_dvb_uptime_seconds counter\nsimply_dvb_uptime_seconds {}",
state.started.elapsed().as_secs()
);
let tuners = state.tuners.status();
let gauges = [
("simply_dvb_tuner_active", "Tuner dostrojony (1/0)"),
("simply_dvb_tuner_locked", "Synchronizacja (lock)"),
("simply_dvb_tuner_signal_percent", "Signal strength %"),
("simply_dvb_tuner_signal_dbm", "Signal strength dBm"),
("simply_dvb_tuner_snr_db", "SNR dB"),
("simply_dvb_tuner_uncorrected_blocks", "Uncorrected blocks"),
("simply_dvb_tuner_bitrate_bps", "Multiplex bitrate b/s"),
("simply_dvb_tuner_subscribers", "Klienci tunera"),
];
for (name, help) in gauges {
let _ = writeln!(o, "# HELP {name} {help}\n# TYPE {name} gauge");
for t in &tuners {
let a = t.active.as_ref();
let sig = a.map(|a| &a.signal);
let v: Option<f64> = match name {
"simply_dvb_tuner_active" => Some(a.is_some() as u8 as f64),
"simply_dvb_tuner_locked" => Some(sig.is_some_and(|s| s.locked) as u8 as f64),
"simply_dvb_tuner_signal_percent" => sig.and_then(|s| s.strength_pct),
"simply_dvb_tuner_signal_dbm" => sig.and_then(|s| s.strength_dbm),
"simply_dvb_tuner_snr_db" => sig.and_then(|s| s.snr_db),
"simply_dvb_tuner_uncorrected_blocks" => {
sig.and_then(|s| s.uncorrected).map(|x| x as f64)
}
"simply_dvb_tuner_bitrate_bps" => Some(a.map_or(0, |a| a.bitrate_bps) as f64),
_ => Some(a.map_or(0, |a| a.subscribers) as f64),
};
if let Some(v) = v {
let mux = a.map(|a| a.tuning.clone()).unwrap_or_default();
let _ = writeln!(
o,
"{name}{{adapter=\"{}\",name=\"{}\",mux=\"{}\"}} {v}",
lbl(&t.id),
lbl(&t.name),
lbl(&mux)
);
}
}
}
let clients = state.clients.list();
let _ = writeln!(o, "# TYPE simply_dvb_clients gauge");
for kind in ["ts", "hls", "recording"] {
let n = clients.iter().filter(|c| c.kind == kind).count();
let _ = writeln!(o, "simply_dvb_clients{{kind=\"{kind}\"}} {n}");
}
let sent: u64 = clients
.iter()
.map(|c| c.bytes.load(std::sync::atomic::Ordering::Relaxed))
.sum();
let _ = writeln!(
o,
"# TYPE simply_dvb_clients_bytes gauge\nsimply_dvb_clients_bytes {sent}"
);
if let Ok(chs) = state.db.channels().await {
let _ = writeln!(o, "# TYPE simply_dvb_channels gauge\nsimply_dvb_channels{{enabled=\"true\"}} {}\nsimply_dvb_channels{{enabled=\"false\"}} {}", chs.iter().filter(|c| c.enabled).count(), chs.iter().filter(|c| !c.enabled).count());
}
if let Ok(n) = state.db.epg_count().await {
let _ = writeln!(
o,
"# TYPE simply_dvb_epg_events gauge\nsimply_dvb_epg_events {n}"
);
}
if let Ok(recs) = state.db.recordings().await {
let _ = writeln!(o, "# TYPE simply_dvb_recordings gauge");
for st in ["scheduled", "recording", "completed", "failed", "cancelled"] {
let _ = writeln!(
o,
"simply_dvb_recordings{{status=\"{st}\"}} {}",
recs.iter().filter(|r| r.status == st).count()
);
}
let _ = writeln!(
o,
"# TYPE simply_dvb_recordings_bytes gauge\nsimply_dvb_recordings_bytes {}",
recs.iter().map(|r| r.size).sum::<i64>()
);
}
if let Some(free) = crate::recorder::free_space(&state.recordings_dir()) {
let _ = writeln!(o, "# TYPE simply_dvb_recordings_free_bytes gauge\nsimply_dvb_recordings_free_bytes {free}");
}
let sessions = state
.hls
.list()
.iter()
.filter(|s| !s.done.load(std::sync::atomic::Ordering::Relaxed))
.count();
let _ = writeln!(
o,
"# TYPE simply_dvb_hls_sessions gauge\nsimply_dvb_hls_sessions {sessions}"
);
(
[(
header::CONTENT_TYPE,
"text/plain; version=0.0.4; charset=utf-8",
)],
o,
)
.into_response()
}
#[cfg(test)]
mod tests {
use super::parse_range;
#[test]
fn ranges() {
assert_eq!(parse_range("bytes=0-99", 1000), Some((0, 99)));
assert_eq!(parse_range("bytes=900-", 1000), Some((900, 999)));
assert_eq!(parse_range("bytes=-100", 1000), Some((900, 999)));
assert_eq!(parse_range("bytes=500-5000", 1000), Some((500, 999)));
assert_eq!(parse_range("bytes=1000-", 1000), None);
assert_eq!(parse_range("bytes=0-1,5-6", 1000), None);
}
}
+252
View File
@@ -0,0 +1,252 @@
//! tvheadend compatibility: the same HTTP paths, identifiers (UUID), authentication
//! parameters (`auth=`, `ticket=`, HTTP Basic) and profile names, so apps configured
//! for tvheadend (port 9981) work unchanged.
//!
//! | tvheadend | simply-dvb |
//! |---------------------------------------------|-----------------------------------|
//! | `/playlist`, `/playlist/channels(.m3u)` | playlist of all channels |
//! | `/playlist/auth/channels`, `/playlist/ticket/channels` | same as above |
//! | `/playlist/channelid/<id>` (+ number/name/uuid) | single-channel playlist (VLC) |
//! | `/stream/channelid/<id>` (+ channelnumber/channelname/channel/<uuid>) | MPEG-TS |
//! | `/xmltv`, `/xmltv/channels` | XMLTV |
//! | `/imagecache/<id>` | channel icon |
use super::public::{self, StreamQuery};
use crate::app::State;
use crate::auth::{self, StreamAccess};
use crate::db::Channel;
use axum::extract::{ConnectInfo, Path, Query, State as AxState};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use std::net::SocketAddr;
fn not_found() -> Response {
(StatusCode::NOT_FOUND, "Channel not found").into_response()
}
fn decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'%' && i + 2 < b.len() {
if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
out.push(v);
i += 3;
continue;
}
}
out.push(if b[i] == b'+' { b' ' } else { b[i] });
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// Finds a channel by tvheadend key kind.
pub async fn find_channel(state: &State, kind: &str, key: &str) -> Option<Channel> {
let key = decode(key);
let key = key
.trim_end_matches(".m3u")
.trim_end_matches(".m3u8")
.trim_end_matches(".ts");
let channels = state.db.channels().await.ok()?;
match kind {
"channelid" => key
.parse::<i64>()
.ok()
.and_then(|id| channels.into_iter().find(|c| c.id == id)),
"channelnumber" => {
let n = key.split('.').next()?.parse::<i64>().ok()?;
channels
.into_iter()
.filter(|c| c.enabled)
.find(|c| c.number == n)
}
"channel" => channels
.into_iter()
.find(|c| c.uuid().eq_ignore_ascii_case(key)),
"channelname" => {
let k = crate::epg::norm_name(key);
channels
.into_iter()
.filter(|c| c.enabled)
.find(|c| c.name.eq_ignore_ascii_case(key) || crate::epg::norm_name(&c.name) == k)
}
_ => None,
}
}
fn line_attr(s: &str) -> String {
s.replace('"', "'").replace(['\n', '\r'], " ")
}
/// Playlist in tvheadend format (links `/stream/channelid/<id>`).
pub fn tvh_m3u(channels: &[Channel], base: &str, auth_q: &str, profile: &str) -> String {
// Byte-for-byte the attribute set and order of tvheadend 4.2/4.3
// (`tvg-logo`, `tvg-id`, `tvg-chno`, then the name), so apps that parse the
// playlist with a fixed layout see no difference. Extra attributes live in /playlist.m3u.
let mut out = String::from("#EXTM3U\n");
for c in channels.iter().filter(|c| c.enabled) {
let logo = if c.icon.is_empty() {
String::new()
} else {
format!(
" tvg-logo=\"{base}/imagecache/{}{}\"",
c.id,
if auth_q.is_empty() {
String::new()
} else {
format!("?{auth_q}")
}
)
};
out.push_str(&format!(
"#EXTINF:-1{logo} tvg-id=\"{}\" tvg-chno=\"{}\",{}\n",
line_attr(&c.xmltv_id()),
c.number,
c.name.replace(['\n', '\r'], " ")
));
let mut q = vec![];
if !auth_q.is_empty() {
q.push(auth_q.to_string());
}
q.push(format!("profile={profile}"));
out.push_str(&format!(
"{base}/stream/channelid/{}?{}\n",
c.id,
q.join("&")
));
}
out
}
/// tvheadend-style authentication parameter (`auth=<token>`).
fn auth_param(a: &StreamAccess) -> String {
match a {
StreamAccess::Token(t) => format!("auth={}", t.token),
_ => String::new(),
}
}
fn m3u_response(body: String, filename: &str) -> Response {
(
[
(
header::CONTENT_TYPE,
"audio/x-mpegurl; charset=utf-8".to_string(),
),
(
header::CONTENT_DISPOSITION,
format!("inline; filename=\"{}\"", filename.replace('"', "")),
),
(header::CACHE_CONTROL, "no-cache".to_string()),
],
body,
)
.into_response()
}
/// `/playlist`, `/playlist/channels`, `/playlist/auth/channels` …
pub async fn playlist_all(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Query(q): Query<StreamQuery>,
) -> Response {
let ctx = match public::access(&state, peer, &headers, &q).await {
Ok(c) => c,
Err(r) => return r,
};
if matches!(ctx.access, StreamAccess::Share(_)) {
return public::unauthorized();
}
let profile = q.profile().unwrap_or_else(|_| "pass".into());
let base = auth::base_url(&state, peer, &headers);
let channels = state.db.channels().await.unwrap_or_default();
m3u_response(
tvh_m3u(&channels, &base, &auth_param(&ctx.access), &profile),
"channels.m3u",
)
}
pub async fn playlist_all_sub(
st: AxState<State>,
ci: ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path(_rest): Path<String>,
q: Query<StreamQuery>,
) -> Response {
playlist_all(st, ci, headers, q).await
}
pub async fn playlist_all_sub2(
st: AxState<State>,
ci: ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path((_a, _b)): Path<(String, String)>,
q: Query<StreamQuery>,
) -> Response {
playlist_all(st, ci, headers, q).await
}
/// `/playlist/channelid/<id>` etc. – single-channel playlist (e.g. to open in VLC).
pub async fn playlist_one(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path((kind, key)): Path<(String, String)>,
Query(q): Query<StreamQuery>,
) -> Response {
if !matches!(
kind.as_str(),
"channelid" | "channelnumber" | "channel" | "channelname"
) {
// e.g. /playlist/auth/channels
return playlist_all(AxState(state), ConnectInfo(peer), headers, Query(q)).await;
}
let ctx = match public::access(&state, peer, &headers, &q).await {
Ok(c) => c,
Err(r) => return r,
};
let Some(c) = find_channel(&state, &kind, &key).await else {
return not_found();
};
if !ctx.access.allows_channel(c.id) {
return public::unauthorized();
}
let profile = q.profile().unwrap_or_else(|_| "pass".into());
let base = auth::base_url(&state, peer, &headers);
let body = tvh_m3u(
std::slice::from_ref(&c),
&base,
&auth_param(&ctx.access),
&profile,
);
m3u_response(body, &format!("{}.m3u", crate::recorder::sanitize(&c.name)))
}
/// `/stream/channelid/<id>`, `/stream/channelnumber/<n>`, `/stream/channelname/<name>`, `/stream/channel/<uuid>`.
pub async fn stream(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path((kind, key)): Path<(String, String)>,
Query(q): Query<StreamQuery>,
) -> Response {
let Some(c) = find_channel(&state, &kind, &key).await else {
return not_found();
};
public::ts_stream_id(&state, peer, &headers, c.id, &q).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn url_decode() {
assert_eq!(decode("TVP%201%20HD"), "TVP 1 HD");
assert_eq!(decode("Polsat+News"), "Polsat News");
assert_eq!(decode("%C5%9Al%C4%85sk"), "Śląsk");
}
}
+867
View File
@@ -0,0 +1,867 @@
//! tvheadend JSON API (the subset used by clients such as PVR Live, Sparkle TV and other
//! Android TV "Live Channels" sources): server info, channels, tags, EPG, recordings
//! (list, schedule, cancel, delete) and recording files (`/dvrfile/<uuid>`).
//!
//! Served on the stream port (9981), where tvheadend has it; requests accept parameters
//! both in the query string and as a form body (tvheadend clients use either). Access
//! follows the stream ACL (open networks, token, panel user via HTTP Basic).
use super::public::{self, StreamQuery};
use crate::app::State;
use crate::db::{now, Channel, EpgEvent, Recording};
use axum::body::Bytes;
use axum::extract::{ConnectInfo, Path, RawQuery, State as AxState};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{any, get};
use axum::{Json, Router};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::net::SocketAddr;
/// API version reported in `/api/serverinfo` (tvheadend 4.2.x).
const API_VERSION: i64 = 19;
pub fn routes() -> Router<State> {
Router::new()
.route("/api/serverinfo", any(serverinfo))
.route("/api/config/capabilities", any(capabilities))
.route("/api/channel/grid", any(channel_grid))
.route("/api/channel/list", any(channel_list))
.route("/api/channeltag/grid", any(tag_grid))
.route("/api/channeltag/list", any(tag_list))
.route("/api/epg/events/grid", any(epg_grid))
.route("/api/epg/events/load", any(epg_load))
.route("/api/dvr/entry/grid", any(dvr_all))
.route("/api/dvr/entry/grid_upcoming", any(dvr_upcoming))
.route("/api/dvr/entry/grid_finished", any(dvr_finished))
.route("/api/dvr/entry/grid_failed", any(dvr_failed))
.route("/api/dvr/entry/grid_removed", any(empty_grid))
.route("/api/dvr/entry/create_by_event", any(dvr_create_by_event))
.route("/api/dvr/entry/create", any(dvr_create))
.route("/api/dvr/entry/cancel", any(dvr_cancel))
.route("/api/dvr/entry/stop", any(dvr_cancel))
.route("/api/dvr/entry/remove", any(dvr_remove))
.route("/api/dvr/autorec/grid", any(empty_grid))
.route("/api/dvr/timerec/grid", any(empty_grid))
.route("/api/dvr/config/grid", any(dvr_config))
.route("/api/idnode/delete", any(dvr_remove))
.route("/api/profile/list", any(profile_list))
.route("/api/status/connections", any(empty_grid))
.route("/api/status/subscriptions", any(empty_grid))
.route("/api/status/inputs", any(status_inputs))
.route("/api/language/list", any(empty_grid))
.route("/comet/poll", any(comet_poll))
.route("/dvrfile/{uuid}", get(dvr_file))
}
/// Request parameters from the query string and a form-encoded body.
struct Params(HashMap<String, String>);
impl Params {
fn new(query: Option<String>, body: &Bytes) -> Self {
let mut m: HashMap<String, String> = HashMap::new();
for src in [
query.unwrap_or_default(),
String::from_utf8_lossy(body).to_string(),
] {
for (k, v) in url::form_urlencoded::parse(src.as_bytes()) {
m.insert(k.to_string(), v.to_string());
}
}
Params(m)
}
fn get(&self, k: &str) -> Option<&str> {
self.0.get(k).map(|s| s.as_str()).filter(|s| !s.is_empty())
}
fn i64(&self, k: &str) -> Option<i64> {
self.get(k).and_then(|v| v.parse().ok())
}
fn stream_query(&self) -> StreamQuery {
serde_json::from_value(json!(self.0)).unwrap_or_default()
}
/// `uuid` may be a single value or a JSON list (`["a","b"]`).
fn uuids(&self) -> Vec<String> {
let Some(v) = self.get("uuid") else {
return Vec::new();
};
match serde_json::from_str::<Value>(v) {
Ok(Value::Array(a)) => a
.iter()
.filter_map(|x| x.as_str().map(String::from))
.collect(),
Ok(Value::String(s)) => vec![s],
_ => vec![v.to_string()],
}
}
}
/// Shared prologue: parameters + stream ACL.
macro_rules! guard {
($state:expr, $peer:expr, $headers:expr, $q:expr, $body:expr) => {{
let p = Params::new($q, &$body);
if let Err(r) = public::access(&$state, $peer, &$headers, &p.stream_query()).await {
return r;
}
p
}};
}
fn base_url(state: &State, peer: SocketAddr, headers: &HeaderMap) -> String {
crate::auth::base_url(state, peer, headers)
}
fn rec_uuid(id: i64) -> String {
format!("{id:032x}")
}
fn rec_id(uuid: &str) -> Option<i64> {
i64::from_str_radix(uuid.trim_start_matches('0'), 16)
.ok()
.or_else(|| (uuid.chars().all(|c| c == '0')).then_some(0))
}
fn tag_uuid(name: &str) -> String {
use sha2::Digest;
let d = sha2::Sha256::digest(format!("simply-dvb/tag/{name}").as_bytes());
d.iter().take(16).map(|b| format!("{b:02x}")).collect()
}
fn grid(entries: Vec<Value>, p: &Params) -> Json<Value> {
let total = entries.len();
let start = p.i64("start").unwrap_or(0).max(0) as usize;
let limit = p.i64("limit").filter(|l| *l > 0).map(|l| l as usize);
let page: Vec<Value> = entries
.into_iter()
.skip(start)
.take(limit.unwrap_or(usize::MAX))
.collect();
Json(json!({ "entries": page, "total": total, "totalCount": total }))
}
async fn serverinfo(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let _p = guard!(state, peer, headers, q, body);
Json(json!({
"sw_version": format!("4.2.8-simply-dvb-{}", env!("CARGO_PKG_VERSION")),
"api_version": API_VERSION,
"name": "Tvheadend",
"capabilities": CAPABILITIES,
}))
.into_response()
}
const CAPABILITIES: [&str; 3] = ["tvadapters", "caclient", "imagecache"];
/// `/api/config/capabilities` – tvheadend returns a plain JSON array of strings.
async fn capabilities(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let _p = guard!(state, peer, headers, q, body);
Json(json!(CAPABILITIES)).into_response()
}
async fn enabled_channels(state: &State) -> Vec<Channel> {
state
.db
.channels()
.await
.unwrap_or_default()
.into_iter()
.filter(|c| c.enabled)
.collect()
}
fn channel_json(c: &Channel, base: &str) -> Value {
let icon = if c.icon.is_empty() {
String::new()
} else {
format!("imagecache/{}", c.id)
};
json!({
"uuid": c.uuid(),
"enabled": true,
"autoname": false,
"name": c.name,
"number": c.number,
"icon": icon,
"icon_public_url": if icon.is_empty() { String::new() } else { format!("{base}/{icon}") },
"epgauto": true,
"epglimit": 0,
"epggrab": [],
"dvr_pre_time": 0,
"dvr_pst_time": 0,
"epg_running": -1,
"services": c.service_id.map(|s| vec![format!("{s:032x}")]).unwrap_or_default(),
"tags": if c.grp.is_empty() { vec![] } else { vec![tag_uuid(&c.grp)] },
"bouquet": "",
})
}
async fn channel_grid(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
let base = base_url(&state, peer, &headers);
let list = enabled_channels(&state).await;
grid(list.iter().map(|c| channel_json(c, &base)).collect(), &p).into_response()
}
async fn channel_list(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
let list = enabled_channels(&state).await;
grid(
list.iter()
.map(|c| json!({"key": c.uuid(), "val": c.name}))
.collect(),
&p,
)
.into_response()
}
fn groups(list: &[Channel]) -> Vec<String> {
let mut g: Vec<String> = Vec::new();
for c in list {
if !c.grp.is_empty() && !g.contains(&c.grp) {
g.push(c.grp.clone());
}
}
g
}
async fn tag_grid(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
let list = enabled_channels(&state).await;
grid(
groups(&list)
.iter()
.enumerate()
.map(|(i, g)| {
json!({
"uuid": tag_uuid(g), "enabled": true, "index": i, "name": g,
"internal": false, "private": false, "icon": "", "titled_icon": false, "comment": ""
})
})
.collect(),
&p,
)
.into_response()
}
async fn tag_list(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
let list = enabled_channels(&state).await;
grid(
groups(&list)
.iter()
.map(|g| json!({"key": tag_uuid(g), "val": g}))
.collect(),
&p,
)
.into_response()
}
fn event_json(
e: &EpgEvent,
c: &Channel,
next: Option<i64>,
dvr: Option<&Recording>,
base: &str,
) -> Value {
let mut v = json!({
"eventId": e.id,
"episodeId": 0,
"channelName": c.name,
"channelUuid": c.uuid(),
"channelNumber": c.number.to_string(),
"channelIcon": if c.icon.is_empty() { String::new() } else { format!("{base}/imagecache/{}", c.id) },
"start": e.start,
"stop": e.stop,
"title": e.title,
"subtitle": "",
"summary": e.summary,
"description": if e.description.is_empty() { &e.summary } else { &e.description },
"genre": crate::htsp::content_type_of(&e.genre).map(|g| vec![g]).unwrap_or_default(),
});
if let Some(n) = next {
v["nextEventId"] = json!(n);
}
if let Some(r) = e.rating.filter(|r| *r > 0) {
v["ageRating"] = json!(r);
}
if let Some(r) = dvr {
v["dvrUuid"] = json!(rec_uuid(r.id));
v["dvrState"] = json!(if r.status == "recording" {
"recording"
} else {
"scheduled"
});
}
v
}
async fn epg_grid(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
let base = base_url(&state, peer, &headers);
let channels = enabled_channels(&state).await;
let by_id: HashMap<i64, &Channel> = channels.iter().map(|c| (c.id, c)).collect();
// "channel" may be a uuid, a name or a number
let filter = p.get("channel").and_then(|k| {
channels
.iter()
.find(|c| c.uuid() == k || c.name == k || c.number.to_string() == k)
.map(|c| c.id)
});
if p.get("channel").is_some() && filter.is_none() {
return grid(Vec::new(), &p).into_response();
}
let t = now();
let to = p.i64("stop").or(p.i64("end")).unwrap_or(t + 14 * 86400);
let from = if p.get("mode") == Some("now") {
t
} else {
p.i64("start_time").unwrap_or(t)
};
let mut events = state
.db
.epg_range(filter, from, to)
.await
.unwrap_or_default();
if let Some(title) = p.get("title").map(str::to_lowercase) {
events.retain(|e| e.title.to_lowercase().contains(&title));
}
if p.get("mode") == Some("now") {
events.retain(|e| e.start <= t && e.stop > t);
}
let recs = state.db.recordings().await.unwrap_or_default();
let dvr: HashMap<(i64, i64), &Recording> = recs
.iter()
.filter(|r| r.status == "scheduled" || r.status == "recording")
.filter_map(|r| r.channel_id.map(|c| ((c, r.start), r)))
.collect();
let mut out = Vec::with_capacity(events.len());
for (i, e) in events.iter().enumerate() {
let Some(c) = by_id.get(&e.channel_id) else {
continue;
};
let next = events
.get(i + 1)
.filter(|n| n.channel_id == e.channel_id)
.map(|n| n.id);
out.push(event_json(
e,
c,
next,
dvr.get(&(e.channel_id, e.start)).copied(),
&base,
));
}
let total = out.len();
let mut j = grid(out, &p).0;
j["totalCount"] = json!(total);
Json(j).into_response()
}
async fn epg_load(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
let base = base_url(&state, peer, &headers);
let id = p.i64("eventId").unwrap_or(0);
let Ok(Some(e)) = state.db.epg_event(id).await else {
return Json(json!({"entries": []})).into_response();
};
let Ok(Some(c)) = state.db.channel(e.channel_id).await else {
return Json(json!({"entries": []})).into_response();
};
Json(json!({"entries": [event_json(&e, &c, None, None, &base)]})).into_response()
}
// ---------------------------------------------------------------- recordings
fn dvr_json(r: &Recording, channels: &HashMap<i64, Channel>, base: &str) -> Value {
let ch = r.channel_id.and_then(|id| channels.get(&id));
let (status, sched) = match r.status.as_str() {
"scheduled" => ("Scheduled for recording", "scheduled"),
"recording" => ("Running", "recording"),
"completed" => ("Completed OK", "completed"),
"failed" if r.size > 0 => ("Completed with errors", "completedError"),
"failed" => ("Recording failed", "completedError"),
_ => ("Cancelled", "completedRerecord"),
};
let start_real = r.start - r.pre_padding;
let stop_real = r.stop + r.post_padding;
json!({
"uuid": rec_uuid(r.id),
"enabled": true,
"create": r.created_at,
"start": r.start,
"start_extra": r.pre_padding / 60,
"start_real": start_real,
"stop": r.stop,
"stop_extra": r.post_padding / 60,
"stop_real": stop_real,
"duration": r.stop - r.start,
"channel": ch.map(|c| c.uuid()).unwrap_or_default(),
"channel_icon": ch.filter(|c| !c.icon.is_empty()).map(|c| format!("{base}/imagecache/{}", c.id)).unwrap_or_default(),
"channelname": r.channel_name,
"title": {"und": r.title},
"disp_title": r.title,
"disp_subtitle": "",
"disp_description": r.description,
"description": {"und": r.description},
"pri": 2,
"retention": 0,
"removal": 0,
"config_name": "default",
"owner": "simply-dvb",
"creator": "simply-dvb",
"filename": r.file,
"filesize": r.size,
"errorcode": if r.error.is_empty() { 0 } else { 1 },
"errors": if r.error.is_empty() { 0 } else { 1 },
"data_errors": 0,
"status": status,
"sched_status": sched,
"url": if r.file.is_empty() { String::new() } else { format!("dvrfile/{}", rec_uuid(r.id)) },
"autorec": r.autorec_id.map(|a| a.to_string()).unwrap_or_default(),
"comment": r.error,
})
}
async fn dvr_list(
state: &State,
peer: SocketAddr,
headers: &HeaderMap,
p: &Params,
keep: fn(&Recording) -> bool,
) -> Response {
let base = base_url(state, peer, headers);
let channels: HashMap<i64, Channel> = state
.db
.channels()
.await
.unwrap_or_default()
.into_iter()
.map(|c| (c.id, c))
.collect();
let mut recs: Vec<Recording> = state
.db
.recordings()
.await
.unwrap_or_default()
.into_iter()
.filter(keep)
.collect();
recs.sort_by_key(|r| r.start);
grid(
recs.iter().map(|r| dvr_json(r, &channels, &base)).collect(),
p,
)
.into_response()
}
async fn dvr_all(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
dvr_list(&state, peer, &headers, &p, |_| true).await
}
async fn dvr_upcoming(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
dvr_list(&state, peer, &headers, &p, |r| {
r.status == "scheduled" || r.status == "recording"
})
.await
}
async fn dvr_finished(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
dvr_list(&state, peer, &headers, &p, |r| {
r.status == "completed" || (r.status == "failed" && r.size > 0)
})
.await
}
async fn dvr_failed(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
dvr_list(&state, peer, &headers, &p, |r| {
r.status == "cancelled" || (r.status == "failed" && r.size == 0)
})
.await
}
async fn empty_grid(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let _p = guard!(state, peer, headers, q, body);
Json(json!({"entries": [], "total": 0, "totalCount": 0})).into_response()
}
async fn dvr_config(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
let s = state.settings();
grid(
vec![json!({
"uuid": "00000000000000000000000000000001", "enabled": true, "name": "", "profile": "pass",
"pre-extra-time": s.recording_pre_padding_min, "post-extra-time": s.recording_post_padding_min,
"retention-days": s.recordings_keep_days, "comment": "Default profile"
})],
&p,
)
.into_response()
}
async fn profile_list(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
grid(
["pass", "aac", "h264"]
.iter()
.map(|k| json!({"key": k, "val": k}))
.collect(),
&p,
)
.into_response()
}
async fn status_inputs(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
grid(
state
.tuners
.status()
.iter()
.map(|t| {
let a = t.active.as_ref();
json!({
"uuid": t.id, "input": t.name, "stream": a.map(|a| a.tuning.clone()).unwrap_or_default(),
"subs": a.map(|a| a.subscribers).unwrap_or(0),
"weight": 0,
"signal": a.and_then(|a| a.signal.strength_pct).map(|v| (v * 655.35) as i64).unwrap_or(0),
"signal_scale": 2,
"snr": a.and_then(|a| a.signal.snr_db).map(|v| (v * 1000.0) as i64).unwrap_or(0),
"snr_scale": 1,
"unc": a.and_then(|a| a.signal.uncorrected).unwrap_or(0),
"bps": a.map(|a| a.bitrate_bps).unwrap_or(0),
})
})
.collect(),
&p,
)
.into_response()
}
/// tvheadend's push channel; clients poll it – answer "nothing new" after a short wait.
async fn comet_poll(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
let boxid = p.get("boxid").map(String::from).unwrap_or_else(|| {
let mut b = [0u8; 16];
getrandom::fill(&mut b).ok();
b.iter().map(|x| format!("{x:02x}")).collect()
});
if p.get("boxid").is_some() {
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
}
Json(json!({"boxid": boxid, "messages": []})).into_response()
}
#[allow(clippy::too_many_arguments)]
async fn create_recording(
state: &State,
channel: &Channel,
title: &str,
desc: &str,
start: i64,
stop: i64,
pre_min: Option<i64>,
post_min: Option<i64>,
) -> Result<i64, String> {
if stop <= start || stop < now() {
return Err("invalid time".into());
}
let s = state.settings();
let pre = pre_min.unwrap_or(s.recording_pre_padding_min as i64) * 60;
let post = post_min.unwrap_or(s.recording_post_padding_min as i64) * 60;
let id = state
.db
.create_recording(channel, title.trim(), desc, start, stop, pre, post)
.await
.map_err(|e| e.to_string())?;
state.rec_wakeup.notify_one();
tracing::info!(target: "access", "recording scheduled via tvheadend API: {title} ({})", channel.name);
Ok(id)
}
fn bad(msg: &str) -> Response {
(StatusCode::BAD_REQUEST, Json(json!({"error": msg}))).into_response()
}
async fn dvr_create_by_event(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
// event_id may be a number or a JSON list of numbers
let ids: Vec<i64> = match p.get("event_id").map(serde_json::from_str::<Value>) {
Some(Ok(Value::Array(a))) => a.iter().filter_map(|x| x.as_i64()).collect(),
Some(Ok(Value::Number(n))) => n.as_i64().into_iter().collect(),
_ => p.i64("event_id").into_iter().collect(),
};
if ids.is_empty() {
return bad("event_id required");
}
let mut uuids = Vec::new();
for id in ids {
let Ok(Some(e)) = state.db.epg_event(id).await else {
return bad("event does not exist");
};
let Ok(Some(c)) = state.db.channel(e.channel_id).await else {
return bad("channel does not exist");
};
let desc = if e.description.is_empty() {
&e.summary
} else {
&e.description
};
match create_recording(&state, &c, &e.title, desc, e.start, e.stop, None, None).await {
Ok(r) => uuids.push(rec_uuid(r)),
Err(e) => return bad(&e),
}
}
Json(json!({"uuid": uuids})).into_response()
}
async fn dvr_create(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
let Some(conf) = p
.get("conf")
.and_then(|c| serde_json::from_str::<Value>(c).ok())
else {
return bad("conf required");
};
let key = conf["channel"]
.as_str()
.map(String::from)
.unwrap_or_else(|| conf["channel"].to_string());
let channels = state.db.channels().await.unwrap_or_default();
let Some(c) = channels.iter().find(|c| {
c.uuid() == key || c.name == key || c.number.to_string() == key || c.id.to_string() == key
}) else {
return bad("channel does not exist");
};
let title = match &conf["title"] {
Value::Object(m) => m
.values()
.next()
.and_then(|v| v.as_str())
.unwrap_or("Recording")
.to_string(),
Value::String(s) => s.clone(),
_ => "Recording".into(),
};
let desc = match &conf["description"] {
Value::Object(m) => m
.values()
.next()
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string(),
Value::String(s) => s.clone(),
_ => String::new(),
};
let (Some(start), Some(stop)) = (conf["start"].as_i64(), conf["stop"].as_i64()) else {
return bad("start and stop required");
};
match create_recording(
&state,
c,
&title,
&desc,
start,
stop,
conf["start_extra"].as_i64(),
conf["stop_extra"].as_i64(),
)
.await
{
Ok(id) => Json(json!({"uuid": rec_uuid(id)})).into_response(),
Err(e) => bad(&e),
}
}
async fn dvr_cancel(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
for u in p.uuids() {
if let Some(id) = rec_id(&u) {
if !crate::recorder::stop_recording(&state, id) {
let _ = state.db.set_recording_status(id, "cancelled", "").await;
}
}
}
Json(json!({})).into_response()
}
async fn dvr_remove(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
RawQuery(q): RawQuery,
body: Bytes,
) -> Response {
let p = guard!(state, peer, headers, q, body);
for u in p.uuids() {
if let Some(id) = rec_id(&u) {
crate::recorder::stop_recording(&state, id);
if let Ok(Some(r)) = state.db.recording(id).await {
let _ = crate::recorder::remove_recording(&state, &r).await;
tracing::info!(target: "access", "recording deleted via tvheadend API: {}", r.title);
}
}
}
Json(json!({})).into_response()
}
/// Recording file by tvheadend uuid (`/dvrfile/<uuid>`), with Range support.
async fn dvr_file(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Path(uuid): Path<String>,
RawQuery(q): RawQuery,
) -> Response {
let Some(id) = rec_id(uuid.split('.').next().unwrap_or(&uuid)) else {
return (StatusCode::NOT_FOUND, "not found").into_response();
};
public::recording_file_by_id(&state, peer, &headers, id, q).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rec_uuid_roundtrip() {
for id in [0, 1, 255, 123456] {
assert_eq!(rec_id(&rec_uuid(id)), Some(id));
}
assert_eq!(rec_id("zz"), None);
}
#[test]
fn params_merge_query_and_form() {
let p = Params::new(
Some("limit=5&start=1".into()),
&Bytes::from_static(b"uuid=%5B%22a%22%2C%22b%22%5D&auth=x"),
);
assert_eq!(p.i64("limit"), Some(5));
assert_eq!(p.uuids(), vec!["a", "b"]);
assert_eq!(p.get("auth"), Some("x"));
}
}
+891
View File
@@ -0,0 +1,891 @@
//! End-to-end test on the virtual adapter: scanning, channels, M3U, ACL, HLS,
//! MPEG-TS, EPG/XMLTV, sharing and recording.
use axum::body::Body;
use axum::extract::connect_info::MockConnectInfo;
use axum::http::{header, Method, Request, StatusCode};
use axum::Router;
use http_body_util::BodyExt;
use serde_json::{json, Value};
use simply_dvb::app::{AppState, Options, State};
use simply_dvb::db::Db;
use simply_dvb::ts::testgen::GenMux;
use simply_dvb::{auth, epg, recorder, web};
use std::net::SocketAddr;
use std::time::Duration;
use tower::ServiceExt;
struct Env {
state: State,
lan: Router,
wan: Router,
cookie: String,
_dir: tempfile::TempDir,
}
async fn setup() -> Env {
let _ = tracing_subscriber::fmt()
.with_env_filter("simply_dvb=debug")
.with_test_writer()
.try_init();
std::env::set_var("SIMPLY_DVB_VIRTUAL_SPEED", "4");
let dir = tempfile::tempdir().unwrap();
let mux_dir = dir.path().join("muxes");
std::fs::create_dir_all(&mux_dir).unwrap();
let t = chrono::Utc::now().timestamp();
let mut m = GenMux::sample(0x0003, 0x0451, &["TVP1 HD", "Polsat Śląsk", "TVN"], t);
m.other_muxes = vec![(0x0004, 610_000_000)];
std::fs::write(mux_dir.join("538.ts"), m.generate(40)).unwrap();
// second mux – known only from the first one's NIT (network discovery)
let m2 = GenMux::sample(0x0004, 0x0500, &["Radio Test"], t);
std::fs::write(mux_dir.join("610.ts"), m2.generate(4)).unwrap();
let db = Db::open(&dir.path().join("t.db")).await.unwrap();
db.create_user(
"admin",
&auth::hash_password("haslo-admina").unwrap(),
"admin",
)
.await
.unwrap();
db.create_user(
"widz",
&auth::hash_password("haslo-widza").unwrap(),
"viewer",
)
.await
.unwrap();
let opts = Options {
data_dir: dir.path().to_path_buf(),
dev_root: dir.path().join("brak-dvb").to_string_lossy().to_string(),
virtual_dirs: vec![mux_dir.to_string_lossy().to_string()],
stream_port: Some(9981),
htsp_port: None,
};
let (state, epg_rx) = AppState::new(db, opts).await.unwrap();
tokio::spawn(epg::writer_task(state.clone(), epg_rx));
tokio::spawn(recorder::scheduler_task(state.clone()));
let st = state.clone();
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_millis(500)).await;
st.tuners.reap();
st.hls.reap();
}
});
let lan = web::router(state.clone())
.layer(MockConnectInfo(SocketAddr::from(([192, 168, 1, 50], 5000))));
let wan =
web::router(state.clone()).layer(MockConnectInfo(SocketAddr::from(([8, 8, 8, 8], 5000))));
let mut env = Env {
state,
lan,
wan,
cookie: String::new(),
_dir: dir,
};
env.cookie = login(&env.lan, "admin", "haslo-admina").await;
env
}
async fn login(r: &Router, user: &str, pw: &str) -> String {
let res = r
.clone()
.oneshot(
Request::post("/api/login")
.header(header::CONTENT_TYPE, "application/json")
.header("x-requested-with", "simply-dvb")
.body(Body::from(
json!({"username": user, "password": pw}).to_string(),
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let c = res
.headers()
.get(header::SET_COOKIE)
.unwrap()
.to_str()
.unwrap();
c.split(';').next().unwrap().to_string()
}
async fn call(
r: &Router,
method: Method,
uri: &str,
cookie: &str,
body: Option<Value>,
) -> (StatusCode, Vec<u8>) {
let mut b = Request::builder()
.method(method)
.uri(uri)
.header("x-requested-with", "simply-dvb");
if !cookie.is_empty() {
b = b.header(header::COOKIE, cookie);
}
let req = match body {
Some(v) => b
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(v.to_string()))
.unwrap(),
None => b.body(Body::empty()).unwrap(),
};
let res = r.clone().oneshot(req).await.unwrap();
let st = res.status();
let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
(st, bytes)
}
async fn json_of(
r: &Router,
method: Method,
uri: &str,
cookie: &str,
body: Option<Value>,
) -> Value {
let (st, b) = call(r, method, uri, cookie, body).await;
assert!(
st.is_success(),
"{uri}: {st} {}",
String::from_utf8_lossy(&b)
);
serde_json::from_slice(&b).unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn full_flow() {
let env = setup().await;
let c = env.cookie.clone();
eprintln!("== setup ok");
// no session -> 401, missing CSRF header -> 403
let (st, _) = call(&env.lan, Method::GET, "/api/channels", "", None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let res = env
.lan
.clone()
.oneshot(
Request::post("/api/scan")
.header(header::COOKIE, &c)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::FORBIDDEN);
// virtual adapter
let ad = json_of(&env.lan, Method::GET, "/api/adapters", &c, None).await;
assert_eq!(ad.as_array().unwrap().len(), 1);
eprintln!("== adapters ok");
// scanning
json_of(
&env.lan,
Method::POST,
"/api/scan",
&c,
Some(json!({"preset": "custom", "frequencies_mhz": [538, 546]})),
)
.await;
let mut done = false;
for _ in 0..100 {
tokio::time::sleep(Duration::from_millis(200)).await;
let s = json_of(&env.lan, Method::GET, "/api/scan", &c, None).await;
if !s["running"].as_bool().unwrap() {
assert_eq!(s["muxes_found"], 2, "{s}");
assert_eq!(s["services_found"], 4);
assert_eq!(s["channels_created"], 4);
done = true;
break;
}
}
assert!(done, "scan did not finish");
let chans = json_of(&env.lan, Method::GET, "/api/channels", &c, None).await;
let chans = chans.as_array().unwrap();
assert_eq!(chans.len(), 4);
assert_eq!(chans[0]["name"], "TVP1 HD");
assert_eq!(chans[0]["number"], 1);
assert_eq!(chans[1]["name"], "Polsat Śląsk");
assert_eq!(chans[1]["service"]["video"], "HEVC");
let id1 = chans[0]["id"].as_i64().unwrap();
let id2 = chans[1]["id"].as_i64().unwrap();
// reordering
json_of(
&env.lan,
Method::POST,
"/api/channels/order",
&c,
Some(json!({"ids": [id2, id1]})),
)
.await;
let chans = json_of(&env.lan, Method::GET, "/api/channels", &c, None).await;
assert_eq!(chans[0]["id"].as_i64().unwrap(), id2);
// a viewer cannot change the configuration
let vc = login(&env.lan, "widz", "haslo-widza").await;
let (st, _) = call(
&env.lan,
Method::PUT,
&format!("/api/channels/{id1}"),
&vc,
Some(json!({"name": "X"})),
)
.await;
assert_eq!(st, StatusCode::FORBIDDEN);
// M3U: LAN without a token, WAN requires a token
let (st, body) = call(&env.lan, Method::GET, "/playlist.m3u", "", None).await;
assert_eq!(st, StatusCode::OK);
let m3u = String::from_utf8(body).unwrap();
assert!(m3u.starts_with("#EXTM3U"));
assert!(m3u.contains(&format!("/stream/{id1}.ts")));
let (st, _) = call(&env.wan, Method::GET, "/playlist.m3u", "", None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let tok = json_of(
&env.lan,
Method::POST,
"/api/tokens",
&c,
Some(json!({"name": "Sony TV"})),
)
.await;
let token = tok["token"].as_str().unwrap().to_string();
let (st, body) = call(
&env.wan,
Method::GET,
&format!("/playlist.m3u?format=hls&token={token}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::OK);
let m3u = String::from_utf8(body).unwrap();
assert!(
m3u.contains(&format!("/hls/{id1}/index.m3u8?token={token}")),
"{m3u}"
);
// token restricted to a network
let tok2 = json_of(
&env.lan,
Method::POST,
"/api/tokens",
&c,
Some(json!({"name": "Tylko LAN", "allow_cidrs": "192.168.0.0/16"})),
)
.await;
let (st, _) = call(
&env.wan,
Method::GET,
&format!("/playlist.m3u?token={}", tok2["token"].as_str().unwrap()),
"",
None,
)
.await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
// ---- tvheadend compatibility
let (st, body) = call(
&env.wan,
Method::GET,
&format!("/playlist?auth={token}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::OK);
let tvh = String::from_utf8(body).unwrap();
assert!(
tvh.contains(&format!(
"/stream/channelid/{id1}?auth={token}&profile=pass"
)),
"{tvh}"
);
assert!(tvh.contains("tvg-id=\"") && tvh.contains("tvg-chno=\"1\""));
for path in [
"/playlist/channels",
"/playlist/channels.m3u",
"/playlist/auth/channels",
] {
let (st, _) = call(
&env.wan,
Method::GET,
&format!("{path}?ticket={token}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::OK, "{path}");
}
let (st, one) = call(
&env.lan,
Method::GET,
&format!("/playlist/channelid/{id1}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(
String::from_utf8(one).unwrap().matches("#EXTINF").count(),
1
);
// HTTP Basic with a panel login (like tvheadend clients)
let basic = format!("Basic {}", base64_encode("admin:haslo-admina"));
let res = env
.wan
.clone()
.oneshot(
Request::get("/xmltv/channels")
.header(header::AUTHORIZATION, &basic)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = env
.wan
.clone()
.oneshot(
Request::get("/xmltv/channels")
.header(
header::AUTHORIZATION,
format!("Basic {}", base64_encode("admin:zle")),
)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
// stream by channel number
let res = env
.lan
.clone()
.oneshot(
Request::get("/stream/channelnumber/2?profile=webtv-h264-aac-mpegts-unknown")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let mut b = res.into_body();
let f = tokio::time::timeout(Duration::from_secs(10), b.frame())
.await
.unwrap()
.unwrap()
.unwrap();
assert_eq!(f.into_data().unwrap()[0], 0x47);
drop(b);
let (st, _) = call(&env.lan, Method::GET, "/stream/channelid/99999", "", None).await;
assert_eq!(st, StatusCode::NOT_FOUND);
// separate stream port: no panel and no API
let stream_port = web::stream_router(env.state.clone())
.layer(MockConnectInfo(SocketAddr::from(([192, 168, 1, 60], 5000))));
let (st, _) = call(&stream_port, Method::GET, "/playlist", "", None).await;
assert_eq!(st, StatusCode::OK);
let (st, _) = call(&stream_port, Method::GET, "/api/channels", &c, None).await;
assert_eq!(st, StatusCode::NOT_FOUND);
// tvheadend JSON API (PVR Live and other Android TV sources)
let (st, body) = call(&stream_port, Method::GET, "/api/serverinfo", "", None).await;
assert_eq!(st, StatusCode::OK);
let info: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(info["name"], "Tvheadend");
let (_, body) = call(
&stream_port,
Method::GET,
"/api/channel/grid?limit=999",
"",
None,
)
.await;
let grid: serde_json::Value = serde_json::from_slice(&body).unwrap();
let first = &grid["entries"][0];
assert_eq!(grid["total"], 4);
assert!(first["name"].is_string());
let uuid = first["uuid"].as_str().unwrap().to_string();
let (_, body) = call(
&stream_port,
Method::GET,
&format!("/api/epg/events/grid?channel={uuid}&limit=5"),
"",
None,
)
.await;
let epg: serde_json::Value = serde_json::from_slice(&body).unwrap();
// EIT has not been collected yet at this point: only the shape is checked
assert!(epg["entries"].is_array(), "{epg}");
assert!(epg["totalCount"].is_number());
let _ = uuid;
// the WAN side needs a token here too
let wan_stream = web::stream_router(env.state.clone())
.layer(MockConnectInfo(SocketAddr::from(([8, 8, 8, 8], 5000))));
let (st, _) = call(&wan_stream, Method::GET, "/api/channel/grid", "", None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let (st, _) = call(
&wan_stream,
Method::GET,
&format!("/api/channel/grid?auth={token}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::OK);
// HLS
let (st, body) = call(
&env.wan,
Method::GET,
&format!("/hls/{id1}/index.m3u8?token={token}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
let pl = String::from_utf8(body).unwrap();
assert!(pl.contains("#EXT-X-TARGETDURATION"));
let seg_line = pl
.lines()
.find(|l| l.ends_with(&format!("?token={token}")))
.expect("segment in playlist")
.to_string();
let (st, seg) = call(
&env.wan,
Method::GET,
&format!("/hls/{id1}/{seg_line}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::OK);
assert!(seg.len() > 188 * 10 && seg.len() % 188 == 0);
assert_eq!(seg[0], 0x47);
// second channel from the same mux shares the tuner
let (st, _) = call(
&env.lan,
Method::GET,
&format!("/hls/{id2}/index.m3u8"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::OK);
let status = json_of(&env.lan, Method::GET, "/api/status", &c, None).await;
assert_eq!(status["tuners"][0]["active"]["state"], "locked");
assert_eq!(status["hls_sessions"].as_array().unwrap().len(), 2);
// raw MPEG-TS
let res = env
.lan
.clone()
.oneshot(
Request::get(format!("/stream/{id1}.ts"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.headers()[header::CONTENT_TYPE], "video/mp2t");
let mut body = res.into_body();
let frame = tokio::time::timeout(Duration::from_secs(10), body.frame())
.await
.unwrap()
.unwrap()
.unwrap();
let data = frame.into_data().unwrap();
assert_eq!(data[0], 0x47);
drop(body);
// EPG from EIT -> XMLTV
let mut found = false;
for _ in 0..40 {
let (st, body) = call(&env.lan, Method::GET, "/epg.xml", "", None).await;
assert_eq!(st, StatusCode::OK);
let x = String::from_utf8(body).unwrap();
if x.contains("<programme") && x.contains("TVP1 HD - audycja 1") {
assert!(x.contains("<channel id=\""));
found = true;
break;
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
assert!(found, "no EPG in XMLTV");
let chans = json_of(&env.lan, Method::GET, "/api/channels", &c, None).await;
assert!(
chans
.as_array()
.unwrap()
.iter()
.any(|ch| !ch["now"].is_null()),
"no current programme"
);
// public sharing
let sh = json_of(
&env.lan,
Method::POST,
&format!("/api/channels/{id1}/share"),
&c,
Some(json!({"enabled": true})),
)
.await;
let share = sh["token"].as_str().unwrap().to_string();
let (st, page) = call(&env.wan, Method::GET, &format!("/watch/{share}"), "", None).await;
assert_eq!(st, StatusCode::OK);
assert!(String::from_utf8_lossy(&page).contains("TVP1 HD"));
let (st, _) = call(
&env.wan,
Method::GET,
&format!("/hls/{id1}/index.m3u8?share={share}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::OK);
let (st, _) = call(
&env.wan,
Method::GET,
&format!("/hls/{id2}/index.m3u8?share={share}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let (st, _) = call(
&env.wan,
Method::GET,
&format!("/playlist.m3u?share={share}"),
"",
None,
)
.await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
json_of(
&env.lan,
Method::POST,
&format!("/api/channels/{id1}/share"),
&c,
Some(json!({"enabled": false})),
)
.await;
let (st, _) = call(&env.wan, Method::GET, &format!("/watch/{share}"), "", None).await;
assert_eq!(st, StatusCode::NOT_FOUND);
// manual recording (about 8 s of stream at 4x speed)
let now = chrono::Utc::now().timestamp();
let rec = json_of(
&env.lan,
Method::POST,
"/api/recordings",
&c,
Some(json!({"channel_id": id1, "title": "Test recording", "start": now, "stop": now + 8})),
)
.await;
let rid = rec["id"].as_i64().unwrap();
let mut status = String::new();
for _ in 0..120 {
tokio::time::sleep(Duration::from_millis(250)).await;
let r = json_of(&env.lan, Method::GET, "/api/recordings", &c, None).await;
status = r[0]["status"].as_str().unwrap().to_string();
if status == "completed" || status == "failed" {
break;
}
}
assert_eq!(status, "completed");
let (st, pl) = call(
&env.lan,
Method::GET,
&format!("/recordings/{rid}/index.m3u8"),
&c,
None,
)
.await;
assert_eq!(st, StatusCode::OK);
let pl = String::from_utf8(pl).unwrap();
assert!(
pl.contains("#EXT-X-BYTERANGE:") && pl.contains("#EXT-X-ENDLIST"),
"{pl}"
);
let res = env
.lan
.clone()
.oneshot(
Request::get(format!("/recordings/{rid}/file"))
.header(header::COOKIE, &c)
.header(header::RANGE, "bytes=0-187")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::PARTIAL_CONTENT);
let b = res.into_body().collect().await.unwrap().to_bytes();
assert_eq!(b.len(), 188);
assert_eq!(b[0], 0x47);
// settings: validation
let mut s = json_of(&env.lan, Method::GET, "/api/settings", &c, None).await;
s["hls_window"] = json!(1);
let (st, _) = call(&env.lan, Method::PUT, "/api/settings", &c, Some(s.clone())).await;
assert_eq!(st, StatusCode::BAD_REQUEST);
s["hls_window"] = json!(10);
s["stream_open_cidrs"] = json!([]);
json_of(&env.lan, Method::PUT, "/api/settings", &c, Some(s)).await;
// LAN without a token is no longer open, but a panel session is enough
let (st, _) = call(&env.lan, Method::GET, "/playlist.m3u", "", None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
let (st, _) = call(&env.lan, Method::GET, "/playlist.m3u", &c, None).await;
assert_eq!(st, StatusCode::OK);
// series recording rule: matches upcoming “TVN - audycja N” programmes from EIT
let rule = json_of(
&env.lan,
Method::POST,
"/api/autorec",
&c,
Some(json!({"name": "TVN", "pattern": "^TVN - audycja [2-4]$"})),
)
.await;
assert!(rule["scheduled"].as_u64().unwrap() >= 1, "{rule}");
let recs = json_of(&env.lan, Method::GET, "/api/recordings", &c, None).await;
assert!(recs
.as_array()
.unwrap()
.iter()
.any(|r| r["autorec_id"] == rule["id"] && r["status"] == "scheduled"));
// running it again does not create duplicates
let again = simply_dvb::recorder::run_autorec(&env.state).await.unwrap();
assert_eq!(again, 0);
json_of(
&env.lan,
Method::DELETE,
&format!("/api/autorec/{}", rule["id"]),
&c,
None,
)
.await;
// Prometheus metrics
let (st, body) = call(&env.lan, Method::GET, "/metrics", &c, None).await;
assert_eq!(st, StatusCode::OK);
let m = String::from_utf8(body).unwrap();
assert!(
m.contains("simply_dvb_tuner_locked{adapter=\"virtual0\""),
"{m}"
);
assert!(m.contains("simply_dvb_channels{enabled=\"true\"}"));
let (st, _) = call(&env.wan, Method::GET, "/metrics", "", None).await;
assert_eq!(st, StatusCode::UNAUTHORIZED);
// backup and restore
let (st, backup) = call(&env.lan, Method::GET, "/api/backup", &c, None).await;
assert_eq!(st, StatusCode::OK);
let backup: Value = serde_json::from_slice(&backup).unwrap();
assert_eq!(backup["channels"].as_array().unwrap().len(), 4);
json_of(
&env.lan,
Method::DELETE,
&format!("/api/channels/{id1}"),
&c,
None,
)
.await;
let r = json_of(&env.lan, Method::POST, "/api/restore", &c, Some(backup)).await;
assert_eq!(r["channels"], 4);
let chans = json_of(&env.lan, Method::GET, "/api/channels", &c, None).await;
assert_eq!(chans.as_array().unwrap().len(), 4);
env.state.tuners.shutdown();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn xmltv_import_maps_channels() {
let env = setup().await;
let c = env.cookie.clone();
let db = &env.state.db;
let ch = db.create_channel(1, "TVP 1", None, "TV").await.unwrap();
db.create_channel(2, "Other channel", None, "TV")
.await
.unwrap();
let xml = r#"<tv><channel id="TVP1.pl"><display-name>TVP1</display-name></channel>
<programme start="20990101060000 +0100" stop="20990101070000 +0100" channel="TVP1.pl"><title>Teleexpress</title><desc>Wiadomości</desc></programme>
<programme start="20990101070000 +0100" stop="20990101080000 +0100" channel="Nieznany"><title>X</title></programme></tv>"#;
let (matched, n) = epg::import_xml(&env.state, xml).await.unwrap();
assert_eq!((matched, n), (1, 1));
let ev = json_of(
&env.lan,
Method::GET,
&format!("/api/epg?channel={ch}&from=4070900000&to=4071000000"),
&c,
None,
)
.await;
assert_eq!(ev[0]["title"], "Teleexpress");
assert_eq!(ev[0]["source"], "xmltv");
}
fn base64_encode(s: &str) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(s)
}
/// HTSP client side of the wire format (enough for the test).
mod htsp_client {
pub use simply_dvb::htsp::msg::{Msg, Val};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
pub async fn send(s: &mut TcpStream, m: Msg) {
s.write_all(&m.encode()).await.unwrap();
}
pub async fn recv(s: &mut TcpStream) -> Msg {
let mut l = [0u8; 4];
s.read_exact(&mut l).await.unwrap();
let mut b = vec![0u8; u32::from_be_bytes(l) as usize];
s.read_exact(&mut b).await.unwrap();
Msg::decode(&b).unwrap()
}
/// Sends a request and returns its reply (async messages are collected into `seen`).
pub async fn call(s: &mut TcpStream, seq: i64, m: Msg, seen: &mut Vec<Msg>) -> Msg {
send(s, m.int("seq", seq)).await;
loop {
let r = recv(s).await;
if r.get_i64("seq") == Some(seq) {
return r;
}
seen.push(r);
}
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn htsp_protocol() {
use htsp_client::*;
let env = setup().await;
let c = env.cookie.clone();
json_of(
&env.lan,
Method::POST,
"/api/scan",
&c,
Some(json!({"preset": "custom", "frequencies_mhz": [538], "follow_nit": false})),
)
.await;
for _ in 0..100 {
tokio::time::sleep(Duration::from_millis(200)).await;
let s = json_of(&env.lan, Method::GET, "/api/scan", &c, None).await;
if !s["running"].as_bool().unwrap() {
break;
}
}
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let (_stop_tx, stop_rx) = tokio::sync::watch::channel(false);
tokio::spawn(simply_dvb::htsp::serve(
env.state.clone(),
listener,
stop_rx,
));
let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
let mut seen = Vec::new();
let hello = call(
&mut s,
1,
Msg::method("hello")
.int("htspversion", 34)
.str("clientname", "Kodi")
.str("clientversion", "21"),
&mut seen,
)
.await;
assert_eq!(hello.get_i64("htspversion"), Some(34));
assert_eq!(hello.get_bin("challenge").unwrap().len(), 32);
// 127.0.0.1 is in the default open networks: no credentials needed
let auth = call(&mut s, 2, Msg::method("authenticate"), &mut seen).await;
assert!(auth.get("noaccess").is_none(), "{auth:?}");
call(
&mut s,
3,
Msg::method("enableAsyncMetadata").int("epg", 1),
&mut seen,
)
.await;
loop {
let m = recv(&mut s).await;
let done = m.get_str("method") == Some("initialSyncCompleted");
seen.push(m);
if done {
break;
}
}
let channels: Vec<&Msg> = seen
.iter()
.filter(|m| m.get_str("method") == Some("channelAdd"))
.collect();
assert_eq!(channels.len(), 3, "{seen:?}");
assert_eq!(channels[0].get_str("channelName"), Some("TVP1 HD"));
assert!(seen.iter().any(|m| m.get_str("method") == Some("tagAdd")));
let ch = channels[0].get_i64("channelId").unwrap();
call(
&mut s,
4,
Msg::method("subscribe")
.int("subscriptionId", 9)
.int("channelId", ch),
&mut seen,
)
.await;
let mut started = false;
let mut video = 0;
let mut audio = 0;
let mut first_key = None;
let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
while tokio::time::Instant::now() < deadline && (video < 20 || audio < 20) {
let m = tokio::time::timeout(Duration::from_secs(5), recv(&mut s))
.await
.expect("no HTSP data");
match m.get_str("method") {
Some("subscriptionStart") => {
let Some(Val::List(streams)) = m.get("streams") else {
panic!("no streams")
};
assert!(streams.len() >= 2);
started = true;
}
Some("muxpkt") => {
assert!(started, "muxpkt before subscriptionStart");
assert!(!m.get_bin("payload").unwrap().is_empty());
if m.get_i64("stream") == Some(1) {
first_key.get_or_insert(m.get_i64("frametype").unwrap());
video += 1;
} else {
audio += 1;
}
}
Some("subscriptionStop") => panic!("stopped: {m:?}"),
_ => {}
}
}
assert!(video >= 20 && audio >= 20, "video {video} audio {audio}");
// the stream starts with a keyframe
assert_eq!(first_key, Some('I' as i64));
let r = call(
&mut s,
5,
Msg::method("unsubscribe").int("subscriptionId", 9),
&mut seen,
)
.await;
assert!(r.get("error").is_none());
}
+82
View File
@@ -0,0 +1,82 @@
/* simply-dvb – "control room" style panel (inspired by RustProxy) */
:root {
color-scheme: dark;
--bg: #131615;
--panel: #1b1f1d;
--panel2: #202622;
--line: #323a34;
--row-line: #2b332c;
--muted: #a0aaa0;
--subtle: #879082;
--text: #edf0e9;
--accent: #f69b74;
--accent-hover: #ffb090;
--accent-ink: #221810;
--green: #bdd293;
--red: #ffaaa2;
--blue: #8ebcff;
--yellow: #e7c76d;
--sidebar-bg: #101310;
--nav-active-bg: #242b23;
--field-bg: #131813;
--field-line: #47523f;
--danger-line: #644a47;
--notice-bg: #29251c;
--notice-line: #554833;
--mono: ui-monospace, SFMono-Regular, "JetBrains Mono", Consolas, monospace;
--sans: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
--radius: 3px;
}
html[data-theme=light] {
color-scheme: light;
--bg: #f4f6f2;
--panel: #fff;
--panel2: #edf1eb;
--line: #cbd3c7;
--row-line: #dde3d9;
--muted: #5e685f;
--subtle: #6f786c;
--text: #1d241f;
--accent: #b85b38;
--accent-hover: #9c4729;
--accent-ink: #fff;
--green: #5f783f;
--red: #b64a43;
--blue: #2d6bc4;
--yellow: #8c6a12;
--sidebar-bg: #eef2ec;
--nav-active-bg: #dfe7da;
--field-bg: #fff;
--field-line: #b9c3b3;
--danger-line: #e3b8b3;
--notice-bg: #fbf5e6;
--notice-line: #e2d2a8;
}
html[data-theme=midnight] {
--bg: #050605;
--panel: #0c0e0d;
--panel2: #121513;
--line: #222823;
--row-line: #1a1f1b;
--sidebar-bg: #000;
--nav-active-bg: #151a15;
--field-bg: #070907;
--field-line: #333c30;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 13px/1.45 var(--sans); }
a { color: var(--accent); text-decoration: none; }
a:hover { color: var(--accent-hover); }
.hidden { display: none !important; }
.mono { font-family: var(--mono); }
.muted { color: var(--muted); }
.small { font-size: 11px; }
.error-text { color: var(--red); min-height: 1.2em; }
.ok-text { color: var(--green); }
.warn-text { color: var(--yellow); }
h1, h2, h3 { font-weight: 600; margin: 0; letter-spacing: -.01em; }
code, .code { font-family: var(--mono); font-size: 12px; background: var(--field-bg); border: 1px solid var(--line); padding: 1px 5px; border-radius: var(--radius); word-break: break-all; }
::-webkit-scrollbar { width: 10px; height: 10px; }
::-webkit-scrollbar-track { background: var(--bg); }
::-webkit-scrollbar-thumb { background: #4f5d50; border-radius: 6px; border: 2px solid var(--bg); }
+38
View File
@@ -0,0 +1,38 @@
/* ---------------------------------------------------------------- shell */
.shell { display: flex; min-height: 100vh; }
.sidebar { position: fixed; inset: 0 auto 0 0; width: 52px; background: var(--sidebar-bg); border-right: 1px solid var(--line); display: flex; flex-direction: column; align-items: stretch; padding: 10px 0; gap: 4px; z-index: 20; transition: width .15s; overflow: hidden; }
.sidebar:hover { width: 190px; box-shadow: 4px 0 18px #0006; }
.sidebar a { display: flex; align-items: center; gap: 12px; height: 36px; padding: 0 15px; color: var(--muted); border-left: 2px solid transparent; white-space: nowrap; }
.sidebar a span { display: none; font-size: 13px; }
.sidebar:hover a span { display: inline; }
.sidebar a:hover { color: var(--text); background: var(--nav-active-bg); }
.sidebar a.active { color: var(--green); background: var(--nav-active-bg); border-left-color: var(--green); }
.sidebar svg { width: 18px; height: 18px; flex: 0 0 18px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
.sidebar svg .fill { fill: currentColor; }
.brand-mark { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; box-sizing: border-box; width: 34px; height: 34px; border: 2px solid var(--accent); color: var(--accent); font: 700 13px/1 var(--mono); letter-spacing: -.02em; border-radius: 4px; white-space: nowrap; }
.brand-mark.big { width: 54px; height: 54px; font-size: 20px; margin: 0 0 18px; }
/* Sidebar brand link: its own box, not styled like the nav items (no left border/padding/hover). */
.sidebar a.brand { height: 48px; padding: 0 0 0 9px; margin-bottom: 8px; border-left: 0; background: none; }
.sidebar a.brand:hover { background: none; }
.sidebar a.brand .brand-mark { display: inline-flex; }
.sidebar-foot { margin-top: auto; display: flex; justify-content: center; padding: 10px; }
.live-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--subtle); display: inline-block; }
.live-dot.on { background: var(--green); box-shadow: 0 0 6px var(--green); }
.live-dot.off { background: var(--red); }
.main { flex: 1; margin-left: 52px; min-width: 0; }
.topbar { display: flex; justify-content: space-between; align-items: center; height: 42px; padding: 0 18px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--bg); z-index: 10; }
.crumbs { font: 11px var(--mono); letter-spacing: .12em; text-transform: uppercase; color: var(--muted); display: flex; gap: 10px; }
.crumbs #crumb { color: var(--text); text-transform: none; letter-spacing: .04em; }
.crumbs .sep { color: var(--subtle); }
.top-actions { display: flex; gap: 8px; align-items: center; }
.who { font: 11px var(--mono); color: var(--muted); padding: 0 6px; }
.view { padding: 18px 18px 40px; }
/* ---------------------------------------------------------------- page header */
.page-head { display: flex; justify-content: space-between; align-items: flex-end; gap: 16px; margin-bottom: 16px; flex-wrap: wrap; }
.eyebrow { font: 10px var(--mono); letter-spacing: .16em; text-transform: uppercase; color: var(--green); display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
.eyebrow::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
.page-head h1 { font-size: 26px; }
.page-head p { margin: 6px 0 0; color: var(--muted); font-size: 12px; }
.actions { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
+92
View File
@@ -0,0 +1,92 @@
/* ---------------------------------------------------------------- panels */
.grid { display: grid; gap: 10px; }
.g1 { grid-template-columns: minmax(0, 1fr); }
.g2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.g3 { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.g4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 14px; min-width: 0; }
.panel > header { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 10px; flex-wrap: wrap; }
.panel > header h2 { font-size: 14px; }
.panel + .panel, .grid + .panel, .panel + .grid, .grid + .grid { margin-top: 10px; }
.grid > .panel + .panel { margin-top: 0; }
.stat .label, .label { font: 10px var(--mono); letter-spacing: .1em; text-transform: uppercase; color: var(--muted); }
.stat .value { font: 500 26px var(--mono); margin-top: 8px; }
.stat .sub { font: 11px var(--mono); color: var(--muted); margin-top: 4px; }
.kv { display: grid; grid-template-columns: max-content 1fr; gap: 4px 14px; font-size: 12px; }
.kv > :nth-child(odd) { color: var(--muted); font: 11px var(--mono); padding-top: 1px; }
.pill { display: inline-block; font: 10px var(--mono); letter-spacing: .06em; padding: 2px 7px; border: 1px solid var(--field-line); border-radius: 2px; color: var(--muted); white-space: nowrap; }
.pill.ok { color: var(--green); border-color: #576847; }
.pill.warn { color: var(--yellow); border-color: var(--notice-line); }
.pill.err { color: var(--red); border-color: var(--danger-line); }
.pill.acc { color: var(--accent); border-color: #6d5a45; }
.pill.blue { color: var(--blue); border-color: #3b5272; }
.notice { background: var(--notice-bg); border: 1px solid var(--notice-line); color: var(--text); padding: 10px 12px; border-radius: var(--radius); font-size: 12px; margin-bottom: 10px; }
.empty { color: var(--muted); padding: 24px; text-align: center; border: 1px dashed var(--line); border-radius: var(--radius); }
/* meters */
.meter { height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; margin: 6px 0 2px; }
.meter > i { display: block; height: 100%; background: var(--accent); border-radius: 3px; transition: width .4s; }
.meter.good > i { background: var(--green); }
.meter.bad > i { background: var(--red); }
.meter.blue > i { background: var(--blue); }
.spark { width: 100%; height: 46px; display: block; }
.spark path { fill: none; stroke: var(--accent); stroke-width: 1.6; }
.spark .area { fill: var(--accent); opacity: .12; stroke: none; }
/* ---------------------------------------------------------------- tables */
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th { text-align: left; font: 10px var(--mono); letter-spacing: .1em; text-transform: uppercase; color: var(--muted); font-weight: 400; padding: 6px 8px; border-bottom: 1px solid var(--line); white-space: nowrap; }
td { padding: 6px 8px; border-bottom: 1px solid var(--row-line); vertical-align: middle; }
tr:hover td { background: var(--panel2); }
td.num, th.num { text-align: right; font-family: var(--mono); }
td.actions-cell { text-align: right; white-space: nowrap; }
tr.dragging td { opacity: .4; }
tr.drop-target td { border-top: 2px solid var(--accent); }
.drag { cursor: grab; color: var(--subtle); user-select: none; font-size: 14px; padding: 0 4px; }
.logo { width: 46px; height: 28px; object-fit: contain; display: block; }
.logo-ph { width: 46px; height: 28px; display: flex; align-items: center; justify-content: center; font: 600 10px var(--mono); color: var(--subtle); border: 1px dashed var(--line); border-radius: 2px; }
/* ---------------------------------------------------------------- forms */
input, select, textarea { font: 12px var(--sans); color: var(--text); background: var(--field-bg); border: 1px solid var(--field-line); border-radius: var(--radius); padding: 6px 8px; min-height: 28px; max-width: 100%; }
input:focus, select:focus, textarea:focus { outline: 1px solid var(--accent); border-color: var(--accent); }
textarea { width: 100%; min-height: 70px; font-family: var(--mono); resize: vertical; }
input[type=checkbox] { min-height: 0; width: 15px; height: 15px; accent-color: var(--accent); vertical-align: middle; }
label { display: flex; flex-direction: column; gap: 4px; font: 11px var(--mono); color: var(--muted); letter-spacing: .02em; }
label.check { flex-direction: row; align-items: center; gap: 8px; font: 12px var(--sans); color: var(--text); }
.form-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 12px; }
.form-grid .full { grid-column: 1 / -1; }
.hint { font: 11px var(--sans); color: var(--subtle); }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.btn { font: 12px var(--sans); display: inline-flex; align-items: center; gap: 6px; padding: 5px 11px; min-height: 28px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); color: var(--text); cursor: pointer; white-space: nowrap; }
.btn:hover { border-color: #89917c; }
.btn.primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); font-weight: 600; }
.btn.primary:hover { background: var(--accent-hover); }
.btn.danger { color: var(--red); border-color: var(--danger-line); }
.btn.ghost { background: transparent; }
.btn.small { padding: 2px 8px; min-height: 22px; font-size: 11px; }
.btn.icon { padding: 2px 8px; }
.btn.wide { width: 100%; justify-content: center; }
.btn:disabled { opacity: .5; cursor: default; }
.switch { position: relative; width: 30px; height: 16px; display: inline-block; }
.switch input { opacity: 0; width: 0; height: 0; }
.switch span { position: absolute; inset: 0; background: var(--line); border-radius: 10px; cursor: pointer; transition: .15s; }
.switch span::before { content: ""; position: absolute; width: 12px; height: 12px; left: 2px; top: 2px; background: var(--muted); border-radius: 50%; transition: .15s; }
.switch input:checked + span { background: #4d6136; }
.switch input:checked + span::before { transform: translateX(14px); background: var(--green); }
.tabs { display: flex; gap: 2px; border-bottom: 1px solid var(--line); margin-bottom: 12px; }
.tabs button { background: none; border: none; color: var(--muted); padding: 7px 12px; cursor: pointer; font: 12px var(--sans); border-bottom: 2px solid transparent; }
.tabs button.active { color: var(--text); border-bottom-color: var(--accent); }
/* ---------------------------------------------------------------- modal & toasts */
.modal { position: fixed; inset: 0; background: rgba(0, 0, 0, .68); display: flex; align-items: flex-start; justify-content: center; z-index: 50; padding: 6vh 16px; overflow-y: auto; }
.modal-card { background: var(--panel); border: 1px solid var(--line); border-radius: 4px; width: min(720px, 100%); padding: 16px 18px; box-shadow: 0 12px 40px #0009; }
.modal-card.wide { width: min(1100px, 100%); }
.modal-card > header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px; }
.modal-card > header h2 { font-size: 16px; }
.modal-foot { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
.toasts { position: fixed; right: 16px; bottom: 16px; display: flex; flex-direction: column; gap: 8px; z-index: 60; }
.toast { background: #d0dfb4; color: #1c2818; border: 1px solid #ebf2de; padding: 9px 14px; border-radius: 3px; font-size: 12px; max-width: 420px; box-shadow: 0 6px 20px #0007; animation: slide .2s; white-space: pre-wrap; }
.toast.err { background: #ffd2bd; color: #42241b; border-color: #ff9f7a; }
@keyframes slide { from { transform: translateY(10px); opacity: 0; } }
+141
View File
@@ -0,0 +1,141 @@
/* ---------------------------------------------------------------- login */
.login { min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 20px; }
.login-card { width: 340px; background: var(--panel); border: 1px solid var(--line); padding: 28px; border-radius: 4px; display: flex; flex-direction: column; gap: 12px; }
.login-card h1 { font-size: 24px; margin-bottom: 6px; }
.login-card input { padding: 9px 10px; font-size: 13px; }
/* ---------------------------------------------------------------- tuner cards */
.tuner { display: grid; grid-template-columns: 1fr; gap: 8px; }
.tuner .t-head { display: flex; justify-content: space-between; gap: 10px; align-items: flex-start; }
.tuner h3 { font-size: 14px; }
.tuner .t-meta { font: 11px var(--mono); color: var(--muted); }
.sig { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 10px; }
.sig .value { font: 500 18px var(--mono); margin-top: 4px; }
/* ---------------------------------------------------------------- TV */
.tv { display: grid; grid-template-columns: 320px minmax(0, 1fr); gap: 10px; align-items: start; }
.tv-list { max-height: calc(100vh - 150px); overflow-y: auto; padding: 0; }
.tv-list .search { padding: 8px; border-bottom: 1px solid var(--line); position: sticky; top: 0; background: var(--panel); z-index: 1; display: flex; gap: 6px; }
.tv-list .search input { flex: 1; }
.ch-item { display: grid; grid-template-columns: 28px 50px 1fr; gap: 8px; align-items: center; padding: 7px 10px; border-bottom: 1px solid var(--row-line); cursor: pointer; }
.ch-item:hover { background: var(--panel2); }
.ch-item.active { background: var(--nav-active-bg); box-shadow: inset 2px 0 0 var(--accent); }
.ch-item .n { font: 11px var(--mono); color: var(--muted); text-align: right; }
.ch-item .t { min-width: 0; }
.ch-item .name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.ch-item .now { font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.ch-item .meter { height: 3px; margin: 3px 0 0; }
.player { position: relative; background: #000; aspect-ratio: 16 / 9; width: 100%; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; }
.player video { width: 100%; height: 100%; display: block; background: #000; }
.player .overlay { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; color: #ddd; font: 12px var(--mono); pointer-events: none; text-align: center; padding: 20px; background: radial-gradient(circle, #0008, #000c); }
.player .overlay.err { color: #ffaaa2; }
.player .badge { position: absolute; top: 10px; left: 10px; font: 10px var(--mono); letter-spacing: .1em; color: #fff; background: #c43c2acc; padding: 2px 7px; border-radius: 2px; pointer-events: none; }
.spinner { width: 28px; height: 28px; border: 3px solid #fff3; border-top-color: var(--accent); border-radius: 50%; animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.np { display: grid; grid-template-columns: 1fr auto; gap: 10px; }
.np h2 { font-size: 18px; }
.np .time { font: 11px var(--mono); color: var(--muted); }
.np .desc { color: var(--muted); font-size: 12px; margin-top: 6px; max-height: 7.5em; overflow: auto; white-space: pre-line; }
.day-list .ev { display: grid; grid-template-columns: 52px 1fr auto; gap: 8px; padding: 5px 0; border-bottom: 1px solid var(--row-line); align-items: center; }
.day-list .ev.cur { color: var(--accent); }
.day-list .ev.past { color: var(--subtle); }
.day-list .ev .tm { font: 11px var(--mono); }
/* ---------------------------------------------------------------- EPG grid */
.epg { position: relative; overflow: auto; max-height: calc(100vh - 170px); border: 1px solid var(--line); background: var(--panel); }
.epg-inner { position: relative; }
.epg-row { display: flex; height: 52px; border-bottom: 1px solid var(--row-line); }
.epg-ch { position: sticky; left: 0; z-index: 3; width: 170px; flex: 0 0 170px; background: var(--panel); border-right: 1px solid var(--line); display: flex; align-items: center; gap: 8px; padding: 0 8px; font-size: 12px; cursor: pointer; }
.epg-ch .n { font: 10px var(--mono); color: var(--muted); width: 22px; text-align: right; }
.epg-ch .logo, .epg-ch .logo-ph { width: 40px; height: 24px; }
.epg-ch .nm { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 600; }
.epg-track { position: relative; flex: 1; }
.epg-ev { position: absolute; top: 4px; bottom: 4px; background: var(--panel2); border: 1px solid var(--line); border-radius: 2px; padding: 4px 7px; overflow: hidden; cursor: pointer; font-size: 11px; white-space: nowrap; }
.epg-ev:hover { border-color: var(--accent); z-index: 2; }
.epg-ev .tt { font-weight: 600; overflow: hidden; text-overflow: ellipsis; }
.epg-ev .tm { font: 10px var(--mono); color: var(--muted); }
.epg-ev.cur { border-color: #6d5a45; background: #2a2620; }
html[data-theme=light] .epg-ev.cur { background: #fbeee6; }
.epg-ev.rec::after { content: "●"; color: #e25b45; position: absolute; right: 5px; top: 3px; font-size: 10px; }
.epg-head { display: flex; position: sticky; top: 0; z-index: 4; background: var(--panel); border-bottom: 1px solid var(--line); height: 26px; }
.epg-head .corner { position: sticky; left: 0; width: 170px; flex: 0 0 170px; background: var(--panel); border-right: 1px solid var(--line); z-index: 5; }
.epg-head .hours { position: relative; flex: 1; }
.epg-head .h { position: absolute; top: 0; height: 26px; border-left: 1px solid var(--line); font: 10px var(--mono); color: var(--muted); padding: 6px 6px; }
.epg-now { position: absolute; top: 0; bottom: 0; width: 2px; background: var(--accent); z-index: 2; pointer-events: none; }
/* ---------------------------------------------------------------- scan log */
.log { font: 11px/1.6 var(--mono); background: var(--field-bg); border: 1px solid var(--line); padding: 8px 10px; max-height: 260px; overflow: auto; white-space: pre-wrap; border-radius: var(--radius); }
.copy-row { display: flex; gap: 6px; align-items: center; margin: 4px 0; }
.copy-row code { flex: 1; padding: 5px 8px; }
/* ---------------------------------------------------------------- bare pages (watch, message) */
body.bare { min-height: 100vh; }
.message { max-width: 520px; margin: 18vh auto; padding: 20px; text-align: center; }
.message .brand-mark { margin: 0 auto 16px; }
.watch-head { display: flex; gap: 14px; align-items: center; padding: 16px 22px; border-bottom: 1px solid var(--line); }
.watch-head .brand-mark { margin: 0; }
.watch-head h1 { font-size: 20px; }
.watch-main { max-width: 1200px; margin: 18px auto; padding: 0 16px; }
.player .osd { position: absolute; top: 12px; right: 14px; font: 600 22px var(--mono); color: #fff; background: #000a; padding: 6px 12px; border-radius: 3px; opacity: 0; transition: opacity .25s; pointer-events: none; text-shadow: 0 1px 2px #000; }
.player .osd.show { opacity: 1; }
.player:fullscreen { border: 0; border-radius: 0; }
/* ---------------------------------------------------------------- live charts */
.section-head { display: flex; align-items: center; justify-content: space-between; margin: 14px 0 8px; }
.section-head h2 { font-size: 14px; }
.chart-card { position: relative; padding: 12px 14px 10px; }
.chart-head { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; flex-wrap: wrap; margin-bottom: 6px; }
.chart-vals { display: flex; gap: 12px; flex-wrap: wrap; font: 11px var(--mono); color: var(--muted); }
.chart-vals b { color: var(--text); font-weight: 600; }
.chart-vals .cv i { display: inline-block; width: 8px; height: 8px; border-radius: 2px; margin-right: 4px; vertical-align: 0; }
.chart { width: 100%; height: 92px; display: block; overflow: visible; }
.chart .g { stroke: var(--row-line); stroke-width: 1; vector-effect: non-scaling-stroke; }
.chart .ln { fill: none; stroke-width: 1.6; vector-effect: non-scaling-stroke; stroke-linejoin: round; }
.chart .area { opacity: .12; stroke: none; }
.chart rect { opacity: .85; }
.chart .cursor { stroke: var(--muted); stroke-width: 1; stroke-dasharray: 3 3; vector-effect: non-scaling-stroke; }
.chart-scale { position: absolute; right: 16px; top: 36px; bottom: 26px; display: flex; flex-direction: column; justify-content: space-between; font: 9px var(--mono); color: var(--subtle); pointer-events: none; text-align: right; }
.chart-hover { min-height: 14px; margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.tuner-charts { margin-top: 4px; }
.tuner-charts .chart-card { background: var(--panel2); }
.player .overlay .hint { max-width: 560px; margin-top: 8px; font-size: 12px; color: #ddd; text-align: center; line-height: 1.45; }
.player .overlay .btn { margin-top: 10px; }
/* ---------------------------------------------------------------- channel filters */
.filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; padding: 0 0 12px; border-bottom: 1px solid var(--row-line); margin-bottom: 8px; }
.filters input:not([type]) { width: 200px; }
.filters select { width: auto; }
.filters .check { font-size: 12px; white-space: nowrap; }
.filters .spacer { flex: 1; }
tr.off td { opacity: .55; }
tr.off td:last-child, tr.off td:nth-last-child(2), tr.off td:nth-last-child(3) { opacity: 1; }
/* ---------------------------------------------------------------- logs */
.log-view { max-height: calc(100vh - 300px); min-height: 320px; white-space: normal; padding: 4px 0; }
.log-line { display: grid; grid-template-columns: 150px 46px 120px 1fr auto; gap: 10px; padding: 2px 10px; border-bottom: 1px solid var(--row-line); align-items: baseline; }
.log-line:hover { background: var(--panel2); }
.log-ts { color: var(--subtle); white-space: nowrap; }
.log-lv { font-weight: 600; color: var(--muted); }
.log-cat { color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.log-msg { white-space: pre-wrap; word-break: break-word; color: var(--text); }
.log-target { color: var(--subtle); font-size: 10px; white-space: nowrap; max-width: 160px; overflow: hidden; text-overflow: ellipsis; }
.lv-warn .log-lv { color: var(--yellow); }
.lv-error .log-lv, .lv-error .log-msg { color: var(--red); }
.lv-debug .log-msg { color: var(--muted); }
#log-cats button .pill { margin-left: 2px; padding: 0 5px; }
@media (max-width: 900px) { .log-line { grid-template-columns: 1fr; gap: 0; } .log-target { display: none; } }
/* ---------------------------------------------------------------- recording schedule */
.sched-day { margin: 14px 0; }
.sched-head { font-size: 13px; margin-bottom: 4px; }
.sched-grid { position: relative; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel2);
background-image: repeating-linear-gradient(90deg, var(--row-line) 0 1px, transparent 1px calc(100% / 24)); }
.sched-tick { position: absolute; top: 1px; font: 9px var(--mono); color: var(--subtle); transform: translateX(3px); }
.sched-now { position: absolute; top: 0; bottom: 0; width: 2px; background: var(--red); z-index: 2; }
.sched-bar { position: absolute; height: 22px; line-height: 22px; padding: 0 6px; font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
border-radius: 3px; background: color-mix(in srgb, var(--c) 28%, transparent); border-left: 3px solid var(--c); color: var(--text); }
.sched-bar.live { box-shadow: 0 0 0 1px var(--red) inset; }
.sched-bar.conflict { background: repeating-linear-gradient(135deg, color-mix(in srgb, var(--red) 35%, transparent) 0 6px, color-mix(in srgb, var(--red) 15%, transparent) 6px 12px); border-left-color: var(--red); }
tr.row-warn td { background: color-mix(in srgb, var(--red) 8%, transparent); }
+40
View File
@@ -0,0 +1,40 @@
/* ---------------------------------------------------------------- personalizacja */
html[data-density=compact] .view { padding: 12px 12px 30px; }
html[data-density=compact] .panel { padding: 8px 10px; }
html[data-density=compact] td { padding: 4px 6px; }
html[data-density=compact] .btn { min-height: 24px; padding: 3px 9px; }
html[data-density=compact] .ch-item { padding: 4px 8px; }
html[data-density=compact] .page-head { margin-bottom: 10px; }
html[data-density=compact] .page-head h1 { font-size: 22px; }
html[data-density=compact] .stat .value { font-size: 22px; margin-top: 4px; }
html[data-density=compact] .grid { gap: 8px; }
html[data-sidebar=pinned] .sidebar { width: 190px; }
html[data-sidebar=pinned] .sidebar a span { display: inline; }
html[data-sidebar=pinned] .main { margin-left: 190px; }
html[data-sidebar=pinned] .sidebar:hover { box-shadow: none; }
html[data-motion=off] *:not(.spinner) { transition: none !important; animation: none !important; }
.hide-logos .ch-item { grid-template-columns: 28px 1fr; }
.hide-logos .ch-item .logo, .hide-logos .ch-item .logo-ph { display: none; }
.hide-progress .ch-item .meter { display: none; }
.clock { font: 12px var(--mono); color: var(--text); padding: 0 8px; letter-spacing: .04em; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; }
.seg button { background: var(--panel); color: var(--muted); border: 0; border-right: 1px solid var(--line); padding: 4px 9px; font: 11px var(--mono); cursor: pointer; min-height: 26px; }
.seg button:last-child { border-right: 0; }
.seg button.on { background: var(--nav-active-bg); color: var(--accent); }
.swatches { display: flex; gap: 8px; flex-wrap: wrap; }
.swatch { width: 26px; height: 26px; border-radius: 50%; border: 2px solid var(--line); cursor: pointer; padding: 0; }
.swatch.on { border-color: var(--text); box-shadow: 0 0 0 2px var(--bg) inset; }
.pref-row { display: grid; grid-template-columns: 220px 1fr; gap: 10px; align-items: center; padding: 7px 0; border-bottom: 1px solid var(--row-line); }
.pref-row:last-child { border-bottom: 0; }
.pref-row > span { color: var(--muted); font: 11px var(--mono); letter-spacing: .03em; }
@media (max-width: 860px) {
html[data-sidebar=pinned] .main { margin-left: 52px; }
html[data-sidebar=pinned] .sidebar { width: 52px; }
html[data-sidebar=pinned] .sidebar a span { display: none; }
.pref-row { grid-template-columns: 1fr; }
}
/* language picker (one option per langs/*.json pack) */
.lang-select { background: var(--panel); color: var(--muted); border: 1px solid var(--line); border-radius: var(--radius); font: 11px var(--mono); min-height: 28px; padding: 3px 6px; cursor: pointer; max-width: 220px; }
.lang-select:hover, .lang-select:focus { color: var(--text); border-color: var(--accent); outline: none; }
#lang-switch .lang-select { width: auto; }
+12
View File
@@ -0,0 +1,12 @@
/* ---------------------------------------------------------------- responsive */
@media (max-width: 1100px) { .g4 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .g3 { grid-template-columns: 1fr 1fr; } }
@media (max-width: 860px) {
.tv { grid-template-columns: 1fr; }
.tv-list { max-height: 40vh; order: 2; }
.g2, .g3, .g4 { grid-template-columns: 1fr; }
.view { padding: 12px; }
.who { display: none; }
.epg-ch, .epg-head .corner { width: 110px; flex-basis: 110px; }
.epg-ch .logo, .epg-ch .logo-ph { display: none; }
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect x="2" y="2" width="60" height="60" rx="6" fill="#131615" stroke="#f69b74" stroke-width="4"/><text x="32" y="42" font-family="ui-monospace,Consolas,monospace" font-size="26" font-weight="700" text-anchor="middle" fill="#f69b74">s/d</text></svg>

After

Width:  |  Height:  |  Size: 310 B

+56
View File
@@ -0,0 +1,56 @@
<!doctype html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>simply-dvb</title>
<link rel="icon" href="/assets/favicon.svg">
__ASSETS__
</head>
<body>
<div id="login" class="login hidden">
<form id="login-form" class="login-card" autocomplete="on">
<div class="brand-mark big">s/d</div>
<div class="eyebrow">simply-dvb · panel</div>
<h1>Sign in</h1>
<label>Username<input name="username" autocomplete="username" required autofocus></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required></label>
<button class="btn primary wide" type="submit">Sign in</button>
<p id="login-error" class="error-text"></p>
</form>
</div>
<div id="shell" class="shell hidden">
<nav class="sidebar" id="sidebar">
<a class="brand" href="#/overview" title="simply-dvb"><span class="brand-mark">s/d</span></a>
<a data-route="overview" href="#/overview" title="Overview"><svg viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg><span>Overview</span></a>
<a data-route="tv" href="#/tv" title="TV"><svg viewBox="0 0 24 24"><rect x="2" y="6" width="20" height="13" rx="1"/><path d="M8 2l4 4 4-4"/></svg><span>TV</span></a>
<a data-route="epg" href="#/epg" title="TV guide"><svg viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="17" rx="1"/><path d="M3 9h18M8 2v4M16 2v4M7 13h4M7 17h8"/></svg><span>TV guide</span></a>
<a data-route="channels" href="#/channels" title="Channels"><svg viewBox="0 0 24 24"><path d="M8 6h13M8 12h13M8 18h13"/><circle cx="4" cy="6" r="1"/><circle cx="4" cy="12" r="1"/><circle cx="4" cy="18" r="1"/></svg><span>Channels</span></a>
<a data-route="recordings" href="#/recordings" title="Recordings"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3.5" class="fill"/></svg><span>Recordings</span></a>
<a data-route="tuners" href="#/tuners" title="Tuners & scanning"><svg viewBox="0 0 24 24"><path d="M5 12.5a10 10 0 0 1 14 0M8.5 16a5 5 0 0 1 7 0"/><circle cx="12" cy="19.5" r="1" class="fill"/><path d="M2 9a14.5 14.5 0 0 1 20 0"/></svg><span>Tuners</span></a>
<a data-route="access" href="#/access" title="Access & sharing"><svg viewBox="0 0 24 24"><path d="M12 3l8 3v6c0 4.5-3.4 8.3-8 9-4.6-.7-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg><span>Access</span></a>
<a data-route="logs" href="#/logs" title="Logs"><svg viewBox="0 0 24 24"><path d="M4 5h16M4 10h10M4 15h16M4 20h7"/></svg><span>Logs</span></a>
<a data-route="settings" href="#/settings" title="Settings"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg><span>Settings</span></a>
<div class="sidebar-foot"><span class="live-dot" id="live-dot" title="Server connection"></span></div>
</nav>
<div class="main">
<header class="topbar">
<div class="crumbs"><span class="crumb-root" id="server-name">CONTROL ROOM</span><span class="sep">/</span><span id="crumb">Overview</span></div>
<div class="top-actions">
<span class="clock hidden" id="clock"></span>
<div id="lang-switch" data-no-i18n></div>
<button class="btn ghost icon" id="theme-toggle" title="Theme"><svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/></svg></button>
<span class="who" id="who"></span>
<button class="btn ghost" id="logout">⎋ Sign out</button>
</div>
</header>
<section id="view" class="view"></section>
</div>
</div>
<div id="modal" class="modal hidden"><div class="modal-card" role="dialog"><header><h2 id="modal-title"></h2><button class="btn ghost icon" id="modal-close" title="Close">✕</button></header><div id="modal-body"></div></div></div>
<div id="toasts" class="toasts"></div>
</body>
</html>
+193
View File
@@ -0,0 +1,193 @@
/* simply-dvb – UI translation engine.
* The UI source text is English and doubles as the translation key (gettext style).
* Language packs live in langs/<locale>.json ({meta, translations, patterns}); build.rs
* validates them and embeds them in the bundle as window.SDVB_LANGS. When a language other
* than English is active, every text node inserted into the DOM (and placeholder/title/
* aria-label) is translated; missing entries fall back to the English source text.
* Pattern replacements use $1..$9 for raw groups and $t1..$t9 for groups translated again. */
(function () {
'use strict';
var LANG_KEY = 'sdvb-lang';
var DEFAULT = 'en_US';
var LANGS = {};
(window.SDVB_LANGS || []).forEach(function (p) {
var code = p.meta.locale;
LANGS[code] = {
name: p.meta.native_name || p.meta.name || code,
english: p.meta.name || code,
dir: p.meta.direction || 'ltr',
dict: p.translations || {},
rx: (p.patterns || []).map(function (x) { return [new RegExp(x.match), x.replace]; })
};
});
if (!LANGS[DEFAULT]) LANGS[DEFAULT] = { name: 'English', english: 'English', dir: 'ltr', dict: {}, rx: [] };
/** Resolves a stored or requested code ("pl", "pl-PL", "pl_PL") to an available locale. */
function resolve(code) {
if (!code) return null;
var c = String(code).replace('-', '_');
if (LANGS[c]) return c;
var base = c.split('_')[0].toLowerCase();
var keys = Object.keys(LANGS);
for (var i = 0; i < keys.length; i++) if (keys[i].split('_')[0].toLowerCase() === base) return keys[i];
return null;
}
var saved = null;
try { saved = localStorage.getItem(LANG_KEY); } catch (e) {}
var lang = resolve(saved) || DEFAULT;
var active = lang !== DEFAULT;
function expand(tpl, m) {
return tpl.replace(/\$(t?)(\d)/g, function (_, t, n) {
var g = m[+n] == null ? '' : m[+n];
return t ? tr(g) : g;
});
}
function lookup(k) {
var L = LANGS[lang];
if (Object.prototype.hasOwnProperty.call(L.dict, k)) return L.dict[k];
for (var i = 0; i < L.rx.length; i++) {
var m = L.rx[i][0].exec(k);
if (m) return expand(L.rx[i][1], m);
}
return undefined;
}
function tr(s) {
if (!active || s == null) return s;
var str = String(s);
var k = str.trim();
if (!k) return str;
var v = lookup(k);
if (v === undefined || v === '') return str;
return str.replace(k, function () { return v; });
}
var SKIP = { SCRIPT: 1, STYLE: 1, CODE: 1, TEXTAREA: 1 };
var ATTRS = ['placeholder', 'title', 'aria-label'];
function translateTree(root) {
if (!active || !root) return;
if (root.nodeType === 3) {
var p = root.parentNode;
if (p && !SKIP[p.nodeName]) { var n = tr(root.nodeValue); if (n !== root.nodeValue) root.nodeValue = n; }
return;
}
if (root.nodeType !== 1 || SKIP[root.nodeName] || (root.hasAttribute && root.hasAttribute('data-no-i18n'))) return;
var els = [root].concat(Array.prototype.slice.call(root.querySelectorAll('[placeholder],[title],[aria-label]')));
els.forEach(function (el) {
ATTRS.forEach(function (a) {
if (el.hasAttribute(a)) { var v = el.getAttribute(a), n = tr(v); if (n !== v) el.setAttribute(a, n); }
});
});
var w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
acceptNode: function (node) {
for (var e = node.parentNode; e && e !== root.parentNode; e = e.parentNode) {
if (SKIP[e.nodeName] || (e.hasAttribute && e.hasAttribute('data-no-i18n'))) return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
});
var node;
while ((node = w.nextNode())) {
var nv = tr(node.nodeValue);
if (nv !== node.nodeValue) node.nodeValue = nv;
}
}
function boot() {
document.documentElement.lang = lang.replace('_', '-');
document.documentElement.dir = LANGS[lang].dir;
if (!active) return;
translateTree(document.body);
new MutationObserver(function (list) {
list.forEach(function (m) {
if (m.type === 'attributes') { translateTree(m.target); return; }
m.addedNodes.forEach(translateTree);
});
}).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ATTRS });
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
else Promise.resolve().then(boot);
window.I18N = {
get lang() { return lang; },
/** Short UI code of the active language, e.g. "EN". */
get short() { return lang.split('_')[0].toUpperCase(); },
tr: tr,
/** Available languages: [{code, short, name, english}], English first, then by name. */
languages: function () {
return Object.keys(LANGS).sort(function (a, b) {
return (a === DEFAULT ? -1 : b === DEFAULT ? 1 : 0) || LANGS[a].english.localeCompare(LANGS[b].english);
}).map(function (c) {
return { code: c, short: c.split('_')[0].toUpperCase(), name: LANGS[c].name, english: LANGS[c].english };
});
},
setLang: function (l) {
try { localStorage.setItem(LANG_KEY, resolve(l) || DEFAULT); } catch (e) {}
location.reload();
},
/** For tooling: English keys with no translation in the given language. */
missing: function (code) {
var c = resolve(code) || code, d = (LANGS[c] || {}).dict || {}, en = LANGS[DEFAULT].dict;
return Object.keys(en).filter(function (k) { return !Object.prototype.hasOwnProperty.call(d, k); });
}
};
})();
/* UI personalization (stored in localStorage, applied before the first render). */
(function () {
'use strict';
var KEY = 'sdvb-prefs';
var DEFAULTS = { chartWindow: 10, theme: 'dark', accent: 'orange', density: 'comfortable', scale: 100, sidebar: 'hover', start: 'overview',
logos: true, progress: true, autoplay: false, epgZoom: 4, clock: false, motion: true };
var ACCENTS = {
orange: ['#f69b74', '#ffb090', '#221810', '#b85b38'],
green: ['#bdd293', '#d3e6ad', '#1b2410', '#5f783f'],
blue: ['#8ebcff', '#b0d0ff', '#0c1a2e', '#2d6bc4'],
violet: ['#c5a3ff', '#d8c0ff', '#1d1230', '#7a4fc4'],
red: ['#ff8a80', '#ffaaa2', '#2b0f0c', '#b64a43'],
teal: ['#6fd6c6', '#94e6d9', '#0c2420', '#1f8a7a'],
amber: ['#f2c14e', '#f7d47e', '#2a2008', '#9a6a00']
};
var prefs = {};
function load() {
var p = {};
try { p = JSON.parse(localStorage.getItem(KEY) || '{}') || {}; } catch (e) {}
prefs = {};
Object.keys(DEFAULTS).forEach(function (k) { prefs[k] = p[k] === undefined ? DEFAULTS[k] : p[k]; });
}
var mq = window.matchMedia ? window.matchMedia('(prefers-color-scheme: light)') : null;
function apply() {
var html = document.documentElement;
var theme = prefs.theme === 'system' ? (mq && mq.matches ? 'light' : 'dark') : prefs.theme;
html.dataset.theme = theme;
html.dataset.density = prefs.density;
html.dataset.sidebar = prefs.sidebar;
html.dataset.motion = prefs.motion ? 'on' : 'off';
var a = ACCENTS[prefs.accent] || ACCENTS.orange;
var light = theme === 'light';
html.style.setProperty('--accent', light ? a[3] : a[0]);
html.style.setProperty('--accent-hover', light ? a[3] : a[1]);
html.style.setProperty('--accent-ink', light ? '#fff' : a[2]);
html.style.zoom = prefs.scale && prefs.scale !== 100 ? (prefs.scale / 100) : '';
}
load();
apply();
if (mq && mq.addEventListener) mq.addEventListener('change', function () { if (prefs.theme === 'system') apply(); });
window.SDVB_PREFS = {
get: function (k) { return prefs[k]; },
all: function () { return JSON.parse(JSON.stringify(prefs)); },
set: function (k, v) {
prefs[k] = v;
try { localStorage.setItem(KEY, JSON.stringify(prefs)); } catch (e) {}
apply();
},
reset: function () { try { localStorage.removeItem(KEY); } catch (e) {} load(); apply(); },
accents: Object.keys(ACCENTS),
accentColor: function (k) { return (ACCENTS[k] || ACCENTS.orange)[0]; }
};
})();
+230
View File
@@ -0,0 +1,230 @@
/* simply-dvb – HLS player (hls.js / native HLS in Safari) with automatic profile selection */
(function () {
'use strict';
var CODECS = {
'H.264': 'video/mp4; codecs="avc1.640028"',
'HEVC': ['video/mp4; codecs="hvc1.1.6.L120.90"', 'video/mp4; codecs="hvc1.1.6.L123.B0"', 'video/mp4; codecs="hev1.1.6.L120.90"', 'video/mp4; codecs="hvc1.2.4.L120.90"'],
'MPEG-2': null,
'AAC': 'audio/mp4; codecs="mp4a.40.2"',
'MP2': 'audio/mpeg',
'AC-3': 'audio/mp4; codecs="ac-3"',
'E-AC-3': 'audio/mp4; codecs="ec-3"',
'AAC-LATM': null
};
function mse() {
return window.ManagedMediaSource || window.MediaSource;
}
function supported(label) {
if (!label) return true;
var c = CODECS[label];
if (c === undefined) return true;
if (c === null) return false;
var M = mse();
if (!M || !M.isTypeSupported) return false;
var list = Array.isArray(c) ? c : [c];
for (var i = 0; i < list.length; i++) if (M.isTypeSupported(list[i])) return true;
return false;
}
function list(x) { return Array.isArray(x) ? x : (x ? [x] : []); }
/** Codec label without the language suffix, e.g. "MP2 (pol)" -> "MP2". */
function codec(label) { return String(label || '').replace(/ \(.*\)$/, ''); }
/** True when at least one of the audio tracks can be decoded (or there is no audio info). */
function audioOk(audio) {
var a = list(audio).map(codec);
return !a.length || a.some(supported);
}
/**
* Best profile for this browser: pass → aac → h264. Without ffmpeg on the server only
* "pass" is possible, so it is always tried first.
*/
function pickProfile(video, audio, transcode) {
if (transcode === false) return 'pass';
if (!supported(codec(video))) return 'h264';
if (!audioOk(audio)) return 'aac';
return 'pass';
}
function tr(x) { return window.I18N ? window.I18N.tr(x) : x; }
/** Human-readable (translated) explanation why the original stream cannot be decoded here. */
function explain(video, audio) {
var parts = [];
var v = codec(video);
if (v && !supported(v)) {
parts.push(tr(v === 'HEVC'
? 'This browser reports no HEVC (H.265) support. Chrome/Edge decode it only with hardware acceleration (on Linux: VA-API); Safari plays it natively.'
: 'This browser reports no support for ' + v + ' video.'));
}
if (!audioOk(audio)) parts.push(tr('This browser reports no support for any audio track (' + list(audio).map(codec).join(', ') + ').'));
return parts.join(' ');
}
function el(tag, cls, text) {
var e = document.createElement(tag);
if (cls) e.className = cls;
if (text != null) e.textContent = text;
return e;
}
/**
* opts: { channelId, share, token, video, audio, profile ('auto'|'pass'|'aac'|'h264'), src (full playlist URL), live, onProfile }
*/
function create(container, opts) {
container.innerHTML = '';
var video = el('video');
video.controls = true;
video.playsInline = true;
video.autoplay = true;
var overlay = el('div', 'overlay');
var badge = el('div', 'badge', opts.live === false ? 'RECORDING' : 'LIVE');
container.appendChild(video);
container.appendChild(overlay);
container.appendChild(badge);
var hls = null;
var destroyed = false;
var fallbackOrder = opts.transcode === false ? ['pass'] : ['pass', 'aac', 'h264'];
var profile = opts.profile && opts.profile !== 'auto' ? opts.profile : pickProfile(opts.video, opts.audio, opts.transcode);
var auto = !opts.profile || opts.profile === 'auto';
var retries = 0;
function status(msg, err, hint) {
overlay.innerHTML = '';
if (!msg) { overlay.classList.add('hidden'); return; }
overlay.classList.remove('hidden');
overlay.classList.toggle('err', !!err);
if (!err) overlay.appendChild(el('div', 'spinner'));
overlay.appendChild(el('div', null, msg));
if (hint) overlay.appendChild(el('div', 'hint', hint));
if (err && opts.vlcUrl) {
var a = el('a', 'btn small', '▶ Open in VLC');
a.href = opts.vlcUrl;
a.setAttribute('download', '');
overlay.appendChild(a);
}
}
/** Final failure: explain codecs and what can be done. */
function failed(msg) {
var why = explain(opts.video, opts.audio);
var hint = why;
if (opts.transcode === false) hint = (why ? why + ' ' : '') + tr('Install ffmpeg on the server to enable transcoding, or open the channel in VLC.');
status(tr('Could not play: ' + msg), true, hint);
}
function url() {
if (opts.src) return opts.src;
var q = [];
if (profile !== 'pass') q.push('profile=' + profile);
if (opts.share) q.push('share=' + encodeURIComponent(opts.share));
if (opts.token) q.push('token=' + encodeURIComponent(opts.token));
return '/hls/' + opts.channelId + '/index.m3u8' + (q.length ? '?' + q.join('&') : '');
}
function nextProfile() {
if (!auto || opts.src) return false;
var i = fallbackOrder.indexOf(profile);
if (i < 0 || i + 1 >= fallbackOrder.length) return false;
profile = fallbackOrder[i + 1];
return true;
}
function teardown() {
if (hls) { try { hls.destroy(); } catch (e) {} hls = null; }
video.removeAttribute('src');
try { video.load(); } catch (e) {}
}
function start() {
teardown();
if (destroyed) return;
if (opts.onProfile) opts.onProfile(profile);
status(opts.live === false ? 'Loading recording…' : 'Tuning and buffering…');
var src = url();
if (window.Hls && window.Hls.isSupported()) {
hls = new window.Hls({
liveSyncDurationCount: 2,
liveMaxLatencyDurationCount: 6,
manifestLoadingTimeOut: 30000,
manifestLoadingMaxRetry: 3,
levelLoadingTimeOut: 20000,
fragLoadingTimeOut: 30000,
enableWorker: true,
backBufferLength: 30
});
hls.on(window.Hls.Events.MANIFEST_PARSED, function () {
var p = video.play();
if (p && p.catch) p.catch(function () { status('Click ▶ to play', true); });
});
hls.on(window.Hls.Events.FRAG_BUFFERED, function () { status(null); retries = 0; });
hls.on(window.Hls.Events.ERROR, function (_e, data) {
if (!data.fatal) return;
var codecProblem = data.type === window.Hls.ErrorTypes.MEDIA_ERROR ||
/codec|incompatible|bufferAddCodec|addSourceBuffer/i.test(String(data.details) + ' ' + String(data.reason || ''));
if (codecProblem && nextProfile()) {
status('Browser lacks the codec – switching to the “' + profile + '” profile…');
setTimeout(start, 300);
return;
}
if (data.type === window.Hls.ErrorTypes.MEDIA_ERROR && retries < 2) {
retries++;
hls.recoverMediaError();
return;
}
if (data.type === window.Hls.ErrorTypes.NETWORK_ERROR && retries < 4) {
retries++;
status('Connection problem – retrying (' + retries + ')…');
setTimeout(start, 2000);
return;
}
var msg = (data.response && data.response.data) || data.details || 'playback error';
failed(String(msg));
});
hls.loadSource(src);
hls.attachMedia(video);
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = src;
video.addEventListener('playing', function () { status(null); }, { once: true });
video.addEventListener('error', function () {
if (nextProfile()) { start(); return; }
failed('the stream');
}, { once: true });
var p = video.play();
if (p && p.catch) p.catch(function () {});
} else {
status('This browser does not support HLS', true);
}
}
video.addEventListener('waiting', function () { if (!overlay.classList.contains('err')) status('Buffering…'); });
video.addEventListener('playing', function () { status(null); });
start();
return {
video: video,
get profile() { return profile; },
setProfile: function (p) { auto = p === 'auto'; profile = auto ? pickProfile(opts.video, opts.audio) : p; start(); },
destroy: function () { destroyed = true; teardown(); container.innerHTML = ''; }
};
}
window.SDVB = { createPlayer: create, pickProfile: pickProfile, codecSupported: supported, explain: explain };
// Public page /watch/<token>
document.addEventListener('DOMContentLoaded', function () {
if (!document.body.classList.contains('watch')) return;
var box = document.getElementById('player');
if (!box) return;
create(box, {
channelId: box.getAttribute('data-channel'),
share: box.getAttribute('data-share'),
video: box.getAttribute('data-video'),
audio: (box.getAttribute('data-audio') || '').split('|').filter(Boolean),
transcode: box.getAttribute('data-transcode') !== '0',
profile: 'auto'
});
});
})();
+1559
View File
File diff suppressed because it is too large. Load diff
+28
View File
@@ -0,0 +1,28 @@
Copyright (c) 2017 Dailymotion (http://www.dailymotion.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
src/remux/mp4-generator.js and src/demux/exp-golomb.ts implementation in this project
are derived from the HLS library for video.js (https://github.com/videojs/videojs-contrib-hls)
That work is also covered by the Apache 2 License, following copyright:
Copyright (c) 2013-2015 Brightcove
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 OR COPYRIGHT HOLDERS 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.
+4
View File
@@ -0,0 +1,4 @@
!function e(t){var r,i;r=this,i=function(){"use strict";function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function i(e,t,r,i,n,a,s){try{var o=e[a](s),l=o.value}catch(e){return void r(e)}o.done?t(l):Promise.resolve(l).then(i,n)}function n(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,y(i.key),i)}}function a(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function s(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=function(e,t){if(e){if("string"==typeof e)return r(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,t):void 0}}(e))||t){i&&(e=i);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function o(e,t,r){return(t=y(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},l.apply(null,arguments)}function u(e){return u=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},u(e)}function d(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,p(e,t)}function h(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(h=function(){return!!e})()}function f(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function c(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?f(Object(r),!0).forEach((function(t){o(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):f(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function g(e,t){if(null==e)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(-1!==t.indexOf(i))continue;r[i]=e[i]}return r}function v(){
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
var e,t,r="function"==typeof Symbol?Symbol:{},i=r.iterator||"@@iterator",n=r.toStringTag||"@@toStringTag";function a(r,i,n,a){var l=i&&i.prototype instanceof o?i:o,u=Object.create(l.prototype);return m(u,"_invoke",function(r,i,n){var a,o,l,u=0,d=n||[],h=!1,f={p:0,n:0,v:e,a:c,f:c.bind(e,4),d:function(t,r){return a=t,o=0,l=e,f.n=r,s}};function c(r,i){for(o=r,l=i,t=0;!h&&u&&!n&&t<d.length;t++){var n,a=d[t],c=f.p,g=a[2];r>3?(n=g===i)&&(l=a[(o=a[4])?5:(o=3,3)],a[4]=a[5]=e):a[0]<=c&&((n=r<2&&c<a[1])?(o=0,f.v=i,f.n=a[1]):c<g&&(n=r<3||a[0]>i||i>g)&&(a[4]=r,a[5]=i,f.n=g,o=0))}if(n||r>1)return s;throw h=!0,i}return function(n,d,g){if(u>1)throw TypeError("Generator is already running");for(h&&1===d&&c(d,g),o=d,l=g;(t=o<2?e:l)||!h;){a||(o?o<3?(o>1&&(f.n=-1),c(o,l)):f.n=l:f.v=l);try{if(u=2,a){if(o||(n="next"),t=a[n]){if(!(t=t.call(a,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,o<2&&(o=0)}else 1===o&&(t=a.return)&&t.call(a),o<2&&(l=TypeError("The iterator does not provide a '"+n+"' method"),o=1);a=e}else if((t=(h=f.n<0)?l:r.call(i,f))!==s)break}catch(t){a=e,o=1,l=t}finally{u=1}}return{value:t,done:h}}}(r,n,a),!0),u}var s={};function o(){}function l(){}function u(){}t=Object.getPrototypeOf;var d=[][i]?t(t([][i]())):(m(t={},i,(function(){return this})),t),h=u.prototype=o.prototype=Object.create(d);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,m(e,n,"GeneratorFunction")),e.prototype=Object.create(h),e}return l.prototype=u,m(h,"constructor",u),m(u,"constructor",l),l.displayName="GeneratorFunction",m(u,n,"GeneratorFunction"),m(h),m(h,n,"Generator"),m(h,i,(function(){return this})),m(h,"toString",(function(){return"[object Generator]"})),(v=function(){return{w:a,m:f}})()}function m(e,t,r,i){var n=Object.defineProperty;try{n({},"",{})}catch(e){n=0}m=function(e,t,r,i){function a(t,r){m(e,t,(function(e){return this._invoke(t,r,e)}))}t?n?n(e,t,{value:r,enumerable:!i,configurable:!i,writable:!i}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},m(e,t,r,i)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function y(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function E(e){var t="function"==typeof Map?new Map:void 0;return E=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var n=new(e.bind.apply(e,i));return r&&p(n,r.prototype),n}(e,arguments,u(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),p(r,e)},E(e)}function T(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}var S="utf-16",A="utf-16be",I="utf-16le",L="utf-8";function R(e,t){if(e<0)return-R(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){var i=Math.floor(e*r);return(i%2==0?i:i+1)/r}return Math.round(e*r)/r}function b(){try{return crypto.randomUUID()}catch(i){try{var e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(e){var r=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=(r+16*Math.random())%16|0;return r=Math.floor(r/16),("x"==e?t:3&t|8).toString(16)}))}}}function k(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var D,P,_={exports:{}},C=(D||(D=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function n(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function a(e,t,i,a,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new n(i,a||e,s),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,n=[];if(0===this._eventsCount)return n;for(i in e=this._events)t.call(e,i)&&n.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(e)):n},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var n=0,a=i.length,s=new Array(a);n<a;n++)s[n]=i[n].fn;retLine truncated
//# sourceMappingURL=hls.min.js.map