moq_video/encode/producer.rs
1//! Encode decoded video frames and publish them as a moq video track.
2//!
3//! Encoding is strictly on demand: the track and catalog entry are advertised
4//! immediately, but the camera stays closed (LED off, no CPU) until a subscriber
5//! appears. When the last viewer leaves, the camera is released again. This
6//! mirrors `moq-boy`, which pauses its emulator on `track::Producer::used()` /
7//! `unused()`.
8
9use std::time::Instant;
10
11use moq_net::Timestamp;
12
13use crate::capture;
14use crate::{Error, Frame};
15
16use super::Encoded;
17use super::encoder::{self, Codec};
18use super::rate::{Control, Policy};
19use super::sink::Sink;
20
21/// Last-resort framerate when neither the caller nor the camera reports one.
22const DEFAULT_FRAMERATE: u32 = 30;
23
24/// Per-codec splitter + importer pair. Each codec frames its packets and resolves
25/// its catalog rendition differently, so the producer holds one of these.
26enum Codecs {
27 H264 {
28 split: moq_mux::codec::h264::Split,
29 import: moq_mux::codec::h264::Import,
30 },
31 H265 {
32 split: moq_mux::codec::h265::Split,
33 import: moq_mux::codec::h265::Import,
34 },
35}
36
37/// Publishes encoded video frames as a moq track (avc3 / hev1 depending on the
38/// codec).
39///
40/// Built on the async side so the track is advertised (and the catalog
41/// registered) before the camera opens; this is what lets a subscriber
42/// trigger capture on demand. The `moq_mux::codec` importer for the codec
43/// handles catalog registration and framing.
44pub struct Producer {
45 codecs: Codecs,
46}
47
48impl Producer {
49 /// Publish a track for `codec` into `broadcast`, registering its rendition
50 /// in `catalog`. The frames fed to [`publish`](Self::publish) must be in
51 /// that codec's framing (the matching [`Encoder`](super::Encoder) emits it).
52 pub fn new(
53 mut broadcast: moq_net::broadcast::Producer,
54 catalog: moq_mux::catalog::Producer,
55 codec: Codec,
56 ) -> Result<Self, Error> {
57 let codecs = match codec {
58 Codec::H264 => {
59 let track = moq_mux::import::unique_track(&mut broadcast, ".avc3")?;
60 Codecs::H264 {
61 split: moq_mux::codec::h264::Split::new(),
62 import: moq_mux::codec::h264::Import::new(track, catalog.reserve(), Default::default())?,
63 }
64 }
65 Codec::H265 => {
66 let track = moq_mux::import::unique_track(&mut broadcast, ".hev1")?;
67 Codecs::H265 {
68 split: moq_mux::codec::h265::Split::new(),
69 import: moq_mux::codec::h265::Import::new(track, catalog.reserve(), Default::default())?,
70 }
71 }
72 };
73 Ok(Self { codecs })
74 }
75
76 /// A watch-only handle to the track's subscriber demand, created eagerly so
77 /// subscription state is observable before any frames arrive. Watch it via
78 /// [`used`](moq_net::track::Demand::used) / [`unused`](moq_net::track::Demand::unused).
79 pub fn demand(&self) -> moq_net::track::Demand {
80 match &self.codecs {
81 Codecs::H264 { import, .. } => import.demand(),
82 Codecs::H265 { import, .. } => import.demand(),
83 }
84 }
85
86 /// Publish already-encoded frames, each at its own timestamp. Each frame is one
87 /// whole access unit in the producer's codec framing.
88 pub fn publish(&mut self, encoded: &[Encoded]) -> Result<(), Error> {
89 for frame in encoded {
90 let timestamp = Some(frame.timestamp);
91 // The encoder emits one whole access unit per frame, so flush to emit it.
92 match &mut self.codecs {
93 Codecs::H264 { split, import } => {
94 let mut frames = split.decode(&frame.payload, timestamp)?;
95 frames.extend(split.flush(timestamp)?);
96 import.decode(frames)?;
97 }
98 Codecs::H265 { split, import } => {
99 let mut frames = split.decode(&frame.payload, timestamp)?;
100 frames.extend(split.flush(timestamp)?);
101 import.decode(frames)?;
102 }
103 }
104 }
105 Ok(())
106 }
107
108 /// Mark a break in the published timeline: whatever is published next does not continue
109 /// what came before.
110 ///
111 /// Call this when the encoder stops rather than merely pausing between frames -- a
112 /// capture that goes idle, a source switch, anything that will resume on a re-anchored
113 /// clock. See [`Producer::discontinuity`](moq_mux::container::Producer::discontinuity)
114 /// for what the marker buys a consumer.
115 pub fn discontinuity(&mut self) -> Result<(), Error> {
116 match &mut self.codecs {
117 Codecs::H264 { import, .. } => import.discontinuity()?,
118 Codecs::H265 { import, .. } => import.discontinuity()?,
119 }
120 Ok(())
121 }
122
123 /// Finalize the track.
124 ///
125 /// Consumes the producer: nothing can be published after the track ends, so
126 /// this is the last call rather than one leaving a dead producer in your hands.
127 pub fn finish(mut self) -> Result<(), Error> {
128 match &mut self.codecs {
129 Codecs::H264 { import, .. } => import.finish()?,
130 Codecs::H265 { import, .. } => import.finish()?,
131 }
132 Ok(())
133 }
134
135 /// Abort the track with `err` instead of finishing it cleanly, so subscribers
136 /// see the real cause rather than [`moq_net::Error::Dropped`].
137 ///
138 /// Consumes the producer, like [`finish`](Self::finish).
139 pub fn abort(self, err: moq_net::Error) {
140 match self.codecs {
141 Codecs::H264 { import, .. } => import.abort(err),
142 Codecs::H265 { import, .. } => import.abort(err),
143 }
144 }
145}
146
147/// Source-agnostic encode knobs for [`publish_capture`], where the geometry
148/// (width / height / framerate) comes from the capture source, not the caller.
149/// For the bring-your-own-frames [`Encoder`](super::Encoder) path, where you
150/// must specify geometry, use [`Config`](super::Config) instead.
151///
152/// `#[non_exhaustive]`: construct via [`Options::default`] and set fields, so
153/// new knobs can be added without breaking callers.
154#[derive(Clone, Default)]
155#[non_exhaustive]
156pub struct Options {
157 /// Target bitrate in bits per second; `None` derives from resolution.
158 ///
159 /// This is a ceiling, not a fixed rate: with [`bandwidth`](Self::bandwidth)
160 /// set, the encoder backs off below it while the uplink is congested and
161 /// climbs back afterwards, but never exceeds it.
162 pub bitrate: Option<u64>,
163 /// Output codec. Defaults to [`Codec::H264`].
164 pub codec: Codec,
165 /// Encoder implementation preference.
166 pub kind: encoder::Kind,
167 /// The connection's send-bandwidth estimate, from
168 /// [`Session::send_bandwidth`](moq_net::Session::send_bandwidth) (or
169 /// `moq_native::Reconnect::send_bandwidth`, which survives reconnects).
170 ///
171 /// Set it and the encoder tracks the estimate per the default
172 /// [`rate::Policy`](super::rate::Policy), so a closing uplink gets a softer
173 /// picture instead of a stalled one. Leave it `None` and the
174 /// encoder holds [`bitrate`](Self::bitrate) regardless of congestion, which
175 /// is what you want when the estimate isn't meaningful (a local file, a test
176 /// harness) or unavailable (a publisher that only accepts inbound sessions).
177 pub bandwidth: Option<moq_net::bandwidth::Consumer>,
178}
179
180// Hand-written: `bandwidth::Consumer` isn't `Debug`, but its presence is the
181// only part worth printing anyway.
182impl std::fmt::Debug for Options {
183 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184 f.debug_struct("Options")
185 .field("bitrate", &self.bitrate)
186 .field("codec", &self.codec)
187 .field("kind", &self.kind)
188 .field("bandwidth", &self.bandwidth.is_some())
189 .finish()
190 }
191}
192
193/// Capture a webcam and publish it as an on-demand video track.
194///
195/// Returns when the broadcast is dropped (the track stops being announced)
196/// or the capture loop fails. The camera is opened only while at least one
197/// subscriber is watching; frames are stamped from `clock`, so passing the
198/// same [`Clock`](moq_mux::Clock) to a concurrent audio publish keeps the two
199/// tracks aligned.
200pub async fn publish_capture(
201 broadcast: moq_net::broadcast::Producer,
202 catalog: moq_mux::catalog::Producer,
203 capture: capture::Config,
204 encode: Options,
205 clock: moq_mux::Clock,
206) -> Result<(), Error> {
207 // A caller asking for exactly zero is an error; omitting it (None) is
208 // fine and resolves to the camera's reported rate once it's open.
209 if capture.framerate == Some(0) {
210 return Err(Error::InvalidFramerate(0));
211 }
212
213 let mut producer = Producer::new(broadcast, catalog, encode.codec)?;
214 let demand = producer.demand();
215
216 let result = capture_loop(&mut producer, &demand, &capture, &encode, &clock).await;
217
218 // This runs only when the loop ends on its own (the track is usually already
219 // going away by then); a Ctrl+C cancels the future before this point, since
220 // async `Drop` can't finalize the track.
221 match &result {
222 // Clean end (the track was dropped): best-effort finish.
223 Ok(()) => {
224 if let Err(err) = producer.finish() {
225 tracing::debug!(error = %err, "video track finish after capture ended");
226 }
227 }
228 // The capture loop failed: abort with the real cause so subscribers see it.
229 Err(err) => producer.abort(moq_net::Error::Transport(err.to_string())),
230 }
231 result
232}
233
234/// Off macOS, [`publish_capture`]'s future must stay `Send` so a server can
235/// `tokio::spawn` it: the encoder runs on its own thread and the capture guard
236/// is `Send` there. This is never called; it exists only to fail compilation if
237/// the future ever regains a `!Send` component. macOS is exempt (the objc
238/// capture session is `!Send`).
239#[cfg(not(target_os = "macos"))]
240#[allow(dead_code)]
241fn assert_publish_capture_send(
242 broadcast: moq_net::broadcast::Producer,
243 catalog: moq_mux::catalog::Producer,
244 capture: capture::Config,
245 encode: Options,
246 clock: moq_mux::Clock,
247) {
248 fn is_send<T: Send>(_: &T) {}
249 is_send(&publish_capture(broadcast, catalog, capture, encode, clock));
250}
251
252/// The live rate control state: the estimate source paired with the policy
253/// tracking it. `None` once there's nothing left to track, which is what stops
254/// the `select!` arm from spinning on a channel that is permanently ready.
255type Rate = Option<(moq_net::bandwidth::Consumer, Control)>;
256
257/// Wait for the next bandwidth estimate, or forever when rate control is off or
258/// finished. Cancel-safe: [`Consumer::changed`](moq_net::bandwidth::Consumer::changed)
259/// only reads shared state, so losing this race to a frame drops no estimate,
260/// it just re-reads the latest one next time round.
261async fn next_estimate(rate: &mut Rate) -> Option<Option<u64>> {
262 match rate {
263 Some((bandwidth, _)) => bandwidth.changed().await.ok(),
264 // No estimate source: park this arm forever so `select!` ignores it.
265 None => std::future::pending().await,
266 }
267}
268
269/// Feed an estimate through the policy and retune the encoder if it moved.
270///
271/// `None` means the producer is gone (the session ended for good), so rate
272/// control retires; a `Some(None)` estimate means the value is merely
273/// unavailable right now, which the policy holds through.
274async fn apply_estimate(encoder: &mut Sink, rate: &mut Rate, estimate: Option<Option<u64>>) {
275 let Some((_, control)) = rate.as_mut() else { return };
276
277 let Some(estimate) = estimate else {
278 tracing::debug!("bandwidth estimate ended; holding the current encoder bitrate");
279 *rate = None;
280 return;
281 };
282
283 let Some(bitrate) = control.update(estimate, Instant::now()) else {
284 return;
285 };
286
287 match encoder.set_bitrate(bitrate).await {
288 Ok(()) => tracing::debug!(bitrate, estimate, "adjusted encoder bitrate"),
289 // The encoder can't retune, so keep encoding at the rate it opened with
290 // and stop asking. Dropping the source also stops the estimate arm, which
291 // would otherwise wake this loop for nothing on every change.
292 Err(Error::BitrateUnsupported(name)) => {
293 tracing::warn!(encoder = name, "encoder cannot follow the bandwidth estimate");
294 *rate = None;
295 }
296 // A transient failure: keep the policy running so the next change retries.
297 // The policy already moved its target, so a persistent failure just means
298 // the encoder trails it; that's better than giving up on the first blip.
299 Err(err) => tracing::warn!(error = %err, bitrate, "failed to adjust encoder bitrate"),
300 }
301}
302
303/// A dropped or closed track is the normal end of a publish; any other cause is
304/// a real abort (e.g. a transport reset) worth surfacing rather than treating as
305/// a clean exit.
306fn log_track_ended(err: moq_net::Error) {
307 if matches!(err, moq_net::Error::Dropped | moq_net::Error::Closed) {
308 tracing::debug!("video track no longer announced; stopping capture");
309 } else {
310 tracing::warn!(error = %err, "video track aborted; stopping capture");
311 }
312}
313
314/// Async capture/encode loop. Captures one frame up front to populate the
315/// catalog (the codec/resolution only exist once the encoder has produced an
316/// SPS), then releases the camera whenever the last viewer leaves and reopens it
317/// when one returns.
318///
319/// Cancel safety: every wait here is a real `.await` (a frame read, a demand
320/// transition, or an encode), so dropping this future (e.g. on Ctrl+C) drops
321/// `camera` and `encoder`, which release the device (LED off) and join the
322/// encode thread. Both the capture and encode threads sit idle between frames,
323/// so their joins return promptly unless the underlying device or encoder is
324/// itself wedged.
325async fn capture_loop(
326 producer: &mut Producer,
327 demand: &moq_net::track::Demand,
328 capture: &capture::Config,
329 encode: &Options,
330 clock: &moq_mux::Clock,
331) -> Result<(), Error> {
332 // The catalog video rendition only appears once a frame has been encoded (the
333 // importer reads the SPS). Until then we capture regardless of demand so a
334 // catalog-driven subscriber can discover the track and trigger `used()`.
335 // After that we release the camera while unwatched.
336 let mut catalog_ready = false;
337
338 loop {
339 if catalog_ready {
340 // Idle until a viewer subscribes; the track ending is a clean exit.
341 if let Err(err) = demand.used().await {
342 log_track_ended(err);
343 return Ok(());
344 }
345 }
346
347 // Open the camera and an encoder sized to its negotiated mode.
348 let mut camera = capture::open(capture).await?;
349 // Prefer an explicit --fps, otherwise the camera's reported rate, falling
350 // back only if the backend doesn't expose one.
351 let framerate = capture
352 .framerate
353 .or_else(|| camera.framerate())
354 .unwrap_or(DEFAULT_FRAMERATE);
355 let mut encoder_config = encoder::Config::new(camera.width(), camera.height(), framerate);
356 encoder_config.bitrate = encode.bitrate;
357 encoder_config.codec = encode.codec;
358 encoder_config.kind = encode.kind.clone();
359 // Off macOS this opens the encoder on a dedicated thread; see `sink`.
360 let mut encoder = Sink::open(&encoder_config).await?;
361 // Force an IDR on the first frame of each (re)open so a viewer subscribing
362 // after an idle gap can start decoding immediately.
363 let mut force_keyframe = true;
364 tracing::info!(encoder = encoder.name(), device = camera.device(), "capturing");
365
366 // Rate control is per encoder: this one opened at the configured bitrate,
367 // so the policy's ceiling is that rate and the target starts there. A
368 // reopened camera starts optimistic again rather than inheriting the
369 // backed-off rate from whatever the link was doing last time.
370 let mut rate = encode
371 .bandwidth
372 .clone()
373 .map(|bandwidth| (bandwidth, Control::new(Policy::new(encoder_config.resolved_bitrate()))));
374
375 loop {
376 // While watched, race the next frame against the last viewer leaving so
377 // we release the camera promptly when demand drops. `biased` checks
378 // demand first so an unwatched track stops before reading another frame.
379 let frame = if catalog_ready {
380 tokio::select! {
381 biased;
382 res = demand.unused() => {
383 if let Err(err) = res {
384 log_track_ended(err);
385 return Ok(());
386 }
387 break; // no viewers: release the camera, then wait for one
388 }
389 // Retune between frames rather than mid-encode, and only when
390 // the policy says the target actually moved.
391 estimate = next_estimate(&mut rate) => {
392 apply_estimate(&mut encoder, &mut rate, estimate).await;
393 continue;
394 }
395 frame = camera.read() => frame,
396 }
397 } else {
398 camera.read().await
399 };
400
401 let Some(surface) = frame else { break }; // device stopped producing frames
402
403 // Stamp at capture, so a backend that buffers still publishes each
404 // access unit at the time the picture was grabbed.
405 let frame = Frame::new(surface, Timestamp::from_micros(clock.micros())?);
406 let encoded = encoder.encode(frame, force_keyframe).await?;
407 force_keyframe = false;
408 // Once the encoder emits a frame the importer has parsed the SPS and
409 // the catalog rendition exists, so demand gating can take over.
410 catalog_ready |= !encoded.is_empty();
411 producer.publish(&encoded)?;
412 }
413
414 // Drop the camera (LED off) and encoder before waiting for the next viewer.
415 drop(camera);
416 if catalog_ready {
417 tracing::info!("no viewers: released camera");
418 }
419 }
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425 use crate::encode::{Config, Encoder};
426
427 /// Encode a handful of synthetic frames for `codec` and publish them through a
428 /// real [`Producer`], returning the catalog rendition's track name. The
429 /// rendition only appears once the matching importer parses the codec config
430 /// out of the encoded keyframe, so a returned name proves the whole
431 /// encode -> split -> import -> catalog path works for that codec.
432 ///
433 /// `kind` is explicit so the test picks a deterministic encoder rather than
434 /// `Auto`, which on Linux CI would try the NVENC backend and panic in cudarc
435 /// on a GPU-less runner.
436 async fn roundtrip_rendition(codec: Codec, kind: encoder::Kind) -> String {
437 let mut broadcast = moq_net::broadcast::Info::new().produce();
438 let catalog = moq_mux::catalog::Producer::new(&mut broadcast).unwrap();
439 let mut producer = Producer::new(broadcast, catalog.clone(), codec).unwrap();
440
441 let mut config = Config::new(320, 240, 30);
442 config.codec = codec;
443 config.kind = kind;
444 let mut encoder = Encoder::new(&config).unwrap();
445 assert_eq!(encoder.codec(), codec);
446
447 let rgba = vec![0x80u8; 320 * 240 * 4];
448 for i in 0..10u64 {
449 let surface = crate::Surface::rgba(&rgba, crate::Size::new(320, 240)).unwrap();
450 let frame = Frame::new(surface, Timestamp::from_micros(i * 33_333).unwrap());
451 producer.publish(&encoder.encode(&frame).unwrap()).unwrap();
452 }
453 producer.publish(&encoder.finish().unwrap()).unwrap();
454
455 let snapshot = catalog.snapshot();
456 snapshot
457 .video
458 .renditions
459 .keys()
460 .next()
461 .cloned()
462 .expect("the importer should have registered a video rendition")
463 }
464
465 #[tokio::test]
466 async fn h264_roundtrip_publishes_avc3() {
467 // Software (openh264) so the test is deterministic and never touches a
468 // hardware backend.
469 assert!(
470 roundtrip_rendition(Codec::H264, encoder::Kind::Software)
471 .await
472 .ends_with(".avc3")
473 );
474 }
475
476 /// H.265 has no software encoder, so this only runs where a hardware one
477 /// exists (VideoToolbox on macOS, the only hardware backend on this target).
478 #[cfg(target_os = "macos")]
479 #[tokio::test]
480 async fn h265_roundtrip_publishes_hev1() {
481 assert!(
482 roundtrip_rendition(Codec::H265, encoder::Kind::Hardware)
483 .await
484 .ends_with(".hev1")
485 );
486 }
487}