From eec863d9107f9e9d3519f4f54f67827cf8346dc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 15:12:21 +0300 Subject: [PATCH] S1: move the open_* container openers and their DTS/ID3/Xing helpers to raw_open.rs (pure move, AVI stays in lib.rs) --- crates/ec-probe/src/lib.rs | 359 +------------------------------- crates/ec-probe/src/raw_open.rs | 357 +++++++++++++++++++++++++++++++ 2 files changed, 360 insertions(+), 356 deletions(-) create mode 100644 crates/ec-probe/src/raw_open.rs diff --git a/crates/ec-probe/src/lib.rs b/crates/ec-probe/src/lib.rs index 2a1241b4..e555461b 100644 --- a/crates/ec-probe/src/lib.rs +++ b/crates/ec-probe/src/lib.rs @@ -29,6 +29,7 @@ pub mod decoder; mod dts; mod raw; +mod raw_open; pub mod tags; use std::collections::VecDeque; @@ -45,6 +46,8 @@ use ec_core::registry::{ use ec_core::timebase::{Rounding, TimeBase, Timestamp}; use ec_core::{ChannelLayout, SampleFormat}; +use raw_open::{open_adts, open_dts, open_flac, open_mp3, open_wav}; + pub use decoder::{AudioDecoder, opus_layout, opus_pre_skip}; pub use tags::Tags; @@ -525,282 +528,6 @@ fn read_upto(r: &mut impl Read, buf: &mut [u8]) -> Result { Ok(at) } -/// The `data` chunk of a RIFF/WAVE file, as `(start, end)`, when it holds a -/// DTS stream: 16-bit PCM stereo whose samples spell DTS frames, or the -/// `0x2001` format tag that says so outright. The chunk walk is the file's -/// own, so a `fmt ` chunk the PCM reader would refuse is no obstacle. -fn wav_dts_span(src: &mut R, end: u64) -> Result> { - let mut at = 12u64; - while at + 8 <= end { - src.seek(SeekFrom::Start(at))?; - let mut h = [0u8; 8]; - if read_upto(src, &mut h)? < 8 { - break; - } - let size = u64::from(u32::from_le_bytes([h[4], h[5], h[6], h[7]])); - let body = at + 8; - if &h[..4] == b"data" { - // A streamed writer's placeholder size means the file is the bound. - let stop = if size == 0 || size == 0xFFFF_FFFF || body + size > end { - end - } else { - body + size - }; - let mut window = vec![0u8; HEAD.min((stop - body) as usize)]; - src.seek(SeekFrom::Start(body))?; - let got = read_upto(src, &mut window)?; - window.truncate(got); - return Ok(dts_chains(&window).then_some((body, stop))); - } - at = body + size + (size & 1); - } - Ok(None) -} - -fn open_dts_span( - mut src: R, - format: Format, - start: u64, - end: u64, -) -> Result { - let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)]; - src.seek(SeekFrom::Start(start))?; - let got = read_upto(&mut src, &mut window)?; - window.truncate(got); - let (core, _) = dts::access_unit(&window) - .ok_or_else(|| Error::corrupt("dts: no frame at the start of the stream"))?; - let total = dts_total(&window, end, start); - let demuxer = raw::RawDemuxer::new( - src, - raw::Kind::Dts, - raw::dts_parameters(&core), - start, - end, - total, - None, - )?; - Ok(Reader::wrap( - format, - Box::new(demuxer), - Tags::default(), - vec![0], - )) -} - -fn open_wav(mut src: R, end: u64) -> Result { - if let Some((start, stop)) = wav_dts_span(&mut src, end)? { - return open_dts_span(src, Format::Wav, start, stop); - } - src.rewind()?; - let (spec, frames, compressed) = { - let reader = ec_riff::WavReader::new(&mut src)?; - (reader.spec(), reader.duration(), reader.compressed().cloned()) - }; - let start = src.stream_position()?; - if let Some(c) = compressed { - let (params, kind) = raw::wav_compressed_parameters(spec, &c)?; - let bytes_per = match kind { - raw::Kind::WavBlocks { block, samples } => (block as u64, samples), - _ => (u64::from(spec.channels.max(1)), 1), - }; - let audio_end = frames - .map(|n| start + n / bytes_per.1 * bytes_per.0) - .unwrap_or(end) - .min(end); - let total = frames.or(Some((audio_end - start) / bytes_per.0 * bytes_per.1)); - let demuxer = raw::RawDemuxer::new(src, kind, params, start, audio_end, total, None)?; - return Ok(Reader::wrap( - Format::Wav, - Box::new(demuxer), - Tags::default(), - vec![0], - )); - } - let (params, block_align) = raw::wav_parameters(spec)?; - // A `data` size the header did not state (a streamed writer's placeholder) - // means the file itself is the bound. - let audio_end = frames - .map(|n| start + n * block_align as u64) - .unwrap_or(end) - .min(end); - let total = frames.or(Some((audio_end - start) / block_align as u64)); - let demuxer = raw::RawDemuxer::new( - src, - raw::Kind::Wav { block_align }, - params, - start, - audio_end, - total, - None, - )?; - Ok(Reader::wrap( - Format::Wav, - Box::new(demuxer), - Tags::default(), - vec![0], - )) -} - -fn open_flac(mut src: R, head: &[u8], end: u64) -> Result { - let base = tags::id3v2_len(head).unwrap_or(0); - src.seek(SeekFrom::Start(base))?; - let mut magic = [0u8; 4]; - read_upto(&mut src, &mut magic)?; - if &magic != b"fLaC" { - return Err(Error::corrupt("FLAC: no stream marker")); - } - let mut info: Option = None; - let mut tags = Tags::default(); - let mut at = base + 4; - loop { - let mut header = [0u8; 4]; - if read_upto(&mut src, &mut header)? < 4 { - return Err(Error::corrupt("FLAC: metadata ended before any frame")); - } - let last = header[0] & 0x80 != 0; - let kind = header[0] & 0x7f; - let len = u64::from(u32::from_be_bytes([0, header[1], header[2], header[3]])) - .min(end.saturating_sub(at + 4)); - let mut body = vec![0u8; len as usize]; - read_upto(&mut src, &mut body)?; - at += 4 + len; - match kind { - 0 => info = Some(ec_flac::StreamInfo::parse(&body)?), - 4 => tags.merge(tags::from_vorbis_comment(&body)), - _ => {} - } - if last { - break; - } - } - let info = info.ok_or_else(|| Error::corrupt("FLAC: no STREAMINFO block"))?; - let params = ec_flac::codec_parameters(&info); - let total = match info.total_samples { - 0 => None, - n => Some(n), - }; - let demuxer = raw::RawDemuxer::new(src, raw::Kind::Flac, params, at, end, total, Some(info))?; - Ok(Reader::wrap(Format::Flac, Box::new(demuxer), tags, vec![0])) -} - -fn open_mp3(mut src: R, head: &[u8], end: u64) -> Result { - let (start, tags) = id3(&mut src, head, end)?; - let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)]; - src.seek(SeekFrom::Start(start))?; - let got = read_upto(&mut src, &mut window)?; - window.truncate(got); - let at = frame_sync(&window, Format::Mp3) - .ok_or_else(|| Error::corrupt("mp3: no frame in the first 64 KiB"))?; - let header = ec_mp3::FrameHeader::parse(&window[at..])?; - let mut start = start + at as u64; - let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start); - // A Xing/Info header states the frame count exactly; without one the - // duration is the bitrate estimate the oracle also falls back to, which is - // right for CBR and approximate for VBR. - let per_frame = header.samples_per_frame() as u64; - let xing = xing_frames(&window[at..], &header); - if xing.is_some() { - // The Xing frame carries no audio — it is a header wearing a frame's - // clothes, and a decoder handed it emits a granule of silence. Both - // the oracle and this reader start after it. - start += header.frame_len().unwrap_or(0) as u64; - } - // Gapless, as the gapless tag states it: a decoder emits the encoder delay - // plus its own 529 samples of Layer III synthesis delay before the first - // sample that was ever recorded, and the file runs `padding` samples past - // the last one. Both are silence a player must not play, and a file with no - // tag has neither — its frames are all there is to go on. - let (padding, total) = match &xing { - Some(x) => ( - x.delay + MP3_DECODER_DELAY, - Some( - (x.frames * per_frame) - .saturating_sub(u64::from(x.padding.saturating_sub(MP3_DECODER_DELAY))), - ), - ), - None => ( - 0, - header - .frame_len() - .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)), - ), - }; - let demuxer = raw::RawDemuxer::new( - src, - raw::Kind::Mp3, - raw::mp3_parameters(&header), - start, - audio_end, - total, - None, - )? - .with_initial_padding(padding); - Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0])) -} - -fn open_adts(mut src: R, head: &[u8], end: u64) -> Result { - let (start, tags) = id3(&mut src, head, end)?; - let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)]; - src.seek(SeekFrom::Start(start))?; - let got = read_upto(&mut src, &mut window)?; - window.truncate(got); - let at = frame_sync(&window, Format::Adts) - .ok_or_else(|| Error::corrupt("aac: no ADTS frame in the first 64 KiB"))?; - let header = ec_aac::parse_adts(&window[at..])?; - let start = start + at as u64; - let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start); - // ADTS states no duration anywhere: every frame is 1024 samples, so the - // file's size over its *average* frame is the estimate — the same one - // the oracle prints "estimating duration from bitrate" about. Averaged rather - // than taken off the first frame, which on a real encode is nothing like - // the mean (a 3-second fixture came out 5 seconds long that way). - let (mut sum, mut count, mut walk) = (0u64, 0u64, at); - while count < 512 { - let Ok(h) = ec_aac::parse_adts(&window[walk..]) else { - break; - }; - if h.frame_length == 0 || walk + h.frame_length > window.len() { - break; - } - sum += h.frame_length as u64; - count += 1; - walk += h.frame_length; - } - let total = (count > 0).then(|| (audio_end - start) * count / sum * 1024); - let demuxer = raw::RawDemuxer::new( - src, - raw::Kind::Adts, - raw::adts_parameters(&header), - start, - audio_end, - total, - None, - )?; - Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0])) -} - -fn open_dts(src: R, end: u64) -> Result { - open_dts_span(src, Format::Dts, 0, end) -} - -/// Duration estimate in samples: the span's size over the mean access unit -/// of the head window. -fn dts_total(window: &[u8], end: u64, start: u64) -> Option { - let (mut sum, mut samples, mut at) = (0u64, 0u64, 0usize); - while sum < (1 << 20) { - let Some((core, len)) = dts::access_unit(window.get(at..)?) else { - break; - }; - if at + len > window.len() { - break; - } - sum += len as u64; - samples += u64::from(core.samples); - at += len; - } - (sum > 0).then(|| (end - start) * samples / sum) -} - fn open_avi(src: R) -> Result { let reader = ec_riff::AviReader::new(src)?; let demuxer = AviDemuxer::new(reader)?; @@ -1223,86 +950,6 @@ impl Demuxer for AviDemuxer { } } -/// Skip an ID3v2 tag at the head of a stream, reading its text on the way past. -fn id3(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> { - let mut tags = Tags::default(); - let start = match tags::id3v2_len(head) { - Some(len) => { - let len = len.min(end); - let mut tag = vec![0u8; len as usize]; - src.rewind()?; - read_upto(src, &mut tag)?; - tags.merge(tags::from_id3v2(&tag)); - len - } - None => 0, - }; - // The v1 block at the end fills in what v2 did not say. - if end >= 128 { - src.seek(SeekFrom::Start(end - 128))?; - let mut tail = [0u8; 128]; - read_upto(src, &mut tail)?; - tags.merge(tags::from_id3v1(&tail)); - } - Ok((start, tags)) -} - -/// Bytes of ID3v1 at the end of a stream, which are not audio. -fn id3v1_len(src: &mut R, end: u64) -> Result { - if end < 128 { - return Ok(0); - } - src.seek(SeekFrom::Start(end - 128))?; - let mut tail = [0u8; 3]; - read_upto(src, &mut tail)?; - Ok(u64::from(&tail == b"TAG") * 128) -} - -/// The frame count a Xing/Info header states, when the first frame carries one. -fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option { - let at = 4 + usize::from(header.crc) * 2 + header.side_info_len(); - let tag = frame.get(at..at + 8)?; - if &tag[..4] != b"Xing" && &tag[..4] != b"Info" { - return None; - } - let flags = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]); - if flags & 1 == 0 { - return None; - } - let n = frame.get(at + 8..at + 12)?; - let frames = u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]])); - // The gapless extension sits behind whichever optional fields the flags - // claimed -- frame count, byte count, the 100-byte seek table, quality -- - // and states the two trims 21 bytes into itself, twelve bits each. - let mut extension_at = at + 12; - extension_at += usize::from(flags & 2 != 0) * 4; - extension_at += usize::from(flags & 4 != 0) * 100; - extension_at += usize::from(flags & 8 != 0) * 4; - let (delay, padding) = match frame.get(extension_at + 21..extension_at + 24) { - Some(&[a, b, c]) => ( - u32::from(a) << 4 | u32::from(b) >> 4, - (u32::from(b) & 0xF) << 8 | u32::from(c), - ), - _ => (0, 0), - }; - Some(Xing { - frames, - delay, - padding, - }) -} - -/// What an MP3's Xing/Info header states: how long the file is, and the two -/// silences the encoder had to add to make whole frames of it. -struct Xing { - /// Audio frames in the file, the header frame itself excluded. - frames: u64, - /// Encoder delay: samples of silence in front of the first real one. - delay: u32, - /// Encoder padding: samples of silence after the last real one. - padding: u32, -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/ec-probe/src/raw_open.rs b/crates/ec-probe/src/raw_open.rs new file mode 100644 index 00000000..f9368e76 --- /dev/null +++ b/crates/ec-probe/src/raw_open.rs @@ -0,0 +1,357 @@ +use super::*; + +/// The `data` chunk of a RIFF/WAVE file, as `(start, end)`, when it holds a +/// DTS stream: 16-bit PCM stereo whose samples spell DTS frames, or the +/// `0x2001` format tag that says so outright. The chunk walk is the file's +/// own, so a `fmt ` chunk the PCM reader would refuse is no obstacle. +fn wav_dts_span(src: &mut R, end: u64) -> Result> { + let mut at = 12u64; + while at + 8 <= end { + src.seek(SeekFrom::Start(at))?; + let mut h = [0u8; 8]; + if read_upto(src, &mut h)? < 8 { + break; + } + let size = u64::from(u32::from_le_bytes([h[4], h[5], h[6], h[7]])); + let body = at + 8; + if &h[..4] == b"data" { + // A streamed writer's placeholder size means the file is the bound. + let stop = if size == 0 || size == 0xFFFF_FFFF || body + size > end { + end + } else { + body + size + }; + let mut window = vec![0u8; HEAD.min((stop - body) as usize)]; + src.seek(SeekFrom::Start(body))?; + let got = read_upto(src, &mut window)?; + window.truncate(got); + return Ok(dts_chains(&window).then_some((body, stop))); + } + at = body + size + (size & 1); + } + Ok(None) +} + +fn open_dts_span( + mut src: R, + format: Format, + start: u64, + end: u64, +) -> Result { + let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)]; + src.seek(SeekFrom::Start(start))?; + let got = read_upto(&mut src, &mut window)?; + window.truncate(got); + let (core, _) = dts::access_unit(&window) + .ok_or_else(|| Error::corrupt("dts: no frame at the start of the stream"))?; + let total = dts_total(&window, end, start); + let demuxer = raw::RawDemuxer::new( + src, + raw::Kind::Dts, + raw::dts_parameters(&core), + start, + end, + total, + None, + )?; + Ok(Reader::wrap( + format, + Box::new(demuxer), + Tags::default(), + vec![0], + )) +} + +pub(crate) fn open_wav(mut src: R, end: u64) -> Result { + if let Some((start, stop)) = wav_dts_span(&mut src, end)? { + return open_dts_span(src, Format::Wav, start, stop); + } + src.rewind()?; + let (spec, frames, compressed) = { + let reader = ec_riff::WavReader::new(&mut src)?; + (reader.spec(), reader.duration(), reader.compressed().cloned()) + }; + let start = src.stream_position()?; + if let Some(c) = compressed { + let (params, kind) = raw::wav_compressed_parameters(spec, &c)?; + let bytes_per = match kind { + raw::Kind::WavBlocks { block, samples } => (block as u64, samples), + _ => (u64::from(spec.channels.max(1)), 1), + }; + let audio_end = frames + .map(|n| start + n / bytes_per.1 * bytes_per.0) + .unwrap_or(end) + .min(end); + let total = frames.or(Some((audio_end - start) / bytes_per.0 * bytes_per.1)); + let demuxer = raw::RawDemuxer::new(src, kind, params, start, audio_end, total, None)?; + return Ok(Reader::wrap( + Format::Wav, + Box::new(demuxer), + Tags::default(), + vec![0], + )); + } + let (params, block_align) = raw::wav_parameters(spec)?; + // A `data` size the header did not state (a streamed writer's placeholder) + // means the file itself is the bound. + let audio_end = frames + .map(|n| start + n * block_align as u64) + .unwrap_or(end) + .min(end); + let total = frames.or(Some((audio_end - start) / block_align as u64)); + let demuxer = raw::RawDemuxer::new( + src, + raw::Kind::Wav { block_align }, + params, + start, + audio_end, + total, + None, + )?; + Ok(Reader::wrap( + Format::Wav, + Box::new(demuxer), + Tags::default(), + vec![0], + )) +} + +pub(crate) fn open_flac(mut src: R, head: &[u8], end: u64) -> Result { + let base = tags::id3v2_len(head).unwrap_or(0); + src.seek(SeekFrom::Start(base))?; + let mut magic = [0u8; 4]; + read_upto(&mut src, &mut magic)?; + if &magic != b"fLaC" { + return Err(Error::corrupt("FLAC: no stream marker")); + } + let mut info: Option = None; + let mut tags = Tags::default(); + let mut at = base + 4; + loop { + let mut header = [0u8; 4]; + if read_upto(&mut src, &mut header)? < 4 { + return Err(Error::corrupt("FLAC: metadata ended before any frame")); + } + let last = header[0] & 0x80 != 0; + let kind = header[0] & 0x7f; + let len = u64::from(u32::from_be_bytes([0, header[1], header[2], header[3]])) + .min(end.saturating_sub(at + 4)); + let mut body = vec![0u8; len as usize]; + read_upto(&mut src, &mut body)?; + at += 4 + len; + match kind { + 0 => info = Some(ec_flac::StreamInfo::parse(&body)?), + 4 => tags.merge(tags::from_vorbis_comment(&body)), + _ => {} + } + if last { + break; + } + } + let info = info.ok_or_else(|| Error::corrupt("FLAC: no STREAMINFO block"))?; + let params = ec_flac::codec_parameters(&info); + let total = match info.total_samples { + 0 => None, + n => Some(n), + }; + let demuxer = raw::RawDemuxer::new(src, raw::Kind::Flac, params, at, end, total, Some(info))?; + Ok(Reader::wrap(Format::Flac, Box::new(demuxer), tags, vec![0])) +} + +pub(crate) fn open_mp3(mut src: R, head: &[u8], end: u64) -> Result { + let (start, tags) = id3(&mut src, head, end)?; + let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)]; + src.seek(SeekFrom::Start(start))?; + let got = read_upto(&mut src, &mut window)?; + window.truncate(got); + let at = frame_sync(&window, Format::Mp3) + .ok_or_else(|| Error::corrupt("mp3: no frame in the first 64 KiB"))?; + let header = ec_mp3::FrameHeader::parse(&window[at..])?; + let mut start = start + at as u64; + let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start); + // A Xing/Info header states the frame count exactly; without one the + // duration is the bitrate estimate the oracle also falls back to, which is + // right for CBR and approximate for VBR. + let per_frame = header.samples_per_frame() as u64; + let xing = xing_frames(&window[at..], &header); + if xing.is_some() { + // The Xing frame carries no audio — it is a header wearing a frame's + // clothes, and a decoder handed it emits a granule of silence. Both + // the oracle and this reader start after it. + start += header.frame_len().unwrap_or(0) as u64; + } + // Gapless, as the gapless tag states it: a decoder emits the encoder delay + // plus its own 529 samples of Layer III synthesis delay before the first + // sample that was ever recorded, and the file runs `padding` samples past + // the last one. Both are silence a player must not play, and a file with no + // tag has neither — its frames are all there is to go on. + let (padding, total) = match &xing { + Some(x) => ( + x.delay + MP3_DECODER_DELAY, + Some( + (x.frames * per_frame) + .saturating_sub(u64::from(x.padding.saturating_sub(MP3_DECODER_DELAY))), + ), + ), + None => ( + 0, + header + .frame_len() + .and_then(|len| (len > 0).then(|| (audio_end - start) / len as u64 * per_frame)), + ), + }; + let demuxer = raw::RawDemuxer::new( + src, + raw::Kind::Mp3, + raw::mp3_parameters(&header), + start, + audio_end, + total, + None, + )? + .with_initial_padding(padding); + Ok(Reader::wrap(Format::Mp3, Box::new(demuxer), tags, vec![0])) +} + +pub(crate) fn open_adts(mut src: R, head: &[u8], end: u64) -> Result { + let (start, tags) = id3(&mut src, head, end)?; + let mut window = vec![0u8; HEAD.min(end.saturating_sub(start) as usize)]; + src.seek(SeekFrom::Start(start))?; + let got = read_upto(&mut src, &mut window)?; + window.truncate(got); + let at = frame_sync(&window, Format::Adts) + .ok_or_else(|| Error::corrupt("aac: no ADTS frame in the first 64 KiB"))?; + let header = ec_aac::parse_adts(&window[at..])?; + let start = start + at as u64; + let audio_end = end.saturating_sub(id3v1_len(&mut src, end)?).max(start); + // ADTS states no duration anywhere: every frame is 1024 samples, so the + // file's size over its *average* frame is the estimate — the same one + // the oracle prints "estimating duration from bitrate" about. Averaged rather + // than taken off the first frame, which on a real encode is nothing like + // the mean (a 3-second fixture came out 5 seconds long that way). + let (mut sum, mut count, mut walk) = (0u64, 0u64, at); + while count < 512 { + let Ok(h) = ec_aac::parse_adts(&window[walk..]) else { + break; + }; + if h.frame_length == 0 || walk + h.frame_length > window.len() { + break; + } + sum += h.frame_length as u64; + count += 1; + walk += h.frame_length; + } + let total = (count > 0).then(|| (audio_end - start) * count / sum * 1024); + let demuxer = raw::RawDemuxer::new( + src, + raw::Kind::Adts, + raw::adts_parameters(&header), + start, + audio_end, + total, + None, + )?; + Ok(Reader::wrap(Format::Adts, Box::new(demuxer), tags, vec![0])) +} + +pub(crate) fn open_dts(src: R, end: u64) -> Result { + open_dts_span(src, Format::Dts, 0, end) +} + +/// Duration estimate in samples: the span's size over the mean access unit +/// of the head window. +fn dts_total(window: &[u8], end: u64, start: u64) -> Option { + let (mut sum, mut samples, mut at) = (0u64, 0u64, 0usize); + while sum < (1 << 20) { + let Some((core, len)) = dts::access_unit(window.get(at..)?) else { + break; + }; + if at + len > window.len() { + break; + } + sum += len as u64; + samples += u64::from(core.samples); + at += len; + } + (sum > 0).then(|| (end - start) * samples / sum) +} + +/// Skip an ID3v2 tag at the head of a stream, reading its text on the way past. +fn id3(src: &mut R, head: &[u8], end: u64) -> Result<(u64, Tags)> { + let mut tags = Tags::default(); + let start = match tags::id3v2_len(head) { + Some(len) => { + let len = len.min(end); + let mut tag = vec![0u8; len as usize]; + src.rewind()?; + read_upto(src, &mut tag)?; + tags.merge(tags::from_id3v2(&tag)); + len + } + None => 0, + }; + // The v1 block at the end fills in what v2 did not say. + if end >= 128 { + src.seek(SeekFrom::Start(end - 128))?; + let mut tail = [0u8; 128]; + read_upto(src, &mut tail)?; + tags.merge(tags::from_id3v1(&tail)); + } + Ok((start, tags)) +} + +/// Bytes of ID3v1 at the end of a stream, which are not audio. +fn id3v1_len(src: &mut R, end: u64) -> Result { + if end < 128 { + return Ok(0); + } + src.seek(SeekFrom::Start(end - 128))?; + let mut tail = [0u8; 3]; + read_upto(src, &mut tail)?; + Ok(u64::from(&tail == b"TAG") * 128) +} + +/// The frame count a Xing/Info header states, when the first frame carries one. +fn xing_frames(frame: &[u8], header: &ec_mp3::FrameHeader) -> Option { + let at = 4 + usize::from(header.crc) * 2 + header.side_info_len(); + let tag = frame.get(at..at + 8)?; + if &tag[..4] != b"Xing" && &tag[..4] != b"Info" { + return None; + } + let flags = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]); + if flags & 1 == 0 { + return None; + } + let n = frame.get(at + 8..at + 12)?; + let frames = u64::from(u32::from_be_bytes([n[0], n[1], n[2], n[3]])); + // The gapless extension sits behind whichever optional fields the flags + // claimed -- frame count, byte count, the 100-byte seek table, quality -- + // and states the two trims 21 bytes into itself, twelve bits each. + let mut extension_at = at + 12; + extension_at += usize::from(flags & 2 != 0) * 4; + extension_at += usize::from(flags & 4 != 0) * 100; + extension_at += usize::from(flags & 8 != 0) * 4; + let (delay, padding) = match frame.get(extension_at + 21..extension_at + 24) { + Some(&[a, b, c]) => ( + u32::from(a) << 4 | u32::from(b) >> 4, + (u32::from(b) & 0xF) << 8 | u32::from(c), + ), + _ => (0, 0), + }; + Some(Xing { + frames, + delay, + padding, + }) +} + +/// What an MP3's Xing/Info header states: how long the file is, and the two +/// silences the encoder had to add to make whole frames of it. +struct Xing { + /// Audio frames in the file, the header frame itself excluded. + frames: u64, + /// Encoder delay: samples of silence in front of the first real one. + delay: u32, + /// Encoder padding: samples of silence after the last real one. + padding: u32, +}