1use crate::container::Delay;
2use std::collections::{HashMap, HashSet, VecDeque};
3use std::task::Poll;
4use std::time::Duration;
5
6use bytes::Bytes;
7use hang::catalog::{AudioCodec, AudioConfig, Catalog, Container, VideoConfig};
8use mp4_atom::DecodeMaybe;
9
10use crate::Result;
11use crate::catalog::Stream;
12use crate::container::Frame;
13use crate::container::consumer::Event;
14use crate::container::fmp4::Error;
15use crate::container::{ExportSource, Resume};
16use moq_net::Timestamp;
17
18const INIT_WAIT: Duration = Duration::from_secs(30);
30
31const INIT_SHARE: usize = crate::container::consumer::DEFAULT_MAX_BUFFER;
35
36pub struct Export<S: Stream> {
80 source: crate::Source,
81 catalog: Feed<S>,
82 delay: Delay,
83 fragment_duration: Option<Duration>,
84
85 tracks: HashMap<String, Fmp4Track>,
88
89 departed: HashMap<String, Fmp4Track>,
93
94 spares: HashMap<String, Rendition>,
98
99 retired: HashSet<String>,
102
103 init: Init,
104
105 late: bool,
108
109 next_track_id: u32,
111
112 sequence_number: u32,
120}
121
122enum Feed<S> {
124 Live(S),
125 Ended,
127 Stopped,
129}
130
131impl<S> Feed<S> {
132 fn live(&self) -> bool {
133 matches!(self, Feed::Live(_))
134 }
135}
136
137enum Init {
139 Waiting {
142 queued: VecDeque<(String, Fragment)>,
143 deadline: Option<Box<kio::clock::Sleep>>,
144 },
145 Written {
148 first_late: u32,
149 queued: VecDeque<Fragment>,
150 },
151}
152
153impl Init {
154 fn written(&self) -> bool {
155 matches!(self, Init::Written { .. })
156 }
157
158 fn poll_expired(&mut self, read: bool, waiter: &kio::Waiter) -> bool {
160 let Init::Waiting { deadline, .. } = self else {
161 return false;
162 };
163 if read && deadline.is_none() {
164 *deadline = Some(Box::new(kio::clock::sleep(INIT_WAIT)));
165 }
166 deadline
167 .as_mut()
168 .is_some_and(|deadline| waiter.poll_future(std::pin::Pin::new(deadline)).is_ready())
169 }
170
171 fn write(&mut self, first_late: u32) {
173 if let Init::Waiting { queued, .. } = self {
174 let queued = std::mem::take(queued)
175 .into_iter()
176 .map(|(_, fragment)| fragment)
177 .collect();
178 *self = Init::Written { first_late, queued };
179 }
180 }
181}
182
183#[derive(Clone, Debug)]
189pub enum Chunk {
190 Init(Bytes),
192
193 Fragment(Fragment),
195}
196
197impl Chunk {
198 pub fn data(&self) -> &Bytes {
200 match self {
201 Chunk::Init(data) => data,
202 Chunk::Fragment(fragment) => &fragment.data,
203 }
204 }
205
206 pub fn into_data(self) -> Bytes {
208 match self {
209 Chunk::Init(data) => data,
210 Chunk::Fragment(fragment) => fragment.data,
211 }
212 }
213
214 pub fn init(self) -> Option<Bytes> {
216 match self {
217 Chunk::Init(data) => Some(data),
218 Chunk::Fragment(_) => None,
219 }
220 }
221
222 pub fn fragment(self) -> Option<Fragment> {
224 match self {
225 Chunk::Init(_) => None,
226 Chunk::Fragment(fragment) => Some(fragment),
227 }
228 }
229}
230
231#[derive(Clone, Debug)]
233pub struct Fragment {
234 pub data: Bytes,
236
237 pub independent: bool,
241
242 pub duration: Duration,
244}
245
246#[allow(
248 clippy::large_enum_variant,
249 reason = "one per rendition, so the variant sizes never add up to an allocation's worth; only large when extra features grow the video config"
250)]
251enum Rendition {
252 Video(VideoConfig),
253 Audio(AudioConfig),
254}
255
256impl Rendition {
257 fn subscribe(&self, source: &crate::Source, name: &str, delay: Delay) -> Result<Option<ExportSource>> {
258 match self {
259 Rendition::Video(config) => ExportSource::for_fmp4_video(source, name, config, delay),
260 Rendition::Audio(config) => ExportSource::for_audio(source, name, config, delay),
261 }
262 }
263
264 fn read_by(&self, export: &ExportSource, source: &crate::Source, name: &str) -> bool {
266 match self {
267 Rendition::Video(config) => export.reads(source, name, config),
268 Rendition::Audio(config) => export.reads(source, name, config),
269 }
270 }
271
272 fn is_video(&self) -> bool {
273 matches!(self, Rendition::Video(_))
274 }
275
276 fn may_reorder(&self) -> bool {
279 match self {
280 Rendition::Video(config) => match config.reorder {
281 Some(depth) => depth > 0,
282 None => crate::codec::video::max_reorder(config) > 0,
283 },
284 Rendition::Audio(_) => false,
285 }
286 }
287
288 fn default_frame(&self) -> Duration {
290 match self {
291 Rendition::Video(config) => {
292 Duration::from_secs_f64(1.0 / super::usable_video_framerate(config).unwrap_or(30.0))
293 }
294 Rendition::Audio(config) => super::audio_default_frame(config),
295 }
296 }
297}
298
299struct Declaration {
301 trak: mp4_atom::Trak,
302 trex: mp4_atom::Trex,
303 ftyp: Option<mp4_atom::Ftyp>,
305 provisional: bool,
308}
309
310enum Phase {
312 Reading(Subscription),
314 Ended(Subscription),
316 Lost(Subscription),
319 Departed(Resume),
321 Stopped,
323}
324
325struct Subscription {
327 source: ExportSource,
328 described: bool,
331}
332
333struct Batch {
335 frames: Vec<Frame>,
336 independent: bool,
339}
340
341#[derive(Default)]
344enum Buffer {
345 #[default]
346 Empty,
347 Open(Batch),
348 Closed(Batch),
350}
351
352impl Buffer {
353 fn batch(&self) -> Option<&Batch> {
354 match self {
355 Buffer::Empty => None,
356 Buffer::Open(batch) | Buffer::Closed(batch) => Some(batch),
357 }
358 }
359
360 fn is_empty(&self) -> bool {
361 self.batch().is_none()
362 }
363
364 fn is_closed(&self) -> bool {
365 matches!(self, Buffer::Closed(_))
366 }
367
368 fn first(&self) -> Option<&Frame> {
369 self.batch()?.frames.first()
370 }
371
372 fn last(&self) -> Option<&Frame> {
373 self.batch()?.frames.last()
374 }
375
376 fn last_mut(&mut self) -> Option<&mut Frame> {
377 match self {
378 Buffer::Empty => None,
379 Buffer::Open(batch) | Buffer::Closed(batch) => batch.frames.last_mut(),
380 }
381 }
382
383 fn push(&mut self, frame: Frame) {
385 match self {
386 Buffer::Open(batch) => batch.frames.push(frame),
387 _ => {
388 *self = Buffer::Open(Batch {
389 independent: frame.keyframe,
390 frames: vec![frame],
391 })
392 }
393 }
394 }
395
396 fn close(&mut self) {
398 *self = match std::mem::take(self) {
399 Buffer::Open(batch) => Buffer::Closed(batch),
400 buffer => buffer,
401 };
402 }
403
404 fn take(&mut self) -> Option<Batch> {
405 match std::mem::take(self) {
406 Buffer::Empty => None,
407 Buffer::Open(batch) | Buffer::Closed(batch) => Some(batch),
408 }
409 }
410}
411
412struct Fmp4Track {
413 phase: Phase,
414
415 config: Rendition,
416
417 declaration: Option<Declaration>,
420
421 pending: Option<Frame>,
423
424 buffer: Buffer,
425
426 is_video: bool,
429
430 opus: bool,
432
433 default_frame: Duration,
436
437 written: Option<Duration>,
440
441 decode_end: Option<u64>,
448
449 held: usize,
451
452 track_id: u32,
453 timescale: u64,
456}
457
458impl Fmp4Track {
459 fn new(source: ExportSource, config: Rendition, track_id: u32) -> Result<Self> {
460 let timescale = match &config {
461 Rendition::Video(config) => catalog_timescale_video(config)?,
462 Rendition::Audio(config) => catalog_timescale_audio(config)?,
463 };
464 Ok(Self {
465 phase: Phase::Reading(Subscription {
466 source,
467 described: false,
468 }),
469 is_video: config.is_video(),
470 opus: matches!(&config, Rendition::Audio(config) if matches!(config.codec, AudioCodec::Opus)),
471 default_frame: config.default_frame(),
472 config,
473 declaration: None,
474 pending: None,
475 buffer: Buffer::Empty,
476 written: None,
477 decode_end: None,
478 held: 0,
479 track_id,
480 timescale,
481 })
482 }
483
484 fn next_start(&self) -> Option<Duration> {
491 self.buffer
492 .first()
493 .or(self.pending.as_ref())
494 .and_then(|frame| crate::container::time(frame.timestamp))
495 }
496
497 fn subscription(&self) -> Option<&Subscription> {
499 match &self.phase {
500 Phase::Reading(subscription) | Phase::Ended(subscription) | Phase::Lost(subscription) => Some(subscription),
501 Phase::Departed(_) | Phase::Stopped => None,
502 }
503 }
504
505 fn subscription_mut(&mut self) -> Option<&mut Subscription> {
506 match &mut self.phase {
507 Phase::Reading(subscription) | Phase::Ended(subscription) | Phase::Lost(subscription) => Some(subscription),
508 Phase::Departed(_) | Phase::Stopped => None,
509 }
510 }
511
512 fn finished(&self) -> bool {
514 !matches!(self.phase, Phase::Reading(_))
515 }
516
517 fn described(&self) -> bool {
518 self.subscription().is_some_and(|subscription| subscription.described)
519 }
520
521 fn end(&mut self) {
523 self.phase = match std::mem::replace(&mut self.phase, Phase::Stopped) {
524 Phase::Reading(subscription) => Phase::Ended(subscription),
525 phase => phase,
526 };
527 }
528
529 fn lose(&mut self) {
531 self.phase = match std::mem::replace(&mut self.phase, Phase::Stopped) {
532 Phase::Reading(subscription) => Phase::Lost(subscription),
533 phase => phase,
534 };
535 }
536
537 fn lost(&self) -> bool {
538 matches!(self.phase, Phase::Lost(_))
539 }
540
541 fn depart(&mut self) {
544 self.phase = match std::mem::replace(&mut self.phase, Phase::Stopped) {
545 Phase::Reading(subscription) | Phase::Ended(subscription) => Phase::Departed(subscription.source.resume()),
546 phase => phase,
547 };
548 }
549
550 fn reconfigure(&mut self, name: &str, config: Rendition) -> Result<()> {
552 if config.is_video() != self.is_video {
553 return Err(Error::TrackChanged(name.to_string()).into());
554 }
555 if let (Rendition::Video(video), Some(subscription)) = (&config, self.subscription_mut())
556 && !subscription.source.note_catalog(video)
557 {
558 return Err(Error::TrackChanged(name.to_string()).into());
559 }
560 self.default_frame = config.default_frame();
561 self.config = config;
562 self.describe(name)
563 }
564
565 fn moved(&mut self) {
568 self.pending = None;
569 self.buffer.close();
570 }
571
572 fn rejoin(&mut self, name: &str, config: Rendition, source: ExportSource) -> Result<()> {
575 self.phase = Phase::Reading(Subscription {
576 source,
577 described: false,
578 });
579 self.reconfigure(name, config)
580 }
581
582 fn describe(&mut self, name: &str) -> Result<()> {
585 let Some(declaration) = self.declaration()? else {
586 return Ok(());
587 };
588 match &mut self.declaration {
589 Some(declared) => {
590 let guessed = declared.provisional || declaration.provisional;
591 if sample_entry(&declared.trak, guessed) != sample_entry(&declaration.trak, guessed) {
592 return Err(Error::TrackChanged(name.to_string()).into());
593 }
594 if declared.provisional && !declaration.provisional {
598 *declared = declaration;
599 }
600 }
601 None => self.declaration = Some(declaration),
602 }
603 if let Some(subscription) = self.subscription_mut() {
604 subscription.described = true;
605 }
606 Ok(())
607 }
608
609 fn declaration(&self) -> Result<Option<Declaration>> {
615 let init = match &self.config {
616 Rendition::Video(config) => match &config.container {
617 Container::Cmaf { init, .. } => init,
618 Container::Legacy | Container::Loc | Container::Raw | Container::Cts => {
619 let Some(Subscription { source, .. }) = self.subscription() else {
620 return Ok(None);
621 };
622 if !source.header_ready() || !source.video_geometry_ready(config) {
623 return Ok(None);
624 }
625 let description = config
628 .description
629 .as_ref()
630 .filter(|d| !d.is_empty())
631 .or(source.description())
632 .map(|d| d.as_ref());
633 let config = source.video_config(config).unwrap_or_else(|| config.clone());
634 let trak = super::synthesize_video_trak(self.track_id, self.timescale, &config, description)?;
635 return Ok(Some(Declaration::synthesized(trak)));
636 }
637 Container::Unknown(unknown) => return Err(crate::Error::unsupported_container(unknown)),
638 },
639 Rendition::Audio(config) => match &config.container {
640 Container::Cmaf { init, .. } => init,
641 Container::Legacy | Container::Loc | Container::Raw | Container::Cts => {
642 let trak = super::synthesize_audio_trak(self.track_id, self.timescale, config)?;
643 let mut declaration = Declaration::synthesized(trak);
644 declaration.provisional = matches!(config.codec, AudioCodec::Opus) && config.description.is_none();
645 return Ok(Some(declaration));
646 }
647 Container::Unknown(unknown) => return Err(crate::Error::unsupported_container(unknown)),
648 },
649 };
650
651 let mut ftyp = None;
652 let mut traks = Vec::new();
653 let mut trexs = Vec::new();
654 extract_init(init, self.track_id, &mut ftyp, &mut traks, &mut trexs)?;
655 let mut trak = match <[mp4_atom::Trak; 1]>::try_from(traks) {
656 Ok([trak]) => trak,
657 Err(traks) if traks.is_empty() => return Err(Error::NoTracks.into()),
658 Err(_) => return Err(Error::MultipleTracks.into()),
659 };
660 trak.mdia.mdhd.timescale = super::mdhd_timescale(self.timescale)?;
663 let trex = trexs.pop().unwrap_or_else(|| default_trex(self.track_id));
664 Ok(Some(Declaration {
665 trak,
666 trex,
667 ftyp,
668 provisional: false,
669 }))
670 }
671}
672
673impl Declaration {
674 fn synthesized(trak: mp4_atom::Trak) -> Self {
675 Self {
676 trex: default_trex(trak.tkhd.track_id),
677 trak,
678 ftyp: None,
679 provisional: false,
680 }
681 }
682}
683
684fn sample_entry(trak: &mp4_atom::Trak, guessed: bool) -> mp4_atom::Stsd {
690 let mut stsd = trak.mdia.minf.stbl.stsd.clone();
691 for codec in &mut stsd.codecs {
692 match codec {
693 mp4_atom::Codec::Mp4a(mp4a) => {
694 mp4a.esds.es_desc.dec_config.max_bitrate = 0;
695 mp4a.esds.es_desc.dec_config.avg_bitrate = 0;
696 mp4a.btrt = None;
697 }
698 mp4_atom::Codec::Opus(opus) if guessed => {
699 opus.dops.pre_skip = 0;
700 opus.dops.input_sample_rate = 0;
701 }
702 _ => {}
703 }
704 }
705 stsd
706}
707
708fn default_trex(track_id: u32) -> mp4_atom::Trex {
709 mp4_atom::Trex {
710 track_id,
711 default_sample_description_index: 1,
712 ..Default::default()
713 }
714}
715
716impl<S: Stream> Export<S> {
717 pub fn new(source: crate::Source, catalog: S) -> Self {
724 Self {
725 source,
726 catalog: Feed::Live(catalog),
727 delay: Delay::default(),
728 fragment_duration: None,
729 tracks: HashMap::new(),
730 departed: HashMap::new(),
731 spares: HashMap::new(),
732 retired: HashSet::new(),
733 init: Init::Waiting {
734 queued: VecDeque::new(),
735 deadline: None,
736 },
737 late: false,
738 next_track_id: 1,
739 sequence_number: 1,
740 }
741 }
742
743 pub fn with_delay(mut self, delay: Delay) -> Self {
749 self.delay = delay;
750 self
751 }
752
753 pub fn with_fragment_duration(mut self, duration: impl Into<Option<Duration>>) -> Self {
773 self.fragment_duration = duration.into();
774 self
775 }
776
777 pub(crate) fn with_late_tracks(mut self) -> Self {
780 self.late = true;
781 self
782 }
783
784 pub(crate) fn stop(&mut self) {
789 self.catalog = Feed::Stopped;
790 for track in self.tracks.values_mut() {
791 track.phase = Phase::Stopped;
792 }
793 }
794
795 pub(crate) fn declaration(&self, track_id: u32) -> Option<(&mp4_atom::Trak, &mp4_atom::Trex)> {
797 self.declarations()
798 .find(|(id, _, _)| *id == track_id)
799 .map(|(_, trak, trex)| (trak, trex))
800 }
801
802 pub(crate) fn declarations(&self) -> impl Iterator<Item = (u32, &mp4_atom::Trak, &mp4_atom::Trex)> {
804 self.tracks.values().chain(self.departed.values()).filter_map(|track| {
805 let declaration = track.declaration.as_ref()?;
806 Some((track.track_id, &declaration.trak, &declaration.trex))
807 })
808 }
809
810 #[cfg_attr(feature = "async", kio::wrapper)]
826 pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Bytes>>> {
827 Poll::Ready(Ok(
828 std::task::ready!(self.poll_next_chunk(waiter)?).map(Chunk::into_data)
829 ))
830 }
831
832 #[cfg_attr(feature = "async", kio::wrapper)]
835 pub fn poll_next_chunk(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Chunk>>> {
836 loop {
841 while let Feed::Live(catalog) = &mut self.catalog {
843 match catalog.poll_next(waiter)? {
844 Poll::Ready(Some(snapshot)) => self.update_catalog(&snapshot.value.without_ext())?,
845 Poll::Ready(None) => {
846 self.catalog = Feed::Ended;
847 break;
848 }
849 Poll::Pending => break,
850 }
851 }
852
853 let waiting = !self.init.written();
861 let mut lost = Vec::new();
862 for (name, track) in &mut self.tracks {
863 if track.pending.is_some() || track.buffer.is_closed() || (waiting && track.held >= INIT_SHARE) {
864 continue;
865 }
866 while let Phase::Reading(subscription) = &mut track.phase {
867 let event = match subscription.source.poll_event(waiter) {
868 Poll::Ready(Err(err)) if subscription.source.lost() => {
869 track.lose();
870 lost.push((name.clone(), err));
871 break;
872 }
873 event => event?,
874 };
875 match event {
876 Poll::Ready(Some(Event::Frame { frame, .. })) => {
877 if !track.described() || frame.keyframe {
879 track.describe(name)?;
880 if !track.described() {
881 continue;
882 }
883 }
884 if waiting {
885 track.held += crate::container::consumer::frame_cost(&frame);
886 }
887 track.pending = Some(frame);
888 break;
889 }
890 Poll::Ready(Some(Event::FrameEnd { end, .. })) => {
891 if track.is_video
892 && let Some(last) = track.buffer.last_mut()
893 && last.duration.is_none()
894 {
895 last.duration =
896 timestamp_gap(last.timestamp, end, moq_net::Timescale::new(track.timescale)?)?;
897 if self.fragment_duration == Some(Duration::ZERO) && last.duration.is_some() {
898 break;
899 }
900 }
901 }
902 Poll::Ready(Some(Event::Cut { .. })) => {}
904 Poll::Ready(Some(Event::GroupEnd)) => {
905 if track.buffer.is_empty() {
906 continue;
907 }
908 track.buffer.close();
909 break;
910 }
911 Poll::Ready(None) => {
912 track.end();
913 break;
914 }
915 Poll::Pending => break,
916 }
917 }
918 }
919 let mut continued = false;
920 for (name, err) in lost {
921 continued |= self.survive(&name, err)?;
922 }
923 if self.settle_spares()? || continued {
926 continue;
927 }
928
929 if let Init::Waiting { queued, .. } = &self.init {
932 if self.init_ready() {
933 let init = self.build_init()?;
934 self.init.write(self.next_track_id);
935 return Poll::Ready(Ok(Some(Chunk::Init(init))));
936 }
937 if !self.catalog.live() && self.tracks.values().all(Fmp4Track::finished) {
938 if !queued.is_empty() && !matches!(self.catalog, Feed::Stopped) {
940 return Poll::Ready(Err(Error::TrackUndescribed(self.undescribed()).into()));
941 }
942 return Poll::Ready(Ok(None));
943 }
944 let read = self
946 .tracks
947 .values()
948 .filter_map(Fmp4Track::subscription)
949 .any(|sub| sub.source.read());
950 if self.init.poll_expired(read, waiter) {
951 return Poll::Ready(Err(Error::TrackUndescribed(self.undescribed()).into()));
952 }
953 } else if let Init::Written { queued, .. } = &mut self.init
954 && let Some(fragment) = queued.pop_front()
955 {
956 return Poll::Ready(Ok(Some(Chunk::Fragment(fragment))));
957 }
958
959 if let Some(name) = self.completed_fragment() {
962 let track = self.tracks.get_mut(&name).unwrap();
963 let batch = track.buffer.take().unwrap();
964 let fragment = emit_fragment(&name, track, &mut self.sequence_number, batch, None)?;
965 if let Some(chunk) = self.deliver(name, fragment) {
966 return Poll::Ready(Ok(Some(chunk)));
967 }
968 continue;
969 }
970
971 let chosen = self
975 .tracks
976 .iter()
977 .filter_map(|(name, t)| {
978 let f = t.pending.as_ref()?;
979 Some((crate::container::time(f.timestamp)?, !t.is_video, name.clone()))
980 })
981 .min()
982 .map(|(_, _, name)| name);
983
984 if let Some(name) = chosen {
985 let frag = self.fragment_duration;
986 let track = self.tracks.get_mut(&name).unwrap();
987 let frame = track.pending.take().unwrap();
988 let fragment = if frag == Some(Duration::ZERO) {
991 if let Some(batch) = track.buffer.take() {
992 let fragment = emit_fragment(&name, track, &mut self.sequence_number, batch, Some(&frame))?;
995 track.pending = Some(frame);
996 fragment
997 } else if track.is_video && frame.duration.is_none() {
998 track.buffer.push(frame);
999 continue;
1000 } else {
1001 let batch = Batch {
1002 independent: frame.keyframe,
1003 frames: vec![frame],
1004 };
1005 emit_fragment(&name, track, &mut self.sequence_number, batch, None)?
1006 }
1007 } else if should_flush(&track.buffer, &frame, frag) {
1008 let batch = track.buffer.take().unwrap();
1009 let fragment = emit_fragment(&name, track, &mut self.sequence_number, batch, Some(&frame))?;
1010 track.buffer.push(frame);
1012 fragment
1013 } else {
1014 track.buffer.push(frame);
1015 continue;
1017 };
1018 if let Some(chunk) = self.deliver(name, fragment) {
1019 return Poll::Ready(Ok(Some(chunk)));
1020 }
1021 continue;
1022 }
1023
1024 let flushable = self
1029 .tracks
1030 .iter()
1031 .filter_map(|(name, t)| {
1032 let first = crate::container::time(t.buffer.first()?.timestamp)?;
1033 (t.finished() || t.buffer.is_closed()).then(|| (first, !t.is_video, name.clone()))
1034 })
1035 .min()
1036 .map(|(_, _, name)| name);
1037
1038 if let Some(name) = flushable {
1039 let track = self.tracks.get_mut(&name).unwrap();
1040 let batch = track.buffer.take().unwrap();
1041 let fragment = emit_fragment(&name, track, &mut self.sequence_number, batch, None)?;
1042 if let Some(chunk) = self.deliver(name, fragment) {
1043 return Poll::Ready(Ok(Some(chunk)));
1044 }
1045 continue;
1046 }
1047
1048 if self.init.written()
1050 && !self.catalog.live()
1051 && self.tracks.values().all(|t| t.finished() && t.buffer.is_empty())
1052 {
1053 return Poll::Ready(Ok(None));
1054 }
1055
1056 return Poll::Pending;
1057 }
1058 }
1059
1060 fn deliver(&mut self, name: String, fragment: Fragment) -> Option<Chunk> {
1063 match &mut self.init {
1064 Init::Written { .. } => Some(Chunk::Fragment(fragment)),
1065 Init::Waiting { queued, .. } => {
1066 queued.push_back((name, fragment));
1067 None
1068 }
1069 }
1070 }
1071
1072 fn undescribed(&self) -> Vec<String> {
1074 let mut names: Vec<String> = self
1075 .tracks
1076 .iter()
1077 .filter(|(_, track)| !track.described())
1078 .map(|(name, _)| name.clone())
1079 .collect();
1080 names.sort();
1081 names
1082 }
1083
1084 fn completed_fragment(&self) -> Option<String> {
1086 let earliest = self.tracks.values().filter_map(Fmp4Track::next_start).min()?;
1087 self.tracks
1088 .iter()
1089 .filter_map(|(name, track)| {
1090 let first = crate::container::time(track.buffer.first()?.timestamp)?;
1091 let complete = (track.finished() && track.pending.is_none())
1093 || track.buffer.is_closed()
1094 || (self.fragment_duration == Some(Duration::ZERO)
1095 && track.buffer.last().is_some_and(|frame| frame.duration.is_some()));
1096 complete.then_some((first, !track.is_video, name))
1097 })
1098 .filter(|(start, _, _)| *start <= earliest)
1099 .min()
1100 .map(|(_, _, name)| name.clone())
1101 }
1102
1103 fn update_catalog(&mut self, catalog: &Catalog) -> Result<()> {
1104 let mut catalog = catalog.clone();
1107 catalog
1108 .video
1109 .renditions
1110 .retain(|name, config| crate::catalog::hang::supported(name, &config.container));
1111 catalog
1112 .audio
1113 .renditions
1114 .retain(|name, config| crate::catalog::hang::supported(name, &config.container));
1115 self.source.retain_selectable(&mut catalog);
1116
1117 let video = catalog
1118 .video
1119 .renditions
1120 .into_iter()
1121 .map(|(name, config)| (name, Rendition::Video(config)));
1122 let audio = catalog
1123 .audio
1124 .renditions
1125 .into_iter()
1126 .map(|(name, config)| (name, Rendition::Audio(config)));
1127
1128 let mut active = HashSet::new();
1129 let mut listed = HashSet::new();
1130 let mut spares = HashMap::new();
1131 for (name, config) in video.chain(audio) {
1132 if active.contains(&name) || !listed.insert(name.clone()) || self.retired.contains(&name) {
1134 continue;
1135 }
1136 if !self.tracks.contains_key(&name)
1137 && !self.departed.contains_key(&name)
1138 && self.init.written()
1139 && !self.late
1140 {
1141 if !self.spares.contains_key(&name) {
1142 tracing::warn!(track = %name, "rendition joined after the init; it waits to continue a failed one");
1143 }
1144 spares.insert(name, config);
1145 continue;
1146 }
1147 if !self.tracks.contains_key(&name)
1148 && let Some(track) = self.departed.remove(&name)
1149 {
1150 self.tracks.insert(name.clone(), track);
1151 }
1152 let moved = self
1153 .tracks
1154 .get(&name)
1155 .and_then(Fmp4Track::subscription)
1156 .is_some_and(|subscription| !config.read_by(&subscription.source, &self.source, &name));
1157 if moved && let Init::Waiting { queued, .. } = &mut self.init {
1159 self.tracks.remove(&name);
1160 queued.retain(|(queued, _)| *queued != name);
1161 }
1162 match self.tracks.get_mut(&name) {
1163 Some(track) if track.subscription().is_some() && !moved => track.reconfigure(&name, config)?,
1164 Some(track) => {
1165 let Some(source) = config.subscribe(&self.source, &name, self.delay)? else {
1166 continue;
1167 };
1168 let source = match std::mem::replace(&mut track.phase, Phase::Stopped) {
1172 Phase::Reading(previous) | Phase::Ended(previous) | Phase::Lost(previous) => {
1173 track.moved();
1174 source.continuing(&previous.source)
1175 }
1176 Phase::Departed(resume) => source.resuming(&resume),
1177 Phase::Stopped => source,
1178 };
1179 track.rejoin(&name, config, source)?;
1180 }
1181 None => {
1182 let Some(source) = config.subscribe(&self.source, &name, self.delay)? else {
1185 continue;
1186 };
1187 let mut track = Fmp4Track::new(source, config, self.next_track_id)?;
1188 self.next_track_id += 1;
1189 track.describe(&name)?;
1190 self.tracks.insert(name.clone(), track);
1191 }
1192 }
1193 active.insert(name);
1194 }
1195
1196 match &mut self.init {
1197 Init::Written { first_late, .. } => {
1198 for (name, track) in &mut self.tracks {
1202 if !active.contains(name) && !track.lost() {
1203 track.depart();
1204 }
1205 }
1206 let drained = self.tracks.extract_if(|_, track| {
1208 track.subscription().is_none() && track.pending.is_none() && track.buffer.is_empty()
1209 });
1210 for (name, track) in drained {
1211 if track.written.is_some() || track.track_id < *first_late {
1212 self.departed.insert(name, track);
1213 }
1214 }
1215 }
1216 Init::Waiting { queued, .. } => {
1217 self.tracks.retain(|name, _| active.contains(name));
1218 queued.retain(|(name, _)| active.contains(name));
1219 }
1220 }
1221 self.retired.retain(|name| listed.contains(name));
1222 self.spares = spares;
1223 self.settle_spares().map(|_| ())
1224 }
1225
1226 fn survive(&mut self, name: &str, err: crate::Error) -> Result<bool> {
1235 if !self.init.written()
1238 && let Some(track) = self.tracks.get(name)
1239 && !track.described()
1240 {
1241 self.tracks.remove(name);
1242 self.retired.insert(name.to_string());
1243 }
1244 let continued = self.settle_spares()?;
1245 if !self
1246 .tracks
1247 .values()
1248 .any(|track| matches!(track.phase, Phase::Reading(_)))
1249 {
1250 return Err(err);
1251 }
1252 if self.tracks.get(name).is_some_and(Fmp4Track::lost) {
1253 tracing::warn!(track = name, %err, "rendition failed; the export keeps its other media");
1254 }
1255 Ok(continued)
1256 }
1257
1258 fn settle_spares(&mut self) -> Result<bool> {
1265 let mut names: Vec<String> = self.spares.keys().cloned().collect();
1266 names.sort();
1267 let mut continued = false;
1268 for name in names {
1269 let is_video = self.spares[&name].is_video();
1270 let medium = |track: &Fmp4Track| track.is_video == is_video;
1271 let pick = |tracks: &HashMap<String, Fmp4Track>, phase: fn(&Phase) -> bool| {
1272 tracks
1273 .iter()
1274 .filter(|(_, track)| medium(track) && phase(&track.phase))
1275 .map(|(key, track)| (track.track_id, key.clone()))
1276 .min()
1277 .map(|(_, key)| key)
1278 };
1279 let reading = self
1280 .tracks
1281 .values()
1282 .any(|track| medium(track) && matches!(track.phase, Phase::Reading(_)));
1283 let lost = pick(&self.tracks, |phase| matches!(phase, Phase::Lost(_)));
1284 let track = match lost {
1285 Some(key) => self.tracks.remove(&key).map(|track| (key, track)),
1286 None if reading => continue,
1287 None => match pick(&self.tracks, |phase| matches!(phase, Phase::Departed(_))) {
1288 Some(key) => self.tracks.remove(&key).map(|track| (key, track)),
1289 None => pick(&self.departed, |_| true).and_then(|key| self.departed.remove_entry(&key)),
1290 },
1291 };
1292 let Some((previous, mut track)) = track else {
1293 return Err(Error::TrackAdded(name).into());
1294 };
1295 let config = self.spares.remove(&name).expect("a listed spare");
1296 let Some(source) = config.subscribe(&self.source, &name, self.delay)? else {
1297 match track.phase {
1299 Phase::Departed(_) if track.subscription().is_none() && track.buffer.is_empty() => {
1300 self.departed.insert(previous, track)
1301 }
1302 _ => self.tracks.insert(previous, track),
1303 };
1304 continue;
1305 };
1306 let source = match std::mem::replace(&mut track.phase, Phase::Stopped) {
1307 Phase::Lost(failed) => {
1308 self.retired.insert(previous.clone());
1309 source.continuing(&failed.source)
1310 }
1311 Phase::Departed(resume) => source.resuming(&resume),
1312 _ => unreachable!("picked a lost or departed track"),
1313 };
1314 tracing::info!(track = %name, replaces = %previous, "continuing a declared rendition");
1315 track.moved();
1316 track.rejoin(&name, config, source)?;
1317 self.tracks.insert(name, track);
1318 continued = true;
1319 }
1320 Ok(continued)
1321 }
1322
1323 #[cfg(test)]
1325 pub(super) fn held(&self) -> usize {
1326 let frames = self.tracks.values().flat_map(|track| {
1327 let buffered = track.buffer.batch().into_iter().flat_map(|batch| &batch.frames);
1328 buffered.chain(&track.pending)
1329 });
1330 let queued = match &self.init {
1331 Init::Waiting { queued, .. } => queued.iter().map(|(_, fragment)| fragment).collect::<Vec<_>>(),
1332 Init::Written { queued, .. } => queued.iter().collect(),
1333 };
1334 frames.map(|frame| frame.payload.len()).sum::<usize>()
1335 + queued.iter().map(|fragment| fragment.data.len()).sum::<usize>()
1336 }
1337
1338 fn init_ready(&self) -> bool {
1340 !self.tracks.is_empty() && self.tracks.values().all(Fmp4Track::described)
1341 }
1342
1343 fn build_init(&self) -> Result<Bytes> {
1346 let mut tracks: Vec<&Fmp4Track> = self.tracks.values().collect();
1347 tracks.sort_by_key(|track| (!track.is_video, track.track_id));
1348
1349 let mut traks = Vec::new();
1350 let mut trexs = Vec::new();
1351 let mut ftyp = None;
1352 for track in tracks {
1353 let declaration = track.declaration.as_ref().expect("init_ready checked every track");
1354 ftyp = ftyp.or_else(|| declaration.ftyp.clone());
1355 traks.push(declaration.trak.clone());
1356 trexs.push(declaration.trex.clone());
1357 }
1358
1359 Ok(crate::container::fmp4::encode_init(ftyp, traks, trexs)?)
1360 }
1361}
1362
1363pub(crate) fn extract_init(
1374 init: &Bytes,
1375 track_id: u32,
1376 ftyp_data: &mut Option<mp4_atom::Ftyp>,
1377 traks: &mut Vec<mp4_atom::Trak>,
1378 trexs: &mut Vec<mp4_atom::Trex>,
1379) -> Result<()> {
1380 let mut cursor = std::io::Cursor::new(init.as_ref());
1381 while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).map_err(crate::Error::mp4)? {
1382 match atom {
1383 mp4_atom::Any::Ftyp(f) if ftyp_data.is_none() => {
1384 *ftyp_data = Some(f);
1385 }
1386 mp4_atom::Any::Moov(moov) => {
1387 for mut trak in moov.trak {
1388 trak.tkhd.track_id = track_id;
1389 trak.edts = None;
1393 trak.tkhd.duration = super::UNKNOWN_DURATION;
1399 traks.push(trak);
1400 }
1401 if let Some(mvex) = moov.mvex {
1402 for mut trex in mvex.trex {
1403 trex.track_id = track_id;
1404 trexs.push(trex);
1405 }
1406 }
1407 }
1408 _ => {}
1409 }
1410 }
1411 Ok(())
1412}
1413
1414fn should_flush(buffer: &Buffer, frame: &Frame, fragment_duration: Option<Duration>) -> bool {
1422 let batch = match buffer {
1423 Buffer::Empty => return false,
1424 Buffer::Closed(_) => return true,
1425 Buffer::Open(batch) => batch,
1426 };
1427 if frame.keyframe {
1428 return true;
1429 }
1430 let Some(cap) = fragment_duration else {
1431 return false;
1432 };
1433 let mut ptss = std::iter::once(frame)
1436 .chain(&batch.frames)
1437 .filter_map(|f| crate::container::time(f.timestamp));
1438 let Some(first) = ptss.next() else {
1439 return false;
1440 };
1441 let (min, max) = ptss.fold((first, first), |(min, max), pts| (min.min(pts), max.max(pts)));
1442 max.saturating_sub(min) >= cap
1443}
1444
1445fn encode_fragment(
1453 track: &mut Fmp4Track,
1454 sequence_number: &mut u32,
1455 frames: Vec<Frame>,
1456 opens_gop: bool,
1457) -> Result<Bytes> {
1458 let Some(first) = frames.first() else {
1459 return Err(Error::NoFrames.into());
1460 };
1461 let timescale = moq_net::Timescale::new(track.timescale)?;
1462 let base_dts = match track.decode_end {
1463 Some(end) if !opens_gop => end,
1464 _ => super::base_ticks(first, timescale)?,
1465 };
1466 let info = crate::container::fmp4::FragmentInfo {
1467 track_id: track.track_id,
1468 timescale,
1469 sequence_number: *sequence_number,
1470 kind: if track.is_video {
1471 super::Kind::Video
1472 } else {
1473 super::Kind::Audio
1474 },
1475 };
1476 let (data, decode_end) = super::encode_at(info, base_dts, &frames)?;
1477 *sequence_number += 1;
1478 track.decode_end = Some(decode_end);
1479 Ok(data)
1480}
1481
1482fn emit_fragment(
1488 name: &str,
1489 track: &mut Fmp4Track,
1490 sequence_number: &mut u32,
1491 batch: Batch,
1492 successor: Option<&Frame>,
1493) -> Result<Fragment> {
1494 let Batch {
1495 mut frames,
1496 independent,
1497 } = batch;
1498 apply_codec_durations(&mut frames, track.opus);
1499 let partial = !independent || successor.is_some_and(|next| !next.keyframe);
1501 let independent = !track.is_video || independent;
1504 if let (Some(first), Some(written)) = (frames.first(), track.written) {
1505 let start = Duration::try_from(first.timestamp)?;
1506 if independent && start <= written {
1507 return Err(Error::TrackRewound {
1508 track: name.to_string(),
1509 start,
1510 written,
1511 }
1512 .into());
1513 }
1514 }
1515 for frame in &frames {
1516 track.written = track.written.max(Some(Duration::try_from(frame.timestamp)?));
1517 }
1518 let timescale = moq_net::Timescale::new(track.timescale)?;
1519 let run = if partial && track.config.may_reorder() {
1520 Run::PartialGop
1521 } else {
1522 Run::Whole
1523 };
1524 infer_missing_durations(&mut frames, successor, track.default_frame, timescale, run)?;
1525 let duration = fragment_duration(&frames, track.default_frame, timescale)?;
1526 let data = encode_fragment(track, sequence_number, frames, independent)?;
1527 Ok(Fragment {
1528 data,
1529 independent,
1530 duration,
1531 })
1532}
1533
1534fn fragment_duration(frames: &[Frame], default_frame: Duration, timescale: moq_net::Timescale) -> Result<Duration> {
1541 if frames.is_empty() {
1542 return Ok(Duration::ZERO);
1543 }
1544 if frames
1545 .iter()
1546 .all(|f| f.duration.is_some_and(|duration| !duration.is_zero()))
1547 {
1548 let ticks = frames.iter().try_fold(0u64, |sum, frame| -> Result<u64> {
1550 let ticks = super::trun_duration(frame.duration.unwrap(), timescale)?;
1551 sum.checked_add(u64::from(ticks))
1552 .ok_or_else(|| moq_net::TimeOverflow.into())
1553 })?;
1554 return Ok(Timestamp::new(ticks, timescale)?.try_into()?);
1555 }
1556 let mut min = Duration::MAX;
1557 let mut max = Duration::ZERO;
1558 for f in frames {
1559 let pts = Duration::try_from(f.timestamp)?;
1560 min = min.min(pts);
1561 max = max.max(pts);
1562 }
1563 Ok((max - min) + default_frame)
1564}
1565
1566pub(crate) fn apply_codec_durations(frames: &mut [Frame], opus: bool) {
1574 if !opus {
1575 return;
1576 }
1577 for frame in frames {
1578 if frame.duration.is_none() {
1579 frame.duration = crate::codec::opus::packet_samples(&frame.payload)
1580 .and_then(|samples| Timestamp::from_scale(samples as u64, 48_000).ok());
1581 }
1582 }
1583}
1584
1585pub(crate) fn infer_missing_durations(
1613 frames: &mut [Frame],
1614 successor: Option<&Frame>,
1615 default_frame: Duration,
1616 timescale: moq_net::Timescale,
1617 run: Run,
1618) -> Result<()> {
1619 let infer_from_pts = pts_monotonic(frames, successor);
1620 let cadence = fallback_duration(default_frame, timescale);
1621
1622 for i in 0..frames.len() {
1623 let successor = infer_from_pts
1624 .then(|| duration_bound(frames, successor, i))
1625 .flatten()
1626 .cloned();
1627 let stated = frames[i].duration.is_some_and(|duration| !duration.is_zero());
1628 infer_missing_duration(&mut frames[i], successor.as_ref(), default_frame, timescale)?;
1629 if run == Run::PartialGop
1630 && !stated
1631 && let (Some(inferred), Some(cadence)) = (frames[i].duration, cadence)
1632 && let (Some(longer), Some(shorter)) = (crate::container::time(inferred), crate::container::time(cadence))
1633 && longer > shorter
1634 {
1635 frames[i].duration = Some(cadence);
1636 }
1637 }
1638
1639 Ok(())
1640}
1641
1642#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1644pub(crate) enum Run {
1645 Whole,
1648 PartialGop,
1651}
1652
1653pub(crate) fn infer_missing_duration(
1655 frame: &mut Frame,
1656 successor: Option<&Frame>,
1657 default_frame: Duration,
1658 timescale: moq_net::Timescale,
1659) -> Result<()> {
1660 if frame.duration.is_some_and(|duration| !duration.is_zero()) {
1661 return Ok(());
1662 }
1663
1664 frame.duration = match successor {
1665 Some(next) => timestamp_gap(frame.timestamp, next.timestamp, timescale)?,
1666 None => None,
1667 }
1668 .or_else(|| fallback_duration(default_frame, timescale))
1669 .filter(|duration| !duration.is_zero());
1670 Ok(())
1671}
1672
1673fn fallback_duration(default_frame: Duration, timescale: moq_net::Timescale) -> Option<Timestamp> {
1676 if let Some(ticks) = super::rounded_duration_ticks(default_frame, timescale.as_u64()) {
1677 Timestamp::new(ticks, timescale).ok()
1678 } else {
1679 Timestamp::try_from(default_frame).ok()
1680 }
1681}
1682
1683pub(super) fn timestamp_gap(
1692 start: Timestamp,
1693 end: Timestamp,
1694 timescale: moq_net::Timescale,
1695) -> Result<Option<Timestamp>> {
1696 let start_ticks = super::timestamp_ticks(start, timescale)?;
1697 let end_ticks = super::timestamp_ticks(end, timescale)?;
1698 match end_ticks.checked_sub(start_ticks) {
1699 Some(ticks) if ticks > 0 => Ok(Some(Timestamp::new(ticks, timescale)?)),
1700 _ => Ok(None),
1701 }
1702}
1703
1704fn pts_monotonic(frames: &[Frame], successor: Option<&Frame>) -> bool {
1705 let frames_monotonic = frames.windows(2).all(|pair| pair[1].timestamp >= pair[0].timestamp);
1706 let successor_monotonic = match (frames.last(), successor.filter(|next| !next.keyframe)) {
1709 (Some(last), Some(successor)) => successor.timestamp >= last.timestamp,
1710 _ => true,
1711 };
1712 frames_monotonic && successor_monotonic
1713}
1714
1715fn duration_bound<'a>(frames: &'a [Frame], successor: Option<&'a Frame>, index: usize) -> Option<&'a Frame> {
1724 frames.get(index + 1).or(successor).filter(|next| !next.keyframe)
1725}
1726
1727pub(crate) fn catalog_timescale_video(config: &VideoConfig) -> Result<u64> {
1728 Ok(match &config.container {
1729 Container::Cmaf { init, .. } => {
1730 parse_timescale_from_init(init).unwrap_or_else(|_| crate::container::fmp4::default_video_timescale(config))
1731 }
1732 Container::Loc | Container::Legacy | Container::Raw | Container::Cts => {
1733 crate::container::fmp4::default_video_timescale(config)
1734 }
1735 Container::Unknown(unknown) => return Err(crate::Error::unsupported_container(unknown)),
1736 })
1737}
1738
1739pub(crate) fn catalog_timescale_audio(config: &hang::catalog::AudioConfig) -> Result<u64> {
1740 Ok(match &config.container {
1741 Container::Cmaf { init, .. } => parse_timescale_from_init(init).unwrap_or(config.sample_rate as u64),
1742 Container::Loc | Container::Legacy | Container::Raw | Container::Cts => config.sample_rate as u64,
1743 Container::Unknown(unknown) => return Err(crate::Error::unsupported_container(unknown)),
1744 })
1745}
1746
1747fn parse_timescale_from_init(init: &[u8]) -> Result<u64> {
1748 let mut cursor = std::io::Cursor::new(init);
1749 while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).map_err(crate::Error::mp4)? {
1750 if let mp4_atom::Any::Moov(moov) = atom {
1751 let trak = moov.trak.first().ok_or(Error::NoTracks)?;
1752 return Ok(trak.mdia.mdhd.timescale as u64);
1753 }
1754 }
1755 Err(Error::NoMoov.into())
1756}
1757
1758#[cfg(test)]
1759mod tests {
1760 use bytes::Bytes;
1761
1762 use super::*;
1763
1764 fn ts(micros: u64) -> Timestamp {
1765 Timestamp::from_micros(micros).unwrap()
1766 }
1767
1768 fn duration_micros(frame: &Frame) -> u128 {
1769 frame.duration.unwrap().as_micros().unwrap()
1770 }
1771
1772 fn frame(timestamp_us: u64, duration_us: Option<u64>) -> Frame {
1773 Frame {
1774 timestamp: ts(timestamp_us),
1775 decode: None,
1776 duration: duration_us.map(ts),
1777 payload: Bytes::from_static(&[0xDE, 0xAD]),
1778 keyframe: false,
1779 }
1780 }
1781
1782 #[test]
1784 fn closing_a_closed_buffer_keeps_its_frames() {
1785 let mut buffer = Buffer::Empty;
1786 buffer.push(group_start(0));
1787 buffer.close();
1788 buffer.close();
1789 assert!(buffer.is_closed());
1790 assert_eq!(buffer.take().map(|batch| batch.frames.len()), Some(1));
1791 }
1792
1793 fn group_start(timestamp_us: u64) -> Frame {
1796 Frame {
1797 keyframe: true,
1798 ..frame(timestamp_us, None)
1799 }
1800 }
1801
1802 #[test]
1803 fn infer_missing_durations_uses_default_for_trailing_sample() {
1804 let mut frames = vec![frame(0, Some(0)), frame(41_667, None), frame(83_334, None)];
1805 infer_missing_durations(
1806 &mut frames,
1807 None,
1808 Duration::from_millis(33),
1809 moq_net::Timescale::MICRO,
1810 Run::Whole,
1811 )
1812 .unwrap();
1813
1814 assert_eq!(frames[0].duration, Some(ts(41_667)));
1815 assert_eq!(frames[1].duration, Some(ts(41_667)));
1816 assert_eq!(frames[2].duration, Some(ts(33_000)));
1817 assert_eq!(
1818 fragment_duration(
1819 &frames,
1820 Duration::from_millis(33),
1821 frames[0].duration.unwrap().scale().unwrap()
1822 )
1823 .unwrap(),
1824 Duration::from_micros(116_334)
1825 );
1826 }
1827
1828 #[test]
1829 fn infer_missing_duration_uses_default_for_single_frame() {
1830 let mut frames = vec![frame(83_333, Some(0))];
1831 infer_missing_durations(
1832 &mut frames,
1833 None,
1834 Duration::from_millis(40),
1835 moq_net::Timescale::MICRO,
1836 Run::Whole,
1837 )
1838 .unwrap();
1839
1840 assert_eq!(frames[0].duration, Some(ts(40_000)));
1841 assert_eq!(
1842 fragment_duration(
1843 &frames,
1844 Duration::from_millis(40),
1845 frames[0].duration.unwrap().scale().unwrap()
1846 )
1847 .unwrap(),
1848 Duration::from_millis(40)
1849 );
1850 }
1851
1852 #[test]
1856 fn infer_trailing_duration_from_successor_frame() {
1857 let successor = frame(83_334, None);
1858 let mut frames = vec![frame(41_667, None)];
1859 infer_missing_durations(
1860 &mut frames,
1861 Some(&successor),
1862 Duration::from_millis(33),
1863 moq_net::Timescale::MICRO,
1864 Run::Whole,
1865 )
1866 .unwrap();
1867
1868 assert_eq!(frames[0].duration, Some(ts(41_667)));
1869 assert_eq!(
1870 fragment_duration(
1871 &frames,
1872 Duration::from_millis(33),
1873 frames[0].duration.unwrap().scale().unwrap()
1874 )
1875 .unwrap(),
1876 Duration::from_micros(41_667)
1877 );
1878 }
1879
1880 #[test]
1884 fn a_partial_gop_caps_inferred_durations_at_the_cadence() {
1885 let successor = frame(100_000, None);
1886 let mut frames = vec![frame(0, Some(50_000)), frame(10_000, None), frame(20_000, None)];
1887 infer_missing_durations(
1888 &mut frames,
1889 Some(&successor),
1890 Duration::from_millis(33),
1891 moq_net::Timescale::MICRO,
1892 Run::PartialGop,
1893 )
1894 .unwrap();
1895
1896 let durations: Vec<_> = frames.iter().map(duration_micros).collect();
1897 assert_eq!(durations, vec![50_000, 10_000, 33_000]);
1898 }
1899
1900 #[test]
1904 fn inferred_microsecond_clock_carries_fractional_ticks_forward() {
1905 let timescale = moq_net::Timescale::new(30_000).unwrap();
1906 let mut frames = vec![
1907 frame(0, None),
1908 frame(33_333, None),
1909 frame(66_667, None),
1910 frame(66_678, None),
1911 ];
1912 infer_missing_durations(
1913 &mut frames,
1914 None,
1915 Duration::from_nanos(33_333_333),
1916 timescale,
1917 Run::Whole,
1918 )
1919 .unwrap();
1920
1921 let durations: Vec<_> = frames
1922 .iter()
1923 .map(|frame| {
1924 let duration = frame.duration.unwrap();
1925 (duration.value(), duration.scale())
1926 })
1927 .collect();
1928 assert_eq!(durations, vec![(1_000, Some(timescale)); 4]);
1929 }
1930
1931 #[test]
1936 fn infer_stops_at_a_group_boundary() {
1937 let next_group = group_start(2_405_070_000);
1938 let mut frames = vec![frame(63_244, None)];
1939 infer_missing_durations(
1940 &mut frames,
1941 Some(&next_group),
1942 Duration::from_millis(33),
1943 moq_net::Timescale::MICRO,
1944 Run::Whole,
1945 )
1946 .unwrap();
1947
1948 assert_eq!(frames[0].duration, Some(ts(33_000)));
1949 assert_eq!(
1950 fragment_duration(
1951 &frames,
1952 Duration::from_millis(33),
1953 frames[0].duration.unwrap().scale().unwrap()
1954 )
1955 .unwrap(),
1956 Duration::from_millis(33)
1957 );
1958 }
1959
1960 #[test]
1964 fn infer_stops_at_an_interior_group_boundary() {
1965 let mut frames = vec![frame(0, None), frame(21_333, None), group_start(600_000_000)];
1966 infer_missing_durations(
1967 &mut frames,
1968 None,
1969 Duration::from_millis(21),
1970 moq_net::Timescale::MICRO,
1971 Run::Whole,
1972 )
1973 .unwrap();
1974
1975 assert_eq!(frames[0].duration, Some(ts(21_333)), "same group, real delta");
1976 assert_eq!(duration_micros(&frames[1]), 21_000, "bounded by the next group");
1977 assert_eq!(duration_micros(&frames[2]), 21_000, "nothing after it at all");
1978 }
1979
1980 #[test]
1985 fn codec_durations_keep_one_packet_groups_exact() {
1986 let packet = Bytes::from_static(&[0x78, 0x00, 0x00, 0x00]);
1988 let mut frames: Vec<Frame> = (0..3)
1989 .map(|i| Frame {
1990 payload: packet.clone(),
1991 ..group_start(i * 20_000)
1992 })
1993 .collect();
1994
1995 apply_codec_durations(&mut frames, true);
1996 infer_missing_durations(
1997 &mut frames,
1998 None,
1999 Duration::from_micros(21_333),
2000 moq_net::Timescale::MICRO,
2001 Run::Whole,
2002 )
2003 .unwrap();
2004
2005 for f in &frames {
2006 assert_eq!(
2007 f.duration.unwrap().as_micros().unwrap(),
2008 20_000,
2009 "TOC duration, not the fallback"
2010 );
2011 }
2012 }
2013
2014 #[test]
2017 fn infer_ignores_a_rewound_group_boundary() {
2018 let next_group = group_start(0);
2019 let mut frames = vec![frame(1_000_000, None), frame(1_033_000, None)];
2020 infer_missing_durations(
2021 &mut frames,
2022 Some(&next_group),
2023 Duration::from_millis(50),
2024 moq_net::Timescale::MICRO,
2025 Run::Whole,
2026 )
2027 .unwrap();
2028
2029 assert_eq!(
2030 frames[0].duration,
2031 Some(ts(33_000)),
2032 "in-group delta survives the rewind"
2033 );
2034 assert_eq!(duration_micros(&frames[1]), 50_000, "last in group falls back");
2035 }
2036
2037 #[test]
2038 fn infer_missing_durations_avoids_non_monotonic_pts() {
2039 let successor = frame(66_000, None);
2040 let mut frames = vec![frame(0, None), frame(99_000, None), frame(33_000, None)];
2041 infer_missing_durations(
2042 &mut frames,
2043 Some(&successor),
2044 Duration::from_millis(33),
2045 moq_net::Timescale::MICRO,
2046 Run::Whole,
2047 )
2048 .unwrap();
2049
2050 assert_eq!(frames[0].duration, Some(ts(33_000)));
2051 assert_eq!(frames[1].duration, Some(ts(33_000)));
2052 assert_eq!(frames[2].duration, Some(ts(33_000)));
2053 assert_eq!(
2054 fragment_duration(
2055 &frames,
2056 Duration::from_millis(33),
2057 frames[0].duration.unwrap().scale().unwrap()
2058 )
2059 .unwrap(),
2060 Duration::from_micros(99_000)
2061 );
2062 }
2063
2064 #[test]
2067 fn extract_init_strips_edit_lists() {
2068 use mp4_atom::Encode;
2069
2070 let trak = mp4_atom::Trak {
2071 edts: Some(mp4_atom::Edts {
2072 elst: Some(mp4_atom::Elst {
2073 entries: vec![mp4_atom::ElstEntry::default()],
2074 }),
2075 }),
2076 ..Default::default()
2077 };
2078 let moov = mp4_atom::Moov {
2079 trak: vec![trak],
2080 ..Default::default()
2081 };
2082 let mut init = Vec::new();
2083 moov.encode(&mut init).unwrap();
2084
2085 let mut traks = Vec::new();
2086 let mut trexs = Vec::new();
2087 let mut ftyp = None;
2088 extract_init(&Bytes::from(init), 1, &mut ftyp, &mut traks, &mut trexs).unwrap();
2089
2090 assert_eq!(traks.len(), 1);
2091 assert!(traks[0].edts.is_none(), "the source edit must not be applied twice");
2092 }
2093
2094 #[test]
2098 fn extract_init_clears_a_stale_track_duration() {
2099 use mp4_atom::Encode;
2100
2101 let moov = mp4_atom::Moov {
2102 mvhd: mp4_atom::Mvhd {
2103 timescale: 1_000,
2104 ..Default::default()
2105 },
2106 trak: vec![mp4_atom::Trak {
2107 tkhd: mp4_atom::Tkhd {
2108 duration: 30_000, ..Default::default()
2110 },
2111 mdia: mp4_atom::Mdia {
2112 mdhd: mp4_atom::Mdhd {
2113 timescale: 48_000,
2114 ..Default::default()
2115 },
2116 ..Default::default()
2117 },
2118 ..Default::default()
2119 }],
2120 ..Default::default()
2121 };
2122 let mut init = Vec::new();
2123 moov.encode(&mut init).unwrap();
2124
2125 let mut traks = Vec::new();
2126 let mut trexs = Vec::new();
2127 let mut ftyp = None;
2128 extract_init(&Bytes::from(init), 1, &mut ftyp, &mut traks, &mut trexs).unwrap();
2129
2130 assert_eq!(traks.len(), 1);
2131 assert_eq!(
2132 traks[0].tkhd.duration,
2133 u64::MAX,
2134 "a live fragmented init declares an unknown duration"
2135 );
2136 }
2137}