Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

add decoder implementation using AVAssetReader (#249)

Brendan Allan0668cc142cad
diff --git a/Cargo.lock b/Cargo.lock
index 922034978..38fbf87e3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1064,6 +1064,7 @@ dependencies = [
"cap-flags",
"cap-project",
"cap-recording",
+ "cidre",
"ffmpeg-hw-device",
"ffmpeg-next",
"ffmpeg-sys-next",
@@ -1071,7 +1072,6 @@ dependencies = [
"futures-intrusive",
"image 0.25.5",
"log",
- "nix 0.29.0",
"pretty_assertions",
"serde",
"specta",
@@ -1226,17 +1226,18 @@ dependencies = [
[[package]]
name = "cidre"
-version = "0.4.0"
-source = "git+https://github.com/yury/cidre?rev=1e008bec49a0f97aeaaea6130a0ba20fe00aa03b#1e008bec49a0f97aeaaea6130a0ba20fe00aa03b"
+version = "0.5.0"
+source = "git+https://github.com/yury/cidre?rev=3479c18b9ac81dbb15d0acb3a75edd6b42d044b1#3479c18b9ac81dbb15d0acb3a75edd6b42d044b1"
dependencies = [
"cidre-macros",
"parking_lot",
+ "tokio",
]
[[package]]
name = "cidre-macros"
version = "0.1.0"
-source = "git+https://github.com/yury/cidre?rev=1e008bec49a0f97aeaaea6130a0ba20fe00aa03b#1e008bec49a0f97aeaaea6130a0ba20fe00aa03b"
+source = "git+https://github.com/yury/cidre?rev=3479c18b9ac81dbb15d0acb3a75edd6b42d044b1#3479c18b9ac81dbb15d0acb3a75edd6b42d044b1"
[[package]]
name = "clang-sys"
diff --git a/Cargo.toml b/Cargo.toml
index 6237f8a34..f38650b01 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -18,8 +18,8 @@ tokio = { version = "1.39.3", features = [
"rt-multi-thread",
"time",
] }
-tauri = { version = "2.2.3", features = [ "specta" ] }
-specta = { version = "=2.0.0-rc.20", features = [ "derive" ] }
+tauri = { version = "2.2.3", features = ["specta"] }
+specta = { version = "=2.0.0-rc.20", features = ["derive"] }
scap = { git = "https://github.com/CapSoftware/scap", rev = "58d4410bf52f" }
nokhwa = { git = "https://github.com/CapSoftware/nokhwa", rev = "d37141b1883d", features = [
@@ -36,6 +36,8 @@ sentry = { version = "0.34.0", features = [
"debug-images",
] }
+cidre = { git = "https://github.com/yury/cidre", rev = "3479c18b9ac81dbb15d0acb3a75edd6b42d044b1" }
+
windows = "0.58.0"
windows-sys = "0.59.0"
windows-capture = "=1.3.6"
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index fee5ae9f2..e1059653a 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -34,7 +34,7 @@ export type CurrentDialog =
export type DialogState = { open: false } | ({ open: boolean } & CurrentDialog);
-export const FPS = 30;
+export const FPS = 60;
export const OUTPUT_SIZE = {
x: 1920,
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index f707da416..f28c35ebc 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -32,14 +32,7 @@ axum = { version = "0.7.9", features = ["macros", "ws"] }
tokio.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
-cocoa = "0.26.0"
-core-graphics = "0.24.0"
-core-foundation = "0.10.0"
-objc = "0.2.7"
-objc-foundation = "0.1.1"
-objc2-foundation = { version = "0.2.2", features = ["NSValue"] }
-nokhwa-bindings-macos.workspace = true
-cidre = { git = "https://github.com/yury/cidre", rev = "1e008bec49a0f97aeaaea6130a0ba20fe00aa03b", default-features = false, features = [
+cidre = { workspace = true, default-features = false, features = [
"private",
"blocks",
@@ -52,6 +45,13 @@ cidre = { git = "https://github.com/yury/cidre", rev = "1e008bec49a0f97aeaaea613
"macos_13_0",
] }
+cocoa = "0.26.0"
+core-graphics = "0.24.0"
+core-foundation = "0.10.0"
+objc = "0.2.7"
+objc-foundation = "0.1.1"
+objc2-foundation = { version = "0.2.2", features = ["NSValue"] }
+nokhwa-bindings-macos.workspace = true
screencapturekit = "0.2.8"
[target.'cfg(target_os = "windows")'.dependencies]
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index f73679d47..3bf26294e 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -23,8 +23,8 @@ thiserror.workspace = true
wgpu.workspace = true
bezier_easing = "0.1.1"
-[target.'cfg(unix)'.dependencies]
-nix = { version = "0.29.0", features = ["fs"] }
+[target.'cfg(target_os = "macos")'.dependencies]
+cidre.workspace = true
[dev-dependencies]
pretty_assertions = "1.4.1"
diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rs
index 9821a8f0e..2b3600ab2 100644
--- a/crates/rendering/src/decoder.rs
+++ b/crates/rendering/src/decoder.rs
@@ -5,20 +5,17 @@ use std::{
sync::{mpsc, Arc},
};
+use cidre::cv::pixel_buffer::LockFlags;
use ffmpeg::{
codec::{self, Capabilities},
- format::{self},
- frame::{self},
- rescale,
- software::{self},
- Codec, Rational, Rescale,
+ format, frame, rescale, software, Codec, Rational, Rescale,
};
use ffmpeg_hw_device::{CodecContextExt, HwDevice};
use ffmpeg_sys_next::{avcodec_find_decoder, AVHWDeviceType};
pub type DecodedFrame = Arc<Vec<u8>>;
-enum VideoDecoderMessage {
+pub enum VideoDecoderMessage {
GetFrame(f32, tokio::sync::oneshot::Sender<DecodedFrame>),
}
@@ -87,10 +84,113 @@ enum CachedFrameData {
pub struct AsyncVideoDecoder;
-impl AsyncVideoDecoder {
- pub fn spawn(path: PathBuf, fps: u32) -> AsyncVideoDecoderHandle {
+#[derive(Clone)]
+pub struct AsyncVideoDecoderHandle {
+ sender: mpsc::Sender<VideoDecoderMessage>,
+}
+
+impl AsyncVideoDecoderHandle {
+ pub async fn get_frame(&self, time: f32) -> Option<DecodedFrame> {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ self.sender
+ .send(VideoDecoderMessage::GetFrame(time, tx))
+ .unwrap();
+ rx.await.ok()
+ }
+}
+
+pub enum GetFrameError {
+ Failed,
+}
+
+struct PeekableReceiver<T> {
+ rx: mpsc::Receiver<T>,
+ peeked: Option<T>,
+}
+
+impl<T> PeekableReceiver<T> {
+ fn peek(&mut self) -> Option<&T> {
+ if self.peeked.is_some() {
+ self.peeked.as_ref()
+ } else {
+ match self.rx.try_recv() {
+ Ok(value) => {
+ self.peeked = Some(value);
+ self.peeked.as_ref()
+ }
+ Err(_) => None,
+ }
+ }
+ }
+
+ fn recv(&mut self) -> Result<T, mpsc::RecvError> {
+ if let Some(value) = self.peeked.take() {
+ Ok(value)
+ } else {
+ self.rx.recv()
+ }
+ }
+}
+
+fn ff_find_decoder(
+ s: &format::context::Input,
+ st: &format::stream::Stream,
+ codec_id: codec::Id,
+) -> Option<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(Codec::wrap(codec));
+ }
+ }
+
+ let found = avcodec_find_decoder(codec_id.into());
+
+ if found.is_null() {
+ return None;
+ }
+ Some(Codec::wrap(found))
+ }
+}
+
+pub enum Decoder {
+ Ffmpeg(FfmpegDecoder),
+ #[cfg(target_os = "macos")]
+ AVAssetReader(AVAssetReaderDecoder),
+}
+
+impl Decoder {
+ pub fn spawn(name: &'static str, path: PathBuf, fps: u32) -> AsyncVideoDecoderHandle {
let (tx, rx) = mpsc::channel();
+ let handle = AsyncVideoDecoderHandle { sender: tx };
+
+ #[cfg(target_os = "macos")]
+ {
+ AVAssetReaderDecoder::spawn(name, path, fps, rx);
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ {
+ FfmpegDecoder::spawn(name, path, fps, rx);
+ }
+
+ handle
+ }
+}
+
+struct FfmpegDecoder;
+
+impl FfmpegDecoder {
+ fn spawn(name: &'static str, path: PathBuf, fps: u32, rx: mpsc::Receiver<VideoDecoderMessage>) {
std::thread::spawn(move || {
let mut input = ffmpeg::format::input(&path).unwrap();
@@ -152,6 +252,12 @@ impl AsyncVideoDecoder {
let mut temp_frame = ffmpeg::frame::Video::empty();
+ // let mut packets = input.packets().peekable();
+
+ let width = decoder.width();
+ let height = decoder.height();
+ 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.
@@ -164,10 +270,6 @@ impl AsyncVideoDecoder {
let mut packets = input.packets().peekable();
- let width = decoder.width();
- let height = decoder.height();
- let black_frame = LazyCell::new(|| Arc::new(vec![0; (width * height * 4) as usize]));
-
while let Ok(r) = peekable_requests.recv() {
match r {
VideoDecoderMessage::GetFrame(requested_time, sender) => {
@@ -193,8 +295,8 @@ impl AsyncVideoDecoder {
.as_ref()
.map(|last| {
requested_frame < last.0 ||
- // seek forward for big jumps. this threshold is arbitrary but should be derived from i-frames in future
- requested_frame - last.0 > FRAME_CACHE_SIZE as u32
+ // seek forward for big jumps. this threshold is arbitrary but should be derived from i-frames in future
+ requested_frame - last.0 > FRAME_CACHE_SIZE as u32
})
.unwrap_or(true)
{
@@ -206,7 +308,6 @@ impl AsyncVideoDecoder {
decoder.flush();
input.seek(position, ..position).unwrap();
last_decoded_frame = None;
- last_sent_frame = None;
packets = input.packets().peekable();
}
@@ -334,84 +435,405 @@ impl AsyncVideoDecoder {
}
}
});
-
- AsyncVideoDecoderHandle { sender: tx }
}
}
-#[derive(Clone)]
-pub struct AsyncVideoDecoderHandle {
- sender: mpsc::Sender<VideoDecoderMessage>,
-}
+use tokio::runtime::Handle as TokioHandle;
-impl AsyncVideoDecoderHandle {
- pub async fn get_frame(&self, time: f32) -> Option<DecodedFrame> {
- let (tx, rx) = tokio::sync::oneshot::channel();
- self.sender
- .send(VideoDecoderMessage::GetFrame(time, tx))
- .unwrap();
- rx.await.ok()
+#[cfg(target_os = "macos")]
+mod macos {
+ use super::*;
+ use cidre::{arc::R, av, cm, cv, ns};
+ use format::context::input::PacketIter;
+
+ #[derive(Clone)]
+ enum CachedFrame {
+ Raw(R<cv::ImageBuf>),
+ Processed(Arc<Vec<u8>>),
}
-}
-pub enum GetFrameError {
- Failed,
-}
+ 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());
-struct PeekableReceiver<T> {
- rx: mpsc::Receiver<T>,
- peeked: Option<T>,
-}
+ let data = if matches!(format, format::Pixel::RGBA) {
+ let _lock = image_buf.base_address_lock(LockFlags::READ_ONLY).unwrap();
-impl<T> PeekableReceiver<T> {
- fn peek(&mut self) -> Option<&T> {
- if self.peeked.is_some() {
- self.peeked.as_ref()
- } else {
- match self.rx.try_recv() {
- Ok(value) => {
- self.peeked = Some(value);
- self.peeked.as_ref()
+ let bytes_per_row = image_buf.plane_bytes_per_row(0);
+ let width = image_buf.width() as usize;
+ let height = image_buf.height();
+
+ let slice = unsafe {
+ std::slice::from_raw_parts::<'static, _>(
+ image_buf.plane_base_address(0),
+ bytes_per_row * height,
+ )
+ };
+
+ let bytes = Vec::with_capacity(width * height * 4);
+
+ let row_length = width * 4;
+
+ for i in 0..height {
+ bytes.as_mut_slice()[i * row_length..((i + 1) * row_length)]
+ .copy_from_slice(
+ &slice[i * bytes_per_row..(i * bytes_per_row + row_length)],
+ )
+ }
+
+ bytes
+ } else {
+ let mut ffmpeg_frame = ffmpeg::frame::Video::new(
+ format,
+ image_buf.width() as u32,
+ image_buf.height() as u32,
+ );
+
+ match ffmpeg_frame.format() {
+ format::Pixel::NV12 => {
+ let _lock =
+ image_buf.base_address_lock(LockFlags::READ_ONLY).unwrap();
+
+ for plane_i in 0..image_buf.plane_count() {
+ let bytes_per_row = image_buf.plane_bytes_per_row(plane_i);
+ let height = image_buf.plane_height(plane_i);
+
+ let ffmpeg_stride = ffmpeg_frame.stride(plane_i);
+ let row_length = bytes_per_row.min(ffmpeg_stride);
+
+ let slice = unsafe {
+ std::slice::from_raw_parts::<'static, _>(
+ image_buf.plane_base_address(plane_i),
+ bytes_per_row * height,
+ )
+ };
+
+ for i in 0..height {
+ ffmpeg_frame.data_mut(plane_i)
+ [i * ffmpeg_stride..(i * ffmpeg_stride + row_length)]
+ .copy_from_slice(
+ &slice[i * bytes_per_row
+ ..(i * bytes_per_row + row_length)],
+ )
+ }
+ }
+ }
+ format::Pixel::YUV420P => {
+ let _lock =
+ image_buf.base_address_lock(LockFlags::READ_ONLY).unwrap();
+
+ for plane_i in 0..image_buf.plane_count() {
+ let bytes_per_row = image_buf.plane_bytes_per_row(plane_i);
+ let height = image_buf.plane_height(plane_i);
+
+ let ffmpeg_stride = ffmpeg_frame.stride(plane_i);
+ let row_length = bytes_per_row.min(ffmpeg_stride);
+
+ let slice = unsafe {
+ std::slice::from_raw_parts::<'static, _>(
+ image_buf.plane_base_address(plane_i),
+ bytes_per_row * height,
+ )
+ };
+
+ for i in 0..height {
+ ffmpeg_frame.data_mut(plane_i)
+ [i * ffmpeg_stride..(i * ffmpeg_stride + row_length)]
+ .copy_from_slice(
+ &slice[i * bytes_per_row
+ ..(i * bytes_per_row + row_length)],
+ )
+ }
+ }
+ }
+ format => todo!("implement {:?}", format),
+ }
+
+ let mut converter = ffmpeg::software::converter(
+ (ffmpeg_frame.width(), ffmpeg_frame.height()),
+ ffmpeg_frame.format(),
+ format::Pixel::RGBA,
+ )
+ .unwrap();
+
+ let mut rgb_frame = frame::Video::empty();
+ converter.run(&ffmpeg_frame, &mut rgb_frame).unwrap();
+
+ rgb_frame.data(0).to_vec()
+ };
+
+ let data = Arc::new(data);
+
+ *self = Self::Processed(data.clone());
+
+ data
}
- Err(_) => None,
+ CachedFrame::Processed(data) => data.clone(),
}
}
}
- fn recv(&mut self) -> Result<T, mpsc::RecvError> {
- if let Some(value) = self.peeked.take() {
- Ok(value)
- } else {
- self.rx.recv()
- }
- }
-}
+ pub struct AVAssetReaderDecoder;
+
+ impl AVAssetReaderDecoder {
+ pub fn spawn(
+ name: &'static str,
+ path: PathBuf,
+ fps: u32,
+ rx: mpsc::Receiver<VideoDecoderMessage>,
+ ) {
+ let handle = tokio::runtime::Handle::current();
+
+ std::thread::spawn(move || {
+ let (pixel_format, width, height) = {
+ 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 =
+ ff_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()),
+ decoder.width(),
+ decoder.height(),
+ )
+ };
-fn ff_find_decoder(
- s: &format::context::Input,
- st: &format::stream::Stream,
- codec_id: codec::Id,
-) -> Option<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,
- };
+ let asset = av::UrlAsset::with_url(
+ &ns::Url::with_fs_path_str(path.to_str().unwrap(), false),
+ None,
+ )
+ .unwrap();
- if let Some(codec) = codec {
- if !codec.is_null() {
- return Some(Codec::wrap(codec));
- }
+ fn get_reader_track_output(
+ asset: &av::UrlAsset,
+ time: f32,
+ handle: &TokioHandle,
+ pixel_format: cv::PixelFormat,
+ ) -> R<av::AssetReaderTrackOutput> {
+ let mut reader = av::AssetReader::with_asset(&asset).unwrap();
+
+ let time_range = cm::TimeRange {
+ start: cm::Time::with_secs(time as f64, 100),
+ duration: asset.duration(),
+ };
+
+ reader.set_time_range(time_range);
+
+ let tracks = handle
+ .block_on(asset.load_tracks_with_media_type(av::MediaType::video()))
+ .unwrap();
+
+ let track = tracks.get(0).unwrap();
+
+ 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()],
+ )),
+ )
+ .unwrap();
+
+ reader_track_output.set_always_copies_sample_data(false);
+
+ reader.add_output(&reader_track_output).unwrap();
+
+ reader.start_reading().ok();
+
+ reader_track_output
+ }
+
+ let mut track_output = get_reader_track_output(&asset, 0.0, &handle, pixel_format);
+
+ let black_frame =
+ LazyCell::new(|| Arc::new(vec![0; (width * height * 4) as usize]));
+
+ let mut cache = BTreeMap::<u32, CachedFrame>::new();
+
+ let mut last_active_frame = None::<u32>;
+
+ let mut last_decoded_frame = None::<u32>;
+ let mut last_sent_frame = None::<(u32, DecodedFrame)>;
+
+ while let Ok(r) = rx.recv() {
+ match r {
+ VideoDecoderMessage::GetFrame(requested_time, sender) => {
+ let requested_frame = (requested_time * fps as f32).floor() as u32;
+
+ let mut sender = if let Some(cached) = cache.get_mut(&requested_frame) {
+ let data = cached.process();
+
+ sender.send(data.clone()).ok();
+ last_sent_frame = Some((requested_frame, data));
+ continue;
+ } else {
+ Some(sender)
+ };
+
+ let cache_min =
+ requested_frame.saturating_sub(FRAME_CACHE_SIZE as u32 / 2);
+ let cache_max = requested_frame + FRAME_CACHE_SIZE as u32 / 2;
+
+ if requested_frame <= 0
+ || last_sent_frame
+ .as_ref()
+ .map(|last| {
+ requested_frame < last.0 ||
+ // seek forward for big jumps. this threshold is arbitrary but should be derived from i-frames in future
+ requested_frame - last.0 > FRAME_CACHE_SIZE as u32
+ })
+ .unwrap_or(true)
+ {
+ track_output = get_reader_track_output(
+ &asset,
+ requested_time,
+ &handle,
+ pixel_format,
+ );
+ last_decoded_frame = None;
+ }
+
+ last_active_frame = Some(requested_frame);
+
+ let mut exit = false;
+
+ while let Some((current_frame, mut cache_frame)) = 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),
+ fps,
+ );
+
+ let image_buf = sample_buf.image_buf()?;
+
+ Some((current_frame, CachedFrame::Raw(image_buf.retained())))
+ })
+ {
+ // 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())
+ .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);
+
+ 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 current_frame == requested_frame {
+ if let Some(sender) = sender.take() {
+ let data = cache_frame.process();
+ last_sent_frame = Some((current_frame, data.clone()));
+ sender.send(data).ok();
+
+ 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 current_frame > max {
+ min
+ } else {
+ max
+ }
+ };
+
+ cache.remove(&frame);
+ } else {
+ cache.clear()
+ }
+ }
+
+ cache.insert(current_frame, cache_frame.clone());
+ }
+
+ if current_frame > requested_frame && sender.is_some() {
+ if let Some((sender, last_sent_frame)) = last_sent_frame
+ .as_ref()
+ .and_then(|l| Some((sender.take()?, l)))
+ {
+ sender.send(last_sent_frame.1.clone()).ok();
+ } else if let Some(sender) = sender.take() {
+ sender.send(cache_frame.process()).ok();
+ }
+ }
+
+ exit = exit || exceeds_cache_bounds;
+
+ if exit {
+ break;
+ }
+ }
+
+ if let Some((sender, last_sent_frame)) =
+ sender.take().zip(last_sent_frame.as_ref())
+ {
+ sender.send(last_sent_frame.1.clone()).ok();
+ }
+ }
+ }
+ }
+
+ println!("Decoder thread ended");
+ });
}
+ }
- let found = avcodec_find_decoder(codec_id.into());
+ 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!(),
+ }
+ }
- if found.is_null() {
- return None;
+ 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!(),
}
- Some(Codec::wrap(found))
}
}
+
+#[cfg(target_os = "macos")]
+use macos::*;
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index fcb7d7ca6..2bbab936c 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -9,7 +9,7 @@ use cap_project::{
SLOW_VELOCITY_THRESHOLD, XY,
};
use core::f64;
-use decoder::{AsyncVideoDecoder, AsyncVideoDecoderHandle, GetFrameError};
+use decoder::{AsyncVideoDecoder, AsyncVideoDecoderHandle, Decoder, GetFrameError};
use futures::future::OptionFuture;
use futures_intrusive::channel::shared::oneshot_channel;
use serde::{Deserialize, Serialize};
@@ -100,7 +100,8 @@ pub struct SegmentVideoPaths<'a> {
impl RecordingSegmentDecoders {
pub fn new(meta: &RecordingMeta, segment: SegmentVideoPaths) -> Self {
- let screen = AsyncVideoDecoder::spawn(
+ let screen = Decoder::spawn(
+ "screen",
meta.project_path.join(segment.display),
match &meta.content {
Content::SingleSegment { segment } => segment.display.fps,
@@ -108,7 +109,8 @@ impl RecordingSegmentDecoders {
},
);
let camera = segment.camera.map(|camera| {
- AsyncVideoDecoder::spawn(
+ Decoder::spawn(
+ "camera",
meta.project_path.join(camera),
match &meta.content {
Content::SingleSegment { segment } => segment.camera.as_ref().unwrap().fps,