use alloc::collections::VecDeque;
use alloc::vec::Vec;
use core::num::NonZeroUsize;
use core::time::Duration;
use broadcast_core::Parse;
use broadcast_core::stage::Instant;
use mpeg_ts::mux::{SectionPacketiser, split_sections};
use mpeg_ts::pid::{Pid, well_known};
use mpeg_ts::section::Section;
use mpeg_ts::ts::TS_PACKET_SIZE;
use crate::sub_table::SubTableId;
const PAT_TABLE_ID: u8 = crate::table_id::TableId::Pat as u8;
const PMT_TABLE_ID: u8 = crate::table_id::TableId::Pmt as u8;
const NIT_ACTUAL_TABLE_ID: u8 = crate::table_id::TableId::NetworkInformationActual as u8;
const SDT_ACTUAL_TABLE_ID: u8 = crate::table_id::TableId::ServiceDescriptionActual as u8;
const TDT_TABLE_ID: u8 = crate::table_id::TableId::TimeAndDate as u8;
const TOT_TABLE_ID: u8 = crate::table_id::TableId::TimeOffset as u8;
pub const NIT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(10));
pub const BAT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(10));
pub const SDT_ACTUAL_MAX_INTERVAL: SectionInterval =
SectionInterval::from_const(Duration::from_secs(2));
pub const SDT_OTHER_MAX_INTERVAL: SectionInterval =
SectionInterval::from_const(Duration::from_secs(10));
pub const EIT_PF_ACTUAL_MAX_INTERVAL: SectionInterval =
SectionInterval::from_const(Duration::from_secs(2));
pub const EIT_PF_OTHER_MAX_INTERVAL: SectionInterval =
SectionInterval::from_const(Duration::from_secs(10));
pub const EIT_SCHED_MAX_INTERVAL: SectionInterval =
SectionInterval::from_const(Duration::from_secs(10));
pub const EIT_SCHED_EXT_MAX_INTERVAL: SectionInterval =
SectionInterval::from_const(Duration::from_secs(30));
pub const TDT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(30));
pub const TOT_MAX_INTERVAL: SectionInterval = SectionInterval::from_const(Duration::from_secs(30));
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct SectionInterval(Duration);
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("section interval {interval:?} is below the {min:?} minimum (EN 300 468 §5.1.4.1)")]
#[non_exhaustive]
pub struct SectionIntervalTooShort {
pub interval: Duration,
pub min: Duration,
}
impl SectionInterval {
pub const fn try_new(
interval: Duration,
) -> core::result::Result<Self, SectionIntervalTooShort> {
if interval.as_nanos() < MIN_SECTION_INTERVAL_NANOS {
Err(SectionIntervalTooShort {
interval,
min: MIN_SECTION_INTERVAL,
})
} else {
Ok(Self(interval))
}
}
#[must_use]
pub const fn from_const(interval: Duration) -> Self {
assert!(
interval.as_nanos() >= MIN_SECTION_INTERVAL_NANOS,
"named section interval is below the 25 ms minimum (EN 300 468 §5.1.4.1)"
);
Self(interval)
}
#[must_use]
pub const fn duration(self) -> Duration {
self.0
}
}
impl TryFrom<Duration> for SectionInterval {
type Error = SectionIntervalTooShort;
fn try_from(interval: Duration) -> core::result::Result<Self, Self::Error> {
Self::try_new(interval)
}
}
impl From<SectionInterval> for Duration {
fn from(interval: SectionInterval) -> Self {
interval.0
}
}
pub const MIN_SECTION_INTERVAL: Duration = Duration::from_millis(25);
const MIN_SECTION_INTERVAL_NANOS: u128 = 25_000_000;
pub const PAT_MAX_INTERVAL: SectionInterval =
SectionInterval::from_const(Duration::from_millis(100));
pub const PMT_MAX_INTERVAL: SectionInterval =
SectionInterval::from_const(Duration::from_millis(100));
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct SectionKey {
pub pid: Pid,
pub table_id: u8,
pub section_number: u8,
pub sub_table: Option<SubTableId>,
}
impl SectionKey {
#[must_use]
pub const fn new(pid: Pid, table_id: u8, section_number: u8) -> Self {
Self {
pid,
table_id,
section_number,
sub_table: None,
}
}
#[must_use]
pub const fn in_sub_table(mut self, sub_table: SubTableId) -> Self {
self.sub_table = Some(sub_table);
self
}
fn covers(&self, stored: &Self) -> bool {
self.pid == stored.pid
&& self.table_id == stored.table_id
&& self.section_number == stored.section_number
&& self.sub_table.is_none_or(|s| Some(s) == stored.sub_table)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct RejectedSection {
pub pid: Pid,
pub reason: SectionRejection,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum SectionRejection {
NotASection,
MoreThanOneSection,
DuplicateSection,
Malformed,
WrongTableId {
expected: u8,
found: Option<u8>,
},
}
impl SectionRejection {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
SectionRejection::NotASection => "not_a_section",
SectionRejection::MoreThanOneSection => "more_than_one_section",
SectionRejection::DuplicateSection => "duplicate_section",
SectionRejection::Malformed => "malformed",
SectionRejection::WrongTableId { .. } => "wrong_table_id",
}
}
}
broadcast_core::impl_spec_display!(SectionRejection);
pub struct SiMux {
entries: Vec<Entry>,
rejected: VecDeque<RejectedSection>,
max_rejected: usize,
rejected_dropped: u64,
packetisers: Vec<SectionPacketiser>,
}
struct Entry {
key: SectionKey,
section: Vec<u8>,
interval: SectionInterval,
last_emit: Option<Instant>,
}
fn packetiser_for(packetisers: &mut Vec<SectionPacketiser>, pid: Pid) -> &mut SectionPacketiser {
if let Some(idx) = packetisers.iter().position(|p| p.pid() == pid) {
&mut packetisers[idx]
} else {
packetisers.push(SectionPacketiser::new(pid));
let last = packetisers.len() - 1;
&mut packetisers[last]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SiMuxLimits {
pub max_rejected: NonZeroUsize,
}
impl SiMux {
#[must_use]
pub fn new(limits: SiMuxLimits) -> Self {
Self {
entries: Vec::new(),
rejected: VecDeque::new(),
max_rejected: limits.max_rejected.get(),
rejected_dropped: 0,
packetisers: Vec::new(),
}
}
fn reject(&mut self, pid: Pid, reason: SectionRejection) {
if self.rejected.len() >= self.max_rejected {
self.rejected.pop_front();
self.rejected_dropped = self.rejected_dropped.saturating_add(1);
}
self.rejected.push_back(RejectedSection { pid, reason });
}
pub fn upsert(
&mut self,
pid: Pid,
section: Vec<u8>,
interval: SectionInterval,
) -> core::result::Result<(), SectionRejection> {
let rejection = self.register(pid, section, interval);
match rejection {
Some(reason) => {
self.reject(pid, reason);
Err(reason)
}
None => Ok(()),
}
}
fn register(
&mut self,
pid: Pid,
section: Vec<u8>,
interval: SectionInterval,
) -> Option<SectionRejection> {
let batch = split_sections(§ion);
let owned = match batch.len() {
0 => return Some(SectionRejection::NotASection),
1 => match Section::parse(batch[0]) {
Ok(parsed) => parsed,
Err(_) => return Some(SectionRejection::Malformed),
},
_ => {
if !sections_are_distinct(&batch) {
return Some(SectionRejection::DuplicateSection);
}
return Some(SectionRejection::MoreThanOneSection);
}
};
let sub_table = if owned.section_syntax_indicator {
Some(SubTableId::of_section(&owned))
} else {
None
};
let key = SectionKey {
pid,
table_id: owned.table_id,
section_number: owned.section_number,
sub_table,
};
let Ok(stored) = owned.serialize() else {
return Some(SectionRejection::Malformed);
};
if let Some(entry) = self.entries.iter_mut().find(|e| e.key == key) {
if entry.section != stored {
entry.last_emit = None;
}
entry.section = stored;
entry.interval = interval;
} else {
self.entries.push(Entry {
key,
section: stored,
interval,
last_emit: None,
});
}
None
}
pub fn remove(&mut self, key: SectionKey) -> bool {
let before = self.entries.len();
self.entries.retain(|e| !key.covers(&e.key));
self.entries.len() != before
}
pub fn keys(&self) -> impl Iterator<Item = SectionKey> + '_ {
self.entries.iter().map(|e| e.key)
}
pub fn rejected(&self) -> impl ExactSizeIterator<Item = &RejectedSection> + '_ {
self.rejected.iter()
}
pub fn take_rejected(&mut self) -> Vec<RejectedSection> {
self.rejected.drain(..).collect()
}
#[must_use]
pub fn rejected_dropped(&self) -> u64 {
self.rejected_dropped
}
pub fn upsert_pat(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
upsert_checked(
self,
well_known::PAT,
section,
PAT_MAX_INTERVAL,
PAT_TABLE_ID,
)
}
pub fn upsert_pmt(
&mut self,
pid: Pid,
section: Vec<u8>,
) -> core::result::Result<(), SectionRejection> {
upsert_checked(self, pid, section, PMT_MAX_INTERVAL, PMT_TABLE_ID)
}
pub fn upsert_sdt_actual(
&mut self,
section: Vec<u8>,
) -> core::result::Result<(), SectionRejection> {
upsert_checked(
self,
well_known::SDT_BAT,
section,
SDT_ACTUAL_MAX_INTERVAL,
SDT_ACTUAL_TABLE_ID,
)
}
pub fn upsert_nit(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
upsert_checked(
self,
well_known::NIT,
section,
NIT_MAX_INTERVAL,
NIT_ACTUAL_TABLE_ID,
)
}
pub fn upsert_tdt(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
upsert_checked(
self,
well_known::TDT_TOT,
section,
TDT_MAX_INTERVAL,
TDT_TABLE_ID,
)
}
pub fn upsert_tot(&mut self, section: Vec<u8>) -> core::result::Result<(), SectionRejection> {
upsert_checked(
self,
well_known::TDT_TOT,
section,
TOT_MAX_INTERVAL,
TOT_TABLE_ID,
)
}
pub fn poll_into(&mut self, now: Instant, out: &mut Vec<[u8; TS_PACKET_SIZE]>) -> usize {
out.clear();
let before = out.len();
let packetisers = &mut self.packetisers;
for entry in &mut self.entries {
let due = match entry.last_emit {
None => true,
Some(last) => now.saturating_duration_since(last) >= entry.interval.duration(),
};
if due {
let mut tmp = Vec::new();
let refs: [&[u8]; 1] = [&entry.section];
let packetiser = packetiser_for(packetisers, entry.key.pid);
packetiser.packetise_into(&refs, &mut tmp);
out.append(&mut tmp);
entry.last_emit = Some(now);
}
}
out.len() - before
}
pub fn poll(&mut self, now: Instant) -> Vec<[u8; TS_PACKET_SIZE]> {
let mut out = Vec::new();
self.poll_into(now, &mut out);
out
}
}
fn sections_are_distinct(sections: &[&[u8]]) -> bool {
let mut keys: Vec<(u8, u8, Option<SubTableId>)> = Vec::with_capacity(sections.len());
for bytes in sections {
let Ok(section) = Section::parse(bytes) else {
return true;
};
let sub_table = if section.section_syntax_indicator {
Some(SubTableId::of_section(§ion))
} else {
None
};
let key = (section.table_id, section.section_number, sub_table);
if keys.contains(&key) {
return false;
}
keys.push(key);
}
true
}
fn upsert_checked(
mux: &mut SiMux,
pid: Pid,
section: Vec<u8>,
interval: SectionInterval,
table_id: u8,
) -> core::result::Result<(), SectionRejection> {
if split_sections(§ion)
.first()
.is_some_and(|s| s.first().copied() != Some(table_id))
{
let reason = SectionRejection::WrongTableId {
expected: table_id,
found: section.first().copied(),
};
mux.reject(pid, reason);
return Err(reason);
}
mux.upsert(pid, section, interval)
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
use alloc::vec::Vec;
use mpeg_ts::ts::{ContinuityCounter, SectionReassembler, TsPacket};
fn test_mux() -> SiMux {
SiMux::new(SiMuxLimits {
max_rejected: NonZeroUsize::new(8).expect("non-zero"),
})
}
fn concat_sections(sections: &[Vec<u8>]) -> Vec<u8> {
let total: usize = sections.iter().map(|s| s.len()).sum();
let mut out = Vec::with_capacity(total);
for s in sections {
out.extend_from_slice(s);
}
out
}
#[test]
fn interval_constants_match_spec() {
assert_eq!(NIT_MAX_INTERVAL.duration(), Duration::from_secs(10));
assert_eq!(BAT_MAX_INTERVAL.duration(), Duration::from_secs(10));
assert_eq!(SDT_ACTUAL_MAX_INTERVAL.duration(), Duration::from_secs(2));
assert_eq!(SDT_OTHER_MAX_INTERVAL.duration(), Duration::from_secs(10));
assert_eq!(
EIT_PF_ACTUAL_MAX_INTERVAL.duration(),
Duration::from_secs(2)
);
assert_eq!(
EIT_PF_OTHER_MAX_INTERVAL.duration(),
Duration::from_secs(10)
);
assert_eq!(EIT_SCHED_MAX_INTERVAL.duration(), Duration::from_secs(10));
assert_eq!(
EIT_SCHED_EXT_MAX_INTERVAL.duration(),
Duration::from_secs(30)
);
assert_eq!(TDT_MAX_INTERVAL.duration(), Duration::from_secs(30));
assert_eq!(TOT_MAX_INTERVAL.duration(), Duration::from_secs(30));
assert_eq!(PAT_MAX_INTERVAL.duration(), Duration::from_millis(100));
assert_eq!(PMT_MAX_INTERVAL.duration(), Duration::from_millis(100));
assert_eq!(MIN_SECTION_INTERVAL, Duration::from_millis(25));
}
#[test]
fn new_and_default_simux_are_empty() {
let mut mux = test_mux();
let pkts = mux.poll(Instant::ZERO);
assert!(pkts.is_empty());
}
#[test]
fn first_poll_always_emits() {
let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
s.clone(),
SectionInterval::from_const(Duration::from_millis(100)),
)
.expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
assert!(!pkts.is_empty(), "first poll must emit");
}
#[test]
fn first_poll_emits_all_entries() {
let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
s1.clone(),
SectionInterval::from_const(Duration::from_millis(100)),
)
.expect("scheduled section");
mux.upsert(
Pid::from_const(0x0200),
s2.clone(),
SectionInterval::from_const(Duration::from_millis(200)),
)
.expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
let pids: Vec<Pid> = pkts
.iter()
.map(|raw| TsPacket::parse(raw).unwrap().header.pid)
.collect();
assert!(pids.contains(&Pid::from_const(0x0100)));
assert!(pids.contains(&Pid::from_const(0x0200)));
}
#[test]
fn entry_emits_only_when_due() {
let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 10]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
s.clone(),
SectionInterval::from_const(Duration::from_millis(100)),
)
.expect("scheduled section");
let pkts0 = mux.poll(Instant::ZERO);
assert!(!pkts0.is_empty());
let pkts50 = mux.poll(Instant::from_millis(50));
assert!(pkts50.is_empty(), "should not emit at t=50");
let pkts99 = mux.poll(Instant::from_millis(99));
assert!(pkts99.is_empty(), "should not emit at t=99");
let pkts100 = mux.poll(Instant::from_millis(100));
assert!(!pkts100.is_empty(), "should emit at t=100");
}
#[test]
fn two_entries_different_cadence() {
let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x01; 5]);
let s2 = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0x02; 5]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
concat_sections(&[s1]),
SectionInterval::from_const(Duration::from_millis(100)),
)
.expect("scheduled section");
mux.upsert(
Pid::from_const(0x0200),
concat_sections(&[s2]),
SectionInterval::from_const(Duration::from_millis(200)),
)
.expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
assert!(!pkts.is_empty());
let pkts100 = mux.poll(Instant::from_millis(100));
assert!(!pkts100.is_empty());
let pids100: Vec<Pid> = pkts100
.iter()
.map(|raw| TsPacket::parse(raw).unwrap().header.pid)
.collect();
assert!(
pids100.contains(&Pid::from_const(0x0100)),
"PID 0x0100 should emit at t=100"
);
assert!(
!pids100.contains(&Pid::from_const(0x0200)),
"PID 0x0200 should NOT emit at t=100"
);
let pkts150 = mux.poll(Instant::from_millis(150));
assert!(pkts150.is_empty(), "neither should emit at t=150");
let pkts200 = mux.poll(Instant::from_millis(200));
let pids200: Vec<Pid> = pkts200
.iter()
.map(|raw| TsPacket::parse(raw).unwrap().header.pid)
.collect();
assert!(
pids200.contains(&Pid::from_const(0x0100)),
"PID 0x0100 should emit at t=200"
);
assert!(
pids200.contains(&Pid::from_const(0x0200)),
"PID 0x0200 should emit at t=200"
);
}
#[test]
fn entry_emits_again_after_full_interval() {
let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
s,
SectionInterval::from_const(Duration::from_secs(1)),
)
.expect("scheduled section");
let n0 = mux.poll_into(Instant::ZERO, &mut Vec::new());
assert!(n0 > 0);
let mut buf = Vec::new();
let n999 = mux.poll_into(Instant::from_millis(999), &mut buf);
assert_eq!(n999, 0);
let mut buf2 = Vec::new();
let n1000 = mux.poll_into(Instant::from_millis(1000), &mut buf2);
assert!(n1000 > 0);
}
#[test]
fn upsert_updates_existing_entry() {
let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0xAA, 0xAA]);
let s2 =
test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0xBB, 0xBB, 0xBB]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
s1,
SectionInterval::from_const(Duration::from_millis(100)),
)
.expect("scheduled section");
mux.upsert(
Pid::from_const(0x0100),
s2.clone(),
SectionInterval::from_const(Duration::from_millis(200)),
)
.expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
let mut reasm = SectionReassembler::default();
for raw in &pkts {
let pkt = TsPacket::parse(raw).unwrap();
if pkt.header.pid == Pid::from_const(0x0100) {
reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
}
}
let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
assert_eq!(got.len(), 1);
assert_eq!(got[0].as_ref(), s2.as_slice());
}
#[test]
fn upsert_tdt_then_tot_both_emitted_with_continuous_cc() {
let tdt = test_fixtures::psi::long_section(0x70, 1, 0, 0, &[0xAA; 5]); let tot = test_fixtures::psi::long_section(0x73, 1, 0, 0, &[0xBB; 8]); let mut mux = test_mux();
mux.upsert_tdt(tdt.clone()).expect("scheduled section");
mux.upsert_tot(tot.clone()).expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
assert!(!pkts.is_empty());
let mut table_ids_seen = Vec::new();
let mut reasm = SectionReassembler::default();
let mut prev_cc: Option<ContinuityCounter> = None;
for raw in &pkts {
let pkt = TsPacket::parse(raw).unwrap();
assert_eq!(pkt.header.pid, well_known::TDT_TOT);
if let Some(prev) = prev_cc {
assert_eq!(
pkt.header.continuity_counter.forward_distance_from(prev),
1,
"continuity counter must be continuous across table kinds on one PID"
);
}
prev_cc = Some(pkt.header.continuity_counter);
reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
}
while let Some(section) = reasm.pop_section() {
table_ids_seen.push(section.as_ref()[0]);
}
assert!(table_ids_seen.contains(&0x70), "TDT missing from output");
assert!(table_ids_seen.contains(&0x73), "TOT missing from output");
}
#[test]
fn upsert_sdt_and_bat_both_emitted() {
let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xCC; 5]);
let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0xDD; 6]);
let mut mux = test_mux();
mux.upsert_sdt_actual(sdt.clone())
.expect("scheduled section");
mux.upsert(
well_known::SDT_BAT,
bat.clone(),
SectionInterval::from_const(Duration::from_millis(1000)),
)
.expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
let mut table_ids_seen = Vec::new();
let mut reasm = SectionReassembler::default();
for raw in &pkts {
let pkt = TsPacket::parse(raw).unwrap();
reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
}
while let Some(section) = reasm.pop_section() {
table_ids_seen.push(section.as_ref()[0]);
}
assert!(table_ids_seen.contains(&0x42), "SDT actual missing");
assert!(table_ids_seen.contains(&0x4A), "BAT missing");
}
fn emitted_sections(mux: &mut SiMux) -> Vec<Vec<u8>> {
let mut reasm = SectionReassembler::default();
for raw in &mux.poll(Instant::ZERO) {
let pkt = TsPacket::parse(raw).unwrap();
reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
}
core::iter::from_fn(|| reasm.pop_section())
.map(|s| s.as_ref().to_vec())
.collect()
}
fn eit_pf(service_id: u16, tsid: u16, onid: u16, tag: u8) -> Vec<u8> {
let mut payload = Vec::new();
payload.extend_from_slice(&tsid.to_be_bytes());
payload.extend_from_slice(&onid.to_be_bytes());
payload.extend_from_slice(&[0x00, 0x4E, tag]);
test_fixtures::psi::long_section(0x4E, service_id, 0, 0, &payload)
}
fn sdt(tsid: u16, onid: u16, tag: u8) -> Vec<u8> {
let mut payload = Vec::new();
payload.extend_from_slice(&onid.to_be_bytes());
payload.extend_from_slice(&[0xFF, tag]);
test_fixtures::psi::long_section(0x46, tsid, 0, 0, &payload)
}
#[test]
fn every_services_eit_present_following_is_scheduled() {
let mut mux = test_mux();
let sections: Vec<Vec<u8>> = (1..=3u16)
.map(|svc| eit_pf(svc, 1000, 1, svc as u8))
.collect();
for section in §ions {
mux.upsert(
Pid::from_const(0x0012),
section.clone(),
EIT_PF_ACTUAL_MAX_INTERVAL,
)
.expect("scheduled");
}
assert_eq!(mux.keys().count(), 3);
let mut got = emitted_sections(&mut mux);
got.sort();
let mut want = sections;
want.sort();
assert_eq!(got, want);
}
#[test]
fn two_networks_sdt_other_with_one_transport_stream_id_are_both_scheduled() {
let mut mux = test_mux();
let (a, b) = (sdt(1000, 1, 0xA1), sdt(1000, 2, 0xB2));
for section in [&a, &b] {
mux.upsert(well_known::SDT_BAT, section.clone(), SDT_OTHER_MAX_INTERVAL)
.expect("scheduled");
}
let mut got = emitted_sections(&mut mux);
got.sort();
let mut want = vec![a, b];
want.sort();
assert_eq!(got, want);
}
#[test]
fn two_programmes_pmt_on_one_pid_are_both_scheduled() {
let mut mux = test_mux();
let (a, b) = (
test_fixtures::psi::long_section(0x02, 1, 0, 0, &[0xE1, 0x00, 0xF0, 0x00]),
test_fixtures::psi::long_section(0x02, 2, 0, 0, &[0xE1, 0x00, 0xF0, 0x00]),
);
for section in [&a, &b] {
mux.upsert(Pid::from_const(0x0100), section.clone(), PMT_MAX_INTERVAL)
.expect("scheduled");
}
assert_eq!(emitted_sections(&mut mux).len(), 2);
}
#[test]
fn a_newer_section_of_the_same_sub_table_replaces_only_its_own() {
let mut mux = test_mux();
let pid = Pid::from_const(0x0012);
for svc in [1u16, 2] {
mux.upsert(pid, eit_pf(svc, 1000, 1, 0x10), EIT_PF_ACTUAL_MAX_INTERVAL)
.expect("scheduled");
}
let newer = eit_pf(2, 1000, 1, 0x20);
mux.upsert(pid, newer.clone(), EIT_PF_ACTUAL_MAX_INTERVAL)
.expect("replaced");
assert_eq!(mux.keys().count(), 2);
let got = emitted_sections(&mut mux);
assert!(got.contains(&newer));
assert!(got.contains(&eit_pf(1, 1000, 1, 0x10)));
}
#[test]
fn removing_a_key_without_a_sub_table_removes_every_sub_table_section() {
let mut mux = test_mux();
let pid = Pid::from_const(0x0012);
for svc in [1u16, 2] {
mux.upsert(pid, eit_pf(svc, 1000, 1, 0x10), EIT_PF_ACTUAL_MAX_INTERVAL)
.expect("scheduled");
}
let one = mux.keys().next().expect("a key");
assert!(mux.remove(one));
assert_eq!(mux.keys().count(), 1);
assert!(mux.remove(SectionKey::new(pid, 0x4E, 0)));
assert_eq!(mux.keys().count(), 0);
}
#[test]
fn the_rejection_log_is_bounded_and_counts_what_it_drops() {
let mut mux = SiMux::new(SiMuxLimits {
max_rejected: NonZeroUsize::new(2).expect("non-zero"),
});
for _ in 0..5 {
mux.upsert(well_known::PAT, Vec::new(), PAT_MAX_INTERVAL)
.expect_err("empty input is no section");
}
assert_eq!(mux.rejected().len(), 2);
assert_eq!(mux.rejected_dropped(), 3);
assert_eq!(mux.take_rejected().len(), 2);
assert_eq!(mux.rejected().len(), 0);
}
#[test]
fn upsert_sdt_actual_uses_correct_pid() {
let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
let mut mux = test_mux();
mux.upsert_sdt_actual(s).expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
let pids: Vec<Pid> = pkts
.iter()
.map(|raw| TsPacket::parse(raw).unwrap().header.pid)
.collect();
assert!(pids.iter().all(|&p| p == well_known::SDT_BAT));
}
#[test]
fn upsert_pat_uses_correct_pid() {
let s = test_fixtures::psi::long_section(0x00, 1, 0, 0, &[0x01, 0x02]);
let mut mux = test_mux();
mux.upsert_pat(s).expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
assert!(!pkts.is_empty());
let pids: Vec<Pid> = pkts
.iter()
.map(|raw| TsPacket::parse(raw).unwrap().header.pid)
.collect();
assert!(pids.iter().all(|&p| p == well_known::PAT));
assert!(
mux.poll(Instant::from_nanos(
(PAT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
))
.is_empty()
);
assert!(
!mux.poll(Instant::from_nanos(
PAT_MAX_INTERVAL.duration().as_nanos() as u64
))
.is_empty()
);
}
#[test]
fn upsert_nit_uses_correct_pid() {
let s = test_fixtures::psi::long_section(0x40, 1, 0, 0, &[0x01]);
let mut mux = test_mux();
mux.upsert_nit(s).expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
assert!(!pkts.is_empty());
let pids: Vec<Pid> = pkts
.iter()
.map(|raw| TsPacket::parse(raw).unwrap().header.pid)
.collect();
assert!(pids.iter().all(|&p| p == well_known::NIT));
assert!(
mux.poll(Instant::from_nanos(
(NIT_MAX_INTERVAL.duration() / 2).as_nanos() as u64
))
.is_empty()
);
assert!(
!mux.poll(Instant::from_nanos(
NIT_MAX_INTERVAL.duration().as_nanos() as u64
))
.is_empty()
);
}
#[test]
fn upsert_tdt_uses_correct_pid() {
let s = test_fixtures::psi::long_section(0x70, 1, 0, 0, &[0x01]);
let mut mux = test_mux();
mux.upsert_tdt(s).expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
let pids: Vec<Pid> = pkts
.iter()
.map(|raw| TsPacket::parse(raw).unwrap().header.pid)
.collect();
assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
}
#[test]
fn upsert_tot_uses_correct_pid() {
let s = test_fixtures::psi::long_section(0x73, 1, 0, 0, &[0x01]);
let mut mux = test_mux();
mux.upsert_tot(s).expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
let pids: Vec<Pid> = pkts
.iter()
.map(|raw| TsPacket::parse(raw).unwrap().header.pid)
.collect();
assert!(pids.iter().all(|&p| p == well_known::TDT_TOT));
}
#[test]
fn upsert_rejects_an_empty_input() {
let mut mux = test_mux();
let pat = test_fixtures::psi::pat_section(1, 0, &[(1, 0x1000)]);
mux.upsert_pat(pat.clone()).expect("PAT is schedulable");
assert_eq!(
mux.upsert(well_known::PAT, Vec::new(), PAT_MAX_INTERVAL),
Err(SectionRejection::NotASection)
);
assert_eq!(mux.rejected().len(), 1);
assert_eq!(mux.rejected().next().expect("one").pid, well_known::PAT);
let pkts = mux.poll(Instant::ZERO);
let mut reasm = SectionReassembler::default();
for raw in &pkts {
let pkt = TsPacket::parse(raw).unwrap();
reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
}
let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
assert_eq!(got.len(), 1);
assert_eq!(got[0].as_ref(), pat.as_slice());
}
#[test]
fn upsert_rejects_two_sections_that_share_a_key() {
let a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
let b = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x02]);
let mut mux = test_mux();
assert_eq!(
mux.upsert(
well_known::SDT_BAT,
concat_sections(&[a, b]),
SDT_ACTUAL_MAX_INTERVAL
),
Err(SectionRejection::DuplicateSection)
);
}
#[test]
fn upsert_rejects_a_second_section_of_another_table() {
let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
let bat = test_fixtures::psi::long_section(0x4A, 1, 0, 0, &[0x02]);
let mut mux = test_mux();
assert_eq!(
mux.upsert(
well_known::SDT_BAT,
concat_sections(&[sdt, bat]),
SDT_ACTUAL_MAX_INTERVAL
),
Err(SectionRejection::MoreThanOneSection)
);
}
#[test]
fn upsert_keeps_a_complete_section_and_rejects_a_trailing_fragment() {
let whole = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
let mut with_tail = whole.clone();
with_tail.extend_from_slice(&[0x4A, 0x00]);
let mut mux = test_mux();
mux.upsert(well_known::SDT_BAT, with_tail, SDT_ACTUAL_MAX_INTERVAL)
.expect("the complete section is schedulable");
let pkts = mux.poll(Instant::ZERO);
let mut reasm = SectionReassembler::default();
for raw in &pkts {
let pkt = TsPacket::parse(raw).unwrap();
reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
}
let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
assert_eq!(got.len(), 1);
assert_eq!(got[0].as_ref(), whole.as_slice());
}
#[test]
fn sections_of_one_table_are_keyed_by_their_section_number() {
let first = test_fixtures::psi::long_section(
0x4E,
1,
0,
0,
&[0x00, 0x01, 0x00, 0x01, 0x00, 0x4E, 0x01],
);
let second = test_fixtures::psi::long_section(
0x4E,
1,
0,
1,
&[0x00, 0x01, 0x00, 0x01, 0x00, 0x4E, 0x02],
);
let mut mux = test_mux();
let pid = Pid::from_const(0x0012);
mux.upsert(pid, first.clone(), EIT_SCHED_MAX_INTERVAL)
.expect("first section");
mux.upsert(pid, second.clone(), EIT_SCHED_MAX_INTERVAL)
.expect("second section");
let pkts = mux.poll(Instant::ZERO);
let mut reasm = SectionReassembler::default();
for raw in &pkts {
let pkt = TsPacket::parse(raw).unwrap();
reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
}
let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
assert_eq!(got.len(), 2, "both sections of the table must go out");
}
#[test]
fn upsert_pat_rejects_a_section_of_another_table() {
let sdt = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0x01]);
let mut mux = test_mux();
assert_eq!(
mux.upsert_pat(sdt),
Err(SectionRejection::WrongTableId {
expected: PAT_TABLE_ID,
found: Some(0x42),
})
);
assert!(mux.poll(Instant::ZERO).is_empty());
}
#[test]
fn simux_round_trip_single_entry() {
let s1 = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 20]);
let interval = SectionInterval::from_const(Duration::from_millis(100));
let mut mux = test_mux();
mux.upsert(Pid::from_const(0x0100), s1.clone(), interval)
.expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
let mut reasm = SectionReassembler::default();
for raw in &pkts {
let pkt = TsPacket::parse(raw).unwrap();
if pkt.header.pid == Pid::from_const(0x0100) {
reasm.feed(pkt.payload.unwrap(), pkt.header.pusi);
}
}
let got: Vec<_> = core::iter::from_fn(|| reasm.pop_section()).collect();
assert_eq!(got.len(), 1, "round-trip must recover the section");
assert_eq!(got[0].as_ref(), s1.as_slice());
}
#[test]
fn simux_round_trip_multi_pid() {
let s_a = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xA0; 10]);
let s_b = test_fixtures::psi::long_section(0x46, 1, 0, 0, &[0xB0; 10]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
s_a.clone(),
SectionInterval::from_const(Duration::from_millis(100)),
)
.expect("scheduled section");
mux.upsert(
Pid::from_const(0x0200),
s_b.clone(),
SectionInterval::from_const(Duration::from_millis(100)),
)
.expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
let mut reasm_a = SectionReassembler::default();
let mut reasm_b = SectionReassembler::default();
for raw in &pkts {
let pkt = TsPacket::parse(raw).unwrap();
match pkt.header.pid.value() {
0x0100 => reasm_a.feed(pkt.payload.unwrap(), pkt.header.pusi),
0x0200 => reasm_b.feed(pkt.payload.unwrap(), pkt.header.pusi),
_ => {}
}
}
let got_a: Vec<_> = core::iter::from_fn(|| reasm_a.pop_section()).collect();
let got_b: Vec<_> = core::iter::from_fn(|| reasm_b.pop_section()).collect();
assert_eq!(got_a.len(), 1);
assert_eq!(got_b.len(), 1);
assert_eq!(got_a[0].as_ref(), s_a.as_slice());
assert_eq!(got_b[0].as_ref(), s_b.as_slice());
}
#[test]
fn continuity_counter_continuous_across_polls() {
let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0xAA; 250]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
s,
SectionInterval::from_const(Duration::from_millis(100)),
)
.expect("scheduled section");
let pkts1 = mux.poll(Instant::ZERO);
assert!(pkts1.len() >= 2, "need ≥2 packets to test CC continuity");
let last_cc_pkts1 = TsPacket::parse(&pkts1[pkts1.len() - 1])
.unwrap()
.header
.continuity_counter;
let pkts2 = mux.poll(Instant::from_millis(100));
assert!(!pkts2.is_empty(), "second poll must emit");
let first_cc_pkts2 = TsPacket::parse(&pkts2[0])
.unwrap()
.header
.continuity_counter;
assert_eq!(
first_cc_pkts2.forward_distance_from(last_cc_pkts1),
1,
"CC must continue across poll cycles"
);
}
#[test]
fn poll_into_clears_out_before_appending() {
let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0xAA, 0xAA]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
s,
SectionInterval::from_const(Duration::from_millis(100)),
)
.expect("scheduled section");
let mut out = vec![[0u8; TS_PACKET_SIZE]; 42];
let n = mux.poll_into(Instant::ZERO, &mut out);
assert_eq!(n, out.len(), "out must contain only new packets");
}
#[test]
#[should_panic(expected = "25 ms")]
fn named_interval_const_rejects_sub_25ms_interval() {
let _ = SectionInterval::from_const(Duration::from_millis(10));
}
#[test]
fn section_interval_rejects_below_the_25ms_floor() {
for bad in [
Duration::ZERO,
Duration::from_millis(1),
Duration::from_millis(24),
MIN_SECTION_INTERVAL - Duration::from_nanos(1),
] {
let err = SectionInterval::try_new(bad).unwrap_err();
assert_eq!(err.interval, bad);
assert_eq!(err.min, MIN_SECTION_INTERVAL);
assert!(SectionInterval::try_from(bad).is_err());
}
assert_eq!(
SectionInterval::try_new(MIN_SECTION_INTERVAL)
.expect("the floor itself is valid")
.duration(),
MIN_SECTION_INTERVAL
);
assert_eq!(
Duration::from(SectionInterval::from_const(Duration::from_secs(2))),
Duration::from_secs(2)
);
}
#[test]
fn upsert_accepts_25ms_interval() {
let s = test_fixtures::psi::long_section(0x42, 1, 0, 0, &[0x00, 0x01, 0xFF, 0xAA, 0xAA]);
let mut mux = test_mux();
mux.upsert(
Pid::from_const(0x0100),
s,
SectionInterval::from_const(MIN_SECTION_INTERVAL),
)
.expect("scheduled section");
let pkts = mux.poll(Instant::ZERO);
assert!(!pkts.is_empty());
}
}