moq_ext_publisher/publish/spec.rs
1//! Publishing what a [`MediaSpec`] names, opened and set in one call.
2
3use moq_ext_sources::{
4 AudioSource, Error, VideoSource,
5 spec::{AudioSourceSpec, MediaSpec, VideoOpenOptions},
6};
7#[cfg(feature = "file")]
8use moq_ext_sources::{EncodedAudio, EncodedVideo, MediaFile, spec::VideoSourceSpec};
9#[cfg(feature = "file")]
10use tracing::{debug, warn};
11
12use super::{AudioEncoding, LocalBroadcast, VideoEncoding, music, pcm, voice};
13
14/// How [`LocalBroadcast::set_spec`] encodes the sources it opens.
15#[derive(Debug, Clone)]
16#[non_exhaustive]
17pub struct MediaEncoding {
18 /// The renditions of a raw video source.
19 pub video: VideoEncoding,
20 /// The encoding of a raw audio source.
21 ///
22 /// `None` picks [`voice`] for a microphone and [`music`] for anything
23 /// else. A PCM encoding takes the rate and layout of a source that
24 /// reports them, so the samples go out as they come in.
25 pub audio: Option<AudioEncoding>,
26}
27
28impl MediaEncoding {
29 /// Creates an encoding of `video`, with the audio encoding picked by the source.
30 #[must_use]
31 pub fn new(video: VideoEncoding) -> Self {
32 Self { video, audio: None }
33 }
34
35 /// Returns this encoding with `audio` as the audio encoding.
36 #[must_use]
37 pub fn with_audio(mut self, audio: impl Into<AudioEncoding>) -> Self {
38 self.audio = Some(audio.into());
39 self
40 }
41
42 /// Returns the encoding of `source`, which `spec` names.
43 fn audio_for(&self, spec: Option<&AudioSourceSpec>, source: &AudioSource) -> AudioEncoding {
44 let encoding = self.audio.clone().unwrap_or_else(|| match spec {
45 Some(AudioSourceSpec::Microphone(_)) => voice(),
46 _ => music(),
47 });
48 match source.format() {
49 Some(format) if encoding.config.codec == moq_audio::encode::Codec::Pcm => {
50 pcm(format).with_group_span(encoding.group_span)
51 }
52 _ => encoding,
53 }
54 }
55}
56
57impl Default for MediaEncoding {
58 /// Returns the default [`VideoEncoding`], with the audio encoding picked by the source.
59 fn default() -> Self {
60 Self::new(VideoEncoding::default())
61 }
62}
63
64impl From<VideoEncoding> for MediaEncoding {
65 fn from(video: VideoEncoding) -> Self {
66 Self::new(video)
67 }
68}
69
70/// The video a spec names, opened.
71enum Video {
72 /// No video.
73 Clear,
74 /// Raw pictures, for the encoder.
75 Raw(VideoSource),
76 /// A file's H.264, as it is stored.
77 #[cfg(feature = "file")]
78 Encoded(EncodedVideo),
79}
80
81/// The audio a spec names, opened.
82enum Audio {
83 /// The audio as it is.
84 Keep,
85 /// No audio.
86 Clear,
87 /// Raw samples, for the encoder.
88 Raw(AudioSource),
89 /// A file's AAC, as it is stored.
90 #[cfg(feature = "file")]
91 Encoded(EncodedAudio),
92}
93
94impl LocalBroadcast {
95 /// Opens the sources `spec` names with default options and publishes them.
96 ///
97 /// The same as [`set_spec_with`](Self::set_spec_with) with the default
98 /// [`VideoOpenOptions`]. See there for what opens and what it replaces.
99 ///
100 /// # Errors
101 ///
102 /// As [`set_spec_with`](Self::set_spec_with).
103 ///
104 /// # Panics
105 ///
106 /// Panics when called outside a Tokio runtime.
107 ///
108 /// # Examples
109 ///
110 /// ```no_run
111 /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
112 /// use moq_ext_publisher::{LocalBroadcast, MediaEncoding};
113 /// use moq_ext_sources::spec::MediaSpec;
114 ///
115 /// let broadcast = LocalBroadcast::new();
116 /// broadcast.set_spec(&MediaSpec::test(), MediaEncoding::default()).await?;
117 /// # Ok(())
118 /// # }
119 /// ```
120 pub async fn set_spec(
121 &self,
122 spec: &MediaSpec,
123 encoding: impl Into<MediaEncoding>,
124 ) -> Result<(), Error> {
125 let options = VideoOpenOptions::default();
126 self.set_spec_with(spec, &options, encoding).await
127 }
128
129 /// Opens the sources `spec` names with `options` and publishes them.
130 ///
131 /// The video opens with `options` and its raw pictures encode into
132 /// `encoding.video`. A `file:` video goes out as it is stored, its H.264
133 /// in one rendition, unless [`MediaSpec::reencode`] decodes it into the
134 /// renditions. Without [`MediaSpec::audio`], a `file:` video brings the
135 /// file's own audio, passed through or decoded as the video is, and any
136 /// other video leaves the audio as it is. An audio source of the video's
137 /// file plays against the file's clock, as does any file
138 /// `VideoOpenOptions::with_file` holds. The file's own audio is left out
139 /// with a warning if it does not open, for example in another codec than
140 /// AAC. Passed through, the video is left out the same way if the audio
141 /// goes out, as `set_encoded_file` does. A file without video publishes
142 /// its audio alone.
143 ///
144 /// Every source opens before any is set, so a source that fails to open
145 /// leaves the broadcast as it was. A microphone opens without echo
146 /// cancellation, as [`AudioSourceSpec::open`] does: open it with a
147 /// canceller and pass it to [`set_audio`](Self::set_audio) instead. A
148 /// passthrough file leaves [`video_source`](Self::video_source) empty.
149 ///
150 /// Cancellation safe: dropping the future drops the sources it opened.
151 ///
152 /// # Errors
153 ///
154 /// Fails if a source does not open, as
155 /// [`VideoSourceSpec::open`](moq_ext_sources::spec::VideoSourceSpec::open)
156 /// and [`AudioSourceSpec::open`] do, with [`Error::InvalidConfig`] for a
157 /// file that has neither video nor audio while the spec names no other
158 /// audio, for a file whose video does not open and whose own audio does
159 /// not go out instead, for an encoding that [`set_video`](Self::set_video)
160 /// or [`set_audio`](Self::set_audio) refuses, and with [`Error::Closed`]
161 /// after [`close`](Self::close).
162 ///
163 /// # Panics
164 ///
165 /// Panics when called outside a Tokio runtime.
166 ///
167 /// # Examples
168 ///
169 /// ```no_run
170 /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
171 /// use moq_ext_publisher::{LocalBroadcast, VideoEncoding, VideoRendition};
172 /// use moq_ext_sources::spec::{AudioSourceSpec, MediaSpec, TestTone, VideoOpenOptions};
173 ///
174 /// let broadcast = LocalBroadcast::new();
175 /// let spec = MediaSpec::new("test:bounce".parse()?)
176 /// .with_audio(AudioSourceSpec::Test(TestTone::Beeps));
177 /// let encoding = VideoEncoding::single(VideoRendition::p360());
178 /// let options = VideoOpenOptions::default().with_size(moq_video::Size::new(640, 360));
179 /// broadcast.set_spec_with(&spec, &options, encoding).await?;
180 /// # Ok(())
181 /// # }
182 /// ```
183 pub async fn set_spec_with(
184 &self,
185 spec: &MediaSpec,
186 options: &VideoOpenOptions,
187 encoding: impl Into<MediaEncoding>,
188 ) -> Result<(), Error> {
189 self.check_open()?;
190 let encoding = encoding.into();
191 let (video, audio) = open(spec, options).await?;
192 // The audio is set first and refuses a bad encoding before anything
193 // changes, so the video is checked before it.
194 if let Video::Raw(source) = &video {
195 encoding.video.validate(source.format().rate)?;
196 }
197 match audio {
198 Audio::Keep => {}
199 Audio::Clear => self.clear_audio(),
200 Audio::Raw(source) => {
201 let audio = encoding.audio_for(spec.audio.as_ref(), &source);
202 self.set_audio(source, audio)?;
203 }
204 #[cfg(feature = "file")]
205 Audio::Encoded(source) => self.set_encoded_audio(source)?,
206 }
207 match video {
208 Video::Clear => self.clear_video(),
209 Video::Raw(source) => self.set_video(source, encoding.video)?,
210 #[cfg(feature = "file")]
211 Video::Encoded(source) => self.set_encoded_video(source)?,
212 }
213 Ok(())
214 }
215}
216
217/// Opens the video and the audio `spec` names.
218async fn open(spec: &MediaSpec, options: &VideoOpenOptions) -> Result<(Video, Audio), Error> {
219 #[cfg(feature = "file")]
220 if let VideoSourceSpec::File { path, looping } = &spec.video {
221 let file = options
222 .open_file(path, moq_ext_sources::FileEnd::looping(*looping))
223 .await?;
224 return open_file(spec, options, file).await;
225 }
226 let video = match spec.video.open(options).await? {
227 Some(source) => Video::Raw(source),
228 None => Video::Clear,
229 };
230 let audio = match &spec.audio {
231 None => Audio::Keep,
232 Some(audio) => open_audio(audio, options).await?,
233 };
234 Ok((video, audio))
235}
236
237/// Opens the video of `file`, which `spec` names, and the audio that goes with it.
238#[cfg(feature = "file")]
239async fn open_file(
240 spec: &MediaSpec,
241 options: &VideoOpenOptions,
242 file: MediaFile,
243) -> Result<(Video, Audio), Error> {
244 if file.info().video.is_none() && file.info().audio.is_none() && spec.audio.is_none() {
245 return Err(Error::invalid(format!(
246 "{} has neither video nor audio",
247 file.path().display()
248 )));
249 }
250 let video = match (&file.info().video, spec.reencode) {
251 (None, _) => Ok(Video::Clear),
252 (Some(_), false) => file.encoded_video().map(Video::Encoded),
253 (Some(_), true) => file.video(Default::default()).await.map(Video::Raw),
254 };
255 // An audio source of the video's file shares its clock.
256 let options = options.clone().with_file(file.clone());
257 let audio = match &spec.audio {
258 Some(audio) => open_audio(audio, &options).await?,
259 None if file.info().audio.is_none() => {
260 debug!(path = %file.path().display(), "the file has no audio");
261 Audio::Clear
262 }
263 None => {
264 let audio = if spec.reencode {
265 file.audio().map(Audio::Raw)
266 } else {
267 file.encoded_audio().map(Audio::Encoded)
268 };
269 match (audio, &video) {
270 (Ok(audio), _) => audio,
271 (Err(err), Ok(_)) => {
272 warn!(error = %err, "publishing the file's video without its audio");
273 Audio::Clear
274 }
275 (Err(_), Err(_)) => Audio::Clear,
276 }
277 }
278 };
279 // A passthrough file whose own audio goes out stays up without its video.
280 let video = match video {
281 Err(err) if !spec.reencode && matches!(audio, Audio::Encoded(_)) => {
282 warn!(error = %err, "publishing the file's audio without its video");
283 Video::Clear
284 }
285 video => video?,
286 };
287 Ok((video, audio))
288}
289
290/// Opens the audio source `spec` names, a file through the one `options` holds if the paths match.
291#[cfg_attr(
292 not(feature = "file"),
293 expect(unused_variables, reason = "only a file reads the options")
294)]
295async fn open_audio(spec: &AudioSourceSpec, options: &VideoOpenOptions) -> Result<Audio, Error> {
296 #[cfg(feature = "file")]
297 if let AudioSourceSpec::File { path, looping } = spec {
298 let file = options
299 .open_file(path, moq_ext_sources::FileEnd::looping(*looping))
300 .await?;
301 return file.audio().map(Audio::Raw);
302 }
303 Ok(match spec.open().await? {
304 Some(source) => Audio::Raw(source),
305 None => Audio::Clear,
306 })
307}