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
use bytes::{Buf, BufMut, Bytes, BytesMut};
use failure::{bail, format_err, Error};
use once_cell::sync::Lazy;
use rtsp_types::Message;
use std::convert::TryFrom;
use std::fmt::{Debug, Display};
use std::num::NonZeroU32;
pub mod client;
pub mod codec;
pub static X_ACCEPT_DYNAMIC_RATE: Lazy<rtsp_types::HeaderName> = Lazy::new(|| {
rtsp_types::HeaderName::from_static_str("x-Accept-Dynamic-Rate").expect("is ascii")
});
pub static X_DYNAMIC_RATE: Lazy<rtsp_types::HeaderName> =
Lazy::new(|| rtsp_types::HeaderName::from_static_str("x-Dynamic-Rate").expect("is ascii"));
#[derive(Debug)]
pub struct ReceivedMessage {
pub ctx: Context,
pub msg: Message<Bytes>,
}
#[derive(Copy, Clone)]
pub struct Timestamp {
timestamp: i64,
clock_rate: NonZeroU32,
start: u32,
}
impl Timestamp {
pub fn new(timestamp: i64, clock_rate: NonZeroU32, start: u32) -> Result<Self, Error> {
match timestamp.checked_sub(i64::from(start)) {
None => bail!("timestamp - start must not underflow"),
Some(_) => Ok(Timestamp {
timestamp,
clock_rate,
start,
}),
}
}
#[inline]
pub fn timestamp(&self) -> i64 {
self.timestamp
}
#[inline]
pub fn start(&self) -> u32 {
self.start
}
#[inline]
pub fn clock_rate(&self) -> NonZeroU32 {
self.clock_rate
}
#[inline]
pub fn elapsed(&self) -> i64 {
self.timestamp - i64::from(self.start)
}
#[inline]
pub fn elapsed_secs(&self) -> f64 {
(self.elapsed() as f64) / (self.clock_rate.get() as f64)
}
pub fn try_add(&self, delta: u32) -> Result<Self, Error> {
Ok(Timestamp {
timestamp: self
.timestamp
.checked_add(i64::from(delta))
.ok_or_else(|| format_err!("overflow on {:?} + {}", &self, delta))?,
clock_rate: self.clock_rate,
start: self.start,
})
}
}
impl Display for Timestamp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{} (mod-2^32: {}), npt {:.03}",
self.timestamp,
self.timestamp as u32,
self.elapsed_secs()
)
}
}
impl Debug for Timestamp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(self, f)
}
}
pub const UNIX_EPOCH: NtpTimestamp = NtpTimestamp((2_208_988_800) << 32);
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct NtpTimestamp(pub u64);
impl std::fmt::Display for NtpTimestamp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let since_epoch = self.0.wrapping_sub(UNIX_EPOCH.0);
let sec_since_epoch = (since_epoch >> 32) as u32;
let tm = time::at(time::Timespec {
sec: i64::from(sec_since_epoch),
nsec: 0,
});
let ms = ((since_epoch & 0xFFFF_FFFF) * 1_000) >> 32;
let zone_minutes = tm.tm_utcoff.abs() / 60;
write!(
f,
"{}.{:03}{}{:02}:{:02}",
tm.strftime("%FT%T").map_err(|_| std::fmt::Error)?,
ms,
if tm.tm_utcoff > 0 { '+' } else { '-' },
zone_minutes / 60,
zone_minutes % 60
)
}
}
impl std::fmt::Debug for NtpTimestamp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} /* {} */", self.0, self)
}
}
#[derive(Copy, Clone)]
pub struct Context {
conn_local_addr: std::net::SocketAddr,
conn_peer_addr: std::net::SocketAddr,
conn_established_wall: time::Timespec,
conn_established: std::time::Instant,
msg_pos: u64,
msg_received_wall: time::Timespec,
msg_received: std::time::Instant,
}
impl Context {
#[doc(hidden)]
pub fn dummy() -> Self {
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0);
Self {
conn_local_addr: addr,
conn_peer_addr: addr,
conn_established_wall: time::get_time(),
conn_established: std::time::Instant::now(),
msg_pos: 0,
msg_received_wall: time::get_time(),
msg_received: std::time::Instant::now(),
}
}
pub fn conn_established(&self) -> std::time::Instant {
self.conn_established
}
pub fn msg_received(&self) -> std::time::Instant {
self.msg_received
}
pub fn msg_pos(&self) -> u64 {
self.msg_pos
}
}
impl Debug for Context {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"[{}(me)->{}@{} pos={}@{}]",
&self.conn_local_addr,
&self.conn_peer_addr,
time::at(self.conn_established_wall)
.strftime("%FT%T")
.map_err(|_| std::fmt::Error)?,
self.msg_pos,
time::at(self.msg_received_wall)
.strftime("%FT%T")
.map_err(|_| std::fmt::Error)?
)
}
}
struct Codec {
ctx: Context,
}
pub(crate) fn as_range(buf: &[u8], subset: &[u8]) -> Option<std::ops::Range<usize>> {
if subset.is_empty() {
return None;
}
let subset_p = subset.as_ptr() as usize;
let buf_p = buf.as_ptr() as usize;
let off = match subset_p.checked_sub(buf_p) {
Some(off) => off,
None => panic!(
"{}-byte subset not within {}-byte buf",
subset.len(),
buf.len()
),
};
let end = off + subset.len();
assert!(end <= buf.len());
Some(off..end)
}
impl tokio_util::codec::Decoder for Codec {
type Item = ReceivedMessage;
type Error = failure::Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
let (msg, len): (Message<&[u8]>, _) = match rtsp_types::Message::parse(src) {
Ok((m, l)) => (m, l),
Err(rtsp_types::ParseError::Error) => bail!("RTSP parse error: {:#?}", &self.ctx),
Err(rtsp_types::ParseError::Incomplete) => return Ok(None),
};
let msg = match msg {
Message::Request(msg) => {
let body_range = as_range(src, msg.body());
let msg = msg.replace_body(rtsp_types::Empty);
if let Some(r) = body_range {
let mut raw_msg = src.split_to(len);
raw_msg.advance(r.start);
raw_msg.truncate(r.len());
Message::Request(msg.replace_body(raw_msg.freeze()))
} else {
src.advance(len);
Message::Request(msg.replace_body(Bytes::new()))
}
}
Message::Response(msg) => {
let body_range = as_range(src, msg.body());
let msg = msg.replace_body(rtsp_types::Empty);
if let Some(r) = body_range {
let mut raw_msg = src.split_to(len);
raw_msg.advance(r.start);
raw_msg.truncate(r.len());
Message::Response(msg.replace_body(raw_msg.freeze()))
} else {
src.advance(len);
Message::Response(msg.replace_body(Bytes::new()))
}
}
Message::Data(msg) => {
let body_range = as_range(src, msg.as_slice());
let msg = msg.replace_body(rtsp_types::Empty);
if let Some(r) = body_range {
let mut raw_msg = src.split_to(len);
raw_msg.advance(r.start);
raw_msg.truncate(r.len());
Message::Data(msg.replace_body(raw_msg.freeze()))
} else {
src.advance(len);
Message::Data(msg.replace_body(Bytes::new()))
}
}
};
self.ctx.msg_received_wall = time::get_time();
self.ctx.msg_received = std::time::Instant::now();
let msg = ReceivedMessage { ctx: self.ctx, msg };
self.ctx.msg_pos += u64::try_from(len).expect("usize fits in u64");
Ok(Some(msg))
}
}
impl tokio_util::codec::Encoder<rtsp_types::Message<bytes::Bytes>> for Codec {
type Error = failure::Error;
fn encode(
&mut self,
item: rtsp_types::Message<bytes::Bytes>,
dst: &mut BytesMut,
) -> Result<(), Self::Error> {
let mut w = std::mem::replace(dst, BytesMut::new()).writer();
item.write(&mut w).expect("bytes Writer is infallible");
*dst = w.into_inner();
Ok(())
}
}