forge
Explore
Log in

Don't you dare go Hollow

S1: move the open_* container openers and their DTS/ID3/Xing helpers to raw_open.rs (pure move, AVI stays in lib.rs)

Browse files at this commit

eec863d9107f9e9d3519f4f54f67827cf8346dc2Ahmet Kaan GümüşParent: cd5df0a
crates/ec-probe/src/lib.rsmodified+3 -356
@@ -29,6 +29,7 @@
29 pub mod decoder;29 pub mod decoder;
30 mod dts;30 mod dts;
31 mod raw;31 mod raw;
32+mod raw_open;
32 pub mod tags;33 pub mod tags;
33 34
34 use std::collections::VecDeque;35 use std::collections::VecDeque;
@@ -45,6 +46,8 @@ use ec_core::registry::{
45 use ec_core::timebase::{Rounding, TimeBase, Timestamp};46 use ec_core::timebase::{Rounding, TimeBase, Timestamp};
46 use ec_core::{ChannelLayout, SampleFormat};47 use ec_core::{ChannelLayout, SampleFormat};
47 48
49+use raw_open::{open_adts, open_dts, open_flac, open_mp3, open_wav};
50+
48 pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip};51 pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip};
49 pub use tags::Tags;52 pub use tags::Tags;
50 53
@@ -525,282 +528,6 @@ fn read_upto(r: &mut impl Read, buf: &mut [u8]) -> Result<usize> {
525 Ok(at)528 Ok(at)
526 }529 }
527 530
528-/// The `data` chunk of a RIFF/WAVE file, as `(start, end)`, when it holds a
529-/// DTS stream: 16-bit PCM stereo whose samples spell DTS frames, or the
530-/// `0x2001` format tag that says so outright. The chunk walk is the file's
531-/// own, so a `fmt ` chunk the PCM reader would refuse is no obstacle.
532-fn wav_dts_span<R: Read + Seek>(src: &mut R, end: u64) -> Result<Option<(u64, u64)>> {
533- let mut at = 12u64;
534- while at + 8 <= end {
535- src.seek(SeekFrom::Start(at))?;
536- let mut h = [0u8; 8];
537- if read_upto(src, &mut h)? < 8 {
538- break;
539- }
540- let size = u64::from(u32::from_le_bytes([h[4], h[5], h[6], h[7]]));
541- let body = at + 8;
542- if &h[..4] == b"data" {
543- // A streamed writer's placeholder size means the file is the bound.
544- let stop = if size == 0 || size == 0xFFFF_FFFF || body + size > end {
545- end
546- } else {
547- body + size
548- };
549- let mut window = vec![0u8; HEAD.min((stop - body) as usize)];
550- src.seek(SeekFrom::Start(body))?;
551- let got = read_upto(src, &mut window)?;
552- window.truncate(got);
553- return Ok(dts_chains(&window).then_some((body, stop)));
554- }
555- at = body + size + (size & 1);
556- }
557- Ok(None)
558-}
559-
560-fn open_dts_span<R: Read + Seek + Send + 'static>(
561- mut src: R,
562- format: Format,
563- start: u64,
564- end: u64,
565-) -> Result<Reader> {
566- let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)];
567- src.seek(SeekFrom::Start(start))?;
568- let got = read_upto(&mut src, &mut window)?;
569- window.truncate(got);
570- let (core, _) = dts::access_unit(&window)
571- .ok_or_else(|| Error::corrupt("dts: no frame at the start of the stream"))?;
572- let total = dts_total(&window, end, start);
573- let demuxer = raw::RawDemuxer::new(
574- src,
575- raw::Kind::Dts,
576- raw::dts_parameters(&core),
577- start,
578- end,
579- total,
580- None,
581- )?;
582- Ok(Reader::wrap(
583- format,
584- Box::new(demuxer),
585- Tags::default(),
586- vec![0],
587- ))
588-}
589-
590-fn open_wav<R: Read + Seek + Send + 'static>(mut src: R, end: u64) -> Result<Reader> {
591- if let Some((start, stop)) = wav_dts_span(&mut src, end)? {
592- return open_dts_span(src, Format::Wav, start, stop);
593- }
594- src.rewind()?;
595- let (spec, frames, compressed) = {
596- let reader = ec_riff::WavReader::new(&mut src)?;
597- (reader.spec(), reader.duration(), reader.compressed().cloned())
598- };
599- let start = src.stream_position()?;
600- if let Some(c) = compressed {
601- let (params, kind) = raw::wav_compressed_parameters(spec, &c)?;
602- let bytes_per = match kind {
603- raw::Kind::WavBlocks { block, samples } => (block as u64, samples),
604- _ => (u64::from(spec.channels.max(1)), 1),
605- };
606- let audio_end = frames
607- .map(|n| start + n / bytes_per.1 * bytes_per.0)
608- .unwrap_or(end)
609- .min(end);
610- let total = frames.or(Some((audio_end - start) / bytes_per.0 * bytes_per.1));
611- let demuxer = raw::RawDemuxer::new(src, kind, params, start, audio_end, total, None)?;
612- return Ok(Reader::wrap(
613- Format::Wav,
614- Box::new(demuxer),
615- Tags::default(),
616- vec![0],
617- ));
618- }
619- let (params, block_align) = raw::wav_parameters(spec)?;
620- // A `data` size the header did not state (a streamed writer's placeholder)
621- // means the file itself is the bound.
622- let audio_end = frames
623- .map(|n| start + n * block_align as u64)
624- .unwrap_or(end)
625- .min(end);
626- let total = frames.or(Some((audio_end - start) / block_align as u64));
627- let demuxer = raw::RawDemuxer::new(
628- src,
629- raw::Kind::Wav { block_align },
630- params,
631- start,
632- audio_end,
633- total,
634- None,
635- )?;
636- Ok(Reader::wrap(
637- Format::Wav,
638- Box::new(demuxer),
639- Tags::default(),
640- vec![0],
641- ))
642-}
643-
644-fn open_flac<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
645- let base = tags::id3v2_len(head).unwrap_or(0);
646- src.seek(SeekFrom::Start(base))?;
647- let mut magic = [0u8; 4];
648- read_upto(&mut src, &mut magic)?;
649- if &magic != b"fLaC" {
650- return Err(Error::corrupt("FLAC: no stream marker"));
651- }
652- let mut info: Option<ec_flac::StreamInfo> = None;
653- let mut tags = Tags::default();
654- let mut at = base + 4;
655- loop {
656- let mut header = [0u8; 4];
657- if read_upto(&mut src, &mut header)? < 4 {
658- return Err(Error::corrupt("FLAC: metadata ended before any frame"));
659- }
660- let last = header[0] & 0x80 != 0;
661- let kind = header[0] & 0x7f;
662- let len = u64::from(u32::from_be_bytes([0, header[1], header[2], header[3]]))
663- .min(end.saturating_sub(at + 4));
664- let mut body = vec![0u8; len as usize];
665- read_upto(&mut src, &mut body)?;
666- at += 4 + len;
667- match kind {
668- 0 => info = Some(ec_flac::StreamInfo::parse(&body)?),
669- 4 => tags.merge(tags::from_vorbis_comment(&body)),
670- _ => {}
671- }
672- if last {
673- break;
674- }
675- }
676- let info = info.ok_or_else(|| Error::corrupt("FLAC: no STREAMINFO block"))?;
677- let params = ec_flac::codec_parameters(&info);
678- let total = match info.total_samples {
679- 0 => None,
680- n => Some(n),
681- };
682- let demuxer = raw::RawDemuxer::new(src, raw::Kind::Flac, params, at, end, total, Some(info))?;
683- Ok(Reader::wrap(Format::Flac, Box::new(demuxer), tags, vec![0]))
684-}
685-
686-fn open_mp3<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
687- let (start, tags) = id3(&mut src, head, end)?;
688- let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)];
689- src.seek(SeekFrom::Start(start))?;
690- let got = read_upto(&mut src, &mut window)?;
691- window.truncate(got);
692- let at = frame_sync(&window, Format::Mp3)
693- .ok_or_else(|| Error::corrupt("mp3: no frame in the first 64 KiB"))?;
694- let header = ec_mp3::FrameHeader::parse(&window[at..])?;
695- let mut start = start + at as u64;
696- let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start);
697- // A Xing/Info header states the frame count exactly; without one the
698- // duration is the bitrate estimate the oracle also falls back to, which is
699- // right for CBR and approximate for VBR.
700- let per_frame = header.samples_per_frame() as u64;
701- let xing = xing_frames(&window[at..], &header);
702- if xing.is_some() {
703- // The Xing frame carries no audio — it is a header wearing a frame's
704- // clothes, and a decoder handed it emits a granule of silence. Both
705- // the oracle and this reader start after it.
706- start += header.frame_len().unwrap_or(0) as u64;
707- }
708- // Gapless, as the gapless tag states it: a decoder emits the encoder delay
709- // plus its own 529 samples of Layer III synthesis delay before the first
710- // sample that was ever recorded, and the file runs `padding` samples past
711- // the last one. Both are silence a player must not play, and a file with no
712- // tag has neither — its frames are all there is to go on.
713- let (padding, total) = match &xing {
714- Some(x) => (
715- x.delay + MP3_DECODER_DELAY,
716- Some(
717- (x.frames * per_frame)
718- .saturating_sub(u64::from(x.padding.saturating_sub(MP3_DECODER_DELAY))),
719- ),
720- ),
721- None => (
722- 0,
723- header
724- .frame_len()
725- .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)),
726- ),
727- };
728- let demuxer = raw::RawDemuxer::new(
729- src,
730- raw::Kind::Mp3,
731- raw::mp3_parameters(&header),
732- start,
733- audio_end,
734- total,
735- None,
736- )?
737- .with_initial_padding(padding);
738- Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0]))
739-}
740-
741-fn open_adts<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
742- let (start, tags) = id3(&mut src, head, end)?;
743- let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)];
744- src.seek(SeekFrom::Start(start))?;
745- let got = read_upto(&mut src, &mut window)?;
746- window.truncate(got);
747- let at = frame_sync(&window, Format::Adts)
748- .ok_or_else(|| Error::corrupt("aac: no ADTS frame in the first 64 KiB"))?;
749- let header = ec_aac::parse_adts(&window[at..])?;
750- let start = start + at as u64;
751- let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start);
752- // ADTS states no duration anywhere: every frame is 1024 samples, so the
753- // file's size over its *average* frame is the estimate — the same one
754- // the oracle prints "estimating duration from bitrate" about. Averaged rather
755- // than taken off the first frame, which on a real encode is nothing like
756- // the mean (a 3-second fixture came out 5 seconds long that way).
757- let (mut sum, mut count, mut walk) = (0u64, 0u64, at);
758- while count < 512 {
759- let Ok(h) = ec_aac::parse_adts(&window[walk..]) else {
760- break;
761- };
762- if h.frame_length == 0 || walk + h.frame_length > window.len() {
763- break;
764- }
765- sum += h.frame_length as u64;
766- count += 1;
767- walk += h.frame_length;
768- }
769- let total = (count > 0).then(|| (audio_end - start) * count / sum * 1024);
770- let demuxer = raw::RawDemuxer::new(
771- src,
772- raw::Kind::Adts,
773- raw::adts_parameters(&header),
774- start,
775- audio_end,
776- total,
777- None,
778- )?;
779- Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0]))
780-}
781-
782-fn open_dts<R: Read + Seek + Send + 'static>(src: R, end: u64) -> Result<Reader> {
783- open_dts_span(src, Format::Dts, 0, end)
784-}
785-
786-/// Duration estimate in samples: the span's size over the mean access unit
787-/// of the head window.
788-fn dts_total(window: &[u8], end: u64, start: u64) -> Option<u64> {
789- let (mut sum, mut samples, mut at) = (0u64, 0u64, 0usize);
790- while sum < (1 << 20) {
791- let Some((core, len)) = dts::access_unit(window.get(at..)?) else {
792- break;
793- };
794- if at + len > window.len() {
795- break;
796- }
797- sum += len as u64;
798- samples += u64::from(core.samples);
799- at += len;
800- }
801- (sum > 0).then(|| (end - start) * samples / sum)
802-}
803-
804 fn open_avi<R: Read + Seek + Send + 'static>(src: R) -> Result<Reader> {531 fn open_avi<R: Read + Seek + Send + 'static>(src: R) -> Result<Reader> {
805 let reader = ec_riff::AviReader::new(src)?;532 let reader = ec_riff::AviReader::new(src)?;
806 let demuxer = AviDemuxer::new(reader)?;533 let demuxer = AviDemuxer::new(reader)?;
@@ -1223,86 +950,6 @@ impl<R: Read + Seek + Send> Demuxer for AviDemuxer<R> {
1223 }950 }
1224 }951 }
1225 952
1226-/// Skip an ID3v2 tag at the head of a stream, reading its text on the way past.
1227-fn id3<R: Read + Seek>(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> {
1228- let mut tags = Tags::default();
1229- let start = match tags::id3v2_len(head) {
1230- Some(len) => {
1231- let len = len.min(end);
1232- let mut tag = vec![0u8; len as usize];
1233- src.rewind()?;
1234- read_upto(src, &mut tag)?;
1235- tags.merge(tags::from_id3v2(&tag));
1236- len
1237- }
1238- None => 0,
1239- };
1240- // The v1 block at the end fills in what v2 did not say.
1241- if end >= 128 {
1242- src.seek(SeekFrom::Start(end - 128))?;
1243- let mut tail = [0u8; 128];
1244- read_upto(src, &mut tail)?;
1245- tags.merge(tags::from_id3v1(&tail));
1246- }
1247- Ok((start, tags))
1248-}
1249-
1250-/// Bytes of ID3v1 at the end of a stream, which are not audio.
1251-fn id3v1_len<R: Read + Seek>(src: &mut R, end: u64) -> Result<u64> {
1252- if end < 128 {
1253- return Ok(0);
1254- }
1255- src.seek(SeekFrom::Start(end - 128))?;
1256- let mut tail = [0u8; 3];
1257- read_upto(src, &mut tail)?;
1258- Ok(u64::from(&tail == b"TAG") * 128)
1259-}
1260-
1261-/// The frame count a Xing/Info header states, when the first frame carries one.
1262-fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option<Xing> {
1263- let at = 4 + usize::from(header.crc) * 2 + header.side_info_len();
1264- let tag = frame.get(at..at + 8)?;
1265- if &tag[..4] != b"Xing" && &tag[..4] != b"Info" {
1266- return None;
1267- }
1268- let flags = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]);
1269- if flags & 1 == 0 {
1270- return None;
1271- }
1272- let n = frame.get(at + 8..at + 12)?;
1273- let frames = u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]]));
1274- // The gapless extension sits behind whichever optional fields the flags
1275- // claimed -- frame count, byte count, the 100-byte seek table, quality --
1276- // and states the two trims 21 bytes into itself, twelve bits each.
1277- let mut extension_at = at + 12;
1278- extension_at += usize::from(flags & 2 != 0) * 4;
1279- extension_at += usize::from(flags & 4 != 0) * 100;
1280- extension_at += usize::from(flags & 8 != 0) * 4;
1281- let (delay, padding) = match frame.get(extension_at + 21..extension_at + 24) {
1282- Some(&[a, b, c]) => (
1283- u32::from(a) << 4 | u32::from(b) >> 4,
1284- (u32::from(b) & 0xF) << 8 | u32::from(c),
1285- ),
1286- _ => (0, 0),
1287- };
1288- Some(Xing {
1289- frames,
1290- delay,
1291- padding,
1292- })
1293-}
1294-
1295-/// What an MP3's Xing/Info header states: how long the file is, and the two
1296-/// silences the encoder had to add to make whole frames of it.
1297-struct Xing {
1298- /// Audio frames in the file, the header frame itself excluded.
1299- frames: u64,
1300- /// Encoder delay: samples of silence in front of the first real one.
1301- delay: u32,
1302- /// Encoder padding: samples of silence after the last real one.
1303- padding: u32,
1304-}
1305-
1306 #[cfg(test)]953 #[cfg(test)]
1307 mod tests {954 mod tests {
1308 use super::*;955 use super::*;
crates/ec-probe/src/raw_open.rsadded+357 -0
@@ -0,0 +1,357 @@
1+use super::*;
2+
3+/// The `data` chunk of a RIFF/WAVE file, as `(start, end)`, when it holds a
4+/// DTS stream: 16-bit PCM stereo whose samples spell DTS frames, or the
5+/// `0x2001` format tag that says so outright. The chunk walk is the file's
6+/// own, so a `fmt ` chunk the PCM reader would refuse is no obstacle.
7+fn wav_dts_span<R: Read + Seek>(src: &mut R, end: u64) -> Result<Option<(u64, u64)>> {
8+ let mut at = 12u64;
9+ while at + 8 <= end {
10+ src.seek(SeekFrom::Start(at))?;
11+ let mut h = [0u8; 8];
12+ if read_upto(src, &mut h)? < 8 {
13+ break;
14+ }
15+ let size = u64::from(u32::from_le_bytes([h[4], h[5], h[6], h[7]]));
16+ let body = at + 8;
17+ if &h[..4] == b"data" {
18+ // A streamed writer's placeholder size means the file is the bound.
19+ let stop = if size == 0 || size == 0xFFFF_FFFF || body + size > end {
20+ end
21+ } else {
22+ body + size
23+ };
24+ let mut window = vec![0u8; HEAD.min((stop - body) as usize)];
25+ src.seek(SeekFrom::Start(body))?;
26+ let got = read_upto(src, &mut window)?;
27+ window.truncate(got);
28+ return Ok(dts_chains(&window).then_some((body, stop)));
29+ }
30+ at = body + size + (size & 1);
31+ }
32+ Ok(None)
33+}
34+
35+fn open_dts_span<R: Read + Seek + Send + 'static>(
36+ mut src: R,
37+ format: Format,
38+ start: u64,
39+ end: u64,
40+) -> Result<Reader> {
41+ let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)];
42+ src.seek(SeekFrom::Start(start))?;
43+ let got = read_upto(&mut src, &mut window)?;
44+ window.truncate(got);
45+ let (core, _) = dts::access_unit(&window)
46+ .ok_or_else(|| Error::corrupt("dts: no frame at the start of the stream"))?;
47+ let total = dts_total(&window, end, start);
48+ let demuxer = raw::RawDemuxer::new(
49+ src,
50+ raw::Kind::Dts,
51+ raw::dts_parameters(&core),
52+ start,
53+ end,
54+ total,
55+ None,
56+ )?;
57+ Ok(Reader::wrap(
58+ format,
59+ Box::new(demuxer),
60+ Tags::default(),
61+ vec![0],
62+ ))
63+}
64+
65+pub(crate) fn open_wav<R: Read + Seek + Send + 'static>(mut src: R, end: u64) -> Result<Reader> {
66+ if let Some((start, stop)) = wav_dts_span(&mut src, end)? {
67+ return open_dts_span(src, Format::Wav, start, stop);
68+ }
69+ src.rewind()?;
70+ let (spec, frames, compressed) = {
71+ let reader = ec_riff::WavReader::new(&mut src)?;
72+ (reader.spec(), reader.duration(), reader.compressed().cloned())
73+ };
74+ let start = src.stream_position()?;
75+ if let Some(c) = compressed {
76+ let (params, kind) = raw::wav_compressed_parameters(spec, &c)?;
77+ let bytes_per = match kind {
78+ raw::Kind::WavBlocks { block, samples } => (block as u64, samples),
79+ _ => (u64::from(spec.channels.max(1)), 1),
80+ };
81+ let audio_end = frames
82+ .map(|n| start + n / bytes_per.1 * bytes_per.0)
83+ .unwrap_or(end)
84+ .min(end);
85+ let total = frames.or(Some((audio_end - start) / bytes_per.0 * bytes_per.1));
86+ let demuxer = raw::RawDemuxer::new(src, kind, params, start, audio_end, total, None)?;
87+ return Ok(Reader::wrap(
88+ Format::Wav,
89+ Box::new(demuxer),
90+ Tags::default(),
91+ vec![0],
92+ ));
93+ }
94+ let (params, block_align) = raw::wav_parameters(spec)?;
95+ // A `data` size the header did not state (a streamed writer's placeholder)
96+ // means the file itself is the bound.
97+ let audio_end = frames
98+ .map(|n| start + n * block_align as u64)
99+ .unwrap_or(end)
100+ .min(end);
101+ let total = frames.or(Some((audio_end - start) / block_align as u64));
102+ let demuxer = raw::RawDemuxer::new(
103+ src,
104+ raw::Kind::Wav { block_align },
105+ params,
106+ start,
107+ audio_end,
108+ total,
109+ None,
110+ )?;
111+ Ok(Reader::wrap(
112+ Format::Wav,
113+ Box::new(demuxer),
114+ Tags::default(),
115+ vec![0],
116+ ))
117+}
118+
119+pub(crate) fn open_flac<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
120+ let base = tags::id3v2_len(head).unwrap_or(0);
121+ src.seek(SeekFrom::Start(base))?;
122+ let mut magic = [0u8; 4];
123+ read_upto(&mut src, &mut magic)?;
124+ if &magic != b"fLaC" {
125+ return Err(Error::corrupt("FLAC: no stream marker"));
126+ }
127+ let mut info: Option<ec_flac::StreamInfo> = None;
128+ let mut tags = Tags::default();
129+ let mut at = base + 4;
130+ loop {
131+ let mut header = [0u8; 4];
132+ if read_upto(&mut src, &mut header)? < 4 {
133+ return Err(Error::corrupt("FLAC: metadata ended before any frame"));
134+ }
135+ let last = header[0] & 0x80 != 0;
136+ let kind = header[0] & 0x7f;
137+ let len = u64::from(u32::from_be_bytes([0, header[1], header[2], header[3]]))
138+ .min(end.saturating_sub(at + 4));
139+ let mut body = vec![0u8; len as usize];
140+ read_upto(&mut src, &mut body)?;
141+ at += 4 + len;
142+ match kind {
143+ 0 => info = Some(ec_flac::StreamInfo::parse(&body)?),
144+ 4 => tags.merge(tags::from_vorbis_comment(&body)),
145+ _ => {}
146+ }
147+ if last {
148+ break;
149+ }
150+ }
151+ let info = info.ok_or_else(|| Error::corrupt("FLAC: no STREAMINFO block"))?;
152+ let params = ec_flac::codec_parameters(&info);
153+ let total = match info.total_samples {
154+ 0 => None,
155+ n => Some(n),
156+ };
157+ let demuxer = raw::RawDemuxer::new(src, raw::Kind::Flac, params, at, end, total, Some(info))?;
158+ Ok(Reader::wrap(Format::Flac, Box::new(demuxer), tags, vec![0]))
159+}
160+
161+pub(crate) fn open_mp3<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
162+ let (start, tags) = id3(&mut src, head, end)?;
163+ let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)];
164+ src.seek(SeekFrom::Start(start))?;
165+ let got = read_upto(&mut src, &mut window)?;
166+ window.truncate(got);
167+ let at = frame_sync(&window, Format::Mp3)
168+ .ok_or_else(|| Error::corrupt("mp3: no frame in the first 64 KiB"))?;
169+ let header = ec_mp3::FrameHeader::parse(&window[at..])?;
170+ let mut start = start + at as u64;
171+ let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start);
172+ // A Xing/Info header states the frame count exactly; without one the
173+ // duration is the bitrate estimate the oracle also falls back to, which is
174+ // right for CBR and approximate for VBR.
175+ let per_frame = header.samples_per_frame() as u64;
176+ let xing = xing_frames(&window[at..], &header);
177+ if xing.is_some() {
178+ // The Xing frame carries no audio — it is a header wearing a frame's
179+ // clothes, and a decoder handed it emits a granule of silence. Both
180+ // the oracle and this reader start after it.
181+ start += header.frame_len().unwrap_or(0) as u64;
182+ }
183+ // Gapless, as the gapless tag states it: a decoder emits the encoder delay
184+ // plus its own 529 samples of Layer III synthesis delay before the first
185+ // sample that was ever recorded, and the file runs `padding` samples past
186+ // the last one. Both are silence a player must not play, and a file with no
187+ // tag has neither — its frames are all there is to go on.
188+ let (padding, total) = match &xing {
189+ Some(x) => (
190+ x.delay + MP3_DECODER_DELAY,
191+ Some(
192+ (x.frames * per_frame)
193+ .saturating_sub(u64::from(x.padding.saturating_sub(MP3_DECODER_DELAY))),
194+ ),
195+ ),
196+ None => (
197+ 0,
198+ header
199+ .frame_len()
200+ .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)),
201+ ),
202+ };
203+ let demuxer = raw::RawDemuxer::new(
204+ src,
205+ raw::Kind::Mp3,
206+ raw::mp3_parameters(&header),
207+ start,
208+ audio_end,
209+ total,
210+ None,
211+ )?
212+ .with_initial_padding(padding);
213+ Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0]))
214+}
215+
216+pub(crate) fn open_adts<R: Read + Seek + Send + 'static>(mut src: R, head: &[u8], end: u64) -> Result<Reader> {
217+ let (start, tags) = id3(&mut src, head, end)?;
218+ let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)];
219+ src.seek(SeekFrom::Start(start))?;
220+ let got = read_upto(&mut src, &mut window)?;
221+ window.truncate(got);
222+ let at = frame_sync(&window, Format::Adts)
223+ .ok_or_else(|| Error::corrupt("aac: no ADTS frame in the first 64 KiB"))?;
224+ let header = ec_aac::parse_adts(&window[at..])?;
225+ let start = start + at as u64;
226+ let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start);
227+ // ADTS states no duration anywhere: every frame is 1024 samples, so the
228+ // file's size over its *average* frame is the estimate — the same one
229+ // the oracle prints "estimating duration from bitrate" about. Averaged rather
230+ // than taken off the first frame, which on a real encode is nothing like
231+ // the mean (a 3-second fixture came out 5 seconds long that way).
232+ let (mut sum, mut count, mut walk) = (0u64, 0u64, at);
233+ while count < 512 {
234+ let Ok(h) = ec_aac::parse_adts(&window[walk..]) else {
235+ break;
236+ };
237+ if h.frame_length == 0 || walk + h.frame_length > window.len() {
238+ break;
239+ }
240+ sum += h.frame_length as u64;
241+ count += 1;
242+ walk += h.frame_length;
243+ }
244+ let total = (count > 0).then(|| (audio_end - start) * count / sum * 1024);
245+ let demuxer = raw::RawDemuxer::new(
246+ src,
247+ raw::Kind::Adts,
248+ raw::adts_parameters(&header),
249+ start,
250+ audio_end,
251+ total,
252+ None,
253+ )?;
254+ Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0]))
255+}
256+
257+pub(crate) fn open_dts<R: Read + Seek + Send + 'static>(src: R, end: u64) -> Result<Reader> {
258+ open_dts_span(src, Format::Dts, 0, end)
259+}
260+
261+/// Duration estimate in samples: the span's size over the mean access unit
262+/// of the head window.
263+fn dts_total(window: &[u8], end: u64, start: u64) -> Option<u64> {
264+ let (mut sum, mut samples, mut at) = (0u64, 0u64, 0usize);
265+ while sum < (1 << 20) {
266+ let Some((core, len)) = dts::access_unit(window.get(at..)?) else {
267+ break;
268+ };
269+ if at + len > window.len() {
270+ break;
271+ }
272+ sum += len as u64;
273+ samples += u64::from(core.samples);
274+ at += len;
275+ }
276+ (sum > 0).then(|| (end - start) * samples / sum)
277+}
278+
279+/// Skip an ID3v2 tag at the head of a stream, reading its text on the way past.
280+fn id3<R: Read + Seek>(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> {
281+ let mut tags = Tags::default();
282+ let start = match tags::id3v2_len(head) {
283+ Some(len) => {
284+ let len = len.min(end);
285+ let mut tag = vec![0u8; len as usize];
286+ src.rewind()?;
287+ read_upto(src, &mut tag)?;
288+ tags.merge(tags::from_id3v2(&tag));
289+ len
290+ }
291+ None => 0,
292+ };
293+ // The v1 block at the end fills in what v2 did not say.
294+ if end >= 128 {
295+ src.seek(SeekFrom::Start(end - 128))?;
296+ let mut tail = [0u8; 128];
297+ read_upto(src, &mut tail)?;
298+ tags.merge(tags::from_id3v1(&tail));
299+ }
300+ Ok((start, tags))
301+}
302+
303+/// Bytes of ID3v1 at the end of a stream, which are not audio.
304+fn id3v1_len<R: Read + Seek>(src: &mut R, end: u64) -> Result<u64> {
305+ if end < 128 {
306+ return Ok(0);
307+ }
308+ src.seek(SeekFrom::Start(end - 128))?;
309+ let mut tail = [0u8; 3];
310+ read_upto(src, &mut tail)?;
311+ Ok(u64::from(&tail == b"TAG") * 128)
312+}
313+
314+/// The frame count a Xing/Info header states, when the first frame carries one.
315+fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option<Xing> {
316+ let at = 4 + usize::from(header.crc) * 2 + header.side_info_len();
317+ let tag = frame.get(at..at + 8)?;
318+ if &tag[..4] != b"Xing" && &tag[..4] != b"Info" {
319+ return None;
320+ }
321+ let flags = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]);
322+ if flags & 1 == 0 {
323+ return None;
324+ }
325+ let n = frame.get(at + 8..at + 12)?;
326+ let frames = u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]]));
327+ // The gapless extension sits behind whichever optional fields the flags
328+ // claimed -- frame count, byte count, the 100-byte seek table, quality --
329+ // and states the two trims 21 bytes into itself, twelve bits each.
330+ let mut extension_at = at + 12;
331+ extension_at += usize::from(flags & 2 != 0) * 4;
332+ extension_at += usize::from(flags & 4 != 0) * 100;
333+ extension_at += usize::from(flags & 8 != 0) * 4;
334+ let (delay, padding) = match frame.get(extension_at + 21..extension_at + 24) {
335+ Some(&[a, b, c]) => (
336+ u32::from(a) << 4 | u32::from(b) >> 4,
337+ (u32::from(b) & 0xF) << 8 | u32::from(c),
338+ ),
339+ _ => (0, 0),
340+ };
341+ Some(Xing {
342+ frames,
343+ delay,
344+ padding,
345+ })
346+}
347+
348+/// What an MP3's Xing/Info header states: how long the file is, and the two
349+/// silences the encoder had to add to make whole frames of it.
350+struct Xing {
351+ /// Audio frames in the file, the header frame itself excluded.
352+ frames: u64,
353+ /// Encoder delay: samples of silence in front of the first real one.
354+ delay: u32,
355+ /// Encoder padding: samples of silence after the last real one.
356+ padding: u32,
357+}