use std::rc::Rc;
use std::sync::mpsc;
use std::sync::{Mutex, MutexGuard, OnceLock};
use std::time::{SystemTime, UNIX_EPOCH};
use std::num::NonZeroUsize;
use std::sync::Arc;
fn native_test_lock() -> MutexGuard<'static, ()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
.lock()
.expect("native test lock")
}
use rustduck_core::{
AsyncReportConfig, BitRateConfidence, CrcValidation, DuckContext, InputSwitcher,
InputSwitcherConfig, MemoryInput, MemoryOutput, MemoryQueuePolicy, ProcessorConfig,
ProcessorInput, ProcessorOutput, Report, ReportForwarder, SectionFile, Severity, Standards,
SwitcherInput, SwitcherOutput, SystemMonitor, TS_PACKET_SIZE, TSAnalyzer, TSProcessor,
WaitStatus,
};
fn mpeg_crc32(bytes: &[u8]) -> u32 {
bytes.iter().fold(0xFFFF_FFFF, |crc, &byte| {
(0..8).fold(crc ^ (u32::from(byte) << 24), |crc, _| {
if crc & 0x8000_0000 != 0 {
(crc << 1) ^ 0x04C1_1DB7
} else {
crc << 1
}
})
})
}
fn psi_packet(pid: u16, mut section: Vec<u8>) -> [u8; TS_PACKET_SIZE] {
section.extend_from_slice(&mpeg_crc32(§ion).to_be_bytes());
assert!(section.len() <= TS_PACKET_SIZE - 5);
let mut packet = [0xFF; TS_PACKET_SIZE];
packet[..4].copy_from_slice(&[
0x47,
0x40 | u8::try_from(pid >> 8).expect("PID high byte"),
u8::try_from(pid & 0x00FF).expect("PID low byte"),
0x10,
]);
packet[4] = 0;
packet[5..5 + section.len()].copy_from_slice(§ion);
packet
}
fn pat_packet() -> [u8; TS_PACKET_SIZE] {
psi_packet(
0,
vec![
0x00, 0xB0, 0x0D, 0x00, 0x01, 0xC1, 0x00, 0x00, 0x00, 0x01, 0xE1, 0x00, ],
)
}
fn pmt_packet_with_ca_descriptor() -> [u8; TS_PACKET_SIZE] {
psi_packet(
0x100,
vec![
0x02, 0xB0, 0x13, 0x00, 0x01, 0xC1, 0x00, 0x00, 0xE1, 0x01, 0xF0, 0x06, 0x09, 0x04, 0x12, 0x34, 0xE1, 0x23, ],
)
}
#[test]
fn report_context_and_section_file_preserve_native_dependency_order() {
let _lock = native_test_lock();
let mut report = Report::asynchronous(AsyncReportConfig::default()).expect("report");
report
.log(rustduck_core::Severity::Info, "report integration")
.expect("report log");
let mut context = DuckContext::new(Rc::clone(&report)).expect("context");
Rc::get_mut(&mut context)
.expect("new context has one owner")
.add_standards(Standards::MPEG | Standards::DVB)
.expect("add standards");
assert_eq!(
context.standards().expect("query standards"),
Standards::MPEG | Standards::DVB
);
let mut sections = SectionFile::new(Rc::clone(&context)).expect("section file");
sections
.set_crc_validation(CrcValidation::Check)
.expect("set crc validation");
assert_eq!(sections.binary_size().expect("binary size"), 0);
assert_eq!(sections.sections_count().expect("section count"), 0);
assert_eq!(sections.tables_count().expect("table count"), 0);
assert_eq!(
sections.to_binary().expect("binary output"),
Vec::<u8>::new()
);
assert!(!sections.to_xml().expect("xml output").is_empty());
assert!(!sections.to_json().expect("json output").is_empty());
drop(sections);
drop(context);
Rc::get_mut(&mut report)
.expect("context no longer retains report")
.terminate()
.expect("terminate report");
}
#[test]
fn asynchronous_report_forwards_and_releases_its_callback_slot_after_termination() {
let _lock = native_test_lock();
let (sender, receiver) = mpsc::channel();
let forwarder = ReportForwarder::new(move |severity, message| {
let _ = sender.send((severity, message.to_owned()));
});
let mut report = Report::asynchronous_with_forwarder(
AsyncReportConfig {
synchronous_log: true,
..AsyncReportConfig::default()
},
forwarder,
)
.expect("forwarding report");
report.log(Severity::Info, "forwarded report").expect("log");
assert_eq!(
receiver.recv_timeout(std::time::Duration::from_secs(1)),
Ok((Severity::Info, "forwarded report".to_owned()))
);
Rc::get_mut(&mut report)
.expect("report has one owner")
.terminate()
.expect("terminate report");
drop(report);
let next = Report::asynchronous_with_forwarder(
AsyncReportConfig::default(),
ReportForwarder::new(|_, _| {}),
);
assert!(next.is_ok(), "termination must release the callback slot");
}
#[test]
fn asynchronous_reports_share_one_forwarding_destination_until_all_terminate() {
let _lock = native_test_lock();
let forwarder = ReportForwarder::new(|_, _| {});
let mut first =
Report::asynchronous_with_forwarder(AsyncReportConfig::default(), forwarder.clone())
.expect("first forwarding report");
let mut second = Report::asynchronous_with_forwarder(AsyncReportConfig::default(), forwarder)
.expect("second forwarding report");
assert!(
Report::asynchronous_with_forwarder(
AsyncReportConfig::default(),
ReportForwarder::new(|_, _| {}),
)
.is_err()
);
Rc::get_mut(&mut first)
.expect("first report has one owner")
.terminate()
.expect("terminate first report");
assert!(
Report::asynchronous_with_forwarder(
AsyncReportConfig::default(),
ReportForwarder::new(|_, _| {}),
)
.is_err()
);
Rc::get_mut(&mut second)
.expect("second report has one owner")
.terminate()
.expect("terminate second report");
assert!(
Report::asynchronous_with_forwarder(
AsyncReportConfig::default(),
ReportForwarder::new(|_, _| {}),
)
.is_ok()
);
}
#[test]
fn analyzer_reset_clears_packet_and_pmt_state() {
let _lock = native_test_lock();
let report = Report::null().expect("report");
let context = DuckContext::new(report).expect("context");
let mut analyzer = TSAnalyzer::new(context).expect("analyzer");
let packets = [pat_packet(), pmt_packet_with_ca_descriptor()].concat();
analyzer.feed(&packets).expect("feed PAT and PMT");
let snapshot = analyzer.snapshot().expect("snapshot");
assert_eq!(snapshot.summary.packet_count, 2);
let service = snapshot
.services
.iter()
.find(|service| service.service_id == 1)
.expect("service discovered from PAT and PMT");
assert!(service.ca_descriptors.iter().any(|descriptor| {
descriptor.cas_id == 0x1234
&& descriptor.ca_pid == 0x123
&& descriptor.program_level
&& descriptor.elementary_pid.is_none()
}));
analyzer.reset().expect("reset");
let reset_snapshot = analyzer.snapshot().expect("reset snapshot");
assert_eq!(reset_snapshot.summary.packet_count, 0);
assert!(reset_snapshot.services.is_empty());
assert!(reset_snapshot.pids.is_empty());
analyzer.feed(&pat_packet()).expect("feed PAT after reset");
let service = analyzer
.snapshot()
.expect("snapshot after reset PAT")
.services
.into_iter()
.find(|service| service.service_id == 1)
.expect("service rediscovered from PAT");
assert!(service.ca_descriptors.is_empty());
}
#[test]
fn analyzer_snapshot_preserves_pid_scrambling_metadata() {
let _lock = native_test_lock();
let report = Report::null().expect("report");
let context = DuckContext::new(report).expect("context");
let mut analyzer = TSAnalyzer::new(context).expect("analyzer");
let mut packet = [0xFF; TS_PACKET_SIZE];
packet[..4].copy_from_slice(&[0x47, 0x00, 0x20, 0x90]);
analyzer.feed(&packet).expect("feed scrambled packet");
let pid = analyzer
.snapshot()
.expect("snapshot")
.pids
.into_iter()
.find(|pid| pid.pid == 0x20)
.expect("PID is present");
assert_eq!(pid.current_scrambling_control, 2);
assert_eq!(pid.cas_id, 0);
assert!(pid.cas_operators.is_empty());
}
#[test]
fn analyzer_rejects_unaligned_input() {
let _lock = native_test_lock();
let report = Report::null().expect("report");
let context = DuckContext::new(report).expect("context");
let mut analyzer = TSAnalyzer::new(context).expect("analyzer");
assert!(matches!(
analyzer.feed(&[0x47; TS_PACKET_SIZE - 1]),
Err(rustduck_core::Error::InvalidArgument { .. })
));
}
#[test]
fn analyzer_bitrate_hint_overrides_the_pcr_estimate() {
let _lock = native_test_lock();
let report = Report::null().expect("report");
let context = DuckContext::new(report).expect("context");
let mut analyzer = TSAnalyzer::new(context).expect("analyzer");
const HINT: f64 = 8_000_000.0;
analyzer
.set_bitrate_hint(HINT, BitRateConfidence::Override)
.expect("set bitrate hint");
analyzer.feed(&[0x47; TS_PACKET_SIZE]).expect("feed");
let bitrate = analyzer.snapshot().expect("snapshot").summary.ts_bitrate;
assert!(
(bitrate - HINT).abs() < 1.0,
"expected the override hint {HINT} to win, got {bitrate}"
);
}
#[test]
fn analyzer_rejects_invalid_bitrate_hints() {
let _lock = native_test_lock();
let report = Report::null().expect("report");
let context = DuckContext::new(report).expect("context");
let mut analyzer = TSAnalyzer::new(context).expect("analyzer");
for invalid in [-1.0, f64::NAN, f64::INFINITY] {
assert!(matches!(
analyzer.set_bitrate_hint(invalid, BitRateConfidence::Override),
Err(rustduck_core::Error::InvalidArgument {
field: "bitrate",
..
})
));
}
}
#[test]
fn processor_memory_endpoints_run_to_orderly_eof() {
let _lock = native_test_lock();
let report = Report::stderr().expect("report");
let input = MemoryInput::new(
NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
MemoryQueuePolicy::Backpressure,
)
.expect("input");
let output = MemoryOutput::new(
NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
MemoryQueuePolicy::Backpressure,
)
.expect("output");
input.push(&[0x47; TS_PACKET_SIZE]).expect("push packet");
input.close();
let mut processor = TSProcessor::new(report).expect("processor");
processor
.start(&ProcessorConfig {
input: Some(ProcessorInput::Memory(Arc::clone(&input))),
output: Some(ProcessorOutput::Memory(Arc::clone(&output))),
..ProcessorConfig::default()
})
.expect("start");
let received = output.recv();
let packet = received.unwrap_or_else(|error| {
panic!(
"receive failed: {error}; callback error: {:?}",
processor.take_memory_error()
)
});
assert_eq!(packet, Some(vec![0x47; TS_PACKET_SIZE]));
match processor.try_wait().expect("try wait") {
WaitStatus::Pending => processor.wait_for_termination().expect("wait"),
WaitStatus::Stopped => {}
_ => panic!("unknown wait status"),
}
assert_eq!(processor.state(), rustduck_core::HostState::Stopped);
assert_eq!(output.recv().expect("eof"), None);
assert!(processor.take_memory_error().is_none());
}
#[test]
fn input_switcher_memory_endpoints_run_to_orderly_eof() {
let _lock = native_test_lock();
let report = Report::stderr().expect("report");
let input = MemoryInput::new(
NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
MemoryQueuePolicy::Backpressure,
)
.expect("input");
let output = MemoryOutput::new(
NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
MemoryQueuePolicy::Backpressure,
)
.expect("output");
input.push(&[0x47; TS_PACKET_SIZE]).expect("push packet");
input.close();
let mut switcher = InputSwitcher::new(report).expect("switcher");
switcher
.start(&InputSwitcherConfig {
inputs: vec![SwitcherInput::Memory(Arc::clone(&input))],
output: Some(SwitcherOutput::Memory(Arc::clone(&output))),
..InputSwitcherConfig::default()
})
.expect("start");
assert_eq!(
output.recv().expect("receive"),
Some(vec![0x47; TS_PACKET_SIZE])
);
switcher.wait_for_termination().expect("wait");
assert_eq!(output.recv().expect("eof"), None);
assert!(switcher.take_memory_error().is_none());
}
#[test]
fn system_monitor_runs_through_stop_and_wait() {
let _lock = native_test_lock();
let report = Report::null().expect("report");
let mut monitor = SystemMonitor::new(report, None).expect("monitor");
monitor.start().expect("start");
monitor.stop().expect("stop");
monitor.wait_for_termination().expect("wait");
assert_eq!(monitor.state(), rustduck_core::HostState::Stopped);
}
#[test]
fn section_file_binary_io_uses_explicit_paths() {
let _lock = native_test_lock();
let report = Report::null().expect("null report");
let context = DuckContext::new(report).expect("context");
let sections = SectionFile::new(context).expect("section file");
let path = std::env::temp_dir().join(format!(
"rustduck-phase-c-{}-{}-sections.bin",
std::process::id(),
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("system clock")
.as_nanos()
));
sections
.save_binary(&path)
.expect("save empty section file");
assert!(path.is_file());
std::fs::remove_file(path).expect("remove test file");
}