1use std::collections::BTreeMap;
20use std::time::Duration;
21
22use bytes::Bytes;
23use serde::{Deserialize, Serialize};
24use serde_with::base64::Base64;
25use serde_with::{DurationMilliSeconds, serde_as};
26
27use crate::catalog::hang::CatalogExt;
28
29pub(super) const SI_PIDS: &[u16] = &[
42 0x0010, 0x0011, 0x0012, 0x0014, ];
47
48pub(super) fn si_interval(table_id: u8) -> Option<Duration> {
57 match table_id {
58 0x40..=0x41 => Some(Duration::from_secs(10)),
60 0x42 => Some(Duration::from_secs(2)),
62 0x46 => Some(Duration::from_secs(10)),
64 0x4A => Some(Duration::from_secs(10)),
66 0x4E => Some(Duration::from_secs(2)),
68 0x4F => Some(Duration::from_secs(10)),
70 0x50..=0x5F => Some(Duration::from_secs(10)),
72 0x60..=0x6F => Some(Duration::from_secs(30)),
74 0x70 | 0x73 => Some(Duration::from_secs(30)),
76 _ => None,
77 }
78}
79
80#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
87#[serde(remote = "Self", rename_all = "camelCase")]
88#[non_exhaustive]
89pub struct Mpegts {
90 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
94 pub tracks: BTreeMap<String, Track>,
95
96 #[serde(default, skip_serializing_if = "Vec::is_empty")]
99 pub program_descriptors: Vec<Descriptor>,
100
101 #[serde(default, skip_serializing_if = "Option::is_none")]
105 pub program: Option<Program>,
106
107 #[serde(
129 default,
130 skip_serializing_if = "BTreeMap::is_empty",
131 serialize_with = "serialize_si",
132 deserialize_with = "deserialize_si"
133 )]
134 pub si: BTreeMap<u16, BTreeMap<u8, SiEntry>>,
135
136 #[serde(default, skip_serializing_if = "Option::is_none")]
142 pub mux_rate: Option<u64>,
143
144 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub passthrough: Option<PassthroughTrack>,
148}
149
150impl Serialize for Mpegts {
151 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
152 Mpegts::serialize(self, serializer)
153 }
154}
155
156impl<'de> Deserialize<'de> for Mpegts {
157 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
158 let mpegts = Mpegts::deserialize(deserializer)?;
159 if let Some(passthrough) = &mpegts.passthrough
160 && mpegts.names(&passthrough.track)
161 {
162 return Err(serde::de::Error::custom(format!(
163 "the passthrough track `{}` is also described as a demultiplexed one",
164 passthrough.track
165 )));
166 }
167 Ok(mpegts)
168 }
169}
170
171impl Mpegts {
172 pub fn is_empty(&self) -> bool {
174 self.tracks.is_empty()
175 && self.program_descriptors.is_empty()
176 && self.program.is_none()
177 && self.si.is_empty()
178 && self.mux_rate.is_none()
179 && self.passthrough.is_none()
180 }
181
182 pub(crate) fn has_track(&self) -> bool {
185 self.passthrough.is_some()
186 || self
187 .tracks
188 .values()
189 .any(|track| track.verbatim.is_some() || track.pes_packet.is_some())
190 || self
191 .si
192 .values()
193 .flat_map(BTreeMap::values)
194 .any(|entry| !entry.track.is_empty())
195 }
196
197 fn names(&self, track: &str) -> bool {
199 self.tracks.contains_key(track)
200 || self
201 .si
202 .values()
203 .flat_map(BTreeMap::values)
204 .any(|entry| entry.track == track)
205 }
206}
207
208#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
216#[serde(rename_all = "camelCase")]
217#[non_exhaustive]
218pub struct PassthroughTrack {
219 pub track: String,
221
222 #[serde(default)]
229 pub random_access: bool,
230}
231
232impl PassthroughTrack {
233 pub fn new(track: impl Into<String>) -> Self {
235 Self {
236 track: track.into(),
237 random_access: false,
238 }
239 }
240}
241
242#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
250#[serde(rename_all = "camelCase")]
251#[non_exhaustive]
252pub struct Program {
253 pub transport_stream_id: u16,
256
257 pub program_number: u16,
260
261 pub pmt_pid: u16,
263}
264
265#[serde_as]
274#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
275#[serde(rename_all = "camelCase")]
276#[non_exhaustive]
277pub struct SiEntry {
278 pub track: String,
282
283 #[serde_as(as = "Option<DurationMilliSeconds<u64>>")]
290 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub interval: Option<Duration>,
292
293 #[serde(skip)]
298 pub(crate) sections: Vec<Bytes>,
299}
300
301fn serialize_si<S: serde::Serializer>(
307 si: &BTreeMap<u16, BTreeMap<u8, SiEntry>>,
308 serializer: S,
309) -> Result<S::Ok, S::Error> {
310 use serde::ser::{Error, SerializeMap};
311 let mut map = serializer.serialize_map(Some(si.len()))?;
312 for (pid, tables) in si {
313 for entry in tables.values() {
314 if !entry.sections.is_empty() {
315 return Err(S::Error::custom(format!(
316 "inline SI sections on PID {pid} name no track and cannot be serialized"
317 )));
318 }
319 }
320 let tables: BTreeMap<String, &SiEntry> = tables.iter().map(|(id, entry)| (id.to_string(), entry)).collect();
321 map.serialize_entry(&pid.to_string(), &tables)?;
322 }
323 map.end()
324}
325
326fn deserialize_si<'de, D>(deserializer: D) -> Result<BTreeMap<u16, BTreeMap<u8, SiEntry>>, D::Error>
329where
330 D: serde::Deserializer<'de>,
331{
332 use serde::de::Error;
333
334 #[serde_as]
336 #[derive(Deserialize)]
337 #[serde(rename_all = "camelCase", deny_unknown_fields)]
338 struct Inline {
339 #[serde_as(as = "Vec<Base64>")]
340 sections: Vec<Bytes>,
341 #[serde_as(as = "Option<DurationMilliSeconds<u64>>")]
342 #[serde(default)]
343 interval: Option<Duration>,
344 }
345
346 let raw: BTreeMap<String, serde_json::Value> = Deserialize::deserialize(deserializer)?;
347 let mut si = BTreeMap::new();
348 for (pid, value) in raw {
349 let pid: u16 = pid.parse().map_err(D::Error::custom)?;
350 let tables = if value.get("sections").is_some() {
351 let inline: Inline = serde_json::from_value(value).map_err(D::Error::custom)?;
352 let mut tables: BTreeMap<u8, SiEntry> = BTreeMap::new();
353 for section in inline.sections {
354 let Some(&table_id) = section.first() else {
355 return Err(D::Error::custom(format!("empty SI section on PID {pid}")));
356 };
357 tables
358 .entry(table_id)
359 .or_insert_with(|| SiEntry {
360 interval: inline.interval.or_else(|| si_interval(table_id)),
363 ..Default::default()
364 })
365 .sections
366 .push(section);
367 }
368 tables
369 } else {
370 let tables: BTreeMap<String, SiEntry> = serde_json::from_value(value).map_err(D::Error::custom)?;
371 tables
372 .into_iter()
373 .map(|(table_id, entry)| Ok((table_id.parse().map_err(D::Error::custom)?, entry)))
374 .collect::<Result<_, D::Error>>()?
375 };
376 si.insert(pid, tables);
377 }
378 Ok(si)
379}
380
381#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
383#[serde(rename_all = "camelCase")]
384#[non_exhaustive]
385pub struct Track {
386 pub pid: u16,
389
390 #[serde(default, skip_serializing_if = "Vec::is_empty")]
393 pub descriptors: Vec<Descriptor>,
394
395 #[serde(default, skip_serializing_if = "Option::is_none")]
397 pub verbatim: Option<Verbatim>,
398
399 #[serde(default, skip_serializing_if = "Option::is_none")]
402 pub pes_packet: Option<PesPacket>,
403}
404
405impl Track {
406 pub fn new(pid: u16) -> Self {
408 Self {
409 pid,
410 descriptors: Vec::new(),
411 verbatim: None,
412 pes_packet: None,
413 }
414 }
415}
416
417#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
423#[serde(rename_all = "camelCase")]
424#[non_exhaustive]
425pub struct Verbatim {
426 pub stream_type: u8,
428
429 pub framing: Framing,
432}
433
434impl Verbatim {
435 pub fn new(stream_type: u8, framing: Framing) -> Self {
437 Self { stream_type, framing }
438 }
439}
440
441#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
450#[serde(rename_all = "camelCase")]
451#[non_exhaustive]
452pub struct PesPacket {
453 pub stream_type: u8,
456}
457
458impl PesPacket {
459 pub fn new(stream_type: u8) -> Self {
461 Self { stream_type }
462 }
463}
464
465#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
470#[serde(rename_all = "camelCase")]
471#[non_exhaustive]
472pub enum Framing {
473 #[default]
476 Section,
477}
478
479#[serde_as]
482#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
483#[serde(rename_all = "camelCase")]
484pub struct Descriptor {
485 pub tag: u8,
487 #[serde_as(as = "Base64")]
489 pub data: Bytes,
490}
491
492#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
495#[non_exhaustive]
496pub struct Ext {
497 #[serde(default, skip_serializing_if = "Mpegts::is_empty")]
498 pub mpegts: Mpegts,
500}
501
502impl CatalogExt for Ext {}
503
504pub trait Catalog: CatalogExt {
509 fn mpegts_mut(&mut self) -> Option<&mut Mpegts>;
516}
517
518impl Catalog for () {
519 fn mpegts_mut(&mut self) -> Option<&mut Mpegts> {
520 None
521 }
522}
523
524impl Catalog for crate::catalog::hang::Extra {
527 fn mpegts_mut(&mut self) -> Option<&mut Mpegts> {
528 None
529 }
530}
531
532impl Catalog for Ext {
533 fn mpegts_mut(&mut self) -> Option<&mut Mpegts> {
534 Some(&mut self.mpegts)
535 }
536}
537
538#[cfg(test)]
539mod test {
540 use super::*;
541
542 #[test]
543 fn mux_rate_alone_is_not_empty() {
544 let mpegts = Mpegts {
547 mux_rate: Some(2_500_000),
548 ..Default::default()
549 };
550 assert!(!mpegts.is_empty());
551 let json = serde_json::to_string(&Ext { mpegts }).unwrap();
552 assert_eq!(json, r#"{"mpegts":{"muxRate":2500000}}"#);
553 assert_eq!(serde_json::to_string(&Ext::default()).unwrap(), "{}");
555 }
556
557 #[test]
558 fn passthrough_roundtrip() {
559 let mut passthrough = PassthroughTrack::new("0.m2ts");
560 passthrough.random_access = true;
561 let mpegts = Mpegts {
562 passthrough: Some(passthrough),
563 mux_rate: Some(2_499_999),
564 ..Default::default()
565 };
566
567 let json = serde_json::to_string(&Ext { mpegts: mpegts.clone() }).unwrap();
568 assert_eq!(
569 json,
570 r#"{"mpegts":{"muxRate":2499999,"passthrough":{"track":"0.m2ts","randomAccess":true}}}"#
571 );
572 assert_eq!(serde_json::from_str::<Ext>(&json).unwrap().mpegts, mpegts);
573
574 let json = serde_json::to_string(&PassthroughTrack::new("0.m2ts")).unwrap();
576 assert_eq!(json, r#"{"track":"0.m2ts","randomAccess":false}"#);
577 let read: PassthroughTrack = serde_json::from_str(r#"{"track":"0.m2ts"}"#).unwrap();
578 assert_eq!(read, PassthroughTrack::new("0.m2ts"));
579 serde_json::from_str::<PassthroughTrack>(r#"{"randomAccess":true}"#)
580 .expect_err("a passthrough names its track");
581 }
582
583 #[test]
586 fn a_passthrough_track_described_as_demultiplexed_is_refused() {
587 let passthrough = r#""passthrough":{"track":"0.m2ts","randomAccess":true}"#;
588 for other in [
589 r#""tracks":{"0.m2ts":{"pid":256}}"#,
590 r#""si":{"17":{"66":{"track":"0.m2ts"}}}"#,
591 ] {
592 let json = format!("{{{passthrough},{other}}}");
593 serde_json::from_str::<Mpegts>(&json).expect_err(&json);
594 }
595
596 let json = format!(
597 r#"{{{passthrough},"tracks":{{"0.avc3":{{"pid":256}}}},"program":{{"transportStreamId":1,"programNumber":1,"pmtPid":4096}}}}"#
598 );
599 let mpegts: Mpegts = serde_json::from_str(&json).unwrap();
600 assert_eq!(mpegts.passthrough.unwrap().track, "0.m2ts");
601 }
602
603 #[test]
604 fn section_roundtrip() {
605 let mut mpegts = Mpegts::default();
606 mpegts.tracks.insert(
608 "audio".to_string(),
609 Track {
610 pid: 0x101,
611 descriptors: vec![Descriptor {
612 tag: 0x0a,
613 data: Bytes::from_static(b"eng\x00"),
614 }],
615 verbatim: None,
616 pes_packet: None,
617 },
618 );
619 mpegts.tracks.insert(
621 ".scte35".to_string(),
622 Track {
623 pid: 0x102,
624 descriptors: Vec::new(),
625 verbatim: Some(Verbatim::new(0x86, Framing::Section)),
626 pes_packet: None,
627 },
628 );
629 mpegts.tracks.insert(
631 "0.ts".to_string(),
632 Track {
633 pid: 0x103,
634 descriptors: Vec::new(),
635 verbatim: None,
636 pes_packet: Some(PesPacket::new(0x06)),
637 },
638 );
639 mpegts.program_descriptors.push(Descriptor {
640 tag: 0x05,
641 data: Bytes::from_static(b"CUEI"),
642 });
643 mpegts.mux_rate = Some(2_500_000);
644
645 let json = serde_json::to_string(&Ext { mpegts: mpegts.clone() }).unwrap();
646 assert!(json.contains("\"Q1VFSQ==\""), "descriptor data is base64: {json}");
648 assert!(
649 json.contains("\"muxRate\":2500000"),
650 "mux rate is a bare integer: {json}"
651 );
652 assert!(
653 json.contains("\"pesPacket\":{\"streamType\":6}"),
654 "the whole-PES member is camelCase: {json}"
655 );
656
657 let parsed: Ext = serde_json::from_str(&json).unwrap();
658 assert_eq!(parsed.mpegts, mpegts, "mpegts section round-trips");
659 }
660
661 #[test]
662 fn program_and_si_roundtrip() {
663 let entry = SiEntry {
664 track: "0x0011-0x42.si".to_string(),
665 interval: Some(Duration::from_secs(2)),
666 ..Default::default()
667 };
668
669 let mpegts = Mpegts {
670 program: Some(Program {
671 transport_stream_id: 0x1234,
672 program_number: 1,
673 pmt_pid: 0x0064,
674 ..Default::default()
675 }),
676 si: BTreeMap::from([(0x0011, BTreeMap::from([(0x42u8, entry)]))]),
677 ..Default::default()
678 };
679 assert!(!mpegts.is_empty(), "a program record is not empty");
680
681 let json = serde_json::to_string(&Ext { mpegts: mpegts.clone() }).unwrap();
682 assert!(json.contains("\"pmtPid\":100"), "identity stays structured: {json}");
683 assert!(json.contains("\"17\":"), "PID key written as a string: {json}");
685 assert!(json.contains("\"66\":"), "table_id key written as a string: {json}");
686 assert!(
687 json.contains("\"track\":\"0x0011-0x42.si\""),
688 "the entry names its track: {json}"
689 );
690 assert!(json.contains("\"interval\":2000"), "interval is bare millis: {json}");
694
695 let parsed: Ext = serde_json::from_str(&json).unwrap();
696 assert_eq!(parsed.mpegts, mpegts, "program and SI round-trip");
697 }
698
699 #[test]
700 fn inline_si_form_is_read() {
701 let json = r#"{
706 "program": {"pmtPid": 4096, "programNumber": 1, "transportStreamId": 1},
707 "si": {
708 "17": {
709 "interval": 2000,
710 "sections": ["QvAlAAHBAAD/Af8AAfyAFEgSAQZGRm1wZWcJU2VydmljZTAxd3xDyg=="]
711 }
712 },
713 "tracks": {"0.avc3": {"pid": 256}}
714 }"#;
715 let mpegts: Mpegts = serde_json::from_str(json).expect("the 0.11.0 form must decode");
716
717 let sdt = &mpegts.si[&0x0011][&0x42];
720 assert_eq!(sdt.track, "");
721 assert_eq!(sdt.interval, Some(Duration::from_secs(2)));
722 assert_eq!(sdt.sections.len(), 1);
723 assert_eq!(sdt.sections[0][0], 0x42);
724 assert_eq!(mpegts.si[&0x0011].len(), 1);
725
726 let json = r#"{"si": {"18": {"sections": ["TgAB", "UAAB", "TgAC"]}}}"#;
729 let mpegts: Mpegts = serde_json::from_str(json).unwrap();
730 let eit = &mpegts.si[&0x0012];
731 assert_eq!(eit.len(), 2);
732 assert_eq!(eit[&0x4e].sections.len(), 2);
733 assert_eq!(eit[&0x4e].interval, Some(Duration::from_secs(2)));
734 assert_eq!(eit[&0x50].sections.len(), 1);
735 assert_eq!(eit[&0x50].interval, Some(Duration::from_secs(10)));
736
737 serde_json::to_string(&mpegts).expect_err("inline sections must not serialize");
740 }
741
742 #[test]
743 fn track_backed_si_roundtrip_after_legacy_read() {
744 let json = r#"{"si": {
747 "17": {"sections": ["QvAlAAHBAAD/Af8AAfyAFEgSAQZGRm1wZWcJU2VydmljZTAxd3xDyg=="]},
748 "18": {"78": {"track": "si/18/78", "interval": 2000}}
749 }}"#;
750 let mut mpegts: Mpegts = serde_json::from_str(json).unwrap();
751 serde_json::to_string(&mpegts).expect_err("the inline entry must not serialize");
752 mpegts.si.remove(&0x0011);
753 let json = serde_json::to_string(&mpegts).unwrap();
754 assert!(json.contains("\"si/18/78\""), "track-backed entry still writes: {json}");
755 let parsed: Mpegts = serde_json::from_str(&json).unwrap();
756 assert_eq!(parsed, mpegts);
757 }
758
759 #[test]
760 fn unknown_framing_is_refused() {
761 let json = r#"{
762 "tracks": {
763 "x.ts": {
764 "pid": 500,
765 "verbatim": { "streamType": 6, "framing": "future" }
766 }
767 }
768 }"#;
769 let err = serde_json::from_str::<Mpegts>(json).expect_err("unknown framing must fail");
770 assert!(
771 err.to_string().contains("future"),
772 "error should name the unknown variant: {err}"
773 );
774 }
775
776 #[test]
779 fn legacy_pes_framing_is_refused() {
780 for verbatim in [
781 r#"{ "streamType": 6, "framing": "pes", "streamId": 189 }"#,
782 r#"{ "streamType": 6 }"#,
783 ] {
784 let json = format!(r#"{{ "tracks": {{ "x.ts": {{ "pid": 500, "verbatim": {verbatim} }} }} }}"#);
785 serde_json::from_str::<Mpegts>(&json).expect_err(&format!("{verbatim} must be refused"));
786 }
787 }
788
789 #[test]
790 fn invalid_si_pid_key_is_refused() {
791 let json = r#"{ "si": { "not-a-pid": { "66": { "track": "si" } } } }"#;
792 serde_json::from_str::<Mpegts>(json).expect_err("a non-integer SI PID key must fail");
793 }
794
795 #[test]
796 fn mixed_si_forms_are_refused() {
797 let json = r#"{ "si": { "17": {
800 "sections": ["QvAlAAHBAAD/Af8AAfyAFEgSAQZGRm1wZWcJU2VydmljZTAxd3xDyg=="],
801 "66": { "track": "si/17/66" }
802 } } }"#;
803 serde_json::from_str::<Mpegts>(json).expect_err("sections with a table_id entry must fail");
804 }
805
806 #[tokio::test]
809 async fn section_rides_the_msf_catalog() {
810 use crate::catalog::Stream as _;
811
812 let mut broadcast = moq_net::broadcast::Info::new().produce();
813 let mut producer = crate::catalog::Producer::new(
814 &mut broadcast,
815 crate::catalog::Config::default().with_catalog(crate::catalog::hang::Catalog::<Ext>::default()),
816 )
817 .unwrap();
818
819 let mut guard = producer.modify(producer.next_timestamp()).unwrap();
820 guard.ext.mpegts.program = Some(Program {
821 transport_stream_id: 0x1234,
822 program_number: 1,
823 pmt_pid: 0x0064,
824 ..Default::default()
825 });
826 guard.ext.mpegts.tracks.insert(
827 ".ts".to_string(),
828 Track {
829 pid: 0x0102,
830 descriptors: vec![Descriptor {
831 tag: 0x05,
832 data: Bytes::from_static(b"CUEI"),
833 }],
834 verbatim: Some(Verbatim::new(0x86, Framing::Section)),
835 pes_packet: None,
836 },
837 );
838 let expected = guard.ext.mpegts.clone();
839 drop(guard);
840
841 let mut consumer =
842 crate::catalog::Consumer::<Ext>::new(&broadcast.consume(), crate::catalog::CatalogFormat::Msf)
843 .await
844 .unwrap();
845
846 let catalog = consumer.next().await.unwrap().expect("catalog published").value;
847 assert_eq!(
848 catalog.ext.mpegts, expected,
849 "the mpegts section survives the MSF track"
850 );
851 }
852}