dvb-si 17.0.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
//! The service list a multiplex announces: SDT service entries joined with the
//! NIT's logical channel numbers (ETSI EN 300 468 §5.2.3 SDT, §5.2.1 NIT,
//! §6.2.33 service_descriptor; the LCN descriptor is NorDig / EACEM private).
//!
//! A `service_id` is only unique within one transport stream's namespace
//! (EN 300 468 §5.2.2/§5.2.3), so every entry is keyed by [`ServiceKey`]
//! (`original_network_id`, `transport_stream_id`, `service_id`), never by
//! `service_id` alone.

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;

/// Logical key identifying a service across the DVB network.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct ServiceKey {
    /// original_network_id from the EIT/SDT.
    pub original_network_id: u16,
    /// transport_stream_id from the EIT/SDT.
    pub transport_stream_id: u16,
    /// service_id.
    pub service_id: u16,
}

/// The `service_descriptor` view of one SDT entry.
#[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(),
        }
    }
}

/// What [`ServiceList::feed_section`] completed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Absorbed {
    /// The section completed no SDT or NIT set.
    Nothing,
    /// A complete SDT set was folded in.
    Sdt,
    /// A complete NIT set was folded in.
    Nit,
}

impl Absorbed {
    /// The table kind, or `"nothing"`.
    #[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);

/// Whether `table_id` is an SDT (actual or other transport stream).
pub(crate) fn is_sdt_table_id(table_id: u8) -> bool {
    table_id == TableId::ServiceDescriptionActual as u8
        || table_id == TableId::ServiceDescriptionOther as u8
}

/// The first service descriptor among `descriptors`, decoded: the one place an
/// SDT entry's descriptors become a service's type and names.
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,
    })
}

/// The decoded `service_name` of the first service descriptor among
/// `descriptors`.
#[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)
}

/// One service of a [`ServiceList`].
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServiceInfo {
    /// The service's network-wide identity.
    pub key: ServiceKey,
    /// 3-bit running_status from its SDT entry (EN 300 468 Table 6).
    pub running_status: RunningStatus,
    /// `service_type` of its first service descriptor; `None` when the SDT
    /// entry carries none.
    pub service_type: Option<ServiceType>,
    /// Annex A decoded provider name from that descriptor.
    pub provider_name: Option<String>,
    /// Annex A decoded service name from that descriptor.
    pub service_name: Option<String>,
    /// Logical channel number the NIT assigns this service, if any.
    pub logical_channel_number: Option<u16>,
}

/// The caller's bound on a [`ServiceList`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ServiceListLimits {
    /// How many distinct [`ServiceKey`]s the list holds services for, and how
    /// many it holds logical channel numbers for. A key beyond it is not
    /// stored and is counted by [`ServiceList::refused_for_capacity`].
    pub max_services: NonZeroUsize,
}

/// The services of every SDT folded in, with the LCNs of every NIT folded in.
#[derive(Debug, Clone)]
pub struct ServiceList {
    services: BTreeMap<ServiceKey, ServiceInfo>,
    lcns: BTreeMap<ServiceKey, u16>,
    max_services: usize,
    refused_for_capacity: u64,
}

/// A descriptor registry that decodes the `logical_channel_descriptor` (tag
/// 0x83) under the EACEM and NorDig private data specifiers, which
/// [`ServiceList::absorb_nit`] needs the NIT parsed with.
#[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 {
    /// An empty list within `limits`.
    #[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,
        }
    }

    /// How many services and logical channel numbers were not stored because
    /// the list was at [`ServiceListLimits::max_services`]. A growing count
    /// means the bound is too small for the stream.
    #[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,
            },
        );
    }

    /// Fold in the services of a complete SDT. A service seen again (same
    /// [`ServiceKey`]) replaces the earlier entry, and a service of the same
    /// `(original_network_id, transport_stream_id)` the SDT no longer lists is
    /// forgotten: a complete SDT is the whole sub_table (EN 300 468 §5.2.3).
    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);
        }
    }

    /// Fold in the services of one SDT section, for a caller that parses
    /// sections itself rather than reassembling a complete table.
    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);
        }
    }

    /// Feed one section as the demux emits it: SDT and NIT sections go to
    /// `collector`, and a set it completes is folded in (an SDT through
    /// [`absorb_sdt`](Self::absorb_sdt), a NIT, parsed with `registry`,
    /// through [`absorb_nit`](Self::absorb_nit)). Any other table, an invalid
    /// section or an incomplete set is [`Absorbed::Nothing`], so a caller names
    /// no `table_id`.
    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
        }
    }

    /// Fold in the logical channel numbers of a complete NIT. The NIT must have
    /// been parsed with [`logical_channel_registry`] (or one that decodes the
    /// descriptor) for any to be seen.
    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);
                        }
                    }
                }
            }
        }
    }

    /// Number of distinct services.
    #[must_use]
    pub fn len(&self) -> usize {
        self.services.len()
    }

    /// Whether no service has been folded in.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.services.is_empty()
    }

    /// The services in channel-list order: those with an LCN first, by LCN
    /// then key, then the rest by key. Each carries its LCN.
    #[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
    }
}