rtci-rtp 0.4.1

RTP packets, header extensions (RFC 3550, RFC 8285) and codec payload formats for WebRTC
Documentation
//! RFC 4733 section 4: the tone payload and its sending procedure.

use super::*;

/// RFC 4733 section 4.3.3: the layout of Figure 2; the reserved bits are sent as zero and
/// ignored on reception.
#[test]
fn a_tone_round_trips_with_zero_reserved_bits_and_ignores_them_on_reading() {
    let tone = Tone {
        modulation: 0x0155,
        modulation_divided_by_three: true,
        volume: 10,
        duration: 160,
        frequencies: vec![350, 440],
    };
    let payload = tone.marshal().unwrap();
    assert_eq!(
        &[0xAA, 0xCA, 0x00, 0xA0, 0x01, 0x5E, 0x01, 0xB8],
        &payload[..]
    );
    assert_eq!(Some(tone.clone()), Tone::unmarshal(&payload));
    // A sender that set the reserved bits: they are ignored.
    let mut lax = payload.to_vec();
    lax[4] |= 0xF0;
    lax[6] |= 0xA0;
    assert_eq!(Some(tone), Tone::unmarshal(&lax));
}

/// RFC 4733 section 4.3.3: "The value of zero is not permitted, and tones with such a
/// duration SHOULD be ignored."
#[test]
fn a_tone_of_duration_zero_is_neither_sent_nor_taken() {
    assert!(Tone::default().marshal().is_err());
    assert_eq!(None, Tone::unmarshal(&[0x00, 0x0A, 0x00, 0x00, 0x01, 0x5E]));
    assert!(
        Tone {
            volume: 64,
            duration: 1,
            ..Default::default()
        }
        .marshal()
        .is_err()
    );
}

/// RFC 4733 section 4.4.1: each further packet of a tone has the timestamp of the one before
/// plus its duration; the marker is on the first (section 4.3.2).
#[test]
fn the_packets_of_a_long_tone_follow_on_from_each_other() {
    let tone = Tone {
        volume: 8,
        duration: 1,
        frequencies: vec![425],
        ..Default::default()
    };
    let packets = ToneSender {
        packet_duration: 160,
    }
    .packets(&tone, 4_294_967_000, 400)
    .unwrap();
    assert_eq!(3, packets.len());
    let mut expected = 4_294_967_000u32;
    for (i, packet) in packets.iter().enumerate() {
        assert_eq!(expected, packet.timestamp, "packet {i}");
        assert_eq!(i == 0, packet.marker);
        let report = Tone::unmarshal(&packet.payload).unwrap();
        assert_eq!(vec![425], report.frequencies);
        expected = expected.wrapping_add(u32::from(report.duration));
    }
    assert_eq!(
        vec![160, 160, 80],
        packets
            .iter()
            .map(|p| Tone::unmarshal(&p.payload).unwrap().duration)
            .collect::<Vec<_>>()
    );
}

fn report(payload: &[u8]) -> Tone {
    Tone::unmarshal(payload).expect("a tone report")
}

/// RFC 4733 section 4.4.1: "each packet for the tone payload type stands alone; a lost packet
/// means a gap ... the sender SHOULD combine new and old tone reports in the same RTP packet
/// using RFC 2198 audio redundancy". Each packet's RED payload carries the report before it,
/// so a receiver that lost one packet recovers its report from the next; the first packet of
/// the next tone carries the last report of the one before.
#[test]
fn tone_reports_are_combined_with_the_report_before_in_rfc_2198_redundancy() {
    use crate::codec::red::{RedDecoder, RedPacket};

    let mut sender =
        RedundantToneSender::new(101, 63, ToneIntervalControl::new(160, 160, 1)).unwrap();
    assert_eq!(63, sender.payload_type());
    let tone = Tone {
        volume: 8,
        duration: 1,
        frequencies: vec![425],
        ..Default::default()
    };
    let packets = sender.packets(&tone, 1000, 400).unwrap();
    assert_eq!(3, packets.len(), "precondition: a tone of three packets");
    assert_eq!(
        vec![(1000, true), (1160, false), (1320, false)],
        packets
            .iter()
            .map(|p| (p.timestamp, p.marker))
            .collect::<Vec<_>>()
    );

    let red: Vec<RedPacket> = packets
        .iter()
        .map(|p| RedPacket::parse(&p.payload).expect("a RED payload"))
        .collect();
    let primaries: Vec<Tone> = red
        .iter()
        .map(|r| {
            assert_eq!(101, r.primary().payload_type);
            report(&r.primary().data)
        })
        .collect();
    assert_eq!(
        vec![160, 160, 80],
        primaries.iter().map(|t| t.duration).collect::<Vec<_>>()
    );
    assert!(
        red[0].redundant().is_empty(),
        "nothing older than the first"
    );
    for i in 1..3 {
        let old = red[i].redundant();
        assert_eq!(1, old.len(), "packet {i} carries the report before it");
        assert_eq!(101, old[0].payload_type);
        assert_eq!(160, old[0].timestamp_offset, "packet {i}");
        assert_eq!(red[i - 1].primary().data, old[0].data, "packet {i}");
    }

    // The second packet is lost: its report comes back from the third.
    let mut decoder = RedDecoder::default();
    let mut received = decoder.decode(0, 1000, &packets[0].payload).unwrap();
    received.extend(decoder.decode(2, 1320, &packets[2].payload).unwrap());
    let lost = received
        .iter()
        .find(|b| b.timestamp == 1160)
        .expect("the lost packet's report is recovered");
    assert!(!lost.primary);
    assert_eq!(primaries[1], report(&lost.data));

    // The next tone's first packet carries the last report of this one.
    let next = Tone {
        frequencies: vec![350, 440],
        ..tone.clone()
    };
    let packets = sender.packets(&next, 1400, 160).unwrap();
    assert_eq!(1, packets.len());
    assert!(packets[0].marker);
    let red = RedPacket::parse(&packets[0].payload).unwrap();
    assert_eq!(vec![350, 440], report(&red.primary().data).frequencies);
    assert_eq!(1, red.redundant().len());
    assert_eq!(80, red.redundant()[0].timestamp_offset);
    assert_eq!(primaries[2], report(&red.redundant()[0].data));
}

/// RFC 4733 section 4.4.3: "If the sender determines that packets are being lost due to
/// congestion (e.g., through RTCP receiver reports), it SHOULD increase the packetization
/// interval for initial and interim tone reports ... Both the maximum packetization interval
/// and maximum increase in packetization interval at any one time are therefore a matter of
/// configuration". The interval grows by at most the configured step per lossy report, never
/// past the configured maximum, holds between the thresholds and comes back without loss.
#[test]
fn the_interval_of_initial_and_interim_reports_lengthens_while_reports_show_loss() {
    let durations = |packets: &[TonePacket]| -> Vec<u16> {
        packets
            .iter()
            .map(|p| report(&p.payload).duration)
            .collect()
    };
    let tone = Tone {
        volume: 8,
        duration: 1,
        frequencies: vec![425],
        ..Default::default()
    };

    let mut control = ToneIntervalControl::new(160, 480, 160);
    assert_eq!(160, control.packet_duration());
    assert_eq!(
        vec![160, 160, 160, 160, 160, 160, 40],
        durations(&control.sender().packets(&tone, 0, 1000).unwrap()),
        "precondition: no loss, the initial interval"
    );
    assert_eq!(
        160,
        control.on_receiver_report(0),
        "never below the initial"
    );
    assert_eq!(
        160,
        control.on_receiver_report(TONE_HIGH_LOSS_FRACTION - 1),
        "below the threshold: no change"
    );
    assert_eq!(320, control.on_receiver_report(64), "25 % lost: one step");
    assert_eq!(
        vec![320, 320, 320, 40],
        durations(&control.sender().packets(&tone, 0, 1000).unwrap())
    );
    assert_eq!(480, control.on_receiver_report(TONE_HIGH_LOSS_FRACTION));
    assert_eq!(
        480,
        control.on_receiver_report(255),
        "never past the maximum"
    );
    assert_eq!(480, control.on_receiver_report(13), "5 % lost: held");
    assert_eq!(320, control.on_receiver_report(TONE_LOW_LOSS_FRACTION));
    assert_eq!(160, control.on_receiver_report(0));
    assert_eq!(160, control.on_receiver_report(0));

    // The largest increase at any one time is the configured one.
    let mut fine = ToneIntervalControl::new(160, 1600, 40);
    assert_eq!(200, fine.on_receiver_report(255));
    assert_eq!(240, fine.on_receiver_report(255));
    let mut strict = ToneIntervalControl::new(160, 1600, 40).with_loss_thresholds(1, 0);
    assert_eq!(200, strict.on_receiver_report(1));

    // The redundant sender follows its control.
    let mut sender =
        RedundantToneSender::new(101, 63, ToneIntervalControl::new(160, 480, 160)).unwrap();
    assert_eq!(320, sender.on_receiver_report(64));
    assert_eq!(320, sender.control().packet_duration());
    let primaries: Vec<u16> = sender
        .packets(&tone, 0, 800)
        .unwrap()
        .iter()
        .map(|p| {
            let red = crate::codec::red::RedPacket::parse(&p.payload).unwrap();
            report(&red.primary().data).duration
        })
        .collect();
    assert_eq!(vec![320, 320, 160], primaries);
}