Skip to main content

moq_mux/container/ts/
catalog.rs

1//! MPEG-TS catalog extension (the `mpegts` section).
2//!
3//! The `mpegts` section carries everything needed to faithfully re-mux a broadcast
4//! back to MPEG-TS that doesn't belong in the codec-neutral media configs: one
5//! entry per track (its original PID and PMT descriptors), a `verbatim` or
6//! `pesPacket` carriage record for every elementary stream we don't decode (SCTE-35,
7//! teletext, DVB subtitles, private data, ...), the program-level PMT descriptors, the program
8//! identity ([`Program`]), and the standalone SI table map ([`SiEntry`]).
9//! Demuxed media tracks keep their codec config in the base `video`/`audio`
10//! sections; only their MPEG-TS identity lands here. A constant-rate source also
11//! records its multiplex rate ([`Mpegts::mux_rate`]), so export can pad the rebuilt
12//! stream back to it. A multiplex carried whole instead names its one track in
13//! [`Mpegts::passthrough`].
14//!
15//! The section is specified by `drafts/draft-lcurley-moq-mpegts.md` and rides the
16//! root of either catalog: the hang track alongside `video`/`audio`, and the MSF
17//! track alongside `tracks`.
18
19use 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
29/// The standalone SI PIDs we capture. Everything on a captured PID is carried,
30/// whatever its `table_id`: the SDT PID also carries the BAT, the EIT PID carries
31/// both now/next and the full schedule, and a table we've never heard of is exactly
32/// as worth preserving as one we have.
33///
34/// TDT/TOT (0x0014) is proxied, not synthesized (#2914): EIT event times are
35/// expressed on the source's clock, so a locally-minted time next to a relayed
36/// schedule can disagree with it, and TOT's `local_time_offset` descriptors (DST
37/// transitions, per-country offsets) are operator data an exporter cannot invent.
38/// Each tick replaces the last on its latest-value slot, so staleness is bounded by
39/// the source's own repetition interval plus path latency, the same class a TS
40/// receiver already lives with.
41pub(super) const SI_PIDS: &[u16] = &[
42	0x0010, // NIT (network description)
43	0x0011, // SDT and BAT (service and bouquet description)
44	0x0012, // EIT (event information: now/next and schedule)
45	0x0014, // TDT and TOT (time and local-time offset)
46];
47
48/// The DVB maximum repetition interval for a known `table_id` (ETSI TS 101 211).
49///
50/// Export treats the interval as an upper bound and repeats at half of it, not at
51/// the source's observed cadence, which is a property of that multiplexer's bitrate
52/// shaping and means nothing downstream. `None` for a table we don't recognize;
53/// export then falls back to its PSI cadence, so an unknown table degrades to a safe
54/// (fast) rate rather than being dropped. Keyed by `table_id` rather than PID because that is the granularity the
55/// spec defines: the EIT PID alone carries tables wanting 2s and 30s.
56pub(super) fn si_interval(table_id: u8) -> Option<Duration> {
57	match table_id {
58		// NIT actual/other.
59		0x40..=0x41 => Some(Duration::from_secs(10)),
60		// SDT actual.
61		0x42 => Some(Duration::from_secs(2)),
62		// SDT other.
63		0x46 => Some(Duration::from_secs(10)),
64		// BAT.
65		0x4A => Some(Duration::from_secs(10)),
66		// EIT now/next actual.
67		0x4E => Some(Duration::from_secs(2)),
68		// EIT now/next other.
69		0x4F => Some(Duration::from_secs(10)),
70		// EIT schedule actual.
71		0x50..=0x5F => Some(Duration::from_secs(10)),
72		// EIT schedule other.
73		0x60..=0x6F => Some(Duration::from_secs(30)),
74		// TDT and TOT.
75		0x70 | 0x73 => Some(Duration::from_secs(30)),
76		_ => None,
77	}
78}
79
80/// The `mpegts` catalog section.
81///
82/// Omitted from the catalog when empty, so a broadcast that needs none of it stays
83/// byte-identical to one without the extension. Reading refuses a section that names its
84/// [`passthrough`](Self::passthrough) track in [`tracks`](Self::tracks) or [`si`](Self::si) too.
85// `remote = "Self"` derives inherent (de)serializers, which the trait impls below wrap.
86#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
87#[serde(remote = "Self", rename_all = "camelCase")]
88#[non_exhaustive]
89pub struct Mpegts {
90	/// Per-track MPEG-TS info, keyed by MoQ track name. Media tracks record their
91	/// PID and PMT descriptors; undecoded tracks add a [`Verbatim`] or [`PesPacket`]
92	/// carriage record.
93	#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
94	pub tracks: BTreeMap<String, Track>,
95
96	/// PMT program-level descriptors (`program_info`), carried verbatim. Export
97	/// re-emits these; the SCTE-35 'CUEI' registration is derived when absent.
98	#[serde(default, skip_serializing_if = "Vec::is_empty")]
99	pub program_descriptors: Vec<Descriptor>,
100
101	/// Program identity from the PAT. Present only for a source that carries one (a TS
102	/// input); omitted for media-only broadcasts, so export then synthesizes a minimal
103	/// identity.
104	#[serde(default, skip_serializing_if = "Option::is_none")]
105	pub program: Option<Program>,
106
107	/// Standalone SI tables, keyed by the PID they ride on (0x0011 SDT, 0x0010 NIT,
108	/// 0x0012 EIT, ...) and then by `table_id`. The section bytes themselves live on
109	/// each entry's snapshot [track](SiEntry::track); the catalog only maps where they
110	/// are and how often export must re-emit them. Export re-emits each entry's
111	/// sections byte-for-byte on its PID, so the service name, provider, network, and
112	/// EPG survive without anyone parsing them.
113	///
114	/// `table_id` is byte 0 of generic section syntax (ISO 13818-1), so the key is no
115	/// less generic than the PID: which *ranges* mean what is a DVB convention, and
116	/// none appears here.
117	///
118	/// JSON object keys are strings, so both keys are written in decimal (`"17"`)
119	/// rather than as numbers. The catalog is parsed via `serde_json::Value`, which
120	/// will not coerce a string key back to an integer on its own.
121	///
122	/// Reading also accepts the form every published moq-cli through 0.11 wrote,
123	/// `{"17": {"interval": 2000, "sections": ["<base64>"]}}`: the sections inline
124	/// under the PID with no `table_id` level. Those decode into one entry per
125	/// `table_id` (byte 0 of each section) carrying its sections in
126	/// `SiEntry::sections` and naming no track. Nothing writes that form:
127	/// serializing such an entry fails rather than emit a dangling track reference.
128	#[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	/// The rate the PCR clock paces the whole multiplex at, in bits per second:
137	/// every PID plus PSI plus null stuffing, measured between PCRs on import. Not a
138	/// sum of elementary streams; each rendition's `bitrate` keeps its codec meaning.
139	/// Present only while the source is constant-rate, so a VBR or file-paced input
140	/// leaves it absent. Export pads its output with null packets to this rate.
141	#[serde(default, skip_serializing_if = "Option::is_none")]
142	pub mux_rate: Option<u64>,
143
144	/// The track carrying the multiplex whole, when a [`Passthrough`](super::Passthrough)
145	/// publishes it rather than demultiplexing it.
146	#[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	/// True when the section carries nothing, so it's omitted from the catalog.
173	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	/// Whether the section lists a track it carries itself: an undecoded stream, an SI table, or
183	/// the passthrough.
184	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	/// Whether `tracks` or `si` names `track`.
198	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/// A transport stream carried whole, as one track of verbatim packets.
209///
210/// The track's frames are runs of whole 188-byte packets in source order, each in the legacy
211/// container with the PCR time of its first byte. Nothing else about the multiplex is described
212/// for it, because all of it stays in-band: the PAT, PMT, and SI ride the track as authored,
213/// scrambled payloads included. The section's [`mux_rate`](Mpegts::mux_rate) is measured over
214/// every packet of the track.
215#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
216#[serde(rename_all = "camelCase")]
217#[non_exhaustive]
218pub struct PassthroughTrack {
219	/// The track carrying the packets, published in the same broadcast as the catalog.
220	pub track: String,
221
222	/// Whether every group starts at a random access point of the multiplex's video stream, or of
223	/// its clock PID when it has none, so a subscriber can decode from the first object of any.
224	///
225	/// Only ever true for a single program with at most one video stream: programs or video
226	/// streams sharing a clock can stagger their GOPs, leaving no packet that starts all of them.
227	/// Always written; a reader treats it as false when absent.
228	#[serde(default)]
229	pub random_access: bool,
230}
231
232impl PassthroughTrack {
233	/// A passthrough on `track`, with no random access promised.
234	pub fn new(track: impl Into<String>) -> Self {
235		Self {
236			track: track.into(),
237			random_access: false,
238		}
239	}
240}
241
242/// Program identity, from the PAT.
243///
244/// The only part of the service layer we parse, because export has to: these three
245/// values rebuild a PAT/PMT consistent with the SI tables carried on the tracks
246/// [`SiEntry`] maps. Everything else about the program (its name, provider, type,
247/// network) stays opaque bytes. Named for the MPEG concept rather than the DVB one: DVB calls
248/// a program a service, but the same PAT fields carry an ATSC or ISDB stream too.
249#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
250#[serde(rename_all = "camelCase")]
251#[non_exhaustive]
252pub struct Program {
253	/// Transport stream ID from the PAT, preserved so the rebuilt PAT stays
254	/// consistent with the carried SI.
255	pub transport_stream_id: u16,
256
257	/// Program number from the PAT (the DVB service ID). Re-emitted as the PAT program
258	/// number and the PMT `program_number`.
259	pub program_number: u16,
260
261	/// Original PMT PID from the PAT, preserved so PMT cross-references survive.
262	pub pmt_pid: u16,
263}
264
265/// One standalone SI table's carriage: which track holds its sections, and how
266/// often export must re-emit them.
267///
268/// The sections themselves ride the named snapshot track (see the `ts` module docs
269/// for the track format), not the catalog, so a table revision republishes a small
270/// track group instead of the whole catalog. Sections stay opaque: nothing here
271/// parses a table, so an SDT, a BAT, an EPG, or a table we've never heard of all
272/// round-trip the same way.
273#[serde_as]
274#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)]
275#[serde(rename_all = "camelCase")]
276#[non_exhaustive]
277pub struct SiEntry {
278	/// Name of the snapshot track carrying this table's sections, on the same
279	/// broadcast as the catalog. Each group is a complete snapshot of the table's
280	/// current sections; a joiner reads only the newest group.
281	pub track: String,
282
283	/// Re-emit at least this often. A hint: import fills in the DVB maximum for the
284	/// tables it recognizes, and export repeats at half of it. Absent for an unknown
285	/// `table_id`, which export then re-emits on its own PSI cadence, so an unknown
286	/// table degrades to a safe rate rather than being dropped.
287	///
288	/// Serialized as an integer number of milliseconds (sub-ms precision is truncated).
289	#[serde_as(as = "Option<DurationMilliSeconds<u64>>")]
290	#[serde(default, skip_serializing_if = "Option::is_none")]
291	pub interval: Option<Duration>,
292
293	/// The sections themselves, only for an entry read from the pre-`table_id`
294	/// catalog form (see [`Mpegts::si`]): that form carried them inline, so there
295	/// is no track to subscribe to and export re-emits these instead. Empty for an
296	/// entry that names a track. Serializing an entry that carries them fails.
297	#[serde(skip)]
298	pub(crate) sections: Vec<Bytes>,
299}
300
301/// Encode [`Mpegts::si`] with both integer keys as decimal strings.
302///
303/// An entry carrying inline sections (see [`Mpegts::si`]) names no track, so
304/// there is nothing faithful to write for it: serialization fails rather than
305/// emit a dangling empty track reference.
306fn 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
326/// Decode [`Mpegts::si`] in either form: the `table_id`-keyed map of track
327/// references, or the pre-`table_id` inline form under the same PID keys.
328fn 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	/// The pre-`table_id` form of one PID's entry.
335	#[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						// The inline form's interval covered the whole PID; a table it
361						// left unbounded gets the DVB maximum export would use anyway.
362						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/// One track's MPEG-TS identity and signaling.
382#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
383#[serde(rename_all = "camelCase")]
384#[non_exhaustive]
385pub struct Track {
386	/// Original MPEG-TS PID. Export prefers it so PID cross-references survive;
387	/// tracks without an entry are renumbered.
388	pub pid: u16,
389
390	/// PMT ES-level descriptors (ISO-639 language, registration, ...), carried
391	/// verbatim so they survive the round-trip.
392	#[serde(default, skip_serializing_if = "Vec::is_empty")]
393	pub descriptors: Vec<Descriptor>,
394
395	/// Present when the stream is carried as sections (not decoded into `video`/`audio`).
396	#[serde(default, skip_serializing_if = "Option::is_none")]
397	pub verbatim: Option<Verbatim>,
398
399	/// Present when each frame is one whole PES packet, sent at its timestamp. An entry
400	/// carries this or [`Self::verbatim`], never both.
401	#[serde(default, skip_serializing_if = "Option::is_none")]
402	pub pes_packet: Option<PesPacket>,
403}
404
405impl Track {
406	/// A new media track entry (decoded; no verbatim carriage), recording its PID.
407	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/// Carriage record for an undecoded elementary stream carried as complete sections.
418///
419/// Each frame includes the section header and CRC, timestamped at its first section byte
420/// on the PCR-derived program clock, as for [`PesPacket`]. SCTE-35 splice times ride inside
421/// the payload, shifted onto the catalog clock through `pts_adjustment`.
422#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
423#[serde(rename_all = "camelCase")]
424#[non_exhaustive]
425pub struct Verbatim {
426	/// Raw PMT `stream_type` to re-announce, including types the muxer does not recognize.
427	pub stream_type: u8,
428
429	/// How the verbatim payload is framed, so export knows how to repacketize it. Required:
430	/// draft -00 let an absent one mean PES payloads, which nothing carries any more.
431	pub framing: Framing,
432}
433
434impl Verbatim {
435	/// A new verbatim carriage record of the given `stream_type` and `framing`.
436	pub fn new(stream_type: u8, framing: Framing) -> Self {
437		Self { stream_type, framing }
438	}
439}
440
441/// Carriage record for an undecoded elementary stream whose frames are whole PES packets.
442///
443/// Each frame is one complete PES packet, start code through payload, with its PTS, DTS
444/// and every other header field already on the catalog clock. Its timestamp is the
445/// packet's placement: the program clock at its first byte, which export sends it at.
446/// Each frame is a group of its own, except MPEG-1/2 video's, grouped from one sequence header
447/// to the next. A member beside [`Verbatim`] rather than a [`Framing`], so a consumer that predates it
448/// ignores the track instead of refusing the catalog.
449#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
450#[serde(rename_all = "camelCase")]
451#[non_exhaustive]
452pub struct PesPacket {
453	/// PMT `stream_type` to re-announce (0x06 private PES, ...). The `stream_id` rides
454	/// in each packet.
455	pub stream_type: u8,
456}
457
458impl PesPacket {
459	/// A new whole-PES carriage record of the given `stream_type`.
460	pub fn new(stream_type: u8) -> Self {
461		Self { stream_type }
462	}
463}
464
465/// How a verbatim stream's payload is framed on the wire, so export can repacketize it.
466///
467/// A PES stream rides [`PesPacket`] instead. The `"pes"` framing draft -00 defined is refused
468/// rather than read as a section.
469#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
470#[serde(rename_all = "camelCase")]
471#[non_exhaustive]
472pub enum Framing {
473	/// Private sections (table_id + section_length framing). Each frame is one
474	/// complete section. Used by SCTE-35 and other private-section signaling.
475	#[default]
476	Section,
477}
478
479/// One PMT descriptor, carried verbatim so language/registration/etc. survive the
480/// round-trip without a per-descriptor parser.
481#[serde_as]
482#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
483#[serde(rename_all = "camelCase")]
484pub struct Descriptor {
485	/// The descriptor tag (e.g. 0x05 registration, 0x0A ISO-639 language).
486	pub tag: u8,
487	/// The descriptor body, base64-encoded in the catalog.
488	#[serde_as(as = "Base64")]
489	pub data: Bytes,
490}
491
492/// The application catalog extension carrying the `mpegts` section. Empty by
493/// default, so the section is omitted until an MPEG-TS detail is recorded.
494#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
495#[non_exhaustive]
496pub struct Ext {
497	#[serde(default, skip_serializing_if = "Mpegts::is_empty")]
498	/// MPEG-TS program, stream, and descriptor metadata.
499	pub mpegts: Mpegts,
500}
501
502impl CatalogExt for Ext {}
503
504/// An extension that can carry an `mpegts` catalog section.
505///
506/// Implement this for an application extension to compose MPEG-TS carriage with
507/// additional sections.
508pub trait Catalog: CatalogExt {
509	/// The section to record MPEG-TS details into, or `None` for an extension that
510	/// doesn't carry them.
511	///
512	/// Keep this stable per catalog: an importer samples support once at
513	/// construction, so a result that flips between `Some` and `None` mid-stream
514	/// would disable verbatim carriage or fail.
515	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
524// The untyped passthrough carries no typed mpegts section (a TS importer driving an `Extra`
525// catalog records verbatim streams as raw JSON sections, not the typed `Mpegts` view).
526impl 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		// The rate is the only field of a media-only CBR source, so it must keep the
545		// section alive rather than be dropped with it.
546		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		// An absent rate is omitted, never `null`.
554		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		// `randomAccess` is always written, and read as false when absent.
575		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	/// A track is carried whole or demultiplexed, never both, while the two lanes of one source can
584	/// share the section.
585	#[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		// A media track: PID + a language descriptor, no verbatim carriage.
607		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		// A verbatim SCTE-35 track.
620		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		// A whole-PES private data track.
630		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		// Descriptor bytes are base64 ("CUEI" -> "Q1VFSQ==").
647		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		// Both keys are decimal strings, since JSON object keys are strings.
684		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		// Lock in the interval's wire shape: a bare integer number of milliseconds.
691		// Without the `DurationMilliSeconds` adapter this regresses to serde's default
692		// `{secs, nanos}` object.
693		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		// The `mpegts` section moq-cli 0.11.0 publishes for an ffmpeg TS with an SDT:
702		// the sections inline under the PID, no `table_id` level. Every published CLI
703		// through 0.11 writes this, so a consumer that refuses it drops SRT/TS export
704		// for every one of them.
705		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		// The one SDT section keys itself by its table_id (0x42), carries its bytes
718		// inline, keeps the PID's interval, and names no track.
719		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		// Two tables on one PID split into two entries, and a PID without an
727		// interval falls back to the DVB maximum for each table it carries.
728		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		// The inline form never comes back out: an entry carrying sections names
738		// no track, so serialization fails rather than emit a dangling reference.
739		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		// A catalog mixing the legacy inline form with a track-backed entry still
745		// writes the track-backed half; only the entry naming no track is refused.
746		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	/// Draft -00's PES framing, named or implied by an absent `framing`, is refused rather than
777	/// read as a section: its frames are bare PES payloads, which nothing can re-emit faithfully.
778	#[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		// `sections` alongside any other key would silently drop the new-form
798		// entries: the inline reader ignores unknown keys without this.
799		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	/// The `mpegts` section is not hang-only: the same JSON rides the MSF catalog track, so a
807	/// broadcast demuxed from MPEG-TS can be re-muxed from either catalog.
808	#[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}