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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
use std::num::NonZeroU32;
use std::{borrow::Cow, fmt::Debug, num::NonZeroU16, pin::Pin};
use self::channel_mapping::*;
use self::timeline::Timeline;
use async_stream::try_stream;
use bytes::Bytes;
use failure::{bail, format_err, Error};
use futures::{SinkExt, StreamExt};
use log::{debug, trace, warn};
use pin_project::pin_project;
use sdp::session_description::SessionDescription;
use tokio::pin;
use tokio_util::codec::Framed;
use url::Url;
use crate::{codec::CodecItem, Context};
mod channel_mapping;
mod parse;
pub mod rtp;
mod timeline;
pub const KEEPALIVE_DURATION: std::time::Duration = std::time::Duration::from_secs(30);
#[derive(Copy, Clone, Debug)]
pub enum InitialTimestampPolicy {
Default,
Require,
Ignore,
Permissive,
}
impl Default for InitialTimestampPolicy {
fn default() -> Self {
InitialTimestampPolicy::Default
}
}
impl std::fmt::Display for InitialTimestampPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
InitialTimestampPolicy::Default => f.pad("default"),
InitialTimestampPolicy::Require => f.pad("require"),
InitialTimestampPolicy::Ignore => f.pad("ignore"),
InitialTimestampPolicy::Permissive => f.pad("permissive"),
}
}
}
impl std::str::FromStr for InitialTimestampPolicy {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"default" => InitialTimestampPolicy::Default,
"require" => InitialTimestampPolicy::Require,
"ignore" => InitialTimestampPolicy::Ignore,
"permissive" => InitialTimestampPolicy::Permissive,
_ => bail!("Initial timestamp mode {:?} not understood", s),
})
}
}
#[derive(Default)]
pub struct PlayPolicy {
initial_timestamp: InitialTimestampPolicy,
ignore_zero_seq: bool,
enforce_timestamps_with_max_jump_secs: Option<NonZeroU32>,
}
impl PlayPolicy {
pub fn initial_timestamp(self, initial_timestamp: InitialTimestampPolicy) -> Self {
Self {
initial_timestamp,
..self
}
}
pub fn ignore_zero_seq(self, ignore_zero_seq: bool) -> Self {
Self {
ignore_zero_seq,
..self
}
}
pub fn enforce_timestamps_with_max_jump_secs(self, secs: NonZeroU32) -> Self {
Self {
enforce_timestamps_with_max_jump_secs: Some(secs),
..self
}
}
}
#[derive(Debug)]
pub struct Presentation {
pub streams: Vec<Stream>,
base_url: Url,
pub control: Url,
pub accept_dynamic_rate: bool,
sdp: SessionDescription,
}
#[derive(Debug)]
pub struct Stream {
pub media: String,
pub encoding_name: String,
pub rtp_payload_type: u8,
pub clock_rate: u32,
pub channels: Option<NonZeroU16>,
depacketizer: Result<crate::codec::Depacketizer, Error>,
pub control: Option<Url>,
alt_control: Option<Url>,
state: StreamState,
}
impl Stream {
pub fn parameters(&self) -> Option<&crate::codec::Parameters> {
self.depacketizer.as_ref().ok().and_then(|d| d.parameters())
}
}
#[derive(Debug)]
enum StreamState {
Uninit,
Init(StreamStateInit),
Playing {
timeline: Timeline,
rtp_handler: rtp::StrictSequenceChecker,
},
}
#[derive(Copy, Clone, Debug, Default)]
struct StreamStateInit {
ssrc: Option<u32>,
initial_seq: Option<u16>,
initial_rtptime: Option<u32>,
}
#[derive(Clone)]
pub struct Credentials {
pub username: String,
pub password: String,
}
pub trait State {}
pub struct Described {
presentation: Presentation,
session_id: Option<String>,
channels: ChannelMappings,
}
impl State for Described {}
#[pin_project(project = PlayingProj)]
pub struct Playing {
presentation: Presentation,
session_id: String,
channels: ChannelMappings,
pending_keepalive_cseq: Option<u32>,
#[pin]
keepalive_timer: tokio::time::Sleep,
}
impl State for Playing {}
struct RtspConnection {
creds: Option<Credentials>,
requested_auth: Option<digest_auth::WwwAuthenticateHeader>,
stream: Framed<tokio::net::TcpStream, crate::Codec>,
user_agent: String,
next_cseq: u32,
}
#[pin_project]
pub struct Session<S: State> {
conn: RtspConnection,
#[pin]
state: S,
}
impl RtspConnection {
async fn connect(url: &Url, creds: Option<Credentials>) -> Result<Self, Error> {
if url.scheme() != "rtsp" {
bail!("Only rtsp urls supported (no rtsps yet)");
}
if url.username() != "" || url.password().is_some() {
bail!("URL must not contain credentials");
}
let host = url
.host_str()
.ok_or_else(|| format_err!("Must specify host in rtsp url {}", &url))?;
let port = url.port().unwrap_or(554);
let stream = tokio::net::TcpStream::connect((host, port)).await?;
let conn_established_wall = time::get_time();
let conn_established = std::time::Instant::now();
let conn_local_addr = stream.local_addr()?;
let conn_peer_addr = stream.peer_addr()?;
let stream = Framed::new(
stream,
crate::Codec {
ctx: crate::Context {
conn_established_wall,
conn_established,
conn_local_addr,
conn_peer_addr,
msg_pos: 0,
msg_received_wall: conn_established_wall,
msg_received: conn_established,
},
},
);
Ok(Self {
creds,
requested_auth: None,
stream,
user_agent: "moonfire-rtsp test".to_string(),
next_cseq: 1,
})
}
async fn send(
&mut self,
req: &mut rtsp_types::Request<Bytes>,
) -> Result<rtsp_types::Response<Bytes>, Error> {
loop {
let cseq = self.send_nowait(req).await?;
let msg = self
.stream
.next()
.await
.ok_or_else(|| format_err!("unexpected EOF while waiting for reply"))??;
let resp = match msg.msg {
rtsp_types::Message::Response(r) => r,
o => bail!("Unexpected RTSP message {:?}", &o),
};
if parse::get_cseq(&resp) != Some(cseq) {
bail!(
"didn't get expected CSeq {:?} on {:?} at {:#?}",
&cseq,
&resp,
&msg.ctx
);
}
if resp.status() == rtsp_types::StatusCode::Unauthorized {
if self.requested_auth.is_some() {
bail!(
"Received Unauthorized after trying digest auth at {:#?}",
&msg.ctx
);
}
let www_authenticate = match resp.header(&rtsp_types::headers::WWW_AUTHENTICATE) {
None => bail!(
"Unauthorized without WWW-Authenticate header at {:#?}",
&msg.ctx
),
Some(h) => h,
};
let www_authenticate = www_authenticate.as_str();
if !www_authenticate.starts_with("Digest ") {
bail!(
"Non-digest authentication requested at {:#?}: {}",
&msg.ctx,
www_authenticate
);
}
let www_authenticate = digest_auth::WwwAuthenticateHeader::parse(www_authenticate)?;
self.requested_auth = Some(www_authenticate);
continue;
} else if !resp.status().is_success() {
bail!(
"RTSP {:?} request returned {} at {:#?}",
req.method(),
resp.status(),
&msg.ctx
);
}
return Ok(resp);
}
}
async fn send_nowait(&mut self, req: &mut rtsp_types::Request<Bytes>) -> Result<u32, Error> {
let cseq = self.next_cseq;
self.next_cseq += 1;
match (self.requested_auth.as_mut(), self.creds.as_ref()) {
(None, _) => {}
(Some(auth), Some(creds)) => {
let uri = req.request_uri().map(|u| u.as_str()).unwrap_or("*");
let method = digest_auth::HttpMethod(Cow::Borrowed(req.method().into()));
let ctx = digest_auth::AuthContext::new_with_method(
&creds.username,
&creds.password,
uri,
Option::<&'static [u8]>::None,
method,
);
let authorization = auth.respond(&ctx)?.to_string();
req.insert_header(rtsp_types::headers::AUTHORIZATION, authorization);
}
(Some(_), None) => bail!("Authentication required; no credentials supplied"),
}
req.insert_header(rtsp_types::headers::CSEQ, cseq.to_string());
req.insert_header(rtsp_types::headers::USER_AGENT, self.user_agent.clone());
self.stream
.send(rtsp_types::Message::Request(req.clone()))
.await?;
Ok(cseq)
}
}
impl Session<Described> {
pub async fn describe(url: Url, creds: Option<Credentials>) -> Result<Self, Error> {
let mut conn = RtspConnection::connect(&url, creds).await?;
let mut req =
rtsp_types::Request::builder(rtsp_types::Method::Describe, rtsp_types::Version::V1_0)
.header(rtsp_types::headers::ACCEPT, "application/sdp")
.request_uri(url.clone())
.build(Bytes::new());
let response = conn.send(&mut req).await?;
let presentation = parse::parse_describe(url, response)?;
Ok(Session {
conn,
state: Described {
presentation,
session_id: None,
channels: ChannelMappings::default(),
},
})
}
pub fn streams(&self) -> &[Stream] {
&self.state.presentation.streams
}
pub async fn setup(&mut self, stream_i: usize) -> Result<(), Error> {
let stream = &mut self.state.presentation.streams[stream_i];
if !matches!(stream.state, StreamState::Uninit) {
bail!("stream already set up");
}
let proposed_channel_id = self.state.channels.next_unassigned()?;
let url = stream
.control
.as_ref()
.unwrap_or(&self.state.presentation.control)
.clone();
let mut req =
rtsp_types::Request::builder(rtsp_types::Method::Setup, rtsp_types::Version::V1_0)
.request_uri(url)
.header(
rtsp_types::headers::TRANSPORT,
format!(
"RTP/AVP/TCP;unicast;interleaved={}-{}",
proposed_channel_id,
proposed_channel_id + 1
),
)
.header(crate::X_DYNAMIC_RATE.clone(), "1".to_owned());
if let Some(ref s) = self.state.session_id {
req = req.header(rtsp_types::headers::SESSION, s.clone());
}
let response = self.conn.send(&mut req.build(Bytes::new())).await?;
debug!("SETUP response: {:#?}", &response);
let response = parse::parse_setup(&response)?;
match self.state.session_id.as_ref() {
Some(old) if old != response.session_id => {
bail!(
"SETUP response changed session id from {:?} to {:?}",
old,
response.session_id
);
}
Some(_) => {}
None => self.state.session_id = Some(response.session_id.to_owned()),
};
self.state.channels.assign(response.channel_id, stream_i)?;
stream.state = StreamState::Init(StreamStateInit {
ssrc: response.ssrc,
initial_seq: None,
initial_rtptime: None,
});
Ok(())
}
pub async fn play(mut self, policy: PlayPolicy) -> Result<Session<Playing>, Error> {
let session_id = self
.state
.session_id
.take()
.ok_or_else(|| format_err!("must SETUP before PLAY"))?;
trace!("PLAY with channel mappings: {:#?}", &self.state.channels);
let response = self
.conn
.send(
&mut rtsp_types::Request::builder(
rtsp_types::Method::Play,
rtsp_types::Version::V1_0,
)
.request_uri(self.state.presentation.control.clone())
.header(rtsp_types::headers::SESSION, session_id.clone())
.header(rtsp_types::headers::RANGE, "npt=0.000-".to_owned())
.build(Bytes::new()),
)
.await?;
parse::parse_play(response, &mut self.state.presentation)?;
let setup_streams = self
.state
.presentation
.streams
.iter()
.filter(|s| matches!(s.state, StreamState::Init(_)))
.count();
let all_have_time = self
.state
.presentation
.streams
.iter()
.all(|s| match s.state {
StreamState::Init(StreamStateInit {
initial_rtptime, ..
}) => initial_rtptime.is_some(),
_ => true,
});
for (i, s) in self.state.presentation.streams.iter_mut().enumerate() {
match s.state {
StreamState::Init(StreamStateInit {
initial_rtptime,
initial_seq,
ssrc,
..
}) => {
let initial_rtptime =
match policy.initial_timestamp {
InitialTimestampPolicy::Require | InitialTimestampPolicy::Default
if setup_streams > 1 =>
{
if initial_rtptime.is_none() {
bail!(
"Expected rtptime on PLAY with mode {:?}, missing on stream \
{} ({:?}). Consider setting initial timestamp mode \
use-if-all-present.",
policy.initial_timestamp, i, &s.control);
}
initial_rtptime
}
InitialTimestampPolicy::Permissive
if setup_streams > 1 && all_have_time =>
{
initial_rtptime
}
_ => None,
};
let initial_seq = match initial_seq {
Some(0) if policy.ignore_zero_seq => {
log::info!("Ignoring seq=0 on stream {}", i);
None
}
o => o,
};
s.state = StreamState::Playing {
timeline: Timeline::new(
initial_rtptime,
s.clock_rate,
policy.enforce_timestamps_with_max_jump_secs,
)?,
rtp_handler: rtp::StrictSequenceChecker::new(ssrc, initial_seq),
};
}
StreamState::Uninit => {}
StreamState::Playing { .. } => unreachable!(),
};
}
Ok(Session {
conn: self.conn,
state: Playing {
presentation: self.state.presentation,
session_id,
channels: self.state.channels,
keepalive_timer: tokio::time::sleep(KEEPALIVE_DURATION),
pending_keepalive_cseq: None,
},
})
}
}
pub enum PacketItem {
RtpPacket(rtp::Packet),
SenderReport(rtp::SenderReport),
}
impl Session<Playing> {
pub fn pkts(self) -> impl futures::Stream<Item = Result<PacketItem, Error>> {
try_stream! {
let self_ = self;
tokio::pin!(self_);
while let Some(pkt) = self_.as_mut().next().await {
let pkt = pkt?;
yield pkt;
}
}
}
pub fn demuxed(
mut self,
) -> Result<impl futures::Stream<Item = Result<CodecItem, Error>>, Error> {
for s in &mut self.state.presentation.streams {
if matches!(s.state, StreamState::Playing { .. }) {
if let Err(ref mut e) = s.depacketizer {
return Err(std::mem::replace(e, format_err!("(placeholder)")));
}
}
}
Ok(try_stream! {
let self_ = self;
tokio::pin!(self_);
while let Some(pkt) = self_.as_mut().next().await {
let pkt = pkt?;
match pkt {
PacketItem::RtpPacket(p) => {
let self_ = self_.as_mut().project();
let state = self_.state.project();
let depacketizer = match &mut state.presentation.streams[p.stream_id].depacketizer {
Ok(d) => d,
Err(_) => unreachable!("depacketizer was Ok"),
};
depacketizer.push(p)?;
while let Some(demuxed) = depacketizer.pull()? {
yield demuxed;
}
},
PacketItem::SenderReport(p) => yield CodecItem::SenderReport(p),
};
}
})
}
async fn next(self: Pin<&mut Self>) -> Option<Result<PacketItem, Error>> {
let this = self.project();
let mut state = this.state.project();
loop {
tokio::select! {
biased;
msg = this.conn.stream.next() => {
let msg = match msg {
Some(Ok(m)) => m,
Some(Err(e)) => return Some(Err(e)),
None => return None,
};
match msg.msg {
rtsp_types::Message::Data(data) => {
match Session::handle_data(&mut state, msg.ctx, data) {
Err(e) => return Some(Err(e)),
Ok(Some(pkt)) => return Some(Ok(pkt)),
Ok(None) => continue,
};
},
rtsp_types::Message::Response(response) => {
if let Err(e) = Session::handle_response(&mut state, response) {
return Some(Err(e));
}
},
rtsp_types::Message::Request(request) => {
warn!("Received RTSP request in Playing state. Responding unimplemented.\n{:#?}",
request);
},
}
},
() = &mut state.keepalive_timer => {
if let Err(e) = Session::handle_keepalive_timer(this.conn, &mut state).await {
return Some(Err(e));
}
},
}
}
}
async fn handle_keepalive_timer(
conn: &mut RtspConnection,
state: &mut PlayingProj<'_>,
) -> Result<(), Error> {
if let Some(cseq) = state.pending_keepalive_cseq {
bail!(
"Server failed to respond to keepalive {} within {:?}",
cseq,
KEEPALIVE_DURATION
);
}
*state.pending_keepalive_cseq = Some(
conn.send_nowait(
&mut rtsp_types::Request::builder(
rtsp_types::Method::GetParameter,
rtsp_types::Version::V1_0,
)
.request_uri(state.presentation.base_url.clone())
.header(rtsp_types::headers::SESSION, state.session_id.clone())
.build(Bytes::new()),
)
.await?,
);
state
.keepalive_timer
.as_mut()
.reset(tokio::time::Instant::now() + KEEPALIVE_DURATION);
Ok(())
}
fn handle_response(
state: &mut PlayingProj<'_>,
response: rtsp_types::Response<Bytes>,
) -> Result<(), Error> {
if matches!(*state.pending_keepalive_cseq,
Some(cseq) if parse::get_cseq(&response) == Some(cseq))
{
*state.pending_keepalive_cseq = None;
return Ok(());
}
bail!("Unexpected RTSP response {:#?}", response);
}
fn handle_data(
state: &mut PlayingProj<'_>,
ctx: Context,
data: rtsp_types::Data<Bytes>,
) -> Result<Option<PacketItem>, Error> {
let c = data.channel_id();
let m = match state.channels.lookup(c) {
Some(m) => m,
None => bail!("Data message on unexpected channel {} at {:#?}", c, &ctx),
};
let stream = &mut state.presentation.streams[m.stream_i];
let (mut timeline, rtp_handler) = match &mut stream.state {
StreamState::Playing {
timeline,
rtp_handler,
} => (timeline, rtp_handler),
_ => unreachable!("Session<Playing>'s {}->{:?} not in Playing state", c, m),
};
match m.channel_type {
ChannelType::Rtp => Ok(Some(rtp_handler.rtp(
ctx,
&mut timeline,
m.stream_i,
data.into_body(),
)?)),
ChannelType::Rtcp => {
Ok(rtp_handler.rtcp(ctx, &mut timeline, m.stream_i, data.into_body())?)
}
}
}
pub fn streams(&self) -> &[Stream] {
&self.state.presentation.streams
}
}