Skip to main content

moq_mux/container/ts/
passthrough.rs

1//! Carrying a transport stream whole, without demultiplexing it.
2
3use std::collections::{BTreeMap, HashMap, VecDeque};
4
5use bytes::BytesMut;
6use mpeg2ts::ts::{Pid, TsPacket};
7
8use super::import::{Framer, PatReader, SectionReassembler, adaptation_valid, discontinuity_indicator, pcr};
9use super::mux_rate::{Meter, PCR_WRAP};
10use super::psi::{self, Pmt};
11
12/// The PCR clock, in Hz.
13pub(super) const PCR_HZ: u64 = 27_000_000;
14
15/// The longest a group runs without a random access point before a PCR starts the next, in
16/// PCR ticks: one second.
17const FALLBACK_TICKS: u64 = PCR_HZ;
18
19/// PCR ticks in a microsecond, the unit of an object's timestamp.
20const TICKS_PER_MICRO: u64 = PCR_HZ / 1_000_000;
21
22/// The longest unflagged step forward taken as elapsed time, in PCR ticks: the media-aware
23/// import's [`LEAP`](super::step::LEAP).
24const LEAP_TICKS: u64 = super::step::LEAP.as_micros() as u64 * TICKS_PER_MICRO;
25
26/// The most bytes a group holds before its next object starts another, so a source with sparse
27/// random access points still gives a joiner a group it can take whole.
28pub(super) const GROUP_BYTES_MAX: u64 = 16 * 1024 * 1024;
29
30/// The most objects a group holds before its next object starts another, which a source stamping
31/// PCRs far more often than the 40 ms norm could otherwise grow without a boundary.
32pub(super) const GROUP_OBJECTS_MAX: usize = 4096;
33
34/// The bytes a PCR sits into its packet: four of header, the adaptation field's length and flags,
35/// and the five bytes the 33-bit base ends in.
36pub(super) const PCR_OFFSET: u64 = 10;
37
38/// The packet sizes a sync byte can recur at: 188, BDAV's 192, and 204 with Reed-Solomon parity.
39const PACKET_SIZES: [usize; 3] = [TsPacket::SIZE, 192, 204];
40
41/// The sync bytes in a row, at one stride, that settle the packet size: payload rarely fakes that.
42const SYNC_RUN: usize = 4;
43
44/// The bytes from a candidate first sync byte to the last one a run of the widest stride needs.
45const SYNC_WINDOW: usize = 204 * (SYNC_RUN - 1) + 1;
46
47/// The stream types a PMT declares video with. A video stream carried under a private stream
48/// type (0x06 with a registration descriptor) is not recognized, and its program groups on the
49/// clock PID's random access points instead.
50const VIDEO_STREAM_TYPES: &[u8] = &[
51	0x01, // MPEG-1 video
52	0x02, // MPEG-2 video
53	0x10, // MPEG-4 part 2
54	0x1B, // H.264
55	0x1F, // H.264 SVC sub-bitstream
56	0x20, // H.264 MVC sub-bitstream
57	0x24, // H.265
58	0x33, // H.266
59	0x42, // AVS
60	0xD1, // Dirac
61	0xEA, // VC-1
62];
63
64/// Publishes a transport stream verbatim, as one track of whole 188-byte packets.
65///
66/// Every packet goes out in input order, on the track the catalog's `mpegts` section names in
67/// [`passthrough`](super::Mpegts::passthrough), with the multiplex rate in its
68/// [`mux_rate`](super::Mpegts::mux_rate). It reads the PAT and PMT to find the program clock and
69/// the video stream, and reads nothing else past an adaptation field, so a scrambled multiplex
70/// groups and paces exactly like its clear twin.
71///
72/// # Objects and groups
73///
74/// An object runs from one PCR packet on the clock PID to the next, and is also cut wherever a
75/// group starts. A group starts at:
76///
77/// - a packet with `random_access_indicator` on the video PID, or on the clock PID when the
78///   program has no video;
79/// - a PCR that breaks the count (see Timestamps): one with `discontinuity_indicator`, or a
80///   step not taken as elapsed time, since no group may hold a PCR discontinuity;
81/// - the first PCR at least one second after the group's start, for a source that never marks
82///   random access;
83/// - the first object that would take the group past half of what `moq-net` caches of one group,
84///   in bytes or in frames, so a long GOP cannot outgrow what a relay caches. Objects are never
85///   split to meet the bound.
86///
87/// Only the first of these makes a group a random access point, so any other start publishes
88/// [`random_access`](super::PassthroughTrack::random_access) false from then on, as does any group
89/// carried while the layout allows no random access (more than one program or video stream). A
90/// group the PCR discontinuity starts is behind a break even when it is also a random access
91/// point.
92///
93/// Bytes before the first group are dropped: until the PMT, a PCR, and a group start have all
94/// been seen there is no group to put them in. The track is byte-identical to the input from its
95/// first group on, and only from there. Bytes off the 188-byte packet grid are dropped too.
96///
97/// # Timestamps
98///
99/// An object's timestamp is the PCR time of its first byte, interpolated at the rate between the
100/// PCRs either side of it, floored to microseconds. A PCR stamps the byte holding the last bit of
101/// its base, ten bytes into its packet, so even an object that starts at a PCR packet sits ten
102/// bytes of that rate before its own PCR.
103///
104/// Every timestamp is then shifted onto the catalog's [`Clock`](crate::Clock) by one offset, fixed
105/// through the reservation's [`Timebase`](crate::catalog::Timebase) by the first object: zero when
106/// that object places the clock, and otherwise whatever lands it at now on a clock already in use.
107///
108/// PCRs are unwrapped into a 64-bit count of 27 MHz ticks that never goes back. A step forward of
109/// at most half the 2^33 * 300 tick period adds to the count, across the wrap included, unless it
110/// is more than 10 s without `discontinuity_indicator`. A PCR with the flag whose step is forward
111/// adds the step too. Every other step, back with or without the flag or that unflagged leap, is
112/// another timeline, such as a switch between two encoders whose clocks were never locked, and is
113/// spliced: the count carries on from the time the rate before the PCR gives it. Either way the
114/// bytes before it are timed at the rate before it, and the next group starts behind a break
115/// marker. The bytes still go out verbatim, so a decoder downstream sees the step as the source
116/// sent it. The timeline therefore depends only on the bytes since the importer's
117/// first PCR and its shift, and two importers of one feed started at the same packet each placing
118/// its own catalog's clock publish identical objects.
119///
120/// The catalog's extension must carry the `mpegts` section ([`Catalog`](super::Catalog)), such as
121/// [`Ext`](super::Ext): [`new`](Self::new) refuses one that does not.
122pub struct Passthrough<E: super::Catalog = super::Ext> {
123	catalog: crate::catalog::Producer<E>,
124	/// Held until the first group is written, so the first catalog already names the track with
125	/// its final `randomAccess`.
126	reservation: Option<crate::catalog::Reserved<E>>,
127	/// Shifts every object's PCR time onto the catalog clock, anchored by the first object.
128	shift: crate::catalog::Timebase<E>,
129	media: crate::container::Producer<crate::catalog::hang::Wire>,
130	/// The section as last written to the catalog, `None` before the first group.
131	section: Option<Section<E>>,
132
133	scratch: Vec<u8>,
134	framer: Framer,
135	/// Set once the packet size has been confirmed as 188.
136	sized: bool,
137	/// Bytes of whole packets seen so far: the position every PCR and object is placed at.
138	offset: u64,
139
140	pat: PatReader,
141	crc_errors: u64,
142	/// The programs the PAT lists, in PAT order, without the network PID.
143	programs: Vec<psi::Association>,
144	pmt_sections: HashMap<Pid, SectionReassembler>,
145	/// Each listed program's clock and video PIDs, once its PMT has been read.
146	pmts: BTreeMap<u16, Program>,
147	/// The PCR PID given by [`with_pcr_pid`](Self::with_pcr_pid), overriding the PMT's.
148	pcr_override: Option<u16>,
149	/// The PID pacing the multiplex.
150	pcr_pid: Option<u16>,
151	/// The PID whose `random_access_indicator` starts a group.
152	access_pid: Option<u16>,
153	/// Whether the layout allows random access at all: one program, at most one video PID, and
154	/// that program's own clock.
155	single: bool,
156	/// Whether the PMT of the clock's program has been read.
157	mapped: bool,
158
159	timing: Clock,
160	/// A `discontinuity_indicator` on the clock PID, waiting for the PCR that it flags (normally
161	/// in the same packet).
162	pending_break: bool,
163	/// The PCR time of the last object written, which no later one goes below.
164	written: u64,
165
166	groups: Groups,
167	/// Whether every group so far started at a random access point, and the layout allowed random
168	/// access throughout.
169	all_random_access: bool,
170
171	mux_rate: Meter,
172}
173
174/// Owns the passthrough's catalog entry once written, removing it however the track ends, as the
175/// demultiplexed lane's catalog entries are.
176struct Section<E: super::Catalog> {
177	catalog: crate::catalog::Producer<E>,
178	written: Written,
179}
180
181/// What a passthrough last wrote into the `mpegts` section.
182#[derive(Clone, PartialEq)]
183struct Written {
184	track: super::PassthroughTrack,
185	mux_rate: Option<u64>,
186}
187
188/// A passthrough that [finished](Passthrough::finish): its track has ended, and it can still be
189/// read or aborted, but it takes no more input.
190///
191/// Dropping it releases the track and removes it from the catalog's `mpegts` section.
192///
193/// ```compile_fail,E0599
194/// # fn cannot_decode(mut passthrough: moq_mux::container::ts::passthrough::Finished) {
195/// passthrough.decode(b"").unwrap();
196/// # }
197/// ```
198#[must_use = "dropping it releases the track and its catalog section"]
199pub struct Finished<E: super::Catalog = super::Ext> {
200	passthrough: Passthrough<E>,
201}
202
203impl<E: super::Catalog> Finished<E> {
204	/// The name of the track carrying the packets.
205	pub fn track(&self) -> &str {
206		self.passthrough.track()
207	}
208
209	/// Abort the track with `err`; see [`Passthrough::abort`]. Readers still draining get the clean end
210	/// instead once every group below the end finished.
211	pub fn abort(self, err: moq_net::Error) {
212		self.passthrough.abort(err);
213	}
214}
215
216impl<E: super::Catalog> Drop for Section<E> {
217	fn drop(&mut self) {
218		// A closed catalog has nothing left to remove it from. The rate stays: it is the
219		// multiplex's, which a demultiplexing importer of the same source may also write, and
220		// that importer leaves it in place when it ends too.
221		if let Ok(mut catalog) = self.catalog.edit() {
222			if let Some(mpegts) = catalog.ext.mpegts_mut() {
223				mpegts.passthrough = None;
224			}
225			let _ = catalog.commit();
226		}
227	}
228}
229
230#[derive(Default)]
231struct Program {
232	pcr_pid: Option<u16>,
233	video: Vec<u16>,
234}
235
236/// The clock pacing the multiplex.
237enum Clock {
238	/// No PCR yet: nothing can be timed, so no object opens.
239	Unseen,
240	Seen {
241		timebase: Timebase,
242		/// The object being filled, from its first packet.
243		open: Option<Object>,
244		/// Closed objects waiting on the next PCR for their timestamps.
245		queue: VecDeque<Object>,
246	},
247}
248
249/// The groups written so far.
250enum Groups {
251	/// Before the first group: the PCR time the importer started waiting for a group start at,
252	/// once the clock's program is mapped and a PCR seen.
253	Waiting(Option<u64>),
254	/// The group being written.
255	Writing(Group),
256}
257
258/// The PCRs since the importer's first, or since the last break.
259struct Timebase {
260	/// The last PCR, raw.
261	raw: u64,
262	/// The last few PCRs, newest last: enough to time every object since the one before last.
263	samples: VecDeque<Sample>,
264}
265
266#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267pub(super) struct Sample {
268	/// Where the PCR's byte sits in the input.
269	pub(super) at: u64,
270	/// The unwrapped PCR, in 27 MHz ticks.
271	pub(super) ticks: u64,
272}
273
274struct Object {
275	/// Where the object's first byte sits in the input.
276	at: u64,
277	payload: BytesMut,
278	/// Why this object starts a group, if it does.
279	start: Option<Start>,
280	/// Whether a flagged PCR jump comes before this object, which the track marks with a break
281	/// whatever else starts its group.
282	discontinuity: bool,
283}
284
285#[derive(Clone, Copy, Debug, PartialEq, Eq)]
286enum Start {
287	RandomAccess,
288	Discontinuity,
289	Fallback,
290	/// The group before would have outgrown [`GROUP_BYTES_MAX`] or [`GROUP_OBJECTS_MAX`].
291	Full,
292}
293
294struct Group {
295	/// The PCR time of the group's first byte.
296	ticks: u64,
297	bytes: u64,
298	objects: usize,
299}
300
301impl<E: super::Catalog> Passthrough<E> {
302	/// A passthrough importer publishing one track on `broadcast`, listed in the catalog behind
303	/// `reserved`.
304	///
305	/// Fails with [`NoMpegtsSection`](crate::Error::NoMpegtsSection) when the catalog's extension
306	/// carries no `mpegts` section to list the track in.
307	pub fn new(broadcast: moq_net::broadcast::Producer, reserved: crate::catalog::Reserved<E>) -> crate::Result<Self> {
308		let catalog = reserved.producer();
309		let mut snapshot = catalog.snapshot();
310		let Some(mpegts) = snapshot.ext.mpegts_mut() else {
311			return Err(crate::Error::NoMpegtsSection);
312		};
313		// A rate the catalog already records measured this multiplex; the meter confirms,
314		// replaces, or clears it.
315		let measured = mpegts.mux_rate;
316		catalog.count_ext_tracks(|ext: &mut E| ext.mpegts_mut().is_some_and(|mpegts| mpegts.has_track()));
317		let track = broadcast.unique_track(".m2ts", catalog.track_info(hang::catalog::PRIORITY.video));
318		let media = catalog.media_raw(track, crate::catalog::hang::Wire::legacy(crate::container::Kind::Data))?;
319		Ok(Self {
320			shift: catalog.timebase(),
321			catalog,
322			reservation: Some(reserved),
323			media,
324			section: None,
325			scratch: Vec::new(),
326			framer: Framer::default(),
327			sized: false,
328			offset: 0,
329			pat: PatReader::default(),
330			crc_errors: 0,
331			programs: Vec::new(),
332			pmt_sections: HashMap::new(),
333			pmts: BTreeMap::new(),
334			pcr_override: None,
335			pcr_pid: None,
336			access_pid: None,
337			single: false,
338			mapped: false,
339			timing: Clock::Unseen,
340			pending_break: false,
341			written: 0,
342			groups: Groups::Waiting(None),
343			all_random_access: true,
344			mux_rate: Meter::measured(measured),
345		})
346	}
347
348	/// Shift the multiplex's timestamps through `timebase`, a timestamp base of the catalog
349	/// `reserved` belongs to, instead of a fresh one: importers of one source share its offset.
350	///
351	/// Set it before the first [`decode`](Self::decode), which may anchor the timebase.
352	pub fn with_timebase(mut self, timebase: crate::catalog::Timebase<E>) -> Self {
353		self.shift = timebase;
354		self
355	}
356
357	/// Pace the multiplex on `pid` rather than on the `PCR_PID` of the PAT's first program.
358	///
359	/// Groups then start at random access points of the video stream of the first program whose
360	/// PMT names `pid` as its clock. When no program does, they start at `pid`'s own random access
361	/// points, which mark no program's decoding boundary, so the track never claims random access.
362	pub fn with_pcr_pid(mut self, pid: u16) -> Self {
363		self.pcr_override = Some(pid);
364		self.pcr_pid = Some(pid);
365		self
366	}
367
368	/// The name of the track carrying the packets.
369	pub fn track(&self) -> &str {
370		self.media.name()
371	}
372
373	/// Append `data` and publish every whole packet it completes. A trailing partial packet is
374	/// kept for the next call.
375	pub fn decode(&mut self, data: &[u8]) -> crate::Result<()> {
376		self.scratch.extend_from_slice(data);
377		if !self.sized {
378			self.probe_packet_size(false)?;
379		}
380		self.packets()
381	}
382
383	/// Publish what is left at the end of the input, close the track, and return the
384	/// [`Finished`] passthrough.
385	///
386	/// No later PCR will arrive, so the objects since the last one are timed at the rate of the
387	/// interval before it. The catalog keeps listing the track until the [`Finished`] passthrough
388	/// drops.
389	///
390	/// A finish that fails ends the track with an error, so it can't be retried.
391	pub fn finish(mut self) -> crate::Result<Finished<E>> {
392		if let Err(err) = self.end() {
393			// The objects already written stay readable, then subscribers get an error.
394			let _ = self.media.end_with(Some(err.reason()));
395			return Err(err);
396		}
397		Ok(Finished { passthrough: self })
398	}
399
400	/// Publish the rest of the input and finish the track, stopping at the first failure.
401	fn end(&mut self) -> crate::Result<()> {
402		if !self.sized {
403			self.probe_packet_size(true)?;
404			self.packets()?;
405		}
406		self.close_object();
407		self.drain_queue()?;
408		self.reservation = None;
409		self.media.end_with(None)?;
410		Ok(())
411	}
412
413	/// Abort the track with `err` instead of finishing, so subscribers see the real cause rather
414	/// than [`moq_net::Error::Dropped`]. Consumes the importer.
415	pub fn abort(self, err: moq_net::Error) {
416		let Self { media, section, .. } = self;
417		media.abort(err);
418		drop(section);
419	}
420
421	/// Publish every whole packet in the scratch buffer, once the packet size is settled.
422	fn packets(&mut self) -> crate::Result<()> {
423		if !self.sized {
424			return Ok(());
425		}
426		let mut off = 0;
427		while let Some(at) = self.framer.next(&self.scratch, &mut off) {
428			let pkt: [u8; TsPacket::SIZE] = self.scratch[at..at + TsPacket::SIZE].try_into().unwrap();
429			self.packet(&pkt)?;
430		}
431		self.scratch.drain(..off);
432		Ok(())
433	}
434
435	/// Settle the packet size before the 188-byte framer can lock onto a false grid, refusing a
436	/// 192- or 204-byte source, and drop the bytes before the first sync byte of the grid.
437	///
438	/// Each offset is tried, in order, once the bytes a run of every stride needs from it have
439	/// arrived, so where the grid is found does not depend on how the input was chunked. At the
440	/// end of the input a shorter run settles the offsets left, so a stream too short for a full
441	/// run still publishes.
442	fn probe_packet_size(&mut self, eof: bool) -> crate::Result<()> {
443		let scratch = &self.scratch;
444		let syncs = |k: usize, size: usize, run: usize| (0..run).all(|i| scratch.get(k + i * size) == Some(&0x47));
445		let checkable = (scratch.len() + 1).saturating_sub(SYNC_WINDOW);
446
447		let mut found = (0..checkable).find_map(|k| {
448			PACKET_SIZES
449				.iter()
450				.find(|&&size| syncs(k, size, SYNC_RUN))
451				.map(|&size| (k, size))
452		});
453		if found.is_none() && eof {
454			// Every sync byte at the stride that still fits in what is left.
455			let fits = |k: usize, size: usize| (scratch.len() - k).div_ceil(size);
456			found = (checkable..scratch.len())
457				.filter(|&k| scratch.len() - k >= TsPacket::SIZE)
458				.find_map(|k| {
459					PACKET_SIZES
460						.iter()
461						.find(|&&size| {
462							fits(k, size) >= 2 - usize::from(size == TsPacket::SIZE) && syncs(k, size, fits(k, size))
463						})
464						.map(|&size| (k, size))
465				});
466		}
467
468		match found {
469			Some((k, TsPacket::SIZE)) => {
470				self.scratch.drain(..k);
471				self.sized = true;
472			}
473			Some((_, size)) => return Err(crate::Error::TsPacketSize(size)),
474			// No grid starts at any offset tried: leading junk.
475			None => {
476				self.scratch.drain(..checkable);
477			}
478		}
479		Ok(())
480	}
481
482	fn packet(&mut self, pkt: &[u8; TsPacket::SIZE]) -> crate::Result<()> {
483		let at = self.offset;
484		self.offset += TsPacket::SIZE as u64;
485		let pid = u16::from_be_bytes([pkt[1] & 0x1f, pkt[2]]);
486
487		if pid == Pid::PAT {
488			self.pat_packet(pkt)?;
489		} else if let Ok(pmt_pid) = Pid::new(pid)
490			&& self.pmt_sections.contains_key(&pmt_pid)
491		{
492			self.pmt_packet(pmt_pid, pkt)?;
493		}
494
495		// A packet the demodulator flagged corrupt, or whose adaptation field overruns it, is
496		// carried like any other, but nothing is read from it.
497		let readable = pkt[1] & 0x80 == 0 && adaptation_valid(pkt);
498		let mut start = None;
499		let mut clock = false;
500		let mut discontinuity = false;
501		if readable && self.pcr_pid == Some(pid) {
502			if discontinuity_indicator(pkt) {
503				self.pending_break = true;
504			}
505			if let Some(raw) = pcr(pkt) {
506				clock = true;
507				start = self.clock(raw, at)?;
508				discontinuity = start == Some(Start::Discontinuity);
509			}
510		}
511		if readable && self.access_pid == Some(pid) && random_access_indicator(pkt) && self.can_start() {
512			start = Some(Start::RandomAccess);
513		}
514
515		let opens = start.is_some() || (clock && self.started());
516		let Clock::Seen { open, queue, .. } = &mut self.timing else {
517			return Ok(());
518		};
519		if opens {
520			// A PCR packet already closed the object before it.
521			if !clock && let Some(object) = open.take() {
522				queue.push_back(object);
523			}
524			let mut payload = BytesMut::with_capacity(TsPacket::SIZE * 8);
525			payload.extend_from_slice(pkt);
526			*open = Some(Object {
527				at,
528				payload,
529				start,
530				discontinuity,
531			});
532		} else if let Some(open) = open.as_mut() {
533			open.payload.extend_from_slice(pkt);
534		}
535
536		let waiting = open.as_ref().map_or(0, |open| open.payload.len() as u64)
537			+ queue.iter().map(|object| object.payload.len() as u64).sum::<u64>();
538		if waiting > GROUP_BYTES_MAX {
539			return Err(crate::Error::PcrGap {
540				pid: self.pcr_pid.unwrap_or_default(),
541				bytes: waiting,
542			});
543		}
544		Ok(())
545	}
546
547	/// A PCR at `at` on the clock PID: close the object it ends, time everything waiting on it,
548	/// and say whether its packet starts a group.
549	fn clock(&mut self, raw: u64, at: u64) -> crate::Result<Option<Start>> {
550		let at = at + PCR_OFFSET;
551		self.close_object();
552		let flagged = std::mem::take(&mut self.pending_break);
553
554		let Clock::Seen { timebase, .. } = &mut self.timing else {
555			// The first PCR starts the count at its own value.
556			self.timing = Clock::Seen {
557				timebase: Timebase {
558					raw,
559					samples: VecDeque::from([Sample { at, ticks: raw }]),
560				},
561				open: None,
562				queue: VecDeque::new(),
563			};
564			if let Groups::Waiting(since) = &mut self.groups {
565				*since = self.mapped.then_some(raw);
566			}
567			if self.mux_rate.pcr(raw, self.offset / TsPacket::SIZE as u64) {
568				self.record()?;
569			}
570			return Ok(None);
571		};
572
573		// A retransmitted break (the same flagged PCR again) declares nothing new.
574		let flagged = flagged && !(timebase.samples.len() == 1 && timebase.raw == raw);
575		let step = (raw + PCR_WRAP - timebase.raw) % PCR_WRAP;
576		let last = timebase.samples.back().expect("a timebase has a sample").ticks;
577		// A step back, or one forward too far to be elapsed time, is another timeline: the
578		// count carries on from where the rate before it puts this PCR, ignoring the step.
579		let spliced = (step > PCR_WRAP / 2 || (!flagged && step > LEAP_TICKS)).then(|| locate(at, &timebase.samples));
580
581		if flagged || spliced.is_some() {
582			// No PCR on the old side is coming: what waits on one is timed by the rate before it,
583			// and the new side carries on from there.
584			self.drain_queue()?;
585			let ticks = spliced.unwrap_or(last + step).max(self.written);
586			// The object before was closed and the queue drained, so both start empty.
587			self.timing = Clock::Seen {
588				timebase: Timebase {
589					raw,
590					samples: VecDeque::from([Sample { at, ticks }]),
591				},
592				open: None,
593				queue: VecDeque::new(),
594			};
595			if self.mux_rate.discontinuity() {
596				self.record()?;
597			}
598			if self.mux_rate.pcr(raw, self.offset / TsPacket::SIZE as u64) {
599				self.record()?;
600			}
601			// The jump is not elapsed time, so the wait for the first group starts over.
602			if let Groups::Waiting(Some(since)) = &mut self.groups {
603				*since = ticks;
604			}
605			return Ok(self.started().then_some(Start::Discontinuity));
606		}
607
608		let ticks = last + step;
609		timebase.raw = raw;
610		timebase.samples.push_back(Sample { at, ticks });
611		if timebase.samples.len() > 3 {
612			timebase.samples.pop_front();
613		}
614		self.drain_queue()?;
615		if self.mux_rate.pcr(raw, self.offset / TsPacket::SIZE as u64) {
616			self.record()?;
617		}
618
619		let since = match &mut self.groups {
620			Groups::Writing(group) => Some(group.ticks),
621			Groups::Waiting(since) if self.mapped => Some(*since.get_or_insert(ticks)),
622			Groups::Waiting(_) => None,
623		};
624		Ok(since
625			.filter(|since| ticks.saturating_sub(*since) >= FALLBACK_TICKS && self.can_start())
626			.map(|_| Start::Fallback))
627	}
628
629	/// Whether a group may start here: once the first one has, always; before it, only once the
630	/// clock's program is mapped and a PCR has been seen.
631	fn can_start(&self) -> bool {
632		self.started() || (self.mapped && matches!(self.timing, Clock::Seen { .. }))
633	}
634
635	/// Whether the first group has started, written or still waiting on its timestamp.
636	fn started(&self) -> bool {
637		matches!(self.groups, Groups::Writing(_))
638			|| matches!(&self.timing, Clock::Seen { open, queue, .. } if open.is_some() || !queue.is_empty())
639	}
640
641	fn close_object(&mut self) {
642		if let Clock::Seen { open, queue, .. } = &mut self.timing
643			&& let Some(object) = open.take()
644		{
645			queue.push_back(object);
646		}
647	}
648
649	/// Time and write every waiting object against the current timebase.
650	fn drain_queue(&mut self) -> crate::Result<()> {
651		loop {
652			let Clock::Seen { timebase, queue, .. } = &mut self.timing else {
653				return Ok(());
654			};
655			let Some(object) = queue.pop_front() else {
656				return Ok(());
657			};
658			let ticks = locate(object.at, &timebase.samples);
659			self.write(object, ticks)?;
660		}
661	}
662
663	fn write(&mut self, object: Object, ticks: u64) -> crate::Result<()> {
664		// Extrapolating past the last PCR before a break can overshoot where the count resumes.
665		let mut ticks = ticks.max(self.written);
666		if object.discontinuity
667			&& let Groups::Writing(group) = &self.groups
668		{
669			// The break's marker sits on the last object's microsecond, or the one past the newest
670			// group's start when that is later, and the group behind it has to start past the
671			// marker. A splice can resume on either, as after a PCR repeated or a one-PCR timebase,
672			// neither of which gives a rate.
673			let past_object = (self.written / TICKS_PER_MICRO + 1) * TICKS_PER_MICRO;
674			let past_group = (group.ticks / TICKS_PER_MICRO + 2) * TICKS_PER_MICRO;
675			ticks = ticks.max(past_object).max(past_group);
676		}
677		self.written = ticks;
678		let timestamp = moq_net::Timestamp::from_micros(ticks / TICKS_PER_MICRO)?;
679		// The first object, which starts a group, anchors the shift and is live on arrival.
680		let timestamp = self.shift.shift(timestamp)?;
681		let size = object.payload.len() as u64;
682		let start = match (object.start, &mut self.groups) {
683			(Some(start), _) => Some(start),
684			(None, Groups::Writing(group)) => {
685				if group.bytes + size > GROUP_BYTES_MAX || group.objects >= GROUP_OBJECTS_MAX {
686					Some(Start::Full)
687				} else {
688					group.bytes += size;
689					group.objects += 1;
690					None
691				}
692			}
693			// Only an object that starts a group opens before the first one.
694			(None, Groups::Waiting(_)) => Some(Start::Fallback),
695		};
696
697		if let Some(start) = start {
698			if object.discontinuity && matches!(self.groups, Groups::Writing(_)) {
699				self.media.discontinuity()?;
700			}
701			if start != Start::RandomAccess || !self.single {
702				self.all_random_access = false;
703			}
704			self.groups = Groups::Writing(Group {
705				ticks,
706				bytes: size,
707				objects: 1,
708			});
709		}
710		self.media.write(crate::container::Frame {
711			timestamp,
712			decode: None,
713			duration: None,
714			payload: object.payload.freeze(),
715			keyframe: start.is_some(),
716		})?;
717		if start.is_some() {
718			self.record()?;
719			self.reservation = None;
720		}
721		Ok(())
722	}
723
724	/// Write the track and rate to the catalog if they changed. Nothing is written before the first
725	/// group.
726	fn record(&mut self) -> crate::Result<()> {
727		if matches!(self.groups, Groups::Waiting(_)) && self.section.is_none() {
728			return Ok(());
729		}
730		let mut track = super::PassthroughTrack::new(self.media.name());
731		track.random_access = self.single && self.all_random_access;
732		let written = Written {
733			track,
734			mux_rate: self.mux_rate.published(),
735		};
736		if self.section.as_ref().is_some_and(|section| section.written == written) {
737			return Ok(());
738		}
739		// The demultiplexing lane of the same source may record the rate too, so write it only
740		// when this meter's own value changes: one that has measured nothing leaves it alone.
741		let rate_changed = self.section.as_ref().and_then(|section| section.written.mux_rate) != written.mux_rate;
742		let update = written.clone();
743		{
744			let mut catalog = self.catalog.edit()?;
745			// `new` checked the section exists, and an extension keeps it for its life.
746			if let Some(mpegts) = catalog.ext.mpegts_mut() {
747				mpegts.passthrough = Some(update.track);
748				if rate_changed {
749					mpegts.mux_rate = update.mux_rate;
750				}
751			}
752			catalog.commit()?;
753		}
754		match &mut self.section {
755			Some(section) => section.written = written,
756			None => {
757				self.section = Some(Section {
758					catalog: self.catalog.clone(),
759					written,
760				})
761			}
762		}
763		Ok(())
764	}
765
766	fn pat_packet(&mut self, pkt: &[u8; TsPacket::SIZE]) -> crate::Result<()> {
767		let Some(pat) = self.pat.push(pkt, &mut self.crc_errors) else {
768			return Ok(());
769		};
770		let programs: Vec<_> = pat
771			.programs
772			.into_iter()
773			.filter(|program| program.program_number != 0)
774			.collect();
775		if programs == self.programs {
776			return Ok(());
777		}
778		self.pmt_sections
779			.retain(|pid, _| programs.iter().any(|program| program.pmt_pid == *pid));
780		for program in &programs {
781			self.pmt_sections.entry(program.pmt_pid).or_default();
782		}
783		self.pmts
784			.retain(|number, _| programs.iter().any(|program| program.program_number == *number));
785		self.programs = programs;
786		self.remap()
787	}
788
789	fn pmt_packet(&mut self, pid: Pid, pkt: &[u8; TsPacket::SIZE]) -> crate::Result<()> {
790		let mut sections = Vec::new();
791		self.pmt_sections.entry(pid).or_default().push(pkt, &mut sections);
792		let mut changed = false;
793		for section in sections {
794			if section.first() != Some(&psi::PMT_TABLE_ID) || !psi::crc_ok(&section) {
795				continue;
796			}
797			let Some(pmt) = Pmt::parse(&section) else {
798				continue;
799			};
800			let listed = self
801				.programs
802				.iter()
803				.any(|program| program.program_number == pmt.program_number && program.pmt_pid == pid);
804			if !listed {
805				continue;
806			}
807			let program = Program {
808				pcr_pid: pmt.pcr_pid.map(|pid| pid.as_u16()),
809				video: pmt
810					.streams
811					.iter()
812					.filter(|es| VIDEO_STREAM_TYPES.contains(&es.stream_type))
813					.map(|es| es.pid.as_u16())
814					.collect(),
815			};
816			let known = self.pmts.get(&pmt.program_number);
817			if known.is_none_or(|known| known.pcr_pid != program.pcr_pid || known.video != program.video) {
818				self.pmts.insert(pmt.program_number, program);
819				changed = true;
820			}
821		}
822		if changed {
823			self.remap()?;
824		}
825		Ok(())
826	}
827
828	/// The PAT or a PMT changed: find the clock, the PID that marks random access, and whether
829	/// the layout allows random access at all.
830	fn remap(&mut self) -> crate::Result<()> {
831		let clock = match self.pcr_override {
832			Some(pid) => self
833				.programs
834				.iter()
835				.find(|program| {
836					self.pmts
837						.get(&program.program_number)
838						.is_some_and(|pmt| pmt.pcr_pid == Some(pid))
839				})
840				.or(self.programs.first()),
841			None => self.programs.first(),
842		};
843		let pmt = clock.and_then(|program| self.pmts.get(&program.program_number));
844
845		let pcr_pid = self.pcr_override.or(pmt.and_then(|pmt| pmt.pcr_pid));
846		// Whether the clock is the mapped program's own. An overriding clock no program names
847		// marks its own random access points, which are no program's decoding boundary.
848		let owned = pmt.is_some_and(|pmt| pmt.pcr_pid == pcr_pid);
849		let access_pid = match pmt {
850			Some(pmt) if owned => pmt.video.first().copied().or(pcr_pid),
851			_ => pcr_pid,
852		};
853		let mapped = pmt.is_some();
854		let single = self.programs.len() == 1 && owned && pmt.is_some_and(|pmt| pmt.video.len() <= 1);
855
856		if pcr_pid != self.pcr_pid {
857			// A new clock PID is a new clock: its next PCR is taken as flagged.
858			if self.pcr_pid.is_some() {
859				self.pending_break = true;
860			}
861			self.pcr_pid = pcr_pid;
862		}
863		self.access_pid = access_pid;
864		self.mapped = mapped;
865		self.single = single;
866		// The group in progress now carries what no random access point covers, and it stays cached.
867		if !single && self.started() {
868			self.all_random_access = false;
869		}
870		self.record()
871	}
872}
873
874/// Whether a packet's adaptation field sets `random_access_indicator`.
875fn random_access_indicator(pkt: &[u8; TsPacket::SIZE]) -> bool {
876	pkt[3] & 0x20 != 0 && pkt[4] > 0 && pkt[5] & 0x40 != 0
877}
878
879/// The PCR time of the byte at `at`, from the PCRs of its timebase.
880///
881/// Interpolated between the two PCRs either side of it; extrapolated at the rate of the nearest
882/// interval when it lies before the timebase's first PCR or after its last. With a single PCR
883/// there is no rate, and the byte takes that PCR's time.
884pub(super) fn locate(at: u64, samples: &VecDeque<Sample>) -> u64 {
885	let (first, last) = (samples[0], samples[samples.len() - 1]);
886	let (a, b) = match samples.iter().zip(samples.iter().skip(1)).find(|(_, b)| at < b.at) {
887		Some((a, b)) => (*a, *b),
888		None if samples.len() >= 2 => (samples[samples.len() - 2], last),
889		None => return last.ticks,
890	};
891	let span = u128::from(b.at - a.at);
892	let ticks = u128::from(b.ticks - a.ticks);
893	if at >= a.at {
894		a.ticks + (u128::from(at - a.at) * ticks / span) as u64
895	} else {
896		debug_assert_eq!(a.at, first.at);
897		a.ticks
898			.saturating_sub((u128::from(a.at - at) * ticks).div_ceil(span) as u64)
899	}
900}