mirror of
https://github.com/storytold/effectcraft.git
synced 2026-11-27 04:38:38 +00:00
media: honor delayed PCM starts in shared AVI (#4071)
This commit is contained in:
@@ -599,7 +599,7 @@ fn compute_audio_starts(container: &ContainerFile, track_idx: usize, codec: Code
|
||||
let den = i128::from(s.rate.max(1));
|
||||
let scale = i128::from(s.scale.max(1));
|
||||
if s.sample_size > 0 {
|
||||
let mut acc = 0i64;
|
||||
let mut acc = delayed_avi_pcm_start(s).map_or(0, |(start, _)| start);
|
||||
return AudioStarts::complete(
|
||||
s.chunks
|
||||
.iter()
|
||||
@@ -1390,6 +1390,33 @@ fn default_video_info(width: u32, height: u32, frame_rate: FrameRate, codec: &Co
|
||||
}
|
||||
}
|
||||
|
||||
/// A byte-timed PCM stream uses one indexed unit per interleaved sample frame.
|
||||
/// Convert its stream-clock start to native samples before counting those units.
|
||||
fn delayed_avi_pcm_start(stream: &avi::Stream) -> Option<(i64, u32)> {
|
||||
if stream.start == 0 || stream.scale == 0 || stream.rate == 0 {
|
||||
return None;
|
||||
}
|
||||
let wave = stream.audio.as_ref()?;
|
||||
if !matches!((wave.format_tag, wave.bits_per_sample), (1, 8 | 16 | 24 | 32) | (3, 32 | 64)) {
|
||||
return None;
|
||||
}
|
||||
let (sample_rate, channels) = filmcraft_media::bounded_audio_dimensions(wave.sample_rate, u32::from(wave.channels)).ok()?;
|
||||
let packed = u32::from(wave.bits_per_sample.div_ceil(8)) * channels;
|
||||
// The shared decoder consumes packed PCM. Keep the prior route when the
|
||||
// indexed sample size or block padding implies a different packet clock.
|
||||
if stream.sample_size != packed || u32::from(wave.block_align) > packed {
|
||||
return None;
|
||||
}
|
||||
let start = i128::from(stream.start) * i128::from(stream.scale) * i128::from(sample_rate) / i128::from(stream.rate);
|
||||
Some((i64::try_from(start).ok()?, sample_rate))
|
||||
}
|
||||
|
||||
fn delayed_avi_pcm_end(stream: &avi::Stream) -> Option<Tick> {
|
||||
let (start, sample_rate) = delayed_avi_pcm_start(stream)?;
|
||||
let end = stream.chunks.iter().fold(start, |frames, chunk| frames.saturating_add(i64::from(chunk.size / stream.sample_size)));
|
||||
Some(Tick::from_units(end, i64::from(sample_rate)))
|
||||
}
|
||||
|
||||
fn open_avi(name: &str, source: SharedBytes) -> Option<Result<SharedSource>> {
|
||||
let file = avi::open(&*source).ok()?;
|
||||
let video_idx = file.streams.iter().position(|s| s.kind == avi::StreamKind::Video && !s.chunks.is_empty() && s.rate > 0 && s.scale > 0);
|
||||
@@ -1404,22 +1431,25 @@ fn open_avi(name: &str, source: SharedBytes) -> Option<Result<SharedSource>> {
|
||||
if video_idx.is_none() && audio_candidates.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let delayed_audio_end = audio_candidates.iter().filter_map(|&(idx, _, _, _)| delayed_avi_pcm_end(&file.streams[idx])).max().unwrap_or(Tick::ZERO);
|
||||
|
||||
if let Some(idx) = video_idx
|
||||
&& let Some(raw) = RawAvi::new(&file.streams[idx])
|
||||
{
|
||||
// Shared AVI audio positions are relative to the first chunk. Keep the
|
||||
// legacy path for a track with a separate stream start.
|
||||
if audio_candidates.iter().any(|&(audio, _, _, _)| file.streams[audio].start != 0) {
|
||||
if audio_candidates.iter().any(|&(audio, _, _, _)| {
|
||||
let stream = &file.streams[audio];
|
||||
stream.start != 0 && delayed_avi_pcm_start(stream).is_none()
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
let duration = audio_candidates
|
||||
.iter()
|
||||
.filter(|&&(audio, _, _, _)| file.streams[audio].start == 0)
|
||||
.map(|&(audio, _, _, _)| {
|
||||
let s = &file.streams[audio];
|
||||
Tick::from_units(i64::from(s.length).saturating_mul(i64::from(s.scale.max(1))), i64::from(s.rate.max(1)))
|
||||
})
|
||||
.fold(raw.duration(file.streams[idx].chunks.len()), Tick::max);
|
||||
.fold(raw.duration(file.streams[idx].chunks.len()).max(delayed_audio_end), Tick::max);
|
||||
let video = ContainerVideoPart { track_idx: idx, info: raw.info(&file.streams[idx]), state: Mutex::new(VideoState::RawAvi(raw)) };
|
||||
return finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), Some(video), duration, audio_candidates);
|
||||
}
|
||||
@@ -1453,6 +1483,7 @@ fn open_avi(name: &str, source: SharedBytes) -> Option<Result<SharedSource>> {
|
||||
} else {
|
||||
let duration = audio_candidates
|
||||
.iter()
|
||||
.filter(|&&(idx, _, _, _)| delayed_avi_pcm_start(&file.streams[idx]).is_none())
|
||||
.map(|(idx, _, params, _)| {
|
||||
let s = &file.streams[*idx];
|
||||
let units = if params.codec == CodecId::Pcm && s.sample_size > 0 {
|
||||
@@ -1468,7 +1499,7 @@ fn open_avi(name: &str, source: SharedBytes) -> Option<Result<SharedSource>> {
|
||||
(None, duration)
|
||||
};
|
||||
|
||||
finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), video, duration, audio_candidates)
|
||||
finish_container_source(name, "avi", source, ContainerFile::Avi(Box::new(file)), video, duration.max(delayed_audio_end), audio_candidates)
|
||||
}
|
||||
|
||||
fn estimate_mpeg_frame_rate_pts(pts: impl IntoIterator<Item = i64>) -> FrameRate {
|
||||
|
||||
@@ -97,3 +97,77 @@ fn raw_rgb_avi_with_dropped_slot_keeps_legacy_playback() -> Result<(), Box<dyn s
|
||||
assert_eq!((frame.width, frame.height), (WIDTH, HEIGHT));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn audio_header(bytes: &[u8]) -> Result<usize, &'static str> {
|
||||
bytes.windows(12).position(|window| &window[..4] == b"strh" && &window[8..] == b"auds").map(|offset| offset + 8).ok_or("AVI audio stream header")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delayed_avi_pcm_keeps_raw_rgb_and_reports_the_later_audio_end() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut bytes = fixture(24, true, false)?;
|
||||
let at = audio_header(&bytes)?;
|
||||
let delay = AUDIO_PER_FRAME as u32 + 13;
|
||||
bytes[at + 28..at + 32].copy_from_slice(&delay.to_le_bytes()); // dwStart
|
||||
bytes[at + 32..at + 36].copy_from_slice(&1u32.to_le_bytes()); // stale dwLength
|
||||
|
||||
let bytes: Arc<[u8]> = bytes.into();
|
||||
let dir = tempfile::tempdir()?;
|
||||
let path = dir.path().join("delayed-rgb.avi");
|
||||
std::fs::write(&path, &bytes)?;
|
||||
let end = Tick::from_units(i64::from(delay) + 3 * AUDIO_PER_FRAME as i64, i64::from(AUDIO_RATE));
|
||||
for info in [crate::probe::probe(&path)?, crate::probe::probe_bytes("delayed-rgb.avi", bytes.clone())?] {
|
||||
assert_eq!(info.duration.0, end.0);
|
||||
assert!(info.has_audio && info.has_video);
|
||||
}
|
||||
let disk = stream::open_source(&path).ok_or("unrecognized AVI")?.0?;
|
||||
let memory = stream::open_bytes("delayed-rgb.avi", bytes)?;
|
||||
for opened in [disk, memory] {
|
||||
let MediaSource::Craft(source) = opened else { panic!("delayed fixed-size PCM should stay on the shared RGB route") };
|
||||
let frame = source.video_frame(FrameRequest { time: Tick::from_units(1, i64::from(FPS)), scale: 1.0 })?;
|
||||
let PixelData::Rgba8(pixels) = &frame.data else { panic!("expected RGBA picture") };
|
||||
assert_eq!(&pixels[..4], &rgba(1, 0, 0));
|
||||
|
||||
let delay = i64::from(delay);
|
||||
let after = source.audio(delay + AUDIO_PER_FRAME as i64, 2, AUDIO_RATE)?;
|
||||
assert_eq!(after.channels[0], [2000.0 / 32768.0; 2]);
|
||||
let first = source.audio(delay - 2, 4, AUDIO_RATE)?;
|
||||
assert_eq!(first.channels[0], [0.0, 0.0, 1000.0 / 32768.0, 1000.0 / 32768.0]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delayed_avi_pcm_audio_only_uses_the_stream_clock_and_indexed_samples() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let audio = avi::StreamSpec::Audio(avi::AudioSpec::pcm(AUDIO_RATE, 1, 16));
|
||||
let mut writer = avi::AviWriter::new(Cursor::new(Vec::new()), vec![audio], avi::MuxOptions::default())?;
|
||||
writer.write_chunk(0, &8192i16.to_le_bytes().repeat(5), true)?;
|
||||
writer.write_chunk(0, &16384i16.to_le_bytes().repeat(9), true)?;
|
||||
let mut bytes = writer.finish()?.into_inner();
|
||||
let at = audio_header(&bytes)?;
|
||||
// This stream clock places dwStart at 4.8 native samples, truncated to 4.
|
||||
bytes[at + 20..at + 24].copy_from_slice(&1u32.to_le_bytes());
|
||||
bytes[at + 24..at + 28].copy_from_slice(&5000u32.to_le_bytes());
|
||||
bytes[at + 28..at + 32].copy_from_slice(&3u32.to_le_bytes());
|
||||
bytes[at + 32..at + 36].copy_from_slice(&200u32.to_le_bytes());
|
||||
|
||||
let bytes: Arc<[u8]> = bytes.into();
|
||||
let opened = stream::open_bytes("delayed-pcm.avi", bytes.clone())?;
|
||||
let MediaSource::Craft(source) = opened else { panic!("expected shared PCM reader") };
|
||||
assert_eq!(source.audio(0, 6, AUDIO_RATE)?.channels[0], [0.0, 0.0, 0.0, 0.0, 0.25, 0.25]);
|
||||
assert_eq!(source.audio(17, 2, AUDIO_RATE)?.channels[0], [0.5, 0.0]);
|
||||
let info = crate::probe::probe_bytes("delayed-pcm.avi", bytes)?;
|
||||
assert_eq!(info.duration.0, Tick::from_units(18, i64::from(AUDIO_RATE)).0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delayed_avi_pcm_with_conflicting_block_size_keeps_legacy_rgb_route() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut bytes = fixture(24, true, false)?;
|
||||
let at = audio_header(&bytes)?;
|
||||
bytes[at + 28..at + 32].copy_from_slice(&16u32.to_le_bytes());
|
||||
bytes[at + 44..at + 48].copy_from_slice(&1u32.to_le_bytes()); // dwSampleSize
|
||||
let opened = stream::open_bytes("delayed-pcm-block.avi", bytes.into())?;
|
||||
let MediaSource::Film(source) = opened else { panic!("expected legacy PCM block alignment") };
|
||||
assert_eq!(source.audio(15, 2, AUDIO_RATE)?.channels[0], [0.0, 1000.0 / 32768.0]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user