oarust 0.8.6

GPU-first semantic computing engine written in Rust
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
//! Composed demux, decode, and presentation-order playback sessions.

use std::{collections::VecDeque, path::Path, time::Duration};

use crate::{Engine, Error, Result};

use super::{VideoContainerInfo, VideoContainerKind, VideoDecoder, VideoDemuxer, VideoFrame};

/// Playback policy for one local video source.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VideoPlayerConfig {
	/// Restart at the beginning after the final display-order frame.
	pub loop_playback: bool,
	/// Override the container average frame rate when pacing [`VideoPlayer::tick`].
	pub frame_rate_override: Option<f64>,
	/// Begin in the playing state. Manual [`VideoPlayer::advance`] calls ignore this.
	pub start_playing: bool,
	/// Maximum display-order frames retained for exact backward/forward stepping.
	pub presentation_cache_frames: usize,
	/// Maximum retained planar bytes across the presentation cache.
	pub presentation_cache_bytes: usize,
}

impl Default for VideoPlayerConfig {
	fn default() -> Self {
		Self {
			loop_playback: true,
			frame_rate_override: None,
			start_playing: true,
			presentation_cache_frames: 32,
			presentation_cache_bytes: 256 * 1024 * 1024,
		}
	}
}

/// Observable counters for one player lifetime.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct VideoPlayerStats {
	/// Frames presented by open, stepping, ticking, or seeking.
	pub presented_frames: u64,
	/// Packets submitted to the decoder.
	pub decoded_packets: u64,
	/// Explicit or looping seek resets.
	pub seek_resets: u64,
	/// End-of-stream wraps performed by looping playback.
	pub loop_restarts: u64,
	/// Frames decoded again while rebuilding history after a cache miss.
	pub seek_replay_frames: u64,
	/// Exact display steps served from retained history.
	pub presentation_cache_hits: u64,
	/// Backward/forward history requests that required deterministic replay.
	pub presentation_cache_misses: u64,
	/// Number of frames currently retained in presentation history.
	pub presentation_cache_resident: usize,
	/// Configured maximum number of retained presentation frames.
	pub presentation_cache_capacity: usize,
}

/// Stateful local video player composed from [`VideoDemuxer`] and [`VideoDecoder`].
///
/// `open` decodes through the first display-order frame, so [`current_frame`](Self::current_frame)
/// is immediately available on success. Timing controls do not create a second
/// decoder or runtime owner; all hardware work remains inside the supplied
/// Engine-owned decoder session.
pub struct VideoPlayer {
	state: Option<PlayerState>,
}

struct PlayerState {
	demuxer: VideoDemuxer,
	decoder: VideoDecoder,
	output: PlayerOutput,
	info: VideoContainerInfo,
	config: VideoPlayerConfig,
	current: Option<VideoFrame>,
	drained: VecDeque<VideoFrame>,
	presentation_cache: VecDeque<CachedPresentation>,
	presentation_cache_bytes: usize,
	frame_interval: Duration,
	accumulator: Duration,
	playing: bool,
	done: bool,
	display_index: u64,
	next_display_index: u64,
	display_timestamps: Vec<DisplayTimestamp>,
	indexed: bool,
	stats: VideoPlayerStats,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum PlayerOutput {
	HostPlanar,
	Native,
}

struct CachedPresentation {
	index: u64,
	frame: VideoFrame,
	bytes: usize,
}

#[derive(Clone, Copy)]
struct DisplayTimestamp {
	ticks: u64,
	duration: Duration,
}

impl VideoPlayer {
	/// Open a local source and present its first display-order frame.
	///
	/// # Errors
	///
	/// Returns an error for invalid pacing, demux/decode failure, unsupported
	/// codec/device capabilities, or a source with no displayable frame.
	pub fn open(engine: &Engine, path: impl AsRef<Path>, config: VideoPlayerConfig) -> Result<Self> {
		Self::open_with_output(engine, path, config, PlayerOutput::HostPlanar)
	}

	/// Open a player whose frames retain the decoder's native Vulkan images.
	///
	/// This route does not read decoded pixels back to the host. Frames returned
	/// by [`current_frame`](Self::current_frame) retain their decoder slots;
	/// GPU consumers must register completion with [`VideoFrame::mark_consumed`].
	/// Presentation history is disabled because holding cached decoder slots
	/// can exhaust the decoder's bounded DPB. Seeking and backward stepping
	/// still work by decoding again from a random-access packet.
	///
	/// A native frame is not a render [`crate::Texture`]. A renderer must
	/// explicitly convert or sample its planes before displaying it.
	///
	/// # Errors
	///
	/// Returns the same stream and device errors as [`open`](Self::open).
	pub fn open_native(
		engine: &Engine,
		path: impl AsRef<Path>,
		config: VideoPlayerConfig,
	) -> Result<Self> {
		Self::open_with_output(engine, path, config, PlayerOutput::Native)
	}

	fn open_with_output(
		engine: &Engine,
		path: impl AsRef<Path>,
		config: VideoPlayerConfig,
		output: PlayerOutput,
	) -> Result<Self> {
		if config
			.frame_rate_override
			.is_some_and(|rate| !rate.is_finite() || rate <= 0.0)
		{
			return Err(Error::invalid_argument(
				"video player frame-rate override must be finite and positive",
			));
		}
		let demuxer = VideoDemuxer::open(path)?;
		let info = demuxer.info();
		let indexed = info.kind() != VideoContainerKind::MpegTs;
		let timestamp_ticks = if indexed {
			demuxer.presentation_timestamps()?
		} else {
			Vec::new()
		};
		let mut display_timestamps = Vec::new();
		display_timestamps
			.try_reserve_exact(timestamp_ticks.len())
			.map_err(|_| Error::resource_exhausted("video display index allocation failed"))?;
		for ticks in timestamp_ticks {
			display_timestamps.push(DisplayTimestamp {
				ticks,
				duration: ticks_to_duration(ticks, info)?,
			});
		}
		let decoder = VideoDecoder::create(engine, info)?;
		let rate = config
			.frame_rate_override
			.unwrap_or_else(|| info.frame_rate());
		let rate = if rate.is_finite() && rate > 0.0 {
			rate
		} else {
			30.0
		};
		let frame_interval = Duration::from_secs_f64(1.0 / rate);
		let presentation_cache_capacity = if output == PlayerOutput::Native || !indexed {
			0
		} else {
			let frame_bytes = usize::try_from(info.width())
				.ok()
				.and_then(|width| {
					usize::try_from(info.height())
						.ok()
						.and_then(|height| width.checked_mul(height))
				})
				.and_then(|luma| luma.checked_mul(3))
				.and_then(|samples| samples.checked_div(2))
				.ok_or_else(|| Error::out_of_range("video player frame size overflows usize"))?;
			config.presentation_cache_frames.min(
				config
					.presentation_cache_bytes
					.checked_div(frame_bytes)
					.unwrap_or(0),
			)
		};
		let mut player = Self {
			state: Some(PlayerState {
				demuxer,
				decoder,
				output,
				info,
				config,
				current: None,
				drained: VecDeque::new(),
				presentation_cache: VecDeque::new(),
				presentation_cache_bytes: 0,
				frame_interval,
				accumulator: Duration::ZERO,
				playing: config.start_playing,
				done: false,
				display_index: 0,
				next_display_index: 0,
				display_timestamps,
				indexed,
				stats: VideoPlayerStats {
					presentation_cache_capacity,
					..VideoPlayerStats::default()
				},
			}),
		};
		if !player.advance_one()? {
			return Err(Error::data_loss(
				"video source contains no displayable frame",
			));
		}
		Ok(player)
	}

	/// Present exactly one next display-order frame, independent of play/pause state.
	///
	/// Returns `false` only after a non-looping source is exhausted.
	pub fn advance(&mut self) -> Result<bool> {
		self.advance_one()
	}

	/// Present the preceding display-order frame.
	///
	/// Retained history is presented without decoding. If the requested frame
	/// has already been evicted, the player seeks through a bounded preceding
	/// presentation window and deterministically rebuilds through the target.
	pub fn step_backward(&mut self) -> Result<()> {
		self.step_frames(-1)
	}

	/// Move by a signed number of display-order frames.
	///
	/// Positive movement stops successfully at the end of a non-looping stream.
	/// Negative movement saturates at the first indexed display frame. A zero
	/// delta is a no-op.
	pub fn step_frames(&mut self, delta: i32) -> Result<()> {
		if delta >= 0 {
			for _ in 0..delta.unsigned_abs() {
				if !self.advance_one()? {
					break;
				}
			}
			return Ok(());
		}

		let current = self.state_ref()?.display_index;
		let target = current.saturating_sub(u64::from(delta.unsigned_abs()));
		if target == current {
			return Ok(());
		}
		if !self.state_ref()?.indexed {
			return Err(Error::missing_capability(
				"backward stepping requires an indexed video source",
			));
		}
		if self.present_cached(target)? {
			return Ok(());
		}
		self.record_cache_miss()?;
		self.replay_to_index(target)
	}

	/// Advance according to elapsed wall-clock time while playing.
	///
	/// Returns the number of frames presented. Paused players do not accumulate
	/// elapsed time, preventing a burst of implicit skipping after resume.
	pub fn tick(&mut self, elapsed: Duration) -> Result<u32> {
		let state = self.state_mut()?;
		if !state.playing || state.done {
			return Ok(0);
		}
		state.accumulator = state
			.accumulator
			.checked_add(elapsed)
			.ok_or_else(|| Error::out_of_range("video player clock accumulator overflowed"))?;
		let mut advanced = 0_u32;
		loop {
			let state = self.state_mut()?;
			if state.accumulator < state.frame_interval {
				break;
			}
			state.accumulator -= state.frame_interval;
			if !self.advance_one()? {
				break;
			}
			advanced = advanced
				.checked_add(1)
				.ok_or_else(|| Error::resource_exhausted("video tick frame count overflowed"))?;
		}
		Ok(advanced)
	}

	/// Seek to a presentation timestamp in the selected track time base.
	///
	/// The demuxer rewinds to the preceding keyframe; the player then decodes
	/// forward until it reaches the first frame at or after `timestamp`.
	pub fn seek(&mut self, timestamp: u64) -> Result<()> {
		if !self.state_ref()?.indexed {
			if timestamp != 0 {
				return Err(Error::missing_capability(
					"unindexed video sources support rewind to zero only",
				));
			}
			let state = self.state_mut()?;
			state.decoder.flush()?;
			state.demuxer.seek(0)?;
			state.drained.clear();
			Self::clear_presentation_cache(state);
			state.current = None;
			state.accumulator = Duration::ZERO;
			state.done = false;
			state.display_index = 0;
			state.next_display_index = 0;
			state.stats.seek_resets = state
				.stats
				.seek_resets
				.checked_add(1)
				.ok_or_else(|| Error::resource_exhausted("video seek counter overflowed"))?;
			if !self.advance_decoded_one()? {
				return Err(Error::data_loss(
					"video source contains no displayable frame",
				));
			}
			return Ok(());
		}
		let target = {
			let state = self.state_ref()?;
			if timestamp >= state.info.duration() && state.info.duration() != 0 {
				return Err(Error::out_of_range(
					"video player seek timestamp is outside the stream duration",
				));
			}
			state
				.display_timestamps
				.partition_point(|point| point.ticks < timestamp)
		};
		if target == self.state_ref()?.display_timestamps.len() {
			return Err(Error::out_of_range(
				"video seek found no display frame at the requested timestamp",
			));
		}
		self.rebuild_to_index(target, false)
	}

	/// Present the most recent indexed frame at or before a track timestamp.
	///
	/// This is the seek policy for an external audio clock: choosing the first
	/// frame after the requested time would display future video early. A
	/// timestamp before the first frame selects that first frame. Unindexed
	/// streams can only be rewound to zero.
	pub fn seek_at_or_before(&mut self, timestamp: u64) -> Result<()> {
		let state = self.state_ref()?;
		if !state.indexed {
			return if timestamp == 0 {
				self.seek(0)
			} else {
				Err(Error::missing_capability(
					"timestamp seeking requires an indexed video source",
				))
			};
		}
		let target = display_index_at_or_before(&state.display_timestamps, timestamp)
			.ok_or_else(|| Error::data_loss("video source has no indexed display frames"))?;
		self.seek_frame(
			u64::try_from(target).map_err(|_| Error::out_of_range("video display index exceeds u64"))?,
		)
	}

	/// Seek to an exact zero-based display-order frame.
	///
	/// A retained target is presented without decoding. Otherwise the player
	/// seeks to a bounded preceding presentation window and rebuilds decoder
	/// state through the requested frame.
	pub fn seek_frame(&mut self, index: u64) -> Result<()> {
		if !self.state_ref()?.indexed {
			return Err(Error::missing_capability(
				"frame seeking requires an indexed video source",
			));
		}
		let target =
			usize::try_from(index).map_err(|_| Error::out_of_range("video frame index exceeds usize"))?;
		if target >= self.state_ref()?.display_timestamps.len() {
			return Err(Error::out_of_range(
				"video frame index is outside the display sequence",
			));
		}
		if self.state_ref()?.display_index == index || self.present_cached(index)? {
			return Ok(());
		}
		self.rebuild_to_index(target, false)
	}

	/// Rewind and present the first frame.
	pub fn reset(&mut self) -> Result<()> {
		self.seek(0)
	}

	/// End the current decode sequence and discard delayed frames.
	///
	/// Playback becomes done until [`seek`](Self::seek) or [`reset`](Self::reset)
	/// establishes a new random-access boundary.
	pub fn flush(&mut self) -> Result<usize> {
		let state = self.state_mut()?;
		let discarded = state.decoder.flush()?.len() + state.drained.len();
		state.drained.clear();
		Self::clear_presentation_cache(state);
		state.done = true;
		state.accumulator = Duration::ZERO;
		Ok(discarded)
	}

	/// Explicitly release decoder and demuxer state. A second close is harmless.
	pub fn close(&mut self) {
		if let Some(mut state) = self.state.take() {
			state.decoder.close();
			state.demuxer.close();
		}
	}

	/// Resume time-paced playback.
	pub fn play(&mut self) -> Result<()> {
		self.state_mut()?.playing = true;
		Ok(())
	}

	/// Pause time-paced playback and discard fractional accumulated time.
	pub fn pause(&mut self) -> Result<()> {
		let state = self.state_mut()?;
		state.playing = false;
		state.accumulator = Duration::ZERO;
		Ok(())
	}

	/// Toggle time-paced playback.
	pub fn toggle_play(&mut self) -> Result<()> {
		let state = self.state_mut()?;
		state.playing = !state.playing;
		if !state.playing {
			state.accumulator = Duration::ZERO;
		}
		Ok(())
	}

	/// Change end-of-stream looping policy.
	pub fn set_looping(&mut self, looping: bool) -> Result<()> {
		self.state_mut()?.config.loop_playback = looping;
		Ok(())
	}

	/// Borrow the currently presented frame.
	pub fn current_frame(&self) -> Result<&VideoFrame> {
		self
			.state_ref()?
			.current
			.as_ref()
			.ok_or_else(|| Error::failed_precondition("VideoPlayer has no current frame"))
	}

	/// Timestamp at which the next display frame may replace the current one.
	///
	/// Indexed containers use the next frame's PTS, which respects variable
	/// frame rate and gaps. Sequential sources use the current frame's declared
	/// end; an unknown duration cannot be paced by an external clock.
	/// `None` means the indexed stream has no further display frame.
	pub fn next_presentation_boundary(&self) -> Result<Option<Duration>> {
		let state = self.state_ref()?;
		if state.indexed {
			let next = state
				.display_index
				.checked_add(1)
				.ok_or_else(|| Error::out_of_range("video display index overflowed"))?;
			let next = usize::try_from(next)
				.map_err(|_| Error::out_of_range("video display index exceeds usize"))?;
			return Ok(
				state
					.display_timestamps
					.get(next)
					.map(|point| point.duration),
			);
		}
		let timing = self.current_frame()?.timing();
		let duration = timing.duration().ok_or_else(|| {
			Error::missing_capability(
				"unindexed video requires known frame durations for clocked playback",
			)
		})?;
		let boundary = timing
			.presentation_timestamp()
			.checked_add(duration)
			.ok_or_else(|| Error::out_of_range("video presentation time overflowed"))?;
		Ok(Some(boundary))
	}

	/// Return the absolute zero-based display index in the selected track.
	pub fn current_frame_index(&self) -> Result<u64> {
		Ok(self.state_ref()?.display_index)
	}

	/// Return selected stream metadata while open.
	pub fn info(&self) -> Option<VideoContainerInfo> {
		self.state.as_ref().map(|state| state.info)
	}

	/// Return a snapshot of playback counters while open.
	pub fn stats(&self) -> Option<VideoPlayerStats> {
		self.state.as_ref().map(|state| state.stats)
	}

	/// Return whether time-paced playback is enabled.
	pub fn is_playing(&self) -> bool {
		self.state.as_ref().is_some_and(|state| state.playing)
	}

	/// Return whether a non-looping stream has presented its final frame.
	pub fn is_done(&self) -> bool {
		self.state.as_ref().is_none_or(|state| state.done)
	}

	/// Return whether the player still owns its sessions.
	pub const fn is_open(&self) -> bool {
		self.state.is_some()
	}

	fn advance_one(&mut self) -> Result<bool> {
		let cached_target = {
			let state = self.state_ref()?;
			state
				.display_index
				.checked_add(1)
				.filter(|next| *next < state.next_display_index)
		};
		if let Some(target) = cached_target {
			if self.present_cached(target)? {
				return Ok(true);
			}
			self.record_cache_miss()?;
			self.replay_to_index(target)?;
			return Ok(true);
		}
		self.advance_decoded_one()
	}

	fn advance_decoded_one(&mut self) -> Result<bool> {
		loop {
			let state = self.state_mut()?;
			if let Some(frame) = state.drained.pop_front() {
				Self::present_new(state, frame)?;
				if state.drained.is_empty() && state.demuxer.is_eos() && !state.config.loop_playback {
					state.done = true;
				}
				return Ok(true);
			}
			if state.done {
				return Ok(false);
			}
			match state.demuxer.read_next_packet()? {
				Some(packet) => {
					state.stats.decoded_packets =
						state.stats.decoded_packets.checked_add(1).ok_or_else(|| {
							Error::resource_exhausted("video decoded-packet counter overflowed")
						})?;
					let frame = match state.output {
						PlayerOutput::HostPlanar => state.decoder.decode(&packet)?,
						PlayerOutput::Native => state.decoder.decode_native(&packet)?,
					};
					if let Some(frame) = frame {
						Self::present_new(state, frame)?;
						return Ok(true);
					}
				}
				None => {
					state.drained.extend(state.decoder.flush()?);
					if !state.drained.is_empty() {
						continue;
					}
					if !state.config.loop_playback {
						state.done = true;
						return Ok(false);
					}
					state.demuxer.seek(0)?;
					state.stats.loop_restarts = state
						.stats
						.loop_restarts
						.checked_add(1)
						.ok_or_else(|| Error::resource_exhausted("video loop counter overflowed"))?;
					state.stats.seek_resets = state
						.stats
						.seek_resets
						.checked_add(1)
						.ok_or_else(|| Error::resource_exhausted("video seek counter overflowed"))?;
					state.display_index = 0;
					state.next_display_index = 0;
					Self::clear_presentation_cache(state);
				}
			}
		}
	}

	fn present_new(state: &mut PlayerState, frame: VideoFrame) -> Result<()> {
		if !state.indexed {
			let index = state.next_display_index;
			state.next_display_index = index
				.checked_add(1)
				.ok_or_else(|| Error::resource_exhausted("video display index overflowed"))?;
			state.current = Some(frame);
			state.display_index = index;
			state.stats.presented_frames = state
				.stats
				.presented_frames
				.checked_add(1)
				.ok_or_else(|| Error::resource_exhausted("video presented-frame counter overflowed"))?;
			return Ok(());
		}
		let minimum = usize::try_from(state.next_display_index)
			.map_err(|_| Error::out_of_range("video display index exceeds usize"))?;
		let timestamp = frame.timing().presentation_timestamp();
		let remaining = state.display_timestamps.get(minimum..).ok_or_else(|| {
			Error::data_loss("video decoder advanced beyond the container display index")
		})?;
		let relative = remaining.partition_point(|point| point.duration < timestamp);
		let resolved = minimum
			.checked_add(relative)
			.ok_or_else(|| Error::out_of_range("video display index overflowed"))?;
		let Some(point) = state.display_timestamps.get(resolved) else {
			return Err(Error::data_loss(
				"decoded frame timestamp is absent from the container display index",
			));
		};
		if point.duration != timestamp {
			return Err(Error::data_loss(
				"decoded frame timestamp does not match the container display index",
			));
		}
		let index = u64::try_from(resolved)
			.map_err(|_| Error::out_of_range("video display index exceeds u64"))?;
		state.current = Some(frame.clone());
		state.display_index = index;
		state.next_display_index = index
			.checked_add(1)
			.ok_or_else(|| Error::resource_exhausted("video display index overflowed"))?;
		state.stats.presented_frames = state
			.stats
			.presented_frames
			.checked_add(1)
			.ok_or_else(|| Error::resource_exhausted("video presented-frame counter overflowed"))?;
		Self::retain_presentation(state, index, frame)?;
		Ok(())
	}

	fn present_cached(&mut self, index: u64) -> Result<bool> {
		let state = self.state_mut()?;
		let Some(frame) = state
			.presentation_cache
			.iter()
			.find(|entry| entry.index == index)
			.map(|entry| entry.frame.clone())
		else {
			return Ok(false);
		};
		state.current = Some(frame);
		state.display_index = index;
		state.done = false;
		state.stats.presented_frames = state
			.stats
			.presented_frames
			.checked_add(1)
			.ok_or_else(|| Error::resource_exhausted("video presented-frame counter overflowed"))?;
		state.stats.presentation_cache_hits = state
			.stats
			.presentation_cache_hits
			.checked_add(1)
			.ok_or_else(|| Error::resource_exhausted("video cache-hit counter overflowed"))?;
		Ok(true)
	}

	fn record_cache_miss(&mut self) -> Result<()> {
		let state = self.state_mut()?;
		state.stats.presentation_cache_misses = state
			.stats
			.presentation_cache_misses
			.checked_add(1)
			.ok_or_else(|| Error::resource_exhausted("video cache-miss counter overflowed"))?;
		Ok(())
	}

	fn replay_to_index(&mut self, target: u64) -> Result<()> {
		let target = usize::try_from(target)
			.map_err(|_| Error::out_of_range("video replay index exceeds usize"))?;
		self.rebuild_to_index(target, true)
	}

	fn rebuild_to_index(&mut self, target: usize, replay: bool) -> Result<()> {
		let timestamp = {
			let state = self.state_ref()?;
			let history = state.stats.presentation_cache_capacity.max(1);
			let seek_start = target.saturating_add(1).saturating_sub(history);
			state
				.display_timestamps
				.get(seek_start)
				.ok_or_else(|| Error::out_of_range("video rebuild index is outside the stream"))?
				.ticks
		};
		{
			let state = self.state_mut()?;
			state.decoder.flush()?;
			state.demuxer.seek(timestamp)?;
			state.drained.clear();
			Self::clear_presentation_cache(state);
			state.current = None;
			state.accumulator = Duration::ZERO;
			state.done = false;
			state.display_index = 0;
			state.next_display_index = 0;
			state.stats.seek_resets = state
				.stats
				.seek_resets
				.checked_add(1)
				.ok_or_else(|| Error::resource_exhausted("video seek counter overflowed"))?;
		}
		loop {
			if !self.advance_decoded_one()? {
				return Err(Error::data_loss(
					"video rebuild ended before the requested display frame",
				));
			}
			let current = {
				let state = self.state_mut()?;
				if replay {
					state.stats.seek_replay_frames = state
						.stats
						.seek_replay_frames
						.checked_add(1)
						.ok_or_else(|| Error::resource_exhausted("video replay counter overflowed"))?;
				}
				usize::try_from(state.display_index)
					.map_err(|_| Error::out_of_range("video display index exceeds usize"))?
			};
			if current == target {
				return Ok(());
			}
			if current > target {
				return Err(Error::data_loss(
					"video rebuild skipped the requested display frame",
				));
			}
		}
	}

	fn retain_presentation(state: &mut PlayerState, index: u64, frame: VideoFrame) -> Result<()> {
		let Some(bytes) = frame.as_yuv420p().map(<[u8]>::len) else {
			return Ok(());
		};
		if state.stats.presentation_cache_capacity == 0
			|| state.config.presentation_cache_bytes == 0
			|| bytes > state.config.presentation_cache_bytes
		{
			return Ok(());
		}
		state.presentation_cache_bytes = state
			.presentation_cache_bytes
			.checked_add(bytes)
			.ok_or_else(|| Error::resource_exhausted("video cache byte count overflowed"))?;
		state.presentation_cache.push_back(CachedPresentation {
			index,
			frame,
			bytes,
		});
		while state.presentation_cache.len() > state.stats.presentation_cache_capacity
			|| state.presentation_cache_bytes > state.config.presentation_cache_bytes
		{
			let evicted = state
				.presentation_cache
				.pop_front()
				.ok_or_else(|| Error::internal("video presentation cache accounting diverged"))?;
			state.presentation_cache_bytes -= evicted.bytes;
		}
		state.stats.presentation_cache_resident = state.presentation_cache.len();
		Ok(())
	}

	fn clear_presentation_cache(state: &mut PlayerState) {
		state.presentation_cache.clear();
		state.presentation_cache_bytes = 0;
		state.stats.presentation_cache_resident = 0;
	}

	fn state_ref(&self) -> Result<&PlayerState> {
		self
			.state
			.as_ref()
			.ok_or_else(|| Error::failed_precondition("VideoPlayer is closed"))
	}

	fn state_mut(&mut self) -> Result<&mut PlayerState> {
		self
			.state
			.as_mut()
			.ok_or_else(|| Error::failed_precondition("VideoPlayer is closed"))
	}
}

fn ticks_to_duration(ticks: u64, info: VideoContainerInfo) -> Result<Duration> {
	let time_base = info.time_base();
	let nanos = u128::from(ticks)
		.checked_mul(u128::from(time_base.numerator()))
		.and_then(|value| value.checked_mul(1_000_000_000))
		.ok_or_else(|| Error::out_of_range("video player timestamp overflows nanoseconds"))?
		/ u128::from(time_base.denominator());
	let seconds = u64::try_from(nanos / 1_000_000_000)
		.map_err(|_| Error::out_of_range("video player timestamp exceeds Duration"))?;
	let subsec_nanos = u32::try_from(nanos % 1_000_000_000)
		.map_err(|_| Error::out_of_range("video player timestamp remainder exceeds u32"))?;
	Ok(Duration::new(seconds, subsec_nanos))
}

fn display_index_at_or_before(points: &[DisplayTimestamp], ticks: u64) -> Option<usize> {
	let last = points.get(
		points
			.partition_point(|point| point.ticks <= ticks)
			.saturating_sub(1),
	)?;
	Some(points.partition_point(|point| point.ticks < last.ticks))
}