Skip to main content

moq_video/decode/
sink.rs

1//! A [`Decoder`](super::Decoder) that owns the thread it runs on, so any thread
2//! (or task) can drive it.
3//!
4//! The decode-side mirror of [`encode::Sink`](crate::encode::Sink), for the same
5//! reason: the Windows backend is a Media Foundation transform whose COM handles
6//! must be created, driven, and dropped all on one thread (COM apartments are
7//! per-thread). Backends are `!Send` and the synchronous `Decoder` inherits it;
8//! confinement is enforced by that plus the `Worker` below, which keeps the
9//! whole codec lifetime on one thread. A decoder held across `.await` in a
10//! plain task does not keep it: the future migrates between executor workers,
11//! so the apartment is opened on one and closed on another.
12//!
13//! macOS and iOS keep decoding inline: VideoToolbox has no COM apartment to balance, so
14//! a thread would only add a hop, and its zero-copy `CVPixelBuffer` surface is
15//! `!Send` and could not cross to one anyway.
16
17use bytes::Bytes;
18use hang::catalog::VideoConfig;
19use moq_net::Timestamp;
20
21use super::decoder::Config;
22use crate::{Error, Frame};
23
24#[cfg(apple)]
25use inline::Inner;
26#[cfg(not(apple))]
27use threaded::Inner;
28
29/// A [`Decoder`](super::Decoder) confined to one thread, driven from anywhere.
30///
31/// Same shape as [`Decoder`](super::Decoder), except that
32/// [`decode`](Self::decode) and [`flush`](Self::flush) are `async` and `decode`
33/// takes its payload by value (it may cross a thread). [`receive`](Self::receive)
34/// stays synchronous: each `decode` and `flush` has already moved what the codec
35/// readied to this side. Reach for this instead of a `Decoder` whenever the decoder
36/// outlives a single thread's stack: a spawned task, an object shared across
37/// threads, an FFI handle. A `Decoder` you build, drive, and drop inside one
38/// function needs none of it.
39///
40/// [`Consumer`](super::Consumer) is built on one, so a caller reading a
41/// subscribed track from a task already gets this and needs nothing here.
42///
43/// # Cancellation
44///
45/// Not cancel-safe, and it says so rather than letting it slide. A queued request
46/// runs whether or not anyone is still waiting, so dropping the future (racing it
47/// in a `select!`, giving it a timeout) can leave the decoder a step ahead of the
48/// caller. Rather than let the next call carry on against a decoder that has moved,
49/// the sink refuses every call after a
50/// cancelled one. Drop it and open another.
51///
52/// Apple platforms never refuse, because there is no thread to run ahead: the decoder runs
53/// inline, so a dropped future either had not started the call or had already
54/// finished it. Write to the contract above regardless, or the same code loses
55/// frames elsewhere.
56pub struct Sink(Inner);
57
58impl Sink {
59	/// Open a decoder for `catalog` on its own thread. Returns once the decoder
60	/// is built (or its construction fails), so an unsupported codec surfaces
61	/// here rather than on the first frame.
62	pub async fn open(catalog: &VideoConfig, config: &Config) -> Result<Self, Error> {
63		Ok(Self(Inner::open(catalog, config).await?))
64	}
65
66	/// The decoder name in use, e.g. `"mediafoundation"`.
67	pub fn name(&self) -> &str {
68		self.0.name()
69	}
70
71	/// Submit one access unit, waiting until the codec has taken it.
72	///
73	/// Otherwise [`Decoder::decode`](super::Decoder::decode): its pictures come out
74	/// of [`receive`](Self::receive), zero or more of them, since a backend that
75	/// reorders holds pictures back. `payload` is a [`Bytes`], so handing it over
76	/// is a refcount rather than a copy.
77	pub async fn decode(&mut self, payload: Bytes, timestamp: Timestamp, keyframe: bool) -> Result<(), Error> {
78		self.0.decode(payload, timestamp, keyframe).await
79	}
80
81	/// Pop the oldest ready frame, or `None` while the decoder holds the rest.
82	///
83	/// Call until it returns `None` after each [`decode`](Self::decode) and
84	/// [`flush`](Self::flush).
85	pub fn receive(&mut self) -> Result<Option<Frame>, Error> {
86		self.0.receive()
87	}
88
89	/// Mark the end of input, so [`receive`](Self::receive) returns the frames the
90	/// decoder still holds once the stream has ended.
91	///
92	/// Otherwise [`Decoder::flush`](super::Decoder::flush), confined to the codec
93	/// thread like [`decode`](Self::decode).
94	pub async fn flush(&mut self) -> Result<(), Error> {
95		self.0.flush().await
96	}
97}
98
99#[cfg(not(apple))]
100mod threaded {
101	use bytes::Bytes;
102	use hang::catalog::VideoConfig;
103	use moq_net::Timestamp;
104	use tokio::sync::{mpsc, oneshot};
105
106	use super::super::decoder::{Config, Decoder};
107	use crate::worker::{Queue, Ready, Worker};
108	use crate::{Error, Frame};
109
110	/// Work for the decode thread, in order with the frames around it.
111	enum Request {
112		Decode {
113			payload: Bytes,
114			timestamp: Timestamp,
115			keyframe: bool,
116			resp: oneshot::Sender<Result<(), Error>>,
117		},
118		Flush {
119			resp: oneshot::Sender<Result<(), Error>>,
120		},
121	}
122
123	/// Move everything the decoder has ready into `queue`.
124	fn collect(decoder: &mut Decoder, queue: &Queue<Frame>) -> Result<(), Error> {
125		let mut queue = queue.lock();
126		while let Some(frame) = decoder.receive()? {
127			queue.push_back(frame);
128		}
129		Ok(())
130	}
131
132	/// Build a decoder and serve requests until the channel closes. Runs entirely
133	/// on the decode thread; see [`crate::worker`].
134	fn run(
135		catalog: VideoConfig,
136		config: Config,
137		queue: Queue<Frame>,
138		ready: Ready<String>,
139		mut requests: mpsc::UnboundedReceiver<Request>,
140	) {
141		let mut decoder = match Decoder::new(&catalog, &config) {
142			Ok(decoder) => decoder,
143			Err(err) => return ready.err(err),
144		};
145		// If the awaiting `open` was cancelled, give up before decoding.
146		if !ready.ok(decoder.name().to_owned()) {
147			return;
148		}
149
150		// Serve each request in arrival order. The decoder and its COM / MFT
151		// handles are created, used, and dropped only on this thread.
152		while let Some(req) = requests.blocking_recv() {
153			match req {
154				Request::Decode {
155					payload,
156					timestamp,
157					keyframe,
158					resp,
159				} => {
160					let decoded = decoder
161						.decode(&payload, timestamp, keyframe)
162						.and_then(|()| collect(&mut decoder, &queue));
163					let _ = resp.send(decoded);
164				}
165				Request::Flush { resp } => {
166					// Collected even when the flush failed, so the pictures it readied come out
167					// ahead of whatever the caller queues behind the drain.
168					let flushed = decoder.flush();
169					let collected = collect(&mut decoder, &queue);
170					let _ = resp.send(flushed.and(collected));
171				}
172			}
173		}
174		// `decoder` drops here, on this thread, balancing the COM apartment.
175	}
176
177	/// A [`Decoder`] running on its own thread. See the module docs.
178	pub struct Inner {
179		worker: Worker<Request, String>,
180		queue: Queue<Frame>,
181	}
182
183	impl Inner {
184		pub async fn open(catalog: &VideoConfig, config: &Config) -> Result<Self, Error> {
185			let catalog = catalog.clone();
186			let config = config.clone();
187			let queue = Queue::default();
188			let filled = queue.clone();
189			let worker = Worker::open("moq-video-decode", move |ready, requests| {
190				run(catalog, config, filled, ready, requests)
191			})
192			.await?;
193			Ok(Self { worker, queue })
194		}
195
196		pub fn name(&self) -> &str {
197			self.worker.info()
198		}
199
200		pub async fn decode(&mut self, payload: Bytes, timestamp: Timestamp, keyframe: bool) -> Result<(), Error> {
201			self.worker
202				.request(|resp| Request::Decode {
203					payload,
204					timestamp,
205					keyframe,
206					resp,
207				})
208				.await
209		}
210
211		pub fn receive(&mut self) -> Result<Option<Frame>, Error> {
212			Ok(self.queue.pop())
213		}
214
215		pub async fn flush(&mut self) -> Result<(), Error> {
216			self.worker.request(|resp| Request::Flush { resp }).await
217		}
218	}
219}
220
221#[cfg(apple)]
222mod inline {
223	use bytes::Bytes;
224	use hang::catalog::VideoConfig;
225	use moq_net::Timestamp;
226
227	use super::super::decoder::{Config, Decoder};
228	use crate::{Error, Frame};
229
230	/// A [`Decoder`] driven inline on the calling thread (see the module docs).
231	pub struct Inner(Decoder);
232
233	// SAFETY: VideoToolbox and Core Foundation handles may move between threads
234	// when calls remain serialized. `Sink` provides that serialization; the
235	// synchronous `Decoder` remains thread-bound.
236	unsafe impl Send for Inner {}
237
238	impl Inner {
239		pub async fn open(catalog: &VideoConfig, config: &Config) -> Result<Self, Error> {
240			Ok(Self(Decoder::new(catalog, config)?))
241		}
242
243		pub fn name(&self) -> &str {
244			self.0.name()
245		}
246
247		/// Async only to match the threaded `Inner`; there's no thread to hand
248		/// this to, so it decodes inline.
249		pub async fn decode(&mut self, payload: Bytes, timestamp: Timestamp, keyframe: bool) -> Result<(), Error> {
250			self.0.decode(&payload, timestamp, keyframe)
251		}
252
253		pub fn receive(&mut self) -> Result<Option<Frame>, Error> {
254			self.0.receive()
255		}
256
257		pub async fn flush(&mut self) -> Result<(), Error> {
258			self.0.flush()
259		}
260	}
261}
262
263/// Apple platforms are exempt by design: the inline sink decodes on the calling thread, so
264/// there is no confinement to assert (see the module docs).
265#[cfg(all(test, not(apple)))]
266mod tests {
267	use std::collections::HashSet;
268	use std::sync::{Arc, Mutex};
269	use std::thread::ThreadId;
270
271	use super::super::Backend;
272	use super::super::backend::probe;
273	use super::*;
274
275	fn probe_catalog() -> VideoConfig {
276		let mut catalog = VideoConfig::new(hang::catalog::H264 {
277			inline: true,
278			profile: 0x42,
279			constraints: 0,
280			level: 30,
281		});
282		catalog.coded_width = Some(probe::SIZE.width);
283		catalog.coded_height = Some(probe::SIZE.height);
284		catalog
285	}
286
287	fn probe_config() -> Config {
288		let mut config = Config::new();
289		config.backend = Backend::Named(probe::NAME.into());
290		config
291	}
292
293	fn at(index: u64) -> Timestamp {
294		Timestamp::from_micros(index * 33_333).unwrap()
295	}
296
297	/// Regression: the Windows decoder opens a COM apartment on the thread that
298	/// builds it and closes it on the thread that drops it. Every owner holds the
299	/// codec across `.await` in a spawned task (`decode::Consumer`'s read loop,
300	/// which libmoq drives; moq-transcode's feed and fetch pipeline), so the
301	/// future migrates between executor workers and the apartment is opened on
302	/// one and closed on another.
303	#[test]
304	fn the_codec_stays_on_one_thread_however_it_is_driven() {
305		let _probe = probe::exclusive();
306
307		let sink = Arc::new(Mutex::new(Some(
308			pollster::block_on(Sink::open(&probe_catalog(), &probe_config())).unwrap(),
309		)));
310
311		// Drive it the way a migrating task does: a fresh caller thread every
312		// time, none of them the one that opened it.
313		let mut callers = vec![std::thread::current().id()];
314		for index in 0..3u64 {
315			let sink = sink.clone();
316			let caller = std::thread::spawn(move || {
317				let mut guard = sink.lock().unwrap();
318				let sink = guard.as_mut().unwrap();
319				pollster::block_on(sink.decode(Bytes::from_static(b"au"), at(index), index == 0)).unwrap();
320				// The frame really came back, so the assertions below are about a
321				// decoder that ran rather than one that no-opped.
322				let frame = sink.receive().unwrap().expect("one frame per access unit");
323				assert!(sink.receive().unwrap().is_none());
324				assert_eq!(frame.timestamp, at(index));
325				std::thread::current().id()
326			});
327			callers.push(caller.join().unwrap());
328		}
329
330		// ...and dropped from yet another.
331		let closer = std::thread::spawn(move || {
332			sink.lock().unwrap().take();
333			std::thread::current().id()
334		});
335		callers.push(closer.join().unwrap());
336
337		let log = probe::take();
338		for what in ["open", "decode", "drop"] {
339			assert!(log.iter().any(|(event, _)| *event == what), "no {what} in {log:?}");
340		}
341
342		let threads: HashSet<ThreadId> = log.iter().map(|(_, id)| *id).collect();
343		assert_eq!(threads.len(), 1, "the codec ran on more than one thread: {log:?}");
344
345		let codec = threads.into_iter().next().unwrap();
346		assert!(
347			!callers.contains(&codec),
348			"the codec ran on a caller's thread rather than its own: {log:?}"
349		);
350	}
351}