Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Separate video decoder (#388)

Brendan Allan0ec7c28b4ace
diff --git a/Cargo.lock b/Cargo.lock
index 7405d7cd0..4b9bfdbec 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1150,6 +1150,7 @@ dependencies = [
"bytemuck",
"cap-flags",
"cap-project",
+ "cap-video-decode",
"cidre",
"ffmpeg-hw-device",
"ffmpeg-next",
@@ -1188,8 +1189,12 @@ dependencies = [
name = "cap-video-decode"
version = "0.1.0"
dependencies = [
+ "cidre",
+ "ffmpeg-hw-device",
"ffmpeg-next",
"ffmpeg-sys-next",
+ "tokio",
+ "tracing",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 69c7a9ce1..7efca6cb8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -39,6 +39,7 @@ sentry = { version = "0.34.0", features = [
"backtrace",
"debug-images",
] }
+tracing = "0.1.41"
cidre = { git = "https://github.com/yury/cidre", rev = "ef04aaabe14ffbbce4a330973a74b6d797d073ff" }
diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.toml
index cecfb6420..f30416f03 100644
--- a/apps/cli/Cargo.toml
+++ b/apps/cli/Cargo.toml
@@ -21,7 +21,7 @@ editor = "0.1.1"
scap.workspace = true
uuid = { version = "1.11.1", features = ["v4"] }
ffmpeg = { workspace = true }
-tracing = "0.1.41"
+tracing.workspace = true
tracing-subscriber = "0.3.19"
nokhwa.workspace = true
flume.workspace = true
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 7f14f8f99..d9a087d3d 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -56,7 +56,7 @@ futures-intrusive = "0.5.0"
anyhow.workspace = true
futures = "0.3"
axum = { version = "0.7.5", features = ["ws"] }
-tracing = "0.1.40"
+tracing.workspace = true
tempfile = "3.9.0"
ffmpeg.workspace = true
chrono = { version = "0.4.31", features = ["serde"] }
diff --git a/crates/editor/Cargo.toml b/crates/editor/Cargo.toml
index 52e7668ed..483e8143e 100644
--- a/crates/editor/Cargo.toml
+++ b/crates/editor/Cargo.toml
@@ -18,5 +18,5 @@ specta.workspace = true
serde = { version = "1", features = ["derive"] }
sentry.workspace = true
futures = "0.3.31"
-tracing = "0.1.41"
+tracing.workspace = true
flume.workspace = true
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index 8e64ba2b8..3199e3e5e 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -27,7 +27,7 @@ serde = { version = "1", features = ["derive"] }
specta.workspace = true
tempfile = "3.12.0"
thiserror.workspace = true
-tracing = { version = "0.1", features = ["release_max_level_info"] }
+tracing = { workspace = true, features = ["release_max_level_info"] }
futures = "0.3.31"
axum = { version = "0.7.9", features = ["macros", "ws"] }
tokio.workspace = true
diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.toml
index 73ccc5f5f..14515671d 100644
--- a/crates/recording/Cargo.toml
+++ b/crates/recording/Cargo.toml
@@ -18,7 +18,7 @@ ffmpeg = { workspace = true }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
chrono = "0.4.38"
-tracing = "0.1.40"
+tracing.workspace = true
device_query = "2.1.0"
image = "0.25.2"
either = "1.13.0"
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 88d0ad437..ff5c1e729 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -8,6 +8,7 @@ anyhow.workspace = true
bytemuck = { version = "1.7", features = ["derive"] }
cap-flags = { path = "../flags" }
cap-project = { path = "../project" }
+cap-video-decode = { path = "../video-decode" }
ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }
tokio.workspace = true
ffmpeg.workspace = true
@@ -22,7 +23,7 @@ thiserror.workspace = true
wgpu.workspace = true
bezier_easing = "0.1.1"
reactive_graph = "0.1.5"
-tracing = "0.1.41"
+tracing.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
cidre.workspace = true
diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs
index b7fae9fb4..4665f14ea 100644
--- a/crates/rendering/src/decoder/avassetreader.rs
+++ b/crates/rendering/src/decoder/avassetreader.rs
@@ -1,5 +1,4 @@
use std::{
- cell::LazyCell,
collections::BTreeMap,
path::PathBuf,
sync::{mpsc, Arc},
@@ -8,9 +7,7 @@ use std::{
use cidre::{
arc::R,
av::{self, AssetReaderTrackOutput},
- cm,
cv::{self, pixel_buffer::LockFlags},
- ns,
};
use ffmpeg::{codec, format, frame, Rational};
use tokio::{runtime::Handle as TokioHandle, sync::oneshot};
@@ -27,7 +24,9 @@ impl CachedFrame {
fn process(&mut self) -> Arc<Vec<u8>> {
match self {
CachedFrame::Raw(image_buf) => {
- let format = pixel_format_to_pixel(image_buf.pixel_format());
+ let format = cap_video_decode::avassetreader::pixel_format_to_pixel(
+ image_buf.pixel_format(),
+ );
let data = if matches!(format, format::Pixel::RGBA) {
let _lock = unsafe {
@@ -174,91 +173,25 @@ impl CachedFrame {
}
pub struct AVAssetReaderDecoder {
- path: PathBuf,
- pixel_format: cv::PixelFormat,
- tokio_handle: TokioHandle,
- fps: u32,
- track_output: R<AssetReaderTrackOutput>,
- reader: R<av::AssetReader>,
+ inner: cap_video_decode::AVAssetReaderDecoder,
last_decoded_frame: Option<(u32, CachedFrame)>,
is_done: bool,
}
impl AVAssetReaderDecoder {
- fn new(path: PathBuf, tokio_handle: TokioHandle, fps: u32) -> Result<Self, String> {
- let pixel_format = {
- let input = ffmpeg::format::input(&path).unwrap();
-
- let input_stream = input
- .streams()
- .best(ffmpeg::media::Type::Video)
- .ok_or("Could not find a video stream")
- .unwrap();
-
- let decoder_codec =
- super::ffmpeg::find_decoder(&input, &input_stream, input_stream.parameters().id())
- .unwrap();
-
- let mut context = codec::context::Context::new_with_codec(decoder_codec);
- context.set_parameters(input_stream.parameters()).unwrap();
-
- let decoder = context.decoder().video().unwrap();
-
- pixel_to_pixel_format(decoder.format())
- };
-
- let (track_output, reader) =
- get_reader_track_output(&path, 0.0, &tokio_handle, pixel_format)?;
-
+ fn new(path: PathBuf, tokio_handle: TokioHandle) -> Result<Self, String> {
Ok(Self {
- path,
- pixel_format,
- tokio_handle,
- fps,
- track_output,
- reader,
+ inner: cap_video_decode::AVAssetReaderDecoder::new(path, tokio_handle)?,
last_decoded_frame: None,
is_done: false,
})
}
fn reset(&mut self, requested_time: f32) {
- self.reader.cancel_reading();
- (self.track_output, self.reader) = get_reader_track_output(
- &self.path,
- requested_time,
- &self.tokio_handle,
- self.pixel_format,
- )
- .unwrap();
+ self.inner.reset(requested_time);
self.last_decoded_frame = None;
}
- fn get_next_frame(&mut self) -> Option<(u32, CachedFrame)> {
- let frame = self
- .track_output
- .next_sample_buf()
- .unwrap()
- .and_then(|sample_buf| {
- let current_frame = pts_to_frame(
- sample_buf.pts().value,
- Rational::new(1, sample_buf.pts().scale),
- self.fps,
- );
-
- let image_buf = sample_buf.image_buf()?;
-
- // info!("decoded frame {}", current_frame);
-
- Some((current_frame, CachedFrame::Raw(image_buf.retained())))
- });
-
- self.last_decoded_frame = frame.clone();
- self.is_done = frame.is_none();
-
- frame
- }
-
fn last_decoded_frame(&mut self) -> Option<&mut (u32, CachedFrame)> {
self.last_decoded_frame.as_mut()
}
@@ -283,7 +216,7 @@ impl AVAssetReaderDecoder {
ready_tx: oneshot::Sender<Result<(), String>>,
tokio_handle: tokio::runtime::Handle,
) {
- let mut this = match AVAssetReaderDecoder::new(path, tokio_handle, fps) {
+ let mut this = match AVAssetReaderDecoder::new(path, tokio_handle) {
Ok(v) => {
ready_tx.send(Ok(())).ok();
v
@@ -303,6 +236,8 @@ impl AVAssetReaderDecoder {
// let mut last_decoded_frame = None::<(u32, CachedFrame)>;
let mut last_sent_frame = None::<(u32, DecodedFrame)>;
+ let mut frames = this.inner.frames();
+
while let Ok(r) = rx.recv() {
match r {
VideoDecoderMessage::GetFrame(requested_time, sender) => {
@@ -334,13 +269,33 @@ impl AVAssetReaderDecoder {
.unwrap_or(true)
{
this.reset(requested_time);
+ frames = this.inner.frames();
}
last_active_frame = Some(requested_frame);
let mut exit = false;
- while let Some((current_frame, mut cache_frame)) = this.get_next_frame() {
+ for frame in &mut frames {
+ let Ok(frame) = frame.map_err(|e| format!("read frame / {e}")) else {
+ continue;
+ };
+
+ let current_frame = pts_to_frame(
+ frame.pts().value,
+ Rational::new(1, frame.pts().scale),
+ fps,
+ );
+
+ let Some(frame) = frame.image_buf() else {
+ continue;
+ };
+
+ let mut cache_frame = CachedFrame::Raw(frame.retained());
+
+ this.last_decoded_frame = Some((current_frame, cache_frame.clone()));
+ this.is_done = false;
+
// Handles frame skips.
// We use the cache instead of last_sent_frame as newer non-matching frames could have been decoded.
if let Some(most_recent_prev_frame) =
@@ -422,6 +377,8 @@ impl AVAssetReaderDecoder {
}
}
+ this.is_done = true;
+
if let Some((sender, last_sent_frame)) =
sender.take().zip(last_sent_frame.as_ref())
{
@@ -439,71 +396,3 @@ impl AVAssetReaderDecoder {
println!("Decoder thread ended");
}
}
-
-fn pixel_to_pixel_format(pixel: format::Pixel) -> cv::PixelFormat {
- match pixel {
- format::Pixel::NV12 => cv::PixelFormat::_420V,
- // this is intentional, it works and is faster /shrug
- format::Pixel::YUV420P => cv::PixelFormat::_420V,
- format::Pixel::RGBA => cv::PixelFormat::_32_RGBA,
- _ => todo!(),
- }
-}
-
-fn pixel_format_to_pixel(format: cv::PixelFormat) -> format::Pixel {
- match format {
- cv::PixelFormat::_420V => format::Pixel::NV12,
- cv::PixelFormat::_32_RGBA => format::Pixel::RGBA,
- _ => todo!(),
- }
-}
-
-fn get_reader_track_output(
- path: &PathBuf,
- time: f32,
- handle: &TokioHandle,
- pixel_format: cv::PixelFormat,
-) -> Result<(R<av::AssetReaderTrackOutput>, R<av::AssetReader>), String> {
- let asset = av::UrlAsset::with_url(
- &ns::Url::with_fs_path_str(path.to_str().unwrap(), false),
- None,
- )
- .ok_or_else(|| format!("UrlAsset::with_url{{{path:?}}}"))?;
-
- let mut reader =
- av::AssetReader::with_asset(&asset).map_err(|e| format!("AssetReader::with_asset: {e}"))?;
-
- let time_range = cm::TimeRange {
- start: cm::Time::with_secs(time as f64, 100),
- duration: cm::Time::infinity(),
- };
-
- reader.set_time_range(time_range);
-
- let tracks = handle
- .block_on(asset.load_tracks_with_media_type(av::MediaType::video()))
- .map_err(|e| format!("asset.load_tracks_with_media_type: {e}"))?;
-
- let track = tracks.get(0).map_err(|e| e.to_string())?;
-
- let mut reader_track_output = av::AssetReaderTrackOutput::with_track(
- &track,
- Some(&ns::Dictionary::with_keys_values(
- &[cv::pixel_buffer::keys::pixel_format().as_ns()],
- &[pixel_format.to_cf_number().as_ns().as_id_ref()],
- )),
- )
- .map_err(|e| format!("asset.reader_track_output{{{pixel_format:?}}}): {e}"))?;
-
- reader_track_output.set_always_copies_sample_data(false);
-
- reader
- .add_output(&reader_track_output)
- .map_err(|e| format!("reader.add_output: {e}"))?;
-
- reader
- .start_reading()
- .map_err(|e| format!("reader.start_reading: {e}"))?;
-
- Ok((reader_track_output, reader))
-}
diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rs
index b24141a81..7e266c0f0 100644
--- a/crates/rendering/src/decoder/ffmpeg.rs
+++ b/crates/rendering/src/decoder/ffmpeg.rs
@@ -13,6 +13,7 @@ use ffmpeg_hw_device::{CodecContextExt, CodecExt, HwDevice};
use ffmpeg_sys_next::{avcodec_find_decoder, AVHWDeviceType};
use log::debug;
use tokio::sync::oneshot;
+use tracing::error;
use super::{pts_to_frame, DecodedFrame, VideoDecoderMessage, FRAME_CACHE_SIZE};
@@ -22,17 +23,14 @@ struct CachedFrame {
}
impl CachedFrame {
- fn process(&mut self, decoder: &codec::decoder::Video) -> Arc<Vec<u8>> {
+ fn process(&mut self, width: u32, height: u32) -> Arc<Vec<u8>> {
match &mut self.data {
CachedFrameData::Raw(frame) => {
let rgb_frame = if frame.format() != format::Pixel::RGBA {
// Reinitialize the scaler with the new input format
- let mut scaler = software::converter(
- (decoder.width(), decoder.height()),
- frame.format(),
- format::Pixel::RGBA,
- )
- .unwrap();
+ let mut scaler =
+ software::converter((width, height), frame.format(), format::Pixel::RGBA)
+ .unwrap();
let mut rgb_frame = frame::Video::empty();
scaler.run(&frame, &mut rgb_frame).unwrap();
@@ -81,82 +79,24 @@ impl FfmpegDecoder {
fps: u32,
rx: mpsc::Receiver<VideoDecoderMessage>,
ready_tx: oneshot::Sender<Result<(), String>>,
- ) {
- std::thread::spawn(move || {
- let mut input = ffmpeg::format::input(&path).unwrap();
-
- let input_stream = input
- .streams()
- .best(ffmpeg::media::Type::Video)
- .ok_or("Could not find a video stream")
- .unwrap();
-
- let decoder_codec =
- find_decoder(&input, &input_stream, input_stream.parameters().id()).unwrap();
-
- let mut context = codec::context::Context::new_with_codec(decoder_codec);
- context.set_parameters(input_stream.parameters()).unwrap();
-
- let input_stream_index = input_stream.index();
- let time_base = input_stream.time_base();
- let frame_rate = input_stream.rate();
-
- // Create a decoder for the video stream
- let mut decoder = context.decoder().video().unwrap();
-
- {
- use codec::threading::{Config, Type};
-
- let capabilities = decoder_codec.capabilities();
-
- if capabilities.intersects(Capabilities::FRAME_THREADS) {
- decoder.set_threading(Config::kind(Type::Frame));
- } else if capabilities.intersects(Capabilities::SLICE_THREADS) {
- decoder.set_threading(Config::kind(Type::Slice));
- } else {
- decoder.set_threading(Config::count(1));
- }
- }
-
- let width = decoder.width();
- let height = decoder.height();
-
- let exceeds_common_hw_limits = width > 4096 || height > 4096;
-
- let mut hw_device = if exceeds_common_hw_limits {
- debug!("Video dimensions {width}x{height} exceed common hardware decoder limits (4096x4096), not using hardware acceleration");
- None
+ ) -> Result<(), String> {
+ let mut this = cap_video_decode::FFmpegDecoder::new(
+ path,
+ Some(if cfg!(target_os = "macos") {
+ AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX
} else {
- let hw_device_types = if cfg!(target_os = "macos") {
- [AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX].as_slice()
- } else {
- [
- AVHWDeviceType::AV_HWDEVICE_TYPE_CUDA,
- AVHWDeviceType::AV_HWDEVICE_TYPE_D3D12VA,
- AVHWDeviceType::AV_HWDEVICE_TYPE_D3D11VA,
- AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
- AVHWDeviceType::AV_HWDEVICE_TYPE_VULKAN,
- AVHWDeviceType::AV_HWDEVICE_TYPE_DXVA2,
- ]
- .as_slice()
- };
+ AVHWDeviceType::AV_HWDEVICE_TYPE_D3D12VA
+ }),
+ )?;
- hw_device_types
- .iter()
- .find_map(|&typ| decoder.try_use_hw_device(typ).ok())
- };
- let hw_device = hw_device.as_ref();
-
- if hw_device.is_none() && !exceeds_common_hw_limits {
- debug!("No hardware acceleration available, falling back to software decoding");
- }
+ let time_base = this.decoder().time_base();
+ let start_time = this.start_time();
+ let width = this.decoder().width();
+ let height = this.decoder().height();
+ std::thread::spawn(move || {
let mut temp_frame = ffmpeg::frame::Video::empty();
- // let mut packets = input.packets().peekable();
-
- let black_frame = LazyCell::new(|| Arc::new(vec![0; (width * height * 4) as usize]));
-
let mut cache = BTreeMap::<u32, CachedFrame>::new();
// active frame is a frame that triggered decode.
// frames that are within render_more_margin of this frame won't trigger decode.
@@ -167,7 +107,7 @@ impl FfmpegDecoder {
let mut peekable_requests = PeekableReceiver { rx, peeked: None };
- let mut packets = input.packets().peekable();
+ let mut frames = this.frames().peekable();
let _ = ready_tx.send(Ok(()));
@@ -179,7 +119,7 @@ impl FfmpegDecoder {
// continue;
let mut sender = if let Some(cached) = cache.get_mut(&requested_frame) {
- let data = cached.process(&decoder);
+ let data = cached.process(width, height);
sender.send(data.clone()).ok();
last_sent_frame = Some((requested_frame, data));
@@ -201,132 +141,130 @@ impl FfmpegDecoder {
})
.unwrap_or(true)
{
- let timestamp_us =
- ((requested_frame as f32 / frame_rate.numerator() as f32)
- * 1_000_000.0) as i64;
- let position = timestamp_us.rescale((1, 1_000_000), rescale::TIME_BASE);
-
- debug!("seeking to {}", position);
- decoder.flush();
- input.seek(position, ..position).unwrap();
- last_decoded_frame = None;
+ debug!("seeking to {}", requested_frame);
+
+ this.reset(requested_time);
+ frames = this.frames().peekable();
- packets = input.packets().peekable();
+ last_decoded_frame = None;
}
last_active_frame = Some(requested_frame);
+ let mut exit = false;
+
loop {
if peekable_requests.peek().is_some() {
break;
}
- let Some((stream, packet)) = packets.next() else {
- // handles the case where the cache doesn't contain a frame so we fallback to the previously sent one
- if let Some(last_sent_frame) = &last_sent_frame {
- if last_sent_frame.0 < requested_frame {
- sender.take().map(|s| s.send(last_sent_frame.1.clone()));
- }
- }
- sender.take().map(|s| s.send(black_frame.clone()));
+ let Some(frame) = frames.next() else {
break;
};
- if stream.index() == input_stream_index {
- let start_offset = stream.start_time();
-
- let _ = decoder.send_packet(&packet);
-
- let mut exit = false;
-
- while decoder.receive_frame(&mut temp_frame).is_ok() {
- let current_frame = pts_to_frame(
- temp_frame.pts().unwrap() - start_offset,
- time_base,
- fps,
- );
-
- // Handles frame skips. requested_frame == last_decoded_frame should be handled by the frame cache.
- if let Some((last_decoded_frame, sender)) = last_decoded_frame
- .filter(|last_decoded_frame| {
- requested_frame > *last_decoded_frame
- && requested_frame < current_frame
- })
- .and_then(|l| Some((l, sender.take()?)))
- {
- let data = cache
- .get_mut(&last_decoded_frame)
- .map(|f| f.process(&decoder))
- .unwrap_or_else(|| black_frame.clone());
-
- last_sent_frame = Some((last_decoded_frame, data.clone()));
- sender.send(data).ok();
+ {
+ let frame = match frame {
+ Ok(f) => f,
+ Err(e) => {
+ error!("Error decoding frame: {}", e);
+ break;
}
+ };
+
+ let current_frame = pts_to_frame(
+ temp_frame.pts().unwrap() - start_time,
+ time_base,
+ fps,
+ );
+
+ // Handles frame skips. requested_frame == last_decoded_frame should be handled by the frame cache.
+ if let Some((last_decoded_frame, sender)) = last_decoded_frame
+ .filter(|last_decoded_frame| {
+ requested_frame > *last_decoded_frame
+ && requested_frame < current_frame
+ })
+ .and_then(|l| Some((l, sender.take()?)))
+ {
+ let Some(data) = cache
+ .get_mut(&last_decoded_frame)
+ .map(|f| f.process(width, height))
+ else {
+ break;
+ };
+ // .unwrap_or_else(|| black_frame.clone());
+
+ last_sent_frame = Some((last_decoded_frame, data.clone()));
+ sender.send(data).ok();
+ }
- last_decoded_frame = Some(current_frame);
+ last_decoded_frame = Some(current_frame);
- let exceeds_cache_bounds = current_frame > cache_max;
- let too_small_for_cache_bounds = current_frame < cache_min;
+ let exceeds_cache_bounds = current_frame > cache_max;
+ let too_small_for_cache_bounds = current_frame < cache_min;
- let frame = hw_device
- .and_then(|d| d.get_hwframe(&temp_frame))
- .unwrap_or(std::mem::replace(
- &mut temp_frame,
- frame::Video::empty(),
- ));
+ // let frame = hw_device
+ // .and_then(|d| d.get_hwframe(&temp_frame))
+ // .unwrap_or(std::mem::replace(
+ // &mut temp_frame,
+ // frame::Video::empty(),
+ // ));
- if !too_small_for_cache_bounds {
- let mut cache_frame = CachedFrame {
- data: CachedFrameData::Raw(frame),
- };
+ if !too_small_for_cache_bounds {
+ let mut cache_frame = CachedFrame {
+ data: CachedFrameData::Raw(frame),
+ };
- if current_frame == requested_frame {
- if let Some(sender) = sender.take() {
- let data = cache_frame.process(&decoder);
- last_sent_frame =
- Some((current_frame, data.clone()));
- sender.send(data).ok();
+ if current_frame == requested_frame {
+ if let Some(sender) = sender.take() {
+ let data = cache_frame.process(width, height);
+ last_sent_frame = Some((current_frame, data.clone()));
+ sender.send(data).ok();
- break;
- }
+ break;
}
+ }
- if cache.len() >= FRAME_CACHE_SIZE {
- if let Some(last_active_frame) = &last_active_frame {
- let frame = if requested_frame > *last_active_frame
- {
- *cache.keys().next().unwrap()
- } else if requested_frame < *last_active_frame {
- *cache.keys().next_back().unwrap()
- } else {
- let min = *cache.keys().min().unwrap();
- let max = *cache.keys().max().unwrap();
+ if cache.len() >= FRAME_CACHE_SIZE {
+ if let Some(last_active_frame) = &last_active_frame {
+ let frame = if requested_frame > *last_active_frame {
+ *cache.keys().next().unwrap()
+ } else if requested_frame < *last_active_frame {
+ *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
- }
- };
+ if current_frame > max {
+ min
+ } else {
+ max
+ }
+ };
- cache.remove(&frame);
- } else {
- cache.clear()
- }
+ cache.remove(&frame);
+ } else {
+ cache.clear()
}
-
- cache.insert(current_frame, cache_frame);
}
- exit = exit || exceeds_cache_bounds;
+ cache.insert(current_frame, cache_frame);
}
- if exit {
- break;
- }
+ exit = exit || exceeds_cache_bounds;
+ }
+ }
+
+ // handles the case where the cache doesn't contain a frame so we fallback to the previously sent one
+ if let Some(last_sent_frame) = &last_sent_frame {
+ if last_sent_frame.0 < requested_frame {
+ sender.take().map(|s| s.send(last_sent_frame.1.clone()));
}
}
+ if exit {
+ continue;
+ }
+
if let Some((sender, last_sent_frame)) =
sender.take().zip(last_sent_frame.clone())
{
@@ -336,6 +274,8 @@ impl FfmpegDecoder {
}
}
});
+
+ Ok(())
}
}
diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.toml
index 95b40c165..7ba70195e 100644
--- a/crates/utils/Cargo.toml
+++ b/crates/utils/Cargo.toml
@@ -9,13 +9,13 @@ nix = { version = "0.29.0", features = ["fs"] }
[target.'cfg(windows)'.dependencies]
tokio.workspace = true
windows = { version = "0.58.0", features = [
- "Win32_Foundation",
- "Win32_System",
- "Win32_System_WindowsProgramming",
- "Win32_Security",
- "Win32_Storage_FileSystem",
- "Win32_System_Pipes",
- "Win32_System_Diagnostics_Debug",
+ "Win32_Foundation",
+ "Win32_System",
+ "Win32_System_WindowsProgramming",
+ "Win32_Security",
+ "Win32_Storage_FileSystem",
+ "Win32_System_Pipes",
+ "Win32_System_Diagnostics_Debug",
] }
windows-sys = "0.52.0"
@@ -26,4 +26,4 @@ uuid = "1.11.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
flume = "0.11.0"
-tracing = "0.1.41"
+tracing.workspace = true
diff --git a/crates/video-decode/Cargo.toml b/crates/video-decode/Cargo.toml
index c63d6dd86..d9a86459e 100644
--- a/crates/video-decode/Cargo.toml
+++ b/crates/video-decode/Cargo.toml
@@ -6,3 +6,9 @@ edition = "2021"
[dependencies]
ffmpeg.workspace = true
ffmpeg-sys-next.workspace = true
+ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }
+tokio.workspace = true
+tracing = "0.1.41"
+
+[target.'cfg(target_os = "macos")'.dependencies]
+cidre = { workspace = true }
diff --git a/crates/video-decode/src/avassetreader.rs b/crates/video-decode/src/avassetreader.rs
new file mode 100644
index 000000000..1d918848a
--- /dev/null
+++ b/crates/video-decode/src/avassetreader.rs
@@ -0,0 +1,150 @@
+use std::path::PathBuf;
+
+use cidre::{
+ arc::{self, R},
+ av::{self},
+ cm,
+ cv::{self},
+ ns,
+};
+use ffmpeg::{codec as avcodec, format as avformat};
+use tokio::runtime::Handle as TokioHandle;
+
+pub struct AVAssetReaderDecoder {
+ path: PathBuf,
+ pixel_format: cv::PixelFormat,
+ tokio_handle: TokioHandle,
+ track_output: R<av::AssetReaderTrackOutput>,
+ reader: R<av::AssetReader>,
+}
+
+impl AVAssetReaderDecoder {
+ pub fn new(path: PathBuf, tokio_handle: TokioHandle) -> Result<Self, String> {
+ let pixel_format = {
+ let input = ffmpeg::format::input(&path).unwrap();
+
+ let input_stream = input
+ .streams()
+ .best(ffmpeg::media::Type::Video)
+ .ok_or("Could not find a video stream")
+ .unwrap();
+
+ let decoder = avcodec::Context::from_parameters(input_stream.parameters())
+ .map_err(|e| format!("decoder context / {e}"))?
+ .decoder()
+ .video()
+ .map_err(|e| format!("video decoder / {e}"))?;
+
+ pixel_to_pixel_format(decoder.format())
+ };
+
+ let (track_output, reader) =
+ Self::get_reader_track_output(&path, 0.0, &tokio_handle, pixel_format)?;
+
+ Ok(Self {
+ path,
+ pixel_format,
+ tokio_handle,
+ track_output,
+ reader,
+ })
+ }
+
+ pub fn reset(&mut self, requested_time: f32) -> Result<(), String> {
+ self.reader.cancel_reading();
+ (self.track_output, self.reader) = Self::get_reader_track_output(
+ &self.path,
+ requested_time,
+ &self.tokio_handle,
+ self.pixel_format,
+ )?;
+
+ Ok(())
+ }
+
+ fn get_reader_track_output(
+ path: &PathBuf,
+ time: f32,
+ handle: &TokioHandle,
+ pixel_format: cv::PixelFormat,
+ ) -> Result<(R<av::AssetReaderTrackOutput>, R<av::AssetReader>), String> {
+ let asset = av::UrlAsset::with_url(
+ &ns::Url::with_fs_path_str(path.to_str().unwrap(), false),
+ None,
+ )
+ .ok_or_else(|| format!("UrlAsset::with_url{{{path:?}}}"))?;
+
+ let mut reader = av::AssetReader::with_asset(&asset)
+ .map_err(|e| format!("AssetReader::with_asset: {e}"))?;
+
+ let time_range = cm::TimeRange {
+ start: cm::Time::with_secs(time as f64, 100),
+ duration: cm::Time::infinity(),
+ };
+
+ reader.set_time_range(time_range);
+
+ let tracks = handle
+ .block_on(asset.load_tracks_with_media_type(av::MediaType::video()))
+ .map_err(|e| format!("asset.load_tracks_with_media_type: {e}"))?;
+
+ let track = tracks.get(0).map_err(|e| e.to_string())?;
+
+ let mut reader_track_output = av::AssetReaderTrackOutput::with_track(
+ &track,
+ Some(&ns::Dictionary::with_keys_values(
+ &[cv::pixel_buffer::keys::pixel_format().as_ns()],
+ &[pixel_format.to_cf_number().as_ns().as_id_ref()],
+ )),
+ )
+ .map_err(|e| format!("asset.reader_track_output{{{pixel_format:?}}}): {e}"))?;
+
+ reader_track_output.set_always_copies_sample_data(false);
+
+ reader
+ .add_output(&reader_track_output)
+ .map_err(|e| format!("reader.add_output: {e}"))?;
+
+ reader
+ .start_reading()
+ .map_err(|e| format!("reader.start_reading: {e}"))?;
+
+ Ok((reader_track_output, reader))
+ }
+
+ pub fn frames(&mut self) -> FramesIter {
+ FramesIter {
+ track_output: &mut self.track_output,
+ }
+ }
+}
+
+pub struct FramesIter<'a> {
+ track_output: &'a mut av::AssetReaderTrackOutput,
+}
+
+impl<'a> Iterator for FramesIter<'a> {
+ type Item = ns::ExResult<'static, arc::R<cm::SampleBuf>>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.track_output.next_sample_buf().transpose()
+ }
+}
+
+pub fn pixel_to_pixel_format(pixel: avformat::Pixel) -> cv::PixelFormat {
+ match pixel {
+ avformat::Pixel::NV12 => cv::PixelFormat::_420V,
+ // this is intentional, it works and is faster /shrug
+ avformat::Pixel::YUV420P => cv::PixelFormat::_420V,
+ avformat::Pixel::RGBA => cv::PixelFormat::_32_RGBA,
+ _ => todo!(),
+ }
+}
+
+pub fn pixel_format_to_pixel(format: cv::PixelFormat) -> avformat::Pixel {
+ match format {
+ cv::PixelFormat::_420V => avformat::Pixel::NV12,
+ cv::PixelFormat::_32_RGBA => avformat::Pixel::RGBA,
+ _ => todo!(),
+ }
+}
diff --git a/crates/video-decode/src/ffmpeg.rs b/crates/video-decode/src/ffmpeg.rs
new file mode 100644
index 000000000..7add56b14
--- /dev/null
+++ b/crates/video-decode/src/ffmpeg.rs
@@ -0,0 +1,150 @@
+use ffmpeg::{
+ codec as avcodec,
+ format::{self as avformat, context::input::PacketIter},
+ frame as avframe, util as avutil,
+};
+use ffmpeg_hw_device::{CodecContextExt, HwDevice};
+use ffmpeg_sys_next::{AVHWDeviceType, EAGAIN};
+use std::path::PathBuf;
+use tracing::debug;
+
+pub struct FFmpegDecoder {
+ input: avformat::context::Input,
+ decoder: avcodec::decoder::Video,
+ stream_index: usize,
+ hw_device: Option<HwDevice>,
+ start_time: i64,
+}
+
+impl FFmpegDecoder {
+ pub fn new(
+ path: impl Into<PathBuf>,
+ hw_device_type: Option<AVHWDeviceType>,
+ ) -> Result<Self, String> {
+ fn inner(
+ path: PathBuf,
+ hw_device_type: Option<AVHWDeviceType>,
+ ) -> Result<FFmpegDecoder, String> {
+ let input = ffmpeg::format::input(&path).map_err(|e| format!("open file / {e}"))?;
+
+ let input_stream = input
+ .streams()
+ .best(avutil::media::Type::Video)
+ .ok_or_else(|| "no video stream".to_string())?;
+
+ let start_time = input_stream.start_time();
+
+ let stream_index = input_stream.index();
+
+ let mut decoder = avcodec::Context::from_parameters(input_stream.parameters())
+ .map_err(|e| format!("decoder context / {e}"))?
+ .decoder()
+ .video()
+ .map_err(|e| format!("video decoder / {e}"))?;
+
+ let width = decoder.width();
+ let height = decoder.height();
+
+ let exceeds_common_hw_limits = width > 4096 || height > 4096;
+
+ let hw_device = hw_device_type
+ .and_then(|_| {
+ if exceeds_common_hw_limits{
+ debug!("Video dimensions {width}x{height} exceed common hardware decoder limits (4096x4096), not using hardware acceleration");
+ None
+ } else {
+ None
+ }
+ })
+ .and_then(|hw_device_type| decoder.try_use_hw_device(hw_device_type).ok());
+
+ Ok(FFmpegDecoder {
+ input,
+ decoder,
+ stream_index,
+ hw_device,
+ start_time,
+ })
+ }
+
+ inner(path.into(), hw_device_type)
+ }
+
+ pub fn reset(&mut self, requested_time: f32) -> Result<(), ffmpeg::Error> {
+ use ffmpeg::rescale;
+ let timestamp_us = (requested_time * 1_000_000.0) as i64;
+ let position = rescale::Rescale::rescale(&timestamp_us, (1, 1_000_000), rescale::TIME_BASE);
+
+ self.decoder.flush();
+ self.input.seek(position, ..position)
+ }
+
+ pub fn frames(&mut self) -> FramesIter {
+ FramesIter {
+ packets: self.input.packets(),
+ decoder: &mut self.decoder,
+ stream_index: self.stream_index,
+ hw_device: self.hw_device.as_mut(),
+ }
+ }
+
+ pub fn decoder(&self) -> &avcodec::decoder::Video {
+ &self.decoder
+ }
+
+ pub fn start_time(&self) -> i64 {
+ self.start_time
+ }
+}
+
+unsafe impl Send for FFmpegDecoder {}
+
+pub struct FramesIter<'a> {
+ decoder: &'a mut avcodec::decoder::Video,
+ packets: PacketIter<'a>,
+ stream_index: usize,
+ hw_device: Option<&'a mut HwDevice>,
+}
+
+impl FramesIter<'_> {
+ pub fn decoder(&self) -> &avcodec::decoder::Video {
+ self.decoder
+ }
+}
+
+impl<'a> Iterator for FramesIter<'a> {
+ type Item = Result<avframe::Video, avutil::error::Error>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let mut frame = avframe::Video::empty();
+
+ loop {
+ match self.decoder.receive_frame(&mut frame) {
+ Ok(()) => {
+ return match &self.hw_device {
+ Some(hw_device) => Some(Ok(hw_device.get_hwframe(&frame).unwrap_or(frame))),
+ None => Some(Ok(frame)),
+ }
+ }
+ Err(ffmpeg::Error::Eof) => return None,
+ Err(ffmpeg::Error::Other { errno }) if errno == EAGAIN => {}
+ Err(e) => return Some(Err(e)),
+ }
+
+ let Some((stream, packet)) = self.packets.next() else {
+ return None;
+ };
+
+ if stream.index() != self.stream_index {
+ continue;
+ };
+
+ match self.decoder.send_packet(&packet) {
+ Ok(_) => {}
+ Err(ffmpeg::Error::Eof) => return None,
+ Err(ffmpeg::Error::Other { errno }) if errno == EAGAIN => {}
+ Err(e) => return Some(Err(e)),
+ }
+ }
+ }
+}
diff --git a/crates/video-decode/src/lib.rs b/crates/video-decode/src/lib.rs
new file mode 100644
index 000000000..65ea1d5a1
--- /dev/null
+++ b/crates/video-decode/src/lib.rs
@@ -0,0 +1,7 @@
+#[cfg(target_os = "macos")]
+pub mod avassetreader;
+pub mod ffmpeg;
+
+#[cfg(target_os = "macos")]
+pub use avassetreader::AVAssetReaderDecoder;
+pub use ffmpeg::FFmpegDecoder;
diff --git a/crates/video-decode/src/main.rs b/crates/video-decode/src/main.rs
index 288596573..384452f2a 100644
--- a/crates/video-decode/src/main.rs
+++ b/crates/video-decode/src/main.rs
@@ -1,65 +1,22 @@
-fn main() {
- let path = "/Users/brendonovich/Library/Application Support/so.cap.desktop.dev/recordings/51ecf128-913e-456c-8959-c73c6c4a60b3.cap/content/segments/segment-0/display.mp4";
-
- let mut input = ffmpeg::format::input(&path).unwrap();
-
- let input_stream = input
- .streams()
- .best(ffmpeg::media::Type::Video)
- .ok_or("Could not find a video stream")
- .unwrap();
-
- let decoder_codec =
- find_decoder(&input, &input_stream, input_stream.parameters().id()).unwrap();
-
- let mut context = ffmpeg::codec::context::Context::new_with_codec(decoder_codec);
- context.set_parameters(input_stream.parameters()).unwrap();
-
- let input_stream_index = input_stream.index();
- let time_base = input_stream.time_base();
- let frame_rate = input_stream.rate();
-
- // Create a decoder for the video stream
- let mut decoder = context.decoder().video().unwrap();
+use std::time::Instant;
- let mut temp_frame = ffmpeg::frame::Video::empty();
+use ffmpeg_sys_next::AVHWDeviceType;
- for (stream, packet) in input.packets() {
- if stream.index() == input_stream_index {
- decoder.send_packet(&packet).unwrap();
+use cap_video_decode::FFmpegDecoder;
- while decoder.receive_frame(&mut temp_frame).is_ok() {
- dbg!(temp_frame.pts());
- }
- }
- }
-}
-
-pub fn find_decoder(
- s: &ffmpeg::format::context::Input,
- st: &ffmpeg::format::stream::Stream,
- codec_id: ffmpeg::codec::Id,
-) -> Option<ffmpeg::Codec> {
- unsafe {
- use ffmpeg::media::Type;
- let codec = match st.parameters().medium() {
- Type::Video => Some((*s.as_ptr()).video_codec),
- Type::Audio => Some((*s.as_ptr()).audio_codec),
- Type::Subtitle => Some((*s.as_ptr()).subtitle_codec),
- _ => None,
- };
-
- if let Some(codec) = codec {
- if !codec.is_null() {
- return Some(ffmpeg::Codec::wrap(codec));
- }
- }
-
- let found = ffmpeg::sys::avcodec_find_decoder(codec_id.into());
-
- if found.is_null() {
- return None;
- }
- Some(ffmpeg::Codec::wrap(found))
- }
+fn main() {
+ let path = "/Users/brendonovich/Library/Application Support/so.cap.desktop.dev/recordings/789cca54-58ff-4c02-a772-56a01af580bf.cap/content/segments/segment-0/display.mp4";
+ let mut decoder =
+ FFmpegDecoder::new(path, Some(AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX)).unwrap();
+
+ let start = Instant::now();
+
+ let frame_count = decoder.frames().count();
+ let duration = start.elapsed();
+ println!(
+ "decoded {} frames in {:?} - {} frames/s",
+ frame_count,
+ duration,
+ frame_count as f64 / duration.as_secs_f64()
+ );
}