feat: Playtube Jam – gemeinsam hoeren, synchron auf dem eigenen Handy (1.4.0)

Jam starten (laufender Song wird der erste) oder per Code/Link beitreten, Jam-Ansicht
im Stil von "PC steuern": Teilnehmer, Warteschlange, Einladen per Teilen/Kopieren,
Host-Rechte. Die YouTube-Music-WebView gleicht sich mit dem Jam ab; Benachrichtigung
und Kopfhoerertasten steuern im Jam den Jam. App-Links jam.fojadrachi.de,
playtube://jam/<CODE> und "Teilen" von YouTube-Links. OkHttp fuer den WebSocket.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-08 01:36:55 +01:00
co-authored by Claude Opus 5.5
parent 29d38ef2e6
commit 3b3b746329
19 changed files with 1978 additions and 14 deletions
@@ -0,0 +1,244 @@
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.5
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<Member>,
val current: Item?,
val queue: List<Item>,
val history: List<Item>,
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) }
}
/** 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<Item> =
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<Pair<Double, Double>>()
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)
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()
}
/** Was der eigene Player tun soll, damit er zum Jam passt. */
fun decide(want: Target?, local: Local, tolerance: Double = TOLERANCE_S): List<Step> {
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>(Step.Load(want.videoId, max(0.0, want.pos)))
if (want.paused || want.pos < 0) steps.add(Step.Pause)
return steps
}
val steps = mutableListOf<Step>()
if (want.pos < 0) {
if (!local.paused) steps.add(Step.Pause)
if (local.pos > 0.5) steps.add(Step.Seek(0.0))
return steps
}
if (abs(local.pos - want.pos) > tolerance && !(nearEnd && local.pos > want.pos)) steps.add(Step.Seek(want.pos))
if (want.paused && !local.paused) steps.add(Step.Pause)
if (!want.paused && local.paused) steps.add(Step.Play)
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). */
const val PROBE = """
(function () {
var video = document.querySelector('video');
var id = null;
try { if (location.pathname === '/watch') { id = new URL(location.href).searchParams.get('v'); } } catch (e) { id = null; }
var ad = !!document.querySelector('.ad-showing, .ad-interrupting');
var error = !!document.querySelector('.ytp-error, yt-playability-error-supported-renderers:not([hidden]) .reason');
return JSON.stringify({
id: id,
t: video ? video.currentTime : 0,
d: (video && isFinite(video.duration)) ? video.duration : 0,
paused: video ? video.paused : true,
ended: video ? video.ended : false,
ad: ad,
error: error
});
})();
"""
fun watchUrl(videoId: String): String = "https://music.youtube.com/watch?v=$videoId"
}