Skip to main content

dvb_si/tables/
sat.rs

1//! Satellite Access Table (SAT) — ETSI EN 300 468 §5.2.11.
2//!
3//! Long-form private section on PID 0x001B with table_id 0x4D. The SAT is a
4//! *family*: a common `satellite_access_section()` header carries a 6-bit
5//! `satellite_table_id` discriminant ([`SatTableId`]) that selects one of five
6//! body structures (position v2, cell fragment, time association, beamhopping
7//! time plan, position v3).
8//!
9//! The body is bit-packed orbital / beamhopping data (33-bit NCR split fields,
10//! two's-complement lat/long, conditional ephemeris loops). It is exposed here
11//! as a raw byte slice ([`Sat::body`]); the full per-variant field layout is
12//! documented in `docs/en_300_468.md` (Tables 11a–11i). This mirrors the crate
13//! convention of keeping complex variable-length loops raw (cf. the descriptor
14//! loops in `bat.rs`).
15
16use crate::error::{Error, Result};
17use crate::traits::Table;
18use dvb_common::{Parse, Serialize};
19use num_enum::TryFromPrimitive;
20
21/// table_id for the Satellite Access Table.
22pub const TABLE_ID: u8 = 0x4D;
23/// Well-known PID on which the SAT is carried (EN 300 468 Table 1, §5.1.3).
24pub const PID: u16 = 0x001B;
25
26/// Bytes of fixed header before the body (table_id..reserved_zero_future_use).
27const HEADER_LEN: usize = 9;
28/// `section_length` counts from byte 3 (just after the field) to end of section.
29const SECTION_LENGTH_PREFIX: usize = 3;
30/// CRC_32 trailer length.
31const CRC_LEN: usize = 4;
32
33/// `satellite_table_id` discriminant — selects the SAT body structure (§5.2.11.1, Table 11b).
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TryFromPrimitive)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize))]
36#[repr(u8)]
37pub enum SatTableId {
38    /// `satellite_position_v2_info` — TLE/SGP4 orbital elements (§5.2.11.2).
39    PositionV2 = 0,
40    /// `cell_fragment_info` — earth-surface cell coverage areas (§5.2.11.3).
41    CellFragment = 1,
42    /// `time_association_info` — NCR↔UTC time association (§5.2.11.4).
43    TimeAssociation = 2,
44    /// `beamhopping_time_plan_info` — beam illumination schedule (§5.2.11.5).
45    BeamhoppingTimePlan = 3,
46    /// `satellite_position_v3_info` — ephemeris state vectors (§5.2.11.6).
47    PositionV3 = 4,
48}
49
50/// Satellite Access Table section (EN 300 468 §5.2.11.1, Table 11a).
51///
52/// The typed fields cover the common section header; [`Sat::body`] is the raw
53/// body whose structure depends on [`Sat::satellite_table_id`].
54#[derive(Debug, Clone, PartialEq, Eq)]
55#[cfg_attr(feature = "serde", derive(serde::Serialize))]
56#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
57pub struct Sat<'a> {
58    /// 6-bit discriminant selecting the body structure (see [`SatTableId`]).
59    pub satellite_table_id: u8,
60    /// 10-bit sub_table discriminator (e.g. the 10 MSBs of `satellite_id`).
61    pub table_count: u16,
62    /// 5-bit sub_table version number.
63    pub version_number: u8,
64    /// When `true`, this sub_table is currently applicable.
65    pub current_next_indicator: bool,
66    /// Section number within the sub_table.
67    pub section_number: u8,
68    /// Highest section number of the sub_table.
69    pub last_section_number: u8,
70    /// Raw body bytes — interpret per [`Sat::satellite_table_id`]; layout in `docs/tables/sat.md`.
71    pub body: &'a [u8],
72}
73
74impl Sat<'_> {
75    /// Typed view of [`Sat::satellite_table_id`], or `None` if reserved (5–63).
76    #[must_use]
77    pub fn kind(&self) -> Option<SatTableId> {
78        SatTableId::try_from(self.satellite_table_id).ok()
79    }
80}
81
82impl<'a> Parse<'a> for Sat<'a> {
83    type Error = crate::error::Error;
84    fn parse(bytes: &'a [u8]) -> Result<Self> {
85        let min_len = HEADER_LEN + CRC_LEN;
86        if bytes.len() < min_len {
87            return Err(Error::BufferTooShort {
88                need: min_len,
89                have: bytes.len(),
90                what: "Sat",
91            });
92        }
93        if bytes[0] != TABLE_ID {
94            return Err(Error::UnexpectedTableId {
95                table_id: bytes[0],
96                what: "Sat",
97                expected: &[TABLE_ID],
98            });
99        }
100        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
101        let total = SECTION_LENGTH_PREFIX + section_length;
102        if bytes.len() < total || total < HEADER_LEN + CRC_LEN {
103            return Err(Error::SectionLengthOverflow {
104                declared: section_length,
105                available: bytes.len().saturating_sub(SECTION_LENGTH_PREFIX),
106            });
107        }
108        let satellite_table_id = bytes[3] >> 2;
109        let table_count = (((bytes[3] & 0x03) as u16) << 8) | bytes[4] as u16;
110        let version_number = (bytes[5] >> 1) & 0x1F;
111        let current_next_indicator = bytes[5] & 0x01 != 0;
112        let section_number = bytes[6];
113        let last_section_number = bytes[7];
114        // bytes[8] = reserved_zero_future_use
115        let body = &bytes[HEADER_LEN..total - CRC_LEN];
116        Ok(Sat {
117            satellite_table_id,
118            table_count,
119            version_number,
120            current_next_indicator,
121            section_number,
122            last_section_number,
123            body,
124        })
125    }
126}
127
128impl Serialize for Sat<'_> {
129    type Error = crate::error::Error;
130    fn serialized_len(&self) -> usize {
131        HEADER_LEN + self.body.len() + CRC_LEN
132    }
133    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
134        let len = self.serialized_len();
135        if buf.len() < len {
136            return Err(Error::OutputBufferTooSmall {
137                need: len,
138                have: buf.len(),
139            });
140        }
141        let section_length = (len - SECTION_LENGTH_PREFIX) as u16;
142        buf[0] = TABLE_ID;
143        // section_syntax_indicator=1, private_indicator=1, reserved=11, section_length hi nibble.
144        buf[1] = 0xF0 | ((section_length >> 8) as u8 & 0x0F);
145        buf[2] = (section_length & 0xFF) as u8;
146        buf[3] = (self.satellite_table_id << 2) | ((self.table_count >> 8) as u8 & 0x03);
147        buf[4] = (self.table_count & 0xFF) as u8;
148        // reserved=11, version_number(5), current_next_indicator(1).
149        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
150        buf[6] = self.section_number;
151        buf[7] = self.last_section_number;
152        buf[8] = 0x00; // reserved_zero_future_use
153        let body_end = HEADER_LEN + self.body.len();
154        buf[HEADER_LEN..body_end].copy_from_slice(self.body);
155        let crc = dvb_common::crc32_mpeg2::compute(&buf[..body_end]);
156        buf[body_end..len].copy_from_slice(&crc.to_be_bytes());
157        Ok(len)
158    }
159}
160
161impl<'a> Table<'a> for Sat<'a> {
162    const TABLE_ID: u8 = TABLE_ID;
163    const PID: u16 = PID;
164}
165
166impl<'a> crate::traits::TableDef<'a> for Sat<'a> {
167    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
168    const NAME: &'static str = "SATELLITE_ACCESS";
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    /// Build a SAT section with the given discriminant + body.
176    fn build_sat(satellite_table_id: u8, table_count: u16, body: &[u8]) -> Vec<u8> {
177        let section_length = (HEADER_LEN - SECTION_LENGTH_PREFIX + body.len() + CRC_LEN) as u16;
178        let mut v = vec![
179            TABLE_ID,
180            0xF0 | ((section_length >> 8) as u8 & 0x0F),
181            (section_length & 0xFF) as u8,
182            (satellite_table_id << 2) | ((table_count >> 8) as u8 & 0x03),
183            (table_count & 0xFF) as u8,
184            0xC0 | (0x05 << 1) | 0x01, // version 5, current_next = 1
185            0x00,                      // section_number
186            0x00,                      // last_section_number
187            0x00,                      // reserved_zero_future_use
188        ];
189        v.extend_from_slice(body);
190        v.extend_from_slice(&[0, 0, 0, 0]);
191        v
192    }
193
194    #[test]
195    fn parse_position_v3_discriminant() {
196        let body = [0xAA, 0xBB, 0xCC, 0xDD];
197        let bytes = build_sat(4, 0x1A3, &body);
198        let sat = Sat::parse(&bytes).unwrap();
199        assert_eq!(sat.satellite_table_id, 4);
200        assert_eq!(sat.kind(), Some(SatTableId::PositionV3));
201        assert_eq!(sat.table_count, 0x1A3);
202        assert_eq!(sat.version_number, 5);
203        assert!(sat.current_next_indicator);
204        assert_eq!(sat.body, &body);
205    }
206
207    #[test]
208    fn reserved_discriminant_has_no_kind() {
209        let bytes = build_sat(7, 0, &[]);
210        let sat = Sat::parse(&bytes).unwrap();
211        assert_eq!(sat.satellite_table_id, 7);
212        assert_eq!(sat.kind(), None);
213    }
214
215    #[test]
216    fn parse_rejects_wrong_tag() {
217        let mut bytes = build_sat(0, 0, &[1, 2, 3]);
218        bytes[0] = 0x40;
219        assert!(matches!(
220            Sat::parse(&bytes).unwrap_err(),
221            Error::UnexpectedTableId { table_id: 0x40, .. }
222        ));
223    }
224
225    #[test]
226    fn rejects_short_buffer() {
227        assert!(matches!(
228            Sat::parse(&[0x4D, 0xF0]).unwrap_err(),
229            Error::BufferTooShort { what: "Sat", .. }
230        ));
231    }
232
233    #[test]
234    fn serialize_round_trip() {
235        let body = [0x01, 0x02, 0x03, 0x04, 0x05];
236        let bytes = build_sat(1, 0x2FF, &body);
237        let sat = Sat::parse(&bytes).unwrap();
238        let mut buf = vec![0u8; sat.serialized_len()];
239        sat.serialize_into(&mut buf).unwrap();
240        let re = Sat::parse(&buf).unwrap();
241        assert_eq!(sat, re);
242        assert_eq!(re.kind(), Some(SatTableId::CellFragment));
243        assert_eq!(re.table_count, 0x2FF);
244    }
245}