From 6edd29bcecb7eeeda827c67ca1b306b84b1ba099 Mon Sep 17 00:00:00 2001 From: ajisth69 Date: Sat, 5 Dec 2026 20:05:21 +0530 Subject: [PATCH 1/2] feat(playback): adaptive multi-connection accelerator for addon streams --- .../playback/AdaptiveAddonStreamDataSource.kt | 445 ++++++++++++++++++ .../com/lastwave/app/playback/MusicPlayer.kt | 32 +- 2 files changed, 476 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/com/lastwave/app/playback/AdaptiveAddonStreamDataSource.kt diff --git a/app/src/main/java/com/lastwave/app/playback/AdaptiveAddonStreamDataSource.kt b/app/src/main/java/com/lastwave/app/playback/AdaptiveAddonStreamDataSource.kt new file mode 100644 index 000000000..006f1fb7d --- /dev/null +++ b/app/src/main/java/com/lastwave/app/playback/AdaptiveAddonStreamDataSource.kt @@ -0,0 +1,445 @@ +package com.lastwave.app.playback + +import android.net.Uri +import android.os.SystemClock +import androidx.media3.common.C +import androidx.media3.datasource.DataSource +import androidx.media3.datasource.DataSpec +import androidx.media3.datasource.HttpDataSource +import androidx.media3.datasource.TransferListener +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.job +import kotlinx.coroutines.launch +import java.io.IOException +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ConcurrentSkipListMap +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong + +/** + * Adaptive multi-connection reader for addon (lossless/provider) HTTP streams. + * + * The stream is first read through [singleStream] exactly as before. While that + * read runs, throughput is sampled; if it falls below [Config.realtimeBytesPerSec], + * one bounded Range request probes the server. Only when that response carries a + * matching `Content-Range` does the loader fan out to + * [config.minConcurrency]..[config.maxConcurrency] concurrent 256 KB ranges into + * an ordered, bounded window. Many CDNs omit `Accept-Ranges` from a plain GET, + * so the probe — not the header — decides whether parallel reads are safe. + * + * This class is inert for everything except addon streams: non-addon `DataSpec`s + * are delegated byte-for-byte to [singleStream], so YouTube keeps using + * [ChunkedRangeDataSource] and ordinary playback is unchanged. + * + * A 429/503 or a server that ignores `Range` falls back to fewer connections + * and finally to [singleStream] at the last byte delivered. `close()` (ExoPlayer + * calls it on seek, skip and release) cancels every worker and closes every + * connection. + */ +class AdaptiveAddonStreamDataSource( + private val singleStream: DataSource, + private val connectionFactory: DataSource.Factory, + private val isAddonStream: (DataSpec) -> Boolean, + private val config: Config = Config(), +) : DataSource { + + data class Config( + val chunkSize: Long = 256 * 1024L, + val minConcurrency: Int = 16, + val maxConcurrency: Int = 32, + val realtimeBytesPerSec: Long = 250 * 1024L, + val sampleWindowBytes: Long = 256 * 1024L, + ) + + private enum class Mode { PASSTHROUGH, SINGLE, PARALLEL, FAILED } + + private class Chunk(val bytes: ByteArray) { + var offset: Int = 0 + } + + private val lock = Any() + private val readyChunks = ConcurrentSkipListMap() + private val openConnections = ConcurrentHashMap() + + private val nextFetchIndex = AtomicLong(0L) + private val inFlight = AtomicInteger(0) + private val fallingBack = AtomicBoolean(false) + + @Volatile private var mode = Mode.PASSTHROUGH + @Volatile private var closed = false + @Volatile private var activeScope: CoroutineScope? = null + private var dispatcher: Job? = null + @Volatile private var failure: Throwable? = null + + private var originalSpec: DataSpec? = null + @Volatile private var windowBase = 0L + @Volatile private var nextReadyIndex = 0L + @Volatile private var lastFetchIndex = Long.MAX_VALUE + @Volatile private var totalLength = C.LENGTH_UNSET.toLong() + @Volatile private var deliveredPosition = 0L + private var uri: Uri? = null + private var responseHeaders: Map> = emptyMap() + + @Volatile private var concurrency = config.minConcurrency + @Volatile private var rampDone = false + @Volatile private var escalationBlocked = false + @Volatile private var rangeVerified = false + private var sampleBytes = 0L + private var sampleStartMs = 0L + + override fun addTransferListener(transferListener: TransferListener) { + singleStream.addTransferListener(transferListener) + } + + override fun open(dataSpec: DataSpec): Long { + close() + originalSpec = dataSpec + deliveredPosition = dataSpec.position + totalLength = dataSpec.length + nextReadyIndex = 0L + lastFetchIndex = Long.MAX_VALUE + sampleBytes = 0L + sampleStartMs = SystemClock.elapsedRealtime() + failure = null + fallingBack.set(false) + closed = false + concurrency = config.minConcurrency + rampDone = false + escalationBlocked = false + rangeVerified = false + + val length = singleStream.open(dataSpec) + uri = singleStream.uri + responseHeaders = singleStream.responseHeaders + if (length != C.LENGTH_UNSET.toLong()) totalLength = length + + mode = if (isAddonStream(dataSpec)) Mode.SINGLE else Mode.PASSTHROUGH + return length + } + + override fun read(buffer: ByteArray, offset: Int, length: Int): Int { + if (length == 0) return 0 + return when (mode) { + Mode.PASSTHROUGH -> { + val read = singleStream.read(buffer, offset, length) + if (read > 0) deliveredPosition += read + read + } + Mode.SINGLE -> readSingle(buffer, offset, length) + Mode.PARALLEL -> readParallel(buffer, offset, length) + Mode.FAILED -> throw IOException("Addon stream accelerator failed", failure) + } + } + + private fun readSingle(buffer: ByteArray, offset: Int, length: Int): Int { + val read = singleStream.read(buffer, offset, length) + if (read == C.RESULT_END_OF_INPUT) { + totalLength = deliveredPosition + return read + } + if (read <= 0) return read + deliveredPosition += read + sample(read) + return read + } + + /** Samples delivered bytes; escalates once a window proves the stream is too slow. */ + private fun sample(bytes: Int) { + sampleBytes += bytes + val elapsed = SystemClock.elapsedRealtime() - sampleStartMs + val windowMs = maxOf(500L, config.sampleWindowBytes * 1_000L / config.realtimeBytesPerSec) + if (sampleBytes < config.sampleWindowBytes && elapsed < windowMs) return + val rate = if (elapsed > 0) sampleBytes * 1_000L / elapsed else Long.MAX_VALUE + sampleBytes = 0L + sampleStartMs = SystemClock.elapsedRealtime() + if (rate < config.realtimeBytesPerSec) escalate() + } + + private fun escalate() { + if (mode != Mode.SINGLE || closed || escalationBlocked) return + val scope = CoroutineScope(SupervisorJob() + kotlinx.coroutines.Dispatchers.IO) + activeScope = scope + windowBase = deliveredPosition + nextFetchIndex.set(0L) + inFlight.set(0) + lastFetchIndex = if (totalLength != C.LENGTH_UNSET.toLong()) { + val remaining = totalLength - windowBase + if (remaining <= 0L) -1L else (remaining - 1L) / config.chunkSize + } else { + Long.MAX_VALUE + } + nextReadyIndex = 0L + rangeVerified = false + sampleBytes = 0L + sampleStartMs = SystemClock.elapsedRealtime() + mode = Mode.PARALLEL + runCatching { singleStream.close() } + dispatcher = scope.launch { dispatchLoop() } + android.util.Log.i( + TAG, + "[ADAPTIVE] slow addon stream (${config.realtimeBytesPerSec}B/s threshold), " + + "probing one ${config.chunkSize / 1024}KB range before ramping to $concurrency", + ) + } + + private suspend fun dispatchLoop() { + val scope = activeScope ?: return + while (scope.isActive && !closed) { + // Never fan out until the first ranged response proves the server + // honours Range; a 200 full-body response would waste N full files. + if (!rangeVerified && nextFetchIndex.get() > 0L) { + delay(DISPATCH_IDLE_MS) + continue + } + val window = concurrency + WINDOW_SLACK + if (inFlight.get() + readyChunks.size < window && nextFetchIndex.get() <= lastFetchIndex) { + val index = nextFetchIndex.getAndIncrement() + inFlight.incrementAndGet() + scope.launch { fetchChunk(index) } + } else { + delay(DISPATCH_IDLE_MS) + } + } + } + + private suspend fun fetchChunk(index: Long) { + val scope = activeScope ?: return + val spec = originalSpec ?: return + var connection: DataSource? = null + try { + val start = windowBase + index * config.chunkSize + if (totalLength != C.LENGTH_UNSET.toLong() && start >= totalLength) { + synchronized(lock) { lastFetchIndex = index - 1L; lock.notifyAll() } + return + } + val chunkSpec = spec.buildUpon() + .setPosition(start) + .setLength(config.chunkSize) + .setHttpRequestHeaders(spec.httpRequestHeaders.filterKeys { !it.equals("Range", true) }) + .build() + val source = connectionFactory.createDataSource() + connection = source + openConnections[index] = source + currentCoroutineContext().job.invokeOnCancellation { runCatching { source.close() } } + if (!scope.isActive || closed) return + source.open(chunkSpec) + if (index == 0L) { + if (!honorsRange(source.responseHeaders, start)) { + onRangeUnsupported() + return + } + rangeVerified = true + android.util.Log.i( + TAG, + "[ADAPTIVE] range probe ok, ramping to $concurrency x ${config.chunkSize / 1024}KB ranges", + ) + } + val bytes = ByteArray(config.chunkSize.toInt()) + var written = 0 + while (scope.isActive && !closed && written < bytes.size) { + val read = source.read(bytes, written, bytes.size - written) + if (read == C.RESULT_END_OF_INPUT || read <= 0) break + written += read + } + if (!scope.isActive || closed) return + val data = if (written == 0) EMPTY_BYTES else bytes.copyOf(written) + synchronized(lock) { + if (data.size < config.chunkSize.toInt()) lastFetchIndex = index + readyChunks[index] = Chunk(data) + lock.notifyAll() + } + } catch (error: HttpDataSource.InvalidResponseCodeException) { + when (error.responseCode) { + 416 -> { + // A 416 is a valid ranged answer: the stream simply ended. + if (index == 0L) rangeVerified = true + synchronized(lock) { lastFetchIndex = index - 1L; lock.notifyAll() } + } + 429, 503 -> onBackpressure() + else -> fail(error) + } + } catch (error: CancellationException) { + // Our own close() cancelled the workers; nothing to report. + if (!closed && scope.isActive) throw error + } catch (error: IOException) { + if (!closed && scope.isActive) fail(error) + } catch (error: Exception) { + if (!closed && scope.isActive) fail(error) + } finally { + runCatching { connection?.close() } + openConnections.remove(index) + inFlight.decrementAndGet() + synchronized(lock) { lock.notifyAll() } + // The probe died before it could establish range support; don't + // leave the dispatcher waiting forever for a verification flag. + if (index == 0L && !rangeVerified && !closed && scope.isActive && failure == null) { + onRangeUnsupported() + } + } + } + + private fun readParallel(buffer: ByteArray, offset: Int, length: Int): Int { + while (true) { + failure?.let { throw IOException("Addon stream accelerator failed", it) } + if (closed) throw IOException("Addon stream accelerator closed") + // A backpressure/range fallback switched us back to the single + // stream while the reader was parked; keep delivering from there. + if (mode == Mode.SINGLE) return readSingle(buffer, offset, length) + if (mode != Mode.PARALLEL) throw IOException("Addon stream accelerator stopped") + synchronized(lock) { + val chunk = readyChunks[nextReadyIndex] + if (chunk != null) { + val available = chunk.bytes.size - chunk.offset + if (available > 0) { + val count = minOf(length, available) + System.arraycopy(chunk.bytes, chunk.offset, buffer, offset, count) + chunk.offset += count + deliveredPosition += count + if (chunk.offset >= chunk.bytes.size) { + readyChunks.remove(nextReadyIndex) + nextReadyIndex++ + } + sampleParallel(count) + return count + } + // Zero-length chunk: the worker marked the stream's end here. + readyChunks.remove(nextReadyIndex) + nextReadyIndex++ + lock.notifyAll() + } else if (nextReadyIndex > lastFetchIndex) { + return C.RESULT_END_OF_INPUT + } else { + try { + lock.wait(WAIT_MS) + } catch (error: InterruptedException) { + Thread.currentThread().interrupt() + throw IOException(error) + } + } + } + } + } + + private fun sampleParallel(bytes: Int) { + sampleBytes += bytes + val elapsed = SystemClock.elapsedRealtime() - sampleStartMs + val windowMs = maxOf(500L, config.sampleWindowBytes * 1_000L / config.realtimeBytesPerSec) + if (sampleBytes < config.sampleWindowBytes && elapsed < windowMs) return + val rate = if (elapsed > 0) sampleBytes * 1_000L / elapsed else Long.MAX_VALUE + sampleBytes = 0L + sampleStartMs = SystemClock.elapsedRealtime() + if (rate < config.realtimeBytesPerSec && !rampDone && concurrency < config.maxConcurrency) { + concurrency = minOf(config.maxConcurrency, concurrency * 2) + rampDone = true + android.util.Log.i(TAG, "[ADAPTIVE] still slow, raised concurrency to $concurrency") + } + } + + private fun onBackpressure() { + if (concurrency > 1) { + concurrency = maxOf(1, concurrency / 2) + android.util.Log.i(TAG, "[ADAPTIVE] server backpressure, concurrency now $concurrency") + return + } + fallbackToSingle("server still refusing 429/503") + } + + /** A ranged request returned a plain 200 body: stop before fanning out. */ + private fun onRangeUnsupported() { + fallbackToSingle("server ignored Range header") + } + + private fun fallbackToSingle(reason: String) { + if (!fallingBack.compareAndSet(false, true)) return + // A server that either ignored Range or pushed back must not be + // probed again for the rest of this open. + escalationBlocked = true + rampDone = true + android.util.Log.i(TAG, "[ADAPTIVE] $reason, falling back to single stream") + activeScope?.cancel() + activeScope = null + readyChunks.clear() + openConnections.values.forEach { runCatching { it.close() } } + openConnections.clear() + val spec = originalSpec + if (spec == null) { + mode = Mode.FAILED + return + } + val known = if (totalLength != C.LENGTH_UNSET.toLong()) totalLength - deliveredPosition else 0L + val remaining = if (known > 0L) known else C.LENGTH_UNSET.toLong() + val resumed = spec.buildUpon() + .setPosition(deliveredPosition) + .setLength(remaining) + .build() + try { + singleStream.open(resumed) + mode = Mode.SINGLE + sampleBytes = 0L + sampleStartMs = SystemClock.elapsedRealtime() + } catch (error: Exception) { + fail(error) + } + synchronized(lock) { lock.notifyAll() } + } + + private fun fail(error: Throwable) { + if (closed) return + if (failure == null) failure = error + activeScope?.cancel() + activeScope = null + mode = Mode.FAILED + synchronized(lock) { lock.notifyAll() } + } + + override fun getUri(): Uri? = if (mode == Mode.PARALLEL) uri else singleStream.uri + + override fun getResponseHeaders(): Map> = + if (mode == Mode.PARALLEL) responseHeaders else singleStream.responseHeaders + + override fun close() { + closed = true + activeScope?.cancel() + activeScope = null + dispatcher?.cancel() + dispatcher = null + synchronized(lock) { lock.notifyAll() } + openConnections.values.forEach { runCatching { it.close() } } + openConnections.clear() + readyChunks.clear() + runCatching { singleStream.close() } + originalSpec = null + mode = Mode.PASSTHROUGH + failure = null + fallingBack.set(false) + rangeVerified = false + inFlight.set(0) + nextFetchIndex.set(0L) + } + + companion object { + private const val TAG = "AdaptiveAddonStream" + private const val WINDOW_SLACK = 4 + private const val DISPATCH_IDLE_MS = 10L + private const val WAIT_MS = 100L + private val EMPTY_BYTES = ByteArray(0) + private val CONTENT_RANGE_START = Regex("""bytes\s+(\d+)\s*-""", RegexOption.IGNORE_CASE) + + /** A bounded Range request must answer `Content-Range: bytes -...`. */ + private fun honorsRange(headers: Map>, start: Long): Boolean { + val value = headers.entries + .firstOrNull { it.key.equals("Content-Range", ignoreCase = true) } + ?.value?.firstOrNull() + ?: return false + return CONTENT_RANGE_START.find(value)?.groupValues?.get(1)?.toLongOrNull() == start + } + } +} diff --git a/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt b/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt index f5a18cf82..02c7b3ad2 100644 --- a/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt +++ b/app/src/main/java/com/lastwave/app/playback/MusicPlayer.kt @@ -842,7 +842,17 @@ class MusicPlayer @Inject constructor( internal val cacheDataSourceFactory: CacheDataSource.Factory by lazy { val defaultDataSourceFactory = androidx.media3.datasource.DefaultDataSource.Factory(appContext, httpUpstreamFactory) val chunkedUpstreamFactory = androidx.media3.datasource.DataSource.Factory { - ChunkedRangeDataSource(defaultDataSourceFactory.createDataSource(), refresher = ::refreshRejectedYouTubeUrl) + // YouTube keeps the exact chunked/refreshing behaviour it has today. + // The adaptive wrapper is inert for every other stream; it only + // activates for addon/lossless URLs that advertise byte ranges. + AdaptiveAddonStreamDataSource( + singleStream = ChunkedRangeDataSource( + defaultDataSourceFactory.createDataSource(), + refresher = ::refreshRejectedYouTubeUrl, + ), + connectionFactory = defaultDataSourceFactory, + isAddonStream = ::isAddonAcceleratedStream, + ) } CacheDataSource.Factory() .setCache(mediaCache) @@ -850,6 +860,26 @@ class MusicPlayer @Inject constructor( .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR) } + /** + * Only addon/provider streams may use the parallel accelerator. Their + * `DataSpec` key is always `lossless:...`, which is set on the MediaItem + * before the loader opens it — checking the key here avoids depending on + * the asynchronous [preparedStreams] registration having landed. YouTube, + * local files, casts and DASH segments keep the existing data-source path. + */ + private fun isAddonAcceleratedStream(spec: DataSpec): Boolean { + if (spec.uri.scheme != "http" && spec.uri.scheme != "https") return false + val key = spec.key + if (key == null) { + val stream = preparedStreams.values.firstOrNull { it.url == spec.uri.toString() } ?: return false + return stream.youtubeCandidate == null && stream.cacheKey.startsWith("lossless:") + } + if (!key.startsWith("lossless:")) return false + // A DASH manifest or segment is not one rangeable file. + val segment = spec.uri.lastPathSegment.orEmpty() + return !segment.endsWith(".mpd", ignoreCase = true) && !segment.endsWith(".m4s", ignoreCase = true) + } + /** Refused googlevideo URL -> the same-file replacement already minted for it. */ private val refreshedYouTubeUrls = ConcurrentHashMap() From cfd491394a2c7cb0319bec5076227fef5a37bd27 Mon Sep 17 00:00:00 2001 From: ajisth69 Date: Sat, 5 Dec 2026 20:15:27 +0530 Subject: [PATCH 2/2] fix(playback): use ReentrantLock condition for accelerator buffer signalling --- .../playback/AdaptiveAddonStreamDataSource.kt | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/com/lastwave/app/playback/AdaptiveAddonStreamDataSource.kt b/app/src/main/java/com/lastwave/app/playback/AdaptiveAddonStreamDataSource.kt index 006f1fb7d..55f32c7c9 100644 --- a/app/src/main/java/com/lastwave/app/playback/AdaptiveAddonStreamDataSource.kt +++ b/app/src/main/java/com/lastwave/app/playback/AdaptiveAddonStreamDataSource.kt @@ -12,14 +12,15 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel -import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.isActive -import kotlinx.coroutines.job import kotlinx.coroutines.launch import java.io.IOException import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentSkipListMap +import java.util.concurrent.TimeUnit +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong @@ -65,7 +66,8 @@ class AdaptiveAddonStreamDataSource( var offset: Int = 0 } - private val lock = Any() + private val lock = ReentrantLock() + private val signal = lock.newCondition() private val readyChunks = ConcurrentSkipListMap() private val openConnections = ConcurrentHashMap() @@ -217,7 +219,7 @@ class AdaptiveAddonStreamDataSource( try { val start = windowBase + index * config.chunkSize if (totalLength != C.LENGTH_UNSET.toLong() && start >= totalLength) { - synchronized(lock) { lastFetchIndex = index - 1L; lock.notifyAll() } + lock.withLock { lastFetchIndex = index - 1L; signal.signalAll() } return } val chunkSpec = spec.buildUpon() @@ -228,7 +230,6 @@ class AdaptiveAddonStreamDataSource( val source = connectionFactory.createDataSource() connection = source openConnections[index] = source - currentCoroutineContext().job.invokeOnCancellation { runCatching { source.close() } } if (!scope.isActive || closed) return source.open(chunkSpec) if (index == 0L) { @@ -251,17 +252,17 @@ class AdaptiveAddonStreamDataSource( } if (!scope.isActive || closed) return val data = if (written == 0) EMPTY_BYTES else bytes.copyOf(written) - synchronized(lock) { + lock.withLock { if (data.size < config.chunkSize.toInt()) lastFetchIndex = index readyChunks[index] = Chunk(data) - lock.notifyAll() + signal.signalAll() } } catch (error: HttpDataSource.InvalidResponseCodeException) { when (error.responseCode) { 416 -> { // A 416 is a valid ranged answer: the stream simply ended. if (index == 0L) rangeVerified = true - synchronized(lock) { lastFetchIndex = index - 1L; lock.notifyAll() } + lock.withLock { lastFetchIndex = index - 1L; signal.signalAll() } } 429, 503 -> onBackpressure() else -> fail(error) @@ -277,7 +278,7 @@ class AdaptiveAddonStreamDataSource( runCatching { connection?.close() } openConnections.remove(index) inFlight.decrementAndGet() - synchronized(lock) { lock.notifyAll() } + lock.withLock { signal.signalAll() } // The probe died before it could establish range support; don't // leave the dispatcher waiting forever for a verification flag. if (index == 0L && !rangeVerified && !closed && scope.isActive && failure == null) { @@ -294,7 +295,7 @@ class AdaptiveAddonStreamDataSource( // stream while the reader was parked; keep delivering from there. if (mode == Mode.SINGLE) return readSingle(buffer, offset, length) if (mode != Mode.PARALLEL) throw IOException("Addon stream accelerator stopped") - synchronized(lock) { + lock.withLock { val chunk = readyChunks[nextReadyIndex] if (chunk != null) { val available = chunk.bytes.size - chunk.offset @@ -313,12 +314,12 @@ class AdaptiveAddonStreamDataSource( // Zero-length chunk: the worker marked the stream's end here. readyChunks.remove(nextReadyIndex) nextReadyIndex++ - lock.notifyAll() + signal.signalAll() } else if (nextReadyIndex > lastFetchIndex) { return C.RESULT_END_OF_INPUT } else { try { - lock.wait(WAIT_MS) + signal.await(WAIT_MS, TimeUnit.MILLISECONDS) } catch (error: InterruptedException) { Thread.currentThread().interrupt() throw IOException(error) @@ -388,7 +389,7 @@ class AdaptiveAddonStreamDataSource( } catch (error: Exception) { fail(error) } - synchronized(lock) { lock.notifyAll() } + lock.withLock { signal.signalAll() } } private fun fail(error: Throwable) { @@ -397,7 +398,7 @@ class AdaptiveAddonStreamDataSource( activeScope?.cancel() activeScope = null mode = Mode.FAILED - synchronized(lock) { lock.notifyAll() } + lock.withLock { signal.signalAll() } } override fun getUri(): Uri? = if (mode == Mode.PARALLEL) uri else singleStream.uri @@ -411,7 +412,7 @@ class AdaptiveAddonStreamDataSource( activeScope = null dispatcher?.cancel() dispatcher = null - synchronized(lock) { lock.notifyAll() } + lock.withLock { signal.signalAll() } openConnections.values.forEach { runCatching { it.close() } } openConnections.clear() readyChunks.clear()