1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use alpha2_eval::FrameNeed;
use alpha2_media::SourceId;
use alpha2_render::{CacheEligibility, RenderCacheKey, RenderSize, RenderedTexture};
use alpha2_time::MediaTime;
use crate::schedule::frame_times;
use crate::{
EngineError, EngineProject, FrameProvider, FrameRenderer, MissingFramePolicy, QualityProfile,
};
const MAX_PREFETCH_FRAMES: u32 = 120;
/// Result of one real-time presentation attempt; `I` is [`FrameRenderer::Image`].
#[derive(Debug)]
pub struct PlaybackFrame<'a, I = RenderedTexture> {
/// Timeline time requested by the host clock.
pub requested_time: MediaTime,
/// Timeline time of the returned texture, absent before the first success.
pub presented_time: Option<MediaTime>,
/// Current or held picture. It remains owned by the player.
pub texture: Option<&'a I>,
/// Sources unavailable for the requested time.
pub missing_sources: Vec<SourceId>,
/// Whether the texture is the previous successful frame.
pub repeated: bool,
/// Whether the output equals the last one returned, so nothing was rendered and the host
/// need not present it again.
pub unchanged: bool,
}
/// Render size, frame-graph cache key and renderer content epoch of the last returned texture.
type ShownKey = (RenderSize, RenderCacheKey, u64);
/// Stateful real-time runner holding the last picture drawn. `I` is [`FrameRenderer::Image`]: a
/// [`RenderedTexture`] on the GPU or an `Arc<CpuImage>` on the [`alpha2_render::CpuRenderer`].
///
/// Defaults to [`MissingFramePolicy::HoldPrevious`]; see [`Player::with_missing_frame_policy`].
#[derive(Debug)]
pub struct Player<I = RenderedTexture> {
quality: QualityProfile,
prefetch_frames: u32,
missing_frame_policy: MissingFramePolicy,
last_frame: Option<(MediaTime, I)>,
/// What `last_frame` shows, when its key names everything it depends on.
shown: Option<ShownKey>,
}
impl<I> Default for Player<I> {
fn default() -> Self {
Self {
quality: QualityProfile::preview(),
prefetch_frames: 2,
missing_frame_policy: MissingFramePolicy::HoldPrevious,
last_frame: None,
shown: None,
}
}
}
impl<I> Player<I> {
/// The size frames of `project` render at, for preparing captions.
///
/// # Errors
/// Returns an error when the quality profile cannot size the project.
pub fn render_size(
&self,
project: &EngineProject,
) -> Result<alpha2_render::RenderSize, EngineError> {
self.quality.render_size(&project.project().settings)
}
/// Creates a player with explicit runtime quality.
///
/// # Errors
/// Returns [`EngineError::InvalidQualityProfile`] for invalid controls.
pub fn new(quality: QualityProfile) -> Result<Self, EngineError> {
quality.validate()?;
Ok(Self {
quality,
..Self::default()
})
}
/// Sets how many future frame boundaries prefetch requests include, clamped to 120.
#[must_use]
pub const fn with_prefetch_frames(mut self, frames: u32) -> Self {
self.prefetch_frames = if frames > MAX_PREFETCH_FRAMES {
MAX_PREFETCH_FRAMES
} else {
frames
};
self
}
/// How many future frame boundaries prefetch requests include.
#[must_use]
pub const fn prefetch_frames(&self) -> u32 {
self.prefetch_frames
}
/// Returns the active quality profile.
#[must_use]
pub const fn quality(&self) -> QualityProfile {
self.quality
}
/// Sets what [`Player::render_at`] returns while source frames are missing.
///
/// [`MissingFramePolicy::HoldPrevious`] repeats the last successful texture;
/// [`MissingFramePolicy::Wait`] withholds it so the host can show a loading state. The held
/// frame is retained either way.
#[must_use]
pub const fn with_missing_frame_policy(mut self, policy: MissingFramePolicy) -> Self {
self.missing_frame_policy = policy;
self
}
/// Returns the policy used when source frames are unavailable.
#[must_use]
pub const fn missing_frame_policy(&self) -> MissingFramePolicy {
self.missing_frame_policy
}
/// Collects deduplicated decode requests for the current and future frames.
///
/// # Errors
/// Returns evaluation or timeline overflow errors.
pub fn prefetch_needs(
&self,
project: &EngineProject,
time: MediaTime,
) -> Result<Vec<FrameNeed>, EngineError> {
let rate = project.project().settings.frame_rate;
let first = rate
.frame_at_or_before(time)
.ok_or(EngineError::OutOfRange)?;
let mut needs = Vec::new();
for (_, frame_time) in
frame_times(rate, first, self.prefetch_frames.saturating_add(1), None)?
{
for need in project.frame_needs(frame_time)? {
if !needs.iter().any(|existing: &FrameNeed| {
existing.source_id == need.source_id && existing.media_time == need.media_time
}) {
needs.push(need);
}
}
}
Ok(needs)
}
/// Evaluates and attempts to present the host clock's current frame.
///
/// With inputs missing, the last successful texture is returned with `repeated = true` under
/// [`MissingFramePolicy::HoldPrevious`] and withheld under [`MissingFramePolicy::Wait`].
/// `texture` is absent before the first success.
///
/// A frame whose size, cache key and content epoch match the last returned texture (with every
/// source keyed) is not rendered and returns `unchanged = true`. Unkeyed sources always render.
///
/// # Errors
/// Returns timeline evaluation, quality, or rendering failures, and
/// [`EngineError::UnregisteredEffect`] naming an effect the frame draws
/// that `renderer` has not registered.
pub fn render_at<'a, R: FrameRenderer<Image = I> + ?Sized>(
&'a mut self,
project: &EngineProject,
renderer: &R,
frames: &dyn FrameProvider,
time: MediaTime,
) -> Result<PlaybackFrame<'a, I>, EngineError> {
let frame = project.evaluate(time)?;
crate::frame::check_frame_effects(renderer, &frame)?;
let size = self.quality.render_size(&project.project().settings)?;
renderer.set_texture_budget_bytes(self.quality.texture_budget_bytes);
renderer.set_quality_controls(
self.quality.max_filter_samples,
self.quality.motion_blur_subframes,
);
let built = renderer.build_frame_graph(size, &frame, frames)?;
if let Some(graph) = built.graph {
let key = match graph.output().map(|output| graph.cache_eligibility(output)) {
Some(Ok(CacheEligibility::Eligible)) => Some(
renderer
.graph_cache_key(&graph)
.map_err(alpha2_render::GraphError::into_render_error)?,
),
_ => None,
};
let unchanged = self.last_frame.is_some()
&& key.is_some_and(|key| self.shown == Some((size, key, renderer.content_epoch())));
if !unchanged {
let texture = renderer.render_frame_graph(&graph, &built.pending)?;
self.last_frame = Some((time, texture));
// Read after the render, which may itself have cleared the result cache.
self.shown = key.map(|key| (size, key, renderer.content_epoch()));
}
let (presented_time, texture) =
self.last_frame.as_mut().ok_or(EngineError::OutOfRange)?;
// The held texture is this frame's too.
*presented_time = time;
renderer.record_frame_outcome(true, false);
return Ok(PlaybackFrame {
requested_time: time,
presented_time: Some(*presented_time),
texture: Some(texture),
missing_sources: Vec::new(),
repeated: false,
unchanged,
});
}
// A hold is not this frame: the next complete one is presented, whatever its key.
self.shown = None;
let (presented_time, texture) = match self.missing_frame_policy {
MissingFramePolicy::HoldPrevious => self
.last_frame
.as_ref()
.map_or((None, None), |(time, texture)| (Some(*time), Some(texture))),
MissingFramePolicy::Wait => (None, None),
};
renderer.record_frame_outcome(texture.is_some(), texture.is_some());
Ok(PlaybackFrame {
requested_time: time,
presented_time,
texture,
missing_sources: built.report.missing_sources,
repeated: texture.is_some(),
unchanged: false,
})
}
/// Drops the held frame, for example after a seek or project swap.
pub fn reset(&mut self) {
self.last_frame = None;
self.shown = None;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prefetch_configuration_is_bounded() {
let player = Player::<RenderedTexture>::default().with_prefetch_frames(u32::MAX);
assert_eq!(player.prefetch_frames, MAX_PREFETCH_FRAMES);
}
#[test]
fn hold_previous_is_the_default_missing_frame_policy() {
assert_eq!(
Player::<RenderedTexture>::default().missing_frame_policy(),
MissingFramePolicy::HoldPrevious
);
}
#[test]
fn the_missing_frame_policy_is_configurable() {
let player = Player::<RenderedTexture>::default()
.with_missing_frame_policy(MissingFramePolicy::Wait);
assert_eq!(player.missing_frame_policy(), MissingFramePolicy::Wait);
assert_eq!(
player
.with_missing_frame_policy(MissingFramePolicy::HoldPrevious)
.missing_frame_policy(),
MissingFramePolicy::HoldPrevious
);
}
#[test]
fn configuring_the_policy_preserves_quality_and_prefetch() {
let player = Player::<RenderedTexture>::new(QualityProfile::export())
.expect("valid quality")
.with_prefetch_frames(7)
.with_missing_frame_policy(MissingFramePolicy::Wait);
assert_eq!(player.quality(), QualityProfile::export());
assert_eq!(player.prefetch_frames, 7);
assert_eq!(player.missing_frame_policy(), MissingFramePolicy::Wait);
}
}