This commit is contained in:
Mateusz Gruszczyński committed 2026-11-17 16:47:14 +01:00
commit 4cb9717db2
97 files changed
+5946

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.providers.tv.permission.READ_EPG_DATA" />
<uses-permission android:name="com.android.providers.tv.permission.WRITE_EPG_DATA" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- optional autostart of the player (opening a screen from the background) -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-feature android:name="android.software.leanback" android:required="false" />
<uses-feature android:name="android.software.live_tv" android:required="false" />
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<application
android:allowBackup="true"
android:banner="@drawable/banner"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
<activity
android:name=".ui.MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- also opened by the TV app when the source is added ("Set up channels") -->
<activity
android:name=".ui.SetupActivity"
android:exported="true"
android:windowSoftInputMode="adjustPan" />
<activity android:name=".ui.ServersActivity" android:exported="true" />
<activity android:name=".ui.GuideActivity" android:exported="false" />
<activity android:name=".ui.SettingsActivity" android:exported="false" />
<activity
android:name=".ui.LiveActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
android:exported="false"
android:theme="@android:style/Theme.Material.NoActionBar.Fullscreen" />
<!-- second home-screen tile: straight into the own player -->
<activity-alias
android:name=".LiveTv"
android:banner="@drawable/banner_live"
android:exported="true"
android:label="@string/live_tv_label"
android:targetActivity=".ui.LiveActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
</activity-alias>
<activity android:name=".ui.RecordingsActivity" android:exported="false" />
<activity
android:name=".ui.PlayerActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
android:exported="false" />
<receiver android:name=".BootReceiver" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
<service
android:name=".WakeService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Opens the live TV player when the TV wakes up from standby (user setting)" />
</service>
<service
android:name=".tif.SimplyTvInputService"
android:exported="true"
android:permission="android.permission.BIND_TV_INPUT">
<intent-filter>
<action android:name="android.media.tv.TvInputService" />
</intent-filter>
<meta-data
android:name="android.media.tv.input"
android:resource="@xml/tvinputservice" />
</service>
</application>
</manifest>
@@ -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
}
+33
View File
@@ -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)) }
}
}
@@ -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)
}
+223
View File
@@ -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<ServerConfig> {
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<ServerConfig>) {
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 <T> 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
}
}
@@ -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<String, Any> = 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<Any> = (fields[name] as? List<Any>) ?: emptyList()
fun maps(name: String): List<HtsMsg> = list(name).filterIsInstance<HtsMsg>()
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<Byte>(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<Pair<String?, Any>>): 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<Any> {
val l = ArrayList<Any>()
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
}
}
}
}
@@ -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<Int, LinkedBlockingQueue<HtsMsg>>()
@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<HtsMsg>(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"
}
}
@@ -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()
}
}
@@ -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<HChannel>, val events: List<HEvent>, val dvr: List<HDvr>)
/**
* 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<HChannel>()
val events = ArrayList<HEvent>()
val dvr = ArrayList<HDvr>()
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: "<server id>:<id>". */
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<io.simplydvb.tv.ServerConfig, Long>? {
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<String>()
var channels = 0
var events = 0
var recordings = 0
val fresh = HashMap<String, Snapshot>()
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<String, Long> {
val out = HashMap<String, Long>()
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<HChannel>): Map<Long, Long> {
val cr = ctx.contentResolver
val input = inputId(ctx)
val existing = channelRows(ctx).filterKeys { it.startsWith(srv.id + ":") }
val keep = HashSet<String>()
val result = HashMap<Long, Long>()
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<Long, Long>, events: List<HEvent>) {
val cr = ctx.contentResolver
val now = System.currentTimeMillis()
val ops = ArrayList<ContentProviderOperation>()
// 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<String>) {
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<Long, Long>, dvr: List<HDvr>) {
val cr = ctx.contentResolver
val input = inputId(ctx)
val existing = HashMap<Long, Long>()
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<ContentProviderOperation>) {
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()
}
}
@@ -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<ServerConfig, Long> {
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<TvTrackInfo>()
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"
}
}
}
@@ -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<SyncWorker>(1, TimeUnit.HOURS)
.setConstraints(network)
.build()
WorkManager.getInstance(ctx).enqueueUniquePeriodicWork(PERIODIC, ExistingPeriodicWorkPolicy.KEEP, req)
}
fun now(ctx: Context) {
val req = OneTimeWorkRequestBuilder<SyncWorker>().setConstraints(network).build()
WorkManager.getInstance(ctx).enqueueUniqueWork(ONCE, ExistingWorkPolicy.REPLACE, req)
}
}
}
@@ -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<HChannel> = emptyList()
private var events: Map<Long, List<HEvent>> = 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<HChannel>, events: Map<Long, List<HEvent>>, 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()
}
}
}
@@ -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<HChannel> = emptyList()
private var events: Map<Long, List<HEvent>> = emptyMap()
private var dvr: MutableList<HDvr> = 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<TextView>(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<TextView>(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<TextView>(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() }
}
}
}
}
@@ -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<HChannel> = emptyList()
private var events: Map<Long, List<HEvent>> = emptyMap()
private val dvr = ArrayList<HDvr>()
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<SparkView>(R.id.t_cpu_spark).apply {
setup(Triple("#f69b74", 100f, true), Triple("#e8ece9", 100f, false))
}
rateSpark = findViewById<SparkView>(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<PlayerView>(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<TextView>(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<View>(R.id.digits).visibility = View.GONE
if (i >= 0) tune(i)
}
private fun nowNext(ch: HChannel): Pair<HEvent?, HEvent?> {
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<View>(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<HEvent?, HEvent?, List<HEvent>> {
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<TextView>(R.id.o_number).text = ch.number.toString()
findViewById<TextView>(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<View>(R.id.o_now_box).visibility = View.VISIBLE
if (now != null) {
findViewById<TextView>(R.id.o_now_time).text = span(now)
findViewById<TextView>(R.id.o_now_title).text = now.title
val desc = if (Prefs.osdDescription(this)) now.description.ifEmpty { now.summary }.replace('\n', ' ') else ""
findViewById<TextView>(R.id.o_now_desc).apply {
text = desc
visibility = if (desc.isEmpty()) View.GONE else View.VISIBLE
}
findViewById<View>(R.id.o_progress).visibility = View.VISIBLE
} else {
findViewById<TextView>(R.id.o_now_time).text = ""
findViewById<TextView>(R.id.o_now_title).text = getString(R.string.no_programmes)
findViewById<View>(R.id.o_now_desc).visibility = View.GONE
findViewById<View>(R.id.o_progress).visibility = View.GONE
findViewById<TextView>(R.id.o_now_left).text = ""
}
fun column(box: Int, label: Int, value: Int, title: String, e: HEvent?) {
findViewById<View>(box).visibility = if (e == null) View.INVISIBLE else View.VISIBLE
findViewById<TextView>(label).text = title
findViewById<TextView>(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<View>(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<TextView>(R.id.o_clock).text = fmtTime.format(Date(nowMs))
findViewById<TextView>(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<android.widget.ProgressBar>(R.id.o_progress).progress = ((t - now.start) * 1000 / total).toInt().coerceIn(0, 1000)
val left = ((now.stop - t + 59) / 60).coerceAtLeast(0)
findViewById<TextView>(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<LinearLayout>(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<TextView>(R.id.t_name).text = getString(R.string.loading)
findViewById<TextView>(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<String>()
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<TextView>(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<TextView>(R.id.t_rate).text = rate?.let { mbit(it) } ?: "–"
findViewById<TextView>(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<View>(R.id.t_lock).backgroundTintList =
ColorStateList.valueOf(getColor(if (locked) R.color.green else R.color.red))
findViewById<TextView>(R.id.t_name).text = t.optString("input")
findViewById<TextView>(R.id.t_stream).text = t.optString("stream")
findViewById<TextView>(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<TextView>(R.id.t_cpu).text = cpu?.let { "%.0f%%".format(Locale.ROOT, it) } ?: "–"
findViewById<TextView>(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<String>()
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<TextView>(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<TextView>(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<TextView>(R.id.number).text = ch.number.toString()
v.findViewById<TextView>(R.id.name).text =
if (activeRecording(ch.id) != null) "${ch.name} · REC" else ch.name
v.findViewById<TextView>(R.id.now).text = nowNext(ch).first?.title ?: ""
Logos.load(this@LiveActivity, ch.icon, v.findViewById<ImageView>(R.id.logo))
return v
}
}
}
@@ -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<String, Bitmap>(200)
private val missing = HashSet<String>()
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) }
}
}
}
@@ -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<View>(R.id.live).setOnClickListener { startActivity(Intent(this, LiveActivity::class.java)) }
findViewById<View>(R.id.guide).setOnClickListener { startActivity(Intent(this, GuideActivity::class.java)) }
findViewById<View>(R.id.recordings).setOnClickListener { startActivity(Intent(this, RecordingsActivity::class.java)) }
findViewById<View>(R.id.watch).setOnClickListener { openTvApp() }
findViewById<View>(R.id.servers).setOnClickListener { startActivity(Intent(this, ServersActivity::class.java)) }
findViewById<View>(R.id.settings).setOnClickListener { startActivity(Intent(this, SettingsActivity::class.java)) }
findViewById<View>(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<View>(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<TextView>(R.id.m_clock).text = time.format(now)
findViewById<TextView>(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<Long, Int, String>? {
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<TextView>(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<TextView>(R.id.m_now)
val bar = findViewById<ProgressBar>(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<TextView>(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<TextView>(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<View>(R.id.m_dot).backgroundTintList = ColorStateList.valueOf(getColor(color))
findViewById<TextView>(R.id.guide_sub).text = getString(R.string.sub_guide)
findViewById<TextView>(R.id.recordings_sub).text = getString(R.string.sub_recordings, p.getInt("recordings", 0))
findViewById<TextView>(R.id.watch_sub).text = getString(R.string.sub_tv_app)
findViewById<TextView>(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<TextView>(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()
}
}
}
@@ -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<PlayerView>(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"
}
}
@@ -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<TextView>(R.id.title).setText(R.string.recordings)
findViewById<ListView>(R.id.left).visibility = View.GONE
val list = findViewById<ListView>(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<TextView>(R.id.hint).text = getString(R.string.loading)
thread(name = "recordings") {
try {
val dvr = EpgSync.fetch(this, withEpg = false).dvr
.sortedWith(compareBy<HDvr> { if (it.state == "completed") 1 else 0 }.thenByDescending { it.start })
val fmt = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
main.post {
findViewById<TextView>(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<TextView>(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() }
}
}
}
}
@@ -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<Row> = 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<TextView>(R.id.line1).text = r.line1
v.findViewById<TextView>(R.id.line2).apply {
text = r.line2
visibility = if (r.line2.isEmpty()) View.GONE else View.VISIBLE
}
v.findViewById<TextView>(R.id.badge).text = r.badge
v.findViewById<ImageView>(R.id.icon).apply {
if (r.icon != 0) {
setImageResource(r.icon)
visibility = View.VISIBLE
} else {
visibility = View.GONE
}
}
return v
}
}
@@ -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<ListView>(R.id.list)
adapter = RowAdapter(this)
list.adapter = adapter
list.setOnItemClickListener { _, _, pos, _ -> (adapter.getItem(pos).tag as? ServerConfig)?.let { ask(it) } }
findViewById<Button>(R.id.add).setOnClickListener { startActivity(Intent(this, SetupActivity::class.java)) }
findViewById<Button>(R.id.load).setOnClickListener { loadIntoTv() }
}
override fun onResume() {
super.onResume()
val servers = ServerConfig.all(this)
if (servers.isEmpty() && !openedNew) {
openedNew = true
startActivity(Intent(this, SetupActivity::class.java))
return
}
val active = ServerConfig.activeId(this)
adapter.rows = servers.map { s ->
Row(
s.label + if (s.id == active) " · " + getString(R.string.active) else "",
"${s.host} · HTSP ${s.htspPort} / HTTP ${s.httpPort} · " +
getString(if (s.tvInput) R.string.tv_source_on else R.string.tv_source_off),
icon = if (s.id == active) R.drawable.ic_play else if (s.tvInput) R.drawable.ic_tv else 0,
tag = s,
)
}
if (servers.isNotEmpty()) findViewById<ListView>(R.id.list).requestFocus()
}
private fun ask(s: ServerConfig) {
val items = arrayOf(
getString(R.string.use_in_player),
getString(if (s.tvInput) R.string.tv_source_off else R.string.tv_source_on),
getString(R.string.edit),
getString(R.string.delete),
)
AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert)
.setTitle(s.label)
.setItems(items) { _, which ->
when (which) {
0 -> {
ServerConfig.setActive(this, s.id)
onResume()
}
1 -> {
ServerConfig.save(this, s.copy(tvInput = !s.tvInput))
onResume()
SyncWorker.now(this)
}
2 -> startActivity(Intent(this, SetupActivity::class.java).putExtra(SetupActivity.EXTRA_SERVER, s.id))
3 -> AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert)
.setMessage(getString(R.string.delete_server_confirm, s.label))
.setPositiveButton(R.string.delete) { _, _ ->
ServerConfig.delete(this, s.id)
onResume()
SyncWorker.now(this)
}
.setNegativeButton(R.string.close, null)
.show()
}
}
.show()
}
private fun loadIntoTv() {
val result = findViewById<TextView>(R.id.result)
val btn = findViewById<Button>(R.id.load)
btn.isEnabled = false
result.setTextColor(getColor(R.color.muted))
result.text = getString(R.string.loading)
thread(name = "load") {
try {
val n = EpgSync.run(this)
SyncWorker.schedule(this)
main.post {
result.setTextColor(getColor(R.color.green))
result.text = getString(R.string.sync_done, n)
btn.isEnabled = true
setResult(RESULT_OK)
// opened by the TV app ("set up channels"): back to it
if (callingActivity != null) main.postDelayed({ finish() }, 1500)
}
} catch (e: Exception) {
main.post {
result.setTextColor(getColor(R.color.red))
result.text = getString(R.string.error, e.message ?: e.toString())
btn.isEnabled = true
}
}
}
}
}
@@ -0,0 +1,171 @@
package io.simplydvb.tv.ui
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import io.simplydvb.tv.AutoStart
import io.simplydvb.tv.Prefs
import io.simplydvb.tv.R
import io.simplydvb.tv.ServerConfig
/**
* Settings: OSD, player, start-up and servers. Rows on the right; the left column explains
* the highlighted row, so the list stays short enough for a TV screen.
*/
class SettingsActivity : Activity() {
/** Refreshes the value shown on each row (after changes, on return from other screens). */
private val refreshers = ArrayList<() -> Unit>()
private lateinit var rows: LinearLayout
private lateinit var hint: TextView
private var first: View? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
rows = findViewById(R.id.rows)
hint = findViewById(R.id.hint)
section(R.string.set_sec_osd)
toggle(R.drawable.ic_info, R.string.set_osd_zap, R.string.set_osd_zap_desc, "osd_on_zap", true)
choice(
R.drawable.ic_guide, R.string.set_osd_seconds, R.string.set_osd_seconds_desc,
value = { getString(R.string.set_seconds, Prefs.osdSeconds(this)) },
) {
val opts = Prefs.OSD_SECONDS
val cur = opts.indexOf(Prefs.osdSeconds(this))
Prefs.set(this, "osd_seconds", opts[(cur + 1) % opts.size])
}
toggle(R.drawable.ic_antenna, R.string.set_osd_tech, R.string.set_osd_tech_desc, "osd_tech", true)
toggle(R.drawable.ic_recordings, R.string.set_osd_desc, R.string.set_osd_desc_desc, "osd_desc", true)
section(R.string.set_sec_player)
toggle(R.drawable.ic_antenna, R.string.set_tuner_card, R.string.set_tuner_card_desc, "tuner_info", false)
toggle(R.drawable.ic_tv, R.string.tunneling, R.string.set_tunneling_desc, "tunneling", true)
section(R.string.set_sec_start)
row(
R.drawable.ic_play, getString(R.string.autostart), getString(R.string.set_autostart_desc),
value = {
val on = AutoStart.enabled(this)
(if (!on) getString(R.string.off) else if (AutoStart.allowed(this)) getString(R.string.on) else getString(R.string.autostart_needs_permission)) to on
},
) { toggleAutostart() }
section(R.string.set_sec_servers)
row(
R.drawable.ic_server, getString(R.string.set_servers), getString(R.string.set_servers_desc),
value = {
val all = ServerConfig.all(this)
val active = ServerConfig.load(this)
(if (all.isEmpty()) "–" else active.label + if (all.size > 1) " +${all.size - 1}" else "") to null
},
) { startActivity(Intent(this, ServersActivity::class.java)) }
section(R.string.set_sec_about)
val version = try {
packageManager.getPackageInfo(packageName, 0).versionName ?: ""
} catch (_: Exception) {
""
}
row(R.drawable.ic_info, getString(R.string.set_version), "simply-tv $version", value = { version to null }, click = null)
first?.requestFocus()
}
override fun onResume() {
super.onResume()
refreshers.forEach { it() }
}
private fun section(title: Int) {
val d = resources.displayMetrics.density
val tv = TextView(this, null, 0, R.style.OsdLabel).apply {
setText(title)
setPadding((4 * d).toInt(), ((if (rows.childCount == 0) 0 else 22) * d).toInt(), 0, (4 * d).toInt())
}
rows.addView(tv)
}
private fun toggle(icon: Int, title: Int, desc: Int, key: String, def: Boolean) =
row(icon, getString(title), getString(desc), value = {
val on = Prefs.bool(this, key, def)
getString(if (on) R.string.on else R.string.off) to on
}) { Prefs.set(this, key, !Prefs.bool(this, key, def)) }
private fun choice(icon: Int, title: Int, desc: Int, value: () -> String, click: () -> Unit) =
row(icon, getString(title), getString(desc), value = { value() to null }, click = click)
/**
* Adds a row. `value` returns the text on the right and whether it is a switch
* (true / false: green / grey pill, null: plain value).
*/
private fun row(icon: Int, title: String, desc: String, value: () -> Pair<String, Boolean?>, click: (() -> Unit)?) {
val v = LayoutInflater.from(this).inflate(R.layout.setting_row, rows, false)
v.findViewById<ImageView>(R.id.s_icon).setImageResource(icon)
v.findViewById<TextView>(R.id.s_title).text = title
// the description is shown in the left column for the highlighted row
v.findViewById<TextView>(R.id.s_desc).visibility = View.GONE
val valueView = v.findViewById<TextView>(R.id.s_value)
val refresh = {
val (text, on) = value()
valueView.text = text
when (on) {
true -> {
valueView.setBackgroundResource(R.drawable.pill_on)
valueView.setTextColor(getColor(R.color.green))
}
false -> {
valueView.setBackgroundResource(R.drawable.pill_off)
valueView.setTextColor(getColor(R.color.muted))
}
null -> {
valueView.background = null
valueView.setTextColor(getColor(R.color.muted))
}
}
}
refresh()
refreshers.add(refresh)
v.setOnFocusChangeListener { _, has ->
if (has) {
hint.text = desc
// keep the section header of the first row visible when scrolling up
if (rows.indexOfChild(v) <= 1) findViewById<View>(R.id.scroll).scrollTo(0, 0)
}
}
if (click != null) {
v.setOnClickListener {
click()
refresh()
}
} else {
v.isClickable = false
}
rows.addView(v)
if (first == null) first = v
}
private fun toggleAutostart() {
val on = !AutoStart.enabled(this)
AutoStart.setEnabled(this, on)
if (on && !AutoStart.allowed(this)) {
AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert)
.setTitle(R.string.autostart)
.setMessage(getString(R.string.autostart_permission, packageName))
.setPositiveButton(R.string.open_settings) { _, _ ->
if (!AutoStart.requestPermission(this)) {
Toast.makeText(this, getString(R.string.autostart_no_settings), Toast.LENGTH_LONG).show()
}
}
.setNegativeButton(R.string.close, null)
.show()
}
}
}
@@ -0,0 +1,245 @@
package io.simplydvb.tv.ui
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.graphics.Bitmap
import android.os.Build
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.QRCodeWriter
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import io.simplydvb.tv.R
import io.simplydvb.tv.ServerConfig
import io.simplydvb.tv.htsp.HtspClient
import io.simplydvb.tv.tif.EpgSync
import io.simplydvb.tv.tif.SyncWorker
import kotlin.concurrent.thread
/**
* Server settings. Also the "setup" screen the TV app opens when the simply-tv source is
* added: it connects, loads channels and the guide and returns RESULT_OK.
*/
class SetupActivity : Activity() {
private val main = Handler(Looper.getMainLooper())
@Volatile private var pairing = 0
/** Server being edited ("" = a new one, gets its id on the first save). */
private var editId = ""
private var tvInput = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_setup)
editId = intent.getStringExtra(EXTRA_SERVER) ?: ""
val c = (if (editId.isNotEmpty()) ServerConfig.byId(this, editId) else null) ?: ServerConfig.empty()
tvInput = c.tvInput
val nameField = findViewById<EditText>(R.id.name)
nameField.setText(c.name)
val host = findViewById<EditText>(R.id.host)
val htsp = findViewById<EditText>(R.id.htsp_port)
val http = findViewById<EditText>(R.id.http_port)
val user = findViewById<EditText>(R.id.username)
val pass = findViewById<EditText>(R.id.password)
val result = findViewById<TextView>(R.id.result)
val connect = findViewById<Button>(R.id.connect)
host.setText(c.host)
htsp.setText(c.htspPort.toString())
http.setText(c.httpPort.toString())
user.setText(c.username)
pass.setText(c.password)
if (c.configured) connect.requestFocus() else host.requestFocus()
fun form() = ServerConfig(
host = host.text.toString().trim(),
htspPort = htsp.text.toString().toIntOrNull() ?: 9982,
httpPort = http.text.toString().toIntOrNull() ?: 9981,
username = user.text.toString().trim(),
password = pass.text.toString(),
id = editId,
name = nameField.text.toString().trim(),
tvInput = tvInput,
)
findViewById<Button>(R.id.pair).setOnClickListener {
val cfg = form()
if (cfg.host.isEmpty()) {
result.setTextColor(getColor(R.color.red))
result.text = getString(R.string.pair_need_host)
host.requestFocus()
return@setOnClickListener
}
startPairing(cfg)
}
connect.setOnClickListener {
pairing++
findViewById<View>(R.id.pair_panel).visibility = View.GONE
val cfg = form()
if (cfg.host.isEmpty()) {
host.requestFocus()
return@setOnClickListener
}
connect.isEnabled = false
result.setTextColor(getColor(R.color.muted))
result.text = getString(R.string.connecting)
thread(name = "setup") {
try {
val name = HtspClient(cfg.host, cfg.htspPort, cfg.username, cfg.password).use { cl ->
cl.connect()
listOf(cl.serverName, cl.serverVersion).filter { it.isNotEmpty() }.joinToString(" ")
}
editId = ServerConfig.save(this, cfg.copy(name = cfg.name.ifEmpty { cfg.host })).id
main.post { result.text = getString(R.string.syncing, name.ifEmpty { cfg.host }) }
syncAndFinish(connect)
} catch (e: Exception) {
main.post {
result.setTextColor(getColor(R.color.red))
result.text = getString(R.string.error, e.message ?: e.toString())
connect.isEnabled = true
}
}
}
}
}
/** Loads channels/guide into the TV and returns to the TV app when it opened this screen. */
private fun syncAndFinish(connect: Button) {
val result = findViewById<TextView>(R.id.result)
val n = EpgSync.run(this)
SyncWorker.schedule(this)
main.post {
result.setTextColor(getColor(R.color.green))
result.text = getString(R.string.sync_done, n)
connect.isEnabled = true
setResult(RESULT_OK)
// opened by the TV app: go back to it after a moment
if (callingActivity != null) main.postDelayed({ finish() }, 1500)
}
}
// ---------------------------------------------------------------- QR pairing
private fun http(method: String, url: String, body: String? = null): Pair<Int, String> {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 6000
c.readTimeout = 10000
c.requestMethod = method
if (body != null) {
c.doOutput = true
c.setRequestProperty("Content-Type", "application/json")
c.outputStream.use { it.write(body.toByteArray()) }
}
try {
val code = c.responseCode
val text = (if (code < 400) c.inputStream else c.errorStream)?.use { it.readBytes().toString(Charsets.UTF_8) } ?: ""
return code to text
} finally {
c.disconnect()
}
}
private fun qr(text: String, size: Int): Bitmap {
val m = QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, size, size, mapOf(EncodeHintType.MARGIN to 1))
val bmp = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565)
for (y in 0 until size) for (x in 0 until size) bmp.setPixel(x, y, if (m[x, y]) 0xff000000.toInt() else 0xffffffff.toInt())
return bmp
}
/**
* The server creates a pairing request; the QR code opens the panel on a phone where an
* administrator confirms it; meanwhile the TV polls and receives its access token.
*/
private fun startPairing(form: ServerConfig) {
val my = ++pairing
val result = findViewById<TextView>(R.id.result)
val panel = findViewById<LinearLayout>(R.id.pair_panel)
val connect = findViewById<Button>(R.id.connect)
result.setTextColor(getColor(R.color.muted))
result.text = getString(R.string.connecting)
thread(name = "pair") {
try {
val base = form.httpBase
val device = listOf(Build.MANUFACTURER, Build.MODEL).distinct().joinToString(" ")
val (code, text) = http("POST", "$base/api/pair/start", JSONObject().put("device", device).toString())
if (code != 200) throw IllegalStateException(errorOf(text, code))
val j = JSONObject(text)
val secret = j.getString("secret")
val url = j.getString("url")
val pairCode = j.getString("code")
val until = System.currentTimeMillis() + j.optLong("expires_in", 600) * 1000
val bmp = qr(url, 480)
main.post {
if (my != pairing) return@post
findViewById<ImageView>(R.id.pair_qr).setImageBitmap(bmp)
findViewById<TextView>(R.id.pair_code).text = pairCode.chunked(3).joinToString(" ")
findViewById<TextView>(R.id.pair_url).text = url
panel.visibility = View.VISIBLE
result.text = getString(R.string.pair_waiting)
}
while (my == pairing && System.currentTimeMillis() < until) {
Thread.sleep(2000)
val (pc, pt) = http("GET", "$base/api/pair/poll?secret=$secret")
if (pc == 410) break
if (pc != 200) continue
val r = JSONObject(pt)
if (r.optString("status") != "ok") continue
val cfg = form.copy(
host = form.host,
htspPort = if (r.isNull("htsp_port")) form.htspPort else r.optInt("htsp_port", form.htspPort),
httpPort = r.optInt("http_port", form.httpPort),
username = "simply-tv",
password = r.getString("token"),
)
val saved = ServerConfig.save(this, cfg.copy(name = cfg.name.ifEmpty { cfg.host }))
editId = saved.id
main.post {
findViewById<EditText>(R.id.name).setText(saved.name)
panel.visibility = View.GONE
findViewById<EditText>(R.id.htsp_port).setText(cfg.htspPort.toString())
findViewById<EditText>(R.id.http_port).setText(cfg.httpPort.toString())
findViewById<EditText>(R.id.username).setText(cfg.username)
findViewById<EditText>(R.id.password).setText(cfg.password)
result.setTextColor(getColor(R.color.green))
result.text = getString(R.string.pair_done, r.optString("name"))
}
syncAndFinish(connect)
return@thread
}
if (my == pairing) main.post {
panel.visibility = View.GONE
result.setTextColor(getColor(R.color.red))
result.text = getString(R.string.pair_expired)
}
} catch (e: Exception) {
main.post {
if (my != pairing) return@post
panel.visibility = View.GONE
result.setTextColor(getColor(R.color.red))
result.text = getString(R.string.error, e.message ?: e.toString())
}
}
}
}
private fun errorOf(text: String, code: Int): String = try {
JSONObject(text).optString("error").ifEmpty { "HTTP $code" }
} catch (_: Exception) {
"HTTP $code"
}
companion object {
const val EXTRA_SERVER = "server_id"
}
override fun onDestroy() {
super.onDestroy()
pairing++
}
}
@@ -0,0 +1,86 @@
package io.simplydvb.tv.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View
/**
* Tiny line chart for the tuner card. Each series has its own colour and scale
* (`max` > 0: fixed 0..max, `max` = 0: scaled to the largest visible value).
* By default: SNR (0–35 dB) and signal (0–100 %).
*/
class SparkView(ctx: Context, attrs: AttributeSet? = null) : View(ctx, attrs) {
private class Series(val paint: Paint, val max: Float, val fill: Boolean) {
val v = ArrayList<Float>()
}
private val keep = 90
private var series = listOf(
Series(stroke("#7aa7ff", 3f), 35f, false),
Series(stroke("#bdd293", 2f).apply { alpha = 170 }, 100f, false),
)
private val pGrid = Paint().apply { color = Color.parseColor("#22ffffff"); strokeWidth = 1f }
private fun stroke(c: String, w: Float) = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor(c)
strokeWidth = w
style = Paint.Style.STROKE
}
/** Replaces the series: (colour, max, filled area). */
fun setup(vararg s: Triple<String, Float, Boolean>) {
series = s.mapIndexed { i, (c, m, f) -> Series(stroke(c, if (i == 0) 2.5f else 1.8f), m, f) }
invalidate()
}
fun clear() {
series.forEach { it.v.clear() }
invalidate()
}
/** One value per series (null draws 0). */
fun push(vararg values: Float?) {
series.forEachIndexed { i, s ->
s.v.add(values.getOrNull(i) ?: 0f)
while (s.v.size > keep) s.v.removeAt(0)
}
invalidate()
}
/** Compatibility: SNR (dB) and signal (%). */
fun add(snrDb: Float?, signalPct: Float?) = push(snrDb, signalPct)
override fun onDraw(c: Canvas) {
val w = width.toFloat()
val h = height.toFloat()
for (i in 1..3) c.drawLine(0f, h * i / 4, w, h * i / 4, pGrid)
for (s in series.asReversed()) line(c, s, w, h)
}
private fun line(c: Canvas, s: Series, w: Float, h: Float) {
val v = s.v
if (v.size < 2) return
val top = if (s.max > 0) s.max else (v.maxOrNull() ?: 0f).coerceAtLeast(1e-6f) * 1.15f
val step = w / (keep - 1)
val x0 = w - (v.size - 1) * step
val path = Path()
v.forEachIndexed { i, y ->
val px = x0 + i * step
val py = h - 2 - (y / top).coerceIn(0f, 1f) * (h - 4)
if (i == 0) path.moveTo(px, py) else path.lineTo(px, py)
}
if (s.fill) {
val area = Path(path)
area.lineTo(w, h)
area.lineTo(x0, h)
area.close()
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = s.paint.color; alpha = 45; style = Paint.Style.FILL }
c.drawPath(area, p)
}
c.drawPath(path, s.paint)
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape android:shape="rectangle">
<solid android:color="@color/accent" />
<corners android:radius="6dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/panel" />
<stroke android:width="1dp" android:color="@color/line" />
<corners android:radius="6dp" />
</shape>
</item>
</selector>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#b3050605" />
<stroke android:width="1dp" android:color="#33ffffff" />
<corners android:radius="8dp" />
</shape>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#14ffffff" />
<stroke android:width="1dp" android:color="#2effffff" />
<corners android:radius="6dp" />
</shape>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#e25b45" />
<corners android:radius="6dp" />
</shape>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="#ffffff" />
</shape>
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape android:shape="rectangle">
<solid android:color="@color/panel" />
<stroke android:width="2dp" android:color="@color/accent" />
<corners android:radius="4dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/panel" />
<stroke android:width="1dp" android:color="@color/line" />
<corners android:radius="4dp" />
</shape>
</item>
</selector>
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- main "Watch TV" button: accent ring + warm fill when focused -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<layer-list>
<item><shape><solid android:color="#2ef69b74" /><corners android:radius="20dp" /></shape></item>
<item android:top="5dp" android:left="5dp" android:right="5dp" android:bottom="5dp"><shape><solid android:color="#1a1411" /><stroke android:width="2dp" android:color="@color/accent" /><corners android:radius="16dp" /></shape></item>
</layer-list>
</item>
<item>
<layer-list>
<item android:top="5dp" android:left="5dp" android:right="5dp" android:bottom="5dp"><shape><solid android:color="@color/panel" /><stroke android:width="1dp" android:color="@color/line" /><corners android:radius="16dp" /></shape></item>
</layer-list>
</item>
</selector>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item><shape><solid android:color="#1c211e" /></shape></item>
<item android:top="1dp"><shape><solid android:color="#0a0c0b" /></shape></item>
</layer-list>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:pathData="M5,12.5a10,10 0 0,1 14,0M8.5,16a5,5 0 0,1 7,0M2,9a14.5,14.5 0 0,1 20,0" />
<path android:fillColor="#FFFFFFFF" android:pathData="M12,18.5a1,1 0 1,0 0.01,0z" />
</vector>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="12dp" android:height="12dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:pathData="M6,10l6,6 6,-6" android:strokeColor="#e8ece9" android:strokeWidth="2.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:fillColor="#00000000" />
</vector>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="12dp" android:height="12dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:pathData="M14,6l-6,6 6,6" android:strokeColor="#e8ece9" android:strokeWidth="2.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:fillColor="#00000000" />
</vector>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="12dp" android:height="12dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:pathData="M10,6l6,6 -6,6" android:strokeColor="#e8ece9" android:strokeWidth="2.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:fillColor="#00000000" />
</vector>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="12dp" android:height="12dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:pathData="M6,14l6,-6 6,6" android:strokeColor="#e8ece9" android:strokeWidth="2.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:fillColor="#00000000" />
</vector>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M4,7h16M9,7V4h6v3M6,7l1,13h10l1,-13" />
</vector>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M3,4h18v17h-18z" />
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M3,9h18M8,2v4M16,2v4M7,13h4M7,17h8" />
</vector>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M12,3a9,9 0,1 0,0.01 0z" />
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M12,11v6M12,7.5v0.2" />
</vector>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- simply-tv logo: stacked channel cards, the front one playing -->
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="48dp" android:height="48dp" android:viewportWidth="48" android:viewportHeight="48">
<path android:pathData="M18,5h20a5,5 0 0 1 5,5v11a5,5 0 0 1 -5,5h-20a5,5 0 0 1 -5,-5v-11a5,5 0 0 1 5,-5z" android:strokeColor="#4a524d" android:strokeWidth="3" android:fillColor="#00000000" />
<path android:pathData="M14,11h20a5,5 0 0 1 5,5v11a5,5 0 0 1 -5,5h-20a5,5 0 0 1 -5,-5v-11a5,5 0 0 1 5,-5z" android:fillColor="#050605" android:strokeColor="#8d968f" android:strokeWidth="3" />
<path android:pathData="M10,17h20a5,5 0 0 1 5,5v11a5,5 0 0 1 -5,5h-20a5,5 0 0 1 -5,-5v-11a5,5 0 0 1 5,-5z" android:fillColor="#f69b74" />
<path android:pathData="M17,22.6v10.8c0,0.8 0.9,1.3 1.6,0.9l8,-5.4c0.6,-0.4 0.6,-1.3 0,-1.7l-8,-5.4c-0.7,-0.5 -1.6,0 -1.6,0.8z" android:fillColor="#1a120e" />
</vector>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#FFFFFFFF" android:pathData="M7.5,4.8v14.4L19,12z" />
</vector>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="30dp" android:height="30dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:pathData="M8.5,5.6v12.8c0,0.8 0.9,1.3 1.6,0.8l9.6,-6.4c0.6,-0.4 0.6,-1.3 0,-1.7l-9.6,-6.4c-0.7,-0.4 -1.6,0.1 -1.6,0.9z" android:fillColor="#1a120e" />
</vector>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineJoin="round" android:pathData="M3.5,3.5h6v6h-6zM14.5,3.5h6v6h-6zM3.5,14.5h6v6h-6z" />
<path android:fillColor="#FFFFFFFF" android:pathData="M5.5,5.5h2v2h-2zM16.5,5.5h2v2h-2zM5.5,16.5h2v2h-2zM14,14h3v3h-3zM17,17h3v3h-3zM17,14h3v1.5h-3zM14,18.5h1.5v1.5h-1.5z" />
</vector>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#FFFFFFFF" android:pathData="M12,6a6,6 0 1,0 0.01,0z" />
</vector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M12,3a9,9 0 1,0 0.01,0z" />
<path android:fillColor="#FFFFFFFF" android:pathData="M12,8.5a3.5,3.5 0 1,0 0.01,0z" />
</vector>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M4,4h16v6H4zM4,14h16v6H4z" />
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="2.2" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M8,7h0.01M8,17h0.01" />
</vector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M12,9a3,3 0 1,0 0.01,0z" />
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M12,2v3M12,19v3M2,12h3M19,12h3M4.9,4.9l2.1,2.1M17,17l2.1,2.1M4.9,19.1l2.1,-2.1M17,7l2.1,-2.1" />
</vector>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#FFFFFFFF" android:pathData="M6.5,6.5h11v11h-11z" />
</vector>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M20,12a8,8 0 0,1 -14.3,4.9M4,12a8,8 0 0,1 14.3,-4.9" />
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M18.5,3v4.5h-4.5M5.5,21v-4.5h4.5" />
</vector>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24" android:tint="@color/text">
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M2,6h20v13h-20z" />
<path android:fillColor="#00000000" android:strokeColor="#FFFFFFFF" android:strokeWidth="1.8" android:strokeLineCap="round" android:strokeLineJoin="round" android:pathData="M8,2l4,4 4,-4" />
</vector>
+2
View File
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="#171b19" /><stroke android:width="1dp" android:color="#333a36" /><corners android:radius="5dp" /></shape>
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="@color/accent" /><corners android:radius="7dp" /></shape>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"><color android:color="#33f69b74" /></item>
<item android:state_selected="true"><color android:color="#22f69b74" /></item>
<item android:state_activated="true"><color android:color="#22f69b74" /></item>
<item><color android:color="@android:color/transparent" /></item>
</selector>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- OSD: dark at the bottom, fading out towards the picture -->
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:angle="90" android:startColor="#f5050605" android:centerColor="#e6050605" android:centerY="0.6" android:endColor="#00050605" />
</shape>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape><corners android:radius="2dp" /><solid android:color="#26ffffff" /></shape>
</item>
<item android:id="@android:id/progress">
<clip><shape><corners android:radius="2dp" /><solid android:color="@color/accent" /></shape></clip>
</item>
</layer-list>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#14ffffff" />
<stroke android:width="1dp" android:color="#40ffffff" />
<corners android:radius="12dp" />
</shape>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#33bdd293" />
<stroke android:width="1dp" android:color="@color/green" />
<corners android:radius="12dp" />
</shape>
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"><solid android:color="@color/accent" /></shape>
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape android:shape="rectangle">
<solid android:color="#1fffffff" />
<stroke android:width="2dp" android:color="@color/accent" />
<corners android:radius="10dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="#0affffff" />
<corners android:radius="10dp" />
</shape>
</item>
</selector>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"><shape><solid android:color="#1a1411" /><stroke android:width="2dp" android:color="@color/accent" /><corners android:radius="8dp" /></shape></item>
<item><shape><solid android:color="@color/panel" /><stroke android:width="1dp" android:color="@color/line" /><corners android:radius="8dp" /></shape></item>
</selector>
+2
View File
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"><stroke android:width="1dp" android:color="@color/line" /><corners android:radius="12dp" /></shape>
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape><solid android:color="#1a1411" /><stroke android:width="2dp" android:color="@color/accent" /><corners android:radius="12dp" /></shape>
</item>
<item>
<shape><solid android:color="@color/panel" /><stroke android:width="1dp" android:color="@color/line" /><corners android:radius="12dp" /></shape>
</item>
</selector>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg">
<io.simplydvb.tv.ui.EpgGridView
android:id="@+id/grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<TextView
android:id="@+id/hint"
style="@style/Muted"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
+189
View File
@@ -0,0 +1,189 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000">
<androidx.media3.ui.PlayerView
android:id="@+id/player"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
app:show_buffering="when_playing"
app:use_controller="false" />
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#cc050605"
android:padding="18dp"
android:textColor="@color/text"
android:textSize="18sp"
android:visibility="gone" />
<!-- OSD: channel, technical details, now (with progress), before and later -->
<LinearLayout
android:id="@+id/osd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="@drawable/osd_bg"
android:orientation="vertical"
android:paddingStart="48dp"
android:paddingTop="80dp"
android:paddingEnd="48dp"
android:paddingBottom="30dp"
android:visibility="gone">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal">
<TextView android:id="@+id/o_number" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="18dp" android:minWidth="56dp" android:textColor="@color/accent" android:textSize="34sp" android:fontFamily="monospace" />
<ImageView android:id="@+id/o_logo" android:layout_width="84dp" android:layout_height="52dp" android:layout_marginEnd="18dp" android:contentDescription="@null" android:scaleType="fitCenter" />
<LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical">
<TextView android:id="@+id/o_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="end" android:textColor="@color/text" android:textSize="24sp" android:fontFamily="sans-serif-medium" />
<LinearLayout android:id="@+id/o_chips" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="6dp" android:orientation="horizontal" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="18dp" android:gravity="end" android:orientation="vertical">
<TextView android:id="@+id/o_clock" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/text" android:textSize="30sp" android:fontFamily="monospace" />
<TextView android:id="@+id/o_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/muted" android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
<View android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginTop="16dp" android:background="#26ffffff" />
<LinearLayout android:id="@+id/o_now_box" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="14dp" android:gravity="center_vertical" android:orientation="horizontal">
<TextView style="@style/OsdLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/osd_now" android:textColor="@color/accent" />
<TextView android:id="@+id/o_now_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:textColor="@color/muted" android:textSize="13sp" android:fontFamily="monospace" />
<View android:layout_width="0dp" android:layout_height="1dp" android:layout_weight="1" />
<TextView android:id="@+id/o_now_left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/muted" android:textSize="13sp" />
</LinearLayout>
<TextView android:id="@+id/o_now_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="2dp" android:singleLine="true" android:ellipsize="end" android:textColor="@color/text" android:textSize="22sp" android:fontFamily="sans-serif-medium" />
<ProgressBar android:id="@+id/o_progress" style="@android:style/Widget.Material.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="4dp" android:layout_marginTop="8dp" android:max="1000" android:progressDrawable="@drawable/osd_progress" />
<TextView android:id="@+id/o_now_desc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:maxLines="2" android:ellipsize="end" android:lineSpacingExtra="2dp" android:textColor="@color/muted" android:textSize="13sp" />
</LinearLayout>
<LinearLayout android:id="@+id/o_more" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:orientation="horizontal">
<LinearLayout android:id="@+id/o_prev_box" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginEnd="24dp" android:orientation="vertical">
<TextView android:id="@+id/o_prev_label" style="@style/OsdLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/o_prev" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:singleLine="true" android:ellipsize="end" android:textColor="#c3cac5" android:textSize="14sp" />
</LinearLayout>
<LinearLayout android:id="@+id/o_next_box" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginEnd="24dp" android:orientation="vertical">
<TextView android:id="@+id/o_next_label" style="@style/OsdLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/o_next" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:singleLine="true" android:ellipsize="end" android:textColor="#c3cac5" android:textSize="14sp" />
</LinearLayout>
<LinearLayout android:id="@+id/o_later_box" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginEnd="24dp" android:orientation="vertical">
<TextView android:id="@+id/o_later_label" style="@style/OsdLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/o_later" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:singleLine="true" android:ellipsize="end" android:textColor="#c3cac5" android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- channel number being typed -->
<TextView
android:id="@+id/digits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|start"
android:layout_margin="40dp"
android:background="@drawable/card"
android:fontFamily="monospace"
android:paddingStart="24dp"
android:paddingTop="10dp"
android:paddingEnd="24dp"
android:paddingBottom="10dp"
android:textColor="@color/accent"
android:textSize="44sp"
android:visibility="gone" />
<!-- tuner card (optional, top right) -->
<LinearLayout
android:id="@+id/tuner_card"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:layout_gravity="top|end"
android:layout_margin="20dp"
android:background="@drawable/card"
android:orientation="vertical"
android:padding="10dp"
android:visibility="gone">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal">
<View android:id="@+id/t_lock" android:layout_width="8dp" android:layout_height="8dp" android:layout_marginEnd="7dp" android:background="@drawable/dot" />
<TextView android:id="@+id/t_name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:singleLine="true" android:ellipsize="end" android:textColor="@color/text" android:textSize="12sp" android:fontFamily="sans-serif-medium" />
</LinearLayout>
<TextView android:id="@+id/t_stream" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="end" android:textColor="@color/muted" android:textSize="9sp" android:fontFamily="monospace" />
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="6dp" android:gravity="center_vertical" android:orientation="horizontal">
<LinearLayout android:layout_width="96dp" android:layout_height="wrap_content" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:text="@string/t_signal_snr" android:textColor="@color/muted" android:textSize="9sp" />
<TextView android:id="@+id/t_signal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:textColor="@color/green" android:textSize="14sp" android:fontFamily="monospace" />
</LinearLayout>
<io.simplydvb.tv.ui.SparkView android:id="@+id/t_spark" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="1" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="6dp" android:gravity="center_vertical" android:orientation="horizontal">
<LinearLayout android:layout_width="96dp" android:layout_height="wrap_content" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:text="@string/t_cpu" android:textColor="@color/muted" android:textSize="9sp" />
<TextView android:id="@+id/t_cpu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:textColor="@color/accent" android:textSize="14sp" android:fontFamily="monospace" />
<TextView android:id="@+id/t_cpu_sub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:textColor="@color/muted" android:textSize="9sp" android:fontFamily="monospace" />
</LinearLayout>
<io.simplydvb.tv.ui.SparkView android:id="@+id/t_cpu_spark" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="1" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="6dp" android:gravity="center_vertical" android:orientation="horizontal">
<LinearLayout android:layout_width="96dp" android:layout_height="wrap_content" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:text="@string/t_stream_rate" android:textColor="@color/muted" android:textSize="9sp" />
<TextView android:id="@+id/t_rate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:textColor="@color/blue" android:textSize="14sp" android:fontFamily="monospace" />
<TextView android:id="@+id/t_rate_sub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:textColor="@color/muted" android:textSize="9sp" android:fontFamily="monospace" />
</LinearLayout>
<io.simplydvb.tv.ui.SparkView android:id="@+id/t_rate_spark" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="1" />
</LinearLayout>
<TextView android:id="@+id/t_video" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:singleLine="true" android:ellipsize="end" android:textColor="@color/text" android:textSize="9sp" android:fontFamily="monospace" />
<TextView android:id="@+id/t_details" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:lineSpacingExtra="1dp" android:textColor="@color/muted" android:textSize="9sp" android:fontFamily="monospace" />
</LinearLayout>
<!-- channel list (OK button) -->
<LinearLayout
android:id="@+id/list_panel"
android:layout_width="460dp"
android:layout_height="match_parent"
android:background="#ee050605"
android:orientation="vertical"
android:paddingTop="28dp"
android:visibility="gone">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="24dp" android:text="@string/channels" android:textColor="@color/text" android:textSize="22sp" android:fontFamily="sans-serif-medium" />
<TextView android:id="@+id/list_server" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="24dp" android:layout_marginEnd="24dp" android:layout_marginTop="2dp" android:layout_marginBottom="12dp" android:singleLine="true" android:ellipsize="end" android:textColor="@color/muted" android:textSize="13sp" />
<ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" android:divider="@color/line" android:dividerHeight="1dp" android:listSelector="@drawable/list_item" android:choiceMode="singleChoice" />
</LinearLayout>
<!-- programme grid (GUIDE, right arrow) -->
<io.simplydvb.tv.ui.EpgGridView
android:id="@+id/epg_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<!-- recording indicator -->
<TextView
android:id="@+id/rec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|start"
android:layout_margin="28dp"
android:background="@drawable/card"
android:drawableStart="@drawable/ic_record"
android:drawablePadding="8dp"
android:drawableTint="@color/red"
android:gravity="center_vertical"
android:paddingStart="10dp"
android:paddingTop="6dp"
android:paddingEnd="12dp"
android:paddingBottom="6dp"
android:text="REC"
android:textColor="@color/text"
android:textSize="13sp"
android:visibility="gone" />
</FrameLayout>
+125
View File
@@ -0,0 +1,125 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Start screen: header, the player (focused), shortcuts, server state, remote keys -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg"
android:orientation="vertical">
<LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="vertical" android:paddingStart="36dp" android:paddingTop="26dp" android:paddingEnd="36dp">
<!-- header -->
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal">
<ImageView android:layout_width="30dp" android:layout_height="30dp" android:contentDescription="@string/app_name" android:src="@drawable/ic_logo" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:text="@string/app_name" android:textColor="@color/text" android:textSize="20sp" android:textStyle="bold" />
<View android:layout_width="0dp" android:layout_height="1dp" android:layout_weight="1" />
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="end" android:orientation="vertical">
<TextView android:id="@+id/m_clock" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/text" android:textSize="22sp" android:fontFamily="sans-serif-medium" />
<TextView android:id="@+id/m_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
</LinearLayout>
<!-- the player: focused on start, OK opens it -->
<LinearLayout android:id="@+id/live" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="-5dp" android:layout_marginTop="13dp" android:layout_marginEnd="-5dp" android:background="@drawable/hero_bg" android:clickable="true" android:focusable="true" android:gravity="center_vertical" android:orientation="horizontal" android:paddingStart="31dp" android:paddingTop="27dp" android:paddingEnd="31dp" android:paddingBottom="27dp">
<FrameLayout android:layout_width="64dp" android:layout_height="64dp" android:background="@drawable/play_circle">
<ImageView android:layout_width="30dp" android:layout_height="30dp" android:layout_gravity="center" android:contentDescription="@null" android:src="@drawable/ic_play_solid" />
</FrameLayout>
<LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="22dp" android:layout_weight="1" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/watch_title" android:textColor="@color/text" android:textSize="26sp" android:textStyle="bold" />
<TextView android:id="@+id/m_now" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="6dp" android:singleLine="true" android:ellipsize="end" android:textColor="#c3cac5" android:textSize="13sp" />
<ProgressBar android:id="@+id/m_progress" style="@android:style/Widget.Material.ProgressBar.Horizontal" android:layout_width="420dp" android:layout_height="4dp" android:layout_marginTop="10dp" android:max="1000" android:progressDrawable="@drawable/osd_progress" android:visibility="invisible" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:gravity="center_horizontal" android:orientation="vertical">
<TextView android:layout_width="40dp" android:layout_height="30dp" android:background="@drawable/keycap_accent" android:gravity="center" android:text="OK" android:textColor="#1a120e" android:textSize="12sp" android:textStyle="bold" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:text="@string/m_start" android:textColor="#a3aca5" android:textSize="10sp" />
</LinearLayout>
</LinearLayout>
<!-- shortcuts -->
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="9dp" android:orientation="horizontal">
<LinearLayout android:id="@+id/guide" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@drawable/tile_bg" android:clickable="true" android:focusable="true" android:orientation="vertical" android:paddingStart="14dp" android:paddingTop="14dp" android:paddingEnd="14dp" android:paddingBottom="12dp">
<ImageView android:layout_width="22dp" android:layout_height="22dp" android:contentDescription="@null" android:src="@drawable/ic_guide" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:singleLine="true" android:text="@string/guide_short" android:textColor="@color/text" android:textSize="14sp" android:fontFamily="sans-serif-medium" />
<TextView android:id="@+id/guide_sub" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:singleLine="true" android:ellipsize="end" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:id="@+id/recordings" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginStart="12dp" android:background="@drawable/tile_bg" android:clickable="true" android:focusable="true" android:orientation="vertical" android:paddingStart="14dp" android:paddingTop="14dp" android:paddingEnd="14dp" android:paddingBottom="12dp">
<ImageView android:layout_width="22dp" android:layout_height="22dp" android:contentDescription="@null" android:src="@drawable/ic_recordings" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:singleLine="true" android:text="@string/recordings" android:textColor="@color/text" android:textSize="14sp" android:fontFamily="sans-serif-medium" />
<TextView android:id="@+id/recordings_sub" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:singleLine="true" android:ellipsize="end" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:id="@+id/watch" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginStart="12dp" android:background="@drawable/tile_bg" android:clickable="true" android:focusable="true" android:orientation="vertical" android:paddingStart="14dp" android:paddingTop="14dp" android:paddingEnd="14dp" android:paddingBottom="12dp">
<ImageView android:layout_width="22dp" android:layout_height="22dp" android:contentDescription="@null" android:src="@drawable/ic_tv" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:singleLine="true" android:text="@string/tv_app" android:textColor="@color/text" android:textSize="14sp" android:fontFamily="sans-serif-medium" />
<TextView android:id="@+id/watch_sub" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:singleLine="true" android:ellipsize="end" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:id="@+id/servers" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginStart="12dp" android:background="@drawable/tile_bg" android:clickable="true" android:focusable="true" android:orientation="vertical" android:paddingStart="14dp" android:paddingTop="14dp" android:paddingEnd="14dp" android:paddingBottom="12dp">
<ImageView android:layout_width="22dp" android:layout_height="22dp" android:contentDescription="@null" android:src="@drawable/ic_server" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:singleLine="true" android:text="@string/servers" android:textColor="@color/text" android:textSize="14sp" android:fontFamily="sans-serif-medium" />
<TextView android:id="@+id/servers_sub" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:singleLine="true" android:ellipsize="end" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:id="@+id/settings" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_marginStart="12dp" android:background="@drawable/tile_bg" android:clickable="true" android:focusable="true" android:orientation="vertical" android:paddingStart="14dp" android:paddingTop="14dp" android:paddingEnd="14dp" android:paddingBottom="12dp">
<ImageView android:layout_width="22dp" android:layout_height="22dp" android:contentDescription="@null" android:src="@drawable/ic_settings" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:singleLine="true" android:text="@string/settings" android:textColor="@color/text" android:textSize="14sp" android:fontFamily="sans-serif-medium" />
<TextView android:id="@+id/settings_sub" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:singleLine="true" android:ellipsize="end" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
</LinearLayout>
<!-- server state (what used to be the centre of the screen) -->
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="14dp" android:background="@drawable/status_box" android:gravity="center_vertical" android:orientation="horizontal" android:paddingStart="16dp" android:paddingTop="10dp" android:paddingEnd="12dp" android:paddingBottom="10dp">
<View android:id="@+id/m_dot" android:layout_width="10dp" android:layout_height="10dp" android:background="@drawable/dot" android:backgroundTint="@color/muted" />
<LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:layout_weight="1" android:orientation="vertical">
<TextView android:id="@+id/server" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="end" android:textColor="@color/text" android:textSize="13sp" android:fontFamily="sans-serif-medium" />
<TextView android:id="@+id/status" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="2dp" android:maxLines="2" android:ellipsize="end" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:id="@+id/sync" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:background="@drawable/small_button" android:clickable="true" android:focusable="true" android:gravity="center_vertical" android:orientation="horizontal" android:paddingStart="12dp" android:paddingTop="7dp" android:paddingEnd="12dp" android:paddingBottom="7dp">
<ImageView android:layout_width="15dp" android:layout_height="15dp" android:contentDescription="@null" android:src="@drawable/ic_sync" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:text="@string/sync_short" android:textColor="@color/text" android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- remote keys in the player -->
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/hint_bar" android:orientation="vertical" android:paddingStart="36dp" android:paddingTop="12dp" android:paddingEnd="36dp" android:paddingBottom="14dp">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:letterSpacing="0.13" android:text="@string/keys_title" android:textAllCaps="true" android:textColor="@color/muted" android:textSize="9sp" android:fontFamily="sans-serif-medium" />
<HorizontalScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:focusable="false" android:scrollbars="none">
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal">
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal">
<LinearLayout android:layout_width="wrap_content" android:layout_height="22dp" android:minWidth="24dp" android:background="@drawable/keycap" android:gravity="center" android:orientation="horizontal" android:paddingStart="6dp" android:paddingEnd="6dp"><ImageView android:layout_width="12dp" android:layout_height="12dp" android:contentDescription="@null" android:src="@drawable/ic_chev_up" /><ImageView android:layout_width="12dp" android:layout_height="12dp" android:contentDescription="@null" android:src="@drawable/ic_chev_down" /></LinearLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="7dp" android:singleLine="true" android:text="@string/key_channel" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:gravity="center_vertical" android:orientation="horizontal">
<TextView android:layout_width="wrap_content" android:layout_height="22dp" android:minWidth="24dp" android:background="@drawable/keycap" android:gravity="center" android:paddingStart="6dp" android:paddingEnd="6dp" android:text="OK" android:textColor="@color/text" android:textSize="10sp" android:textStyle="bold" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="7dp" android:singleLine="true" android:text="@string/key_list" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:gravity="center_vertical" android:orientation="horizontal">
<LinearLayout android:layout_width="wrap_content" android:layout_height="22dp" android:minWidth="24dp" android:background="@drawable/keycap" android:gravity="center" android:orientation="horizontal" android:paddingStart="6dp" android:paddingEnd="6dp"><ImageView android:layout_width="12dp" android:layout_height="12dp" android:contentDescription="@null" android:src="@drawable/ic_chev_left" /></LinearLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="7dp" android:singleLine="true" android:text="@string/key_osd" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:gravity="center_vertical" android:orientation="horizontal">
<LinearLayout android:layout_width="wrap_content" android:layout_height="22dp" android:minWidth="24dp" android:background="@drawable/keycap" android:gravity="center" android:orientation="horizontal" android:paddingStart="6dp" android:paddingEnd="6dp"><ImageView android:layout_width="12dp" android:layout_height="12dp" android:contentDescription="@null" android:src="@drawable/ic_chev_right" /></LinearLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="7dp" android:singleLine="true" android:text="@string/key_guide" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:gravity="center_vertical" android:orientation="horizontal">
<TextView android:layout_width="wrap_content" android:layout_height="22dp" android:minWidth="24dp" android:background="@drawable/keycap" android:gravity="center" android:paddingStart="6dp" android:paddingEnd="6dp" android:text="0–9" android:textColor="@color/text" android:textSize="10sp" android:textStyle="bold" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="7dp" android:singleLine="true" android:text="@string/key_number" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:gravity="center_vertical" android:orientation="horizontal">
<FrameLayout android:layout_width="24dp" android:layout_height="22dp" android:background="@drawable/keycap"><View android:layout_width="10dp" android:layout_height="10dp" android:layout_gravity="center" android:background="@drawable/dot" android:backgroundTint="#e25b45" /></FrameLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="7dp" android:singleLine="true" android:text="@string/key_record" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:gravity="center_vertical" android:orientation="horizontal">
<FrameLayout android:layout_width="24dp" android:layout_height="22dp" android:background="@drawable/keycap"><View android:layout_width="10dp" android:layout_height="10dp" android:layout_gravity="center" android:background="@drawable/dot" android:backgroundTint="#5aa05a" /></FrameLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="7dp" android:singleLine="true" android:text="@string/key_audio" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:gravity="center_vertical" android:orientation="horizontal">
<FrameLayout android:layout_width="24dp" android:layout_height="22dp" android:background="@drawable/keycap"><View android:layout_width="10dp" android:layout_height="10dp" android:layout_gravity="center" android:background="@drawable/dot" android:backgroundTint="#e6c84a" /></FrameLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="7dp" android:singleLine="true" android:text="@string/key_subtitles" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:gravity="center_vertical" android:orientation="horizontal">
<FrameLayout android:layout_width="24dp" android:layout_height="22dp" android:background="@drawable/keycap"><View android:layout_width="10dp" android:layout_height="10dp" android:layout_gravity="center" android:background="@drawable/dot" android:backgroundTint="#5b8cff" /></FrameLayout>
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="7dp" android:singleLine="true" android:text="@string/key_card" android:textColor="#a3aca5" android:textSize="11sp" />
</LinearLayout>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</LinearLayout>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000">
<androidx.media3.ui.PlayerView
android:id="@+id/player"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:show_buffering="when_playing" />
</FrameLayout>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="36dp">
<TextView android:id="@+id/title" style="@style/Title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/recordings" />
<TextView android:id="@+id/hint" style="@style/Muted" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="6dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="18dp"
android:layout_weight="1"
android:orientation="horizontal">
<ListView android:id="@+id/left" android:layout_width="320dp" android:layout_height="match_parent" android:choiceMode="singleChoice" android:divider="@color/line" android:dividerHeight="1dp" android:listSelector="@drawable/list_item" />
<View android:layout_width="1dp" android:layout_height="match_parent" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:background="@color/line" />
<ListView android:id="@+id/right" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:divider="@color/line" android:dividerHeight="1dp" android:listSelector="@drawable/list_item" />
</LinearLayout>
</LinearLayout>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="40dp">
<TextView style="@style/Title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/servers" />
<TextView style="@style/Muted" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="6dp" android:maxWidth="900dp" android:lineSpacingExtra="3dp" android:text="@string/servers_hint" />
<LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginTop="20dp" android:layout_weight="1" android:orientation="horizontal">
<ListView android:id="@+id/list" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:divider="@color/line" android:dividerHeight="1dp" android:listSelector="@drawable/list_item" />
<LinearLayout android:layout_width="340dp" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:orientation="vertical">
<Button android:id="@+id/add" style="@style/TvButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/add_server" />
<Button android:id="@+id/load" style="@style/TvButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:drawableStart="@drawable/ic_sync" android:drawablePadding="14dp" android:text="@string/load_into_tv" />
<TextView android:id="@+id/result" style="@style/Muted" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:lineSpacingExtra="3dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="40dp">
<!-- left: title and a live preview of the OSD option being changed -->
<LinearLayout android:layout_width="260dp" android:layout_height="match_parent" android:layout_marginEnd="36dp" android:orientation="vertical">
<ImageView android:layout_width="40dp" android:layout_height="40dp" android:contentDescription="@null" android:src="@drawable/ic_settings" />
<TextView style="@style/Title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="14dp" android:text="@string/settings" />
<TextView android:id="@+id/hint" style="@style/Muted" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:lineSpacingExtra="3dp" android:textSize="13sp" />
</LinearLayout>
<ScrollView android:id="@+id/scroll" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:scrollbars="none">
<LinearLayout android:id="@+id/rows" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingBottom="40dp" />
</ScrollView>
</LinearLayout>
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="48dp">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:paddingEnd="48dp">
<TextView style="@style/Title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/setup_title" />
<TextView style="@style/Muted" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:lineSpacingExtra="4dp" android:text="@string/setup_hint" />
<TextView android:id="@+id/result" style="@style/Muted" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:lineSpacingExtra="4dp" android:textSize="17sp" />
<LinearLayout
android:id="@+id/pair_panel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:visibility="gone">
<ImageView android:id="@+id/pair_qr" android:layout_width="240dp" android:layout_height="240dp" android:background="#ffffff" android:contentDescription="@string/pair_qr" android:padding="10dp" />
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="28dp" android:orientation="vertical">
<TextView style="@style/Muted" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/pair_code_label" />
<TextView android:id="@+id/pair_code" android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="monospace" android:letterSpacing="0.2" android:textColor="@color/accent" android:textSize="44sp" android:textStyle="bold" />
<TextView android:id="@+id/pair_url" style="@style/Muted" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:maxWidth="360dp" android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="420dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView style="@style/Label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/server_name" />
<EditText android:id="@+id/name" style="@style/Field" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/server_name_hint" android:inputType="text" android:importantForAutofill="no" />
<TextView style="@style/Label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/server_address" />
<EditText android:id="@+id/host" style="@style/Field" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="192.168.1.10" android:inputType="textUri" android:importantForAutofill="no" />
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical" android:paddingEnd="8dp">
<TextView style="@style/Label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/htsp_port" />
<EditText android:id="@+id/htsp_port" style="@style/Field" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:importantForAutofill="no" />
</LinearLayout>
<LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical" android:paddingStart="8dp">
<TextView style="@style/Label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/http_port" />
<EditText android:id="@+id/http_port" style="@style/Field" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:importantForAutofill="no" />
</LinearLayout>
</LinearLayout>
<TextView style="@style/Label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/username" />
<EditText android:id="@+id/username" style="@style/Field" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/optional" android:inputType="text" android:importantForAutofill="no" />
<TextView style="@style/Label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/password_token" />
<EditText android:id="@+id/password" style="@style/Field" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/optional" android:inputType="textPassword" android:importantForAutofill="no" />
<Button android:id="@+id/pair" style="@style/TvButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:drawableStart="@drawable/ic_qr" android:drawablePadding="14dp" android:text="@string/pair_with_qr" />
<Button android:id="@+id/connect" style="@style/TvButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:drawableStart="@drawable/ic_sync" android:drawablePadding="14dp" android:text="@string/connect_and_sync" />
</LinearLayout>
</LinearLayout>
</ScrollView>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.media3.ui.SubtitleView
android:id="@+id/subtitles"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
+21
View File
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="56dp"
android:orientation="horizontal"
android:paddingStart="12dp"
android:paddingTop="8dp"
android:paddingEnd="12dp"
android:paddingBottom="8dp">
<ImageView android:id="@+id/icon" android:layout_width="22dp" android:layout_height="22dp" android:layout_marginEnd="14dp" android:contentDescription="@null" android:visibility="gone" />
<LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical">
<TextView android:id="@+id/line1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ellipsize="end" android:singleLine="true" android:textColor="@color/text" android:textSize="17sp" />
<TextView android:id="@+id/line2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ellipsize="end" android:maxLines="2" android:textColor="@color/muted" android:textSize="13sp" />
</LinearLayout>
<TextView android:id="@+id/badge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:textColor="@color/accent" android:textSize="13sp" />
</LinearLayout>
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="64dp"
android:orientation="horizontal"
android:paddingStart="16dp"
android:paddingEnd="16dp">
<TextView android:id="@+id/number" android:layout_width="44dp" android:layout_height="wrap_content" android:gravity="end" android:layout_marginEnd="14dp" android:textColor="@color/muted" android:textSize="16sp" android:fontFamily="monospace" />
<ImageView android:id="@+id/logo" android:layout_width="64dp" android:layout_height="40dp" android:layout_marginEnd="14dp" android:contentDescription="@null" android:scaleType="fitCenter" />
<LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical" android:paddingTop="6dp" android:paddingBottom="6dp">
<TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="end" android:textColor="@color/text" android:textSize="17sp" />
<TextView android:id="@+id/now" android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="end" android:textColor="@color/muted" android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- one row of the settings screen: icon, title + description, value -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:background="@drawable/setting_row"
android:focusable="true"
android:clickable="true"
android:gravity="center_vertical"
android:minHeight="56dp"
android:orientation="horizontal"
android:paddingStart="18dp"
android:paddingTop="10dp"
android:paddingEnd="18dp"
android:paddingBottom="10dp">
<ImageView android:id="@+id/s_icon" android:layout_width="22dp" android:layout_height="22dp" android:layout_marginEnd="16dp" android:contentDescription="@null" />
<LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical">
<TextView android:id="@+id/s_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@color/text" android:textSize="15sp" />
<TextView android:id="@+id/s_desc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="2dp" android:lineSpacingExtra="1dp" android:textColor="@color/muted" android:textSize="12sp" />
</LinearLayout>
<TextView android:id="@+id/s_value" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:minWidth="64dp" android:gravity="center" android:paddingStart="12dp" android:paddingTop="4dp" android:paddingEnd="12dp" android:paddingBottom="4dp" android:textColor="@color/text" android:textSize="13sp" />
</LinearLayout>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

+159
View File
@@ -0,0 +1,159 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="watch_tv">Oglądaj w aplikacji TV</string>
<string name="guide_and_record">Program TV i nagrywanie</string>
<string name="recordings">Nagrania</string>
<string name="sync_now">Odśwież kanały i program</string>
<string name="server_settings">Serwery</string>
<string name="not_configured">Nie ustawiono serwera – otwórz Ustawienia serwera</string>
<string name="setup_title">Połącz z simply-dvb</string>
<string name="setup_hint">Podaj adres serwera simply-dvb (tvheadend też działa). Kanały, logotypy i program TV pojawią się jako źródło we wbudowanej aplikacji TV telewizora.
Najprościej: wpisz sam adres i wybierz „Paruj kodem QR” – zeskanuj kod telefonem i zatwierdź w panelu, token ustawi się sam. W sieci lokalnej możesz też połączyć się bez logowania.</string>
<string name="server_address">Adres serwera (IP lub nazwa hosta)</string>
<string name="htsp_port">Port HTSP</string>
<string name="http_port">Port HTTP (strumienie)</string>
<string name="username">Nazwa użytkownika</string>
<string name="password_token">Hasło / token dostępu</string>
<string name="optional">opcjonalnie</string>
<string name="connect_and_sync">Połącz i wczytaj kanały</string>
<string name="connecting">Łączenie…</string>
<string name="syncing">Połączono z %1$s. Wczytywanie kanałów, logotypów i programu…</string>
<string name="sync_done">Gotowe: %1$d kanałów. Otwórz aplikację TV i wybierz źródło simply-tv.</string>
<string name="error">Błąd: %1$s</string>
<string name="status_line">Kanały: %1$d · audycje: %2$d · nagrania: %3$d\nOstatnie odświeżenie: %4$s</string>
<string name="status_never">Jeszcze nie odświeżono</string>
<string name="status_error">Ostatnie odświeżenie nie powiodło się: %1$s</string>
<string name="sync_started">Odświeżanie w tle…</string>
<string name="guide_hint">Góra/dół: kanały · lewo/prawo: audycje · OK: szczegóły, nagrywanie, oglądanie</string>
<string name="recording_default_title">Nagranie</string>
<string name="record">Nagraj</string>
<string name="cancel_recording">Anuluj nagranie</string>
<string name="recording_scheduled">Zaplanowano nagranie: %1$s</string>
<string name="recording_cancelled">Nagranie anulowane</string>
<string name="scheduled_badge">NAGR</string>
<string name="now">teraz</string>
<string name="play">Odtwórz</string>
<string name="delete">Usuń</string>
<string name="stop">Zatrzymaj</string>
<string name="close">Zamknij</string>
<string name="delete_confirm">Usunąć nagranie „%1$s”?</string>
<string name="no_recordings">Brak nagrań.</string>
<string name="no_programmes">Brak programu dla tego kanału.</string>
<string name="loading">Wczytywanie…</string>
<string name="state_scheduled">zaplanowane</string>
<string name="state_recording">trwa nagrywanie</string>
<string name="state_completed">nagrane</string>
<string name="state_failed">nieudane</string>
<string name="open_tv_failed">Nie udało się otworzyć aplikacji TV – wybierz źródło simply-tv w wejściach telewizora.</string>
<string name="channels">Kanały</string>
<string name="own_player">Odtwarzacz simply-tv</string>
<string name="tv_app">Aplikacja TV</string>
<string name="no_channels">Brak kanałów – odśwież na ekranie głównym.</string>
<string name="tuning">Przełączanie na %1$s…</string>
<string name="no_signal">Brak obrazu: %1$s</string>
<string name="next">Następnie: %1$s</string>
<string name="pair_with_qr">Paruj kodem QR</string>
<string name="pair_qr">Kod QR do parowania</string>
<string name="pair_code_label">Kod</string>
<string name="pair_need_host">Najpierw wpisz adres serwera.</string>
<string name="pair_waiting">Zeskanuj kod QR telefonem i zatwierdź w panelu simply-dvb (albo otwórz Dostęp → Sparuj telewizor i wpisz kod). Czekam…</string>
<string name="pair_expired">Kod wygasł – naciśnij ponownie „Paruj kodem QR”.</string>
<string name="pair_done">Sparowano jako „%1$s”. Wczytywanie kanałów, logotypów i programu…</string>
<string name="t_signal">Sygnał</string>
<string name="t_bitrate">Mbit/s</string>
<string name="epg_hint">OK: nagraj / oglądaj · Wstecz: lista kanałów</string>
<string name="tuner_info">Informacje o tunerze w odtwarzaczu</string>
<string name="on">wł.</string>
<string name="off">wył.</string>
<string name="record_now">Nagraj teraz</string>
<string name="watch">Oglądaj</string>
<string name="recording_started">Nagrywanie: %1$s</string>
<string name="recording_stopped">Nagrywanie zatrzymane</string>
<string name="audio_track">Dźwięk: %1$s</string>
<string name="subtitles_on">Napisy włączone</string>
<string name="subtitles_off">Napisy wyłączone</string>
<string name="no_epg_now">Brak informacji o audycji – nagrywam 2 godziny</string>
<string name="player_keys">Odtwarzacz: góra/dół lub CH+/CH- zmienia kanał · INFO lub strzałka w lewo: informacje na ekranie (teraz, wcześniej, później, obraz i sygnał) · OK: lista kanałów · strzałka w prawo lub GUIDE: siatka programu · CZERWONY/REC: nagrywanie · ZIELONY: dźwięk · ŻÓŁTY: napisy · NIEBIESKI: karta tunera · przycisk poprzedniego kanału</string>
<string name="server_name">Nazwa</string>
<string name="server_name_hint">np. Dom, Działka</string>
<string name="servers">Serwery</string>
<string name="add_server">Dodaj serwer</string>
<string name="use_in_player">Używaj w odtwarzaczu, programie i nagraniach</string>
<string name="tv_source_on">Aplikacja TV: wł.</string>
<string name="tv_source_off">Aplikacja TV: wył.</string>
<string name="active">aktywny</string>
<string name="edit">Edytuj</string>
<string name="delete_server_confirm">Usunąć serwer „%1$s” z simply-tv? Jego kanały znikną z aplikacji TV.</string>
<string name="server_switched">Serwer: %1$s</string>
<string name="load_into_tv">Wczytaj kanały do aplikacji TV</string>
<string name="servers_hint">Aktywny serwer jest używany w odtwarzaczu, programie i nagraniach (w odtwarzaczu: strzałka w lewo na liście kanałów). Serwery z „Aplikacja TV: wł.” dostarczają kanały do wbudowanej aplikacji TV telewizora.</string>
<string name="choose_server">Wybierz serwer</string>
<string name="switch_server_hint">Strzałka w lewo: inny serwer</string>
<string name="t_signal_snr">Sygnał / SNR</string>
<string name="t_cpu">CPU serwera</string>
<string name="t_stream_rate">Strumień (odbierany)</string>
<string name="epg_grid_hint">OK: szczegóły i nagrywanie · CZERWONY: nagraj · ZIELONY: teraz · CH+/CH-: strona · WSTECZ: zamknij</string>
<string name="tunneling">Tunelowanie wideo</string>
<string name="autostart">Uruchamiaj odtwarzacz z telewizorem</string>
<string name="autostart_needs_permission">brak uprawnienia</string>
<string name="autostart_permission">Aby otwierać odtwarzacz po włączeniu telewizora, Android wymaga dla simply-tv uprawnienia „Wyświetlanie nad innymi aplikacjami”. Zezwól na nie na następnym ekranie.\n\nJeśli telewizor nie ma takiego ekranu, nadaj je jednorazowo z komputera:\nadb shell appops set %1$s SYSTEM_ALERT_WINDOW allow</string>
<string name="open_settings">Otwórz ustawienia</string>
<string name="autostart_no_settings">Ten telewizor nie ma takiego ekranu ustawień – użyj polecenia adb</string>
<string name="live_tv_label">simply-tv Na żywo</string>
<string name="osd_now">Teraz</string>
<string name="osd_before">Wcześniej</string>
<string name="osd_next">Następnie</string>
<string name="osd_later">Później</string>
<string name="osd_left">jeszcze %d min</string>
<string name="osd_signal">Sygnał</string>
<string name="settings">Ustawienia</string>
<string name="set_sec_osd">Informacje na ekranie (OSD)</string>
<string name="set_sec_player">Odtwarzacz</string>
<string name="set_sec_start">Uruchamianie</string>
<string name="set_sec_servers">Serwery</string>
<string name="set_sec_about">O aplikacji</string>
<string name="set_osd_zap">Pokazuj przy zmianie kanału</string>
<string name="set_osd_zap_desc">Kanał, co leci teraz z paskiem postępu, co było i co będzie. INFO lub strzałka w lewo pokazuje je zawsze.</string>
<string name="set_osd_seconds">Czas wyświetlania</string>
<string name="set_osd_seconds_desc">Jak długo OSD zostaje na ekranie po zmianie kanału</string>
<string name="set_seconds">%d s</string>
<string name="set_osd_tech">Szczegóły techniczne</string>
<string name="set_osd_tech_desc">Rozdzielczość, dźwięk, sygnał i przepływność strumienia odbieranego przez telewizor</string>
<string name="set_osd_desc">Opis audycji</string>
<string name="set_osd_desc_desc">Dwie linie o bieżącej audycji</string>
<string name="set_tuner_card">Karta tunera przy zmianie kanału</string>
<string name="set_tuner_card_desc">Szczegółowa karta (prawy górny róg): wykresy sygnału, CPU serwera, przepływność, błędy. NIEBIESKI przełącza ją podczas oglądania.</string>
<string name="set_tunneling_desc">Telewizor sam dekoduje i synchronizuje obraz, jak własny tuner. Wyłącz, jeśli na jakimś kanale nie ma obrazu.</string>
<string name="set_autostart_desc">Otwiera odtwarzacz na ostatnim kanale po starcie lub wybudzeniu telewizora</string>
<string name="set_servers">Zarządzaj serwerami</string>
<string name="set_servers_desc">Dodawanie, przełączanie i usuwanie serwerów oraz wybór, które zasilają aplikację TV</string>
<string name="set_version">Wersja</string>
<string name="set_choose">Wybierz</string>
<string name="watch_title">Oglądaj telewizję</string>
<string name="m_start">start</string>
<string name="guide_short">Program TV</string>
<string name="sync_short">Synchronizuj</string>
<string name="keys_title">Pilot w odtwarzaczu</string>
<string name="key_channel">kanał</string>
<string name="key_list">lista kanałów</string>
<string name="key_osd">informacje (OSD)</string>
<string name="key_guide">program TV</string>
<string name="key_number">numer</string>
<string name="key_record">nagrywaj</string>
<string name="key_audio">dźwięk</string>
<string name="key_subtitles">napisy</string>
<string name="key_card">karta tunera</string>
<string name="m_resume">Wróć do %1$s</string>
<string name="m_now_on">teraz: %1$s, %2$s</string>
<string name="m_no_epg">brak informacji o programie</string>
<string name="m_first">Otwórz odtwarzacz i wybierz kanał</string>
<string name="m_unreachable">Serwer niedostępny: %1$s</string>
<string name="m_loading">Sprawdzam, co leci…</string>
<string name="sub_guide">siatka programu</string>
<string name="sub_recordings">zapisane: %1$d</string>
<string name="sub_tv_app">kanały we wbudowanej aplikacji TV</string>
<string name="sub_settings">OSD, uruchamianie, obraz</string>
<string name="sub_no_server">brak serwera</string>
<string name="status_compact">kanały: %1$d · audycje: %2$d · nagrania: %3$d · odświeżono %4$s</string>
</resources>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="bg">#050605</color>
<color name="panel">#0f1211</color>
<color name="line">#262c28</color>
<color name="text">#e8ece9</color>
<color name="muted">#8d968f</color>
<color name="accent">#f69b74</color>
<color name="red">#e25b45</color>
<color name="green">#bdd293</color>
<color name="blue">#7aa7ff</color>
<color name="text_soft">#c3cac5</color>
</resources>
+160
View File
@@ -0,0 +1,160 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">simply-tv</string>
<string name="watch_tv">Watch in the TV app</string>
<string name="guide_and_record">Programme guide &amp; recording</string>
<string name="recordings">Recordings</string>
<string name="sync_now">Refresh channels &amp; guide</string>
<string name="server_settings">Servers</string>
<string name="not_configured">Server not set – open Server settings</string>
<string name="setup_title">Connect to simply-dvb</string>
<string name="setup_hint">Enter the address of your simply-dvb server (tvheadend works too). Channels, logos and the programme guide appear as a source in the TV\'s own TV app.
Easiest: enter just the address and choose “Pair with QR code” – scan it with your phone and confirm in the panel, the token is set up for you. In the local network you can also connect without a login.</string>
<string name="server_address">Server address (IP or host name)</string>
<string name="htsp_port">HTSP port</string>
<string name="http_port">HTTP (stream) port</string>
<string name="username">User name</string>
<string name="password_token">Password / access token</string>
<string name="optional">optional</string>
<string name="connect_and_sync">Connect and load channels</string>
<string name="connecting">Connecting…</string>
<string name="syncing">Connected to %1$s. Loading channels, logos and the guide…</string>
<string name="sync_done">Done: %1$d channels. Open the TV app and choose the simply-tv source.</string>
<string name="error">Error: %1$s</string>
<string name="status_line">Channels: %1$d · programmes: %2$d · recordings: %3$d\nLast refresh: %4$s</string>
<string name="status_never">Not refreshed yet</string>
<string name="status_error">Last refresh failed: %1$s</string>
<string name="sync_started">Refreshing in the background…</string>
<string name="guide_hint">Up/down: channels · left/right: programmes · OK: details, recording, watch</string>
<string name="recording_default_title">Recording</string>
<string name="record">Record</string>
<string name="cancel_recording">Cancel recording</string>
<string name="recording_scheduled">Recording scheduled: %1$s</string>
<string name="recording_cancelled">Recording cancelled</string>
<string name="scheduled_badge">REC</string>
<string name="now">now</string>
<string name="play">Play</string>
<string name="delete">Delete</string>
<string name="stop">Stop</string>
<string name="close">Close</string>
<string name="delete_confirm">Delete the recording “%1$s”?</string>
<string name="no_recordings">No recordings yet.</string>
<string name="no_programmes">No programme data for this channel.</string>
<string name="loading">Loading…</string>
<string name="state_scheduled">scheduled</string>
<string name="state_recording">recording now</string>
<string name="state_completed">recorded</string>
<string name="state_failed">failed</string>
<string name="open_tv_failed">The TV app could not be opened – choose the simply-tv source in the TV\'s inputs.</string>
<string name="channels">Channels</string>
<string name="own_player">simply-tv player</string>
<string name="tv_app">TV app</string>
<string name="no_channels">No channels – refresh in the main screen.</string>
<string name="tuning">Tuning %1$s…</string>
<string name="no_signal">No picture: %1$s</string>
<string name="next">Next: %1$s</string>
<string name="pair_with_qr">Pair with QR code</string>
<string name="pair_qr">QR code for pairing</string>
<string name="pair_code_label">Code</string>
<string name="pair_need_host">Enter the server address first.</string>
<string name="pair_waiting">Scan the QR code with your phone and confirm in the simply-dvb panel (or open Access → Pair a TV and type the code). Waiting…</string>
<string name="pair_expired">The code expired – press “Pair with QR code” again.</string>
<string name="pair_done">Paired as “%1$s”. Loading channels, logos and the guide…</string>
<string name="t_signal">Signal</string>
<string name="t_bitrate">Mbit/s</string>
<string name="epg_hint">OK: record / watch · Back: channel list</string>
<string name="tuner_info">Tuner info in the player</string>
<string name="on">on</string>
<string name="off">off</string>
<string name="record_now">Record now</string>
<string name="watch">Watch</string>
<string name="recording_started">Recording: %1$s</string>
<string name="recording_stopped">Recording stopped</string>
<string name="audio_track">Audio: %1$s</string>
<string name="subtitles_on">Subtitles on</string>
<string name="subtitles_off">Subtitles off</string>
<string name="no_epg_now">No programme information – recording 2 hours</string>
<string name="player_keys">Player: up/down or CH+/CH- change channel · INFO or left arrow: on-screen info (now, before, later, picture and signal) · OK: channel list · right arrow or GUIDE: programme grid · RED/REC: record · GREEN: audio · YELLOW: subtitles · BLUE: tuner card · previous-channel button</string>
<string name="server_name">Name</string>
<string name="server_name_hint">e.g. Home, Summer house</string>
<string name="servers">Servers</string>
<string name="add_server">Add server</string>
<string name="use_in_player">Use in the player, guide and recordings</string>
<string name="tv_source_on">TV app: on</string>
<string name="tv_source_off">TV app: off</string>
<string name="active">active</string>
<string name="edit">Edit</string>
<string name="delete_server_confirm">Remove the server “%1$s” from simply-tv? Its channels disappear from the TV app.</string>
<string name="server_switched">Server: %1$s</string>
<string name="load_into_tv">Load channels into the TV app</string>
<string name="servers_hint">The active server is used by the player, guide and recordings (in the player: left arrow in the channel list). Servers with “TV app: on” supply channels to the TV\'s own TV app.</string>
<string name="choose_server">Choose a server</string>
<string name="switch_server_hint">Left arrow: other server</string>
<string name="t_signal_snr">Signal / SNR</string>
<string name="t_cpu">Server CPU</string>
<string name="t_stream_rate">Stream (received)</string>
<string name="epg_grid_hint">OK: details and recording · RED: record · GREEN: now · CH+/CH-: page · BACK: close</string>
<string name="tunneling">Tunnelled video playback</string>
<string name="autostart">Start the player with the TV</string>
<string name="autostart_needs_permission">needs permission</string>
<string name="autostart_permission">To open the player when the TV is switched on, Android requires the “Display over other apps” permission for simply-tv. Allow it on the next screen.\n\nIf the TV does not offer that screen, grant it once from a computer:\nadb shell appops set %1$s SYSTEM_ALERT_WINDOW allow</string>
<string name="open_settings">Open settings</string>
<string name="autostart_no_settings">This TV has no such settings screen – use the adb command</string>
<string name="live_tv_label">simply-tv Live</string>
<string name="osd_now">Now</string>
<string name="osd_before">Before</string>
<string name="osd_next">Next</string>
<string name="osd_later">Later</string>
<string name="osd_left">%d min left</string>
<string name="osd_signal">Signal</string>
<string name="settings">Settings</string>
<string name="set_sec_osd">On-screen display</string>
<string name="set_sec_player">Player</string>
<string name="set_sec_start">Start-up</string>
<string name="set_sec_servers">Servers</string>
<string name="set_sec_about">About</string>
<string name="set_osd_zap">Show on channel change</string>
<string name="set_osd_zap_desc">Channel, what is on now with progress, before and later. INFO or the left arrow always shows it.</string>
<string name="set_osd_seconds">Display time</string>
<string name="set_osd_seconds_desc">How long the OSD stays on screen after a channel change</string>
<string name="set_seconds">%d s</string>
<string name="set_osd_tech">Technical details</string>
<string name="set_osd_tech_desc">Resolution, audio, signal and the stream bitrate received by the TV</string>
<string name="set_osd_desc">Programme description</string>
<string name="set_osd_desc_desc">Two lines about the current programme</string>
<string name="set_tuner_card">Tuner card on channel change</string>
<string name="set_tuner_card_desc">Detailed card (top right): signal charts, server CPU, bitrate, errors. BLUE switches it during playback.</string>
<string name="set_tunneling_desc">The TV decodes and syncs the picture itself, like its own tuner. Switch off if a channel shows no picture.</string>
<string name="set_autostart_desc">Opens the player on the last channel when the TV boots or wakes up</string>
<string name="set_servers">Manage servers</string>
<string name="set_servers_desc">Add, switch or remove servers and choose which feed the TV app</string>
<string name="set_version">Version</string>
<string name="set_choose">Choose</string>
<string name="watch_title">Watch TV</string>
<string name="m_start">start</string>
<string name="guide_short">Programme guide</string>
<string name="sync_short">Sync</string>
<string name="keys_title">Remote in the player</string>
<string name="key_channel">channel</string>
<string name="key_list">channel list</string>
<string name="key_osd">info (OSD)</string>
<string name="key_guide">programme grid</string>
<string name="key_number">number</string>
<string name="key_record">record</string>
<string name="key_audio">audio</string>
<string name="key_subtitles">subtitles</string>
<string name="key_card">tuner card</string>
<string name="m_resume">Back to %1$s</string>
<string name="m_now_on">now: %1$s, %2$s</string>
<string name="m_no_epg">no programme information</string>
<string name="m_first">Open the player and pick a channel</string>
<string name="m_unreachable">Server unreachable: %1$s</string>
<string name="m_loading">Checking what is on…</string>
<string name="sub_guide">programme grid</string>
<string name="sub_recordings">saved: %1$d</string>
<string name="sub_tv_app">channels in the built-in TV app</string>
<string name="sub_settings">OSD, start-up, picture</string>
<string name="sub_no_server">no server</string>
<string name="status_compact">channels: %1$d · programmes: %2$d · recordings: %3$d · refreshed %4$s</string>
</resources>
+58
View File
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="@android:style/Theme.Material.NoActionBar">
<item name="android:windowBackground">@color/bg</item>
<item name="android:colorAccent">@color/accent</item>
<item name="android:colorPrimary">@color/bg</item>
<item name="android:textColor">@color/text</item>
</style>
<style name="Title">
<item name="android:textSize">30sp</item>
<item name="android:textColor">@color/text</item>
<item name="android:fontFamily">sans-serif-medium</item>
</style>
<style name="Muted">
<item name="android:textSize">15sp</item>
<item name="android:textColor">@color/muted</item>
</style>
<style name="TvButton" parent="@android:style/Widget.Material.Button.Borderless">
<item name="android:background">@drawable/button</item>
<item name="android:textColor">@color/text</item>
<item name="android:textSize">17sp</item>
<item name="android:textAllCaps">false</item>
<item name="android:paddingStart">22dp</item>
<item name="android:paddingEnd">22dp</item>
<item name="android:minHeight">52dp</item>
<item name="android:focusable">true</item>
</style>
<style name="OsdLabel">
<item name="android:textSize">11sp</item>
<item name="android:textColor">@color/muted</item>
<item name="android:letterSpacing">0.12</item>
<item name="android:textAllCaps">true</item>
<item name="android:fontFamily">sans-serif-medium</item>
</style>
<!-- compact buttons for the start screen menu -->
<style name="MenuButton" parent="TvButton">
<item name="android:textSize">14sp</item>
<item name="android:minHeight">40dp</item>
<item name="android:paddingStart">16dp</item>
<item name="android:paddingEnd">16dp</item>
<item name="android:paddingTop">6dp</item>
<item name="android:paddingBottom">6dp</item>
</style>
<style name="Field">
<item name="android:textSize">17sp</item>
<item name="android:textColor">@color/text</item>
<item name="android:textColorHint">@color/muted</item>
<item name="android:background">@drawable/field</item>
<item name="android:padding">12dp</item>
<item name="android:singleLine">true</item>
</style>
<style name="Label">
<item name="android:textSize">13sp</item>
<item name="android:textColor">@color/muted</item>
<item name="android:layout_marginTop">14dp</item>
<item name="android:layout_marginBottom">4dp</item>
</style>
</resources>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<tv-input xmlns:android="http://schemas.android.com/apk/res/android"
android:canRecord="true"
android:setupActivity="io.simplydvb.tv.ui.ServersActivity"
android:tunerCount="2" />
@@ -0,0 +1,69 @@
package io.simplydvb.tv.htsp
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
class HtspTest {
@Test
fun messageRoundTrip() {
val m = HtsMsg.method("test")
.put("zero", 0L).put("small", 5L).put("big", 1_700_000_000_123L).put("u8", 200L).put("neg", -42L)
.put("s", "zażółć").put("b", byteArrayOf(1, 2, 3))
.put("l", listOf(1L, "x", HtsMsg().put("k", 7L)))
.put("m", HtsMsg().put("inner", "v"))
val wire = m.encode()
val len = ((wire[0].toInt() and 0xff) shl 24) or ((wire[1].toInt() and 0xff) shl 16) or
((wire[2].toInt() and 0xff) shl 8) or (wire[3].toInt() and 0xff)
assertEquals(wire.size - 4, len)
val d = HtsMsg.decode(wire, 4, len)
assertEquals("test", d.method)
assertEquals(0L, d.long("zero"))
assertEquals(5L, d.long("small"))
assertEquals(1_700_000_000_123L, d.long("big"))
assertEquals(200L, d.long("u8"))
assertEquals(-42L, d.long("neg"))
assertEquals("zażółć", d.str("s"))
assertEquals(3, d.bin("b")!!.size)
assertEquals(3, d.list("l").size)
assertEquals(7L, (d.list("l")[2] as HtsMsg).long("k"))
assertEquals("v", d.map("m")!!.str("inner"))
}
/** Against a running server: SIMPLYTV_TEST_HOST=127.0.0.1 SIMPLYTV_TEST_PORT=9982 */
@Test
fun liveServer() {
val host = System.getenv("SIMPLYTV_TEST_HOST")
assumeTrue(host != null)
val port = System.getenv("SIMPLYTV_TEST_PORT")?.toInt() ?: 9982
HtspClient(host!!, port, System.getenv("SIMPLYTV_TEST_USER") ?: "", System.getenv("SIMPLYTV_TEST_PASS") ?: "").use { c ->
c.connect()
println("server: ${c.serverName} ${c.serverVersion} htsp ${c.htspVersion}")
var channels = 0
var events = 0
var dvr = 0
var firstChannel = 0L
val done = CountDownLatch(1)
c.onAsync = { m ->
when (m.method) {
"channelAdd" -> { channels++; if (firstChannel == 0L) firstChannel = m.long("channelId") ?: 0 }
"eventAdd" -> events++
"dvrEntryAdd" -> dvr++
"initialSyncCompleted" -> done.countDown()
}
}
c.request(HtsMsg.method("enableAsyncMetadata").put("epg", 1L))
assertTrue(done.await(60, TimeUnit.SECONDS))
println("channels=$channels events=$events dvr=$dvr")
assertTrue(channels > 0)
val t = c.request(HtsMsg.method("getTicket").put("channelId", firstChannel))
println("ticket: ${t.str("path")} ${t.str("ticket")}")
assertTrue(t.str("path")!!.startsWith("/stream/channelid/"))
val ev = c.request(HtsMsg.method("getEvents").put("channelId", firstChannel).put("numFollowing", 3L))
println("events of $firstChannel: ${ev.maps("events").map { it.str("title") }}")
}
}
}