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

@@ -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)
}
}