forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

extaudio.rs349 lines, 13.4 KiBHistoryRawDownload
1//! DTS and the legacy audio codecs the family decodes, seated in the engine.
2//!
3//! Two pieces live here, both over the family's own crates:
4//!
5//! - [`ExtDecoder`]: one packet in, interleaved f32 out, for DTS (`ec-dts`: core
6//! 5.1, XCH 6.1, X96, 14-bit and little-endian words; a DTS-HD stream decodes
7//! its backward compatible core and an XLL layer is refused by name) and for
8//! what `ec-probe`'s decoder registry carries: IMA and MS ADPCM, QuickTime
9//! `ima4`, A-law, mu-law and AMR-NB/WB (`ec-pcm-ext`, `ec-amr`).
10//! The transport stream and AVI audio door ([`crate::demux::ts::TsDecoder`])
11//! feeds it packets out of its own demuxer.
12//! - [`ExtFileTrack`]: one such audio stream read through `ec_probe::Reader`,
13//! for the containers whose audio no other reader here takes: a Matroska
14//! `A_DTS` track, a QuickTime / 3GP / mp4 track in one of these codecs, a
15//! WAVE file that is not plain PCM (or is DTS), a raw `.dts`, a raw `.amr`.
16//!
17//! The channel order every decoder here hands back is the film order the
18//! engine's stereo fold expects (FL FR FC LFE BL BR SL SR); the one layout that
19//! does not arrive in it, DTS 6.1 (L R C LFE Ls Rs Cs), is permuted to it.
20
21use std::io::Read;
22use std::path::{Path, PathBuf};
23
24use ec_core::registry::SeekMode;
25use ec_core::timebase::{Rounding, TimeBase, Timestamp};
26use ec_core::{CodecId, CodecParameters, MediaParameters, MediaType, Packet};
27
28/// Whether `codec` is one this module decodes.
29pub(crate) fn is_ext_codec(codec: CodecId) -> bool {
30 matches!(
31 codec,
32 CodecId::Dts
33 | CodecId::ImaAdpcmWav
34 | CodecId::MsAdpcm
35 | CodecId::ImaAdpcmQt
36 | CodecId::PcmAlaw
37 | CodecId::PcmMulaw
38 | CodecId::AmrNb
39 | CodecId::AmrWb
40 // MPEG-1/2 audio layers I to III: one `ec-mp3` decoder reads all three.
41 | CodecId::Mp1
42 | CodecId::Mp2
43 | CodecId::Mp3
44 )
45}
46
47/// Whether a Matroska codec id names DTS (`A_DTS`, `A_DTS/EXPRESS`, `A_DTS/LOSSLESS`).
48pub(crate) fn is_mkv_dts(id: &str) -> bool {
49 id == "A_DTS" || id.starts_with("A_DTS/")
50}
51
52/// Whether a Matroska codec id names an MPEG-1/2 Layer I or II track (`A_MPEG/L1`, `A_MPEG/L2`),
53/// which [`ExtFileTrack::open_native`] reads and decodes.
54pub(crate) fn is_mkv_mpeg_layer(id: &str) -> bool {
55 matches!(id, "A_MPEG/L1" | "A_MPEG/L2")
56}
57
58enum Inner {
59 Dts(Box<ec_dts::DtsDecoder>),
60 Probe(Box<ec_probe::AudioDecoder>),
61}
62
63/// A decoder for one of the codecs of [`is_ext_codec`], fed one packet at a time.
64pub(crate) struct ExtDecoder {
65 inner: Inner,
66 scratch: Vec<f32>,
67}
68
69impl ExtDecoder {
70 pub(crate) fn new(params: &CodecParameters) -> crate::Result<Self> {
71 let inner = match params.codec {
72 CodecId::Dts => Inner::Dts(Box::new(ec_dts::DtsDecoder::with_options(ec_dts::Options {
73 // A lossless DTS-HD MA track is named, not silently played as
74 // its lossy core.
75 refuse_xll: true,
76 }))),
77 codec if is_ext_codec(codec) => Inner::Probe(Box::new(
78 ec_probe::AudioDecoder::new(params).map_err(|e| format!("{}: {e}", codec.name()))?,
79 )),
80 codec => return Err(format!("{}: no decoder in the extended audio seat", codec.name()).into()),
81 };
82 Ok(Self {
83 inner,
84 scratch: Vec::new(),
85 })
86 }
87
88 /// One packet in. `Ok(None)` when it decodes to nothing yet; otherwise the
89 /// interleaved samples and the channel count they were decoded at.
90 pub(crate) fn decode(&mut self, data: &[u8]) -> crate::Result<Option<(Vec<f32>, usize)>> {
91 match &mut self.inner {
92 Inner::Dts(d) => match d.decode_frame(data) {
93 Ok(frame) => {
94 let channels = frame.layout.channel_count().max(1);
95 let mut samples: Vec<f32> = frame
96 .data
97 .first()
98 .into_iter()
99 .flat_map(|plane| plane.as_chunks::<4>().0.iter())
100 .map(|s| f32::from_le_bytes(*s))
101 .collect();
102 if channels == 7 {
103 // L R C LFE Ls Rs Cs -> L R C LFE Cs Ls Rs, the 6.1 order of the fold.
104 for f in samples.as_chunks_mut::<7>().0 {
105 f[4..].rotate_right(1);
106 }
107 }
108 Ok((!samples.is_empty()).then_some((samples, channels)))
109 }
110 Err(ec_core::Error::NeedMore) => Ok(None),
111 Err(e) => Err(format!("DTS: {e}").into()),
112 },
113 Inner::Probe(d) => {
114 let packet = Packet::new(0, TimeBase::new(1, 1000), data.to_vec());
115 match d.decode(&packet, &mut self.scratch) {
116 Ok(()) => {}
117 Err(ec_core::Error::NeedMore) => return Ok(None),
118 Err(e) => return Err(format!("{}: {e}", d.codec().name()).into()),
119 }
120 let channels = d.channels().max(1);
121 Ok((!self.scratch.is_empty()).then(|| (std::mem::take(&mut self.scratch), channels)))
122 }
123 }
124 }
125}
126
127/// Which audio stream of a file to open.
128#[derive(Clone, Copy)]
129pub(crate) enum Pick {
130 /// The n-th audio stream, in file order.
131 Nth(usize),
132 /// The stream with this container-native id (a Matroska track number).
133 Native(u64),
134}
135
136/// One audio stream of a file, read through `ec_probe::Reader`.
137pub(crate) struct ExtFileTrack {
138 path: PathBuf,
139 reader: ec_probe::Reader,
140 stream: u32,
141 pick: Pick,
142 params: CodecParameters,
143 time_base: TimeBase,
144 /// What the decoder emits.
145 pub(crate) sample_rate: u32,
146 pub(crate) src_channels: usize,
147 pub(crate) total_samples: Option<u64>,
148 /// Samples at the head the container says are not audible (an edit list's
149 /// start, an encoder delay): media position of the first audible sample.
150 pub(crate) priming: u64,
151 /// Seconds a decoder is run ahead of the first sample it is asked for.
152 pub(crate) pre_roll_secs: f64,
153}
154
155/// The formats worth the cost of opening a reader for: the ones that carry
156/// these codecs and that a standalone-audio or mp4 open would otherwise misread.
157fn sniffs_as_ext(path: &Path) -> bool {
158 let mut head = vec![0u8; 64 << 10];
159 let Ok(mut file) = std::fs::File::open(path) else {
160 return false;
161 };
162 let mut n = 0;
163 while n < head.len() {
164 match file.read(&mut head[n..]) {
165 Ok(0) | Err(_) => break,
166 Ok(m) => n += m,
167 }
168 }
169 matches!(
170 ec_probe::sniff(&head[..n]),
171 Some(
172 ec_probe::Format::Wav
173 | ec_probe::Format::Dts
174 | ec_probe::Format::Amr
175 | ec_probe::Format::Mp4
176 | ec_probe::Format::Matroska
177 )
178 )
179}
180
181impl ExtFileTrack {
182 /// The `index`-th audio stream of `path` when it is in one of the codecs
183 /// here, `Ok(None)` when it is anything else (or not a file this reads).
184 pub(crate) fn open(path: &Path, index: usize) -> crate::Result<Option<Self>> {
185 if !sniffs_as_ext(path) {
186 return Ok(None);
187 }
188 Self::open_pick(path, Pick::Nth(index))
189 }
190
191 /// The Matroska track numbered `number`, `Ok(None)` when it is not DTS.
192 pub(crate) fn open_native(path: &Path, number: u64) -> crate::Result<Option<Self>> {
193 Self::open_pick(path, Pick::Native(number))
194 }
195
196 fn open_pick(path: &Path, pick: Pick) -> crate::Result<Option<Self>> {
197 let reader = match ec_probe::Reader::open(path) {
198 Ok(reader) => reader,
199 Err(_) => return Ok(None),
200 };
201 let audio: Vec<_> = reader
202 .streams()
203 .iter()
204 .filter(|s| s.params.codec.media_type() == MediaType::Audio)
205 .collect();
206 let info = match pick {
207 Pick::Nth(n) => audio.get(n).copied(),
208 Pick::Native(id) => reader
209 .stream_of_native(id)
210 .and_then(|i| audio.iter().find(|s| s.index == i).copied()),
211 };
212 let Some(info) = info else {
213 return Ok(None);
214 };
215 if !is_ext_codec(info.params.codec) {
216 return Ok(None);
217 }
218 let reader_is_mp4 = reader.format() == ec_probe::Format::Mp4;
219 let (stream, params, time_base) = (info.index, info.params.clone(), info.time_base);
220 let duration = info.duration;
221 let codec = info.params.codec;
222 let padding = u64::from(info.initial_padding);
223 let (mut rate, mut channels) = match &params.media {
224 MediaParameters::Audio(a) => (a.sample_rate, a.layout.channel_count()),
225 _ => (0, 0),
226 };
227 let mut track = Self {
228 path: path.to_path_buf(),
229 reader,
230 stream,
231 pick,
232 params,
233 time_base,
234 sample_rate: rate,
235 src_channels: channels.max(1),
236 total_samples: None,
237 priming: padding,
238 pre_roll_secs: match codec {
239 CodecId::Dts => 0.2,
240 CodecId::AmrNb | CodecId::AmrWb => 0.5,
241 _ => 0.0,
242 },
243 };
244 // DTS states its rate and width in the stream, and a container's header
245 // for it is often a default: the first frame that decodes is the truth.
246 // Decoding a few packets also makes a refusal (DTS-HD XLL) the open's.
247 // An mp4 / QuickTime edit list starts the presentation `media_time` into the
248 // media: those samples are not heard (AMR's and ADPCM's muxers write one).
249 if reader_is_mp4
250 && let Pick::Nth(n) = pick
251 && let Ok(mp4) = crate::mp4track::open(path)
252 && let Some(&(track_id, Some(stream))) = crate::mp4track::audio_tracks(&mp4).get(n)
253 && let Some(t) = crate::mp4track::media_time(&mp4, track_id)
254 {
255 let scale = u64::from(crate::mp4track::timescale(&mp4, stream).max(1));
256 track.priming = t * u64::from(track.sample_rate.max(1)) / scale;
257 }
258 let mut decoder = track.decoder()?;
259 for _ in 0..64 {
260 let Some((_, bytes)) = track.next_packet()? else {
261 break;
262 };
263 if let Some((_, c)) = decoder.decode(&bytes)? {
264 channels = c;
265 break;
266 }
267 }
268 if let Inner::Dts(d) = &decoder.inner
269 && let Some(info) = d.frame_info()
270 {
271 rate = info.sample_rate;
272 }
273 track.reopen()?;
274 if rate == 0 {
275 return Err(format!("{}: the audio track states no sample rate", path.display()).into());
276 }
277 track.sample_rate = rate;
278 track.priming = track.priming.min(u64::MAX / 2);
279 track.src_channels = channels.max(1);
280 track.total_samples = duration
281 .filter(|&d| d > 0)
282 .map(|d| (time_base.rescale(d, TimeBase::from_rate(rate), Rounding::Down).max(0) as u64).saturating_sub(track.priming));
283 Ok(Some(track))
284 }
285
286 /// What reaches the timeline: mono, or a pair for anything else.
287 pub(crate) fn channels(&self) -> u16 {
288 if self.src_channels == 1 { 1 } else { 2 }
289 }
290
291 pub(crate) fn codec_name(&self) -> &'static str {
292 self.params.codec.name()
293 }
294
295 pub(crate) fn decoder(&self) -> crate::Result<ExtDecoder> {
296 ExtDecoder::new(&self.params)
297 }
298
299 fn reopen(&mut self) -> crate::Result<()> {
300 let reader = ec_probe::Reader::open(&self.path).map_err(|e| format!("{}: {e}", self.path.display()))?;
301 self.stream = match self.pick {
302 Pick::Nth(n) => reader
303 .streams()
304 .iter()
305 .filter(|s| s.params.codec.media_type() == MediaType::Audio)
306 .nth(n)
307 .map(|s| s.index),
308 Pick::Native(id) => reader.stream_of_native(id),
309 }
310 .ok_or("the audio stream vanished on reopen")?;
311 self.reader = reader;
312 Ok(())
313 }
314
315 /// Positions the track so the next packet starts at or before `secs`.
316 pub(crate) fn seek(&mut self, secs: f64) -> crate::Result<()> {
317 let secs = secs - self.pre_roll_secs;
318 if secs <= 0.05 {
319 return self.reopen();
320 }
321 let ticks = (secs * self.time_base.den() as f64 / self.time_base.num().max(1) as f64) as i64;
322 match self
323 .reader
324 .seek(self.stream, Timestamp::new(ticks, self.time_base), SeekMode::Exact)
325 {
326 Ok(_) => Ok(()),
327 Err(_) => self.reopen(),
328 }
329 }
330
331 /// The next packet of the stream: its start in samples, when the container
332 /// states one, and its bytes. `Ok(None)` at the end.
333 pub(crate) fn next_packet(&mut self) -> crate::Result<Option<(Option<u64>, Vec<u8>)>> {
334 loop {
335 match self.reader.next_packet() {
336 Ok(p) if p.stream == self.stream => {
337 let pos = p
338 .pts
339 .or(p.dts)
340 .map(|t| p.time_base.rescale(t, TimeBase::from_rate(self.sample_rate), Rounding::Nearest).max(0) as u64);
341 return Ok(Some((pos, p.data.as_ref().to_vec())));
342 }
343 Ok(_) => {}
344 Err(ec_core::Error::Eof) => return Ok(None),
345 Err(e) => return Err(format!("{}: {e}", self.path.display()).into()),
346 }
347 }
348 }
349}