moq_ext_publisher/publish/
encoding.rs1use std::{collections::BTreeSet, time::Duration};
4
5use moq_ext_sources::{AudioFormat, Error};
6use moq_net::bandwidth::Rate;
7
8const OPUS_FRAMES_MICROS: [u128; 6] = [2_500, 5_000, 10_000, 20_000, 40_000, 60_000];
13
14#[derive(Debug, Clone)]
16#[non_exhaustive]
17pub struct VideoEncoding {
18 pub renditions: Vec<VideoRendition>,
20 pub record_timestamps: bool,
31}
32
33impl VideoEncoding {
34 #[must_use]
36 pub fn single(rendition: VideoRendition) -> Self {
37 Self::ladder([rendition])
38 }
39
40 #[must_use]
42 pub fn ladder(renditions: impl IntoIterator<Item = VideoRendition>) -> Self {
43 Self {
44 renditions: renditions.into_iter().collect(),
45 record_timestamps: false,
46 }
47 }
48
49 #[must_use]
51 pub fn with_recorded_timestamps(mut self) -> Self {
52 self.record_timestamps = true;
53 self
54 }
55
56 pub(crate) fn validate(&self, source: moq_video::FrameRate) -> Result<(), Error> {
58 if self.renditions.is_empty() {
59 return Err(Error::invalid(
60 "a video encoding needs at least one rendition",
61 ));
62 }
63 let mut seen = BTreeSet::new();
64 for rendition in &self.renditions {
65 if rendition.name.is_empty() {
66 return Err(Error::invalid("a rendition name cannot be empty"));
67 }
68 if !seen.insert(rendition.name.as_str()) {
69 return Err(Error::invalid(format!(
70 "two renditions are named {}",
71 rendition.name
72 )));
73 }
74 if let Some(size) = rendition.size
75 && (size.width == 0
76 || size.height == 0
77 || size.width % 2 == 1
78 || size.height % 2 == 1)
79 {
80 return Err(Error::invalid(format!(
81 "rendition {} has size {size}, but both sides must be even and non-zero",
82 rendition.name
83 )));
84 }
85 if let Some(rate) = rendition.rate
86 && rate.as_f64() > source.as_f64()
87 {
88 return Err(Error::invalid(format!(
89 "rendition {} asks for {rate} fps from a source that runs at {source}",
90 rendition.name
91 )));
92 }
93 if rendition.config.join.is_zero() {
94 return Err(Error::invalid(format!(
95 "rendition {} has a zero keyframe interval",
96 rendition.name
97 )));
98 }
99 if rendition.config.codec == moq_video::encode::Codec::H265
102 && rendition.config.backend == moq_video::encode::Backend::Software
103 {
104 return Err(n0_error::e!(Error::NoEncoder {
105 codec: "H.265 in software".to_string()
106 }));
107 }
108 }
109 Ok(())
110 }
111}
112
113impl Default for VideoEncoding {
114 fn default() -> Self {
116 Self::single(VideoRendition::default())
117 }
118}
119
120#[derive(Debug, Clone)]
133#[non_exhaustive]
134pub struct VideoRendition {
135 pub name: String,
137 pub size: Option<moq_video::Size>,
139 pub rate: Option<moq_video::FrameRate>,
141 pub config: moq_video::encode::Config,
143}
144
145impl VideoRendition {
146 #[must_use]
151 pub fn new(name: impl Into<String>) -> Self {
152 let rate = moq_video::FrameRate::new(30, 1).expect("30 fps is a valid rate");
153 Self {
154 name: name.into(),
155 size: None,
156 rate: None,
157 config: moq_video::encode::Config::new(0, 0, rate),
159 }
160 }
161
162 #[must_use]
164 pub fn with_size(mut self, size: moq_video::Size) -> Self {
165 self.size = Some(size);
166 self
167 }
168
169 #[must_use]
171 pub fn with_rate(mut self, rate: moq_video::FrameRate) -> Self {
172 self.rate = Some(rate);
173 self
174 }
175
176 #[must_use]
178 pub fn p360() -> Self {
179 Self::preset("360p", 640, 360, 500)
180 }
181
182 #[must_use]
184 pub fn p720() -> Self {
185 Self::preset("720p", 1280, 720, 1_800)
186 }
187
188 fn preset(name: &str, width: u32, height: u32, kbps: u64) -> Self {
197 let mut rendition = Self::new(name);
198 rendition.size = Some(moq_video::Size::new(width, height));
199 rendition.config.bitrate = Some(Rate::from_kbps(kbps));
200 rendition
201 }
202
203 pub(crate) fn encode_config(
205 &self,
206 size: moq_video::Size,
207 rate: moq_video::FrameRate,
208 color: Option<moq_video::Color>,
209 ) -> moq_video::encode::Config {
210 let size = self.size.unwrap_or(size);
211 let mut config = self.config.clone();
212 config.width = size.width;
213 config.height = size.height;
214 config.framerate = self.rate.unwrap_or(rate);
215 config.color = config.color.or(color);
216 config.resize.get_or_insert_with(Default::default);
220 config
221 }
222}
223
224impl Default for VideoRendition {
225 fn default() -> Self {
227 Self::new("video")
228 }
229}
230
231#[derive(Debug, Clone)]
238#[non_exhaustive]
239pub struct AudioEncoding {
240 pub config: moq_audio::encode::Config,
242 pub group_span: Duration,
251}
252
253impl AudioEncoding {
254 #[must_use]
256 pub fn new(config: moq_audio::encode::Config) -> Self {
257 Self {
258 config,
259 group_span: moq_audio::encode::Options::default().join,
260 }
261 }
262
263 #[must_use]
267 pub fn with_group_span(mut self, span: Duration) -> Self {
268 self.group_span = span;
269 self
270 }
271
272 pub(crate) fn track_name(&self) -> String {
274 self.config.codec.to_string()
275 }
276
277 pub(crate) fn options(&self, track: String) -> moq_audio::encode::Options {
279 let mut options = moq_audio::encode::Options::default();
280 options.track = Some(track);
281 options.config = self.config.clone();
282 options.join = self.group_span;
283 options
284 }
285
286 pub(crate) fn validate(&self) -> Result<(), Error> {
288 let config = &self.config;
289 if config.codec == moq_audio::encode::Codec::Pcm && config.bitrate.is_some() {
290 return Err(Error::invalid(
291 "PCM's bitrate follows from its rate and layout and cannot be set",
292 ));
293 }
294 if config.frame_duration.is_zero() {
295 return Err(Error::invalid("an audio frame duration cannot be zero"));
296 }
297 if config.codec == moq_audio::encode::Codec::Opus
298 && !OPUS_FRAMES_MICROS.contains(&config.frame_duration.as_micros())
299 {
300 return Err(Error::invalid(format!(
301 "Opus encodes frames of 2.5, 5, 10, 20, 40 or 60 ms, not {:?}",
302 config.frame_duration
303 )));
304 }
305 if self.group_span.is_zero() {
306 return Err(Error::invalid("an audio group span cannot be zero"));
307 }
308 Ok(())
309 }
310}
311
312impl From<moq_audio::encode::Config> for AudioEncoding {
313 fn from(config: moq_audio::encode::Config) -> Self {
314 Self::new(config)
315 }
316}
317
318#[must_use]
320pub fn voice() -> AudioEncoding {
321 opus(moq_audio::Layout::Mono, 32)
322}
323
324#[must_use]
326pub fn music() -> AudioEncoding {
327 opus(moq_audio::Layout::Stereo, 128)
328}
329
330#[must_use]
336pub fn pcm(format: AudioFormat) -> AudioEncoding {
337 let input = moq_audio::encode::Input::new(format.sample_rate, format.layout);
338 moq_audio::encode::Config::from_input(moq_audio::encode::Codec::Pcm, &input).into()
339}
340
341fn opus(layout: moq_audio::Layout, kbps: u64) -> AudioEncoding {
343 let mut config = moq_audio::encode::Config::new(48_000, layout);
344 config.codec = moq_audio::encode::Codec::Opus;
345 config.bitrate = Some(Rate::from_kbps(kbps));
346 config.into()
347}
348
349#[cfg(test)]
350mod tests {
351 use super::*;
352
353 fn fps(n: u32) -> moq_video::FrameRate {
354 moq_video::FrameRate::new(n, 1).expect("valid")
355 }
356
357 #[test]
358 fn an_empty_ladder_is_refused() {
359 let encoding = VideoEncoding::ladder([]);
360 assert!(matches!(
361 encoding.validate(fps(30)),
362 Err(Error::InvalidConfig { .. })
363 ));
364 }
365
366 #[test]
367 fn duplicate_names_are_refused() {
368 let encoding = VideoEncoding::ladder([VideoRendition::p360(), VideoRendition::p360()]);
369 assert!(matches!(
370 encoding.validate(fps(30)),
371 Err(Error::InvalidConfig { .. })
372 ));
373 }
374
375 #[test]
376 fn a_rate_above_the_source_is_refused() {
377 let encoding = VideoEncoding::single(VideoRendition {
378 rate: Some(fps(60)),
379 ..VideoRendition::p360()
380 });
381 assert!(encoding.validate(fps(30)).is_err());
382 assert!(encoding.validate(fps(60)).is_ok());
383 }
384
385 #[test]
386 fn software_h265_has_no_encoder() {
387 let mut rendition = VideoRendition::p360();
388 rendition.config.codec = moq_video::encode::Codec::H265;
389 rendition.config.backend = moq_video::encode::Backend::Software;
390 assert!(matches!(
391 VideoEncoding::single(rendition).validate(fps(30)),
392 Err(Error::NoEncoder { .. })
393 ));
394 }
395
396 #[test]
397 fn the_keyframe_interval_sets_the_encoder_join() {
398 let mut rendition = VideoRendition::new("video");
399 rendition.config.join = Duration::from_secs(1);
400 let size = moq_video::Size::new(1280, 720);
401 for rate in [fps(30), fps(15)] {
402 let config = rendition.encode_config(size, rate, None);
403 assert_eq!(config.join, Duration::from_secs(1));
404 assert_eq!(config.effective_join(), Duration::from_secs(1));
405 }
406 }
407
408 #[test]
409 fn the_rendition_size_and_rate_override_the_source() {
410 let rendition = VideoRendition {
411 rate: Some(fps(15)),
412 ..VideoRendition::p360()
413 };
414 let config = rendition.encode_config(moq_video::Size::new(1280, 720), fps(30), None);
415 assert_eq!(config.size(), moq_video::Size::new(640, 360));
416 assert_eq!(config.framerate, fps(15));
417 assert_eq!(config.bitrate, Some(Rate::from_kbps(500)));
418 }
419
420 #[test]
421 fn the_default_encoding_is_one_rendition_at_the_source() {
422 let encoding = VideoEncoding::default();
423 assert_eq!(encoding.renditions.len(), 1);
424 let rendition = &encoding.renditions[0];
425 assert_eq!(rendition.name, "video");
426 assert_eq!(rendition.size, None);
427 assert_eq!(rendition.rate, None);
428 assert!(!encoding.record_timestamps);
429 assert!(encoding.validate(fps(30)).is_ok());
430 let source = moq_video::Size::new(854, 480);
431 let config = rendition.encode_config(source, fps(24), None);
432 assert_eq!(config.size(), source);
433 assert_eq!(config.framerate, fps(24));
434 }
435
436 #[test]
437 fn voice_is_mono_opus() {
438 let encoding = voice();
439 assert_eq!(encoding.config.layout, moq_audio::Layout::Mono);
440 assert_eq!(encoding.config.codec, moq_audio::encode::Codec::Opus);
441 assert!(encoding.validate().is_ok());
442 }
443
444 #[test]
445 fn pcm_follows_the_source() {
446 let mut encoding = pcm(AudioFormat {
447 sample_rate: 44_100,
448 layout: moq_audio::Layout::Stereo,
449 });
450 assert_eq!(encoding.config.sample_rate, 44_100);
451 assert_eq!(encoding.config.layout, moq_audio::Layout::Stereo);
452 assert!(encoding.validate().is_ok());
453 encoding.config.bitrate = Some(Rate::from_kbps(1));
454 assert!(encoding.validate().is_err());
455 }
456
457 #[test]
459 fn the_group_span_sets_the_audio_join() {
460 let default = voice();
461 assert_eq!(default.group_span, Duration::from_millis(100));
462 assert_eq!(
463 default.options("opus".to_string()).join,
464 moq_audio::encode::Options::default().join
465 );
466
467 let short = voice().with_group_span(Duration::from_millis(20));
468 let options = short.options("opus".to_string());
469 assert_eq!(options.join, Duration::from_millis(20));
470 assert_eq!(options.track.as_deref(), Some("opus"));
471 assert_eq!(options.config.bitrate, Some(Rate::from_kbps(32)));
472 }
473
474 #[test]
475 fn a_zero_group_span_is_refused() {
476 let encoding = voice().with_group_span(Duration::ZERO);
477 assert!(matches!(
478 encoding.validate(),
479 Err(Error::InvalidConfig { .. })
480 ));
481 }
482}