1use 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
29pub struct Sink(Inner);
57
58impl Sink {
59 pub async fn open(catalog: &VideoConfig, config: &Config) -> Result<Self, Error> {
63 Ok(Self(Inner::open(catalog, config).await?))
64 }
65
66 pub fn name(&self) -> &str {
68 self.0.name()
69 }
70
71 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 pub fn receive(&mut self) -> Result<Option<Frame>, Error> {
86 self.0.receive()
87 }
88
89 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 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 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 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 !ready.ok(decoder.name().to_owned()) {
147 return;
148 }
149
150 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 let flushed = decoder.flush();
169 let collected = collect(&mut decoder, &queue);
170 let _ = resp.send(flushed.and(collected));
171 }
172 }
173 }
174 }
176
177 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 pub struct Inner(Decoder);
232
233 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 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#[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 #[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 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 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 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}