Skip to main content

str0m/format/
format_params.rs

1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4use super::Codec;
5use crate::sdp::FormatParam;
6
7/// Codec specific format parameters.
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
9pub struct FormatParams {
10    /// Opus specific parameter.
11    ///
12    /// The minimum duration of media represented by a packet.
13    pub min_p_time: Option<u8>,
14
15    /// Opus specific parameter.
16    ///
17    /// Decoder-side preference for stereo audio. Default is mono per
18    /// RFC 7587 Section 7.1: <https://datatracker.ietf.org/doc/html/rfc7587#section-7.1>
19    pub stereo: Option<bool>,
20
21    /// Opus specific parameter.
22    ///
23    /// Sender-side stereo hint for Opus. When set, it signals the intent to
24    /// transmit stereo from the sender, matching the symmetric m-line model.
25    pub sprop_stereo: Option<bool>,
26
27    /// Opus specific parameter.
28    ///
29    /// Specifies that the decoder can do Opus in-band FEC
30    pub use_inband_fec: Option<bool>,
31
32    /// Opus specific parameter.
33    ///
34    /// Specifies that the decoder prefers DTX (Discontinuous Transmission) such that
35    /// the packet rate is greatly lowered during periods of silence.
36    pub use_dtx: Option<bool>,
37
38    /// Whether h264 sending media encoded at a different level in the offerer-to-answerer
39    /// direction than the level in the answerer-to-offerer direction, is allowed.
40    pub level_asymmetry_allowed: Option<bool>,
41
42    /// What h264 packetization mode is used.
43    ///
44    /// * 0 - single nal.
45    /// * 1 - STAP-A, FU-A is allowed. Non-interleaved.
46    pub packetization_mode: Option<u8>,
47
48    /// H264 profile level.
49    ///
50    /// * 42 00 1f - 4200=baseline (B)              1f=level 3.1
51    /// * 42 e0 1f - 42e0=constrained baseline (CB) 1f=level 3.1
52    /// * 4d 00 1f - 4d00=main (M)                  1f=level 3.1
53    /// * 64 00 1f - 6400=high (H)                  1f=level 3.1
54    pub profile_level_id: Option<u32>,
55
56    /// VP9 profile id.
57    pub profile_id: Option<u32>,
58
59    /// AV1 profile.
60    ///
61    /// Indicates the highest AV1 profile that may have been used to generate
62    /// the bitstream or that the receiver supports. The range of possible values
63    /// is identical to the seq_profile syntax element specified in AV1. If the
64    /// parameter is not present, it MUST be inferred to be 0 ("Main" profile).
65    ///
66    /// 0  8-bit or 10-bit 4:2:0
67    /// 1  8-bit or 10-bit 4:4:4
68    /// 2  8-bit or 10-bit 4:2:2
69    /// 2  12-bit          4:2:0, 4:2:2, 4:4:4
70    pub profile: Option<u8>,
71
72    /// AV1 level-idx.
73    ///
74    /// Indicates the highest AV1 level that may have been used to generate the
75    /// bitstream or that the receiver supports. The range of possible values
76    /// is identical to the seq_level_idx syntax element specified in AV1. If
77    /// the parameter is not present, it MUST be inferred to be 5 (level 3.1).
78    pub level_idx: Option<u8>,
79
80    /// AV1 tier.
81    ///
82    /// Indicates the highest tier that may have been used to generate the  bitstream
83    /// or that the receiver supports. The range of possible values is identical
84    /// to the seq_tier syntax element specified in AV1. If the parameter is not
85    /// present, the tier MUST be inferred to be 0.
86    pub tier: Option<u8>,
87
88    /// H.265/HEVC profile, tier, and level.
89    ///
90    /// Contains:
91    /// * profile: Main, Main10, Main Still Picture, etc.
92    /// * tier: Main or High.
93    /// * level: 3.1, 4.0, 5.0, etc.
94    ///
95    /// See ITU-T H.265 Annex A for complete definitions.
96    pub h265_profile_tier_level: Option<crate::packet::H265ProfileTierLevel>,
97
98    /// H.266/VVC profile, tier, and level.
99    ///
100    /// Contains:
101    /// * profile: Main 10, Main 10 4:4:4, etc.
102    /// * tier: Main or High.
103    /// * level: 3.1, 4.0, 5.0, etc.
104    ///
105    /// See ITU-T H.266 Annex A and RFC 9328 §7.2 for complete definitions.
106    pub h266_profile_tier_level: Option<crate::packet::H266ProfileTierLevel>,
107
108    /// H.265 sprop-max-don-diff parameter (RFC 7798 §7.1).
109    /// When > 0, DONL fields are included in H.265 RTP packets to support
110    /// out-of-order NAL unit decoding.
111    pub sprop_max_don_diff: Option<u16>,
112
113    /// Highest event code in the inclusive `0-X` telephone-event SDP range.
114    ///
115    /// Only contiguous ranges starting at zero are supported. `None` uses the
116    /// library default `0-16`. Negotiation takes the smaller maximum per payload
117    /// type across the session.
118    pub telephone_event_max: Option<u8>,
119
120    /// AMR-WB `octet-align`. `Some(true)` selects the octet-aligned payload
121    /// layout, otherwise bandwidth-efficient is used.
122    pub octet_align: Option<bool>,
123
124    /// AMR-WB `mode-set`, a bitmask of the allowed speech modes 0..=8.
125    ///
126    /// A mode set from either peer applies to both directions, so only write
127    /// frames in these modes.
128    pub mode_set: Option<u16>,
129}
130
131#[cfg(feature = "drv")]
132crate::drv_identity_copy!(FormatParams);
133
134impl FormatParams {
135    pub(crate) const DEFAULT_TELEPHONE_EVENT_MAX: u8 = 16;
136
137    pub(crate) fn from_sdp_fmtp<'a>(
138        codec: Codec,
139        mut lines: impl Iterator<Item = &'a [FormatParam]>,
140    ) -> Option<Self> {
141        let mut params = Self::default();
142        if codec.is_tele() {
143            let max = match lines.next() {
144                None => Self::DEFAULT_TELEPHONE_EVENT_MAX,
145                Some([FormatParam::BareRange(max) | FormatParam::TelephoneEvents(max)]) => *max,
146                _ => return None,
147            };
148            if lines.next().is_some() {
149                return None;
150            }
151            params.telephone_event_max = Some(max);
152        } else {
153            for line in lines {
154                for param in line {
155                    // Decline AMR-WB payload types that need features str0m lacks.
156                    if codec == Codec::AmrWb && *param == FormatParam::AmrWbUnsupported {
157                        return None;
158                    }
159                    if !matches!(param, FormatParam::TelephoneEvents(_)) {
160                        params.set_param(param);
161                    }
162                }
163            }
164        }
165        Some(params)
166    }
167
168    /// Parse an fmtp line to create a FormatParams.
169    ///
170    /// Example `minptime=10;useinbandfec=1`, or `0-16` for telephone events.
171    pub fn parse_line(line: &str) -> Self {
172        let mut p = FormatParams::default();
173        let key_vals: Vec<_> = line
174            .split(';')
175            .filter_map(|pair| {
176                let mut kv = pair.split('=');
177                match (kv.next(), kv.next()) {
178                    (Some(k), Some(v)) => Some((k.trim().to_string(), v.trim().to_string())),
179                    (Some(value), None) => {
180                        let value = value.trim();
181                        let param = FormatParam::parse_telephone_events(value);
182                        if param == FormatParam::Unknown && !value.is_empty() {
183                            debug!("Ignoring unsupported fmtp value: {value}");
184                        }
185                        p.set_param(&param);
186                        None
187                    }
188                    (None, _) => None,
189                }
190            })
191            .collect();
192
193        for param in FormatParam::parse_pairs(key_vals) {
194            p.set_param(&param);
195        }
196
197        p
198    }
199
200    pub(crate) fn set_param(&mut self, param: &FormatParam) {
201        use FormatParam::*;
202        match param {
203            MinPTime(v) => self.min_p_time = Some(*v),
204            Stereo(v) => self.stereo = Some(*v),
205            SpropStereo(v) => self.sprop_stereo = Some(*v),
206            UseInbandFec(v) => self.use_inband_fec = Some(*v),
207            UseDtx(v) => self.use_dtx = Some(*v),
208            LevelAsymmetryAllowed(v) => self.level_asymmetry_allowed = Some(*v),
209            PacketizationMode(v) => self.packetization_mode = Some(*v),
210            ProfileLevelId(v) => self.profile_level_id = Some(*v),
211            ProfileId(v) => self.profile_id = Some(*v),
212            Profile(v) => self.profile = Some(*v),
213            LevelIdx(v) => self.level_idx = Some(*v),
214            Tier(v) => self.tier = Some(*v),
215            H265ProfileTierLevel(v) => self.h265_profile_tier_level = Some(*v),
216            H266ProfileTierLevel(v) => self.h266_profile_tier_level = Some(*v),
217            SpropMaxDonDiff(v) => self.sprop_max_don_diff = Some(*v),
218            TelephoneEvents(v) => self.telephone_event_max = Some(*v),
219            BareRange(_) | BarePtList(_) => {}
220            OctetAlign(v) => self.octet_align = Some(*v),
221            ModeSet(v) => self.mode_set = Some(*v),
222            AmrWbUnsupported => {}
223            Apt(_) => {}
224            Red(_) => {}
225            Unknown => {}
226        }
227    }
228
229    pub(crate) fn to_format_param(self) -> Vec<FormatParam> {
230        use FormatParam::*;
231        let mut r = Vec::with_capacity(5);
232
233        if let Some(v) = self.min_p_time {
234            r.push(MinPTime(v));
235        }
236        if let Some(v) = self.stereo {
237            r.push(Stereo(v));
238        }
239        if let Some(v) = self.sprop_stereo {
240            r.push(SpropStereo(v));
241        }
242        if let Some(v) = self.use_inband_fec {
243            r.push(UseInbandFec(v));
244        }
245        if let Some(v) = self.use_dtx {
246            r.push(UseDtx(v));
247        }
248        if let Some(v) = self.level_asymmetry_allowed {
249            r.push(LevelAsymmetryAllowed(v));
250        }
251        if let Some(v) = self.packetization_mode {
252            r.push(PacketizationMode(v));
253        }
254        if let Some(v) = self.profile_level_id {
255            r.push(ProfileLevelId(v));
256        }
257        if let Some(v) = self.profile_id {
258            r.push(ProfileId(v));
259        }
260        if let Some(v) = self.profile {
261            r.push(Profile(v));
262        }
263        if let Some(v) = self.level_idx {
264            r.push(LevelIdx(v));
265        }
266        if let Some(v) = self.tier {
267            r.push(Tier(v));
268        }
269        // H.265 Profile/Tier/Level: Keep as composite, it serializes all three params
270        if let Some(ptl) = self.h265_profile_tier_level {
271            r.push(H265ProfileTierLevel(ptl));
272        }
273        // H.266 Profile/Tier/Level: serialized as one composite (all three fmtp params).
274        if let Some(ptl) = self.h266_profile_tier_level {
275            r.push(H266ProfileTierLevel(ptl));
276        }
277        if let Some(v) = self.sprop_max_don_diff {
278            r.push(SpropMaxDonDiff(v));
279        }
280        if let Some(v) = self.telephone_event_max {
281            r.push(TelephoneEvents(v));
282        }
283        if let Some(v) = self.octet_align {
284            r.push(OctetAlign(v));
285        }
286        if let Some(v) = self.mode_set {
287            r.push(ModeSet(v));
288        }
289
290        r
291    }
292}
293
294impl fmt::Display for FormatParams {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        let s = self
297            .to_format_param()
298            .into_iter()
299            .map(|f| f.to_string())
300            .collect::<Vec<_>>()
301            .join(";");
302        write!(f, "{s}")
303    }
304}
305
306#[cfg(test)]
307mod test {
308    use super::*;
309
310    #[test]
311    fn telephone_event_ranges_roundtrip() {
312        for max in [0, 7, 15, 16, 255] {
313            let value = format!("0-{max}");
314            let params = FormatParams::parse_line(&value);
315            assert_eq!(params.telephone_event_max, Some(max));
316            assert_eq!(params.to_string(), value);
317        }
318        for value in ["", "0-", "0-256", "15-0", "1-15", "0-15,16", "0-+15"] {
319            assert_eq!(
320                FormatParam::parse_telephone_events(value),
321                FormatParam::Unknown
322            );
323        }
324    }
325
326    #[test]
327    fn sprop_max_don_diff_roundtrip() {
328        // Test that sprop-max-don-diff parameter round-trips correctly
329        let f = FormatParams {
330            sprop_max_don_diff: Some(32),
331            ..Default::default()
332        };
333
334        // Serialize to string
335        let fmtp_str = f.to_string();
336        assert_eq!(fmtp_str, "sprop-max-don-diff=32");
337
338        // Parse back
339        let parsed = FormatParams::parse_line(&fmtp_str);
340        assert_eq!(parsed.sprop_max_don_diff, Some(32));
341    }
342
343    #[test]
344    fn sprop_stereo_roundtrip() {
345        let f = FormatParams {
346            sprop_stereo: Some(true),
347            ..Default::default()
348        };
349
350        let fmtp_str = f.to_string();
351        assert_eq!(fmtp_str, "sprop-stereo=1");
352
353        let parsed = FormatParams::parse_line(&fmtp_str);
354        assert_eq!(parsed.sprop_stereo, Some(true));
355    }
356
357    #[test]
358    fn h265_combined_params_roundtrip() {
359        use crate::packet::H265ProfileTierLevel;
360
361        // Test H.265 with both profile/tier/level and sprop-max-don-diff
362        let ptl = H265ProfileTierLevel::new(1, 0, 93).unwrap();
363        let f = FormatParams {
364            h265_profile_tier_level: Some(ptl),
365            sprop_max_don_diff: Some(32),
366            ..Default::default()
367        };
368
369        // Serialize to string
370        let fmtp_str = f.to_string();
371        assert!(fmtp_str.contains("profile-id=1"));
372        assert!(fmtp_str.contains("tier-flag=0"));
373        assert!(fmtp_str.contains("level-id=93"));
374        assert!(fmtp_str.contains("sprop-max-don-diff=32"));
375
376        // Parse back
377        let parsed = FormatParams::parse_line(&fmtp_str);
378        assert_eq!(parsed.h265_profile_tier_level, Some(ptl));
379        assert_eq!(parsed.sprop_max_don_diff, Some(32));
380    }
381
382    #[test]
383    fn h266_combined_params_roundtrip() {
384        use crate::packet::H266ProfileTierLevel;
385
386        // Test H.266 with both profile/tier/level and sprop-max-don-diff
387        let ptl = H266ProfileTierLevel::new(1, 0, 51).unwrap();
388        let f = FormatParams {
389            h266_profile_tier_level: Some(ptl),
390            sprop_max_don_diff: Some(32),
391            ..Default::default()
392        };
393
394        // Serialize to string
395        let fmtp_str = f.to_string();
396        assert!(fmtp_str.contains("profile-id=1"));
397        assert!(fmtp_str.contains("tier-flag=0"));
398        assert!(fmtp_str.contains("level-id=51"));
399        assert!(fmtp_str.contains("sprop-max-don-diff=32"));
400
401        // Parse back
402        let parsed = FormatParams::parse_line(&fmtp_str);
403        assert_eq!(parsed.h266_profile_tier_level, Some(ptl));
404        assert_eq!(parsed.sprop_max_don_diff, Some(32));
405    }
406
407    #[test]
408    fn amr_wb_fmtp() {
409        let f = FormatParams::parse_line("octet-align=1; mode-set=0, 1,2;max-red=220");
410        assert_eq!(f.to_string(), "octet-align=1;mode-set=0,1,2");
411        assert_eq!(
412            FormatParams::parse_line("mode-set=0,9"),
413            FormatParams::default()
414        );
415
416        let declined = |codec, k: &str, v: &str| {
417            let line = [FormatParam::parse(k, v)];
418            FormatParams::from_sdp_fmtp(codec, [&line[..]].into_iter()).is_none()
419        };
420        for (k, v) in [
421            ("crc", "1"),
422            ("robust-sorting", "1"),
423            ("interleaving", "30"),
424            ("mode-change-period", "2"),
425        ] {
426            assert!(declined(Codec::AmrWb, k, v), "{k}={v}");
427            assert!(!declined(Codec::Opus, k, v), "{k}={v}");
428        }
429        for (k, v) in [
430            ("crc", "0"),
431            ("robust-sorting", "0"),
432            ("mode-change-period", "1"),
433        ] {
434            assert!(!declined(Codec::AmrWb, k, v), "{k}={v}");
435        }
436    }
437}