Skip to main content

moq_ext_publisher/publish/
encoding.rs

1//! How a broadcast encodes its sources: renditions and their presets.
2
3use std::{collections::BTreeSet, time::Duration};
4
5use moq_ext_sources::{AudioFormat, Error};
6use moq_net::bandwidth::Rate;
7
8/// The frame durations Opus accepts, in microseconds.
9///
10/// Another one would fail later in the publication, after `set_audio` has
11/// returned.
12const OPUS_FRAMES_MICROS: [u128; 6] = [2_500, 5_000, 10_000, 20_000, 40_000, 60_000];
13
14/// How a video source is encoded: one or more renditions of the same picture.
15#[derive(Debug, Clone)]
16#[non_exhaustive]
17pub struct VideoEncoding {
18    /// The renditions, which a subscriber chooses among.
19    pub renditions: Vec<VideoRendition>,
20    /// Whether the broadcast records each published frame's source timestamp and capture instant.
21    ///
22    /// The broadcast moves source timestamps onto its own clock, so a
23    /// subscriber only ever sees broadcast timestamps. The record maps one
24    /// back, for
25    /// [`LocalBroadcast::video_source_timestamp`](crate::LocalBroadcast::video_source_timestamp)
26    /// and
27    /// [`LocalBroadcast::video_captured_at`](crate::LocalBroadcast::video_captured_at):
28    /// a round-trip measurement such as capture-to-result latency. It keeps
29    /// 64 bytes for each of the last 512 frames, no pixels. Off by default.
30    pub record_timestamps: bool,
31}
32
33impl VideoEncoding {
34    /// Encodes one rendition.
35    #[must_use]
36    pub fn single(rendition: VideoRendition) -> Self {
37        Self::ladder([rendition])
38    }
39
40    /// Encodes a simulcast ladder: several renditions of the same picture.
41    #[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    /// Turns on [`record_timestamps`](Self::record_timestamps).
50    #[must_use]
51    pub fn with_recorded_timestamps(mut self) -> Self {
52        self.record_timestamps = true;
53        self
54    }
55
56    /// Checks everything that can be checked without opening an encoder.
57    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            // OpenH264 is the one encoder every build carries, and it only
100            // encodes H.264. A software-only H.265 rendition can never open.
101            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    /// Returns one rendition named `video` at the source's size and rate.
115    fn default() -> Self {
116        Self::single(VideoRendition::default())
117    }
118}
119
120/// One encoding of a broadcast's picture.
121///
122/// The encoder settings are moq-video's own [`Config`]. Its `width`, `height`
123/// and `framerate` are filled in from [`size`](Self::size), [`rate`](Self::rate)
124/// and the source when the rendition opens, and so is its `color` unless set.
125/// Its `resize` is filled in with moq-video's defaults unless set, so a frame
126/// of another size is scaled on the encoder's thread.
127/// Its `join` is the keyframe interval: a subscriber cannot draw anything
128/// before a keyframe, so it sets how long a new viewer waits for a picture and
129/// how long a rendition switch takes.
130///
131/// [`Config`]: moq_video::encode::Config
132#[derive(Debug, Clone)]
133#[non_exhaustive]
134pub struct VideoRendition {
135    /// The track name, which a subscriber picks the rendition by.
136    pub name: String,
137    /// The encoded size. `None` encodes at the source's own size.
138    pub size: Option<moq_video::Size>,
139    /// The frame rate. `None` follows the source. It cannot exceed the source's rate.
140    pub rate: Option<moq_video::FrameRate>,
141    /// The encoder settings: bitrate, keyframe interval, codec, backend, preset.
142    pub config: moq_video::encode::Config,
143}
144
145impl VideoRendition {
146    /// Creates a rendition at the source's size with moq-video's default settings.
147    ///
148    /// The defaults are H.264 from any backend, a keyframe every two seconds,
149    /// and a bitrate derived from the size and rate.
150    #[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            // The size and rate are placeholders until the rendition opens.
158            config: moq_video::encode::Config::new(0, 0, rate),
159        }
160    }
161
162    /// Returns this rendition encoded at `size` instead of the source's size.
163    #[must_use]
164    pub fn with_size(mut self, size: moq_video::Size) -> Self {
165        self.size = Some(size);
166        self
167    }
168
169    /// Returns this rendition at `rate` instead of the source's frame rate.
170    #[must_use]
171    pub fn with_rate(mut self, rate: moq_video::FrameRate) -> Self {
172        self.rate = Some(rate);
173        self
174    }
175
176    /// Returns `360p`: 640x360 at 500 kbit/s.
177    #[must_use]
178    pub fn p360() -> Self {
179        Self::preset("360p", 640, 360, 500)
180    }
181
182    /// Returns `720p`: 1280x720 at 1.8 Mbit/s.
183    #[must_use]
184    pub fn p720() -> Self {
185        Self::preset("720p", 1280, 720, 1_800)
186    }
187
188    /// Creates a 16:9 preset with a bitrate chosen for 30 fps camera content.
189    ///
190    /// The bitrate is close to the 0.07 bit per pixel that moq-video derives
191    /// on its own. At 30 fps that is 484 kbit/s for 360p, a little below the
192    /// preset, and 1.94 Mbit/s for 720p, a little above it. moq-transcode's
193    /// default ladder spends more, 2.5 Mbit/s at 720p. Set
194    /// [`Config::bitrate`](moq_video::encode::Config::bitrate) for another
195    /// trade between quality and the links a rendition fits.
196    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    /// Returns the encoder config for this rendition of a source of `size` at `rate`.
204    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        // A frame of another size than the track advertises is scaled on the
217        // encoder's own thread, so the source's thread and the encode task
218        // never do the pixel work.
219        config.resize.get_or_insert_with(Default::default);
220        config
221    }
222}
223
224impl Default for VideoRendition {
225    /// Returns a rendition named `video` at the source's size and rate.
226    fn default() -> Self {
227        Self::new("video")
228    }
229}
230
231/// How an audio source is encoded: moq-audio's encoder settings and the span of each group.
232///
233/// Build one from a preset in [`audio_encoding`](crate::audio_encoding), or
234/// from any moq-audio [`Config`] through `From`.
235///
236/// [`Config`]: moq_audio::encode::Config
237#[derive(Debug, Clone)]
238#[non_exhaustive]
239pub struct AudioEncoding {
240    /// The encoder settings: codec, sample rate, layout, bitrate, frame duration.
241    pub config: moq_audio::encode::Config,
242    /// How much audio each group carries, moq-audio's `join`.
243    ///
244    /// Each group is a stream of its own on the wire. A shorter span loses
245    /// less audio when a packet is lost, since a loss stalls only the rest of
246    /// its group, and lets a new subscriber start closer to the live edge. A
247    /// longer one opens fewer streams, which matters most at a media relay that
248    /// fans out to many subscribers. moq-audio's default is 100 ms; 20 ms, one
249    /// Opus frame per group, was its default before. It cannot be zero.
250    pub group_span: Duration,
251}
252
253impl AudioEncoding {
254    /// Creates an encoding of `config` with moq-audio's default group span.
255    #[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    /// Returns this encoding with each group carrying `span` of audio.
264    ///
265    /// See [`group_span`](Self::group_span) for the trade-off.
266    #[must_use]
267    pub fn with_group_span(mut self, span: Duration) -> Self {
268        self.group_span = span;
269        self
270    }
271
272    /// Returns the track name this encoding publishes under.
273    pub(crate) fn track_name(&self) -> String {
274        self.config.codec.to_string()
275    }
276
277    /// Returns moq-audio's publication options for this encoding under `track`.
278    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    /// Checks everything that can be checked without opening an encoder.
287    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/// Returns Opus mono at 32 kbit/s in 20 ms frames, for speech.
319#[must_use]
320pub fn voice() -> AudioEncoding {
321    opus(moq_audio::Layout::Mono, 32)
322}
323
324/// Returns Opus stereo at 128 kbit/s in 20 ms frames, for music.
325#[must_use]
326pub fn music() -> AudioEncoding {
327    opus(moq_audio::Layout::Stereo, 128)
328}
329
330/// Returns uncompressed PCM in 20 ms frames at the rate and layout of `format`.
331///
332/// Pass the source's own format, so the samples go out as they come in. A
333/// microphone's format is known only once it opens, and is resampled to
334/// whatever is passed here.
335#[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
341/// Returns Opus at 48 kHz in `layout` at `kbps`.
342fn 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    /// The group span defaults to moq-audio's and reaches its publication options.
458    #[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}