forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB052d1d3Tahinli2 months ago3627 commits

raw.rs401 lines, 13.8 KiBHistoryRawDownload
1//! The four formats that are a codec and nothing else: WAV, MP3, FLAC and
2//! ADTS. One demuxer serves all four, because they differ only in how a frame
3//! states its own length — everything after that (the packet stream, the frame
4//! index, sample-accurate seeking) is the same walk.
5//!
6//! Framing comes from the codec crates rather than being re-derived here:
7//! [`ec_mp3::FrameHeader`], [`ec_flac::decode::find_frame_sync`] and
8//! [`ec_aac::parse_adts`] each already know their own header.
9
10use std::io::{Read, Seek, SeekFrom};
11
12use ec_core::error::{Error, Result};
13use ec_core::frame::{ChannelLayout, SampleFormat};
14use ec_core::packet::{Buf, Packet, PacketFlags};
15use ec_core::registry::{
16 AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters, SeekMode, StreamInfo,
17};
18use ec_core::timebase::{Rounding, TimeBase, Timestamp};
19
20/// Bytes read per refill.
21const CHUNK: usize = 64 << 10;
22/// Consumed bytes tolerated in front of the window before it is compacted.
23const COMPACT_AT: usize = 256 << 10;
24/// Frames of PCM in one WAV packet: big enough that a packet is not a syscall
25/// per millisecond, small enough to seek inside without decoding a second.
26const WAV_FRAMES: usize = 4096;
27
28/// How a format states the length of one frame.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub(crate) enum Kind {
31 /// Fixed-size PCM: a "frame" is one interleaved sample.
32 Wav {
33 block_align: usize,
34 },
35 Mp3,
36 Flac,
37 Adts,
38}
39
40/// A frame's byte length and how many inter-channel samples it holds.
41struct Framing {
42 bytes: usize,
43 samples: u64,
44}
45
46/// One elementary audio stream read straight out of a file.
47pub(crate) struct RawDemuxer<R> {
48 r: R,
49 kind: Kind,
50 streams: Vec<StreamInfo>,
51 /// Offset of the first frame and one past the last audio byte.
52 start: u64,
53 end: u64,
54 /// Offset the window starts at, and the file offset the reader itself sits
55 /// at (window end).
56 pos: u64,
57 read_at: u64,
58 buf: Vec<u8>,
59 head: usize,
60 /// Next packet's first sample, in the stream's own time base.
61 sample: u64,
62 rate: u32,
63 /// `STREAMINFO`, needed to read a FLAC frame header.
64 flac: Option<ec_flac::StreamInfo>,
65 /// `(first sample, offset)` per frame, built on the first seek.
66 index: Vec<(u64, u64)>,
67 indexed: bool,
68}
69
70impl<R: Read + Seek> RawDemuxer<R> {
71 pub(crate) fn new(
72 mut r: R,
73 kind: Kind,
74 params: CodecParameters,
75 start: u64,
76 end: u64,
77 total_samples: Option<u64>,
78 flac: Option<ec_flac::StreamInfo>,
79 ) -> Result<RawDemuxer<R>> {
80 let rate = params
81 .audio()
82 .map(|a| a.sample_rate)
83 .filter(|r| *r > 0)
84 .ok_or_else(|| Error::corrupt("a raw audio stream with no sample rate"))?;
85 let mut info = StreamInfo::new(0, TimeBase::from_rate(rate), params);
86 info.start_time = Some(0);
87 info.duration = total_samples.map(|n| n as i64);
88 r.seek(SeekFrom::Start(start))?;
89 Ok(RawDemuxer {
90 r,
91 kind,
92 streams: vec![info],
93 start,
94 end,
95 pos: start,
96 read_at: start,
97 buf: Vec::with_capacity(CHUNK),
98 head: 0,
99 sample: 0,
100 rate,
101 flac,
102 index: Vec::new(),
103 indexed: false,
104 })
105 }
106
107 /// State that this stream opens with `samples` a decoder emits before the
108 /// first audible one ([`StreamInfo::initial_padding`]).
109 pub(crate) fn with_initial_padding(mut self, samples: u32) -> RawDemuxer<R> {
110 self.streams[0].initial_padding = samples;
111 self
112 }
113
114 /// Samples in a typical frame of this format, for the tail of an estimate.
115 fn frame_samples(&self) -> u64 {
116 match self.kind {
117 Kind::Wav { .. } => WAV_FRAMES as u64,
118 Kind::Mp3 => 1152,
119 Kind::Flac => self
120 .flac
121 .as_ref()
122 .map_or(4096, |i| u64::from(i.max_block_size)),
123 Kind::Adts => 1024,
124 }
125 }
126
127 /// At least `want` bytes in the window, or fewer at the end of the stream.
128 fn fill(&mut self, want: usize) -> Result<()> {
129 if self.head > COMPACT_AT {
130 self.buf.drain(..self.head);
131 self.pos += self.head as u64;
132 self.head = 0;
133 }
134 while self.buf.len() - self.head < want && self.read_at < self.end {
135 let chunk = CHUNK.min((self.end - self.read_at) as usize);
136 let at = self.buf.len();
137 self.buf.resize(at + chunk, 0);
138 let mut got = 0;
139 while got < chunk {
140 match self.r.read(&mut self.buf[at + got..]) {
141 Ok(0) => break,
142 Ok(n) => got += n,
143 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
144 Err(e) => return Err(Error::Io(e)),
145 }
146 }
147 self.buf.truncate(at + got);
148 self.read_at += got as u64;
149 if got == 0 {
150 break;
151 }
152 }
153 Ok(())
154 }
155
156 /// The unread bytes of the window.
157 fn window(&self) -> &[u8] {
158 &self.buf[self.head..]
159 }
160
161 /// Where the window's head sits in the file.
162 fn offset(&self) -> u64 {
163 self.pos + self.head as u64
164 }
165
166 /// Drop the window and resume reading at `offset`.
167 fn jump(&mut self, offset: u64) -> Result<()> {
168 self.r.seek(SeekFrom::Start(offset))?;
169 self.buf.clear();
170 self.head = 0;
171 self.pos = offset;
172 self.read_at = offset;
173 Ok(())
174 }
175
176 /// The frame at the window's head, or [`Error::Eof`] at the end.
177 ///
178 /// Resyncs over junk: a byte that does not open a frame is skipped, which
179 /// is what carries a reader over an ID3 tag in the middle of a stream or a
180 /// scrap of a torn download.
181 fn framing(&mut self) -> Result<Framing> {
182 let want = match self.kind {
183 Kind::Wav { block_align } => block_align * WAV_FRAMES,
184 // A FLAC frame is bounded by the *next* sync word, so the window
185 // has to hold a whole one plus the head of its successor.
186 Kind::Flac => 1 << 20,
187 _ => 8192,
188 };
189 let flac = self.flac.clone();
190 let kind = self.kind;
191 let mut skipped = 0u64;
192 loop {
193 self.fill(want)?;
194 let left = self.window().len();
195 if left == 0 {
196 return Err(Error::Eof);
197 }
198 let tail = self.read_at >= self.end;
199 match frame_at(kind, self.window(), flac.as_ref()) {
200 Ok(f) => return Ok(f),
201 Err(e) if e.is_need_more() && tail => {
202 // The tail of a file: whatever is left is the last frame.
203 return Ok(Framing {
204 bytes: left,
205 samples: self.frame_samples(),
206 });
207 }
208 Err(_) if skipped < (1 << 20) => {
209 self.head += 1;
210 skipped += 1;
211 }
212 Err(e) => return Err(e),
213 }
214 }
215 }
216
217 /// Walk every frame once, recording where each starts.
218 fn build_index(&mut self) -> Result<()> {
219 if self.indexed {
220 return Ok(());
221 }
222 let (at, sample) = (self.offset(), self.sample);
223 self.jump(self.start)?;
224 let mut sample_at = 0u64;
225 while self.offset() < self.end {
226 let f = match self.framing() {
227 Ok(f) => f,
228 Err(e) if e.is_eof() => break,
229 Err(e) => return Err(e),
230 };
231 // `framing` may have resynced past junk: index where the frame
232 // really starts, not where the walk was standing.
233 self.index.push((sample_at, self.offset()));
234 sample_at += f.samples;
235 self.head += f.bytes;
236 }
237 self.indexed = true;
238 // Put the reader back where the caller had it.
239 self.jump(at)?;
240 self.sample = sample;
241 Ok(())
242 }
243}
244
245/// One frame's geometry, read from the head of `data`.
246fn frame_at(kind: Kind, data: &[u8], flac: Option<&ec_flac::StreamInfo>) -> Result<Framing> {
247 match kind {
248 Kind::Wav { block_align } => {
249 let frames = (data.len() / block_align).min(WAV_FRAMES);
250 match frames {
251 0 => Err(Error::Eof),
252 n => Ok(Framing {
253 bytes: n * block_align,
254 samples: n as u64,
255 }),
256 }
257 }
258 Kind::Mp3 => {
259 let header = ec_mp3::FrameHeader::parse(data)?;
260 let bytes = header
261 .frame_len()
262 .ok_or_else(|| Error::corrupt("mp3: a free-format frame states no length"))?;
263 if bytes > data.len() {
264 return Err(Error::NeedMore);
265 }
266 Ok(Framing {
267 bytes,
268 samples: header.samples_per_frame() as u64,
269 })
270 }
271 Kind::Adts => {
272 let header = ec_aac::parse_adts(data)?;
273 if header.frame_length > data.len() {
274 return Err(Error::NeedMore);
275 }
276 Ok(Framing {
277 bytes: header.frame_length,
278 samples: 1024 * u64::from(header.raw_blocks),
279 })
280 }
281 Kind::Flac => {
282 if ec_flac::decode::find_frame_sync(data, 0, flac) != Some(0) {
283 return Err(Error::corrupt("flac: not a frame header"));
284 }
285 let mut r = ec_core::BitReader::new(data);
286 let header = ec_flac::decode::parse_frame_header(&mut r, flac)?;
287 // A frame ends where the next one starts; the last frame of a file
288 // ends at the file's end, which the caller's `NeedMore` handles.
289 let bytes = ec_flac::decode::find_frame_sync(data, 1, flac).ok_or(Error::NeedMore)?;
290 Ok(Framing {
291 bytes,
292 samples: header.block_size as u64,
293 })
294 }
295 }
296}
297
298impl<R: Read + Seek + Send> Demuxer for RawDemuxer<R> {
299 fn streams(&self) -> &[StreamInfo] {
300 &self.streams
301 }
302
303 fn next_packet(&mut self) -> Result<Packet> {
304 if self.offset() >= self.end {
305 return Err(Error::Eof);
306 }
307 let f = self.framing()?;
308 let data = Buf::copy_from_slice(&self.window()[..f.bytes]);
309 self.head += f.bytes;
310 let pts = self.sample;
311 self.sample += f.samples;
312 let mut packet = Packet::new(0, TimeBase::from_rate(self.rate), data);
313 packet.pts = Some(pts as i64);
314 packet.dts = Some(pts as i64);
315 packet.duration = Some(f.samples as i64);
316 packet.flags = PacketFlags {
317 keyframe: true,
318 ..PacketFlags::default()
319 };
320 Ok(packet)
321 }
322
323 fn seek(&mut self, _stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
324 let target = to
325 .rescale(TimeBase::from_rate(self.rate), Rounding::Down)
326 .ticks
327 .max(0) as u64;
328 // PCM needs no index and no rounding: every sample is a random access
329 // point, at a byte offset arithmetic gives.
330 if let Kind::Wav { block_align } = self.kind {
331 let at = self.start + target * block_align as u64;
332 self.jump(at.min(self.end))?;
333 self.sample = target;
334 return Ok(());
335 }
336 self.build_index()?;
337 let found = self.index.partition_point(|(s, _)| *s <= target);
338 let i = match mode {
339 SeekMode::SyncAfter => found.min(self.index.len().saturating_sub(1)),
340 // At or before: the frame the target sits inside.
341 _ => found.saturating_sub(1),
342 };
343 let (sample, at) = match self.index.get(i) {
344 Some(&entry) => entry,
345 None => return Err(Error::Eof),
346 };
347 self.jump(at)?;
348 self.sample = sample;
349 Ok(())
350 }
351}
352
353/// Codec parameters for a WAVE stream, whose `fmt ` chunk names its codec
354/// outright.
355pub(crate) fn wav_parameters(spec: ec_riff::WavSpec) -> Result<(CodecParameters, usize)> {
356 let format = spec.sample_format()?;
357 let codec = match (format, spec.bits_per_sample) {
358 (SampleFormat::F32, _) => CodecId::PcmF32Le,
359 (_, 8) => CodecId::PcmU8,
360 (_, 16) => CodecId::PcmS16Le,
361 (_, 24) => CodecId::PcmS24Le,
362 (_, 32) => CodecId::PcmS32Le,
363 (_, bits) => {
364 return Err(Error::unsupported(
365 format!("a {bits}-bit WAVE file"),
366 "only 8, 16, 24 and 32 bit samples have a PCM codec id",
367 ));
368 }
369 };
370 let mut params = CodecParameters::new(codec);
371 params.media = MediaParameters::Audio(AudioParameters {
372 sample_rate: spec.sample_rate,
373 layout: spec.layout(),
374 format: Some(format),
375 bits_per_sample: Some(u32::from(spec.bits_per_sample)),
376 });
377 Ok((params, spec.block_align()))
378}
379
380/// Codec parameters for an ADTS stream, from its first frame header.
381pub(crate) fn adts_parameters(header: &ec_aac::AdtsHeader) -> CodecParameters {
382 let mut params = CodecParameters::new(CodecId::Aac);
383 params.media = MediaParameters::Audio(AudioParameters {
384 sample_rate: header.sample_rate,
385 layout: ChannelLayout::from_count(usize::from(header.channels.max(1))),
386 format: Some(SampleFormat::F32),
387 bits_per_sample: None,
388 });
389 // ADTS states its configuration in every frame, but a decoder built from
390 // parameters alone still wants the ASC form of it.
391 params.extradata = Some(Buf::from_vec(ec_aac::audio_specific_config_bytes(
392 header.sample_rate,
393 header.channels,
394 )));
395 params
396}
397
398/// Codec parameters for an MP3 stream, from its first frame header.
399pub(crate) fn mp3_parameters(header: &ec_mp3::FrameHeader) -> CodecParameters {
400 ec_mp3::codec_parameters(header.sample_rate, header.channels())
401}