From 561e91e2160c667c654eb5fb1a35871a11d71502 Mon Sep 17 00:00:00 2001 From: Oleksandr Shyshatskyi Date: Wed, 28 Oct 2026 19:29:14 +0200 Subject: [PATCH] Fix navigation speech with stock audio focus grants --- backends/osmand/CMakeLists.txt | 4 +- backends/osmand/navi_voiced.cpp | 22 ++- backends/osmand/qnx_pcm_out.cpp | 12 +- backends/osmand/qnx_pcm_out.h | 1 + backends/osmand/stock_focus.cpp | 64 +++++++ backends/osmand/stock_focus.h | 22 +++ contracts/qr39/provider/slot-manifest.csv | 6 +- docs/design/voice-guidance-wiring.md | 45 +++++ src/CMakeLists.txt | 1 + src/compat/qr39/navicore_compat.c | 97 ++++++++++- src/compat/qr39/provider_slots.def | 3 - src/runtime/open_navi_audio_focus.c | 194 ++++++++++++++++++++++ src/runtime/open_navi_audio_focus.h | 23 +++ tests/CMakeLists.txt | 3 +- tests/run_plugin_tests.sh | 2 +- tests/stock_focus_test.cpp | 80 +++++++++ 16 files changed, 555 insertions(+), 24 deletions(-) create mode 100644 backends/osmand/stock_focus.cpp create mode 100644 backends/osmand/stock_focus.h create mode 100644 src/runtime/open_navi_audio_focus.c create mode 100644 src/runtime/open_navi_audio_focus.h create mode 100644 tests/stock_focus_test.cpp diff --git a/backends/osmand/CMakeLists.txt b/backends/osmand/CMakeLists.txt index 6e422c5..48ca3fe 100644 --- a/backends/osmand/CMakeLists.txt +++ b/backends/osmand/CMakeLists.txt @@ -31,7 +31,7 @@ endif() # Voice daemon pieces that the plugin does not link (it keeps an exact, reviewed # dependency set): the process-backed audio focus. Host-testable. -add_library(voice_daemon STATIC process_focus.cpp) +add_library(voice_daemon STATIC process_focus.cpp stock_focus.cpp) target_include_directories(voice_daemon PUBLIC ${ONC_ROOT}/include ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(voice_daemon PUBLIC navigation_ui) target_compile_options(voice_daemon PRIVATE ${ONC_WARNINGS}) @@ -52,7 +52,7 @@ if(RHVOICE_BUILD AND RHVOICE_INCLUDE) add_executable(navi_voiced navi_voiced.cpp rhvoice_engine.cpp ${ONC_RHVOICE_OBJECTS}) target_include_directories(navi_voiced PRIVATE ${RHVOICE_INCLUDE}) target_compile_options(navi_voiced PRIVATE ${ONC_WARNINGS} ${ONC_TARGET_FLAGS}) - target_link_libraries(navi_voiced PRIVATE voice_daemon navigation_ui asound m) + target_link_libraries(navi_voiced PRIVATE voice_daemon navigation_ui asound socket m) # libasound needs libpps.so.1, which the linker only finds through -rpath-link. target_link_options(navi_voiced PRIVATE -static-libstdc++ -static-libgcc -Wl,-rpath-link,${CMAKE_SYSROOT}/armle-v7/lib) diff --git a/backends/osmand/navi_voiced.cpp b/backends/osmand/navi_voiced.cpp index 8bf2ab8..f910c40 100644 --- a/backends/osmand/navi_voiced.cpp +++ b/backends/osmand/navi_voiced.cpp @@ -1,14 +1,15 @@ // navi_voiced: speaks navigation prompts sent by the OsmAnd backend. // // navi_voiced [--queue NAME] [--device PCM] [--rhvoice-data DIR] [--voice NAME] -// [--rate PERCENT] [--focus none|alloc] [--alloc-cmd PATH] +// [--rate PERCENT] [--focus stock|none|alloc] [--alloc-cmd PATH] // [--alloc-route CHANNEL SOURCE ZONE] [--selftest TEXT] // // Receives messages (voice_link.h), synthesizes with RHVoice, plays on io-audio -// and, with --focus alloc, holds the DSP channel through the as_alloc helper -// (contracts/native/as_audio_service_allocate_channel.md). --selftest speaks one +// and waits for stock navigation allocation and preparation before playing. +// --focus alloc is retained only for explicit diagnostics. --selftest speaks one // sentence through the same stack and exits; it is the first thing to run on the radio. #include "process_focus.h" +#include "stock_focus.h" #include "qnx_pcm_out.h" #include "rhvoice_engine.h" #include "voice_link.h" @@ -38,7 +39,7 @@ struct Options { std::string rhvoice_data = "/tmp/tts/rhvoice"; std::string voice = "Natalia"; int rate_percent = 100; - bool focus_alloc = false; + std::string focus = "stock"; std::string alloc_cmd = "/tmp/tts/as_alloc"; std::string channel = "2", source = "8", zone = "1"; // NAVIGATION / NAVI / DRIVER std::string selftest; @@ -59,8 +60,8 @@ bool parse(int argc, char** argv, Options& o) { else if (a == "--rate") { std::string v; if (!value(v)) return false; o.rate_percent = std::atoi(v.c_str()); } else if (a == "--focus") { std::string v; - if (!value(v) || (v != "none" && v != "alloc")) return false; - o.focus_alloc = v == "alloc"; + if (!value(v) || (v != "stock" && v != "none" && v != "alloc")) return false; + o.focus = v; } else if (a == "--alloc-cmd") { if (!value(o.alloc_cmd)) return false; } else if (a == "--alloc-route") { @@ -80,7 +81,7 @@ int main(int argc, char** argv) { if (!parse(argc, argv, opt)) { std::fprintf(stderr, "usage: %s [--queue NAME] [--device PCM] [--rhvoice-data DIR] [--voice NAME]\n" - " [--rate PERCENT] [--focus none|alloc] [--alloc-cmd PATH]\n" + " [--rate PERCENT] [--focus stock|none|alloc] [--alloc-cmd PATH]\n" " [--alloc-route CHANNEL SOURCE ZONE] [--selftest TEXT]\n", argv[0]); return 64; } @@ -89,7 +90,10 @@ int main(int argc, char** argv) { engine.set_rate_percent(opt.rate_percent); std::unique_ptr focus; - if (opt.focus_alloc) { + if (opt.focus == "stock") { + focus.reset(new StockFocus()); + } else if (opt.focus == "alloc") { + std::fprintf(stderr, "voice: --focus alloc is an unverified diagnostic path; use stock for guidance\n"); ProcessFocus::Options f; f.argv = {opt.alloc_cmd, opt.channel, opt.source, opt.zone, "86400"}; f.env = {"LD_LIBRARY_PATH=/pas/lib/dll:/pas/lib:/lib:/usr/lib:/proc/boot"}; @@ -122,7 +126,7 @@ int main(int argc, char** argv) { sigaction(SIGTERM, &sa, nullptr); sigaction(SIGINT, &sa, nullptr); std::printf("navi_voiced ready queue=%s device=%s focus=%s voice=%s\n", opt.queue.c_str(), - opt.device.c_str(), opt.focus_alloc ? "alloc" : "none", opt.voice.c_str()); + opt.device.c_str(), opt.focus.c_str(), opt.voice.c_str()); std::fflush(stdout); server.run(); g_server = nullptr; diff --git a/backends/osmand/qnx_pcm_out.cpp b/backends/osmand/qnx_pcm_out.cpp index b3eca03..fcee3b1 100644 --- a/backends/osmand/qnx_pcm_out.cpp +++ b/backends/osmand/qnx_pcm_out.cpp @@ -69,20 +69,23 @@ bool QnxPcmOut::open_device(unsigned sample_rate_hz) { void QnxPcmOut::close_device() { if (!handle_) return; snd_pcm_t* h = static_cast(handle_); - snd_pcm_plugin_flush(h, SND_PCM_CHANNEL_PLAYBACK); // drains what was written + if (focus_.valid()) snd_pcm_plugin_playback_drain(h); + else snd_pcm_plugin_flush(h, SND_PCM_CHANNEL_PLAYBACK); snd_pcm_close(h); handle_ = nullptr; rate_ = 0; } bool QnxPcmOut::write(const short* samples, std::size_t count, unsigned sample_rate_hz) { - if (!focused_) return false; + if (!focused_ || !focus_.valid()) return false; if (handle_ && rate_ != sample_rate_hz) close_device(); if (!handle_ && !open_device(sample_rate_hz)) return false; snd_pcm_t* h = static_cast(handle_); const char* p = reinterpret_cast(samples); std::size_t left = count * sizeof(short); + unsigned stalled = 0; while (left > 0) { + if (!focus_.valid()) return false; std::size_t n = left < fragment_ ? left : fragment_; ssize_t w = snd_pcm_plugin_write(h, p, n); if (w < static_cast(n)) { @@ -98,6 +101,11 @@ bool QnxPcmOut::write(const short* samples, std::size_t count, unsigned sample_r } if (w < 0) w = 0; } + if (w <= 0 && ++stalled >= 3) { + std::fprintf(stderr, "voice: pcm made no progress\n"); + return false; + } + if (w > 0) stalled = 0; p += w; left -= static_cast(w); } diff --git a/backends/osmand/qnx_pcm_out.h b/backends/osmand/qnx_pcm_out.h index e197235..a761f70 100644 --- a/backends/osmand/qnx_pcm_out.h +++ b/backends/osmand/qnx_pcm_out.h @@ -19,6 +19,7 @@ class AudioFocus { public: virtual ~AudioFocus() = default; virtual bool request() = 0; + virtual bool valid() { return true; } virtual void release() = 0; }; diff --git a/backends/osmand/stock_focus.cpp b/backends/osmand/stock_focus.cpp new file mode 100644 index 0000000..13d5d67 --- /dev/null +++ b/backends/osmand/stock_focus.cpp @@ -0,0 +1,64 @@ +#include "stock_focus.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace navicore_osmand { +bool StockFocus::request() { + release(); + struct sockaddr_un sa{}; + if (path_.size() >= sizeof(sa.sun_path)) return false; + fd_ = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd_ < 0) return false; + fcntl(fd_, F_SETFD, FD_CLOEXEC); + fcntl(fd_, F_SETFL, fcntl(fd_, F_GETFL, 0) | O_NONBLOCK); + sa.sun_family = AF_UNIX; + std::memcpy(sa.sun_path, path_.c_str(), path_.size() + 1); + // A local listener accepts without waiting for stock. The bounded wait below + // is for its asynchronous allocation/preparation reply. + if (connect(fd_, reinterpret_cast(&sa), sizeof(sa)) != 0 || + send(fd_, "A", 1, MSG_NOSIGNAL) != 1) { + std::fprintf(stderr, "voice: stock focus connect: %s\n", std::strerror(errno)); + release(); return false; + } + const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms_); + while (std::chrono::steady_clock::now() < end) { + struct pollfd p = {fd_, POLLIN, 0}; + int rc = poll(&p, 1, 50); + if (rc < 0 && errno == EINTR) continue; + if (rc < 0) break; + if (rc > 0) { + char reply = 0; + if (recv(fd_, &reply, 1, 0) == 1 && reply == 'G') { + granted_ = true; + std::fprintf(stderr, "voice: stock focus granted\n"); + return valid(); + } + std::fprintf(stderr, "voice: stock focus rejected reply=%u\n", unsigned(reply)); + break; + } + } + std::fprintf(stderr, "voice: stock focus unavailable\n"); + release(); return false; +} +bool StockFocus::valid() { + if (!granted_ || fd_ < 0) return false; + struct pollfd p = {fd_, POLLIN, 0}; + int rc = poll(&p, 1, 0); + if (rc == 0 || (rc < 0 && errno == EINTR)) return true; + // R, EOF, or any unexpected message invalidates the grant. Keep the fd open + // until release(): the server must not acknowledge before PCM is closed. + granted_ = false; + std::fprintf(stderr, "voice: stock focus revoked/disconnected\n"); + return false; +} +void StockFocus::release() { + granted_ = false; + if (fd_ >= 0) { close(fd_); fd_ = -1; } +} +} diff --git a/backends/osmand/stock_focus.h b/backends/osmand/stock_focus.h new file mode 100644 index 0000000..cb29461 --- /dev/null +++ b/backends/osmand/stock_focus.h @@ -0,0 +1,22 @@ +#pragma once +#include "qnx_pcm_out.h" +#include +namespace navicore_osmand { +// The socket is owned only by the speech worker. No detached watcher or polling +// thread: each PCM chunk checks for stock revocation or a lost provider. +class StockFocus : public AudioFocus { +public: + explicit StockFocus(std::string path = "/tmp/navicore-audio.sock", + unsigned timeout_ms = 9000) + : path_(std::move(path)), timeout_ms_(timeout_ms) {} + ~StockFocus() override { release(); } + bool request() override; + bool valid() override; + void release() override; +private: + std::string path_; + unsigned timeout_ms_; + int fd_ = -1; + bool granted_ = false; +}; +} diff --git a/contracts/qr39/provider/slot-manifest.csv b/contracts/qr39/provider/slot-manifest.csv index d40c309..a5fc219 100644 --- a/contracts/qr39/provider/slot-manifest.csv +++ b/contracts/qr39/provider/slot-manifest.csv @@ -35,9 +35,9 @@ adapter,slot,si_name,reachability,abi_words_after_self,abi_prototype,implementat "9","5","SI_GPSData","reachable_typed","1","uint32_t(self;word0)","open_navi_static_9_5","g_gps_vtable","nv_navigation:0x0810cf1c","0 while ACTIVE; 1 before init/during teardown","input words only; no output or retained storage" "9","6","SI_GPSData","reachable_typed","1","uint32_t(self;word0)","open_navi_gps_interval","g_gps_vtable","nv_navigation:0x0810cf1c","0 while ACTIVE; 1 before init/during teardown","input words only; no output or retained storage" "10","3","SI_AudioHandling","reachable_typed","3","uint32_t(self;word0;word1;word2)","open_navi_static_10_3","g_audio_vtable","nv_navigation:0x0812e560","0 while ACTIVE; 1 before init/during teardown","input words only; no output or retained storage" -"10","5","SI_AudioHandling","reachable_typed","3","uint32_t(self;word0;word1;word2)","open_navi_static_10_5","g_audio_vtable","nv_navigation:0x0812e560","0 while ACTIVE; 1 before init/during teardown","input words only; no output or retained storage" -"10","7","SI_AudioHandling","reachable_typed","3","uint32_t(self;word0;word1;word2)","open_navi_static_10_7","g_audio_vtable","nv_navigation:0x0812e560","0 while ACTIVE; 1 before init/during teardown","input words only; no output or retained storage" -"10","8","SI_AudioHandling","reachable_typed","3","uint32_t(self;word0;word1;word2)","open_navi_static_10_8","g_audio_vtable","nv_navigation:0x0812e560","0 while ACTIVE; 1 before init/during teardown","input words only; no output or retained storage" +"10","5","SI_AudioHandling","reachable_typed","3","uint32_t(self;handle;source;result)","nc_provider_audio_allocation","g_audio_vtable","nv_navigation:0x0812fcbc","0 for active matching source/transaction; 1 for stale or inactive callback; slot 5 drives stock focus worker","three 32-bit values copied under lock; source 1; allocation and preparation grant result 1; deactivation acknowledgement waits for PCM close" +"10","7","SI_AudioHandling","reachable_typed","3","uint32_t(self;handle;source;result)","nc_provider_audio_preparation","g_audio_vtable","nv_navigation:0x0812ec04","0 for active matching source/transaction; 1 for stale or inactive callback; slot 7 drives stock focus worker","three 32-bit values copied under lock; source 1; allocation and preparation grant result 1; deactivation acknowledgement waits for PCM close" +"10","8","SI_AudioHandling","reachable_typed","3","uint32_t(self;handle;source;reason)","nc_provider_audio_deactivation","g_audio_vtable","nv_navigation:0x0812f9a4","0 for active matching source/transaction; 1 for stale or inactive callback; slot 8 drives stock focus worker","three 32-bit values copied under lock; source 1; allocation and preparation grant result 1; deactivation acknowledgement waits for PCM close" "10","17","SI_AudioHandling","reachable_typed","3","uint32_t(self;word0;word1;word2)","open_navi_10_17","g_audio_vtable","nv_navigation:0x0812e560","0 while ACTIVE; 1 before init/during teardown","input words only; no output or retained storage" "10","18","SI_AudioHandling","reachable_typed","3","uint32_t(self;word0;word1;word2)","open_navi_static_10_18","g_audio_vtable","nv_navigation:0x0812e560","0 while ACTIVE; 1 before init/during teardown","input words only; no output or retained storage" "10","19","SI_AudioHandling","reachable_typed","2","uint32_t(self;word0;word1)","open_navi_audio_volume","g_audio_vtable","nv_navigation:0x0812e560","0 while ACTIVE; 1 before init/during teardown","input words only; no output or retained storage" diff --git a/docs/design/voice-guidance-wiring.md b/docs/design/voice-guidance-wiring.md index 626623c..5992b96 100644 --- a/docs/design/voice-guidance-wiring.md +++ b/docs/design/voice-guidance-wiring.md @@ -1,5 +1,50 @@ # Voice guidance: wiring Ukrainian TTS into Open NaviCore + +## Implemented stock focus, 2026-10-28 + +This section supersedes the historical design and ProcessFocus deployment notes below. +The backend continues to send prompts through `/navicore-voice`; no backend ABI change is +needed. `navi_voiced --focus stock` (the default) talks to the provider over +`/tmp/navicore-audio.sock`. One connection owns one prompt. The provider's joined worker +invokes the existing typed stock callbacks; the renderer never waits for audio. + +- Outbound adapter 10 slot 6 requests **PanaNav source 1**, mapped by stock to source 21. + This is a different enum from `as_audio_service` source 8. +- Inbound slot 5 `(handle, source, result=1)` grants allocation. The worker then sends + outbound slot 7 preparation and waits for inbound slot 7 with the same handle/source + and result 1. Only then does the daemon open/write `pcmC7D0p`. +- Inbound slot 8 requests deactivation. The daemon checks revocation between PCM writes, + flushes queued samples, closes PCM, then disconnects. The provider acknowledges with + outbound slot 9 and native success result 1. Normal completion drains PCM before + disconnecting and invoking outbound slot 8 release. +- Denial, stale callbacks, a missing provider, and timeouts fail visibly. There is no + automatic fallback. Explicit `--focus alloc` and `--focus none` remain diagnostics. + A request made before the stock audio adapter is initialized can expire. + +Recovered callsites: allocation `0812fee8`, preparation `0812e868`, release `0812db5c`, +deactivation reply `0812d8e4`; inbound allocation `0812fcbc`, preparation `0812ec04`, +deactivation `0812f9a4`. The provider slot manifest records the three inbound contracts. +The local protocol is `A` request, `G` granted, `D` denied, `R` revoked; disconnect releases. +Acquisition expires after 8 seconds (client 9), a held grant after 60 seconds, and a dead +revoked client after 2 seconds. The provider stops/joins its listener at deinitialization. + +Implementation: `src/runtime/open_navi_audio_focus.*`, provider adapter 10 methods, +`backends/osmand/stock_focus.*`, and `qnx_pcm_out.*`. QNX's playback-drain call replaces +flush on normal completion; flush is used for revoked audio. `navi_voiced` now links +`libsocket`; the backend dependency set is unchanged. + +Validation: all 36 host tests pass, including asynchronous grant/preparation, stale +callbacks, denial, disconnect, timeout, and revocation acknowledgement ordering. QNX +build, provider ABI/ELF checks, and both IFS packages pass. On M9304002366, the stock +callbacks granted source 1 and selftest reported `spoken=1`, all failure counters zero. +A prompt sent through the installed daemon's normal message queue also received both +grants and released focus. Speaker audibility has not yet been confirmed by the operator. +The external workspace report `contracts/native/navi_audio_silence_20261028.md` contains +Ghidra and live evidence paths and the installation record. + +## Historical design (2026-10-20) + 2026-10-20. Offline analysis, nothing was run on the radio for this note. It answers: how do spoken guidance prompts get from the OsmAnd backend to the speakers, given what the TTS work found about sound (`contracts/native/as_audio_service_allocate_channel.md` in the radio workspace, outside this repository)? diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 415aa0b..4b317ba 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -7,6 +7,7 @@ set(ONC_PROVIDER_INCLUDES ${ONC_ROOT}/include ${CMAKE_CURRENT_SOURCE_DIR}/compat add_library(provider SHARED compat/qr39/navicore_compat.c compat/qr39/host_callbacks.c + runtime/open_navi_audio_focus.c runtime/open_navi_api_telemetry.c runtime/open_navi_callback_backend.c runtime/open_navi_cluster_backend.c diff --git a/src/compat/qr39/navicore_compat.c b/src/compat/qr39/navicore_compat.c index b62a8b3..da4a80b 100644 --- a/src/compat/qr39/navicore_compat.c +++ b/src/compat/qr39/navicore_compat.c @@ -2,6 +2,7 @@ #include "open_navi.h" #include "open_navi_api_telemetry.h" +#include "open_navi_audio_focus.h" #include "open_navi_callback_backend.h" #include "open_navi_cluster_agent.h" #include "open_navi_backend_loader.h" @@ -140,6 +141,9 @@ static uint32_t open_navi_19_3(void *, uint32_t, uint32_t, static uint32_t open_navi_20_6(void *, uint32_t, uint32_t, const OpenNaviConnectionDeviceInfoInput *); static uint32_t open_navi_25_21(void *, uint32_t, uint32_t, const char *); +static uint32_t nc_provider_audio_allocation(void *, uint32_t, uint32_t, uint32_t); +static uint32_t nc_provider_audio_preparation(void *, uint32_t, uint32_t, uint32_t); +static uint32_t nc_provider_audio_deactivation(void *, uint32_t, uint32_t, uint32_t); static void open_navi_finish_deinitialize(void); static void open_navi_lifecycle_release(OpenNaviLifecycleLease *lease); @@ -237,6 +241,15 @@ OPEN_NAVI_PROVIDER_TYPECHECK(8, 8, open_navi_vehicle_speed, OpenNaviProviderSelf OPEN_NAVI_PROVIDER_TYPECHECK(8, 12, open_navi_8_12, OpenNaviProviderU32ConstChar); OPEN_NAVI_PROVIDER_TYPECHECK(9, 4, nc_provider_gps_data, OpenNaviProviderSelfConstVoid); OPEN_NAVI_PROVIDER_TYPECHECK(9, 6, open_navi_gps_interval, OpenNaviProviderSelfU32); +typedef char audio_allocation_typecheck[ + __builtin_types_compatible_p(__typeof__(&nc_provider_audio_allocation), + OpenNaviProviderSelfU32U32U32) ? 1 : -1]; +typedef char audio_preparation_typecheck[ + __builtin_types_compatible_p(__typeof__(&nc_provider_audio_preparation), + OpenNaviProviderSelfU32U32U32) ? 1 : -1]; +typedef char audio_deactivation_typecheck[ + __builtin_types_compatible_p(__typeof__(&nc_provider_audio_deactivation), + OpenNaviProviderSelfU32U32U32) ? 1 : -1]; OPEN_NAVI_PROVIDER_TYPECHECK(10, 17, open_navi_10_17, OpenNaviProviderSelfU32U32U8); OPEN_NAVI_PROVIDER_TYPECHECK(10, 19, open_navi_audio_volume, OpenNaviProviderSelfU32U8); OPEN_NAVI_PROVIDER_TYPECHECK(12, 5, open_navi_12_5, OpenNaviProviderSelfU32); @@ -362,10 +375,10 @@ static const PanaGenericVirtual g_audio_vtable[OPEN_NAVI_DUMMY_VTABLE_SLOTS] = { V2, V1, (PanaGenericVirtual)open_navi_static_10_3, V1, - (PanaGenericVirtual)open_navi_static_10_5, + (PanaGenericVirtual)nc_provider_audio_allocation, V1, - (PanaGenericVirtual)open_navi_static_10_7, - (PanaGenericVirtual)open_navi_static_10_8, + (PanaGenericVirtual)nc_provider_audio_preparation, + (PanaGenericVirtual)nc_provider_audio_deactivation, V8, (PanaGenericVirtual)open_navi_10_17, (PanaGenericVirtual)open_navi_static_10_18, @@ -1219,6 +1232,51 @@ static uint32_t open_navi_audio_volume(void *self, return 0u; \ } +static uint32_t nc_provider_audio_allocation(void *self, uint32_t handle, + uint32_t source, uint32_t value) +{ + OpenNaviLifecycleLease lease; + uint32_t result; + (void)self; + if (!open_navi_lifecycle_acquire(&lease)) return 1u; + open_navi_api_telemetry_record(10u, 5u, 3u, handle, source, value, 0u); + result = open_navi_audio_focus_event(5u, handle, source, value); + open_navi_log(LOG_NOTICE, "audio-focus inbound slot=5 handle=%u source=%u value=%u accepted=%u", + handle, source, value, result == 0u); + open_navi_lifecycle_release(&lease); + return result; +} + +static uint32_t nc_provider_audio_preparation(void *self, uint32_t handle, + uint32_t source, uint32_t value) +{ + OpenNaviLifecycleLease lease; + uint32_t result; + (void)self; + if (!open_navi_lifecycle_acquire(&lease)) return 1u; + open_navi_api_telemetry_record(10u, 7u, 3u, handle, source, value, 0u); + result = open_navi_audio_focus_event(7u, handle, source, value); + open_navi_log(LOG_NOTICE, "audio-focus inbound slot=7 handle=%u source=%u value=%u accepted=%u", + handle, source, value, result == 0u); + open_navi_lifecycle_release(&lease); + return result; +} + +static uint32_t nc_provider_audio_deactivation(void *self, uint32_t handle, + uint32_t source, uint32_t value) +{ + OpenNaviLifecycleLease lease; + uint32_t result; + (void)self; + if (!open_navi_lifecycle_acquire(&lease)) return 1u; + open_navi_api_telemetry_record(10u, 8u, 3u, handle, source, value, 0u); + result = open_navi_audio_focus_event(8u, handle, source, value); + open_navi_log(LOG_NOTICE, "audio-focus inbound slot=8 handle=%u source=%u value=%u accepted=%u", + handle, source, value, result == 0u); + open_navi_lifecycle_release(&lease); + return result; +} + static uint32_t open_navi_static_provider_accept(void *self, uint32_t slot, uint32_t word_count, @@ -2019,6 +2077,34 @@ static int open_navi_signal_after_adapter_ready(uint32_t adapter_id) } } +uint32_t open_navi_audio_focus_next_handle(void) +{ + return open_navi_callback_allocate_handle(); +} + +void open_navi_audio_focus_trace(const char *event, uint32_t handle, uint32_t value) +{ + open_navi_log(LOG_NOTICE, "audio-focus %s handle=%u value=%u", event, handle, value); +} + +uint32_t open_navi_audio_focus_dispatch(uint32_t slot, uint32_t handle, + uint32_t source, uint32_t value) +{ + OpenNaviLifecycleLease lease; + void *proxy; + uint32_t result = 1u; + if (!open_navi_lifecycle_acquire_proxy(10u, slot, &lease, &proxy)) return 1u; + if (slot == 6u) result = nc_host_audio_request_audio_source_allocation(proxy, handle, source); + else if (slot == 7u) result = nc_host_audio_request_audio_source_preparation(proxy, handle, source); + else if (slot == 8u) result = nc_host_audio_signal_deallocate_audio_source(proxy, source); + else if (slot == 9u) result = nc_host_audio_reply_audio_source_deactivation(proxy, handle, source, value); + open_navi_log(LOG_NOTICE, "audio-focus outbound slot=%u handle=%u source=%u value=%u status=%u", + slot, handle, source, value, result); + if (!open_navi_lifecycle_is_current(&lease)) result = 1u; + open_navi_lifecycle_release(&lease); + return result; +} + uint32_t open_navi_callback_signal_audio_availability(uint32_t state) { OpenNaviLifecycleLease lease; @@ -2887,6 +2973,10 @@ uint32_t panaInitialize(const void *init_record) open_navi_cluster_backend_reset(); open_navi_read_guidance_status_marker(); open_navi_cluster_relay_start(); +#ifdef __QNX__ + if (!open_navi_audio_focus_start(NULL)) + open_navi_log(LOG_ERR, "audio-focus socket start failed errno=%d", errno); +#endif /* The backend choice is process-lifetime and must be finalized while the * renderer is still COLD. Failure is deliberately non-fatal: bootstrap * leaves the built-in magenta backend selected. */ @@ -2968,6 +3058,7 @@ static void open_navi_finish_deinitialize(void) open_navi_api_telemetry_reset(); open_navi_pointer_backend_reset(); open_navi_callback_backend_reset(); + open_navi_audio_focus_stop(); open_navi_cluster_relay_stop(); open_navi_cluster_backend_reset(); open_navi_breadcrumb("deinitialize: finish end"); diff --git a/src/compat/qr39/provider_slots.def b/src/compat/qr39/provider_slots.def index 48f0b56..6084c70 100644 --- a/src/compat/qr39/provider_slots.def +++ b/src/compat/qr39/provider_slots.def @@ -21,9 +21,6 @@ OPEN_NAVI_STATIC_SLOT(8, 14, 1) OPEN_NAVI_STATIC_SLOT(9, 3, 2) OPEN_NAVI_STATIC_SLOT(9, 5, 1) OPEN_NAVI_STATIC_SLOT(10, 3, 3) -OPEN_NAVI_STATIC_SLOT(10, 5, 3) -OPEN_NAVI_STATIC_SLOT(10, 7, 3) -OPEN_NAVI_STATIC_SLOT(10, 8, 3) OPEN_NAVI_STATIC_SLOT(10, 18, 3) OPEN_NAVI_STATIC_SLOT(12, 3, 2) OPEN_NAVI_STATIC_SLOT(12, 4, 1) diff --git a/src/runtime/open_navi_audio_focus.c b/src/runtime/open_navi_audio_focus.c new file mode 100644 index 0000000..3cc1aac --- /dev/null +++ b/src/runtime/open_navi_audio_focus.c @@ -0,0 +1,194 @@ +#define _POSIX_C_SOURCE 200809L +#include "open_navi_audio_focus.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* PanaNav source 1 -> navigation source 21. Not as_audio_service's NAVI=8. */ +#define PANA_SOURCE 1u +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_t thread; +static int running, stopping, listener = -1; +static char socket_path[sizeof(((struct sockaddr_un *)0)->sun_path)]; +static uint32_t active_handle, deactivation_handle; +static int allocation = -1, preparation = -1; + +static long long now_ms(void) +{ + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + return (long long)t.tv_sec * 1000 + t.tv_nsec / 1000000; +} +static int stopped(void) +{ + int result; + pthread_mutex_lock(&lock); result = stopping; pthread_mutex_unlock(&lock); + return result; +} +static void nonblock(int fd) +{ + int flags = fcntl(fd, F_GETFL, 0); + if (flags >= 0) (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK); + (void)fcntl(fd, F_SETFD, FD_CLOEXEC); +} +uint32_t open_navi_audio_focus_event(uint32_t slot, uint32_t handle, + uint32_t source, uint32_t value) +{ + uint32_t result = 1u; + pthread_mutex_lock(&lock); + if (active_handle != 0u && source == PANA_SOURCE) { + if (slot == 5u && handle == active_handle) { + allocation = value == 1u ? 1 : 0; result = 0u; + } else if (slot == 7u && handle == active_handle) { + preparation = value == 1u ? 1 : 0; result = 0u; + } else if (slot == 8u && handle != 0u) { + deactivation_handle = handle; result = 0u; + } + } + pthread_mutex_unlock(&lock); + return result; +} +static int send_byte(int fd, char c) +{ + return send(fd, &c, 1, MSG_NOSIGNAL) == 1; +} +static void serve_prompt(int fd) +{ + struct pollfd p = {fd, POLLIN, 0}; + long long deadline = now_ms() + 1000; + char command = 0; + uint32_t handle, revoke; + int alloc, prep, preparing = 0, granted = 0, revoked = 0; + while (!stopped() && now_ms() < deadline) { + if (poll(&p, 1, 50) > 0) { + if (recv(fd, &command, 1, 0) != 1) return; + break; + } + } + if (command != 'A' || stopped()) return; + handle = open_navi_audio_focus_next_handle(); + if (handle == 0u) return; + pthread_mutex_lock(&lock); + active_handle = handle; deactivation_handle = 0u; + allocation = preparation = -1; + pthread_mutex_unlock(&lock); + open_navi_audio_focus_trace("request", handle, PANA_SOURCE); + if (open_navi_audio_focus_dispatch(6u, handle, PANA_SOURCE, 0u) != 0u) { + (void)send_byte(fd, 'D'); + goto done; + } + deadline = now_ms() + 8000; + while (!stopped()) { + pthread_mutex_lock(&lock); + alloc = allocation; prep = preparation; revoke = deactivation_handle; + pthread_mutex_unlock(&lock); + if (revoke != 0u && !revoked) { + revoked = 1; + open_navi_audio_focus_trace("revoke", handle, revoke); + if (!send_byte(fd, 'R')) break; + /* The worker closes PCM before disconnecting. Bound a dead client. */ + deadline = now_ms() + 2000; + } + if (!revoked && !granted) { + if (alloc == 0 || prep == 0) { + open_navi_audio_focus_trace("denied", handle, 0u); + (void)send_byte(fd, 'D'); break; + } + if (alloc == 1 && !preparing) { + preparing = 1; + if (open_navi_audio_focus_dispatch(7u, handle, PANA_SOURCE, 0u) != 0u) { + (void)send_byte(fd, 'D'); break; + } + } + if (alloc == 1 && prep == 1) { + if (!send_byte(fd, 'G')) break; + granted = 1; + deadline = now_ms() + 60000; + open_navi_audio_focus_trace("granted", handle, PANA_SOURCE); + } + } + if (now_ms() >= deadline) { + open_navi_audio_focus_trace("expired", handle, (uint32_t)granted); + (void)send_byte(fd, granted ? 'R' : 'D'); break; + } + p.revents = 0; + if (poll(&p, 1, 50) > 0) { + char c; + ssize_t n = recv(fd, &c, 1, 0); + if (n == 0 || n > 0 || (errno != EAGAIN && errno != EINTR)) break; + } + } +done: + pthread_mutex_lock(&lock); + revoke = deactivation_handle; + active_handle = deactivation_handle = 0u; + pthread_mutex_unlock(&lock); + if (revoke != 0u) + (void)open_navi_audio_focus_dispatch(9u, revoke, PANA_SOURCE, 1u); + else + (void)open_navi_audio_focus_dispatch(8u, handle, PANA_SOURCE, 0u); + open_navi_audio_focus_trace("released", handle, revoke); +} +static void *serve(void *unused) +{ + (void)unused; + while (!stopped()) { + struct pollfd p = {listener, POLLIN, 0}; + int fd; + if (poll(&p, 1, 50) <= 0) continue; + fd = accept(listener, NULL, NULL); + if (fd < 0) continue; + nonblock(fd); + serve_prompt(fd); + close(fd); + } + return NULL; +} +int open_navi_audio_focus_start(const char *path) +{ + struct sockaddr_un sa; + int fd; + if (path == NULL) path = OPEN_NAVI_AUDIO_SOCKET; + if (strlen(path) >= sizeof(sa.sun_path)) return 0; + pthread_mutex_lock(&lock); + if (running) { pthread_mutex_unlock(&lock); return 1; } + fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) { pthread_mutex_unlock(&lock); return 0; } + nonblock(fd); + memset(&sa, 0, sizeof(sa)); sa.sun_family = AF_UNIX; + strcpy(sa.sun_path, path); + (void)unlink(path); + if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) != 0 || listen(fd, 1) != 0) { + close(fd); pthread_mutex_unlock(&lock); return 0; + } + (void)chmod(path, 0666); + strcpy(socket_path, path); + listener = fd; stopping = 0; + if (pthread_create(&thread, NULL, serve, NULL) != 0) { + close(fd); unlink(path); listener = -1; + pthread_mutex_unlock(&lock); return 0; + } + running = 1; + pthread_mutex_unlock(&lock); + open_navi_audio_focus_trace("listening", 0u, 0u); + return 1; +} +void open_navi_audio_focus_stop(void) +{ + pthread_mutex_lock(&lock); + if (!running) { pthread_mutex_unlock(&lock); return; } + stopping = 1; + pthread_mutex_unlock(&lock); + pthread_join(thread, NULL); + close(listener); unlink(socket_path); + pthread_mutex_lock(&lock); + listener = -1; running = 0; + pthread_mutex_unlock(&lock); +} diff --git a/src/runtime/open_navi_audio_focus.h b/src/runtime/open_navi_audio_focus.h new file mode 100644 index 0000000..6c7aad1 --- /dev/null +++ b/src/runtime/open_navi_audio_focus.h @@ -0,0 +1,23 @@ +#ifndef OPEN_NAVI_AUDIO_FOCUS_H +#define OPEN_NAVI_AUDIO_FOCUS_H +#include +#ifdef __cplusplus +extern "C" { +#endif +/* One stream connection owns one prompt. Client sends A; server replies G only + * after stock allocation and preparation, D on failure, R on revocation. + * Closing the connection releases/acknowledges the stock source. */ +#define OPEN_NAVI_AUDIO_SOCKET "/tmp/navicore-audio.sock" +int open_navi_audio_focus_start(const char *path); +void open_navi_audio_focus_stop(void); +uint32_t open_navi_audio_focus_event(uint32_t slot, uint32_t handle, + uint32_t source, uint32_t value); +/* Provider-owned lifecycle-gated transport; never called under the state lock. */ +uint32_t open_navi_audio_focus_dispatch(uint32_t slot, uint32_t handle, + uint32_t source, uint32_t value); +uint32_t open_navi_audio_focus_next_handle(void); +void open_navi_audio_focus_trace(const char *event, uint32_t handle, uint32_t value); +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 325fbe9..1095f2b 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -46,7 +46,7 @@ find_package(Threads REQUIRED) set(src ${ONC_ROOT}/src) set(HOST_RENDERER_SOURCES ${src}/renderer/open_navi_renderer.c ${src}/renderer/open_navi_renderer_backend_table.c ${src}/renderer/open_navi_renderer_pointer.c ${src}/renderer/open_navi_renderer_dispatch.c ${src}/renderer/open_navi_renderer_lifecycle.c ${src}/renderer/open_navi_screen_input.c ${src}/backend/open_navi_default_backend.c ${src}/platform/host/open_navi_renderer_stub.c) -set(HOST_PROVIDER_SOURCES ${src}/compat/qr39/navicore_compat.c ${src}/runtime/open_navi_api_telemetry.c +set(HOST_PROVIDER_SOURCES ${src}/runtime/open_navi_audio_focus.c ${src}/compat/qr39/navicore_compat.c ${src}/runtime/open_navi_api_telemetry.c ${src}/runtime/open_navi_callback_backend.c ${src}/runtime/open_navi_cluster_backend.c ${src}/runtime/open_navi_cluster_agent.c ${src}/runtime/open_navi_cluster_relay.c ${ONC_CAGENT_SOURCES} ${src}/backend/open_navi_backend_loader.c ${src}/compat/qr39/host_callbacks.c @@ -102,6 +102,7 @@ onc_test(localization_test SOURCES localization_test.cpp LIBS navigation_ui m) onc_test(voice_prompts_test SOURCES voice_prompts_test.cpp LIBS navigation_ui m) onc_test(voice_worker_test SOURCES voice_worker_test.cpp LIBS navigation_ui m) onc_test(voice_link_test SOURCES voice_link_test.cpp LIBS navigation_ui m rt) +onc_test(stock_focus_test SOURCES stock_focus_test.cpp ${src}/runtime/open_navi_audio_focus.c LIBS voice_daemon navigation_ui m) onc_test(process_focus_test SOURCES process_focus_test.cpp LIBS voice_daemon navigation_ui m) onc_test(camera_controller_test SOURCES camera_controller_test.cpp LIBS navigation_ui) onc_test(dev_menu_test SOURCES dev_menu_test.cpp LIBS navigation_ui) diff --git a/tests/run_plugin_tests.sh b/tests/run_plugin_tests.sh index df771d3..4d28591 100644 --- a/tests/run_plugin_tests.sh +++ b/tests/run_plugin_tests.sh @@ -92,7 +92,7 @@ $cc $common_flags \ -DOPEN_NAVI_RENDERER_STUB \ -DOPEN_NAVI_BACKEND_PLUGIN_PATH='"'"$plugin_path"'"' \ -DEXPECT_TRACE_PATH='"'"$trace_path"'"' \ - src/compat/qr39/navicore_compat.c src/runtime/open_navi_api_telemetry.c src/runtime/open_navi_callback_backend.c \ + src/runtime/open_navi_audio_focus.c src/compat/qr39/navicore_compat.c src/runtime/open_navi_api_telemetry.c src/runtime/open_navi_callback_backend.c \ src/runtime/open_navi_cluster_backend.c src/runtime/open_navi_cluster_agent.c src/runtime/open_navi_cluster_relay.c \ src/backend/open_navi_backend_loader.c \ src/compat/qr39/host_callbacks.c src/runtime/open_navi_gps_backend.c \ diff --git a/tests/stock_focus_test.cpp b/tests/stock_focus_test.cpp new file mode 100644 index 0000000..c6c4566 --- /dev/null +++ b/tests/stock_focus_test.cpp @@ -0,0 +1,80 @@ +#include "stock_focus.h" +#include "open_navi_audio_focus.h" +#include +#include +#include +#include +#include +#include +#include +using namespace navicore_osmand; +static std::atomic next_id{100}, request_id{0}, prepare_id{0}, releases{0}, acks{0}; +static std::atomic auto_grant{false}, auto_prepare{false}; +extern "C" uint32_t open_navi_audio_focus_next_handle() { return ++next_id; } +extern "C" void open_navi_audio_focus_trace(const char*, uint32_t, uint32_t) {} +extern "C" uint32_t open_navi_audio_focus_dispatch(uint32_t slot, uint32_t handle, + uint32_t source, uint32_t value) { + assert(source == 1); + if (slot == 6) { + request_id = handle; + if (auto_grant) open_navi_audio_focus_event(5, handle, source, 1); + } else if (slot == 7) { + prepare_id = handle; + if (auto_prepare) open_navi_audio_focus_event(7, handle, source, 1); + } else if (slot == 8) { + ++releases; + } else if (slot == 9) { + assert(handle == 999 && value == 1); ++acks; + } else assert(false); + return 0; +} +template static void await(Predicate ready) { + for (int i = 0; i < 200 && !ready(); ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + assert(ready()); +} +int main() { + char temp[] = "/tmp/onc-focus-XXXXXX"; + assert(mkdtemp(temp)); + std::string path = std::string(temp) + "/focus.sock"; + StockFocus missing(path, 100); + assert(!missing.request()); + assert(open_navi_audio_focus_start(path.c_str())); + StockFocus focus(path, 1500); + std::atomic finished{false}, result{false}; + std::thread client([&] { result = focus.request(); finished = true; }); + await([] { return request_id.load() != 0; }); + unsigned h = request_id; + assert(open_navi_audio_focus_event(5, h + 1, 1, 1) == 1); + assert(open_navi_audio_focus_event(5, h, 8, 1) == 1); + assert(!finished); + assert(open_navi_audio_focus_event(5, h, 1, 1) == 0); + await([&] { return prepare_id == h; }); + assert(!finished); + assert(open_navi_audio_focus_event(7, h, 1, 1) == 0); + client.join(); assert(result && focus.valid()); + assert(open_navi_audio_focus_event(8, 999, 1, 1) == 0); + await([&] { return !focus.valid(); }); + assert(acks == 0); + focus.release(); + await([] { return acks == 1; }); + request_id = 0; finished = false; + std::thread denied([&] { result = focus.request(); finished = true; }); + await([] { return request_id.load() != 0; }); + assert(open_navi_audio_focus_event(5, request_id, 1, 0) == 0); + denied.join(); assert(!result); + await([] { return releases == 1; }); + request_id = 0; + StockFocus impatient(path, 100); + assert(!impatient.request()); + await([] { return releases == 2; }); + auto_grant = auto_prepare = true; + assert(focus.request() && focus.valid()); + focus.release(); + await([] { return releases == 3; }); + assert(focus.request()); + open_navi_audio_focus_stop(); + assert(!focus.valid()); focus.release(); + assert(releases == 4); + rmdir(temp); +}