forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

raw.rs487 lines, 16.9 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 /// Block-coded audio (IMA/MS ADPCM): one packet is one `block` of bytes
36 /// decoding to `samples` frames.
37 WavBlocks {
38 block: usize,
39 samples: u64,
40 },
41 Mp3,
42 Flac,
43 Adts,
44 /// DTS core frames, each with its extension substream when one follows.
45 Dts,
46}
47
48/// A frame's byte length and how many inter-channel samples it holds.
49struct Framing {
50 bytes: usize,
51 samples: u64,
52}
53
54/// One elementary audio stream read straight out of a file.
55pub(crate) struct RawDemuxer<R> {
56 r: R,
57 kind: Kind,
58 streams: Vec<StreamInfo>,
59 /// Offset of the first frame and one past the last audio byte.
60 start: u64,
61 end: u64,
62 /// Offset the window starts at, and the file offset the reader itself sits
63 /// at (window end).
64 pos: u64,
65 read_at: u64,
66 buf: Vec<u8>,
67 head: usize,
68 /// Next packet's first sample, in the stream's own time base.
69 sample: u64,
70 rate: u32,
71 /// `STREAMINFO`, needed to read a FLAC frame header.
72 flac: Option<ec_flac::StreamInfo>,
73 /// `(first sample, offset)` per frame, built on the first seek.
74 index: Vec<(u64, u64)>,
75 indexed: bool,
76}
77
78impl<R: Read + Seek> RawDemuxer<R> {
79 pub(crate) fn new(
80 mut r: R,
81 kind: Kind,
82 params: CodecParameters,
83 start: u64,
84 end: u64,
85 total_samples: Option<u64>,
86 flac: Option<ec_flac::StreamInfo>,
87 ) -> Result<RawDemuxer<R>> {
88 let rate = params
89 .audio()
90 .map(|a| a.sample_rate)
91 .filter(|r| *r > 0)
92 .ok_or_else(|| Error::corrupt("a raw audio stream with no sample rate"))?;
93 let mut info = StreamInfo::new(0, TimeBase::from_rate(rate), params);
94 info.start_time = Some(0);
95 info.duration = total_samples.map(|n| n as i64);
96 r.seek(SeekFrom::Start(start))?;
97 Ok(RawDemuxer {
98 r,
99 kind,
100 streams: vec![info],
101 start,
102 end,
103 pos: start,
104 read_at: start,
105 buf: Vec::with_capacity(CHUNK),
106 head: 0,
107 sample: 0,
108 rate,
109 flac,
110 index: Vec::new(),
111 indexed: false,
112 })
113 }
114
115 /// State that this stream opens with `samples` a decoder emits before the
116 /// first audible one ([`StreamInfo::initial_padding`]).
117 pub(crate) fn with_initial_padding(mut self, samples: u32) -> RawDemuxer<R> {
118 self.streams[0].initial_padding = samples;
119 self
120 }
121
122 /// Samples in a typical frame of this format, for the tail of an estimate.
123 fn frame_samples(&self) -> u64 {
124 match self.kind {
125 Kind::Wav { .. } => WAV_FRAMES as u64,
126 Kind::WavBlocks { samples, .. } => samples,
127 Kind::Mp3 => 1152,
128 Kind::Flac => self
129 .flac
130 .as_ref()
131 .map_or(4096, |i| u64::from(i.max_block_size)),
132 Kind::Adts => 1024,
133 Kind::Dts => 512,
134 }
135 }
136
137 /// At least `want` bytes in the window, or fewer at the end of the stream.
138 fn fill(&mut self, want: usize) -> Result<()> {
139 if self.head > COMPACT_AT {
140 self.buf.drain(..self.head);
141 self.pos += self.head as u64;
142 self.head = 0;
143 }
144 while self.buf.len() - self.head < want && self.read_at < self.end {
145 let chunk = CHUNK.min((self.end - self.read_at) as usize);
146 let at = self.buf.len();
147 self.buf.resize(at + chunk, 0);
148 let mut got = 0;
149 while got < chunk {
150 match self.r.read(&mut self.buf[at + got..]) {
151 Ok(0) => break,
152 Ok(n) => got += n,
153 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
154 Err(e) => return Err(Error::Io(e)),
155 }
156 }
157 self.buf.truncate(at + got);
158 self.read_at += got as u64;
159 if got == 0 {
160 break;
161 }
162 }
163 Ok(())
164 }
165
166 /// The unread bytes of the window.
167 fn window(&self) -> &[u8] {
168 &self.buf[self.head..]
169 }
170
171 /// Where the window's head sits in the file.
172 fn offset(&self) -> u64 {
173 self.pos + self.head as u64
174 }
175
176 /// Drop the window and resume reading at `offset`.
177 fn jump(&mut self, offset: u64) -> Result<()> {
178 self.r.seek(SeekFrom::Start(offset))?;
179 self.buf.clear();
180 self.head = 0;
181 self.pos = offset;
182 self.read_at = offset;
183 Ok(())
184 }
185
186 /// The frame at the window's head, or [`Error::Eof`] at the end.
187 ///
188 /// Resyncs over junk: a byte that does not open a frame is skipped, which
189 /// is what carries a reader over an ID3 tag in the middle of a stream or a
190 /// scrap of a torn download.
191 fn framing(&mut self) -> Result<Framing> {
192 let want = match self.kind {
193 Kind::Wav { block_align } => block_align * WAV_FRAMES,
194 Kind::WavBlocks { block, .. } => block,
195 // A FLAC frame is bounded by the *next* sync word, so the window
196 // has to hold a whole one plus the head of its successor.
197 Kind::Flac => 1 << 20,
198 _ => 8192,
199 };
200 let flac = self.flac.clone();
201 let kind = self.kind;
202 let mut skipped = 0u64;
203 loop {
204 self.fill(want)?;
205 let left = self.window().len();
206 if left == 0 {
207 return Err(Error::Eof);
208 }
209 let tail = self.read_at >= self.end;
210 match frame_at(kind, self.window(), flac.as_ref()) {
211 Ok(f) => return Ok(f),
212 Err(e) if e.is_need_more() && tail => {
213 // The tail of a file: whatever is left is the last frame.
214 return Ok(Framing {
215 bytes: left,
216 samples: self.frame_samples(),
217 });
218 }
219 Err(_) if skipped < (1 << 20) => {
220 self.head += 1;
221 skipped += 1;
222 }
223 Err(e) => return Err(e),
224 }
225 }
226 }
227
228 /// Walk every frame once, recording where each starts.
229 fn build_index(&mut self) -> Result<()> {
230 if self.indexed {
231 return Ok(());
232 }
233 let (at, sample) = (self.offset(), self.sample);
234 self.jump(self.start)?;
235 let mut sample_at = 0u64;
236 while self.offset() < self.end {
237 let f = match self.framing() {
238 Ok(f) => f,
239 Err(e) if e.is_eof() => break,
240 Err(e) => return Err(e),
241 };
242 // `framing` may have resynced past junk: index where the frame
243 // really starts, not where the walk was standing.
244 self.index.push((sample_at, self.offset()));
245 sample_at += f.samples;
246 self.head += f.bytes;
247 }
248 self.indexed = true;
249 // Put the reader back where the caller had it.
250 self.jump(at)?;
251 self.sample = sample;
252 Ok(())
253 }
254}
255
256/// One frame's geometry, read from the head of `data`.
257fn frame_at(kind: Kind, data: &[u8], flac: Option<&ec_flac::StreamInfo>) -> Result<Framing> {
258 match kind {
259 Kind::Wav { block_align } => {
260 let frames = (data.len() / block_align).min(WAV_FRAMES);
261 match frames {
262 0 => Err(Error::Eof),
263 n => Ok(Framing {
264 bytes: n * block_align,
265 samples: n as u64,
266 }),
267 }
268 }
269 Kind::WavBlocks { block, samples } => match data.len() >= block && block > 0 {
270 true => Ok(Framing {
271 bytes: block,
272 samples,
273 }),
274 false => Err(Error::Eof),
275 },
276 Kind::Mp3 => {
277 let header = ec_mp3::FrameHeader::parse(data)?;
278 let bytes = header
279 .frame_len()
280 .ok_or_else(|| Error::corrupt("mp3: a free-format frame states no length"))?;
281 if bytes > data.len() {
282 return Err(Error::NeedMore);
283 }
284 Ok(Framing {
285 bytes,
286 samples: header.samples_per_frame() as u64,
287 })
288 }
289 Kind::Adts => {
290 let header = ec_aac::parse_adts(data)?;
291 if header.frame_length > data.len() {
292 return Err(Error::NeedMore);
293 }
294 Ok(Framing {
295 bytes: header.frame_length,
296 samples: 1024 * u64::from(header.raw_blocks),
297 })
298 }
299 Kind::Dts => {
300 let Some((core, len)) = crate::dts::access_unit(data) else {
301 return Err(if data.len() < 16 {
302 Error::NeedMore
303 } else {
304 Error::corrupt("dts: not a frame header")
305 });
306 };
307 if len > data.len() {
308 return Err(Error::NeedMore);
309 }
310 Ok(Framing {
311 bytes: len,
312 samples: u64::from(core.samples),
313 })
314 }
315 Kind::Flac => {
316 if ec_flac::decode::find_frame_sync(data, 0, flac) != Some(0) {
317 return Err(Error::corrupt("flac: not a frame header"));
318 }
319 let mut r = ec_core::BitReader::new(data);
320 let header = ec_flac::decode::parse_frame_header(&mut r, flac)?;
321 // A frame ends where the next one starts; the last frame of a file
322 // ends at the file's end, which the caller's `NeedMore` handles.
323 let bytes = ec_flac::decode::find_frame_sync(data, 1, flac).ok_or(Error::NeedMore)?;
324 Ok(Framing {
325 bytes,
326 samples: header.block_size as u64,
327 })
328 }
329 }
330}
331
332impl<R: Read + Seek + Send> Demuxer for RawDemuxer<R> {
333 fn streams(&self) -> &[StreamInfo] {
334 &self.streams
335 }
336
337 fn next_packet(&mut self) -> Result<Packet> {
338 if self.offset() >= self.end {
339 return Err(Error::Eof);
340 }
341 let f = self.framing()?;
342 let data = Buf::copy_from_slice(&self.window()[..f.bytes]);
343 self.head += f.bytes;
344 let pts = self.sample;
345 self.sample += f.samples;
346 let mut packet = Packet::new(0, TimeBase::from_rate(self.rate), data);
347 packet.pts = Some(pts as i64);
348 packet.dts = Some(pts as i64);
349 packet.duration = Some(f.samples as i64);
350 packet.flags = PacketFlags {
351 keyframe: true,
352 ..PacketFlags::default()
353 };
354 Ok(packet)
355 }
356
357 fn seek(&mut self, _stream: u32, to: Timestamp, mode: SeekMode) -> Result<()> {
358 let target = to
359 .rescale(TimeBase::from_rate(self.rate), Rounding::Down)
360 .ticks
361 .max(0) as u64;
362 // PCM needs no index and no rounding: every sample is a random access
363 // point, at a byte offset arithmetic gives.
364 if let Kind::Wav { block_align } = self.kind {
365 let at = self.start + target * block_align as u64;
366 self.jump(at.min(self.end))?;
367 self.sample = target;
368 return Ok(());
369 }
370 if let Kind::WavBlocks { block, samples } = self.kind {
371 let n = target / samples.max(1);
372 let at = self.start + n * block as u64;
373 self.jump(at.min(self.end))?;
374 self.sample = n * samples.max(1);
375 return Ok(());
376 }
377 self.build_index()?;
378 let found = self.index.partition_point(|(s, _)| *s <= target);
379 let i = match mode {
380 SeekMode::SyncAfter => found.min(self.index.len().saturating_sub(1)),
381 // At or before: the frame the target sits inside.
382 _ => found.saturating_sub(1),
383 };
384 let (sample, at) = match self.index.get(i) {
385 Some(&entry) => entry,
386 None => return Err(Error::Eof),
387 };
388 self.jump(at)?;
389 self.sample = sample;
390 Ok(())
391 }
392}
393
394/// Codec parameters for a WAVE stream, whose `fmt ` chunk names its codec
395/// outright.
396/// Codec parameters and packet geometry for a compressed WAVE stream
397/// (IMA/MS ADPCM, A-law, mu-law): the kind to read it with.
398pub(crate) fn wav_compressed_parameters(
399 spec: ec_riff::WavSpec,
400 c: &ec_riff::WavCompressed,
401) -> Result<(CodecParameters, Kind)> {
402 let codec = ec_riff::WavCompressed::codec_of(c.tag)
403 .ok_or_else(|| Error::unsupported("this WAVE format", "no decoder for it"))?;
404 let mut params = CodecParameters::new(codec);
405 params.media = MediaParameters::Audio(AudioParameters {
406 sample_rate: spec.sample_rate,
407 layout: spec.layout(),
408 format: Some(SampleFormat::S16),
409 bits_per_sample: Some(16),
410 });
411 if !c.extra.is_empty() {
412 params.extradata = Some(Buf::copy_from_slice(&c.extra));
413 }
414 let kind = match c.tag {
415 0x0006 | 0x0007 => Kind::Wav {
416 block_align: usize::from(spec.channels),
417 },
418 _ => Kind::WavBlocks {
419 block: usize::from(c.block_align),
420 samples: u64::from(c.samples_per_block),
421 },
422 };
423 if matches!(kind, Kind::WavBlocks { block, samples } if block == 0 || samples == 0) {
424 return Err(Error::corrupt("WAVE: a block-coded format with no block size"));
425 }
426 Ok((params, kind))
427}
428
429pub(crate) fn wav_parameters(spec: ec_riff::WavSpec) -> Result<(CodecParameters, usize)> {
430 let format = spec.sample_format()?;
431 let codec = match (format, spec.bits_per_sample) {
432 (SampleFormat::F32, _) => CodecId::PcmF32Le,
433 (_, 8) => CodecId::PcmU8,
434 (_, 16) => CodecId::PcmS16Le,
435 (_, 24) => CodecId::PcmS24Le,
436 (_, 32) => CodecId::PcmS32Le,
437 (_, bits) => {
438 return Err(Error::unsupported(
439 format!("a {bits}-bit WAVE file"),
440 "only 8, 16, 24 and 32 bit samples have a PCM codec id",
441 ));
442 }
443 };
444 let mut params = CodecParameters::new(codec);
445 params.media = MediaParameters::Audio(AudioParameters {
446 sample_rate: spec.sample_rate,
447 layout: spec.layout(),
448 format: Some(format),
449 bits_per_sample: Some(u32::from(spec.bits_per_sample)),
450 });
451 Ok((params, spec.block_align()))
452}
453
454/// Codec parameters for an ADTS stream, from its first frame header.
455pub(crate) fn adts_parameters(header: &ec_aac::AdtsHeader) -> CodecParameters {
456 let mut params = CodecParameters::new(CodecId::Aac);
457 params.media = MediaParameters::Audio(AudioParameters {
458 sample_rate: header.sample_rate,
459 layout: ChannelLayout::from_count(usize::from(header.channels.max(1))),
460 format: Some(SampleFormat::F32),
461 bits_per_sample: None,
462 });
463 // ADTS states its configuration in every frame, but a decoder built from
464 // parameters alone still wants the ASC form of it.
465 params.extradata = Some(Buf::from_vec(ec_aac::audio_specific_config_bytes(
466 header.sample_rate,
467 header.channels,
468 )));
469 params
470}
471
472/// Codec parameters for an MP3 stream, from its first frame header.
473pub(crate) fn mp3_parameters(header: &ec_mp3::FrameHeader) -> CodecParameters {
474 ec_mp3::codec_parameters(header.sample_rate, header.channels())
475}
476
477/// Codec parameters for a DTS stream, from its first core frame header.
478pub(crate) fn dts_parameters(core: &crate::dts::Core) -> CodecParameters {
479 let mut params = CodecParameters::new(CodecId::Dts);
480 params.media = MediaParameters::Audio(AudioParameters {
481 sample_rate: core.rate,
482 layout: ChannelLayout::from_count(usize::from(core.channels)),
483 format: None,
484 bits_per_sample: None,
485 });
486 params
487}