commit 4cb9717db22cc3a5d945c5682431992e3f55b15f Author: Mateusz Gruszczyński Date: Tue Nov 17 16:47:14 2026 +0100 v0.8.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..775b00c --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.gradle/ +build/ +app/build/ +local.properties +dist/ +keystore/*.jks +keystore/keystore.properties +*.iml +.idea/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..df9e9a1 --- /dev/null +++ b/README.md @@ -0,0 +1,108 @@ +# simply-tv + +Android TV app for [simply-dvb](../simple-dvbt) (works with tvheadend too). It makes the DVB +server a **source of the TV's own live-TV app** (Android TV Input Framework): channels with +logos and the programme guide appear in the TV's channel list and guide, and playback runs in +the TV's player with hardware decoding (HEVC, AC-3/E-AC-3, MPEG-2…). + +* **Protocol**: tvheadend's HTSP (port 9982) for channels, EPG, recordings and tickets; streams + over HTTP (port 9981, `/stream/channelid/`), exactly like tvheadend clients. +* **Channels & logos**: synced into the TV database (Android `TvContract`), logos from the + server (`/imagecache/`) – no paid logo packs. +* **Programme guide**: 7 days, genres, descriptions; refreshed every hour and on demand. +* **Recording**: on the server (simply-dvb DVR). From the app (*Programme guide & recording*, + OK on a programme) and – where the TV app supports it – from the TV's own guide. Finished + recordings are listed in the app (*Recordings*: play, stop, delete) and in the TV's + recordings list. +* **Playback**: ExoPlayer (Media3) on the surface of the TV app; audio-track and DVB subtitle + selection from the TV's menu; recordings with seeking. +* **Own player** (*simply-tv player*): full screen, channel up/down and numbers on the remote, OK = channel list with logos and what's on, info banner with now/next. Works independently of the TV app – both can be used. +* Languages: English, Polish (follows the TV's language). + +Target: Android TV 8.0+ (tested target: Sony BRAVIA with Android TV 12). + +## Build + +Only Docker is needed: + +```sh +scripts/build-apk.sh # -> dist/simply-tv-.apk +``` + +The first build creates the builder image (JDK 17 + Android SDK, ~1.5 GB) and a signing key in +`keystore/`. **Keep the `keystore/` folder** (back it up): Android installs updates only when +they are signed with the same key. + +## Install on the TV + +1. TV: *Settings → System → About* – press *Build* 7 times (developer mode). +2. TV: *Settings → System → Developer options* – turn on *Network debugging* (*ADB debugging*). +3. Computer (same network): + ```sh + scripts/install-tv.sh # e.g. 192.168.1.50 + ``` + The first time the TV asks whether to allow this computer – choose *Always allow* and run the + command again if it stopped. + +## Pairing with a QR code + +On the setup screen enter only the server address and choose **Pair with QR code**. Scan the code with a phone, sign in to the simply-dvb panel and confirm – the TV receives its own access token, nothing has to be typed with the remote (alternatively type the 6-character code in the panel under *Access → Pair a TV*). + +## Several servers + +simply-tv keeps a list of servers (*Servers* on the start screen, also opened by the TV app's "set up channels"). For each server: + +* **Use in player** – makes it the active server for the own player, guide and recordings. In the player, open the channel list (OK) and press **left** to switch servers; the last channel is remembered per server. +* **TV app source on/off** – whether its channels are loaded into the TV's own live-TV app. Several servers can feed the TV app at once; the server name is shown as the channel's network. Switching a server off removes its channels (and recordings) from the TV app on the next sync. +* **Load channels into the TV app** syncs all enabled servers right away. + +## Start screen + +The player comes first: *Watch TV* has the focus, so OK opens it on the last channel. Under the title the screen shows that channel and what is on it right now, with a progress bar – read from the server (`/api/epg/events/grid`), refreshed when the programme ends. Below: Programme guide, Recordings, TV app (the TV's built-in live-TV app with the simply-tv channels), Servers and Settings; then the active server's state with a Sync button; at the bottom the remote's keys in the player. + +## On-screen display (OSD) + +On every channel change, and with INFO or the left arrow at any time, the player shows at the bottom: channel number, logo and name; small chips with the picture (Full HD 1920×1080 50 fps), audio (E-AC-3 5.1), signal and SNR from the server (green / amber / red) and the bitrate the TV actually receives, plus REC while the channel is being recorded; the clock and date; what is on **now** with its time, a progress bar, minutes left and a short description; and what was on **before**, what comes **next** and **later**. INFO / left again or BACK hides it. + +## Settings + +*Settings* on the start screen: OSD on channel change, display time (3–15 s), technical details and description in the OSD; the detailed tuner card on channel change (off by default – the OSD carries the main figures; BLUE still switches it during playback); tunnelled video; start with the TV; server management; version. The left column explains the highlighted option. + +## Player remote keys + +Up / CH+ – next channel, down / CH- – previous · digits – channel number · OK – channel list (left: other server, right: programme grid) · right arrow or GUIDE – programme grid · left arrow or INFO – OSD (and the tuner card if switched on) · RED / REC – record the current programme (again: stop) · GREEN – audio track · YELLOW – subtitles · BLUE – tuner card on/off · last-channel key – previous channel. + +**Programme grid** (also *Programme guide* on the start screen): channels down, time across, a "now" line and the details of the highlighted programme on top. Up/down – channel, left/right – programme, CH+/CH- – a page, OK – details with record / watch, RED – record or cancel, GREEN – back to now, BACK – close. Some Sony remotes keep the GUIDE key for the TV's own guide – the right arrow always works. + +The tuner card (top right, optional) shows the adapter, frequency, lock, three small charts – signal/SNR, server CPU (whole host and the simply-dvb process, needs simply-dvb 0.1.13+) and the stream bitrate actually received by the TV (multiplex bitrate below) – plus modulation/FEC, BER and error counters. + +**Smooth video:** *Tunnelled video playback* (*Settings*, on by default) lets the TV's own video pipeline decode and sync the picture – the same path the built-in tuner uses. If a channel shows no picture with it, switch it off. The tuner card's white line shows what the TV does with the stream: resolution, frames shown per second, dropped frames (red), buffer and decoder; the last line shows simply-dvb's driver timing (time of a signal statistics read and the longest pause in the stream). + +**Start with the TV:** *Start the player with the TV* (*Settings*) opens the own player on the last channel when the TV boots and when it wakes up from standby. Android only lets an app open a screen from the background with the *Display over other apps* permission – the app opens that settings screen; if the TV has none, grant it once from a computer: `adb shell appops set io.simplydvb.tv SYSTEM_ALERT_WINDOW allow`. The home screen also has a second tile, *simply-tv Live*, that goes straight into the player. The TV button on the remote always opens the TV's own TV app – simply-tv channels play there too (via the TV input). + +## First start + +**Easiest – QR code:** enter only the server address and choose *Pair with QR code*. Scan the code with a phone, sign in to the simply-dvb panel and confirm – the server creates an access token for the TV and the TV picks it up by itself (no typing of tokens on the remote). Without a phone: panel → Access → *Pair a TV* and type the 6-character code shown on the TV. + +Manually: + +1. simply-tv opens the server settings: address of the simply-dvb server, HTSP port (9982), + HTTP port (9981). In the local network no user/password is needed; from outside use any + user name and an **access token** as the password (simply-dvb panel → Access → tokens). +2. *Connect and load channels* – channels, logos and the guide are written to the TV. +3. Open the TV app (Sony: *TV* button / Inputs) and choose the **simply-tv** source. Channel + up/down, numbers and the guide button work like with the built-in tuner. + +## Layout + +``` +app/src/main/java/io/simplydvb/tv/ + htsp/ HTSMSG codec and HTSP client (hello, SHA-1 auth, request/response, async) + tif/ TvInputService (playback + recording sessions), EPG/channel sync, WorkManager job + player/ ExoPlayer setup for DVB MPEG-TS + ui/ start screen, settings, servers (also the TV input setup), guide, recordings, player with OSD +scripts/ build-apk.sh, install-tv.sh, docker/android.Dockerfile +``` + +Tests: `gradle :app:testDebugUnitTest` (HTSMSG codec); with +`SIMPLYTV_TEST_HOST= SIMPLYTV_TEST_PORT=9982` also against a running server. diff --git a/README.pl.md b/README.pl.md new file mode 100644 index 0000000..d41c75b --- /dev/null +++ b/README.pl.md @@ -0,0 +1,93 @@ +# simply-tv + +Aplikacja na Android TV dla [simply-dvb](../simple-dvbt) (działa też z tvheadend). Dodaje serwer +DVB jako **źródło we wbudowanej aplikacji TV telewizora** (Android TV Input Framework): kanały z +logotypami i program TV pojawiają się na liście kanałów i w przewodniku telewizora, a obraz +odtwarza odtwarzacz telewizora ze sprzętowym dekodowaniem (HEVC, AC-3/E-AC-3, MPEG-2…). + +* **Protokół**: HTSP tvheadend (port 9982) – kanały, EPG, nagrania i bilety (ticket); strumienie + po HTTP (port 9981, `/stream/channelid/`), dokładnie jak klienci tvheadend. +* **Kanały i logotypy**: zapisywane w bazie TV Androida (`TvContract`), logotypy z serwera + (`/imagecache/`) – bez płatnych pakietów. +* **Program TV**: 7 dni, gatunki, opisy; odświeżany co godzinę i na żądanie. +* **Nagrywanie**: na serwerze (DVR simply-dvb). Z aplikacji (*Program TV i nagrywanie*, OK na + audycji) oraz – jeśli aplikacja TV telewizora to obsługuje – z jej przewodnika. Gotowe nagrania + są w aplikacji (*Nagrania*: odtwórz, zatrzymaj, usuń) i na liście nagrań telewizora. +* **Odtwarzanie**: ExoPlayer (Media3) na powierzchni aplikacji TV; wybór ścieżki dźwiękowej i + napisów DVB z menu telewizora; nagrania z przewijaniem. +* **Własny odtwarzacz** (*Odtwarzacz simply-tv*): pełny ekran, kanał +/− i numery z pilota, OK = lista kanałów z logotypami i bieżącą audycją, pasek informacji z „teraz/następnie”. Działa niezależnie od aplikacji TV – można używać obu. +* Języki: angielski, polski (wg języka telewizora). + +Docelowo: Android TV 8.0+ (testowy cel: Sony BRAVIA z Android TV 12). + +## Budowanie + +Potrzebny jest tylko Docker: + +```sh +scripts/build-apk.sh # -> dist/simply-tv-.apk +``` + +Pierwsze budowanie tworzy obraz budujący (JDK 17 + Android SDK, ok. 1,5 GB) oraz klucz podpisu w +`keystore/`. **Zachowaj katalog `keystore/`** (zrób kopię): Android instaluje aktualizację tylko +wtedy, gdy jest podpisana tym samym kluczem. + +## Instalacja na telewizorze + +1. TV: *Ustawienia → System → Informacje* – naciśnij 7× *Kompilacja* (tryb dewelopera). +2. TV: *Ustawienia → System → Opcje programisty* – włącz *Debugowanie przez sieć* (*Debugowanie ADB*). +3. Komputer (ta sama sieć): + ```sh + scripts/install-tv.sh # np. 192.168.1.50 + ``` + Za pierwszym razem telewizor zapyta, czy zezwolić temu komputerowi – wybierz *Zawsze zezwalaj* + i uruchom polecenie ponownie, jeśli się zatrzymało. + +## Parowanie kodem QR + +Na ekranie konfiguracji wpisz tylko adres serwera i wybierz **Paruj kodem QR**. Zeskanuj kod telefonem, zaloguj się do panelu simply-dvb i zatwierdź – telewizor dostaje własny token dostępu, nic nie trzeba wpisywać pilotem (albo wpisz 6-znakowy kod w panelu: *Dostęp → Sparuj telewizor*). + +## Kilka serwerów + +simply-tv trzyma listę serwerów (*Serwery* na ekranie startowym, otwiera się też z „konfiguracji kanałów” w aplikacji TV). Dla każdego serwera: + +* **Używaj w odtwarzaczu** – serwer aktywny dla własnego odtwarzacza, przewodnika i nagrań. W odtwarzaczu otwórz listę kanałów (OK) i wciśnij **w lewo**, aby przełączyć serwer; ostatni kanał jest pamiętany osobno dla każdego serwera. +* **Źródło aplikacji TV wł./wył.** – czy kanały tego serwera trafiają do wbudowanej aplikacji TV telewizora. Kilka serwerów może zasilać ją jednocześnie; nazwa serwera widnieje jako sieć kanału. Wyłączenie serwera usuwa jego kanały (i nagrania) z aplikacji TV przy następnej synchronizacji. +* **Wczytaj kanały do aplikacji TV** od razu synchronizuje wszystkie włączone serwery. + +## Ekran startowy + +Najpierw odtwarzacz: *Oglądaj telewizję* ma fokus, więc OK otwiera go na ostatnim kanale. Pod tytułem widać ten kanał i to, co na nim teraz leci, z paskiem postępu – dane z serwera (`/api/epg/events/grid`), odświeżane po zakończeniu audycji. Niżej: Program TV, Nagrania, Aplikacja TV (wbudowana aplikacja telewizora z kanałami simply-tv), Serwery i Ustawienia; dalej stan aktywnego serwera z przyciskiem Synchronizuj, a na dole klawisze pilota w odtwarzaczu. + +## Informacje na ekranie (OSD) + +Przy każdej zmianie kanału, a przyciskiem INFO lub strzałką w lewo w dowolnej chwili, odtwarzacz pokazuje na dole: numer, logo i nazwę kanału; małe znaczniki z obrazem (Full HD 1920×1080 50 fps), dźwiękiem (E-AC-3 5.1), sygnałem i SNR z serwera (zielony / pomarańczowy / czerwony) oraz przepływnością faktycznie odbieraną przez telewizor, a także REC, gdy kanał jest nagrywany; zegar i datę; co leci **teraz** z godzinami, paskiem postępu, pozostałymi minutami i krótkim opisem; oraz co było **wcześniej**, co będzie **następnie** i **później**. Ponowne INFO / strzałka w lewo albo WSTECZ chowa OSD. + +## Ustawienia + +*Ustawienia* na ekranie startowym: OSD przy zmianie kanału, czas wyświetlania (3–15 s), szczegóły techniczne i opis w OSD; szczegółowa karta tunera przy zmianie kanału (domyślnie wyłączona – OSD pokazuje najważniejsze dane; NIEBIESKI nadal włącza ją podczas oglądania); tunelowanie wideo; start razem z telewizorem; zarządzanie serwerami; wersja. Lewa kolumna objaśnia zaznaczoną opcję. + +## Klawisze pilota w odtwarzaczu + +Góra / CH+ – następny kanał, dół / CH- – poprzedni · cyfry – numer kanału · OK – lista kanałów (w lewo: inny serwer, w prawo: siatka programu) · strzałka w prawo lub GUIDE – siatka programu · strzałka w lewo lub INFO – OSD (i karta tunera, jeśli włączona) · CZERWONY / REC – nagraj bieżącą audycję (ponownie: zatrzymaj) · ZIELONY – ścieżka dźwiękowa · ŻÓŁTY – napisy · NIEBIESKI – karta tunera wł./wył. · przycisk poprzedniego kanału. + +**Siatka programu** (także *Program TV* na ekranie startowym): kanały w pionie, czas w poziomie, linia „teraz” i szczegóły zaznaczonej audycji u góry. Góra/dół – kanał, lewo/prawo – audycja, CH+/CH- – strona, OK – szczegóły z nagrywaniem / oglądaniem, CZERWONY – nagraj lub anuluj, ZIELONY – powrót do „teraz”, WSTECZ – zamknij. Niektóre piloty Sony zostawiają przycisk GUIDE dla przewodnika telewizora – strzałka w prawo działa zawsze. + +Karta tunera (prawy górny róg, opcjonalna) pokazuje adapter, częstotliwość, synchronizację, trzy małe wykresy – sygnał/SNR, CPU serwera (cały host i proces simply-dvb, wymaga simply-dvb 0.1.13+) oraz przepływność strumienia faktycznie odbieranego przez telewizor (pod spodem przepływność multipleksu) – a także modulację/FEC, BER i liczniki błędów. + +**Płynny obraz:** *Tunelowanie wideo* (*Ustawienia*, domyślnie włączone) przekazuje dekodowanie i synchronizację obrazu do toru wideo telewizora – tego samego, którego używa wbudowany tuner. Jeśli na jakimś kanale nie ma wtedy obrazu, wyłącz je. Biała linia na karcie tunera pokazuje, co telewizor robi ze strumieniem: rozdzielczość, wyświetlane klatki na sekundę, gubione klatki (na czerwono), bufor i dekoder; ostatnia linia to czasy sterownika w simply-dvb (odczyt statystyk sygnału i najdłuższa przerwa w strumieniu). + +**Start razem z telewizorem:** *Uruchamiaj odtwarzacz z telewizorem* (*Ustawienia*) otwiera własny odtwarzacz na ostatnim kanale po starcie telewizora i po wybudzeniu ze stanu czuwania. Android pozwala otworzyć ekran z tła tylko z uprawnieniem *Wyświetlanie nad innymi aplikacjami* – aplikacja otwiera ten ekran ustawień; jeśli telewizor go nie ma, nadaj je raz z komputera: `adb shell appops set io.simplydvb.tv SYSTEM_ALERT_WINDOW allow`. Na ekranie głównym jest też drugi kafelek, *simply-tv Na żywo*, który od razu otwiera odtwarzacz. Przycisk TV na pilocie zawsze otwiera wbudowaną aplikację TV telewizora – kanały simply-tv też w niej działają (przez wejście TV). + +## Pierwsze uruchomienie + +**Najprościej – kod QR:** wpisz tylko adres serwera i wybierz *Paruj kodem QR*. Zeskanuj kod telefonem, zaloguj się do panelu simply-dvb i zatwierdź – serwer utworzy token dostępu dla telewizora, a telewizor sam go pobierze (bez wpisywania tokenu pilotem). Bez telefonu: panel → Dostęp → *Sparuj telewizor* i wpisz 6-znakowy kod z ekranu TV. + +Ręcznie: + +1. simply-tv otworzy ustawienia serwera: adres serwera simply-dvb, port HTSP (9982), port HTTP + (9981). W sieci lokalnej użytkownik i hasło nie są potrzebne; spoza domu dowolna nazwa + użytkownika i **token dostępu** jako hasło (panel simply-dvb → Dostęp → tokeny). +2. *Połącz i wczytaj kanały* – kanały, logotypy i program trafiają do telewizora. +3. Otwórz aplikację TV (Sony: przycisk *TV* / Wejścia) i wybierz źródło **simply-tv**. Kanał + +/−, numery i przycisk przewodnika działają jak przy wbudowanym tunerze. diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..e083696 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,68 @@ +import java.util.Properties + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +// Release signing: keystore/simply-tv.jks (created by scripts/build-apk.sh on the first build). +// Keep that file – Android only installs an update signed with the same key. +val signing = Properties().apply { + val f = rootProject.file("keystore/keystore.properties") + if (f.exists()) f.inputStream().use { load(it) } +} + +android { + namespace = "io.simplydvb.tv" + compileSdk = 34 + + defaultConfig { + applicationId = "io.simplydvb.tv" + minSdk = 26 + targetSdk = 34 + versionCode = 9 + versionName = "0.8.0" + } + + signingConfigs { + create("release") { + if (signing.isNotEmpty()) { + storeFile = rootProject.file(signing.getProperty("storeFile")) + storePassword = signing.getProperty("storePassword") + keyAlias = signing.getProperty("keyAlias") + keyPassword = signing.getProperty("keyPassword") + } + } + } + + buildTypes { + release { + isMinifyEnabled = false + signingConfig = if (signing.isNotEmpty()) signingConfigs.getByName("release") else signingConfigs.getByName("debug") + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { + jvmTarget = "17" + } + testOptions { + unitTests.isReturnDefaultValues = true + } + lint { + abortOnError = false + checkReleaseBuilds = false + } +} + +dependencies { + val media3 = "1.4.1" + implementation("androidx.media3:media3-exoplayer:$media3") + implementation("androidx.media3:media3-ui:$media3") + implementation("androidx.work:work-runtime:2.9.1") + implementation("com.google.zxing:core:3.5.3") + testImplementation("junit:junit:4.13.2") +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..3ff8e6b --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/io/simplydvb/tv/AutoStart.kt b/app/src/main/java/io/simplydvb/tv/AutoStart.kt new file mode 100644 index 0000000..ef4b366 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/AutoStart.kt @@ -0,0 +1,136 @@ +package io.simplydvb.tv + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.Service +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.content.pm.ServiceInfo +import android.net.Uri +import android.os.Build +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.provider.Settings +import android.util.Log +import io.simplydvb.tv.ui.LiveActivity + +/** + * Optional autostart of the own player: when the TV starts and when it wakes up from + * standby (Sony TVs rarely boot – the power button only switches the screen). + * + * Android 10+ lets an app open a screen from the background only with the + * "Display over other apps" permission, so that is required. + */ +object AutoStart { + private const val TAG = "simply-tv" + private fun prefs(ctx: Context) = ctx.getSharedPreferences("live", Context.MODE_PRIVATE) + + fun enabled(ctx: Context) = prefs(ctx).getBoolean("autostart", false) + + fun setEnabled(ctx: Context, on: Boolean) { + prefs(ctx).edit().putBoolean("autostart", on).apply() + apply(ctx) + } + + fun allowed(ctx: Context) = Settings.canDrawOverlays(ctx) + + /** Opens the system screen for "Display over other apps"; false when the TV has none. */ + fun requestPermission(ctx: Context): Boolean = try { + ctx.startActivity( + Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + ctx.packageName)) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) + true + } catch (_: Exception) { + false + } + + /** Starts or stops the watcher service according to the setting. */ + fun apply(ctx: Context) { + val i = Intent(ctx, WakeService::class.java) + if (enabled(ctx)) { + try { + ctx.startForegroundService(i) + } catch (e: Exception) { + Log.w(TAG, "autostart service: $e") + } + } else { + ctx.stopService(i) + } + } + + fun launchPlayer(ctx: Context, reason: String) { + if (!enabled(ctx) || ServerConfig.all(ctx).none { it.configured }) return + if (!allowed(ctx)) { + Log.w(TAG, "autostart ($reason): no 'display over other apps' permission") + return + } + Log.i(TAG, "autostart ($reason)") + try { + ctx.startActivity( + Intent(ctx, LiveActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), + ) + } catch (e: Exception) { + Log.w(TAG, "autostart: $e") + } + } +} + +/** TV started: start the watcher and open the player. */ +class BootReceiver : BroadcastReceiver() { + override fun onReceive(ctx: Context, intent: Intent) { + if (!AutoStart.enabled(ctx)) return + AutoStart.apply(ctx) + if (intent.action == Intent.ACTION_MY_PACKAGE_REPLACED) return + // let the launcher come up first, otherwise it covers the player + Handler(Looper.getMainLooper()).postDelayed({ AutoStart.launchPlayer(ctx, "boot") }, 4000) + } +} + +/** + * Keeps a screen-on listener (it can only be registered at run time) so the player also + * opens when the TV wakes up from standby. + */ +class WakeService : Service() { + private val main = Handler(Looper.getMainLooper()) + private val receiver = object : BroadcastReceiver() { + override fun onReceive(ctx: Context, intent: Intent) { + main.removeCallbacksAndMessages(null) + main.postDelayed({ AutoStart.launchPlayer(ctx, "wake") }, 2500) + } + } + + override fun onCreate() { + super.onCreate() + val nm = getSystemService(NotificationManager::class.java) + nm.createNotificationChannel(NotificationChannel("autostart", getString(R.string.autostart), NotificationManager.IMPORTANCE_MIN)) + val n = Notification.Builder(this, "autostart") + .setSmallIcon(R.drawable.ic_tv) + .setContentTitle(getString(R.string.autostart)) + .build() + if (Build.VERSION.SDK_INT >= 34) { + startForeground(1, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) + } else { + startForeground(1, n) + } + registerReceiver(receiver, IntentFilter(Intent.ACTION_SCREEN_ON)) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (!AutoStart.enabled(this)) stopSelf() + return START_STICKY + } + + override fun onDestroy() { + unregisterReceiver(receiver) + main.removeCallbacksAndMessages(null) + super.onDestroy() + } + + override fun onBind(intent: Intent?): IBinder? = null +} diff --git a/app/src/main/java/io/simplydvb/tv/Dvr.kt b/app/src/main/java/io/simplydvb/tv/Dvr.kt new file mode 100644 index 0000000..d683b5d --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/Dvr.kt @@ -0,0 +1,33 @@ +package io.simplydvb.tv + +import android.content.Context +import io.simplydvb.tv.htsp.HtsMsg +import io.simplydvb.tv.tif.HDvr +import io.simplydvb.tv.tif.HEvent + +/** Recording requests on the server (shared by the guide and the player). */ +object Dvr { + fun record(ctx: Context, e: HEvent): HDvr { + val r = Server.session(ctx) { it.request(HtsMsg.method("addDvrEntry").put("eventId", e.id)) } + if (r.int("success") != 1) throw IllegalStateException(r.str("error") ?: "rejected") + return HDvr(r.long("id") ?: 0, e.channelId, "", e.title, "", e.start, e.stop, "scheduled", 0) + } + + /** Records a channel from now on without programme data. */ + fun recordNow(ctx: Context, channelId: Long, title: String, seconds: Long): HDvr { + val now = System.currentTimeMillis() / 1000 + val r = Server.session(ctx) { + it.request( + HtsMsg.method("addDvrEntry").put("channelId", channelId).put("start", now) + .put("stop", now + seconds).put("title", title), + ) + } + if (r.int("success") != 1) throw IllegalStateException(r.str("error") ?: "rejected") + return HDvr(r.long("id") ?: 0, channelId, "", title, "", now, now + seconds, "recording", 0) + } + + fun cancel(ctx: Context, r: HDvr) { + val method = if (r.state == "recording") "stopDvrEntry" else "cancelDvrEntry" + Server.session(ctx) { it.request(HtsMsg.method(method).put("id", r.id)) } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/Prefs.kt b/app/src/main/java/io/simplydvb/tv/Prefs.kt new file mode 100644 index 0000000..dc5de51 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/Prefs.kt @@ -0,0 +1,28 @@ +package io.simplydvb.tv + +import android.content.Context + +/** Player and app settings (shared preferences "live", as before). */ +object Prefs { + private fun p(ctx: Context) = ctx.getSharedPreferences("live", Context.MODE_PRIVATE) + + /** OSD with the programme info on every channel change. */ + fun osdOnZap(ctx: Context) = p(ctx).getBoolean("osd_on_zap", true) + + /** How long the OSD stays (seconds). */ + fun osdSeconds(ctx: Context) = p(ctx).getInt("osd_seconds", 6) + val OSD_SECONDS = intArrayOf(3, 6, 10, 15) + + /** Resolution, signal and stream bitrate in the OSD. */ + fun osdTech(ctx: Context) = p(ctx).getBoolean("osd_tech", true) + + /** Programme description in the OSD. */ + fun osdDescription(ctx: Context) = p(ctx).getBoolean("osd_desc", true) + + /** Detailed tuner card (top right) on every channel change. */ + fun tunerCard(ctx: Context) = p(ctx).getBoolean("tuner_info", false) + + fun set(ctx: Context, key: String, value: Boolean) = p(ctx).edit().putBoolean(key, value).apply() + fun set(ctx: Context, key: String, value: Int) = p(ctx).edit().putInt(key, value).apply() + fun bool(ctx: Context, key: String, def: Boolean) = p(ctx).getBoolean(key, def) +} diff --git a/app/src/main/java/io/simplydvb/tv/Server.kt b/app/src/main/java/io/simplydvb/tv/Server.kt new file mode 100644 index 0000000..0b48eb0 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/Server.kt @@ -0,0 +1,223 @@ +package io.simplydvb.tv + +import android.content.Context +import android.net.Uri +import io.simplydvb.tv.htsp.HtsMsg +import io.simplydvb.tv.htsp.HtspClient +import org.json.JSONArray +import org.json.JSONObject +import java.util.UUID + +/** + * One simply-dvb (or tvheadend) server. The app keeps a list: the *active* one is used by the + * player, guide and recordings screens; every server with [tvInput] on feeds its channels into + * the TV's own TV app. + */ +data class ServerConfig( + val host: String, + val htspPort: Int, + val httpPort: Int, + val username: String, + val password: String, + val id: String = "", + val name: String = "", + val tvInput: Boolean = true, +) { + val configured get() = host.isNotBlank() + val httpBase get() = "http://${if (host.contains(':') && !host.startsWith("[")) "[$host]" else host}:$httpPort" + val label get() = name.ifBlank { host } + + fun toJson(): JSONObject = JSONObject() + .put("id", id).put("name", name).put("host", host) + .put("htsp_port", htspPort).put("http_port", httpPort) + .put("username", username).put("password", password).put("tv_input", tvInput) + + companion object { + private const val PREFS = "server" + + private fun fromJson(o: JSONObject) = ServerConfig( + host = o.optString("host"), + htspPort = o.optInt("htsp_port", 9982), + httpPort = o.optInt("http_port", 9981), + username = o.optString("username"), + password = o.optString("password"), + id = o.optString("id"), + name = o.optString("name"), + tvInput = o.optBoolean("tv_input", true), + ) + + fun empty() = ServerConfig("", 9982, 9981, "", "") + + /** All servers (migrates the single server of version 0.3 on first use). */ + fun all(ctx: Context): List { + val p = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + val raw = p.getString("servers", null) + if (raw == null) { + val host = p.getString("host", "") ?: "" + if (host.isEmpty()) return emptyList() + val legacy = ServerConfig( + host = host, + htspPort = p.getInt("htsp_port", 9982), + httpPort = p.getInt("http_port", 9981), + username = p.getString("username", "") ?: "", + password = p.getString("password", "") ?: "", + id = "s1", + ) + write(ctx, listOf(legacy)) + p.edit().putString("active", legacy.id).apply() + return listOf(legacy) + } + val a = try { + JSONArray(raw) + } catch (_: Exception) { + JSONArray() + } + return (0 until a.length()).mapNotNull { a.optJSONObject(it)?.let(::fromJson) }.filter { it.id.isNotEmpty() } + } + + private fun write(ctx: Context, list: List) { + val a = JSONArray() + list.forEach { a.put(it.toJson()) } + ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString("servers", a.toString()).apply() + } + + fun byId(ctx: Context, id: String): ServerConfig? = all(ctx).firstOrNull { it.id == id } + + fun activeId(ctx: Context): String? { + val list = all(ctx) + val id = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("active", null) + return (list.firstOrNull { it.id == id } ?: list.firstOrNull())?.id + } + + /** The server used by the player, guide and recordings screens. */ + fun load(ctx: Context): ServerConfig = activeId(ctx)?.let { byId(ctx, it) } ?: empty() + + fun setActive(ctx: Context, id: String) { + ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString("active", id).apply() + } + + /** Adds (no id yet) or replaces a server; returns it with its id. */ + fun save(ctx: Context, c: ServerConfig): ServerConfig { + val list = all(ctx).toMutableList() + val saved = c.copy( + id = c.id.ifEmpty { UUID.randomUUID().toString().take(8) }, + host = c.host.trim(), + username = c.username.trim(), + name = c.name.trim(), + ) + val i = list.indexOfFirst { it.id == saved.id } + if (i >= 0) list[i] = saved else list.add(saved) + write(ctx, list) + if (list.size == 1 || activeId(ctx) == null) setActive(ctx, saved.id) + return saved + } + + fun delete(ctx: Context, id: String) { + write(ctx, all(ctx).filter { it.id != id }) + if (ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString("active", null) == id) { + all(ctx).firstOrNull()?.let { setActive(ctx, it.id) } + } + } + } +} + +/** Helpers on top of the HTSP client for the things the app needs. */ +object Server { + /** Opens a connection to [c] (default: the active server), runs [block] and closes it. */ + fun session(ctx: Context, c: ServerConfig = ServerConfig.load(ctx), block: (HtspClient) -> T): T { + if (!c.configured) throw IllegalStateException(ctx.getString(R.string.not_configured)) + HtspClient(c.host, c.htspPort, c.username, c.password).use { client -> + client.connect() + return block(client) + } + } + + /** + * Playback address of a channel or a recording: the server hands out a path and a + * ticket (HTSP getTicket) that authorizes the HTTP stream without a password. + */ + fun ticketUrl( + ctx: Context, + client: HtspClient, + channelId: Long? = null, + dvrId: Long? = null, + c: ServerConfig = ServerConfig.load(ctx), + ): Uri { + val req = HtsMsg.method("getTicket") + if (channelId != null) req["channelId"] = channelId + if (dvrId != null) req["dvrId"] = dvrId + val r = client.request(req) + val path = r.str("path") ?: throw IllegalStateException("no stream path") + val ticket = r.str("ticket") ?: "" + val b = Uri.parse(c.httpBase + (if (path.startsWith("/")) path else "/$path")).buildUpon() + if (ticket.isNotEmpty()) b.appendQueryParameter("ticket", ticket) + return b.build() + } + + /** GET on the server's HTTP API (tvheadend-compatible JSON), with the token as password. */ + fun getJson(ctx: Context, pathAndQuery: String, c: ServerConfig = ServerConfig.load(ctx)): JSONObject { + val conn = java.net.URL(c.httpBase + pathAndQuery).openConnection() as java.net.HttpURLConnection + conn.connectTimeout = 3000 + conn.readTimeout = 5000 + if (c.password.isNotEmpty()) { + val auth = android.util.Base64.encodeToString( + "${c.username.ifEmpty { "simply-tv" }}:${c.password}".toByteArray(), android.util.Base64.NO_WRAP, + ) + conn.setRequestProperty("Authorization", "Basic $auth") + } + try { + if (conn.responseCode != 200) throw IllegalStateException("HTTP ${conn.responseCode}") + return JSONObject(conn.inputStream.use { it.readBytes().toString(Charsets.UTF_8) }) + } finally { + conn.disconnect() + } + } + + /** Channel logo address (`channelIcon` is relative, e.g. imagecache/12). */ + /** + * Downloads a small file (channel logo). Follows redirects itself – also from http to + * https, which HttpURLConnection refuses to do – because the server redirects to the + * original address of logos that point to other websites. + */ + fun download(url: String, maxBytes: Int = 3_000_000): ByteArray? { + var u = java.net.URL(url) + for (hop in 0 until 5) { + val c = u.openConnection() as java.net.HttpURLConnection + c.instanceFollowRedirects = false + c.connectTimeout = 5000 + c.readTimeout = 10000 + c.setRequestProperty("User-Agent", "simply-tv (Android TV)") + try { + val code = c.responseCode + if (code in 300..399) { + val loc = c.getHeaderField("Location") ?: return null + u = java.net.URL(u, loc) + continue + } + if (code != 200) return null + val out = java.io.ByteArrayOutputStream() + c.inputStream.use { inp -> + val buf = ByteArray(16384) + while (true) { + val n = inp.read(buf) + if (n < 0) break + out.write(buf, 0, n) + if (out.size() > maxBytes) return null + } + } + return out.toByteArray().takeIf { it.isNotEmpty() } + } finally { + c.disconnect() + } + } + return null + } + + fun iconUrl(ctx: Context, icon: String, c: ServerConfig = ServerConfig.load(ctx)): String? { + if (icon.isBlank()) return null + if (icon.startsWith("http://") || icon.startsWith("https://")) return icon + val sep = if (icon.startsWith("/")) "" else "/" + val auth = if (c.password.isNotEmpty()) "?ticket=" + Uri.encode(c.password) else "" + return c.httpBase + sep + icon + auth + } +} diff --git a/app/src/main/java/io/simplydvb/tv/htsp/HtsMsg.kt b/app/src/main/java/io/simplydvb/tv/htsp/HtsMsg.kt new file mode 100644 index 0000000..d287499 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/htsp/HtsMsg.kt @@ -0,0 +1,168 @@ +package io.simplydvb.tv.htsp + +import java.io.ByteArrayOutputStream +import java.nio.charset.StandardCharsets + +/** + * HTSMSG – the binary message format of tvheadend's HTSP protocol. + * + * Every field: type (1 byte), name length (1), data length (4, big endian), name, data. + * Types: 1 = map, 2 = signed 64-bit integer (little endian, minimal bytes), 3 = string, + * 4 = binary, 5 = list (fields without names). A message on the wire is a 4-byte + * big-endian length followed by the fields of the root map. + */ +class HtsMsg(val fields: LinkedHashMap = LinkedHashMap()) { + + operator fun set(name: String, value: Any) { + fields[name] = value + } + + fun put(name: String, value: Any): HtsMsg { + fields[name] = value + return this + } + + val method: String? get() = str("method") + + fun str(name: String): String? = when (val v = fields[name]) { + is String -> v + is Long -> v.toString() + else -> null + } + + fun long(name: String): Long? = when (val v = fields[name]) { + is Long -> v + is String -> v.toLongOrNull() + else -> null + } + + fun int(name: String): Int? = long(name)?.toInt() + + fun bin(name: String): ByteArray? = fields[name] as? ByteArray + + fun map(name: String): HtsMsg? = fields[name] as? HtsMsg + + @Suppress("UNCHECKED_CAST") + fun list(name: String): List = (fields[name] as? List) ?: emptyList() + + fun maps(name: String): List = list(name).filterIsInstance() + + fun has(name: String) = fields.containsKey(name) + + override fun toString(): String = fields.entries.joinToString(", ", "{", "}") { (k, v) -> + "$k=" + when (v) { + is ByteArray -> "<${v.size} bytes>" + is String -> if (v.length > 60) "\"${v.take(60)}…\"" else "\"$v\"" + else -> v.toString() + } + } + + /** Wire form: length prefix + body. */ + fun encode(): ByteArray { + val body = encodeFields(fields.entries.map { it.key to it.value }) + val out = ByteArrayOutputStream(body.size + 4) + writeU32(out, body.size.toLong()) + out.write(body) + return out.toByteArray() + } + + companion object { + private const val MAP = 1 + private const val S64 = 2 + private const val STR = 3 + private const val BIN = 4 + private const val LIST = 5 + + fun method(name: String) = HtsMsg().put("method", name) + + private fun writeU32(out: ByteArrayOutputStream, v: Long) { + out.write(((v shr 24) and 0xff).toInt()) + out.write(((v shr 16) and 0xff).toInt()) + out.write(((v shr 8) and 0xff).toInt()) + out.write((v and 0xff).toInt()) + } + + private fun s64(v: Long): ByteArray { + if (v == 0L) return ByteArray(0) + val bytes = ArrayList(8) + var x = v + // little endian, minimal length (negative numbers keep all 8 bytes) + for (i in 0 until 8) { + bytes.add((x and 0xff).toByte()) + x = x ushr 8 + if (x == 0L && v > 0) break + } + return bytes.toByteArray() + } + + private fun encodeFields(entries: List>): ByteArray { + val out = ByteArrayOutputStream() + for ((name, value) in entries) { + val (type, data) = when (value) { + is HtsMsg -> MAP to encodeFields(value.fields.entries.map { it.key to it.value }) + is Long -> S64 to s64(value) + is Int -> S64 to s64(value.toLong()) + is Boolean -> S64 to s64(if (value) 1 else 0) + is String -> STR to value.toByteArray(StandardCharsets.UTF_8) + is ByteArray -> BIN to value + is List<*> -> LIST to encodeFields(value.filterNotNull().map { null to it }) + else -> STR to value.toString().toByteArray(StandardCharsets.UTF_8) + } + val n = name?.toByteArray(StandardCharsets.UTF_8) ?: ByteArray(0) + out.write(type) + out.write(n.size) + writeU32(out, data.size.toLong()) + out.write(n) + out.write(data) + } + return out.toByteArray() + } + + /** Decodes a message body (without the 4-byte length). */ + fun decode(buf: ByteArray, off: Int = 0, len: Int = buf.size): HtsMsg { + val m = HtsMsg() + decodeInto(buf, off, len) { name, v -> m.fields[name ?: ""] = v } + return m + } + + private fun decodeList(buf: ByteArray, off: Int, len: Int): List { + val l = ArrayList() + decodeInto(buf, off, len) { _, v -> l.add(v) } + return l + } + + private fun decodeInto(buf: ByteArray, off: Int, len: Int, sink: (String?, Any) -> Unit) { + var p = off + val end = off + len + while (p + 6 <= end) { + val type = buf[p].toInt() and 0xff + val nlen = buf[p + 1].toInt() and 0xff + val dlen = ((buf[p + 2].toLong() and 0xff) shl 24) or + ((buf[p + 3].toLong() and 0xff) shl 16) or + ((buf[p + 4].toLong() and 0xff) shl 8) or + (buf[p + 5].toLong() and 0xff) + p += 6 + if (p + nlen + dlen > end) break + val name = if (nlen > 0) String(buf, p, nlen, StandardCharsets.UTF_8) else null + p += nlen + val d = dlen.toInt() + val v: Any = when (type) { + MAP -> decode(buf, p, d) + S64 -> { + var x = 0L + for (i in 0 until minOf(d, 8)) x = x or ((buf[p + i].toLong() and 0xff) shl (8 * i)) + // tvheadend writes positive numbers with the minimal number of bytes + // (no sign extension) and negative ones with all 8 bytes + x + } + STR -> String(buf, p, d, StandardCharsets.UTF_8) + BIN -> buf.copyOfRange(p, p + d) + LIST -> decodeList(buf, p, d) + else -> buf.copyOfRange(p, p + d) + } + sink(name, v) + p += d + } + } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/htsp/HtspClient.kt b/app/src/main/java/io/simplydvb/tv/htsp/HtspClient.kt new file mode 100644 index 0000000..7f93d5d --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/htsp/HtspClient.kt @@ -0,0 +1,148 @@ +package io.simplydvb.tv.htsp + +import android.util.Log +import java.io.BufferedInputStream +import java.io.Closeable +import java.io.DataInputStream +import java.io.IOException +import java.io.OutputStream +import java.net.InetSocketAddress +import java.net.Socket +import java.security.MessageDigest +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +class HtspException(msg: String) : IOException(msg) + +/** + * Minimal HTSP client (tvheadend protocol, as served by simply-dvb on port 9982): + * hello + SHA-1 digest authentication, request/response matched by `seq`, and + * asynchronous messages (channelAdd, eventAdd, dvrEntryAdd…) delivered to [onAsync]. + */ +class HtspClient( + private val host: String, + private val port: Int, + private val username: String, + private val password: String, +) : Closeable { + private val socket = Socket() + private lateinit var out: OutputStream + private val seq = AtomicInteger(1) + private val pending = ConcurrentHashMap>() + @Volatile private var closed = false + private var reader: Thread? = null + + /** Called on the reader thread for messages that are not responses. */ + @Volatile var onAsync: ((HtsMsg) -> Unit)? = null + var serverName: String = "" + private set + var serverVersion: String = "" + private set + var htspVersion: Int = 0 + private set + + fun connect(timeoutMs: Int = 6000): HtspClient { + socket.connect(InetSocketAddress(host, port), timeoutMs) + socket.tcpNoDelay = true + socket.soTimeout = 0 + out = socket.getOutputStream() + val input = DataInputStream(BufferedInputStream(socket.getInputStream(), 64 * 1024)) + reader = Thread({ readLoop(input) }, "htsp-reader").apply { + isDaemon = true + start() + } + val hello = request( + HtsMsg.method("hello") + .put("htspversion", 34L) + .put("clientname", "simply-tv") + .put("clientversion", "0.1"), + ) + serverName = hello.str("servername") ?: "" + serverVersion = hello.str("serverversion") ?: "" + htspVersion = hello.int("htspversion") ?: 0 + if (username.isNotEmpty() || password.isNotEmpty()) { + val challenge = hello.bin("challenge") ?: ByteArray(0) + val sha = MessageDigest.getInstance("SHA-1") + sha.update(password.toByteArray(Charsets.UTF_8)) + sha.update(challenge) + val r = request( + HtsMsg.method("authenticate") + .put("username", username.ifEmpty { "simply-tv" }) + .put("digest", sha.digest()), + ) + if (r.int("noaccess") == 1) throw HtspException("access denied – check the user name and password (token)") + } + return this + } + + /** Sends a request and waits for its response. */ + fun request(msg: HtsMsg, timeoutSec: Long = 20): HtsMsg { + if (closed) throw HtspException("connection closed") + val id = seq.getAndIncrement() + val q = LinkedBlockingQueue(1) + pending[id] = q + msg["seq"] = id.toLong() + try { + val bytes = msg.encode() + synchronized(this) { + out.write(bytes) + out.flush() + } + val r = q.poll(timeoutSec, TimeUnit.SECONDS) + ?: throw HtspException("no answer to ${msg.method} from the server") + if (r.has("__closed")) throw HtspException("connection closed") + r.str("error")?.let { err -> + if (r.int("noaccess") == 1) throw HtspException("access denied: $err") + } + return r + } finally { + pending.remove(id) + } + } + + private fun readLoop(input: DataInputStream) { + try { + while (!closed) { + val len = input.readInt() + if (len < 0 || len > 64 * 1024 * 1024) throw HtspException("bad message length $len") + val buf = ByteArray(len) + input.readFully(buf) + val m = HtsMsg.decode(buf) + val s = m.int("seq") + val q = if (s != null) pending[s] else null + if (q != null) { + q.offer(m) + } else { + try { + onAsync?.invoke(m) + } catch (e: Exception) { + Log.w(TAG, "async handler failed", e) + } + } + } + } catch (e: Exception) { + if (!closed) Log.i(TAG, "connection ended: ${e.message}") + } finally { + closed = true + // wake up everybody waiting for an answer + for (q in pending.values) q.offer(HtsMsg().put("__closed", 1L)) + onAsync?.invoke(HtsMsg.method("__disconnected")) + } + } + + val isClosed get() = closed + + override fun close() { + closed = true + try { + socket.close() + } catch (_: IOException) { + } + } + + companion object { + private const val TAG = "HtspClient" + } +} diff --git a/app/src/main/java/io/simplydvb/tv/player/Players.kt b/app/src/main/java/io/simplydvb/tv/player/Players.kt new file mode 100644 index 0000000..0f317b0 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/player/Players.kt @@ -0,0 +1,103 @@ +package io.simplydvb.tv.player + +import android.content.Context +import androidx.annotation.OptIn +import androidx.media3.common.AudioAttributes +import androidx.media3.common.C +import androidx.media3.common.util.UnstableApi +import androidx.media3.datasource.DataSource +import androidx.media3.datasource.DataSpec +import androidx.media3.datasource.DefaultHttpDataSource +import androidx.media3.datasource.TransferListener +import java.util.concurrent.atomic.AtomicLong +import androidx.media3.exoplayer.DefaultLoadControl +import androidx.media3.exoplayer.DefaultRenderersFactory +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.source.DefaultMediaSourceFactory +import androidx.media3.exoplayer.trackselection.DefaultTrackSelector +import androidx.media3.extractor.DefaultExtractorsFactory +import androidx.media3.extractor.ts.DefaultTsPayloadReaderFactory +import androidx.media3.extractor.ts.TsExtractor + +/** Counts bytes received by the player (the real stream bitrate shown in the tuner card). */ +@OptIn(UnstableApi::class) +class ByteMeter : TransferListener { + private val total = AtomicLong() + private var lastBytes = 0L + private var lastAt = 0L + + override fun onTransferInitializing(source: DataSource, dataSpec: DataSpec, isNetwork: Boolean) {} + override fun onTransferStart(source: DataSource, dataSpec: DataSpec, isNetwork: Boolean) {} + override fun onTransferEnd(source: DataSource, dataSpec: DataSpec, isNetwork: Boolean) {} + override fun onBytesTransferred(source: DataSource, dataSpec: DataSpec, isNetwork: Boolean, bytesTransferred: Int) { + if (isNetwork) total.addAndGet(bytesTransferred.toLong()) + } + + /** Bytes received so far (for callers that keep their own window). */ + fun total(): Long = total.get() + + /** Bits per second since the previous call (null on the first call). */ + @Synchronized + fun rate(): Double? { + val now = android.os.SystemClock.elapsedRealtime() + val b = total.get() + val r = if (lastAt == 0L || now <= lastAt) null else (b - lastBytes) * 8000.0 / (now - lastAt) + lastAt = now + lastBytes = b + return r + } +} + +/** ExoPlayer set up for DVB MPEG-TS streams (live channels and recordings). */ +object Players { + @OptIn(UnstableApi::class) + /** Tunnelled playback (the TV's own A/V sync path) – on by default for the own player. */ + fun tunneling(ctx: Context) = ctx.getSharedPreferences("live", Context.MODE_PRIVATE).getBoolean("tunneling", true) + + fun create(ctx: Context, live: Boolean, meter: ByteMeter? = null, tunneling: Boolean = false): ExoPlayer { + val extractors = DefaultExtractorsFactory() + .setTsExtractorMode(TsExtractor.MODE_SINGLE_PMT) + .setTsExtractorFlags( + DefaultTsPayloadReaderFactory.FLAG_ALLOW_NON_IDR_KEYFRAMES or + DefaultTsPayloadReaderFactory.FLAG_DETECT_ACCESS_UNITS, + ) + .setTsExtractorTimestampSearchBytes(1_500 * 188) + val http = DefaultHttpDataSource.Factory() + .setUserAgent("simply-tv (Android TV)") + .setConnectTimeoutMs(8000) + .setReadTimeoutMs(15000) + .setAllowCrossProtocolRedirects(true) + .setTransferListener(meter) + val renderers = DefaultRenderersFactory(ctx) + .setEnableDecoderFallback(true) + .setExtensionRendererMode(DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON) + // live TV: start quickly, keep a few seconds in reserve against network hiccups + val load = DefaultLoadControl.Builder() + .setBufferDurationsMs( + if (live) 3000 else 15000, + if (live) 20000 else 50000, + if (live) 1500 else 2500, + if (live) 3000 else 5000, + ) + .build() + // Tunnelling hands decoding, A/V sync and frame release to the TV's video pipeline + // (what the TV's own tuner uses). Without it, 50i broadcasts on some TV SoCs drop + // frames while the audio keeps running. It falls back automatically when the + // device or the format does not support it. + val selector = DefaultTrackSelector(ctx).apply { + setParameters(buildUponParameters().setTunnelingEnabled(tunneling)) + } + return ExoPlayer.Builder(ctx, renderers) + .setTrackSelector(selector) + .setMediaSourceFactory(DefaultMediaSourceFactory(http, extractors)) + .setLoadControl(load) + .setAudioAttributes( + AudioAttributes.Builder() + .setUsage(C.USAGE_MEDIA) + .setContentType(C.AUDIO_CONTENT_TYPE_MOVIE) + .build(), + false, + ) + .build() + } +} diff --git a/app/src/main/java/io/simplydvb/tv/tif/EpgSync.kt b/app/src/main/java/io/simplydvb/tv/tif/EpgSync.kt new file mode 100644 index 0000000..e708dc8 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/tif/EpgSync.kt @@ -0,0 +1,388 @@ +package io.simplydvb.tv.tif + +import android.content.ComponentName +import android.content.ContentProviderOperation +import android.content.ContentUris +import android.content.ContentValues +import android.content.Context +import android.media.tv.TvContract +import android.net.Uri +import android.util.Log +import io.simplydvb.tv.Server +import io.simplydvb.tv.htsp.HtsMsg +import java.net.HttpURLConnection +import java.net.URL +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +data class HChannel(val id: Long, val number: Int, val name: String, val icon: String, val nextEventId: Long?) +data class HEvent( + val id: Long, + val channelId: Long, + val start: Long, + val stop: Long, + val title: String, + val summary: String, + val description: String, + val contentType: Int?, + val ageRating: Int?, +) +data class HDvr( + val id: Long, + val channelId: Long?, + val channelName: String, + val title: String, + val description: String, + val start: Long, + val stop: Long, + val state: String, + val size: Long, +) + +/** Everything the server announced in one metadata sync. */ +class Snapshot(val channels: List, val events: List, val dvr: List) + +/** + * Copies channels, logos, the programme guide and recordings from the server into + * Android's TV database (TvContract), where the TV's own player and guide read them. + */ +object EpgSync { + private const val TAG = "EpgSync" + + fun inputId(ctx: Context): String = + TvContract.buildInputId(ComponentName(ctx, SimplyTvInputService::class.java)) + + /** Reads channels, EPG (7 days) and recordings over HTSP. */ + fun fetch( + ctx: Context, + epgDays: Int = 7, + withEpg: Boolean = true, + server: io.simplydvb.tv.ServerConfig = io.simplydvb.tv.ServerConfig.load(ctx), + ): Snapshot = Server.session(ctx, server) { client -> + val channels = ArrayList() + val events = ArrayList() + val dvr = ArrayList() + val done = CountDownLatch(1) + client.onAsync = { m -> + when (m.method) { + "channelAdd" -> channels.add( + HChannel( + id = m.long("channelId") ?: 0, + number = m.int("channelNumber") ?: 0, + name = m.str("channelName") ?: "", + icon = m.str("channelIcon") ?: "", + nextEventId = m.long("nextEventId"), + ), + ) + "eventAdd" -> events.add(event(m)) + "dvrEntryAdd" -> dvr.add(dvrEntry(m)) + "initialSyncCompleted", "__disconnected" -> done.countDown() + } + } + client.request( + HtsMsg.method("enableAsyncMetadata") + .put("epg", if (withEpg) 1L else 0L) + .put("epgMaxTime", System.currentTimeMillis() / 1000 + epgDays * 86400L), + ) + if (!done.await(120, TimeUnit.SECONDS)) throw IllegalStateException("the server did not finish the sync") + client.onAsync = null + Snapshot(channels.sortedBy { it.number }, events, dvr) + } + + fun event(m: HtsMsg) = HEvent( + id = m.long("eventId") ?: 0, + channelId = m.long("channelId") ?: 0, + start = m.long("start") ?: 0, + stop = m.long("stop") ?: 0, + title = m.str("title") ?: "", + summary = m.str("summary") ?: "", + description = m.str("description") ?: "", + contentType = m.int("contentType"), + ageRating = m.int("ageRating"), + ) + + fun dvrEntry(m: HtsMsg) = HDvr( + id = m.long("id") ?: 0, + channelId = m.long("channel"), + channelName = m.str("channelName") ?: "", + title = m.str("title") ?: "", + description = m.str("description") ?: m.str("summary") ?: "", + start = m.long("start") ?: 0, + stop = m.long("stop") ?: 0, + state = m.str("state") ?: "", + size = m.long("dataSize") ?: 0, + ) + + /** Key of a server's channel/event/recording in the TV database: ":". */ + fun key(serverId: String, id: Long) = "$serverId:$id" + + /** Splits a key back into (server, id); old single-server rows have no server part. */ + fun parseKey(ctx: Context, key: String?): Pair? { + if (key.isNullOrEmpty()) return null + val i = key.lastIndexOf(':') + val id = key.substring(i + 1).toLongOrNull() ?: return null + val server = if (i > 0) io.simplydvb.tv.ServerConfig.byId(ctx, key.substring(0, i)) else io.simplydvb.tv.ServerConfig.load(ctx) + return (server ?: return null) to id + } + + /** + * Full sync of every server that feeds the TV's TV app: fetches each one and writes the + * TV database. Channels of servers switched off (or removed) disappear from the TV; a + * server that cannot be reached keeps its channels until it answers again. + * Returns the number of channels in the TV. + */ + fun run(ctx: Context): Int { + val servers = io.simplydvb.tv.ServerConfig.all(ctx) + val enabled = servers.filter { it.tvInput && it.configured } + val keepServers = enabled.map { it.id }.toMutableSet() + val errors = ArrayList() + var channels = 0 + var events = 0 + var recordings = 0 + val fresh = HashMap() + for (srv in enabled) { + try { + fresh[srv.id] = fetch(ctx, server = srv) + } catch (e: Exception) { + errors.add("${srv.label}: ${e.message}") + Log.w(TAG, "sync of ${srv.label} failed: ${e.message}") + } + } + // channels of servers that are off or removed (and rows from old versions without a key) + val existing = channelRows(ctx) + for ((k, row) in existing) { + val sid = k.substringBeforeLast(':', "") + if (sid.isEmpty() || sid !in keepServers) ctx.contentResolver.delete(TvContract.buildChannelUri(row), null, null) + } + for (srv in enabled) { + val snap = fresh[srv.id] ?: continue + val rows = writeChannels(ctx, srv, snap.channels) + writePrograms(ctx, srv, rows, snap.events) + writeRecordings(ctx, srv, rows, snap.dvr) + channels += snap.channels.size + events += snap.events.size + recordings += snap.dvr.size + } + removeRecordingsOf(ctx, keepServers) + val e = ctx.getSharedPreferences("sync", Context.MODE_PRIVATE).edit() + .putLong("last", System.currentTimeMillis()) + .putInt("channels", channels) + .putInt("events", events) + .putInt("recordings", recordings) + if (errors.isEmpty()) e.remove("error") else e.putString("error", errors.joinToString("; ")) + e.apply() + if (enabled.isNotEmpty() && fresh.isEmpty()) throw IllegalStateException(errors.joinToString("; ")) + Log.i(TAG, "synced $channels channels, $events events, $recordings recordings from ${fresh.size} server(s)") + return channels + } + + /** Channel key ("server:channel") → row id in TvContract.Channels. */ + fun channelRows(ctx: Context): Map { + val out = HashMap() + ctx.contentResolver.query( + TvContract.buildChannelsUriForInput(inputId(ctx)), + arrayOf(TvContract.Channels._ID, TvContract.Channels.COLUMN_INTERNAL_PROVIDER_ID), + null, null, null, + )?.use { c -> + while (c.moveToNext()) out[c.getString(1) ?: "row${c.getLong(0)}"] = c.getLong(0) + } + return out + } + + private fun writeChannels(ctx: Context, srv: io.simplydvb.tv.ServerConfig, channels: List): Map { + val cr = ctx.contentResolver + val input = inputId(ctx) + val existing = channelRows(ctx).filterKeys { it.startsWith(srv.id + ":") } + val keep = HashSet() + val result = HashMap() + for (ch in channels) { + val k = key(srv.id, ch.id) + val v = ContentValues().apply { + put(TvContract.Channels.COLUMN_INPUT_ID, input) + put(TvContract.Channels.COLUMN_DISPLAY_NUMBER, ch.number.toString()) + put(TvContract.Channels.COLUMN_DISPLAY_NAME, ch.name) + put(TvContract.Channels.COLUMN_SERVICE_ID, ch.id.toInt()) + put(TvContract.Channels.COLUMN_ORIGINAL_NETWORK_ID, 0) + put(TvContract.Channels.COLUMN_TRANSPORT_STREAM_ID, 0) + put(TvContract.Channels.COLUMN_TYPE, TvContract.Channels.TYPE_OTHER) + put(TvContract.Channels.COLUMN_SERVICE_TYPE, TvContract.Channels.SERVICE_TYPE_AUDIO_VIDEO) + put(TvContract.Channels.COLUMN_SEARCHABLE, 1) + put(TvContract.Channels.COLUMN_INTERNAL_PROVIDER_ID, k) + put(TvContract.Channels.COLUMN_INTERNAL_PROVIDER_DATA, ch.icon.toByteArray()) + put(TvContract.Channels.COLUMN_NETWORK_AFFILIATION, srv.label) + } + val row = existing[k] + val id = if (row != null) { + cr.update(TvContract.buildChannelUri(row), v, null, null) + row + } else { + val uri = cr.insert(TvContract.Channels.CONTENT_URI, v) ?: continue + ContentUris.parseId(uri) + } + keep.add(k) + result[ch.id] = id + } + // channels removed on the server + for ((k, row) in existing) if (k !in keep) cr.delete(TvContract.buildChannelUri(row), null, null) + // logos (best effort, outside the critical path) + for (ch in channels) { + val row = result[ch.id] ?: continue + val url = Server.iconUrl(ctx, ch.icon, srv) ?: continue + try { + downloadLogo(ctx, url, TvContract.buildChannelLogoUri(row)) + } catch (e: Exception) { + Log.w(TAG, "logo of ${ch.name} ($url): ${e.message}") + } + } + return result + } + + /** + * The TV app shows channel logos only as bitmaps the TV can decode: the logo is decoded + * here (SVG and broken files are skipped), scaled down and stored as PNG. + */ + private fun downloadLogo(ctx: Context, url: String, target: Uri) { + val bytes = Server.download(url) ?: throw IllegalStateException("download failed") + var bmp = android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + ?: throw IllegalStateException("not a bitmap (SVG?)") + val max = 512 + if (bmp.width > max || bmp.height > max) { + val k = max.toFloat() / maxOf(bmp.width, bmp.height) + bmp = android.graphics.Bitmap.createScaledBitmap(bmp, (bmp.width * k).toInt().coerceAtLeast(1), (bmp.height * k).toInt().coerceAtLeast(1), true) + } + ctx.contentResolver.openOutputStream(target)?.use { bmp.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) } + ?: throw IllegalStateException("TV database refused the logo") + } + + /** DVB content nibble → Android canonical genre. */ + private fun genre(ct: Int?): String? { + if (ct == null || ct <= 0) return null + val major = if (ct > 0x0f) ct shr 4 else ct + val g = when (major) { + 0x1 -> TvContract.Programs.Genres.MOVIES + 0x2 -> TvContract.Programs.Genres.NEWS + 0x3 -> TvContract.Programs.Genres.ENTERTAINMENT + 0x4 -> TvContract.Programs.Genres.SPORTS + 0x5 -> TvContract.Programs.Genres.FAMILY_KIDS + 0x6 -> TvContract.Programs.Genres.MUSIC + 0x7 -> TvContract.Programs.Genres.ARTS + 0x8 -> TvContract.Programs.Genres.NEWS + 0x9 -> TvContract.Programs.Genres.EDUCATION + 0xA -> TvContract.Programs.Genres.LIFE_STYLE + else -> null + } ?: return null + return TvContract.Programs.Genres.encode(g) + } + + private fun writePrograms(ctx: Context, srv: io.simplydvb.tv.ServerConfig, rows: Map, events: List) { + val cr = ctx.contentResolver + val now = System.currentTimeMillis() + val ops = ArrayList() + // replace the guide of every channel (old entries of past days go too) + for (row in rows.values) { + ops.add( + ContentProviderOperation.newDelete(TvContract.buildProgramsUriForChannel(row)).build(), + ) + } + flush(ctx, ops) + for (e in events.sortedBy { it.start }) { + val row = rows[e.channelId] ?: continue + if (e.stop * 1000 < now - 6 * 3600_000L) continue + val v = ContentValues().apply { + put(TvContract.Programs.COLUMN_CHANNEL_ID, row) + put(TvContract.Programs.COLUMN_TITLE, e.title) + val shortDesc = e.summary.ifEmpty { e.description } + if (shortDesc.isNotEmpty()) put(TvContract.Programs.COLUMN_SHORT_DESCRIPTION, shortDesc.take(250)) + if (e.description.isNotEmpty()) put(TvContract.Programs.COLUMN_LONG_DESCRIPTION, e.description) + put(TvContract.Programs.COLUMN_START_TIME_UTC_MILLIS, e.start * 1000) + put(TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS, e.stop * 1000) + genre(e.contentType)?.let { put(TvContract.Programs.COLUMN_CANONICAL_GENRE, it) } + put(TvContract.Programs.COLUMN_INTERNAL_PROVIDER_DATA, key(srv.id, e.id).toByteArray()) + } + ops.add(ContentProviderOperation.newInsert(TvContract.Programs.CONTENT_URI).withValues(v).build()) + if (ops.size >= 300) flush(ctx, ops) + } + flush(ctx, ops) + Log.d(TAG, "programs written for ${rows.size} channels") + cr.notifyChange(TvContract.Programs.CONTENT_URI, null) + } + + /** Finished recordings appear in the TV's "Recordings" list (where supported). */ + fun recordingUri(serverId: String, id: Long) = "simplytv://dvr/$serverId/$id" + + /** Recordings in the TV of servers that are off or removed. */ + private fun removeRecordingsOf(ctx: Context, keepServers: Set) { + try { + ctx.contentResolver.query( + TvContract.RecordedPrograms.CONTENT_URI, + arrayOf(TvContract.RecordedPrograms._ID, TvContract.RecordedPrograms.COLUMN_RECORDING_DATA_URI), + "${TvContract.RecordedPrograms.COLUMN_INPUT_ID}=?", arrayOf(inputId(ctx)), null, + )?.use { c -> + while (c.moveToNext()) { + val segs = Uri.parse(c.getString(1) ?: "").pathSegments + if (segs.size < 2 || segs[0] !in keepServers) { + ctx.contentResolver.delete(TvContract.buildRecordedProgramUri(c.getLong(0)), null, null) + } + } + } + } catch (_: Exception) { + } + } + + private fun writeRecordings(ctx: Context, srv: io.simplydvb.tv.ServerConfig, rows: Map, dvr: List) { + val cr = ctx.contentResolver + val input = inputId(ctx) + val existing = HashMap() + try { + cr.query( + TvContract.RecordedPrograms.CONTENT_URI, + arrayOf(TvContract.RecordedPrograms._ID, TvContract.RecordedPrograms.COLUMN_RECORDING_DATA_URI), + "${TvContract.RecordedPrograms.COLUMN_INPUT_ID}=?", arrayOf(input), null, + )?.use { c -> + while (c.moveToNext()) { + val segs = Uri.parse(c.getString(1) ?: "").pathSegments + if (segs.size < 2 || segs[0] != srv.id) continue + val id = segs[1].toLongOrNull() ?: continue + existing[id] = c.getLong(0) + } + } + } catch (e: Exception) { + Log.i(TAG, "recorded programs are not available on this TV: ${e.message}") + return + } + val done = dvr.filter { it.state == "completed" && it.size > 0 } + val keep = done.map { it.id }.toSet() + for ((id, row) in existing) { + if (id !in keep) cr.delete(TvContract.buildRecordedProgramUri(row), null, null) + } + for (r in done) { + if (existing.containsKey(r.id)) continue + val v = ContentValues().apply { + put(TvContract.RecordedPrograms.COLUMN_INPUT_ID, input) + r.channelId?.let { rows[it] }?.let { put(TvContract.RecordedPrograms.COLUMN_CHANNEL_ID, it) } + put(TvContract.RecordedPrograms.COLUMN_TITLE, r.title) + if (r.description.isNotEmpty()) put(TvContract.RecordedPrograms.COLUMN_SHORT_DESCRIPTION, r.description.take(250)) + put(TvContract.RecordedPrograms.COLUMN_START_TIME_UTC_MILLIS, r.start * 1000) + put(TvContract.RecordedPrograms.COLUMN_END_TIME_UTC_MILLIS, r.stop * 1000) + put(TvContract.RecordedPrograms.COLUMN_RECORDING_DURATION_MILLIS, (r.stop - r.start) * 1000) + put(TvContract.RecordedPrograms.COLUMN_RECORDING_DATA_BYTES, r.size) + put(TvContract.RecordedPrograms.COLUMN_RECORDING_DATA_URI, recordingUri(srv.id, r.id)) + } + try { + cr.insert(TvContract.RecordedPrograms.CONTENT_URI, v) + } catch (e: Exception) { + Log.d(TAG, "recorded program ${r.title}: ${e.message}") + } + } + } + + private fun flush(ctx: Context, ops: ArrayList) { + if (ops.isEmpty()) return + try { + ctx.contentResolver.applyBatch(TvContract.AUTHORITY, ops) + } catch (e: Exception) { + Log.w(TAG, "TV database write failed: ${e.message}") + } + ops.clear() + } +} diff --git a/app/src/main/java/io/simplydvb/tv/tif/SimplyTvInputService.kt b/app/src/main/java/io/simplydvb/tv/tif/SimplyTvInputService.kt new file mode 100644 index 0000000..d25e860 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/tif/SimplyTvInputService.kt @@ -0,0 +1,398 @@ +package io.simplydvb.tv.tif + +import android.content.Context +import android.media.PlaybackParams +import android.media.tv.TvContentRating +import android.media.tv.TvContract +import android.media.tv.TvInputManager +import android.media.tv.TvInputService +import android.media.tv.TvTrackInfo +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.util.Log +import android.view.LayoutInflater +import android.view.Surface +import android.view.View +import androidx.annotation.OptIn +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.MimeTypes +import androidx.media3.common.PlaybackException +import androidx.media3.common.Player +import androidx.media3.common.TrackSelectionOverride +import androidx.media3.common.Tracks +import androidx.media3.common.text.CueGroup +import androidx.media3.common.util.UnstableApi +import androidx.media3.ui.SubtitleView +import io.simplydvb.tv.R +import io.simplydvb.tv.Server +import io.simplydvb.tv.ServerConfig +import io.simplydvb.tv.htsp.HtsMsg +import io.simplydvb.tv.player.Players +import java.util.concurrent.Executors + +/** + * TV input: makes simply-dvb a source in the TV's own live-TV app (Sony: TV / inputs). + * Channels and the guide come from [EpgSync]; tuning plays the server's MPEG-TS stream + * with ExoPlayer on the surface the TV app provides (hardware decoding of HEVC, AC-3…). + */ +/** Server and server-side channel id of a channel row in the TV database. */ +internal fun channelOf(ctx: Context, channelUri: Uri): Pair { + val key = ctx.contentResolver.query( + channelUri, arrayOf(TvContract.Channels.COLUMN_INTERNAL_PROVIDER_ID), null, null, null, + )?.use { c -> if (c.moveToFirst()) c.getString(0) else null } + return EpgSync.parseKey(ctx, key) + ?: throw IllegalStateException("unknown channel $channelUri (server removed?)") +} + +class SimplyTvInputService : TvInputService() { + + override fun onCreate() { + super.onCreate() + SyncWorker.schedule(this) + } + + override fun onCreateSession(inputId: String): Session = PlayerSession(this) + + override fun onCreateRecordingSession(inputId: String): RecordingSession = DvrSession(this) + + // ------------------------------------------------------------------ playback + + @OptIn(UnstableApi::class) + private class PlayerSession(private val ctx: Context) : Session(ctx), Player.Listener { + private val main = Handler(Looper.getMainLooper()) + private val io = Executors.newSingleThreadExecutor() + private val player = Players.create(ctx, live = true).also { it.addListener(this) } + private var subtitles: SubtitleView? = null + private var current: Uri? = null + private var retries = 0 + private var recorded = false + private var tuneSeq = 0 + + init { + setOverlayViewEnabled(true) + } + + override fun onCreateOverlayView(): View { + val v = LayoutInflater.from(ctx).inflate(R.layout.overlay, null) + subtitles = v.findViewById(R.id.subtitles) + return v + } + + override fun onRelease() { + player.release() + io.shutdownNow() + } + + override fun onSetSurface(surface: Surface?): Boolean { + player.setVideoSurface(surface) + return true + } + + override fun onSetStreamVolume(volume: Float) { + player.volume = volume + } + + override fun onSetCaptionEnabled(enabled: Boolean) { + player.trackSelectionParameters = player.trackSelectionParameters.buildUpon() + .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, !enabled).build() + } + + override fun onTune(channelUri: Uri): Boolean { + current = channelUri + recorded = false + retries = 0 + notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING) + notifyTimeShiftStatusChanged(TvInputManager.TIME_SHIFT_STATUS_UNSUPPORTED) + player.stop() + start(channelUri) + return true + } + + private fun start(channelUri: Uri) { + val seq = ++tuneSeq + io.execute { + try { + val (srv, serviceId) = channelOf(ctx, channelUri) + val url = Server.session(ctx, srv) { Server.ticketUrl(ctx, it, channelId = serviceId, c = srv) } + main.post { + if (seq != tuneSeq) return@post + play(url, live = true) + notifyContentAllowed() + } + } catch (e: Exception) { + Log.w(TAG, "tune failed: ${e.message}") + main.post { if (seq == tuneSeq) notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN) } + } + } + } + + private fun play(url: Uri, live: Boolean) { + val item = MediaItem.Builder().setUri(url) + .setMimeType(MimeTypes.VIDEO_MP2T) + .build() + player.setMediaItem(item) + player.prepare() + player.playWhenReady = true + Log.i(TAG, "playing ${url.buildUpon().clearQuery().build()} (live=$live)") + } + + // ---- recorded programmes (TvView.timeShiftPlay with a RecordedPrograms uri) + + override fun onTimeShiftPlay(recordedProgramUri: Uri) { + recorded = true + tuneSeq++ + notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING) + player.stop() + val seq = tuneSeq + io.execute { + try { + val data = ctx.contentResolver.query( + recordedProgramUri, arrayOf(TvContract.RecordedPrograms.COLUMN_RECORDING_DATA_URI), null, null, null, + )?.use { c -> if (c.moveToFirst()) c.getString(0) else null } + val segs = Uri.parse(data ?: "").pathSegments + val srv = segs.getOrNull(0)?.let { ServerConfig.byId(ctx, it) } + ?: throw IllegalStateException("the server of this recording is not configured") + val dvrId = segs.getOrNull(1)?.toLongOrNull() + ?: throw IllegalStateException("not a simply-tv recording") + val url = Server.session(ctx, srv) { Server.ticketUrl(ctx, it, dvrId = dvrId, c = srv) } + main.post { + if (seq != tuneSeq) return@post + play(url, live = false) + notifyTimeShiftStatusChanged(TvInputManager.TIME_SHIFT_STATUS_AVAILABLE) + } + } catch (e: Exception) { + Log.w(TAG, "recording playback failed: ${e.message}") + main.post { notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN) } + } + } + } + + override fun onTimeShiftPause() { + player.playWhenReady = false + } + + override fun onTimeShiftResume() { + player.playWhenReady = true + } + + override fun onTimeShiftSeekTo(timeMs: Long) { + player.seekTo(timeMs - startOffset()) + } + + override fun onTimeShiftSetPlaybackParams(params: PlaybackParams) { + player.setPlaybackSpeed(params.speed) + } + + // positions in recordings are reported on the wall-clock scale the TV app expects + private var startedAt = 0L + private fun startOffset() = startedAt + + override fun onTimeShiftGetStartPosition(): Long = + if (recorded) startedAt else TvInputManager.TIME_SHIFT_INVALID_TIME + + override fun onTimeShiftGetCurrentPosition(): Long = + if (recorded) startedAt + player.currentPosition else TvInputManager.TIME_SHIFT_INVALID_TIME + + // ---- player events + + override fun onPlaybackStateChanged(state: Int) { + if (state == Player.STATE_READY && recorded && startedAt == 0L) startedAt = System.currentTimeMillis() + if (state == Player.STATE_ENDED && !recorded) current?.let { main.postDelayed({ start(it) }, 500) } + } + + override fun onRenderedFirstFrame() { + retries = 0 + notifyVideoAvailable() + } + + override fun onPlayerError(error: PlaybackException) { + Log.w(TAG, "player error: ${error.errorCodeName} ${error.message}") + val uri = current + if (!recorded && uri != null && retries < 5) { + retries++ + notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_BUFFERING) + main.postDelayed({ if (current == uri) start(uri) }, 1500L * retries) + } else { + notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN) + } + } + + override fun onIsLoadingChanged(isLoading: Boolean) {} + + override fun onCues(cueGroup: CueGroup) { + subtitles?.setCues(cueGroup.cues) + } + + override fun onTracksChanged(tracks: Tracks) { + val list = ArrayList() + var audioSel: String? = null + var videoSel: String? = null + var textSel: String? = null + tracks.groups.forEachIndexed { gi, g -> + for (ti in 0 until g.length) { + val f = g.getTrackFormat(ti) + val id = "$gi:$ti" + val type = when (g.type) { + C.TRACK_TYPE_AUDIO -> TvTrackInfo.TYPE_AUDIO + C.TRACK_TYPE_VIDEO -> TvTrackInfo.TYPE_VIDEO + C.TRACK_TYPE_TEXT -> TvTrackInfo.TYPE_SUBTITLE + else -> continue + } + val b = TvTrackInfo.Builder(type, id) + f.language?.let { b.setLanguage(it) } + if (type == TvTrackInfo.TYPE_AUDIO) { + if (f.channelCount > 0) b.setAudioChannelCount(f.channelCount) + if (f.sampleRate > 0) b.setAudioSampleRate(f.sampleRate) + b.setDescription(listOfNotNull(f.label, codecName(f.sampleMimeType)).joinToString(" ")) + } + if (type == TvTrackInfo.TYPE_VIDEO) { + if (f.width > 0) b.setVideoWidth(f.width) + if (f.height > 0) b.setVideoHeight(f.height) + if (f.frameRate > 0) b.setVideoFrameRate(f.frameRate) + } + list.add(b.build()) + if (g.isTrackSelected(ti)) when (type) { + TvTrackInfo.TYPE_AUDIO -> audioSel = id + TvTrackInfo.TYPE_VIDEO -> videoSel = id + TvTrackInfo.TYPE_SUBTITLE -> textSel = id + } + } + } + notifyTracksChanged(list) + notifyTrackSelected(TvTrackInfo.TYPE_AUDIO, audioSel) + notifyTrackSelected(TvTrackInfo.TYPE_VIDEO, videoSel) + notifyTrackSelected(TvTrackInfo.TYPE_SUBTITLE, textSel) + } + + private fun codecName(mime: String?) = when (mime) { + MimeTypes.AUDIO_AC3 -> "AC-3" + MimeTypes.AUDIO_E_AC3 -> "E-AC-3" + MimeTypes.AUDIO_AAC -> "AAC" + MimeTypes.AUDIO_MPEG_L2, MimeTypes.AUDIO_MPEG -> "MPEG" + else -> null + } + + override fun onSelectTrack(type: Int, trackId: String?): Boolean { + val ctype = when (type) { + TvTrackInfo.TYPE_AUDIO -> C.TRACK_TYPE_AUDIO + TvTrackInfo.TYPE_VIDEO -> C.TRACK_TYPE_VIDEO + TvTrackInfo.TYPE_SUBTITLE -> C.TRACK_TYPE_TEXT + else -> return false + } + val params = player.trackSelectionParameters.buildUpon() + if (trackId == null) { + params.setTrackTypeDisabled(ctype, true) + } else { + val (gi, ti) = trackId.split(':').map { it.toInt() } + val group = player.currentTracks.groups.getOrNull(gi) ?: return false + params.setTrackTypeDisabled(ctype, false) + .setOverrideForType(TrackSelectionOverride(group.mediaTrackGroup, ti)) + } + player.trackSelectionParameters = params.build() + notifyTrackSelected(type, trackId) + return true + } + + override fun onUnblockContent(unblockedRating: TvContentRating?) {} + + companion object { + private const val TAG = "SimplyTvSession" + } + } + + // ------------------------------------------------------------------ recording + + /** + * Recording requested by the TV app: the server records (simply-dvb's DVR); when it is + * done the programme is added to the TV's recordings list. + */ + private class DvrSession(private val ctx: Context) : RecordingSession(ctx) { + private val io = Executors.newSingleThreadExecutor() + private var channelUri: Uri? = null + private var dvrId: Long? = null + private var server: ServerConfig? = null + + override fun onTune(channelUri: Uri) { + this.channelUri = channelUri + notifyTuned(channelUri) + } + + override fun onStartRecording(programUri: Uri?) { + val ch = channelUri ?: return notifyError(TvInputManager.RECORDING_ERROR_UNKNOWN) + io.execute { + try { + val (srv, serviceId) = channelOf(ctx, ch) + server = srv + var eventId: Long? = null + var title = ctx.getString(R.string.recording_default_title) + var stop = System.currentTimeMillis() / 1000 + 4 * 3600 + if (programUri != null) { + ctx.contentResolver.query( + programUri, + arrayOf( + TvContract.Programs.COLUMN_INTERNAL_PROVIDER_DATA, + TvContract.Programs.COLUMN_TITLE, + TvContract.Programs.COLUMN_END_TIME_UTC_MILLIS, + ), + null, null, null, + )?.use { c -> + if (c.moveToFirst()) { + eventId = c.getBlob(0)?.let { String(it).substringAfterLast(':').toLongOrNull() } + title = c.getString(1) ?: title + stop = c.getLong(2) / 1000 + } + } + } + val req = HtsMsg.method("addDvrEntry") + if (eventId != null) { + req["eventId"] = eventId!! + } else { + req["channelId"] = serviceId + req["start"] = System.currentTimeMillis() / 1000 + req["stop"] = stop + req["title"] = title + } + val r = Server.session(ctx, srv) { it.request(req) } + dvrId = r.long("id") + if (r.int("success") != 1 || dvrId == null) throw IllegalStateException(r.str("error") ?: "rejected") + Log.i(TAG, "server recording $dvrId started: $title") + } catch (e: Exception) { + Log.w(TAG, "recording failed: ${e.message}") + notifyError(TvInputManager.RECORDING_ERROR_UNKNOWN) + } + } + } + + override fun onStopRecording() { + val id = dvrId ?: return notifyError(TvInputManager.RECORDING_ERROR_UNKNOWN) + val srv = server ?: return notifyError(TvInputManager.RECORDING_ERROR_UNKNOWN) + io.execute { + try { + Server.session(ctx, srv) { it.request(HtsMsg.method("stopDvrEntry").put("id", id)) } + // the finished recording shows up after the next sync; refresh now + EpgSync.run(ctx) + val uri = ctx.contentResolver.query( + TvContract.RecordedPrograms.CONTENT_URI, + arrayOf(TvContract.RecordedPrograms._ID), + "${TvContract.RecordedPrograms.COLUMN_RECORDING_DATA_URI}=?", + arrayOf(EpgSync.recordingUri(srv.id, id)), null, + )?.use { c -> if (c.moveToFirst()) TvContract.buildRecordedProgramUri(c.getLong(0)) else null } + if (uri != null) notifyRecordingStopped(uri) else notifyError(TvInputManager.RECORDING_ERROR_UNKNOWN) + } catch (e: Exception) { + Log.w(TAG, "stopping the recording failed: ${e.message}") + notifyError(TvInputManager.RECORDING_ERROR_UNKNOWN) + } + } + } + + override fun onRelease() { + io.shutdown() + } + + companion object { + private const val TAG = "SimplyTvDvr" + } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/tif/SyncWorker.kt b/app/src/main/java/io/simplydvb/tv/tif/SyncWorker.kt new file mode 100644 index 0000000..6c142a8 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/tif/SyncWorker.kt @@ -0,0 +1,50 @@ +package io.simplydvb.tv.tif + +import android.content.Context +import android.util.Log +import androidx.work.Constraints +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.ExistingWorkPolicy +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.Worker +import androidx.work.WorkerParameters +import io.simplydvb.tv.ServerConfig +import java.util.concurrent.TimeUnit + +/** Background sync of channels, programme guide and recordings (hourly + on demand). */ +class SyncWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) { + override fun doWork(): Result { + if (ServerConfig.all(applicationContext).none { it.configured && it.tvInput }) return Result.success() + return try { + EpgSync.run(applicationContext) + Result.success() + } catch (e: Exception) { + Log.w("SyncWorker", "sync failed: ${e.message}") + applicationContext.getSharedPreferences("sync", Context.MODE_PRIVATE).edit() + .putString("error", e.message ?: e.toString()).apply() + if (runAttemptCount < 3) Result.retry() else Result.failure() + } + } + + companion object { + private const val PERIODIC = "simplytv-sync" + private const val ONCE = "simplytv-sync-now" + + private val network = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build() + + fun schedule(ctx: Context) { + val req = PeriodicWorkRequestBuilder(1, TimeUnit.HOURS) + .setConstraints(network) + .build() + WorkManager.getInstance(ctx).enqueueUniquePeriodicWork(PERIODIC, ExistingPeriodicWorkPolicy.KEEP, req) + } + + fun now(ctx: Context) { + val req = OneTimeWorkRequestBuilder().setConstraints(network).build() + WorkManager.getInstance(ctx).enqueueUniqueWork(ONCE, ExistingWorkPolicy.REPLACE, req) + } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/ui/EpgGridView.kt b/app/src/main/java/io/simplydvb/tv/ui/EpgGridView.kt new file mode 100644 index 0000000..beb2de6 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/ui/EpgGridView.kt @@ -0,0 +1,345 @@ +package io.simplydvb.tv.ui + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.RectF +import android.graphics.Typeface +import android.text.Layout +import android.text.StaticLayout +import android.text.TextPaint +import android.text.TextUtils +import android.util.AttributeSet +import android.util.TypedValue +import android.view.KeyEvent +import android.view.View +import io.simplydvb.tv.R +import io.simplydvb.tv.tif.HChannel +import io.simplydvb.tv.tif.HEvent +import java.text.DateFormat +import java.util.Date + +/** + * Full-screen programme grid (channels down, time across) like the simply-dvb web panel: + * details of the highlighted programme on top, a "now" line, recordings marked. + * D-pad: up/down channel, left/right programme, CH+/CH- a page, OK opens the programme. + */ +class EpgGridView(ctx: Context, attrs: AttributeSet? = null) : View(ctx, attrs) { + interface Listener { + fun onEvent(ch: HChannel, e: HEvent) + fun onChannel(ch: HChannel) + fun onRecord(e: HEvent) {} + } + + var listener: Listener? = null + var isScheduled: (HEvent) -> Boolean = { false } + var hint: String = "" + + private var channels: List = emptyList() + private var events: Map> = emptyMap() + private var row = 0 + private var firstRow = 0 + private var focusTime = 0L + private var winStart = 0L + private val span = 150 * 60L // visible time range: 2.5 h + + private fun dp(v: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, v, resources.displayMetrics) + private fun sp(v: Float) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, v, resources.displayMetrics) + + private val cText = ctx.getColor(R.color.text) + private val cMuted = ctx.getColor(R.color.muted) + private val cAccent = ctx.getColor(R.color.accent) + private val cRed = ctx.getColor(R.color.red) + private val cLine = ctx.getColor(R.color.line) + + private val pBg = Paint().apply { color = Color.parseColor("#f2060807") } + private val pRowAlt = Paint().apply { color = Color.parseColor("#0affffff") } + private val pCell = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.parseColor("#1c221f") } + private val pCellNow = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.parseColor("#26302b") } + private val pFocus = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = cAccent } + private val pLine = Paint().apply { color = cLine; strokeWidth = dp(1f) } + private val pNow = Paint().apply { color = cRed; strokeWidth = dp(2f) } + private val pDot = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = cRed } + private val tTitle = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = cText; textSize = sp(22f); typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL) } + private val tInfo = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = cMuted; textSize = sp(13f) } + private val tDesc = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.parseColor("#c3cac5"); textSize = sp(13f) } + private val tCell = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = cText; textSize = sp(13f) } + private val tCellSub = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = cMuted; textSize = sp(11f) } + private val tNum = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = cAccent; textSize = sp(13f); typeface = Typeface.MONOSPACE } + private val tTime = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = cMuted; textSize = sp(12f); typeface = Typeface.MONOSPACE } + private val tClock = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = cText; textSize = sp(20f); typeface = Typeface.MONOSPACE; textAlign = Paint.Align.RIGHT } + private val tHint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = cMuted; textSize = sp(11f); textAlign = Paint.Align.RIGHT } + + private val padX get() = dp(32f) + private val headH get() = dp(150f) + private val barH get() = dp(26f) + private val rowH get() = dp(44f) + private val nameW get() = dp(200f) + private val gridTop get() = headH + barH + private val visibleRows get() = ((height - gridTop - dp(12f)) / rowH).toInt().coerceAtLeast(1) + + private val fmtTime = DateFormat.getTimeInstance(DateFormat.SHORT) + private val fmtDay = DateFormat.getDateInstance(DateFormat.FULL) + private val tick = object : Runnable { + override fun run() { + invalidate() + postDelayed(this, 30_000) + } + } + + init { + isFocusable = true + isFocusableInTouchMode = true + } + + private fun now() = System.currentTimeMillis() / 1000 + private fun floor30(t: Long) = t - Math.floorMod(t, 1800L) + + fun setData(channels: List, events: Map>, focusChannel: Int) { + this.channels = channels + this.events = events + row = focusChannel.coerceIn(0, (channels.size - 1).coerceAtLeast(0)) + focusTime = now() + winStart = floor30(focusTime) + firstRow = 0 + post { ensureRowVisible(center = true) } + invalidate() + } + + /** Recordings changed: just redraw. */ + fun refresh() = invalidate() + + fun focusedChannel(): HChannel? = channels.getOrNull(row) + fun focusedEvent(): HEvent? = channels.getOrNull(row)?.let { eventAt(it, focusTime) } + + private fun list(ch: HChannel) = events[ch.id].orEmpty() + + /** Programme on `ch` at `t`, else the next one after, else the last one before. */ + private fun eventAt(ch: HChannel, t: Long): HEvent? { + val l = list(ch) + return l.firstOrNull { it.start <= t && it.stop > t } + ?: l.firstOrNull { it.start > t && it.start < winStart + span } + ?: l.lastOrNull { it.stop <= t && it.stop > winStart } + } + + private fun ensureRowVisible(center: Boolean = false) { + val n = visibleRows + if (center) firstRow = row - n / 2 + if (row < firstRow) firstRow = row + if (row >= firstRow + n) firstRow = row - n + 1 + firstRow = firstRow.coerceIn(0, (channels.size - n).coerceAtLeast(0)) + } + + private fun focusEvent(e: HEvent) { + val minStart = floor30(now()) + if (e.start >= winStart + span - 1800 || e.start < winStart) { + winStart = (floor30(e.start) - if (e.start < winStart) 0 else 1800).coerceAtLeast(minStart) + } + focusTime = maxOf(e.start, winStart) + } + + private fun move(dx: Int) { + val ch = channels.getOrNull(row) ?: return + val cur = eventAt(ch, focusTime) + val l = list(ch) + val next = when { + cur == null -> null + dx > 0 -> l.firstOrNull { it.start >= cur.stop } + else -> l.lastOrNull { it.stop <= cur.start && it.stop > now() } + } + if (next != null) { + focusEvent(next) + } else { + // no data in this row: step the time by half an hour + val minStart = floor30(now()) + focusTime = (focusTime + dx * 1800L).coerceAtLeast(now()) + if (focusTime >= winStart + span - 1800) winStart += 1800 + if (focusTime < winStart) winStart = maxOf(minStart, floor30(focusTime)) + } + invalidate() + } + + private fun moveRow(d: Int) { + if (channels.isEmpty()) return + row = (row + d).coerceIn(0, channels.size - 1) + ensureRowVisible() + invalidate() + } + + override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { + when (keyCode) { + KeyEvent.KEYCODE_DPAD_UP -> moveRow(-1) + KeyEvent.KEYCODE_DPAD_DOWN -> moveRow(1) + KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_PAGE_UP -> moveRow(-visibleRows) + KeyEvent.KEYCODE_CHANNEL_DOWN, KeyEvent.KEYCODE_PAGE_DOWN -> moveRow(visibleRows) + KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> move(1) + KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_MEDIA_REWIND -> move(-1) + KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> { + val ch = channels.getOrNull(row) ?: return true + val e = eventAt(ch, focusTime) + if (e != null) listener?.onEvent(ch, e) else listener?.onChannel(ch) + } + KeyEvent.KEYCODE_PROG_RED, KeyEvent.KEYCODE_MEDIA_RECORD -> focusedEvent()?.let { listener?.onRecord(it) } + KeyEvent.KEYCODE_PROG_GREEN -> { + // back to "now" + focusTime = now() + winStart = floor30(focusTime) + invalidate() + } + else -> return super.onKeyDown(keyCode, event) + } + return true + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + postDelayed(tick, 30_000) + } + + override fun onDetachedFromWindow() { + removeCallbacks(tick) + super.onDetachedFromWindow() + } + + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + super.onSizeChanged(w, h, oldw, oldh) + ensureRowVisible(center = true) + } + + // ------------------------------------------------------------ drawing + + override fun onDraw(c: Canvas) { + val w = width.toFloat() + val h = height.toFloat() + c.drawRect(0f, 0f, w, h, pBg) + val t = now() + drawHeader(c, w, t) + + val gx = padX + nameW + val gw = w - padX - gx + val pps = gw / span + val winEnd = winStart + span + + // time bar + val barY = headH + barH - dp(8f) + var s = winStart + while (s < winEnd) { + val x = gx + (s - winStart) * pps + c.drawText(fmtTime.format(Date(s * 1000)), x + dp(4f), barY, tTime) + c.drawLine(x, headH + dp(4f), x, h - dp(12f), pLine) + s += 1800 + } + c.drawLine(padX, gridTop, w - padX, gridTop, pLine) + + val focused = focusedEvent() + val r = RectF() + for (i in 0 until visibleRows) { + val idx = firstRow + i + val ch = channels.getOrNull(idx) ?: break + val y = gridTop + i * rowH + if (idx % 2 == 1) c.drawRect(padX, y, w - padX, y + rowH, pRowAlt) + // channel column + val cy = y + rowH / 2 + tCell.textSize / 3 + val num = ch.number.toString() + if (idx == row) { + r.set(padX, y + dp(3f), padX + nameW - dp(8f), y + rowH - dp(3f)) + c.drawRoundRect(r, dp(6f), dp(6f), pCellNow) + } + c.drawText(num, padX + dp(8f), cy, tNum) + val nx = padX + dp(52f) + c.drawText(TextUtils.ellipsize(ch.name, tCell, nameW - dp(64f), TextUtils.TruncateAt.END).toString(), nx, cy, tCell) + // programmes + val l = list(ch).filter { it.stop > winStart && it.start < winEnd } + if (l.isEmpty()) { + c.drawText(context.getString(R.string.no_programmes), gx + dp(10f), cy, tCellSub) + } + for (e in l) { + val x1 = gx + (maxOf(e.start, winStart) - winStart) * pps + val x2 = gx + (minOf(e.stop, winEnd) - winStart) * pps + r.set(x1 + dp(2f), y + dp(3f), x2 - dp(2f), y + rowH - dp(3f)) + if (r.width() < dp(3f)) continue + val isFocus = idx == row && e == focused && hasFocus() + val airing = e.start <= t && e.stop > t + c.drawRoundRect(r, dp(6f), dp(6f), if (isFocus) pFocus else if (airing) pCellNow else pCell) + var tx = r.left + dp(8f) + if (isScheduled(e)) { + c.drawCircle(tx + dp(4f), r.centerY(), dp(4f), pDot) + tx += dp(14f) + } + val avail = r.right - tx - dp(6f) + if (avail > dp(14f)) { + val tp = if (isFocus) TextPaint(tCell).apply { color = Color.parseColor("#1a120e") } else tCell + val title = TextUtils.ellipsize(e.title, tp, avail, TextUtils.TruncateAt.END).toString() + c.drawText(title, tx, r.centerY() - dp(1f), tp) + val sub = TextPaint(tCellSub).apply { if (isFocus) color = Color.parseColor("#4a2f22") } + val time = fmtTime.format(Date(e.start * 1000)) + "–" + fmtTime.format(Date(e.stop * 1000)) + c.drawText(TextUtils.ellipsize(time, sub, avail, TextUtils.TruncateAt.END).toString(), tx, r.centerY() + sub.textSize, sub) + } + } + } + // now line + if (t in winStart until winEnd) { + val x = gx + (t - winStart) * pps + c.drawLine(x, headH + dp(2f), x, gridTop + visibleRows * rowH, pNow) + } + if (channels.isEmpty()) c.drawText(context.getString(R.string.no_channels), gx, gridTop + rowH, tInfo) + } + + private fun drawHeader(c: Canvas, w: Float, t: Long) { + val top = dp(26f) + c.drawText(fmtTime.format(Date(t * 1000)), w - padX, top + tClock.textSize * 0.8f, tClock) + c.drawText(fmtDay.format(Date(winStart * 1000)), w - padX, top + tClock.textSize + dp(14f), tHint) + if (hint.isNotEmpty()) c.drawText(hint, w - padX, headH - dp(8f), tHint) + val ch = channels.getOrNull(row) ?: return + val e = focusedEvent() + val textW = (w - padX * 2 - dp(260f)).toInt().coerceAtLeast(100) + var y = top + tInfo.textSize + val chLine = "${ch.number} ${ch.name}" + c.drawText(chLine, padX, y, tInfo) + if (e == null) { + c.drawText(context.getString(R.string.no_programmes), padX, y + dp(30f), tTitle) + return + } + y += dp(8f) + tTitle.textSize + val rec = isScheduled(e) + var tx = padX + if (rec) { + c.drawCircle(tx + dp(6f), y - tTitle.textSize / 3, dp(6f), pDot) + tx += dp(20f) + } + c.drawText(TextUtils.ellipsize(e.title, tTitle, textW - (tx - padX), TextUtils.TruncateAt.END).toString(), tx, y, tTitle) + y += dp(6f) + tInfo.textSize + val mins = (e.stop - e.start) / 60 + val whenText = buildString { + if (e.start <= t && e.stop > t) { + append(context.getString(R.string.now)).append(" · ") + } else if (DateFormat.getDateInstance().format(Date(e.start * 1000)) != DateFormat.getDateInstance().format(Date(t * 1000))) { + append(DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date(e.start * 1000))).append(" ") + } + append(fmtTime.format(Date(e.start * 1000))).append("–").append(fmtTime.format(Date(e.stop * 1000))) + append(" · ").append(mins).append(" min") + if (e.summary.isNotEmpty() && e.summary != e.title) append(" · ").append(e.summary) + } + c.drawText(TextUtils.ellipsize(whenText, tInfo, textW.toFloat(), TextUtils.TruncateAt.END).toString(), padX, y, tInfo) + // progress of a running programme + if (e.start <= t && e.stop > t) { + val pw = dp(160f) + val py = y + dp(6f) + c.drawRect(padX, py, padX + pw, py + dp(3f), pLine) + c.drawRect(padX, py, padX + pw * (t - e.start) / (e.stop - e.start).coerceAtLeast(1), py + dp(3f), pFocus) + } + val desc = e.description.ifEmpty { e.summary }.replace('\n', ' ') + if (desc.isNotEmpty()) { + val lay = StaticLayout.Builder.obtain(desc, 0, desc.length, tDesc, textW) + .setMaxLines(2) + .setEllipsize(TextUtils.TruncateAt.END) + .setAlignment(Layout.Alignment.ALIGN_NORMAL) + .build() + c.save() + c.translate(padX, y + dp(14f)) + lay.draw(c) + c.restore() + } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/ui/GuideActivity.kt b/app/src/main/java/io/simplydvb/tv/ui/GuideActivity.kt new file mode 100644 index 0000000..531e0ec --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/ui/GuideActivity.kt @@ -0,0 +1,138 @@ +package io.simplydvb.tv.ui + +import android.app.Activity +import android.app.AlertDialog +import android.content.Intent +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.view.View +import android.widget.TextView +import android.widget.Toast +import io.simplydvb.tv.R +import io.simplydvb.tv.Server +import io.simplydvb.tv.ServerConfig +import io.simplydvb.tv.htsp.HtsMsg +import io.simplydvb.tv.tif.EpgSync +import io.simplydvb.tv.tif.HChannel +import io.simplydvb.tv.tif.HDvr +import io.simplydvb.tv.tif.HEvent +import io.simplydvb.tv.tif.SyncWorker +import java.text.DateFormat +import java.util.Date +import kotlin.concurrent.thread + +/** Programme guide by channel with recording (scheduled on the server). */ +class GuideActivity : Activity() { + private val main = Handler(Looper.getMainLooper()) + private lateinit var grid: EpgGridView + private var channels: List = emptyList() + private var events: Map> = emptyMap() + private var dvr: MutableList = mutableListOf() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_guide) + grid = findViewById(R.id.grid) + grid.hint = getString(R.string.epg_grid_hint) + grid.isScheduled = { scheduledFor(it) != null } + grid.listener = object : EpgGridView.Listener { + override fun onEvent(ch: HChannel, e: HEvent) = ask(e) + override fun onChannel(ch: HChannel) = watch(ch) + override fun onRecord(e: HEvent) { + val r = scheduledFor(e) + if (r != null) cancel(r) else record(e) + } + } + findViewById(R.id.hint).text = getString(R.string.loading) + load() + } + + private fun load() { + thread(name = "guide") { + try { + val snap = EpgSync.fetch(this) + main.post { + channels = snap.channels + events = snap.events.groupBy { it.channelId }.mapValues { (_, l) -> l.sortedBy { it.start } } + dvr = snap.dvr.toMutableList() + findViewById(R.id.hint).visibility = View.GONE + val sid = ServerConfig.activeId(this) ?: "" + val last = getSharedPreferences("live", MODE_PRIVATE).getLong("last_channel_$sid", -1) + grid.setData(channels, events, channels.indexOfFirst { it.id == last }.coerceAtLeast(0)) + grid.visibility = View.VISIBLE + grid.requestFocus() + } + } catch (e: Exception) { + main.post { findViewById(R.id.hint).text = getString(R.string.error, e.message ?: e.toString()) } + } + } + } + + /** Opens the own player on this channel. */ + private fun watch(ch: HChannel) { + val sid = ServerConfig.activeId(this) ?: "" + getSharedPreferences("live", MODE_PRIVATE).edit().putLong("last_channel_$sid", ch.id).apply() + startActivity(Intent(this, LiveActivity::class.java)) + } + + private fun nowTitle(channelId: Long): String { + val t = System.currentTimeMillis() / 1000 + return events[channelId]?.firstOrNull { it.start <= t && it.stop > t }?.title ?: "" + } + + private fun scheduledFor(e: HEvent): HDvr? = dvr.firstOrNull { + it.channelId == e.channelId && it.start == e.start && (it.state == "scheduled" || it.state == "recording") + } + + private fun ask(e: HEvent) { + val rec = scheduledFor(e) + val b = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert) + .setTitle(e.title) + .setMessage(listOf(e.summary, e.description).filter { it.isNotEmpty() }.joinToString("\n\n").take(800)) + .setNegativeButton(R.string.close, null) + if (rec == null) { + b.setPositiveButton(R.string.record) { _, _ -> record(e) } + } else { + b.setPositiveButton(R.string.cancel_recording) { _, _ -> cancel(rec) } + } + val t = System.currentTimeMillis() / 1000 + val ch = channels.firstOrNull { it.id == e.channelId } + if (ch != null && e.start <= t && e.stop > t) b.setNeutralButton(R.string.watch) { _, _ -> watch(ch) } + b.show() + } + + private fun record(e: HEvent) { + thread(name = "record") { + try { + val r = Server.session(this) { it.request(HtsMsg.method("addDvrEntry").put("eventId", e.id)) } + if (r.int("success") != 1) throw IllegalStateException(r.str("error") ?: "rejected") + val id = r.long("id") ?: 0 + main.post { + dvr.add(HDvr(id, e.channelId, "", e.title, "", e.start, e.stop, "scheduled", 0)) + grid.refresh() + Toast.makeText(this, getString(R.string.recording_scheduled, e.title), Toast.LENGTH_SHORT).show() + } + } catch (ex: Exception) { + main.post { Toast.makeText(this, getString(R.string.error, ex.message), Toast.LENGTH_LONG).show() } + } + } + } + + private fun cancel(r: HDvr) { + thread(name = "cancel") { + try { + val method = if (r.state == "recording") "stopDvrEntry" else "cancelDvrEntry" + Server.session(this) { it.request(HtsMsg.method(method).put("id", r.id)) } + main.post { + dvr.removeAll { it.id == r.id } + grid.refresh() + Toast.makeText(this, R.string.recording_cancelled, Toast.LENGTH_SHORT).show() + SyncWorker.now(this) + } + } catch (ex: Exception) { + main.post { Toast.makeText(this, getString(R.string.error, ex.message), Toast.LENGTH_LONG).show() } + } + } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/ui/LiveActivity.kt b/app/src/main/java/io/simplydvb/tv/ui/LiveActivity.kt new file mode 100644 index 0000000..2e67e95 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/ui/LiveActivity.kt @@ -0,0 +1,874 @@ +package io.simplydvb.tv.ui + +import android.app.Activity +import android.app.AlertDialog +import android.content.Context +import android.content.res.ColorStateList +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.view.KeyEvent +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.WindowManager +import android.widget.AdapterView +import android.widget.BaseAdapter +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ListView +import android.widget.TextView +import android.widget.Toast +import androidx.annotation.OptIn +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.MimeTypes +import androidx.media3.common.PlaybackException +import androidx.media3.common.Player +import androidx.media3.common.TrackSelectionOverride +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.analytics.AnalyticsListener +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.ui.PlayerView +import io.simplydvb.tv.Dvr +import io.simplydvb.tv.Prefs +import io.simplydvb.tv.R +import io.simplydvb.tv.Server +import io.simplydvb.tv.ServerConfig +import io.simplydvb.tv.player.ByteMeter +import io.simplydvb.tv.player.Players +import io.simplydvb.tv.tif.EpgSync +import io.simplydvb.tv.tif.HChannel +import io.simplydvb.tv.tif.HDvr +import io.simplydvb.tv.tif.HEvent +import org.json.JSONObject +import java.text.DateFormat +import java.util.Date +import java.util.Locale +import java.util.concurrent.Executors + +/** + * The app's own live-TV player (alternative to the TV's TV app). + * + * Remote: arrows / CH± zap, digits = number, OK = channel list (right arrow there = guide of + * the highlighted channel, OK on a programme = record / watch), INFO / left = OSD, RED / REC = + * record, GREEN = audio track, YELLOW = subtitles, BLUE = tuner card, LAST = previous channel. + */ +class LiveActivity : Activity() { + private val main = Handler(Looper.getMainLooper()) + private val io = Executors.newFixedThreadPool(2) + private lateinit var player: ExoPlayer + private lateinit var listPanel: LinearLayout + private lateinit var list: ListView + private lateinit var grid: EpgGridView + private lateinit var osd: LinearLayout + private lateinit var message: TextView + private lateinit var card: LinearLayout + private lateinit var spark: SparkView + private lateinit var cpuSpark: SparkView + private lateinit var rateSpark: SparkView + private val meter = ByteMeter() + private var channels: List = emptyList() + private var events: Map> = emptyMap() + private val dvr = ArrayList() + private var index = -1 + private var previous = -1 + private var tuneSeq = 0 + private var loadSeq = 0 + private var decoder = "" + private var lastRendered = -1 + private var lastDropped = -1 + private var retries = 0 + private var digits = "" + private var cardUntil = 0L + private var cardPolling = false + private var osdUntil = 0L + private var osdSignal: JSONObject? = null + private var osdSignalAt = 0L + private var osdBytes = -1L + private var osdBytesAt = 0L + private var osdRate: Double? = null + private val osdTick = object : Runnable { + override fun run() { + if (osd.visibility != View.VISIBLE) return + if (System.currentTimeMillis() >= osdUntil) { + hideOsd() + return + } + updateOsd() + main.postDelayed(this, 1000) + } + } + private val digitsDone = Runnable { tuneNumber() } + + private fun prefs() = getSharedPreferences("live", Context.MODE_PRIVATE) + private val tunerInfo get() = Prefs.tunerCard(this) + + @OptIn(UnstableApi::class) + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_live) + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + listPanel = findViewById(R.id.list_panel) + list = findViewById(R.id.list) + grid = findViewById(R.id.epg_grid) + osd = findViewById(R.id.osd) + message = findViewById(R.id.message) + card = findViewById(R.id.tuner_card) + spark = findViewById(R.id.t_spark) + cpuSpark = findViewById(R.id.t_cpu_spark).apply { + setup(Triple("#f69b74", 100f, true), Triple("#e8ece9", 100f, false)) + } + rateSpark = findViewById(R.id.t_rate_spark).apply { + setup(Triple("#7aa7ff", 0f, true)) + } + player = Players.create(this, live = true, meter = meter, tunneling = Players.tunneling(this)) + player.addAnalyticsListener(object : AnalyticsListener { + override fun onVideoDecoderInitialized(eventTime: AnalyticsListener.EventTime, decoderName: String, initializedTimestampMs: Long, initializationDurationMs: Long) { + decoder = decoderName + } + }) + findViewById(R.id.player).player = player + player.addListener(object : Player.Listener { + override fun onRenderedFirstFrame() { + retries = 0 + message.visibility = View.GONE + } + + override fun onPlaybackStateChanged(state: Int) { + if (state == Player.STATE_ENDED) main.postDelayed({ tune(index, banner = false) }, 500) + } + + override fun onPlayerError(error: PlaybackException) { + if (retries < 5) { + retries++ + main.postDelayed({ tune(index, banner = false) }, 1500L * retries) + } else { + showMessage(getString(R.string.no_signal, error.errorCodeName)) + } + } + }) + list.adapter = adapter + list.setOnItemClickListener { _, _, pos, _ -> + closePanels() + tune(pos) + } + grid.hint = getString(R.string.epg_grid_hint) + grid.isScheduled = { scheduledFor(it) != null } + grid.listener = object : EpgGridView.Listener { + override fun onEvent(ch: HChannel, e: HEvent) = askEvent(e) + override fun onChannel(ch: HChannel) { + val i = channels.indexOf(ch) + closePanels() + if (i >= 0) tune(i) + } + override fun onRecord(e: HEvent) { + val r = scheduledFor(e) + if (r != null) cancel(r) else record(e) + } + } + loadServer() + } + + private val serverId get() = ServerConfig.activeId(this) ?: "" + private fun lastKey() = "last_channel_$serverId" + + /** (Re)loads channels, EPG and recordings of the active server and tunes its last channel. */ + private fun loadServer() { + val seq = ++loadSeq + player.stop() + tuneSeq++ + channels = emptyList() + events = emptyMap() + dvr.clear() + index = -1 + previous = -1 + adapter.notifyDataSetChanged() + val srv = ServerConfig.load(this) + val count = ServerConfig.all(this).size + findViewById(R.id.list_server).text = + srv.label + if (count > 1) " · " + getString(R.string.switch_server_hint) else "" + showMessage(getString(R.string.loading) + " · " + srv.label) + io.execute { + try { + val snap = EpgSync.fetch(this, epgDays = 2) + main.post { + if (seq != loadSeq) return@post + channels = snap.channels + events = snap.events.groupBy { it.channelId }.mapValues { (_, l) -> l.sortedBy { it.start } } + dvr.clear() + dvr.addAll(snap.dvr) + adapter.notifyDataSetChanged() + if (channels.isEmpty()) { + showMessage(getString(R.string.no_channels)) + } else { + val p = prefs() + val last = p.getLong(lastKey(), p.getLong("last_channel", -1)) + tune(channels.indexOfFirst { it.id == last }.coerceAtLeast(0)) + if (listPanel.visibility == View.VISIBLE) openList() + } + } + } catch (e: Exception) { + main.post { if (seq == loadSeq) showMessage(getString(R.string.error, e.message ?: e.toString())) } + } + } + } + + /** Server picker (left arrow in the channel list). */ + private fun chooseServer() { + val servers = ServerConfig.all(this).filter { it.configured } + if (servers.size < 2) return + val active = serverId + val names = servers.map { it.label + if (it.id == active) " · " + getString(R.string.active) else "" }.toTypedArray() + AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert) + .setTitle(R.string.choose_server) + .setSingleChoiceItems(names, servers.indexOfFirst { it.id == active }) { d, which -> + d.dismiss() + val s = servers[which] + if (s.id == active) return@setSingleChoiceItems + ServerConfig.setActive(this, s.id) + toast(getString(R.string.server_switched, s.label)) + cardUntil = 0 + grid.visibility = View.GONE + loadServer() + } + .show() + } + + private fun showMessage(text: String) { + message.text = text + message.visibility = View.VISIBLE + } + + private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show() + + // ------------------------------------------------------------ tuning + + private fun tune(i: Int, banner: Boolean = true) { + if (channels.isEmpty()) return + val target = (i + channels.size) % channels.size + if (target != index && index >= 0) previous = index + index = target + val ch = channels[index] + // the start screen shows this channel and what is on it + prefs().edit() + .putLong(lastKey(), ch.id) + .putInt(lastKey() + "_number", ch.number) + .putString(lastKey() + "_name", ch.name) + .apply() + if (banner) { + osdSignal = null + osdBytes = -1 + osdRate = null + if (Prefs.osdOnZap(this)) showOsd() else hideOsd() + if (tunerInfo) showCard() + } + updateRec() + player.stop() + val seq = ++tuneSeq + io.execute { + try { + val url = Server.session(this) { Server.ticketUrl(this, it, channelId = ch.id) } + main.post { + if (seq != tuneSeq) return@post + player.setMediaItem(MediaItem.Builder().setUri(url).setMimeType(MimeTypes.VIDEO_MP2T).build()) + player.prepare() + player.playWhenReady = true + } + } catch (e: Exception) { + main.post { if (seq == tuneSeq) showMessage(getString(R.string.error, e.message ?: e.toString())) } + } + } + } + + private fun tuneNumber() { + val n = digits.toIntOrNull() + digits = "" + val i = channels.indexOfFirst { it.number == n } + findViewById(R.id.digits).visibility = View.GONE + if (i >= 0) tune(i) + } + + private fun nowNext(ch: HChannel): Pair { + val t = System.currentTimeMillis() / 1000 + val l = events[ch.id].orEmpty() + val i = l.indexOfFirst { it.start <= t && it.stop > t } + return if (i >= 0) l[i] to l.getOrNull(i + 1) else null to l.firstOrNull { it.start > t } + } + + private fun activeRecording(channelId: Long): HDvr? { + val t = System.currentTimeMillis() / 1000 + return dvr.firstOrNull { + it.channelId == channelId && (it.state == "recording" || (it.state == "scheduled" && it.start <= t && it.stop > t)) + } + } + + private fun scheduledFor(e: HEvent): HDvr? = dvr.firstOrNull { + it.channelId == e.channelId && it.start == e.start && (it.state == "scheduled" || it.state == "recording") + } + + private fun updateRec() { + val ch = channels.getOrNull(index) + findViewById(R.id.rec).visibility = + if (ch != null && activeRecording(ch.id) != null) View.VISIBLE else View.GONE + } + + // ------------------------------------------------------------ OSD + + private val fmtTime: DateFormat = DateFormat.getTimeInstance(DateFormat.SHORT) + + private fun span(e: HEvent) = fmtTime.format(Date(e.start * 1000)) + "–" + fmtTime.format(Date(e.stop * 1000)) + + /** Programme before, during and after `t` on a channel. */ + private fun around(ch: HChannel, t: Long): Triple> { + val l = events[ch.id].orEmpty() + val i = l.indexOfFirst { it.start <= t && it.stop > t } + return if (i >= 0) { + Triple(l.getOrNull(i - 1)?.takeIf { it.stop <= t }, l[i], l.drop(i + 1).take(2)) + } else { + Triple(l.lastOrNull { it.stop <= t }, null, l.filter { it.start > t }.take(2)) + } + } + + /** Shows the OSD for `seconds` (programme info, progress, technical details). */ + private fun showOsd(seconds: Int = Prefs.osdSeconds(this)) { + val ch = channels.getOrNull(index) ?: return + osdUntil = System.currentTimeMillis() + seconds * 1000L + findViewById(R.id.o_number).text = ch.number.toString() + findViewById(R.id.o_name).text = ch.name + Logos.load(this, ch.icon, findViewById(R.id.o_logo)) + fillProgrammes(ch) + updateOsd() + osd.animate().cancel() + if (osd.visibility != View.VISIBLE) { + osd.alpha = 0f + osd.translationY = 40f + osd.visibility = View.VISIBLE + } + osd.animate().alpha(1f).translationY(0f).setDuration(180).start() + main.removeCallbacks(osdTick) + main.postDelayed(osdTick, 1000) + } + + private fun hideOsd() { + main.removeCallbacks(osdTick) + if (osd.visibility != View.VISIBLE) return + osdUntil = 0 + // the end action does not run if showOsd() cancels the animation + osd.animate().alpha(0f).translationY(40f).setDuration(160).withEndAction { osd.visibility = View.GONE }.start() + } + + private fun fillProgrammes(ch: HChannel) { + val t = System.currentTimeMillis() / 1000 + val (prev, now, later) = around(ch, t) + findViewById(R.id.o_now_box).visibility = View.VISIBLE + if (now != null) { + findViewById(R.id.o_now_time).text = span(now) + findViewById(R.id.o_now_title).text = now.title + val desc = if (Prefs.osdDescription(this)) now.description.ifEmpty { now.summary }.replace('\n', ' ') else "" + findViewById(R.id.o_now_desc).apply { + text = desc + visibility = if (desc.isEmpty()) View.GONE else View.VISIBLE + } + findViewById(R.id.o_progress).visibility = View.VISIBLE + } else { + findViewById(R.id.o_now_time).text = "" + findViewById(R.id.o_now_title).text = getString(R.string.no_programmes) + findViewById(R.id.o_now_desc).visibility = View.GONE + findViewById(R.id.o_progress).visibility = View.GONE + findViewById(R.id.o_now_left).text = "" + } + fun column(box: Int, label: Int, value: Int, title: String, e: HEvent?) { + findViewById(box).visibility = if (e == null) View.INVISIBLE else View.VISIBLE + findViewById(label).text = title + findViewById(value).text = e?.let { fmtTime.format(Date(it.start * 1000)) + " " + it.title } ?: "" + } + column(R.id.o_prev_box, R.id.o_prev_label, R.id.o_prev, getString(R.string.osd_before), prev) + column(R.id.o_next_box, R.id.o_next_label, R.id.o_next, getString(R.string.osd_next), later.getOrNull(0)) + column(R.id.o_later_box, R.id.o_later_label, R.id.o_later, getString(R.string.osd_later), later.getOrNull(1)) + findViewById(R.id.o_more).visibility = if (prev == null && later.isEmpty()) View.GONE else View.VISIBLE + } + + /** Every second while the OSD is shown: clock, progress, technical chips. */ + @OptIn(UnstableApi::class) + private fun updateOsd() { + val ch = channels.getOrNull(index) ?: return + val nowMs = System.currentTimeMillis() + val t = nowMs / 1000 + findViewById(R.id.o_clock).text = fmtTime.format(Date(nowMs)) + findViewById(R.id.o_date).text = + android.text.format.DateFormat.format("EEE d MMM", Date(nowMs)).toString() + val (_, now, _) = around(ch, t) + if (now != null) { + val total = (now.stop - now.start).coerceAtLeast(1) + findViewById(R.id.o_progress).progress = ((t - now.start) * 1000 / total).toInt().coerceIn(0, 1000) + val left = ((now.stop - t + 59) / 60).coerceAtLeast(0) + findViewById(R.id.o_now_left).text = getString(R.string.osd_left, left) + } + // throughput measured over the OSD's own window + val bytes = meter.total() + if (osdBytes >= 0 && nowMs - osdBytesAt >= 900) { + osdRate = (bytes - osdBytes) * 8000.0 / (nowMs - osdBytesAt) + } + if (osdBytes < 0 || nowMs - osdBytesAt >= 900) { + osdBytes = bytes + osdBytesAt = nowMs + } + renderChips(ch) + // signal from the server, every 2 s while the OSD is up + if (Prefs.osdTech(this) && nowMs - osdSignalAt >= 2000) { + osdSignalAt = nowMs + val chId = ch.id + io.execute { + val j = try { + Server.getJson(this, "/api/status/inputs?channel=$chId").optJSONArray("entries")?.optJSONObject(0) + } catch (_: Exception) { + null + } + main.post { + if (channels.getOrNull(index)?.id == chId) { + osdSignal = j + if (osd.visibility == View.VISIBLE) renderChips(channels[index]) + } + } + } + } + } + + private fun chip(text: String, color: Int = getColor(R.color.text), rec: Boolean = false): TextView = + TextView(this).apply { + this.text = text + textSize = 11f + setTextColor(if (rec) getColor(R.color.text) else color) + typeface = android.graphics.Typeface.MONOSPACE + setBackgroundResource(if (rec) R.drawable.chip_rec else R.drawable.chip) + val d = resources.displayMetrics.density + setPadding((8 * d).toInt(), (3 * d).toInt(), (8 * d).toInt(), (3 * d).toInt()) + layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) + .apply { marginEnd = (6 * d).toInt() } + } + + @OptIn(UnstableApi::class) + private fun renderChips(ch: HChannel) { + val box = findViewById(R.id.o_chips) + box.removeAllViews() + if (activeRecording(ch.id) != null) box.addView(chip("REC", rec = true)) + if (!Prefs.osdTech(this)) { + box.visibility = if (box.childCount > 0) View.VISIBLE else View.GONE + return + } + box.visibility = View.VISIBLE + player.videoFormat?.let { f -> + if (f.width > 0) { + val tag = when { + f.height >= 2160 -> "UHD" + f.height >= 1080 -> "Full HD" + f.height >= 720 -> "HD" + else -> "SD" + } + val fps = if (f.frameRate > 0) " %.0f fps".format(Locale.ROOT, f.frameRate) else "" + box.addView(chip("$tag ${f.width}×${f.height}$fps")) + } + } + player.audioFormat?.let { a -> + val codec = when (a.sampleMimeType) { + MimeTypes.AUDIO_AC3 -> "AC-3" + MimeTypes.AUDIO_E_AC3, MimeTypes.AUDIO_E_AC3_JOC -> "E-AC-3" + MimeTypes.AUDIO_AAC -> "AAC" + MimeTypes.AUDIO_MPEG, MimeTypes.AUDIO_MPEG_L2 -> "MPEG" + else -> null + } + val chs = when (a.channelCount) { + 1 -> "mono"; 2 -> "2.0"; 6 -> "5.1"; 8 -> "7.1"; else -> null + } + listOfNotNull(codec, chs).takeIf { it.isNotEmpty() }?.let { box.addView(chip(it.joinToString(" "))) } + } + osdSignal?.let { j -> + val sig = num(j, "strength_pct") + val snr = num(j, "snr_db") + if (sig != null || snr != null) { + val good = (snr ?: 99.0) >= 20 && (sig ?: 100.0) >= 50 + val weak = (snr ?: 99.0) < 15 || (sig ?: 100.0) < 30 + val color = getColor(if (weak) R.color.red else if (good) R.color.green else R.color.accent) + val txt = listOfNotNull( + sig?.let { getString(R.string.osd_signal) + " %.0f%%".format(Locale.ROOT, it) }, + snr?.let { "SNR %.0f dB".format(Locale.ROOT, it) }, + ).joinToString(" ") + box.addView(chip(txt, color)) + } + } + osdRate?.takeIf { it > 0 }?.let { box.addView(chip(mbit(it), getColor(R.color.blue))) } + } + + // ------------------------------------------------------------ tuner card + + /** Shows the tuner card for a few seconds, refreshing it every second from the server. */ + private fun showCard(seconds: Int = 8) { + cardUntil = System.currentTimeMillis() + seconds * 1000L + if (card.visibility != View.VISIBLE) { + spark.clear() + findViewById(R.id.t_name).text = getString(R.string.loading) + findViewById(R.id.t_stream).text = "" + card.visibility = View.VISIBLE + } + if (!cardPolling) { + cardPolling = true + pollCard() + } + } + + private fun pollCard() { + if (System.currentTimeMillis() > cardUntil || isFinishing) { + card.visibility = View.GONE + cardPolling = false + return + } + val ch = channels.getOrNull(index) + if (ch == null) { + main.postDelayed({ pollCard() }, 1000) + return + } + io.execute { + val t = try { + Server.getJson(this, "/api/status/inputs?channel=${ch.id}").optJSONArray("entries")?.optJSONObject(0) + } catch (_: Exception) { + null + } + main.post { + val rate = meter.rate() + if (t != null) renderCard(t, rate) else renderRate(rate, null) + renderVideo() + main.postDelayed({ pollCard() }, 1000) + } + } + } + + private fun num(o: JSONObject, k: String): Double? = if (o.isNull(k) || !o.has(k)) null else o.optDouble(k).takeIf { !it.isNaN() } + + private fun mbit(bps: Double) = if (bps >= 1e6) "%.1f Mb/s".format(Locale.ROOT, bps / 1e6) else "%.0f kb/s".format(Locale.ROOT, bps / 1e3) + + /** What the TV does with the stream: resolution, rendered / dropped frames per second, buffer, decoder. */ + @OptIn(UnstableApi::class) + private fun renderVideo() { + val f = player.videoFormat + val parts = ArrayList() + if (f != null) { + parts.add("${f.width}x${f.height}" + if (f.frameRate > 0) " %.0ffps".format(Locale.ROOT, f.frameRate) else "") + } + val c = player.videoDecoderCounters + if (c != null) { + c.ensureUpdated() + val r = c.renderedOutputBufferCount + // only frames thrown away because they came too late; "skipped" ones are the + // frames before the first keyframe when joining a stream – normal + val d = c.droppedBufferCount + if (lastRendered >= 0 && r >= lastRendered) { + parts.add("${r - lastRendered}/s") + val dd = d - lastDropped + if (dd > 0) parts.add("drop $dd/s") + } + lastRendered = r + lastDropped = d + } + parts.add("buf %.1fs".format(Locale.ROOT, player.totalBufferedDuration / 1000.0)) + if (Players.tunneling(this)) parts.add("tunnel") + if (decoder.isNotEmpty()) parts.add(decoder.removePrefix("OMX.").removePrefix("c2.")) + val v = findViewById(R.id.t_video) + v.text = parts.joinToString(" · ") + v.setTextColor(getColor(if (parts.any { it.startsWith("drop") }) R.color.red else R.color.text)) + } + + private fun renderRate(rate: Double?, mux: Long?) { + if (rate != null) rateSpark.push(rate.toFloat()) + findViewById(R.id.t_rate).text = rate?.let { mbit(it) } ?: "–" + findViewById(R.id.t_rate_sub).text = mux?.takeIf { it > 0 }?.let { "MUX " + mbit(it.toDouble()) } ?: "" + } + + private fun renderCard(t: JSONObject, rate: Double?) { + val locked = t.optBoolean("locked", true) + val sig = num(t, "strength_pct") + val snr = num(t, "snr_db") + val dbm = num(t, "strength_dbm") + val ber = num(t, "ber") + findViewById(R.id.t_lock).backgroundTintList = + ColorStateList.valueOf(getColor(if (locked) R.color.green else R.color.red)) + findViewById(R.id.t_name).text = t.optString("input") + findViewById(R.id.t_stream).text = t.optString("stream") + findViewById(R.id.t_signal).text = + (sig?.let { "%.0f%%".format(Locale.ROOT, it) } ?: "–") + " " + (snr?.let { "%.0fdB".format(Locale.ROOT, it) } ?: "") + spark.add(snr?.toFloat(), sig?.toFloat()) + // server load + val cpu = num(t, "server_cpu") + val proc = num(t, "server_proc_cpu") + val temp = num(t, "server_temp") + cpuSpark.push(cpu?.toFloat(), proc?.toFloat()) + findViewById(R.id.t_cpu).text = cpu?.let { "%.0f%%".format(Locale.ROOT, it) } ?: "–" + findViewById(R.id.t_cpu_sub).text = listOfNotNull( + proc?.let { "dvb %.1f%%".format(Locale.ROOT, it) }, + temp?.let { "%.0f°C".format(Locale.ROOT, it) }, + ).joinToString(" ") + renderRate(rate, t.optLong("bps")) + val lines = ArrayList() + listOfNotNull( + t.optString("modulation").takeIf { it.isNotEmpty() && it != "null" }, + t.optString("code_rate").takeIf { it.isNotEmpty() && it != "null" }?.let { "FEC $it" }, + t.optString("guard_interval").takeIf { it.isNotEmpty() && it != "null" }?.let { "GI $it" }, + dbm?.let { "%.1f dBm".format(Locale.ROOT, it) }, + ).takeIf { it.isNotEmpty() }?.let { lines.add(it.joinToString(" · ")) } + lines.add( + listOfNotNull( + ber?.let { "BER %.1e".format(Locale.ROOT, it) }, + "UNC ${t.optLong("unc")}", + "CC ${t.optLong("cc")}", + "TEI ${t.optLong("te")}", + "${t.optInt("subs")} cl.", + ).joinToString(" · "), + ) + // driver timing (simply-dvb 0.1.14+): slow demodulator reads / pauses in the stream + if (t.has("read_gap_ms") && !t.isNull("read_gap_ms")) { + lines.add("stats ${t.optLong("status_ms")} ms · gap ${t.optLong("read_gap_ms")} ms") + } + findViewById(R.id.t_details).text = lines.joinToString("\n") + } + + // ------------------------------------------------------------ guide & recording + + private fun closePanels() { + listPanel.visibility = View.GONE + grid.visibility = View.GONE + } + + private fun openList() { + listPanel.visibility = View.VISIBLE + hideOsd() + list.setSelection(index.coerceAtLeast(0)) + list.setItemChecked(index, true) + list.requestFocus() + } + + /** Full-screen programme grid, focused on channel `chIndex`. */ + private fun openGuide(chIndex: Int) { + if (channels.isEmpty()) return + listPanel.visibility = View.GONE + hideOsd() + cardUntil = 0 + card.visibility = View.GONE + grid.setData(channels, events, chIndex.coerceAtLeast(0)) + grid.visibility = View.VISIBLE + grid.requestFocus() + } + + private fun askEvent(e: HEvent) { + val rec = scheduledFor(e) + val t = System.currentTimeMillis() / 1000 + val chIndex = channels.indexOfFirst { it.id == e.channelId } + val b = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert) + .setTitle(e.title) + .setMessage(listOf(e.summary, e.description).filter { it.isNotEmpty() }.joinToString("\n\n").take(700)) + .setNegativeButton(R.string.close, null) + if (rec == null) b.setPositiveButton(R.string.record) { _, _ -> record(e) } + else b.setPositiveButton(R.string.cancel_recording) { _, _ -> cancel(rec) } + if (e.start <= t && chIndex >= 0) b.setNeutralButton(R.string.watch) { _, _ -> + closePanels() + tune(chIndex) + } + b.show() + } + + private fun record(e: HEvent) { + io.execute { + try { + val r = Dvr.record(this, e) + main.post { + dvr.add(r) + toast(getString(R.string.recording_scheduled, e.title)) + grid.refresh() + adapter.notifyDataSetChanged() + updateRec() + } + } catch (ex: Exception) { + main.post { toast(getString(R.string.error, ex.message)) } + } + } + } + + private fun cancel(r: HDvr) { + io.execute { + try { + Dvr.cancel(this, r) + main.post { + dvr.removeAll { it.id == r.id } + toast(getString(if (r.state == "recording") R.string.recording_stopped else R.string.recording_cancelled)) + grid.refresh() + adapter.notifyDataSetChanged() + updateRec() + } + } catch (ex: Exception) { + main.post { toast(getString(R.string.error, ex.message)) } + } + } + } + + /** RED / REC: records the current programme of this channel (or stops a running recording). */ + private fun recordCurrent() { + val ch = channels.getOrNull(index) ?: return + activeRecording(ch.id)?.let { return cancel(it.copy(state = "recording")) } + val now = nowNext(ch).first + if (now != null) { + record(now) + return + } + io.execute { + try { + val r = Dvr.recordNow(this, ch.id, ch.name, 2 * 3600) + main.post { + dvr.add(r) + toast(getString(R.string.no_epg_now)) + updateRec() + } + } catch (ex: Exception) { + main.post { toast(getString(R.string.error, ex.message)) } + } + } + } + + // ------------------------------------------------------------ audio / subtitles + + private fun cycleAudio() { + val groups = player.currentTracks.groups.filter { it.type == C.TRACK_TYPE_AUDIO } + val all = groups.flatMap { g -> (0 until g.length).map { g to it } } + if (all.size < 2) return + val cur = all.indexOfFirst { (g, i) -> g.isTrackSelected(i) } + val (g, i) = all[(cur + 1) % all.size] + player.trackSelectionParameters = player.trackSelectionParameters.buildUpon() + .setOverrideForType(TrackSelectionOverride(g.mediaTrackGroup, i)).build() + val f = g.getTrackFormat(i) + val name = listOfNotNull( + f.language?.let { Locale(it).displayLanguage.ifEmpty { it } }, + f.label, + when (f.sampleMimeType) { + MimeTypes.AUDIO_AC3 -> "AC-3" + MimeTypes.AUDIO_E_AC3 -> "E-AC-3" + MimeTypes.AUDIO_AAC -> "AAC" + else -> null + }, + ).joinToString(" · ").ifEmpty { "${(cur + 1) % all.size + 1}" } + toast(getString(R.string.audio_track, name)) + } + + private fun toggleSubtitles() { + val off = !player.trackSelectionParameters.disabledTrackTypes.contains(C.TRACK_TYPE_TEXT) + player.trackSelectionParameters = player.trackSelectionParameters.buildUpon() + .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, off).build() + toast(getString(if (off) R.string.subtitles_off else R.string.subtitles_on)) + } + + // ------------------------------------------------------------ keys + + /** GUIDE before any view (PlayerView) gets the key. */ + override fun dispatchKeyEvent(event: KeyEvent): Boolean { + if (event.keyCode == KeyEvent.KEYCODE_GUIDE || event.keyCode == KeyEvent.KEYCODE_TV_DATA_SERVICE) { + if (event.action == KeyEvent.ACTION_UP) { + if (grid.visibility == View.VISIBLE) { + closePanels() + } else { + openGuide(if (listPanel.visibility == View.VISIBLE) list.selectedItemPosition.takeIf { it >= 0 } ?: index else index) + } + } + return true + } + return super.dispatchKeyEvent(event) + } + + override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { + if (grid.visibility == View.VISIBLE) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + closePanels() + return true + } + return super.onKeyDown(keyCode, event) + } + if (listPanel.visibility == View.VISIBLE) { + when (keyCode) { + KeyEvent.KEYCODE_BACK -> closePanels() + KeyEvent.KEYCODE_DPAD_LEFT -> chooseServer() + KeyEvent.KEYCODE_DPAD_RIGHT -> openGuide(list.selectedItemPosition.takeIf { it >= 0 } ?: index) + else -> return super.onKeyDown(keyCode, event) + } + return true + } + when (keyCode) { + // like a TV remote: up / CH+ = next channel, down / CH- = previous + KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_PAGE_UP -> tune(index + 1) + KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_CHANNEL_DOWN, KeyEvent.KEYCODE_PAGE_DOWN -> tune(index - 1) + KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_MENU -> openList() + KeyEvent.KEYCODE_DPAD_RIGHT -> openGuide(index) + // INFO / left: OSD on or off (and the tuner card, if it is switched on) + KeyEvent.KEYCODE_INFO, KeyEvent.KEYCODE_DPAD_LEFT -> { + if (osd.visibility == View.VISIBLE) { + hideOsd() + } else { + showOsd(seconds = maxOf(Prefs.osdSeconds(this), 10)) + if (tunerInfo) showCard() + } + } + KeyEvent.KEYCODE_BACK -> if (osd.visibility == View.VISIBLE) hideOsd() else return super.onKeyDown(keyCode, event) + KeyEvent.KEYCODE_LAST_CHANNEL -> if (previous >= 0) tune(previous) + KeyEvent.KEYCODE_PROG_RED, KeyEvent.KEYCODE_MEDIA_RECORD -> recordCurrent() + KeyEvent.KEYCODE_PROG_GREEN, KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK -> cycleAudio() + KeyEvent.KEYCODE_PROG_YELLOW, KeyEvent.KEYCODE_CAPTIONS -> toggleSubtitles() + KeyEvent.KEYCODE_PROG_BLUE -> { + // toggles the automatic tuner card + val on = !tunerInfo + prefs().edit().putBoolean("tuner_info", on).apply() + toast(getString(R.string.tuner_info) + ": " + getString(if (on) R.string.on else R.string.off)) + if (on) showCard() else cardUntil = 0 + } + in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9 -> { + digits += (keyCode - KeyEvent.KEYCODE_0).toString() + findViewById(R.id.digits).apply { + text = digits + visibility = View.VISIBLE + } + main.removeCallbacks(digitsDone) + main.postDelayed(digitsDone, 1500) + } + else -> return super.onKeyDown(keyCode, event) + } + return true + } + + override fun onStop() { + super.onStop() + player.stop() + } + + override fun onRestart() { + super.onRestart() + if (index >= 0) tune(index, banner = false) + } + + override fun onDestroy() { + super.onDestroy() + player.release() + io.shutdownNow() + main.removeCallbacksAndMessages(null) + } + + private val adapter = object : BaseAdapter() { + override fun getCount() = channels.size + override fun getItem(position: Int) = channels[position] + override fun getItemId(position: Int) = channels[position].id + + override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { + val v = convertView ?: LayoutInflater.from(this@LiveActivity).inflate(R.layout.row_channel, parent, false) + val ch = channels[position] + v.findViewById(R.id.number).text = ch.number.toString() + v.findViewById(R.id.name).text = + if (activeRecording(ch.id) != null) "${ch.name} · REC" else ch.name + v.findViewById(R.id.now).text = nowNext(ch).first?.title ?: "" + Logos.load(this@LiveActivity, ch.icon, v.findViewById(R.id.logo)) + return v + } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/ui/Logos.kt b/app/src/main/java/io/simplydvb/tv/ui/Logos.kt new file mode 100644 index 0000000..f243584 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/ui/Logos.kt @@ -0,0 +1,47 @@ +package io.simplydvb.tv.ui + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.os.Handler +import android.os.Looper +import android.util.LruCache +import android.widget.ImageView +import io.simplydvb.tv.Server +import java.util.concurrent.Executors + +/** Channel logos from the server, loaded in the background and kept in memory. */ +object Logos { + private val cache = LruCache(200) + private val missing = HashSet() + private val pool = Executors.newFixedThreadPool(3) + private val main = Handler(Looper.getMainLooper()) + + fun load(ctx: Context, icon: String, view: ImageView) { + val url = Server.iconUrl(ctx, icon) + view.tag = url + if (url == null) { + view.setImageDrawable(null) + return + } + cache.get(url)?.let { + view.setImageBitmap(it) + return + } + view.setImageDrawable(null) + if (synchronized(missing) { url in missing }) return + pool.execute { + val bmp = try { + Server.download(url)?.let { BitmapFactory.decodeByteArray(it, 0, it.size) } + } catch (_: Exception) { + null + } + if (bmp == null) { + synchronized(missing) { missing.add(url) } + return@execute + } + cache.put(url, bmp) + main.post { if (view.tag == url) view.setImageBitmap(bmp) } + } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/ui/MainActivity.kt b/app/src/main/java/io/simplydvb/tv/ui/MainActivity.kt new file mode 100644 index 0000000..39f2c68 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/ui/MainActivity.kt @@ -0,0 +1,245 @@ +package io.simplydvb.tv.ui + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.content.res.ColorStateList +import android.media.tv.TvContract +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.text.format.DateUtils +import android.view.View +import android.widget.ProgressBar +import android.widget.TextView +import android.widget.Toast +import io.simplydvb.tv.AutoStart +import io.simplydvb.tv.R +import io.simplydvb.tv.Server +import io.simplydvb.tv.ServerConfig +import io.simplydvb.tv.tif.EpgSync +import io.simplydvb.tv.tif.SyncWorker +import java.security.MessageDigest +import java.text.DateFormat +import java.util.Date +import kotlin.concurrent.thread + +/** + * Start screen: the player first (focused, OK opens it on the last channel, with what is on + * there right now from the server), shortcuts, the server's state and the remote's keys. + */ +class MainActivity : Activity() { + private var askedSetup = false + private val main = Handler(Looper.getMainLooper()) + private val time = DateFormat.getTimeInstance(DateFormat.SHORT) + + /** The programme now on the last channel, as the server reported it. */ + private data class NowOn(val title: String, val start: Long, val stop: Long) + + private var nowOn: NowOn? = null + private var channelLabel: String? = null + private var nowError: String? = null + private var fetchedAt = 0L + private var fetching = false + + private val tick = object : Runnable { + override fun run() { + showClock() + val t = System.currentTimeMillis() / 1000 + // ask again when the programme ended, and every 5 minutes anyway + val stale = nowOn?.let { t >= it.stop } ?: true + if ((stale && System.currentTimeMillis() - fetchedAt > 30_000) || System.currentTimeMillis() - fetchedAt > 300_000) { + loadNowOn() + } else { + showNowOn() + } + main.postDelayed(this, 15_000) + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + findViewById(R.id.live).setOnClickListener { startActivity(Intent(this, LiveActivity::class.java)) } + findViewById(R.id.guide).setOnClickListener { startActivity(Intent(this, GuideActivity::class.java)) } + findViewById(R.id.recordings).setOnClickListener { startActivity(Intent(this, RecordingsActivity::class.java)) } + findViewById(R.id.watch).setOnClickListener { openTvApp() } + findViewById(R.id.servers).setOnClickListener { startActivity(Intent(this, ServersActivity::class.java)) } + findViewById(R.id.settings).setOnClickListener { startActivity(Intent(this, SettingsActivity::class.java)) } + findViewById(R.id.sync).setOnClickListener { + SyncWorker.now(this) + Toast.makeText(this, R.string.sync_started, Toast.LENGTH_SHORT).show() + } + AutoStart.apply(this) + SyncWorker.schedule(this) + findViewById(R.id.live).requestFocus() + } + + override fun onResume() { + super.onResume() + if (ServerConfig.all(this).isEmpty() && !askedSetup) { + askedSetup = true + startActivity(Intent(this, SetupActivity::class.java)) + } + showServer() + // back from the player or another server: what is on may have changed + fetchedAt = 0 + main.removeCallbacks(tick) + main.post(tick) + } + + override fun onPause() { + super.onPause() + main.removeCallbacks(tick) + } + + private fun showClock() { + val now = Date() + findViewById(R.id.m_clock).text = time.format(now) + findViewById(R.id.m_date).text = DateFormat.getDateInstance(DateFormat.FULL).format(now) + } + + // ------------------------------------------------------------ what is on + + /** The channel the player opens: last one watched on the active server. */ + private fun lastChannel(): Triple? { + val sid = ServerConfig.activeId(this) ?: return null + val p = getSharedPreferences("live", Context.MODE_PRIVATE) + val id = p.getLong("last_channel_$sid", -1) + if (id < 0) return null + return Triple(id, p.getInt("last_channel_${sid}_number", 0), p.getString("last_channel_${sid}_name", null) ?: "") + } + + /** The server's channel UUID (the same derivation as simply-dvb's `Channel::uuid`). */ + private fun channelUuid(id: Long): String = + MessageDigest.getInstance("SHA-256").digest("simple-dvbt/channel/$id".toByteArray()) + .take(16).joinToString("") { "%02x".format(it) } + + private fun loadNowOn() { + if (fetching) return + val last = lastChannel() + val srv = ServerConfig.load(this) + if (last == null || !srv.configured) { + nowOn = null + channelLabel = null + nowError = null + fetchedAt = System.currentTimeMillis() + showNowOn() + return + } + if (nowOn == null && nowError == null) findViewById(R.id.m_now).text = getString(R.string.m_loading) + fetching = true + thread(name = "now-on") { + var on: NowOn? = null + var label: String? = last.third.takeIf { it.isNotEmpty() }?.let { if (last.second > 0) "${last.second} · $it" else it } + var err: String? = null + try { + val j = Server.getJson(this, "/api/epg/events/grid?channel=${channelUuid(last.first)}&limit=2", srv) + val t = System.currentTimeMillis() / 1000 + val entries = j.optJSONArray("entries") + for (i in 0 until (entries?.length() ?: 0)) { + val e = entries!!.getJSONObject(i) + if (label == null) { + val n = e.optInt("channelNumber") + label = (if (n > 0) "$n · " else "") + e.optString("channelName") + } + val start = e.optLong("start") + val stop = e.optLong("stop") + if (start <= t && stop > t) { + on = NowOn(e.optString("title"), start, stop) + break + } + } + } catch (e: Exception) { + err = e.message ?: e.toString() + } + main.post { + fetching = false + fetchedAt = System.currentTimeMillis() + nowOn = on + channelLabel = label + nowError = err + showNowOn() + } + } + } + + private fun showNowOn() { + val text = findViewById(R.id.m_now) + val bar = findViewById(R.id.m_progress) + val t = System.currentTimeMillis() / 1000 + val on = nowOn?.takeIf { t < it.stop } + text.setTextColor(getColor(if (nowError != null) R.color.red else R.color.text_soft)) + when { + nowError != null -> { + text.text = getString(R.string.m_unreachable, nowError) + bar.visibility = View.INVISIBLE + } + channelLabel == null && lastChannel() == null -> { + text.text = getString(R.string.m_first) + bar.visibility = View.INVISIBLE + } + on == null -> { + text.text = getString(R.string.m_resume, channelLabel ?: "") + " · " + getString(R.string.m_no_epg) + bar.visibility = View.INVISIBLE + } + else -> { + val span = time.format(Date(on.start * 1000)) + "–" + time.format(Date(on.stop * 1000)) + text.text = getString(R.string.m_resume, channelLabel ?: "") + " · " + getString(R.string.m_now_on, on.title, span) + bar.progress = ((t - on.start) * 1000 / (on.stop - on.start).coerceAtLeast(1)).toInt().coerceIn(0, 1000) + bar.visibility = View.VISIBLE + } + } + } + + // ------------------------------------------------------------ server state, tiles + + private fun showServer() { + val c = ServerConfig.load(this) + val all = ServerConfig.all(this) + val p = getSharedPreferences("sync", Context.MODE_PRIVATE) + val last = p.getLong("last", 0) + val err = p.getString("error", null) + findViewById(R.id.server).text = if (c.configured) { + listOf(c.label, c.host, "HTSP ${c.htspPort}").distinct().joinToString(" · ") + + if (all.size > 1) " (+${all.size - 1})" else "" + } else { + getString(R.string.not_configured) + } + val status = StringBuilder( + if (last == 0L) getString(R.string.status_never) + else getString( + R.string.status_compact, + p.getInt("channels", 0), p.getInt("events", 0), p.getInt("recordings", 0), + DateUtils.getRelativeTimeSpanString(last), + ), + ) + if (err != null) status.append(" · ").append(getString(R.string.status_error, err)) + findViewById(R.id.status).text = status + val color = when { + !c.configured -> R.color.muted + err != null -> R.color.red + last == 0L -> R.color.muted + else -> R.color.green + } + findViewById(R.id.m_dot).backgroundTintList = ColorStateList.valueOf(getColor(color)) + + findViewById(R.id.guide_sub).text = getString(R.string.sub_guide) + findViewById(R.id.recordings_sub).text = getString(R.string.sub_recordings, p.getInt("recordings", 0)) + findViewById(R.id.watch_sub).text = getString(R.string.sub_tv_app) + findViewById(R.id.servers_sub).text = + if (all.isEmpty()) getString(R.string.sub_no_server) else c.label + if (all.size > 1) " +${all.size - 1}" else "" + findViewById(R.id.settings_sub).text = getString(R.string.sub_settings) + } + + /** Opens the TV's own live-TV app on the first simply-tv channel. */ + private fun openTvApp() { + val rows = EpgSync.channelRows(this).values.sorted() + val uri = rows.firstOrNull()?.let { TvContract.buildChannelUri(it) } ?: TvContract.Channels.CONTENT_URI + try { + startActivity(Intent(Intent.ACTION_VIEW, uri)) + } catch (e: Exception) { + Toast.makeText(this, R.string.open_tv_failed, Toast.LENGTH_LONG).show() + } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/ui/PlayerActivity.kt b/app/src/main/java/io/simplydvb/tv/ui/PlayerActivity.kt new file mode 100644 index 0000000..7f4daf5 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/ui/PlayerActivity.kt @@ -0,0 +1,76 @@ +package io.simplydvb.tv.ui + +import android.app.Activity +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.view.WindowManager +import android.widget.Toast +import androidx.annotation.OptIn +import androidx.media3.common.MediaItem +import androidx.media3.common.MimeTypes +import androidx.media3.common.PlaybackException +import androidx.media3.common.Player +import androidx.media3.common.util.UnstableApi +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.ui.PlayerView +import io.simplydvb.tv.R +import io.simplydvb.tv.Server +import io.simplydvb.tv.player.Players +import kotlin.concurrent.thread + +/** Plays a recording from the server (seeking with the remote's arrows). */ +class PlayerActivity : Activity() { + private val main = Handler(Looper.getMainLooper()) + private var player: ExoPlayer? = null + + @OptIn(UnstableApi::class) + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_player) + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + val dvrId = intent.getLongExtra(DVR_ID, -1) + val p = Players.create(this, live = false, tunneling = Players.tunneling(this)) + player = p + val view = findViewById(R.id.player) + view.player = p + view.setShowFastForwardButton(true) + view.setShowRewindButton(true) + view.requestFocus() + p.addListener(object : Player.Listener { + override fun onPlayerError(error: PlaybackException) { + Toast.makeText(this@PlayerActivity, getString(R.string.error, error.errorCodeName), Toast.LENGTH_LONG).show() + } + }) + thread(name = "ticket") { + try { + val url = Server.session(this) { Server.ticketUrl(this, it, dvrId = dvrId) } + main.post { + p.setMediaItem(MediaItem.Builder().setUri(url).setMimeType(MimeTypes.VIDEO_MP2T).build()) + p.prepare() + p.playWhenReady = true + } + } catch (e: Exception) { + main.post { + Toast.makeText(this, getString(R.string.error, e.message), Toast.LENGTH_LONG).show() + finish() + } + } + } + } + + override fun onStop() { + super.onStop() + player?.playWhenReady = false + } + + override fun onDestroy() { + super.onDestroy() + player?.release() + player = null + } + + companion object { + const val DVR_ID = "dvr_id" + } +} diff --git a/app/src/main/java/io/simplydvb/tv/ui/RecordingsActivity.kt b/app/src/main/java/io/simplydvb/tv/ui/RecordingsActivity.kt new file mode 100644 index 0000000..3265ced --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/ui/RecordingsActivity.kt @@ -0,0 +1,128 @@ +package io.simplydvb.tv.ui + +import android.app.Activity +import android.app.AlertDialog +import android.content.Intent +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.text.format.Formatter +import android.view.View +import android.widget.ListView +import android.widget.TextView +import android.widget.Toast +import io.simplydvb.tv.R +import io.simplydvb.tv.Server +import io.simplydvb.tv.htsp.HtsMsg +import io.simplydvb.tv.tif.EpgSync +import io.simplydvb.tv.tif.HDvr +import io.simplydvb.tv.tif.SyncWorker +import java.text.DateFormat +import java.util.Date +import kotlin.concurrent.thread + +/** Recordings on the server: play, cancel scheduled ones, delete finished ones. */ +class RecordingsActivity : Activity() { + private val main = Handler(Looper.getMainLooper()) + private lateinit var adapter: RowAdapter + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_recordings) + findViewById(R.id.title).setText(R.string.recordings) + findViewById(R.id.left).visibility = View.GONE + val list = findViewById(R.id.right) + adapter = RowAdapter(this) + list.adapter = adapter + list.setOnItemClickListener { _, _, pos, _ -> (adapter.getItem(pos).tag as? HDvr)?.let { ask(it) } } + list.requestFocus() + } + + override fun onResume() { + super.onResume() + load() + } + + private fun stateText(s: String) = when (s) { + "scheduled" -> getString(R.string.state_scheduled) + "recording" -> getString(R.string.state_recording) + "completed" -> getString(R.string.state_completed) + else -> getString(R.string.state_failed) + } + + private fun load() { + findViewById(R.id.hint).text = getString(R.string.loading) + thread(name = "recordings") { + try { + val dvr = EpgSync.fetch(this, withEpg = false).dvr + .sortedWith(compareBy { if (it.state == "completed") 1 else 0 }.thenByDescending { it.start }) + val fmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT) + main.post { + findViewById(R.id.hint).text = "" + adapter.rows = if (dvr.isEmpty()) listOf(Row(getString(R.string.no_recordings))) else dvr.map { r -> + Row( + r.title, + listOf(r.channelName, fmt.format(Date(r.start * 1000)), stateText(r.state), + if (r.size > 0) Formatter.formatShortFileSize(this, r.size) else "") + .filter { it.isNotEmpty() }.joinToString(" · "), + icon = when (r.state) { + "completed" -> R.drawable.ic_play + "recording", "scheduled" -> R.drawable.ic_record + else -> 0 + }, + tag = r, + ) + } + } + } catch (e: Exception) { + main.post { findViewById(R.id.hint).text = getString(R.string.error, e.message ?: e.toString()) } + } + } + } + + private fun ask(r: HDvr) { + val b = AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert) + .setTitle(r.title) + .setMessage(r.description.take(600)) + .setNegativeButton(R.string.close, null) + when (r.state) { + "completed" -> { + b.setPositiveButton(R.string.play) { _, _ -> + startActivity(Intent(this, PlayerActivity::class.java).putExtra(PlayerActivity.DVR_ID, r.id)) + } + b.setNeutralButton(R.string.delete) { _, _ -> confirmDelete(r) } + } + "recording" -> { + b.setPositiveButton(R.string.play) { _, _ -> + startActivity(Intent(this, PlayerActivity::class.java).putExtra(PlayerActivity.DVR_ID, r.id)) + } + b.setNeutralButton(R.string.stop) { _, _ -> action("stopDvrEntry", r) } + } + "scheduled" -> b.setPositiveButton(R.string.cancel_recording) { _, _ -> action("cancelDvrEntry", r) } + else -> b.setNeutralButton(R.string.delete) { _, _ -> action("deleteDvrEntry", r) } + } + b.show() + } + + private fun confirmDelete(r: HDvr) { + AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert) + .setMessage(getString(R.string.delete_confirm, r.title)) + .setPositiveButton(R.string.delete) { _, _ -> action("deleteDvrEntry", r) } + .setNegativeButton(R.string.close, null) + .show() + } + + private fun action(method: String, r: HDvr) { + thread(name = "dvr") { + try { + Server.session(this) { it.request(HtsMsg.method(method).put("id", r.id)) } + main.post { + load() + SyncWorker.now(this) + } + } catch (e: Exception) { + main.post { Toast.makeText(this, getString(R.string.error, e.message), Toast.LENGTH_LONG).show() } + } + } + } +} diff --git a/app/src/main/java/io/simplydvb/tv/ui/Rows.kt b/app/src/main/java/io/simplydvb/tv/ui/Rows.kt new file mode 100644 index 0000000..27f89be --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/ui/Rows.kt @@ -0,0 +1,51 @@ +package io.simplydvb.tv.ui + +import android.content.Context +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.BaseAdapter +import android.widget.ImageView +import android.widget.TextView +import io.simplydvb.tv.R + +/** One list row: icon (optional), two lines of text and a badge on the right. */ +data class Row( + val line1: String, + val line2: String = "", + val badge: String = "", + val icon: Int = 0, + val tag: Any? = null, +) + +class RowAdapter(private val ctx: Context) : BaseAdapter() { + var rows: List = emptyList() + set(v) { + field = v + notifyDataSetChanged() + } + + override fun getCount() = rows.size + override fun getItem(position: Int) = rows[position] + override fun getItemId(position: Int) = position.toLong() + + override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { + val v = convertView ?: LayoutInflater.from(ctx).inflate(R.layout.row, parent, false) + val r = rows[position] + v.findViewById(R.id.line1).text = r.line1 + v.findViewById(R.id.line2).apply { + text = r.line2 + visibility = if (r.line2.isEmpty()) View.GONE else View.VISIBLE + } + v.findViewById(R.id.badge).text = r.badge + v.findViewById(R.id.icon).apply { + if (r.icon != 0) { + setImageResource(r.icon) + visibility = View.VISIBLE + } else { + visibility = View.GONE + } + } + return v + } +} diff --git a/app/src/main/java/io/simplydvb/tv/ui/ServersActivity.kt b/app/src/main/java/io/simplydvb/tv/ui/ServersActivity.kt new file mode 100644 index 0000000..5028b41 --- /dev/null +++ b/app/src/main/java/io/simplydvb/tv/ui/ServersActivity.kt @@ -0,0 +1,121 @@ +package io.simplydvb.tv.ui + +import android.app.Activity +import android.app.AlertDialog +import android.content.Intent +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.widget.Button +import android.widget.ListView +import android.widget.TextView +import io.simplydvb.tv.R +import io.simplydvb.tv.ServerConfig +import io.simplydvb.tv.tif.EpgSync +import io.simplydvb.tv.tif.SyncWorker +import kotlin.concurrent.thread + +/** + * Server list: add/edit/remove servers, pick the active one (player, guide, recordings) and + * choose which ones feed the TV's own TV app. Also the setup screen the TV app opens. + */ +class ServersActivity : Activity() { + private val main = Handler(Looper.getMainLooper()) + private lateinit var adapter: RowAdapter + private var openedNew = false + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_servers) + val list = findViewById(R.id.list) + adapter = RowAdapter(this) + list.adapter = adapter + list.setOnItemClickListener { _, _, pos, _ -> (adapter.getItem(pos).tag as? ServerConfig)?.let { ask(it) } } + findViewById