Skip to main content

moq_audio/decode/
backpressure.rs

1use std::time::Duration;
2
3use kio::clock::Instant;
4
5/// Decides when [`Consumer::read`](super::Consumer::read) decodes a packet, which is how a
6/// player splits its playout delay between decoded PCM in its playback ring and encoded
7/// media held in the consumer.
8///
9/// The ring holds the floor as PCM. The rest of the delay, the hold, stays encoded, so
10/// memory follows the bytes actually received rather than the delay. The consumer keeps
11/// reading packets as they arrive, so its delay estimate still times each one, and
12/// decodes a packet at `timestamp`:
13///
14///   - once the media queued behind it covers the hold, or nothing more continues it
15///     (a gap, a declared end, or the track's end is queued after it). A backlog past
16///     the delay still reaches the ring this way, to be caught up;
17///   - while the playhead is known, also once it is within the floor of where the
18///     packet's output ends, keeping the ring on its floor when the network runs late.
19///
20/// With no hold every packet decodes at once and the ring bounds itself. The playhead is
21/// unknown until the first [`observe`](Self::observe), and again after each gap or end
22/// the consumer hands over, until an observation lands past it.
23///
24/// Dropping the handle stops the gating, decoding every packet as it arrives.
25pub struct Backpressure {
26	state: kio::Producer<State>,
27}
28
29#[derive(Debug, Default)]
30pub(super) struct State {
31	pub floor: Duration,
32	pub hold: Duration,
33	/// Media at the first value sounds at the second, advancing in real time from there.
34	pub playhead: Option<(Duration, Instant)>,
35	/// Bumped on every update, so a waiting read notices one.
36	pub version: u64,
37}
38
39impl Backpressure {
40	pub(super) fn new() -> (Self, kio::Consumer<State>) {
41		let state = kio::Producer::new(State::default());
42		let consumer = state.consume();
43		(Self { state }, consumer)
44	}
45
46	/// Split the playout delay: up to `floor` decoded in the ring, and `hold` past it encoded.
47	pub fn set_latency(&self, floor: Duration, hold: Duration) {
48		self.update(|state| {
49			state.floor = floor;
50			state.hold = hold;
51		});
52	}
53
54	/// Note that media at `timestamp`, on the consumer's timeline, sounds at `at`.
55	/// An unscaled timestamp carries no time, so it is ignored.
56	pub fn observe(&self, timestamp: moq_net::Timestamp, at: Instant) {
57		if let Ok(timestamp) = Duration::try_from(timestamp) {
58			self.update(|state| state.playhead = Some((timestamp, at)));
59		}
60	}
61
62	fn update(&self, f: impl FnOnce(&mut State)) {
63		if let Ok(mut state) = self.state.write() {
64			f(&mut state);
65			state.version += 1;
66		}
67	}
68}
69
70impl std::fmt::Debug for Backpressure {
71	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72		f.debug_struct("Backpressure").finish_non_exhaustive()
73	}
74}