package de.fojadrachi.playtube import org.json.JSONArray import org.json.JSONObject import kotlin.math.abs import kotlin.math.max /** * Playtube Jam: Protokoll und reine Sync-Logik (ohne Android-Klassen, mit JUnit getestet). * Dieselben Regeln gelten in Playtube am PC (src/jam.rs) und im Web-Client (public/sync.js). * * Wiedergabe-Modell des Servers: playback = { paused, position, ref }. Position zur Serverzeit T: * paused ? position : position + (T - ref) / 1000. Negativ heisst "startet gleich". */ object JamSync { const val TOLERANCE_S = 1.0 /** Beim Spulen etwas vorhalten: bis das Video an der neuen Stelle spielt, vergeht Zeit. */ const val SEEK_LEAD_S = 0.2 private const val NUDGE_START_S = 0.08 private const val NUDGE_STOP_S = 0.03 private const val NUDGE_GAIN = 0.25 private const val NUDGE_MAX = 0.08 /** * Wiedergabetempo, das eine kleine Abweichung [drift] (eigene minus Jam-Position, s) ausgleicht - * unhoerbar, die Tonhoehe bleibt. Einmal angefangen ([current] != 1) bis fast 0 ausgleichen. */ fun nudgeRate(drift: Double, current: Double): Double { val threshold = if (abs(current - 1.0) > 0.001) NUDGE_STOP_S else NUDGE_START_S if (!drift.isFinite() || abs(drift) < threshold) return 1.0 val rate = (1.0 - NUDGE_GAIN * drift).coerceIn(1.0 - NUDGE_MAX, 1.0 + NUDGE_MAX) return Math.round(rate * 1000.0) / 1000.0 } private const val CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" private val VIDEO_ID = Regex("^[A-Za-z0-9_-]{11}$") data class Item( val id: String, val videoId: String, val title: String, val artist: String, val thumb: String, val dur: Double?, val by: String, val byName: String, ) data class Member( val id: String, val name: String, val client: String, val online: Boolean, val host: Boolean, val cantPlay: Boolean, ) data class Playback(val paused: Boolean, val position: Double, val ref: Double) data class State( val code: String, val you: String, val hostId: String, val allControl: Boolean, val canControl: Boolean, val search: Boolean, val members: List, val current: Item?, val queue: List, val history: List, val playback: Playback, val serverNow: Double, ) { val isHost: Boolean get() = you == hostId } // ------------------------------------------------------------------ Codes und Links /** "abc-234", "ABC 234" oder Einladungslink -> "ABC234", sonst null. */ fun normalizeCode(input: String?): String? { if (input == null) return null var text = input.trim().substringBefore('?').substringBefore('#').trimEnd('/') if (text.contains('/')) text = text.substringAfterLast('/') val code = text.filter { !it.isWhitespace() && it != '-' }.uppercase() return if (code.length == 6 && code.all { it in CODE_ALPHABET }) code else null } /** Video-ID aus ID oder YouTube-/YouTube-Music-Link. */ fun parseVideoId(input: String?): String? { val text = input?.trim() ?: return null if (VIDEO_ID.matches(text)) return text val rest = text.substringAfter("://", text) val host = rest.substringBefore('/').lowercase().removePrefix("www.").removePrefix("m.").removePrefix("music.") val path = rest.substringAfter('/', "").substringBefore('#') val pathOnly = path.substringBefore('?') val query = path.substringAfter('?', "") val id = when (host) { "youtu.be" -> pathOnly.substringBefore('/') "youtube.com", "youtube-nocookie.com" -> query.split('&').firstOrNull { it.startsWith("v=") }?.removePrefix("v=") ?: pathOnly.split('/').let { parts -> if (parts.size >= 2 && parts[0] in setOf("shorts", "embed", "live", "v")) parts[1] else null } else -> null } return id?.takeIf { VIDEO_ID.matches(it) } } private val PLAYLIST_ID = Regex("^(PL|OLAK5uy_|RD|LL|UU|FL|OL|LM)[A-Za-z0-9_-]{0,80}$") /** Playlist-/Album-ID aus einer ID oder einem Link mit `list=`, sonst null. */ fun parsePlaylistId(input: String?): String? { val text = input?.trim() ?: return null val raw = if (text.contains("youtube.com") || text.contains("youtu.be") || text.contains("://")) { val rest = text.substringAfter("://", text) val host = rest.substringBefore('/').lowercase().removePrefix("www.").removePrefix("m.").removePrefix("music.") if (host != "youtube.com" && host != "youtu.be") return null rest.substringAfter('?', "").substringBefore('#').split('&') .firstOrNull { it.startsWith("list=") }?.removePrefix("list=") ?: return null } else text val id = raw.removePrefix("VL") return id.takeIf { PLAYLIST_ID.matches(it) } } /** Playlist-Link (ohne einzelnes Video) aus einem geteilten Text. */ fun playlistIdFromSharedText(text: String?): String? = text?.split(Regex("\\s+"))?.firstNotNullOfOrNull { word -> if (parseVideoId(word) == null) parsePlaylistId(word) else null } /** Sucht in einem geteilten Text (z. B. aus der YouTube-App) den ersten YouTube-Link. */ fun videoIdFromSharedText(text: String?): String? = text?.split(Regex("\\s+"))?.firstNotNullOfOrNull { parseVideoId(it) } fun prettyCode(code: String): String = if (code.length == 6) code.substring(0, 3) + " " + code.substring(3) else code fun formatTime(seconds: Double): String { val total = if (seconds.isFinite() && seconds > 0) seconds.toLong() else 0L val h = total / 3600 val m = (total / 60) % 60 val s = total % 60 return if (h > 0) String.format("%d:%02d:%02d", h, m, s) else String.format("%d:%02d", m, s) } // ------------------------------------------------------------------ Zustand lesen fun parseState(json: JSONObject): State { fun item(o: JSONObject?): Item? = o?.let { Item( id = it.optString("id"), videoId = it.optString("videoId"), title = it.optString("title"), artist = it.optString("artist"), thumb = it.optString("thumb"), dur = if (it.isNull("dur") || !it.has("dur")) null else it.optDouble("dur").takeIf { d -> d.isFinite() }, by = it.optString("by"), byName = it.optString("byName"), ) } fun items(a: JSONArray?): List = if (a == null) emptyList() else (0 until a.length()).mapNotNull { item(a.optJSONObject(it)) } val members = json.optJSONArray("members")?.let { a -> (0 until a.length()).mapNotNull { a.optJSONObject(it) }.map { Member( id = it.optString("id"), name = it.optString("name"), client = it.optString("client"), online = it.optBoolean("online"), host = it.optBoolean("host"), cantPlay = it.optBoolean("cantPlay"), ) } } ?: emptyList() val pb = json.optJSONObject("playback") return State( code = json.optString("code"), you = json.optString("you"), hostId = json.optString("hostId"), allControl = json.optBoolean("allControl"), canControl = json.optBoolean("canControl"), search = json.optJSONObject("features")?.optBoolean("search") ?: false, members = members, current = item(json.optJSONObject("current")), queue = items(json.optJSONArray("queue")), history = items(json.optJSONArray("history")), playback = Playback( paused = pb?.optBoolean("paused", true) ?: true, position = pb?.optDouble("position", 0.0) ?: 0.0, ref = pb?.optDouble("ref", 0.0) ?: 0.0, ), serverNow = json.optDouble("serverNow", 0.0), ) } // ------------------------------------------------------------------ Zeit und Abgleich /** Zeitabgleich ueber ping/pong: die Messung mit der kuerzesten Laufzeit zaehlt. */ class Clock { private val samples = ArrayList>() var offset = 0.0 private set fun add(c: Double, s: Double, r: Double) { val rtt = r - c if (rtt < 0 || rtt > 30_000) return samples.add(rtt to s - (c + rtt / 2)) if (samples.size > 10) samples.removeAt(0) offset = samples.minByOrNull { it.first }!!.second } fun hint(serverNow: Double, localNow: Double) { if (samples.isEmpty()) offset = serverNow - localNow } fun serverNow(localNow: Double): Double = localNow + offset } fun positionAt(playback: Playback, serverNow: Double): Double = if (playback.paused) playback.position else playback.position + (serverNow - playback.ref) / 1000.0 data class Target(val videoId: String, val itemId: String, val pos: Double, val paused: Boolean, val dur: Double?) fun target(state: State?, serverNow: Double): Target? { val item = state?.current ?: return null return Target(item.videoId, item.id, positionAt(state.playback, serverNow), state.playback.paused, item.dur) } data class Local(val videoId: String?, val pos: Double, val paused: Boolean, val rate: Double = 1.0) sealed class Step { data class Load(val videoId: String, val pos: Double) : Step() data class Seek(val pos: Double) : Step() data object Play : Step() data object Pause : Step() data class Rate(val rate: Double) : Step() } /** Was der eigene Player tun soll, damit er zum Jam passt. */ fun decide(want: Target?, local: Local, tolerance: Double = TOLERANCE_S): List { if (want == null) return if (local.videoId != null && !local.paused) listOf(Step.Pause) else emptyList() val nearEnd = want.dur != null && want.pos > want.dur - 3 if (local.videoId != want.videoId) { // Am Titelende springt YouTube Music von selbst weiter - nicht den alten Titel neu laden. if (nearEnd) return if (local.paused) emptyList() else listOf(Step.Pause) val steps = mutableListOf(Step.Load(want.videoId, max(0.0, want.pos))) if (want.paused || want.pos < 0) steps.add(Step.Pause) return steps } val steps = mutableListOf() if (want.pos < 0) { if (!local.paused) steps.add(Step.Pause) if (local.pos > 0.5) steps.add(Step.Seek(0.0)) return steps } val drift = local.pos - want.pos val seek = abs(drift) > tolerance && !(nearEnd && local.pos > want.pos) if (seek) steps.add(Step.Seek(if (want.paused) want.pos else want.pos + SEEK_LEAD_S)) if (want.paused && !local.paused) steps.add(Step.Pause) if (!want.paused && local.paused) steps.add(Step.Play) // Feinabgleich ueber das Tempo, solange beide normal laufen. val desired = if (!seek && !want.paused && !local.paused && !nearEnd) nudgeRate(drift, local.rate) else 1.0 if (abs(desired - local.rate) > 0.004) steps.add(Step.Rate(desired)) return steps } fun reachedEnd(local: Local, duration: Double, ended: Boolean): Boolean = ended || (duration > 0 && local.pos >= duration - 0.6) /** * JavaScript: Stand des Players auf music.youtube.com (wie jam_probe.js am PC). Video-ID, Zeit und * Laenge kommen von der Player-API - so darf man in YouTube Music weiter stoebern, und von * mehreren