From 30d982add0abbe7b78cffba4cebdacc3d2bb32cf Mon Sep 17 00:00:00 2001 From: Riko Date: Sat, 7 Nov 2026 23:32:57 -0800 Subject: [PATCH] CarLife: select a receiver profile so 3.x and 4.x head units both connect A 3.3.9 receiver announces protocol 1.0, skips the authentication challenge, sends frame rate 0, and keeps the first frame's parameter sets for its own decoder resets. Select a per-session profile from the announced major: 1.x establishes at video negotiation and receives parameter sets only with the first keyframe of each format; 3.x/4.x keeps the challenge flow and in-band sets on every keyframe. Keyframes for the legacy profile start with the IDR slice so the receiver's reset path can prepend its stored SPS/PPS. --- .../openxplay/stream/carlife/CarlifeOutput.kt | 36 +++++++++++++++---- .../stream/carlife/CarlifeSession.kt | 31 +++++++++++++--- .../stream/carlife/ReceiverProfile.kt | 29 +++++++++++++++ .../stream/carlife/CarlifeOutputTest.kt | 36 +++++++++++++++++++ .../stream/carlife/CarlifeSessionTest.kt | 28 +++++++++++++++ 5 files changed, 148 insertions(+), 12 deletions(-) create mode 100644 kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/ReceiverProfile.kt 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 6697d5d..d1319b7 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 @@ -332,25 +332,47 @@ public class CarlifeOutput( 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 selected = current.session ?: continue - if (selected !== previous) { nextSend = 0; previous = selected } + if (selected !== previous) { + nextSend = 0; previous = selected; videoFormat = null; parameterSetsSent = false + } if (pending.epoch != current.epoch.get() || pending.format !== current.format || !selected.streaming) continue + if (pending.format !== videoFormat) { videoFormat = pending.format; parameterSetsSent = false } try { val period = 1_000_000_000L / selected.fps val wait = nextSend - System.nanoTime() if (wait > 0) TimeUnit.NANOSECONDS.sleep(wait) if (pending.epoch != current.epoch.get() || current.session !== selected) continue val annex = Nal.avccToAnnexB(pending.frame.data) - val bytes = if (pending.frame.keyFrame) { - val parsed = AvcConfig.parse(pending.format.config) - val sets = (parsed.sps + parsed.pps).fold(byteArrayOf()) { all, nal -> - all + byteArrayOf(0, 0, 0, 1) + nal + val bytes = when { + selected.parameterSetsInEveryKeyframe -> if (pending.frame.keyFrame) { + val parsed = AvcConfig.parse(pending.format.config) + val sets = (parsed.sps + parsed.pps).fold(byteArrayOf()) { all, nal -> + all + byteArrayOf(0, 0, 0, 1) + nal + } + sets + annex + } else annex + // A 3.x receiver keeps the first frame's parameter sets and supplies them + // itself after a decoder reset, but only to a keyframe whose first NAL is IDR. + pending.frame.keyFrame -> { + val idr = Nal.units(pending.frame.data, Nal.Format.AVCC) + .dropWhile { it[0].toInt() and 0x1f != 5 }.toList() + if (idr.isEmpty()) annex else { + val sets = if (parameterSetsSent) byteArrayOf() else AvcConfig.parse(pending.format.config) + .let { parsed -> (parsed.sps + parsed.pps).fold(byteArrayOf()) { all, nal -> + all + byteArrayOf(0, 0, 0, 1) + nal + } } + parameterSetsSent = true + sets + idr.fold(byteArrayOf()) { all, nal -> all + byteArrayOf(0, 0, 0, 1) + nal } + } } - sets + annex - } else annex + else -> annex + } try { if (selected.video(bytes)) { val now = System.nanoTime() 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 2fa7349..0a34521 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 @@ -26,6 +26,8 @@ internal class CarlifeSession( private val channels = ConcurrentHashMap() private val crypto = CarlifeCrypto() private var version = false + private var peerMajor = 0L + private var profile: ReceiverProfile? = null private var deviceSent = false private var authAnswered = false private var authAccepted = false @@ -39,6 +41,9 @@ internal class CarlifeSession( private set @Volatile var fps = config.fps private set + /** The selected receiver generation; available after 98305. */ + internal val receiver: ReceiverProfile get() = checkNotNull(profile) + internal val parameterSetsInEveryKeyframe: Boolean get() = receiver.parameterSetsInEveryKeyframe private var encoderChannel = 1 private var encryptionRequested = false private var lastKeyframeRequest = 0L @@ -107,14 +112,19 @@ internal class CarlifeSession( when (message.id) { 98305 -> { protocolRequire(!version, "unexpected_phase") - val major = payload.number(1) - if (major !in 3L..4L) { - diagnostic("version_rejected major=${diagnosticVersion(major)} minor=${diagnosticVersion(payload.number(2))}") + val announced = payload.number(1) ?: run { + diagnostic("version_rejected major=absent minor=${diagnosticVersion(payload.number(2))}") throw CarlifeProtocolException("version_mismatch") } + val selected = ReceiverProfile.of(announced) ?: run { + diagnostic("version_rejected major=${diagnosticVersion(announced)} minor=${diagnosticVersion(payload.number(2))}") + throw CarlifeProtocolException("version_mismatch") + } + peerMajor = announced + profile = selected version = true stage("version_matched") - send(1, 65538, ProtoWriter().number(1, 1).number(2, 4).build()) + send(1, 65538, ProtoWriter().number(1, 1).number(2, announced).build()) report(CarlifeState.CONNECTED) } 98343, 98307 -> sendDevice() @@ -159,6 +169,14 @@ internal class CarlifeSession( 98413 -> { protocolRequire(!crypto.active, "unexpected_phase"); send(1, 65646) } 98415 -> { crypto.activate(); diagnostic("encryption active=true") } 98311 -> { + // A receiver that does not challenge the sender establishes the session at video + // negotiation, as a 4.x receiver does at 98380. + if (!authenticated && !receiver.challenges) { + authenticated = true + stage("established") + diagnostic("authentication absent peerMajor=$peerMajor") + report(CarlifeState.AUTHENTICATED) + } protocolRequire(authenticated, "unexpected_phase") val rawWidth = payload.number(1) val rawHeight = payload.number(2) @@ -173,7 +191,8 @@ internal class CarlifeSession( width = it.width height = it.height } - fps = (payload.number(3)?.toInt() ?: config.fps).coerceIn(1, config.fps) + val requestedFps = payload.number(3)?.toInt() ?: 0 + fps = if (requestedFps > 0) requestedFps.coerceIn(1, config.fps) else config.fps encoderChannel = message.channel diagnostic("video_negotiated requested=${requestedWidth}x$requestedHeight selected=${width}x$height fps=$fps codec=H264") stage("video_negotiated") @@ -187,6 +206,8 @@ internal class CarlifeSession( stage("video_requested") requestKeyframe() } + 98389 -> runCatching { Proto.parse(message.payload).text(1) }.getOrNull() + ?.let { diagnostic("peer_code code=$it") } 98314 -> { streaming = false stage("video_stopped") diff --git a/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/ReceiverProfile.kt b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/ReceiverProfile.kt new file mode 100644 index 0000000..39449f6 --- /dev/null +++ b/kotlin/carlife/src/main/kotlin/org/openxplay/stream/carlife/ReceiverProfile.kt @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2026 OpenXPlay.org +// SPDX-License-Identifier: AGPL-3.0-only +// Created by riko chen on 2026-11-07 + +package org.openxplay.stream.carlife + +/** + * Protocol differences between CarLife receiver generations, selected from the major version the + * head unit announces in 98305. Both profiles share framing, ports, touch and video delivery; + * only the session handshake and the video parameter-set policy differ. + */ +internal enum class ReceiverProfile( + internal val majors: LongRange, + /** A 4.x receiver challenges the sender and waits for its result; 3.x has no challenge. */ + internal val challenges: Boolean, + /** 4.x accepts in-band parameter sets in every keyframe; 3.x stores them once per decoder. */ + internal val parameterSetsInEveryKeyframe: Boolean, +) { + /** 3.x generation (CarLife 3.0 apps, protocol 1.0). */ + Legacy(1L..1L, challenges = false, parameterSetsInEveryKeyframe = false), + + /** 4.x generation (protocol 4.x); the majors the previous implementation accepted. */ + Current(3L..4L, challenges = true, parameterSetsInEveryKeyframe = true), + ; + + companion object { + fun of(major: Long): ReceiverProfile? = entries.firstOrNull { major in it.majors } + } +} diff --git a/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeOutputTest.kt b/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeOutputTest.kt index 164cf64..64a0c65 100644 --- a/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeOutputTest.kt +++ b/kotlin/carlife/src/test/kotlin/org/openxplay/stream/carlife/CarlifeOutputTest.kt @@ -38,6 +38,16 @@ class CarlifeOutputTest { } error("Expected CarLife response $id") } + fun handshakeLegacy() { + send(98305, ProtoWriter().number(1, 1).number(2, 0).build()) + assertEquals(1L, Proto.parse(next(65538).payload).number(1)) + send(98343) + next(65540) + send(98307) + send(98311, ProtoWriter().number(1, 1280).number(2, 720).number(3, 0).build()) + assertEquals(30L, Proto.parse(next(65544).payload).number(3)) + send(98313) + } fun handshake() { send(98305, ProtoWriter().number(1, 4).number(2, 1).build()) assertEquals(1L, Proto.parse(next(65538).payload).number(1)) @@ -89,6 +99,32 @@ class CarlifeOutputTest { } finally { output.close() } } + @Test fun protocolOneReceiverGetsParameterSetsOnceAndKeyframesStartWithIdr() { + val host = RecordingHost() + val output = CarlifeOutput(CarlifeConfig(bindAddress = "127.0.0.1", discovery = false, ports = List(7) { 0 })) + try { + output.open(host) + val session = SessionId(21) + output.onSession(SessionState(session, SessionPhase.ACTIVE), SessionConfig(emptyMap())) + output.onVideoFormat(ScreenId.MAIN, testFormat()) + await { output.boundPorts.size == 7 } + Peer(output).use { peer -> + peer.handshakeLegacy() + await { host.events.any { it is ControlEvent.KeyFrameRequest } } + fun key(marker: Byte) = VideoFrame(ScreenId.MAIN, session, + byteArrayOf(0, 0, 0, 2, 0x09, 0x30, 0, 0, 0, 2, 0x65, marker), 0, true, 0) + output.onVideoFrame(key(1)) + val first = Nal.units(peer.next(131073, 2).payload, Nal.Format.ANNEX_B) + .map { it[0].toInt() and 0x1f }.toList() + assertEquals(listOf(7, 8, 5), first) + output.onVideoFrame(key(2)) + val second = Nal.units(peer.next(131073, 2).payload, Nal.Format.ANNEX_B) + .map { it[0].toInt() and 0x1f }.toList() + assertEquals(listOf(5), second) + } + } finally { output.close() } + } + @Test fun wireIsSilentBeforeVersionAndCloseCancelsAllReaders() { val host = RecordingHost() val stopped = CountDownLatch(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 7c0c45b..8ed729b 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 @@ -119,6 +119,34 @@ class CarlifeSessionTest { assertFalse(fixture.session.video(byteArrayOf(1))) } + @Test fun protocolOneReceiverEstablishesWithoutChallengeAndDefaultsAZeroFrameRate() { + val fixture = Fixture() + fixture.receive(98305, ProtoWriter().number(1, 1).number(2, 0).build()) + assertEquals(1L, Proto.parse(fixture.messages().single().payload).number(2)) + fixture.receive(98343) + fixture.receive(98307) + fixture.receive(98311, ProtoWriter().number(1, 2327).number(2, 1041).number(3, 0).build()) + assertTrue(fixture.session.authenticated) + assertFalse(fixture.session.parameterSetsInEveryKeyframe) + assertEquals(30L, Proto.parse(fixture.messages().last { it.id == 65544 }.payload).number(3)) + assertTrue(fixture.states.any { it.state == CarlifeState.AUTHENTICATED }) + fixture.receive(98313) + assertTrue(fixture.session.video(byteArrayOf(0, 0, 0, 1, 0x65))) + } + + @Test fun receiverProfileIsSelectedFromTheAnnouncedMajor() { + assertEquals(ReceiverProfile.Legacy, ReceiverProfile.of(1)) + assertEquals(ReceiverProfile.Current, ReceiverProfile.of(3)) + assertEquals(ReceiverProfile.Current, ReceiverProfile.of(4)) + assertNull(ReceiverProfile.of(5)) + } + + @Test fun protocolFourReceiverKeepsParameterSetsInBand() { + val fixture = Fixture() + fixture.receive(98305, ProtoWriter().number(1, 4).number(2, 1).build()) + assertTrue(fixture.session.parameterSetsInEveryKeyframe) + } + @Test fun fixedSourceSpsSizeIsUsedInTheFirstEncoderReply() { val fixture = Fixture(testFormat()) fixture.authenticate()