Skip to main content

mln_runtime/render/session/
acquired.rs

1use std::sync::Arc;
2
3use mln_style::error::Error;
4
5use super::shared::{Published, SessionShared, with_unlocked_wakes};
6use super::{RenderSessionState, ThreadEnd};
7use crate::render::frame::FrameResult;
8use crate::render::target::{ConsumerSync, FrameTexture, GpuSync, SyncKind};
9use crate::render::worker;
10
11/// A frame of a borrowed ring that the host acquired, until it gives it
12/// back. Dropping it gives it back as [`release`](Self::release) with
13/// [`SyncKind::CpuComplete`] does.
14pub struct AcquiredFrame {
15    pub(super) shared: Arc<SessionShared>,
16    /// Dropped after the frame is given back.
17    pub(super) thread_end: ThreadEnd,
18    pub(super) slot: usize,
19    pub(super) frame: Published,
20    pub(super) done: bool,
21}
22
23impl std::fmt::Debug for AcquiredFrame {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        f.debug_struct("AcquiredFrame").field("slot", &self.slot).field("frame", &self.frame).finish_non_exhaustive()
26    }
27}
28
29impl AcquiredFrame {
30    /// The index of the frame's texture in the ring.
31    #[must_use]
32    pub fn slot(&self) -> usize {
33        self.slot
34    }
35
36    /// The result of the demand that rendered the frame.
37    #[must_use]
38    pub fn result(&self) -> &FrameResult {
39        &self.frame.result
40    }
41
42    /// What to wait for before reading the frame's texture. The object it
43    /// names is the session's, and stays valid until the frame is given
44    /// back.
45    #[must_use]
46    pub fn producer_sync(&self) -> GpuSync {
47        self.frame.sync
48    }
49
50    /// The host's texture that holds the frame.
51    #[must_use]
52    pub fn texture(&self) -> Option<&FrameTexture> {
53        self.frame.texture.as_ref()
54    }
55
56    /// Whether [`release`](Self::release) takes a sync of `kind`.
57    #[must_use]
58    pub fn accepts(&self, kind: SyncKind) -> bool {
59        self.shared.capabilities.consumer_sync_kinds.contains(kind)
60    }
61
62    /// Opens a view of the frame, which keeps the frame's texture and sync
63    /// objects in place until the view drops: an
64    /// [`abandon`](super::RenderSession::abandon) fails while one is open, and a
65    /// dispose of the session keeps them until the last view ends. Keep the
66    /// frame until its views end.
67    ///
68    /// Fails with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind) once the
69    /// session can no longer render.
70    pub fn view(&self) -> Result<FrameView, Error> {
71        let mut state = self.shared.state.lock();
72        if !matches!(
73            state.lifecycle,
74            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
75        ) {
76            return Err(Error::target_lost("the render session failed, or was detached, abandoned, or disposed"));
77        }
78        state.views += 1;
79        Ok(FrameView { shared: Arc::clone(&self.shared), _thread_end: self.thread_end.clone() })
80    }
81
82    /// Whether the session can still render: the frame's objects stay valid
83    /// until it ends.
84    #[must_use]
85    pub fn session_live(&self) -> bool {
86        matches!(
87            self.shared.state.lock().lifecycle,
88            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
89        )
90    }
91
92    /// Gives the frame back once the host's reads of its texture reach
93    /// `consumer`: the session waits for it before it renders into the
94    /// texture again, and takes the sync file or GL fence that it names.
95    ///
96    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind), handing
97    /// back the frame and `consumer`, for a kind that the session's
98    /// [`consumer_sync_kinds`](super::RenderSessionCapabilities::consumer_sync_kinds)
99    /// lacks.
100    #[expect(
101        clippy::result_large_err,
102        reason = "the error hands back the frame and the consumer's sync, so that the caller can release it another way"
103    )]
104    pub fn release(mut self, consumer: ConsumerSync) -> Result<(), (AcquiredFrame, ConsumerSync, Error)> {
105        if !self.shared.capabilities.consumer_sync_kinds.contains(consumer.sync.kind) {
106            return Err((self, consumer, Error::unsupported("render backend does not support this gpu sync kind")));
107        }
108        self.done = true;
109        give_back(&self.shared, self.slot, Some(consumer));
110        Ok(())
111    }
112
113    /// Gives the frame up without saying when the host's reads end: the
114    /// session never renders into its texture again, even when
115    /// [`set_ring`](super::RenderSession::set_ring) gives the ring the texture
116    /// again, until a [`release_target`](super::RenderSession::release_target) of
117    /// the ring.
118    pub fn discard(mut self) {
119        self.done = true;
120        give_back(&self.shared, self.slot, None);
121    }
122}
123
124/// A view of an acquired frame, which [`AcquiredFrame::view`] opens, until
125/// it drops.
126pub struct FrameView {
127    shared: Arc<SessionShared>,
128    /// Dropped after the view ends.
129    _thread_end: ThreadEnd,
130}
131
132impl std::fmt::Debug for FrameView {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        f.debug_struct("FrameView").finish_non_exhaustive()
135    }
136}
137
138impl Drop for FrameView {
139    fn drop(&mut self) {
140        let release = {
141            let mut state = self.shared.state.lock();
142            state.views = state.views.saturating_sub(1);
143            state.views == 0 && std::mem::take(&mut state.viewed_teardown)
144        };
145        if release {
146            worker::post(&self.shared.queue, |worker, _| worker.release_viewed());
147        }
148    }
149}
150
151impl Drop for AcquiredFrame {
152    fn drop(&mut self) {
153        if !self.done {
154            give_back(&self.shared, self.slot, Some(ConsumerSync::of(GpuSync::of(SyncKind::CpuComplete))));
155        }
156    }
157}
158
159/// Gives the ring's `slot` back to the session, with the host's `consumer`
160/// sync, or discarded without one.
161fn give_back(shared: &Arc<SessionShared>, slot: usize, consumer: Option<ConsumerSync>) {
162    with_unlocked_wakes(|| {
163        let mut state = shared.state.lock();
164        state.acquired_frames = state.acquired_frames.saturating_sub(1);
165        let live = matches!(
166            state.lifecycle,
167            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
168        );
169        if !live {
170            if let Some(entry) = state.ring.get_mut(slot) {
171                entry.acquired = false;
172                // The host's GPU may still read a texture whose wait never
173                // ran.
174                entry.quarantined |=
175                    consumer.as_ref().is_none_or(|consumer| consumer.sync.kind != SyncKind::CpuComplete);
176            }
177            // A sync file that no backend waits on closes with `consumer`.
178            return;
179        }
180        if let Some(sync) = consumer {
181            worker::post(&shared.queue, move |worker, outbox| worker.release_slot(slot, sync, outbox));
182        } else {
183            if let Some(entry) = state.ring.get_mut(slot) {
184                entry.acquired = false;
185                entry.quarantined = !entry.retired;
186                entry.retired = false;
187            }
188            worker::post(&shared.queue, move |worker, outbox| worker.discard_slot(slot, outbox));
189        }
190    });
191}