forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

bitstream.rs198 lines, 7.2 KiBHistoryRawDownload
1//! AMR-NB bitstream: RFC 4867 / 3GPP TS 26.101 IF1 (octet-aligned, "MIME/IETF storage") frame
2//! parsing into decoder parameters (wmf_to_ets + bits2prm of opencore-amr).
3#![allow(dead_code)]
4
5use super::tables::*;
6
7/// Receive frame type (C `enum RXFrameType`, same numeric order).
8#[derive(Clone, Copy, PartialEq, Eq, Debug)]
9pub enum RxFrameType {
10 SpeechGood = 0,
11 SpeechDegraded = 1,
12 Onset = 2,
13 SpeechBad = 3,
14 SidFirst = 4,
15 SidUpdate = 5,
16 SidBad = 6,
17 NoData = 7,
18}
19
20impl Mode {
21 /// Mode from index 0..=8 (8 = MrDtx).
22 #[inline]
23 pub fn from_index(i: usize) -> Option<Mode> {
24 Some(match i {
25 0 => Mode::Mr475,
26 1 => Mode::Mr515,
27 2 => Mode::Mr59,
28 3 => Mode::Mr67,
29 4 => Mode::Mr74,
30 5 => Mode::Mr795,
31 6 => Mode::Mr102,
32 7 => Mode::Mr122,
33 8 => Mode::MrDtx,
34 _ => return None,
35 })
36 }
37 /// Index 0..=8 (C enum value).
38 #[inline]
39 pub fn index(self) -> usize {
40 self as usize
41 }
42}
43
44/// Errors from frame parsing.
45#[derive(Clone, Copy, PartialEq, Eq, Debug)]
46pub enum BitstreamError {
47 /// Fewer bytes than the ToC byte + payload for this frame type.
48 Truncated,
49 /// Frame type 9..=14 (unsupported SID variants / reserved): the C decoder rejects these.
50 InvalidFrameType,
51}
52
53/// One parsed frame.
54#[derive(Clone, Debug)]
55pub struct ParsedFrame {
56 /// RX type to pass to Decoder_amr (SpeechGood for FT 0-7, SidFirst/SidUpdate for FT 8, NoData for FT 15).
57 pub frame_type: RxFrameType,
58 /// Codec mode for Decoder_amr/post-filter. FT 0-7: that mode; SID: mode indication carried in the
59 /// SID frame (0..7); NoData: `prev_mode` as passed in.
60 pub mode: Mode,
61 /// Raw frame type field (0..=15) from the ToC byte.
62 pub ft: u8,
63 /// Q (frame quality) bit from the ToC byte (opencore ignores it; informational).
64 pub q: bool,
65 /// Decoded parameters: for SID frames the 5 MRDTX parameters, else the mode's parameters.
66 /// Entries past the used count are 0. Size MAX_PRM_SIZE + 1 (as C `parm[MAX_PRM_SIZE+1]`).
67 pub prm: [i16; MAX_PRM_SIZE + 1],
68 /// Total bytes consumed from the input (1 ToC byte + payload bytes).
69 pub consumed: usize,
70}
71
72/// Payload bytes following the ToC byte for frame type `ft` (WmfDecBytesPerFrame:
73/// 12,13,15,17,19,20,26,31 for FT 0-7, 5 for SID FT 8, 0 for FT 15). `None` for FT 9..=14 or ft > 15.
74#[inline]
75pub fn frame_bytes(ft: u8) -> Option<usize> {
76 match ft {
77 0..=8 | 15 => Some(WMFDECBYTESPERFRAME[ft as usize] as usize),
78 _ => None,
79 }
80}
81
82/// C wmf_to_ets: unpack IF1 payload bits into ETS order, one bit per i16 (`ets` is zero-initialised
83/// by the caller; at most MAX_SERIAL_SIZE entries are written). `ft` in 0..=8 (8 = SID, 39 bits).
84pub fn wmf_to_ets(ft: u8, payload: &[u8], ets: &mut [i16; MAX_SERIAL_SIZE]) {
85 let n = NUMOFBITS[ft as usize] as usize;
86 let bit = |i: usize| -> i16 { ((payload[i >> 3] >> ((!i) & 7)) & 1) as i16 };
87 if ft < 8 {
88 let tab: &[i16] = match ft {
89 0 => &REORDERBITS_MR475,
90 1 => &REORDERBITS_MR515,
91 2 => &REORDERBITS_MR59,
92 3 => &REORDERBITS_MR67,
93 4 => &REORDERBITS_MR74,
94 5 => &REORDERBITS_MR795,
95 6 => &REORDERBITS_MR102,
96 _ => &REORDERBITS_MR122,
97 };
98 for i in (0..n).rev() {
99 ets[tab[i] as usize] = bit(i);
100 }
101 } else {
102 for i in (0..n).rev() {
103 ets[i] = bit(i);
104 }
105 }
106}
107
108/// C Bits2prm: ETS serial bits -> parameters (prm must hold MAX_PRM_SIZE entries).
109pub fn bits2prm(mode: Mode, bits: &[i16], prm: &mut [i16]) {
110 let (prmno, bitno): (usize, &[i16]) = match mode {
111 Mode::Mr475 => (PRMNO[0] as usize, &BITNO_MR475),
112 Mode::Mr515 => (PRMNO[1] as usize, &BITNO_MR515),
113 Mode::Mr59 => (PRMNO[2] as usize, &BITNO_MR59),
114 Mode::Mr67 => (PRMNO[3] as usize, &BITNO_MR67),
115 Mode::Mr74 => (PRMNO[4] as usize, &BITNO_MR74),
116 Mode::Mr795 => (PRMNO[5] as usize, &BITNO_MR795),
117 Mode::Mr102 => (PRMNO[6] as usize, &BITNO_MR102),
118 Mode::Mr122 => (PRMNO[7] as usize, &BITNO_MR122),
119 Mode::MrDtx => (PRMNO[8] as usize, &BITNO_MRDTX),
120 };
121 let mut pos = 0usize;
122 for i in 0..prmno {
123 let nb = bitno[i] as usize;
124 let mut v: i16 = 0;
125 for k in 0..nb {
126 v = (v << 1) | bits[pos + k];
127 }
128 prm[i] = v;
129 pos += nb;
130 }
131}
132
133/// Parse one IF1 frame at the start of `data`: ToC byte (F, FT(4), Q, 2 pad bits) followed by the
134/// payload. Follows opencore AMRDecode(MIME_IETF): the F bit and Q bit do not alter decoding;
135/// FT 9..=14 is an error; FT 15 yields NoData with mode `prev_mode`; FT 8 yields SidFirst
136/// (STI bit 35 == 0) or SidUpdate (STI == 1) with the mode taken from bits 36..38 (LSB first).
137/// For decoding feed `frame_type`, `mode` and `prm` to Decoder_amr (post filter uses `mode`).
138/// The glue should remember `mode` as the next `prev_mode`.
139pub fn parse_frame(data: &[u8], prev_mode: Mode) -> Result<ParsedFrame, BitstreamError> {
140 let hdr = *data.first().ok_or(BitstreamError::Truncated)?;
141 let ft = (hdr >> 3) & 0x0f;
142 let q = (hdr & 0x04) != 0;
143 let nbytes = frame_bytes(ft).ok_or(BitstreamError::InvalidFrameType)?;
144 if data.len() < 1 + nbytes {
145 return Err(BitstreamError::Truncated);
146 }
147 let payload = &data[1..1 + nbytes];
148 let mut prm = [0i16; MAX_PRM_SIZE + 1];
149 let mut ets = [0i16; MAX_SERIAL_SIZE];
150 let (frame_type, mode);
151 if ft <= 7 {
152 mode = Mode::from_index(ft as usize).unwrap();
153 frame_type = RxFrameType::SpeechGood;
154 wmf_to_ets(ft, payload, &mut ets);
155 bits2prm(mode, &ets, &mut prm);
156 } else if ft == 8 {
157 wmf_to_ets(ft, payload, &mut ets);
158 let m = ets[36] as usize | ((ets[37] as usize) << 1) | ((ets[38] as usize) << 2);
159 mode = Mode::from_index(m).unwrap();
160 frame_type = if ets[35] == 0 { RxFrameType::SidFirst } else { RxFrameType::SidUpdate };
161 bits2prm(Mode::MrDtx, &ets, &mut prm);
162 } else {
163 mode = prev_mode;
164 frame_type = RxFrameType::NoData;
165 }
166 Ok(ParsedFrame { frame_type, mode, ft, q, prm, consumed: 1 + nbytes })
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 #[test]
174 fn sizes() {
175 assert_eq!(frame_bytes(7), Some(31));
176 assert_eq!(frame_bytes(8), Some(5));
177 assert_eq!(frame_bytes(15), Some(0));
178 assert_eq!(frame_bytes(10), None);
179 // (bits + 7) / 8 for each mode
180 for ft in 0..8usize {
181 assert_eq!((NUMOFBITS[ft] as usize + 7) / 8, WMFDECBYTESPERFRAME[ft] as usize);
182 }
183 }
184
185 #[test]
186 fn parse_mr122_zero_and_nodata() {
187 let f = [7u8 << 3 | 4; 32];
188 let p = parse_frame(&f, Mode::Mr475).unwrap();
189 assert_eq!(p.frame_type, RxFrameType::SpeechGood);
190 assert_eq!(p.mode, Mode::Mr122);
191 assert_eq!(p.consumed, 32);
192 let p = parse_frame(&[15 << 3], Mode::Mr67).unwrap();
193 assert_eq!(p.frame_type, RxFrameType::NoData);
194 assert_eq!(p.mode, Mode::Mr67);
195 assert_eq!(parse_frame(&[9 << 3], Mode::Mr67).unwrap_err(), BitstreamError::InvalidFrameType);
196 assert_eq!(parse_frame(&[7 << 3, 0], Mode::Mr67).unwrap_err(), BitstreamError::Truncated);
197 }
198}