martin-core 0.18.0

Basic building blocks of MapLibre's Martin tile server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! One `MapLibre` map drawing still images into its own texture, driven from a single thread.

use std::collections::HashMap;
use std::future::Future;
use std::ops::Deref;
use std::path::Path;
use std::pin::Pin;
use std::sync::{Arc, Condvar, Mutex, Once, PoisonError};
use std::task::{Context, Poll, Wake, Waker};
use std::time::{Duration, Instant};

use image::RgbaImage;
use maplibre_native_ffi::{
    CameraOptions, CameraUpdate, CameraUpdateMode, CommandCompletion, LogHandler, LogSeverity, LogicalExtent,
    LogicalSize, MapHandle, MapMode, MapOptions, NativeFuture, OffscreenDescriptor, OffscreenDeviceHandle,
    OffscreenDeviceOptions, RenderDriverKind, RenderSessionAttachOptions, RenderSessionHandle, RuntimeEvent,
    RuntimeEventFlag, RuntimeEventHandler, RuntimeEventType, RuntimeHandle, RuntimeOptions, TextureReadbackResult,
    set_log_callback,
};

use tracing::{error, info, warn};

use crate::resources::styles::StyleError;

/// How long a call into `MapLibre` may take before its renderer is given up on.
const NATIVE_TIMEOUT: Duration = Duration::from_secs(60);

/// A `MapLibre` runtime shared by every renderer of a pool, with one ambient cache.
pub struct Runtime {
    /// The native runtime.
    handle: Releasable<RuntimeHandle>,
    /// Style-load listeners, by the id of the map they listen to.
    listeners: Arc<Mutex<HashMap<u64, Arc<StyleListener>>>>,
}

impl std::fmt::Debug for Runtime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Runtime").finish_non_exhaustive()
    }
}

impl Drop for Runtime {
    /// Releases the runtime and waits until its native threads have stopped.
    fn drop(&mut self) {
        let signal = Arc::new(Signal::default());
        let Some(handle) = self.handle.take() else { return };
        let released = handle
            .release()
            .map(|released| block_on(&signal, released, "runtime release"))
            .map_err(|err| StyleError::from(err.error));
        if let Err(err) | Ok(Err(err)) = released {
            warn!(error = %err, "Failed to release the MapLibre runtime");
        }
    }
}

impl Runtime {
    /// Creates a runtime whose ambient cache holds up to `ambient_cache_bytes`
    /// (`None` keeps `MapLibre`'s default, `Some(0)` disables it).
    ///
    /// # Errors
    ///
    /// Returns [`StyleError::RenderingError`] when `MapLibre` cannot start.
    pub fn new(ambient_cache_bytes: Option<u64>) -> Result<Self, StyleError> {
        forward_logs();
        let handle = RuntimeHandle::create(Some(&RuntimeOptions::default()))?;
        let listeners: Arc<Mutex<HashMap<u64, Arc<StyleListener>>>> = Arc::default();
        let routes = Arc::downgrade(&listeners);
        let signal = Arc::new(Signal::default());
        let handler = RuntimeEventHandler::new(move |batch| {
            let Some(routes) = routes.upgrade() else { return };
            let routes = routes.lock().unwrap_or_else(PoisonError::into_inner);
            for event in batch {
                if let Some(listener) = routes.get(&event.source) {
                    listener.observe(&event);
                }
            }
        });
        block_on(&signal, handle.set_event_handler(handler)?, "event handler setup")?;
        if let Some(bytes) = ambient_cache_bytes {
            block_on(
                &signal,
                handle.set_maximum_ambient_cache_size(bytes)?,
                "ambient cache setup",
            )?;
        }
        Ok(Self {
            handle: Releasable(Some(handle)),
            listeners,
        })
    }
}

/// One worker's graphics device, created with `single_context` when the worker is built.
///
/// `single_context` requires that the device's sessions never render at the same time, which holds because a
/// worker renders one image at a time.
#[derive(Debug)]
pub struct WorkerDevice {
    runtime: Arc<Runtime>,
    device: OffscreenDeviceHandle,
}

impl WorkerDevice {
    /// Creates the device for a new worker of a pool of `runtime`.
    ///
    /// # Errors
    ///
    /// Returns [`StyleError::GraphicsUnavailable`] when no graphics device can be created.
    pub fn new(runtime: Arc<Runtime>) -> Result<Self, StyleError> {
        let options = OffscreenDeviceOptions {
            single_context: Some(true),
            ..OffscreenDeviceOptions::default()
        };
        let device = OffscreenDeviceHandle::create(Some(&options)).map_err(|err| StyleError::GraphicsUnavailable {
            reason: err.to_string(),
        })?;
        Ok(Self { runtime, device })
    }

    /// Creates a renderer on this worker's device. See [`Renderer::new`].
    pub fn renderer(&self, mode: MapMode, width: u32, height: u32, pixel_ratio: f64) -> Result<Renderer, StyleError> {
        Renderer::new(&self.runtime, &self.device, mode, width, height, pixel_ratio)
    }
}

/// Forwards `MapLibre`'s log records to `tracing` under the target `maplibre_native`, once per process.
fn forward_logs() {
    static FORWARDED: Once = Once::new();
    FORWARDED.call_once(|| {
        let handler = LogHandler::new(|severity, event, code, message| match severity {
            LogSeverity::Info => {
                info!(target: "maplibre_native", { maplibre.event = ?event, maplibre.code = code }, "{message}");
            }
            LogSeverity::Warning => {
                warn!(target: "maplibre_native", { maplibre.event = ?event, maplibre.code = code }, "{message}");
            }
            LogSeverity::Error | LogSeverity::Unknown(_) => {
                error!(target: "maplibre_native", { maplibre.event = ?event, maplibre.code = code }, "{message}");
            }
        });
        if let Err(err) = set_log_callback(handler) {
            warn!(error = %err, "Failed to forward MapLibre's log records to tracing");
        }
    });
}

/// What a map reported about loading a style.
#[derive(Debug, Clone)]
enum StyleOutcome {
    /// The style loaded.
    Loaded,
    /// The style failed to load, with `MapLibre`'s reason.
    Failed(String),
}

/// Collects the style-load outcomes one map reports while a style load is pending.
///
/// Outcomes are kept with their generation, because only once the style command has
/// committed is it known which generation the new style starts at.
#[derive(Debug, Default)]
struct StyleListener {
    /// Outcomes reported since the pending load began, with their generations,
    /// or `None` while no load is pending.
    outcomes: Mutex<Option<Vec<(u64, StyleOutcome)>>>,
    /// Raised whenever an outcome is recorded.
    signal: Arc<Signal>,
}

impl StyleListener {
    /// Records `event` if it is a style-load outcome and a load is pending.
    fn observe(&self, event: &RuntimeEvent) {
        let outcome = if matches!(event.r#type, RuntimeEventType::MapStyleLoaded) {
            StyleOutcome::Loaded
        } else if matches!(event.r#type, RuntimeEventType::MapLoadingFailed) {
            StyleOutcome::Failed(event.message.clone())
        } else {
            return;
        };
        if let Some(outcomes) = self.outcomes.lock().unwrap_or_else(PoisonError::into_inner).as_mut() {
            outcomes.push((event.generation, outcome));
            self.signal.raise();
        }
    }

    /// Starts collecting outcomes for a new load, dropping any earlier ones.
    fn begin(&self) {
        *self.outcomes.lock().unwrap_or_else(PoisonError::into_inner) = Some(Vec::new());
    }

    /// Waits for the first outcome at or after `generation`, and stops collecting, giving up at `until`.
    fn wait(&self, generation: u64, until: Instant) -> Option<StyleOutcome> {
        loop {
            let seen = self.signal.seen();
            let mut outcomes = self.outcomes.lock().unwrap_or_else(PoisonError::into_inner);
            let found = outcomes
                .iter()
                .flatten()
                .find(|(reported, _)| *reported >= generation)
                .map(|(_, outcome)| outcome.clone());
            if found.is_some() || Instant::now() >= until {
                *outcomes = None;
                return found;
            }
            drop(outcomes);
            self.signal.wait_past(seen, until);
        }
    }
}

/// A map in tile or static mode with a session-owned texture it reads its still images back from.
///
/// Every call blocks the calling thread until `MapLibre` answers.
#[derive(Debug)]
pub struct Renderer {
    /// The pool's runtime, kept alive for as long as the map.
    runtime: Arc<Runtime>,
    /// The map the camera, style and overlays apply to.
    map: Releasable<MapHandle>,
    /// The render target the map draws into.
    session: Releasable<RenderSessionHandle>,
    /// Style-load outcomes of `map`.
    style: Arc<StyleListener>,
    /// Raised by every native completion this renderer waits on.
    signal: Arc<Signal>,
}

impl Renderer {
    /// Creates a map of `mode` drawing `width` x `height` logical pixels at `pixel_ratio` into a texture on `device`.
    pub fn new(
        runtime: &Arc<Runtime>,
        device: &OffscreenDeviceHandle,
        mode: MapMode,
        width: u32,
        height: u32,
        pixel_ratio: f64,
    ) -> Result<Self, StyleError> {
        let signal = Arc::new(Signal::default());
        let extent = LogicalExtent::new(width, height, pixel_ratio);
        let options = MapOptions {
            map_mode: mode,
            event_mask: Some(RuntimeEventFlag::MAP_STYLE_LOADED | RuntimeEventFlag::MAP_LOADING_FAILED),
            ..MapOptions::new(extent)
        };
        let (map, created) = runtime.handle.create_map(&options)?;
        block_on(&signal, created, "map creation")?;

        let attach = RenderSessionAttachOptions::new(RenderDriverKind::CoreWorker);
        let descriptor = OffscreenDescriptor::new(LogicalSize::new(width, height));
        let (session, attached) = map.attach_offscreen(&descriptor, &attach, Some(device))?;
        let style = Arc::new(StyleListener::default());
        runtime
            .listeners
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(map.id(), Arc::clone(&style));
        let renderer = Self {
            runtime: Arc::clone(runtime),
            map: Releasable(Some(map)),
            session: Releasable(Some(session)),
            style,
            signal,
        };
        block_on(&renderer.signal, attached, "render target attachment")?;
        Ok(renderer)
    }

    /// Loads the style at `path` and waits until `MapLibre` has loaded or rejected it.
    pub fn load_style(&mut self, path: &Path) -> Result<(), StyleError> {
        if !path.is_file() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("Path {} is not a file", path.display()),
            )
            .into());
        }
        let Some(path) = path.to_str() else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Path {} is not valid UTF-8", path.display()),
            )
            .into());
        };
        let url = format!("file://{path}");
        self.set_style(|map| map.set_style_url(&url))
    }

    /// Loads the style document `json` and waits until `MapLibre` has loaded or rejected it.
    pub fn load_style_json(&mut self, json: &str) -> Result<(), StyleError> {
        self.set_style(|map| map.set_style_json(json))
    }

    /// Sends the style command `set` and waits until `MapLibre` has loaded or rejected its style.
    fn set_style(
        &self,
        set: impl FnOnce(&MapHandle) -> maplibre_native_ffi::Result<NativeFuture<CommandCompletion>>,
    ) -> Result<(), StyleError> {
        let until = Instant::now() + NATIVE_TIMEOUT;
        self.style.begin();
        // A failed style command loads nothing, so no outcome would ever arrive.
        let set = match block_on(&self.signal, set(&self.map)?, "style command") {
            Ok(set) => set,
            Err(StyleError::RenderingError(err)) => {
                return Err(StyleError::StyleLoadError {
                    message: err.to_string(),
                });
            }
            Err(err) => return Err(err),
        };
        match self.style.wait(set.generation, until) {
            Some(StyleOutcome::Loaded) => Ok(()),
            Some(StyleOutcome::Failed(message)) => Err(StyleError::StyleLoadError { message }),
            None => Err(StyleError::Timeout {
                call: "style load",
                timeout: NATIVE_TIMEOUT,
            }),
        }
    }

    /// Resizes the drawing to `width` x `height` logical pixels, keeping the map and its style.
    pub fn resize(&mut self, width: u32, height: u32) -> Result<(), StyleError> {
        block_on(
            &self.signal,
            self.session.resize(LogicalSize::new(width, height))?,
            "resize",
        )?;
        Ok(())
    }

    /// The map, for adding and removing overlay sources and layers.
    pub fn map(&self) -> &MapHandle {
        &self.map
    }

    /// Waits for the outcome of a style command, failing if `MapLibre` rejected it or did not answer in time.
    pub fn command(
        &self,
        command: maplibre_native_ffi::Result<NativeFuture<CommandCompletion>>,
    ) -> Result<(), StyleError> {
        block_on(&self.signal, command?, "style command")?;
        Ok(())
    }

    /// Moves the camera to `camera` and renders the still image `MapLibre` produces once everything it shows has loaded.
    pub fn render(&mut self, camera: CameraOptions) -> Result<RgbaImage, StyleError> {
        self.map.discarding().update_camera(&CameraUpdate {
            mode: CameraUpdateMode::Jump,
            camera,
            ..CameraUpdate::default()
        })?;
        block_on(&self.signal, self.map.request_still_image()?, "still image")?;
        // Frame results queue up on the session until drained, and the still image needs none of them.
        self.session.drain_frame_results()?;
        let readback = block_on(&self.signal, self.session.read_texture()?, "texture readback")?;
        Ok(unpremultiply(readback))
    }
}

impl Drop for Renderer {
    /// Detaches and releases the session, then the map, waiting for each, so no native
    /// worker still draws when the runtime or the process goes away.
    fn drop(&mut self) {
        let detached = self
            .session
            .detach()
            .map(|detached| block_on(&self.signal, detached, "render session detach"))
            .map_err(StyleError::from);
        if let Err(err) | Ok(Err(err)) = detached {
            warn!(error = %err, "Failed to detach a render session");
        }
        if let Some(session) = self.session.take() {
            let released = session
                .release()
                .map(|(released, _)| block_on(&self.signal, released, "render session release"))
                .map_err(|err| StyleError::from(err.error));
            if let Err(err) | Ok(Err(err)) = released {
                warn!(error = %err, "Failed to release a render session");
            }
        }
        let Some(map) = self.map.take() else { return };
        let id = map.id();
        let released = map
            .release()
            .map(|released| block_on(&self.signal, released, "map release"))
            .map_err(|err| StyleError::from(err.error));
        if let Err(err) | Ok(Err(err)) = released {
            warn!(error = %err, "Failed to release a map");
        }
        self.runtime
            .listeners
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&id);
    }
}

/// A native handle that `Drop` moves out to release it and wait for its teardown.
#[derive(Debug)]
struct Releasable<T>(Option<T>);

impl<T> Releasable<T> {
    /// Moves the handle out, leaving nothing to release twice.
    fn take(&mut self) -> Option<T> {
        self.0.take()
    }
}

impl<T> Deref for Releasable<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.0
            .as_ref()
            .expect("a handle is only moved out while its owner drops")
    }
}

/// Converts `MapLibre`'s premultiplied readback to straight alpha, rounding as `MapLibre`'s own
/// `unpremultiply` does, and drops any row padding.
fn unpremultiply(readback: TextureReadbackResult) -> RgbaImage {
    let TextureReadbackResult { mut data, info } = readback;
    let row = info.width as usize * 4;
    let stride = info.stride as usize;
    if stride != row {
        for y in 1..info.height as usize {
            data.copy_within(y * stride..y * stride + row, y * row);
        }
    }
    data.truncate(row * info.height as usize);
    for pixel in data.as_chunks_mut::<4>().0 {
        let alpha = u16::from(pixel[3]);
        if alpha != 0 && alpha != 255 {
            for channel in &mut pixel[..3] {
                // At most 255, since a premultiplied channel never exceeds its alpha.
                *channel = u8::try_from((255 * u16::from(*channel) + alpha / 2) / alpha).unwrap_or(u8::MAX);
            }
        }
    }
    RgbaImage::from_raw(info.width, info.height, data).expect("readback holds width x height RGBA pixels")
}

/// A counter that threads wait on to move past, raised by native callbacks and future wakers.
#[derive(Debug, Default)]
struct Signal {
    /// How often the signal was raised.
    raised: Mutex<u64>,
    /// Notified on every raise.
    changed: Condvar,
}

impl Signal {
    /// Records one more raise and wakes the waiting thread.
    fn raise(&self) {
        *self.raised.lock().unwrap_or_else(PoisonError::into_inner) += 1;
        self.changed.notify_all();
    }

    /// The raise count, to pass to [`Signal::wait_past`] after checking what the raise announces.
    fn seen(&self) -> u64 {
        *self.raised.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Blocks until the signal was raised after `seen`, or until `until`.
    fn wait_past(&self, seen: u64, until: Instant) {
        let raised = self.raised.lock().unwrap_or_else(PoisonError::into_inner);
        let timeout = until.saturating_duration_since(Instant::now());
        drop(
            self.changed
                .wait_timeout_while(raised, timeout, |raised| *raised == seen)
                .unwrap_or_else(PoisonError::into_inner),
        );
    }
}

impl Wake for Signal {
    fn wake(self: Arc<Self>) {
        self.raise();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        self.raise();
    }
}

/// Blocks the calling thread until `future` resolves, sleeping on `signal` between polls, or fails `call` once [`NATIVE_TIMEOUT`] has passed.
fn block_on<T, E>(
    signal: &Arc<Signal>,
    mut future: impl Future<Output = Result<T, E>> + Unpin,
    call: &'static str,
) -> Result<T, StyleError>
where
    StyleError: From<E>,
{
    let until = Instant::now() + NATIVE_TIMEOUT;
    let waker = Waker::from(Arc::clone(signal));
    let mut context = Context::from_waker(&waker);
    loop {
        let seen = signal.seen();
        if let Poll::Ready(output) = Pin::new(&mut future).poll(&mut context) {
            return Ok(output?);
        }
        if Instant::now() >= until {
            return Err(StyleError::Timeout {
                call,
                timeout: NATIVE_TIMEOUT,
            });
        }
        signal.wait_past(seen, until);
    }
}