rtflow-media 0.7.0

Encoded media types, bitstream helpers and container-agnostic demuxing for rtflow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! Media types and hardware-encoder integration helpers.
//!
//! [`AccessUnit`] carries encoded frames (Annex-B for video, raw AAC/PCM
//! for audio) into the data plane; the `*_video`/`*_audio` constructors
//! below remove the SDP/clock boilerplate when wiring a hardware encoder
//! (HiSilicon HiMPP VENC, V4L2, ...) into the framework.

pub mod bitstream;
pub mod clock;
pub mod connection;
pub mod crypto;
pub mod demux;
pub mod flv;
pub mod vod;

pub use connection::SdpConnection;
pub use crypto::SdpCrypto;
pub use demux::{DemuxedSample, Demuxer};

/// MPEG-TS packet size in bytes.
pub const TS_PACKET_SIZE: usize = 188;

use bytes::Bytes;
use std::{sync::Arc, time::Duration};
pub type TrackId = u8;
pub type RtpTimestamp = u32;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum Codec {
    H264,
    H265,
    Aac,
    Pcma,
    Pcmu,
    Opus,
    Vp8,
    Vp9,
    /// MPEG-1/2 Audio (MP3), RFC 2250/5219.
    Mp3,
    /// G.726 at 16 kbit/s (RFC 3551).
    G726_16,
    /// G.726 at 24 kbit/s.
    G726_24,
    /// G.726 at 32 kbit/s.
    G726_32,
    /// G.726 at 40 kbit/s.
    G726_40,
    /// AV1 video (draft-ietf-payload-av1).
    Av1,
    /// Motion JPEG (RFC 2435).
    Jpeg,
    /// H.263 (RFC 4629, `H263-1998`).
    H263,
    /// MPEG-4 Part 2 Visual (RFC 3016, `MP4V-ES`).
    Mpeg4,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MediaKind {
    Video,
    Audio,
}

/// SDP media direction (`a=sendonly`/`a=recvonly`/`a=sendrecv`/`a=inactive`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SdpDirection {
    SendOnly,
    RecvOnly,
    SendRecv,
    Inactive,
}

impl SdpDirection {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::SendOnly => "sendonly",
            Self::RecvOnly => "recvonly",
            Self::SendRecv => "sendrecv",
            Self::Inactive => "inactive",
        }
    }

    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "sendonly" => Some(Self::SendOnly),
            "recvonly" => Some(Self::RecvOnly),
            "sendrecv" => Some(Self::SendRecv),
            "inactive" => Some(Self::Inactive),
            _ => None,
        }
    }
}

/// SDP `a=rtcp:<port> [address]` override.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RtcpAddress {
    pub port: u16,
    pub address: Option<std::net::IpAddr>,
}
#[derive(Clone, Debug)]
pub struct AccessUnit {
    pub track_id: TrackId,
    pub codec: Codec,
    pub pts: Duration,
    pub dts: Option<Duration>,
    pub rtp_timestamp: RtpTimestamp,
    pub is_keyframe: bool,
    pub data: Bytes,
    /// 帧内 NAL 边界(每个 NAL 的起始偏移,末尾带 len 哨兵)。
    /// 硬件编码器(HiSilicon VENC)直接给出时填 `Some`,下游 RTP 打包按偏移切分,
    /// 不必扫描 Annex-B 起始码。一帧内所有 NAL 共享同一 pts/rtp_timestamp。
    pub nal_offsets: Option<std::sync::Arc<[u32]>>,
}

impl AccessUnit {
    /// Determine the media kind from the codec.
    pub fn kind(&self) -> MediaKind {
        match self.codec {
            Codec::H264
            | Codec::H265
            | Codec::Vp8
            | Codec::Vp9
            | Codec::Av1
            | Codec::Jpeg
            | Codec::H263
            | Codec::Mpeg4 => MediaKind::Video,
            Codec::Aac
            | Codec::Pcma
            | Codec::Pcmu
            | Codec::Opus
            | Codec::Mp3
            | Codec::G726_16
            | Codec::G726_24
            | Codec::G726_32
            | Codec::G726_40 => MediaKind::Audio,
        }
    }

    /// Construct a video access unit. `data` is an Annex-B H.264/H.265
    /// access unit (start codes included, as produced by HiMPP VENC).
    pub fn video(
        track_id: TrackId,
        codec: Codec,
        pts: Duration,
        rtp_timestamp: RtpTimestamp,
        is_keyframe: bool,
        data: Bytes,
    ) -> Self {
        Self {
            track_id,
            codec,
            pts,
            dts: None,
            rtp_timestamp,
            is_keyframe,
            data,
            nal_offsets: None,
        }
    }

    /// 构造一帧“带 NAL 边界”的视频访问单元(硬件编码器多 packet 输出)。
    ///
    /// `data` 是整帧连续缓冲(可来自 DMA/MMZ),`nal_offsets` 是帧内每个 NAL 的
    /// 起始偏移加末尾哨兵。下游 RTP 打包按偏移切片,**不再扫描 Annex-B 起始码**。
    /// 一帧内所有 NAL(SPS/PPS/SEI/slice)共享同一个 `pts` / `rtp_timestamp`。
    pub fn video_with_nal_offsets(
        track_id: TrackId,
        codec: Codec,
        pts: Duration,
        rtp_timestamp: RtpTimestamp,
        is_keyframe: bool,
        data: Bytes,
        nal_offsets: std::sync::Arc<[u32]>,
    ) -> Self {
        Self {
            track_id,
            codec,
            pts,
            dts: None,
            rtp_timestamp,
            is_keyframe,
            data,
            nal_offsets: Some(nal_offsets),
        }
    }

    /// Construct an audio access unit (raw AAC frame or 8 kHz G.711
    /// sample block; the caller supplies the RTP timestamp).
    pub fn audio(
        track_id: TrackId,
        codec: Codec,
        pts: Duration,
        rtp_timestamp: RtpTimestamp,
        data: Bytes,
    ) -> Self {
        Self {
            track_id,
            codec,
            pts,
            dts: None,
            rtp_timestamp,
            is_keyframe: true,
            data,
            nal_offsets: None,
        }
    }
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TrackDescription {
    pub id: TrackId,
    pub kind: MediaKind,
    pub codec: Codec,
    pub clock_rate: u32,
    pub channels: Option<u8>,
    pub payload_type: u8,
    pub fmtp: Option<Arc<str>>,
    pub control: Arc<str>,
    /// Video width in pixels (if known).
    pub width: Option<u32>,
    /// Video height in pixels (if known).
    pub height: Option<u32>,
    /// Video frame rate as (numerator, denominator) (if known).
    pub frame_rate: Option<(u32, u32)>,
    /// SDP media direction; `None` means unspecified.
    pub direction: Option<SdpDirection>,
    /// SDP `a=ptime` packetization interval in milliseconds.
    pub ptime: Option<u32>,
    /// SDP `a=rtcp` RTCP port/address override.
    pub rtcp: Option<RtcpAddress>,
    /// SDP `b=AS` bandwidth in kbit/s.
    pub bandwidth_as: Option<u32>,
    /// RFC 4588 RTX mapping when the SDP advertised a retransmission stream.
    pub rtx: Option<RtxConfig>,
    /// SRTP crypto parameters from SDP `a=crypto:` attribute.
    pub crypto: Option<crate::crypto::SdpCrypto>,
}
impl TrackDescription {
    /// H.264 video track from encoder parameter sets.
    ///
    /// `sps`/`pps` are the NAL bodies *without* start codes (extract them
    /// with [`bitstream::h264_parameter_sets`] from an Annex-B IDR).
    /// `sps`/`pps` may be empty for raw single-NAL setups, in which case
    /// the fmtp is a plain `packetization-mode=1` (the mount auto-injects
    /// `sprop-parameter-sets` once a keyframe with parameter sets arrives).
    pub fn h264_video(
        id: TrackId,
        sps: &[u8],
        pps: &[u8],
        width: u32,
        height: u32,
        frame_rate: u32,
    ) -> Self {
        // Empty parameter sets → no fmtp yet: the mount auto-injects
        // sprop-parameter-sets from the first keyframe that carries them
        // (hardware encoders with separated SPS/PPS), which DESCRIBE then
        // merges in. A stream without any parameter sets still works when
        // every IDR carries them inline (single-NAL packaging is valid
        // under the default packetization-mode=0).
        let fmtp = if sps.is_empty() || pps.is_empty() {
            None
        } else {
            Some(Arc::from(bitstream::h264_fmtp(sps, pps)))
        };
        Self {
            id,
            kind: MediaKind::Video,
            codec: Codec::H264,
            clock_rate: crate::clock::VIDEO_CLOCK_RATE,
            channels: None,
            payload_type: 96,
            fmtp,
            control: Arc::from(format!("track{id}")),
            width: Some(width),
            height: Some(height),
            frame_rate: Some((frame_rate, 1)),
            direction: None,
            ptime: None,
            rtcp: None,
            bandwidth_as: None,
            rtx: None,
            crypto: None,
        }
    }

    /// H.265 video track from encoder parameter sets (VPS/SPS/PPS NAL
    /// bodies without start codes).
    pub fn h265_video(
        id: TrackId,
        vps: &[u8],
        sps: &[u8],
        pps: &[u8],
        width: u32,
        height: u32,
        frame_rate: u32,
    ) -> Self {
        let fmtp = if vps.is_empty() || sps.is_empty() || pps.is_empty() {
            None
        } else {
            Some(Arc::from(bitstream::h265_fmtp(vps, sps, pps)))
        };
        Self {
            id,
            kind: MediaKind::Video,
            codec: Codec::H265,
            clock_rate: crate::clock::VIDEO_CLOCK_RATE,
            channels: None,
            payload_type: 96,
            fmtp,
            control: Arc::from(format!("track{id}")),
            width: Some(width),
            height: Some(height),
            frame_rate: Some((frame_rate, 1)),
            direction: None,
            ptime: None,
            rtcp: None,
            bandwidth_as: None,
            rtx: None,
            crypto: None,
        }
    }

    /// AAC-LC audio track (MPEG4-GENERIC, RFC 3640 fmtp with an
    /// auto-generated `config=` AudioSpecificConfig).
    pub fn aac_audio(id: TrackId, sample_rate: u32, channels: u8) -> Self {
        let fmtp = bitstream::aac_audio_specific_config(sample_rate, channels)
            .map(|config| Arc::from(bitstream::aac_fmtp(&config)));
        Self {
            id,
            kind: MediaKind::Audio,
            codec: Codec::Aac,
            clock_rate: sample_rate,
            channels: Some(channels),
            payload_type: 97,
            fmtp,
            control: Arc::from(format!("track{id}")),
            width: None,
            height: None,
            frame_rate: None,
            direction: None,
            ptime: None,
            rtcp: None,
            bandwidth_as: None,
            rtx: None,
            crypto: None,
        }
    }

    /// Opus audio track (RFC 7587: 48 kHz clock, stereo by default, PT 96).
    pub fn opus_audio(id: TrackId, channels: u8) -> Self {
        Self {
            id,
            kind: MediaKind::Audio,
            codec: Codec::Opus,
            clock_rate: 48_000,
            channels: Some(channels.max(1)),
            payload_type: 96,
            fmtp: None,
            control: Arc::from(format!("track{id}")),
            width: None,
            height: None,
            frame_rate: None,
            direction: None,
            ptime: Some(20),
            rtcp: None,
            bandwidth_as: None,
            rtx: None,
            crypto: None,
        }
    }

    /// G.711 A-law audio track (8 kHz, 1 channel; no fmtp needed).
    pub fn pcma_audio(id: TrackId, sample_rate: u32, channels: u8) -> Self {
        Self {
            id,
            kind: MediaKind::Audio,
            codec: Codec::Pcma,
            clock_rate: sample_rate,
            channels: Some(channels),
            payload_type: 8,
            fmtp: None,
            control: Arc::from(format!("track{id}")),
            width: None,
            height: None,
            frame_rate: None,
            direction: None,
            ptime: None,
            rtcp: None,
            bandwidth_as: None,
            rtx: None,
            crypto: None,
        }
    }

    /// MPEG-1/2 Audio (MP3) track: 90 kHz clock, static payload type 14.
    pub fn mp3_audio(id: TrackId) -> Self {
        Self {
            id,
            kind: MediaKind::Audio,
            codec: Codec::Mp3,
            clock_rate: 90_000,
            channels: Some(2),
            payload_type: 14,
            fmtp: None,
            control: Arc::from(format!("track{id}")),
            width: None,
            height: None,
            frame_rate: None,
            direction: None,
            ptime: None,
            rtcp: None,
            bandwidth_as: None,
            rtx: None,
            crypto: None,
        }
    }

    /// G.726 audio track (8 kHz, 1 channel); `codec` selects the bit rate.
    fn g726_audio(id: TrackId, codec: Codec) -> Self {
        Self {
            id,
            kind: MediaKind::Audio,
            codec,
            clock_rate: 8_000,
            channels: Some(1),
            payload_type: 96u8.saturating_add(id),
            fmtp: None,
            control: Arc::from(format!("track{id}")),
            width: None,
            height: None,
            frame_rate: None,
            direction: None,
            ptime: None,
            rtcp: None,
            bandwidth_as: None,
            rtx: None,
            crypto: None,
        }
    }

    pub fn g726_16_audio(id: TrackId) -> Self {
        Self::g726_audio(id, Codec::G726_16)
    }

    pub fn g726_24_audio(id: TrackId) -> Self {
        Self::g726_audio(id, Codec::G726_24)
    }

    pub fn g726_32_audio(id: TrackId) -> Self {
        Self::g726_audio(id, Codec::G726_32)
    }

    pub fn g726_40_audio(id: TrackId) -> Self {
        Self::g726_audio(id, Codec::G726_40)
    }

    /// AV1 video track (90 kHz clock, dynamic payload type).
    pub fn av1_video(id: TrackId, width: u32, height: u32) -> Self {
        Self::video_track(id, Codec::Av1, width, height)
    }

    /// Motion JPEG video track (90 kHz clock, dynamic payload type).
    pub fn jpeg_video(id: TrackId, width: u32, height: u32) -> Self {
        Self::video_track(id, Codec::Jpeg, width, height)
    }

    /// H.263 video track (`H263-1998`, 90 kHz clock).
    pub fn h263_video(id: TrackId, width: u32, height: u32) -> Self {
        Self::video_track(id, Codec::H263, width, height)
    }

    /// MPEG-4 Part 2 Visual track (`MP4V-ES`, 90 kHz clock).
    pub fn mpeg4_video(id: TrackId, width: u32, height: u32) -> Self {
        Self::video_track(id, Codec::Mpeg4, width, height)
    }

    fn video_track(id: TrackId, codec: Codec, width: u32, height: u32) -> Self {
        Self {
            id,
            kind: MediaKind::Video,
            codec,
            clock_rate: 90_000,
            channels: None,
            payload_type: 96u8.saturating_add(id),
            fmtp: None,
            control: Arc::from(format!("track{id}")),
            width: Some(width),
            height: Some(height),
            frame_rate: None,
            direction: None,
            ptime: None,
            rtcp: None,
            bandwidth_as: None,
            rtx: None,
            crypto: None,
        }
    }

    /// G.711 μ-law audio track (8 kHz, 1 channel; no fmtp needed).
    pub fn pcmu_audio(id: TrackId, sample_rate: u32, channels: u8) -> Self {
        Self {
            id,
            kind: MediaKind::Audio,
            codec: Codec::Pcmu,
            clock_rate: sample_rate,
            channels: Some(channels),
            payload_type: 0,
            fmtp: None,
            control: Arc::from(format!("track{id}")),
            width: None,
            height: None,
            frame_rate: None,
            direction: None,
            ptime: None,
            rtcp: None,
            bandwidth_as: None,
            rtx: None,
            crypto: None,
        }
    }
}

impl MediaDescription {
    /// Build a description from tracks (ids must be contiguous from 0).
    pub fn from_tracks(session_name: impl Into<Arc<str>>, tracks: Vec<TrackDescription>) -> Self {
        Self {
            session_name: session_name.into(),
            tracks,
            connection: None,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MediaDescription {
    pub session_name: Arc<str>,
    pub tracks: Vec<TrackDescription>,
    /// SDP connection information (`c=` line). None if not present.
    pub connection: Option<crate::connection::SdpConnection>,
}
impl MediaDescription {
    /// Build a description with no SDP session connection. Protocol servers
    /// add the negotiated `c=` information when encoding.
    pub fn new(session_name: impl Into<Arc<str>>, tracks: Vec<TrackDescription>) -> Self {
        Self {
            session_name: session_name.into(),
            tracks,
            connection: None,
        }
    }

    pub fn track(&self, id: TrackId) -> Option<&TrackDescription> {
        self.tracks.iter().find(|t| t.id == id)
    }
}

/// RTX (RFC 4588) parameters derived for one video track. RTX is advertised
/// only when the server enables it; the payload type is allocated from the
/// dynamic range so it never collides with a media PT.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RtxConfig {
    pub payload_type: u8,
    pub ssrc: u32,
    pub apt: u8,
}

/// Allocate one RTX PT/SSRC per video track without colliding with any media
/// payload type in the description.
pub fn rtx_configs(description: &MediaDescription) -> std::collections::HashMap<u8, RtxConfig> {
    let used = description
        .tracks
        .iter()
        .map(|track| track.payload_type)
        .collect::<std::collections::HashSet<_>>();
    let mut assigned = std::collections::HashSet::new();
    let mut configs = std::collections::HashMap::new();
    for track in &description.tracks {
        if track.kind != MediaKind::Video || track.payload_type < 96 {
            continue;
        }
        let mut candidates = (96u8..=127).rev();
        let payload_type = candidates
            .find(|pt| !used.contains(pt) && !assigned.contains(pt) && *pt != track.payload_type);
        let Some(payload_type) = payload_type else {
            continue;
        };
        assigned.insert(payload_type);
        configs.insert(
            track.id,
            RtxConfig {
                payload_type,
                ssrc: 0x5254_0000
                    ^ (u32::from(track.id).wrapping_mul(0x9e37_79b9))
                    ^ u32::from(track.payload_type),
                apt: track.payload_type,
            },
        );
    }
    configs
}

#[cfg(test)]
mod rtx_tests {
    use super::*;

    #[test]
    fn rtx_payload_types_are_distinct_and_do_not_collide() {
        let description = MediaDescription::new(
            "rtx",
            vec![
                TrackDescription::h264_video(0, &[], &[], 640, 360, 30),
                TrackDescription::h264_video(1, &[], &[], 320, 180, 30),
            ],
        );
        let configs = rtx_configs(&description);
        assert_eq!(configs.len(), 2);
        let first = configs.get(&0).unwrap();
        let second = configs.get(&1).unwrap();
        assert_ne!(first.payload_type, second.payload_type);
        assert_eq!(first.apt, 96);
        assert!(first.payload_type >= 96 && first.payload_type <= 127);
        assert_ne!(first.ssrc, second.ssrc);
    }

    #[test]
    fn srtp_tracks_get_rtx_config() {
        let mut track = TrackDescription::h264_video(0, &[], &[], 640, 360, 30);
        track.crypto = Some(crate::crypto::SdpCrypto {
            tag: 1,
            crypto_suite: "AES_128_CM_HMAC_SHA1_80".into(),
            key_params: "inline:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=".into(),
            session_params: None,
        });
        let description = MediaDescription::new("srtp", vec![track]);
        assert_eq!(rtx_configs(&description).len(), 1);
    }
}