package io.simplydvb.tv.htsp import java.io.ByteArrayOutputStream import java.nio.charset.StandardCharsets /** * HTSMSG – the binary message format of tvheadend's HTSP protocol. * * Every field: type (1 byte), name length (1), data length (4, big endian), name, data. * Types: 1 = map, 2 = signed 64-bit integer (little endian, minimal bytes), 3 = string, * 4 = binary, 5 = list (fields without names). A message on the wire is a 4-byte * big-endian length followed by the fields of the root map. */ class HtsMsg(val fields: LinkedHashMap = LinkedHashMap()) { operator fun set(name: String, value: Any) { fields[name] = value } fun put(name: String, value: Any): HtsMsg { fields[name] = value return this } val method: String? get() = str("method") fun str(name: String): String? = when (val v = fields[name]) { is String -> v is Long -> v.toString() else -> null } fun long(name: String): Long? = when (val v = fields[name]) { is Long -> v is String -> v.toLongOrNull() else -> null } fun int(name: String): Int? = long(name)?.toInt() fun bin(name: String): ByteArray? = fields[name] as? ByteArray fun map(name: String): HtsMsg? = fields[name] as? HtsMsg @Suppress("UNCHECKED_CAST") fun list(name: String): List = (fields[name] as? List) ?: emptyList() fun maps(name: String): List = list(name).filterIsInstance() fun has(name: String) = fields.containsKey(name) override fun toString(): String = fields.entries.joinToString(", ", "{", "}") { (k, v) -> "$k=" + when (v) { is ByteArray -> "<${v.size} bytes>" is String -> if (v.length > 60) "\"${v.take(60)}…\"" else "\"$v\"" else -> v.toString() } } /** Wire form: length prefix + body. */ fun encode(): ByteArray { val body = encodeFields(fields.entries.map { it.key to it.value }) val out = ByteArrayOutputStream(body.size + 4) writeU32(out, body.size.toLong()) out.write(body) return out.toByteArray() } companion object { private const val MAP = 1 private const val S64 = 2 private const val STR = 3 private const val BIN = 4 private const val LIST = 5 fun method(name: String) = HtsMsg().put("method", name) private fun writeU32(out: ByteArrayOutputStream, v: Long) { out.write(((v shr 24) and 0xff).toInt()) out.write(((v shr 16) and 0xff).toInt()) out.write(((v shr 8) and 0xff).toInt()) out.write((v and 0xff).toInt()) } private fun s64(v: Long): ByteArray { if (v == 0L) return ByteArray(0) val bytes = ArrayList(8) var x = v // little endian, minimal length (negative numbers keep all 8 bytes) for (i in 0 until 8) { bytes.add((x and 0xff).toByte()) x = x ushr 8 if (x == 0L && v > 0) break } return bytes.toByteArray() } private fun encodeFields(entries: List>): ByteArray { val out = ByteArrayOutputStream() for ((name, value) in entries) { val (type, data) = when (value) { is HtsMsg -> MAP to encodeFields(value.fields.entries.map { it.key to it.value }) is Long -> S64 to s64(value) is Int -> S64 to s64(value.toLong()) is Boolean -> S64 to s64(if (value) 1 else 0) is String -> STR to value.toByteArray(StandardCharsets.UTF_8) is ByteArray -> BIN to value is List<*> -> LIST to encodeFields(value.filterNotNull().map { null to it }) else -> STR to value.toString().toByteArray(StandardCharsets.UTF_8) } val n = name?.toByteArray(StandardCharsets.UTF_8) ?: ByteArray(0) out.write(type) out.write(n.size) writeU32(out, data.size.toLong()) out.write(n) out.write(data) } return out.toByteArray() } /** Decodes a message body (without the 4-byte length). */ fun decode(buf: ByteArray, off: Int = 0, len: Int = buf.size): HtsMsg { val m = HtsMsg() decodeInto(buf, off, len) { name, v -> m.fields[name ?: ""] = v } return m } private fun decodeList(buf: ByteArray, off: Int, len: Int): List { val l = ArrayList() decodeInto(buf, off, len) { _, v -> l.add(v) } return l } private fun decodeInto(buf: ByteArray, off: Int, len: Int, sink: (String?, Any) -> Unit) { var p = off val end = off + len while (p + 6 <= end) { val type = buf[p].toInt() and 0xff val nlen = buf[p + 1].toInt() and 0xff val dlen = ((buf[p + 2].toLong() and 0xff) shl 24) or ((buf[p + 3].toLong() and 0xff) shl 16) or ((buf[p + 4].toLong() and 0xff) shl 8) or (buf[p + 5].toLong() and 0xff) p += 6 if (p + nlen + dlen > end) break val name = if (nlen > 0) String(buf, p, nlen, StandardCharsets.UTF_8) else null p += nlen val d = dlen.toInt() val v: Any = when (type) { MAP -> decode(buf, p, d) S64 -> { var x = 0L for (i in 0 until minOf(d, 8)) x = x or ((buf[p + i].toLong() and 0xff) shl (8 * i)) // tvheadend writes positive numbers with the minimal number of bytes // (no sign extension) and negative ones with all 8 bytes x } STR -> String(buf, p, d, StandardCharsets.UTF_8) BIN -> buf.copyOfRange(p, p + d) LIST -> decodeList(buf, p, d) else -> buf.copyOfRange(p, p + d) } sink(name, v) p += d } } } }