Spotify AAC Support

This commit is contained in:
Danny
2026-11-15 10:44:42 -08:00
parent c7a9bf284b
commit bb8a202d90
3 changed files with 193 additions and 30 deletions
@@ -32,14 +32,14 @@ def nal_types(data: bytes) -> list[int]:
return types
def import_av():
"""Import a PyAV whose FFmpeg includes libx264, preferring the system install."""
def import_av(codec: str = "libx264"):
"""Import a PyAV whose FFmpeg includes the codec, preferring the system install."""
errors = []
try:
import av
if "libx264" in av.codecs_available:
if codec in av.codecs_available:
return av
errors.append(f"system PyAV {av.__version__} lacks libx264")
errors.append(f"system PyAV {av.__version__} lacks {codec}")
except ImportError as error:
errors.append(f"system PyAV missing ({error})")
if os.path.isdir(ISOLATED_DEPS):
@@ -48,15 +48,15 @@ def import_av():
sys.path.insert(0, ISOLATED_DEPS)
try:
import av
if "libx264" in av.codecs_available:
if codec in av.codecs_available:
return av
errors.append(f"isolated PyAV {av.__version__} lacks libx264")
errors.append(f"isolated PyAV {av.__version__} lacks {codec}")
except ImportError as error:
errors.append(f"isolated PyAV missing ({error})")
finally:
if sys.path and sys.path[0] == ISOLATED_DEPS:
sys.path.pop(0)
raise RuntimeError("No H.264 encoder available: " + "; ".join(errors))
raise RuntimeError(f"No {codec} encoder available: " + "; ".join(errors))
# ANDROID AUTO VIDEO PERFORMANCE GUARDRAIL: The software fallback uses zero-latency H.264 with no encoder-side frame queue.
@@ -5,7 +5,7 @@ by messages the session loop already reads, so nothing here waits on the car and
keeps its timing: open → setup (PCM) → audio focus → start → timestamped PCM with ACK credit.
PCM comes from the Spotify supervisor's real-time pipe (48 kHz, 16-bit, stereo), which runs on the
system clock and carries silence while paused. Focus is requested when sound starts and released
system clock and carries silence while paused; cars that only take AAC-LC get it encoded here. Focus is requested when sound starts and released
after a stretch of silence, the way a phone treats a paused player. If the car takes focus for good
(the driver picks the radio), the selected source is paused instead of fighting for the speakers.
"""
@@ -21,6 +21,7 @@ import termios
import threading
import time
from collections.abc import Callable
from fractions import Fraction
from pathlib import Path
from typing import Any
@@ -31,6 +32,7 @@ MSG_CHANNEL_OPEN_RESPONSE = 0x08
AUDIO_FOCUS_REQUEST = 0x12
AUDIO_FOCUS_NOTIFICATION = 0x13
AV_MEDIA_WITH_TIMESTAMP = 0x0000
AV_MEDIA_CODEC_CONFIG = 0x0001
AV_SETUP_REQUEST = 0x8000
AV_START_INDICATION = 0x8001
AV_STOP_INDICATION = 0x8002
@@ -38,6 +40,7 @@ AV_SETUP_RESPONSE = 0x8003
AV_MEDIA_ACK = 0x8004
CODEC_PCM = 1
CODEC_AAC_LC = 2
AUDIO_TYPE_MEDIA = 3
SETUP_STATUS_READY = 2
FOCUS_GAIN, FOCUS_RELEASE = 1, 4
@@ -59,19 +62,61 @@ RELEASE_AFTER = 8.0 # seconds of silence before giving t
STEP_TIMEOUT = 3.0
ACK_STALL = 3.0
RETRY_AFTER = 10.0
AAC_FRAME_BYTES = 1024 * FRAME_BYTES
AAC_PER_PASS = 8
AAC_BITRATE = 192000
def media_channel(channels: list[dict]) -> tuple[int, int] | None:
"""(channel id, configuration index) of the head unit's PCM media channel at 48 kHz/16-bit/stereo."""
for channel in channels:
if channel.get('media_type') != CODEC_PCM or channel.get('audio_type') != AUDIO_TYPE_MEDIA:
continue
for index, config in enumerate(channel.get('audio_configs', [])):
if (one(config, 1), one(config, 2), one(config, 3)) == (RATE, BITS, CHANNELS):
return int(channel['id']), index
def audio_format(config: dict) -> tuple:
return one(config, 1), one(config, 2), one(config, 3)
def media_channel(channels: list[dict]) -> tuple[int, int, int] | None:
"""(channel id, configuration index, codec) of the head unit's 48 kHz/16-bit/stereo media channel, PCM first."""
for codec in (CODEC_PCM, CODEC_AAC_LC):
for channel in channels:
if channel.get('media_type') != codec or channel.get('audio_type') != AUDIO_TYPE_MEDIA:
continue
for index, config in enumerate(channel.get('audio_configs', [])):
if audio_format(config) == (RATE, BITS, CHANNELS):
return int(channel['id']), index, codec
return None
def offered_audio(channels: list[dict]) -> list[dict]:
return [{'id': c.get('id'), 'media_type': c.get('media_type'), 'audio_type': c.get('audio_type'),
'configs': [list(audio_format(config)) for config in c.get('audio_configs', [])]}
for c in channels if 'audio_type' in c]
class AacEncoder:
"""48 kHz stereo s16 PCM to raw AAC-LC access units (no ADTS)."""
def __init__(self):
from openpilot.starpilot.system.starport.encoder import import_av
import numpy as np
av = import_av('aac')
self.av, self.np = av, np
codec = av.CodecContext.create('aac', 'w')
codec.sample_rate = RATE
codec.layout = 'stereo'
codec.format = 'fltp'
codec.bit_rate = AAC_BITRATE
codec.time_base = Fraction(1, RATE)
codec.open()
self.codec = codec
self.pts = 0
self.config = bytes(codec.extradata or b'')[:2] # AudioSpecificConfig
def encode(self, pcm: bytes) -> list[bytes]:
np = self.np
samples = np.frombuffer(pcm, dtype='<i2').reshape(-1, CHANNELS).T.astype(np.float32) / 32768.0
frame = self.av.AudioFrame.from_ndarray(np.ascontiguousarray(samples), format='fltp', layout='stereo')
frame.sample_rate, frame.pts = RATE, self.pts
self.pts += samples.shape[1]
return [bytes(packet) for packet in self.codec.encode(frame)]
class PipeSource:
"""Non-blocking reader of the Spotify pipe; reopens when the audio server restarts."""
@@ -169,8 +214,12 @@ def pause_music() -> None:
class MediaAudio:
def __init__(self, session, channel: int, config_index: int, source, log: Callable[..., None],
pause: Callable[[], None] = pause_music, clock: Callable[[], float] = time.monotonic):
pause: Callable[[], None] = pause_music, clock: Callable[[], float] = time.monotonic,
codec: int = CODEC_PCM, make_encoder: Callable[[], Any] = AacEncoder):
self.session, self.channel, self.config_index = session, channel, config_index
self.codec, self.make_encoder = codec, make_encoder
self.encoder: Any = None
self.config_slack = 0
self.source, self.log, self.pause, self.clock = source, log, pause, clock
self.state = 'closed' # closed, opening, setup, ready, focus_wait, playing, suspended, unavailable
self.deadline = 0.0
@@ -193,12 +242,15 @@ class MediaAudio:
@classmethod
def create(cls, session, log, *, source=None, routed: Callable[[], bool] = music_routed, **kwargs):
found = media_channel(session.channels)
log('media_audio_offered', channels=offered_audio(session.channels),
chosen=None if found is None else {'channel': found[0], 'config': found[1], 'codec': found[2]})
if found is None:
return None
if source is None:
from openpilot.starpilot.soloist.backend import starport_pipe
source = PipeSource(starport_pipe(), routed)
return cls(session, *found, source, log, **kwargs)
channel, index, codec = found
return cls(session, channel, index, source, log, codec=codec, **kwargs)
def _event(self, name: str, **values) -> None:
self.log(f'media_audio_{name}', channel=self.channel, **values)
@@ -242,6 +294,8 @@ class MediaAudio:
self.session.send(self.channel, MSG_CHANNEL_OPEN_REQUEST, field(1, 0) + field(2, self.channel), control=True)
self._set('opening', STEP_TIMEOUT)
elif self.state == 'ready' and sounding and not self.car_paused and now >= self.retry_at:
if self.codec == CODEC_AAC_LC:
self.encoder = self.make_encoder()
self.session.send(0, AUDIO_FOCUS_REQUEST, field(1, FOCUS_GAIN))
self._set('focus_wait', STEP_TIMEOUT)
elif self.state == 'playing':
@@ -270,20 +324,35 @@ class MediaAudio:
self._event('ack_stall', pending=self.unacked)
self._give_back('ack_stall')
return
if self.codec == CODEC_AAC_LC:
self._send_aac(now)
return
sent = 0
while self.unacked < self.window and len(self.buffer) >= MIN_CHUNK and sent < 2:
size = min(len(self.buffer), MAX_CHUNK)
size -= size % FRAME_BYTES
chunk = bytes(self.buffer[:size])
del self.buffer[:size]
timestamp = self.base_us + self.frames_sent * 1_000_000 // RATE
self.session.send(self.channel, AV_MEDIA_WITH_TIMESTAMP, struct.pack('>Q', timestamp) + chunk)
self.frames_sent += size // FRAME_BYTES
self.unacked += 1
self.pending.append(now)
self.stats['chunks_sent'] += 1
self._emit(now, chunk, size // FRAME_BYTES)
sent += 1
def _send_aac(self, now: float) -> None:
sent = 0
while self.unacked < self.window and len(self.buffer) >= AAC_FRAME_BYTES and sent < AAC_PER_PASS:
pcm = bytes(self.buffer[:AAC_FRAME_BYTES])
del self.buffer[:AAC_FRAME_BYTES]
for unit in self.encoder.encode(pcm):
self._emit(now, unit, AAC_FRAME_BYTES // FRAME_BYTES)
sent += 1
def _emit(self, now: float, payload: bytes, frames: int) -> None:
timestamp = self.base_us + self.frames_sent * 1_000_000 // RATE
self.session.send(self.channel, AV_MEDIA_WITH_TIMESTAMP, struct.pack('>Q', timestamp) + payload)
self.frames_sent += frames
self.unacked += 1
self.pending.append(now)
self.stats['chunks_sent'] += 1
def _timeout(self, now: float) -> None:
state = self.state
self.deadline = 0.0
@@ -317,7 +386,7 @@ class MediaAudio:
self._event('open_rejected', status=signed(one(fields, 1)))
self._set('unavailable')
else:
self.session.send(self.channel, AV_SETUP_REQUEST, field(1, CODEC_PCM))
self.session.send(self.channel, AV_SETUP_REQUEST, field(1, self.codec))
self._set('setup', STEP_TIMEOUT)
elif kind == AV_SETUP_RESPONSE and self.state == 'setup':
window, configs = int(one(fields, 2, 0) or 0), fields.get(3, [])
@@ -330,6 +399,10 @@ class MediaAudio:
self._set('ready')
elif kind == AV_MEDIA_ACK:
count = int(one(fields, 2, 0) or 0)
excess = count - self.unacked
if one(fields, 1) == self.session_id and 0 < excess <= self.config_slack:
self.config_slack -= excess # the codec config was acknowledged like a frame
count -= excess
if one(fields, 1) == self.session_id and 0 < count <= self.unacked:
self.unacked -= count
del self.pending[:count]
@@ -341,9 +414,12 @@ class MediaAudio:
self._event('focus', focus=focus, unsolicited=unsolicited)
if focus in GAINED and self.state in ('focus_wait', 'suspended'):
self.session_id += 1
self.unacked, self.pending, self.frames_sent = 0, [], 0
self.unacked, self.pending, self.frames_sent, self.config_slack = 0, [], 0, 0
self.base_us = time.monotonic_ns() // 1000
self.session.send(self.channel, AV_START_INDICATION, field(1, self.session_id) + field(2, self.config_index))
if self.encoder is not None and self.encoder.config:
self.session.send(self.channel, AV_MEDIA_CODEC_CONFIG, self.encoder.config)
self.config_slack = 1
self._set('playing')
elif focus == STATE_LOSS_TRANSIENT and self.state == 'playing':
self.session.send(self.channel, AV_STOP_INDICATION)
@@ -19,7 +19,7 @@ SILENCE = b'\x00' * len(TONE)
class Session:
def __init__(self):
self.channels = CIVIC
self.channels: list[dict] = CIVIC
self.sent = []
def send(self, channel, kind, body=b'', control=False):
self.sent.append((channel, kind, body))
@@ -64,9 +64,96 @@ def play(stream, session, source, now):
assert session.sent[-1] == (4, ma.AV_START_INDICATION, field(1, 1) + field(2, 0))
def test_media_channel_picks_pcm_media_not_guidance_or_aac():
assert ma.media_channel(CIVIC) == (4, 0)
assert ma.media_channel([c for c in CIVIC if c['id'] != 4]) is None
# A 2022 CR-V's DUDUAUTO head unit: media only as AAC-LC, guidance/system as PCM.
DUDUAUTO = [
{'id': 4, 'media_type': 2, 'audio_type': 3, 'audio_configs': [{1: [48000], 2: [16], 3: [2]}]},
{'id': 5, 'media_type': 1, 'audio_type': 1, 'audio_configs': [{1: [16000], 2: [16], 3: [1]}]},
{'id': 6, 'media_type': 1, 'audio_type': 2, 'audio_configs': [{1: [16000], 2: [16], 3: [1]}]},
{'id': 15, 'media_type': None},
]
class Encoder:
config = b'\x11\x90'
def encode(self, pcm):
assert len(pcm) == ma.AAC_FRAME_BYTES
return [b'au%d' % len(pcm)]
def test_media_channel_prefers_pcm_and_falls_back_to_aac():
assert ma.media_channel(CIVIC) == (4, 0, ma.CODEC_PCM)
assert ma.media_channel([c for c in CIVIC if c['id'] != 4]) == (18, 0, ma.CODEC_AAC_LC)
assert ma.media_channel(DUDUAUTO) == (4, 0, ma.CODEC_AAC_LC)
assert ma.media_channel([c for c in CIVIC if c['id'] not in (4, 18)]) is None
def test_create_logs_what_the_car_offered():
logs, session = [], Session()
def record(name, **values):
logs.append((name, values))
assert ma.MediaAudio.create(session, record, source=Source()).codec == ma.CODEC_PCM
assert logs[-1][0] == 'media_audio_offered' and logs[-1][1]['chosen'] == {'channel': 4, 'config': 0, 'codec': 1}
assert {'id': 18, 'media_type': 2, 'audio_type': 3, 'configs': [[48000, 16, 2]]} in logs[-1][1]['channels']
session.channels = DUDUAUTO
assert ma.MediaAudio.create(session, record, source=Source()).codec == ma.CODEC_AAC_LC
assert logs[-1][1]['chosen']['codec'] == ma.CODEC_AAC_LC
session.channels = [c for c in DUDUAUTO if c['id'] != 4]
assert ma.MediaAudio.create(session, record, source=Source()) is None
assert logs[-1][1]['chosen'] is None and len(logs[-1][1]['channels']) == 2
def aac_stream(make_encoder=Encoder, window=4):
session, source, now = Session(), Source(), [100.0]
session.channels = DUDUAUTO
stream = ma.MediaAudio(session, 4, 0, source, lambda *a, **k: None, clock=lambda: now[0],
codec=ma.CODEC_AAC_LC, make_encoder=make_encoder)
stream.service()
stream.handle(4, ma.MSG_CHANNEL_OPEN_RESPONSE, {1: [0]})
assert parse_fields(session.sent[-1][2]) == {1: [ma.CODEC_AAC_LC]}
stream.handle(4, ma.AV_SETUP_RESPONSE, {1: [2], 2: [window], 3: [0]})
source.data += TONE
return stream, session
def test_aac_sends_config_then_one_frame_per_message():
stream, session = aac_stream()
stream.service()
stream.handle(0, ma.AUDIO_FOCUS_NOTIFICATION, {1: [ma.STATE_GAIN]})
assert session.sent[-1] == (4, ma.AV_MEDIA_CODEC_CONFIG, b'\x11\x90')
stream.service()
media = [body for _, kind, body in session.sent if kind == ma.AV_MEDIA_WITH_TIMESTAMP]
assert len(media) == 4 # window of 4
stamps = [struct.unpack('>Q', body[:8])[0] - stream.base_us for body in media]
assert stamps == [0, 21333, 42666, 64000] and media[0][8:] == b'au4096'
stream.handle(4, ma.AV_MEDIA_ACK, {1: [1], 2: [5]}) # the car counted the codec config too
assert stream.unacked == 0 and stream.config_slack == 0 and stream.status()['acked'] == 4
def test_aac_frame_acks_work_when_the_config_is_not_acknowledged():
stream, session = aac_stream()
stream.service()
stream.handle(0, ma.AUDIO_FOCUS_NOTIFICATION, {1: [ma.STATE_GAIN]})
stream.service()
stream.handle(4, ma.AV_MEDIA_ACK, {1: [1], 2: [4]})
assert stream.unacked == 0 and stream.config_slack == 1 and stream.status()['acked'] == 4
def test_aac_encoder_failure_raises_before_asking_for_focus():
def broken():
raise RuntimeError('No aac encoder available')
stream, session = aac_stream(broken)
with pytest.raises(RuntimeError):
stream.service()
assert (0, ma.AUDIO_FOCUS_REQUEST) not in session.kinds()
def test_real_aac_encoder_makes_raw_lc_frames():
pytest.importorskip('av')
encoder = ma.AacEncoder()
assert encoder.config == b'\x11\x90' # AAC-LC, 48 kHz, stereo
units = [u for _ in range(4) for u in encoder.encode(TONE[:ma.AAC_FRAME_BYTES])]
assert units and all(u[:2] != b'\xff\xf1' for u in units) # no ADTS header
def test_stays_closed_until_spotify_is_routed(audio):