rtmp-runtime 0.13.0

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: the messages a publisher sends before its
//! first frame (Adobe RTMP 1.0 §7.1.2, §7.1.4, §7.1.5; Adobe FLV v10.1
//! Annex E §E.4.1–§E.4.3).
//!
//! A decoder cannot start on frame data alone: it needs the stream description
//! (`@setDataFrame`/`onMetaData`) and each track's decoder configuration
//! (`avcC` for AVC, the `AudioSpecificConfig` for AAC) first. [`publish_open`]
//! is that ordered plan; [`write`](PublishMessage::write) turns one message
//! into the connection's wire bytes through the session's own chunk writer,
//! and the caller writes them in order. No socket, no clock.

use alloc::vec::Vec;

use crate::RtmpError;
use crate::chunk::Message;
use crate::flv::{
    AacPacketType, AudioTagHeader, AvcPacketType, CodecId, FrameType, OnMetadata, SoundFormat,
    SoundRate, SoundSize, VideoTagHeader,
};
use crate::ids::{ChunkStreamId, MessageStreamId, Timestamp};
use crate::message::MessageTypeId;

/// One track a publish describes, as the opening messages state it.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum PublishTrack {
    /// An AVC video track: coded size and its `avcC`.
    Video {
        /// Coded picture width in pixels.
        width: u16,
        /// Coded picture height in pixels.
        height: u16,
        /// The `AVCDecoderConfigurationRecord` (`avcC`) bytes.
        avc_config: Vec<u8>,
    },
    /// An AAC audio track: its sample rate, channel count and its
    /// `AudioSpecificConfig`.
    Audio {
        /// Sample rate in Hz, as an `onMetaData` `audiosamplerate` states it.
        sample_rate: u32,
        /// Channel count; two or more is sent as `stereo`.
        channel_count: u16,
        /// The raw `AudioSpecificConfig` bytes.
        asc: Vec<u8>,
    },
}

impl PublishTrack {
    /// This track's decoder-configuration tag body at timestamp 0.
    fn sequence_header(&self) -> Result<(MessageTypeId, Vec<u8>), RtmpError> {
        match self {
            Self::Video { avc_config, .. } => {
                let mut header = VideoTagHeader::new(
                    FrameType::Keyframe,
                    CodecId::Avc,
                    Some(AvcPacketType::SequenceHeader),
                    Some(0),
                );
                header.data = avc_config;
                Ok((MessageTypeId::Video, header.to_bytes()?))
            }
            Self::Audio {
                channel_count, asc, ..
            } => {
                let mut header = AudioTagHeader::new(
                    SoundFormat::Aac,
                    SoundRate::Khz44,
                    SoundSize::Bits16,
                    AudioTagHeader::sound_type_for_channels(*channel_count),
                    Some(AacPacketType::SequenceHeader),
                );
                header.data = asc;
                Ok((MessageTypeId::Audio, header.to_bytes()?))
            }
        }
    }
}

/// The ordered messages a publisher sends between `publish` and its first
/// frame: the `@setDataFrame`/`onMetaData` stream description, then every
/// track's sequence header, each at timestamp 0.
///
/// The metadata message states [`OnMetadata`]'s properties in the publisher's
/// RTMP form ([`OnMetadata::publish_body`]), where an FLV file writes
/// [`OnMetadata::script_body`]; a live stream gives
/// no duration, because there is no length to claim.
///
/// # Errors
/// [`RtmpError::Malformed`] when `tracks` holds neither an AVC video nor an
/// AAC audio track, and [`RtmpError::FieldOverflow`] when a property key
/// exceeds its AMF0 length prefix.
pub fn publish_open(tracks: &[PublishTrack]) -> Result<Vec<PublishMessage>, RtmpError> {
    let metadata = OnMetadata::new(tracks, None)?;
    let mut plan = Vec::with_capacity(tracks.len() + 1);
    plan.push(PublishMessage::Metadata(metadata.publish_body()?));
    for track in tracks {
        let (message_type_id, body) = track.sequence_header()?;
        plan.push(PublishMessage::SequenceHeader {
            message_type_id,
            body,
        });
    }
    Ok(plan)
}

/// One message of the opening plan (RTMP §7.1.2, §7.1.4, §7.1.5).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum PublishMessage {
    /// The Data-AMF0 message payload a publisher sends (§7.1.2):
    /// `@setDataFrame`, `onMetaData` and the properties
    /// ([`OnMetadata::publish_body`]), ready to frame and write.
    Metadata(Vec<u8>),
    /// One track's AVC/AAC sequence header at timestamp 0.
    SequenceHeader {
        /// Audio (8) or video (9).
        message_type_id: MessageTypeId,
        /// The FLV tag body.
        body: Vec<u8>,
    },
}

impl PublishMessage {
    /// This message's RTMP message type.
    #[must_use]
    pub fn message_type(&self) -> MessageTypeId {
        match self {
            Self::Metadata(_) => MessageTypeId::DataAmf0,
            Self::SequenceHeader {
                message_type_id, ..
            } => *message_type_id,
        }
    }

    /// This message as one chunk-stream message at timestamp 0, ready for
    /// [`crate::chunk::ChunkWriter::write`].
    ///
    /// An Audio(8)/Video(9) message carries the FLV tag body as written
    /// (§7.1.4, §7.1.5), and a Data-AMF0(18) message the publisher's
    /// `@setDataFrame` payload (§7.1.2).
    #[must_use]
    pub fn to_message(&self) -> Message {
        let payload = match self {
            Self::Metadata(body) | Self::SequenceHeader { body, .. } => body.clone(),
        };
        Message {
            chunk_stream_id: ChunkStreamId::new(PAYLOAD_CHUNK_STREAM_ID),
            timestamp: Timestamp::ZERO,
            message_type_id: self.message_type(),
            message_stream_id: MessageStreamId::new(DEFAULT_STREAM_ID),
            payload,
        }
    }
}

#[cfg(feature = "target")]
pub use target_split::PublishTarget;

#[cfg(feature = "target")]
mod target_split {
    use alloc::string::{String, ToString};

    /// The `app` and stream key an RTMP publish URL names: the inverse of
    /// [`crate::target::RtmpTarget::tc_url`].
    #[non_exhaustive]
    #[derive(Clone, PartialEq, Eq)]
    pub struct PublishTarget {
        /// The RTMP `app` name.
        pub app: String,
        /// The publishing name (stream key); empty when the URL states none.
        pub stream_key: String,
    }

    /// Manual `Debug`: the stream key is the publish secret and never renders
    /// (issue #1142).
    impl core::fmt::Debug for PublishTarget {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("PublishTarget")
                .field("app", &self.app)
                .field("stream_key", &"<redacted>")
                .finish()
        }
    }

    impl PublishTarget {
        /// Split an `rtmp://host[:port]/app/stream-key` URL into its `app` and
        /// stream key, with an RTMP server's own convention: everything before
        /// the **last** path segment is the app (a multi-segment app such as
        /// `app/instance` keeps its slashes) and the last segment is the stream
        /// key.
        ///
        /// A URL with no path at all falls back to `app = "live"` and an empty
        /// key (a push route configured without one), and one segment names
        /// only the app. A URL that does not parse is that same fallback rather
        /// than an error: a push route's configuration, not its URL, decides
        /// the app and key it publishes to.
        #[must_use]
        pub fn parse(url: &str) -> Self {
            let Ok(parsed) = url::Url::parse(url) else {
                return Self::default();
            };
            let segments: Vec<&str> = parsed
                .path()
                .trim_matches('/')
                .split('/')
                .filter(|segment| !segment.is_empty())
                .collect();
            match segments.split_last() {
                None => Self::default(),
                Some((last, [])) => Self {
                    app: (*last).to_string(),
                    stream_key: String::new(),
                },
                Some((last, rest)) => Self {
                    app: rest.join("/"),
                    stream_key: (*last).to_string(),
                },
            }
        }
    }

    impl Default for PublishTarget {
        fn default() -> Self {
            Self {
                app: "live".to_string(),
                stream_key: String::new(),
            }
        }
    }
}

/// Chunk stream id the publish opening messages travel on: the payload stream's
/// (audio, data), which is also where [`crate::client::ClientSession::send_audio`]
/// and [`crate::client::ClientSession::send_metadata`] put theirs, so a receiver
/// sees one continuing chunk-stream state.
const PAYLOAD_CHUNK_STREAM_ID: u32 = 4;
/// Message stream id a publish uses before `createStream` answers (the id the
/// session's own `send_*` fall back to).
const DEFAULT_STREAM_ID: u32 = 1;