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};
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,
Mp3,
G726_16,
G726_24,
G726_32,
G726_40,
Av1,
Jpeg,
H263,
Mpeg4,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MediaKind {
Video,
Audio,
}
#[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,
}
}
}
#[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,
pub nal_offsets: Option<std::sync::Arc<[u32]>>,
}
impl AccessUnit {
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,
}
}
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,
}
}
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),
}
}
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>,
pub width: Option<u32>,
pub height: Option<u32>,
pub frame_rate: Option<(u32, u32)>,
pub direction: Option<SdpDirection>,
pub ptime: Option<u32>,
pub rtcp: Option<RtcpAddress>,
pub bandwidth_as: Option<u32>,
pub rtx: Option<RtxConfig>,
pub crypto: Option<crate::crypto::SdpCrypto>,
}
impl TrackDescription {
pub fn h264_video(
id: TrackId,
sps: &[u8],
pps: &[u8],
width: u32,
height: u32,
frame_rate: u32,
) -> Self {
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,
}
}
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,
}
}
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,
}
}
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,
}
}
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,
}
}
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,
}
}
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)
}
pub fn av1_video(id: TrackId, width: u32, height: u32) -> Self {
Self::video_track(id, Codec::Av1, width, height)
}
pub fn jpeg_video(id: TrackId, width: u32, height: u32) -> Self {
Self::video_track(id, Codec::Jpeg, width, height)
}
pub fn h263_video(id: TrackId, width: u32, height: u32) -> Self {
Self::video_track(id, Codec::H263, width, height)
}
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,
}
}
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 {
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>,
pub connection: Option<crate::connection::SdpConnection>,
}
impl MediaDescription {
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)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RtxConfig {
pub payload_type: u8,
pub ssrc: u32,
pub apt: u8,
}
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);
}
}