From ef7360c69d178c34e022110a3c94afa68604dd14 Mon Sep 17 00:00:00 2001 From: mbalous Date: Tue, 24 Nov 2026 18:16:29 +0100 Subject: [PATCH 01/10] feat: add experimental USB Android Auto audio Add direct USB playback, native route ownership, and Bluetooth fallback. The candidate audio routes require verification on the target head unit. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- Makefile | 8 +- core/aa_channels.cpp | 69 ++++++- core/aa_session.cpp | 89 ++++++++- core/aa_session.hpp | 28 ++- core/sdr_builder.cpp | 10 +- core/sdr_builder.hpp | 2 +- docs/USB.md | 21 ++- platform/audio_mixer.hpp | 130 +++++++++++++ platform/audio_output.cpp | 137 ++++++++++++++ platform/audio_output.hpp | 43 +++++ platform/audio_player.cpp | 302 ++++++++++++++++++++++++++++++ platform/audio_player.hpp | 58 ++++++ platform/audio_probe.cpp | 114 +++++++++++ platform/audio_probe.hpp | 19 ++ platform/audio_route.cpp | 283 ++++++++++++++++++++++++++++ platform/audio_route.hpp | 71 +++++++ platform/evo_knob.cpp | 12 +- platform/main.cpp | 14 +- platform/service_app.cpp | 81 ++++++++ platform/service_app.hpp | 8 +- platform/service_contract.hpp | 2 + platform/vmost_client.hpp | 35 ++++ tests/fake_audio_output.c | 106 +++++++++++ tests/fake_vmostclient.c | 5 + tests/host.mk | 23 ++- tests/test_audio_mixer.cpp | 42 +++++ tests/test_audio_output.cpp | 41 ++++ tests/test_audio_player.cpp | 58 ++++++ tests/test_audio_probe.cpp | 72 +++++++ tests/test_audio_route.cpp | 188 +++++++++++++++++++ tests/test_evo_sdr.cpp | 9 + tests/test_routed_audio.cpp | 152 +++++++++++++++ tests/test_session_phone.cpp | 140 +++++++++++++- tests/test_wireless_lifecycle.cpp | 159 ++++++++++++++++ tools/evo_check.cpp | 20 +- 35 files changed, 2521 insertions(+), 30 deletions(-) create mode 100644 platform/audio_mixer.hpp create mode 100644 platform/audio_output.cpp create mode 100644 platform/audio_output.hpp create mode 100644 platform/audio_player.cpp create mode 100644 platform/audio_player.hpp create mode 100644 platform/audio_probe.cpp create mode 100644 platform/audio_probe.hpp create mode 100644 platform/audio_route.cpp create mode 100644 platform/audio_route.hpp create mode 100644 tests/fake_audio_output.c create mode 100644 tests/test_audio_mixer.cpp create mode 100644 tests/test_audio_output.cpp create mode 100644 tests/test_audio_player.cpp create mode 100644 tests/test_audio_probe.cpp create mode 100644 tests/test_audio_route.cpp create mode 100644 tests/test_routed_audio.cpp diff --git a/Makefile b/Makefile index 2ac52af..5da4740 100644 --- a/Makefile +++ b/Makefile @@ -45,6 +45,7 @@ USB_OBJ = $(USB_SRC:.cpp=.o) DAEMON_SRC = platform/alps_spp.cpp platform/alps_spp_codec.cpp platform/evo_ap.cpp \ platform/evo_ap_config.cpp platform/evo_spp_snapshot.cpp platform/evo_touch.cpp platform/evo_knob.cpp \ platform/vmost_client.cpp platform/evo_control.cpp platform/evo_sdr_sensors.cpp platform/evo_mic.cpp \ + platform/audio_output.cpp platform/audio_player.cpp platform/audio_route.cpp \ $(KOMBI_SRC) platform/evo_bmw_guidance.cpp platform/evo_pill.cpp \ platform/peek_timing.cpp platform/wireless_loop.cpp platform/service_app.cpp platform/main.cpp \ platform/wifi_link.cpp $(USB_SRC) @@ -53,13 +54,14 @@ SUPERVISOR_OBJ = tools/aa_supervisor.o platform/evo_spp_snapshot.o platform/alps platform/evo_ilm.o platform/evo_process.o platform/evo_ap.o platform/evo_ap_config.o platform/evo_wlan.o \ platform/evo_reboot.o platform/vmost_client.o platform/usb_accessory.o platform/log_copy.o \ platform/update_package.o platform/update_install.o platform/update_car.o -CHECK_OBJ = tools/evo_check.o platform/alps_spp.o platform/alps_spp_codec.o platform/evo_process.o +CHECK_OBJ = tools/evo_check.o platform/alps_spp.o platform/alps_spp_codec.o platform/evo_process.o \ + platform/audio_probe.o platform/vmost_client.o CAPTURE_OBJ = tools/evo_capture.o ARM_OBJ = $(sort $(DAEMON_OBJ) $(PLATFORM_OBJ) $(SUPERVISOR_OBJ) $(CHECK_OBJ) $(CAPTURE_OBJ)) # The service's modules tests/test_wireless_lifecycle.cpp links around its fake Alps link and handshake. LIFECYCLE_OBJ = $(PLATFORM_OBJ) platform/evo_touch.o platform/evo_knob.o platform/vmost_client.o platform/evo_control.o \ platform/evo_mic.o platform/evo_pill.o $(KOMBI_OBJ) platform/evo_bmw_guidance.o platform/peek_timing.o \ - platform/wifi_link.o $(USB_OBJ) + platform/wifi_link.o platform/audio_output.o platform/audio_player.o platform/audio_route.o $(USB_OBJ) VIDEO_LIBS = -l:libxsvideo.so.4 -l:libdrm_omap.so.1 -l:libdrm.so.2 -lpthread -lrt @@ -127,7 +129,7 @@ sdk-link-check: hmiapp/libEntryAad.so # Read-only diagnostics, run by hand on the car; neither is part of a release. dev-tools: evo-check evo-capture evo-check: $(CHECK_OBJ) - $(CXX) $(CXXFLAGS) -o $@ $^ $(HARDEN_LDFLAGS) $(LDSHLIB) -l:libdbus-1.so.3 -lpthread -lrt + $(CXX) $(CXXFLAGS) -o $@ $^ $(HARDEN_LDFLAGS) $(LDSHLIB) -l:libdbus-1.so.3 -lpthread -lrt -ldl # Passive SOME/IP recorder (tools/evo_capture.cpp: receive only, nothing sent). evo-capture: $(CAPTURE_OBJ) $(CXX) $(CXXFLAGS) -o $@ $^ $(HARDEN_LDFLAGS) $(LDSHLIB) -lrt diff --git a/core/aa_channels.cpp b/core/aa_channels.cpp index 14563c3..18ddf87 100644 --- a/core/aa_channels.cpp +++ b/core/aa_channels.cpp @@ -2,11 +2,13 @@ // SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 // The session's message handlers, one per route of core/aa_protocol.hpp, grouped by channel. #include +#include #include "aa_protocol.hpp" #include "aa_session.hpp" #include "crash_handler.hpp" #include "dhu_sdp.h" +#include "pb.hpp" #include "sdr_builder.hpp" namespace aa { @@ -39,6 +41,21 @@ size_t bodySize(const Message& message) { return message.size() > kMessageIdSize ? message.size() - kMessageIdSize : 0; } +bool audioStartFields(const Message& message, uint32_t& session, uint32_t& config) { + session = config = 0; + pb::FieldReader reader(bodyOf(message), bodySize(message)); + pb::Field field; + while (reader.next(field)) { + if (field.number == 1 || field.number == 2) { + if (field.type != pb::kVarint || field.value > std::numeric_limits::max()) { + return false; + } + (field.number == 1 ? session : config) = static_cast(field.value); + } + } + return !reader.malformed(); +} + } // namespace bool AASession::dispatch(uint8_t channel, const Message& message) { @@ -71,6 +88,7 @@ bool AASession::dispatch(uint8_t channel, const Message& message) { break; case Route::kAudioStop: printf("[AASession] >>> Received AV STOP_INDICATION on Channel %u.\n", channel); + stopAudio(channel); break; case Route::kInputBinding: onInputBinding(channel); @@ -193,7 +211,7 @@ void AASession::onDiscovery() { printf("[AASession] >>> Received ServiceDiscoveryRequest from phone! Sending ServiceDiscoveryResponse...\n"); const Message response = message::discoveryResponse( buildCarServiceDiscovery(kDhuSdpProtobuf, kDhuSdpProtobufLen, vehicleFile_, softwareVersion_, display_, - carMake_, codedSide_, codedModel_)); + carMake_, codedSide_, codedModel_, audioData_.fn != nullptr)); if (sendSealed(channel::kControl, response)) { printf("[AASession] >>> Sent ServiceDiscoveryResponse (%u bytes)\n", static_cast(response.size())); } @@ -285,12 +303,39 @@ void AASession::onSetup(uint8_t channel) { // stream stopped and started again (guidance, Assistant) gets a new one, and acks with 0 then fill the phone's window // of unacked messages: the stream stalls. void AASession::onStart(uint8_t channel, const Message& message) { + if (channel::isAudioSink(channel) && audioStream_.fn) { + stopAudio(channel); + } const uint32_t session = bodyField(message, 1); if (session != kNoField) { mediaSessions_[channel] = session; } printf("[AASession] >>> AV START_INDICATION on Channel %u (session %u)\n", channel, session == kNoField ? 0u : session); + if (channel::isAudioSink(channel) && audioStream_.fn) { + uint32_t audioSession, config; + if (!audioStartFields(message, audioSession, config) || + config >= (channel == channel::kGuidanceAudio ? 2u : 1u)) { + fprintf(stderr, "[AASession] invalid audio START on channel %u; ending session\n", channel); + audioFailed_.store(true); + giveUp(); + return; + } + const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + mediaSessions_[channel] = audioSession; + audioConfig_[index] = config; + audioActive_[index] = true; + audioStream_.fn(channel, audioSession, config, true, audioStream_.user); + } +} + +void AASession::stopAudio(uint8_t channel) { + flushAudioAcks(channel); + const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + if (audioActive_[index]) { + audioActive_[index] = false; + audioStream_.fn(channel, mediaSessions_[channel], audioConfig_[index], false, audioStream_.user); + } } // Media of any channel: counted, video handed to the callbacks, everything acked. The phone counts each media message @@ -298,14 +343,15 @@ void AASession::onStart(uint8_t channel, const Message& message) { // short to hold a picture is acked too, or it would hold a slot of that window for the rest of the session. void AASession::onMedia(uint8_t channel, uint16_t id, const Message& message) { ++mediaMessages_; + bool deferredAck = false; if (mediaMessages_ % kMediaLogEvery == 1) { printf("[AASession] >>> Streaming Media Frame %u on Channel %u (%u bytes)\n", mediaMessages_, channel, static_cast(message.size())); } if (channel::isAudioSink(channel) && id == msg::kMediaData) { - // Sound plays over the car's Bluetooth: phone audio is only counted (8-byte timestamp, then s16le PCM). if (message.size() > kTimestampedHeader) { - uint32_t& count = audioMessages_[channel == channel::kMediaAudio ? 1 : 0]; + const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + uint32_t& count = audioMessages_[index]; ++count; if (count <= kAudioLoggedFirst || count % kAudioLogEvery == 0) { printf("[AASession] audio %s frame #%u: %u bytes PCM, pts=%llu\n", @@ -313,6 +359,19 @@ void AASession::onMedia(uint8_t channel, uint16_t id, const Message& message) { static_cast(message.size() - kTimestampedHeader), static_cast(bigEndian64(&message[kMessageIdSize]))); } + const size_t pcmSize = message.size() - kTimestampedHeader; + const size_t frameSize = index == 1 ? 4 : 2; + if (audioData_.fn && audioActive_[index]) { + if (pcmSize % frameSize == 0) { + audioData_.fn(channel, mediaSessions_[channel], &message[kTimestampedHeader], pcmSize, + bigEndian64(&message[kMessageIdSize]), audioData_.user); + const uint32_t rate = index == 1 || audioConfig_[index] == 1 ? 48000 : 16000; + deferAudioAck(channel, mediaSessions_[channel], pcmSize, rate); + deferredAck = true; + } else { + fprintf(stderr, "[AASession] dropping unaligned audio frame on channel %u\n", channel); + } + } } } else if (channel == channel::kVideo) { // Cut at the protocol's offsets, never by scanning: a timestamp can hold 00 00 01 and look like a start code. @@ -336,7 +395,9 @@ void AASession::onMedia(uint8_t channel, uint16_t id, const Message& message) { g_trail.stage = kTrailHandler; } } - sendSealed(channel, message::mediaAck(mediaSessions_[channel])); + if (!deferredAck) { + sendSealed(channel, message::mediaAck(mediaSessions_[channel])); + } } // A message the phone sent on one of its streams, but lost on the way (a fragment that did not decrypt, a reassembly diff --git a/core/aa_session.cpp b/core/aa_session.cpp index 0944da9..0cff610 100644 --- a/core/aa_session.cpp +++ b/core/aa_session.cpp @@ -80,6 +80,7 @@ AASession::AASession() codedModel_(nullptr), longestSilenceMs_(0), goodbye_(false), + audioFailed_(false), lastReceivedMs_(0), connectedMs_(0), givenUp_(false), @@ -96,6 +97,8 @@ AASession::AASession() pthread_mutex_init(&socketLock_, nullptr); memset(mediaSessions_, 0, sizeof(mediaSessions_)); audioMessages_[0] = audioMessages_[1] = 0; + audioActive_[0] = audioActive_[1] = false; + audioConfig_[0] = audioConfig_[1] = 0; resetCounters(); } @@ -135,6 +138,18 @@ void AASession::setNavStatusCallback(NavStatusCallback cb, void* user_data) { navigation_.user = user_data; } +bool AASession::setAudioCallbacks(AudioDataCallback data, AudioStreamCallback stream, void* user_data) { + if ((data == nullptr) != (stream == nullptr)) { + fprintf(stderr, "[AASession] direct audio needs both callbacks\n"); + return false; + } + audioData_.fn = data; + audioData_.user = user_data; + audioStream_.fn = stream; + audioStream_.user = user_data; + return true; +} + void AASession::postTouchEvent(const TouchEventOut& ev) { inbox_.postTouch(ev); } @@ -254,6 +269,8 @@ bool AASession::start(int client_fd) { mediaMessages_ = 0; memset(mediaSessions_, 0, sizeof(mediaSessions_)); audioMessages_[0] = audioMessages_[1] = 0; + audioAcks_[0].clear(); + audioAcks_[1].clear(); lastReceivedMs_ = 0; // the previous thread is joined givenUp_ = false; versionTaken_ = false; @@ -263,6 +280,7 @@ bool AASession::start(int client_fd) { txFrame_.clear(); longestSilenceMs_.store(0); goodbye_.store(false); // after the ended callback of a session replaced above + audioFailed_.store(false); resetCounters(); setRunning(true); if (pthread_create(&thread_, nullptr, &AASession::threadMain, this) != 0) { @@ -334,6 +352,10 @@ void AASession::run() { void AASession::finish() { inbox_.stopLocation(); + audioAcks_[0].clear(); + audioAcks_[1].clear(); + stopAudio(channel::kGuidanceAudio); + stopAudio(channel::kMediaAudio); // This thread alone closes the socket, whether the session ended by itself or stop() asked; the ended callback // runs only in the first case. const bool endedByItself = clearRunning(); @@ -353,6 +375,11 @@ bool AASession::receiveExactly(uint8_t* to, size_t size) { const int wakeFd = inbox_.wakeFd(); // The car input and our pings are sent from this loop: a send that fails there ends it too. while (got < size && running() && !sendBroken_) { + const uint64_t nowUs = monotonicUs(); + sendDueAudioAcks(nowUs); + if (sendBroken_) { + return false; + } // Checked at every turn, data or not: bytes that trickle in keep the silence from ever counting. if (!tls_.established() && locationClockMs() - connectedMs_ >= kTlsDeadlineMs) { printf("[AASession] TLS still not established %u s after the connection: session ends.\n", @@ -390,7 +417,8 @@ bool AASession::receiveExactly(uint8_t* to, size_t size) { fds[1].revents = 0; nfds = 2; } - const int ready = poll(fds, nfds, 1000); + const uint64_t delayUs = audioAckWaitUs(nowUs); + const int ready = poll(fds, nfds, static_cast((delayUs + 999) / 1000)); if (ready < 0) { if (errno == EINTR) { continue; @@ -444,6 +472,65 @@ bool AASession::receiveExactly(uint8_t* to, size_t size) { return got == size; } +void AASession::deferAudioAck(uint8_t channel, uint32_t session, size_t pcmBytes, uint32_t sampleRate) { + const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + std::deque& queue = audioAcks_[index]; + if (queue.size() >= kMaxUnacked) { + sendSealed(channel, message::mediaAck(queue.front().session)); + queue.pop_front(); + } + const uint64_t now = monotonicUs(); + const uint64_t start = !queue.empty() && queue.back().dueUs > now ? queue.back().dueUs : now; + const size_t frameBytes = index ? 4 : 2; + uint64_t duration = static_cast(pcmBytes / frameBytes) * 1000000ULL / sampleRate; + if (duration > 500000) { + duration = 500000; // the player retains at most 500 ms of any oversized frame + } + const AudioAck ack = {session, start + duration}; + queue.push_back(ack); +} + +void AASession::sendDueAudioAcks(uint64_t nowUs) { + for (unsigned index = 0; index < 2; ++index) { + std::deque& queue = audioAcks_[index]; + const uint8_t channel = index ? channel::kMediaAudio : channel::kGuidanceAudio; + while (!queue.empty() && queue.front().dueUs <= nowUs) { + const uint32_t session = queue.front().session; + queue.pop_front(); + if (!sendSealed(channel, message::mediaAck(session))) { + return; + } + } + } +} + +void AASession::flushAudioAcks(uint8_t channel) { + const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + std::deque& queue = audioAcks_[index]; + while (!queue.empty()) { + const uint32_t session = queue.front().session; + queue.pop_front(); + if (running() && !sendSealed(channel, message::mediaAck(session))) { + queue.clear(); + break; + } + } +} + +uint64_t AASession::audioAckWaitUs(uint64_t nowUs) const { + uint64_t delay = 1000000; + for (unsigned index = 0; index < 2; ++index) { + if (!audioAcks_[index].empty()) { + const uint64_t due = audioAcks_[index].front().dueUs; + const uint64_t left = due > nowUs ? due - nowUs : 0; + if (left < delay) { + delay = left; + } + } + } + return delay; +} + // A frame that did not go out whole breaks the stream for good: the phone reads the next frame as the rest of this one, // and a sealed frame moved the TLS sequence on even when none of it left. Most callers cannot do anything about a // failure, so the first one ends the session here, as lost rather than a goodbye (the service then calls the phone diff --git a/core/aa_session.hpp b/core/aa_session.hpp index 4a498d2..e0a37b1 100644 --- a/core/aa_session.hpp +++ b/core/aa_session.hpp @@ -9,6 +9,7 @@ #include #include +#include #include "aa_frame.hpp" #include "aa_input.hpp" @@ -35,6 +36,10 @@ using VideoFocusCallback = void (*)(bool, uint32_t, void*); using MicRequestCallback = void (*)(bool, void*); // Navigation status (channel 10, ids from 0x8000): the message id, then its body. using NavStatusCallback = void (*)(uint16_t, const uint8_t*, size_t, void*); +// PCM and stream lifecycle on the session thread. The receiver must copy data and return without blocking. +// Channel 8: mono S16LE, config 0 = 16 kHz, 1 = 48 kHz. Channel 9: stereo S16LE, config 0 = 48 kHz. +using AudioDataCallback = void (*)(uint8_t, uint32_t, const uint8_t*, size_t, uint64_t, void*); +using AudioStreamCallback = void (*)(uint8_t, uint32_t, uint32_t, bool, void*); class AASession { public: @@ -53,10 +58,13 @@ class AASession { // The phone ended this session with ByeBye (the user left Android Auto), rather than going silent or breaking the // connection. Read by the ended callback; reset by start(). bool phoneSaidGoodbye() const { return goodbye_.load(); } + bool audioFailed() const { return audioFailed_.load(); } // The car gives the session up, as when the phone is gone (its video decoder stalled). From a callback on the // session thread only: the session ends once that callback returns, its ended callback runs, and // phoneSaidGoodbye() stays false. void giveUp() { givenUp_ = true; } + // From any thread: interrupt the current connection and run the normal lost-session callback. + void requestDisconnect() { interrupt(); } // Set before start(). void setDisconnectCallback(SessionEndedCallback cb, void* user_data = nullptr); @@ -65,6 +73,9 @@ class AASession { void setVideoFocusCallback(VideoFocusCallback cb, void* user_data = nullptr); void setMicRequestCallback(MicRequestCallback cb, void* user_data = nullptr); void setNavStatusCallback(NavStatusCallback cb, void* user_data = nullptr); + // Both callbacks enable direct audio discovery; both null restore Bluetooth discovery. Set before start(). + // False when only one callback is provided; the previous setting remains unchanged. + bool setAudioCallbacks(AudioDataCallback data, AudioStreamCallback stream, void* user_data = nullptr); void setTouchForwarding(bool on) { inbox_.setTouchForwarding(on); } // on by default; keys go either way // The file holding the car's model, year, side and fuel (SdrIdentity::loadVehicleFile), read at each service // discovery; kept as given, so it must outlive the session. None by default: the default car. @@ -150,6 +161,11 @@ class AASession { void onSensorStart(uint8_t channel, const Message& message); void onSetup(uint8_t channel); void onStart(uint8_t channel, const Message& message); + void stopAudio(uint8_t channel); + void deferAudioAck(uint8_t channel, uint32_t session, size_t pcmBytes, uint32_t sampleRate); + void sendDueAudioAcks(uint64_t nowUs); + void flushAudioAcks(uint8_t channel); + uint64_t audioAckWaitUs(uint64_t nowUs) const; void onMedia(uint8_t channel, uint16_t id, const Message& message); void ackDropped(const FrameHeader& header); // a frame dropped or skipped: the media message it closes void onVideoFocusRequest(uint8_t channel, const Message& message); @@ -170,6 +186,8 @@ class AASession { Callback focus_; Callback microphone_; Callback navigation_; + Callback audioData_; + Callback audioStream_; const char* vehicleFile_; const char* softwareVersion_; const char* carMake_; @@ -180,6 +198,7 @@ class AASession { CarInbox inbox_; std::atomic longestSilenceMs_; std::atomic goodbye_; // set on the session thread, read by the ended callback + std::atomic audioFailed_; // Session thread only. uint64_t lastReceivedMs_; // when the phone last sent anything, 0 before its first byte uint64_t connectedMs_; // when the session thread started on this connection @@ -194,7 +213,14 @@ class AASession { uint32_t mediaSessions_[256]; // per channel, the session id of its start indication, echoed in our acks uint32_t mediaMessages_; // media messages received, every channel uint32_t audioMessages_[2]; // guidance (8), media (9) - uint32_t microphoneChunks_; // sent since the phone opened the microphone + bool audioActive_[2]; + uint32_t audioConfig_[2]; + struct AudioAck { + uint32_t session; + uint64_t dueUs; + }; + std::deque audioAcks_[2]; + uint32_t microphoneChunks_; // sent since the phone opened the microphone // Log throttles, per session. unsigned framesSeen_[256]; unsigned keysLogged_, movesLogged_, navigationLogged_, pings_; diff --git a/core/sdr_builder.cpp b/core/sdr_builder.cpp index e67f21a..23e0871 100644 --- a/core/sdr_builder.cpp +++ b/core/sdr_builder.cpp @@ -379,7 +379,7 @@ void setDiscoveryTrim(DiscoveryTrim trim) { std::vector buildCarServiceDiscovery(const uint8_t* base, size_t baseLen, const char* vehicleFile, const char* softwareVersion, const DisplayPlan& display, const char* make, - DriverPosition codedSide, const char* codedModel) { + DriverPosition codedSide, const char* codedModel, bool directAudio) { SdrIdentity identity; identity.driverPosition = codedSide; // before the file, whose "side=" and "model=" win if (codedModel && validCarModel(codedModel)) { @@ -401,11 +401,15 @@ std::vector buildCarServiceDiscovery(const uint8_t* base, size_t baseLe declareFuel(sdr, identity.fuel); tuneMainDisplay(sdr, display); declareTouchscreen(sdr, display); - removeMediaChannel(sdr); + if (!directAudio) { + removeMediaChannel(sdr); + } if (g_trim) { g_trim(sdr); } - retypeGuidanceSink(sdr); + if (!directAudio) { + retypeGuidanceSink(sdr); + } return sdr; } diff --git a/core/sdr_builder.hpp b/core/sdr_builder.hpp index 3e7568f..ea0941f 100644 --- a/core/sdr_builder.hpp +++ b/core/sdr_builder.hpp @@ -75,7 +75,7 @@ std::vector buildCarServiceDiscovery(const uint8_t* base, size_t baseLe const char* softwareVersion, const DisplayPlan& display = DisplayPlan(), const char* make = nullptr, DriverPosition codedSide = DriverPosition::kLeft, - const char* codedModel = nullptr); + const char* codedModel = nullptr, bool directAudio = false); } // namespace aa diff --git a/docs/USB.md b/docs/USB.md index a4b0a8c..e73a0e3 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -4,8 +4,23 @@ faire d'Android Auto sans fil, ou quand le Wi-Fi de la voiture rame. L'état des essais est dans le [journal des versions](../CHANGELOG.md). -Avec le câble, l'image, les commandes, le micro, le GPS et le guidage passent par l'USB. **Le son reste sur le -Bluetooth de la voiture**, comme en sans fil : le téléphone doit donc rester appairé à la voiture. +Avec le câble, l'image, les commandes, le micro, le GPS et le guidage passent par l'USB. Le service essaie aussi le +son direct par USB (musique et annonces), sans modifier les appels ni le micro. Il utilise les sorties +`entertainment` et `carplay_alt` et les routes audio observées sur un autre EntryNav2. + +**Le son direct n'a pas encore été vérifié en voiture sur cette version.** Si les sorties ou la lecture de la table +des routes ne sont pas disponibles, le service conserve le son Bluetooth. En cas d'erreur pendant une session directe, +il la relance en Bluetooth et conserve ce choix jusqu'à l'arrêt du service. Le service ne vérifie pas si le téléphone +est connecté en Bluetooth : vérifier la connexion média en cas de repli. Si la libération de la route audio ne peut pas +être confirmée, une nouvelle session est refusée plutôt que de risquer un conflit avec le son de la voiture. + +Pour forcer le Bluetooth dès le départ, Android Auto arrêté, créer `/var/local/data/AA/usb-bluetooth-audio` ; retirer +ce fichier pour réessayer le son direct au prochain démarrage. Le sans-fil garde son comportement Bluetooth actuel. + +L'outil de développement `evo-check --audio-routes` lit la table des connexions audio sans construire ni supprimer de +route ; `evo-check --context` relève notamment la configuration ALSA et la version du système. Ces relevés ne prouvent +pas qu'une route soit utilisable. Le contexte contient aussi des informations réseau : les retirer avant de partager +sa sortie. ## Choisir le câble ou le sans-fil @@ -70,5 +85,5 @@ case du menu retire le fichier, nom de prise compris : il est à réécrire ensu |---|---| | Rien ne se passe au branchement | Câble de données et non de charge seule. Sur le téléphone, choisir « Transfert de fichiers » dans la notification USB, puis rebrancher. | | Le téléphone affiche Android Auto mais pas l'iDrive | Débrancher, attendre 10 secondes, rebrancher. | -| Pas de son | Le son passe par le Bluetooth : vérifier que le téléphone est connecté à la voiture. | +| Pas de son | Forcer le Bluetooth avec `usb-bluetooth-audio`, redémarrer Android Auto et vérifier que le téléphone est connecté à la voiture en média. | | Toujours rien | Activer les journaux ([maintenance](MAINTENANCE.md)), reproduire, et joindre le journal du service à un ticket : les lignes `[UsbLoop]` et `[UsbBridge]` disent ce qui a été vu sur les prises. | diff --git a/platform/audio_mixer.hpp b/platform/audio_mixer.hpp new file mode 100644 index 0000000..d360d1d --- /dev/null +++ b/platform/audio_mixer.hpp @@ -0,0 +1,130 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +// Bounded 48 kHz stereo output from the Android Auto media and mono speech streams. +#ifndef ENTRY_AAD_PLATFORM_AUDIO_MIXER_HPP +#define ENTRY_AAD_PLATFORM_AUDIO_MIXER_HPP + +#include +#include + +#include + +namespace evo { + +// The caller serializes access. No pointers to input data are retained. +class AudioMixer { +public: + static const size_t kCapacityFrames = 24000; // 500 ms at 48 kHz + + AudioMixer() : media_(kCapacityFrames, 2), speech_(kCapacityFrames, 1) {} + + void clearMedia() { media_.clear(); } + void clearSpeech() { speech_.clear(); } + size_t mediaFrames() const { return media_.size(); } + size_t speechFrames() const { return speech_.size(); } + + // Returns false for malformed PCM or an unsupported speech configuration. A full buffer discards oldest frames. + bool pushMedia(const uint8_t* pcm, size_t bytes) { + if (!pcm || !bytes || bytes % 4) { + return false; + } + if (bytes / 4 > kCapacityFrames) { + pcm += bytes - kCapacityFrames * 4; + bytes = kCapacityFrames * 4; + } + for (size_t i = 0; i < bytes; i += 4) { + media_.push(sample(pcm + i), sample(pcm + i + 2)); + } + return true; + } + + bool pushSpeech(const uint8_t* pcm, size_t bytes, unsigned config) { + if (!pcm || !bytes || bytes % 2 || config > 1) { + return false; + } + const unsigned copies = config == 0 ? 3 : 1; + const size_t maxInputFrames = kCapacityFrames / copies; + if (bytes / 2 > maxInputFrames) { + pcm += bytes - maxInputFrames * 2; + bytes = maxInputFrames * 2; + } + for (size_t i = 0; i < bytes; i += 2) { + const int16_t value = sample(pcm + i); + for (unsigned n = 0; n < copies; ++n) { + speech_.push(value, 0); + } + } + return true; + } + + // Stereo S16 output, at most maxFrames. Speech ducks media to 30%, with clipping after mixing. + size_t read(int16_t* out, size_t maxFrames, bool media = true, bool speech = true) { + if (!out) { + return 0; + } + size_t written = 0; + while (written < maxFrames && ((media && media_.size()) || (speech && speech_.size()))) { + int16_t left = 0, right = 0, voice = 0, unused = 0; + if (media) { + media_.pop(left, right); + } + const bool speaking = speech && speech_.pop(voice, unused); + const int gain = speaking ? 30 : 100; + out[written * 2] = clamp((int(left) * gain) / 100 + voice); + out[written * 2 + 1] = clamp((int(right) * gain) / 100 + voice); + ++written; + } + return written; + } + +private: + class Ring { + public: + Ring(size_t frames, size_t channels) + : data_(frames * channels), channels_(channels), capacity_(frames), head_(0), size_(0) {} + size_t size() const { return size_; } + void clear() { head_ = size_ = 0; } + void push(int16_t left, int16_t right) { + if (size_ == capacity_) { + head_ = (head_ + 1) % capacity_; + --size_; + } + const size_t index = ((head_ + size_) % capacity_) * channels_; + data_[index] = left; + if (channels_ == 2) { + data_[index + 1] = right; + } + ++size_; + } + bool pop(int16_t& left, int16_t& right) { + if (!size_) { + return false; + } + const size_t index = head_ * channels_; + left = data_[index]; + right = channels_ == 2 ? data_[index + 1] : 0; + head_ = (head_ + 1) % capacity_; + --size_; + return true; + } + + private: + std::vector data_; + size_t channels_, capacity_, head_, size_; + }; + + static int16_t sample(const uint8_t* pcm) { + const uint16_t u = static_cast(pcm[0]) | (static_cast(pcm[1]) << 8); + const int32_t signedValue = u < 0x8000 ? u : int32_t(u) - 0x10000; + return static_cast(signedValue); + } + static int16_t clamp(int value) { + return static_cast(value > 32767 ? 32767 : value < -32768 ? -32768 : value); + } + + Ring media_, speech_; +}; + +} // namespace evo + +#endif diff --git a/platform/audio_output.cpp b/platform/audio_output.cpp new file mode 100644 index 0000000..206a251 --- /dev/null +++ b/platform/audio_output.cpp @@ -0,0 +1,137 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include "audio_output.hpp" + +#include +#include + +#include "evo_log.hpp" + +namespace evo { + +AudioOutput::AudioOutput() + : lib_(nullptr), + pcm_(nullptr), + open_(nullptr), + params_(nullptr), + write_(nullptr), + recover_(nullptr), + drop_(nullptr), + prepare_(nullptr), + state_(nullptr), + start_(nullptr), + close_(nullptr), + error_(nullptr) {} + +AudioOutput::~AudioOutput() { + close(); +} + +bool AudioOutput::open(const char* pcm, const char* library, unsigned channels) { + close(); + if (!pcm || !*pcm || !library || !*library || (channels != 1 && channels != 2)) { + ELOG("AudioOutput", "missing PCM or ALSA library name"); + return false; + } + lib_ = dlopen(library, RTLD_NOW | RTLD_LOCAL); + if (!lib_) { + ELOG("AudioOutput", "cannot load ALSA: %s", dlerror()); + return false; + } + *reinterpret_cast(&open_) = dlsym(lib_, "snd_pcm_open"); + *reinterpret_cast(¶ms_) = dlsym(lib_, "snd_pcm_set_params"); + *reinterpret_cast(&write_) = dlsym(lib_, "snd_pcm_writei"); + *reinterpret_cast(&recover_) = dlsym(lib_, "snd_pcm_recover"); + *reinterpret_cast(&drop_) = dlsym(lib_, "snd_pcm_drop"); + *reinterpret_cast(&prepare_) = dlsym(lib_, "snd_pcm_prepare"); + *reinterpret_cast(&state_) = dlsym(lib_, "snd_pcm_state"); + *reinterpret_cast(&start_) = dlsym(lib_, "snd_pcm_start"); + *reinterpret_cast(&close_) = dlsym(lib_, "snd_pcm_close"); + *reinterpret_cast(&error_) = dlsym(lib_, "snd_strerror"); + if (!open_ || !params_ || !write_ || !recover_ || !drop_ || !prepare_ || !state_ || !start_ || !close_ || !error_) { + ELOG("AudioOutput", "ALSA playback functions unavailable"); + close(); + return false; + } + const int err = open_(&pcm_, pcm, 0, 1); // playback, nonblocking + if (err < 0) { + ELOG("AudioOutput", "cannot open %s: %s", pcm, error_(err)); + close(); + return false; + } + const int configured = params_(pcm_, 2, 3, channels, 48000, 1, 100000); // S16LE, interleaved + if (configured < 0) { + ELOG("AudioOutput", "cannot configure %s: %s", pcm, error_(configured)); + close(); + return false; + } + return true; +} + +long AudioOutput::write(const int16_t* samples, size_t frames) { + if (!pcm_ || !samples || !frames) { + ELOG("AudioOutput", "write without an open PCM or samples"); + return -EINVAL; + } + long result = write_(pcm_, samples, static_cast(frames)); + if (result == -EPIPE) { + const int recovered = recover_(pcm_, static_cast(result), 1); + result = recovered < 0 ? recovered : -EAGAIN; + } + if (result > 0 && state_(pcm_) == 2) { // ALSA PREPARED: start short prompts without waiting for a full buffer. + const int started = start_(pcm_); + if (started < 0) { + result = started; + } + } + if (result < 0 && result != -EAGAIN) { + ELOG("AudioOutput", "playback write failed: %s", error_(static_cast(result))); + } + return result; +} + +bool AudioOutput::flush() { + if (!pcm_ || !drop_ || !prepare_) { + ELOG("AudioOutput", "flush without an open PCM"); + return false; + } + const int dropped = drop_(pcm_); + const int prepared = dropped < 0 ? dropped : prepare_(pcm_); + if (prepared < 0) { + ELOG("AudioOutput", "cannot flush PCM: %s", error_(prepared)); + return false; + } + return true; +} + +void AudioOutput::close() { + if (pcm_ && close_) { + if (drop_) { + const int stopped = drop_(pcm_); + if (stopped < 0 && error_) { + ELOG("AudioOutput", "stopping PCM failed: %s", error_(stopped)); + } + } + const int err = close_(pcm_); + if (err < 0 && error_) { + ELOG("AudioOutput", "closing PCM failed: %s", error_(err)); + } + } + pcm_ = nullptr; + if (lib_) { + dlclose(lib_); + lib_ = nullptr; + } + open_ = nullptr; + params_ = nullptr; + write_ = nullptr; + recover_ = nullptr; + drop_ = nullptr; + prepare_ = nullptr; + state_ = nullptr; + start_ = nullptr; + close_ = nullptr; + error_ = nullptr; +} + +} // namespace evo diff --git a/platform/audio_output.hpp b/platform/audio_output.hpp new file mode 100644 index 0000000..b4ce1f4 --- /dev/null +++ b/platform/audio_output.hpp @@ -0,0 +1,43 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +// Nonblocking playback through the head unit's ALSA library; owned by the playback worker. +#ifndef ENTRY_AAD_PLATFORM_AUDIO_OUTPUT_HPP +#define ENTRY_AAD_PLATFORM_AUDIO_OUTPUT_HPP + +#include +#include + +namespace evo { + +class AudioOutput { +public: + AudioOutput(); + ~AudioOutput(); + AudioOutput(const AudioOutput&) = delete; + AudioOutput& operator=(const AudioOutput&) = delete; + + // Load and open an existing PCM, 48 kHz S16LE. The library argument also permits a fake in host tests. + bool open(const char* pcm, const char* library = "libasound.so.2", unsigned channels = 2); + // Returns written frames, -EAGAIN when full, or a negative ALSA error. Handles a recoverable underrun once. + long write(const int16_t* samples, size_t frames); + bool flush(); + void close(); + +private: + void* lib_; + void* pcm_; + int (*open_)(void**, const char*, int, int); + int (*params_)(void*, int, int, unsigned, unsigned, int, unsigned); + long (*write_)(void*, const void*, unsigned long); + int (*recover_)(void*, int, int); + int (*drop_)(void*); + int (*prepare_)(void*); + int (*state_)(void*); + int (*start_)(void*); + int (*close_)(void*); + const char* (*error_)(int); +}; + +} // namespace evo + +#endif diff --git a/platform/audio_player.cpp b/platform/audio_player.cpp new file mode 100644 index 0000000..4b9fcf3 --- /dev/null +++ b/platform/audio_player.cpp @@ -0,0 +1,302 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include "audio_player.hpp" + +#include +#include + +#include "aa_protocol.hpp" +#include "audio_route.hpp" +#include "evo_log.hpp" + +namespace evo { + +AudioPlayer::AudioPlayer() + : route_(nullptr), thread_(0), started_(false), quit_(false), inCall_(false), generation_(0), failure_(0) { + active_[0] = active_[1] = false; + seen_[0] = seen_[1] = false; + sessions_[0] = sessions_[1] = configs_[0] = configs_[1] = 0; + lastData_[0] = lastData_[1] = 0; + pthread_mutex_init(&mu_, nullptr); + pthread_cond_init(&cv_, nullptr); +} + +AudioPlayer::~AudioPlayer() { + stop(); + pthread_cond_destroy(&cv_); + pthread_mutex_destroy(&mu_); +} + +bool AudioPlayer::start(const char* pcm, const char* library) { + if (started_) { + ELOG("AudioPlayer", "already started"); + return false; + } + if (!output_.open(pcm, library)) { + return false; + } + pthread_mutex_lock(&mu_); + route_ = nullptr; + pthread_mutex_unlock(&mu_); + return startWorker(); +} + +bool AudioPlayer::startRouted(AudioRoute& route, const char* mediaPcm, const char* promptPcm, const char* library) { + if (started_) { + ELOG("AudioPlayer", "already started"); + return false; + } + if (!output_.open(mediaPcm, library)) { + return false; + } + if (!promptOutput_.open(promptPcm, library, 1)) { + output_.close(); + return false; + } + pthread_mutex_lock(&mu_); + route_ = &route; + pthread_mutex_unlock(&mu_); + return startWorker(); +} + +bool AudioPlayer::startWorker() { + quit_ = false; + failure_.store(0); + if (pthread_create(&thread_, nullptr, threadMain, this) != 0) { + ELOG("AudioPlayer", "cannot start playback worker"); + output_.close(); + promptOutput_.close(); + pthread_mutex_lock(&mu_); + route_ = nullptr; + pthread_mutex_unlock(&mu_); + return false; + } + started_ = true; + return true; +} + +void AudioPlayer::stop() { + if (!started_) { + return; + } + pthread_mutex_lock(&mu_); + quit_ = true; + pthread_cond_signal(&cv_); + pthread_mutex_unlock(&mu_); + pthread_join(thread_, nullptr); + started_ = false; + pthread_mutex_lock(&mu_); + if (route_) { + route_->request(0); + } + route_ = nullptr; + active_[0] = active_[1] = false; + seen_[0] = seen_[1] = false; + mixer_.clearMedia(); + mixer_.clearSpeech(); + pthread_mutex_unlock(&mu_); + output_.close(); + promptOutput_.close(); +} + +void AudioPlayer::setCall(bool active) { + pthread_mutex_lock(&mu_); + if (inCall_ != active) { + inCall_ = active; + mixer_.clearMedia(); + mixer_.clearSpeech(); + seen_[0] = seen_[1] = false; + ++generation_; + if (active && route_) { + route_->prohibitRestore(); + route_->request(0); + } + pthread_cond_signal(&cv_); + } + pthread_mutex_unlock(&mu_); +} + +void AudioPlayer::stream(uint8_t channel, uint32_t session, uint32_t config, bool started, void* user) { + AudioPlayer* self = static_cast(user); + if (!self || !aa::channel::isAudioSink(channel)) { + ELOG("AudioPlayer", "invalid stream callback"); + return; + } + const unsigned index = channel == aa::channel::kMediaAudio ? 1 : 0; + pthread_mutex_lock(&self->mu_); + self->active_[index] = started; + self->seen_[index] = false; + self->sessions_[index] = session; + self->configs_[index] = config; + if (index) { + self->mixer_.clearMedia(); + } else { + self->mixer_.clearSpeech(); + } + ++self->generation_; + pthread_cond_signal(&self->cv_); + pthread_mutex_unlock(&self->mu_); +} + +void AudioPlayer::data(uint8_t channel, uint32_t session, const uint8_t* pcm, size_t bytes, uint64_t, void* user) { + AudioPlayer* self = static_cast(user); + if (!self || !aa::channel::isAudioSink(channel)) { + ELOG("AudioPlayer", "invalid PCM callback"); + return; + } + const unsigned index = channel == aa::channel::kMediaAudio ? 1 : 0; + if (pthread_mutex_trylock(&self->mu_) != 0) { + ELOG("AudioPlayer", "PCM dropped while playback buffer is busy"); + return; + } + if (self->inCall_) { + pthread_mutex_unlock(&self->mu_); + return; + } + if (self->active_[index] && self->sessions_[index] == session) { + const bool ok = + index ? self->mixer_.pushMedia(pcm, bytes) : self->mixer_.pushSpeech(pcm, bytes, self->configs_[index]); + if (ok) { + self->lastData_[index] = monoMs(); + self->seen_[index] = true; + pthread_cond_signal(&self->cv_); + } else { + ELOG("AudioPlayer", "invalid PCM for channel %u", channel); + } + } else { + ELOG("AudioPlayer", "PCM for inactive stream on channel %u", channel); + } + pthread_mutex_unlock(&self->mu_); +} + +void* AudioPlayer::threadMain(void* user) { + static_cast(user)->run(); + return nullptr; +} + +void AudioPlayer::run() { + int16_t samples[480 * 2]; + size_t count = 0, offset = 0; + uint32_t generation = 0; + uint32_t stalledSince = 0; + bool stalled = false; + uint16_t selected = 0; + for (;;) { + pthread_mutex_lock(&mu_); + if (generation != generation_) { + count = offset = 0; + generation = generation_; + stalled = false; + const bool quit = quit_; + const bool routed = route_ != nullptr; + pthread_mutex_unlock(&mu_); + if (quit) { + break; + } + if (!output_.flush() || (routed && !promptOutput_.flush())) { + failure_.store(-EIO); + break; + } + continue; + } + if (route_) { + const uint32_t now = monoMs(); + uint16_t wanted = 0; + if (!inCall_) { + if (mixer_.mediaFrames() || (active_[1] && seen_[1] && now - lastData_[1] < 1000)) { + wanted = 0x315; + } else if (mixer_.speechFrames() || (active_[0] && seen_[0] && now - lastData_[0] < 1000)) { + wanted = 0x31A; + } + } + route_->request(wanted); + if (route_->failure()) { + failure_.store(-EIO); + pthread_mutex_unlock(&mu_); + break; + } + if (selected != wanted) { + selected = wanted; + count = offset = 0; + stalled = false; + pthread_mutex_unlock(&mu_); + if (!output_.flush() || !promptOutput_.flush()) { + failure_.store(-EIO); + break; + } + continue; + } + if (!wanted || !route_->owns(wanted)) { + timespec until; + clock_gettime(CLOCK_REALTIME, &until); + until.tv_nsec += 20000000; + if (until.tv_nsec >= 1000000000) { + ++until.tv_sec; + until.tv_nsec -= 1000000000; + } + if (!quit_) { + pthread_cond_timedwait(&cv_, &mu_, &until); + } + const bool quit = quit_; + pthread_mutex_unlock(&mu_); + if (quit) { + break; + } + continue; + } + } + while (!quit_ && offset == count) { + count = mixer_.read(samples, 480, !route_ || selected == 0x315, true); + offset = 0; + if (count) { + if (route_ && selected == 0x31A) { + for (size_t i = 0; i < count; ++i) { + samples[i] = samples[i * 2]; + } + } + break; + } + stalled = false; + if (route_) { + break; + } + pthread_cond_wait(&cv_, &mu_); + if (generation != generation_) { + break; + } + } + const bool quit = quit_; + pthread_mutex_unlock(&mu_); + if (quit) { + break; + } + if (offset == count) { + usleep(10000); + continue; + } + const bool prompt = route_ && selected == 0x31A; + const long written = prompt ? promptOutput_.write(samples + offset, count - offset) + : output_.write(samples + offset * 2, count - offset); + if (written > 0) { + offset += static_cast(written); + stalled = false; + } else if (written == 0 || written == -EAGAIN) { + const uint32_t now = monoMs(); + if (!stalled) { + stalled = true; + stalledSince = now; + } else if (now - stalledSince >= 2000) { + failure_.store(-ETIMEDOUT); + ELOG("AudioPlayer", "playback stalled for 2 seconds"); + break; + } + usleep(10000); + } else { + failure_.store(static_cast(written)); + ELOG("AudioPlayer", "playback stopped: error %ld", written); + break; + } + } +} + +} // namespace evo diff --git a/platform/audio_player.hpp b/platform/audio_player.hpp new file mode 100644 index 0000000..d183fb4 --- /dev/null +++ b/platform/audio_player.hpp @@ -0,0 +1,58 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +// A bounded playback worker; native source routing is managed separately. +#ifndef ENTRY_AAD_PLATFORM_AUDIO_PLAYER_HPP +#define ENTRY_AAD_PLATFORM_AUDIO_PLAYER_HPP + +#include +#include +#include + +#include + +#include "audio_mixer.hpp" +#include "audio_output.hpp" + +namespace evo { + +class AudioRoute; + +class AudioPlayer { +public: + AudioPlayer(); + ~AudioPlayer(); + AudioPlayer(const AudioPlayer&) = delete; + AudioPlayer& operator=(const AudioPlayer&) = delete; + + // Called before session discovery. False leaves the caller free to select Bluetooth instead. + bool start(const char* pcm, const char* library = "libasound.so.2"); + bool startRouted(AudioRoute& route, const char* mediaPcm, const char* promptPcm, + const char* library = "libasound.so.2"); + void stop(); + int failure() const { return failure_.load(); } + void setCall(bool active); + + // The session callbacks copy to bounded buffers; no ALSA operation runs on the session thread. + static void data(uint8_t channel, uint32_t session, const uint8_t* pcm, size_t bytes, uint64_t pts, void* user); + static void stream(uint8_t channel, uint32_t session, uint32_t config, bool started, void* user); + +private: + static void* threadMain(void* user); + void run(); + bool startWorker(); + + AudioOutput output_; + AudioOutput promptOutput_; + AudioMixer mixer_; + AudioRoute* route_; + pthread_mutex_t mu_; + pthread_cond_t cv_; + pthread_t thread_; + bool started_, quit_, active_[2], inCall_, seen_[2]; + uint32_t sessions_[2], configs_[2], generation_, lastData_[2]; + std::atomic failure_; +}; + +} // namespace evo + +#endif diff --git a/platform/audio_probe.cpp b/platform/audio_probe.cpp new file mode 100644 index 0000000..9e65e51 --- /dev/null +++ b/platform/audio_probe.cpp @@ -0,0 +1,114 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include "audio_probe.hpp" + +#include + +#include + +#include "evo_log.hpp" +#include "vmost_client.hpp" + +namespace evo { +namespace { + +const uint8_t kConnectionMaster = 0x03; +const uint16_t kConnectionTable = 0xC03; + +struct Reply { + bool received; + std::vector payload; + Reply() : received(false) {} +}; + +void onMessage(void* message, void* user) { + Reply* reply = static_cast(user); + VmostMsgView view; + if (!reply || !parseVmostMsg(message, view) || view.fblock != kConnectionMaster || view.inst != 0 || + view.fkt != kConnectionTable || view.op != kMostOpStatus || reply->received) { + return; + } + reply->received = true; + if (view.len) { + reply->payload.assign(view.data, view.data + view.len); + } +} + +} // namespace + +bool readAudioRouteTable(std::vector& payload, unsigned waitMs) { + payload.clear(); + VmostClient client; + const VmostClient::Load loaded = client.load(); + if (loaded != VmostClient::kLoaded) { + ELOG("AudioProbe", "vMOST unavailable (%d): %s", static_cast(loaded), client.error().c_str()); + return false; + } + Reply reply; + if (client.connect(onMessage, &reply, 0) != 0) { + ELOG("AudioProbe", "vMOST connection refused"); + client.unload(); + return false; + } + const bool registered = client.shadowRegister(kConnectionMaster, 0) == 0; + int fd = -1; + bool ok = false; + if (!registered) { + ELOG("AudioProbe", "ConnectionMaster shadow registration refused"); + } else if (client.fileDescriptorGet(&fd) != 0 || fd < 0) { + ELOG("AudioProbe", "cannot obtain vMOST descriptor"); + } else { + const uint8_t position[] = {0, 0}; + VmostMsgOut request; + buildVmostGet(request, kConnectionMaster, 0, kConnectionTable, position, sizeof(position)); + if (client.send(&request) != 0) { + ELOG("AudioProbe", "connection table Get refused"); + } else { + const uint32_t start = monoMs(); + while (!reply.received) { + const uint32_t elapsed = monoMs() - start; + if (elapsed >= waitMs) { + break; + } + const uint32_t remaining = waitMs - elapsed; + pollfd p = {fd, POLLIN, 0}; + const int result = poll(&p, 1, remaining < 100 ? static_cast(remaining) : 100); + if (result < 0 && errno == EINTR) { + continue; + } + if (result < 0 || (result > 0 && (p.revents & (POLLERR | POLLHUP | POLLNVAL)))) { + ELOG("AudioProbe", "vMOST connection failed while awaiting the table"); + break; + } + if (result > 0 && (p.revents & POLLIN) && client.processMessages() != 0) { + ELOG("AudioProbe", "cannot process vMOST reply"); + break; + } + } + if (!reply.received) { + ELOG("AudioProbe", "connection table did not answer"); + } else if (reply.payload.size() < 2 || (reply.payload.size() - 2) % 3 != 0) { + ELOG("AudioProbe", "unexpected connection table length: %u bytes", + static_cast(reply.payload.size())); + } else { + payload.swap(reply.payload); + ok = true; + } + } + } + if (registered && client.shadowDeregister(kConnectionMaster, 0) != 0) { + ELOG("AudioProbe", "shadow deregistration failed"); + ok = false; + } + if (client.disconnect() != 0) { + ELOG("AudioProbe", "vMOST disconnect failed"); + ok = false; + } + client.unload(); + if (!ok) { + payload.clear(); + } + return ok; +} + +} // namespace evo diff --git a/platform/audio_probe.hpp b/platform/audio_probe.hpp new file mode 100644 index 0000000..f3490ce --- /dev/null +++ b/platform/audio_probe.hpp @@ -0,0 +1,19 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +// Read the ConnectionMaster audio connection table without changing a route. +#ifndef ENTRY_AAD_PLATFORM_AUDIO_PROBE_HPP +#define ENTRY_AAD_PLATFORM_AUDIO_PROBE_HPP + +#include + +#include + +namespace evo { + +// Runs in a separate diagnostic process, not alongside the service's process-global vMOST connection. +// The raw Status payload is returned on success. A missing, malformed or timed-out reply is a failure. +bool readAudioRouteTable(std::vector& payload, unsigned waitMs); + +} // namespace evo + +#endif diff --git a/platform/audio_route.cpp b/platform/audio_route.cpp new file mode 100644 index 0000000..c5f0c61 --- /dev/null +++ b/platform/audio_route.cpp @@ -0,0 +1,283 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include "audio_route.hpp" + +#include +#include + +#include "evo_log.hpp" + +namespace evo { +namespace { +const uint8_t kBlock = 0x03; +const uint16_t kTable = 0xC03, kBuildFunction = 0x053, kRemoveFunction = 0x054; +const uint32_t kTimeoutMs = 10000, kPollMs = 1000; + +bool has(const std::vector& entries, uint16_t value) { + return std::find(entries.begin(), entries.end(), value) != entries.end(); +} +} // namespace + +AudioRoute::AudioRoute() + : enabled_(false), + ready_(false), + quiescent_(false), + desired_(0), + owned_(0), + usable_(0), + restoreEpoch_(0), + failure_(0), + phase_(kIdle), + shadowed_(false), + received_(false), + tableOk_(false), + responseOk_(false), + timedOut_(false), + foreign_(false), + route_(0), + handle_(0), + nextHandle_(0xA600), + sentAt_(0), + nextPoll_(0), + claimEpoch_(0) {} + +bool AudioRoute::wants(const VmostMsgView& m) const { + return m.fblock == kBlock && m.inst == 0 && + (m.fkt == kTable || m.fkt == kBuildFunction || m.fkt == kRemoveFunction); +} + +bool AudioRoute::parseTable(const VmostMsgView& m, std::vector& active) const { + active.clear(); + if (m.len < 2 || (m.len - 2) % 3) { + return false; + } + for (size_t i = 2; i < m.len; i += 3) { + if (m.data[i + 2] == 0) { + active.push_back(static_cast((m.data[i] << 8) | m.data[i + 1])); + } + } + std::sort(active.begin(), active.end()); + active.erase(std::unique(active.begin(), active.end()), active.end()); + return true; +} + +void AudioRoute::onMessage(const VmostMsgView& m) { + if (!wants(m)) { + return; + } + if (m.fkt == kTable && m.op == kMostOpStatus && + (phase_ == kPreflight || phase_ == kBefore || phase_ == kAfter || phase_ == kReleaseTable || + phase_ == kRestoreTable || phase_ == kMonitor)) { + tableOk_ = parseTable(m, observed_); + received_ = true; + } else if ((phase_ == kBuild || phase_ == kRemove || phase_ == kRestore) && + m.fkt == (phase_ == kRemove ? kRemoveFunction : kBuildFunction) && m.len >= 2 && + static_cast((m.data[0] << 8) | m.data[1]) == handle_) { + if (m.op == 0xD || m.op == 0x9 || m.op == 0xF) { + responseOk_ = m.op == 0xD; + received_ = true; + } + } +} + +void AudioRoute::fail(const char* reason) { + ELOG("AudioRoute", "%s", reason); + failure_.store(1); + ready_.store(false); + usable_.store(0); + desired_.store(0); + ++restoreEpoch_; +} + +void AudioRoute::query(Phase phase, uint32_t now, VmostPort& port) { + static const uint8_t position[] = {0, 0}; + VmostMsgOut m; + buildVmostGet(m, kBlock, 0, kTable, position, sizeof(position)); + phase_ = phase; + received_ = false; + sentAt_ = now; + timedOut_ = false; + if (port.send(m) != 0) { + fail("connection table Get refused"); + phase_ = owned_.load() ? kPlaying : kIdle; + nextPoll_ = now + kPollMs; + } +} + +void AudioRoute::call(Phase phase, uint16_t route, uint32_t now, VmostPort& port) { + handle_ = ++nextHandle_; + const uint8_t data[] = {static_cast(handle_ >> 8), static_cast(handle_), + static_cast(route >> 8), static_cast(route)}; + VmostMsgOut m; + memset(&m, 0, sizeof(m)); + m.addr = 0xFFFF; + m.fblock = kBlock; + m.fkt = phase == kRemove ? kRemoveFunction : kBuildFunction; + m.op = kMostOpStartResultAck; + m.len = sizeof(data); + m.data = data; + phase_ = phase; + received_ = false; + timedOut_ = false; + sentAt_ = now; + if (port.send(m) != 0) { + fail("route request refused by vMOST"); + phase_ = owned_.load() ? kPlaying : kIdle; + nextPoll_ = now + kPollMs; + } +} + +int AudioRoute::dueInMs(uint32_t) const { + return 50; +} + +void AudioRoute::tick(uint32_t now, VmostPort& port) { + if (!shadowed_) { + if (!enabled_.load() || failure_.load()) { + return; + } + if (port.shadow(kBlock, 0, true) != 0) { + fail("ConnectionMaster shadow registration refused"); + return; + } + shadowed_ = true; + query(kPreflight, now, port); + return; + } + if (phase_ != kIdle && phase_ != kPlaying && !received_ && now - sentAt_ >= kTimeoutMs && !timedOut_) { + timedOut_ = true; + fail("connection table or route request timed out; ownership is uncertain"); + if (phase_ != kBuild && phase_ != kRemove && phase_ != kRestore) { + phase_ = owned_.load() ? kPlaying : kIdle; + nextPoll_ = now + kPollMs; + } + } + if (received_) { + received_ = false; + if (phase_ == kBuild || phase_ == kRemove || phase_ == kRestore) { + if (!responseOk_) { + fail("ConnectionMaster rejected a route request"); + phase_ = owned_.load() ? kPlaying : kIdle; + nextPoll_ = now + kPollMs; + } else if (phase_ == kBuild) { + owned_.store(route_); + query(kAfter, now, port); + } else if (phase_ == kRemove) { + owned_.store(0); + usable_.store(0); + query(kRestoreTable, now, port); + } else { + phase_ = kIdle; + } + } else if (!tableOk_) { + fail("malformed connection table"); + phase_ = owned_.load() ? kPlaying : kIdle; + nextPoll_ = now + kPollMs; + } else if (phase_ == kPreflight) { + ready_.store(true); + phase_ = kIdle; + } else if (phase_ == kBefore) { + if (!enabled_.load() || desired_.load() != route_ || failure_.load()) { + phase_ = kIdle; + } else if (has(observed_, route_)) { + fail("candidate route is already in use"); + phase_ = kIdle; + } else { + before_ = observed_; + call(kBuild, route_, now, port); + } + } else if (phase_ == kAfter) { + displaced_.clear(); + for (size_t i = 0; i < before_.size(); ++i) { + if (!has(observed_, before_[i])) { + displaced_.push_back(before_[i]); + } + } + playing_ = observed_; + foreign_ = !has(observed_, route_); + if (foreign_) { + fail("built route is not active in the table"); + } else if (!failure_.load() && enabled_.load() && desired_.load() == route_) { + usable_.store(route_); + } + nextPoll_ = now + kPollMs; + phase_ = kPlaying; + } else if (phase_ == kMonitor) { + if (observed_ != playing_) { + foreign_ = true; + } + if (!has(observed_, route_)) { + owned_.store(0); + usable_.store(0); + fail("another source replaced the audio route"); + phase_ = kIdle; + } else { + phase_ = kPlaying; + } + nextPoll_ = now + kPollMs; + } else if (phase_ == kReleaseTable) { + if (observed_ != playing_) { + foreign_ = true; + } + if (has(observed_, route_)) { + call(kRemove, route_, now, port); + } else { + owned_.store(0); + phase_ = kIdle; + } + } else if (phase_ == kRestoreTable) { + if (!foreign_ && restoreEpoch_.load() == claimEpoch_ && displaced_.size() == 1 && observed_.empty()) { + call(kRestore, displaced_[0], now, port); + } else { + phase_ = kIdle; + } + } + } + const uint16_t desired = desired_.load(); + if (phase_ == kIdle && enabled_.load() && ready_.load() && desired && !failure_.load()) { + route_ = desired; + claimEpoch_ = restoreEpoch_.load(); + foreign_ = false; + query(kBefore, now, port); + } else if (phase_ == kPlaying) { + if ((!enabled_.load() || desired_.load() != route_ || failure_.load()) && + static_cast(now - nextPoll_) >= 0) { + usable_.store(0); + query(kReleaseTable, now, port); + } else if (static_cast(now - nextPoll_) >= 0) { + query(kMonitor, now, port); + nextPoll_ = now + kPollMs; + } + } + if (!enabled_.load() && phase_ == kIdle && !owned_.load()) { + quiescent_.store(true); + } +} + +void AudioRoute::finish(VmostPort& port) { + enabled_.store(false); + desired_.store(0); + const uint32_t start = monoMs(); + while ((owned_.load() || phase_ == kBuild || phase_ == kRemove || phase_ == kRestore || phase_ == kReleaseTable || + phase_ == kRestoreTable || phase_ == kAfter) && + monoMs() - start < 12000) { + tick(monoMs(), port); + port.pump(50); + } + if (owned_.load() || phase_ == kBuild || phase_ == kRemove) { + ELOG("AudioRoute", "shutdown with unresolved route ownership"); + } + if (shadowed_ && port.shadow(kBlock, 0, false) != 0) { + ELOG("AudioRoute", "shadow deregistration failed"); + } + shadowed_ = false; + ready_.store(false); +} + +void AudioRoute::connectionLost() { + if (enabled_.load() || owned_.load()) { + fail("vMOST connection lost; route cleanup cannot be confirmed"); + } +} + +} // namespace evo diff --git a/platform/audio_route.hpp b/platform/audio_route.hpp new file mode 100644 index 0000000..716e7d0 --- /dev/null +++ b/platform/audio_route.hpp @@ -0,0 +1,71 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +// ConnectionMaster route ownership on the controller's existing vMOST connection. +#ifndef ENTRY_AAD_PLATFORM_AUDIO_ROUTE_HPP +#define ENTRY_AAD_PLATFORM_AUDIO_ROUTE_HPP + +#include +#include + +#include "vmost_client.hpp" + +namespace evo { + +class AudioRoute : public VmostPeer { +public: + AudioRoute(); + // Called from other threads. A zero route releases the current one. Repeated calls are harmless. + void enable(bool on) { + if (!on) { + quiescent_.store(false); + } + enabled_.store(on); + } + void request(uint16_t route) { desired_.store(route); } + // A native call or other externally selected source must never be displaced by restoration. + void prohibitRestore() { ++restoreEpoch_; } + bool ready() const { return ready_.load(); } + bool quiescent() const { return quiescent_.load(); } + bool owns(uint16_t route) const { return usable_.load() == route && route != 0; } + int failure() const { return failure_.load(); } + + bool wants(const VmostMsgView& message) const override; + void onMessage(const VmostMsgView& message) override; + int dueInMs(uint32_t nowMs) const override; + void tick(uint32_t nowMs, VmostPort& port) override; + void finish(VmostPort& port) override; + void connectionLost() override; + +private: + enum Phase { + kIdle, + kPreflight, + kBefore, + kBuild, + kAfter, + kPlaying, + kMonitor, + kReleaseTable, + kRemove, + kRestoreTable, + kRestore + }; + void query(Phase phase, uint32_t now, VmostPort& port); + void call(Phase phase, uint16_t route, uint32_t now, VmostPort& port); + void fail(const char* reason); + bool parseTable(const VmostMsgView& message, std::vector& active) const; + + std::atomic enabled_, ready_, quiescent_; + std::atomic desired_, owned_, usable_; + std::atomic restoreEpoch_; + std::atomic failure_; + Phase phase_; + bool shadowed_, received_, tableOk_, responseOk_, timedOut_, foreign_; + uint16_t route_, handle_, nextHandle_; + uint32_t sentAt_, nextPoll_, claimEpoch_; + std::vector before_, playing_, displaced_, observed_; +}; + +} // namespace evo + +#endif diff --git a/platform/evo_knob.cpp b/platform/evo_knob.cpp index a56a6e6..40d60d9 100644 --- a/platform/evo_knob.cpp +++ b/platform/evo_knob.cpp @@ -200,8 +200,8 @@ bool EvoKnob::load() { } bool EvoKnob::start(InputMode mode, Callback cb, void* user) { - if (started_ || mode == INPUT_OFF) { - return mode == INPUT_OFF; + if (started_ || (mode == INPUT_OFF && !peer_)) { + return mode == INPUT_OFF && !started_; } mode_ = mode; cb_ = cb; @@ -659,8 +659,12 @@ void EvoKnob::run() { if (!linkLost && dropped()) { linkLost = true; } - if (peer_ && !linkLost) { - peer_->finish(*this); + if (peer_) { + if (!linkLost && connected_ && !running_) { + peer_->finish(*this); + } else { + peer_->connectionLost(); + } } fd_ = -1; } diff --git a/platform/main.cpp b/platform/main.cpp index 429881d..535c724 100644 --- a/platform/main.cpp +++ b/platform/main.cpp @@ -333,6 +333,8 @@ int main(int argc, char** argv) { display.leftInset()); } evo::ServiceApp app(kAaPort, video, &quit); + evo::VmostPeerPair mostPeers(app.audioRoute, app.kombiMost); + app.audioRoute.enable(usb && access(evo::contract::kUsbBluetoothAudio, F_OK) != 0); app.videoConfig.setDisplay(display.canvasWidth, display.canvasHeight, display.width, display.height, display.shownWidth, display.shownHeight); app.videoConfig.holdCloseFrames = !usb; // pairs come from the Wi-Fi's bursts, not the cable @@ -353,7 +355,7 @@ int main(int argc, char** argv) { evo::EvoControl control; const bool logsKept = access(evo::contract::kMaintenance, F_OK) == 0; if (usb) { - ELOG("Main", "USB cable: no Bluetooth change, no Wi-Fi, no TCP server; media over the BMW Bluetooth source"); + ELOG("Main", "USB cable: no Bluetooth change, no Wi-Fi, no TCP server; direct audio if preflight succeeds"); } else { std::string source; if (!evo::loadAccessPoint(app.ap, source)) { @@ -466,10 +468,15 @@ int main(int argc, char** argv) { fclose(f); } } - knob.setPeer(&app.kombiMost); + knob.setPeer(&mostPeers); if (!knob.start(input, evo::ServiceApp::knobEvent, &app)) { ELOG("Main", "controller unavailable for this run"); } + } else if (usb && access(evo::contract::kUsbBluetoothAudio, F_OK) != 0) { + knob.setPeer(&mostPeers); + if (!knob.start(input, nullptr, nullptr)) { + ELOG("Main", "vMOST unavailable for direct audio"); + } } app.markReady(); pthread_t phones; // the wireless loop, or the USB one @@ -543,11 +550,12 @@ int main(int argc, char** argv) { touch.setOwned(false); knob.setOwned(false); touch.stop(); - knob.stop(); // UDP 30567 back to iDrive, vMOST copies deregistered, before the session goes app.pill.stop(); // nothing calls show() any more control.stop(); // state file removed: the iDrive app shows "Android Auto" again app.server.stop(); // join the accept thread before stopping its last session app.session.stop(); + app.audioPlayer.stop(); + knob.stop(); // release owned routes and vMOST copies after the session and playback stop app.video.stop(); app.kombi.stop(); evo::kombi::closeBmwGuidance(); diff --git a/platform/service_app.cpp b/platform/service_app.cpp index 6c61760..3b337b1 100644 --- a/platform/service_app.cpp +++ b/platform/service_app.cpp @@ -41,6 +41,10 @@ ServiceApp::ServiceApp(uint16_t p, bool v, std::atomic* quit) wppReply(false), wppAccepted(false), projectionOverUsb(false), + directAudio(false), + audioFallback(false), + audioRouteUsed(false), + audioCleanupRequested(false), lostWireless(0), htRebuilds(0), quit_(quit) { @@ -55,6 +59,7 @@ ServiceApp::~ServiceApp() { mic.stop(); kombi.stop(); session.stop(); + audioPlayer.stop(); video.stop(); bt.stop(); pthread_mutex_destroy(&mu); @@ -146,6 +151,23 @@ unsigned ServiceApp::lostSessions() { ServiceApp::Turn ServiceApp::turn(bool service) { Turn t; + if (audioPlayer.failure() && pthread_mutex_trylock(&connectMu) == 0) { + pthread_mutex_lock(&mu); + const bool fallback = directAudio && session.isActive(); + if (fallback) { + directAudio = false; + audioFallback = true; + } + pthread_mutex_unlock(&mu); + if (fallback) { + ELOG("ServiceApp", + "direct audio failed (%d): restarting USB in Bluetooth mode for this run; Bluetooth media " + "connection is not checked", + audioPlayer.failure()); + session.requestDisconnect(); + } + pthread_mutex_unlock(&connectMu); + } pthread_mutex_lock(&mu); t.failed = wirelessDone; t.active = session.isActive(); @@ -412,6 +434,7 @@ void ServiceApp::command(const ControlCommand& c, void* user) { a->parkAssist = owns; } else if (c.verb == "call") { // iDrive app (CDS communication.callStatus): phone keys go to iDrive's call screen a->inCall = c.arg != 0; + a->audioPlayer.setCall(a->inCall); a->volume.call(a->inCall); // during a call the pill shows the call's volume (volume_state.hpp) if (a->knob) { a->knob->setPhoneToIdrive(c.arg != 0); @@ -474,6 +497,12 @@ void ServiceApp::ended(void* user) { a->kombiMost.onSessionEnded(); const bool goodbye = a->session.phoneSaidGoodbye(); pthread_mutex_lock(&a->mu); + const bool audioFailed = + a->projectionOverUsb && a->directAudio && (a->session.audioFailed() || a->audioPlayer.failure() != 0); + if (audioFailed) { + a->audioFallback = true; + } + a->directAudio = false; a->focus = false; a->asking = false; a->mediaPress.cancel(); @@ -483,6 +512,9 @@ void ServiceApp::ended(void* user) { ++a->lostWireless; } pthread_mutex_unlock(&a->mu); + if (audioFailed) { + ELOG("ServiceApp", "direct audio failed: next USB session uses Bluetooth; media connection is not checked"); + } a->server.notifySessionEnded(); ELOG("ServiceApp", "session ended%s", goodbye ? " (the phone said goodbye)" : lost ? " (lost)" : ""); } @@ -533,6 +565,32 @@ void ServiceApp::startProjection(int fd, bool overUsb) { pthread_mutex_unlock(&a->connectMu); return; } + a->audioPlayer.stop(); + a->session.setAudioCallbacks(nullptr, nullptr); + if (a->audioRouteUsed) { + if (!a->audioCleanupRequested) { + a->audioRoute.enable(false); + a->audioCleanupRequested = true; + } + for (unsigned waited = 0; !a->audioRoute.quiescent() && waited < 12000 && !a->stopRequested(); waited += 50) { + usleep(50000); + } + if (a->stopRequested() || !a->audioRoute.quiescent()) { + if (!a->audioRoute.quiescent()) { + ELOG("ServiceApp", "audio route cleanup unconfirmed; refusing to start a new session"); + } + close(fd); + a->server.notifySessionEnded(); + pthread_mutex_lock(&a->mu); + a->tcpPreparing = false; + pthread_mutex_unlock(&a->mu); + pthread_mutex_unlock(&a->connectMu); + return; + } + a->audioRouteUsed = false; + a->audioCleanupRequested = false; + a->audioRoute.enable(true); + } bool videoOk = true; if (a->videoEnabled) { pthread_mutex_lock(&a->videoMu); @@ -556,6 +614,29 @@ void ServiceApp::startProjection(int fd, bool overUsb) { if (aside) { ELOG("ServiceApp", "Android Auto starts aside: the iDrive app shows it once iDrive is on its page"); } + bool direct = false; + pthread_mutex_lock(&a->mu); + const bool mayTryAudio = overUsb && !a->audioFallback && access(contract::kUsbBluetoothAudio, F_OK) != 0; + pthread_mutex_unlock(&a->mu); + for (unsigned waited = 0; + mayTryAudio && !a->audioRoute.ready() && !a->audioRoute.failure() && waited < 2000 && !a->stopRequested(); + waited += 50) { + usleep(50000); + } + if (mayTryAudio && a->audioRoute.ready()) { + direct = a->audioPlayer.startRouted(a->audioRoute, "entertainment", "carplay_alt"); + if (direct) { + a->audioRouteUsed = true; + a->session.setAudioCallbacks(AudioPlayer::data, AudioPlayer::stream, &a->audioPlayer); + ELOG("ServiceApp", "USB direct audio: experimental EntryNav2 playback profile"); + } + } + if (overUsb && !direct) { + ELOG("ServiceApp", "USB audio uses Bluetooth; verify that Bluetooth media is connected (not checked here)"); + } + pthread_mutex_lock(&a->mu); + a->directAudio = direct; + pthread_mutex_unlock(&a->mu); if (!overUsb) { a->wifiLink.connected(fd); // before the session owns fd } diff --git a/platform/service_app.hpp b/platform/service_app.hpp index 1db132e..1c4ef18 100644 --- a/platform/service_app.hpp +++ b/platform/service_app.hpp @@ -18,6 +18,8 @@ #include "aa_session.hpp" #include "alps_spp.hpp" +#include "audio_player.hpp" +#include "audio_route.hpp" #include "evo_control.hpp" #include "evo_knob.hpp" #include "evo_mic.hpp" @@ -109,7 +111,9 @@ class ServiceApp : public WirelessHost, public UsbHost { aa::AASession session; EvoMic mic; // car mic for the Assistant (stopped before the session it posts to) evo::kombi::MostHud kombiMost; // F-series cluster over MOST, on the controller reader (destroyed after kombi) - evo::kombi::Arrows kombi; // AA turn-by-turn -> HUD/cluster arrows, SOME/IP 0xB006 to the KOMBI + AudioRoute audioRoute; + AudioPlayer audioPlayer; + evo::kombi::Arrows kombi; // AA turn-by-turn -> HUD/cluster arrows, SOME/IP 0xB006 to the KOMBI aa::TcpServer server; aa::ApInfo ap; EvoVideoConfig videoConfig; @@ -138,6 +142,8 @@ class ServiceApp : public WirelessHost, public UsbHost { std::atomic videoFrames; // counted on the session thread without mu bool wppReply, wppAccepted; bool projectionOverUsb; // the last session came over USB (its loss is not the wireless loop's business) + bool directAudio, audioFallback; // under mu: fallback lasts for this service run + bool audioRouteUsed, audioCleanupRequested; // under connectMu: cleanup before another session unsigned lostWireless; // wireless sessions ended without ByeBye, and connections refused for 802.11n (#203) unsigned htRebuilds; // beacon rebuilds in a row for a phone on 802.11n; under connectMu diff --git a/platform/service_contract.hpp b/platform/service_contract.hpp index 88bba4e..fc981d7 100644 --- a/platform/service_contract.hpp +++ b/platform/service_contract.hpp @@ -33,6 +33,8 @@ constexpr char kKombiMostLayout[] = "/var/local/data/AA/kombi-most-layout"; constexpr char kKombiSingle[] = "/var/local/data/AA/kombi-single-maneuver"; // Present: Android Auto over a USB cable instead of wireless. Empty, or the one USB port to use ("1-1"). constexpr char kUsb[] = "/var/local/data/AA/usb"; +// Present: USB projection keeps the existing Bluetooth audio path. +constexpr char kUsbBluetoothAudio[] = "/var/local/data/AA/usb-bluetooth-audio"; constexpr char kAppLog[] = "/var/local/data/AA/app.log"; constexpr char kAppLogOld[] = "/var/local/data/AA/app.old.log"; // The service's log in the maintenance profile, kept across the car's sleep (kept_log.hpp). diff --git a/platform/vmost_client.hpp b/platform/vmost_client.hpp index fa986b1..c69ccc7 100644 --- a/platform/vmost_client.hpp +++ b/platform/vmost_client.hpp @@ -148,6 +148,41 @@ class VmostPeer { virtual int dueInMs(uint32_t nowMs) const = 0; // how soon tick() has work; the reader waits 100 ms at most virtual void tick(uint32_t nowMs, VmostPort& port) = 0; virtual void finish(VmostPort& port) = 0; // the connection closes right after + virtual void connectionLost() {} // no more requests can be sent on this connection +}; + +class VmostPeerPair : public VmostPeer { +public: + VmostPeerPair(VmostPeer& first, VmostPeer& second) : first_(first), second_(second) {} + bool wants(const VmostMsgView& m) const override { return first_.wants(m) || second_.wants(m); } + void onMessage(const VmostMsgView& m) override { + if (first_.wants(m)) { + first_.onMessage(m); + } + if (second_.wants(m)) { + second_.onMessage(m); + } + } + int dueInMs(uint32_t nowMs) const override { + const int first = first_.dueInMs(nowMs), second = second_.dueInMs(nowMs); + return first < second ? first : second; + } + void tick(uint32_t nowMs, VmostPort& port) override { + first_.tick(nowMs, port); + second_.tick(nowMs, port); + } + void finish(VmostPort& port) override { + first_.finish(port); + second_.finish(port); + } + void connectionLost() override { + first_.connectionLost(); + second_.connectionLost(); + } + +private: + VmostPeer& first_; + VmostPeer& second_; }; } // namespace evo diff --git a/tests/fake_audio_output.c b/tests/fake_audio_output.c new file mode 100644 index 0000000..00e5636 --- /dev/null +++ b/tests/fake_audio_output.c @@ -0,0 +1,106 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include +#include + +static int fake_pcm, prompt_pcm, media_state, prompt_state, starts, next_error, closed, recovered, written; +static int prompt_written, dropped, stuck; +static int* state_for(void* pcm) { + return pcm == &fake_pcm ? &media_state : &prompt_state; +} +int snd_pcm_open(void** pcm, const char* name, int stream, int flags) { + if ((strcmp(name, "test") && strcmp(name, "prompt")) || stream != 0 || flags != 1) { + return -ENOENT; + } + *pcm = strcmp(name, "prompt") == 0 ? &prompt_pcm : &fake_pcm; + __atomic_store_n(state_for(*pcm), 2, __ATOMIC_SEQ_CST); + return 0; +} +int snd_pcm_set_params(void* pcm, int format, int access, unsigned channels, unsigned rate, int resample, + unsigned latency) { + return ((pcm == &fake_pcm && channels == 2) || (pcm == &prompt_pcm && channels == 1)) && format == 2 && + access == 3 && rate == 48000 && resample == 1 && latency == 100000 + ? 0 + : -EINVAL; +} +long snd_pcm_writei(void* pcm, const void* data, unsigned long frames) { + if ((pcm != &fake_pcm && pcm != &prompt_pcm) || !data || !frames) { + return -EINVAL; + } + if (__atomic_load_n(&stuck, __ATOMIC_SEQ_CST)) { + return -EAGAIN; + } + const int result = __atomic_exchange_n(&next_error, 0, __ATOMIC_SEQ_CST); + if (result) { + return result; + } + const long count = frames > 2 ? 2 : (long)frames; + __atomic_add_fetch(pcm == &prompt_pcm ? &prompt_written : &written, (int)count, __ATOMIC_SEQ_CST); + return count; +} +int snd_pcm_recover(void* pcm, int error, int silent) { + if ((pcm != &fake_pcm && pcm != &prompt_pcm) || error != -EPIPE || silent != 1) { + return -EINVAL; + } + __atomic_add_fetch(&recovered, 1, __ATOMIC_SEQ_CST); + __atomic_store_n(state_for(pcm), 2, __ATOMIC_SEQ_CST); + return 0; +} +int snd_pcm_close(void* pcm) { + if (pcm != &fake_pcm && pcm != &prompt_pcm) { + return -EINVAL; + } + __atomic_add_fetch(&closed, 1, __ATOMIC_SEQ_CST); + return 0; +} +int snd_pcm_drop(void* pcm) { + if (pcm != &fake_pcm && pcm != &prompt_pcm) { + return -EINVAL; + } + __atomic_add_fetch(&dropped, 1, __ATOMIC_SEQ_CST); + __atomic_store_n(state_for(pcm), 1, __ATOMIC_SEQ_CST); + return 0; +} +int snd_pcm_prepare(void* pcm) { + if (pcm != &fake_pcm && pcm != &prompt_pcm) { + return -EINVAL; + } + __atomic_store_n(state_for(pcm), 2, __ATOMIC_SEQ_CST); + return 0; +} +int snd_pcm_state(void* pcm) { + return __atomic_load_n(state_for(pcm), __ATOMIC_SEQ_CST); +} +int snd_pcm_start(void* pcm) { + __atomic_store_n(state_for(pcm), 3, __ATOMIC_SEQ_CST); + __atomic_add_fetch(&starts, 1, __ATOMIC_SEQ_CST); + return 0; +} +const char* snd_strerror(int error) { + (void)error; + return "fake error"; +} +void fake_audio_error(int error) { + __atomic_store_n(&next_error, error, __ATOMIC_SEQ_CST); +} +int fake_audio_closed(void) { + return __atomic_load_n(&closed, __ATOMIC_SEQ_CST); +} +int fake_audio_recovered(void) { + return __atomic_load_n(&recovered, __ATOMIC_SEQ_CST); +} +int fake_audio_written(void) { + return __atomic_load_n(&written, __ATOMIC_SEQ_CST); +} +int fake_audio_prompt_written(void) { + return __atomic_load_n(&prompt_written, __ATOMIC_SEQ_CST); +} +int fake_audio_dropped(void) { + return __atomic_load_n(&dropped, __ATOMIC_SEQ_CST); +} +int fake_audio_starts(void) { + return __atomic_load_n(&starts, __ATOMIC_SEQ_CST); +} +void fake_audio_stuck(int value) { + __atomic_store_n(&stuck, value, __ATOMIC_SEQ_CST); +} diff --git a/tests/fake_vmostclient.c b/tests/fake_vmostclient.c index 0b5ab1c..49a9f28 100644 --- a/tests/fake_vmostclient.c +++ b/tests/fake_vmostclient.c @@ -254,6 +254,11 @@ int vmostMostMsgSend(void* msg) { enqueue(0xA0, 1, 0xC10, 0xC, &one, 1); } else if (isEcuReset(m)) { answerEcuReset(m); + } else if (m->fblock == 0x03 && m->inst == 0 && m->fkt == 0xC03 && m->op == 1 && m->len == 2 && m->data[0] == 0 && + m->data[1] == 0 && getenv("FAKE_AUDIO_TABLE")) { + const uint8_t table[] = {0, 0, 0, 1, 0, 3, 0x15, 2}; + const uint16_t len = strcmp(getenv("FAKE_AUDIO_TABLE"), "bad") == 0 ? 7 : sizeof(table); + enqueue(0x03, 0, 0xC03, 0xC, table, len); } return 0; } diff --git a/tests/host.mk b/tests/host.mk index 52512b6..0d970ad 100644 --- a/tests/host.mk +++ b/tests/host.mk @@ -55,13 +55,20 @@ endef host-test = $(call host-program,test-$(1),tests/test_$(subst -,_,$(1)).cpp $(2),$(3),$(4)) $(eval $(call host-program,evo-check-host,tools/evo_check.cpp platform/alps_spp.cpp platform/alps_spp_codec.cpp \ - platform/evo_process.cpp,dbus,$$(HOST_DBUS_LIBS))) + platform/evo_process.cpp platform/audio_probe.cpp platform/vmost_client.cpp,dbus,$$(HOST_DBUS_LIBS) -ldl)) $(eval $(call host-program,test-evo-capture,tools/evo_capture.cpp)) $(eval $(call host-test,aa-frame,core/aa_frame.cpp)) $(eval $(call host-test,session-phone,$(SESSION_SRC),session,-lssl -lcrypto)) $(eval $(call host-test,parsers,platform/alps_spp_codec.cpp platform/evo_ap_config.cpp)) $(eval $(call host-test,alps-spp,platform/alps_spp.cpp platform/alps_spp_codec.cpp platform/evo_process.cpp,dbus,$$(HOST_DBUS_LIBS))) $(eval $(call host-test,media-recall,platform/evo_knob.cpp platform/vmost_client.cpp,,-ldl)) +$(eval $(call host-test,audio-probe,platform/audio_probe.cpp platform/vmost_client.cpp,,-ldl)) +$(eval $(call host-test,audio-route,platform/audio_route.cpp platform/vmost_client.cpp,,-ldl)) +$(eval $(call host-test,audio-mixer)) +$(eval $(call host-test,audio-output,platform/audio_output.cpp,,-ldl)) +$(eval $(call host-test,audio-player,platform/audio_player.cpp platform/audio_output.cpp,,-ldl)) +$(eval $(call host-test,routed-audio,platform/audio_player.cpp platform/audio_output.cpp \ + platform/audio_route.cpp platform/vmost_client.cpp,,-ldl)) $(eval $(call host-test,kombi-phone,platform/kombi_phone.cpp)) $(eval $(call host-test,kombi-display,platform/kombi_display.cpp platform/kombi_phone.cpp)) $(eval $(call host-test,kombi-graph,platform/kombi_graph.cpp platform/kombi_someip.cpp)) @@ -127,6 +134,7 @@ $(HOST_BUILD)/$(1).so: $(HOST_BUILD)/obj/$(1).o endef $(eval $(call host-fixture,fake-vmostclient,tests/fake_vmostclient.c)) $(eval $(call host-fixture,fake-vmostclient-nosym,tests/fake_vmostclient.c,-DFAKE_VMOST_NO_CONNECTED)) +$(eval $(call host-fixture,fake-audio-output,tests/fake_audio_output.c)) comma := , $(eval $(call host-fixture,fake-libasound,tests/fake_libasound.c,-pthread,-Wl$(comma)-soname$(comma)libasound.so.2 -pthread)) @@ -148,6 +156,10 @@ HOST_RUN_evo-input = $< $(call host-fake,fake-vmostclient) HOST_RUN_evo-reboot = $< $(call host-fake,fake-vmostclient) HOST_RUN_evo-wlan = $< $(call host-fake,fake-vmostclient) $(call host-fake,fake-vmostclient-nosym) HOST_RUN_evo-mic = $< $(call host-fake,fake-libasound) +HOST_RUN_audio-probe = $< $(call host-fake,fake-vmostclient) +HOST_RUN_audio-output = $< $(call host-fake,fake-audio-output) +HOST_RUN_audio-player = $< $(call host-fake,fake-audio-output) +HOST_RUN_routed-audio = $< $(call host-fake,fake-audio-output) HOST_RUN_wireless-phone = $< tests/fixtures/wireless_phone.golden define host-run @@ -163,8 +175,9 @@ HOST_UNITS = evo-elf evo-input evo-control peek-timing volume-state volume-pill HOST_ONLY_UNITS = spp-snapshot supervisor evo-ilm video-presentation evo-wlan evo-mic no-inherit HOST_KOMBI_UNITS = kombi-phone kombi-display kombi-graph kombi-guide kombi-client kombi-nav kombi-golden kombi-most HOST_USB_UNITS = usb-accessory usb-bridge usb-loop +HOST_AUDIO_UNITS = audio-probe audio-route audio-mixer audio-output audio-player routed-audio HOST_RUNS = $(HOST_UNITS) $(HOST_ONLY_UNITS) $(HOST_KOMBI_UNITS) $(HOST_USB_UNITS) \ - aa-frame session-phone parsers alps-spp bmw-guidance media-recall evo-gps evo-capture evo-touch-live + $(HOST_AUDIO_UNITS) aa-frame session-phone parsers alps-spp bmw-guidance media-recall evo-gps evo-capture evo-touch-live HOST_PREREQS_alps-spp = $(HOST_BUILD)/evo-check-host HOST_PREREQS_evo-ilm = $(HOST_BUILD)/evo-check-host @@ -172,13 +185,17 @@ HOST_PREREQS_evo-input = $(HOST_BUILD)/fake-vmostclient.so HOST_PREREQS_evo-reboot = $(HOST_BUILD)/fake-vmostclient.so HOST_PREREQS_evo-wlan = $(HOST_BUILD)/fake-vmostclient.so $(HOST_BUILD)/fake-vmostclient-nosym.so HOST_PREREQS_evo-mic = $(HOST_BUILD)/fake-libasound.so +HOST_PREREQS_audio-probe = $(HOST_BUILD)/fake-vmostclient.so +HOST_PREREQS_audio-output = $(HOST_BUILD)/fake-audio-output.so +HOST_PREREQS_audio-player = $(HOST_BUILD)/fake-audio-output.so +HOST_PREREQS_routed-audio = $(HOST_BUILD)/fake-audio-output.so $(foreach test,$(HOST_RUNS),$(eval $(call host-run,$(test),$(HOST_PREREQS_$(test))))) test-frame-host: run-host-aa-frame test-session-host: run-host-session-phone test-parsers: run-host-parsers test-spp-host: run-host-alps-spp -test-media-host: run-host-media-recall +test-media-host: run-host-media-recall $(addprefix run-host-,$(HOST_AUDIO_UNITS)) test-kombi-core-host: $(addprefix run-host-,$(HOST_KOMBI_UNITS)) test-kombi-host: test-kombi-core-host run-host-bmw-guidance test-usb-host: $(addprefix run-host-,$(HOST_USB_UNITS)) diff --git a/tests/test_audio_mixer.cpp b/tests/test_audio_mixer.cpp new file mode 100644 index 0000000..380365c --- /dev/null +++ b/tests/test_audio_mixer.cpp @@ -0,0 +1,42 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include +#include + +#include + +#include "audio_mixer.hpp" + +int main() { + evo::AudioMixer mixer; + int16_t out[16] = {}; + const uint8_t music[] = {0xe8, 0x03, 0x18, 0xfc, 0xe8, 0x03, 0x18, 0xfc, + 0xe8, 0x03, 0x18, 0xfc, 0xe8, 0x03, 0x18, 0xfc}; + const uint8_t speech[] = {0xe8, 0x03}; + assert(mixer.pushMedia(music, sizeof(music))); + assert(mixer.pushSpeech(speech, sizeof(speech), 0)); + assert(mixer.read(out, 8) == 4); + for (size_t i = 0; i < 3; ++i) { + assert(out[2 * i] == 1300 && out[2 * i + 1] == 700); + } + assert(out[6] == 1000 && out[7] == -1000); + assert(mixer.read(out, 8) == 0); + assert(!mixer.pushMedia(music, 3) && !mixer.pushSpeech(speech, 1, 0) && !mixer.pushSpeech(speech, 2, 2)); + const uint8_t loud[] = {0xff, 0x7f, 0x00, 0x80}; + const uint8_t loudVoice[] = {0xff, 0x7f}; + assert(mixer.pushMedia(loud, sizeof(loud)) && mixer.pushSpeech(loudVoice, sizeof(loudVoice), 1)); + assert(mixer.read(out, 1) == 1 && out[0] == 32767 && out[1] == 22937); + assert(mixer.pushMedia(music, sizeof(music))); + mixer.clearMedia(); + assert(mixer.read(out, 1) == 0); + std::vector overflow((evo::AudioMixer::kCapacityFrames + 1) * 4, 0); + overflow[0] = 1; + overflow[overflow.size() - 4] = 2; + assert(mixer.pushMedia(overflow.data(), overflow.size())); + assert(mixer.read(out, 1) == 1 && out[0] == 0); + std::vector rest(evo::AudioMixer::kCapacityFrames * 2); + assert(mixer.read(rest.data(), evo::AudioMixer::kCapacityFrames) == evo::AudioMixer::kCapacityFrames - 1); + assert(rest[(evo::AudioMixer::kCapacityFrames - 2) * 2] == 2); + puts("PASS audio mixer: bounds, formats, voice ducking, clipping and stream clear"); + return 0; +} diff --git a/tests/test_audio_output.cpp b/tests/test_audio_output.cpp new file mode 100644 index 0000000..c9037a0 --- /dev/null +++ b/tests/test_audio_output.cpp @@ -0,0 +1,41 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include +#include +#include +#include + +#include "audio_output.hpp" + +int main(int argc, char** argv) { + assert(argc == 2); + void* lib = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL); + assert(lib); + typedef void (*SetError)(int); + typedef int (*GetValue)(); + SetError setError = nullptr; + GetValue closed = nullptr, recovered = nullptr, dropped = nullptr, starts = nullptr; + *reinterpret_cast(&setError) = dlsym(lib, "fake_audio_error"); + *reinterpret_cast(&closed) = dlsym(lib, "fake_audio_closed"); + *reinterpret_cast(&recovered) = dlsym(lib, "fake_audio_recovered"); + *reinterpret_cast(&dropped) = dlsym(lib, "fake_audio_dropped"); + *reinterpret_cast(&starts) = dlsym(lib, "fake_audio_starts"); + assert(setError && closed && recovered && dropped && starts); + evo::AudioOutput output; + assert(!output.open("missing", argv[1])); + assert(output.open("test", argv[1])); + int16_t samples[8] = {}; + assert(output.write(samples, 4) == 2 && starts() == 1); + setError(-EAGAIN); + assert(output.write(samples, 4) == -EAGAIN); + setError(-EPIPE); + assert(output.write(samples, 4) == -EAGAIN && recovered() == 1); + setError(-EIO); + assert(output.write(samples, 4) == -EIO); + output.close(); + assert(closed() == 1 && dropped() == 1); + assert(output.write(samples, 4) == -EINVAL); + dlclose(lib); + puts("PASS audio output: nonblocking open, short start, partial writes, underrun and failure"); + return 0; +} diff --git a/tests/test_audio_player.cpp b/tests/test_audio_player.cpp new file mode 100644 index 0000000..070d0da --- /dev/null +++ b/tests/test_audio_player.cpp @@ -0,0 +1,58 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include +#include +#include +#include +#include + +#include "audio_player.hpp" + +int main(int argc, char** argv) { + assert(argc == 2); + void* lib = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL); + assert(lib); + typedef void (*SetError)(int); + typedef int (*GetValue)(); + SetError setError = nullptr, setStuck = nullptr; + GetValue written = nullptr, closed = nullptr; + *reinterpret_cast(&setError) = dlsym(lib, "fake_audio_error"); + *reinterpret_cast(&written) = dlsym(lib, "fake_audio_written"); + *reinterpret_cast(&closed) = dlsym(lib, "fake_audio_closed"); + *reinterpret_cast(&setStuck) = dlsym(lib, "fake_audio_stuck"); + assert(setError && setStuck && written && closed); + evo::AudioPlayer player; + assert(!player.start("missing", argv[1])); + assert(player.start("test", argv[1])); + const uint8_t pcm[] = {1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0}; + evo::AudioPlayer::stream(9, 7, 0, true, &player); + evo::AudioPlayer::data(9, 7, pcm, sizeof(pcm), 0, &player); + for (unsigned i = 0; i < 200 && written() < 3; ++i) { + usleep(10000); + } + assert(written() == 3 && player.failure() == 0); + evo::AudioPlayer::stream(9, 7, 0, false, &player); + setError(-EIO); + evo::AudioPlayer::stream(9, 8, 0, true, &player); + evo::AudioPlayer::data(9, 8, pcm, sizeof(pcm), 0, &player); + for (unsigned i = 0; i < 200 && !player.failure(); ++i) { + usleep(10000); + } + assert(player.failure() == -EIO); + player.stop(); + assert(closed() == 1); + assert(player.start("test", argv[1])); + setStuck(1); + evo::AudioPlayer::stream(9, 9, 0, true, &player); + evo::AudioPlayer::data(9, 9, pcm, sizeof(pcm), 0, &player); + for (unsigned i = 0; i < 400 && !player.failure(); ++i) { + usleep(10000); + } + assert(player.failure() == -ETIMEDOUT); + setStuck(0); + player.stop(); + assert(closed() == 2); + dlclose(lib); + puts("PASS audio player: bounded worker, partial writes, stream lifecycle and error reporting"); + return 0; +} diff --git a/tests/test_audio_probe.cpp b/tests/test_audio_probe.cpp new file mode 100644 index 0000000..3342397 --- /dev/null +++ b/tests/test_audio_probe.cpp @@ -0,0 +1,72 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "audio_probe.hpp" +#include "vmost_client.hpp" + +static std::string readLog(const char* path) { + std::string text; + FILE* file = fopen(path, "r"); + if (file) { + char buffer[256]; + size_t n; + while ((n = fread(buffer, 1, sizeof(buffer), file)) != 0) { + text.append(buffer, n); + } + fclose(file); + } + return text; +} + +int main(int argc, char** argv) { + assert(argc == 2); + char dir[] = "/tmp/entry-audio-probe-XXXXXX"; + assert(mkdtemp(dir)); + const std::string socketPath = std::string(dir) + "/socket"; + const std::string logPath = std::string(dir) + "/sent"; + assert(setenv("FAKE_VMOST_LOG", logPath.c_str(), 1) == 0); + evo::setVmostForTest(socketPath.c_str(), argv[1]); + std::vector table; + assert(!evo::readAudioRouteTable(table, 100) && table.empty()); + + const int fd = socket(AF_UNIX, SOCK_STREAM, 0); + assert(fd >= 0); + sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + assert(socketPath.size() < sizeof(addr.sun_path)); + strcpy(addr.sun_path, socketPath.c_str()); + assert(bind(fd, reinterpret_cast(&addr), sizeof(addr)) == 0); + + assert(setenv("FAKE_AUDIO_TABLE", "good", 1) == 0); + assert(evo::readAudioRouteTable(table, 1000)); + const uint8_t expected[] = {0, 0, 0, 1, 0, 3, 0x15, 2}; + assert(table == std::vector(expected, expected + sizeof(expected))); + const std::string log = readLog(logPath.c_str()); + assert(log.find("register 03.00\n") != std::string::npos); + assert(log.find("send addr=ffff 03.00.c03 op=1 len=2 : 00 00\n") != std::string::npos); + assert(log.find("deregister 03.00\n") != std::string::npos); + assert(log.find("op=6") == std::string::npos); + + assert(setenv("FAKE_AUDIO_TABLE", "bad", 1) == 0); + assert(!evo::readAudioRouteTable(table, 1000) && table.empty()); + assert(setenv("FAKE_WLAN_SILENT", "1", 1) == 0); + assert(!evo::readAudioRouteTable(table, 50) && table.empty()); + + close(fd); + unlink(socketPath.c_str()); + unlink(logPath.c_str()); + rmdir(dir); + puts("PASS audio route probe: read-only Get, malformed reply and timeout"); + return 0; +} diff --git a/tests/test_audio_route.cpp b/tests/test_audio_route.cpp new file mode 100644 index 0000000..a86c50d --- /dev/null +++ b/tests/test_audio_route.cpp @@ -0,0 +1,188 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include +#include + +#include + +#include "audio_route.hpp" + +struct Sent { + uint16_t function; + uint32_t op; + std::vector data; +}; + +class Port : public evo::VmostPort { +public: + std::vector sent; + unsigned registrations, removals; + Port() : registrations(0), removals(0) {} + int send(evo::VmostMsgOut& m) override { + assert(m.addr == 0xFFFF && m.fblock == 3 && m.inst == 0); + Sent s = {m.fkt, m.op, std::vector(m.data, m.data + m.len)}; + sent.push_back(s); + return 0; + } + int shadow(uint8_t block, uint8_t instance, bool on) override { + assert(block == 3 && instance == 0); + on ? ++registrations : ++removals; + return 0; + } + void pump(int) override {} +}; + +static void table(evo::AudioRoute& route, std::initializer_list active) { + std::vector bytes(2, 0); + for (uint16_t id : active) { + bytes.push_back(static_cast(id >> 8)); + bytes.push_back(static_cast(id)); + bytes.push_back(0); + } + evo::VmostMsgView msg = {0, 3, 0, 0xC03, 0xC, static_cast(bytes.size()), &bytes[0]}; + route.onMessage(msg); +} + +static void result(evo::AudioRoute& route, const Sent& sent, uint32_t op = 0xD) { + assert(sent.data.size() == 4 && sent.op == 6); + evo::VmostMsgView msg = {0, 3, 0, sent.function, op, 2, &sent.data[0]}; + route.onMessage(msg); +} + +static void expect(const Port& port, uint16_t function, uint32_t op, uint16_t id = 0) { + assert(!port.sent.empty()); + const Sent& s = port.sent.back(); + if (s.function != function || s.op != op) { + fprintf(stderr, "expected %03x/%u, got %03x/%u\n", function, op, s.function, s.op); + } + assert(s.function == function && s.op == op); + if (op == 1) { + assert(s.data.size() == 2 && s.data[0] == 0 && s.data[1] == 0); + } else { + assert(s.data.size() == 4 && ((s.data[2] << 8) | s.data[3]) == id); + } +} + +static void preflight(evo::AudioRoute& route, Port& port) { + route.enable(true); + route.tick(1, port); + expect(port, 0xC03, 1); + table(route, {1}); + route.tick(2, port); + assert(route.ready()); +} + +static void take(evo::AudioRoute& route, Port& port) { + route.request(0x315); + route.tick(3, port); + expect(port, 0xC03, 1); + table(route, {1}); + route.tick(4, port); + expect(port, 0x53, 6, 0x315); + result(route, port.sent.back()); + route.tick(5, port); + expect(port, 0xC03, 1); + table(route, {0x315}); + route.tick(6, port); + assert(route.owns(0x315)); +} + +int main() { + { + evo::AudioRoute route; + Port port; + preflight(route, port); + take(route, port); + route.enable(false); + assert(!route.quiescent()); + route.request(0); + route.tick(1006, port); + expect(port, 0xC03, 1); + table(route, {0x315}); + route.tick(1007, port); + expect(port, 0x54, 6, 0x315); + result(route, port.sent.back()); + route.tick(1008, port); + table(route, {}); + route.tick(1009, port); + assert(!route.quiescent()); + expect(port, 0x53, 6, 1); + result(route, port.sent.back()); + route.tick(1010, port); + assert(!route.owns(0x315) && !route.failure() && route.quiescent()); + route.finish(port); + assert(port.registrations == 1 && port.removals == 1); + } + { + evo::AudioRoute route; + Port port; + preflight(route, port); + take(route, port); + route.tick(1006, port); + table(route, {2}); + route.tick(1007, port); + assert(route.failure() && !route.owns(0x315)); + const size_t count = port.sent.size(); + route.request(0); + route.tick(2000, port); + assert(port.sent.size() == count); // the driver's new source is never removed or replaced + route.finish(port); + } + { + evo::AudioRoute route; + Port port; + preflight(route, port); + route.request(0x315); + route.tick(3, port); + route.enable(false); + route.request(0); + table(route, {1}); + route.tick(4, port); + assert(route.quiescent() && port.sent.back().function == 0xC03); // no build after quiescing + route.finish(port); + } + { + evo::AudioRoute route; + Port port; + preflight(route, port); + route.request(0x315); + route.tick(3, port); + table(route, {0x315}); + route.tick(4, port); + assert(route.failure() && !route.owns(0x315)); + assert(port.sent.back().op == 1); // never claim someone else's route + route.finish(port); + } + { + evo::AudioRoute route; + Port port; + preflight(route, port); + route.request(0x315); + route.tick(3, port); + table(route, {1}); + route.tick(4, port); + const Sent build = port.sent.back(); + route.tick(10004, port); + assert(route.failure() && !route.owns(0x315)); + route.enable(false); + route.tick(10005, port); + assert(!route.quiescent()); // a timed-out build may still be granted + result(route, build); // a late grant still has to be relinquished + route.tick(10005, port); + table(route, {0x315}); + route.tick(10006, port); + route.tick(11006, port); + table(route, {0x315}); + route.tick(11007, port); + expect(port, 0x54, 6, 0x315); + result(route, port.sent.back()); + route.tick(11008, port); + table(route, {}); + route.tick(11009, port); + assert(route.quiescent()); + assert(port.sent.back().function == 0xC03); // no source restoration after an uncertain result + route.finish(port); + } + puts("PASS audio routes: preflight, ownership, restoration, driver selection and late grant"); + return 0; +} diff --git a/tests/test_evo_sdr.cpp b/tests/test_evo_sdr.cpp index 327c153..79a6147 100644 --- a/tests/test_evo_sdr.cpp +++ b/tests/test_evo_sdr.cpp @@ -247,6 +247,15 @@ int main() { CHECK(values(source, 3) == std::vector({1, 10}) && values(source, 4) == std::vector({8})); const std::vector leftPetrol = aa::buildCarServiceDiscovery(kDhuSdpProtobuf, kDhuSdpProtobufLen, nullptr, nullptr); + const std::vector directAudio = + aa::buildCarServiceDiscovery(kDhuSdpProtobuf, kDhuSdpProtobufLen, nullptr, nullptr, aa::DisplayPlan(), nullptr, + aa::DriverPosition::kLeft, nullptr, true); + std::vector sink8, sink9, speechSettings, template8, template9; + CHECK(service(directAudio, 8, sink8) && service(directAudio, 9, sink9)); + CHECK(service(orig, 8, template8) && service(orig, 9, template9)); + CHECK(sink8 == template8 && sink9 == template9); + CHECK(!service(leftPetrol, 9, sink9) && service(leftPetrol, 8, sink8) && sub(sink8, 3, speechSettings)); + CHECK(value(speechSettings, 2) == 2); CHECK(values(leftPetrol, 6) == std::vector({0})); CHECK(service(leftPetrol, 1, sensorService) && sub(sensorService, 2, source)); CHECK(values(source, 3) == std::vector({1}) && values(source, 4).empty()); diff --git a/tests/test_routed_audio.cpp b/tests/test_routed_audio.cpp new file mode 100644 index 0000000..87938bc --- /dev/null +++ b/tests/test_routed_audio.cpp @@ -0,0 +1,152 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#include +#include +#include +#include +#include + +#include + +#include "audio_player.hpp" +#include "audio_route.hpp" +#include "evo_log.hpp" + +struct Message { + uint16_t function; + uint32_t op; + std::vector data; +}; + +class Port : public evo::VmostPort { +public: + std::vector messages; + int send(evo::VmostMsgOut& m) override { + Message message = {m.fkt, m.op, std::vector(m.data, m.data + m.len)}; + messages.push_back(message); + return 0; + } + int shadow(uint8_t, uint8_t, bool) override { return 0; } + void pump(int) override {} +}; + +static void table(evo::AudioRoute& route, std::initializer_list active) { + std::vector bytes(2, 0); + for (uint16_t id : active) { + bytes.push_back(static_cast(id >> 8)); + bytes.push_back(static_cast(id)); + bytes.push_back(0); + } + evo::VmostMsgView message = {0, 3, 0, 0xC03, 0xC, static_cast(bytes.size()), &bytes[0]}; + route.onMessage(message); +} + +static void answer(evo::AudioRoute& route, const Message& sent) { + assert(sent.op == 6 && sent.data.size() == 4); + evo::VmostMsgView message = {0, 3, 0, sent.function, 0xD, 2, &sent.data[0]}; + route.onMessage(message); +} + +static void waitRequest(evo::AudioRoute& route, Port& port, size_t count) { + for (unsigned i = 0; i < 200 && port.messages.size() < count; ++i) { + route.tick(evo::monoMs(), port); + usleep(10000); + } + assert(port.messages.size() == count); +} + +int main(int argc, char** argv) { + assert(argc == 2); + void* lib = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL); + assert(lib); + typedef int (*Get)(); + typedef void (*Set)(int); + Get written = nullptr, promptWritten = nullptr; + Set error = nullptr; + *reinterpret_cast(&written) = dlsym(lib, "fake_audio_written"); + *reinterpret_cast(&promptWritten) = dlsym(lib, "fake_audio_prompt_written"); + *reinterpret_cast(&error) = dlsym(lib, "fake_audio_error"); + assert(written && promptWritten && error); + + evo::AudioRoute route; + Port port; + route.enable(true); + route.tick(evo::monoMs(), port); + table(route, {1}); + route.tick(evo::monoMs(), port); + assert(route.ready()); + evo::AudioPlayer player; + assert(player.startRouted(route, "test", "prompt", argv[1])); + const uint8_t voice[] = {1, 0, 2, 0}; + evo::AudioPlayer::stream(8, 1, 0, true, &player); + evo::AudioPlayer::data(8, 1, voice, sizeof(voice), 0, &player); + waitRequest(route, port, 2); + assert(port.messages.back().function == 0xC03); + table(route, {1}); + route.tick(evo::monoMs(), port); + assert(port.messages.back().function == 0x53 && port.messages.back().data[3] == 0x1A); + answer(route, port.messages.back()); + route.tick(evo::monoMs(), port); + table(route, {1, 0x31A}); + route.tick(evo::monoMs(), port); + for (unsigned i = 0; i < 200 && promptWritten() < 6; ++i) { + usleep(10000); + } + assert(promptWritten() == 6 && written() == 0); + + player.setCall(true); + evo::AudioPlayer::data(8, 1, voice, sizeof(voice), 0, &player); + usleep(50000); + assert(promptWritten() == 6); + route.tick(evo::monoMs() + 1100, port); + assert(port.messages.back().function == 0xC03); + table(route, {1, 0x31A}); + route.tick(evo::monoMs() + 1101, port); + assert(port.messages.back().function == 0x54); + answer(route, port.messages.back()); + route.tick(evo::monoMs() + 1102, port); + table(route, {1}); + route.tick(evo::monoMs() + 1103, port); + + player.setCall(false); + const uint8_t music[] = {1, 0, 2, 0, 3, 0, 4, 0}; + evo::AudioPlayer::stream(8, 1, 0, false, &player); + evo::AudioPlayer::stream(9, 2, 0, true, &player); + evo::AudioPlayer::data(9, 2, music, sizeof(music), 0, &player); + const size_t next = port.messages.size() + 1; + waitRequest(route, port, next); + table(route, {1}); + route.tick(evo::monoMs(), port); + assert(port.messages.back().function == 0x53 && port.messages.back().data[3] == 0x15); + answer(route, port.messages.back()); + route.tick(evo::monoMs(), port); + table(route, {0x315}); + route.tick(evo::monoMs(), port); + for (unsigned i = 0; i < 200 && written() < 2; ++i) { + usleep(10000); + } + assert(written() == 2 && player.failure() == 0); + error(-EIO); + evo::AudioPlayer::data(9, 2, music, sizeof(music), 0, &player); + for (unsigned i = 0; i < 200 && !player.failure(); ++i) { + usleep(10000); + } + assert(player.failure() == -EIO); + player.stop(); + + route.tick(evo::monoMs() + 1200, port); + table(route, {0x315}); + route.tick(evo::monoMs() + 1201, port); + assert(port.messages.back().function == 0x54); + answer(route, port.messages.back()); + route.tick(evo::monoMs() + 1202, port); + table(route, {}); + route.tick(evo::monoMs() + 1203, port); + assert(port.messages.back().function == 0x53); // the FM source was displaced by music + answer(route, port.messages.back()); + route.tick(evo::monoMs() + 1204, port); + route.finish(port); + dlclose(lib); + puts("PASS routed audio: FM prompt, call interruption, media and playback failure"); + return 0; +} diff --git a/tests/test_session_phone.cpp b/tests/test_session_phone.cpp index 194d634..8a2e444 100644 --- a/tests/test_session_phone.cpp +++ b/tests/test_session_phone.cpp @@ -262,6 +262,13 @@ void onMic(bool open, void*) { void onNav(uint16_t id, const uint8_t* body, size_t len, void*) { event(format("nav %04x ", id) + (len ? hex(body, len) : std::string("-"))); } +void onAudioData(uint8_t channel, uint32_t session, const uint8_t* pcm, size_t len, uint64_t pts, void*) { + event(format("audio data ch=%u session=%u pts=%llu ", channel, session, static_cast(pts)) + + hex(pcm, len)); +} +void onAudioStream(uint8_t channel, uint32_t session, uint32_t config, bool started, void*) { + event(format("audio stream ch=%u session=%u config=%u start=%d", channel, session, config, started ? 1 : 0)); +} // The golden was recorded on an M340i of 2019: the model and year come from a vehicle file, as on that car. char g_vehicleFile[96]; @@ -596,13 +603,17 @@ class Phone { struct Link { aa::AASession session; int phoneFd; - explicit Link(bool touch = true) : phoneFd(-1) { + explicit Link(bool touch = true, bool audio = false) : phoneFd(-1) { int fds[2]; if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) != 0) { fprintf(stderr, "FAIL socketpair\n"); exit(1); } watch(session, touch); + if (audio && !session.setAudioCallbacks(onAudioData, onAudioStream)) { + fprintf(stderr, "FAIL audio callbacks\n"); + exit(1); + } phoneFd = fds[1]; if (!session.start(fds[0])) { fprintf(stderr, "FAIL session start\n"); @@ -1124,6 +1135,112 @@ std::string audioFocusProtobuf() { return std::string(); } +std::string directAudioSession() { + std::vector log; + Link link(true, true); + Phone phone(link.phoneFd, log); + phone.handshake(); + phone.discover(); + takeEvents(); + phone.send(8, kSealed, bytes({0x80, 0x01, 0x08, 0x07, 0x10, 0x01})); + phone.send(8, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 3, 0x11, 0x22})); + phone.send(8, kSealed, bytes({0x80, 0x01, 0x08, 0x09})); + phone.send(9, kSealed, bytes({0x80, 0x01, 0x08, 0x0b})); + phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4})); + phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 5, 1, 2, 3})); + phone.send(8, kSealed, bytes({0x80, 0x02})); + phone.send(8, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 6, 1, 2})); + phone.settle(); + phone.headUnitPings(30, false); + const std::vector events = takeEvents(); + const std::vector expected = { + "audio stream ch=8 session=7 config=1 start=1", "audio data ch=8 session=7 pts=3 1122", + "audio stream ch=8 session=7 config=1 start=0", "audio stream ch=8 session=9 config=0 start=1", + "audio stream ch=9 session=11 config=0 start=1", "audio data ch=9 session=11 pts=4 01020304", + "audio stream ch=8 session=9 config=0 start=0", + }; + if (events != expected) { + return "unexpected audio start/data/stop callbacks"; + } + if (std::find(log.begin(), log.end(), "hu ch=9 fl=0b 8004 080b1001") == log.end()) { + return "media ack did not retain the stream session id"; + } + phone.leave(); + if (!waitEnded(link.session)) { + return "session did not end"; + } + link.session.stop(); + const std::vector endEvents = takeEvents(); + if (std::find(endEvents.begin(), endEvents.end(), "audio stream ch=9 session=11 config=0 start=0") == + endEvents.end()) { + return "active audio was not stopped on disconnect"; + } + return std::string(); +} + +std::string pacedAudioAcks() { + std::vector log; + Link link(true, true); + Phone phone(link.phoneFd, log); + phone.handshake(); + phone.discover(); + phone.send(9, kSealed, bytes({0x80, 0x01, 0x08, 0x05})); + Bytes pcm(57600, 0); // 300 ms of stereo 48 kHz S16LE + phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 1}) + pcm); + phone.settle(); + const std::string ack = "hu ch=9 fl=0b 8004 08051001"; + if (std::find(log.begin(), log.end(), ack) != log.end()) { + return "music was acknowledged before its playback duration"; + } + phone.headUnitPings(450, false); + if (std::count(log.begin(), log.end(), ack) != 1) { + return "paced music ack was not sent"; + } + phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 2}) + pcm); + phone.send(9, kSealed, bytes({0x80, 0x02})); + phone.settle(); + if (std::count(log.begin(), log.end(), ack) != 2) { + return "STOP did not flush the pending ack with its original session id"; + } + phone.leave(); + if (!waitEnded(link.session)) { + return "session did not end"; + } + return std::string(); +} + +std::string invalidAudioStart() { + const Bytes invalid[] = { + bytes({0x80, 0x01, 0x08, 0x01, 0x10, 0x02}), // unknown speech configuration + bytes({0x80, 0x01, 0x08, 0x01, 0x10, 0x80}), // truncated protobuf + bytes({0x80, 0x01, 0x08, 0x01, 0x12, 0x00}), // configuration has wrong wire type + }; + for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { + std::vector log; + Link link(true, true); + Phone phone(link.phoneFd, log); + phone.handshake(); + phone.discover(); + takeEvents(); + phone.send(8, kSealed, invalid[i]); + phone.untilClosed(); + if (!waitEnded(link.session)) { + return "invalid START did not end session"; + } + if (!link.session.audioFailed()) { + return "invalid START did not report an audio failure"; + } + link.session.stop(); + const std::vector events = takeEvents(); + for (size_t j = 0; j < events.size(); ++j) { + if (events[j].find("audio ") == 0) { + return "invalid START reached the playback callback"; + } + } + } + return std::string(); +} + // A phone that stops speaking by itself (iDrive has the screen, no music) keeps its session as long as it answers the // head unit's pings; one that answers nothing loses it within the 5 s silence limit, pings or not. Run on the clock, // so it is checked here and kept out of the golden. An empty verdict: passed. @@ -1818,6 +1935,12 @@ int main(int argc, char** argv) { } const std::string audioFocus = writing ? std::string() : audioFocusProtobuf(); takeEvents(); + const std::string directAudio = writing ? std::string() : directAudioSession(); + takeEvents(); + const std::string pacedAudio = writing ? std::string() : pacedAudioAcks(); + takeEvents(); + const std::string invalidAudio = writing ? std::string() : invalidAudioStart(); + takeEvents(); const std::string quiet = writing ? std::string() : quietPhone(); takeEvents(); const std::string broken = writing ? std::string() : brokenStream(); @@ -1878,6 +2001,21 @@ int main(int argc, char** argv) { return 1; } puts("PASS session, audio focus protobuf: decodes field 1 across field order and varint width"); + if (!directAudio.empty()) { + printf("FAIL session, direct audio: %s\n", directAudio.c_str()); + return 1; + } + puts("PASS session, direct audio: stream lifecycle, PCM, acks and disconnect"); + if (!pacedAudio.empty()) { + printf("FAIL session, paced audio: %s\n", pacedAudio.c_str()); + return 1; + } + puts("PASS session, paced audio: time-based acks and STOP flush"); + if (!invalidAudio.empty()) { + printf("FAIL session, invalid audio start: %s\n", invalidAudio.c_str()); + return 1; + } + puts("PASS session, invalid audio start: unsupported or malformed stream ends safely"); if (!quiet.empty()) { printf("FAIL session, quiet phone: %s\n", quiet.c_str()); return 1; diff --git a/tests/test_wireless_lifecycle.cpp b/tests/test_wireless_lifecycle.cpp index 6cfb556..08a45d9 100644 --- a/tests/test_wireless_lifecycle.cpp +++ b/tests/test_wireless_lifecycle.cpp @@ -3,13 +3,17 @@ // The service's wireless loop (wireless_loop) and app commands (service_app), with a fake Alps link and handshake. // The AA session runs on a socketpair. The peeks' timing on its own: tests/test_peek_timing.cpp. #include +#include +#include #include #include #include +#include #include #include #include +#include #include "alps_spp.hpp" #include "evo_ap.hpp" @@ -131,6 +135,156 @@ static bool linkClosedWithin(unsigned ms) { } return !fixtureLink; } + +static void usbAudioFailure(const char* library) { + void* fake = dlopen(library, RTLD_NOW | RTLD_LOCAL); + assert(fake); + typedef void (*SetError)(int); + SetError setError = nullptr; + *reinterpret_cast(&setError) = dlsym(fake, "fake_audio_error"); + assert(setError); + evo::ServiceApp app(50000, false, &quitFlag); + app.session.setDisconnectCallback(evo::ServiceApp::ended, &app); + assert(app.audioPlayer.start("test", library)); + app.directAudio = app.projectionOverUsb = true; + int pair[2]; + assert(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); + assert(app.session.start(pair[0])); + const uint8_t pcm[] = {1, 0, 2, 0}; + setError(-EIO); + evo::AudioPlayer::stream(9, 7, 0, true, &app.audioPlayer); + evo::AudioPlayer::data(9, 7, pcm, sizeof(pcm), 0, &app.audioPlayer); + for (unsigned i = 0; i < 200 && !app.audioPlayer.failure(); ++i) { + usleep(10000); + } + assert(app.audioPlayer.failure() == -EIO); + app.turn(false); + for (unsigned i = 0; i < 200 && app.session.isActive(); ++i) { + usleep(10000); + } + app.session.stop(); + assert(!app.session.isActive() && app.audioFallback && !app.directAudio && !app.session.phoneSaidGoodbye()); + app.audioPlayer.stop(); + close(pair[1]); + dlclose(fake); + puts("PASS USB audio failure: interrupted session, sticky Bluetooth fallback"); +} + +class AudioGatePort : public evo::VmostPort { +public: + uint16_t function; + std::vector data; + AudioGatePort() : function(0) {} + int send(evo::VmostMsgOut& message) override { + function = message.fkt; + data.assign(message.data, message.data + message.len); + return 0; + } + int shadow(uint8_t, uint8_t, bool) override { return 0; } + void pump(int) override {} +}; + +static void audioGateTable(evo::AudioRoute& route, bool active) { + const uint8_t bytes[] = {0, 0, 3, 0x15, 0}; + evo::VmostMsgView message = {0, 3, 0, 0xC03, 0xC, static_cast(active ? 5 : 2), bytes}; + route.onMessage(message); +} + +static void audioGateResult(evo::AudioRoute& route, AudioGatePort& port) { + assert(port.data.size() == 4); + evo::VmostMsgView message = {0, 3, 0, port.function, 0xD, 2, &port.data[0]}; + route.onMessage(message); +} + +struct AudioGateConnection { + evo::ServiceApp* app; + int fd; +}; + +static void* audioGateConnect(void* user) { + AudioGateConnection* connection = static_cast(user); + connection->app->usbPhoneReady(connection->fd); + return nullptr; +} + +static void usbAudioCleanupGate() { + evo::ServiceApp app(50000, false, &quitFlag); + AudioGatePort port; + app.markReady(); + app.audioFallback = true; + app.audioRoute.enable(true); + const uint32_t now = evo::monoMs(); + app.audioRoute.tick(now, port); + audioGateTable(app.audioRoute, false); + app.audioRoute.tick(now + 1, port); + app.audioRoute.request(0x315); + app.audioRoute.tick(now + 2, port); + audioGateTable(app.audioRoute, false); + app.audioRoute.tick(now + 3, port); + assert(port.function == 0x53); + audioGateResult(app.audioRoute, port); + app.audioRoute.tick(now + 4, port); + audioGateTable(app.audioRoute, true); + app.audioRoute.tick(now + 5, port); + assert(app.audioRoute.owns(0x315)); + app.audioRouteUsed = true; + app.audioRoute.request(0); + int pair[2]; + assert(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); + AudioGateConnection connection = {&app, pair[0]}; + pthread_t thread; + assert(pthread_create(&thread, nullptr, audioGateConnect, &connection) == 0); + for (unsigned i = 0; i < 200 && !app.projectionBusy(); ++i) { + usleep(10000); + } + usleep(100000); + assert(app.projectionBusy() && !app.session.isActive()); + app.audioRoute.tick(now + 1100, port); + audioGateTable(app.audioRoute, true); + app.audioRoute.tick(now + 1101, port); + assert(port.function == 0x54 && !app.session.isActive()); + audioGateResult(app.audioRoute, port); + app.audioRoute.tick(now + 1102, port); + audioGateTable(app.audioRoute, false); + app.audioRoute.tick(now + 1103, port); + pthread_join(thread, nullptr); + assert(app.session.isActive() && !app.audioRouteUsed); + app.session.stop(); + close(pair[1]); + + app.audioRoute.request(0x315); + app.audioRoute.tick(now + 1200, port); + audioGateTable(app.audioRoute, false); + app.audioRoute.tick(now + 1201, port); + assert(port.function == 0x53); + app.audioRouteUsed = true; + assert(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); + connection.fd = pair[0]; + assert(pthread_create(&thread, nullptr, audioGateConnect, &connection) == 0); + for (unsigned i = 0; i < 200 && !app.projectionBusy(); ++i) { + usleep(10000); + } + usleep(100000); + app.requestStop(); + pthread_join(thread, nullptr); + assert(!app.session.isActive() && !app.audioRoute.quiescent()); + close(pair[1]); + audioGateResult(app.audioRoute, port); + app.audioRoute.tick(now + 1202, port); + audioGateTable(app.audioRoute, true); + app.audioRoute.tick(now + 1203, port); + app.audioRoute.tick(now + 2203, port); + audioGateTable(app.audioRoute, true); + app.audioRoute.tick(now + 2204, port); + assert(port.function == 0x54); + audioGateResult(app.audioRoute, port); + app.audioRoute.tick(now + 2205, port); + audioGateTable(app.audioRoute, false); + app.audioRoute.tick(now + 2206, port); + assert(app.audioRoute.quiescent()); + app.audioRoute.finish(port); + puts("PASS USB audio cleanup: session waits for route release and stops safely"); +} // A session on a socketpair that ends by itself, without ByeBye: the phone's side of the connection closes. static void loseSession(evo::ServiceApp& app) { int pair[2]; @@ -400,4 +554,9 @@ int main() { "PASS actual wireless loop: no handshake during TCP preparation or active session, nor into the BMW app's link " "found then, rearmed after session stop, Bluetooth link closed after a lost wireless session; app commands and " "volume through the peeks; PC socketpair only"); + const char* audioLibrary = getenv("ENTRY_AAD_AUDIO_TEST_LIB"); + if (audioLibrary) { + usbAudioFailure(audioLibrary); + } + usbAudioCleanupGate(); } diff --git a/tools/evo_check.cpp b/tools/evo_check.cpp index 0d0c53e..a1b8539 100644 --- a/tools/evo_check.cpp +++ b/tools/evo_check.cpp @@ -14,6 +14,7 @@ #include #include "alps_spp.hpp" +#include "audio_probe.hpp" #include "evo_log.hpp" #include "evo_process.hpp" @@ -142,6 +143,7 @@ void context() { "/sys/class/graphics/fb0/modes", "/sys/bus/rpmsg/devices/rpmsg0/name", "/proc/bus/input/devices", + "/etc/asound.conf", "/proc/asound/cards", "/proc/asound/pcm"}; for (size_t i = 0; i < sizeof(paths) / sizeof(paths[0]) && !stopped; ++i) { @@ -169,11 +171,12 @@ void context() { } void usage() { puts( - "evo-check --scene | --context | --bluetooth | --monitor [seconds 1..60] | --help\n" + "evo-check --scene | --context | --audio-routes | --bluetooth | --monitor [seconds 1..60] | --help\n" "evo-check --dbus-names | --dbus-introspect | --dbus-watch [seconds 1..3600]\n" "Read and watch only: no UUID, configuration, surface or TCP port.\n" "--scene: IVI scene and candidate layers; each command is bounded to 2 seconds.\n" "--context: video, MOST, audio and inputs, network, ports and firewall, read only.\n" + "--audio-routes: read ConnectionMaster's audio connection table; no route is changed.\n" "--bluetooth: the Alps API, then spp_data_interface of instances 0 and 1.\n" "--monitor: bounded watch (30 seconds by default), Ctrl-C to end it.\n" "--dbus-names: system bus names, with the pid and command line of their process.\n" @@ -433,9 +436,10 @@ int main(int argc, char** argv) { } bool scene = (argc == 2 || argc == 3) && !strcmp(argv[1], "--scene"); // optional: another CLI (host tests) bool surroundings = argc == 2 && !strcmp(argv[1], "--context"); + bool audioRoutes = argc == 2 && !strcmp(argv[1], "--audio-routes"); bool bluetooth = argc == 2 && !strcmp(argv[1], "--bluetooth"); bool monitor = (argc == 2 || argc == 3) && !strcmp(argv[1], "--monitor"); - if (!scene && !surroundings && !bluetooth && !monitor) { + if (!scene && !surroundings && !audioRoutes && !bluetooth && !monitor) { usage(); return 2; } @@ -463,6 +467,18 @@ int main(int argc, char** argv) { context(); return stopped ? 1 : 0; } + if (audioRoutes) { + std::vector table; + if (!evo::readAudioRouteTable(table, 3000)) { + return 1; + } + printf("ConnectionMaster table: position %u, %u\n", table[0], table[1]); + for (size_t i = 2; i < table.size(); i += 3) { + printf(" route 0x%04x status %u\n", (table[i] << 8) | table[i + 1], table[i + 2]); + } + puts("Read only; no route was built or removed."); + return 0; + } if (scene) { const char* ctl = argc == 3 ? argv[2] : "/usr/bin/LayerManagerControl"; bool ok = command(ctl, "get", "scene"); From 82bd0acc5d9c272c3c792a5c361d13cdbaa831b1 Mon Sep 17 00:00:00 2001 From: mbalous Date: Sun, 29 Nov 2026 00:23:54 +0100 Subject: [PATCH 02/10] feat(audio): improve direct USB audio handling Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- core/aa_channels.cpp | 8 +-- core/aa_protocol.hpp | 9 ++- core/aa_session.cpp | 31 +++++---- core/aa_session.hpp | 10 +-- core/sdr_builder.cpp | 11 +++ docs/USB.md | 31 +++++---- platform/audio_mixer.hpp | 70 ++++++++++++------- platform/audio_player.cpp | 108 +++++++++++++++++++++++------- platform/audio_player.hpp | 9 ++- platform/audio_route.cpp | 3 + platform/main.cpp | 4 +- platform/service_app.cpp | 46 ++++++++----- platform/service_app.hpp | 2 +- platform/service_contract.hpp | 1 - tests/test_aa_messages.cpp | 1 + tests/test_audio_mixer.cpp | 8 +++ tests/test_evo_sdr.cpp | 6 +- tests/test_routed_audio.cpp | 29 ++++++++ tests/test_session_phone.cpp | 11 ++- tests/test_wireless_lifecycle.cpp | 33 +++++++-- 20 files changed, 312 insertions(+), 119 deletions(-) diff --git a/core/aa_channels.cpp b/core/aa_channels.cpp index 18ddf87..fb03613 100644 --- a/core/aa_channels.cpp +++ b/core/aa_channels.cpp @@ -321,7 +321,7 @@ void AASession::onStart(uint8_t channel, const Message& message) { giveUp(); return; } - const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + const unsigned index = channel::audioIndex(channel); mediaSessions_[channel] = audioSession; audioConfig_[index] = config; audioActive_[index] = true; @@ -331,7 +331,7 @@ void AASession::onStart(uint8_t channel, const Message& message) { void AASession::stopAudio(uint8_t channel) { flushAudioAcks(channel); - const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + const unsigned index = channel::audioIndex(channel); if (audioActive_[index]) { audioActive_[index] = false; audioStream_.fn(channel, mediaSessions_[channel], audioConfig_[index], false, audioStream_.user); @@ -350,12 +350,12 @@ void AASession::onMedia(uint8_t channel, uint16_t id, const Message& message) { } if (channel::isAudioSink(channel) && id == msg::kMediaData) { if (message.size() > kTimestampedHeader) { - const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + const unsigned index = channel::audioIndex(channel); uint32_t& count = audioMessages_[index]; ++count; if (count <= kAudioLoggedFirst || count % kAudioLogEvery == 0) { printf("[AASession] audio %s frame #%u: %u bytes PCM, pts=%llu\n", - channel == channel::kMediaAudio ? "media(ch9)" : "speech(ch8)", count, + index == 1 ? "media(ch9)" : index == 2 ? "system(ch16)" : "guidance(ch8)", count, static_cast(message.size() - kTimestampedHeader), static_cast(bigEndian64(&message[kMessageIdSize]))); } diff --git a/core/aa_protocol.hpp b/core/aa_protocol.hpp index 5deade2..a286dbc 100644 --- a/core/aa_protocol.hpp +++ b/core/aa_protocol.hpp @@ -24,9 +24,16 @@ const uint8_t kMediaAudio = 9; // removed from the discovery: media plays over const uint8_t kNavigation = 10; const uint8_t kMediaStatus = 12; const uint8_t kMicrophone = 14; +const uint8_t kSystemAudio = 16; inline bool isAudioSink(unsigned ch) { - return ch == kGuidanceAudio || ch == kMediaAudio; + return ch == kGuidanceAudio || ch == kMediaAudio || ch == kSystemAudio; +} +inline unsigned audioIndex(unsigned ch) { + return ch == kMediaAudio ? 1 : ch == kSystemAudio ? 2 : 0; +} +inline uint8_t audioChannel(unsigned index) { + return index == 1 ? kMediaAudio : index == 2 ? kSystemAudio : kGuidanceAudio; } // The streams the phone sends the car, where it holds at most kMaxUnacked media messages without an ack: the media // sinks of the service discovery. diff --git a/core/aa_session.cpp b/core/aa_session.cpp index 0cff610..12d9c21 100644 --- a/core/aa_session.cpp +++ b/core/aa_session.cpp @@ -96,9 +96,9 @@ AASession::AASession() pthread_mutex_init(&lifecycleLock_, nullptr); pthread_mutex_init(&socketLock_, nullptr); memset(mediaSessions_, 0, sizeof(mediaSessions_)); - audioMessages_[0] = audioMessages_[1] = 0; - audioActive_[0] = audioActive_[1] = false; - audioConfig_[0] = audioConfig_[1] = 0; + memset(audioMessages_, 0, sizeof(audioMessages_)); + memset(audioActive_, 0, sizeof(audioActive_)); + memset(audioConfig_, 0, sizeof(audioConfig_)); resetCounters(); } @@ -268,9 +268,10 @@ bool AASession::start(int client_fd) { microphoneChunks_ = 0; mediaMessages_ = 0; memset(mediaSessions_, 0, sizeof(mediaSessions_)); - audioMessages_[0] = audioMessages_[1] = 0; - audioAcks_[0].clear(); - audioAcks_[1].clear(); + memset(audioMessages_, 0, sizeof(audioMessages_)); + for (unsigned i = 0; i < 3; ++i) { + audioAcks_[i].clear(); + } lastReceivedMs_ = 0; // the previous thread is joined givenUp_ = false; versionTaken_ = false; @@ -352,10 +353,12 @@ void AASession::run() { void AASession::finish() { inbox_.stopLocation(); - audioAcks_[0].clear(); - audioAcks_[1].clear(); + for (unsigned i = 0; i < 3; ++i) { + audioAcks_[i].clear(); + } stopAudio(channel::kGuidanceAudio); stopAudio(channel::kMediaAudio); + stopAudio(channel::kSystemAudio); // This thread alone closes the socket, whether the session ended by itself or stop() asked; the ended callback // runs only in the first case. const bool endedByItself = clearRunning(); @@ -473,7 +476,7 @@ bool AASession::receiveExactly(uint8_t* to, size_t size) { } void AASession::deferAudioAck(uint8_t channel, uint32_t session, size_t pcmBytes, uint32_t sampleRate) { - const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + const unsigned index = channel::audioIndex(channel); std::deque& queue = audioAcks_[index]; if (queue.size() >= kMaxUnacked) { sendSealed(channel, message::mediaAck(queue.front().session)); @@ -481,7 +484,7 @@ void AASession::deferAudioAck(uint8_t channel, uint32_t session, size_t pcmBytes } const uint64_t now = monotonicUs(); const uint64_t start = !queue.empty() && queue.back().dueUs > now ? queue.back().dueUs : now; - const size_t frameBytes = index ? 4 : 2; + const size_t frameBytes = index == 1 ? 4 : 2; uint64_t duration = static_cast(pcmBytes / frameBytes) * 1000000ULL / sampleRate; if (duration > 500000) { duration = 500000; // the player retains at most 500 ms of any oversized frame @@ -491,9 +494,9 @@ void AASession::deferAudioAck(uint8_t channel, uint32_t session, size_t pcmBytes } void AASession::sendDueAudioAcks(uint64_t nowUs) { - for (unsigned index = 0; index < 2; ++index) { + for (unsigned index = 0; index < 3; ++index) { std::deque& queue = audioAcks_[index]; - const uint8_t channel = index ? channel::kMediaAudio : channel::kGuidanceAudio; + const uint8_t channel = channel::audioChannel(index); while (!queue.empty() && queue.front().dueUs <= nowUs) { const uint32_t session = queue.front().session; queue.pop_front(); @@ -505,7 +508,7 @@ void AASession::sendDueAudioAcks(uint64_t nowUs) { } void AASession::flushAudioAcks(uint8_t channel) { - const unsigned index = channel == channel::kMediaAudio ? 1 : 0; + const unsigned index = channel::audioIndex(channel); std::deque& queue = audioAcks_[index]; while (!queue.empty()) { const uint32_t session = queue.front().session; @@ -519,7 +522,7 @@ void AASession::flushAudioAcks(uint8_t channel) { uint64_t AASession::audioAckWaitUs(uint64_t nowUs) const { uint64_t delay = 1000000; - for (unsigned index = 0; index < 2; ++index) { + for (unsigned index = 0; index < 3; ++index) { if (!audioAcks_[index].empty()) { const uint64_t due = audioAcks_[index].front().dueUs; const uint64_t left = due > nowUs ? due - nowUs : 0; diff --git a/core/aa_session.hpp b/core/aa_session.hpp index e0a37b1..7b8469d 100644 --- a/core/aa_session.hpp +++ b/core/aa_session.hpp @@ -37,7 +37,7 @@ using MicRequestCallback = void (*)(bool, void*); // Navigation status (channel 10, ids from 0x8000): the message id, then its body. using NavStatusCallback = void (*)(uint16_t, const uint8_t*, size_t, void*); // PCM and stream lifecycle on the session thread. The receiver must copy data and return without blocking. -// Channel 8: mono S16LE, config 0 = 16 kHz, 1 = 48 kHz. Channel 9: stereo S16LE, config 0 = 48 kHz. +// Channel 8: mono 16/48 kHz; channel 9: stereo 48 kHz; channel 16: mono 16 kHz. All S16LE. using AudioDataCallback = void (*)(uint8_t, uint32_t, const uint8_t*, size_t, uint64_t, void*); using AudioStreamCallback = void (*)(uint8_t, uint32_t, uint32_t, bool, void*); @@ -212,14 +212,14 @@ class AASession { bool sendBroken_; // a send failed: nothing more goes out, the session ends (sendExactly) uint32_t mediaSessions_[256]; // per channel, the session id of its start indication, echoed in our acks uint32_t mediaMessages_; // media messages received, every channel - uint32_t audioMessages_[2]; // guidance (8), media (9) - bool audioActive_[2]; - uint32_t audioConfig_[2]; + uint32_t audioMessages_[3]; // guidance, media, system + bool audioActive_[3]; + uint32_t audioConfig_[3]; struct AudioAck { uint32_t session; uint64_t dueUs; }; - std::deque audioAcks_[2]; + std::deque audioAcks_[3]; uint32_t microphoneChunks_; // sent since the phone opened the microphone // Log throttles, per session. unsigned framesSeen_[256]; diff --git a/core/sdr_builder.cpp b/core/sdr_builder.cpp index 23e0871..3ab16ce 100644 --- a/core/sdr_builder.cpp +++ b/core/sdr_builder.cpp @@ -409,6 +409,17 @@ std::vector buildCarServiceDiscovery(const uint8_t* base, size_t baseLe } if (!directAudio) { retypeGuidanceSink(sdr); + } else { + Bytes format, sink, service; + pb::appendUint(format, 1, 16000); + pb::appendUint(format, 2, 16); + pb::appendUint(format, 3, 1); + pb::appendUint(sink, 1, 1); // PCM + pb::appendUint(sink, 2, kSystemAudio); + pb::appendMessage(sink, 3, format); + pb::appendUint(service, 1, channel::kSystemAudio); + pb::appendMessage(service, 3, sink); + pb::appendMessage(sdr, kServiceField, service); } return sdr; } diff --git a/docs/USB.md b/docs/USB.md index e73a0e3..a9d5385 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -4,24 +4,29 @@ faire d'Android Auto sans fil, ou quand le Wi-Fi de la voiture rame. L'état des essais est dans le [journal des versions](../CHANGELOG.md). -Avec le câble, l'image, les commandes, le micro, le GPS et le guidage passent par l'USB. Le service essaie aussi le -son direct par USB (musique et annonces), sans modifier les appels ni le micro. Il utilise les sorties -`entertainment` et `carplay_alt` et les routes audio observées sur un autre EntryNav2. - -**Le son direct n'a pas encore été vérifié en voiture sur cette version.** Si les sorties ou la lecture de la table -des routes ne sont pas disponibles, le service conserve le son Bluetooth. En cas d'erreur pendant une session directe, -il la relance en Bluetooth et conserve ce choix jusqu'à l'arrêt du service. Le service ne vérifie pas si le téléphone -est connecté en Bluetooth : vérifier la connexion média en cas de repli. Si la libération de la route audio ne peut pas -être confirmée, une nouvelle session est refusée plutôt que de risquer un conflit avec le son de la voiture. - -Pour forcer le Bluetooth dès le départ, Android Auto arrêté, créer `/var/local/data/AA/usb-bluetooth-audio` ; retirer -ce fichier pour réessayer le son direct au prochain démarrage. Le sans-fil garde son comportement Bluetooth actuel. +Avec le câble, l'image, les commandes, le micro, le GPS et le son Android Auto passent par l'USB. La musique et les +sons système utilisent la sortie ALSA `entertainment` et la route `0x315` ; le guidage utilise `carplay_alt` et +`0x31a`, même pendant la musique. Ces paires ont été rapportées audibles sur un autre EntryNav2 (BMW X1 F48, +[Jiraiya43/EntryNav2-Android-Auto#143](https://github.com/Jiraiya43/EntryNav2-Android-Auto/pull/143)), pas sur toutes +les variantes. Elles ne sont pas les identifiants `0x1d0` et A2I d'un NBT EVO QNX. +Le service essaie actuellement ce profil sans reconnaître la version de l'unité : sa compatibilité avec une autre +variante n'est pas établie. + +**Le son direct et ces routes n'ont pas encore été vérifiés sur cette voiture.** Il n'y a pas de repli automatique +vers Bluetooth : si le son direct ne peut pas démarrer ou échoue, la session USB est refusée ou interrompue ; arrêter +et redémarrer le service pour réessayer. Si la libération d'une route ne peut pas être confirmée, une nouvelle session +est refusée plutôt que de risquer un conflit avec le son de la voiture. Les appels restent gérés par le Bluetooth +mains libres de la voiture ; le sans-fil garde son comportement Bluetooth actuel. L'outil de développement `evo-check --audio-routes` lit la table des connexions audio sans construire ni supprimer de route ; `evo-check --context` relève notamment la configuration ALSA et la version du système. Ces relevés ne prouvent pas qu'une route soit utilisable. Le contexte contient aussi des informations réseau : les retirer avant de partager sa sortie. +Avant utilisation en route, vérifier voiture à l'arrêt : musique et volume, guidage pendant la radio et la musique, +Assistant et micro, appels mains libres et reprise, changement de source, puis arrêt et débranchement. Vérifier aussi +que l'écran Android Auto reste affiché après l'Assistant. Les essais PC et la compilation ne prouvent aucun de ces points. + ## Choisir le câble ou le sans-fil Dans le menu Android Auto de l'iDrive, cocher **Câble USB au lieu du sans-fil**, puis brancher le téléphone sur une @@ -85,5 +90,5 @@ case du menu retire le fichier, nom de prise compris : il est à réécrire ensu |---|---| | Rien ne se passe au branchement | Câble de données et non de charge seule. Sur le téléphone, choisir « Transfert de fichiers » dans la notification USB, puis rebrancher. | | Le téléphone affiche Android Auto mais pas l'iDrive | Débrancher, attendre 10 secondes, rebrancher. | -| Pas de son | Forcer le Bluetooth avec `usb-bluetooth-audio`, redémarrer Android Auto et vérifier que le téléphone est connecté à la voiture en média. | +| Pas de son | Relever la version du système, la configuration ALSA et la table des routes ; une sortie ouverte ou une route acceptée ne prouve pas qu'elle atteint les haut-parleurs. Redémarrer le service après une erreur. | | Toujours rien | Activer les journaux ([maintenance](MAINTENANCE.md)), reproduire, et joindre le journal du service à un ticket : les lignes `[UsbLoop]` et `[UsbBridge]` disent ce qui a été vu sur les prises. | diff --git a/platform/audio_mixer.hpp b/platform/audio_mixer.hpp index d360d1d..e9f0eca 100644 --- a/platform/audio_mixer.hpp +++ b/platform/audio_mixer.hpp @@ -16,12 +16,15 @@ class AudioMixer { public: static const size_t kCapacityFrames = 24000; // 500 ms at 48 kHz - AudioMixer() : media_(kCapacityFrames, 2), speech_(kCapacityFrames, 1) {} + AudioMixer() : media_(kCapacityFrames, 2), speech_(kCapacityFrames, 1), system_(kCapacityFrames, 1) {} void clearMedia() { media_.clear(); } void clearSpeech() { speech_.clear(); } + void clearSystem() { system_.clear(); } size_t mediaFrames() const { return media_.size(); } size_t speechFrames() const { return speech_.size(); } + size_t systemFrames() const { return system_.size(); } + size_t trimMedia(size_t keep) { return media_.trim(keep); } // Returns false for malformed PCM or an unsupported speech configuration. A full buffer discards oldest frames. bool pushMedia(const uint8_t* pcm, size_t bytes) { @@ -39,39 +42,28 @@ class AudioMixer { } bool pushSpeech(const uint8_t* pcm, size_t bytes, unsigned config) { - if (!pcm || !bytes || bytes % 2 || config > 1) { - return false; - } - const unsigned copies = config == 0 ? 3 : 1; - const size_t maxInputFrames = kCapacityFrames / copies; - if (bytes / 2 > maxInputFrames) { - pcm += bytes - maxInputFrames * 2; - bytes = maxInputFrames * 2; - } - for (size_t i = 0; i < bytes; i += 2) { - const int16_t value = sample(pcm + i); - for (unsigned n = 0; n < copies; ++n) { - speech_.push(value, 0); - } - } - return true; + return pushMono(speech_, pcm, bytes, config); } - // Stereo S16 output, at most maxFrames. Speech ducks media to 30%, with clipping after mixing. - size_t read(int16_t* out, size_t maxFrames, bool media = true, bool speech = true) { + bool pushSystem(const uint8_t* pcm, size_t bytes) { return pushMono(system_, pcm, bytes, 0); } + + // Stereo S16 output, at most maxFrames. Speech and system audio duck media. + size_t read(int16_t* out, size_t maxFrames, bool media = true, bool speech = true, bool system = true) { if (!out) { return 0; } size_t written = 0; - while (written < maxFrames && ((media && media_.size()) || (speech && speech_.size()))) { - int16_t left = 0, right = 0, voice = 0, unused = 0; + while (written < maxFrames && + ((media && media_.size()) || (speech && speech_.size()) || (system && system_.size()))) { + int16_t left = 0, right = 0, voice = 0, tone = 0, unused = 0; if (media) { media_.pop(left, right); } const bool speaking = speech && speech_.pop(voice, unused); - const int gain = speaking ? 30 : 100; - out[written * 2] = clamp((int(left) * gain) / 100 + voice); - out[written * 2 + 1] = clamp((int(right) * gain) / 100 + voice); + const bool sounding = system && system_.pop(tone, unused); + const int gain = speaking || sounding ? 30 : 100; + out[written * 2] = clamp((int(left) * gain) / 100 + voice + tone); + out[written * 2 + 1] = clamp((int(right) * gain) / 100 + voice + tone); ++written; } return written; @@ -84,6 +76,15 @@ class AudioMixer { : data_(frames * channels), channels_(channels), capacity_(frames), head_(0), size_(0) {} size_t size() const { return size_; } void clear() { head_ = size_ = 0; } + size_t trim(size_t keep) { + if (size_ <= keep) { + return 0; + } + const size_t dropped = size_ - keep; + head_ = (head_ + dropped) % capacity_; + size_ = keep; + return dropped; + } void push(int16_t left, int16_t right) { if (size_ == capacity_) { head_ = (head_ + 1) % capacity_; @@ -113,6 +114,25 @@ class AudioMixer { size_t channels_, capacity_, head_, size_; }; + static bool pushMono(Ring& ring, const uint8_t* pcm, size_t bytes, unsigned config) { + if (!pcm || !bytes || bytes % 2 || config > 1) { + return false; + } + const unsigned copies = config == 0 ? 3 : 1; + const size_t maxInputFrames = kCapacityFrames / copies; + if (bytes / 2 > maxInputFrames) { + pcm += bytes - maxInputFrames * 2; + bytes = maxInputFrames * 2; + } + for (size_t i = 0; i < bytes; i += 2) { + const int16_t value = sample(pcm + i); + for (unsigned n = 0; n < copies; ++n) { + ring.push(value, 0); + } + } + return true; + } + static int16_t sample(const uint8_t* pcm) { const uint16_t u = static_cast(pcm[0]) | (static_cast(pcm[1]) << 8); const int32_t signedValue = u < 0x8000 ? u : int32_t(u) - 0x10000; @@ -122,7 +142,7 @@ class AudioMixer { return static_cast(value > 32767 ? 32767 : value < -32768 ? -32768 : value); } - Ring media_, speech_; + Ring media_, speech_, system_; }; } // namespace evo diff --git a/platform/audio_player.cpp b/platform/audio_player.cpp index 4b9fcf3..c3be06d 100644 --- a/platform/audio_player.cpp +++ b/platform/audio_player.cpp @@ -12,11 +12,12 @@ namespace evo { AudioPlayer::AudioPlayer() - : route_(nullptr), thread_(0), started_(false), quit_(false), inCall_(false), generation_(0), failure_(0) { - active_[0] = active_[1] = false; - seen_[0] = seen_[1] = false; - sessions_[0] = sessions_[1] = configs_[0] = configs_[1] = 0; - lastData_[0] = lastData_[1] = 0; + : route_(nullptr), thread_(0), started_(false), quit_(false), inCall_(false), promptOpen_(false), generation_(0), + failure_(0) { + for (unsigned i = 0; i < 3; ++i) { + active_[i] = seen_[i] = false; + sessions_[i] = configs_[i] = lastData_[i] = 0; + } pthread_mutex_init(&mu_, nullptr); pthread_cond_init(&cv_, nullptr); } @@ -49,10 +50,14 @@ bool AudioPlayer::startRouted(AudioRoute& route, const char* mediaPcm, const cha if (!output_.open(mediaPcm, library)) { return false; } - if (!promptOutput_.open(promptPcm, library, 1)) { + if (!promptPcm || !*promptPcm || !library || !*library) { + ELOG("AudioPlayer", "missing prompt PCM or ALSA library"); output_.close(); return false; } + promptPcm_ = promptPcm; + library_ = library; + promptOpen_ = false; pthread_mutex_lock(&mu_); route_ = &route; pthread_mutex_unlock(&mu_); @@ -90,13 +95,16 @@ void AudioPlayer::stop() { route_->request(0); } route_ = nullptr; - active_[0] = active_[1] = false; - seen_[0] = seen_[1] = false; + for (unsigned i = 0; i < 3; ++i) { + active_[i] = seen_[i] = false; + } mixer_.clearMedia(); mixer_.clearSpeech(); + mixer_.clearSystem(); pthread_mutex_unlock(&mu_); output_.close(); promptOutput_.close(); + promptOpen_ = false; } void AudioPlayer::setCall(bool active) { @@ -105,7 +113,10 @@ void AudioPlayer::setCall(bool active) { inCall_ = active; mixer_.clearMedia(); mixer_.clearSpeech(); - seen_[0] = seen_[1] = false; + mixer_.clearSystem(); + for (unsigned i = 0; i < 3; ++i) { + seen_[i] = false; + } ++generation_; if (active && route_) { route_->prohibitRestore(); @@ -116,24 +127,44 @@ void AudioPlayer::setCall(bool active) { pthread_mutex_unlock(&mu_); } +void AudioPlayer::endSession() { + pthread_mutex_lock(&mu_); + for (unsigned i = 0; i < 3; ++i) { + active_[i] = seen_[i] = false; + } + mixer_.clearMedia(); + mixer_.clearSpeech(); + mixer_.clearSystem(); + ++generation_; + if (route_) { + route_->request(0); + } + pthread_cond_signal(&cv_); + pthread_mutex_unlock(&mu_); +} + void AudioPlayer::stream(uint8_t channel, uint32_t session, uint32_t config, bool started, void* user) { AudioPlayer* self = static_cast(user); if (!self || !aa::channel::isAudioSink(channel)) { ELOG("AudioPlayer", "invalid stream callback"); return; } - const unsigned index = channel == aa::channel::kMediaAudio ? 1 : 0; + const unsigned index = aa::channel::audioIndex(channel); pthread_mutex_lock(&self->mu_); self->active_[index] = started; self->seen_[index] = false; self->sessions_[index] = session; self->configs_[index] = config; - if (index) { - self->mixer_.clearMedia(); - } else { - self->mixer_.clearSpeech(); + if (started || index == 1) { + if (index == 1) { + self->mixer_.clearMedia(); + } else if (index == 2) { + self->mixer_.clearSystem(); + } else { + self->mixer_.clearSpeech(); + } + ++self->generation_; } - ++self->generation_; pthread_cond_signal(&self->cv_); pthread_mutex_unlock(&self->mu_); } @@ -144,7 +175,7 @@ void AudioPlayer::data(uint8_t channel, uint32_t session, const uint8_t* pcm, si ELOG("AudioPlayer", "invalid PCM callback"); return; } - const unsigned index = channel == aa::channel::kMediaAudio ? 1 : 0; + const unsigned index = aa::channel::audioIndex(channel); if (pthread_mutex_trylock(&self->mu_) != 0) { ELOG("AudioPlayer", "PCM dropped while playback buffer is busy"); return; @@ -154,8 +185,9 @@ void AudioPlayer::data(uint8_t channel, uint32_t session, const uint8_t* pcm, si return; } if (self->active_[index] && self->sessions_[index] == session) { - const bool ok = - index ? self->mixer_.pushMedia(pcm, bytes) : self->mixer_.pushSpeech(pcm, bytes, self->configs_[index]); + const bool ok = index == 1 ? self->mixer_.pushMedia(pcm, bytes) + : index == 2 ? self->mixer_.pushSystem(pcm, bytes) + : self->mixer_.pushSpeech(pcm, bytes, self->configs_[index]); if (ok) { self->lastData_[index] = monoMs(); self->seen_[index] = true; @@ -181,6 +213,7 @@ void AudioPlayer::run() { uint32_t stalledSince = 0; bool stalled = false; uint16_t selected = 0; + bool granted = false; for (;;) { pthread_mutex_lock(&mu_); if (generation != generation_) { @@ -188,12 +221,11 @@ void AudioPlayer::run() { generation = generation_; stalled = false; const bool quit = quit_; - const bool routed = route_ != nullptr; pthread_mutex_unlock(&mu_); if (quit) { break; } - if (!output_.flush() || (routed && !promptOutput_.flush())) { + if (!output_.flush() || (promptOpen_ && !promptOutput_.flush())) { failure_.store(-EIO); break; } @@ -203,12 +235,23 @@ void AudioPlayer::run() { const uint32_t now = monoMs(); uint16_t wanted = 0; if (!inCall_) { - if (mixer_.mediaFrames() || (active_[1] && seen_[1] && now - lastData_[1] < 1000)) { - wanted = 0x315; - } else if (mixer_.speechFrames() || (active_[0] && seen_[0] && now - lastData_[0] < 1000)) { + if (mixer_.speechFrames() || (active_[0] && seen_[0] && now - lastData_[0] < 300)) { wanted = 0x31A; + } else if (mixer_.mediaFrames() || mixer_.systemFrames() || + (active_[1] && seen_[1] && now - lastData_[1] < 1000) || + (active_[2] && seen_[2] && now - lastData_[2] < 300)) { + wanted = 0x315; } } + if (wanted == 0x31A && !promptOpen_) { + pthread_mutex_unlock(&mu_); + if (!promptOutput_.open(promptPcm_.c_str(), library_.c_str(), 1)) { + failure_.store(-EIO); + break; + } + promptOpen_ = true; + continue; + } route_->request(wanted); if (route_->failure()) { failure_.store(-EIO); @@ -217,10 +260,11 @@ void AudioPlayer::run() { } if (selected != wanted) { selected = wanted; + granted = false; count = offset = 0; stalled = false; pthread_mutex_unlock(&mu_); - if (!output_.flush() || !promptOutput_.flush()) { + if (!output_.flush() || (promptOpen_ && !promptOutput_.flush())) { failure_.store(-EIO); break; } @@ -244,9 +288,20 @@ void AudioPlayer::run() { } continue; } + if (!granted) { + granted = true; + if (wanted == 0x315) { + const size_t dropped = mixer_.trimMedia(9600); // 200 ms at 48 kHz + if (dropped) { + ELOG("AudioPlayer", "trimmed %u stale media frames after route grant", + static_cast(dropped)); + } + } + } } while (!quit_ && offset == count) { - count = mixer_.read(samples, 480, !route_ || selected == 0x315, true); + count = mixer_.read(samples, 480, !route_ || selected == 0x315, !route_ || selected == 0x31A, + !route_ || selected == 0x315); offset = 0; if (count) { if (route_ && selected == 0x31A) { @@ -297,6 +352,9 @@ void AudioPlayer::run() { break; } } + if (route_) { + route_->request(0); + } } } // namespace evo diff --git a/platform/audio_player.hpp b/platform/audio_player.hpp index d183fb4..91b23c2 100644 --- a/platform/audio_player.hpp +++ b/platform/audio_player.hpp @@ -9,6 +9,7 @@ #include #include +#include #include "audio_mixer.hpp" #include "audio_output.hpp" @@ -24,11 +25,12 @@ class AudioPlayer { AudioPlayer(const AudioPlayer&) = delete; AudioPlayer& operator=(const AudioPlayer&) = delete; - // Called before session discovery. False leaves the caller free to select Bluetooth instead. + // Called before session discovery. False means direct playback is unavailable. bool start(const char* pcm, const char* library = "libasound.so.2"); bool startRouted(AudioRoute& route, const char* mediaPcm, const char* promptPcm, const char* library = "libasound.so.2"); void stop(); + void endSession(); int failure() const { return failure_.load(); } void setCall(bool active); @@ -45,11 +47,12 @@ class AudioPlayer { AudioOutput promptOutput_; AudioMixer mixer_; AudioRoute* route_; + std::string promptPcm_, library_; pthread_mutex_t mu_; pthread_cond_t cv_; pthread_t thread_; - bool started_, quit_, active_[2], inCall_, seen_[2]; - uint32_t sessions_[2], configs_[2], generation_, lastData_[2]; + bool started_, quit_, active_[3], inCall_, seen_[3], promptOpen_; + uint32_t sessions_[3], configs_[3], generation_, lastData_[3]; std::atomic failure_; }; diff --git a/platform/audio_route.cpp b/platform/audio_route.cpp index c5f0c61..1096860 100644 --- a/platform/audio_route.cpp +++ b/platform/audio_route.cpp @@ -119,6 +119,8 @@ void AudioRoute::call(Phase phase, uint16_t route, uint32_t now, VmostPort& port phase_ = phase; received_ = false; timedOut_ = false; + ELOG("AudioRoute", "%s connection 0x%x (handle 0x%x)", phase == kRemove ? "releasing" : "building", route, + handle_); sentAt_ = now; if (port.send(m) != 0) { fail("route request refused by vMOST"); @@ -199,6 +201,7 @@ void AudioRoute::tick(uint32_t now, VmostPort& port) { fail("built route is not active in the table"); } else if (!failure_.load() && enabled_.load() && desired_.load() == route_) { usable_.store(route_); + ELOG("AudioRoute", "connection 0x%x granted and present in the table", route_); } nextPoll_ = now + kPollMs; phase_ = kPlaying; diff --git a/platform/main.cpp b/platform/main.cpp index 535c724..e8f551d 100644 --- a/platform/main.cpp +++ b/platform/main.cpp @@ -334,7 +334,7 @@ int main(int argc, char** argv) { } evo::ServiceApp app(kAaPort, video, &quit); evo::VmostPeerPair mostPeers(app.audioRoute, app.kombiMost); - app.audioRoute.enable(usb && access(evo::contract::kUsbBluetoothAudio, F_OK) != 0); + app.audioRoute.enable(usb); app.videoConfig.setDisplay(display.canvasWidth, display.canvasHeight, display.width, display.height, display.shownWidth, display.shownHeight); app.videoConfig.holdCloseFrames = !usb; // pairs come from the Wi-Fi's bursts, not the cable @@ -472,7 +472,7 @@ int main(int argc, char** argv) { if (!knob.start(input, evo::ServiceApp::knobEvent, &app)) { ELOG("Main", "controller unavailable for this run"); } - } else if (usb && access(evo::contract::kUsbBluetoothAudio, F_OK) != 0) { + } else if (usb) { knob.setPeer(&mostPeers); if (!knob.start(input, nullptr, nullptr)) { ELOG("Main", "vMOST unavailable for direct audio"); diff --git a/platform/service_app.cpp b/platform/service_app.cpp index 3b337b1..d8144a9 100644 --- a/platform/service_app.cpp +++ b/platform/service_app.cpp @@ -42,7 +42,7 @@ ServiceApp::ServiceApp(uint16_t p, bool v, std::atomic* quit) wppAccepted(false), projectionOverUsb(false), directAudio(false), - audioFallback(false), + audioBlocked(false), audioRouteUsed(false), audioCleanupRequested(false), lostWireless(0), @@ -153,17 +153,16 @@ ServiceApp::Turn ServiceApp::turn(bool service) { Turn t; if (audioPlayer.failure() && pthread_mutex_trylock(&connectMu) == 0) { pthread_mutex_lock(&mu); - const bool fallback = directAudio && session.isActive(); - if (fallback) { + const bool failed = directAudio && session.isActive(); + if (failed) { directAudio = false; - audioFallback = true; + audioBlocked = true; } pthread_mutex_unlock(&mu); - if (fallback) { - ELOG("ServiceApp", - "direct audio failed (%d): restarting USB in Bluetooth mode for this run; Bluetooth media " - "connection is not checked", + if (failed) { + ELOG("ServiceApp", "USB direct audio failed (%d); stopping session, restart service to retry", audioPlayer.failure()); + audioRoute.request(0); session.requestDisconnect(); } pthread_mutex_unlock(&connectMu); @@ -493,6 +492,7 @@ void ServiceApp::ended(void* user) { ServiceApp* a = static_cast(user); // No stop()/join here: this callback runs on the AA session thread. a->mic.request(false); + a->audioPlayer.endSession(); a->kombi.onSessionEnded(); a->kombiMost.onSessionEnded(); const bool goodbye = a->session.phoneSaidGoodbye(); @@ -500,7 +500,7 @@ void ServiceApp::ended(void* user) { const bool audioFailed = a->projectionOverUsb && a->directAudio && (a->session.audioFailed() || a->audioPlayer.failure() != 0); if (audioFailed) { - a->audioFallback = true; + a->audioBlocked = true; } a->directAudio = false; a->focus = false; @@ -513,7 +513,8 @@ void ServiceApp::ended(void* user) { } pthread_mutex_unlock(&a->mu); if (audioFailed) { - ELOG("ServiceApp", "direct audio failed: next USB session uses Bluetooth; media connection is not checked"); + a->audioRoute.request(0); + ELOG("ServiceApp", "USB direct audio failed; restart the service to retry"); } a->server.notifySessionEnded(); ELOG("ServiceApp", "session ended%s", goodbye ? " (the phone said goodbye)" : lost ? " (lost)" : ""); @@ -536,9 +537,12 @@ void ServiceApp::startProjection(int fd, bool overUsb) { return; } pthread_mutex_lock(&a->mu); - bool ready = a->ready; + bool ready = a->ready && (!overUsb || !a->audioBlocked); pthread_mutex_unlock(&a->mu); if (!ready) { + if (overUsb) { + ELOG("ServiceApp", "USB session refused: service not ready or direct audio is blocked"); + } close(fd); a->server.notifySessionEnded(); pthread_mutex_unlock(&a->connectMu); @@ -589,7 +593,7 @@ void ServiceApp::startProjection(int fd, bool overUsb) { } a->audioRouteUsed = false; a->audioCleanupRequested = false; - a->audioRoute.enable(true); + a->audioRoute.enable(overUsb); } bool videoOk = true; if (a->videoEnabled) { @@ -615,15 +619,12 @@ void ServiceApp::startProjection(int fd, bool overUsb) { ELOG("ServiceApp", "Android Auto starts aside: the iDrive app shows it once iDrive is on its page"); } bool direct = false; - pthread_mutex_lock(&a->mu); - const bool mayTryAudio = overUsb && !a->audioFallback && access(contract::kUsbBluetoothAudio, F_OK) != 0; - pthread_mutex_unlock(&a->mu); for (unsigned waited = 0; - mayTryAudio && !a->audioRoute.ready() && !a->audioRoute.failure() && waited < 2000 && !a->stopRequested(); + overUsb && !a->audioRoute.ready() && !a->audioRoute.failure() && waited < 2000 && !a->stopRequested(); waited += 50) { usleep(50000); } - if (mayTryAudio && a->audioRoute.ready()) { + if (overUsb && a->audioRoute.ready()) { direct = a->audioPlayer.startRouted(a->audioRoute, "entertainment", "carplay_alt"); if (direct) { a->audioRouteUsed = true; @@ -632,7 +633,16 @@ void ServiceApp::startProjection(int fd, bool overUsb) { } } if (overUsb && !direct) { - ELOG("ServiceApp", "USB audio uses Bluetooth; verify that Bluetooth media is connected (not checked here)"); + ELOG("ServiceApp", "USB direct audio setup failed (route ready=%d, error=%d); restart service to retry", + a->audioRoute.ready(), a->audioRoute.failure()); + close(fd); + a->server.notifySessionEnded(); + pthread_mutex_lock(&a->mu); + a->audioBlocked = true; + a->tcpPreparing = false; + pthread_mutex_unlock(&a->mu); + pthread_mutex_unlock(&a->connectMu); + return; } pthread_mutex_lock(&a->mu); a->directAudio = direct; diff --git a/platform/service_app.hpp b/platform/service_app.hpp index 1c4ef18..33292e5 100644 --- a/platform/service_app.hpp +++ b/platform/service_app.hpp @@ -142,7 +142,7 @@ class ServiceApp : public WirelessHost, public UsbHost { std::atomic videoFrames; // counted on the session thread without mu bool wppReply, wppAccepted; bool projectionOverUsb; // the last session came over USB (its loss is not the wireless loop's business) - bool directAudio, audioFallback; // under mu: fallback lasts for this service run + bool directAudio, audioBlocked; // under mu: persistent audio failure requires a service restart bool audioRouteUsed, audioCleanupRequested; // under connectMu: cleanup before another session unsigned lostWireless; // wireless sessions ended without ByeBye, and connections refused for 802.11n (#203) unsigned htRebuilds; // beacon rebuilds in a row for a phone on 802.11n; under connectMu diff --git a/platform/service_contract.hpp b/platform/service_contract.hpp index fc981d7..17ae274 100644 --- a/platform/service_contract.hpp +++ b/platform/service_contract.hpp @@ -34,7 +34,6 @@ constexpr char kKombiSingle[] = "/var/local/data/AA/kombi-single-maneuver"; // Present: Android Auto over a USB cable instead of wireless. Empty, or the one USB port to use ("1-1"). constexpr char kUsb[] = "/var/local/data/AA/usb"; // Present: USB projection keeps the existing Bluetooth audio path. -constexpr char kUsbBluetoothAudio[] = "/var/local/data/AA/usb-bluetooth-audio"; constexpr char kAppLog[] = "/var/local/data/AA/app.log"; constexpr char kAppLogOld[] = "/var/local/data/AA/app.old.log"; // The service's log in the maintenance profile, kept across the car's sleep (kept_log.hpp). diff --git a/tests/test_aa_messages.cpp b/tests/test_aa_messages.cpp index df05196..6a3d610 100644 --- a/tests/test_aa_messages.cpp +++ b/tests/test_aa_messages.cpp @@ -108,6 +108,7 @@ void routes() { CHECK(routeOf(1, 0x8000) == Route::kSetup); CHECK(routeOf(8, 0x8001) == Route::kStart && routeOf(14, 0x8001) == Route::kStart); CHECK(routeOf(8, 0x8002) == Route::kAudioStop && routeOf(9, 0x8002) == Route::kAudioStop); + CHECK(routeOf(16, 0x8002) == Route::kAudioStop && routeOf(16, 0x0000) == Route::kMedia); CHECK(routeOf(3, 0x8002) == Route::kInputBinding && routeOf(5, 0x8002) == Route::kInputBinding); CHECK(routeOf(7, 0x8002) == Route::kInputBinding); CHECK(routeOf(2, 0x8002) == Route::kOther && routeOf(0, 0x8002) == Route::kControl); diff --git a/tests/test_audio_mixer.cpp b/tests/test_audio_mixer.cpp index 380365c..b9b1f59 100644 --- a/tests/test_audio_mixer.cpp +++ b/tests/test_audio_mixer.cpp @@ -37,6 +37,14 @@ int main() { std::vector rest(evo::AudioMixer::kCapacityFrames * 2); assert(mixer.read(rest.data(), evo::AudioMixer::kCapacityFrames) == evo::AudioMixer::kCapacityFrames - 1); assert(rest[(evo::AudioMixer::kCapacityFrames - 2) * 2] == 2); + assert(mixer.pushMedia(music, sizeof(music))); + assert(mixer.trimMedia(2) == 2 && mixer.mediaFrames() == 2 && mixer.trimMedia(2) == 0); + assert(mixer.pushSystem(speech, sizeof(speech))); + assert(mixer.read(out, 3, true, false, true) == 3); + assert(out[0] == 1300 && out[1] == 700); + assert(out[4] == 1000 && out[5] == 1000); + mixer.clearSystem(); + assert(mixer.read(out, 1) == 0); puts("PASS audio mixer: bounds, formats, voice ducking, clipping and stream clear"); return 0; } diff --git a/tests/test_evo_sdr.cpp b/tests/test_evo_sdr.cpp index 79a6147..991edca 100644 --- a/tests/test_evo_sdr.cpp +++ b/tests/test_evo_sdr.cpp @@ -250,10 +250,14 @@ int main() { const std::vector directAudio = aa::buildCarServiceDiscovery(kDhuSdpProtobuf, kDhuSdpProtobufLen, nullptr, nullptr, aa::DisplayPlan(), nullptr, aa::DriverPosition::kLeft, nullptr, true); - std::vector sink8, sink9, speechSettings, template8, template9; + std::vector sink8, sink9, sink16, systemSettings, systemFormat, speechSettings, template8, template9; CHECK(service(directAudio, 8, sink8) && service(directAudio, 9, sink9)); CHECK(service(orig, 8, template8) && service(orig, 9, template9)); CHECK(sink8 == template8 && sink9 == template9); + CHECK(service(directAudio, 16, sink16) && sub(sink16, 3, systemSettings)); + CHECK(value(systemSettings, 1) == 1 && value(systemSettings, 2) == 2 && sub(systemSettings, 3, systemFormat)); + CHECK(value(systemFormat, 1) == 16000 && value(systemFormat, 2) == 16 && value(systemFormat, 3) == 1); + CHECK(!service(leftPetrol, 16, sink16)); CHECK(!service(leftPetrol, 9, sink9) && service(leftPetrol, 8, sink8) && sub(sink8, 3, speechSettings)); CHECK(value(speechSettings, 2) == 2); CHECK(values(leftPetrol, 6) == std::vector({0})); diff --git a/tests/test_routed_audio.cpp b/tests/test_routed_audio.cpp index 87938bc..c1513c2 100644 --- a/tests/test_routed_audio.cpp +++ b/tests/test_routed_audio.cpp @@ -80,6 +80,7 @@ int main(int argc, char** argv) { const uint8_t voice[] = {1, 0, 2, 0}; evo::AudioPlayer::stream(8, 1, 0, true, &player); evo::AudioPlayer::data(8, 1, voice, sizeof(voice), 0, &player); + evo::AudioPlayer::stream(8, 1, 0, false, &player); // the route may be granted after STOP waitRequest(route, port, 2); assert(port.messages.back().function == 0xC03); table(route, {1}); @@ -146,6 +147,34 @@ int main(int argc, char** argv) { answer(route, port.messages.back()); route.tick(evo::monoMs() + 1204, port); route.finish(port); + evo::AudioRoute missingPromptRoute; + evo::AudioPlayer missingPrompt; + assert(missingPrompt.startRouted(missingPromptRoute, "test", "missing", argv[1])); + evo::AudioPlayer::stream(8, 3, 0, true, &missingPrompt); + evo::AudioPlayer::data(8, 3, voice, sizeof(voice), 0, &missingPrompt); + for (unsigned i = 0; i < 200 && !missingPrompt.failure(); ++i) { + usleep(10000); + } + assert(missingPrompt.failure() == -EIO); + missingPrompt.stop(); + + evo::AudioRoute endedRoute; + Port endedPort; + endedRoute.enable(true); + endedRoute.tick(evo::monoMs(), endedPort); + table(endedRoute, {1}); + endedRoute.tick(evo::monoMs(), endedPort); + evo::AudioPlayer endedPlayer; + assert(endedPlayer.startRouted(endedRoute, "test", "prompt", argv[1])); + evo::AudioPlayer::stream(8, 4, 0, true, &endedPlayer); + evo::AudioPlayer::data(8, 4, voice, sizeof(voice), 0, &endedPlayer); + waitRequest(endedRoute, endedPort, 2); + endedPlayer.endSession(); + table(endedRoute, {1}); + endedRoute.tick(evo::monoMs(), endedPort); + assert(endedPort.messages.back().function == 0xC03); // no build after the session ended + endedPlayer.stop(); + endedRoute.finish(endedPort); dlclose(lib); puts("PASS routed audio: FM prompt, call interruption, media and playback failure"); return 0; diff --git a/tests/test_session_phone.cpp b/tests/test_session_phone.cpp index 8a2e444..6f46874 100644 --- a/tests/test_session_phone.cpp +++ b/tests/test_session_phone.cpp @@ -1148,6 +1148,9 @@ std::string directAudioSession() { phone.send(9, kSealed, bytes({0x80, 0x01, 0x08, 0x0b})); phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 3, 4})); phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 5, 1, 2, 3})); + phone.send(16, kSealed, bytes({0x80, 0x01, 0x08, 0x0c})); + phone.send(16, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 7, 0x33, 0x44})); + phone.send(16, kSealed, bytes({0x80, 0x02})); phone.send(8, kSealed, bytes({0x80, 0x02})); phone.send(8, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 6, 1, 2})); phone.settle(); @@ -1157,6 +1160,8 @@ std::string directAudioSession() { "audio stream ch=8 session=7 config=1 start=1", "audio data ch=8 session=7 pts=3 1122", "audio stream ch=8 session=7 config=1 start=0", "audio stream ch=8 session=9 config=0 start=1", "audio stream ch=9 session=11 config=0 start=1", "audio data ch=9 session=11 pts=4 01020304", + "audio stream ch=16 session=12 config=0 start=1", "audio data ch=16 session=12 pts=7 3344", + "audio stream ch=16 session=12 config=0 start=0", "audio stream ch=8 session=9 config=0 start=0", }; if (events != expected) { @@ -1165,6 +1170,9 @@ std::string directAudioSession() { if (std::find(log.begin(), log.end(), "hu ch=9 fl=0b 8004 080b1001") == log.end()) { return "media ack did not retain the stream session id"; } + if (std::count(log.begin(), log.end(), "hu ch=16 fl=0b 8004 080c1001") != 1) { + return "system audio ack did not retain its stream session id"; + } phone.leave(); if (!waitEnded(link.session)) { return "session did not end"; @@ -1214,6 +1222,7 @@ std::string invalidAudioStart() { bytes({0x80, 0x01, 0x08, 0x01, 0x10, 0x02}), // unknown speech configuration bytes({0x80, 0x01, 0x08, 0x01, 0x10, 0x80}), // truncated protobuf bytes({0x80, 0x01, 0x08, 0x01, 0x12, 0x00}), // configuration has wrong wire type + bytes({0x80, 0x01, 0x08, 0x01, 0x10, 0x01}), // system only offers configuration 0 }; for (size_t i = 0; i < sizeof(invalid) / sizeof(invalid[0]); ++i) { std::vector log; @@ -1222,7 +1231,7 @@ std::string invalidAudioStart() { phone.handshake(); phone.discover(); takeEvents(); - phone.send(8, kSealed, invalid[i]); + phone.send(i == 3 ? 16 : 8, kSealed, invalid[i]); phone.untilClosed(); if (!waitEnded(link.session)) { return "invalid START did not end session"; diff --git a/tests/test_wireless_lifecycle.cpp b/tests/test_wireless_lifecycle.cpp index 08a45d9..4a994c0 100644 --- a/tests/test_wireless_lifecycle.cpp +++ b/tests/test_wireless_lifecycle.cpp @@ -163,11 +163,27 @@ static void usbAudioFailure(const char* library) { usleep(10000); } app.session.stop(); - assert(!app.session.isActive() && app.audioFallback && !app.directAudio && !app.session.phoneSaidGoodbye()); + assert(!app.session.isActive() && app.audioBlocked && !app.directAudio && !app.session.phoneSaidGoodbye()); app.audioPlayer.stop(); close(pair[1]); dlclose(fake); - puts("PASS USB audio failure: interrupted session, sticky Bluetooth fallback"); + puts("PASS USB audio failure: interrupted session, no playback fallback"); +} + +static void usbAudioUnavailable() { + evo::ServiceApp app(50000, false, &quitFlag); + app.markReady(); + app.audioRoute.enable(true); + app.audioRoute.connectionLost(); + int pair[2]; + assert(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); + app.usbPhoneReady(pair[0]); + assert(app.audioBlocked && !app.directAudio && !app.session.isActive()); + close(pair[1]); + assert(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); + app.usbPhoneReady(pair[0]); + assert(app.audioBlocked && !app.session.isActive()); + close(pair[1]); } class AudioGatePort : public evo::VmostPort { @@ -199,11 +215,16 @@ static void audioGateResult(evo::AudioRoute& route, AudioGatePort& port) { struct AudioGateConnection { evo::ServiceApp* app; int fd; + bool usb; }; static void* audioGateConnect(void* user) { AudioGateConnection* connection = static_cast(user); - connection->app->usbPhoneReady(connection->fd); + if (connection->usb) { + connection->app->usbPhoneReady(connection->fd); + } else { + evo::ServiceApp::connected(connection->fd, connection->app); + } return nullptr; } @@ -211,7 +232,6 @@ static void usbAudioCleanupGate() { evo::ServiceApp app(50000, false, &quitFlag); AudioGatePort port; app.markReady(); - app.audioFallback = true; app.audioRoute.enable(true); const uint32_t now = evo::monoMs(); app.audioRoute.tick(now, port); @@ -231,7 +251,7 @@ static void usbAudioCleanupGate() { app.audioRoute.request(0); int pair[2]; assert(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); - AudioGateConnection connection = {&app, pair[0]}; + AudioGateConnection connection = {&app, pair[0], false}; pthread_t thread; assert(pthread_create(&thread, nullptr, audioGateConnect, &connection) == 0); for (unsigned i = 0; i < 200 && !app.projectionBusy(); ++i) { @@ -252,6 +272,7 @@ static void usbAudioCleanupGate() { app.session.stop(); close(pair[1]); + app.audioRoute.enable(true); app.audioRoute.request(0x315); app.audioRoute.tick(now + 1200, port); audioGateTable(app.audioRoute, false); @@ -260,6 +281,7 @@ static void usbAudioCleanupGate() { app.audioRouteUsed = true; assert(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); connection.fd = pair[0]; + connection.usb = true; assert(pthread_create(&thread, nullptr, audioGateConnect, &connection) == 0); for (unsigned i = 0; i < 200 && !app.projectionBusy(); ++i) { usleep(10000); @@ -558,5 +580,6 @@ int main() { if (audioLibrary) { usbAudioFailure(audioLibrary); } + usbAudioUnavailable(); usbAudioCleanupGate(); } From a4608b5b76e16a1d27cb62e85a35a360f3c8cfe5 Mon Sep 17 00:00:00 2001 From: mbalous Date: Sun, 29 Nov 2026 00:24:48 +0100 Subject: [PATCH 03/10] style(audio): format direct audio changes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- core/aa_channels.cpp | 6 ++++-- core/aa_session.hpp | 2 +- platform/audio_mixer.hpp | 4 +--- platform/audio_player.cpp | 8 +++++++- platform/audio_route.cpp | 3 +-- tests/test_session_phone.cpp | 9 ++++----- 6 files changed, 18 insertions(+), 14 deletions(-) diff --git a/core/aa_channels.cpp b/core/aa_channels.cpp index fb03613..383b927 100644 --- a/core/aa_channels.cpp +++ b/core/aa_channels.cpp @@ -355,8 +355,10 @@ void AASession::onMedia(uint8_t channel, uint16_t id, const Message& message) { ++count; if (count <= kAudioLoggedFirst || count % kAudioLogEvery == 0) { printf("[AASession] audio %s frame #%u: %u bytes PCM, pts=%llu\n", - index == 1 ? "media(ch9)" : index == 2 ? "system(ch16)" : "guidance(ch8)", count, - static_cast(message.size() - kTimestampedHeader), + index == 1 ? "media(ch9)" + : index == 2 ? "system(ch16)" + : "guidance(ch8)", + count, static_cast(message.size() - kTimestampedHeader), static_cast(bigEndian64(&message[kMessageIdSize]))); } const size_t pcmSize = message.size() - kTimestampedHeader; diff --git a/core/aa_session.hpp b/core/aa_session.hpp index 7b8469d..dd6b318 100644 --- a/core/aa_session.hpp +++ b/core/aa_session.hpp @@ -212,7 +212,7 @@ class AASession { bool sendBroken_; // a send failed: nothing more goes out, the session ends (sendExactly) uint32_t mediaSessions_[256]; // per channel, the session id of its start indication, echoed in our acks uint32_t mediaMessages_; // media messages received, every channel - uint32_t audioMessages_[3]; // guidance, media, system + uint32_t audioMessages_[3]; // guidance, media, system bool audioActive_[3]; uint32_t audioConfig_[3]; struct AudioAck { diff --git a/platform/audio_mixer.hpp b/platform/audio_mixer.hpp index e9f0eca..c5e6a0a 100644 --- a/platform/audio_mixer.hpp +++ b/platform/audio_mixer.hpp @@ -41,9 +41,7 @@ class AudioMixer { return true; } - bool pushSpeech(const uint8_t* pcm, size_t bytes, unsigned config) { - return pushMono(speech_, pcm, bytes, config); - } + bool pushSpeech(const uint8_t* pcm, size_t bytes, unsigned config) { return pushMono(speech_, pcm, bytes, config); } bool pushSystem(const uint8_t* pcm, size_t bytes) { return pushMono(system_, pcm, bytes, 0); } diff --git a/platform/audio_player.cpp b/platform/audio_player.cpp index c3be06d..439215f 100644 --- a/platform/audio_player.cpp +++ b/platform/audio_player.cpp @@ -12,7 +12,13 @@ namespace evo { AudioPlayer::AudioPlayer() - : route_(nullptr), thread_(0), started_(false), quit_(false), inCall_(false), promptOpen_(false), generation_(0), + : route_(nullptr), + thread_(0), + started_(false), + quit_(false), + inCall_(false), + promptOpen_(false), + generation_(0), failure_(0) { for (unsigned i = 0; i < 3; ++i) { active_[i] = seen_[i] = false; diff --git a/platform/audio_route.cpp b/platform/audio_route.cpp index 1096860..c7bc16a 100644 --- a/platform/audio_route.cpp +++ b/platform/audio_route.cpp @@ -119,8 +119,7 @@ void AudioRoute::call(Phase phase, uint16_t route, uint32_t now, VmostPort& port phase_ = phase; received_ = false; timedOut_ = false; - ELOG("AudioRoute", "%s connection 0x%x (handle 0x%x)", phase == kRemove ? "releasing" : "building", route, - handle_); + ELOG("AudioRoute", "%s connection 0x%x (handle 0x%x)", phase == kRemove ? "releasing" : "building", route, handle_); sentAt_ = now; if (port.send(m) != 0) { fail("route request refused by vMOST"); diff --git a/tests/test_session_phone.cpp b/tests/test_session_phone.cpp index 6f46874..96a1c42 100644 --- a/tests/test_session_phone.cpp +++ b/tests/test_session_phone.cpp @@ -1157,12 +1157,11 @@ std::string directAudioSession() { phone.headUnitPings(30, false); const std::vector events = takeEvents(); const std::vector expected = { - "audio stream ch=8 session=7 config=1 start=1", "audio data ch=8 session=7 pts=3 1122", - "audio stream ch=8 session=7 config=1 start=0", "audio stream ch=8 session=9 config=0 start=1", - "audio stream ch=9 session=11 config=0 start=1", "audio data ch=9 session=11 pts=4 01020304", + "audio stream ch=8 session=7 config=1 start=1", "audio data ch=8 session=7 pts=3 1122", + "audio stream ch=8 session=7 config=1 start=0", "audio stream ch=8 session=9 config=0 start=1", + "audio stream ch=9 session=11 config=0 start=1", "audio data ch=9 session=11 pts=4 01020304", "audio stream ch=16 session=12 config=0 start=1", "audio data ch=16 session=12 pts=7 3344", - "audio stream ch=16 session=12 config=0 start=0", - "audio stream ch=8 session=9 config=0 start=0", + "audio stream ch=16 session=12 config=0 start=0", "audio stream ch=8 session=9 config=0 start=0", }; if (events != expected) { return "unexpected audio start/data/stop callbacks"; From 47299d771df4c82bde538af353260b208b003381 Mon Sep 17 00:00:00 2001 From: mbalous Date: Sun, 29 Nov 2026 00:31:49 +0100 Subject: [PATCH 04/10] fix(audio): finish partial prompt writes and link sanitizer tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- platform/audio_player.cpp | 5 +++-- tests/host.mk | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/platform/audio_player.cpp b/platform/audio_player.cpp index 439215f..2022e77 100644 --- a/platform/audio_player.cpp +++ b/platform/audio_player.cpp @@ -241,9 +241,10 @@ void AudioPlayer::run() { const uint32_t now = monoMs(); uint16_t wanted = 0; if (!inCall_) { - if (mixer_.speechFrames() || (active_[0] && seen_[0] && now - lastData_[0] < 300)) { + if (mixer_.speechFrames() || (selected == 0x31A && offset < count) || + (active_[0] && seen_[0] && now - lastData_[0] < 300)) { wanted = 0x31A; - } else if (mixer_.mediaFrames() || mixer_.systemFrames() || + } else if (mixer_.mediaFrames() || mixer_.systemFrames() || (selected == 0x315 && offset < count) || (active_[1] && seen_[1] && now - lastData_[1] < 1000) || (active_[2] && seen_[2] && now - lastData_[2] < 300)) { wanted = 0x315; diff --git a/tests/host.mk b/tests/host.mk index 0d970ad..4ab377d 100644 --- a/tests/host.mk +++ b/tests/host.mk @@ -66,7 +66,8 @@ $(eval $(call host-test,audio-probe,platform/audio_probe.cpp platform/vmost_clie $(eval $(call host-test,audio-route,platform/audio_route.cpp platform/vmost_client.cpp,,-ldl)) $(eval $(call host-test,audio-mixer)) $(eval $(call host-test,audio-output,platform/audio_output.cpp,,-ldl)) -$(eval $(call host-test,audio-player,platform/audio_player.cpp platform/audio_output.cpp,,-ldl)) +$(eval $(call host-test,audio-player,platform/audio_player.cpp platform/audio_output.cpp \ + platform/audio_route.cpp platform/vmost_client.cpp,,-ldl)) $(eval $(call host-test,routed-audio,platform/audio_player.cpp platform/audio_output.cpp \ platform/audio_route.cpp platform/vmost_client.cpp,,-ldl)) $(eval $(call host-test,kombi-phone,platform/kombi_phone.cpp)) From 7335f501bb13fe0b476d2dbb90b9cbbe58cf9d14 Mon Sep 17 00:00:00 2001 From: mbalous Date: Sun, 29 Nov 2026 00:54:58 +0100 Subject: [PATCH 05/10] Pace USB audio acknowledgements by queue progress Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- core/aa_channels.cpp | 12 +++-- core/aa_session.cpp | 48 +++++++++++++------ core/aa_session.hpp | 19 +++++--- docs/USB.md | 4 ++ platform/audio_output.cpp | 8 +++- platform/audio_output.hpp | 1 + platform/audio_player.cpp | 76 ++++++++++++++++++++++-------- platform/audio_player.hpp | 6 ++- platform/service_app.cpp | 5 +- tests/test_audio_player.cpp | 42 ++++++++++++++++- tests/test_routed_audio.cpp | 49 +++++++++++++++++++ tests/test_session_phone.cpp | 91 ++++++++++++++++++++++++++++++++---- 12 files changed, 301 insertions(+), 60 deletions(-) diff --git a/core/aa_channels.cpp b/core/aa_channels.cpp index 383b927..be5b5b4 100644 --- a/core/aa_channels.cpp +++ b/core/aa_channels.cpp @@ -365,11 +365,13 @@ void AASession::onMedia(uint8_t channel, uint16_t id, const Message& message) { const size_t frameSize = index == 1 ? 4 : 2; if (audioData_.fn && audioActive_[index]) { if (pcmSize % frameSize == 0) { - audioData_.fn(channel, mediaSessions_[channel], &message[kTimestampedHeader], pcmSize, - bigEndian64(&message[kMessageIdSize]), audioData_.user); - const uint32_t rate = index == 1 || audioConfig_[index] == 1 ? 48000 : 16000; - deferAudioAck(channel, mediaSessions_[channel], pcmSize, rate); - deferredAck = true; + const uint64_t marker = + audioData_.fn(channel, mediaSessions_[channel], &message[kTimestampedHeader], pcmSize, + bigEndian64(&message[kMessageIdSize]), audioData_.user); + if (marker) { + deferAudioAck(channel, mediaSessions_[channel], marker); + deferredAck = true; + } } else { fprintf(stderr, "[AASession] dropping unaligned audio frame on channel %u\n", channel); } diff --git a/core/aa_session.cpp b/core/aa_session.cpp index 12d9c21..09f6c88 100644 --- a/core/aa_session.cpp +++ b/core/aa_session.cpp @@ -46,6 +46,8 @@ const unsigned kMicrophoneLogEvery = 250; // fails its check breaks TLS at once (TlsClient::broken): the session ends at that frame. const unsigned kUnreadableLimit = 16; const int kTouchMove = 2; +const uint64_t kAudioAckTimeoutUs = 1000000; +const uint64_t kAudioProgressPollUs = 20000; uint64_t monotonicUs() { timespec now; @@ -138,15 +140,18 @@ void AASession::setNavStatusCallback(NavStatusCallback cb, void* user_data) { navigation_.user = user_data; } -bool AASession::setAudioCallbacks(AudioDataCallback data, AudioStreamCallback stream, void* user_data) { - if ((data == nullptr) != (stream == nullptr)) { - fprintf(stderr, "[AASession] direct audio needs both callbacks\n"); +bool AASession::setAudioCallbacks(AudioDataCallback data, AudioStreamCallback stream, AudioProgressCallback progress, + void* user_data) { + if ((data == nullptr) != (stream == nullptr) || (data == nullptr) != (progress == nullptr)) { + fprintf(stderr, "[AASession] direct audio needs data, stream and progress callbacks\n"); return false; } audioData_.fn = data; audioData_.user = user_data; audioStream_.fn = stream; audioStream_.user = user_data; + audioProgress_.fn = progress; + audioProgress_.user = user_data; return true; } @@ -225,6 +230,8 @@ void AASession::resetCounters() { keysLogged_ = movesLogged_ = navigationLogged_ = pings_ = pingsAsked_ = pingAnswers_ = 0; playbackState_ = kNoField; memset(framesSeen_, 0, sizeof(framesSeen_)); + memset(audioAckTimeouts_, 0, sizeof(audioAckTimeouts_)); + memset(audioAckOverflows_, 0, sizeof(audioAckOverflows_)); plainAfterTls_ = refusedBeforeTls_ = plainKindCount_ = 0; plainKindsFull_ = false; } @@ -475,21 +482,19 @@ bool AASession::receiveExactly(uint8_t* to, size_t size) { return got == size; } -void AASession::deferAudioAck(uint8_t channel, uint32_t session, size_t pcmBytes, uint32_t sampleRate) { +void AASession::deferAudioAck(uint8_t channel, uint32_t session, uint64_t marker) { const unsigned index = channel::audioIndex(channel); std::deque& queue = audioAcks_[index]; if (queue.size() >= kMaxUnacked) { + const unsigned count = ++audioAckOverflows_[index]; + if (count <= 3 || count % 100 == 0) { + fprintf(stderr, "[AASession] audio ACK queue full on channel %u (%u times); releasing oldest\n", channel, + count); + } sendSealed(channel, message::mediaAck(queue.front().session)); queue.pop_front(); } - const uint64_t now = monotonicUs(); - const uint64_t start = !queue.empty() && queue.back().dueUs > now ? queue.back().dueUs : now; - const size_t frameBytes = index == 1 ? 4 : 2; - uint64_t duration = static_cast(pcmBytes / frameBytes) * 1000000ULL / sampleRate; - if (duration > 500000) { - duration = 500000; // the player retains at most 500 ms of any oversized frame - } - const AudioAck ack = {session, start + duration}; + const AudioAck ack = {session, marker, monotonicUs() + kAudioAckTimeoutUs}; queue.push_back(ack); } @@ -497,7 +502,17 @@ void AASession::sendDueAudioAcks(uint64_t nowUs) { for (unsigned index = 0; index < 3; ++index) { std::deque& queue = audioAcks_[index]; const uint8_t channel = channel::audioChannel(index); - while (!queue.empty() && queue.front().dueUs <= nowUs) { + if (queue.empty()) { + continue; + } + const uint64_t progress = audioProgress_.fn(channel, audioProgress_.user); + while (!queue.empty() && (queue.front().marker <= progress || queue.front().deadlineUs <= nowUs)) { + if (queue.front().marker > progress) { + const unsigned count = ++audioAckTimeouts_[index]; + if (count <= 3 || count % 100 == 0) { + fprintf(stderr, "[AASession] audio ACK timed out on channel %u (%u times)\n", channel, count); + } + } const uint32_t session = queue.front().session; queue.pop_front(); if (!sendSealed(channel, message::mediaAck(session))) { @@ -524,8 +539,11 @@ uint64_t AASession::audioAckWaitUs(uint64_t nowUs) const { uint64_t delay = 1000000; for (unsigned index = 0; index < 3; ++index) { if (!audioAcks_[index].empty()) { - const uint64_t due = audioAcks_[index].front().dueUs; - const uint64_t left = due > nowUs ? due - nowUs : 0; + const uint64_t deadline = audioAcks_[index].front().deadlineUs; + uint64_t left = deadline > nowUs ? deadline - nowUs : 0; + if (left > kAudioProgressPollUs) { + left = kAudioProgressPollUs; + } if (left < delay) { delay = left; } diff --git a/core/aa_session.hpp b/core/aa_session.hpp index dd6b318..3ffbb42 100644 --- a/core/aa_session.hpp +++ b/core/aa_session.hpp @@ -38,8 +38,11 @@ using MicRequestCallback = void (*)(bool, void*); using NavStatusCallback = void (*)(uint16_t, const uint8_t*, size_t, void*); // PCM and stream lifecycle on the session thread. The receiver must copy data and return without blocking. // Channel 8: mono 16/48 kHz; channel 9: stereo 48 kHz; channel 16: mono 16 kHz. All S16LE. -using AudioDataCallback = void (*)(uint8_t, uint32_t, const uint8_t*, size_t, uint64_t, void*); +// Data returns a per-channel cumulative 48 kHz frame marker, or zero when rejected. Progress returns the +// cumulative frames removed from that channel's queue, including discarded frames, or zero if temporarily busy. +using AudioDataCallback = uint64_t (*)(uint8_t, uint32_t, const uint8_t*, size_t, uint64_t, void*); using AudioStreamCallback = void (*)(uint8_t, uint32_t, uint32_t, bool, void*); +using AudioProgressCallback = uint64_t (*)(uint8_t, void*); class AASession { public: @@ -73,9 +76,10 @@ class AASession { void setVideoFocusCallback(VideoFocusCallback cb, void* user_data = nullptr); void setMicRequestCallback(MicRequestCallback cb, void* user_data = nullptr); void setNavStatusCallback(NavStatusCallback cb, void* user_data = nullptr); - // Both callbacks enable direct audio discovery; both null restore Bluetooth discovery. Set before start(). - // False when only one callback is provided; the previous setting remains unchanged. - bool setAudioCallbacks(AudioDataCallback data, AudioStreamCallback stream, void* user_data = nullptr); + // All callbacks enable direct audio discovery; all null restore Bluetooth discovery. Set before start(). + // False for an incomplete set; the previous setting remains unchanged. + bool setAudioCallbacks(AudioDataCallback data, AudioStreamCallback stream, AudioProgressCallback progress, + void* user_data = nullptr); void setTouchForwarding(bool on) { inbox_.setTouchForwarding(on); } // on by default; keys go either way // The file holding the car's model, year, side and fuel (SdrIdentity::loadVehicleFile), read at each service // discovery; kept as given, so it must outlive the session. None by default: the default car. @@ -162,7 +166,7 @@ class AASession { void onSetup(uint8_t channel); void onStart(uint8_t channel, const Message& message); void stopAudio(uint8_t channel); - void deferAudioAck(uint8_t channel, uint32_t session, size_t pcmBytes, uint32_t sampleRate); + void deferAudioAck(uint8_t channel, uint32_t session, uint64_t marker); void sendDueAudioAcks(uint64_t nowUs); void flushAudioAcks(uint8_t channel); uint64_t audioAckWaitUs(uint64_t nowUs) const; @@ -188,6 +192,7 @@ class AASession { Callback navigation_; Callback audioData_; Callback audioStream_; + Callback audioProgress_; const char* vehicleFile_; const char* softwareVersion_; const char* carMake_; @@ -217,9 +222,11 @@ class AASession { uint32_t audioConfig_[3]; struct AudioAck { uint32_t session; - uint64_t dueUs; + uint64_t marker; + uint64_t deadlineUs; }; std::deque audioAcks_[3]; + unsigned audioAckTimeouts_[3], audioAckOverflows_[3]; uint32_t microphoneChunks_; // sent since the phone opened the microphone // Log throttles, per session. unsigned framesSeen_[256]; diff --git a/docs/USB.md b/docs/USB.md index a9d5385..65e4fa8 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -12,6 +12,10 @@ les variantes. Elles ne sont pas les identifiants `0x1d0` et A2I d'un NBT EVO QN Le service essaie actuellement ce profil sans reconnaître la version de l'unité : sa compatibilité avec une autre variante n'est pas établie. +Les acquittements audio suivent les échantillons retirés des files bornées, y compris ceux abandonnés lors d'un +dépassement ou d'une interruption ; ils ne prouvent pas que le son est sorti des haut-parleurs. Un acquittement bloqué +est libéré après une seconde. Les sous-alimentations ALSA et les acquittements forcés sont signalés dans le journal. + **Le son direct et ces routes n'ont pas encore été vérifiés sur cette voiture.** Il n'y a pas de repli automatique vers Bluetooth : si le son direct ne peut pas démarrer ou échoue, la session USB est refusée ou interrompue ; arrêter et redémarrer le service pour réessayer. Si la libération d'une route ne peut pas être confirmée, une nouvelle session diff --git a/platform/audio_output.cpp b/platform/audio_output.cpp index 206a251..430f6ef 100644 --- a/platform/audio_output.cpp +++ b/platform/audio_output.cpp @@ -21,7 +21,8 @@ AudioOutput::AudioOutput() state_(nullptr), start_(nullptr), close_(nullptr), - error_(nullptr) {} + error_(nullptr), + underruns_(0) {} AudioOutput::~AudioOutput() { close(); @@ -29,6 +30,7 @@ AudioOutput::~AudioOutput() { bool AudioOutput::open(const char* pcm, const char* library, unsigned channels) { close(); + underruns_ = 0; if (!pcm || !*pcm || !library || !*library || (channels != 1 && channels != 2)) { ELOG("AudioOutput", "missing PCM or ALSA library name"); return false; @@ -75,6 +77,10 @@ long AudioOutput::write(const int16_t* samples, size_t frames) { } long result = write_(pcm_, samples, static_cast(frames)); if (result == -EPIPE) { + ++underruns_; + if (underruns_ <= 3 || underruns_ % 100 == 0) { + ELOG("AudioOutput", "playback underrun #%u; attempting recovery", underruns_); + } const int recovered = recover_(pcm_, static_cast(result), 1); result = recovered < 0 ? recovered : -EAGAIN; } diff --git a/platform/audio_output.hpp b/platform/audio_output.hpp index b4ce1f4..fe4d979 100644 --- a/platform/audio_output.hpp +++ b/platform/audio_output.hpp @@ -36,6 +36,7 @@ class AudioOutput { int (*start_)(void*); int (*close_)(void*); const char* (*error_)(int); + unsigned underruns_; }; } // namespace evo diff --git a/platform/audio_player.cpp b/platform/audio_player.cpp index 2022e77..f47052b 100644 --- a/platform/audio_player.cpp +++ b/platform/audio_player.cpp @@ -23,6 +23,7 @@ AudioPlayer::AudioPlayer() for (unsigned i = 0; i < 3; ++i) { active_[i] = seen_[i] = false; sessions_[i] = configs_[i] = lastData_[i] = 0; + submitted_[i] = released_[i] = 0; } pthread_mutex_init(&mu_, nullptr); pthread_cond_init(&cv_, nullptr); @@ -104,9 +105,9 @@ void AudioPlayer::stop() { for (unsigned i = 0; i < 3; ++i) { active_[i] = seen_[i] = false; } - mixer_.clearMedia(); - mixer_.clearSpeech(); - mixer_.clearSystem(); + for (unsigned i = 0; i < 3; ++i) { + clear(i); + } pthread_mutex_unlock(&mu_); output_.close(); promptOutput_.close(); @@ -117,10 +118,8 @@ void AudioPlayer::setCall(bool active) { pthread_mutex_lock(&mu_); if (inCall_ != active) { inCall_ = active; - mixer_.clearMedia(); - mixer_.clearSpeech(); - mixer_.clearSystem(); for (unsigned i = 0; i < 3; ++i) { + clear(i); seen_[i] = false; } ++generation_; @@ -138,9 +137,9 @@ void AudioPlayer::endSession() { for (unsigned i = 0; i < 3; ++i) { active_[i] = seen_[i] = false; } - mixer_.clearMedia(); - mixer_.clearSpeech(); - mixer_.clearSystem(); + for (unsigned i = 0; i < 3; ++i) { + clear(i); + } ++generation_; if (route_) { route_->request(0); @@ -162,39 +161,41 @@ void AudioPlayer::stream(uint8_t channel, uint32_t session, uint32_t config, boo self->sessions_[index] = session; self->configs_[index] = config; if (started || index == 1) { - if (index == 1) { - self->mixer_.clearMedia(); - } else if (index == 2) { - self->mixer_.clearSystem(); - } else { - self->mixer_.clearSpeech(); - } + self->clear(index); ++self->generation_; } pthread_cond_signal(&self->cv_); pthread_mutex_unlock(&self->mu_); } -void AudioPlayer::data(uint8_t channel, uint32_t session, const uint8_t* pcm, size_t bytes, uint64_t, void* user) { +uint64_t AudioPlayer::data(uint8_t channel, uint32_t session, const uint8_t* pcm, size_t bytes, uint64_t, void* user) { AudioPlayer* self = static_cast(user); if (!self || !aa::channel::isAudioSink(channel)) { ELOG("AudioPlayer", "invalid PCM callback"); - return; + return 0; } const unsigned index = aa::channel::audioIndex(channel); if (pthread_mutex_trylock(&self->mu_) != 0) { ELOG("AudioPlayer", "PCM dropped while playback buffer is busy"); - return; + return 0; } if (self->inCall_) { pthread_mutex_unlock(&self->mu_); - return; + return 0; } + uint64_t marker = 0; if (self->active_[index] && self->sessions_[index] == session) { + const size_t before = self->queued(index); const bool ok = index == 1 ? self->mixer_.pushMedia(pcm, bytes) : index == 2 ? self->mixer_.pushSystem(pcm, bytes) : self->mixer_.pushSpeech(pcm, bytes, self->configs_[index]); if (ok) { + const uint64_t frames = index == 1 ? bytes / 4 + : index == 0 && self->configs_[index] == 1 ? bytes / 2 + : (bytes / 2) * 3; + self->submitted_[index] += frames; + self->released_[index] += before + frames - self->queued(index); + marker = self->submitted_[index]; self->lastData_[index] = monoMs(); self->seen_[index] = true; pthread_cond_signal(&self->cv_); @@ -205,6 +206,36 @@ void AudioPlayer::data(uint8_t channel, uint32_t session, const uint8_t* pcm, si ELOG("AudioPlayer", "PCM for inactive stream on channel %u", channel); } pthread_mutex_unlock(&self->mu_); + return marker; +} + +uint64_t AudioPlayer::progress(uint8_t channel, void* user) { + AudioPlayer* self = static_cast(user); + if (!self || !aa::channel::isAudioSink(channel)) { + ELOG("AudioPlayer", "invalid progress callback"); + return 0; + } + if (pthread_mutex_trylock(&self->mu_) != 0) { + return 0; + } + const uint64_t progress = self->released_[aa::channel::audioIndex(channel)]; + pthread_mutex_unlock(&self->mu_); + return progress; +} + +size_t AudioPlayer::queued(unsigned index) const { + return index == 1 ? mixer_.mediaFrames() : index == 2 ? mixer_.systemFrames() : mixer_.speechFrames(); +} + +void AudioPlayer::clear(unsigned index) { + released_[index] += queued(index); + if (index == 1) { + mixer_.clearMedia(); + } else if (index == 2) { + mixer_.clearSystem(); + } else { + mixer_.clearSpeech(); + } } void* AudioPlayer::threadMain(void* user) { @@ -299,6 +330,7 @@ void AudioPlayer::run() { granted = true; if (wanted == 0x315) { const size_t dropped = mixer_.trimMedia(9600); // 200 ms at 48 kHz + released_[1] += dropped; if (dropped) { ELOG("AudioPlayer", "trimmed %u stale media frames after route grant", static_cast(dropped)); @@ -307,8 +339,12 @@ void AudioPlayer::run() { } } while (!quit_ && offset == count) { + const size_t before[] = {queued(0), queued(1), queued(2)}; count = mixer_.read(samples, 480, !route_ || selected == 0x315, !route_ || selected == 0x31A, !route_ || selected == 0x315); + for (unsigned i = 0; i < 3; ++i) { + released_[i] += before[i] - queued(i); + } offset = 0; if (count) { if (route_ && selected == 0x31A) { diff --git a/platform/audio_player.hpp b/platform/audio_player.hpp index 91b23c2..5bc5c4a 100644 --- a/platform/audio_player.hpp +++ b/platform/audio_player.hpp @@ -35,13 +35,16 @@ class AudioPlayer { void setCall(bool active); // The session callbacks copy to bounded buffers; no ALSA operation runs on the session thread. - static void data(uint8_t channel, uint32_t session, const uint8_t* pcm, size_t bytes, uint64_t pts, void* user); + static uint64_t data(uint8_t channel, uint32_t session, const uint8_t* pcm, size_t bytes, uint64_t pts, void* user); static void stream(uint8_t channel, uint32_t session, uint32_t config, bool started, void* user); + static uint64_t progress(uint8_t channel, void* user); private: static void* threadMain(void* user); void run(); bool startWorker(); + size_t queued(unsigned index) const; + void clear(unsigned index); AudioOutput output_; AudioOutput promptOutput_; @@ -53,6 +56,7 @@ class AudioPlayer { pthread_t thread_; bool started_, quit_, active_[3], inCall_, seen_[3], promptOpen_; uint32_t sessions_[3], configs_[3], generation_, lastData_[3]; + uint64_t submitted_[3], released_[3]; std::atomic failure_; }; diff --git a/platform/service_app.cpp b/platform/service_app.cpp index d8144a9..25eb888 100644 --- a/platform/service_app.cpp +++ b/platform/service_app.cpp @@ -570,7 +570,7 @@ void ServiceApp::startProjection(int fd, bool overUsb) { return; } a->audioPlayer.stop(); - a->session.setAudioCallbacks(nullptr, nullptr); + a->session.setAudioCallbacks(nullptr, nullptr, nullptr); if (a->audioRouteUsed) { if (!a->audioCleanupRequested) { a->audioRoute.enable(false); @@ -628,7 +628,8 @@ void ServiceApp::startProjection(int fd, bool overUsb) { direct = a->audioPlayer.startRouted(a->audioRoute, "entertainment", "carplay_alt"); if (direct) { a->audioRouteUsed = true; - a->session.setAudioCallbacks(AudioPlayer::data, AudioPlayer::stream, &a->audioPlayer); + a->session.setAudioCallbacks(AudioPlayer::data, AudioPlayer::stream, AudioPlayer::progress, + &a->audioPlayer); ELOG("ServiceApp", "USB direct audio: experimental EntryNav2 playback profile"); } } diff --git a/tests/test_audio_player.cpp b/tests/test_audio_player.cpp index 070d0da..fe69749 100644 --- a/tests/test_audio_player.cpp +++ b/tests/test_audio_player.cpp @@ -6,10 +6,35 @@ #include #include +#include + #include "audio_player.hpp" int main(int argc, char** argv) { assert(argc == 2); + evo::AudioPlayer accounting; + const uint8_t small[] = {1, 0, 2, 0, 3, 0, 4, 0}; + evo::AudioPlayer::stream(9, 1, 0, true, &accounting); + assert(evo::AudioPlayer::data(9, 1, small, sizeof(small), 0, &accounting) == 2); + assert(evo::AudioPlayer::progress(9, &accounting) == 0); + std::vector large((evo::AudioMixer::kCapacityFrames + 1) * 4, 0); + const uint64_t last = evo::AudioPlayer::data(9, 1, large.data(), large.size(), 0, &accounting); + assert(last == evo::AudioMixer::kCapacityFrames + 3); + assert(evo::AudioPlayer::progress(9, &accounting) == 3); // overflow discards oldest and oversized prefix + accounting.setCall(true); + assert(evo::AudioPlayer::progress(9, &accounting) == last); + assert(evo::AudioPlayer::data(9, 1, small, sizeof(small), 0, &accounting) == 0); + accounting.setCall(false); + evo::AudioPlayer::stream(8, 2, 0, true, &accounting); + assert(evo::AudioPlayer::data(8, 2, small, 2, 0, &accounting) == 3); + evo::AudioPlayer::stream(8, 2, 0, false, &accounting); + assert(evo::AudioPlayer::progress(8, &accounting) == 0); // short prompts survive STOP + evo::AudioPlayer::stream(8, 3, 1, true, &accounting); + assert(evo::AudioPlayer::progress(8, &accounting) == 3); + assert(evo::AudioPlayer::data(8, 2, small, 2, 0, &accounting) == 0); + assert(evo::AudioPlayer::data(8, 3, small, 2, 0, &accounting) == 4); + accounting.endSession(); + assert(evo::AudioPlayer::progress(8, &accounting) == 4); void* lib = dlopen(argv[1], RTLD_NOW | RTLD_LOCAL); assert(lib); typedef void (*SetError)(int); @@ -26,11 +51,26 @@ int main(int argc, char** argv) { assert(player.start("test", argv[1])); const uint8_t pcm[] = {1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0}; evo::AudioPlayer::stream(9, 7, 0, true, &player); - evo::AudioPlayer::data(9, 7, pcm, sizeof(pcm), 0, &player); + uint64_t played = 0; + for (unsigned i = 0; i < 200 && !played; ++i) { + played = evo::AudioPlayer::data(9, 7, pcm, sizeof(pcm), 0, &player); + if (!played) { + usleep(10000); + } + } + assert(played == 3); for (unsigned i = 0; i < 200 && written() < 3; ++i) { usleep(10000); } assert(written() == 3 && player.failure() == 0); + uint64_t progress = 0; + for (unsigned i = 0; i < 200 && progress < played; ++i) { + progress = evo::AudioPlayer::progress(9, &player); + if (progress < played) { + usleep(10000); + } + } + assert(progress >= played); evo::AudioPlayer::stream(9, 7, 0, false, &player); setError(-EIO); evo::AudioPlayer::stream(9, 8, 0, true, &player); diff --git a/tests/test_routed_audio.cpp b/tests/test_routed_audio.cpp index c1513c2..daae838 100644 --- a/tests/test_routed_audio.cpp +++ b/tests/test_routed_audio.cpp @@ -175,6 +175,55 @@ int main(int argc, char** argv) { assert(endedPort.messages.back().function == 0xC03); // no build after the session ended endedPlayer.stop(); endedRoute.finish(endedPort); + + evo::AudioRoute delayedRoute; + Port delayedPort; + delayedRoute.enable(true); + delayedRoute.tick(evo::monoMs(), delayedPort); + table(delayedRoute, {1}); + delayedRoute.tick(evo::monoMs(), delayedPort); + evo::AudioPlayer delayed; + assert(delayed.startRouted(delayedRoute, "test", "prompt", argv[1])); + evo::AudioPlayer::stream(9, 5, 0, true, &delayed); + std::vector buffered(12000 * 4, 0); + uint64_t marker = 0; + for (unsigned i = 0; i < 200 && !marker; ++i) { + marker = evo::AudioPlayer::data(9, 5, buffered.data(), buffered.size(), 0, &delayed); + if (!marker) { + usleep(10000); + } + } + assert(marker == 12000); + waitRequest(delayedRoute, delayedPort, 2); + assert(evo::AudioPlayer::progress(9, &delayed) == 0); // no grant, no playout + table(delayedRoute, {1}); + delayedRoute.tick(evo::monoMs(), delayedPort); + assert(delayedPort.messages.back().function == 0x53); + answer(delayedRoute, delayedPort.messages.back()); + delayedRoute.tick(evo::monoMs(), delayedPort); + table(delayedRoute, {0x315}); + delayedRoute.tick(evo::monoMs(), delayedPort); + uint64_t progress = 0; + for (unsigned i = 0; i < 200 && progress < 2400; ++i) { + progress = evo::AudioPlayer::progress(9, &delayed); + if (progress < 2400) { + usleep(10000); + } + } + assert(progress >= 2400 && progress <= marker); // trim to 200 ms counts as discarded progress + delayed.stop(); + delayedRoute.tick(evo::monoMs() + 1200, delayedPort); + table(delayedRoute, {0x315}); + delayedRoute.tick(evo::monoMs() + 1201, delayedPort); + assert(delayedPort.messages.back().function == 0x54); + answer(delayedRoute, delayedPort.messages.back()); + delayedRoute.tick(evo::monoMs() + 1202, delayedPort); + table(delayedRoute, {}); + delayedRoute.tick(evo::monoMs() + 1203, delayedPort); + assert(delayedPort.messages.back().function == 0x53); + answer(delayedRoute, delayedPort.messages.back()); + delayedRoute.tick(evo::monoMs() + 1204, delayedPort); + delayedRoute.finish(delayedPort); dlclose(lib); puts("PASS routed audio: FM prompt, call interruption, media and playback failure"); return 0; diff --git a/tests/test_session_phone.cpp b/tests/test_session_phone.cpp index 96a1c42..d6e71a1 100644 --- a/tests/test_session_phone.cpp +++ b/tests/test_session_phone.cpp @@ -262,13 +262,59 @@ void onMic(bool open, void*) { void onNav(uint16_t id, const uint8_t* body, size_t len, void*) { event(format("nav %04x ", id) + (len ? hex(body, len) : std::string("-"))); } -void onAudioData(uint8_t channel, uint32_t session, const uint8_t* pcm, size_t len, uint64_t pts, void*) { +struct FakeAudio { + pthread_mutex_t mutex; + uint64_t submitted[3], released[3]; + uint32_t configs[3]; + bool automatic; + + FakeAudio() : submitted{}, released{}, configs{}, automatic(true) { pthread_mutex_init(&mutex, nullptr); } + ~FakeAudio() { pthread_mutex_destroy(&mutex); } + void hold() { + pthread_mutex_lock(&mutex); + automatic = false; + pthread_mutex_unlock(&mutex); + } + void release(unsigned index, uint64_t frames) { + pthread_mutex_lock(&mutex); + released[index] += frames; + pthread_mutex_unlock(&mutex); + } +}; + +unsigned audioIndex(uint8_t channel) { + return channel == 9 ? 1 : channel == 16 ? 2 : 0; +} + +uint64_t onAudioData(uint8_t channel, uint32_t session, const uint8_t* pcm, size_t len, uint64_t pts, void* user) { event(format("audio data ch=%u session=%u pts=%llu ", channel, session, static_cast(pts)) + hex(pcm, len)); + FakeAudio& audio = *static_cast(user); + const unsigned index = audioIndex(channel); + pthread_mutex_lock(&audio.mutex); + const uint64_t frames = index == 1 ? len / 4 : index == 0 && audio.configs[index] == 1 ? len / 2 : (len / 2) * 3; + audio.submitted[index] += frames; + const uint64_t marker = audio.submitted[index]; + if (audio.automatic) { + audio.released[index] = marker; + } + pthread_mutex_unlock(&audio.mutex); + return marker; } -void onAudioStream(uint8_t channel, uint32_t session, uint32_t config, bool started, void*) { +void onAudioStream(uint8_t channel, uint32_t session, uint32_t config, bool started, void* user) { + FakeAudio& audio = *static_cast(user); + pthread_mutex_lock(&audio.mutex); + audio.configs[audioIndex(channel)] = config; + pthread_mutex_unlock(&audio.mutex); event(format("audio stream ch=%u session=%u config=%u start=%d", channel, session, config, started ? 1 : 0)); } +uint64_t onAudioProgress(uint8_t channel, void* user) { + FakeAudio& audio = *static_cast(user); + pthread_mutex_lock(&audio.mutex); + const uint64_t progress = audio.released[audioIndex(channel)]; + pthread_mutex_unlock(&audio.mutex); + return progress; +} // The golden was recorded on an M340i of 2019: the model and year come from a vehicle file, as on that car. char g_vehicleFile[96]; @@ -602,15 +648,16 @@ class Phone { // One session on a fresh socketpair, the phone end for the test. struct Link { aa::AASession session; + FakeAudio audio; int phoneFd; - explicit Link(bool touch = true, bool audio = false) : phoneFd(-1) { + explicit Link(bool touch = true, bool directAudio = false) : phoneFd(-1) { int fds[2]; if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) != 0) { fprintf(stderr, "FAIL socketpair\n"); exit(1); } watch(session, touch); - if (audio && !session.setAudioCallbacks(onAudioData, onAudioStream)) { + if (directAudio && !session.setAudioCallbacks(onAudioData, onAudioStream, onAudioProgress, &audio)) { fprintf(stderr, "FAIL audio callbacks\n"); exit(1); } @@ -1191,24 +1238,50 @@ std::string pacedAudioAcks() { Phone phone(link.phoneFd, log); phone.handshake(); phone.discover(); + link.audio.hold(); phone.send(9, kSealed, bytes({0x80, 0x01, 0x08, 0x05})); Bytes pcm(57600, 0); // 300 ms of stereo 48 kHz S16LE phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 1}) + pcm); + phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 2}) + pcm); phone.settle(); const std::string ack = "hu ch=9 fl=0b 8004 08051001"; - if (std::find(log.begin(), log.end(), ack) != log.end()) { - return "music was acknowledged before its playback duration"; + phone.headUnitPings(350, false); + if (std::count(log.begin(), log.end(), ack) != 0) { + return "music was acknowledged without queue progress"; + } + link.audio.release(1, 7200); + phone.headUnitPings(100, false); + if (std::count(log.begin(), log.end(), ack) != 0) { + return "partial queue progress acknowledged an incomplete packet"; } - phone.headUnitPings(450, false); + link.audio.release(1, 7200); + phone.headUnitPings(100, false); if (std::count(log.begin(), log.end(), ack) != 1) { - return "paced music ack was not sent"; + return "queue progress did not release exactly one music ack"; } - phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 2}) + pcm); phone.send(9, kSealed, bytes({0x80, 0x02})); phone.settle(); if (std::count(log.begin(), log.end(), ack) != 2) { return "STOP did not flush the pending ack with its original session id"; } + phone.send(9, kSealed, bytes({0x80, 0x01, 0x08, 0x06})); + phone.send(9, kSealed, bytes({0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 3}) + pcm); + phone.settle(); + link.audio.release(1, 14400); // progress from the stopped stream must not acknowledge the new stream + phone.headUnitPings(100, false); + const std::string nextAck = "hu ch=9 fl=0b 8004 08061001"; + if (std::count(log.begin(), log.end(), nextAck) != 0) { + return "stale queue progress acknowledged a new stream"; + } + phone.headUnitPings(1100, false); + if (std::count(log.begin(), log.end(), nextAck) != 1) { + return "stalled audio ack did not time out exactly once"; + } + link.audio.release(1, 14400); + phone.headUnitPings(100, false); + if (std::count(log.begin(), log.end(), nextAck) != 1) { + return "late queue progress duplicated an ack"; + } phone.leave(); if (!waitEnded(link.session)) { return "session did not end"; From 84cdcd96bebdb3da65153aa31d14eb68ba5509bb Mon Sep 17 00:00:00 2001 From: mbalous Date: Sun, 29 Nov 2026 00:55:33 +0100 Subject: [PATCH 06/10] Clarify USB guidance route limitation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/USB.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/USB.md b/docs/USB.md index 65e4fa8..b6ef3ea 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -6,7 +6,8 @@ faire d'Android Auto sans fil, ou quand le Wi-Fi de la voiture rame. L'état des Avec le câble, l'image, les commandes, le micro, le GPS et le son Android Auto passent par l'USB. La musique et les sons système utilisent la sortie ALSA `entertainment` et la route `0x315` ; le guidage utilise `carplay_alt` et -`0x31a`, même pendant la musique. Ces paires ont été rapportées audibles sur un autre EntryNav2 (BMW X1 F48, +`0x31a`. Le service bascule entre ces routes : la musique et le guidage ne sont pas encore joués simultanément. +Ces paires ont été rapportées audibles sur un autre EntryNav2 (BMW X1 F48, [Jiraiya43/EntryNav2-Android-Auto#143](https://github.com/Jiraiya43/EntryNav2-Android-Auto/pull/143)), pas sur toutes les variantes. Elles ne sont pas les identifiants `0x1d0` et A2I d'un NBT EVO QNX. Le service essaie actuellement ce profil sans reconnaître la version de l'unité : sa compatibilité avec une autre From 1f720caab5816e4e08b7caf3e4dd8efdb7a148ea Mon Sep 17 00:00:00 2001 From: mbalous Date: Mon, 30 Nov 2026 23:48:56 +0100 Subject: [PATCH 07/10] Fix USB audio prompt drain and route preflight wait Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- platform/audio_output.cpp | 20 +++++++++- platform/audio_output.hpp | 3 ++ platform/audio_player.cpp | 61 ++++++++++++++++++++++++------- platform/audio_player.hpp | 2 +- platform/audio_route.cpp | 4 +- platform/audio_route.hpp | 2 + platform/main.cpp | 4 ++ platform/service_app.cpp | 20 ++++++---- tests/fake_audio_output.c | 24 +++++++++++- tests/test_routed_audio.cpp | 36 ++++++++++++++++-- tests/test_wireless_lifecycle.cpp | 32 ++++++++++++++++ 11 files changed, 179 insertions(+), 29 deletions(-) diff --git a/platform/audio_output.cpp b/platform/audio_output.cpp index 430f6ef..d393759 100644 --- a/platform/audio_output.cpp +++ b/platform/audio_output.cpp @@ -15,6 +15,7 @@ AudioOutput::AudioOutput() open_(nullptr), params_(nullptr), write_(nullptr), + delay_(nullptr), recover_(nullptr), drop_(nullptr), prepare_(nullptr), @@ -43,6 +44,7 @@ bool AudioOutput::open(const char* pcm, const char* library, unsigned channels) *reinterpret_cast(&open_) = dlsym(lib_, "snd_pcm_open"); *reinterpret_cast(¶ms_) = dlsym(lib_, "snd_pcm_set_params"); *reinterpret_cast(&write_) = dlsym(lib_, "snd_pcm_writei"); + *reinterpret_cast(&delay_) = dlsym(lib_, "snd_pcm_delay"); *reinterpret_cast(&recover_) = dlsym(lib_, "snd_pcm_recover"); *reinterpret_cast(&drop_) = dlsym(lib_, "snd_pcm_drop"); *reinterpret_cast(&prepare_) = dlsym(lib_, "snd_pcm_prepare"); @@ -50,7 +52,8 @@ bool AudioOutput::open(const char* pcm, const char* library, unsigned channels) *reinterpret_cast(&start_) = dlsym(lib_, "snd_pcm_start"); *reinterpret_cast(&close_) = dlsym(lib_, "snd_pcm_close"); *reinterpret_cast(&error_) = dlsym(lib_, "snd_strerror"); - if (!open_ || !params_ || !write_ || !recover_ || !drop_ || !prepare_ || !state_ || !start_ || !close_ || !error_) { + if (!open_ || !params_ || !write_ || !delay_ || !recover_ || !drop_ || !prepare_ || !state_ || !start_ || !close_ || + !error_) { ELOG("AudioOutput", "ALSA playback functions unavailable"); close(); return false; @@ -96,6 +99,20 @@ long AudioOutput::write(const int16_t* samples, size_t frames) { return result; } +long AudioOutput::pendingFrames() { + if (!pcm_) { + return -EINVAL; + } + long frames = 0; + const int result = delay_(pcm_, &frames); + if (result < 0 && result != -EPIPE) { + ELOG("AudioOutput", "cannot read playback delay: %s", error_(result)); + return result; + } + // An underrun means the queued audio has already run out. + return result == -EPIPE || frames < 0 ? 0 : frames; +} + bool AudioOutput::flush() { if (!pcm_ || !drop_ || !prepare_) { ELOG("AudioOutput", "flush without an open PCM"); @@ -131,6 +148,7 @@ void AudioOutput::close() { open_ = nullptr; params_ = nullptr; write_ = nullptr; + delay_ = nullptr; recover_ = nullptr; drop_ = nullptr; prepare_ = nullptr; diff --git a/platform/audio_output.hpp b/platform/audio_output.hpp index fe4d979..f52dd86 100644 --- a/platform/audio_output.hpp +++ b/platform/audio_output.hpp @@ -20,6 +20,8 @@ class AudioOutput { bool open(const char* pcm, const char* library = "libasound.so.2", unsigned channels = 2); // Returns written frames, -EAGAIN when full, or a negative ALSA error. Handles a recoverable underrun once. long write(const int16_t* samples, size_t frames); + // Returns frames left to play, or a negative ALSA error. + long pendingFrames(); bool flush(); void close(); @@ -29,6 +31,7 @@ class AudioOutput { int (*open_)(void**, const char*, int, int); int (*params_)(void*, int, int, unsigned, unsigned, int, unsigned); long (*write_)(void*, const void*, unsigned long); + int (*delay_)(void*, long*); int (*recover_)(void*, int, int); int (*drop_)(void*); int (*prepare_)(void*); diff --git a/platform/audio_player.cpp b/platform/audio_player.cpp index f47052b..f6cc68c 100644 --- a/platform/audio_player.cpp +++ b/platform/audio_player.cpp @@ -10,6 +10,9 @@ #include "evo_log.hpp" namespace evo { +namespace { +const uint32_t kPlaybackTimeoutMs = 2000; +} // namespace AudioPlayer::AudioPlayer() : route_(nullptr), @@ -18,7 +21,7 @@ AudioPlayer::AudioPlayer() quit_(false), inCall_(false), promptOpen_(false), - generation_(0), + generation_{}, failure_(0) { for (unsigned i = 0; i < 3; ++i) { active_[i] = seen_[i] = false; @@ -122,7 +125,8 @@ void AudioPlayer::setCall(bool active) { clear(i); seen_[i] = false; } - ++generation_; + ++generation_[0]; + ++generation_[1]; if (active && route_) { route_->prohibitRestore(); route_->request(0); @@ -140,7 +144,8 @@ void AudioPlayer::endSession() { for (unsigned i = 0; i < 3; ++i) { clear(i); } - ++generation_; + ++generation_[0]; + ++generation_[1]; if (route_) { route_->request(0); } @@ -162,7 +167,7 @@ void AudioPlayer::stream(uint8_t channel, uint32_t session, uint32_t config, boo self->configs_[index] = config; if (started || index == 1) { self->clear(index); - ++self->generation_; + ++self->generation_[self->route_ && index == 0 ? 1 : 0]; } pthread_cond_signal(&self->cv_); pthread_mutex_unlock(&self->mu_); @@ -246,23 +251,33 @@ void* AudioPlayer::threadMain(void* user) { void AudioPlayer::run() { int16_t samples[480 * 2]; size_t count = 0, offset = 0; - uint32_t generation = 0; + uint32_t generation[] = {0, 0}; uint32_t stalledSince = 0; + uint32_t lastPromptWrite = 0; bool stalled = false; + bool promptPending = false; uint16_t selected = 0; bool granted = false; for (;;) { pthread_mutex_lock(&mu_); - if (generation != generation_) { - count = offset = 0; - generation = generation_; - stalled = false; + const bool mediaReset = generation[0] != generation_[0]; + const bool promptReset = generation[1] != generation_[1]; + if (mediaReset || promptReset) { + if (selected == 0x31A ? promptReset : mediaReset) { + count = offset = 0; + stalled = false; + } + if (promptReset) { + promptPending = false; + } + generation[0] = generation_[0]; + generation[1] = generation_[1]; const bool quit = quit_; pthread_mutex_unlock(&mu_); if (quit) { break; } - if (!output_.flush() || (promptOpen_ && !promptOutput_.flush())) { + if ((mediaReset && !output_.flush()) || (promptReset && promptOpen_ && !promptOutput_.flush())) { failure_.store(-EIO); break; } @@ -290,17 +305,33 @@ void AudioPlayer::run() { promptOpen_ = true; continue; } - route_->request(wanted); if (route_->failure()) { failure_.store(-EIO); pthread_mutex_unlock(&mu_); break; } + if (selected == 0x31A && wanted != selected && promptPending && !inCall_ && !quit_ && + route_->owns(selected)) { + pthread_mutex_unlock(&mu_); + const long pending = promptOutput_.pendingFrames(); + if (pending < 0 || (pending > 0 && now - lastPromptWrite >= kPlaybackTimeoutMs)) { + ELOG("AudioPlayer", "cannot finish prompt playback (pending=%ld)", pending); + failure_.store(pending < 0 ? static_cast(pending) : -ETIMEDOUT); + break; + } + promptPending = pending > 0; + if (promptPending) { + usleep(10000); + } + continue; + } + route_->request(wanted); if (selected != wanted) { selected = wanted; granted = false; count = offset = 0; stalled = false; + promptPending = false; pthread_mutex_unlock(&mu_); if (!output_.flush() || (promptOpen_ && !promptOutput_.flush())) { failure_.store(-EIO); @@ -359,7 +390,7 @@ void AudioPlayer::run() { break; } pthread_cond_wait(&cv_, &mu_); - if (generation != generation_) { + if (generation[0] != generation_[0]) { break; } } @@ -378,12 +409,16 @@ void AudioPlayer::run() { if (written > 0) { offset += static_cast(written); stalled = false; + if (prompt) { + promptPending = true; + lastPromptWrite = monoMs(); + } } else if (written == 0 || written == -EAGAIN) { const uint32_t now = monoMs(); if (!stalled) { stalled = true; stalledSince = now; - } else if (now - stalledSince >= 2000) { + } else if (now - stalledSince >= kPlaybackTimeoutMs) { failure_.store(-ETIMEDOUT); ELOG("AudioPlayer", "playback stalled for 2 seconds"); break; diff --git a/platform/audio_player.hpp b/platform/audio_player.hpp index 5bc5c4a..c70ad13 100644 --- a/platform/audio_player.hpp +++ b/platform/audio_player.hpp @@ -55,7 +55,7 @@ class AudioPlayer { pthread_cond_t cv_; pthread_t thread_; bool started_, quit_, active_[3], inCall_, seen_[3], promptOpen_; - uint32_t sessions_[3], configs_[3], generation_, lastData_[3]; + uint32_t sessions_[3], configs_[3], generation_[2], lastData_[3]; uint64_t submitted_[3], released_[3]; std::atomic failure_; }; diff --git a/platform/audio_route.cpp b/platform/audio_route.cpp index c7bc16a..8fa2792 100644 --- a/platform/audio_route.cpp +++ b/platform/audio_route.cpp @@ -11,7 +11,7 @@ namespace evo { namespace { const uint8_t kBlock = 0x03; const uint16_t kTable = 0xC03, kBuildFunction = 0x053, kRemoveFunction = 0x054; -const uint32_t kTimeoutMs = 10000, kPollMs = 1000; +const uint32_t kPollMs = 1000; bool has(const std::vector& entries, uint16_t value) { return std::find(entries.begin(), entries.end(), value) != entries.end(); @@ -145,7 +145,7 @@ void AudioRoute::tick(uint32_t now, VmostPort& port) { query(kPreflight, now, port); return; } - if (phase_ != kIdle && phase_ != kPlaying && !received_ && now - sentAt_ >= kTimeoutMs && !timedOut_) { + if (phase_ != kIdle && phase_ != kPlaying && !received_ && now - sentAt_ >= kReplyTimeoutMs && !timedOut_) { timedOut_ = true; fail("connection table or route request timed out; ownership is uncertain"); if (phase_ != kBuild && phase_ != kRemove && phase_ != kRestore) { diff --git a/platform/audio_route.hpp b/platform/audio_route.hpp index 716e7d0..9dbf3d9 100644 --- a/platform/audio_route.hpp +++ b/platform/audio_route.hpp @@ -13,6 +13,8 @@ namespace evo { class AudioRoute : public VmostPeer { public: + static const uint32_t kReplyTimeoutMs = 10000; + AudioRoute(); // Called from other threads. A zero route releases the current one. Repeated calls are harmless. void enable(bool on) { diff --git a/platform/main.cpp b/platform/main.cpp index e8f551d..2849e76 100644 --- a/platform/main.cpp +++ b/platform/main.cpp @@ -471,11 +471,15 @@ int main(int argc, char** argv) { knob.setPeer(&mostPeers); if (!knob.start(input, evo::ServiceApp::knobEvent, &app)) { ELOG("Main", "controller unavailable for this run"); + if (usb) { + app.audioRoute.connectionLost(); + } } } else if (usb) { knob.setPeer(&mostPeers); if (!knob.start(input, nullptr, nullptr)) { ELOG("Main", "vMOST unavailable for direct audio"); + app.audioRoute.connectionLost(); } } app.markReady(); diff --git a/platform/service_app.cpp b/platform/service_app.cpp index 25eb888..f5e3fe4 100644 --- a/platform/service_app.cpp +++ b/platform/service_app.cpp @@ -619,12 +619,14 @@ void ServiceApp::startProjection(int fd, bool overUsb) { ELOG("ServiceApp", "Android Auto starts aside: the iDrive app shows it once iDrive is on its page"); } bool direct = false; - for (unsigned waited = 0; - overUsb && !a->audioRoute.ready() && !a->audioRoute.failure() && waited < 2000 && !a->stopRequested(); - waited += 50) { + const uint32_t preflightStart = monoMs(); + // Let the vMOST worker finish its query, with a bounded allowance for dispatch. + while (overUsb && !a->audioRoute.ready() && !a->audioRoute.failure() && !a->stopRequested() && + monoMs() - preflightStart < AudioRoute::kReplyTimeoutMs + 1000) { usleep(50000); } - if (overUsb && a->audioRoute.ready()) { + const bool stopping = overUsb && a->stopRequested(); + if (overUsb && !stopping && a->audioRoute.ready() && !a->audioRoute.failure()) { direct = a->audioPlayer.startRouted(a->audioRoute, "entertainment", "carplay_alt"); if (direct) { a->audioRouteUsed = true; @@ -634,12 +636,16 @@ void ServiceApp::startProjection(int fd, bool overUsb) { } } if (overUsb && !direct) { - ELOG("ServiceApp", "USB direct audio setup failed (route ready=%d, error=%d); restart service to retry", - a->audioRoute.ready(), a->audioRoute.failure()); + if (!stopping) { + ELOG("ServiceApp", "USB direct audio setup failed (route ready=%d, error=%d); restart service to retry", + a->audioRoute.ready(), a->audioRoute.failure()); + } close(fd); a->server.notifySessionEnded(); pthread_mutex_lock(&a->mu); - a->audioBlocked = true; + if (!stopping) { + a->audioBlocked = true; + } a->tcpPreparing = false; pthread_mutex_unlock(&a->mu); pthread_mutex_unlock(&a->connectMu); diff --git a/tests/fake_audio_output.c b/tests/fake_audio_output.c index 00e5636..2d5ed46 100644 --- a/tests/fake_audio_output.c +++ b/tests/fake_audio_output.c @@ -4,7 +4,7 @@ #include static int fake_pcm, prompt_pcm, media_state, prompt_state, starts, next_error, closed, recovered, written; -static int prompt_written, dropped, stuck; +static int prompt_written, dropped, stuck, prompt_delay, prompt_delay_checks, prompt_dropped; static int* state_for(void* pcm) { return pcm == &fake_pcm ? &media_state : &prompt_state; } @@ -53,11 +53,24 @@ int snd_pcm_close(void* pcm) { __atomic_add_fetch(&closed, 1, __ATOMIC_SEQ_CST); return 0; } +int snd_pcm_delay(void* pcm, long* frames) { + if (pcm != &fake_pcm && pcm != &prompt_pcm) { + return -EINVAL; + } + *frames = pcm == &prompt_pcm ? __atomic_load_n(&prompt_delay, __ATOMIC_SEQ_CST) : 0; + if (pcm == &prompt_pcm) { + __atomic_add_fetch(&prompt_delay_checks, 1, __ATOMIC_SEQ_CST); + } + return 0; +} int snd_pcm_drop(void* pcm) { if (pcm != &fake_pcm && pcm != &prompt_pcm) { return -EINVAL; } __atomic_add_fetch(&dropped, 1, __ATOMIC_SEQ_CST); + if (pcm == &prompt_pcm) { + __atomic_add_fetch(&prompt_dropped, 1, __ATOMIC_SEQ_CST); + } __atomic_store_n(state_for(pcm), 1, __ATOMIC_SEQ_CST); return 0; } @@ -104,3 +117,12 @@ int fake_audio_starts(void) { void fake_audio_stuck(int value) { __atomic_store_n(&stuck, value, __ATOMIC_SEQ_CST); } +void fake_audio_prompt_delay(int frames) { + __atomic_store_n(&prompt_delay, frames, __ATOMIC_SEQ_CST); +} +int fake_audio_prompt_delay_checks(void) { + return __atomic_load_n(&prompt_delay_checks, __ATOMIC_SEQ_CST); +} +int fake_audio_prompt_dropped(void) { + return __atomic_load_n(&prompt_dropped, __ATOMIC_SEQ_CST); +} diff --git a/tests/test_routed_audio.cpp b/tests/test_routed_audio.cpp index daae838..ad813a1 100644 --- a/tests/test_routed_audio.cpp +++ b/tests/test_routed_audio.cpp @@ -61,12 +61,15 @@ int main(int argc, char** argv) { assert(lib); typedef int (*Get)(); typedef void (*Set)(int); - Get written = nullptr, promptWritten = nullptr; - Set error = nullptr; + Get written = nullptr, promptWritten = nullptr, promptDelayChecks = nullptr, promptDropped = nullptr; + Set error = nullptr, promptDelay = nullptr; *reinterpret_cast(&written) = dlsym(lib, "fake_audio_written"); *reinterpret_cast(&promptWritten) = dlsym(lib, "fake_audio_prompt_written"); *reinterpret_cast(&error) = dlsym(lib, "fake_audio_error"); - assert(written && promptWritten && error); + *reinterpret_cast(&promptDelay) = dlsym(lib, "fake_audio_prompt_delay"); + *reinterpret_cast(&promptDelayChecks) = dlsym(lib, "fake_audio_prompt_delay_checks"); + *reinterpret_cast(&promptDropped) = dlsym(lib, "fake_audio_prompt_dropped"); + assert(written && promptWritten && error && promptDelay && promptDelayChecks && promptDropped); evo::AudioRoute route; Port port; @@ -78,8 +81,16 @@ int main(int argc, char** argv) { evo::AudioPlayer player; assert(player.startRouted(route, "test", "prompt", argv[1])); const uint8_t voice[] = {1, 0, 2, 0}; + promptDelay(6); evo::AudioPlayer::stream(8, 1, 0, true, &player); - evo::AudioPlayer::data(8, 1, voice, sizeof(voice), 0, &player); + uint64_t voiceMarker = 0; + for (unsigned i = 0; i < 100 && !voiceMarker; ++i) { + voiceMarker = evo::AudioPlayer::data(8, 1, voice, sizeof(voice), 0, &player); + if (!voiceMarker) { + usleep(10000); + } + } + assert(voiceMarker == 6); evo::AudioPlayer::stream(8, 1, 0, false, &player); // the route may be granted after STOP waitRequest(route, port, 2); assert(port.messages.back().function == 0xC03); @@ -95,6 +106,23 @@ int main(int argc, char** argv) { } assert(promptWritten() == 6 && written() == 0); + const int drops = promptDropped(); + for (unsigned i = 0; i < 100 && !promptDelayChecks(); ++i) { + usleep(10000); + } + assert(promptDelayChecks() && promptDropped() == drops); + const int checks = promptDelayChecks(); + evo::AudioPlayer::stream(9, 2, 0, true, &player); + for (unsigned i = 0; i < 100 && promptDelayChecks() == checks; ++i) { + usleep(10000); + } + assert(promptDelayChecks() > checks && promptDropped() == drops); + promptDelay(0); + for (unsigned i = 0; i < 100 && promptDropped() == drops; ++i) { + usleep(10000); + } + assert(promptDropped() == drops + 1); + player.setCall(true); evo::AudioPlayer::data(8, 1, voice, sizeof(voice), 0, &player); usleep(50000); diff --git a/tests/test_wireless_lifecycle.cpp b/tests/test_wireless_lifecycle.cpp index 4a994c0..586a26e 100644 --- a/tests/test_wireless_lifecycle.cpp +++ b/tests/test_wireless_lifecycle.cpp @@ -228,6 +228,37 @@ static void* audioGateConnect(void* user) { return nullptr; } +static void usbAudioSlowPreflight() { + evo::ServiceApp app(50000, false, &quitFlag); + AudioGatePort port; + app.markReady(); + app.audioRoute.enable(true); + app.audioRoute.tick(evo::monoMs(), port); + assert(port.function == 0xC03); + + int pair[2]; + assert(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0); + AudioGateConnection connection = {&app, pair[0], true}; + pthread_t thread; + assert(pthread_create(&thread, nullptr, audioGateConnect, &connection) == 0); + for (unsigned i = 0; i < 200 && !app.projectionBusy(); ++i) { + usleep(10000); + } + assert(app.projectionBusy()); + const uint32_t started = evo::monoMs(); + while (evo::monoMs() - started < 2200 && app.projectionBusy()) { + usleep(10000); + } + assert(app.projectionBusy() && !app.session.isActive()); + + app.requestStop(); + pthread_join(thread, nullptr); + assert(!app.audioBlocked && !app.projectionBusy()); + close(pair[1]); + app.audioRoute.finish(port); + puts("PASS USB audio preflight: waits past two seconds and cancels on stop"); +} + static void usbAudioCleanupGate() { evo::ServiceApp app(50000, false, &quitFlag); AudioGatePort port; @@ -581,5 +612,6 @@ int main() { usbAudioFailure(audioLibrary); } usbAudioUnavailable(); + usbAudioSlowPreflight(); usbAudioCleanupGate(); } From 4b1ba1837c4e2fcfab3486c2d1c0c732da41bedb Mon Sep 17 00:00:00 2001 From: mbalous Date: Mon, 30 Nov 2026 23:55:42 +0100 Subject: [PATCH 08/10] Fix audio test submissions under lock contention Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/audio_test_util.hpp | 24 ++++++++++++++++++++++++ tests/test_audio_player.cpp | 5 +++-- tests/test_routed_audio.cpp | 17 ++++++----------- tests/test_wireless_lifecycle.cpp | 3 ++- 4 files changed, 35 insertions(+), 14 deletions(-) create mode 100644 tests/audio_test_util.hpp diff --git a/tests/audio_test_util.hpp b/tests/audio_test_util.hpp new file mode 100644 index 0000000..a1be535 --- /dev/null +++ b/tests/audio_test_util.hpp @@ -0,0 +1,24 @@ +// Copyright (c) 2026 mbalous +// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 +#ifndef ENTRY_AAD_TESTS_AUDIO_TEST_UTIL_HPP +#define ENTRY_AAD_TESTS_AUDIO_TEST_UTIL_HPP + +#include +#include + +#include "audio_player.hpp" + +inline uint64_t submitAudio(evo::AudioPlayer& player, uint8_t channel, uint32_t session, const uint8_t* pcm, + size_t bytes) { + uint64_t marker = 0; + for (unsigned i = 0; i < 200 && !marker; ++i) { + marker = evo::AudioPlayer::data(channel, session, pcm, bytes, 0, &player); + if (!marker) { + usleep(10000); + } + } + assert(marker); + return marker; +} + +#endif diff --git a/tests/test_audio_player.cpp b/tests/test_audio_player.cpp index fe69749..5e468f6 100644 --- a/tests/test_audio_player.cpp +++ b/tests/test_audio_player.cpp @@ -9,6 +9,7 @@ #include #include "audio_player.hpp" +#include "audio_test_util.hpp" int main(int argc, char** argv) { assert(argc == 2); @@ -74,7 +75,7 @@ int main(int argc, char** argv) { evo::AudioPlayer::stream(9, 7, 0, false, &player); setError(-EIO); evo::AudioPlayer::stream(9, 8, 0, true, &player); - evo::AudioPlayer::data(9, 8, pcm, sizeof(pcm), 0, &player); + submitAudio(player, 9, 8, pcm, sizeof(pcm)); for (unsigned i = 0; i < 200 && !player.failure(); ++i) { usleep(10000); } @@ -84,7 +85,7 @@ int main(int argc, char** argv) { assert(player.start("test", argv[1])); setStuck(1); evo::AudioPlayer::stream(9, 9, 0, true, &player); - evo::AudioPlayer::data(9, 9, pcm, sizeof(pcm), 0, &player); + submitAudio(player, 9, 9, pcm, sizeof(pcm)); for (unsigned i = 0; i < 400 && !player.failure(); ++i) { usleep(10000); } diff --git a/tests/test_routed_audio.cpp b/tests/test_routed_audio.cpp index ad813a1..956c698 100644 --- a/tests/test_routed_audio.cpp +++ b/tests/test_routed_audio.cpp @@ -10,6 +10,7 @@ #include "audio_player.hpp" #include "audio_route.hpp" +#include "audio_test_util.hpp" #include "evo_log.hpp" struct Message { @@ -83,13 +84,7 @@ int main(int argc, char** argv) { const uint8_t voice[] = {1, 0, 2, 0}; promptDelay(6); evo::AudioPlayer::stream(8, 1, 0, true, &player); - uint64_t voiceMarker = 0; - for (unsigned i = 0; i < 100 && !voiceMarker; ++i) { - voiceMarker = evo::AudioPlayer::data(8, 1, voice, sizeof(voice), 0, &player); - if (!voiceMarker) { - usleep(10000); - } - } + const uint64_t voiceMarker = submitAudio(player, 8, 1, voice, sizeof(voice)); assert(voiceMarker == 6); evo::AudioPlayer::stream(8, 1, 0, false, &player); // the route may be granted after STOP waitRequest(route, port, 2); @@ -141,7 +136,7 @@ int main(int argc, char** argv) { const uint8_t music[] = {1, 0, 2, 0, 3, 0, 4, 0}; evo::AudioPlayer::stream(8, 1, 0, false, &player); evo::AudioPlayer::stream(9, 2, 0, true, &player); - evo::AudioPlayer::data(9, 2, music, sizeof(music), 0, &player); + submitAudio(player, 9, 2, music, sizeof(music)); const size_t next = port.messages.size() + 1; waitRequest(route, port, next); table(route, {1}); @@ -156,7 +151,7 @@ int main(int argc, char** argv) { } assert(written() == 2 && player.failure() == 0); error(-EIO); - evo::AudioPlayer::data(9, 2, music, sizeof(music), 0, &player); + submitAudio(player, 9, 2, music, sizeof(music)); for (unsigned i = 0; i < 200 && !player.failure(); ++i) { usleep(10000); } @@ -179,7 +174,7 @@ int main(int argc, char** argv) { evo::AudioPlayer missingPrompt; assert(missingPrompt.startRouted(missingPromptRoute, "test", "missing", argv[1])); evo::AudioPlayer::stream(8, 3, 0, true, &missingPrompt); - evo::AudioPlayer::data(8, 3, voice, sizeof(voice), 0, &missingPrompt); + submitAudio(missingPrompt, 8, 3, voice, sizeof(voice)); for (unsigned i = 0; i < 200 && !missingPrompt.failure(); ++i) { usleep(10000); } @@ -195,7 +190,7 @@ int main(int argc, char** argv) { evo::AudioPlayer endedPlayer; assert(endedPlayer.startRouted(endedRoute, "test", "prompt", argv[1])); evo::AudioPlayer::stream(8, 4, 0, true, &endedPlayer); - evo::AudioPlayer::data(8, 4, voice, sizeof(voice), 0, &endedPlayer); + submitAudio(endedPlayer, 8, 4, voice, sizeof(voice)); waitRequest(endedRoute, endedPort, 2); endedPlayer.endSession(); table(endedRoute, {1}); diff --git a/tests/test_wireless_lifecycle.cpp b/tests/test_wireless_lifecycle.cpp index 586a26e..2298ef8 100644 --- a/tests/test_wireless_lifecycle.cpp +++ b/tests/test_wireless_lifecycle.cpp @@ -16,6 +16,7 @@ #include #include "alps_spp.hpp" +#include "audio_test_util.hpp" #include "evo_ap.hpp" #include "evo_log.hpp" #include "service_app.hpp" @@ -153,7 +154,7 @@ static void usbAudioFailure(const char* library) { const uint8_t pcm[] = {1, 0, 2, 0}; setError(-EIO); evo::AudioPlayer::stream(9, 7, 0, true, &app.audioPlayer); - evo::AudioPlayer::data(9, 7, pcm, sizeof(pcm), 0, &app.audioPlayer); + submitAudio(app.audioPlayer, 9, 7, pcm, sizeof(pcm)); for (unsigned i = 0; i < 200 && !app.audioPlayer.failure(); ++i) { usleep(10000); } From 76b8aaa2ab14c1df3a245d14a8b713c7c30e7fff Mon Sep 17 00:00:00 2001 From: mbalous Date: Thu, 3 Dec 2026 01:07:11 +0100 Subject: [PATCH 09/10] fix(audio): clean up before wireless rejoin Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- platform/service_app.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/platform/service_app.cpp b/platform/service_app.cpp index f5e3fe4..f0fd260 100644 --- a/platform/service_app.cpp +++ b/platform/service_app.cpp @@ -557,18 +557,6 @@ void ServiceApp::startProjection(int fd, bool overUsb) { pthread_mutex_unlock(&a->mu); ELOG("ServiceApp", "phone %s connection received; preparing the video and the AA session", overUsb ? "USB" : "TCP"); a->session.stop(); // join callbacks before destroying/reinitializing video buffers - if (!overUsb && a->phoneMustRejoin()) { - close(fd); - a->server.notifySessionEnded(); - pthread_mutex_lock(&a->mu); - a->tcpPreparing = false; - // Not a session lost without ByeBye, but counted with them on purpose: the wireless loop then drops the - // Bluetooth link the phone kept, and the phone starts again with the rebuilt beacon. - ++a->lostWireless; - pthread_mutex_unlock(&a->mu); - pthread_mutex_unlock(&a->connectMu); - return; - } a->audioPlayer.stop(); a->session.setAudioCallbacks(nullptr, nullptr, nullptr); if (a->audioRouteUsed) { @@ -595,6 +583,18 @@ void ServiceApp::startProjection(int fd, bool overUsb) { a->audioCleanupRequested = false; a->audioRoute.enable(overUsb); } + if (!overUsb && a->phoneMustRejoin()) { + close(fd); + a->server.notifySessionEnded(); + pthread_mutex_lock(&a->mu); + a->tcpPreparing = false; + // Not a session lost without ByeBye, but counted with them on purpose: the wireless loop then drops the + // Bluetooth link the phone kept, and the phone starts again with the rebuilt beacon. + ++a->lostWireless; + pthread_mutex_unlock(&a->mu); + pthread_mutex_unlock(&a->connectMu); + return; + } bool videoOk = true; if (a->videoEnabled) { pthread_mutex_lock(&a->videoMu); From ab6daac8f8b306fb3595d7e14b522503488597ef Mon Sep 17 00:00:00 2001 From: mbalous Date: Thu, 3 Dec 2026 01:08:40 +0100 Subject: [PATCH 10/10] style(audio): format rebased service state Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- platform/service_app.hpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/platform/service_app.hpp b/platform/service_app.hpp index 33292e5..310f49d 100644 --- a/platform/service_app.hpp +++ b/platform/service_app.hpp @@ -141,11 +141,11 @@ class ServiceApp : public WirelessHost, public UsbHost { unsigned sppLinks, tcpLinks, usbLinks; std::atomic videoFrames; // counted on the session thread without mu bool wppReply, wppAccepted; - bool projectionOverUsb; // the last session came over USB (its loss is not the wireless loop's business) + bool projectionOverUsb; // the last session came over USB (its loss is not the wireless loop's business) bool directAudio, audioBlocked; // under mu: persistent audio failure requires a service restart bool audioRouteUsed, audioCleanupRequested; // under connectMu: cleanup before another session - unsigned lostWireless; // wireless sessions ended without ByeBye, and connections refused for 802.11n (#203) - unsigned htRebuilds; // beacon rebuilds in a row for a phone on 802.11n; under connectMu + unsigned lostWireless; // wireless sessions ended without ByeBye, and connections refused for 802.11n (#203) + unsigned htRebuilds; // beacon rebuilds in a row for a phone on 802.11n; under connectMu private: // A phone connection, from the TCP listener or the USB loop: the video is made ready and the session starts.