diff --git a/backends/osmand/CMakeLists.txt b/backends/osmand/CMakeLists.txt index f8debcf..199ce1a 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 stock_focus.cpp) +add_library(voice_daemon STATIC process_focus.cpp stock_focus.cpp recorded_voice_engine.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}) @@ -42,23 +42,25 @@ else() return() endif() -# navi_voiced: the speech daemon (docs/design/voice-guidance-wiring.md). It needs +# navi_voiced always supports recorded packs. Optional RHVoice synthesis needs # RHVoice built for QNX by uk-voice/tts/build.sh; pass the build tree and headers: # -DRHVOICE_BUILD=/build/rhvoice-qnx -DRHVOICE_INCLUDE=/dl/RHVoice/src/include +add_executable(navi_voiced navi_voiced.cpp) if(RHVOICE_BUILD AND RHVOICE_INCLUDE) file(GLOB_RECURSE ONC_RHVOICE_OBJECTS CONFIGURE_DEPENDS ${RHVOICE_BUILD}/src/core/*.o ${RHVOICE_BUILD}/src/hts_engine/*.o ${RHVOICE_BUILD}/src/lib/*.o) set_source_files_properties(${ONC_RHVOICE_OBJECTS} PROPERTIES EXTERNAL_OBJECT TRUE GENERATED TRUE) - add_executable(navi_voiced navi_voiced.cpp rhvoice_engine.cpp ${ONC_RHVOICE_OBJECTS}) + target_sources(navi_voiced PRIVATE rhvoice_engine.cpp ${ONC_RHVOICE_OBJECTS}) + target_compile_definitions(navi_voiced PRIVATE ONC_WITH_RHVOICE) 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 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) - set_target_properties(navi_voiced PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} - SKIP_BUILD_RPATH ON) endif() +target_compile_options(navi_voiced PRIVATE ${ONC_WARNINGS} ${ONC_TARGET_FLAGS}) +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) +set_target_properties(navi_voiced PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + SKIP_BUILD_RPATH ON) # ---- QNX: the plugin ------------------------------------------------------ set(OSMAND_CORE_LIB_DIR ${OSMAND_QNX_ROOT}/source/binaries/qnx/gcc-armv7/Release) diff --git a/backends/osmand/navi_voiced.cpp b/backends/osmand/navi_voiced.cpp index f910c40..268eec7 100644 --- a/backends/osmand/navi_voiced.cpp +++ b/backends/osmand/navi_voiced.cpp @@ -3,8 +3,10 @@ // navi_voiced [--queue NAME] [--device PCM] [--rhvoice-data DIR] [--voice NAME] // [--rate PERCENT] [--focus stock|none|alloc] [--alloc-cmd PATH] // [--alloc-route CHANNEL SOURCE ZONE] [--selftest TEXT] +// [--engine recorded|rhvoice] [--recorded-data DIR] // -// Receives messages (voice_link.h), synthesizes with RHVoice, plays on io-audio +// Receives messages (voice_link.h), assembles recorded clips or synthesizes with +// explicitly selected RHVoice, plays on io-audio // 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. @@ -12,6 +14,7 @@ #include "stock_focus.h" #include "qnx_pcm_out.h" #include "rhvoice_engine.h" +#include "recorded_voice_engine.h" #include "voice_link.h" #include "voice_worker.h" @@ -38,6 +41,8 @@ struct Options { std::string device = "pcmC7D0p"; std::string rhvoice_data = "/tmp/tts/rhvoice"; std::string voice = "Natalia"; + std::string engine = "rhvoice"; + std::string recorded_data; int rate_percent = 100; std::string focus = "stock"; std::string alloc_cmd = "/tmp/tts/as_alloc"; @@ -57,6 +62,10 @@ bool parse(int argc, char** argv, Options& o) { else if (a == "--device") { if (!value(o.device)) return false; } else if (a == "--rhvoice-data") { if (!value(o.rhvoice_data)) return false; } else if (a == "--voice") { if (!value(o.voice)) return false; } + else if (a == "--engine") { + if (!value(o.engine) || (o.engine != "recorded" && o.engine != "rhvoice")) return false; + } + else if (a == "--recorded-data") { if (!value(o.recorded_data)) return false; } 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; @@ -83,11 +92,29 @@ int main(int argc, char** argv) { "usage: %s [--queue NAME] [--device PCM] [--rhvoice-data DIR] [--voice NAME]\n" " [--rate PERCENT] [--focus stock|none|alloc] [--alloc-cmd PATH]\n" " [--alloc-route CHANNEL SOURCE ZONE] [--selftest TEXT]\n", argv[0]); + std::fprintf(stderr, " [--engine recorded|rhvoice] [--recorded-data DIR] (recorded voices: male|female)\n"); return 64; } - RhVoiceEngine engine(opt.rhvoice_data, opt.voice); - engine.set_rate_percent(opt.rate_percent); + std::unique_ptr engine; + if (opt.engine == "recorded") { + if (opt.rate_percent != 100) { + std::fprintf(stderr, "voice: --rate is unavailable for recorded clips\n"); + return 64; + } + auto recorded = std::make_unique(opt.recorded_data, opt.voice); + if (opt.recorded_data.empty() || !recorded->initialize()) return 78; + engine = std::move(recorded); + } else { +#ifdef ONC_WITH_RHVOICE + auto rhvoice = std::make_unique(opt.rhvoice_data, opt.voice); + rhvoice->set_rate_percent(opt.rate_percent); + engine = std::move(rhvoice); +#else + std::fprintf(stderr, "voice: RHVoice support was not built; select --engine recorded\n"); + return 78; +#endif + } std::unique_ptr focus; if (opt.focus == "stock") { @@ -103,7 +130,7 @@ int main(int argc, char** argv) { focus.reset(new AlwaysFocus()); } QnxPcmOut out(opt.device, *focus); - VoiceWorker worker(engine, out); + VoiceWorker worker(*engine, out); worker.start(); if (!opt.selftest.empty()) { @@ -125,8 +152,8 @@ int main(int argc, char** argv) { sa.sa_handler = on_signal; // sets an atomic flag; run() notices within 200 ms 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.c_str(), opt.voice.c_str()); + std::printf("navi_voiced ready queue=%s device=%s focus=%s engine=%s voice=%s\n", opt.queue.c_str(), + opt.device.c_str(), opt.focus.c_str(), opt.engine.c_str(), opt.voice.c_str()); std::fflush(stdout); server.run(); g_server = nullptr; diff --git a/backends/osmand/recorded_voice_engine.cpp b/backends/osmand/recorded_voice_engine.cpp new file mode 100644 index 0000000..e8975ef --- /dev/null +++ b/backends/osmand/recorded_voice_engine.cpp @@ -0,0 +1,145 @@ +#include "recorded_voice_engine.h" + +#include +#include +#include +#include + +namespace navicore_osmand { +namespace { +constexpr unsigned kSampleRate = 24000; +constexpr std::size_t kGapSamples = 480; +constexpr std::size_t kMaxClipBytes = 480000; // ten seconds, mono PCM16 + +std::string key(std::string text) { + while (!text.empty() && (text.back() == '.' || text.back() == '\r' || text.back() == ' ')) + text.pop_back(); + return text; +} + +bool clip_id(const std::string& id) { + if (id.empty() || id.size() > 64) return false; + for (char c : id) + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')) return false; + return true; +} + +unsigned le16(const unsigned char* p) { return p[0] | (unsigned(p[1]) << 8); } +unsigned le32(const unsigned char* p) { + return le16(p) | (le16(p + 2) << 16); +} +bool tag(const unsigned char* p, const char* s) { + return p[0] == s[0] && p[1] == s[1] && p[2] == s[2] && p[3] == s[3]; +} +} // namespace + +bool RecordedVoiceEngine::initialize() { + if (attempted_) return ready_; + attempted_ = true; + if (voice_ != "male" && voice_ != "female") { + std::fprintf(stderr, "voice: recorded voice must be male or female, got %s\n", voice_.c_str()); + return false; + } + std::ifstream file(directory_ + "/recipes.tsv"); + std::string line; + if (!std::getline(file, line) || line != "NAVI-RECORDED-1\t24000\t480") { + std::fprintf(stderr, "voice: missing/invalid recorded manifest %s/recipes.tsv\n", directory_.c_str()); + return false; + } + std::map> parsed; + bool malformed = false; + while (std::getline(file, line)) { + const auto tab = line.find('\t'); + if (line.size() > 1024 || tab == std::string::npos || tab == 0 || parsed.size() >= 8192) { + malformed = true; break; + } + std::string text = key(line.substr(0, tab)); + std::istringstream fields(line.substr(tab + 1)); + std::vector ids; + std::string id; + bool valid = true; + while (std::getline(fields, id, ',')) { + if (!clip_id(id) || ids.size() >= 3) { valid = false; break; } + ids.push_back(id); + } + if (!valid || ids.empty() || line.back() == ',' || !parsed.emplace(text, ids).second) { + malformed = true; break; + } + } + if (malformed || !file.eof() || parsed.empty()) { + std::fprintf(stderr, "voice: malformed recorded manifest %s/recipes.tsv\n", directory_.c_str()); + return false; + } + recipes_ = std::move(parsed); + ready_ = true; + std::fprintf(stderr, "voice: recorded pack ready voice=%s recipes=%zu directory=%s\n", + voice_.c_str(), recipes_.size(), directory_.c_str()); + return true; +} + +bool RecordedVoiceEngine::read_clip(const std::string& id, std::vector& pcm) { + const std::string path = directory_ + "/" + voice_ + "/clips/" + id + ".wav"; + std::ifstream file(path, std::ios::binary | std::ios::ate); + const std::streamoff length = file ? static_cast(file.tellg()) : 0; + if (length < 44 || length > static_cast(kMaxClipBytes + 4096)) { + std::fprintf(stderr, "voice: missing/invalid recorded clip %s\n", path.c_str()); + return false; + } + std::vector bytes(static_cast(length)); + file.seekg(0); + if (!file.read(reinterpret_cast(bytes.data()), length)) return false; + bool format = false; + const unsigned char* data = nullptr; + std::size_t count = 0; + bool valid = tag(bytes.data(), "RIFF") && tag(bytes.data() + 8, "WAVE") && + le32(bytes.data() + 4) == bytes.size() - 8; + std::size_t offset = 12; + while (valid && offset + 8 <= bytes.size()) { + const auto* chunk = bytes.data() + offset; + const std::size_t size = le32(chunk + 4); + offset += 8; + if (size > bytes.size() - offset) { valid = false; break; } + if (tag(chunk, "fmt ")) { + format = size >= 16 && le16(bytes.data() + offset) == 1 && + le16(bytes.data() + offset + 2) == 1 && le32(bytes.data() + offset + 4) == kSampleRate && + le32(bytes.data() + offset + 8) == kSampleRate * 2 && + le16(bytes.data() + offset + 12) == 2 && le16(bytes.data() + offset + 14) == 16; + if (!format) valid = false; + } else if (tag(chunk, "data")) { + if (data || size == 0 || size % 2 || size > kMaxClipBytes) { valid = false; break; } + data = bytes.data() + offset; + count = size / 2; + } + offset += size + (size & 1); + } + if (!valid || !format || !data || offset != bytes.size()) { + std::fprintf(stderr, "voice: recorded clip must be 24000 Hz mono PCM16 WAV: %s\n", path.c_str()); + return false; + } + pcm.reserve(pcm.size() + count); + for (std::size_t i = 0; i < count; ++i) { + const unsigned value = le16(data + 2 * i); + pcm.push_back(static_cast(value < 32768 ? static_cast(value) : static_cast(value) - 65536)); + } + return true; +} + +bool RecordedVoiceEngine::synthesize(const std::string& text, ui::loc::Language language, + std::vector& pcm, unsigned& sample_rate_hz) { + pcm.clear(); + sample_rate_hz = 0; + if (language != ui::loc::Language::Ukrainian || !initialize()) return false; + auto recipe = recipes_.find(key(text)); + if (recipe == recipes_.end()) { + std::fprintf(stderr, "voice: recorded prompt unavailable: %s\n", text.c_str()); + return false; + } + for (const auto& id : recipe->second) { + if (!pcm.empty()) pcm.insert(pcm.end(), kGapSamples, 0); + if (!read_clip(id, pcm)) { pcm.clear(); return false; } + } + sample_rate_hz = kSampleRate; + return true; +} + +} // namespace navicore_osmand diff --git a/backends/osmand/recorded_voice_engine.h b/backends/osmand/recorded_voice_engine.h new file mode 100644 index 0000000..abff2da --- /dev/null +++ b/backends/osmand/recorded_voice_engine.h @@ -0,0 +1,28 @@ +#pragma once + +#include "voice_worker.h" + +#include +#include +#include + +namespace navicore_osmand { + +// Offline sentence lookup and PCM assembly. A missing recording fails visibly; +// selecting RHVoice instead is an explicit daemon option, never a fallback. +class RecordedVoiceEngine : public TtsEngine { +public: + RecordedVoiceEngine(std::string directory, std::string voice) + : directory_(std::move(directory)), voice_(std::move(voice)) {} + bool initialize(); + bool synthesize(const std::string& text, ui::loc::Language language, + std::vector& pcm, unsigned& sample_rate_hz) override; + +private: + bool read_clip(const std::string& id, std::vector& pcm); + std::string directory_, voice_; + std::map> recipes_; + bool attempted_ = false, ready_ = false; +}; + +} // namespace navicore_osmand diff --git a/backends/osmand/voice_prompts.cpp b/backends/osmand/voice_prompts.cpp index cb624dd..e6fbaf6 100644 --- a/backends/osmand/voice_prompts.cpp +++ b/backends/osmand/voice_prompts.cpp @@ -61,7 +61,7 @@ std::string action(ManeuverKind kind, int roundabout_exit, Language language) { case ManeuverKind::SharpRight: return "поверніть різко праворуч"; case ManeuverKind::KeepLeft: return "тримайтеся лівіше"; case ManeuverKind::KeepRight: return "тримайтеся правіше"; - case ManeuverKind::UTurn: return "розвернітеся"; + case ManeuverKind::UTurn: return "розверніться"; case ManeuverKind::Roundabout: { static const char* const ordinal[] = { "першому", "другому", "третьому", "четвертому", diff --git a/docs/design/voice-guidance-wiring.md b/docs/design/voice-guidance-wiring.md index 5992b96..ed7abb9 100644 --- a/docs/design/voice-guidance-wiring.md +++ b/docs/design/voice-guidance-wiring.md @@ -1,5 +1,37 @@ # Voice guidance: wiring Ukrainian TTS into Open NaviCore +## Recorded Ukrainian voices, 2026-10-28 + +`navi_voiced --engine recorded --recorded-data DIR --voice female` (or `male`) +uses the locally generated ElevenLabs pack. `RecordedVoiceEngine` implements the +existing `TtsEngine` interface: it maps the incoming sentence to one to three +PCM clips, inserts the audition's 20 ms gaps, and hands the complete sentence to +the existing voice worker, stock focus and io-audio path. No cloud access occurs +on the radio. RHVoice remains an explicit `--engine rhvoice` choice when built in. +Missing recipes, missing clips and invalid WAVs fail visibly; they never switch +to another voice. Recorded playback rejects a non-default `--rate`. + +The compact pack has 61 clips per voice and covers the current 2,206 Ukrainian +sentences. `tools/export_recorded_voice_pack.py SOURCE OUTPUT` validates the +audition pack and exports both voices plus `recipes.tsv`. Lookup aliases cover +digit-based planner output, the written-out audition sentences, and both old and +corrected U-turn spellings. The output header is +`NAVI-RECORDED-124000480`; each following line is +`sentenceclip-id[,clip-id[,clip-id]]`. Clips live at +`DIR/{male,female}/clips/.wav`: mono, 24 kHz, PCM16 RIFF/WAVE. + +The sibling `voice-uk-ifs` package includes these assets as slot data, outside +the small boot IFS. Its launcher defaults to recorded/female; flags +`voice-uk.d/engine` and `voice-uk.d/voice` select engine and profile on the next +daemon start. An existing RHVoice profile flag requires explicitly selecting +`rhvoice`, or changing that profile to `female`/`male`, during migration. + +`recorded_voice_test` checks assembly, voice selection, unsupported input and +malformed/missing files. Passing an exported pack directory as its argument +also exercises actual planner output and real WAVs for both voices. Intonation +differences at joins are known and await later recording refinement; structural +tests do not establish perceived quality or speaker audibility. + ## Implemented stock focus, 2026-10-28 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0bc396c..6b90754 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -105,6 +105,7 @@ 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(recorded_voice_test SOURCES recorded_voice_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) onc_test(reroute_state_test SOURCES reroute_state_test.cpp INCLUDES ${ONC_ROOT}/backends/osmand) diff --git a/tests/recorded_voice_test.cpp b/tests/recorded_voice_test.cpp new file mode 100644 index 0000000..9eec1b9 --- /dev/null +++ b/tests/recorded_voice_test.cpp @@ -0,0 +1,119 @@ +#include "recorded_voice_engine.h" + +#include +#include +#include +#include +#include +#include +#include + +using namespace navicore_osmand; +using ui::loc::Language; + +namespace { +void u16(std::ofstream& f, unsigned n) { f.put(static_cast(n)); f.put(static_cast(n >> 8)); } +void u32(std::ofstream& f, unsigned n) { u16(f, n); u16(f, n >> 16); } +void wav(const std::string& path, unsigned rate, short sample) { + std::ofstream f(path, std::ios::binary); + f.write("RIFF", 4); u32(f, 40); f.write("WAVEfmt ", 8); u32(f, 16); + u16(f, 1); u16(f, 1); u32(f, rate); u32(f, rate * 2); u16(f, 2); u16(f, 16); + f.write("data", 4); u32(f, 4); u16(f, static_cast(sample)); u16(f, 123); +} +void manifest(const std::string& root, const std::string& rows) { + std::ofstream(root + "/recipes.tsv") << "NAVI-RECORDED-1\t24000\t480\n" << rows; +} +void fixture() { + char directory[] = "/tmp/onc-recorded-XXXXXX"; + const char* made = mkdtemp(directory); assert(made); + std::string root(made); + for (const auto& voice : {"male", "female"}) { + assert(mkdir((root + "/" + voice).c_str(), 0700) == 0); + assert(mkdir((root + "/" + voice + "/clips").c_str(), 0700) == 0); + } + wav(root + "/male/clips/distance.wav", 24000, -1000); + wav(root + "/male/clips/action.wav", 24000, 2000); + wav(root + "/female/clips/distance.wav", 24000, -3000); + wav(root + "/female/clips/action.wav", 24000, 4000); + manifest(root, "Через 200 метрів поверніть праворуч\tdistance,action\nmissing\tdistance,missing\n"); + std::vector pcm; unsigned rate = 0; + RecordedVoiceEngine male(root, "male"), female(root, "female"); + assert(male.initialize() && female.initialize()); + assert(male.synthesize("Через 200 метрів поверніть праворуч.", Language::Ukrainian, pcm, rate)); + assert(rate == 24000 && pcm.size() == 484 && pcm[0] == -1000 && pcm[482] == 2000); + for (std::size_t i = 2; i < 482; ++i) assert(pcm[i] == 0); + assert(female.synthesize("Через 200 метрів поверніть праворуч", Language::Ukrainian, pcm, rate)); + assert(pcm[0] == -3000 && pcm[482] == 4000); + assert(!male.synthesize("unknown", Language::Ukrainian, pcm, rate) && pcm.empty() && rate == 0); + assert(!male.synthesize("missing", Language::Ukrainian, pcm, rate) && pcm.empty() && rate == 0); + assert(!male.synthesize("Через 200 метрів поверніть праворуч", Language::English, pcm, rate)); + assert(pcm.empty() && rate == 0); + wav(root + "/male/clips/action.wav", 22050, 2000); + assert(!male.synthesize("Через 200 метрів поверніть праворуч", Language::Ukrainian, pcm, rate)); + assert(pcm.empty() && rate == 0); + assert(!RecordedVoiceEngine(root, "../male").initialize()); + // A malformed final line without a newline must not expose a partial pack. + manifest(root, "valid\tdistance\ninvalid\t../escape"); + assert(!RecordedVoiceEngine(root, "male").initialize()); + manifest(root, "duplicate\tdistance\nduplicate\taction\n"); + assert(!RecordedVoiceEngine(root, "male").initialize()); + for (const auto& voice : {"male", "female"}) { + for (const auto& id : {"distance", "action"}) + std::remove((root + "/" + voice + "/clips/" + id + ".wav").c_str()); + rmdir((root + "/" + voice + "/clips").c_str()); rmdir((root + "/" + voice).c_str()); + } + std::remove((root + "/recipes.tsv").c_str()); rmdir(root.c_str()); +} + +// Optional real-pack integration: every planner action, distance, follow-up and +// status must resolve and read actual PCM for both voices. Not a synthetic map. +void actual_pack(const char* root) { + const ui::ManeuverKind kinds[] = {ui::ManeuverKind::Left, ui::ManeuverKind::SlightLeft, + ui::ManeuverKind::SharpLeft, ui::ManeuverKind::Right, ui::ManeuverKind::SlightRight, + ui::ManeuverKind::SharpRight, ui::ManeuverKind::KeepLeft, ui::ManeuverKind::KeepRight, + ui::ManeuverKind::UTurn, ui::ManeuverKind::Arrive, ui::ManeuverKind::Roundabout}; + std::vector actions; + for (auto kind : kinds) { + ui::Maneuver m; m.kind = kind; + if (kind == ui::ManeuverKind::Roundabout) { + for (int exit = 0; exit <= 8; ++exit) { m.roundabout_exit = exit; actions.push_back(m); } + } else actions.push_back(m); + } + for (const auto& voice : {"male", "female"}) { + RecordedVoiceEngine engine(root, voice); assert(engine.initialize()); + unsigned count = 0; + auto check = [&](const std::string& text) { + std::vector pcm; unsigned rate = 0; + if (!engine.synthesize(text, Language::Ukrainian, pcm, rate)) { + std::fprintf(stderr, "Missing real pack prompt: %s\n", text.c_str()); std::abort(); + } + assert(rate == 24000 && !pcm.empty()); ++count; + }; + for (const auto& action : actions) { + ui::GuidanceState s; s.maneuver = action; + for (int distance = 50; distance <= 1000; distance += 50) { + s.distance_to_maneuver_metres = distance == 950 ? 949 : distance; + check(PromptPlanner::maneuver_sentence(s, 0, Language::Ukrainian)); + } + check(PromptPlanner::maneuver_sentence(s, 3, Language::Ukrainian)); + s.has_following_maneuver = true; + for (const auto& following : actions) { + s.following_maneuver = following; + for (int distance = 50; distance <= 200; distance += 50) { + s.distance_to_maneuver_metres = distance; + check(PromptPlanner::maneuver_sentence(s, 2, Language::Ukrainian)); + } + check(PromptPlanner::maneuver_sentence(s, 3, Language::Ukrainian)); + } + } + check("Прокладаю новий маршрут"); check("Ви прибули до місця призначення"); + std::printf("real recorded pack voice=%s planner cases=%u OK\n", voice, count); + } +} +} // namespace + +int main(int argc, char** argv) { + fixture(); + if (argc == 2) actual_pack(argv[1]); + std::puts("recorded voice tests passed"); +} diff --git a/tools/export_recorded_voice_pack.py b/tools/export_recorded_voice_pack.py new file mode 100644 index 0000000..0d7561d --- /dev/null +++ b/tools/export_recorded_voice_pack.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Export an audition pack to navi_voiced's offline recorded-pack layout. + +Usage: python3 tools/export_recorded_voice_pack.py COMPACT_PACK OUTPUT_DIRECTORY +The source contains pack.json, recipes.json, and male/female/clips/*.wav. +No generation, network access, or audio re-encoding is performed. +""" +import argparse +import json +from pathlib import Path +import re +import shutil +import wave + + +def export(source, output): + pack = json.loads((source / 'pack.json').read_text()) + recipes = json.loads((source / 'recipes.json').read_text()) + ids = {row['id'] for row in pack['fragments']} + if len(ids) != len(pack['fragments']) or not ids: + raise ValueError('Empty or duplicate fragment IDs') + if any(not re.fullmatch(r'[a-z0-9-]{1,64}', ident) for ident in ids): + raise ValueError('Invalid fragment ID') + mapping = {} + for row in recipes: + clips = row['clips'] + if not 1 <= len(clips) <= 3 or not set(clips) <= ids: + raise ValueError('Invalid recipe clips') + # Include spoken words, existing digit-based prompts, and corrected U-turn wording. + for text in [row['text'], row['runtime_text'], row['runtime_text'].replace('розвернітеся', 'розверніться').replace('Розвернітеся', 'Розверніться')]: + text = text.rstrip('.\r ') + if not text or '\t' in text or '\n' in text: + raise ValueError('Invalid recipe text') + if text in mapping and mapping[text] != clips: + raise ValueError('Conflicting recipe') + mapping[text] = clips + if len(mapping) > 8192: + raise ValueError('Too many recipe aliases') + # Validate every clip before writing output, including the radio format and size bound. + for voice in ['male', 'female']: + for ident in sorted(ids): + path = source / voice / 'clips' / (ident + '.wav') + with wave.open(str(path), 'rb') as audio: + if ((audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) != (1, 2, 24000) + or not 0 < audio.getnframes() <= 240000): + raise ValueError('Invalid clip format: ' + str(path)) + for voice in ['male', 'female']: + dest = output / voice / 'clips' + dest.mkdir(parents=True, exist_ok=True) + for ident in sorted(ids): + shutil.copyfile(source / voice / 'clips' / (ident + '.wav'), dest / (ident + '.wav')) + manifest = ['NAVI-RECORDED-1\t24000\t480'] + manifest += [text + '\t' + ','.join(clips) for text, clips in sorted(mapping.items())] + (output / 'recipes.tsv').write_text('\n'.join(manifest) + '\n') + (output / 'pack.json').write_text(json.dumps(pack, ensure_ascii=False, indent=2) + '\n') + print(f'Exported {len(ids)} clips per voice, {len(recipes)} sentences, {len(mapping)} lookup aliases') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('source', type=Path) + parser.add_argument('output', type=Path) + args = parser.parse_args() + export(args.source, args.output)