1use std::collections::VecDeque;
4use std::pin::Pin;
5use std::task::{Context, Poll};
6
7use hang::catalog::VideoConfig;
8use kio::clock::Instant;
9use moq_mux::container::Read as Encoded;
10
11use super::decoder::Config;
12use super::sink::Sink;
13use crate::Error;
14use crate::Frame;
15pub use moq_mux::container::Delay;
16
17#[non_exhaustive]
24pub enum Read {
25 Frame(Frame),
27 #[non_exhaustive]
32 Gap {
33 timestamp: moq_net::Timestamp,
35 duration: std::time::Duration,
37 },
38 #[non_exhaustive]
43 End {
44 end: moq_net::Timestamp,
46 },
47}
48
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum Start {
61 #[default]
67 Oldest,
68 Latest,
75}
76
77#[derive(Clone, Debug)]
86#[non_exhaustive]
87pub struct Options {
88 pub decoder: Config,
90 pub priority: i8,
94 pub start: Start,
96 pub delay: Delay,
105}
106
107impl Default for Options {
108 fn default() -> Self {
109 Self {
110 decoder: Config::default(),
111 priority: hang::catalog::PRIORITY.video,
112 start: Start::default(),
113 delay: Delay::default(),
114 }
115 }
116}
117
118impl Options {
119 pub fn new() -> Self {
121 Self::default()
122 }
123}
124
125fn stated(options: &Options) -> Delay {
128 let mut delay = options.delay;
129 delay.min = match options.start {
130 Start::Oldest => None,
131 Start::Latest => delay.min.or(Some(std::time::Duration::ZERO)),
132 };
133 delay
134}
135
136pub struct Consumer {
143 slot: Slot,
144 control: Option<moq_net::track::Control>,
147 name: String,
148 arrival: Option<Instant>,
150 options: Options,
151 max_age: Option<std::time::Duration>,
153 retune: kio::Lock<Option<Delay>>,
156}
157
158const ARRIVALS: usize = 32;
167
168enum Slot {
173 Idle(Box<Reader>),
174 Busy(Step),
175}
176
177type Step = Pin<Box<dyn Future<Output = (Box<Reader>, Result<Option<Item>, Error>)> + Send>>;
179
180type Item = (Read, Option<Instant>);
182
183struct Reader {
185 decoder: Sink,
190 track: moq_mux::container::Consumer<moq_mux::catalog::hang::Wire>,
191 pending: VecDeque<Item>,
196 arrivals: VecDeque<(u128, Instant)>,
202 drained: bool,
204 released: bool,
207 recover: bool,
209 leading_floor: Option<moq_net::Timestamp>,
210 retune: kio::Lock<Option<Delay>>,
212}
213
214impl Consumer {
215 pub async fn new(
218 broadcast: &moq_net::broadcast::Consumer,
219 catalog: &VideoConfig,
220 name: impl Into<String>,
221 options: Options,
222 ) -> Result<Self, Error> {
223 let (reader, control, max_age) = Reader::open(broadcast, catalog, &name.into(), &options).await?;
224 let retune = reader.retune.clone();
225 Ok(Self {
226 name: reader.decoder.name().to_owned(),
227 control: Some(control),
228 max_age,
229 slot: Slot::Idle(Box::new(reader)),
230 arrival: None,
231 options,
232 retune,
233 })
234 }
235
236 pub fn name(&self) -> &str {
238 &self.name
239 }
240
241 pub fn options(&self) -> &Options {
244 &self.options
245 }
246
247 pub fn max_delay(&self) -> std::time::Duration {
250 let max = self.options.delay.max.unwrap_or(std::time::Duration::MAX);
251 max.min(self.max_age.unwrap_or(std::time::Duration::MAX))
252 }
253
254 pub fn set_max_delay(&mut self, max: std::time::Duration) {
263 if self.options.start == Start::Oldest && self.options.delay.max.is_none() {
264 return;
265 }
266 self.options.delay = self.options.delay.with_max(max);
267 let delay = stated(&self.options);
268 match &mut self.slot {
269 Slot::Idle(reader) => {
270 *self.retune.lock() = None;
271 reader.track.set_delay(delay);
272 }
273 Slot::Busy(_) => *self.retune.lock() = Some(delay),
274 }
275 }
276
277 pub fn set_priority(&mut self, priority: i8) {
282 let Some(control) = &self.control else {
283 return;
284 };
285 let mut subscription = control.subscription();
286 if subscription.ranges.iter().any(|range| range.priority != priority) {
287 for range in &mut subscription.ranges {
288 range.priority = priority;
289 }
290 let _ = control.update(subscription);
292 }
293 }
294
295 pub fn arrival(&self) -> Option<Instant> {
306 self.arrival
307 }
308
309 pub async fn read(&mut self) -> Result<Option<Read>, Error> {
317 std::future::poll_fn(|cx| self.poll_read(cx)).await
318 }
319
320 fn poll_read(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<Read>, Error>> {
321 if matches!(self.slot, Slot::Idle(_)) {
322 let Slot::Idle(mut reader) =
324 std::mem::replace(&mut self.slot, Slot::Busy(Box::pin(std::future::pending())))
325 else {
326 unreachable!("matched above");
327 };
328 self.slot = Slot::Busy(Box::pin(async move {
329 let result = reader.read().await;
330 (reader, result)
331 }));
332 }
333 let Slot::Busy(step) = &mut self.slot else {
334 unreachable!("started above");
335 };
336 let Poll::Ready((reader, result)) = step.as_mut().poll(cx) else {
337 return Poll::Pending;
338 };
339 if reader.released {
340 self.control = None;
341 }
342 let mut reader = reader;
343 if let Some(delay) = self.retune.lock().take() {
345 reader.track.set_delay(delay);
346 }
347 self.slot = Slot::Idle(reader);
349 let Some((read, arrival)) = result? else {
350 return Poll::Ready(Ok(None));
351 };
352 if let Read::Frame(_) = read {
354 self.arrival = arrival;
355 }
356 Poll::Ready(Ok(Some(read)))
357 }
358}
359
360#[cfg(test)]
361impl Consumer {
362 async fn next_frame(&mut self) -> Result<Option<Frame>, Error> {
364 loop {
365 match self.read().await? {
366 Some(Read::Frame(frame)) => return Ok(Some(frame)),
367 Some(Read::Gap { .. } | Read::End { .. }) => {}
368 None => return Ok(None),
369 }
370 }
371 }
372
373 fn reader(&mut self) -> &mut Reader {
375 let Slot::Idle(reader) = &mut self.slot else {
376 panic!("the decoder is not idle");
377 };
378 reader
379 }
380}
381
382impl Reader {
383 async fn open(
386 broadcast: &moq_net::broadcast::Consumer,
387 catalog: &VideoConfig,
388 name: &str,
389 options: &Options,
390 ) -> Result<(Self, moq_net::track::Control, Option<std::time::Duration>), Error> {
391 let decoder = Sink::open(catalog, &options.decoder).await.map_err(|err| match err {
392 Error::UnsupportedCodec(reason) => Error::UnsupportedConfig(reason),
395 err => err,
396 })?;
397
398 let playout = moq_mux::container::Playout::new(stated(options), std::time::Duration::ZERO);
412 let track = broadcast.track(hang::catalog::Reference::track(catalog, name))?;
413 let subscription = playout.subscription(
416 moq_net::track::Subscription::default()
417 .with_ranges([moq_net::track::Range::ALL.with_priority(options.priority)]),
418 );
419 let mut subscriber = track.subscribe(subscription).await?;
420 if options.start == Start::Latest {
424 subscriber.largest().await;
425 }
426 let control = subscriber.control();
427 let max_age = subscriber.info().max_age;
428 let track = subscriber;
429 let container = moq_mux::catalog::hang::Wire::try_from(catalog)?;
433 let track = playout.consumer(track, container);
436
437 let reader = Self {
438 decoder,
439 track,
440 pending: VecDeque::new(),
441 arrivals: VecDeque::new(),
442 drained: false,
443 released: false,
444 recover: true,
445 leading_floor: None,
446 retune: kio::Lock::new(None),
447 };
448 Ok((reader, control, max_age))
449 }
450
451 async fn read(&mut self) -> Result<Option<Item>, Error> {
454 loop {
455 if let Some(item) = self.pending.pop_front() {
456 return Ok(Some(item));
457 }
458 if self.drained {
459 return Ok(None);
460 }
461
462 let read = kio::wait(|waiter| {
463 if let Some(delay) = self.retune.lock().take() {
464 self.track.set_delay(delay);
465 }
466 self.track.poll_read(waiter)
467 })
468 .await;
469 self.released |= !matches!(read, Ok(Some(_)));
470 let mux_frame = match read? {
471 Some(Encoded::Frame { frame, .. }) => Some(frame),
472 Some(Encoded::Gap { timestamp, duration }) => {
478 let drained = self.drain().await;
479 self.pending.push_back((Read::Gap { timestamp, duration }, None));
480 self.recover = true;
481 drained?;
482 continue;
483 }
484 Some(Encoded::End { end, .. }) => {
486 let drained = self.drain().await;
487 self.pending.push_back((Read::End { end }, None));
488 drained?;
489 continue;
490 }
491 None => None,
492 };
493
494 let Some(mux_frame) = mux_frame else {
495 let drained = self.drain().await;
500 self.drained = true;
507 drained?;
508 continue;
509 };
510
511 if mux_frame.keyframe {
512 self.leading_floor = self.recover.then_some(mux_frame.timestamp);
513 self.recover = false;
514 }
515 if self.leading_floor.is_some_and(|floor| mux_frame.timestamp < floor) {
516 continue;
517 }
518
519 let arrived = self.track.arrival();
520 let queued = arrived.zip(mux_frame.timestamp.as_micros().ok());
522 if let Some((arrived, micros)) = queued {
523 if self.arrivals.len() == ARRIVALS {
524 self.arrivals.pop_front();
525 }
526 self.arrivals.push_back((micros, arrived));
527 }
528 let decoded = self
529 .decoder
530 .decode(mux_frame.payload, mux_frame.timestamp, mux_frame.keyframe)
531 .await;
532 if decoded.is_err() && queued.is_some() {
533 self.arrivals.pop_back();
536 }
537 decoded?;
538 self.receive()?;
539 }
540 }
541
542 fn receive(&mut self) -> Result<(), Error> {
544 while let Some(picture) = self.decoder.receive()? {
545 let arrival = picture.timestamp.as_micros().ok().and_then(|at| {
547 let index = {
550 let mut matches = self
551 .arrivals
552 .iter()
553 .enumerate()
554 .filter(|(_, (timestamp, _))| *timestamp == at);
555 matches
556 .next()
557 .filter(|_| matches.next().is_none())
558 .map(|(index, _)| index)?
559 };
560 let (_, arrived) = self.arrivals.remove(index)?;
561 let mut position = 0;
564 self.arrivals.retain(|(timestamp, _)| {
565 position += 1;
566 position > index || *timestamp > at
567 });
568 Some(arrived)
569 });
570 self.pending.push_back((Read::Frame(picture), arrival));
571 }
572 Ok(())
573 }
574
575 async fn drain(&mut self) -> Result<(), Error> {
578 let flushed = self.decoder.flush().await;
579 let received = self.receive();
580 self.arrivals.clear();
582 flushed.and(received)
583 }
584}
585
586#[cfg(test)]
587mod tests {
588 #![cfg_attr(
589 not(feature = "openh264"),
590 allow(dead_code, unused_imports, reason = "only the `openh264` feature uses it")
591 )]
592
593 use bytes::Bytes;
594 use moq_net::Timestamp;
595
596 fn produce_origin() -> moq_net::origin::Producer {
598 let (producer, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::default());
599 if tokio::runtime::Handle::try_current().is_ok() {
600 tokio::spawn(moq_net::time::run(driver));
601 } else {
602 std::mem::forget(driver);
605 }
606 producer
607 }
608 use super::*;
609 use crate::decode::Backend;
610 use crate::decode::backend::probe;
611 use crate::encode::{Backend as EncodeBackend, Config as EncodeConfig, Encoder, Publisher as EncodePublisher};
612 use moq_mux::container::Container as _;
613
614 #[tokio::test]
615 #[cfg(feature = "openh264")]
616 async fn reads_cmaf_container_declared_by_catalog() {
617 let mut source_broadcast = moq_net::broadcast::Info::new().produce();
618 let source_subscriber = source_broadcast.consume();
619 let source_catalog =
620 moq_mux::catalog::Producer::new(&mut source_broadcast, moq_mux::catalog::Config::default()).unwrap();
621 let config = EncodeConfig {
622 backend: EncodeBackend::Software,
623 ..EncodeConfig::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
624 };
625 let rendition = config.probe().await.unwrap();
626 let reserved = source_catalog.reserve().with_interval(config.effective_join());
627 let track = source_broadcast.unique_track(".avc3", reserved.track_info(hang::catalog::PRIORITY.video));
628 let mut producer = EncodePublisher::new(track, reserved, rendition).unwrap();
629 let mut encoder = Encoder::new(&config).unwrap();
630 let rgba = vec![0x80u8; 320 * 240 * 4];
631 for index in 0..2 {
632 encoder.cut().unwrap();
633 let surface = crate::Surface::rgba(&rgba, crate::Size::new(320, 240)).unwrap();
634 let frame = crate::Frame::new(moq_net::Timestamp::from_micros(index * 33_333).unwrap(), surface);
635 for encoded in encoder.encode_all(&frame).unwrap() {
636 producer.publish(&encoded).unwrap();
637 }
638 }
639
640 let origin = produce_origin();
641 let catalog = moq_mux::catalog::Consumer::<()>::new(&source_subscriber, moq_mux::catalog::CatalogFormat::Hang)
642 .await
643 .unwrap();
644 let source = moq_mux::Source::new(origin.consume(), source_subscriber.clone());
645 let mut export = moq_mux::container::fmp4::Export::new(source, catalog)
650 .with_delay(moq_mux::container::Delay::default().with_max(std::time::Duration::from_secs(30)));
651 let init = export.next().await.unwrap().expect("CMAF init");
652 let fragment = export.next().await.unwrap().expect("CMAF fragment");
653
654 let mut broadcast = moq_net::broadcast::Info::new().produce();
655 let subscriber = broadcast.consume();
656 let catalog = moq_mux::catalog::Producer::new(&mut broadcast, moq_mux::catalog::Config::default()).unwrap();
657 let mut import = moq_mux::container::fmp4::Import::new(broadcast, catalog.reserve()).with_cmaf(true);
658 import.decode(&init).unwrap();
659 import.decode(&fragment).unwrap();
660
661 let snapshot = catalog.snapshot();
662 let (name, config) = snapshot.video.renditions.iter().next().expect("video rendition");
663 assert!(matches!(config.container, hang::catalog::Container::Cmaf { .. }));
664 let mut consumer = Consumer::new(
665 &subscriber,
666 config,
667 name,
668 Options {
669 decoder: Config {
670 backend: Backend::Software,
671 ..Config::new()
672 },
673 ..Options::new()
674 },
675 )
676 .await
677 .unwrap();
678
679 let frame = consumer.next_frame().await.unwrap().expect("decoded frame");
680 assert_eq!(frame.size(), crate::Size::new(320, 240));
681 }
682
683 #[tokio::test]
691 async fn a_second_consumer_starts_at_the_live_edge() {
692 let broadcast = moq_net::broadcast::Info::new().produce();
693 let track = broadcast
694 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
695 .unwrap();
696 let published = track.clone();
698 let subscriber = broadcast.consume();
699 let mut producer = moq_mux::container::Producer::new(
700 track,
701 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
702 );
703 for index in 0..3u64 {
705 producer
706 .write(moq_mux::container::Frame {
707 timestamp: Timestamp::from_micros(index * 1_000_000).unwrap(),
708 decode: None,
709 duration: None,
710 payload: Bytes::from_static(b"access unit"),
711 keyframe: true,
712 })
713 .unwrap();
714 }
715 let _finished = producer.finish().unwrap();
716
717 let catalog = VideoConfig::new(hang::catalog::H264 {
718 inline: true,
719 profile: 0x42,
720 constraints: 0,
721 level: 30,
722 });
723 let mut consumer = Consumer::new(
724 &subscriber,
725 &catalog,
726 "video",
727 Options {
728 decoder: Config {
729 backend: Backend::Named(probe::BUFFERED_NAME.into()),
730 ..Config::new()
731 },
732 start: Start::Latest,
733 delay: Delay {
737 max: Some(std::time::Duration::from_secs(10)),
738 ..Delay::default()
739 },
740 ..Options::new()
741 },
742 )
743 .await
744 .unwrap();
745
746 let frame = consumer.next_frame().await.unwrap().expect("a decoded frame");
751 assert_eq!(
752 frame.timestamp,
753 Timestamp::from_micros(2_000_000).unwrap(),
754 "a fresh consumer replayed the groups an earlier reader still holds",
755 );
756
757 assert_eq!(
763 published.subscription().map(|sub| sub.ranges),
764 Some(vec![
765 moq_net::track::Range::from(moq_net::track::Start::Live {
766 min: Some(std::time::Duration::ZERO),
767 max: Some(std::time::Duration::from_secs(10)),
768 })
769 .with_priority(hang::catalog::PRIORITY.video)
770 ]),
771 "the publisher was asked to rewind the track",
772 );
773 }
774
775 #[tokio::test]
783 async fn the_default_reads_every_cached_group() {
784 let broadcast = moq_net::broadcast::Info::new().produce();
785 let track = broadcast
786 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
787 .unwrap();
788 let subscriber = broadcast.consume();
789 let mut producer = moq_mux::container::Producer::new(
790 track,
791 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
792 );
793 for index in 0..3u64 {
794 producer
795 .write(moq_mux::container::Frame {
796 timestamp: Timestamp::from_micros(index * 1_000_000).unwrap(),
797 decode: None,
798 duration: None,
799 payload: Bytes::from_static(b"access unit"),
800 keyframe: true,
801 })
802 .unwrap();
803 }
804 let _finished = producer.finish().unwrap();
805
806 let catalog = VideoConfig::new(hang::catalog::H264 {
807 inline: true,
808 profile: 0x42,
809 constraints: 0,
810 level: 30,
811 });
812 let mut consumer = Consumer::new(
813 &subscriber,
814 &catalog,
815 "video",
816 Options {
817 decoder: Config {
818 backend: Backend::Named(probe::BUFFERED_NAME.into()),
821 ..Config::new()
822 },
823 delay: Delay {
826 max: Some(std::time::Duration::from_secs(10)),
827 ..Delay::default()
828 },
829 ..Options::new()
830 },
831 )
832 .await
833 .unwrap();
834
835 let mut seen = Vec::new();
836 while let Some(frame) = consumer.next_frame().await.unwrap() {
837 seen.push(frame.timestamp);
838 }
839 assert_eq!(
840 seen,
841 vec![
842 Timestamp::from_micros(0).unwrap(),
843 Timestamp::from_micros(1_000_000).unwrap(),
844 Timestamp::from_micros(2_000_000).unwrap(),
845 ],
846 "the default dropped groups the caller never asked to drop",
847 );
848 }
849
850 #[tokio::test]
854 async fn priority_reaches_the_subscription_and_moves_in_place() {
855 let broadcast = moq_net::broadcast::Info::new().produce();
856 let track = broadcast
857 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
858 .unwrap();
859 let published = track.clone();
860 let subscriber = broadcast.consume();
861 let mut producer = moq_mux::container::Producer::new(
862 track,
863 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
864 );
865 let catalog = VideoConfig::new(hang::catalog::H264 {
866 inline: true,
867 profile: 0x42,
868 constraints: 0,
869 level: 30,
870 });
871 let options = Options {
872 decoder: Config {
873 backend: Backend::Named(probe::BUFFERED_NAME.into()),
874 ..Config::new()
875 },
876 ..Options::new()
877 };
878 let mut consumer = Consumer::new(&subscriber, &catalog, "video", options).await.unwrap();
879 assert_eq!(
880 published.subscription().map(|sub| sub.ranges[0].priority),
881 Some(hang::catalog::PRIORITY.video)
882 );
883
884 consumer.set_priority(10);
885 assert_eq!(published.subscription().map(|sub| sub.ranges[0].priority), Some(10));
886
887 {
889 let read = consumer.read();
890 tokio::pin!(read);
891 assert!(futures::poll!(read.as_mut()).is_pending());
892 }
893 consumer.set_priority(-20);
894 assert_eq!(published.subscription().map(|sub| sub.ranges[0].priority), Some(-20));
895
896 producer
897 .write(moq_mux::container::Frame {
898 timestamp: Timestamp::from_micros(0).unwrap(),
899 decode: None,
900 duration: None,
901 payload: Bytes::from_static(b"access unit"),
902 keyframe: true,
903 })
904 .unwrap();
905 let _finished = producer.finish().unwrap();
906 let frame = consumer
907 .next_frame()
908 .await
909 .unwrap()
910 .expect("the waiting read's picture");
911 assert_eq!(frame.timestamp, Timestamp::from_micros(0).unwrap());
912 }
913
914 #[tokio::test]
917 async fn a_moved_max_delay_reaches_the_subscription() {
918 let broadcast = moq_net::broadcast::Info::new().produce();
919 let track = broadcast
920 .create_track(
921 "video",
922 hang::container::track_info(hang::catalog::PRIORITY.video)
923 .with_max_age(std::time::Duration::from_secs(5)),
924 )
925 .unwrap();
926 let published = track.clone();
927 let mut producer = moq_mux::container::Producer::new(
928 track,
929 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
930 );
931 let catalog = VideoConfig::new(hang::catalog::H264 {
932 inline: true,
933 profile: 0x42,
934 constraints: 0,
935 level: 30,
936 });
937 let options = Options {
938 decoder: Config {
939 backend: Backend::Named(probe::BUFFERED_NAME.into()),
940 ..Config::new()
941 },
942 delay: Delay {
943 max: Some(std::time::Duration::from_millis(500)),
944 ..Delay::default()
945 },
946 ..Options::new()
947 };
948 let mut consumer = Consumer::new(&broadcast.consume(), &catalog, "video", options)
949 .await
950 .unwrap();
951 let live_max = || match published.subscription().unwrap().ranges[..] {
952 [
953 moq_net::track::Range {
954 start: moq_net::track::Start::Live { max, .. },
955 ..
956 },
957 ] => max,
958 ref ranges => panic!("expected one live join, got {ranges:?}"),
959 };
960 assert_eq!(consumer.max_delay(), std::time::Duration::from_millis(500));
961
962 consumer.set_max_delay(std::time::Duration::from_secs(2));
963 assert_eq!(consumer.max_delay(), std::time::Duration::from_secs(2));
964 assert_eq!(consumer.options().delay.max, Some(std::time::Duration::from_secs(2)));
965 assert_eq!(live_max(), Some(std::time::Duration::from_secs(2)));
966
967 consumer.set_max_delay(std::time::Duration::from_secs(9));
968 assert_eq!(
969 consumer.max_delay(),
970 std::time::Duration::from_secs(5),
971 "past the max age"
972 );
973
974 {
976 let read = consumer.read();
977 tokio::pin!(read);
978 assert!(futures::poll!(read.as_mut()).is_pending());
979 }
980 consumer.set_max_delay(std::time::Duration::from_secs(3));
981 {
982 let read = consumer.read();
983 tokio::pin!(read);
984 assert!(futures::poll!(read.as_mut()).is_pending());
985 }
986 assert_eq!(
987 live_max(),
988 Some(std::time::Duration::from_secs(3)),
989 "the next read retunes before it waits"
990 );
991
992 producer
993 .write(moq_mux::container::Frame {
994 timestamp: Timestamp::from_micros(0).unwrap(),
995 decode: None,
996 duration: None,
997 payload: Bytes::from_static(b"access unit"),
998 keyframe: true,
999 })
1000 .unwrap();
1001 let _finished = producer.finish().unwrap();
1002 consumer
1003 .next_frame()
1004 .await
1005 .unwrap()
1006 .expect("the waiting read's picture");
1007 }
1008
1009 #[tokio::test]
1012 async fn a_history_subscription_ignores_a_moved_max_delay() {
1013 let broadcast = moq_net::broadcast::Info::new().produce();
1014 let published = broadcast
1015 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1016 .unwrap();
1017 let catalog = VideoConfig::new(hang::catalog::H264 {
1018 inline: true,
1019 profile: 0x42,
1020 constraints: 0,
1021 level: 30,
1022 });
1023 let options = Options {
1024 decoder: Config {
1025 backend: Backend::Named(probe::BUFFERED_NAME.into()),
1026 ..Config::new()
1027 },
1028 start: Start::Oldest,
1029 delay: Delay {
1030 max: None,
1031 ..Delay::default()
1032 },
1033 ..Options::new()
1034 };
1035 let mut consumer = Consumer::new(&broadcast.consume(), &catalog, "video", options)
1036 .await
1037 .unwrap();
1038 let before = published.subscription().unwrap();
1039 let budget = consumer.max_delay();
1040 consumer.set_max_delay(std::time::Duration::ZERO);
1041 assert_eq!(consumer.options().delay.max, None);
1042 assert_eq!(consumer.max_delay(), budget);
1043 assert_eq!(published.subscription().unwrap(), before);
1044 }
1045
1046 #[tokio::test]
1049 async fn an_ended_read_releases_the_subscription() {
1050 let broadcast = moq_net::broadcast::Info::new().produce();
1051 let track = broadcast
1052 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1053 .unwrap();
1054 let subscriber = broadcast.consume();
1055 let catalog = VideoConfig::new(hang::catalog::H264 {
1056 inline: true,
1057 profile: 0x42,
1058 constraints: 0,
1059 level: 30,
1060 });
1061 let options = Options {
1062 decoder: Config {
1063 backend: Backend::Named(probe::BUFFERED_NAME.into()),
1064 ..Config::new()
1065 },
1066 ..Options::new()
1067 };
1068 let mut consumer = Consumer::new(&subscriber, &catalog, "video", options).await.unwrap();
1069 assert!(track.subscription().is_some());
1070
1071 let group = track
1073 .create_group(moq_net::frame::Frame::new(
1074 Timestamp::from_micros(0).unwrap(),
1075 Bytes::from_static(&[0xFF]),
1076 ))
1077 .unwrap();
1078 let _group = group.finish().unwrap();
1079
1080 assert!(consumer.read().await.is_err(), "the malformed frame decoded");
1081 assert!(track.subscription().is_none(), "the ended consumer still subscribes");
1082 }
1083
1084 #[test]
1091 fn max_delay_reaches_the_subscription_and_not_the_decoder() {
1092 let _probe = probe::native_exclusive();
1093 let broadcast = moq_net::broadcast::Info::new().produce();
1094 let track = broadcast
1095 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1096 .unwrap();
1097 let published = track.clone();
1098 let subscriber = broadcast.consume();
1099 let mut producer = moq_mux::container::Producer::new(
1100 track,
1101 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
1102 );
1103 producer
1104 .write(moq_mux::container::Frame {
1105 timestamp: Timestamp::from_micros(0).unwrap(),
1106 decode: None,
1107 duration: None,
1108 payload: Bytes::from_static(b"access unit"),
1109 keyframe: true,
1110 })
1111 .unwrap();
1112 let _finished = producer.finish().unwrap();
1113
1114 let catalog = VideoConfig::new(hang::catalog::H264 {
1115 inline: true,
1116 profile: 0x42,
1117 constraints: 0,
1118 level: 30,
1119 });
1120 let decoder = Config {
1121 backend: Backend::Named(probe::NATIVE_NAME.into()),
1122 output: crate::Output::Cpu,
1123 scale_hint: Some(crate::Size::new(160, 120)),
1124 ..Default::default()
1125 };
1126 let max_delay = std::time::Duration::from_secs(10);
1127 let mut consumer = pollster::block_on(Consumer::new(
1128 &subscriber,
1129 &catalog,
1130 "video",
1131 Options {
1132 decoder: decoder.clone(),
1133 delay: Delay {
1134 max: Some(max_delay),
1135 ..Delay::default()
1136 },
1137 ..Options::new()
1138 },
1139 ))
1140 .unwrap();
1141
1142 let subscription = published.subscription().expect("the consumer subscribed");
1143 let max = match subscription.ranges[..] {
1144 [
1145 moq_net::track::Range {
1146 start: moq_net::track::Start::Live { max, .. },
1147 ..
1148 },
1149 ] => max,
1150 ref ranges => panic!("expected one live join, got {ranges:?}"),
1151 };
1152 assert_eq!(max, Some(max_delay), "the age budget did not reach the publisher");
1153
1154 let opened = probe::native_opened().expect("the decoder opened");
1155 assert_eq!(opened.output, decoder.output);
1156 assert_eq!(opened.scale_hint, decoder.scale_hint);
1157
1158 let frame = pollster::block_on(consumer.next_frame())
1159 .unwrap()
1160 .expect("a decoded frame");
1161 assert!(
1162 matches!(frame.surface, crate::Surface::I420(_)),
1163 "CPU output was not enforced"
1164 );
1165 }
1166
1167 #[tokio::test]
1168 async fn leading_pictures_require_a_continuous_previous_group() {
1169 tokio::time::pause();
1170 let broadcast = moq_net::broadcast::Info::new().produce();
1171 let track = broadcast
1172 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1173 .unwrap();
1174 let catalog = VideoConfig::new(hang::catalog::H264 {
1175 inline: true,
1176 profile: 0x42,
1177 constraints: 0,
1178 level: 30,
1179 });
1180 let mut consumer = Consumer::new(
1181 &broadcast.consume(),
1182 &catalog,
1183 "video",
1184 Options {
1185 decoder: Config {
1186 backend: Backend::Named(probe::BUFFERED_NAME.into()),
1187 ..Config::new()
1188 },
1189 delay: Delay {
1190 max: Some(std::time::Duration::from_secs(10)),
1191 ..Delay::default()
1192 },
1193 ..Options::new()
1194 },
1195 )
1196 .await
1197 .unwrap();
1198 let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1199 let write = |stamps: &[u64]| {
1200 let mut group = None;
1201 let frames: Vec<_> = stamps
1202 .iter()
1203 .enumerate()
1204 .map(|(index, stamp)| moq_mux::container::Frame {
1205 timestamp: Timestamp::from_micros(*stamp).unwrap(),
1206 decode: None,
1207 duration: None,
1208 payload: Bytes::from_static(b"access unit"),
1209 keyframe: index == 0,
1210 })
1211 .collect();
1212 wire.write(&mut moq_mux::container::Writer::new(&track, &mut group), &frames)
1213 .unwrap();
1214 group.unwrap().finish().unwrap();
1215 };
1216 write(&[1000, 800, 900, 1100]);
1217 write(&[2000, 1800, 1900, 2100]);
1218 let mut got = Vec::new();
1219 for _ in 0..5 {
1220 got.push(
1221 consumer
1222 .next_frame()
1223 .await
1224 .unwrap()
1225 .unwrap()
1226 .timestamp
1227 .as_micros()
1228 .unwrap(),
1229 );
1230 }
1231 assert_eq!(
1232 got,
1233 [1000, 1100, 2000, 1800, 1900],
1234 "join trims, continuous delivery keeps every leading picture"
1235 );
1236 consumer.reader().track.set_delay(Delay::default());
1237 write(&[3000]);
1238 write(&[4000, 3800, 3900, 4100]);
1239 let _track = track.finish().unwrap();
1240 got.clear();
1241 while let Some(frame) = consumer.next_frame().await.unwrap() {
1242 got.push(frame.timestamp.as_micros().unwrap());
1243 }
1244 assert_eq!(
1245 got,
1246 [2100, 4000, 4100],
1247 "a later latency skip must trim its recovery group too"
1248 );
1249 }
1250
1251 #[tokio::test(start_paused = true)]
1256 async fn track_end_drains_buffered_decoder() {
1257 let broadcast = moq_net::broadcast::Info::new().produce();
1258 let track = broadcast
1259 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1260 .unwrap();
1261 let subscriber = broadcast.consume();
1262 let mut producer = moq_mux::container::Producer::new(
1263 track,
1264 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
1265 );
1266 let mut written = Vec::new();
1267 for index in 0..2u64 {
1268 written.push(Instant::now());
1269 producer
1270 .write(moq_mux::container::Frame {
1271 timestamp: Timestamp::from_micros(index * 33_333).unwrap(),
1272 decode: None,
1273 duration: None,
1274 payload: Bytes::from_static(b"access unit"),
1275 keyframe: index == 0,
1276 })
1277 .unwrap();
1278 tokio::time::advance(std::time::Duration::from_millis(10)).await;
1279 }
1280 let _finished = producer.finish().unwrap();
1281
1282 let catalog = VideoConfig::new(hang::catalog::H264 {
1283 inline: true,
1284 profile: 0x42,
1285 constraints: 0,
1286 level: 30,
1287 });
1288 let mut consumer = Consumer::new(
1289 &subscriber,
1290 &catalog,
1291 "video",
1292 Options {
1293 decoder: Config {
1294 backend: Backend::Named(probe::BUFFERED_NAME.into()),
1295 ..Config::new()
1296 },
1297 ..Options::new()
1298 },
1299 )
1300 .await
1301 .unwrap();
1302
1303 assert_eq!(consumer.arrival(), None, "nothing read yet");
1304 let mut timestamps = Vec::new();
1305 let mut arrivals = Vec::new();
1306 while let Some(frame) = consumer.next_frame().await.unwrap() {
1307 timestamps.push(frame.timestamp.as_micros().unwrap());
1308 arrivals.push(consumer.arrival());
1309 }
1310 assert_eq!(timestamps, vec![0, 33_333]);
1311 assert_eq!(arrivals, written.into_iter().map(Some).collect::<Vec<_>>());
1312 assert!(
1313 consumer.next_frame().await.unwrap().is_none(),
1314 "the decoder was drained twice"
1315 );
1316 }
1317
1318 #[tokio::test(start_paused = true)]
1321 async fn arrival_follows_a_reordered_picture() {
1322 let (shown, landed) = decode_bframes(probe::REORDER_NAME).await;
1323 let expected: Vec<_> = [0, 1, 2, 3].map(|index| (index, Some(landed[&index]))).into();
1324 assert_eq!(shown, expected);
1325 }
1326
1327 #[tokio::test(start_paused = true)]
1331 async fn arrival_follows_a_picture_in_decode_order() {
1332 let (shown, landed) = decode_bframes(probe::BUFFERED_NAME).await;
1333 let expected: Vec<_> = [0, 3, 1, 2].map(|index| (index, Some(landed[&index]))).into();
1334 assert_eq!(shown, expected);
1335 }
1336
1337 async fn decode_bframes(decoder: &str) -> (Vec<(u64, Option<Instant>)>, std::collections::BTreeMap<u64, Instant>) {
1341 let (broadcast, track) = live_track();
1342 let mut consumer = Consumer::new(
1343 &broadcast.consume(),
1344 &catalog(),
1345 "video",
1346 Options {
1347 decoder: Config {
1348 backend: Backend::Named(decoder.into()),
1349 ..Config::new()
1350 },
1351 delay: Delay {
1352 max: Some(std::time::Duration::from_secs(10)),
1353 ..Delay::default()
1354 },
1355 ..Options::new()
1356 },
1357 )
1358 .await
1359 .unwrap();
1360
1361 let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1362 let mut group = None;
1363 let mut landed = std::collections::BTreeMap::new();
1364 for (index, frame) in [0u64, 3, 1, 2].into_iter().enumerate() {
1365 landed.insert(frame, Instant::now());
1366 wire.write(
1367 &mut moq_mux::container::Writer::new(&track, &mut group),
1368 &[moq_mux::container::Frame {
1369 timestamp: Timestamp::from_micros(frame * 33_333).unwrap(),
1370 decode: None,
1371 duration: None,
1372 payload: Bytes::from_static(b"access unit"),
1373 keyframe: index == 0,
1374 }],
1375 )
1376 .unwrap();
1377 tokio::time::advance(std::time::Duration::from_millis(10)).await;
1378 }
1379 group.unwrap().finish().unwrap();
1380 let _track = track.finish().unwrap();
1381
1382 let mut shown = Vec::new();
1383 while let Some(frame) = consumer.next_frame().await.unwrap() {
1384 let index = u64::try_from(frame.timestamp.as_micros().unwrap()).unwrap() / 33_333;
1385 shown.push((index, consumer.arrival()));
1386 }
1387 (shown, landed)
1388 }
1389
1390 #[tokio::test(start_paused = true)]
1393 async fn arrivals_are_bounded() {
1394 const FRAMES: u64 = ARRIVALS as u64 + 8;
1395 let (broadcast, track) = live_track();
1396 let mut consumer = Consumer::new(
1397 &broadcast.consume(),
1398 &catalog(),
1399 "video",
1400 Options {
1401 decoder: Config {
1402 backend: Backend::Named(probe::HOLDING_NAME.into()),
1403 ..Config::new()
1404 },
1405 delay: Delay {
1406 max: Some(std::time::Duration::from_secs(10)),
1407 ..Delay::default()
1408 },
1409 ..Options::new()
1410 },
1411 )
1412 .await
1413 .unwrap();
1414
1415 let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1416 let mut group = None;
1417 let frames: Vec<_> = (0..FRAMES)
1418 .map(|index| moq_mux::container::Frame {
1419 timestamp: Timestamp::from_micros(index * 33_333).unwrap(),
1420 decode: None,
1421 duration: None,
1422 payload: Bytes::from_static(b"access unit"),
1423 keyframe: index == 0,
1424 })
1425 .collect();
1426 wire.write(&mut moq_mux::container::Writer::new(&track, &mut group), &frames)
1427 .unwrap();
1428 group.unwrap().finish().unwrap();
1429 let _track = track.finish().unwrap();
1430
1431 let mut sourced = Vec::new();
1432 while consumer.next_frame().await.unwrap().is_some() {
1433 assert!(consumer.reader().arrivals.len() <= ARRIVALS);
1434 sourced.push(consumer.arrival().is_some());
1435 }
1436 let mut expected = vec![false; FRAMES as usize - ARRIVALS];
1437 expected.extend(vec![true; ARRIVALS]);
1438 assert_eq!(sourced, expected);
1439 }
1440
1441 #[tokio::test]
1445 async fn an_end_drains_the_pictures_before_it() {
1446 let broadcast = moq_net::broadcast::Info::new().produce();
1447 let track = broadcast
1448 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1449 .unwrap();
1450 let subscriber = broadcast.consume();
1451 let mut producer = moq_mux::container::Producer::new(
1452 track,
1453 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video),
1454 );
1455 let picture = |micros: u64, payload: &'static [u8]| moq_mux::container::Frame {
1456 timestamp: Timestamp::from_micros(micros).unwrap(),
1457 decode: None,
1458 duration: Some(Timestamp::from_micros(33_333).unwrap()),
1459 payload: Bytes::from_static(payload),
1460 keyframe: true,
1461 };
1462 producer.write(picture(100_000, b"old access unit")).unwrap();
1463 producer.cut(None).unwrap();
1464 producer.discontinuity().unwrap();
1465
1466 let catalog = VideoConfig::new(hang::catalog::H264 {
1467 inline: true,
1468 profile: 0x42,
1469 constraints: 0,
1470 level: 30,
1471 });
1472 let mut consumer = Consumer::new(
1473 &subscriber,
1474 &catalog,
1475 "video",
1476 Options {
1477 decoder: Config {
1478 backend: Backend::Named(probe::BUFFERED_NAME.into()),
1479 ..Config::new()
1480 },
1481 delay: Delay {
1482 max: Some(std::time::Duration::from_secs(10)),
1483 ..Delay::default()
1484 },
1485 ..Options::new()
1486 },
1487 )
1488 .await
1489 .unwrap();
1490
1491 let mut reads = Vec::new();
1492 let mut read = async |consumer: &mut Consumer| {
1493 reads.push(match consumer.read().await.unwrap() {
1494 Some(Read::Frame(frame)) => format!("frame {}", frame.timestamp.as_micros().unwrap()),
1495 Some(Read::Gap { timestamp, duration }) => {
1496 format!("gap {}+{}", timestamp.as_micros().unwrap(), duration.as_micros())
1497 }
1498 Some(Read::End { end }) => format!("end {}", end.as_micros().unwrap()),
1499 None => "none".to_string(),
1500 });
1501 };
1502 read(&mut consumer).await;
1504 read(&mut consumer).await;
1505
1506 producer.write(picture(200_000, b"new access unit")).unwrap();
1507 let _finished = producer.finish().unwrap();
1508 read(&mut consumer).await;
1509 read(&mut consumer).await;
1510 assert_eq!(reads, ["frame 100000", "end 133333", "frame 200000", "none"]);
1512 }
1513
1514 async fn read_all(consumer: &mut Consumer) -> Vec<String> {
1516 let mut reads = Vec::new();
1517 loop {
1518 reads.push(match consumer.read().await {
1519 Ok(Some(Read::Frame(frame))) => format!("frame {}", frame.timestamp.as_micros().unwrap()),
1520 Ok(Some(Read::Gap { timestamp, .. })) => format!("gap {}", timestamp.as_micros().unwrap()),
1521 Ok(Some(Read::End { end })) => format!("end {}", end.as_micros().unwrap()),
1522 Ok(None) => return reads,
1523 Err(_) => "error".to_string(),
1524 });
1525 }
1526 }
1527
1528 #[tokio::test]
1531 async fn a_failed_drain_keeps_its_end() {
1532 let broadcast = moq_net::broadcast::Info::new().produce();
1533 let track = broadcast
1534 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1535 .unwrap();
1536 let subscriber = broadcast.consume();
1537 let mut producer = moq_mux::container::Producer::new(
1538 track,
1539 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video),
1540 );
1541 let picture = |micros: u64| moq_mux::container::Frame {
1542 timestamp: Timestamp::from_micros(micros).unwrap(),
1543 decode: None,
1544 duration: Some(Timestamp::from_micros(33_333).unwrap()),
1545 payload: Bytes::from_static(b"access unit"),
1546 keyframe: true,
1547 };
1548 producer.write(picture(100_000)).unwrap();
1549 producer.cut(None).unwrap();
1550 producer.discontinuity().unwrap();
1551 producer.write(picture(200_000)).unwrap();
1552 let _finished = producer.finish().unwrap();
1553
1554 let catalog = VideoConfig::new(hang::catalog::H264 {
1555 inline: true,
1556 profile: 0x42,
1557 constraints: 0,
1558 level: 30,
1559 });
1560 let mut consumer = Consumer::new(
1561 &subscriber,
1562 &catalog,
1563 "video",
1564 Options {
1565 decoder: Config {
1566 backend: Backend::Named(probe::FAILING_FLUSH_NAME.into()),
1567 ..Config::new()
1568 },
1569 delay: Delay {
1570 max: Some(std::time::Duration::from_secs(10)),
1571 ..Delay::default()
1572 },
1573 ..Options::new()
1574 },
1575 )
1576 .await
1577 .unwrap();
1578
1579 assert_eq!(
1580 read_all(&mut consumer).await,
1581 ["error", "frame 100000", "end 133333", "error", "frame 200000"]
1582 );
1583 }
1584
1585 #[tokio::test(start_paused = true)]
1588 async fn a_failed_drain_keeps_its_gap_and_recovery() {
1589 let broadcast = moq_net::broadcast::Info::new().produce();
1590 let track = broadcast
1591 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1592 .unwrap();
1593 let catalog = VideoConfig::new(hang::catalog::H264 {
1594 inline: true,
1595 profile: 0x42,
1596 constraints: 0,
1597 level: 30,
1598 });
1599 let mut consumer = Consumer::new(
1600 &broadcast.consume(),
1601 &catalog,
1602 "video",
1603 Options {
1604 decoder: Config {
1605 backend: Backend::Named(probe::FAILING_FLUSH_NAME.into()),
1606 ..Config::new()
1607 },
1608 delay: Delay {
1609 max: Some(std::time::Duration::from_secs(10)),
1610 ..Delay::default()
1611 },
1612 ..Options::new()
1613 },
1614 )
1615 .await
1616 .unwrap();
1617 let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1618 let write = |stamps: &[u64]| {
1619 let mut group = None;
1620 let frames: Vec<_> = stamps
1621 .iter()
1622 .enumerate()
1623 .map(|(index, stamp)| moq_mux::container::Frame {
1624 timestamp: Timestamp::from_micros(*stamp).unwrap(),
1625 decode: None,
1626 duration: None,
1627 payload: Bytes::from_static(b"access unit"),
1628 keyframe: index == 0,
1629 })
1630 .collect();
1631 wire.write(&mut moq_mux::container::Writer::new(&track, &mut group), &frames)
1632 .unwrap();
1633 group.unwrap().finish().unwrap();
1634 };
1635 write(&[1000, 1100]);
1636 let first = consumer.next_frame().await.unwrap().unwrap();
1637 assert_eq!(first.timestamp.as_micros().unwrap(), 1000);
1638
1639 consumer.reader().track.set_delay(Delay::default());
1640 write(&[2000]);
1641 write(&[3000, 2800, 2900, 3100]);
1642 assert!(consumer.read().await.is_err(), "the drain did not fail");
1643 consumer.set_priority(-20);
1645 assert_eq!(track.subscription().map(|sub| sub.ranges[0].priority), Some(-20));
1646 let _track = track.finish().unwrap();
1647 let reads = read_all(&mut consumer).await;
1648 assert_eq!(
1649 reads[..2],
1650 ["frame 1100", "gap 1100"],
1651 "the drained picture, then its gap: {reads:?}"
1652 );
1653 assert_eq!(
1654 reads[2..],
1655 ["frame 3000", "error", "frame 3100"],
1656 "recovery trims the leading pictures: {reads:?}"
1657 );
1658 }
1659
1660 #[cfg(not(apple))]
1664 #[tokio::test]
1665 async fn a_cancelled_read_resumes_the_flush_in_flight() {
1666 probe::prepare_blocking_flush();
1667 let broadcast = moq_net::broadcast::Info::new().produce();
1668 let track = broadcast
1669 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1670 .unwrap();
1671 let subscriber = broadcast.consume();
1672 let producer = moq_mux::container::Producer::new(
1673 track,
1674 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
1675 );
1676 let _finished = producer.finish().unwrap();
1677
1678 let catalog = VideoConfig::new(hang::catalog::H264 {
1679 inline: true,
1680 profile: 0x42,
1681 constraints: 0,
1682 level: 30,
1683 });
1684 let mut consumer = Consumer::new(
1685 &subscriber,
1686 &catalog,
1687 "video",
1688 Options {
1689 decoder: Config {
1690 backend: Backend::Named(probe::BLOCKING_FLUSH_NAME.into()),
1691 ..Config::new()
1692 },
1693 ..Options::new()
1694 },
1695 )
1696 .await
1697 .unwrap();
1698
1699 let mut read = Box::pin(consumer.next_frame());
1700 let entered = async {
1701 tokio::select! {
1702 _result = &mut read => panic!("flush returned before cancellation"),
1703 _ = probe::flush_entered() => {}
1704 }
1705 };
1706 if kio::clock::timeout(std::time::Duration::from_secs(1), entered)
1707 .await
1708 .is_err()
1709 {
1710 probe::release_flush();
1711 panic!("flush never reached the codec thread");
1712 }
1713 drop(read);
1714 probe::release_flush();
1715
1716 assert!(
1717 consumer.next_frame().await.unwrap().is_none(),
1718 "the cancelled read's flush was not resumed"
1719 );
1720 assert!(consumer.next_frame().await.unwrap().is_none());
1721 }
1722
1723 #[cfg(all(target_os = "linux", feature = "vaapi", feature = "openh264"))]
1725 #[tokio::test]
1726 async fn the_track_ending_drains_the_decoder() {
1727 const FRAMES: u64 = 5;
1728 let config = EncodeConfig {
1729 backend: EncodeBackend::Software,
1730 ..EncodeConfig::new(320, 240, crate::FrameRate::new(30, 1).unwrap())
1731 };
1732 let catalog = config.probe().await.expect("probe the software encoder");
1733
1734 let broadcast = moq_net::broadcast::Info::new().produce();
1735 let track = broadcast
1736 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1737 .unwrap();
1738 let subscriber = broadcast.consume();
1739 let mut producer = moq_mux::container::Producer::new(
1740 track,
1741 moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Data),
1742 );
1743
1744 let mut encoder = Encoder::new(&config).unwrap();
1745 let rgba = vec![0x80u8; 320 * 240 * 4];
1746 let mut written = Vec::new();
1748 for index in 0..FRAMES {
1749 if index == 0 {
1750 encoder.cut().unwrap();
1751 }
1752 let surface = crate::Surface::rgba(&rgba, crate::Size::new(320, 240)).unwrap();
1753 let frame = crate::Frame::new(moq_net::Timestamp::from_micros(index * 33_333).unwrap(), surface);
1754 for encoded in encoder.encode_all(&frame).unwrap() {
1755 let before = Instant::now();
1756 producer
1757 .write(moq_mux::container::Frame {
1758 timestamp: encoded.timestamp,
1759 decode: None,
1760 duration: None,
1761 payload: encoded.payload,
1762 keyframe: index == 0,
1763 })
1764 .unwrap();
1765 written.push((before, Instant::now()));
1766 }
1767 }
1768 let _finished = producer.finish().unwrap();
1769
1770 let decode = Options {
1771 decoder: Config {
1772 backend: Backend::Named("vaapi".into()),
1773 ..Config::new()
1774 },
1775 ..Options::new()
1776 };
1777 let Ok(mut consumer) = Consumer::new(&subscriber, &catalog, "video", decode).await else {
1780 return;
1781 };
1782
1783 let mut timestamps = Vec::new();
1784 let mut arrivals = Vec::new();
1785 while let Some(frame) = consumer.next_frame().await.unwrap() {
1786 timestamps.push(frame.timestamp.as_micros().unwrap());
1787 arrivals.push(consumer.arrival().expect("the picture kept its arrival"));
1788 }
1789 let expected: Vec<u128> = (0..FRAMES as u128).map(|index| index * 33_333).collect();
1790 assert_eq!(timestamps, expected, "the track ended before the stream did");
1791 for (index, (arrived, (before, after))) in arrivals.iter().zip(&written).enumerate() {
1792 assert!(
1793 before <= arrived && arrived <= after,
1794 "picture {index} reports another access unit's arrival"
1795 );
1796 }
1797
1798 assert!(consumer.next_frame().await.unwrap().is_none());
1801 }
1802
1803 const SECOND: u64 = 1_000_000;
1805
1806 fn catalog() -> VideoConfig {
1807 VideoConfig::new(hang::catalog::H264 {
1808 inline: true,
1809 profile: 0x42,
1810 constraints: 0,
1811 level: 30,
1812 })
1813 }
1814
1815 fn live_track() -> (moq_net::broadcast::Producer, moq_net::track::Producer) {
1816 let broadcast = moq_net::broadcast::Info::new().produce();
1817 let track = broadcast
1818 .create_track("video", hang::container::track_info(hang::catalog::PRIORITY.video))
1819 .unwrap();
1820 (broadcast, track)
1821 }
1822
1823 #[tokio::test]
1826 async fn the_first_subscription_states_the_min_delay() {
1827 let (broadcast, mut track) = live_track();
1828 let delay = Delay {
1829 min: Some(std::time::Duration::from_millis(300)),
1830 max: Some(std::time::Duration::from_millis(500)),
1831 };
1832 let consume = broadcast.consume();
1833 let catalog = catalog();
1834 let mut open = Box::pin(Consumer::new(
1835 &consume,
1836 &catalog,
1837 "video",
1838 Options {
1839 decoder: Config {
1840 backend: Backend::Named(probe::IMMEDIATE_NAME.into()),
1841 ..Config::new()
1842 },
1843 start: Start::Latest,
1844 delay,
1845 ..Options::new()
1846 },
1847 ));
1848 let first = tokio::select! {
1851 opened = &mut open => panic!("the open finished with no live edge (ok: {})", opened.is_ok()),
1852 first = track.subscription_changed() => first.unwrap(),
1853 };
1854 assert_eq!(
1855 first.map(|sub| sub.ranges),
1856 Some(vec![
1857 moq_net::track::Range::from(moq_net::track::Start::Live {
1858 min: Some(std::time::Duration::from_millis(300)),
1859 max: delay.max,
1860 })
1861 .with_priority(hang::catalog::PRIORITY.video)
1862 ])
1863 );
1864 }
1865
1866 #[tokio::test]
1869 async fn a_device_refusal_is_an_unsupported_config() {
1870 let (broadcast, _track) = live_track();
1871 let result = Consumer::new(
1872 &broadcast.consume(),
1873 &catalog(),
1874 "video",
1875 Options {
1876 decoder: Config {
1877 backend: Backend::Named(probe::REFUSING_NAME.into()),
1878 ..Config::new()
1879 },
1880 ..Options::new()
1881 },
1882 )
1883 .await;
1884 match result {
1885 Err(Error::UnsupportedConfig(reason)) => assert!(reason.contains("cannot decode"), "{reason}"),
1886 Err(other) => panic!("expected UnsupportedConfig, got {other:?}"),
1887 Ok(_) => panic!("the consumer opened a decoder its device refused"),
1888 }
1889 }
1890
1891 #[tokio::test(start_paused = true)]
1894 async fn a_refused_access_unit_does_not_lend_its_arrival() {
1895 let (broadcast, track) = live_track();
1896 let mut consumer = Consumer::new(
1897 &broadcast.consume(),
1898 &catalog(),
1899 "video",
1900 Options {
1901 decoder: Config {
1902 backend: Backend::Named(probe::IMMEDIATE_NAME.into()),
1903 ..Config::new()
1904 },
1905 delay: Delay {
1906 max: Some(std::time::Duration::from_secs(10)),
1907 ..Delay::default()
1908 },
1909 ..Options::new()
1910 },
1911 )
1912 .await
1913 .unwrap();
1914
1915 let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1916 let mut landed = Vec::new();
1919 for (sequence, payload) in [probe::CORRUPT, b"access unit".as_slice()].into_iter().enumerate() {
1920 landed.push(Instant::now());
1921 let mut group = None;
1922 wire.write(
1923 &mut moq_mux::container::Writer::new(&track, &mut group),
1924 &[moq_mux::container::Frame {
1925 decode: None,
1926 timestamp: Timestamp::from_micros(sequence as u64 * SECOND).unwrap(),
1928 duration: None,
1929 payload: Bytes::from_static(payload),
1930 keyframe: true,
1931 }],
1932 )
1933 .unwrap();
1934 group.unwrap().finish().unwrap();
1935 tokio::time::advance(std::time::Duration::from_millis(10)).await;
1936 }
1937 let _track = track.finish().unwrap();
1938
1939 let Err(err) = consumer.next_frame().await else {
1940 panic!("the refused access unit did not fail the read");
1941 };
1942 assert!(err.to_string().contains("corrupt"), "unexpected error: {err}");
1943 consumer
1944 .next_frame()
1945 .await
1946 .unwrap()
1947 .expect("the next access unit decodes");
1948 assert_eq!(consumer.arrival(), Some(landed[1]));
1949 assert_eq!(consumer.reader().arrivals.len(), 0, "nothing stays queued");
1950 }
1951
1952 #[tokio::test(start_paused = true)]
1955 async fn a_repeated_timestamp_reports_no_arrival() {
1956 let (broadcast, track) = live_track();
1957 let mut consumer = Consumer::new(
1958 &broadcast.consume(),
1959 &catalog(),
1960 "video",
1961 Options {
1962 decoder: Config {
1963 backend: Backend::Named(probe::HOLDING_NAME.into()),
1964 ..Config::new()
1965 },
1966 delay: Delay {
1967 max: Some(std::time::Duration::from_secs(10)),
1968 ..Delay::default()
1969 },
1970 ..Options::new()
1971 },
1972 )
1973 .await
1974 .unwrap();
1975
1976 let wire = moq_mux::catalog::hang::Wire::legacy(moq_mux::container::Kind::Video);
1977 let mut group = None;
1978 for keyframe in [true, false] {
1979 wire.write(
1980 &mut moq_mux::container::Writer::new(&track, &mut group),
1981 &[moq_mux::container::Frame {
1982 timestamp: Timestamp::ZERO,
1983 decode: None,
1984 duration: None,
1985 payload: Bytes::from_static(b"access unit"),
1986 keyframe,
1987 }],
1988 )
1989 .unwrap();
1990 tokio::time::advance(std::time::Duration::from_millis(10)).await;
1991 }
1992 group.unwrap().finish().unwrap();
1993 let _track = track.finish().unwrap();
1994
1995 let mut shown = 0;
1996 while consumer.next_frame().await.unwrap().is_some() {
1997 assert_eq!(consumer.arrival(), None, "picture {shown} guessed an arrival");
1998 shown += 1;
1999 }
2000 assert!(shown > 0, "the decoder returned no picture");
2001 }
2002}