Skip to main content

oa/runtime/
event.rs

1use std::sync::{Arc, Mutex};
2
3use std::{fmt, time::Duration};
4
5use crate::Result;
6
7use super::{
8	Device, RetirementTicket, TimestampPair,
9	device::logical::video::{DecodeStatus, EncodeReceipt},
10};
11
12/// Exact completion point for work submitted to an OA runtime.
13///
14/// Dropping an event never waits. The originating runtime's retirement service
15/// keeps submitted resources and their Vulkan device alive through completion.
16#[derive(Clone)]
17#[must_use]
18pub struct Event {
19	device: Arc<Device>,
20	epoch: u64,
21	retirement: RetirementTicket,
22	timing: Option<TimestampPair>,
23	timing_start: Option<TimestampPair>,
24	decode_statuses: Option<Arc<Mutex<Vec<Arc<DecodeStatus>>>>>,
25	encode_receipts: Option<Arc<Mutex<Vec<Arc<EncodeReceipt>>>>>,
26}
27
28impl Event {
29	pub(crate) fn same_as(&self, other: &Self) -> bool {
30		self.epoch == other.epoch && self.device.same_as(&other.device)
31	}
32
33	pub(crate) fn follows_or_equals(&self, other: &Self) -> bool {
34		self.epoch >= other.epoch && self.device.same_as(&other.device)
35	}
36
37	pub(super) const fn new(
38		device: Arc<Device>,
39		epoch: u64,
40		retirement: RetirementTicket,
41		timing: Option<TimestampPair>,
42	) -> Self {
43		Self {
44			device,
45			epoch,
46			retirement,
47			timing,
48			timing_start: None,
49			decode_statuses: None,
50			encode_receipts: None,
51		}
52	}
53
54	/// Runtime supplies the first chunk of the same ordered timed plan. Keep
55	/// its query pool alive while completion still names the final submission.
56	pub(super) fn set_timing_start(&mut self, first: &Self) {
57		self.timing_start = first.timing.clone();
58	}
59
60	pub(super) fn set_decode_statuses(&mut self, statuses: Vec<Arc<DecodeStatus>>) {
61		if !statuses.is_empty() {
62			self.decode_statuses = Some(Arc::new(Mutex::new(statuses)));
63		}
64	}
65
66	pub(super) fn set_encode_receipts(&mut self, receipts: Vec<Arc<EncodeReceipt>>) {
67		if !receipts.is_empty() {
68			self.encode_receipts = Some(Arc::new(Mutex::new(receipts)));
69		}
70	}
71
72	/// Encoded-packet receipts collected at this event's completion. The
73	/// event first verifies feedback status, so a returned packet is safe to
74	/// materialize from its slot's bitstream.
75	pub(super) fn encode_receipts(&self) -> Vec<Arc<EncodeReceipt>> {
76		self
77			.encode_receipts
78			.as_ref()
79			.map(|receipts| {
80				receipts
81					.lock()
82					.unwrap_or_else(|poisoned| poisoned.into_inner())
83					.clone()
84			})
85			.unwrap_or_default()
86	}
87
88	fn verify_encode_receipts(&self) -> Result<()> {
89		if let Some(receipts) = &self.encode_receipts {
90			let receipts = receipts
91				.lock()
92				.unwrap_or_else(|poisoned| poisoned.into_inner());
93			for receipt in receipts.iter() {
94				receipt.verify()?;
95			}
96		}
97		Ok(())
98	}
99
100	fn verify_decode_statuses(&self) -> Result<()> {
101		if let Some(statuses) = &self.decode_statuses {
102			let mut statuses = statuses
103				.lock()
104				.unwrap_or_else(|poisoned| poisoned.into_inner());
105			for status in statuses.iter() {
106				status.verify()?;
107			}
108			statuses.clear();
109		}
110		Ok(())
111	}
112
113	pub(crate) const fn epoch(&self) -> u64 {
114		self.epoch
115	}
116
117	pub(in crate::runtime) fn comes_from(&self, device: &Arc<Device>) -> bool {
118		self.device.same_as(device)
119	}
120
121	pub(in crate::runtime) fn retain_until_complete<T>(&self, value: T)
122	where
123		T: Send + 'static,
124	{
125		self.retirement.retain_until_complete(value);
126	}
127
128	/// Return whether this exact submission point has completed.
129	///
130	/// # Errors
131	///
132	/// Returns an error when retirement or replayed decode has failed, or
133	/// when Vulkan cannot query the originating timeline.
134	pub fn is_complete(&self) -> Result<bool> {
135		self.retirement.check_failure()?;
136		let complete = self.device.is_complete(self.epoch)?;
137		self.retirement.check_failure()?;
138		if complete {
139			self.verify_decode_statuses()?;
140			self.verify_encode_receipts()?;
141		}
142		Ok(complete)
143	}
144
145	/// Wait until this exact submission point completes and its submitted command
146	/// buffer has been retired on the host.
147	///
148	/// # Errors
149	///
150	/// Returns an error when the exact timeline wait, submission retirement,
151	/// or any replayed video decode fails.
152	pub fn wait(&self) -> Result<()> {
153		// The worker performs the exact device wait and retains every resource.
154		// Observe its outcome instead of issuing a second Vulkan wait, including
155		// after the execution domain has entered terminal failure.
156		self.retirement.wait()?;
157		self.verify_decode_statuses()?;
158		self.verify_encode_receipts()
159	}
160
161	/// Materialize every encoded packet captured by this event's plan.
162	///
163	/// The event waits for completion first, so returned packets are
164	/// guaranteed complete feedback plus a readable bitstream. Plans without
165	/// recorded encode nodes return an empty list.
166	///
167	/// # Errors
168	///
169	/// Returns an error when the wait fails, feedback did not complete, or a
170	/// packet cannot be read back from its slot.
171	pub fn encoded_packets(&self) -> Result<Vec<crate::video::EncodedVideoPacket>> {
172		self.wait()?;
173		self
174			.encode_receipts()
175			.iter()
176			.map(|receipt| receipt.packet())
177			.collect()
178	}
179
180	/// Return the complete device duration without waiting.
181	///
182	/// Returns `Ok(None)` while this event is incomplete.
183	///
184	/// # Errors
185	///
186	/// Returns an error when this event was not produced by a timed submission,
187	/// completion cannot be queried, or Vulkan timestamp readback fails.
188	pub fn try_device_duration(&self) -> Result<Option<Duration>> {
189		let Some(timing) = &self.timing else {
190			return Err(crate::Error::failed_precondition(
191				"event was not produced by a timed submission",
192			));
193		};
194		if !self.is_complete()? {
195			return Ok(None);
196		}
197		Ok(Some(self.timing_start.as_ref().map_or_else(
198			|| timing.duration(),
199			|start| start.duration_until(timing),
200		)?))
201	}
202
203	/// Wait for this event and return its complete device duration.
204	///
205	/// # Errors
206	///
207	/// Returns an error when this event was not produced by a timed submission,
208	/// completion waiting fails, or Vulkan timestamp readback fails.
209	pub fn device_duration(&self) -> Result<Duration> {
210		let Some(timing) = &self.timing else {
211			return Err(crate::Error::failed_precondition(
212				"event was not produced by a timed submission",
213			));
214		};
215		self.wait()?;
216		self
217			.timing_start
218			.as_ref()
219			.map_or_else(|| timing.duration(), |start| start.duration_until(timing))
220	}
221}
222
223impl fmt::Debug for Event {
224	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
225		formatter
226			.debug_struct("Event")
227			.field("epoch", &self.epoch)
228			.finish_non_exhaustive()
229	}
230}
231
232#[cfg(test)]
233#[path = "../../../../test/rs/runtime/event_unit.rs"]
234mod tests;