Skip to main content

moq_video/encode/
producer.rs

1//! Encode raw frames and publish them as a moq video track, following the uplink's grant.
2
3use std::sync::Arc;
4use std::task::Poll;
5
6use moq_mux::catalog::hang::CatalogExt;
7use moq_mux::rate;
8use moq_net::bandwidth::Rate;
9
10use super::Sink;
11use super::encoder::{Codec, Config};
12use super::publisher::{Finished, Publisher};
13use crate::{Error, Frame};
14
15/// Encode and publication policy for [`Producer`].
16///
17/// `#[non_exhaustive]`: construct via [`Options::new`] and set fields, so new knobs can be added
18/// without breaking callers.
19#[derive(Clone, Debug)]
20#[non_exhaustive]
21pub struct Options {
22	/// Track name to publish under. `None` derives a unique one from the codec (`0.avc3`, then
23	/// `1.avc3`, ...). Subscribers find it through the catalog either way.
24	pub track: Option<String>,
25	/// The encoder: the geometry every written frame has, the codec, the backend, and the
26	/// [`bitrate`](Config::bitrate), which is the ceiling the grant never raises it past.
27	pub config: Config,
28	/// The connection's bandwidth, as an allocator over
29	/// [`Session::send_bandwidth`](moq_net::Session::send_bandwidth) (or
30	/// `moq_tokio::Connection::send_bandwidth`, which survives reconnects).
31	///
32	/// The track reserves its ceiling against it and, while someone watches, retunes the encoder
33	/// to its share between frames, per the default [`rate::Policy`], so a closing uplink gets a
34	/// softer picture instead of a stalled one. Pass the same allocator to every sender on the
35	/// connection, audio included, so their bitrates sum to the uplink instead of each matching it.
36	///
37	/// Defaults to [`Allocator::unlimited`](moq_net::bandwidth::Allocator::unlimited), which holds
38	/// the ceiling regardless of congestion.
39	pub bandwidth: moq_net::bandwidth::Allocator,
40	/// The next lower rendition of the same source, when this one is encoded beside it.
41	///
42	/// Makes this rendition a simulcast rung: while the grant can no longer fund it, it stops
43	/// encoding, drops what is written to it, and advertises itself disabled, so the lower
44	/// renditions keep their share, and it resumes on a keyframe once the grant recovers. It takes
45	/// the track priority one below the lower rendition's, so the allocator fills that one first.
46	/// Needs a [`bandwidth`](Self::bandwidth) to follow, and a ceiling above the lower one's.
47	pub lower: Option<Rung>,
48}
49
50impl Options {
51	/// Encode with `config`, holding its bitrate.
52	pub fn new(config: Config) -> Self {
53		Self {
54			track: None,
55			config,
56			bandwidth: moq_net::bandwidth::Allocator::unlimited(),
57			lower: None,
58		}
59	}
60}
61
62/// A rendition's place in a simulcast ladder, from [`Producer::rung`], which the next
63/// rendition up takes as its [`Options::lower`].
64///
65/// Watches the rendition without keeping it publishing: once it finishes or drops, the rung
66/// above has nothing to fall back to and never disables.
67#[derive(Clone)]
68pub struct Rung {
69	ceiling: kio::Consumer<Rate>,
70	priority: i8,
71}
72
73impl std::fmt::Debug for Rung {
74	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75		f.debug_struct("Rung")
76			.field("ceiling", &*self.ceiling.read())
77			.field("priority", &self.priority)
78			.finish()
79	}
80}
81
82impl Rung {
83	/// The rendition's current ceiling, or `None` once it ended. Arms `waiter` for either change.
84	fn ceiling(&self, waiter: &kio::Waiter) -> Option<Rate> {
85		match self.ceiling.poll(waiter, |_| Poll::<()>::Pending) {
86			Poll::Pending => Some(*self.ceiling.read()),
87			// The closure never completes, so this is the channel closing.
88			Poll::Ready(_) => None,
89		}
90	}
91}
92
93/// What a [`Producer`]'s encoder is doing.
94enum Encoding {
95	/// Encoding every frame written.
96	Open(Sink),
97	/// Stopped by a [`discontinuity`](Producer::discontinuity) or a capture between sources: the
98	/// next frame written reopens it.
99	Idle,
100	/// Stopped while the grant cannot fund this rung: frames written are dropped until it resumes.
101	Disabled,
102}
103
104/// Encode raw [`Frame`]s and publish them as a moq video track (avc3 / hev1 by codec).
105///
106/// The counterpart of `moq_audio::encode::Producer`: it owns its encoder, registers the catalog
107/// rendition at construction, probed from the encoder so a subscriber can discover the track
108/// before a frame is written, and follows the [`bandwidth`](Options::bandwidth) grant between
109/// frames. [`Publisher`] is the layer below, for frames you encoded yourself.
110///
111/// While nobody watches, a rendition with no [`lower`](Options::lower) one encodes at its
112/// ceiling and ignores the grant: its groups wait in the cache rather than being paced to a
113/// subscriber, and the next viewer's grant applies afresh. A rung keeps following the grant,
114/// which reports the slice it would get back, so it resumes after its viewers left.
115///
116/// The `async` methods are not cancel-safe, as [`Sink`]'s are not: a cancelled one leaves the
117/// encoder refusing every later call, so drop the producer instead.
118pub struct Producer {
119	publisher: Publisher,
120	encoding: Encoding,
121	/// The encoder settings, whose bitrate is the ceiling, to reopen with.
122	config: Config,
123	/// The ceiling, which caps every grant. A channel, so a rung above this rendition wakes when
124	/// it moves and when this rendition ends.
125	ceiling: kio::Producer<Rate>,
126	/// The track priority, which a higher rung takes one below.
127	priority: i8,
128	lower: Option<Rung>,
129	/// Reserves against the track a decoder identity change moves the rendition to.
130	allocator: moq_net::bandwidth::Allocator,
131	/// This rendition's claim on the track named by `demand`.
132	reservation: Arc<moq_net::bandwidth::Reservation>,
133	/// The track `reservation` claims on, which stays the published one until a frame moves it.
134	demand: moq_net::track::Demand,
135	/// `None` once retired: the grant ended for good, so the encoder holds its rate.
136	grant: Option<rate::Grant>,
137	/// What the encoder produces, or reopens at.
138	target: rate::Target,
139	/// Whether someone watched at the last write, so a rendition that never disables rests at
140	/// its ceiling once nobody does.
141	watched: bool,
142	/// Whether nothing has been published since the last break marker, which a second break
143	/// would only repeat.
144	marked: bool,
145	/// Whether a resume's encoder refused the funded rate, so this rung now resumes only at its
146	/// full ceiling, which needs no retune, rather than overshoot a partial grant.
147	ceiling_only: bool,
148	/// The soonest a resume at the ceiling that failed is tried again, a grant's retry step later.
149	resume_retry: Option<kio::clock::Instant>,
150	/// Whether the grant is being followed with nothing written, so a resume re-enables the rung
151	/// without opening an encoder nobody would feed.
152	unwritten: bool,
153}
154
155impl Producer {
156	/// Open the encoder and publish a track for it in `broadcast`, registering its rendition in
157	/// `catalog` immediately.
158	///
159	/// The rendition comes from [`Config::probe`], so it says what the first keyframe will. An
160	/// unsupported codec, resolution, or backend fails here, before the track exists.
161	pub async fn new<E: CatalogExt>(
162		broadcast: &moq_net::broadcast::Producer,
163		catalog: moq_mux::catalog::Producer<E>,
164		options: Options,
165	) -> Result<Self, Error> {
166		let name = options.track.clone();
167		let codec = options.config.codec;
168		Self::open_on(catalog, options, |info| match name {
169			Some(name) => Ok(broadcast.create_track(name, info).ok_or(moq_net::Error::Duplicate)?),
170			None => Ok(broadcast.unique_track(suffix(codec), info)),
171		})
172		.await
173	}
174
175	/// Open the encoder and publish the track a subscriber's `request` asks for, registering its
176	/// rendition in `catalog` immediately, as [`new`](Self::new) does.
177	///
178	/// This is how an on-demand publisher serves a track asked for again after its last producer
179	/// dropped while read: serve it with the options it was first published with. Its readers
180	/// hold the track info they set, so options that change it (such as the priority a
181	/// [`lower`](Options::lower) rung sets) end the track with
182	/// [`MalformedTrack`](moq_net::Error::MalformedTrack) and fail here. Nothing checks the rest: its
183	/// readers also decode with the codec settings they were first given, so keep those too. The
184	/// request names the track, so [`Options::track`] must be `None`. A config this machine can't
185	/// encode rejects the request with [`NotFound`](moq_net::Error::NotFound), and a
186	/// rendition the catalog refuses ends the accepted track with it.
187	pub async fn requested<E: CatalogExt>(
188		request: moq_net::track::Request,
189		catalog: moq_mux::catalog::Producer<E>,
190		options: Options,
191	) -> Result<Self, Error> {
192		let mut request = Some(request);
193		let opened = match options.track {
194			Some(_) => Err(Error::UnsupportedConfig("a requested track is already named".into())),
195			None => {
196				Self::open_on(catalog, options, |info| {
197					Ok(accepted(request.take().expect("accepted once"), info)?)
198				})
199				.await
200			}
201		};
202		// Not accepted: the subscribers waiting on it learn it won't be served. `NotFound`, not
203		// `Unsupported`, which moq-lite sends as a retryable `Internal`, so a relay would ask again.
204		if let (Err(_), Some(request)) = (&opened, request) {
205			request.reject(moq_net::Error::NotFound);
206		}
207		opened
208	}
209
210	/// Open the encoder and publish it on the track `create` makes from its info.
211	async fn open_on<E: CatalogExt>(
212		catalog: moq_mux::catalog::Producer<E>,
213		options: Options,
214		create: impl FnOnce(moq_net::track::Info) -> Result<moq_net::track::Producer, Error>,
215	) -> Result<Self, Error> {
216		let Options {
217			track: _,
218			config,
219			bandwidth,
220			lower,
221		} = options;
222		let ceiling = config.resolved_bitrate();
223		if let Some(below) = lower.as_ref().and_then(|lower| lower.ceiling(&kio::Waiter::noop()))
224			&& below >= ceiling
225		{
226			return Err(Error::UnsupportedConfig(format!(
227				"the lower rendition's {} bps is not below this one's {} bps",
228				below.as_bps(),
229				ceiling.as_bps()
230			)));
231		}
232		// Both before the track exists: a config this machine can't encode fails without leaving
233		// a track advertised that will never carry frames. The probe closes its encoder before this
234		// one opens, so only one codec session is live.
235		let rendition = config.probe().await?;
236		let sink = Sink::open(&config).await?;
237
238		let priority = lower
239			.as_ref()
240			.map_or(hang::catalog::PRIORITY.video, |lower| lower.priority.saturating_sub(1));
241		let track = create(catalog.track_info(priority))?;
242		let mut producer = Self::with_track(track, &catalog, config, rendition, bandwidth, lower)?;
243		producer.encoding = Encoding::Open(sink);
244		Ok(producer)
245	}
246
247	/// Publish `rendition` on `track` with no encoder open yet: the next frame written, or
248	/// [`open`](Self::open), opens one.
249	pub(crate) fn with_track<E: CatalogExt>(
250		track: moq_net::track::Producer,
251		catalog: &moq_mux::catalog::Producer<E>,
252		mut config: Config,
253		rendition: hang::catalog::VideoConfig,
254		allocator: moq_net::bandwidth::Allocator,
255		lower: Option<Rung>,
256	) -> Result<Self, Error> {
257		let priority = track.info().priority;
258		// Held to end the track if the catalog refuses the rendition, so a subscriber already
259		// waiting on it learns that rather than reading a drop.
260		let held = track.clone();
261		let publisher = match Publisher::new(
262			track,
263			catalog.reserve().with_interval(config.effective_join()),
264			rendition,
265		) {
266			Ok(publisher) => publisher,
267			Err(err) => {
268				let _ = held.abort(moq_net::Error::NotFound);
269				return Err(err);
270			}
271		};
272		drop(held);
273		let ceiling = config.resolved_bitrate();
274		config.bitrate = Some(ceiling);
275		let demand = publisher.demand();
276		let reservation = Arc::new(allocator.reserve(&demand, ceiling));
277		let grant = rate::Grant::new(reservation.consume(), policy(ceiling, lower.as_ref()));
278		publisher.report_bitrate(ceiling);
279		Ok(Self {
280			publisher,
281			encoding: Encoding::Idle,
282			config,
283			ceiling: kio::Producer::new(ceiling),
284			priority,
285			lower,
286			allocator,
287			reservation,
288			demand,
289			grant: Some(grant),
290			target: rate::Target::Enabled(ceiling),
291			watched: false,
292			marked: false,
293			ceiling_only: false,
294			resume_retry: None,
295			unwritten: false,
296		})
297	}
298
299	/// A watch-only handle to the published track's subscriber demand. A frame that changes the
300	/// decoder identity, such as a resume at a ceiling past the declared level, moves the
301	/// rendition to a newly named track, so read this again after [`write`](Self::write).
302	pub fn demand(&self) -> moq_net::track::Demand {
303		self.publisher.demand()
304	}
305
306	/// A handle that aborts the published track without keeping it open, so an owner can end
307	/// it while a [`write`](Self::write) still holds this producer. Like [`demand`](Self::demand),
308	/// read it again after a write.
309	pub fn abort_handle(&self) -> moq_net::track::AbortHandle {
310		self.publisher.abort_handle()
311	}
312
313	/// This rendition's place in a simulcast ladder, for the next rendition up to take as its
314	/// [`Options::lower`].
315	pub fn rung(&self) -> Rung {
316		Rung {
317			ceiling: self.ceiling.consume(),
318			priority: self.priority,
319		}
320	}
321
322	/// This track's claim on the [`bandwidth`](Options::bandwidth) allocator, whose
323	/// [`rate`](moq_net::bandwidth::Reservation::rate) is the grant the encoder follows. A frame
324	/// that moves the rendition to a new track claims on that one instead, so read this again
325	/// after [`write`](Self::write).
326	pub fn reservation(&self) -> &Arc<moq_net::bandwidth::Reservation> {
327		&self.reservation
328	}
329
330	/// The bitrate the encoder produces at, or `None` while a rung is disabled.
331	pub fn bitrate(&self) -> Option<Rate> {
332		match self.target {
333			rate::Target::Enabled(bitrate) => Some(bitrate),
334			rate::Target::Disabled => None,
335		}
336	}
337
338	/// Encode and publish one frame at its own timestamp, at the configured size.
339	///
340	/// Follows any grant change first, so the encoder retunes between frames rather than mid-
341	/// encode. A backend that pipelines publishes an earlier frame's output here, so a call that
342	/// publishes nothing is normal. While a rung is disabled, the frame is dropped unencoded.
343	///
344	/// Takes the frame as anything that can become an [`Arc`], like [`Sink::encode`], so a
345	/// source fanning one frame out to a ladder hands each rung a clone of the handle.
346	pub async fn write(&mut self, frame: impl Into<Arc<Frame>>) -> Result<(), Error> {
347		self.follow().await;
348		if let Encoding::Idle = self.encoding {
349			let wanted = self.bitrate().unwrap_or(*self.ceiling.read());
350			if let Some(sink) = self.reopen(wanted).await? {
351				self.encoding = Encoding::Open(sink);
352			}
353		}
354		let Encoding::Open(sink) = &mut self.encoding else {
355			return Ok(());
356		};
357		sink.encode(frame).await?;
358		self.publish_ready()
359	}
360
361	/// Cut a new group at the next written frame.
362	///
363	/// Optional: the encoder already keyframes every [`join`](Config::join), and each of those cuts
364	/// a group. Reach for it to place a boundary the encoder cannot see, such as a scene change.
365	/// Fails when the encoder cannot force a keyframe, leaving groups to that interval. A stopped
366	/// encoder opens with a keyframe anyway, so this does nothing then.
367	pub async fn cut(&mut self) -> Result<(), Error> {
368		match &mut self.encoding {
369			Encoding::Open(sink) => sink.cut().await,
370			Encoding::Idle | Encoding::Disabled => Ok(()),
371		}
372	}
373
374	/// Set the ceiling to `bitrate`, retuning the encoder to it from roughly the next frame. No
375	/// keyframe is forced. The reservation moves with it, so a later grant never retunes above it.
376	///
377	/// Some backends cannot raise past the bitrate they opened at (openh264), so configure the
378	/// highest you will ask for and adapt downwards. A refused rate, such as
379	/// [`Error::BitrateUnsupported`] or openh264's raise past its opening rate, changes nothing:
380	/// the encoder keeps encoding at its current rate. Only [`Error::CodecGone`] means it stopped.
381	pub async fn set_bitrate(&mut self, bitrate: Rate) -> Result<(), Error> {
382		if let Encoding::Open(sink) = &mut self.encoding {
383			sink.set_bitrate(bitrate).await?;
384		}
385		if !matches!(self.encoding, Encoding::Disabled) {
386			self.target = rate::Target::Enabled(bitrate);
387			self.publisher.report_bitrate(bitrate);
388		}
389		self.config.bitrate = Some(bitrate);
390		if let Ok(mut ceiling) = self.ceiling.write() {
391			*ceiling = bitrate;
392		}
393		self.reservation.update(bitrate);
394		// The grant follows from the rate the encoder applied itself, even when the ceiling is
395		// unchanged and the policy with it, so a grant below it retunes back down.
396		if let Some(grant) = self.grant.as_mut() {
397			grant.set_policy(policy(bitrate, self.lower.as_ref()));
398			if !matches!(self.encoding, Encoding::Disabled) {
399				grant.assume(rate::Target::Enabled(bitrate));
400			}
401		}
402		Ok(())
403	}
404
405	/// Mark a break in the published timeline: what is written next does not continue what came
406	/// before.
407	///
408	/// Call this when the source stops rather than merely pausing between frames, such as a
409	/// paused game or a source switch. The encoder drains into the track and closes, so what
410	/// resumes opens a group with a keyframe from a fresh one. Errors when the drain fails, after
411	/// the break is marked anyway: only those last frames are lost.
412	pub async fn discontinuity(&mut self) -> Result<(), Error> {
413		let drained = self.close().await;
414		self.mark()?;
415		drained
416	}
417
418	/// Drain the encoder into the track and finish it.
419	///
420	/// Consumes the producer, releasing the encoder and the bandwidth claim. The returned
421	/// [`Finished`] keeps the track and its catalog rendition published, and can still
422	/// [`abort`](Finished::abort) them. A drain that fails ends the track with an error instead,
423	/// since a clean end promises a subscriber everything the publisher produced.
424	pub async fn finish(self) -> Result<Finished, Error> {
425		let Self {
426			mut publisher,
427			encoding,
428			ceiling,
429			reservation,
430			..
431		} = self;
432		// The claim goes before the drain, so siblings can take the room while the last frames go
433		// out, and the ceiling closes, so a rung above stops counting on this one now.
434		drop((ceiling, reservation));
435		let drained = match encoding {
436			Encoding::Open(mut sink) => {
437				async {
438					sink.flush().await?;
439					while let Some(encoded) = sink.receive()? {
440						publisher.publish(&encoded)?;
441					}
442					Ok::<_, Error>(())
443				}
444				.await
445			}
446			Encoding::Idle | Encoding::Disabled => Ok(()),
447		};
448		match drained {
449			Ok(()) => publisher.finish(),
450			Err(err) => {
451				publisher.abort(moq_net::Error::Transport(err.to_string()));
452				Err(err)
453			}
454		}
455	}
456
457	/// Abort the track with `err` instead of finishing it, so subscribers see the real cause rather
458	/// than [`moq_net::Error::Dropped`].
459	pub fn abort(self, err: moq_net::Error) {
460		self.publisher.abort(err);
461	}
462}
463
464/// What the capture driver needs beyond the public API: it sizes the encoder to each camera it
465/// opens, and releases the encoder with its camera rather than on a drain.
466#[cfg(feature = "capture")]
467impl Producer {
468	/// Encode at `config` from the next frame written, for a capture's source reopened at
469	/// whatever mode it negotiated. Call it once the encoder stopped: the next write opens one.
470	///
471	/// The ceiling and its claim follow the mode, and rate control starts over from the ceiling,
472	/// enabled, since what the link did while the source was closed says little about now.
473	pub(crate) fn configure(&mut self, mut config: Config) -> Result<(), Error> {
474		let ceiling = config.resolved_bitrate();
475		config.bitrate = Some(ceiling);
476		self.config = config;
477		if let Ok(mut current) = self.ceiling.write() {
478			*current = ceiling;
479		}
480		self.reservation.update(ceiling);
481		if self.grant.is_some() {
482			self.grant = Some(rate::Grant::new(
483				self.reservation.consume(),
484				policy(ceiling, self.lower.as_ref()),
485			));
486		}
487		if let Encoding::Disabled = self.encoding {
488			self.publisher.set_enabled(true)?;
489		}
490		self.encoding = Encoding::Idle;
491		self.target = rate::Target::Enabled(ceiling);
492		self.watched = false;
493		// Another mode can land on another backend, which may retune where this one refused.
494		self.ceiling_only = false;
495		self.resume_retry = None;
496		self.publisher.report_bitrate(ceiling);
497		Ok(())
498	}
499
500	/// [`discontinuity`](Self::discontinuity), for a capture whose source stopped or whose viewers
501	/// left this rendition. A failed drain only logs: it costs the last frames, and the next frame
502	/// written opens a fresh encoder, so it never takes down the renditions beside this one.
503	/// Errors only when the break cannot be marked, as the track has closed.
504	pub(crate) async fn stop(&mut self) -> Result<(), Error> {
505		if let Err(err) = self.close().await {
506			tracing::warn!(track = %self.demand.name(), error = %err, "failed to drain a stopped rendition's encoder");
507		}
508		self.mark()
509	}
510
511	/// Close the encoder without draining it and mark the break, for a capture that cancelled an
512	/// encode mid-call: the encoder refuses every call after that, so it cannot drain.
513	pub(crate) fn release(&mut self) -> Result<(), Error> {
514		if let Encoding::Open(_) = self.encoding {
515			self.encoding = Encoding::Idle;
516		}
517		self.mark()
518	}
519
520	/// The open encoder's backend name.
521	pub(crate) fn name(&self) -> Option<&str> {
522		match &self.encoding {
523			Encoding::Open(sink) => Some(sink.name()),
524			Encoding::Idle | Encoding::Disabled => None,
525		}
526	}
527
528	/// What the open encoder's backend applied.
529	pub(crate) fn applied(&self) -> Option<super::Applied> {
530		match &self.encoding {
531			Encoding::Open(sink) => Some(sink.applied()),
532			Encoding::Idle | Encoding::Disabled => None,
533		}
534	}
535
536	/// The group a subscriber wants past the largest published; see [`Publisher::wanted`].
537	pub(crate) fn wanted(&self) -> Option<u64> {
538		self.publisher.wanted()
539	}
540
541	/// Follow the grant with nothing written, for a rung nobody watches.
542	///
543	/// A rung the grant disabled re-enables once it is funded again, so a viewer that switched
544	/// down when it disabled can switch back; its encoder opens on the next frame written. Does
545	/// nothing for a rendition with no [`lower`](Options::lower) one, which ignores the grant
546	/// while unwatched.
547	pub(crate) async fn follow_unwritten(&mut self) {
548		if self.lower.is_none() {
549			return;
550		}
551		self.unwritten = true;
552		self.follow().await;
553		self.unwritten = false;
554	}
555
556	/// Report source frames the encoder never saw, in the catalog's stats.
557	pub(crate) fn report_skipped(&self, frames: u64) {
558		self.publisher.report_skipped(frames);
559	}
560}
561
562impl Producer {
563	/// Publish every access unit the encoder has ready, then move the claim to the track the
564	/// rendition is on now, even when publishing failed, so it never stays on an ended track.
565	fn publish_ready(&mut self) -> Result<(), Error> {
566		let published = match &mut self.encoding {
567			Encoding::Open(sink) => Self::publish_from(sink, &mut self.publisher, &mut self.marked),
568			Encoding::Idle | Encoding::Disabled => Ok(()),
569		};
570		self.follow_track();
571		published
572	}
573
574	fn publish_from(sink: &mut Sink, publisher: &mut Publisher, marked: &mut bool) -> Result<(), Error> {
575		while let Some(encoded) = sink.receive()? {
576			publisher.publish(&encoded)?;
577			*marked = false;
578		}
579		Ok(())
580	}
581
582	/// Drain the encoder and close it, so the next frame written opens a fresh one. A disabled
583	/// rung stays disabled, still dropping what is written until the grant resumes it.
584	async fn close(&mut self) -> Result<(), Error> {
585		match std::mem::replace(&mut self.encoding, Encoding::Idle) {
586			Encoding::Open(sink) => self.drain(sink).await,
587			Encoding::Idle => Ok(()),
588			Encoding::Disabled => {
589				self.encoding = Encoding::Disabled;
590				Ok(())
591			}
592		}
593	}
594
595	/// Flush `sink` and publish its tail, closing it.
596	async fn drain(&mut self, mut sink: Sink) -> Result<(), Error> {
597		sink.flush().await?;
598		let published = Self::publish_from(&mut sink, &mut self.publisher, &mut self.marked);
599		self.follow_track();
600		published
601	}
602
603	/// Publish the break marker, unless nothing was published since the last one.
604	fn mark(&mut self) -> Result<(), Error> {
605		if !self.marked {
606			self.publisher.discontinuity()?;
607			self.marked = true;
608		}
609		Ok(())
610	}
611
612	/// A frame whose decoder identity differs from the declared one publishes under a new name
613	/// and ends the old track. The claim moves there, following on from the current target.
614	fn follow_track(&mut self) {
615		let demand = self.publisher.demand();
616		if demand.name() == self.demand.name() {
617			return;
618		}
619		tracing::info!(track = %demand.name(), "video moved to a new track");
620		self.reservation = Arc::new(self.allocator.reserve(&demand, *self.ceiling.read()));
621		self.demand = demand;
622		if let Some(grant) = self.grant.as_mut() {
623			let mut moved = rate::Grant::new(self.reservation.consume(), grant.policy().clone());
624			moved.assume(self.target);
625			*grant = moved;
626		}
627		// The new track's stats start empty.
628		if let rate::Target::Enabled(bitrate) = self.target {
629			self.publisher.report_bitrate(bitrate);
630		}
631	}
632
633	/// Apply every target the grant has due, or rest at the ceiling while nobody watches a
634	/// rendition that never disables.
635	///
636	/// A target that fails to apply is taken back and asked for again a ramp step later, so an
637	/// encoder that cannot retune at all costs one attempt per step while the grant moves.
638	async fn follow(&mut self) {
639		if self.lower.is_none() {
640			let watched = self.demand.wanted();
641			let rested = self.watched && !watched;
642			self.watched = watched;
643			if rested {
644				self.rest().await;
645			}
646			if !watched {
647				return;
648			}
649		}
650
651		self.resume_at_ceiling().await;
652
653		let noop = kio::Waiter::noop();
654		// Each target is one the grant would not hand out again without a new grant, a deadline,
655		// or a failure, all of which leave it pending until the next write.
656		loop {
657			let policy = policy(*self.ceiling.read(), self.lower.as_ref());
658			let Some(grant) = self.grant.as_mut() else { return };
659			grant.set_policy(policy);
660			let target = match grant.poll_next(&noop) {
661				Poll::Pending => return,
662				Poll::Ready(Ok(target)) => target,
663				Poll::Ready(Err(_)) => {
664					tracing::debug!("bandwidth grant ended; holding the current encoder bitrate");
665					self.grant = None;
666					return;
667				}
668			};
669			if let Err(err) = self.apply(target).await {
670				tracing::warn!(error = %err, ?target, "failed to follow the bandwidth grant");
671				if let Some(grant) = self.grant.as_mut() {
672					grant.failed();
673				}
674				return;
675			}
676			// A deferred resume told the grant the rung is still off, so it would only offer the
677			// same resume again: wait for the next write.
678			if matches!(target, rate::Target::Enabled(_)) && matches!(self.encoding, Encoding::Disabled) {
679				return;
680			}
681			tracing::debug!(?target, "followed the bandwidth grant");
682		}
683	}
684
685	/// Resume a rung that only resumes at its ceiling, once its slice of the grant covers it.
686	async fn resume_at_ceiling(&mut self) {
687		if !self.ceiling_only || self.grant.is_none() || !matches!(self.encoding, Encoding::Disabled) {
688			return;
689		}
690		let ceiling = *self.ceiling.read();
691		if !self.reservation.rate().is_some_and(|rate| rate >= ceiling) {
692			return;
693		}
694		let now = kio::clock::now();
695		if self.resume_retry.is_some_and(|retry| now < retry) {
696			return;
697		}
698		let target = rate::Target::Enabled(ceiling);
699		match self.apply(target).await {
700			Ok(()) => {
701				self.resume_retry = None;
702				if let Some(grant) = self.grant.as_mut() {
703					grant.assume(target);
704				}
705			}
706			// Retried a step later, as a failed grant target is, rather than on every frame.
707			Err(err) => {
708				tracing::warn!(error = %err, bitrate = ceiling.as_bps(), "failed to resume at the ceiling");
709				self.resume_retry = now.checked_add(rate::RETRY);
710			}
711		}
712	}
713
714	/// Leave a rung disabled and tell the grant so, which then offers its resume again from the
715	/// current estimate.
716	fn defer_resume(&mut self) {
717		if let Some(grant) = self.grant.as_mut() {
718			grant.assume(rate::Target::Disabled);
719		}
720	}
721
722	/// Return an encoder nobody watches to its ceiling, and start its rate control over from
723	/// there for the next viewer.
724	async fn rest(&mut self) {
725		// Retired: the grant is gone, and the encoder holds its rate.
726		if self.grant.is_none() {
727			return;
728		}
729		let ceiling = *self.ceiling.read();
730		if let Err(err) = self.apply(rate::Target::Enabled(ceiling)).await {
731			// The grant still matches the rate the encoder kept, so the next viewer follows on from it.
732			tracing::warn!(error = %err, bitrate = ceiling.as_bps(), "failed to rest the encoder bitrate");
733			return;
734		}
735		self.grant = Some(rate::Grant::new(self.reservation.consume(), policy(ceiling, None)));
736	}
737
738	/// Apply a rate-control target, leaving the rendition as it was when that fails.
739	///
740	/// A disable drains the encoder into the track and closes it; a resume reopens one, whose
741	/// first frame is a keyframe on every backend.
742	async fn apply(&mut self, target: rate::Target) -> Result<(), Error> {
743		match (target, &mut self.encoding) {
744			(rate::Target::Disabled, Encoding::Disabled) => Ok(()),
745			(rate::Target::Disabled, _) => {
746				// The catalog first, the only step that leaves the rendition as it was when it fails.
747				// After it the encoder goes whatever the drain reports, so the catalog never
748				// advertises a rendition whose frames are dropped.
749				self.publisher.set_enabled(false)?;
750				self.target = rate::Target::Disabled;
751				let drained = match std::mem::replace(&mut self.encoding, Encoding::Disabled) {
752					Encoding::Open(sink) => self.drain(sink).await,
753					Encoding::Idle | Encoding::Disabled => Ok(()),
754				};
755				// The encoder is gone either way, so a lost tail only costs those frames.
756				if let Err(err) = drained {
757					tracing::warn!(error = %err, "failed to drain a disabled rendition's encoder");
758				}
759				self.mark()
760			}
761			(rate::Target::Enabled(bitrate), Encoding::Open(sink)) => {
762				sink.set_bitrate(bitrate).await?;
763				self.target = target;
764				self.publisher.report_bitrate(bitrate);
765				Ok(())
766			}
767			// Applied when the next frame reopens the encoder.
768			(rate::Target::Enabled(bitrate), Encoding::Idle) => {
769				self.target = target;
770				self.publisher.report_bitrate(bitrate);
771				Ok(())
772			}
773			// A resume. One deferred leaves the grant agreeing the rung is off, and
774			// `resume_at_ceiling` resumes it once its slice covers the ceiling.
775			(rate::Target::Enabled(bitrate), Encoding::Disabled) => {
776				let ceiling = *self.ceiling.read();
777				let bitrate = bitrate.min(ceiling);
778				if self.ceiling_only && bitrate < ceiling {
779					self.defer_resume();
780					return Ok(());
781				}
782				// Nothing is written, so the next frame opens the encoder, which disables the rung
783				// again rather than overshoot if the backend refuses this rate.
784				if self.unwritten {
785					self.publisher.set_enabled(true)?;
786					self.target = rate::Target::Enabled(bitrate);
787					self.publisher.report_bitrate(bitrate);
788					self.encoding = Encoding::Idle;
789					return Ok(());
790				}
791				let mut sink = Sink::open(&self.config).await?;
792				if bitrate < ceiling
793					&& let Err(err) = sink.set_bitrate(bitrate).await
794				{
795					// Opening at the ceiling would overshoot the grant, and retrying would reopen
796					// an encoder every ramp step on a backend that can never retune.
797					tracing::warn!(error = %err, bitrate = bitrate.as_bps(), "resumed encoder refused the funded bitrate; resuming only at the ceiling");
798					self.ceiling_only = true;
799					self.defer_resume();
800					return Ok(());
801				}
802				self.publisher.set_enabled(true)?;
803				self.target = rate::Target::Enabled(bitrate);
804				self.publisher.report_bitrate(bitrate);
805				self.encoding = Encoding::Open(sink);
806				Ok(())
807			}
808		}
809	}
810
811	/// Open an encoder at the ceiling and retune it to `wanted`, which becomes the target once it
812	/// opens. A failed open changes nothing.
813	///
814	/// One that cannot retune still opens, at the ceiling, which the grant then follows on from.
815	/// A rung whose lower rendition still serves disables instead, as a refused resume does, since
816	/// the ceiling would overshoot its grant, and from then on resumes only at its full ceiling:
817	/// `None` then.
818	async fn reopen(&mut self, wanted: Rate) -> Result<Option<Sink>, Error> {
819		let mut sink = Sink::open(&self.config).await?;
820		let ceiling = *self.ceiling.read();
821		let wanted = wanted.min(ceiling);
822		let applied = match wanted < ceiling {
823			true => match sink.set_bitrate(wanted).await {
824				Ok(()) => wanted,
825				// Only while a lower rendition still serves below this one, as the grant disables.
826				Err(err)
827					if self
828						.lower
829						.as_ref()
830						.and_then(|lower| lower.ceiling(&kio::Waiter::noop()))
831						.is_some_and(|lower| lower < ceiling) =>
832				{
833					tracing::warn!(error = %err, bitrate = wanted.as_bps(), "reopened encoder refused the funded bitrate; resuming only at the ceiling");
834					self.ceiling_only = true;
835					self.publisher.set_enabled(false)?;
836					self.target = rate::Target::Disabled;
837					self.encoding = Encoding::Disabled;
838					self.mark()?;
839					self.defer_resume();
840					return Ok(None);
841				}
842				Err(err) => {
843					tracing::warn!(error = %err, bitrate = wanted.as_bps(), "reopened encoder kept its ceiling");
844					ceiling
845				}
846			},
847			false => ceiling,
848		};
849		self.target = rate::Target::Enabled(applied);
850		if applied != wanted
851			&& let Some(grant) = self.grant.as_mut()
852		{
853			grant.assume(self.target);
854		}
855		self.publisher.report_bitrate(applied);
856		Ok(Some(sink))
857	}
858}
859
860/// Accept `request` with `info`, failing if that ended the track, as a renewal with another
861/// info does, so nothing registers a rendition for a track that will never carry frames.
862fn accepted(
863	request: moq_net::track::Request,
864	info: moq_net::track::Info,
865) -> Result<moq_net::track::Producer, moq_net::Error> {
866	let track = request.accept(info);
867	match track.poll_closed(&kio::Waiter::noop()) {
868		Poll::Ready(Err(err)) => Err(err),
869		_ => Ok(track),
870	}
871}
872
873/// The track name suffix for `codec`: avc3 or hev1, which carry their parameter sets in band.
874pub(crate) fn suffix(codec: Codec) -> &'static str {
875	match codec {
876		Codec::H264 => ".avc3",
877		Codec::H265 => ".hev1",
878	}
879}
880
881/// The policy a rendition follows: its `ceiling`, above the `lower` rendition's current ceiling.
882fn policy(ceiling: Rate, lower: Option<&Rung>) -> rate::Policy {
883	let mut policy = rate::Policy::new(ceiling);
884	policy.lower = lower.and_then(|lower| lower.ceiling(&kio::Waiter::noop()));
885	policy
886}
887
888#[cfg(test)]
889mod tests {
890	use std::time::Duration;
891
892	use moq_net::Timestamp;
893
894	use super::*;
895	use crate::encode::backend::probe;
896	use crate::encode::encoder;
897
898	fn config(kind: encoder::Backend, ceiling: Rate) -> Config {
899		let mut config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
900		config.backend = kind;
901		config.bitrate = Some(ceiling);
902		config
903	}
904
905	/// The rendition the probe backend would declare, if it emitted H.264: it emits the frame's
906	/// timestamp instead, which publishes nothing, so the declared shape never gets corrected.
907	fn rendition() -> hang::catalog::VideoConfig {
908		hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::H264(hang::catalog::H264 {
909			inline: true,
910			profile: 0x64,
911			constraints: 0,
912			level: 0x1f,
913		}))
914	}
915
916	/// A producer on the probe backend, publishing `name` with no encoder open yet.
917	fn probed(
918		broadcast: &moq_net::broadcast::Producer,
919		catalog: &moq_mux::catalog::Producer,
920		name: &str,
921		ceiling: Rate,
922		bandwidth: moq_net::bandwidth::Allocator,
923		lower: Option<Rung>,
924	) -> Producer {
925		let track = broadcast
926			.create_track(name, catalog.track_info(hang::catalog::PRIORITY.video))
927			.unwrap();
928		let config = config(encoder::Backend::Named(probe::NAME.into()), ceiling);
929		Producer::with_track(track, catalog, config, rendition(), bandwidth, lower).unwrap()
930	}
931
932	/// A mid-gray frame at `micros`, advancing it by one frame at 30 fps.
933	fn frame(micros: &mut u64) -> Frame {
934		let size = crate::Size::new(320, 240);
935		let i420 = crate::I420::new(size, vec![0x80; crate::I420::len(size).unwrap()]).unwrap();
936		let frame = Frame::new(Timestamp::from_micros(*micros).unwrap(), crate::Surface::I420(i420));
937		*micros += 33_333;
938		frame
939	}
940
941	fn enabled(catalog: &moq_mux::catalog::Producer, name: &str) -> bool {
942		catalog.snapshot().video.renditions[name].enabled
943	}
944
945	fn events(name: &str) -> usize {
946		probe::take().iter().filter(|(event, _)| *event == name).count()
947	}
948
949	/// A watched producer retunes to a falling grant between frames, and climbs back to its
950	/// ceiling after congestion clears although the grant never changes again, retrying a step
951	/// the encoder refused rather than waiting for the next change.
952	#[tokio::test(start_paused = true)]
953	#[expect(
954		clippy::await_holding_lock,
955		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
956	)]
957	async fn follows_a_falling_and_recovering_grant() {
958		let _probe = probe::exclusive();
959		let ceiling = Rate::from_mbps(4);
960		let estimate = moq_net::bandwidth::Producer::new();
961		estimate.set(Some(ceiling)).unwrap();
962		let bandwidth = moq_net::bandwidth::Allocator::new(estimate.consume());
963
964		let mut broadcast = moq_net::broadcast::Info::new().produce();
965		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
966		let mut producer = probed(&broadcast, &catalog, "video", ceiling, bandwidth, None);
967		let _viewer = broadcast
968			.consume()
969			.track("video")
970			.unwrap()
971			.subscribe(None)
972			.await
973			.unwrap();
974		let mut micros = 0;
975
976		producer.write(frame(&mut micros)).await.unwrap();
977		assert_eq!(producer.bitrate(), Some(ceiling));
978
979		estimate.set(Some(Rate::from_mbps(1))).unwrap();
980		for _ in 0..3 {
981			tokio::time::advance(Duration::from_millis(33)).await;
982			producer.write(frame(&mut micros)).await.unwrap();
983		}
984		let fallen = probe::bitrates();
985		assert!(!fallen.is_empty(), "the encoder never followed the grant down");
986		assert!(fallen.iter().all(|&bps| bps <= 1_000_000), "{fallen:?}");
987		assert!(producer.bitrate().unwrap() <= Rate::from_mbps(1));
988
989		// The last grant change: the link recovers a second later.
990		tokio::time::advance(Duration::from_secs(1)).await;
991		estimate.set(Some(ceiling)).unwrap();
992		probe::refuse_once(ceiling.as_bps());
993		let _ = probe::take();
994
995		// A minute of frames is far past anything the ramp still needs.
996		for _ in 0..600 {
997			tokio::time::advance(Duration::from_millis(100)).await;
998			producer.write(frame(&mut micros)).await.unwrap();
999		}
1000		let recovered = probe::bitrates();
1001		assert_eq!(
1002			recovered.last(),
1003			Some(&ceiling.as_bps()),
1004			"the ramp stalled: {recovered:?}"
1005		);
1006		assert_eq!(producer.bitrate(), Some(ceiling));
1007		assert!(
1008			events("set_bitrate") > recovered.len(),
1009			"the refused step was never retried: {recovered:?}"
1010		);
1011
1012		let _finished = producer.finish().await.unwrap();
1013	}
1014
1015	/// A rung the grant cannot fund stops encoding, drops what is written, and advertises itself
1016	/// disabled; resumed, it opens a fresh encoder and advertises itself again.
1017	#[tokio::test]
1018	#[expect(
1019		clippy::await_holding_lock,
1020		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1021	)]
1022	async fn disables_and_reenables_its_rendition() {
1023		let _probe = probe::exclusive();
1024		let mut broadcast = moq_net::broadcast::Info::new().produce();
1025		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1026		let unlimited = moq_net::bandwidth::Allocator::unlimited();
1027		let low = probed(
1028			&broadcast,
1029			&catalog,
1030			"low",
1031			Rate::from_kbps(500),
1032			unlimited.clone(),
1033			None,
1034		);
1035		let ceiling = Rate::from_mbps(2);
1036		let mut high = probed(&broadcast, &catalog, "high", ceiling, unlimited, Some(low.rung()));
1037		let mut micros = 0;
1038
1039		high.write(frame(&mut micros)).await.unwrap();
1040		assert!(enabled(&catalog, "high"));
1041		let _ = probe::take();
1042
1043		high.apply(rate::Target::Disabled).await.unwrap();
1044		assert!(!enabled(&catalog, "high"));
1045		assert_eq!(high.bitrate(), None);
1046		let disabled = probe::take();
1047		assert!(disabled.iter().any(|(event, _)| *event == "flush"), "{disabled:?}");
1048		assert!(disabled.iter().any(|(event, _)| *event == "drop"), "{disabled:?}");
1049
1050		high.write(frame(&mut micros)).await.unwrap();
1051		assert_eq!(events("encode"), 0, "a disabled rung encodes nothing");
1052
1053		let resumed = Rate::from_mbps(1);
1054		high.apply(rate::Target::Enabled(resumed)).await.unwrap();
1055		assert!(enabled(&catalog, "high"));
1056		assert_eq!(high.bitrate(), Some(resumed));
1057		assert_eq!(probe::bitrates(), [resumed.as_bps()]);
1058		assert_eq!(events("open"), 1);
1059
1060		high.write(frame(&mut micros)).await.unwrap();
1061		assert_eq!(events("encode"), 1);
1062
1063		let _high = high.finish().await.unwrap();
1064		let _low = low.finish().await.unwrap();
1065	}
1066
1067	/// A rung whose resumed encoder refuses the funded rate stays disabled rather than open at a
1068	/// ceiling the grant cannot fund, and from then on resumes only at its full ceiling.
1069	#[tokio::test]
1070	#[expect(
1071		clippy::await_holding_lock,
1072		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1073	)]
1074	async fn a_refused_resume_waits_for_the_ceiling() {
1075		let _probe = probe::exclusive();
1076		let mut broadcast = moq_net::broadcast::Info::new().produce();
1077		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1078		let unlimited = moq_net::bandwidth::Allocator::unlimited();
1079		let low = probed(
1080			&broadcast,
1081			&catalog,
1082			"low",
1083			Rate::from_kbps(500),
1084			unlimited.clone(),
1085			None,
1086		);
1087		let ceiling = Rate::from_mbps(2);
1088		let mut high = probed(&broadcast, &catalog, "high", ceiling, unlimited, Some(low.rung()));
1089		let mut micros = 0;
1090
1091		high.write(frame(&mut micros)).await.unwrap();
1092		high.apply(rate::Target::Disabled).await.unwrap();
1093		let _ = probe::take();
1094
1095		let funded = Rate::from_mbps(1);
1096		probe::refuse_once(funded.as_bps());
1097		high.apply(rate::Target::Enabled(funded)).await.unwrap();
1098		assert!(!enabled(&catalog, "high"), "a refused resume stays disabled");
1099		assert_eq!(high.bitrate(), None);
1100
1101		// A grant that would now retune fine still funds less than the ceiling.
1102		let _ = probe::take();
1103		high.apply(rate::Target::Enabled(funded)).await.unwrap();
1104		assert!(!enabled(&catalog, "high"));
1105		assert_eq!(events("open"), 0, "a partial grant no longer reopens the encoder");
1106
1107		high.apply(rate::Target::Enabled(ceiling)).await.unwrap();
1108		assert!(enabled(&catalog, "high"));
1109		assert_eq!(high.bitrate(), Some(ceiling));
1110		let resumed = probe::take();
1111		assert!(resumed.iter().all(|(event, _)| *event != "set_bitrate"), "{resumed:?}");
1112
1113		let _high = high.finish().await.unwrap();
1114		let _low = low.finish().await.unwrap();
1115	}
1116
1117	/// A rung disabled under congestion whose viewers left re-enables once the grant funds it
1118	/// again, with nothing written and no encoder opened, so a viewer can switch back; the next
1119	/// frame written opens its encoder.
1120	#[cfg(feature = "capture")]
1121	#[tokio::test(start_paused = true)]
1122	#[expect(
1123		clippy::await_holding_lock,
1124		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1125	)]
1126	async fn an_unwatched_rung_re_enables_once_funded() {
1127		let _probe = probe::exclusive();
1128		let estimate = moq_net::bandwidth::Producer::new();
1129		estimate.set(Some(Rate::from_mbps(4))).unwrap();
1130		let bandwidth = moq_net::bandwidth::Allocator::new(estimate.consume());
1131
1132		let mut broadcast = moq_net::broadcast::Info::new().produce();
1133		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1134		let low = probed(
1135			&broadcast,
1136			&catalog,
1137			"low",
1138			Rate::from_kbps(500),
1139			moq_net::bandwidth::Allocator::unlimited(),
1140			None,
1141		);
1142		let ceiling = Rate::from_mbps(2);
1143		let mut high = probed(&broadcast, &catalog, "high", ceiling, bandwidth, Some(low.rung()));
1144		let mut micros = 0;
1145		high.write(frame(&mut micros)).await.unwrap();
1146
1147		// Disabled while the link was congested, as the grant would have.
1148		high.apply(rate::Target::Disabled).await.unwrap();
1149		high.defer_resume();
1150		assert!(!enabled(&catalog, "high"));
1151		let _ = probe::take();
1152
1153		// Nobody watches it now, and the link has recovered: following the grant re-enables it.
1154		tokio::time::advance(Duration::from_secs(1)).await;
1155		high.follow_unwritten().await;
1156		assert!(enabled(&catalog, "high"));
1157		assert_eq!(events("open"), 0, "an encoder opened for a rendition nobody writes to");
1158
1159		high.write(frame(&mut micros)).await.unwrap();
1160		assert_eq!(events("open"), 1);
1161		assert!(high.bitrate().is_some());
1162
1163		let _high = high.finish().await.unwrap();
1164		let _low = low.finish().await.unwrap();
1165	}
1166
1167	/// A rung whose lower rendition ended has nothing to fall back to, so an encoder reopened at a
1168	/// rate it refuses keeps the ceiling rather than disabling the last rendition.
1169	#[tokio::test(start_paused = true)]
1170	#[expect(
1171		clippy::await_holding_lock,
1172		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1173	)]
1174	async fn a_rung_without_a_lower_rendition_keeps_encoding() {
1175		let _probe = probe::exclusive();
1176		let mut broadcast = moq_net::broadcast::Info::new().produce();
1177		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1178		let unlimited = moq_net::bandwidth::Allocator::unlimited();
1179		let low = probed(
1180			&broadcast,
1181			&catalog,
1182			"low",
1183			Rate::from_kbps(500),
1184			unlimited.clone(),
1185			None,
1186		);
1187		let ceiling = Rate::from_mbps(2);
1188		let mut high = probed(&broadcast, &catalog, "high", ceiling, unlimited, Some(low.rung()));
1189		let mut micros = 0;
1190		high.write(frame(&mut micros)).await.unwrap();
1191		let funded = Rate::from_kbps(1_200);
1192		high.apply(rate::Target::Enabled(funded)).await.unwrap();
1193		high.discontinuity().await.unwrap();
1194
1195		let _low = low.finish().await.unwrap();
1196		probe::refuse_once(funded.as_bps());
1197		high.write(frame(&mut micros)).await.unwrap();
1198		assert!(enabled(&catalog, "high"));
1199		assert_eq!(high.bitrate(), Some(ceiling));
1200
1201		let _high = high.finish().await.unwrap();
1202	}
1203
1204	/// A rung re-enabled with nothing written whose encoder then refuses the funded rate disables
1205	/// again rather than send at its ceiling, and from then on resumes only once its slice covers
1206	/// the ceiling.
1207	#[cfg(feature = "capture")]
1208	#[tokio::test(start_paused = true)]
1209	#[expect(
1210		clippy::await_holding_lock,
1211		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1212	)]
1213	async fn a_refused_lazy_resume_stays_under_the_grant() {
1214		let _probe = probe::exclusive();
1215		let ceiling = Rate::from_mbps(2);
1216		let funded = Rate::from_kbps(1_200);
1217		let estimate = moq_net::bandwidth::Producer::new();
1218		estimate.set(Some(funded)).unwrap();
1219		let bandwidth = moq_net::bandwidth::Allocator::new(estimate.consume());
1220
1221		let mut broadcast = moq_net::broadcast::Info::new().produce();
1222		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1223		let low = probed(
1224			&broadcast,
1225			&catalog,
1226			"low",
1227			Rate::from_kbps(500),
1228			moq_net::bandwidth::Allocator::unlimited(),
1229			None,
1230		);
1231		let mut high = probed(&broadcast, &catalog, "high", ceiling, bandwidth, Some(low.rung()));
1232		let mut micros = 0;
1233		high.write(frame(&mut micros)).await.unwrap();
1234		high.apply(rate::Target::Disabled).await.unwrap();
1235		high.defer_resume();
1236
1237		// Funded in part, it re-enables unwritten; the frame that reopens it finds the rate refused.
1238		tokio::time::advance(Duration::from_secs(1)).await;
1239		high.follow_unwritten().await;
1240		assert!(enabled(&catalog, "high"));
1241		assert_eq!(high.bitrate(), Some(funded));
1242		probe::refuse_once(funded.as_bps());
1243		high.write(frame(&mut micros)).await.unwrap();
1244		assert!(
1245			!enabled(&catalog, "high"),
1246			"the rung sent past its grant at the ceiling"
1247		);
1248		assert_eq!(high.bitrate(), None);
1249
1250		// The same partial grant no longer resumes it; one covering the ceiling does.
1251		for _ in 0..5 {
1252			tokio::time::advance(Duration::from_secs(1)).await;
1253			high.follow_unwritten().await;
1254		}
1255		assert!(!enabled(&catalog, "high"));
1256		estimate.set(Some(Rate::from_mbps(4))).unwrap();
1257		tokio::time::advance(Duration::from_secs(1)).await;
1258		high.follow_unwritten().await;
1259		assert!(enabled(&catalog, "high"));
1260		assert_eq!(high.bitrate(), Some(ceiling));
1261
1262		let _high = high.finish().await.unwrap();
1263		let _low = low.finish().await.unwrap();
1264	}
1265
1266	/// A rung waiting for its ceiling resumes from the grant: not while its slice covers only
1267	/// part of the ceiling, and at once when the slice covers it, including after `set_bitrate`
1268	/// lowers the ceiling to what the slice already funds.
1269	#[tokio::test(start_paused = true)]
1270	#[expect(
1271		clippy::await_holding_lock,
1272		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1273	)]
1274	async fn a_deferred_resume_follows_the_grant_to_the_ceiling() {
1275		let _probe = probe::exclusive();
1276		let estimate = moq_net::bandwidth::Producer::new();
1277		estimate.set(Some(Rate::from_kbps(1_500))).unwrap();
1278		let bandwidth = moq_net::bandwidth::Allocator::new(estimate.consume());
1279
1280		let mut broadcast = moq_net::broadcast::Info::new().produce();
1281		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1282		let low = probed(
1283			&broadcast,
1284			&catalog,
1285			"low",
1286			Rate::from_kbps(500),
1287			moq_net::bandwidth::Allocator::unlimited(),
1288			None,
1289		);
1290		let ceiling = Rate::from_mbps(2);
1291		let mut high = probed(&broadcast, &catalog, "high", ceiling, bandwidth, Some(low.rung()));
1292		let _viewer = broadcast
1293			.consume()
1294			.track("high")
1295			.unwrap()
1296			.subscribe(None)
1297			.await
1298			.unwrap();
1299		let mut micros = 0;
1300
1301		high.write(frame(&mut micros)).await.unwrap();
1302		high.apply(rate::Target::Disabled).await.unwrap();
1303		let funded = Rate::from_mbps(1);
1304		probe::refuse_once(funded.as_bps());
1305		high.apply(rate::Target::Enabled(funded)).await.unwrap();
1306		assert_eq!(high.bitrate(), None);
1307		let _ = probe::take();
1308
1309		// The slice funds part of the ceiling: the grant offers resumes, and none opens.
1310		for _ in 0..30 {
1311			tokio::time::advance(Duration::from_millis(100)).await;
1312			high.write(frame(&mut micros)).await.unwrap();
1313		}
1314		assert!(!enabled(&catalog, "high"));
1315		assert_eq!(events("open"), 0);
1316
1317		// A ceiling the slice covers resumes it on the next frame, at that ceiling.
1318		let lowered = Rate::from_mbps(1);
1319		high.set_bitrate(lowered).await.unwrap();
1320		high.write(frame(&mut micros)).await.unwrap();
1321		assert!(enabled(&catalog, "high"));
1322		assert_eq!(high.bitrate(), Some(lowered));
1323		let resumed = probe::take();
1324		assert!(resumed.iter().any(|(event, _)| *event == "open"), "{resumed:?}");
1325		assert!(resumed.iter().all(|(event, _)| *event != "set_bitrate"), "{resumed:?}");
1326
1327		let _high = high.finish().await.unwrap();
1328		let _low = low.finish().await.unwrap();
1329	}
1330
1331	/// A resume at the ceiling whose encoder fails to open is tried again a grant's retry step
1332	/// later, not on every frame.
1333	#[tokio::test(start_paused = true)]
1334	#[expect(
1335		clippy::await_holding_lock,
1336		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1337	)]
1338	async fn a_failed_resume_waits_a_retry_step() {
1339		let _probe = probe::exclusive();
1340		let estimate = moq_net::bandwidth::Producer::new();
1341		estimate.set(Some(Rate::from_mbps(10))).unwrap();
1342		let bandwidth = moq_net::bandwidth::Allocator::new(estimate.consume());
1343
1344		let mut broadcast = moq_net::broadcast::Info::new().produce();
1345		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1346		let low = probed(
1347			&broadcast,
1348			&catalog,
1349			"low",
1350			Rate::from_kbps(500),
1351			moq_net::bandwidth::Allocator::unlimited(),
1352			None,
1353		);
1354		let ceiling = Rate::from_mbps(2);
1355		let mut high = probed(&broadcast, &catalog, "high", ceiling, bandwidth, Some(low.rung()));
1356		let _viewer = broadcast
1357			.consume()
1358			.track("high")
1359			.unwrap()
1360			.subscribe(None)
1361			.await
1362			.unwrap();
1363		let mut micros = 0;
1364
1365		// Disabled, and resuming only at its ceiling, which the slice covers.
1366		high.write(frame(&mut micros)).await.unwrap();
1367		high.apply(rate::Target::Disabled).await.unwrap();
1368		probe::refuse_once(Rate::from_mbps(1).as_bps());
1369		high.apply(rate::Target::Enabled(Rate::from_mbps(1))).await.unwrap();
1370		let _ = probe::take();
1371
1372		// An encoder that keeps failing to open, written to well inside one retry step: the
1373		// ceiling resume and the grant's own resume each try once, not once per frame.
1374		probe::fail_opens(u32::MAX);
1375		for _ in 0..8 {
1376			high.write(frame(&mut micros)).await.unwrap();
1377			tokio::time::advance(moq_mux::rate::RETRY / 10).await;
1378		}
1379		let opens = events("open");
1380		assert!((1..=2).contains(&opens), "{opens} opens in one retry step");
1381		assert!(!enabled(&catalog, "high"));
1382
1383		// Once the encoder opens again, the next retry resumes the rung at its ceiling.
1384		probe::fail_opens(0);
1385		tokio::time::advance(moq_mux::rate::RETRY).await;
1386		high.write(frame(&mut micros)).await.unwrap();
1387		assert!(enabled(&catalog, "high"));
1388		assert_eq!(high.bitrate(), Some(ceiling));
1389
1390		let _high = high.finish().await.unwrap();
1391		let _low = low.finish().await.unwrap();
1392	}
1393
1394	/// A rung must sit above the rendition it falls back to: one that does not fails before its
1395	/// track exists.
1396	#[tokio::test]
1397	async fn a_rung_at_or_below_its_lower_rendition_is_refused() {
1398		let mut broadcast = moq_net::broadcast::Info::new().produce();
1399		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1400		let unlimited = moq_net::bandwidth::Allocator::unlimited();
1401		let lower = probed(&broadcast, &catalog, "lower", Rate::from_mbps(2), unlimited, None);
1402
1403		let mut options = Options::new(config(encoder::Backend::Named(probe::NAME.into()), Rate::from_mbps(2)));
1404		options.lower = Some(lower.rung());
1405		assert!(Producer::new(&broadcast, catalog.clone(), options).await.is_err());
1406		assert_eq!(catalog.snapshot().video.renditions.len(), 1);
1407	}
1408
1409	/// A rung takes the priority below the rendition it falls back to, so the allocator funds
1410	/// that one first.
1411	#[tokio::test]
1412	#[cfg(feature = "openh264")]
1413	async fn a_rung_takes_the_priority_below_its_lower_rendition() {
1414		let mut broadcast = moq_net::broadcast::Info::new().produce();
1415		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1416		let unlimited = moq_net::bandwidth::Allocator::unlimited();
1417		let lower = probed(&broadcast, &catalog, "lower", Rate::from_kbps(500), unlimited, None);
1418
1419		let mut options = Options::new(config(encoder::Backend::Software, Rate::from_mbps(1)));
1420		options.lower = Some(lower.rung());
1421		let higher = Producer::new(&broadcast, catalog, options).await.unwrap();
1422		// Read back from the track it created.
1423		assert_eq!(higher.priority, lower.priority - 1);
1424	}
1425
1426	/// A track asked for again after its producer dropped while read is served by a producer on
1427	/// the request, published with the same options, and its reader reads on.
1428	#[tokio::test]
1429	#[cfg(feature = "openh264")]
1430	async fn a_requested_producer_serves_a_renewal() {
1431		let mut broadcast = moq_net::broadcast::Info::new().produce();
1432		let mut requests = broadcast.requests();
1433		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1434		let options = Options::new(config(encoder::Backend::Software, Rate::from_mbps(1)));
1435		let mut first = options.clone();
1436		first.track = Some("video".into());
1437		let mut producer = Producer::new(&broadcast, catalog.clone(), first).await.unwrap();
1438		let mut reader = subscribe(&broadcast).await;
1439		let mut micros = 0;
1440		producer.write(frame(&mut micros)).await.unwrap();
1441		producer.cut().await.unwrap();
1442		producer.write(frame(&mut micros)).await.unwrap();
1443		assert!(reader.recv_group().await.unwrap().is_some());
1444		drop(producer);
1445
1446		let request = requests.requested_track().await.unwrap();
1447		assert_eq!(request.name(), "video");
1448		let mut next = Producer::requested(request, catalog.clone(), options).await.unwrap();
1449		assert!(catalog.snapshot().video.renditions.contains_key("video"));
1450		next.write(frame(&mut micros)).await.unwrap();
1451		let next = next.finish().await.unwrap();
1452		let mut frames = 0;
1453		while let Some(mut group) = reader.recv_group().await.unwrap() {
1454			while group.next_frame().await.unwrap().is_some() {
1455				frames += 1;
1456			}
1457		}
1458		assert!(frames > 0, "the reader reads what the requested producer wrote");
1459		drop(next);
1460	}
1461
1462	/// A renewal served with options that change its track info ends the track with
1463	/// `MalformedTrack`, so the producer fails rather than advertise a rendition nothing will carry.
1464	#[tokio::test]
1465	#[cfg(feature = "openh264")]
1466	async fn a_requested_producer_refuses_a_renewal_it_would_change() {
1467		let mut broadcast = moq_net::broadcast::Info::new().produce();
1468		let mut requests = broadcast.requests();
1469		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1470		// Published as a higher rung would be, one priority below the default.
1471		let track = broadcast
1472			.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video - 1))
1473			.unwrap();
1474		let mut reader = subscribe(&broadcast).await;
1475		drop(track);
1476
1477		let request = requests.requested_track().await.unwrap();
1478		let options = Options::new(config(encoder::Backend::Software, Rate::from_mbps(1)));
1479		let refused = Producer::requested(request, catalog.clone(), options).await;
1480		assert!(matches!(refused, Err(Error::Net(moq_net::Error::MalformedTrack))));
1481		assert!(!catalog.snapshot().video.renditions.contains_key("video"));
1482		assert!(matches!(reader.recv_group().await, Err(moq_net::Error::MalformedTrack)));
1483	}
1484
1485	/// A rendition the catalog refuses, here a name another producer claims, ends its track
1486	/// with `NotFound`, so a subscriber already waiting on it isn't left reading a drop.
1487	#[tokio::test]
1488	async fn a_refused_rendition_ends_its_track() {
1489		let mut broadcast = moq_net::broadcast::Info::new().produce();
1490		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1491		let unlimited = moq_net::bandwidth::Allocator::unlimited();
1492		let _claim = probed(
1493			&broadcast,
1494			&catalog,
1495			"video",
1496			Rate::from_mbps(1),
1497			unlimited.clone(),
1498			None,
1499		);
1500
1501		let other = moq_net::broadcast::Info::new().produce();
1502		let track = other
1503			.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video))
1504			.unwrap();
1505		let mut reader = other.consume().track("video").unwrap().subscribe(None).await.unwrap();
1506		let config = config(encoder::Backend::Named(probe::NAME.into()), Rate::from_mbps(1));
1507		assert!(Producer::with_track(track, &catalog, config, rendition(), unlimited, None).is_err());
1508		assert!(matches!(reader.recv_group().await, Err(moq_net::Error::NotFound)));
1509	}
1510
1511	/// A request names its track, so a requested producer given a name of its own fails and
1512	/// rejects the request, ending the subscriber waiting on it.
1513	#[tokio::test]
1514	async fn a_requested_producer_refuses_another_name() {
1515		let mut broadcast = moq_net::broadcast::Info::new().produce();
1516		let mut requests = broadcast.requests();
1517		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1518		let pending = broadcast.consume().track("video").unwrap().subscribe(None);
1519		let request = requests.requested_track().await.unwrap();
1520		let mut options = Options::new(config(encoder::Backend::Named(probe::NAME.into()), Rate::from_mbps(1)));
1521		options.track = Some("other".into());
1522		assert!(Producer::requested(request, catalog, options).await.is_err());
1523		assert!(matches!(pending.await, Err(moq_net::Error::NotFound)));
1524	}
1525
1526	/// Subscribe to `video`, skipping no group however far behind the reader falls.
1527	#[cfg(feature = "openh264")]
1528	async fn subscribe(broadcast: &moq_net::broadcast::Producer) -> moq_net::track::Subscriber {
1529		let history = moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::ALL]);
1530		broadcast
1531			.consume()
1532			.track("video")
1533			.unwrap()
1534			.subscribe(history)
1535			.await
1536			.unwrap()
1537	}
1538
1539	/// The frames in each group `consumer` reads, until the track ends.
1540	#[cfg(feature = "openh264")]
1541	async fn read(mut consumer: moq_net::track::Subscriber) -> Vec<usize> {
1542		let mut groups = Vec::new();
1543		while let Some(mut group) = consumer.recv_group().await.unwrap() {
1544			let mut frames = 0;
1545			while group.next_frame().await.unwrap().is_some() {
1546				frames += 1;
1547			}
1548			groups.push(frames);
1549		}
1550		groups
1551	}
1552
1553	/// A discontinuity drains the encoder and marks the break once, however often it is called,
1554	/// and the next frame opens a fresh encoder on a keyframe.
1555	#[tokio::test]
1556	#[cfg(feature = "openh264")]
1557	async fn a_discontinuity_marks_the_break_once() {
1558		let mut broadcast = moq_net::broadcast::Info::new().produce();
1559		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1560		let mut options = Options::new(config(encoder::Backend::Software, Rate::from_mbps(1)));
1561		options.track = Some("video".into());
1562		let mut producer = Producer::new(&broadcast, catalog, options).await.unwrap();
1563		let consumer = subscribe(&broadcast).await;
1564		let mut micros = 0;
1565
1566		producer.write(frame(&mut micros)).await.unwrap();
1567		producer.discontinuity().await.unwrap();
1568		producer.discontinuity().await.unwrap();
1569		producer.write(frame(&mut micros)).await.unwrap();
1570		let _finished = producer.finish().await.unwrap();
1571
1572		assert_eq!(read(consumer).await, [1, 1, 1]);
1573	}
1574
1575	/// A disabled rung's last frames reach the track before its break marker, and it resumes on
1576	/// a keyframe, so a subscriber reads the gap as a break rather than a stall.
1577	#[tokio::test]
1578	#[cfg(feature = "openh264")]
1579	async fn a_disabled_rung_resumes_on_a_new_group() {
1580		let mut broadcast = moq_net::broadcast::Info::new().produce();
1581		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1582		let mut options = Options::new(config(encoder::Backend::Software, Rate::from_mbps(1)));
1583		options.track = Some("video".into());
1584		let mut producer = Producer::new(&broadcast, catalog, options).await.unwrap();
1585		let consumer = subscribe(&broadcast).await;
1586		let mut micros = 0;
1587
1588		producer.write(frame(&mut micros)).await.unwrap();
1589		producer.apply(rate::Target::Disabled).await.unwrap();
1590		producer.write(frame(&mut micros)).await.unwrap();
1591		producer
1592			.apply(rate::Target::Enabled(Rate::from_kbps(500)))
1593			.await
1594			.unwrap();
1595		producer.write(frame(&mut micros)).await.unwrap();
1596		let _finished = producer.finish().await.unwrap();
1597
1598		assert_eq!(read(consumer).await, [1, 1, 1]);
1599	}
1600
1601	/// A rung resumed at a ceiling past its declared level publishes a new track, and its
1602	/// bandwidth claim moves there with it rather than watching the track that ended.
1603	#[tokio::test]
1604	#[cfg(feature = "openh264")]
1605	async fn a_resume_past_the_declared_level_moves_the_claim() {
1606		let mut broadcast = moq_net::broadcast::Info::new().produce();
1607		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1608		let mut options = Options::new(config(encoder::Backend::Software, Rate::from_mbps(2)));
1609		options.track = Some("video".into());
1610		let mut producer = Producer::new(&broadcast, catalog, options).await.unwrap();
1611		let mut micros = 0;
1612
1613		producer.write(frame(&mut micros)).await.unwrap();
1614		let before = producer.reservation().clone();
1615		producer.apply(rate::Target::Disabled).await.unwrap();
1616		// 3 Mbps takes H.264 level 2.1, past the 2.0 the 2 Mbps rendition declared.
1617		producer.set_bitrate(Rate::from_mbps(3)).await.unwrap();
1618		producer.apply(rate::Target::Enabled(Rate::from_mbps(3))).await.unwrap();
1619		producer.write(frame(&mut micros)).await.unwrap();
1620
1621		assert_eq!(producer.demand().name(), "video/1");
1622		assert!(
1623			!Arc::ptr_eq(&before, producer.reservation()),
1624			"the claim still watches the ended track"
1625		);
1626		let _finished = producer.finish().await.unwrap();
1627		assert_eq!(Arc::strong_count(&before), 1, "a finished producer still holds a claim");
1628	}
1629
1630	/// A disable that fails partway leaves the catalog and the encoder agreeing, so viewers
1631	/// never wait on a rendition the catalog calls enabled while its frames are dropped.
1632	#[tokio::test]
1633	#[cfg(feature = "openh264")]
1634	async fn a_failed_disable_leaves_the_catalog_and_encoder_agreeing() {
1635		let mut broadcast = moq_net::broadcast::Info::new().produce();
1636		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1637		let track = broadcast
1638			.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video))
1639			.unwrap();
1640		let config = config(encoder::Backend::Software, Rate::from_mbps(1));
1641		let rendition = config.probe().await.unwrap();
1642		let unlimited = moq_net::bandwidth::Allocator::unlimited();
1643		let mut producer = Producer::with_track(track.clone(), &catalog, config, rendition, unlimited, None).unwrap();
1644		let mut micros = 0;
1645
1646		producer.write(frame(&mut micros)).await.unwrap();
1647		// The track breaks, so the break marker the disable writes fails.
1648		track.abort(moq_net::Error::Cancel).unwrap();
1649		let disabled = producer.apply(rate::Target::Disabled).await;
1650
1651		assert!(disabled.is_err(), "the break marker should fail on a broken track");
1652		let encoding = matches!(producer.encoding, Encoding::Open(_));
1653		assert_eq!(
1654			encoding,
1655			enabled(&catalog, "video"),
1656			"the catalog and the encoder disagree"
1657		);
1658	}
1659
1660	/// A lost tail must reach the subscriber as an abort: finishing the track anyway would
1661	/// report a truncated stream as a complete one, and only the publisher would ever know.
1662	#[tokio::test]
1663	#[expect(
1664		clippy::await_holding_lock,
1665		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1666	)]
1667	async fn a_lost_tail_aborts_the_track() {
1668		let _probe = probe::exclusive();
1669		let mut broadcast = moq_net::broadcast::Info::new().produce();
1670		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1671		let unlimited = moq_net::bandwidth::Allocator::unlimited();
1672		let mut producer = probed(&broadcast, &catalog, "video", Rate::from_mbps(1), unlimited, None);
1673		let mut track = broadcast
1674			.consume()
1675			.track("video")
1676			.unwrap()
1677			.subscribe(None)
1678			.await
1679			.unwrap();
1680		let mut micros = 0;
1681
1682		// The probe holds this frame back, so only the flush can publish it.
1683		producer.write(frame(&mut micros)).await.unwrap();
1684		probe::lose_tail();
1685		assert!(producer.finish().await.is_err());
1686
1687		let Err(err) = track.recv_group().await else {
1688			panic!("expected an abort, not a clean end");
1689		};
1690		assert!(
1691			err.to_string().contains("the probe lost its tail"),
1692			"the abort should carry the drain failure: {err}"
1693		);
1694	}
1695
1696	/// `set_bitrate` lowers the ceiling while the grant is climbing back toward the old one:
1697	/// nothing retunes past the new ceiling, and the encoder recovers to it.
1698	#[tokio::test(start_paused = true)]
1699	#[expect(
1700		clippy::await_holding_lock,
1701		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1702	)]
1703	async fn a_lowered_ceiling_caps_a_recovering_grant() {
1704		let _probe = probe::exclusive();
1705		let old = Rate::from_mbps(4);
1706		let lowered = Rate::from_mbps(2);
1707		let estimate = moq_net::bandwidth::Producer::new();
1708		estimate.set(Some(Rate::from_mbps(1))).unwrap();
1709		let bandwidth = moq_net::bandwidth::Allocator::new(estimate.consume());
1710
1711		let mut broadcast = moq_net::broadcast::Info::new().produce();
1712		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1713		let mut producer = probed(&broadcast, &catalog, "video", old, bandwidth, None);
1714		let _viewer = broadcast
1715			.consume()
1716			.track("video")
1717			.unwrap()
1718			.subscribe(None)
1719			.await
1720			.unwrap();
1721		let mut micros = 0;
1722
1723		producer.write(frame(&mut micros)).await.unwrap();
1724		assert!(producer.bitrate().unwrap() <= Rate::from_mbps(1));
1725		// The link recovers, and the encoder starts climbing back toward the old ceiling.
1726		tokio::time::advance(Duration::from_secs(1)).await;
1727		estimate.set(Some(old)).unwrap();
1728		for _ in 0..3 {
1729			tokio::time::advance(Duration::from_millis(100)).await;
1730			producer.write(frame(&mut micros)).await.unwrap();
1731		}
1732
1733		producer.set_bitrate(lowered).await.unwrap();
1734		let _ = probe::bitrates();
1735		for _ in 0..600 {
1736			tokio::time::advance(Duration::from_millis(100)).await;
1737			producer.write(frame(&mut micros)).await.unwrap();
1738		}
1739		let applied = probe::bitrates();
1740		assert!(applied.iter().all(|&bps| bps <= lowered.as_bps()), "{applied:?}");
1741		assert_eq!(producer.bitrate(), Some(lowered));
1742		assert_eq!(producer.reservation().rate(), Some(lowered));
1743	}
1744
1745	/// A manual retune to the unchanged ceiling hands the encoder back to the grant rather than
1746	/// leaving it at the ceiling the grant cannot fund.
1747	#[tokio::test(start_paused = true)]
1748	#[expect(
1749		clippy::await_holding_lock,
1750		reason = "the guard only keeps other tests out of the process-wide probe log, and this runtime has one thread, so holding it across an await blocks nothing"
1751	)]
1752	async fn a_manual_retune_returns_to_the_grant() {
1753		let _probe = probe::exclusive();
1754		let ceiling = Rate::from_mbps(4);
1755		let estimate = moq_net::bandwidth::Producer::new();
1756		estimate.set(Some(Rate::from_mbps(1))).unwrap();
1757		let bandwidth = moq_net::bandwidth::Allocator::new(estimate.consume());
1758
1759		let mut broadcast = moq_net::broadcast::Info::new().produce();
1760		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
1761		let mut producer = probed(&broadcast, &catalog, "video", ceiling, bandwidth, None);
1762		let _viewer = broadcast
1763			.consume()
1764			.track("video")
1765			.unwrap()
1766			.subscribe(None)
1767			.await
1768			.unwrap();
1769		let mut micros = 0;
1770
1771		producer.write(frame(&mut micros)).await.unwrap();
1772		assert!(producer.bitrate().unwrap() <= Rate::from_mbps(1));
1773
1774		producer.set_bitrate(ceiling).await.unwrap();
1775		assert_eq!(producer.bitrate(), Some(ceiling));
1776		for _ in 0..10 {
1777			tokio::time::advance(Duration::from_millis(100)).await;
1778			producer.write(frame(&mut micros)).await.unwrap();
1779		}
1780		assert!(
1781			producer.bitrate().unwrap() <= Rate::from_mbps(1),
1782			"{:?}",
1783			producer.bitrate()
1784		);
1785	}
1786}