StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Add tests for raw transport stream backpressure and split HLS timestamp fixture server
David Nashash2394d0cfcb96
diff --git a/app/src/androidTest/java/com/streamvault/app/tv/TvInputPlaybackRuntimeTest.kt b/app/src/androidTest/java/com/streamvault/app/tv/TvInputPlaybackRuntimeTest.ktnew file mode 100644index 00000000..e8dc85db--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/tv/TvInputPlaybackRuntimeTest.kt@@ -0,0 +1,430 @@+package com.streamvault.app.tv++import android.content.ContentValues+import android.media.tv.TvContract+import android.media.tv.TvView+import android.net.Uri+import android.os.SystemClock+import android.util.Log+import android.view.View+import androidx.test.core.app.ActivityScenario+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.streamvault.app.MainActivity+import com.streamvault.data.local.StreamVaultDatabase+import com.streamvault.data.local.entity.ChannelEntity+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.domain.model.ProviderType+import dagger.hilt.internal.GeneratedComponentManager+import javax.inject.Provider+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.flow.first+import androidx.datastore.core.DataStore+import androidx.datastore.preferences.core.Preferences+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.core.intPreferencesKey+import org.json.JSONArray+import org.json.JSONObject+import org.junit.Assume.assumeTrue+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import java.util.concurrent.atomic.AtomicBoolean+import java.util.concurrent.atomic.AtomicInteger++/** Explicitly opted-in loopback fixtures, tuned through the real Android TV framework. */+@RunWith(AndroidJUnit4::class)+class TvInputPlaybackRuntimeTest {+ @Test+ fun fixtureCleanupIsComplete() {+ assumeTrue(InstrumentationRegistry.getArguments().getString("tvInputCleanupAudit") == "true")+ val app = ApplicationProvider.getApplicationContext<android.app.Application>()+ val component = (app as GeneratedComponentManager<*>).generatedComponent()+ val db = (component.javaClass.getDeclaredField("provideDatabaseProvider").apply {+ isAccessible = true+ }.get(component) as Provider<*>).get() as StreamVaultDatabase+ val counts = JSONObject()+ for ((name, query) in listOf(+ "providers" to "SELECT COUNT(*) FROM providers WHERE name LIKE 'TIF fixture %'",+ "configs" to "SELECT COUNT(*) FROM provider_configs WHERE identity_key LIKE 'tif-fixture-%'",+ "channels" to "SELECT COUNT(*) FROM channels WHERE name LIKE 'TIF fixture %'"+ )) {+ db.openHelper.readableDatabase.query(query).use { cursor ->+ check(cursor.moveToFirst())+ counts.put(name, cursor.getInt(0))+ }+ }+ app.contentResolver.query(TvContract.buildChannelsUriForInput(+ "${app.packageName}/com.streamvault.app.tvinput.StreamVaultTvInputService"),+ arrayOf(TvContract.Channels.COLUMN_DISPLAY_NAME), null, null, null)?.use { cursor ->+ var owned = 0+ while (cursor.moveToNext()) if (cursor.getString(0)?.startsWith("TIF fixture ") == true) owned+++ counts.put("frameworkChannels", owned)+ }+ app.filesDir.resolve("tif-cleanup-audit.json").writeText(counts.toString(2))+ for (key in listOf("providers", "configs", "channels", "frameworkChannels")) {+ assertTrue("Fixture rows remain: $counts", counts.getInt(key) == 0)+ }+ }++ @Test+ fun tuneFixtureChannels() = runBlocking {+ val args = InstrumentationRegistry.getArguments()+ assumeTrue(args.getString("tvInputFixture") == "true")+ val runId = requireNotNull(args.getString("runId"))+ require(runId.matches(Regex("[A-Za-z0-9_-]{1,40}")))+ val urls = requireNotNull(args.getString("fixtureUrls")).split(',')+ urls.forEach { require(Uri.parse(it).host in setOf("127.0.0.1", "localhost")) }+ val duration = args.getString("durationSeconds")?.toLong() ?: 130L+ require(duration in 10L..180L)+ val app = ApplicationProvider.getApplicationContext<android.app.Application>()+ val component = (app as GeneratedComponentManager<*>).generatedComponent()+ val db = (component.javaClass.getDeclaredField("provideDatabaseProvider").apply {+ isAccessible = true+ }.get(component) as Provider<*>).get() as StreamVaultDatabase+ val inputId = "${app.packageName}/com.streamvault.app.tvinput.StreamVaultTvInputService"+ val preferences = (component.javaClass.getDeclaredField("preferencesRepositoryProvider").apply {+ isAccessible = true+ }.get(component) as Provider<*>).get() as com.streamvault.data.preferences.PreferencesRepository+ @Suppress("UNCHECKED_CAST")+ val preferenceStore = preferences.javaClass.getDeclaredMethod("getPreferencesDataStore").apply {+ isAccessible = true+ }.invoke(preferences) as DataStore<Preferences>+ val originalPreferences = preferenceStore.data.first()+ val originalAutomaticConfiguration = preferences.automaticSyncConfiguration.first()+ val providerId = db.providerDao().insert(ProviderEntity(+ name = "TIF fixture $runId", type = ProviderType.M3U, isActive = false+ ))+ val previousAutomaticOverride = originalAutomaticConfiguration.providers[providerId]+ val rows = mutableListOf<Uri>()+ val events = JSONArray()+ val available = AtomicBoolean(false)+ val terminal = AtomicBoolean(false)+ val availableCount = AtomicInteger(0)+ val expectTerminal = args.getString("expectTerminal") == "true"+ val expectEofRecovery = args.getString("expectEofRecovery") == "true"+ val expectEofTerminal = args.getString("expectEofTerminal") == "true"+ val observeOutage = args.getString("observeOutage") == "true"+ val verifyOwnership = args.getString("tvInputVerifyOwnership") == "true"+ val surfaceCycle = args.getString("tvInputSurfaceCycle") == "true"+ val surfaceCallbackDelayMs = args.getString("tvInputSurfaceCallbackDelayMs")?.toLong() ?: 0L+ require(surfaceCallbackDelayMs in 0L..250L)+ val releaseWaitMs = args.getString("tvInputReleaseWaitMs")?.toLong() ?: 0L+ require(releaseWaitMs in 0L..5_000L)+ var currentIndex = -1+ fun event(name: String, detail: String = "") {+ val row = JSONObject().put("elapsedMs", SystemClock.elapsedRealtime())+ .put("channelIndex", currentIndex).put("event", name).put("detail", detail)+ synchronized(events) { events.put(row) }+ Log.i("TvInputFixture", row.toString())+ }+ var scenario: ActivityScenario<MainActivity>? = null+ lateinit var view: TvView+ var viewInitialized = false+ var workerProbe: com.streamvault.app.ui.PlaybackWorkerAdmissionProbe? = null+ var catalogProbe: com.streamvault.app.ui.PlaybackInflightCatalogProbe? = null+ var guideProbe: com.streamvault.app.ui.PlaybackInflightEpgProbe? = null+ var indexProbe: com.streamvault.app.ui.PlaybackIndexWorkProbe? = null+ var playbackProviderId = providerId+ // The normal catalog publisher removes non-active provider channels. Hold+ // its existing serialization lock while these temporary framework rows exist.+ val catalogMutex = com.streamvault.app.tvinput.TvInputChannelSyncManager::class.java+ .getDeclaredField("syncMutex").apply { isAccessible = true }.get(null)+ as kotlinx.coroutines.sync.Mutex+ catalogMutex.lock()+ try {+ // The fixture config contains a playback URL, not a catalog playlist. Keep app-wide+ // automatic provider scans from importing it while this disposable provider exists.+ preferences.setAutomaticSyncSettings(providerId,+ com.streamvault.domain.sync.AutomaticSyncSettings(enabled = false, live = false,+ movies = false, series = false, epg = false))+ event("automatic-sync-isolated")+ db.providerSnapshotDao().commitConfiguration(com.streamvault.data.local.entity.ProviderConfigEntity(+ providerId = providerId, type = ProviderType.M3U, schemaVersion = 1,+ configurationGeneration = 1, identityKey = "tif-fixture-$runId",+ encryptedConfigJson = com.google.gson.Gson().toJson(+ com.streamvault.domain.model.M3uConfig(playlistUrl = urls.first())),+ updatedAt = System.currentTimeMillis()+ ))+ urls.forEachIndexed { index, url ->+ val id = db.channelDao().insert(ChannelEntity(name = "TIF fixture $index",+ providerId = providerId, streamId = index + 1L, streamUrl = url))+ rows += requireNotNull(app.contentResolver.insert(TvContract.Channels.CONTENT_URI,+ ContentValues().apply {+ put(TvContract.Channels.COLUMN_INPUT_ID, inputId)+ put(TvContract.Channels.COLUMN_TYPE, TvContract.Channels.TYPE_OTHER)+ put(TvContract.Channels.COLUMN_DISPLAY_NUMBER, "990${index}")+ put(TvContract.Channels.COLUMN_DISPLAY_NAME, "TIF fixture $index")+ put(TvContract.Channels.COLUMN_INTERNAL_PROVIDER_DATA, "$providerId:$id")+ }))+ }+ scenario = ActivityScenario.launch(MainActivity::class.java)+ scenario.onActivity { activity ->+ view = TvView(activity)+ viewInitialized = true+ view.setCallback(object : TvView.TvInputCallback() {+ override fun onVideoAvailable(inputId: String) {+ availableCount.incrementAndGet()+ available.set(true); event("available")+ }+ override fun onVideoUnavailable(inputId: String, reason: Int) {+ available.set(false); event("unavailable", reason.toString())+ if (reason == android.media.tv.TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN) terminal.set(true)+ }+ override fun onConnectionFailed(inputId: String) { event("connection-failed") }+ override fun onDisconnected(inputId: String) { event("disconnected") }+ override fun onChannelRetuned(inputId: String, channelUri: Uri) { event("retuned", channelUri.toString()) }+ })+ // TvView secures its SurfaceView by default. Only these explicitly+ // opted-in, unencrypted loopback fixtures permit screenshot capture.+ (view.getChildAt(0) as android.view.SurfaceView).setSecure(false)+ activity.setContentView(view)+ }+ // Admit and checkpoint actual imports while idle, before the TV tune+ // acquires playback ownership. Each probe owns only its fixture jobs.+ catalogProbe = com.streamvault.app.ui.PlaybackInflightCatalogProbe.start(app, args, runId) { row ->+ event("catalog-probe", row.toString())+ }+ guideProbe = com.streamvault.app.ui.PlaybackInflightEpgProbe.start(app, component, args, runId) { row ->+ event("guide-probe", row.toString())+ }+ indexProbe = com.streamvault.app.ui.PlaybackIndexWorkProbe.start(app, args, runId) { row ->+ event("index-probe", row.toString())+ }+ rows.forEachIndexed { index, uri ->+ indexProbe?.navigation(urls[index])?.let { navigation ->+ playbackProviderId = checkNotNull(navigation.providerId)+ check(navigation.internalId > 0L)+ check(app.contentResolver.update(uri, ContentValues().apply {+ put(TvContract.Channels.COLUMN_INTERNAL_PROVIDER_DATA,+ "$playbackProviderId:${navigation.internalId}")+ }, null, null) == 1)+ event("framework-provider-linked", JSONObject().put("providerId",playbackProviderId)+ .put("internalId",navigation.internalId).toString())+ }+ scenario.onActivity {+ currentIndex = index+ available.set(false)+ terminal.set(false)+ availableCount.set(0)+ event("tune")+ view.tune(inputId, uri)+ }+ val deadline = SystemClock.elapsedRealtime() + 150_000L+ while (!available.get() && !terminal.get() && SystemClock.elapsedRealtime() < deadline) Thread.sleep(100)+ if (expectTerminal) {+ assertTrue("Expected bounded terminal startup failure", terminal.get() && !available.get())+ if (verifyOwnership) assertTrue("Terminal TV input retained ownership",+ !com.streamvault.domain.sync.AutomaticSyncActivity.isProviderPlaybackActive(playbackProviderId))+ event("terminal-observed")+ Thread.sleep(5_000L)+ return@forEachIndexed+ }+ assertTrue("TV input never reported video available for fixture $index", available.get())+ if (verifyOwnership) {+ assertTrue("TV input missing provider ownership",+ com.streamvault.domain.sync.AutomaticSyncActivity.isProviderPlaybackActive(playbackProviderId))+ event("ownership-context", JSONObject().put("providerId", playbackProviderId)+ .put("global", com.streamvault.domain.sync.AutomaticSyncActivity.hasPlayback)+ .put("provider", true).toString())+ }+ if (expectEofRecovery) {+ event("initial-video-available")+ val recoveryDeadline = SystemClock.elapsedRealtime() + 90_000L+ while (availableCount.get() < 2 && !terminal.get() && SystemClock.elapsedRealtime() < recoveryDeadline) Thread.sleep(100)+ assertTrue("Expected one EOF recovery before steady capture", availableCount.get() == 2 && available.get())+ event("eof-recovery-observed")+ }+ if (surfaceCycle) {+ val recovered = cycleTvViewSurface(+ scenario = checkNotNull(scenario),+ view = view,+ available = available,+ terminal = terminal,+ availableCount = availableCount,+ providerId = playbackProviderId,+ checkOwnership = verifyOwnership,+ callbackDelayMs = surfaceCallbackDelayMs,+ emit = ::event+ )+ assertTrue("TV input did not recover after the diagnostic surface cycle", recovered)+ }+ catalogProbe?.playbackReady()+ guideProbe?.playbackReady()+ indexProbe?.verifyPlaybackContext(playbackProviderId, "TV_INPUT")+ indexProbe?.playbackReady()+ event("capture-begin")+ workerProbe = com.streamvault.app.ui.PlaybackWorkerAdmissionProbe.start(app, args, runId) { row ->+ event("worker-probe", row.toString())+ }+ val end = SystemClock.elapsedRealtime() + duration * 1_000L+ while (SystemClock.elapsedRealtime() < end) Thread.sleep(100)+ if (expectEofTerminal) {+ assertTrue("Repeated EOF must become unavailable after exactly one recovery",+ terminal.get() && !available.get() && availableCount.get() == 2)+ event("eof-terminal-observed")+ } else if (observeOutage) {+ assertTrue("Expected under-rate source to remain unavailable at observation end", !available.get())+ event("outage-observed", "terminal=${terminal.get()} availableCount=${availableCount.get()}")+ } else {+ assertTrue("TV input stopped reporting available for fixture $index", available.get())+ }+ event("capture-end")+ workerProbe?.finishWhilePlaying()+ catalogProbe?.finishWhilePlaying()+ guideProbe?.finishWhilePlaying()+ indexProbe?.finishWhilePlaying()+ }+ } finally {+ try {+ event("tvview-reset-start")+ scenario?.onActivity { if (viewInitialized) view.reset() }+ event("tvview-reset-return")+ if (releaseWaitMs > 0L) {+ event("release-wait-start", "timeoutMs=$releaseWaitMs")+ val releaseStatus = waitForPlaybackRelease(playbackProviderId, releaseWaitMs)+ event("release-wait-finished", releaseStatus)+ }+ event("scenario-close-start")+ scenario?.close()+ event("scenario-close-return")+ if (verifyOwnership) {+ val releaseDeadline = SystemClock.elapsedRealtime() + 10_000L+ while (com.streamvault.domain.sync.AutomaticSyncActivity.isProviderPlaybackActive(playbackProviderId) &&+ SystemClock.elapsedRealtime() < releaseDeadline) Thread.sleep(50)+ assertTrue("Released TV input retained ownership",+ !com.streamvault.domain.sync.AutomaticSyncActivity.isProviderPlaybackActive(playbackProviderId))+ event("ownership-released")+ }+ } finally {+ try {+ try {+ finishOwnedProbes(workerProbe, guideProbe, catalogProbe, indexProbe)+ } finally {+ rows.forEach { app.contentResolver.delete(it, null, null) }+ db.openHelper.writableDatabase.execSQL(+ "DELETE FROM provider_configs WHERE provider_id = ?", arrayOf(providerId))+ db.providerDao().delete(providerId)+ }+ } finally {+ try {+ restoreFixturePreferences(preferences, providerId, previousAutomaticOverride,+ preferenceStore, originalPreferences)+ event("automatic-sync-restored")+ app.filesDir.resolve("tif-$runId.json").writeText(events.toString(2))+ } finally { catalogMutex.unlock() }+ }+ }+ }+ }+ private fun cycleTvViewSurface(+ scenario: ActivityScenario<MainActivity>,+ view: TvView,+ available: AtomicBoolean,+ terminal: AtomicBoolean,+ availableCount: AtomicInteger,+ providerId: Long,+ checkOwnership: Boolean,+ callbackDelayMs: Long,+ emit: (String, String) -> Unit+ ): Boolean {+ val previousAvailableCount = availableCount.get()+ if (callbackDelayMs > 0L) Thread.sleep(1_000L)+ scenario.onActivity {+ emit("surface-cycle-hide-start", "previousAvailableCount=$previousAvailableCount")+ view.visibility = View.INVISIBLE+ if (callbackDelayMs > 0L) {+ emit("surface-callback-delay-start", "delayMs=$callbackDelayMs")+ Thread.sleep(callbackDelayMs)+ emit("surface-callback-delay-end", "delayMs=$callbackDelayMs")+ }+ emit("surface-cycle-hidden", "")+ }+ Thread.sleep(1_500L)+ scenario.onActivity {+ view.visibility = View.VISIBLE+ emit("surface-cycle-shown", "")+ }+ // Readiness may stay READY across a surface-only cycle, so a new availability+ // callback is diagnostic evidence rather than a recovery requirement.+ Thread.sleep(2_000L)+ if (!available.get() && !terminal.get()) {+ val deadline = SystemClock.elapsedRealtime() + 15_000L+ while (!available.get() && !terminal.get() && SystemClock.elapsedRealtime() < deadline) {+ Thread.sleep(100L)+ }+ }+ val playbackOwned = com.streamvault.domain.sync.AutomaticSyncActivity+ .isProviderPlaybackActive(providerId)+ val freshAvailableCallback = availableCount.get() > previousAvailableCount+ val recovered = available.get() && !terminal.get() && (!checkOwnership || playbackOwned)+ emit(+ "surface-cycle-result",+ JSONObject()+ .put("previousAvailableCount", previousAvailableCount)+ .put("availableCount", availableCount.get())+ .put("freshAvailableCallback", freshAvailableCallback)+ .put("available", available.get())+ .put("terminal", terminal.get())+ .put("playbackOwned", playbackOwned)+ .put("ownershipRequired", checkOwnership)+ .put("recovered", recovered)+ .toString()+ )+ return recovered+ }++ private fun waitForPlaybackRelease(providerId: Long, timeoutMs: Long): String {+ val deadline = SystemClock.elapsedRealtime() + timeoutMs+ while (com.streamvault.domain.sync.AutomaticSyncActivity.isProviderPlaybackActive(providerId) &&+ SystemClock.elapsedRealtime() < deadline) {+ Thread.sleep(50L)+ }+ val stillActive = com.streamvault.domain.sync.AutomaticSyncActivity+ .isProviderPlaybackActive(providerId)+ return JSONObject()+ .put("timeoutMs", timeoutMs)+ .put("playbackOwned", stillActive)+ .put("released", !stillActive)+ .toString()+ }++ private suspend fun finishOwnedProbes(+ worker: com.streamvault.app.ui.PlaybackWorkerAdmissionProbe?,+ guide: com.streamvault.app.ui.PlaybackInflightEpgProbe?,+ catalog: com.streamvault.app.ui.PlaybackInflightCatalogProbe?,+ index: com.streamvault.app.ui.PlaybackIndexWorkProbe?+ ) {+ try {+ worker?.finishAfterPlayback()+ guide?.finishAfterPlayback()+ catalog?.finishAfterPlayback()+ index?.finishAfterPlayback()+ } finally {+ try { index?.close() } finally { catalog?.close() }+ }+ }++ private suspend fun restoreFixturePreferences(+ preferences: com.streamvault.data.preferences.PreferencesRepository,+ providerId: Long,+ previousOverride: com.streamvault.domain.sync.AutomaticSyncSettings?,+ store: DataStore<Preferences>,+ original: Preferences+ ) {+ preferences.setAutomaticSyncSettings(providerId, previousOverride)+ store.edit { values ->+ fun <T> restore(key: Preferences.Key<T>) {+ val old = original[key]+ if (old == null) values.remove(key) else values[key] = old+ }+ restore(stringPreferencesKey("automatic_sync_status_$providerId"))+ restore(longPreferencesKey("catalog_sync_upgrade_started_$providerId"))+ restore(intPreferencesKey("catalog_sync_engine_$providerId"))+ }+ }++}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/ChunkedHttpReaderDiagnosticTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/ChunkedHttpReaderDiagnosticTest.ktnew file mode 100644index 00000000..cd723d90--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/ChunkedHttpReaderDiagnosticTest.kt@@ -0,0 +1,398 @@+package com.streamvault.app.ui++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import okhttp3.OkHttpClient+import okhttp3.Request+import okio.Buffer+import org.json.JSONArray+import org.json.JSONObject+import org.junit.Assume.assumeTrue+import org.junit.Test+import org.junit.runner.RunWith+import java.io.ByteArrayOutputStream+import java.io.EOFException+import java.io.File+import java.io.InputStream+import java.net.HttpURLConnection+import java.net.InetSocketAddress+import java.net.Socket+import java.net.URI+import java.net.URL+import java.security.MessageDigest+import java.util.concurrent.TimeUnit++/** Opt-in Android-side HTTP chunk parser comparison; this does not create a player or change app policy. */+@RunWith(AndroidJUnit4::class)+class ChunkedHttpReaderDiagnosticTest {+ @Test+ fun compareBareReadersAgainstChunkedFixture() {+ val args = InstrumentationRegistry.getArguments()+ assumeTrue(args.getString("chunkedReaderDiagnostic") == "true")+ val runId = requireNotNull(args.getString("runId"))+ require(runId.matches(Regex("[A-Za-z0-9_-]{1,40}")))+ val baseUrl = requireNotNull(args.getString("fixtureBaseUrl")).trimEnd('/')+ val baseUri = URI(baseUrl)+ require(+ baseUri.scheme == "http" &&+ baseUri.host?.lowercase() in setOf("127.0.0.1", "localhost", "10.0.2.2") &&+ baseUri.port in 1..65_535 &&+ baseUri.userInfo == null &&+ baseUri.rawPath.isNullOrEmpty() &&+ baseUri.rawQuery == null &&+ baseUri.rawFragment == null+ ) { "fixtureBaseUrl must be a plain HTTP loopback URL with an explicit port" }+ val mediaPath = args.getString("mediaPath") ?: "/raw/1002.ts"+ val expectedBytes = requireNotNull(args.getString("expectedBytes")).toLong()+ val expectedSha256 = requireNotNull(args.getString("expectedSha256"))+ val callTimeoutSeconds = args.getString("callTimeoutSeconds")?.toLong() ?: 90L+ require(mediaPath.startsWith("/raw/") && !mediaPath.contains(".."))++ val report = JSONObject()+ .put("runId", runId)+ .put("fixtureBaseUrl", baseUrl)+ .put("mediaPath", mediaPath)+ .put("expectedBytes", expectedBytes)+ .put("expectedSha256", expectedSha256)+ .put("callTimeoutSeconds", callTimeoutSeconds)+ .put("okHttpVersionFromGradle", "4.12.0")+ .put("kotlinRuntimeVersion", KotlinVersion.CURRENT.toString())+ .put("readers", JSONArray())++ val reset = readJson("$baseUrl/control?reset=1")+ report.put("fixtureReset", reset)++ val okHttp = OkHttpClient.Builder()+ .connectTimeout(5, TimeUnit.SECONDS)+ .readTimeout(15, TimeUnit.SECONDS)+ .callTimeout(callTimeoutSeconds, TimeUnit.SECONDS)+ .build()+ val readers = report.getJSONArray("readers")+ readers.put(readWithOkHttpBodyStream(okHttp, "$baseUrl$mediaPath?reader=android-okhttp-body-stream-940", 940))+ readers.put(readWithOkHttp(okHttp, "$baseUrl$mediaPath?reader=android-okhttp-940", 940))+ readers.put(readWithOkHttp(okHttp, "$baseUrl$mediaPath?reader=android-okhttp-8192", 8_192))+ readers.put(readWithOkHttp(okHttp, "$baseUrl$mediaPath?reader=android-okhttp-32768", 32_768))+ readers.put(readWithHttpUrlConnection("$baseUrl$mediaPath?reader=android-httpurlconnection"))+ readers.put(readChunkedWireDirectly("$baseUrl$mediaPath?reader=android-raw-socket"))+ for (index in 0 until readers.length()) {+ val reader = readers.getJSONObject(index)+ reader.put("matchesExpectedBytes", reader.optLong("payloadBytes", -1L) == expectedBytes)+ reader.put("matchesExpectedSha256", reader.optString("payloadSha256") == expectedSha256)+ }++ report.put("fixtureEventsAfterRetrievedExternally", true)+ report.put("elapsedRealtimeMs", android.os.SystemClock.elapsedRealtime())+ val context = ApplicationProvider.getApplicationContext<Context>()+ val file = File(context.cacheDir, "chunked-http-reader-$runId.json")+ file.writeText(report.toString(2), Charsets.UTF_8)+ println("ChunkedHttpReaderDiagnostic report=${file.absolutePath} readers=${readers.length()}")+ }++ private fun readWithOkHttp(client: OkHttpClient, url: String, bufferBytes: Int): JSONObject {+ val started = android.os.SystemClock.elapsedRealtime()+ var responseCode: Int? = null+ var responseHeaders = JSONArray()+ val digest = MessageDigest.getInstance("SHA-256")+ var payloadBytes = 0L+ var reachedBodyEof = false+ var failure: Throwable? = null+ try {+ val request = Request.Builder()+ .url(url)+ .header("Accept-Encoding", "identity")+ .header("Connection", "close")+ .build()+ client.newCall(request).execute().use { response ->+ responseCode = response.code+ responseHeaders = headersJson(response.headers.toMultimap())+ val source = requireNotNull(response.body).source()+ val buffer = Buffer()+ while (true) {+ val read = source.read(buffer, bufferBytes.toLong())+ if (read == -1L) {+ reachedBodyEof = true+ break+ }+ val bytes = buffer.readByteArray(read)+ digest.update(bytes)+ payloadBytes += bytes.size+ }+ }+ } catch (error: Throwable) {+ failure = error+ }+ return result("okhttp-$bufferBytes", started, responseCode, responseHeaders, payloadBytes,+ digest.digest(), reachedBodyEof, failure).put("readBufferBytes", bufferBytes)+ }++ private fun readWithOkHttpBodyStream(client: OkHttpClient, url: String, bufferBytes: Int): JSONObject {+ val started = android.os.SystemClock.elapsedRealtime()+ var responseCode: Int? = null+ var responseHeaders = JSONArray()+ val digest = MessageDigest.getInstance("SHA-256")+ var payloadBytes = 0L+ var reachedBodyEof = false+ var failure: Throwable? = null+ try {+ val request = Request.Builder()+ .url(url)+ .header("Accept-Encoding", "identity")+ .header("Connection", "close")+ .build()+ client.newCall(request).execute().use { response ->+ responseCode = response.code+ responseHeaders = headersJson(response.headers.toMultimap())+ val input = requireNotNull(response.body).byteStream()+ val buffer = ByteArray(bufferBytes)+ while (true) {+ val read = input.read(buffer)+ if (read == -1) {+ reachedBodyEof = true+ break+ }+ digest.update(buffer, 0, read)+ payloadBytes += read+ }+ }+ } catch (error: Throwable) {+ failure = error+ }+ return result("okhttp-body-stream-$bufferBytes", started, responseCode, responseHeaders,+ payloadBytes, digest.digest(), reachedBodyEof, failure).put("readBufferBytes", bufferBytes)+ }++ private fun readWithHttpUrlConnection(url: String): JSONObject {+ val started = android.os.SystemClock.elapsedRealtime()+ var responseCode: Int? = null+ var responseHeaders = JSONArray()+ val digest = MessageDigest.getInstance("SHA-256")+ var payloadBytes = 0L+ var reachedBodyEof = false+ var failure: Throwable? = null+ val connection = URL(url).openConnection() as HttpURLConnection+ try {+ connection.connectTimeout = 5_000+ connection.readTimeout = 15_000+ connection.useCaches = false+ connection.instanceFollowRedirects = false+ connection.setRequestProperty("Accept-Encoding", "identity")+ connection.setRequestProperty("Connection", "close")+ responseCode = connection.responseCode+ responseHeaders = headersJson(connection.headerFields.filterKeys { it != null })+ connection.inputStream.use { input ->+ val buffer = ByteArray(8_192)+ while (true) {+ val read = input.read(buffer)+ if (read == -1) {+ reachedBodyEof = true+ break+ }+ digest.update(buffer, 0, read)+ payloadBytes += read+ }+ }+ } catch (error: Throwable) {+ failure = error+ } finally {+ connection.disconnect()+ }+ return result("httpurlconnection", started, responseCode, responseHeaders, payloadBytes,+ digest.digest(), reachedBodyEof, failure).put("readBufferBytes", 8_192)+ }++ private fun readChunkedWireDirectly(url: String): JSONObject {+ val started = android.os.SystemClock.elapsedRealtime()+ val uri = URI(url)+ val socket = Socket()+ val digest = MessageDigest.getInstance("SHA-256")+ val tail = TailRing(128)+ val rawChunkTerminator = ByteArrayOutputStream()+ var statusLine: String? = null+ var responseHeaders = JSONArray()+ var payloadBytes = 0L+ var wireBytes = 0L+ var reachedBodyEof = false+ var terminatorSeen = false+ var trailingBytes = 0L+ var failure: Throwable? = null+ try {+ socket.connect(InetSocketAddress(uri.host, uri.port), 5_000)+ socket.soTimeout = 15_000+ val output = socket.getOutputStream()+ val request = "GET ${uri.rawPath}${uri.rawQuery?.let { "?$it" } ?: ""} HTTP/1.1\r\n" ++ "Host: ${uri.host}:${uri.port}\r\n" ++ "Accept-Encoding: identity\r\n" ++ "Connection: close\r\n\r\n"+ output.write(request.toByteArray(Charsets.US_ASCII))+ output.flush()+ val input = socket.getInputStream()+ statusLine = readCrlfLine(input, tail).toString(Charsets.US_ASCII)+ wireBytes += statusLine!!.length + 2+ while (true) {+ val line = readCrlfLine(input, tail)+ wireBytes += line.size + 2+ if (line.isEmpty()) break+ responseHeaders.put(String(line, Charsets.US_ASCII))+ }+ while (true) {+ val sizeLineBytes = readCrlfLine(input, tail)+ wireBytes += sizeLineBytes.size + 2+ val sizeLine = String(sizeLineBytes, Charsets.US_ASCII)+ if (sizeLineBytes.isEmpty()) throw java.net.ProtocolException("empty chunk-size line")+ val sizeText = sizeLine.substringBefore(';').trim()+ val chunkBytes = sizeText.toLongOrNull(16)+ ?: throw java.net.ProtocolException("invalid chunk-size line")+ if (chunkBytes == 0L) {+ terminatorSeen = true+ rawChunkTerminator.write(sizeLineBytes)+ rawChunkTerminator.write(byteArrayOf(13, 10))+ while (true) {+ val trailer = readCrlfLine(input, tail)+ wireBytes += trailer.size + 2+ rawChunkTerminator.write(trailer)+ rawChunkTerminator.write(byteArrayOf(13, 10))+ if (trailer.isEmpty()) break+ }+ while (true) {+ val extra = input.read()+ if (extra == -1) {+ reachedBodyEof = true+ break+ }+ trailingBytes+++ wireBytes+++ tail.append(extra.toByte())+ }+ break+ }+ var remaining = chunkBytes+ val buffer = ByteArray(16_384)+ while (remaining > 0) {+ val read = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())+ if (read == -1) throw EOFException("EOF inside chunk body after $payloadBytes bytes")+ digest.update(buffer, 0, read)+ tail.append(buffer, 0, read)+ payloadBytes += read+ wireBytes += read+ remaining -= read+ }+ val cr = input.read()+ val lf = input.read()+ if (cr != 13 || lf != 10) throw java.net.ProtocolException("chunk lacked CRLF terminator")+ tail.append(cr.toByte())+ tail.append(lf.toByte())+ wireBytes += 2+ }+ } catch (error: Throwable) {+ failure = error+ } finally {+ runCatching { socket.close() }+ }+ return JSONObject()+ .put("reader", "raw-socket-chunk-decoder")+ .put("startedElapsedRealtimeMs", started)+ .put("finishedElapsedRealtimeMs", android.os.SystemClock.elapsedRealtime())+ .put("responseCodeLine", statusLine ?: JSONObject.NULL)+ .put("responseHeaders", responseHeaders)+ .put("payloadBytes", payloadBytes)+ .put("payloadSha256", digest.digest().toHex())+ .put("wireBytes", wireBytes)+ .put("terminalChunkSeen", terminatorSeen)+ .put("terminalChunkHex", rawChunkTerminator.toByteArray().toHex())+ .put("rawTailHex", tail.snapshot().toHex())+ .put("trailingBytesAfterTerminator", trailingBytes)+ .put("reachedSocketEof", reachedBodyEof)+ .put("error", failure?.let(::throwableJson) ?: JSONObject.NULL)+ }++ private fun readCrlfLine(input: InputStream, tail: TailRing): ByteArray {+ val line = ByteArrayOutputStream()+ var previous = -1+ while (true) {+ val current = input.read()+ if (current == -1) throw EOFException("EOF before CRLF line terminator")+ tail.append(current.toByte())+ if (previous == 13 && current == 10) {+ val bytes = line.toByteArray()+ return bytes.copyOf(bytes.size - 1)+ }+ line.write(current)+ previous = current+ }+ }++ private fun readJson(url: String): JSONObject {+ val connection = URL(url).openConnection() as HttpURLConnection+ connection.connectTimeout = 5_000+ connection.readTimeout = 5_000+ connection.useCaches = false+ return try {+ require(connection.responseCode == 200) { "Fixture returned HTTP ${connection.responseCode} for $url" }+ JSONObject(connection.inputStream.bufferedReader(Charsets.UTF_8).use { it.readText() })+ } finally {+ connection.disconnect()+ }+ }++ private fun headersJson(headers: Map<String, List<String>>): JSONArray = JSONArray().apply {+ headers.forEach { (name, values) ->+ values.forEach { value -> put("$name: $value") }+ }+ }++ private fun result(+ name: String,+ started: Long,+ status: Int?,+ headers: JSONArray,+ bytes: Long,+ digest: ByteArray,+ reachedEof: Boolean,+ failure: Throwable?+ ) = JSONObject()+ .put("reader", name)+ .put("startedElapsedRealtimeMs", started)+ .put("finishedElapsedRealtimeMs", android.os.SystemClock.elapsedRealtime())+ .put("status", status ?: JSONObject.NULL)+ .put("responseHeaders", headers)+ .put("payloadBytes", bytes)+ .put("payloadSha256", digest.toHex())+ .put("reachedBodyEof", reachedEof)+ .put("error", failure?.let(::throwableJson) ?: JSONObject.NULL)++ private fun throwableJson(error: Throwable): JSONObject {+ val causes = JSONArray()+ generateSequence(error) { it.cause }.take(8).forEach { cause ->+ causes.put(JSONObject()+ .put("type", cause.javaClass.name)+ .put("message", cause.message.orEmpty().take(300))+ .put("stack", JSONArray(cause.stackTrace.take(12).map { it.toString() })))+ }+ return JSONObject().put("causes", causes)+ }++ private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it.toInt() and 0xff) }++ private class TailRing(private val capacity: Int) {+ private val bytes = ByteArray(capacity)+ private var next = 0+ private var size = 0++ fun append(value: Byte) {+ bytes[next] = value+ next = (next + 1) % capacity+ if (size < capacity) size+++ }++ fun append(value: ByteArray, offset: Int, length: Int) {+ val start = maxOf(offset, offset + length - capacity)+ for (index in start until offset + length) append(value[index])+ }++ fun snapshot(): ByteArray = ByteArray(size) { index ->+ bytes[(next - size + index + capacity) % capacity]+ }+ }+}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/FrameRateFallbackRuntimeTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/FrameRateFallbackRuntimeTest.ktnew file mode 100644index 00000000..1c6ea151--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/FrameRateFallbackRuntimeTest.kt@@ -0,0 +1,268 @@+package com.streamvault.app.ui++import android.app.Application+import android.os.Debug+import android.os.SystemClock+import androidx.lifecycle.ViewModelStore+import androidx.datastore.core.DataStore+import androidx.datastore.preferences.core.Preferences+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.media3.common.Format+import androidx.media3.exoplayer.ExoPlayer+import androidx.media3.exoplayer.analytics.AnalyticsListener+import androidx.test.core.app.ActivityScenario+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.streamvault.app.MainActivity+import com.streamvault.core.navigation.PlayerNavigationRequest+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.sync.ProviderSyncCommands+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.LegacyProvider+import com.streamvault.domain.model.LiveStreamFormatMode+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.repository.ChannelRepository+import com.streamvault.domain.repository.ProviderRepository+import com.streamvault.feature.playback.player.PlayerViewModel+import com.streamvault.player.PlaybackState+import com.streamvault.player.PlayerEngine+import com.streamvault.player.playback.VideoStallDetector+import com.streamvault.player.stats.FrameRateDetector+import com.streamvault.player.stats.PlayerStatsCollector+import dagger.hilt.internal.GeneratedComponentManager+import java.io.File+import javax.inject.Provider+import kotlin.math.abs+import kotlin.math.roundToLong+import kotlinx.coroutines.delay+import kotlinx.coroutines.Job+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.collect+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.json.JSONArray+import org.json.JSONObject+import org.junit.Assume.assumeTrue+import org.junit.Test+import org.junit.runner.RunWith++/** Opt-in fixture: real fullscreen UI, with missing metadata/rounded estimator input injected. */+@RunWith(AndroidJUnit4::class)+class FrameRateFallbackRuntimeTest {+ private fun field(owner: Any, name: String): Any? = owner.javaClass.getDeclaredField(name).apply {+ isAccessible = true+ }.get(owner)++ private fun getter(owner: Any, name: String): Any? = owner.javaClass.methods.single {+ it.name.substringBefore('$') == name && it.parameterCount == 0+ }.invoke(owner)++ private fun players(store: ViewModelStore): List<PlayerViewModel> = buildList {+ for (key in store.keys()) {+ val model = store[key] ?: continue+ if (model is PlayerViewModel) add(model)+ for (entry in model.javaClass.declaredFields.filter { Map::class.java.isAssignableFrom(it.type) }) {+ val map = entry.apply { isAccessible = true }.get(model) as? Map<*, *> ?: continue+ map.values.filterIsInstance<ViewModelStore>().forEach { addAll(players(it)) }+ }+ }+ }.distinct()++ @Test fun fullscreenRoundedTimestampFallback() = runBlocking {+ val args = InstrumentationRegistry.getArguments()+ assumeTrue(args.getString("fpsFixture") == "true")+ val url = requireNotNull(args.getString("fixtureUrl"))+ require(java.net.URI(url).host in setOf("10.0.2.2", "127.0.0.1", "localhost"))+ val runId = requireNotNull(args.getString("runId"))+ require(runId.matches(Regex("[A-Za-z0-9_-]{1,40}")))+ val expected = requireNotNull(args.getString("expectedEstimate")).toFloat()+ val duration = args.getString("durationSeconds")?.toInt() ?: 150+ require(duration in 90..300)+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val app = ApplicationProvider.getApplicationContext<Application>()+ val component = (app as GeneratedComponentManager<*>).generatedComponent()+ val prefs = (field(component, "preferencesRepositoryProvider") as Provider<*>).get() as PreferencesRepository+ val providers = (field(component, "providerRepositoryImplProvider") as Provider<*>).get() as ProviderRepository+ val channels = (field(component, "channelRepositoryImplProvider") as Provider<*>).get() as ChannelRepository+ val savedProvider = providers.getActiveProvider().first()?.id+ val savedLastProvider = prefs.lastActiveProviderId.first()+ val savedMatching = prefs.playerRefreshRateMatchingEnabled.first()+ prefs.setPlayerRefreshRateMatchingEnabled(true)+ fun <T> main(action: () -> T): T {+ val result = java.util.concurrent.atomic.AtomicReference<T>()+ instrumentation.runOnMainSync { result.set(action()) }+ return result.get()+ }+ val scenario = ActivityScenario.launch(MainActivity::class.java)+ var engine: PlayerEngine? = null+ var player: ExoPlayer? = null+ var detector: FrameRateDetector? = null+ var stall: VideoStallDetector? = null+ var formatObserver: AnalyticsListener? = null+ var fixtureProviderId: Long? = null+ var errorJob: Job? = null+ val errors = JSONArray()+ val startedAt = SystemClock.elapsedRealtime()+ val samples = JSONArray()+ val marker = File(app.filesDir, "fps-ready-$runId.json")+ marker.delete()+ try {+ val providerId = providers.addProvider(LegacyProvider(+ name = "FPS fixture $runId", type = ProviderType.XTREAM_CODES,+ serverUrl = "${java.net.URI(url).scheme}://${java.net.URI(url).rawAuthority}",+ username = "v5-fixture", password = "v5-fixture", maxConnections = 5,+ allowedOutputFormats = listOf("m3u8"), preferredLiveStreamFormat = LiveStreamFormatMode.HLS,+ isActive = false, xtreamFastSyncEnabled = false+ )).getOrNull()?.also { fixtureProviderId = it } ?: error("Fixture provider creation failed")+ check(providers.refreshProviderData(providerId, force = true).isSuccess)+ val sync = (field(component, "syncManagerProvider") as Provider<*>).get() as ProviderSyncCommands+ check(sync.processQueuedXtreamIndexJobs(providerId, section = ContentType.LIVE, force = true).isSuccess)+ val streamId = java.net.URI(url).path.substringAfterLast('/').substringBefore('.').toLong()+ val channel = withTimeout(60_000) {+ channels.getChannels(providerId).first { rows -> rows.any { it.streamId == streamId } }+ }.first { it.streamId == streamId }+ check(providers.setActiveProvider(providerId).isSuccess)+ prefs.setLastActiveProviderId(providerId)+ println("FPS fixture provisioned provider=$providerId channel=${channel.id}")+ scenario.onActivity { activity ->+ activity.openPlayer(PlayerNavigationRequest(+ streamUrl = channel.streamUrl, channelId = channel.epgChannelId,+ title = channel.name, internalId = channel.id, providerId = providerId, categoryId = channel.categoryId,+ contentType = "LIVE"+ ))+ }+ withTimeout(60_000) {+ var lastState = ""+ while (engine == null) {+ scenario.onActivity { activity ->+ val found = players(activity.viewModelStore)+ val state = found.joinToString {+ "${it.playerEngine.playbackState.value}:${it.playerEngine.isPlaying.value}" ++ ":session=${getter(it, "getPrepareRequestVersion")}" ++ ":resolved=${getter(it, "getCurrentResolvedStreamInfo") != null}" ++ ":resolution=${it.playbackResolutionUiState.value.javaClass.simpleName}"+ }+ if (state != lastState) { println("FPS fullscreen players=${found.size} state=$state"); lastState = state }+ engine = found.map { it.playerEngine }.firstOrNull {+ it.isPlaying.value && it.playbackState.value == PlaybackState.READY+ }+ }+ delay(100)+ }+ }+ val active = requireNotNull(engine)+ errorJob = launch { active.error.collect { if (it != null) errors.put(it.javaClass.simpleName) } }+ lateinit var collector: PlayerStatsCollector+ val declaredFps = main {+ player = field(active, "exoPlayer") as ExoPlayer+ detector = field(active, "frameRateDetector") as FrameRateDetector+ stall = field(active, "videoStallDetector") as VideoStallDetector+ collector = field(active, "statsCollector") as PlayerStatsCollector+ val exo = requireNotNull(player)+ val original = exo.videoFormat?.frameRate+ // Do not change codec timestamps or frame delivery. Only the estimator sees rounding.+ formatObserver = object : AnalyticsListener {+ override fun onVideoInputFormatChanged(+ eventTime: AnalyticsListener.EventTime, format: Format,+ decoderReuseEvaluation: androidx.media3.exoplayer.DecoderReuseEvaluation?+ ) { collector.onVideoFormatChanged(format.buildUpon().setFrameRate(Format.NO_VALUE.toFloat()).build()) }+ }.also(exo::addAnalyticsListener)+ exo.videoFormat?.let {+ collector.onVideoFormatChanged(it.buildUpon().setFrameRate(Format.NO_VALUE.toFloat()).build())+ }+ requireNotNull(detector).reset()+ exo.setVideoFrameMetadataListener { pts, _, _, _ ->+ requireNotNull(stall).onVideoFrameRendered((pts / 1_000L).coerceAtLeast(0L))+ requireNotNull(detector).onFrame((pts / 1000.0).roundToLong() * 1000L)+ }+ original+ }+ val injectedAtMs = SystemClock.elapsedRealtime() - startedAt+ fun snapshot(): JSONObject = main {+ val exo = requireNotNull(player)+ val binder = requireNotNull(field(active, "viewBinder"))+ val controller = field(binder, "refreshRateController")+ val view = field(binder, "boundPlayerView") as? android.view.View+ val counters = exo.videoDecoderCounters.also { it?.ensureUpdated() }+ JSONObject()+ .put("elapsedMs", SystemClock.elapsedRealtime() - startedAt)+ .put("estimatedFps", requireNotNull(detector).lockedFrameRate)+ .put("publishedFps", active.videoFormat.value.frameRate)+ .put("hostRequestedFps", field(binder, "displayFrameRate"))+ .put("surfaceVotedFps", controller?.let { field(it, "votedRate") })+ .put("displayHz", view?.display?.mode?.refreshRate)+ .put("state", active.playbackState.value.name)+ .put("isPlaying", active.isPlaying.value)+ .put("bufferMs", exo.totalBufferedDuration)+ .put("rebufferCount", active.playerStats.value.rebufferCount)+ .put("rendered", counters?.renderedOutputBufferCount)+ .put("dropped", counters?.droppedBufferCount)+ .put("skipped", counters?.skippedOutputBufferCount)+ .put("decoder", active.playerStats.value.videoDecoderName)+ .put("cpuMs", android.os.Process.getElapsedCpuTime())+ .put("javaBytes", Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())+ .put("pssKb", Debug.MemoryInfo().also { Debug.getMemoryInfo(it) }.totalPss)+ }+ withTimeout(35_000) {+ while (true) {+ val s = snapshot()+ if (abs(s.optDouble("estimatedFps") - expected) < 0.02 &&+ abs(s.optDouble("publishedFps") - expected) < 0.02 &&+ abs(s.optDouble("hostRequestedFps") - expected) < 0.02 &&+ abs(s.optDouble("surfaceVotedFps") - expected) < 0.02) break+ delay(100)+ }+ }+ val matchedAtMs = SystemClock.elapsedRealtime() - startedAt+ marker.writeText(snapshot().toString(2))+ val deadline = SystemClock.elapsedRealtime() + duration * 1000L+ while (SystemClock.elapsedRealtime() < deadline) {+ samples.put(snapshot())+ delay(1000)+ }+ val result = JSONObject().put("runId", runId).put("fixtureUrl", url)+ .put("expectedEstimate", expected).put("declaredDecoderFps", declaredFps)+ .put("roundedEstimatorInput", true).put("missingMetadataInjected", true)+ .put("injectedAtMs", injectedAtMs).put("matchedAtMs", matchedAtMs)+ .put("durationSeconds", duration)+ .put("liveIdentityPresent", main { (field(active, "lastStreamInfo") as? StreamInfo)?.livePlaybackIdentity != null })+ .put("detectorImplementation", if (requireNotNull(detector).javaClass.declaredFields.any { it.name == "intervals" }) "windowed" else "minimum")+ .put("errors", errors)+ .put("samples", samples).put("final", snapshot())+ File(app.filesDir, "fps-result-$runId.json").writeText(result.toString(2))+ check(active.isPlaying.value && active.playbackState.value == PlaybackState.READY)+ check(errors.length() == 0)+ check(active.playerStats.value.rebufferCount == 0)+ } finally {+ errorJob?.cancelAndJoin()+ main {+ formatObserver?.let { player?.removeAnalyticsListener(it) }+ player?.setVideoFrameMetadataListener { pts, _, _, _ ->+ stall?.onVideoFrameRendered((pts / 1000L).coerceAtLeast(0L))+ detector?.onFrame(pts)+ }+ engine?.stop()+ }+ scenario.close()+ try {+ fixtureProviderId?.let { check(providers.deleteProvider(it).isSuccess) }+ } finally {+ savedProvider?.let { providers.setActiveProvider(it) }+ if (savedLastProvider != null) prefs.setLastActiveProviderId(savedLastProvider)+ else {+ @Suppress("UNCHECKED_CAST")+ val store = prefs.javaClass.getDeclaredMethod("getPreferencesDataStore").apply {+ isAccessible = true+ }.invoke(prefs) as DataStore<Preferences>+ store.edit { it.remove(longPreferencesKey("last_active_provider_id")) }+ }+ prefs.setPlayerRefreshRateMatchingEnabled(savedMatching)+ }+ }+ }+}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/HiddenControlsPlaybackRuntimeTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/HiddenControlsPlaybackRuntimeTest.ktnew file mode 100644index 00000000..2830c75b--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/HiddenControlsPlaybackRuntimeTest.kt@@ -0,0 +1,272 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.app.ui++import android.app.Application+import android.net.Uri+import android.os.SystemClock+import android.util.Log+import androidx.lifecycle.ViewModelStore+import androidx.media3.exoplayer.ExoPlayer+import androidx.test.core.app.ActivityScenario+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.streamvault.app.MainActivity+import com.streamvault.core.navigation.PlayerNavigationRequest+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.feature.playback.player.PlayerViewModel+import com.streamvault.feature.playback.player.toggleControls+import com.streamvault.player.PlaybackState+import dagger.hilt.internal.GeneratedComponentManager+import javax.inject.Provider+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.json.JSONArray+import org.json.JSONObject+import org.junit.Assume.assumeTrue+import org.junit.Test+import org.junit.runner.RunWith++/** Normal PlayerScreen, local live fixtures, no replacement render view or TIF pipeline. */+@RunWith(AndroidJUnit4::class)+class HiddenControlsPlaybackRuntimeTest {+ @Test fun exerciseDefaultLivePlayer() = runBlocking {+ val args = InstrumentationRegistry.getArguments()+ assumeTrue(args.getString("hiddenControlsFixture") == "true")+ val run = requireNotNull(args.getString("runId"))+ require(run.matches(Regex("[A-Za-z0-9_-]{1,40}")))+ val urls = requireNotNull(args.getString("fixtureUrls")).split(',')+ require(urls.all { Uri.parse(it).host in setOf("127.0.0.1", "localhost") })+ val seconds = args.getString("durationSeconds")?.toInt() ?: 130+ require(seconds in 10..160)+ val app = ApplicationProvider.getApplicationContext<Application>()+ val component = (app as GeneratedComponentManager<*>).generatedComponent()+ val prefs = (component.javaClass.getDeclaredField("preferencesRepositoryProvider").apply {+ isAccessible = true+ }.get(component) as Provider<*>).get() as PreferencesRepository+ val originalTimeshift = prefs.playerTimeshiftEnabled.first()+ val instrumentation = InstrumentationRegistry.getInstrumentation()+ val events = JSONArray()+ fun main(block: () -> Unit) = instrumentation.runOnMainSync(block)+ fun players(store: ViewModelStore): List<PlayerViewModel> = buildList {+ for (key in store.keys()) {+ val model = store[key] ?: continue+ if (model is PlayerViewModel) add(model)+ model.javaClass.declaredFields.filter { Map::class.java.isAssignableFrom(it.type) }.forEach { field ->+ val values = field.apply { isAccessible = true }.get(model) as? Map<*, *> ?: return@forEach+ values.values.filterIsInstance<ViewModelStore>().forEach { addAll(players(it)) }+ }+ }+ }.distinct()+ fun resolvedUrl(vm: PlayerViewModel): String = vm.javaClass.methods.single {+ it.name.substringBefore('$') == "getCurrentResolvedPlaybackUrl" && it.parameterCount == 0+ }.invoke(vm) as String+ fun emit(row: JSONObject) {+ row.put("elapsedMs", SystemClock.elapsedRealtime())+ synchronized(events) { events.put(row) }+ Log.i("HiddenControlsFixture", row.toString())+ }+ // Durable record survives a host-side harness interruption before finally executes.+ app.filesDir.resolve("hidden-controls-$run-original.json").writeText(+ JSONObject().put("timeshift", originalTimeshift).toString())+ prefs.setPlayerTimeshiftEnabled(false)+ var scenario: ActivityScenario<MainActivity>? = null+ var workerProbe: PlaybackWorkerAdmissionProbe? = null+ var inflightProbe: PlaybackInflightEpgProbe? = null+ var catalogProbe: PlaybackInflightCatalogProbe? = null+ var indexProbe: PlaybackIndexWorkProbe? = null+ var workerEngine: com.streamvault.player.PlayerEngine? = null+ var audioSourceProbe: PlaybackAudioSourceProbe? = null+ var audioSourceEngine: com.streamvault.player.PlayerEngine? = null+ try {+ inflightProbe = PlaybackInflightEpgProbe.start(app, component, args, run, ::emit)+ catalogProbe = PlaybackInflightCatalogProbe.start(app, args, run, ::emit)+ indexProbe = PlaybackIndexWorkProbe.start(app, args, run, ::emit)+ scenario = ActivityScenario.launch(MainActivity::class.java)+ urls.forEachIndexed { index, url ->+ val navigation = indexProbe?.navigation(url) ?: inflightProbe?.navigation(url) ?: PlayerNavigationRequest(+ streamUrl = url, title = "Local live fixture $index", contentType = "LIVE")+ scenario.onActivity { it.openPlayer(navigation) }+ var vm: PlayerViewModel? = null+ val deadline = SystemClock.elapsedRealtime() + 60_000L+ while (vm == null && SystemClock.elapsedRealtime() < deadline) {+ scenario.onActivity { activity ->+ vm = players(activity.viewModelStore).lastOrNull {+ resolvedUrl(it) == url && it.playerEngine.isPlaying.value &&+ it.playerEngine.playbackState.value == PlaybackState.READY+ }+ }+ Thread.sleep(100)+ }+ val model = checkNotNull(vm) { "Normal PlayerScreen did not start fixture $index" }+ val engine = model.playerEngine+ if (args.getString("audioSourceProbe") == "true") {+ check(urls.size == 1) { "Source timing probe requires one fixture per run" }+ lateinit var native: ExoPlayer+ main { native = engine.javaClass.getDeclaredField("exoPlayer").apply {+ isAccessible = true+ }.get(engine) as ExoPlayer }+ audioSourceEngine = engine+ audioSourceProbe = PlaybackAudioSourceProbe(native, ::emit)+ audioSourceProbe!!.install()+ }+ // Read the effective media clock on its playback thread. Public playbackParameters+ // reports user intent and can omit internal live catch-up adjustments.+ val clockSample = java.util.concurrent.atomic.AtomicReference<JSONObject>()+ fun sampleClock(native: ExoPlayer) {+ native.createMessage { _, _ ->+ val internal = native.javaClass.getDeclaredField("internalPlayer").apply {+ isAccessible = true+ }.get(native)+ val clock = internal.javaClass.getDeclaredField("mediaClock").apply {+ isAccessible = true+ }.get(internal)+ val parameters = clock.javaClass.getDeclaredMethod("getPlaybackParameters").apply {+ isAccessible = true+ }.invoke(clock) as androidx.media3.common.PlaybackParameters+ clockSample.set(JSONObject().put("speed", parameters.speed)+ .put("elapsedMs", SystemClock.elapsedRealtime()))+ }.send()+ }+ fun visibility(show: Boolean) = main { if (model.showControls.value != show) model.toggleControls() }+ @Suppress("UNCHECKED_CAST")+ val position = engine.javaClass.getDeclaredField("_currentPosition").apply {+ isAccessible = true+ }.get(engine) as MutableStateFlow<Long>+ fun snapshot(stage: String): JSONObject {+ lateinit var row: JSONObject+ main {+ val native = engine.javaClass.getDeclaredField("exoPlayer").apply {+ isAccessible = true+ }.get(engine) as ExoPlayer+ native.videoDecoderCounters?.ensureUpdated()+ sampleClock(native)+ val video = native.videoFormat+ val displayHz = native.videoFormat?.let { _ ->+ val binder = engine.javaClass.getDeclaredField("viewBinder").apply {+ isAccessible = true+ }.get(engine)+ val view = binder.javaClass.getDeclaredField("boundPlayerView").apply {+ isAccessible = true+ }.get(binder) as? android.view.View+ view?.display?.mode?.refreshRate+ }+ val videoMode = engine.javaClass.getDeclaredField("requestedVideoDecoderMode")+ .apply { isAccessible = true }.get(engine).toString()+ val audioMode = engine.javaClass.getDeclaredField("requestedAudioDecoderMode")+ .apply { isAccessible = true }.get(engine).toString()+ row = JSONObject().put("event", stage).put("channelIndex", index)+ .put("state", engine.playbackState.value.name).put("playing", engine.isPlaying.value)+ .put("error", native.playerError?.errorCode ?: JSONObject.NULL)+ .put("isLoading", native.isLoading)+ .put("positionSubscriptions", position.subscriptionCount.value)+ .put("controlsVisible", model.showControls.value)+ .put("diagnosticsVisible", model.showDiagnostics.value)+ .put("timeshift", engine.playerStats.value.isTimeshiftPlayback)+ .put("bufferedMs", native.totalBufferedDuration)+ .put("rendered", native.videoDecoderCounters?.renderedOutputBufferCount ?: 0)+ .put("dropped", native.videoDecoderCounters?.droppedBufferCount ?: 0)+ .put("skipped", native.videoDecoderCounters?.skippedOutputBufferCount ?: 0)+ .put("droppedInput", native.videoDecoderCounters?.droppedInputBufferCount ?: 0)+ .put("maxConsecutiveDrops", native.videoDecoderCounters?.maxConsecutiveDroppedBufferCount ?: 0)+ .put("droppedToKeyframe", native.videoDecoderCounters?.droppedToKeyframeCount ?: 0)+ .put("processingOffsetUs", native.videoDecoderCounters?.totalVideoFrameProcessingOffsetUs ?: 0)+ .put("processingOffsetCount", native.videoDecoderCounters?.videoFrameProcessingOffsetCount ?: 0)+ .put("effectiveClock", clockSample.get() ?: JSONObject.NULL)+ .put("requestedSpeed", native.playbackParameters.speed)+ .put("liveOffsetMs", native.currentLiveOffset)+ .put("decoder", engine.playerStats.value.videoDecoderName)+ .put("requestedVideoDecoderMode", videoMode)+ .put("requestedAudioDecoderMode", audioMode)+ .put("renderSurfaceType", engine.renderSurfaceType.value.name)+ .put("formatFps", video?.frameRate ?: JSONObject.NULL)+ .put("videoWidth", video?.width ?: 0)+ .put("videoHeight", video?.height ?: 0)+ .put("audioDecoder", engine.playerStats.value.audioDecoderName)+ .put("javaHeapBytes", Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())+ .put("gcCount", android.os.Debug.getRuntimeStat("art.gc.gc-count"))+ .put("gcTimeMs", android.os.Debug.getRuntimeStat("art.gc.gc-time"))+ .put("displayHz", displayHz ?: JSONObject.NULL)+ .put("rebufferCount", engine.playerStats.value.rebufferCount)+ .put("mainCpuMs", SystemClock.currentThreadTimeMillis())+ .put("processCpuMs", android.os.Process.getElapsedCpuTime())+ }+ return row+ }+ visibility(false)+ Thread.sleep(1_000)+ check(!model.showDiagnostics.value)+ emit(snapshot("capture-begin"))+ check(engine.javaClass.getDeclaredField("requestedVideoDecoderMode").apply {+ isAccessible = true+ }.get(engine).toString() == "AUTO") { "Expected default AUTO video decoder mode" }+ check(engine.javaClass.getDeclaredField("requestedAudioDecoderMode").apply {+ isAccessible = true+ }.get(engine).toString() == "AUTO") { "Expected default AUTO audio decoder mode" }+ val workload = PlaybackImportWorkload.start(app, component, args, run, ::emit)+ workerProbe = PlaybackWorkerAdmissionProbe.start(app, args, run, ::emit)+ if (workerProbe != null || inflightProbe != null || catalogProbe != null || indexProbe != null) workerEngine = engine+ inflightProbe?.verifyPlaybackContext(model.javaClass.methods.single {+ it.name.substringBefore('$') == "getCurrentProviderId" && it.parameterCount == 0+ }.invoke(model) as Long)+ inflightProbe?.playbackReady()+ catalogProbe?.playbackReady()+ indexProbe?.verifyPlaybackContext(model.javaClass.methods.single {+ it.name.substringBefore('$') == "getCurrentProviderId" && it.parameterCount == 0+ }.invoke(model) as Long)+ indexProbe?.playbackReady()+ try {+ repeat(seconds) {+ Thread.sleep(1_000)+ emit(snapshot("sample"))+ audioSourceProbe?.drain()+ check(!engine.playerStats.value.isTimeshiftPlayback)+ }+ } finally {+ workload?.close()+ workerProbe?.finishWhilePlaying()+ inflightProbe?.finishWhilePlaying()+ catalogProbe?.finishWhilePlaying()+ indexProbe?.finishWhilePlaying()+ }+ visibility(true)+ Thread.sleep(700)+ emit(snapshot("controls-open"))+ visibility(false)+ Thread.sleep(700)+ emit(snapshot("controls-closed"))+ val final = snapshot("capture-end")+ emit(final)+ check(engine.playbackState.value == PlaybackState.READY && engine.isPlaying.value) {+ "Playback unhealthy at end of channel $index: ${engine.playbackState.value}, playing=${engine.isPlaying.value}"+ }+ check(final.isNull("error")) {+ "Native player error at end of channel $index"+ }+ if (args.getString("indexLifecycleProbe")=="true") indexProbe?.verifyPauseResume(engine)+ }+ } finally {+ try {+ // Closing the Activity can retain service playback. Stop only this probe's+ // engine, including on a failed assertion, before checking idle admission.+ main { workerEngine?.stop() }+ if (audioSourceProbe != null) emit(JSONObject().put("event", "activity-close-begin"))+ scenario?.close()+ if (audioSourceProbe != null) emit(JSONObject().put("event", "activity-close-end"))+ try { audioSourceProbe?.finish() } finally { main { audioSourceEngine?.stop() } }+ workerProbe?.finishAfterPlayback()+ inflightProbe?.finishAfterPlayback()+ catalogProbe?.finishAfterPlayback()+ indexProbe?.finishAfterPlayback()+ } finally {+ try { indexProbe?.close() } finally { try { catalogProbe?.close() } finally {+ prefs.setPlayerTimeshiftEnabled(originalTimeshift)+ app.filesDir.resolve("hidden-controls-$run.json").writeText(events.toString(2))+ }+ }+ }+ }+ }+}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlaybackAudioSourceProbe.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackAudioSourceProbe.ktnew file mode 100644index 00000000..1555efbd--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackAudioSourceProbe.kt@@ -0,0 +1,116 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.app.ui++import android.os.SystemClock+import androidx.media3.exoplayer.ExoPlayer+import androidx.media3.exoplayer.PlayerMessage+import androidx.media3.exoplayer.analytics.AnalyticsListener+import androidx.media3.exoplayer.audio.AudioSink+import androidx.media3.exoplayer.audio.DefaultAudioSink+import androidx.test.platform.app.InstrumentationRegistry+import java.lang.reflect.InvocationTargetException+import java.lang.reflect.Proxy+import java.util.concurrent.ConcurrentLinkedQueue+import org.json.JSONObject++/** Opt-in timing observer. Never calls an audio callback synthetically or changes sink policy. */+internal class PlaybackAudioSourceProbe(private val native: ExoPlayer, private val emit: (JSONObject) -> Unit) {+ private val instrumentation = InstrumentationRegistry.getInstrumentation()+ private data class Event(val kind: String, val time: Long, val thread: String,+ val bytes: Int, val bufferMs: Long, val feedMs: Long)+ private val pending = ConcurrentLinkedQueue<Event>()+ private lateinit var sink: DefaultAudioSink+ private lateinit var original: AudioSink.Listener+ private lateinit var proxy: AudioSink.Listener+ private var installed = false+ private val field = DefaultAudioSink::class.java.getDeclaredField("listener").apply { isAccessible = true }+ private val analytics = object : AnalyticsListener {+ override fun onAudioUnderrun(eventTime: AnalyticsListener.EventTime, bufferSize: Int,+ bufferSizeMs: Long, elapsedSinceLastFeedMs: Long) {+ record("audio-callback", bufferSize, bufferSizeMs, elapsedSinceLastFeedMs)+ }+ }+ private fun record(kind: String, bytes: Int, bufferMs: Long, feedMs: Long) {+ pending.add(Event(kind, SystemClock.elapsedRealtime(), Thread.currentThread().name, bytes, bufferMs, feedMs))+ }+ private fun playback(block: () -> Unit): Boolean {+ lateinit var message: PlayerMessage+ instrumentation.runOnMainSync { message = native.createMessage { _, _ -> block() }.send() }+ return message.blockUntilDelivered(5_000)+ }+ fun install() {+ instrumentation.runOnMainSync {+ val renderer = (0 until native.rendererCount).map { native.getRenderer(it) }+ .first { it is androidx.media3.exoplayer.audio.MediaCodecAudioRenderer }+ val audioField = androidx.media3.exoplayer.audio.MediaCodecAudioRenderer::class.java+ .getDeclaredField("audioSink").apply { isAccessible = true }+ var current = audioField.get(renderer) as AudioSink+ repeat(5) {+ if (current !is DefaultAudioSink) {+ val delegate = current.javaClass.declaredFields.firstOrNull {+ AudioSink::class.java.isAssignableFrom(it.type)+ } ?: error("Unrecognized audio sink wrapper: ${current.javaClass.name}")+ current = delegate.apply { isAccessible = true }.get(current) as AudioSink+ }+ }+ sink = current as DefaultAudioSink+ native.addAnalyticsListener(analytics)+ }+ check(playback {+ original = checkNotNull(field.get(sink) as? AudioSink.Listener)+ proxy = Proxy.newProxyInstance(AudioSink.Listener::class.java.classLoader,+ arrayOf(AudioSink.Listener::class.java)) { _, method, args ->+ if (method.name == "onUnderrun") {+ record("audio-source", args!![0] as Int, args[1] as Long, args[2] as Long)+ }+ try { method.invoke(original, *(args ?: emptyArray())) }+ catch (error: InvocationTargetException) { throw error.targetException }+ } as AudioSink.Listener+ field.set(sink, proxy)+ check(field.get(sink) === proxy)+ }) { "Audio observer installation message was not delivered" }+ installed = true+ emit(JSONObject().put("event", "audio-observer-installed").put("sink", sink.javaClass.name))+ }+ fun drain() {+ while (true) {+ val event = pending.poll() ?: return+ emit(JSONObject().put("event", event.kind).put("eventElapsedMs", event.time)+ .put("eventThread", event.thread).put("bufferSize", event.bytes)+ .put("bufferSizeMs", event.bufferMs).put("elapsedSinceLastFeedMs", event.feedMs))+ }+ }+ fun finish() {+ // Leave the observer installed through Activity cleanup, then restore before stopping our player.+ Thread.sleep(350)+ var released = false+ instrumentation.runOnMainSync { released = native.isReleased }+ var restorationFailure: Throwable? = null+ try {+ if (installed) {+ if (released) {+ // Released players reject playback messages; restore the detached sink reference.+ check(field.get(sink) === proxy)+ field.set(sink, original)+ } else {+ check(playback { check(field.get(sink) === proxy); field.set(sink, original) }) {+ "Live audio observer restoration message was not delivered"+ }+ }+ }+ } catch (failure: Throwable) {+ restorationFailure = failure+ throw failure+ } finally {+ try {+ instrumentation.runOnMainSync { native.removeAnalyticsListener(analytics) }+ } catch (failure: Throwable) {+ restorationFailure?.addSuppressed(failure) ?: throw failure+ } finally {+ drain()+ }+ }+ emit(JSONObject().put("event", "audio-observer-restored").put("playerReleased", released))+ }+}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlaybackBufferComparisonRuntimeTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackBufferComparisonRuntimeTest.ktindex 9f55d7cc..05395893 100644--- a/app/src/androidTest/java/com/streamvault/app/ui/PlaybackBufferComparisonRuntimeTest.kt+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackBufferComparisonRuntimeTest.kt@@ -2,10 +2,20 @@ package com.streamvault.app.uiimport android.app.Applicationimport android.app.ActivityManager+import android.media.MediaCodecListimport android.os.Debug+import android.os.Buildimport android.os.SystemClock+import android.view.SurfaceView+import android.view.TextureViewimport androidx.media3.common.C+import androidx.media3.common.Timelineimport androidx.media3.common.Player as Media3Player+import androidx.media3.exoplayer.ExoPlayer+import androidx.media3.exoplayer.analytics.AnalyticsListener+import androidx.media3.exoplayer.source.LoadEventInfo+import androidx.media3.exoplayer.source.MediaLoadData+import androidx.media3.ui.PlayerViewimport androidx.test.core.app.ActivityScenarioimport androidx.test.core.app.ApplicationProviderimport androidx.test.ext.junit.runners.AndroidJUnit4@@ -14,6 +24,14 @@ import com.streamvault.app.MainActivityimport com.streamvault.domain.model.PlaybackBufferModeimport com.streamvault.domain.model.PlaybackContentKindimport com.streamvault.domain.model.DecoderMode+import com.streamvault.domain.model.PlayerSurfaceMode+import com.streamvault.domain.model.LivePlaybackIdentity+import com.streamvault.domain.model.RecordingSourceType+import com.streamvault.domain.util.LivePlaybackByteTap+import com.streamvault.data.manager.recording.HlsLiveCaptureEngine+import com.streamvault.data.manager.recording.RecordingHttpClientFactory+import com.streamvault.data.manager.recording.RecordingOutputTarget+import com.streamvault.data.manager.recording.ResolvedRecordingSourceimport com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.StreamTypeimport com.streamvault.player.PlaybackState@@ -24,11 +42,17 @@ import kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancel+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.collectimport kotlinx.coroutines.launchimport kotlinx.coroutines.runBlocking+import kotlinx.coroutines.suspendCancellableCoroutineimport kotlinx.coroutines.withTimeout+import kotlinx.coroutines.withTimeoutOrNull+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithExceptionimport org.json.JSONArrayimport org.json.JSONObjectimport org.junit.Assume.assumeTrue@@ -57,9 +81,15 @@ class PlaybackBufferComparisonRuntimeTest {val bufferMode = arguments.getString("bufferMode")?.let(PlaybackBufferMode::valueOf)?: PlaybackBufferMode.AUTO- require(bufferMode in setOf(PlaybackBufferMode.AUTO, PlaybackBufferMode.MEDIUM)) {+ require(bufferMode in setOf(PlaybackBufferMode.AUTO, PlaybackBufferMode.MEDIUM, PlaybackBufferMode.LARGE)) {"Unsupported comparison buffer mode: $bufferMode"}+ val initialBufferMode = arguments.getString("initialBufferMode")+ ?.let(PlaybackBufferMode::valueOf)+ ?: bufferMode+ require(initialBufferMode in setOf(PlaybackBufferMode.AUTO, PlaybackBufferMode.MEDIUM, PlaybackBufferMode.LARGE)) {+ "Unsupported initial comparison buffer mode: $initialBufferMode"+ }val containerExtension = arguments.getString("containerExtension")?.trim()?.removePrefix(".")@@ -74,9 +104,20 @@ class PlaybackBufferComparisonRuntimeTest {// and its post-restoration pressure window in one source session.val durationSeconds = arguments.getString("durationSeconds")?.toIntOrNull()?.coerceIn(30, 600) ?: 120+ val startupWaitTimeoutSeconds = arguments.getString("startupWaitTimeoutSeconds")+ ?.toLongOrNull()?.coerceIn(0L, 120L) ?: 45L+ val timestampWaitStackProbe = arguments.getString("timestampWaitStackProbe") == "true"+ val forceProviderSubtitleSelection = arguments.getString("forceProviderSubtitleSelection") == "true"// Development-only Stage 3 control; never write a saved decoder preference.val videoDecoderMode = arguments.getString("videoDecoderMode")?.let(DecoderMode::valueOf)+ val surfaceMode = arguments.getString("surfaceMode")?.let(PlayerSurfaceMode::valueOf)val manualVideoHeight = arguments.getString("manualVideoHeight")?.toIntOrNull()+ val tapMode = arguments.getString("tapMode") ?: "inactive"+ val recordingDelaySeconds = arguments.getString("recordingDelaySeconds")?.toLongOrNull() ?: 0L+ require(recordingDelaySeconds in 0L..90L)+ require(tapMode in setOf("inactive", "idle", "recording"))+ require(tapMode == "inactive" || streamType == StreamType.HLS && contentKind == PlaybackContentKind.LIVE)+ val liveIdentity = if (tapMode == "inactive") null else LivePlaybackIdentity(9_999_999L, 1L)val instrumentation = InstrumentationRegistry.getInstrumentation()val app = ApplicationProvider.getApplicationContext<Application>()@@ -86,32 +127,203 @@ class PlaybackBufferComparisonRuntimeTest {isAccessible = true}.get(component) as Provider<*>val engine = provider.get() as PlayerEngine+ val tap = engine.javaClass.getDeclaredField("livePlaybackByteTap").apply {+ isAccessible = true+ }.get(engine) as LivePlaybackByteTap+ fun tapSnapshot(): JSONObject {+ val registry = tap.javaClass.getDeclaredField("activeHlsSources").apply {+ isAccessible = true+ }.get(tap) as Map<*, *>+ var payload = 0L+ var playlists = 0L+ var captures = 0+ synchronized(registry) {+ registry.values.filterNotNull().forEach { session -> synchronized(session) {+ fun field(name: String) = session.javaClass.getDeclaredField(name).apply {+ isAccessible = true+ }.get(session)+ payload += (field("payloadBytes") as Int).toLong()+ playlists += (field("playlistBytes") as Int).toLong()+ captures += (field("captures") as Set<*>).size+ } }+ }+ return JSONObject().put("payloadBytes", payload).put("playlistBytes", playlists).put("captures", captures)+ }fun requestedMode(field: String) = engine.javaClass.getDeclaredField(field).apply {isAccessible = true}.get(engine) as DecoderModeval originalAudioMode = requestedMode("requestedAudioDecoderMode")val originalVideoMode = requestedMode("requestedVideoDecoderMode")+ val originalSurfaceMode = engine.javaClass.getDeclaredField("requestedSurfaceMode").apply {+ isAccessible = true+ }.get(engine) as PlayerSurfaceModeval scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)val errors = JSONArray()+ val loadDiagnostics = JSONArray()+ var diagnosticPlayer: ExoPlayer? = null+ val loadDiagnosticListener = object : AnalyticsListener {+ override fun onLoadCompleted(+ eventTime: AnalyticsListener.EventTime,+ loadEventInfo: LoadEventInfo,+ mediaLoadData: MediaLoadData+ ) {+ synchronized(loadDiagnostics) {+ loadDiagnostics.put(JSONObject()+ .put("event", "completed")+ .put("elapsedRealtimeMs", SystemClock.elapsedRealtime())+ .put("loadTaskId", loadEventInfo.loadTaskId)+ .put("bytesLoaded", loadEventInfo.bytesLoaded)+ .put("position", loadEventInfo.dataSpec.position))+ }+ }++ override fun onLoadError(+ eventTime: AnalyticsListener.EventTime,+ loadEventInfo: LoadEventInfo,+ mediaLoadData: MediaLoadData,+ error: java.io.IOException,+ wasCanceled: Boolean+ ) {+ val causes = JSONArray()+ generateSequence<Throwable>(error) { it.cause }.take(8).forEach { cause ->+ val trace = JSONArray()+ cause.stackTrace.take(12).forEach { trace.put(it.toString()) }+ val row = JSONObject().put("type", cause.javaClass.name).put("stack", trace)+ // Only retain protocol parser details, with URLs redacted. General HTTP+ // exception messages may contain provider paths or account credentials.+ if (cause is java.net.ProtocolException) {+ row.put("protocolDetail", cause.message.orEmpty()+ .replace(Regex("https?://\\S+"), "<url>").take(500))+ }+ causes.put(row)+ }+ synchronized(loadDiagnostics) {+ loadDiagnostics.put(JSONObject()+ .put("event", "error")+ .put("elapsedRealtimeMs", SystemClock.elapsedRealtime())+ .put("loadTaskId", loadEventInfo.loadTaskId)+ .put("bytesLoaded", loadEventInfo.bytesLoaded)+ .put("position", loadEventInfo.dataSpec.position)+ .put("wasCanceled", wasCanceled)+ .put("causes", causes))+ }+ }+ }+ var forcedSubtitleTrackId: String? = null+ val timestampWaitStacks = JSONArray()+ val timestampWaitStacksLock = Any()+ fun timestampWaitStackSnapshot(): JSONObject {+ val matchingThreads = JSONArray()+ Thread.getAllStackTraces().forEach { (thread, trace) ->+ val matchIndex = trace.indexOfFirst { frame ->+ frame.className == "androidx.media3.common.util.TimestampAdjuster" &&+ frame.methodName == "sharedInitializeOrWait"+ }+ if (matchIndex >= 0) {+ val frames = JSONArray()+ trace.take(32).forEach { frame ->+ frames.put(JSONObject()+ .put("class", frame.className)+ .put("method", frame.methodName)+ .put("file", frame.fileName ?: JSONObject.NULL)+ .put("line", frame.lineNumber))+ }+ matchingThreads.put(JSONObject()+ .put("name", thread.name)+ .put("state", thread.state.name)+ .put("timestampAdjusterFrameIndex", matchIndex)+ .put("stack", frames))+ }+ }+ return JSONObject()+ .put("elapsedRealtimeMs", SystemClock.elapsedRealtime())+ .put("matchingThreadCount", matchingThreads.length())+ .put("threads", matchingThreads)+ }+ var timestampWaitStackJob: kotlinx.coroutines.Job? = null+ val decoderCapabilities = mutableMapOf<String, Triple<Boolean?, Boolean?, Boolean?>>()val errorJob = scope.launchCollectErrors(engine, errors)fun <T> main(action: () -> T): T {val result = java.util.concurrent.atomic.AtomicReference<T>()instrumentation.runOnMainSync { result.set(action()) }return result.get()}+ // Public playbackParameters contains the user's requested speed, not Media3's live+ // adjustment. Read the clock/control on their owning playback thread for this probe.+ suspend fun nativeTimingSample(): JSONObject = withTimeout(2_000L) {+ suspendCancellableCoroutine { continuation ->+ main {+ val player = engine.javaClass.getDeclaredField("exoPlayer").apply {+ isAccessible = true+ }.get(engine) as androidx.media3.exoplayer.ExoPlayer+ val internalPlayer = player.javaClass.getDeclaredField("internalPlayer").apply {+ isAccessible = true+ }.get(player)+ player.createMessage { _, _ ->+ try {+ fun field(name: String) = internalPlayer.javaClass.getDeclaredField(name).apply {+ isAccessible = true+ }.get(internalPlayer)+ val control = field("livePlaybackSpeedControl") as+ androidx.media3.exoplayer.LivePlaybackSpeedControl+ val clock = field("mediaClock")+ val parameters = clock.javaClass.getDeclaredMethod("getPlaybackParameters").apply {+ isAccessible = true+ }.invoke(clock) as androidx.media3.common.PlaybackParameters+ val sample = JSONObject()+ .put("nativeClockSpeed", parameters.speed)+ .put("controlTargetLiveOffsetUs", control.targetLiveOffsetUs+ .takeUnless { it == C.TIME_UNSET } ?: JSONObject.NULL)+ if (continuation.isActive) continuation.resume(sample)+ } catch (error: Exception) {+ if (continuation.isActive) continuation.resumeWithException(error)+ }+ }.send()+ }+ }+ }+ suspend fun rendererQueueSample(): JSONObject = withTimeout(2_000L) {+ suspendCancellableCoroutine { continuation ->+ main {+ val player = engine.javaClass.getDeclaredField("exoPlayer").apply {+ isAccessible = true+ }.get(engine) as ExoPlayer+ val renderer = findVideoRenderer(player)+ player.createMessage { _, _ ->+ val snapshot = videoRendererQueueSnapshot(renderer)+ if (continuation.isActive) continuation.resume(snapshot)+ }.send()+ }+ }+ }val scenario = ActivityScenario.launch(MainActivity::class.java)var renderView: android.view.View? = nullval samples = JSONArray()val startedAt = SystemClock.elapsedRealtime()+ val gcBaseline = JSONObject(Debug.getRuntimeStats())+ val recordingBytes = java.util.concurrent.atomic.AtomicLong()+ val recordingFailure = java.util.concurrent.atomic.AtomicReference<String?>()+ var recordingJob: kotlinx.coroutines.Job? = null+ val recordingFile = java.io.File(app.filesDir, "tap-profile-$runId.ts")try {scenario.onActivity { activity ->- renderView = engine.createRenderView(activity, com.streamvault.player.PlayerSurfaceResizeMode.FIT)+ surfaceMode?.let(engine::setSurfaceMode)+ val surfaceType = if (surfaceMode == null) {+ com.streamvault.player.PlayerRenderSurfaceType.AUTO+ } else {+ engine.renderSurfaceType.value+ }+ renderView = engine.createRenderView(+ activity,+ com.streamvault.player.PlayerSurfaceResizeMode.FIT,+ surfaceType+ )activity.setContentView(renderView)engine.bindRenderView(renderView!!, com.streamvault.player.PlayerSurfaceResizeMode.FIT)}main {engine.setMediaSessionEnabled(true)- engine.setPlaybackBufferMode(bufferMode)+ engine.setPlaybackBufferMode(initialBufferMode)videoDecoderMode?.let { engine.setDecoderModes(originalAudioMode, it) }engine.prepare(StreamInfo(@@ -119,17 +331,91 @@ class PlaybackBufferComparisonRuntimeTest {title = "Stage 1 ${streamType.name} buffer fixture",streamType = streamType,containerExtension = containerExtension,- playbackContentKind = contentKind+ playbackContentKind = contentKind,+ livePlaybackIdentity = liveIdentity))+ diagnosticPlayer = engine.javaClass.getDeclaredField("exoPlayer").apply {+ isAccessible = true+ }.get(engine) as ExoPlayer+ diagnosticPlayer?.addAnalyticsListener(loadDiagnosticListener)engine.play()}- withTimeout(45_000) {- while (!engine.isPlaying.value || engine.playbackState.value != PlaybackState.READY ||- engine.playerStats.value.ttffMs <= 0L- ) delay(100)+ if (forceProviderSubtitleSelection) {+ withTimeout(15_000L) {+ while (engine.availableSubtitleTracks.value.none {+ it.subtitleSource == com.streamvault.player.SubtitleTrackSource.PROVIDER+ }) delay(100)+ }+ val subtitleTrack = engine.availableSubtitleTracks.value.first {+ it.subtitleSource == com.streamvault.player.SubtitleTrackSource.PROVIDER+ }+ main { engine.selectSubtitleTrack(subtitleTrack.id) }+ forcedSubtitleTrackId = subtitleTrack.id+ }+ if (timestampWaitStackProbe) {+ timestampWaitStackJob = scope.launch(Dispatchers.Default) {+ while (true) {+ val snapshot = timestampWaitStackSnapshot()+ synchronized(timestampWaitStacksLock) {+ timestampWaitStacks.put(snapshot)+ }+ delay(500)+ }+ }+ }+ val initialFirstFrameObserved = if (startupWaitTimeoutSeconds == 0L) {+ false+ } else {+ withTimeoutOrNull(startupWaitTimeoutSeconds * 1_000L) {+ while (!engine.isPlaying.value || engine.playbackState.value != PlaybackState.READY ||+ engine.playerStats.value.ttffMs <= 0L+ ) delay(100)+ true+ } ?: false+ }+ val initialFirstFrameAtMs = if (initialFirstFrameObserved) {+ SystemClock.elapsedRealtime() - startedAt+ } else null+ if (initialBufferMode != bufferMode && initialFirstFrameObserved) {+ main { engine.setPlaybackBufferMode(bufferMode) }+ withTimeout(45_000) {+ while (engine.playbackState.value == PlaybackState.READY &&+ engine.playerStats.value.ttffMs > 0L+ ) delay(20)+ while (!engine.isPlaying.value || engine.playbackState.value != PlaybackState.READY ||+ engine.playerStats.value.ttffMs <= 0L+ ) delay(100)+ }+ }+ val firstFrameAtMs = if (engine.playerStats.value.ttffMs > 0L) {+ SystemClock.elapsedRealtime() - startedAt+ } else null+ if (tapMode == "recording") {+ delay(recordingDelaySeconds * 1000L)+ // Exercise the production HLS recorder, requiring reuse of foreground resources.+ val forbiddenUpstream = okhttp3.OkHttpClient.Builder().addInterceptor {+ throw java.io.IOException("Unexpected duplicate upstream recording request")+ }.build()+ recordingJob = scope.launch {+ try {+ HlsLiveCaptureEngine(RecordingHttpClientFactory { forbiddenUpstream }, tap).capture(+ source = ResolvedRecordingSource(+ url = fixtureUrl, sourceType = RecordingSourceType.HLS,+ livePlaybackIdentity = liveIdentity+ ),+ outputTarget = RecordingOutputTarget.FileTarget(recordingFile),+ contentResolver = app.contentResolver,+ scheduledEndMs = System.currentTimeMillis() + durationSeconds * 1000L + 5_000L,+ onProgress = { recordingBytes.set(it.bytesWritten) }+ )+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (error: Exception) {+ recordingFailure.set(error.javaClass.simpleName + ": " + error.message)+ }+ }}- val firstFrameAtMs = SystemClock.elapsedRealtime() - startedAtmanualVideoHeight?.let { height -> main {val track = engine.availableVideoTracks.value.first { it.name.contains("${height}p") }engine.selectVideoTrack(track.id)@@ -140,19 +426,85 @@ class PlaybackBufferComparisonRuntimeTest {val decoderSample = main {val player = engine.javaClass.getDeclaredField("exoPlayer").apply {isAccessible = true- }.get(engine) as androidx.media3.exoplayer.ExoPlayer+ }.get(engine) as ExoPlayerval counters = player.videoDecoderCounterscounters?.ensureUpdated()+ val window = if (player.currentTimeline.isEmpty) null else+ player.currentTimeline.getWindow(player.currentMediaItemIndex, Timeline.Window())+ val videoFormat = player.videoFormat+ val playerView = renderView as? PlayerView+ val outputView = playerView?.videoSurfaceView+ val surfaceState = when (outputView) {+ is SurfaceView -> JSONObject()+ .put("class", outputView.javaClass.name)+ .put("attachedToWindow", outputView.isAttachedToWindow)+ .put("width", outputView.width)+ .put("height", outputView.height)+ .put("surfaceValid", runCatching { outputView.holder.surface?.isValid }+ .getOrNull() ?: JSONObject.NULL)+ is TextureView -> JSONObject()+ .put("class", outputView.javaClass.name)+ .put("attachedToWindow", outputView.isAttachedToWindow)+ .put("width", outputView.width)+ .put("height", outputView.height)+ .put("textureAvailable", outputView.isAvailable)+ null -> JSONObject().put("class", JSONObject.NULL)+ .put("attachedToWindow", JSONObject.NULL)+ else -> JSONObject()+ .put("class", outputView.javaClass.name)+ .put("attachedToWindow", outputView.isAttachedToWindow)+ }+ val rendererSnapshot = videoRendererSnapshot(player)+ val decoderName = engine.playerStats.value.videoDecoderName+ val decoderCapabilitiesForName = decoderName.takeIf { it.isNotBlank() }?.let { name ->+ decoderCapabilities.getOrPut(name) {+ runCatching {+ val codecInfo = MediaCodecList(MediaCodecList.ALL_CODECS).codecInfos+ .firstOrNull { it.name == name }+ if (codecInfo == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {+ Triple(null, null, null)+ } else {+ Triple(+ codecInfo.isHardwareAccelerated,+ codecInfo.isSoftwareOnly,+ codecInfo.isVendor+ )+ }+ }.getOrDefault(Triple(null, null, null))+ }+ }JSONObject()+ .put("requestedPlaybackSpeed", player.playbackParameters.speed)+ .put("isLoading", player.isLoading)+ .put("liveWindowDynamic", window?.isDynamic)+ .put("defaultPositionMs", window?.defaultPositionMs)+ .put("requestedMediaItemTargetOffsetMs", player.currentMediaItem?.liveConfiguration+ ?.targetOffsetMs?.takeUnless { it == C.TIME_UNSET } ?: JSONObject.NULL)+ .put("playlistTargetOffsetMs", window?.liveConfiguration?.targetOffsetMs+ ?.takeUnless { it == C.TIME_UNSET } ?: JSONObject.NULL)+ .put("playlistMinPlaybackSpeed", window?.liveConfiguration?.minPlaybackSpeed+ ?.takeUnless { it == C.RATE_UNSET } ?: JSONObject.NULL)+ .put("playlistMaxPlaybackSpeed", window?.liveConfiguration?.maxPlaybackSpeed+ ?.takeUnless { it == C.RATE_UNSET } ?: JSONObject.NULL).put("rendered", counters?.renderedOutputBufferCount)+ .put("queuedInput", counters?.queuedInputBufferCount)+ .put("skippedInput", counters?.skippedInputBufferCount).put("dropped", counters?.droppedBufferCount).put("skipped", counters?.skippedOutputBufferCount).put("droppedToKeyframe", counters?.droppedToKeyframeCount).put("maxConsecutiveDropped", counters?.maxConsecutiveDroppedBufferCount).put("decoderInitCount", counters?.decoderInitCount)- .put("frameRate", player.videoFormat?.frameRate)- .put("codecs", player.videoFormat?.codecs)- .put("colorTransfer", player.videoFormat?.colorInfo?.colorTransfer)+ .put("frameRate", videoFormat?.frameRate)+ .put("maxInputSize", videoFormat?.maxInputSize)+ .put("codecs", videoFormat?.codecs)+ .put("colorTransfer", videoFormat?.colorInfo?.colorTransfer)+ .put("videoRendererClass", rendererSnapshot.first)+ .put("videoCodecAdapterClass", rendererSnapshot.second)+ .put("decoderHardwareAccelerated", decoderCapabilitiesForName?.first ?: JSONObject.NULL)+ .put("decoderSoftwareOnly", decoderCapabilitiesForName?.second ?: JSONObject.NULL)+ .put("decoderVendor", decoderCapabilitiesForName?.third ?: JSONObject.NULL)+ .put("renderSurfaceType", engine.renderSurfaceType.value.name)+ .put("renderSurface", surfaceState).put("videoOverrideCount", player.trackSelectionParameters.overrides.values.count {it.mediaTrackGroup.type == C.TRACK_TYPE_VIDEO})@@ -166,6 +518,8 @@ class PlaybackBufferComparisonRuntimeTest {}.maxOrNull()).put("displayRefreshHz", renderView?.display?.mode?.refreshRate)}+ val nativeTiming = nativeTimingSample()+ val rendererQueue = rendererQueueSample()val memory = Debug.MemoryInfo().also { Debug.getMemoryInfo(it) }val javaAllocated = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()val liveOffsetMs = if (contentKind == PlaybackContentKind.LIVE) main {@@ -200,21 +554,50 @@ class PlaybackBufferComparisonRuntimeTest {.put("ttffMs", stats.ttffMs).put("javaAllocatedBytes", javaAllocated).put("totalPssKb", memory.totalPss)+ .put("runtimeStats", JSONObject(Debug.getRuntimeStats()))+ .put("tap", tapSnapshot())+ .put("recordingBytes", recordingBytes.get()).put("decoderCounters", decoderSample)+ .put("rendererQueue", rendererQueue)+ .put("nativeTiming", nativeTiming))delay(1_000)}+ timestampWaitStackJob?.cancelAndJoin()+ timestampWaitStackJob = nullval last = engine.playerStats.valueval result = JSONObject().put("runId", runId)+ .put("loadDiagnostics", synchronized(loadDiagnostics) { JSONArray(loadDiagnostics.toString()) }).put("fixtureUrl", fixtureUrl.replace(Regex("https?://[^/]+"), "<fixture-host>")).put("contentKind", contentKind.name).put("streamType", streamType.name).put("bufferMode", bufferMode.name)+ .put("initialBufferMode", initialBufferMode.name)+ .put("bufferModeSwitchedAfterInitialReady", initialBufferMode != bufferMode)+ .put("tapMode", tapMode)+ .put("recordingDelaySeconds", recordingDelaySeconds)+ .put("runtimeStatsBaseline", gcBaseline)+ .put("runtimeStatsFinal", JSONObject(Debug.getRuntimeStats()))+ .put("recordingBytes", recordingBytes.get())+ .put("recordingFailure", recordingFailure.get() ?: JSONObject.NULL)+ .put("recordingFile", if (tapMode == "recording") recordingFile.name else JSONObject.NULL).put("requestedVideoDecoderMode", videoDecoderMode?.name ?: originalVideoMode.name)+ .put("requestedSurfaceMode", surfaceMode?.name ?: originalSurfaceMode.name)+ .put("renderSurfaceType", engine.renderSurfaceType.value.name).put("lowRamDevice", lowRamDevice).put("durationSeconds", durationSeconds)- .put("firstFrameMs", firstFrameAtMs)+ .put("firstFrameMs", firstFrameAtMs ?: JSONObject.NULL)+ .put("initialFirstFrameMs", initialFirstFrameAtMs ?: JSONObject.NULL)+ .put("initialFirstFrameObserved", initialFirstFrameObserved)+ .put("timestampWaitStackProbeEnabled", timestampWaitStackProbe)+ .put("timestampWaitStackSamples", timestampWaitStacks)+ .put("forceProviderSubtitleSelection", forceProviderSubtitleSelection)+ .put("forcedSubtitleTrackId", forcedSubtitleTrackId ?: JSONObject.NULL)+ .put("availableSubtitleTracks", JSONArray(engine.availableSubtitleTracks.value.map { track ->+ JSONObject().put("id", track.id).put("name", track.name)+ .put("selected", track.isSelected).put("source", track.subtitleSource.name)+ })).put("finalState", engine.playbackState.value.name).put("finalIsPlaying", engine.isPlaying.value).put("finalPositionMs", engine.currentPosition.value)@@ -243,6 +626,8 @@ class PlaybackBufferComparisonRuntimeTest {.put("samples", samples)val resultJson = result.toString(2)java.io.File(app.filesDir, "buffer-comparison-$runId.json").writeText(resultJson)+ check(recordingFailure.get() == null) { "Recording failed: ${recordingFailure.get()}" }+ if (tapMode == "recording") check(recordingBytes.get() > 0) { "Shared recording produced no output" }arguments.getString("resultCallbackUrl")?.trim()?.takeIf(String::isNotEmpty)?.let { callbackUrl ->val connection = java.net.URL(callbackUrl).openConnection() as java.net.HttpURLConnectiontry {@@ -263,13 +648,17 @@ class PlaybackBufferComparisonRuntimeTest {"rebuffers=${last.rebufferCount} dropped=${last.droppedFrames} " +"size=${last.width}x${last.height} errors=${errors.length()}")} finally {+ timestampWaitStackJob?.cancelAndJoin()+ recordingJob?.cancelAndJoin()scope.cancel()errorJob.cancel()main {+ diagnosticPlayer?.removeAnalyticsListener(loadDiagnosticListener)engine.stop()engine.clearPreloadWindow()renderView?.let(engine::releaseRenderView)videoDecoderMode?.let { engine.setDecoderModes(originalAudioMode, originalVideoMode) }+ surfaceMode?.let { engine.setSurfaceMode(originalSurfaceMode) }}scenario.close()}@@ -278,4 +667,89 @@ class PlaybackBufferComparisonRuntimeTest {private fun CoroutineScope.launchCollectErrors(engine: PlayerEngine, errors: JSONArray) = launch {engine.error.collect { error -> if (error != null) synchronized(errors) { errors.put(error.javaClass.simpleName) } }}++ /** Best-effort reflection for distinguishing MediaCodec adapter queueing modes in diagnostics. */+ private fun videoRendererSnapshot(player: ExoPlayer): Pair<String?, String?> {+ val renderer = findVideoRenderer(player) ?: return null to null+ var owner: Class<*>? = renderer.javaClass+ var codecField: java.lang.reflect.Field? = null+ while (owner != null && codecField == null) {+ codecField = owner.declaredFields.firstOrNull { it.name == "codec" }+ owner = owner.superclass+ }+ val adapterClass = codecField?.let { field ->+ runCatching {+ field.isAccessible = true+ field.get(renderer)?.javaClass?.name+ }.getOrNull()+ }+ return renderer.javaClass.name to adapterClass+ }++ /** Read codec queue state on the playback thread; unavailable private fields stay null. */+ private fun videoRendererQueueSnapshot(renderer: Any?): JSONObject {+ renderer ?: return JSONObject().put("snapshotAvailable", false).put("failure", "video-renderer-unavailable")+ val failures = JSONArray()+ fun readField(target: Any?, name: String): Any? {+ if (target == null) {+ failures.put("$name:owner-null")+ return null+ }+ var owner: Class<*>? = target.javaClass+ while (owner != null) {+ val field = owner.declaredFields.firstOrNull { it.name == name }+ if (field != null) {+ return runCatching {+ field.isAccessible = true+ field.get(target)+ }.onFailure { failures.put("$name:${it.javaClass.simpleName}") }.getOrNull()+ }+ owner = owner.superclass+ }+ failures.put("$name:not-found")+ return null+ }+ val outputBufferInfo = readField(renderer, "outputBufferInfo")+ val displaySurface = readField(renderer, "displaySurface")+ val placeholderSurface = readField(renderer, "placeholderSurface")+ val result = JSONObject()+ .put("snapshotAvailable", true)+ .put("rendererClass", renderer.javaClass.name)+ .put("codecOperatingRate", readField(renderer, "codecOperatingRate") ?: JSONObject.NULL)+ .put("inputIndex", readField(renderer, "inputIndex") ?: JSONObject.NULL)+ .put("outputIndex", readField(renderer, "outputIndex") ?: JSONObject.NULL)+ .put("largestQueuedPresentationTimeUs",+ readField(renderer, "largestQueuedPresentationTimeUs") ?: JSONObject.NULL)+ .put("outputBufferInfoClass", outputBufferInfo?.javaClass?.name ?: JSONObject.NULL)+ .put("outputPresentationTimeUs",+ readField(outputBufferInfo, "presentationTimeUs") ?: JSONObject.NULL)+ .put("displaySurfaceClass", displaySurface?.javaClass?.name ?: JSONObject.NULL)+ .put("displaySurfaceValid", (displaySurface as? android.view.Surface)?.isValid ?: JSONObject.NULL)+ .put("placeholderSurfaceClass", placeholderSurface?.javaClass?.name ?: JSONObject.NULL)+ .put("placeholderSurfaceValid",+ (placeholderSurface as? android.view.Surface)?.isValid ?: JSONObject.NULL)+ if (failures.length() > 0) result.put("fieldFailures", failures)+ return result+ }++ private fun findVideoRenderer(player: ExoPlayer): Any? {+ return runCatching {+ val rendererCount = player.javaClass.methods.firstOrNull {+ it.name == "getRendererCount" && it.parameterCount == 0+ }?.invoke(player) as? Int ?: return@runCatching null+ val getRenderer = player.javaClass.methods.firstOrNull {+ it.name == "getRenderer" && it.parameterTypes.contentEquals(arrayOf(Int::class.javaPrimitiveType))+ } ?: return@runCatching null+ (0 until rendererCount).asSequence()+ .mapNotNull { index -> runCatching { getRenderer.invoke(player, index) }.getOrNull() }+ .firstOrNull { candidate ->+ val trackType = runCatching {+ candidate.javaClass.methods.firstOrNull {+ it.name == "getTrackType" && it.parameterCount == 0+ }?.invoke(candidate) as? Int+ }.getOrNull()+ trackType == C.TRACK_TYPE_VIDEO || candidate.javaClass.simpleName.contains("VideoRenderer")+ }+ }.getOrNull()+ }}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlaybackCatalogCleanupAuditTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackCatalogCleanupAuditTest.ktnew file mode 100644index 00000000..55be35be--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackCatalogCleanupAuditTest.kt@@ -0,0 +1,80 @@+package com.streamvault.app.ui++import android.app.Application+import androidx.datastore.preferences.core.edit+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.streamvault.app.benchmark.XtreamSyncBenchmarkEntryPoint+import dagger.hilt.android.EntryPointAccessors+import org.json.JSONObject+import org.junit.Assume.assumeTrue+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class PlaybackCatalogCleanupAuditTest {+ @Test fun removeOwnedCatalogOrigins() = kotlinx.coroutines.runBlocking {+ val args = InstrumentationRegistry.getArguments()+ assumeTrue(args.getString("catalogOriginCleanup") == "true")+ val ids = requireNotNull(args.getString("originCleanupIds")).split(',').map { it.toLong().also { id -> require(id > 0) } }+ val app = ApplicationProvider.getApplicationContext<Application>()+ val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)+ val origins = app.getSharedPreferences("automatic_sync_work", android.content.Context.MODE_PRIVATE)+ val policy = com.streamvault.domain.sync.AutomaticSyncSettings(movies = false, series = false, epg = false).toString()+ val keys = ids.flatMap { id ->+ check(graph.database().providerDao().getById(id) == null) { "Provider still exists" }+ check(origins.getBoolean("xtream_$id", false) && origins.getBoolean("xtream_split_queue_$id", false))+ check(origins.getString("xtream_policy_$id", null) == policy) { "Origin policy changed since fixture audit" }+ listOf("xtream_$id", "xtream_split_queue_$id", "xtream_policy_$id")+ }+ check(origins.edit().apply { keys.forEach { remove(it) } }.commit())+ check(keys.none { origins.contains(it) })+ app.filesDir.resolve("catalog-origin-cleanup.json").writeText(JSONObject().put("removedKeys", org.json.JSONArray(keys)).toString(2))+ }+ @Test fun fixtureRowsAreRemoved() {+ assumeTrue(InstrumentationRegistry.getArguments().getString("catalogCleanupAudit") == "true")+ val app = ApplicationProvider.getApplicationContext<Application>()+ val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)+ val counts = JSONObject()+ for ((name, query) in listOf(+ "providers" to "SELECT COUNT(*) FROM providers WHERE name LIKE 'In-flight catalog fixture %'",+ "configs" to "SELECT COUNT(*) FROM provider_configs WHERE identity_key LIKE 'catalog-fixture-%'",+ "guideProviders" to "SELECT COUNT(*) FROM providers WHERE name LIKE 'In-flight guide fixture %'",+ "guideConfigs" to "SELECT COUNT(*) FROM provider_configs WHERE identity_key LIKE 'epg-fixture-%'"+ )) {+ graph.database().openHelper.readableDatabase.query(query).use { cursor ->+ check(cursor.moveToFirst())+ counts.put(name, cursor.getInt(0))+ check(cursor.getInt(0) == 0) { "Owned fixture rows remain: $name" }+ }+ }+ val guideIds = InstrumentationRegistry.getArguments().getString("guideCleanupIds")+ ?.split(',')?.map { it.toLong().also { id -> require(id > 0) } }.orEmpty()+ if (guideIds.isNotEmpty()) {+ val placeholders = guideIds.joinToString(",") { "?" }+ graph.database().openHelper.readableDatabase.query(+ "SELECT COUNT(*) FROM programs WHERE provider_id IN ($placeholders)",+ guideIds.map { -it as Any }.toTypedArray()).use { cursor ->+ check(cursor.moveToFirst());counts.put("guideStages", cursor.getInt(0));check(cursor.getInt(0) == 0)+ }+ }+ app.filesDir.resolve("catalog-cleanup-audit.json").writeText(counts.toString(2))+ }+ @Test fun restoreOnlyOwnedIndexLearning() = kotlinx.coroutines.runBlocking {+ assumeTrue(InstrumentationRegistry.getArguments().getString("indexLearningCleanup") == "true")+ val app = ApplicationProvider.getApplicationContext<Application>()+ val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)+ val file = app.filesDir.resolve("index-owned-learning-cleanup.json")+ val saved = JSONObject(file.readText())+ @Suppress("UNCHECKED_CAST")+ val store = graph.preferences().javaClass.getDeclaredMethod("getPreferencesDataStore")+ .apply { isAccessible = true }.invoke(graph.preferences()) as androidx.datastore.core.DataStore<androidx.datastore.preferences.core.Preferences>+ val key = androidx.datastore.preferences.core.stringPreferencesKey("live_variant_observations")+ store.edit { values ->+ check(values[key] == saved.getString("expected")) { "Learning changed after audit; preserve current data" }+ values[key] = saved.getString("original")+ }+ check(file.delete())+ }+}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlaybackImportWorkload.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackImportWorkload.ktnew file mode 100644index 00000000..a0079a54--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackImportWorkload.kt@@ -0,0 +1,121 @@+package com.streamvault.app.ui++import android.app.Application+import android.net.Uri+import android.os.Bundle+import android.os.SystemClock+import com.streamvault.app.benchmark.XtreamSyncBenchmarkEntryPoint+import com.streamvault.domain.model.LegacyProvider+import com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.EpgRepository+import dagger.hilt.android.EntryPointAccessors+import javax.inject.Provider+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.first+import org.json.JSONObject++/** Opt-in contention probe: real import code on IO, only newly-created local providers. */+internal class PlaybackImportWorkload private constructor(+ private val app: Application,+ private val component: Any,+ private val base: String,+ private val run: String,+ private val emit: (JSONObject) -> Unit+) {+ private val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val ids = mutableListOf<Long>()+ private val jobs = mutableListOf<Deferred<Unit>>()++ private suspend fun add(kind: String): Long {+ // Distinct configurations: provider identity is derived from the playlist URL.+ val url = "$base/$kind.m3u"+ val result = graph.providers().addProvider(LegacyProvider(+ name = "Playback import fixture $run $kind", type = ProviderType.M3U,+ serverUrl = url, m3uUrl = url, isActive = false,+ epgSyncMode = ProviderEpgSyncMode.SKIP, m3uVodClassificationEnabled = true))+ check(result is Result.Success) { "Could not add disposable import provider $kind: $result" }+ ids.add(result.data)+ app.filesDir.resolve("playback-import-$run.json").writeText(+ JSONObject().put("providerIds", org.json.JSONArray(ids)).toString())+ return result.data+ }++ private suspend fun runKind(kind: String, id: Long) {+ val epg = if (kind == "epg") (component.javaClass.getDeclaredField("epgRepositoryImplProvider")+ .apply { isAccessible = true }.get(component) as Provider<*>).get() as EpgRepository else null+ // Six scheduled refreshes make overlap measurable; this is a stress workload,+ // not a claim that production normally refreshes every twenty seconds.+ val start = SystemClock.elapsedRealtime() + 10_000L+ repeat(6) { round ->+ delay((start + round * 20_000L - SystemClock.elapsedRealtime()).coerceAtLeast(0L))+ val before = SystemClock.elapsedRealtime()+ emit(JSONObject().put("event", "import-start").put("kind", kind).put("round", round))+ val result = if (kind == "epg") epg!!.refreshEpg(id, "$base/guide.xml?round=$round")+ else graph.sync().refreshPlaylistCatalog(id)+ check(result is Result.Success) { "Local $kind import failed: ${result.javaClass.simpleName}" }+ val count = if (kind == "epg") graph.database().programDao().countByProvider(id)+ else graph.database().channelDao().getByProvider(id).first().size+ check(count > 0) { "Local $kind import produced no rows" }+ emit(JSONObject().put("event", "import-end").put("kind", kind).put("round", round)+ .put("durationMs", SystemClock.elapsedRealtime() - before).put("rows", count))+ }+ }++ suspend fun close() {+ var failure: Throwable? = null+ try {+ withTimeout(180_000L) { jobs.awaitAll() }+ } catch (error: Throwable) { failure = error }+ finally {+ scope.cancel()+ jobs.forEach { it.cancelAndJoin() }+ for (id in ids) {+ graph.database().programDao().deleteByProvider(-id)+ val deleted = graph.providers().deleteProvider(id)+ check(deleted is Result.Success && graph.providers().getProvider(id) == null) {+ "Disposable provider cleanup failed: $id"+ }+ }+ emit(JSONObject().put("event", "import-cleanup").put("providersRemoved", ids.size))+ }+ failure?.let { throw it }+ }++ companion object {+ suspend fun start(app: Application, component: Any, args: Bundle, run: String,+ emit: (JSONObject) -> Unit): PlaybackImportWorkload? {+ val base = args.getString("importFixtureBase") ?: return null+ require(app.packageName.endsWith(".debug"))+ val uri = Uri.parse(base)+ require(uri.scheme == "http" && uri.host in setOf("127.0.0.1", "localhost"))+ val kinds = when (args.getString("importKinds") ?: "both") {+ "epg" -> listOf("epg")+ "catalog" -> listOf("catalog")+ "both" -> listOf("catalog", "epg")+ else -> error("importKinds must be epg, catalog, or both")+ }+ val probe = PlaybackImportWorkload(app, component, base.trimEnd('/'), run, emit)+ try {+ val providers = kinds.map { it to probe.add(it) }+ emit(JSONObject().put("event", "import-ready").put("providers", providers.size))+ for ((kind, id) in providers) {+ probe.jobs.add(probe.scope.async {+ try { probe.runKind(kind, id) }+ catch (error: Throwable) {+ emit(JSONObject().put("event", "import-error").put("kind", kind)+ .put("exception", error.javaClass.simpleName))+ throw error+ }+ })+ }+ } catch (error: Throwable) {+ probe.close()+ throw error+ }+ return probe+ }+ }+}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlaybackIndexWorkProbe.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackIndexWorkProbe.ktnew file mode 100644index 00000000..1cf21aa2--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackIndexWorkProbe.kt@@ -0,0 +1,237 @@+package com.streamvault.app.ui++import android.app.Application+import android.content.Context+import android.net.Uri+import android.os.Bundle+import androidx.datastore.core.DataStore+import androidx.datastore.preferences.core.*+import androidx.work.WorkManager+import androidx.work.WorkInfo+import com.streamvault.app.benchmark.XtreamSyncBenchmarkEntryPoint+import com.streamvault.data.local.entity.*+import com.streamvault.data.sync.XtreamIndexWorker+import com.streamvault.data.sync.StalkerIndexWorker+import com.streamvault.domain.model.*+import com.streamvault.domain.sync.AutomaticSyncActivity+import com.streamvault.domain.sync.AutomaticSyncSettings+import dagger.hilt.android.EntryPointAccessors+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.first+import org.json.JSONObject+import java.net.URL+import java.util.concurrent.TimeUnit++/** Opt-in real automatic movie/series index work; only a newly allocated fixture provider. */+internal class PlaybackIndexWorkProbe private constructor(+ private val app: Application, private val base: String, private val run: String,+ private val section: ContentType, private val emit: (JSONObject) -> Unit,+ private val providerKind: String = "xtream"+) {+ private val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)+ private val work = WorkManager.getInstance(app)+ private var id = 0L+ private var sameProvider = false+ private var deferWhileBusy = true+ private var expectDeferred = false+ private var injectSignal = false+ private var signalInjected = false+ private fun setTestSignal(active: Boolean) {+ val type=Class.forName("com.streamvault.data.remote.stalker.StalkerTrafficCoordinator")+ type.getDeclaredMethod(if(active) "notePlaybackStarted" else "notePlaybackStopped",java.lang.Long.TYPE)+ .invoke(type.getField("INSTANCE").get(null),id)+ signalInjected=active+ emit(JSONObject().put("event","index-test-signal").put("active",active).put("trafficPlaybackActive",trafficActive()))+ }+ suspend fun navigation(url: String): com.streamvault.core.navigation.PlayerNavigationRequest? {+ if (!sameProvider) return null+ val streamId = Uri.parse(url).lastPathSegment!!.substringBefore('.').toLong() - 1000L+ val row = graph.database().channelDao().getByProviderSync(id).single { it.streamId == streamId }+ val extension = Uri.parse(url).lastPathSegment!!.substringAfterLast('.').lowercase()+ require(extension in setOf("ts", "m3u8"))+ val logical = com.streamvault.data.remote.stalker.StalkerUrlFactory.buildInternalStreamUrl(id,+ com.streamvault.data.remote.stalker.StalkerStreamKind.LIVE,streamId,"ffmpeg $url",extension)+ graph.database().channelDao().updateAll(listOf(row.copy(streamUrl = logical)))+ return com.streamvault.core.navigation.PlayerNavigationRequest(streamUrl=logical,title="Local index provider fixture",+ channelId=streamId.toString(),internalId=row.id,providerId=id,contentType="LIVE")+ }+ private fun trafficActive(): Boolean {+ val type=Class.forName("com.streamvault.data.remote.stalker.StalkerTrafficCoordinator")+ return type.getDeclaredMethod("isPlaybackActive",java.lang.Long.TYPE).invoke(type.getField("INSTANCE").get(null),id) as Boolean+ }+ fun verifyPlaybackContext(providerId: Long, playbackPath: String = "MAIN") {+ if (!sameProvider) return+ check(providerId==id && AutomaticSyncActivity.hasPlayback)+ emit(JSONObject().put("event","index-same-provider-context").put("providerId",id)+ .put(if (playbackPath == "TV_INPUT") "frameworkProviderId" else "viewModelProviderId",providerId)+ .put("playbackPath",playbackPath).put("globalPlaybackOwned",true).put("trafficPlaybackActive",trafficActive()))+ if (injectSignal) setTestSignal(true)+ if (expectDeferred) check(trafficActive())+ }+ suspend fun finishAfterPlayback() {+ if (!expectDeferred) return+ withTimeout(15_000) { while (AutomaticSyncActivity.hasPlayback) delay(100) }+ if (signalInjected) setTestSignal(false)+ check(!trafficActive())+ withTimeout(90_000) { while (count()!=20_000 || graph.database().stalkerIndexJobDao().get(id,section.name)?.state!=StalkerIndexState.COMPLETE) delay(200) }+ emit(JSONObject().put("event","index-idle-resumed").put("rows",count()).put("trafficPlaybackActive",trafficActive()))+ }+ @Suppress("UNCHECKED_CAST")+ private val store = graph.preferences().javaClass.getDeclaredMethod("getPreferencesDataStore")+ .apply { isAccessible = true }.invoke(graph.preferences()) as DataStore<Preferences>+ private lateinit var original: Preferences+ private var oldOverride: AutomaticSyncSettings? = null+ private var originSnapshot: Map<String, Any?> = emptyMap()+ private val originKeys get() = listOf("stalker_$id", "stalker_split_queue_$id", "stalker_policy_$id")+ private val policy get() = AutomaticSyncSettings(live = false, movies = section == ContentType.MOVIE,+ series = section == ContentType.SERIES, epg = false, deferWhileBusy = deferWhileBusy)+ private suspend fun control(path: String) = withContext(Dispatchers.IO) {+ URL("$base/$path").openConnection().apply { connectTimeout = 5000; readTimeout = 5000 }+ .getInputStream().use { it.bufferedReader().readText() }+ }+ private suspend fun count(): Int {+ if (providerKind != "stalker") return graph.database().xtreamContentIndexDao().countActiveRows(id, section.name)+ val table = if (section == ContentType.MOVIE) "movies" else "series"+ return withContext(Dispatchers.IO) {+ graph.database().openHelper.readableDatabase.query("SELECT COUNT(*) FROM $table WHERE provider_id = ?", arrayOf(id)).use {+ check(it.moveToFirst()); it.getInt(0)+ }+ }+ }+ private suspend fun info() = withContext(Dispatchers.IO) {+ work.getWorkInfosForUniqueWork("provider-automatic-index-$id").get(30, TimeUnit.SECONDS)+ }+ suspend fun playbackReady() {+ check(AutomaticSyncActivity.hasPlayback)+ control("release")+ emit(JSONObject().put("event", "index-released").put("section", section.name).put("playbackOwned", true))+ }+ suspend fun finishWhilePlaying() {+ check(AutomaticSyncActivity.hasPlayback)+ val job = graph.database().xtreamIndexJobDao().get(id, section.name)+ val stalkerJob = if (providerKind == "stalker") graph.database().stalkerIndexJobDao().get(id, section.name) else null+ val jobState = stalkerJob?.state?.name ?: job?.state+ val rows = count()+ emit(JSONObject().put("event", "index-observed").put("providerId", id).put("section", section.name)+ .put("rows", rows).put("summaryRows", graph.database().xtreamContentIndexDao().countActiveRows(id, section.name)).put("jobState", jobState).put("cursor", stalkerJob?.nextCategoryIndex ?: job?.nextCategoryIndex)+ .put("indexedRows", stalkerJob?.indexedRows ?: job?.indexedRows).put("workStates", info().joinToString { it.state.name })+ .put("playbackOwned", true))+ if (expectDeferred) {+ check(rows in 1 until 20_000 && trafficActive()) { "Index did not defer: rows=$rows state=$jobState" }+ emit(JSONObject().put("event","index-deferred-verified").put("rows",rows).put("jobState",jobState))+ return+ }+ check(rows == 20_000 && jobState == if (providerKind == "stalker") "COMPLETE" else "SUCCESS") {+ "Index fixture incomplete: rows=$rows state=$jobState"+ }+ }+ suspend fun verifyPauseResume(engine: com.streamvault.player.PlayerEngine) {+ check(expectDeferred && !injectSignal)+ withContext(Dispatchers.Main) { engine.pause() }+ withTimeout(5_000) { while (engine.isPlaying.value) delay(50) }+ check(AutomaticSyncActivity.hasPlayback && trafficActive())+ emit(JSONObject().put("event","index-owner-paused").put("trafficPlaybackActive",true).put("globalPlaybackOwned",true))+ withContext(Dispatchers.Main) { engine.play() }+ withTimeout(5_000) { while (!trafficActive() || !engine.isPlaying.value) delay(50) }+ emit(JSONObject().put("event","index-owner-resumed").put("trafficPlaybackActive",true))+ }+ suspend fun close() {+ if (id == 0L) return+ if (signalInjected) setTestSignal(false)+ work.cancelUniqueWork("provider-automatic-index-$id").result.get(30, TimeUnit.SECONDS)+ if (providerKind == "stalker") work.cancelUniqueWork("provider-stalker-index-$id").result.get(30, TimeUnit.SECONDS)+ check(graph.providers().deleteProvider(id) is Result.Success)+ graph.preferences().setAutomaticSyncSettings(id, oldOverride)+ store.edit { values ->+ fun <T> restore(key: Preferences.Key<T>) {+ val prior = original[key]+ if (prior == null) values.remove(key) else values[key] = prior+ }+ restore(stringPreferencesKey("automatic_sync_status_$id"))+ restore(longPreferencesKey("catalog_sync_upgrade_started_$id"))+ restore(intPreferencesKey("catalog_sync_engine_$id"))+ }+ if (providerKind == "stalker") {+ val origins = app.getSharedPreferences("automatic_sync_work", Context.MODE_PRIVATE)+ origins.edit().apply { originKeys.forEach { key -> when (val old = originSnapshot[key]) {+ is Boolean -> putBoolean(key, old)+ is String -> putString(key, old)+ else -> remove(key)+ } } }.commit()+ }+ check(graph.providers().getProvider(id) == null)+ emit(JSONObject().put("event", "index-cleanup").put("providerId", id))+ }+ companion object {+ suspend fun start(app: Application, args: Bundle, run: String, emit: (JSONObject) -> Unit): PlaybackIndexWorkProbe? {+ val base = args.getString("indexFixtureBase") ?: return null+ require(app.packageName.endsWith(".debug") && Uri.parse(base).scheme == "http" &&+ Uri.parse(base).host in setOf("127.0.0.1", "localhost"))+ require(listOf("catalogFixtureBase", "inflightFixtureBase", "workerFixtureBase", "importFixtureBase").all { args.getString(it) == null })+ val section = ContentType.valueOf(requireNotNull(args.getString("indexSection")))+ require(section in setOf(ContentType.MOVIE, ContentType.SERIES))+ val kind = args.getString("indexProviderKind") ?: "xtream"+ require(kind in setOf("xtream", "stalker"))+ check(!AutomaticSyncActivity.hasPlayback)+ val probe = PlaybackIndexWorkProbe(app, base, run, section, emit, kind)+ probe.sameProvider=args.getString("indexSameProvider")=="true"+ probe.deferWhileBusy=args.getString("indexDeferWhileBusy")!="false"+ probe.expectDeferred=args.getString("indexExpectDeferred")=="true"+ probe.injectSignal=args.getString("indexInjectSignal")=="true"+ require(!probe.injectSignal || probe.expectDeferred)+ require(!probe.sameProvider || kind=="stalker")+ require(!probe.expectDeferred || probe.sameProvider)+ probe.original = probe.store.data.first()+ try {+ probe.control("reset")+ val type = if (kind == "stalker") ProviderType.STALKER_PORTAL else ProviderType.XTREAM_CODES+ probe.id = probe.graph.database().providerDao().insert(ProviderEntity(+ name = "In-flight catalog fixture index $run", type = type, isActive = false))+ if (kind == "stalker") {+ // Match production scheduler origin metadata before startup continuation observes jobs.+ val origins = app.getSharedPreferences("automatic_sync_work", Context.MODE_PRIVATE)+ probe.originSnapshot = probe.originKeys.associateWith { origins.all[it] }+ check(origins.edit().putBoolean("stalker_${probe.id}", true).commit())+ }+ probe.oldOverride = probe.graph.preferences().automaticSyncConfiguration.first().providers[probe.id]+ probe.graph.preferences().setAutomaticSyncSettings(probe.id, probe.policy.copy(enabled = false))+ val config: ProviderConfiguration = if (kind == "xtream") XtreamConfig(base, "bench_$run", "fixture",+ epgSyncMode = ProviderEpgSyncMode.SKIP) else StalkerConfig(base,+ StalkerDeviceIdentity("02:00:00:00:00:78"), epgSyncMode = ProviderEpgSyncMode.SKIP,+ catalogMode = StalkerCatalogMode.BACKGROUND_INDEX,+ transportGrant = StalkerTransportGrant(StalkerTransportMode.USER_ACCEPTED_HTTP,+ StalkerTransportOrigin("http", "127.0.0.1", Uri.parse(base).port), consentedAt = System.currentTimeMillis()))+ probe.graph.database().providerSnapshotDao().commitConfiguration(ProviderConfigEntity(+ providerId = probe.id, type = type, schemaVersion = 1,+ configurationGeneration = 1, identityKey = "catalog-fixture-index-$run",+ encryptedConfigJson = com.google.gson.Gson().toJson(config), updatedAt = System.currentTimeMillis()))+ probe.graph.database().categoryDao().insertAll((1L..4L).map {+ CategoryEntity(categoryId = it, name = "Index fixture $it", type = section, providerId = probe.id)+ })+ if (probe.sameProvider) probe.graph.database().channelDao().insertAll((1L..2L).map {+ ChannelEntity(name="Index live fixture $it",streamId=it,providerId=probe.id,streamUrl="$base/unplayed/$it.ts")+ })+ val now = System.currentTimeMillis()+ (probe.graph.preferences() as com.streamvault.data.preferences.PreferencesRepository)+ .completeCatalogSyncUpgrade(probe.id)+ probe.graph.syncMetadata().updateMetadata(SyncMetadata(probe.id,+ lastMovieSync = now, lastMovieSuccess = now, lastSeriesSync = now, lastSeriesSuccess = now))+ if (kind == "xtream") probe.graph.database().xtreamIndexJobDao().upsert(XtreamIndexJobEntity(+ providerId = probe.id, section = section.name, state = "QUEUED", totalCategories = 4, updatedAt = now))+ else probe.graph.database().stalkerIndexJobDao().upsert(StalkerIndexJobEntity(+ providerId = probe.id, section = section, state = StalkerIndexState.QUEUED, totalCategories = 4, updatedAt = now))+ app.filesDir.resolve("index-$run-owned.json").writeText(JSONObject().put("providerId", probe.id).toString())+ probe.graph.preferences().setAutomaticSyncSettings(probe.id, probe.policy)+ if (kind == "xtream") XtreamIndexWorker.enqueue(app, probe.id, section.name, force = false, automatic = true)+ else StalkerIndexWorker.enqueue(app, probe.id, section.name, force = false, automatic = true)+ withTimeout(40_000) {+ while (!JSONObject(probe.control("gate")).getBoolean("held") || probe.count() < 500) delay(100)+ }+ check(probe.info().any { it.state == WorkInfo.State.RUNNING }) { "Automatic index not running: ${probe.info().joinToString { it.state.name }}" }+ emit(JSONObject().put("event", "index-admitted-idle").put("providerId", probe.id)+ .put("section", section.name).put("rows", probe.count()).put("playbackOwned", false))+ return probe+ } catch (error: Throwable) { probe.close(); throw error }+ }+ }+}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlaybackInflightCatalogProbe.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackInflightCatalogProbe.ktnew file mode 100644index 00000000..0d10f762--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackInflightCatalogProbe.kt@@ -0,0 +1,221 @@+package com.streamvault.app.ui++import android.app.Application+import android.net.Uri+import android.os.Bundle+import androidx.datastore.core.DataStore+import androidx.datastore.preferences.core.*+import androidx.work.*+import com.streamvault.app.benchmark.XtreamSyncBenchmarkEntryPoint+import com.streamvault.data.sync.ProviderSyncWorker+import com.streamvault.domain.model.*+import com.streamvault.domain.sync.AutomaticSyncActivity+import com.streamvault.domain.sync.AutomaticSyncSettings+import dagger.hilt.android.EntryPointAccessors+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.first+import org.json.JSONObject+import java.net.URL+import java.util.UUID+import java.util.concurrent.TimeUnit++/** Held local response proves automatic work was admitted before viewing started. */+internal class PlaybackInflightCatalogProbe private constructor(+ private val app: Application, private val base: String, private val run: String,+ private val kind: String, private val emit: (JSONObject) -> Unit+) {+ private val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)+ private val work = WorkManager.getInstance(app)+ private var id = 0L+ private var workId: UUID? = null+ private var ownedRequestId: UUID? = null+ @Suppress("UNCHECKED_CAST")+ private val store = graph.preferences().javaClass.getDeclaredMethod("getPreferencesDataStore")+ .apply { isAccessible = true }.invoke(graph.preferences()) as DataStore<Preferences>+ private lateinit var original: Preferences+ private var previousOverride: AutomaticSyncSettings? = null+ private var originSnapshot: Map<String, Any?> = emptyMap()+ private val originKeys get() = listOf("${kind}_$id", "${kind}_split_queue_$id", "${kind}_policy_$id")+ private var expectYield = false+ private var deferWhileBusy = true+ private var prestageTarget = 0+ private fun stagedRows(): Int = graph.database().openHelper.readableDatabase.query(+ "SELECT COUNT(*) FROM channel_import_stage WHERE provider_id = ?", arrayOf<Any>(id)+ ).use { it.moveToFirst(); it.getInt(0) }+ private suspend fun workflowPhase(): String {+ val dao = graph.database().providerWorkflowDao()+ val workflow = dao.getWorkflow(id) ?: return "MISSING"+ return dao.getPhases(id, workflow.generation).firstOrNull { it.phase.name == "PRIMARY_CATALOG" }?.state?.name.orEmpty()+ }+ private suspend fun control(path: String): String = withContext(Dispatchers.IO) {+ URL("$base/$path").openConnection().apply { connectTimeout = 5_000; readTimeout = 5_000 }+ .getInputStream().use { it.bufferedReader().readText() }+ }+ private suspend fun info() = withContext(Dispatchers.IO) {+ work.getWorkInfoById(checkNotNull(workId)).get(30, TimeUnit.SECONDS)!!+ }+ suspend fun playbackReady() {+ check(AutomaticSyncActivity.hasPlayback)+ if (!expectYield) check(info().state == WorkInfo.State.RUNNING)+ control("release")+ emit(JSONObject().put("event", "catalog-released").put("kind", kind).put("playbackOwned", true))+ }+ suspend fun finishWhilePlaying() {+ check(AutomaticSyncActivity.hasPlayback)+ val state = info()+ val count = graph.database().channelDao().getByProvider(id).first().size+ val retainedSeed = graph.database().channelDao().getByProvider(id).first().any { it.streamId == 999_999L }+ emit(JSONObject().put("event", "catalog-observed").put("kind", kind)+ .put("workState", state.state.name).put("rows", count)+ .put("retainedSeed", retainedSeed).put("fixtureRows", count - if (retainedSeed) 1 else 0)+ .put("outcome", graph.preferences().automaticSyncStatuses.first()[id]?.outcome?.name)+ .put("playbackOwned", true))+ if (expectYield) {+ val workflow = checkNotNull(graph.database().providerWorkflowDao().getWorkflow(id))+ val metadata = graph.syncMetadata().getMetadata(id)+ val committed = graph.database().channelDao().getByProvider(id).first()+ check(count == 1 && committed.single().streamId == 999_999L && stagedRows() == 0 &&+ workflow.leaseToken == null && workflow.leaseExpiresAt == null &&+ (metadata?.lastLiveSuccess ?: 0L) == 0L && (metadata?.liveCount ?: 0) == 0 &&+ graph.preferences().automaticSyncStatuses.first()[id]?.outcome?.name == "WAITING_PLAYBACK") {+ "Deferred catalog not safely retained: rows=$count staged=${stagedRows()} phase=${workflowPhase()}"+ }+ emit(JSONObject().put("event", "catalog-yield-verified").put("rows", count)+ .put("stagedRows", stagedRows()).put("phase", workflowPhase())+ .put("leaseReleased", true).put("liveFreshnessUnchanged", true))+ return+ }+ check(state.state == WorkInfo.State.SUCCEEDED && count - (if (retainedSeed) 1 else 0) == 20_000) {+ "Catalog fixture did not finish: state=${state.state} rows=$count"+ }+ }+ suspend fun finishAfterPlayback() {+ if (!expectYield) return+ withTimeout(15_000) { while (AutomaticSyncActivity.hasPlayback) delay(100) }+ work.cancelUniqueWork("provider-automatic-check-$id").result.get(30, TimeUnit.SECONDS)+ ProviderSyncWorker.enqueueAutomaticCheck(app, id,+ AutomaticSyncSettings(movies = false, series = false, epg = false))+ withTimeout(90_000) {+ while (graph.database().channelDao().getByProvider(id).first().size != 20_000 || workflowPhase() != "SUCCEEDED") delay(200)+ }+ check(stagedRows() == 0)+ emit(JSONObject().put("event", "catalog-idle-resumed").put("rows", 20_000).put("phase", workflowPhase()))+ }+ suspend fun close() {+ if (id == 0L) return+ // Cancel only this fixture's worker; await its completion before deleting its rows.+ ownedRequestId?.let { work.cancelWorkById(it).result.get(30, TimeUnit.SECONDS) }+ graph.sync().cancelStalkerIndexSync(id)+ check(graph.providers().deleteProvider(id) is Result.Success)+ graph.preferences().setAutomaticSyncSettings(id, previousOverride)+ store.edit { values ->+ fun <T> restore(key: Preferences.Key<T>) {+ val prior = original[key]+ if (prior == null) values.remove(key) else values[key] = prior+ }+ restore(stringPreferencesKey("automatic_sync_status_$id"))+ restore(longPreferencesKey("catalog_sync_upgrade_started_$id"))+ restore(intPreferencesKey("catalog_sync_engine_$id"))+ }+ app.getSharedPreferences("automatic_sync_work", android.content.Context.MODE_PRIVATE).edit().apply {+ originKeys.forEach { key -> when (val old = originSnapshot[key]) {+ is Boolean -> putBoolean(key, old)+ is String -> putString(key, old)+ else -> remove(key)+ } }+ }.commit().also { check(it) }+ check(graph.providers().getProvider(id) == null)+ emit(JSONObject().put("event", "catalog-cleanup").put("providerId", id))+ }+ companion object {+ suspend fun start(app: Application, args: Bundle, run: String,+ emit: (JSONObject) -> Unit): PlaybackInflightCatalogProbe? {+ val base = args.getString("catalogFixtureBase") ?: return null+ val kind = requireNotNull(args.getString("catalogKind"))+ require(kind in setOf("xtream", "stalker") && app.packageName.endsWith(".debug"))+ require(Uri.parse(base).scheme == "http" && Uri.parse(base).host in setOf("127.0.0.1", "localhost"))+ require(listOf("inflightFixtureBase", "importFixtureBase", "workerFixtureBase").all { args.getString(it) == null })+ check(!AutomaticSyncActivity.hasPlayback)+ val probe = PlaybackInflightCatalogProbe(app, base, run, kind, emit)+ probe.expectYield = args.getString("catalogExpectYield") == "true"+ probe.deferWhileBusy = args.getString("catalogDefer") != "false"+ probe.prestageTarget = args.getString("catalogPrestageRows")?.toInt() ?: 0+ require(probe.prestageTarget in 0..20_000)+ probe.original = probe.store.data.first()+ val originalConfiguration = probe.graph.preferences().automaticSyncConfiguration.first()+ try {+ probe.control("reset")+ // Let the application-launch scan finish before publishing this fixture.+ // Otherwise it can claim our provider ahead of the explicitly tracked request.+ delay(2_000)+ withTimeout(30_000) {+ while (probe.work.getWorkInfosByTag(ProviderSyncWorker::class.java.name)+ .get(30, TimeUnit.SECONDS).any { it.state == WorkInfo.State.RUNNING }) delay(100)+ }+ val type = if (kind == "xtream") ProviderType.XTREAM_CODES else ProviderType.STALKER_PORTAL+ probe.id = probe.graph.database().providerDao().insert(+ com.streamvault.data.local.entity.ProviderEntity(name = "In-flight catalog fixture $run",+ type = type, isActive = false))+ val origins = app.getSharedPreferences("automatic_sync_work", android.content.Context.MODE_PRIVATE)+ probe.originSnapshot = probe.originKeys.associateWith { origins.all[it] }+ probe.previousOverride = originalConfiguration.providers[probe.id]+ probe.graph.preferences().setAutomaticSyncSettings(probe.id, AutomaticSyncSettings(enabled = false))+ val config: ProviderConfiguration = if (kind == "xtream")+ XtreamConfig(base, "bench_$run", "fixture", epgSyncMode = ProviderEpgSyncMode.SKIP)+ else StalkerConfig(base, StalkerDeviceIdentity("02:00:00:00:00:77"),+ transportGrant = StalkerTransportGrant(StalkerTransportMode.USER_ACCEPTED_HTTP,+ StalkerTransportOrigin("http", "127.0.0.1", Uri.parse(base).port), consentedAt = System.currentTimeMillis()),+ epgSyncMode = ProviderEpgSyncMode.SKIP)+ probe.graph.database().providerSnapshotDao().commitConfiguration(+ com.streamvault.data.local.entity.ProviderConfigEntity(providerId = probe.id, type = type,+ schemaVersion = 1, configurationGeneration = 1, identityKey = "catalog-fixture-$run",+ encryptedConfigJson = com.google.gson.Gson().toJson(config), updatedAt = System.currentTimeMillis()))+ if (probe.expectYield || probe.prestageTarget > 0) probe.graph.database().channelDao().insert(+ com.streamvault.data.local.entity.ChannelEntity(name = "Catalog retained fixture seed",+ providerId = probe.id, streamId = 999_999, streamUrl = "$base/retained.ts"))+ app.filesDir.resolve("catalog-$run-owned.json").writeText(JSONObject().put("providerId", probe.id).toString())+ probe.graph.preferences().setAutomaticSyncSettings(probe.id,+ AutomaticSyncSettings(movies = false, series = false, epg = false,+ deferWhileBusy = probe.deferWhileBusy))+ // Use the production unique name/KEEP policy so the automatic observer and+ // this probe converge on one request instead of competing for the lease.+ ProviderSyncWorker.enqueueAutomaticCheck(app, probe.id,+ AutomaticSyncSettings(movies = false, series = false, epg = false,+ deferWhileBusy = probe.deferWhileBusy))+ withTimeout(15_000) {+ while (probe.workId == null) {+ probe.workId = probe.work.getWorkInfosForUniqueWork("provider-automatic-check-${probe.id}")+ .get(30, TimeUnit.SECONDS).firstOrNull { !it.state.isFinished }?.id+ if (probe.workId == null) delay(100)+ }+ }+ withTimeout(30_000) {+ while (!JSONObject(probe.control("gate")).getBoolean("held")) {+ check(!probe.info().state.isFinished) { "Catalog worker finished before reaching gate" }+ delay(100)+ }+ }+ probe.ownedRequestId = probe.workId+ if (probe.info().state != WorkInfo.State.RUNNING) {+ // A concurrent global automatic scan may own the workflow lease. Track+ // that real running worker, but never cancel a request we did not create.+ val running = probe.work.getWorkInfosByTag(ProviderSyncWorker::class.java.name)+ .get(30, TimeUnit.SECONDS).filter { it.state == WorkInfo.State.RUNNING }+ check(running.size == 1) { "Ambiguous catalog worker ownership: ${running.size}" }+ probe.workId = running.single().id+ }+ emit(JSONObject().put("event", "catalog-admitted-idle").put("kind", kind)+ .put("providerId", probe.id).put("workId", probe.workId.toString())+ .put("trackedGlobalScan", probe.workId != probe.ownedRequestId)+ .put("workState", "RUNNING").put("playbackOwned", false))+ if (probe.expectYield || probe.prestageTarget > 0) {+ val target = if (probe.expectYield) 1000 else probe.prestageTarget+ withTimeout(20_000) { while (probe.stagedRows() < target) delay(100) }+ emit(JSONObject().put("event", "catalog-partially-staged").put("stagedRows", probe.stagedRows())+ .put("committedRows", probe.graph.database().channelDao().getByProvider(probe.id).first().size))+ }+ return probe+ } catch (error: Throwable) { probe.close(); throw error }+ }+ }+}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlaybackInflightEpgProbe.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackInflightEpgProbe.ktnew file mode 100644index 00000000..ec50fd8a--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackInflightEpgProbe.kt@@ -0,0 +1,434 @@+package com.streamvault.app.ui++import android.app.Application+import android.net.Uri+import android.os.Bundle+import androidx.datastore.core.DataStore+import androidx.datastore.preferences.core.*+import androidx.work.WorkInfo+import androidx.work.WorkManager+import com.streamvault.app.benchmark.XtreamSyncBenchmarkEntryPoint+import com.streamvault.data.sync.BackgroundEpgSyncWorker+import com.streamvault.domain.model.*+import com.streamvault.data.local.entity.ChannelEntity+import com.streamvault.domain.model.LegacyProvider+import com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.EpgRepository+import com.streamvault.domain.sync.AutomaticSyncActivity+import com.streamvault.domain.sync.AutomaticSyncSettings+import dagger.hilt.android.EntryPointAccessors+import java.net.URL+import java.util.UUID+import java.util.concurrent.TimeUnit+import javax.inject.Provider+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.first+import org.json.JSONArray+import org.json.JSONObject++/** Admit a real guide worker while idle, hold its response after one staged batch, then view. */+internal class PlaybackInflightEpgProbe private constructor(+ private val app: Application, private val component: Any, private val base: String,+ private val run: String, private val emit: (JSONObject) -> Unit,+ private val providerKind: String = "m3u"+) {+ private val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)+ private val work = WorkManager.getInstance(app)+ private val ids = mutableListOf<Long>()+ private var guideId = 0L+ private var manualId = 0L+ private var guideRequestId: UUID? = null+ private var sameProvider = false+ private var interruptGuide = false+ private var networkFault = false+ private var httpError = false+ private var permanentHttpError = false+ private var networkObservation: Deferred<Unit>? = null+ private var networkFirstAttempt = -1+ private var perChannel = false+ private var holdDuringCancel = false+ private val expectedPrograms get() = if (perChannel) 6001 else 100_000+ private val expectedSeedRows get() = if (perChannel) 1 else 0+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private var laneProbe: Deferred<Long>? = null+ private var prefixMetadata: SyncMetadata? = null++ suspend fun navigation(url: String): com.streamvault.core.navigation.PlayerNavigationRequest? {+ if (!sameProvider) return null+ val streamId = Uri.parse(url).lastPathSegment!!.substringBefore('.').toLong() - 1000L+ val channel = graph.database().channelDao().getByProviderSync(guideId).single { it.streamId == streamId }+ val logical = com.streamvault.data.remote.stalker.StalkerUrlFactory.buildInternalStreamUrl(+ guideId, com.streamvault.data.remote.stalker.StalkerStreamKind.LIVE, streamId, "ffmpeg $url", "m3u8")+ graph.database().channelDao().updateAll(listOf(channel.copy(streamUrl = logical)))+ return com.streamvault.core.navigation.PlayerNavigationRequest(streamUrl = logical, title = "Local provider fixture",+ channelId = streamId.toString(), internalId = channel.id, providerId = guideId, contentType = "LIVE")+ }++ private fun trafficPlaybackActive(): Boolean {+ val type = Class.forName("com.streamvault.data.remote.stalker.StalkerTrafficCoordinator")+ return type.getDeclaredMethod("isPlaybackActive", java.lang.Long.TYPE)+ .invoke(type.getField("INSTANCE").get(null), guideId) as Boolean+ }++ fun verifyPlaybackContext(providerId: Long) {+ if (!sameProvider) return+ check(providerId == guideId)+ emit(JSONObject().put("event", "stalker-same-provider-context").put("providerId", guideId)+ .put("viewModelProviderId", providerId).put("globalPlaybackOwned", AutomaticSyncActivity.hasPlayback)+ .put("trafficPlaybackActive", trafficPlaybackActive()))+ }++ private suspend fun retainedSeedRows() = graph.database().openHelper.readableDatabase.query(+ "SELECT COUNT(*) FROM programs WHERE provider_id = ? AND title = 'Portal retained seed'", arrayOf<Any>(guideId)+ ).use { it.moveToFirst(); it.getInt(0) }++ private suspend fun verifyInterrupted() {+ val state = withContext(Dispatchers.IO) { work.getWorkInfoById(checkNotNull(guideRequestId)).get(30, TimeUnit.SECONDS)!!.state }+ val metadata = graph.syncMetadata().getMetadata(guideId)+ val rows = graph.database().programDao().countByProvider(guideId)+ val stage = graph.database().programDao().countByProvider(-guideId)+ val seed = retainedSeedRows()+ val unchanged = metadata?.lastEpgSuccess == prefixMetadata?.lastEpgSuccess && metadata?.epgCount == prefixMetadata?.epgCount+ emit(JSONObject().put("event", "stalker-guide-interrupted-verified").put("programs", rows)+ .put("stagedPrograms", stage).put("oldUncoveredSeedRows", seed).put("workState", state.name)+ .put("freshnessUnchanged", unchanged))+ check(state == WorkInfo.State.CANCELLED && rows == 5001 && stage == 0 && seed == 1 && unchanged)+ }+ private var visibleDuringPlayback = -1+ private var phaseDuringPlayback = ""+ private val policy = AutomaticSyncSettings(enabled = false, live = false, movies = false, series = false, epg = true)+ @Suppress("UNCHECKED_CAST")+ private val store = graph.preferences().javaClass.getDeclaredMethod("getPreferencesDataStore")+ .apply { isAccessible = true }.invoke(graph.preferences()) as DataStore<Preferences>+ private lateinit var originalPreferences: Preferences+ private val previousOverrides = mutableMapOf<Long, AutomaticSyncSettings?>()++ private suspend fun add(kind: String): Long {+ if (providerKind in setOf("xtream", "stalker")) {+ val type = if (providerKind == "stalker") ProviderType.STALKER_PORTAL else ProviderType.XTREAM_CODES+ val id = graph.database().providerDao().insert(com.streamvault.data.local.entity.ProviderEntity(+ name = "In-flight guide fixture $run $kind", type = type, isActive = false))+ ids.add(id)+ previousOverrides[id] = graph.preferences().automaticSyncConfiguration.first().providers[id]+ graph.preferences().setAutomaticSyncSettings(id, policy)+ graph.database().providerSnapshotDao().commitConfiguration(com.streamvault.data.local.entity.ProviderConfigEntity(+ providerId = id, type = type, schemaVersion = 1,+ configurationGeneration = 1, identityKey = "epg-fixture-$run-$kind",+ encryptedConfigJson = com.google.gson.Gson().toJson(if (providerKind == "xtream") XtreamConfig(+ base, "${run}_$kind", "fixture", epgSyncMode = ProviderEpgSyncMode.BACKGROUND) else StalkerConfig(+ base, StalkerDeviceIdentity("02:00:00:00:00:79"), epgSyncMode = ProviderEpgSyncMode.BACKGROUND,+ guideSourcePolicy = GuideSourcePolicy.PROVIDER_ONLY,+ transportGrant = StalkerTransportGrant(StalkerTransportMode.USER_ACCEPTED_HTTP,+ StalkerTransportOrigin("http", "127.0.0.1", Uri.parse(base).port), consentedAt = System.currentTimeMillis()))),+ updatedAt = System.currentTimeMillis()))+ app.filesDir.resolve("inflight-$run.json").writeText(JSONObject().put("providerIds", JSONArray(ids)).toString())+ return id+ }+ val url = "$base/$kind.m3u?run=$run"+ val result = graph.providers().addProvider(LegacyProvider(+ name = "In-flight guide fixture $run $kind", type = ProviderType.M3U,+ serverUrl = url, m3uUrl = url,+ epgUrl = "$base/${if (kind == "background") "guide" else "small"}.xml?run=$run",+ epgSyncMode = ProviderEpgSyncMode.BACKGROUND, isActive = false))+ check(result is Result.Success) { "In-flight fixture provider creation failed" }+ ids.add(result.data)+ previousOverrides[result.data] = graph.preferences().automaticSyncConfiguration.first().providers[result.data]+ graph.preferences().setAutomaticSyncSettings(result.data, policy)+ app.filesDir.resolve("inflight-$run.json").writeText(JSONObject().put("providerIds", JSONArray(ids)).toString())+ return result.data+ }++ private suspend fun infos(id: Long) = withContext(Dispatchers.IO) {+ work.getWorkInfosForUniqueWork("provider-epg-$id").get(30, TimeUnit.SECONDS)+ }++ private suspend fun enqueue(id: Long, manual: Boolean = false): UUID {+ val before = infos(id).map { it.id }.toSet()+ if (manual) graph.sync().scheduleManualEpgSync(id)+ else BackgroundEpgSyncWorker.enqueue(app, id, force = true, initialDelaySeconds = 0)+ return withTimeout(15_000L) {+ var added: UUID? = null+ while (added == null) {+ added = infos(id).firstOrNull { it.id !in before }?.id+ if (added == null) delay(50L)+ }+ added+ }+ }++ private suspend fun awaitSuccess(id: UUID) = withTimeout(90_000L) {+ while (withContext(Dispatchers.IO) { work.getWorkInfoById(id).get(30, TimeUnit.SECONDS) }?.state != WorkInfo.State.SUCCEEDED) delay(200L)+ }++ private suspend fun phase(): String {+ val dao = graph.database().providerWorkflowDao()+ val workflow = dao.getWorkflow(guideId) ?: return "MISSING"+ return dao.getPhases(guideId, workflow.generation).firstOrNull { it.phase.name == "EPG" }?.state?.name.orEmpty()+ }++ private suspend fun networkSnapshot(label: String): WorkInfo {+ val info = withContext(Dispatchers.IO) {+ work.getWorkInfoById(checkNotNull(guideRequestId)).get(30, TimeUnit.SECONDS)!!+ }+ if (label == "network-first-outcome") networkFirstAttempt = info.runAttemptCount+ val metadata = graph.syncMetadata().getMetadata(guideId)+ emit(JSONObject().put("event", label).put("requestId", info.id.toString())+ .put("workState", info.state.name).put("attempt", info.runAttemptCount)+ .put("playbackOwned", AutomaticSyncActivity.hasPlayback)+ .put("programs", graph.database().programDao().countByProvider(guideId))+ .put("stagedPrograms", graph.database().programDao().countByProvider(-guideId))+ .put("phase", phase()).put("jobState", graph.database().xtreamIndexJobDao().get(guideId, "EPG")?.state)+ .put("oldSeedRows", if (providerKind == "stalker") retainedSeedRows() else -1)+ .put("metadataCount", metadata?.epgCount)+ .put("lastEpgSuccess", metadata?.lastEpgSuccess ?: 0L)+ .put("baselineLastEpgSuccess", prefixMetadata?.lastEpgSuccess ?: 0L)+ .put("freshnessUnchanged", (metadata?.lastEpgSuccess ?: 0L) == (prefixMetadata?.lastEpgSuccess ?: 0L))+ .put("freshnessAdvanced", (metadata?.lastEpgSuccess ?: 0L) > (prefixMetadata?.lastEpgSuccess ?: 0L)))+ return info+ }++ private suspend fun finishNetworkFault() {+ try {+ withTimeout(15_000L) { while (AutomaticSyncActivity.hasPlayback) delay(100L) }+ withContext(Dispatchers.IO) {+ URL("$base/recover?run=$run").openConnection().apply { connectTimeout=5000; readTimeout=5000 }+ .getInputStream().use { it.readBytes() }+ }+ emit(JSONObject().put("event", "network-source-restored").put("resubmitted", false))+ withTimeout(180_000L) {+ while (!withContext(Dispatchers.IO) {+ work.getWorkInfoById(checkNotNull(guideRequestId)).get(30, TimeUnit.SECONDS)!!.state.isFinished+ }) delay(250L)+ }+ val info = networkSnapshot("network-idle-result")+ if (permanentHttpError) {+ check(info.state == WorkInfo.State.SUCCEEDED && info.runAttemptCount == networkFirstAttempt &&+ graph.database().programDao().countByProvider(guideId) == 1 &&+ graph.database().programDao().countByProvider(-guideId) == 0 &&+ (graph.syncMetadata().getMetadata(guideId)?.lastEpgSuccess ?: 0L) ==+ (prefixMetadata?.lastEpgSuccess ?: 0L)) { "Authentication error retried or replaced cached guide" }+ return+ }+ check(info.state == WorkInfo.State.SUCCEEDED && info.runAttemptCount > 0 &&+ graph.database().programDao().countByProvider(guideId) == 100_000 &&+ graph.database().programDao().countByProvider(-guideId) == 0) { "Natural guide retry did not recover" }+ if (providerKind == "stalker") check(retainedSeedRows() == 0 &&+ graph.syncMetadata().getMetadata(guideId)?.epgCount == 100_000 &&+ (graph.syncMetadata().getMetadata(guideId)?.lastEpgSuccess ?: 0L) > (prefixMetadata?.lastEpgSuccess ?: 0L))+ } finally { cleanup() }+ }++ suspend fun playbackReady() = withContext(Dispatchers.IO) {+ check(AutomaticSyncActivity.hasPlayback)+ if (interruptGuide) {+ val cancelledAt = android.os.SystemClock.elapsedRealtime()+ work.cancelWorkById(checkNotNull(guideRequestId)).result.get(30, TimeUnit.SECONDS)+ emit(JSONObject().put("event", "stalker-guide-cancel-requested")+ .put("acknowledgedAfterMs",android.os.SystemClock.elapsedRealtime()-cancelledAt))+ if (holdDuringCancel) {+ laneProbe = scope.async {+ val manager = graph.sync()+ val locks = manager.javaClass.getDeclaredField("providerWorkLocks").apply { isAccessible = true }+ .get(manager) as com.streamvault.data.sync.ProviderWorkLockRegistry+ withTimeout(90_000L) { locks.withStalkerGuideLock(guideId) { Unit } }+ val elapsed = android.os.SystemClock.elapsedRealtime() - cancelledAt+ emit(JSONObject().put("event", "stalker-guide-cancel-lane-free").put("latencyMs", elapsed)+ .put("responseReleased", false))+ elapsed+ }+ emit(JSONObject().put("event", "stalker-guide-response-left-held").put("playbackOwned", true))+ return@withContext+ }+ }+ URL("$base/release?run=$run").openConnection().apply { connectTimeout = 5_000; readTimeout = 5_000 }+ .getInputStream().use { it.readBytes() }+ emit(JSONObject().put("event", "inflight-released").put("playbackOwned", true))+ if (networkFault) networkObservation = scope.async {+ withTimeout(60_000L) {+ while (true) {+ val info = work.getWorkInfoById(checkNotNull(guideRequestId)).get(30, TimeUnit.SECONDS)!!+ if (info.state.isFinished || (info.state == WorkInfo.State.ENQUEUED && info.runAttemptCount > 0)) break+ delay(100L)+ }+ }+ networkSnapshot("network-first-outcome")+ Unit+ }+ }++ suspend fun finishWhilePlaying() {+ check(AutomaticSyncActivity.hasPlayback)+ if (interruptGuide) { laneProbe?.await(); verifyInterrupted(); return }+ if (networkFault) {+ try { networkObservation?.await() } catch (e: TimeoutCancellationException) {+ emit(JSONObject().put("event", "network-first-outcome-timeout"))+ }+ networkSnapshot("network-during-playback")+ return+ }+ visibleDuringPlayback = graph.database().programDao().countByProvider(guideId)+ phaseDuringPlayback = phase()+ emit(JSONObject().put("event", "inflight-observed").put("playbackOwned", true)+ .put("visiblePrograms", visibleDuringPlayback).put("stagedPrograms", graph.database().programDao().countByProvider(-guideId))+ .put("phase", phaseDuringPlayback))+ if (providerKind in setOf("xtream", "stalker")) {+ val stage = graph.database().programDao().countByProvider(-guideId)+ val job = graph.database().xtreamIndexJobDao().get(guideId, "EPG")+ emit(JSONObject().put("event", if (providerKind == "stalker") "stalker-guide-observed" else "xtream-guide-observed").put("programs", visibleDuringPlayback)+ .put("stagedPrograms", stage).put("phase", phaseDuringPlayback).put("jobState", job?.state))+ if (providerKind == "stalker") {+ val state = withContext(Dispatchers.IO) {+ work.getWorkInfoById(checkNotNull(guideRequestId)).get(30, TimeUnit.SECONDS)!!.state+ }+ val metadata = graph.syncMetadata().getMetadata(guideId)+ val seed = graph.database().openHelper.readableDatabase.query(+ "SELECT COUNT(*) FROM programs WHERE provider_id = ? AND title = 'Portal retained seed'",+ arrayOf<Any>(guideId)).use { it.moveToFirst(); it.getInt(0) }+ emit(JSONObject().put("event", "stalker-guide-completion-verified").put("programs", visibleDuringPlayback)+ .put("stagedPrograms", stage).put("workState", state.name).put("oldCoveredSeedRows", seed)+ .put("metadataCount", metadata?.epgCount).put("freshnessAdvanced", (metadata?.lastEpgSuccess ?: 0L) > 0L)+ .put("ownership", "UNIQUE_WORKER_GUIDE_MUTEX").put("guideShape", if(perChannel) "PER_CHANNEL" else "BULK").put("expectedSeedRows",expectedSeedRows))+ check(visibleDuringPlayback == expectedPrograms && stage == 0 && seed == expectedSeedRows && state == WorkInfo.State.SUCCEEDED &&+ metadata?.epgCount == expectedPrograms && (metadata.lastEpgSuccess ?: 0L) > 0L) { "Native guide incomplete" }+ return+ }+ check(visibleDuringPlayback == 100_000 && stage == 0 && phaseDuringPlayback == "SUCCEEDED") {+ "Xtream guide did not finish: visible=$visibleDuringPlayback staged=$stage phase=$phaseDuringPlayback"+ }+ return+ }+ awaitSuccess(enqueue(manualId, manual = true))+ check(graph.database().programDao().countByProvider(manualId) == 1000)+ graph.preferences().setAutomaticSyncSettings(manualId, policy.copy(deferWhileBusy = false))+ awaitSuccess(enqueue(manualId))+ emit(JSONObject().put("event", "inflight-manual-optout-success").put("playbackOwned", true))+ }++ suspend fun finishAfterPlayback() {+ if (networkFault) { finishNetworkFault(); return }+ if (interruptGuide) {+ try {+ withTimeout(15_000L) { while (AutomaticSyncActivity.hasPlayback) delay(100L) }+ guideRequestId = enqueue(guideId)+ awaitSuccess(checkNotNull(guideRequestId))+ val rows = graph.database().programDao().countByProvider(guideId)+ val metadata = graph.syncMetadata().getMetadata(guideId)+ check(rows == expectedPrograms && retainedSeedRows() == expectedSeedRows && metadata?.epgCount == expectedPrograms &&+ (metadata.lastEpgSuccess ?: 0L) > (prefixMetadata?.lastEpgSuccess ?: 0L))+ emit(JSONObject().put("event", "stalker-guide-idle-repair-verified").put("programs", rows)+ .put("freshnessAdvanced", true).put("oldCoveredSeedRows", retainedSeedRows()))+ } finally { cleanup() }+ return+ }+ if (providerKind in setOf("xtream", "stalker")) { cleanup(); return }+ try {+ withTimeout(15_000L) { while (AutomaticSyncActivity.hasPlayback) delay(100L) }+ awaitSuccess(enqueue(guideId))+ check(graph.database().programDao().countByProvider(guideId) == 100_000)+ check(graph.database().programDao().countByProvider(-guideId) == 0)+ emit(JSONObject().put("event", "inflight-idle-success").put("phase", phase()).put("programs", 100_000))+ } finally { cleanup() }+ check(visibleDuringPlayback == 1 && phaseDuringPlayback == "PENDING") {+ "In-flight guide continued during playback: visible=$visibleDuringPlayback phase=$phaseDuringPlayback"+ }+ }++ private suspend fun cleanup() {+ if (holdDuringCancel) withContext(Dispatchers.IO) {+ URL("$base/close-held").openConnection().apply { connectTimeout=5000;readTimeout=5000 }+ .getInputStream().use { it.readBytes() }+ }+ scope.cancel()+ for (id in ids) {+ BackgroundEpgSyncWorker.cancel(app, id)+ graph.database().programDao().deleteByProvider(-id)+ graph.providers().deleteProvider(id)+ graph.preferences().setAutomaticSyncSettings(id, previousOverrides[id])+ store.edit { values ->+ fun <T> restore(key: Preferences.Key<T>) {+ val previous = originalPreferences[key]+ if (previous == null) values.remove(key) else values[key] = previous+ }+ restore(stringPreferencesKey("automatic_sync_status_$id"))+ restore(longPreferencesKey("catalog_sync_upgrade_started_$id"))+ restore(intPreferencesKey("catalog_sync_engine_$id"))+ }+ check(graph.providers().getProvider(id) == null)+ }+ emit(JSONObject().put("event", "inflight-cleanup").put("providersRemoved", ids.size))+ }++ companion object {+ suspend fun start(app: Application, component: Any, args: Bundle, run: String,+ emit: (JSONObject) -> Unit): PlaybackInflightEpgProbe? {+ val base = args.getString("inflightFixtureBase") ?: return null+ require(args.getString("workerFixtureBase") == null && args.getString("importFixtureBase") == null)+ require(Uri.parse(base).host in setOf("127.0.0.1", "localhost") && app.packageName.endsWith(".debug"))+ check(!AutomaticSyncActivity.hasPlayback)+ val kind = args.getString("inflightProviderKind") ?: "m3u"+ require(kind in setOf("m3u", "xtream", "stalker"))+ val probe = PlaybackInflightEpgProbe(app, component, base, run, emit, kind)+ probe.networkFault = args.getString("inflightNetworkFault") == "true"+ probe.httpError = args.getString("inflightHttpError") == "true"+ probe.permanentHttpError = args.getString("inflightPermanentHttpError") == "true"+ require(!probe.httpError || probe.networkFault)+ require(!probe.permanentHttpError || probe.httpError)+ require(!probe.networkFault || kind in setOf("xtream", "stalker"))+ probe.perChannel = args.getString("inflightGuideShape") == "perChannel"+ probe.holdDuringCancel = args.getString("inflightHoldDuringCancel") == "true"+ require(!probe.perChannel || kind == "stalker")+ probe.sameProvider = args.getString("inflightSameProvider") == "true"+ probe.interruptGuide = args.getString("inflightInterrupt") == "true"+ require(!probe.sameProvider || kind == "stalker")+ require(!probe.interruptGuide || probe.sameProvider)+ require(!probe.holdDuringCancel || probe.interruptGuide)+ probe.originalPreferences = probe.store.data.first()+ try {+ probe.guideId = probe.add("background")+ if (kind != "stalker") probe.manualId = probe.add("manual")+ if (kind == "stalker") {+ probe.graph.database().channelDao().insertAll((1L..(if (probe.perChannel) 4L else 2000L)).map {+ ChannelEntity(name = "Portal guide fixture $it", streamId = it, epgChannelId = it.toString(),+ streamUrl = "$base/unplayed/$it.ts", providerId = probe.guideId)+ })+ }+ val epg = (component.javaClass.getDeclaredField("epgRepositoryImplProvider").apply { isAccessible = true }+ .get(component) as Provider<*>).get() as EpgRepository+ check(epg.refreshEpg(probe.guideId, "$base/seed.xml?run=$run") is Result.Success)+ check(probe.graph.database().programDao().countByProvider(probe.guideId) == 1)+ probe.prefixMetadata = probe.graph.syncMetadata().getMetadata(probe.guideId)+ probe.guideRequestId = probe.enqueue(probe.guideId)+ withTimeout(if (kind == "stalker") 90_000L else 30_000L) {+ if (probe.httpError) {+ withContext(Dispatchers.IO) {+ while (true) {+ val state = URL("$base/gate?run=$run").openConnection()+ .apply { connectTimeout=5000; readTimeout=5000 }.getInputStream()+ .use { JSONObject(it.bufferedReader().readText()) }+ if (state.optBoolean("requestSeen")) break+ delay(100L)+ }+ }+ } else while (probe.graph.database().programDao().countByProvider(+ if (kind == "stalker") probe.guideId else -probe.guideId) < 5000) delay(100L)+ }+ emit(JSONObject().put("event", "inflight-admitted").put("playbackOwned", AutomaticSyncActivity.hasPlayback)+ .put("providerIds", JSONArray(probe.ids))+ .put("visiblePrograms", probe.graph.database().programDao().countByProvider(probe.guideId))+ .put("stagedPrograms", probe.graph.database().programDao().countByProvider(-probe.guideId)))+ if (kind == "stalker") {+ val seed = probe.graph.database().openHelper.readableDatabase.query(+ "SELECT COUNT(*) FROM programs WHERE provider_id = ? AND title = 'Portal retained seed'",+ arrayOf<Any>(probe.guideId)).use { it.moveToFirst(); it.getInt(0) }+ probe.prefixMetadata = probe.graph.syncMetadata().getMetadata(probe.guideId)+ check(seed == 1 && probe.infos(probe.guideId).any { it.state == WorkInfo.State.RUNNING })+ emit(JSONObject().put("event", "stalker-guide-prefix-verified").put("oldUncoveredGuideRetained", true)+ .put("programs", probe.graph.database().programDao().countByProvider(probe.guideId)))+ }+ } catch (error: Throwable) { probe.cleanup(); throw error }+ return probe+ }+ }+}diff --git a/app/src/androidTest/java/com/streamvault/app/ui/PlaybackWorkerAdmissionProbe.kt b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackWorkerAdmissionProbe.ktnew file mode 100644index 00000000..820f8683--- /dev/null+++ b/app/src/androidTest/java/com/streamvault/app/ui/PlaybackWorkerAdmissionProbe.kt@@ -0,0 +1,231 @@+package com.streamvault.app.ui++import android.app.Application+import android.net.Uri+import android.os.Bundle+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkInfo+import androidx.work.WorkManager+import androidx.work.workDataOf+import androidx.datastore.core.DataStore+import androidx.datastore.preferences.core.Preferences+import androidx.datastore.preferences.core.edit+import com.streamvault.app.benchmark.XtreamSyncBenchmarkEntryPoint+import com.streamvault.data.sync.BackgroundEpgSyncWorker+import com.streamvault.data.sync.ProviderSyncWorker+import com.streamvault.domain.model.LegacyProvider+import com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.Result+import com.streamvault.domain.sync.AutomaticSyncActivity+import com.streamvault.domain.sync.AutomaticSyncSettings+import dagger.hilt.android.EntryPointAccessors+import java.util.UUID+import java.util.concurrent.TimeUnit+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.first+import org.json.JSONArray+import org.json.JSONObject++/** Actual WorkManager admission, with small local fixtures and only disposable provider IDs. */+internal class PlaybackWorkerAdmissionProbe private constructor(+ private val app: Application, private val base: String, private val run: String,+ private val emit: (JSONObject) -> Unit,+ private val observeUnownedTvInput: Boolean = false+) {+ private val graph = EntryPointAccessors.fromApplication(app, XtreamSyncBenchmarkEntryPoint::class.java)+ private val work = WorkManager.getInstance(app)+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val ids = mutableListOf<Long>()+ private val catalogWorkIds = mutableListOf<UUID>()+ private lateinit var observation: Deferred<Unit>+ private var epgId = 0L+ private var catalogId = 0L+ private var normalRows = -1+ private var normalAttempts = -1+ private var repairRows = -1+ private var repairAttempts = -1+ private var automaticRows = -1+ private var automaticOutcome = ""+ private var epgWorkId: UUID? = null+ private val epgPolicy = AutomaticSyncSettings(live = false, movies = false, series = false, epg = true)+ @Suppress("UNCHECKED_CAST")+ private val store = graph.preferences().javaClass.getDeclaredMethod("getPreferencesDataStore")+ .apply { isAccessible = true }.invoke(graph.preferences()) as DataStore<Preferences>+ private lateinit var originalPreferences: Preferences++ private fun verifyOwnership() {+ check(AutomaticSyncActivity.hasPlayback == !observeUnownedTvInput)+ }++ private suspend fun add(kind: String): Long {+ val url = "$base/$kind.m3u?run=$run"+ val result = graph.providers().addProvider(LegacyProvider(+ name = "Worker admission fixture $run $kind", type = ProviderType.M3U,+ serverUrl = url, m3uUrl = url, epgUrl = "$base/guide.xml?run=$run",+ isActive = false, epgSyncMode = ProviderEpgSyncMode.BACKGROUND))+ check(result is Result.Success) { "Disposable worker provider setup failed: $result" }+ ids.add(result.data)+ graph.preferences().setAutomaticSyncSettings(result.data, if (kind == "epg") epgPolicy+ else AutomaticSyncSettings(movies = false, series = false, epg = false))+ app.filesDir.resolve("worker-probe-$run.json").writeText(+ JSONObject().put("providerIds", JSONArray(ids)).toString())+ return result.data+ }++ private suspend fun enqueueCatalog() {+ val request = OneTimeWorkRequestBuilder<ProviderSyncWorker>()+ .setInputData(workDataOf("automatic_provider_id" to catalogId)).build()+ catalogWorkIds.add(request.id)+ withContext(Dispatchers.IO) { work.enqueue(request).result.get(30, TimeUnit.SECONDS) }+ }++ private suspend fun epgIds(): Set<UUID> = withContext(Dispatchers.IO) {+ work.getWorkInfosForUniqueWork("provider-epg-$epgId").get(30, TimeUnit.SECONDS).map { it.id }.toSet()+ }++ private suspend fun awaitNewEpg(previous: Set<UUID>) = withTimeout(15_000L) {+ while (true) {+ val added = epgIds() - previous+ if (added.isNotEmpty()) { epgWorkId = added.single(); break }+ delay(50L)+ }+ }++ private suspend fun epgInfo(): WorkInfo = withContext(Dispatchers.IO) {+ requireNotNull(work.getWorkInfoById(requireNotNull(epgWorkId)).get(30, TimeUnit.SECONDS))+ }++ private suspend fun enqueueRepair() {+ val previous = epgIds()+ enqueueBackground(force = true, delaySeconds = 0)+ awaitNewEpg(previous)+ }++ private fun enqueueBackground(force: Boolean, delaySeconds: Long) {+ // One test APK can probe both the released signature and the added intent flag.+ val companion = BackgroundEpgSyncWorker.Companion+ val method = companion.javaClass.methods.single { it.name == "enqueue" }+ val parameters = if (method.parameterCount == 5) arrayOf(app, epgId, force, delaySeconds, false)+ else arrayOf(app, epgId, force, delaySeconds)+ method.invoke(companion, *parameters)+ }++ private suspend fun checkpoint(phase: String): Pair<Int, Int> {+ val info = epgInfo()+ val rows = graph.database().programDao().countByProvider(epgId)+ val outcome = graph.preferences().automaticSyncStatuses.first()[catalogId]?.outcome?.name.orEmpty()+ val channels = graph.database().channelDao().getByProvider(catalogId).first().size+ emit(JSONObject().put("event", "worker-checkpoint").put("phase", phase)+ .put("playbackOwned", AutomaticSyncActivity.hasPlayback).put("epgRows", rows)+ .put("epgWorkState", info.state.name).put("epgAttempts", info.runAttemptCount)+ .put("automaticCatalogRows", channels).put("automaticOutcome", outcome))+ if (phase == "repair-during-playback") { automaticRows = channels; automaticOutcome = outcome }+ return rows to info.runAttemptCount+ }++ private suspend fun awaitEpgSuccess() = withTimeout(60_000L) {+ while (epgInfo().state != WorkInfo.State.SUCCEEDED) delay(200L)+ check(graph.database().programDao().countByProvider(epgId) == 1000)+ }++ suspend fun finishWhilePlaying() {+ observation.await()+ verifyOwnership()+ if (observeUnownedTvInput) return+ // Exercise the real settings action, not a direct refresh/import API.+ val previous = epgIds()+ graph.sync().scheduleManualEpgSync(epgId)+ awaitNewEpg(previous)+ awaitEpgSuccess()+ emit(JSONObject().put("event", "worker-manual-success").put("playbackOwned", AutomaticSyncActivity.hasPlayback))+ // A user who explicitly permits overlap retains that choice.+ graph.preferences().setAutomaticSyncSettings(epgId, epgPolicy.copy(deferWhileBusy = false))+ enqueueRepair()+ awaitEpgSuccess()+ emit(JSONObject().put("event", "worker-optout-success").put("playbackOwned", AutomaticSyncActivity.hasPlayback))+ graph.preferences().setAutomaticSyncSettings(epgId, epgPolicy)+ }++ suspend fun finishAfterPlayback() {+ try {+ withTimeout(15_000L) { while (AutomaticSyncActivity.hasPlayback) delay(100L) }+ // Resubmit only this probe's jobs to test eligibility without waiting out backoff.+ catalogWorkIds.forEach { work.cancelWorkById(it).result.get(30, TimeUnit.SECONDS) }+ enqueueCatalog()+ withTimeout(60_000L) {+ while (graph.database().channelDao().getByProvider(catalogId).first().isEmpty()) delay(200L)+ }+ enqueueRepair()+ awaitEpgSuccess()+ emit(JSONObject().put("event", "worker-idle-success").put("playbackOwned", AutomaticSyncActivity.hasPlayback))+ } finally {+ scope.cancel()+ if (::observation.isInitialized) observation.cancelAndJoin()+ catalogWorkIds.forEach { work.cancelWorkById(it).result.get(30, TimeUnit.SECONDS) }+ for (id in ids) {+ BackgroundEpgSyncWorker.cancel(app, id)+ graph.database().programDao().deleteByProvider(-id)+ check(graph.providers().deleteProvider(id) is Result.Success)+ graph.preferences().setAutomaticSyncSettings(id, null)+ check(graph.providers().getProvider(id) == null)+ }+ store.edit { values ->+ val owned = ids.flatMap { id -> listOf("automatic_sync_status_$id",+ "catalog_sync_upgrade_started_$id", "catalog_sync_engine_$id") }.toSet()+ for (key in values.asMap().keys.filter { it.name in owned }) {+ @Suppress("UNCHECKED_CAST")+ val typed = key as Preferences.Key<Any>+ val old = originalPreferences[typed]+ if (old == null) values.remove(typed) else values[typed] = old+ }+ }+ emit(JSONObject().put("event", "worker-cleanup").put("providersRemoved", ids.size))+ }+ if (observeUnownedTvInput) {+ check(normalRows == 1000 && repairRows == 1000 && automaticRows == 20) {+ "Unowned TV-input observation mismatch: normal=$normalRows repair=$repairRows catalog=$automaticRows"+ }+ return+ }+ check(normalRows == 0 && repairRows == 0 && normalAttempts > 0 && repairAttempts > 0) {+ "Background EPG overlapped playback: normalRows=$normalRows repairRows=$repairRows"+ }+ check(automaticRows == 0 && automaticOutcome == "WAITING_PLAYBACK") {+ "Automatic catalog did not defer: rows=$automaticRows outcome=$automaticOutcome"+ }+ }++ companion object {+ suspend fun start(app: Application, args: Bundle, run: String,+ emit: (JSONObject) -> Unit): PlaybackWorkerAdmissionProbe? {+ val base = args.getString("workerFixtureBase") ?: return null+ val uri = Uri.parse(base)+ require(app.packageName.endsWith(".debug") && uri.scheme == "http" &&+ uri.host in setOf("127.0.0.1", "localhost"))+ require(args.getString("fixtureUrls")!!.split(',').size == 1)+ val probe = PlaybackWorkerAdmissionProbe(app, base.trimEnd('/'), run, emit,+ args.getString("workerObserveUnownedTvInput") == "true")+ probe.originalPreferences = probe.store.data.first()+ probe.epgId = probe.add("epg")+ probe.catalogId = probe.add("catalog")+ probe.observation = probe.scope.async {+ delay(10_000L)+ probe.verifyOwnership()+ val previous = probe.epgIds()+ probe.enqueueBackground(force = false, delaySeconds = 30) // Normal scheduling delay.+ probe.awaitNewEpg(previous)+ probe.enqueueCatalog()+ emit(JSONObject().put("event", "worker-enqueued").put("playbackOwned", AutomaticSyncActivity.hasPlayback))+ delay(55_000L)+ val normal = probe.checkpoint("normal-during-playback")+ probe.normalRows = normal.first; probe.normalAttempts = normal.second+ probe.enqueueRepair()+ delay(55_000L)+ val repair = probe.checkpoint("repair-during-playback")+ probe.repairRows = repair.first; probe.repairAttempts = repair.second+ }+ return probe+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt b/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.ktindex d0fcc023..8a4aa87c 100644--- a/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt+++ b/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt@@ -12,10 +12,15 @@ import android.os.Looperimport android.util.Logimport android.view.Surfaceimport androidx.media3.common.MediaItem+import androidx.media3.common.C+import androidx.media3.common.PlaybackExceptionimport androidx.media3.common.Playerimport androidx.media3.datasource.DataSourceimport androidx.media3.datasource.okhttp.OkHttpDataSourceimport androidx.media3.exoplayer.ExoPlayer+import androidx.media3.exoplayer.analytics.AnalyticsListener+import androidx.media3.exoplayer.source.LoadEventInfo+import androidx.media3.exoplayer.source.MediaLoadDataimport androidx.media3.exoplayer.dash.DashMediaSourceimport androidx.media3.exoplayer.hls.HlsMediaSourceimport androidx.media3.exoplayer.rtsp.RtspMediaSource@@ -26,20 +31,31 @@ import com.streamvault.domain.model.Channelimport com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.util.BoundedExpiringCacheimport com.streamvault.domain.model.StreamType+import com.streamvault.domain.model.PlaybackContentKind+import com.streamvault.domain.sync.AutomaticSyncActivity+import com.streamvault.player.playback.LiveStartupWatchdog+import com.streamvault.player.playback.PlaybackTransferTracker+import com.streamvault.player.playback.StartupRefreshGate+import com.streamvault.player.playback.LiveMpegTsEndRecoveryimport com.streamvault.domain.repository.ChannelRepositoryimport com.streamvault.player.playback.applyUnsafeTlsBypassimport com.streamvault.player.playback.applyPlaybackTransportPolicy+import com.streamvault.player.playback.applyPlaybackTimestampInitializationPolicy+import com.streamvault.player.playback.applyPlaybackRenditionLoadingPolicyimport dagger.hilt.android.AndroidEntryPointimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.launch+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActiveimport kotlinx.coroutines.withContextimport java.net.InetSocketAddressimport java.net.Proxyimport okhttp3.OkHttpClientimport javax.inject.Inject+import java.io.IOException@AndroidEntryPointclass StreamVaultTvInputService : TvInputService() {@@ -61,31 +77,198 @@ class StreamVaultTvInputService : TvInputService() {override fun onCreateSession(inputId: String): Session = StreamVaultSession(this)private inner class StreamVaultSession(context: Context) : Session(context) {+ private val playbackOwner = Any()+ private var tunedProviderId: Long? = nullprivate val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)+ private val startupWatchdog = LiveStartupWatchdog()+ private val startupTransfers = PlaybackTransferTracker()+ private val startupRefreshGate = StartupRefreshGate()+ private val endRecovery = LiveMpegTsEndRecovery()+ private val surfaceRecovery = LiveMpegTsEndRecovery()+ private var surfaceRecoveryGeneration: Long? = null+ private var endRecoveryGeneration: Long? = null+ private val pendingLoadRetries = mutableSetOf<Long>()+ private var startupStream: StreamInfo? = null+ private var firstVideoFrame = false+ private var outputSurface: Surface? = null+ private var startupTerminal = false+ private var tuneGeneration = 0Lprivate val player: ExoPlayer = ExoPlayer.Builder(context).build().apply {addListener(object : Player.Listener {+ override fun onRenderedFirstFrame() { firstVideoFrame = true }++ override fun onPlayerError(error: PlaybackException) {+ if (Log.isLoggable(TAG, Log.DEBUG)) Log.d(TAG,+ "lifecycle event=player-error code=${error.errorCode} surfaceValid=${outputSurface?.isValid} stream=${startupStream != null} terminal=$startupTerminal")+ val info = startupStream ?: return+ if (startupTerminal || startupRefreshGate.isPending || endRecovery.isPending || surfaceRecovery.isPending) return+ val eligible = canRecoverTvInputSurfaceError(info, inferStreamType(info), firstVideoFrame,+ player.playWhenReady, pendingLoadRetries.isNotEmpty(), outputSurface != null, error.errorCode)+ if (surfaceRecovery.onEnded(android.os.SystemClock.elapsedRealtime(), eligible)) {+ surfaceRecoveryGeneration = tuneGeneration+ AutomaticSyncActivity.stopped(playbackOwner)+ notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING)+ Log.i(TAG, "surface-recovery awaiting-surface attempt=1")+ player.stop()+ return+ }+ startupTerminal = true+ AutomaticSyncActivity.stopped(playbackOwner)+ notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN)+ }+override fun onPlaybackStateChanged(playbackState: Int) {when (playbackState) {Player.STATE_READY -> notifyVideoAvailable()Player.STATE_BUFFERING -> notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING)- Player.STATE_IDLE, Player.STATE_ENDED -> Unit+ Player.STATE_ENDED -> handleStreamEnded()+ Player.STATE_IDLE -> Unit}}})+ addAnalyticsListener(object : AnalyticsListener {+ override fun onLoadError(eventTime: AnalyticsListener.EventTime, loadEventInfo: LoadEventInfo,+ mediaLoadData: MediaLoadData, error: IOException, wasCanceled: Boolean) {+ if (wasCanceled) pendingLoadRetries.remove(loadEventInfo.loadTaskId)+ else pendingLoadRetries.add(loadEventInfo.loadTaskId)+ }++ override fun onLoadCompleted(eventTime: AnalyticsListener.EventTime,+ loadEventInfo: LoadEventInfo, mediaLoadData: MediaLoadData) {+ pendingLoadRetries.remove(loadEventInfo.loadTaskId)+ }++ override fun onLoadCanceled(eventTime: AnalyticsListener.EventTime,+ loadEventInfo: LoadEventInfo, mediaLoadData: MediaLoadData) {+ pendingLoadRetries.remove(loadEventInfo.loadTaskId)+ }+ })}private val mainHandler = Handler(Looper.getMainLooper())+ init {+ scope.launch {+ while (isActive) {+ delay(1_000L)+ val info = startupStream+ // Opt-in diagnostics for the separate Android TV input player. Avoid+ // URLs, provider identifiers and credentials in playback health logs.+ if (info != null && Log.isLoggable(TAG, Log.DEBUG)) {+ val counters = player.videoDecoderCounters+ Log.d(TAG, "health generation=$tuneGeneration state=${player.playbackState}" ++ " playing=${player.isPlaying} positionMs=${player.currentPosition}" ++ " bufferedMs=${player.totalBufferedDuration} firstFrame=$firstVideoFrame" ++ " rendered=${counters?.renderedOutputBufferCount ?: 0}" ++ " dropped=${counters?.droppedBufferCount ?: 0}" ++ " error=${player.playerError?.errorCode}")+ }+ if (surfaceRecovery.isPending) {+ when (surfaceRecovery.evaluate(+ android.os.SystemClock.elapsedRealtime(),+ canResume = info != null && !startupTerminal &&+ surfaceRecoveryGeneration == tuneGeneration && player.playWhenReady &&+ outputSurface?.isValid == true,+ hasActiveTransfers = startupTransfers.hasActiveTransfers+ )) {+ StartupRefreshGate.Action.READY -> info?.let {+ Log.i(TAG, "surface-recovery transfers-drained refresh=1")+ prepareStream(it, preserveEpisode = true)+ }+ StartupRefreshGate.Action.GIVE_UP -> {+ Log.w(TAG, "surface-recovery abandoned reason=transfers-not-drained")+ failStartup()+ }+ StartupRefreshGate.Action.WAIT -> Unit+ }+ continue+ }+ if (endRecovery.isPending) {+ when (endRecovery.evaluate(+ android.os.SystemClock.elapsedRealtime(),+ canResume = info != null && !startupTerminal &&+ endRecoveryGeneration == tuneGeneration && player.playWhenReady &&+ outputSurface?.isValid == true,+ hasActiveTransfers = startupTransfers.hasActiveTransfers+ )) {+ StartupRefreshGate.Action.READY -> info?.let {+ Log.i(TAG, "live-ts-end transfers-drained refresh=1")+ prepareStream(it, preserveEpisode = true)+ }+ StartupRefreshGate.Action.GIVE_UP -> {+ Log.w(TAG, "live-ts-end refresh-abandoned reason=transfers-not-drained")+ failStartup()+ }+ StartupRefreshGate.Action.WAIT -> Unit+ }+ continue+ }+ if (startupRefreshGate.isPending) {+ when (startupRefreshGate.evaluate(+ android.os.SystemClock.elapsedRealtime(),+ canResume = info != null && !startupTerminal && player.playWhenReady && outputSurface?.isValid == true,+ hasActiveTransfers = startupTransfers.hasActiveTransfers+ )) {+ StartupRefreshGate.Action.READY -> info?.let { prepareStream(it, true) }+ StartupRefreshGate.Action.GIVE_UP -> failStartup()+ StartupRefreshGate.Action.WAIT -> Unit+ }+ continue+ }+ val action = startupWatchdog.evaluate(+ nowMs = android.os.SystemClock.elapsedRealtime(),+ eligible = info != null && !startupTerminal &&+ info.drmInfo == null && inferStreamType(info) != StreamType.RTSP &&+ info.playbackContentKind !in setOf(PlaybackContentKind.ON_DEMAND, PlaybackContentKind.CATCH_UP) &&+ outputSurface?.isValid == true && player.playWhenReady && player.playerError == null &&+ player.playbackState in setOf(Player.STATE_BUFFERING, Player.STATE_READY) &&+ pendingLoadRetries.isEmpty(),+ firstVideoFrameRendered = firstVideoFrame,+ audioOnlyPlaying = player.isPlaying && !player.currentTracks.isTypeSelected(C.TRACK_TYPE_VIDEO),+ bufferedDurationMs = player.totalBufferedDuration,+ sourceRetryAlreadyUsed = endRecovery.hasAttempted+ )+ if (action == LiveStartupWatchdog.Action.NONE || info == null) continue+ Log.w("StreamVaultTvInput", "startup-watchdog action=$action")+ if (action == LiveStartupWatchdog.Action.REFRESH_SOURCE) {+ startupRefreshGate.begin(android.os.SystemClock.elapsedRealtime())+ player.stop()+ } else {+ failStartup()+ }+ }+ }+ }+override fun onTune(channelUri: Uri): Boolean {+ val generation = ++tuneGeneration+ startupStream = null+ startupTerminal = false+ startupWatchdog.reset()+ surfaceRecovery.reset()+ surfaceRecoveryGeneration = null+ startupRefreshGate.clear()+ endRecovery.reset()+ endRecoveryGeneration = nullnotifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING)scope.launch {- tune(channelUri)+ tune(channelUri, generation)}return true}override fun onSetSurface(surface: Surface?): Boolean {+ if (Log.isLoggable(TAG, Log.DEBUG)) Log.d(TAG,+ "lifecycle event=set-surface-begin newPresent=${surface != null} newValid=${surface?.isValid} oldPresent=${outputSurface != null} oldValid=${outputSurface?.isValid}")+ if (outputSurface !== surface) {+ startupWatchdog.pauseClock()+ startupRefreshGate.pauseClock()+ endRecovery.pauseClock()+ surfaceRecovery.pauseClock()+ }+ outputSurface = surfaceplayer.setVideoSurface(surface)+ if (Log.isLoggable(TAG, Log.DEBUG)) Log.d(TAG, "lifecycle event=set-surface-end")return true}@@ -96,24 +279,38 @@ class StreamVaultTvInputService : TvInputService() {override fun onSetCaptionEnabled(enabled: Boolean) = Unitoverride fun onRelease() {+ if (Log.isLoggable(TAG, Log.DEBUG)) Log.d(TAG,+ "lifecycle event=release-begin surfacePresent=${outputSurface != null} surfaceValid=${outputSurface?.isValid}")+ AutomaticSyncActivity.stopped(playbackOwner)+ tuneGeneration+++ startupStream = null+ surfaceRecovery.reset()+ surfaceRecoveryGeneration = null+ startupRefreshGate.clear()+ endRecovery.reset()+ endRecoveryGeneration = nullscope.cancel()player.release()+ if (Log.isLoggable(TAG, Log.DEBUG)) Log.d(TAG, "lifecycle event=release-end")}- private suspend fun tune(channelUri: Uri) {+ private suspend fun tune(channelUri: Uri, generation: Long) {val channelRef = withContext(Dispatchers.IO) { loadChannelRef(channelUri) }+ if (generation != tuneGeneration) returnif (channelRef == null) {notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN)return}val channel = channelRepository.getChannel(channelRef.channelId)+ if (generation != tuneGeneration) returnif (channel == null) {notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN)return}val streamInfo = channelRepository.getStreamInfo(channel).getOrNull()+ if (generation != tuneGeneration) returnif (streamInfo == null) {notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN)return@@ -121,17 +318,69 @@ class StreamVaultTvInputService : TvInputService() {notifyContentAllowed()notifyChannelRetuned(channelUri)- val mediaSource = buildMediaSource(streamInfo)- player.setMediaSource(mediaSource)+ tunedProviderId = channel.providerId+ prepareStream(streamInfo, preserveEpisode = false)+ }++ private fun prepareStream(streamInfo: StreamInfo, preserveEpisode: Boolean) {+ surfaceRecovery.reset(preserveAttempt = preserveEpisode)+ surfaceRecoveryGeneration = null+ startupRefreshGate.clear()+ endRecovery.reset(preserveAttempt = preserveEpisode)+ endRecoveryGeneration = null+ startupStream = streamInfo+ startupTerminal = false+ firstVideoFrame = false+ pendingLoadRetries.clear()+ startupWatchdog.reset(preserveEpisode)+ // This player bypasses Media3PlayerEngine; own its background-sync signal+ // for the whole tune, including buffering and drain-safe source refreshes.+ AutomaticSyncActivity.started(playbackOwner, tunedProviderId)+ player.setMediaSource(buildMediaSource(streamInfo))player.prepare()player.playWhenReady = true}+ private fun failStartup() {+ surfaceRecovery.reset(preserveAttempt = true)+ surfaceRecoveryGeneration = null+ startupRefreshGate.clear()+ endRecovery.reset(preserveAttempt = true)+ endRecoveryGeneration = null+ startupTerminal = true+ player.playWhenReady = false+ player.stop()+ AutomaticSyncActivity.stopped(playbackOwner)+ notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN)+ }++ private fun handleStreamEnded() {+ val info = startupStream ?: return+ if (startupTerminal || endRecovery.isPending) return+ val eligible = canRecoverTvInputEnd(info, inferStreamType(info), firstVideoFrame,+ player.playWhenReady, pendingLoadRetries.isNotEmpty() || startupRefreshGate.isPending)+ if (endRecovery.onEnded(android.os.SystemClock.elapsedRealtime(), eligible)) {+ endRecoveryGeneration = tuneGeneration+ Log.w(TAG, "live-ts-end refresh-requested attempt=1")+ notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_TUNING)+ player.stop()+ } else {+ Log.w(TAG, "live-ts-end terminal eligible=$eligible exhausted=${endRecovery.hasAttempted}")+ startupTerminal = true+ player.playWhenReady = false+ AutomaticSyncActivity.stopped(playbackOwner)+ notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN)+ }+ }+private fun buildMediaSource(streamInfo: StreamInfo): MediaSource {val streamType = inferStreamType(streamInfo)val mediaItem = MediaItem.fromUri(streamInfo.url)return when (streamType) {- StreamType.HLS -> HlsMediaSource.Factory(buildHttpDataSource(streamInfo)).createMediaSource(mediaItem)+ StreamType.HLS -> HlsMediaSource.Factory(buildHttpDataSource(streamInfo))+ .applyPlaybackTimestampInitializationPolicy(streamInfo.playbackContentKind)+ .applyPlaybackRenditionLoadingPolicy(streamInfo.playbackContentKind)+ .createMediaSource(mediaItem)StreamType.DASH -> DashMediaSource.Factory(buildHttpDataSource(streamInfo)).createMediaSource(mediaItem)StreamType.SMOOTH_STREAMING -> SsMediaSource.Factory(buildHttpDataSource(streamInfo)).createMediaSource(mediaItem)StreamType.RTSP -> RtspMediaSource.Factory().createMediaSource(mediaItem)@@ -142,10 +391,13 @@ class StreamVaultTvInputService : TvInputService() {}private fun buildHttpDataSource(streamInfo: StreamInfo): DataSource.Factory {- return OkHttpDataSource.Factory(okHttpClient.forPlayback(streamInfo)).apply {+ val factory = OkHttpDataSource.Factory(okHttpClient.forPlayback(streamInfo)).apply {setUserAgent(streamInfo.userAgent ?: DEFAULT_USER_AGENT)setDefaultRequestProperties(streamInfo.headers)}+ return if (streamInfo.playbackContentKind !in setOf(PlaybackContentKind.ON_DEMAND, PlaybackContentKind.CATCH_UP) &&+ streamInfo.drmInfo == null && inferStreamType(streamInfo) != StreamType.RTSP+ ) startupTransfers.wrap(factory) else factory}private fun inferStreamType(streamInfo: StreamInfo): StreamType {diff --git a/app/src/main/java/com/streamvault/app/tvinput/TvInputEndRecoveryPolicy.kt b/app/src/main/java/com/streamvault/app/tvinput/TvInputEndRecoveryPolicy.ktnew file mode 100644index 00000000..3568eb05--- /dev/null+++ b/app/src/main/java/com/streamvault/app/tvinput/TvInputEndRecoveryPolicy.kt@@ -0,0 +1,22 @@+package com.streamvault.app.tvinput++import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import com.streamvault.player.playback.ResolvedStreamType+import com.streamvault.player.playback.canRecoverLiveMpegTsEnd++/** TV input owns its source directly. Keep unknown/progressive/finite sources out of live EOF recovery. */+internal fun canRecoverTvInputEnd(+ info: StreamInfo?,+ type: StreamType,+ firstVideoFrame: Boolean,+ playWhenReady: Boolean,+ retryPending: Boolean+): Boolean = canRecoverLiveMpegTsEnd(+ streamInfo = info,+ streamType = if (type == StreamType.MPEG_TS) ResolvedStreamType.MPEG_TS_LIVE else ResolvedStreamType.UNKNOWN,+ playbackStarted = firstVideoFrame,+ playWhenReady = playWhenReady,+ hasIndependentSourceOwner = false,+ retryPending = retryPending+)diff --git a/app/src/main/java/com/streamvault/app/tvinput/TvInputSurfaceRecoveryPolicy.kt b/app/src/main/java/com/streamvault/app/tvinput/TvInputSurfaceRecoveryPolicy.ktnew file mode 100644index 00000000..6076051b--- /dev/null+++ b/app/src/main/java/com/streamvault/app/tvinput/TvInputSurfaceRecoveryPolicy.kt@@ -0,0 +1,17 @@+package com.streamvault.app.tvinput++import androidx.media3.common.PlaybackException+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType++/** Restrict surface-loss repair to the directly owned clear live HTTP TS path we measured. */+internal fun canRecoverTvInputSurfaceError(+ info: StreamInfo?,+ type: StreamType,+ firstVideoFrame: Boolean,+ playWhenReady: Boolean,+ retryPending: Boolean,+ surfacePresent: Boolean,+ errorCode: Int+): Boolean = errorCode == PlaybackException.ERROR_CODE_DECODING_FAILED && !surfacePresent &&+ canRecoverTvInputEnd(info, type, firstVideoFrame, playWhenReady, retryPending)diff --git a/app/src/test/java/com/streamvault/app/tvinput/TvInputEndRecoveryPolicyTest.kt b/app/src/test/java/com/streamvault/app/tvinput/TvInputEndRecoveryPolicyTest.ktnew file mode 100644index 00000000..68bbb62e--- /dev/null+++ b/app/src/test/java/com/streamvault/app/tvinput/TvInputEndRecoveryPolicyTest.kt@@ -0,0 +1,57 @@+package com.streamvault.app.tvinput++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.PlaybackContentKind+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import com.streamvault.domain.model.DrmInfo+import com.streamvault.domain.model.DrmScheme+import org.junit.Test+import com.streamvault.player.playback.LiveMpegTsEndRecovery+import com.streamvault.player.playback.LiveStartupWatchdog++class TvInputEndRecoveryPolicyTest {+ private val live = StreamInfo("http://fixture.test/raw.ts", playbackContentKind = PlaybackContentKind.LIVE)+ private fun eligible(info: StreamInfo? = live, type: StreamType = StreamType.MPEG_TS,+ frame: Boolean = true, requested: Boolean = true, retry: Boolean = false) =+ canRecoverTvInputEnd(info, type, frame, requested, retry)++ @Test fun `only explicit HTTP live TS with rendered video can recover`() {+ assertThat(eligible()).isTrue()+ assertThat(eligible(live.copy(url = "https://fixture.test/raw.ts"))).isTrue()+ assertThat(eligible(frame = false)).isFalse()+ assertThat(eligible(requested = false)).isFalse()+ assertThat(eligible(retry = true)).isFalse()+ assertThat(eligible(null)).isFalse()+ }++ @Test fun `other source types and finite ownership never reopen on end`() {+ StreamType.entries.filter { it != StreamType.MPEG_TS }.forEach { assertThat(eligible(type = it)).isFalse() }+ listOf(PlaybackContentKind.UNKNOWN, PlaybackContentKind.ON_DEMAND, PlaybackContentKind.CATCH_UP).forEach {+ assertThat(eligible(live.copy(playbackContentKind = it))).isFalse()+ }+ }++ @Test fun `DRM RTSP local and invalid sources remain excluded`() {+ assertThat(eligible(live.copy(drmInfo = DrmInfo(DrmScheme.WIDEVINE, "https://license.test/")))).isFalse()+ listOf("rtsp://fixture.test/live", "file:///recording.ts", "content://recording/1", "invalid URI").forEach {+ assertThat(eligible(live.copy(url = it))).isFalse()+ }+ }++ @Test fun `spent EOF attempt prevents a second startup source refresh`() {+ val end = LiveMpegTsEndRecovery()+ assertThat(end.onEnded(0, eligible())).isTrue()+ end.reset(preserveAttempt = true)+ val startup = LiveStartupWatchdog()+ fun evaluate(time: Long) = startup.evaluate(time, eligible = true,+ firstVideoFrameRendered = false, audioOnlyPlaying = false, bufferedDurationMs = 0,+ sourceRetryAlreadyUsed = end.hasAttempted)+ assertThat(evaluate(0)).isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(evaluate(45_000)).isEqualTo(LiveStartupWatchdog.Action.GIVE_UP)+ end.reset()+ startup.reset()+ assertThat(evaluate(50_000)).isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(evaluate(95_000)).isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)+ }+}diff --git a/app/src/test/java/com/streamvault/app/tvinput/TvInputSurfaceRecoveryPolicyTest.kt b/app/src/test/java/com/streamvault/app/tvinput/TvInputSurfaceRecoveryPolicyTest.ktnew file mode 100644index 00000000..1d08596e--- /dev/null+++ b/app/src/test/java/com/streamvault/app/tvinput/TvInputSurfaceRecoveryPolicyTest.kt@@ -0,0 +1,84 @@+package com.streamvault.app.tvinput++import androidx.media3.common.PlaybackException+import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.DrmInfo+import com.streamvault.domain.model.DrmScheme+import com.streamvault.domain.model.PlaybackContentKind+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import com.streamvault.player.playback.LiveMpegTsEndRecovery+import com.streamvault.player.playback.StartupRefreshGate+import org.junit.Test++class TvInputSurfaceRecoveryPolicyTest {+ private val liveTs = StreamInfo(+ url = "http://fixture.test/live.ts",+ playbackContentKind = PlaybackContentKind.LIVE+ )++ private fun eligible(+ info: StreamInfo? = liveTs,+ type: StreamType = StreamType.MPEG_TS,+ firstFrame: Boolean = true,+ playWhenReady: Boolean = true,+ retryPending: Boolean = false,+ surfacePresent: Boolean = false,+ errorCode: Int = PlaybackException.ERROR_CODE_DECODING_FAILED+ ) = canRecoverTvInputSurfaceError(+ info = info,+ type = type,+ firstVideoFrame = firstFrame,+ playWhenReady = playWhenReady,+ retryPending = retryPending,+ surfacePresent = surfacePresent,+ errorCode = errorCode+ )++ @Test+ fun `only a decoded live HTTP TS surface-loss error is eligible`() {+ assertThat(eligible()).isTrue()+ assertThat(eligible(liveTs.copy(url = "https://fixture.test/live.ts"))).isTrue()+ assertThat(eligible(surfacePresent = true)).isFalse()+ assertThat(eligible(errorCode = PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED)).isFalse()+ assertThat(eligible(info = null)).isFalse()+ assertThat(eligible(type = StreamType.HLS)).isFalse()+ assertThat(eligible(type = StreamType.RTSP)).isFalse()+ assertThat(eligible(type = StreamType.PROGRESSIVE)).isFalse()+ }++ @Test+ fun `startup pause retry DRM and non-live content remain ineligible`() {+ assertThat(eligible(firstFrame = false)).isFalse()+ assertThat(eligible(playWhenReady = false)).isFalse()+ assertThat(eligible(retryPending = true)).isFalse()+ assertThat(eligible(liveTs.copy(playbackContentKind = PlaybackContentKind.UNKNOWN))).isFalse()+ assertThat(eligible(liveTs.copy(playbackContentKind = PlaybackContentKind.ON_DEMAND))).isFalse()+ assertThat(eligible(liveTs.copy(playbackContentKind = PlaybackContentKind.CATCH_UP))).isFalse()+ assertThat(eligible(liveTs.copy(drmInfo = DrmInfo(DrmScheme.WIDEVINE, "https://license.test/")))).isFalse()+ assertThat(eligible(liveTs.copy(url = "rtsp://fixture.test/live.ts"))).isFalse()+ assertThat(eligible(liveTs.copy(url = "file:///recording.ts"))).isFalse()+ }++ @Test+ fun `eligible surface repair reuses one-shot drain and quiet gate`() {+ val recovery = LiveMpegTsEndRecovery()++ assertThat(recovery.onEnded(0L, eligible = eligible())).isTrue()+ assertThat(recovery.isPending).isTrue()+ assertThat(recovery.evaluate(1_000L, canResume = true, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(recovery.evaluate(2_000L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(recovery.evaluate(2_499L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(recovery.evaluate(2_500L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.READY)+ assertThat(recovery.isPending).isFalse()++ recovery.reset(preserveAttempt = true)+ assertThat(recovery.onEnded(3_000L, eligible = eligible())).isFalse()+ recovery.reset()+ assertThat(recovery.onEnded(4_000L, eligible = eligible())).isTrue()+ }+}diff --git a/data/src/main/java/com/streamvault/data/local/dao/ProviderWorkflowDao.kt b/data/src/main/java/com/streamvault/data/local/dao/ProviderWorkflowDao.ktindex 49579661..7225499f 100644--- a/data/src/main/java/com/streamvault/data/local/dao/ProviderWorkflowDao.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/ProviderWorkflowDao.kt@@ -601,6 +601,18 @@ abstract class ProviderWorkflowDao {) == 1}+ @Transaction+ open suspend fun defer(lease: ProviderWorkflowLease, now: Long): Boolean {+ if (ownsLease(lease.providerId, lease.generation, lease.phase, lease.token) != 1) return false+ check(finishPhase(+ lease.providerId, lease.generation, lease.phase, ProviderWorkflowPhaseState.PENDING,+ getCheckpoint(lease.providerId, lease.generation, lease.phase), null, null, now+ ) == 1)+ return finishWorkflowOwnership(+ lease.providerId, lease.generation, lease.token, ProviderWorkflowState.PENDING, null, null, now+ ) == 1+ }+@Transactionopen suspend fun fail(lease: ProviderWorkflowLease,diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.ktindex 5a3d003b..95646c1f 100644--- a/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt@@ -235,6 +235,7 @@ class HlsLiveCaptureEngine @Inject constructor(}}var lastWrittenMapIdentity: String? = null+ var sharedRecordingStarted = falseval byteRangeState = HlsByteRangeState()var lastDataAt = System.currentTimeMillis()while (kotlinx.coroutines.currentCoroutineContext().isActive && System.currentTimeMillis() < scheduledEndMs) {@@ -322,6 +323,7 @@ class HlsLiveCaptureEngine @Inject constructor(// Cache key bytes by URI so rotated keys are fetched once eachval keyCache = mutableMapOf<String, ByteArray>()var newSegmentsThisRound = false+ val skippedBeforeStart = ArrayList<String>()for (segment in playlist.segments) {kotlinx.coroutines.currentCoroutineContext().ensureActive()val rangeIdentity = segment.byteRange?.let { "@${it.offset}:${it.length}" }.orEmpty()@@ -336,7 +338,17 @@ class HlsLiveCaptureEngine @Inject constructor(segmentRangeLength)val bytes = if (activeCapture != null) {- capturedSegment?.bytes ?: break+ if (capturedSegment == null) {+ // The foreground player may already have downloaded the+ // beginning of this live window before recording attached.+ // Choose the first available post-attachment segment once;+ // after writing starts, every missing segment must be awaited.+ if (!sharedRecordingStarted) {+ skippedBeforeStart += segmentIdentity+ continue+ } else break+ }+ capturedSegment.bytes} else {try {fetchBytes(segment.uri, headers, client, source, segment.byteRange)@@ -416,6 +428,10 @@ class HlsLiveCaptureEngine @Inject constructor(}capturedMap?.let { activeCapture?.consume(it) }sink.write(payload)+ if (activeCapture != null && !sharedRecordingStarted) {+ seenSegments.addAll(skippedBeforeStart)+ sharedRecordingStarted = true+ }seenSegments += segmentIdentitycapturedSegment?.let { activeCapture?.consume(it) }bytesWritten += payload.sizediff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.ktindex 49129f2f..ae6274aa 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt@@ -366,7 +366,7 @@ class StalkerRequestCoordinator internal constructor(val backgroundBlocked = lowPriority &&(state.interactiveWaiters > 0 || state.interactiveInFlight > 0)val adaptiveIndex = adaptiveIndexingEnabled && priority == StalkerNetworkPriority.INDEX- val playbackActive = StalkerTrafficCoordinator.isPlaybackActive(providerId)+ val playbackActive = StalkerTrafficCoordinator.shouldDeferIndexForPlayback(providerId)val indexWait = if (adaptiveIndex && playbackActive) NETWORK_ADMISSION_POLL_MILLIS else 0Lval indexWindowFull = adaptiveIndex && state.indexNetworkInFlight >=(if (playbackActive) 1 else state.indexLimit())@@ -449,7 +449,7 @@ class StalkerRequestCoordinator internal constructor(val state = states[permit.providerId] ?: returnstate.mutex.withLock {val changed = when {- error == null -> state.indexPacing.success(StalkerTrafficCoordinator.isPlaybackActive(permit.providerId))+ error == null -> state.indexPacing.success(StalkerTrafficCoordinator.shouldDeferIndexForPlayback(permit.providerId))error.isProviderStressSignal() -> state.indexPacing.stress()else -> { state.indexPacing.resetHealth(); false }}diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.ktindex 955ae0b8..ea5062be 100644--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt@@ -1,6 +1,8 @@package com.streamvault.data.remote.stalkerimport com.streamvault.data.BuildConfig+import com.streamvault.data.sync.AutomaticSyncExecution+import com.streamvault.domain.sync.AutomaticSyncActivityimport java.util.concurrent.ConcurrentHashMapinternal object StalkerTrafficCoordinator {@@ -26,7 +28,7 @@ internal object StalkerTrafficCoordinator {}fun isPlaybackActive(providerId: Long): Boolean =- providerId > 0L && (activePlaybackCountsByProvider[providerId] ?: 0) > 0+ providerId > 0L && (hasExplicitPlaybackMarker(providerId) || AutomaticSyncActivity.isProviderPlaybackActive(providerId))fun forgetProvider(providerId: Long) {if (providerId > 0L) activePlaybackCountsByProvider.remove(providerId)@@ -41,13 +43,21 @@ internal object StalkerTrafficCoordinator {// Every wire request, including page-base probes, is paced by network admission.0L} else- if (isPlaybackActive(providerId)) {+ if (shouldDeferIndexForPlayback(providerId)) {PLAYBACK_BACKGROUND_PAGE_DELAY_MILLIS} else {NORMAL_BACKGROUND_PAGE_DELAY_MILLIS}- fun shouldDeferIndexForPlayback(providerId: Long): Boolean = isPlaybackActive(providerId)+ fun shouldDeferIndexForPlayback(providerId: Long): Boolean =+ hasExplicitPlaybackMarker(providerId) || (+ AutomaticSyncExecution.automatic.get() == true &&+ AutomaticSyncExecution.policy.get()?.deferWhileBusy != false &&+ AutomaticSyncActivity.isProviderPlaybackActive(providerId)+ )++ private fun hasExplicitPlaybackMarker(providerId: Long): Boolean =+ providerId > 0L && (activePlaybackCountsByProvider[providerId] ?: 0) > 0internal fun resetForTests() {activePlaybackCountsByProvider.clear()diff --git a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.ktindex d7a4cb46..87f6af90 100644--- a/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/EpgRepositoryImpl.kt@@ -298,7 +298,13 @@ class EpgRepositoryImpl @Inject constructor("EpgRepository","EPG request failed for provider $providerId (${request.safeRequestIdentitySummary(providerRequestProfile)}): HTTP ${response.code}")- return@withLock Result.error("Failed to download EPG: HTTP ${response.code}")+ val message = "Failed to download EPG: HTTP ${response.code}"+ // Preserve transient HTTP failures through the guide executor's result wrapper.+ // Authentication and other permanent client errors must not enter retry backoff.+ val cause = if (response.code == 408 || response.code == 429 || response.code in 500..599) {+ IOException(message)+ } else null+ return@withLock Result.error(message, cause)}val contentLength = response.header("Content-Length")?.toLongOrNull() ?: -1Ldiff --git a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgExecution.kt b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgExecution.ktindex c4ffb8bb..cd51671e 100644--- a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgExecution.kt+++ b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgExecution.kt@@ -1,6 +1,57 @@package com.streamvault.data.syncimport com.streamvault.domain.model.ProviderType+import kotlinx.coroutines.CoroutineStart+import kotlinx.coroutines.NonCancellable+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.firstOrNull+import kotlinx.coroutines.selects.select+import kotlinx.coroutines.supervisorScope+import kotlinx.coroutines.withContext++internal fun canYieldInflightGuide(providerType: ProviderType?, userInitiated: Boolean): Boolean =+ // M3U XMLTV has an atomic staged swap. Xtream job metadata and Stalker incremental+ // writes need separate interruption coverage before enabling this for those paths.+ !userInitiated && providerType == ProviderType.M3U++/** Cancel only the import child, allowing the workflow owner to release its lease normally. */+internal suspend fun runGuideWithPlaybackYield(+ enabled: Boolean,+ shouldDefer: Flow<Boolean>,+ sync: suspend () -> ProviderWorkflowOutcome+): ProviderWorkflowOutcome {+ if (!enabled) return sync()+ return supervisorScope {+ val viewing = async(start = CoroutineStart.UNDISPATCHED) {+ if (shouldDefer.firstOrNull { it } != true) awaitCancellation()+ }+ val importing = async { sync() }+ try {+ select {+ importing.onAwait { it }+ viewing.onAwait {+ importing.cancelAndJoin()+ ProviderWorkflowOutcome.Deferred+ }+ }+ } finally {+ withContext(NonCancellable) {+ viewing.cancelAndJoin()+ importing.cancelAndJoin()+ }+ }+ }+}++/** Freshness overrides do not imply user intent: background repair still yields to viewing. */+internal fun shouldDeferBackgroundEpgForPlayback(+ userInitiated: Boolean,+ deferWhileBusy: Boolean,+ playbackActive: Boolean+): Boolean = !userInitiated && deferWhileBusy && playbackActive/** Stalker guide work is owned by its unique worker and guide mutex, independently of catalog leases. */internal suspend fun executeBackgroundEpg(@@ -9,6 +60,7 @@ internal suspend fun executeBackgroundEpg(sync: suspend () -> ProviderWorkflowOutcome): ProviderWorkflowDisposition = if (providerType == ProviderType.STALKER_PORTAL) {when (val outcome = sync()) {+ ProviderWorkflowOutcome.Deferred -> ProviderWorkflowDisposition.RETRYis ProviderWorkflowOutcome.Success -> ProviderWorkflowDisposition.SUCCEEDEDis ProviderWorkflowOutcome.Failure -> if (outcome.retryable) ProviderWorkflowDisposition.RETRYelse ProviderWorkflowDisposition.FAILEDdiff --git a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.ktindex 2171929f..997103d6 100644--- a/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/BackgroundEpgSyncWorker.kt@@ -18,6 +18,9 @@ import com.streamvault.data.local.entity.ProviderWorkflowReasonimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.XtreamIndexJobDaoimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.sync.AutomaticSyncActivity+import com.streamvault.data.preferences.PreferencesRepository+import kotlinx.coroutines.flow.combineimport dagger.hilt.EntryPointimport dagger.hilt.InstallInimport dagger.hilt.android.EntryPointAccessors@@ -36,6 +39,8 @@ class BackgroundEpgSyncWorker(fun providerWorkflowRunner(): ProviderWorkflowRunnerfun providerDao(): ProviderDaofun xtreamIndexJobDao(): XtreamIndexJobDao+ fun automaticSyncRunner(): AutomaticSyncRunner+ fun preferencesRepository(): PreferencesRepository}override suspend fun doWork(): Result {@@ -54,6 +59,7 @@ class BackgroundEpgSyncWorker(}val force = inputData.getBoolean(KEY_FORCE_REFRESH, false)+ val userInitiated = inputData.getBoolean(KEY_USER_INITIATED, false)return try {val entryPoint = EntryPointAccessors.fromApplication(@@ -61,6 +67,14 @@ class BackgroundEpgSyncWorker(BackgroundEpgSyncWorkerEntryPoint::class.java)val provider = entryPoint.providerDao().getById(providerId)+ if (provider != null && shouldDeferBackgroundEpgForPlayback(+ userInitiated = userInitiated,+ deferWhileBusy = entryPoint.automaticSyncRunner().settings(providerId).deferWhileBusy,+ playbackActive = AutomaticSyncActivity.hasPlayback+ )) {+ Log.i(TAG, "Deferring background EPG sync for provider $providerId: playback is active")+ return Result.retry()+ }if (!force && provider?.type == ProviderType.XTREAM_CODES &&entryPoint.xtreamIndexJobDao().hasPendingCatalogWork(providerId)) {@@ -77,43 +91,56 @@ class BackgroundEpgSyncWorker(block = sync)}) {- val epgResult = entryPoint.syncCommands().syncEpg(providerId, force = force)- when (val result = epgResult) {- is com.streamvault.domain.model.Result.Success -> {- // A successful EPG sync may still have transient partial failures.- val syncState = entryPoint.syncCommands().currentSyncState(providerId)- if (syncState is com.streamvault.domain.model.SyncState.Partial &&- syncState.hasRetryableEpgFailure- ) {- Log.i(TAG, "Scheduling retry for provider $providerId: EPG completed with retryable failure")+ runGuideWithPlaybackYield(+ enabled = canYieldInflightGuide(provider?.type, userInitiated),+ shouldDefer = combine(AutomaticSyncActivity.playbackActive,+ entryPoint.preferencesRepository().automaticSyncConfiguration) { active, settings ->+ shouldDeferBackgroundEpgForPlayback(userInitiated,+ settings.forProvider(providerId).deferWhileBusy, active)+ }+ ) {+ val epgResult = entryPoint.syncCommands().syncEpg(providerId, force = force)+ when (val result = epgResult) {+ is com.streamvault.domain.model.Result.Success -> {+ // A successful EPG sync may still have transient partial failures.+ val syncState = entryPoint.syncCommands().currentSyncState(providerId)+ if (syncState is com.streamvault.domain.model.SyncState.Partial &&+ syncState.hasRetryableEpgFailure+ ) {+ Log.i(TAG, "Scheduling retry for provider $providerId: EPG completed with retryable failure")+ ProviderWorkflowOutcome.Failure(+ code = "EPG_PARTIAL_RETRYABLE",+ message = "EPG completed with a retryable partial failure.",+ retryable = true+ )+ } else {+ ProviderWorkflowOutcome.Success(+ partial = syncState is com.streamvault.domain.model.SyncState.Partial+ )+ }+ }+ is com.streamvault.domain.model.Result.Error -> {+ if (result.message.contains("not found", ignoreCase = true)) {+ ProviderWorkflowOutcome.Success()+ } else {+ ProviderWorkflowOutcome.Failure(+ code = "EPG_SYNC",+ message = result.message,+ cause = result.exception+ )+ }+ }+ com.streamvault.domain.model.Result.Loading ->ProviderWorkflowOutcome.Failure(- code = "EPG_PARTIAL_RETRYABLE",- message = "EPG completed with a retryable partial failure.",+ code = "EPG_LOADING",+ message = "EPG operation did not reach a terminal state.",retryable = true)- } else {- ProviderWorkflowOutcome.Success(- partial = syncState is com.streamvault.domain.model.SyncState.Partial- )- }}- is com.streamvault.domain.model.Result.Error -> {- if (result.message.contains("not found", ignoreCase = true)) {- ProviderWorkflowOutcome.Success()- } else {- ProviderWorkflowOutcome.Failure(- code = "EPG_SYNC",- message = result.message,- cause = result.exception- )- }+ }.also { outcome ->+ if (outcome == ProviderWorkflowOutcome.Deferred) {+ Log.i(TAG, "Deferring in-flight background EPG sync for provider $providerId: playback became active")}- com.streamvault.domain.model.Result.Loading ->- ProviderWorkflowOutcome.Failure(- code = "EPG_LOADING",- message = "EPG operation did not reach a terminal state.",- retryable = true- )}}) {@@ -139,6 +166,7 @@ class BackgroundEpgSyncWorker(private const val TAG = "BackgroundEpgWorker"private const val KEY_PROVIDER_ID = "provider_id"private const val KEY_FORCE_REFRESH = "force_refresh"+ private const val KEY_USER_INITIATED = "user_initiated"private const val INVALID_PROVIDER_ID = -1L/*** Default delay before the first background EPG sync runs after enqueue. This@@ -151,7 +179,8 @@ class BackgroundEpgSyncWorker(context: Context,providerId: Long,force: Boolean = false,- initialDelaySeconds: Long = DEFAULT_INITIAL_DELAY_SECONDS+ initialDelaySeconds: Long = DEFAULT_INITIAL_DELAY_SECONDS,+ userInitiated: Boolean = false) {if (providerId <= 0L) returnval request = OneTimeWorkRequestBuilder<BackgroundEpgSyncWorker>()@@ -159,6 +188,7 @@ class BackgroundEpgSyncWorker(Data.Builder().putLong(KEY_PROVIDER_ID, providerId).putBoolean(KEY_FORCE_REFRESH, force)+ .putBoolean(KEY_USER_INITIATED, userInitiated).build()).setConstraints(diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt b/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.ktindex 4bdae987..3346612f 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderEpgSyncExecutor.kt@@ -233,6 +233,7 @@ internal class ProviderEpgSyncExecutor(val bulkCoveredChannelKeys = linkedSetOf<String>()var importedProgramCount = 0var providerRateLimited = false+ var bulkGuideFailed = falsevar bulkEpgReturnedEmpty = falsesuspend fun flushPrograms() {@@ -281,14 +282,17 @@ internal class ProviderEpgSyncExecutor(}}}.onFailure { error ->+ bulkGuideFailed = trueproviderRateLimited = error.hasStalkerRateLimit()Log.d(TAG, "Bulk Stalker portal EPG fetch unavailable for provider ${provider.id}", error)}val uncoveredGuideRequests = guideRequests.filterNot { it.channelKey in bulkCoveredChannelKeys }- // A usable bulk guide is the completed guide result. Many portals intentionally omit- // channels with no programmes; probing each omitted channel can take many minutes.+ // Bulk coverage avoids per-channel crawling of intentionally omitted channels.+ // A failed bulk response remains incomplete and is retried by its owning worker.val bulkGuideUsable = bulkCoveredChannelKeys.isNotEmpty()+ // Incremental rows survive a broken response, but they do not establish a complete guide.+ val bulkGuideIncomplete = bulkGuideFailed && bulkGuideUsableval perChannelGuideWindowed = !bulkGuideUsable && uncoveredGuideRequests.size > STALKER_PER_CHANNEL_EPG_REQUESTS_PER_RUNval fallbackGuideRequests = if (providerRateLimited || bulkGuideUsable) {emptyList()@@ -389,7 +393,7 @@ internal class ProviderEpgSyncExecutor(syncMetadataRepository.updateMetadata(existingMetadata.copy(lastEpgSync = now,- lastEpgSuccess = if (guideLooksHealthy) now else existingMetadata.lastEpgSuccess,+ lastEpgSuccess = if (guideLooksHealthy && !bulkGuideIncomplete) now else existingMetadata.lastEpgSuccess,epgCount = epgCount))@@ -411,7 +415,7 @@ internal class ProviderEpgSyncExecutor("Stalker portal guide imported $epgCount programs, but ${failedChannels.size} channels failed (${summarizeChannelNames(failedChannels)}).")}- if (!guideLooksHealthy && previousProgramCount >= STALKER_MIN_HEALTHY_EPG_PROGRAMS) {+ if (bulkGuideIncomplete || (!guideLooksHealthy && previousProgramCount >= STALKER_MIN_HEALTHY_EPG_PROGRAMS)) {warnings.add("Stalker portal guide import looked incomplete ($importedProgramCount programs across ${replacedChannelKeys.size} channels); preserved untouched prior guide data for the rest.")diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.ktindex c1ae84a5..43a91f5a 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt@@ -34,6 +34,11 @@ class ProviderSyncWorkScheduler @Inject constructor(initialDelaySeconds = if (force) 0L else 30L)}+ fun scheduleManualEpg(providerId: Long) {+ BackgroundEpgSyncWorker.enqueue(applicationContext, providerId, force = true,+ initialDelaySeconds = 0L, userInitiated = true)+ }+fun scheduleProviderResume(providerId: Long, configurationGeneration: Long? = null) {if (configurationGeneration != null) {ProviderSyncWorker.enqueueProviderConfigRevision(diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.ktindex 7107f0f0..bb646cbf 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt@@ -253,7 +253,20 @@ class ProviderSyncWorker(// Interrupted setup is recovery, independent of automatic refresh policy.entryPoint.syncCommands().resumePrimaryCatalog(provider.id, true)} else {- entryPoint.automaticSyncRunner().check(provider.id)+ try {+ entryPoint.automaticSyncRunner().check(provider.id)+ } catch (cancelled: kotlinx.coroutines.CancellationException) {+ // The pipeline cancels/joins its own reader and writer before this+ // control signal arrives. External worker cancellation stays cancellation.+ kotlinx.coroutines.currentCoroutineContext().let { context ->+ if (!context[kotlinx.coroutines.Job]!!.isActive) throw cancelled+ }+ if (!cancelled.isXtreamLivePlaybackDeferral()) throw cancelled+ entryPoint.automaticSyncRunner().reportIndexWaiting(provider.id,+ com.streamvault.domain.sync.AutomaticSyncOutcome.WAITING_PLAYBACK)+ Log.i(TAG, "Automatic bulk live catalog yielded before commit")+ return@execute ProviderWorkflowOutcome.Deferred+ }}if (requestedProviderId != provider.id && entryPoint.automaticSyncRunner().retryCheck(provider.id)) sawRetryableFailure = trueif (requestedProviderId == provider.id || (trackInitialLiveOnboarding && !provider.isActive)) {diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.kt b/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.ktindex f9c76380..4762714a 100644--- a/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.kt+++ b/data/src/main/java/com/streamvault/data/sync/ProviderWorkflowRunner.kt@@ -21,6 +21,8 @@ import kotlinx.coroutines.launchimport kotlinx.coroutines.withContextsealed interface ProviderWorkflowOutcome {+ /** Cooperative scheduling control, not a provider or network failure. */+ data object Deferred : ProviderWorkflowOutcomedata class Success(val checkpoint: String? = null,val partial: Boolean = false@@ -153,6 +155,9 @@ class ProviderWorkflowRunner @Inject constructor(): ProviderWorkflowDisposition {val now = System.currentTimeMillis()return when (outcome) {+ ProviderWorkflowOutcome.Deferred -> if (workflowDao.defer(lease, now)) {+ ProviderWorkflowDisposition.RETRY+ } else ProviderWorkflowDisposition.SUPERSEDEDis ProviderWorkflowOutcome.Success -> {if (workflowDao.complete(diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktindex 95211554..b20d7f74 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -845,7 +845,17 @@ class SyncManager @Inject constructor(stageChannelItems = { id, items, seen, categories, session ->catalogStager.stageChannelItems(id, items, seen, categories, session, useLiveAdmissionCount = true)},- emitProgress = ::emitProviderProgress+ emitProgress = ::emitProviderProgress,+ beforeBulkLiveBatch = { providerId ->+ if (kotlin.coroutines.coroutineContext[ProviderWorkflowExecutionContext]?.lease?.phase ==+ com.streamvault.data.local.entity.ProviderWorkflowPhase.PRIMARY_CATALOG &&+ AutomaticSyncExecution.automatic.get() == true &&+ shouldYieldXtreamLiveBatch(true,+ preferencesRepository.automaticSyncConfiguration.first().forProvider(providerId).deferWhileBusy,+ com.streamvault.domain.sync.AutomaticSyncActivity.hasPlayback)) {+ throw XtreamLivePlaybackDeferredException()+ }+ })}@@ -931,7 +941,7 @@ class SyncManager @Inject constructor(override fun scheduleAutomaticSyncCheck() { ProviderSyncWorker.enqueueForegroundCheck(applicationContext) }override fun scheduleManualEpgSync(providerId: Long) {- providerSyncWorkScheduler.scheduleBackgroundEpg(providerId, force = true)+ providerSyncWorkScheduler.scheduleManualEpg(providerId)}override fun scheduleBackgroundEpgSync(providerId: Long) {diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.ktindex 831f4c8a..255c85f2 100644--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerXtreamLiveStrategy.kt@@ -49,7 +49,8 @@ internal class SyncManagerXtreamLiveStrategy(private val liveCategorySequentialModeWarning: String,private val isCurrentlyLowOnMemory: () -> Boolean = { false },private val stageChannelItems: suspend (Long, List<Channel>, MutableSet<Long>, FallbackCategoryCollector, Long?) -> StagedCatalogSnapshot,- private val emitProgress: (Long, SyncProgress) -> Unit+ private val emitProgress: (Long, SyncProgress) -> Unit,+ private val beforeBulkLiveBatch: suspend (Long) -> Unit = {}) {suspend fun syncXtreamLiveCatalog(provider: Provider,@@ -340,6 +341,7 @@ internal class SyncManagerXtreamLiveStrategy(suspend fun flushRawBatch(rawBatch: List<RawItem>) {if (rawBatch.isEmpty()) return+ beforeBulkLiveBatch(provider.id)lateinit var mappedChannels: List<Channel>mappingElapsedMs += measureTimeMillis {val mapped = mapRawBatch(rawBatch.asSequence()).toList()diff --git a/data/src/main/java/com/streamvault/data/sync/XtreamLivePlaybackYield.kt b/data/src/main/java/com/streamvault/data/sync/XtreamLivePlaybackYield.ktnew file mode 100644index 00000000..91971274--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/XtreamLivePlaybackYield.kt@@ -0,0 +1,13 @@+package com.streamvault.data.sync++import kotlinx.coroutines.CancellationException++/** Cooperative control flow for an uncommitted bulk LIVE attempt, never a provider failure. */+internal class XtreamLivePlaybackDeferredException : CancellationException("Automatic live catalog yielded for playback")++internal fun shouldYieldXtreamLiveBatch(automatic: Boolean, deferWhileBusy: Boolean, playbackActive: Boolean): Boolean =+ automatic && deferWhileBusy && playbackActive++internal fun Throwable.isXtreamLivePlaybackDeferral(): Boolean =+ this is XtreamLivePlaybackDeferredException ||+ (this is CancellationException && cause != null && cause !== this && cause!!.isXtreamLivePlaybackDeferral())diff --git a/data/src/test/java/com/streamvault/data/local/ProviderWorkflowDaoTest.kt b/data/src/test/java/com/streamvault/data/local/ProviderWorkflowDaoTest.ktindex 566c18c1..f59897b8 100644--- a/data/src/test/java/com/streamvault/data/local/ProviderWorkflowDaoTest.kt+++ b/data/src/test/java/com/streamvault/data/local/ProviderWorkflowDaoTest.kt@@ -38,6 +38,21 @@ class ProviderWorkflowDaoTest {database.close()}+ @Test+ fun `deferral is lease fenced and preserves the last checkpoint`() = runTest {+ insertProvider()+ val dao = database.providerWorkflowDao()+ val ticket = dao.request(PROVIDER_ID, ProviderWorkflowPhase.EPG, ProviderWorkflowReason.PERIODIC, 100L)+ val lease = checkNotNull(dao.claim(ticket, "guide", 101L, 1000L, 0L))+ dao.updateRunningCheckpoint(PROVIDER_ID, ticket.generation, ticket.phase, lease.token, "stage=5000", 102L)+ assertThat(dao.defer(lease.copy(token = "stale"), 103L)).isFalse()+ assertThat(dao.getWorkflow(PROVIDER_ID)!!.state).isEqualTo(ProviderWorkflowState.RUNNING)+ assertThat(dao.defer(lease, 104L)).isTrue()+ assertThat(dao.getCheckpoint(PROVIDER_ID, ticket.generation, ticket.phase)).isEqualTo("stage=5000")+ assertThat(dao.getWorkflow(PROVIDER_ID)!!.lastErrorCode).isNull()+ assertThat(dao.claim(ticket, "resumed", 105L, 1000L, 0L)).isNotNull()+ }+@Testfun `concurrent schedulers grant exactly one workflow lease`() = runTest {insertProvider()diff --git a/data/src/test/java/com/streamvault/data/manager/recording/RecordingCaptureEngineTest.kt b/data/src/test/java/com/streamvault/data/manager/recording/RecordingCaptureEngineTest.ktindex 5b55d29a..e0416237 100644--- a/data/src/test/java/com/streamvault/data/manager/recording/RecordingCaptureEngineTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/recording/RecordingCaptureEngineTest.kt@@ -3,9 +3,18 @@ package com.streamvault.data.manager.recordingimport android.content.ContentResolverimport com.google.common.truth.Truth.assertThatimport com.streamvault.domain.model.RecordingSourceType+import com.streamvault.domain.model.LivePlaybackIdentity+import com.streamvault.domain.util.LivePlaybackByteTap+import com.streamvault.domain.util.effectiveHttpRequestProperties+import com.streamvault.domain.util.livePlaybackRequestFingerprintimport java.io.IOExceptionimport java.util.concurrent.atomic.AtomicIntegerimport kotlinx.coroutines.test.runTest+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.withTimeoutimport okhttp3.Interceptorimport okhttp3.MediaType.Companion.toMediaTypeimport okhttp3.OkHttpClient@@ -89,4 +98,175 @@ class RecordingCaptureEngineTest {.message("OK").body(body.toResponseBody("application/vnd.apple.mpegurl".toMediaType())).build()-}\ No newline at end of file++ @Test+ fun sharedRecordingStartsAtAvailableNewSegmentWithoutWaitingForOldPlaylistEntries() = runTest {+ sharedStartupScenario(waitForMiddle = false)+ }++ @Test+ fun sharedRecordingWaitsForMissingSegmentAfterItsFirstWrite() = runTest {+ sharedStartupScenario(waitForMiddle = true)+ }++ @Test+ fun sharedRecordingKeepsWarmEncryptionKeyAndInitializationMap() = runTest {+ sharedStartupScenario(waitForMiddle = false, encrypted = true)+ }++ @Test+ fun sequentialSharedRecordingsReuseWarmHlsDependenciesWithoutUpstreamRequests() = runTest {+ val url = "https://fixture.invalid/live/index.m3u8"+ val identity = LivePlaybackIdentity(1, 2)+ val source = ResolvedRecordingSource(url, RecordingSourceType.HLS, livePlaybackIdentity = identity)+ val fingerprint = livePlaybackRequestFingerprint(+ url,+ effectiveHttpRequestProperties(source.headers, source.userAgent)+ )+ val tap = LivePlaybackByteTap()+ val key = ByteArray(16) { it.toByte() }+ val iv = ByteArray(16) { 1 }+ fun encrypt(value: String): ByteArray = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding")+ .apply {+ init(+ javax.crypto.Cipher.ENCRYPT_MODE,+ javax.crypto.spec.SecretKeySpec(key, "AES"),+ javax.crypto.spec.IvParameterSpec(iv)+ )+ }+ .doFinal(value.toByteArray())+ fun publish(name: String, bytes: ByteArray, playlist: Boolean = false) {+ val resourceUrl = java.net.URI(url).resolve(name).toString()+ tap.beginHlsResource(identity, fingerprint, resourceUrl, resourceUrl, playlist).use { publisher ->+ publisher.publish(bytes, 0, bytes.size)+ publisher.complete()+ }+ }+ fun manifest(segments: List<String>, endList: Boolean = false): ByteArray = buildString {+ append("#EXTM3U\n#EXT-X-TARGETDURATION:2\n")+ append("#EXT-X-KEY:METHOD=AES-128,URI=\"key\",IV=0x")+ append(iv.joinToString("") { "%02x".format(it) })+ append("\n#EXT-X-MAP:URI=\"init\"\n")+ segments.forEach { append("#EXTINF:2,\n$it\n") }+ if (endList) append("#EXT-X-ENDLIST\n")+ }.toByteArray()++ publish("index.m3u8", manifest(listOf("old.ts")), playlist = true)+ publish("key", key)+ publish("init", encrypt("INIT"))+ publish("old.ts", encrypt("OLD"))++ val upstreamRequests = AtomicInteger()+ val client = OkHttpClient.Builder()+ .addInterceptor {+ upstreamRequests.incrementAndGet()+ throw IOException("Shared recording unexpectedly opened an upstream request")+ }+ .build()+ val engine = HlsLiveCaptureEngine(RecordingHttpClientFactory { client }, tap)+ val firstOutput = tempFolder.newFile("shared-first.ts")+ val firstSegmentWritten = CompletableDeferred<Unit>()+ val firstUpdater = launch {+ delay(100)+ publish("index.m3u8", manifest(listOf("old.ts", "first.ts")), playlist = true)+ publish("first.ts", encrypt("A"))+ }+ val firstCapture = launch {+ engine.capture(+ source,+ RecordingOutputTarget.FileTarget(firstOutput),+ mock<ContentResolver>(),+ System.currentTimeMillis() + 60_000,+ onProgress = { firstSegmentWritten.complete(Unit) }+ )+ }+ withTimeout(5_000) { firstSegmentWritten.await() }+ firstCapture.cancelAndJoin()+ firstUpdater.join()+ assertThat(firstOutput.readText()).isEqualTo("INITA")++ val secondOutput = tempFolder.newFile("shared-second.ts")+ val secondUpdater = launch {+ delay(100)+ publish(+ "index.m3u8",+ manifest(listOf("old.ts", "first.ts", "second.ts"), endList = true),+ playlist = true+ )+ publish("second.ts", encrypt("B"))+ }+ withTimeout(10_000) {+ engine.capture(+ source,+ RecordingOutputTarget.FileTarget(secondOutput),+ mock<ContentResolver>(),+ System.currentTimeMillis() + 60_000,+ onProgress = {}+ )+ }+ secondUpdater.join()++ assertThat(secondOutput.readText()).isEqualTo("INITB")+ assertThat(upstreamRequests.get()).isEqualTo(0)+ }++ private suspend fun kotlinx.coroutines.test.TestScope.sharedStartupScenario(+ waitForMiddle: Boolean,+ encrypted: Boolean = false+ ) {+ val url = "https://fixture.invalid/live/index.m3u8"+ val identity = LivePlaybackIdentity(1, 2)+ val source = ResolvedRecordingSource(url, RecordingSourceType.HLS, livePlaybackIdentity = identity)+ val fingerprint = livePlaybackRequestFingerprint(url, effectiveHttpRequestProperties(source.headers, source.userAgent))+ val tap = LivePlaybackByteTap()+ val key = ByteArray(16) { it.toByte() }+ val iv = ByteArray(16) { 1 }+ fun publishBytes(name: String, bytes: ByteArray, playlist: Boolean = false) {+ val resourceUrl = java.net.URI(url).resolve(name).toString()+ tap.beginHlsResource(identity, fingerprint, resourceUrl, resourceUrl, playlist).use { publisher ->+ publisher.publish(bytes, 0, bytes.size)+ publisher.complete()+ }+ }+ fun publish(name: String, body: String, playlist: Boolean = false) {+ val bytes = if (encrypted && !playlist) {+ javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding").apply {+ init(javax.crypto.Cipher.ENCRYPT_MODE, javax.crypto.spec.SecretKeySpec(key, "AES"),+ javax.crypto.spec.IvParameterSpec(iv))+ }.doFinal(body.toByteArray())+ } else body.toByteArray()+ publishBytes(name, bytes, playlist)+ }+ val encryption = if (encrypted) {+ "#EXT-X-KEY:METHOD=AES-128,URI=\"key\",IV=0x${iv.joinToString("") { "%02x".format(it) }}\n" ++ "#EXT-X-MAP:URI=\"init\"\n"+ } else ""+ val playlist = "#EXTM3U\n#EXT-X-TARGETDURATION:2\n" + encryption ++ listOf("old", "a", "b", "c").joinToString("") { "#EXTINF:2,\n$it.ts\n" }+ publish("index.m3u8", playlist, true)+ if (encrypted) {+ publishBytes("key", key)+ publish("init", "INIT")+ }+ publish("old.ts", "old")+ val outputFile = tempFolder.newFile()+ val client = OkHttpClient.Builder().addInterceptor { error("Recording opened a duplicate upstream request") }.build()+ launch {+ delay(100)+ publish("a.ts", "A")+ if (!waitForMiddle) publish("b.ts", "B")+ publish("c.ts", "C")+ if (waitForMiddle) {+ delay(1500)+ assertThat(outputFile.readText()).isEqualTo("A")+ publish("b.ts", "B")+ }+ publish("index.m3u8", playlist + "#EXT-X-ENDLIST\n", true)+ }+ HlsLiveCaptureEngine(RecordingHttpClientFactory { client }, tap).capture(+ source, RecordingOutputTarget.FileTarget(outputFile), mock<ContentResolver>(),+ System.currentTimeMillis() + 60_000, {}+ )+ assertThat(outputFile.readText()).isEqualTo(if (encrypted) "INITABC" else "ABC")+ }+}diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.ktindex 487fea87..c92edfb1 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt@@ -5,6 +5,7 @@ import com.streamvault.domain.model.StalkerRequestPriorityimport java.net.SocketTimeoutExceptionimport java.util.concurrent.atomic.AtomicIntegerimport kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.asContextElementimport kotlinx.coroutines.asyncimport kotlinx.coroutines.awaitAllimport kotlinx.coroutines.test.advanceUntilIdle@@ -423,4 +424,51 @@ class StalkerRequestCoordinatorTest {bulk.await()assertThat(bulkStarted.isCompleted).isTrue()}+ @Test fun engineOwnedAutomaticIndexWaitsForReleaseWhileInteractiveRequestsContinue() = runTest {+ val owner=Any()+ val coordinator=StalkerRequestCoordinator(null,true) { testScheduler.currentTime }+ try {+ com.streamvault.domain.sync.AutomaticSyncActivity.started(owner,707)+ kotlinx.coroutines.withContext(+ com.streamvault.data.sync.AutomaticSyncExecution.automatic.asContextElement(true) ++ com.streamvault.data.sync.AutomaticSyncExecution.policy.asContextElement(com.streamvault.domain.sync.AutomaticSyncSettings())+ ) {+ val pending=async { coordinator.acquireNetworkPermit(707,StalkerNetworkPriority.INDEX) }+ runCurrent()+ assertThat(pending.isCompleted).isFalse()+ val interactive=coordinator.acquireNetworkPermit(707,StalkerNetworkPriority.INTERACTIVE)+ coordinator.releaseNetworkPermit(interactive)+ com.streamvault.domain.sync.AutomaticSyncActivity.stopped(owner)+ advanceUntilIdle()+ coordinator.releaseNetworkPermit(pending.await())+ }+ } finally { com.streamvault.domain.sync.AutomaticSyncActivity.stopped(owner) }+ }+ @Test fun engineOwnedPlaybackDoesNotBlockManualOrOptOutIndexNetworkAdmission() = runTest {+ val owner=Any()+ val coordinator=StalkerRequestCoordinator(null,true) { testScheduler.currentTime }+ try {+ com.streamvault.domain.sync.AutomaticSyncActivity.started(owner,708)+ for (automatic in listOf(false,true)) kotlinx.coroutines.withContext(+ com.streamvault.data.sync.AutomaticSyncExecution.automatic.asContextElement(automatic) ++ com.streamvault.data.sync.AutomaticSyncExecution.policy.asContextElement(com.streamvault.domain.sync.AutomaticSyncSettings(deferWhileBusy=!automatic))+ ) {+ val pending=async { coordinator.acquireNetworkPermit(708,StalkerNetworkPriority.INDEX) }+ runCurrent(); assertThat(pending.isCompleted).isTrue()+ coordinator.releaseNetworkPermit(pending.await())+ }+ } finally { com.streamvault.domain.sync.AutomaticSyncActivity.stopped(owner) }+ }+ @Test fun engineOwnedOtherProviderDoesNotBlockAutomaticIndexNetworkAdmission() = runTest {+ val owner=Any()+ val coordinator=StalkerRequestCoordinator(null,true) { testScheduler.currentTime }+ try {+ com.streamvault.domain.sync.AutomaticSyncActivity.started(owner,709)+ kotlinx.coroutines.withContext(com.streamvault.data.sync.AutomaticSyncExecution.automatic.asContextElement(true)) {+ val pending=async { coordinator.acquireNetworkPermit(710,StalkerNetworkPriority.INDEX) }+ runCurrent(); assertThat(pending.isCompleted).isTrue()+ coordinator.releaseNetworkPermit(pending.await())+ }+ } finally { com.streamvault.domain.sync.AutomaticSyncActivity.stopped(owner) }+ }}diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.ktindex 520ba700..c31554a9 100644--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt@@ -50,4 +50,42 @@ class StalkerTrafficCoordinatorTest {assertThat(StalkerTrafficCoordinator.isPlaybackActive(7L)).isTrue()}+ @Test fun engineOwnedLivePlaybackDefersOnlyMatchingAutomaticWork() {+ val owner=Any()+ val automatic=com.streamvault.data.sync.AutomaticSyncExecution.automatic+ val policy=com.streamvault.data.sync.AutomaticSyncExecution.policy+ val previousAutomatic=automatic.get(); val previousPolicy=policy.get()+ try {+ com.streamvault.domain.sync.AutomaticSyncActivity.started(owner,7)+ automatic.set(true); policy.set(com.streamvault.domain.sync.AutomaticSyncSettings())+ assertThat(StalkerTrafficCoordinator.isPlaybackActive(7)).isTrue()+ assertThat(StalkerTrafficCoordinator.shouldDeferIndexForPlayback(7)).isTrue()+ assertThat(StalkerTrafficCoordinator.shouldDeferIndexForPlayback(8)).isFalse()+ com.streamvault.domain.sync.AutomaticSyncActivity.stopped(owner)+ assertThat(StalkerTrafficCoordinator.shouldDeferIndexForPlayback(7)).isFalse()+ } finally {+ automatic.set(previousAutomatic); policy.set(previousPolicy)+ com.streamvault.domain.sync.AutomaticSyncActivity.stopped(owner)+ }+ }+ @Test fun manualAndOptOutKeepWorkingWithoutHidingActualPlaybackOwnership() {+ val owner=Any()+ val automatic=com.streamvault.data.sync.AutomaticSyncExecution.automatic+ val policy=com.streamvault.data.sync.AutomaticSyncExecution.policy+ val previousAutomatic=automatic.get(); val previousPolicy=policy.get()+ try {+ com.streamvault.domain.sync.AutomaticSyncActivity.started(owner,7)+ automatic.set(false); policy.set(com.streamvault.domain.sync.AutomaticSyncSettings())+ assertThat(StalkerTrafficCoordinator.isPlaybackActive(7)).isTrue()+ assertThat(StalkerTrafficCoordinator.shouldDeferIndexForPlayback(7)).isFalse()+ automatic.set(true); policy.set(com.streamvault.domain.sync.AutomaticSyncSettings(deferWhileBusy=false))+ assertThat(StalkerTrafficCoordinator.shouldDeferIndexForPlayback(7)).isFalse()+ assertThat(StalkerTrafficCoordinator.backgroundInterPageDelayMillis(7,false)).isEqualTo(1000L)+ policy.set(null)+ assertThat(StalkerTrafficCoordinator.shouldDeferIndexForPlayback(7)).isTrue()+ } finally {+ automatic.set(previousAutomatic); policy.set(previousPolicy)+ com.streamvault.domain.sync.AutomaticSyncActivity.stopped(owner)+ }+ }}diff --git a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.ktindex 458a2365..d3d86b34 100644--- a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt+++ b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt@@ -186,6 +186,7 @@ class ProviderRepositoryImplTest {).thenAnswer { invocation ->val block = invocation.getArgument<suspend () -> ProviderWorkflowOutcome>(6)when (val outcome = runBlocking { block() }) {+ ProviderWorkflowOutcome.Deferred -> ProviderWorkflowDisposition.RETRYis ProviderWorkflowOutcome.Success -> ProviderWorkflowDisposition.SUCCEEDEDis ProviderWorkflowOutcome.Failure -> if (outcome.retryable) {ProviderWorkflowDisposition.RETRYdiff --git a/data/src/test/java/com/streamvault/data/sync/BackgroundEpgAdmissionTest.kt b/data/src/test/java/com/streamvault/data/sync/BackgroundEpgAdmissionTest.ktnew file mode 100644index 00000000..a3b54173--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/BackgroundEpgAdmissionTest.kt@@ -0,0 +1,16 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class BackgroundEpgAdmissionTest {+ @Test fun `background guide work yields only when requested and playback is owned`() {+ assertThat(shouldDeferBackgroundEpgForPlayback(false, true, true)).isTrue()+ assertThat(shouldDeferBackgroundEpgForPlayback(false, true, false)).isFalse()+ assertThat(shouldDeferBackgroundEpgForPlayback(false, false, true)).isFalse()+ }++ @Test fun `explicit user refresh remains admitted with the default busy policy`() {+ assertThat(shouldDeferBackgroundEpgForPlayback(true, true, true)).isFalse()+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/BackgroundEpgPlaybackYieldTest.kt b/data/src/test/java/com/streamvault/data/sync/BackgroundEpgPlaybackYieldTest.ktnew file mode 100644index 00000000..74303702--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/BackgroundEpgPlaybackYieldTest.kt@@ -0,0 +1,72 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.ProviderType+import java.io.IOException+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.cancelAndJoin+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.runTest+import org.junit.Test++class BackgroundEpgPlaybackYieldTest {+ @Test fun `playback cancels and joins only the import before returning deferred`() = runTest {+ val active = MutableStateFlow(false)+ val entered = CompletableDeferred<Unit>()+ var closed = false+ val result = async {+ runGuideWithPlaybackYield(true, active) {+ try { entered.complete(Unit); awaitCancellation() }+ finally { closed = true }+ }+ }+ entered.await()+ active.value = true+ assertThat(result.await()).isEqualTo(ProviderWorkflowOutcome.Deferred)+ assertThat(closed).isTrue()+ }++ @Test fun `manual and incremental Stalker work never enter playback interruption`() = runTest {+ assertThat(canYieldInflightGuide(ProviderType.M3U, true)).isFalse()+ assertThat(canYieldInflightGuide(ProviderType.STALKER_PORTAL, false)).isFalse()+ assertThat(canYieldInflightGuide(ProviderType.XTREAM_CODES, false)).isFalse()+ assertThat(canYieldInflightGuide(ProviderType.M3U, false)).isTrue()+ val result = runGuideWithPlaybackYield(false, flow { error("Must not observe playback") }) {+ ProviderWorkflowOutcome.Success()+ }+ assertThat(result).isInstanceOf(ProviderWorkflowOutcome.Success::class.java)+ }++ @Test fun `opted out or idle work finishes normally and failures retain their type`() = runTest {+ assertThat(runGuideWithPlaybackYield(true, flowOf(false)) {+ ProviderWorkflowOutcome.Success()+ }).isInstanceOf(ProviderWorkflowOutcome.Success::class.java)+ val failure = IOException("fixture")+ try {+ runGuideWithPlaybackYield(true, flowOf(false)) { throw failure }+ error("Expected the source failure")+ } catch (actual: IOException) { assertThat(actual.message).isEqualTo(failure.message) }+ }++ @Test fun `external worker cancellation remains cancellation rather than a deferred outcome`() = runTest {+ val entered = CompletableDeferred<Unit>()+ var returned = false+ var closed = false+ val job = launch {+ runGuideWithPlaybackYield(true, flowOf(false)) {+ try { entered.complete(Unit); awaitCancellation() }+ finally { closed = true }+ }+ returned = true+ }+ entered.await()+ job.cancelAndJoin()+ assertThat(returned).isFalse()+ assertThat(closed).isTrue()+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/GuideHttpFailureTest.kt b/data/src/test/java/com/streamvault/data/sync/GuideHttpFailureTest.ktnew file mode 100644index 00000000..218d3174--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/GuideHttpFailureTest.kt@@ -0,0 +1,78 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.ProgramDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.parser.XmltvParser+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.repository.EpgRepositoryImpl+import com.streamvault.domain.model.*+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.EpgSourceRepository+import com.streamvault.domain.repository.SyncMetadataRepository+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.runTest+import okhttp3.OkHttpClient+import okhttp3.Protocol+import okhttp3.Response+import okhttp3.ResponseBody.Companion.toResponseBody+import org.junit.Test+import org.mockito.kotlin.*++/** Real HTTP response -> repository result -> guide executor classification and freshness. */+class GuideHttpFailureTest {+ @Test fun `temporary HTTP guide failures remain retryable without replacing cached data`() = runTest {+ for (status in listOf(408, 429, 500, 502, 503, 504)) verifyFailure(status, retryable = true)+ }++ @Test fun `authentication and permanent HTTP guide failures do not schedule retries`() = runTest {+ for (status in listOf(400, 401, 403, 404, 410)) verifyFailure(status, retryable = false)+ }++ private suspend fun verifyFailure(status: Int, retryable: Boolean) {+ val preferences: PreferencesRepository = mock()+ val programs: ProgramDao = mock()+ val providers: ProviderDao = mock()+ val metadata: SyncMetadataRepository = mock()+ val sources: EpgSourceRepository = mock()+ whenever(preferences.getEpgTimeShiftMinutes(7L)).thenReturn(0)+ whenever(preferences.getHiddenCategoryIds(7L, ContentType.LIVE)).thenReturn(flowOf(emptySet()))+ whenever(programs.countByProvider(7L)).thenReturn(1)+ whenever(providers.getById(7L)).thenReturn(null)+ whenever(sources.resolveForProvider(7L, emptySet())).thenReturn(EpgResolutionSummary())+ val transaction = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ }+ val client = OkHttpClient.Builder().addInterceptor { chain ->+ Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1)+ .code(status).message("Fixture HTTP error").body("fixture".toResponseBody()).build()+ }.build()+ val repository = EpgRepositoryImpl(programDao = programs, providerDao = providers,+ xmltvParser = XmltvParser(), okHttpClient = client, transactionRunner = transaction,+ epgSourceRepository = sources, preferencesRepository = preferences)+ val direct = repository.refreshEpg(7L, "https://example.test/guide.xml")+ assertThat(direct).isInstanceOf(Result.Error::class.java)+ val error = direct as Result.Error+ assertThat(error.message).isEqualTo("Failed to download EPG: HTTP $status")+ assertThat(error.exception is java.io.IOException).isEqualTo(retryable)+ val executor = ProviderEpgSyncExecutor(preferencesRepository = preferences,+ epgRepository = repository, epgSourceRepository = sources, channelDao = mock(),+ programDao = programs, transactionRunner = transaction, syncMetadataRepository = metadata,+ stalkerPortalStateStore = mock(), stalkerRequestCoordinator = mock(),+ createStalkerProvider = { error("Unexpected Stalker request") },+ xtreamSupport = SyncManagerXtreamSupport(mock(), { false }, { it?.message.orEmpty() },+ { _, _, _ -> }, 1000L, 1000L, "fixture"),+ progress = { _, _, _ -> }, sanitizeThrowableMessage = { it?.message.orEmpty() })+ val provider = LegacyProvider(id = 7L, name = "Fixture", type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.test", username = "fixture", password = "fixture",+ guideSourcePolicy = GuideSourcePolicy.PROVIDER_ONLY)+ val outcome = executor.syncXtreamProviderEpg(provider, SyncMetadata(7L), 1000L, true, null)+ assertThat(outcome.hasRetryableFailure).isEqualTo(retryable)+ assertThat(outcome.warnings).isNotEmpty()+ verify(metadata, never()).updateMetadata(any())+ verify(programs, never()).deleteByProvider(any())+ verify(programs, never()).moveToProvider(any(), any())+ verify(programs, never()).insertAll(any())+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkSchedulerIntegrationTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkSchedulerIntegrationTest.ktindex ed96c575..ea2208ff 100644--- a/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkSchedulerIntegrationTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/ProviderSyncWorkSchedulerIntegrationTest.kt@@ -69,9 +69,29 @@ class ProviderSyncWorkSchedulerIntegrationTest {val manager = workManager()BackgroundEpgSyncWorker.enqueue(context, 987957L, force = false, initialDelaySeconds = 3600L)val original = manager.getWorkInfosForUniqueWork(providerEpgWorkUniqueName(987957L)).get().single { !it.state.isFinished }- BackgroundEpgSyncWorker.enqueue(context, 987957L, force = true, initialDelaySeconds = 3600L)+ BackgroundEpgSyncWorker.enqueue(context, 987957L, force = true,+ initialDelaySeconds = 3600L, userInitiated = true)val replacement = manager.getWorkInfosForUniqueWork(providerEpgWorkUniqueName(987957L)).get().single { !it.state.isFinished }assertThat(replacement.id).isNotEqualTo(original.id)+ val input = kotlinx.coroutines.runBlocking(kotlinx.coroutines.Dispatchers.IO) {+ (manager as androidx.work.impl.WorkManagerImpl).workDatabase.workSpecDao()+ .getWorkSpec(replacement.id.toString())!!.input+ }+ assertThat(input.getBoolean("user_initiated", false)).isTrue()+ assertThat(input.getBoolean("force_refresh", false)).isTrue()+ }++ @Test fun `background guide repair forces freshness without claiming a manual request`() {+ val context = RuntimeEnvironment.getApplication()+ val manager = workManager()+ BackgroundEpgSyncWorker.enqueue(context, 987959L, force = true, initialDelaySeconds = 3600L)+ val queued = manager.getWorkInfosForUniqueWork(providerEpgWorkUniqueName(987959L)).get().single { !it.state.isFinished }+ val input = kotlinx.coroutines.runBlocking(kotlinx.coroutines.Dispatchers.IO) {+ (manager as androidx.work.impl.WorkManagerImpl).workDatabase.workSpecDao()+ .getWorkSpec(queued.id.toString())!!.input+ }+ assertThat(input.getBoolean("force_refresh", false)).isTrue()+ assertThat(input.getBoolean("user_initiated", false)).isFalse()}@Test fun `a policy edit retains a successor check when a foreground check is already pending`() {diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.ktindex ea59724a..c3fcd0ae 100644--- a/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.kt+++ b/data/src/test/java/com/streamvault/data/sync/ProviderWorkflowRunnerTest.kt@@ -47,6 +47,24 @@ class ProviderWorkflowRunnerTest {database.close()}+ @Test+ fun `cooperative deferral clears the lease without publishing a failure and can immediately resume`() = runTest {+ insertProvider()+ val disposition = runner.execute(PROVIDER_ID, ProviderWorkflowPhase.EPG, ProviderWorkflowReason.PERIODIC) {+ ProviderWorkflowOutcome.Deferred+ }+ assertThat(disposition).isEqualTo(ProviderWorkflowDisposition.RETRY)+ val workflow = database.providerWorkflowDao().getWorkflow(PROVIDER_ID)!!+ assertThat(workflow.state).isEqualTo(ProviderWorkflowState.PENDING)+ assertThat(workflow.leaseToken).isNull()+ assertThat(workflow.lastErrorCode).isNull()+ assertThat(database.providerWorkflowDao().getPhases(PROVIDER_ID, workflow.generation).single().state)+ .isEqualTo(ProviderWorkflowPhaseState.PENDING)+ assertThat(runner.execute(PROVIDER_ID, ProviderWorkflowPhase.EPG, ProviderWorkflowReason.PERIODIC) {+ ProviderWorkflowOutcome.Success()+ }).isEqualTo(ProviderWorkflowDisposition.SUCCEEDED)+ }+@Testfun `successful execution publishes the terminal phase and workflow`() = runTest {insertProvider()diff --git a/data/src/test/java/com/streamvault/data/sync/StalkerNativeGuideInterruptionTest.kt b/data/src/test/java/com/streamvault/data/sync/StalkerNativeGuideInterruptionTest.ktnew file mode 100644index 00000000..94967c6b--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/StalkerNativeGuideInterruptionTest.kt@@ -0,0 +1,194 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.DatabaseTransactionRunner+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.ProgramDao+import com.streamvault.data.local.entity.ChannelGuideSyncEntity+import com.streamvault.data.local.entity.ProgramEntity+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.data.remote.stalker.StalkerPortalStateStore+import com.streamvault.data.remote.stalker.StalkerProvider+import com.streamvault.data.remote.stalker.StalkerRequestCoordinator+import com.streamvault.domain.model.*+import com.streamvault.domain.repository.EpgRepository+import com.streamvault.domain.repository.EpgSourceRepository+import com.streamvault.domain.repository.SyncMetadataRepository+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.*+import java.io.IOException++/** Regression contract for native bulk guide bodies interrupted after streaming a prefix. */+class StalkerNativeGuideInterruptionTest {+ @Test+ fun `interrupted bulk prefix remains useful but does not make guide fresh or hide retry`() = runTest {+ val fixture = Fixture(bulkFailsAfterPrefix = true)+ fixture.setUp()++ val outcome = fixture.run()++ assertThat(outcome.hasRetryableFailure).isTrue()+ assertThat(outcome.warnings).isNotEmpty()+ assertThat(fixture.savedPrograms.count { it.channelId == "100" }).isEqualTo(6_000)+ assertThat(fixture.savedPrograms.any { it.channelId == "200" && it.title == "Old uncovered guide" }).isTrue()+ assertThat(fixture.savedPrograms.none { it.channelId == "100" && it.title == "Old covered guide" }).isTrue()+ verify(fixture.metadataRepository).updateMetadata(argThat {+ lastEpgSync == fixture.now && lastEpgSuccess == fixture.previousSuccess && epgCount == 6_001+ })+ }++ @Test+ fun `complete bulk guide remains healthy and advances freshness`() = runTest {+ val fixture = Fixture(bulkFailsAfterPrefix = false)+ fixture.setUp()++ val outcome = fixture.run()++ assertThat(outcome.hasRetryableFailure).isFalse()+ assertThat(outcome.warnings).isEmpty()+ assertThat(fixture.savedPrograms.count { it.channelId == "100" }).isEqualTo(6_000)+ assertThat(fixture.savedPrograms.any { it.channelId == "200" && it.title == "Old uncovered guide" }).isTrue()+ verify(fixture.metadataRepository).updateMetadata(argThat {+ lastEpgSync == fixture.now && lastEpgSuccess == fixture.now && epgCount == 6_001+ })+ }++ @Test+ fun `zero-prefix bulk failure can recover through complete per-channel fallback`() = runTest {+ val fixture = Fixture(bulkFailsAfterPrefix = false, bulkFailsBeforePrefix = true)+ fixture.setUp()++ val outcome = fixture.run()++ assertThat(outcome.hasRetryableFailure).isFalse()+ assertThat(outcome.warnings).isEmpty()+ assertThat(fixture.savedPrograms.count { it.channelId == "100" }).isEqualTo(2)+ assertThat(fixture.savedPrograms.count { it.channelId == "200" }).isEqualTo(2)+ assertThat(fixture.savedPrograms.any { it.title == "Old covered guide" || it.title == "Old uncovered guide" }).isFalse()+ verify(fixture.metadataRepository).updateMetadata(argThat {+ lastEpgSync == fixture.now && lastEpgSuccess == fixture.now && epgCount == 4+ })+ }++ private class Fixture(+ private val bulkFailsAfterPrefix: Boolean,+ private val bulkFailsBeforePrefix: Boolean = false+ ) {+ val now = 2_000L+ val previousSuccess = 1_000L+ val metadataRepository: SyncMetadataRepository = mock()+ val savedPrograms = mutableListOf(+ ProgramEntity(providerId = 7L, channelId = "100", title = "Old covered guide"),+ ProgramEntity(providerId = 7L, channelId = "200", title = "Old uncovered guide")+ )++ private val preferences: PreferencesRepository = mock()+ private val channelDao: ChannelDao = mock()+ private val programDao: ProgramDao = mock()+ private val epgSources: EpgSourceRepository = mock()+ private val portalState: StalkerPortalStateStore = mock()+ private val stalkerProvider: StalkerProvider = mock()+ private val transaction = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ }+ private val executor = ProviderEpgSyncExecutor(+ preferencesRepository = preferences,+ epgRepository = mock<EpgRepository>(),+ epgSourceRepository = epgSources,+ channelDao = channelDao,+ programDao = programDao,+ transactionRunner = transaction,+ syncMetadataRepository = metadataRepository,+ stalkerPortalStateStore = portalState,+ stalkerRequestCoordinator = StalkerRequestCoordinator(null, false, { now }),+ createStalkerProvider = { stalkerProvider },+ xtreamSupport = SyncManagerXtreamSupport(+ adaptiveSyncPolicy = mock(),+ shouldRememberSequentialPreference = { false },+ sanitizeThrowableMessage = { it?.message.orEmpty() },+ progress = { _, _, _ -> },+ movieRequestTimeoutMillis = 1_000L,+ seriesRequestTimeoutMillis = 1_000L,+ recoveryAbortWarningSuffix = "fixture"+ ),+ progress = { _, _, _ -> },+ sanitizeThrowableMessage = { it?.message.orEmpty() }+ )++ suspend fun setUp() {+ whenever(preferences.getHiddenCategoryIds(7L, ContentType.LIVE)).thenReturn(flowOf(emptySet()))+ whenever(epgSources.resolveForProvider(7L, emptySet())).thenReturn(EpgResolutionSummary())+ whenever(channelDao.getGuideSyncEntriesByProvider(7L)).thenReturn(+ listOf(+ ChannelGuideSyncEntity(name = "Covered", streamId = 100L, epgChannelId = "100"),+ ChannelGuideSyncEntity(name = "Uncovered", streamId = 200L, epgChannelId = "200")+ )+ )+ whenever(programDao.countByProvider(7L)).thenAnswer { savedPrograms.size }+ whenever(programDao.deleteForChannel(eq(7L), any())).thenAnswer { invocation ->+ val channelId = invocation.getArgument<String>(1)+ savedPrograms.removeAll { it.channelId == channelId }+ Unit+ }+ whenever(programDao.insertAll(any<List<ProgramEntity>>())).doSuspendableAnswer { invocation ->+ savedPrograms += invocation.getArgument<List<ProgramEntity>>(0)+ }+ whenever(metadataRepository.getMetadata(7L)).thenReturn(+ SyncMetadata(providerId = 7L, lastEpgSuccess = previousSuccess)+ )+ whenever(portalState.getValidated(7L)).thenReturn(null)+ whenever(stalkerProvider.recordEpgCapability(any())).thenReturn(Unit)+ whenever(stalkerProvider.streamBulkEpg(eq(6), any())).doSuspendableAnswer { invocation ->+ val onProgram = invocation.getArgument<suspend (Program) -> Unit>(1)+ if (!bulkFailsBeforePrefix) {+ repeat(6_000) { index ->+ onProgram(+ Program(+ channelId = "100",+ title = "Portal programme ${index + 1}",+ startTime = index * 60_000L,+ endTime = (index + 1) * 60_000L+ )+ )+ }+ }+ if (bulkFailsAfterPrefix || bulkFailsBeforePrefix) {+ Result.error("Interrupted native guide", IOException("fixture EOF"))+ }+ else Result.success(6_000)+ }+ whenever(stalkerProvider.streamEpg(any(), eq(6), any())).doSuspendableAnswer { invocation ->+ val channelId = invocation.getArgument<String>(0)+ val onProgram = invocation.getArgument<suspend (Program) -> Unit>(2)+ repeat(2) { index ->+ onProgram(+ Program(+ channelId = channelId,+ title = "Fallback $channelId ${index + 1}",+ startTime = index * 60_000L,+ endTime = (index + 1) * 60_000L+ )+ )+ }+ Result.success(2)+ }+ }++ suspend fun run() = executor.syncStalkerProviderEpg(+ provider = LegacyProvider(+ id = 7L,+ name = "Native guide fixture",+ type = ProviderType.STALKER_PORTAL,+ serverUrl = "http://portal.test",+ stalkerMacAddress = "00:11:22:33:44:55",+ guideSourcePolicy = GuideSourcePolicy.PROVIDER_ONLY+ ),+ metadata = SyncMetadata(providerId = 7L, lastEpgSuccess = previousSuccess),+ now = now,+ force = true,+ onProgress = null+ )+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/XtreamLivePlaybackYieldTest.kt b/data/src/test/java/com/streamvault/data/sync/XtreamLivePlaybackYieldTest.ktnew file mode 100644index 00000000..119f1778--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/XtreamLivePlaybackYieldTest.kt@@ -0,0 +1,37 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.test.runTest+import org.junit.Test+import java.io.IOException++class XtreamLivePlaybackYieldTest {+ @Test fun `manual idle and opt out remain eligible to continue`() {+ for (automatic in listOf(false, true)) for (defer in listOf(false, true)) for (active in listOf(false, true)) {+ assertThat(shouldYieldXtreamLiveBatch(automatic, defer, active)).isEqualTo(automatic && defer && active)+ }+ assertThat(CancellationException("external cancellation").isXtreamLivePlaybackDeferral()).isFalse()+ assertThat(IOException("source failure").isXtreamLivePlaybackDeferral()).isFalse()+ }++ @Test fun `pipeline drains children and preserves deferral identity without cancelling caller`() = runTest {+ var readerClosed = false+ var writes = 0+ val failure = runCatching {+ runXtreamLivePipeline<Int>(batchRows = 1, batchBytes = 100, queuedBatches = 1,+ estimatedBytes = { 1 }, prepare = {}, read = { emit ->+ try { repeat(100) { emit(it) }; 100 } finally { readerClosed = true }+ }, consume = {+ if (++writes == 2) throw XtreamLivePlaybackDeferredException()+ })+ }.exceptionOrNull()!!+ assertThat(failure.isXtreamLivePlaybackDeferral()).isTrue()+ assertThat(readerClosed).isTrue()+ assertThat(writes).isEqualTo(2)+ // A following child can run: cancellation was confined to the pipeline's scope.+ assertThat(async { 42 }.await()).isEqualTo(42)+ }+}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 2981b870..06805c28 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -11,12 +11,32 @@ All notable product changes are recorded in this document.### Changed- Channel, movie, series, and VOD category searches now ignore Latin accents (for example, “café” matches “cafe”). Existing catalogs upgrade automatically, with their content preserved.+- Reduced HLS playback allocations and released obsolete live-stream cache data while preserving resources needed by playback and shared recordings.+- Reduced background UI work during playback by stopping hidden playback controls from collecting state updates; reopening controls and open settings or chapter sheets continue receiving current values.+- Improved playback interruption diagnostics to distinguish rebuffering from dropped frames and track interruption durations more accurately.### Fixed+- Fixed eligible live MPEG-TS channels remaining unavailable after an Android TV-input video surface was recreated; playback now makes one safe recovery attempt.+- Fixed interrupted Stalker guide downloads being marked fresh and losing automatic retry; useful partial guide data is retained until a complete refresh succeeds.+- Fixed automatic guide refreshes stopping after temporary HTTP errors such as 429 and 503; they now retain cached guide data and retry, while authentication failures remain terminal.- Fixed a Sports tab crash on Android 11 when initializing Brazilian Portuguese EPG title parsing.- Fixed HLS playback failing on master playlists with `EXT-X-MEDIA` rendition tags missing the required `NAME` attribute.- Fixed some more backup and restore bugs.- Fixed sports listings ending in `- VT` appearing as scheduled matches instead of replays, and localized the new league names in Sports.+- Fixed automatic background EPG refreshes and freshness-repair jobs ignoring the defer-while-busy preference during playback, while preserving manual refreshes and explicit overlap settings.+- Fixed M3U guide imports already in progress continuing after playback starts; they now defer safely, retain existing guide data, and can retry after playback stops.+- Fixed automatic Xtream bulk live-channel imports continuing during playback; they now yield safely and can retry when idle without replacing the existing channel list with partial data.+- Fixed Stalker automatic indexing missing live playback from the same provider when deciding whether to defer background work.+- Fixed Android TV-input playback not being recognized by background-sync scheduling, allowing automatic catalog and guide work to run despite defer-while-busy settings.+- Fixed incorrect frame-rate estimates for streams with missing frame-rate metadata or rounded video timestamps.+- Fixed repeated live HLS rebuffering in manual buffer modes when playback started too close to the live edge.+- Fixed long pauses between reads in Medium and Large buffer modes causing idle-sensitive live MPEG-TS connections to close.+- Fixed raw MPEG-TS H.264 picture freezes caused by header-only decoder samples with duplicate timestamps.+- Improved bounded recovery from temporarily unavailable or expired live HLS media segments while preserving terminal authentication errors.+- Fixed optional HLS subtitle loading blocking audio/video prefetch on affected live streams.+- Fixed live streams remaining stuck before the first frame by allowing one recovery attempt and reporting failure if startup still cannot complete, including Android TV-input playback.+- Added one bounded recovery attempt when an eligible live MPEG-TS stream ends unexpectedly, including Android TV-input playback, while preserving normal end-of-playback behavior for finite content.+- Fixed shared HLS recording restarts losing required encryption keys or initialization data.## [1.2.2]diff --git a/domain/src/main/java/com/streamvault/domain/sync/AutomaticSync.kt b/domain/src/main/java/com/streamvault/domain/sync/AutomaticSync.ktindex 12946fb4..a9494db9 100644--- a/domain/src/main/java/com/streamvault/domain/sync/AutomaticSync.kt+++ b/domain/src/main/java/com/streamvault/domain/sync/AutomaticSync.kt@@ -84,12 +84,22 @@ data class AutomaticSyncStatus(val sections: List<RefreshSection> = emptyList())-/** In-process playback ownership, including paused/buffering players and split screen. */+/** Engine-owned playback sessions, including paused/buffering players and split screen. */object AutomaticSyncActivity {- private val players = java.util.concurrent.ConcurrentHashMap.newKeySet<Any>()+ private val players = java.util.concurrent.ConcurrentHashMap<Any, Long>()private val mutablePlaybackActive = kotlinx.coroutines.flow.MutableStateFlow(false)val playbackActive: kotlinx.coroutines.flow.StateFlow<Boolean> get() = mutablePlaybackActiveval hasPlayback: Boolean get() = players.isNotEmpty()- fun started(owner: Any) { synchronized(players) { players.add(owner); mutablePlaybackActive.value = players.isNotEmpty() } }+ fun started(owner: Any) = started(owner, null)+ fun started(owner: Any, providerId: Long?) {+ synchronized(players) {+ // Reprepare transfers this owner's provider instead of adding a second session.+ players[owner] = providerId?.takeIf { it > 0L } ?: 0L+ mutablePlaybackActive.value = players.isNotEmpty()+ }+ }+ fun isProviderPlaybackActive(providerId: Long): Boolean = providerId > 0L && synchronized(players) {+ players.containsValue(providerId)+ }fun stopped(owner: Any) { synchronized(players) { players.remove(owner); mutablePlaybackActive.value = players.isNotEmpty() } }}diff --git a/domain/src/main/java/com/streamvault/domain/util/LivePlaybackByteTap.kt b/domain/src/main/java/com/streamvault/domain/util/LivePlaybackByteTap.ktindex dd34417e..f7145dda 100644--- a/domain/src/main/java/com/streamvault/domain/util/LivePlaybackByteTap.kt+++ b/domain/src/main/java/com/streamvault/domain/util/LivePlaybackByteTap.kt@@ -1,9 +1,9 @@package com.streamvault.domain.utilimport com.streamvault.domain.model.LivePlaybackIdentity-import java.io.ByteArrayOutputStreamimport java.io.Closeableimport java.io.IOException+import java.net.URIimport java.security.MessageDigestimport java.util.concurrent.ScheduledThreadPoolExecutorimport java.util.concurrent.TimeUnit@@ -23,9 +23,40 @@ private data class CachedHlsResource(val aliases: Set<HlsResourceKey>,val bytes: ByteArray,val updatedAtMs: Long,- val isPlaylist: Boolean+ val isPlaylist: Boolean,+ val isMediaSegment: Boolean,+ val wasReferencedDependency: Boolean,+ val references: HlsPlaylistReferences?)+private data class HlsPlaylistReferences(val media: Set<String>, val dependencies: Set<String>)++/** Identify resource roles conservatively before reclaiming media or consumed dependencies. */+private fun hlsPlaylistReferences(baseUrl: String, bytes: ByteArray): HlsPlaylistReferences? = runCatching {+ require(bytes.looksLikeHlsPlaylist())+ val base = URI(baseUrl)+ val media = HashSet<String>()+ val dependencies = HashSet<String>()+ var mediaUriExpected = false+ bytes.toString(Charsets.UTF_8).lineSequence().forEach { rawLine ->+ val line = rawLine.trim().removePrefix("\uFEFF")+ if (line.startsWith("#EXTINF:")) mediaUriExpected = true+ if (line.startsWith("#") && ':' in line) {+ val attributes = line.substringAfter(':')+ val uris = HLS_URI_ATTRIBUTE.findAll(attributes).map { it.groupValues[1] }.toList()+ // Unknown/unresolved attribute syntax must not make a dependency evictable.+ if ("URI=" in attributes) require(uris.isNotEmpty())+ uris.forEach { dependencies.add(base.resolve(it).toString()) }+ } else if (line.isNotEmpty() && !line.startsWith("#")) {+ if (mediaUriExpected) media.add(base.resolve(line).toString())+ mediaUriExpected = false+ }+ }+ HlsPlaylistReferences(media, dependencies)+}.getOrNull()++private val HLS_URI_ATTRIBUTE = Regex("(?:^|,)URI=\"([^\"]*)\"")+private data class HlsResourceKey(val url: String,val rangeStart: Long,@@ -53,6 +84,56 @@ private fun ByteArray.looksLikeText(): Boolean = all { byte ->private val HLS_WHITESPACE_BYTES = setOf(' '.code, '\t'.code, '\n'.code, '\r'.code)+/** Accumulates responses without copying all earlier bytes whenever the buffer grows. */+private class HlsResponseBuffer {+ private val chunks = ArrayList<ByteArray>()+ private var tailSize = 0+ var size: Int = 0+ private set++ fun write(bytes: ByteArray, offset: Int, length: Int) {+ var sourceOffset = offset+ var remaining = length+ while (remaining > 0) {+ if (chunks.isEmpty() || tailSize == chunks.last().size) {+ // Small playlists and keys do not need a full segment-sized chunk.+ chunks.add(ByteArray(if (chunks.isEmpty()) remaining.coerceIn(4096, 65536) else 65536))+ tailSize = 0+ }+ val tail = chunks.last()+ val count = minOf(remaining, tail.size - tailSize)+ bytes.copyInto(tail, tailSize, sourceOffset, sourceOffset + count)+ tailSize += count+ sourceOffset += count+ remaining -= count+ size += count+ }+ }++ fun takeBytes(): ByteArray {+ val result = if (chunks.size == 1 && tailSize == chunks[0].size) {+ chunks[0]+ } else {+ ByteArray(size).also { bytes ->+ var offset = 0+ chunks.forEachIndexed { index, chunk ->+ val count = if (index == chunks.lastIndex) tailSize else chunk.size+ chunk.copyInto(bytes, offset, 0, count)+ offset += count+ }+ }+ }+ clear()+ return result+ }++ fun clear() {+ chunks.clear()+ tailSize = 0+ size = 0+ }+}+class LivePlaybackCaptureBackpressureException : IOException("Live playback capture exceeded its bounded buffer.")@@ -352,9 +433,15 @@ class LivePlaybackByteTap @Inject constructor() {@Synchronizedprivate fun consume(resourceId: Long, capture: HlsCaptureImpl) {val resource = resourcesById[resourceId] ?: return- if (capture !in captures || resource.id < capture.firstRecordingResourceId) return+ if (capture !in captures || resource.id < capture.firstRecordingResourceId &&+ !resource.wasReferencedDependency && !isReferencedDependency(resource)+ ) returncapture.consumedResourceIds += resource.id- if (!isRequiredByCapture(resource)) removeResource(resource)+ // Initialization maps can be consumed by one recording and still be needed+ // by another recording which attaches after Media3's one-time map request.+ if (!isRequiredByCapture(resource) && !resource.isPlaylist &&+ !resource.wasReferencedDependency && !isReferencedDependency(resource)+ ) removeResource(resource)}@Synchronized@@ -369,19 +456,54 @@ class LivePlaybackByteTap @Inject constructor() {@Synchronizedprivate fun detach(capture: HlsCaptureImpl) {captures.remove(capture)- resourcesById.values.toList()- .filterNot(::isRequiredByCapture)- .forEach(::removeResource)if (captures.isEmpty()) {failure = null+ // Keep the current manifest and warm dependencies for a subsequent+ // recording. Closing the last reader must not discard a cached key/map+ // which playback may never request again.+ pruneIdleObsoleteResources()scheduleHlsCleanup(this@HlsSourceSession)+ } else {+ resourcesById.values.toList()+ .filter { it.isMediaSegment && !isRequiredByCapture(it) && !isReferencedDependency(it) }+ .forEach(::removeResource)+ }+ }++ private fun isReferencedDependency(resource: CachedHlsResource): Boolean =+ resourcesById.values.any { playlist ->+ playlist.references?.dependencies?.let { dependencies ->+ resource.aliases.any { it.url in dependencies }+ } == true+ }++ /** Idle readers never record media from before attachment. Retain the current+ * window conservatively, but release classified resources once every cached+ * playlist has rolled past them. Unknown manifests/resources remain bounded+ * by the existing cache policy rather than being guessed disposable here. */+ private fun pruneIdleObsoleteResources() {+ if (captures.isNotEmpty()) return+ val playlists = resourcesById.values.filter { it.isPlaylist }+ if (playlists.isEmpty()) return+ val references = playlists.map { it.references ?: return }+ val referenced = HashSet<String>()+ references.forEach {+ referenced.addAll(it.media)+ referenced.addAll(it.dependencies)}+ resourcesById.values.toList()+ .filter { resource ->+ !resource.isPlaylist && (resource.isMediaSegment || resource.wasReferencedDependency) &&+ resource.aliases.none { it.url in referenced }+ }+ .forEach(::removeResource)}private fun isRequiredByCapture(resource: CachedHlsResource): Boolean =captures.any { capture ->- resource.id >= capture.firstRecordingResourceId &&- resource.id !in capture.consumedResourceIds+ resource.id !in capture.consumedResourceIds &&+ (resource.id >= capture.firstRecordingResourceId ||+ resource.wasReferencedDependency || isReferencedDependency(resource))}@Synchronized@@ -409,19 +531,30 @@ class LivePlaybackByteTap @Inject constructor() {return}- val used = if (isPlaylist) playlistBytes else payloadBytes- if (captures.isNotEmpty() && used + bytes.size > limit) {- // A recording must not silently skip an evicted segment. Fail the capture before- // producing a file with gaps; foreground playback remains non-blocking.- failure = LivePlaybackCaptureBackpressureException()- return- }- while (captures.isEmpty() &&- (if (isPlaylist) playlistBytes else payloadBytes) + bytes.size > limit- ) {- val oldest = resourcesById.values.firstOrNull { it.isPlaylist == isPlaylist } ?: break+ val playlists = resourcesById.values.filter { it.isPlaylist }+ val references = playlists.mapNotNull { it.references }+ val dependenciesKnown = playlists.isNotEmpty() && references.size == playlists.size+ val dependencies = references.flatMapTo(HashSet()) { it.dependencies }+ val isMediaSegment = !isPlaylist &&+ aliases.any { alias -> references.any { alias.url in it.media } } &&+ aliases.none { it.url in dependencies }+ while ((if (isPlaylist) playlistBytes else payloadBytes) + bytes.size > limit) {+ val oldest = resourcesById.values.firstOrNull { resource ->+ resource.isPlaylist == isPlaylist &&+ // Keep referenced keys/maps warm even before a recording attaches.+ resource.aliases.none { it.url in dependencies } &&+ (captures.isEmpty() ||+ dependenciesKnown && !isRequiredByCapture(resource) &&+ (resource.isMediaSegment || resource.wasReferencedDependency))+ } ?: breakremoveResource(oldest)}+ if ((if (isPlaylist) playlistBytes else payloadBytes) + bytes.size > limit) {+ // Never evict a segment still owed to a recording, or guess that a warm key,+ // initialization response, or unclassified payload is disposable media.+ if (captures.isNotEmpty()) failure = LivePlaybackCaptureBackpressureException()+ return+ }val resourceId = nextResourceId++val entry = CachedHlsResource(@@ -430,11 +563,15 @@ class LivePlaybackByteTap @Inject constructor() {aliases = aliases,bytes = bytes,updatedAtMs = elapsedRealtimeMs(),- isPlaylist = isPlaylist+ isPlaylist = isPlaylist,+ isMediaSegment = isMediaSegment,+ wasReferencedDependency = !isPlaylist && aliases.any { it.url in dependencies },+ references = if (isPlaylist) hlsPlaylistReferences(resolvedUrl, bytes) else null)resourcesById[resourceId] = entryaliases.forEach { resourcesByUrl[it] = entry }if (isPlaylist) playlistBytes += bytes.size else payloadBytes += bytes.size+ if (isPlaylist) pruneIdleObsoleteResources()}private fun CachedHlsResource.toPublicResource() =@@ -451,6 +588,9 @@ class LivePlaybackByteTap @Inject constructor() {private fun removeResource(resource: CachedHlsResource) {val entry = resourcesById.entries.firstOrNull { it.value === resource } ?: returnresourcesById.remove(entry.key)+ // IDs are monotonic and cannot become readable again after removal.+ // Keeping their consumption history would grow for the entire recording.+ captures.forEach { it.consumedResourceIds.remove(resource.id) }resource.aliases.forEach { alias ->if (resourcesByUrl[alias] === resource) resourcesByUrl.remove(alias)}@@ -464,7 +604,7 @@ class LivePlaybackByteTap @Inject constructor() {private val rangeStart: Long,private val rangeLength: Long) : HlsPublisher {- private var output = ByteArrayOutputStream()+ private val output = HlsResponseBuffer()private var completed = falseprivate var oversized = false@@ -474,9 +614,9 @@ class LivePlaybackByteTap @Inject constructor() {synchronized(this@HlsSourceSession) {if (completed || oversized) returnlastActivityAtMs = elapsedRealtimeMs()- if (output.size() + length > MAX_HLS_RESOURCE_BYTES) {+ if (length > MAX_HLS_RESOURCE_BYTES - output.size) {oversized = true- output.reset()+ output.clear()return}output.write(buffer, offset, length)@@ -490,12 +630,12 @@ class LivePlaybackByteTap @Inject constructor() {if (oversized) {if (captures.isNotEmpty()) failure = LivePlaybackCaptureBackpressureException()} else {- val bytes = output.toByteArray()+ val bytes = output.takeBytes()val bodyIsPlaylist = bytes.looksLikeHlsPlaylist() ||(isPlaylist && bytes.looksLikeText())store(requestedUrl, resolvedUrl, bytes, bodyIsPlaylist, rangeStart, rangeLength)}- output = ByteArrayOutputStream()+ output.clear()}scheduleHlsCleanup(this@HlsSourceSession)}@@ -504,7 +644,7 @@ class LivePlaybackByteTap @Inject constructor() {synchronized(this@HlsSourceSession) {if (completed) returncompleted = true- output = ByteArrayOutputStream()+ output.clear()}scheduleHlsCleanup(this@HlsSourceSession)}diff --git a/domain/src/test/java/com/streamvault/domain/sync/AutomaticSyncActivityTest.kt b/domain/src/test/java/com/streamvault/domain/sync/AutomaticSyncActivityTest.ktnew file mode 100644index 00000000..e197c299--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/sync/AutomaticSyncActivityTest.kt@@ -0,0 +1,55 @@+package com.streamvault.domain.sync++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class AutomaticSyncActivityTest {+ @Test fun reprepareTransfersProviderWithoutLeakingAnOwner() {+ val owner = Any()+ try {+ AutomaticSyncActivity.started(owner, 7)+ AutomaticSyncActivity.started(owner, 7)+ AutomaticSyncActivity.started(owner, 8)+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(7)).isFalse()+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(8)).isTrue()+ assertThat(AutomaticSyncActivity.playbackActive.value).isTrue()+ AutomaticSyncActivity.stopped(owner)+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(8)).isFalse()+ assertThat(AutomaticSyncActivity.hasPlayback).isFalse()+ } finally { AutomaticSyncActivity.stopped(owner) }+ }+ @Test fun multiplePlayersAndProvidersRetainOnlyTheirOwnOwnership() {+ val first=Any(); val second=Any(); val other=Any()+ try {+ AutomaticSyncActivity.started(first,7); AutomaticSyncActivity.started(second,7)+ AutomaticSyncActivity.started(other,8)+ AutomaticSyncActivity.stopped(first)+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(7)).isTrue()+ AutomaticSyncActivity.stopped(other)+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(8)).isFalse()+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(7)).isTrue()+ AutomaticSyncActivity.stopped(second)+ assertThat(AutomaticSyncActivity.playbackActive.value).isFalse()+ } finally { listOf(first,second,other).forEach(AutomaticSyncActivity::stopped) }+ }+ @Test fun unknownPlaybackStillBlocksGlobalAdmissionWithoutClaimingAProvider() {+ val owner=Any()+ try {+ AutomaticSyncActivity.started(owner)+ assertThat(AutomaticSyncActivity.hasPlayback).isTrue()+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(1)).isFalse()+ AutomaticSyncActivity.started(owner,-1)+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(-1)).isFalse()+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(0)).isFalse()+ } finally { AutomaticSyncActivity.stopped(owner) }+ }+ @Test fun stoppedOwnerCanResumeWithProviderIdentity() {+ val owner=Any()+ try {+ AutomaticSyncActivity.started(owner,7); AutomaticSyncActivity.stopped(owner)+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(7)).isFalse()+ AutomaticSyncActivity.started(owner,7)+ assertThat(AutomaticSyncActivity.isProviderPlaybackActive(7)).isTrue()+ } finally { AutomaticSyncActivity.stopped(owner) }+ }+}diff --git a/domain/src/test/java/com/streamvault/domain/util/LivePlaybackByteTapTest.kt b/domain/src/test/java/com/streamvault/domain/util/LivePlaybackByteTapTest.ktnew file mode 100644index 00000000..94edbee7--- /dev/null+++ b/domain/src/test/java/com/streamvault/domain/util/LivePlaybackByteTapTest.kt@@ -0,0 +1,399 @@+package com.streamvault.domain.util++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.LivePlaybackIdentity+import org.junit.Test++class LivePlaybackByteTapTest {+ private val tap = LivePlaybackByteTap()+ private val identity = LivePlaybackIdentity(1, 2)+ private val playlistUrl = "https://fixture.invalid/live/index.m3u8"++ private fun publisher(url: String, playlist: Boolean = false, start: Long = 0, length: Long = -1) =+ tap.beginHlsResource(identity, "fingerprint", url, url, playlist, start, length)++ private fun publish(url: String, bytes: ByteArray, playlist: Boolean = false) {+ publisher(url, playlist).use { resource ->+ resource.publish(bytes, 0, bytes.size)+ resource.complete()+ }+ }++ private fun openCapture(): LivePlaybackByteTap.HlsCapture =+ requireNotNull(tap.attachHls(identity, "fingerprint"))++ @Test fun `late recording can read warm playlists and encryption or initialization resources`() {+ val playlist = "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"key\"\n#EXT-X-MAP:URI=\"init\"\n".toByteArray()+ val key = ByteArray(16) { it.toByte() }+ val init = byteArrayOf(4, 5, 6)+ publish(playlistUrl, playlist, playlist = true)+ publish("https://fixture.invalid/live/key", key)+ publish("https://fixture.invalid/live/init", init)+ openCapture().use { capture ->+ assertThat(capture.resource(playlistUrl)?.bytes).isEqualTo(playlist)+ assertThat(capture.resource("https://fixture.invalid/live/key")?.bytes).isEqualTo(key)+ assertThat(capture.resource("https://fixture.invalid/live/init")?.bytes).isEqualTo(init)+ assertThat(tap.attachHls(identity, "different")).isNull()+ }+ }++ @Test fun `consumed map and warm playlist dependencies survive for the next recording`() {+ val base = "https://fixture.invalid/live/"+ val mapUrl = base + "init.mp4"+ val keyUrl = base + "key"+ val segmentUrl = base + "segment.mp4"+ val playlist = """+ #EXTM3U+ #EXT-X-TARGETDURATION:2+ #EXT-X-KEY:METHOD=AES-128,URI="key"+ #EXT-X-MAP:URI="init.mp4",BYTERANGE="4@0"+ #EXTINF:2,+ segment.mp4+ """.trimIndent().toByteArray()+ publish(playlistUrl, playlist, playlist = true)+ publish(keyUrl, ByteArray(16) { it.toByte() })++ openCapture().use { first ->+ publisher(mapUrl, start = 0, length = 4).use { resource ->+ resource.publish(byteArrayOf(4, 3, 2, 1), 0, 4)+ resource.complete()+ }+ publish(segmentUrl, byteArrayOf(8, 9))+ val map = requireNotNull(first.resource(mapUrl, rangeStart = 0, rangeLength = 4))+ val segment = requireNotNull(first.recordingResource(segmentUrl))+ first.consume(map)+ first.consume(segment)++ assertThat(first.resource(mapUrl, rangeStart = 0, rangeLength = 4)).isNotNull()+ assertThat(first.resource(segmentUrl)).isNull()+ }++ openCapture().use { second ->+ assertThat(second.resource(playlistUrl)?.bytes).isEqualTo(playlist)+ assertThat(second.resource(keyUrl)?.bytes).isEqualTo(ByteArray(16) { it.toByte() })+ assertThat(second.resource(mapUrl, rangeStart = 0, rangeLength = 4)?.bytes)+ .isEqualTo(byteArrayOf(4, 3, 2, 1))+ // A resource from the first capture is never eligible as newly recorded media.+ assertThat(second.recordingResource(segmentUrl)).isNull()+ val nextSegmentUrl = base + "next.mp4"+ publish(nextSegmentUrl, byteArrayOf(10, 11))+ assertThat(second.recordingResource(nextSegmentUrl)?.bytes).isEqualTo(byteArrayOf(10, 11))+ }+ }++ @Test fun `closing capture prunes rolled media but keeps current window and its dependencies`() {+ val base = "https://fixture.invalid/live/"+ val oldSegment = base + "old.ts"+ val currentSegment = base + "current.ts"+ val currentKey = base + "current-key"+ val currentMap = base + "current-init"+ publish(+ playlistUrl,+ "#EXTM3U\n#EXTINF:2,\nold.ts\n".toByteArray(),+ playlist = true+ )+ publish(oldSegment, byteArrayOf(1, 2, 3))+ publish(+ playlistUrl,+ ("#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"current-key\"\n" ++ "#EXT-X-MAP:URI=\"current-init\"\n#EXTINF:2,\ncurrent.ts\n").toByteArray(),+ playlist = true+ )+ publish(currentKey, ByteArray(16) { 7 })+ publish(currentMap, byteArrayOf(5, 6, 7))+ publish(currentSegment, byteArrayOf(8, 9, 10))++ openCapture().close()++ openCapture().use { capture ->+ assertThat(capture.resource(playlistUrl)).isNotNull()+ assertThat(capture.resource(oldSegment)).isNull()+ assertThat(capture.resource(currentSegment)?.bytes).isEqualTo(byteArrayOf(8, 9, 10))+ assertThat(capture.resource(currentKey)?.bytes).isEqualTo(ByteArray(16) { 7 })+ assertThat(capture.resource(currentMap)?.bytes).isEqualTo(byteArrayOf(5, 6, 7))+ }+ }++ @Test fun `idle playlist roll prunes obsolete media and retains current resources`() {+ val base = "https://fixture.invalid/live/"+ val oldSegment = base + "old.ts"+ val currentSegment = base + "current.ts"+ val currentKey = base + "current-key"+ val currentMap = base + "current-init"+ publish(+ playlistUrl,+ "#EXTM3U\n#EXTINF:2,\nold.ts\n#EXTINF:2,\ncurrent.ts\n".toByteArray(),+ playlist = true+ )+ publish(oldSegment, byteArrayOf(1, 2, 3))+ publish(+ playlistUrl,+ ("#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"current-key\"\n" ++ "#EXT-X-MAP:URI=\"current-init\"\n#EXTINF:2,\ncurrent.ts\n").toByteArray(),+ playlist = true+ )+ publish(currentKey, ByteArray(16) { 7 })+ publish(currentMap, byteArrayOf(5, 6, 7))+ publish(currentSegment, byteArrayOf(8, 9, 10))++ openCapture().use { capture ->+ assertThat(capture.resource(oldSegment)).isNull()+ assertThat(capture.resource(playlistUrl)).isNotNull()+ assertThat(capture.resource(currentSegment)?.bytes).isEqualTo(byteArrayOf(8, 9, 10))+ assertThat(capture.resource(currentKey)?.bytes).isEqualTo(ByteArray(16) { 7 })+ assertThat(capture.resource(currentMap)?.bytes).isEqualTo(byteArrayOf(5, 6, 7))+ }+ }++ @Test fun `detaching one capture does not prune a segment another capture still owes`() {+ val base = "https://fixture.invalid/live/"+ val firstSegment = base + "first.ts"+ val secondSegment = base + "second.ts"+ publish(+ playlistUrl,+ "#EXTM3U\n#EXTINF:2,\nfirst.ts\n#EXTINF:2,\nsecond.ts\n".toByteArray(),+ playlist = true+ )+ val first = openCapture()+ val second = openCapture()+ publish(firstSegment, byteArrayOf(1, 2))+ publish(secondSegment, byteArrayOf(3, 4))++ first.consume(requireNotNull(first.recordingResource(firstSegment)))+ first.close()++ assertThat(second.recordingResource(firstSegment)?.bytes).isEqualTo(byteArrayOf(1, 2))+ assertThat(second.recordingResource(secondSegment)?.bytes).isEqualTo(byteArrayOf(3, 4))+ second.close()+ }++ @Test fun `consumed rotated maps can be reclaimed under recording cache pressure`() {+ val base = "https://fixture.invalid/live/"+ publish(playlistUrl, "#EXTM3U\n".toByteArray(), playlist = true)+ openCapture().use { capture ->+ repeat(4) { index ->+ publish(playlistUrl, "#EXTM3U\n#EXT-X-MAP:URI=\"init-$index\"\n".toByteArray(), true)+ publish(base + "init-$index", ByteArray(12 * 1024 * 1024) { index.toByte() })+ capture.throwIfFailed()+ val map = requireNotNull(capture.resource(base + "init-$index"))+ capture.consume(map)+ assertThat(capture.resource(base + "init-$index")).isNotNull()+ }+ }+ }++ @Test fun `a warm map not consumed by another recording remains protected under pressure`() {+ val base = "https://fixture.invalid/live/"+ publish(playlistUrl, "#EXTM3U\n#EXT-X-MAP:URI=\"init-0\"\n".toByteArray(), true)+ publish(base + "init-0", ByteArray(12 * 1024 * 1024))+ openCapture().use { first ->+ openCapture().use { second ->+ first.consume(requireNotNull(first.resource(base + "init-0")))+ publish(playlistUrl, "#EXTM3U\n#EXT-X-MAP:URI=\"init-1\"\n".toByteArray(), true)+ publish(base + "init-1", ByteArray(12 * 1024 * 1024))+ first.consume(requireNotNull(first.resource(base + "init-1")))+ publish(playlistUrl, "#EXTM3U\n#EXT-X-MAP:URI=\"init-2\"\n".toByteArray(), true)+ publish(base + "init-2", ByteArray(12 * 1024 * 1024))+ org.junit.Assert.assertThrows(LivePlaybackCaptureBackpressureException::class.java) {+ second.throwIfFailed()+ }+ assertThat(second.resource(base + "init-0")).isNotNull()+ assertThat(second.resource(base + "init-1")).isNotNull()+ }+ }+ }++ @Test fun `removed media does not keep an unbounded recording consumption history`() {+ val url = "https://fixture.invalid/live/media.ts"+ publish(playlistUrl, "#EXTM3U\n#EXTINF:2,\nmedia.ts\n".toByteArray(), true)+ openCapture().use { capture ->+ repeat(1_000) {+ publish(url, byteArrayOf(1, 2))+ capture.consume(requireNotNull(capture.recordingResource(url)))+ }+ val history = capture.javaClass.getDeclaredField("consumedResourceIds").apply {+ isAccessible = true+ }.get(capture) as Set<*>+ assertThat(history.size).isLessThan(16)+ }+ }++ @Test fun `resource that completes after attachment is available without a second request`() {+ publish(playlistUrl, "#EXTM3U\n".toByteArray(), playlist = true)+ val url = "https://fixture.invalid/live/segment.ts"+ publisher(url).use { resource ->+ val bytes = ByteArray(65_537) { (it % 251).toByte() }+ resource.publish(bytes, 0, 50_000)+ openCapture().use { capture ->+ resource.publish(bytes, 50_000, bytes.size - 50_000)+ resource.complete()+ assertThat(capture.recordingResource(url)?.bytes).isEqualTo(bytes)+ }+ }+ }++ @Test fun `recording starts with new resources and one reader cannot discard another reader's segment`() {+ val old = "https://fixture.invalid/old.ts"+ val fresh = "https://fixture.invalid/new.ts"+ publish(old, byteArrayOf(1))+ openCapture().use { first ->+ openCapture().use { second ->+ assertThat(first.recordingResource(old)).isNull()+ publish(fresh, byteArrayOf(2, 3))+ first.consume(requireNotNull(first.recordingResource(fresh)))+ assertThat(second.recordingResource(fresh)?.bytes).isEqualTo(byteArrayOf(2, 3))+ second.consume(requireNotNull(second.recordingResource(fresh)))+ assertThat(second.recordingResource(fresh)).isNull()+ }+ }+ }++ @Test fun `range keys distinguish adjacent initialization or segment byte ranges`() {+ val url = "https://fixture.invalid/live/file.mp4"+ publisher(url, start = 20, length = 3).use { resource ->+ openCapture().use { capture ->+ resource.publish(byteArrayOf(9, 8, 7), 0, 3)+ resource.complete()+ assertThat(capture.recordingResource(url, 20, 3)?.bytes).isEqualTo(byteArrayOf(9, 8, 7))+ assertThat(capture.recordingResource(url, 21, 3)).isNull()+ assertThat(capture.recordingResource(url)).isNull()+ }+ }+ }++ @Test fun `incomplete reads never become captured resources`() {+ val url = "https://fixture.invalid/live/truncated.ts"+ publisher(url).use { resource -> resource.publish(byteArrayOf(1, 2), 0, 2) }+ openCapture().use { capture -> assertThat(capture.resource(url)).isNull() }+ }++ @Test fun `chunked response preserves offset reads and owns published bytes`() {+ val url = "https://fixture.invalid/live/large.ts"+ val expected = ByteArray(3 * 65536 + 31) { (it % 251).toByte() }+ val scratch = ByteArray(4107)+ publisher(url).use { resource ->+ var position = 0+ while (position < expected.size) {+ val count = minOf(4093, expected.size - position)+ expected.copyInto(scratch, 7, position, position + count)+ resource.publish(scratch, 7, count)+ scratch.fill(0)+ position += count+ }+ resource.complete()+ resource.complete()+ }+ openCapture().use { capture -> assertThat(capture.resource(url)?.bytes).isEqualTo(expected) }+ }++ @Test fun `response at the byte limit is retained intact`() {+ val url = "https://fixture.invalid/live/limit.ts"+ val chunk = ByteArray(65536) { (it % 239).toByte() }+ publisher(url).use { resource ->+ repeat(512) { resource.publish(chunk, 0, chunk.size) }+ resource.complete()+ }+ openCapture().use { capture ->+ val bytes = requireNotNull(capture.resource(url)).bytes+ assertThat(bytes.size).isEqualTo(32 * 1024 * 1024)+ assertThat(bytes.take(31)).containsExactlyElementsIn(chunk.take(31)).inOrder()+ assertThat(bytes.takeLast(31)).containsExactlyElementsIn(chunk.takeLast(31)).inOrder()+ }+ }++ @Test fun `oversized response fails recording explicitly without retaining partial bytes`() {+ publish(playlistUrl, "#EXTM3U\n".toByteArray(), playlist = true)+ openCapture().use { capture ->+ val url = "https://fixture.invalid/live/oversized.ts"+ publisher(url).use { resource ->+ val chunk = ByteArray(65536)+ repeat(512) { resource.publish(chunk, 0, chunk.size) }+ resource.publish(byteArrayOf(1), 0, 1)+ resource.complete()+ }+ assertThat(capture.resource(url)).isNull()+ org.junit.Assert.assertThrows(LivePlaybackCaptureBackpressureException::class.java) {+ capture.throwIfFailed()+ }+ }+ }++ @Test fun `recording can reclaim old media after its playlist window rolls while preserving dependencies`() {+ val base = "https://fixture.invalid/live/"+ val oldSegments = (1..5).map { "old-$it.ts" }+ val header = "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"key\"\n#EXT-X-MAP:URI=\"init\"\n"+ publish(playlistUrl, (header + oldSegments.joinToString("") { "#EXTINF:2,\n$it\n" }).toByteArray(), true)+ val key = ByteArray(16) { 7 }+ val init = ByteArray(128) { 9 }+ publish(base + "key", key)+ publish(base + "init", init)+ oldSegments.forEach { publish(base + it, ByteArray(8 * 1024 * 1024)) }+ publish(playlistUrl, (header + "#EXTINF:2,\nnew.ts\n").toByteArray(), true)+ openCapture().use { capture ->+ publish(base + "new.ts", ByteArray(8 * 1024 * 1024) { 1 })+ capture.throwIfFailed()+ assertThat(capture.recordingResource(base + "new.ts")?.bytes?.size).isEqualTo(8 * 1024 * 1024)+ assertThat(capture.resource(base + oldSegments.first())).isNull()+ assertThat(capture.resource(base + oldSegments[2])).isNull()+ assertThat(capture.resource(base + "key")?.bytes).isEqualTo(key)+ assertThat(capture.resource(base + "init")?.bytes).isEqualTo(init)+ }+ }++ @Test fun `cache pressure cannot evict segments still owed to another recording`() {+ val base = "https://fixture.invalid/live/"+ publish(playlistUrl, "#EXTM3U\n#EXTINF:2,\na.ts\n#EXTINF:2,\nb.ts\n#EXTINF:2,\nc.ts\n".toByteArray(), true)+ openCapture().use { first ->+ openCapture().use { second ->+ listOf("a.ts", "b.ts").forEach { name ->+ publish(base + name, ByteArray(12 * 1024 * 1024))+ first.consume(requireNotNull(first.recordingResource(base + name)))+ }+ publish(base + "c.ts", ByteArray(12 * 1024 * 1024))+ org.junit.Assert.assertThrows(LivePlaybackCaptureBackpressureException::class.java) {+ second.throwIfFailed()+ }+ assertThat(second.recordingResource(base + "a.ts")).isNotNull()+ assertThat(second.recordingResource(base + "b.ts")).isNotNull()+ }+ }+ }++ @Test fun `map sharing a URI with media and unresolved variable dependencies remain protected`() {+ val url = "https://fixture.invalid/live/shared.mp4"+ val headers = listOf(+ "#EXT-X-MAP:URI=\"shared.mp4\",BYTERANGE=\"32@0\"",+ "#EXT-X-KEY:METHOD=AES-128,URI=\"{\$key}\""+ )+ headers.forEach { header ->+ publish(playlistUrl, "#EXTM3U\n#EXTINF:2,\nshared.mp4\n".toByteArray(), true)+ publish(url, ByteArray(32 * 1024 * 1024))+ publish(playlistUrl, "#EXTM3U\n$header\n#EXTINF:2,\nshared.mp4\n".toByteArray(), true)+ openCapture().use { capture ->+ publish("https://fixture.invalid/live/new.ts", byteArrayOf(1))+ org.junit.Assert.assertThrows(LivePlaybackCaptureBackpressureException::class.java) {+ capture.throwIfFailed()+ }+ assertThat(capture.resource(url)).isNotNull()+ }+ }+ }++ @Test fun `idle eviction removes obsolete rotated keys while retaining the current key`() {+ val base = "https://fixture.invalid/live/"+ fun manifest(key: String, segment: String) =+ "#EXTM3U\n#EXT-X-KEY:METHOD=AES-128,URI=\"$key\"\n#EXTINF:2,\n$segment\n".toByteArray()+ publish(playlistUrl, manifest("old-key", "old.ts"), true)+ publish(base + "old-key", ByteArray(16))+ publish(base + "old.ts", ByteArray(16 * 1024 * 1024))+ publish(playlistUrl, manifest("current-key", "new.ts"), true)+ val currentKey = ByteArray(16) { 1 }+ publish(base + "current-key", currentKey)+ publish(base + "new.ts", ByteArray(16 * 1024 * 1024))+ openCapture().use { capture ->+ assertThat(capture.resource(base + "old-key")).isNull()+ assertThat(capture.resource(base + "current-key")?.bytes).isEqualTo(currentKey)+ assertThat(capture.resource(base + "new.ts")?.bytes?.size).isEqualTo(16 * 1024 * 1024)+ }+ }+}diff --git a/feature/playback/src/androidTest/java/com/streamvault/feature/playback/player/ControlsStateCollectionTest.kt b/feature/playback/src/androidTest/java/com/streamvault/feature/playback/player/ControlsStateCollectionTest.ktnew file mode 100644index 00000000..2c0b6482--- /dev/null+++ b/feature/playback/src/androidTest/java/com/streamvault/feature/playback/player/ControlsStateCollectionTest.kt@@ -0,0 +1,59 @@+package com.streamvault.feature.playback.player++import androidx.compose.runtime.SideEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.google.common.truth.Truth.assertThat+import kotlinx.coroutines.flow.MutableStateFlow+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class ControlsStateCollectionTest {+ @get:Rule val compose = createComposeRule()++ @Test fun hiddenControlsStopObservingAndReopeningReadsLatestState() {+ val source = MutableStateFlow(0)+ val visible = mutableStateOf(true)+ var observed = -1+ var compositions = 0+ compose.setContent {+ val value = source.collectAsControlsState(visible.value).value+ SideEffect { observed = value; compositions++ }+ }+ compose.waitUntil { source.subscriptionCount.value == 1 }+ compose.runOnIdle { source.value = 1 }+ compose.waitUntil { observed == 1 }+ compose.runOnIdle { visible.value = false }+ compose.waitForIdle()+ compose.runOnIdle { assertThat(source.subscriptionCount.value).isEqualTo(0) }+ val hiddenCompositions = compositions+ compose.runOnIdle { repeat(100) { source.value = it + 2 } }+ compose.waitForIdle()+ compose.runOnIdle {+ assertThat(observed).isEqualTo(1)+ assertThat(compositions).isEqualTo(hiddenCompositions)+ visible.value = true+ }+ compose.waitUntil { observed == 101 && source.subscriptionCount.value == 1 }+ }++ @Test fun openSheetKeepsControlsStateCurrentWhileChromeIsHidden() {+ val source = MutableStateFlow(0)+ val sheetOpen = mutableStateOf(true)+ var observed = -1+ compose.setContent {+ val value = source.collectAsControlsState(active = sheetOpen.value).value+ SideEffect { observed = value }+ }+ compose.waitUntil { source.subscriptionCount.value == 1 }+ compose.runOnIdle { source.value = 23 }+ compose.waitUntil { observed == 23 }+ compose.runOnIdle { sheetOpen.value = false }+ compose.waitForIdle()+ compose.runOnIdle { assertThat(source.subscriptionCount.value).isEqualTo(0) }+ }+}diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/ControlsStateCollection.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/ControlsStateCollection.ktnew file mode 100644index 00000000..3cef573a--- /dev/null+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/ControlsStateCollection.kt@@ -0,0 +1,15 @@+package com.streamvault.feature.playback.player++import androidx.compose.runtime.Composable+import androidx.compose.runtime.State+import androidx.compose.runtime.remember+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.emptyFlow++/** Controls keep their last snapshot for exit animations; reopening reads the latest value. */+@Composable+internal fun <T> StateFlow<T>.collectAsControlsState(active: Boolean): State<T> {+ val observed = remember(this, active) { if (active) this else emptyFlow() }+ return observed.collectAsStateWithLifecycle(initialValue = value)+}diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.ktindex 9c0832ee..9340246c 100644--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt@@ -85,28 +85,29 @@ internal fun PlayerControlsOverlayHost(showBackButton: Boolean = false,onBackToMenu: () -> Unit = {}) {- val currentPosition by playerEngine.currentPosition.collectAsStateWithLifecycle()- val duration by playerEngine.duration.collectAsStateWithLifecycle()- val chapters by playerEngine.chapters.collectAsStateWithLifecycle()- val currentProgram by viewModel.currentProgram.collectAsStateWithLifecycle()- val playbackTitle by viewModel.playbackTitle.collectAsStateWithLifecycle()- val currentSeries by viewModel.currentSeries.collectAsStateWithLifecycle()- val currentEpisode by viewModel.currentEpisode.collectAsStateWithLifecycle()- val nextEpisode by viewModel.nextEpisode.collectAsStateWithLifecycle()- val availableAudioTracks by viewModel.availableAudioTracks.collectAsStateWithLifecycle()- val availableSubtitleTracks by viewModel.availableSubtitleTracks.collectAsStateWithLifecycle()- val stremioSubtitlePickerState by viewModel.stremioSubtitlePickerState.collectAsStateWithLifecycle()- val availableVideoQualities by viewModel.availableVideoQualities.collectAsStateWithLifecycle()- val liveTranslationAvailable by viewModel.liveTranslationAvailable.collectAsStateWithLifecycle()- val currentChannelRecording by viewModel.currentChannelRecording.collectAsStateWithLifecycle()- val isMuted by viewModel.isMuted.collectAsStateWithLifecycle()- val mediaTitle by viewModel.mediaTitle.collectAsStateWithLifecycle()- val playbackSpeed by viewModel.playbackSpeed.collectAsStateWithLifecycle()- val audioVideoSyncEnabled by viewModel.audioVideoSyncEnabled.collectAsStateWithLifecycle()- val castConnectionState by viewModel.castConnectionState.collectAsStateWithLifecycle()- val seekPreview by viewModel.seekPreview.collectAsStateWithLifecycle()- val timeshiftUiState by viewModel.timeshiftUiState.collectAsStateWithLifecycle()- val sleepTimerUiState by viewModel.sleepTimerUiState.collectAsStateWithLifecycle()+ val observeControls = visible || showChapterSheet || showPlaybackSettingsSheet+ val currentPosition by playerEngine.currentPosition.collectAsControlsState(observeControls)+ val duration by playerEngine.duration.collectAsControlsState(observeControls)+ val chapters by playerEngine.chapters.collectAsControlsState(observeControls)+ val currentProgram by viewModel.currentProgram.collectAsControlsState(observeControls)+ val playbackTitle by viewModel.playbackTitle.collectAsControlsState(observeControls)+ val currentSeries by viewModel.currentSeries.collectAsControlsState(observeControls)+ val currentEpisode by viewModel.currentEpisode.collectAsControlsState(observeControls)+ val nextEpisode by viewModel.nextEpisode.collectAsControlsState(observeControls)+ val availableAudioTracks by viewModel.availableAudioTracks.collectAsControlsState(observeControls)+ val availableSubtitleTracks by viewModel.availableSubtitleTracks.collectAsControlsState(observeControls)+ val stremioSubtitlePickerState by viewModel.stremioSubtitlePickerState.collectAsControlsState(observeControls)+ val availableVideoQualities by viewModel.availableVideoQualities.collectAsControlsState(observeControls)+ val liveTranslationAvailable by viewModel.liveTranslationAvailable.collectAsControlsState(observeControls)+ val currentChannelRecording by viewModel.currentChannelRecording.collectAsControlsState(observeControls)+ val isMuted by viewModel.isMuted.collectAsControlsState(observeControls)+ val mediaTitle by viewModel.mediaTitle.collectAsControlsState(observeControls)+ val playbackSpeed by viewModel.playbackSpeed.collectAsControlsState(observeControls)+ val audioVideoSyncEnabled by viewModel.audioVideoSyncEnabled.collectAsControlsState(observeControls)+ val castConnectionState by viewModel.castConnectionState.collectAsControlsState(observeControls)+ val seekPreview by viewModel.seekPreview.collectAsControlsState(observeControls)+ val timeshiftUiState by viewModel.timeshiftUiState.collectAsControlsState(observeControls)+ val sleepTimerUiState by viewModel.sleepTimerUiState.collectAsControlsState(observeControls)val currentSeriesSeasons = remember(currentSeries) {currentSeries?.seasons.sanitizedForPlayer()}diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.ktindex da186402..b0064ade 100644--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt@@ -48,6 +48,7 @@ import com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.util.LivePlaybackByteTapimport com.streamvault.domain.settings.VodTrackPreferencesimport com.streamvault.domain.model.VideoFormat+import com.streamvault.player.stats.PlaybackBufferingTrackerimport com.streamvault.domain.repository.PlaybackCompatibilityRepositoryimport com.streamvault.player.audio.PlayerAudioFocusControllerimport com.streamvault.player.playback.ActiveDecoderPolicy@@ -88,6 +89,11 @@ import com.streamvault.player.playback.resolveRetrySeekPositionMsimport com.streamvault.player.playback.resolveScheduledRetrySeekPositionMsimport com.streamvault.player.playback.StreamTypeResolverimport com.streamvault.player.playback.VideoStallDetector+import com.streamvault.player.playback.LiveStartupWatchdog+import com.streamvault.player.playback.LiveMpegTsEndRecovery+import com.streamvault.player.playback.canRecoverLiveMpegTsEnd+import com.streamvault.player.playback.StartupRefreshGate+import com.streamvault.player.playback.liveStartupTimeoutMessageimport com.streamvault.player.playback.AutomaticRecoveryActionimport com.streamvault.player.playback.buildDecoderReuseWorkaroundEvaluationimport com.streamvault.player.playback.buildPlaybackRendererPlan@@ -263,6 +269,10 @@ class Media3PlayerEngine @Inject constructor(private var liveBufferingRecoveryArmed = falseprivate var playbackStartedRecoveryArmed = falseprivate var hasRenderedFirstVideoFrame = false+ private val liveStartupWatchdog = LiveStartupWatchdog()+ private val startupRefreshGate = StartupRefreshGate()+ private val liveMpegTsEndRecovery = LiveMpegTsEndRecovery()+ private var startupTimedOut = falseprivate var prepareStartMs = 0Lprivate var retryAttempt = 0private var retryJob: Job? = null@@ -372,6 +382,7 @@ class Media3PlayerEngine @Inject constructor(.setResetOnNetworkTypeChange(true).build()private val frameRateDetector = FrameRateDetector()+ private val bufferingTracker = PlaybackBufferingTracker(SystemClock::elapsedRealtime)private val statsCollector = PlayerStatsCollector(scopeProvider = { scope },currentPosition = _currentPosition,@@ -394,7 +405,9 @@ class Media3PlayerEngine @Inject constructor(transferListener = transferByteCounter,livePlaybackByteTap = livePlaybackByteTap)- private val mediaSourceFactory = PlayerMediaSourceFactory(dataSourceFactoryProvider)+ private val mediaSourceFactory = PlayerMediaSourceFactory(dataSourceFactoryProvider) {+ requestedPlaybackBufferMode+ }private var preloadWindowManager: Media3PreloadWindowManager? = nullprivate var pendingPreloadWindow: PlayerPreloadWindow? = nullprivate val compatibilityProfile: PlaybackCompatibilityProfile = DefaultPlaybackCompatibilityProfile@@ -495,6 +508,62 @@ class Media3PlayerEngine @Inject constructor(val liveStream = isCurrentStreamLive()val selectedVideo = exoPlayer?.currentTracks?.isTypeSelected(C.TRACK_TYPE_VIDEO) == trueval effectivePlaybackStarted = isEffectivelyPlaybackStarted()+ val startupPlayer = exoPlayer+ if (liveMpegTsEndRecovery.isPending) {+ when (liveMpegTsEndRecovery.evaluate(+ nowMs = SystemClock.elapsedRealtime(),+ canResume = lastStreamInfo != null && startupPlayer?.playWhenReady == true &&+ _playbackQualityGate.value == null && viewBinder.hasUsableVideoOutput(startupPlayer),+ hasActiveTransfers = mediaSourceFactory.hasActiveNetworkTransfers+ )) {+ StartupRefreshGate.Action.READY -> {+ Log.i(TAG, "live-ts-end transfers-drained refresh=1")+ lastStreamInfo?.let { prepareInternal(it, true, null, true) }+ }+ StartupRefreshGate.Action.GIVE_UP -> {+ Log.w(TAG, "live-ts-end refresh-abandoned reason=transfers-not-drained")+ _isPlaying.value = false+ _playbackState.value = PlaybackState.ENDED+ audioFocusController.onPauseOrStop()+ com.streamvault.domain.sync.AutomaticSyncActivity.stopped(this)+ }+ StartupRefreshGate.Action.WAIT -> Unit+ }+ continue+ }+ if (startupRefreshGate.isPending) {+ val gateAction = startupRefreshGate.evaluate(+ nowMs = SystemClock.elapsedRealtime(),+ canResume = lastStreamInfo != null && startupPlayer?.playWhenReady == true &&+ _playbackQualityGate.value == null && viewBinder.hasUsableVideoOutput(startupPlayer),+ hasActiveTransfers = mediaSourceFactory.hasActiveNetworkTransfers+ )+ if (gateAction == StartupRefreshGate.Action.READY) {+ Log.i(TAG, "startup-watchdog transfers-drained")+ lastStreamInfo?.let { prepareInternal(it, true, null, true) }+ } else if (gateAction == StartupRefreshGate.Action.GIVE_UP) {+ handleStartupWatchdog(LiveStartupWatchdog.Action.GIVE_UP)+ }+ continue+ }+ val startupAction = liveStartupWatchdog.evaluate(+ nowMs = SystemClock.elapsedRealtime(),+ eligible = liveStream && !startupTimedOut && lastStreamInfo != null &&+ lastStreamInfo?.drmInfo == null && currentResolvedStreamType != ResolvedStreamType.RTSP &&+ _playbackState.value in setOf(PlaybackState.BUFFERING, PlaybackState.READY) &&+ startupPlayer?.playWhenReady == true && _playbackQualityGate.value == null &&+ !isPlayingTimeshiftSnapshot && activeLiveTimeshiftStreamInfo == null &&+ viewBinder.hasUsableVideoOutput(startupPlayer) &&+ currentRetryPolicy?.hasPendingLoadRecovery != true && retryJob?.isActive != true,+ firstVideoFrameRendered = hasRenderedFirstVideoFrame,+ audioOnlyPlaying = !selectedVideo && _isPlaying.value,+ bufferedDurationMs = stats.bufferedDurationMs,+ sourceRetryAlreadyUsed = retryAttempt > 0+ )+ if (startupAction != LiveStartupWatchdog.Action.NONE) {+ handleStartupWatchdog(startupAction)+ continue+ }val liveBufferingRecoveryEligible = liveStream && effectivePlaybackStartedval appStallRecoveryDeferred = shouldDeferAppStallRecovery(activeMediaLoadRetry = currentRetryPolicy?.hasPendingLoadRecovery == true,@@ -519,7 +588,9 @@ class Media3PlayerEngine @Inject constructor(liveStream && selectedVideo && !appStallRecoveryDeferred && shouldRecoverFrameSilentReadyStalls(currentResolvedStreamType,lastStreamInfo?.playbackContentKind ?: PlaybackContentKind.UNKNOWN- )+ ),+ // Track refill during grace without consuming an unhandled stall event.+ deferReporting = shouldIgnoreLiveHlsStartupStall())val qualityPolicy = trackController.qualityPolicySnapshot(constrainResolutionForMultiView = constrainResolutionForMultiView,@@ -579,14 +650,7 @@ class Media3PlayerEngine @Inject constructor(continue}if (stalled) {- if (shouldIgnoreLiveHlsStartupStall()) {- Log.w(- TAG,- "video-stall startup grace retained for live-hls surface=${_renderSurfaceType.value} target=${PlaybackLogSanitizer.sanitizeUrl(lastStreamInfo?.url)}"- )- } else {- handleVideoStall()- }+ handleVideoStall()}}}@@ -594,7 +658,7 @@ class Media3PlayerEngine @Inject constructor(override fun prepare(streamInfo: StreamInfo) {if (ensureNotDisposed("prepare")) return- com.streamvault.domain.sync.AutomaticSyncActivity.started(this)+ com.streamvault.domain.sync.AutomaticSyncActivity.started(this, streamInfo.livePlaybackIdentity?.providerId)if (_subtitleOffsetMs.value != 0) {_subtitleOffsetMs.value = 0subtitleOffsetUs.set(0L)@@ -627,7 +691,7 @@ class Media3PlayerEngine @Inject constructor()lastStreamInfo = streamInfo- lastMediaId = mediaSourceFactory.mediaIdFor(streamInfo)+ lastMediaId = mediaSourceFactory.compatibilityMediaIdFor(streamInfo)currentResolvedStreamType = playbackPlan.resolvedStreamTypecurrentTimeoutProfile = playbackPlan.timeoutProfilecurrentRetryContext = playbackPlan.retryContext@@ -645,6 +709,12 @@ class Media3PlayerEngine @Inject constructor(vodHttpProtocolMode = requestedVodHttpProtocolMode,preload = false).second+ startupTimedOut = false+ hasRenderedFirstVideoFrame = false+ prepareStartMs = System.currentTimeMillis()+ liveStartupWatchdog.reset(preserveEpisode = true)+ startupRefreshGate.clear()+ liveMpegTsEndRecovery.reset(preserveAttempt = true)player.setMediaSource(withSubtitleOffset(mediaSource), /* resetPosition= */ false)player.prepare()@@ -656,7 +726,7 @@ class Media3PlayerEngine @Inject constructor(}override fun play() {- if (exoPlayer != null && lastStreamInfo != null) com.streamvault.domain.sync.AutomaticSyncActivity.started(this)+ if (exoPlayer != null && lastStreamInfo != null) com.streamvault.domain.sync.AutomaticSyncActivity.started(this, lastStreamInfo?.livePlaybackIdentity?.providerId)if (_playbackQualityGate.value != null) {qualityGateResumeIntent = truereturn@@ -668,6 +738,9 @@ class Media3PlayerEngine @Inject constructor(}override fun pause() {+ liveStartupWatchdog.pauseClock()+ startupRefreshGate.pauseClock()+ liveMpegTsEndRecovery.pauseClock()if (_playbackQualityGate.value != null) qualityGateResumeIntent = falseretryJob?.cancel()exoPlayer?.playWhenReady = false@@ -675,6 +748,10 @@ class Media3PlayerEngine @Inject constructor(}override fun stop() {+ startupTimedOut = false+ liveStartupWatchdog.reset()+ startupRefreshGate.clear()+ liveMpegTsEndRecovery.reset()viewBinder.setDisplayFrameRate(null)com.streamvault.domain.sync.AutomaticSyncActivity.stopped(this)clearAdaptiveDecodePressure()@@ -698,6 +775,7 @@ class Media3PlayerEngine @Inject constructor(setInjectedSubtitleText(null)statsCollector.stop()statsCollector.reset()+ bufferingTracker.reset()audioFocusController.onPauseOrStop()}@@ -766,10 +844,16 @@ class Media3PlayerEngine @Inject constructor(override fun setPlaybackBufferMode(mode: PlaybackBufferMode) {if (requestedPlaybackBufferMode == mode) return+ val previousMode = requestedPlaybackBufferModerequestedPlaybackBufferMode = modelastStreamInfo?.let { streamInfo ->val wasPlaying = exoPlayer?.playWhenReady == true- val position = exoPlayer?.currentPosition+ val targetChanged = mediaSourceFactory.liveTargetOffsetMsFor(+ streamInfo, currentResolvedStreamType, previousMode+ ) != mediaSourceFactory.liveTargetOffsetMsFor(streamInfo, currentResolvedStreamType, mode)+ // Preserving the old live position would override the new target in Media3's+ // speed controller. Rejoin its default position when the user changes that target.+ val position = exoPlayer?.currentPosition.takeUnless { targetChanged }prepareInternal(streamInfo, preserveRetryState = false, seekPositionMs = position, autoPlay = wasPlaying)}}@@ -1222,11 +1306,20 @@ class Media3PlayerEngine @Inject constructor(}override fun clearRenderBinding() {+ liveStartupWatchdog.pauseClock()+ startupRefreshGate.pauseClock()+ liveMpegTsEndRecovery.pauseClock()viewBinder.attachPlayer(null)}override fun releaseRenderView(renderView: android.view.View) {+ val hadOutput = viewBinder.hasUsableVideoOutput(exoPlayer)viewBinder.release(renderView)+ if (hadOutput && !viewBinder.hasUsableVideoOutput(exoPlayer)) {+ liveStartupWatchdog.pauseClock()+ startupRefreshGate.pauseClock()+ liveMpegTsEndRecovery.pauseClock()+ }}override fun resetLiveHandoffGrace() {@@ -1284,6 +1377,10 @@ class Media3PlayerEngine @Inject constructor(currentBufferIsLive = nullcurrentBufferPolicyLabel = nullcurrentBufferPolicy = null+ startupTimedOut = false+ liveStartupWatchdog.reset()+ startupRefreshGate.clear()+ liveMpegTsEndRecovery.reset()playbackStarted = falseliveBufferingRecoveryArmed = falseplaybackStartedRecoveryArmed = false@@ -1350,8 +1447,12 @@ class Media3PlayerEngine @Inject constructor(retryGeneration++pendingRetrySeekPositionOverrideMs = nulllastStreamInfo = streamInfo- val mediaId = mediaSourceFactory.mediaIdFor(streamInfo)+ val mediaId = mediaSourceFactory.compatibilityMediaIdFor(streamInfo)val mediaChanged = lastMediaId != mediaId+ startupTimedOut = false+ startupRefreshGate.clear()+ liveMpegTsEndRecovery.reset(preserveAttempt = preserveRetryState && !mediaChanged)+ liveStartupWatchdog.reset(preserveEpisode = preserveRetryState && !mediaChanged)if (!preserveRetryState || mediaChanged) {_playbackQualityGate.value = nullqualityGateResumeIntent = false@@ -1392,6 +1493,7 @@ class Media3PlayerEngine @Inject constructor(_chapters.value = emptyList()trackController.resetSelections(preserveVideoSelection = preserveRetryState && !mediaChanged)statsCollector.reset()+ bufferingTracker.reset(recovering = preserveRetryState && !mediaChanged)videoStallDetector.reset()if (!preserveRetryState) {liveBufferingRecoveryArmed = false@@ -2010,10 +2112,45 @@ class Media3PlayerEngine @Inject constructor(private fun createPlayerListener(): Player.Listener {return object : Player.Listener {+ override fun onEvents(player: Player, events: Player.Events) {+ if (player !== exoPlayer) return+ if (!events.containsAny(+ Player.EVENT_PLAYBACK_STATE_CHANGED,+ Player.EVENT_IS_PLAYING_CHANGED,+ Player.EVENT_PLAY_WHEN_READY_CHANGED,+ Player.EVENT_POSITION_DISCONTINUITY+ )) return+ // onEvents observes the final state after the individual callbacks in this batch.+ statsCollector.updatePlaybackActivity(player.isPlaying, player.playWhenReady)+ bufferingTracker.update(+ state = _playbackState.value,+ playWhenReady = player.playWhenReady,+ playbackStarted = isEffectivelyPlaybackStarted()+ ).forEach { event ->+ if (event.cause == PlaybackBufferingTracker.Cause.REBUFFER &&+ event.outcome == PlaybackBufferingTracker.Outcome.STARTED+ ) statsCollector.incrementRebufferCount()+ val liveOffset = player.currentLiveOffset.takeUnless { it == C.TIME_UNSET }+ Log.i(+ TAG,+ "buffering-event cause=${event.cause} outcome=${event.outcome} durationMs=${event.durationMs} " ++ "bufferMs=${player.totalBufferedDuration} liveOffsetMs=$liveOffset " ++ "loading=${player.isLoading} policy=$currentBufferPolicyLabel " ++ "${playbackLoadControl?.describeAllocation().orEmpty()} " ++ "selectedBps=${exoPlayer?.videoFormat?.bitrate} " ++ "estimateBps=${lastBandwidthEstimateBps.get()} decoder=$selectedVideoDecoderName"+ )+ }+ }+override fun onPlaybackStateChanged(state: Int) {+ if (state == Player.STATE_ENDED && tryRecoverLiveMpegTsEnd()) returnif (state == Player.STATE_ENDED) com.streamvault.domain.sync.AutomaticSyncActivity.stopped(this)- val previousState = _playbackState.value- _playbackState.value = when (state) {+ _playbackState.value = if (startupTimedOut) PlaybackState.ERROR+ else if ((startupRefreshGate.isPending || liveMpegTsEndRecovery.isPending) &&+ state in setOf(Player.STATE_IDLE, Player.STATE_ENDED)) PlaybackState.BUFFERING+ else if (liveMpegTsEndRecovery.abandoned && state == Player.STATE_IDLE) PlaybackState.ENDED+ else when (state) {Player.STATE_IDLE -> PlaybackState.IDLEPlayer.STATE_BUFFERING -> PlaybackState.BUFFERINGPlayer.STATE_READY -> PlaybackState.READY@@ -2021,9 +2158,6 @@ class Media3PlayerEngine @Inject constructor(else -> PlaybackState.IDLE}updateForegroundPreloadPriority()- if (previousState == PlaybackState.READY && _playbackState.value == PlaybackState.BUFFERING) {- statsCollector.incrementRebufferCount()- }if (_playbackState.value == PlaybackState.READY) {_retryStatus.value = nullretryAttempt = resolveRetryAttemptAfterReady(@@ -2051,21 +2185,20 @@ class Media3PlayerEngine @Inject constructor(}override fun onIsPlayingChanged(isPlaying: Boolean) {- _isPlaying.value = isPlaying+ _isPlaying.value = isPlaying && !startupTimedOutupdateForegroundPreloadPriority()if (isPlaying) {if (_playbackState.value == PlaybackState.READY) {markPlaybackStarted("playing-ready")}- statsCollector.start()audioFocusController.onPlaybackStarted()- } else {- statsCollector.stop()}syncTimeshiftState()}override fun onPlayerError(error: PlaybackException) {+ if (startupTimedOut || startupRefreshGate.isPending || liveMpegTsEndRecovery.isPending ||+ liveMpegTsEndRecovery.abandoned) returnif (_playbackQualityGate.value != null) {if (deferredQualityGateError == null) deferredQualityGateError = errorLog.w(@@ -2083,6 +2216,7 @@ class Media3PlayerEngine @Inject constructor(newPosition: Player.PositionInfo,reason: Int) {+ if (reason == Player.DISCONTINUITY_REASON_SEEK) bufferingTracker.onSeek()adaptiveDecodePressurePolicy.discontinuity()_currentPosition.value = newPosition.positionMssyncTimeshiftState()@@ -2366,6 +2500,60 @@ class Media3PlayerEngine @Inject constructor(liveBufferingRecoveryArmed = liveBufferingRecoveryArmed || playbackStartedRecoveryArmed)+ private fun tryRecoverLiveMpegTsEnd(): Boolean {+ if (isDisposed || startupTimedOut || liveMpegTsEndRecovery.abandoned) return false+ if (liveMpegTsEndRecovery.isPending) return true+ val player = exoPlayer ?: return false+ val eligible = canRecoverLiveMpegTsEnd(+ streamInfo = lastStreamInfo,+ streamType = currentResolvedStreamType,+ playbackStarted = isEffectivelyPlaybackStarted(),+ playWhenReady = player.playWhenReady,+ hasIndependentSourceOwner = isPlayingTimeshiftSnapshot || activeLiveTimeshiftStreamInfo != null ||+ _playbackQualityGate.value != null,+ retryPending = currentRetryPolicy?.hasPendingLoadRecovery == true || retryJob?.isActive == true ||+ startupRefreshGate.isPending+ )+ if (!liveMpegTsEndRecovery.onEnded(SystemClock.elapsedRealtime(), eligible)) {+ if (eligible) Log.w(TAG, "live-ts-end refresh-exhausted")+ return false+ }+ Log.w(TAG, "live-ts-end refresh-requested attempt=1 " ++ "target=${PlaybackLogSanitizer.sanitizeUrl(lastStreamInfo?.url.orEmpty())}")+ bufferingTracker.onRecovery()+ _playbackState.value = PlaybackState.BUFFERING+ _isPlaying.value = false+ preloadWindowManager?.clearWindow()+ player.stop()+ return true+ }++ private fun handleStartupWatchdog(action: LiveStartupWatchdog.Action) {+ val streamInfo = lastStreamInfo ?: return+ Log.w(TAG, "startup-watchdog action=$action streamType=$currentResolvedStreamType " ++ "bufferMs=${_playerStats.value.bufferedDurationMs} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}")+ if (action == LiveStartupWatchdog.Action.REFRESH_SOURCE) {+ startupRefreshGate.begin(SystemClock.elapsedRealtime())+ preloadWindowManager?.clearWindow()+ exoPlayer?.stop()+ return+ }+ startupRefreshGate.clear()+ startupTimedOut = true+ retryJob?.cancel()+ retryJob = null+ retryGeneration+++ currentRetryPolicy?.clearPendingLoadRecovery()+ _retryStatus.value = null+ exoPlayer?.playWhenReady = false+ exoPlayer?.stop()+ audioFocusController.onPauseOrStop()+ com.streamvault.domain.sync.AutomaticSyncActivity.stopped(this)+ _isPlaying.value = false+ _playbackState.value = PlaybackState.ERROR+ _error.tryEmit(PlayerError.SourceError(liveStartupTimeoutMessage(context)))+ }+private fun handleVideoStall() {val streamInfo = lastStreamInfo ?: returnif (exoPlayer?.currentTracks?.isTypeSelected(C.TRACK_TYPE_VIDEO) != true) return@@ -2402,6 +2590,7 @@ class Media3PlayerEngine @Inject constructor())) {LiveVideoStallRecovery.Result.SEEKED -> {+ bufferingTracker.onRecovery()videoStallDetector.restartAfterRecoveryAttempt()Log.w(TAG, "video-stall in-place-live-seek attempt=$videoStallRecoveryAttempt")return@@ -2948,6 +3137,7 @@ class Media3PlayerEngine @Inject constructor(retryPolicy.clearPendingLoadRecovery()val nextAttempt = resolveNextAppSourceRetryAttempt(retryAttempt)if (retryPolicy.shouldRetryWholeSource(error, effectivePlaybackStarted, nextAttempt)) {+ val mediaRefusalRefresh = retryPolicy.isLiveMediaRefusal(error)val delayMs = retryPolicy.retryDelayMs(error, nextAttempt)val player = exoPlayerval retrySeekPositionMs = resolveRetrySeekPositionMs(@@ -3010,7 +3200,7 @@ class Media3PlayerEngine @Inject constructor(liveBufferingRecoveryArmed = false),seekPositionMs = scheduledSeekPositionMs,- autoPlay = true+ autoPlay = if (mediaRefusalRefresh) exoPlayer?.playWhenReady == true else true)}return@@ -3018,9 +3208,12 @@ class Media3PlayerEngine @Inject constructor(pendingRetrySeekPositionOverrideMs = null_retryStatus.value = null+ val failureReason = if (retryPolicy.isLiveMediaRefusal(error)) {+ "live-media-refusal-budget-exhausted"+ } else retryPolicy.retryReason(error)Log.e(TAG,- "fatal-error category=$category reason=${retryPolicy.retryReason(error)} " ++ "fatal-error category=$category reason=$failureReason " +"errorCode=${error.errorCodeName} causeChain=${formatErrorCauseChain(error)} " +"target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)} message=${PlaybackLogSanitizer.sanitizeMessage(error.message)}")diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.ktindex a3b7cd4a..b2144b6f 100644--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt@@ -240,6 +240,7 @@ data class PlayerStats(val measuredFrameRate: Float = 0f,/** Running average of the whole-stream network bitrate in bps, rounded to 0.1 Mbps; 0 until measured. */val measuredBitrate: Long = 0L,+ /** Cumulative drops reported by Media3 callbacks; can trail its immediate decoder counter. */val droppedFrames: Int = 0,val width: Int = 0,val height: Int = 0,diff --git a/player/src/main/java/com/streamvault/player/playback/AvcAccessUnitExtractorsFactory.kt b/player/src/main/java/com/streamvault/player/playback/AvcAccessUnitExtractorsFactory.ktnew file mode 100644index 00000000..90cfdc90--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/AvcAccessUnitExtractorsFactory.kt@@ -0,0 +1,55 @@+package com.streamvault.player.playback++import android.net.Uri+import androidx.media3.common.C+import androidx.media3.common.util.UnstableApi+import androidx.media3.extractor.Extractor+import androidx.media3.extractor.ExtractorOutput+import androidx.media3.extractor.ExtractorsFactory+import androidx.media3.extractor.ForwardingExtractor+import androidx.media3.extractor.ForwardingExtractorOutput+import androidx.media3.extractor.ForwardingExtractorsFactory+import androidx.media3.extractor.TrackOutput+import androidx.media3.extractor.ts.TsExtractor++/** Preserves TS access-unit detection while keeping AVC prefixes with their picture. */+@UnstableApi+internal class AvcAccessUnitExtractorsFactory(+ private val upstream: ExtractorsFactory+) : ForwardingExtractorsFactory(upstream) {+ override fun createExtractors(): Array<Extractor> = wrap(upstream.createExtractors())++ override fun createExtractors(uri: Uri, responseHeaders: Map<String, List<String>>): Array<Extractor> =+ wrap(upstream.createExtractors(uri, responseHeaders))++ private fun wrap(extractors: Array<Extractor>): Array<Extractor> = extractors.map {+ if (it is TsExtractor) AvcAccessUnitExtractor(it) else it+ }.toTypedArray()+}++@UnstableApi+private class AvcAccessUnitExtractor(delegate: Extractor) : ForwardingExtractor(delegate) {+ private val outputs = mutableMapOf<Int, AvcAccessUnitTrackOutput>()++ override fun init(output: ExtractorOutput) {+ outputs.clear()+ super.init(object : ForwardingExtractorOutput(output) {+ override fun track(id: Int, type: Int): TrackOutput {+ val delegate = super.track(id, type)+ return if (type == C.TRACK_TYPE_VIDEO) {+ outputs.getOrPut(id) { AvcAccessUnitTrackOutput(delegate) }+ } else delegate+ }+ })+ }++ override fun seek(position: Long, timeUs: Long) {+ outputs.values.forEach { it.reset() }+ super.seek(position, timeUs)+ }++ override fun release() {+ outputs.clear()+ super.release()+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/AvcAccessUnitTrackOutput.kt b/player/src/main/java/com/streamvault/player/playback/AvcAccessUnitTrackOutput.ktnew file mode 100644index 00000000..9589c339--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/AvcAccessUnitTrackOutput.kt@@ -0,0 +1,183 @@+package com.streamvault.player.playback++import androidx.media3.common.DataReader+import androidx.media3.common.Format+import androidx.media3.common.MimeTypes+import androidx.media3.common.util.ParsableByteArray+import androidx.media3.common.util.UnstableApi+import androidx.media3.container.NalUnitUtil+import androidx.media3.extractor.ForwardingTrackOutput+import androidx.media3.extractor.TrackOutput+import java.util.ArrayDeque++/** Keeps non-picture AVC prefix samples with their following picture. */+@UnstableApi+internal class AvcAccessUnitTrackOutput(+ delegate: TrackOutput,+ private val maxPendingHeaderBytes: Int = 256 * 1024,+ private val maxPendingHeaderSamples: Int = 64,+ private val maxNalMarkers: Int = 4096+) : ForwardingTrackOutput(delegate) {+ private data class Nal(val position: Long, val type: Int)+ private data class Header(val timeUs: Long, val flags: Int, val start: Long, val end: Long)++ private val nalMarkers = ArrayDeque<Nal>()+ private val pendingHeaders = ArrayDeque<Header>()+ private val prefixFlags = BooleanArray(3)+ private var bytesWritten = 0L+ private var formatKnown = false+ private var clearAvc = false+ private var passthroughUntilReset = false++ init {+ require(maxPendingHeaderBytes > 0 && maxPendingHeaderSamples > 0 && maxNalMarkers > 0)+ }++ override fun format(format: Format) {+ val nextClearAvc = format.sampleMimeType == MimeTypes.VIDEO_H264 && format.drmInitData == null+ if (!nextClearAvc) {+ flushHeaders()+ nalMarkers.clear()+ prefixFlags.fill(false)+ }+ formatKnown = true+ clearAvc = nextClearAvc+ super.format(format)+ }++ override fun sampleData(data: ParsableByteArray, length: Int) =+ sampleData(data, length, TrackOutput.SAMPLE_DATA_PART_MAIN)++ override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {+ if (sampleDataPart != TrackOutput.SAMPLE_DATA_PART_MAIN) {+ fallBackToPassthrough()+ } else if (!passthroughUntilReset && (!formatKnown || clearAvc)) {+ // Scan before Format is known too: one TS payload can contain both CSD and VCL.+ scanNals(data.data, data.position, data.position + length)+ }+ super.sampleData(data, length, sampleDataPart)+ bytesWritten += length+ }++ override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean): Int =+ sampleData(input, length, allowEndOfInput, TrackOutput.SAMPLE_DATA_PART_MAIN)++ override fun sampleData(+ input: DataReader,+ length: Int,+ allowEndOfInput: Boolean,+ sampleDataPart: Int+ ): Int {+ // H264Reader uses ParsableByteArray. Preserve unfamiliar/opaque writer paths verbatim.+ fallBackToPassthrough()+ return super.sampleData(input, length, allowEndOfInput, sampleDataPart).also {+ if (it > 0) bytesWritten += it+ }+ }++ override fun sampleMetadata(+ timeUs: Long,+ flags: Int,+ size: Int,+ offset: Int,+ cryptoData: TrackOutput.CryptoData?+ ) {+ val end = bytesWritten - offset+ val start = end - size+ if (cryptoData != null) fallBackToPassthrough()+ if (!clearAvc || passthroughUntilReset || cryptoData != null ||+ size <= 0 || offset < 0 || start < 0+ ) {+ flushHeaders()+ discardMarkersBefore(end)+ super.sampleMetadata(timeUs, flags, size, offset, cryptoData)+ return+ }++ discardMarkersBefore(start)+ var hasNal = false+ var hasPicture = false+ var onlyPrefixNals = true+ for (nal in nalMarkers) {+ if (nal.position >= end) break+ hasNal = true+ if (nal.type in 1..5 || nal.type in 19..21) hasPicture = true+ if (nal.type !in PREFIX_NAL_TYPES) onlyPrefixNals = false+ }+ discardMarkersBefore(end)++ if (pendingHeaders.isNotEmpty() && pendingHeaders.last.end != start) flushHeaders()+ if (hasPicture) {+ val mergedSize = if (pendingHeaders.isEmpty()) size.toLong() else end - pendingHeaders.first.start+ if (mergedSize > Int.MAX_VALUE) {+ fallBackToPassthrough()+ super.sampleMetadata(timeUs, flags, size, offset, cryptoData)+ return+ }+ var mergedFlags = flags+ for (header in pendingHeaders) mergedFlags = mergedFlags or header.flags+ pendingHeaders.clear()+ // Keep the picture's timestamp. Equal timestamps on actual pictures are not deduplicated.+ super.sampleMetadata(timeUs, mergedFlags, mergedSize.toInt(), offset, cryptoData)+ } else if (hasNal && onlyPrefixNals) {+ pendingHeaders.addLast(Header(timeUs, flags, start, end))+ if (pendingHeaders.size > maxPendingHeaderSamples ||+ end - pendingHeaders.first.start > maxPendingHeaderBytes+ ) fallBackToPassthrough()+ } else {+ // Unknown NALs or missing boundaries must not silently discard samples.+ flushHeaders()+ super.sampleMetadata(timeUs, flags, size, offset, cryptoData)+ }+ }++ /** The owning extractor's seek resets its sample queues; old metadata must not be flushed. */+ fun reset() {+ pendingHeaders.clear()+ nalMarkers.clear()+ prefixFlags.fill(false)+ bytesWritten = 0L+ passthroughUntilReset = false+ }++ private fun scanNals(data: ByteArray, start: Int, end: Int) {+ var offset = start+ while (offset < end) {+ val nalStart = NalUnitUtil.findNalUnit(data, offset, end, prefixFlags)+ if (nalStart == end) return+ val header = nalStart + 3+ if (header !in start until end || nalMarkers.size >= maxNalMarkers) {+ fallBackToPassthrough()+ return+ }+ nalMarkers.addLast(Nal(bytesWritten + header - start, data[header].toInt() and 0x1f))+ offset = header + 1+ }+ }++ private fun discardMarkersBefore(position: Long) {+ while (nalMarkers.isNotEmpty() && nalMarkers.first.position < position) nalMarkers.removeFirst()+ }++ private fun flushHeaders() {+ while (pendingHeaders.isNotEmpty()) {+ val header = pendingHeaders.removeFirst()+ super.sampleMetadata(+ header.timeUs, header.flags, (header.end - header.start).toInt(),+ (bytesWritten - header.end).toInt(), null+ )+ }+ }++ private fun fallBackToPassthrough() {+ flushHeaders()+ nalMarkers.clear()+ prefixFlags.fill(false)+ passthroughUntilReset = true+ }++ private companion object {+ // SEI, SPS, PPS, AUD, filler, SPS extension, prefix and subset SPS.+ val PREFIX_NAL_TYPES = setOf(6, 7, 8, 9, 12, 13, 14, 15)+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/HlsRenditionLoadingPolicy.kt b/player/src/main/java/com/streamvault/player/playback/HlsRenditionLoadingPolicy.ktnew file mode 100644index 00000000..83ce495f--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/HlsRenditionLoadingPolicy.kt@@ -0,0 +1,99 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import androidx.media3.common.C+import androidx.media3.exoplayer.LoadingInfo+import androidx.media3.exoplayer.hls.HlsMediaSource+import androidx.media3.exoplayer.source.CompositeSequenceableLoaderFactory+import androidx.media3.exoplayer.source.DefaultCompositeSequenceableLoaderFactory+import androidx.media3.exoplayer.source.SequenceableLoader+import com.streamvault.domain.model.PlaybackContentKind++/** Keep an in-flight optional rendition from pinning live audio/video prefetch. */+fun HlsMediaSource.Factory.applyPlaybackRenditionLoadingPolicy(+ contentKind: PlaybackContentKind+): HlsMediaSource.Factory = setCompositeSequenceableLoaderFactory(+ if (isLivePlayback(contentKind, ResolvedStreamType.HLS)) {+ InFlightOptionalRenditionLoaderFactory()+ } else {+ DefaultCompositeSequenceableLoaderFactory()+ }+)++internal class InFlightOptionalRenditionLoaderFactory : CompositeSequenceableLoaderFactory {+ private val upstream = DefaultCompositeSequenceableLoaderFactory()++ override fun empty(): SequenceableLoader = upstream.empty()++ @Suppress("DEPRECATION", "OVERRIDE_DEPRECATION")+ override fun createCompositeSequenceableLoader(vararg loaders: SequenceableLoader): SequenceableLoader =+ upstream.createCompositeSequenceableLoader(*loaders)++ override fun create(+ loaders: List<SequenceableLoader>,+ loaderTrackTypes: List<List<Int>>+ ): SequenceableLoader {+ val aggregate = upstream.create(loaders, loaderTrackTypes)+ val optional = BooleanArray(loaders.size) { index ->+ val types = loaderTrackTypes[index]+ types.isNotEmpty() && types.all { it == C.TRACK_TYPE_TEXT || it == C.TRACK_TYPE_METADATA }+ }+ if (optional.none { it } || optional.all { it }) return aggregate+ return InFlightOptionalRenditionLoader(aggregate, loaders.toList(), optional)+ }+}++private class InFlightOptionalRenditionLoader(+ private val aggregate: SequenceableLoader,+ private val loaders: List<SequenceableLoader>,+ private val optional: BooleanArray+) : SequenceableLoader by aggregate {+ private val skipForThisCall = BooleanArray(loaders.size)++ override fun getNextLoadPositionUs(): Long {+ if (!hasUnfinishedPrimary()) return aggregate.nextLoadPositionUs+ var next = Long.MAX_VALUE+ for (index in loaders.indices) {+ if (optional[index] && loaders[index].isLoading) continue+ val position = loaders[index].nextLoadPositionUs+ if (position != C.TIME_END_OF_SOURCE) next = minOf(next, position)+ }+ return if (next == Long.MAX_VALUE) C.TIME_END_OF_SOURCE else next+ }++ override fun continueLoading(loadingInfo: LoadingInfo): Boolean {+ if (!hasUnfinishedPrimary()) return aggregate.continueLoading(loadingInfo)+ for (index in loaders.indices) {+ skipForThisCall[index] = optional[index] && loaders[index].isLoading+ }+ // Preserve Media3's minimum-position/behind-playback scheduling. HLS wrappers+ // permit one load in flight, so another continue call cannot advance a busy one.+ // Snapshot eligibility so starting a text request does not also advance A/V past+ // the load-control budget within this same progress loop.+ var madeProgress = false+ do {+ var next = Long.MAX_VALUE+ for (index in loaders.indices) {+ if (skipForThisCall[index]) continue+ val position = loaders[index].nextLoadPositionUs+ if (position != C.TIME_END_OF_SOURCE) next = minOf(next, position)+ }+ if (next == Long.MAX_VALUE) break+ var progressed = false+ for (index in loaders.indices) {+ if (skipForThisCall[index]) continue+ val loader = loaders[index]+ val position = loader.nextLoadPositionUs+ val behind = position != C.TIME_END_OF_SOURCE && position <= loadingInfo.playbackPositionUs+ if (position == next || behind) progressed = loader.continueLoading(loadingInfo) || progressed+ }+ madeProgress = madeProgress || progressed+ } while (progressed)+ return madeProgress+ }++ private fun hasUnfinishedPrimary(): Boolean = loaders.indices.any {+ !optional[it] && loaders[it].nextLoadPositionUs != C.TIME_END_OF_SOURCE+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/HlsTimestampInitializationPolicy.kt b/player/src/main/java/com/streamvault/player/playback/HlsTimestampInitializationPolicy.ktnew file mode 100644index 00000000..8469342b--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/HlsTimestampInitializationPolicy.kt@@ -0,0 +1,31 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import androidx.media3.exoplayer.hls.HlsMediaSource+import com.streamvault.domain.model.PlaybackContentKind+import java.util.concurrent.TimeoutException++internal const val LIVE_HLS_TIMESTAMP_INITIALIZATION_TIMEOUT_MS = 30_000L++/**+ * Bounds the secondary rendition's dependency wait, not the HTTP request or total startup.+ * Keep one policy for foreground, preload and Android TV-input playback. Finite media retains+ * Media3's default; the live budget permits slow primary initialization before retrying.+ */+fun HlsMediaSource.Factory.applyPlaybackTimestampInitializationPolicy(+ contentKind: PlaybackContentKind+): HlsMediaSource.Factory = setTimestampAdjusterInitializationTimeoutMs(+ if (isLivePlayback(contentKind, ResolvedStreamType.HLS)) {+ LIVE_HLS_TIMESTAMP_INITIALIZATION_TIMEOUT_MS+ } else {+ 0L+ }+)++/** Media3 1.11 wraps this particular shared-adjuster failure in IOException. */+internal fun isHlsTimestampInitializationTimeout(error: Throwable): Boolean =+ generateSequence(error) { it.cause }.any {+ it is TimeoutException &&+ it.message?.startsWith("TimestampAdjuster failed to initialize in ") == true+ }diff --git a/player/src/main/java/com/streamvault/player/playback/LenientHlsPlaylistParserFactory.kt b/player/src/main/java/com/streamvault/player/playback/LenientHlsPlaylistParserFactory.ktindex 98c4771b..9da2bf56 100644--- a/player/src/main/java/com/streamvault/player/playback/LenientHlsPlaylistParserFactory.kt+++ b/player/src/main/java/com/streamvault/player/playback/LenientHlsPlaylistParserFactory.kt@@ -3,6 +3,7 @@package com.streamvault.player.playbackimport androidx.media3.common.util.UnstableApi+import androidx.media3.common.Cimport androidx.media3.exoplayer.hls.playlist.DefaultHlsPlaylistParserFactoryimport androidx.media3.exoplayer.hls.playlist.HlsMediaPlaylistimport androidx.media3.exoplayer.hls.playlist.HlsMultivariantPlaylist@@ -15,7 +16,9 @@ import java.io.ByteArrayInputStream* Works around HLS master playlists that omit the required NAME attribute on EXT-X-MEDIA.* Media3 rejects those playlists, while other HLS clients commonly accept them.*/-internal class LenientHlsPlaylistParserFactory : HlsPlaylistParserFactory {+internal class LenientHlsPlaylistParserFactory(+ private val stabilityTargetOffsetMs: Long? = null+) : HlsPlaylistParserFactory {private val delegateFactory = DefaultHlsPlaylistParserFactory()override fun createPlaylistParser(): ParsingLoadable.Parser<HlsPlaylist> =@@ -31,9 +34,42 @@ internal class LenientHlsPlaylistParserFactory : HlsPlaylistParserFactory {ParsingLoadable.Parser<HlsPlaylist> { uri, inputStream ->val manifest = inputStream.readBytes().toString(Charsets.UTF_8)val compatibleManifest = addMissingMediaNames(manifest)- delegate.parse(uri, ByteArrayInputStream(compatibleManifest.toByteArray(Charsets.UTF_8)))+ val playlist = delegate.parse(uri, ByteArrayInputStream(compatibleManifest.toByteArray(Charsets.UTF_8)))+ if (playlist is HlsMediaPlaylist) applyStabilityTarget(playlist) else playlist}+ private fun applyStabilityTarget(playlist: HlsMediaPlaylist): HlsMediaPlaylist {+ val targetMs = stabilityTargetOffsetMs ?: return playlist+ if (targetMs <= 0 || targetMs > Long.MAX_VALUE / 1_000L) return playlist+ val targetUs = targetMs * 1_000L+ // Preserve finite/event intent, explicit provider starts and short windows. A+ // full target-duration segment must remain before the requested start position.+ if (playlist.hasEndTag || playlist.playlistType != HlsMediaPlaylist.PLAYLIST_TYPE_UNKNOWN ||+ playlist.startOffsetUs != C.TIME_UNSET || playlist.targetDurationUs <= 0L ||+ playlist.durationUs - targetUs < playlist.targetDurationUs+ ) return playlist+ val control = playlist.serverControl+ val sourceTargetUs = when {+ control.partHoldBackUs != C.TIME_UNSET && playlist.partTargetDurationUs != C.TIME_UNSET ->+ control.partHoldBackUs+ control.holdBackUs != C.TIME_UNSET -> control.holdBackUs+ else -> 3L * playlist.targetDurationUs+ }+ if (sourceTargetUs >= targetUs) return playlist++ // Client-side equivalent of EXT-X-START:TIME-OFFSET=-target. Retaining the+ // original server control leaves Media3's speed-adjustment gate untouched.+ // Copy every unrelated field, including keys/maps, parts and interstitials.+ return HlsMediaPlaylist(+ playlist.playlistType, playlist.baseUri, playlist.tags, -targetUs, false,+ playlist.startTimeUs, playlist.hasDiscontinuitySequence, playlist.discontinuitySequence,+ playlist.mediaSequence, playlist.version, playlist.targetDurationUs, playlist.partTargetDurationUs,+ playlist.hasIndependentSegments, playlist.hasEndTag, playlist.hasProgramDateTime,+ playlist.protectionSchemes, playlist.segments, playlist.trailingParts, playlist.serverControl,+ playlist.renditionReports, playlist.interstitials, playlist.lastSeenInitSegment+ )+ }+private fun addMissingMediaNames(manifest: String): String {var fallbackNameIndex = 0return manifest.lineSequence().joinToString("\n") { line ->diff --git a/player/src/main/java/com/streamvault/player/playback/LiveMpegTsEndRecovery.kt b/player/src/main/java/com/streamvault/player/playback/LiveMpegTsEndRecovery.ktnew file mode 100644index 00000000..74f3c729--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/LiveMpegTsEndRecovery.kt@@ -0,0 +1,49 @@+package com.streamvault.player.playback++import com.streamvault.domain.model.PlaybackContentKind+import com.streamvault.domain.model.StreamInfo+import java.net.URI++/** A clean end is unexpected only for an explicitly live, directly owned HTTP TS source. */+fun canRecoverLiveMpegTsEnd(+ streamInfo: StreamInfo?,+ streamType: ResolvedStreamType,+ playbackStarted: Boolean,+ playWhenReady: Boolean,+ hasIndependentSourceOwner: Boolean,+ retryPending: Boolean+): Boolean = streamInfo != null &&+ streamInfo.playbackContentKind == PlaybackContentKind.LIVE &&+ streamType == ResolvedStreamType.MPEG_TS_LIVE && streamInfo.drmInfo == null &&+ runCatching { URI(streamInfo.url).scheme?.lowercase() in setOf("http", "https") }.getOrDefault(false) &&+ playbackStarted && playWhenReady && !hasIndependentSourceOwner && !retryPending++/** One refresh per tune; a source that repeatedly ends must not reopen forever. */+class LiveMpegTsEndRecovery {+ private val drain = StartupRefreshGate()+ private var attempted = false+ val hasAttempted: Boolean get() = attempted+ val isPending: Boolean get() = drain.isPending+ var abandoned = false+ private set++ fun onEnded(nowMs: Long, eligible: Boolean): Boolean {+ if (!eligible || attempted) return false+ attempted = true+ drain.begin(nowMs)+ return true+ }++ fun evaluate(nowMs: Long, canResume: Boolean, hasActiveTransfers: Boolean): StartupRefreshGate.Action =+ drain.evaluate(nowMs, canResume, hasActiveTransfers).also {+ if (it == StartupRefreshGate.Action.GIVE_UP) abandoned = true+ }++ fun pauseClock() = drain.pauseClock()++ fun reset(preserveAttempt: Boolean = false) {+ drain.clear()+ abandoned = false+ if (!preserveAttempt) attempted = false+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/LiveStartupErrorMessage.kt b/player/src/main/java/com/streamvault/player/playback/LiveStartupErrorMessage.ktnew file mode 100644index 00000000..153f37b6--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/LiveStartupErrorMessage.kt@@ -0,0 +1,15 @@+package com.streamvault.player.playback++import android.content.Context+import android.content.res.Configuration+import com.streamvault.player.R+import java.util.Locale++internal fun liveStartupTimeoutMessage(context: Context): String {+ // App language selection sets the process locale. The injected application context+ // can still carry the device's configuration rather than the UI's localized wrapper.+ val configuration = Configuration(context.resources.configuration)+ configuration.setLocale(Locale.getDefault())+ return context.createConfigurationContext(configuration)+ .getString(R.string.player_error_live_startup_timeout)+}diff --git a/player/src/main/java/com/streamvault/player/playback/LiveStartupWatchdog.kt b/player/src/main/java/com/streamvault/player/playback/LiveStartupWatchdog.ktnew file mode 100644index 00000000..85b3b8c0--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/LiveStartupWatchdog.kt@@ -0,0 +1,62 @@+package com.streamvault.player.playback++/** A monotonic, playable-progress budget for an initial live tune, separate from network retries. */+class LiveStartupWatchdog(+ private val noProgressTimeoutMs: Long = 45_000L,+ private val minBufferProgressMs: Long = 250L+) {+ enum class Action { NONE, REFRESH_SOURCE, GIVE_UP }++ private var lastProgressAtMs: Long? = null+ private var reserveHighWaterMs = 0L+ private var refreshUsed = false+ private var reported = false+ private var completed = false++ init {+ require(noProgressTimeoutMs > 0 && minBufferProgressMs > 0)+ }++ fun reset(preserveEpisode: Boolean = false) {+ if (!preserveEpisode || completed) refreshUsed = false+ lastProgressAtMs = null+ reserveHighWaterMs = 0L+ reported = false+ completed = false+ }++ /** Pause/detach must clear elapsed time even if the next polling tick never runs. */+ fun pauseClock() {+ lastProgressAtMs = null+ reserveHighWaterMs = 0L+ }++ fun evaluate(+ nowMs: Long,+ eligible: Boolean,+ firstVideoFrameRendered: Boolean,+ audioOnlyPlaying: Boolean,+ bufferedDurationMs: Long,+ sourceRetryAlreadyUsed: Boolean = false+ ): Action {+ if (firstVideoFrameRendered || audioOnlyPlaying) completed = true+ if (completed || reported) return Action.NONE+ if (!eligible) {+ pauseClock()+ return Action.NONE+ }+ val reserve = bufferedDurationMs.coerceAtLeast(0)+ val lastProgress = lastProgressAtMs+ if (lastProgress == null || reserve - reserveHighWaterMs >= minBufferProgressMs) {+ lastProgressAtMs = nowMs+ reserveHighWaterMs = maxOf(reserveHighWaterMs, reserve)+ return Action.NONE+ }+ if (nowMs - lastProgress < noProgressTimeoutMs) return Action.NONE+ reported = true+ return if (!refreshUsed && !sourceRetryAlreadyUsed) {+ refreshUsed = true+ Action.REFRESH_SOURCE+ } else Action.GIVE_UP+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/Media3PreloadWindowManager.kt b/player/src/main/java/com/streamvault/player/playback/Media3PreloadWindowManager.ktindex 6e9d3e81..8e383b4a 100644--- a/player/src/main/java/com/streamvault/player/playback/Media3PreloadWindowManager.kt+++ b/player/src/main/java/com/streamvault/player/playback/Media3PreloadWindowManager.kt@@ -223,13 +223,13 @@ internal class Media3PreloadWindowManager(val currentItem = normalized.items[normalized.currentIndex]val reusableCurrent = candidatesByKey[currentItem.key]- ?.takeIf { it.streamIdentity == preloadStreamIdentity(currentItem.streamInfo) }+ ?.takeIf { it.streamIdentity == streamIdentityFor(currentItem.streamInfo) }if (reusableCurrent == null) providerLimitBlocked = falseval stableCurrentIndex = reusableCurrent?.rankingIndex ?: normalized.currentIndexval nextCandidates = linkedMapOf<String, ManagedCandidate>()normalized.items.forEachIndexed { rankingIndex, item ->- val streamIdentity = preloadStreamIdentity(item.streamInfo)+ val streamIdentity = streamIdentityFor(item.streamInfo)val expectedRankingIndex = stableCurrentIndex + rankingIndex - normalized.currentIndexval existing = candidatesByKey[item.key]if (existing != null && existing.streamIdentity == streamIdentity &&@@ -294,7 +294,7 @@ internal class Media3PreloadWindowManager(fun getMediaSource(streamInfo: StreamInfo): ManagedMediaSource? {val manager = preloadManager ?: return nullif (released) return null- val mediaItem = mediaItemsByStreamIdentity[preloadStreamIdentity(streamInfo)] ?: return null+ val mediaItem = mediaItemsByStreamIdentity[streamIdentityFor(streamInfo)] ?: return nullval candidate = candidatesByKey.values.firstOrNull { it.mediaItem == mediaItem } ?: return nullcompletedMediaItems.remove(mediaItem)foregroundMediaItems += mediaItem@@ -417,6 +417,9 @@ internal class Media3PreloadWindowManager()}+ private fun streamIdentityFor(streamInfo: StreamInfo): String =+ "${preloadStreamIdentity(streamInfo)}:${mediaSourceFactory.mediaIdFor(streamInfo)}"+private fun logSkip(item: PlayerPreloadItem, reason: String) {safeLog("preload skipped key=${sanitizePreloadKey(item.key)} " +diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackBufferPolicies.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackBufferPolicies.ktindex 473be4da..06cab809 100644--- a/player/src/main/java/com/streamvault/player/playback/PlaybackBufferPolicies.kt+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackBufferPolicies.kt@@ -52,6 +52,7 @@ internal object PlaybackBufferPolicies {private const val LARGE_LIVE_MAX_BUFFER_MS = 90_000private const val LARGE_LIVE_PLAYBACK_BUFFER_MS = 5_000private const val LARGE_LIVE_REBUFFER_MS = 15_000+ private const val RAW_TS_LOADING_WINDOW_MS = 2_000fun forPlayback(isLive: Boolean,@@ -104,9 +105,11 @@ internal object PlaybackBufferPolicies {val isLive = isLivePlayback(kind, resolvedStreamType)if (bufferMode == PlaybackBufferMode.MEDIUM && isLive) {return mediumLivePolicy(label = "medium-live", qualityReason = "user-medium")+ .withRawTsLoadingWindow(resolvedStreamType)}if (bufferMode == PlaybackBufferMode.LARGE && isLive) {return largeLivePolicy(label = "large-live", qualityReason = "user-large")+ .withRawTsLoadingWindow(resolvedStreamType)}if (!isLive && resolvedStreamType == ResolvedStreamType.HLS) {return baselineLivePolicy(@@ -229,6 +232,17 @@ internal object PlaybackBufferPolicies {)}+ private fun PlaybackBufferPolicy.withRawTsLoadingWindow(+ resolvedStreamType: ResolvedStreamType+ ): PlaybackBufferPolicy {+ if (resolvedStreamType != ResolvedStreamType.MPEG_TS_LIVE) return this+ // Continuous TS keeps one response open while loading pauses. Retain the existing+ // ceiling and restart loading near it to avoid prolonged socket backpressure.+ // Startup/refill thresholds and byte limits are independent of this loading floor.+ // Progressive loading checks can overshoot this duration window.+ return copy(minBufferMs = maxOf(minBufferMs, maxBufferMs - RAW_TS_LOADING_WINDOW_MS))+ }+private fun mediumLivePolicy(label: String,qualityReason: String,diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackLoadControl.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackLoadControl.ktindex dcf8b274..311d3808 100644--- a/player/src/main/java/com/streamvault/player/playback/PlaybackLoadControl.kt+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackLoadControl.kt@@ -2,6 +2,7 @@package com.streamvault.player.playback+import android.os.SystemClockimport androidx.media3.common.Cimport androidx.media3.exoplayer.DefaultLoadControlimport androidx.media3.exoplayer.LoadControl@@ -30,8 +31,21 @@ internal class PlaybackLoadControl(private val selections = mutableMapOf<PlayerId, Array<out ExoTrackSelection?>>()private val appliedModes = mutableMapOf<PlayerId, Boolean>()private val references = mutableMapOf<PlayerId, Int>()+ private var foregroundTargetBytes = DEFAULT_MIN_BUFFER_SIZE+ private data class AllocationSnapshot(val playerId: PlayerId, val bytes: Int, val target: Int, val atMs: Long)+ @Volatile private var foregroundAllocation: AllocationSnapshot? = null++ /** Small immutable snapshot published from the playback thread for transition diagnostics. */+ fun describeAllocation(): String {+ val snapshot = foregroundAllocation ?: return "allocatedBytes=unknown targetBytes=unknown"+ return "allocatedBytes=${snapshot.bytes} targetBytes=${snapshot.target} " ++ "allocationSampleAgeMs=${(SystemClock.elapsedRealtime() - snapshot.atMs).coerceAtLeast(0L)}"+ }override fun onPrepared(playerId: PlayerId) {+ if (references[playerId] == null && playerId != PlayerId.PRELOAD) {+ foregroundTargetBytes = DEFAULT_MIN_BUFFER_SIZE+ }references[playerId] = (references[playerId] ?: 0) + 1super.onPrepared(playerId)}@@ -57,7 +71,14 @@ internal class PlaybackLoadControl(appliedModes[parameters.playerId] = multiviewMode}}- return super.shouldContinueLoading(parameters)+ val loading = super.shouldContinueLoading(parameters)+ if (parameters.playerId != PlayerId.PRELOAD) {+ foregroundAllocation = AllocationSnapshot(+ parameters.playerId, getAllocator(parameters.playerId).totalBytesAllocated,+ foregroundTargetBytes, SystemClock.elapsedRealtime()+ )+ }+ return loading}override fun onStopped(playerId: PlayerId) {@@ -78,6 +99,7 @@ internal class PlaybackLoadControl(references.remove(playerId)selections.remove(playerId)appliedModes.remove(playerId)+ if (foregroundAllocation?.playerId == playerId) foregroundAllocation = null}}// Reserve half the Java heap for the app, decoder bookkeeping and chunk overshoot.@@ -113,6 +135,8 @@ internal class PlaybackLoadControl(}val floor = if (preload) DEFAULT_MIN_BUFFER_SIZE elsemaxOf(DEFAULT_MIN_BUFFER_SIZE, policy.targetBufferBytes)- return (knownBytes + unknownBytes).coerceAtLeast(floor.toLong()).coerceAtMost(budget).toInt()+ val target = (knownBytes + unknownBytes).coerceAtLeast(floor.toLong()).coerceAtMost(budget).toInt()+ if (!preload) foregroundTargetBytes = target+ return target}}diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackTransferTracker.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackTransferTracker.ktnew file mode 100644index 00000000..80d3bcb3--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackTransferTracker.kt@@ -0,0 +1,55 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import android.net.Uri+import androidx.media3.datasource.DataSource+import androidx.media3.datasource.DataSpec+import androidx.media3.datasource.TransferListener+import java.util.Collections+import java.util.IdentityHashMap++/** Tracks actual HTTP data-source ownership through open/close, including cancelled reads. */+class PlaybackTransferTracker {+ private val active = Collections.newSetFromMap(IdentityHashMap<DataSource, Boolean>())++ val hasActiveTransfers: Boolean+ get() = synchronized(active) { active.isNotEmpty() }++ fun wrap(upstream: DataSource.Factory): DataSource.Factory = DataSource.Factory {+ TrackedDataSource(upstream.createDataSource())+ }++ private inner class TrackedDataSource(private val upstream: DataSource) : DataSource {+ private var tracked = false++ override fun addTransferListener(transferListener: TransferListener) = upstream.addTransferListener(transferListener)++ override fun open(dataSpec: DataSpec): Long {+ if (dataSpec.uri.scheme.equals("http", true) || dataSpec.uri.scheme.equals("https", true)) {+ synchronized(active) { active.add(this) }+ tracked = true+ }+ try {+ return upstream.open(dataSpec)+ } catch (failure: Throwable) {+ try { close() } catch (closing: Throwable) { failure.addSuppressed(closing) }+ throw failure+ }+ }++ override fun read(buffer: ByteArray, offset: Int, length: Int): Int = upstream.read(buffer, offset, length)+ override fun getUri(): Uri? = upstream.uri+ override fun getResponseHeaders(): Map<String, List<String>> = upstream.responseHeaders++ override fun close() {+ // Do not advertise a drained source before its upstream close has completed.+ // A failed close remains conservatively active; the refresh gate can give up.+ upstream.close()+ if (tracked) {+ synchronized(active) { active.remove(this) }+ tracked = false+ }+ }+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.ktindex 18e83f18..c2323491 100644--- a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt+++ b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt@@ -11,6 +11,7 @@ import androidx.media3.common.MimeTypesimport androidx.media3.common.util.UnstableApiimport androidx.media3.datasource.DataSourceimport androidx.media3.extractor.DefaultExtractorsFactory+import androidx.media3.extractor.ExtractorsFactoryimport androidx.media3.extractor.ts.TsExtractorimport androidx.media3.extractor.ts.DefaultTsPayloadReaderFactoryimport androidx.media3.exoplayer.dash.DashMediaSource@@ -23,6 +24,8 @@ import androidx.media3.exoplayer.source.ProgressiveMediaSourceimport androidx.media3.exoplayer.drm.DrmSessionManagerProviderimport com.streamvault.domain.model.DrmInfoimport com.streamvault.domain.model.DrmScheme+import com.streamvault.domain.model.PlaybackBufferMode+import com.streamvault.domain.model.PlaybackContentKindimport com.streamvault.domain.model.VodHttpProtocolModeimport com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.StreamType@@ -38,8 +41,8 @@ private val TS_SUBTITLE_FORMATS: List<Format> = listOf(.build())-internal fun liveMpegTsExtractorsFactory(): DefaultExtractorsFactory =- DefaultExtractorsFactory()+internal fun liveMpegTsExtractorsFactory(normalizeAvcSamples: Boolean = true): ExtractorsFactory {+ val factory = DefaultExtractorsFactory().setDisableArtworkMetadata(true)// Xtream live ".ts" URLs are raw transport streams, not HLS segments. The HLS// mode path is more permissive about segment continuity, but it also enables@@ -51,11 +54,18 @@ internal fun liveMpegTsExtractorsFactory(): DefaultExtractorsFactory =or DefaultTsPayloadReaderFactory.FLAG_IGNORE_SPLICE_INFO_STREAM).setTsSubtitleFormats(TS_SUBTITLE_FORMATS)+ // Detection remains enabled for streams without AUD. Normalize prefix-only samples+ // instead of removing their bytes or disabling that compatibility path.+ return if (normalizeAvcSamples) AvcAccessUnitExtractorsFactory(factory) else factory+}@UnstableApiclass PlayerMediaSourceFactory(- private val dataSourceFactoryProvider: PlayerDataSourceFactoryProvider+ private val dataSourceFactoryProvider: PlayerDataSourceFactoryProvider,+ private val bufferModeProvider: () -> PlaybackBufferMode = { PlaybackBufferMode.AUTO }) {+ private val transfers = PlaybackTransferTracker()+ val hasActiveNetworkTransfers: Boolean get() = transfers.hasActiveTransfersfun create(streamInfo: StreamInfo,resolvedStreamType: ResolvedStreamType,@@ -70,11 +80,13 @@ class PlayerMediaSourceFactory(vodHttpProtocolMode = vodHttpProtocolMode,preload = preload)- val mediaSource = mediaSourceFactory.createMediaSource(mediaItemFor(streamInfo))+ val mediaItem = mediaItemFor(streamInfo, resolvedStreamType)+ val mediaSource = mediaSourceFactory.createMediaSource(mediaItem)Log.i(TAG,"media-source streamType=$resolvedStreamType timeout=$timeoutProfile source=${mediaSource::class.java.simpleName} " ++ "requestedLiveTargetFloorMs=${liveTargetOffsetMsFor(streamInfo, resolvedStreamType)} " +"target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.requestHeadersOrigin ?: streamInfo.url)}")return timeoutProfile to mediaSource@@ -87,17 +99,24 @@ class PlayerMediaSourceFactory(vodHttpProtocolMode: VodHttpProtocolMode = VodHttpProtocolMode.COMPATIBILITY_HTTP1,preload: Boolean = false): Pair<PlayerTimeoutProfile, MediaSource.Factory> {- val (timeoutProfile, dataSourceFactory) = dataSourceFactoryProvider.createFactory(+ val (timeoutProfile, upstreamDataSourceFactory) = dataSourceFactoryProvider.createFactory(streamInfo = streamInfo,resolvedStreamType = resolvedStreamType,vodHttpProtocolMode = vodHttpProtocolMode,preload = preload)+ val dataSourceFactory = if (isLivePlayback(streamInfo.playbackContentKind, resolvedStreamType) &&+ streamInfo.drmInfo == null && resolvedStreamType != ResolvedStreamType.RTSP+ ) transfers.wrap(upstreamDataSourceFactory) else upstreamDataSourceFactoryval mediaSourceFactory = when {streamInfo.streamType == StreamType.RTSP || resolvedStreamType == ResolvedStreamType.RTSP ->RtspMediaSource.Factory()resolvedStreamType == ResolvedStreamType.HLS -> HlsMediaSource.Factory(dataSourceFactory)- .setPlaylistParserFactory(LenientHlsPlaylistParserFactory())+ .applyPlaybackTimestampInitializationPolicy(streamInfo.playbackContentKind)+ .applyPlaybackRenditionLoadingPolicy(streamInfo.playbackContentKind)+ .setPlaylistParserFactory(LenientHlsPlaylistParserFactory(+ stabilityTargetOffsetMs = liveTargetOffsetMsFor(streamInfo, resolvedStreamType)+ )).setAllowChunklessPreparation(true).setLoadErrorHandlingPolicy(retryPolicy)@@ -114,7 +133,9 @@ class PlayerMediaSourceFactory(resolvedStreamType == ResolvedStreamType.MPEG_TS_LIVE -> ProgressiveMediaSource.Factory(dataSourceFactory,- liveMpegTsExtractorsFactory()+ liveMpegTsExtractorsFactory(+ normalizeAvcSamples = isLivePlayback(streamInfo.playbackContentKind, resolvedStreamType)+ )).setLoadErrorHandlingPolicy(retryPolicy)@@ -142,10 +163,23 @@ class PlayerMediaSourceFactory(return timeoutProfile to mediaSourceFactory}- internal fun mediaItemFor(streamInfo: StreamInfo): MediaItem {+ internal fun liveTargetOffsetMsFor(+ streamInfo: StreamInfo,+ resolvedStreamType: ResolvedStreamType = StreamTypeResolver.resolve(streamInfo),+ bufferMode: PlaybackBufferMode = bufferModeProvider()+ ): Long? = if (+ streamInfo.playbackContentKind == PlaybackContentKind.LIVE &&+ resolvedStreamType == ResolvedStreamType.HLS &&+ bufferMode in setOf(PlaybackBufferMode.MEDIUM, PlaybackBufferMode.LARGE)+ ) STABILITY_LIVE_TARGET_MS else null++ internal fun mediaItemFor(+ streamInfo: StreamInfo,+ resolvedStreamType: ResolvedStreamType = StreamTypeResolver.resolve(streamInfo)+ ): MediaItem {return MediaItem.Builder().setUri(Uri.parse(streamInfo.url))- .setMediaId(mediaIdFor(streamInfo))+ .setMediaId(mediaIdFor(streamInfo, resolvedStreamType)).setMediaMetadata(androidx.media3.common.MediaMetadata.Builder().setTitle(streamInfo.title)@@ -170,9 +204,22 @@ class PlayerMediaSourceFactory(.build()}- fun mediaIdFor(streamInfo: StreamInfo): String {+ fun mediaIdFor(+ streamInfo: StreamInfo,+ resolvedStreamType: ResolvedStreamType = StreamTypeResolver.resolve(streamInfo)+ ): String {+ val key = mediaIdentityKeyFor(streamInfo)+ val target = liveTargetOffsetMsFor(streamInfo, resolvedStreamType)+ return stableHash(if (target == null) key else "$key|liveTargetOffsetMs=$target")+ }++ /** Decoder history belongs to the media, independently of its live-start policy. */+ internal fun compatibilityMediaIdFor(streamInfo: StreamInfo): String =+ stableHash(mediaIdentityKeyFor(streamInfo))++ private fun mediaIdentityKeyFor(streamInfo: StreamInfo): String {val drmKey = streamInfo.drmInfo?.let { "${it.scheme}:${it.licenseUrl}" }.orEmpty()- return stableHash("${streamInfo.url}|${streamInfo.title.orEmpty()}|$drmKey")+ return "${streamInfo.url}|${streamInfo.title.orEmpty()}|$drmKey"}private fun DrmScheme.toUuid(): UUID = when (this) {@@ -183,6 +230,7 @@ class PlayerMediaSourceFactory(companion object {private const val TAG = "PlayerMediaSourceFactory"+ private const val STABILITY_LIVE_TARGET_MS = 10_000L}}diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt b/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.ktindex 151e8960..27515876 100644--- a/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt+++ b/player/src/main/java/com/streamvault/player/playback/PlayerRetryPolicy.kt@@ -38,6 +38,9 @@ class PlayerRetryPolicy() : LoadErrorHandlingPolicy {private val defaultFallbackPolicy = DefaultLoadErrorHandlingPolicy()private val pendingLoadRecoveryTaskIds = ConcurrentHashMap.newKeySet<Long>()+ // Published from load callbacks for the application-thread fatal-error handler. Keep+ // exact exception identities: a playlist/auth error with the same status is not media.+ @Volatile private var exhaustedMediaRefusals: List<Throwable> = emptyList()/** True while Media3 still owns a retry or fallback for a failed load task. */val hasPendingLoadRecovery: Boolean@@ -67,10 +70,17 @@ class PlayerRetryPolicy(*/fun shouldRetryWholeSource(error: Throwable, playbackStarted: Boolean, attempt: Int): Boolean =attempt <= MAX_WHOLE_SOURCE_RETRIES_PER_OUTAGE &&- shouldRetry(error, streamContext, playbackStarted, attempt)+ (playbackStarted && isLiveMediaRefusal(error) ||+ shouldRetry(error, streamContext, playbackStarted, attempt))fun maxWholeSourceRetryAttempts(error: Throwable, playbackStarted: Boolean): Int =- if (maxAttempts(error, playbackStarted) > 0) MAX_WHOLE_SOURCE_RETRIES_PER_OUTAGE else 0+ if (playbackStarted && isLiveMediaRefusal(error) || maxAttempts(error, playbackStarted) > 0)+ MAX_WHOLE_SOURCE_RETRIES_PER_OUTAGE else 0++ internal fun isLiveMediaRefusal(error: Throwable): Boolean {+ val refusals = exhaustedMediaRefusals+ return generateSequence(error) { it.cause }.any { cause -> refusals.any { it === cause } }+ }fun clearPendingLoadRecovery() {val hadPendingRecovery = pendingLoadRecoveryTaskIds.isNotEmpty()@@ -79,6 +89,7 @@ class PlayerRetryPolicy(}fun retryDelayMs(error: Throwable, attempt: Int): Long {+ if (isLiveMediaRefusal(error)) return FAST_TRANSIENT_RETRY_DELAY_MSval category = PlayerErrorClassifier.classify(error)if (fastRetryOnTransientFailures() && isFastRetryEligible(category)) {return FAST_TRANSIENT_RETRY_DELAY_MS@@ -115,6 +126,7 @@ class PlayerRetryPolicy(}fun retryReason(error: Throwable): String {+ if (isLiveMediaRefusal(error)) return "refresh-live-media-playlist"return when (PlayerErrorClassifier.classify(error)) {PlaybackErrorCategory.LIVE_WINDOW -> "refresh-live-window"PlaybackErrorCategory.NETWORK -> "transient-network"@@ -183,11 +195,26 @@ class PlayerRetryPolicy(val error = loadErrorInfo.exceptionval started = playbackStarted()val category = PlayerErrorClassifier.classify(error)- val retryDelayMs = if (shouldRetry(error, streamContext, started, attempt)) {+ val mediaRefusal = started && streamContext.isLive &&+ streamContext.resolvedStreamType == ResolvedStreamType.HLS &&+ loadErrorInfo.mediaLoadData.dataType == C.DATA_TYPE_MEDIA &&+ generateSequence<Throwable>(error) { it.cause }+ .filterIsInstance<HttpDataSource.InvalidResponseCodeException>()+ .any { it.responseCode in setOf(403, 404, 410) }+ val retryDelayMs = if (mediaRefusal) {+ if (attempt == 1) FAST_TRANSIENT_RETRY_DELAY_MS else C.TIME_UNSET+ } else if (shouldRetry(error, streamContext, started, attempt)) {retryDelayMs(error, attempt)} else {C.TIME_UNSET}+ if (mediaRefusal && attempt > 1 && retryDelayMs == C.TIME_UNSET &&+ exhaustedMediaRefusals.none { it === error }+ ) {+ // Multiple audio/video loads can fail together. Bound retention even if a+ // track is abandoned before its fatal error reaches the player.+ exhaustedMediaRefusals = (exhaustedMediaRefusals + error).takeLast(8)+ }if (Log.isLoggable(PLAYBACK_PERF_TAG, Log.DEBUG)) {val causeTypes = generateSequence<Throwable>(error) { it.cause }.map { it.javaClass.simpleName }@@ -196,6 +223,7 @@ class PlayerRetryPolicy(Log.d(PLAYBACK_PERF_TAG,"load-retry category=$category attempt=$attempt delayMs=$retryDelayMs " ++ "dataType=${loadErrorInfo.mediaLoadData.dataType} mediaRefusal=$mediaRefusal " +"started=$started streamType=${streamContext.resolvedStreamType} " +"contentKind=${streamContext.playbackContentKind} causes=$causeTypes")@@ -219,7 +247,16 @@ class PlayerRetryPolicy(streamContext: PlaybackRetryContext,playbackStarted: Boolean): Int {- return when (PlayerErrorClassifier.classify(error)) {+ val category = PlayerErrorClassifier.classify(error)+ if (streamContext.isLive && streamContext.resolvedStreamType == ResolvedStreamType.HLS &&+ category in setOf(PlaybackErrorCategory.NETWORK, PlaybackErrorCategory.UNKNOWN) &&+ isHlsTimestampInitializationTimeout(error)+ ) {+ // A dependency wait is not a failed socket read. Repeating the normal live+ // request budget would turn the finite wait into minutes before refreshing.+ return 1+ }+ return when (category) {PlaybackErrorCategory.DRM,PlaybackErrorCategory.DECODER,PlaybackErrorCategory.CLEAR_TEXT_BLOCKED,diff --git a/player/src/main/java/com/streamvault/player/playback/StartupRefreshGate.kt b/player/src/main/java/com/streamvault/player/playback/StartupRefreshGate.ktnew file mode 100644index 00000000..a40772ba--- /dev/null+++ b/player/src/main/java/com/streamvault/player/playback/StartupRefreshGate.kt@@ -0,0 +1,48 @@+package com.streamvault.player.playback++/** Cancel first, then wait for owned HTTP sources to drain before opening a replacement. */+class StartupRefreshGate(+ private val drainTimeoutMs: Long = 25_000L,+ private val quietPeriodMs: Long = 500L+) {+ init { require(drainTimeoutMs > 0 && quietPeriodMs >= 0) }+ enum class Action { WAIT, READY, GIVE_UP }+ var isPending = false+ private set+ private var startedAtMs: Long? = null+ private var quietAtMs: Long? = null++ fun begin(nowMs: Long) {+ isPending = true+ startedAtMs = nowMs+ quietAtMs = null+ }++ fun pauseClock() {+ startedAtMs = null+ quietAtMs = null+ }++ fun clear() {+ isPending = false+ pauseClock()+ }++ fun evaluate(nowMs: Long, canResume: Boolean, hasActiveTransfers: Boolean): Action {+ if (!isPending) return Action.WAIT+ if (!canResume) { pauseClock(); return Action.WAIT }+ val started = startedAtMs ?: nowMs.also { startedAtMs = it }+ if (hasActiveTransfers) {+ quietAtMs = null+ if (nowMs - started >= drainTimeoutMs) {+ clear()+ return Action.GIVE_UP+ }+ return Action.WAIT+ }+ val quiet = quietAtMs ?: nowMs.also { quietAtMs = it }+ if (nowMs - quiet < quietPeriodMs) return Action.WAIT+ clear()+ return Action.READY+ }+}diff --git a/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt b/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.ktindex 0b037afb..063d4488 100644--- a/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt+++ b/player/src/main/java/com/streamvault/player/playback/VideoStallDetector.kt@@ -15,12 +15,15 @@ class VideoStallDetector(private var lastPositionMs: Long = 0Lprivate var lastPositionCheckMs: Long = 0Lprivate var stalled = false+ private var bufferingReserveHighWaterMs: Long? = null+ private var lastBufferingProgressAtMs: Long? = null@Synchronizedfun restartAfterRecoveryAttempt() {startedAtMs = nowMs()lastPositionCheckMs = startedAtMsstalled = false+ clearBufferingProgress()// Retain lastFrameAtMs: a seek attempt is not evidence of a rendered frame.}@@ -33,6 +36,7 @@ class VideoStallDetector(lastPositionMs = 0LlastPositionCheckMs = nowstalled = false+ clearBufferingProgress()}@Synchronized@@ -61,7 +65,8 @@ class VideoStallDetector(recoverBufferingStalls: Boolean = false,recoverReadyStalls: Boolean = true,recoverPositionAdvancingReadyStalls: Boolean = true,- recoverFrameSilentReadyStalls: Boolean = false+ recoverFrameSilentReadyStalls: Boolean = false,+ deferReporting: Boolean = false): Boolean {val now = nowMs()val playbackRequested = isPlaying || playWhenReady@@ -71,15 +76,31 @@ class VideoStallDetector(lastPositionMs = currentPositionMslastPositionCheckMs = nowstalled = false+ clearBufferingProgress()return false}- if (now - startedAtMs < initialGraceMs) return falseif (canEvaluateBufferingStall) {- val frameSilent = if (lastFrameAtMs <= 0L) {- now - startedAtMs >= bufferingStallThresholdMs- } else {- now - lastFrameAtMs >= bufferingStallThresholdMs+ val previousReserve = bufferingReserveHighWaterMs+ if (previousReserve == null || bufferedDurationMs > previousReserve) {+ bufferingReserveHighWaterMs = bufferedDurationMs+ // A first observation is only a baseline. Later growth proves active refill;+ // frame silence is expected while load control waits for enough media.+ if (previousReserve != null) lastBufferingProgressAtMs = now}+ } else {+ clearBufferingProgress()+ }+ if (deferReporting) {+ // Observe refill throughout startup grace, but do not consume a one-shot stall+ // that the caller cannot handle yet. Keep frame and progress clocks intact.+ stalled = false+ return false+ }+ if (now - startedAtMs < initialGraceMs) return false+ if (canEvaluateBufferingStall) {+ val frameAtMs = if (lastFrameAtMs <= 0L) startedAtMs else lastFrameAtMs+ val lastProgressAtMs = maxOf(frameAtMs, lastBufferingProgressAtMs ?: frameAtMs)+ val frameSilent = now - lastProgressAtMs >= bufferingStallThresholdMsif (frameSilent && !stalled) {stalled = truereturn true@@ -124,4 +145,9 @@ class VideoStallDetector(if (!frameSilent) stalled = falsereturn false}++ private fun clearBufferingProgress() {+ bufferingReserveHighWaterMs = null+ lastBufferingProgressAtMs = null+ }}diff --git a/player/src/main/java/com/streamvault/player/stats/FrameRateDetector.kt b/player/src/main/java/com/streamvault/player/stats/FrameRateDetector.ktindex e00c88c2..c3225c4b 100644--- a/player/src/main/java/com/streamvault/player/stats/FrameRateDetector.kt+++ b/player/src/main/java/com/streamvault/player/stats/FrameRateDetector.kt@@ -1,17 +1,19 @@package com.streamvault.player.statsimport java.util.concurrent.atomic.AtomicInteger+import kotlin.math.abs+import kotlin.math.roundToInt/*** Detects the nominal frame rate of a stream from the presentation timestamps of rendered frames- * and then **locks**: after [framesToLock] usable frames it computes the rate once, snaps it to the- * nearest standard broadcast rate (23.976 / 24 / 25 / 29.97 / 30 / 50 / 59.94 / 60) and stops doing- * any work. This is deliberately cheaper than counting frames per second forever, and unlike a- * rendered-frames-per-second measurement it reports the *stream* rate even when a slow device is- * dropping frames, because it uses the smallest timestamp gap rather than the render throughput.+ * and then locks. At least [framesToLock] usable intervals and four seconds of timing are needed:+ * millisecond-rounded timestamps otherwise cannot reliably distinguish 59.94 from 60 fps.+ * A supported cluster of short intervals establishes the frame period; longer intervals contribute+ * their nearest whole number of frames, preserving cadence when the renderer drops frames.+ * Isolated short gaps cannot establish a faster rate. Insufficient evidence stays unknown.*- * Cost while detecting: one subtraction and one comparison per rendered frame. Cost after locking:- * two volatile reads per frame.+ * Observation uses a bounded primitive ring buffer. Estimation is occasional and stops after a lock;+ * the steady-state frame callback only checks the published result and source generation.** Threading: [onFrame] is called on ExoPlayer's playback thread, [lockedFrameRate] is read from the* Main thread, and [reset] may be called from Main. The working state is only touched on the@@ -28,8 +30,11 @@ class FrameRateDetector(private var activeGeneration = -1private var lastPresentationTimeUs = Long.MIN_VALUE- private var minDeltaUs = Long.MAX_VALUE- private var usableFrames = 0+ private val intervals = LongArray(MAX_SAMPLES)+ private var sampleCount = 0+ private var nextSample = 0+ private var sampleSpanUs = 0L+ private var samplesSinceEstimate = 0/** Detected frame rate, or 0 until enough frames have been seen. */val lockedFrameRate: Float get() {@@ -50,28 +55,84 @@ class FrameRateDetector(if (activeGeneration != currentGeneration) {activeGeneration = currentGenerationlastPresentationTimeUs = Long.MIN_VALUE- minDeltaUs = Long.MAX_VALUE- usableFrames = 0+ clearSamples()}val last = lastPresentationTimeUslastPresentationTimeUs = presentationTimeUsif (last == Long.MIN_VALUE) returnval delta = presentationTimeUs - last- // Ignore seeks/discontinuities and duplicate timestamps: only 5..240 fps gaps count.- if (delta < MIN_DELTA_US || delta > MAX_DELTA_US) return- if (delta < minDeltaUs) minDeltaUs = delta- usableFrames++- if (usableFrames >= framesToLock) {- result = Detection(activeGeneration, snapToStandardRate(1_000_000f / minDeltaUs))+ if (delta == 0L) return+ if (delta < 0L || delta > MAX_DELTA_US) {+ clearSamples()+ return}+ if (delta < MIN_DELTA_US) return+ if (sampleCount == intervals.size) sampleSpanUs -= intervals[nextSample] else sampleCount+++ intervals[nextSample] = delta+ sampleSpanUs += delta+ nextSample = (nextSample + 1) % intervals.size+ samplesSinceEstimate+++ if (sampleCount >= framesToLock && sampleSpanUs >= MIN_SPAN_US &&+ samplesSinceEstimate >= ESTIMATE_INTERVAL+ ) {+ samplesSinceEstimate = 0+ estimate()?.let { result = Detection(activeGeneration, it) }+ }+ }++ private fun clearSamples() {+ sampleCount = 0+ nextSample = 0+ sampleSpanUs = 0+ samplesSinceEstimate = 0+ }++ private fun estimate(): Float? {+ val sorted = intervals.copyOf(sampleCount).also { it.sort() }+ var periodUs = 0.0+ for (start in sorted.indices) {+ var end = start + 1+ while (end < sorted.size && sorted[end] - sorted[start] <= CLUSTER_SPREAD_US) end+++ if (end - start >= 2) {+ // A rare normal interval can reveal a faster source under heavy frame dropping.+ // Do not mistake it for an outlier and lock to half-rate before more timing arrives.+ if (start > 0 && sampleSpanUs < OUTLIER_OBSERVATION_US) return null+ var sum = 0L+ for (index in start until end) sum += sorted[index]+ periodUs = sum.toDouble() / (end - start)+ break+ }+ }+ if (periodUs == 0.0) return null+ var spanUs = 0L+ var frameIntervals = 0L+ var supported = 0+ for (gap in sorted) {+ val frames = (gap / periodUs).roundToInt()+ if (frames >= 1 && abs(gap - frames * periodUs) <= INTERVAL_ERROR_US) {+ spanUs += gap+ frameIntervals += frames+ supported+++ }+ }+ if (supported * 100 < sampleCount * 95 || spanUs < MIN_SPAN_US) return null+ val rate = (1_000_000.0 * frameIntervals / spanUs).toFloat()+ return rate.takeIf { it in 5f..240f }?.let(::snapToStandardRate)}companion object {const val DEFAULT_FRAMES_TO_LOCK = 60- private const val MIN_DELTA_US = 1_000_000L / 240+ private const val MAX_SAMPLES = 1024+ private const val MIN_SPAN_US = 4_000_000L+ private const val OUTLIER_OBSERVATION_US = 8_000_000L+ private const val ESTIMATE_INTERVAL = 30+ // Allow whole-millisecond rounding even at 240 fps; validate the final rate separately.+ private const val MIN_DELTA_US = 3_000Lprivate const val MAX_DELTA_US = 1_000_000L / 5- private val STANDARD_RATES = floatArrayOf(23.976f, 24f, 25f, 29.97f, 30f, 48f, 50f, 59.94f, 60f, 100f, 120f)+ private const val CLUSTER_SPREAD_US = 2_000L+ private const val INTERVAL_ERROR_US = 1_100+ private val STANDARD_RATES = floatArrayOf(23.976f, 24f, 25f, 29.97f, 30f, 47.952f, 48f, 50f, 59.94f, 60f, 100f, 119.88f, 120f, 240f)/** Snap to a standard rate when within 2 %, otherwise keep two decimals. */fun snapToStandardRate(rate: Float): Float {diff --git a/player/src/main/java/com/streamvault/player/stats/PlaybackBufferingTracker.kt b/player/src/main/java/com/streamvault/player/stats/PlaybackBufferingTracker.ktnew file mode 100644index 00000000..aba7c8b7--- /dev/null+++ b/player/src/main/java/com/streamvault/player/stats/PlaybackBufferingTracker.kt@@ -0,0 +1,54 @@+package com.streamvault.player.stats++import com.streamvault.player.PlaybackState++/** Main-thread diagnostics. BUFFERING records an interruption, not proof of buffer depletion. */+internal class PlaybackBufferingTracker(private val nowMs: () -> Long) {+ // A renderer/track reconfiguration can enter BUFFERING while media remains buffered.+ // Keep counting that interruption without assigning a network or reserve cause.+ enum class Cause { STARTUP, SEEK, RECOVERY, REBUFFER }+ enum class Outcome { STARTED, RESUMED, CANCELLED }+ data class Event(val cause: Cause, val outcome: Outcome, val durationMs: Long)++ private var pendingCause: Cause? = Cause.STARTUP+ private var activeCause: Cause? = null+ private var startedAtMs = 0L++ fun reset(recovering: Boolean = false) {+ pendingCause = if (recovering) Cause.RECOVERY else Cause.STARTUP+ activeCause = null+ }++ fun onSeek() {+ pendingCause = Cause.SEEK+ }++ fun onRecovery() {+ pendingCause = Cause.RECOVERY+ }++ fun update(state: PlaybackState, playWhenReady: Boolean, playbackStarted: Boolean): List<Event> {+ val now = nowMs()+ val events = mutableListOf<Event>()+ if (activeCause != null && (state != PlaybackState.BUFFERING || !playWhenReady || pendingCause != null)) {+ events += Event(+ activeCause!!,+ if (state == PlaybackState.READY && playWhenReady && pendingCause == null) {+ Outcome.RESUMED+ } else Outcome.CANCELLED,+ (now - startedAtMs).coerceAtLeast(0L)+ )+ activeCause = null+ }+ if (state == PlaybackState.BUFFERING && playWhenReady && activeCause == null) {+ val cause = pendingCause ?: if (playbackStarted) Cause.REBUFFER else Cause.STARTUP+ pendingCause = null+ activeCause = cause+ startedAtMs = now+ events += Event(cause, Outcome.STARTED, 0L)+ } else if (state == PlaybackState.READY) {+ pendingCause = null+ }+ return events+ }+}diff --git a/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt b/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.ktindex 70314100..38f2971d 100644--- a/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt+++ b/player/src/main/java/com/streamvault/player/stats/PlayerStatsCollector.kt@@ -90,7 +90,12 @@ class PlayerStatsCollector(lastAudioFormat = format}- /** Called by [androidx.media3.exoplayer.analytics.AnalyticsListener] — always on Main. */+ /**+ * Media3 reports batches, so this total can lag DecoderCounters.droppedBufferCount+ * until the renderer reaches its notification threshold or stops. They are overlapping+ * measurements of the same drops; adding the native count would double count them.+ * Called by [androidx.media3.exoplayer.analytics.AnalyticsListener] on Main.+ */fun onDroppedFrames(count: Int) {droppedFrames += count}@@ -116,16 +121,24 @@ class PlayerStatsCollector(* | Data | Interval |* |---|---|* | `currentPosition` / `duration` | Every 250 ms |- * | `bufferedDurationMs` | Every 500 ms (every 2 ticks) |- * | Codec / bitrate / dropped frames | Every 1 000 ms (every 4 ticks) |+ * | `bufferedDurationMs` | Every 500 ms, including requested buffering |+ * | Codec / bitrate / dropped frames | Every 1 000 ms |*/+ fun updatePlaybackActivity(isPlaying: Boolean, playWhenReady: Boolean) {+ if (isPlaying || playWhenReady && playbackState.value == PlaybackState.BUFFERING) {+ start()+ } else {+ stop()+ }+ }+fun start() {- stop()+ if (pollingJob?.isActive == true) returnpollingJob = scopeProvider().launch(Dispatchers.Main.immediate) {- // Initialise to their trigger thresholds so the very first tick emits+ // Initialise to their trigger thresholds so the first poll emits// buffered and stats updates immediately (consistent with player-start UX).- var ticksSinceBufferedUpdate = BUFFERED_UPDATE_TICKS- var ticksSinceStatsUpdate = STATS_UPDATE_TICKS+ var bufferedElapsedMs = BUFFERED_UPDATE_INTERVAL_MS+ var statsElapsedMs = STATS_UPDATE_INTERVAL_MSwhile (isActive) {val player = playerProvider?.invoke()@@ -141,15 +154,14 @@ class PlayerStatsCollector(}// --- Tier 2: Buffered duration (every 500 ms) ------------------- if (ticksSinceBufferedUpdate >= BUFFERED_UPDATE_TICKS) {- val buffered = (player.bufferedPosition - player.currentPosition)- .coerceAtLeast(0L)+ if (bufferedElapsedMs >= BUFFERED_UPDATE_INTERVAL_MS) {+ val buffered = player.totalBufferedDuration.coerceAtLeast(0L)playerStats.value = playerStats.value.copy(bufferedDurationMs = buffered)- ticksSinceBufferedUpdate = 0+ bufferedElapsedMs = 0L}// --- Tier 3: Codec / bitrate / dropped frames (every 1 000 ms) -- if (ticksSinceStatsUpdate >= STATS_UPDATE_TICKS) {+ if (statsElapsedMs >= STATS_UPDATE_INTERVAL_MS) {val video = lastVideoFormatval audio = lastAudioFormatval dropped = droppedFrames@@ -186,13 +198,17 @@ class PlayerStatsCollector(?: playerStats.value.height,bandwidthEstimate = lastBandwidthEstimate)- ticksSinceStatsUpdate = 0+ statsElapsedMs = 0L}}- delay(POSITION_UPDATE_INTERVAL_MS)- ticksSinceBufferedUpdate++- ticksSinceStatsUpdate+++ // During buffering only diagnostics advance; do not poll stalled position at 4 Hz.+ val intervalMs = if (playbackState.value == PlaybackState.BUFFERING) {+ BUFFERED_UPDATE_INTERVAL_MS+ } else POSITION_UPDATE_INTERVAL_MS+ delay(intervalMs)+ bufferedElapsedMs += intervalMs+ statsElapsedMs += intervalMs}}}@@ -206,10 +222,10 @@ class PlayerStatsCollector(/** Base polling interval. All other intervals are multiples of this. */private const val POSITION_UPDATE_INTERVAL_MS = 250L- /** Buffered duration sampled every 2 ticks = 500 ms. */- private const val BUFFERED_UPDATE_TICKS = 2+ /** Buffer diagnostics remain current while position polling is suspended. */+ private const val BUFFERED_UPDATE_INTERVAL_MS = 500L- /** Heavy stats (codec / bitrate / dropped frames) every 4 ticks = 1 000 ms. */- private const val STATS_UPDATE_TICKS = 4+ /** Heavy stats (codec / bitrate / dropped frames) once per second. */+ private const val STATS_UPDATE_INTERVAL_MS = 1_000L}}diff --git a/player/src/main/java/com/streamvault/player/ui/PlayerViewBinder.kt b/player/src/main/java/com/streamvault/player/ui/PlayerViewBinder.ktindex 01a5ca49..bc04d5f0 100644--- a/player/src/main/java/com/streamvault/player/ui/PlayerViewBinder.kt+++ b/player/src/main/java/com/streamvault/player/ui/PlayerViewBinder.kt@@ -4,6 +4,8 @@ import android.content.Contextimport android.graphics.Colorimport android.view.LayoutInflaterimport android.view.View+import android.view.SurfaceView+import android.view.TextureViewimport android.widget.FrameLayoutimport androidx.media3.common.text.Cueimport androidx.media3.ui.AspectRatioFrameLayout@@ -26,6 +28,16 @@ class PlayerViewBinder(private var boundResizeMode: PlayerSurfaceResizeMode = PlayerSurfaceResizeMode.FITprivate var injectedSubtitleCues: List<Cue> = emptyList()+ fun hasUsableVideoOutput(player: androidx.media3.exoplayer.ExoPlayer?): Boolean {+ val view = boundPlayerView ?: return false+ if (player == null || view.player !== player || !view.isAttachedToWindow || !view.isShown) return false+ return when (val output = view.videoSurfaceView) {+ is SurfaceView -> output.holder.surface.isValid+ is TextureView -> output.isAvailable+ else -> false+ }+ }+fun createRenderView(context: Context,resizeMode: PlayerSurfaceResizeMode,diff --git a/player/src/main/res/values-ar/strings.xml b/player/src/main/res/values-ar/strings.xmlnew file mode 100644index 00000000..a40d20f4--- /dev/null+++ b/player/src/main/res/values-ar/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">تعذر بدء التشغيل. جرّب بثًا آخر.</string>+</resources>diff --git a/player/src/main/res/values-bg/strings.xml b/player/src/main/res/values-bg/strings.xmlnew file mode 100644index 00000000..6715f800--- /dev/null+++ b/player/src/main/res/values-bg/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Възпроизвеждането не можа да започне. Опитайте друг поток.</string>+</resources>diff --git a/player/src/main/res/values-cs/strings.xml b/player/src/main/res/values-cs/strings.xmlnew file mode 100644index 00000000..42b05393--- /dev/null+++ b/player/src/main/res/values-cs/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Přehrávání se nepodařilo spustit. Zkuste jiný stream.</string>+</resources>diff --git a/player/src/main/res/values-da/strings.xml b/player/src/main/res/values-da/strings.xmlnew file mode 100644index 00000000..2346bbe9--- /dev/null+++ b/player/src/main/res/values-da/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Afspilningen kunne ikke starte. Prøv en anden stream.</string>+</resources>diff --git a/player/src/main/res/values-de/strings.xml b/player/src/main/res/values-de/strings.xmlnew file mode 100644index 00000000..dac56323--- /dev/null+++ b/player/src/main/res/values-de/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Die Wiedergabe konnte nicht gestartet werden. Versuche einen anderen Stream.</string>+</resources>diff --git a/player/src/main/res/values-el/strings.xml b/player/src/main/res/values-el/strings.xmlnew file mode 100644index 00000000..29c02ed3--- /dev/null+++ b/player/src/main/res/values-el/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Δεν ήταν δυνατή η έναρξη της αναπαραγωγής. Δοκιμάστε άλλη ροή.</string>+</resources>diff --git a/player/src/main/res/values-es/strings.xml b/player/src/main/res/values-es/strings.xmlnew file mode 100644index 00000000..60d763da--- /dev/null+++ b/player/src/main/res/values-es/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">No se pudo iniciar la reproducción. Prueba otra transmisión.</string>+</resources>diff --git a/player/src/main/res/values-fa/strings.xml b/player/src/main/res/values-fa/strings.xmlnew file mode 100644index 00000000..60eec22a--- /dev/null+++ b/player/src/main/res/values-fa/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">پخش شروع نشد. جریان دیگری را امتحان کنید.</string>+</resources>diff --git a/player/src/main/res/values-fi/strings.xml b/player/src/main/res/values-fi/strings.xmlnew file mode 100644index 00000000..b1d063f8--- /dev/null+++ b/player/src/main/res/values-fi/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Toistoa ei voitu aloittaa. Kokeile toista suoratoistoa.</string>+</resources>diff --git a/player/src/main/res/values-fil/strings.xml b/player/src/main/res/values-fil/strings.xmlnew file mode 100644index 00000000..5b677871--- /dev/null+++ b/player/src/main/res/values-fil/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Hindi masimulan ang pag-play. Subukan ang ibang stream.</string>+</resources>diff --git a/player/src/main/res/values-fr/strings.xml b/player/src/main/res/values-fr/strings.xmlnew file mode 100644index 00000000..c52cdaaf--- /dev/null+++ b/player/src/main/res/values-fr/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">La lecture n’a pas pu démarrer. Essayez un autre flux.</string>+</resources>diff --git a/player/src/main/res/values-hi/strings.xml b/player/src/main/res/values-hi/strings.xmlnew file mode 100644index 00000000..2f291c08--- /dev/null+++ b/player/src/main/res/values-hi/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">प्लेबैक शुरू नहीं हो सका। कोई दूसरी स्ट्रीम आज़माएँ।</string>+</resources>diff --git a/player/src/main/res/values-hr/strings.xml b/player/src/main/res/values-hr/strings.xmlnew file mode 100644index 00000000..6e537421--- /dev/null+++ b/player/src/main/res/values-hr/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Reprodukcija se nije mogla pokrenuti. Pokušajte s drugim prijenosom.</string>+</resources>diff --git a/player/src/main/res/values-hu/strings.xml b/player/src/main/res/values-hu/strings.xmlnew file mode 100644index 00000000..1604ad8b--- /dev/null+++ b/player/src/main/res/values-hu/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">A lejátszás nem indult el. Próbáljon másik adatfolyamot.</string>+</resources>diff --git a/player/src/main/res/values-in/strings.xml b/player/src/main/res/values-in/strings.xmlnew file mode 100644index 00000000..2517a6b8--- /dev/null+++ b/player/src/main/res/values-in/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Pemutaran tidak dapat dimulai. Coba siaran lain.</string>+</resources>diff --git a/player/src/main/res/values-it/strings.xml b/player/src/main/res/values-it/strings.xmlnew file mode 100644index 00000000..262c279b--- /dev/null+++ b/player/src/main/res/values-it/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Impossibile avviare la riproduzione. Prova un altro flusso.</string>+</resources>diff --git a/player/src/main/res/values-iw/strings.xml b/player/src/main/res/values-iw/strings.xmlnew file mode 100644index 00000000..56dceb08--- /dev/null+++ b/player/src/main/res/values-iw/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">לא ניתן להתחיל את הניגון. נסו שידור אחר.</string>+</resources>diff --git a/player/src/main/res/values-ja/strings.xml b/player/src/main/res/values-ja/strings.xmlnew file mode 100644index 00000000..a3c1ecf3--- /dev/null+++ b/player/src/main/res/values-ja/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">再生を開始できませんでした。別のストリームをお試しください。</string>+</resources>diff --git a/player/src/main/res/values-ko/strings.xml b/player/src/main/res/values-ko/strings.xmlnew file mode 100644index 00000000..98c20cbe--- /dev/null+++ b/player/src/main/res/values-ko/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">재생을 시작할 수 없습니다. 다른 스트림을 시도해 보세요.</string>+</resources>diff --git a/player/src/main/res/values-mk/strings.xml b/player/src/main/res/values-mk/strings.xmlnew file mode 100644index 00000000..6769fe6a--- /dev/null+++ b/player/src/main/res/values-mk/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Репродукцијата не може да започне. Обидете се со друг пренос.</string>+</resources>diff --git a/player/src/main/res/values-ms/strings.xml b/player/src/main/res/values-ms/strings.xmlnew file mode 100644index 00000000..4a1acb57--- /dev/null+++ b/player/src/main/res/values-ms/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Main balik tidak dapat dimulakan. Cuba strim lain.</string>+</resources>diff --git a/player/src/main/res/values-nb/strings.xml b/player/src/main/res/values-nb/strings.xmlnew file mode 100644index 00000000..de07588c--- /dev/null+++ b/player/src/main/res/values-nb/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Avspillingen kunne ikke starte. Prøv en annen strøm.</string>+</resources>diff --git a/player/src/main/res/values-nl/strings.xml b/player/src/main/res/values-nl/strings.xmlnew file mode 100644index 00000000..24a97ea9--- /dev/null+++ b/player/src/main/res/values-nl/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Het afspelen kon niet starten. Probeer een andere stream.</string>+</resources>diff --git a/player/src/main/res/values-pl/strings.xml b/player/src/main/res/values-pl/strings.xmlnew file mode 100644index 00000000..edf45f02--- /dev/null+++ b/player/src/main/res/values-pl/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Nie udało się rozpocząć odtwarzania. Spróbuj innego strumienia.</string>+</resources>diff --git a/player/src/main/res/values-pt/strings.xml b/player/src/main/res/values-pt/strings.xmlnew file mode 100644index 00000000..e4739d49--- /dev/null+++ b/player/src/main/res/values-pt/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Não foi possível iniciar a reprodução. Experimente outra transmissão.</string>+</resources>diff --git a/player/src/main/res/values-ro/strings.xml b/player/src/main/res/values-ro/strings.xmlnew file mode 100644index 00000000..7322d861--- /dev/null+++ b/player/src/main/res/values-ro/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Redarea nu a putut începe. Încercați alt flux.</string>+</resources>diff --git a/player/src/main/res/values-ru/strings.xml b/player/src/main/res/values-ru/strings.xmlnew file mode 100644index 00000000..3d5bb530--- /dev/null+++ b/player/src/main/res/values-ru/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Не удалось начать воспроизведение. Попробуйте другой поток.</string>+</resources>diff --git a/player/src/main/res/values-sk/strings.xml b/player/src/main/res/values-sk/strings.xmlnew file mode 100644index 00000000..3c3af55f--- /dev/null+++ b/player/src/main/res/values-sk/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Prehrávanie sa nepodarilo spustiť. Skúste iný stream.</string>+</resources>diff --git a/player/src/main/res/values-sq/strings.xml b/player/src/main/res/values-sq/strings.xmlnew file mode 100644index 00000000..4029c0f7--- /dev/null+++ b/player/src/main/res/values-sq/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Riprodhimi nuk mund të fillonte. Provoni një transmetim tjetër.</string>+</resources>diff --git a/player/src/main/res/values-sr/strings.xml b/player/src/main/res/values-sr/strings.xmlnew file mode 100644index 00000000..8cce2c31--- /dev/null+++ b/player/src/main/res/values-sr/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Репродукција није могла да почне. Покушајте са другим стримом.</string>+</resources>diff --git a/player/src/main/res/values-sv/strings.xml b/player/src/main/res/values-sv/strings.xmlnew file mode 100644index 00000000..ded3a2ae--- /dev/null+++ b/player/src/main/res/values-sv/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Uppspelningen kunde inte starta. Prova en annan ström.</string>+</resources>diff --git a/player/src/main/res/values-th/strings.xml b/player/src/main/res/values-th/strings.xmlnew file mode 100644index 00000000..29b411bf--- /dev/null+++ b/player/src/main/res/values-th/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">ไม่สามารถเริ่มเล่นได้ โปรดลองสตรีมอื่น</string>+</resources>diff --git a/player/src/main/res/values-tr/strings.xml b/player/src/main/res/values-tr/strings.xmlnew file mode 100644index 00000000..b60ed144--- /dev/null+++ b/player/src/main/res/values-tr/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Oynatma başlatılamadı. Başka bir yayın deneyin.</string>+</resources>diff --git a/player/src/main/res/values-uk/strings.xml b/player/src/main/res/values-uk/strings.xmlnew file mode 100644index 00000000..313ad704--- /dev/null+++ b/player/src/main/res/values-uk/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Не вдалося почати відтворення. Спробуйте інший потік.</string>+</resources>diff --git a/player/src/main/res/values-vi/strings.xml b/player/src/main/res/values-vi/strings.xmlnew file mode 100644index 00000000..32d69025--- /dev/null+++ b/player/src/main/res/values-vi/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Không thể bắt đầu phát. Hãy thử luồng khác.</string>+</resources>diff --git a/player/src/main/res/values-zh-rTW/strings.xml b/player/src/main/res/values-zh-rTW/strings.xmlnew file mode 100644index 00000000..accade6d--- /dev/null+++ b/player/src/main/res/values-zh-rTW/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">無法開始播放。請嘗試其他串流。</string>+</resources>diff --git a/player/src/main/res/values-zh/strings.xml b/player/src/main/res/values-zh/strings.xmlnew file mode 100644index 00000000..7274ee38--- /dev/null+++ b/player/src/main/res/values-zh/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">无法开始播放。请尝试其他直播流。</string>+</resources>diff --git a/player/src/main/res/values/strings.xml b/player/src/main/res/values/strings.xmlnew file mode 100644index 00000000..fec75a50--- /dev/null+++ b/player/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="player_error_live_startup_timeout">Playback could not start. Try another stream.</string>+</resources>diff --git a/player/src/test/java/com/streamvault/player/playback/AvcAccessUnitExtractorsFactoryTest.kt b/player/src/test/java/com/streamvault/player/playback/AvcAccessUnitExtractorsFactoryTest.ktnew file mode 100644index 00000000..4fe94a09--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/AvcAccessUnitExtractorsFactoryTest.kt@@ -0,0 +1,72 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import android.net.Uri+import androidx.media3.common.util.TimestampAdjuster+import androidx.media3.extractor.DefaultExtractorsFactory+import androidx.media3.extractor.Extractor+import androidx.media3.extractor.ExtractorInput+import androidx.media3.extractor.ExtractorOutput+import androidx.media3.extractor.ExtractorsFactory+import androidx.media3.extractor.PositionHolder+import androidx.media3.extractor.ts.DefaultTsPayloadReaderFactory+import androidx.media3.extractor.ts.TsExtractor+import androidx.media3.extractor.text.SubtitleParser+import com.google.common.truth.Truth.assertThat+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class AvcAccessUnitExtractorsFactoryTest {++ @Test+ fun `wraps TS extractors and preserves non TS extractor instances`() {+ val nonTs = PassthroughExtractor()+ val ts = TsExtractor(+ TsExtractor.MODE_SINGLE_PMT,+ TsExtractor.FLAG_EMIT_RAW_SUBTITLE_DATA,+ SubtitleParser.Factory.UNSUPPORTED,+ TimestampAdjuster(0),+ DefaultTsPayloadReaderFactory(+ DefaultTsPayloadReaderFactory.FLAG_DETECT_ACCESS_UNITS or+ DefaultTsPayloadReaderFactory.FLAG_ALLOW_NON_IDR_KEYFRAMES or+ DefaultTsPayloadReaderFactory.FLAG_IGNORE_SPLICE_INFO_STREAM+ ),+ TsExtractor.DEFAULT_TIMESTAMP_SEARCH_BYTES+ )+ val upstream = FixedExtractorsFactory(arrayOf(nonTs, ts))++ val wrapped = AvcAccessUnitExtractorsFactory(upstream).createExtractors()++ assertThat(wrapped).hasLength(2)+ assertThat(wrapped[0]).isSameInstanceAs(nonTs)+ assertThat(wrapped[1]).isNotSameInstanceAs(ts)+ assertThat((wrapped[1] as androidx.media3.extractor.ForwardingExtractor).underlyingImplementation)+ .isSameInstanceAs(ts)+ }++ @Test+ fun `unnormalized factory path leaves TS extractor direct`() {+ val extractors = liveMpegTsExtractorsFactory(normalizeAvcSamples = false).createExtractors()++ assertThat(extractors.none { it.javaClass.simpleName == "AvcAccessUnitExtractor" }).isTrue()+ assertThat(extractors.any { it is TsExtractor }).isTrue()+ }++ private class FixedExtractorsFactory(private val extractors: Array<Extractor>) : ExtractorsFactory {+ override fun createExtractors(): Array<Extractor> = extractors++ override fun createExtractors(uri: Uri, responseHeaders: Map<String, List<String>>): Array<Extractor> =+ extractors+ }++ private class PassthroughExtractor : Extractor {+ override fun sniff(input: ExtractorInput): Boolean = false+ override fun init(output: ExtractorOutput) = Unit+ override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int = Extractor.RESULT_END_OF_INPUT+ override fun seek(position: Long, timeUs: Long) = Unit+ override fun release() = Unit+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/AvcAccessUnitTrackOutputTest.kt b/player/src/test/java/com/streamvault/player/playback/AvcAccessUnitTrackOutputTest.ktnew file mode 100644index 00000000..da075b56--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/AvcAccessUnitTrackOutputTest.kt@@ -0,0 +1,343 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import androidx.media3.common.C+import androidx.media3.common.DataReader+import androidx.media3.common.DrmInitData+import androidx.media3.common.Format+import androidx.media3.common.MimeTypes+import androidx.media3.common.util.ParsableByteArray+import androidx.media3.extractor.TrackOutput+import com.google.common.truth.Truth.assertThat+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class AvcAccessUnitTrackOutputTest {++ @Test+ fun `holds AUD SPS PPS and SEI samples and merges their bytes and flags into following VCL`() {+ val delegate = RecordingTrackOutput()+ val output = AvcAccessUnitTrackOutput(delegate)+ output.format(avcFormat())+ val headers = listOf(+ annexB(9, 0xf0),+ annexB3(7, 0x11, 0x12),+ annexB(8, 0x21),+ annexB3(6, 0x31, 0x32)+ )+ headers.forEachIndexed { index, bytes ->+ writeSample(output, bytes, timeUs = 10_000L + index, flags = if (index == 0) OTHER_FLAG else 0)+ }++ assertThat(delegate.samples).isEmpty()++ val picture = annexB(5, 0x41, 0x42, 0x43)+ writeSample(output, picture, timeUs = 33_333L, flags = C.BUFFER_FLAG_KEY_FRAME)++ assertThat(delegate.samples).hasSize(1)+ assertSample(+ delegate.samples.single(),+ bytes = headers.fold(byteArrayOf()) { all, next -> all + next } + picture,+ timeUs = 33_333L,+ flags = OTHER_FLAG or C.BUFFER_FLAG_KEY_FRAME+ )+ }++ @Test+ fun `keeps separate VCL samples even when their timestamps are equal`() {+ val delegate = RecordingTrackOutput()+ val output = AvcAccessUnitTrackOutput(delegate)+ output.format(avcFormat())+ val first = annexB(5, 0x51, 0x52)+ val second = annexB3(1, 0x61, 0x62)++ writeSample(output, first, timeUs = 90_000L, flags = C.BUFFER_FLAG_KEY_FRAME)+ writeSample(output, second, timeUs = 90_000L, flags = 0)++ assertThat(delegate.samples).hasSize(2)+ assertSample(delegate.samples[0], first, 90_000L, C.BUFFER_FLAG_KEY_FRAME)+ assertSample(delegate.samples[1], second, 90_000L, 0)+ }++ @Test+ fun `delivers VCL without AUD immediately`() {+ val delegate = RecordingTrackOutput()+ val output = AvcAccessUnitTrackOutput(delegate)+ output.format(avcFormat())+ val picture = annexB3(1, 0x71, 0x72)++ writeSample(output, picture, timeUs = 123_000L)++ assertThat(delegate.samples).hasSize(1)+ assertSample(delegate.samples.single(), picture, 123_000L, 0)+ }++ @Test+ fun `recognizes split three and four byte prefixes written before format`() {+ val delegate = RecordingTrackOutput()+ val output = AvcAccessUnitTrackOutput(delegate)+ val aud = annexB3(9, 0xf0)+ val split = 2+ output.sampleData(ParsableByteArray(aud.copyOfRange(0, split)), split)+ output.sampleData(ParsableByteArray(aud.copyOfRange(split, aud.size)), aud.size - split)+ output.format(avcFormat())+ output.sampleMetadata(0L, 0, aud.size, 0, null)+ val picture = annexB(5, 0x01, 0x02)++ assertThat(delegate.samples).isEmpty()+ writeSample(output, picture, timeUs = 40_000L, flags = C.BUFFER_FLAG_KEY_FRAME)++ assertThat(delegate.samples).hasSize(1)+ assertSample(delegate.samples.single(), aud + picture, 40_000L, C.BUFFER_FLAG_KEY_FRAME)+ }++ @Test+ fun `uses metadata size and offset when sample data is written ahead`() {+ val delegate = RecordingTrackOutput()+ val output = AvcAccessUnitTrackOutput(delegate)+ output.format(avcFormat())+ val prefix = annexB(9, 0xf0)+ val firstPicture = annexB3(5, 0x11, 0x12)+ val secondPicture = annexB(1, 0x21, 0x22, 0x23)+ val trailing = byteArrayOf(0x55, 0x66)+ val writtenAhead = prefix + firstPicture + secondPicture + trailing+ output.sampleData(ParsableByteArray(writtenAhead), writtenAhead.size)++ output.sampleMetadata(+ 0L,+ OTHER_FLAG,+ prefix.size,+ writtenAhead.size - prefix.size,+ null+ )+ output.sampleMetadata(+ 33_333L,+ C.BUFFER_FLAG_KEY_FRAME,+ firstPicture.size,+ secondPicture.size + trailing.size,+ null+ )+ output.sampleMetadata(33_333L, 0, secondPicture.size, trailing.size, null)++ assertThat(delegate.samples).hasSize(2)+ assertSample(+ delegate.samples[0],+ prefix + firstPicture,+ 33_333L,+ OTHER_FLAG or C.BUFFER_FLAG_KEY_FRAME+ )+ assertSample(delegate.samples[1], secondPicture, 33_333L, 0)+ }++ @Test+ fun `reset discards pending headers and prevents cross seek merge`() {+ val delegate = RecordingTrackOutput()+ val output = AvcAccessUnitTrackOutput(delegate)+ output.format(avcFormat())+ val header = annexB(9, 0xf0)+ val picture = annexB3(1, 0x31, 0x32)+ writeSample(output, header, timeUs = 100_000L)++ output.reset()+ writeSample(output, picture, timeUs = 0L)++ assertThat(delegate.samples).hasSize(1)+ assertSample(delegate.samples.single(), picture, 0L, 0)+ }++ @Test+ fun `passes non AVC and DRM crypto samples through unchanged`() {+ val nonAvcDelegate = RecordingTrackOutput()+ val nonAvc = AvcAccessUnitTrackOutput(nonAvcDelegate)+ nonAvc.format(Format.Builder().setSampleMimeType(MimeTypes.VIDEO_H265).build())+ val h265LikeHeader = annexB(9, 0xf0)+ val h265LikePicture = annexB3(1, 0x31)+ writeSample(nonAvc, h265LikeHeader, 10_000L)+ writeSample(nonAvc, h265LikePicture, 10_000L)+ assertThat(nonAvcDelegate.samples).hasSize(2)+ assertSample(nonAvcDelegate.samples[0], h265LikeHeader, 10_000L, 0)+ assertSample(nonAvcDelegate.samples[1], h265LikePicture, 10_000L, 0)++ val drmDelegate = RecordingTrackOutput()+ val drmOutput = AvcAccessUnitTrackOutput(drmDelegate)+ drmOutput.format(avcFormat().buildUpon().setDrmInitData(DrmInitData("cenc", emptyList())).build())+ val key = ByteArray(16) { it.toByte() }+ val crypto = TrackOutput.CryptoData(C.CRYPTO_MODE_AES_CTR, key, 0, 0)+ val encryptedHeaderNal = annexB(9, 0xf0)+ writeSample(drmOutput, encryptedHeaderNal, 20_000L, flags = 0, cryptoData = crypto)++ assertThat(drmDelegate.samples).hasSize(1)+ assertSample(drmDelegate.samples.single(), encryptedHeaderNal, 20_000L, 0)+ assertThat(drmDelegate.samples.single().cryptoData).isSameInstanceAs(crypto)+ }++ @Test+ fun `clear AVC format with crypto metadata flushes prefix and preserves encrypted sample`() {+ val delegate = RecordingTrackOutput()+ val output = AvcAccessUnitTrackOutput(delegate)+ output.format(avcFormat())+ val prefix = annexB(9, 0xf0)+ val encryptedPicture = annexB3(5, 0x25, 0x26)+ val followingPrefix = annexB3(9, 0xf0)+ val followingPicture = annexB(1, 0x27, 0x28)+ val crypto = TrackOutput.CryptoData(C.CRYPTO_MODE_AES_CTR, ByteArray(16) { it.toByte() }, 0, 0)++ writeSample(output, prefix, timeUs = 10_000L, flags = OTHER_FLAG)+ writeSample(output, encryptedPicture, timeUs = 33_333L, flags = C.BUFFER_FLAG_KEY_FRAME, cryptoData = crypto)+ writeSample(output, followingPrefix, timeUs = 40_000L, flags = OTHER_FLAG)+ writeSample(output, followingPicture, timeUs = 66_666L)++ assertThat(delegate.samples).hasSize(4)+ assertSample(delegate.samples[0], prefix, 10_000L, OTHER_FLAG)+ assertSample(delegate.samples[1], encryptedPicture, 33_333L, C.BUFFER_FLAG_KEY_FRAME)+ assertThat(delegate.samples[1].cryptoData).isSameInstanceAs(crypto)+ assertSample(delegate.samples[2], followingPrefix, 40_000L, OTHER_FLAG)+ assertSample(delegate.samples[3], followingPicture, 66_666L, 0)+ }++ @Test+ fun `opaque DataReader path flushes prefix and preserves byte order`() {+ val delegate = RecordingTrackOutput()+ val output = AvcAccessUnitTrackOutput(delegate)+ output.format(avcFormat())+ val prefix = annexB(9, 0xf0)+ val picture = annexB3(1, 0x35, 0x36)+ writeSample(output, prefix, timeUs = 10_000L, flags = OTHER_FLAG)++ val input = ByteArrayInputStream(picture)+ val reader = DataReader { target, offset, length -> input.read(target, offset, length) }+ assertThat(output.sampleData(reader, picture.size, false, TrackOutput.SAMPLE_DATA_PART_MAIN)).isEqualTo(picture.size)+ output.sampleMetadata(33_333L, C.BUFFER_FLAG_KEY_FRAME, picture.size, 0, null)++ assertThat(delegate.samples).hasSize(2)+ assertSample(delegate.samples[0], prefix, 10_000L, OTHER_FLAG)+ assertSample(delegate.samples[1], picture, 33_333L, C.BUFFER_FLAG_KEY_FRAME)+ }++ @Test+ fun `byte sample and NAL marker limits fall back to original metadata`() {+ val header = annexB(9, 0xf0)+ val picture = annexB3(1, 0x31, 0x32)++ val byteLimitedDelegate = RecordingTrackOutput()+ val byteLimited = AvcAccessUnitTrackOutput(+ delegate = byteLimitedDelegate,+ maxPendingHeaderBytes = header.size - 1+ )+ byteLimited.format(avcFormat())+ writeSample(byteLimited, header, 10_000L, flags = OTHER_FLAG)+ writeSample(byteLimited, picture, 33_333L, flags = C.BUFFER_FLAG_KEY_FRAME)+ assertThat(byteLimitedDelegate.samples).hasSize(2)+ assertSample(byteLimitedDelegate.samples[0], header, 10_000L, OTHER_FLAG)+ assertSample(byteLimitedDelegate.samples[1], picture, 33_333L, C.BUFFER_FLAG_KEY_FRAME)++ val sampleLimitedDelegate = RecordingTrackOutput()+ val sampleLimited = AvcAccessUnitTrackOutput(+ delegate = sampleLimitedDelegate,+ maxPendingHeaderSamples = 1+ )+ sampleLimited.format(avcFormat())+ val secondHeader = annexB3(6, 0x41)+ writeSample(sampleLimited, header, 10_000L)+ writeSample(sampleLimited, secondHeader, 10_001L)+ writeSample(sampleLimited, picture, 33_333L)+ assertThat(sampleLimitedDelegate.samples).hasSize(3)+ assertSample(sampleLimitedDelegate.samples[0], header, 10_000L, 0)+ assertSample(sampleLimitedDelegate.samples[1], secondHeader, 10_001L, 0)+ assertSample(sampleLimitedDelegate.samples[2], picture, 33_333L, 0)++ val markerLimitedDelegate = RecordingTrackOutput()+ val markerLimited = AvcAccessUnitTrackOutput(+ delegate = markerLimitedDelegate,+ maxNalMarkers = 1+ )+ markerLimited.format(avcFormat())+ val twoHeaders = annexB(9, 0xf0) + annexB3(6, 0x51)+ writeSample(markerLimited, twoHeaders, 10_000L)+ writeSample(markerLimited, picture, 33_333L)+ assertThat(markerLimitedDelegate.samples).hasSize(2)+ assertSample(markerLimitedDelegate.samples[0], twoHeaders, 10_000L, 0)+ assertSample(markerLimitedDelegate.samples[1], picture, 33_333L, 0)+ }++ private fun avcFormat() = Format.Builder().setSampleMimeType(MimeTypes.VIDEO_H264).build()++ private fun writeSample(+ output: TrackOutput,+ bytes: ByteArray,+ timeUs: Long,+ flags: Int = 0,+ cryptoData: TrackOutput.CryptoData? = null+ ) {+ output.sampleData(ParsableByteArray(bytes), bytes.size)+ output.sampleMetadata(timeUs, flags, bytes.size, 0, cryptoData)+ }++ private fun assertSample(sample: CapturedSample, bytes: ByteArray, timeUs: Long, flags: Int) {+ assertThat(sample.bytes.toList()).isEqualTo(bytes.toList())+ assertThat(sample.timeUs).isEqualTo(timeUs)+ assertThat(sample.flags).isEqualTo(flags)+ }++ private fun annexB(type: Int, vararg payload: Int) =+ byteArrayOf(0, 0, 0, 1, type.toByte()) + payload.map(Int::toByte).toByteArray()++ private fun annexB3(type: Int, vararg payload: Int) =+ byteArrayOf(0, 0, 1, type.toByte()) + payload.map(Int::toByte).toByteArray()++ private data class CapturedSample(+ val bytes: ByteArray,+ val timeUs: Long,+ val flags: Int,+ val cryptoData: TrackOutput.CryptoData?+ )++ private class RecordingTrackOutput : TrackOutput {+ private val pending = ByteArrayOutputStream()+ val samples = mutableListOf<CapturedSample>()++ override fun format(format: Format) = Unit++ override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int {+ val bytes = ByteArray(length)+ val count = input.read(bytes, 0, length)+ if (count == C.RESULT_END_OF_INPUT && allowEndOfInput) return C.RESULT_END_OF_INPUT+ if (count < 0) throw java.io.EOFException()+ pending.write(bytes, 0, count)+ return count+ }++ override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {+ pending.write(data.data, data.position, length)+ data.skipBytes(length)+ }++ override fun sampleMetadata(+ timeUs: Long,+ flags: Int,+ size: Int,+ offset: Int,+ cryptoData: TrackOutput.CryptoData?+ ) {+ val written = pending.toByteArray()+ val start = written.size - offset - size+ check(start >= 0 && start + size <= written.size) {+ "Invalid sample boundary size=$size offset=$offset available=${written.size}"+ }+ val sampleBytes = written.copyOfRange(start, start + size)+ val trailing = written.copyOfRange(start + size, written.size)+ pending.reset()+ if (trailing.isNotEmpty()) pending.write(trailing)+ samples += CapturedSample(sampleBytes, timeUs, flags, cryptoData)+ }+ }++ private companion object {+ const val OTHER_FLAG = 0x20+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/HlsRenditionLoadingPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/HlsRenditionLoadingPolicyTest.ktnew file mode 100644index 00000000..647c1433--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/HlsRenditionLoadingPolicyTest.kt@@ -0,0 +1,260 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import androidx.media3.common.C+import androidx.media3.exoplayer.LoadingInfo+import androidx.media3.exoplayer.source.DefaultCompositeSequenceableLoaderFactory+import androidx.media3.exoplayer.source.SequenceableLoader+import com.google.common.truth.Truth.assertThat+import org.junit.Test++class HlsRenditionLoadingPolicyTest {++ @Test+ fun `busy text loader pins Media3 default but live policy lets video continue`() {+ val defaultText = FakeLoader(nextUs = 2 * SECOND_US, loading = true)+ val defaultVideo = FakeLoader(nextUs = 4 * SECOND_US) { loader ->+ if (loader.nextUs < 6 * SECOND_US) {+ loader.nextUs += 2 * SECOND_US+ true+ } else false+ }+ val default = DefaultCompositeSequenceableLoaderFactory().create(+ listOf(defaultVideo, defaultText),+ listOf(listOf(C.TRACK_TYPE_VIDEO), listOf(C.TRACK_TYPE_TEXT))+ )++ assertThat(default.nextLoadPositionUs).isEqualTo(2 * SECOND_US)+ default.continueLoading(loadingInfo())+ assertThat(defaultVideo.continueCalls).isEmpty()++ val policyText = FakeLoader(nextUs = 2 * SECOND_US, loading = true)+ val policyVideo = FakeLoader(nextUs = 4 * SECOND_US) { loader ->+ if (loader.nextUs < 6 * SECOND_US) {+ loader.nextUs += 2 * SECOND_US+ true+ } else false+ }+ val policy = InFlightOptionalRenditionLoaderFactory().create(+ listOf(policyVideo, policyText),+ listOf(listOf(C.TRACK_TYPE_VIDEO), listOf(C.TRACK_TYPE_TEXT))+ )++ assertThat(policy.nextLoadPositionUs).isEqualTo(4 * SECOND_US)+ policy.continueLoading(loadingInfo())++ assertThat(policyVideo.continueCalls).containsExactly(4 * SECOND_US, 6 * SECOND_US).inOrder()+ assertThat(policyText.continueCalls).isEmpty()+ assertThat(policy.nextLoadPositionUs).isEqualTo(6 * SECOND_US)+ }++ @Test+ fun `nonloading text rendition retains normal catchup without exceeding loader budget`() {+ val text = FakeLoader(nextUs = 4 * SECOND_US, maxLoadPositionUs = 6 * SECOND_US)+ val video = FakeLoader(nextUs = 2 * SECOND_US, maxLoadPositionUs = 6 * SECOND_US)+ val loader = policy(video, text)++ loader.continueLoading(loadingInfo())++ assertThat(text.continueCalls).isNotEmpty()+ assertThat(video.continueCalls)+ .containsAtLeast(2 * SECOND_US, 4 * SECOND_US)+ assertThat((video.continueCalls + text.continueCalls).max()).isAtMost(6 * SECOND_US)+ }++ @Test+ fun `text rendition becoming busy during continue does not extend av load budget`() {+ val video = FakeLoader(nextUs = 10 * SECOND_US) { loader ->+ loader.nextUs += 2 * SECOND_US+ true+ }+ val text = FakeLoader(nextUs = 2 * SECOND_US) { loader ->+ loader.nextUs = 4 * SECOND_US+ loader.loading = true+ true+ }+ val loader = policy(video, text)++ loader.continueLoading(loadingInfo())++ assertThat(video.continueCalls).isEmpty()+ assertThat(text.continueCalls).contains(2 * SECOND_US)+ assertThat(loader.nextLoadPositionUs).isEqualTo(10 * SECOND_US)++ text.loading = false++ assertThat(loader.nextLoadPositionUs).isEqualTo(4 * SECOND_US)+ }++ @Test+ fun `inflight audio video loaders remain coupled`() {+ val video = FakeLoader(nextUs = 2 * SECOND_US, loading = true)+ val audio = FakeLoader(nextUs = 4 * SECOND_US)+ val text = FakeLoader(nextUs = SECOND_US, loading = true)+ val loader = InFlightOptionalRenditionLoaderFactory().create(+ listOf(video, audio, text),+ listOf(+ listOf(C.TRACK_TYPE_VIDEO),+ listOf(C.TRACK_TYPE_AUDIO),+ listOf(C.TRACK_TYPE_TEXT)+ )+ )++ assertThat(loader.nextLoadPositionUs).isEqualTo(2 * SECOND_US)+ loader.continueLoading(loadingInfo())++ assertThat(video.continueCalls).containsExactly(2 * SECOND_US)+ assertThat(audio.continueCalls).isEmpty()+ assertThat(text.continueCalls).isEmpty()+ }++ @Test+ fun `inflight metadata rendition does not pin live video loading`() {+ val video = FakeLoader(nextUs = 4 * SECOND_US) { loader ->+ if (loader.nextUs < 6 * SECOND_US) {+ loader.nextUs += 2 * SECOND_US+ true+ } else false+ }+ val metadata = FakeLoader(nextUs = 2 * SECOND_US, loading = true)+ val loader = InFlightOptionalRenditionLoaderFactory().create(+ listOf(video, metadata),+ listOf(listOf(C.TRACK_TYPE_VIDEO), listOf(C.TRACK_TYPE_METADATA))+ )++ assertThat(loader.nextLoadPositionUs).isEqualTo(4 * SECOND_US)+ loader.continueLoading(loadingInfo())++ assertThat(video.continueCalls).contains(4 * SECOND_US)+ assertThat(metadata.continueCalls).isEmpty()+ }++ @Test+ fun `unknown mixed and image loaders are not classified as optional`() {+ val primaryVideo = FakeLoader(nextUs = 8 * SECOND_US)+ val busyText = FakeLoader(nextUs = SECOND_US, loading = true)+ val unknown = FakeLoader(nextUs = 3 * SECOND_US) { false }+ val mixed = FakeLoader(nextUs = 5 * SECOND_US, loading = true)+ val image = FakeLoader(nextUs = 6 * SECOND_US)+ val loaders = listOf(primaryVideo, busyText, unknown, mixed, image)+ val types = listOf(+ listOf(C.TRACK_TYPE_VIDEO),+ listOf(C.TRACK_TYPE_TEXT),+ listOf(C.TRACK_TYPE_UNKNOWN),+ listOf(C.TRACK_TYPE_VIDEO, C.TRACK_TYPE_TEXT),+ listOf(C.TRACK_TYPE_IMAGE)+ )+ val loader = InFlightOptionalRenditionLoaderFactory().create(loaders, types)++ assertThat(loader.nextLoadPositionUs).isEqualTo(3 * SECOND_US)+ loader.continueLoading(loadingInfo())++ assertThat(busyText.continueCalls).isEmpty()+ assertThat(primaryVideo.continueCalls).isEmpty()+ assertThat(unknown.continueCalls).containsExactly(3 * SECOND_US)+ assertThat(mixed.continueCalls).isEmpty()+ assertThat(image.continueCalls).isEmpty()+ }++ @Test+ fun `active primary end of source falls back to aggregate including optional loader`() {+ val video = FakeLoader(nextUs = C.TIME_END_OF_SOURCE)+ val text = FakeLoader(nextUs = 2 * SECOND_US, loading = true)+ val loader = policy(video, text)++ assertThat(loader.nextLoadPositionUs).isEqualTo(2 * SECOND_US)+ loader.continueLoading(loadingInfo())++ assertThat(text.continueCalls).containsExactly(2 * SECOND_US)+ assertThat(loader.nextLoadPositionUs).isEqualTo(2 * SECOND_US)+ }++ @Test+ fun `empty and text-only factories retain default aggregate behavior`() {+ val factory = InFlightOptionalRenditionLoaderFactory()+ val empty = factory.create(emptyList(), emptyList())+ val text = FakeLoader(nextUs = 3 * SECOND_US, loading = true)+ val textOnly = factory.create(listOf(text), listOf(listOf(C.TRACK_TYPE_TEXT)))++ assertThat(empty.nextLoadPositionUs).isEqualTo(C.TIME_END_OF_SOURCE)+ assertThat(empty.bufferedPositionUs).isEqualTo(C.TIME_END_OF_SOURCE)+ assertThat(empty.isLoading).isFalse()+ assertThat(textOnly.nextLoadPositionUs).isEqualTo(3 * SECOND_US)+ }++ @Test+ fun `aggregate buffer loading and reevaluation behavior remains delegated`() {+ val video = FakeLoader(+ nextUs = 5 * SECOND_US,+ bufferedUs = 7 * SECOND_US,+ loading = true+ )+ val text = FakeLoader(+ nextUs = 2 * SECOND_US,+ bufferedUs = 4 * SECOND_US,+ loading = true+ )+ val default = DefaultCompositeSequenceableLoaderFactory().create(+ listOf(video, text),+ listOf(listOf(C.TRACK_TYPE_VIDEO), listOf(C.TRACK_TYPE_TEXT))+ )+ val videoForPolicy = FakeLoader(nextUs = 5 * SECOND_US, bufferedUs = 7 * SECOND_US, loading = true)+ val textForPolicy = FakeLoader(nextUs = 2 * SECOND_US, bufferedUs = 4 * SECOND_US, loading = true)+ val policy = policy(videoForPolicy, textForPolicy)++ assertThat(policy.bufferedPositionUs).isEqualTo(default.bufferedPositionUs)+ assertThat(policy.isLoading).isEqualTo(default.isLoading)+ policy.reevaluateBuffer(6 * SECOND_US)++ assertThat(videoForPolicy.reevaluatedAtUs).containsExactly(6 * SECOND_US)+ assertThat(textForPolicy.reevaluatedAtUs).containsExactly(6 * SECOND_US)+ }++ private fun policy(video: FakeLoader, text: FakeLoader): SequenceableLoader =+ InFlightOptionalRenditionLoaderFactory().create(+ listOf(video, text),+ listOf(listOf(C.TRACK_TYPE_VIDEO), listOf(C.TRACK_TYPE_TEXT))+ )++ private fun loadingInfo(positionUs: Long = 0L): LoadingInfo = LoadingInfo.Builder()+ .setPlaybackPositionUs(positionUs)+ .setPlaybackSpeed(1f)+ .setLastRebufferRealtimeMs(C.TIME_UNSET)+ .build()++ private class FakeLoader(+ var nextUs: Long,+ private val maxLoadPositionUs: Long = Long.MAX_VALUE,+ var bufferedUs: Long = nextUs,+ var loading: Boolean = false,+ private val action: ((FakeLoader) -> Boolean)? = null+ ) : SequenceableLoader {+ val continueCalls = mutableListOf<Long>()+ val reevaluatedAtUs = mutableListOf<Long>()++ override fun getBufferedPositionUs(): Long = bufferedUs++ override fun getNextLoadPositionUs(): Long = nextUs++ override fun continueLoading(loadingInfo: LoadingInfo): Boolean {+ continueCalls += nextUs+ if (loading) return false+ action?.let { return it(this) }+ if (nextUs >= maxLoadPositionUs || nextUs == C.TIME_END_OF_SOURCE) return false+ nextUs = minOf(nextUs + 2 * SECOND_US, maxLoadPositionUs)+ bufferedUs = maxOf(bufferedUs, nextUs)+ return true+ }++ override fun isLoading(): Boolean = loading++ override fun reevaluateBuffer(positionUs: Long) {+ reevaluatedAtUs += positionUs+ }+ }++ private companion object {+ const val SECOND_US = 1_000_000L+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/HlsTimestampInitializationPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/HlsTimestampInitializationPolicyTest.ktnew file mode 100644index 00000000..bbf4820c--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/HlsTimestampInitializationPolicyTest.kt@@ -0,0 +1,82 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import androidx.media3.exoplayer.hls.HlsMediaSource+import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.PlaybackContentKind+import com.streamvault.domain.model.StreamInfo+import com.streamvault.domain.model.StreamType+import java.io.IOException+import java.util.concurrent.TimeoutException+import okhttp3.OkHttpClient+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class HlsTimestampInitializationPolicyTest {+ @Test+ fun `foreground and preload use same live wait and preserve finite defaults`() {+ val provider = PlayerDataSourceFactoryProvider(+ RuntimeEnvironment.getApplication(), OkHttpClient()+ )+ val sourceFactory = PlayerMediaSourceFactory(provider)+ for (kind in PlaybackContentKind.entries) {+ for (preload in listOf(false, true)) {+ val info = StreamInfo(+ url = "https://example.test/master.m3u8",+ streamType = StreamType.HLS,+ playbackContentKind = kind+ )+ val context = PlaybackRetryContext(+ ResolvedStreamType.HLS,+ PlayerTimeoutProfile.resolve(info, ResolvedStreamType.HLS, preload),+ kind+ )+ val factory = sourceFactory.createMediaSourceFactory(+ info, ResolvedStreamType.HLS, PlayerRetryPolicy(context) { false },+ preload = preload+ ).second as HlsMediaSource.Factory+ assertThat(waitMs(factory)).isEqualTo(expectedWait(kind))+ }+ }+ }++ @Test+ fun `direct hls factory policy covers tv input and resets finite reuse`() {+ val provider = PlayerDataSourceFactoryProvider(+ RuntimeEnvironment.getApplication(), OkHttpClient()+ )+ val info = StreamInfo("https://example.test/master.m3u8", streamType = StreamType.HLS)+ val dataSourceFactory = provider.createFactory(info, ResolvedStreamType.HLS).second+ val factory = HlsMediaSource.Factory(dataSourceFactory)+ for (kind in listOf(PlaybackContentKind.LIVE, PlaybackContentKind.ON_DEMAND,+ PlaybackContentKind.UNKNOWN, PlaybackContentKind.CATCH_UP)) {+ assertThat(factory.applyPlaybackTimestampInitializationPolicy(kind)).isSameInstanceAs(factory)+ assertThat(waitMs(factory)).isEqualTo(expectedWait(kind))+ }+ }++ @Test+ fun `recognition requires typed dependency failure and its exact library prefix`() {+ assertThat(isHlsTimestampInitializationTimeout(IOException(TimeoutException(+ "TimestampAdjuster failed to initialize in 30000 milliseconds"+ )))).isTrue()+ assertThat(isHlsTimestampInitializationTimeout(IOException(TimeoutException("other wait")))).isFalse()+ assertThat(isHlsTimestampInitializationTimeout(IOException(+ "TimestampAdjuster failed to initialize in 30000 milliseconds"+ ))).isFalse()+ assertThat(isHlsTimestampInitializationTimeout(TimeoutException())).isFalse()+ }++ private fun expectedWait(kind: PlaybackContentKind) = when (kind) {+ PlaybackContentKind.LIVE, PlaybackContentKind.UNKNOWN -> 30_000L+ PlaybackContentKind.ON_DEMAND, PlaybackContentKind.CATCH_UP -> 0L+ }++ private fun waitMs(factory: HlsMediaSource.Factory): Long =+ HlsMediaSource.Factory::class.java.getDeclaredField("timestampAdjusterInitializationTimeoutMs")+ .apply { isAccessible = true }.getLong(factory)+}diff --git a/player/src/test/java/com/streamvault/player/playback/HlsTimestampRetryPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/HlsTimestampRetryPolicyTest.ktnew file mode 100644index 00000000..fabd456d--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/HlsTimestampRetryPolicyTest.kt@@ -0,0 +1,92 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import androidx.media3.common.C+import androidx.media3.common.PlaybackException+import androidx.media3.datasource.DataSpec+import androidx.media3.exoplayer.source.LoadEventInfo+import androidx.media3.exoplayer.source.MediaLoadData+import androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicy+import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.PlaybackContentKind+import java.io.IOException+import java.net.SocketTimeoutException+import java.util.concurrent.TimeoutException+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class HlsTimestampRetryPolicyTest {+ @Test+ fun `live dependency wait has one load retry before and after playback starts`() {+ for (started in listOf(false, true)) {+ val policy = policy(PlaybackContentKind.LIVE, started)+ val error = dependencyTimeout()+ val firstFailure = loadError(error, 1)+ assertThat(policy.getRetryDelayMsFor(firstFailure)).isEqualTo(1_000L)+ assertThat(policy.hasPendingLoadRecovery).isTrue()+ val exhausted = LoadErrorHandlingPolicy.LoadErrorInfo(+ firstFailure.loadEventInfo, firstFailure.mediaLoadData, error, 2+ )+ assertThat(policy.getRetryDelayMsFor(exhausted)).isEqualTo(C.TIME_UNSET)+ policy.onLoadTaskConcluded(firstFailure.loadEventInfo.loadTaskId)+ assertThat(policy.hasPendingLoadRecovery).isFalse()+ assertThat(policy.maxAttempts(error, started)).isEqualTo(1)+ val fatal = PlaybackException("dependency wait", error, PlaybackException.ERROR_CODE_IO_UNSPECIFIED)+ assertThat(policy.shouldRetryWholeSource(fatal, started, 1)).isTrue()+ assertThat(policy.shouldRetryWholeSource(fatal, started, 2)).isFalse()+ }+ }++ @Test+ fun `ordinary live socket failures keep existing retry budget`() {+ val policy = policy(PlaybackContentKind.LIVE, false)+ assertThat(policy.maxAttempts(SocketTimeoutException("read timeout"), false)).isEqualTo(10)+ assertThat(policy.maxAttempts(IOException(TimeoutException("another dependency")), true)).isEqualTo(10)+ }++ @Test+ fun `finite hls retry behavior is unchanged`() {+ val generic = IOException(TimeoutException("another dependency"))+ for (started in listOf(false, true)) {+ val policy = policy(PlaybackContentKind.ON_DEMAND, started)+ assertThat(policy.maxAttempts(dependencyTimeout(), started))+ .isEqualTo(policy.maxAttempts(generic, started))+ }+ }++ @Test+ fun `dependency cause does not override terminal auth or drm categories`() {+ val policy = policy(PlaybackContentKind.LIVE, true)+ assertThat(policy.maxAttempts(IOException("HTTP 403", dependencyTimeout()), true)).isEqualTo(0)+ assertThat(policy.maxAttempts(PlaybackException(+ "license failure", dependencyTimeout(), PlaybackException.ERROR_CODE_DRM_UNSPECIFIED+ ), true)).isEqualTo(0)+ }++ @Test+ fun `non hls live source does not inherit dependency retry cap`() {+ val policy = PlayerRetryPolicy(PlaybackRetryContext(+ ResolvedStreamType.MPEG_TS_LIVE, PlayerTimeoutProfile.LIVE, PlaybackContentKind.LIVE+ )) { true }+ assertThat(policy.maxAttempts(dependencyTimeout(), true)).isEqualTo(10)+ }++ private fun policy(kind: PlaybackContentKind, started: Boolean) = PlayerRetryPolicy(+ PlaybackRetryContext(ResolvedStreamType.HLS, PlayerTimeoutProfile.LIVE, kind)+ ) { started }++ private fun dependencyTimeout() = IOException(TimeoutException(+ "TimestampAdjuster failed to initialize in 30000 milliseconds"+ ))++ private fun loadError(error: IOException, count: Int): LoadErrorHandlingPolicy.LoadErrorInfo {+ val spec = DataSpec.Builder().setUri("https://example.test/audio.ts").build()+ return LoadErrorHandlingPolicy.LoadErrorInfo(+ LoadEventInfo.Builder(LoadEventInfo.getNewId(), spec, 0L).build(),+ MediaLoadData(C.DATA_TYPE_MEDIA), error, count+ )+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/LenientHlsPlaylistParserFactoryTest.kt b/player/src/test/java/com/streamvault/player/playback/LenientHlsPlaylistParserFactoryTest.ktnew file mode 100644index 00000000..c1e432c3--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/LenientHlsPlaylistParserFactoryTest.kt@@ -0,0 +1,197 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import android.net.Uri+import androidx.media3.common.C+import androidx.media3.exoplayer.hls.playlist.HlsMediaPlaylist+import com.google.common.truth.Truth.assertThat+import java.io.ByteArrayInputStream+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class LenientHlsPlaylistParserFactoryTest {+ @Test+ fun `manual floor is added only when source target and window leave segment safety margin`() {+ val twelveSecondPlaylist = mediaPlaylist(+ targetDurationSeconds = 2,+ segmentCount = 6,+ serverControl = "CAN-BLOCK-RELOAD=YES,HOLD-BACK=6.0"+ )++ val playlist = parse(twelveSecondPlaylist, stabilityTargetOffsetMs = 10_000L)++ assertThat(playlist.startOffsetUs).isEqualTo(2_000_000L)+ assertThat(playlist.hasPositiveStartOffset).isFalse()+ assertThat(playlist.preciseStart).isFalse()+ assertThat(playlist.serverControl.holdBackUs).isEqualTo(6_000_000L)+ assertThat(playlist.durationUs).isEqualTo(12_000_000L)+ }++ @Test+ fun `short published window remains unchanged`() {+ val playlist = parse(+ mediaPlaylist(targetDurationSeconds = 2, segmentCount = 3, serverControl = "HOLD-BACK=6.0"),+ stabilityTargetOffsetMs = 10_000L+ )++ assertThat(playlist.startOffsetUs).isEqualTo(C.TIME_UNSET)+ assertThat(playlist.serverControl.holdBackUs).isEqualTo(6_000_000L)+ }++ @Test+ fun `larger normal three target duration reserve is not lowered`() {+ val playlist = parse(+ mediaPlaylist(targetDurationSeconds = 6, segmentCount = 6),+ stabilityTargetOffsetMs = 10_000L+ )++ assertThat(playlist.startOffsetUs).isEqualTo(C.TIME_UNSET)+ assertThat(playlist.durationUs).isEqualTo(36_000_000L)+ }++ @Test+ fun `larger explicit hold back is not lowered`() {+ val playlist = parse(+ mediaPlaylist(targetDurationSeconds = 2, segmentCount = 12, serverControl = "HOLD-BACK=18.0"),+ stabilityTargetOffsetMs = 10_000L+ )++ assertThat(playlist.startOffsetUs).isEqualTo(C.TIME_UNSET)+ assertThat(playlist.serverControl.holdBackUs).isEqualTo(18_000_000L)+ }++ @Test+ fun `explicit provider start offsets are preserved`() {+ for (offset in listOf("5.0", "-5.0")) {+ val input = mediaPlaylist(+ targetDurationSeconds = 2,+ segmentCount = 12,+ startOffsetSeconds = offset,+ serverControl = "HOLD-BACK=6.0"+ )+ val parsedProviderStart = parse(input, stabilityTargetOffsetMs = null).startOffsetUs+ val playlist = parse(+ input,+ stabilityTargetOffsetMs = 10_000L+ )++ assertThat(playlist.startOffsetUs).isEqualTo(parsedProviderStart)+ }+ }++ @Test+ fun `finite vod and event playlists remain unchanged`() {+ val vod = parse(+ mediaPlaylist(+ targetDurationSeconds = 2,+ segmentCount = 12,+ playlistType = "VOD",+ endList = true+ ),+ stabilityTargetOffsetMs = 10_000L+ )+ val event = parse(+ mediaPlaylist(targetDurationSeconds = 2, segmentCount = 12, playlistType = "EVENT"),+ stabilityTargetOffsetMs = 10_000L+ )++ assertThat(vod.startOffsetUs).isEqualTo(C.TIME_UNSET)+ assertThat(vod.hasEndTag).isTrue()+ assertThat(event.startOffsetUs).isEqualTo(C.TIME_UNSET)+ assertThat(event.playlistType).isEqualTo(HlsMediaPlaylist.PLAYLIST_TYPE_EVENT)+ }++ @Test+ fun `plain live playlist gets floor while absent server control remains absent`() {+ val playlist = parse(+ mediaPlaylist(targetDurationSeconds = 2, segmentCount = 6),+ stabilityTargetOffsetMs = 10_000L+ )++ assertThat(playlist.startOffsetUs).isEqualTo(2_000_000L)+ assertThat(playlist.serverControl.holdBackUs).isEqualTo(C.TIME_UNSET)+ }++ @Test+ fun `part hold back remains intact and controls the source target when valid`() {+ val playlist = parse(+ mediaPlaylist(+ targetDurationSeconds = 2,+ segmentCount = 6,+ partTargetSeconds = 0.5,+ serverControl = "HOLD-BACK=18.0,PART-HOLD-BACK=4.0"+ ),+ stabilityTargetOffsetMs = 10_000L+ )++ assertThat(playlist.startOffsetUs).isEqualTo(2_000_000L)+ assertThat(playlist.serverControl.holdBackUs).isEqualTo(18_000_000L)+ assertThat(playlist.serverControl.partHoldBackUs).isEqualTo(4_000_000L)+ }++ @Test+ fun `floor clone preserves playlist timeline and segment metadata`() {+ val originalText = mediaPlaylist(+ targetDurationSeconds = 2,+ segmentCount = 6,+ serverControl = "CAN-BLOCK-RELOAD=YES,HOLD-BACK=6.0",+ discontinuitySequence = 7,+ mediaSequence = 44+ )+ val original = parse(originalText, stabilityTargetOffsetMs = null)+ val floored = parse(originalText, stabilityTargetOffsetMs = 10_000L)++ assertThat(floored.startOffsetUs).isEqualTo(2_000_000L)+ assertThat(floored.baseUri).isEqualTo(original.baseUri)+ assertThat(floored.tags).containsExactlyElementsIn(original.tags)+ assertThat(floored.mediaSequence).isEqualTo(original.mediaSequence)+ assertThat(floored.discontinuitySequence).isEqualTo(original.discontinuitySequence)+ assertThat(floored.hasDiscontinuitySequence).isEqualTo(original.hasDiscontinuitySequence)+ assertThat(floored.durationUs).isEqualTo(original.durationUs)+ assertThat(floored.targetDurationUs).isEqualTo(original.targetDurationUs)+ assertThat(floored.serverControl.holdBackUs).isEqualTo(original.serverControl.holdBackUs)+ assertThat(floored.segments.map { it.url }).containsExactlyElementsIn(original.segments.map { it.url })+ assertThat(floored.segments.map { it.durationUs })+ .containsExactlyElementsIn(original.segments.map { it.durationUs })+ assertThat(floored.segments.map { it.relativeStartTimeUs })+ .containsExactlyElementsIn(original.segments.map { it.relativeStartTimeUs })+ }++ private fun parse(text: String, stabilityTargetOffsetMs: Long?): HlsMediaPlaylist {+ val parser = LenientHlsPlaylistParserFactory(stabilityTargetOffsetMs).createPlaylistParser()+ return parser.parse(+ Uri.parse("https://example.test/live.m3u8"),+ ByteArrayInputStream(text.toByteArray(Charsets.UTF_8))+ ) as HlsMediaPlaylist+ }++ private fun mediaPlaylist(+ targetDurationSeconds: Int,+ segmentCount: Int,+ serverControl: String? = null,+ playlistType: String? = null,+ startOffsetSeconds: String? = null,+ partTargetSeconds: Double? = null,+ endList: Boolean = false,+ discontinuitySequence: Int = 0,+ mediaSequence: Int = 0+ ): String = buildString {+ appendLine("#EXTM3U")+ appendLine("#EXT-X-VERSION:6")+ appendLine("#EXT-X-TARGETDURATION:$targetDurationSeconds")+ appendLine("#EXT-X-MEDIA-SEQUENCE:$mediaSequence")+ if (discontinuitySequence != 0) appendLine("#EXT-X-DISCONTINUITY-SEQUENCE:$discontinuitySequence")+ playlistType?.let { appendLine("#EXT-X-PLAYLIST-TYPE:$it") }+ startOffsetSeconds?.let { appendLine("#EXT-X-START:TIME-OFFSET=$it,PRECISE=YES") }+ partTargetSeconds?.let { appendLine("#EXT-X-PART-INF:PART-TARGET=$it") }+ serverControl?.let { appendLine("#EXT-X-SERVER-CONTROL:$it") }+ repeat(segmentCount) { index ->+ appendLine("#EXTINF:$targetDurationSeconds.0,")+ appendLine("segment${mediaSequence + index}.ts")+ }+ if (endList) appendLine("#EXT-X-ENDLIST")+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/LiveMpegTsEndRecoveryTest.kt b/player/src/test/java/com/streamvault/player/playback/LiveMpegTsEndRecoveryTest.ktnew file mode 100644index 00000000..1181b1e3--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/LiveMpegTsEndRecoveryTest.kt@@ -0,0 +1,89 @@+package com.streamvault.player.playback++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.DrmInfo+import com.streamvault.domain.model.DrmScheme+import com.streamvault.domain.model.PlaybackContentKind+import com.streamvault.domain.model.StreamInfo+import org.junit.Test++class LiveMpegTsEndRecoveryTest {+ private val live = StreamInfo("https://example.test/live.ts", playbackContentKind = PlaybackContentKind.LIVE)++ private fun eligible(+ info: StreamInfo? = live,+ type: ResolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,+ started: Boolean = true,+ requested: Boolean = true,+ owned: Boolean = false,+ retry: Boolean = false+ ) = canRecoverLiveMpegTsEnd(info, type, started, requested, owned, retry)++ @Test fun `only explicit clear HTTP live TS can refresh after an end`() {+ assertThat(eligible()).isTrue()+ assertThat(eligible(live.copy(url = "http://example.test/live.ts"))).isTrue()+ for (kind in listOf(PlaybackContentKind.UNKNOWN, PlaybackContentKind.ON_DEMAND, PlaybackContentKind.CATCH_UP)) {+ assertThat(eligible(live.copy(playbackContentKind = kind))).isFalse()+ }+ for (type in ResolvedStreamType.entries.filter { it != ResolvedStreamType.MPEG_TS_LIVE }) {+ assertThat(eligible(type = type)).isFalse()+ }+ for (url in listOf("file:///recording.ts", "content://recording/1", "rtsp://example.test/live", "malformed URL")) {+ assertThat(eligible(live.copy(url = url))).isFalse()+ }+ assertThat(eligible(null)).isFalse()+ assertThat(eligible(live.copy(drmInfo = DrmInfo(DrmScheme.WIDEVINE, "https://example.test/license")))).isFalse()+ }++ @Test fun `no refresh before playback or against another owner or paused user`() {+ assertThat(eligible(started = false)).isFalse()+ assertThat(eligible(requested = false)).isFalse()+ assertThat(eligible(owned = true)).isFalse()+ assertThat(eligible(retry = true)).isFalse()+ }++ @Test fun `one refresh waits for active sources and quiet interval`() {+ val recovery = LiveMpegTsEndRecovery()+ assertThat(recovery.hasAttempted).isFalse()+ assertThat(recovery.onEnded(0, eligible = true)).isTrue()+ assertThat(recovery.hasAttempted).isTrue()+ assertThat(recovery.evaluate(1_000, true, true)).isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(recovery.evaluate(2_000, true, false)).isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(recovery.evaluate(2_499, true, false)).isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(recovery.evaluate(2_500, true, false)).isEqualTo(StartupRefreshGate.Action.READY)+ assertThat(recovery.isPending).isFalse()+ recovery.reset(preserveAttempt = true)+ assertThat(recovery.hasAttempted).isTrue()+ assertThat(recovery.onEnded(10_000, eligible = true)).isFalse()+ recovery.reset()+ assertThat(recovery.hasAttempted).isFalse()+ assertThat(recovery.onEnded(20_000, eligible = true)).isTrue()+ }++ @Test fun `undrained source ends the attempt without opening another`() {+ val recovery = LiveMpegTsEndRecovery()+ recovery.onEnded(0, eligible = true)+ assertThat(recovery.evaluate(25_000, true, true)).isEqualTo(StartupRefreshGate.Action.GIVE_UP)+ assertThat(recovery.abandoned).isTrue()+ assertThat(recovery.isPending).isFalse()+ assertThat(recovery.onEnded(30_000, eligible = true)).isFalse()+ }++ @Test fun `pause suspends drain clock and does not replenish refresh budget`() {+ val recovery = LiveMpegTsEndRecovery()+ recovery.onEnded(0, eligible = true)+ recovery.pauseClock()+ assertThat(recovery.evaluate(100_000, false, true)).isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(recovery.evaluate(200_000, true, true)).isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(recovery.evaluate(225_000, true, true)).isEqualTo(StartupRefreshGate.Action.GIVE_UP)+ recovery.reset(preserveAttempt = true)+ assertThat(recovery.abandoned).isFalse()+ assertThat(recovery.onEnded(300_000, eligible = true)).isFalse()+ }++ @Test fun `ineligible end does not consume a future eligible attempt`() {+ val recovery = LiveMpegTsEndRecovery()+ assertThat(recovery.onEnded(0, eligible = false)).isFalse()+ assertThat(recovery.onEnded(100, eligible = true)).isTrue()+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/LiveMpegTsExtractorFlagsDiagnosticTest.kt b/player/src/test/java/com/streamvault/player/playback/LiveMpegTsExtractorFlagsDiagnosticTest.ktnew file mode 100644index 00000000..c9efea40--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/LiveMpegTsExtractorFlagsDiagnosticTest.kt@@ -0,0 +1,366 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import androidx.media3.common.C+import androidx.media3.common.DataReader+import androidx.media3.common.Format+import androidx.media3.common.util.ParsableByteArray+import androidx.media3.common.util.TimestampAdjuster+import android.net.Uri+import androidx.media3.extractor.DefaultExtractorInput+import androidx.media3.extractor.Extractor+import androidx.media3.extractor.ExtractorOutput+import androidx.media3.extractor.PositionHolder+import androidx.media3.extractor.SeekMap+import androidx.media3.extractor.TrackOutput+import androidx.media3.extractor.ts.DefaultTsPayloadReaderFactory+import androidx.media3.extractor.ts.TsExtractor+import androidx.media3.extractor.text.SubtitleParser+import java.io.ByteArrayOutputStream+import java.io.File+import java.io.FileInputStream+import java.security.MessageDigest+import org.json.JSONArray+import org.json.JSONObject+import org.junit.Assume.assumeTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** Opt-in diagnostic; it reads an external TS asset and never changes production parser settings. */+@RunWith(RobolectricTestRunner::class)+class LiveMpegTsExtractorFlagsDiagnosticTest {++ @Test+ fun `report raw live ts sample boundaries with and without access unit detection`() {+ val inputPath = System.getenv(INPUT_ENV)?.trim().orEmpty()+ val reportPath = System.getenv(REPORT_ENV)?.trim().orEmpty()+ assumeTrue("Set $INPUT_ENV and $REPORT_ENV to enable this diagnostic", inputPath.isNotEmpty() && reportPath.isNotEmpty())++ val inputFile = File(inputPath).canonicalFile+ val reportFile = File(reportPath).canonicalFile+ check(inputFile.isFile) { "Diagnostic TS input does not exist: $inputFile" }+ reportFile.parentFile?.mkdirs()++ val currentFlags =+ DefaultTsPayloadReaderFactory.FLAG_DETECT_ACCESS_UNITS or+ DefaultTsPayloadReaderFactory.FLAG_ALLOW_NON_IDR_KEYFRAMES or+ DefaultTsPayloadReaderFactory.FLAG_IGNORE_SPLICE_INFO_STREAM+ val withoutAccessUnitDetection =+ DefaultTsPayloadReaderFactory.FLAG_ALLOW_NON_IDR_KEYFRAMES or+ DefaultTsPayloadReaderFactory.FLAG_IGNORE_SPLICE_INFO_STREAM++ val current = extractVariant(inputFile, "current_flags", currentFlags)+ val withoutDetect = extractVariant(inputFile, "without_detect_access_units", withoutAccessUnitDetection)+ val coalesced = extractVariant(+ inputFile,+ "live_factory_avc_prefix_coalescing",+ currentFlags,+ useLiveFactory = true+ )+ check(coalesced.getString("vclSampleSequence") == withoutDetect.getString("vclSampleSequence")) {+ "AVC coalescing changed per-sample VCL PTS/flags/size/payload sequence"+ }+ check(coalesced.getInt("headerOnlyOrNonVclSamples") == 0) {+ "AVC coalescing left header-only samples: ${coalesced.getInt("headerOnlyOrNonVclSamples")}"+ }+ check(coalesced.getString("samplePayloadSha256") == withoutDetect.getString("samplePayloadSha256")) {+ "AVC coalescing changed concatenated in-range sample payload bytes"+ }+ val report = JSONObject()+ .put("inputPath", inputFile.path)+ .put("inputBytes", inputFile.length())+ .put("inputSha256", sha256(inputFile))+ .put("extractorMode", "MODE_SINGLE_PMT")+ .put("inputLengthContract", "C.LENGTH_UNSET")+ .put("limits", JSONObject().put("maxVclTimeUsInclusive", MAX_VIDEO_TIME_US).put("maxVideoSamples", MAX_VIDEO_SAMPLES))+ .put("coverageNote", "Extraction continues until a VCL sample reaches the 15s boundary; summaries compare only samples with timeUs <= 15s, excluding later batch overshoot.")+ .put("variants", JSONArray().put(current).put(withoutDetect).put(coalesced))++ reportFile.writeText(report.toString(2), Charsets.UTF_8)+ println("LiveMpegTsExtractorFlagsDiagnostic report=${reportFile.path} current=${current.getInt("videoSampleCount")} withoutDetect=${withoutDetect.getInt("videoSampleCount")}")+ }++ private fun extractVariant(+ inputFile: File,+ name: String,+ payloadReaderFlags: Int,+ useLiveFactory: Boolean = false+ ): JSONObject {+ val output = RecordingExtractorOutput()+ val extractor: Extractor+ if (useLiveFactory) {+ val uri = Uri.fromFile(inputFile)+ val candidates = liveMpegTsExtractorsFactory().createExtractors(uri, emptyMap())+ extractor = candidates.firstOrNull { it.javaClass.simpleName == "AvcAccessUnitExtractor" }+ ?: error("Live raw-TS factory did not return its AVC-normalizing TS extractor: ${candidates.map { it.javaClass.name }}")+ } else {+ val payloadReaderFactory = DefaultTsPayloadReaderFactory(payloadReaderFlags)+ extractor = TsExtractor(+ TsExtractor.MODE_SINGLE_PMT,+ TsExtractor.FLAG_EMIT_RAW_SUBTITLE_DATA,+ SubtitleParser.Factory.UNSUPPORTED,+ TimestampAdjuster(0),+ payloadReaderFactory,+ TsExtractor.DEFAULT_TIMESTAMP_SEARCH_BYTES+ )+ }+ val positionHolder = PositionHolder()+ var result = Extractor.RESULT_CONTINUE+ extractor.init(output)+ FileInputStream(inputFile).use { fileInput ->+ val dataReader = DataReader { buffer, offset, length -> fileInput.read(buffer, offset, length) }+ val input = DefaultExtractorInput(dataReader, 0L, C.LENGTH_UNSET.toLong())+ while (!output.shouldStop() && result != Extractor.RESULT_END_OF_INPUT) {+ result = extractor.read(input, positionHolder)+ check(result != Extractor.RESULT_SEEK) {+ "Live extractor unexpectedly requested a seek for $name to ${positionHolder.position}"+ }+ }+ }+ extractor.release()+ return output.summary(name, payloadReaderFlags, result)+ }++ private class RecordingExtractorOutput : ExtractorOutput {+ private val tracks = linkedMapOf<Int, RecordingTrackOutput>()+ private var endedTracks = false+ private var seekMapDurationUs = C.TIME_UNSET++ override fun track(id: Int, type: Int): TrackOutput =+ tracks.getOrPut(id) { RecordingTrackOutput(id, type) }++ override fun endTracks() {+ endedTracks = true+ }++ override fun seekMap(seekMap: SeekMap) {+ seekMapDurationUs = seekMap.durationUs+ }++ fun shouldStop(): Boolean {+ val video = tracks.values.firstOrNull { it.trackType == C.TRACK_TYPE_VIDEO }+ return video?.shouldStop() == true+ }++ fun summary(name: String, flags: Int, readResult: Int): JSONObject {+ val videoTracks = tracks.values.filter { it.trackType == C.TRACK_TYPE_VIDEO }+ val allVideoSamples = videoTracks.flatMap { it.samples }+ val videoSamples = allVideoSamples.filter { it.timeUs <= MAX_VIDEO_TIME_US }+ val vclSequence = JSONArray()+ videoSamples.filter { it.hasVcl }.forEach { sample ->+ vclSequence.put(+ JSONObject()+ .put("timeUs", sample.timeUs)+ .put("flags", sample.flags)+ .put("size", sample.size)+ .put("payloadSha256", sha256(sample.payload))+ )+ }+ var duplicateTimestamps = 0+ var timestampRegressions = 0+ videoSamples.zipWithNext().forEach { (previous, current) ->+ when {+ current.timeUs == previous.timeUs -> duplicateTimestamps+++ current.timeUs < previous.timeUs -> timestampRegressions+++ }+ }+ val firstVideoTimeUs = videoSamples.firstOrNull()?.timeUs+ val lastVideoTimeUs = videoSamples.lastOrNull()?.timeUs+ val nonVclSamples = videoSamples.count { !it.hasVcl }+ val payloadDigest = MessageDigest.getInstance("SHA-256")+ videoSamples.forEach { payloadDigest.update(it.payload) }+ val nalCounts = linkedMapOf<Int, Int>()+ videoSamples.flatMap { it.nalTypes }.forEach { type -> nalCounts[type] = (nalCounts[type] ?: 0) + 1 }+ val firstSamples = JSONArray()+ videoSamples.take(FIRST_SAMPLES_TO_REPORT).forEach { sample ->+ firstSamples.put(+ JSONObject()+ .put("timeUs", sample.timeUs)+ .put("size", sample.size)+ .put("flags", sample.flags)+ .put("nalTypes", JSONArray(sample.nalTypes))+ .put("hasVcl", sample.hasVcl)+ .put("containsAud", sample.nalTypes.contains(H264_AUD_NAL_TYPE))+ )+ }+ val formats = JSONArray()+ videoTracks.mapNotNull { it.format }.distinctBy { it.sampleMimeType to it.codecs }.forEach { format ->+ formats.put(+ JSONObject()+ .put("sampleMimeType", format.sampleMimeType)+ .put("codecs", format.codecs)+ .put("width", format.width)+ .put("height", format.height)+ .put("frameRate", format.frameRate)+ )+ }+ return JSONObject()+ .put("name", name)+ .put("payloadReaderFlags", flags)+ .put("factoryPath", if (name.startsWith("live_factory")) "liveMpegTsExtractorsFactory" else "directTsExtractorReference")+ .put("extractorMode", if (name.startsWith("live_factory")) "DIRECT_LIVE_MPEG_TS_POLICY (MODE_SINGLE_PMT)" else "MODE_SINGLE_PMT")+ .put("inputLengthContract", "C.LENGTH_UNSET")+ .put("seekMapDurationUs", seekMapDurationUs)+ .put("readResult", readResult)+ .put("tracksEnded", endedTracks)+ .put("videoTrackCount", videoTracks.size)+ .put("videoSampleCount", videoSamples.size)+ .put("rawVideoSampleCountIncludingBoundaryOvershoot", allVideoSamples.size)+ .put("samplesBeyondMaxVclTime", allVideoSamples.count { it.timeUs > MAX_VIDEO_TIME_US })+ .put("videoSampleBytes", videoSamples.sumOf { it.size.toLong() })+ .put("samplePayloadSha256", payloadDigest.digest().joinToString("") { "%02x".format(it) })+ .put("vclSampleCount", videoSamples.count { it.hasVcl })+ .put("lastVclTimeUs", videoSamples.lastOrNull { it.hasVcl }?.timeUs ?: JSONObject.NULL)+ .put("vclSampleSequence", vclSequence.toString())+ .put("zeroSizeSamples", videoSamples.count { it.size == 0 })+ .put("nonVclSamples", nonVclSamples)+ .put("headerOnlyOrNonVclSamples", nonVclSamples)+ .put("audSamples", videoSamples.count { it.nalTypes.contains(H264_AUD_NAL_TYPE) })+ .put("nalTypeCounts", JSONObject().also { counts -> nalCounts.forEach { (type, count) -> counts.put(type.toString(), count) } })+ .put("duplicateTimestamps", duplicateTimestamps)+ .put("timestampRegressions", timestampRegressions)+ .put("firstVideoTimeUs", firstVideoTimeUs ?: JSONObject.NULL)+ .put("lastVideoTimeUs", lastVideoTimeUs ?: JSONObject.NULL)+ .put("videoFormats", formats)+ .put("firstSamples", firstSamples)+ }+ }++ private class RecordingTrackOutput(+ val trackId: Int,+ val trackType: Int+ ) : TrackOutput {+ private val pendingMainData = ByteArrayOutputStream()+ val samples = mutableListOf<VideoSample>()+ var format: Format? = null+ private set++ override fun format(format: Format) {+ this.format = format+ }++ override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int {+ if (length <= 0) return 0+ val bytes = ByteArray(length)+ var total = 0+ while (total < length) {+ val read = input.read(bytes, total, length - total)+ if (read == C.RESULT_END_OF_INPUT) {+ if (total == 0 && allowEndOfInput) return C.RESULT_END_OF_INPUT+ if (allowEndOfInput) break+ throw java.io.EOFException("Extractor sample data ended after $total of $length bytes")+ }+ if (read == 0) continue+ total += read+ }+ if (trackType == C.TRACK_TYPE_VIDEO && sampleDataPart == TrackOutput.SAMPLE_DATA_PART_MAIN) {+ pendingMainData.write(bytes, 0, total)+ }+ return total+ }++ override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {+ val bytes = data.data+ val start = data.position+ if (trackType == C.TRACK_TYPE_VIDEO && sampleDataPart == TrackOutput.SAMPLE_DATA_PART_MAIN) {+ pendingMainData.write(bytes, start, length)+ }+ data.skipBytes(length)+ }++ override fun sampleMetadata(+ timeUs: Long,+ flags: Int,+ size: Int,+ offset: Int,+ cryptoData: TrackOutput.CryptoData?+ ) {+ if (trackType != C.TRACK_TYPE_VIDEO) return+ val bytes = pendingMainData.toByteArray()+ val sampleStart = bytes.size - offset - size+ if (sampleStart < 0 || sampleStart + size > bytes.size) {+ samples += VideoSample(timeUs, size, flags, emptyList(), hasVcl = false, payload = byteArrayOf())+ pendingMainData.reset()+ return+ }+ val sampleBytes = bytes.copyOfRange(sampleStart, sampleStart + size)+ val trailingBytes = bytes.copyOfRange(sampleStart + size, bytes.size)+ pendingMainData.reset()+ if (trailingBytes.isNotEmpty()) pendingMainData.write(trailingBytes)+ val nals = parseH264NalTypes(sampleBytes)+ samples += VideoSample(+ timeUs = timeUs,+ size = size,+ flags = flags,+ nalTypes = nals,+ hasVcl = nals.any(::isVclNal),+ payload = sampleBytes+ )+ }++ fun shouldStop(): Boolean =+ samples.size >= MAX_VIDEO_SAMPLES || (samples.lastOrNull { it.hasVcl }?.timeUs ?: 0L) >= MAX_VIDEO_TIME_US+ }++ private data class VideoSample(+ val timeUs: Long,+ val size: Int,+ val flags: Int,+ val nalTypes: List<Int>,+ val hasVcl: Boolean,+ val payload: ByteArray+ )++ private companion object {+ const val INPUT_ENV = "STREAMVAULT_TS_EXTRACTOR_INPUT"+ const val REPORT_ENV = "STREAMVAULT_TS_EXTRACTOR_REPORT"+ const val MAX_VIDEO_TIME_US = 15_000_000L+ const val MAX_VIDEO_SAMPLES = 2_000+ const val FIRST_SAMPLES_TO_REPORT = 40+ const val H264_AUD_NAL_TYPE = 9++ fun isVclNal(type: Int): Boolean = type in 1..5 || type in 19..21++ fun parseH264NalTypes(sample: ByteArray): List<Int> {+ val result = mutableListOf<Int>()+ var index = 0+ while (index + 3 < sample.size) {+ val prefixLength = when {+ sample[index] == 0.toByte() && sample[index + 1] == 0.toByte() &&+ sample[index + 2] == 1.toByte() -> 3+ index + 4 < sample.size && sample[index] == 0.toByte() &&+ sample[index + 1] == 0.toByte() && sample[index + 2] == 0.toByte() &&+ sample[index + 3] == 1.toByte() -> 4+ else -> 0+ }+ if (prefixLength == 0) {+ index+++ continue+ }+ val headerIndex = index + prefixLength+ if (headerIndex < sample.size) result += sample[headerIndex].toInt() and 0x1f+ index = headerIndex + 1+ }+ return result+ }++ fun sha256(file: File): String {+ val digest = MessageDigest.getInstance("SHA-256")+ FileInputStream(file).use { input ->+ val buffer = ByteArray(1024 * 1024)+ while (true) {+ val read = input.read(buffer)+ if (read < 0) break+ digest.update(buffer, 0, read)+ }+ }+ return digest.digest().joinToString("") { "%02x".format(it) }+ }++ fun sha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256")+ .digest(bytes)+ .joinToString("") { "%02x".format(it) }+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/LiveStartupErrorMessageTest.kt b/player/src/test/java/com/streamvault/player/playback/LiveStartupErrorMessageTest.ktnew file mode 100644index 00000000..4997e656--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/LiveStartupErrorMessageTest.kt@@ -0,0 +1,119 @@+package com.streamvault.player.playback++import android.content.res.Configuration+import android.os.LocaleList+import com.google.common.truth.Truth.assertThat+import com.google.common.truth.Truth.assertWithMessage+import java.io.File+import java.util.Locale+import javax.xml.parsers.DocumentBuilderFactory+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment++@RunWith(RobolectricTestRunner::class)+class LiveStartupErrorMessageTest {+ @Test+ fun `message follows selected app locale for every advertised locale without mutating context`() {+ val repositoryRoot = findRepositoryRoot()+ val advertisedLocales = readAdvertisedLocales(+ repositoryRoot.resolve("app/src/main/res/xml/locales_config.xml")+ )+ assertThat(advertisedLocales).hasSize(38)++ val applicationContext = RuntimeEnvironment.getApplication()+ val originalLocale = Locale.getDefault()+ val originalApplicationConfiguration = Configuration(applicationContext.resources.configuration)+ val englishConfiguration = Configuration(originalApplicationConfiguration).apply {+ setLocales(LocaleList.forLanguageTags("en-US"))+ }+ val englishContext = applicationContext.createConfigurationContext(englishConfiguration)+ val englishContextConfiguration = Configuration(englishContext.resources.configuration)+ val englishMessage = englishContext.getString(com.streamvault.player.R.string.player_error_live_startup_timeout)++ try {+ for (languageTag in advertisedLocales) {+ val selectedLocale = Locale.forLanguageTag(languageTag)+ Locale.setDefault(selectedLocale)++ val expectedXmlMessage = readExpectedString(+ repositoryRoot.resolve("player/src/main/res"),+ languageTag,+ "player_error_live_startup_timeout"+ )+ val actualMessage = liveStartupTimeoutMessage(englishContext)++ assertWithMessage("message for advertised locale $languageTag")+ .that(actualMessage)+ .isEqualTo(expectedXmlMessage)+ if (languageTag != "en") {+ assertWithMessage("localized message for $languageTag")+ .that(actualMessage)+ .isNotEqualTo(englishMessage)+ }+ assertWithMessage("caller context configuration after $languageTag lookup")+ .that(englishContext.resources.configuration)+ .isEqualTo(englishContextConfiguration)+ assertWithMessage("application context configuration after $languageTag lookup")+ .that(applicationContext.resources.configuration)+ .isEqualTo(originalApplicationConfiguration)+ assertWithMessage("process default locale after $languageTag lookup")+ .that(Locale.getDefault())+ .isEqualTo(selectedLocale)+ }+ } finally {+ Locale.setDefault(originalLocale)+ }+ }++ private fun findRepositoryRoot(): File {+ val workingDirectory = System.getProperty("user.dir") ?: "."+ var current = File(workingDirectory).absoluteFile+ while (true) {+ if (File(current, "app/src/main/res/xml/locales_config.xml").isFile &&+ File(current, "player/src/main/res").isDirectory+ ) {+ return current+ }+ current = current.parentFile ?: error("Could not find repository root from $workingDirectory")+ }+ }++ private fun readAdvertisedLocales(localesConfig: File): List<String> {+ require(localesConfig.isFile) { "Missing locale config: $localesConfig" }+ val factory = DocumentBuilderFactory.newInstance().apply {+ setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)+ setFeature("http://xml.org/sax/features/external-general-entities", false)+ setFeature("http://xml.org/sax/features/external-parameter-entities", false)+ }+ val document = factory.newDocumentBuilder().parse(localesConfig)+ val localeNodes = document.getElementsByTagName("locale")+ return (0 until localeNodes.length).map { index ->+ localeNodes.item(index).attributes.getNamedItem("android:name")?.nodeValue+ ?: error("Locale entry has no android:name in $localesConfig")+ }+ }++ private fun readExpectedString(resourcesRoot: File, languageTag: String, resourceName: String): String {+ val valuesDirectory = when {+ languageTag == "en" -> "values"+ languageTag == "zh-TW" -> "values-zh-rTW"+ else -> "values-$languageTag"+ }+ val stringsFile = File(resourcesRoot, "$valuesDirectory/strings.xml")+ require(stringsFile.isFile) { "Missing $resourceName translation for $languageTag: $stringsFile" }+ val factory = DocumentBuilderFactory.newInstance().apply {+ setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)+ setFeature("http://xml.org/sax/features/external-general-entities", false)+ setFeature("http://xml.org/sax/features/external-parameter-entities", false)+ }+ val document = factory.newDocumentBuilder().parse(stringsFile)+ val nodes = document.getElementsByTagName("string")+ val matchingNode = (0 until nodes.length)+ .map(nodes::item)+ .firstOrNull { it.attributes.getNamedItem("name")?.nodeValue == resourceName }+ ?: error("Missing $resourceName in $stringsFile")+ return matchingNode.textContent+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/LiveStartupWatchdogTest.kt b/player/src/test/java/com/streamvault/player/playback/LiveStartupWatchdogTest.ktnew file mode 100644index 00000000..ef02780b--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/LiveStartupWatchdogTest.kt@@ -0,0 +1,197 @@+package com.streamvault.player.playback++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class LiveStartupWatchdogTest {+ @Test+ fun `flat reserve refreshes at exactly the no progress boundary once`() {+ val watchdog = LiveStartupWatchdog()++ assertThat(watchdog.evaluate(0L, eligible = true, firstVideoFrameRendered = false,+ audioOnlyPlaying = false, bufferedDurationMs = 0L)).isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(44_999L, eligible = true, firstVideoFrameRendered = false,+ audioOnlyPlaying = false, bufferedDurationMs = 0L)).isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(45_000L, eligible = true, firstVideoFrameRendered = false,+ audioOnlyPlaying = false, bufferedDurationMs = 0L)).isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)+ assertThat(watchdog.evaluate(90_000L, eligible = true, firstVideoFrameRendered = false,+ audioOnlyPlaying = false, bufferedDurationMs = 0L)).isEqualTo(LiveStartupWatchdog.Action.NONE)+ }++ @Test+ fun `preserved refresh episode gets a fresh clock then gives up without a second refresh`() {+ val watchdog = LiveStartupWatchdog()+ assertThat(watchdog.evaluate(1_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(46_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)++ watchdog.reset(preserveEpisode = true)+ assertThat(watchdog.evaluate(500_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(544_999L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(545_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.GIVE_UP)+ assertThat(watchdog.evaluate(590_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ }++ @Test+ fun `already used source retry skips refresh and gives up at boundary`() {+ val watchdog = LiveStartupWatchdog()+ assertThat(watchdog.evaluate(0L, true, false, false, 0L,+ sourceRetryAlreadyUsed = true)).isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(45_000L, true, false, false, 0L,+ sourceRetryAlreadyUsed = true)).isEqualTo(LiveStartupWatchdog.Action.GIVE_UP)+ }++ @Test+ fun `growing reserve for more than two minutes is not a no progress episode`() {+ val watchdog = LiveStartupWatchdog()+ for (second in 0..130) {+ assertThat(watchdog.evaluate(second * 1_000L, true, false, false,+ second * 1_000L)).isEqualTo(LiveStartupWatchdog.Action.NONE)+ }+ assertThat(watchdog.evaluate(174_999L, true, false, false, 130_000L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(175_000L, true, false, false, 130_000L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)+ }++ @Test+ fun `buffer progress must clear the minimum gain above the high water mark`() {+ val watchdog = LiveStartupWatchdog(noProgressTimeoutMs = 1_000L, minBufferProgressMs = 250L)+ assertThat(watchdog.evaluate(0L, true, false, false, 1_000L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(900L, true, false, false, 1_249L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(1_000L, true, false, false, 1_250L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(1_999L, true, false, false, 1_499L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(2_000L, true, false, false, 1_500L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(2_999L, true, false, false, 1_500L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(3_000L, true, false, false, 1_500L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)+ }++ @Test+ fun `oscillating reserve does not accumulate progress`() {+ val watchdog = LiveStartupWatchdog(noProgressTimeoutMs = 1_000L, minBufferProgressMs = 250L)+ assertThat(watchdog.evaluate(0L, true, false, false, 1_000L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(500L, true, false, false, 900L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(999L, true, false, false, 1_100L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(1_000L, true, false, false, 1_000L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)+ }++ @Test+ fun `ineligible interval suspends clock and reserve but retains episode budget`() {+ val watchdog = LiveStartupWatchdog(noProgressTimeoutMs = 1_000L, minBufferProgressMs = 250L)+ assertThat(watchdog.evaluate(0L, true, false, false, 700L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(900L, false, false, false, 5_000L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(100_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(100_999L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(101_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)++ watchdog.reset(preserveEpisode = true) // Source reprepare clears the report latch only.+ watchdog.evaluate(102_000L, false, false, false, 0L) // e.g. pause after refresh+ watchdog.evaluate(200_000L, true, false, false, 0L)+ assertThat(watchdog.evaluate(201_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.GIVE_UP)+ }++ @Test+ fun `first frame or audio only playback completes the episode`() {+ val videoWatchdog = LiveStartupWatchdog(noProgressTimeoutMs = 1_000L)+ assertThat(videoWatchdog.evaluate(0L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(videoWatchdog.evaluate(500L, true, firstVideoFrameRendered = true,+ audioOnlyPlaying = false, bufferedDurationMs = 0L)).isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(videoWatchdog.evaluate(10_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ videoWatchdog.reset()+ assertThat(videoWatchdog.evaluate(20_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(videoWatchdog.evaluate(21_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)++ val audioWatchdog = LiveStartupWatchdog(noProgressTimeoutMs = 1_000L)+ audioWatchdog.evaluate(0L, true, false, false, 0L)+ audioWatchdog.evaluate(500L, true, false, audioOnlyPlaying = true, bufferedDurationMs = 0L)+ assertThat(audioWatchdog.evaluate(10_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ }++ @Test+ fun `new prepare can explicitly start a fresh outage budget`() {+ val watchdog = LiveStartupWatchdog(noProgressTimeoutMs = 1_000L)+ watchdog.evaluate(0L, true, false, false, 0L)+ assertThat(watchdog.evaluate(1_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)++ watchdog.reset(preserveEpisode = false)+ assertThat(watchdog.evaluate(100_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(101_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)+ }++ @Test+ fun `pause clock rebases no progress time and keeps the episode retry budget`() {+ val watchdog = LiveStartupWatchdog()+ assertThat(watchdog.evaluate(0L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(44_999L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ watchdog.pauseClock() // Called synchronously at pause/detach, without relying on polling.++ assertThat(watchdog.evaluate(1_000_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(1_044_999L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(1_045_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)++ watchdog.reset(preserveEpisode = true)+ assertThat(watchdog.evaluate(2_000_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ watchdog.pauseClock()+ assertThat(watchdog.evaluate(2_100_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(2_144_999L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(2_145_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.GIVE_UP)++ val completedAudioWatchdog = LiveStartupWatchdog()+ completedAudioWatchdog.evaluate(0L, true, false, false, 0L)+ completedAudioWatchdog.evaluate(500L, true, false, audioOnlyPlaying = true, bufferedDurationMs = 0L)+ completedAudioWatchdog.pauseClock()+ assertThat(completedAudioWatchdog.evaluate(1_000_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ }++ @Test+ fun `large monotonic clock origin does not consume budget`() {+ val watchdog = LiveStartupWatchdog()+ val origin = 8_000_000_000L+ assertThat(watchdog.evaluate(origin, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(origin + 44_999L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.NONE)+ assertThat(watchdog.evaluate(origin + 45_000L, true, false, false, 0L))+ .isEqualTo(LiveStartupWatchdog.Action.REFRESH_SOURCE)+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/Media3PreloadWindowManagerTest.kt b/player/src/test/java/com/streamvault/player/playback/Media3PreloadWindowManagerTest.ktindex c56f3ef3..c75edfe6 100644--- a/player/src/test/java/com/streamvault/player/playback/Media3PreloadWindowManagerTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/Media3PreloadWindowManagerTest.kt@@ -10,6 +10,8 @@ import androidx.media3.exoplayer.upstream.DefaultBandwidthMeterimport androidx.media3.exoplayer.source.preload.DefaultPreloadManagerimport androidx.media3.exoplayer.upstream.LoadErrorHandlingPolicyimport com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.PlaybackBufferMode+import com.streamvault.domain.model.PlaybackContentKindimport androidx.media3.common.Cimport com.streamvault.domain.model.StreamTypeimport com.streamvault.player.PlayerPreloadContentType@@ -178,6 +180,58 @@ class Media3PreloadWindowManagerTest {manager.release()}+ @Test+ fun `mode change cannot hand off a deliberately mislabeled live stream's previous target source`() {+ val context = RuntimeEnvironment.getApplication()+ val dataSourceProvider = PlayerDataSourceFactoryProvider(+ context = context,+ baseClient = okhttp3.OkHttpClient()+ )+ var mode = PlaybackBufferMode.AUTO+ val mediaSourceFactory = PlayerMediaSourceFactory(dataSourceProvider) { mode }+ val manager = Media3PreloadWindowManager(+ context = context,+ mediaSourceFactory = mediaSourceFactory,+ dataSourceFactoryProvider = dataSourceProvider,+ bandwidthMeter = DefaultBandwidthMeter.Builder(context).build()+ )+ val player = manager.createPlayer(+ renderersFactory = DefaultRenderersFactory(context),+ loadControl = DefaultLoadControl(),+ preloadDataSourceFactory = DefaultDataSource.Factory(context)+ ) {+ it.setReleaseTimeoutMs(0L)+ }+ val liveHls = StreamInfo(+ url = "https://example.test/live/channel.m3u8",+ streamType = StreamType.HLS,+ containerExtension = "m3u8",+ playbackContentKind = PlaybackContentKind.LIVE+ )+ // Normal LIVE entries are excluded from preloading. Deliberately label this LIVE+ // StreamInfo as VOD to exercise defensive cache identity if such an item is supplied.+ val window = PlayerPreloadWindow(+ items = listOf(PlayerPreloadItem("managed-live-hls", liveHls, PlayerPreloadContentType.VOD)),+ currentIndex = 0+ )++ manager.updateWindow(window)+ val previous = manager.getMediaSource(liveHls)!!+ val previousMediaId = previous.mediaSource.mediaItem.mediaId+ mode = PlaybackBufferMode.MEDIUM++ assertThat(manager.getMediaSource(liveHls)).isNull()++ manager.updateWindow(window)+ val updated = manager.getMediaSource(liveHls)!!++ assertThat(updated.mediaSource).isNotSameInstanceAs(previous.mediaSource)+ assertThat(updated.mediaSource.mediaItem.mediaId).isNotEqualTo(previousMediaId)++ player.release()+ manager.release()+ }+@Testfun `handed off source retains its retry policy and reports foreground recovery changes`() {val context = RuntimeEnvironment.getApplication()diff --git a/player/src/test/java/com/streamvault/player/playback/Media3SharedTimestampAdjusterTest.kt b/player/src/test/java/com/streamvault/player/playback/Media3SharedTimestampAdjusterTest.ktnew file mode 100644index 00000000..de8ba9b3--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/Media3SharedTimestampAdjusterTest.kt@@ -0,0 +1,169 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import androidx.media3.common.C+import androidx.media3.common.util.TimestampAdjuster+import com.google.common.truth.Truth.assertThat+import java.io.IOException+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicReference+import java.util.concurrent.TimeoutException+import org.robolectric.shadows.ShadowSystemClock+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** Deterministic checks of Media3's real shared HLS timestamp-adjuster wait contract. */+@RunWith(RobolectricTestRunner::class)+class Media3SharedTimestampAdjusterTest {++ @Test+ fun `non primary waits without primary and times out when configured`() {+ val adjuster = TimestampAdjuster(TimestampAdjuster.MODE_SHARED)+ val finished = CountDownLatch(1)+ val failure = AtomicReference<Throwable?>()+ val timeoutMs = 180L++ val waiter = Thread {+ try {+ adjuster.sharedInitializeOrWait(+ /* canInitialize= */ false,+ /* nextSampleTimestampUs= */ C.TIME_UNSET,+ timeoutMs+ )+ } catch (error: Throwable) {+ failure.set(error)+ } finally {+ finished.countDown()+ }+ }.apply {+ name = "timestamp-adjuster-timeout-test"+ isDaemon = true+ }++ waiter.start()+ try {+ awaitWaitingState(waiter, allowTimedWait = true)+ // Media3 uses Android elapsedRealtime() in the timeout loop. Advance Robolectric's+ // clock after the worker enters Object.wait(); the real wait then wakes normally.+ ShadowSystemClock.advanceBy(timeoutMs + 1, TimeUnit.MILLISECONDS)+ assertThat(finished.await(2, TimeUnit.SECONDS)).isTrue()+ waiter.join(1_000)++ assertThat(failure.get()).isInstanceOf(TimeoutException::class.java)+ assertThat(failure.get()?.message).contains("$timeoutMs milliseconds")+ assertThat(isHlsTimestampInitializationTimeout(IOException(failure.get()))).isTrue()+ assertThat(adjuster.isInitialized).isFalse()+ assertThat(adjuster.timestampOffsetUs).isEqualTo(C.TIME_UNSET)+ } finally {+ waiter.interrupt()+ waiter.join(1_000)+ }+ }++ @Test+ fun `delayed primary sample initializes and releases an already waiting secondary`() {+ val adjuster = TimestampAdjuster(TimestampAdjuster.MODE_SHARED)+ val entered = CountDownLatch(1)+ val finished = CountDownLatch(1)+ val failure = AtomicReference<Throwable?>()+ val timeoutMs = 2_000L++ val secondary = Thread {+ entered.countDown()+ try {+ adjuster.sharedInitializeOrWait(+ /* canInitialize= */ false,+ /* nextSampleTimestampUs= */ C.TIME_UNSET,+ timeoutMs+ )+ } catch (error: Throwable) {+ failure.set(error)+ } finally {+ finished.countDown()+ }+ }.apply {+ name = "timestamp-adjuster-secondary-test"+ isDaemon = true+ }++ secondary.start()+ try {+ assertThat(entered.await(1, TimeUnit.SECONDS)).isTrue()+ awaitWaitingState(secondary, allowTimedWait = true)+ assertThat(finished.count).isEqualTo(1L)+ assertThat(adjuster.isInitialized).isFalse()++ val desiredFirstSampleUs = 4_000_000L+ val rawFirstSampleUs = 19_000_000L+ adjuster.sharedInitializeOrWait(+ /* canInitialize= */ true,+ desiredFirstSampleUs,+ /* timeoutMs= */ 0L+ )+ assertThat(adjuster.adjustSampleTimestamp(rawFirstSampleUs)).isEqualTo(desiredFirstSampleUs)++ assertThat(finished.await(1, TimeUnit.SECONDS)).isTrue()+ secondary.join(1_000)+ assertThat(failure.get()).isNull()+ assertThat(adjuster.isInitialized).isTrue()+ assertThat(adjuster.timestampOffsetUs).isEqualTo(desiredFirstSampleUs - rawFirstSampleUs)+ } finally {+ secondary.interrupt()+ secondary.join(1_000)+ }+ }++ @Test+ fun `interrupt releases an unbounded non primary wait`() {+ val adjuster = TimestampAdjuster(TimestampAdjuster.MODE_SHARED)+ val entered = CountDownLatch(1)+ val finished = CountDownLatch(1)+ val failure = AtomicReference<Throwable?>()++ val secondary = Thread {+ entered.countDown()+ try {+ adjuster.sharedInitializeOrWait(+ /* canInitialize= */ false,+ /* nextSampleTimestampUs= */ C.TIME_UNSET,+ /* timeoutMs= */ 0L+ )+ } catch (error: Throwable) {+ failure.set(error)+ } finally {+ finished.countDown()+ }+ }.apply {+ name = "timestamp-adjuster-cancel-test"+ isDaemon = true+ }++ secondary.start()+ try {+ assertThat(entered.await(1, TimeUnit.SECONDS)).isTrue()+ awaitWaitingState(secondary)+ secondary.interrupt()++ assertThat(finished.await(1, TimeUnit.SECONDS)).isTrue()+ secondary.join(1_000)+ assertThat(failure.get()).isInstanceOf(InterruptedException::class.java)+ assertThat(adjuster.isInitialized).isFalse()+ } finally {+ secondary.interrupt()+ secondary.join(1_000)+ }+ }++ private fun awaitWaitingState(thread: Thread, allowTimedWait: Boolean = false) {+ val deadlineNs = System.nanoTime() + TimeUnit.SECONDS.toNanos(2)+ fun waiting() = thread.state == Thread.State.WAITING ||+ allowTimedWait && thread.state == Thread.State.TIMED_WAITING+ while (!waiting() && System.nanoTime() < deadlineNs) {+ Thread.yield()+ }+ assertThat(waiting()).isTrue()+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackBufferPoliciesTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackBufferPoliciesTest.ktindex 245c040b..6d441ef6 100644--- a/player/src/test/java/com/streamvault/player/playback/PlaybackBufferPoliciesTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackBufferPoliciesTest.kt@@ -85,6 +85,115 @@ class PlaybackBufferPoliciesTest {}}+ @Test+ fun `manual raw TS live retains existing buffer ceilings with a two second loading window`() {+ for (lowMemory in listOf(false, true)) {+ for (mode in listOf(PlaybackBufferMode.MEDIUM, PlaybackBufferMode.LARGE)) {+ val actual = PlaybackBufferPolicies.forPlayback(+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,+ compatibilityMode = false,+ lowMemoryDevice = lowMemory,+ bufferMode = mode,+ streamInfo = StreamInfo(+ url = "http://fixture.invalid/live.ts",+ streamType = StreamType.MPEG_TS,+ playbackContentKind = PlaybackContentKind.LIVE+ )+ )+ val expected = when (mode) {+ PlaybackBufferMode.MEDIUM -> PlaybackBufferPolicy(+ label = "medium-live",+ minBufferMs = 43_000,+ maxBufferMs = 45_000,+ playbackBufferMs = 3_000,+ rebufferMs = 10_000,+ targetBufferBytes = 32 * 1024 * 1024,+ prioritizeTimeOverSizeThresholds = false,+ qualityReason = "user-medium"+ )+ PlaybackBufferMode.LARGE -> PlaybackBufferPolicy(+ label = "large-live",+ minBufferMs = 88_000,+ maxBufferMs = 90_000,+ playbackBufferMs = 5_000,+ rebufferMs = 15_000,+ targetBufferBytes = 64 * 1024 * 1024,+ prioritizeTimeOverSizeThresholds = false,+ qualityReason = "user-large"+ )+ else -> error("Only manual modes belong in this assertion")+ }++ assertEquals("$mode / lowMemory=$lowMemory", expected, actual)+ }+ }+ }++ @Test+ fun `manual mode ceilings stay unchanged for non-raw formats and non-live content`() {+ val liveFormats = listOf(+ ResolvedStreamType.HLS to StreamType.HLS,+ ResolvedStreamType.DASH to StreamType.DASH,+ ResolvedStreamType.SMOOTH_STREAMING to StreamType.SMOOTH_STREAMING,+ ResolvedStreamType.PROGRESSIVE to StreamType.PROGRESSIVE,+ ResolvedStreamType.RTSP to StreamType.RTSP+ )+ for ((resolvedType, declaredType) in liveFormats) {+ for (lowMemory in listOf(false, true)) {+ for (mode in listOf(PlaybackBufferMode.MEDIUM, PlaybackBufferMode.LARGE)) {+ val actual = PlaybackBufferPolicies.forPlayback(+ resolvedStreamType = resolvedType,+ compatibilityMode = false,+ lowMemoryDevice = lowMemory,+ bufferMode = mode,+ streamInfo = StreamInfo(+ url = "https://example.invalid/live/content",+ streamType = declaredType,+ playbackContentKind = PlaybackContentKind.LIVE+ )+ )++ assertEquals(+ "$resolvedType / $mode / lowMemory=$lowMemory",+ expectedPolicy(PlaybackContentKind.LIVE, resolvedType, lowMemory, mode),+ actual+ )+ assertThat(actual.maxBufferMs).isEqualTo(+ if (mode == PlaybackBufferMode.MEDIUM) 45_000 else 90_000+ )+ }+ }+ }++ for (kind in listOf(PlaybackContentKind.ON_DEMAND, PlaybackContentKind.CATCH_UP)) {+ for (lowMemory in listOf(false, true)) {+ for (mode in listOf(PlaybackBufferMode.MEDIUM, PlaybackBufferMode.LARGE)) {+ val info = StreamInfo(+ url = "http://fixture.invalid/archive.ts",+ streamType = StreamType.MPEG_TS,+ playbackContentKind = kind+ )+ val actual = PlaybackBufferPolicies.forPlayback(+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,+ compatibilityMode = false,+ lowMemoryDevice = lowMemory,+ bufferMode = mode,+ streamInfo = info+ )+ val automatic = PlaybackBufferPolicies.forPlayback(+ resolvedStreamType = ResolvedStreamType.MPEG_TS_LIVE,+ compatibilityMode = false,+ lowMemoryDevice = lowMemory,+ bufferMode = PlaybackBufferMode.AUTO,+ streamInfo = info+ )++ assertEquals("$kind / lowMemory=$lowMemory / $mode", automatic, actual)+ }+ }+ }+ }+private fun expectedPolicy(kind: PlaybackContentKind,resolvedType: ResolvedStreamType,@@ -103,7 +212,7 @@ class PlaybackBufferPoliciesTest {}if (live && mode == PlaybackBufferMode.MEDIUM) {- return PlaybackBufferPolicy(+ val policy = PlaybackBufferPolicy(label = "medium-live",minBufferMs = 15_000,maxBufferMs = 45_000,@@ -113,9 +222,14 @@ class PlaybackBufferPoliciesTest {prioritizeTimeOverSizeThresholds = false,qualityReason = "user-medium")+ return if (live && resolvedType == ResolvedStreamType.MPEG_TS_LIVE) {+ policy.copy(minBufferMs = 43_000)+ } else {+ policy+ }}if (live && mode == PlaybackBufferMode.LARGE) {- return PlaybackBufferPolicy(+ val policy = PlaybackBufferPolicy(label = "large-live",minBufferMs = 30_000,maxBufferMs = 90_000,@@ -125,6 +239,11 @@ class PlaybackBufferPoliciesTest {prioritizeTimeOverSizeThresholds = false,qualityReason = "user-large")+ return if (live && resolvedType == ResolvedStreamType.MPEG_TS_LIVE) {+ policy.copy(minBufferMs = 88_000)+ } else {+ policy+ }}if (!live && resolvedType == ResolvedStreamType.HLS) {@@ -492,7 +611,7 @@ class PlaybackBufferPoliciesTest {)assertThat(policy.label).isEqualTo("medium-live")- assertThat(policy.minBufferMs).isEqualTo(15_000)+ assertThat(policy.minBufferMs).isEqualTo(43_000)assertThat(policy.maxBufferMs).isEqualTo(45_000)assertThat(policy.targetBufferBytes).isEqualTo(32 * 1024 * 1024)}diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackLoadControlTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackLoadControlTest.ktindex 398eee8a..9bf5ef55 100644--- a/player/src/test/java/com/streamvault/player/playback/PlaybackLoadControlTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackLoadControlTest.kt@@ -31,6 +31,24 @@ class PlaybackLoadControlTest {MediaItem.fromUri("https://example.invalid/fixture.m3u8"))+ @Test+ fun `allocation diagnostics remain safe after the playback thread releases the player`() {+ val control = PlaybackLoadControl(policy, 192L * MIB, false)+ val id = PlayerId.UNSET+ val selection = fixedVideo(20_000_000)+ val parameters = LoadControl.Parameters(+ id, timeline, MediaSource.MediaPeriodId(timeline.getUidOfPeriod(0)),+ 0L, 0L, 1f, true, false, C.TIME_UNSET, C.TIME_UNSET+ )+ control.onPrepared(id)+ control.onTracksSelected(parameters, TrackGroupArray(selection.trackGroup), arrayOf(selection))+ control.shouldContinueLoading(parameters)+ assertThat(control.describeAllocation()).contains("allocatedBytes=0")+ control.onReleased(id)+ // Transition callbacks may run after playback-thread release. They must not query its allocator.+ assertThat(control.describeAllocation()).contains("allocatedBytes=unknown")+ }+@Testfun `high bitrate playback keeps loading past the old 32 MiB restriction`() {assertThat(loadingAfter(48, 192, fixedVideo(80_000_000))).isTrue()diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicyTest.ktindex 742709ea..481fcfd4 100644--- a/player/src/test/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicyTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackStallRecoveryPolicyTest.kt@@ -2,9 +2,64 @@ package com.streamvault.player.playbackimport com.google.common.truth.Truth.assertThatimport com.streamvault.domain.model.PlaybackContentKind+import com.streamvault.player.PlaybackStateimport org.junit.Testclass PlaybackStallRecoveryPolicyTest {+ @Test+ fun `startup grace does not consume the first buffering stall after recovery`() {+ var nowMs = 1L+ val detector = VideoStallDetector(nowMs = { nowMs })+ detector.reset()++ fun evaluate(graceActive: Boolean): Boolean {+ val deferred = shouldDeferAppStallRecovery(+ activeMediaLoadRetry = false,+ sourceRetryPending = false+ )+ return detector.shouldReportStall(+ playbackState = PlaybackState.BUFFERING,+ isPlaying = false,+ playbackStarted = true, // Recovery is armed from prior playback.+ currentPositionMs = 0L,+ bufferedDurationMs = 0L,+ playWhenReady = true,+ recoverBufferingStalls = !deferred,+ deferReporting = graceActive+ )+ }++ nowMs = 9_001L+ assertThat(evaluate(graceActive = true)).isFalse()+ nowMs = 15_001L+ assertThat(evaluate(graceActive = false)).isTrue()+ assertThat(evaluate(graceActive = false)).isFalse()+ }++ @Test+ fun `active refill after startup grace still protects valid buffering`() {+ var nowMs = 1L+ val detector = VideoStallDetector(nowMs = { nowMs })+ detector.reset()+ for (second in 1..30) {+ nowMs = second * 1_000L + 1L+ val deferred = shouldDeferAppStallRecovery(+ activeMediaLoadRetry = false,+ sourceRetryPending = false+ )+ assertThat(detector.shouldReportStall(+ playbackState = PlaybackState.BUFFERING,+ isPlaying = false,+ playbackStarted = true,+ currentPositionMs = 0L,+ bufferedDurationMs = second * 1_000L,+ playWhenReady = true,+ recoverBufferingStalls = !deferred,+ deferReporting = second < 15+ )).isFalse()+ }+ }+@Testfun `pending Media3 load retry defers app level stall recovery`() {assertThat(diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackTransferTrackerTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackTransferTrackerTest.ktnew file mode 100644index 00000000..fef07a9f--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackTransferTrackerTest.kt@@ -0,0 +1,148 @@+@file:androidx.media3.common.util.UnstableApi++package com.streamvault.player.playback++import android.net.Uri+import androidx.media3.datasource.DataSource+import androidx.media3.datasource.DataSpec+import androidx.media3.datasource.TransferListener+import com.google.common.truth.Truth.assertThat+import java.io.IOException+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicReference+import org.junit.Assert.assertThrows+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class PlaybackTransferTrackerTest {+ @Test+ fun `tracks only HTTP and HTTPS transfers from open until close`() {+ val delegates = mutableListOf<TestDataSource>()+ val tracker = PlaybackTransferTracker()+ val wrapped = tracker.wrap(DataSource.Factory {+ TestDataSource().also(delegates::add)+ })++ val http = wrapped.createDataSource()+ http.open(DataSpec(Uri.parse("http://fixture.test/live.m3u8")))+ assertThat(tracker.hasActiveTransfers).isTrue()+ http.close()+ assertThat(tracker.hasActiveTransfers).isFalse()++ val https = wrapped.createDataSource()+ https.open(DataSpec(Uri.parse("https://fixture.test/segment.ts")))+ assertThat(tracker.hasActiveTransfers).isTrue()+ https.close()+ assertThat(tracker.hasActiveTransfers).isFalse()++ val file = wrapped.createDataSource()+ file.open(DataSpec(Uri.parse("file:///tmp/local.ts")))+ assertThat(tracker.hasActiveTransfers).isFalse()+ file.close()+ assertThat(delegates).hasSize(3)+ }++ @Test+ fun `failed HTTP open preserves open error and suppressed close error`() {+ val delegate = TestDataSource(+ openFailure = IOException("fixture open failed"),+ failFirstClose = true+ )+ val tracker = PlaybackTransferTracker()+ val source = tracker.wrap(DataSource.Factory { delegate }).createDataSource()++ val openFailure = assertThrows(IOException::class.java) {+ source.open(DataSpec(Uri.parse("http://fixture.test/broken")))+ }++ assertThat(delegate.closeCalls).isEqualTo(1)+ assertThat(openFailure.message).isEqualTo("fixture open failed")+ assertThat(openFailure.suppressed.map { it.message }).containsExactly("delegate close failed")+ assertThat(tracker.hasActiveTransfers).isTrue()++ source.close()+ assertThat(tracker.hasActiveTransfers).isFalse()+ }++ @Test+ fun `transfer remains active until delegate close has actually returned`() {+ val closeEntered = CountDownLatch(1)+ val allowClose = CountDownLatch(1)+ val closeFailure = AtomicReference<Throwable?>(null)+ val delegate = TestDataSource(onClose = {+ closeEntered.countDown()+ check(allowClose.await(2, TimeUnit.SECONDS)) { "test did not release delegate close" }+ })+ val tracker = PlaybackTransferTracker()+ val source = tracker.wrap(DataSource.Factory { delegate }).createDataSource()+ source.open(DataSpec(Uri.parse("http://fixture.test/slow-close")))++ val closingThread = Thread {+ try {+ source.close()+ } catch (failure: Throwable) {+ closeFailure.set(failure)+ }+ }+ closingThread.start()+ try {+ assertThat(closeEntered.await(1, TimeUnit.SECONDS)).isTrue()+ assertThat(tracker.hasActiveTransfers).isTrue()+ } finally {+ allowClose.countDown()+ closingThread.join(2_000)+ }++ assertThat(closingThread.isAlive).isFalse()+ assertThat(closeFailure.get()).isNull()+ assertThat(tracker.hasActiveTransfers).isFalse()+ }++ @Test+ fun `failed delegate close stays tracked until a later close succeeds`() {+ val delegate = TestDataSource(failFirstClose = true)+ val tracker = PlaybackTransferTracker()+ val source = tracker.wrap(DataSource.Factory { delegate }).createDataSource()+ source.open(DataSpec(Uri.parse("https://fixture.test/slow-cancel")))++ assertThrows(IOException::class.java) { source.close() }+ assertThat(tracker.hasActiveTransfers).isTrue()++ source.close()+ assertThat(tracker.hasActiveTransfers).isFalse()+ assertThat(delegate.closeCalls).isEqualTo(2)+ }++ private class TestDataSource(+ private val openFailure: IOException? = null,+ private val onClose: () -> Unit = {},+ failFirstClose: Boolean = false+ ) : DataSource {+ var closeCalls = 0+ private set+ private var shouldFailFirstClose = failFirstClose++ override fun addTransferListener(transferListener: TransferListener) = Unit++ override fun open(dataSpec: DataSpec): Long {+ openFailure?.let { throw it }+ return 0L+ }++ override fun read(buffer: ByteArray, offset: Int, length: Int): Int = -1++ override fun getUri(): Uri? = null++ override fun close() {+ closeCalls+++ if (shouldFailFirstClose) {+ shouldFailFirstClose = false+ throw IOException("delegate close failed")+ }+ onClose()+ }+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.ktindex 8fe1a49d..cde084c8 100644--- a/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/PlayerMediaSourceFactoryTest.kt@@ -2,7 +2,12 @@ package com.streamvault.player.playbackimport androidx.media3.exoplayer.source.ProgressiveMediaSourceimport androidx.media3.extractor.ts.TsExtractor+import androidx.media3.exoplayer.hls.HlsMediaSource+import androidx.media3.exoplayer.source.DefaultCompositeSequenceableLoaderFactory+import androidx.media3.common.Cimport com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.PlaybackBufferMode+import com.streamvault.domain.model.PlaybackContentKindimport com.streamvault.domain.model.StreamInfoimport com.streamvault.domain.model.StreamTypeimport com.streamvault.domain.model.DrmInfo@@ -18,6 +23,38 @@ import org.robolectric.RuntimeEnvironment@RunWith(RobolectricTestRunner::class)class PlayerMediaSourceFactoryTest {+ @Test+ fun `live hls foreground and preload wire optional rendition policy while finite hls stays default`() {+ val dataSourceProvider = dataSourceProvider()+ val sourceFactory = PlayerMediaSourceFactory(dataSourceProvider)+ val live = liveHls()+ val retryPolicy = PlayerRetryPolicy(+ streamContext = PlaybackRetryContext(+ resolvedStreamType = ResolvedStreamType.HLS,+ timeoutProfile = PlayerTimeoutProfile.LIVE,+ playbackContentKind = PlaybackContentKind.LIVE+ ),+ playbackStarted = { false }+ )++ val foreground = sourceFactory.createMediaSourceFactory(+ live, ResolvedStreamType.HLS, retryPolicy, preload = false+ ).second as HlsMediaSource.Factory+ val preload = sourceFactory.createMediaSourceFactory(+ live, ResolvedStreamType.HLS, retryPolicy, preload = true+ ).second as HlsMediaSource.Factory+ val finite = sourceFactory.createMediaSourceFactory(+ liveHls(PlaybackContentKind.ON_DEMAND), ResolvedStreamType.HLS, retryPolicy, preload = false+ ).second as HlsMediaSource.Factory++ assertThat(compositeLoaderFactory(foreground))+ .isInstanceOf(InFlightOptionalRenditionLoaderFactory::class.java)+ assertThat(compositeLoaderFactory(preload))+ .isInstanceOf(InFlightOptionalRenditionLoaderFactory::class.java)+ assertThat(compositeLoaderFactory(finite))+ .isInstanceOf(DefaultCompositeSequenceableLoaderFactory::class.java)+ }+@Testfun `direct live mpeg ts policy declares single pmt and live duration`() {assertThat(DIRECT_LIVE_MPEG_TS_POLICY.extractorMode)@@ -89,4 +126,152 @@ class PlayerMediaSourceFactoryTest {assertThat(drmConfiguration).isNotNull()assertThat(drmConfiguration?.licenseUri?.toString().orEmpty()).isEmpty()}++ @Test+ fun `explicit medium and large live hls modes request parser floor without media item bounds`() {+ val dataSourceProvider = dataSourceProvider()+ val streamInfo = liveHls()++ for (mode in listOf(PlaybackBufferMode.MEDIUM, PlaybackBufferMode.LARGE)) {+ val item = PlayerMediaSourceFactory(dataSourceProvider) { mode }+ .mediaItemFor(streamInfo, ResolvedStreamType.HLS)++ assertThat(PlayerMediaSourceFactory(dataSourceProvider) { mode }+ .liveTargetOffsetMsFor(streamInfo, ResolvedStreamType.HLS)).isEqualTo(10_000L)+ assertThat(item.liveConfiguration?.targetOffsetMs).isEqualTo(C.TIME_UNSET)+ assertThat(item.liveConfiguration?.minPlaybackSpeed).isEqualTo(C.RATE_UNSET)+ assertThat(item.liveConfiguration?.maxPlaybackSpeed).isEqualTo(C.RATE_UNSET)+ assertThat(item.liveConfiguration?.minOffsetMs).isEqualTo(C.TIME_UNSET)+ assertThat(item.liveConfiguration?.maxOffsetMs).isEqualTo(C.TIME_UNSET)+ }+ }++ @Test+ fun `auto and small modes leave live hls configuration unchanged`() {+ val dataSourceProvider = dataSourceProvider()+ val streamInfo = liveHls()+ val defaultItem = PlayerMediaSourceFactory(dataSourceProvider)+ .mediaItemFor(streamInfo, ResolvedStreamType.HLS)++ for (mode in listOf(PlaybackBufferMode.AUTO, PlaybackBufferMode.SMALL)) {+ val item = PlayerMediaSourceFactory(dataSourceProvider) { mode }+ .mediaItemFor(streamInfo, ResolvedStreamType.HLS)++ assertThat(item.liveConfiguration).isEqualTo(defaultItem.liveConfiguration)+ assertThat(item.liveConfiguration?.targetOffsetMs).isEqualTo(C.TIME_UNSET)+ }+ }++ @Test+ fun `live target applies only to known live content resolved as hls`() {+ val factory = PlayerMediaSourceFactory(dataSourceProvider()) { PlaybackBufferMode.MEDIUM }+ val cases = listOf(+ liveHls(PlaybackContentKind.ON_DEMAND) to ResolvedStreamType.HLS,+ liveHls(PlaybackContentKind.CATCH_UP) to ResolvedStreamType.HLS,+ liveHls(PlaybackContentKind.UNKNOWN) to ResolvedStreamType.HLS,+ liveHls() to ResolvedStreamType.DASH,+ liveTs() to ResolvedStreamType.MPEG_TS_LIVE,+ liveHls() to ResolvedStreamType.UNKNOWN+ )++ cases.forEach { (streamInfo, resolvedType) ->+ assertThat(factory.mediaItemFor(streamInfo, resolvedType).liveConfiguration?.targetOffsetMs)+ .isEqualTo(C.TIME_UNSET)+ }+ }++ @Test+ fun `manual live hls target separates media ids while medium and large share identity`() {+ val dataSourceProvider = dataSourceProvider()+ val streamInfo = liveHls()+ val defaultId = PlayerMediaSourceFactory(dataSourceProvider)+ .mediaIdFor(streamInfo, ResolvedStreamType.HLS)+ val mediumId = PlayerMediaSourceFactory(dataSourceProvider) { PlaybackBufferMode.MEDIUM }+ .mediaIdFor(streamInfo, ResolvedStreamType.HLS)+ val largeId = PlayerMediaSourceFactory(dataSourceProvider) { PlaybackBufferMode.LARGE }+ .mediaIdFor(streamInfo, ResolvedStreamType.HLS)+ val vod = streamInfo.copy(playbackContentKind = PlaybackContentKind.ON_DEMAND)+ val mediumVodId = PlayerMediaSourceFactory(dataSourceProvider) { PlaybackBufferMode.MEDIUM }+ .mediaIdFor(vod, ResolvedStreamType.HLS)++ assertThat(mediumId).isNotEqualTo(defaultId)+ assertThat(largeId).isEqualTo(mediumId)+ assertThat(mediumVodId)+ .isEqualTo(PlayerMediaSourceFactory(dataSourceProvider).mediaIdFor(vod, ResolvedStreamType.HLS))+ }++ @Test+ fun `target-aware source ids do not change compatibility identity across mode switches`() {+ val dataSourceProvider = dataSourceProvider()+ val streamInfo = liveHls()+ var mode = PlaybackBufferMode.AUTO+ val factory = PlayerMediaSourceFactory(dataSourceProvider) { mode }+ val legacyId = factory.compatibilityMediaIdFor(streamInfo)+ val autoSourceId = factory.mediaIdFor(streamInfo, ResolvedStreamType.HLS)++ mode = PlaybackBufferMode.MEDIUM+ val mediumSourceId = factory.mediaIdFor(streamInfo, ResolvedStreamType.HLS)+ val mediumCompatibilityId = factory.compatibilityMediaIdFor(streamInfo)+ mode = PlaybackBufferMode.LARGE+ val largeSourceId = factory.mediaIdFor(streamInfo, ResolvedStreamType.HLS)++ assertThat(autoSourceId).isEqualTo(legacyId)+ assertThat(mediumCompatibilityId).isEqualTo(legacyId)+ assertThat(factory.compatibilityMediaIdFor(streamInfo)).isEqualTo(legacyId)+ assertThat(mediumSourceId).isNotEqualTo(autoSourceId)+ assertThat(largeSourceId).isEqualTo(mediumSourceId)+ assertThat(largeSourceId).isNotEqualTo(legacyId)+ }++ @Test+ fun `manual live hls parser floor preserves request headers and drm configuration`() {+ val dataSourceProvider = dataSourceProvider()+ val drm = DrmInfo(+ scheme = DrmScheme.WIDEVINE,+ licenseUrl = "https://license.example.test/widevine",+ headers = mapOf("X-License-Token" to "test-token")+ )+ val streamInfo = liveHls().copy(+ headers = mapOf("Authorization" to "Bearer test-token"),+ drmInfo = drm+ )+ val item = PlayerMediaSourceFactory(dataSourceProvider) { PlaybackBufferMode.MEDIUM }+ .mediaItemFor(streamInfo, ResolvedStreamType.HLS)+ val drmConfiguration = item.localConfiguration?.drmConfiguration++ assertThat(item.localConfiguration?.uri?.toString()).isEqualTo(streamInfo.url)+ assertThat(drmConfiguration?.licenseUri?.toString()).isEqualTo(drm.licenseUrl)+ assertThat(drmConfiguration?.licenseRequestHeaders).isEqualTo(drm.headers)+ assertThat(item.liveConfiguration?.targetOffsetMs).isEqualTo(C.TIME_UNSET)+ assertThat(PlayerMediaSourceFactory(dataSourceProvider) { PlaybackBufferMode.MEDIUM }+ .liveTargetOffsetMsFor(streamInfo, ResolvedStreamType.HLS)).isEqualTo(10_000L)+ }++ private fun dataSourceProvider() = PlayerDataSourceFactoryProvider(+ context = RuntimeEnvironment.getApplication(),+ baseClient = OkHttpClient()+ )++ private fun liveHls(+ contentKind: PlaybackContentKind = PlaybackContentKind.LIVE+ ) = StreamInfo(+ url = "https://example.test/live/channel.m3u8",+ streamType = StreamType.HLS,+ containerExtension = "m3u8",+ playbackContentKind = contentKind+ )++ private fun liveTs() = StreamInfo(+ url = "https://example.test/live/channel.ts",+ streamType = StreamType.MPEG_TS,+ containerExtension = "ts",+ playbackContentKind = PlaybackContentKind.LIVE+ )++ private fun compositeLoaderFactory(factory: HlsMediaSource.Factory): Any {+ val field = HlsMediaSource.Factory::class.java+ .getDeclaredField("compositeSequenceableLoaderFactory")+ field.isAccessible = true+ return requireNotNull(field.get(factory))+ }}diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.ktindex 0be77b90..3912cfa0 100644--- a/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/PlayerRetryPolicyTest.kt@@ -257,6 +257,129 @@ class PlayerRetryPolicyTest {assertThat(fallback?.type).isEqualTo(LoadErrorHandlingPolicy.FALLBACK_TYPE_LOCATION)}+ @Test+ fun `post-start live hls media refusals get one fast load retry then one source retry`() {+ var started = true+ val observed = PlayerRetryPolicy(liveContext, playbackStarted = { started })++ for (status in listOf(403, 404, 410)) {+ val first = loadError(responseCode = status, errorCount = 1)+ assertThat(observed.getRetryDelayMsFor(first)).isEqualTo(500L)+ assertThat(observed.hasPendingLoadRecovery).isTrue()+ observed.onLoadTaskConcluded(first.loadEventInfo.loadTaskId)+ assertThat(observed.hasPendingLoadRecovery).isFalse()++ val exhausted = loadError(responseCode = status, errorCount = 2, exception = first.exception)+ assertThat(observed.getRetryDelayMsFor(exhausted)).isEqualTo(C.TIME_UNSET)+ assertThat(observed.isLiveMediaRefusal(first.exception)).isTrue()+ assertThat(observed.retryReason(first.exception)).isEqualTo("refresh-live-media-playlist")+ assertThat(observed.retryDelayMs(first.exception, 1)).isEqualTo(500L)+ assertThat(observed.maxWholeSourceRetryAttempts(first.exception, playbackStarted = true)).isEqualTo(1)+ assertThat(observed.shouldRetryWholeSource(first.exception, playbackStarted = true, attempt = 1)).isTrue()+ assertThat(observed.shouldRetryWholeSource(first.exception, playbackStarted = true, attempt = 2)).isFalse()+ }+ }++ @Test+ fun `media refusal recovery is tied to the exhausted exception identity`() {+ val observed = PlayerRetryPolicy(liveContext, playbackStarted = { true })+ val first = loadError(responseCode = 403, errorCount = 1)+ observed.getRetryDelayMsFor(first)+ val exhausted = loadError(responseCode = 403, errorCount = 2, exception = first.exception)++ assertThat(observed.getRetryDelayMsFor(exhausted)).isEqualTo(C.TIME_UNSET)+ val sameFailureWrapped = IOException("player source error", first.exception)+ val another403 = loadError(responseCode = 403, errorCount = 2).exception+ assertThat(observed.isLiveMediaRefusal(sameFailureWrapped)).isTrue()+ assertThat(observed.shouldRetryWholeSource(sameFailureWrapped, playbackStarted = true, attempt = 1)).isTrue()+ assertThat(observed.isLiveMediaRefusal(another403)).isFalse()+ assertThat(observed.shouldRetryWholeSource(another403, playbackStarted = true, attempt = 1)).isFalse()+ assertThat(observed.shouldRetryWholeSource(IOException("HTTP 403"), playbackStarted = true, attempt = 1))+ .isFalse()+ }++ @Test+ fun `only post-start live hls media refusal is eligible for contextual retry`() {+ val manifest403 = loadError(responseCode = 403, dataType = C.DATA_TYPE_MANIFEST, errorCount = 2)+ assertMediaRefusalNotEligible(manifest403)++ val drm403 = loadError(responseCode = 403, dataType = C.DATA_TYPE_DRM, errorCount = 2)+ assertMediaRefusalNotEligible(drm403)++ val startupPolicy = PlayerRetryPolicy(liveContext, playbackStarted = { false })+ val media403 = loadError(responseCode = 403, errorCount = 1)+ assertThat(startupPolicy.getRetryDelayMsFor(media403)).isEqualTo(C.TIME_UNSET)+ assertThat(startupPolicy.isLiveMediaRefusal(media403.exception)).isFalse()+ assertThat(startupPolicy.shouldRetryWholeSource(media403.exception, playbackStarted = false, attempt = 1))+ .isFalse()++ val vodContext = PlaybackRetryContext(+ resolvedStreamType = ResolvedStreamType.HLS,+ timeoutProfile = PlayerTimeoutProfile.VOD,+ playbackContentKind = PlaybackContentKind.ON_DEMAND+ )+ val vodPolicy = PlayerRetryPolicy(vodContext, playbackStarted = { true })+ val vodMedia403 = loadError(responseCode = 403, errorCount = 1)+ assertThat(vodPolicy.getRetryDelayMsFor(vodMedia403)).isEqualTo(C.TIME_UNSET)+ assertThat(vodPolicy.isLiveMediaRefusal(vodMedia403.exception)).isFalse()+ assertThat(vodPolicy.shouldRetryWholeSource(vodMedia403.exception, playbackStarted = true, attempt = 1))+ .isFalse()++ val dashContext = PlaybackRetryContext(+ resolvedStreamType = ResolvedStreamType.DASH,+ timeoutProfile = PlayerTimeoutProfile.LIVE,+ playbackContentKind = PlaybackContentKind.LIVE+ )+ val dashPolicy = PlayerRetryPolicy(dashContext, playbackStarted = { true })+ val dashMedia403 = loadError(responseCode = 403, errorCount = 1)+ assertThat(dashPolicy.getRetryDelayMsFor(dashMedia403)).isEqualTo(C.TIME_UNSET)+ assertThat(dashPolicy.isLiveMediaRefusal(dashMedia403.exception)).isFalse()+ assertThat(dashPolicy.shouldRetryWholeSource(dashMedia403.exception, playbackStarted = true, attempt = 1))+ .isFalse()+ }++ @Test+ fun `excluded refusal codes keep their existing policy and do not authorize source refresh`() {+ val observed = PlayerRetryPolicy(liveContext, playbackStarted = { true })+ for (status in listOf(401, 456, 509)) {+ val error = loadError(responseCode = status, errorCount = 1)+ assertThat(observed.getRetryDelayMsFor(error)).isEqualTo(C.TIME_UNSET)+ assertThat(observed.isLiveMediaRefusal(error.exception)).isFalse()+ assertThat(observed.shouldRetryWholeSource(error.exception, playbackStarted = true, attempt = 1)).isFalse()+ }++ val outsideSet410 = loadError(responseCode = 410, dataType = C.DATA_TYPE_DRM, errorCount = 2)+ assertThat(observed.getRetryDelayMsFor(outsideSet410)).isEqualTo(observed.retryDelayMs(outsideSet410.exception, 2))+ assertThat(observed.isLiveMediaRefusal(outsideSet410.exception)).isFalse()+ assertThat(observed.retryReason(outsideSet410.exception)).isNotEqualTo("refresh-live-media-playlist")+ }++ @Test+ fun `bounded exhausted media refusal context survives load completion and evicts oldest identity`() {+ val observed = PlayerRetryPolicy(liveContext, playbackStarted = { true })+ val errors = (0..8).map { index ->+ val first = loadError(responseCode = 403, errorCount = 1)+ observed.getRetryDelayMsFor(first)+ observed.onLoadTaskConcluded(first.loadEventInfo.loadTaskId)+ val exhausted = loadError(responseCode = 403, errorCount = 2, exception = first.exception)+ observed.getRetryDelayMsFor(exhausted)+ first.exception+ }++ assertThat(observed.isLiveMediaRefusal(errors.first())).isFalse()+ assertThat(errors.drop(1).all(observed::isLiveMediaRefusal)).isTrue()+ assertThat(errors.drop(1).all {+ observed.shouldRetryWholeSource(it, playbackStarted = true, attempt = 1)+ }).isTrue()+ }++ private fun assertMediaRefusalNotEligible(errorInfo: LoadErrorHandlingPolicy.LoadErrorInfo) {+ val observed = PlayerRetryPolicy(liveContext, playbackStarted = { true })+ assertThat(observed.getRetryDelayMsFor(errorInfo)).isEqualTo(C.TIME_UNSET)+ assertThat(observed.isLiveMediaRefusal(errorInfo.exception)).isFalse()+ assertThat(observed.shouldRetryWholeSource(errorInfo.exception, playbackStarted = true, attempt = 1)).isFalse()+ }+@Testfun `eligible server error falls back to an available track when no alternate location exists`() {val selection = policy.getFallbackSelectionFor(@@ -407,11 +530,16 @@ class PlayerRetryPolicyTest {private fun fallbackOptions(locations: Int, tracks: Int) =LoadErrorHandlingPolicy.FallbackOptions(locations, 0, tracks, 0, false)- private fun loadError(responseCode: Int): LoadErrorHandlingPolicy.LoadErrorInfo {+ private fun loadError(+ responseCode: Int,+ dataType: Int = C.DATA_TYPE_MEDIA,+ errorCount: Int = 1,+ exception: IOException? = null+ ): LoadErrorHandlingPolicy.LoadErrorInfo {val dataSpec = DataSpec.Builder().setUri("https://example.com/manifest.m3u8").build()- val exception = HttpDataSource.InvalidResponseCodeException(+ val failure = exception ?: HttpDataSource.InvalidResponseCodeException(responseCode,null,null,@@ -422,9 +550,9 @@ class PlayerRetryPolicyTest {val loadEventInfo = LoadEventInfo.Builder(LoadEventInfo.getNewId(), dataSpec, 0L).build()return LoadErrorHandlingPolicy.LoadErrorInfo(loadEventInfo,- MediaLoadData(C.DATA_TYPE_MEDIA),- exception,- 1+ MediaLoadData(dataType),+ failure,+ errorCount)}}diff --git a/player/src/test/java/com/streamvault/player/playback/StartupRefreshGateTest.kt b/player/src/test/java/com/streamvault/player/playback/StartupRefreshGateTest.ktnew file mode 100644index 00000000..02e8a991--- /dev/null+++ b/player/src/test/java/com/streamvault/player/playback/StartupRefreshGateTest.kt@@ -0,0 +1,105 @@+package com.streamvault.player.playback++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class StartupRefreshGateTest {+ @Test+ fun `drain completion requires a stable quiet interval`() {+ val gate = StartupRefreshGate()+ gate.begin(100L)++ assertThat(gate.evaluate(100L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(599L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.isPending).isTrue()+ assertThat(gate.evaluate(600L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.READY)+ assertThat(gate.isPending).isFalse()+ }++ @Test+ fun `new transfer during quiet interval restarts the quiet clock`() {+ val gate = StartupRefreshGate()+ gate.begin(0L)++ assertThat(gate.evaluate(0L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(499L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(500L, canResume = true, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(700L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(1_199L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(1_200L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.READY)+ }++ @Test+ fun `active transfers give up at the drain deadline`() {+ val gate = StartupRefreshGate(drainTimeoutMs = 25_000L, quietPeriodMs = 500L)+ gate.begin(1_000L)++ assertThat(gate.evaluate(25_999L, canResume = true, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(26_000L, canResume = true, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.GIVE_UP)+ assertThat(gate.isPending).isFalse()+ assertThat(gate.evaluate(30_000L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ }++ @Test+ fun `pause or output loss suspends drain clock but preserves pending refresh`() {+ val gate = StartupRefreshGate(drainTimeoutMs = 25_000L, quietPeriodMs = 500L)+ gate.begin(0L)++ assertThat(gate.evaluate(20_000L, canResume = false, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.isPending).isTrue()+ assertThat(gate.evaluate(1_000_000L, canResume = false, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.WAIT)++ // The bounded drain budget starts only when playback/output can resume.+ assertThat(gate.evaluate(1_000_000L, canResume = true, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(1_024_999L, canResume = true, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(1_025_000L, canResume = true, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.GIVE_UP)+ }++ @Test+ fun `not resumable without transfers pauses both timeout and quiet interval`() {+ val gate = StartupRefreshGate(drainTimeoutMs = 1_000L, quietPeriodMs = 500L)+ gate.begin(0L)++ assertThat(gate.evaluate(900L, canResume = false, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(50_000L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(50_499L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ assertThat(gate.evaluate(50_500L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.READY)+ }++ @Test+ fun `begin replaces previous timing state and clear cancels pending refresh`() {+ val gate = StartupRefreshGate(drainTimeoutMs = 1_000L, quietPeriodMs = 100L)+ gate.begin(0L)+ assertThat(gate.evaluate(900L, canResume = true, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.WAIT)++ gate.begin(10_000L)+ assertThat(gate.evaluate(10_999L, canResume = true, hasActiveTransfers = true))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ gate.clear()+ assertThat(gate.isPending).isFalse()+ assertThat(gate.evaluate(20_000L, canResume = true, hasActiveTransfers = false))+ .isEqualTo(StartupRefreshGate.Action.WAIT)+ }+}diff --git a/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt b/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.ktindex c4bc708a..829bba56 100644--- a/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/VideoStallDetectorTest.kt@@ -7,6 +7,79 @@ import org.junit.Testclass VideoStallDetectorTest {private var nowMs = 0L+ @Test+ fun `active refill can outlast frame silence but stalled refill still times out`() {+ val detector = VideoStallDetector(nowMs = { nowMs })+ detector.reset()+ nowMs = 1_000L+ detector.onVideoFrameRendered(500L)+ for (second in 2..14) {+ nowMs = second * 1_000L+ assertThat(detector.shouldReportStall(+ PlaybackState.BUFFERING, false, true, 500L, (second - 2) * 1_000L,+ playWhenReady = true, recoverBufferingStalls = true+ )).isFalse()+ }+ nowMs = 21_999L+ assertThat(detector.shouldReportStall(+ PlaybackState.BUFFERING, false, true, 500L, 12_000L,+ playWhenReady = true, recoverBufferingStalls = true+ )).isFalse()+ nowMs = 22_000L+ assertThat(detector.shouldReportStall(+ PlaybackState.BUFFERING, false, true, 500L, 12_000L,+ playWhenReady = true, recoverBufferingStalls = true+ )).isTrue()+ assertThat(detector.shouldReportStall(+ PlaybackState.BUFFERING, false, true, 500L, 12_000L,+ playWhenReady = true, recoverBufferingStalls = true+ )).isFalse()+ }++ @Test+ fun `reserve oscillation below previous maximum is not refill progress`() {+ val detector = VideoStallDetector(nowMs = { nowMs })+ detector.reset()+ nowMs = 1_000L+ detector.onVideoFrameRendered(500L)+ for ((time, reserve) in listOf(2_000L to 1_000L, 3_000L to 2_000L,+ 4_000L to 1_900L, 5_000L to 2_000L)) {+ nowMs = time+ assertThat(detector.shouldReportStall(+ PlaybackState.BUFFERING, false, true, 500L, reserve,+ playWhenReady = true, recoverBufferingStalls = true+ )).isFalse()+ }+ nowMs = 11_000L+ assertThat(detector.shouldReportStall(+ PlaybackState.BUFFERING, false, true, 500L, 2_000L,+ playWhenReady = true, recoverBufferingStalls = true+ )).isTrue()+ }++ @Test+ fun `refill progress does not suppress a ready decoder stall`() {+ val detector = VideoStallDetector(nowMs = { nowMs })+ detector.reset()+ nowMs = 1_000L+ detector.onVideoFrameRendered(500L)+ nowMs = 7_000L+ detector.shouldReportStall(+ PlaybackState.BUFFERING, false, true, 500L, 100L,+ playWhenReady = true, recoverBufferingStalls = true+ )+ nowMs = 8_000L+ detector.shouldReportStall(+ PlaybackState.BUFFERING, false, true, 500L, 4_000L,+ playWhenReady = true, recoverBufferingStalls = true+ )+ nowMs = 9_000L+ assertThat(detector.shouldReportStall(+ PlaybackState.READY, true, true, 9_000L, 4_000L,+ recoverFrameSilentReadyStalls = true+ )).isTrue()+ }+@Testfun `unsuccessful recovery is reported again after grace without inventing a rendered frame`() {val detector = detector()diff --git a/player/src/test/java/com/streamvault/player/stats/FrameRateDetectorTest.kt b/player/src/test/java/com/streamvault/player/stats/FrameRateDetectorTest.ktindex 5995bdff..888656d7 100644--- a/player/src/test/java/com/streamvault/player/stats/FrameRateDetectorTest.kt+++ b/player/src/test/java/com/streamvault/player/stats/FrameRateDetectorTest.kt@@ -2,14 +2,104 @@ package com.streamvault.player.statsimport com.google.common.truth.Truth.assertThatimport org.junit.Test+import kotlin.math.roundToLongclass FrameRateDetectorTest {+ @Test+ fun `millisecond rounded timestamps preserve broadcast cadence`() {+ for (rate in listOf(23.976f, 24f, 25f, 29.97f, 30f, 47.952f, 48f, 50f, 59.94f, 60f, 100f, 119.88f, 120f, 240f)) {+ val detector = FrameRateDetector()+ repeat(1500) { frame ->+ val pts = (frame * 1_000_000.0 / rate / 1000).roundToLong() * 1000+ detector.onFrame(pts)+ }+ assertThat(detector.lockedFrameRate).isEqualTo(rate)+ }+ }++ @Test+ fun `rounded timestamps with dropped frames retain fractional cadence`() {+ for (rate in listOf(29.97f, 59.94f, 60f)) {+ val detector = FrameRateDetector()+ var frame = 0L+ val strides = intArrayOf(2, 3, 1, 2, 1, 3, 1)+ repeat(600) { sample ->+ detector.onFrame((frame * 1_000_000.0 / rate / 1000).roundToLong() * 1000)+ frame += strides[sample % strides.size]+ }+ assertThat(detector.lockedFrameRate).isEqualTo(rate)+ }+ }++ @Test fun `rare single frame intervals do not make a high rate stream lock to half rate`() {+ for (rate in listOf(59.94f, 60f)) {+ val detector = FrameRateDetector()+ var frame = 0L+ repeat(600) { sample ->+ detector.onFrame((frame * 1_000_000.0 / rate / 1000).roundToLong() * 1000)+ frame += if (sample % 80 == 0) 1 else 2+ }+ assertThat(detector.lockedFrameRate).isEqualTo(rate)+ }+ }++ @Test+ fun `isolated short interval cannot determine the stream cadence`() {+ val detector = FrameRateDetector()+ var pts = 0L+ repeat(400) { frame ->+ detector.onFrame(pts)+ pts += when (frame) {+ 20 -> 8_000+ 21 -> 72_000+ else -> 40_000+ }+ }+ assertThat(detector.lockedFrameRate).isEqualTo(25f)+ }++ @Test fun `four seconds of timing and the requested sample count are both required`() {+ val detector = FrameRateDetector()+ feed(detector, intervalUs = 16_667, frames = 200)+ assertThat(detector.lockedFrameRate).isEqualTo(0f)+ feed(detector, intervalUs = 16_667, frames = 200, startUs = 200 * 16_667L)+ assertThat(detector.lockedFrameRate).isEqualTo(60f)++ val moreSamples = FrameRateDetector(framesToLock = 300)+ feed(moreSamples, intervalUs = 40_000, frames = 200)+ assertThat(moreSamples.lockedFrameRate).isEqualTo(0f)+ feed(moreSamples, intervalUs = 40_000, frames = 200, startUs = 8_000_000L)+ assertThat(moreSamples.lockedFrameRate).isEqualTo(25f)+ }++ @Test fun `duplicate timestamps do not erase valid observations`() {+ val detector = FrameRateDetector()+ repeat(400) { frame ->+ repeat(2) { detector.onFrame(frame * 20_000L) }+ }+ assertThat(detector.lockedFrameRate).isEqualTo(50f)+ }++ @Test fun `stable nonstandard cadence is retained but irregular timing stays unknown`() {+ val nonstandard = FrameRateDetector()+ feed(nonstandard, intervalUs = 25_000, frames = 400)+ assertThat(nonstandard.lockedFrameRate).isEqualTo(40f)+ val irregular = FrameRateDetector()+ val gaps = longArrayOf(20_000, 33_000, 47_000, 73_000)+ var pts = 0L+ repeat(1500) { frame ->+ irregular.onFrame(pts)+ pts += gaps[frame % gaps.size]+ }+ assertThat(irregular.lockedFrameRate).isEqualTo(0f)+ }+@Testfun `fractional timestamp cadences remain distinct from integer rates`() {for ((interval, expected) in listOf(41_708L to 23.976f, 33_367L to 29.97f, 16_683L to 59.94f)) {val detector = FrameRateDetector(framesToLock = 10)- feed(detector, intervalUs = interval, frames = 11)+ feed(detector, intervalUs = interval, frames = 600)assertThat(detector.lockedFrameRate).isEqualTo(expected)}}@@ -33,7 +123,7 @@ class FrameRateDetectorTest {@Testfun `locks to 25 fps for 40ms frame spacing`() {val detector = FrameRateDetector(framesToLock = 10)- feed(detector, intervalUs = 40_000, frames = 11)+ feed(detector, intervalUs = 40_000, frames = 200)assertThat(detector.lockedFrameRate).isEqualTo(25f)}@@ -43,7 +133,7 @@ class FrameRateDetectorTest {val detector = FrameRateDetector(framesToLock = 10)var pts = 0Lval jitter = longArrayOf(19_900, 20_100, 20_000, 19_950, 20_050)- repeat(12) { i ->+ repeat(400) { i ->detector.onFrame(pts)pts += jitter[i % jitter.size]}@@ -57,7 +147,8 @@ class FrameRateDetectorTest {// 25 fps stream but the device renders only every other or third frame, except a few.var pts = 0Lval gapsInFrames = intArrayOf(2, 3, 1, 2, 3, 3, 2, 1, 2, 3, 2)- for (gap in gapsInFrames) {+ repeat(300) { index ->+ val gap = gapsInFrames[index % gapsInFrames.size]detector.onFrame(pts)pts += 40_000L * gap}@@ -74,27 +165,30 @@ class FrameRateDetectorTest {}@Test- fun `ignores discontinuities and stops working once locked`() {+ fun `discontinuity restarts observations and a completed lock stays stable`() {val detector = FrameRateDetector(framesToLock = 10)- feed(detector, intervalUs = 40_000, frames = 5)- detector.onFrame(90_000_000L) // seek: huge gap must not count- feed(detector, intervalUs = 40_000, frames = 7, startUs = 90_040_000L)- assertThat(detector.lockedFrameRate).isEqualTo(25f)+ feed(detector, intervalUs = 40_000, frames = 50)+ detector.onFrame(90_000_000L)+ repeat(400) { frame ->+ detector.onFrame(90_016_667L + frame * 16_667L)+ if (frame == 120) assertThat(detector.lockedFrameRate).isEqualTo(0f)+ }+ assertThat(detector.lockedFrameRate).isEqualTo(60f)// Once locked, wildly different spacing is ignored.- feed(detector, intervalUs = 16_667, frames = 30, startUs = 200_000_000L)- assertThat(detector.lockedFrameRate).isEqualTo(25f)+ feed(detector, intervalUs = 40_000, frames = 300, startUs = 200_000_000L)+ assertThat(detector.lockedFrameRate).isEqualTo(60f)}@Testfun `reset allows a new stream to be detected`() {val detector = FrameRateDetector(framesToLock = 10)- feed(detector, intervalUs = 40_000, frames = 11)+ feed(detector, intervalUs = 40_000, frames = 200)assertThat(detector.lockedFrameRate).isEqualTo(25f)detector.reset()assertThat(detector.lockedFrameRate).isEqualTo(0f)- feed(detector, intervalUs = 20_000, frames = 11)+ feed(detector, intervalUs = 20_000, frames = 300)assertThat(detector.lockedFrameRate).isEqualTo(50f)}}diff --git a/player/src/test/java/com/streamvault/player/stats/PlaybackBufferingTrackerTest.kt b/player/src/test/java/com/streamvault/player/stats/PlaybackBufferingTrackerTest.ktnew file mode 100644index 00000000..a8e34fd1--- /dev/null+++ b/player/src/test/java/com/streamvault/player/stats/PlaybackBufferingTrackerTest.kt@@ -0,0 +1,80 @@+package com.streamvault.player.stats++import com.google.common.truth.Truth.assertThat+import com.streamvault.player.PlaybackState+import com.streamvault.player.stats.PlaybackBufferingTracker.Cause+import com.streamvault.player.stats.PlaybackBufferingTracker.Outcome+import org.junit.Test++class PlaybackBufferingTrackerTest {+ private var now = 0L+ private val tracker = PlaybackBufferingTracker { now }++ private fun update(state: PlaybackState, started: Boolean = true, requested: Boolean = true) =+ tracker.update(state, requested, started)++ @Test fun `startup and a seek are not rebuffers`() {+ assertThat(update(PlaybackState.BUFFERING, started = false).single().cause).isEqualTo(Cause.STARTUP)+ now = 1_200+ val opened = update(PlaybackState.READY).single()+ assertThat(opened.durationMs).isEqualTo(1_200)+ assertThat(opened.outcome).isEqualTo(Outcome.RESUMED)+ tracker.onSeek()+ assertThat(update(PlaybackState.BUFFERING).single().cause).isEqualTo(Cause.SEEK)+ }++ @Test fun `rebuffer is counted once and measures the entire interruption`() {+ update(PlaybackState.READY)+ assertThat(update(PlaybackState.BUFFERING).single().cause).isEqualTo(Cause.REBUFFER)+ now = 1_000+ assertThat(update(PlaybackState.BUFFERING)).isEmpty()+ now = 4_500+ val resumed = update(PlaybackState.READY).single()+ assertThat(resumed.cause).isEqualTo(Cause.REBUFFER)+ assertThat(resumed.outcome).isEqualTo(Outcome.RESUMED)+ assertThat(resumed.durationMs).isEqualTo(4_500)+ }++ @Test fun `paused buffering does not start an interruption and pause ends active measurement`() {+ update(PlaybackState.READY)+ assertThat(update(PlaybackState.BUFFERING, requested = false)).isEmpty()+ update(PlaybackState.BUFFERING)+ now = 600+ val cancelled = update(PlaybackState.BUFFERING, requested = false).single()+ assertThat(cancelled.outcome).isEqualTo(Outcome.CANCELLED)+ assertThat(cancelled.durationMs).isEqualTo(600)+ now = 60_000+ assertThat(update(PlaybackState.READY, requested = false)).isEmpty()+ }++ @Test fun `seek in an existing interruption cancels rebuffer rather than claiming recovery`() {+ update(PlaybackState.READY)+ update(PlaybackState.BUFFERING)+ now = 700+ tracker.onSeek()+ val events = update(PlaybackState.BUFFERING)+ assertThat(events.map { it.outcome }).containsExactly(Outcome.CANCELLED, Outcome.STARTED).inOrder()+ assertThat(events.last().cause).isEqualTo(Cause.SEEK)+ now = 900+ assertThat(update(PlaybackState.READY).single().durationMs).isEqualTo(200)+ }++ @Test fun `source preparation and in-place recovery are separated from rebuffers`() {+ tracker.reset(recovering = true)+ assertThat(update(PlaybackState.BUFFERING).single().cause).isEqualTo(Cause.RECOVERY)+ update(PlaybackState.READY)+ tracker.onRecovery()+ assertThat(update(PlaybackState.BUFFERING).single().cause).isEqualTo(Cause.RECOVERY)+ tracker.reset()+ assertThat(update(PlaybackState.BUFFERING, started = false).single().cause).isEqualTo(Cause.STARTUP)+ }++ @Test fun `error and stop do not claim playback resumed`() {+ for (terminal in listOf(PlaybackState.ERROR, PlaybackState.IDLE, PlaybackState.ENDED)) {+ tracker.reset()+ update(PlaybackState.READY)+ update(PlaybackState.BUFFERING)+ assertThat(update(terminal).single().outcome).isEqualTo(Outcome.CANCELLED)+ }+ }+}diff --git a/player/src/test/java/com/streamvault/player/stats/PlayerStatsCollectorTest.kt b/player/src/test/java/com/streamvault/player/stats/PlayerStatsCollectorTest.ktnew file mode 100644index 00000000..f42fa474--- /dev/null+++ b/player/src/test/java/com/streamvault/player/stats/PlayerStatsCollectorTest.kt@@ -0,0 +1,75 @@+@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)++package com.streamvault.player.stats++import androidx.media3.exoplayer.ExoPlayer+import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.model.VideoFormat+import com.streamvault.player.PlaybackState+import com.streamvault.player.PlayerStats+import java.lang.reflect.Proxy+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.advanceTimeBy+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.runCurrent+import kotlinx.coroutines.test.runTest+import kotlinx.coroutines.test.setMain+import org.junit.Test++class PlayerStatsCollectorTest {+ @Test fun `refill stats stay live without isPlaying and stop when paused or idle`() = runTest {+ Dispatchers.setMain(StandardTestDispatcher(testScheduler))+ try {+ var bufferedMs = 200L+ var bufferReads = 0+ var positionReads = 0+ val player = Proxy.newProxyInstance(ExoPlayer::class.java.classLoader, arrayOf(ExoPlayer::class.java)) {+ _, method, _ ->+ when (method.name) {+ "getTotalBufferedDuration" -> { bufferReads++; bufferedMs }+ "getCurrentPosition" -> { positionReads++; 1_000L }+ "getDuration" -> 60_000L+ else -> error("Unexpected player access: ${method.name}")+ }+ } as ExoPlayer+ val state = MutableStateFlow(PlaybackState.BUFFERING)+ val stats = MutableStateFlow(PlayerStats())+ val collector = PlayerStatsCollector(+ scopeProvider = { backgroundScope },+ currentPosition = MutableStateFlow(0L), duration = MutableStateFlow(0L),+ videoFormat = MutableStateFlow(VideoFormat(0, 0)), playerStats = stats,+ playbackState = state, clockMs = { testScheduler.currentTime }+ ).also { it.bind { player } }+ collector.updatePlaybackActivity(isPlaying = false, playWhenReady = true)+ runCurrent()+ assertThat(stats.value.bufferedDurationMs).isEqualTo(200)+ bufferedMs = 2_700L+ advanceTimeBy(500)+ runCurrent()+ assertThat(stats.value.bufferedDurationMs).isEqualTo(2_700)+ assertThat(positionReads).isEqualTo(0)+ val beforeDuplicateStart = bufferReads+ collector.updatePlaybackActivity(isPlaying = false, playWhenReady = true)+ runCurrent()+ assertThat(bufferReads).isEqualTo(beforeDuplicateStart)+ collector.updatePlaybackActivity(isPlaying = false, playWhenReady = false)+ advanceTimeBy(2_000)+ runCurrent()+ assertThat(bufferReads).isEqualTo(beforeDuplicateStart)+ state.value = PlaybackState.READY+ collector.updatePlaybackActivity(isPlaying = true, playWhenReady = true)+ runCurrent()+ assertThat(positionReads).isGreaterThan(0)+ state.value = PlaybackState.IDLE+ collector.updatePlaybackActivity(isPlaying = false, playWhenReady = true)+ val stoppedReads = bufferReads+ advanceTimeBy(2_000)+ runCurrent()+ assertThat(bufferReads).isEqualTo(stoppedReads)+ } finally {+ Dispatchers.resetMain()+ }+ }+}diff --git a/tools/prepare_raw_ts_backpressure_media.py b/tools/prepare_raw_ts_backpressure_media.pynew file mode 100644index 00000000..d159656e--- /dev/null+++ b/tools/prepare_raw_ts_backpressure_media.py@@ -0,0 +1,180 @@+#!/usr/bin/env python3+"""Create and validate one-pass continuous raw TS from the V5 2-second assets."""++from __future__ import annotations++import argparse+import hashlib+import json+import pathlib+import subprocess+import tempfile++if __package__:+ from .raw_ts_backpressure_fixture_server import scan_transport_stream+else:+ from raw_ts_backpressure_fixture_server import scan_transport_stream+++SEGMENT_COUNT = 300+EXPECTED_DURATION_SECONDS = 600.0+PTS_REORDER_TOLERANCE_SECONDS = 0.25+++def ffprobe_metadata(ffprobe: pathlib.Path, media: pathlib.Path) -> dict[str, object]:+ result = subprocess.check_output([+ str(ffprobe), "-v", "error", "-show_entries",+ "format=duration,size,bit_rate:stream=index,codec_type,codec_name,width,height,avg_frame_rate,r_frame_rate,time_base,start_time,duration",+ "-of", "json", str(media),+ ], text=True)+ return json.loads(result)+++def validate_packet_timestamps(ffprobe: pathlib.Path, media: pathlib.Path) -> dict[str, object]:+ process = subprocess.Popen([+ str(ffprobe), "-v", "error", "-show_packets", "-show_entries",+ "packet=stream_index,pts,dts,pts_time,dts_time", "-of", "compact=p=0:nk=0", str(media),+ ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ assert process.stdout is not None+ stats: dict[str, dict[str, object]] = {}+ packet_count = 0+ for line in process.stdout:+ values = {}+ for field in line.rstrip("\r\n").split("|"):+ if "=" in field:+ key, value = field.split("=", 1)+ values[key] = value+ if values.get("stream_index") is None:+ continue+ index = values["stream_index"]+ pts = float(values["pts_time"]) if values.get("pts_time") not in (None, "N/A") else None+ dts = float(values["dts_time"]) if values.get("dts_time") not in (None, "N/A") else None+ row = stats.setdefault(index, {+ "packets": 0, "firstPtsSeconds": None, "lastPtsSeconds": None,+ "firstDtsSeconds": None, "lastDtsSeconds": None,+ "maxPtsRegressionSeconds": 0.0,+ })+ if pts is not None:+ previous_pts = row["lastPtsSeconds"]+ if previous_pts is None:+ row["firstPtsSeconds"] = pts+ else:+ regression = float(previous_pts) - pts+ row["maxPtsRegressionSeconds"] = max(float(row["maxPtsRegressionSeconds"]), regression)+ if regression > PTS_REORDER_TOLERANCE_SECONDS:+ process.kill()+ raise ValueError(+ f"PTS regressed by {regression:.6f}s in stream {index}; likely timestamp reset"+ )+ row["lastPtsSeconds"] = pts+ if dts is not None:+ previous_dts = row["lastDtsSeconds"]+ if previous_dts is None:+ row["firstDtsSeconds"] = dts+ elif dts <= float(previous_dts):+ process.kill()+ raise ValueError(f"DTS did not advance in stream {index}: {previous_dts} -> {dts}")+ row["lastDtsSeconds"] = dts+ row["packets"] = int(row["packets"]) + 1+ packet_count += 1++ stderr = process.stderr.read() if process.stderr else ""+ return_code = process.wait()+ if return_code != 0:+ raise RuntimeError(f"ffprobe packet scan failed ({return_code}): {stderr[-2000:]}")+ if packet_count == 0 or not stats:+ raise ValueError("ffprobe returned no packets")+ if any(row["firstPtsSeconds"] is None or row["lastPtsSeconds"] is None+ or row["firstDtsSeconds"] is None or row["lastDtsSeconds"] is None for row in stats.values()):+ raise ValueError("packet stream is missing PTS or DTS")+ return {"packetCount": packet_count, "streams": stats,+ "ptsRegressionToleranceSeconds": PTS_REORDER_TOLERANCE_SECONDS}+++def segment_list(root: pathlib.Path) -> list[pathlib.Path]:+ assets = [root / f"segment_{index:03d}.ts" for index in range(SEGMENT_COUNT)]+ missing = [str(path) for path in assets if not path.is_file()]+ if missing:+ raise FileNotFoundError(f"missing expected TS segment(s): {missing[:4]}")+ for path in assets:+ if path.stat().st_size == 0 or path.stat().st_size % 188:+ raise ValueError(f"segment is not nonempty and 188-byte aligned: {path.name}")+ return assets+++def concat_manifest(assets: list[pathlib.Path], manifest: pathlib.Path) -> None:+ rows = []+ for asset in assets:+ # FFmpeg concat demuxer accepts quoted absolute paths; escape single quotes.+ escaped = str(asset.resolve()).replace("'", "'\\''")+ rows.append(f"file '{escaped}'")+ manifest.write_text("\n".join(rows) + "\n", encoding="utf-8")+++def prepare_media(segment_root: pathlib.Path, output: pathlib.Path,+ ffmpeg: pathlib.Path, ffprobe: pathlib.Path) -> dict[str, object]:+ if output.exists():+ raise FileExistsError(f"refusing to overwrite existing output: {output}")+ assets = segment_list(segment_root.resolve(strict=True))+ output.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(prefix="raw-ts-concat-") as temp:+ manifest = pathlib.Path(temp) / "segments.ffconcat"+ concat_manifest(assets, manifest)+ command = [+ str(ffmpeg), "-hide_banner", "-nostdin", "-loglevel", "warning",+ "-f", "concat", "-safe", "0", "-i", str(manifest),+ "-map", "0", "-c", "copy", "-mpegts_flags", "+resend_headers",+ "-muxdelay", "0", "-muxpreload", "0", "-f", "mpegts", str(output),+ ]+ result = subprocess.run(command, capture_output=True, text=True)+ if result.returncode != 0:+ raise RuntimeError(f"ffmpeg remux failed ({result.returncode}): {result.stderr[-4000:]}")++ transport = scan_transport_stream(output)+ metadata = ffprobe_metadata(ffprobe, output)+ fmt = metadata.get("format", {})+ duration = float(fmt.get("duration", 0))+ streams = metadata.get("streams", [])+ videos = [stream for stream in streams if stream.get("codec_type") == "video"]+ audios = [stream for stream in streams if stream.get("codec_type") == "audio"]+ if len(videos) != 1 or videos[0].get("codec_name") != "h264":+ raise ValueError(f"expected one H.264 video stream, got {videos}")+ if len(audios) != 1 or audios[0].get("codec_name") != "aac":+ raise ValueError(f"expected one AAC audio stream, got {audios}")+ if abs(duration - EXPECTED_DURATION_SECONDS) > 2.0:+ raise ValueError(f"remux duration {duration:.3f}s is not approximately 600s")+ timestamp_scan = validate_packet_timestamps(ffprobe, output)+ return {+ "inputSegmentRoot": str(segment_root.resolve()),+ "inputSegmentCount": len(assets),+ "inputSegmentBytes": sum(asset.stat().st_size for asset in assets),+ "outputFile": str(output.resolve()),+ "outputBytes": output.stat().st_size,+ "outputSha256": hashlib.sha256(output.read_bytes()).hexdigest(),+ "transportScan": transport,+ "ffprobe": metadata,+ "timestampScan": timestamp_scan,+ "ffmpegCommand": command,+ "looped": False,+ }+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("--segment-root", required=True, type=pathlib.Path)+ parser.add_argument("--output", required=True, type=pathlib.Path)+ parser.add_argument("--ffmpeg", required=True, type=pathlib.Path)+ parser.add_argument("--ffprobe", required=True, type=pathlib.Path)+ parser.add_argument("--report", required=True, type=pathlib.Path)+ args = parser.parse_args()+ result = prepare_media(args.segment_root, args.output, args.ffmpeg, args.ffprobe)+ args.report.parent.mkdir(parents=True, exist_ok=True)+ args.report.write_text(json.dumps(result, indent=2), encoding="utf-8")+ print(json.dumps({key: result[key] for key in (+ "inputSegmentCount", "outputFile", "outputBytes", "outputSha256",+ "transportScan", "timestampScan", "looped",+ )}, indent=2), flush=True)+++if __name__ == "__main__":+ main()diff --git a/tools/prepare_split_hls_timestamp_fixture.py b/tools/prepare_split_hls_timestamp_fixture.pynew file mode 100644index 00000000..f1d3d582--- /dev/null+++ b/tools/prepare_split_hls_timestamp_fixture.py@@ -0,0 +1,213 @@+#!/usr/bin/env python3+"""Prepare aligned video-only/audio-only MPEG-TS HLS assets for local tests."""++from __future__ import annotations++import argparse+import hashlib+import json+import math+import pathlib+import re+import subprocess+++def parse_hls_playlist(path: pathlib.Path) -> list[dict[str, object]]:+ rows = path.read_text(encoding="utf-8").splitlines()+ durations: list[float] = []+ files: list[str] = []+ current_duration: float | None = None+ for row in rows:+ if row.startswith("#EXTINF:"):+ current_duration = float(row.split(":", 1)[1].split(",", 1)[0])+ elif row and not row.startswith("#"):+ if current_duration is None:+ raise ValueError(f"segment URI without EXTINF in {path}")+ durations.append(current_duration)+ files.append(row)+ current_duration = None+ if current_duration is not None or not files:+ raise ValueError(f"incomplete or empty HLS playlist: {path}")+ return [{"file": file, "durationSeconds": duration}+ for file, duration in zip(files, durations, strict=True)]+++def trim_subsecond_tail(path: pathlib.Path, segments: list[dict[str, object]]) -> list[dict[str, object]]:+ if segments and float(segments[-1]["durationSeconds"]) < 0.5:+ trailing = path.parent / str(segments[-1]["file"])+ lines = path.read_text(encoding="utf-8").splitlines()+ uri = str(segments[-1]["file"])+ previous_extinf = next(i for i in range(len(lines) - 1, -1, -1) if lines[i].startswith("#EXTINF:"))+ uri_index = next((i for i in range(previous_extinf + 1, len(lines))+ if lines[i] and not lines[i].startswith("#")), None)+ if uri_index is None or lines[uri_index] != uri:+ raise ValueError(f"could not locate trailing short segment URI {uri}")+ del lines[uri_index]+ del lines[previous_extinf]+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")+ trailing.unlink()+ return segments[:-1]+ return segments+++def assert_ts_packet_sync(path: pathlib.Path) -> None:+ with path.open("rb") as stream:+ offset = 0+ while True:+ packet = stream.read(188)+ if not packet:+ break+ if len(packet) != 188 or packet[0] != 0x47:+ raise ValueError(f"invalid MPEG-TS packet alignment in {path.name} at {offset}")+ offset += 188+++def packet_metadata(ffprobe: str, path: pathlib.Path, selector: str) -> dict:+ return probe(ffprobe, path, selector)+++def probe(ffprobe: str, path: pathlib.Path, select: str | None = None) -> dict:+ args = [ffprobe, "-v", "error"]+ if select:+ args.extend(("-select_streams", select))+ args.extend(("-show_entries",+ "format=duration:stream=codec_name,codec_type,profile,level,start_time,duration,time_base,id,width,height,r_frame_rate",+ "-show_packets", "-read_intervals", "%+#1", "-of", "json", str(path)))+ return json.loads(subprocess.check_output(args, text=True))+++def avc_codec_string(path: pathlib.Path) -> str:+ payload = path.read_bytes()+ pattern = re.compile(b"\\x00\\x00\\x00\\x01|\\x00\\x00\\x01")+ for match in pattern.finditer(payload):+ header = match.end()+ if header + 3 >= len(payload):+ continue+ nal_header = payload[header]+ if nal_header & 0x80 or nal_header & 0x1F != 7:+ continue+ profile_idc, constraints, level_idc = payload[header + 1:header + 4]+ return f"avc1.{profile_idc:02X}{constraints:02X}{level_idc:02X}"+ raise ValueError(f"could not find AVC SPS in {path.name}")+++def aac_codec_string(profile: str | None) -> str:+ profile_map = {"LC": 2, "HE-AAC": 5, "HE-AACv2": 29}+ if profile not in profile_map:+ raise ValueError(f"unsupported AAC profile for HLS CODECS: {profile}")+ return f"mp4a.40.{profile_map[profile]}"+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--source", required=True, type=pathlib.Path)+ parser.add_argument("--output", required=True, type=pathlib.Path)+ parser.add_argument("--ffmpeg", required=True)+ parser.add_argument("--ffprobe", required=True)+ parser.add_argument("--segment-seconds", type=float, default=2.0)+ args = parser.parse_args()+ source = args.source.resolve(strict=True)+ output = args.output.resolve()+ if output.exists():+ raise SystemExit(f"refusing to overwrite existing output: {output}")+ if not math.isfinite(args.segment_seconds) or args.segment_seconds <= 0:+ raise SystemExit("segment duration must be finite and positive")+ output.mkdir(parents=True)+ try:+ source_probe = probe(args.ffprobe, source)+ source_streams = source_probe.get("streams", [])+ if not any(row.get("codec_type") == "video" and row.get("codec_name") == "h264"+ for row in source_streams):+ raise ValueError("source must contain H.264 video")+ if not any(row.get("codec_type") == "audio" and row.get("codec_name") == "aac"+ for row in source_streams):+ raise ValueError("source must contain AAC audio")+ video_duration: float | None = None+ for role, mapping in (("video", "0:v:0"), ("audio", "0:a:0")):+ role_dir = output / role+ role_dir.mkdir()+ command = [args.ffmpeg, "-hide_banner", "-nostdin", "-y", "-loglevel", "warning",+ "-i", str(source)]+ # AAC can extend a fraction beyond the video timeline. Clamp it to+ # the measured video playlist so both live renditions have equal+ # segment counts and a common timeline.+ if role == "audio" and video_duration is not None:+ command.extend(("-t", f"{video_duration:.6f}"))+ command.extend(("-map", mapping, "-c", "copy", "-sn", "-dn",+ "-mpegts_flags", "+resend_headers", "-f", "hls",+ "-hls_time", str(args.segment_seconds), "-hls_list_size", "0",+ "-hls_playlist_type", "vod", "-hls_flags", "independent_segments",+ "-hls_segment_filename", str(role_dir / "segment_%03d.ts"),+ str(role_dir / "index.m3u8")))+ subprocess.run(command, check=True)+ if role == "video":+ video_duration = sum(float(row["durationSeconds"])+ for row in parse_hls_playlist(role_dir / "index.m3u8"))++ video_segments = parse_hls_playlist(output / "video" / "index.m3u8")+ audio_segments = parse_hls_playlist(output / "audio" / "index.m3u8")+ if len(audio_segments) == len(video_segments) + 1:+ audio_segments = trim_subsecond_tail(output / "audio" / "index.m3u8", audio_segments)+ if len(video_segments) != len(audio_segments):+ raise ValueError(f"rendition segment counts differ: video={len(video_segments)} audio={len(audio_segments)}")+ video_total = sum(float(row["durationSeconds"]) for row in video_segments)+ audio_total = sum(float(row["durationSeconds"]) for row in audio_segments)+ source_duration = float(source_probe["format"]["duration"])+ if abs(video_total - audio_total) > 0.15:+ raise ValueError(f"rendition durations are not aligned: {video_total:.3f}s vs {audio_total:.3f}s")+ if abs(video_total - source_duration) > 0.5:+ raise ValueError(f"rendition duration {video_total:.3f}s does not cover source {source_duration:.3f}s")++ for role, segments, selector, expected_codec in (+ ("video", video_segments, "v:0", "h264"),+ ("audio", audio_segments, "a:0", "aac"),+ ):+ sample_indexes = {0, 1, len(segments) // 2, len(segments) - 1}+ for index, segment in enumerate(segments):+ path = output / role / str(segment["file"])+ assert_ts_packet_sync(path)+ segment["bytes"] = path.stat().st_size+ segment["sha256"] = hashlib.sha256(path.read_bytes()).hexdigest()+ if index in sample_indexes:+ metadata = packet_metadata(args.ffprobe, path, selector)+ stream = next((row for row in metadata.get("streams", [])+ if row.get("codec_name") == expected_codec), None)+ if stream is None:+ raise ValueError(f"{role} segment has no {expected_codec}: {path.name}")+ packets = metadata.get("packets", [])+ if not packets or "pts_time" not in packets[0]:+ raise ValueError(f"{role} segment has no first packet PTS: {path.name}")+ segment["firstPacketPtsSeconds"] = float(packets[0]["pts_time"])+ segment["codec"] = stream["codec_name"]+ segment["streamId"] = stream.get("id")+ audio_stream = next(row for row in source_streams if row.get("codec_type") == "audio")+ metadata = {+ "source": {"path": str(source), "bytes": source.stat().st_size,+ "sha256": hashlib.sha256(source.read_bytes()).hexdigest(),+ "durationSeconds": source_duration, "ffprobe": source_probe},+ "targetDurationSeconds": args.segment_seconds,+ "durationAlignmentDeltaSeconds": video_total - audio_total,+ "video": {"codec": "h264", "codecString": avc_codec_string(+ output / "video" / str(video_segments[0]["file"])), "segments": video_segments},+ "audio": {"codec": "aac", "codecString": aac_codec_string(audio_stream.get("profile")),+ "segments": audio_segments},+ }+ (output / "media.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")+ (output / "prepare-command.json").write_text(json.dumps({"commands": [+ [args.ffmpeg, "-i", str(source), "-map", "0:v:0", "-c", "copy", "..."],+ [args.ffmpeg, "-i", str(source), "-map", "0:a:0", "-c", "copy", "..."],+ ]}, indent=2), encoding="utf-8")+ print(json.dumps({"output": str(output), "videoSegments": len(video_segments),+ "audioSegments": len(audio_segments),+ "videoDurationSeconds": video_total,+ "audioDurationSeconds": audio_total,+ "sourceDurationSeconds": source_duration}, indent=2))+ except Exception:+ # Never leave a partial fixture that looks valid.+ import shutil+ shutil.rmtree(output)+ raise+++if __name__ == "__main__":+ main()diff --git a/tools/raw_ts_backpressure_fixture_server.py b/tools/raw_ts_backpressure_fixture_server.pynew file mode 100644index 00000000..950dd182--- /dev/null+++ b/tools/raw_ts_backpressure_fixture_server.py@@ -0,0 +1,515 @@+#!/usr/bin/env python3+"""One-pass raw MPEG-TS fixture with measurable socket-write backpressure.++The server does not loop or modify the supplied media. A paced source uses an+absolute byte deadline; time deliberately spent pacing is reported separately+from time blocked inside socket.sendall().+"""++from __future__ import annotations++import argparse+import hashlib+import json+import math+import pathlib+import socket+import threading+import time+from collections import defaultdict+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import urlsplit+++TS_PACKET_BYTES = 188+DEFAULT_CHUNK_BYTES = 48_128 # 256 MPEG-TS packets+DEFAULT_WRITE_BLOCK_THRESHOLD_MS = 50.0+CHANNELS = {"1001", "1002"}+++def scan_transport_stream(path: pathlib.Path) -> dict[str, int]:+ """Validate packet alignment, sync bytes, and per-PID payload continuity."""+ size = path.stat().st_size+ if size == 0 or size % TS_PACKET_BYTES:+ raise ValueError("MPEG-TS file must be nonempty and 188-byte packet aligned")++ last_counter: dict[int, int] = {}+ last_packet: dict[int, bytes] = {}+ packet_count = 0+ continuity_errors = 0+ bad_sync = 0+ with path.open("rb") as media:+ offset = 0+ while True:+ packet = media.read(TS_PACKET_BYTES)+ if not packet:+ break+ packet_count += 1+ if len(packet) != TS_PACKET_BYTES or packet[0] != 0x47:+ bad_sync += 1+ offset += TS_PACKET_BYTES+ continue++ pid = ((packet[1] & 0x1F) << 8) | packet[2]+ adaptation_control = (packet[3] >> 4) & 0x03+ counter = packet[3] & 0x0F+ has_payload = adaptation_control in (1, 3)+ has_discontinuity = (+ adaptation_control in (2, 3) and packet[4] > 0 and bool(packet[5] & 0x80)+ )+ if has_discontinuity:+ last_counter.pop(pid, None)+ last_packet.pop(pid, None)+ if has_payload and pid == 0x1FFF:+ # The null PID is not continuity-counter checked by the TS spec.+ offset += TS_PACKET_BYTES+ continue+ if has_payload and pid in last_counter:+ expected = (last_counter[pid] + 1) & 0x0F+ # A repeated counter is only legal for an exact duplicate packet.+ if counter != expected and not (+ counter == last_counter[pid] and packet == last_packet[pid]+ ):+ continuity_errors += 1+ if has_payload:+ last_counter[pid] = counter+ last_packet[pid] = packet+ offset += TS_PACKET_BYTES++ if bad_sync or continuity_errors:+ raise ValueError(+ f"invalid MPEG-TS packet stream: badSync={bad_sync} "+ f"continuityErrors={continuity_errors}"+ )+ return {"bytes": size, "packets": packet_count, "badSync": bad_sync,+ "continuityErrors": continuity_errors}+++def sha256_file(path: pathlib.Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as media:+ for block in iter(lambda: media.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def paced_deadline_seconds(payload_bytes_sent: int, wire_rate_bps: float) -> float:+ if payload_bytes_sent < 0 or not math.isfinite(wire_rate_bps) or wire_rate_bps <= 0:+ raise ValueError("payload bytes must be nonnegative and wire rate must be finite and positive")+ return payload_bytes_sent * 8.0 / wire_rate_bps+++def chunk_payload(data: bytes, chunk_bytes: int = DEFAULT_CHUNK_BYTES):+ if chunk_bytes <= 0 or chunk_bytes % TS_PACKET_BYTES:+ raise ValueError("chunk size must be a positive multiple of 188 bytes")+ for offset in range(0, len(data), chunk_bytes):+ yield data[offset:offset + chunk_bytes]+++def json_bytes(value: object) -> bytes:+ return json.dumps(value, separators=(",", ":")).encode("utf-8")+++def snapshot_stream(stream: dict[str, object]) -> dict[str, object]:+ snapshot = dict(stream)+ for key in ("blockedWrites", "failedWrites"):+ value = stream.get(key)+ if isinstance(value, list):+ snapshot[key] = [dict(item) for item in value]+ pending = stream.get("pendingSend")+ if isinstance(pending, dict):+ snapshot["pendingSend"] = dict(pending)+ return snapshot+++def create_server(+ media_file: pathlib.Path,+ port: int,+ pace_multiplier: float,+ media_duration_seconds: float,+ send_buffer_bytes: int,+ send_timeout_seconds: float,+ write_block_threshold_ms: float = DEFAULT_WRITE_BLOCK_THRESHOLD_MS,+ chunk_bytes: int = DEFAULT_CHUNK_BYTES,+ continuation_file: pathlib.Path | None = None,+ continuation_duration_seconds: float | None = None,+) -> ThreadingHTTPServer:+ if not math.isfinite(pace_multiplier) or pace_multiplier <= 0:+ raise ValueError("pace multiplier must be finite and positive")+ if not math.isfinite(media_duration_seconds) or media_duration_seconds <= 0:+ raise ValueError("media duration must be finite and positive")+ if send_buffer_bytes <= 0:+ raise ValueError("send buffer size must be positive")+ if not math.isfinite(send_timeout_seconds) or send_timeout_seconds < 0:+ raise ValueError("send timeout must be finite and nonnegative")+ if not math.isfinite(write_block_threshold_ms) or write_block_threshold_ms < 0:+ raise ValueError("write block threshold must be finite and nonnegative")+ if chunk_bytes <= 0 or chunk_bytes % TS_PACKET_BYTES:+ raise ValueError("chunk size must be a positive multiple of 188 bytes")+ media_file = media_file.resolve(strict=True)+ media_scan = scan_transport_stream(media_file)+ media_sha256 = sha256_file(media_file)+ wire_rate_bps = media_scan["bytes"] * 8.0 / media_duration_seconds * pace_multiplier+ if (continuation_file is None) != (continuation_duration_seconds is None):+ raise ValueError("continuation file and duration must be supplied together")+ continuation_scan = None+ continuation_sha256 = None+ continuation_wire_rate_bps = None+ if continuation_file is not None:+ if not math.isfinite(continuation_duration_seconds) or continuation_duration_seconds <= 0:+ raise ValueError("continuation duration must be finite and positive")+ continuation_file = continuation_file.resolve(strict=True)+ continuation_scan = scan_transport_stream(continuation_file)+ continuation_sha256 = sha256_file(continuation_file)+ continuation_wire_rate_bps = (+ continuation_scan["bytes"] * 8.0 / continuation_duration_seconds * pace_multiplier+ )++ state_lock = threading.Lock()+ events: list[dict[str, object]] = []+ active_streams: dict[str, dict[str, object]] = {}+ next_id = 0+ next_request_index = 0+ server = ThreadingHTTPServer(("127.0.0.1", port), RawTsHandler)+ server.daemon_threads = True+ server.media_file = media_file+ server.media_scan = media_scan+ server.media_sha256 = media_sha256+ server.media_duration_seconds = media_duration_seconds+ server.pace_multiplier = pace_multiplier+ server.wire_rate_bps = wire_rate_bps+ server.continuation_file = continuation_file+ server.continuation_scan = continuation_scan+ server.continuation_sha256 = continuation_sha256+ server.continuation_duration_seconds = continuation_duration_seconds+ server.continuation_wire_rate_bps = continuation_wire_rate_bps+ server.send_buffer_bytes = send_buffer_bytes+ server.send_timeout_seconds = send_timeout_seconds+ server.write_block_threshold_ms = write_block_threshold_ms+ server.chunk_bytes = chunk_bytes+ server.state_lock = state_lock+ server.events = events+ server.active_streams = active_streams+ server.next_id = next_id+ server.next_request_index = next_request_index+ server.reset_wall_time = time.time()+ return server+++class RawTsHandler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"+ server_version = "RawTsBackpressureFixture/1.0"++ def log_message(self, *_args) -> None:+ pass++ def _reply(self, status: int, payload: bytes, content_type: str = "application/json") -> None:+ self.send_response(status)+ self.send_header("Content-Type", content_type)+ self.send_header("Content-Length", str(len(payload)))+ self.send_header("Cache-Control", "no-store")+ self.send_header("Connection", "close")+ self.end_headers()+ try:+ self.wfile.write(payload)+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):+ pass+ self.close_connection = True++ def do_GET(self) -> None:+ parsed = urlsplit(self.path)+ if parsed.path == "/status":+ with self.server.state_lock:+ value = {+ "ok": True,+ "port": self.server.server_port,+ "mediaFile": str(self.server.media_file),+ "mediaDurationSeconds": self.server.media_duration_seconds,+ "mediaScan": self.server.media_scan,+ "mediaSha256": self.server.media_sha256,+ "paceMultiplier": self.server.pace_multiplier,+ "wireRateBps": self.server.wire_rate_bps,+ "continuationFile": str(self.server.continuation_file) if self.server.continuation_file else None,+ "continuationDurationSeconds": self.server.continuation_duration_seconds,+ "continuationScan": self.server.continuation_scan,+ "continuationSha256": self.server.continuation_sha256,+ "continuationWireRateBps": self.server.continuation_wire_rate_bps,+ "sendBufferBytesRequested": self.server.send_buffer_bytes,+ "sendTimeoutSeconds": self.server.send_timeout_seconds,+ "writeBlockThresholdMs": self.server.write_block_threshold_ms,+ "activeStreams": len(self.server.active_streams),+ }+ return self._reply(200, json_bytes(value))++ if parsed.path == "/events":+ with self.server.state_lock:+ value = {+ "settings": {+ "mediaFile": str(self.server.media_file),+ "mediaDurationSeconds": self.server.media_duration_seconds,+ "mediaScan": self.server.media_scan,+ "mediaSha256": self.server.media_sha256,+ "paceMultiplier": self.server.pace_multiplier,+ "wireRateBps": self.server.wire_rate_bps,+ "continuationFile": str(self.server.continuation_file) if self.server.continuation_file else None,+ "continuationDurationSeconds": self.server.continuation_duration_seconds,+ "continuationScan": self.server.continuation_scan,+ "continuationSha256": self.server.continuation_sha256,+ "continuationWireRateBps": self.server.continuation_wire_rate_bps,+ "sendBufferBytesRequested": self.server.send_buffer_bytes,+ "sendTimeoutSeconds": self.server.send_timeout_seconds,+ "writeBlockThresholdMs": self.server.write_block_threshold_ms,+ "chunkBytes": self.server.chunk_bytes,+ },+ "events": list(self.server.events),+ "activeStreams": [snapshot_stream(row) for row in self.server.active_streams.values()],+ }+ return self._reply(200, json_bytes(value))++ if parsed.path == "/control" and parsed.query == "reset=1":+ with self.server.state_lock:+ if self.server.active_streams:+ return self._reply(409, json_bytes({"error": "stream active"}))+ self.server.events.clear()+ self.server.reset_wall_time = time.time()+ self.server.next_request_index = 0+ value = {"ok": True, "resetUnixSeconds": self.server.reset_wall_time}+ return self._reply(200, json_bytes(value))++ parts = parsed.path.strip("/").split("/")+ if len(parts) != 2 or parts[0] != "raw" or parts[1] not in {"1001.ts", "1002.ts"}:+ return self._reply(404, json_bytes({"error": "not found"}))+ channel = parts[1].removesuffix(".ts")+ if self.headers.get("Range"):+ return self._reply(416, b"", "text/plain")++ with self.server.state_lock:+ self.server.next_id += 1+ stream_id = f"{channel}-{self.server.next_id}"+ self.server.next_request_index += 1+ request_index = self.server.next_request_index+ use_continuation = (+ self.server.continuation_file is not None and request_index > 1+ )+ selected_file = self.server.continuation_file if use_continuation else self.server.media_file+ selected_duration = (+ self.server.continuation_duration_seconds if use_continuation+ else self.server.media_duration_seconds+ )+ selected_scan = self.server.continuation_scan if use_continuation else self.server.media_scan+ selected_wire_rate_bps = (+ self.server.continuation_wire_rate_bps if use_continuation+ else self.server.wire_rate_bps+ )+ started_unix = time.time()+ started_mono = time.monotonic()+ stream = {+ "streamId": stream_id,+ "channel": channel,+ "requestIndex": request_index,+ "mediaFile": str(selected_file),+ "mediaDurationSeconds": selected_duration,+ "mediaScan": selected_scan,+ "mediaSha256": self.server.continuation_sha256 if use_continuation else self.server.media_sha256,+ "wireRateBps": selected_wire_rate_bps,+ "startedUnixSeconds": started_unix,+ "startedMonotonicSeconds": started_mono,+ "elapsedSeconds": 0.0,+ "bytesSent": 0,+ "sendallCalls": 0,+ "totalSendallMs": 0.0,+ "maxSendallMs": 0.0,+ "blockedWriteCount": 0,+ "blockedWrites": [],+ "failedWrites": [],+ "pendingSend": None,+ "pacingWaitSeconds": 0.0,+ "connectionCloseReason": "active",+ "sendBufferBytesRequested": self.server.send_buffer_bytes,+ "sendTimeoutSeconds": self.server.send_timeout_seconds,+ "sendBufferBytesActual": None,+ "requestRange": None,+ }+ self.server.active_streams[stream_id] = snapshot_stream(stream)++ actual_send_buffer = None+ try:+ self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF,+ self.server.send_buffer_bytes)+ actual_send_buffer = self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)+ if self.server.send_timeout_seconds > 0:+ self.connection.settimeout(self.server.send_timeout_seconds)+ with self.server.state_lock:+ stream["sendBufferBytesActual"] = actual_send_buffer+ self.server.active_streams[stream_id] = snapshot_stream(stream)+ self.send_response(200)+ self.send_header("Content-Type", "video/mp2t")+ self.send_header("Transfer-Encoding", "chunked")+ self.send_header("Cache-Control", "no-store")+ self.send_header("Connection", "close")+ self.end_headers()+ self.wfile.flush()++ began = time.monotonic()+ began_unix = time.time()+ with self.server.state_lock:+ stream["beganUnixSeconds"] = began_unix+ stream["beganElapsedMonotonic"] = began+ self.server.active_streams[stream_id] = snapshot_stream(stream)+ sent = 0+ reason = "complete"+ with selected_file.open("rb") as media:+ while True:+ payload = media.read(self.server.chunk_bytes)+ if not payload:+ self.connection.sendall(b"0\r\n\r\n")+ break+ due_offset = paced_deadline_seconds(sent, selected_wire_rate_bps)+ wait_seconds = due_offset - (time.monotonic() - began)+ if wait_seconds > 0:+ time.sleep(wait_seconds)+ with self.server.state_lock:+ stream["pacingWaitSeconds"] = float(stream["pacingWaitSeconds"]) + wait_seconds+ self.server.active_streams[stream_id] = snapshot_stream(stream)+ wire_chunk = f"{len(payload):X}\r\n".encode("ascii") + payload + b"\r\n"+ send_started = time.monotonic()+ pending = {+ "startElapsedSeconds": send_started - began,+ "startUnixSeconds": time.time(),+ "payloadBytes": len(payload),+ "wireBytes": len(wire_chunk),+ }+ with self.server.state_lock:+ stream["pendingSend"] = pending+ self.server.active_streams[stream_id] = snapshot_stream(stream)+ try:+ self.connection.sendall(wire_chunk)+ except socket.timeout:+ elapsed_ms = (time.monotonic() - send_started) * 1000.0+ with self.server.state_lock:+ stream["pendingSend"] = None+ stream["sendallCalls"] = int(stream["sendallCalls"]) + 1+ stream["totalSendallMs"] = float(stream["totalSendallMs"]) + elapsed_ms+ stream["maxSendallMs"] = max(float(stream["maxSendallMs"]), elapsed_ms)+ stream["partialChunkMayHaveBeenSent"] = True+ failed = stream["failedWrites"]+ assert isinstance(failed, list)+ failed.append({**pending, "durationMs": elapsed_ms, "outcome": "send-timeout"})+ if elapsed_ms >= self.server.write_block_threshold_ms:+ stream["blockedWriteCount"] = int(stream["blockedWriteCount"]) + 1+ blocked = stream["blockedWrites"]+ assert isinstance(blocked, list)+ blocked.append({**pending, "durationMs": elapsed_ms, "outcome": "send-timeout"})+ self.server.active_streams[stream_id] = snapshot_stream(stream)+ reason = "send-timeout"+ break+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):+ elapsed_ms = (time.monotonic() - send_started) * 1000.0+ with self.server.state_lock:+ stream["pendingSend"] = None+ stream["sendallCalls"] = int(stream["sendallCalls"]) + 1+ stream["totalSendallMs"] = float(stream["totalSendallMs"]) + elapsed_ms+ stream["maxSendallMs"] = max(float(stream["maxSendallMs"]), elapsed_ms)+ stream["partialChunkMayHaveBeenSent"] = True+ failed = stream["failedWrites"]+ assert isinstance(failed, list)+ failed.append({**pending, "durationMs": elapsed_ms, "outcome": "client-disconnect"})+ if elapsed_ms >= self.server.write_block_threshold_ms:+ stream["blockedWriteCount"] = int(stream["blockedWriteCount"]) + 1+ blocked = stream["blockedWrites"]+ assert isinstance(blocked, list)+ blocked.append({**pending, "durationMs": elapsed_ms, "outcome": "client-disconnect"})+ self.server.active_streams[stream_id] = snapshot_stream(stream)+ reason = "client-disconnect"+ break+ elapsed_ms = (time.monotonic() - send_started) * 1000.0+ sent += len(payload)+ with self.server.state_lock:+ stream["pendingSend"] = None+ stream["bytesSent"] = sent+ stream["sendallCalls"] = int(stream["sendallCalls"]) + 1+ stream["totalSendallMs"] = float(stream["totalSendallMs"]) + elapsed_ms+ stream["maxSendallMs"] = max(float(stream["maxSendallMs"]), elapsed_ms)+ if elapsed_ms >= self.server.write_block_threshold_ms:+ stream["blockedWriteCount"] = int(stream["blockedWriteCount"]) + 1+ blocked = stream["blockedWrites"]+ assert isinstance(blocked, list)+ blocked.append({**pending, "durationMs": elapsed_ms, "outcome": "sent"})+ stream["elapsedSeconds"] = time.monotonic() - started_mono+ self.server.active_streams[stream_id] = snapshot_stream(stream)+ with self.server.state_lock:+ stream["connectionCloseReason"] = reason+ self.server.active_streams[stream_id] = snapshot_stream(stream)+ self.close_connection = True+ except socket.timeout:+ with self.server.state_lock:+ stream["connectionCloseReason"] = "send-timeout"+ stream["partialChunkMayHaveBeenSent"] = True+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):+ with self.server.state_lock:+ stream["connectionCloseReason"] = "client-disconnect"+ finally:+ with self.server.state_lock:+ stream["elapsedSeconds"] = time.monotonic() - started_mono+ stream["endedUnixSeconds"] = time.time()+ stream["sendBufferBytesActual"] = actual_send_buffer+ if stream["connectionCloseReason"] == "active":+ stream["connectionCloseReason"] = reason if "reason" in locals() else "connection-error"+ self.server.active_streams.pop(stream_id, None)+ self.server.events.append({"event": "raw-stream", **stream})+ self.close_connection = True+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("--port", type=int, default=18796)+ parser.add_argument("--media-file", required=True, type=pathlib.Path)+ parser.add_argument("--media-duration-seconds", type=float, required=True)+ parser.add_argument("--continuation-file", type=pathlib.Path)+ parser.add_argument("--continuation-duration-seconds", type=float)+ parser.add_argument("--pace-multiplier", type=float, default=1.0)+ parser.add_argument("--send-buffer-bytes", type=int, default=65_536)+ parser.add_argument("--send-timeout-seconds", type=float, default=0.0)+ parser.add_argument("--write-block-threshold-ms", type=float,+ default=DEFAULT_WRITE_BLOCK_THRESHOLD_MS)+ parser.add_argument("--chunk-bytes", type=int, default=DEFAULT_CHUNK_BYTES)+ args = parser.parse_args()+ try:+ server = create_server(+ media_file=args.media_file,+ port=args.port,+ pace_multiplier=args.pace_multiplier,+ media_duration_seconds=args.media_duration_seconds,+ send_buffer_bytes=args.send_buffer_bytes,+ send_timeout_seconds=args.send_timeout_seconds,+ write_block_threshold_ms=args.write_block_threshold_ms,+ chunk_bytes=args.chunk_bytes,+ continuation_file=args.continuation_file,+ continuation_duration_seconds=args.continuation_duration_seconds,+ )+ except (OSError, ValueError) as exc:+ parser.error(str(exc))+ print(json.dumps({+ "listening": f"127.0.0.1:{args.port}",+ "mediaFile": str(server.media_file),+ "mediaDurationSeconds": server.media_duration_seconds,+ "mediaScan": server.media_scan,+ "mediaSha256": server.media_sha256,+ "paceMultiplier": server.pace_multiplier,+ "wireRateBps": server.wire_rate_bps,+ "continuationFile": str(server.continuation_file) if server.continuation_file else None,+ "continuationDurationSeconds": server.continuation_duration_seconds,+ "continuationScan": server.continuation_scan,+ "continuationSha256": server.continuation_sha256,+ "continuationWireRateBps": server.continuation_wire_rate_bps,+ "sendBufferBytesRequested": server.send_buffer_bytes,+ "sendTimeoutSeconds": server.send_timeout_seconds,+ }), flush=True)+ try:+ server.serve_forever()+ finally:+ server.server_close()+++if __name__ == "__main__":+ main()diff --git a/tools/split_hls_timestamp_fixture_server.py b/tools/split_hls_timestamp_fixture_server.pynew file mode 100644index 00000000..7c45c9f0--- /dev/null+++ b/tools/split_hls_timestamp_fixture_server.py@@ -0,0 +1,510 @@+#!/usr/bin/env python3+"""Split audio/video MPEG-TS HLS fixture for timestamp-adjuster wait tests.++The fixture expects pre-generated ``video/segment_NNN.ts`` and+``audio/segment_NNN.ts`` files plus ``media.json`` from+prepare_split_hls_timestamp_fixture.py. It serves an explicit-codec master+playlist and independent, aligned live media playlists. In delayed-valid mode+the first requested video segment sends PAT/PMT and paced null packets before+the original first video PES/PTS. In missing-primary mode it keeps the+initially selected video sequence active with PAT/PMT and null packets but+never emits a video PES; later sequences are playable. In+missing-primary-all mode every video sequence remains without a PES. Audio+segments remain available normally.++This is test tooling only; no provider URLs or credentials are used.+"""++from __future__ import annotations++import argparse+import json+import math+import pathlib+import threading+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from urllib.parse import urlsplit++PACKET_SIZE = 188+++def ts_packets(payload: bytes) -> list[bytes]:+ if len(payload) % PACKET_SIZE:+ raise ValueError("MPEG-TS asset size is not a multiple of 188")+ packets = [payload[i:i + PACKET_SIZE] for i in range(0, len(payload), PACKET_SIZE)]+ if any(packet[0] != 0x47 for packet in packets):+ raise ValueError("MPEG-TS asset contains a bad sync byte")+ return packets+++def _payload(packet: bytes) -> tuple[int, bool, bytes] | None:+ pid = ((packet[1] & 0x1F) << 8) | packet[2]+ start = bool(packet[1] & 0x40)+ control = (packet[3] >> 4) & 0x03+ if control not in (1, 3):+ return None+ offset = 4+ if control == 3:+ offset += 1 + packet[4]+ if offset >= PACKET_SIZE:+ return None+ return pid, start, packet[offset:]+++def _psi_section(packets: list[bytes], pid: int, table_id: int) -> tuple[bytes, list[int]]:+ data = bytearray()+ packet_indices: list[int] = []+ expected: int | None = None+ for index, packet in enumerate(packets):+ info = _payload(packet)+ if info is None or info[0] != pid:+ continue+ _, start, payload = info+ if start:+ pointer = payload[0]+ payload = payload[1 + pointer:]+ data.clear()+ packet_indices.clear()+ expected = None+ if not payload:+ continue+ packet_indices.append(index)+ data.extend(payload)+ if len(data) >= 3 and expected is None:+ if data[0] != table_id:+ data.clear()+ packet_indices.clear()+ continue+ expected = 3 + (((data[1] & 0x0F) << 8) | data[2])+ if expected is not None and len(data) >= expected:+ return bytes(data[:expected]), packet_indices+ raise ValueError(f"MPEG-TS PID {pid} has no complete PSI table 0x{table_id:02x}")+++def find_program_packets(payload: bytes) -> dict[str, int | list[int]]:+ """Return PAT/PMT packet indexes, AVC PID, and first AVC PES packet index."""+ packets = ts_packets(payload)+ pat, pat_indices = _psi_section(packets, 0, 0x00)+ pat_end = len(pat) - 4+ pmt_pid = None+ for offset in range(8, pat_end, 4):+ program = int.from_bytes(pat[offset:offset + 2], "big")+ pid = ((pat[offset + 2] & 0x1F) << 8) | pat[offset + 3]+ if program:+ pmt_pid = pid+ break+ if pmt_pid is None:+ raise ValueError("PAT has no program entry")+ pmt, pmt_indices = _psi_section(packets, pmt_pid, 0x02)+ pmt_end = len(pmt) - 4+ program_info_length = ((pmt[10] & 0x0F) << 8) | pmt[11]+ offset = 12 + program_info_length+ video_pid = None+ while offset + 5 <= pmt_end:+ stream_type = pmt[offset]+ elementary_pid = ((pmt[offset + 1] & 0x1F) << 8) | pmt[offset + 2]+ es_info_length = ((pmt[offset + 3] & 0x0F) << 8) | pmt[offset + 4]+ if stream_type == 0x1B:+ video_pid = elementary_pid+ break+ offset += 5 + es_info_length+ if video_pid is None:+ raise ValueError("PMT has no AVC elementary stream")+ first_video_pes = None+ for index, packet in enumerate(packets):+ info = _payload(packet)+ if info is None:+ continue+ pid, start, elementary = info+ if pid == video_pid and start:+ if len(elementary) < 9 or elementary[:3] != b"\x00\x00\x01":+ raise ValueError("first AVC payload unit does not begin with a PES header")+ has_pts = bool(elementary[7] & 0x80)+ if not has_pts:+ raise ValueError("first AVC PES has no PTS")+ first_video_pes = index+ break+ if first_video_pes is None:+ raise ValueError("MPEG-TS has no AVC PES start")+ return {+ "patPid": 0,+ "pmtPid": pmt_pid,+ "videoPid": video_pid,+ "patPacketIndexes": pat_indices,+ "pmtPacketIndexes": pmt_indices,+ "firstVideoPesPacketIndex": first_video_pes,+ }+++def null_packet(counter: int = 0) -> bytes:+ """Build one legal MPEG-TS null-PID packet."""+ return b"\x47\x1f\xff\x10" + bytes([counter & 0x0F]) + b"\xff" * (PACKET_SIZE - 5)+++def build_prefix_and_suffix(payload: bytes) -> tuple[bytes, bytes, dict[str, int | list[int]]]:+ details = find_program_packets(payload)+ packets = ts_packets(payload)+ indexes = list(details["patPacketIndexes"]) + list(details["pmtPacketIndexes"])+ prefix = b"".join(packets[index] for index in indexes)+ suffix = b"".join(packets[int(details["firstVideoPesPacketIndex"]):])+ if not prefix or not suffix:+ raise ValueError("could not isolate PSI prefix and first AVC PES")+ return prefix, suffix, details+++class FixtureState:+ def __init__(self, root: pathlib.Path, mode: str, delay_seconds: float,+ null_packets_per_second: float, window_segments: int,+ rendition_profile: str = "audio-video",+ subtitle_discontinuity_sequence_offset: int = 0) -> None:+ self.root = root+ self.mode = mode+ self.delay_seconds = delay_seconds+ self.null_packets_per_second = null_packets_per_second+ self.window_segments = window_segments+ if rendition_profile not in ("audio-video", "video-subtitles"):+ raise ValueError(f"unsupported rendition profile: {rendition_profile}")+ if subtitle_discontinuity_sequence_offset < 0:+ raise ValueError("subtitle discontinuity sequence offset must be nonnegative")+ self.rendition_profile = rendition_profile+ self.subtitle_discontinuity_sequence_offset = subtitle_discontinuity_sequence_offset+ metadata = json.loads((root / "media.json").read_text(encoding="utf-8"))+ self.video = metadata["video"]+ self.audio = metadata["audio"]+ self.video_segments = len(self.video["segments"])+ self.audio_segments = len(self.audio["segments"])+ if self.video_segments != self.audio_segments or self.video_segments < window_segments:+ raise ValueError("video/audio segment counts must match and cover the live window")+ self.lock = threading.Lock()+ self.events: list[dict] = []+ self.origin = time.monotonic() - 2.0 * window_segments+ self.wall_origin = time.time() - 2.0 * window_segments+ self.delayed_sequences: set[int] = set()+ self.delay_target_sequence: int | None = None+ self.request_counter = 0+ self.started_at = time.monotonic()++ def record(self, event: str, **data: object) -> None:+ with self.lock:+ self.events.append({"wallTime": time.time(), "monotonicSeconds": time.monotonic(),+ "event": event, **data})++ def reset(self) -> dict:+ with self.lock:+ self.origin = time.monotonic() - 2.0 * self.window_segments+ self.wall_origin = time.time() - 2.0 * self.window_segments+ self.delayed_sequences.clear()+ self.delay_target_sequence = None+ self.events.clear()+ self.started_at = time.monotonic()+ self.record("reset", mode=self.mode)+ return self.status()++ def status(self) -> dict:+ with self.lock:+ elapsed = time.monotonic() - self.origin+ current = max(0, int(elapsed / 2.0))+ opened = sum(event["event"] == "stream-open" for event in self.events)+ closed = sum(event["event"] in ("stream-close", "client-disconnect")+ for event in self.events)+ return {"mode": self.mode, "renditionProfile": self.rendition_profile,+ "delaySeconds": self.delay_seconds,+ "nullPacketsPerSecond": self.null_packets_per_second,+ "subtitleDiscontinuitySequenceOffset": self.subtitle_discontinuity_sequence_offset,+ "windowSegments": self.window_segments, "currentSequence": current,+ "delayedSequences": sorted(self.delayed_sequences),+ "delayTargetSequence": self.delay_target_sequence,+ "activeRequestCount": max(0, opened - closed)}++ def window(self) -> tuple[int, int, float, float]:+ with self.lock:+ current = max(1, int((time.monotonic() - self.origin) / 2.0))+ end = current - 1+ start = max(0, end - self.window_segments + 1)+ return start, end, self.wall_origin, self.origin+++def chunked_write(handler: BaseHTTPRequestHandler, payload: bytes) -> None:+ if payload:+ handler.wfile.write(f"{len(payload):X}\r\n".encode("ascii"))+ handler.wfile.write(payload)+ handler.wfile.write(b"\r\n")+ handler.wfile.flush()+++class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *_args: object) -> None:+ pass++ @property+ def state(self) -> FixtureState:+ return self.server.fixture_state # type: ignore[attr-defined]++ def _reply(self, body: bytes, content_type: str, status: int = 200) -> None:+ self.send_response(status)+ self.send_header("Content-Type", content_type)+ self.send_header("Content-Length", str(len(body)))+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(body)++ def do_GET(self) -> None: # noqa: N802+ route = urlsplit(self.path).path+ if route == "/health":+ return self._reply(b'{"ok":true}', "application/json")+ if route == "/status":+ return self._reply(json.dumps(self.state.status()).encode(), "application/json")+ if route == "/events":+ with self.state.lock:+ snapshot = {"settings": {"mode": self.state.mode,+ "renditionProfile": self.state.rendition_profile,+ "delaySeconds": self.state.delay_seconds,+ "nullPacketsPerSecond": self.state.null_packets_per_second,+ "subtitleDiscontinuitySequenceOffset": self.state.subtitle_discontinuity_sequence_offset,+ "windowSegments": self.state.window_segments},+ "events": list(self.state.events)}+ return self._reply(json.dumps(snapshot).encode(), "application/json")+ if route == "/control":+ return self._reply(json.dumps(self.state.reset()).encode(), "application/json")+ if route == "/master.m3u8":+ if self.state.rendition_profile == "video-subtitles":+ body = ("#EXTM3U\n#EXT-X-VERSION:3\n"+ '#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="Fixture Subtitles",'+ 'DEFAULT=YES,AUTOSELECT=YES,FORCED=NO,URI="subtitle/index.m3u8"\n'+ f'#EXT-X-STREAM-INF:BANDWIDTH=1900000,CODECS="{self.state.video["codecString"]}",'+ 'SUBTITLES="subs"\nvideo/index.m3u8\n').encode("utf-8")+ else:+ body = ("#EXTM3U\n#EXT-X-VERSION:3\n"+ '#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="Fixture Audio",'+ 'DEFAULT=YES,AUTOSELECT=YES,URI="audio/index.m3u8"\n'+ f'#EXT-X-STREAM-INF:BANDWIDTH=2200000,CODECS="{self.state.video["codecString"]},'+ f'{self.state.audio["codecString"]}",'+ 'AUDIO="audio"\nvideo/index.m3u8\n').encode("utf-8")+ return self._reply(body, "application/vnd.apple.mpegurl")+ if route in ("/video/index.m3u8", "/audio/index.m3u8", "/subtitle/index.m3u8"):+ role = route.split("/")[1]+ start, end, wall_origin, _ = self.state.window()+ metadata = self.state.video if role in ("video", "subtitle") else self.state.audio+ count = len(metadata["segments"])+ target = max(2, math.ceil(max(metadata["segments"][n % count]["durationSeconds"]+ for n in range(start, end + 1))) if end >= start else 2)+ rows = ["#EXTM3U", "#EXT-X-VERSION:3", f"#EXT-X-TARGETDURATION:{target}",+ f"#EXT-X-MEDIA-SEQUENCE:{start}"]+ if role == "subtitle" and self.state.subtitle_discontinuity_sequence_offset:+ rows.insert(3, f"#EXT-X-DISCONTINUITY-SEQUENCE:{self.state.subtitle_discontinuity_sequence_offset}")+ for number in range(start, end + 1):+ wall = wall_origin + number * 2.0+ stamp = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(wall)) + ".%03dZ" % int(wall % 1 * 1000)+ rows.extend((f"#EXT-X-PROGRAM-DATE-TIME:{stamp}",+ f"#EXTINF:{metadata['segments'][number % count]['durationSeconds']:.6f},",+ f"/{role}/segment/{number}.{'vtt' if role == 'subtitle' else 'ts'}"))+ return self._reply(("\n".join(rows) + "\n").encode(), "application/vnd.apple.mpegurl")+ if route.startswith("/subtitle/segment/"):+ try:+ sequence = int(route.rsplit("/", 1)[1].removesuffix(".vtt"))+ except ValueError:+ return self._reply(b"not found", "text/plain", 404)+ if sequence < 0:+ return self._reply(b"not found", "text/plain", 404)+ index = sequence % len(self.state.video["segments"])+ first_pts = self.state.video["segments"][0].get("firstPacketPtsSeconds", 1.4)+ mpegts_pts = int(round((float(first_pts) + 2.0 * index) * 90_000)) % (1 << 33)+ duration = float(self.state.video["segments"][index]["durationSeconds"])+ cue_end = min(1.0, max(0.1, duration - 0.01))+ seconds = int(cue_end)+ millis = int(round((cue_end - seconds) * 1000))+ body = ("WEBVTT\n"+ f"X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:{mpegts_pts}\n\n"+ f"00:00:00.000 --> 00:00:{seconds:02d}.{millis:03d}\n"+ f"Fixture subtitle {sequence}\n").encode("utf-8")+ self.state.record("subtitle-segment", sequence=sequence, assetIndex=index,+ bytes=len(body), mpegtsPts=mpegts_pts)+ return self._reply(body, "text/vtt")+ if route.startswith("/video/segment/") or route.startswith("/audio/segment/"):+ parts = route.strip("/").split("/")+ role = parts[0]+ try:+ sequence = int(parts[2].removesuffix(".ts"))+ except (IndexError, ValueError):+ return self._reply(b"not found", "text/plain", 404)+ metadata = self.state.video if role == "video" else self.state.audio+ segments = metadata["segments"]+ if sequence < 0 or not segments:+ return self._reply(b"not found", "text/plain", 404)+ asset_index = sequence % len(segments)+ asset = self.state.root / role / segments[asset_index]["file"]+ if not asset.is_file():+ return self._reply(b"not found", "text/plain", 404)+ payload = asset.read_bytes()+ opened = time.monotonic()+ with self.state.lock:+ self.state.request_counter += 1+ request_id = self.state.request_counter+ event = {"role": role, "sequence": sequence, "assetIndex": asset_index,+ "assetBytes": len(payload), "requestWallTime": time.time(),+ "requestId": request_id}+ self.state.record("stream-open", **event)+ if role != "video" or self.state.mode == "off":+ try:+ self._reply(payload, "video/mp2t")+ self.state.record("stream-close", **event, statusCode=200,+ bytes=len(payload), elapsedMs=(time.monotonic() - opened) * 1000,+ closeReason="body-complete")+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as error:+ self.state.record("client-disconnect", **event, phase="normal-segment",+ elapsedMs=(time.monotonic() - opened) * 1000,+ exception=type(error).__name__)+ return++ prefix, suffix, transport = build_prefix_and_suffix(payload)+ should_delay = False+ selected_target = False+ with self.state.lock:+ if self.state.delay_target_sequence is None:+ self.state.delay_target_sequence = sequence+ selected_target = True+ if self.state.mode == "missing-primary-all":+ should_delay = True+ elif sequence == self.state.delay_target_sequence:+ if self.state.mode == "missing-primary":+ # A retry of the selected sequence must remain without+ # primary PTS; otherwise a reconnect would invalidate+ # the missing-timestamp condition.+ should_delay = True+ elif sequence not in self.state.delayed_sequences:+ self.state.delayed_sequences.add(sequence)+ should_delay = True+ if selected_target:+ self.state.record("primary-delay-target-selected", sequence=sequence,+ assetIndex=asset_index, mode=self.state.mode)+ if not should_delay:+ try:+ self._reply(payload, "video/mp2t")+ self.state.record("stream-close", **event, statusCode=200,+ bytes=len(payload), elapsedMs=(time.monotonic() - opened) * 1000,+ closeReason="body-complete", videoPid=transport["videoPid"])+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as error:+ self.state.record("client-disconnect", **event, phase="normal-segment",+ elapsedMs=(time.monotonic() - opened) * 1000,+ exception=type(error).__name__)+ return++ chunks_per_second = self.state.null_packets_per_second+ if self.state.mode == "delayed-valid":+ delay = self.state.delay_seconds+ filler_count = max(0, int(math.floor(delay * chunks_per_second)))+ filler_bytes = filler_count * PACKET_SIZE+ total_length = len(prefix) + filler_bytes + len(suffix)+ self.send_response(200)+ self.send_header("Content-Type", "video/mp2t")+ self.send_header("Content-Length", str(total_length))+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(prefix)+ self.wfile.flush()+ header_sent = time.monotonic()+ self.state.record("primary-headers-and-psi-sent", **event, statusCode=200,+ prefixBytes=len(prefix), firstVideoPesPacketIndex=transport["firstVideoPesPacketIndex"],+ videoPid=transport["videoPid"], declaredLength=total_length)+ delivered_nulls = 0+ try:+ for index in range(filler_count):+ deadline = header_sent + (index + 1) / chunks_per_second+ remaining = deadline - time.monotonic()+ if remaining > 0:+ time.sleep(remaining)+ self.wfile.write(null_packet(index))+ delivered_nulls += 1+ self.wfile.write(suffix)+ self.wfile.flush()+ self.state.record("primary-playable-pes-sent", **event,+ firstPlayablePesAfterMs=(time.monotonic() - header_sent) * 1000,+ nullPackets=delivered_nulls, bytes=len(suffix),+ videoPid=transport["videoPid"])+ self.state.record("stream-close", **event, bytes=total_length,+ elapsedMs=(time.monotonic() - opened) * 1000,+ closeReason="body-complete")+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as error:+ self.state.record("client-disconnect", **event, phase="delayed-valid",+ deliveredNullPackets=delivered_nulls,+ elapsedMs=(time.monotonic() - opened) * 1000,+ exception=type(error).__name__)+ return++ # Missing-primary mode deliberately keeps a valid HTTP chunked body+ # and null-PID TS packets flowing; no video PES/PTS is sent.+ self.send_response(200)+ self.send_header("Content-Type", "video/mp2t")+ self.send_header("Transfer-Encoding", "chunked")+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.state.record("primary-headers-and-psi-sent", **event, statusCode=200,+ prefixBytes=len(prefix), firstVideoPesPacketIndex=transport["firstVideoPesPacketIndex"],+ videoPid=transport["videoPid"], bodyMode="indefinite-chunked")+ try:+ chunked_write(self, prefix)+ group_size = max(1, int(chunks_per_second / 2))+ counter = 0+ while True:+ deadline = opened + (counter + group_size) / chunks_per_second+ remaining = deadline - time.monotonic()+ if remaining > 0:+ time.sleep(remaining)+ packets = b"".join(null_packet(counter + n) for n in range(group_size))+ chunked_write(self, packets)+ counter += group_size+ if counter % max(group_size, int(chunks_per_second * 5)) == 0:+ self.state.record("primary-null-packet-progress", **event,+ nullPackets=counter,+ elapsedMs=(time.monotonic() - opened) * 1000)+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError) as error:+ self.state.record("client-disconnect", **event, phase="missing-primary",+ elapsedMs=(time.monotonic() - opened) * 1000,+ exception=type(error).__name__)+ return+ return self._reply(b"not found", "text/plain", 404)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--root", required=True, type=pathlib.Path)+ parser.add_argument("--host", default="0.0.0.0")+ parser.add_argument("--port", type=int, default=18798)+ parser.add_argument("--mode", choices=("off", "delayed-valid", "missing-primary",+ "missing-primary-all"), default="off")+ parser.add_argument("--delay-seconds", type=float, default=25.0)+ parser.add_argument("--null-packets-per-second", type=float, default=20.0)+ parser.add_argument("--window-segments", type=int, default=30)+ parser.add_argument("--rendition-profile", choices=("audio-video", "video-subtitles"),+ default="audio-video")+ parser.add_argument("--subtitle-discontinuity-sequence-offset", type=int, default=0,+ help="Optional discontinuity sequence offset applied only to the subtitle playlist")+ args = parser.parse_args()+ if not math.isfinite(args.delay_seconds) or args.delay_seconds < 0:+ raise SystemExit("--delay-seconds must be finite and nonnegative")+ if not math.isfinite(args.null_packets_per_second) or args.null_packets_per_second <= 0:+ raise SystemExit("--null-packets-per-second must be finite and positive")+ if args.window_segments < 6:+ raise SystemExit("--window-segments must be at least six")+ if args.subtitle_discontinuity_sequence_offset < 0:+ raise SystemExit("--subtitle-discontinuity-sequence-offset must be nonnegative")+ root = args.root.resolve(strict=True)+ state = FixtureState(root, args.mode, args.delay_seconds,+ args.null_packets_per_second, args.window_segments,+ args.rendition_profile, args.subtitle_discontinuity_sequence_offset)+ server = ThreadingHTTPServer((args.host, args.port), Handler)+ server.daemon_threads = True+ server.fixture_state = state # type: ignore[attr-defined]+ state.record("started", host=args.host, port=args.port,+ renditionProfile=args.rendition_profile,+ subtitleDiscontinuitySequenceOffset=args.subtitle_discontinuity_sequence_offset)+ print(json.dumps({"host": args.host, "port": args.port, "mode": args.mode,+ "root": str(root), "windowSegments": args.window_segments}), flush=True)+ server.serve_forever()+++if __name__ == "__main__":+ main()diff --git a/tools/tests/test_live_fixture_delay.py b/tools/tests/test_live_fixture_delay.pynew file mode 100644index 00000000..232abf52--- /dev/null+++ b/tools/tests/test_live_fixture_delay.py@@ -0,0 +1,425 @@+import importlib.util+import math+from datetime import datetime+from pathlib import Path+import json+import tempfile+import threading+import time+import urllib.parse+import urllib.error+import urllib.request+from http.server import ThreadingHTTPServer+import unittest+from unittest import mock+++spec = importlib.util.spec_from_file_location(+ "dynamic_live_fixture", Path(__file__).parents[1] / "v5_dynamic_live_fixture_server.py"+)+fixture = importlib.util.module_from_spec(spec)+spec.loader.exec_module(fixture)+++class SegmentDelayTest(unittest.TestCase):+ def test_healthy_mode_never_delays(self):+ for elapsed in (0, 20, 55, 90):+ self.assertEqual(0, fixture.segment_delay_seconds(elapsed, 0, 0, 20))++ def test_only_requests_inside_each_gap_wait_for_its_end(self):+ expected = {19: 0, 20: 6, 22: 4, 26: 0, 49: 0, 50: 6, 55: 1, 56: 0}+ for elapsed, delay in expected.items():+ with self.subTest(elapsed=elapsed):+ self.assertEqual(delay, fixture.segment_delay_seconds(elapsed, 30, 6, 20))+++class SourceShapeTest(unittest.TestCase):+ def test_last_published_segment_has_finished_at_current_wall_clock(self):+ with mock.patch.object(fixture.time, "time", return_value=1_000.0), \+ mock.patch.object(fixture.time, "monotonic", return_value=500.0), \+ mock.patch.dict(fixture.origins, {}, clear=True), \+ mock.patch.dict(fixture.wall_origins, {}, clear=True), \+ mock.patch.dict(fixture.jump_offsets, {"1001": 0}, clear=True):+ playlist = fixture.manifest("1001", "127.0.0.1", 18785)+ dates = [line.split(":", 1)[1] for line in playlist.splitlines()+ if line.startswith("#EXT-X-PROGRAM-DATE-TIME:")]+ self.assertEqual(6, len(dates))+ last_end = datetime.fromisoformat(dates[-1].replace("Z", "+00:00")).timestamp() + 2+ self.assertLessEqual(last_end, 1_000.0)+ self.assertIn("/asset/1001/005.ts", playlist)++ def test_short_window_preserves_initial_wall_clock_alignment(self):+ with mock.patch.object(fixture.time, "time", return_value=1_000.0), \+ mock.patch.object(fixture.time, "monotonic", return_value=500.0), \+ mock.patch.dict(fixture.origins, {}, clear=True), \+ mock.patch.dict(fixture.wall_origins, {}, clear=True), \+ mock.patch.dict(fixture.jump_offsets, {"1001": 0}, clear=True):+ playlist = fixture.manifest("1001", "127.0.0.1", 18785, 10.0, window_size=3)+ dates = [line.split(":", 1)[1] for line in playlist.splitlines()+ if line.startswith("#EXT-X-PROGRAM-DATE-TIME:")]+ self.assertEqual(3, len(dates))+ first_start = datetime.fromisoformat(dates[0].replace("Z", "+00:00")).timestamp()+ last_end = datetime.fromisoformat(dates[-1].replace("Z", "+00:00")).timestamp() + 2+ self.assertEqual(994.0, first_start)+ self.assertLessEqual(last_end, 1_000.0)+ self.assertIn("/asset/1001/002.ts", playlist)+ self.assertIn("#EXT-X-SERVER-CONTROL:HOLD-BACK=10.0", playlist)++ def test_hold_back_is_optional_and_respects_three_target_duration_floor(self):+ self.assertIsNone(fixture.validated_hold_back_seconds(None))+ self.assertEqual(6, fixture.validated_hold_back_seconds(6))+ with self.assertRaisesRegex(ValueError, "at least 6 seconds"):+ fixture.validated_hold_back_seconds(5.999)+ for invalid in (math.nan, math.inf, -math.inf):+ with self.subTest(invalid=invalid), self.assertRaisesRegex(ValueError, "finite"):+ fixture.validated_hold_back_seconds(invalid)++ def test_manifest_omits_hold_back_by_default_and_emits_explicit_value(self):+ fixture.origins.clear()+ fixture.wall_origins.clear()+ default = fixture.manifest("1001", "127.0.0.1", 18785)+ self.assertNotIn("#EXT-X-SERVER-CONTROL", default)+ with_hold_back = fixture.manifest("1001", "127.0.0.1", 18785, 6)+ self.assertIn("#EXT-X-SERVER-CONTROL:HOLD-BACK=6.0", with_hold_back)++ def test_paced_schedule_uses_bounded_chunks_and_absolute_byte_deadlines(self):+ schedule = fixture.paced_chunk_schedule(25, 80, chunk_bytes=10)+ self.assertEqual([(0, 10, 0.0), (10, 10, 2.0), (20, 5, 2.5)], schedule)++ def test_unlimited_delivery_is_immediate_and_still_chunked(self):+ schedule = fixture.paced_chunk_schedule(25, None, chunk_bytes=10)+ self.assertEqual([(0, 10, 0.0), (10, 10, 0.0), (20, 5, 0.0)], schedule)++ def test_invalid_pacing_settings_are_rejected(self):+ for args in ((-1, None, 10), (1, 0, 10), (1, None, 0)):+ with self.subTest(args=args), self.assertRaises(ValueError):+ fixture.paced_chunk_schedule(*args)++ def test_reset_archives_prior_run_events(self):+ old_events = list(fixture.events)+ old_completed = list(fixture.completed_runs)+ old_run_number = fixture.run_number+ try:+ fixture.events.clear()+ fixture.completed_runs.clear()+ fixture.run_number = 7+ fixture.record("test-event", marker="keep")+ fixture.archive_current_run()+ self.assertEqual(8, fixture.run_number)+ self.assertEqual("keep", fixture.completed_runs[0]["events"][0]["marker"])+ self.assertEqual([], fixture.events)+ finally:+ fixture.events[:] = old_events+ fixture.completed_runs[:] = old_completed+ fixture.run_number = old_run_number+++class RefusalInjectionTest(unittest.TestCase):+ def test_segment_404_is_one_shot_for_same_url_and_does_not_refuse_playlists(self):+ injector = fixture.RefusalInjector("segment-404-once", after_seconds=20)++ before = injector.decide("media-segment", "1001", 10, 0, 19.999)+ first = injector.decide("media-segment", "1001", 10, 0, 20.0)+ retry = injector.decide("media-segment", "1001", 10, 0, 20.1)+ next_segment = injector.decide("media-segment", "1001", 11, 0, 21.0)+ playlist = injector.decide("playlist", "1001", 8, None, 22.0)++ self.assertEqual(200, before["statusCode"])+ self.assertEqual(404, first["statusCode"])+ self.assertEqual(2, first["attempts"])+ self.assertEqual(200, retry["statusCode"])+ self.assertEqual(3, retry["attempts"])+ self.assertEqual(200, next_segment["statusCode"])+ self.assertEqual(200, playlist["statusCode"])++ def test_segment_404_can_repeat_only_once_per_configured_period(self):+ injector = fixture.RefusalInjector(+ "segment-404-once", after_seconds=20, period_seconds=30+ )++ self.assertEqual(404, injector.decide("media-segment", "1001", 10, 0, 20)["statusCode"])+ self.assertEqual(200, injector.decide("media-segment", "1001", 10, 0, 21)["statusCode"])+ self.assertEqual(200, injector.decide("media-segment", "1001", 10, 0, 50)["statusCode"])+ self.assertEqual(404, injector.decide("media-segment", "1001", 11, 0, 50.1)["statusCode"])+ self.assertEqual(200, injector.decide("media-segment", "1001", 11, 0, 50.2)["statusCode"])++ def test_stale_generation_refuses_old_uri_and_accepts_rotated_uri_for_same_sequence(self):+ injector = fixture.RefusalInjector("segment-403-rotate", after_seconds=20)+ with mock.patch.object(fixture.time, "time", return_value=1_000.0), \+ mock.patch.object(fixture.time, "monotonic", return_value=500.0), \+ mock.patch.dict(fixture.origins, {}, clear=True), \+ mock.patch.dict(fixture.wall_origins, {}, clear=True), \+ mock.patch.dict(fixture.jump_offsets, {"1001": 0}, clear=True):+ before = fixture.manifest(+ "1001", "127.0.0.1", 18785,+ token_generation_for_segment=injector.generation_for+ )+ refusal = injector.decide("media-segment", "1001", 3, 0, 20)+ after = fixture.manifest(+ "1001", "127.0.0.1", 18785,+ token_generation_for_segment=injector.generation_for+ )++ old_uri = "/asset/1001/003.ts?generation=0"+ new_uri = "/asset/1001/003.ts?generation=1"+ self.assertIn(old_uri, before)+ self.assertNotIn(old_uri, after)+ self.assertIn(new_uri, after)+ self.assertEqual(403, refusal["statusCode"])+ self.assertEqual(403, injector.decide("media-segment", "1001", 3, 0, 20.1)["statusCode"])+ accepted = injector.decide("media-segment", "1001", 3, 1, 20.2)+ self.assertEqual(200, accepted["statusCode"])+ self.assertEqual(1, accepted["attempts"])+ self.assertEqual(200, injector.decide("playlist", "1001", 0, None, 21)["statusCode"])++ def test_reset_clears_failure_selection_generations_and_uri_attempt_counts(self):+ injector = fixture.RefusalInjector("segment-403-rotate", after_seconds=20)+ first = injector.decide("media-segment", "1001", 10, 0, 20)+ self.assertEqual(403, first["statusCode"])+ self.assertEqual(1, injector.generation_for("1001", 10))++ injector.reset()++ self.assertEqual({}, injector.snapshot()["selectedSequences"])+ self.assertEqual([], injector.snapshot()["tokenGenerations"])+ after_reset = injector.decide("media-segment", "1001", 10, 0, 20)+ self.assertEqual(403, after_reset["statusCode"])+ self.assertEqual(1, after_reset["attempts"])++ def test_playlist_403_negative_control_never_refuses_media_segments(self):+ injector = fixture.RefusalInjector("playlist-403-after-start", after_seconds=20)++ self.assertEqual(200, injector.decide("playlist", "1001", 10, None, 19.9)["statusCode"])+ self.assertEqual(403, injector.decide("playlist", "1001", 10, None, 20)["statusCode"])+ self.assertEqual(403, injector.decide("playlist", "1001", 11, None, 21)["statusCode"])+ self.assertEqual(200, injector.decide("media-segment", "1001", 10, 0, 21)["statusCode"])++ def test_permanent_media_403_refuses_new_sequences_but_not_playlists_and_resets(self):+ injector = fixture.RefusalInjector("segment-403-permanent-after-start", after_seconds=20)++ self.assertEqual(200, injector.decide("media-segment", "1001", 10, 0, 19.9)["statusCode"])+ self.assertEqual(403, injector.decide("media-segment", "1001", 10, 0, 20)["statusCode"])+ self.assertEqual(403, injector.decide("media-segment", "1001", 11, 0, 20.1)["statusCode"])+ self.assertEqual(200, injector.decide("playlist", "1001", 11, None, 20.2)["statusCode"])++ injector.reset()++ self.assertEqual(403, injector.decide("media-segment", "1001", 10, 0, 20.3)["statusCode"])+ self.assertEqual(200, injector.decide("playlist", "1001", 10, None, 20.4)["statusCode"])++ def test_injector_exposes_http_status_field_for_unrun_410_case(self):+ injector = fixture.RefusalInjector(+ "segment-404-once", after_seconds=20, status_code=410+ )+ decision = injector.decide("media-segment", "1001", 10, 0, 20)++ self.assertEqual(410, decision["statusCode"])++ def test_refusal_configuration_rejects_invalid_mode_timing_and_status(self):+ with self.assertRaisesRegex(ValueError, "unsupported refusal mode"):+ fixture.RefusalInjector("all-urls")+ with self.assertRaisesRegex(ValueError, "finite and nonnegative"):+ fixture.RefusalInjector("segment-404-once", after_seconds=float("nan"))+ with self.assertRaisesRegex(ValueError, "supported only"):+ fixture.RefusalInjector("segment-403-rotate", period_seconds=30)+ with self.assertRaisesRegex(ValueError, "403, 404, or 410"):+ fixture.RefusalInjector("segment-404-once", status_code=401)+++class RefusalHttpIntegrationTest(unittest.TestCase):+ def setUp(self):+ self.original_events = list(fixture.events)+ self.original_origins = dict(fixture.origins)+ self.original_wall_origins = dict(fixture.wall_origins)+ self.original_jump_offsets = dict(fixture.jump_offsets)+ fixture.events.clear()+ fixture.origins.clear()+ fixture.wall_origins.clear()+ fixture.jump_offsets.clear()+ fixture.jump_offsets.update({channel: 0 for channel in fixture.CHANNELS})++ def tearDown(self):+ fixture.events[:] = self.original_events+ fixture.origins.clear()+ fixture.origins.update(self.original_origins)+ fixture.wall_origins.clear()+ fixture.wall_origins.update(self.original_wall_origins)+ fixture.jump_offsets.clear()+ fixture.jump_offsets.update(self.original_jump_offsets)++ def create_server(self, mode):+ media_root = tempfile.TemporaryDirectory()+ for number in range(6):+ (Path(media_root.name) / f"segment_{number:03d}.ts").write_bytes(+ f"segment-{number}".encode()+ )+ server = ThreadingHTTPServer(("127.0.0.1", 0), fixture.Handler)+ server.segment_root = Path(media_root.name)+ server.stall_period = 0+ server.stall_duration = 0+ server.stall_start = 20+ server.stall_origin = time.monotonic() - 25+ server.hold_back_seconds = None+ server.window_size = 6+ server.segment_rate_cap_bps = None+ server.refusal_injector = fixture.RefusalInjector(mode, after_seconds=20)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()++ def close():+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)+ media_root.cleanup()++ self.addCleanup(close)+ return f"http://127.0.0.1:{server.server_port}", server++ @staticmethod+ def request(url):+ try:+ with urllib.request.urlopen(url, timeout=2) as response:+ return response.status, response.headers, response.read()+ except urllib.error.HTTPError as error:+ return error.code, error.headers, error.read()++ def test_public_host_covers_account_stream_and_manifest_urls_with_default_preserved(self):+ base, server = self.create_server("off")+ for host in ("10.0.2.2", "127.0.0.1"):+ with self.subTest(host=host):+ if host == "127.0.0.1":+ server.public_host = host+ status, _, body = self.request(f"{base}/player_api.php")+ self.assertEqual(200, status)+ self.assertEqual(host, json.loads(body)["server_info"]["url"])+ status, _, body = self.request(f"{base}/player_api.php?action=get_live_streams")+ self.assertEqual(200, status)+ for stream in json.loads(body):+ source = urllib.parse.urlsplit(stream["direct_source"])+ self.assertEqual(host, source.hostname)+ self.assertEqual(server.server_port, source.port)+ status, _, body = self.request(f"{base}/live/v5/v5/1001.m3u8")+ self.assertEqual(200, status)+ uris = [line for line in body.decode().splitlines() if line and not line.startswith("#")]+ self.assertTrue(uris)+ for uri in uris:+ parsed = urllib.parse.urlsplit(uri)+ self.assertEqual(host, parsed.hostname)+ self.assertEqual(server.server_port, parsed.port)++ def test_segment_404_is_empty_same_url_retry_succeeds_and_playlist_stays_200(self):+ base, server = self.create_server("segment-404-once")+ playlist_status, _, playlist_body = self.request(f"{base}/live/v5/v5/1001.m3u8")+ first_status, first_headers, first_body = self.request(f"{base}/asset/1001/003.ts")+ retry_status, _, retry_body = self.request(f"{base}/asset/1001/003.ts")+ event_status, _, event_body = self.request(f"{base}/events")+ events = json.loads(event_body)["events"]+ responses = [event for event in events if event["event"] == "http-response"]++ self.assertEqual(200, playlist_status)+ self.assertIn(b"#EXTM3U", playlist_body)+ self.assertEqual(404, first_status)+ self.assertEqual("0", first_headers["Content-Length"])+ self.assertEqual(b"", first_body)+ self.assertEqual(200, retry_status)+ self.assertEqual(b"segment-3", retry_body)+ self.assertEqual(200, event_status)+ media_responses = [event for event in responses if event["role"] == "media-segment"]+ self.assertEqual([404, 200], [event["statusCode"] for event in media_responses])+ self.assertEqual([1, 2], [event["attempts"] for event in media_responses])+ self.assertEqual([0, len(retry_body)], [event["bytes"] for event in media_responses])+ playlist_responses = [event for event in responses if event["role"] == "playlist"]+ self.assertEqual([200], [event["statusCode"] for event in playlist_responses])+ self.assertEqual("segment-404-once", server.refusal_injector.mode)++ def test_segment_403_rotates_only_same_sequence_generation_and_tracks_attempts(self):+ base, _ = self.create_server("segment-403-rotate")+ playlist_url = f"{base}/live/v5/v5/1001.m3u8"+ playlist_status, _, initial_manifest = self.request(playlist_url)+ self.assertEqual(200, playlist_status)+ initial_segment_url = next(+ line for line in initial_manifest.decode().splitlines()+ if "/asset/1001/003.ts?generation=0" in line+ )+ initial_path = urllib.parse.urlsplit(initial_segment_url).path+ first_status, first_headers, first_body = self.request(+ f"{base}{initial_path}?generation=0"+ )+ self.assertEqual(403, first_status)+ self.assertEqual("0", first_headers["Content-Length"])+ self.assertEqual(b"", first_body)++ second_playlist_status, _, rotated_manifest = self.request(playlist_url)+ self.assertEqual(200, second_playlist_status)+ rotated_segment_url = next(+ line for line in rotated_manifest.decode().splitlines()+ if "/asset/1001/003.ts?generation=1" in line+ )+ rotated_path = urllib.parse.urlsplit(rotated_segment_url).path+ old_retry_status, _, _ = self.request(f"{base}{initial_path}?generation=0")+ new_generation_status, _, payload = self.request(+ f"{base}{rotated_path}?generation=1"+ )+ event_status, _, event_body = self.request(f"{base}/events")+ response_events = [+ event for event in json.loads(event_body)["events"]+ if event["event"] == "http-response"+ ]+ media_events = [event for event in response_events if event["role"] == "media-segment"]+ playlist_events = [event for event in response_events if event["role"] == "playlist"]++ self.assertEqual(403, old_retry_status)+ self.assertEqual(200, new_generation_status)+ self.assertTrue(payload.startswith(b"segment-3"))+ self.assertEqual(200, event_status)+ self.assertEqual([0, 0, 1], [event["tokenGeneration"] for event in media_events])+ self.assertEqual([403, 403, 200], [event["statusCode"] for event in media_events])+ self.assertEqual([1, 2, 1], [event["attempts"] for event in media_events])+ self.assertEqual([200, 200], [event["statusCode"] for event in playlist_events])+ self.assertTrue(any(+ {"sequence": 3, "generation": 1} in event["advertisedTokenGenerations"]+ for event in playlist_events+ ))++ def test_playlist_403_negative_control_leaves_media_segments_healthy(self):+ base, _ = self.create_server("playlist-403-after-start")+ status, headers, body = self.request(f"{base}/live/v5/v5/1001.m3u8")+ media_status, _, media_body = self.request(f"{base}/asset/1001/003.ts")+ events_status, _, events_body = self.request(f"{base}/events")+ response_events = [+ event for event in json.loads(events_body)["events"]+ if event["event"] == "http-response"+ ]++ self.assertEqual(403, status)+ self.assertEqual("0", headers["Content-Length"])+ self.assertEqual(b"", body)+ self.assertEqual(200, media_status)+ self.assertEqual(b"segment-3", media_body)+ self.assertEqual(200, events_status)+ self.assertEqual([403, 200], [event["statusCode"] for event in response_events])+ self.assertEqual(["playlist", "media-segment"], [event["role"] for event in response_events])++ def test_permanent_media_403_is_recorded_per_sequence_while_playlists_stay_healthy(self):+ base, _ = self.create_server("segment-403-permanent-after-start")+ first_media_status, _, _ = self.request(f"{base}/asset/1001/003.ts")+ next_media_status, _, _ = self.request(f"{base}/asset/1001/004.ts")+ playlist_status, _, playlist_body = self.request(f"{base}/live/v5/v5/1001.m3u8")+ events_status, _, events_body = self.request(f"{base}/events")+ response_events = [+ event for event in json.loads(events_body)["events"]+ if event["event"] == "http-response"+ ]++ self.assertEqual([403, 403], [first_media_status, next_media_status])+ self.assertEqual(200, playlist_status)+ self.assertIn(b"#EXTM3U", playlist_body)+ self.assertEqual(200, events_status)+ self.assertEqual(+ [("media-segment", 3, 403), ("media-segment", 4, 403), ("playlist", 0, 200)],+ [(event["role"], event["sequence"], event["statusCode"]) for event in response_events],+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/tests/test_raw_ts_backpressure_fixture_server.py b/tools/tests/test_raw_ts_backpressure_fixture_server.pynew file mode 100644index 00000000..4e75261a--- /dev/null+++ b/tools/tests/test_raw_ts_backpressure_fixture_server.py@@ -0,0 +1,259 @@+import http.client+from pathlib import Path+import tempfile+import threading+import time+import unittest++from tools.raw_ts_backpressure_fixture_server import (+ TS_PACKET_BYTES,+ chunk_payload,+ create_server,+ paced_deadline_seconds,+ sha256_file,+ scan_transport_stream,+)+++def valid_ts_packets(count: int) -> bytes:+ packets = []+ for index in range(count):+ packets.append(bytes((+ [0x47, 0x01, 0x00, 0x10 | (index & 0x0F)] + [0xFF] * 184+ )))+ return b"".join(packets)+++class RawTsFixtureHelpersTest(unittest.TestCase):+ def test_scanner_accepts_continuous_packet_stream_and_rejects_sync_or_counter_errors(self):+ with tempfile.TemporaryDirectory() as directory:+ media = Path(directory) / "valid.ts"+ media.write_bytes(valid_ts_packets(32))+ result = scan_transport_stream(media)+ self.assertEqual(32 * TS_PACKET_BYTES, result["bytes"])+ self.assertEqual(32, result["packets"])+ self.assertEqual(0, result["badSync"])+ self.assertEqual(0, result["continuityErrors"])++ bad_sync = Path(directory) / "bad-sync.ts"+ bad_sync.write_bytes(b"X" + valid_ts_packets(2)[1:])+ with self.assertRaisesRegex(ValueError, "badSync=1"):+ scan_transport_stream(bad_sync)++ bad_counter = bytearray(valid_ts_packets(3))+ bad_counter[2 * TS_PACKET_BYTES + 3] = 0x17+ bad_cc = Path(directory) / "bad-counter.ts"+ bad_cc.write_bytes(bad_counter)+ with self.assertRaisesRegex(ValueError, "continuityErrors=1"):+ scan_transport_stream(bad_cc)++ def test_absolute_pacing_deadlines_and_packet_aligned_chunks(self):+ self.assertEqual(0.0, paced_deadline_seconds(0, 80.0))+ self.assertEqual(2.0, paced_deadline_seconds(20, 80.0))+ self.assertEqual(2.5, paced_deadline_seconds(25, 80.0))+ payload = bytes(range(256)) * 200+ chunks = list(chunk_payload(payload, 188 * 4))+ self.assertEqual(payload, b"".join(chunks))+ self.assertTrue(all(len(chunk) % 188 == 0 for chunk in chunks[:-1]))+ with self.assertRaisesRegex(ValueError, "multiple of 188"):+ list(chunk_payload(b"x", 64))++ def test_pacing_timeout_and_buffer_settings_are_validated(self):+ with tempfile.TemporaryDirectory() as directory:+ media = Path(directory) / "valid.ts"+ media.write_bytes(valid_ts_packets(8))+ for kwargs in (+ {"pace_multiplier": 0},+ {"media_duration_seconds": 0},+ {"send_buffer_bytes": 0},+ {"send_timeout_seconds": -1},+ {"send_timeout_seconds": float("nan")},+ {"chunk_bytes": 187},+ {"continuation_file": media},+ ):+ with self.subTest(kwargs=kwargs), self.assertRaises(ValueError):+ options = {+ "media_file": media,+ "port": 0,+ "pace_multiplier": 1.0,+ "media_duration_seconds": 10.0,+ "send_buffer_bytes": 4096,+ "send_timeout_seconds": 0.0,+ }+ options.update(kwargs)+ create_server(**options)+++class RawTsFixtureHttpTest(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory()+ self.media = Path(self.temp.name) / "stream.ts"+ self.media.write_bytes(valid_ts_packets(512))+ self.server = create_server(+ media_file=self.media,+ port=0,+ pace_multiplier=1.0,+ media_duration_seconds=0.01,+ send_buffer_bytes=4096,+ send_timeout_seconds=0,+ chunk_bytes=188 * 32,+ write_block_threshold_ms=10,+ )+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)+ self.thread.start()+ self.addCleanup(self._close)+ self.host, self.port = self.server.server_address++ def _close(self):+ self.server.shutdown()+ self.server.server_close()+ self.thread.join(timeout=2)+ self.temp.cleanup()++ def test_fast_reader_gets_one_chunked_stream_and_events_report_settings(self):+ connection = http.client.HTTPConnection(self.host, self.port, timeout=5)+ connection.request("GET", "/raw/1001.ts")+ response = connection.getresponse()+ self.assertEqual(200, response.status)+ self.assertEqual("chunked", response.getheader("Transfer-Encoding"))+ self.assertIsNone(response.getheader("Content-Length"))+ self.assertEqual(self.media.read_bytes(), response.read())+ connection.close()++ events = self._get_json("/events")+ self.assertEqual(1, len(events["events"]))+ stream = events["events"][0]+ self.assertEqual("raw-stream", stream["event"])+ self.assertEqual("1001", stream["channel"])+ self.assertEqual("complete", stream["connectionCloseReason"])+ self.assertEqual(self.media.stat().st_size, stream["bytesSent"])+ self.assertGreater(stream["sendallCalls"], 1)+ self.assertIsNotNone(stream["sendBufferBytesActual"])+ self.assertEqual(0.0, stream["sendTimeoutSeconds"])+ self.assertEqual(1, stream["requestIndex"])+ self.assertEqual(str(self.media.resolve()), stream["mediaFile"])+ self.assertEqual(sha256_file(self.media), stream["mediaSha256"])+ self.assertIsNone(events["settings"]["continuationFile"])++ def test_continuation_is_selected_after_first_request_and_reset_restarts_sequence(self):+ continuation = Path(self.temp.name) / "continuation.ts"+ continuation.write_bytes(valid_ts_packets(256))+ self.server.continuation_file = continuation.resolve()+ self.server.continuation_scan = scan_transport_stream(continuation)+ self.server.continuation_duration_seconds = 0.01+ self.server.continuation_wire_rate_bps = continuation.stat().st_size * 8 / 0.01+ self.server.continuation_sha256 = sha256_file(continuation)++ def get_body():+ connection = http.client.HTTPConnection(self.host, self.port, timeout=5)+ connection.request("GET", "/raw/1001.ts")+ response = connection.getresponse()+ self.assertEqual(200, response.status)+ body = response.read()+ connection.close()+ return body++ first_body = get_body()+ second_body = get_body()+ third_body = get_body()+ self.assertEqual(self.media.read_bytes(), first_body)+ self.assertEqual(continuation.read_bytes(), second_body)+ self.assertEqual(continuation.read_bytes(), third_body)++ events = self._get_json("/events")+ self.assertEqual([1, 2, 3], [row["requestIndex"] for row in events["events"]])+ self.assertEqual(+ [str(self.media.resolve()), str(continuation.resolve()), str(continuation.resolve())],+ [row["mediaFile"] for row in events["events"]],+ )+ self.assertEqual(+ [self.media.stat().st_size, continuation.stat().st_size, continuation.stat().st_size],+ [row["bytesSent"] for row in events["events"]],+ )+ self.assertEqual(+ [sha256_file(self.media), sha256_file(continuation), sha256_file(continuation)],+ [row["mediaSha256"] for row in events["events"]],+ )+ self.assertTrue(all(row["connectionCloseReason"] == "complete" for row in events["events"]))++ reset = self._get_json("/control?reset=1")+ self.assertTrue(reset["ok"])+ reset_body = get_body()+ self.assertEqual(self.media.read_bytes(), reset_body)+ reset_events = self._get_json("/events")["events"]+ self.assertEqual(1, len(reset_events))+ self.assertEqual(1, reset_events[0]["requestIndex"])+ self.assertEqual(str(self.media.resolve()), reset_events[0]["mediaFile"])++ def test_stalled_reader_records_real_blocked_send_timeout_not_pacing_wait(self):+ # Reduce the server send queue, leave the HTTP response unread, and send+ # enough real bytes for the kernel to apply TCP backpressure.+ self.media.write_bytes(valid_ts_packets(32_768))+ self.server.media_scan = scan_transport_stream(self.media)+ self.server.media_file = self.media+ self.server.media_duration_seconds = 0.01+ self.server.wire_rate_bps = self.media.stat().st_size * 8 / 0.01+ self.server.send_timeout_seconds = 0.15+ self.server.send_buffer_bytes = 4096+ self.server.chunk_bytes = 188 * 256++ connection = http.client.HTTPConnection(self.host, self.port, timeout=5)+ connection.request("GET", "/raw/1002.ts")+ response = connection.getresponse() # Read headers only; intentionally do not consume the body.+ self.assertEqual(200, response.status)+ self.assertEqual("chunked", response.getheader("Transfer-Encoding"))++ deadline = time.monotonic() + 3+ while time.monotonic() < deadline:+ events = self._get_json("/events")+ if events["events"]:+ break+ time.sleep(0.02)+ connection.close()+ self.assertEqual(1, len(events["events"]))+ stream = events["events"][0]+ self.assertEqual("send-timeout", stream["connectionCloseReason"])+ self.assertGreater(stream["maxSendallMs"], 100)+ self.assertGreater(stream["sendallCalls"], 0)+ self.assertGreaterEqual(stream["pacingWaitSeconds"], 0)+ self.assertTrue(stream.get("partialChunkMayHaveBeenSent", False))+ self.assertTrue(stream["failedWrites"])+ self.assertEqual("send-timeout", stream["failedWrites"][-1]["outcome"])+ self.assertGreater(stream["sendBufferBytesActual"], 0)++ def test_real_pacing_wait_is_reported_separately_from_sendall_time(self):+ self.server.media_duration_seconds = 0.2+ self.server.wire_rate_bps = self.media.stat().st_size * 8 / 0.2+ self.server.send_timeout_seconds = 0+ started = time.monotonic()+ connection = http.client.HTTPConnection(self.host, self.port, timeout=5)+ connection.request("GET", "/raw/1001.ts")+ response = connection.getresponse()+ payload = response.read()+ elapsed = time.monotonic() - started+ connection.close()++ self.assertEqual(self.media.read_bytes(), payload)+ self.assertGreaterEqual(elapsed, 0.15)+ events = self._get_json("/events")+ stream = events["events"][0]+ self.assertEqual("complete", stream["connectionCloseReason"])+ self.assertGreater(stream["pacingWaitSeconds"], 0.05)+ wall_delta = stream["beganUnixSeconds"] - stream["startedUnixSeconds"]+ monotonic_delta = stream["beganElapsedMonotonic"] - stream["startedMonotonicSeconds"]+ self.assertLess(abs(wall_delta - monotonic_delta), 0.1)+ self.assertGreaterEqual(stream["totalSendallMs"], 0)++ def _get_json(self, path):+ connection = http.client.HTTPConnection(self.host, self.port, timeout=5)+ connection.request("GET", path)+ response = connection.getresponse()+ payload = response.read()+ connection.close()+ self.assertEqual(200, response.status)+ import json+ return json.loads(payload)+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/tests/test_split_hls_timestamp_fixture_server.py b/tools/tests/test_split_hls_timestamp_fixture_server.pynew file mode 100644index 00000000..ec853028--- /dev/null+++ b/tools/tests/test_split_hls_timestamp_fixture_server.py@@ -0,0 +1,444 @@+from __future__ import annotations++import json+import pathlib+import re+import sys+import tempfile+import threading+import time+import unittest+import urllib.request+from http.server import ThreadingHTTPServer++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))++from split_hls_timestamp_fixture_server import ( # noqa: E402+ FixtureState,+ Handler,+ PACKET_SIZE,+ build_prefix_and_suffix,+ find_program_packets,+ null_packet,+ ts_packets,+)+++def _ts_packet(pid: int, payload: bytes, *, start: bool = False, cc: int = 0) -> bytes:+ header = bytes((0x47, ((0x40 if start else 0) | ((pid >> 8) & 0x1F)), pid & 0xFF,+ 0x10 | (cc & 0x0F)))+ if len(payload) > PACKET_SIZE - 4:+ raise ValueError("payload too long")+ return header + payload + b"\xff" * (PACKET_SIZE - 4 - len(payload))+++def _test_avc_ts() -> bytes:+ # PAT: program 1 -> PMT PID 0x100.+ pat = bytes.fromhex("00 b0 0d 00 01 c1 00 00 00 01 e1 00 00 00 00 00")+ # PMT: program 1, PCR/video PID 0x101, AVC stream type 0x1b.+ pmt = bytes.fromhex("02 b0 12 00 01 c1 00 00 e1 01 f0 00 1b e1 01 f0 00 00 00 00 00")+ pts = bytes((0x21, 0x00, 0x01, 0x00, 0x01))+ pes = b"\x00\x00\x01\xe0\x00\x00\x80\x80\x05" + pts + b"\x00\x00\x01\x65\xaa\xbb"+ return b"".join((+ _ts_packet(0, b"\x00" + pat, start=True),+ _ts_packet(0x100, b"\x00" + pmt, start=True),+ _ts_packet(0x101, pes, start=True),+ ))+++class SplitHlsTimestampFixtureServerTest(unittest.TestCase):+ def test_extracts_program_psi_and_first_playable_video_pes(self) -> None:+ payload = _test_avc_ts()+ details = find_program_packets(payload)+ self.assertEqual(0x100, details["pmtPid"])+ self.assertEqual(0x101, details["videoPid"])+ self.assertEqual(2, details["firstVideoPesPacketIndex"])+ prefix, suffix, _ = build_prefix_and_suffix(payload)+ self.assertEqual(payload[:2 * PACKET_SIZE], prefix)+ self.assertEqual(payload[2 * PACKET_SIZE:], suffix)++ def test_null_packet_uses_null_pid_and_is_well_formed_ts(self) -> None:+ packet = null_packet(7)+ self.assertEqual(PACKET_SIZE, len(packet))+ self.assertEqual(0x1FFF, ((packet[1] & 0x1F) << 8) | packet[2])+ self.assertEqual([packet], ts_packets(packet))++ def test_master_and_renditions_are_separate_and_aligned(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = pathlib.Path(temporary)+ for role in ("video", "audio"):+ (root / role).mkdir()+ for index in range(6):+ (root / role / f"segment_{index:03d}.ts").write_bytes(_test_avc_ts())+ metadata = {+ "video": {"codecString": "avc1.42C01E",+ "segments": [{"file": f"segment_{i:03d}.ts", "durationSeconds": 2.0}+ for i in range(6)]},+ "audio": {"codecString": "mp4a.40.2",+ "segments": [{"file": f"segment_{i:03d}.ts", "durationSeconds": 2.0}+ for i in range(6)]},+ }+ (root / "media.json").write_text(json.dumps(metadata), encoding="utf-8")+ state = FixtureState(root, "off", 0.1, 20.0, 6)+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server.fixture_state = state+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ base = f"http://127.0.0.1:{server.server_port}"+ master = urllib.request.urlopen(base + "/master.m3u8", timeout=2).read().decode()+ video = urllib.request.urlopen(base + "/video/index.m3u8", timeout=2).read().decode()+ audio = urllib.request.urlopen(base + "/audio/index.m3u8", timeout=2).read().decode()+ self.assertIn('CODECS="avc1.42C01E,mp4a.40.2"', master)+ self.assertIn('URI="audio/index.m3u8"', master)+ self.assertIn("video/index.m3u8", master)+ video_sequence, video_rows = self._playlist_rows(video, "video", "ts")+ audio_sequence, audio_rows = self._playlist_rows(audio, "audio", "ts")+ self.assertEqual(6, len(video_rows))+ self.assertEqual(6, len(audio_rows))+ self.assertEqual(video_sequence, video_rows[0][0])+ self.assertEqual(audio_sequence, audio_rows[0][0])+ self.assertEqual(+ list(range(video_sequence, video_sequence + len(video_rows))),+ [row[0] for row in video_rows],+ )+ self.assertEqual(+ list(range(audio_sequence, audio_sequence + len(audio_rows))),+ [row[0] for row in audio_rows],+ )+ common_sequences = set(row[0] for row in video_rows) & set(row[0] for row in audio_rows)+ self.assertGreaterEqual(len(common_sequences), 5)+ video_program_dates = {sequence: program_date for sequence, program_date, _ in video_rows}+ audio_program_dates = {sequence: program_date for sequence, program_date, _ in audio_rows}+ video_durations = {sequence: duration for sequence, _, duration in video_rows}+ audio_durations = {sequence: duration for sequence, _, duration in audio_rows}+ for sequence in common_sequences:+ self.assertEqual(video_program_dates[sequence], audio_program_dates[sequence])+ self.assertEqual(video_durations[sequence], audio_durations[sequence])+ finally:+ server.shutdown()+ server.server_close()+ thread.join(1)++ @staticmethod+ def _playlist_rows(playlist: str, role: str, extension: str) -> tuple[int, list[tuple[int, str, str]]]:+ rows = playlist.splitlines()+ media_sequence = next(+ int(line.split(":", 1)[1]) for line in rows+ if line.startswith("#EXT-X-MEDIA-SEQUENCE:")+ )+ segments: list[tuple[int, str, str]] = []+ program_date: str | None = None+ duration: str | None = None+ for line in rows:+ if line.startswith("#EXT-X-PROGRAM-DATE-TIME:"):+ program_date = line.split(":", 1)[1]+ elif line.startswith("#EXTINF:"):+ duration = line.split(":", 1)[1].split(",", 1)[0]+ elif line.startswith(f"/{role}/segment/"):+ match = re.fullmatch(rf"/{role}/segment/(\d+)\.{extension}", line)+ if match is None or program_date is None or duration is None:+ raise AssertionError(f"Malformed {role} playlist segment row: {line}")+ segments.append((int(match.group(1)), program_date, duration))+ program_date = None+ duration = None+ return media_sequence, segments++ def test_delayed_valid_sends_psi_then_paced_nulls_then_original_pes(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = pathlib.Path(temporary)+ for role in ("video", "audio"):+ (root / role).mkdir()+ for index in range(6):+ (root / role / f"segment_{index:03d}.ts").write_bytes(_test_avc_ts())+ rows = [{"file": f"segment_{i:03d}.ts", "durationSeconds": 2.0} for i in range(6)]+ (root / "media.json").write_text(json.dumps({"video": {"codecString": "avc1.42C01E", "segments": rows},+ "audio": {"codecString": "mp4a.40.2", "segments": rows}}), encoding="utf-8")+ state = FixtureState(root, "delayed-valid", 0.12, 25.0, 6)+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server.fixture_state = state+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ base = f"http://127.0.0.1:{server.server_port}"+ request_started = time.monotonic()+ with urllib.request.urlopen(base + "/video/segment/5.ts", timeout=2) as response:+ body = response.read()+ self.assertEqual(200, response.status)+ elapsed = time.monotonic() - request_started+ self.assertGreaterEqual(elapsed, 0.10)+ prefix, suffix, _ = build_prefix_and_suffix(_test_avc_ts())+ self.assertEqual(prefix, body[:len(prefix)])+ expected_null_count = math_floor(0.12 * 25.0)+ null_start = len(prefix)+ nulls = body[null_start:null_start + expected_null_count * PACKET_SIZE]+ self.assertEqual(expected_null_count * PACKET_SIZE, len(nulls))+ self.assertTrue(all(((packet[1] & 0x1F) << 8 | packet[2]) == 0x1FFF+ for packet in ts_packets(nulls)))+ self.assertEqual(suffix, body[null_start + len(nulls):])+ events = state.events+ self.assertEqual(1, sum(row["event"] == "primary-delay-target-selected" for row in events))+ sent = next(row for row in events if row["event"] == "primary-playable-pes-sent")+ self.assertGreaterEqual(sent["firstPlayablePesAfterMs"], 100)+ self.assertEqual(expected_null_count, sent["nullPackets"])+ finally:+ server.shutdown()+ server.server_close()+ thread.join(1)++ def test_video_subtitle_profile_uses_non_audio_text_rendition(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = pathlib.Path(temporary)+ for role in ("video", "audio"):+ (root / role).mkdir()+ for index in range(6):+ (root / role / f"segment_{index:03d}.ts").write_bytes(_test_avc_ts())+ rows = [{"file": f"segment_{i:03d}.ts", "durationSeconds": 2.0} for i in range(6)]+ (root / "media.json").write_text(json.dumps({+ "video": {"codecString": "avc1.42C01E", "segments": rows},+ "audio": {"codecString": "mp4a.40.2", "segments": rows},+ }), encoding="utf-8")+ state = FixtureState(root, "missing-primary", 0.1, 20.0, 6,+ rendition_profile="video-subtitles")+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server.fixture_state = state+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ base = f"http://127.0.0.1:{server.server_port}"+ master = urllib.request.urlopen(base + "/master.m3u8", timeout=2).read().decode()+ subtitle = urllib.request.urlopen(base + "/subtitle/index.m3u8", timeout=2).read().decode()+ video = urllib.request.urlopen(base + "/video/index.m3u8", timeout=2).read().decode()+ vtt = urllib.request.urlopen(base + "/subtitle/segment/5.vtt", timeout=2).read().decode()+ self.assertIn("TYPE=SUBTITLES", master)+ self.assertIn('SUBTITLES="subs"', master)+ self.assertNotIn("TYPE=AUDIO", master)+ self.assertIn("/subtitle/segment/", subtitle)+ self.assertNotIn("#EXT-X-DISCONTINUITY-SEQUENCE:", subtitle)+ self.assertNotIn("#EXT-X-DISCONTINUITY-SEQUENCE:", video)+ self.assertIn("X-TIMESTAMP-MAP=LOCAL:00:00:00.000,MPEGTS:1026000", vtt)+ self.assertIn("Fixture subtitle 5", vtt)+ finally:+ server.shutdown()+ server.server_close()+ thread.join(1)++ def test_subtitle_discontinuity_sequence_offset_is_rendition_scoped(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = pathlib.Path(temporary)+ for role in ("video", "audio"):+ (root / role).mkdir()+ for index in range(6):+ (root / role / f"segment_{index:03d}.ts").write_bytes(_test_avc_ts())+ rows = [{"file": f"segment_{i:03d}.ts", "durationSeconds": 2.0} for i in range(6)]+ (root / "media.json").write_text(json.dumps({+ "video": {"codecString": "avc1.42C01E", "segments": rows},+ "audio": {"codecString": "mp4a.40.2", "segments": rows},+ }), encoding="utf-8")+ state = FixtureState(root, "off", 0.1, 20.0, 6,+ rendition_profile="video-subtitles",+ subtitle_discontinuity_sequence_offset=1)+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server.fixture_state = state+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ base = f"http://127.0.0.1:{server.server_port}"+ subtitle = urllib.request.urlopen(base + "/subtitle/index.m3u8", timeout=2).read().decode()+ video = urllib.request.urlopen(base + "/video/index.m3u8", timeout=2).read().decode()+ status = json.loads(urllib.request.urlopen(base + "/status", timeout=2).read())+ events = json.loads(urllib.request.urlopen(base + "/events", timeout=2).read())+ self.assertIn("#EXT-X-DISCONTINUITY-SEQUENCE:1", subtitle)+ self.assertNotIn("#EXT-X-DISCONTINUITY-SEQUENCE:", video)+ self.assertEqual(1, status["subtitleDiscontinuitySequenceOffset"])+ self.assertEqual(1, events["settings"]["subtitleDiscontinuitySequenceOffset"])+ finally:+ server.shutdown()+ server.server_close()+ thread.join(1)++ def test_missing_primary_keeps_chunked_stream_without_video_pes(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = pathlib.Path(temporary)+ for role in ("video", "audio"):+ (root / role).mkdir()+ for index in range(6):+ (root / role / f"segment_{index:03d}.ts").write_bytes(_test_avc_ts())+ rows = [{"file": f"segment_{i:03d}.ts", "durationSeconds": 2.0} for i in range(6)]+ (root / "media.json").write_text(json.dumps({"video": {"codecString": "avc1.42C01E", "segments": rows},+ "audio": {"codecString": "mp4a.40.2", "segments": rows}}), encoding="utf-8")+ state = FixtureState(root, "missing-primary", 0.1, 40.0, 6)+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server.fixture_state = state+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ response = None+ try:+ response = urllib.request.urlopen(+ f"http://127.0.0.1:{server.server_port}/video/segment/5.ts", timeout=2)+ self.assertEqual(200, response.status)+ prefix_size = len(build_prefix_and_suffix(_test_avc_ts())[0])+ prefix = response.read(prefix_size)+ self.assertEqual(prefix_size, len(prefix))+ filler = response.read(5 * PACKET_SIZE)+ self.assertTrue(filler)+ self.assertTrue(all(((packet[1] & 0x1F) << 8 | packet[2]) == 0x1FFF+ for packet in ts_packets(filler[:len(filler) // PACKET_SIZE * PACKET_SIZE])))+ self.assertTrue(any(row["event"] == "primary-headers-and-psi-sent" and+ row.get("bodyMode") == "indefinite-chunked" for row in state.events))+ finally:+ if response is not None:+ response.close()+ server.shutdown()+ server.server_close()+ thread.join(1)++ def test_missing_primary_retries_remain_invalid_but_later_sequence_is_playable(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = pathlib.Path(temporary)+ for role in ("video", "audio"):+ (root / role).mkdir()+ for index in range(6):+ (root / role / f"segment_{index:03d}.ts").write_bytes(_test_avc_ts())+ rows = [{"file": f"segment_{i:03d}.ts", "durationSeconds": 2.0} for i in range(6)]+ (root / "media.json").write_text(json.dumps({+ "video": {"codecString": "avc1.42C01E", "segments": rows},+ "audio": {"codecString": "mp4a.40.2", "segments": rows},+ }), encoding="utf-8")+ state = FixtureState(root, "missing-primary", 0.1, 40.0, 6)+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server.fixture_state = state+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ responses = []+ try:+ base = f"http://127.0.0.1:{server.server_port}/video/segment"+ prefix_size = len(build_prefix_and_suffix(_test_avc_ts())[0])+ for _ in range(2):+ response = urllib.request.urlopen(f"{base}/5.ts", timeout=2)+ responses.append(response)+ self.assertEqual(200, response.status)+ self.assertEqual(prefix_size, len(response.read(prefix_size)))+ filler = response.read(5 * PACKET_SIZE)+ self.assertTrue(filler)+ complete_packets = len(filler) // PACKET_SIZE+ self.assertGreater(complete_packets, 0)+ self.assertTrue(all(+ ((packet[1] & 0x1F) << 8 | packet[2]) == 0x1FFF+ for packet in ts_packets(filler[:complete_packets * PACKET_SIZE])+ ))+ response.close()+ responses.remove(response)++ next_sequence = urllib.request.urlopen(f"{base}/6.ts", timeout=2)+ responses.append(next_sequence)+ playable = next_sequence.read()+ self.assertEqual(_test_avc_ts(), playable)+ next_sequence.close()+ responses.remove(next_sequence)++ events = state.events+ self.assertEqual(1, sum(+ row["event"] == "primary-delay-target-selected" and row["sequence"] == 5+ for row in events+ ))+ self.assertEqual(2, sum(+ row["event"] == "primary-headers-and-psi-sent" and row["sequence"] == 5+ for row in events+ ))+ self.assertTrue(any(+ row["event"] == "stream-close" and row["sequence"] == 6 and+ row.get("closeReason") == "body-complete"+ for row in events+ ))+ finally:+ for response in responses:+ response.close()+ server.shutdown()+ server.server_close()+ thread.join(1)++ def test_missing_primary_all_keeps_every_video_sequence_invalid_and_audio_valid(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = pathlib.Path(temporary)+ for role in ("video", "audio"):+ (root / role).mkdir()+ for index in range(6):+ (root / role / f"segment_{index:03d}.ts").write_bytes(_test_avc_ts())+ rows = [{"file": f"segment_{i:03d}.ts", "durationSeconds": 2.0} for i in range(6)]+ (root / "media.json").write_text(json.dumps({+ "video": {"codecString": "avc1.42C01E", "segments": rows},+ "audio": {"codecString": "mp4a.40.2", "segments": rows},+ }), encoding="utf-8")+ state = FixtureState(root, "missing-primary-all", 0.1, 40.0, 6)+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ server.fixture_state = state+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ responses = []+ try:+ base = f"http://127.0.0.1:{server.server_port}"+ prefix_size = len(build_prefix_and_suffix(_test_avc_ts())[0])+ for sequence in (5, 6):+ response = urllib.request.urlopen(+ f"{base}/video/segment/{sequence}.ts", timeout=2)+ responses.append(response)+ self.assertEqual(200, response.status)+ self.assertEqual(prefix_size, len(response.read(prefix_size)))+ filler = response.read(5 * PACKET_SIZE)+ packet_bytes = len(filler) // PACKET_SIZE * PACKET_SIZE+ self.assertGreater(packet_bytes, 0)+ self.assertTrue(all(+ ((packet[1] & 0x1F) << 8 | packet[2]) == 0x1FFF+ for packet in ts_packets(filler[:packet_bytes])+ ))+ response.close()+ responses.remove(response)++ audio = urllib.request.urlopen(f"{base}/audio/segment/6.ts", timeout=2)+ responses.append(audio)+ self.assertEqual(_test_avc_ts(), audio.read())+ audio.close()+ responses.remove(audio)+ before_reset_events = state.events+ self.assertTrue(any(+ row["event"] == "stream-close" and row["role"] == "audio" and+ row["sequence"] == 6 and row.get("closeReason") == "body-complete"+ for row in before_reset_events+ ))++ # Reset re-anchors the live window, but must not change the+ # selected failure mode or make a later video sequence valid.+ reset_status = state.reset()+ self.assertEqual("missing-primary-all", reset_status["mode"])+ later = urllib.request.urlopen(f"{base}/video/segment/7.ts", timeout=2)+ responses.append(later)+ self.assertEqual(200, later.status)+ self.assertEqual(prefix_size, len(later.read(prefix_size)))+ filler = later.read(5 * PACKET_SIZE)+ self.assertGreater(len(filler) // PACKET_SIZE, 0)+ later.close()+ responses.remove(later)++ events = state.events+ self.assertEqual(1, sum(+ row["event"] == "primary-delay-target-selected" for row in events+ ))+ self.assertTrue(all(+ row.get("bodyMode") == "indefinite-chunked"+ for row in events if row["event"] == "primary-headers-and-psi-sent"+ ), events)+ finally:+ for response in responses:+ response.close()+ server.shutdown()+ server.server_close()+ thread.join(1)+++def math_floor(value: float) -> int:+ return int(value // 1)+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/v5_dynamic_live_fixture_server.py b/tools/v5_dynamic_live_fixture_server.pyindex 4f416d13..9fc0a7ad 100644--- a/tools/v5_dynamic_live_fixture_server.py+++ b/tools/v5_dynamic_live_fixture_server.py@@ -13,9 +13,12 @@ from __future__ import annotationsimport argparseimport json+import mathimport pathlibimport threadingimport time+from collections import defaultdict+from collections.abc import Callableimport urllib.parsefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer@@ -28,6 +31,172 @@ MEDIA_ASSET_COUNT = 300# fixture reuses those finite segments modulo their count so a two-minute,# two-channel validation never presents a stuck playlist at an artificial cap.MAX_SEQUENCE = 10_000+SEGMENT_CHUNK_BYTES = 64 * 1024+REFUSAL_MODES = {+ "off",+ "segment-404-once",+ "segment-403-rotate",+ "segment-403-permanent-after-start",+ "playlist-403-after-start",+}+REFUSAL_STATUS_CODES = {403, 404, 410}+++def segment_delay_seconds(elapsed: float, period: float, duration: float, start: float) -> float:+ """Repeatable delivery gaps; default zero leaves the healthy fixture unchanged."""+ if period <= 0 or duration <= 0 or elapsed < start:+ return 0.0+ phase = (elapsed - start) % period+ return max(0.0, duration - phase)+++def validated_hold_back_seconds(value: float | None) -> float | None:+ """Return a playlist hold-back that meets HLS's 3x target duration floor."""+ if value is None:+ return None+ if not math.isfinite(value):+ raise ValueError("hold-back must be finite")+ minimum = 3 * SEGMENT_SECONDS+ if value < minimum:+ raise ValueError(f"hold-back must be at least {minimum:g} seconds")+ return value+++def paced_chunk_schedule(payload_bytes: int, cap_bits_per_second: int | None,+ chunk_bytes: int = SEGMENT_CHUNK_BYTES) -> list[tuple[int, int, float]]:+ """Chunk offsets/sizes and elapsed deadlines for capped delivery.++ The first bounded chunk is due immediately. Each following deadline is+ based on total bytes sent, so scheduler delays do not accumulate as drift.+ """+ if payload_bytes < 0 or chunk_bytes <= 0:+ raise ValueError("payload size must be nonnegative and chunk size positive")+ if cap_bits_per_second is None:+ return [(offset, min(chunk_bytes, payload_bytes - offset), 0.0)+ for offset in range(0, payload_bytes, chunk_bytes)]+ if cap_bits_per_second <= 0:+ raise ValueError("delivery cap must be positive")+ chunks = []+ for offset in range(0, payload_bytes, chunk_bytes):+ size = min(chunk_bytes, payload_bytes - offset)+ deadline = 0.0 if offset == 0 else (offset + size) * 8 / cap_bits_per_second+ chunks.append((offset, size, deadline))+ return chunks+++class RefusalInjector:+ """Deterministic role-scoped HTTP refusals for local HLS playback probes."""++ def __init__(self, mode: str = "off", after_seconds: float = 20.0,+ period_seconds: float = 0.0, status_code: int | None = None) -> None:+ if mode not in REFUSAL_MODES:+ raise ValueError(f"unsupported refusal mode: {mode}")+ if not math.isfinite(after_seconds) or after_seconds < 0:+ raise ValueError("refusal start time must be finite and nonnegative")+ if not math.isfinite(period_seconds) or period_seconds < 0:+ raise ValueError("refusal period must be finite and nonnegative")+ if period_seconds and mode != "segment-404-once":+ raise ValueError("periodic refusals are supported only for segment-404-once")+ if status_code is not None and status_code not in REFUSAL_STATUS_CODES:+ raise ValueError("refusal status code must be one of 403, 404, or 410")+ if mode == "off" and status_code is not None:+ raise ValueError("status code cannot be set when refusal mode is off")+ self.mode = mode+ self.after_seconds = after_seconds+ self.period_seconds = period_seconds+ self.status_code = status_code+ self._lock = threading.Lock()+ self._attempts: dict[tuple[str, str, int, int], int] = defaultdict(int)+ self._failed_once: set[str] = set()+ self._failed_periods: set[tuple[str, int]] = set()+ self._periodically_refused_uris: set[tuple[str, int]] = set()+ self._token_generations: dict[tuple[str, int], int] = defaultdict(int)+ self._selected_sequences: dict[str, int] = {}++ def generation_for(self, channel: str, sequence_number: int) -> int:+ with self._lock:+ return self._token_generations[(channel, sequence_number)]++ def decide(self, role: str, channel: str, sequence_number: int,+ token_generation: int | None, elapsed_seconds: float) -> dict[str, int | str | None | bool]:+ """Return HTTP outcome and URI-attempt count without doing any I/O or sleeping."""+ generation = 0 if token_generation is None else token_generation+ key = (role, channel, sequence_number, generation)+ with self._lock:+ self._attempts[key] += 1+ attempts = self._attempts[key]+ status_code = 200+ refused = False+ selected_sequence = self._selected_sequences.get(channel)+ current_generation = self._token_generations[(channel, sequence_number)]++ if self.mode == "segment-404-once" and role == "media-segment" and \+ elapsed_seconds >= self.after_seconds:+ if self.period_seconds:+ period_index = int((elapsed_seconds - self.after_seconds) // self.period_seconds)+ period_key = (channel, period_index)+ uri_key = (channel, sequence_number)+ if period_key not in self._failed_periods and uri_key not in self._periodically_refused_uris:+ self._failed_periods.add(period_key)+ self._periodically_refused_uris.add(uri_key)+ refused = True+ else:+ if channel not in self._failed_once:+ self._failed_once.add(channel)+ refused = True+ if refused:+ status_code = self.status_code or 404++ elif self.mode == "segment-403-rotate" and role == "media-segment":+ if selected_sequence is None and elapsed_seconds >= self.after_seconds:+ self._selected_sequences[channel] = sequence_number+ selected_sequence = sequence_number+ current_generation = 1+ self._token_generations[(channel, sequence_number)] = current_generation+ refused = True+ elif generation != current_generation:+ refused = True+ if refused:+ status_code = self.status_code or 403++ elif self.mode == "segment-403-permanent-after-start" and role == "media-segment" and \+ elapsed_seconds >= self.after_seconds:+ refused = True+ status_code = self.status_code or 403++ elif self.mode == "playlist-403-after-start" and role == "playlist" and \+ elapsed_seconds >= self.after_seconds:+ refused = True+ status_code = self.status_code or 403++ return {+ "statusCode": status_code,+ "attempts": attempts,+ "tokenGeneration": generation,+ "currentTokenGeneration": current_generation,+ "refused": refused,+ "selectedSequence": self._selected_sequences.get(channel),+ }++ def reset(self) -> None:+ with self._lock:+ self._attempts.clear()+ self._failed_once.clear()+ self._failed_periods.clear()+ self._periodically_refused_uris.clear()+ self._token_generations.clear()+ self._selected_sequences.clear()++ def snapshot(self) -> dict[str, object]:+ with self._lock:+ generations = [+ {"channel": channel, "sequence": sequence_number, "generation": generation}+ for (channel, sequence_number), generation in sorted(self._token_generations.items())+ ]+ selected = dict(self._selected_sequences)+ return {"selectedSequences": selected, "tokenGenerations": generations}++CHANNELS = {"1001": "V5 Dynamic Live Alpha","1002": "V5 Dynamic Live Beta",@@ -39,6 +208,8 @@ origins: dict[str, float] = {}wall_origins: dict[str, float] = {}jump_offsets: dict[str, int] = {key: 0 for key in CHANNELS}sequence = 0+completed_runs: list[dict] = []+run_number = 1def record(event: str, **values: object) -> None:@@ -47,6 +218,15 @@ def record(event: str, **values: object) -> None:events.append(row)+def archive_current_run() -> None:+ """Move current events to the run archive before resetting its clock."""+ global run_number+ if events:+ completed_runs.append({"run": run_number, "events": list(events)})+ run_number += 1+ events.clear()++def json_reply(handler: BaseHTTPRequestHandler, body: object, status: int = 200) -> None:payload = json.dumps(body).encode("utf-8")handler.send_response(status)@@ -73,20 +253,34 @@ def text_reply(handler: BaseHTTPRequestHandler, body: str, content_type: str) ->pass-def current_sequence(channel: str) -> int:+def empty_reply(handler: BaseHTTPRequestHandler, status_code: int) -> None:+ handler.send_response(status_code)+ handler.send_header("Content-Length", "0")+ handler.send_header("Cache-Control", "no-store")+ handler.end_headers()+++def current_sequence(channel: str, window_size: int = WINDOW_SIZE) -> int:with lock:# Start with a complete six-segment live window; the server has no# future media and therefore never advertises segments ahead of wall# clock time.- origin = origins.setdefault(channel, time.monotonic() - SEGMENT_SECONDS * WINDOW_SIZE)- wall_origins.setdefault(channel, time.time() - SEGMENT_SECONDS * WINDOW_SIZE)+ origin = origins.setdefault(channel, time.monotonic() - SEGMENT_SECONDS * window_size)+ wall_origins.setdefault(channel, time.time() - SEGMENT_SECONDS * window_size)offset = jump_offsets[channel]return max(0, int((time.monotonic() - origin) / SEGMENT_SECONDS) + offset)-def manifest(channel: str, host: str, port: int) -> str:- end = min(MAX_SEQUENCE - 1, current_sequence(channel))- start = max(0, end - WINDOW_SIZE + 1)+def manifest(channel: str, host: str, port: int,+ hold_back_seconds: float | None = None,+ window_size: int = WINDOW_SIZE,+ token_generation_for_segment: Callable[[str, int], int] | None = None) -> str:+ # current_sequence is the next segment's start slot. Only publish segments+ # whose full duration has elapsed; otherwise PDT puts the live edge in the future.+ if window_size < 1:+ raise ValueError("window size must be positive")+ end = min(MAX_SEQUENCE - 1, max(0, current_sequence(channel, window_size) - 1))+ start = max(0, end - window_size + 1)with lock:wall_origin = wall_origins[channel]rows = [@@ -95,15 +289,21 @@ def manifest(channel: str, host: str, port: int) -> str:"#EXT-X-TARGETDURATION:2",f"#EXT-X-MEDIA-SEQUENCE:{start}",]+ if hold_back_seconds is not None:+ rows.append(f"#EXT-X-SERVER-CONTROL:HOLD-BACK={hold_back_seconds:.1f}")for number in range(start, end + 1):program_date_time = time.strftime("%Y-%m-%dT%H:%M:%S",time.gmtime(wall_origin + number * SEGMENT_SECONDS),) + ".%03dZ" % int((wall_origin + number * SEGMENT_SECONDS) % 1 * 1000)+ segment_uri = f"http://{host}:{port}/asset/{channel}/{number:03d}.ts"+ if token_generation_for_segment is not None:+ generation = token_generation_for_segment(channel, number)+ segment_uri += f"?generation={generation}"rows.extend((f"#EXT-X-PROGRAM-DATE-TIME:{program_date_time}","#EXTINF:2.000000,",- f"http://{host}:{port}/asset/{channel}/{number:03d}.ts",+ segment_uri,))return "\n".join(rows) + "\n"@@ -116,6 +316,7 @@ class Handler(BaseHTTPRequestHandler):def do_GET(self) -> None: # noqa: N802 - stdlib handler APIglobal sequence+ public_host = getattr(self.server, "public_host", "10.0.2.2")parsed = urllib.parse.urlsplit(self.path)query = urllib.parse.parse_qs(parsed.query)@@ -126,16 +327,20 @@ class Handler(BaseHTTPRequestHandler):jump_event: tuple[str, int] | None = Nonewith lock:if query.get("reset", ["0"])[0] == "1":- events.clear()+ archive_current_run()origins.clear()wall_origins.clear()jump_offsets.update({key: 0 for key in CHANNELS})+ self.server.stall_origin = time.monotonic()+ self.server.refusal_injector.reset()selected = query.get("channel", list(CHANNELS))[0]if query.get("jump", ["0"])[0] == "1":if selected not in CHANNELS:selected = list(CHANNELS)[0]jump_offsets[selected] += JUMP_SEGMENTS- origin = origins.setdefault(selected, time.monotonic() - SEGMENT_SECONDS * WINDOW_SIZE)+ origin = origins.setdefault(+ selected, time.monotonic() - SEGMENT_SECONDS * self.server.window_size+ )jump_event = (selected, max(0, int((time.monotonic() - origin) / SEGMENT_SECONDS) + jump_offsets[selected]))wall_origins[selected] = time.time() - jump_event[1] * SEGMENT_SECONDSstate = {"origins": dict(origins), "jumpOffsets": dict(jump_offsets)}@@ -146,8 +351,20 @@ class Handler(BaseHTTPRequestHandler):if parsed.path == "/events":with lock:- return json_reply(self, {"events": list(events), "origins": dict(origins),- "jumpOffsets": dict(jump_offsets)})+ response = {"run": run_number, "events": list(events),+ "completedRuns": list(completed_runs),+ "origins": dict(origins),+ "jumpOffsets": dict(jump_offsets)}+ response["fixtureSettings"] = {+ "windowSegments": self.server.window_size,+ "holdBackSeconds": self.server.hold_back_seconds,+ "refusalMode": self.server.refusal_injector.mode,+ "refusalAfterSeconds": self.server.refusal_injector.after_seconds,+ "refusalPeriodSeconds": self.server.refusal_injector.period_seconds,+ "refusalStatusCode": self.server.refusal_injector.status_code,+ }+ response["refusalState"] = self.server.refusal_injector.snapshot()+ return json_reply(self, response)if parsed.path == "/player_api.php":action = query.get("action", [""])[0]@@ -156,7 +373,7 @@ class Handler(BaseHTTPRequestHandler):"user_info": {"username": "v5-fixture", "password": "v5-fixture", "auth": 1,"status": "Active", "max_connections": "5","allowed_output_formats": ["m3u8"]},- "server_info": {"url": "10.0.2.2", "port": str(self.server.server_port),+ "server_info": {"url": public_host, "port": str(self.server.server_port),"server_protocol": "http", "timezone": "UTC","timestamp_now": int(time.time())},}@@ -166,7 +383,7 @@ class Handler(BaseHTTPRequestHandler):body = [{"stream_id": int(channel), "name": name, "category_id": "501","epg_channel_id": f"V5_{channel}", "tv_archive": 0,"container_extension": "m3u8",- "direct_source": f"http://10.0.2.2:{self.server.server_port}/live/v5/v5/{channel}.m3u8"}+ "direct_source": f"http://{public_host}:{self.server.server_port}/live/v5/v5/{channel}.m3u8"}for channel, name in CHANNELS.items()]elif action in ("get_short_epg", "get_simple_data_table"):body = {"epg_listings": []}@@ -183,9 +400,54 @@ class Handler(BaseHTTPRequestHandler):channel = parts[-1].removesuffix(".m3u8")if channel not in CHANNELS:return json_reply(self, {"error": "unknown channel"}, status=404)- record("manifest", channel=channel, sequence=current_sequence(channel))- return text_reply(self, manifest(channel, "10.0.2.2", self.server.server_port),- "application/vnd.apple.mpegurl")+ started = time.monotonic()+ elapsed = started - self.server.stall_origin+ sequence_number = current_sequence(channel, self.server.window_size)+ record("manifest", channel=channel, sequence=sequence_number)+ token_generation_for_segment = None+ if self.server.refusal_injector.mode == "segment-403-rotate":+ token_generation_for_segment = self.server.refusal_injector.generation_for+ body = manifest(channel, public_host, self.server.server_port,+ self.server.hold_back_seconds, self.server.window_size,+ token_generation_for_segment)+ media_sequence_start = next(+ int(line.split(":", 1)[1]) for line in body.splitlines()+ if line.startswith("#EXT-X-MEDIA-SEQUENCE:")+ )+ decision = self.server.refusal_injector.decide(+ "playlist", channel, media_sequence_start, None, elapsed+ )+ advertised_generations = [+ {"sequence": int(line.split("/")[-1].split(".")[0]),+ "generation": int(line.rsplit("=", 1)[1])}+ for line in body.splitlines()+ if "/asset/" in line and "?generation=" in line+ ]+ if decision["statusCode"] != 200:+ empty_reply(self, int(decision["statusCode"]))+ record("http-response", role="playlist", channel=channel,+ sequence=media_sequence_start, tokenGeneration=None,+ statusCode=decision["statusCode"], attempts=decision["attempts"],+ bytes=0, expectedBytes=0, elapsedSeconds=time.monotonic() - started,+ advertisedTokenGenerations=[])+ return+ payload = body.encode("utf-8")+ self.send_response(200)+ self.send_header("Content-Type", "application/vnd.apple.mpegurl")+ self.send_header("Content-Length", str(len(payload)))+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ try:+ self.wfile.write(payload)+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):+ pass+ record("http-response", role="playlist", channel=channel,+ sequence=media_sequence_start, tokenGeneration=None,+ statusCode=200, attempts=decision["attempts"],+ bytes=len(payload), expectedBytes=len(payload),+ elapsedSeconds=time.monotonic() - started,+ advertisedTokenGenerations=advertised_generations)+ returnif len(parts) == 3 and parts[0] == "asset" and parts[1] in CHANNELS:channel, name = parts[1], parts[2]@@ -195,25 +457,92 @@ class Handler(BaseHTTPRequestHandler):number = int(name[:-3])except ValueError:return json_reply(self, {"error": "not found"}, status=404)+ started = time.monotonic()+ elapsed = started - self.server.stall_origin+ try:+ token_generation = int(query.get("generation", ["0"])[0])+ if token_generation < 0:+ raise ValueError+ except ValueError:+ empty_reply(self, 400)+ record("http-response", role="media-segment", channel=channel,+ sequence=number, tokenGeneration=None, statusCode=400,+ attempts=1, bytes=0, expectedBytes=0,+ elapsedSeconds=time.monotonic() - started)+ returnasset_number = number % MEDIA_ASSET_COUNTtarget = self.server.segment_root / f"segment_{asset_number:03d}.ts"if number < 0 or number >= MAX_SEQUENCE or not target.is_file():record("segment-missing", channel=channel, sequence=number)- return json_reply(self, {"error": "not found"}, status=404)+ empty_reply(self, 404)+ decision = self.server.refusal_injector.decide(+ "media-segment", channel, number, token_generation, elapsed+ )+ record("http-response", role="media-segment", channel=channel,+ sequence=number, tokenGeneration=token_generation,+ statusCode=404, attempts=decision["attempts"], bytes=0,+ expectedBytes=0, elapsedSeconds=time.monotonic() - started)+ return+ decision = self.server.refusal_injector.decide(+ "media-segment", channel, number, token_generation, elapsed+ )+ if decision["statusCode"] != 200:+ empty_reply(self, int(decision["statusCode"]))+ record("http-response", role="media-segment", channel=channel,+ sequence=number, tokenGeneration=token_generation,+ statusCode=decision["statusCode"], attempts=decision["attempts"],+ bytes=0, expectedBytes=0, elapsedSeconds=time.monotonic() - started,+ currentTokenGeneration=decision["currentTokenGeneration"],+ selectedSequence=decision["selectedSequence"])+ returnwith lock:sequence += 1request_id = sequence- record("segment", id=request_id, channel=channel, sequence=number)+ record("segment", id=request_id, role="media-segment", channel=channel,+ sequence=number, tokenGeneration=token_generation,+ attempts=decision["attempts"])+ delay_seconds = segment_delay_seconds(+ time.monotonic() - self.server.stall_origin,+ self.server.stall_period, self.server.stall_duration, self.server.stall_start,+ )+ if delay_seconds > 0:+ record("segment-delay", channel=channel, sequence=number, seconds=delay_seconds)+ time.sleep(delay_seconds)payload = target.read_bytes()self.send_response(200)self.send_header("Content-Type", "video/mp2t")self.send_header("Content-Length", str(len(payload)))self.send_header("Cache-Control", "no-store")self.end_headers()+ cap = self.server.segment_rate_cap_bps+ delivery_started = time.monotonic()+ delivered = 0try:- self.wfile.write(payload)- except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):+ for offset, size, deadline_offset in paced_chunk_schedule(len(payload), cap):+ if cap is not None:+ remaining = delivery_started + deadline_offset - time.monotonic()+ if remaining > 0:+ time.sleep(remaining)+ self.wfile.write(payload[offset:offset + size])+ delivered += size+ self.wfile.flush()+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError):+ # Cancellation can happen during a paced wait or a write. The+ # full Content-Length remains correct for successful responses;+ # this event records the partial body when the peer disconnects.pass+ record("segment-delivery", id=request_id, channel=channel, sequence=number,+ role="media-segment", tokenGeneration=token_generation,+ statusCode=200, attempts=decision["attempts"],+ bytes=delivered, expectedBytes=len(payload),+ elapsedSeconds=time.monotonic() - delivery_started,+ rateCapBitsPerSecond=cap)+ record("http-response", role="media-segment", channel=channel,+ sequence=number, tokenGeneration=token_generation,+ statusCode=200, attempts=decision["attempts"], bytes=delivered,+ expectedBytes=len(payload), elapsedSeconds=time.monotonic() - started,+ currentTokenGeneration=decision["currentTokenGeneration"],+ selectedSequence=decision["selectedSequence"])returnreturn json_reply(self, {"error": "not found"}, status=404)@@ -222,12 +551,54 @@ class Handler(BaseHTTPRequestHandler):def main() -> None:parser = argparse.ArgumentParser()parser.add_argument("--port", type=int, default=18785)+ parser.add_argument("--public-host", choices=("10.0.2.2", "127.0.0.1", "localhost"),+ default="10.0.2.2", help="Host advertised in fixture API and segment URLs")parser.add_argument("--segment-root", required=True, type=pathlib.Path)+ parser.add_argument("--segment-stall-period", type=float, default=0)+ parser.add_argument("--segment-stall-duration", type=float, default=0)+ parser.add_argument("--segment-stall-start", type=float, default=20)+ parser.add_argument("--hold-back-seconds", type=float)+ parser.add_argument("--window-segments", type=int, default=WINDOW_SIZE)+ parser.add_argument("--segment-rate-cap-bps", type=int)+ parser.add_argument("--refusal-mode", choices=sorted(REFUSAL_MODES), default="off")+ parser.add_argument("--refusal-after-seconds", type=float, default=20.0)+ parser.add_argument("--refusal-period-seconds", type=float, default=0.0)+ parser.add_argument("--refusal-status-code", type=int, choices=sorted(REFUSAL_STATUS_CODES))args = parser.parse_args()+ if (args.segment_stall_period < 0 or args.segment_stall_duration < 0+ or args.segment_stall_start < 0+ or args.segment_stall_duration > 0 and args.segment_stall_period <= args.segment_stall_duration):+ parser.error("stall period must exceed duration; all stall settings must be nonnegative")+ try:+ hold_back = validated_hold_back_seconds(args.hold_back_seconds)+ except ValueError as exc:+ parser.error(str(exc))+ if args.segment_rate_cap_bps is not None and args.segment_rate_cap_bps <= 0:+ parser.error("segment rate cap must be positive")+ if args.window_segments < 1:+ parser.error("window segment count must be positive")+ try:+ refusal_injector = RefusalInjector(+ mode=args.refusal_mode,+ after_seconds=args.refusal_after_seconds,+ period_seconds=args.refusal_period_seconds,+ status_code=args.refusal_status_code,+ )+ except ValueError as exc:+ parser.error(str(exc))if not all((args.segment_root / f"segment_{number:03d}.ts").is_file() for number in range(MEDIA_ASSET_COUNT)):raise SystemExit(f"expected {MEDIA_ASSET_COUNT} two-second segments in {args.segment_root}")server = ThreadingHTTPServer(("127.0.0.1", args.port), Handler)+ server.public_host = args.public_hostserver.segment_root = args.segment_root.resolve()+ server.stall_period = args.segment_stall_period+ server.stall_duration = args.segment_stall_duration+ server.stall_start = args.segment_stall_start+ server.stall_origin = time.monotonic()+ server.hold_back_seconds = hold_back+ server.window_size = args.window_segments+ server.segment_rate_cap_bps = args.segment_rate_cap_bps+ server.refusal_injector = refusal_injectorprint(f"V5 dynamic-live fixture listening on 0.0.0.0:{args.port}", flush=True)server.serve_forever()