Skip to main content

moq_mux/container/
writer.rs

1use moq_net::frame::Frame;
2/// Where a [`Container`](super::Container) writes a group's frames: the group, or the track whose
3/// next group the first frame creates, keyed by that frame's timestamp.
4pub struct Writer<'a> {
5	track: &'a moq_net::track::Producer,
6	group: &'a mut Option<moq_net::group::Producer>,
7	/// How the first frame creates the group, for tests.
8	#[cfg(test)]
9	open: Open,
10}
11
12impl<'a> Writer<'a> {
13	/// Write into `group`, appending one to `track` with the first frame while it is `None`.
14	pub fn new(track: &'a moq_net::track::Producer, group: &'a mut Option<moq_net::group::Producer>) -> Self {
15		Self {
16			track,
17			group,
18			#[cfg(test)]
19			open: Open::Append,
20		}
21	}
22
23	/// [`Self::new`], opening the group as `open` says so a test can write groups out of order.
24	#[cfg(test)]
25	pub(crate) fn opening(
26		track: &'a moq_net::track::Producer,
27		group: &'a mut Option<moq_net::group::Producer>,
28		open: Open,
29	) -> Self {
30		Self { track, group, open }
31	}
32
33	/// Write a frame, appending the group to the track with it when it is the first.
34	pub fn write_frame<B: moq_net::IntoBytes>(
35		&mut self,
36		timestamp: moq_net::Timestamp,
37		data: B,
38	) -> moq_net::Result<()> {
39		match self.group {
40			Some(group) => group.write_frame(Frame::new(timestamp, data)),
41			None => {
42				#[cfg(test)]
43				match self.open {
44					Open::Append => {}
45					Open::Create => {
46						*self.group = Some(self.track.create_group(Frame::new(timestamp, data))?);
47						return Ok(());
48					}
49					Open::Follow => {
50						let key = self.track.info().rescale(timestamp)?.value();
51						let from = self.track.largest().map_or(0, |largest| largest.group + 1);
52						if from < key {
53							self.track.skip_groups(from..key);
54						}
55						*self.group = Some(self.track.create_group(Frame::new(timestamp, data))?);
56						return Ok(());
57					}
58				}
59				*self.group = Some(self.track.append_group(Frame::new(timestamp, data))?);
60				Ok(())
61			}
62		}
63	}
64
65	/// The newest timestamp the group holds, `None` before its first frame.
66	pub fn latest(&self) -> Option<moq_net::Timestamp> {
67		self.group.as_ref().and_then(|group| group.latest())
68	}
69
70	/// How many frames the group holds.
71	pub fn frame_count(&self) -> usize {
72		self.group.as_ref().map_or(0, |group| group.frame_count())
73	}
74
75	/// The track's timescale, which every frame timestamp is converted into.
76	pub fn timescale(&self) -> Option<moq_net::Timescale> {
77		self.track.info().timescale
78	}
79}
80
81/// How a test's first frame creates its group.
82#[cfg(test)]
83#[derive(Clone, Copy)]
84pub(crate) enum Open {
85	/// `append_group`, skipping every start it passes.
86	Append,
87	/// `create_group`, leaving the starts around it unproduced.
88	Create,
89	/// `create_group`, skipping the starts between the newest group and it.
90	Follow,
91}