Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add frame pooling to AsyncConverterPool and FrameConverter

Richie McIlroyd59e961b11e4
diff --git a/crates/frame-converter/examples/benchmark.rs b/crates/frame-converter/examples/benchmark.rs
index 2d457dfec..4449274b1 100644
--- a/crates/frame-converter/examples/benchmark.rs
+++ b/crates/frame-converter/examples/benchmark.rs
@@ -49,6 +49,7 @@ fn benchmark_pool(
input_capacity: 120,
output_capacity: 120,
drop_strategy: DropStrategy::DropOldest,
+ ..Default::default()
};
let pool = AsyncConverterPool::from_config(config.clone(), pool_config)
@@ -182,6 +183,7 @@ fn simulate_realtime_pipeline(
input_capacity: 60,
output_capacity: 30,
drop_strategy: DropStrategy::DropOldest,
+ ..Default::default()
};
let pool = AsyncConverterPool::from_config(config.clone(), pool_config)
diff --git a/crates/frame-converter/src/d3d11.rs b/crates/frame-converter/src/d3d11.rs
index fccc462ab..1b8cb34c2 100644
--- a/crates/frame-converter/src/d3d11.rs
+++ b/crates/frame-converter/src/d3d11.rs
@@ -659,6 +659,17 @@ pub fn is_format_supported(pixel: Pixel) -> bool {
impl FrameConverter for D3D11Converter {
fn convert(&self, input: frame::Video) -> Result<frame::Video, ConvertError> {
+ let mut output =
+ frame::Video::new(self.output_format, self.output_width, self.output_height);
+ self.convert_into(input, &mut output)?;
+ Ok(output)
+ }
+
+ fn convert_into(
+ &self,
+ input: frame::Video,
+ output: &mut frame::Video,
+ ) -> Result<(), ConvertError> {
let start = Instant::now();
let count = self.conversion_count.fetch_add(1, Ordering::Relaxed);
@@ -798,13 +809,7 @@ impl FrameConverter for D3D11Converter {
)
.map_err(|e| ConvertError::ConversionFailed(format!("Map output failed: {e:?}")))?;
- let mut output =
- frame::Video::new(self.output_format, self.output_width, self.output_height);
- copy_mapped_to_frame(
- mapped.pData as *const u8,
- mapped.RowPitch as usize,
- &mut output,
- );
+ copy_mapped_to_frame(mapped.pData as *const u8, mapped.RowPitch as usize, output);
resources.context.Unmap(&resources.staging_output, 0);
@@ -828,7 +833,7 @@ impl FrameConverter for D3D11Converter {
);
}
- Ok(output)
+ Ok(())
}
}
diff --git a/crates/frame-converter/src/frame_pool.rs b/crates/frame-converter/src/frame_pool.rs
new file mode 100644
index 000000000..51d880fbf
--- /dev/null
+++ b/crates/frame-converter/src/frame_pool.rs
@@ -0,0 +1,58 @@
+use ffmpeg::{format::Pixel, frame};
+use parking_lot::Mutex;
+use std::sync::Arc;
+
+pub struct VideoFramePool {
+ frames: Mutex<Vec<frame::Video>>,
+ format: Pixel,
+ width: u32,
+ height: u32,
+ capacity: usize,
+}
+
+impl VideoFramePool {
+ pub fn new(capacity: usize, format: Pixel, width: u32, height: u32) -> Arc<Self> {
+ let mut frames = Vec::with_capacity(capacity);
+ for _ in 0..capacity {
+ frames.push(frame::Video::new(format, width, height));
+ }
+
+ Arc::new(Self {
+ frames: Mutex::new(frames),
+ format,
+ width,
+ height,
+ capacity,
+ })
+ }
+
+ pub fn get(&self) -> frame::Video {
+ self.frames
+ .lock()
+ .pop()
+ .unwrap_or_else(|| frame::Video::new(self.format, self.width, self.height))
+ }
+
+ pub fn put(&self, frame: frame::Video) {
+ let mut frames = self.frames.lock();
+ if frames.len() < self.capacity {
+ frames.push(frame);
+ }
+ }
+
+ pub fn available(&self) -> usize {
+ self.frames.lock().len()
+ }
+
+ pub fn capacity(&self) -> usize {
+ self.capacity
+ }
+
+ pub fn format(&self) -> Pixel {
+ self.format
+ }
+
+ pub fn dimensions(&self) -> (u32, u32) {
+ (self.width, self.height)
+ }
+}
diff --git a/crates/frame-converter/src/lib.rs b/crates/frame-converter/src/lib.rs
index 21094440e..572a449c8 100644
--- a/crates/frame-converter/src/lib.rs
+++ b/crates/frame-converter/src/lib.rs
@@ -4,6 +4,9 @@ pub use swscale::*;
mod pool;
pub use pool::*;
+mod frame_pool;
+pub use frame_pool::*;
+
#[cfg(target_os = "macos")]
mod videotoolbox;
#[cfg(target_os = "macos")]
@@ -56,6 +59,16 @@ impl std::fmt::Display for ConverterBackend {
pub trait FrameConverter: Send + Sync + 'static {
fn convert(&self, input: ffmpeg::frame::Video) -> Result<ffmpeg::frame::Video, ConvertError>;
+ fn convert_into(
+ &self,
+ input: ffmpeg::frame::Video,
+ output: &mut ffmpeg::frame::Video,
+ ) -> Result<(), ConvertError> {
+ let result = self.convert(input)?;
+ *output = result;
+ Ok(())
+ }
+
fn name(&self) -> &'static str;
fn backend(&self) -> ConverterBackend;
diff --git a/crates/frame-converter/src/pool.rs b/crates/frame-converter/src/pool.rs
index c0a93f146..ee8ac5a49 100644
--- a/crates/frame-converter/src/pool.rs
+++ b/crates/frame-converter/src/pool.rs
@@ -1,4 +1,4 @@
-use crate::{ConversionConfig, ConvertError, FrameConverter, create_converter};
+use crate::{ConversionConfig, ConvertError, FrameConverter, VideoFramePool, create_converter};
use ffmpeg::frame;
use std::{
sync::{
@@ -28,6 +28,7 @@ pub struct ConverterPoolConfig {
pub input_capacity: usize,
pub output_capacity: usize,
pub drop_strategy: DropStrategy,
+ pub frame_pool_capacity: usize,
}
impl Default for ConverterPoolConfig {
@@ -37,6 +38,7 @@ impl Default for ConverterPoolConfig {
input_capacity: 8,
output_capacity: 8,
drop_strategy: DropStrategy::DropOldest,
+ frame_pool_capacity: 16,
}
}
}
@@ -60,6 +62,7 @@ pub struct AsyncConverterPool {
workers: Vec<JoinHandle<()>>,
shutdown: Arc<AtomicBool>,
stats: Arc<PoolStats>,
+ frame_pool: Option<Arc<VideoFramePool>>,
}
struct PoolStats {
@@ -81,8 +84,13 @@ impl Default for PoolStats {
impl AsyncConverterPool {
pub fn new(converter: Arc<dyn FrameConverter>, config: ConverterPoolConfig) -> Self {
let converter_name = converter.name().to_string();
- Self::new_with_factory(move |_| Ok(Arc::clone(&converter)), &converter_name, config)
- .expect("Factory using pre-created converter should not fail")
+ Self::new_with_factory(
+ move |_| Ok(Arc::clone(&converter)),
+ &converter_name,
+ config,
+ None,
+ )
+ .expect("Factory using pre-created converter should not fail")
}
pub fn from_config(
@@ -92,6 +100,17 @@ impl AsyncConverterPool {
let first_converter = create_converter(conversion_config.clone())?;
let converter_name = first_converter.name().to_string();
+ let frame_pool = if pool_config.frame_pool_capacity > 0 {
+ Some(VideoFramePool::new(
+ pool_config.frame_pool_capacity,
+ conversion_config.output_format,
+ conversion_config.output_width,
+ conversion_config.output_height,
+ ))
+ } else {
+ None
+ };
+
Self::new_with_factory(
move |worker_id| {
if worker_id == 0 {
@@ -102,6 +121,7 @@ impl AsyncConverterPool {
},
&converter_name,
pool_config,
+ frame_pool,
)
}
@@ -109,6 +129,7 @@ impl AsyncConverterPool {
factory: F,
converter_name: &str,
config: ConverterPoolConfig,
+ frame_pool: Option<Arc<VideoFramePool>>,
) -> Result<Self, ConvertError>
where
F: Fn(usize) -> Result<Arc<dyn FrameConverter>, ConvertError> + Send + Sync + 'static,
@@ -128,6 +149,7 @@ impl AsyncConverterPool {
let shutdown = Arc::clone(&shutdown);
let stats = Arc::clone(&stats);
let drop_strategy = config.drop_strategy;
+ let frame_pool = frame_pool.clone();
let handle = thread::Builder::new()
.name(format!("converter-worker-{worker_id}"))
@@ -139,7 +161,7 @@ impl AsyncConverterPool {
return;
}
};
- worker_loop(
+ worker_loop(WorkerContext {
worker_id,
converter,
input_rx,
@@ -147,7 +169,8 @@ impl AsyncConverterPool {
shutdown,
stats,
drop_strategy,
- );
+ frame_pool,
+ });
})
.expect("Failed to spawn converter worker thread");
@@ -155,8 +178,14 @@ impl AsyncConverterPool {
}
info!(
- "AsyncConverterPool started with {} workers using {} converter",
- config.worker_count, converter_name
+ "AsyncConverterPool started with {} workers using {} converter{}",
+ config.worker_count,
+ converter_name,
+ if frame_pool.is_some() {
+ " with frame pooling"
+ } else {
+ ""
+ }
);
Ok(Self {
@@ -165,6 +194,7 @@ impl AsyncConverterPool {
workers,
shutdown,
stats,
+ frame_pool: frame_pool.clone(),
})
}
@@ -224,6 +254,16 @@ impl AsyncConverterPool {
}
}
+ pub fn return_frame(&self, frame: frame::Video) {
+ if let Some(pool) = &self.frame_pool {
+ pool.put(frame);
+ }
+ }
+
+ pub fn frame_pool(&self) -> Option<&Arc<VideoFramePool>> {
+ self.frame_pool.as_ref()
+ }
+
pub fn drain_with_timeout(
&mut self,
mut frame_handler: impl FnMut(ConvertedFrame),
@@ -288,7 +328,7 @@ impl AsyncConverterPool {
}
}
-fn worker_loop(
+struct WorkerContext {
worker_id: usize,
converter: Arc<dyn FrameConverter>,
input_rx: flume::Receiver<InputFrame>,
@@ -296,36 +336,69 @@ fn worker_loop(
shutdown: Arc<AtomicBool>,
stats: Arc<PoolStats>,
drop_strategy: DropStrategy,
-) {
- debug!("Converter worker {} started", worker_id);
+ frame_pool: Option<Arc<VideoFramePool>>,
+}
+
+fn worker_loop(ctx: WorkerContext) {
+ debug!(
+ "Converter worker {} started{}",
+ ctx.worker_id,
+ if ctx.frame_pool.is_some() {
+ " with frame pooling"
+ } else {
+ ""
+ }
+ );
let mut local_converted = 0u64;
let mut local_errors = 0u64;
- while !shutdown.load(Ordering::Relaxed) {
- match input_rx.recv_timeout(Duration::from_millis(100)) {
+ while !ctx.shutdown.load(Ordering::Relaxed) {
+ match ctx.input_rx.recv_timeout(Duration::from_millis(100)) {
Ok(input) => {
let sequence = input.sequence;
let submit_time = input.submit_time;
let convert_start = Instant::now();
- match converter.convert(input.frame) {
+
+ let result = if let Some(ref pool) = ctx.frame_pool {
+ let mut output = pool.get();
+ match ctx.converter.convert_into(input.frame, &mut output) {
+ Ok(()) => Ok(output),
+ Err(e) => {
+ pool.put(output);
+ Err(e)
+ }
+ }
+ } else {
+ ctx.converter.convert(input.frame)
+ };
+
+ match result {
Ok(converted) => {
let conversion_duration = convert_start.elapsed();
local_converted += 1;
- stats.frames_converted.fetch_add(1, Ordering::Relaxed);
+ ctx.stats.frames_converted.fetch_add(1, Ordering::Relaxed);
- match output_tx.try_send(ConvertedFrame {
+ match ctx.output_tx.try_send(ConvertedFrame {
frame: converted,
sequence,
submit_time,
conversion_duration,
}) {
Ok(()) => {}
- Err(flume::TrySendError::Full(_frame)) => match drop_strategy {
- DropStrategy::DropOldest | DropStrategy::DropNewest => {
- stats.frames_dropped.fetch_add(1, Ordering::Relaxed);
+ Err(flume::TrySendError::Full(dropped_frame)) => {
+ match ctx.drop_strategy {
+ DropStrategy::DropOldest | DropStrategy::DropNewest => {
+ ctx.stats.frames_dropped.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ if let Some(ref pool) = ctx.frame_pool {
+ pool.put(dropped_frame.frame);
+ }
+ }
+ Err(flume::TrySendError::Disconnected(dropped_frame)) => {
+ if let Some(ref pool) = ctx.frame_pool {
+ pool.put(dropped_frame.frame);
}
- },
- Err(flume::TrySendError::Disconnected(_)) => {
break;
}
}
@@ -335,7 +408,7 @@ fn worker_loop(
if local_errors % 10 == 1 {
warn!(
"Worker {}: conversion error (#{} total): {}",
- worker_id, local_errors, e
+ ctx.worker_id, local_errors, e
);
}
}
@@ -352,7 +425,7 @@ fn worker_loop(
debug!(
"Converter worker {} finished: {} converted, {} errors",
- worker_id, local_converted, local_errors
+ ctx.worker_id, local_converted, local_errors
);
}
diff --git a/crates/frame-converter/src/swscale.rs b/crates/frame-converter/src/swscale.rs
index 1d5f72041..eafff2924 100644
--- a/crates/frame-converter/src/swscale.rs
+++ b/crates/frame-converter/src/swscale.rs
@@ -65,17 +65,26 @@ impl SwscaleConverter {
impl FrameConverter for SwscaleConverter {
fn convert(&self, input: frame::Video) -> Result<frame::Video, ConvertError> {
- let pts = input.pts();
let mut output =
frame::Video::new(self.output_format, self.output_width, self.output_height);
+ self.convert_into(input, &mut output)?;
+ Ok(output)
+ }
+
+ fn convert_into(
+ &self,
+ input: frame::Video,
+ output: &mut frame::Video,
+ ) -> Result<(), ConvertError> {
+ let pts = input.pts();
let context = self.get_or_create_context()?;
context
- .run(&input, &mut output)
+ .run(&input, output)
.map_err(|e| ConvertError::ConversionFailed(e.to_string()))?;
output.set_pts(pts);
- Ok(output)
+ Ok(())
}
fn name(&self) -> &'static str {
diff --git a/crates/recording/examples/camera-benchmark.rs b/crates/recording/examples/camera-benchmark.rs
index 8d99d5a4e..5b0f35d7e 100644
--- a/crates/recording/examples/camera-benchmark.rs
+++ b/crates/recording/examples/camera-benchmark.rs
@@ -141,6 +141,7 @@ async fn run_camera_encoding_benchmark(
input_capacity: 120,
output_capacity: 90,
drop_strategy: DropStrategy::DropOldest,
+ ..Default::default()
};
let pool = AsyncConverterPool::from_config(conversion_config, pool_config)
diff --git a/crates/recording/examples/encoding-benchmark.rs b/crates/recording/examples/encoding-benchmark.rs
index d9e62ad59..310b1c991 100644
--- a/crates/recording/examples/encoding-benchmark.rs
+++ b/crates/recording/examples/encoding-benchmark.rs
@@ -72,6 +72,7 @@ fn run_synthetic_benchmark(
input_capacity: 120,
output_capacity: 90,
drop_strategy: DropStrategy::DropOldest,
+ ..Default::default()
};
let pool = AsyncConverterPool::from_config(conversion_config, pool_config)
diff --git a/crates/recording/src/output_pipeline/async_camera.rs b/crates/recording/src/output_pipeline/async_camera.rs
index e9ae05242..fb94c7905 100644
--- a/crates/recording/src/output_pipeline/async_camera.rs
+++ b/crates/recording/src/output_pipeline/async_camera.rs
@@ -88,6 +88,7 @@ impl Muxer for AsyncCameraMp4Muxer {
input_capacity: config.input_capacity,
output_capacity: config.output_capacity,
drop_strategy: DropStrategy::DropOldest,
+ ..Default::default()
};
let pool = AsyncConverterPool::from_config(conversion_config, pool_config)