Skip to main content

oa/video/
player.rs

1//! Composed demux, decode, and presentation-order playback sessions.
2
3use std::{collections::VecDeque, path::Path, time::Duration};
4
5use crate::{Error, Result, Runtime, Texture};
6
7use super::{VideoContainerInfo, VideoContainerKind, VideoDecoder, VideoDemuxer, VideoFrame};
8pub use crate::video::types::VideoPlayerConfig;
9
10impl Default for VideoPlayerConfig {
11	fn default() -> Self {
12		Self {
13			loop_playback: true,
14			frame_rate_override: None,
15			start_playing: true,
16			presentation_cache_frames: 32,
17			presentation_cache_bytes: 256 * 1024 * 1024,
18		}
19	}
20}
21
22/// Observable counters for one player lifetime.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24pub struct VideoPlayerStats {
25	/// Frames presented by open, stepping, ticking, or seeking.
26	pub presented_frames: u64,
27	/// Packets submitted to the decoder.
28	pub decoded_packets: u64,
29	/// Explicit or looping seek resets.
30	pub seek_resets: u64,
31	/// End-of-stream wraps performed by looping playback.
32	pub loop_restarts: u64,
33	/// Frames decoded again while rebuilding history after a cache miss.
34	pub seek_replay_frames: u64,
35	/// Exact display steps served from retained history.
36	pub presentation_cache_hits: u64,
37	/// Backward/forward history requests that required deterministic replay.
38	pub presentation_cache_misses: u64,
39	/// Number of frames currently retained in presentation history.
40	pub presentation_cache_resident: usize,
41	/// Configured maximum number of retained presentation frames.
42	pub presentation_cache_capacity: usize,
43}
44
45/// Stateful local video player composed from [`VideoDemuxer`] and [`VideoDecoder`].
46///
47/// `open` decodes through the first display-order frame, so [`current_frame`](Self::current_frame)
48/// is immediately available on success. Timing controls do not create a second
49/// decoder or runtime owner; all hardware work remains inside the supplied
50/// Runtime-owned decoder session.
51pub struct VideoPlayer {
52	state: Option<PlayerState>,
53}
54
55struct PlayerState {
56	demuxer: VideoDemuxer,
57	decoder: VideoDecoder,
58	output: PlayerOutput,
59	info: VideoContainerInfo,
60	config: VideoPlayerConfig,
61	current: Option<VideoFrame>,
62	queued: VecDeque<VideoFrame>,
63	decoder_drained: bool,
64	presentation_cache: VecDeque<CachedPresentation>,
65	presentation_cache_bytes: usize,
66	canvas_yuv: bool,
67	frame_interval: Duration,
68	duration: Duration,
69	accumulator: Duration,
70	playing: bool,
71	done: bool,
72	display_index: u64,
73	next_display_index: u64,
74	display_timestamps: Vec<DisplayTimestamp>,
75	indexed: bool,
76	stats: VideoPlayerStats,
77}
78
79#[derive(Clone, Copy, PartialEq, Eq)]
80enum PlayerOutput {
81	HostPlanar,
82	Native,
83}
84
85struct CachedPresentation {
86	index: u64,
87	frame: VideoFrame,
88	bytes: usize,
89}
90
91#[derive(Clone, Copy)]
92struct DisplayTimestamp {
93	ticks: u64,
94	duration: Duration,
95}
96
97impl VideoPlayer {
98	/// Open a local source and present its first display-order frame.
99	///
100	/// # Errors
101	///
102	/// Returns an error for invalid pacing, demux/decode failure, unsupported
103	/// codec/device capabilities, or a source with no displayable frame.
104	pub fn open(
105		runtime: &Runtime,
106		path: impl AsRef<Path>,
107		config: VideoPlayerConfig,
108	) -> Result<Self> {
109		Self::open_with_output(runtime, path, config, PlayerOutput::HostPlanar)
110	}
111
112	/// Open a player whose frames retain the decoder's native Vulkan images.
113	///
114	/// This route does not read decoded pixels back to the host. Frames returned
115	/// by [`current_frame`](Self::current_frame) retain their decoder slots;
116	/// GPU consumers must register completion with [`VideoFrame::mark_consumed`].
117	/// Converted presentation textures use the configured bounded history;
118	/// decoder slots themselves are never cached. A backward cache miss rebuilds
119	/// a preceding window once, so subsequent reverse steps reuse GPU textures.
120	///
121	/// A native frame is not a render [`crate::Texture`]. A renderer must
122	/// explicitly convert or sample its planes before displaying it.
123	///
124	/// # Errors
125	///
126	/// Returns the same stream and device errors as [`open`](Self::open).
127	pub fn new_native(
128		runtime: &Runtime,
129		path: impl AsRef<Path>,
130		config: VideoPlayerConfig,
131	) -> Result<Self> {
132		Self::open_with_output(runtime, path, config, PlayerOutput::Native)
133	}
134
135	fn open_with_output(
136		runtime: &Runtime,
137		path: impl AsRef<Path>,
138		config: VideoPlayerConfig,
139		output: PlayerOutput,
140	) -> Result<Self> {
141		if config
142			.frame_rate_override
143			.is_some_and(|rate| !rate.is_finite() || rate <= 0.0)
144		{
145			return Err(Error::invalid_argument(
146				"video player frame-rate override must be finite and positive",
147			));
148		}
149		let demuxer = VideoDemuxer::open(path)?;
150		let info = demuxer.info();
151		let indexed = info.kind() != VideoContainerKind::MpegTs;
152		let (timestamp_ticks, presentation_end) = if indexed {
153			demuxer.presentation_timestamps()?
154		} else {
155			(Vec::new(), 0)
156		};
157		let mut display_timestamps = Vec::new();
158		display_timestamps
159			.try_reserve_exact(timestamp_ticks.len())
160			.map_err(|_| Error::resource_exhausted("video display index allocation failed"))?;
161		for ticks in timestamp_ticks {
162			display_timestamps.push(DisplayTimestamp {
163				ticks,
164				duration: ticks_to_duration(ticks, info)?,
165			});
166		}
167		let rate = config
168			.frame_rate_override
169			.unwrap_or_else(|| info.frame_rate());
170		let rate = if rate.is_finite() && rate > 0.0 {
171			rate
172		} else {
173			30.0
174		};
175		let frame_interval = Duration::try_from_secs_f64(1.0 / rate)
176			.ok()
177			.filter(|interval| !interval.is_zero())
178			.ok_or_else(|| {
179				Error::out_of_range("video player frame interval is outside Duration precision")
180			})?;
181		let duration = ticks_to_duration(presentation_end, info)?;
182		let decoder = VideoDecoder::new(runtime, info)?;
183		let presentation_cache_capacity = if !indexed {
184			0
185		} else {
186			let frame_bytes = usize::try_from(info.width())
187				.ok()
188				.and_then(|width| {
189					usize::try_from(info.height())
190						.ok()
191						.and_then(|height| width.checked_mul(height))
192				})
193				.and_then(|luma| match output {
194					// Current Texture storage retains both its packed buffer and
195					// sampled image. Charge both copies to the history budget.
196					PlayerOutput::Native => luma.checked_mul(8),
197					PlayerOutput::HostPlanar => luma.checked_mul(3)?.checked_div(2),
198				})
199				.ok_or_else(|| Error::out_of_range("video player frame size overflows usize"))?;
200			config.presentation_cache_frames.min(
201				config
202					.presentation_cache_bytes
203					.checked_div(frame_bytes)
204					.unwrap_or(0),
205			)
206		};
207		let mut player = Self {
208			state: Some(PlayerState {
209				demuxer,
210				decoder,
211				output,
212				info,
213				config,
214				current: None,
215				queued: VecDeque::new(),
216				decoder_drained: false,
217				presentation_cache: VecDeque::new(),
218				presentation_cache_bytes: 0,
219				canvas_yuv: false,
220				frame_interval,
221				duration,
222				accumulator: Duration::ZERO,
223				playing: config.start_playing,
224				done: false,
225				display_index: 0,
226				next_display_index: 0,
227				display_timestamps,
228				indexed,
229				stats: VideoPlayerStats {
230					presentation_cache_capacity,
231					..VideoPlayerStats::default()
232				},
233			}),
234		};
235		if !player.advance_one()? {
236			return Err(Error::data_loss(
237				"video source contains no displayable frame",
238			));
239		}
240		Ok(player)
241	}
242
243	/// Present exactly one next display-order frame, independent of play/pause state.
244	///
245	/// Returns `false` only after a non-looping source is exhausted.
246	pub fn advance(&mut self) -> Result<bool> {
247		self.advance_one()
248	}
249
250	/// Present the preceding display-order frame.
251	///
252	/// Retained history is presented without decoding. If the requested frame
253	/// has already been evicted, the player seeks through a bounded preceding
254	/// presentation window and deterministically rebuilds through the target.
255	pub fn step_backward(&mut self) -> Result<()> {
256		self.step_frames(-1)
257	}
258
259	/// Move by a signed number of display-order frames.
260	///
261	/// Positive movement stops successfully at the end of a non-looping stream.
262	/// Negative movement saturates at the first indexed display frame. A zero
263	/// delta is a no-op.
264	pub fn step_frames(&mut self, delta: i32) -> Result<()> {
265		if delta >= 0 {
266			for _ in 0..delta.unsigned_abs() {
267				if !self.advance_one()? {
268					break;
269				}
270			}
271			return Ok(());
272		}
273
274		let current = self.state_ref()?.display_index;
275		let target = current.saturating_sub(u64::from(delta.unsigned_abs()));
276		if target == current {
277			return Ok(());
278		}
279		if !self.state_ref()?.indexed {
280			return Err(Error::missing_capability(
281				"backward stepping requires an indexed video source",
282			));
283		}
284		if self.present_cached(target)? {
285			return Ok(());
286		}
287		self.record_cache_miss()?;
288		self.replay_to_index(target)
289	}
290
291	/// Advance according to elapsed wall-clock time while playing.
292	///
293	/// Returns the number of frames presented. Paused players do not accumulate
294	/// elapsed time, preventing a burst of implicit skipping after resume.
295	pub fn tick(&mut self, elapsed: Duration) -> Result<u32> {
296		self.tick_bounded(elapsed, u32::MAX)
297	}
298
299	pub(crate) fn tick_bounded(&mut self, elapsed: Duration, budget: u32) -> Result<u32> {
300		let state = self.state_mut()?;
301		if !state.playing || state.done {
302			return Ok(0);
303		}
304		state.accumulator = state
305			.accumulator
306			.checked_add(elapsed)
307			.ok_or_else(|| Error::out_of_range("video player clock accumulator overflowed"))?;
308		let mut advanced = 0_u32;
309		while advanced < budget {
310			let state = self.state_mut()?;
311			// Sequential containers lack an index and packet durations. Decode
312			// at most one display frame ahead to pace from its real PTS. Keep
313			// decoder reorder output in the same queue used by manual stepping.
314			let mut interval = state.frame_interval;
315			if !state.indexed && state.config.frame_rate_override.is_none() {
316				Self::fill_display_queue(state)?;
317				if let (Some(current), Some(next)) = (&state.current, state.queued.front()) {
318					// PES packets without a timestamp carry zero. Repeated or
319					// regressing timestamps retain the last usable cadence.
320					if let Some(delta) = next
321						.timing()
322						.presentation_timestamp()
323						.checked_sub(current.timing().presentation_timestamp())
324						.filter(|delta| !delta.is_zero())
325					{
326						interval = delta;
327						state.frame_interval = delta;
328					}
329				}
330			}
331			if state.accumulator < interval {
332				break;
333			}
334			state.accumulator -= interval;
335			if !self.advance_one()? {
336				break;
337			}
338			advanced = advanced
339				.checked_add(1)
340				.ok_or_else(|| Error::resource_exhausted("video tick frame count overflowed"))?;
341		}
342		Ok(advanced)
343	}
344
345	/// Seek to a presentation timestamp in the selected track time base.
346	///
347	/// The demuxer rewinds to the preceding keyframe; the player then decodes
348	/// forward until it reaches the first frame at or after `timestamp`.
349	pub fn seek(&mut self, timestamp: u64) -> Result<()> {
350		if !self.state_ref()?.indexed {
351			if timestamp != 0 {
352				return Err(Error::missing_capability(
353					"unindexed video sources support rewind to zero only",
354				));
355			}
356			let state = self.state_mut()?;
357			state.decoder.flush()?;
358			state.demuxer.seek(0)?;
359			state.queued.clear();
360			state.decoder_drained = false;
361			Self::clear_presentation_cache(state);
362			state.current = None;
363			state.accumulator = Duration::ZERO;
364			state.done = false;
365			state.display_index = 0;
366			state.next_display_index = 0;
367			state.stats.seek_resets = state
368				.stats
369				.seek_resets
370				.checked_add(1)
371				.ok_or_else(|| Error::resource_exhausted("video seek counter overflowed"))?;
372			if !self.advance_decoded_one()? {
373				return Err(Error::data_loss(
374					"video source contains no displayable frame",
375				));
376			}
377			return Ok(());
378		}
379		let target = {
380			let state = self.state_ref()?;
381			if timestamp >= state.info.duration() && state.info.duration() != 0 {
382				return Err(Error::out_of_range(
383					"video player seek timestamp is outside the stream duration",
384				));
385			}
386			state
387				.display_timestamps
388				.partition_point(|point| point.ticks < timestamp)
389		};
390		if target == self.state_ref()?.display_timestamps.len() {
391			return Err(Error::out_of_range(
392				"video seek found no display frame at the requested timestamp",
393			));
394		}
395		self.rebuild_to_index(target, false)
396	}
397
398	/// Present the most recent indexed frame at or before a track timestamp.
399	///
400	/// This is the seek policy for an external audio clock: choosing the first
401	/// frame after the requested time would display future video early. A
402	/// timestamp before the first frame selects that first frame. Unindexed
403	/// streams can only be rewound to zero.
404	pub fn seek_at_or_before(&mut self, timestamp: u64) -> Result<()> {
405		let state = self.state_ref()?;
406		if !state.indexed {
407			return if timestamp == 0 {
408				self.seek(0)
409			} else {
410				Err(Error::missing_capability(
411					"timestamp seeking requires an indexed video source",
412				))
413			};
414		}
415		let target = display_index_at_or_before(&state.display_timestamps, timestamp)
416			.ok_or_else(|| Error::data_loss("video source has no indexed display frames"))?;
417		self.seek_frame(
418			u64::try_from(target).map_err(|_| Error::out_of_range("video display index exceeds u64"))?,
419		)
420	}
421
422	pub(crate) fn seek_time_at_or_before(&mut self, target: Duration) -> Result<()> {
423		let state = self.state_ref()?;
424		let points = &state.display_timestamps;
425		let last = points
426			.get(
427				points
428					.partition_point(|point| point.duration <= target)
429					.saturating_sub(1),
430			)
431			.ok_or_else(|| Error::data_loss("video source has no indexed display frames"))?;
432		self.seek_at_or_before(last.ticks)
433	}
434
435	/// Seek to an exact zero-based display-order frame.
436	///
437	/// A retained target is presented without decoding. Otherwise the player
438	/// seeks to a bounded preceding presentation window and rebuilds decoder
439	/// state through the requested frame.
440	pub fn seek_frame(&mut self, index: u64) -> Result<()> {
441		if !self.state_ref()?.indexed {
442			return Err(Error::missing_capability(
443				"frame seeking requires an indexed video source",
444			));
445		}
446		let target =
447			usize::try_from(index).map_err(|_| Error::out_of_range("video frame index exceeds usize"))?;
448		if target >= self.state_ref()?.display_timestamps.len() {
449			return Err(Error::out_of_range(
450				"video frame index is outside the display sequence",
451			));
452		}
453		let state = self.state_ref()?;
454		if (state.current.is_some() && state.display_index == index) || self.present_cached(index)? {
455			return Ok(());
456		}
457		self.rebuild_to_index(target, false)
458	}
459
460	/// Rewind and present the first frame.
461	pub fn reset(&mut self) -> Result<()> {
462		self.seek(0)
463	}
464
465	/// End the current decode sequence and discard delayed frames.
466	///
467	/// Playback becomes done until [`seek`](Self::seek) or [`reset`](Self::reset)
468	/// establishes a new random-access boundary.
469	pub fn flush(&mut self) -> Result<usize> {
470		let state = self.state_mut()?;
471		let discarded = state.decoder.flush()?.len() + state.queued.len();
472		state.queued.clear();
473		state.decoder_drained = false;
474		Self::clear_presentation_cache(state);
475		state.done = true;
476		state.accumulator = Duration::ZERO;
477		Ok(discarded)
478	}
479
480	/// Explicitly release decoder and demuxer state. A second close is harmless.
481	pub fn close(&mut self) {
482		if let Some(mut state) = self.state.take() {
483			state.decoder.close();
484			state.demuxer.close();
485		}
486	}
487
488	/// Resume time-paced playback.
489	pub fn play(&mut self) -> Result<()> {
490		self.state_mut()?.playing = true;
491		Ok(())
492	}
493
494	/// Pause time-paced playback and discard fractional accumulated time.
495	pub fn pause(&mut self) -> Result<()> {
496		let state = self.state_mut()?;
497		state.playing = false;
498		state.accumulator = Duration::ZERO;
499		Ok(())
500	}
501
502	/// Toggle time-paced playback.
503	pub fn toggle_play(&mut self) -> Result<()> {
504		let state = self.state_mut()?;
505		state.playing = !state.playing;
506		if !state.playing {
507			state.accumulator = Duration::ZERO;
508		}
509		Ok(())
510	}
511
512	/// Change end-of-stream looping policy.
513	pub fn set_looping(&mut self, looping: bool) -> Result<()> {
514		self.state_mut()?.config.loop_playback = looping;
515		Ok(())
516	}
517
518	/// Borrow the currently presented frame.
519	pub fn current_frame(&self) -> Result<&VideoFrame> {
520		self
521			.state_ref()?
522			.current
523			.as_ref()
524			.ok_or_else(|| Error::failed_precondition("VideoPlayer has no current frame"))
525	}
526
527	/// Convert the currently presented frame into a `Texture` for rendering.
528	///
529	/// Native decoded frames convert on-device through the decoder's
530	/// native-plane-to-RGBA path. The presented frame is then re-seated on the
531	/// texture: its timing, extent, and color metadata remain observable
532	/// through [`current_frame`](Self::current_frame) while the decoder slot
533	/// is released for the next decode. A texture-backed frame returns its
534	/// backing directly, so repeated calls for the same presented frame are
535	/// free. Host-planar playback has no texture path.
536	///
537	/// # Errors
538	///
539	/// Returns an error after close, when no frame is presented, for a
540	/// non-native frame without a texture backing, or when the conversion
541	/// submission fails.
542	pub fn current_frame_texture(&mut self) -> Result<Texture> {
543		let state = self.state_mut()?;
544		let frame = state
545			.current
546			.clone()
547			.ok_or_else(|| Error::failed_precondition("VideoPlayer has no current frame"))?;
548		if let Some(texture) = frame.as_texture() {
549			return Ok(texture.clone());
550		}
551		let texture = state.decoder.native_frame_texture(&frame)?;
552		if frame.native_backing().is_some() {
553			let presented =
554				VideoFrame::from_texture(texture.clone(), frame.timing(), frame.color_info(), None);
555			state.current = Some(presented.clone());
556			Self::retain_presentation(state, state.display_index, presented)?;
557		}
558		Ok(texture)
559	}
560
561	pub(crate) fn enable_canvas_yuv(&mut self) -> Result<()> {
562		self.state_mut()?.canvas_yuv = true;
563		Ok(())
564	}
565
566	pub(crate) fn prepare_viewer_frame(&mut self) -> Result<VideoFrame> {
567		let state = self.state_mut()?;
568		let frame = state
569			.current
570			.clone()
571			.ok_or_else(|| Error::failed_precondition("VideoPlayer has no current frame"))?;
572		if frame.canvas_planes().is_some() || frame.as_texture().is_some() {
573			return Ok(frame);
574		}
575		if state.canvas_yuv
576			&& matches!(
577				frame.native_format(),
578				Some(
579					crate::video::VideoPixelFormat::P010
580						| crate::video::VideoPixelFormat::Yuv420Planar10
581						| crate::video::VideoPixelFormat::P012
582				)
583			) {
584			let staged = state.decoder.stage_native_canvas_frame(&frame)?;
585			state.current = Some(staged.clone());
586			Self::retain_presentation(state, state.display_index, staged.clone())?;
587			return Ok(staged);
588		}
589		self.current_frame_texture()?;
590		Ok(self.current_frame()?.clone())
591	}
592
593	/// Timestamp at which the next display frame may replace the current one.
594	///
595	/// Indexed containers use the next frame's PTS, which respects variable
596	/// frame rate and gaps. Sequential sources use the current frame's declared
597	/// end; an unknown duration cannot be paced by an external clock.
598	/// `None` means the indexed stream has no further display frame.
599	pub fn next_presentation_boundary(&self) -> Result<Option<Duration>> {
600		let state = self.state_ref()?;
601		if state.indexed {
602			let next = state
603				.display_index
604				.checked_add(1)
605				.ok_or_else(|| Error::out_of_range("video display index overflowed"))?;
606			let next = usize::try_from(next)
607				.map_err(|_| Error::out_of_range("video display index exceeds usize"))?;
608			return Ok(
609				state
610					.display_timestamps
611					.get(next)
612					.map(|point| point.duration),
613			);
614		}
615		let timing = self.current_frame()?.timing();
616		let duration = timing.duration().ok_or_else(|| {
617			Error::missing_capability(
618				"unindexed video requires known frame durations for clocked playback",
619			)
620		})?;
621		let boundary = timing
622			.presentation_timestamp()
623			.checked_add(duration)
624			.ok_or_else(|| Error::out_of_range("video presentation time overflowed"))?;
625		Ok(Some(boundary))
626	}
627
628	/// Return the absolute zero-based display index in the selected track.
629	pub fn current_frame_index(&self) -> Result<u64> {
630		Ok(self.state_ref()?.display_index)
631	}
632
633	/// Return selected stream metadata while open.
634	pub fn info(&self) -> Option<VideoContainerInfo> {
635		self.state.as_ref().map(|state| state.info)
636	}
637
638	pub(crate) fn duration(&self) -> Result<Duration> {
639		Ok(self.state_ref()?.duration)
640	}
641
642	pub(crate) fn advance_for_playback(&mut self) -> Result<bool> {
643		let state = self.state_mut()?;
644		if state.indexed
645			&& state
646				.current
647				.as_ref()
648				.is_some_and(|frame| frame.native_backing().is_some())
649		{
650			// Catch-up can skip rendering several successive frames. Release the
651			// superseded lease just as the replay path does before decoding again.
652			state.current = None;
653		}
654		self.advance_one()
655	}
656
657	/// Return a snapshot of playback counters while open.
658	pub fn stats(&self) -> Option<VideoPlayerStats> {
659		self.state.as_ref().map(|state| state.stats)
660	}
661
662	/// Return whether time-paced playback is enabled.
663	pub fn is_playing(&self) -> bool {
664		self.state.as_ref().is_some_and(|state| state.playing)
665	}
666
667	/// Return whether a non-looping stream has presented its final frame.
668	pub fn is_done(&self) -> bool {
669		self.state.as_ref().is_none_or(|state| state.done)
670	}
671
672	/// Return whether the player still owns its sessions.
673	pub const fn is_open(&self) -> bool {
674		self.state.is_some()
675	}
676
677	fn advance_one(&mut self) -> Result<bool> {
678		let cached_target = {
679			let state = self.state_ref()?;
680			state
681				.display_index
682				.checked_add(1)
683				.filter(|next| *next < state.next_display_index)
684		};
685		if let Some(target) = cached_target {
686			if self.present_cached(target)? {
687				return Ok(true);
688			}
689			self.record_cache_miss()?;
690			self.replay_to_index(target)?;
691			return Ok(true);
692		}
693		self.advance_decoded_one()
694	}
695
696	fn fill_display_queue(state: &mut PlayerState) -> Result<()> {
697		while state.queued.is_empty() && !state.decoder_drained {
698			let Some(packet) = state.demuxer.read_next_packet()? else {
699				state.queued.extend(state.decoder.flush()?);
700				state.decoder_drained = true;
701				break;
702			};
703			state.stats.decoded_packets = state
704				.stats
705				.decoded_packets
706				.checked_add(1)
707				.ok_or_else(|| Error::resource_exhausted("video decoded-packet counter overflowed"))?;
708			let frame = match state.output {
709				PlayerOutput::HostPlanar => state.decoder.decode(&packet)?,
710				PlayerOutput::Native => state.decoder.decode_native(&packet)?,
711			};
712			state.queued.extend(frame);
713		}
714		Ok(())
715	}
716
717	fn advance_decoded_one(&mut self) -> Result<bool> {
718		let state = self.state_mut()?;
719		if state.done {
720			return Ok(false);
721		}
722		Self::fill_display_queue(state)?;
723		if state.queued.is_empty() && state.config.loop_playback && state.next_display_index != 0 {
724			state.demuxer.seek(0)?;
725			state.stats.loop_restarts = state
726				.stats
727				.loop_restarts
728				.checked_add(1)
729				.ok_or_else(|| Error::resource_exhausted("video loop counter overflowed"))?;
730			state.stats.seek_resets = state
731				.stats
732				.seek_resets
733				.checked_add(1)
734				.ok_or_else(|| Error::resource_exhausted("video seek counter overflowed"))?;
735			state.display_index = 0;
736			state.next_display_index = 0;
737			state.decoder_drained = false;
738			Self::clear_presentation_cache(state);
739			Self::fill_display_queue(state)?;
740		}
741		let Some(frame) = state.queued.pop_front() else {
742			state.done = true;
743			return Ok(false);
744		};
745		Self::present_new(state, frame)?;
746		if state.indexed
747			&& state.decoder_drained
748			&& state.queued.is_empty()
749			&& !state.config.loop_playback
750		{
751			state.done = true;
752		}
753		Ok(true)
754	}
755
756	fn present_new(state: &mut PlayerState, frame: VideoFrame) -> Result<()> {
757		if !state.indexed {
758			let index = state.next_display_index;
759			state.next_display_index = index
760				.checked_add(1)
761				.ok_or_else(|| Error::resource_exhausted("video display index overflowed"))?;
762			state.current = Some(frame);
763			state.display_index = index;
764			state.stats.presented_frames = state
765				.stats
766				.presented_frames
767				.checked_add(1)
768				.ok_or_else(|| Error::resource_exhausted("video presented-frame counter overflowed"))?;
769			return Ok(());
770		}
771		let minimum = usize::try_from(state.next_display_index)
772			.map_err(|_| Error::out_of_range("video display index exceeds usize"))?;
773		let timestamp = frame.timing().presentation_timestamp();
774		let remaining = state.display_timestamps.get(minimum..).ok_or_else(|| {
775			Error::data_loss("video decoder advanced beyond the container display index")
776		})?;
777		let relative = remaining.partition_point(|point| point.duration < timestamp);
778		let resolved = minimum
779			.checked_add(relative)
780			.ok_or_else(|| Error::out_of_range("video display index overflowed"))?;
781		let Some(point) = state.display_timestamps.get(resolved) else {
782			return Err(Error::data_loss(
783				"decoded frame timestamp is absent from the container display index",
784			));
785		};
786		if point.duration != timestamp {
787			return Err(Error::data_loss(
788				"decoded frame timestamp does not match the container display index",
789			));
790		}
791		let index = u64::try_from(resolved)
792			.map_err(|_| Error::out_of_range("video display index exceeds u64"))?;
793		state.current = Some(frame.clone());
794		state.display_index = index;
795		state.next_display_index = index
796			.checked_add(1)
797			.ok_or_else(|| Error::resource_exhausted("video display index overflowed"))?;
798		state.stats.presented_frames = state
799			.stats
800			.presented_frames
801			.checked_add(1)
802			.ok_or_else(|| Error::resource_exhausted("video presented-frame counter overflowed"))?;
803		Self::retain_presentation(state, index, frame)?;
804		Ok(())
805	}
806
807	fn present_cached(&mut self, index: u64) -> Result<bool> {
808		let state = self.state_mut()?;
809		let Some(frame) = state
810			.presentation_cache
811			.iter()
812			.find(|entry| entry.index == index)
813			.map(|entry| entry.frame.clone())
814		else {
815			return Ok(false);
816		};
817		state.current = Some(frame);
818		state.display_index = index;
819		state.done = false;
820		state.stats.presented_frames = state
821			.stats
822			.presented_frames
823			.checked_add(1)
824			.ok_or_else(|| Error::resource_exhausted("video presented-frame counter overflowed"))?;
825		state.stats.presentation_cache_hits = state
826			.stats
827			.presentation_cache_hits
828			.checked_add(1)
829			.ok_or_else(|| Error::resource_exhausted("video cache-hit counter overflowed"))?;
830		Ok(true)
831	}
832
833	fn record_cache_miss(&mut self) -> Result<()> {
834		let state = self.state_mut()?;
835		state.stats.presentation_cache_misses = state
836			.stats
837			.presentation_cache_misses
838			.checked_add(1)
839			.ok_or_else(|| Error::resource_exhausted("video cache-miss counter overflowed"))?;
840		Ok(())
841	}
842
843	fn replay_to_index(&mut self, target: u64) -> Result<()> {
844		let target = usize::try_from(target)
845			.map_err(|_| Error::out_of_range("video replay index exceeds usize"))?;
846		self.rebuild_to_index(target, true)
847	}
848
849	fn rebuild_to_index(&mut self, target: usize, replay: bool) -> Result<()> {
850		let (timestamp, history_start) = {
851			let state = self.state_ref()?;
852			let history = state.stats.presentation_cache_capacity.max(1);
853			let seek_start = target.saturating_add(1).saturating_sub(history);
854			let timestamp = state
855				.display_timestamps
856				.get(seek_start)
857				.ok_or_else(|| Error::out_of_range("video rebuild index is outside the stream"))?
858				.ticks;
859			(timestamp, seek_start)
860		};
861		{
862			let state = self.state_mut()?;
863			state.decoder.flush()?;
864			state.demuxer.seek(timestamp)?;
865			state.queued.clear();
866			state.decoder_drained = false;
867			Self::clear_presentation_cache(state);
868			state.current = None;
869			state.accumulator = Duration::ZERO;
870			state.done = false;
871			state.display_index = 0;
872			state.next_display_index = 0;
873			state.stats.seek_resets = state
874				.stats
875				.seek_resets
876				.checked_add(1)
877				.ok_or_else(|| Error::resource_exhausted("video seek counter overflowed"))?;
878		}
879		loop {
880			// Rebuild intermediates are private, superseded frames. Release our
881			// previous native lease before reserving the next DPB output; holding
882			// it until present_new can exhaust AV1's reference-heavy slot pool.
883			self.state_mut()?.current = None;
884			if !self.advance_decoded_one()? {
885				return Err(Error::data_loss(
886					"video rebuild ended before the requested display frame",
887				));
888			}
889			let current = {
890				let state = self.state_mut()?;
891				if replay {
892					state.stats.seek_replay_frames = state
893						.stats
894						.seek_replay_frames
895						.checked_add(1)
896						.ok_or_else(|| Error::resource_exhausted("video replay counter overflowed"))?;
897				}
898				usize::try_from(state.display_index)
899					.map_err(|_| Error::out_of_range("video display index exceeds usize"))?
900			};
901			// Cache independent presentation resources, not DPB leases. Populate
902			// the preceding window during this replay rather than repeating a
903			// random-access decode for every held-left key repeat.
904			if self.state_ref()?.output == PlayerOutput::Native
905				&& self.state_ref()?.stats.presentation_cache_capacity > 0
906				&& current >= history_start
907			{
908				self.prepare_viewer_frame()?;
909			}
910			if current == target {
911				return Ok(());
912			}
913			if current > target {
914				return Err(Error::data_loss(
915					"video rebuild skipped the requested display frame",
916				));
917			}
918		}
919	}
920
921	fn retain_presentation(state: &mut PlayerState, index: u64, frame: VideoFrame) -> Result<()> {
922		let bytes = if let Some((planes, _)) = frame.canvas_planes() {
923			Some(planes.byte_len())
924		} else if let Some(texture) = frame.as_texture() {
925			texture
926				.width()
927				.checked_mul(texture.height())
928				.and_then(|pixels| pixels.checked_mul(8))
929		} else if let Some(samples) = frame.as_yuv420p10() {
930			samples.len().checked_mul(2)
931		} else {
932			frame.as_yuv420p().map(<[u8]>::len)
933		};
934		let Some(bytes) = bytes else {
935			return Ok(());
936		};
937		if state.stats.presentation_cache_capacity == 0
938			|| state.config.presentation_cache_bytes == 0
939			|| bytes > state.config.presentation_cache_bytes
940		{
941			return Ok(());
942		}
943		if let Some(position) = state
944			.presentation_cache
945			.iter()
946			.position(|entry| entry.index == index)
947		{
948			let previous = state
949				.presentation_cache
950				.remove(position)
951				.ok_or_else(|| Error::internal("video cache entry disappeared"))?;
952			state.presentation_cache_bytes -= previous.bytes;
953		}
954		state.presentation_cache_bytes = state
955			.presentation_cache_bytes
956			.checked_add(bytes)
957			.ok_or_else(|| Error::resource_exhausted("video cache byte count overflowed"))?;
958		state.presentation_cache.push_back(CachedPresentation {
959			index,
960			frame,
961			bytes,
962		});
963		while state.presentation_cache.len() > state.stats.presentation_cache_capacity
964			|| state.presentation_cache_bytes > state.config.presentation_cache_bytes
965		{
966			let evicted = state
967				.presentation_cache
968				.pop_front()
969				.ok_or_else(|| Error::internal("video presentation cache accounting diverged"))?;
970			state.presentation_cache_bytes -= evicted.bytes;
971		}
972		state.stats.presentation_cache_resident = state.presentation_cache.len();
973		Ok(())
974	}
975
976	fn clear_presentation_cache(state: &mut PlayerState) {
977		state.presentation_cache.clear();
978		state.presentation_cache_bytes = 0;
979		state.stats.presentation_cache_resident = 0;
980	}
981
982	fn state_ref(&self) -> Result<&PlayerState> {
983		self
984			.state
985			.as_ref()
986			.ok_or_else(|| Error::failed_precondition("VideoPlayer is closed"))
987	}
988
989	fn state_mut(&mut self) -> Result<&mut PlayerState> {
990		self
991			.state
992			.as_mut()
993			.ok_or_else(|| Error::failed_precondition("VideoPlayer is closed"))
994	}
995}
996
997fn ticks_to_duration(ticks: u64, info: VideoContainerInfo) -> Result<Duration> {
998	let time_base = info.time_base();
999	let nanos = u128::from(ticks)
1000		.checked_mul(u128::from(time_base.numerator()))
1001		.and_then(|value| value.checked_mul(1_000_000_000))
1002		.ok_or_else(|| Error::out_of_range("video player timestamp overflows nanoseconds"))?
1003		/ u128::from(time_base.denominator());
1004	let seconds = u64::try_from(nanos / 1_000_000_000)
1005		.map_err(|_| Error::out_of_range("video player timestamp exceeds Duration"))?;
1006	let subsec_nanos = u32::try_from(nanos % 1_000_000_000)
1007		.map_err(|_| Error::out_of_range("video player timestamp remainder exceeds u32"))?;
1008	Ok(Duration::new(seconds, subsec_nanos))
1009}
1010
1011fn display_index_at_or_before(points: &[DisplayTimestamp], ticks: u64) -> Option<usize> {
1012	let last = points.get(
1013		points
1014			.partition_point(|point| point.ticks <= ticks)
1015			.saturating_sub(1),
1016	)?;
1017	Some(points.partition_point(|point| point.ticks < last.ticks))
1018}