Skip to main content

rtmp_runtime/flv/
publish.rs

1//! The publish opening sequence: the messages a publisher sends before its
2//! first frame (Adobe RTMP 1.0 §7.1.2, §7.1.4, §7.1.5; Adobe FLV v10.1
3//! Annex E §E.4.1–§E.4.3).
4//!
5//! A decoder cannot start on frame data alone: it needs the stream description
6//! (`@setDataFrame`/`onMetaData`) and each track's decoder configuration
7//! (`avcC` for AVC, the `AudioSpecificConfig` for AAC) first. [`publish_open`]
8//! is that ordered plan; [`write`](PublishMessage::write) turns one message
9//! into the connection's wire bytes through the session's own chunk writer,
10//! and the caller writes them in order. No socket, no clock.
11
12use alloc::vec::Vec;
13
14use crate::RtmpError;
15use crate::chunk::Message;
16use crate::flv::{
17    AacPacketType, AudioTagHeader, AvcPacketType, CodecId, FrameType, OnMetadata, SoundFormat,
18    SoundRate, SoundSize, VideoTagHeader,
19};
20use crate::ids::{ChunkStreamId, MessageStreamId, Timestamp};
21use crate::message::MessageTypeId;
22
23/// One track a publish describes, as the opening messages state it.
24#[non_exhaustive]
25#[derive(Debug, Clone, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub enum PublishTrack {
28    /// An AVC video track: coded size and its `avcC`.
29    Video {
30        /// Coded picture width in pixels.
31        width: u16,
32        /// Coded picture height in pixels.
33        height: u16,
34        /// The `AVCDecoderConfigurationRecord` (`avcC`) bytes.
35        avc_config: Vec<u8>,
36    },
37    /// An AAC audio track: its sample rate, channel count and its
38    /// `AudioSpecificConfig`.
39    Audio {
40        /// Sample rate in Hz, as an `onMetaData` `audiosamplerate` states it.
41        sample_rate: u32,
42        /// Channel count; two or more is sent as `stereo`.
43        channel_count: u16,
44        /// The raw `AudioSpecificConfig` bytes.
45        asc: Vec<u8>,
46    },
47}
48
49impl PublishTrack {
50    /// This track's decoder-configuration tag body at timestamp 0.
51    fn sequence_header(&self) -> Result<(MessageTypeId, Vec<u8>), RtmpError> {
52        match self {
53            Self::Video { avc_config, .. } => {
54                let mut header = VideoTagHeader::new(
55                    FrameType::Keyframe,
56                    CodecId::Avc,
57                    Some(AvcPacketType::SequenceHeader),
58                    Some(0),
59                );
60                header.data = avc_config;
61                Ok((MessageTypeId::Video, header.to_bytes()?))
62            }
63            Self::Audio {
64                channel_count, asc, ..
65            } => {
66                let mut header = AudioTagHeader::new(
67                    SoundFormat::Aac,
68                    SoundRate::Khz44,
69                    SoundSize::Bits16,
70                    AudioTagHeader::sound_type_for_channels(*channel_count),
71                    Some(AacPacketType::SequenceHeader),
72                );
73                header.data = asc;
74                Ok((MessageTypeId::Audio, header.to_bytes()?))
75            }
76        }
77    }
78}
79
80/// The ordered messages a publisher sends between `publish` and its first
81/// frame: the `@setDataFrame`/`onMetaData` stream description, then every
82/// track's sequence header, each at timestamp 0.
83///
84/// The metadata message states [`OnMetadata`]'s properties in the publisher's
85/// RTMP form ([`OnMetadata::publish_body`]), where an FLV file writes
86/// [`OnMetadata::script_body`]; a live stream gives
87/// no duration, because there is no length to claim.
88///
89/// # Errors
90/// [`RtmpError::Malformed`] when `tracks` holds neither an AVC video nor an
91/// AAC audio track, and [`RtmpError::FieldOverflow`] when a property key
92/// exceeds its AMF0 length prefix.
93pub fn publish_open(tracks: &[PublishTrack]) -> Result<Vec<PublishMessage>, RtmpError> {
94    let metadata = OnMetadata::new(tracks, None)?;
95    let mut plan = Vec::with_capacity(tracks.len() + 1);
96    plan.push(PublishMessage::Metadata(metadata.publish_body()?));
97    for track in tracks {
98        let (message_type_id, body) = track.sequence_header()?;
99        plan.push(PublishMessage::SequenceHeader {
100            message_type_id,
101            body,
102        });
103    }
104    Ok(plan)
105}
106
107/// One message of the opening plan (RTMP §7.1.2, §7.1.4, §7.1.5).
108#[non_exhaustive]
109#[derive(Debug, Clone, PartialEq)]
110pub enum PublishMessage {
111    /// The Data-AMF0 message payload a publisher sends (§7.1.2):
112    /// `@setDataFrame`, `onMetaData` and the properties
113    /// ([`OnMetadata::publish_body`]), ready to frame and write.
114    Metadata(Vec<u8>),
115    /// One track's AVC/AAC sequence header at timestamp 0.
116    SequenceHeader {
117        /// Audio (8) or video (9).
118        message_type_id: MessageTypeId,
119        /// The FLV tag body.
120        body: Vec<u8>,
121    },
122}
123
124impl PublishMessage {
125    /// This message's RTMP message type.
126    #[must_use]
127    pub fn message_type(&self) -> MessageTypeId {
128        match self {
129            Self::Metadata(_) => MessageTypeId::DataAmf0,
130            Self::SequenceHeader {
131                message_type_id, ..
132            } => *message_type_id,
133        }
134    }
135
136    /// This message as one chunk-stream message at timestamp 0, ready for
137    /// [`crate::chunk::ChunkWriter::write`].
138    ///
139    /// An Audio(8)/Video(9) message carries the FLV tag body as written
140    /// (§7.1.4, §7.1.5), and a Data-AMF0(18) message the publisher's
141    /// `@setDataFrame` payload (§7.1.2).
142    #[must_use]
143    pub fn to_message(&self) -> Message {
144        let payload = match self {
145            Self::Metadata(body) | Self::SequenceHeader { body, .. } => body.clone(),
146        };
147        Message {
148            chunk_stream_id: ChunkStreamId::new(PAYLOAD_CHUNK_STREAM_ID),
149            timestamp: Timestamp::ZERO,
150            message_type_id: self.message_type(),
151            message_stream_id: MessageStreamId::new(DEFAULT_STREAM_ID),
152            payload,
153        }
154    }
155}
156
157#[cfg(feature = "target")]
158pub use target_split::PublishTarget;
159
160#[cfg(feature = "target")]
161mod target_split {
162    use alloc::string::{String, ToString};
163
164    /// The `app` and stream key an RTMP publish URL names: the inverse of
165    /// [`crate::target::RtmpTarget::tc_url`].
166    #[non_exhaustive]
167    #[derive(Clone, PartialEq, Eq)]
168    pub struct PublishTarget {
169        /// The RTMP `app` name.
170        pub app: String,
171        /// The publishing name (stream key); empty when the URL states none.
172        pub stream_key: String,
173    }
174
175    /// Manual `Debug`: the stream key is the publish secret and never renders
176    /// (issue #1142).
177    impl core::fmt::Debug for PublishTarget {
178        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
179            f.debug_struct("PublishTarget")
180                .field("app", &self.app)
181                .field("stream_key", &"<redacted>")
182                .finish()
183        }
184    }
185
186    impl PublishTarget {
187        /// Split an `rtmp://host[:port]/app/stream-key` URL into its `app` and
188        /// stream key, with an RTMP server's own convention: everything before
189        /// the **last** path segment is the app (a multi-segment app such as
190        /// `app/instance` keeps its slashes) and the last segment is the stream
191        /// key.
192        ///
193        /// A URL with no path at all falls back to `app = "live"` and an empty
194        /// key (a push route configured without one), and one segment names
195        /// only the app. A URL that does not parse is that same fallback rather
196        /// than an error: a push route's configuration, not its URL, decides
197        /// the app and key it publishes to.
198        #[must_use]
199        pub fn parse(url: &str) -> Self {
200            let Ok(parsed) = url::Url::parse(url) else {
201                return Self::default();
202            };
203            let segments: Vec<&str> = parsed
204                .path()
205                .trim_matches('/')
206                .split('/')
207                .filter(|segment| !segment.is_empty())
208                .collect();
209            match segments.split_last() {
210                None => Self::default(),
211                Some((last, [])) => Self {
212                    app: (*last).to_string(),
213                    stream_key: String::new(),
214                },
215                Some((last, rest)) => Self {
216                    app: rest.join("/"),
217                    stream_key: (*last).to_string(),
218                },
219            }
220        }
221    }
222
223    impl Default for PublishTarget {
224        fn default() -> Self {
225            Self {
226                app: "live".to_string(),
227                stream_key: String::new(),
228            }
229        }
230    }
231}
232
233/// Chunk stream id the publish opening messages travel on: the payload stream's
234/// (audio, data), which is also where [`crate::client::ClientSession::send_audio`]
235/// and [`crate::client::ClientSession::send_metadata`] put theirs, so a receiver
236/// sees one continuing chunk-stream state.
237const PAYLOAD_CHUNK_STREAM_ID: u32 = 4;
238/// Message stream id a publish uses before `createStream` answers (the id the
239/// session's own `send_*` fall back to).
240const DEFAULT_STREAM_ID: u32 = 1;