Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add multi-position decoder pool for AVAssetReader

Richie McIlroycf969693ccea
diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs
index 43e96a7ea..db6ea9d38 100644
--- a/crates/rendering/src/decoder/avassetreader.rs
+++ b/crates/rendering/src/decoder/avassetreader.rs
@@ -18,6 +18,7 @@ use tokio::{runtime::Handle as TokioHandle, sync::oneshot};
use crate::{DecodedFrame, PixelFormat};
use super::frame_converter::{copy_bgra_to_rgba, copy_rgba_plane};
+use super::multi_position::{DecoderPoolManager, MultiPositionDecoderConfig, ScrubDetector};
use super::{DecoderInitResult, DecoderType, FRAME_CACHE_SIZE, VideoDecoderMessage, pts_to_frame};
struct SendableImageBuf(R<cv::ImageBuf>);
@@ -296,21 +297,141 @@ impl CachedFrame {
}
}
-pub struct AVAssetReaderDecoder {
+struct DecoderInstance {
inner: cap_video_decode::AVAssetReaderDecoder,
is_done: bool,
+ frames_iter_valid: bool,
}
-impl AVAssetReaderDecoder {
- fn new(path: PathBuf, tokio_handle: TokioHandle) -> Result<Self, String> {
+impl DecoderInstance {
+ fn new(
+ path: PathBuf,
+ tokio_handle: TokioHandle,
+ start_time: f32,
+ keyframe_index: Option<cap_video_decode::avassetreader::KeyframeIndex>,
+ ) -> Result<Self, String> {
Ok(Self {
- inner: cap_video_decode::AVAssetReaderDecoder::new(path, tokio_handle)?,
+ inner: cap_video_decode::AVAssetReaderDecoder::new_with_keyframe_index(
+ path,
+ tokio_handle,
+ start_time,
+ keyframe_index,
+ )?,
is_done: false,
+ frames_iter_valid: true,
})
}
fn reset(&mut self, requested_time: f32) {
let _ = self.inner.reset(requested_time);
+ self.is_done = false;
+ self.frames_iter_valid = true;
+ }
+
+ fn current_position(&self) -> f32 {
+ self.inner.current_position_secs()
+ }
+}
+
+pub struct AVAssetReaderDecoder {
+ decoders: Vec<DecoderInstance>,
+ pool_manager: DecoderPoolManager,
+ active_decoder_idx: usize,
+ scrub_detector: ScrubDetector,
+}
+
+impl AVAssetReaderDecoder {
+ fn new(path: PathBuf, tokio_handle: TokioHandle) -> Result<Self, String> {
+ let mut primary_decoder =
+ cap_video_decode::AVAssetReaderDecoder::new(path.clone(), tokio_handle.clone())?;
+
+ let keyframe_index = primary_decoder.take_keyframe_index();
+ let keyframe_index_arc: Option<Arc<cap_video_decode::avassetreader::KeyframeIndex>> = None;
+
+ let fps = keyframe_index
+ .as_ref()
+ .map(|kf| kf.fps() as u32)
+ .unwrap_or(30);
+ let duration_secs = keyframe_index
+ .as_ref()
+ .map(|kf| kf.duration_secs())
+ .unwrap_or(0.0);
+
+ let config = MultiPositionDecoderConfig {
+ path: path.clone(),
+ tokio_handle: tokio_handle.clone(),
+ keyframe_index: keyframe_index_arc,
+ fps,
+ duration_secs,
+ };
+
+ let pool_manager = DecoderPoolManager::new(config);
+
+ let primary_instance = DecoderInstance {
+ inner: primary_decoder,
+ is_done: false,
+ frames_iter_valid: true,
+ };
+
+ let mut decoders = vec![primary_instance];
+
+ let initial_positions = pool_manager.positions();
+ for pos in initial_positions.iter().skip(1) {
+ let start_time = pos.position_secs;
+ match DecoderInstance::new(path.clone(), tokio_handle.clone(), start_time, None) {
+ Ok(instance) => {
+ decoders.push(instance);
+ tracing::info!(
+ position_secs = start_time,
+ decoder_index = decoders.len() - 1,
+ "Created additional decoder instance for multi-position pool"
+ );
+ }
+ Err(e) => {
+ tracing::warn!(
+ position_secs = start_time,
+ error = %e,
+ "Failed to create additional decoder instance, continuing with fewer decoders"
+ );
+ }
+ }
+ }
+
+ tracing::info!(
+ decoder_count = decoders.len(),
+ fps = fps,
+ duration_secs = duration_secs,
+ "Initialized multi-position decoder pool"
+ );
+
+ Ok(Self {
+ decoders,
+ pool_manager,
+ active_decoder_idx: 0,
+ scrub_detector: ScrubDetector::new(),
+ })
+ }
+
+ fn select_best_decoder(&mut self, requested_time: f32) -> (usize, bool) {
+ let (best_id, distance, needs_reset) =
+ self.pool_manager.find_best_decoder_for_time(requested_time);
+
+ let decoder_idx = best_id.min(self.decoders.len().saturating_sub(1));
+
+ if needs_reset && decoder_idx < self.decoders.len() {
+ tracing::debug!(
+ decoder_idx = decoder_idx,
+ requested_time = requested_time,
+ distance = distance,
+ "Resetting decoder for seek"
+ );
+ self.decoders[decoder_idx].reset(requested_time);
+ self.pool_manager
+ .update_decoder_position(best_id, self.decoders[decoder_idx].current_position());
+ }
+
+ self.active_decoder_idx = decoder_idx;
+ (decoder_idx, needs_reset)
}
pub fn spawn(
@@ -341,8 +462,8 @@ impl AVAssetReaderDecoder {
}
};
- let video_width = this.inner.width();
- let video_height = this.inner.height();
+ let video_width = this.decoders[0].inner.width();
+ let video_height = this.decoders[0].inner.height();
let init_result = DecoderInitResult {
width: video_width,
@@ -358,7 +479,6 @@ impl AVAssetReaderDecoder {
let last_sent_frame = Rc::new(RefCell::new(None::<ProcessedFrame>));
let first_ever_frame = Rc::new(RefCell::new(None::<ProcessedFrame>));
- let mut frames = this.inner.frames();
let processor = ImageBufProcessor::new();
struct PendingRequest {
@@ -397,6 +517,12 @@ impl AVAssetReaderDecoder {
pending_requests.sort_by_key(|r| r.frame);
+ let is_scrubbing = if let Some(first_req) = pending_requests.first() {
+ this.scrub_detector.record_request(first_req.frame)
+ } else {
+ false
+ };
+
let mut i = 0;
while i < pending_requests.len() {
let request = &pending_requests[i];
@@ -421,35 +547,16 @@ impl AVAssetReaderDecoder {
let requested_frame = min_requested_frame;
let requested_time = requested_frame as f32 / fps as f32;
- const BACKWARD_SEEK_TOLERANCE: u32 = 120;
+ let (decoder_idx, was_reset) = this.select_best_decoder(requested_time);
let cache_min = min_requested_frame.saturating_sub(FRAME_CACHE_SIZE as u32 / 2);
- let cache_max = max_requested_frame + FRAME_CACHE_SIZE as u32 / 2;
-
- let cache_frame_min = cache.keys().next().copied();
- let cache_frame_max = cache.keys().next_back().copied();
-
- let needs_reset = if let (Some(c_min), Some(c_max)) = (cache_frame_min, cache_frame_max)
- {
- let is_backward_seek_beyond_tolerance =
- requested_frame + BACKWARD_SEEK_TOLERANCE < c_min;
- let is_forward_seek_beyond_cache =
- requested_frame > c_max + FRAME_CACHE_SIZE as u32 / 4;
- is_backward_seek_beyond_tolerance || is_forward_seek_beyond_cache
+ let cache_max = if is_scrubbing {
+ max_requested_frame + FRAME_CACHE_SIZE as u32 / 4
} else {
- true
+ max_requested_frame + FRAME_CACHE_SIZE as u32 / 2
};
- if needs_reset {
- debug!(
- decoder = _name,
- requested_frame = requested_frame,
- cache_min = ?cache_frame_min,
- cache_max = ?cache_frame_max,
- "Triggering decoder reset"
- );
- this.reset(requested_time);
- frames = this.inner.frames();
+ if was_reset {
*last_sent_frame.borrow_mut() = None;
cache.retain(|&f, _| f >= cache_min && f <= cache_max);
}
@@ -458,84 +565,109 @@ impl AVAssetReaderDecoder {
let mut exit = false;
let mut frames_iterated = 0u32;
+ let mut last_decoded_position: Option<f32> = None;
- for frame in &mut frames {
- let Ok(frame) = frame.map_err(|e| format!("read frame / {e}")) else {
- continue;
- };
- frames_iterated += 1;
+ {
+ let decoder = &mut this.decoders[decoder_idx];
+ let mut frames = decoder.inner.frames();
- let current_frame =
- pts_to_frame(frame.pts().value, Rational::new(1, frame.pts().scale), fps);
+ for frame in &mut frames {
+ let Ok(frame) = frame.map_err(|e| format!("read frame / {e}")) else {
+ continue;
+ };
+ frames_iterated += 1;
- let Some(frame) = frame.image_buf() else {
- continue;
- };
+ let current_frame =
+ pts_to_frame(frame.pts().value, Rational::new(1, frame.pts().scale), fps);
- let cache_frame = CachedFrame::new(&processor, frame.retained(), current_frame);
+ let position_secs = current_frame as f32 / fps as f32;
+ last_decoded_position = Some(position_secs);
- if first_ever_frame.borrow().is_none() {
- *first_ever_frame.borrow_mut() = Some(cache_frame.data().clone());
- }
+ let Some(frame) = frame.image_buf() else {
+ continue;
+ };
- this.is_done = false;
+ let cache_frame = CachedFrame::new(&processor, frame.retained(), current_frame);
- let exceeds_cache_bounds = current_frame > cache_max;
- let too_small_for_cache_bounds = current_frame < cache_min;
+ if first_ever_frame.borrow().is_none() {
+ *first_ever_frame.borrow_mut() = Some(cache_frame.data().clone());
+ }
- if !too_small_for_cache_bounds {
- if cache.len() >= FRAME_CACHE_SIZE {
- if let Some(last_active) = &last_active_frame {
- let frame_to_remove = if requested_frame > *last_active {
- *cache.keys().next().unwrap()
- } else if requested_frame < *last_active {
- *cache.keys().next_back().unwrap()
+ decoder.is_done = false;
+
+ let exceeds_cache_bounds = current_frame > cache_max;
+ let too_small_for_cache_bounds = current_frame < cache_min;
+
+ if !too_small_for_cache_bounds {
+ if cache.len() >= FRAME_CACHE_SIZE {
+ if let Some(last_active) = &last_active_frame {
+ let frame_to_remove = if requested_frame > *last_active {
+ *cache.keys().next().unwrap()
+ } else if requested_frame < *last_active {
+ *cache.keys().next_back().unwrap()
+ } else {
+ let min = *cache.keys().min().unwrap();
+ let max = *cache.keys().max().unwrap();
+ if current_frame > max { min } else { max }
+ };
+ cache.remove(&frame_to_remove);
} else {
- let min = *cache.keys().min().unwrap();
- let max = *cache.keys().max().unwrap();
- if current_frame > max { min } else { max }
- };
- cache.remove(&frame_to_remove);
- } else {
- cache.clear()
+ cache.clear()
+ }
}
- }
- cache.insert(current_frame, cache_frame.clone());
+ cache.insert(current_frame, cache_frame.clone());
- let mut remaining_requests = Vec::with_capacity(pending_requests.len());
- for req in pending_requests.drain(..) {
- if req.frame == current_frame {
- let data = cache_frame.data().clone();
- *last_sent_frame.borrow_mut() = Some(data.clone());
- if req.sender.send(data.to_decoded_frame()).is_err() {
- debug!("frame receiver dropped before send");
- }
- } else if req.frame < current_frame {
- if let Some(cached) = cache.get(&req.frame) {
- let data = cached.data().clone();
+ let mut remaining_requests = Vec::with_capacity(pending_requests.len());
+ for req in pending_requests.drain(..) {
+ if req.frame == current_frame {
+ let data = cache_frame.data().clone();
*last_sent_frame.borrow_mut() = Some(data.clone());
if req.sender.send(data.to_decoded_frame()).is_err() {
debug!("frame receiver dropped before send");
}
+ } else if req.frame < current_frame {
+ if let Some(cached) = cache.get(&req.frame) {
+ let data = cached.data().clone();
+ *last_sent_frame.borrow_mut() = Some(data.clone());
+ if req.sender.send(data.to_decoded_frame()).is_err() {
+ debug!("frame receiver dropped before send");
+ }
+ } else if is_scrubbing {
+ let data = cache_frame.data().clone();
+ *last_sent_frame.borrow_mut() = Some(data.clone());
+ if req.sender.send(data.to_decoded_frame()).is_err() {
+ debug!(
+ "frame receiver dropped before send (scrub fallback)"
+ );
+ }
+ }
+ } else {
+ remaining_requests.push(req);
}
- } else {
- remaining_requests.push(req);
}
+ pending_requests = remaining_requests;
}
- pending_requests = remaining_requests;
- }
- *last_sent_frame.borrow_mut() = Some(cache_frame.data().clone());
+ *last_sent_frame.borrow_mut() = Some(cache_frame.data().clone());
- exit = exit || exceeds_cache_bounds;
+ exit = exit || exceeds_cache_bounds;
+
+ if is_scrubbing && frames_iterated > 3 {
+ break;
+ }
- if pending_requests.is_empty() || exit {
- break;
+ if pending_requests.is_empty() || exit {
+ break;
+ }
}
+
+ decoder.is_done = true;
}
- this.is_done = true;
+ if let Some(pos) = last_decoded_position {
+ this.pool_manager.update_decoder_position(decoder_idx, pos);
+ }
if !pending_requests.is_empty() {
debug!(
@@ -543,6 +675,7 @@ impl AVAssetReaderDecoder {
pending_count = pending_requests.len(),
frames_iterated = frames_iterated,
cache_size = cache.len(),
+ is_scrubbing = is_scrubbing,
"Handling unfulfilled requests after frame iteration"
);
}
@@ -557,6 +690,7 @@ impl AVAssetReaderDecoder {
debug!(
decoder = _name,
requested_frame = req.frame,
+ is_scrubbing = is_scrubbing,
"Sending last known frame as fallback"
);
if req.sender.send(last.to_decoded_frame()).is_err() {
diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rs
index 5eb56ed79..f02800b2d 100644
--- a/crates/rendering/src/decoder/mod.rs
+++ b/crates/rendering/src/decoder/mod.rs
@@ -16,6 +16,8 @@ mod ffmpeg;
mod frame_converter;
#[cfg(target_os = "windows")]
mod media_foundation;
+#[cfg(target_os = "macos")]
+pub mod multi_position;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecoderType {
diff --git a/crates/rendering/src/decoder/multi_position.rs b/crates/rendering/src/decoder/multi_position.rs
new file mode 100644
index 000000000..ce453a2ba
--- /dev/null
+++ b/crates/rendering/src/decoder/multi_position.rs
@@ -0,0 +1,247 @@
+use std::{collections::BTreeMap, path::PathBuf, sync::Arc};
+
+use tokio::runtime::Handle as TokioHandle;
+
+use cap_video_decode::avassetreader::KeyframeIndex;
+
+pub const MAX_DECODER_POOL_SIZE: usize = 3;
+pub const REPOSITION_THRESHOLD_SECS: f32 = 5.0;
+
+pub struct DecoderPosition {
+ pub id: usize,
+ pub position_secs: f32,
+ pub last_access_time: std::time::Instant,
+ pub access_count: u64,
+}
+
+impl DecoderPosition {
+ pub fn new(id: usize, position_secs: f32) -> Self {
+ Self {
+ id,
+ position_secs,
+ last_access_time: std::time::Instant::now(),
+ access_count: 0,
+ }
+ }
+
+ pub fn touch(&mut self) {
+ self.last_access_time = std::time::Instant::now();
+ self.access_count += 1;
+ }
+}
+
+pub struct MultiPositionDecoderConfig {
+ pub path: PathBuf,
+ pub tokio_handle: TokioHandle,
+ pub keyframe_index: Option<Arc<KeyframeIndex>>,
+ pub fps: u32,
+ pub duration_secs: f64,
+}
+
+pub struct DecoderPoolManager {
+ config: MultiPositionDecoderConfig,
+ positions: Vec<DecoderPosition>,
+ access_history: BTreeMap<u32, u64>,
+ total_accesses: u64,
+}
+
+impl DecoderPoolManager {
+ pub fn new(config: MultiPositionDecoderConfig) -> Self {
+ let initial_positions = Self::calculate_initial_positions(&config);
+
+ let positions: Vec<DecoderPosition> = initial_positions
+ .into_iter()
+ .enumerate()
+ .map(|(id, pos)| DecoderPosition::new(id, pos))
+ .collect();
+
+ Self {
+ config,
+ positions,
+ access_history: BTreeMap::new(),
+ total_accesses: 0,
+ }
+ }
+
+ fn calculate_initial_positions(config: &MultiPositionDecoderConfig) -> Vec<f32> {
+ if let Some(ref kf_index) = config.keyframe_index {
+ let strategic = kf_index.get_strategic_positions(MAX_DECODER_POOL_SIZE);
+ strategic.into_iter().map(|t| t as f32).collect()
+ } else {
+ let duration = config.duration_secs as f32;
+ if duration <= 0.0 {
+ vec![0.0]
+ } else {
+ (0..MAX_DECODER_POOL_SIZE)
+ .map(|i| {
+ let frac = i as f32 / MAX_DECODER_POOL_SIZE as f32;
+ (duration * frac).min(duration)
+ })
+ .collect()
+ }
+ }
+ }
+
+ pub fn find_best_decoder_for_time(&mut self, requested_time: f32) -> (usize, f32, bool) {
+ self.total_accesses += 1;
+
+ let frame = (requested_time * self.config.fps as f32).floor() as u32;
+ *self.access_history.entry(frame).or_insert(0) += 1;
+
+ let mut best_decoder_id = 0;
+ let mut best_distance = f32::MAX;
+ let mut needs_reset = true;
+
+ for position in &self.positions {
+ let distance = (position.position_secs - requested_time).abs();
+ let is_usable = position.position_secs <= requested_time
+ && (requested_time - position.position_secs) < REPOSITION_THRESHOLD_SECS;
+
+ if is_usable && distance < best_distance {
+ best_distance = distance;
+ best_decoder_id = position.id;
+ needs_reset = false;
+ }
+ }
+
+ if needs_reset {
+ for position in &self.positions {
+ let distance = (position.position_secs - requested_time).abs();
+ if distance < best_distance {
+ best_distance = distance;
+ best_decoder_id = position.id;
+ }
+ }
+ }
+
+ if let Some(pos) = self.positions.iter_mut().find(|p| p.id == best_decoder_id) {
+ pos.touch();
+ }
+
+ (best_decoder_id, best_distance, needs_reset)
+ }
+
+ pub fn update_decoder_position(&mut self, decoder_id: usize, new_position: f32) {
+ if let Some(pos) = self.positions.iter_mut().find(|p| p.id == decoder_id) {
+ pos.position_secs = new_position;
+ }
+ }
+
+ pub fn should_rebalance(&self) -> bool {
+ self.total_accesses > 0 && self.total_accesses % 100 == 0
+ }
+
+ pub fn get_rebalance_positions(&self) -> Vec<f32> {
+ if self.access_history.is_empty() {
+ return self.positions.iter().map(|p| p.position_secs).collect();
+ }
+
+ let mut hotspots: Vec<(u32, u64)> = self
+ .access_history
+ .iter()
+ .map(|(&frame, &count)| (frame, count))
+ .collect();
+ hotspots.sort_by(|a, b| b.1.cmp(&a.1));
+
+ let top_hotspots: Vec<f32> = hotspots
+ .into_iter()
+ .take(MAX_DECODER_POOL_SIZE)
+ .map(|(frame, _)| frame as f32 / self.config.fps as f32)
+ .collect();
+
+ if top_hotspots.len() < MAX_DECODER_POOL_SIZE {
+ let mut result = top_hotspots;
+ let remaining = MAX_DECODER_POOL_SIZE - result.len();
+ let duration = self.config.duration_secs as f32;
+ for i in 0..remaining {
+ let frac = (i + 1) as f32 / (remaining + 1) as f32;
+ result.push(duration * frac);
+ }
+ result
+ } else {
+ top_hotspots
+ }
+ }
+
+ pub fn positions(&self) -> &[DecoderPosition] {
+ &self.positions
+ }
+
+ pub fn config(&self) -> &MultiPositionDecoderConfig {
+ &self.config
+ }
+}
+
+pub struct ScrubDetector {
+ last_request_time: std::time::Instant,
+ last_frame: u32,
+ request_rate: f64,
+ is_scrubbing: bool,
+ scrub_start_time: Option<std::time::Instant>,
+}
+
+impl ScrubDetector {
+ const SCRUB_THRESHOLD_RATE: f64 = 5.0;
+ const SCRUB_COOLDOWN_MS: u64 = 150;
+
+ pub fn new() -> Self {
+ Self {
+ last_request_time: std::time::Instant::now(),
+ last_frame: 0,
+ request_rate: 0.0,
+ is_scrubbing: false,
+ scrub_start_time: None,
+ }
+ }
+
+ pub fn record_request(&mut self, frame: u32) -> bool {
+ let now = std::time::Instant::now();
+ let elapsed = now.duration_since(self.last_request_time);
+ let elapsed_secs = elapsed.as_secs_f64().max(0.001);
+
+ let frame_delta = frame.abs_diff(self.last_frame);
+
+ let instantaneous_rate = frame_delta as f64 / elapsed_secs;
+ self.request_rate = self.request_rate * 0.7 + instantaneous_rate * 0.3;
+
+ let was_scrubbing = self.is_scrubbing;
+
+ if self.request_rate > Self::SCRUB_THRESHOLD_RATE && frame_delta > 1 {
+ self.is_scrubbing = true;
+ if self.scrub_start_time.is_none() {
+ self.scrub_start_time = Some(now);
+ }
+ } else if elapsed.as_millis() as u64 > Self::SCRUB_COOLDOWN_MS {
+ self.is_scrubbing = false;
+ self.scrub_start_time = None;
+ }
+
+ self.last_request_time = now;
+ self.last_frame = frame;
+
+ if was_scrubbing != self.is_scrubbing {
+ tracing::debug!(
+ is_scrubbing = self.is_scrubbing,
+ request_rate = self.request_rate,
+ frame_delta = frame_delta,
+ "Scrub state changed"
+ );
+ }
+
+ self.is_scrubbing
+ }
+
+ pub fn is_scrubbing(&self) -> bool {
+ self.is_scrubbing
+ }
+
+ pub fn scrub_duration(&self) -> Option<std::time::Duration> {
+ self.scrub_start_time.map(|start| start.elapsed())
+ }
+}
+
+impl Default for ScrubDetector {
+ fn default() -> Self {
+ Self::new()
+ }
+}
diff --git a/crates/video-decode/src/avassetreader.rs b/crates/video-decode/src/avassetreader.rs
index efc9e9501..696fa2628 100644
--- a/crates/video-decode/src/avassetreader.rs
+++ b/crates/video-decode/src/avassetreader.rs
@@ -13,6 +13,7 @@ use tokio::runtime::Handle as TokioHandle;
pub struct KeyframeIndex {
keyframes: Vec<(u32, f64)>,
fps: f64,
+ duration_secs: f64,
}
impl KeyframeIndex {
@@ -38,6 +39,15 @@ impl KeyframeIndex {
}
};
+ let duration_secs = {
+ let duration = video_stream.duration();
+ if duration > 0 {
+ duration as f64 * time_base.numerator() as f64 / time_base.denominator() as f64
+ } else {
+ 0.0
+ }
+ };
+
let mut keyframes = Vec::new();
let mut input =
@@ -62,11 +72,16 @@ impl KeyframeIndex {
path = %path.display(),
keyframe_count = keyframes.len(),
fps = fps,
+ duration_secs = duration_secs,
build_ms = elapsed.as_millis(),
"Built keyframe index"
);
- Ok(Self { keyframes, fps })
+ Ok(Self {
+ keyframes,
+ fps,
+ duration_secs,
+ })
}
pub fn nearest_keyframe_before(&self, target_frame: u32) -> Option<(u32, f64)> {
@@ -87,13 +102,69 @@ impl KeyframeIndex {
Some(self.keyframes[idx])
}
+ pub fn nearest_keyframe_after(&self, target_frame: u32) -> Option<(u32, f64)> {
+ if self.keyframes.is_empty() {
+ return None;
+ }
+
+ let pos = self
+ .keyframes
+ .binary_search_by_key(&target_frame, |(frame, _)| *frame);
+
+ let idx = match pos {
+ Ok(i) => {
+ if i + 1 < self.keyframes.len() {
+ i + 1
+ } else {
+ i
+ }
+ }
+ Err(i) => {
+ if i < self.keyframes.len() {
+ i
+ } else {
+ return None;
+ }
+ }
+ };
+
+ Some(self.keyframes[idx])
+ }
+
+ pub fn get_strategic_positions(&self, num_positions: usize) -> Vec<f64> {
+ if self.keyframes.is_empty() || num_positions == 0 {
+ return vec![0.0];
+ }
+
+ let total_keyframes = self.keyframes.len();
+ if total_keyframes <= num_positions {
+ return self.keyframes.iter().map(|(_, time)| *time).collect();
+ }
+
+ let step = total_keyframes / num_positions;
+ self.keyframes
+ .iter()
+ .step_by(step.max(1))
+ .take(num_positions)
+ .map(|(_, time)| *time)
+ .collect()
+ }
+
pub fn fps(&self) -> f64 {
self.fps
}
+ pub fn duration_secs(&self) -> f64 {
+ self.duration_secs
+ }
+
pub fn keyframe_count(&self) -> usize {
self.keyframes.len()
}
+
+ pub fn keyframes(&self) -> &[(u32, f64)] {
+ &self.keyframes
+ }
}
pub struct AVAssetReaderDecoder {
@@ -105,10 +176,19 @@ pub struct AVAssetReaderDecoder {
width: u32,
height: u32,
keyframe_index: Option<KeyframeIndex>,
+ current_position_secs: f32,
}
impl AVAssetReaderDecoder {
pub fn new(path: PathBuf, tokio_handle: TokioHandle) -> Result<Self, String> {
+ Self::new_at_position(path, tokio_handle, 0.0)
+ }
+
+ pub fn new_at_position(
+ path: PathBuf,
+ tokio_handle: TokioHandle,
+ start_time: f32,
+ ) -> Result<Self, String> {
let keyframe_index = match KeyframeIndex::build(&path) {
Ok(index) => Some(index),
Err(e) => {
@@ -121,6 +201,15 @@ impl AVAssetReaderDecoder {
}
};
+ Self::new_with_keyframe_index(path, tokio_handle, start_time, keyframe_index)
+ }
+
+ pub fn new_with_keyframe_index(
+ path: PathBuf,
+ tokio_handle: TokioHandle,
+ start_time: f32,
+ keyframe_index: Option<KeyframeIndex>,
+ ) -> Result<Self, String> {
let (pixel_format, width, height) = {
let input = ffmpeg::format::input(&path).unwrap();
@@ -143,8 +232,26 @@ impl AVAssetReaderDecoder {
)
};
- let (track_output, reader) =
- Self::get_reader_track_output(&path, 0.0, &tokio_handle, pixel_format, width, height)?;
+ let seek_time = if let Some(ref kf_index) = keyframe_index {
+ let fps = kf_index.fps();
+ let target_frame = (start_time as f64 * fps).round() as u32;
+ if let Some((_, keyframe_time)) = kf_index.nearest_keyframe_before(target_frame) {
+ keyframe_time as f32
+ } else {
+ start_time
+ }
+ } else {
+ start_time
+ };
+
+ let (track_output, reader) = Self::get_reader_track_output(
+ &path,
+ seek_time,
+ &tokio_handle,
+ pixel_format,
+ width,
+ height,
+ )?;
Ok(Self {
path,
@@ -155,6 +262,7 @@ impl AVAssetReaderDecoder {
width,
height,
keyframe_index,
+ current_position_secs: seek_time,
})
}
@@ -187,6 +295,8 @@ impl AVAssetReaderDecoder {
self.height,
)?;
+ self.current_position_secs = seek_time;
+
let elapsed = reset_start.elapsed();
tracing::info!(
requested_time = requested_time,
@@ -200,6 +310,26 @@ impl AVAssetReaderDecoder {
Ok(())
}
+ pub fn current_position_secs(&self) -> f32 {
+ self.current_position_secs
+ }
+
+ pub fn update_position(&mut self, position_secs: f32) {
+ self.current_position_secs = position_secs;
+ }
+
+ pub fn path(&self) -> &PathBuf {
+ &self.path
+ }
+
+ pub fn pixel_format(&self) -> cv::PixelFormat {
+ self.pixel_format
+ }
+
+ pub fn take_keyframe_index(&mut self) -> Option<KeyframeIndex> {
+ self.keyframe_index.take()
+ }
+
pub fn keyframe_index(&self) -> Option<&KeyframeIndex> {
self.keyframe_index.as_ref()
}