Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<PendingFrame>()
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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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<ServerSocket>()
val queue = ArrayBlockingQueue<PendingFrame>(3)
val queue = CarlifeFrameQueue()
val epoch = AtomicLong()
// The lock protects only the mailbox. All transport I/O happens after releasing it.
val audioLock = ReentrantLock()
Expand Down Expand Up @@ -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 } }
Expand Down Expand Up @@ -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) })
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Int, CarlifeConnection>()
private val crypto = CarlifeCrypto()
Expand All @@ -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()
Expand Down Expand Up @@ -80,11 +95,6 @@ internal class CarlifeSession(
private val rootFailure = AtomicReference<Failure?>()
private val wireLogAt = mutableMapOf<Int, Long>()

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")
}
Expand Down Expand Up @@ -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") }
Expand Down Expand Up @@ -397,7 +407,7 @@ internal class CarlifeSession(
streaming = false
stage("video_reconfiguring")
encoderInfo()
requestKeyframe()
sendKeyframeRequest("source_size_change")
}
}

Expand All @@ -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()
Expand All @@ -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))
}

Expand Down
Loading
Loading