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