Skip to main content

moq_video/encode/
sink.rs

1//! An [`Encoder`](super::Encoder) that owns the thread it runs on, so any
2//! thread (or task) can drive it.
3//!
4//! Off macOS and iOS the encoder runs on a dedicated OS thread (mirroring the capture
5//! pump): the Windows hardware encoder is a Media
6//! Foundation MFT whose COM handles must be created, driven, and dropped all on
7//! one thread (COM apartments are per-thread), and whose encode call blocks on
8//! MFT events. Driving it inline on a tokio worker would unbalance the
9//! per-thread COM refcount as the future migrates between workers and park a
10//! worker on a stalled MFT. A synchronous caller has the same problem for the
11//! same reason: an FFI object shared between threads opens the apartment on
12//! whichever thread built it and closes it on whichever thread drops it.
13//! Confining the whole encoder lifetime to one thread fixes both; frames are
14//! `Send` there (Windows D3D11 textures and CPU I420 both are), and the thread
15//! moves the packets each call readies into a queue the caller pops.
16//!
17//! macOS and iOS keep encoding inline: VideoToolbox has no COM apartment to balance and
18//! doesn't block on an event loop, so a thread would only add a hop, and its
19//! zero-copy `CVPixelBuffer` surface is `!Send` and couldn't cross to one anyway.
20
21use std::sync::Arc;
22
23use super::Encoded;
24use super::encoder::{Applied, Config};
25use crate::{Error, Frame};
26
27#[cfg(apple)]
28use inline::Inner;
29#[cfg(not(apple))]
30use threaded::Inner;
31
32/// An [`Encoder`](super::Encoder) confined to one thread, driven from anywhere.
33///
34/// Same shape as [`Encoder`](super::Encoder), one method at a time, except that
35/// the calls that reach the codec are `async` and [`encode`](Self::encode) takes
36/// the frame by value (it may cross a thread). [`receive`](Self::receive) stays
37/// synchronous: each `encode` and `flush` has already moved what the codec
38/// readied to this side. Reach for this instead of an `Encoder` whenever the
39/// encoder outlives a single thread's stack: an object shared across threads, an
40/// FFI handle, a task that migrates between executor workers. An `Encoder` you
41/// build, drive, and drop inside one function needs none of it.
42///
43/// Awaiting rather than blocking is the point: the codec runs on its own thread,
44/// so the executor keeps its worker while a slow hardware encoder works through
45/// a frame. A caller with no executor to yield to (an FFI boundary that must
46/// return a result synchronously) blocks on these futures itself.
47///
48/// # Cancellation
49///
50/// These futures are not cancel-safe, and the sink says so rather than letting
51/// it slide. The codec runs on its own thread, so a request that has been queued
52/// runs whether or not anyone is still waiting: dropping the future (racing it in
53/// a `select!`, giving it a timeout) leaves the codec a step ahead of the stream,
54/// holding output nobody collected. Rather than let the next call carry on and
55/// publish a track quietly missing those frames, the sink refuses every call
56/// after a cancelled one. Drop it and open another.
57///
58/// Racing an encode against a shutdown signal is fine, since the sink is on its
59/// way out anyway. What does not work is cancelling one and carrying on.
60///
61/// Apple platforms never refuse, because there is no thread to run ahead: the encoder
62/// runs inline, so a dropped future either had not started the call or had
63/// already finished it. Write to the contract above regardless, or the same code
64/// loses frames elsewhere.
65pub struct Sink(Inner);
66
67impl Sink {
68	/// Open an encoder for `config` on its own thread. Returns once the encoder
69	/// is built (or its construction fails), so a bad config or a missing backend
70	/// surfaces here rather than on the first frame.
71	pub async fn open(config: &Config) -> Result<Self, Error> {
72		Ok(Self(Inner::open(config).await?))
73	}
74
75	/// The encoder name in use, e.g. `"mediafoundation"`.
76	pub fn name(&self) -> &str {
77		self.0.name()
78	}
79
80	/// The latency and compression controls the backend applied, like the
81	/// encoder's own report.
82	pub fn applied(&self) -> Applied {
83		self.0.applied()
84	}
85
86	/// Cut a new group at the next frame, like
87	/// [`Encoder::cut`](super::Encoder::cut).
88	///
89	/// Queued behind the frames already in flight rather than applied to
90	/// whichever one the codec happens to be on, so it opens the group at the
91	/// next frame you pass to [`encode`](Self::encode). Awaited for the
92	/// backend's verdict: a backend that cannot cut refuses here with
93	/// [`Error::CutUnsupported`](crate::Error::CutUnsupported), the same answer
94	/// the direct encoder gives, rather than queueing a request it will ignore.
95	pub async fn cut(&mut self) -> Result<(), Error> {
96		self.0.cut().await
97	}
98
99	/// Submit one frame, waiting until the codec has taken it.
100	///
101	/// Otherwise [`Encoder::encode`](super::Encoder::encode): its access units come
102	/// out of [`receive`](Self::receive), each stamped with the frame it came from.
103	///
104	/// One call at a time, so the sink never queues raw frames of its own: the
105	/// only pictures in flight are the one being encoded and whatever the codec
106	/// pipelines (none on NVENC or openh264). A source that outruns the codec
107	/// should drop the raw frames it has not submitted yet, never encoded
108	/// packets, which later frames depend on.
109	///
110	/// Takes ownership, since the frame may be moved to the encode thread, but
111	/// takes it as anything that can become an [`Arc`] so a caller fanning one
112	/// frame out to several encoders (a transcode ladder) hands over a clone of
113	/// the handle rather than a copy of the pixels. Pass a [`Frame`] and it is
114	/// wrapped for you.
115	pub async fn encode(&mut self, frame: impl Into<Arc<Frame>>) -> Result<(), Error> {
116		self.0.encode(frame.into()).await
117	}
118
119	/// Pop the oldest ready access unit, or `None` while the codec holds the rest.
120	///
121	/// Call until it returns `None` after each [`encode`](Self::encode) and
122	/// [`flush`](Self::flush).
123	pub fn receive(&mut self) -> Result<Option<Encoded>, Error> {
124		self.0.receive()
125	}
126
127	/// Retune the encoder, waiting for the backend's verdict.
128	///
129	/// A refused rate, such as [`Error::BitrateUnsupported`], is not fatal: the encoder keeps
130	/// its rate and keeps encoding (see [`Encoder::set_bitrate`](super::Encoder::set_bitrate)).
131	/// [`Error::CodecGone`] means the encode thread stopped, so the sink cannot continue.
132	pub async fn set_bitrate(&mut self, bitrate: moq_net::bandwidth::Rate) -> Result<(), Error> {
133		self.0.set_bitrate(bitrate).await
134	}
135
136	/// Mark the end of input, so [`receive`](Self::receive) returns every access
137	/// unit the codec still holds, leaving it ready for the frames that follow.
138	/// See [`Encoder::flush`](super::Encoder::flush).
139	///
140	/// A live track needs this at every group boundary: a backend that pipelines
141	/// is still holding the last frames of a group when it ends, and they would
142	/// otherwise surface in the next group ahead of its keyframe, where a
143	/// subscriber joining there cannot decode them. Publishing frame by frame
144	/// with no group structure needs none of it.
145	///
146	/// Flush and receive before dropping the sink, or its last pictures never
147	/// reach a subscriber.
148	pub async fn flush(&mut self) -> Result<(), Error> {
149		self.0.flush().await
150	}
151}
152
153#[cfg(not(apple))]
154mod threaded {
155	use std::sync::Arc;
156
157	use tokio::sync::{mpsc, oneshot};
158
159	use super::super::Encoded;
160	use super::super::encoder::{Applied, Config, Encoder};
161	use crate::worker::{Queue, Ready, Worker};
162	use crate::{Error, Frame};
163
164	/// Work for the encode thread. Every variant goes down the same channel so a
165	/// cut or a bitrate change lands in order with the frames around it, rather
166	/// than racing them.
167	enum Request {
168		/// A frame to encode, plus a oneshot to report, in order, whether the codec
169		/// took it.
170		Encode {
171			frame: Arc<Frame>,
172			resp: oneshot::Sender<Result<(), Error>>,
173		},
174		/// Cut a group at the next frame, reporting whether the backend can: a
175		/// refusal has to reach the caller, since the alternative is a group
176		/// boundary that silently never happens.
177		Cut { resp: oneshot::Sender<Result<(), Error>> },
178		/// Retune to a new bitrate, reporting whether the backend took it, so the
179		/// caller's rate control knows the rate it is encoding at. The round trip
180		/// is affordable because the rate control policy only sends one of these
181		/// when the target moves meaningfully, not per frame.
182		SetBitrate {
183			bitrate: moq_net::bandwidth::Rate,
184			resp: oneshot::Sender<Result<(), Error>>,
185		},
186		/// Mark the end of input at a group boundary, leaving the codec running.
187		Flush { resp: oneshot::Sender<Result<(), Error>> },
188	}
189
190	/// What the encode thread reports once its encoder is open.
191	pub struct Opened {
192		name: String,
193		applied: Applied,
194	}
195
196	/// Move everything the encoder has ready into `queue`.
197	fn collect(encoder: &mut Encoder, queue: &Queue<Encoded>) -> Result<(), Error> {
198		let mut queue = queue.lock();
199		while let Some(encoded) = encoder.receive()? {
200			queue.push_back(encoded);
201		}
202		Ok(())
203	}
204
205	/// Build an encoder for `config` and serve requests until the channel closes.
206	/// Runs entirely on the encode thread; see [`crate::worker`].
207	fn run(
208		config: Config,
209		queue: Queue<Encoded>,
210		ready: Ready<Opened>,
211		mut requests: mpsc::UnboundedReceiver<Request>,
212	) {
213		let mut encoder = match Encoder::new(&config) {
214			Ok(encoder) => encoder,
215			Err(err) => return ready.err(err),
216		};
217		// If the awaiting `open` was cancelled, give up before encoding.
218		let opened = Opened {
219			name: encoder.name().to_owned(),
220			applied: encoder.applied(),
221		};
222		if !ready.ok(opened) {
223			return;
224		}
225
226		// Serve each request in arrival order. The encoder and its COM / MFT
227		// handles are created, used, and dropped only on this thread, which the
228		// encoder drops on once the channel closes.
229		while let Some(req) = requests.blocking_recv() {
230			match req {
231				Request::Encode { frame, resp } => {
232					let encoded = encoder.encode(&frame).and_then(|()| collect(&mut encoder, &queue));
233					let _ = resp.send(encoded);
234				}
235				Request::Cut { resp } => {
236					let _ = resp.send(encoder.cut());
237				}
238				Request::SetBitrate { bitrate, resp } => {
239					let _ = resp.send(encoder.set_bitrate(bitrate));
240				}
241				Request::Flush { resp } => {
242					let flushed = encoder.flush().and_then(|()| collect(&mut encoder, &queue));
243					let _ = resp.send(flushed);
244				}
245			}
246		}
247	}
248
249	/// An [`Encoder`] running on its own thread. See the module docs.
250	pub struct Inner {
251		worker: Worker<Request, Opened>,
252		queue: Queue<Encoded>,
253	}
254
255	impl Inner {
256		pub async fn open(config: &Config) -> Result<Self, Error> {
257			let config = config.clone();
258			let queue = Queue::default();
259			let filled = queue.clone();
260			let worker = Worker::open("moq-video-encode", move |ready, requests| {
261				run(config, filled, ready, requests)
262			})
263			.await?;
264			Ok(Self { worker, queue })
265		}
266
267		pub fn name(&self) -> &str {
268			&self.worker.info().name
269		}
270
271		pub fn applied(&self) -> Applied {
272			self.worker.info().applied.clone()
273		}
274
275		pub async fn cut(&mut self) -> Result<(), Error> {
276			self.worker.request(|resp| Request::Cut { resp }).await
277		}
278
279		pub async fn encode(&mut self, frame: Arc<Frame>) -> Result<(), Error> {
280			self.worker.request(|resp| Request::Encode { frame, resp }).await
281		}
282
283		pub fn receive(&mut self) -> Result<Option<Encoded>, Error> {
284			Ok(self.queue.pop())
285		}
286
287		pub async fn set_bitrate(&mut self, bitrate: moq_net::bandwidth::Rate) -> Result<(), Error> {
288			self.worker.request(|resp| Request::SetBitrate { bitrate, resp }).await
289		}
290
291		pub async fn flush(&mut self) -> Result<(), Error> {
292			self.worker.request(|resp| Request::Flush { resp }).await
293		}
294	}
295}
296
297#[cfg(apple)]
298mod inline {
299	use std::sync::Arc;
300
301	use super::super::Encoded;
302	use super::super::encoder::{Applied, Config, Encoder};
303	use crate::{Error, Frame};
304
305	/// An [`Encoder`] driven inline on the calling thread (see the module docs).
306	pub struct Inner(Encoder);
307
308	// SAFETY: VideoToolbox and Core Foundation handles may move between threads
309	// when calls remain serialized. `Sink` provides that serialization; the
310	// synchronous `Encoder` remains thread-bound.
311	unsafe impl Send for Inner {}
312
313	impl Inner {
314		pub async fn open(config: &Config) -> Result<Self, Error> {
315			Ok(Self(Encoder::new(config)?))
316		}
317
318		pub fn name(&self) -> &str {
319			self.0.name()
320		}
321
322		pub fn applied(&self) -> Applied {
323			self.0.applied()
324		}
325
326		/// Async only to match the threaded `Inner`; there's no thread to hand this
327		/// to, so it runs inline. The same holds for the calls below.
328		pub async fn cut(&mut self) -> Result<(), Error> {
329			self.0.cut()
330		}
331
332		pub async fn encode(&mut self, frame: Arc<Frame>) -> Result<(), Error> {
333			self.0.encode(&frame)
334		}
335
336		pub fn receive(&mut self) -> Result<Option<Encoded>, Error> {
337			self.0.receive()
338		}
339
340		pub async fn set_bitrate(&mut self, bitrate: moq_net::bandwidth::Rate) -> Result<(), Error> {
341			self.0.set_bitrate(bitrate)
342		}
343
344		pub async fn flush(&mut self) -> Result<(), Error> {
345			self.0.flush()
346		}
347	}
348}
349
350#[cfg(test)]
351mod tests {
352	#[cfg(not(apple))]
353	use std::collections::HashSet;
354	#[cfg(not(apple))]
355	use std::sync::{Arc, Mutex};
356	#[cfg(not(apple))]
357	use std::thread::ThreadId;
358
359	use super::super::backend::probe;
360	use super::super::{Backend, Codec};
361	use super::*;
362	use crate::{I420, Surface};
363
364	/// A mid-gray frame at the probe backend's resolution, stamped as the
365	/// `index`th frame of a 30fps stream.
366	fn gray(index: u64) -> Frame {
367		let size = crate::Size::new(320, 240);
368		let i420 = I420::new(size, vec![0x80u8; I420::len(size).unwrap()]).unwrap();
369		Frame::new(
370			moq_net::Timestamp::from_micros(index * 33_333).unwrap(),
371			Surface::I420(i420),
372		)
373	}
374
375	fn probe_config() -> Config {
376		let mut config = Config::new(320, 240, crate::FrameRate::new(30, 1).unwrap());
377		config.codec = Codec::H264;
378		config.backend = Backend::Named(probe::NAME.into());
379		config
380	}
381
382	/// The sink and the direct encoder answer a cut the same way: queued for the
383	/// next frame on a backend that can, and that frame is the one the codec
384	/// sees it on rather than whichever it was busy with.
385	#[test]
386	fn a_cut_lands_on_the_next_frame() {
387		let _probe = probe::exclusive();
388
389		let mut sink = pollster::block_on(Sink::open(&probe_config())).unwrap();
390		pollster::block_on(sink.encode(gray(0))).unwrap();
391		pollster::block_on(sink.cut()).unwrap();
392		pollster::block_on(sink.encode(gray(1))).unwrap();
393		pollster::block_on(sink.encode(gray(2))).unwrap();
394		drop(sink);
395
396		let events: Vec<_> = probe::take()
397			.into_iter()
398			.map(|(event, _)| event)
399			.filter(|event| matches!(*event, "encode" | "cut"))
400			.collect();
401		assert_eq!(events, vec!["encode", "encode", "cut", "encode"]);
402	}
403
404	/// A backend that cannot cut refuses through the sink exactly as it does
405	/// directly, and the sink stays usable: the refusal is the caller's to act
406	/// on, not a poisoned session.
407	#[test]
408	fn a_backend_that_cannot_cut_refuses_through_the_sink() {
409		let _probe = probe::exclusive();
410
411		let mut config = probe_config();
412		config.backend = Backend::Named(probe::NO_CUT.into());
413		let mut sink = pollster::block_on(Sink::open(&config)).unwrap();
414		assert_eq!(sink.name(), probe::NO_CUT);
415		assert!(!sink.applied().cut, "the report says it cannot cut");
416
417		let err = pollster::block_on(sink.cut()).expect_err("the backend cannot cut");
418		assert!(
419			matches!(err, Error::CutUnsupported(name) if name == probe::NO_CUT),
420			"unexpected error: {err:?}"
421		);
422
423		pollster::block_on(sink.encode(gray(0))).unwrap();
424		drop(sink);
425		let log = probe::take();
426		assert!(
427			!log.iter().any(|(event, _)| *event == "cut"),
428			"a refused cut still reached the codec: {log:?}"
429		);
430	}
431
432	/// Regression: a queued request runs on the encode thread whether or not the
433	/// caller is still waiting, so a cancelled `encode` leaves the codec a step
434	/// ahead of the stream with output nobody received. Carrying on would publish
435	/// a track quietly missing those frames, which is worse than an error: only
436	/// the publisher could ever tell, and only by decoding its own output.
437	///
438	/// Apple platforms are exempt by design: the inline sink encodes on the calling thread,
439	/// so there is nothing to run ahead (see the module docs).
440	#[cfg(not(apple))]
441	#[test]
442	fn a_cancelled_call_poisons_the_sink() {
443		let _probe = probe::exclusive();
444
445		let mut sink = pollster::block_on(Sink::open(&probe_config())).unwrap();
446
447		// Cancel an encode the moment it starts waiting, the shape a `select!` or a
448		// timeout produces. Holding the codec inside the call is what makes the
449		// cancel land mid-flight rather than race the encode thread for it.
450		let gate = probe::hold();
451		pollster::block_on(async {
452			let mut encode = Box::pin(sink.encode(gray(0)));
453			assert!(
454				futures::poll!(encode.as_mut()).is_pending(),
455				"the encode should still be waiting on the held codec"
456			);
457			// Dropped here, with the request queued and the reply still to come.
458		});
459		drop(gate);
460
461		// The codec really did run, so the stream is missing whatever came back.
462		let err = pollster::block_on(sink.encode(gray(1))).expect_err("the sink should refuse");
463		assert!(err.to_string().contains("cancelled"), "unexpected error: {err}");
464		// ...and it stays refused rather than recovering on the call after.
465		assert!(pollster::block_on(sink.flush()).is_err());
466
467		drop(sink);
468		let log = probe::take();
469		assert!(
470			log.iter().any(|(event, _)| *event == "encode"),
471			"the cancelled request should still have reached the codec: {log:?}"
472		);
473	}
474
475	/// Regression: the Windows backend opens a COM apartment on the thread that
476	/// builds the codec and closes it on the thread that drops it, so a codec
477	/// reachable from more than one thread has to own a thread of its own. Both
478	/// FFI bindings held a bare `Encoder` and drove it from whichever thread
479	/// called in, which leaked the opening thread's initialization and ran
480	/// `CoUninitialize` on a thread that never initialized COM.
481	///
482	/// Asserted on every platform rather than only Windows: the confinement is
483	/// what the bindings now rely on, so it should fail here rather than on a
484	/// machine none of CI has. Apple platforms are exempt by design: the inline sink has
485	/// no thread of its own to confine anything to.
486	#[cfg(not(apple))]
487	#[test]
488	fn the_codec_stays_on_one_thread_however_it_is_driven() {
489		let _probe = probe::exclusive();
490
491		let sink = Arc::new(Mutex::new(Some(
492			pollster::block_on(Sink::open(&probe_config())).unwrap(),
493		)));
494
495		// Drive it the way an FFI handle gets driven: a fresh caller thread every
496		// time, none of them the thread that opened it.
497		let mut callers = vec![std::thread::current().id()];
498		let mut received = Vec::new();
499		for index in 0..3u64 {
500			let sink = sink.clone();
501			let caller = std::thread::spawn(move || {
502				let mut guard = sink.lock().unwrap();
503				let sink = guard.as_mut().unwrap();
504				pollster::block_on(sink.cut()).unwrap();
505				pollster::block_on(sink.encode(gray(index))).unwrap();
506				pollster::block_on(sink.set_bitrate(moq_net::bandwidth::Rate::from_bps(500_000 + index))).unwrap();
507				// Only the first frame closes a group, so the two after it stay in
508				// the codec and leave the drain below something to find.
509				if index == 0 {
510					pollster::block_on(sink.flush()).unwrap();
511				}
512				let mut received = Vec::new();
513				while let Some(frame) = sink.receive().unwrap() {
514					received.push(frame.timestamp.as_micros().unwrap());
515				}
516				(std::thread::current().id(), received)
517			});
518			let (caller, frames) = caller.join().unwrap();
519			callers.push(caller);
520			received.extend(frames);
521		}
522
523		// The probe holds each frame back by one, so a flush that reached the codec
524		// hands back the frame the group ended on, ahead of frame 1, which frame 2
525		// pushed out. An inherited no-op would leave frame 0 to surface after the
526		// boundary, in the next group.
527		assert_eq!(received, vec![0, 33_333], "the group boundary did not empty the codec");
528
529		// ...and drained, then dropped, from yet another.
530		let closer = std::thread::spawn(move || {
531			let mut sink = sink.lock().unwrap().take().unwrap();
532			pollster::block_on(sink.flush()).unwrap();
533			let mut tail = Vec::new();
534			while let Some(frame) = sink.receive().unwrap() {
535				tail.push(frame.timestamp.as_micros().unwrap());
536			}
537			drop(sink);
538			(std::thread::current().id(), tail)
539		});
540		let (closer, tail) = closer.join().unwrap();
541		callers.push(closer);
542
543		// Frame 2 never came back from an encode call and no flush claimed it, so
544		// the drain has to. Dropping the sink instead would lose it silently.
545		assert_eq!(tail, vec![2 * 33_333], "the drain lost the codec's tail");
546
547		let log = probe::take();
548		for what in ["open", "encode", "set_bitrate", "flush", "drop"] {
549			assert!(log.iter().any(|(event, _)| *event == what), "no {what} in {log:?}");
550		}
551
552		let threads: HashSet<ThreadId> = log.iter().map(|(_, id)| *id).collect();
553		assert_eq!(threads.len(), 1, "the codec ran on more than one thread: {log:?}");
554
555		let codec = threads.into_iter().next().unwrap();
556		assert!(
557			!callers.contains(&codec),
558			"the codec ran on a caller's thread rather than its own: {log:?}"
559		);
560	}
561}