Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

mic and display capture integration

PJ8fa3a54e2c38
diff --git a/Cargo.lock b/Cargo.lock
index c5aa35b35..833b1947a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -736,6 +736,7 @@ dependencies = [
"serde",
"smol",
"specta",
+ "tempfile",
"thiserror",
"tracing",
"tracing-subscriber",
@@ -1554,6 +1555,7 @@ dependencies = [
"tempfile",
"tokio",
"tracing",
+ "tracing-subscriber",
"uuid",
"wgpu",
]
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index c7493d01a..9e488b905 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -79,6 +79,7 @@ cap-media = { path = "../../../crates/media" }
reqwest = { version = "0.12.7", features = ["json", "stream", "multipart"] }
dotenvy_macro = "0.15.7"
global-hotkey = "0.5.5"
+tracing-subscriber = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
core-graphics = "0.24.0"
diff --git a/apps/desktop/src-tauri/src/display.rs b/apps/desktop/src-tauri/src/display.rs
deleted file mode 100644
index a300a78ff..000000000
--- a/apps/desktop/src-tauri/src/display.rs
+++ /dev/null
@@ -1,370 +0,0 @@
-use ffmpeg::{format as avformat, frame::Video, software};
-use std::path::PathBuf;
-
-use scap::{
- capturer::{Area, Capturer, Options, Point, Resolution, Size},
- frame::{Frame, FrameType},
- Target,
-};
-use serde::{Deserialize, Serialize};
-use specta::Type;
-use tokio::sync::{oneshot, watch};
-
-use crate::{
- capture::CaptureController,
- encoder::{bgra_frame, H264Encoder},
- macos,
-};
-
-#[derive(Type, Serialize, Deserialize, Debug, Clone)]
-pub struct Bounds {
- pub x: f64,
- pub y: f64,
- pub width: f64,
- pub height: f64,
-}
-
-#[derive(Type, Serialize)]
-pub struct CaptureWindow {
- id: u32,
- name: String,
-}
-
-#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
-#[serde(rename_all = "camelCase", tag = "type")]
-pub enum CaptureTarget {
- Screen,
- Window { id: u32 },
-}
-
-#[tauri::command(async)]
-#[specta::specta]
-pub fn list_capture_windows() -> Vec<CaptureWindow> {
- if !scap::has_permission() {
- return vec![];
- }
-
- let targets = scap::get_all_targets();
-
- let windows = macos::get_on_screen_windows();
-
- targets
- .into_iter()
- .filter_map(|target| match target {
- Target::Window(scap_window)
- if windows
- .iter()
- .any(|window| window.window_number == scap_window.raw_handle) =>
- {
- Some(scap_window)
- }
- _ => None,
- })
- .map(|scap_window| {
- // Find the corresponding window to get the application name
- let app_name = windows
- .iter()
- .find(|window| window.window_number == scap_window.raw_handle)
- .map(|window| window.owner_name.clone())
- .unwrap_or(scap_window.title.clone());
- CaptureWindow {
- id: scap_window.id,
- name: app_name,
- }
- })
- .collect::<Vec<_>>()
-}
-
-pub const FPS: u32 = 30;
-
-// ffmpeg
-// .command
-// .args(["-f", "mp4", "-map", &format!("{}:v", ffmpeg_input.index)])
-// .args(["-codec:v", "libx264", "-preset", "ultrafast"])
-// .args(["-g", &keyframe_interval_str])
-// .args(["-keyint_min", &keyframe_interval_str])
-// .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
-// // .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
-// // .args(["-movflags", "frag_keyframe+empty_moov"])
-// .args([
-// "-vf",
-// &format!("fps={},scale=in_range=full:out_range=limited", display::FPS),
-// ])
-// .arg(&output_path);
-
-pub async fn start_capturing(
- output_path: PathBuf,
- capture_target: &CaptureTarget,
- start_writing_rx: watch::Receiver<bool>,
-) -> CaptureController {
- dbg!(capture_target);
-
- // Bring the window into focus if we're capturing a window
- if let CaptureTarget::Window { id: window_number } = capture_target {
- bring_window_to_focus(*window_number);
- }
-
- let targets = scap::get_all_targets();
-
- let mut capturer = {
- let crop_area = match capture_target {
- CaptureTarget::Window { id: window_number } => {
- get_window_bounds(*window_number).map(|bounds| Area {
- size: Size {
- width: bounds.width,
- height: bounds.height,
- },
- origin: Point {
- x: bounds.x,
- y: bounds.y,
- },
- })
- }
- _ => None,
- };
-
- let excluded_titles = [
- "Cap",
- "Cap Camera",
- "Cap Recordings",
- "Cap In Progress Recording",
- ];
- let excluded_targets: Vec<scap::Target> = targets
- .clone()
- .into_iter()
- .filter(|target| match target {
- Target::Window(scap_window)
- if excluded_titles.contains(&scap_window.title.as_str()) =>
- {
- true
- }
- _ => false,
- })
- .collect();
-
- let options = Options {
- fps: FPS,
- show_highlight: true,
- show_cursor: true,
- output_type: FrameType::BGRAFrame,
- output_resolution: Resolution::Captured,
- crop_area,
- excluded_targets: Some(excluded_targets),
- ..Default::default()
- };
-
- Capturer::new(dbg!(options))
- };
-
- let controller = CaptureController::new(output_path);
-
- let (tx, rx) = oneshot::channel();
-
- std::thread::spawn({
- let controller = controller.clone();
- move || {
- let capture_format = avformat::Pixel::BGRA;
- let output_format = H264Encoder::output_format();
-
- let capture_size = capturer.get_output_frame_size();
- let frame_size = scale_dimensions(capture_size[0], capture_size[1], 1920);
-
- let mut encoder = H264Encoder::new(
- &controller.output_path,
- frame_size.0,
- frame_size.1,
- FPS as f64,
- );
-
- // 1080p scaling via scap causes artifacts on external monitors so ffmpeg it is
- let mut scaler = software::scaling::Context::get(
- capture_format,
- capture_size[0],
- capture_size[1],
- output_format,
- frame_size.0,
- frame_size.1,
- software::scaling::Flags::FAST_BILINEAR,
- )
- .unwrap();
-
- capturer.start_capture();
-
- let mut start_time_tx = Some(tx);
-
- loop {
- if controller.is_stopped() {
- break;
- }
-
- let frame = capturer.get_next_frame();
-
- if controller.is_paused() {
- continue;
- }
-
- if let Some(tx) = start_time_tx.take() {
- tx.send(()).ok();
- }
-
- if !*start_writing_rx.borrow() {
- continue;
- }
-
- match frame {
- Ok(Frame::BGRA(frame)) => {
- if let Some(rgb_frame) =
- bgra_frame(&frame.data, capture_size[0], capture_size[1])
- {
- let mut yuv_frame = Video::empty();
- scaler.run(&rgb_frame, &mut yuv_frame).unwrap();
-
- encoder.encode_frame(yuv_frame, frame.display_time / 1_000_000);
- }
- }
- _ => println!("Failed to get frame"),
- }
- }
-
- encoder.close();
- }
- });
-
- rx.await.unwrap(); // wait for first frame
-
- controller
-}
-
-pub fn get_window_bounds(window_number: u32) -> Option<Bounds> {
- let windows = macos::get_on_screen_windows();
-
- let window = windows
- .into_iter()
- .find(|w| w.window_number == window_number)?;
-
- Some(Bounds {
- width: window.bounds.width as f64,
- height: window.bounds.height as f64,
- x: window.bounds.x as f64,
- y: window.bounds.y as f64,
- })
-}
-
-fn scale_dimensions(width: u32, height: u32, max_width: u32) -> (u32, u32) {
- if width <= max_width {
- return (width, height);
- }
-
- let aspect_ratio = width as f32 / height as f32;
- let new_width = max_width;
- let new_height = (new_width as f32 / aspect_ratio).round() as u32;
-
- // Ensure dimensions are divisible by 2
- (new_width & !1, new_height & !1)
-}
-
-use crate::macos::get_on_screen_windows;
-use std::io::Write;
-use std::process::Command;
-use tempfile::NamedTempFile;
-
-fn bring_window_to_focus(window_id: u32) {
- println!("Attempting to bring window {} to focus", window_id);
-
- // Get the window information associated with the window id
- let windows = get_on_screen_windows();
- if let Some(window) = windows.into_iter().find(|w| w.window_number == window_id) {
- let process_id = window.process_id;
- let window_title = window.name.clone();
- let bounds_x = window.bounds.x;
- let bounds_y = window.bounds.y;
- let bounds_width = window.bounds.width;
- let bounds_height = window.bounds.height;
- let should_focus = true;
-
- // Prepare the AppleScript
- let apple_script = r#"
- on run argv
- set processId to item 1 of argv as number
- set windowTitle to item 2 of argv
- set boundsX to item 3 of argv as number
- set boundsY to item 4 of argv as number
- set boundsWidth to item 5 of argv as number
- set boundsHeight to item 6 of argv as number
- set shouldFocus to item 7 of argv as boolean or true
-
- log "processId: " & processId
- log "windowTitle: " & windowTitle
- log "boundsX: " & boundsX
- log "boundsY: " & boundsY
- log "boundsWidth: " & boundsWidth
- log "boundsHeight: " & boundsHeight
-
- tell application "System Events"
- set appProcess to first process whose unix id is processId
- set frontmost of appProcess to true
-
- tell appProcess
- set appWindowsCount to count of windows
- log "appWindowsCount: " & appWindowsCount
-
- if appWindowsCount is equal to 1 then
- perform action "AXRaise" of first window
- log "--found window--"
- return
- end if
-
- repeat with checkedWindow in windows
- tell checkedWindow
- if title contains windowTitle and position is equal to {boundsX, boundsY} and size is equal to {boundsWidth, boundsHeight} then
- perform action "AXRaise" of checkedWindow
- log "--found window--"
- exit repeat
- end if
- end tell
- end repeat
- end tell
- end tell
- end run
- "#;
-
- // Prepare arguments
- let args = vec![
- process_id.to_string(),
- window_title.clone(),
- bounds_x.to_string(),
- bounds_y.to_string(),
- bounds_width.to_string(),
- bounds_height.to_string(),
- should_focus.to_string(),
- ];
-
- // Write the AppleScript to a temporary file
- let mut script_file = NamedTempFile::new().expect("Failed to create temp file");
- script_file
- .write_all(apple_script.as_bytes())
- .expect("Failed to write to temp file");
-
- // Execute the AppleScript with arguments
- let output = Command::new("osascript")
- .arg(script_file.path())
- .args(&args)
- .output();
-
- match output {
- Ok(output) => {
- if output.status.success() {
- println!("Successfully executed AppleScript");
- } else {
- let error_message = String::from_utf8_lossy(&output.stderr);
- eprintln!("AppleScript execution failed: {}", error_message);
- }
- }
- Err(e) => eprintln!("Failed to execute AppleScript: {}", e),
- }
-
- println!("Finished attempt to bring window {} to focus", window_id);
- } else {
- eprintln!("Window with id {} not found", window_id);
- }
-}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 4b70705fc..3c456f250 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -2,7 +2,6 @@ mod audio;
mod auth;
mod camera;
mod capture;
-mod display;
mod encoder;
mod flags;
mod general_settings;
@@ -21,19 +20,19 @@ use auth::AuthStore;
use camera::{list_cameras, CameraFeed};
use cap_editor::{AudioData, EditorState, ProjectRecordings};
use cap_editor::{EditorInstance, FRAMES_WS_PATH};
-use cap_ffmpeg::FFmpeg;
+use cap_media::{platform::Bounds, sources::ScreenCaptureTarget};
use cap_project::{
ProjectConfiguration, RecordingMeta, SharingMeta, TimelineConfiguration, TimelineSegment,
};
use cap_rendering::ProjectUniforms;
use cap_utils::create_named_pipe;
-use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
+// use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use general_settings::GeneralSettingsStore;
use image::{ImageBuffer, Rgba};
use mp4::Mp4Reader;
use num_traits::ToBytes;
use png::{ColorType, Encoder};
-use recording::{DisplaySource, InProgressRecording};
+use recording::{list_capture_windows, InProgressRecording, FPS};
use scap::capturer::Capturer;
use scap::frame::Frame;
use serde::{Deserialize, Serialize};
@@ -64,7 +63,7 @@ use windows::CapWindow;
#[derive(specta::Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct RecordingOptions {
- capture_target: CaptureTarget,
+ capture_target: ScreenCaptureTarget,
camera_label: Option<String>,
audio_input_name: Option<String>,
}
@@ -120,7 +119,7 @@ impl App {
CurrentRecordingChanged(json).emit(&self.handle).ok();
- if let DisplaySource::Window { .. } = &current_recording.display_source {
+ if let ScreenCaptureTarget::Window { .. } = &current_recording.display_source {
CapWindow::WindowCaptureOccluder.show(&self.handle);
} else {
self.close_occluder_window();
@@ -291,14 +290,19 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result
.join("recordings")
.join(format!("{id}.cap"));
- let recording = recording::start(
+ match recording::start(
recording_dir,
&state.start_recording_options,
state.camera_feed.as_ref(),
)
- .await;
-
- state.set_current_recording(recording);
+ .await
+ {
+ Ok(recording) => state.set_current_recording(recording),
+ Err(error) => {
+ eprintln!("{error}");
+ return Err("Failed to set up recording".into());
+ }
+ };
if let Some(window) = CapWindow::Main.get(&app) {
window.minimize().ok();
@@ -339,7 +343,7 @@ async fn resume_recording(state: MutableState<'_, App>) -> Result<(), String> {
let mut state = state.write().await;
if let Some(recording) = &mut state.current_recording {
- recording.resume().await?;
+ recording.play().await?;
recording.segments.push(
SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -364,7 +368,7 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
.as_secs_f64(),
);
- current_recording.stop();
+ current_recording.stop().await;
println!("Recording stopped");
if let Some(window) = (CapWindow::InProgressRecording { position: None }).get(&app) {
@@ -380,7 +384,7 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
.recording_dir
.join("screenshots/display.jpg");
create_screenshot(
- current_recording.display.output_path.clone(),
+ current_recording.display_output_path.clone(),
display_screenshot.clone(),
None,
)
@@ -2185,7 +2189,7 @@ pub async fn run() {
camera_ws_port,
camera_feed: None,
start_recording_options: RecordingOptions {
- capture_target: CaptureTarget::Screen,
+ capture_target: ScreenCaptureTarget::Screen,
camera_label: None,
audio_input_name: None,
},
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 6d742f68d..89e3e6946 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -3,5 +3,7 @@
#[tokio::main]
async fn main() {
+ tracing_subscriber::fmt::init();
+
desktop_solid_lib::run().await
}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index f05c2a1af..c15c706c2 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,8 +1,9 @@
-use crate::audio::AudioCapturer;
+// use crate::audio::AudioCapturer;
use crate::camera::CameraFeed;
-use crate::capture::CaptureController;
+// use crate::capture::CaptureController;
use crate::flags;
-use cap_ffmpeg::{FFmpeg, FFmpegInput, FFmpegProcess, FFmpegRawAudioInput};
+// use cap_ffmpeg::{FFmpeg, FFmpegInput, FFmpegProcess, FFmpegRawAudioInput};
+use cap_media::{encoders::*, filters::*, pipeline::*, sources::*, MediaError};
use device_query::{DeviceQuery, DeviceState};
use futures::future::OptionFuture;
use serde::Deserialize;
@@ -22,16 +23,19 @@ use objc::runtime::{Class, Object, Sel, BOOL, NO, YES};
use objc::*;
use crate::{
- audio, camera,
- display::{self, get_window_bounds, CaptureTarget},
- Bounds, RecordingOptions,
+ audio,
+ camera,
+ // display::{self, get_window_bounds, CaptureTarget},
+ RecordingOptions,
};
-#[derive(Clone, Type, Serialize)]
-#[serde(rename_all = "camelCase", tag = "variant")]
-pub enum DisplaySource {
- Screen,
- Window { bounds: Bounds },
+// TODO: Hacky, please fix
+pub const FPS: u32 = 30;
+
+#[tauri::command(async)]
+#[specta::specta]
+pub fn list_capture_windows() -> Vec<CaptureWindow> {
+ ScreenCaptureSource::list_targets()
}
#[derive(Serialize, Deserialize, Clone, Type)]
@@ -50,28 +54,26 @@ pub struct MouseEvent {
pub struct InProgressRecording {
pub recording_dir: PathBuf,
#[serde(skip)]
- pub ffmpeg_process: FFmpegProcess,
+ pub pipeline: Pipeline<SynchronisedClock<()>>,
#[serde(skip)]
- pub display: CaptureController,
- pub display_source: DisplaySource,
+ pub display_output_path: PathBuf,
#[serde(skip)]
- pub camera: Option<CaptureController>,
+ pub camera_output_path: Option<PathBuf>,
#[serde(skip)]
- pub audio: Option<(FFmpegCaptureOutput<FFmpegRawAudioInput>, AudioCapturer)>,
+ pub audio_output_path: Option<PathBuf>,
+ pub display_source: ScreenCaptureTarget,
pub segments: Vec<f64>,
- #[serde(skip)]
- pub mouse_moves: Arc<Mutex<Vec<MouseEvent>>>,
- #[serde(skip)]
- pub mouse_clicks: Arc<Mutex<Vec<MouseEvent>>>,
- #[serde(skip)]
- pub stop_signal: Arc<Mutex<bool>>,
+ // #[serde(skip)]
+ // pub mouse_moves: Arc<Mutex<Vec<MouseEvent>>>,
+ // #[serde(skip)]
+ // pub mouse_clicks: Arc<Mutex<Vec<MouseEvent>>>,
}
unsafe impl Send for InProgressRecording {}
unsafe impl Sync for InProgressRecording {}
impl InProgressRecording {
- pub fn stop(&mut self) {
+ pub async fn stop(&mut self) {
use cap_project::*;
let meta = RecordingMeta {
project_path: self.recording_dir.clone(),
@@ -82,26 +84,16 @@ impl InProgressRecording {
),
display: Display {
path: self
- .display
- .output_path
+ .display_output_path
.strip_prefix(&self.recording_dir)
.unwrap()
.to_owned(),
},
- camera: self.camera.as_ref().map(|camera| CameraMeta {
- path: camera
- .output_path
- .strip_prefix(&self.recording_dir)
- .unwrap()
- .to_owned(),
+ camera: self.camera_output_path.as_ref().map(|path| CameraMeta {
+ path: path.strip_prefix(&self.recording_dir).unwrap().to_owned(),
}),
- audio: self.audio.as_ref().map(|audio| AudioMeta {
- path: audio
- .0
- .output_path
- .strip_prefix(&self.recording_dir)
- .unwrap()
- .to_owned(),
+ audio: self.audio_output_path.as_ref().map(|path| AudioMeta {
+ path: path.strip_prefix(&self.recording_dir).unwrap().to_owned(),
}),
segments: {
let relative_segments = self
@@ -130,57 +122,32 @@ impl InProgressRecording {
};
// Signal the mouse event tracking to stop
- *self.stop_signal.lock().unwrap() = true;
-
- self.display.stop();
- if let Some(camera) = &self.camera {
- camera.stop();
+ if let Err(error) = self.pipeline.shutdown().await {
+ eprintln!("Error while stopping recording: {error}");
}
- self.ffmpeg_process.stop();
- if let Err(e) = self.ffmpeg_process.wait() {
- eprintln!("Failed to wait for ffmpeg process: {:?}", e);
- }
- if let Some(audio) = self.audio.take() {
- audio.0.capture.stop();
- drop(audio);
- }
+ // if flags::RECORD_MOUSE {
+ // // Save mouse events to files
+ // let mouse_moves_path = self.recording_dir.join("mousemoves.json");
+ // let mouse_clicks_path = self.recording_dir.join("mouseclicks.json");
- if flags::RECORD_MOUSE {
- // Save mouse events to files
- let mouse_moves_path = self.recording_dir.join("mousemoves.json");
- let mouse_clicks_path = self.recording_dir.join("mouseclicks.json");
+ // let mouse_moves = self.mouse_moves.lock().unwrap();
+ // let mouse_clicks = self.mouse_clicks.lock().unwrap();
- let mouse_moves = self.mouse_moves.lock().unwrap();
- let mouse_clicks = self.mouse_clicks.lock().unwrap();
+ // let mut mouse_moves_file = File::create(mouse_moves_path).unwrap();
+ // let mut mouse_clicks_file = File::create(mouse_clicks_path).unwrap();
- let mut mouse_moves_file = File::create(mouse_moves_path).unwrap();
- let mut mouse_clicks_file = File::create(mouse_clicks_path).unwrap();
-
- serde_json::to_writer(&mut mouse_moves_file, &*mouse_moves).unwrap();
- serde_json::to_writer(&mut mouse_clicks_file, &*mouse_clicks).unwrap();
- }
+ // serde_json::to_writer(&mut mouse_moves_file, &*mouse_moves).unwrap();
+ // serde_json::to_writer(&mut mouse_clicks_file, &*mouse_clicks).unwrap();
+ // }
meta.save_for_project();
}
- pub fn stop_and_discard(&mut self) {
+ pub async fn stop_and_discard(&mut self) {
// Signal the mouse event tracking to stop
- *self.stop_signal.lock().unwrap() = true;
-
- // Stop all recording processes
- self.display.stop();
- if let Some(camera) = &self.camera {
- camera.stop();
- }
-
- self.ffmpeg_process.stop();
- if let Err(e) = self.ffmpeg_process.wait() {
- eprintln!("Failed to wait for ffmpeg process: {:?}", e);
- }
- if let Some(audio) = self.audio.take() {
- audio.0.capture.stop();
- drop(audio);
+ if let Err(error) = self.pipeline.shutdown().await {
+ eprintln!("Error while stopping recording: {error}");
}
// Delete all recorded files
@@ -190,189 +157,155 @@ impl InProgressRecording {
}
pub async fn pause(&mut self) -> Result<(), String> {
- self.display.pause();
- if let Some(camera) = &mut self.camera {
- camera.pause();
- }
- if let Some(audio) = &mut self.audio {
- audio.0.capture.pause();
- }
- println!("Sent pause command to FFmpeg");
+ let _ = self.pipeline.pause().await;
Ok(())
}
- pub async fn resume(&mut self) -> Result<(), String> {
- self.display.resume();
- if let Some(camera) = &mut self.camera {
- camera.resume();
- }
- if let Some(audio) = &mut self.audio {
- audio.0.capture.resume();
- }
-
- println!("Sent resume command to FFmpeg");
+ pub async fn play(&mut self) -> Result<(), String> {
+ let _ = self.pipeline.play().await;
Ok(())
}
}
-pub struct FFmpegCaptureOutput<T> {
- pub input: FFmpegInput<T>,
- pub capture: CaptureController,
- pub output_path: PathBuf,
-}
-
pub async fn start(
recording_dir: PathBuf,
recording_options: &RecordingOptions,
camera_feed: Option<&CameraFeed>,
-) -> InProgressRecording {
+) -> Result<InProgressRecording, MediaError> {
let content_dir = recording_dir.join("content");
std::fs::create_dir_all(&content_dir).unwrap();
- let mut ffmpeg = FFmpeg::new();
-
- let (start_writing_tx, start_writing_rx) = watch::channel(false);
-
- let audio_pipe_path = content_dir.join("audio-input.pipe");
-
- let (display, camera, audio) = tokio::join!(
- display::start_capturing(
- content_dir.join("display.mp4"),
- &recording_options.capture_target,
- start_writing_rx.clone(),
- ),
- OptionFuture::from(camera_feed.map(|camera_feed| {
- camera::start_capturing(
- content_dir.join("camera.mp4"),
- camera_feed,
- start_writing_rx.clone(),
- )
- }),),
- OptionFuture::from(
- recording_options
- .audio_input_name()
- .and_then(audio::AudioCapturer::init)
- .map(|capturer| {
- audio::start_capturing(capturer, audio_pipe_path.clone(), start_writing_rx)
- }),
- )
- );
-
- let audio = if let Some((controller, capturer)) = audio {
- let output_path = content_dir.join("audio-input.mp3");
-
- dbg!(&capturer.config);
-
- let ffmpeg_input = ffmpeg.add_input(FFmpegRawAudioInput {
- input: audio_pipe_path.into_os_string(),
- sample_format: capturer.sample_format().to_string(),
- sample_rate: capturer.sample_rate(),
- channels: capturer.channels(),
- });
-
- ffmpeg
- .command
- .args(["-f", "mp3", "-map", &format!("{}:a", ffmpeg_input.index)])
- .args(["-b:a", "128k"])
- .args(["-ar", &capturer.sample_rate().to_string()])
- .args(["-ac", &capturer.channels().to_string(), "-async", "1"])
- .args([
- "-af",
- "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
- ])
- .arg(&output_path);
-
- Some((
- FFmpegCaptureOutput {
- input: ffmpeg_input,
- capture: controller,
- output_path,
- },
- capturer,
- ))
- } else {
- None
- };
-
- let ffmpeg_process = ffmpeg.start();
-
- tokio::time::sleep(Duration::from_secs(1)).await;
+ let clock = SynchronisedClock::<()>::new();
+ let mut pipeline_builder = Pipeline::builder(clock);
+
+ let display_output_path = content_dir.join("display.mp4");
+ let mut audio_output_path = None;
+ let mut camera_output_path = None;
+
+ let screen_source = ScreenCaptureSource::init(&recording_options.capture_target, None, None);
+ let screen_config = screen_source.info();
+ let screen_filter = VideoFilter::init(
+ "screen",
+ screen_config,
+ "scale=in_range=full:out_range=limited",
+ )?;
+ let screen_encoder = H264Encoder::init(
+ "screen",
+ screen_config,
+ Output::File(display_output_path.clone()),
+ )?;
+ pipeline_builder = pipeline_builder
+ .source("screen_capture", screen_source)
+ .pipe("screen_capture_filter", screen_filter)
+ .sink("screen_capture_encoder", screen_encoder);
+
+ if let Some(mic_source) = AudioInputSource::init(recording_options.audio_input_name.as_ref()) {
+ let mic_config = mic_source.info();
+ audio_output_path = Some(content_dir.join("audio-input.mp3"));
+
+ // let mic_filter = AudioFilter::init("microphone", mic_config, "aresample=async=1:min_hard_comp=0.100000:first_pts=0")?;
+ let mic_encoder = MP3Encoder::init(
+ "microphone",
+ mic_config,
+ Output::File(audio_output_path.clone().unwrap()),
+ )?;
+
+ pipeline_builder = pipeline_builder
+ .source("microphone_capture", mic_source)
+ // .pipe("microphone_filter", mic_filter)
+ .sink("microphone_encoder", mic_encoder);
+ }
- println!("Starting writing to named pipes");
+ if let Some(camera_source) = CameraSource::init(recording_options.camera_label.as_ref()) {
+ let camera_config = camera_source.info();
+ camera_output_path = Some(content_dir.join("camera.mp4"));
+
+ let camera_filter = VideoFilter::init(
+ "camera",
+ camera_config,
+ "scale=in_range=full:out_range=limited",
+ )?;
+ let camera_encoder = H264Encoder::init(
+ "camera",
+ camera_config,
+ Output::File(camera_output_path.clone().unwrap()),
+ )?;
+
+ pipeline_builder = pipeline_builder
+ .source("camera_capture", camera_source)
+ .pipe("camera_filter", camera_filter)
+ .sink("camera_encoder", camera_encoder);
+ }
- start_writing_tx.send(true).unwrap();
+ let mut pipeline = pipeline_builder.build().await?;
+ pipeline.play().await?;
// Initialize mouse event tracking
- let mouse_moves = Arc::new(Mutex::new(Vec::new()));
- let mouse_clicks = Arc::new(Mutex::new(Vec::new()));
- let stop_signal = Arc::new(Mutex::new(false));
+ // let mouse_moves = Arc::new(Mutex::new(Vec::new()));
+ // let mouse_clicks = Arc::new(Mutex::new(Vec::new()));
+ // let stop_signal = Arc::new(Mutex::new(false));
// Start mouse event tracking
- let mouse_moves_clone = Arc::clone(&mouse_moves);
- let mouse_clicks_clone = Arc::clone(&mouse_clicks);
- let stop_signal_clone = Arc::clone(&stop_signal);
- tokio::spawn(async move {
- let device_state = DeviceState::new();
- let mut last_mouse_state = device_state.get_mouse();
- let start_time = Instant::now();
-
- while !*stop_signal_clone.lock().unwrap() {
- let mouse_state = device_state.get_mouse();
- let elapsed = start_time.elapsed().as_secs_f64() * 1000.0;
- let unix_time = chrono::Utc::now().timestamp_millis() as f64;
-
- if mouse_state.coords != last_mouse_state.coords {
- let mouse_event = MouseEvent {
- active_modifiers: vec![],
- cursor_id: get_cursor_id(),
- process_time_ms: elapsed,
- event_type: "mouseMoved".to_string(),
- unix_time_ms: unix_time,
- x: mouse_state.coords.0 as f64,
- y: mouse_state.coords.1 as f64,
- };
- mouse_moves_clone.lock().unwrap().push(mouse_event);
- }
-
- if mouse_state.button_pressed[0] && !last_mouse_state.button_pressed[0] {
- let mouse_event = MouseEvent {
- active_modifiers: vec![],
- cursor_id: get_cursor_id(),
- process_time_ms: elapsed,
- event_type: "mouseClicked".to_string(),
- unix_time_ms: unix_time,
- x: mouse_state.coords.0 as f64,
- y: mouse_state.coords.1 as f64,
- };
- mouse_clicks_clone.lock().unwrap().push(mouse_event);
- }
-
- last_mouse_state = mouse_state;
- tokio::time::sleep(Duration::from_millis(10)).await;
- }
- });
-
- InProgressRecording {
+ // let mouse_moves_clone = Arc::clone(&mouse_moves);
+ // let mouse_clicks_clone = Arc::clone(&mouse_clicks);
+ // let stop_signal_clone = Arc::clone(&stop_signal);
+ // tokio::spawn(async move {
+ // let device_state = DeviceState::new();
+ // let mut last_mouse_state = device_state.get_mouse();
+ // let start_time = Instant::now();
+
+ // while !*stop_signal_clone.lock().unwrap() {
+ // let mouse_state = device_state.get_mouse();
+ // let elapsed = start_time.elapsed().as_secs_f64() * 1000.0;
+ // let unix_time = chrono::Utc::now().timestamp_millis() as f64;
+
+ // if mouse_state.coords != last_mouse_state.coords {
+ // let mouse_event = MouseEvent {
+ // active_modifiers: vec![],
+ // cursor_id: get_cursor_id(),
+ // process_time_ms: elapsed,
+ // event_type: "mouseMoved".to_string(),
+ // unix_time_ms: unix_time,
+ // x: mouse_state.coords.0 as f64,
+ // y: mouse_state.coords.1 as f64,
+ // };
+ // mouse_moves_clone.lock().unwrap().push(mouse_event);
+ // }
+
+ // if mouse_state.button_pressed[0] && !last_mouse_state.button_pressed[0] {
+ // let mouse_event = MouseEvent {
+ // active_modifiers: vec![],
+ // cursor_id: get_cursor_id(),
+ // process_time_ms: elapsed,
+ // event_type: "mouseClicked".to_string(),
+ // unix_time_ms: unix_time,
+ // x: mouse_state.coords.0 as f64,
+ // y: mouse_state.coords.1 as f64,
+ // };
+ // mouse_clicks_clone.lock().unwrap().push(mouse_event);
+ // }
+
+ // last_mouse_state = mouse_state;
+ // tokio::time::sleep(Duration::from_millis(10)).await;
+ // }
+ // });
+
+ Ok(InProgressRecording {
segments: vec![SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs_f64()],
+ pipeline,
recording_dir,
- ffmpeg_process,
- display,
- display_source: match recording_options.capture_target {
- CaptureTarget::Screen => DisplaySource::Screen,
- CaptureTarget::Window { id: window_number } => DisplaySource::Window {
- bounds: get_window_bounds(window_number).unwrap(),
- },
- },
- camera,
- audio,
- mouse_moves,
- mouse_clicks,
- stop_signal,
- }
+ display_source: recording_options.capture_target.clone(),
+ display_output_path,
+ audio_output_path,
+ camera_output_path,
+ // mouse_moves,
+ // mouse_clicks,
+ // stop_signal,
+ })
}
fn get_cursor_id() -> String {
diff --git a/apps/desktop/src/routes/(window-chrome)/index.tsx b/apps/desktop/src/routes/(window-chrome)/index.tsx
index 25e82ce76..843636195 100644
--- a/apps/desktop/src/routes/(window-chrome)/index.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/index.tsx
@@ -145,7 +145,7 @@ export default function () {
const selectedWindow = () => {
const d = options.data?.captureTarget;
- if (d?.type !== "window") return;
+ if (d?.variant !== "window") return;
return windows.data?.find((data) => data.id === d.id);
};
@@ -232,7 +232,7 @@ export default function () {
open={windowSelectOpen()}
onOpenChange={(o: boolean) => {
// prevents tab onChange from interfering with dropdown trigger click
- if (o === false && options.data?.captureTarget.type === "screen")
+ if (o === false && options.data?.captureTarget.variant === "screen")
return;
setWindowSelectOpen(o);
}}
@@ -248,25 +248,25 @@ export default function () {
if (!d || !options.data) return;
commands.setRecordingOptions({
...options.data,
- captureTarget: { type: "window", id: d.id },
+ captureTarget: { variant: "window", ...d },
});
setWindowSelectOpen(false);
}}
placement="top-end"
>
<SwitchTab
- value={options.data?.captureTarget.type}
+ value={options.data?.captureTarget.variant}
disabled={isRecording()}
onChange={(s) => {
if (!options.data) return;
- if (options.data?.captureTarget.type === s) {
+ if (options.data?.captureTarget.variant === s) {
setWindowSelectOpen(false);
return;
}
if (s === "screen") {
commands.setRecordingOptions({
...options.data,
- captureTarget: { type: "screen" },
+ captureTarget: { variant: "screen" },
});
setWindowSelectOpen(false);
} else if (s === "window") {
@@ -492,7 +492,7 @@ export default function () {
await requestPermission("microphone");
if (permissions?.data?.microphone === "granted") {
commands.setRecordingOptions({
- ...options.data,
+ ...options.data!,
audioInputName: audioDevice().name,
});
}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index eb02a2f8d..332c58523 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -366,21 +366,19 @@ export type CameraMeta = { path: string }
export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }
export type CameraXPosition = "left" | "center" | "right"
export type CameraYPosition = "top" | "bottom"
-export type CaptureTarget = { type: "screen" } | { type: "window"; id: number }
-export type CaptureWindow = { id: number; name: string }
+export type CaptureWindow = { id: number; name: string; bounds: Bounds }
export type Crop = { position: XY<number>; size: XY<number> }
export type CurrentRecordingChanged = JsonValue<InProgressRecording | null>
export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: CursorType }
export type CursorType = "pointer" | "circle"
export type Display = { path: string }
-export type DisplaySource = { variant: "screen" } | { variant: "window"; bounds: Bounds }
export type EditorStateChanged = { playhead_position: number }
export type GeneralSettingsStore = { upload_individual_files: boolean; open_editor_after_recording: boolean; hide_dock_icon?: boolean }
export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }
export type HotkeyAction = "startRecording" | "stopRecording" | "restartRecording" | "takeScreenshot"
export type HotkeysConfiguration = { show: boolean }
export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }
-export type InProgressRecording = { recordingDir: string; displaySource: DisplaySource; segments: number[] }
+export type InProgressRecording = { recordingDir: string; displaySource: ScreenCaptureTarget; segments: number[] }
export type JsonValue<T> = [T]
export type NewRecordingAdded = { path: string }
export type NewScreenshotAdded = { path: string }
@@ -392,7 +390,7 @@ export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background
export type ProjectRecordings = { display: Video; camera: Video | null; audio: Audio | null }
export type RecordingMeta = { pretty_name: string; sharing?: SharingMeta | null; display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; segments?: RecordingSegment[] }
export type RecordingMetaChanged = { id: string }
-export type RecordingOptions = { captureTarget: CaptureTarget; cameraLabel: string | null; audioInputName: string | null }
+export type RecordingOptions = { captureTarget: ScreenCaptureTarget; cameraLabel: string | null; audioInputName: string | null }
export type RecordingOptionsChanged = null
export type RecordingSegment = { start: number; end: number }
export type RecordingStarted = null
@@ -404,6 +402,7 @@ export type RequestOpenSettings = { page: string }
export type RequestRestartRecording = null
export type RequestStartRecording = null
export type RequestStopRecording = null
+export type ScreenCaptureTarget = ({ variant: "window" } & CaptureWindow) | { variant: "screen" }
export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordings; path: string }
export type SharingMeta = { id: string; link: string }
export type ShowCapturesPanel = null
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index 90793c359..5881d8071 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -21,6 +21,7 @@ scap = { path = "../../../scap" }
# scap = { git = "https://github.com/CapSoftware/scap", rev = "691bd88798d3" }
serde = { version = "1", features = ["derive"] }
specta = "=2.0.0-rc.19"
+tempfile = "3.12.0"
thiserror = "1.0"
tracing = "0.1"
diff --git a/crates/media/src/encoders/mp3.rs b/crates/media/src/encoders/mp3.rs
index 7852647ed..fcbef2324 100644
--- a/crates/media/src/encoders/mp3.rs
+++ b/crates/media/src/encoders/mp3.rs
@@ -24,7 +24,7 @@ pub struct MP3Encoder {
}
impl MP3Encoder {
- const OUTPUT_BITRATE: usize = 192 * 1000; // 192k
+ const OUTPUT_BITRATE: usize = 128 * 1000; // 128k
pub fn init(tag: &'static str, config: AudioInfo, output: Output) -> Result<Self, MediaError> {
let destination = match output {
diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs
index 9a153c30f..6565b06f8 100644
--- a/crates/media/src/lib.rs
+++ b/crates/media/src/lib.rs
@@ -10,7 +10,7 @@ pub mod data;
pub mod encoders;
pub mod filters;
pub mod pipeline;
-mod platform;
+pub mod platform;
pub mod sources;
pub fn init() -> Result<(), MediaError> {
@@ -27,6 +27,9 @@ pub enum MediaError {
#[error("Cannot build a pipeline without any tasks")]
EmptyPipeline,
+ #[error("Cannot run any further operations on a pipeline that has been shut down")]
+ ShutdownPipeline,
+
#[error("Failed to launch task: #{0}")]
TaskLaunch(String),
diff --git a/crates/media/src/pipeline/builder.rs b/crates/media/src/pipeline/builder.rs
index 429651fc1..048980395 100644
--- a/crates/media/src/pipeline/builder.rs
+++ b/crates/media/src/pipeline/builder.rs
@@ -101,6 +101,7 @@ impl<T: PipelineClock> PipelineBuilder<T> {
clock,
control,
task_handles,
+ is_shutdown: false,
})
}
}
diff --git a/crates/media/src/pipeline/clock.rs b/crates/media/src/pipeline/clock.rs
index e85952b79..d512c7145 100644
--- a/crates/media/src/pipeline/clock.rs
+++ b/crates/media/src/pipeline/clock.rs
@@ -159,7 +159,8 @@ impl PipelineClock for SynchronisedClock<()> {
if !self.running() {
let mut start_time = self.global_start_time.write().unwrap();
- *start_time = Instant::now();
+ let now = Instant::now();
+ *start_time = now;
self.set_running(true);
}
}
diff --git a/crates/media/src/pipeline/mod.rs b/crates/media/src/pipeline/mod.rs
index 975ddf107..458f3d04c 100644
--- a/crates/media/src/pipeline/mod.rs
+++ b/crates/media/src/pipeline/mod.rs
@@ -9,13 +9,14 @@ pub mod task;
use crate::MediaError;
use builder::PipelineBuilder;
-use clock::PipelineClock;
+pub use clock::*;
use control::{Control, ControlBroadcast, PipelineControlSignal};
pub struct Pipeline<T: PipelineClock> {
clock: T,
control: ControlBroadcast,
task_handles: IndexMap<String, JoinHandle<()>>,
+ is_shutdown: bool,
}
impl<T: PipelineClock> Pipeline<T> {
@@ -24,27 +25,33 @@ impl<T: PipelineClock> Pipeline<T> {
}
pub async fn play(&mut self) -> Result<(), MediaError> {
+ if self.is_shutdown {
+ return Err(MediaError::ShutdownPipeline);
+ };
+
tracing::info!("Starting pipeline execution");
self.clock.start();
self.control.broadcast(Control::Play).await
}
pub async fn pause(&mut self) -> Result<(), MediaError> {
+ if self.is_shutdown {
+ return Err(MediaError::ShutdownPipeline);
+ };
+
tracing::info!("Pausing pipeline execution");
self.clock.stop();
self.control.broadcast(Control::Pause).await
}
- pub async fn shutdown(self) -> Result<(), MediaError> {
+ pub async fn shutdown(&mut self) -> Result<(), MediaError> {
+ if self.is_shutdown {
+ return Err(MediaError::ShutdownPipeline);
+ };
+
tracing::info!("Shutting down pipeline execution");
- let Self {
- mut control,
- task_handles,
- ..
- } = self;
-
- let _ = control.broadcast(Control::Shutdown).await;
- for task in task_handles.into_values() {
+ let _ = self.control.broadcast(Control::Shutdown).await;
+ for (_name, task) in self.task_handles.drain(..) {
let _ = task.join();
}
tracing::info!("Pipeline has been stopped.");
diff --git a/crates/media/src/platform/macos.rs b/crates/media/src/platform/macos.rs
index 9a802f93d..611e37177 100644
--- a/crates/media/src/platform/macos.rs
+++ b/crates/media/src/platform/macos.rs
@@ -135,10 +135,116 @@ unsafe fn get_window_bounds(window_cf_dictionary_ref: CFDictionaryRef) -> Option
};
Bounds {
- x: rect.origin.x as u32,
- y: rect.origin.y as u32,
- width: rect.size.width as u32,
- height: rect.size.height as u32,
+ x: rect.origin.x,
+ y: rect.origin.y,
+ width: rect.size.width,
+ height: rect.size.height,
}
})
}
+
+pub fn bring_window_to_focus(window_id: u32) {
+ // TODO(PJ): Replace with Accessibility API once I remember how it works
+ use std::io::Write;
+ use std::process::Command;
+ use tempfile::NamedTempFile;
+
+ println!("Attempting to bring window {} to focus", window_id);
+
+ // Get the window information associated with the window id
+ let windows = get_on_screen_windows();
+ if let Some(window) = windows.into_iter().find(|w| w.window_id == window_id) {
+ let process_id = window.process_id;
+ let window_title = window.name.clone();
+ let bounds_x = window.bounds.x;
+ let bounds_y = window.bounds.y;
+ let bounds_width = window.bounds.width;
+ let bounds_height = window.bounds.height;
+ let should_focus = true;
+
+ // Prepare the AppleScript
+ let apple_script = r#"
+ on run argv
+ set processId to item 1 of argv as number
+ set windowTitle to item 2 of argv
+ set boundsX to item 3 of argv as number
+ set boundsY to item 4 of argv as number
+ set boundsWidth to item 5 of argv as number
+ set boundsHeight to item 6 of argv as number
+ set shouldFocus to item 7 of argv as boolean or true
+
+ log "processId: " & processId
+ log "windowTitle: " & windowTitle
+ log "boundsX: " & boundsX
+ log "boundsY: " & boundsY
+ log "boundsWidth: " & boundsWidth
+ log "boundsHeight: " & boundsHeight
+
+ tell application "System Events"
+ set appProcess to first process whose unix id is processId
+ set frontmost of appProcess to true
+
+ tell appProcess
+ set appWindowsCount to count of windows
+ log "appWindowsCount: " & appWindowsCount
+
+ if appWindowsCount is equal to 1 then
+ perform action "AXRaise" of first window
+ log "--found window--"
+ return
+ end if
+
+ repeat with checkedWindow in windows
+ tell checkedWindow
+ if title contains windowTitle and position is equal to {boundsX, boundsY} and size is equal to {boundsWidth, boundsHeight} then
+ perform action "AXRaise" of checkedWindow
+ log "--found window--"
+ exit repeat
+ end if
+ end tell
+ end repeat
+ end tell
+ end tell
+ end run
+ "#;
+
+ // Prepare arguments
+ let args = vec![
+ process_id.to_string(),
+ window_title.clone(),
+ bounds_x.to_string(),
+ bounds_y.to_string(),
+ bounds_width.to_string(),
+ bounds_height.to_string(),
+ should_focus.to_string(),
+ ];
+
+ // Write the AppleScript to a temporary file
+ let mut script_file = NamedTempFile::new().expect("Failed to create temp file");
+ script_file
+ .write_all(apple_script.as_bytes())
+ .expect("Failed to write to temp file");
+
+ // Execute the AppleScript with arguments
+ let output = Command::new("osascript")
+ .arg(script_file.path())
+ .args(&args)
+ .output();
+
+ match output {
+ Ok(output) => {
+ if output.status.success() {
+ println!("Successfully executed AppleScript");
+ } else {
+ let error_message = String::from_utf8_lossy(&output.stderr);
+ eprintln!("AppleScript execution failed: {}", error_message);
+ }
+ }
+ Err(e) => eprintln!("Failed to execute AppleScript: {}", e),
+ }
+
+ println!("Finished attempt to bring window {} to focus", window_id);
+ } else {
+ eprintln!("Window with id {} not found", window_id);
+ }
+}
diff --git a/crates/media/src/platform/mod.rs b/crates/media/src/platform/mod.rs
index a63b2d184..0e1fc4e6f 100644
--- a/crates/media/src/platform/mod.rs
+++ b/crates/media/src/platform/mod.rs
@@ -1,15 +1,18 @@
+use serde::{Deserialize, Serialize};
+use specta::Type;
+
#[cfg(target_os = "macos")]
#[path = "macos.rs"]
mod platform_impl;
pub use platform_impl::*;
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Type)]
pub struct Bounds {
- pub x: u32,
- pub y: u32,
- pub width: u32,
- pub height: u32,
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
}
#[derive(Debug)]
diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rs
index 8697e9dd2..39e5d80a2 100644
--- a/crates/media/src/sources/audio_input.rs
+++ b/crates/media/src/sources/audio_input.rs
@@ -31,7 +31,7 @@ pub struct AudioInputSource {
}
impl AudioInputSource {
- pub fn init(selected_audio_input: Option<&str>) -> Option<Self> {
+ pub fn init(selected_audio_input: Option<&String>) -> Option<Self> {
tracing::debug!("Selected audio input: {:?}", selected_audio_input);
let mut devices = Self::get_devices();
diff --git a/crates/media/src/sources/camera.rs b/crates/media/src/sources/camera.rs
index 45b0c1ceb..1a89c8bd5 100644
--- a/crates/media/src/sources/camera.rs
+++ b/crates/media/src/sources/camera.rs
@@ -21,7 +21,7 @@ pub struct CameraSource {
}
impl CameraSource {
- pub fn init(selected_camera: Option<&str>) -> Option<Self> {
+ pub fn init(selected_camera: Option<&String>) -> Option<Self> {
tracing::debug!("Selected camera: {:?}", selected_camera);
let cameras = nokhwa::query(ApiBackend::Auto).unwrap();
diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rs
index d33bf3639..6e02f21b9 100644
--- a/crates/media/src/sources/screen_capture.rs
+++ b/crates/media/src/sources/screen_capture.rs
@@ -1,15 +1,18 @@
use flume::Sender;
use scap::{
- capturer::{get_output_frame_size, Capturer, Options, Resolution},
+ capturer::{get_output_frame_size, Area, Capturer, Options, Point, Resolution, Size},
frame::{Frame, FrameType},
Target,
};
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use specta::Type;
-use std::collections::HashSet;
+use std::collections::HashMap;
-use crate::data::{FFVideo, RawVideoFormat, VideoInfo};
use crate::pipeline::{clock::*, control::Control, task::PipelineSourceTask};
+use crate::{
+ data::{FFVideo, RawVideoFormat, VideoInfo},
+ platform::{Bounds, Window},
+};
static EXCLUDED_WINDOWS: [&'static str; 4] = [
"Cap",
@@ -18,17 +21,44 @@ static EXCLUDED_WINDOWS: [&'static str; 4] = [
"Cap In Progress Recording",
];
-#[derive(Serialize, Type)]
-pub enum CaptureTarget {
- Window { id: u32, name: String },
- Screen { id: u32, name: String },
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct CaptureWindow {
+ pub id: u32,
+ pub name: String,
+ pub bounds: Bounds,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+#[serde(rename_all = "camelCase", tag = "variant")]
+pub enum ScreenCaptureTarget {
+ Window(CaptureWindow),
+ // TODO: Bring back selectable screens/multi-screen support once I figure out the UI
+ Screen,
+ // Screen {
+ // id: u32,
+ // name: String,
+ // },
}
-impl PartialEq<Target> for CaptureTarget {
+// impl Default for ScreenCaptureTarget {
+// fn default() -> Self {
+// let target = scap::targets::get_main_display();
+
+// Self::Screen {
+// id: target.id,
+// name: target.title,
+// }
+// }
+// }
+
+impl PartialEq<Target> for ScreenCaptureTarget {
fn eq(&self, other: &Target) -> bool {
match (self, other) {
- (Self::Window { id, .. }, Target::Window(window)) => window.id == *id,
- (Self::Screen { id, .. }, Target::Display(display)) => display.id == *id,
+ (Self::Window(capture_window), Target::Window(window)) => {
+ window.id == capture_window.id
+ }
+ // (Self::Screen { id, .. }, Target::Display(display)) => display.id == *id,
+ (Self::Screen, Target::Display(_)) => true,
_ => false,
}
}
@@ -44,7 +74,7 @@ impl ScreenCaptureSource {
// TODO: Settings that can be passed here to control video quality
pub fn init(
- capture_target: &CaptureTarget,
+ capture_target: &ScreenCaptureTarget,
fps: Option<u32>,
resolution: Option<Resolution>,
) -> Self {
@@ -52,12 +82,13 @@ impl ScreenCaptureSource {
let output_resolution = resolution.unwrap_or(Resolution::Captured);
let targets = scap::get_all_targets();
+ // TODO: Revert to using actual target not crop area
// warning: this will fall back to the default display if the selected capture target
// is not in the current list
- let target = targets
- .iter()
- .find(|target| capture_target.eq(target))
- .cloned();
+ // let target = targets
+ // .iter()
+ // .find(|target| capture_target.eq(target))
+ // .cloned();
let excluded_targets: Vec<scap::Target> = targets
.into_iter()
.filter(|target| match target {
@@ -70,15 +101,30 @@ impl ScreenCaptureSource {
})
.collect();
+ let crop_area = match capture_target {
+ ScreenCaptureTarget::Window(capture_window) => Some(Area {
+ size: Size {
+ width: capture_window.bounds.width,
+ height: capture_window.bounds.height,
+ },
+ origin: Point {
+ x: capture_window.bounds.x,
+ y: capture_window.bounds.y,
+ },
+ }),
+ ScreenCaptureTarget::Screen => None,
+ };
+
let options = Options {
fps,
- target,
+ // target,
show_cursor: true,
show_highlight: true,
excluded_targets: Some(excluded_targets),
output_type: FrameType::BGRAFrame,
output_resolution,
- crop_area: None,
+ crop_area,
+ ..Default::default()
};
let [frame_width, frame_height] = get_output_frame_size(&options);
@@ -89,32 +135,39 @@ impl ScreenCaptureSource {
}
}
- pub fn list_targets() -> Vec<CaptureTarget> {
+ pub fn list_targets() -> Vec<CaptureWindow> {
if !scap::has_permission() {
return vec![];
}
let targets = scap::get_all_targets();
- let valid_window_ids: HashSet<u32> = crate::platform::get_on_screen_windows()
- .iter()
- .map(|window| window.window_id)
+ let platform_windows: HashMap<u32, Window> = crate::platform::get_on_screen_windows()
+ .into_iter()
+ .map(|window| (window.window_id, window))
.collect();
targets
.into_iter()
.filter_map(|target| match target {
- Target::Window(window) => match valid_window_ids.contains(&window.id) {
- true => Some(CaptureTarget::Window {
- id: window.id,
- name: window.title,
- }),
- false => None,
- },
- Target::Display(display) => Some(CaptureTarget::Screen {
- id: display.id,
- name: display.title,
- }),
+ Target::Window(window) => {
+ platform_windows.get(&window.id).map(|platform_window| {
+ CaptureWindow {
+ id: window.id,
+ // TODO: Only include window name if application has more than one window open?
+ name: format!(
+ "{} - {}",
+ platform_window.owner_name, platform_window.name
+ ),
+ bounds: platform_window.bounds,
+ }
+ })
+ }
+ Target::Display(_) => None,
+ // Target::Display(display) => Some(ScreenCaptureTarget::Screen {
+ // id: display.id,
+ // name: display.title,
+ // }),
})
.collect()
}
@@ -138,6 +191,10 @@ impl PipelineSourceTask for ScreenCaptureSource {
) {
tracing::info!("Preparing screen capture source thread...");
+ let maybe_capture_window_id = match &self.options.target {
+ Some(Target::Window(window)) => Some(window.id),
+ _ => None,
+ };
let mut capturer = Capturer::new(self.options.clone());
let mut capturing = false;
let _ = ready_signal.send(Ok(())).unwrap();
@@ -146,6 +203,9 @@ impl PipelineSourceTask for ScreenCaptureSource {
match control_signal.last() {
Some(Control::Play) => {
if !capturing {
+ if let Some(window_id) = maybe_capture_window_id {
+ crate::platform::bring_window_to_focus(window_id);
+ }
capturer.start_capture();
capturing = true;