str0m 0.18.0

WebRTC library in Sans-IO style
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use std::cmp::Ordering;
use std::fmt::Display;
use std::num::NonZeroU32;
use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::str::FromStr;
use std::time::Duration;
use std::time::Instant;

use serde::{Deserialize, Serialize};

/// Media timeline frequency as represented by a non-zero unsigned integer.
///
/// The frequency can be found in the negotiated payload parameters for a
/// media writer.
///
/// ```no_run
/// # use str0m::Rtc;
/// # use str0m::media::{Mid, MediaTime};
/// # let rtc: Rtc = todo!();
/// #
/// // Obtain mid from Event::MediaAdded
/// let mid: Mid = todo!();
///
/// // Create a media writer for the mid.
/// let writer = rtc.writer(mid).unwrap();
///
/// // Get the payload type (pt) for the wanted codec.
/// let params = writer.payload_params().nth(0).unwrap();
///
/// // Obtain the frequency for the selected codec.
/// let freq = params.spec().clock_rate;
///
/// let mtime = MediaTime::new(2000, freq);
/// ```
#[derive(Debug, Clone, Copy, Serialize)]
pub struct Frequency(NonZeroU32);

impl Frequency {
    /// Microseconds in a second.
    pub const MICROS: Self = Self::make(1_000_000);

    /// 1 / 2 ^ 18 seconds in a second.
    pub const FIXED_POINT_6_18: Frequency = Self::make(2u32.pow(18)); // 262_144

    /// Cycles in a second of a 90 kHz signal.
    pub const NINETY_KHZ: Frequency = Self::make(90_000);

    /// Cycles in a second of a 48 kHz signal.
    pub const FORTY_EIGHT_KHZ: Frequency = Self::make(48_000);

    /// Cycles in a second of a 8000 Hz signal.
    pub const EIGHT_KHZ: Frequency = Self::make(8_000);

    /// Milliseconds in a second.
    pub const MILLIS: Frequency = Self::make(1_000);

    /// Hundredths in a second.
    pub const HUNDREDTHS: Frequency = Self::make(100);

    /// Seconds in a second.
    pub const SECONDS: Frequency = Self::make(1);

    /// Private unconditional non-zero constructor for use with constants.
    const fn make(v: u32) -> Frequency {
        match NonZeroU32::new(v) {
            Some(v) => Self(v),
            None => panic!("assured non-zero value is zero"),
        }
    }

    /// Any non-zero u32 is a valid media timeline frequency.
    pub const fn from_nonzero(v: NonZeroU32) -> Self {
        Self(v)
    }

    /// Every u32 is a valid media timeline frequency except zero.
    pub fn new(v: u32) -> Option<Self> {
        NonZeroU32::new(v).map(Self)
    }

    /// The frequency as a u32.
    pub const fn get(&self) -> u32 {
        self.0.get()
    }

    /// The frequency as a [`std::num::NonZeroU32`] i.e. including a positivity proof.
    pub const fn nonzero(&self) -> NonZeroU32 {
        self.0
    }
}

impl PartialEq for Frequency {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}
impl Eq for Frequency {}

impl From<Frequency> for NonZeroU32 {
    fn from(value: Frequency) -> Self {
        value.0
    }
}

impl From<NonZeroU32> for Frequency {
    fn from(value: NonZeroU32) -> Self {
        Self(value)
    }
}

impl FromStr for Frequency {
    type Err = <NonZeroU32 as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        NonZeroU32::from_str(s).map(Self)
    }
}

impl Display for Frequency {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl<'de> Deserialize<'de> for Frequency {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        NonZeroU32::deserialize(deserializer).map(Self)
    }
}

/// Media timeline offset represented by a count (numerator) / frequency (denominator) in seconds.
///
/// The numerator is typically the packet time of an Rtp header. The denominator is the clock
/// frequency of the media source (typically 90kHz for video and 48kHz for audio). The denominator
/// is guaranteed to be a positive integer while the numerator could be positive, negative, or zero.
///
/// The frequency can be found in the negotiated payload parameters for a media writer.
///
/// ```no_run
/// # use str0m::Rtc;
/// # use str0m::media::{Mid, MediaTime};
/// # let rtc: Rtc = todo!();
/// #
/// // Obtain mid from Event::MediaAdded
/// let mid: Mid = todo!();
///
/// // Create a media writer for the mid.
/// let writer = rtc.writer(mid).unwrap();
///
/// // Get the payload type (pt) for the wanted codec.
/// let params = writer.payload_params().nth(0).unwrap();
///
/// // Obtain the frequency for the selected codec.
/// let freq = params.spec().clock_rate;
///
/// let mtime = MediaTime::new(2000, freq);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct MediaTime(u64, Frequency);

impl MediaTime {
    /// The additive identity: 0/1.
    pub const ZERO: MediaTime = MediaTime::from_secs(0);

    /// Construct a [`MediaTime`] from a guaranteed non-zero [`Frequency`].
    pub const fn new(numer: u64, denom: Frequency) -> Self {
        Self(numer, denom)
    }

    /// The numerator of the offset time.
    #[inline(always)]
    pub const fn numer(&self) -> u64 {
        self.0
    }

    /// The denominator of the offset time.
    #[inline(always)]
    pub const fn denom(&self) -> u32 {
        self.1.get()
    }

    /// The [`Frequency`] of the offset time.
    #[inline(always)]
    pub const fn frequency(&self) -> Frequency {
        self.1
    }

    /// Convenience constructor for numbers of microseconds (v/1_000_000).
    #[inline(always)]
    pub const fn from_micros(v: u64) -> MediaTime {
        MediaTime(v, Frequency::MICROS)
    }

    /// Convenience constructor for numbers of 24-bit 6.18 fixed point units (v/2^18).
    #[inline(always)]
    pub const fn from_fixed_point_6_18(v: u64) -> MediaTime {
        MediaTime(v, Frequency::FIXED_POINT_6_18)
    }

    /// Convenience constructor for numbers of 90kHz units (v/90_000).
    #[inline(always)]
    pub const fn from_90khz(v: u64) -> MediaTime {
        MediaTime(v, Frequency::NINETY_KHZ)
    }

    /// Convenience constructor for numbers of milliseconds (v/1000).
    #[inline(always)]
    pub const fn from_millis(v: u64) -> MediaTime {
        MediaTime(v, Frequency::MILLIS)
    }

    /// Convenience constructor for numbers of hundredths of seconds (v/100).
    #[inline(always)]
    pub const fn from_hundredths(v: u64) -> MediaTime {
        MediaTime(v, Frequency::HUNDREDTHS)
    }

    /// Convenience constructor for numbers of seconds (v/1).
    #[inline(always)]
    pub const fn from_secs(v: u64) -> MediaTime {
        MediaTime(v, Frequency::SECONDS)
    }

    /// Convenience constructor for floating point fractions of seconds as microsecond units.
    #[inline(always)]
    pub fn from_seconds(v: impl Into<f64>) -> MediaTime {
        Self::from_micros((v.into() * 1_000_000.0_f64) as u64)
    }

    /// A floating point fraction second representation.
    #[inline(always)]
    pub fn as_seconds(&self) -> f64 {
        let denom: f64 = self.1.get().into();
        self.0 as f64 / denom
    }

    /// A microsecond representation.
    pub const fn as_micros(&self) -> u64 {
        self.rebase(Frequency::MICROS).numer()
    }

    /// Predicate for checking that the numerator is 0.
    #[inline(always)]
    pub const fn is_zero(&self) -> bool {
        self.0 == 0
    }

    /// Convert this offset time to have a different denominator
    /// (frequency). This conversion may lose precision and, after
    /// arithmetic operations with other times of higher frequencies,
    /// may have a higher frequency.
    #[inline(always)]
    pub const fn rebase(self, denom: Frequency) -> MediaTime {
        if denom.get() == self.1.get() {
            self
        } else {
            let numer = self.0 as i128 * denom.get() as i128 / self.1.get() as i128;
            MediaTime::new(numer as u64, denom)
        }
    }

    #[inline(always)]
    fn same_base(t0: MediaTime, t1: MediaTime) -> (MediaTime, MediaTime) {
        let max = Frequency(t0.1.0.max(t1.1.0));
        (t0.rebase(max), t1.rebase(max))
    }

    /// Checked `MediaTime` subtraction. Returns [`None`] if the result
    /// would be negative.
    ///
    /// # Examples
    ///
    /// Basic usage:
    /// ```
    /// use str0m::media::MediaTime;
    ///
    /// assert_eq!(
    ///     MediaTime::from_micros(10).checked_sub(MediaTime::from_micros(5)),
    ///     Some(MediaTime::from_micros(5))
    /// );
    /// assert_eq!(
    ///     MediaTime::from_micros(5).checked_sub(MediaTime::from_micros(10)),
    ///     None
    /// );
    /// ```
    #[inline]
    pub fn checked_sub(self, rhs: MediaTime) -> Option<MediaTime> {
        let (lhs, rhs) = MediaTime::same_base(self, rhs);
        if lhs.0 < rhs.0 {
            None
        } else {
            Some(MediaTime::new(lhs.0 - rhs.0, lhs.1))
        }
    }

    /// Saturating `MediaTime` subtraction. Returns [`MediaTime::ZERO`] if the result
    /// would be negative.
    ///
    /// # Examples
    ///
    /// Basic usage:
    /// ```
    /// use str0m::media::MediaTime;
    ///
    /// assert_eq!(
    ///     MediaTime::from_micros(10).saturating_sub(MediaTime::from_micros(5)),
    ///     MediaTime::from_micros(5)
    /// );
    /// assert_eq!(
    ///     MediaTime::from_micros(5).saturating_sub(MediaTime::from_micros(10)),
    ///     MediaTime::ZERO
    /// );
    /// ```
    #[inline]
    pub fn saturating_sub(self, rhs: MediaTime) -> MediaTime {
        match self.checked_sub(rhs) {
            Some(v) => v,
            None => MediaTime::ZERO,
        }
    }
}

impl PartialEq for MediaTime {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        let (t0, t1) = MediaTime::same_base(*self, *other);
        t0.0 == t1.0
    }
}
impl Eq for MediaTime {}

impl PartialOrd for MediaTime {
    #[inline(always)]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for MediaTime {
    #[inline(always)]
    fn cmp(&self, other: &Self) -> Ordering {
        let (t0, t1) = MediaTime::same_base(*self, *other);
        if t0 == t1 {
            Ordering::Equal
        } else if t0.0 < t1.0 {
            Ordering::Less
        } else {
            Ordering::Greater
        }
    }
}

impl Add for MediaTime {
    type Output = MediaTime;

    #[inline(always)]
    fn add(self, rhs: Self) -> Self::Output {
        let (t0, t1) = MediaTime::same_base(self, rhs);
        MediaTime::new(t0.0 + t1.0, t0.1)
    }
}

impl Sub for MediaTime {
    type Output = MediaTime;

    fn sub(self, rhs: Self) -> Self::Output {
        self.checked_sub(rhs)
            .expect("overflow when subtracting MediaTime")
    }
}

impl SubAssign for MediaTime {
    fn sub_assign(&mut self, rhs: Self) {
        *self = *self - rhs;
    }
}

impl Sub<MediaTime> for Instant {
    type Output = Instant;

    fn sub(self, rhs: MediaTime) -> Self::Output {
        self - Duration::from(rhs)
    }
}

impl SubAssign<MediaTime> for Instant {
    fn sub_assign(&mut self, rhs: MediaTime) {
        *self = *self - rhs;
    }
}

impl AddAssign for MediaTime {
    fn add_assign(&mut self, rhs: Self) {
        *self = *self + rhs;
    }
}

impl Add<MediaTime> for Instant {
    type Output = Instant;

    fn add(self, rhs: MediaTime) -> Self::Output {
        self + Duration::from(rhs)
    }
}

impl AddAssign<MediaTime> for Instant {
    fn add_assign(&mut self, rhs: MediaTime) {
        *self = *self + rhs;
    }
}

impl From<MediaTime> for Duration {
    fn from(value: MediaTime) -> Self {
        Duration::from_micros(value.rebase(Frequency::MICROS).numer())
    }
}

impl From<Duration> for MediaTime {
    fn from(v: Duration) -> Self {
        MediaTime::new(v.as_micros() as u64, Frequency::MICROS)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn ts_rebase() {
        let t1 = MediaTime::from_seconds(10.0);
        let t2 = t1.rebase(Frequency::NINETY_KHZ);
        assert_eq!(t2.numer(), 90_000 * 10);
        assert_eq!(t2.denom(), 90_000);

        println!("{}", (10.0234_f64).fract());
    }
}