1pub 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
20pub 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 Mp3,
40 G726_16,
42 G726_24,
44 G726_32,
46 G726_40,
48 Av1,
50 Jpeg,
52 H263,
54 Mpeg4,
56}
57#[derive(Clone, Copy, Debug, Eq, PartialEq)]
58pub enum MediaKind {
59 Video,
60 Audio,
61}
62
63#[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#[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 pub nal_offsets: Option<std::sync::Arc<[u32]>>,
112}
113
114impl AccessUnit {
115 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 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 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 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 pub width: Option<u32>,
219 pub height: Option<u32>,
221 pub frame_rate: Option<(u32, u32)>,
223 pub direction: Option<SdpDirection>,
225 pub ptime: Option<u32>,
227 pub rtcp: Option<RtcpAddress>,
229 pub bandwidth_as: Option<u32>,
231 pub rtx: Option<RtxConfig>,
233 pub crypto: Option<crate::crypto::SdpCrypto>,
235}
236impl TrackDescription {
237 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 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 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 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 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 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 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 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 pub fn av1_video(id: TrackId, width: u32, height: u32) -> Self {
457 Self::video_track(id, Codec::Av1, width, height)
458 }
459
460 pub fn jpeg_video(id: TrackId, width: u32, height: u32) -> Self {
462 Self::video_track(id, Codec::Jpeg, width, height)
463 }
464
465 pub fn h263_video(id: TrackId, width: u32, height: u32) -> Self {
467 Self::video_track(id, Codec::H263, width, height)
468 }
469
470 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 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 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 pub connection: Option<crate::connection::SdpConnection>,
538}
539impl MediaDescription {
540 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
559pub struct RtxConfig {
560 pub payload_type: u8,
561 pub ssrc: u32,
562 pub apt: u8,
563}
564
565pub 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}