Skip to main content

rtci_rtp/codec/telephone_event/
mod.rs

1//! Named telephone events, DTMF included ([RFC 4733]).
2//!
3//! The payload is a list of 4-byte event reports:
4//!
5//! ```text
6//!  0                   1                   2                   3
7//!  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
8//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
9//! |     event     |E|R| volume    |          duration             |
10//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
11//! ```
12//!
13//! Besides the wire type (`TelephoneEvent`) this module has the DTMF code table (section 3.2),
14//! the `events` fmtp list (`EventSet`, section 2.4), and two sans-I/O state machines:
15//! `TelephoneEventSender`, which turns "event started / still going / ended" into the packets
16//! of section 2.5.1, and `TelephoneEventReceiver`, which turns received packets back into
17//! started / updated / ended reports following section 2.5.2.
18//!
19//! Event packets travel in the audio stream and share its sequence number space and timestamp
20//! base (section 2.5.1.2): the sender here produces marker, timestamp and payload only, and the
21//! caller numbers the packets with the audio stream's sequencer, one number per packet sent,
22//! retransmissions included (section 2.5.1.6).
23//!
24//! Every event is treated as a non-state event (all events registered for WebRTC are tones), so
25//! a zero duration is never sent and a received zero-duration report is ignored (section 2.3.5).
26//!
27//! [RFC 4733]: https://datatracker.ietf.org/doc/html/rfc4733
28#[cfg(test)]
29mod telephone_event_test;
30
31use bytes::{Buf, BufMut, Bytes, BytesMut};
32use shared::error::{Error, Result};
33use shared::marshal::{Marshal, MarshalSize, Unmarshal};
34use std::fmt;
35
36/// Size of one event report on the wire.
37pub const TELEPHONE_EVENT_SIZE: usize = 4;
38/// The largest volume value: the field is 6 bits, 0 to -63 dBm0 (section 2.3.4).
39pub const TELEPHONE_EVENT_MAX_VOLUME: u8 = 63;
40/// The largest duration one report (one segment) can carry (section 2.5.1.3).
41pub const TELEPHONE_EVENT_MAX_SEGMENT_DURATION: u16 = 0xFFFF;
42
43/// DTMF digit 0 (section 3.2).
44pub const DTMF_0: u8 = 0;
45/// DTMF digit 1.
46pub const DTMF_1: u8 = 1;
47/// DTMF digit 2.
48pub const DTMF_2: u8 = 2;
49/// DTMF digit 3.
50pub const DTMF_3: u8 = 3;
51/// DTMF digit 4.
52pub const DTMF_4: u8 = 4;
53/// DTMF digit 5.
54pub const DTMF_5: u8 = 5;
55/// DTMF digit 6.
56pub const DTMF_6: u8 = 6;
57/// DTMF digit 7.
58pub const DTMF_7: u8 = 7;
59/// DTMF digit 8.
60pub const DTMF_8: u8 = 8;
61/// DTMF digit 9.
62pub const DTMF_9: u8 = 9;
63/// DTMF `*`.
64pub const DTMF_STAR: u8 = 10;
65/// DTMF `#`.
66pub const DTMF_POUND: u8 = 11;
67/// DTMF A.
68pub const DTMF_A: u8 = 12;
69/// DTMF B.
70pub const DTMF_B: u8 = 13;
71/// DTMF C.
72pub const DTMF_C: u8 = 14;
73/// DTMF D.
74pub const DTMF_D: u8 = 15;
75
76/// The event code of a DTMF character (`0-9`, `*`, `#`, `A-D`, case-insensitive), section 3.2.
77pub fn dtmf_event_from_char(c: char) -> Option<u8> {
78    match c {
79        '0'..='9' => Some(c as u8 - b'0'),
80        '*' => Some(DTMF_STAR),
81        '#' => Some(DTMF_POUND),
82        'A'..='D' => Some(c as u8 - b'A' + DTMF_A),
83        'a'..='d' => Some(c as u8 - b'a' + DTMF_A),
84        _ => None,
85    }
86}
87
88/// The DTMF character of an event code 0 to 15 (`A-D` upper case); `None` for any other code.
89pub fn dtmf_char_from_event(event: u8) -> Option<char> {
90    match event {
91        0..=9 => Some((b'0' + event) as char),
92        DTMF_STAR => Some('*'),
93        DTMF_POUND => Some('#'),
94        DTMF_A..=DTMF_D => Some((b'A' + event - DTMF_A) as char),
95        _ => None,
96    }
97}
98
99/// One named-event report (section 2.3).
100///
101/// The R bit is not represented: [`Marshal`] writes it as zero and [`Unmarshal`] ignores it
102/// (section 2.3.3).
103#[derive(PartialEq, Eq, Debug, Default, Copy, Clone)]
104pub struct TelephoneEvent {
105    /// Event code, 0 to 255 (section 2.3.1); DTMF uses 0 to 15.
106    pub event: u8,
107    /// E bit: this report carries the end of the event (section 2.3.2).
108    pub end: bool,
109    /// Power level in -dBm0, 0 to 63 (section 2.3.4). Zero for events without a volume.
110    pub volume: u8,
111    /// Duration of the event or segment so far, in timestamp units (section 2.3.5).
112    pub duration: u16,
113}
114
115impl MarshalSize for TelephoneEvent {
116    fn marshal_size(&self) -> usize {
117        TELEPHONE_EVENT_SIZE
118    }
119}
120
121impl Marshal for TelephoneEvent {
122    /// Writes the 4-byte report with R = 0. Fails on a volume above 63.
123    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
124        if buf.remaining_mut() < TELEPHONE_EVENT_SIZE {
125            return Err(Error::ErrBufferTooSmall);
126        }
127        if self.volume > TELEPHONE_EVENT_MAX_VOLUME {
128            return Err(Error::Other(format!(
129                "telephone-event volume {} exceeds {TELEPHONE_EVENT_MAX_VOLUME}",
130                self.volume
131            )));
132        }
133        buf.put_u8(self.event);
134        buf.put_u8(if self.end { 0x80 } else { 0 } | self.volume);
135        buf.put_u16(self.duration);
136        Ok(TELEPHONE_EVENT_SIZE)
137    }
138}
139
140impl Unmarshal for TelephoneEvent {
141    /// Reads one 4-byte report, ignoring the R bit.
142    fn unmarshal<B>(buf: &mut B) -> Result<Self>
143    where
144        Self: Sized,
145        B: Buf,
146    {
147        if buf.remaining() < TELEPHONE_EVENT_SIZE {
148            return Err(Error::ErrShortPacket);
149        }
150        let event = buf.get_u8();
151        let flags = buf.get_u8();
152        let duration = buf.get_u16();
153        Ok(TelephoneEvent {
154            event,
155            end: flags & 0x80 != 0,
156            volume: flags & 0x3F,
157            duration,
158        })
159    }
160}
161
162/// Parses a telephone-event payload holding one or more reports (section 2.5.1.5).
163///
164/// # Errors
165///
166/// Fails on an empty payload or one whose length is not a multiple of 4.
167pub fn parse_telephone_events(payload: &[u8]) -> Result<Vec<TelephoneEvent>> {
168    if payload.is_empty() || !payload.len().is_multiple_of(TELEPHONE_EVENT_SIZE) {
169        return Err(Error::ErrShortPacket);
170    }
171    let mut buf = payload;
172    let mut events = Vec::with_capacity(payload.len() / TELEPHONE_EVENT_SIZE);
173    while buf.has_remaining() {
174        events.push(TelephoneEvent::unmarshal(&mut buf)?);
175    }
176    Ok(events)
177}
178
179/// Marshals one or more reports into one payload, in order (section 2.5.1.5).
180///
181/// # Errors
182///
183/// Fails on an empty list or a report whose volume exceeds 63.
184pub fn marshal_telephone_events(events: &[TelephoneEvent]) -> Result<Bytes> {
185    if events.is_empty() {
186        return Err(Error::Other(
187            "telephone-event payload needs an event".into(),
188        ));
189    }
190    let mut out = BytesMut::zeroed(events.len() * TELEPHONE_EVENT_SIZE);
191    for (i, event) in events.iter().enumerate() {
192        let start = i * TELEPHONE_EVENT_SIZE;
193        event.marshal_to(&mut out[start..start + TELEPHONE_EVENT_SIZE])?;
194    }
195    Ok(out.freeze())
196}
197
198/// A set of event codes, as the `events` fmtp parameter lists them (section 2.4).
199///
200/// Bounded by construction: one bit per code 0 to 255. [`EventSet::default`] is the set a sender
201/// assumes when the receiver sent no `events` parameter: DTMF 0 to 15 (section 2.5.1.1).
202#[derive(PartialEq, Eq, Copy, Clone)]
203pub struct EventSet {
204    bits: [u64; 4],
205}
206
207impl Default for EventSet {
208    fn default() -> Self {
209        EventSet::dtmf()
210    }
211}
212
213impl fmt::Debug for EventSet {
214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215        write!(f, "EventSet({self})")
216    }
217}
218
219impl fmt::Display for EventSet {
220    /// The fmtp form: ascending, consecutive codes as `a-b` ranges, comma-separated, no spaces.
221    /// An empty set formats as the empty string.
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        let mut first = true;
224        let mut code: u16 = 0;
225        while code <= 255 {
226            if !self.contains(code as u8) {
227                code += 1;
228                continue;
229            }
230            let start = code;
231            while code < 255 && self.contains((code + 1) as u8) {
232                code += 1;
233            }
234            if !first {
235                f.write_str(",")?;
236            }
237            first = false;
238            if start == code {
239                write!(f, "{start}")?;
240            } else {
241                write!(f, "{start}-{code}")?;
242            }
243            code += 1;
244        }
245        Ok(())
246    }
247}
248
249impl EventSet {
250    /// The empty set.
251    pub fn empty() -> Self {
252        EventSet { bits: [0; 4] }
253    }
254
255    /// DTMF events 0 to 15.
256    pub fn dtmf() -> Self {
257        let mut set = EventSet::empty();
258        set.insert_range(DTMF_0, DTMF_D);
259        set
260    }
261
262    /// Parses an `events` list such as `0-15,32,36` (section 2.4): comma-separated codes or
263    /// `low-high` ranges, unsorted, no white space.
264    ///
265    /// # Errors
266    ///
267    /// Fails on an empty list or element, white space, a non-decimal token, a code above 255
268    /// or a range whose upper bound is below its lower bound.
269    pub fn parse(list: &str) -> Result<Self> {
270        let mut set = EventSet::empty();
271        if list.is_empty() {
272            return Err(Error::Other("empty telephone-event list".into()));
273        }
274        for element in list.split(',') {
275            match element.split_once('-') {
276                Some((low, high)) => {
277                    let low = parse_event_code(low)?;
278                    let high = parse_event_code(high)?;
279                    if high < low {
280                        return Err(Error::Other(format!(
281                            "telephone-event range {element} is reversed"
282                        )));
283                    }
284                    set.insert_range(low, high);
285                }
286                None => set.insert(parse_event_code(element)?),
287            }
288        }
289        Ok(set)
290    }
291
292    /// The set a sender may use towards a receiver: the receiver's `events` list when it sent
293    /// one, otherwise DTMF 0 to 15 (section 2.5.1.1).
294    ///
295    /// # Errors
296    ///
297    /// Fails when the list is present and malformed (see [`EventSet::parse`]).
298    pub fn from_peer_fmtp(list: Option<&str>) -> Result<Self> {
299        match list {
300            Some(list) => EventSet::parse(list),
301            None => Ok(EventSet::dtmf()),
302        }
303    }
304
305    /// Adds one code.
306    pub fn insert(&mut self, event: u8) {
307        self.bits[usize::from(event >> 6)] |= 1u64 << (event & 63);
308    }
309
310    /// Adds every code from `low` to `high` inclusive.
311    pub fn insert_range(&mut self, low: u8, high: u8) {
312        for event in low..=high {
313            self.insert(event);
314        }
315    }
316
317    /// Removes one code.
318    pub fn remove(&mut self, event: u8) {
319        self.bits[usize::from(event >> 6)] &= !(1u64 << (event & 63));
320    }
321
322    /// Whether `event` is in the set.
323    pub fn contains(&self, event: u8) -> bool {
324        self.bits[usize::from(event >> 6)] & (1u64 << (event & 63)) != 0
325    }
326
327    /// Whether the set has no code.
328    pub fn is_empty(&self) -> bool {
329        self.bits.iter().all(|b| *b == 0)
330    }
331
332    /// Number of codes in the set.
333    pub fn len(&self) -> usize {
334        self.bits.iter().map(|b| b.count_ones() as usize).sum()
335    }
336
337    /// The codes in ascending order.
338    pub fn iter(&self) -> impl Iterator<Item = u8> + '_ {
339        (0..=255u8).filter(|e| self.contains(*e))
340    }
341}
342
343fn parse_event_code(token: &str) -> Result<u8> {
344    if token.is_empty() || token.len() > 3 || !token.bytes().all(|b| b.is_ascii_digit()) {
345        return Err(Error::Other(format!(
346            "invalid telephone-event code {token:?}"
347        )));
348    }
349    token
350        .parse::<u8>()
351        .map_err(|_| Error::Other(format!("telephone-event code {token} exceeds 255")))
352}
353
354/// One packet the [`TelephoneEventSender`] wants sent: the RTP header fields it decides plus the
355/// payload. The caller fills in the sequence number (the audio stream's next one), SSRC and the
356/// telephone-event payload type.
357#[derive(PartialEq, Eq, Debug, Copy, Clone)]
358pub struct EventPacket {
359    /// RTP marker bit.
360    pub marker: bool,
361    /// RTP timestamp: the start of the event's current segment.
362    pub timestamp: u32,
363    /// The single event report this packet carries.
364    pub event: TelephoneEvent,
365}
366
367impl EventPacket {
368    /// The marshalled 4-byte payload.
369    ///
370    /// # Errors
371    ///
372    /// Fails only on a report with a volume above 63, which the sender never produces.
373    pub fn payload(&self) -> Result<Bytes> {
374        Ok(self.event.marshal()?.freeze())
375    }
376}
377
378#[derive(Debug, Copy, Clone)]
379struct ActiveEvent {
380    event: u8,
381    volume: u8,
382    start_timestamp: u32,
383    /// Cumulative duration reported so far, in timestamp units.
384    reported: u32,
385    /// Whether the next packet is the event's first (carries M).
386    first_pending: bool,
387}
388
389/// The sending procedures of RFC 4733 section 2.5.1 for one event at a time, sans-I/O.
390///
391/// Drive it with [`start`](Self::start), then [`update`](Self::update) at each update interval
392/// (the audio packetization interval, or 50 ms; section 2.5.1.2) and finally
393/// [`end`](Self::end). Durations passed in are cumulative since the event started, in
394/// timestamp units of the telephone-event clock. The sender
395///
396/// * sets M on the first packet only and keeps each segment's start timestamp on all its
397///   packets (sections 2.2.1, 2.2.2, 2.5.1.2);
398/// * never reports a zero duration: a zero passed in is clamped to 1 (section 2.3.5);
399/// * splits events longer than 0xFFFF units into segments: a report of exactly 0xFFFF without
400///   E, then a new segment whose timestamp is the previous one plus 0xFFFF, without M
401///   (section 2.5.1.3);
402/// * produces the final report three times, identical, with E set on all three
403///   (section 2.5.1.4), and the final report of each segment (the 0xFFFF report) three
404///   times too: "The final packet for each event and for each segment SHOULD be sent a
405///   total of three times";
406/// * refuses events outside the receiver's [`EventSet`] (section 2.5.1.1).
407#[derive(Debug, Clone)]
408pub struct TelephoneEventSender {
409    allowed: EventSet,
410    active: Option<ActiveEvent>,
411}
412
413/// How many times the final report of an event is sent (section 2.5.1.4).
414pub const TELEPHONE_EVENT_END_REPEATS: usize = 3;
415
416impl TelephoneEventSender {
417    /// A sender restricted to `allowed`, the receiver's `events` list (or
418    /// [`EventSet::default`] when the receiver sent none).
419    pub fn new(allowed: EventSet) -> Self {
420        TelephoneEventSender {
421            allowed,
422            active: None,
423        }
424    }
425
426    /// The events this sender may send.
427    pub fn allowed(&self) -> &EventSet {
428        &self.allowed
429    }
430
431    /// Whether an event is in progress.
432    pub fn is_active(&self) -> bool {
433        self.active.is_some()
434    }
435
436    /// Starts an event at `rtp_timestamp` (the audio timestamp of the instant it began).
437    /// No packet is produced until the first [`update`](Self::update) or [`end`](Self::end).
438    ///
439    /// # Errors
440    ///
441    /// Fails if an event is already in progress, the event is not in the allowed set, or the
442    /// volume exceeds 63.
443    pub fn start(&mut self, event: u8, volume: u8, rtp_timestamp: u32) -> Result<()> {
444        if self.active.is_some() {
445            return Err(Error::Other(
446                "a telephone event is already in progress".into(),
447            ));
448        }
449        if !self.allowed.contains(event) {
450            return Err(Error::Other(format!(
451                "telephone event {event} is not in the receiver's events list"
452            )));
453        }
454        if volume > TELEPHONE_EVENT_MAX_VOLUME {
455            return Err(Error::Other(format!(
456                "telephone-event volume {volume} exceeds {TELEPHONE_EVENT_MAX_VOLUME}"
457            )));
458        }
459        self.active = Some(ActiveEvent {
460            event,
461            volume,
462            start_timestamp: rtp_timestamp,
463            reported: 0,
464            first_pending: true,
465        });
466        Ok(())
467    }
468
469    /// Reports the event as still going, `total_duration` units after it started.
470    ///
471    /// Returns one packet; when the duration reaches or crosses a segment boundary, the 0xFFFF
472    /// report closing the old segment three times (section 2.5.1.4), then the first report of
473    /// the new one if the duration went past it.
474    ///
475    /// # Errors
476    ///
477    /// Fails with no event in progress, a duration smaller than the last one reported, or one
478    /// that grew by more than 0xFFFF since the last report (it would skip a whole segment).
479    pub fn update(&mut self, total_duration: u32) -> Result<Vec<EventPacket>> {
480        let mut active = self.take_checked(total_duration)?;
481        let total = total_duration.max(1);
482        let mut packets = Vec::with_capacity(1 + TELEPHONE_EVENT_END_REPEATS);
483        Self::advance(&mut active, total, &mut packets);
484        if total != active.reported {
485            let last = Self::report(&mut active, total, false);
486            // A report landing exactly on a segment's end is that segment's final packet.
487            let repeats = if total.is_multiple_of(u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION)) {
488                TELEPHONE_EVENT_END_REPEATS
489            } else {
490                1
491            };
492            for i in 0..repeats {
493                packets.push(EventPacket {
494                    marker: last.marker && i == 0,
495                    ..last
496                });
497            }
498        }
499        active.reported = total;
500        self.active = Some(active);
501        Ok(packets)
502    }
503
504    /// Ends the event, `total_duration` units after it started.
505    ///
506    /// Returns a segment-boundary packet if the duration crosses one, then the final report
507    /// three times: same timestamp, same payload, E set. Only the first of the three can carry
508    /// M (when the event produced no packet before).
509    ///
510    /// # Errors
511    ///
512    /// As [`update`](Self::update). The event stays in progress when this fails.
513    pub fn end(&mut self, total_duration: u32) -> Result<Vec<EventPacket>> {
514        let mut active = self.take_checked(total_duration)?;
515        let total = total_duration.max(1);
516        let mut packets = Vec::with_capacity(1 + TELEPHONE_EVENT_END_REPEATS);
517        Self::advance(&mut active, total, &mut packets);
518        let last = Self::report(&mut active, total, true);
519        for i in 0..TELEPHONE_EVENT_END_REPEATS {
520            packets.push(EventPacket {
521                marker: last.marker && i == 0,
522                ..last
523            });
524        }
525        self.active = None;
526        Ok(packets)
527    }
528
529    /// Abandons the event in progress without sending its end.
530    pub fn reset(&mut self) {
531        self.active = None;
532    }
533
534    fn take_checked(&mut self, total_duration: u32) -> Result<ActiveEvent> {
535        let active = self
536            .active
537            .ok_or_else(|| Error::Other("no telephone event in progress".into()))?;
538        let total = total_duration.max(1);
539        if total < active.reported {
540            return Err(Error::Other(format!(
541                "telephone-event duration {total} is below the {} already reported",
542                active.reported
543            )));
544        }
545        if total - active.reported > u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION) {
546            return Err(Error::Other(format!(
547                "telephone-event duration grew by more than 0xFFFF (from {} to {total})",
548                active.reported
549            )));
550        }
551        Ok(active)
552    }
553
554    /// Segment index of a cumulative duration (> 0): durations 1..=0xFFFF are segment 0.
555    fn segment_of(total: u32) -> u32 {
556        (total - 1) / u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION)
557    }
558
559    /// Emits the 0xFFFF report closing the segment the last report was in, if `total` lies in
560    /// a later segment. `take_checked` bounds the growth, so at most one boundary is crossed.
561    fn advance(active: &mut ActiveEvent, total: u32, packets: &mut Vec<EventPacket>) {
562        let from = if active.reported == 0 {
563            0
564        } else {
565            Self::segment_of(active.reported)
566        };
567        if Self::segment_of(total) > from {
568            let boundary = (from + 1) * u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION);
569            if active.reported != boundary {
570                // The segment's final packet, three times (section 2.5.1.4).
571                let packet = Self::report(active, boundary, false);
572                for i in 0..TELEPHONE_EVENT_END_REPEATS {
573                    packets.push(EventPacket {
574                        marker: packet.marker && i == 0,
575                        ..packet
576                    });
577                }
578                active.reported = boundary;
579            }
580        }
581    }
582
583    fn report(active: &mut ActiveEvent, total: u32, end: bool) -> EventPacket {
584        let max = u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION);
585        let segment = Self::segment_of(total);
586        let duration = (total - segment * max) as u16;
587        let marker = active.first_pending;
588        active.first_pending = false;
589        EventPacket {
590            marker,
591            timestamp: active
592                .start_timestamp
593                .wrapping_add(segment.wrapping_mul(max)),
594            event: TelephoneEvent {
595                event: active.event,
596                end,
597                volume: active.volume,
598                duration,
599            },
600        }
601    }
602}
603
604/// Every packet for one event of `total_duration` units starting at `rtp_timestamp`, with an
605/// update every `interval` units: updates at `interval`, `2 * interval`, ... below the total,
606/// then the final report three times. This is what an `RTCDTMFSender`-like caller sends for one
607/// tone (`interval` is typically 50 ms worth of units, section 2.5.1.2).
608///
609/// # Errors
610///
611/// Fails if `interval` is 0 or above 0xFFFF, or the event is refused (see
612/// [`TelephoneEventSender::start`]).
613pub fn telephone_event_packets(
614    allowed: &EventSet,
615    event: u8,
616    volume: u8,
617    rtp_timestamp: u32,
618    total_duration: u32,
619    interval: u32,
620) -> Result<Vec<EventPacket>> {
621    if interval == 0 || interval > u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION) {
622        return Err(Error::Other(format!(
623            "telephone-event update interval {interval} is out of range"
624        )));
625    }
626    let mut sender = TelephoneEventSender::new(*allowed);
627    sender.start(event, volume, rtp_timestamp)?;
628    let total = total_duration.max(1);
629    let mut packets = Vec::new();
630    let mut elapsed = interval;
631    while elapsed < total {
632        packets.extend(sender.update(elapsed)?);
633        elapsed = elapsed.saturating_add(interval);
634    }
635    packets.extend(sender.end(total)?);
636    Ok(packets)
637}
638
639/// A packet carrying several events (RFC 4733 section 2.5.1.5), as
640/// [`packed_telephone_event_packets`] makes it.
641#[derive(PartialEq, Eq, Debug, Clone)]
642pub struct PackedEventPacket {
643    /// RTP marker bit.
644    pub marker: bool,
645    /// RTP timestamp: the beginning of the first event in the packet.
646    pub timestamp: u32,
647    /// The event reports, in the order the events occurred.
648    pub events: Vec<TelephoneEvent>,
649}
650
651impl PackedEventPacket {
652    /// The marshalled payload: four bytes per event.
653    ///
654    /// # Errors
655    ///
656    /// As [`marshal_telephone_events`].
657    pub fn payload(&self) -> Result<Bytes> {
658        marshal_telephone_events(&self.events)
659    }
660}
661
662/// Events that follow one another without overlap and without a pause, `(event, volume,
663/// duration)` each, the first beginning at `rtp_timestamp`, packed into one packet (RFC 4733
664/// section 2.5.1.5): "the RTP timestamp MUST identify the beginning of the first event", "the M
665/// bit MUST be set if the packet records the beginning of at least one event" (each event here
666/// begins in it), and each event's E bit and duration are those it would have alone (ended,
667/// its whole duration; a zero duration is reported as 1, section 2.3.5). The packet comes three
668/// times, identical, since it is every event's final report (section 2.5.1.4).
669///
670/// # Errors
671///
672/// Fails for no events, an event the receiver's [`EventSet`] does not allow (section 2.5.1.1),
673/// a volume above 63, and a duration above 0xFFFF (a long event is sent alone, in segments,
674/// with [`TelephoneEventSender`]).
675pub fn packed_telephone_event_packets(
676    allowed: &EventSet,
677    events: &[(u8, u8, u32)],
678    rtp_timestamp: u32,
679) -> Result<Vec<PackedEventPacket>> {
680    if events.is_empty() {
681        return Err(Error::Other("no telephone events to pack".to_owned()));
682    }
683    let mut reports = Vec::with_capacity(events.len());
684    for &(event, volume, duration) in events {
685        if !allowed.contains(event) {
686            return Err(Error::Other(format!(
687                "telephone-event {event} is not in the receiver's event list"
688            )));
689        }
690        if volume > 63 {
691            return Err(Error::Other(format!(
692                "telephone-event volume {volume} is above 63"
693            )));
694        }
695        let duration = u16::try_from(duration.max(1)).map_err(|_| {
696            Error::Other(format!(
697                "telephone-event duration {duration} needs segments: send it alone"
698            ))
699        })?;
700        reports.push(TelephoneEvent {
701            event,
702            end: true,
703            volume,
704            duration,
705        });
706    }
707    let packet = PackedEventPacket {
708        marker: true,
709        timestamp: rtp_timestamp,
710        events: reports,
711    };
712    Ok(vec![packet; TELEPHONE_EVENT_END_REPEATS])
713}
714
715/// What a [`TelephoneEventReceiver`] learned from a packet.
716#[derive(PartialEq, Eq, Debug, Copy, Clone)]
717#[non_exhaustive]
718pub enum TelephoneEventReport {
719    /// A new event began at `timestamp` (also reported when its first packets were lost).
720    Started {
721        /// Event code.
722        event: u8,
723        /// Volume of the first report seen.
724        volume: u8,
725        /// RTP timestamp of the start of the event (of its first segment seen).
726        timestamp: u32,
727    },
728    /// The event in progress has now lasted `duration` units in total, segments included.
729    Updated {
730        /// Event code.
731        event: u8,
732        /// Cumulative duration across segments.
733        duration: u32,
734    },
735    /// The event ended, after `total_duration` units in total.
736    Ended {
737        /// Event code.
738        event: u8,
739        /// Total duration across segments.
740        total_duration: u32,
741    },
742}
743
744#[derive(Debug, Copy, Clone)]
745struct ReceivedEvent {
746    event: u8,
747    first_timestamp: u32,
748    segment_timestamp: u32,
749    segment_duration: u16,
750    /// Sum of the durations of the segments before the current one.
751    completed: u32,
752}
753
754impl ReceivedEvent {
755    fn total(&self) -> u32 {
756        self.completed
757            .saturating_add(u32::from(self.segment_duration))
758    }
759
760    /// Whether `timestamp` lies in a segment of this event before or at `upto`.
761    fn covers(&self, event: u8, timestamp: u32, upto: u32) -> bool {
762        event == self.event
763            && timestamp.wrapping_sub(self.first_timestamp)
764                <= upto.wrapping_sub(self.first_timestamp)
765    }
766}
767
768/// The receiving procedures of RFC 4733 section 2.5.2, sans-I/O: feed it every
769/// telephone-event packet's timestamp, marker and payload, get back started / updated / ended
770/// reports.
771///
772/// * The three copies of a final report, and any later report for an event already ended,
773///   produce nothing (sections 2.5.1.4, 2.5.2.2), also when the final packet carried several
774///   events.
775/// * A report for the same event code whose timestamp is the previous segment's timestamp plus
776///   its duration (or plus 0xFFFF, should the 0xFFFF report itself be lost) continues a long
777///   event: durations add up across segments (section 2.5.2.3). A lone report with M set
778///   always starts a new event.
779/// * A report without M for an unknown event starts it (the first packet was lost); a report
780///   for a new event or timestamp ends the event in progress (its end packets were lost).
781/// * The R bit is ignored, and zero-duration reports are ignored (no event is treated as a
782///   state, section 2.3.5).
783/// * Several reports in one packet are handled in order, each starting where the previous one
784///   ended (section 2.5.2.4).
785///
786/// State is one event in progress plus the last ended one; nothing grows with input.
787#[derive(Debug, Default, Clone)]
788pub struct TelephoneEventReceiver {
789    current: Option<ReceivedEvent>,
790    last_ended: Option<ReceivedEvent>,
791}
792
793impl TelephoneEventReceiver {
794    /// A receiver with no event in progress.
795    pub fn new() -> Self {
796        Self::default()
797    }
798
799    /// The event in progress, if any: its code and cumulative duration.
800    pub fn current(&self) -> Option<(u8, u32)> {
801        self.current.map(|c| (c.event, c.total()))
802    }
803
804    /// Handles one telephone-event packet.
805    ///
806    /// # Errors
807    ///
808    /// Fails on a malformed payload (see [`parse_telephone_events`]); state is unchanged then.
809    pub fn receive(
810        &mut self,
811        timestamp: u32,
812        marker: bool,
813        payload: &[u8],
814    ) -> Result<Vec<TelephoneEventReport>> {
815        let events = parse_telephone_events(payload)?;
816        let lone_marker = marker && events.len() == 1;
817        let mut reports = Vec::new();
818        let mut block_timestamp = timestamp;
819        for event in &events {
820            self.receive_one(block_timestamp, lone_marker, event, &mut reports);
821            block_timestamp = block_timestamp.wrapping_add(u32::from(event.duration));
822        }
823        Ok(reports)
824    }
825
826    fn receive_one(
827        &mut self,
828        timestamp: u32,
829        lone_marker: bool,
830        report: &TelephoneEvent,
831        out: &mut Vec<TelephoneEventReport>,
832    ) {
833        if report.duration == 0 {
834            return;
835        }
836        // A report at or before the start of the last ended event's last segment is stale,
837        // whatever its code: events do not overlap (section 2.5.1.5), so it belongs to that
838        // event or to one before it. This covers the repeats of a final packet that carried
839        // several events (section 2.5.1.4).
840        if let Some(ended) = self.last_ended
841            && ended.segment_timestamp.wrapping_sub(timestamp) < 0x8000_0000
842        {
843            return;
844        }
845
846        if let Some(mut current) = self.current {
847            if current.covers(report.event, timestamp, current.segment_timestamp) {
848                if timestamp != current.segment_timestamp {
849                    // A late report from an earlier segment of this event.
850                    return;
851                }
852                if report.duration > current.segment_duration {
853                    current.segment_duration = report.duration;
854                    out.push(TelephoneEventReport::Updated {
855                        event: current.event,
856                        duration: current.total(),
857                    });
858                }
859                self.current = Some(current);
860                if report.end {
861                    self.finish(out);
862                }
863                return;
864            }
865
866            let step = timestamp.wrapping_sub(current.segment_timestamp);
867            let continues = report.event == current.event
868                && !lone_marker
869                && (step == u32::from(current.segment_duration)
870                    || step == u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION));
871            if continues {
872                current.completed = current.completed.saturating_add(step);
873                current.segment_timestamp = timestamp;
874                current.segment_duration = report.duration;
875                out.push(TelephoneEventReport::Updated {
876                    event: current.event,
877                    duration: current.total(),
878                });
879                self.current = Some(current);
880                if report.end {
881                    self.finish(out);
882                }
883                return;
884            }
885
886            // A different event or timestamp: the current one's end packets were lost.
887            self.finish(out);
888        }
889
890        self.current = Some(ReceivedEvent {
891            event: report.event,
892            first_timestamp: timestamp,
893            segment_timestamp: timestamp,
894            segment_duration: report.duration,
895            completed: 0,
896        });
897        out.push(TelephoneEventReport::Started {
898            event: report.event,
899            volume: report.volume,
900            timestamp,
901        });
902        out.push(TelephoneEventReport::Updated {
903            event: report.event,
904            duration: u32::from(report.duration),
905        });
906        if report.end {
907            self.finish(out);
908        }
909    }
910
911    fn finish(&mut self, out: &mut Vec<TelephoneEventReport>) {
912        if let Some(current) = self.current.take() {
913            out.push(TelephoneEventReport::Ended {
914                event: current.event,
915                total_duration: current.total(),
916            });
917            self.last_ended = Some(current);
918        }
919    }
920}