Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

cleanup + fix debug window

Brendan Allan93d527aa3e34
diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rs
index 11df25bf2..39252bca5 100644
--- a/apps/desktop/src-tauri/src/windows.rs
+++ b/apps/desktop/src-tauri/src/windows.rs
@@ -37,6 +37,7 @@ pub enum CapWindowId {
InProgressRecording,
Upgrade,
ModeSelect,
+ Debug,
}
impl FromStr for CapWindowId {
@@ -53,6 +54,7 @@ impl FromStr for CapWindowId {
"recordings-overlay" => Self::RecordingsOverlay,
"upgrade" => Self::Upgrade,
"mode-select" => Self::ModeSelect,
+ "debug" => Self::Debug,
s if s.starts_with("editor-") => Self::Editor {
id: s
.replace("editor-", "")
@@ -86,6 +88,7 @@ impl std::fmt::Display for CapWindowId {
Self::Upgrade => write!(f, "upgrade"),
Self::ModeSelect => write!(f, "mode-select"),
Self::Editor { id } => write!(f, "editor-{id}"),
+ Self::Debug => write!(f, "debug"),
}
}
}
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index 8b6fa8207..2343d1c28 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -94,36 +94,6 @@ impl ScreenCaptureTarget {
}
}
-// impl PartialEq<Target> for ScreenCaptureTarget {
-// fn eq(&self, other: &Target) -> bool {
-// match (self, other) {
-// (Self::Window(capture_window), Target::Window(window)) => {
-// window.id == capture_window.id
-// }
-// (ScreenCaptureTarget::Area(capture_area), Target::Display(display)) => {
-// display.id == capture_area.screen.id
-// }
-// (ScreenCaptureTarget::Screen(capture_screen), Target::Display(display)) => {
-// display.id == capture_screen.id
-// }
-// (&ScreenCaptureTarget::Window(_), &scap::Target::Display(_))
-// | (&ScreenCaptureTarget::Screen(_), &scap::Target::Window(_))
-// | (&ScreenCaptureTarget::Area(_), &scap::Target::Window(_)) => todo!(),
-// }
-// }
-// }
-
-// impl ScreenCaptureTarget {
-// pub fn recording_fps(&self) -> u32 {
-// match self {
-// ScreenCaptureTarget::Window(window) => window.
-// ScreenCaptureTarget::Screen(screen) => screen.refresh_rate,
-// ScreenCaptureTarget::Area(area) => area.screen.refresh_rate,
-// }
-// .min(MAX_FPS)
-// }
-// }
-
pub struct ScreenCaptureSource<TCaptureFormat: ScreenCaptureFormat> {
target: ScreenCaptureTarget,
output_resolution: Option<ScapResolution>,
@@ -205,8 +175,6 @@ impl<TCaptureFormat: ScreenCaptureFormat> Clone for ScreenCaptureSource<TCapture
}
}
-const MAX_FPS: u32 = 60;
-
struct OptionsConfig {
scap_target: scap::Target,
bounds: Bounds,
@@ -214,9 +182,9 @@ struct OptionsConfig {
display_size: (f32, f32),
}
-struct CropRatio {
- position: (f32, f32),
- size: (f32, f32),
+pub struct CropRatio {
+ pub position: (f32, f32),
+ pub size: (f32, f32),
}
impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
@@ -287,20 +255,23 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {
&self.bounds
}
- pub fn crop_ratio(&self) -> ((f32, f32), (f32, f32)) {
+ pub fn crop_ratio(&self) -> CropRatio {
if let Some(crop_area) = &self.options.crop_area {
- (
- (
+ CropRatio {
+ position: (
crop_area.origin.x as f32 / self.display_size.0,
crop_area.origin.y as f32 / self.display_size.1,
),
- (
+ size: (
crop_area.size.width as f32 / self.display_size.0,
crop_area.size.height as f32 / self.display_size.1,
),
- )
+ }
} else {
- ((0.0, 0.0), (1.0, 1.0))
+ CropRatio {
+ position: (0.0, 0.0),
+ size: (1.0, 1.0),
+ }
}
}
@@ -705,6 +676,13 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {
}
}
SCStreamOutputType::Audio => {
+ let res = || {
+ Ok::<_, ()>(cap_fail::fail_err!("screen_capture audio skip", ()))
+ };
+ if let Err(_) = res() {
+ return ControlFlow::Continue(());
+ }
+
let Some(audio_tx) = &audio_tx else {
return ControlFlow::Continue(());
};
diff --git a/crates/media/src/sources/system_audio.rs b/crates/media/src/sources/system_audio.rs
deleted file mode 100644
index 5c1fd000e..000000000
--- a/crates/media/src/sources/system_audio.rs
+++ /dev/null
@@ -1,295 +0,0 @@
-use crate::{
- data::AudioInfo,
- pipeline::{task::PipelineSourceTask, RawNanoseconds, RealTimeClock},
-};
-use ffmpeg::frame as avframe;
-use flume::Receiver;
-
-pub trait SystemAudioSource {
- fn info() -> Result<AudioInfo, String>
- where
- Self: Sized;
-}
-
-#[cfg(target_os = "macos")]
-pub mod macos {
- use crate::{
- data::{AudioInfo, PlanarData},
- pipeline::control::Control,
- };
-
- use super::*;
-
- use cidre::{
- arc, cm, define_obj_type, ns, objc,
- sc::{
- self,
- stream::{Output, OutputImpl},
- },
- };
- use ffmpeg::ChannelLayout;
- use flume::{Receiver, Sender};
-
- #[repr(C)]
- struct DelegateInner {
- tx: Sender<Result<avframe::Audio, String>>,
- }
-
- impl DelegateInner {
- fn new() -> (Self, Receiver<Result<avframe::Audio, String>>) {
- let (tx, rx) = flume::bounded(8);
-
- (Self { tx }, rx)
- }
- }
-
- define_obj_type!(Delegate + OutputImpl, DelegateInner, FRAME_COUNTER);
-
- impl Output for Delegate {}
-
- #[objc::add_methods]
- impl OutputImpl for Delegate {
- extern "C" fn impl_stream_did_output_sample_buf(
- &mut self,
- _cmd: Option<&cidre::objc::Sel>,
- _stream: &sc::Stream,
- sample_buf: &mut cm::SampleBuf,
- kind: sc::OutputType,
- ) {
- match kind {
- sc::OutputType::Screen => {}
- sc::OutputType::Audio => {
- let buf_list = sample_buf.audio_buf_list::<2>().unwrap();
- let slice = buf_list.block().as_slice().unwrap();
-
- let mut frame = ffmpeg::frame::Audio::new(
- ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Planar),
- sample_buf.num_samples() as usize,
- ChannelLayout::STEREO,
- );
- frame.set_rate(48_000);
- let data_bytes_size = buf_list.list().buffers[0].data_bytes_size;
- for i in 0..frame.planes() {
- frame.plane_data_mut(i).copy_from_slice(
- &slice
- [i * data_bytes_size as usize..(i + 1) * data_bytes_size as usize],
- );
- }
-
- frame.set_pts(Some(sample_buf.pts().value));
-
- self.inner_mut().tx.send(Ok(frame));
- }
- sc::OutputType::Mic => {}
- }
- }
- }
-
- pub struct Source {
- content: arc::R<sc::ShareableContent>,
- delegate: arc::R<Delegate>,
- rx: flume::Receiver<Result<avframe::Audio, String>>,
- }
-
- impl Source {
- pub async fn init() -> Result<Self, String> {
- let content = sc::ShareableContent::current()
- .await
- .map_err(|e| format!("System Audio / {e}"))?;
-
- let (inner, rx) = DelegateInner::new();
- let delegate = Delegate::with(inner);
-
- Ok(Self {
- content,
- delegate,
- rx,
- })
- }
- }
-
- impl SystemAudioSource for Source {
- fn info() -> Result<AudioInfo, String> {
- Ok(AudioInfo::new(
- ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Planar),
- 48_000,
- 2,
- )
- .unwrap())
- }
- }
-
- impl PipelineSourceTask for Source {
- type Clock = RealTimeClock<RawNanoseconds>;
- type Output = ffmpeg::frame::Audio;
-
- fn run(
- &mut self,
- mut clock: Self::Clock,
- ready_signal: crate::pipeline::task::PipelineReadySignal,
- mut control_signal: crate::pipeline::control::PipelineControlSignal,
- ) {
- let mut cfg = sc::StreamCfg::new();
- cfg.set_captures_audio(true);
- cfg.set_excludes_current_process_audio(false);
-
- let display = &self.content.displays().get(0).unwrap();
- let filter =
- sc::ContentFilter::with_display_excluding_windows(display, &ns::Array::new());
-
- let stream = sc::Stream::new(&filter, &cfg);
-
- stream
- .add_stream_output(self.delegate.as_ref(), sc::OutputType::Audio, None)
- .unwrap();
-
- futures::executor::block_on(stream.start()).unwrap();
-
- let _ = ready_signal.send(Ok(()));
-
- loop {
- match control_signal.last() {
- Some(Control::Play) => match self.rx.recv() {
- Ok(Ok(mut samples)) => {
- let ts = RawNanoseconds(samples.pts().unwrap() as u64);
- samples.set_pts(clock.timestamp_for(ts));
-
- let _ = output.send(samples);
- }
- _ => {
- break;
- }
- },
- Some(Control::Shutdown) | None => {
- futures::executor::block_on(stream.stop()).unwrap();
- break;
- }
- }
- }
- }
- }
-}
-
-pub mod windows {
- use crate::{
- data::AudioInfo,
- pipeline::{control::Control, task::PipelineSourceTask, RealTimeClock},
- };
- use cpal::{
- traits::{DeviceTrait, HostTrait, StreamTrait},
- *,
- };
- use flume::Sender;
-
- use super::SystemAudioSource;
-
- pub struct Source {
- output: Sender<ffmpeg::frame::Audio>,
- }
-
- impl Source {
- pub fn info() -> Result<AudioInfo, String> {
- let host = cpal::default_host();
-
- let output_device = host
- .default_output_device()
- .ok_or_else(|| "No default output device".to_string())?;
- let supported_config = output_device
- .default_output_config()
- .map_err(|e| format!("Default Stream / {e}"))?;
-
- Ok(AudioInfo::from_stream_config(&supported_config))
- }
- }
-
- impl SystemAudioSource for Source {
- fn info() -> Result<AudioInfo, String>
- where
- Self: Sized,
- {
- Self::info()
- }
- }
-
- impl PipelineSourceTask for Source {
- type Clock = RealTimeClock<StreamInstant>;
- type Output = ffmpeg::frame::Audio;
-
- fn run(
- &mut self,
- mut clock: Self::Clock,
- ready_signal: crate::pipeline::task::PipelineReadySignal,
- mut control_signal: crate::pipeline::control::PipelineControlSignal,
- ) {
- let host = cpal::default_host();
-
- let (tx, rx) = flume::bounded(8);
-
- let init = || {
- let output_device = host
- .default_output_device()
- .ok_or_else(|| "No default output device".to_string())?;
- let supported_config = output_device
- .default_output_config()
- .map_err(|e| format!("Default Stream / {e}"))?;
- let config = supported_config.clone().into();
-
- let stream = output_device
- .build_input_stream_raw(
- &config,
- supported_config.sample_format(),
- {
- let tx = tx.clone();
- move |data, info: &cpal::InputCallbackInfo| {
- tx.send(Ok((data.bytes().to_vec(), info.clone()))).unwrap();
- }
- },
- move |e| {
- let _ = tx.send(Err(e));
- },
- None,
- )
- .map_err(|e| format!("Build Input Stream / {e}"))?;
-
- stream.play().map_err(|e| format!("Play Stream / {e}"))?;
-
- Ok::<_, String>((supported_config, stream))
- };
-
- let (supported_config, _) = match init() {
- Ok(v) => v,
- Err(e) => {
- let _ = ready_signal.send(Err(crate::MediaError::TaskLaunch(e)));
- return;
- }
- };
-
- let audio_info = AudioInfo::from_stream_config(&supported_config);
-
- loop {
- match control_signal.last() {
- Some(Control::Play) => match rx.recv() {
- Ok(Ok((data, info))) => match clock.timestamp_for(info.timestamp().capture)
- {
- None => {
- eprintln!("Clock is currently stopped. Dropping frames.");
- }
- Some(timestamp) => {
- let frame = audio_info.wrap_frame(&data, timestamp);
- if let Err(_) = output.send(frame) {
- break;
- }
- }
- },
- _ => {
- break;
- }
- },
- Some(Control::Shutdown) | None => {
- return;
- }
- }
- }
- }
- }
-}
diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rs
index ea9524fcf..e373b6727 100644
--- a/crates/recording/src/cursor.rs
+++ b/crates/recording/src/cursor.rs
@@ -8,7 +8,7 @@ use std::{
use cap_cursor_capture::RawCursorPosition;
use cap_displays::Display;
-use cap_media::platform::Bounds;
+use cap_media::{platform::Bounds, sources::CropRatio};
use cap_project::{CursorClickEvent, CursorMoveEvent, XY};
use cap_utils::spawn_actor;
use device_query::{DeviceQuery, DeviceState};
@@ -48,7 +48,7 @@ impl CursorActor {
pub fn spawn_cursor_recorder(
#[allow(unused)] screen_bounds: Bounds,
#[cfg(target_os = "macos")] display: Display,
- #[cfg(target_os = "macos")] crop_ratio: ((f32, f32), (f32, f32)),
+ #[cfg(target_os = "macos")] crop_ratio: CropRatio,
cursors_dir: PathBuf,
prev_cursors: Cursors,
next_cursor_id: u32,
@@ -135,7 +135,7 @@ pub fn spawn_cursor_recorder(
let cropped_position = position
.relative_to_display(display)
.normalize()
- .with_crop(crop_ratio.0, crop_ratio.1);
+ .with_crop(crop_ratio.position, crop_ratio.size);
Some((cropped_position.x() as f64, cropped_position.y() as f64))
} else {