Skip to main content

moq_video/encode/
publisher.rs

1//! Publish already-encoded video frames as a moq video track.
2
3use moq_mux::catalog::hang::CatalogExt;
4
5use crate::Error;
6
7use super::Encoded;
8#[cfg(test)]
9use super::encoder;
10
11/// Convert the probed rendition into the importer hint published before the first frame.
12fn rendition_hint(rendition: hang::catalog::VideoConfig) -> moq_mux::catalog::VideoHint {
13	let mut hint = moq_mux::catalog::VideoHint::default();
14	hint.codec = Some(rendition.codec);
15	hint.coded_width = rendition.coded_width;
16	hint.coded_height = rendition.coded_height;
17	hint.display_aspect_width = rendition.display_aspect_width;
18	hint.display_aspect_height = rendition.display_aspect_height;
19	hint.color = rendition.color;
20	hint.framerate = rendition.framerate;
21	hint.reorder = rendition.reorder;
22	hint.bitrate = rendition.bitrate;
23	hint.delay = rendition.delay;
24	hint.optimize_for_latency = rendition.optimize_for_latency;
25	// Authoritative for both the catalog entry and the wire, so dropping it would silently
26	// downgrade a caller's selection to the default.
27	hint.container = rendition.container;
28	hint.preference = rendition.preference;
29	hint
30}
31
32/// Per-codec splitter + importer pair. Each codec frames its packets and resolves
33/// its catalog rendition differently, so the producer holds one of these.
34enum Codecs {
35	H264 {
36		split: moq_mux::codec::h264::Split,
37		import: moq_mux::codec::h264::Import,
38	},
39	H265 {
40		split: moq_mux::codec::h265::Split,
41		import: moq_mux::codec::h265::Import,
42	},
43}
44
45/// Publishes already-encoded video frames as a moq track (avc3 / hev1 depending on the
46/// codec), for a caller that runs its own encoder.
47///
48/// The `moq_mux::codec` importer for the codec handles catalog registration and framing.
49/// [`Producer`](super::Producer) runs the encoder too, and follows the uplink's grant.
50pub struct Publisher {
51	codecs: Codecs,
52}
53
54impl Publisher {
55	/// Publish `rendition` on `track`, registering it under `reserved`, a
56	/// [`catalog::Producer::reserve`](moq_mux::catalog::Producer::reserve)
57	/// that carries any per-track hint such as the encoder's GOP duration
58	/// ([`Reserved::with_interval`](moq_mux::catalog::Reserved::with_interval)).
59	/// The frames fed to [`publish`](Self::publish) must be in that
60	/// codec's framing, which is what the [`Encoder`](super::Encoder) the
61	/// rendition was probed from emits.
62	///
63	/// `rendition` comes from [`Config::probe`](super::Config::probe), so it is
64	/// what the encoder will actually emit rather than a guess. It is published
65	/// immediately, before anything is encoded, which is what lets a subscriber
66	/// discover a track an on-demand encoder has not run for yet; because it
67	/// already says what the first keyframe says, that keyframe confirms the
68	/// catalog instead of correcting it.
69	pub fn new<E: CatalogExt>(
70		track: moq_net::track::Producer,
71		reserved: moq_mux::catalog::Reserved<E>,
72		rendition: hang::catalog::VideoConfig,
73	) -> Result<Self, Error> {
74		let codecs = match &rendition.codec {
75			hang::catalog::VideoCodec::H264(_) => Codecs::H264 {
76				split: moq_mux::codec::h264::Split::new(),
77				import: moq_mux::codec::h264::Import::new(track, reserved, rendition_hint(rendition))?,
78			},
79			hang::catalog::VideoCodec::H265(_) => Codecs::H265 {
80				split: moq_mux::codec::h265::Split::new(),
81				import: moq_mux::codec::h265::Import::new(track, reserved, rendition_hint(rendition))?,
82			},
83			// Unreachable via `Config::probe`, which only encodes what `Codec` covers.
84			other => {
85				return Err(Error::codec(anyhow::anyhow!(
86					"{other} is not a codec this producer can publish"
87				)));
88			}
89		};
90		Ok(Self { codecs })
91	}
92
93	/// A watch-only handle to the track's subscriber demand, created eagerly so
94	/// subscription state is observable before any frames arrive. Watch it via
95	/// [`wanted`](moq_net::track::Demand::wanted) / [`wanted_changed`](moq_net::track::Demand::wanted_changed).
96	pub fn demand(&self) -> moq_net::track::Demand {
97		self.track().demand()
98	}
99
100	/// A handle that aborts the published track without keeping it open, for an owner that
101	/// must end it while this publisher is busy elsewhere.
102	pub fn abort_handle(&self) -> moq_net::track::AbortHandle {
103		self.track().abort_handle()
104	}
105
106	/// The published track. A frame that changes the decoder identity, such as a reopen onto
107	/// another mode or backend, moves the rendition to a newly named one.
108	fn track(&self) -> &moq_net::track::Producer {
109		match &self.codecs {
110			Codecs::H264 { import, .. } => import.track(),
111			Codecs::H265 { import, .. } => import.track(),
112		}
113	}
114
115	/// The group past the largest published while a subscriber asks for one, which the next
116	/// frame should open with a keyframe, or `None` while the largest serves.
117	#[cfg_attr(not(feature = "capture"), allow(dead_code, reason = "only capture forces keyframes"))]
118	pub(crate) fn wanted(&self) -> Option<u64> {
119		let track = self.track();
120		let asked = track.demand().poll_refresh(&kio::Waiter::noop());
121		if !matches!(asked, std::task::Poll::Ready(Ok(()))) {
122			return None;
123		}
124		Some(track.largest().map_or(0, |largest| largest.group.saturating_add(1)))
125	}
126
127	/// Publish one already-encoded frame at its own timestamp: one whole access unit
128	/// in the producer's codec framing.
129	pub fn publish(&mut self, encoded: &Encoded) -> Result<(), Error> {
130		let timestamp = Some(encoded.timestamp);
131		// The encoder emits one whole access unit per frame, so flush to emit it.
132		match &mut self.codecs {
133			Codecs::H264 { split, import } => {
134				let mut frames = split.decode(&encoded.payload, timestamp)?;
135				frames.extend(split.flush(timestamp)?);
136				import.decode(frames)?;
137			}
138			Codecs::H265 { split, import } => {
139				let mut frames = split.decode(&encoded.payload, timestamp)?;
140				frames.extend(split.flush(timestamp)?);
141				import.decode(frames)?;
142			}
143		}
144		Ok(())
145	}
146
147	/// Mark a break in the published timeline: whatever is published next does not continue
148	/// what came before.
149	///
150	/// Call this when the encoder stops rather than merely pausing between frames -- a
151	/// capture that goes idle, a source switch, anything that will resume on a re-anchored
152	/// clock. See [`Producer::discontinuity`](moq_mux::container::Producer::discontinuity)
153	/// for what the marker buys a consumer.
154	pub fn discontinuity(&mut self) -> Result<(), Error> {
155		match &mut self.codecs {
156			Codecs::H264 { import, .. } => import.discontinuity()?,
157			Codecs::H265 { import, .. } => import.discontinuity()?,
158		}
159		Ok(())
160	}
161
162	/// Advertise whether this rendition is being encoded, as the catalog's
163	/// [`enabled`](hang::catalog::VideoConfig::enabled).
164	///
165	/// Disable it when the encoder stops for lack of bandwidth (a
166	/// [`rate::Target::Disabled`](moq_mux::rate::Target::Disabled)), so viewers select a
167	/// lower rendition instead of waiting for frames, and mark the
168	/// [`discontinuity`](Self::discontinuity) too. The advertised rendition is otherwise
169	/// unchanged, its maximum bitrate included. Enable it again with the keyframe that
170	/// resumes it.
171	pub fn set_enabled(&mut self, enabled: bool) -> Result<(), Error> {
172		match &mut self.codecs {
173			Codecs::H264 { import, .. } => import.set_enabled(enabled)?,
174			Codecs::H265 { import, .. } => import.set_enabled(enabled)?,
175		}
176		Ok(())
177	}
178
179	/// Report capture frames the encoder never saw, in the catalog's stats.
180	#[cfg_attr(not(feature = "capture"), allow(dead_code, reason = "only capture skips frames"))]
181	pub(crate) fn report_skipped(&self, frames: u64) {
182		match &self.codecs {
183			Codecs::H264 { import, .. } => import.report_skipped(frames),
184			Codecs::H265 { import, .. } => import.report_skipped(frames),
185		}
186	}
187
188	/// Report the encoder's target bitrate, in the catalog's stats.
189	pub(crate) fn report_bitrate(&self, bitrate: moq_net::bandwidth::Rate) {
190		match &self.codecs {
191			Codecs::H264 { import, .. } => import.report_bitrate(bitrate),
192			Codecs::H265 { import, .. } => import.report_bitrate(bitrate),
193		}
194	}
195
196	/// Finalize the track.
197	///
198	/// Consumes the publisher, releasing the splitter. The returned [`Finished`] keeps the track
199	/// and its catalog rendition published, and can still [`abort`](Finished::abort) them. A
200	/// finish that fails ends the track with an error instead.
201	pub fn finish(self) -> Result<Finished, Error> {
202		// Each publish flushed its access unit, so the splitter holds only input storage.
203		let track = match self.codecs {
204			Codecs::H264 { import, .. } => import.finish()?,
205			Codecs::H265 { import, .. } => import.finish()?,
206		};
207		Ok(Finished { track })
208	}
209
210	/// Abort the track with `err` instead of finishing it cleanly, so subscribers
211	/// see the real cause rather than [`moq_net::Error::Dropped`].
212	pub fn abort(self, err: moq_net::Error) {
213		match self.codecs {
214			Codecs::H264 { import, .. } => import.abort(err),
215			Codecs::H265 { import, .. } => import.abort(err),
216		}
217	}
218}
219
220/// A video track whose [`Producer`](super::Producer) or [`Publisher`] finished it: every frame
221/// is published, and it can still be watched or aborted, but not written to.
222///
223/// Dropping it releases the track like dropping the producer.
224///
225/// ```compile_fail,E0599
226/// # fn cannot_publish(track: moq_video::encode::Finished, encoded: &moq_video::encode::Encoded) {
227/// track.publish(encoded).unwrap();
228/// # }
229/// ```
230#[must_use = "dropping it releases the track and its catalog rendition"]
231pub struct Finished {
232	track: moq_mux::container::Finished<moq_mux::catalog::hang::Wire, hang::catalog::VideoConfig>,
233}
234
235impl Finished {
236	/// A watch-only handle to the track's subscriber demand.
237	pub fn demand(&self) -> moq_net::track::Demand {
238		self.track.demand()
239	}
240
241	/// Abort the track with `err`; see [`moq_net::track::Finished::abort`]. Readers still draining
242	/// get the clean end instead once every group below the end finished.
243	pub fn abort(self, err: moq_net::Error) {
244		self.track.abort(err);
245	}
246}
247
248#[cfg(test)]
249mod tests {
250	#![cfg_attr(
251		not(feature = "openh264"),
252		allow(dead_code, unused_imports, reason = "only the `openh264` feature uses it")
253	)]
254
255	use moq_mux::catalog::Stream as _;
256	use moq_net::Timestamp;
257
258	use super::*;
259	use crate::Frame;
260	use crate::encode::{Codec, Config, Encoder};
261
262	/// Encode a handful of synthetic frames for `codec` and publish them through a real
263	/// [`Publisher`], returning the catalog rendition's track name and config.
264	///
265	/// Asserts the property the whole design rests on: the rendition published before anything is
266	/// encoded is the one the first keyframe resolves. A guessed codec string would be corrected
267	/// here; a probed one is confirmed, so the catalog is written once.
268	///
269	/// `kind` is explicit so the test picks a deterministic encoder rather than `Auto`, which on
270	/// Linux CI would try the NVENC backend and panic in cudarc on a GPU-less runner.
271	async fn roundtrip_rendition(codec: Codec, kind: encoder::Backend) -> hang::catalog::VideoConfig {
272		let mut broadcast = moq_net::broadcast::Info::new().produce();
273		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
274
275		let mut config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
276		config.codec = codec;
277		config.backend = kind;
278
279		let mut producer = Publisher::new(
280			broadcast
281				.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video))
282				.unwrap(),
283			catalog.reserve().with_interval(config.effective_join()),
284			config.probe().await.unwrap(),
285		)
286		.unwrap();
287		let advertised = rendition(&catalog).expect("the rendition publishes before any frame").1;
288
289		let mut encoder = Encoder::new(&config).unwrap();
290		assert_eq!(encoder.codec(), codec);
291
292		let rgba = vec![0x80u8; 320 * 240 * 4];
293		for i in 0..10u64 {
294			let surface = crate::Surface::rgba(&rgba, crate::Size::new(320, 240)).unwrap();
295			let frame = Frame::new(Timestamp::from_micros(i * 33_333).unwrap(), surface);
296			for encoded in encoder.encode_all(&frame).unwrap() {
297				producer.publish(&encoded).unwrap();
298			}
299		}
300		for encoded in encoder.flush_all().unwrap() {
301			producer.publish(&encoded).unwrap();
302		}
303
304		let (_, resolved) = rendition(&catalog).expect("the importer should have registered a video rendition");
305		// Jitter and delay aside, which are measured from the frames rather than declared by either.
306		let (mut before, mut after) = (advertised, resolved.clone());
307		(before.jitter, before.delay) = (None, None);
308		(after.jitter, after.delay) = (None, None);
309		assert_eq!(
310			before, after,
311			"the first keyframe should confirm the advertised rendition, not correct it"
312		);
313		resolved
314	}
315
316	/// The catalog's single video rendition, if it has one yet.
317	fn rendition(catalog: &moq_mux::catalog::Producer) -> Option<(String, hang::catalog::VideoConfig)> {
318		let snapshot = catalog.snapshot();
319		let (name, config) = snapshot.video.renditions.iter().next()?;
320		Some((name.clone(), config.clone()))
321	}
322
323	async fn collect_groups(mut consumer: moq_net::track::Subscriber) -> Vec<usize> {
324		let mut groups = Vec::new();
325		while let Some(mut group) = consumer.recv_group().await.unwrap() {
326			let mut frames = 0;
327			while group.next_frame().await.unwrap().is_some() {
328				frames += 1;
329			}
330			groups.push(frames);
331		}
332		groups
333	}
334
335	/// An on-demand capture resumes on the same wall clock after releasing its camera and encoder,
336	/// so the idle transition must publish a marker group between the two runs. This uses synthetic
337	/// frames and the software encoder to exercise the transition without capture hardware.
338	#[tokio::test]
339	#[cfg(feature = "openh264")]
340	async fn idle_capture_publishes_a_discontinuity_before_resume() {
341		let mut broadcast = moq_net::broadcast::Info::new().produce();
342		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
343		// The synthetic clock jumps ten seconds. Keep every fixture group readable until the
344		// assertion instead of letting the default five-second publisher window evict the marker.
345		let replay = std::time::Duration::from_secs(11);
346		let track = broadcast
347			.create_track(
348				"video",
349				catalog.track_info(hang::catalog::PRIORITY.video).with_max_age(replay),
350			)
351			.unwrap();
352		let consumer =
353			track.subscribe(
354				moq_net::track::Subscription::default().with_ranges([moq_net::track::Range::from(
355					moq_net::track::Start::Live {
356						min: Some(replay),
357						max: Some(replay),
358					},
359				)]),
360			);
361
362		let mut config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
363		config.backend = encoder::Backend::Software;
364		let mut producer = Publisher::new(
365			track,
366			catalog.reserve().with_interval(config.effective_join()),
367			config.probe().await.unwrap(),
368		)
369		.unwrap();
370		let mut encoder = Encoder::new(&config).unwrap();
371		let rgba = vec![0x80u8; 320 * 240 * 4];
372
373		for timestamp in [0, 10_000_000] {
374			if timestamp > 0 {
375				producer.discontinuity().unwrap();
376			}
377			encoder.cut().unwrap();
378			let surface = crate::Surface::rgba(&rgba, crate::Size::new(320, 240)).unwrap();
379			let frame = Frame::new(Timestamp::from_micros(timestamp).unwrap(), surface);
380			for encoded in encoder.encode_all(&frame).unwrap() {
381				producer.publish(&encoded).unwrap();
382			}
383		}
384		let _finished = producer.finish().unwrap();
385
386		assert_eq!(collect_groups(consumer).await, vec![1, 1, 1]);
387	}
388
389	#[tokio::test]
390	#[cfg(feature = "openh264")]
391	async fn source_resize_publishes_a_new_track() {
392		let mut broadcast = moq_net::broadcast::Info::new().produce();
393		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
394		let mut initial = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
395		initial.backend = encoder::Backend::Software;
396		let mut producer = Publisher::new(
397			broadcast
398				.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video))
399				.unwrap(),
400			catalog.reserve().with_interval(initial.effective_join()),
401			initial.probe().await.unwrap(),
402		)
403		.unwrap();
404
405		for (timestamp, config) in [
406			(0, initial),
407			(33_333, Config::new(640, 360, crate::FrameRate::new(30, 1).unwrap())),
408		] {
409			let mut config = config;
410			config.backend = encoder::Backend::Software;
411			let mut encoder = Encoder::new(&config).unwrap();
412			encoder.cut().unwrap();
413			let rgba = vec![0x80u8; usize::try_from(config.width * config.height * 4).unwrap()];
414			let surface = crate::Surface::rgba(&rgba, crate::Size::new(config.width, config.height)).unwrap();
415			let frame = Frame::new(Timestamp::from_micros(timestamp).unwrap(), surface);
416			for encoded in encoder.encode_all(&frame).unwrap() {
417				producer.publish(&encoded).unwrap();
418			}
419			producer.discontinuity().unwrap();
420		}
421
422		// 640x360 takes a higher level than the probed 320x240, so it is a new track.
423		let (name, rendition) = rendition(&catalog).expect("the resized rendition should be published");
424		assert_eq!(name, "video/1", "the resize is a new track");
425		assert_eq!(rendition.coded_width, Some(640));
426		assert_eq!(rendition.coded_height, Some(360));
427	}
428
429	/// Regression: a caller's container and preference have to survive the config -> hint conversion.
430	///
431	/// [`VideoHint::container`](moq_mux::catalog::VideoHint::container) is authoritative for both the
432	/// track writer and the published rendition, so a conversion that drops it silently downgrades
433	/// the caller's selection to Legacy while the catalog still claims whatever it defaulted to. A
434	/// dropped preference would turn a compatibility transcode into a peer of its source.
435	#[tokio::test]
436	#[cfg(feature = "openh264")]
437	async fn a_selected_container_and_preference_survive_the_rendition_hint() {
438		let mut broadcast = moq_net::broadcast::Info::new().produce();
439		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
440
441		let mut config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
442		// Software (openh264) so the test is deterministic and never touches a hardware backend.
443		config.backend = encoder::Backend::Software;
444		let mut selected = config.probe().await.unwrap();
445		selected.container = hang::catalog::Container::Loc;
446		selected.preference = -1;
447
448		let track = broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video));
449		let _producer = Publisher::new(track, catalog.reserve(), selected).unwrap();
450
451		let (_, published) = rendition(&catalog).expect("the rendition publishes before any frame");
452		assert_eq!(published.container, hang::catalog::Container::Loc);
453		assert_eq!(published.preference, -1);
454	}
455
456	/// Regression: the rendition has to reach the wire before anything is encoded.
457	///
458	/// A catalog reservation is held until the rendition resolves, and an unresolved one withholds
459	/// the whole catalog from the broadcast. An encoder that runs only while watched then closes a
460	/// cycle: the catalog waits on a keyframe, the keyframe waits on a subscriber, and the
461	/// subscriber waits on the catalog. Nothing errors on either side; the publisher simply serves
462	/// nothing, forever.
463	#[tokio::test]
464	#[cfg(feature = "openh264")]
465	async fn the_rendition_reaches_the_wire_before_the_first_frame() {
466		let mut broadcast = moq_net::broadcast::Info::new().produce();
467		let consumer = broadcast.consume();
468		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
469
470		let mut config = Config::new(1920, 1080, crate::FrameRate::new(30, 1).unwrap());
471		config.bitrate = Some(moq_net::bandwidth::Rate::from_mbps(6));
472		// Software (openh264) so the test is deterministic and never touches a hardware backend.
473		config.backend = encoder::Backend::Software;
474		let _producer = Publisher::new(
475			broadcast
476				.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video))
477				.unwrap(),
478			catalog.reserve().with_interval(config.effective_join()),
479			config.probe().await.unwrap(),
480		)
481		.unwrap();
482
483		// Published, not merely staged: this reads the catalog track a subscriber would.
484		let mut stream = moq_mux::catalog::Consumer::<()>::new(&consumer, moq_mux::catalog::CatalogFormat::Hang)
485			.await
486			.unwrap();
487		let snapshot = stream.next().await.unwrap().expect("a catalog before any frame").value;
488
489		let (_, rendition) = snapshot
490			.video
491			.renditions
492			.iter()
493			.next()
494			.expect("the track must be discoverable before it has encoded anything");
495
496		// Read out of the encoder rather than guessed: the avc3 shape (parameter sets in band) and
497		// the geometry it was opened at, which is what its first keyframe will carry.
498		let hang::catalog::VideoCodec::H264(h264) = &rendition.codec else {
499			panic!("expected H.264, got {}", rendition.codec)
500		};
501		assert!(h264.inline, "an avc3 track carries its parameter sets in band");
502		assert_eq!(rendition.coded_width, Some(1920));
503		assert_eq!(rendition.coded_height, Some(1080));
504		// Neither is in the bitstream, so both come from the config that was probed.
505		assert_eq!(rendition.framerate, Some(30.0));
506		assert_eq!(rendition.bitrate, Some(6_000_000));
507	}
508
509	/// Finish returns a handle, so abort can still run.
510	#[tokio::test]
511	#[cfg(feature = "openh264")]
512	async fn abort_after_finish() {
513		let mut broadcast = moq_net::broadcast::Info::new().produce();
514		let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
515		let mut config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
516		config.backend = encoder::Backend::Software;
517		let track = broadcast
518			.create_track("video", catalog.track_info(hang::catalog::PRIORITY.video))
519			.unwrap();
520		let mut subscriber = track.subscribe(None);
521		let mut producer = Publisher::new(
522			track,
523			catalog.reserve().with_interval(config.effective_join()),
524			config.probe().await.unwrap(),
525		)
526		.unwrap();
527		let mut encoder = Encoder::new(&config).unwrap();
528		let rgba = vec![0x80u8; 320 * 240 * 4];
529		let surface = crate::Surface::rgba(&rgba, crate::Size::new(320, 240)).unwrap();
530		let frame = Frame::new(Timestamp::from_micros(0).unwrap(), surface);
531		for encoded in encoder.encode_all(&frame).unwrap() {
532			producer.publish(&encoded).unwrap();
533		}
534
535		let finished = producer.finish().unwrap();
536		assert!(subscriber.recv_group().await.unwrap().is_some());
537		finished.abort(moq_net::Error::Cancel);
538	}
539
540	#[tokio::test]
541	#[cfg(feature = "openh264")]
542	async fn h264_roundtrip_publishes_avc3() {
543		// Software (openh264) so the test is deterministic and never touches a
544		// hardware backend.
545		let config = roundtrip_rendition(Codec::H264, encoder::Backend::Software).await;
546		assert_eq!(config.reorder, Some(0));
547		assert_eq!(config.coded_width, Some(320));
548		assert_eq!(config.coded_height, Some(240));
549	}
550
551	/// H.265 has no software encoder, so this only runs where a hardware one
552	/// exists (VideoToolbox on macOS, the only hardware backend on this target).
553	#[cfg(apple)]
554	#[tokio::test]
555	async fn h265_roundtrip_publishes_hev1() {
556		let config = roundtrip_rendition(Codec::H265, encoder::Backend::Hardware).await;
557		assert_eq!(config.coded_width, Some(320));
558		assert_eq!(config.coded_height, Some(240));
559	}
560}
561
562/// A finished [`Publisher`] keeps its track and rendition published, but not its splitter.
563///
564/// Bindings keep finished video producers until their broadcast ends, so a long-lived broadcast
565/// that retires many encoders would otherwise hold each one's largest access unit. The counting
566/// allocator serves this crate's whole unit-test binary, but it counts only on a thread inside
567/// [`released`], so other tests are unaffected.
568#[cfg(test)]
569mod finished {
570	use std::alloc::{GlobalAlloc, Layout, System};
571	use std::cell::Cell;
572
573	use super::*;
574
575	/// The access unit each source publishes, far above the bookkeeping a finished producer keeps.
576	const PAD: usize = 1 << 20;
577
578	thread_local! {
579		/// Bytes this thread freed minus those it allocated while measuring. Per thread so concurrent
580		/// tests don't mix, and `const` so the allocator can read it without allocating.
581		static RELEASED: Cell<Option<isize>> = const { Cell::new(None) };
582	}
583
584	fn count(bytes: isize) {
585		// `try_with` because TLS is unavailable while a thread is being torn down.
586		let _ = RELEASED.try_with(|released| released.set(released.get().map(|n| n + bytes)));
587	}
588
589	/// Counts on the measuring thread; every call forwards to the system allocator unchanged.
590	struct Counting;
591
592	unsafe impl GlobalAlloc for Counting {
593		unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
594			count(-(layout.size() as isize));
595			unsafe { System.alloc(layout) }
596		}
597
598		unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
599			count(layout.size() as isize);
600			unsafe { System.dealloc(ptr, layout) }
601		}
602
603		unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
604			count(layout.size() as isize - new_size as isize);
605			unsafe { System.realloc(ptr, layout, new_size) }
606		}
607	}
608
609	#[global_allocator]
610	static ALLOCATOR: Counting = Counting;
611
612	/// The heap `f` gives back, net of what it allocates on the way.
613	fn released(f: impl FnOnce()) -> isize {
614		RELEASED.with(|released| released.set(Some(0)));
615		f();
616		RELEASED.with(|released| released.replace(None).unwrap())
617	}
618
619	/// An H.264 IDR access unit carrying its SPS and PPS, padded to [`PAD`] with filler data.
620	fn keyframe() -> bytes::Bytes {
621		let mut au = vec![0, 0, 0, 1];
622		au.extend_from_slice(&[
623			0x67, 0x64, 0x00, 0x1f, 0xac, 0x24, 0x84, 0x01, 0x40, 0x16, 0xec, 0x04, 0x40, 0x00, 0x00, 0x03, 0x00, 0x40,
624			0x00, 0x00, 0x0c, 0x23, 0xc6, 0x0c, 0x92,
625		]);
626		au.extend_from_slice(&[0, 0, 0, 1, 0x68, 0xee, 0x32, 0xc8, 0xb0]);
627		au.extend_from_slice(&[0, 0, 0, 1, 0x65, 0x88, 0x84, 0x21]);
628		au.extend_from_slice(&[0, 0, 0, 1, 0x0c]);
629		au.resize(au.len() + PAD, 0xff);
630		au.push(0x80);
631		au.into()
632	}
633
634	#[tokio::test(start_paused = true)]
635	async fn finished_producer_releases_its_splitter() {
636		for sources in [1, 4] {
637			let mut broadcast = moq_net::broadcast::Info::new().produce();
638			let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
639			let consumer = broadcast.consume();
640
641			let rendition = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::H264(hang::catalog::H264 {
642				inline: true,
643				profile: 0x64,
644				constraints: 0,
645				level: 0x1f,
646			}));
647			let finished: Vec<_> = (0..sources)
648				.map(|_| {
649					let track = broadcast.unique_track(".avc3", catalog.track_info(hang::catalog::PRIORITY.video));
650					let mut producer = Publisher::new(track, catalog.reserve(), rendition.clone()).unwrap();
651					for pts in [0, 33_333] {
652						let pts = moq_net::Timestamp::from_micros(pts).unwrap();
653						producer.publish(&Encoded::new(pts, keyframe(), true)).unwrap();
654					}
655					producer.finish().unwrap()
656				})
657				.collect();
658
659			// Late readers keep the published media, so only what the producers own is measured.
660			let snapshot = catalog.snapshot();
661			assert_eq!(snapshot.video.renditions.len(), sources);
662			let _tracks: Vec<_> = snapshot
663				.video
664				.renditions
665				.keys()
666				.map(|name| consumer.track(name).unwrap())
667				.collect();
668
669			let released = released(|| drop(finished));
670			assert!(
671				released < (sources * PAD / 4) as isize,
672				"{sources} finished producers still owned {released} bytes"
673			);
674		}
675	}
676}