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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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

Expand Down Expand Up @@ -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
Expand Down
77 changes: 71 additions & 6 deletions core/aa_channels.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 <cstdio>
#include <limits>

#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 {
Expand Down Expand Up @@ -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<uint32_t>::max()) {
return false;
}
(field.number == 1 ? session : config) = static_cast<uint32_t>(field.value);
}
}
return !reader.malformed();
}

} // namespace

bool AASession::dispatch(uint8_t channel, const Message& message) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<unsigned>(response.size()));
}
Expand Down Expand Up @@ -285,34 +303,79 @@ 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::audioIndex(channel);
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::audioIndex(channel);
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
// it sends against its window of kMaxUnacked until acked, whether the head unit could use it or not: video cut too
// 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<unsigned>(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::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,
static_cast<unsigned>(message.size() - kTimestampedHeader),
index == 1 ? "media(ch9)"
: index == 2 ? "system(ch16)"
: "guidance(ch8)",
count, static_cast<unsigned>(message.size() - kTimestampedHeader),
static_cast<unsigned long long>(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) {
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);
}
}
}
} 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.
Expand All @@ -336,7 +399,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
Expand Down
9 changes: 8 additions & 1 deletion core/aa_protocol.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
114 changes: 111 additions & 3 deletions core/aa_session.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -80,6 +82,7 @@ AASession::AASession()
codedModel_(nullptr),
longestSilenceMs_(0),
goodbye_(false),
audioFailed_(false),
lastReceivedMs_(0),
connectedMs_(0),
givenUp_(false),
Expand All @@ -95,7 +98,9 @@ AASession::AASession()
pthread_mutex_init(&lifecycleLock_, nullptr);
pthread_mutex_init(&socketLock_, nullptr);
memset(mediaSessions_, 0, sizeof(mediaSessions_));
audioMessages_[0] = audioMessages_[1] = 0;
memset(audioMessages_, 0, sizeof(audioMessages_));
memset(audioActive_, 0, sizeof(audioActive_));
memset(audioConfig_, 0, sizeof(audioConfig_));
resetCounters();
}

Expand Down Expand Up @@ -135,6 +140,21 @@ void AASession::setNavStatusCallback(NavStatusCallback cb, void* user_data) {
navigation_.user = user_data;
}

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;
}

void AASession::postTouchEvent(const TouchEventOut& ev) {
inbox_.postTouch(ev);
}
Expand Down Expand Up @@ -210,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;
}
Expand Down Expand Up @@ -253,7 +275,10 @@ bool AASession::start(int client_fd) {
microphoneChunks_ = 0;
mediaMessages_ = 0;
memset(mediaSessions_, 0, sizeof(mediaSessions_));
audioMessages_[0] = audioMessages_[1] = 0;
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;
Expand All @@ -263,6 +288,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) {
Expand Down Expand Up @@ -334,6 +360,12 @@ void AASession::run() {

void AASession::finish() {
inbox_.stopLocation();
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();
Expand All @@ -353,6 +385,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",
Expand Down Expand Up @@ -390,7 +427,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<int>((delayUs + 999) / 1000));
if (ready < 0) {
if (errno == EINTR) {
continue;
Expand Down Expand Up @@ -444,6 +482,76 @@ bool AASession::receiveExactly(uint8_t* to, size_t size) {
return got == size;
}

void AASession::deferAudioAck(uint8_t channel, uint32_t session, uint64_t marker) {
const unsigned index = channel::audioIndex(channel);
std::deque<AudioAck>& 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 AudioAck ack = {session, marker, monotonicUs() + kAudioAckTimeoutUs};
queue.push_back(ack);
}

void AASession::sendDueAudioAcks(uint64_t nowUs) {
for (unsigned index = 0; index < 3; ++index) {
std::deque<AudioAck>& queue = audioAcks_[index];
const uint8_t channel = channel::audioChannel(index);
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))) {
return;
}
}
}
}

void AASession::flushAudioAcks(uint8_t channel) {
const unsigned index = channel::audioIndex(channel);
std::deque<AudioAck>& 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 < 3; ++index) {
if (!audioAcks_[index].empty()) {
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;
}
}
}
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
Expand Down
Loading
Loading