Skip to main content

oa/media/
player.rs

1//! Audio-clocked transport for independently owned audio and video sessions.
2
3use std::{
4	path::{Path, PathBuf},
5	time::{Duration, Instant},
6};
7
8pub use crate::media::types::MediaPlayerConfig;
9use crate::{
10	AudioPlayer, Error, LogComponent, LogLevel, Result, Runtime, VideoFrame, VideoPlayer,
11	audio::AudioPlayerConfig,
12	video::{
13		Mp4TrackEdit, VideoContainerInfo, VideoContainerKind, VideoPlayerConfig, mp4_track_edits,
14	},
15};
16
17use super::clock::TrackTimeline;
18
19impl MediaPlayerConfig {
20	pub fn new(video_path: impl Into<PathBuf>, audio_path: impl Into<PathBuf>) -> Self {
21		Self {
22			video_path: video_path.into(),
23			audio_path: audio_path.into(),
24			audio_ring_milliseconds: 500,
25		}
26	}
27
28	/// Decode the video and default audio tracks of the same local container.
29	pub fn embedded(path: impl Into<PathBuf>) -> Self {
30		let path = path.into();
31		Self::new(path.clone(), path)
32	}
33}
34
35/// Synchronized playback session over independent audio and video owners.
36///
37/// The caller ticks video on the Runtime-owning thread. During the audio segment,
38/// the device output clock paces decoded video. The host clock covers silent
39/// lead-in and the tail after audio drains. A presented native frame retains its
40/// decoder backing until it is replaced and any external GPU consumers retire.
41pub struct MediaPlayer {
42	audio: Option<AudioPlayer>,
43	video: VideoPlayer,
44	video_timeline: TrackTimeline,
45	audio_timeline: TrackTimeline,
46	duration: Duration,
47	position: Duration,
48	last_tick: Option<Instant>,
49	audio_active: bool,
50	audio_needs_seek: bool,
51	looping: bool,
52	done: bool,
53}
54
55impl MediaPlayer {
56	/// Open both tracks paused, with the first video frame decoded.
57	///
58	/// # Errors
59	///
60	/// Requires a supported video stream, both track sources, and an audio
61	/// output configuration that can play the selected PCM.
62	pub fn open(runtime: &Runtime, config: MediaPlayerConfig) -> Result<Self> {
63		if config.video_path.as_os_str().is_empty() || config.audio_path.as_os_str().is_empty() {
64			return Err(Error::invalid_argument(
65				"MediaPlayer requires both track paths",
66			));
67		}
68		let video = open_video_track(runtime, &config.video_path)?;
69		let audio_config = AudioPlayerConfig {
70			uri: config.audio_path,
71			loop_playback: false,
72			ring_milliseconds: config.audio_ring_milliseconds,
73		};
74		let embedded = audio_config.uri == config.video_path;
75		let audio = if embedded {
76			AudioPlayer::open_embedded(runtime, audio_config)?
77				.ok_or_else(|| Error::not_found("MediaPlayer source has no audio track"))?
78		} else {
79			AudioPlayer::open(runtime, audio_config)?
80		};
81		Self::compose(&config.video_path, video, Some(audio), embedded)
82	}
83
84	pub(crate) fn open_viewer(runtime: &Runtime, path: &Path) -> Result<Self> {
85		let mut video = open_video_track(runtime, path)?;
86		if crate::EnvFlag::is_set("OA_VIEWER_YUV_CANVAS") {
87			video.enable_canvas_yuv()?;
88		}
89		// MPEG-TS is an unindexed sequential video path. The current Audio
90		// probe supports embedded PCM sources through MP4 and Matroska/WebM.
91		let info = video
92			.info()
93			.ok_or_else(|| Error::internal("video track failed to open"))?;
94		let audio = if info.kind() == VideoContainerKind::MpegTs {
95			None
96		} else {
97			match AudioPlayer::open_embedded(runtime, AudioPlayerConfig::new(path)) {
98				Ok(audio) => audio,
99				Err(error) => {
100					runtime.log(
101						LogLevel::Warn,
102						LogComponent::AUDIO,
103						format!("Viewer audio unavailable: {error}"),
104					)?;
105					None
106				}
107			}
108		};
109		Self::compose(path, video, audio, true)
110	}
111
112	fn compose(
113		path: &Path,
114		mut video: VideoPlayer,
115		audio: Option<AudioPlayer>,
116		embedded: bool,
117	) -> Result<Self> {
118		let info = video
119			.info()
120			.ok_or_else(|| Error::internal("video track failed to open"))?;
121		let [video_edit, audio_edit] = if embedded && info.kind() == VideoContainerKind::Mp4 {
122			mp4_track_edits(
123				path,
124				[
125					Some(info.track_id()),
126					audio.as_ref().map(AudioPlayer::track_id),
127				],
128			)?
129		} else {
130			[Mp4TrackEdit::default(); 2]
131		};
132		let video_edit = if info.kind() == VideoContainerKind::MpegTs {
133			Mp4TrackEdit {
134				media_start: video.current_frame()?.timing().presentation_timestamp(),
135				..video_edit
136			}
137		} else {
138			video_edit
139		};
140		let video_timeline = TrackTimeline::new(video_edit, video.duration()?)?;
141		let audio_duration = audio.as_ref().map_or(Duration::ZERO, |audio| {
142			Duration::from_micros(audio.duration_us())
143		});
144		let audio_timeline = TrackTimeline::new(audio_edit, audio_duration)?;
145		if let (Some(audio), Some(length)) = (&audio, audio_edit.length) {
146			audio.set_playback_end_us(micros(
147				audio_edit
148					.media_start
149					.checked_add(length)
150					.ok_or_else(|| Error::out_of_range("audio edit end exceeds Duration"))?,
151			));
152		}
153		if info.kind() != VideoContainerKind::MpegTs && !video_edit.media_start.is_zero() {
154			video.seek_time_at_or_before(video_edit.media_start)?;
155		}
156		Ok(Self {
157			audio,
158			video,
159			video_timeline,
160			audio_timeline,
161			duration: video_timeline.end.max(audio_timeline.end),
162			position: Duration::ZERO,
163			last_tick: None,
164			audio_active: false,
165			audio_needs_seek: true,
166			looping: false,
167			done: false,
168		})
169	}
170
171	pub fn play(&mut self) -> Result<()> {
172		self.require_open()?;
173		if self.is_playing() {
174			return Ok(());
175		}
176		if self.done {
177			self.seek_us(0)?;
178		}
179		self.start_audio()?;
180		self.video.play()?;
181		self.last_tick = Some(Instant::now());
182		Ok(())
183	}
184
185	pub fn pause(&mut self) -> Result<()> {
186		self.require_open()?;
187		if let Some(audio) = &self.audio {
188			audio.pause();
189		}
190		self.audio_active = false;
191		self.last_tick = None;
192		self.video.pause()
193	}
194
195	/// Advance up to `max_frames` display frames reached by the playback clock.
196	///
197	/// # Errors
198	///
199	/// Returns an error after close, for a zero budget, or on decoder or device
200	/// failure. The transport pauses on a playback failure.
201	pub fn tick(&mut self, max_frames: u32) -> Result<u32> {
202		self.require_open()?;
203		if max_frames == 0 {
204			return Err(Error::invalid_argument(
205				"MediaPlayer tick budget must be positive",
206			));
207		}
208		let Some(previous) = self.last_tick else {
209			return Ok(0);
210		};
211		let now = Instant::now();
212		self.last_tick = Some(now);
213		let elapsed = now.saturating_duration_since(previous);
214		let result = self.advance_to_clock(elapsed, max_frames);
215		if result.is_err() {
216			let _ = self.pause();
217		}
218		result
219	}
220
221	fn advance_to_clock(&mut self, elapsed: Duration, budget: u32) -> Result<u32> {
222		if let Some(audio) = &self.audio {
223			audio.check_playback()?;
224		}
225		let previous = self.position;
226		if self.audio_active {
227			let audio = self
228				.audio
229				.as_ref()
230				.ok_or_else(|| Error::internal("active media clock has no audio source"))?;
231			let audible = audio.audible_position_us();
232			self.position = self
233				.position
234				.max(self.audio_timeline.movie_at(Duration::from_micros(audible)));
235			if audio.is_eos() && audible >= audio.position_us() {
236				self.audio_active = false;
237			}
238		} else {
239			self.position = self.position.saturating_add(elapsed);
240			if self.audio_needs_seek
241				&& self.audio.is_some()
242				&& previous < self.audio_timeline.start
243				&& self.position >= self.audio_timeline.start
244			{
245				self.position = self.audio_timeline.start;
246				self.start_audio()?;
247			}
248		}
249		if !self.is_seekable() {
250			// TS has no indexed end. Pace from the audible clock while sound
251			// plays, then let the host clock carry any remaining video.
252			let advanced = self
253				.video
254				.tick_bounded(self.position.saturating_sub(previous), budget)?;
255			if self.video.is_done() && !self.audio_active {
256				self.finish()?;
257			}
258			return Ok(advanced);
259		}
260		if !self.duration.is_zero() {
261			self.position = self.position.min(self.duration);
262		}
263		let mut advanced = 0;
264		let video_position = self.position.min(self.video_timeline.end);
265		while advanced < budget && !self.video.is_done() {
266			let Some(next) = self.video.next_presentation_boundary()? else {
267				break;
268			};
269			if self.video_timeline.movie_at(next) > video_position
270				|| self.video_timeline.is_past_end(next)
271				|| !self.video.advance_for_playback()?
272			{
273				break;
274			}
275			advanced += 1;
276		}
277		let audio_drained = !self.audio_active;
278		if advanced < budget && self.position >= self.duration && audio_drained {
279			self.finish()?;
280		}
281		Ok(advanced)
282	}
283
284	fn start_audio(&mut self) -> Result<()> {
285		if let Some(audio) = &mut self.audio
286			&& self.audio_timeline.contains(self.position)
287		{
288			if self.audio_needs_seek {
289				let position = micros(self.audio_timeline.media_at(self.position));
290				if position != 0 || audio.position_us() != 0 || audio.is_eos() {
291					audio.seek(position)?;
292				}
293				self.audio_needs_seek = false;
294			}
295			if !audio.is_eos() {
296				audio.play()?;
297				self.audio_active = true;
298			}
299		}
300		Ok(())
301	}
302
303	fn finish(&mut self) -> Result<()> {
304		if self.looping {
305			self.seek_us(0)?;
306		} else {
307			self.pause()?;
308			self.done = true;
309		}
310		Ok(())
311	}
312
313	/// Seek to a movie timestamp, selecting the video frame at or before it.
314	/// While paused, the audio decoder is repositioned once on resume.
315	///
316	/// # Errors
317	///
318	/// Returns an error when video seeking fails or active audio cannot resume
319	/// at the new position. The transport stays paused on failure.
320	pub fn seek_us(&mut self, timestamp_us: u64) -> Result<()> {
321		self.require_open()?;
322		if timestamp_us != 0 && !self.is_seekable() {
323			return Err(Error::missing_capability(
324				"seeking requires an indexed media source",
325			));
326		}
327		let resume = self.is_playing();
328		self.pause()?;
329		let target = Duration::from_micros(timestamp_us).min(self.duration);
330		let raw = self.video_timeline.media_at(target);
331		if !self.is_seekable() {
332			self.video.reset()?;
333		} else if let Err(error) = self.video.seek_time_at_or_before(raw) {
334			let previous = self.video_timeline.media_at(self.position);
335			if let Err(restore) = self.video.seek_time_at_or_before(previous) {
336				self.video.close();
337				return Err(Error::with_kind(
338					error.kind(),
339					format!(
340						"media seek failed ({error}) and the previous frame could not be restored ({restore})"
341					),
342				));
343			}
344			self.audio_needs_seek = true;
345			return Err(error);
346		}
347		self.position = target;
348		self.audio_needs_seek = true;
349		self.done = false;
350		if resume {
351			self.play()?;
352		}
353		Ok(())
354	}
355
356	pub(crate) fn step_frames(&mut self, steps: i32) -> Result<()> {
357		self.pause()?;
358		if steps < 0 && !self.is_seekable() {
359			return Ok(());
360		}
361		self.video.step_frames(steps)?;
362		let pts = self.current_frame()?.timing().presentation_timestamp();
363		self.position = self.video_timeline.movie_at(pts);
364		self.audio_needs_seek = true;
365		self.done = self.video.is_done() && !self.is_seekable();
366		Ok(())
367	}
368
369	pub fn current_frame(&self) -> Result<&VideoFrame> {
370		self.video.current_frame()
371	}
372
373	pub(crate) fn current_viewer_frame(&mut self) -> Result<Option<VideoFrame>> {
374		let pts = self.current_frame()?.timing().presentation_timestamp();
375		if self.is_seekable() && self.video_timeline.movie_at(pts) > self.position {
376			return Ok(None);
377		}
378		self.video.prepare_viewer_frame().map(Some)
379	}
380
381	pub fn position_us(&self) -> Result<u64> {
382		self.require_open()?;
383		Ok(micros(self.position))
384	}
385
386	pub(crate) fn duration_us(&self) -> u64 {
387		if self.is_seekable() {
388			micros(self.duration)
389		} else {
390			0
391		}
392	}
393
394	pub(crate) fn info(&self) -> Option<VideoContainerInfo> {
395		self.video.info()
396	}
397
398	pub(crate) fn audio(&self) -> Option<&AudioPlayer> {
399		self.audio.as_ref()
400	}
401
402	pub(crate) fn set_looping(&mut self, looping: bool) {
403		self.looping = looping;
404	}
405
406	pub fn is_playing(&self) -> bool {
407		self.last_tick.is_some()
408	}
409
410	pub fn is_done(&self) -> bool {
411		self.done || !self.video.is_open()
412	}
413
414	pub fn close(&mut self) -> Result<()> {
415		self.last_tick = None;
416		self.video.close();
417		self.audio.take().map_or(Ok(()), |mut audio| audio.close())
418	}
419
420	fn require_open(&self) -> Result<()> {
421		if self.video.is_open() {
422			Ok(())
423		} else {
424			Err(Error::failed_precondition("MediaPlayer is closed"))
425		}
426	}
427
428	fn is_seekable(&self) -> bool {
429		self
430			.info()
431			.is_some_and(|info| info.kind() != VideoContainerKind::MpegTs)
432	}
433}
434
435fn open_video_track(runtime: &Runtime, path: &Path) -> Result<VideoPlayer> {
436	VideoPlayer::new_native(
437		runtime,
438		path,
439		VideoPlayerConfig {
440			loop_playback: false,
441			start_playing: false,
442			..VideoPlayerConfig::default()
443		},
444	)
445}
446
447fn micros(duration: Duration) -> u64 {
448	u64::try_from(duration.as_micros()).unwrap_or(u64::MAX)
449}