use std::{
collections::VecDeque,
time::Duration,
};
use bytes::Bytes;
use libmpegts::{
psi::{
PsiPacketizer,
Sections,
},
ts::{
PACKET_SIZE,
TsPacketMut,
},
};
use tokio::time::Instant;
use crate::{
event::{
DatagramFormat,
Event,
StreamInfo,
},
simulcrypt::{
CasRef,
Inner,
},
};
const DEFAULT_REP_PERIOD: Duration = Duration::from_millis(100);
fn carries_ca(pid: u16) -> bool {
(0x0020 ..= 0x1FFE).contains(&pid)
}
struct Slot {
cas: CasRef,
stream_id: u16,
pid: u16,
ecm: Bytes,
packets: Vec<[u8; PACKET_SIZE]>,
cc: u8,
period: Duration,
due: Instant,
}
pub struct Carousel {
slots: Vec<Slot>,
}
impl Carousel {
pub fn new(streams: &[StreamInfo]) -> Self {
let now = Instant::now();
let mut slots: Vec<Slot> = Vec::new();
for info in streams {
if !carries_ca(info.ecm_pid)
|| slots
.iter()
.any(|slot| slot.cas == info.cas && slot.stream_id == info.stream_id)
{
continue;
}
slots.push(Slot {
cas: info.cas,
stream_id: info.stream_id,
pid: info.ecm_pid,
ecm: Bytes::new(),
packets: Vec::new(),
cc: 0,
period: DEFAULT_REP_PERIOD,
due: now,
});
}
Self { slots }
}
pub fn next_due(&self) -> Option<Instant> {
self.slots.iter().map(|slot| slot.due).min()
}
pub fn run(&mut self, inner: &Inner, out: &mut VecDeque<Event>) {
let now = Instant::now();
self.slots.retain_mut(|slot| {
if slot.due > now {
return true;
}
let Ok(entry) = inner.cas_entry(slot.cas) else {
return false;
};
if let Some(params) = entry.params() {
slot.period = params
.rep_period
.filter(|period| !period.is_zero())
.unwrap_or(DEFAULT_REP_PERIOD);
}
if let Some(Event::Ecm { format, data, .. }) = entry.last_ecm(slot.stream_id)
&& data != slot.ecm
{
slot.packets = packetize(slot.pid, format, &data);
slot.ecm = data;
}
if !slot.packets.is_empty() {
out.push_back(Event::Ts(stamp_cc(&slot.packets, &mut slot.cc)));
}
let next = slot.due + slot.period;
slot.due = if next > now { next } else { now + slot.period };
true
});
}
}
struct EmmCas {
cas: CasRef,
streams: Vec<u16>,
cc: u8,
}
pub struct EmmPackets {
cas: Vec<EmmCas>,
}
impl EmmPackets {
pub fn new(streams: &[StreamInfo]) -> Self {
let mut cas: Vec<EmmCas> = Vec::new();
for info in streams {
match cas.iter_mut().find(|slot| slot.cas == info.cas) {
Some(slot) if slot.streams.contains(&info.stream_id) => {}
Some(slot) => slot.streams.push(info.stream_id),
None => cas.push(EmmCas {
cas: info.cas,
streams: vec![info.stream_id],
cc: 0,
}),
}
}
Self { cas }
}
pub fn push(&mut self, inner: &Inner, event: &Event, out: &mut VecDeque<Event>) {
let Event::Emm {
cas,
stream_id,
format,
data,
..
} = event
else {
return;
};
let Some(slot) = self.cas.iter_mut().find(|slot| slot.cas == *cas) else {
return;
};
let Some((pid, broadcast)) = inner.cas_entry(*cas).ok().and_then(|entry| entry.emm_pid())
else {
return;
};
let wanted = if broadcast {
slot.streams[0] == *stream_id
} else {
slot.streams.contains(stream_id)
};
if !wanted || !carries_ca(pid) {
return;
}
let packets = packetize(pid, *format, data);
if !packets.is_empty() {
out.push_back(Event::Ts(stamp_cc(&packets, &mut slot.cc)));
}
}
}
fn packetize(pid: u16, format: DatagramFormat, data: &[u8]) -> Vec<[u8; PACKET_SIZE]> {
let mut packets = Vec::new();
if data.is_empty() {
return packets;
}
match format {
DatagramFormat::Section => {
let mut packetizer = PsiPacketizer::new(pid);
packetizer.set_sections(Sections::from(data));
let mut packet = [0; PACKET_SIZE];
while packetizer.next(&mut packet) {
packets.push(packet);
}
}
DatagramFormat::TsPacket => {
for chunk in data.chunks_exact(PACKET_SIZE) {
let mut packet = [0; PACKET_SIZE];
packet.copy_from_slice(chunk);
TsPacketMut::from(&mut packet).set_pid(pid);
packets.push(packet);
}
}
}
packets
}
fn stamp_cc(packets: &[[u8; PACKET_SIZE]], cc: &mut u8) -> Vec<[u8; PACKET_SIZE]> {
packets
.iter()
.map(|packet| {
let mut packet = *packet;
TsPacketMut::from(&mut packet).set_cc(*cc);
*cc = (*cc + 1) & 0x0F;
packet
})
.collect()
}
#[cfg(test)]
mod tests {
use libmpegts::ts::TsPacketRef;
use super::*;
#[test]
fn section_gets_pusi_pointer_and_stuffing() {
let ecm = [0x80, 0x70, 0x02, 0xAB, 0xCD];
let packets = packetize(0x0100, DatagramFormat::Section, &ecm);
assert_eq!(packets.len(), 1);
let packet = TsPacketRef::from(&packets[0]);
assert_eq!(packet.pid(), 0x0100);
assert!(packet.is_payload_start());
let payload = packet.payload().unwrap();
assert_eq!(payload[0], 0, "pointer field");
assert_eq!(&payload[1 .. 6], &ecm);
assert!(payload[6 ..].iter().all(|&byte| byte == 0xFF));
}
#[test]
fn long_section_spans_packets() {
let mut ecm = vec![0x81, 0x71, 0x2C];
ecm.resize(3 + 300, 0x55);
let packets = packetize(0x0101, DatagramFormat::Section, &ecm);
assert_eq!(packets.len(), 2);
assert!(!TsPacketRef::from(&packets[1]).is_payload_start());
}
#[test]
fn ts_packets_keep_all_but_the_pid() {
let mut data = vec![0u8; PACKET_SIZE * 2 + 10];
for (index, chunk) in data.chunks_exact_mut(PACKET_SIZE).enumerate() {
chunk[0] = 0x47;
chunk[1] = 0x5F;
chunk[2] = 0xFF;
chunk[3] = 0x10;
chunk[4] = index as u8;
}
let packets = packetize(0x0ABC, DatagramFormat::TsPacket, &data);
assert_eq!(packets.len(), 2, "trailing partial packet dropped");
for (index, packet) in packets.iter().enumerate() {
assert_eq!(TsPacketRef::from(packet).pid(), 0x0ABC);
assert_eq!(packet[1] & 0xE0, 0x40, "PUSI kept");
assert_eq!(packet[4], index as u8);
}
}
#[test]
fn empty_datagram_has_no_packets() {
assert!(packetize(0x0100, DatagramFormat::Section, &[]).is_empty());
assert!(packetize(0x0100, DatagramFormat::TsPacket, &[]).is_empty());
}
#[test]
fn cc_runs_across_repetitions_and_wraps() {
let mut ecm = vec![0x80, 0x70, 0xBD];
ecm.resize(3 + 189, 0x55);
let packets = packetize(0x0100, DatagramFormat::Section, &ecm);
let mut cc = 14;
let first = stamp_cc(&packets, &mut cc);
let second = stamp_cc(&packets, &mut cc);
let ccs: Vec<u8> = first
.iter()
.chain(&second)
.map(|packet| TsPacketRef::from(packet).cc())
.collect();
assert_eq!(ccs, [14, 15, 0, 1]);
}
#[test]
fn reserved_pids_and_repeated_streams_get_no_slot() {
let info = |cas, ecm_pid, stream_id| StreamInfo {
cas: CasRef::new(cas),
ecm_pid,
stream_id,
};
let carousel = Carousel::new(&[
info(0, 0x0000, 1),
info(0, 0x001F, 2),
info(0, 0x1FFF, 3),
info(0, 0x0100, 4),
info(0, 0x0100, 4),
info(1, 0x0100, 4),
]);
let slots: Vec<_> = carousel
.slots
.iter()
.map(|slot| (slot.cas, slot.stream_id))
.collect();
assert_eq!(slots, [(CasRef::new(0), 4), (CasRef::new(1), 4)]);
}
}