Skip to main content

moq_net/model/
bandwidth.rs

1//! Rate estimation, split into a [Producer] and [Consumer] handle.
2//!
3//! A [Producer] is used to set the current estimated bitrate, notifying consumers.
4//! A [Consumer] can read the current estimate and wait for changes.
5//! A [Demand] watches whether anyone reads it, so a producer estimates only on demand.
6//!
7//! One estimate covers a whole connection, so senders sharing one divide it with
8//! an [Allocator] rather than each targeting the whole thing. How a sender then
9//! *follows* its share is shared media policy: see `moq_mux::rate`.
10//!
11//! The same reservations set the connection's probe target: their ceilings summed,
12//! which the session hands to its transport's [`Probe`](crate::transport::Probe) so
13//! the estimate can rise to fund them.
14//!
15//! The receive direction mirrors it: [Viewers] divides the receive estimate among the
16//! broadcasts watched over one connection, and their ceilings summed are the PROBE
17//! target the session asks its peer to probe up to.
18//!
19//! A [Limit] is the other side: a live [Cap] an embedder puts on one session's media,
20//! which a gateway enforces however its protocol allows.
21
22use std::{
23	collections::BTreeMap,
24	sync::{
25		Arc,
26		atomic::{AtomicU64, Ordering},
27	},
28	task::{Poll, Wake, Waker},
29};
30
31use crate::{BoundsExceeded, Error, Result, track};
32
33/// A rate, in bits per second.
34///
35/// A newtype rather than a bare integer because everything that meets in an
36/// [`Allocator`] is the same quantity measured the same way: a congestion
37/// controller's estimate, a track's reservation, an encoder's ceiling. One of them
38/// reading bytes per second, or kilobits, is off by a factor of eight or a thousand
39/// and still typechecks, which is the kind of wrong that reaches production.
40///
41/// Named for what it measures rather than for the module: `Session::stats` has called
42/// this quantity a rate all along (`estimated_send_rate`).
43#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub struct Rate(u64);
45
46impl Rate {
47	/// No bandwidth at all.
48	pub const ZERO: Self = Self(0);
49
50	/// A rate in bits per second, the unit every wire and codec API here uses.
51	pub const fn from_bps(bps: u64) -> Self {
52		Self(bps)
53	}
54
55	/// A rate in kilobits (1000 bits) per second, saturating.
56	pub const fn from_kbps(kbps: u64) -> Self {
57		Self(kbps.saturating_mul(1_000))
58	}
59
60	/// A rate in megabits (1000 kilobits) per second, saturating.
61	pub const fn from_mbps(mbps: u64) -> Self {
62		Self(mbps.saturating_mul(1_000_000))
63	}
64
65	/// This rate in bits per second, for handing to a codec or FFI that wants a plain integer.
66	pub const fn as_bps(self) -> u64 {
67		self.0
68	}
69
70	/// This rate scaled by `factor`, saturating at both ends.
71	///
72	/// For fractional arithmetic, such as halving a rate, without spreading `as`
73	/// casts across the callers.
74	pub fn scaled(self, factor: f64) -> Self {
75		let scaled = self.0 as f64 * factor.max(0.0);
76		if scaled >= u64::MAX as f64 {
77			Self(u64::MAX)
78		} else {
79			Self(scaled as u64)
80		}
81	}
82
83	/// The absolute difference between two rates.
84	pub const fn abs_diff(self, other: Self) -> Self {
85		Self(self.0.abs_diff(other.0))
86	}
87}
88
89/// A rate cap: the sustained rate media may arrive or leave at, and the burst above it.
90///
91/// What it counts is up to whoever enforces it: a WebRTC ingest counts depacketized media
92/// payload, leaving RTP, SRTP, and UDP overhead outside it.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94#[non_exhaustive]
95pub struct Cap {
96	/// The sustained rate.
97	pub rate: Rate,
98	/// How far ahead of `rate` media may run, as time at `rate`. Defaults to
99	/// [`Cap::DEFAULT_BURST`], as on QUIC.
100	pub burst: std::time::Duration,
101}
102
103impl Cap {
104	/// About one second of the cap.
105	pub const DEFAULT_BURST: std::time::Duration = std::time::Duration::from_secs(1);
106
107	/// A cap at `rate` with the default burst.
108	pub const fn new(rate: Rate) -> Self {
109		Self {
110			rate,
111			burst: Self::DEFAULT_BURST,
112		}
113	}
114
115	/// This cap with a burst of `burst` at its rate.
116	pub const fn with_burst(mut self, burst: std::time::Duration) -> Self {
117		self.burst = burst;
118		self
119	}
120}
121
122impl From<Rate> for Cap {
123	fn from(rate: Rate) -> Self {
124		Self::new(rate)
125	}
126}
127
128/// A live cap for one session, uncapped while it holds `None`.
129///
130/// Clones share the cap, so an embedder keeps one and hands another to the session, which
131/// follows each [`set`](Self::set) at once. [`Default`] is uncapped.
132pub struct Limit {
133	cap: kio::Producer<Option<Cap>>,
134	/// The cap [`poll_changed`](Self::poll_changed) last reported through this handle.
135	last: Option<Cap>,
136}
137
138impl Limit {
139	/// A handle starting at `cap`, or uncapped for `None`.
140	pub fn new(cap: impl Into<Option<Cap>>) -> Self {
141		let cap = cap.into();
142		Self {
143			cap: kio::Producer::new(cap),
144			last: cap,
145		}
146	}
147
148	/// Replace the cap; `None` lifts it.
149	pub fn set(&self, cap: impl Into<Option<Cap>>) {
150		let cap = cap.into();
151		// Only a dropped producer closes the channel, and this handle is one.
152		if let Ok(mut state) = self.cap.write()
153			&& *state != cap
154		{
155			*state = cap;
156		}
157	}
158
159	/// The current cap, if any, which [`poll_changed`](Self::poll_changed) then counts as seen.
160	pub fn get(&mut self) -> Option<Cap> {
161		self.last = *self.cap.read();
162		self.last
163	}
164
165	/// The cap once it differs from the one this handle last saw: at its creation or clone,
166	/// its last [`get`](Self::get), or its last report.
167	#[cfg_attr(feature = "async", kio::wrapper)]
168	pub fn poll_changed(&mut self, waiter: &kio::Waiter) -> Poll<Option<Cap>> {
169		let last = self.last;
170		match self.cap.poll_ref(waiter, |cap| match **cap {
171			cap if cap != last => Poll::Ready(cap),
172			_ => Poll::Pending,
173		}) {
174			Poll::Ready(Ok(cap)) => {
175				self.last = cap;
176				Poll::Ready(cap)
177			}
178			// This handle holds the producer, so the channel never closes under it.
179			Poll::Ready(Err(_)) | Poll::Pending => Poll::Pending,
180		}
181	}
182}
183
184impl Clone for Limit {
185	fn clone(&self) -> Self {
186		Self {
187			cap: self.cap.clone(),
188			last: *self.cap.read(),
189		}
190	}
191}
192
193impl Default for Limit {
194	fn default() -> Self {
195		Self::new(None)
196	}
197}
198
199impl std::fmt::Debug for Limit {
200	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201		f.debug_tuple("Limit").field(&*self.cap.read()).finish()
202	}
203}
204
205#[derive(Default)]
206struct State {
207	bitrate: Option<Rate>,
208}
209
210/// Produces bandwidth estimates, notifying consumers when the value changes.
211#[derive(Clone)]
212pub struct Producer {
213	state: kio::Producer<State>,
214}
215
216impl Producer {
217	/// Create a fresh producer with no current estimate.
218	pub fn new() -> Self {
219		Self {
220			state: kio::Producer::default(),
221		}
222	}
223
224	/// Set the current bandwidth estimate, or `None` while the backend has none.
225	pub fn set(&self, bitrate: Option<Rate>) -> Result<()> {
226		let mut state = self.state.write().map_err(|_| Error::Dropped)?;
227		if state.bitrate != bitrate {
228			state.bitrate = bitrate;
229		}
230		Ok(())
231	}
232
233	/// Create a new consumer for the bandwidth estimate.
234	pub fn consume(&self) -> Consumer {
235		Consumer {
236			inner: Inner::Whole(self.state.consume()),
237			last: None,
238			probed: false,
239		}
240	}
241
242	/// A handle that mints consumers without being one, so holding it is not demand.
243	pub fn weak(&self) -> Weak {
244		Weak(self.state.passive())
245	}
246
247	/// A watch-only handle to whether anyone reads the estimate.
248	pub fn demand(&self) -> Demand {
249		Demand {
250			state: self.state.passive(),
251			prev: None,
252		}
253	}
254
255	/// Poll for consumer presence to differ from `last`, with the new value once it does.
256	/// Errors once the channel closes.
257	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
258	pub(crate) fn poll_wanted_changed(&self, waiter: &kio::Waiter, last: bool) -> Poll<Result<bool>> {
259		self.state.poll_wanted_changed(waiter, last).map_err(|_| Error::Dropped)
260	}
261}
262
263/// A cloneable, watch-only handle to whether anyone reads a bandwidth estimate.
264///
265/// Holding it is not demand and keeps nothing open. Once every [`Producer`] is gone, its
266/// waits end with [`Error::Dropped`]. Each clone watches on its own, so its first
267/// [`poll_wanted_changed`](Self::poll_wanted_changed) reports the current value.
268pub struct Demand {
269	state: kio::ProducerPassive<State>,
270	// The value `poll_wanted_changed` last returned, or `None` before it returned any.
271	prev: Option<bool>,
272}
273
274impl Clone for Demand {
275	fn clone(&self) -> Self {
276		Self {
277			state: self.state.clone(),
278			prev: None,
279		}
280	}
281}
282
283impl Demand {
284	/// Whether the estimate is still produced and a consumer reads it right now.
285	pub fn wanted(&self) -> bool {
286		!self.state.is_closed() && self.state.wanted()
287	}
288
289	/// [`wanted`](Self::wanted) once it differs from what this handle last returned:
290	/// immediately on the first call, then on each change. Errors once every producer is gone.
291	#[cfg_attr(feature = "async", kio::wrapper)]
292	pub fn poll_wanted_changed(&mut self, waiter: &kio::Waiter) -> Poll<Result<bool>> {
293		loop {
294			if self.state.is_closed() {
295				return Poll::Ready(Err(Error::Dropped));
296			}
297			let wanted = self.state.wanted();
298			if self.prev != Some(wanted) {
299				self.prev = Some(wanted);
300				return Poll::Ready(Ok(wanted));
301			}
302			// Closing fails the wait, which errors above.
303			let _ = std::task::ready!(self.state.poll_wanted_changed(waiter, wanted));
304		}
305	}
306}
307
308impl Default for Producer {
309	fn default() -> Self {
310		Self::new()
311	}
312}
313
314/// Mints [`Consumer`]s on demand without counting as one, nor keeping the channel open.
315#[derive(Clone)]
316pub struct Weak(kio::ProducerPassive<State>);
317
318impl Weak {
319	/// A new consumer, which reports the closure once the producer is gone.
320	pub fn consume(&self) -> Consumer {
321		Consumer {
322			inner: Inner::Whole(self.0.consume()),
323			last: None,
324			probed: false,
325		}
326	}
327}
328
329/// Divides one connection's bandwidth estimate among the tracks sharing it.
330///
331/// Every sender on a connection reads the same estimate, so N senders each
332/// targeting all of it oversubscribe the uplink N times over. Register a track
333/// here and it gets a [`Consumer`] reporting only its own slice, so the slices
334/// sum to the estimate instead of each matching it.
335///
336/// Advisory, not enforced. A track that ignores its slice, or can't follow it at
337/// all (PCM audio has a fixed bitrate), still sends what it sends; the transport
338/// sheds the excess by dropping groups. Rate estimation isn't exact enough
339/// for the difference to be worth policing.
340///
341/// The reservations also set the session's probe target: the sum of every live
342/// reservation's ceiling, demanded or not, so a sender that stopped for lack of
343/// bandwidth keeps asking the connection for its room. A session probes for its own
344/// allocator, so take it from `Session::allocator` (with the `async` feature) rather
345/// than building one: an allocator from [`new`](Self::new) divides an estimate but
346/// probes for nothing.
347///
348/// Clones share one registry, so hand a clone to each sender.
349#[derive(Clone)]
350pub struct Allocator {
351	estimate: Consumer,
352	registry: kio::Producer<Registry>,
353}
354
355impl Allocator {
356	/// Divide `estimate`, with no session probing for the reservations.
357	///
358	/// For an estimate that is not a session's, such as a test's or another
359	/// reservation's slice. A session's own comes from
360	/// `Session::allocator` with the `async` feature.
361	pub fn new(estimate: Consumer) -> Self {
362		Self {
363			estimate,
364			registry: kio::Producer::default(),
365		}
366	}
367
368	/// The same registry dividing `estimate` instead, or nothing when it is `None`.
369	#[cfg(feature = "async")]
370	// Sessions follow their allocator's target; a custom session has no public way to yet.
371	pub(crate) fn with_estimate(&self, estimate: Option<Consumer>) -> Self {
372		Self {
373			estimate: estimate.unwrap_or(Consumer {
374				inner: Inner::Unavailable,
375				last: None,
376				probed: false,
377			}),
378			registry: self.registry.clone(),
379		}
380	}
381
382	/// Probe up to `target` instead of the sum of the reservations, or `None` to follow them again.
383	///
384	/// The override covers these reservations only: `Some(Rate::ZERO)` stops probing for
385	/// them, but a session still probes up to the PROBE target its peer sends, since it
386	/// probes to the larger of the two. The override is the registry's, so it holds for
387	/// every clone and across the reconnects a persistent allocator spans.
388	pub fn set_target(&self, target: Option<Rate>) {
389		if self.retarget(target).is_err() {
390			unreachable!("an allocator's registry has no limit")
391		}
392	}
393
394	/// Override the target, refusing one above the registry's limit.
395	fn retarget(&self, target: Option<Rate>) -> Result<()> {
396		let Ok(mut registry) = self.registry.write() else {
397			unreachable!("the allocator holds its own registry producer")
398		};
399		registry.fits(target.map_or(0, |target| u128::from(target.as_bps())))?;
400		if registry.target != target {
401			registry.target = target;
402		}
403		Ok(())
404	}
405
406	/// Follow the probe target, for the session that probes on the reservations' behalf.
407	///
408	/// Holding it is what marks the reservations [`probed`](Consumer::probed), so only a
409	/// session whose transport has a sender takes one.
410	#[cfg(any(feature = "async", test))]
411	// Sessions follow their allocator's target; a custom session has no public way to yet.
412	pub(crate) fn target(&self) -> Target {
413		let Ok(mut registry) = self.registry.write() else {
414			unreachable!("the allocator holds its own registry producer")
415		};
416		registry.probes += 1;
417		drop(registry);
418		Target {
419			registry: Some(self.registry.consume()),
420			probing: self.registry.downgrade(),
421			last: None,
422		}
423	}
424
425	/// An allocator with nothing to divide, so every reservation reports `None`.
426	///
427	/// `None` already means "no opinion, hold your rate" to a sender, so this is what
428	/// a transport with no congestion estimate, a local file, or a test harness wants,
429	/// and it saves every config struct on the way down from being an `Option`. It is
430	/// also [`Default`], so a config that never sets one encodes at its configured rate.
431	pub fn unlimited() -> Self {
432		Self {
433			estimate: Consumer {
434				inner: Inner::Unavailable,
435				last: None,
436				probed: false,
437			},
438			registry: kio::Producer::default(),
439		}
440	}
441
442	/// Reserve up to `max` for `track`, returning the reservation.
443	///
444	/// `max` is a ceiling, not a measurement: reserve the most the track can ever
445	/// send, not what it happens to be sending. A VBR encoder sitting on a black
446	/// screen at 1 Mbps can jump to 6 Mbps between one frame and the next, and a
447	/// reservation that had followed it down would have already handed that room
448	/// to somebody else.
449	///
450	/// Priority comes from the track ([`track::Info::priority`], higher served
451	/// first). A tier is filled to its reservations before the next one sees a
452	/// bit; within a tier the split is max-min fair, so a share asking for less
453	/// than an even cut takes all of it and leaves the difference to the others.
454	///
455	/// That is the *publisher's* priority, which the send order only falls back on:
456	/// it ranks by each subscription's own priority first, so a subscriber asking for
457	/// video ahead of audio is served that way whatever this decides, and this one
458	/// breaks the ties (or alone orders a broadcast's tracks on a session scheduled
459	/// per broadcast). The publisher's is still the right one to divide by, since
460	/// allocation is a decision about what to *produce*, and there is no single
461	/// subscriber priority to read when several are watching one track.
462	///
463	/// That last part carries a publisher that leaves `priority` at its default:
464	/// one tier of audio and video still serves audio's small reservation in full
465	/// before video takes the remainder.
466	///
467	/// The reservation lasts as long as the returned [`Reservation`]: hold it for as
468	/// long as the sender is publishing, change the ceiling with
469	/// [`update`](Reservation::update), and drop it to hand the room back. It is
470	/// released when the track closes either way, since a [`track::Demand`] is a weak
471	/// handle and reserving never keeps a track alive.
472	///
473	/// Read the current slice through [`Reservation::consume`], which reports `None`
474	/// while the connection has no estimate, telling a sender to hold its current rate
475	/// rather than encode at zero. While nothing is subscribed to the track it reports
476	/// the slice the track would get back, without claiming it from the others.
477	pub fn reserve(&self, track: &track::Demand, max: Rate) -> Reservation {
478		// Read the track before taking the registry lock, so the two are never held
479		// at once and there's no order to get wrong.
480		let claimed = self.claim(self.estimate.clone(), Some(track.clone()), track.priority(), max);
481		let Ok(reservation) = claimed else {
482			unreachable!("an allocator's registry has no limit")
483		};
484		reservation
485	}
486
487	/// Claim up to `max` of `estimate`, active whenever `demand` is, or always without one.
488	///
489	/// Errors without claiming when the ceilings would sum above the registry's limit.
490	fn claim(&self, estimate: Consumer, demand: Option<track::Demand>, priority: i8, max: Rate) -> Result<Reservation> {
491		let (id, grants) = {
492			// Nothing ever closes this channel: the allocator holds the only producer
493			// and never aborts it, so it's open for as long as `self` is.
494			let Ok(mut registry) = self.registry.write() else {
495				unreachable!("the allocator holds its own registry producer")
496			};
497			// Closed tracks can't be demanded again; drop them rather than walking
498			// them on every poll for the rest of the connection.
499			let closed: Vec<u64> = registry
500				.entries
501				.iter()
502				.filter(|(_, entry)| entry.demand.as_ref().is_some_and(track::Demand::is_closed))
503				.map(|(id, _)| *id)
504				.collect();
505			for id in closed {
506				registry.remove(id);
507			}
508			registry.fits(registry.reserved + u128::from(max.as_bps()))?;
509
510			let id = registry.next_id;
511			registry.next_id += 1;
512			registry.generation += 1;
513			registry.reserved += u128::from(max.as_bps());
514			registry.entries.insert(id, Entry { demand, priority, max });
515			(id, registry.grants.clone())
516		};
517
518		Ok(Reservation {
519			share: Share {
520				estimate,
521				registry: self.registry.consume(),
522				grants,
523				id,
524			},
525			registry: self.registry.downgrade(),
526		})
527	}
528}
529
530/// One track's standing claim on an [`Allocator`], held for as long as the sender
531/// that took it is publishing.
532///
533/// Separate from the [`Consumer`] that reads the slice, because the two have opposite
534/// lifetimes: read handles are cloned around and dropped freely, while the claim itself
535/// has to outlive every one of them or the sender silently stops claiming anything.
536#[must_use = "a dropped Reservation is released, so the sender claims nothing and its siblings take the room"]
537pub struct Reservation {
538	share: Share,
539	/// Weak so a reservation can't keep the registry alive: one outliving every
540	/// [`Allocator`] reports the estimate as gone rather than holding the channel open.
541	registry: kio::Weak<Registry>,
542}
543
544impl Reservation {
545	/// This reservation's slice right now.
546	///
547	/// Stateless, unlike [`Consumer::poll_changed`], which carries a cursor over what it last
548	/// reported and so needs a handle of its own.
549	pub fn rate(&self) -> Option<Rate> {
550		self.share.grant()
551	}
552
553	/// A handle reading this reservation's current slice of the estimate.
554	///
555	/// Cloneable and independent of the reservation: once the reservation is dropped
556	/// these report `None`, the same "hold your rate" a missing estimate reports.
557	pub fn consume(&self) -> Consumer {
558		Consumer {
559			inner: Inner::Share(Box::new(self.share.clone())),
560			last: None,
561			probed: false,
562		}
563	}
564
565	/// Change the ceiling, keeping the same claim.
566	///
567	/// For a sender whose ceiling genuinely moved: an encoder reopening at a resolution
568	/// it negotiated with the device, not an encoder observing its own output. A
569	/// reservation that followed the rate a VBR source happens to be sending would hand
570	/// the room away every time the picture went still, and not have it back when the
571	/// picture moved again.
572	///
573	/// Does nothing once every [`Allocator`] is gone, since there is then nothing left
574	/// dividing anything; a reader learns that from its [`consumer`](Self::consume).
575	pub fn update(&self, max: Rate) {
576		if self.resize(max).is_err() {
577			unreachable!("an allocator's registry has no limit")
578		}
579	}
580
581	/// Change the ceiling, refusing one that would sum above the registry's limit.
582	fn resize(&self, max: Rate) -> Result<()> {
583		let Some(registry) = self.registry.upgrade() else {
584			return Ok(());
585		};
586		let Ok(mut registry) = registry.write() else {
587			return Ok(());
588		};
589		let registry = &mut *registry;
590		if let Some(entry) = registry.entries.get_mut(&self.share.id) {
591			let reserved = registry.reserved - u128::from(entry.max.as_bps()) + u128::from(max.as_bps());
592			within(registry.limit, reserved)?;
593			registry.reserved = reserved;
594			registry.generation += 1;
595			entry.max = max;
596		}
597		Ok(())
598	}
599}
600
601impl Drop for Reservation {
602	fn drop(&mut self) {
603		let Some(registry) = self.registry.upgrade() else {
604			return;
605		};
606		let Ok(mut registry) = registry.write() else {
607			return;
608		};
609		registry.remove(self.share.id);
610	}
611}
612
613/// An allocator with nothing to divide, so a config that never sets one leaves its
614/// senders at their configured rates. See [`Allocator::unlimited`].
615impl Default for Allocator {
616	fn default() -> Self {
617		Self::unlimited()
618	}
619}
620
621// Hand-written so the config structs that carry an allocator can still derive
622// `Debug`. The registry is the only part worth printing.
623impl std::fmt::Debug for Allocator {
624	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
625		f.debug_struct("Allocator")
626			.field("registered", &self.registry.read().entries.len())
627			.finish()
628	}
629}
630
631/// Divides one connection's receive estimate among the broadcasts watched over it.
632///
633/// The receive-side mirror of [`Allocator`]. Every player on a connection reads the
634/// same receive estimate, so N players each selecting against all of it oversubscribe
635/// the downlink N times over. [`watch`](Self::watch) a broadcast here and its
636/// [`Viewer`] reports only its own slice, split max-min fair by each viewer's ceiling,
637/// so the slices sum to the estimate instead of each matching it. Viewers carry no
638/// priority: a viewer asking for less than an even cut takes all it asked for and
639/// leaves the rest to the others.
640///
641/// The viewers' ceilings summed are also the PROBE target the session sends its
642/// peer, which probes the connection up to it when it advertised `Increase`, so the
643/// estimate can rise to fund a larger rendition. The target never leaves this hop:
644/// a relay probes its own downlink for its viewers, and never forwards them upstream.
645///
646/// The ceilings may sum to at most [`MAX_TARGET`](Self::MAX_TARGET), which every PROBE
647/// encoding carries: a viewer or override that would pass it is refused with
648/// [`Error::BoundsExceeded`].
649///
650/// Holding a [`Viewer`] (or a [`Consumer`] read from one) requests PROBE, like
651/// holding `Session::recv_bandwidth`. Take it from `Session::viewers` (with the
652/// `async` feature) rather than building one, since only a session sends the target.
653/// Clones share one registry.
654#[derive(Clone)]
655pub struct Viewers {
656	/// The registry, whose own estimate is unused: each viewer reads one minted from
657	/// `estimate`, so holding the registry is not demand.
658	registry: Allocator,
659	/// Mints the receive estimate each viewer reads, or `None` when there is none.
660	estimate: Option<Weak>,
661}
662
663impl Viewers {
664	/// The largest PROBE target: the most the viewers' ceilings, summed, or an override may be.
665	///
666	/// `2^53 - 1` bits per second, the largest integer a JavaScript peer decodes exactly,
667	/// and well inside the wire's varint.
668	pub const MAX_TARGET: Rate = Rate::from_bps((1 << 53) - 1);
669
670	/// Divide the receive estimate `estimate` mints, with no session sending the target.
671	///
672	/// For an estimate that outlives a session, such as one a reconnect loop feeds
673	/// from each session it dials. Hand the same registry to `Client::with_viewers`
674	/// (with the `async` feature) so every session it dials sends the target.
675	pub fn new(estimate: Weak) -> Self {
676		Self {
677			estimate: Some(estimate),
678			..Self::default()
679		}
680	}
681
682	/// The same registry dividing the estimate `estimate` mints instead, or nothing when it is `None`.
683	#[cfg(feature = "async")]
684	pub(crate) fn with_estimate(&self, estimate: Option<Weak>) -> Self {
685		Self {
686			registry: self.registry.clone(),
687			estimate,
688		}
689	}
690
691	/// Watch a broadcast receiving at most `max`, returning its viewer.
692	///
693	/// `max` is a ceiling: what the largest rendition the player would switch to
694	/// needs, not what it happens to be receiving. The claim lasts as long as the
695	/// returned [`Viewer`]: change the ceiling with [`update`](Viewer::update), and drop
696	/// it once the broadcast stops being watched.
697	///
698	/// # Errors
699	///
700	/// [`Error::BoundsExceeded`], watching nothing, when the ceilings would sum above
701	/// [`MAX_TARGET`](Self::MAX_TARGET).
702	pub fn watch(&self, max: Rate) -> Result<Viewer> {
703		let estimate = match &self.estimate {
704			Some(estimate) => estimate.consume(),
705			None => Consumer {
706				inner: Inner::Unavailable,
707				last: None,
708				probed: false,
709			},
710		};
711		Ok(Viewer(self.registry.claim(estimate, None, 0, max)?))
712	}
713
714	/// Send `target` as the PROBE target instead of the viewers' sum, or `None` to follow them again.
715	///
716	/// `Some(Rate::ZERO)` sends no target, so the peer stops probing for these viewers. The
717	/// override is the registry's, so it holds for every clone and across the reconnects a
718	/// persistent registry spans.
719	///
720	/// # Errors
721	///
722	/// [`Error::BoundsExceeded`], keeping the previous override, for a target above
723	/// [`MAX_TARGET`](Self::MAX_TARGET).
724	pub fn set_target(&self, target: Option<Rate>) -> Result<()> {
725		self.registry.retarget(target)
726	}
727
728	/// Follow the PROBE target, for the session that sends it to a peer that probes up to it.
729	///
730	/// Holding it is what marks the viewers [`probed`](Consumer::probed).
731	#[cfg(any(feature = "async", test))]
732	pub(crate) fn target(&self) -> Target {
733		self.registry.target()
734	}
735}
736
737/// No receive estimate to divide, with the PROBE target's limit.
738impl Default for Viewers {
739	fn default() -> Self {
740		let registry = Allocator::unlimited();
741		if let Ok(mut state) = registry.registry.write() {
742			state.limit = Some(Self::MAX_TARGET);
743		}
744		Self {
745			registry,
746			estimate: None,
747		}
748	}
749}
750
751// Hand-written so the config structs that carry a registry can still derive `Debug`.
752impl std::fmt::Debug for Viewers {
753	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
754		f.debug_struct("Viewers")
755			.field("watched", &self.registry.registry.read().entries.len())
756			.finish()
757	}
758}
759
760/// One watched broadcast's standing claim on [`Viewers`], held for as long as it is watched.
761///
762/// Holding it requests PROBE. Dropping it releases the claim and lowers the PROBE target.
763#[must_use = "a dropped Viewer is released, so the broadcast claims nothing and the PROBE target drops"]
764pub struct Viewer(Reservation);
765
766impl Viewer {
767	/// This viewer's slice of the receive estimate right now.
768	///
769	/// `None` while the connection has no receive estimate, telling a player to hold its
770	/// current selection.
771	pub fn rate(&self) -> Option<Rate> {
772		self.0.rate()
773	}
774
775	/// A handle reading this viewer's current slice of the receive estimate.
776	///
777	/// Cloneable and independent of the viewer: once the viewer is dropped these report
778	/// `None`. [`Consumer::probed`] reports whether the peer is asked to probe for it.
779	pub fn consume(&self) -> Consumer {
780		self.0.consume()
781	}
782
783	/// Change the ceiling, keeping the same claim, as when a catalog enables or disables a rendition.
784	///
785	/// # Errors
786	///
787	/// [`Error::BoundsExceeded`], keeping the previous ceiling, when the ceilings would
788	/// sum above [`Viewers::MAX_TARGET`].
789	pub fn update(&self, max: Rate) -> Result<()> {
790		self.0.resize(max)
791	}
792}
793
794/// Every track registered with one [`Allocator`].
795#[derive(Default)]
796struct Registry {
797	/// Keyed by registration order, which a [`Plan`] keeps as its tie-break.
798	entries: BTreeMap<u64, Entry>,
799	next_id: u64,
800	/// The entries' ceilings summed, kept as they change so following the target
801	/// never walks the table. Wide enough that no number of `u64` ceilings overflows.
802	reserved: u128,
803	/// The application's override of `reserved` as the probe target.
804	target: Option<Rate>,
805	/// The most `reserved` and `target` may each be, or `None` for no limit.
806	limit: Option<Rate>,
807	/// How many sessions probe for these reservations, each through its [`Target`].
808	probes: usize,
809	/// Bumped whenever an entry is added, moved or removed, so a [`Plan`] knows the
810	/// entries it divided are still the registry's.
811	generation: u64,
812	/// The division every share of this registry reads.
813	grants: Arc<Grants>,
814}
815
816impl Registry {
817	fn remove(&mut self, id: u64) {
818		if let Some(entry) = self.entries.remove(&id) {
819			self.reserved -= u128::from(entry.max.as_bps());
820			self.generation += 1;
821		}
822	}
823
824	/// Refuse `total` when it is above the registry's limit.
825	fn fits(&self, total: u128) -> Result<()> {
826		within(self.limit, total)
827	}
828
829	/// What the session probes up to.
830	fn target(&self) -> Rate {
831		self.target
832			.unwrap_or_else(|| Rate::from_bps(u64::try_from(self.reserved).unwrap_or(u64::MAX)))
833	}
834}
835
836/// Refuse `total` when it is above `limit`.
837fn within(limit: Option<Rate>, total: u128) -> Result<()> {
838	match limit {
839		Some(limit) if total > u128::from(limit.as_bps()) => Err(Error::BoundsExceeded(BoundsExceeded)),
840		_ => Ok(()),
841	}
842}
843
844/// One registered track's standing reservation.
845struct Entry {
846	/// The track whose demand gates the claim, or `None` for a claim that is always active.
847	demand: Option<track::Demand>,
848	priority: i8,
849	max: Rate,
850}
851
852/// An [`Allocator`]'s probe target, followed by the session that probes for it.
853#[cfg(any(feature = "async", test))]
854// Sessions follow their allocator's target; a custom session has no public way to yet.
855pub(crate) struct Target {
856	/// `None` once every allocator is gone.
857	registry: Option<kio::Consumer<Registry>>,
858	/// Weak, so a session never keeps the registry alive, only counts itself while it does.
859	probing: kio::Weak<Registry>,
860	last: Option<Rate>,
861}
862
863#[cfg(any(feature = "async", test))]
864impl Drop for Target {
865	fn drop(&mut self) {
866		let Some(registry) = self.probing.upgrade() else {
867			return;
868		};
869		let Ok(mut registry) = registry.write() else {
870			return;
871		};
872		registry.probes -= 1;
873	}
874}
875
876#[cfg(any(feature = "async", test))]
877impl Target {
878	/// The target once it differs from the last one returned, arming `waiter` otherwise.
879	///
880	/// Zero once every allocator is gone, since nothing is left reserving.
881	// Sessions follow their allocator's target; a custom session has no public way to yet.
882	pub(crate) fn poll_changed(&mut self, waiter: &kio::Waiter) -> Poll<Rate> {
883		let Some(registry) = &self.registry else {
884			return Poll::Pending;
885		};
886		let last = self.last;
887		let polled = registry
888			.poll(waiter, |registry| match registry.target() {
889				target if Some(target) == last => Poll::Pending,
890				target => Poll::Ready(target),
891			})
892			.map(|res| res.ok());
893		let target = match polled {
894			Poll::Ready(Some(target)) => target,
895			Poll::Ready(None) => {
896				self.registry = None;
897				Rate::ZERO
898			}
899			Poll::Pending => return Poll::Pending,
900		};
901		if Some(target) == last {
902			return Poll::Pending;
903		}
904		self.last = Some(target);
905		Poll::Ready(target)
906	}
907}
908
909/// A share's view of the estimate it divides.
910#[derive(Clone)]
911struct Share {
912	/// What's being divided, which may itself be a share.
913	estimate: Consumer,
914	registry: kio::Consumer<Registry>,
915	/// The registry's division, shared with every other share of it.
916	grants: Arc<Grants>,
917	id: u64,
918}
919
920impl Share {
921	/// This share's slice right now.
922	fn grant(&self) -> Option<Rate> {
923		let estimate = self.estimate.peek()?;
924		self.grants.grant(&self.registry, estimate, self.id)
925	}
926
927	/// Whether a session probes for this share's registry, toward a target above zero.
928	/// A zero target stops probing for these claims, though the session may still probe
929	/// for its peer's target.
930	fn probed(&self) -> bool {
931		let registry = self.registry.read();
932		registry.probes > 0 && registry.target() > Rate::ZERO
933	}
934
935	/// This share's slice and whether a session probes for it, arming `waiter` for
936	/// everything that could move either: the estimate, the registry, and each
937	/// track's demand.
938	fn poll_grant(&mut self, waiter: &kio::Waiter) -> Poll<Result<(Option<Rate>, bool)>> {
939		// Drain the estimate rather than polling it once. A poll that returns Ready
940		// registers no waker, and this share may still conclude its own slice didn't
941		// move (its reservation caps it, so most estimate changes don't reach it) and
942		// park. Without the drain that park would never be woken by the next move.
943		// The value itself is read below, since an unchanged estimate still needs
944		// re-dividing when the tracks sharing it change.
945		loop {
946			match self.estimate.poll_changed(waiter) {
947				// Moved: go round again, which either finds it settled and arms the
948				// waker, or finds it moved again and makes progress toward the latest.
949				Poll::Ready(Ok(_)) => continue,
950				Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
951				Poll::Pending => break,
952			}
953		}
954
955		// Wake on any registration change. The closure never completes, so the only
956		// ready outcome is the registry being gone, i.e. every allocator dropped.
957		if let Poll::Ready(Err(_)) = self.registry.poll(waiter, |_| Poll::<()>::Pending) {
958			return Poll::Ready(Err(Error::Dropped));
959		}
960
961		// Wake on any track's demand moving. The division watches the tracks once on
962		// behalf of every share, so this is one registration rather than one per track.
963		// It comes before the read below, so a move after it either shows in the read
964		// or wakes this waiter.
965		self.grants.watch.park(waiter);
966
967		let grant = self
968			.estimate
969			.peek()
970			.and_then(|estimate| self.grants.grant(&self.registry, estimate, self.id));
971		Poll::Ready(Ok((grant, self.probed())))
972	}
973}
974
975/// One demanded track's claim, snapshotted out of the [`Registry`] so no lock is
976/// held while the tracks themselves are read.
977#[derive(Copy, Clone, Debug, Eq, PartialEq)]
978struct Want {
979	id: u64,
980	priority: i8,
981	max: Rate,
982}
983
984impl Want {
985	/// Where this claim is served: higher priority first, then ascending by reservation,
986	/// so each share takes an even cut of what's left, or all it asked for if that's
987	/// less, which frees the difference for the rest. Registration order breaks ties.
988	fn order(&self) -> (std::cmp::Reverse<i8>, Rate, u64) {
989		(std::cmp::Reverse(self.priority), self.max, self.id)
990	}
991}
992
993/// A registry's division of its estimate, computed once per change to the estimate, the
994/// entries or a track's demand, and read by every share instead of each re-dividing
995/// the whole table.
996///
997/// One plan is cached, for the last estimate read. That assumes every share of a
998/// registry divides the same value, as they do in practice: a reconnecting connection's
999/// persistent estimate is forwarded from its current session's. Shares reading
1000/// different values still get the right slices, but each alternation divides the
1001/// cached entries again (without reading the tracks).
1002#[derive(Default)]
1003struct Grants {
1004	/// The latest division, or `None` before the first read.
1005	plan: kio::Lock<Option<Plan>>,
1006	/// Watches every track's demand on the plan's behalf.
1007	watch: Arc<Watch>,
1008}
1009
1010impl Grants {
1011	/// `id`'s slice of `estimate`, dividing it again only when something it depends on moved.
1012	fn grant(&self, registry: &kio::Consumer<Registry>, estimate: Rate, id: u64) -> Option<Rate> {
1013		let mut plan = self.plan.lock();
1014		// Read before the tracks are, so a move while they are read invalidates this plan.
1015		let epoch = self.watch.epoch.load(Ordering::SeqCst);
1016		let generation = registry.read().generation;
1017		match plan.as_mut() {
1018			Some(current) if current.generation == generation && current.epoch == epoch => {
1019				if current.estimate != estimate {
1020					current.divide(estimate);
1021				}
1022			}
1023			_ => *plan = Some(Plan::new(registry, &self.watch, estimate, epoch)),
1024		}
1025		plan.as_ref().and_then(|plan| plan.grant(id))
1026	}
1027}
1028
1029/// Turns any watched track's demand moving into one wake for every share parked on it.
1030#[derive(Default)]
1031struct Watch {
1032	/// Bumped on every wake, so a plan made before it knows it is stale.
1033	epoch: AtomicU64,
1034	/// Shares parked on a demand moving.
1035	parked: kio::Lock<kio::WaiterList>,
1036}
1037
1038impl Watch {
1039	/// Wake `waiter` on the next demand move.
1040	fn park(&self, waiter: &kio::Waiter) {
1041		waiter.register(&mut self.parked.lock());
1042	}
1043}
1044
1045impl Wake for Watch {
1046	fn wake(self: Arc<Self>) {
1047		self.wake_by_ref();
1048	}
1049
1050	fn wake_by_ref(self: &Arc<Self>) {
1051		self.epoch.fetch_add(1, Ordering::SeqCst);
1052		let mut parked = self.parked.lock().take();
1053		parked.wake();
1054	}
1055}
1056
1057/// One entry as a [`Plan`] found it.
1058#[derive(Copy, Clone)]
1059struct Planned {
1060	want: Want,
1061	state: track::DemandState,
1062	/// Its slice, for an active entry; the others are worked out when read.
1063	grant: u64,
1064}
1065
1066/// One demanded entry in the order it is served.
1067#[derive(Copy, Clone)]
1068struct Served {
1069	/// The index in `Plan::entries`, fixed for this plan's lifetime.
1070	entry: usize,
1071	want: Want,
1072	/// What was left of the estimate before this entry was served.
1073	budget: u64,
1074}
1075
1076/// One division of an estimate among a registry's entries.
1077///
1078/// Strict priority: a tier is filled to its reservations before the next tier sees a
1079/// bit. Within a tier the split is max-min fair, so a share asking for less than an
1080/// even split takes all of it and leaves the rest to the others.
1081///
1082/// Surplus above the total reserved is left unclaimed rather than spread around. A
1083/// reservation is what a sender can use, so handing it more is not a reason to send
1084/// more than it was configured for.
1085struct Plan {
1086	estimate: Rate,
1087	/// The [`Registry::generation`] the entries were read at.
1088	generation: u64,
1089	/// The [`Watch::epoch`] before the tracks were read.
1090	epoch: u64,
1091	/// Every entry, by registration.
1092	entries: Vec<Planned>,
1093	/// The active entries, in the order they are served.
1094	order: Vec<Served>,
1095	/// What is left once every active entry is served.
1096	leftover: u64,
1097	/// Holds the registration on every track's demand, which ends when it is replaced.
1098	_waiter: kio::Waiter,
1099}
1100
1101impl Plan {
1102	/// Read every entry and its track's demand, watching each for the next move, and
1103	/// divide `estimate` among them.
1104	fn new(registry: &kio::Consumer<Registry>, watch: &Arc<Watch>, estimate: Rate, epoch: u64) -> Self {
1105		// Snapshot the registry so the tracks can be read without holding its lock.
1106		let (generation, claims): (u64, Vec<(Want, Option<track::Demand>)>) = {
1107			let registry = registry.read();
1108			let claims = registry
1109				.entries
1110				.iter()
1111				.map(|(id, entry)| {
1112					let want = Want {
1113						id: *id,
1114						priority: entry.priority,
1115						max: entry.max,
1116					};
1117					(want, entry.demand.clone())
1118				})
1119				.collect();
1120			(registry.generation, claims)
1121		};
1122
1123		let waiter = kio::Waiter::new(Waker::from(watch.clone()));
1124		let entries = claims
1125			.into_iter()
1126			.map(|(want, demand)| Planned {
1127				want,
1128				state: demand.map_or(track::DemandState::Active, |demand| demand.poll_state(&waiter)),
1129				grant: 0,
1130			})
1131			.collect();
1132
1133		Self::divided(estimate, generation, epoch, entries, waiter)
1134	}
1135
1136	/// Divide `estimate` among `entries`, which are in registration order.
1137	fn divided(estimate: Rate, generation: u64, epoch: u64, entries: Vec<Planned>, waiter: kio::Waiter) -> Self {
1138		let mut order: Vec<_> = entries
1139			.iter()
1140			.enumerate()
1141			.filter(|(_, entry)| entry.state == track::DemandState::Active)
1142			.map(|(index, entry)| Served {
1143				entry: index,
1144				want: entry.want,
1145				budget: 0,
1146			})
1147			.collect();
1148		// Only a new plan changes this total order; estimate updates just walk it.
1149		order.sort_unstable_by_key(|served| served.want.order());
1150		let mut plan = Self {
1151			estimate,
1152			generation,
1153			epoch,
1154			entries,
1155			order,
1156			leftover: 0,
1157			_waiter: waiter,
1158		};
1159		plan.divide(estimate);
1160		plan
1161	}
1162
1163	/// Divide `estimate` among the entries already read, in their cached serving order.
1164	fn divide(&mut self, estimate: Rate) {
1165		self.estimate = estimate;
1166
1167		// Plain bits per second inside: this is where the division actually happens, and
1168		// wrapping every intermediate would need arithmetic on `Rate` that no caller wants.
1169		let mut budget = estimate.as_bps();
1170		let mut start = 0;
1171		while start < self.order.len() {
1172			let priority = self.order[start].want.priority;
1173			let end = start + self.order[start..].partition_point(|served| served.want.priority == priority);
1174			for index in start..end {
1175				let served = &mut self.order[index];
1176				served.budget = budget;
1177				let grant = served.want.max.as_bps().min(budget / (end - index) as u64);
1178				budget -= grant;
1179
1180				self.entries[served.entry].grant = grant;
1181			}
1182			start = end;
1183		}
1184		self.leftover = budget;
1185	}
1186
1187	/// The slice for `id`.
1188	///
1189	/// An idle entry claims nothing from the others but still reads the slice it would
1190	/// get back: a rendition stopped for lack of bandwidth, whose viewers then left,
1191	/// needs that to know when to resume.
1192	///
1193	/// `None` when `id` isn't registered or its track closed, which is how a released
1194	/// or closed reservation reports "hold your rate" instead of a grant of zero.
1195	fn grant(&self, id: u64) -> Option<Rate> {
1196		let at = self.entries.binary_search_by_key(&id, |entry| entry.want.id).ok()?;
1197		let entry = &self.entries[at];
1198		match entry.state {
1199			track::DemandState::Active => Some(Rate::from_bps(entry.grant)),
1200			track::DemandState::Idle => Some(Rate::from_bps(self.rejoin(entry.want))),
1201			track::DemandState::Closed => None,
1202		}
1203	}
1204
1205	/// What an idle `want` would get were it demanded again.
1206	///
1207	/// Tiers above its own are served first either way, so only its own tier is walked
1208	/// again, with one more entry sharing it, as far as where it would be served.
1209	fn rejoin(&self, want: Want) -> u64 {
1210		let start = self
1211			.order
1212			.partition_point(|served| served.want.priority > want.priority);
1213		let end = self
1214			.order
1215			.partition_point(|served| served.want.priority >= want.priority);
1216		let at = self.order.partition_point(|served| served.want.order() < want.order());
1217		let mut budget = self.order.get(start).map_or(self.leftover, |served| served.budget);
1218		let mut remaining = (end - start + 1) as u64;
1219		for served in &self.order[start..at] {
1220			budget -= served.want.max.as_bps().min(budget / remaining);
1221			remaining -= 1;
1222		}
1223		want.max.as_bps().min(budget / remaining)
1224	}
1225}
1226
1227/// Consumes bandwidth estimates, allowing reads and async change notifications.
1228#[derive(Clone)]
1229pub struct Consumer {
1230	inner: Inner,
1231	last: Option<Rate>,
1232	/// The [`probed`](Self::probed) state [`poll_changed`](Self::poll_changed) last reported.
1233	probed: bool,
1234}
1235
1236/// What a [`Consumer`] is reading: the whole estimate, or one track's slice of it.
1237#[derive(Clone)]
1238enum Inner {
1239	Whole(kio::Consumer<State>),
1240	Share(Box<Share>),
1241	/// [`Allocator::unlimited`]'s: no estimate, and never will be.
1242	Unavailable,
1243}
1244
1245impl Consumer {
1246	/// Get the current bandwidth estimate synchronously.
1247	pub fn peek(&self) -> Option<Rate> {
1248		match &self.inner {
1249			Inner::Whole(state) => state.read().bitrate,
1250			Inner::Share(share) => share.grant(),
1251			Inner::Unavailable => None,
1252		}
1253	}
1254
1255	/// Whether a session probes the connection for this slice's reservation, so the
1256	/// estimate can rise to fund it even while its sender is stopped.
1257	///
1258	/// Only a session whose transport has a sender probes, and none does for it while
1259	/// [`Allocator::set_target`] overrides the target to zero. For a [`Viewer`]'s slice,
1260	/// whether the session asks a peer that advertised `Increase` to probe for it, which
1261	/// [`Viewers::set_target`] can turn off the same way. Without one the estimate
1262	/// stops learning once the connection is app-limited, so a sender that stops for
1263	/// lack of bandwidth could never see enough to resume. Always `false` for a whole
1264	/// estimate, which no reservation backs. [`poll_changed`](Self::poll_changed)
1265	/// reports a change to this too.
1266	pub fn probed(&self) -> bool {
1267		match &self.inner {
1268			Inner::Share(share) => share.probed(),
1269			Inner::Whole(_) | Inner::Unavailable => false,
1270		}
1271	}
1272
1273	/// The bandwidth estimate once it changes, or `None` when it has become unavailable.
1274	///
1275	/// `Ok(None)` means the estimate is unavailable *for now*: the backend
1276	/// stopped reporting one, or the handle spans reconnects and is between
1277	/// sessions. `Err` means the producer is gone and no further change will ever
1278	/// arrive. They're distinct because a caller holds its current rate for the
1279	/// first and stops watching for the second.
1280	///
1281	/// A slice is also reported, unchanged, when [`probed`](Self::probed) flips.
1282	///
1283	/// A backend with no bandwidth estimation at all yields no [Consumer] in the
1284	/// first place, so that case never reaches here.
1285	#[cfg_attr(feature = "async", kio::wrapper)]
1286	pub fn poll_changed(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Rate>>> {
1287		let last = self.last;
1288
1289		let bitrate = match &mut self.inner {
1290			Inner::Whole(state) => match state.poll(waiter, |state| {
1291				if state.bitrate != last {
1292					Poll::Ready(state.bitrate)
1293				} else {
1294					Poll::Pending
1295				}
1296			}) {
1297				Poll::Ready(Ok(bitrate)) => bitrate,
1298				// Closed, and the value hasn't moved since the last read: report it as
1299				// terminal. Collapsing this into `Ok(None)` would be indistinguishable
1300				// from a live-but-unavailable estimate, and since a closed channel is
1301				// always immediately ready, a `select!` over it would spin forever.
1302				Poll::Ready(Err(_)) => return Poll::Ready(Err(Error::Dropped)),
1303				Poll::Pending => return Poll::Pending,
1304			},
1305			// A share recomputes its slice on every wakeup, so it filters the
1306			// unchanged case here rather than inside the poll. Every waker that could
1307			// move the slice was armed by `poll_grant` either way.
1308			// Nothing to report and nothing that could ever change it, so park without
1309			// arming anything rather than reporting a `None` the caller would re-read forever.
1310			Inner::Unavailable => return Poll::Pending,
1311			Inner::Share(share) => match share.poll_grant(waiter) {
1312				Poll::Ready(Ok((grant, probed))) if grant == last && probed == self.probed => return Poll::Pending,
1313				Poll::Ready(Ok((grant, probed))) => {
1314					self.probed = probed;
1315					grant
1316				}
1317				Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
1318				Poll::Pending => return Poll::Pending,
1319			},
1320		};
1321
1322		self.last = bitrate;
1323		Poll::Ready(Ok(bitrate))
1324	}
1325}
1326
1327#[cfg(test)]
1328mod tests {
1329	use super::*;
1330	use crate::broadcast;
1331
1332	#[test]
1333	fn a_limit_reports_each_change_to_every_clone() {
1334		let cap = Cap::new(Rate::from_kbps(8));
1335		let limit = Limit::default();
1336		let mut watch = limit.clone();
1337		assert_eq!(watch.get(), None);
1338		assert!(watch.poll_changed(&kio::Waiter::noop()).is_pending());
1339
1340		limit.set(cap);
1341		assert_eq!(watch.poll_changed(&kio::Waiter::noop()), Poll::Ready(Some(cap)));
1342		assert!(watch.poll_changed(&kio::Waiter::noop()).is_pending());
1343
1344		// A clone starts at the current cap.
1345		let mut late = limit.clone();
1346		assert!(late.poll_changed(&kio::Waiter::noop()).is_pending());
1347		limit.set(None);
1348		assert_eq!(late.poll_changed(&kio::Waiter::noop()), Poll::Ready(None));
1349	}
1350
1351	#[test]
1352	fn a_limit_get_marks_the_cap_seen() {
1353		let low = Cap::new(Rate::from_kbps(8));
1354		let high = Cap::new(Rate::from_kbps(16));
1355		let limit = Limit::new(low);
1356		let mut watch = limit.clone();
1357
1358		// A cap read between the clone and a restore still reports the restore.
1359		limit.set(high);
1360		assert_eq!(watch.get(), Some(high));
1361		limit.set(low);
1362		assert_eq!(watch.poll_changed(&kio::Waiter::noop()), Poll::Ready(Some(low)));
1363	}
1364
1365	/// Priorities matching `hang`'s, which is what the allocator sees in practice.
1366	const AUDIO: i8 = 80;
1367	const VIDEO: i8 = 60;
1368
1369	/// Divide `estimate` among `wants`, returning the slice for `id`, or `None` when `id`
1370	/// isn't among them.
1371	fn allocate(estimate: Rate, wants: &[Want], id: u64) -> Option<Rate> {
1372		let entries = wants.iter().map(|want| (*want, track::DemandState::Active));
1373		plan(estimate, entries).grant(id)
1374	}
1375
1376	/// A division of `estimate` among `entries`, in registration order, with no tracks to watch.
1377	fn plan(estimate: Rate, entries: impl IntoIterator<Item = (Want, track::DemandState)>) -> Plan {
1378		let entries = entries
1379			.into_iter()
1380			.map(|(want, state)| Planned { want, state, grant: 0 })
1381			.collect();
1382		Plan::divided(estimate, 0, 0, entries, kio::Waiter::noop())
1383	}
1384
1385	/// Bits per second, so the tables below stay readable.
1386	fn bps(bps: u64) -> Rate {
1387		Rate::from_bps(bps)
1388	}
1389
1390	fn want(id: u64, priority: i8, max: u64) -> Want {
1391		Want {
1392			id,
1393			priority,
1394			max: bps(max),
1395		}
1396	}
1397
1398	/// A standalone track at `priority`, plus the broadcast keeping it alive.
1399	fn track(priority: i8) -> (broadcast::Producer, track::Producer) {
1400		let broadcast = broadcast::Info::default().produce();
1401		let track = broadcast
1402			.create_track("t", track::Info::timed().with_priority(priority))
1403			.unwrap();
1404		(broadcast, track)
1405	}
1406
1407	#[test]
1408	fn strict_priority_fills_the_top_tier_first() {
1409		let wants = [want(0, AUDIO, 128_000), want(1, VIDEO, 4_000_000)];
1410
1411		// Audio takes its reservation off the top; video gets what's left. This is
1412		// the job `rate::Policy::headroom` used to approximate with a flat 10%.
1413		assert_eq!(allocate(bps(2_000_000), &wants, 0), Some(bps(128_000)));
1414		assert_eq!(allocate(bps(2_000_000), &wants, 1), Some(bps(1_872_000)));
1415	}
1416
1417	#[test]
1418	fn a_starved_tier_gets_nothing() {
1419		let wants = [want(0, AUDIO, 2_000_000), want(1, VIDEO, 4_000_000)];
1420
1421		assert_eq!(allocate(bps(1_000_000), &wants, 0), Some(bps(1_000_000)));
1422		// Strict, not weighted: the lower tier is not owed a floor. Its encoder
1423		// clamps to `rate::Policy::min` and the transport sheds what won't fit.
1424		assert_eq!(allocate(bps(1_000_000), &wants, 1), Some(bps(0)));
1425	}
1426
1427	/// A publisher that doesn't set [`track::Info::priority`] puts audio and video
1428	/// in one tier. That has to come out right anyway, and it does: max-min fair
1429	/// satisfies the small claim first, so audio still gets its full reservation
1430	/// and video takes the rest. Priority only changes the answer once a tier's
1431	/// smaller claims outgrow an even split.
1432	#[test]
1433	fn one_tier_still_serves_audio_before_video() {
1434		let flat = [want(0, 0, 128_000), want(1, 0, 4_000_000)];
1435		let tiered = [want(0, AUDIO, 128_000), want(1, VIDEO, 4_000_000)];
1436
1437		for wants in [flat, tiered] {
1438			assert_eq!(allocate(bps(2_000_000), &wants, 0), Some(bps(128_000)));
1439			assert_eq!(allocate(bps(2_000_000), &wants, 1), Some(bps(1_872_000)));
1440		}
1441	}
1442
1443	#[test]
1444	fn an_even_tier_splits_evenly() {
1445		let wants = [want(0, VIDEO, 4_000_000), want(1, VIDEO, 4_000_000)];
1446
1447		assert_eq!(allocate(bps(6_000_000), &wants, 0), Some(bps(3_000_000)));
1448		assert_eq!(allocate(bps(6_000_000), &wants, 1), Some(bps(3_000_000)));
1449	}
1450
1451	/// Max-min fair, not an even split: a 360p rung sharing with a 1080p one takes
1452	/// only what it asked for and leaves the rest, instead of both being held to half.
1453	#[test]
1454	fn a_small_share_frees_what_it_does_not_want() {
1455		let wants = [want(0, VIDEO, 1_000_000), want(1, VIDEO, 8_000_000)];
1456
1457		assert_eq!(allocate(bps(6_000_000), &wants, 0), Some(bps(1_000_000)));
1458		assert_eq!(allocate(bps(6_000_000), &wants, 1), Some(bps(5_000_000)));
1459	}
1460
1461	/// Capping at the reservation is what keeps an uncongested link encoding at
1462	/// exactly the configured rate. Spreading the surplus instead would only matter
1463	/// if senders scaled a fraction of their grant, which is what headroom did.
1464	#[test]
1465	fn surplus_is_left_unclaimed() {
1466		assert_eq!(
1467			allocate(bps(10_000_000), &[want(0, VIDEO, 4_000_000)], 0),
1468			Some(bps(4_000_000))
1469		);
1470	}
1471
1472	#[test]
1473	fn an_unregistered_share_has_no_grant() {
1474		assert_eq!(allocate(bps(1_000_000), &[], 0), None);
1475		assert_eq!(allocate(bps(1_000_000), &[want(0, VIDEO, 1_000)], 7), None);
1476	}
1477
1478	/// One share's slice, dividing every tier again for it alone: the reference a shared
1479	/// division is checked against.
1480	fn sequential(estimate: Rate, wants: &[Want], id: u64) -> Option<Rate> {
1481		let mut budget = estimate.as_bps();
1482		let mut tier = wants.iter().map(|want| want.priority).max();
1483		while let Some(priority) = tier {
1484			let mut members: Vec<&Want> = wants.iter().filter(|want| want.priority == priority).collect();
1485			members.sort_by_key(|want| want.max);
1486			let mut remaining = members.len() as u64;
1487			for want in members {
1488				let grant = want.max.as_bps().min(budget / remaining);
1489				if want.id == id {
1490					return Some(Rate::from_bps(grant));
1491				}
1492				budget -= grant;
1493				remaining -= 1;
1494			}
1495			tier = wants
1496				.iter()
1497				.map(|want| want.priority)
1498				.filter(|other| *other < priority)
1499				.max();
1500		}
1501		None
1502	}
1503
1504	/// Every slice of one shared division, active or idle, matches dividing the table
1505	/// again for that share alone, across tiers, tied ceilings and rounding.
1506	#[test]
1507	fn one_division_matches_each_share_dividing_alone() {
1508		let mut seed = 42u64;
1509		let mut next = |bound: u64| {
1510			seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
1511			(seed >> 33) % bound
1512		};
1513		for _ in 0..2_000 {
1514			let count = next(12) + 1;
1515			let tiers = next(4) + 1;
1516			let entries: Vec<(Want, bool)> = (0..count)
1517				.map(|id| {
1518					let want = want(id, next(tiers) as i8 - 1, next(5) * 300 + next(3));
1519					(want, next(3) > 0)
1520				})
1521				.collect();
1522			let estimate = bps(next(count * 1_600));
1523			let active: Vec<Want> = entries
1524				.iter()
1525				.filter(|(_, active)| *active)
1526				.map(|(want, _)| *want)
1527				.collect();
1528
1529			let mut plan = plan(
1530				estimate,
1531				entries.iter().map(|(want, active)| {
1532					let state = match active {
1533						true => track::DemandState::Active,
1534						false => track::DemandState::Idle,
1535					};
1536					(*want, state)
1537				}),
1538			);
1539
1540			// A cached order must also serve a new estimate and clear grants when a tier starves.
1541			for estimate in [estimate, Rate::ZERO, bps(next(count * 1_600))] {
1542				plan.divide(estimate);
1543				for (want, is_active) in &entries {
1544					let expected = match is_active {
1545						true => sequential(estimate, &active, want.id),
1546						false => {
1547							let mut rejoined = active.clone();
1548							rejoined.push(*want);
1549							rejoined.sort_by_key(|want| want.id);
1550							sequential(estimate, &rejoined, want.id)
1551						}
1552					};
1553					assert_eq!(
1554						plan.grant(want.id),
1555						expected,
1556						"{want:?} among {entries:?} sharing {estimate:?}"
1557					);
1558				}
1559			}
1560		}
1561	}
1562
1563	/// The headline case: two encoders on one connection must not each target the
1564	/// whole estimate.
1565	#[kio::test]
1566	#[cfg(feature = "async")]
1567	async fn concurrent_tracks_split_the_estimate() {
1568		let estimate = Producer::new();
1569		let allocator = Allocator::new(estimate.consume());
1570
1571		let (_first_broadcast, first) = track(VIDEO);
1572		let _first_sub = first.subscribe(None);
1573		let first = allocator.reserve(&first.demand(), bps(4_000_000));
1574		let mut first_share = first.consume();
1575
1576		estimate.set(Some(bps(2_000_000))).unwrap();
1577		// Alone, it gets everything it asked for that the link can carry.
1578		assert_eq!(first_share.changed().await.unwrap(), Some(bps(2_000_000)));
1579
1580		// A second encoder starts. The first must give half back without anyone
1581		// telling it to, or the two together target 200% of the uplink.
1582		let (_second_broadcast, second) = track(VIDEO);
1583		let _second_sub = second.subscribe(None);
1584		let second_share = allocator.reserve(&second.demand(), bps(4_000_000));
1585
1586		assert_eq!(first_share.changed().await.unwrap(), Some(bps(1_000_000)));
1587		assert_eq!(second_share.rate(), Some(bps(1_000_000)));
1588	}
1589
1590	/// An unwatched track releases its reservation to the others, since an on-demand sender
1591	/// stops encoding entirely while nothing is subscribed, but still reads the slice it
1592	/// would get back, which is what a stopped rendition its viewers left resumes on.
1593	#[test]
1594	fn an_idle_track_claims_nothing() {
1595		let estimate = Producer::new();
1596		let allocator = Allocator::new(estimate.consume());
1597		estimate.set(Some(bps(2_000_000))).unwrap();
1598
1599		let (_watched_broadcast, watched) = track(VIDEO);
1600		let _watched_sub = watched.subscribe(None);
1601		let watched_share = allocator.reserve(&watched.demand(), bps(4_000_000));
1602
1603		let (_idle_broadcast, idle) = track(VIDEO);
1604		let idle_share = allocator.reserve(&idle.demand(), bps(4_000_000));
1605
1606		assert_eq!(watched_share.rate(), Some(bps(2_000_000)));
1607		// What it would get if a viewer joined: an even split with the watched track.
1608		assert_eq!(idle_share.rate(), Some(bps(1_000_000)));
1609
1610		// It joins, and the split happens.
1611		let _idle_sub = idle.subscribe(None);
1612		assert_eq!(watched_share.rate(), Some(bps(1_000_000)));
1613		assert_eq!(idle_share.rate(), Some(bps(1_000_000)));
1614	}
1615
1616	/// Demand transitions have to wake a parked share, not just change what a later
1617	/// `peek` would see; the encoder is sitting in a `select!` on `changed`.
1618	#[kio::test]
1619	#[cfg(feature = "async")]
1620	async fn a_share_wakes_when_a_sibling_goes_idle() {
1621		let estimate = Producer::new();
1622		let allocator = Allocator::new(estimate.consume());
1623		estimate.set(Some(bps(2_000_000))).unwrap();
1624
1625		let (_mine_broadcast, mine) = track(VIDEO);
1626		let _mine_sub = mine.subscribe(None);
1627		let mine_share_reserved = allocator.reserve(&mine.demand(), bps(4_000_000));
1628		let mut mine_share = mine_share_reserved.consume();
1629
1630		let (_sibling_broadcast, sibling) = track(VIDEO);
1631		let sibling_sub = sibling.subscribe(None);
1632		let _sibling_share = allocator.reserve(&sibling.demand(), bps(4_000_000));
1633
1634		assert_eq!(mine_share.changed().await.unwrap(), Some(bps(1_000_000)));
1635
1636		// The sibling's last viewer leaves, so its half comes back to us.
1637		drop(sibling_sub);
1638		assert_eq!(mine_share.changed().await.unwrap(), Some(bps(2_000_000)));
1639	}
1640
1641	/// Records whether a parked poll was actually woken, which re-reading state on a
1642	/// fresh `poll` can't tell you: a lost wakeup still looks correct on the next poll
1643	/// and only shows up as a task that never runs again.
1644	#[derive(Default)]
1645	#[cfg(feature = "async")]
1646	struct Woken(std::sync::atomic::AtomicBool);
1647
1648	#[cfg(feature = "async")]
1649	impl std::task::Wake for Woken {
1650		fn wake(self: std::sync::Arc<Self>) {
1651			self.wake_by_ref();
1652		}
1653
1654		fn wake_by_ref(self: &std::sync::Arc<Self>) {
1655			self.0.store(true, std::sync::atomic::Ordering::SeqCst);
1656		}
1657	}
1658
1659	#[cfg(feature = "async")]
1660	impl Woken {
1661		/// A flag and its waiter. Both are returned because a [`kio::WaiterList`]
1662		/// holds only a `Weak`, so a waiter dropped at the end of the calling
1663		/// statement takes its own registration with it and never fires.
1664		fn new() -> (std::sync::Arc<Self>, kio::Waiter) {
1665			let flag = std::sync::Arc::new(Self::default());
1666			let waiter = kio::Waiter::new(std::task::Waker::from(flag.clone()));
1667			(flag, waiter)
1668		}
1669
1670		fn woken(&self) -> bool {
1671			self.0.load(std::sync::atomic::Ordering::SeqCst)
1672		}
1673	}
1674
1675	/// Regression: a share whose slice didn't move still has to leave the estimate's
1676	/// waker armed. Reservations cap the slice, so most estimate changes don't reach
1677	/// it, and a poll that returned the value without arming anything would park the
1678	/// encoder with nothing left to wake it.
1679	#[kio::test]
1680	#[cfg(feature = "async")]
1681	async fn an_unchanged_slice_keeps_watching_the_estimate() {
1682		let estimate = Producer::new();
1683		let allocator = Allocator::new(estimate.consume());
1684
1685		let (_broadcast, track) = track(VIDEO);
1686		let _sub = track.subscribe(None);
1687		let share_reserved = allocator.reserve(&track.demand(), bps(4_000_000));
1688		let mut share = share_reserved.consume();
1689
1690		estimate.set(Some(bps(10_000_000))).unwrap();
1691		assert_eq!(share.changed().await.unwrap(), Some(bps(4_000_000)));
1692
1693		// Still miles above the reservation, so the slice holds at 4 Mbps: the share
1694		// observes the change, decides it doesn't move, and parks.
1695		let (woken, waiter) = Woken::new();
1696		estimate.set(Some(bps(9_000_000))).unwrap();
1697		assert!(share.poll_changed(&waiter).is_pending());
1698
1699		// The estimate finally drops past the reservation: this has to reach it.
1700		estimate.set(Some(bps(1_000_000))).unwrap();
1701		assert!(woken.woken(), "a parked share must be woken by the next estimate");
1702		assert_eq!(share.changed().await.unwrap(), Some(bps(1_000_000)));
1703	}
1704
1705	/// The same, for the other input: a sibling's demand.
1706	#[kio::test]
1707	#[cfg(feature = "async")]
1708	async fn a_parked_share_is_woken_by_sibling_demand() {
1709		let estimate = Producer::new();
1710		let allocator = Allocator::new(estimate.consume());
1711		estimate.set(Some(bps(2_000_000))).unwrap();
1712
1713		let (_mine_broadcast, mine) = track(VIDEO);
1714		let _mine_sub = mine.subscribe(None);
1715		let share_reserved = allocator.reserve(&mine.demand(), bps(4_000_000));
1716		let mut share = share_reserved.consume();
1717
1718		let (_sibling_broadcast, sibling) = track(VIDEO);
1719		let sibling_sub = sibling.subscribe(None);
1720		let _sibling_share = allocator.reserve(&sibling.demand(), bps(4_000_000));
1721
1722		assert_eq!(share.changed().await.unwrap(), Some(bps(1_000_000)));
1723
1724		let (woken, waiter) = Woken::new();
1725		assert!(share.poll_changed(&waiter).is_pending());
1726		drop(sibling_sub);
1727		assert!(woken.woken(), "a sibling going idle must wake a parked share");
1728	}
1729
1730	/// A share follows the estimate's own lifecycle: unavailable while disconnected
1731	/// (hold the current rate), terminal once the session is gone for good.
1732	#[kio::test]
1733	#[cfg(feature = "async")]
1734	async fn a_share_follows_the_estimate_lifecycle() {
1735		let estimate = Producer::new();
1736		let allocator = Allocator::new(estimate.consume());
1737
1738		let (_broadcast, track) = track(VIDEO);
1739		let _sub = track.subscribe(None);
1740		let share_reserved = allocator.reserve(&track.demand(), bps(4_000_000));
1741		let mut share = share_reserved.consume();
1742
1743		estimate.set(Some(bps(2_000_000))).unwrap();
1744		assert_eq!(share.changed().await.unwrap(), Some(bps(2_000_000)));
1745
1746		estimate.set(None).unwrap();
1747		assert_eq!(share.changed().await.unwrap(), None);
1748
1749		drop(estimate);
1750		assert!(share.changed().await.is_err());
1751		assert!(share.changed().await.is_err());
1752	}
1753
1754	/// A closed track's entry can't linger: it would be walked on every poll for the
1755	/// rest of the connection, and a long-lived publisher churns tracks.
1756	#[test]
1757	fn a_closed_track_is_pruned() {
1758		let estimate = Producer::new();
1759		let allocator = Allocator::new(estimate.consume());
1760
1761		// Both shares are held: dropping one releases its reservation on its own,
1762		// which would prove nothing about pruning the track that closed.
1763		let (_first_broadcast, first) = track(VIDEO);
1764		let _first_share = allocator.reserve(&first.demand(), bps(4_000_000));
1765		first.abort(Error::Cancel).unwrap();
1766
1767		let (_second_broadcast, second) = track(VIDEO);
1768		let _second_share = allocator.reserve(&second.demand(), bps(4_000_000));
1769
1770		assert_eq!(allocator.registry.read().entries.len(), 1);
1771	}
1772
1773	/// Dropping the reservation hands the room back. The registry only ever prunes
1774	/// tracks that have *closed*, so a claim left behind by a track that is still
1775	/// publishing would stand for the rest of the connection.
1776	#[kio::test]
1777	#[cfg(feature = "async")]
1778	async fn dropping_a_reservation_releases_it() {
1779		let estimate = Producer::new();
1780		let allocator = Allocator::new(estimate.consume());
1781		estimate.set(Some(bps(2_000_000))).unwrap();
1782
1783		let (_first_broadcast, first) = track(VIDEO);
1784		let _first_sub = first.subscribe(None);
1785		let first_reserved = allocator.reserve(&first.demand(), bps(4_000_000));
1786
1787		let (_second_broadcast, second) = track(VIDEO);
1788		let _second_sub = second.subscribe(None);
1789		let second_reserved = allocator.reserve(&second.demand(), bps(4_000_000));
1790		assert_eq!(second_reserved.rate(), Some(bps(1_000_000)));
1791
1792		// A read handle is not the claim: the reservation outliving it is what keeps the
1793		// room, and the reservation going away is what returns it.
1794		let mut orphan = first_reserved.consume();
1795		assert_eq!(orphan.changed().await.unwrap(), Some(bps(1_000_000)));
1796
1797		drop(first_reserved);
1798		assert_eq!(allocator.registry.read().entries.len(), 1);
1799		assert_eq!(second_reserved.rate(), Some(bps(2_000_000)));
1800
1801		// The orphaned reader is woken and told, rather than being left parked on a slice
1802		// that will never move again. It reports the same "hold your rate" as a missing
1803		// estimate, not a grant of zero that would tell an encoder to stop.
1804		assert_eq!(orphan.changed().await.unwrap(), None);
1805		assert_eq!(orphan.peek(), None);
1806	}
1807
1808	/// A sender whose ceiling moved (a capture reopening at a resolution it negotiated
1809	/// with the device) changes the claim in place. Re-reserving instead would claim
1810	/// twice, since nothing releases the first entry while the track is still alive.
1811	#[test]
1812	fn update_changes_the_claim_in_place() {
1813		let estimate = Producer::new();
1814		let allocator = Allocator::new(estimate.consume());
1815		estimate.set(Some(bps(6_000_000))).unwrap();
1816
1817		let (_small_broadcast, small) = track(VIDEO);
1818		let _small_sub = small.subscribe(None);
1819		let small_reserved = allocator.reserve(&small.demand(), bps(1_000_000));
1820
1821		let (_large_broadcast, large) = track(VIDEO);
1822		let _large_sub = large.subscribe(None);
1823		let large_reserved = allocator.reserve(&large.demand(), bps(8_000_000));
1824
1825		// Max-min fair: the small claim is satisfied in full, the rest goes to the other.
1826		assert_eq!(small_reserved.rate(), Some(bps(1_000_000)));
1827		assert_eq!(large_reserved.rate(), Some(bps(5_000_000)));
1828
1829		// It reopens at a mode that can use much more, and the split follows without a
1830		// second entry appearing.
1831		small_reserved.update(bps(4_000_000));
1832		assert_eq!(allocator.registry.read().entries.len(), 2);
1833		assert_eq!(small_reserved.rate(), Some(bps(3_000_000)));
1834		assert_eq!(large_reserved.rate(), Some(bps(3_000_000)));
1835
1836		// And back down, which has to release the difference rather than hold it.
1837		small_reserved.update(bps(1_000_000));
1838		assert_eq!(large_reserved.rate(), Some(bps(5_000_000)));
1839	}
1840
1841	/// Collected-language callers can relinquish a ceiling before their retained
1842	/// handle is finalized, without ending the track or waiting for its subscribers.
1843	#[test]
1844	fn zero_ceiling_releases_share_and_probe_target() {
1845		let estimate = Producer::new();
1846		let allocator = Allocator::new(estimate.consume());
1847		estimate.set(Some(bps(3_000_000))).unwrap();
1848		let mut target = allocator.target();
1849		let waiter = kio::Waiter::noop();
1850
1851		let (_encoder_broadcast, encoder) = track(VIDEO);
1852		let _encoder_sub = encoder.subscribe(None);
1853		let retired = allocator.reserve(&encoder.demand(), bps(4_000_000));
1854		let replacement = allocator.reserve(&encoder.demand(), bps(4_000_000));
1855		let (_sibling_broadcast, sibling) = track(VIDEO);
1856		let _sibling_sub = sibling.subscribe(None);
1857		let sibling = allocator.reserve(&sibling.demand(), bps(4_000_000));
1858		assert_eq!(sibling.rate(), Some(bps(1_000_000)));
1859		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(12_000_000)));
1860
1861		retired.update(Rate::ZERO);
1862		assert_eq!(retired.rate(), Some(Rate::ZERO));
1863		assert_eq!(replacement.rate(), Some(bps(1_500_000)));
1864		assert_eq!(sibling.rate(), Some(bps(1_500_000)));
1865		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(8_000_000)));
1866		retired.update(Rate::ZERO);
1867		assert!(target.poll_changed(&waiter).is_pending());
1868
1869		// The registration remains usable, so an encoder may resume in place.
1870		retired.update(bps(4_000_000));
1871		assert_eq!(sibling.rate(), Some(bps(1_000_000)));
1872		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(12_000_000)));
1873		assert!(encoder.demand().is_wanted());
1874	}
1875
1876	/// A reader parked on `changed` has to be woken by its own reservation moving, not
1877	/// just by the estimate or a sibling: the encoder is sitting in a `select!` on it.
1878	#[kio::test]
1879	#[cfg(feature = "async")]
1880	async fn update_wakes_a_parked_reader() {
1881		let estimate = Producer::new();
1882		let allocator = Allocator::new(estimate.consume());
1883		estimate.set(Some(bps(6_000_000))).unwrap();
1884
1885		let (_broadcast, producer) = track(VIDEO);
1886		let _sub = producer.subscribe(None);
1887		let reserved = allocator.reserve(&producer.demand(), bps(1_000_000));
1888		let mut share = reserved.consume();
1889		assert_eq!(share.changed().await.unwrap(), Some(bps(1_000_000)));
1890
1891		let (woken, waiter) = Woken::new();
1892		assert!(share.poll_changed(&waiter).is_pending());
1893
1894		reserved.update(bps(4_000_000));
1895		assert!(woken.woken(), "raising the ceiling must wake the reader");
1896		assert_eq!(share.changed().await.unwrap(), Some(bps(4_000_000)));
1897	}
1898
1899	/// The registry is the allocator's, not a share's: a share that outlives every
1900	/// allocator reports the estimate as gone rather than keeping the channel open.
1901	#[kio::test]
1902	#[cfg(feature = "async")]
1903	async fn a_share_outliving_the_allocator_reports_closed() {
1904		let estimate = Producer::new();
1905		let allocator = Allocator::new(estimate.consume());
1906
1907		let (_broadcast, producer) = track(VIDEO);
1908		let _sub = producer.subscribe(None);
1909		let share_reserved = allocator.reserve(&producer.demand(), bps(4_000_000));
1910		let mut share = share_reserved.consume();
1911
1912		drop(allocator);
1913		drop(estimate);
1914		assert!(share.changed().await.is_err());
1915	}
1916
1917	/// An unavailable estimate and a dead producer must not look alike: a caller
1918	/// holds its rate for the former and stops watching for the latter.
1919	/// Reporting closure as `Ok(None)` would spin any `select!` over `changed()`,
1920	/// because a closed channel is always immediately ready.
1921	#[kio::test]
1922	#[cfg(feature = "async")]
1923	async fn closed_is_distinct_from_unavailable() {
1924		let producer = Producer::new();
1925		let mut consumer = producer.consume();
1926
1927		producer.set(Some(bps(1_000_000))).unwrap();
1928		assert_eq!(consumer.changed().await.unwrap(), Some(bps(1_000_000)));
1929
1930		// Live, but the estimate went away (e.g. disconnected): still watchable.
1931		producer.set(None).unwrap();
1932		assert_eq!(consumer.changed().await.unwrap(), None);
1933
1934		// Gone for good.
1935		drop(producer);
1936		assert!(consumer.changed().await.is_err());
1937		// And it stays terminal rather than flapping back to a value.
1938		assert!(consumer.changed().await.is_err());
1939	}
1940
1941	/// The target sums every reservation, demanded or not, and follows each one
1942	/// being added, moved, released, or pruned with its track, waking the session
1943	/// that follows it.
1944	#[test]
1945	#[cfg(feature = "async")]
1946	fn the_target_sums_every_reservation() {
1947		let allocator = Allocator::unlimited();
1948		let mut target = allocator.target();
1949		let (woken, waiter) = Woken::new();
1950		assert_eq!(target.poll_changed(&waiter), Poll::Ready(Rate::ZERO));
1951		assert!(target.poll_changed(&waiter).is_pending());
1952
1953		let (_watched_broadcast, watched) = track(VIDEO);
1954		let _sub = watched.subscribe(None);
1955		let watched = allocator.reserve(&watched.demand(), bps(4_000_000));
1956		assert!(woken.woken(), "a reservation must wake the session");
1957		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(4_000_000)));
1958
1959		// Nobody watches this one, which is exactly the rung that must still be funded.
1960		let (_idle_broadcast, idle_track) = track(VIDEO);
1961		let idle = allocator.reserve(&idle_track.demand(), bps(1_000_000));
1962		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(5_000_000)));
1963
1964		idle.update(bps(2_000_000));
1965		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(6_000_000)));
1966
1967		drop(watched);
1968		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(2_000_000)));
1969
1970		// A closed track's claim leaves with the next registration, even while its
1971		// reservation is still held.
1972		idle_track.abort(Error::Cancel).unwrap();
1973		let (_other_broadcast, other) = track(VIDEO);
1974		let _other = allocator.reserve(&other.demand(), bps(500_000));
1975		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(500_000)));
1976		drop(idle);
1977		assert!(
1978			target.poll_changed(&waiter).is_pending(),
1979			"a pruned claim is not released twice"
1980		);
1981	}
1982
1983	/// A reservation is probed while a session follows its allocator's target, and a
1984	/// reader parked on an unchanged slice is woken when that flips.
1985	#[test]
1986	#[cfg(feature = "async")]
1987	fn a_following_session_marks_reservations_probed() {
1988		let estimate = Producer::new();
1989		estimate.set(Some(bps(2_000_000))).unwrap();
1990		let allocator = Allocator::new(estimate.consume());
1991		let (_broadcast, producer) = track(VIDEO);
1992		let _sub = producer.subscribe(None);
1993		let reservation = allocator.reserve(&producer.demand(), bps(4_000_000));
1994		let mut grant = reservation.consume();
1995		let (woken, waiter) = Woken::new();
1996		assert!(matches!(grant.poll_changed(&waiter), Poll::Ready(Ok(Some(rate))) if rate == bps(2_000_000)));
1997		assert!(!grant.probed());
1998		assert!(grant.poll_changed(&waiter).is_pending());
1999
2000		let target = allocator.target();
2001		assert!(woken.woken(), "a session starting to probe must wake the reader");
2002		assert!(matches!(grant.poll_changed(&waiter), Poll::Ready(Ok(Some(rate))) if rate == bps(2_000_000)));
2003		assert!(grant.probed());
2004		assert!(grant.poll_changed(&waiter).is_pending());
2005
2006		// A zero target turns probing off, though the session still follows it.
2007		let (woken, waiter) = Woken::new();
2008		assert!(grant.poll_changed(&waiter).is_pending());
2009		allocator.set_target(Some(Rate::ZERO));
2010		assert!(woken.woken(), "turning probing off must wake the reader");
2011		assert!(matches!(grant.poll_changed(&waiter), Poll::Ready(Ok(Some(rate))) if rate == bps(2_000_000)));
2012		assert!(!grant.probed());
2013		allocator.set_target(None);
2014		assert!(matches!(grant.poll_changed(&waiter), Poll::Ready(Ok(Some(rate))) if rate == bps(2_000_000)));
2015		assert!(grant.probed());
2016
2017		drop(target);
2018		assert!(matches!(grant.poll_changed(&waiter), Poll::Ready(Ok(Some(rate))) if rate == bps(2_000_000)));
2019		assert!(!grant.probed());
2020		assert!(!estimate.consume().probed(), "a whole estimate is never probed");
2021	}
2022
2023	/// The override replaces the sum for every clone until it is cleared.
2024	#[test]
2025	fn an_override_replaces_the_sum() {
2026		let allocator = Allocator::unlimited();
2027		let mut target = allocator.target();
2028		let waiter = kio::Waiter::noop();
2029
2030		let (_broadcast, producer) = track(VIDEO);
2031		let _reserved = allocator.reserve(&producer.demand(), bps(4_000_000));
2032		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(4_000_000)));
2033
2034		allocator.clone().set_target(Some(Rate::ZERO));
2035		assert_eq!(target.poll_changed(&waiter), Poll::Ready(Rate::ZERO));
2036
2037		allocator.set_target(None);
2038		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(4_000_000)));
2039	}
2040
2041	/// Several broadcasts on one connection each read their own slice of the receive
2042	/// estimate, max-min fair by ceiling, so together they never claim more than it.
2043	#[test]
2044	fn viewers_split_the_estimate_max_min_fair() {
2045		let estimate = Producer::new();
2046		let viewers = Viewers::new(estimate.weak());
2047		let small = viewers.watch(bps(1_000_000)).unwrap();
2048		let large = viewers.watch(bps(8_000_000)).unwrap();
2049		assert_eq!(small.rate(), None, "no estimate yet: hold the selection");
2050
2051		estimate.set(Some(bps(6_000_000))).unwrap();
2052		assert_eq!(small.rate(), Some(bps(1_000_000)));
2053		assert_eq!(large.rate(), Some(bps(5_000_000)));
2054
2055		let third = viewers.watch(bps(4_000_000)).unwrap();
2056		let grants = [&small, &large, &third].map(|viewer| viewer.rate().unwrap());
2057		assert_eq!(grants, [bps(1_000_000), bps(2_500_000), bps(2_500_000)]);
2058		assert!(grants.iter().map(|rate| rate.as_bps()).sum::<u64>() <= 6_000_000);
2059
2060		// A viewer that leaves hands its slice back.
2061		drop(third);
2062		assert_eq!(large.rate(), Some(bps(5_000_000)));
2063	}
2064
2065	/// The PROBE target sums every live viewer's ceiling until overridden.
2066	#[test]
2067	fn the_viewers_target_sums_their_ceilings() {
2068		let viewers = Viewers::default();
2069		let mut target = viewers.target();
2070		let waiter = kio::Waiter::noop();
2071		assert_eq!(target.poll_changed(&waiter), Poll::Ready(Rate::ZERO));
2072
2073		let first = viewers.watch(bps(3_000_000)).unwrap();
2074		let second = viewers.clone().watch(bps(2_000_000)).unwrap();
2075		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(5_000_000)));
2076		first.update(bps(1_000_000)).unwrap();
2077		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(3_000_000)));
2078
2079		viewers.set_target(Some(Rate::ZERO)).unwrap();
2080		assert_eq!(target.poll_changed(&waiter), Poll::Ready(Rate::ZERO));
2081		viewers.set_target(None).unwrap();
2082		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(3_000_000)));
2083
2084		drop(second);
2085		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(1_000_000)));
2086		drop(first);
2087		assert_eq!(target.poll_changed(&waiter), Poll::Ready(Rate::ZERO));
2088	}
2089
2090	/// The viewers' ceilings sum to at most what every PROBE encoding carries: a viewer,
2091	/// update, or override past it is refused and leaves the target as it was.
2092	#[test]
2093	fn viewer_targets_stay_encodable() {
2094		let viewers = Viewers::default();
2095		let mut target = viewers.target();
2096		let waiter = kio::Waiter::noop();
2097		let max = Viewers::MAX_TARGET.as_bps();
2098		let bounds = |res: Result<()>| matches!(res, Err(Error::BoundsExceeded(_)));
2099
2100		assert!(bounds(viewers.watch(bps(max + 1)).map(drop)));
2101		let first = viewers.watch(bps(max - 1)).unwrap();
2102		assert!(bounds(viewers.watch(bps(2)).map(drop)), "the sum would pass the limit");
2103		let second = viewers.watch(bps(1)).unwrap();
2104		assert_eq!(target.poll_changed(&waiter), Poll::Ready(Viewers::MAX_TARGET));
2105
2106		assert!(bounds(second.update(bps(2))));
2107		first.update(bps(1)).unwrap();
2108		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(2)));
2109		second.update(bps(max - 1)).unwrap();
2110		assert_eq!(target.poll_changed(&waiter), Poll::Ready(Viewers::MAX_TARGET));
2111
2112		viewers.set_target(Some(bps(1_000_000))).unwrap();
2113		assert!(bounds(viewers.set_target(Some(bps(max + 1)))));
2114		assert_eq!(target.poll_changed(&waiter), Poll::Ready(bps(1_000_000)));
2115		viewers.set_target(Some(Viewers::MAX_TARGET)).unwrap();
2116		assert_eq!(target.poll_changed(&waiter), Poll::Ready(Viewers::MAX_TARGET));
2117	}
2118
2119	/// A held viewer is what requests the receive estimate (and so PROBE); the registry
2120	/// alone is not, so a session holding one opens no PROBE stream.
2121	#[test]
2122	fn a_viewer_requests_the_estimate() {
2123		let estimate = Producer::new();
2124		let viewers = Viewers::new(estimate.weak());
2125		assert!(!estimate.demand().wanted());
2126
2127		let viewer = viewers.watch(bps(1_000_000)).unwrap();
2128		assert!(estimate.demand().wanted());
2129		let grant = viewer.consume();
2130		drop(viewer);
2131		assert!(
2132			estimate.demand().wanted(),
2133			"a grant read from the viewer still wants it"
2134		);
2135		drop(grant);
2136		assert!(!estimate.demand().wanted());
2137	}
2138}