Skip to content
Merged
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
36 changes: 34 additions & 2 deletions backends/osmand/ch/ch_query.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <functional>
#include <queue>
#include <string>
#include <utility>
Expand Down Expand Up @@ -106,18 +107,39 @@ class BasicQuery {
public:
explicit BasicQuery(Store store) : store_(std::move(store)) {}

// A start or end node and what reaching it costs already (snapping onto it).
struct Seed { u32 node, cost; };

// Cheapest cost from source to target, INF when unreachable. `meet` is
// the node where the two upward searches met.
u32 run(u32 source, u32 target, u32& meet)
{
const Seed s {source, 0}, t {target, 0};
return run(&s, 1, &t, 1, meet);
}

// Cheapest path from any source to any target, seeds' costs included: one
// search instead of one per pair. INF when unreachable or when `cancelled`
// (asked every 1024 settled nodes) says stop. source_of()/target_of()
// name the seeds the path starts and ends at.
u32 run(const Seed* sources, size_t source_count, const Seed* targets, size_t target_count,
u32& meet, const std::function<bool()>& cancelled = {})
{
settled = 0;
f_.reset(); b_.reset();
using Item = std::pair<u32, u32>;
std::priority_queue<Item, std::vector<Item>, std::greater<Item>> qf, qb;
f_.set(source, 0, source); qf.push({0, source});
b_.set(target, 0, target); qb.push({0, target});
const auto seed = [](Table& table, auto& queue, const Seed& s) {
const Entry* known = table.find(s.node);
if (known && known->dist <= s.cost) return;
table.set(s.node, s.cost, s.node);
queue.push({s.cost, s.node});
};
for (size_t i = 0; i < source_count; ++i) seed(f_, qf, sources[i]);
for (size_t i = 0; i < target_count; ++i) seed(b_, qb, targets[i]);
u32 best = INF; meet = INF;
while (!qf.empty() || !qb.empty()) {
if ((settled & 1023u) == 1023u && cancelled && cancelled()) { meet = INF; return INF; }
const u32 top = std::min(qf.empty() ? INF : qf.top().first, qb.empty() ? INF : qb.top().first);
if (top >= best) break;
const bool forward = !qf.empty() && (qb.empty() || qf.top().first <= qb.top().first);
Expand Down Expand Up @@ -173,6 +195,10 @@ class BasicQuery {
return true;
}

// The seed the last run()'s path starts at (seeds are their own parents).
u32 source_of(u32 meet) const { return root(f_, meet); }
u32 target_of(u32 meet) const { return root(b_, meet); }

size_t settled = 0; // nodes settled by the last run()

private:
Expand Down Expand Up @@ -222,6 +248,12 @@ class BasicQuery {
u32 used_ = 0;
};

static u32 root(const Table& table, u32 v)
{
for (const Entry* e = table.find(v); e && e->parent != v; e = table.find(v)) v = e->parent;
return v;
}

// The cheapest arc at -> to in the upward out (forward) or in arcs of `at`.
bool find(bool forward, u32 at, u32 to, QArc& result)
{
Expand Down
45 changes: 24 additions & 21 deletions backends/osmand/ch/ch_sidecar.h
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ inline const QArc* SidecarStore::arcs(bool forward, u32 node, u32& count, std::v
// sidecar's page cache and the query state are not shared).
class Router {
public:
enum class Status { Ok, NoRoute, Inconsistent };
enum class Status { Ok, NoRoute, Inconsistent, Cancelled };

explicit Router(Sidecar& sidecar) : sidecar_(sidecar), query_(sidecar.store()) {}

Expand All @@ -320,35 +320,37 @@ class Router {
// (120 ms per metre) against the route cost, so a far node does not win on route
// cost alone. With a start heading (degrees clockwise from north) a start node more
// than 120 degrees off it, i.e. behind the car, costs kReversePenaltyMs more, as
// OsmAnd's own routers charge for starting against the initial direction. On success
// runs are the road stretches in travel order (empty when both ends snap to the same
// node: too short to route here) and cost is the routing cost in milliseconds.
// OsmAnd's own routers charge for starting against the initial direction. All
// candidates seed one search with those costs (the best of every pair, in one run).
// On success runs are the road stretches in travel order (empty when both ends snap
// to the same node: too short to route here) and cost is the routing cost in
// milliseconds. `cancelled`, when set, is asked during the search.
Status route(int sx, int sy, int ex, int ey, std::vector<RoadRun>& runs, u32& cost,
double start_heading_degrees = kNoHeading)
double start_heading_degrees = kNoHeading,
const std::function<bool()>& cancelled = {})
{
runs.clear();
sidecar_.nearest_nodes(sx, sy, kSnapNodes, from_);
sidecar_.nearest_nodes(ex, ey, kSnapNodes, to_);
const auto too_far = [](const Sidecar::Candidate& c) { return c.metres > kMaxSnapMetres; };
from_.erase(std::remove_if(from_.begin(), from_.end(), too_far), from_.end());
to_.erase(std::remove_if(to_.begin(), to_.end(), too_far), to_.end());
double best = 1e18;
u32 best_from = 0, best_to = 0, best_cost = INF;
for (const auto& s : from_) {
for (const auto& t : to_) {
u32 meet = 0;
const u32 c = query_.run(s.node, t.node, meet);
if (c == INF) continue;
const double total = c + 120.0 * (s.metres + t.metres) +
reverse_penalty(sx, sy, s, start_heading_degrees);
if (total < best) { best = total; best_from = s.node; best_to = t.node; best_cost = c; }
}
}
if (best_cost == INF) return Status::NoRoute;
sources_.clear();
targets_.clear();
for (const auto& s : from_)
sources_.push_back({s.node, (u32)std::lround(120.0 * s.metres +
reverse_penalty(sx, sy, s, start_heading_degrees))});
for (const auto& t : to_) targets_.push_back({t.node, (u32)std::lround(120.0 * t.metres)});
u32 meet = 0;
query_.run(best_from, best_to, meet); // path_edges reads the last run
if (!query_.path_edges(best_from, best_to, meet, edges_)) return Status::Inconsistent;
cost = best_cost;
const u32 total = query_.run(sources_.data(), sources_.size(), targets_.data(), targets_.size(),
meet, cancelled);
if (total == INF) return cancelled && cancelled() ? Status::Cancelled : Status::NoRoute;
const u32 from = query_.source_of(meet), to = query_.target_of(meet);
u32 offsets = 0;
for (const auto& s : sources_) if (s.node == from) offsets += s.cost;
for (const auto& t : targets_) if (t.node == to) offsets += t.cost;
if (!query_.path_edges(from, to, meet, edges_)) return Status::Inconsistent;
cost = total - std::min(total, offsets);
return merge(runs) ? Status::Ok : Status::Inconsistent;
}

Expand Down Expand Up @@ -397,6 +399,7 @@ class Router {
Sidecar& sidecar_;
BasicQuery<SidecarStore> query_;
std::vector<Sidecar::Candidate> from_, to_;
std::vector<BasicQuery<SidecarStore>::Seed> sources_, targets_;
std::vector<u32> edges_;
};

Expand Down
5 changes: 4 additions & 1 deletion backends/osmand/ch_planner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,14 +93,17 @@ ChPlanner::Segments ChPlanner::route(RoutePlannerFrontEnd& front_end, const SHAR
auto step = Clock::now();
std::vector<onc_ch::RoadRun> runs;
onc_ch::u32 cost = 0;
const auto progress = context->progress;
const auto status = impl_->router->route(start_x, start_y, end_x, end_y, runs, cost,
start_heading_degrees);
start_heading_degrees,
[&progress] { return progress && progress->isCancelled(); });
timing_.search_ms = ms_since(step);
timing_.settled = impl_->router->settled();
timing_.base_edges = impl_->router->edges().size();
timing_.road_runs = runs.size();
if (status == onc_ch::Router::Status::NoRoute) { why = "no_route_in_sidecar"; return {}; }
if (status == onc_ch::Router::Status::Inconsistent) { why = "sidecar_inconsistent"; return {}; }
if (status == onc_ch::Router::Status::Cancelled) { why = "cancelled"; return {}; }
if (runs.empty()) { why = "too_short_for_sidecar"; return {}; }

// Each stretch needs its RouteDataObject: loading the tile at a point of the road
Expand Down
70 changes: 55 additions & 15 deletions backends/osmand/navigation_worker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -262,11 +262,15 @@ std::vector<ui::Lane> lanes_of(const SHARED_PTR<TurnType>& turn)
// Routing runs for seconds. nv_navigation is pinned to one core, where the
// render thread (priority 20) leaves it about half the CPU: a 15 km route
// took 7.3 s there against 3.7 s free to use either core (route_bench,
// 2026-10-15). Below the default priority 10 it only takes idle time from
// the other core's services.
constexpr int kWorkerPriority = 9;

void place_worker_thread()
// 2026-10-15). At the default priority 10 it shares the other core with its
// services in turn; at 9 it only got their idle time, and a busy Android
// Auto session stretched a route by seconds.
constexpr int kWorkerPriority = 10;
// Opening the routing maps (about 10 s for all of Ukraine, 2026-10-27) runs
// ahead of the first route on idle time only.
constexpr int kWarmupPriority = 9;

void place_worker_thread(int priority = kWorkerPriority, const char* name = "worker=placed")
{
const unsigned cpus = _syspage_ptr ? _syspage_ptr->num_cpu : 1u;
const unsigned mask = cpus >= 32u ? ~0u : (1u << cpus) - 1u;
Expand All @@ -276,12 +280,12 @@ void place_worker_thread()
sched_param parameters{};
bool lowered = false;
if (pthread_getschedparam(pthread_self(), &policy, &parameters) == 0) {
parameters.sched_priority = kWorkerPriority;
parameters.sched_priority = priority;
lowered = pthread_setschedparam(pthread_self(), policy, &parameters) == 0;
}
char line[80];
std::snprintf(line, sizeof(line), "worker=placed cpus=%u runmask=%d priority=%d",
cpus, any_cpu ? 1 : 0, lowered ? kWorkerPriority : -1);
std::snprintf(line, sizeof(line), "%s cpus=%u runmask=%d priority=%d",
name, cpus, any_cpu ? 1 : 0, lowered ? priority : -1);
trace(line);
}

Expand Down Expand Up @@ -399,6 +403,11 @@ class NavigationWorker::Impl {
// against later members such as has_pending_ and stopping_.
thread_ = std::thread(&Impl::run, this);
trace("worker=thread_started");
// The first route would otherwise wait for every map to open.
warmup_ = std::thread([this] {
place_worker_thread(kWarmupPriority, "worker=warmup_placed");
(void)prepare_router();
});
}

~Impl() { stop(); }
Expand Down Expand Up @@ -481,6 +490,8 @@ class NavigationWorker::Impl {
if (active_) active_->cancel();
condition_.notify_one();
}
stop_warmup_ = true;
if (warmup_.joinable()) warmup_.join();
if (thread_.joinable()) thread_.join();
if (router_ready_) {
for (const std::string& path : map_paths_)
Expand Down Expand Up @@ -626,10 +637,20 @@ class NavigationWorker::Impl {
return output;
}

// Once, by the warm-up thread or the first route, whichever comes first;
// the other waits for it.
bool prepare_router()
{
std::lock_guard<std::mutex> lock(router_mutex_);
if (router_ready_) return true;
if (routing_xml_.empty() || map_paths_.empty()) return false;
if (router_failed_ || routing_xml_.empty() || map_paths_.empty()) return false;
router_failed_ = !open_router();
return !router_failed_;
}

bool open_router()
{
const auto started = std::chrono::steady_clock::now();
const std::string path = write_routing_xml(routing_xml_);
// fileName namespaces imported configurations. A non-empty value
// would rename "car" and make build("car") return an empty router.
Expand All @@ -651,7 +672,15 @@ class NavigationWorker::Impl {
std::size_t routable = 0;
std::size_t with_hh = 0;
std::vector<std::string> routable_maps;
std::vector<std::string> opened;
for (const std::string& path : map_paths_) {
if (stop_warmup_) {
// Shutting down: close what is open, route never.
for (const std::string& done : opened) (void)closeBinaryMapFile(done);
trace("worker=router_stopped");
return false;
}
opened.push_back(path);
const auto map = initBinaryMapFile(path, false, true);
if (map && !map->routingIndexes.empty()) {
++routable;
Expand All @@ -671,9 +700,11 @@ class NavigationWorker::Impl {
// crosses into a file without it would have no network there.
has_hh_ = with_hh == routable;
{
char line[96];
std::snprintf(line, sizeof(line), "worker=router hh=%d routable=%zu hh_car=%zu",
has_hh_ ? 1 : 0, routable, with_hh);
char line[128];
std::snprintf(line, sizeof(line), "worker=router hh=%d routable=%zu hh_car=%zu open_ms=%lld",
has_hh_ ? 1 : 0, routable, with_hh,
static_cast<long long>(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - started).count()));
trace(line);
}
// Contraction-hierarchy routing: only with a sidecar built from exactly these maps.
Expand Down Expand Up @@ -775,6 +806,9 @@ class NavigationWorker::Impl {
if (request.heading_degrees)
trace_result("worker=route_heading", request.revision,
static_cast<std::size_t>(*request.heading_degrees));
// Both ends on one sidecar node: a route of a few metres, which A* finds
// at once and HH (seconds over the whole network) often does not.
bool skip_hh = false;
if (ch_) {
auto context = new_context();
std::string why;
Expand All @@ -791,19 +825,21 @@ class NavigationWorker::Impl {
found.push_back(std::move(segments));
} else if (!cancel->isAborted()) {
trace(("worker=ch_fallback why=" + (why.empty() ? std::string("route_rejected") : why)).c_str());
skip_hh = why == "too_short_for_sidecar";
}
}
if (found.empty() && !cancel->isAborted()) method = "hh";
if (found.empty() && has_hh_) {
if (found.empty() && has_hh_ && !skip_hh && !cancel->isAborted()) {
auto context = new_context();
found = route_hh(front_end, context, sx, sy, ex, ey,
request.alternatives && kAlternativeRoutes);
}
if (found.empty() && !cancel->isAborted()) {
// A* (no HH data, or HH found nothing usable).
method = "astar";
trace(has_hh_ ? "worker=route_fallback why=hh_unusable"
: "worker=route_fallback why=no_hh_data");
trace(skip_hh ? "worker=route_fallback why=too_short"
: has_hh_ ? "worker=route_fallback why=hh_unusable"
: "worker=route_fallback why=no_hh_data");
auto context = new_context();
std::vector<int> intermediates_x;
std::vector<int> intermediates_y;
Expand Down Expand Up @@ -1018,6 +1054,10 @@ class NavigationWorker::Impl {
std::mutex mutex_;
std::condition_variable condition_;
std::thread thread_;
std::thread warmup_; // opens the routing maps once
std::mutex router_mutex_; // prepare_router: warm-up or first route
std::atomic<bool> stop_warmup_{false};
bool router_failed_ = false; // under router_mutex_
Request pending_;
SearchResult result_;
RouteResult route_result_;
Expand Down
13 changes: 12 additions & 1 deletion backends/osmand/osmand_engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ class OsmAndEngine final : public Engine {
std::uint64_t submitted_route_revision_ = 0;
std::chrono::steady_clock::time_point search_revision_observed_at_{};
bool search_revision_observed_ = false;
std::chrono::steady_clock::time_point ready_at_{}; // rendering came up
GuidanceTracker guidance_tracker_;
// Spoken guidance: the planner decides what to say, the client hands it to navi_voiced.
PromptPlanner prompt_planner_;
Expand Down Expand Up @@ -526,6 +527,7 @@ bool OsmAndEngine::initialize(const Config& config,
// Rendering now has a valid teardown contract. Mark it before allocations
// below so an LVGL construction exception can still release OsmAnd.
phase_ = Phase::Ready;
ready_at_ = std::chrono::steady_clock::now();
trace("init=rendering");
if (!init_vector_map(wakeup))
return false;
Expand Down Expand Up @@ -1546,16 +1548,25 @@ bool OsmAndEngine::sync_navigation_to_screen()
return changed;
}

// The worker opens the routing maps in the background (about 10 s for all of
// Ukraine), so it starts before the first route is asked for: when a place
// card or another screen opens, or a while after start-up, out of its way.
constexpr std::chrono::seconds kWorkerWarmupDelay{30};

void OsmAndEngine::submit_navigation_requests()
{
if (!navigation_worker_ && !worker_creation_failed_ &&
(navigation_->screen() != ui::Screen::FreeDrive || navigation_->place_card() ||
std::chrono::steady_clock::now() - ready_at_ >= kWorkerWarmupDelay))
(void)ensure_navigation_worker();
if (navigation_->screen() == ui::Screen::Search) {
const auto revision = navigation_->search_revision();
const auto now = std::chrono::steady_clock::now();
if (!search_revision_observed_ || revision != observed_search_revision_) {
observed_search_revision_ = revision;
search_revision_observed_at_ = now;
search_revision_observed_ = true;
} else if (revision != submitted_search_revision_ &&
} else if (revision != submitted_search_revision_ && navigation_->search_wanted() &&
now - search_revision_observed_at_ >= search_debounce()) {
submitted_search_revision_ = revision;
if (!navigation_->query().empty()) {
Expand Down
7 changes: 7 additions & 0 deletions backends/osmand/ui/navigation_model.h
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,13 @@ class NavigationModel {
{
return has_destination_ && routes_.empty() && message_ == calculating_message;
}
// The query still needs a search. Not once a destination is picked from
// it: a recent sets the query to its title, and a late search for that
// would cancel the destination's route on the one worker.
bool search_wanted() const noexcept
{
return screen_ == Screen::Search && !query_.empty() && !has_destination_;
}
// Route preview Back: returns to where the route was picked (the search
// results, or free drive with the place card).
bool back_to_search() noexcept;
Expand Down
Loading