openipc-core 0.1.20

Shared OpenIPC FPV packet, RTP, and Realtek RX parsing logic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/// Size of a Realtek USB RX descriptor before any PHY status and payload bytes.
pub const RX_DESC_SIZE: usize = 24;
/// Default native USB bulk-IN transfer size used by the receiver.
pub const DEFAULT_RX_TRANSFER_SIZE: usize = 32 * 1024;

/// Type of packet carried by a Realtek RX descriptor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RxPacketType {
    /// Normal received 802.11 frame.
    NormalRx,
    /// Command-to-host report generated by the chip firmware.
    C2hPacket,
}

/// Parsed metadata from a Realtek USB RX descriptor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RxPacketAttrib {
    /// Number of payload bytes following descriptor, PHY status, and shift bytes.
    pub pkt_len: u16,
    /// Whether PHY status bytes are present after the descriptor.
    pub physt: bool,
    /// Driver-info/PHY-status byte count.
    pub drvinfo_sz: u8,
    /// Extra alignment shift before payload bytes.
    pub shift_sz: u8,
    /// Whether the original 802.11 frame had QoS metadata.
    pub qos: bool,
    /// Realtek priority field.
    pub priority: u8,
    /// More-data bit from the descriptor.
    pub mdata: bool,
    /// 802.11 sequence number reported by the descriptor.
    pub seq_num: u16,
    /// 802.11 fragment number reported by the descriptor.
    pub frag_num: u8,
    /// More-fragments bit from the descriptor.
    pub mfrag: bool,
    /// Whether the chip reports the packet as decrypted.
    pub bdecrypted: bool,
    /// Realtek encryption type field.
    pub encrypt: u8,
    /// Hardware-reported CRC/FCS failure.
    pub crc_err: bool,
    /// Hardware-reported ICV failure.
    pub icv_err: bool,
    /// TSF low timestamp from the descriptor.
    pub tsfl: u32,
    /// Realtek data-rate code.
    pub data_rate: u8,
    /// Realtek bandwidth code.
    pub bw: u8,
    /// STBC flag from PHY status.
    pub stbc: u8,
    /// LDPC flag from PHY status.
    pub ldpc: u8,
    /// Short guard interval flag from PHY status.
    pub sgi: u8,
    /// Scrambler seed from PHY status.
    pub scrambler: u8,
    /// Per-path raw RSSI readings when available.
    pub rssi: [u8; 4],
    /// Per-path raw SNR readings when available.
    pub snr: [i8; 4],
    /// Per-path raw EVM readings when available.
    pub evm: [i8; 4],
    /// Whether this descriptor carries a received frame or a C2H report.
    pub pkt_rpt_type: RxPacketType,
}

impl Default for RxPacketAttrib {
    fn default() -> Self {
        Self {
            pkt_len: 0,
            physt: false,
            drvinfo_sz: 0,
            shift_sz: 0,
            qos: false,
            priority: 0,
            mdata: false,
            seq_num: 0,
            frag_num: 0,
            mfrag: false,
            bdecrypted: false,
            encrypt: 0,
            crc_err: false,
            icv_err: false,
            tsfl: 0,
            data_rate: 0,
            bw: 0,
            stbc: 0,
            ldpc: 0,
            sgi: 0,
            scrambler: 0,
            rssi: [0; 4],
            snr: [0; 4],
            evm: [0; 4],
            pkt_rpt_type: RxPacketType::NormalRx,
        }
    }
}

/// One packet extracted from a Realtek USB RX aggregate.
#[derive(Debug, Clone, Copy)]
pub struct RealtekRxPacket<'a> {
    /// Parsed descriptor metadata.
    pub attrib: RxPacketAttrib,
    /// Borrowed packet bytes after descriptor, PHY status, and alignment shift.
    pub data: &'a [u8],
}

/// Parsed command-to-host report carried in an RX aggregate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct C2hPacket<'a> {
    /// Firmware command/report identifier.
    pub cmd_id: u8,
    /// Optional sequence byte when the report includes one.
    pub seq: Option<u8>,
    /// Remaining C2H payload bytes.
    pub payload: &'a [u8],
}

/// RTL8814A transmit status report extracted from a C2H packet.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TxStatusReport8814 {
    /// Offset at which this report was found in the C2H payload.
    pub header_offset: usize,
    /// Hardware queue selector.
    pub queue_select: u8,
    /// Whether the transmitted packet was broadcast.
    pub packet_broadcast: bool,
    /// Whether the packet exceeded the lifetime limit.
    pub lifetime_over: bool,
    /// Whether the packet exceeded the retry limit.
    pub retry_over: bool,
    /// MAC ID associated with the report.
    pub mac_id: u8,
    /// Number of data retries reported by hardware.
    pub data_retry_count: u8,
    /// Queue residency time in microseconds.
    pub queue_time_us: u32,
    /// Final data-rate code used by hardware.
    pub final_data_rate: u8,
}

/// Error returned while parsing Realtek RX aggregates.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AggregateError {
    /// Fewer than `RX_DESC_SIZE` bytes were available for a descriptor.
    DescriptorTooShort,
    /// Descriptor payload length points beyond the remaining aggregate bytes.
    InvalidPacketLength {
        /// Packet length read from descriptor.
        pkt_len: u16,
        /// Descriptor + metadata + packet offset implied by the descriptor.
        pkt_offset: usize,
        /// Bytes remaining in the aggregate at the current descriptor.
        remaining: usize,
    },
}

impl std::fmt::Display for AggregateError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DescriptorTooShort => write!(f, "RX descriptor is shorter than {RX_DESC_SIZE} bytes"),
            Self::InvalidPacketLength {
                pkt_len,
                pkt_offset,
                remaining,
            } => write!(
                f,
                "invalid RX packet length: pkt_len={pkt_len}, pkt_offset={pkt_offset}, remaining={remaining}"
            ),
        }
    }
}

impl std::error::Error for AggregateError {}

/// Parse a single Realtek RX descriptor.
pub fn parse_rx_descriptor(desc: &[u8]) -> Result<RxPacketAttrib, AggregateError> {
    if desc.len() < RX_DESC_SIZE {
        return Err(AggregateError::DescriptorTooShort);
    }

    let d0 = le32(desc, 0);
    let d1 = le32(desc, 4);
    let d2 = le32(desc, 8);
    let d3 = le32(desc, 12);
    let d4 = le32(desc, 16);
    let d5 = le32(desc, 20);

    Ok(RxPacketAttrib {
        pkt_len: bits(d0, 0, 14) as u16,
        crc_err: bits(d0, 14, 1) != 0,
        icv_err: bits(d0, 15, 1) != 0,
        drvinfo_sz: (bits(d0, 16, 4) * 8) as u8,
        encrypt: bits(d0, 20, 3) as u8,
        qos: bits(d0, 23, 1) != 0,
        shift_sz: bits(d0, 24, 2) as u8,
        physt: bits(d0, 26, 1) != 0,
        bdecrypted: bits(d0, 27, 1) == 0,
        priority: bits(d1, 8, 4) as u8,
        mdata: bits(d1, 26, 1) != 0,
        mfrag: bits(d1, 27, 1) != 0,
        seq_num: bits(d2, 0, 12) as u16,
        frag_num: bits(d2, 12, 4) as u8,
        pkt_rpt_type: if bits(d2, 28, 1) != 0 {
            RxPacketType::C2hPacket
        } else {
            RxPacketType::NormalRx
        },
        data_rate: bits(d3, 0, 7) as u8,
        sgi: bits(d4, 0, 1) as u8,
        ldpc: bits(d4, 1, 1) as u8,
        stbc: bits(d4, 2, 1) as u8,
        bw: bits(d4, 4, 2) as u8,
        scrambler: bits(d4, 9, 7) as u8,
        tsfl: d5,
        ..Default::default()
    })
}

/// Split a Realtek USB bulk-IN transfer into packet descriptors and payloads.
///
/// Realtek devices aggregate one or more RX descriptors into each USB transfer.
/// Each returned packet borrows from `buf`, so callers can parse metadata without
/// copying frame bytes.
pub fn parse_rx_aggregate(buf: &[u8]) -> Result<Vec<RealtekRxPacket<'_>>, AggregateError> {
    let mut packets = Vec::new();
    let mut offset = 0usize;

    while offset < buf.len() {
        let remaining = buf.len() - offset;
        if remaining < RX_DESC_SIZE {
            break;
        }

        let desc = &buf[offset..offset + RX_DESC_SIZE];
        let mut attrib = parse_rx_descriptor(desc)?;
        let data_start =
            offset + RX_DESC_SIZE + attrib.drvinfo_sz as usize + attrib.shift_sz as usize;
        let pkt_offset = RX_DESC_SIZE
            + attrib.drvinfo_sz as usize
            + attrib.shift_sz as usize
            + attrib.pkt_len as usize;
        if attrib.pkt_len == 0 || pkt_offset > remaining {
            return Err(AggregateError::InvalidPacketLength {
                pkt_len: attrib.pkt_len,
                pkt_offset,
                remaining,
            });
        }

        if attrib.pkt_rpt_type == RxPacketType::NormalRx {
            let phy_start = offset + RX_DESC_SIZE;
            let phy_end = phy_start + attrib.drvinfo_sz as usize;
            parse_phy_status(&mut attrib, &buf[phy_start..phy_end]);
        }

        let data_end = data_start + attrib.pkt_len as usize;
        packets.push(RealtekRxPacket {
            attrib,
            data: &buf[data_start..data_end],
        });

        let aligned = round_up_8(pkt_offset);
        if aligned >= remaining {
            break;
        }
        offset += aligned;
    }

    Ok(packets)
}

/// Parse a C2H report header from a Realtek RX packet payload.
pub fn parse_c2h_packet(data: &[u8]) -> Option<C2hPacket<'_>> {
    let (&cmd_id, rest) = data.split_first()?;
    let seq = rest.first().copied();
    let payload = if rest.len() > 1 { &rest[1..] } else { rest };
    Some(C2hPacket {
        cmd_id,
        seq,
        payload,
    })
}

/// Parse RTL8814A TX status reports from a C2H payload.
pub fn parse_8814_tx_status_reports(data: &[u8]) -> Vec<TxStatusReport8814> {
    [1usize, 2usize]
        .into_iter()
        .filter_map(|offset| parse_8814_tx_status_report_at(data, offset))
        .collect()
}

/// Parse one RTL8814A TX status report at a known payload offset.
pub fn parse_8814_tx_status_report_at(
    data: &[u8],
    header_offset: usize,
) -> Option<TxStatusReport8814> {
    let h = data.get(header_offset..header_offset + 6)?;
    let queue_time_raw = u16::from_le_bytes([h[3], h[4]]);
    Some(TxStatusReport8814 {
        header_offset,
        queue_select: h[0] & 0x1f,
        packet_broadcast: h[0] & (1 << 5) != 0,
        lifetime_over: h[0] & (1 << 6) != 0,
        retry_over: h[0] & (1 << 7) != 0,
        mac_id: h[1],
        data_retry_count: h[2] & 0x3f,
        queue_time_us: u32::from(queue_time_raw) * 256,
        final_data_rate: h[5],
    })
}

const fn round_up_8(value: usize) -> usize {
    (value + 7) & !7
}

fn le32(bytes: &[u8], offset: usize) -> u32 {
    u32::from_le_bytes(
        bytes[offset..offset + 4]
            .try_into()
            .expect("descriptor length checked"),
    )
}

const fn bits(word: u32, offset: u8, len: u8) -> u32 {
    if len == 32 {
        word
    } else {
        (word >> offset) & ((1u32 << len) - 1)
    }
}

fn parse_phy_status(attrib: &mut RxPacketAttrib, phy: &[u8]) {
    if phy.len() < 2 {
        return;
    }

    attrib.rssi[0] = phy[0];
    attrib.rssi[1] = phy[1];

    if phy.len() < 28 {
        return;
    }

    attrib.rssi[2] = phy[23];
    attrib.rssi[3] = phy[24];
    attrib.snr[0] = phy[15] as i8;
    attrib.snr[1] = phy[16] as i8;
    attrib.snr[2] = phy[21] as i8;
    attrib.snr[3] = phy[22] as i8;
    attrib.evm[0] = phy[13] as i8;
    attrib.evm[1] = phy[14] as i8;
    attrib.evm[2] = phy[19] as i8;
    attrib.evm[3] = phy[20] as i8;
}

#[cfg(test)]
mod tests {
    use super::*;

    fn put_bits(word: &mut u32, offset: u8, len: u8, value: u32) {
        let mask = ((1u32 << len) - 1) << offset;
        *word = (*word & !mask) | ((value << offset) & mask);
    }

    fn descriptor(pkt_len: u16, drvinfo_units: u8, shift: u8, seq: u16) -> [u8; RX_DESC_SIZE] {
        let mut desc = [0; RX_DESC_SIZE];
        let mut d0 = 0u32;
        put_bits(&mut d0, 0, 14, pkt_len as u32);
        put_bits(&mut d0, 16, 4, drvinfo_units as u32);
        put_bits(&mut d0, 24, 2, shift as u32);
        let mut d2 = 0u32;
        put_bits(&mut d2, 0, 12, seq as u32);
        desc[0..4].copy_from_slice(&d0.to_le_bytes());
        desc[8..12].copy_from_slice(&d2.to_le_bytes());
        desc
    }

    #[test]
    fn parses_single_rx_packet() {
        let mut aggregate = Vec::new();
        aggregate.extend_from_slice(&descriptor(4, 0, 0, 77));
        aggregate.extend_from_slice(&[1, 2, 3, 4]);

        let packets = parse_rx_aggregate(&aggregate).unwrap();
        assert_eq!(packets.len(), 1);
        assert_eq!(packets[0].attrib.pkt_len, 4);
        assert_eq!(packets[0].attrib.seq_num, 77);
        assert_eq!(packets[0].data, &[1, 2, 3, 4]);
    }

    #[test]
    fn parses_c2h_packet_header() {
        let packet = parse_c2h_packet(&[0x42, 0x7f, 1, 2]).unwrap();
        assert_eq!(packet.cmd_id, 0x42);
        assert_eq!(packet.seq, Some(0x7f));
        assert_eq!(packet.payload, &[1, 2]);
    }

    #[test]
    fn parses_8814_tx_status_at_devourer_offsets() {
        let bytes = [0xaa, 0x83, 0x09, 0x25, 0x34, 0x12, 0x6c, 0xbb];
        let reports = parse_8814_tx_status_reports(&bytes);
        assert_eq!(reports.len(), 2);
        assert_eq!(reports[0].header_offset, 1);
        assert_eq!(reports[0].queue_select, 3);
        assert!(reports[0].retry_over);
        assert_eq!(reports[0].mac_id, 9);
        assert_eq!(reports[0].data_retry_count, 0x25);
        assert_eq!(reports[0].queue_time_us, 0x1234 * 256);
        assert_eq!(reports[0].final_data_rate, 0x6c);
    }

    #[test]
    fn advances_by_jaguar_eight_byte_alignment() {
        let mut aggregate = Vec::new();
        aggregate.extend_from_slice(&descriptor(5, 0, 0, 1));
        aggregate.extend_from_slice(&[1, 2, 3, 4, 5]);
        aggregate.extend_from_slice(&[0, 0, 0]);
        aggregate.extend_from_slice(&descriptor(3, 0, 0, 2));
        aggregate.extend_from_slice(&[6, 7, 8]);

        let packets = parse_rx_aggregate(&aggregate).unwrap();
        assert_eq!(packets.len(), 2);
        assert_eq!(packets[0].data, &[1, 2, 3, 4, 5]);
        assert_eq!(packets[1].data, &[6, 7, 8]);
    }
}