1use super::ack::AckPacket;
21use super::handshake::HandshakePacket;
22use super::misc::{
23 AckAckPacket, CongestionWarningPacket, DropReqPacket, KeepAlivePacket, PeerErrorPacket,
24 ShutdownPacket,
25};
26use super::nak::NakPacket;
27use super::number::{AckNumber, SocketId, SrtTimestamp};
28use super::{Error, Result, SRT_HEADER_LEN, put_be32};
29use broadcast_core::error::ReservedBits;
30use broadcast_core::len::{need_in, need_out};
31
32pub(crate) const CONTROL_TYPE_HANDSHAKE: u16 = 0x0000;
36pub(crate) const CONTROL_TYPE_KEEPALIVE: u16 = 0x0001;
38pub(crate) const CONTROL_TYPE_ACK: u16 = 0x0002;
40pub(crate) const CONTROL_TYPE_NAK: u16 = 0x0003;
42pub(crate) const CONTROL_TYPE_CONGESTION_WARNING: u16 = 0x0004;
44pub(crate) const CONTROL_TYPE_SHUTDOWN: u16 = 0x0005;
46pub(crate) const CONTROL_TYPE_ACKACK: u16 = 0x0006;
48pub(crate) const CONTROL_TYPE_DROPREQ: u16 = 0x0007;
50pub(crate) const CONTROL_TYPE_PEERERROR: u16 = 0x0008;
52pub(crate) const CONTROL_TYPE_USER_DEFINED: u16 = 0x7FFF;
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize))]
60#[non_exhaustive]
61pub enum ControlType {
62 Handshake,
64 KeepAlive,
66 Ack,
68 Nak,
70 CongestionWarning,
72 Shutdown,
74 AckAck,
76 DropReq,
78 PeerError,
80 UserDefined,
83 Reserved(u16),
85}
86
87impl ControlType {
88 pub fn from_bits(v: u16) -> Self {
90 match v {
91 CONTROL_TYPE_HANDSHAKE => ControlType::Handshake,
92 CONTROL_TYPE_KEEPALIVE => ControlType::KeepAlive,
93 CONTROL_TYPE_ACK => ControlType::Ack,
94 CONTROL_TYPE_NAK => ControlType::Nak,
95 CONTROL_TYPE_CONGESTION_WARNING => ControlType::CongestionWarning,
96 CONTROL_TYPE_SHUTDOWN => ControlType::Shutdown,
97 CONTROL_TYPE_ACKACK => ControlType::AckAck,
98 CONTROL_TYPE_DROPREQ => ControlType::DropReq,
99 CONTROL_TYPE_PEERERROR => ControlType::PeerError,
100 CONTROL_TYPE_USER_DEFINED => ControlType::UserDefined,
101 other => ControlType::Reserved(other),
102 }
103 }
104
105 pub fn to_bits(self) -> u16 {
107 match self {
108 ControlType::Handshake => CONTROL_TYPE_HANDSHAKE,
109 ControlType::KeepAlive => CONTROL_TYPE_KEEPALIVE,
110 ControlType::Ack => CONTROL_TYPE_ACK,
111 ControlType::Nak => CONTROL_TYPE_NAK,
112 ControlType::CongestionWarning => CONTROL_TYPE_CONGESTION_WARNING,
113 ControlType::Shutdown => CONTROL_TYPE_SHUTDOWN,
114 ControlType::AckAck => CONTROL_TYPE_ACKACK,
115 ControlType::DropReq => CONTROL_TYPE_DROPREQ,
116 ControlType::PeerError => CONTROL_TYPE_PEERERROR,
117 ControlType::UserDefined => CONTROL_TYPE_USER_DEFINED,
118 ControlType::Reserved(v) => v,
119 }
120 }
121
122 pub fn name(&self) -> &'static str {
124 match self {
125 ControlType::Handshake => "handshake",
126 ControlType::KeepAlive => "keep-alive",
127 ControlType::Ack => "ACK",
128 ControlType::Nak => "NAK",
129 ControlType::CongestionWarning => "congestion warning",
130 ControlType::Shutdown => "shutdown",
131 ControlType::AckAck => "ACKACK",
132 ControlType::DropReq => "message drop request",
133 ControlType::PeerError => "peer error",
134 ControlType::UserDefined => "user-defined",
135 ControlType::Reserved(_) => "reserved",
136 }
137 }
138}
139
140broadcast_core::impl_spec_display!(ControlType, Reserved);
141
142#[derive(Debug, Clone, PartialEq)]
147#[cfg_attr(feature = "serde", derive(serde::Serialize))]
148pub struct UserDefinedPacket<'a> {
149 pub control_type: u16,
151 pub subtype: u16,
154 pub type_specific_info: u32,
156 pub timestamp: SrtTimestamp,
158 pub dest_socket_id: SocketId,
160 pub cif: &'a [u8],
162}
163
164impl<'a> UserDefinedPacket<'a> {
165 pub fn as_key_material(&self) -> Result<super::KeyMaterial<'a>> {
169 super::KeyMaterial::parse(self.cif)
170 }
171}
172
173#[derive(Debug, Clone, PartialEq)]
175#[cfg_attr(feature = "serde", derive(serde::Serialize))]
176#[non_exhaustive]
177pub enum ControlPacket<'a> {
178 Handshake(HandshakePacket<'a>),
180 KeepAlive(KeepAlivePacket),
182 Ack(AckPacket),
184 Nak(NakPacket),
186 CongestionWarning(CongestionWarningPacket),
188 Shutdown(ShutdownPacket),
190 AckAck(AckAckPacket),
192 DropReq(DropReqPacket),
194 PeerError(PeerErrorPacket),
196 UserDefined(UserDefinedPacket<'a>),
198}
199
200fn check_reserved_u16(what: &'static str, v: u16) -> Result<()> {
201 if v != 0 {
202 return Err(Error::ReservedBits(ReservedBits::new(
203 what,
204 0,
205 u64::from(v),
206 )));
207 }
208 Ok(())
209}
210
211fn check_reserved_u32(what: &'static str, v: u32) -> Result<()> {
212 if v != 0 {
213 return Err(Error::ReservedBits(ReservedBits::new(
214 what,
215 0,
216 u64::from(v),
217 )));
218 }
219 Ok(())
220}
221
222const LIBSRT_CIF_PAD_LEN: usize = 4;
229
230const CONTROL_TYPE_SHIFT: u32 = 16;
233const CONTROL_TYPE_MASK: u32 = 0x7FFF;
234const CONTROL_TYPE_BITS: u32 = 15;
235const SUBTYPE_MASK: u32 = 0xFFFF;
236
237fn check_no_cif_or_libsrt_pad(what: &'static str, cif: &[u8]) -> Result<bool> {
244 match cif.len() {
245 0 => Ok(false),
246 LIBSRT_CIF_PAD_LEN => {
247 let value = broadcast_core::wire::Reader::at(cif, 0).u32("value")?;
248 if value != 0 {
249 return Err(Error::ReservedBits(ReservedBits::new(
250 what,
251 0,
252 u64::from(value),
253 )));
254 }
255 Ok(true)
256 }
257 extra => Err(Error::UnexpectedTrailingBytes { what, extra }),
258 }
259}
260
261impl<'a> ControlPacket<'a> {
262 pub fn parse(bytes: &'a [u8]) -> Result<Self> {
269 need_in(bytes, SRT_HEADER_LEN, "SRT control packet header")?;
270 let word0 = broadcast_core::wire::Reader::at(bytes, 0).u32("word0")?;
271 if word0 & super::F_BIT == 0 {
272 return Err(Error::WrongPacketKind {
273 expected: "control packet (F=1)",
274 });
275 }
276 let control_type_bits = ((word0 >> CONTROL_TYPE_SHIFT) & CONTROL_TYPE_MASK) as u16;
277 let subtype = (word0 & SUBTYPE_MASK) as u16;
278 let type_specific_info = broadcast_core::wire::Reader::at(bytes, super::TYPE_FIELD_OFFSET)
279 .u32("type_specific_info")?;
280 let timestamp = SrtTimestamp::from_wire(
281 broadcast_core::wire::Reader::at(bytes, super::TIMESTAMP_OFFSET).u32("timestamp")?,
282 );
283 let dest_socket_id = SocketId::from_wire(
284 broadcast_core::wire::Reader::at(bytes, super::DEST_SOCKET_ID_OFFSET)
285 .u32("SocketId")?,
286 );
287 let cif = &bytes[SRT_HEADER_LEN..];
288 let control_type = ControlType::from_bits(control_type_bits);
289
290 Ok(match control_type {
291 ControlType::Handshake => {
292 check_reserved_u16("Subtype", subtype)?;
293 check_reserved_u32("Type-specific Information", type_specific_info)?;
294 ControlPacket::Handshake(HandshakePacket::parse_cif(
295 timestamp,
296 dest_socket_id,
297 cif,
298 )?)
299 }
300 ControlType::KeepAlive => {
301 check_reserved_u16("Subtype", subtype)?;
302 check_reserved_u32("Type-specific Information", type_specific_info)?;
303 let libsrt_pad = check_no_cif_or_libsrt_pad("keep-alive CIF", cif)?;
304 ControlPacket::KeepAlive(KeepAlivePacket {
305 timestamp,
306 dest_socket_id,
307 libsrt_pad,
308 })
309 }
310 ControlType::Ack => {
311 check_reserved_u16("Subtype", subtype)?;
312 ControlPacket::Ack(AckPacket::parse_cif(
313 type_specific_info,
314 timestamp,
315 dest_socket_id,
316 cif,
317 )?)
318 }
319 ControlType::Nak => {
320 check_reserved_u16("Subtype", subtype)?;
321 check_reserved_u32("Type-specific Information", type_specific_info)?;
322 ControlPacket::Nak(NakPacket::parse_cif(timestamp, dest_socket_id, cif)?)
323 }
324 ControlType::CongestionWarning => {
325 check_reserved_u16("Subtype", subtype)?;
326 check_reserved_u32("Type-specific Information", type_specific_info)?;
327 let libsrt_pad = check_no_cif_or_libsrt_pad("congestion warning CIF", cif)?;
328 ControlPacket::CongestionWarning(CongestionWarningPacket {
329 timestamp,
330 dest_socket_id,
331 libsrt_pad,
332 })
333 }
334 ControlType::Shutdown => {
335 check_reserved_u16("Subtype", subtype)?;
336 check_reserved_u32("Type-specific Information", type_specific_info)?;
337 let libsrt_pad = check_no_cif_or_libsrt_pad("shutdown CIF", cif)?;
338 ControlPacket::Shutdown(ShutdownPacket {
339 timestamp,
340 dest_socket_id,
341 libsrt_pad,
342 })
343 }
344 ControlType::AckAck => {
345 check_reserved_u16("Subtype", subtype)?;
346 let libsrt_pad = check_no_cif_or_libsrt_pad("ACKACK CIF", cif)?;
347 ControlPacket::AckAck(AckAckPacket {
348 ack_number: AckNumber::from_wire(type_specific_info),
349 timestamp,
350 dest_socket_id,
351 libsrt_pad,
352 })
353 }
354 ControlType::DropReq => {
355 check_reserved_u16("Subtype", subtype)?;
356 ControlPacket::DropReq(DropReqPacket::parse_cif(
357 type_specific_info,
358 timestamp,
359 dest_socket_id,
360 cif,
361 )?)
362 }
363 ControlType::PeerError => {
364 check_reserved_u16("Subtype", subtype)?;
365 let libsrt_pad = check_no_cif_or_libsrt_pad("peer error CIF", cif)?;
366 ControlPacket::PeerError(PeerErrorPacket {
367 error_code: type_specific_info,
368 timestamp,
369 dest_socket_id,
370 libsrt_pad,
371 })
372 }
373 ControlType::UserDefined | ControlType::Reserved(_) => {
374 ControlPacket::UserDefined(UserDefinedPacket {
375 control_type: control_type_bits,
376 subtype,
377 type_specific_info,
378 timestamp,
379 dest_socket_id,
380 cif,
381 })
382 }
383 })
384 }
385
386 pub fn control_type(&self) -> ControlType {
388 match self {
389 ControlPacket::Handshake(_) => ControlType::Handshake,
390 ControlPacket::KeepAlive(_) => ControlType::KeepAlive,
391 ControlPacket::Ack(_) => ControlType::Ack,
392 ControlPacket::Nak(_) => ControlType::Nak,
393 ControlPacket::CongestionWarning(_) => ControlType::CongestionWarning,
394 ControlPacket::Shutdown(_) => ControlType::Shutdown,
395 ControlPacket::AckAck(_) => ControlType::AckAck,
396 ControlPacket::DropReq(_) => ControlType::DropReq,
397 ControlPacket::PeerError(_) => ControlType::PeerError,
398 ControlPacket::UserDefined(u) => ControlType::from_bits(u.control_type),
399 }
400 }
401
402 fn subtype(&self) -> u16 {
403 match self {
404 ControlPacket::UserDefined(u) => u.subtype,
405 _ => 0,
406 }
407 }
408
409 fn word1(&self) -> Result<u32> {
410 Ok(match self {
411 ControlPacket::Handshake(_)
412 | ControlPacket::KeepAlive(_)
413 | ControlPacket::Nak(_)
414 | ControlPacket::CongestionWarning(_)
415 | ControlPacket::Shutdown(_) => 0,
416 ControlPacket::Ack(a) => a.ack_number.value(),
421 ControlPacket::AckAck(a) => a.ack_number.value(),
422 ControlPacket::DropReq(d) => d.message_number.value(),
423 ControlPacket::PeerError(p) => p.error_code,
424 ControlPacket::UserDefined(u) => u.type_specific_info,
425 })
426 }
427
428 fn timestamp(&self) -> SrtTimestamp {
429 match self {
430 ControlPacket::Handshake(h) => h.timestamp,
431 ControlPacket::KeepAlive(k) => k.timestamp,
432 ControlPacket::Ack(a) => a.timestamp,
433 ControlPacket::Nak(n) => n.timestamp,
434 ControlPacket::CongestionWarning(c) => c.timestamp,
435 ControlPacket::Shutdown(s) => s.timestamp,
436 ControlPacket::AckAck(a) => a.timestamp,
437 ControlPacket::DropReq(d) => d.timestamp,
438 ControlPacket::PeerError(p) => p.timestamp,
439 ControlPacket::UserDefined(u) => u.timestamp,
440 }
441 }
442
443 fn dest_socket_id(&self) -> SocketId {
444 match self {
445 ControlPacket::Handshake(h) => h.dest_socket_id,
446 ControlPacket::KeepAlive(k) => k.dest_socket_id,
447 ControlPacket::Ack(a) => a.dest_socket_id,
448 ControlPacket::Nak(n) => n.dest_socket_id,
449 ControlPacket::CongestionWarning(c) => c.dest_socket_id,
450 ControlPacket::Shutdown(s) => s.dest_socket_id,
451 ControlPacket::AckAck(a) => a.dest_socket_id,
452 ControlPacket::DropReq(d) => d.dest_socket_id,
453 ControlPacket::PeerError(p) => p.dest_socket_id,
454 ControlPacket::UserDefined(u) => u.dest_socket_id,
455 }
456 }
457
458 fn cif_len(&self) -> usize {
459 match self {
460 ControlPacket::Handshake(h) => h.cif_len(),
461 ControlPacket::KeepAlive(k) => {
465 if k.libsrt_pad {
466 LIBSRT_CIF_PAD_LEN
467 } else {
468 0
469 }
470 }
471 ControlPacket::CongestionWarning(c) => {
472 if c.libsrt_pad {
473 LIBSRT_CIF_PAD_LEN
474 } else {
475 0
476 }
477 }
478 ControlPacket::Shutdown(s) => {
479 if s.libsrt_pad {
480 LIBSRT_CIF_PAD_LEN
481 } else {
482 0
483 }
484 }
485 ControlPacket::AckAck(a) => {
486 if a.libsrt_pad {
487 LIBSRT_CIF_PAD_LEN
488 } else {
489 0
490 }
491 }
492 ControlPacket::PeerError(p) => {
493 if p.libsrt_pad {
494 LIBSRT_CIF_PAD_LEN
495 } else {
496 0
497 }
498 }
499 ControlPacket::Ack(a) => a.cif_len(),
500 ControlPacket::Nak(n) => n.cif_len(),
501 ControlPacket::DropReq(d) => d.cif_len(),
502 ControlPacket::UserDefined(u) => u.cif.len(),
503 }
504 }
505
506 pub fn serialized_len(&self) -> usize {
508 SRT_HEADER_LEN + self.cif_len()
509 }
510
511 pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
513 let len = self.serialized_len();
514 need_out(buf, len, "ControlPacket")?;
515 let control_type_bits = self.control_type().to_bits();
516 broadcast_core::len::fit_bits(
517 u64::from(control_type_bits),
518 CONTROL_TYPE_BITS,
519 "Control Type",
520 )?;
521 let word0 = super::F_BIT
522 | (u32::from(control_type_bits) << CONTROL_TYPE_SHIFT)
523 | u32::from(self.subtype());
524 put_be32(buf, 0, word0);
525 put_be32(buf, super::TYPE_FIELD_OFFSET, self.word1()?);
526 put_be32(buf, super::TIMESTAMP_OFFSET, self.timestamp().value());
527 put_be32(
528 buf,
529 super::DEST_SOCKET_ID_OFFSET,
530 self.dest_socket_id().value(),
531 );
532 let cif = &mut buf[SRT_HEADER_LEN..len];
533 match self {
534 ControlPacket::Handshake(h) => {
535 h.write_cif(cif)?;
536 }
537 ControlPacket::KeepAlive(_)
538 | ControlPacket::CongestionWarning(_)
539 | ControlPacket::Shutdown(_)
540 | ControlPacket::AckAck(_)
541 | ControlPacket::PeerError(_) => {
542 cif.fill(0);
543 }
544 ControlPacket::Ack(a) => {
545 a.write_cif(cif)?;
546 }
547 ControlPacket::Nak(n) => {
548 n.write_cif(cif);
549 }
550 ControlPacket::DropReq(d) => {
551 d.write_cif(cif)?;
552 }
553 ControlPacket::UserDefined(u) => {
554 cif.copy_from_slice(u.cif);
555 }
556 }
557 Ok(len)
558 }
559}
560
561impl<'a> broadcast_core::Parse<'a> for ControlPacket<'a> {
562 type Error = crate::Error;
563
564 fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
565 ControlPacket::parse(bytes)
566 }
567}
568
569impl broadcast_core::Serialize for ControlPacket<'_> {
570 type Error = crate::Error;
571
572 fn serialized_len(&self) -> usize {
573 ControlPacket::serialized_len(self)
574 }
575
576 fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
577 ControlPacket::serialize_into(self, buf)
578 }
579}
580
581#[cfg(test)]
582mod tests {
583 use super::*;
584
585 #[test]
586 fn every_control_type_round_trips_its_table_1_wire_value() {
587 for (ty, value) in [
588 (ControlType::Handshake, 0x0000u16),
589 (ControlType::KeepAlive, 0x0001),
590 (ControlType::Ack, 0x0002),
591 (ControlType::Nak, 0x0003),
592 (ControlType::CongestionWarning, 0x0004),
593 (ControlType::Shutdown, 0x0005),
594 (ControlType::AckAck, 0x0006),
595 (ControlType::DropReq, 0x0007),
596 (ControlType::PeerError, 0x0008),
597 (ControlType::UserDefined, 0x7FFF),
598 ] {
599 assert_eq!(ty.to_bits(), value, "{}", ty.name());
600 assert_eq!(ControlType::from_bits(value), ty);
601 }
602 }
603
604 #[test]
605 fn a_control_type_off_table_1_is_reserved_and_keeps_its_value() {
606 for value in [0x0009u16, 0x0010, 0x7FFE] {
609 assert_eq!(ControlType::from_bits(value), ControlType::Reserved(value));
610 assert_eq!(ControlType::from_bits(value).to_bits(), value);
611 }
612 assert_eq!(ControlType::Reserved(0x0010).name(), "reserved");
613 }
614}