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))]
56pub struct Sat<'a> {
57    /// 6-bit discriminant selecting the body structure (see [`SatTableId`]).
58    pub satellite_table_id: u8,
59    /// 10-bit sub_table discriminator (e.g. the 10 MSBs of `satellite_id`).
60    pub table_count: u16,
61    /// 5-bit sub_table version number.
62    pub version_number: u8,
63    /// When `true`, this sub_table is currently applicable.
64    pub current_next_indicator: bool,
65    /// Section number within the sub_table.
66    pub section_number: u8,
67    /// Highest section number of the sub_table.
68    pub last_section_number: u8,
69    /// Raw body bytes — interpret per [`Sat::satellite_table_id`]; layout in `docs/tables/sat.md`.
70    pub body: &'a [u8],
71}
72
73impl Sat<'_> {
74    /// Typed view of [`Sat::satellite_table_id`], or `None` if reserved (5–63).
75    #[must_use]
76    pub fn kind(&self) -> Option<SatTableId> {
77        SatTableId::try_from(self.satellite_table_id).ok()
78    }
79}
80
81impl<'a> Parse<'a> for Sat<'a> {
82    type Error = crate::error::Error;
83    fn parse(bytes: &'a [u8]) -> Result<Self> {
84        let min_len = HEADER_LEN + CRC_LEN;
85        if bytes.len() < min_len {
86            return Err(Error::BufferTooShort {
87                need: min_len,
88                have: bytes.len(),
89                what: "Sat",
90            });
91        }
92        if bytes[0] != TABLE_ID {
93            return Err(Error::UnexpectedTableId {
94                table_id: bytes[0],
95                what: "Sat",
96                expected: &[TABLE_ID],
97            });
98        }
99        let section_length = (((bytes[1] & 0x0F) as usize) << 8) | bytes[2] as usize;
100        let total = SECTION_LENGTH_PREFIX + section_length;
101        if bytes.len() < total || total < HEADER_LEN + CRC_LEN {
102            return Err(Error::SectionLengthOverflow {
103                declared: section_length,
104                available: bytes.len().saturating_sub(SECTION_LENGTH_PREFIX),
105            });
106        }
107        let satellite_table_id = bytes[3] >> 2;
108        let table_count = (((bytes[3] & 0x03) as u16) << 8) | bytes[4] as u16;
109        let version_number = (bytes[5] >> 1) & 0x1F;
110        let current_next_indicator = bytes[5] & 0x01 != 0;
111        let section_number = bytes[6];
112        let last_section_number = bytes[7];
113        // bytes[8] = reserved_zero_future_use
114        let body = &bytes[HEADER_LEN..total - CRC_LEN];
115        Ok(Sat {
116            satellite_table_id,
117            table_count,
118            version_number,
119            current_next_indicator,
120            section_number,
121            last_section_number,
122            body,
123        })
124    }
125}
126
127impl Serialize for Sat<'_> {
128    type Error = crate::error::Error;
129    fn serialized_len(&self) -> usize {
130        HEADER_LEN + self.body.len() + CRC_LEN
131    }
132    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
133        let len = self.serialized_len();
134        if buf.len() < len {
135            return Err(Error::OutputBufferTooSmall {
136                need: len,
137                have: buf.len(),
138            });
139        }
140        let section_length = (len - SECTION_LENGTH_PREFIX) as u16;
141        buf[0] = TABLE_ID;
142        // section_syntax_indicator=1, private_indicator=1, reserved=11, section_length hi nibble.
143        buf[1] = 0xF0 | ((section_length >> 8) as u8 & 0x0F);
144        buf[2] = (section_length & 0xFF) as u8;
145        buf[3] = (self.satellite_table_id << 2) | ((self.table_count >> 8) as u8 & 0x03);
146        buf[4] = (self.table_count & 0xFF) as u8;
147        // reserved=11, version_number(5), current_next_indicator(1).
148        buf[5] = 0xC0 | ((self.version_number & 0x1F) << 1) | u8::from(self.current_next_indicator);
149        buf[6] = self.section_number;
150        buf[7] = self.last_section_number;
151        buf[8] = 0x00; // reserved_zero_future_use
152        let body_end = HEADER_LEN + self.body.len();
153        buf[HEADER_LEN..body_end].copy_from_slice(self.body);
154        let crc = dvb_common::crc32_mpeg2::compute(&buf[..body_end]);
155        buf[body_end..len].copy_from_slice(&crc.to_be_bytes());
156        Ok(len)
157    }
158}
159
160impl<'a> Table<'a> for Sat<'a> {
161    const TABLE_ID: u8 = TABLE_ID;
162    const PID: u16 = PID;
163}
164
165impl<'a> crate::traits::TableDef<'a> for Sat<'a> {
166    const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(TABLE_ID, TABLE_ID)];
167    const NAME: &'static str = "SATELLITE_ACCESS";
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    /// Build a SAT section with the given discriminant + body.
175    fn build_sat(satellite_table_id: u8, table_count: u16, body: &[u8]) -> Vec<u8> {
176        let section_length = (HEADER_LEN - SECTION_LENGTH_PREFIX + body.len() + CRC_LEN) as u16;
177        let mut v = vec![
178            TABLE_ID,
179            0xF0 | ((section_length >> 8) as u8 & 0x0F),
180            (section_length & 0xFF) as u8,
181            (satellite_table_id << 2) | ((table_count >> 8) as u8 & 0x03),
182            (table_count & 0xFF) as u8,
183            0xC0 | (0x05 << 1) | 0x01, // version 5, current_next = 1
184            0x00,                      // section_number
185            0x00,                      // last_section_number
186            0x00,                      // reserved_zero_future_use
187        ];
188        v.extend_from_slice(body);
189        v.extend_from_slice(&[0, 0, 0, 0]);
190        v
191    }
192
193    #[test]
194    fn parse_position_v3_discriminant() {
195        let body = [0xAA, 0xBB, 0xCC, 0xDD];
196        let bytes = build_sat(4, 0x1A3, &body);
197        let sat = Sat::parse(&bytes).unwrap();
198        assert_eq!(sat.satellite_table_id, 4);
199        assert_eq!(sat.kind(), Some(SatTableId::PositionV3));
200        assert_eq!(sat.table_count, 0x1A3);
201        assert_eq!(sat.version_number, 5);
202        assert!(sat.current_next_indicator);
203        assert_eq!(sat.body, &body);
204    }
205
206    #[test]
207    fn reserved_discriminant_has_no_kind() {
208        let bytes = build_sat(7, 0, &[]);
209        let sat = Sat::parse(&bytes).unwrap();
210        assert_eq!(sat.satellite_table_id, 7);
211        assert_eq!(sat.kind(), None);
212    }
213
214    #[test]
215    fn parse_rejects_wrong_tag() {
216        let mut bytes = build_sat(0, 0, &[1, 2, 3]);
217        bytes[0] = 0x40;
218        assert!(matches!(
219            Sat::parse(&bytes).unwrap_err(),
220            Error::UnexpectedTableId { table_id: 0x40, .. }
221        ));
222    }
223
224    #[test]
225    fn rejects_short_buffer() {
226        assert!(matches!(
227            Sat::parse(&[0x4D, 0xF0]).unwrap_err(),
228            Error::BufferTooShort { what: "Sat", .. }
229        ));
230    }
231
232    #[test]
233    fn serialize_round_trip() {
234        let body = [0x01, 0x02, 0x03, 0x04, 0x05];
235        let bytes = build_sat(1, 0x2FF, &body);
236        let sat = Sat::parse(&bytes).unwrap();
237        let mut buf = vec![0u8; sat.serialized_len()];
238        sat.serialize_into(&mut buf).unwrap();
239        let re = Sat::parse(&buf).unwrap();
240        assert_eq!(sat, re);
241        assert_eq!(re.kind(), Some(SatTableId::CellFragment));
242        assert_eq!(re.table_count, 0x2FF);
243    }
244}