forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

container.rs319 lines, 9.9 KiBHistoryRawDownload
1//! The raw `.amr` / `.awb` storage format (RFC 4867 section 5): a magic line,
2//! then one frame after another, each a table-of-contents byte followed by the
3//! speech bits.
4//!
5//! Packets keep the ToC byte in front of the payload, which is also the form the
6//! decoders take, so a packet is exactly one stored frame.
7
8use std::io::{Read, Seek, SeekFrom};
9
10use ec_core::error::{Error, Result};
11use ec_core::frame::ChannelLayout;
12use ec_core::packet::{Buf, Packet, PacketFlags};
13use ec_core::registry::{
14 AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, SeekMode, StreamInfo,
15};
16use ec_core::timebase::{Rounding, TimeBase, Timestamp};
17
18/// Magic of a narrowband file.
19pub const MAGIC_NB: &[u8] = b"#!AMR\n";
20/// Magic of a wideband file.
21pub const MAGIC_WB: &[u8] = b"#!AMR-WB\n";
22
23/// Narrowband or wideband.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum Kind {
26 /// AMR-NB: 8 kHz, 160 samples per frame.
27 Nb,
28 /// AMR-WB: 16 kHz, 320 samples per frame.
29 Wb,
30}
31
32impl Kind {
33 /// Sample rate in Hz.
34 pub fn sample_rate(self) -> u32 {
35 match self {
36 Kind::Nb => 8000,
37 Kind::Wb => 16000,
38 }
39 }
40
41 /// Samples in one 20 ms frame.
42 pub fn frame_samples(self) -> i64 {
43 match self {
44 Kind::Nb => 160,
45 Kind::Wb => 320,
46 }
47 }
48
49 /// The codec carried.
50 pub fn codec(self) -> CodecId {
51 match self {
52 Kind::Nb => CodecId::AmrNb,
53 Kind::Wb => CodecId::AmrWb,
54 }
55 }
56
57 /// The file magic.
58 pub fn magic(self) -> &'static [u8] {
59 match self {
60 Kind::Nb => MAGIC_NB,
61 Kind::Wb => MAGIC_WB,
62 }
63 }
64}
65
66/// The kind of file `buf` opens as, by its magic.
67pub fn probe(buf: &[u8]) -> Option<Kind> {
68 if buf.starts_with(MAGIC_WB) {
69 Some(Kind::Wb)
70 } else if buf.starts_with(MAGIC_NB) {
71 Some(Kind::Nb)
72 } else {
73 None
74 }
75}
76
77/// Payload bytes (after the ToC byte) of an AMR-NB frame of type `ft`.
78pub fn nb_frame_size(ft: u8) -> Result<usize> {
79 const SIZES: [usize; 9] = [12, 13, 15, 17, 19, 20, 26, 31, 5];
80 match ft {
81 0..=8 => Ok(SIZES[usize::from(ft)]),
82 15 => Ok(0),
83 _ => Err(Error::corrupt(format!("AMR-NB frame type {ft} is reserved"))),
84 }
85}
86
87/// Payload bytes (after the ToC byte) of an AMR-WB frame of type `ft`.
88pub fn wb_frame_size(ft: u8) -> Result<usize> {
89 const SIZES: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5];
90 match ft {
91 0..=9 => Ok(SIZES[usize::from(ft)]),
92 14 | 15 => Ok(0),
93 _ => Err(Error::corrupt(format!("AMR-WB frame type {ft} is reserved"))),
94 }
95}
96
97/// Payload bytes of a frame of type `ft` in `kind`.
98pub fn frame_size(kind: Kind, ft: u8) -> Result<usize> {
99 match kind {
100 Kind::Nb => nb_frame_size(ft),
101 Kind::Wb => wb_frame_size(ft),
102 }
103}
104
105/// Reads as many bytes as available; returns the count.
106fn read_upto(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
107 let mut n = 0;
108 while n < buf.len() {
109 match r.read(&mut buf[n..]) {
110 Ok(0) => break,
111 Ok(k) => n += k,
112 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
113 Err(e) => return Err(e.into()),
114 }
115 }
116 Ok(n)
117}
118
119/// A demuxer for `.amr` / `.awb` files.
120pub struct AmrDemuxer<R> {
121 r: R,
122 kind: Kind,
123 streams: Vec<StreamInfo>,
124 /// Offset of the first frame.
125 start: u64,
126 /// Index of the next frame.
127 next: u64,
128 /// Offset of the next frame.
129 pos: u64,
130 /// Frame offsets, built on the first seek.
131 index: Option<Vec<u64>>,
132}
133
134impl<R: Read + Seek + Send> AmrDemuxer<R> {
135 /// Open a file positioned at its magic.
136 pub fn new(mut r: R) -> Result<AmrDemuxer<R>> {
137 let mut head = [0u8; MAGIC_WB.len()];
138 let n = read_upto(&mut r, &mut head)?;
139 let kind = probe(&head[..n]).ok_or_else(|| Error::corrupt("not an AMR storage file"))?;
140 // Fails with Unsupported while a kind's frame table is missing.
141 frame_size(kind, 0)?;
142 let start = kind.magic().len() as u64;
143 r.seek(SeekFrom::Start(start))?;
144 let mut audio = AudioParameters {
145 sample_rate: kind.sample_rate(),
146 layout: ChannelLayout::Mono,
147 ..AudioParameters::default()
148 };
149 audio.bits_per_sample = None;
150 let mut params = CodecParameters::new(kind.codec());
151 params.media = MediaParameters::Audio(audio);
152 let streams = vec![StreamInfo::new(0, TimeBase::from_rate(kind.sample_rate()), params)];
153 Ok(AmrDemuxer { r, kind, streams, start, next: 0, pos: start, index: None })
154 }
155
156 /// Which flavour was opened.
157 pub fn kind(&self) -> Kind {
158 self.kind
159 }
160
161 /// Read the ToC at the current position and its frame; `Ok(None)` at a clean or truncated end.
162 fn read_frame(&mut self) -> Result<Option<Vec<u8>>> {
163 let mut toc = [0u8; 1];
164 if read_upto(&mut self.r, &mut toc)? == 0 {
165 return Ok(None);
166 }
167 let ft = (toc[0] >> 3) & 0x0F;
168 let size = match frame_size(self.kind, ft) {
169 Ok(s) => s,
170 Err(e) => {
171 self.pos += 1;
172 return Err(e);
173 }
174 };
175 let mut data = vec![0u8; 1 + size];
176 data[0] = toc[0];
177 if read_upto(&mut self.r, &mut data[1..])? < size {
178 return Ok(None);
179 }
180 self.pos += 1 + size as u64;
181 Ok(Some(data))
182 }
183
184 fn build_index(&mut self) -> Result<()> {
185 if self.index.is_some() {
186 return Ok(());
187 }
188 let mut offsets = Vec::new();
189 let mut pos = self.start;
190 let mut toc = [0u8; 1];
191 let len = self.r.seek(SeekFrom::End(0))?;
192 loop {
193 self.r.seek(SeekFrom::Start(pos))?;
194 if read_upto(&mut self.r, &mut toc)? == 0 {
195 break;
196 }
197 let Ok(size) = frame_size(self.kind, (toc[0] >> 3) & 0x0F) else {
198 pos += 1;
199 continue;
200 };
201 let end = pos + 1 + size as u64;
202 if end > len {
203 break;
204 }
205 offsets.push(pos);
206 pos = end;
207 }
208 self.index = Some(offsets);
209 Ok(())
210 }
211}
212
213impl<R: Read + Seek + Send> Demuxer for AmrDemuxer<R> {
214 fn streams(&self) -> &[StreamInfo] {
215 &self.streams
216 }
217
218 fn next_packet(&mut self) -> Result<Packet> {
219 let Some(data) = self.read_frame()? else {
220 return Err(Error::Eof);
221 };
222 let samples = self.kind.frame_samples();
223 let mut p = Packet::new(0, TimeBase::from_rate(self.kind.sample_rate()), Buf::from_vec(data))
224 .with_pts(self.next as i64 * samples)
225 .with_duration(samples);
226 p.dts = p.pts;
227 p.flags = PacketFlags { keyframe: true, ..PacketFlags::default() };
228 self.next += 1;
229 Ok(p)
230 }
231
232 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
233 if stream != 0 {
234 return Err(Error::corrupt(format!("no stream {stream}")));
235 }
236 self.build_index()?;
237 let base = TimeBase::from_rate(self.kind.sample_rate());
238 let samples = self.kind.frame_samples();
239 let rounding = match mode {
240 SeekMode::SyncAfter => Rounding::Up,
241 _ => Rounding::Down,
242 };
243 let ticks = to.base.rescale(to.ticks, base, rounding).max(0);
244 let mut frame = match mode {
245 SeekMode::SyncAfter => (ticks + samples - 1) / samples,
246 _ => ticks / samples,
247 } as usize;
248 let index = self.index.as_ref().map_or(&[][..], |v| v.as_slice());
249 frame = frame.min(index.len());
250 let offset = index.get(frame).copied();
251 match offset {
252 Some(o) => self.pos = o,
253 None => {
254 // Past the last frame: land at the end of the last one.
255 self.pos = index.last().map_or(self.start, |_| u64::MAX);
256 }
257 }
258 if self.pos == u64::MAX {
259 self.r.seek(SeekFrom::End(0))?;
260 } else {
261 self.r.seek(SeekFrom::Start(self.pos))?;
262 }
263 self.next = frame as u64;
264 Ok(())
265 }
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271 use std::io::Cursor;
272
273 fn file(frames: &[u8]) -> Vec<u8> {
274 let mut v = MAGIC_NB.to_vec();
275 v.extend_from_slice(frames);
276 v
277 }
278
279 #[test]
280 fn reads_frames_and_stops_at_truncation() {
281 // mode 0 (12 bytes), SID (5 bytes), no-data, then a truncated mode 7.
282 let mut f = vec![0x04];
283 f.extend([1u8; 12]);
284 f.push(0x44);
285 f.extend([2u8; 5]);
286 f.push(0x7C);
287 f.extend([0x3C, 9, 9]);
288 let mut d = AmrDemuxer::new(Cursor::new(file(&f))).unwrap();
289 assert_eq!(d.next_packet().unwrap().data.len(), 13);
290 let p = d.next_packet().unwrap();
291 assert_eq!((p.data.len(), p.pts), (6, Some(160)));
292 assert_eq!(d.next_packet().unwrap().data.len(), 1);
293 assert!(d.next_packet().unwrap_err().is_eof());
294 }
295
296 #[test]
297 fn reserved_type_errors_and_wb_probes() {
298 let mut d = AmrDemuxer::new(Cursor::new(file(&[0x4C, 0x04]))).unwrap();
299 assert!(matches!(d.next_packet(), Err(Error::Corrupt { .. })));
300 assert!(AmrDemuxer::new(Cursor::new(b"#!AMR-WB\n".to_vec())).is_ok());
301 assert_eq!(wb_frame_size(8).unwrap(), 60);
302 assert_eq!(wb_frame_size(9).unwrap(), 5);
303 assert!(wb_frame_size(11).is_err());
304 assert_eq!(probe(b"#!AMR-WB\nxx"), Some(Kind::Wb));
305 }
306
307 #[test]
308 fn seek_lands_on_frame() {
309 let mut f = Vec::new();
310 for i in 0..5u8 {
311 f.push(0x04);
312 f.extend([i; 12]);
313 }
314 let mut d = AmrDemuxer::new(Cursor::new(file(&f))).unwrap();
315 d.seek(0, Timestamp::new(350, TimeBase::from_rate(8000)), SeekMode::SyncBefore).unwrap();
316 let p = d.next_packet().unwrap();
317 assert_eq!((p.pts, p.data[1]), (Some(320), 2));
318 }
319}