use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::num::NonZeroUsize;
use crate::TableId;
use crate::collect::{CompleteNit, CompleteSdt, SectionSetCollector};
use crate::descriptors::service::{ServiceDescriptor, ServiceType};
use crate::descriptors::{AnyDescriptor, DescriptorRegistry, PDS_EACEM, PDS_NORDIG};
use crate::tables::RunningStatus;
use crate::tables::sdt::SdtSection;
use mpeg_ts::pid::Pid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ServiceKey {
pub original_network_id: u16,
pub transport_stream_id: u16,
pub service_id: u16,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Described {
service_type: ServiceType,
provider_name: String,
service_name: String,
}
impl Described {
fn of(descriptor: &ServiceDescriptor<'_>) -> Self {
Self {
service_type: descriptor.service_type,
provider_name: descriptor.provider_name.to_string(),
service_name: descriptor.service_name.to_string(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Absorbed {
Nothing,
Sdt,
Nit,
}
impl Absorbed {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
Self::Nothing => "nothing",
Self::Sdt => "SDT",
Self::Nit => "NIT",
}
}
}
broadcast_core::impl_spec_display!(Absorbed);
pub(crate) fn is_sdt_table_id(table_id: u8) -> bool {
table_id == TableId::ServiceDescriptionActual as u8
|| table_id == TableId::ServiceDescriptionOther as u8
}
fn describe<'d, D>(descriptors: impl IntoIterator<Item = D>) -> Option<Described>
where
D: core::borrow::Borrow<AnyDescriptor<'d>>,
{
descriptors.into_iter().find_map(|d| match d.borrow() {
AnyDescriptor::Service(sd) => Some(Described::of(sd)),
_ => None,
})
}
#[cfg(feature = "jiff")]
pub(crate) fn service_name_in<'d, D>(descriptors: impl IntoIterator<Item = D>) -> Option<String>
where
D: core::borrow::Borrow<AnyDescriptor<'d>>,
{
describe(descriptors).map(|d| d.service_name)
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServiceInfo {
pub key: ServiceKey,
pub running_status: RunningStatus,
pub service_type: Option<ServiceType>,
pub provider_name: Option<String>,
pub service_name: Option<String>,
pub logical_channel_number: Option<u16>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ServiceListLimits {
pub max_services: NonZeroUsize,
}
#[derive(Debug, Clone)]
pub struct ServiceList {
services: BTreeMap<ServiceKey, ServiceInfo>,
lcns: BTreeMap<ServiceKey, u16>,
max_services: usize,
refused_for_capacity: u64,
}
#[must_use]
pub fn logical_channel_registry() -> DescriptorRegistry {
let mut registry = DescriptorRegistry::new();
registry
.with_logical_channel_for_pds(PDS_EACEM)
.with_logical_channel_for_pds(PDS_NORDIG);
registry
}
impl ServiceList {
#[must_use]
pub fn new(limits: ServiceListLimits) -> Self {
Self {
services: BTreeMap::new(),
lcns: BTreeMap::new(),
max_services: limits.max_services.get(),
refused_for_capacity: 0,
}
}
#[must_use]
pub fn refused_for_capacity(&self) -> u64 {
self.refused_for_capacity
}
fn has_room_for(&mut self, known: bool, held: usize) -> bool {
if known || held < self.max_services {
return true;
}
self.refused_for_capacity = self.refused_for_capacity.saturating_add(1);
false
}
fn insert(
&mut self,
key: ServiceKey,
running_status: RunningStatus,
described: Option<Described>,
) {
if !self.has_room_for(self.services.contains_key(&key), self.services.len()) {
return;
}
let (service_type, provider_name, service_name) = match described {
Some(d) => (
Some(d.service_type),
Some(d.provider_name),
Some(d.service_name),
),
None => (None, None, None),
};
self.services.insert(
key,
ServiceInfo {
key,
running_status,
service_type,
provider_name,
service_name,
logical_channel_number: None,
},
);
}
pub fn absorb_sdt(&mut self, sdt: &CompleteSdt<'_>) {
let (onid, tsid) = (sdt.original_network_id, sdt.transport_stream_id);
self.services.retain(|key, _| {
(key.original_network_id, key.transport_stream_id) != (onid, tsid)
|| sdt.services.iter().any(|s| s.service_id == key.service_id)
});
for service in &sdt.services {
let described = describe(service.descriptors.descriptors().iter().flatten());
let key = ServiceKey {
original_network_id: sdt.original_network_id,
transport_stream_id: sdt.transport_stream_id,
service_id: service.service_id,
};
self.insert(key, service.running_status, described);
}
}
pub fn absorb_sdt_section(&mut self, sdt: &SdtSection<'_>) {
for service in &sdt.services {
let described = describe(service.descriptors.iter().flatten());
let key = ServiceKey {
original_network_id: sdt.original_network_id,
transport_stream_id: sdt.transport_stream_id,
service_id: service.service_id,
};
self.insert(key, service.running_status, described);
}
}
pub fn feed_section(
&mut self,
collector: &mut SectionSetCollector,
registry: &DescriptorRegistry,
pid: Pid,
bytes: &[u8],
) -> Absorbed {
let Some(&table_id) = bytes.first() else {
return Absorbed::Nothing;
};
let is_sdt = is_sdt_table_id(table_id);
let is_nit = table_id == TableId::NetworkInformationActual as u8
|| table_id == TableId::NetworkInformationOther as u8;
if !is_sdt && !is_nit {
return Absorbed::Nothing;
}
let Ok(Some(complete)) = collector.push_section_with_pid(Some(pid), bytes) else {
return Absorbed::Nothing;
};
if is_sdt {
if let Ok(sdt) = complete.sdt() {
self.absorb_sdt(&sdt);
}
Absorbed::Sdt
} else {
if let Ok(nit) = complete.nit_with_registry(registry) {
self.absorb_nit(&nit);
}
Absorbed::Nit
}
}
pub fn absorb_nit(&mut self, nit: &CompleteNit<'_>) {
for ts in &nit.transport_streams {
for item in ts.descriptors.descriptors().iter().flatten() {
if let AnyDescriptor::LogicalChannel(lcd) = item {
for entry in &lcd.entries {
let key = ServiceKey {
original_network_id: ts.original_network_id,
transport_stream_id: ts.transport_stream_id,
service_id: entry.service_id,
};
if self.has_room_for(self.lcns.contains_key(&key), self.lcns.len()) {
self.lcns.insert(key, entry.logical_channel_number);
}
}
}
}
}
}
#[must_use]
pub fn len(&self) -> usize {
self.services.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.services.is_empty()
}
#[must_use]
pub fn sorted(&self) -> Vec<ServiceInfo> {
let mut rows: Vec<ServiceInfo> = self
.services
.values()
.map(|info| ServiceInfo {
logical_channel_number: self.lcns.get(&info.key).copied(),
..info.clone()
})
.collect();
rows.sort_by(
|a, b| match (a.logical_channel_number, b.logical_channel_number) {
(Some(x), Some(y)) => x.cmp(&y).then(a.key.cmp(&b.key)),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => a.key.cmp(&b.key),
},
);
rows
}
}