rtmp-runtime 0.13.1

Sans-IO RTMP 1.0 (Adobe Real-Time Messaging Protocol) publish engine for both ends: a driveable ingest server state machine and a publish client over the handshake, chunk stream, AMF0, and message layers; optional tokio socket adapter.
Documentation
//! The publish opening sequence (RTMP 1.0 §7.1.4, §7.1.5; FLV §E.4.1–§E.4.3)
//! and the `app`/stream-key split of a publish URL.

use alloc::vec::Vec;

use crate::amf0::{Amf0Limits, Amf0Value, amf0_parse_values_with};
use crate::flv::{OnMetadata, PublishMessage, PublishTrack, publish_open};
use crate::message::MessageTypeId;

const TEST_AMF0_LIMITS: Amf0Limits = Amf0Limits {
    max_depth: 32,
    max_values: 4096,
};

/// The `avcC` record of the same real file (`flv/av.flv`'s video sequence
/// header body, after its 5-byte `VideoTagHeader`+`AVCPacketType`+`SI24`).
const AVC_CONFIG: &[u8] = &[
    0x01, 0x64, 0x00, 0x1E, 0xFF, 0xE1, 0x00, 0x19, 0x67, 0x64, 0x00, 0x1E, 0xAC, 0xD9, 0x40, 0xA0,
    0x2F, 0xF9, 0x70, 0x11, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0x3C, 0x0F, 0x18,
    0x31, 0x96, 0x01, 0x00, 0x05, 0x68, 0xEB, 0xEC, 0xB2, 0x2C,
];

/// The `AudioSpecificConfig` of the same file (`flv/av.flv`'s audio sequence
/// header body: AAC-LC, 44.1 kHz, mono).
const ASC: &[u8] = &[0x12, 0x08];

/// Bytes of the AMF0 `onMetaData` string: marker, `u16` length, name.
const AMF0_STRING_ONMETADATA_LEN: usize = 3 + 10;

/// The audio track description a publisher sends on a 44.1 kHz mono AAC
/// track: the track's own sample rate and the sample size its `AudioSpecificConfig`
/// states.
fn av_and_aac() -> Vec<PublishTrack> {
    alloc::vec![
        PublishTrack::Video {
            width: 320,
            height: 240,
            avc_config: Vec::from(AVC_CONFIG),
        },
        PublishTrack::Audio {
            sample_rate: 44_100,
            channel_count: 1,
            asc: Vec::from(ASC),
        },
    ]
}

#[test]
fn the_plan_is_metadata_then_video_then_audio() {
    let plan = publish_open(&av_and_aac()).expect("the plan builds");
    let kinds: Vec<MessageTypeId> = plan.iter().map(PublishMessage::message_type).collect();
    assert_eq!(
        kinds,
        [
            MessageTypeId::DataAmf0,
            MessageTypeId::Video,
            MessageTypeId::Audio
        ]
    );
}

/// The properties of an `onMetaData` AMF0 body (`handler`, then an ECMA array).
fn script_properties(body: &[u8]) -> Vec<(alloc::string::String, Amf0Value)> {
    let values = amf0_parse_values_with(body, TEST_AMF0_LIMITS)
        .expect("the FLV script body parses")
        .0;
    match values.as_slice() {
        [Amf0Value::String(handler), Amf0Value::EcmaArray(properties)] => {
            assert_eq!(handler, "onMetaData");
            properties.clone()
        }
        other => panic!("not an onMetaData script body: {other:?}"),
    }
}

#[test]
fn the_metadata_message_is_the_publishers_data_message_without_a_duration() {
    let plan = publish_open(&av_and_aac()).expect("the plan builds");
    let PublishMessage::Metadata(body) = &plan[0] else {
        panic!("the first message is the metadata body");
    };
    let values = amf0_parse_values_with(body, TEST_AMF0_LIMITS)
        .expect("the data message parses")
        .0;
    let [
        Amf0Value::String(set),
        Amf0Value::String(handler),
        Amf0Value::EcmaArray(properties),
    ] = values.as_slice()
    else {
        panic!("not @setDataFrame, onMetaData, array: {values:?}");
    };
    assert_eq!(
        (set.as_str(), handler.as_str()),
        ("@setDataFrame", "onMetaData")
    );
    let names: Vec<&str> = properties.iter().map(|(name, _)| name.as_str()).collect();
    assert_eq!(
        names,
        [
            "width",
            "height",
            "videocodecid",
            "audiocodecid",
            "audiosamplerate",
            "stereo"
        ],
        "a live stream states no duration"
    );
    assert_eq!(properties[0].1, Amf0Value::Number(320.0));
    assert_eq!(properties[1].1, Amf0Value::Number(240.0));
    assert_eq!(properties[5].1, Amf0Value::Boolean(false));
}

/// The FLV file's script tag and the publisher's data message are two wire
/// forms of one property set.
#[test]
fn both_metadata_forms_state_the_same_properties() {
    let tracks = [
        PublishTrack::Video {
            width: 320,
            height: 240,
            avc_config: Vec::new(),
        },
        PublishTrack::Audio {
            sample_rate: 44_100,
            channel_count: 1,
            asc: Vec::new(),
        },
    ];
    let metadata = OnMetadata::new(&tracks, None).expect("builds");
    let file = metadata.script_body().expect("file form");
    assert!(
        file.starts_with(&[0x02, 0x00, 0x0A]),
        "the file form begins with the AMF0 onMetaData name (§E.4.1)"
    );
    let publish = metadata.publish_body().expect("publish form");
    assert_eq!(
        crate::flv::strip_set_data_frame(&publish)[..AMF0_STRING_ONMETADATA_LEN],
        file[..AMF0_STRING_ONMETADATA_LEN],
        "stripping @setDataFrame leaves the file form's handler name first"
    );
    let publish_values = amf0_parse_values_with(&publish, TEST_AMF0_LIMITS)
        .expect("parses")
        .0;
    assert_eq!(
        publish_values.last(),
        Some(&Amf0Value::EcmaArray(script_properties(&file)))
    );
}

#[test]
fn the_sequence_headers_are_the_files_own_tag_bodies() {
    let plan = publish_open(&av_and_aac()).expect("the plan builds");
    let PublishMessage::SequenceHeader {
        message_type_id,
        body,
    } = &plan[1]
    else {
        panic!("the second message is the video sequence header");
    };
    assert_eq!(*message_type_id, MessageTypeId::Video);
    let mut expected = alloc::vec![0x17, 0x00, 0x00, 0x00, 0x00];
    expected.extend_from_slice(AVC_CONFIG);
    assert_eq!(body, &expected);
    let PublishMessage::SequenceHeader {
        message_type_id,
        body,
    } = &plan[2]
    else {
        panic!("the third message is the audio sequence header");
    };
    assert_eq!(*message_type_id, MessageTypeId::Audio);
    assert_eq!(body, &alloc::vec![0xAE, 0x00, 0x12, 0x08]);
}

#[test]
fn the_metadata_message_goes_out_as_the_data_message_it_is() {
    let plan = publish_open(&av_and_aac()).expect("the plan builds");
    let message = plan[0].to_message();
    assert_eq!(message.message_type_id, MessageTypeId::DataAmf0);
    let PublishMessage::Metadata(body) = &plan[0] else {
        panic!("the first message is the metadata body");
    };
    assert_eq!(&message.payload, body);
}

#[test]
fn a_publish_without_a_carriable_track_is_refused() {
    assert!(publish_open(&[]).is_err());
}