Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions crates/rendering/src/decoder/avassetreader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,7 @@ impl AVAssetReaderDecoder {
path: PathBuf,
tokio_handle: TokioHandle,
keyframe_index: Option<Arc<cap_video_decode::avassetreader::KeyframeIndex>>,
requested_time: f32,
) -> Result<Self, String> {
let fps = keyframe_index
.as_ref()
Expand All @@ -455,7 +456,7 @@ impl AVAssetReaderDecoder {
duration_secs,
};

let pool_manager = DecoderPoolManager::new(config);
let mut pool_manager = DecoderPoolManager::new(config);

let permit = tokio_handle
.block_on(async {
Expand All @@ -471,10 +472,11 @@ impl AVAssetReaderDecoder {
let primary_instance = DecoderInstance::new(
path.clone(),
tokio_handle.clone(),
0.0,
requested_time,
keyframe_index_arc.clone(),
permit,
)?;
pool_manager.update_decoder_position(0, primary_instance.current_position());

// Linear playback only needs one reader. Additional readers retain
// AVFoundation state and decoded buffers, so create them only when a
Expand Down Expand Up @@ -827,7 +829,12 @@ impl AVAssetReaderDecoder {
.ok()
.map(Arc::new);
}
match Self::new(path.clone(), tokio_handle.clone(), keyframe_index.clone()) {
match Self::new(
path.clone(),
tokio_handle.clone(),
keyframe_index.clone(),
requested_time,
) {
Ok(decoder) => this = Some(decoder),
Err(error) => {
tracing::warn!(%error, "Failed to initialize video reader on demand");
Expand Down
85 changes: 85 additions & 0 deletions crates/rendering/tests/cold_seek.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#![cfg(target_os = "macos")]

use cap_rendering::{
DecodedFrame, PixelFormat,
decoder::{DecoderType, spawn_decoder},
};
use std::{
collections::{BTreeMap, hash_map::DefaultHasher},
hash::{Hash, Hasher},
path::PathBuf,
time::Duration,
};

fn pixels(frame: &DecodedFrame) -> u64 {
let mut hash = DefaultHasher::new();
frame.width().hash(&mut hash);
frame.height().hash(&mut hash);
match frame.format() {
PixelFormat::Nv12 => {
for (plane, stride) in [
(frame.y_plane().unwrap(), frame.y_stride()),
(frame.uv_plane().unwrap(), frame.uv_stride()),
] {
for row in plane.chunks_exact(stride as usize) {
row[..frame.width() as usize].hash(&mut hash);
}
}
}
other => panic!("Expected native NV12 frames, got {other:?}"),
}
hash.finish()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "Requires CAP_DECODER_TEST_VIDEO (at least 8 seconds) and CAP_DECODER_TEST_FPS on macOS"]
async fn cold_and_idle_seeks_match_sequential_decode() {
ffmpeg::init().unwrap();
let path = PathBuf::from(std::env::var_os("CAP_DECODER_TEST_VIDEO").unwrap());
let fps: u32 = std::env::var("CAP_DECODER_TEST_FPS")
.unwrap()
.parse()
.unwrap();
assert!(fps > 0);
let probe_frames = [
0,
1,
fps,
3 * fps,
5 * fps - 1,
5 * fps,
7 * fps,
7 * fps + 1,
];
let sequential = spawn_decoder("sequential", path.clone(), fps, 0.0, false)
.await
.unwrap();
let mut expected = BTreeMap::new();
for number in 0..=*probe_frames.last().unwrap() {
let frame = sequential
.get_frame_initial(number as f32 / fps as f32)
.await
.unwrap();
if probe_frames.contains(&number) {
expected.insert(number, pixels(&frame));
}
}
drop(sequential);
let resumed = spawn_decoder("resumed", path.clone(), fps, 0.0, false)
.await
.unwrap();
for &number in probe_frames.iter().rev() {
let time = number as f32 / fps as f32;
let cold = spawn_decoder("cold", path.clone(), fps, 0.0, false)
.await
.unwrap();
let frame = cold.get_frame_initial(time).await.unwrap();
assert_eq!(pixels(&frame), expected[&number], "Cold seek at {time}");
assert_eq!(cold.decoder_type(), DecoderType::AVAssetReader);
drop(cold);
tokio::time::sleep(Duration::from_millis(350)).await;
let frame = resumed.get_frame_initial(time).await.unwrap();
assert_eq!(pixels(&frame), expected[&number], "Idle seek at {time}");
assert_eq!(resumed.decoder_type(), DecoderType::AVAssetReader);
}
}
49 changes: 42 additions & 7 deletions crates/video-decode/src/avassetreader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,13 +378,13 @@ impl KeyframeIndex {

fn compute_seek_time(keyframe_index: Option<&Arc<KeyframeIndex>>, requested_time: f32) -> f32 {
if let Some(kf_index) = keyframe_index {
let fps = kf_index.fps();
let target_frame = (requested_time as f64 * fps).round() as u32;
if let Some((_, keyframe_time)) = kf_index.nearest_keyframe_before(target_frame) {
return keyframe_time as f32;
}
if let Some((_, first_keyframe_time)) = kf_index.keyframes().first() {
return *first_keyframe_time as f32;
let keyframes = kf_index.keyframes();
// Rounded frame numbers can alias keyframes across a VFR gap and seek
// past the image that should still be held at the requested time.
let after_request =
keyframes.partition_point(|(_, time)| *time <= f64::from(requested_time));
if let Some((_, keyframe_time)) = keyframes.get(after_request.saturating_sub(1)) {
return *keyframe_time as f32;
}
}
requested_time
Expand Down Expand Up @@ -661,6 +661,41 @@ mod tests {

type Keyframes = Vec<(u32, f64)>;

fn seek_index(keyframes: Keyframes) -> Arc<KeyframeIndex> {
Arc::new(KeyframeIndex {
keyframes,
fps: 2.0,
duration_secs: 8.0,
pixel_format: None,
width: 0,
height: 0,
})
}

#[test]
fn seek_time_does_not_round_forward_across_a_vfr_gap() {
let index = seek_index(vec![(0, 0.0), (6, 3.2), (10, 5.0)]);
assert_eq!(compute_seek_time(Some(&index), 3.0), 0.0);
assert_eq!(compute_seek_time(Some(&index), 3.2), 3.2);
assert_eq!(compute_seek_time(Some(&index), 4.9), 3.2);
assert_eq!(compute_seek_time(Some(&index), 5.0), 5.0);
}

#[test]
fn seek_time_distinguishes_keyframes_with_the_same_rounded_number() {
let index = seek_index(vec![(0, 0.0), (6, 2.8), (6, 3.2)]);
assert_eq!(compute_seek_time(Some(&index), 3.0), 2.8);
}

#[test]
fn seek_time_preserves_start_and_missing_index_fallbacks() {
let index = seek_index(vec![(1, 0.3), (2, 1.0)]);
assert_eq!(compute_seek_time(Some(&index), 0.0), 0.3);
assert_eq!(compute_seek_time(Some(&index), 8.0), 1.0);
assert_eq!(compute_seek_time(Some(&seek_index(Vec::new())), 3.0), 3.0);
assert_eq!(compute_seek_time(None, 3.0), 3.0);
}

fn both_indexes(path: &Path) -> Option<(Option<Keyframes>, Keyframes)> {
ffmpeg::init().unwrap();
let mut input = avformat::input(path).ok()?;
Expand Down
Loading