Skip to main content

mln_runtime/render/
session.rs

1//! The handle of a render session, and the state that its thread shares
2//! with the handle.
3
4use std::any::Any;
5use std::cell::RefCell;
6use std::collections::BTreeMap;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::{Arc, OnceLock};
9use std::thread::ThreadId;
10
11use mln_map::LogicalExtent;
12use mln_renderer::query::{RenderedQueryOptions, SourceQueryOptions};
13use mln_util::error::Error;
14use mln_util::feature::Feature;
15use mln_util::image::PremultipliedImage;
16use mln_util::logging::{Event, Log};
17use mln_util::size::Size;
18use mln_util::thread::Joined;
19use parking_lot::Mutex;
20
21use super::driver::DriverWork;
22use super::frame::{FrameDemand, FrameResult};
23use super::local::Pending;
24use super::query::RenderedQueryGeometry;
25use super::target::{
26    AttachOptions, BorrowedRing, ConsumerSync, Device, DeviceLease, Driver, ExportKind, FrameTexture, GpuSync,
27    RenderTarget, SentSurface, Surface, SyncKind, SyncKinds, Wake,
28};
29use super::worker::{self, Init, SessionQueue, TargetInit, Worker};
30use crate::completion::{Completion, Home, Resolver};
31use crate::map::{Applied, Map};
32use crate::runtime::Outbox;
33
34/// The ID of a render session, unique in the process.
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
36pub(crate) struct SessionId(u64);
37
38/// Where a render session is in its life.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub enum RenderSessionState {
41    /// The session is starting: it builds its renderer and binds to its map.
42    Attaching,
43    Attached,
44    /// A detach or release is on its way.
45    Detaching,
46    /// The session let go of its map and its graphics objects.
47    Detached,
48    /// The session couldn't build its renderer. Its snapshot says why.
49    Failed,
50    Abandoned,
51}
52
53/// The state of a render session at one moment.
54#[derive(Clone, Debug, PartialEq)]
55pub struct RenderSessionSnapshot {
56    pub state: RenderSessionState,
57    /// The target's logical size, and the map's pixel ratio.
58    pub extent: LogicalExtent,
59    /// Grows each time the target changes size or is replaced.
60    pub generation: u64,
61    /// Counts the frames that the session rendered.
62    pub frame_generation: u64,
63    /// Why the session failed.
64    pub failure: Option<Error>,
65    /// Whether the session is attached and has a target to render to. It is
66    /// false from a [`release_target`](RenderSession::release_target) until
67    /// a [`set_surface`](RenderSession::set_surface) gives it a new one.
68    pub has_target: bool,
69    /// How many of a borrowed ring's frames the host holds.
70    pub acquired_frames: u32,
71}
72
73/// What a render session can do.
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
75pub struct RenderSessionCapabilities {
76    pub driver: Driver,
77    /// How many textures the session's texture ring has.
78    pub texture_ring_depth: u32,
79    /// Whether the host can take the frames it renders.
80    pub frame_acquisition: bool,
81    /// Whether [`RenderSession::read_texture`] can read its pixels.
82    pub readback: bool,
83    /// Whether it shows frames on a surface.
84    pub presentation: bool,
85    /// The kind of sync that a borrowed ring's frames carry.
86    pub producer_sync_kind: Option<SyncKind>,
87    /// The kinds of sync that [`AcquiredFrame::release`] takes.
88    pub consumer_sync_kinds: SyncKinds,
89    /// How an exported ring shares its images, for an exported ring.
90    pub export_kind: Option<ExportKind>,
91}
92
93/// A frame of a borrowed ring that the session published, and what the
94/// host waits for before it reads it.
95#[derive(Clone, Debug)]
96pub(crate) struct Published {
97    pub(crate) result: FrameResult,
98    pub(crate) sync: GpuSync,
99    pub(crate) texture: Option<FrameTexture>,
100}
101
102/// One texture of a borrowed ring.
103#[derive(Clone, Debug, Default)]
104pub(crate) struct RingSlot {
105    /// The newest frame rendered into the texture, which the host hasn't
106    /// acquired.
107    pub(crate) frame: Option<Published>,
108    pub(crate) acquired: bool,
109    pub(crate) rendering: bool,
110    /// The host's GPU may still read the texture, so the session renders
111    /// into it no more, even when a new ring has it again, until a release
112    /// of the ring.
113    pub(crate) quarantined: bool,
114    /// The host holds an exported ring's image from before a resize, which
115    /// gave the slot a new one that never reached the host: giving the old
116    /// one up quarantines nothing.
117    pub(crate) retired: bool,
118}
119
120impl RingSlot {
121    pub(crate) fn busy(&self) -> bool {
122        self.acquired || self.rendering || self.quarantined
123    }
124}
125
126/// Work sent to a session's thread, whose completion an abandon can fail at
127/// once instead of waiting for the thread to run it.
128pub(crate) trait PendingWork: Any + Send {
129    fn fail(self: Box<Self>, error: Error);
130}
131
132impl<T: Send + 'static> PendingWork for Resolver<T> {
133    fn fail(self: Box<Self>, error: Error) {
134        (*self).resolve(Err(error));
135    }
136}
137
138/// The ID of a piece of work that waits for a session's thread.
139#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
140pub(crate) struct WorkId(u64);
141
142/// The state that a session's handle and its thread share.
143pub(crate) struct SessionState {
144    pub(crate) lifecycle: RenderSessionState,
145    pub(crate) released: bool,
146    pub(crate) size: Size,
147    /// The scale factor that the target has, as `size` does.
148    pub(crate) scale_factor: f64,
149    /// The scale factor of the last resize sent, which a later resize that
150    /// names none keeps.
151    pub(crate) sent_scale_factor: f64,
152    pub(crate) generation: u64,
153    pub(crate) frame_generation: u64,
154    pub(crate) failure: Option<Error>,
155    /// Whether the session has a target to render to: false from a release
156    /// of its target until it gets a new one.
157    pub(crate) has_target: bool,
158    /// The frame results that wait for a drain.
159    pub(crate) results: Vec<FrameResult>,
160    /// Whether the frame wake ran since the last drain.
161    pub(crate) frame_woken: bool,
162    /// Whether the redraw wake may run: from the last demand until it runs.
163    pub(crate) redraw_armed: bool,
164    /// The attach's completion, until the map binds the session.
165    pub(crate) attach: Option<Resolver<()>>,
166    /// The completions of the detaches on their way.
167    pub(crate) detach_waiters: Vec<Resolver<()>>,
168    /// The completions of the releases on their way.
169    pub(crate) release_waiters: Vec<Resolver<()>>,
170    /// The completions of the work that waits for the session's thread.
171    pending: BTreeMap<WorkId, Box<dyn PendingWork>>,
172    next_work: u64,
173    /// The session's map, until the session lets go of it.
174    pub(crate) map: Option<Map>,
175    /// What the session's thread builds the renderer from, until it does:
176    /// an [`Init`]. It is boxed as `Any` so that the state names no
177    /// graphics types, whose auto traits are deep to prove for every type
178    /// that holds a map handle.
179    pub(crate) init: Option<Box<dyn Any + Send>>,
180    /// Counts the resizes sent, which run on the map's thread before they
181    /// reach the session's.
182    pub(crate) resizes_sent: u64,
183    /// How many graphics objects the session's thread holds.
184    pub(crate) graphics_objects: u32,
185    /// Whether the session's thread keeps its graphics objects until the
186    /// process exits, instead of freeing them, when the session ends.
187    pub(crate) keep_graphics: bool,
188    /// Whether an abandon keeps the graphics objects on any thread, as
189    /// `Device::abandon_keeps_graphics` says of the session's device.
190    pub(crate) abandon_keeps_graphics: bool,
191    /// The slots of a borrowed ring, and none for another target.
192    pub(crate) ring: Vec<RingSlot>,
193    /// How many of the ring's frames the host holds.
194    pub(crate) acquired_frames: u32,
195    /// The ring replacements and releases on their way: no frame is
196    /// acquired until they ran, since the frames published before one name
197    /// textures it replaces or lets go of.
198    pub(crate) pending_retargets: u32,
199    /// How many views are open on the session's acquired frames.
200    pub(crate) views: u32,
201    /// Whether the session's thread keeps graphics objects that the open
202    /// views name, which it lets go of once the last view ends.
203    pub(crate) viewed_teardown: bool,
204}
205
206impl SessionState {
207    /// Keeps `resolver` until the session's thread takes it.
208    fn register<T: Send + 'static>(&mut self, resolver: Resolver<T>) -> WorkId {
209        self.next_work += 1;
210        let id = WorkId(self.next_work);
211        self.pending.insert(id, Box::new(resolver));
212        id
213    }
214
215    /// What an end of the session completes, once the state is unlocked.
216    pub(crate) fn take_waiters(&mut self) -> Waiters {
217        Waiters {
218            attach: self.attach.take(),
219            pending: std::mem::take(&mut self.pending).into_values().collect(),
220            detaches: std::mem::take(&mut self.detach_waiters),
221            releases: std::mem::take(&mut self.release_waiters),
222        }
223    }
224}
225
226/// The completions that wait for a session when it ends.
227pub(crate) struct Waiters {
228    attach: Option<Resolver<()>>,
229    pending: Vec<Box<dyn PendingWork>>,
230    detaches: Vec<Resolver<()>>,
231    releases: Vec<Resolver<()>>,
232}
233
234impl Waiters {
235    /// Completes the releases, and the detaches with `detached`. The attach
236    /// and the work that never ran fail with `lost`.
237    pub(crate) fn settle(self, detached: &Result<(), Error>, lost: impl Fn() -> Error) {
238        if let Some(attach) = self.attach {
239            attach.resolve(Err(lost()));
240        }
241        for work in self.pending {
242            work.fail(lost());
243        }
244        for waiter in self.detaches {
245            waiter.resolve(detached.clone());
246        }
247        for waiter in self.releases {
248            waiter.resolve(Ok(()));
249        }
250    }
251}
252
253/// Who abandons a session.
254#[derive(Clone, Copy, PartialEq, Eq)]
255pub(crate) enum Abandoner {
256    /// The host, through the handle.
257    Host,
258    /// The library, for a session that the host released, or stopped
259    /// servicing.
260    Library,
261}
262
263pub(crate) struct SessionShared {
264    pub(crate) id: SessionId,
265    pub(crate) driver: Driver,
266    /// The work of the thread that runs the session.
267    pub(crate) queue: SessionQueue,
268    /// The thread that runs the session's work, once it is known: a core
269    /// worker's from the attach, and a caller thread's from when the host
270    /// takes the driver work.
271    pub(crate) thread: Arc<OnceLock<ThreadId>>,
272    /// The thread of the map's runtime, which runs the map's side of the
273    /// session's work.
274    runtime_thread: ThreadId,
275    pub(crate) state: Mutex<SessionState>,
276    /// Held while the session's thread runs a task, so an abandon waits for
277    /// the graphics work in progress.
278    pub(crate) gate: Mutex<()>,
279    /// The session's lease on the host's device, which an abandon revokes,
280    /// since graphics objects that it keeps hold the device.
281    lease: DeviceLease,
282    /// Held while [`RenderSession::send_then`] sends a command and attaches
283    /// its callback, and while an attach hands its completion out, which the
284    /// session's thread waits for before it delivers results.
285    sending: Mutex<()>,
286    /// Whether the session's thread is inside a driver call: a core worker
287    /// running a task and delivering what it sent the host, or a service of
288    /// a caller-driven session.
289    pub(crate) in_call: AtomicBool,
290    pub(crate) frame_wake: Option<Wake>,
291    pub(crate) redraw_wake: Option<Wake>,
292    capabilities: RenderSessionCapabilities,
293    driver_work_taken: AtomicBool,
294    /// Whether the driver-work wake may run: from the start of the last
295    /// service until it runs.
296    pub(crate) driver_armed: Arc<AtomicBool>,
297    /// The first of the map's commands that the session's work waits for,
298    /// or `u64::MAX` for none: the map tells the session's thread when it
299    /// ran a command only from that one on, so a command that no work waits
300    /// for wakes no caller's driver.
301    pub(crate) awaited_command: Arc<AtomicU64>,
302    /// In the browser, whether a caller-driven session waits for the device
303    /// that it asked the browser's WebGPU for: its services build nothing
304    /// until the device is there, and the driver-work wake runs then.
305    pub(crate) preparing: AtomicBool,
306}
307
308impl SessionShared {
309    /// A completion that the session's thread resolves.
310    fn completion<T: Send + 'static>(&self) -> (Completion<T>, Resolver<T>) {
311        Completion::at(Home::Later(Arc::clone(&self.thread), self.runtime_thread))
312    }
313
314    /// The completion of the work `id`, unless an end of the session
315    /// completed it first.
316    pub(crate) fn take_work<T: Send + 'static>(&self, id: WorkId) -> Option<Resolver<T>> {
317        let work: Box<dyn Any + Send> = self.state.lock().pending.remove(&id)?;
318        work.downcast::<Resolver<T>>().ok().map(|resolver| *resolver)
319    }
320
321    pub(crate) fn is_released(&self) -> bool {
322        self.state.lock().released
323    }
324
325    /// The redraw wake that tells the host the map has something new to
326    /// draw, unless the host was told since its last demand, or the session
327    /// has no target. The host isn't told again until its next demand.
328    pub(crate) fn take_redraw_wake(&self) -> Option<Wake> {
329        let mut state = self.state.lock();
330        let wake = state.redraw_armed && state.has_target && state.lifecycle == RenderSessionState::Attached;
331        state.redraw_armed &= !wake;
332        wake.then(|| self.redraw_wake.clone()).flatten()
333    }
334
335    /// Starts a detach on the session's thread, after the work sent before.
336    /// The state is locked, and the session usable or failed.
337    fn start_detach(&self, state: &mut SessionState) {
338        state.lifecycle = RenderSessionState::Detaching;
339        worker::post(&self.queue, Worker::detach);
340    }
341
342    /// Releases the session without waiting: it detaches, unless it is
343    /// detached or abandoned already, and every call on it fails after. A
344    /// caller-driven session that isn't attached, or whose map was released,
345    /// is abandoned instead, so the release doesn't wait for the host to
346    /// service it.
347    fn dispose(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
348        with_unlocked_wakes(|| self.dispose_locked(done))
349    }
350
351    /// Releases the session without waiting and without graphics calls past
352    /// the one in progress: a session that hasn't ended is abandoned, and
353    /// keeps its graphics objects until the process exits.
354    fn dispose_keeping_graphics(&self) -> Result<(), Error> {
355        with_unlocked_wakes(|| {
356            {
357                let mut state = self.state.lock();
358                if state.released {
359                    return Err(released());
360                }
361                state.released = true;
362                state.keep_graphics = true;
363                if matches!(state.lifecycle, RenderSessionState::Detached | RenderSessionState::Abandoned) {
364                    return Ok(());
365                }
366            }
367            if self.abandon_locked(Abandoner::Library, true).is_err() {
368                // Only the session's own work could hold the gate here: the
369                // session detaches after it, keeping its graphics objects.
370                let mut state = self.state.lock();
371                if !matches!(
372                    state.lifecycle,
373                    RenderSessionState::Detaching | RenderSessionState::Detached | RenderSessionState::Abandoned
374                ) {
375                    self.start_detach(&mut state);
376                }
377            }
378            Ok(())
379        })
380    }
381
382    fn dispose_locked(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
383        let mut state = self.state.lock();
384        if state.released {
385            return Err(released());
386        }
387        state.released = true;
388        // A released map waits for no service of its session's detach.
389        let map_released = state.map.as_ref().is_some_and(Map::is_released);
390        match state.lifecycle {
391            RenderSessionState::Detached | RenderSessionState::Abandoned => {
392                drop(state);
393                if let Some(done) = done {
394                    done.resolve(Ok(()));
395                }
396                return Ok(());
397            }
398            RenderSessionState::Detaching => {}
399            RenderSessionState::Attaching | RenderSessionState::Failed if self.driver == Driver::CallerThread => {
400                state.release_waiters.extend(done);
401                drop(state);
402                self.abandon_or_detach();
403                return Ok(());
404            }
405            RenderSessionState::Attached if self.driver == Driver::CallerThread && map_released => {
406                state.release_waiters.extend(done);
407                drop(state);
408                self.abandon_or_detach();
409                return Ok(());
410            }
411            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Failed => {
412                self.start_detach(&mut state);
413            }
414        }
415        state.release_waiters.extend(done);
416        Ok(())
417    }
418
419    /// Abandons the released session, or detaches it when its own work
420    /// holds the gate, which only it could here.
421    fn abandon_or_detach(&self) {
422        if self.abandon(Abandoner::Library).is_err() {
423            let mut state = self.state.lock();
424            if state.lifecycle != RenderSessionState::Abandoned {
425                self.start_detach(&mut state);
426            }
427        }
428    }
429
430    /// Stops the session at once, as [`RenderSession::abandon`] documents,
431    /// and returns how many graphics objects it keeps. The library may
432    /// abandon a released session too.
433    pub(crate) fn abandon(&self, by: Abandoner) -> Result<u32, Error> {
434        with_unlocked_wakes(|| self.abandon_locked(by, false))
435    }
436
437    /// Waits for a [`RenderSession::send_then`] in progress to attach its
438    /// callback. The session's thread calls it before it delivers what it
439    /// sent the host, so that a command's result reaches the callback there,
440    /// inside the driver call.
441    pub(crate) fn wait_for_senders(&self) {
442        drop(self.sending.lock());
443    }
444
445    /// Takes the sending lock, which the session's thread waits for before
446    /// it delivers results, unless this thread holds it already: a send
447    /// inside another, such as from a completion that a release settles at
448    /// once on this thread, is delivered after the outer one too.
449    fn hold_sending(&self) -> Option<Sending<'_>> {
450        if SENDING.with(|sending| sending.borrow().contains(&self.id)) {
451            return None;
452        }
453        let guard = self.sending.lock();
454        SENDING.with(|sending| sending.borrow_mut().push(self.id));
455        Some(Sending { id: self.id, _guard: guard })
456    }
457
458    /// Marks the session's thread as inside a driver call until the guard
459    /// drops.
460    pub(crate) fn enter_call(&self) -> InCall<'_> {
461        InCall { shared: self, previous: self.in_call.swap(true, Ordering::SeqCst) }
462    }
463
464    /// Abandons the session, which keeps its graphics objects until the
465    /// process exits if `keep_graphics`, and returns how many it keeps.
466    ///
467    /// A driver call can't be waited for on its own thread, where the
468    /// session's callbacks run inside it, and a host's service on another
469    /// thread is the host's to end, so either is busy. A core worker's call
470    /// on another thread is waited for. A caller-driven session that is
471    /// abandoned off its thread keeps its graphics objects, which only its
472    /// thread may free: once this returns, the host may destroy what they
473    /// were made on.
474    fn abandon_locked(&self, by: Abandoner, keep_graphics: bool) -> Result<u32, Error> {
475        let on_driver = self.thread.get() == Some(&std::thread::current().id());
476        if self.in_call.load(Ordering::SeqCst) {
477            if on_driver {
478                return Err(Error::busy("the render session's driver call is running on this thread"));
479            }
480            if self.driver == Driver::CallerThread && by == Abandoner::Host {
481                return Err(Error::busy("the render session's driver work is running on another thread"));
482            }
483        }
484        let off_thread = self.driver == Driver::CallerThread && !on_driver;
485        let gate = if on_driver {
486            self.gate.try_lock().ok_or_else(|| Error::busy("the render session is rendering on this thread"))?
487        } else {
488            self.gate.lock()
489        };
490        let (waiters, map, kept) = {
491            let mut state = self.state.lock();
492            if by == Abandoner::Host && state.released {
493                return Err(released());
494            }
495            match state.lifecycle {
496                RenderSessionState::Attaching
497                | RenderSessionState::Attached
498                | RenderSessionState::Detaching
499                | RenderSessionState::Failed => {}
500                RenderSessionState::Detached | RenderSessionState::Abandoned => {
501                    return Err(Error::invalid_state("the render session was detached or abandoned"));
502                }
503            }
504            // The views keep the frames' sync objects in place, which the
505            // abandon would let go of. A library's abandon, of a session
506            // that the host released, keeps them until the views end.
507            if by == Abandoner::Host && state.views != 0 {
508                return Err(Error::busy("a view is open on one of the render session's acquired frames"));
509            }
510            state.lifecycle = RenderSessionState::Abandoned;
511            state.keep_graphics |= keep_graphics || off_thread || state.abandon_keeps_graphics;
512            let kept = if state.keep_graphics { state.graphics_objects } else { 0 };
513            (state.take_waiters(), state.map.take(), kept)
514        };
515        match &map {
516            // The map unbinds the session before another can attach.
517            Some(map) => {
518                map.unbind_session_then(self.id, self.queue.clone(), Worker::finish);
519                map.release_session_claim(self.id);
520            }
521            None => worker::post(&self.queue, Worker::finish),
522        }
523        // A core worker lets go of its graphics objects at its next task,
524        // which runs before this returns: the host may destroy what they were
525        // made on once it does.
526        // In the browser the session's queue runs on this thread, which runs
527        // that task here instead, unless it is inside the session's work.
528        #[cfg(target_family = "wasm")]
529        let run_now = self.driver == Driver::CoreWorker
530            && !self.in_call.load(Ordering::SeqCst)
531            && !SENDING.with(|sending| sending.borrow().contains(&self.id));
532        let torn_down = (self.driver == Driver::CoreWorker && !on_driver).then(|| {
533            let (sender, receiver) = std::sync::mpsc::sync_channel::<()>(1);
534            worker::post(&self.queue, move |_, _| {
535                let _ = sender.send(());
536            });
537            receiver
538        });
539        drop(gate);
540        if let Some(receiver) = torn_down {
541            // A worker that ended drops the task, and the sender with it.
542            let _ = receiver.recv();
543        }
544        #[cfg(target_family = "wasm")]
545        if run_now {
546            worker::post(&self.queue, |_, _| {});
547            crate::web::run_session_now(self.id);
548        }
549        // Off the session's thread, the session makes no more graphics
550        // calls: a core worker tore down above, and a caller-driven session
551        // keeps its graphics objects. On it, the teardown that follows
552        // still needs the device.
553        if !on_driver {
554            self.lease.revoke();
555        }
556        if kept != 0 {
557            let reason = if keep_graphics {
558                "it was abandoned without graphics calls"
559            } else if off_thread {
560                "only the thread that services it may free them"
561            } else {
562                "only a detach frees OpenGL and WebGPU objects"
563            };
564            Log::warning(
565                Event::Render,
566                format!("An abandoned render session keeps {kept} graphics objects until the process exits: {reason}"),
567            );
568        }
569        let lost = || Error::target_lost("the render session was abandoned");
570        waiters.settle(&Err(lost()), lost);
571        drop(map);
572        Ok(kept)
573    }
574}
575
576/// Marks a session's thread as inside a driver call, as
577/// [`SessionShared::enter_call`] does.
578pub(crate) struct InCall<'a> {
579    shared: &'a SessionShared,
580    previous: bool,
581}
582
583impl Drop for InCall<'_> {
584    fn drop(&mut self) {
585        self.shared.in_call.store(self.previous, Ordering::SeqCst);
586    }
587}
588
589fn released() -> Error {
590    Error::invalid_state("the render session was released")
591}
592
593/// Fails unless the session takes work: it is attaching or attached, and
594/// not released.
595fn check_usable(state: &SessionState) -> Result<(), Error> {
596    if state.released {
597        return Err(released());
598    }
599    match state.lifecycle {
600        RenderSessionState::Attaching | RenderSessionState::Attached => Ok(()),
601        RenderSessionState::Failed => {
602            Err(state.failure.clone().unwrap_or_else(|| Error::native("the render session failed")))
603        }
604        RenderSessionState::Detaching | RenderSessionState::Detached | RenderSessionState::Abandoned => {
605            Err(Error::invalid_state("the render session is not attached: it was detached or abandoned"))
606        }
607    }
608}
609
610thread_local! {
611    /// The driver wakes that this thread's posts asked for during a handle
612    /// call, which may hold the session's locks.
613    static DEFERRED_WAKES: RefCell<Option<Vec<Wake>>> = const { RefCell::new(None) };
614    /// The sessions whose sending lock this thread holds.
615    static SENDING: RefCell<Vec<SessionId>> = const { RefCell::new(Vec::new()) };
616}
617
618/// A session's sending lock, which [`SessionShared::hold_sending`] took.
619struct Sending<'a> {
620    id: SessionId,
621    _guard: parking_lot::MutexGuard<'a, ()>,
622}
623
624impl Drop for Sending<'_> {
625    fn drop(&mut self) {
626        SENDING.with(|sending| sending.borrow_mut().retain(|id| *id != self.id));
627    }
628}
629
630/// Runs `call`, which may post to a session's queue with the session's locks
631/// held, then the driver wakes that its posts asked for, with nothing locked.
632fn with_unlocked_wakes<R>(call: impl FnOnce() -> R) -> R {
633    let outer = DEFERRED_WAKES.with(|deferred| deferred.borrow_mut().replace(Vec::new()));
634    let result = call();
635    let wakes = DEFERRED_WAKES.with(|deferred| {
636        let mut deferred = deferred.borrow_mut();
637        let wakes = deferred.take().unwrap_or_default();
638        match outer {
639            // The outer call runs them.
640            Some(mut outer) => {
641                outer.extend(wakes);
642                *deferred = Some(outer);
643                Vec::new()
644            }
645            None => wakes,
646        }
647    });
648    for wake in wakes {
649        wake();
650    }
651    result
652}
653
654/// Runs `wake` now, or once the handle call on this thread returns.
655fn wake_unlocked(wake: &Wake) {
656    let deferred = DEFERRED_WAKES.with(|deferred| match deferred.borrow_mut().as_mut() {
657        Some(wakes) => {
658            wakes.push(Arc::clone(wake));
659            true
660        }
661        None => false,
662    });
663    if !deferred {
664        wake();
665    }
666}
667
668/// Sizes in pixels a target of `size` logical pixels at `pixel_ratio`.
669pub(crate) fn physical_size(size: Size, pixel_ratio: f32) -> Size {
670    Size::new((size.width as f32 * pixel_ratio) as u32, (size.height as f32 * pixel_ratio) as u32)
671}
672
673/// A render session: a renderer that draws a map into a target, on a thread
674/// of its own or on the host's.
675///
676/// The host demands frames, which finish with [`FrameResult`]s that
677/// [`drain_frame_results`](Self::drain_frame_results) takes. A demand shows
678/// the map's commands sent before it, except the changes that an open
679/// command group holds back. The session's work runs on its thread in the
680/// order it was sent, and reports through a [`Completion`]. `Clone` is
681/// another handle to the same session, and any thread may use one.
682///
683/// A session that attached with [`Driver::CallerThread`] runs its work only
684/// when the host services its [`DriverWork`], which
685/// [`take_driver_work`](Self::take_driver_work) hands out.
686///
687/// The session lives until [`detach`](Self::detach),
688/// [`release`](Self::release), [`dispose`](Self::dispose) or
689/// [`abandon`](Self::abandon), or until its last handle drops, and it holds
690/// its map until then. A call that sends work to a session that no longer
691/// takes it fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind), or
692/// with the failure of a session that failed.
693///
694/// Unless the session was released or disposed, the last drop of its
695/// handles, [`AcquiredFrame`]s and [`FrameView`]s waits for a core worker's
696/// thread to end, once the session has let go of its graphics objects and
697/// its map. A drop on a thread of the library, such as in a callback or a
698/// wake that the library runs, doesn't wait: it leaves the session's thread
699/// to end alone.
700#[derive(Clone)]
701pub struct RenderSession {
702    handle: Arc<SessionHandle>,
703}
704
705/// Disposes of the session when the last handle drops.
706struct SessionHandle {
707    shared: Arc<SessionShared>,
708    thread_end: ThreadEnd,
709}
710
711/// A core worker's thread, which the last of the host's handles, frames and
712/// views of the session to drop waits for. A caller-driven session has no
713/// thread, and in the browser the thread is the host's.
714type ThreadEnd = Option<Arc<Joined>>;
715
716impl Drop for SessionHandle {
717    /// Disposes of the session, which ends its thread once the frames and
718    /// views of it end too, then waits for the thread as `thread_end` drops,
719    /// unless they hold it.
720    fn drop(&mut self) {
721        let _ = self.shared.dispose(None);
722    }
723}
724
725impl std::fmt::Debug for RenderSession {
726    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
727        f.debug_struct("RenderSession").field("id", &self.shared().id).finish()
728    }
729}
730
731impl PartialEq for RenderSession {
732    fn eq(&self, other: &RenderSession) -> bool {
733        Arc::ptr_eq(&self.handle, &other.handle)
734    }
735}
736
737impl Eq for RenderSession {}
738
739/// Attaches a session to `map`, as [`Map::attach`] documents, and runs `then`
740/// with the session and the attach's completion before the session's thread
741/// may deliver that, as [`Map::attach_then`] documents.
742pub(crate) fn attach<R>(
743    map: &Map,
744    target: RenderTarget,
745    options: AttachOptions,
746    then: impl FnOnce(&RenderSession, Completion<()>) -> R,
747) -> Result<R, Error> {
748    // The wakes that the attach runs, such as a caller-driven session's
749    // driver-work wake, wait for the release of the session's sending lock,
750    // so a host's wake that services the session can't wait for it.
751    with_unlocked_wakes(|| attach_unlocked(map, target, options, then))
752}
753
754fn attach_unlocked<R>(
755    map: &Map,
756    target: RenderTarget,
757    options: AttachOptions,
758    then: impl FnOnce(&RenderSession, Completion<()>) -> R,
759) -> Result<R, Error> {
760    static NEXT_ID: AtomicU64 = AtomicU64::new(1);
761    let id = SessionId(NEXT_ID.fetch_add(1, Ordering::Relaxed));
762    let mut ring = None;
763    let mut export_kind = None;
764    let (size, target) = match target {
765        RenderTarget::Offscreen { size, device } => (size, TargetInit::Offscreen(device)),
766        RenderTarget::Surface { size, surface, device } => {
767            if device.is_none() && !surface.needs_no_device() {
768                return Err(Error::invalid_argument("a surface that the host made needs the host's device"));
769            }
770            surface.check_area()?;
771            surface.check_pixel_format(device.as_ref())?;
772            (size, TargetInit::Surface { surface: SentSurface::new(surface, id), device })
773        }
774        RenderTarget::Borrowed { size, ring: borrowed, device } => {
775            let (producer, consumer) = device.borrowed_sync_kinds(&borrowed)?;
776            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
777                Error::unsupported("render target supports none of the requested producer sync kinds")
778            })?;
779            if borrowed.depth() == 0 || borrowed.physical_size().is_empty() {
780                return Err(Error::invalid_argument("a borrowed ring needs textures of a size"));
781            }
782            ring = Some((borrowed.depth(), picked, consumer));
783            (size, TargetInit::Borrowed { ring: borrowed, device, producer: picked })
784        }
785        RenderTarget::Exported { size, ring: exported, device } => {
786            if exported.depth == 0 {
787                return Err(Error::invalid_argument("an exported ring needs at least one image"));
788            }
789            if exported.kinds.is_empty() {
790                return Err(Error::invalid_argument("an exported ring needs a kind of image to share"));
791            }
792            if size.is_empty() {
793                return Err(Error::invalid_argument("the target's size must not be empty"));
794            }
795            let device = match device {
796                Some(device) => device,
797                None => Device::for_exported_ring(&exported)?,
798            };
799            let (kind, producer, consumer) = device.export_plan(&exported)?;
800            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
801                Error::unsupported("render target supports none of the requested producer sync kinds")
802            })?;
803            ring = Some((exported.depth, picked, consumer));
804            export_kind = Some(kind);
805            (size, TargetInit::Exported { ring: exported, device, kind, producer: picked })
806        }
807    };
808    if size.is_empty() {
809        return Err(Error::invalid_argument("the target's size must not be empty"));
810    }
811    let (target, lease) = target.lease();
812    let presentation = matches!(target, TargetInit::Surface { .. });
813    let queue = SessionQueue::default();
814    let driver_armed = Arc::new(AtomicBool::new(true));
815    if options.driver == Driver::CallerThread
816        && let Some(wake) = options.driver_work_wake
817    {
818        let armed = Arc::clone(&driver_armed);
819        queue.set_waker(Some(Arc::new(move || {
820            if armed.swap(false, Ordering::SeqCst) {
821                wake_unlocked(&wake);
822            }
823        })));
824    }
825    let scale_factor = map.scale_factor();
826    let shared = Arc::new(SessionShared {
827        id,
828        driver: options.driver,
829        queue: queue.clone(),
830        thread: Arc::default(),
831        runtime_thread: map.runtime_thread(),
832        state: Mutex::new(SessionState {
833            lifecycle: RenderSessionState::Attaching,
834            released: false,
835            size,
836            scale_factor,
837            sent_scale_factor: scale_factor,
838            generation: 1,
839            frame_generation: 0,
840            failure: None,
841            has_target: true,
842            results: Vec::new(),
843            frame_woken: false,
844            redraw_armed: true,
845            attach: None,
846            detach_waiters: Vec::new(),
847            release_waiters: Vec::new(),
848            pending: BTreeMap::new(),
849            next_work: 0,
850            map: Some(map.clone()),
851            init: Some(Box::new(Init {
852                target,
853                size,
854                scale_factor,
855                glyph_cache: map.glyph_cache(),
856                font_face_engine: map.font_face_engine(),
857                registry: Arc::clone(map.registry()),
858                tile_cache_enabled: map.tile_cache_enabled(),
859                local_font_family: map.local_font_family(),
860                failure: None,
861                pool: map.pool(),
862            })),
863            resizes_sent: 0,
864            graphics_objects: 0,
865            keep_graphics: false,
866            abandon_keeps_graphics: false,
867            ring: vec![RingSlot::default(); ring.map_or(0, |(depth, _, _)| depth)],
868            acquired_frames: 0,
869            pending_retargets: 0,
870            views: 0,
871            viewed_teardown: false,
872        }),
873        gate: Mutex::new(()),
874        lease,
875        frame_wake: options.frame_wake,
876        redraw_wake: options.redraw_wake,
877        capabilities: RenderSessionCapabilities {
878            driver: options.driver,
879            texture_ring_depth: ring.map_or(1, |(depth, _, _)| depth as u32),
880            frame_acquisition: ring.is_some(),
881            readback: !presentation && ring.is_none(),
882            presentation,
883            producer_sync_kind: ring.map(|(_, producer, _)| producer),
884            consumer_sync_kinds: ring.map_or(SyncKinds::NONE, |(_, _, consumer)| consumer),
885            export_kind,
886        },
887        driver_work_taken: AtomicBool::new(false),
888        driver_armed,
889        awaited_command: Arc::new(AtomicU64::new(u64::MAX)),
890        preparing: AtomicBool::new(false),
891        in_call: AtomicBool::new(false),
892        sending: Mutex::new(()),
893    });
894    let (completion, resolver) = shared.completion();
895    shared.state.lock().attach = Some(resolver);
896    // Held until `then` returns: the session's thread delivers the attach's
897    // result after, inside its driver call.
898    let sending = Arc::clone(&shared);
899    let held = sending.hold_sending();
900    map.claim_session(id, Arc::downgrade(&shared))?;
901    let mut thread_end = None;
902    if options.driver == Driver::CoreWorker {
903        match start_thread(Arc::clone(&shared)) {
904            Ok((thread, end)) => {
905                let _ = shared.thread.set(thread);
906                thread_end = end.map(Arc::new);
907            }
908            Err(error) => {
909                map.release_session_claim(id);
910                return Err(error);
911            }
912        }
913    }
914    let session = RenderSession { handle: Arc::new(SessionHandle { shared, thread_end }) };
915    if let Err(error) = map.bind_session(id, queue, Arc::clone(&session.shared().awaited_command), size) {
916        // The map was released meanwhile: the session lets go of it. Its
917        // drop waits for its thread, which waits for the sending lock.
918        drop(held);
919        drop(session);
920        return Err(error);
921    }
922    if options.driver == Driver::CallerThread {
923        #[cfg(target_family = "wasm")]
924        prepare_caller_driven(session.shared());
925        // The first service builds the renderer, which is work that is ready
926        // now: this wakes the host, unless the map's first update, posted
927        // from the runtime's thread, woke it already.
928        session.shared().queue.wake();
929    }
930    let attached = then(&session, completion);
931    // Before the session, whose drop may wait for its thread, which waits
932    // for the sending lock.
933    drop(held);
934    Ok(attached)
935}
936
937/// Starts a core worker's thread, which builds the session's renderer, then
938/// runs the session's queue until the session ends.
939#[cfg(not(target_family = "wasm"))]
940fn start_thread(shared: Arc<SessionShared>) -> Result<(ThreadId, Option<Joined>), Error> {
941    let thread = mln_util::thread::spawn("RenderSession", move || {
942        let queue = shared.queue.clone();
943        let mut worker = None;
944        worker::build(&shared, &mut worker, &mut None);
945        // The worker holds the session from here on.
946        drop(shared);
947        queue.run(&mut worker);
948        // The session's work that comes from now on drops at once, so tasks
949        // that hold the queue can't keep it alive.
950        queue.close();
951        drop(worker);
952    })
953    .map_err(|error| Error::native(format!("can't start the render session's thread: {error}")))?;
954    let thread_id = thread.thread().id();
955    // The thread ends by itself once the session ends.
956    Ok((thread_id, Some(Joined::new(thread))))
957}
958
959/// Runs a core worker on this thread, the browser's one, in the instance's
960/// pump: it builds the session's renderer once its device is ready, which
961/// may take the browser's WebGPU a while, then runs the session's queue until
962/// the session ends.
963#[cfg(target_family = "wasm")]
964#[expect(clippy::unnecessary_wraps, reason = "the threads of other builds can fail to start")]
965fn start_thread(shared: Arc<SessionShared>) -> Result<(ThreadId, Option<Joined>), Error> {
966    let prepared = worker::prepare(&shared);
967    wasm_bindgen_futures::spawn_local(async move {
968        prepared.await;
969        let queue = shared.queue.clone();
970        let mut worker = None;
971        worker::build(&shared, &mut worker, &mut None);
972        let id = shared.id;
973        // The worker holds the session from here on.
974        drop(shared);
975        let worker = RefCell::new(worker);
976        crate::web::drive_session(id, queue.clone(), move || {
977            queue.run_once(&mut worker.borrow_mut());
978            if queue.is_stopped() {
979                queue.close();
980                drop(worker.borrow_mut().take());
981            }
982        });
983    });
984    Ok((std::thread::current().id(), None))
985}
986
987/// In the browser, asks for the device that a caller-driven session's build
988/// needs, as a core worker does before it builds, and wakes the host to
989/// service the session once the device is there.
990#[cfg(target_family = "wasm")]
991fn prepare_caller_driven(shared: &Arc<SessionShared>) {
992    shared.preparing.store(true, Ordering::SeqCst);
993    let prepared = worker::prepare(shared);
994    let shared = Arc::downgrade(shared);
995    wasm_bindgen_futures::spawn_local(async move {
996        prepared.await;
997        if let Some(shared) = shared.upgrade() {
998            shared.preparing.store(false, Ordering::SeqCst);
999            shared.queue.wake();
1000        }
1001    });
1002}
1003
1004impl RenderSession {
1005    fn shared(&self) -> &Arc<SessionShared> {
1006        &self.handle.shared
1007    }
1008
1009    /// Sends a command with `send`, such as [`barrier`](Self::barrier), and
1010    /// calls `callback` once with its result, where the session delivers
1011    /// it: on the session's thread, inside its driver call, even when the
1012    /// command runs before `send` returns. A [`Completion::on_complete`]
1013    /// after the command returned would run at once on this thread instead.
1014    /// The callback doesn't run when `send` fails.
1015    ///
1016    /// Fails as `send` does.
1017    pub fn send_then<T: Send + 'static>(
1018        &self,
1019        send: impl FnOnce(&RenderSession) -> Result<Completion<T>, Error>,
1020        callback: impl FnOnce(Result<T, Error>) + Send + 'static,
1021    ) -> Result<(), Error> {
1022        // The wakes that the command runs wait for the lock's release, so a
1023        // host's wake that services the session can't wait for it.
1024        with_unlocked_wakes(|| {
1025            let ready = {
1026                let _sending = self.shared().hold_sending();
1027                send(self)?.on_complete_unless_ready(callback)
1028            };
1029            // A result that came without the session's thread, such as a
1030            // command dropped unrun, goes to the callback here.
1031            if let Some((callback, result)) = ready {
1032                callback(result);
1033            }
1034            Ok(())
1035        })
1036    }
1037
1038    /// Sends `task` to the session's thread, after the work sent before,
1039    /// resizes included, and completes with its result. A session that lost
1040    /// its graphics objects before the task runs completes it with
1041    /// [`ErrorKind::TargetLost`](mln_util::ErrorKind).
1042    fn operation<T: Send + 'static>(
1043        &self,
1044        task: impl FnOnce(&mut Worker, &mut Outbox) -> Result<T, Error> + Send + 'static,
1045    ) -> Result<Completion<T>, Error> {
1046        self.settled_operation(|worker, outbox| task(worker, outbox).map(|value| (value, None)))
1047    }
1048
1049    /// Sends `task` as [`operation`](Self::operation) does, and completes
1050    /// once the host's reads that it returns end, or a second passes.
1051    fn settled_operation<T: Send + 'static>(
1052        &self,
1053        task: impl FnOnce(&mut Worker, &mut Outbox) -> Result<(T, Pending), Error> + Send + 'static,
1054    ) -> Result<Completion<T>, Error> {
1055        let shared = self.shared();
1056        with_unlocked_wakes(|| {
1057            let mut state = shared.state.lock();
1058            check_usable(&state)?;
1059            let (completion, resolver) = shared.completion();
1060            let work = state.register(resolver);
1061            let resizes = state.resizes_sent;
1062            worker::post(&shared.queue, move |worker, outbox| {
1063                let task: worker::Task = Box::new(move |worker, outbox| {
1064                    let Some(resolver) = worker.take_work(work) else { return };
1065                    match task(worker, outbox) {
1066                        Ok((value, pending)) => worker.settle_then(
1067                            pending,
1068                            move |outbox, settled| outbox.resolve(resolver, settled.map(|()| value)),
1069                            outbox,
1070                        ),
1071                        Err(error) => outbox.resolve(resolver, Err(error)),
1072                    }
1073                });
1074                worker.after_earlier_work(resizes, task, outbox);
1075            });
1076            drop(state);
1077            Ok(completion)
1078        })
1079    }
1080
1081    /// Hands out the work of a [`Driver::CallerThread`] session, for the
1082    /// calling thread to run: the session's graphics work runs only in its
1083    /// [`service`](DriverWork::service), and on no other thread.
1084    ///
1085    /// Take it once, on the host's graphics thread, from the attach on: the
1086    /// attach itself completes in a service. It stays available after a
1087    /// release, which the host services to its end.
1088    ///
1089    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
1090    /// session on a core worker, and with
1091    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once it was taken.
1092    pub fn take_driver_work(&self) -> Result<DriverWork, Error> {
1093        let shared = self.shared();
1094        if shared.driver != Driver::CallerThread {
1095            return Err(Error::unsupported("the render session runs on a core worker"));
1096        }
1097        if shared.driver_work_taken.swap(true, Ordering::SeqCst) {
1098            return Err(Error::invalid_state("the render session's driver work was taken already"));
1099        }
1100        let _ = shared.thread.set(std::thread::current().id());
1101        Ok(DriverWork::new(Arc::clone(shared)))
1102    }
1103
1104    /// What the session can do. Fails with
1105    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once it is released.
1106    pub fn capabilities(&self) -> Result<RenderSessionCapabilities, Error> {
1107        let state = self.shared().state.lock();
1108        if state.released {
1109            return Err(released());
1110        }
1111        Ok(self.shared().capabilities)
1112    }
1113
1114    /// The session's state now. Fails with
1115    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once it is released.
1116    pub fn snapshot(&self) -> Result<RenderSessionSnapshot, Error> {
1117        let state = self.shared().state.lock();
1118        if state.released {
1119            return Err(released());
1120        }
1121        Ok(RenderSessionSnapshot {
1122            state: state.lifecycle,
1123            extent: LogicalExtent { size: state.size, scale_factor: state.scale_factor },
1124            generation: state.generation,
1125            frame_generation: state.frame_generation,
1126            failure: state.failure.clone(),
1127            has_target: state.lifecycle == RenderSessionState::Attached && state.has_target,
1128            acquired_frames: state.acquired_frames,
1129        })
1130    }
1131
1132    /// Takes the newest frame that a borrowed ring rendered, if one waits:
1133    /// the older frames that the host didn't acquire are dropped, and the
1134    /// session may render into their textures again. While the host holds a
1135    /// frame in every texture, demands wait for a release.
1136    ///
1137    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
1138    /// session without a ring, and as a call that sends work does once the
1139    /// session no longer takes work.
1140    pub fn acquire_frame(&self) -> Result<Option<AcquiredFrame>, Error> {
1141        let shared = self.shared();
1142        let mut state = shared.state.lock();
1143        check_usable(&state)?;
1144        if !shared.capabilities.frame_acquisition {
1145            return Err(Error::unsupported("render session does not expose acquired texture frames"));
1146        }
1147        if state.pending_retargets != 0 {
1148            return Ok(None);
1149        }
1150        let newest = state
1151            .ring
1152            .iter()
1153            .enumerate()
1154            .filter(|(_, slot)| !slot.acquired && slot.frame.is_some())
1155            .max_by_key(|(_, slot)| slot.frame.as_ref().map_or(0, |frame| frame.result.frame_generation))
1156            .map(|(index, _)| index);
1157        let Some(index) = newest else { return Ok(None) };
1158        for (other, slot) in state.ring.iter_mut().enumerate() {
1159            if other != index && !slot.acquired {
1160                slot.frame = None;
1161            }
1162        }
1163        let slot = &mut state.ring[index];
1164        let Some(frame) = slot.frame.take() else { return Ok(None) };
1165        slot.acquired = true;
1166        state.acquired_frames += 1;
1167        Ok(Some(AcquiredFrame {
1168            shared: Arc::clone(shared),
1169            thread_end: self.handle.thread_end.clone(),
1170            slot: index,
1171            frame,
1172            done: false,
1173        }))
1174    }
1175
1176    /// Gives a borrowed ring new textures, of `size` logical pixels: as many
1177    /// as it has, of its format. Once the completion reports success, the
1178    /// session no longer uses the old textures, and no longer waits for the
1179    /// consumer sync that they were given back with: the host may reuse or
1180    /// destroy them. The session's thread polls that sync on its later turns,
1181    /// for a second at most, and logs a wait that runs out. Frames wait for
1182    /// it meanwhile.
1183    ///
1184    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
1185    /// session without a borrowed ring, with
1186    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for another number
1187    /// of textures, and with [`ErrorKind::InvalidState`](mln_util::ErrorKind)
1188    /// while the host holds one of the ring's frames. Completes with
1189    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) for textures of
1190    /// another format or kind.
1191    pub fn set_ring(&self, size: Size, ring: BorrowedRing) -> Result<Completion<Applied>, Error> {
1192        let shared = Arc::clone(self.shared());
1193        {
1194            let mut state = shared.state.lock();
1195            check_usable(&state)?;
1196            if shared.capabilities.readback {
1197                return Err(Error::unsupported("an offscreen session keeps its target"));
1198            }
1199            if !shared.capabilities.frame_acquisition {
1200                return Err(Error::unsupported("a surface session takes no caller-owned texture"));
1201            }
1202            if shared.capabilities.export_kind.is_some() {
1203                return Err(Error::unsupported("an exported ring resizes instead of taking new textures"));
1204            }
1205            if state.acquired_frames != 0 {
1206                return Err(Error::invalid_state("cannot replace the render target while a texture frame is acquired"));
1207            }
1208            if ring.depth() != state.ring.len() {
1209                return Err(Error::invalid_argument(
1210                    "texture_count must equal the ring depth the session attached with",
1211                ));
1212            }
1213            state.pending_retargets += 1;
1214        }
1215        let guard = RetargetGuard(Arc::clone(&shared));
1216        // The guard goes with the closure, whether the closure runs or the
1217        // resize drops it.
1218        self.resize_then(size, None, move |worker, size, scale_factor, outbox| {
1219            let _guard = guard;
1220            worker.set_ring(size, scale_factor, &ring, outbox)
1221        })
1222    }
1223
1224    /// Asks the session to render a frame, which shows the map commands sent
1225    /// before the call, except the changes that an open command group holds
1226    /// back, and the map's animations as they are at the call: demand each
1227    /// frame at the display's pace. A demand sent while the session attaches
1228    /// waits for it.
1229    ///
1230    /// Every demand finishes with one [`FrameResult`] that carries its token.
1231    /// A demand that isn't [`DemandMode::Force`](super::DemandMode::Force)
1232    /// replaces the demands with the same mode still on their way, which
1233    /// finish as [`FrameDisposition::Superseded`](super::FrameDisposition).
1234    /// While the session has no target, or a surface has no texture to
1235    /// render into, a demand finishes as
1236    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
1237    pub fn demand_frame(&self, demand: FrameDemand) -> Result<(), Error> {
1238        let shared = self.shared();
1239        with_unlocked_wakes(|| {
1240            let mut state = shared.state.lock();
1241            check_usable(&state)?;
1242            if !state.ring.is_empty() && state.ring.iter().all(|slot| slot.quarantined) {
1243                return Err(Error::invalid_state(
1244                    "every texture of the ring is quarantined: give the session new textures",
1245                ));
1246            }
1247            let (sequence, sample) =
1248                state.map.as_ref().map_or((0, 0), |map| (map.sent_sequence(), map.frame_demanded()));
1249            state.redraw_armed = true;
1250            worker::post(&shared.queue, move |worker, outbox| worker.demand(demand, sequence, sample, outbox));
1251            Ok(())
1252        })
1253    }
1254
1255    /// Takes the frame results that wait, oldest first. Fails with
1256    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once the session is
1257    /// released.
1258    pub fn drain_frame_results(&self) -> Result<Vec<FrameResult>, Error> {
1259        let mut state = self.shared().state.lock();
1260        if state.released {
1261            return Err(released());
1262        }
1263        state.frame_woken = false;
1264        Ok(std::mem::take(&mut state.results))
1265    }
1266
1267    /// Resizes the target, and the map with it, to `extent`'s size in
1268    /// logical pixels, and sets the map's scale factor to `extent`'s, such
1269    /// as when a window moves to a display of another density. The map keeps
1270    /// its tiles, and the renderer draws the next frame at the new scale
1271    /// factor. A later demand shows the new extent, and one sent before
1272    /// shows the old. An exported ring gets images of the new size, and the
1273    /// frames that the host holds keep theirs until it gives them back.
1274    ///
1275    /// Fails first as a call that sends work does once the session no
1276    /// longer takes work. Then fails with
1277    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a borrowed ring,
1278    /// which [`set_ring`](Self::set_ring) resizes, and with
1279    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an empty size,
1280    /// or a scale factor that isn't finite and positive.
1281    pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
1282        check_usable(&self.shared().state.lock())?;
1283        let capabilities = self.shared().capabilities;
1284        if capabilities.frame_acquisition && capabilities.export_kind.is_none() {
1285            return Err(Error::unsupported("a borrowed ring is sized by its owner: give it new textures instead"));
1286        }
1287        let LogicalExtent { size, scale_factor } = extent;
1288        if !scale_factor.is_finite() || scale_factor <= 0.0 {
1289            return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
1290        }
1291        self.resize_then(size, Some(scale_factor), |worker, size, scale_factor, outbox| {
1292            worker.resize(size, scale_factor, outbox).map(|()| None)
1293        })
1294    }
1295
1296    /// Sends a map command that resizes the map to `size`, at
1297    /// `scale_factor` or the session's when that is `None`, then runs
1298    /// `change` on the session's thread, which resizes or replaces the
1299    /// target.
1300    fn resize_then(
1301        &self,
1302        size: Size,
1303        scale_factor: Option<f64>,
1304        change: impl FnOnce(&mut Worker, Size, f64, &mut Outbox) -> Result<Pending, Error> + Send + 'static,
1305    ) -> Result<Completion<Applied>, Error> {
1306        if size.is_empty() {
1307            return Err(Error::invalid_argument("the target's size must not be empty"));
1308        }
1309        let shared = self.shared();
1310        with_unlocked_wakes(|| {
1311            let mut state = shared.state.lock();
1312            check_usable(&state)?;
1313            let map = state.map.clone().ok_or_else(|| Error::invalid_state("the render session has no map"))?;
1314            let scale_factor = scale_factor.unwrap_or(state.sent_scale_factor);
1315            state.sent_scale_factor = scale_factor;
1316            let (completion, resolver) = shared.completion();
1317            let work = state.register(resolver);
1318            // The work sent after waits for the resize to land, which it
1319            // does even when the map drops it.
1320            state.resizes_sent += 1;
1321            let landing = worker::ResizeLanding::new(shared.queue.clone());
1322            let sent =
1323                map.resize_for_session(size, scale_factor, shared.queue.clone(), move |worker, result, outbox| {
1324                    if let Some(resolver) = worker.take_work::<Applied>(work) {
1325                        match result.and_then(|applied| Ok((applied, change(worker, size, scale_factor, outbox)?))) {
1326                            // A replacement of a ring's textures completes
1327                            // once the host's reads of those it let go of end.
1328                            Ok((applied, pending)) => worker.settle_then(
1329                                pending,
1330                                move |outbox, settled| outbox.resolve(resolver, settled.map(|()| applied)),
1331                                outbox,
1332                            ),
1333                            Err(error) => outbox.resolve(resolver, Err(error)),
1334                        }
1335                    }
1336                    landing.land(worker, outbox);
1337                });
1338            if let Err(error) = sent {
1339                state.pending.remove(&work);
1340                return Err(error);
1341            }
1342            drop(state);
1343            Ok(completion)
1344        })
1345    }
1346
1347    /// Lets go of a surface session's surface, and keeps the rest of the
1348    /// session, such as when the platform takes the window away. The demands
1349    /// on their way, and later ones until
1350    /// [`set_surface`](Self::set_surface) gives the session a surface again,
1351    /// finish as [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
1352    /// Once the release completes, the session no longer uses the surface or
1353    /// the window it was made from, or a ring's textures, and no longer waits
1354    /// for the consumer sync that the textures were given back with: the host
1355    /// may reuse or destroy them. The session's thread polls that sync on its
1356    /// later turns, for a second at most, and logs a wait that runs out. The
1357    /// session keeps nothing of the released textures: one that a later ring
1358    /// has again starts fresh, even one that the host gave up.
1359    ///
1360    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for an
1361    /// offscreen session or an exported ring, whose targets are their own.
1362    pub fn release_target(&self) -> Result<Completion<()>, Error> {
1363        if self.shared().capabilities.export_kind.is_some() {
1364            return Err(Error::unsupported("an exported ring keeps its images until the session ends"));
1365        }
1366        let shared = Arc::clone(self.shared());
1367        let capabilities = shared.capabilities;
1368        if !capabilities.presentation && !capabilities.frame_acquisition {
1369            check_usable(&shared.state.lock())?;
1370            return Err(Error::unsupported("an offscreen session keeps its target"));
1371        }
1372        let guard = {
1373            let mut state = shared.state.lock();
1374            check_usable(&state)?;
1375            if state.acquired_frames != 0 {
1376                return Err(Error::invalid_state("release every acquired frame before the target"));
1377            }
1378            // No frame is acquired until the release runs: its textures go
1379            // with it.
1380            capabilities.frame_acquisition.then(|| {
1381                state.pending_retargets += 1;
1382                RetargetGuard(Arc::clone(&shared))
1383            })
1384        };
1385        self.settled_operation(move |worker, outbox| {
1386            let _guard = guard;
1387            worker.release_target(outbox).map(|pending| ((), pending))
1388        })
1389    }
1390
1391    /// Gives a surface session a new surface of `size` logical pixels, after
1392    /// [`release_target`](Self::release_target), or in place of the one it
1393    /// has, and resizes the map to it. Once the completion reports success,
1394    /// the session no longer uses the old surface. The session presents to
1395    /// it on its device: a window becomes a surface of the device's backend,
1396    /// and a `Surface::wgpu` must come from the instance of a WebGPU
1397    /// device. Where the backend made for the old surface can't present to
1398    /// the new one, as OpenGL ES's context can't to another window, the
1399    /// session makes its backend and renderer again.
1400    ///
1401    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
1402    /// empty size, with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for
1403    /// an offscreen session, and with
1404    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a window that is
1405    /// minimized or has no client area. Completes with
1406    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the session's
1407    /// device can't present to the surface in the format that the session
1408    /// renders in: attach a new session instead. Completes with
1409    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) when the window had no
1410    /// area to present to by then. The session then keeps the surface it had,
1411    /// at the new size.
1412    pub fn set_surface(&self, size: Size, surface: Surface) -> Result<Completion<Applied>, Error> {
1413        check_usable(&self.shared().state.lock())?;
1414        let capabilities = self.shared().capabilities;
1415        if capabilities.frame_acquisition {
1416            return Err(Error::unsupported("a borrowed texture session takes no native surface"));
1417        }
1418        if !capabilities.presentation {
1419            return Err(Error::unsupported("an offscreen session keeps its target"));
1420        }
1421        surface.check_area()?;
1422        let surface = SentSurface::new(surface, self.shared().id);
1423        self.resize_then(size, None, move |worker, size, scale_factor, outbox| {
1424            worker.set_surface(size, scale_factor, surface.receive()?, outbox).map(|()| None)
1425        })
1426    }
1427
1428    /// Ends the frame demands on their way, including those that wait for a
1429    /// map update and the demand of a still image, which finish as
1430    /// [`FrameDisposition::NoUpdate`](super::FrameDisposition), and completes
1431    /// once the work sent before it has run. A still image that still waits
1432    /// gets a new demand once the barrier ran.
1433    pub fn barrier(&self) -> Result<Completion<()>, Error> {
1434        self.operation(|worker, outbox| {
1435            worker.barrier(outbox);
1436            Ok(())
1437        })
1438    }
1439
1440    /// Frees memory that the renderer can rebuild, such as caches.
1441    pub fn reduce_memory_use(&self) -> Result<Completion<()>, Error> {
1442        self.operation(|worker, _| worker.reduce_memory_use())
1443    }
1444
1445    /// Clears what the renderer holds, such as loaded tiles, so that the
1446    /// next frame loads and draws the map again.
1447    pub fn clear_data(&self) -> Result<Completion<()>, Error> {
1448        self.operation(Worker::clear_data)
1449    }
1450
1451    /// Logs the renderer's sources and tiles.
1452    pub fn dump_debug_logs(&self) -> Result<Completion<()>, Error> {
1453        self.operation(|worker, _| worker.dump_debug_logs())
1454    }
1455
1456    /// The pixels of the last frame that an offscreen session rendered:
1457    /// premultiplied RGBA, in rows from top to bottom, at the target's size
1458    /// in pixels.
1459    ///
1460    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
1461    /// surface session. Completes with
1462    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) when the session
1463    /// hasn't rendered a frame since it attached or resized.
1464    pub fn read_texture(&self) -> Result<Completion<PremultipliedImage>, Error> {
1465        check_usable(&self.shared().state.lock())?;
1466        if !self.shared().capabilities.readback {
1467            return Err(Error::unsupported("a surface session can't read its frames back"));
1468        }
1469        self.operation(|worker, _| worker.read_texture())
1470    }
1471
1472    /// The features that the session drew in an area of the screen, in its
1473    /// last frame. A feature that several layers draw appears once for each.
1474    /// The topmost layer's features come first, and the bottom layer's last.
1475    /// A box covers only its part inside the target, so one past every edge
1476    /// covers the whole target.
1477    ///
1478    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
1479    /// point that isn't finite or a line string without points.
1480    pub fn query_rendered_features(
1481        &self,
1482        geometry: RenderedQueryGeometry,
1483        options: RenderedQueryOptions,
1484    ) -> Result<Completion<Vec<Feature>>, Error> {
1485        geometry.points()?;
1486        self.operation(move |worker, _| match geometry.within(worker.size()).map(|geometry| geometry.points()) {
1487            Some(points) => worker.renderer()?.query_rendered_features(&points?, &options),
1488            None => Ok(Vec::new()),
1489        })
1490    }
1491
1492    /// The features of the source `source_id` in the tiles that it loaded
1493    /// for the current view. A source loads tiles only while a visible layer
1494    /// uses it.
1495    ///
1496    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
1497    /// empty `source_id`.
1498    pub fn query_source_features(
1499        &self,
1500        source_id: impl Into<String>,
1501        options: SourceQueryOptions,
1502    ) -> Result<Completion<Vec<Feature>>, Error> {
1503        let source_id = source_id_of(source_id)?;
1504        self.operation(move |worker, _| worker.renderer()?.query_source_features(&source_id, &options))
1505    }
1506
1507    /// The clusters and points that a cluster of a clustered GeoJSON source
1508    /// splits into at the next zoom level. `cluster_id` is a cluster
1509    /// feature's `cluster_id` property.
1510    ///
1511    /// The query reads the source as the session's most recent render
1512    /// attempt had it. A cluster ID belongs to one version of the source's
1513    /// data, so query the features again after the data changes.
1514    ///
1515    /// Completes with [`ErrorKind::NotFound`](mln_util::ErrorKind) when that
1516    /// render had no source `source_id`, or the source has no cluster
1517    /// `cluster_id`, and with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind)
1518    /// when the source isn't a clustered GeoJSON source.
1519    pub fn cluster_children(
1520        &self,
1521        source_id: impl Into<String>,
1522        cluster_id: u32,
1523    ) -> Result<Completion<Vec<feature::Feature<f64>>>, Error> {
1524        let source_id = source_id_of(source_id)?;
1525        self.operation(move |worker, _| worker.cluster(&source_id, cluster_id, |_, children| Ok(children)))
1526    }
1527
1528    /// The points in a cluster of a clustered GeoJSON source: it skips the
1529    /// first `offset`, then holds up to `limit`. It fails as
1530    /// [`cluster_children`](Self::cluster_children) does.
1531    pub fn cluster_leaves(
1532        &self,
1533        source_id: impl Into<String>,
1534        cluster_id: u32,
1535        limit: u32,
1536        offset: u32,
1537    ) -> Result<Completion<Vec<feature::Feature<f64>>>, Error> {
1538        let source_id = source_id_of(source_id)?;
1539        self.operation(move |worker, _| {
1540            worker.cluster(&source_id, cluster_id, |index, _| index.get_leaves(cluster_id, limit, offset))
1541        })
1542    }
1543
1544    /// The zoom level at which a cluster of a clustered GeoJSON source splits
1545    /// into two or more clusters or points. It fails as
1546    /// [`cluster_children`](Self::cluster_children) does.
1547    pub fn cluster_expansion_zoom(
1548        &self,
1549        source_id: impl Into<String>,
1550        cluster_id: u32,
1551    ) -> Result<Completion<u8>, Error> {
1552        let source_id = source_id_of(source_id)?;
1553        self.operation(move |worker, _| {
1554            worker.cluster(&source_id, cluster_id, |index, _| index.get_cluster_expansion_zoom(cluster_id))
1555        })
1556    }
1557
1558    /// Detaches the session from its map and frees its graphics objects. The
1559    /// demands on their way finish as
1560    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once
1561    /// the detach completes, another session can attach to the map.
1562    pub fn detach(&self) -> Result<Completion<()>, Error> {
1563        let shared = self.shared();
1564        with_unlocked_wakes(|| {
1565            let mut state = shared.state.lock();
1566            if !matches!(state.lifecycle, RenderSessionState::Failed) {
1567                check_usable(&state)?;
1568            } else if state.released {
1569                return Err(released());
1570            }
1571            if state.acquired_frames != 0 {
1572                return Err(Error::invalid_state("release every acquired frame before the session detaches"));
1573            }
1574            let (completion, resolver) = shared.completion();
1575            state.detach_waiters.push(resolver);
1576            shared.start_detach(&mut state);
1577            Ok(completion)
1578        })
1579    }
1580
1581    /// Stops the session at once, without its pending graphics work: that
1582    /// work completes with [`ErrorKind::TargetLost`](mln_util::ErrorKind)
1583    /// before this returns, and the demands on their way finish as
1584    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once it
1585    /// returns, the session renders no more, and another session can attach
1586    /// to the map. Release the session afterward.
1587    ///
1588    /// Returns how many graphics objects the session keeps until the
1589    /// process exits. A caller-driven session abandoned on the thread that
1590    /// services it lets go of them there, at its next service or when its
1591    /// [`DriverWork`] drops, and keeps none. Abandoned on another thread, it
1592    /// keeps them, since only that thread may free them, and logs a warning.
1593    ///
1594    /// It waits for a core worker's driver call on another thread, such as a
1595    /// frame that it renders. Fails with
1596    /// [`ErrorKind::Busy`](mln_util::ErrorKind) inside a driver call on the
1597    /// session's own thread, such as from a completion that the session
1598    /// delivers, and while a caller-driven session's service runs on another
1599    /// thread. Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind)
1600    /// once the session is detached, abandoned or released.
1601    pub fn abandon(&self) -> Result<u32, Error> {
1602        self.shared().abandon(Abandoner::Host)
1603    }
1604
1605    /// Abandons the session as [`abandon`](Self::abandon) does, but makes no
1606    /// graphics call: the session keeps its graphics objects until the
1607    /// process exits. Returns how many it keeps, such as its renderer and
1608    /// the backend it draws with.
1609    ///
1610    /// This is for a host whose shutdown may already have destroyed the
1611    /// graphics objects behind the session.
1612    pub fn abandon_keeping_graphics(&self) -> Result<u32, Error> {
1613        with_unlocked_wakes(|| self.shared().abandon_locked(Abandoner::Host, true))
1614    }
1615
1616    /// Releases the session, detaching it first when it is attached. The
1617    /// completion reports when the session has let go of its map and its
1618    /// graphics objects, and nothing waits for its thread to end after
1619    /// that. Every call on the session fails with
1620    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) after.
1621    ///
1622    /// A caller-driven session detaches at the host's next service, so keep
1623    /// servicing it until the release completes. One that isn't attached,
1624    /// such as while it attaches or after it failed, is abandoned instead,
1625    /// and so is one whose map is released before that service.
1626    pub fn release(&self) -> Result<Completion<()>, Error> {
1627        {
1628            let state = self.shared().state.lock();
1629            let live = matches!(state.lifecycle, RenderSessionState::Attaching | RenderSessionState::Attached);
1630            if live && !state.released && state.acquired_frames != 0 {
1631                return Err(Error::invalid_state("release every acquired frame before the session is released"));
1632            }
1633        }
1634        let (completion, resolver) = self.shared().completion();
1635        self.shared().dispose(Some(resolver))?;
1636        self.detach_thread();
1637        Ok(completion)
1638    }
1639
1640    /// Releases the session in any state, without waiting, and nothing waits
1641    /// for its thread to end. Dropping the last handle does the same, then
1642    /// waits for the thread.
1643    pub fn dispose(&self) -> Result<(), Error> {
1644        self.shared().dispose(None)?;
1645        self.detach_thread();
1646        Ok(())
1647    }
1648
1649    /// Releases the session in any state, without waiting and without a
1650    /// graphics call past the one in progress. A session that hasn't ended
1651    /// is abandoned, keeping its graphics objects until the process exits,
1652    /// as [`abandon_keeping_graphics`](Self::abandon_keeping_graphics) does.
1653    /// Nothing waits for its thread to end.
1654    pub fn dispose_keeping_graphics(&self) -> Result<(), Error> {
1655        self.shared().dispose_keeping_graphics()?;
1656        self.detach_thread();
1657        Ok(())
1658    }
1659
1660    /// Leaves a core worker's thread to end alone, for a release or
1661    /// disposal, which don't wait for it.
1662    fn detach_thread(&self) {
1663        if let Some(thread) = &self.handle.thread_end {
1664            thread.detach();
1665        }
1666    }
1667}
1668
1669/// Counts a ring replacement or release on its way until it runs, or never
1670/// will.
1671struct RetargetGuard(Arc<SessionShared>);
1672
1673impl Drop for RetargetGuard {
1674    fn drop(&mut self) {
1675        let mut state = self.0.state.lock();
1676        state.pending_retargets = state.pending_retargets.saturating_sub(1);
1677    }
1678}
1679
1680/// A frame of a borrowed ring that the host acquired, until it gives it
1681/// back. Dropping it gives it back as [`release`](Self::release) with
1682/// [`SyncKind::CpuComplete`] does.
1683pub struct AcquiredFrame {
1684    shared: Arc<SessionShared>,
1685    /// Dropped after the frame is given back.
1686    thread_end: ThreadEnd,
1687    slot: usize,
1688    frame: Published,
1689    done: bool,
1690}
1691
1692impl std::fmt::Debug for AcquiredFrame {
1693    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1694        f.debug_struct("AcquiredFrame").field("slot", &self.slot).field("frame", &self.frame).finish_non_exhaustive()
1695    }
1696}
1697
1698impl AcquiredFrame {
1699    /// The index of the frame's texture in the ring.
1700    #[must_use]
1701    pub fn slot(&self) -> usize {
1702        self.slot
1703    }
1704
1705    /// The result of the demand that rendered the frame.
1706    #[must_use]
1707    pub fn result(&self) -> &FrameResult {
1708        &self.frame.result
1709    }
1710
1711    /// What to wait for before reading the frame's texture. The object it
1712    /// names is the session's, and stays valid until the frame is given
1713    /// back.
1714    #[must_use]
1715    pub fn producer_sync(&self) -> GpuSync {
1716        self.frame.sync
1717    }
1718
1719    /// The host's texture that holds the frame.
1720    #[must_use]
1721    pub fn texture(&self) -> Option<&FrameTexture> {
1722        self.frame.texture.as_ref()
1723    }
1724
1725    /// Whether [`release`](Self::release) takes a sync of `kind`.
1726    #[must_use]
1727    pub fn accepts(&self, kind: SyncKind) -> bool {
1728        self.shared.capabilities.consumer_sync_kinds.contains(kind)
1729    }
1730
1731    /// Opens a view of the frame, which keeps the frame's texture and sync
1732    /// objects in place until the view drops: an
1733    /// [`abandon`](RenderSession::abandon) fails while one is open, and a
1734    /// dispose of the session keeps them until the last view ends. Keep the
1735    /// frame until its views end.
1736    ///
1737    /// Fails with [`ErrorKind::TargetLost`](mln_util::ErrorKind) once the
1738    /// session can no longer render.
1739    pub fn view(&self) -> Result<FrameView, Error> {
1740        let mut state = self.shared.state.lock();
1741        if !matches!(
1742            state.lifecycle,
1743            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1744        ) {
1745            return Err(Error::target_lost("the render session failed, or was detached, abandoned, or disposed"));
1746        }
1747        state.views += 1;
1748        Ok(FrameView { shared: Arc::clone(&self.shared), _thread_end: self.thread_end.clone() })
1749    }
1750
1751    /// Whether the session can still render: the frame's objects stay valid
1752    /// until it ends.
1753    #[must_use]
1754    pub fn session_live(&self) -> bool {
1755        matches!(
1756            self.shared.state.lock().lifecycle,
1757            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1758        )
1759    }
1760
1761    /// Gives the frame back once the host's reads of its texture reach
1762    /// `consumer`: the session waits for it before it renders into the
1763    /// texture again, and takes the sync file or GL fence that it names.
1764    ///
1765    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind), handing
1766    /// back the frame and `consumer`, for a kind that the session's
1767    /// [`consumer_sync_kinds`](RenderSessionCapabilities::consumer_sync_kinds)
1768    /// lacks.
1769    #[expect(
1770        clippy::result_large_err,
1771        reason = "the error hands back the frame and the consumer's sync, so that the caller can release it another way"
1772    )]
1773    pub fn release(mut self, consumer: ConsumerSync) -> Result<(), (AcquiredFrame, ConsumerSync, Error)> {
1774        if !self.shared.capabilities.consumer_sync_kinds.contains(consumer.sync.kind) {
1775            return Err((self, consumer, Error::unsupported("render backend does not support this gpu sync kind")));
1776        }
1777        self.done = true;
1778        give_back(&self.shared, self.slot, Some(consumer));
1779        Ok(())
1780    }
1781
1782    /// Gives the frame up without saying when the host's reads end: the
1783    /// session never renders into its texture again, even when
1784    /// [`set_ring`](RenderSession::set_ring) gives the ring the texture
1785    /// again, until a [`release_target`](RenderSession::release_target) of
1786    /// the ring.
1787    pub fn discard(mut self) {
1788        self.done = true;
1789        give_back(&self.shared, self.slot, None);
1790    }
1791}
1792
1793/// A view of an acquired frame, which [`AcquiredFrame::view`] opens, until
1794/// it drops.
1795pub struct FrameView {
1796    shared: Arc<SessionShared>,
1797    /// Dropped after the view ends.
1798    _thread_end: ThreadEnd,
1799}
1800
1801impl std::fmt::Debug for FrameView {
1802    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1803        f.debug_struct("FrameView").finish_non_exhaustive()
1804    }
1805}
1806
1807impl Drop for FrameView {
1808    fn drop(&mut self) {
1809        let release = {
1810            let mut state = self.shared.state.lock();
1811            state.views = state.views.saturating_sub(1);
1812            state.views == 0 && std::mem::take(&mut state.viewed_teardown)
1813        };
1814        if release {
1815            worker::post(&self.shared.queue, |worker, _| worker.release_viewed());
1816        }
1817    }
1818}
1819
1820impl Drop for AcquiredFrame {
1821    fn drop(&mut self) {
1822        if !self.done {
1823            give_back(&self.shared, self.slot, Some(ConsumerSync::of(GpuSync::of(SyncKind::CpuComplete))));
1824        }
1825    }
1826}
1827
1828/// Gives the ring's `slot` back to the session, with the host's `consumer`
1829/// sync, or discarded without one.
1830fn give_back(shared: &Arc<SessionShared>, slot: usize, consumer: Option<ConsumerSync>) {
1831    with_unlocked_wakes(|| {
1832        let mut state = shared.state.lock();
1833        state.acquired_frames = state.acquired_frames.saturating_sub(1);
1834        let live = matches!(
1835            state.lifecycle,
1836            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1837        );
1838        if !live {
1839            if let Some(entry) = state.ring.get_mut(slot) {
1840                entry.acquired = false;
1841                // The host's GPU may still read a texture whose wait never
1842                // ran.
1843                entry.quarantined |=
1844                    consumer.as_ref().is_none_or(|consumer| consumer.sync.kind != SyncKind::CpuComplete);
1845            }
1846            // A sync file that no backend waits on closes with `consumer`.
1847            return;
1848        }
1849        if let Some(sync) = consumer {
1850            worker::post(&shared.queue, move |worker, outbox| worker.release_slot(slot, sync, outbox));
1851        } else {
1852            if let Some(entry) = state.ring.get_mut(slot) {
1853                entry.acquired = false;
1854                entry.quarantined = !entry.retired;
1855                entry.retired = false;
1856            }
1857            worker::post(&shared.queue, move |worker, outbox| worker.discard_slot(slot, outbox));
1858        }
1859    });
1860}
1861
1862fn source_id_of(source_id: impl Into<String>) -> Result<String, Error> {
1863    let source_id = source_id.into();
1864    if source_id.is_empty() {
1865        return Err(Error::invalid_argument("the source ID must not be empty"));
1866    }
1867    Ok(source_id)
1868}
1869
1870// Handles cross threads; the renderer never leaves its own.
1871const _: () = {
1872    const fn assert_send_sync<T: Send + Sync>() {}
1873    assert_send_sync::<RenderSession>();
1874};