diff --git a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeFrameQueue.kt b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeFrameQueue.kt new file mode 100644 index 0000000..049d13a --- /dev/null +++ b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeFrameQueue.kt @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: 2026 OpenXPlay.org +// SPDX-License-Identifier: AGPL-3.0-only +// Created by riko chen on 2026-11-29 + +package org.openxplay.stream.carlife + +import java.util.concurrent.TimeUnit +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock +import org.openxplay.stream.core.VideoFormat +import org.openxplay.stream.core.VideoFrame + +internal class PendingFrame(val frame: VideoFrame, val format: VideoFormat, val epoch: Long) + +/** + * Video waiting for the negotiated send cadence, bounded by media span, bytes and frame count. + * A short frame limit reset the queue on every source burst and fed a loop of keyframe requests + * and large IDR writes; the span bound absorbs bursts while still capping latency. + */ +internal class CarlifeFrameQueue( + private val maxBytes: Long = 4L * 1024 * 1024, + private val maxSpanUs: Long = 600_000, + private val maxFrames: Int = 120, +) { + enum class Limit { FRAMES, BYTES, SPAN } + class Overflow(val limit: Limit, val bytes: Long, val spanUs: Long) + /** [recovery]: the source should send a keyframe. [overflow]: the queue was reset first. */ + class Offer(val recovery: Boolean, val overflow: Overflow?) + + private val lock = ReentrantLock() + private val ready = lock.newCondition() + private val frames = ArrayDeque() + private var bytes = 0L + private var awaitingKeyframe = true + private var dropped = 0L + private var overflows = 0L + + init { require(maxBytes > 0 && maxSpanUs > 0 && maxFrames > 0) } + + fun offer(pending: PendingFrame): Offer = lock.withLock { + val frame = pending.frame + val size = frame.data.size.toLong() + if (awaitingKeyframe && !frame.keyFrame && size <= maxBytes) { + dropped++ + return Offer(true, null) + } + val queuedBytes = bytes + size + val queuedSpan = spanTo(frame.ptsUs) + val limit = when { + queuedBytes > maxBytes -> Limit.BYTES + frames.size >= maxFrames -> Limit.FRAMES + queuedSpan > maxSpanUs -> Limit.SPAN + else -> null + } + val overflow = limit?.let { + resetLocked() + overflows++ + Overflow(it, queuedBytes, queuedSpan) + } + if (size > maxBytes || (awaitingKeyframe && !frame.keyFrame)) { + dropped++ + return Offer(true, overflow) + } + awaitingKeyframe = false + frames.addLast(pending) + bytes += size + ready.signal() + Offer(false, overflow) + } + + fun poll(timeoutMs: Long): PendingFrame? = lock.withLock { + var remaining = TimeUnit.MILLISECONDS.toNanos(timeoutMs) + while (frames.isEmpty()) { + if (remaining <= 0) return null + remaining = ready.awaitNanos(remaining) + } + frames.removeFirst().also { bytes -= it.frame.data.size } + } + + /** Drops everything queued; the next accepted frame must be a keyframe. */ + fun reset() = lock.withLock { resetLocked() } + + private fun resetLocked() { + dropped += frames.size + frames.clear() + bytes = 0 + awaitingKeyframe = true + } + + val size: Int get() = lock.withLock { frames.size } + val droppedFrames: Long get() = lock.withLock { dropped } + + fun facts(): String = lock.withLock { + val span = if (frames.size > 1) spanTo(frames.last().frame.ptsUs) else 0 + "dropped=$dropped queue=${frames.size} queueBytes=$bytes queueSpanMs=${span / 1_000} queueOverflows=$overflows" + } + + private fun spanTo(newest: Long): Long { + val oldest = frames.firstOrNull()?.frame?.ptsUs ?: return 0 + return if (newest > oldest) newest - oldest else 0 + } +} diff --git a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeOutput.kt b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeOutput.kt index 55046e6..fe12719 100644 --- a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeOutput.kt +++ b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeOutput.kt @@ -14,7 +14,6 @@ import java.net.InetSocketAddress import java.net.NetworkInterface import java.net.ServerSocket import java.net.Socket -import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.ScheduledThreadPoolExecutor import java.util.concurrent.Semaphore import java.util.concurrent.ThreadFactory @@ -42,7 +41,6 @@ public class CarlifeOutput( const val AUDIO_QUEUE_BYTES = 256 * 1024 } - private data class PendingFrame(val frame: VideoFrame, val format: VideoFormat, val epoch: Long) private class AudioAnnouncement(val format: AudioFormat) private data class PendingAudio( val packet: AudioPacket, @@ -61,7 +59,7 @@ public class CarlifeOutput( private class Run(val host: OutputHost, val executor: ScheduledThreadPoolExecutor, val watchdog: ScheduledThreadPoolExecutor) { val active = AtomicBoolean(true) val servers = mutableListOf() - val queue = ArrayBlockingQueue(3) + val queue = CarlifeFrameQueue() val epoch = AtomicLong() // The lock protects only the mailbox. All transport I/O happens after releasing it. val audioLock = ReentrantLock() @@ -93,13 +91,11 @@ public class CarlifeOutput( } val readers = Semaphore(14) val receivedFrames = AtomicLong() - val droppedFrames = AtomicLong() val receivedKeyframes = AtomicLong() val keyRequestPending = AtomicBoolean() @Volatile var session: CarlifeSession? = null @Volatile var format: VideoFormat? = null @Volatile var inputSession: SessionId? = null - @Volatile var awaitingKeyframe = true } private val threads = ThreadFactory { work -> Thread(work, "carlife").apply { isDaemon = true } } @@ -162,7 +158,7 @@ public class CarlifeOutput( } }, { current.format }, { "sourceFrames=${current.receivedFrames.get()} sourceKeyframes=${current.receivedKeyframes.get()} " + - "dropped=${current.droppedFrames.get()} queue=${current.queue.size} audioQueueDropped=${current.droppedAudio.get()}" }, + "${current.queue.facts()} audioQueueDropped=${current.droppedAudio.get()}" }, wakeAudio = { current.audioLock.withLock { current.signalAudio() } }, microphoneCurrent = { current.microphone === it }, finishAudio = { finish, abort -> finishAudio(current, finish, abort) }) @@ -383,33 +379,34 @@ public class CarlifeOutput( if (format.codec != VideoCodec.H264 || current.session?.streaming != true) return current.receivedFrames.incrementAndGet() if (frame.keyFrame) current.receivedKeyframes.incrementAndGet() - if (current.awaitingKeyframe && !frame.keyFrame) { current.droppedFrames.incrementAndGet(); return } - if (frame.keyFrame) current.awaitingKeyframe = false - if (!current.queue.offer(PendingFrame(frame, format, current.epoch.get()))) { - current.droppedFrames.addAndGet(current.queue.size.toLong() + if (frame.keyFrame) 0 else 1) - current.queue.clear() - current.awaitingKeyframe = true - if (frame.keyFrame) { - current.awaitingKeyframe = false - current.queue.offer(PendingFrame(frame, format, current.epoch.get())) - } - if (current.keyRequestPending.compareAndSet(false, true)) runCatching { - current.executor.execute { - current.keyRequestPending.set(false) - current.session?.requestKeyframe() - } - } + val offer = current.queue.offer(PendingFrame(frame, format, current.epoch.get())) + offer.overflow?.let { + current.session?.queueOverflow("limit=${it.limit.name.lowercase()} queueBytes=${it.bytes} queueSpanMs=${it.spanUs / 1_000}") + } + when { + offer.recovery -> recoverKeyframe(current, if (offer.overflow == null) "awaiting_keyframe" else "queue_overflow") + frame.keyFrame -> current.session?.keyframeQueued() } } + private fun recoverKeyframe(current: Run, reason: String) { + if (current.keyRequestPending.compareAndSet(false, true)) runCatching { + current.executor.execute { + current.keyRequestPending.set(false) + safely(current) { current.session?.requestKeyframeRecovery(reason) } + } + }.onFailure { current.keyRequestPending.set(false) } + } + private fun media(current: Run) { var nextSend = 0L var previous: CarlifeSession? = null var videoFormat: VideoFormat? = null var parameterSetsSent = false while (current.active.get()) { - val pending = try { current.queue.poll(250, TimeUnit.MILLISECONDS) } catch (_: InterruptedException) { null } - ?: continue + val pending = try { current.queue.poll(250) } catch (_: InterruptedException) { null } + current.session?.flushKeyframeRequest() + if (pending == null) continue val selected = current.session ?: continue if (selected !== previous) { nextSend = 0; previous = selected; videoFormat = null; parameterSetsSent = false @@ -448,23 +445,21 @@ public class CarlifeOutput( } try { if (selected.video(bytes)) { + if (pending.frame.keyFrame) selected.keyframeSent() val now = System.nanoTime() nextSend = if (nextSend == 0L) now + period else maxOf(nextSend + period, now) } } catch (_: Exception) { terminate(current, selected, "video_write_failed", 2) } } catch (_: Exception) { - current.awaitingKeyframe = true - current.queue.clear() - runCatching { current.executor.execute { safely(current) { selected.requestKeyframe() } } } + current.queue.reset() + recoverKeyframe(current, "frame_rejected") } } } private fun resetMedia(current: Run) { current.epoch.incrementAndGet() - current.droppedFrames.addAndGet(current.queue.size.toLong()) - current.queue.clear() - current.awaitingKeyframe = true + current.queue.reset() } private fun failureCode(error: Throwable): String = when (error) { @@ -600,7 +595,7 @@ public class CarlifeOutput( threads.newThread { synchronized(current.servers) { current.servers.forEach { runCatching { it.close() } }; current.servers.clear() } current.session?.close("output_closed") - current.queue.clear() + current.queue.reset() current.audioLock.withLock { current.clearAudioPackets() current.audioFormats = emptyMap() diff --git a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeSession.kt b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeSession.kt index 44f3207..9ef1e1f 100644 --- a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeSession.kt +++ b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/CarlifeSession.kt @@ -24,7 +24,15 @@ internal class CarlifeSession( private val wakeAudio: () -> Unit = {}, private val microphoneCurrent: (MicRequest) -> Boolean = { true }, private val finishAudio: ((finish: () -> Unit, abort: () -> Unit) -> Unit)? = null, + private val clock: () -> Long = System::nanoTime, ) { + private companion object { + val quietRxIds = setOf(131074, 425985, 425998, 360449) + val quietTxIds = setOf(131073, 131074) + CarlifeAudio.Lane.entries.map { it.dataId } + const val KEYFRAME_RECOVERY_INTERVAL_NS = 1_000_000_000L + const val KEYFRAME_REFRESH_INTERVAL_NS = 5_000_000_000L + } + val active = AtomicBoolean(true) private val channels = ConcurrentHashMap() private val crypto = CarlifeCrypto() @@ -49,7 +57,14 @@ internal class CarlifeSession( internal val parameterSetsInEveryKeyframe: Boolean get() = receiver.parameterSetsInEveryKeyframe private var encoderChannel = 1 private var encryptionRequested = false - private var lastKeyframeRequest = 0L + // Recovery requests are coalesced and the periodic refresh follows keyframes actually sent, so a + // queue overflow cannot feed a loop of keyframe requests and large IDR writes. + private val keyframeLock = Any() + private var lastKeyframeRequest: Long? = null + private var lastKeyframeSent: Long? = null + private var pendingKeyframeReason: String? = null + private val keyframeRequestsDeferred = AtomicLong() + private var queueOverflowLogged = false private val lastSent = AtomicLong(System.nanoTime()) private val sent = AtomicLong() private val createdAt = System.nanoTime() @@ -80,11 +95,6 @@ internal class CarlifeSession( private val rootFailure = AtomicReference() private val wireLogAt = mutableMapOf() - private companion object { - val quietRxIds = setOf(131074, 425985, 425998, 360449) - val quietTxIds = setOf(131073, 131074) + CarlifeAudio.Lane.entries.map { it.dataId } - } - private fun diagnostic(event: String) { diagnosticSink("session=${origin.clientId} phase=$phase elapsedMs=${(System.nanoTime() - createdAt) / 1_000_000} $event") } @@ -237,7 +247,7 @@ internal class CarlifeSession( protocolRequire(authenticated && width > 0, "unexpected_phase") streaming = true stage("video_requested") - requestKeyframe() + sendKeyframeRequest("peer_start") } 98389 -> runCatching { Proto.parse(message.payload).text(1) }.getOrNull() ?.let { diagnostic("peer_code code=$it") } @@ -397,7 +407,7 @@ internal class CarlifeSession( streaming = false stage("video_reconfiguring") encoderInfo() - requestKeyframe() + sendKeyframeRequest("source_size_change") } } @@ -421,7 +431,13 @@ internal class CarlifeSession( send(if (channels[2] != null) 2 else 1, 131074) } if (streaming) { - if (System.nanoTime() - lastKeyframeRequest >= 1_500_000_000L) requestKeyframe() + flushKeyframeRequest() + val time = clock() + val refresh = synchronized(keyframeLock) { + lastKeyframeSent.let { it == null || time - it >= KEYFRAME_REFRESH_INTERVAL_NS } && + lastKeyframeRequest.let { it == null || time - it >= KEYFRAME_REFRESH_INTERVAL_NS } + } + if (refresh) sendKeyframeRequest("periodic") if (sent.get() > 0) report(CarlifeState.STREAMING) } val now = System.nanoTime() @@ -434,15 +450,53 @@ internal class CarlifeSession( if (now - lastSummary >= 10_000_000_000L) { lastSummary = now diagnostic("summary rx=${received.get()} sent=${sent.get()} keyframeRequests=${keyframeRequests.get()} " + + "keyframeRequestsDeferred=${keyframeRequestsDeferred.get()} " + "inputDown=${inputDown.get()} inputUp=${inputUp.get()} inputMove=${inputMove.get()} " + "lastRxMs=${(now - lastReceived.get()) / 1_000_000} lastTxMs=${(now - lastSent.get()) / 1_000_000} " + "encryption=${crypto.active} ${mediaCounters()} ${audio?.stats.orEmpty()}") } } - fun requestKeyframe() { - lastKeyframeRequest = System.nanoTime() - keyframeRequests.incrementAndGet() + /** Asks the source for a keyframe at most once per second; later reasons wait for the pending one. */ + fun requestKeyframeRecovery(reason: String) { + synchronized(keyframeLock) { + if (pendingKeyframeReason == null) pendingKeyframeReason = reason + else keyframeRequestsDeferred.incrementAndGet() + } + flushKeyframeRequest() + } + + /** Sends a deferred recovery request once its interval has passed. Callable from any worker. */ + fun flushKeyframeRequest() { + val reason = synchronized(keyframeLock) { + val time = clock() + val reason = pendingKeyframeReason ?: return + if (!streaming || lastKeyframeRequest.let { it != null && time - it < KEYFRAME_RECOVERY_INTERVAL_NS }) return + reason + } + sendKeyframeRequest(reason) + } + + /** A queued keyframe makes any pending recovery request redundant. */ + fun keyframeQueued() = synchronized(keyframeLock) { pendingKeyframeReason = null } + + fun keyframeSent() = synchronized(keyframeLock) { lastKeyframeSent = clock() } + + /** Logs the first overflow of this session; the summary carries the running count. */ + fun queueOverflow(facts: String) { + val first = synchronized(keyframeLock) { !queueOverflowLogged.also { queueOverflowLogged = true } } + if (first) diagnostic("video_queue_overflow $facts action=reset_queue") + } + + private fun sendKeyframeRequest(reason: String) { + val time = clock() + val sinceLast = synchronized(keyframeLock) { + val previous = lastKeyframeRequest + pendingKeyframeReason = null + lastKeyframeRequest = time + previous?.let { ((time - it) / 1_000_000).toString() } ?: "none" + } + if (keyframeRequests.incrementAndGet() <= 8) diagnostic("video_keyframe_request reason=$reason sinceLastMs=$sinceLast") host.control(ControlEvent.KeyFrameRequest(ScreenId.MAIN, origin)) } diff --git a/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeFrameQueueTest.kt b/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeFrameQueueTest.kt new file mode 100644 index 0000000..da476a7 --- /dev/null +++ b/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeFrameQueueTest.kt @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: 2026 OpenXPlay.org +// SPDX-License-Identifier: AGPL-3.0-only +// Created by riko chen on 2026-11-29 + +package org.openxplay.stream.carlife + +import org.openxplay.stream.core.* +import kotlin.test.* +import org.junit.jupiter.api.Test + +class CarlifeFrameQueueTest { + private val format = testFormat() + private fun frame(ptsMs: Long, key: Boolean = false, size: Int = 100) = PendingFrame( + VideoFrame(ScreenId.MAIN, SessionId(1), ByteArray(size), ptsMs * 1_000, key, 0), format, 0) + + @Test fun waitsForAKeyframeAndAsksForOne() { + val queue = CarlifeFrameQueue() + assertTrue(queue.offer(frame(0)).recovery) + assertFalse(queue.offer(frame(16, key = true)).recovery) + assertFalse(queue.offer(frame(33)).recovery) + assertEquals(2, queue.size) + assertEquals(1, queue.droppedFrames) + } + + @Test fun absorbsABurstWithinTheSpanLimit() { + val queue = CarlifeFrameQueue() + queue.offer(frame(0, key = true)) + // Sixty frames arriving at once, as a Wi-Fi batch or a 60 fps source against 30 fps pacing. + for (index in 1 until 30) assertNull(queue.offer(frame(index * 16L)).overflow) + assertEquals(30, queue.size) + assertEquals(0, queue.droppedFrames) + assertEquals(0L, queue.poll(0)!!.frame.ptsUs) + } + + @Test fun spanOverflowResetsAndKeepsAnIncomingKeyframe() { + val queue = CarlifeFrameQueue(maxSpanUs = 100_000) + queue.offer(frame(0, key = true)) + queue.offer(frame(50)) + val keyed = queue.offer(frame(150, key = true)) + assertEquals(CarlifeFrameQueue.Limit.SPAN, keyed.overflow?.limit) + assertFalse(keyed.recovery) + assertEquals(1, queue.size) + assertTrue(queue.facts().contains("queueOverflows=1")) + + queue.offer(frame(200)) + val delta = queue.offer(frame(300)) + assertEquals(CarlifeFrameQueue.Limit.SPAN, delta.overflow?.limit) + assertTrue(delta.recovery) + assertEquals(0, queue.size) + } + + @Test fun byteAndFrameLimits() { + val bytes = CarlifeFrameQueue(maxBytes = 250) + bytes.offer(frame(0, key = true)) + bytes.offer(frame(1)) + assertEquals(CarlifeFrameQueue.Limit.BYTES, bytes.offer(frame(2)).overflow?.limit) + val frames = CarlifeFrameQueue(maxFrames = 2) + frames.offer(frame(0, key = true)) + frames.offer(frame(1)) + assertEquals(CarlifeFrameQueue.Limit.FRAMES, frames.offer(frame(2)).overflow?.limit) + assertTrue(CarlifeFrameQueue(maxBytes = 50).offer(frame(0, key = true)).recovery, "an oversized frame is dropped") + } + + @Test fun pollTimesOutWhenEmpty() { + assertNull(CarlifeFrameQueue().poll(1)) + } +} diff --git a/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeSessionTest.kt b/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeSessionTest.kt index 8ed729b..f6ddba8 100644 --- a/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeSessionTest.kt +++ b/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeSessionTest.kt @@ -26,13 +26,13 @@ internal fun testFormat(): VideoFormat { } class CarlifeSessionTest { - private class Fixture(val source: VideoFormat? = null) { + private class Fixture(val source: VideoFormat? = null, clock: () -> Long = System::nanoTime) { val host = RecordingHost() val states = mutableListOf() val diagnostics = mutableListOf() val outputs = (1..7).associateWith { ByteArrayOutputStream() } val session = CarlifeSession("test", CarlifeConfig(), CarlifeDeviceInfo(), host, - Origin("carlife", "test"), { states += it }, { diagnostics += it }, { source }) + Origin("carlife", "test"), { states += it }, { diagnostics += it }, { source }, clock = clock) init { for (channel in 1..7) session.attach(CarlifeConnection(ByteArrayInputStream(byteArrayOf()), outputs.getValue(channel), Closeable {}, false, channel)) } fun receive(id: Int, bytes: ByteArray = byteArrayOf(), channel: Int = 1) = session.receive(CarlifeMessage(channel, id, bytes)) @@ -214,4 +214,42 @@ class CarlifeSessionTest { fixture.receive(98386, features(1)) assertEquals(1, fixture.messages().count { it.id == 65642 }) } + + @Test fun recoveryRequestsAreCoalescedAndPeriodicRefreshFollowsSentKeyframes() { + var now = 0L + val fixture = Fixture(clock = { now }) + fun requests() = fixture.host.events.count { it is ControlEvent.KeyFrameRequest } + fixture.authenticate() + fixture.negotiate() + fixture.receive(98313) + assertEquals(1, requests()) + + now += 200_000_000 + fixture.session.requestKeyframeRecovery("queue_overflow") + fixture.session.requestKeyframeRecovery("queue_overflow") + assertEquals(1, requests(), "recovery waits one second after the previous request") + now += 800_000_000 + fixture.session.flushKeyframeRequest() + assertEquals(2, requests()) + fixture.session.flushKeyframeRequest() + assertEquals(2, requests(), "one pending reason produces one request") + + now += 1_500_000_000 + fixture.session.requestKeyframeRecovery("awaiting_keyframe") + assertEquals(3, requests()) + now += 200_000_000 + fixture.session.requestKeyframeRecovery("awaiting_keyframe") + fixture.session.keyframeQueued() + now += 2_000_000_000 + fixture.session.flushKeyframeRequest() + assertEquals(3, requests(), "a queued keyframe cancels pending recovery") + + fixture.session.keyframeSent() + now += 4_000_000_000 + fixture.session.tick() + assertEquals(3, requests(), "no periodic refresh within five seconds of a sent keyframe") + now += 1_000_000_000 + fixture.session.tick() + assertEquals(4, requests()) + } }