#[cfg(test)]
mod telephone_event_test;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use shared::error::{Error, Result};
use shared::marshal::{Marshal, MarshalSize, Unmarshal};
use std::fmt;
pub const TELEPHONE_EVENT_SIZE: usize = 4;
pub const TELEPHONE_EVENT_MAX_VOLUME: u8 = 63;
pub const TELEPHONE_EVENT_MAX_SEGMENT_DURATION: u16 = 0xFFFF;
pub const DTMF_0: u8 = 0;
pub const DTMF_1: u8 = 1;
pub const DTMF_2: u8 = 2;
pub const DTMF_3: u8 = 3;
pub const DTMF_4: u8 = 4;
pub const DTMF_5: u8 = 5;
pub const DTMF_6: u8 = 6;
pub const DTMF_7: u8 = 7;
pub const DTMF_8: u8 = 8;
pub const DTMF_9: u8 = 9;
pub const DTMF_STAR: u8 = 10;
pub const DTMF_POUND: u8 = 11;
pub const DTMF_A: u8 = 12;
pub const DTMF_B: u8 = 13;
pub const DTMF_C: u8 = 14;
pub const DTMF_D: u8 = 15;
pub fn dtmf_event_from_char(c: char) -> Option<u8> {
match c {
'0'..='9' => Some(c as u8 - b'0'),
'*' => Some(DTMF_STAR),
'#' => Some(DTMF_POUND),
'A'..='D' => Some(c as u8 - b'A' + DTMF_A),
'a'..='d' => Some(c as u8 - b'a' + DTMF_A),
_ => None,
}
}
pub fn dtmf_char_from_event(event: u8) -> Option<char> {
match event {
0..=9 => Some((b'0' + event) as char),
DTMF_STAR => Some('*'),
DTMF_POUND => Some('#'),
DTMF_A..=DTMF_D => Some((b'A' + event - DTMF_A) as char),
_ => None,
}
}
#[derive(PartialEq, Eq, Debug, Default, Copy, Clone)]
pub struct TelephoneEvent {
pub event: u8,
pub end: bool,
pub volume: u8,
pub duration: u16,
}
impl MarshalSize for TelephoneEvent {
fn marshal_size(&self) -> usize {
TELEPHONE_EVENT_SIZE
}
}
impl Marshal for TelephoneEvent {
fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
if buf.remaining_mut() < TELEPHONE_EVENT_SIZE {
return Err(Error::ErrBufferTooSmall);
}
if self.volume > TELEPHONE_EVENT_MAX_VOLUME {
return Err(Error::Other(format!(
"telephone-event volume {} exceeds {TELEPHONE_EVENT_MAX_VOLUME}",
self.volume
)));
}
buf.put_u8(self.event);
buf.put_u8(if self.end { 0x80 } else { 0 } | self.volume);
buf.put_u16(self.duration);
Ok(TELEPHONE_EVENT_SIZE)
}
}
impl Unmarshal for TelephoneEvent {
fn unmarshal<B>(buf: &mut B) -> Result<Self>
where
Self: Sized,
B: Buf,
{
if buf.remaining() < TELEPHONE_EVENT_SIZE {
return Err(Error::ErrShortPacket);
}
let event = buf.get_u8();
let flags = buf.get_u8();
let duration = buf.get_u16();
Ok(TelephoneEvent {
event,
end: flags & 0x80 != 0,
volume: flags & 0x3F,
duration,
})
}
}
pub fn parse_telephone_events(payload: &[u8]) -> Result<Vec<TelephoneEvent>> {
if payload.is_empty() || !payload.len().is_multiple_of(TELEPHONE_EVENT_SIZE) {
return Err(Error::ErrShortPacket);
}
let mut buf = payload;
let mut events = Vec::with_capacity(payload.len() / TELEPHONE_EVENT_SIZE);
while buf.has_remaining() {
events.push(TelephoneEvent::unmarshal(&mut buf)?);
}
Ok(events)
}
pub fn marshal_telephone_events(events: &[TelephoneEvent]) -> Result<Bytes> {
if events.is_empty() {
return Err(Error::Other(
"telephone-event payload needs an event".into(),
));
}
let mut out = BytesMut::zeroed(events.len() * TELEPHONE_EVENT_SIZE);
for (i, event) in events.iter().enumerate() {
let start = i * TELEPHONE_EVENT_SIZE;
event.marshal_to(&mut out[start..start + TELEPHONE_EVENT_SIZE])?;
}
Ok(out.freeze())
}
#[derive(PartialEq, Eq, Copy, Clone)]
pub struct EventSet {
bits: [u64; 4],
}
impl Default for EventSet {
fn default() -> Self {
EventSet::dtmf()
}
}
impl fmt::Debug for EventSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "EventSet({self})")
}
}
impl fmt::Display for EventSet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut first = true;
let mut code: u16 = 0;
while code <= 255 {
if !self.contains(code as u8) {
code += 1;
continue;
}
let start = code;
while code < 255 && self.contains((code + 1) as u8) {
code += 1;
}
if !first {
f.write_str(",")?;
}
first = false;
if start == code {
write!(f, "{start}")?;
} else {
write!(f, "{start}-{code}")?;
}
code += 1;
}
Ok(())
}
}
impl EventSet {
pub fn empty() -> Self {
EventSet { bits: [0; 4] }
}
pub fn dtmf() -> Self {
let mut set = EventSet::empty();
set.insert_range(DTMF_0, DTMF_D);
set
}
pub fn parse(list: &str) -> Result<Self> {
let mut set = EventSet::empty();
if list.is_empty() {
return Err(Error::Other("empty telephone-event list".into()));
}
for element in list.split(',') {
match element.split_once('-') {
Some((low, high)) => {
let low = parse_event_code(low)?;
let high = parse_event_code(high)?;
if high < low {
return Err(Error::Other(format!(
"telephone-event range {element} is reversed"
)));
}
set.insert_range(low, high);
}
None => set.insert(parse_event_code(element)?),
}
}
Ok(set)
}
pub fn from_peer_fmtp(list: Option<&str>) -> Result<Self> {
match list {
Some(list) => EventSet::parse(list),
None => Ok(EventSet::dtmf()),
}
}
pub fn insert(&mut self, event: u8) {
self.bits[usize::from(event >> 6)] |= 1u64 << (event & 63);
}
pub fn insert_range(&mut self, low: u8, high: u8) {
for event in low..=high {
self.insert(event);
}
}
pub fn remove(&mut self, event: u8) {
self.bits[usize::from(event >> 6)] &= !(1u64 << (event & 63));
}
pub fn contains(&self, event: u8) -> bool {
self.bits[usize::from(event >> 6)] & (1u64 << (event & 63)) != 0
}
pub fn is_empty(&self) -> bool {
self.bits.iter().all(|b| *b == 0)
}
pub fn len(&self) -> usize {
self.bits.iter().map(|b| b.count_ones() as usize).sum()
}
pub fn iter(&self) -> impl Iterator<Item = u8> + '_ {
(0..=255u8).filter(|e| self.contains(*e))
}
}
fn parse_event_code(token: &str) -> Result<u8> {
if token.is_empty() || token.len() > 3 || !token.bytes().all(|b| b.is_ascii_digit()) {
return Err(Error::Other(format!(
"invalid telephone-event code {token:?}"
)));
}
token
.parse::<u8>()
.map_err(|_| Error::Other(format!("telephone-event code {token} exceeds 255")))
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub struct EventPacket {
pub marker: bool,
pub timestamp: u32,
pub event: TelephoneEvent,
}
impl EventPacket {
pub fn payload(&self) -> Result<Bytes> {
Ok(self.event.marshal()?.freeze())
}
}
#[derive(Debug, Copy, Clone)]
struct ActiveEvent {
event: u8,
volume: u8,
start_timestamp: u32,
reported: u32,
first_pending: bool,
}
#[derive(Debug, Clone)]
pub struct TelephoneEventSender {
allowed: EventSet,
active: Option<ActiveEvent>,
}
pub const TELEPHONE_EVENT_END_REPEATS: usize = 3;
impl TelephoneEventSender {
pub fn new(allowed: EventSet) -> Self {
TelephoneEventSender {
allowed,
active: None,
}
}
pub fn allowed(&self) -> &EventSet {
&self.allowed
}
pub fn is_active(&self) -> bool {
self.active.is_some()
}
pub fn start(&mut self, event: u8, volume: u8, rtp_timestamp: u32) -> Result<()> {
if self.active.is_some() {
return Err(Error::Other(
"a telephone event is already in progress".into(),
));
}
if !self.allowed.contains(event) {
return Err(Error::Other(format!(
"telephone event {event} is not in the receiver's events list"
)));
}
if volume > TELEPHONE_EVENT_MAX_VOLUME {
return Err(Error::Other(format!(
"telephone-event volume {volume} exceeds {TELEPHONE_EVENT_MAX_VOLUME}"
)));
}
self.active = Some(ActiveEvent {
event,
volume,
start_timestamp: rtp_timestamp,
reported: 0,
first_pending: true,
});
Ok(())
}
pub fn update(&mut self, total_duration: u32) -> Result<Vec<EventPacket>> {
let mut active = self.take_checked(total_duration)?;
let total = total_duration.max(1);
let mut packets = Vec::with_capacity(1 + TELEPHONE_EVENT_END_REPEATS);
Self::advance(&mut active, total, &mut packets);
if total != active.reported {
let last = Self::report(&mut active, total, false);
let repeats = if total.is_multiple_of(u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION)) {
TELEPHONE_EVENT_END_REPEATS
} else {
1
};
for i in 0..repeats {
packets.push(EventPacket {
marker: last.marker && i == 0,
..last
});
}
}
active.reported = total;
self.active = Some(active);
Ok(packets)
}
pub fn end(&mut self, total_duration: u32) -> Result<Vec<EventPacket>> {
let mut active = self.take_checked(total_duration)?;
let total = total_duration.max(1);
let mut packets = Vec::with_capacity(1 + TELEPHONE_EVENT_END_REPEATS);
Self::advance(&mut active, total, &mut packets);
let last = Self::report(&mut active, total, true);
for i in 0..TELEPHONE_EVENT_END_REPEATS {
packets.push(EventPacket {
marker: last.marker && i == 0,
..last
});
}
self.active = None;
Ok(packets)
}
pub fn reset(&mut self) {
self.active = None;
}
fn take_checked(&mut self, total_duration: u32) -> Result<ActiveEvent> {
let active = self
.active
.ok_or_else(|| Error::Other("no telephone event in progress".into()))?;
let total = total_duration.max(1);
if total < active.reported {
return Err(Error::Other(format!(
"telephone-event duration {total} is below the {} already reported",
active.reported
)));
}
if total - active.reported > u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION) {
return Err(Error::Other(format!(
"telephone-event duration grew by more than 0xFFFF (from {} to {total})",
active.reported
)));
}
Ok(active)
}
fn segment_of(total: u32) -> u32 {
(total - 1) / u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION)
}
fn advance(active: &mut ActiveEvent, total: u32, packets: &mut Vec<EventPacket>) {
let from = if active.reported == 0 {
0
} else {
Self::segment_of(active.reported)
};
if Self::segment_of(total) > from {
let boundary = (from + 1) * u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION);
if active.reported != boundary {
let packet = Self::report(active, boundary, false);
for i in 0..TELEPHONE_EVENT_END_REPEATS {
packets.push(EventPacket {
marker: packet.marker && i == 0,
..packet
});
}
active.reported = boundary;
}
}
}
fn report(active: &mut ActiveEvent, total: u32, end: bool) -> EventPacket {
let max = u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION);
let segment = Self::segment_of(total);
let duration = (total - segment * max) as u16;
let marker = active.first_pending;
active.first_pending = false;
EventPacket {
marker,
timestamp: active
.start_timestamp
.wrapping_add(segment.wrapping_mul(max)),
event: TelephoneEvent {
event: active.event,
end,
volume: active.volume,
duration,
},
}
}
}
pub fn telephone_event_packets(
allowed: &EventSet,
event: u8,
volume: u8,
rtp_timestamp: u32,
total_duration: u32,
interval: u32,
) -> Result<Vec<EventPacket>> {
if interval == 0 || interval > u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION) {
return Err(Error::Other(format!(
"telephone-event update interval {interval} is out of range"
)));
}
let mut sender = TelephoneEventSender::new(*allowed);
sender.start(event, volume, rtp_timestamp)?;
let total = total_duration.max(1);
let mut packets = Vec::new();
let mut elapsed = interval;
while elapsed < total {
packets.extend(sender.update(elapsed)?);
elapsed = elapsed.saturating_add(interval);
}
packets.extend(sender.end(total)?);
Ok(packets)
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct PackedEventPacket {
pub marker: bool,
pub timestamp: u32,
pub events: Vec<TelephoneEvent>,
}
impl PackedEventPacket {
pub fn payload(&self) -> Result<Bytes> {
marshal_telephone_events(&self.events)
}
}
pub fn packed_telephone_event_packets(
allowed: &EventSet,
events: &[(u8, u8, u32)],
rtp_timestamp: u32,
) -> Result<Vec<PackedEventPacket>> {
if events.is_empty() {
return Err(Error::Other("no telephone events to pack".to_owned()));
}
let mut reports = Vec::with_capacity(events.len());
for &(event, volume, duration) in events {
if !allowed.contains(event) {
return Err(Error::Other(format!(
"telephone-event {event} is not in the receiver's event list"
)));
}
if volume > 63 {
return Err(Error::Other(format!(
"telephone-event volume {volume} is above 63"
)));
}
let duration = u16::try_from(duration.max(1)).map_err(|_| {
Error::Other(format!(
"telephone-event duration {duration} needs segments: send it alone"
))
})?;
reports.push(TelephoneEvent {
event,
end: true,
volume,
duration,
});
}
let packet = PackedEventPacket {
marker: true,
timestamp: rtp_timestamp,
events: reports,
};
Ok(vec![packet; TELEPHONE_EVENT_END_REPEATS])
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
#[non_exhaustive]
pub enum TelephoneEventReport {
Started {
event: u8,
volume: u8,
timestamp: u32,
},
Updated {
event: u8,
duration: u32,
},
Ended {
event: u8,
total_duration: u32,
},
}
#[derive(Debug, Copy, Clone)]
struct ReceivedEvent {
event: u8,
first_timestamp: u32,
segment_timestamp: u32,
segment_duration: u16,
completed: u32,
}
impl ReceivedEvent {
fn total(&self) -> u32 {
self.completed
.saturating_add(u32::from(self.segment_duration))
}
fn covers(&self, event: u8, timestamp: u32, upto: u32) -> bool {
event == self.event
&& timestamp.wrapping_sub(self.first_timestamp)
<= upto.wrapping_sub(self.first_timestamp)
}
}
#[derive(Debug, Default, Clone)]
pub struct TelephoneEventReceiver {
current: Option<ReceivedEvent>,
last_ended: Option<ReceivedEvent>,
}
impl TelephoneEventReceiver {
pub fn new() -> Self {
Self::default()
}
pub fn current(&self) -> Option<(u8, u32)> {
self.current.map(|c| (c.event, c.total()))
}
pub fn receive(
&mut self,
timestamp: u32,
marker: bool,
payload: &[u8],
) -> Result<Vec<TelephoneEventReport>> {
let events = parse_telephone_events(payload)?;
let lone_marker = marker && events.len() == 1;
let mut reports = Vec::new();
let mut block_timestamp = timestamp;
for event in &events {
self.receive_one(block_timestamp, lone_marker, event, &mut reports);
block_timestamp = block_timestamp.wrapping_add(u32::from(event.duration));
}
Ok(reports)
}
fn receive_one(
&mut self,
timestamp: u32,
lone_marker: bool,
report: &TelephoneEvent,
out: &mut Vec<TelephoneEventReport>,
) {
if report.duration == 0 {
return;
}
if let Some(ended) = self.last_ended
&& ended.segment_timestamp.wrapping_sub(timestamp) < 0x8000_0000
{
return;
}
if let Some(mut current) = self.current {
if current.covers(report.event, timestamp, current.segment_timestamp) {
if timestamp != current.segment_timestamp {
return;
}
if report.duration > current.segment_duration {
current.segment_duration = report.duration;
out.push(TelephoneEventReport::Updated {
event: current.event,
duration: current.total(),
});
}
self.current = Some(current);
if report.end {
self.finish(out);
}
return;
}
let step = timestamp.wrapping_sub(current.segment_timestamp);
let continues = report.event == current.event
&& !lone_marker
&& (step == u32::from(current.segment_duration)
|| step == u32::from(TELEPHONE_EVENT_MAX_SEGMENT_DURATION));
if continues {
current.completed = current.completed.saturating_add(step);
current.segment_timestamp = timestamp;
current.segment_duration = report.duration;
out.push(TelephoneEventReport::Updated {
event: current.event,
duration: current.total(),
});
self.current = Some(current);
if report.end {
self.finish(out);
}
return;
}
self.finish(out);
}
self.current = Some(ReceivedEvent {
event: report.event,
first_timestamp: timestamp,
segment_timestamp: timestamp,
segment_duration: report.duration,
completed: 0,
});
out.push(TelephoneEventReport::Started {
event: report.event,
volume: report.volume,
timestamp,
});
out.push(TelephoneEventReport::Updated {
event: report.event,
duration: u32::from(report.duration),
});
if report.end {
self.finish(out);
}
}
fn finish(&mut self, out: &mut Vec<TelephoneEventReport>) {
if let Some(current) = self.current.take() {
out.push(TelephoneEventReport::Ended {
event: current.event,
total_duration: current.total(),
});
self.last_ended = Some(current);
}
}
}