Skip to main content

rtflow_media/
lib.rs

1//! Media types and hardware-encoder integration helpers.
2//!
3//! [`AccessUnit`] carries encoded frames (Annex-B for video, raw AAC/PCM
4//! for audio) into the data plane; the `*_video`/`*_audio` constructors
5//! below remove the SDP/clock boilerplate when wiring a hardware encoder
6//! (HiSilicon HiMPP VENC, V4L2, ...) into the framework.
7
8pub mod bitstream;
9pub mod clock;
10pub mod connection;
11pub mod crypto;
12pub mod demux;
13pub mod flv;
14pub mod vod;
15
16pub use connection::SdpConnection;
17pub use crypto::SdpCrypto;
18pub use demux::{DemuxedSample, Demuxer};
19
20/// MPEG-TS packet size in bytes.
21pub const TS_PACKET_SIZE: usize = 188;
22
23use bytes::Bytes;
24use std::{sync::Arc, time::Duration};
25pub type TrackId = u8;
26pub type RtpTimestamp = u32;
27#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
28#[non_exhaustive]
29pub enum Codec {
30    H264,
31    H265,
32    Aac,
33    Pcma,
34    Pcmu,
35    Opus,
36    Vp8,
37    Vp9,
38    /// MPEG-1/2 Audio (MP3), RFC 2250/5219.
39    Mp3,
40    /// G.726 at 16 kbit/s (RFC 3551).
41    G726_16,
42    /// G.726 at 24 kbit/s.
43    G726_24,
44    /// G.726 at 32 kbit/s.
45    G726_32,
46    /// G.726 at 40 kbit/s.
47    G726_40,
48    /// AV1 video (draft-ietf-payload-av1).
49    Av1,
50    /// Motion JPEG (RFC 2435).
51    Jpeg,
52    /// H.263 (RFC 4629, `H263-1998`).
53    H263,
54    /// MPEG-4 Part 2 Visual (RFC 3016, `MP4V-ES`).
55    Mpeg4,
56}
57#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub enum MediaKind {
59    Video,
60    Audio,
61}
62
63/// SDP media direction (`a=sendonly`/`a=recvonly`/`a=sendrecv`/`a=inactive`).
64#[derive(Clone, Copy, Debug, Eq, PartialEq)]
65pub enum SdpDirection {
66    SendOnly,
67    RecvOnly,
68    SendRecv,
69    Inactive,
70}
71
72impl SdpDirection {
73    pub fn as_str(self) -> &'static str {
74        match self {
75            Self::SendOnly => "sendonly",
76            Self::RecvOnly => "recvonly",
77            Self::SendRecv => "sendrecv",
78            Self::Inactive => "inactive",
79        }
80    }
81
82    pub fn parse(value: &str) -> Option<Self> {
83        match value.trim().to_ascii_lowercase().as_str() {
84            "sendonly" => Some(Self::SendOnly),
85            "recvonly" => Some(Self::RecvOnly),
86            "sendrecv" => Some(Self::SendRecv),
87            "inactive" => Some(Self::Inactive),
88            _ => None,
89        }
90    }
91}
92
93/// SDP `a=rtcp:<port> [address]` override.
94#[derive(Clone, Copy, Debug, Eq, PartialEq)]
95pub struct RtcpAddress {
96    pub port: u16,
97    pub address: Option<std::net::IpAddr>,
98}
99#[derive(Clone, Debug)]
100pub struct AccessUnit {
101    pub track_id: TrackId,
102    pub codec: Codec,
103    pub pts: Duration,
104    pub dts: Option<Duration>,
105    pub rtp_timestamp: RtpTimestamp,
106    pub is_keyframe: bool,
107    pub data: Bytes,
108    /// 帧内 NAL 边界(每个 NAL 的起始偏移,末尾带 len 哨兵)。
109    /// 硬件编码器(HiSilicon VENC)直接给出时填 `Some`,下游 RTP 打包按偏移切分,
110    /// 不必扫描 Annex-B 起始码。一帧内所有 NAL 共享同一 pts/rtp_timestamp。
111    pub nal_offsets: Option<std::sync::Arc<[u32]>>,
112}
113
114impl AccessUnit {
115    /// Determine the media kind from the codec.
116    pub fn kind(&self) -> MediaKind {
117        match self.codec {
118            Codec::H264
119            | Codec::H265
120            | Codec::Vp8
121            | Codec::Vp9
122            | Codec::Av1
123            | Codec::Jpeg
124            | Codec::H263
125            | Codec::Mpeg4 => MediaKind::Video,
126            Codec::Aac
127            | Codec::Pcma
128            | Codec::Pcmu
129            | Codec::Opus
130            | Codec::Mp3
131            | Codec::G726_16
132            | Codec::G726_24
133            | Codec::G726_32
134            | Codec::G726_40 => MediaKind::Audio,
135        }
136    }
137
138    /// Construct a video access unit. `data` is an Annex-B H.264/H.265
139    /// access unit (start codes included, as produced by HiMPP VENC).
140    pub fn video(
141        track_id: TrackId,
142        codec: Codec,
143        pts: Duration,
144        rtp_timestamp: RtpTimestamp,
145        is_keyframe: bool,
146        data: Bytes,
147    ) -> Self {
148        Self {
149            track_id,
150            codec,
151            pts,
152            dts: None,
153            rtp_timestamp,
154            is_keyframe,
155            data,
156            nal_offsets: None,
157        }
158    }
159
160    /// 构造一帧“带 NAL 边界”的视频访问单元(硬件编码器多 packet 输出)。
161    ///
162    /// `data` 是整帧连续缓冲(可来自 DMA/MMZ),`nal_offsets` 是帧内每个 NAL 的
163    /// 起始偏移加末尾哨兵。下游 RTP 打包按偏移切片,**不再扫描 Annex-B 起始码**。
164    /// 一帧内所有 NAL(SPS/PPS/SEI/slice)共享同一个 `pts` / `rtp_timestamp`。
165    pub fn video_with_nal_offsets(
166        track_id: TrackId,
167        codec: Codec,
168        pts: Duration,
169        rtp_timestamp: RtpTimestamp,
170        is_keyframe: bool,
171        data: Bytes,
172        nal_offsets: std::sync::Arc<[u32]>,
173    ) -> Self {
174        Self {
175            track_id,
176            codec,
177            pts,
178            dts: None,
179            rtp_timestamp,
180            is_keyframe,
181            data,
182            nal_offsets: Some(nal_offsets),
183        }
184    }
185
186    /// Construct an audio access unit (raw AAC frame or 8 kHz G.711
187    /// sample block; the caller supplies the RTP timestamp).
188    pub fn audio(
189        track_id: TrackId,
190        codec: Codec,
191        pts: Duration,
192        rtp_timestamp: RtpTimestamp,
193        data: Bytes,
194    ) -> Self {
195        Self {
196            track_id,
197            codec,
198            pts,
199            dts: None,
200            rtp_timestamp,
201            is_keyframe: true,
202            data,
203            nal_offsets: None,
204        }
205    }
206}
207#[derive(Clone, Debug, Eq, PartialEq)]
208pub struct TrackDescription {
209    pub id: TrackId,
210    pub kind: MediaKind,
211    pub codec: Codec,
212    pub clock_rate: u32,
213    pub channels: Option<u8>,
214    pub payload_type: u8,
215    pub fmtp: Option<Arc<str>>,
216    pub control: Arc<str>,
217    /// Video width in pixels (if known).
218    pub width: Option<u32>,
219    /// Video height in pixels (if known).
220    pub height: Option<u32>,
221    /// Video frame rate as (numerator, denominator) (if known).
222    pub frame_rate: Option<(u32, u32)>,
223    /// SDP media direction; `None` means unspecified.
224    pub direction: Option<SdpDirection>,
225    /// SDP `a=ptime` packetization interval in milliseconds.
226    pub ptime: Option<u32>,
227    /// SDP `a=rtcp` RTCP port/address override.
228    pub rtcp: Option<RtcpAddress>,
229    /// SDP `b=AS` bandwidth in kbit/s.
230    pub bandwidth_as: Option<u32>,
231    /// RFC 4588 RTX mapping when the SDP advertised a retransmission stream.
232    pub rtx: Option<RtxConfig>,
233    /// SRTP crypto parameters from SDP `a=crypto:` attribute.
234    pub crypto: Option<crate::crypto::SdpCrypto>,
235}
236impl TrackDescription {
237    /// H.264 video track from encoder parameter sets.
238    ///
239    /// `sps`/`pps` are the NAL bodies *without* start codes (extract them
240    /// with [`bitstream::h264_parameter_sets`] from an Annex-B IDR).
241    /// `sps`/`pps` may be empty for raw single-NAL setups, in which case
242    /// the fmtp is a plain `packetization-mode=1` (the mount auto-injects
243    /// `sprop-parameter-sets` once a keyframe with parameter sets arrives).
244    pub fn h264_video(
245        id: TrackId,
246        sps: &[u8],
247        pps: &[u8],
248        width: u32,
249        height: u32,
250        frame_rate: u32,
251    ) -> Self {
252        // Empty parameter sets → no fmtp yet: the mount auto-injects
253        // sprop-parameter-sets from the first keyframe that carries them
254        // (hardware encoders with separated SPS/PPS), which DESCRIBE then
255        // merges in. A stream without any parameter sets still works when
256        // every IDR carries them inline (single-NAL packaging is valid
257        // under the default packetization-mode=0).
258        let fmtp = if sps.is_empty() || pps.is_empty() {
259            None
260        } else {
261            Some(Arc::from(bitstream::h264_fmtp(sps, pps)))
262        };
263        Self {
264            id,
265            kind: MediaKind::Video,
266            codec: Codec::H264,
267            clock_rate: crate::clock::VIDEO_CLOCK_RATE,
268            channels: None,
269            payload_type: 96,
270            fmtp,
271            control: Arc::from(format!("track{id}")),
272            width: Some(width),
273            height: Some(height),
274            frame_rate: Some((frame_rate, 1)),
275            direction: None,
276            ptime: None,
277            rtcp: None,
278            bandwidth_as: None,
279            rtx: None,
280            crypto: None,
281        }
282    }
283
284    /// H.265 video track from encoder parameter sets (VPS/SPS/PPS NAL
285    /// bodies without start codes).
286    pub fn h265_video(
287        id: TrackId,
288        vps: &[u8],
289        sps: &[u8],
290        pps: &[u8],
291        width: u32,
292        height: u32,
293        frame_rate: u32,
294    ) -> Self {
295        let fmtp = if vps.is_empty() || sps.is_empty() || pps.is_empty() {
296            None
297        } else {
298            Some(Arc::from(bitstream::h265_fmtp(vps, sps, pps)))
299        };
300        Self {
301            id,
302            kind: MediaKind::Video,
303            codec: Codec::H265,
304            clock_rate: crate::clock::VIDEO_CLOCK_RATE,
305            channels: None,
306            payload_type: 96,
307            fmtp,
308            control: Arc::from(format!("track{id}")),
309            width: Some(width),
310            height: Some(height),
311            frame_rate: Some((frame_rate, 1)),
312            direction: None,
313            ptime: None,
314            rtcp: None,
315            bandwidth_as: None,
316            rtx: None,
317            crypto: None,
318        }
319    }
320
321    /// AAC-LC audio track (MPEG4-GENERIC, RFC 3640 fmtp with an
322    /// auto-generated `config=` AudioSpecificConfig).
323    pub fn aac_audio(id: TrackId, sample_rate: u32, channels: u8) -> Self {
324        let fmtp = bitstream::aac_audio_specific_config(sample_rate, channels)
325            .map(|config| Arc::from(bitstream::aac_fmtp(&config)));
326        Self {
327            id,
328            kind: MediaKind::Audio,
329            codec: Codec::Aac,
330            clock_rate: sample_rate,
331            channels: Some(channels),
332            payload_type: 97,
333            fmtp,
334            control: Arc::from(format!("track{id}")),
335            width: None,
336            height: None,
337            frame_rate: None,
338            direction: None,
339            ptime: None,
340            rtcp: None,
341            bandwidth_as: None,
342            rtx: None,
343            crypto: None,
344        }
345    }
346
347    /// Opus audio track (RFC 7587: 48 kHz clock, stereo by default, PT 96).
348    pub fn opus_audio(id: TrackId, channels: u8) -> Self {
349        Self {
350            id,
351            kind: MediaKind::Audio,
352            codec: Codec::Opus,
353            clock_rate: 48_000,
354            channels: Some(channels.max(1)),
355            payload_type: 96,
356            fmtp: None,
357            control: Arc::from(format!("track{id}")),
358            width: None,
359            height: None,
360            frame_rate: None,
361            direction: None,
362            ptime: Some(20),
363            rtcp: None,
364            bandwidth_as: None,
365            rtx: None,
366            crypto: None,
367        }
368    }
369
370    /// G.711 A-law audio track (8 kHz, 1 channel; no fmtp needed).
371    pub fn pcma_audio(id: TrackId, sample_rate: u32, channels: u8) -> Self {
372        Self {
373            id,
374            kind: MediaKind::Audio,
375            codec: Codec::Pcma,
376            clock_rate: sample_rate,
377            channels: Some(channels),
378            payload_type: 8,
379            fmtp: None,
380            control: Arc::from(format!("track{id}")),
381            width: None,
382            height: None,
383            frame_rate: None,
384            direction: None,
385            ptime: None,
386            rtcp: None,
387            bandwidth_as: None,
388            rtx: None,
389            crypto: None,
390        }
391    }
392
393    /// MPEG-1/2 Audio (MP3) track: 90 kHz clock, static payload type 14.
394    pub fn mp3_audio(id: TrackId) -> Self {
395        Self {
396            id,
397            kind: MediaKind::Audio,
398            codec: Codec::Mp3,
399            clock_rate: 90_000,
400            channels: Some(2),
401            payload_type: 14,
402            fmtp: None,
403            control: Arc::from(format!("track{id}")),
404            width: None,
405            height: None,
406            frame_rate: None,
407            direction: None,
408            ptime: None,
409            rtcp: None,
410            bandwidth_as: None,
411            rtx: None,
412            crypto: None,
413        }
414    }
415
416    /// G.726 audio track (8 kHz, 1 channel); `codec` selects the bit rate.
417    fn g726_audio(id: TrackId, codec: Codec) -> Self {
418        Self {
419            id,
420            kind: MediaKind::Audio,
421            codec,
422            clock_rate: 8_000,
423            channels: Some(1),
424            payload_type: 96u8.saturating_add(id),
425            fmtp: None,
426            control: Arc::from(format!("track{id}")),
427            width: None,
428            height: None,
429            frame_rate: None,
430            direction: None,
431            ptime: None,
432            rtcp: None,
433            bandwidth_as: None,
434            rtx: None,
435            crypto: None,
436        }
437    }
438
439    pub fn g726_16_audio(id: TrackId) -> Self {
440        Self::g726_audio(id, Codec::G726_16)
441    }
442
443    pub fn g726_24_audio(id: TrackId) -> Self {
444        Self::g726_audio(id, Codec::G726_24)
445    }
446
447    pub fn g726_32_audio(id: TrackId) -> Self {
448        Self::g726_audio(id, Codec::G726_32)
449    }
450
451    pub fn g726_40_audio(id: TrackId) -> Self {
452        Self::g726_audio(id, Codec::G726_40)
453    }
454
455    /// AV1 video track (90 kHz clock, dynamic payload type).
456    pub fn av1_video(id: TrackId, width: u32, height: u32) -> Self {
457        Self::video_track(id, Codec::Av1, width, height)
458    }
459
460    /// Motion JPEG video track (90 kHz clock, dynamic payload type).
461    pub fn jpeg_video(id: TrackId, width: u32, height: u32) -> Self {
462        Self::video_track(id, Codec::Jpeg, width, height)
463    }
464
465    /// H.263 video track (`H263-1998`, 90 kHz clock).
466    pub fn h263_video(id: TrackId, width: u32, height: u32) -> Self {
467        Self::video_track(id, Codec::H263, width, height)
468    }
469
470    /// MPEG-4 Part 2 Visual track (`MP4V-ES`, 90 kHz clock).
471    pub fn mpeg4_video(id: TrackId, width: u32, height: u32) -> Self {
472        Self::video_track(id, Codec::Mpeg4, width, height)
473    }
474
475    fn video_track(id: TrackId, codec: Codec, width: u32, height: u32) -> Self {
476        Self {
477            id,
478            kind: MediaKind::Video,
479            codec,
480            clock_rate: 90_000,
481            channels: None,
482            payload_type: 96u8.saturating_add(id),
483            fmtp: None,
484            control: Arc::from(format!("track{id}")),
485            width: Some(width),
486            height: Some(height),
487            frame_rate: None,
488            direction: None,
489            ptime: None,
490            rtcp: None,
491            bandwidth_as: None,
492            rtx: None,
493            crypto: None,
494        }
495    }
496
497    /// G.711 μ-law audio track (8 kHz, 1 channel; no fmtp needed).
498    pub fn pcmu_audio(id: TrackId, sample_rate: u32, channels: u8) -> Self {
499        Self {
500            id,
501            kind: MediaKind::Audio,
502            codec: Codec::Pcmu,
503            clock_rate: sample_rate,
504            channels: Some(channels),
505            payload_type: 0,
506            fmtp: None,
507            control: Arc::from(format!("track{id}")),
508            width: None,
509            height: None,
510            frame_rate: None,
511            direction: None,
512            ptime: None,
513            rtcp: None,
514            bandwidth_as: None,
515            rtx: None,
516            crypto: None,
517        }
518    }
519}
520
521impl MediaDescription {
522    /// Build a description from tracks (ids must be contiguous from 0).
523    pub fn from_tracks(session_name: impl Into<Arc<str>>, tracks: Vec<TrackDescription>) -> Self {
524        Self {
525            session_name: session_name.into(),
526            tracks,
527            connection: None,
528        }
529    }
530}
531
532#[derive(Clone, Debug, Eq, PartialEq)]
533pub struct MediaDescription {
534    pub session_name: Arc<str>,
535    pub tracks: Vec<TrackDescription>,
536    /// SDP connection information (`c=` line). None if not present.
537    pub connection: Option<crate::connection::SdpConnection>,
538}
539impl MediaDescription {
540    /// Build a description with no SDP session connection. Protocol servers
541    /// add the negotiated `c=` information when encoding.
542    pub fn new(session_name: impl Into<Arc<str>>, tracks: Vec<TrackDescription>) -> Self {
543        Self {
544            session_name: session_name.into(),
545            tracks,
546            connection: None,
547        }
548    }
549
550    pub fn track(&self, id: TrackId) -> Option<&TrackDescription> {
551        self.tracks.iter().find(|t| t.id == id)
552    }
553}
554
555/// RTX (RFC 4588) parameters derived for one video track. RTX is advertised
556/// only when the server enables it; the payload type is allocated from the
557/// dynamic range so it never collides with a media PT.
558#[derive(Clone, Copy, Debug, Eq, PartialEq)]
559pub struct RtxConfig {
560    pub payload_type: u8,
561    pub ssrc: u32,
562    pub apt: u8,
563}
564
565/// Allocate one RTX PT/SSRC per video track without colliding with any media
566/// payload type in the description.
567pub fn rtx_configs(description: &MediaDescription) -> std::collections::HashMap<u8, RtxConfig> {
568    let used = description
569        .tracks
570        .iter()
571        .map(|track| track.payload_type)
572        .collect::<std::collections::HashSet<_>>();
573    let mut assigned = std::collections::HashSet::new();
574    let mut configs = std::collections::HashMap::new();
575    for track in &description.tracks {
576        if track.kind != MediaKind::Video || track.payload_type < 96 {
577            continue;
578        }
579        let mut candidates = (96u8..=127).rev();
580        let payload_type = candidates
581            .find(|pt| !used.contains(pt) && !assigned.contains(pt) && *pt != track.payload_type);
582        let Some(payload_type) = payload_type else {
583            continue;
584        };
585        assigned.insert(payload_type);
586        configs.insert(
587            track.id,
588            RtxConfig {
589                payload_type,
590                ssrc: 0x5254_0000
591                    ^ (u32::from(track.id).wrapping_mul(0x9e37_79b9))
592                    ^ u32::from(track.payload_type),
593                apt: track.payload_type,
594            },
595        );
596    }
597    configs
598}
599
600#[cfg(test)]
601mod rtx_tests {
602    use super::*;
603
604    #[test]
605    fn rtx_payload_types_are_distinct_and_do_not_collide() {
606        let description = MediaDescription::new(
607            "rtx",
608            vec![
609                TrackDescription::h264_video(0, &[], &[], 640, 360, 30),
610                TrackDescription::h264_video(1, &[], &[], 320, 180, 30),
611            ],
612        );
613        let configs = rtx_configs(&description);
614        assert_eq!(configs.len(), 2);
615        let first = configs.get(&0).unwrap();
616        let second = configs.get(&1).unwrap();
617        assert_ne!(first.payload_type, second.payload_type);
618        assert_eq!(first.apt, 96);
619        assert!(first.payload_type >= 96 && first.payload_type <= 127);
620        assert_ne!(first.ssrc, second.ssrc);
621    }
622
623    #[test]
624    fn srtp_tracks_get_rtx_config() {
625        let mut track = TrackDescription::h264_video(0, &[], &[], 640, 360, 30);
626        track.crypto = Some(crate::crypto::SdpCrypto {
627            tag: 1,
628            crypto_suite: "AES_128_CM_HMAC_SHA1_80".into(),
629            key_params: "inline:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=".into(),
630            session_params: None,
631        });
632        let description = MediaDescription::new("srtp", vec![track]);
633        assert_eq!(rtx_configs(&description).len(), 1);
634    }
635}