Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
move ffmepg hw device to dedicated crate
Brendan Allanf9f8e26c9d33
diff --git a/Cargo.lock b/Cargo.lockindex 6c4bbb04e..4944a8c2a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -795,6 +795,7 @@ dependencies = ["core-foundation 0.10.0","core-graphics 0.24.0","cpal",+ "ffmpeg-hw-device","ffmpeg-next","ffmpeg-sys-next","flume 0.11.0",@@ -804,7 +805,7 @@ dependencies = ["objc","objc-foundation","objc2-foundation",- "scap 0.0.5 (git+https://github.com/filleduchaos/scap?rev=8eb00ce1b9bcf)",+ "scap","serde","specta","tempfile",@@ -831,6 +832,7 @@ dependencies = ["cap-ffmpeg","cap-flags","cap-project",+ "ffmpeg-hw-device","ffmpeg-next","ffmpeg-sys-next","futures",@@ -1654,7 +1656,7 @@ dependencies = ["rand 0.8.5","reqwest","rodio",- "scap 0.0.5 (git+https://github.com/CapSoftware/scap?rev=691bd88798d3)",+ "scap","serde","serde_json","specta",@@ -2057,6 +2059,14 @@ dependencies = ["simd-adler32",]+[[package]]+name = "ffmpeg-hw-device"+version = "0.1.0"+dependencies = [+ "ffmpeg-next",+ "ffmpeg-sys-next",+]+[[package]]name = "ffmpeg-next"version = "7.1.0"@@ -5626,25 +5636,6 @@ dependencies = ["winapi-util",]-[[package]]-name = "scap"-version = "0.0.5"-source = "git+https://github.com/CapSoftware/scap?rev=691bd88798d3#691bd88798d39478e09afb04d460e113097bb855"-dependencies = [- "cocoa 0.25.0",- "core-graphics-helmer-fork",- "dbus",- "objc",- "pipewire",- "rand 0.8.5",- "screencapturekit",- "screencapturekit-sys",- "sysinfo",- "tao-core-video-sys",- "windows 0.52.0",- "windows-capture",-]-[[package]]name = "scap"version = "0.0.5"diff --git a/Cargo.toml b/Cargo.tomlindex 7ca7bf3b1..1d53158e6 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -17,3 +17,4 @@ tokio = { version = "1.39.3", features = [] }tauri = { version = "2.0.0" }specta = { version = "=2.0.0-rc.20" }+scap = { git = "https://github.com/filleduchaos/scap", rev = "8eb00ce1b9bcf" }diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 685ce6383..f77f8768c 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -45,7 +45,7 @@ swift-rs = "1.0.6"nix = { version = "0.29.0", features = ["fs"] }tokio.workspace = trueuuid = { version = "1.10.0", features = ["v4"] }-scap = { git = "https://github.com/CapSoftware/scap", rev = "691bd88798d3" }+scap.workspace = trueffmpeg-sidecar = { git = "https://github.com/CapSoftware/ffmpeg-sidecar", branch = "main" }wgpu = "22.1.0"bytemuck = { version = "1.7", features = ["derive"] }diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex b1a661ce3..e7ea097b8 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -49,7 +49,7 @@ use std::ffi::{CStr, OsStr};use std::fs::File;use std::io::BufWriter;use std::io::{BufReader, Write};-use std::time::{SystemTime, UNIX_EPOCH};+use std::time::{Instant, SystemTime, UNIX_EPOCH};use std::{collections::HashMap, marker::PhantomData, path::PathBuf, process::Command, sync::Arc,time::Duration,@@ -424,8 +424,9 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<.as_secs_f64(),);+ let now = Instant::now();let recording = current_recording.stop().await;- println!("Recording stopped");+ println!("stopped recording in {:?}", now.elapsed());if let Some(window) = CapWindowId::InProgressRecording.get(&app) {window.hide().unwrap();@@ -439,15 +440,19 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<std::fs::create_dir_all(&screenshots_dir).ok();let display_screenshot = screenshots_dir.join("display.jpg");+ let now = Instant::now();create_screenshot(recording.display_output_path.clone(),display_screenshot.clone(),None,).await?;+ println!("created screenshot in {:?}", now.elapsed());- let thumbnail = screenshots_dir.join("thumbnail.png");- create_thumbnail(display_screenshot, thumbnail, (100, 100)).await?;+ // let thumbnail = screenshots_dir.join("thumbnail.png");+ // let now = Instant::now();+ // create_thumbnail(display_screenshot, thumbnail, (100, 100)).await?;+ // println!("created thumbnail in {:?}", now.elapsed());let recording_dir = recording.recording_dir.clone();@@ -1141,17 +1146,17 @@ async fn render_to_file_impl(eprintln!("Failed to save screenshot: {:?}", e);});- // Create and save thumbnail- let thumbnail = image::imageops::resize(- &rgb_img,- 100,- 100,- image::imageops::FilterType::Lanczos3,- );- let thumbnail_path = screenshots_dir.join("thumbnail.png");- thumbnail.save(&thumbnail_path).unwrap_or_else(|e| {- eprintln!("Failed to save thumbnail: {:?}", e);- });+ // // Create and save thumbnail+ // let thumbnail = image::imageops::resize(+ // &rgb_img,+ // 100,+ // 100,+ // image::imageops::FilterType::Lanczos3,+ // );+ // let thumbnail_path = screenshots_dir.join("thumbnail.png");+ // thumbnail.save(&thumbnail_path).unwrap_or_else(|e| {+ // eprintln!("Failed to save thumbnail: {:?}", e);+ // });} else {eprintln!("No frames were processed, cannot save screenshot or thumbnail");}diff --git a/crates/ffmpeg-hw-device/Cargo.toml b/crates/ffmpeg-hw-device/Cargo.tomlnew file mode 100644index 000000000..0a5e2aa00--- /dev/null+++ b/crates/ffmpeg-hw-device/Cargo.toml@@ -0,0 +1,8 @@+[package]+name = "ffmpeg-hw-device"+version = "0.1.0"+edition = "2021"++[dependencies]+ffmpeg.workspace = true+ffmpeg-sys-next.workspace = truediff --git a/crates/ffmpeg-hw-device/src/lib.rs b/crates/ffmpeg-hw-device/src/lib.rsnew file mode 100644index 000000000..9d47db197--- /dev/null+++ b/crates/ffmpeg-hw-device/src/lib.rs@@ -0,0 +1,125 @@+use std::{+ cell::Cell,+ ptr::{null, null_mut},+};++use ffmpeg::{+ codec,+ format::Pixel,+ frame::{self, Video},+};+use ffmpeg_sys_next::{+ av_buffer_ref, av_buffer_unref, av_hwdevice_ctx_create, av_hwframe_transfer_data,+ avcodec_get_hw_config, AVBufferRef, AVCodecContext, AVHWDeviceType, AVPixelFormat,+ AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX,+};++thread_local! {+ static HW_PIX_FMT: Cell<AVPixelFormat> = const { Cell::new(AVPixelFormat::AV_PIX_FMT_NONE) };+}++unsafe extern "C" fn get_format(+ _: *mut AVCodecContext,+ pix_fmts: *const AVPixelFormat,+) -> AVPixelFormat {+ let mut fmt = pix_fmts;++ loop {+ if *fmt == AVPixelFormat::AV_PIX_FMT_NONE {+ break;+ }++ if *fmt == HW_PIX_FMT.get() {+ return *fmt;+ }++ fmt = fmt.offset(1);+ }++ AVPixelFormat::AV_PIX_FMT_NONE+}++pub struct HwDevice {+ pub device_type: AVHWDeviceType,+ pub pix_fmt: Pixel,+ ctx: *mut AVBufferRef,+}++impl HwDevice {+ pub fn get_hwframe(&self, src: &Video) -> Option<Video> {+ unsafe {+ if src.format() == HW_PIX_FMT.get().into() {+ let mut sw_frame = frame::Video::empty();++ if av_hwframe_transfer_data(sw_frame.as_mut_ptr(), src.as_ptr(), 0) >= 0 {+ return Some(sw_frame);+ };+ }+ }++ None+ }+}++impl Drop for HwDevice {+ fn drop(&mut self) {+ unsafe {+ av_buffer_unref(&mut self.ctx);+ }+ }+}++pub trait CodecContextExt {+ fn try_use_hw_device(+ &mut self,+ device_type: AVHWDeviceType,+ pix_fmt: Pixel,+ ) -> Result<HwDevice, &'static str>;+}++impl CodecContextExt for codec::context::Context {+ fn try_use_hw_device(+ &mut self,+ device_type: AVHWDeviceType,+ pix_fmt: Pixel,+ ) -> Result<HwDevice, &'static str> {+ let codec = self.codec().ok_or("no codec")?;++ unsafe {+ let mut i = 0;+ loop {+ let config = avcodec_get_hw_config(codec.as_ptr(), i);+ if config.is_null() {+ return Err("no hw config");+ }++ if (*config).methods & (AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX as i32) == 1+ && (*config).device_type == AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX+ {+ HW_PIX_FMT.set((*config).pix_fmt);+ break;+ }++ i += 1;+ }++ let context = self.as_mut_ptr();++ (*context).get_format = Some(get_format);++ let mut hw_device_ctx = null_mut();++ if av_hwdevice_ctx_create(&mut hw_device_ctx, device_type, null(), null_mut(), 0) < 0 {+ return Err("failed to create hw device context");+ }++ (*context).hw_device_ctx = av_buffer_ref(hw_device_ctx);++ Ok(HwDevice {+ device_type,+ ctx: hw_device_ctx,+ pix_fmt,+ })+ }+ }+}diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.tomlindex 6048f8523..c84b5963a 100644--- a/crates/media/Cargo.toml+++ b/crates/media/Cargo.toml@@ -11,13 +11,14 @@ cap-project = { path = "../project" }cpal = "0.15.3"ffmpeg.workspace = trueffmpeg-sys-next.workspace = true+ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }flume = "0.11.0"indexmap = "2.5.0"nokhwa = { git = "https://github.com/capsoftware/nokhwa", rev = "6ce1e8270d57", features = ["input-native","serialize",] }-scap = { git = "https://github.com/filleduchaos/scap", rev = "8eb00ce1b9bcf" }+scap.workspace = trueserde = { version = "1", features = ["derive"] }specta.workspace = truetempfile = "3.12.0"diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rsindex c54b48ae1..22a058bbf 100644--- a/crates/media/src/encoders/h264.rs+++ b/crates/media/src/encoders/h264.rs@@ -1,3 +1,8 @@+use crate::{+ data::{FFPacket, FFVideo, VideoInfo},+ pipeline::task::PipelineSinkTask,+ MediaError,+};use ffmpeg::{codec::{codec::Codec, context, encoder},format::{self},@@ -5,12 +10,6 @@ use ffmpeg::{Dictionary,};-use crate::{- data::{FFPacket, FFVideo, VideoInfo},- pipeline::task::PipelineSinkTask,- MediaError,-};-use super::Output;pub struct H264Encoder {@@ -27,6 +26,7 @@ impl H264Encoder {let (codec, options) = get_codec_and_options(&config)?;let mut encoder_ctx = context::Context::new_with_codec(codec);+// TODO: Configure this per systemencoder_ctx.set_threading(Config::count(4));let mut encoder = encoder_ctx.encoder().video()?;diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.tomlindex 05d740bf2..67b17da9e 100644--- a/crates/rendering/Cargo.toml+++ b/crates/rendering/Cargo.toml@@ -15,11 +15,12 @@ image = "0.25.2"cap-ffmpeg = { path = "../ffmpeg" }cap-project = { path = "../project" }cap-flags = { path = "../flags" }+ffmpeg-hw-device = { path = "../ffmpeg-hw-device" }tokio.workspace = trueserde_json = "1.0.127"ffmpeg.workspace = true-lru = "0.12.4"ffmpeg-sys-next.workspace = true+lru = "0.12.4"futures = "0.3.30"[target.'cfg(unix)'.dependencies]diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rsindex fd05de351..9eefed428 100644--- a/crates/rendering/src/decoder.rs+++ b/crates/rendering/src/decoder.rs@@ -1,22 +1,16 @@use std::{- cell::Cell,collections::BTreeMap,path::PathBuf,- ptr::{null, null_mut},sync::{mpsc, Arc},};use ffmpeg::{codec,- format::{self, context::input::PacketIter, Pixel},- frame::{self, Video},- rescale, Codec, Packet, Rational, Rescale, Stream,-};-use ffmpeg_sys_next::{- av_buffer_ref, av_buffer_unref, av_hwdevice_ctx_create, av_hwframe_transfer_data,- avcodec_find_decoder, avcodec_get_hw_config, AVBufferRef, AVCodecContext, AVHWDeviceType,- AVPixelFormat, AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX,+ format::{self, context::input::PacketIter},+ frame, rescale, Codec, Packet, Rational, Rescale, Stream,};+use ffmpeg_hw_device::{CodecContextExt, HwDevice};+use ffmpeg_sys_next::{avcodec_find_decoder, AVHWDeviceType};pub type DecodedFrame = Arc<Vec<u8>>;@@ -336,31 +330,6 @@ impl<T> PeekableReceiver<T> {}}-thread_local! {- static HW_PIX_FMT: Cell<AVPixelFormat> = const { Cell::new(AVPixelFormat::AV_PIX_FMT_NONE) };-}--unsafe extern "C" fn get_format(- _: *mut AVCodecContext,- pix_fmts: *const AVPixelFormat,-) -> AVPixelFormat {- let mut fmt = pix_fmts;-- loop {- if *fmt == AVPixelFormat::AV_PIX_FMT_NONE {- break;- }-- if *fmt == HW_PIX_FMT.get() {- return *fmt;- }-- fmt = fmt.offset(1);- }-- AVPixelFormat::AV_PIX_FMT_NONE-}-fn ff_find_decoder(s: &format::context::Input,st: &format::stream::Stream,@@ -389,88 +358,3 @@ fn ff_find_decoder(Some(Codec::wrap(found))}}--struct HwDevice {- pub device_type: AVHWDeviceType,- pub pix_fmt: Pixel,- ctx: *mut AVBufferRef,-}--impl HwDevice {- pub fn get_hwframe(&self, src: &Video) -> Option<Video> {- unsafe {- if src.format() == HW_PIX_FMT.get().into() {- let mut sw_frame = frame::Video::empty();-- if av_hwframe_transfer_data(sw_frame.as_mut_ptr(), src.as_ptr(), 0) >= 0 {- return Some(sw_frame);- };- }- }-- None- }-}--impl Drop for HwDevice {- fn drop(&mut self) {- unsafe {- av_buffer_unref(&mut self.ctx);- }- }-}--trait CodecContextExt {- fn try_use_hw_device(- &mut self,- device_type: AVHWDeviceType,- pix_fmt: Pixel,- ) -> Result<HwDevice, &'static str>;-}--impl CodecContextExt for codec::context::Context {- fn try_use_hw_device(- &mut self,- device_type: AVHWDeviceType,- pix_fmt: Pixel,- ) -> Result<HwDevice, &'static str> {- let codec = self.codec().ok_or("no codec")?;-- unsafe {- let mut i = 0;- loop {- let config = avcodec_get_hw_config(codec.as_ptr(), i);- if config.is_null() {- return Err("no hw config");- }-- if (*config).methods & (AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX as i32) == 1- && (*config).device_type == AVHWDeviceType::AV_HWDEVICE_TYPE_VIDEOTOOLBOX- {- HW_PIX_FMT.set((*config).pix_fmt);- break;- }-- i += 1;- }-- let context = self.as_mut_ptr();-- (*context).get_format = Some(get_format);-- let mut hw_device_ctx = null_mut();-- if av_hwdevice_ctx_create(&mut hw_device_ctx, device_type, null(), null_mut(), 0) < 0 {- return Err("failed to create hw device context");- }-- (*context).hw_device_ctx = av_buffer_ref(hw_device_ctx);-- Ok(HwDevice {- device_type,- ctx: hw_device_ctx,- pix_fmt,- })- }- }-}