0.1.17
build / test (push) Waiting to run

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-17 16:50:28 +01:00
1 parent 528017b0e6
commit 9e65aa0103
27 files changed
+1050 -98

No files matched your search

Generated
+2 -1
View File
@@ -1894,7 +1894,7 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]] [[package]]
name = "simply-dvb" name = "simply-dvb"
version = "0.1.10" version = "0.1.17"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"argon2", "argon2",
@@ -1911,6 +1911,7 @@ dependencies = [
"http-body-util", "http-body-util",
"ipnet", "ipnet",
"libc", "libc",
"log",
"quick-xml", "quick-xml",
"regex", "regex",
"reqwest", "reqwest",
+2 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "simply-dvb" name = "simply-dvb"
version = "0.1.10" version = "0.1.17"
edition = "2021" edition = "2021"
rust-version = "1.85" rust-version = "1.85"
description = "simply-dvb - lightweight DVB-T/T2/C server: scanning, HLS, M3U, EPG/XMLTV, recording and a web panel" description = "simply-dvb - lightweight DVB-T/T2/C server: scanning, HLS, M3U, EPG/XMLTV, recording and a web panel"
@@ -46,6 +46,7 @@ tokio = { version = "1.45", features = ["macros", "rt-multi-thread", "net", "sig
tokio-stream = { version = "0.1", features = ["sync"] } tokio-stream = { version = "0.1", features = ["sync"] }
tokio-util = { version = "0.7", features = ["io"] } tokio-util = { version = "0.7", features = ["io"] }
tracing = "0.1" tracing = "0.1"
log = "0.4"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt", "registry"] } tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt", "registry"] }
unicode-normalization = "0.1" unicode-normalization = "0.1"
sysinfo = { version = "0.36.1", default-features = false, features = ["system", "component"] } sysinfo = { version = "0.36.1", default-features = false, features = ["system", "component"] }
+5
View File
@@ -39,6 +39,7 @@ Tested with **Silicon Labs Si2168** (DVB-T/T2/C) cards + Si2157 tuner.
| 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** | | 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 | | 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, **application traffic** per protocol (MPEG-TS, HLS, HTSP) and from the tuners, clients/HLS sessions, temperature, load; per tuner: mux bitrate, signal strength (%/dBm), SNR, uncorrected blocks, **BER**, **stream errors (CC/TEI)**, lock stages (signal/carrier/FEC/sync/lock), transmission parameters, PIDs/stuffing and **hardware details** (bus, driver, product, USB speed, frequency range, capabilities). **Antenna meter** (*Tuners → Antenna meter*): big live strength/SNR readout with a quality verdict and optional beeps for aligning the antenna from a phone. `/metrics` in Prometheus format. Active clients with protocol, device, address, access, duration and rate | | Monitoring | Live charts on the overview (15 min history): CPU (system and process), memory, process RSS, streaming throughput, **application traffic** per protocol (MPEG-TS, HLS, HTSP) and from the tuners, clients/HLS sessions, temperature, load; per tuner: mux bitrate, signal strength (%/dBm), SNR, uncorrected blocks, **BER**, **stream errors (CC/TEI)**, lock stages (signal/carrier/FEC/sync/lock), transmission parameters, PIDs/stuffing and **hardware details** (bus, driver, product, USB speed, frequency range, capabilities). **Antenna meter** (*Tuners → Antenna meter*): big live strength/SNR readout with a quality verdict and optional beeps for aligning the antenna from a phone. `/metrics` in Prometheus format. Active clients with protocol, device, address, access, duration and rate |
| TV app pairing | The [simply-tv](../simply-tv) Android TV app shows a QR code; scanning it opens *Pair a TV* in the panel – after confirming, the server creates an access token for the TV and hands it over (`POST /api/pair/start`, `GET /api/pair/poll`, codes expire after 10 min) |
| Statistics | Viewing history: watch time, most watched channels, viewers, devices, protocols, time of day and per day (24 h / 7 / 30 days / year) | | Statistics | Viewing history: watch time, most watched channels, viewers, devices, protocols, time of day and per day (24 h / 7 / 30 days / year) |
| 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* | | 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; full database copy from the panel or `simply-dvb db backup` | | Backup | Configuration export/import (muxes, services, channels, rules, tokens, settings) as JSON; full database copy from the panel or `simply-dvb db backup` |
@@ -269,6 +270,10 @@ The interface, server messages and logs are in English; translations are JSON fi
* Signal strength is reported by the Si2157 tuner in dBm, SNR by the Si2168 in dB. * 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. * DVB-T2 with multiple PLPs: set the PLP when adding a mux manually.
## TV app (simply-tv)
The Android TV app [simply-tv](../simply-tv) pairs with a QR code: on the TV enter the server address and choose *Pair with QR code*, scan the code with a phone, sign in to the panel and confirm – an access token is created and handed to the TV (also possible by typing the 6-character code in *Access → Pair a TV*). Endpoints: `POST /api/pair/start`, `GET /api/pair/poll` (TV), `GET /api/pair/{code}`, `POST /api/pair/{code}/confirm` (panel). `/api/status/inputs?channel=<id>` returns the tuner carrying a channel with signal, SNR, BER and error counters.
## Command line tools ## Command line tools
Run them on the server (as root or `sudo -u simply-dvb`; files created as root get the data Run them on the server (as root or `sudo -u simply-dvb`; files created as root get the data
+5
View File
@@ -40,6 +40,7 @@ Testowany z kartami na **Silicon Labs Si2168** (DVB-T/T2/C) + tuner Si2157.
| 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 | | 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 | | 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, **ruch aplikacji** wg protokołu (MPEG-TS, HLS, HTSP) i z tunerów, klienci/sesje HLS, temperatura, obciążenie; dla tunera: przepływność, siła sygnału (%/dBm), SNR, bloki z błędami, **BER**, **błędy strumienia (CC/TEI)**, etapy synchronizacji (sygnał/nośna/FEC/sync/lock), parametry transmisji, PID-y/wypełnienie i **dane sprzętu** (magistrala, sterownik, produkt, prędkość USB, zakres częstotliwości, możliwości). **Miernik anteny** (*Tunery → Miernik anteny*): duży odczyt siły/SNR na żywo z oceną jakości i opcjonalnym dźwiękiem – do ustawiania anteny z telefonem w ręku. `/metrics` w formacie Prometheus | | Monitoring | Wykresy na żywo w przeglądzie (historia 15 min): CPU (system i proces), pamięć, RSS procesu, przepustowość strumieni, **ruch aplikacji** wg protokołu (MPEG-TS, HLS, HTSP) i z tunerów, klienci/sesje HLS, temperatura, obciążenie; dla tunera: przepływność, siła sygnału (%/dBm), SNR, bloki z błędami, **BER**, **błędy strumienia (CC/TEI)**, etapy synchronizacji (sygnał/nośna/FEC/sync/lock), parametry transmisji, PID-y/wypełnienie i **dane sprzętu** (magistrala, sterownik, produkt, prędkość USB, zakres częstotliwości, możliwości). **Miernik anteny** (*Tunery → Miernik anteny*): duży odczyt siły/SNR na żywo z oceną jakości i opcjonalnym dźwiękiem – do ustawiania anteny z telefonem w ręku. `/metrics` w formacie Prometheus |
| Parowanie aplikacji TV | Aplikacja [simply-tv](../simply-tv) na Android TV pokazuje kod QR; po zeskanowaniu otwiera się *Sparuj telewizor* w panelu – po zatwierdzeniu serwer tworzy token dostępu i przekazuje go telewizorowi (`POST /api/pair/start`, `GET /api/pair/poll`, kody wygasają po 10 min) |
| Statystyki | Historia oglądania: czas oglądania, najczęściej oglądane kanały, widzowie, urządzenia, protokoły, pora dnia i dni (24 h / 7 / 30 dni / rok) | | Statystyki | Historia oglądania: czas oglądania, najczęściej oglądane kanały, widzowie, urządzenia, protokoły, pora dnia i dni (24 h / 7 / 30 dni / rok) |
| Kopia zapasowa | Eksport/import konfiguracji (multipleksy, usługi, kanały, reguły, tokeny, ustawienia) jako JSON; pełna kopia bazy z panelu lub `simply-dvb db backup` | | Kopia zapasowa | Eksport/import konfiguracji (multipleksy, usługi, kanały, reguły, tokeny, ustawienia) jako JSON; pełna kopia bazy z panelu lub `simply-dvb db backup` |
| 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 **profilu użytkownika** (działają na każdym urządzeniu). **Ulubione kanały** (★, własny filtr i M3U), **przypomnienia o audycjach** (powiadomienie 2 min przed startem), lista zalogowanych urządzeń z wylogowaniem zdalnym, widok na telefon z dolnym paskiem, instalacja jako aplikacja (PWA, HTTPS) | | 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 **profilu użytkownika** (działają na każdym urządzeniu). **Ulubione kanały** (★, własny filtr i M3U), **przypomnienia o audycjach** (powiadomienie 2 min przed startem), lista zalogowanych urządzeń z wylogowaniem zdalnym, widok na telefon z dolnym paskiem, instalacja jako aplikacja (PWA, HTTPS) |
@@ -265,6 +266,10 @@ Interfejs, komunikaty serwera i logi są po angielsku; tłumaczenia to pliki JSO
* Siła sygnału jest raportowana przez tuner Si2157 w dBm, SNR przez Si2168 w dB. * 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. * DVB-T2 z wieloma PLP: PLP ustawisz przy ręcznym dodawaniu multipleksu.
## Aplikacja TV (simply-tv)
Aplikacja na Android TV [simply-tv](../simply-tv) paruje się kodem QR: na telewizorze wpisz adres serwera i wybierz *Paruj kodem QR*, zeskanuj kod telefonem, zaloguj się do panelu i zatwierdź – serwer tworzy token dostępu i przekazuje go telewizorowi (można też wpisać 6-znakowy kod w *Dostęp → Sparuj telewizor*). `/api/status/inputs?channel=<id>` zwraca tuner obsługujący kanał z siłą sygnału, SNR, BER i licznikami błędów.
## Narzędzia wiersza poleceń ## Narzędzia wiersza poleceń
Uruchamiaj je na serwerze (jako root lub `sudo -u simply-dvb`; pliki tworzone jako root dostają Uruchamiaj je na serwerze (jako root lub `sudo -u simply-dvb`; pliki tworzone jako root dostają
+21 -1
View File
@@ -709,7 +709,27 @@
"Monitoring (Prometheus)": "Monitoring (Prometheus)", "Monitoring (Prometheus)": "Monitoring (Prometheus)",
"Open": "Open", "Open": "Open",
"Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.": "Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.", "Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.": "Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.",
"Browsers and apps signed in to the panel. Signing a device out ends its session immediately.": "Browsers and apps signed in to the panel. Signing a device out ends its session immediately." "Browsers and apps signed in to the panel. Signing a device out ends its session immediately.": "Browsers and apps signed in to the panel. Signing a device out ends its session immediately.",
"background scan": "background scan",
"Background scan of saved muxes while the tuner is free – stops at once when someone watches.": "Background scan of saved muxes while the tuner is free – stops at once when someone watches.",
"Pair a TV": "Pair a TV",
"The simply-tv app on the TV shows a QR code and a 6-character code. Confirming creates an access token for the TV – nothing has to be typed on the remote.": "The simply-tv app on the TV shows a QR code and a 6-character code. Confirming creates an access token for the TV – nothing has to be typed on the remote.",
"Code shown on the TV": "Code shown on the TV",
"Continue": "Continue",
"Only an administrator can pair devices.": "Only an administrator can pair devices.",
"This TV is already paired – it finishes the setup by itself.": "This TV is already paired – it finishes the setup by itself.",
"Code": "Code",
"Token name": "Token name",
"Allowed from (optional)": "Allowed from (optional)",
"Check that the code matches the one on the TV screen. The token can be disabled or deleted any time in Access.": "Check that the code matches the one on the TV screen. The token can be disabled or deleted any time in Access.",
"Pair this TV": "Pair this TV",
"Paired. The TV loads channels and the guide now – you can close this page.": "Paired. The TV loads channels and the guide now – you can close this page.",
"pairing code expired or unknown": "pairing code expired or unknown",
"this device is already paired": "this device is already paired",
"Driver timing": "Driver timing",
"stats": "stats",
"max gap": "max gap",
"Time of the last signal statistics read from the demodulator and the longest pause between reads of the stream. High values point to a slow driver (I2C) and can make playback stutter.": "Time of the last signal statistics read from the demodulator and the longest pause between reads of the stream. High values point to a slow driver (I2C) and can make playback stutter."
}, },
"patterns": [] "patterns": []
} }
+21 -1
View File
@@ -709,7 +709,27 @@
"Monitoring (Prometheus)": "Monitoring (Prometheus)", "Monitoring (Prometheus)": "Monitoring (Prometheus)",
"Open": "Otwórz", "Open": "Otwórz",
"Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.": "Metryki dla Prometheus/Grafana: tunery (sygnał, SNR, błędy, przepływność), klienci, ruch, nagrania i proces. Dodaj ten adres jako cel zbierania (scrape target).", "Metrics for Prometheus/Grafana: tuners (signal, SNR, errors, bitrate), clients, traffic, recordings and the process. Add this address as a scrape target.": "Metryki dla Prometheus/Grafana: tunery (sygnał, SNR, błędy, przepływność), klienci, ruch, nagrania i proces. Dodaj ten adres jako cel zbierania (scrape target).",
"Browsers and apps signed in to the panel. Signing a device out ends its session immediately.": "Przeglądarki i aplikacje zalogowane do panelu. Wylogowanie urządzenia od razu kończy jego sesję." "Browsers and apps signed in to the panel. Signing a device out ends its session immediately.": "Przeglądarki i aplikacje zalogowane do panelu. Wylogowanie urządzenia od razu kończy jego sesję.",
"background scan": "skan w tle",
"Background scan of saved muxes while the tuner is free – stops at once when someone watches.": "Skan zapisanych multipleksów w tle, gdy tuner jest wolny – przerywany natychmiast, gdy ktoś zaczyna oglądać.",
"Pair a TV": "Sparuj telewizor",
"The simply-tv app on the TV shows a QR code and a 6-character code. Confirming creates an access token for the TV – nothing has to be typed on the remote.": "Aplikacja simply-tv na telewizorze pokazuje kod QR i 6-znakowy kod. Zatwierdzenie tworzy token dostępu dla telewizora – nic nie trzeba wpisywać pilotem.",
"Code shown on the TV": "Kod widoczny na telewizorze",
"Continue": "Dalej",
"Only an administrator can pair devices.": "Tylko administrator może parować urządzenia.",
"This TV is already paired – it finishes the setup by itself.": "Ten telewizor jest już sparowany – sam dokończy konfigurację.",
"Code": "Kod",
"Token name": "Nazwa tokenu",
"Allowed from (optional)": "Dozwolony z (opcjonalnie)",
"Check that the code matches the one on the TV screen. The token can be disabled or deleted any time in Access.": "Sprawdź, czy kod zgadza się z tym na ekranie telewizora. Token możesz w każdej chwili wyłączyć lub usunąć w zakładce Dostęp.",
"Pair this TV": "Sparuj ten telewizor",
"Paired. The TV loads channels and the guide now – you can close this page.": "Sparowano. Telewizor wczytuje teraz kanały i program – możesz zamknąć tę stronę.",
"pairing code expired or unknown": "kod parowania wygasł lub jest nieznany",
"this device is already paired": "to urządzenie jest już sparowane",
"Driver timing": "Czasy sterownika",
"stats": "statystyki",
"max gap": "maks. przerwa",
"Time of the last signal statistics read from the demodulator and the longest pause between reads of the stream. High values point to a slow driver (I2C) and can make playback stutter.": "Czas ostatniego odczytu statystyk sygnału z demodulatora i najdłuższa przerwa między odczytami strumienia. Wysokie wartości wskazują na wolny sterownik (I2C) i mogą powodować przycinanie obrazu."
}, },
"patterns": [ "patterns": [
{ {
+5
View File
@@ -28,6 +28,8 @@ pub struct Options {
pub stream_port: Option<u16>, pub stream_port: Option<u16>,
/// HTSP port, if enabled. /// HTSP port, if enabled.
pub htsp_port: Option<u16>, pub htsp_port: Option<u16>,
/// Panel port (for links such as the TV pairing page).
pub panel_port: u16,
} }
#[derive(Default, Clone, serde::Serialize)] #[derive(Default, Clone, serde::Serialize)]
@@ -55,6 +57,8 @@ pub struct AppState {
pub epg_wakeup: Notify, pub epg_wakeup: Notify,
pub xmltv_wakeup: Notify, pub xmltv_wakeup: Notify,
pub rec_wakeup: Notify, pub rec_wakeup: Notify,
/// Bumped whenever any change is committed to the database (see `db::watch_changes`).
pub db_changed: tokio::sync::watch::Sender<u64>,
pub shutting_down: AtomicBool, pub shutting_down: AtomicBool,
pub stats: crate::stats::Stats, pub stats: crate::stats::Stats,
/// The separate stream port is bound (it may wait for tvheadend to release it). /// The separate stream port is bound (it may wait for tvheadend to release it).
@@ -138,6 +142,7 @@ impl AppState {
epg_wakeup: Notify::new(), epg_wakeup: Notify::new(),
xmltv_wakeup: Notify::new(), xmltv_wakeup: Notify::new(),
rec_wakeup: Notify::new(), rec_wakeup: Notify::new(),
db_changed: tokio::sync::watch::channel(0).0,
shutting_down: AtomicBool::new(false), shutting_down: AtomicBool::new(false),
stats: crate::stats::Stats::default(), stats: crate::stats::Stats::default(),
stream_port_active: AtomicBool::new(false), stream_port_active: AtomicBool::new(false),
+17
View File
@@ -194,7 +194,24 @@ async fn check_token(state: &State, t: &str, ip: IpAddr) -> Option<AccessToken>
if !ok { if !ok {
return None; return None;
} }
// "last used" is informational: write it at most once a minute per token
// (the TV app polls several endpoints every second)
let due = {
static SEEN: std::sync::OnceLock<
std::sync::Mutex<std::collections::HashMap<i64, Instant>>,
> = std::sync::OnceLock::new();
let mut m = SEEN.get_or_init(Default::default).lock().unwrap();
let due = m
.get(&tok.id)
.is_none_or(|t| t.elapsed() >= Duration::from_secs(60));
if due {
m.insert(tok.id, Instant::now());
}
due
};
if due {
let _ = state.db.touch_token(tok.id).await; let _ = state.db.touch_token(tok.id).await;
}
Some(tok) Some(tok)
} }
+123 -5
View File
@@ -6,7 +6,7 @@ use crate::ts::tables::PmtStream;
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous}; use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
use sqlx::{FromRow, SqlitePool}; use sqlx::{ConnectOptions, FromRow, SqlitePool};
use std::path::Path; use std::path::Path;
use std::str::FromStr; use std::str::FromStr;
@@ -27,6 +27,65 @@ pub struct Db {
pub pool: SqlitePool, pub pool: SqlitePool,
} }
/// Reports committed database changes: `PRAGMA data_version` on a separate connection
/// changes whenever another connection commits, whatever was written. Lets consumers
/// (HTSP async metadata) sleep while nothing changes instead of re-reading on a timer.
pub async fn watch_changes(db: Db, tx: tokio::sync::watch::Sender<u64>) {
use sqlx::Connection;
let opts = db.pool.connect_options();
loop {
let mut conn = match opts.connect().await {
Ok(c) => c,
Err(e) => {
tracing::warn!("database change watch: {e:#}");
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
continue;
}
};
let mut last: Option<i64> = None;
loop {
// In WAL mode the connection only notices other commits when it starts a
// read, so read something tiny first.
let probe = async {
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM sqlite_schema WHERE 0")
.fetch_one(&mut conn)
.await?;
sqlx::query_scalar::<_, i64>("PRAGMA data_version")
.fetch_one(&mut conn)
.await
};
match probe.await {
Ok(v) => {
if last.is_some_and(|l| l != v) {
tracing::debug!("database changed (data_version {v})");
tx.send_modify(|n| *n += 1);
}
last = Some(v);
}
Err(_) => {
// reconnect; report a change to be safe
tx.send_modify(|n| *n += 1);
let _ = conn.close().await;
break;
}
}
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}
}
}
/// Bumped whenever programme data changes, so EPG consumers (HTSP clients) only rebuild
/// their view when there is something new.
static EPG_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
pub fn epg_version() -> u64 {
EPG_VERSION.load(std::sync::atomic::Ordering::Relaxed)
}
fn epg_changed() {
EPG_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)] #[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct User { pub struct User {
pub id: i64, pub id: i64,
@@ -228,7 +287,13 @@ impl Db {
.journal_mode(SqliteJournalMode::Wal) .journal_mode(SqliteJournalMode::Wal)
.synchronous(SqliteSynchronous::Normal) .synchronous(SqliteSynchronous::Normal)
.foreign_keys(true) .foreign_keys(true)
.busy_timeout(std::time::Duration::from_secs(10)); .busy_timeout(std::time::Duration::from_secs(10))
// diagnostics: statements that keep the database busy show up in the log
.log_statements(log::LevelFilter::Trace)
.log_slow_statements(
log::LevelFilter::Warn,
std::time::Duration::from_millis(250),
);
let pool = SqlitePoolOptions::new() let pool = SqlitePoolOptions::new()
.max_connections(8) .max_connections(8)
.connect_with(opts) .connect_with(opts)
@@ -956,9 +1021,24 @@ impl Db {
n += r.rows_affected() as usize; n += r.rows_affected() as usize;
} }
tx.commit().await?; tx.commit().await?;
if n > 0 {
epg_changed();
}
Ok(n) Ok(n)
} }
/// (event id, channel id, start, stop) of programmes overlapping `from..to` – just
/// what is needed to find each channel's current and next programme.
pub async fn epg_slots(&self, from: i64, to: i64) -> Result<Vec<(i64, i64, i64, i64)>> {
Ok(sqlx::query_as(
"SELECT id, channel_id, start, stop FROM epg_events WHERE stop > ? AND start < ? ORDER BY channel_id, start",
)
.bind(from)
.bind(to)
.fetch_all(&self.pool)
.await?)
}
pub async fn epg_range( pub async fn epg_range(
&self, &self,
channel_id: Option<i64>, channel_id: Option<i64>,
@@ -996,12 +1076,50 @@ impl Db {
) )
} }
/// Removes finished programmes (older than `keep_past_secs`), programmes of channels
/// that no longer exist and ones absurdly far in the future, then lets SQLite tidy up
/// its statistics and give free pages back – the database never needs manual care.
pub async fn epg_cleanup(&self, keep_past_secs: i64) -> Result<u64> { pub async fn epg_cleanup(&self, keep_past_secs: i64) -> Result<u64> {
Ok(sqlx::query("DELETE FROM epg_events WHERE stop < ?") let n = now();
.bind(now() - keep_past_secs) let mut removed = sqlx::query("DELETE FROM epg_events WHERE stop < ? OR start > ?")
.bind(n - keep_past_secs)
.bind(n + 60 * 86_400)
.execute(&self.pool) .execute(&self.pool)
.await? .await?
.rows_affected()) .rows_affected();
removed +=
sqlx::query("DELETE FROM epg_events WHERE channel_id NOT IN (SELECT id FROM channels)")
.execute(&self.pool)
.await?
.rows_affected();
if removed > 0 {
epg_changed();
}
let _ = sqlx::query("PRAGMA optimize").execute(&self.pool).await;
// compact when more than a quarter of the file is free pages (and > 8 MiB)
let free: i64 = sqlx::query_scalar("PRAGMA freelist_count")
.fetch_one(&self.pool)
.await
.unwrap_or(0);
let total: i64 = sqlx::query_scalar("PRAGMA page_count")
.fetch_one(&self.pool)
.await
.unwrap_or(0);
let page: i64 = sqlx::query_scalar("PRAGMA page_size")
.fetch_one(&self.pool)
.await
.unwrap_or(4096);
if total > 0
&& free * 4 > total
&& free * page > (8 << 20)
&& sqlx::query("VACUUM").execute(&self.pool).await.is_ok()
{
tracing::info!("database compacted ({} MiB freed)", (free * page) >> 20);
}
if removed > 0 {
tracing::debug!(target: "epg", "EPG cleanup: {removed} old programmes removed");
}
Ok(removed)
} }
// ------------------------------------------------------------ recordings // ------------------------------------------------------------ recordings
+9 -1
View File
@@ -59,7 +59,15 @@ pub async fn writer_task(state: State, mut rx: mpsc::UnboundedReceiver<(i64, Vec
if out.is_empty() { if out.is_empty() {
continue; continue;
} }
match state.db.upsert_epg(&out, "ota").await { let began = Instant::now();
let res = state.db.upsert_epg(&out, "ota").await;
let ms = began.elapsed().as_millis();
if ms > 300 {
tracing::warn!("storing {} EPG events took {ms} ms", out.len());
} else {
tracing::debug!("stored {} EPG events ({ms} ms)", out.len());
}
match res {
Ok(n) => state.epg_status.lock().unwrap().ota_events_written += n as u64, Ok(n) => state.epg_status.lock().unwrap().ota_events_written += n as u64,
Err(e) => tracing::warn!("storing EPG: {e:#}"), Err(e) => tracing::warn!("storing EPG: {e:#}"),
} }
+52 -1
View File
@@ -24,6 +24,9 @@ pub struct HlsSession {
pub done: AtomicBool, pub done: AtomicBool,
pub started: Instant, pub started: Instant,
pub adapter: Mutex<String>, pub adapter: Mutex<String>,
/// Panel players watching (viewer id → last request). A session whose tracked viewers
/// all left ends right away instead of waiting for the idle timeout.
viewers: Mutex<HashMap<String, Instant>>,
} }
impl HlsSession { impl HlsSession {
@@ -31,6 +34,23 @@ impl HlsSession {
*self.last_access.lock().unwrap() = Instant::now(); *self.last_access.lock().unwrap() = Instant::now();
} }
pub fn see(&self, viewer: &str) {
self.viewers
.lock()
.unwrap()
.insert(viewer.to_string(), Instant::now());
}
/// Removes a viewer; true when it was the last one (the session can end now).
fn forget(&self, viewer: &str) -> bool {
let mut v = self.viewers.lock().unwrap();
v.remove(viewer).is_some() && v.is_empty()
}
fn expire(&self) {
*self.last_access.lock().unwrap() = Instant::now() - Duration::from_secs(86_400);
}
fn idle_for(&self) -> Duration { fn idle_for(&self) -> Duration {
self.last_access.lock().unwrap().elapsed() self.last_access.lock().unwrap().elapsed()
} }
@@ -128,12 +148,29 @@ impl HlsManager {
} }
/// Returns an existing session or starts a new one. /// Returns an existing session or starts a new one.
pub fn get_or_start(&self, state: &State, channel_id: i64, profile: &str) -> Arc<HlsSession> { pub fn get_or_start(
&self,
state: &State,
channel_id: i64,
profile: &str,
viewer: Option<&str>,
) -> Arc<HlsSession> {
let mut map = self.sessions.lock().unwrap(); let mut map = self.sessions.lock().unwrap();
let key = (channel_id, profile.to_string()); let key = (channel_id, profile.to_string());
if let Some(v) = viewer {
// the same player switched channel/profile: its other sessions end now
for (k, s) in map.iter() {
if *k != key && s.forget(v) {
s.expire();
}
}
}
if let Some(s) = map.get(&key) { if let Some(s) = map.get(&key) {
if !s.done.load(Ordering::Relaxed) { if !s.done.load(Ordering::Relaxed) {
s.touch(); s.touch();
if let Some(v) = viewer {
s.see(v);
}
return s.clone(); return s.clone();
} }
} }
@@ -147,7 +184,11 @@ impl HlsManager {
done: AtomicBool::new(false), done: AtomicBool::new(false),
started: Instant::now(), started: Instant::now(),
adapter: Mutex::new(String::new()), adapter: Mutex::new(String::new()),
viewers: Mutex::new(HashMap::new()),
}); });
if let Some(v) = viewer {
sess.see(v);
}
map.insert(key, sess.clone()); map.insert(key, sess.clone());
let st = state.clone(); let st = state.clone();
let s2 = sess.clone(); let s2 = sess.clone();
@@ -162,6 +203,16 @@ impl HlsManager {
sess sess
} }
/// A player stopped: sessions it was the last viewer of end now.
pub fn leave(&self, viewer: &str) {
for s in self.sessions.lock().unwrap().values() {
if s.forget(viewer) {
s.expire();
tracing::debug!("HLS channel {}: last viewer left", s.channel_id);
}
}
}
pub fn reap(&self) { pub fn reap(&self) {
self.sessions.lock().unwrap().retain(|_, s| { self.sessions.lock().unwrap().retain(|_, s| {
!s.done.load(Ordering::Relaxed) || s.idle_for() < Duration::from_secs(5) !s.done.load(Ordering::Relaxed) || s.idle_for() < Duration::from_secs(5)
+77 -25
View File
@@ -272,7 +272,7 @@ impl Session {
} }
"getChannel" => { "getChannel" => {
let id = m.get_i64("channelId").unwrap_or(0); let id = m.get_i64("channelId").unwrap_or(0);
let snap = Snapshot::load(&st, None).await?; let snap = Snapshot::load(&st).await?;
let c = snap let c = snap
.channels .channels
.iter() .iter()
@@ -734,10 +734,12 @@ struct Snapshot {
channels: Vec<Channel>, channels: Vec<Channel>,
services: HashMap<i64, crate::db::Service>, services: HashMap<i64, crate::db::Service>,
now_next: HashMap<i64, (Option<i64>, Option<i64>)>, now_next: HashMap<i64, (Option<i64>, Option<i64>)>,
/// When the next programme starts or ends (a channel's current / next changes then).
next_change: Option<i64>,
} }
impl Snapshot { impl Snapshot {
async fn load(st: &State, events: Option<&[EpgEvent]>) -> Result<Snapshot> { async fn load(st: &State) -> Result<Snapshot> {
let channels: Vec<Channel> = st let channels: Vec<Channel> = st
.db .db
.channels() .channels()
@@ -753,27 +755,23 @@ impl Snapshot {
.map(|s| (s.id, s)) .map(|s| (s.id, s))
.collect(); .collect();
let t = now(); let t = now();
let owned;
let evs = match events {
Some(e) => e,
None => {
owned = st.db.epg_range(None, t, t + 12 * 3600).await?;
&owned
}
};
let mut now_next: HashMap<i64, (Option<i64>, Option<i64>)> = HashMap::new(); let mut now_next: HashMap<i64, (Option<i64>, Option<i64>)> = HashMap::new();
for e in evs { let mut next_change: Option<i64> = None;
let entry = now_next.entry(e.channel_id).or_default(); for (id, channel_id, start, stop) in st.db.epg_slots(t, t + 12 * 3600).await? {
if e.start <= t && e.stop > t { let edge = if start > t { start } else { stop };
entry.0 = Some(e.id); next_change = Some(next_change.map_or(edge, |n| n.min(edge)));
} else if e.start > t && entry.1.is_none() { let entry = now_next.entry(channel_id).or_default();
entry.1 = Some(e.id); if start <= t && stop > t {
entry.0 = Some(id);
} else if start > t && entry.1.is_none() {
entry.1 = Some(id);
} }
} }
Ok(Snapshot { Ok(Snapshot {
channels, channels,
services, services,
now_next, now_next,
next_change,
}) })
} }
@@ -902,15 +900,18 @@ async fn metadata_task(
let mut events = HashMap::new(); let mut events = HashMap::new();
let mut first = true; let mut first = true;
let mut last_epg = Instant::now() - Duration::from_secs(3600); let mut last_epg = Instant::now() - Duration::from_secs(3600);
let mut epg_sent_ver = 0u64;
let mut changes = st.db_changed.subscribe();
loop { loop {
let t = now(); let t = now();
let horizon = max_time.unwrap_or(t + 7 * 86400).min(t + 14 * 86400); let built = Instant::now();
let evs = st // Channels (with their current / next programme), tags and recordings are rebuilt
.db // and compared when the database changed (at most every 30 s), when a programme
.epg_range(None, t - 3600, horizon) // starts or ends, and at once after this client's own changes. That only needs the
.await // next few hours of the guide. The whole guide is re-read only when it changed (at
.unwrap_or_default(); // most every 5 minutes) and hourly – with a client such as Kodi connected all the
let Ok(snap) = Snapshot::load(&st, Some(&evs)).await else { // time, reading 14 days of EPG every 15 s showed up as regular CPU spikes.
let Ok(snap) = Snapshot::load(&st).await else {
tokio::time::sleep(Duration::from_secs(5)).await; tokio::time::sleep(Duration::from_secs(5)).await;
continue; continue;
}; };
@@ -941,8 +942,21 @@ async fn metadata_task(
{ {
return; return;
} }
if epg && (first || last_epg.elapsed() >= Duration::from_secs(120)) { let ver = crate::db::epg_version();
let since = last_epg.elapsed();
if epg
&& (first
|| (ver != epg_sent_ver && since >= Duration::from_secs(300))
|| since >= Duration::from_secs(3600))
{
last_epg = Instant::now(); last_epg = Instant::now();
epg_sent_ver = ver;
let horizon = max_time.unwrap_or(t + 7 * 86400).min(t + 14 * 86400);
let evs = st
.db
.epg_range(None, t - 3600, horizon)
.await
.unwrap_or_default();
let enabled: std::collections::HashSet<i64> = let enabled: std::collections::HashSet<i64> =
snap.channels.iter().map(|c| c.id).collect(); snap.channels.iter().map(|c| c.id).collect();
let by_event: HashMap<(i64, i64), i64> = recs let by_event: HashMap<(i64, i64), i64> = recs
@@ -979,9 +993,47 @@ async fn metadata_task(
return; return;
} }
} }
// Sleep until something can have changed. Changes made through this connection
// (recordings…) wake the loop at once.
const MIN_GAP: Duration = Duration::from_secs(30);
let mut wait = Duration::from_secs(1800);
if let Some(at) = snap.next_change {
wait = wait.min(Duration::from_secs((at - now()).max(1) as u64));
}
if epg && crate::db::epg_version() != epg_sent_ver {
// guide changed but was sent less than 5 minutes ago: send it when due
wait = wait.min(
Duration::from_secs(300)
.saturating_sub(last_epg.elapsed())
.max(Duration::from_secs(1)),
);
}
if epg {
// hourly full EPG refresh (programmes that ended drop out of the window)
wait = wait.min(
Duration::from_secs(3600)
.saturating_sub(last_epg.elapsed())
.max(Duration::from_secs(1)),
);
}
tokio::select! { tokio::select! {
_ = tokio::time::sleep(Duration::from_secs(15)) => {} _ = tokio::time::sleep(wait) => {}
_ = refresh.notified() => {} _ = refresh.notified() => {}
r = changes.changed() => {
if r.is_err() {
// watcher gone: fall back to the plain timer
tokio::time::sleep(MIN_GAP).await;
}
// database writes come in bursts (EPG from the air while watching):
// rebuild at most every 30 s, unless this client changed something
let since = built.elapsed();
if since < MIN_GAP {
tokio::select! {
_ = tokio::time::sleep(MIN_GAP - since) => {}
_ = refresh.notified() => {}
}
}
}
} }
} }
} }
+1
View File
@@ -11,6 +11,7 @@ pub mod htsp;
pub mod icons; pub mod icons;
pub mod logbuf; pub mod logbuf;
pub mod m3u; pub mod m3u;
pub mod pairing;
pub mod pipeline; pub mod pipeline;
pub mod recorder; pub mod recorder;
pub mod scanjob; pub mod scanjob;
+6
View File
@@ -162,6 +162,7 @@ async fn run() -> Result<()> {
virtual_dirs: cli.virtual_dirs.clone(), virtual_dirs: cli.virtual_dirs.clone(),
stream_port: None, stream_port: None,
htsp_port: None, htsp_port: None,
panel_port: 9980,
}; };
let default_listen = let default_listen =
std::env::var("SIMPLY_DVB_LISTEN").unwrap_or_else(|_| "0.0.0.0:9980".into()); std::env::var("SIMPLY_DVB_LISTEN").unwrap_or_else(|_| "0.0.0.0:9980".into());
@@ -210,6 +211,7 @@ async fn run() -> Result<()> {
let htsp = optional(&htsp_listen, "htsp-listen")?; let htsp = optional(&htsp_listen, "htsp-listen")?;
opts.stream_port = stream.map(|a| a.port()); opts.stream_port = stream.map(|a| a.port());
opts.htsp_port = htsp.map(|a| a.port()); opts.htsp_port = htsp.map(|a| a.port());
opts.panel_port = listen.port();
serve(opts, listen, stream, htsp).await serve(opts, listen, stream, htsp).await
} }
Cmd::Db { Cmd::Db {
@@ -491,6 +493,10 @@ async fn serve(
tokio::spawn(epg::grabber_task(state.clone())); tokio::spawn(epg::grabber_task(state.clone()));
tokio::spawn(epg::xmltv_task(state.clone())); tokio::spawn(epg::xmltv_task(state.clone()));
tokio::spawn(recorder::scheduler_task(state.clone())); tokio::spawn(recorder::scheduler_task(state.clone()));
tokio::spawn(simply_dvb::db::watch_changes(
state.db.clone(),
state.db_changed.clone(),
));
tokio::spawn(simply_dvb::stats::sampler_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::scanjob::idle_scan_task(state.clone()));
tokio::spawn(simply_dvb::acl::resolver_task(state.clone())); tokio::spawn(simply_dvb::acl::resolver_task(state.clone()));
+157
View File
@@ -0,0 +1,157 @@
//! Pairing a TV app with a QR code instead of typing an access token.
//!
//! 1. The TV app calls `POST /api/pair/start` (stream or panel port, no login) and shows a QR
//! code with the panel link `…/#/pair/<CODE>` plus the code itself.
//! 2. Someone scans it with a phone, signs in to the panel and confirms: the server creates
//! an access token for the device.
//! 3. The TV app polls `GET /api/pair/poll?secret=…` and receives the token and ports once.
//!
//! The 6-character code only works for a signed-in administrator; the TV identifies itself
//! with a long secret that never leaves the TV. Requests expire after 10 minutes.
use crate::auth::random_token;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
pub const TTL: Duration = Duration::from_secs(600);
const MAX_PENDING: usize = 20;
const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
#[derive(Clone, Debug)]
pub struct Pairing {
pub code: String,
pub secret: String,
/// Device name the TV app reported (e.g. "Sony BRAVIA VH1").
pub device: String,
pub ip: String,
pub created: Instant,
pub created_unix: i64,
/// Set when an administrator confirmed: (token, token name).
pub token: Option<(String, String)>,
}
fn store() -> &'static Mutex<HashMap<String, Pairing>> {
static S: OnceLock<Mutex<HashMap<String, Pairing>>> = OnceLock::new();
S.get_or_init(Default::default)
}
fn purge(m: &mut HashMap<String, Pairing>) {
m.retain(|_, p| p.created.elapsed() < TTL);
}
fn new_code() -> String {
let mut b = [0u8; 6];
getrandom::fill(&mut b).expect("getrandom");
b.iter()
.map(|x| ALPHABET[*x as usize % ALPHABET.len()] as char)
.collect()
}
/// Starts a pairing request; None when too many are waiting.
pub fn start(device: &str, ip: &str) -> Option<Pairing> {
let mut m = store().lock().unwrap();
purge(&mut m);
if m.len() >= MAX_PENDING || m.values().filter(|p| p.ip == ip).count() >= 3 {
return None;
}
let mut code = new_code();
while m.contains_key(&code) {
code = new_code();
}
let device: String = device
.chars()
.filter(|c| !c.is_control())
.take(60)
.collect::<String>()
.trim()
.to_string();
let p = Pairing {
code: code.clone(),
secret: random_token(24),
device: if device.is_empty() {
"TV".into()
} else {
device
},
ip: ip.to_string(),
created: Instant::now(),
created_unix: crate::db::now(),
token: None,
};
m.insert(code, p.clone());
Some(p)
}
/// Normalizes what a user typed (lower case, spaces, dashes).
pub fn normalize(code: &str) -> String {
code.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_uppercase())
.collect()
}
pub fn get(code: &str) -> Option<Pairing> {
let mut m = store().lock().unwrap();
purge(&mut m);
m.get(&normalize(code)).cloned()
}
/// Attaches the created token to a waiting request.
pub fn confirm(code: &str, token: String, name: String) -> bool {
let mut m = store().lock().unwrap();
purge(&mut m);
match m.get_mut(&normalize(code)) {
Some(p) if p.token.is_none() => {
p.token = Some((token, name));
true
}
_ => false,
}
}
pub enum Poll {
Unknown,
Pending,
Done { token: String, name: String },
}
/// The TV asks whether its request was confirmed; a confirmed request is handed out once.
pub fn poll(secret: &str) -> Poll {
let mut m = store().lock().unwrap();
purge(&mut m);
let Some(code) = m
.iter()
.find(|(_, p)| p.secret.len() == secret.len() && p.secret == secret)
.map(|(c, _)| c.clone())
else {
return Poll::Unknown;
};
if m[&code].token.is_none() {
return Poll::Pending;
}
let p = m.remove(&code).unwrap();
let (token, name) = p.token.unwrap();
Poll::Done { token, name }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pairing_flow() {
let p = start("Sony BRAVIA\n", "10.0.0.5").unwrap();
assert_eq!(p.code.len(), 6);
assert_eq!(p.device, "Sony BRAVIA");
assert!(matches!(poll(&p.secret), Poll::Pending));
let typed = format!("{}-{}", &p.code[..3], p.code[3..].to_lowercase());
assert!(get(&typed).is_some());
assert!(confirm(&typed, "tok".into(), "TV".into()));
assert!(!confirm(&p.code, "x".into(), "y".into()));
assert!(matches!(poll(&p.secret), Poll::Done { ref token, .. } if token == "tok"));
// handed out only once
assert!(matches!(poll(&p.secret), Poll::Unknown));
assert!(matches!(poll("nope"), Poll::Unknown));
}
}
+23 -2
View File
@@ -237,6 +237,24 @@ pub fn shell_split(s: &str) -> Vec<String> {
out out
} }
/// PAT, PMT, PCR and elementary streams of a service as last seen in its PMT – the same
/// set (sorted) that [`ServiceFilter::wanted_pids`] produces from a matching PMT.
fn initial_pids(svc: &crate::db::Service) -> Vec<u16> {
let pmt = svc.pmt_pid as u16;
let mut v = vec![0u16, pmt];
if let Ok(streams) = serde_json::from_str::<Vec<crate::ts::tables::PmtStream>>(&svc.streams) {
if !streams.is_empty() {
if (0..0x2000).contains(&svc.pcr_pid) {
v.push(svc.pcr_pid as u16);
}
v.extend(streams.iter().map(|s| s.pid));
}
}
v.sort_unstable();
v.dedup();
v
}
/// Opens the MPEG-TS stream of the selected channel. /// Opens the MPEG-TS stream of the selected channel.
pub async fn open_service( pub async fn open_service(
state: &State, state: &State,
@@ -258,10 +276,13 @@ pub async fn open_service(
} }
let source = resolve(state, channel_id).await?; let source = resolve(state, channel_id).await?;
let pmt_pid = source.service.pmt_pid as u16; let pmt_pid = source.service.pmt_pid as u16;
// PAT + PMT until the PMT names the elementary streams (see `follow_pids`) // Declare the PIDs known from the scan right away. Adding PIDs to a running demux
// filter later (once the PMT arrives) makes some tuner bridges drop a few packets,
// which showed up as dropped frames 2–3 s into playback. The PMT still corrects
// the list if the broadcaster changed it (see `PidFollower`).
let mut sub = state let mut sub = state
.tuners .tuners
.subscribe_pids(&source.mux, prio, Some(vec![0, pmt_pid])) .subscribe_pids(&source.mux, prio, Some(initial_pids(&source.service)))
.await?; .await?;
let adapter = sub.adapter.clone(); let adapter = sub.adapter.clone();
let (tx, rx) = mpsc::channel::<Bytes>(512); let (tx, rx) = mpsc::channel::<Bytes>(512);
+79 -16
View File
@@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::{Duration, Instant};
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
#[derive(Debug, Clone, Serialize, Deserialize, Default)] #[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -46,6 +46,13 @@ pub fn sanitize(s: &str) -> String {
} }
/// Recording scheduler loop. /// Recording scheduler loop.
///
/// Sleeps until the next recording is due instead of polling: it wakes at the start
/// (minus pre-padding) of the next scheduled recording, at once when recordings or rules
/// change (`rec_wakeup`: panel, TV app, HTSP clients), and at least every 5 minutes as a
/// safety net (clock changes, suspend). Recording rules run when the guide changed (at
/// most once a minute, as before) and at least every 15 minutes, because the 48-hour
/// look-ahead window moves with time.
pub async fn scheduler_task(state: State) { pub async fn scheduler_task(state: State) {
// recordings interrupted by a restart // recordings interrupted by a restart
if let Ok(list) = state.db.recordings_by_status("recording").await { if let Ok(list) = state.db.recordings_by_status("recording").await {
@@ -53,26 +60,70 @@ pub async fn scheduler_task(state: State) {
let _ = state.db.set_recording_status(r.id, "scheduled", "").await; let _ = state.db.set_recording_status(r.id, "scheduled", "").await;
} }
} }
let mut n: u64 = 0; const RULES_MIN_GAP: Duration = Duration::from_secs(60);
const RULES_MAX_GAP: Duration = Duration::from_secs(15 * 60);
const SAFETY_WAKE: Duration = Duration::from_secs(300);
const RETENTION_EVERY: Duration = Duration::from_secs(3600);
let mut rules_ran: Option<Instant> = None;
let mut rules_epg = 0u64;
let mut rules_exist = true;
// first cleanup shortly after start, as before
let mut retention_ran = Instant::now() + Duration::from_secs(25) - RETENTION_EVERY;
let mut woken = false;
loop { loop {
if n % 12 == 0 { let ver = crate::db::epg_version();
if let Err(e) = run_autorec(&state).await { let rules_due = match rules_ran {
tracing::warn!("recording rules: {e:#}"); None => true,
Some(at) => {
woken
|| at.elapsed() >= RULES_MAX_GAP
|| (ver != rules_epg && at.elapsed() >= RULES_MIN_GAP)
} }
};
if rules_due {
match run_autorec(&state).await {
Ok((_, n)) => rules_exist = n > 0,
Err(e) => tracing::warn!("recording rules: {e:#}"),
} }
if n % 720 == 5 { rules_ran = Some(Instant::now());
rules_epg = ver;
}
if retention_ran.elapsed() >= RETENTION_EVERY {
retention_ran = Instant::now();
if let Err(e) = retention(&state).await { if let Err(e) = retention(&state).await {
tracing::warn!("recording cleanup: {e:#}"); tracing::warn!("recording cleanup: {e:#}");
} }
} }
if let Err(e) = tick(&state).await { let next = match tick(&state).await {
Ok(n) => n,
Err(e) => {
tracing::warn!("recording scheduler: {e:#}"); tracing::warn!("recording scheduler: {e:#}");
Some(now() + 5)
} }
n += 1; };
tokio::select! { // how long to sleep
_ = tokio::time::sleep(Duration::from_secs(5)) => {} let mut wait = SAFETY_WAKE;
_ = state.rec_wakeup.notified() => {} if let Some(at) = next {
wait = wait.min(Duration::from_secs((at - now()).max(1) as u64));
} }
if rules_exist {
// pick up new guide data for the rules within a minute, like before
let since = rules_ran.map(|t| t.elapsed()).unwrap_or_default();
wait = wait.min(
RULES_MIN_GAP
.saturating_sub(since)
.max(Duration::from_secs(1)),
);
wait = wait.min(
RULES_MAX_GAP
.saturating_sub(since)
.max(Duration::from_secs(1)),
);
}
woken = tokio::select! {
_ = tokio::time::sleep(wait) => false,
_ = state.rec_wakeup.notified() => true,
};
} }
} }
@@ -91,7 +142,12 @@ pub fn compile_pattern(p: &str) -> regex::Regex {
} }
/// Series recording rules: schedules matching programmes within the next 48 h. /// Series recording rules: schedules matching programmes within the next 48 h.
pub async fn run_autorec(state: &State) -> Result<usize> { /// Applies the recording rules to the next 48 hours of the guide.
/// Returns (recordings created, active rules).
pub async fn run_autorec(state: &State) -> Result<(usize, usize)> {
// one run at a time (scheduler and "run now" in the panel), so no duplicates
static RUNNING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
let _guard = RUNNING.lock().await;
let rules: Vec<_> = state let rules: Vec<_> = state
.db .db
.autorecs() .autorecs()
@@ -100,12 +156,13 @@ pub async fn run_autorec(state: &State) -> Result<usize> {
.filter(|r| r.enabled && !r.pattern.trim().is_empty()) .filter(|r| r.enabled && !r.pattern.trim().is_empty())
.collect(); .collect();
if rules.is_empty() { if rules.is_empty() {
return Ok(0); return Ok((0, 0));
} }
let t = now(); let t = now();
let events = state.db.epg_range(None, t, t + 48 * 3600).await?; let events = state.db.epg_range(None, t, t + 48 * 3600).await?;
let s = state.settings(); let s = state.settings();
let mut created = 0; let mut created = 0;
let rules_len = rules.len();
for rule in rules { for rule in rules {
let re = compile_pattern(&rule.pattern); let re = compile_pattern(&rule.pattern);
for e in events for e in events
@@ -143,7 +200,7 @@ pub async fn run_autorec(state: &State) -> Result<usize> {
created += 1; created += 1;
} }
} }
Ok(created) Ok((created, rules_len))
} }
/// Deletes old recordings (by age) and the oldest ones when space runs low. /// Deletes old recordings (by age) and the oldest ones when space runs low.
@@ -209,11 +266,17 @@ pub fn free_space(path: &Path) -> Option<u64> {
Some(st.f_bavail as u64 * st.f_frsize as u64) Some(st.f_bavail as u64 * st.f_frsize as u64)
} }
async fn tick(state: &State) -> Result<()> { /// Starts the recordings that are due; returns when the next one is (unix seconds).
async fn tick(state: &State) -> Result<Option<i64>> {
let t = now(); let t = now();
let mut next: Option<i64> = None;
for r in state.db.recordings_by_status("scheduled").await? { for r in state.db.recordings_by_status("scheduled").await? {
let begin = r.start - r.pre_padding; let begin = r.start - r.pre_padding;
let end = r.stop + r.post_padding; let end = r.stop + r.post_padding;
if t < begin {
next = Some(next.map_or(begin, |n| n.min(begin)));
continue;
}
if t >= end { if t >= end {
state state
.db .db
@@ -249,7 +312,7 @@ async fn tick(state: &State) -> Result<()> {
}); });
} }
} }
Ok(()) Ok(next)
} }
/// Stops a running recording. /// Stops a running recording.
+10
View File
@@ -97,6 +97,11 @@ impl Stats {
} }
} }
/// The newest system sample (CPU, memory, temperature …), if the sampler has run.
pub fn latest(&self) -> Option<Sample> {
self.inner.lock().unwrap().samples.back().cloned()
}
fn push(&self, s: Sample, tuners: Vec<(String, TunerSample)>) { fn push(&self, s: Sample, tuners: Vec<(String, TunerSample)>) {
let mut g = self.inner.lock().unwrap(); let mut g = self.inner.lock().unwrap();
g.samples.push_back(s); g.samples.push_back(s);
@@ -213,7 +218,12 @@ pub async fn sampler_task(state: State) {
let dt = prev_t.elapsed().as_secs_f64().max(0.001); let dt = prev_t.elapsed().as_secs_f64().max(0.001);
prev_t = std::time::Instant::now(); prev_t = std::time::Instant::now();
let began = std::time::Instant::now();
probe.refresh(); probe.refresh();
let took = began.elapsed().as_millis();
if took > 200 {
tracing::warn!("reading system metrics took {took} ms");
}
let proto = state.clients.by_protocol(); let proto = state.clients.by_protocol();
let out_ts_bps = smooth( let out_ts_bps = smooth(
&mut proto_win[0], &mut proto_win[0],
+114 -29
View File
@@ -9,7 +9,7 @@ use anyhow::{anyhow, bail, Result};
use bytes::Bytes; use bytes::Bytes;
use serde::Serialize; use serde::Serialize;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::thread::JoinHandle; use std::thread::JoinHandle;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@@ -48,6 +48,10 @@ pub struct Active {
wanted_ver: AtomicU64, wanted_ver: AtomicU64,
/// Whether the source is currently limited to a PID list. /// Whether the source is currently limited to a PID list.
pub filtered: AtomicBool, pub filtered: AtomicBool,
/// How long the last signal statistics read from the demodulator took (ms).
status_ms: AtomicU64,
/// Longest pause between two reads of the DVR device in the last window (ms).
read_gap_ms: AtomicU64,
} }
/// Transport stream health of the tuned multiplex (counted since tuning). /// Transport stream health of the tuned multiplex (counted since tuning).
@@ -235,6 +239,8 @@ pub struct SlotStatus {
pub delivery_systems: Vec<String>, pub delivery_systems: Vec<String>,
pub enabled: bool, pub enabled: bool,
pub busy: bool, pub busy: bool,
/// Busy with a background (idle) scan that gives way to viewers.
pub idle_scan: bool,
pub priority: u64, pub priority: u64,
pub last_error: String, pub last_error: String,
pub active: Option<ActiveStatus>, pub active: Option<ActiveStatus>,
@@ -255,6 +261,10 @@ pub struct ActiveStatus {
pub tuned: Option<dvb::TunedInfo>, pub tuned: Option<dvb::TunedInfo>,
/// Only the PIDs clients need are read (bitrate and TS counters cover just those). /// Only the PIDs clients need are read (bitrate and TS counters cover just those).
pub pid_filtered: bool, pub pid_filtered: bool,
/// Duration of the last signal statistics read (ms) – slow demodulator I2C shows here.
pub status_ms: u64,
/// Longest pause between DVR reads in the last 2 s window (ms).
pub read_gap_ms: u64,
} }
/// Channel for PMTs seen while streaming: (mux id, PMTs). /// Channel for PMTs seen while streaming: (mux id, PMTs).
@@ -271,6 +281,16 @@ pub struct TunerManager {
/// Receives the PMTs seen while streaming (mux id, PMTs) so service stream /// 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. /// lists stay current even when a scan timed out before a PMT arrived.
pub pmt_tx: Mutex<Option<PmtSender>>, pub pmt_tx: Mutex<Option<PmtSender>>,
/// When tuner status was last requested (unix seconds); while nobody looks, the
/// demodulator statistics are read less often (each read costs I2C traffic).
stats_seen: Arc<AtomicI64>,
}
fn unix_now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
} }
impl TunerManager { impl TunerManager {
@@ -281,6 +301,7 @@ impl TunerManager {
epg_tx, epg_tx,
epg_enabled: AtomicBool::new(true), epg_enabled: AtomicBool::new(true),
pid_filter: Arc::new(AtomicBool::new(true)), pid_filter: Arc::new(AtomicBool::new(true)),
stats_seen: Arc::new(AtomicI64::new(0)),
linger: Mutex::new(Duration::from_secs(8)), linger: Mutex::new(Duration::from_secs(8)),
pmt_tx: Mutex::new(None), pmt_tx: Mutex::new(None),
}) })
@@ -324,6 +345,8 @@ impl TunerManager {
} }
pub fn status(&self) -> Vec<SlotStatus> { pub fn status(&self) -> Vec<SlotStatus> {
// someone is looking at the signal: read the demodulator statistics often
self.stats_seen.store(unix_now(), Ordering::Relaxed);
self.slots self.slots
.lock() .lock()
.unwrap() .unwrap()
@@ -349,6 +372,8 @@ impl TunerManager {
ts: a.ts.lock().unwrap().clone(), ts: a.ts.lock().unwrap().clone(),
tuned: a.tuned.lock().unwrap().clone(), tuned: a.tuned.lock().unwrap().clone(),
pid_filtered: a.filtered.load(Ordering::Relaxed), pid_filtered: a.filtered.load(Ordering::Relaxed),
status_ms: a.status_ms.load(Ordering::Relaxed),
read_gap_ms: a.read_gap_ms.load(Ordering::Relaxed),
} }
}); });
SlotStatus { SlotStatus {
@@ -364,6 +389,8 @@ impl TunerManager {
.collect(), .collect(),
enabled: s.enabled.load(Ordering::Relaxed), enabled: s.enabled.load(Ordering::Relaxed),
busy: s.busy.load(Ordering::Relaxed), busy: s.busy.load(Ordering::Relaxed),
idle_scan: s.busy.load(Ordering::Relaxed)
&& s.idle_scan.load(Ordering::Relaxed),
priority: s.priority.load(Ordering::Relaxed), priority: s.priority.load(Ordering::Relaxed),
last_error: s.last_error.lock().unwrap().clone(), last_error: s.last_error.lock().unwrap().clone(),
active, active,
@@ -501,35 +528,21 @@ impl TunerManager {
tokio::time::sleep(Duration::from_millis(100)).await; tokio::time::sleep(Duration::from_millis(100)).await;
} }
} }
let (active, slot_id) = { // While zapping, the previous channel's session may need a moment to release its
let slots = self.slots.lock().unwrap(); // tuner: a user request waits up to 3 s for one instead of failing at once.
// 1. already tuned let mut attempt = 0;
let mut found = None; let (active, slot_id) = loop {
for s in slots.iter() { match self.attach(mux.id, &params, prio, id, &pids) {
let a = s.active.lock().unwrap(); Ok(x) => break x,
if let Some(x) = a.as_ref() { Err(e)
if x.mux_id == mux.id if prio > Priority::Background
&& x.params == params && attempt < 30
&& !x.is_stopped() && e.to_string().starts_with("no free tuner") =>
&& !matches!(&*x.state.borrow(), TuneState::Failed(_))
{ {
x.declare(id, pids.clone()); attempt += 1;
x.subs.lock().unwrap().insert(id, prio); tokio::time::sleep(Duration::from_millis(100)).await;
*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.declare(id, pids.clone());
active.subs.lock().unwrap().insert(id, prio);
(active, slot.info.id.clone())
} }
Err(e) => return Err(e),
} }
}; };
let rx = active.tx.subscribe(); let rx = active.tx.subscribe();
@@ -556,6 +569,38 @@ impl TunerManager {
} }
} }
/// Joins the multiplex if it is tuned already, or tunes a free adapter.
fn attach(
self: &Arc<Self>,
mux_id: i64,
params: &TuneParams,
prio: Priority,
id: u64,
pids: &Option<Vec<u16>>,
) -> Result<(Arc<Active>, String)> {
let slots = self.slots.lock().unwrap();
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.declare(id, pids.clone());
x.subs.lock().unwrap().insert(id, prio);
*x.idle_since.lock().unwrap() = None;
return Ok((x.clone(), s.info.id.clone()));
}
}
}
let slot = self.pick_slot(&slots, params, prio)?;
let active = self.start(&slot, mux_id, params.clone());
active.declare(id, pids.clone());
active.subs.lock().unwrap().insert(id, prio);
Ok((active, slot.info.id.clone()))
}
/// Whether some adapter could take `params` right now without preempting a scan. /// Whether some adapter could take `params` right now without preempting a scan.
fn has_slot_for(&self, params: &TuneParams) -> bool { fn has_slot_for(&self, params: &TuneParams) -> bool {
self.slots.lock().unwrap().iter().any(|s| { self.slots.lock().unwrap().iter().any(|s| {
@@ -628,6 +673,8 @@ impl TunerManager {
wanted: Mutex::new(HashMap::new()), wanted: Mutex::new(HashMap::new()),
wanted_ver: AtomicU64::new(0), wanted_ver: AtomicU64::new(0),
filtered: AtomicBool::new(false), filtered: AtomicBool::new(false),
status_ms: AtomicU64::new(0),
read_gap_ms: AtomicU64::new(0),
bitrate: AtomicU64::new(0), bitrate: AtomicU64::new(0),
started: Instant::now(), started: Instant::now(),
state: state_rx, state: state_rx,
@@ -639,6 +686,7 @@ impl TunerManager {
let epg_tx = self.epg_tx.clone(); let epg_tx = self.epg_tx.clone();
let collect_eit = self.epg_enabled.load(Ordering::Relaxed); let collect_eit = self.epg_enabled.load(Ordering::Relaxed);
let pid_filter = self.pid_filter.clone(); let pid_filter = self.pid_filter.clone();
let stats_seen = self.stats_seen.clone();
let pmt_tx = self.pmt_tx.lock().unwrap().clone(); let pmt_tx = self.pmt_tx.lock().unwrap().clone();
let slot2 = slot.clone(); let slot2 = slot.clone();
let handle = std::thread::Builder::new() let handle = std::thread::Builder::new()
@@ -655,6 +703,7 @@ impl TunerManager {
pmt_tx, pmt_tx,
collect_eit, collect_eit,
&pid_filter, &pid_filter,
&stats_seen,
); );
if let Err(e) = r { if let Err(e) = r {
let msg = format!("{e:#}"); let msg = format!("{e:#}");
@@ -724,6 +773,7 @@ fn wanted_pids(a: &Active, pmts: &[u16]) -> Option<Vec<u16>> {
Some(set.into_iter().collect()) Some(set.into_iter().collect())
} }
#[allow(clippy::too_many_arguments)]
fn reader_thread( fn reader_thread(
info: &AdapterInfo, info: &AdapterInfo,
a: &Arc<Active>, a: &Arc<Active>,
@@ -732,6 +782,7 @@ fn reader_thread(
pmt_tx: Option<PmtSender>, pmt_tx: Option<PmtSender>,
collect_eit: bool, collect_eit: bool,
pid_filter: &AtomicBool, pid_filter: &AtomicBool,
stats_seen: &AtomicI64,
) -> Result<()> { ) -> Result<()> {
let mut src = dvb::open(info)?; let mut src = dvb::open(info)?;
tracing::info!("{}: tuning {}", info.id, a.params.describe()); tracing::info!("{}: tuning {}", info.id, a.params.describe());
@@ -751,10 +802,20 @@ fn reader_thread(
let mut si = SiCollector::new(collect_eit); let mut si = SiCollector::new(collect_eit);
let mut aligner = Aligner::new(); let mut aligner = Aligner::new();
let mut last_stat = Instant::now(); let mut last_stat = Instant::now();
let mut last_si = Instant::now();
let mut pmts_sent: std::collections::HashMap<u16, crate::ts::tables::Pmt> = Default::default(); let mut pmts_sent: std::collections::HashMap<u16, crate::ts::tables::Pmt> = Default::default();
let mut bytes = 0u64; let mut bytes = 0u64;
let mut last_read = Instant::now();
let mut max_gap = Duration::ZERO;
let mut last_sig = Instant::now();
let mut slow_warned = 0u32;
while !a.stop.load(Ordering::Relaxed) { while !a.stop.load(Ordering::Relaxed) {
let n = src.read(&mut buf)?; let n = src.read(&mut buf)?;
let gap = last_read.elapsed();
last_read = Instant::now();
if gap > max_gap {
max_gap = gap;
}
if n > 0 { if n > 0 {
bytes += n as u64; bytes += n as u64;
aligner.push(&buf[..n], |p| { aligner.push(&buf[..n], |p| {
@@ -773,6 +834,7 @@ fn reader_thread(
pmts.sort_unstable(); pmts.sort_unstable();
if applied.as_ref() != Some(&(ver, pmts.clone(), on)) { if applied.as_ref() != Some(&(ver, pmts.clone(), on)) {
let list = if on { wanted_pids(a, &pmts) } else { None }; let list = if on { wanted_pids(a, &pmts) } else { None };
tracing::debug!("{}: PID filter {:?}", info.id, list);
let ok = src.set_pids(list.as_deref()); let ok = src.set_pids(list.as_deref());
a.filtered.store(ok && list.is_some(), Ordering::Relaxed); a.filtered.store(ok && list.is_some(), Ordering::Relaxed);
applied = Some((ver, pmts, on)); applied = Some((ver, pmts, on));
@@ -787,7 +849,28 @@ fn reader_thread(
); );
bytes = 0; bytes = 0;
last_stat = Instant::now(); last_stat = Instant::now();
a.read_gap_ms
.store(max_gap.as_millis() as u64, Ordering::Relaxed);
max_gap = Duration::ZERO;
*a.ts.lock().unwrap() = ts.st.clone();
}
// Signal statistics: every 2 s while someone watches them (panel, TV app tuner
// card), otherwise every 10 s. On Si2168-class demodulators each read is a series
// of I2C commands that the kernel driver busy-waits on.
let since_sig = last_sig.elapsed();
if since_sig >= Duration::from_secs(2)
&& (since_sig >= Duration::from_secs(10)
|| unix_now() - stats_seen.load(Ordering::Relaxed) < 15)
{
last_sig = Instant::now();
let began = Instant::now();
let mut sig = src.status(); let mut sig = src.status();
let took = began.elapsed().as_millis() as u64;
a.status_ms.store(took, Ordering::Relaxed);
if took > 150 && slow_warned < 5 {
slow_warned += 1;
tracing::warn!("{}: reading signal statistics took {took} ms", info.id);
}
sig.ber = match ( sig.ber = match (
prev_sig.post_bit_errors, prev_sig.post_bit_errors,
sig.post_bit_errors, sig.post_bit_errors,
@@ -801,7 +884,9 @@ fn reader_thread(
}; };
*a.signal.lock().unwrap() = sig.clone(); *a.signal.lock().unwrap() = sig.clone();
prev_sig = sig; prev_sig = sig;
*a.ts.lock().unwrap() = ts.st.clone(); }
if last_si.elapsed() >= Duration::from_secs(2) {
last_si = Instant::now();
let items = si.take_epg(); let items = si.take_epg();
if !items.is_empty() { if !items.is_empty() {
let _ = epg_tx.send((a.mux_id, items)); let _ = epg_tx.send((a.mux_id, items));
+159 -2
View File
@@ -445,6 +445,161 @@ pub async fn signal_hold(
ok() ok()
} }
#[derive(Deserialize)]
pub struct PairStartReq {
#[serde(default)]
device: String,
}
/// TV app: starts a pairing request (no login; the code is confirmed in the panel).
pub async fn pair_start(
AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Json(r): Json<PairStartReq>,
) -> ApiResult<Value> {
let ip = auth::client_ip(&state, peer, &headers).to_string();
let p = crate::pairing::start(&r.device, &ip).ok_or_else(|| {
ApiError(
StatusCode::TOO_MANY_REQUESTS,
"too many pairing requests – try again in a few minutes".into(),
)
})?;
// panel link for the QR code: the host the TV used, on the panel port
let hv = |n: &str| {
headers
.get(n)
.and_then(|v| v.to_str().ok())
.map(|s| s.trim().to_string())
};
let url = match hv("x-forwarded-host") {
Some(h) if !h.is_empty() => format!(
"{}://{h}/#/pair/{}",
hv("x-forwarded-proto").unwrap_or_else(|| "https".into()),
p.code
),
_ => {
let host = hv("host").unwrap_or_else(|| "localhost".into());
let name = match host.rfind(':') {
Some(i) if !host.ends_with(']') => host[..i].to_string(),
_ => host,
};
format!("http://{name}:{}/#/pair/{}", state.opts.panel_port, p.code)
}
};
tracing::info!(target: "access", "pairing request {} from {ip} ({})", p.code, p.device);
Ok(Json(json!({
"code": p.code,
"secret": p.secret,
"expires_in": crate::pairing::TTL.as_secs(),
"url": url,
})))
}
#[derive(Deserialize)]
pub struct PairPollQuery {
secret: String,
}
/// TV app: waits for the confirmation; returns the access token once.
pub async fn pair_poll(
AxState(state): AxState<State>,
Query(q): Query<PairPollQuery>,
) -> ApiResult<Value> {
use crate::pairing::Poll;
match crate::pairing::poll(&q.secret) {
Poll::Unknown => Err(ApiError(
StatusCode::GONE,
"pairing request expired or unknown".into(),
)),
Poll::Pending => Ok(Json(json!({"status": "pending"}))),
Poll::Done { token, name } => Ok(Json(json!({
"status": "ok",
"token": token,
"name": name,
"server_name": state.settings().server_name,
"htsp_port": state.opts.htsp_port,
"http_port": state.opts.stream_port.unwrap_or(state.opts.panel_port),
}))),
}
}
/// Panel: what is waiting under a code (after scanning the QR code).
pub async fn pair_info(
Extension(CurrentUser(u)): Extension<CurrentUser>,
Path(code): Path<String>,
) -> ApiResult<Value> {
require_admin(&u)?;
let p = crate::pairing::get(&code).ok_or_else(|| {
ApiError(
StatusCode::NOT_FOUND,
"pairing code expired or unknown".into(),
)
})?;
Ok(Json(json!({
"code": p.code,
"device": p.device,
"ip": p.ip,
"created": p.created_unix,
"confirmed": p.token.is_some(),
})))
}
#[derive(Deserialize)]
pub struct PairConfirmReq {
#[serde(default)]
name: String,
#[serde(default)]
allow_cidrs: String,
}
/// Panel: confirms a pairing – creates an access token for the device.
pub async fn pair_confirm(
AxState(state): AxState<State>,
Extension(CurrentUser(u)): Extension<CurrentUser>,
Path(code): Path<String>,
Json(r): Json<PairConfirmReq>,
) -> ApiResult<Value> {
require_admin(&u)?;
let p = crate::pairing::get(&code).ok_or_else(|| {
ApiError(
StatusCode::NOT_FOUND,
"pairing code expired or unknown".into(),
)
})?;
if p.token.is_some() {
return Err(ApiError::bad("this device is already paired"));
}
resolve_now(&parse_cidrs(&r.allow_cidrs).map_err(ApiError::bad)?).await;
let mut name = r.name.trim().to_string();
if name.is_empty() {
name = p.device.clone();
}
// token names are shown in lists – keep them unique
let existing: Vec<String> = state
.db
.tokens()
.await?
.into_iter()
.map(|t| t.name)
.collect();
let base = name.clone();
let mut n = 2;
while existing.contains(&name) {
name = format!("{base} ({n})");
n += 1;
}
let token = auth::random_token(24);
state
.db
.create_token(&name, &token, r.allow_cidrs.trim())
.await?;
crate::pairing::confirm(&code, token, name.clone());
state.acl_refresh.notify_one();
tracing::info!(target: "access", "{} paired device {} as token \"{name}\"", u.username, p.device);
Ok(Json(json!({"ok": true, "name": name})))
}
fn prefs_key(user_id: i64) -> String { fn prefs_key(user_id: i64) -> String {
format!("prefs:user:{user_id}") format!("prefs:user:{user_id}")
} }
@@ -1506,6 +1661,8 @@ pub async fn recording_update(
.db .db
.update_recording_times(id, &r.title, r.start, r.stop) .update_recording_times(id, &r.title, r.start, r.stop)
.await?; .await?;
// the scheduler sleeps until the next start: a start moved earlier must wake it
state.rec_wakeup.notify_one();
ok() ok()
} }
@@ -1826,7 +1983,7 @@ pub async fn autorec_create(
.db .db
.create_autorec(&r.name(), r.pattern.trim(), r.channel_id, r.enabled) .create_autorec(&r.name(), r.pattern.trim(), r.channel_id, r.enabled)
.await?; .await?;
let created = crate::recorder::run_autorec(&state).await?; let (created, _) = crate::recorder::run_autorec(&state).await?;
Ok(Json(json!({"ok": true, "id": id, "scheduled": created}))) Ok(Json(json!({"ok": true, "id": id, "scheduled": created})))
} }
@@ -1840,7 +1997,7 @@ pub async fn autorec_update(
.db .db
.update_autorec(id, &r.name(), r.pattern.trim(), r.channel_id, r.enabled) .update_autorec(id, &r.name(), r.pattern.trim(), r.channel_id, r.enabled)
.await?; .await?;
let created = crate::recorder::run_autorec(&state).await?; let (created, _) = crate::recorder::run_autorec(&state).await?;
Ok(Json(json!({"ok": true, "scheduled": created}))) Ok(Json(json!({"ok": true, "scheduled": created})))
} }
+9 -1
View File
@@ -146,7 +146,9 @@ async fn request_log(
|| path.starts_with("/icons/") || path.starts_with("/icons/")
|| path == "/healthz" || path == "/healthz"
|| path == "/metrics"; || path == "/metrics";
if status.is_client_error() || status.is_server_error() { if ms >= 300 {
tracing::warn!(target: "access", "slow request: {ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16());
} else if status.is_client_error() || status.is_server_error() {
tracing::warn!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16()); tracing::warn!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16());
} else if noisy { } else if noisy {
tracing::debug!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16()); tracing::debug!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16());
@@ -175,6 +177,8 @@ pub fn router(state: State) -> Router {
.route("/api/me/password", post(api::change_password)) .route("/api/me/password", post(api::change_password))
.route("/api/me/prefs", get(api::my_prefs).put(api::save_my_prefs)) .route("/api/me/prefs", get(api::my_prefs).put(api::save_my_prefs))
.route("/api/me/sessions", get(api::my_sessions)) .route("/api/me/sessions", get(api::my_sessions))
.route("/api/pair/{code}", get(api::pair_info))
.route("/api/pair/{code}/confirm", post(api::pair_confirm))
.route("/api/me/sessions/others", post(api::end_other_sessions)) .route("/api/me/sessions/others", post(api::end_other_sessions))
.route("/api/me/sessions/{id}", delete(api::end_session)) .route("/api/me/sessions/{id}", delete(api::end_session))
.route("/api/backup/database", get(api::backup_download)) .route("/api/backup/database", get(api::backup_download))
@@ -284,6 +288,7 @@ fn public_routes() -> Router<State> {
.route("/playlist.m3u", get(public::playlist)) .route("/playlist.m3u", get(public::playlist))
.route("/playlist.m3u8", get(public::playlist)) .route("/playlist.m3u8", get(public::playlist))
.route("/epg.xml", get(public::epg_xml)) .route("/epg.xml", get(public::epg_xml))
.route("/hls/leave", post(public::hls_leave))
.route("/hls/{ch}/index.m3u8", get(public::hls_playlist)) .route("/hls/{ch}/index.m3u8", get(public::hls_playlist))
.route("/hls/{ch}/{seg}", get(public::hls_segment)) .route("/hls/{ch}/{seg}", get(public::hls_segment))
.route("/stream/{ch}", get(public::ts_stream)) .route("/stream/{ch}", get(public::ts_stream))
@@ -296,6 +301,9 @@ fn public_routes() -> Router<State> {
.route("/recordings/{id}/file", get(public::recording_file)) .route("/recordings/{id}/file", get(public::recording_file))
.route("/metrics", get(public::metrics)) .route("/metrics", get(public::metrics))
.route("/healthz", get(|| async { "ok" })) .route("/healthz", get(|| async { "ok" }))
// TV app pairing (QR code)
.route("/api/pair/start", post(api::pair_start))
.route("/api/pair/poll", get(api::pair_poll))
// tvheadend-compatible // tvheadend-compatible
.route("/playlist", get(tvh::playlist_all)) .route("/playlist", get(tvh::playlist_all))
.route("/playlist/{a}", get(tvh::playlist_all_sub)) .route("/playlist/{a}", get(tvh::playlist_all_sub))
+25 -1
View File
@@ -32,6 +32,16 @@ pub struct StreamQuery {
channels: Option<String>, channels: Option<String>,
/// M3U: only this channel group /// M3U: only this channel group
group: Option<String>, group: Option<String>,
/// HLS: viewer id of a player instance (lets the server end its old sessions at once)
v: Option<String>,
}
impl StreamQuery {
fn viewer(&self) -> Option<&str> {
self.v
.as_deref()
.filter(|v| (8..=40).contains(&v.len()) && v.chars().all(|c| c.is_ascii_alphanumeric()))
}
} }
impl StreamQuery { impl StreamQuery {
@@ -211,6 +221,9 @@ fn hls_suffix(ctx: &Ctx, q: &StreamQuery, profile: &str) -> String {
if profile != "pass" { if profile != "pass" {
parts.push(format!("profile={profile}")); parts.push(format!("profile={profile}"));
} }
if let Some(v) = q.viewer() {
parts.push(format!("v={v}"));
}
match &ctx.access { match &ctx.access {
StreamAccess::Token(t) => parts.push(format!("token={}", t.token)), StreamAccess::Token(t) => parts.push(format!("token={}", t.token)),
StreamAccess::Share(_) => { StreamAccess::Share(_) => {
@@ -247,7 +260,7 @@ pub async fn hls_playlist(
Ok(p) => p, Ok(p) => p,
Err(e) => return e.into_response(), Err(e) => return e.into_response(),
}; };
let sess = state.hls.get_or_start(&state, id, &profile); let sess = state.hls.get_or_start(&state, id, &profile, q.viewer());
sess.touch(); sess.touch();
if let Err(e) = sess.wait_ready(Duration::from_secs(25)).await { if let Err(e) = sess.wait_ready(Duration::from_secs(25)).await {
return ( return (
@@ -289,6 +302,14 @@ pub async fn hls_playlist(
.into_response() .into_response()
} }
/// `POST /hls/leave?v=<viewer>` – a player stopped (channel change, page closed).
pub async fn hls_leave(AxState(state): AxState<State>, Query(q): Query<StreamQuery>) -> Response {
if let Some(v) = q.viewer() {
state.hls.leave(v);
}
StatusCode::NO_CONTENT.into_response()
}
pub async fn hls_segment( pub async fn hls_segment(
AxState(state): AxState<State>, AxState(state): AxState<State>,
ConnectInfo(peer): ConnectInfo<SocketAddr>, ConnectInfo(peer): ConnectInfo<SocketAddr>,
@@ -322,6 +343,9 @@ pub async fn hls_segment(
.into_response(); .into_response();
}; };
sess.touch(); sess.touch();
if let Some(v) = q.viewer() {
sess.see(v);
}
let Some(data) = sess.wait_segment(seq, Duration::from_secs(12)).await else { let Some(data) = sess.wait_segment(seq, Duration::from_secs(12)).await else {
return (StatusCode::NOT_FOUND, "segment unavailable").into_response(); return (StatusCode::NOT_FOUND, "segment unavailable").into_response();
}; };
+56 -3
View File
@@ -612,23 +612,76 @@ async fn status_inputs(
body: Bytes, body: Bytes,
) -> Response { ) -> Response {
let p = guard!(state, peer, headers, q, body); let p = guard!(state, peer, headers, q, body);
// `?channel=<id>`: only the tuner currently carrying that channel's multiplex
// (used by the simply-tv player for its tuner overlay)
let mut only_mux: Option<i64> = None;
if let Some(id) = p.get("channel").and_then(|v| v.parse::<i64>().ok()) {
let sid = state
.db
.channel(id)
.await
.ok()
.flatten()
.and_then(|c| c.service_id);
if let Some(sid) = sid {
only_mux = state.db.service(sid).await.ok().flatten().map(|s| s.mux_id);
}
if only_mux.is_none() {
only_mux = Some(-1);
}
}
// host load for the player overlay (simply-tv draws a CPU sparkline)
let host = state.stats.latest();
let host_cpu = host.as_ref().and_then(|s| s.cpu);
let host_proc_cpu = host.as_ref().and_then(|s| s.proc_cpu);
let host_temp = host.as_ref().and_then(|s| s.temp);
grid( grid(
state state
.tuners .tuners
.status() .status()
.iter() .iter()
.filter(|t| match only_mux {
Some(m) => t.active.as_ref().is_some_and(|a| a.mux_id == m),
None => true,
})
.map(|t| { .map(|t| {
let a = t.active.as_ref(); let a = t.active.as_ref();
let sig = a.map(|a| &a.signal);
let tuned = a.and_then(|a| a.tuned.as_ref());
json!({ json!({
"uuid": t.id, "input": t.name, "stream": a.map(|a| a.tuning.clone()).unwrap_or_default(), "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), "subs": a.map(|a| a.subscribers).unwrap_or(0),
"weight": 0, "weight": 0,
"signal": a.and_then(|a| a.signal.strength_pct).map(|v| (v * 655.35) as i64).unwrap_or(0), "signal": sig.and_then(|s| s.strength_pct).map(|v| (v * 655.35) as i64).unwrap_or(0),
"signal_scale": 2, "signal_scale": 2,
"snr": a.and_then(|a| a.signal.snr_db).map(|v| (v * 1000.0) as i64).unwrap_or(0), "snr": sig.and_then(|s| s.snr_db).map(|v| (v * 1000.0) as i64).unwrap_or(0),
"snr_scale": 1, "snr_scale": 1,
"unc": a.and_then(|a| a.signal.uncorrected).unwrap_or(0), "unc": sig.and_then(|s| s.uncorrected).unwrap_or(0),
"bps": a.map(|a| a.bitrate_bps).unwrap_or(0), "bps": a.map(|a| a.bitrate_bps).unwrap_or(0),
"te": a.map(|a| a.ts.tei_errors).unwrap_or(0),
"cc": a.map(|a| a.ts.cc_errors).unwrap_or(0),
// simply-dvb extras (plain units)
"adapter": t.id,
"delivery_systems": t.delivery_systems,
"driver": t.device.driver,
"bus": t.device.bus,
"locked": sig.map(|s| s.locked).unwrap_or(false),
"strength_pct": sig.and_then(|s| s.strength_pct),
"strength_dbm": sig.and_then(|s| s.strength_dbm),
"snr_db": sig.and_then(|s| s.snr_db),
"ber": sig.and_then(|s| s.ber),
"modulation": tuned.and_then(|x| x.modulation.clone()),
"code_rate": tuned.and_then(|x| x.code_rate.clone()),
"guard_interval": tuned.and_then(|x| x.guard_interval.clone()),
"transmission_mode": tuned.and_then(|x| x.transmission_mode.clone()),
"pid_filtered": a.map(|a| a.pid_filtered).unwrap_or(false),
"uptime": a.map(|a| a.uptime_secs).unwrap_or(0),
"packets": a.map(|a| a.ts.packets).unwrap_or(0),
"status_ms": a.map(|a| a.status_ms),
"read_gap_ms": a.map(|a| a.read_gap_ms),
"server_cpu": host_cpu,
"server_proc_cpu": host_proc_cpu,
"server_temp": host_temp,
}) })
}) })
.collect(), .collect(),
+2 -1
View File
@@ -61,6 +61,7 @@ async fn setup() -> Env {
virtual_dirs: vec![mux_dir.to_string_lossy().to_string()], virtual_dirs: vec![mux_dir.to_string_lossy().to_string()],
stream_port: Some(9981), stream_port: Some(9981),
htsp_port: None, htsp_port: None,
panel_port: 9980,
}; };
let (state, epg_rx) = AppState::new(db, opts).await.unwrap(); let (state, epg_rx) = AppState::new(db, opts).await.unwrap();
tokio::spawn(epg::writer_task(state.clone(), epg_rx)); tokio::spawn(epg::writer_task(state.clone(), epg_rx));
@@ -687,7 +688,7 @@ async fn full_flow() {
.any(|r| r["autorec_id"] == rule["id"] && r["status"] == "scheduled")); .any(|r| r["autorec_id"] == rule["id"] && r["status"] == "scheduled"));
// running it again does not create duplicates // running it again does not create duplicates
let again = simply_dvb::recorder::run_autorec(&env.state).await.unwrap(); let again = simply_dvb::recorder::run_autorec(&env.state).await.unwrap();
assert_eq!(again, 0); assert_eq!(again.0, 0);
json_of( json_of(
&env.lan, &env.lan,
Method::DELETE, Method::DELETE,
+7
View File
@@ -189,3 +189,10 @@ details.hw .kv { margin-top: 6px; }
.topbar { padding-top: env(safe-area-inset-top); height: calc(42px + env(safe-area-inset-top)); } .topbar { padding-top: env(safe-area-inset-top); height: calc(42px + env(safe-area-inset-top)); }
.sg-pick label { min-width: 0; max-width: 100%; } .sg-pick label { min-width: 0; max-width: 100%; }
.sg-pick select { max-width: 100%; } .sg-pick select { max-width: 100%; }
/* buttons/links inside the player overlay must stay clickable (Play, Open in VLC) */
.player .overlay .btn, .player .overlay a, .player .overlay button { pointer-events: auto; }
/* TV pairing */
.pair-box { max-width: 620px; }
.pair-code { font: 600 28px var(--mono); letter-spacing: .3em; text-transform: uppercase; text-align: center; }
.alert.ok-alert { border-color: var(--green); display: flex; align-items: center; gap: 8px; }
+17 -3
View File
@@ -7,7 +7,9 @@
'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"'], '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, 'MPEG-2': null,
'AAC': 'audio/mp4; codecs="mp4a.40.2"', 'AAC': 'audio/mp4; codecs="mp4a.40.2"',
'MP2': 'audio/mpeg', // MPEG-1 Layer II (DVB-T radio/TV sound): MSE decoders handle MP3 only, so browsers
// get it converted to AAC (cheap: the video is not touched)
'MP2': null,
'AC-3': 'audio/mp4; codecs="ac-3"', 'AC-3': 'audio/mp4; codecs="ac-3"',
'E-AC-3': 'audio/mp4; codecs="ec-3"', 'E-AC-3': 'audio/mp4; codecs="ec-3"',
'AAC-LATM': null 'AAC-LATM': null
@@ -87,7 +89,11 @@
container.appendChild(badge); container.appendChild(badge);
var hls = null; var hls = null;
var destroyed = false; var destroyed = false;
var fallbackOrder = opts.transcode === false ? ['pass'] : ['pass', 'aac', 'h264']; // full video transcoding (h264) only when the browser cannot decode the video itself
var fallbackOrder = opts.transcode === false ? ['pass'] : (supported(codec(opts.video)) ? ['pass', 'aac'] : ['pass', 'aac', 'h264']);
// viewer id: lets the server stop this viewer's previous session at once when the
// channel or profile changes (frees the tuner and ffmpeg immediately)
var viewer = Math.random().toString(36).slice(2, 10) + Date.now().toString(36);
var profile = opts.profile && opts.profile !== 'auto' ? opts.profile : pickProfile(opts.video, opts.audio, opts.transcode); var profile = opts.profile && opts.profile !== 'auto' ? opts.profile : pickProfile(opts.video, opts.audio, opts.transcode);
var auto = !opts.profile || opts.profile === 'auto'; var auto = !opts.profile || opts.profile === 'auto';
var retries = 0; var retries = 0;
@@ -122,6 +128,7 @@
if (profile !== 'pass') q.push('profile=' + profile); if (profile !== 'pass') q.push('profile=' + profile);
if (opts.share) q.push('share=' + encodeURIComponent(opts.share)); if (opts.share) q.push('share=' + encodeURIComponent(opts.share));
if (opts.token) q.push('token=' + encodeURIComponent(opts.token)); if (opts.token) q.push('token=' + encodeURIComponent(opts.token));
if (opts.live !== false) q.push('v=' + viewer);
return '/hls/' + opts.channelId + '/index.m3u8' + (q.length ? '?' + q.join('&') : ''); return '/hls/' + opts.channelId + '/index.m3u8' + (q.length ? '?' + q.join('&') : '');
} }
@@ -133,6 +140,13 @@
return true; return true;
} }
function leave() {
if (opts.src || opts.live === false) return;
var u = '/hls/leave?v=' + viewer;
try { if (!(navigator.sendBeacon && navigator.sendBeacon(u))) fetch(u, { method: 'POST', keepalive: true }); } catch (e) {}
}
window.addEventListener('pagehide', leave);
function teardown() { function teardown() {
if (hls) { try { hls.destroy(); } catch (e) {} hls = null; } if (hls) { try { hls.destroy(); } catch (e) {} hls = null; }
video.removeAttribute('src'); video.removeAttribute('src');
@@ -208,7 +222,7 @@
video: video, video: video,
get profile() { return profile; }, get profile() { return profile; },
setProfile: function (p) { auto = p === 'auto'; profile = auto ? pickProfile(opts.video, opts.audio) : p; start(); }, setProfile: function (p) { auto = p === 'auto'; profile = auto ? pickProfile(opts.video, opts.audio) : p; start(); },
destroy: function () { destroyed = true; teardown(); container.innerHTML = ''; } destroy: function () { destroyed = true; teardown(); leave(); window.removeEventListener('pagehide', leave); container.innerHTML = ''; }
}; };
} }
+46 -4
View File
@@ -157,6 +157,7 @@
recordings: ['Recordings', pageRecordings], recordings: ['Recordings', pageRecordings],
tuners: ['Tuners & scanning', pageTuners], tuners: ['Tuners & scanning', pageTuners],
stats: ['Statistics', pageStats], stats: ['Statistics', pageStats],
pair: ['Pair a TV', pagePair],
signal: ['Antenna meter', pageSignal], signal: ['Antenna meter', pageSignal],
access: ['Access & sharing', pageAccess], access: ['Access & sharing', pageAccess],
logs: ['Logs', pageLogs], logs: ['Logs', pageLogs],
@@ -380,7 +381,8 @@
return '<div class="kv ts-kv">' + return '<div class="kv ts-kv">' +
(tu ? '<span>Transmission</span><span class="mono">' + esc([tu.modulation, tu.code_rate && 'FEC ' + tu.code_rate, tu.guard_interval && 'GI ' + tu.guard_interval, tu.transmission_mode].filter(Boolean).join(' · ')) + '</span>' : '') + (tu ? '<span>Transmission</span><span class="mono">' + esc([tu.modulation, tu.code_rate && 'FEC ' + tu.code_rate, tu.guard_interval && 'GI ' + tu.guard_interval, tu.transmission_mode].filter(Boolean).join(' · ')) + '</span>' : '') +
'<span>Packets</span><span class="mono">' + ts.packets.toLocaleString() + ' · ' + ts.pids + ' PIDs · ' + esc(T('stuffing')) + ' ' + pct(ts.null_packets) + (ts.scrambled ? ' · ' + esc(T('scrambled')) + ' ' + pct(ts.scrambled) : '') + '</span>' + '<span>Packets</span><span class="mono">' + ts.packets.toLocaleString() + ' · ' + ts.pids + ' PIDs · ' + esc(T('stuffing')) + ' ' + pct(ts.null_packets) + (ts.scrambled ? ' · ' + esc(T('scrambled')) + ' ' + pct(ts.scrambled) : '') + '</span>' +
'<span>Errors</span><span class="mono ' + (ts.cc_errors || ts.tei_errors ? 'warn-text' : '') + '">CC ' + ts.cc_errors + ' · TEI ' + ts.tei_errors + '</span></div>'; '<span>Errors</span><span class="mono ' + (ts.cc_errors || ts.tei_errors ? 'warn-text' : '') + '">CC ' + ts.cc_errors + ' · TEI ' + ts.tei_errors + '</span>' +
'<span title="' + esc(T('Time of the last signal statistics read from the demodulator and the longest pause between reads of the stream. High values point to a slow driver (I2C) and can make playback stutter.')) + '">' + esc(T('Driver timing')) + '</span><span class="mono ' + (a.status_ms > 150 || a.read_gap_ms > 300 ? 'warn-text' : '') + '">' + esc(T('stats')) + ' ' + (a.status_ms || 0) + ' ms · ' + esc(T('max gap')) + ' ' + (a.read_gap_ms || 0) + ' ms</span></div>';
} }
/** Adapter hardware: bus, driver, product, ids, frequency range, capabilities. */ /** Adapter hardware: bus, driver, product, ids, frequency range, capabilities. */
function hardwareBlock(t) { function hardwareBlock(t) {
@@ -468,7 +470,7 @@
add('ber', 'Bit error rate (BER)', [{ name: 'BER', values: pick(TS, 'ber') }], { unit: 'ber', min: 0, floor: 1e-6, noArea: true }); add('ber', 'Bit error rate (BER)', [{ name: 'BER', values: pick(TS, 'ber') }], { unit: 'ber', min: 0, floor: 1e-6, noArea: true });
add('tserr', 'Stream errors', [{ name: 'CC', values: pick(TS, 'cc') }, { name: 'TEI', values: pick(TS, 'tei') }], { min: 0, floor: 1, bars: true }); add('tserr', 'Stream errors', [{ name: 'CC', values: pick(TS, 'cc') }, { name: 'TEI', values: pick(TS, 'tei') }], { min: 0, floor: 1, bars: true });
return '<div class="panel tuner"><div class="t-head"><div><h3>' + esc(t.name) + '</h3><div class="t-meta">' + esc(t.id) + ' · ' + esc(t.delivery_systems.join(' / ')) + ' · ' + esc(t.path) + '</div></div>' + return '<div class="panel tuner"><div class="t-head"><div><h3>' + esc(t.name) + '</h3><div class="t-meta">' + esc(t.id) + ' · ' + esc(t.delivery_systems.join(' / ')) + ' · ' + esc(t.path) + '</div></div>' +
'<div class="actions">' + (!t.enabled ? '<span class="pill">disabled</span>' : t.busy ? '<span class="pill warn">scanning</span>' : '<div class="actions">' + (!t.enabled ? '<span class="pill">disabled</span>' : t.busy ? (t.idle_scan ? '<span class="pill blue" title="' + esc(T('Background scan of saved muxes while the tuner is free – stops at once when someone watches.')) + '">' + esc(T('background scan')) + '</span>' : '<span class="pill warn">scanning</span>') :
a ? '<span class="pill ' + (a.state === 'locked' ? 'ok' : a.state === 'tuning' ? 'warn' : 'err') + '">' + esc(a.state === 'locked' ? 'LOCK' : a.state) + '</span>' : '<span class="pill">idle</span>') + '</div></div>' + a ? '<span class="pill ' + (a.state === 'locked' ? 'ok' : a.state === 'tuning' ? 'warn' : 'err') + '">' + esc(a.state === 'locked' ? 'LOCK' : a.state) + '</span>' : '<span class="pill">idle</span>') + '</div></div>' +
(a ? '<div class="kv"><span>Mux</span><span>' + esc(a.tuning) + (a.network_name ? ' · ' + esc(a.network_name) : '') + '</span>' + (a ? '<div class="kv"><span>Mux</span><span>' + esc(a.tuning) + (a.network_name ? ' · ' + esc(a.network_name) : '') + '</span>' +
'<span>Clients</span><span>' + a.subscribers + (a.top_priority ? ' · priority ' + esc(a.top_priority) : '') + '</span>' + '<span>Clients</span><span>' + a.subscribers + (a.top_priority ? ' · priority ' + esc(a.top_priority) : '') + '</span>' +
@@ -1267,7 +1269,7 @@
api('GET', '/api/adapters').then(function (list) { api('GET', '/api/adapters').then(function (list) {
$('#ad-list').innerHTML = list.length ? '<table><tbody>' + list.map(function (a) { $('#ad-list').innerHTML = list.length ? '<table><tbody>' + list.map(function (a) {
return '<tr><td><b>' + esc(a.name) + '</b><div class="small muted mono">' + esc(a.id + ' · ' + a.path) + '</div></td><td class="small">' + esc(a.delivery_systems.join(' / ')) + '</td>' + return '<tr><td><b>' + esc(a.name) + '</b><div class="small muted mono">' + esc(a.id + ' · ' + a.path) + '</div></td><td class="small">' + esc(a.delivery_systems.join(' / ')) + '</td>' +
'<td>' + (a.active ? '<span class="pill ok">' + esc(a.active.tuning) + '</span>' : a.busy ? '<span class="pill warn">scanning</span>' : '<span class="pill">idle</span>') + '</td>' + '<td>' + (a.active ? '<span class="pill ok">' + esc(a.active.tuning) + '</span>' : a.busy ? (a.idle_scan ? '<span class="pill blue" title="' + esc(T('Background scan of saved muxes while the tuner is free – stops at once when someone watches.')) + '">' + esc(T('background scan')) + '</span>' : '<span class="pill warn">scanning</span>') : '<span class="pill">idle</span>') + '</td>' +
'<td>' + sw(a.enabled, 'data-ad="' + esc(a.id) + '"' + (isAdmin() ? '' : ' disabled')) + '</td></tr>'; '<td>' + sw(a.enabled, 'data-ad="' + esc(a.id) + '"' + (isAdmin() ? '' : ' disabled')) + '</td></tr>';
}).join('') + '</tbody></table>' : '<div class="empty">No DVB cards detected. Check <code>ls /dev/dvb</code>, the driver and firmware (for Si2168: <code>dvb-demod-si2168-*.fw</code>) and membership in group <code>video</code>.</div>'; }).join('') + '</tbody></table>' : '<div class="empty">No DVB cards detected. Check <code>ls /dev/dvb</code>, the driver and firmware (for Si2168: <code>dvb-demod-si2168-*.fw</code>) and membership in group <code>video</code>.</div>';
$$('[data-ad]').forEach(function (i) { i.addEventListener('change', function () { api('PUT', '/api/adapters/' + i.getAttribute('data-ad'), { enabled: i.checked }).then(adapters).catch(fail); }); }); $$('[data-ad]').forEach(function (i) { i.addEventListener('change', function () { api('PUT', '/api/adapters/' + i.getAttribute('data-ad'), { enabled: i.checked }).then(adapters).catch(fail); }); });
@@ -1416,7 +1418,7 @@
function pageAccess(view) { function pageAccess(view) {
view.innerHTML = head('Security', 'Access & sharing', 'Playlists for TVs, tokens, access control (ACL) and panel accounts.') + view.innerHTML = head('Security', 'Access & sharing', 'Playlists for TVs, tokens, access control (ACL) and panel accounts.') +
'<div class="panel"><header><h2>Playlists & EPG</h2></header><div id="links"></div></div>' + '<div class="panel"><header><h2>Playlists & EPG</h2></header><div id="links"></div></div>' +
'<div class="grid g2" style="margin-top:10px"><div class="panel"><header><h2>Access tokens</h2>' + (isAdmin() ? '<button class="btn small" id="tok-add">+ New token</button>' : '') + '</header><div id="tokens"></div>' + '<div class="grid g2" style="margin-top:10px"><div class="panel"><header><h2>Access tokens</h2>' + (isAdmin() ? '<span class="row"><button class="btn small" id="tok-pair">' + esc(T('Pair a TV')) + '</button><button class="btn small" id="tok-add">+ New token</button></span>' : '') + '</header><div id="tokens"></div>' +
'<p class="hint">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.</p></div>' + '<p class="hint">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.</p></div>' +
'<div class="panel"><header><h2>Panel users</h2>' + (isAdmin() ? '<button class="btn small" id="usr-add">+ New user</button>' : '') + '</header><div id="users"></div>' + '<div class="panel"><header><h2>Panel users</h2>' + (isAdmin() ? '<button class="btn small" id="usr-add">+ New user</button>' : '') + '</header><div id="users"></div>' +
'<div class="row" style="margin-top:10px"><button class="btn small" id="pw-change">Change my password</button></div></div></div>' + '<div class="row" style="margin-top:10px"><button class="btn small" id="pw-change">Change my password</button></div></div></div>' +
@@ -1507,6 +1509,7 @@
}); });
}); });
if (isAdmin()) { if (isAdmin()) {
$('#tok-pair').addEventListener('click', function () { location.hash = '#/pair'; });
$('#tok-add').addEventListener('click', function () { $('#tok-add').addEventListener('click', function () {
var body = modal('New token', '<div class="form-grid"><label class="full">Name<input name="name" placeholder="e.g. Living room Sony TV"></label><label class="full">Allowed networks (optional)<input name="cidrs" placeholder="e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net"></label></div><div class="modal-foot"><button class="btn primary" id="tok-save">Create</button></div>'); var body = modal('New token', '<div class="form-grid"><label class="full">Name<input name="name" placeholder="e.g. Living room Sony TV"></label><label class="full">Allowed networks (optional)<input name="cidrs" placeholder="e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net"></label></div><div class="modal-foot"><button class="btn primary" id="tok-save">Create</button></div>');
$('#tok-save', body).addEventListener('click', function () { $('#tok-save', body).addEventListener('click', function () {
@@ -1726,6 +1729,45 @@
app.cleanup.push(function () { release(); clearTimeout(beepTimer); if (audio) try { audio.close(); } catch (e) {} }); app.cleanup.push(function () { release(); clearTimeout(beepTimer); if (audio) try { audio.close(); } catch (e) {} });
} }
// ------------------------------------------------------------ TV PAIRING (QR code)
/** Opened from the QR code the simply-tv app shows (#/pair/CODE) or by typing the code. */
function pagePair(view, args) {
var code = (args[0] || '').toUpperCase();
view.innerHTML = head('Access', 'Pair a TV', 'The simply-tv app on the TV shows a QR code and a 6-character code. Confirming creates an access token for the TV – nothing has to be typed on the remote.') +
'<div class="panel pair-box" id="pair-box"></div>';
var box = $('#pair-box');
function ask() {
box.innerHTML = '<div class="form-grid"><label class="full">' + esc(T('Code shown on the TV')) + '<input id="pair-code" class="pair-code" maxlength="7" autocomplete="off" autocapitalize="characters" value="' + esc(code) + '"></label></div>' +
'<div class="modal-foot"><button class="btn primary" id="pair-next">' + esc(T('Continue')) + '</button></div>';
var go = function () { var c = $('#pair-code').value.replace(/[^a-z0-9]/gi, '').toUpperCase(); if (c.length === 6) location.hash = '#/pair/' + c; };
$('#pair-next').addEventListener('click', go);
$('#pair-code').addEventListener('keydown', function (e) { if (e.key === 'Enter') go(); });
$('#pair-code').focus();
}
if (!isAdmin()) { box.innerHTML = '<div class="alert err">' + esc(T('Only an administrator can pair devices.')) + '</div>'; return; }
if (!code) { ask(); return; }
api('GET', '/api/pair/' + encodeURIComponent(code)).then(function (p) {
if (p.confirmed) { box.innerHTML = '<div class="alert">' + esc(T('This TV is already paired – it finishes the setup by itself.')) + '</div>'; return; }
box.innerHTML = '<div class="kv"><span>' + esc(T('Device')) + '</span><span><b>' + esc(p.device) + '</b></span>' +
'<span>' + esc(T('Code')) + '</span><span class="mono">' + esc(p.code) + '</span>' +
'<span>' + esc(T('Address')) + '</span><span class="mono">' + esc(p.ip) + '</span></div>' +
'<div class="form-grid" style="margin-top:12px"><label>' + esc(T('Token name')) + '<input id="pair-name" value="' + esc(p.device) + '"></label>' +
'<label>' + esc(T('Allowed from (optional)')) + '<input id="pair-allow" placeholder="' + esc(T('e.g. 83.1.2.3, 10.8.0.0/24, myhome.ddns.net')) + '"></label></div>' +
'<p class="hint">' + esc(T('Check that the code matches the one on the TV screen. The token can be disabled or deleted any time in Access.')) + '</p>' +
'<div class="modal-foot"><a class="btn" href="#/access">' + esc(T('Cancel')) + '</a><button class="btn primary" id="pair-ok">' + ico('check') + esc(T('Pair this TV')) + '</button></div>';
$('#pair-ok').addEventListener('click', function () {
$('#pair-ok').disabled = true;
api('POST', '/api/pair/' + encodeURIComponent(code) + '/confirm', { name: $('#pair-name').value, allow_cidrs: $('#pair-allow').value }).then(function (r) {
box.innerHTML = '<div class="alert ok-alert">' + ico('check') + esc(T('Paired. The TV loads channels and the guide now – you can close this page.')) + ' (' + esc(r.name) + ')</div>';
}).catch(function (e) { $('#pair-ok').disabled = false; fail(e); });
});
}).catch(function (e) {
code = '';
ask();
box.insertAdjacentHTML('afterbegin', '<div class="alert err" style="margin-bottom:10px">' + esc(T(e.message)) + '</div>');
});
}
// ------------------------------------------------------------ STATISTICS // ------------------------------------------------------------ STATISTICS
function pageStats(view) { function pageStats(view) {
var days = +(SDVB_STORE.get('sdvb-statdays') || 7); var days = +(SDVB_STORE.get('sdvb-statdays') || 7);