Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: Recording optimisations, improved performance with less frame drops
Richie McIlroy665f6c3f2d39
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lockindex 36543798a..22892c205 100644--- a/apps/desktop/src-tauri/Cargo.lock+++ b/apps/desktop/src-tauri/Cargo.lock@@ -471,13 +471,15 @@ dependencies = [name = "cap"version = "0.0.0"dependencies = [+ "capture","dotenv","ffmpeg-sidecar","image",+ "qoi","rust-s3",- "scrap","serde","serde_json",+ "shuteye","tauri","tauri-build","tauri-plugin-context-menu",@@ -485,6 +487,16 @@ dependencies = ["which",]+[[package]]+name = "capture"+version = "0.0.1"+dependencies = [+ "block",+ "cfg-if 0.1.10",+ "libc",+ "winapi 0.2.8",+]+[[package]]name = "cargo_toml"version = "0.15.3"@@ -3409,18 +3421,6 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"-[[package]]-name = "scrap"-version = "0.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "04f3e5e5b3bd8d65b04de768fe0bdbd1e2da0831be9f117e1cc1d71785c9126c"-dependencies = [- "block",- "cfg-if 0.1.10",- "libc",- "winapi 0.2.8",-]-[[package]]name = "security-framework"version = "2.9.2"@@ -3638,6 +3638,15 @@ dependencies = ["winapi 0.3.9",]+[[package]]+name = "shuteye"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ca27229f5eb21ea854a551c24b268c824949a01c41652b6d423c141539252cf"+dependencies = [+ "libc",+]+[[package]]name = "signal-hook-registry"version = "1.4.1"diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 49cce4124..8e1e18f2c 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -13,17 +13,21 @@ edition = "2021"tauri-build = { version = "1.5.0", features = [] }[dependencies]-tauri = { version = "1.5.0", features = [ "fs-write-file", "fs-remove-file", "fs-read-file", "fs-rename-file", "fs-exists", "fs-remove-dir", "fs-read-dir", "fs-copy-file", "fs-create-dir", "window-set-ignore-cursor-events", "macos-private-api", "window-unminimize", "window-minimize", "window-close", "window-show", "window-start-dragging", "window-hide", "window-unmaximize", "window-maximize", "window-set-always-on-top", "shell-open"] }+tauri = { version = "1.5.0", features = [ "window-set-position", "fs-write-file", "fs-remove-file", "fs-read-file", "fs-rename-file", "fs-exists", "fs-remove-dir", "fs-read-dir", "fs-copy-file", "fs-create-dir", "window-set-ignore-cursor-events", "macos-private-api", "window-unminimize", "window-minimize", "window-close", "window-show", "window-start-dragging", "window-hide", "window-unmaximize", "window-maximize", "window-set-always-on-top", "shell-open"] }serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"tauri-plugin-context-menu = "0.5.0"-tauri-plugin-positioner = { version = "1.0", features = ["system-tray"] }-scrap = "0.5.0"+tauri-plugin-positioner = { version = "1.0.4", features = ["system-tray"] }image = "0.24.7"ffmpeg-sidecar = "0.5.1"which = "4.2.2"rust-s3 = "0.34.0-rc3"dotenv = "0.15.0"+capture = { path = "./src/capture" }++[dev-dependencies]+shuteye = "0.3.3"+qoi = "^0.4.1"[features]# this feature is used for production builds or when `devPath` points to the filesystemdiff --git a/apps/desktop/src-tauri/src/capture/Cargo.toml b/apps/desktop/src-tauri/src/capture/Cargo.tomlnew file mode 100644index 000000000..40c4537ee--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/Cargo.toml@@ -0,0 +1,10 @@+[package]+name = "capture"+description = "Adapted version of Scrap crate."+version = "0.0.1"++[dependencies]+block = "0.1"+cfg-if = "0.1"+libc = "0.2"+winapi = "0.2"\ No newline at end of filediff --git a/apps/desktop/src-tauri/src/capture/build.rs b/apps/desktop/src-tauri/src/capture/build.rsnew file mode 100644index 000000000..04fa2aa91--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/build.rs@@ -0,0 +1,12 @@+fn main() {+ if cfg!(windows) {+ // The first choice is Windows because DXGI is amazing.+ println!("cargo:rustc-cfg=dxgi");+ } else if cfg!(target_os="macos") {+ // Quartz is second because macOS is the (annoying) exception.+ println!("cargo:rustc-cfg=quartz");+ } else if cfg!(unix) {+ // On UNIX we pray that X11 (with XCB) is available.+ println!("cargo:rustc-cfg=x11");+ }+}\ No newline at end of filediff --git a/apps/desktop/src-tauri/src/capture/src/common/dxgi.rs b/apps/desktop/src-tauri/src/capture/src/common/dxgi.rsnew file mode 100644index 000000000..12b8f9aa1--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/common/dxgi.rs@@ -0,0 +1,71 @@+use dxgi;+use std::{io, ops};+use std::io::ErrorKind::{WouldBlock, TimedOut, NotFound};++pub struct Capturer {+ inner: dxgi::Capturer,+ width: usize,+ height: usize+}++impl Capturer {+ pub fn new(display: Display) -> io::Result<Capturer> {+ let width = display.width();+ let height = display.height();+ let inner = dxgi::Capturer::new(&display.0)?;+ Ok(Capturer { inner, width, height })+ }++ pub fn width(&self) -> usize {+ self.width+ }++ pub fn height(&self) -> usize {+ self.height+ }++ pub fn frame<'a>(&'a mut self) -> io::Result<Frame<'a>> {+ const MILLISECONDS_PER_FRAME: u32 = 0;+ match self.inner.frame(MILLISECONDS_PER_FRAME) {+ Ok(frame) => Ok(Frame(frame)),+ Err(ref error) if error.kind() == TimedOut => {+ Err(WouldBlock.into())+ },+ Err(error) => Err(error)+ }+ }+}++pub struct Frame<'a>(&'a [u8]);++impl<'a> ops::Deref for Frame<'a> {+ type Target = [u8];+ fn deref(&self) -> &[u8] {+ self.0+ }+}++pub struct Display(dxgi::Display);++impl Display {+ pub fn primary() -> io::Result<Display> {+ match dxgi::Displays::new()?.next() {+ Some(inner) => Ok(Display(inner)),+ None => Err(NotFound.into())+ }+ }++ pub fn all() -> io::Result<Vec<Display>> {+ Ok(dxgi::Displays::new()?+ .map(Display)+ .collect::<Vec<_>>())+ }++ pub fn width(&self) -> usize {+ self.0.width() as usize+ }++ pub fn height(&self) -> usize {+ self.0.height() as usize+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/common/mod.rs b/apps/desktop/src-tauri/src/capture/src/common/mod.rsnew file mode 100644index 000000000..210793326--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/common/mod.rs@@ -0,0 +1,14 @@+cfg_if! {+ if #[cfg(quartz)] {+ mod quartz;+ pub use self::quartz::*;+ } else if #[cfg(x11)] {+ mod x11;+ pub use self::x11::*;+ } else if #[cfg(dxgi)] {+ mod dxgi;+ pub use self::dxgi::*;+ } else {+ //TODO: Fallback implementation.+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/common/quartz.rs b/apps/desktop/src-tauri/src/capture/src/common/quartz.rsnew file mode 100644index 000000000..8a115f831--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/common/quartz.rs@@ -0,0 +1,100 @@+use quartz;+use std::{io, ops, mem};+use std::marker::PhantomData;+use std::sync::{Arc, Mutex, TryLockError};++pub struct Capturer {+ inner: quartz::Capturer,+ frame: Arc<Mutex<Option<quartz::Frame>>>+}++impl Capturer {+ pub fn new(display: Display) -> io::Result<Capturer> {+ let frame = Arc::new(Mutex::new(None));++ let f = frame.clone();+ let inner = quartz::Capturer::new(+ display.0,+ display.width(),+ display.height(),+ quartz::PixelFormat::Argb8888,+ Default::default(),+ move |inner| {+ if let Ok(mut f) = f.lock() {+ *f = Some(inner);+ }+ }+ ).map_err(|_| io::Error::from(io::ErrorKind::Other))?;++ Ok(Capturer { inner, frame })+ }++ pub fn width(&self) -> usize {+ self.inner.width()+ }++ pub fn height(&self) -> usize {+ self.inner.height()+ }++ pub fn frame<'a>(&'a mut self) -> io::Result<Frame<'a>> {+ match self.frame.try_lock() {+ Ok(mut handle) => {+ let mut frame = None;+ mem::swap(&mut frame, &mut handle);++ match frame {+ Some(frame) =>+ Ok(Frame(frame, PhantomData)),++ None =>+ Err(io::ErrorKind::WouldBlock.into())+ }+ }++ Err(TryLockError::WouldBlock) =>+ Err(io::ErrorKind::WouldBlock.into()),++ Err(TryLockError::Poisoned(..)) =>+ Err(io::ErrorKind::Other.into())+ }+ }+}++pub struct Frame<'a>(+ quartz::Frame,+ PhantomData<&'a [u8]>+);++impl<'a> ops::Deref for Frame<'a> {+ type Target = [u8];+ fn deref(&self) -> &[u8] {+ &*self.0+ }+}++pub struct Display(quartz::Display);++impl Display {+ pub fn primary() -> io::Result<Display> {+ Ok(Display(quartz::Display::primary()))+ }++ pub fn all() -> io::Result<Vec<Display>> {+ Ok(+ quartz::Display::online()+ .map_err(|_| io::Error::from(io::ErrorKind::Other))?+ .into_iter()+ .map(Display)+ .collect()+ )+ }++ pub fn width(&self) -> usize {+ self.0.width()+ }++ pub fn height(&self) -> usize {+ self.0.height()+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/common/x11.rs b/apps/desktop/src-tauri/src/capture/src/common/x11.rsnew file mode 100644index 000000000..342a171cd--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/common/x11.rs@@ -0,0 +1,71 @@+use x11;+use std::{io, ops};+use std::rc::Rc;++pub struct Capturer(x11::Capturer);++impl Capturer {+ pub fn new(display: Display) -> io::Result<Capturer> {+ x11::Capturer::new(display.0).map(Capturer)+ }++ pub fn width(&self) -> usize {+ self.0.display().rect().w as usize+ }++ pub fn height(&self) -> usize {+ self.0.display().rect().h as usize+ }++ pub fn frame<'a>(&'a mut self) -> io::Result<Frame<'a>> {+ Ok(Frame(self.0.frame()))+ }+}++pub struct Frame<'a>(&'a [u8]);++impl<'a> ops::Deref for Frame<'a> {+ type Target = [u8];+ fn deref(&self) -> &[u8] {+ self.0+ }+}++pub struct Display(x11::Display);++impl Display {+ pub fn primary() -> io::Result<Display> {+ let server = Rc::new(match x11::Server::default() {+ Ok(server) => server,+ Err(_) => return Err(io::ErrorKind::ConnectionRefused.into())+ });++ let mut displays = x11::Server::displays(server);+ let mut best = displays.next();+ if best.as_ref().map(|x| x.is_default()) == Some(false) {+ best = displays.find(|x| x.is_default()).or(best);+ }++ match best {+ Some(best) => Ok(Display(best)),+ None => Err(io::ErrorKind::NotFound.into())+ }+ }++ pub fn all() -> io::Result<Vec<Display>> {+ let server = Rc::new(match x11::Server::default() {+ Ok(server) => server,+ Err(_) => return Err(io::ErrorKind::ConnectionRefused.into())+ });++ Ok(x11::Server::displays(server).map(Display).collect())+ }++ pub fn width(&self) -> usize {+ self.0.rect().w as usize+ }++ pub fn height(&self) -> usize {+ self.0.rect().h as usize+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/dxgi/ffi.rs b/apps/desktop/src-tauri/src/capture/src/dxgi/ffi.rsnew file mode 100644index 000000000..5bfe317d0--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/dxgi/ffi.rs@@ -0,0 +1,65 @@+use winapi::{+ GUID,+ HRESULT,+ REFIID,+ IDXGIFactory1,+ IDXGIAdapter,+ D3D_DRIVER_TYPE,+ HMODULE,+ UINT,+ ID3D11Device,+ D3D_FEATURE_LEVEL,+ ID3D11DeviceContext+};++pub const DXGI_MAP_READ: UINT = 1;++pub const IID_IDXGIFACTORY1: GUID = GUID {+ Data1: 0x770aae78,+ Data2: 0xf26f,+ Data3: 0x4dba,+ Data4: [0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87]+};++pub const IID_IDXGIOUTPUT1: GUID = GUID {+ Data1: 0x00cddea8,+ Data2: 0x939b,+ Data3: 0x4b83,+ Data4: [0xa3, 0x40, 0xa6, 0x85, 0x22, 0x66, 0x66, 0xcc]+};++pub const IID_IDXGISURFACE: GUID = GUID {+ Data1: 3405559148,+ Data2: 27331,+ Data3: 18569,+ Data4: [191, 71, 158, 35, 187, 210, 96, 236]+};++pub const IID_ID3D11TEXTURE2D: GUID = GUID {+ Data1: 1863690994,+ Data2: 53768,+ Data3: 20105,+ Data4: [154, 180, 72, 149, 53, 211, 79, 156]+};++#[link(name="dxgi")]+#[link(name="d3d11")]+extern "system" {+ pub fn CreateDXGIFactory1(+ id: REFIID,+ pp_factory: *mut *mut IDXGIFactory1+ ) -> HRESULT;++ pub fn D3D11CreateDevice(+ pAdapter: *mut IDXGIAdapter,+ DriverType: D3D_DRIVER_TYPE,+ Software: HMODULE,+ Flags: UINT,+ pFeatureLevels: *mut D3D_FEATURE_LEVEL,+ FeatureLevels: UINT,+ SDKVersion: UINT,+ ppDevice: *mut *mut ID3D11Device,+ pFeatureLevel: *mut D3D_FEATURE_LEVEL,+ ppImmediateContext: *mut *mut ID3D11DeviceContext+ ) -> HRESULT;+}diff --git a/apps/desktop/src-tauri/src/capture/src/dxgi/mod.rs b/apps/desktop/src-tauri/src/capture/src/dxgi/mod.rsnew file mode 100644index 000000000..b2ad8a116--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/dxgi/mod.rs@@ -0,0 +1,433 @@+use self::ffi::*;+use std::{io, mem, ptr, slice};+use winapi::{+ HRESULT,+ IDXGIAdapter1,+ IDXGIFactory1,+ IDXGIOutput1,+ S_OK,+ UINT,+ DXGI_OUTPUT_DESC,+ LONG,+ DXGI_MODE_ROTATION,+ ID3D11Device,+ ID3D11DeviceContext,+ IDXGIOutputDuplication,+ D3D11_SDK_VERSION,+ D3D_DRIVER_TYPE_UNKNOWN,+ D3D_FEATURE_LEVEL_9_1,+ DXGI_ERROR_ACCESS_LOST,+ DXGI_ERROR_WAIT_TIMEOUT,+ DXGI_ERROR_INVALID_CALL,+ E_ACCESSDENIED,+ DXGI_ERROR_UNSUPPORTED,+ ID3D11Texture2D,+ DXGI_ERROR_NOT_CURRENTLY_AVAILABLE,+ DXGI_ERROR_SESSION_DISCONNECTED,+ TRUE,+ IDXGISurface,+ IDXGIResource,+ DXGI_RESOURCE_PRIORITY_MAXIMUM,+ D3D11_CPU_ACCESS_READ,+ D3D11_USAGE_STAGING+};++mod ffi;++//TODO: Split up into files.++pub struct Capturer {+ device: *mut ID3D11Device,+ context: *mut ID3D11DeviceContext,+ duplication: *mut IDXGIOutputDuplication,+ fastlane: bool, surface: *mut IDXGISurface,+ data: *mut u8, len: usize,+ height: usize,+}++impl Capturer {+ pub fn new(display: &Display) -> io::Result<Capturer> {+ let mut device = ptr::null_mut();+ let mut context = ptr::null_mut();+ let mut duplication = ptr::null_mut();+ let mut desc = unsafe { mem::uninitialized() };++ if unsafe {+ D3D11CreateDevice(+ &mut **display.adapter,+ D3D_DRIVER_TYPE_UNKNOWN,+ ptr::null_mut(), // No software rasterizer.+ 0, // No device flags.+ ptr::null_mut(), // Feature levels.+ 0, // Feature levels' length.+ D3D11_SDK_VERSION,+ &mut device,+ &mut D3D_FEATURE_LEVEL_9_1,+ &mut context+ )+ } != S_OK {+ // Unknown error.+ return Err(io::ErrorKind::Other.into());+ }++ let res = wrap_hresult(unsafe {+ (*display.inner).DuplicateOutput(+ &mut **device,+ &mut duplication+ )+ });++ if let Err(err) = res {+ unsafe {+ (*device).Release();+ (*context).Release();+ }+ return Err(err);+ }++ unsafe {+ (*duplication).GetDesc(&mut desc);+ }++ Ok(unsafe {+ let mut capturer = Capturer {+ device, context, duplication,+ fastlane: desc.DesktopImageInSystemMemory == TRUE,+ surface: ptr::null_mut(),+ height: display.height() as usize,+ data: ptr::null_mut(),+ len: 0+ };+ let _ = capturer.load_frame(0);+ capturer+ })+ }++ unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<()> {+ let mut frame = ptr::null_mut();+ let mut info = mem::uninitialized();+ self.data = ptr::null_mut();++ wrap_hresult((*self.duplication).AcquireNextFrame(+ timeout,+ &mut info,+ &mut frame+ ))?;++ if self.fastlane {+ let mut rect = mem::uninitialized();+ let res = wrap_hresult(+ (*self.duplication).MapDesktopSurface(&mut rect)+ );++ (*frame).Release();++ if let Err(err) = res {+ Err(err)+ } else {+ self.data = rect.pBits;+ self.len = self.height * rect.Pitch as usize;+ Ok(())+ }+ } else {+ self.surface = ptr::null_mut();+ self.surface = self.ohgodwhat(frame)?;++ let mut rect = mem::uninitialized();+ wrap_hresult((*self.surface).Map(+ &mut rect,+ DXGI_MAP_READ+ ))?;++ self.data = rect.pBits;+ self.len = self.height * rect.Pitch as usize;+ Ok(())+ }+ }++ unsafe fn ohgodwhat(+ &mut self,+ frame: *mut IDXGIResource+ ) -> io::Result<*mut IDXGISurface> {+ let mut texture: *mut ID3D11Texture2D = ptr::null_mut();+ (*frame).QueryInterface(+ &IID_ID3D11TEXTURE2D,+ &mut texture as *mut *mut _ as *mut *mut _+ );++ let mut texture_desc = mem::uninitialized();+ (*texture).GetDesc(&mut texture_desc);++ texture_desc.Usage = D3D11_USAGE_STAGING;+ texture_desc.BindFlags = 0;+ texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0;+ texture_desc.MiscFlags = 0;++ let mut readable = ptr::null_mut();+ let res = wrap_hresult((*self.device).CreateTexture2D(+ &mut texture_desc,+ ptr::null(),+ &mut readable+ ));++ if let Err(err) = res {+ (*frame).Release();+ (*texture).Release();+ (*readable).Release();+ Err(err)+ } else {+ (*readable).SetEvictionPriority(DXGI_RESOURCE_PRIORITY_MAXIMUM);++ let mut surface = ptr::null_mut();+ (*readable).QueryInterface(+ &IID_IDXGISURFACE,+ &mut surface as *mut *mut _ as *mut *mut _+ );++ (*self.context).CopyResource(+ &mut **readable,+ &mut **texture+ );++ (*frame).Release();+ (*texture).Release();+ (*readable).Release();+ Ok(surface)+ }+ }++ pub fn frame<'a>(&'a mut self, timeout: UINT) -> io::Result<&'a [u8]> {+ unsafe {+ // Release last frame.+ // No error checking needed because we don't care.+ // None of the errors crash anyway.++ if self.fastlane {+ (*self.duplication).UnMapDesktopSurface();+ } else {+ if !self.surface.is_null() {+ (*self.surface).Unmap();+ (*self.surface).Release();+ self.surface = ptr::null_mut();+ }+ }++ (*self.duplication).ReleaseFrame();++ // Get next frame.++ self.load_frame(timeout)?;+ Ok(slice::from_raw_parts(self.data, self.len))+ }+ }+}++impl Drop for Capturer {+ fn drop(&mut self) {+ unsafe {+ if !self.surface.is_null() {+ (*self.surface).Unmap();+ (*self.surface).Release();+ }+ (*self.duplication).Release();+ (*self.device).Release();+ (*self.context).Release();+ }+ }+}++pub struct Displays {+ factory: *mut IDXGIFactory1,+ adapter: *mut IDXGIAdapter1,+ /// Index of the CURRENT adapter.+ nadapter: UINT,+ /// Index of the NEXT display to fetch.+ ndisplay: UINT+}++impl Displays {+ pub fn new() -> io::Result<Displays> {+ let mut factory = ptr::null_mut();+ wrap_hresult(unsafe {+ CreateDXGIFactory1(&IID_IDXGIFACTORY1, &mut factory)+ })?;++ let mut adapter = ptr::null_mut();+ unsafe {+ // On error, our adapter is null, so it's fine.+ (*factory).EnumAdapters1(0, &mut adapter);+ };++ Ok(Displays {+ factory,+ adapter,+ nadapter: 0,+ ndisplay: 0+ })+ }++ // No Adapter => Some(None)+ // Non-Empty Adapter => Some(Some(OUTPUT))+ // End of Adapter => None+ fn read_and_invalidate(&mut self) -> Option<Option<Display>> {+ // If there is no adapter, there is nothing left for us to do.++ if self.adapter.is_null() {+ return Some(None);+ }++ // Otherwise, we get the next output of the current adapter.++ let output = unsafe {+ let mut output = ptr::null_mut();+ (*self.adapter).EnumOutputs(self.ndisplay, &mut output);+ output+ };++ // If the current adapter is done, we free it.+ // We return None so the caller gets the next adapter and tries again.++ if output.is_null() {+ unsafe {+ (*self.adapter).Release();+ self.adapter = ptr::null_mut();+ }+ return None;+ }++ // Advance to the next display.++ self.ndisplay += 1;++ // We get the display's details.++ let desc = unsafe {+ let mut desc = mem::uninitialized();+ (*output).GetDesc(&mut desc);+ desc+ };++ // We cast it up to the version needed for desktop duplication.++ let mut inner = ptr::null_mut();+ unsafe {+ (*output).QueryInterface(+ &IID_IDXGIOUTPUT1,+ &mut inner as *mut *mut _ as *mut *mut _+ );+ (*output).Release();+ }++ // If it's null, we have an error.+ // So we act like the adapter is done.++ if inner.is_null() {+ unsafe {+ (*self.adapter).Release();+ self.adapter = ptr::null_mut();+ }+ return None;+ }++ unsafe {+ (*self.adapter).AddRef();+ }++ Some(Some(Display { inner, adapter: self.adapter, desc }))+ }+}++impl Iterator for Displays {+ type Item = Display;+ fn next(&mut self) -> Option<Display> {+ if let Some(res) = self.read_and_invalidate() {+ res+ } else {+ // We need to replace the adapter.++ self.ndisplay = 0;+ self.nadapter += 1;++ self.adapter = unsafe {+ let mut adapter = ptr::null_mut();+ (*self.factory).EnumAdapters1(+ self.nadapter,+ &mut adapter+ );+ adapter+ };++ if let Some(res) = self.read_and_invalidate() {+ res+ } else {+ // All subsequent adapters will also be empty.+ None+ }+ }+ }+}++impl Drop for Displays {+ fn drop(&mut self) {+ unsafe {+ (*self.factory).Release();+ if !self.adapter.is_null() {+ (*self.adapter).Release();+ }+ }+ }+}++pub struct Display {+ inner: *mut IDXGIOutput1,+ adapter: *mut IDXGIAdapter1,+ desc: DXGI_OUTPUT_DESC+}++impl Display {+ pub fn width(&self) -> LONG {+ self.desc.DesktopCoordinates.right -+ self.desc.DesktopCoordinates.left+ }++ pub fn height(&self) -> LONG {+ self.desc.DesktopCoordinates.bottom -+ self.desc.DesktopCoordinates.top+ }++ pub fn rotation(&self) -> DXGI_MODE_ROTATION {+ self.desc.Rotation+ }++ pub fn name(&self) -> &[u16] {+ let s = &self.desc.DeviceName;+ let i = s.iter()+ .position(|&x| x == 0)+ .unwrap_or(s.len());+ &s[..i]+ }+}++impl Drop for Display {+ fn drop(&mut self) {+ unsafe {+ (*self.inner).Release();+ (*self.adapter).Release();+ }+ }+}++fn wrap_hresult(x: HRESULT) -> io::Result<()> {+ use std::io::ErrorKind::*;+ Err((match x {+ S_OK => return Ok(()),+ DXGI_ERROR_ACCESS_LOST => ConnectionReset,+ DXGI_ERROR_WAIT_TIMEOUT => TimedOut,+ DXGI_ERROR_INVALID_CALL => InvalidData,+ E_ACCESSDENIED => PermissionDenied,+ DXGI_ERROR_UNSUPPORTED => ConnectionRefused,+ DXGI_ERROR_NOT_CURRENTLY_AVAILABLE => Interrupted,+ DXGI_ERROR_SESSION_DISCONNECTED => ConnectionAborted,+ _ => Other+ }).into())+}diff --git a/apps/desktop/src-tauri/src/capture/src/lib.rs b/apps/desktop/src-tauri/src/capture/src/lib.rsnew file mode 100644index 000000000..115c6e0f6--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/lib.rs@@ -0,0 +1,14 @@+#[macro_use]+extern crate cfg_if;+extern crate libc;++#[cfg(quartz)] extern crate block;+#[cfg(quartz)] pub mod quartz;++#[cfg(x11)] pub mod x11;++#[cfg(dxgi)] extern crate winapi;+#[cfg(dxgi)] pub mod dxgi;++mod common;+pub use common::*;\ No newline at end of filediff --git a/apps/desktop/src-tauri/src/capture/src/quartz/capturer.rs b/apps/desktop/src-tauri/src/capture/src/quartz/capturer.rsnew file mode 100644index 000000000..61330b9c1--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/quartz/capturer.rs@@ -0,0 +1,81 @@+use block::{Block, ConcreteBlock};+use libc::c_void;+use super::ffi::*;+use super::config::Config;+use super::display::Display;+use super::frame::Frame;+use std::ptr;++pub struct Capturer {+ stream: CGDisplayStreamRef,+ queue: DispatchQueue,++ width: usize,+ height: usize,+ format: PixelFormat,+ display: Display+}++impl Capturer {+ pub fn new<F: Fn(Frame) + 'static>(+ display: Display,+ width: usize,+ height: usize,+ format: PixelFormat,+ config: Config,+ handler: F+ ) -> Result<Capturer, CGError> {+ let handler: FrameAvailableHandler =+ ConcreteBlock::new(move |status, _, surface, _| {+ use self::CGDisplayStreamFrameStatus::*;+ if status == FrameComplete {+ handler(unsafe { Frame::new(surface) });+ }+ }).copy();++ let queue = unsafe {+ dispatch_queue_create(+ b"quadrupleslap.scrap\0".as_ptr() as *const i8,+ ptr::null_mut()+ )+ };++ let stream = unsafe {+ let config = config.build();+ let stream = CGDisplayStreamCreateWithDispatchQueue(+ display.id(),+ width,+ height,+ format,+ config,+ queue,+ &*handler as *const Block<_, _> as *const c_void+ );+ CFRelease(config);+ stream+ };++ match unsafe { CGDisplayStreamStart(stream) } {+ CGError::Success => Ok(Capturer {+ stream, queue, width, height, format, display+ }),+ x => Err(x)+ }+ }++ pub fn width(&self) -> usize { self.width }+ pub fn height(&self) -> usize { self.height }+ pub fn format(&self) -> PixelFormat { self.format }+ pub fn display(&self) -> Display { self.display }+}++impl Drop for Capturer {+ fn drop(&mut self) {+ unsafe {+ //TODO: Maybe it should wait until `Stopped` before releasing?+ let _ = CGDisplayStreamStop(self.stream);+ CFRelease(self.stream);+ dispatch_release(self.queue);+ }+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/config.rs b/apps/desktop/src-tauri/src/capture/src/quartz/config.rsnew file mode 100644index 000000000..76f1192dc--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/quartz/config.rs@@ -0,0 +1,73 @@+use super::ffi::*;+use libc::c_void;+use std::ptr;++//TODO: Color space, YCbCr matrix.+pub struct Config {+ /// Whether the cursor is visible.+ pub cursor: bool,+ /// Whether it should letterbox or stretch.+ pub letterbox: bool,+ /// Minimum seconds per frame.+ pub throttle: f64,+ /// How many frames are allocated.+ /// 3 is the recommended value.+ /// 8 is the maximum value.+ pub queue_length: i8+}++impl Config {+ /// Don't forget to CFRelease this!+ pub fn build(self) -> CFDictionaryRef {+ unsafe {+ let throttle = CFNumberCreate(+ ptr::null_mut(),+ CFNumberType::Float64,+ &self.throttle as *const _ as *const c_void+ );+ let queue_length = CFNumberCreate(+ ptr::null_mut(),+ CFNumberType::SInt8,+ &self.queue_length as *const _ as *const c_void+ );++ let keys: [CFStringRef; 4] = [+ kCGDisplayStreamShowCursor,+ kCGDisplayStreamPreserveAspectRatio,+ kCGDisplayStreamMinimumFrameTime,+ kCGDisplayStreamQueueDepth+ ];+ let values: [*mut c_void; 4] = [+ cfbool(self.cursor),+ cfbool(self.letterbox),+ throttle,+ queue_length+ ];++ let res = CFDictionaryCreate(+ ptr::null_mut(),+ keys.as_ptr(),+ values.as_ptr(),+ 4,+ &kCFTypeDictionaryKeyCallBacks,+ &kCFTypeDictionaryValueCallBacks+ );++ CFRelease(throttle);+ CFRelease(queue_length);++ res+ }+ }+}++impl Default for Config {+ fn default() -> Config {+ Config {+ cursor: true,+ letterbox: true,+ throttle: 0.0166,+ queue_length: 1+ }+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/display.rs b/apps/desktop/src-tauri/src/capture/src/quartz/display.rsnew file mode 100644index 000000000..5944f5a94--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/quartz/display.rs@@ -0,0 +1,58 @@+use super::ffi::*;+use std::mem;++#[derive(PartialEq, Eq, Debug, Clone, Copy)]+#[repr(C)]+pub struct Display(u32);++impl Display {+ pub fn primary() -> Display {+ Display(unsafe { CGMainDisplayID() })+ }++ pub fn online() -> Result<Vec<Display>, CGError> {+ unsafe {+ let mut arr: [u32; 16] = mem::uninitialized();+ let mut len: u32 = 0;++ match CGGetOnlineDisplayList(16, arr.as_mut_ptr(), &mut len) {+ CGError::Success => (),+ x => return Err(x)+ }++ let mut res = Vec::with_capacity(16);+ for i in 0..len as usize {+ res.push(Display(*arr.get_unchecked(i)));+ }+ Ok(res)+ }+ }++ pub fn id(self) -> u32 {+ self.0+ }++ pub fn width(self) -> usize {+ unsafe { CGDisplayPixelsWide(self.0) }+ }++ pub fn height(self) -> usize {+ unsafe { CGDisplayPixelsHigh(self.0) }+ }++ pub fn is_builtin(self) -> bool {+ unsafe { CGDisplayIsBuiltin(self.0) != 0 }+ }++ pub fn is_primary(self) -> bool {+ unsafe { CGDisplayIsMain(self.0) != 0 }+ }++ pub fn is_active(self) -> bool {+ unsafe { CGDisplayIsActive(self.0) != 0 }+ }++ pub fn is_online(self) -> bool {+ unsafe { CGDisplayIsOnline(self.0) != 0 }+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/ffi.rs b/apps/desktop/src-tauri/src/capture/src/quartz/ffi.rsnew file mode 100644index 000000000..7653fec39--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/quartz/ffi.rs@@ -0,0 +1,228 @@+#![allow(dead_code)]++use block::RcBlock;+use libc::c_void;++pub type CGDisplayStreamRef = *mut c_void;+pub type CFDictionaryRef = *mut c_void;+pub type CFBooleanRef = *mut c_void;+pub type CFNumberRef = *mut c_void;+pub type CFStringRef = *mut c_void;+pub type CGDisplayStreamUpdateRef = *mut c_void;+pub type IOSurfaceRef = *mut c_void;+pub type DispatchQueue = *mut c_void;+pub type DispatchQueueAttr = *mut c_void;+pub type CFAllocatorRef = *mut c_void;++#[repr(C)]+pub struct CFDictionaryKeyCallBacks {+ callbacks: [usize; 5],+ version: i32+}++#[repr(C)]+pub struct CFDictionaryValueCallBacks {+ callbacks: [usize; 4],+ version: i32+}++macro_rules! pixel_format {+ ($a:expr, $b:expr, $c:expr, $d:expr) => {+ ($a as i32) << 24+ | ($b as i32) << 16+ | ($c as i32) << 8+ | ($d as i32)+ }+}++pub const SURFACE_LOCK_READ_ONLY: u32 = 0x0000_0001;+pub const SURFACE_LOCK_AVOID_SYNC: u32 = 0x0000_0002;++pub fn cfbool(x: bool) -> CFBooleanRef {+ unsafe {+ if x { kCFBooleanTrue } else { kCFBooleanFalse }+ }+}++#[repr(i32)]+#[derive(PartialEq, Eq, Debug, Clone, Copy)]+pub enum CGDisplayStreamFrameStatus {+ /// A new frame was generated.+ FrameComplete = 0,+ /// A new frame was not generated because the display did not change.+ FrameIdle = 1,+ /// A new frame was not generated because the display has gone blank.+ FrameBlank = 2,+ /// The display stream was stopped.+ Stopped = 3,+ #[doc(hidden)]+ __Nonexhaustive+}++#[repr(i32)]+#[derive(PartialEq, Eq, Debug, Clone, Copy)]+pub enum CFNumberType {+ /* Fixed-width types */+ SInt8 = 1,+ SInt16 = 2,+ SInt32 = 3,+ SInt64 = 4,+ Float32 = 5,+ Float64 = 6, /* 64-bit IEEE 754 */+ /* Basic C types */+ Char = 7,+ Short = 8,+ Int = 9,+ Long = 10,+ LongLong = 11,+ Float = 12,+ Double = 13,+ /* Other */+ CFIndex = 14,+ NSInteger = 15,+ CGFloat = 16+}++#[repr(i32)]+#[derive(PartialEq, Eq, Debug, Clone, Copy)]+#[must_use]+pub enum CGError {+ Success = 0,+ Failure = 1000,+ IllegalArgument = 1001,+ InvalidConnection = 1002,+ InvalidContext = 1003,+ CannotComplete = 1004,+ NotImplemented = 1006,+ RangeCheck = 1007,+ TypeCheck = 1008,+ InvalidOperation = 1010,+ NoneAvailable = 1011,+ #[doc(hidden)]+ __Nonexhaustive+}++#[repr(i32)]+#[derive(PartialEq, Eq, Debug, Clone, Copy)]+pub enum PixelFormat {+ /// Packed Little Endian ARGB8888+ Argb8888 = pixel_format!('B','G','R','A'),+ /// Packed Little Endian ARGB2101010+ Argb2101010 = pixel_format!('l','1','0','r'),+ /// 2-plane "video" range YCbCr 4:2:0+ YCbCr420Video = pixel_format!('4','2','0','v'),+ /// 2-plane "full" range YCbCr 4:2:0+ YCbCr420Full = pixel_format!('4','2','0','f'),+ #[doc(hidden)]+ __Nonexhaustive+}++pub type CGDisplayStreamFrameAvailableHandler = *const c_void;++pub type FrameAvailableHandler = RcBlock<(+ CGDisplayStreamFrameStatus, // status+ u64, // displayTime+ IOSurfaceRef, // frameSurface+ CGDisplayStreamUpdateRef // updateRef+), ()>;++#[link(name="System", kind="dylib")]+#[link(name="CoreGraphics", kind="framework")]+#[link(name="CoreFoundation", kind="framework")]+#[link(name="IOSurface", kind="framework")]+extern {+ // CoreGraphics++ pub static kCGDisplayStreamShowCursor: CFStringRef;+ pub static kCGDisplayStreamPreserveAspectRatio: CFStringRef;+ pub static kCGDisplayStreamMinimumFrameTime: CFStringRef;+ pub static kCGDisplayStreamQueueDepth: CFStringRef;++ pub fn CGDisplayStreamCreateWithDispatchQueue(+ display: u32,+ output_width: usize,+ output_height: usize,+ pixel_format: PixelFormat,+ properties: CFDictionaryRef,+ queue: DispatchQueue,+ handler: CGDisplayStreamFrameAvailableHandler+ ) -> CGDisplayStreamRef;++ pub fn CGDisplayStreamStart(+ displayStream: CGDisplayStreamRef+ ) -> CGError;++ pub fn CGDisplayStreamStop(+ displayStream: CGDisplayStreamRef+ ) -> CGError;++ pub fn CGMainDisplayID() -> u32;+ pub fn CGDisplayPixelsWide(display: u32) -> usize;+ pub fn CGDisplayPixelsHigh(display: u32) -> usize;++ pub fn CGGetOnlineDisplayList(+ max_displays: u32,+ online_displays: *mut u32,+ display_count: *mut u32+ ) -> CGError;++ pub fn CGDisplayIsBuiltin(display: u32) -> i32;+ pub fn CGDisplayIsMain(display: u32) -> i32;+ pub fn CGDisplayIsActive(display: u32) -> i32;+ pub fn CGDisplayIsOnline(display: u32) -> i32;++ // IOSurface++ pub fn IOSurfaceGetAllocSize(buffer: IOSurfaceRef) -> usize;+ pub fn IOSurfaceGetBaseAddress(buffer: IOSurfaceRef) -> *mut c_void;+ pub fn IOSurfaceIncrementUseCount(buffer: IOSurfaceRef);+ pub fn IOSurfaceDecrementUseCount(buffer: IOSurfaceRef);+ pub fn IOSurfaceLock(+ buffer: IOSurfaceRef,+ options: u32,+ seed: *mut u32+ ) -> i32;+ pub fn IOSurfaceUnlock(+ buffer: IOSurfaceRef,+ options: u32,+ seed: *mut u32+ ) -> i32;++ // Dispatch++ pub fn dispatch_queue_create(+ label: *const i8,+ attr: DispatchQueueAttr+ ) -> DispatchQueue;++ pub fn dispatch_release(+ object: DispatchQueue+ );++ // Core Foundation++ pub static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks;+ pub static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks;++ // EVEN THE BOOLEANS ARE REFERENCES.+ pub static kCFBooleanTrue: CFBooleanRef;+ pub static kCFBooleanFalse: CFBooleanRef;++ pub fn CFNumberCreate(+ allocator: CFAllocatorRef,+ theType: CFNumberType,+ valuePtr: *const c_void+ ) -> CFNumberRef;++ pub fn CFDictionaryCreate(+ allocator: CFAllocatorRef,+ keys: *const *mut c_void,+ values: *const *mut c_void,+ numValues: i64,+ keyCallBacks: *const CFDictionaryKeyCallBacks,+ valueCallBacks: *const CFDictionaryValueCallBacks+ ) -> CFDictionaryRef;++ pub fn CFRetain(cf: *const c_void);+ pub fn CFRelease(cf: *const c_void);+}diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/frame.rs b/apps/desktop/src-tauri/src/capture/src/quartz/frame.rsnew file mode 100644index 000000000..3b6b0496d--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/quartz/frame.rs@@ -0,0 +1,49 @@+use super::ffi::*;+use std::{ops, ptr, slice};++pub struct Frame {+ surface: IOSurfaceRef,+ inner: &'static [u8]+}++impl Frame {+ pub unsafe fn new(surface: IOSurfaceRef) -> Frame {+ CFRetain(surface);+ IOSurfaceIncrementUseCount(surface);++ IOSurfaceLock(+ surface,+ SURFACE_LOCK_READ_ONLY,+ ptr::null_mut()+ );++ let inner = slice::from_raw_parts(+ IOSurfaceGetBaseAddress(surface) as *const u8,+ IOSurfaceGetAllocSize(surface)+ );++ Frame { surface, inner }+ }+}++impl ops::Deref for Frame {+ type Target = [u8];+ fn deref<'a>(&'a self) -> &'a [u8] {+ self.inner+ }+}++impl Drop for Frame {+ fn drop(&mut self) {+ unsafe {+ IOSurfaceUnlock(+ self.surface,+ SURFACE_LOCK_READ_ONLY,+ ptr::null_mut()+ );++ IOSurfaceDecrementUseCount(self.surface);+ CFRelease(self.surface);+ }+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/quartz/mod.rs b/apps/desktop/src-tauri/src/capture/src/quartz/mod.rsnew file mode 100644index 000000000..fce89e3b3--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/quartz/mod.rs@@ -0,0 +1,11 @@+mod capturer;+mod config;+mod display;+mod ffi;+mod frame;++pub use self::capturer::Capturer;+pub use self::config::Config;+pub use self::display::Display;+pub use self::ffi::{CGError, PixelFormat};+pub use self::frame::Frame;diff --git a/apps/desktop/src-tauri/src/capture/src/x11/capturer.rs b/apps/desktop/src-tauri/src/capture/src/x11/capturer.rsnew file mode 100644index 000000000..7f3f3ad57--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/x11/capturer.rs@@ -0,0 +1,160 @@+use libc;+use std::{io, ptr, slice};+use super::Display;+use super::ffi::*;++pub struct Capturer {+ display: Display,+ shmid: i32,+ xcbid: u32,+ buffer: *const u8,++ request: xcb_shm_get_image_cookie_t,+ loading: usize,+ size: usize+}++impl Capturer {+ pub fn new(+ display: Display+ ) -> io::Result<Capturer> {+ // Calculate dimensions.++ let pixel_width = 4;+ let rect = display.rect();+ let size = (rect.w as usize) * (rect.h as usize) * pixel_width;++ // Create a shared memory segment.++ let shmid = unsafe {+ libc::shmget(+ libc::IPC_PRIVATE,+ size * 2,+ // Everyone can do anything.+ libc::IPC_CREAT | 0o777+ )+ };++ if shmid == -1 {+ return Err(io::Error::last_os_error());+ }++ // Attach the segment to a readable address.++ let buffer = unsafe {+ libc::shmat(+ shmid,+ ptr::null(),+ libc::SHM_RDONLY+ )+ } as *mut u8;++ if buffer as isize == -1 {+ return Err(io::Error::last_os_error());+ }++ // Attach the segment to XCB.++ let server = display.server().raw();+ let xcbid = unsafe { xcb_generate_id(server) };+ unsafe {+ xcb_shm_attach(+ server,+ xcbid,+ shmid as u32,+ 0 // False, i.e. not read-only.+ );+ }++ // Start the first screenshot early.++ let request = unsafe {+ xcb_shm_get_image_unchecked(+ server,+ display.root(),+ rect.x, rect.y,+ rect.w, rect.h,+ !0, // Plane mask.+ XCB_IMAGE_FORMAT_Z_PIXMAP,+ xcbid,+ 0 // Byte offset.+ )+ };++ // Return!++ Ok(Capturer {+ display, shmid, xcbid, buffer,+ request, loading: 0, size+ })+ }++ pub fn display(&self) -> &Display {+ &self.display+ }++ pub fn frame<'b>(&'b mut self) -> &'b [u8] {+ // Get the return value.++ let result = unsafe {+ let off = self.loading & self.size;+ slice::from_raw_parts(+ self.buffer.offset(off as isize),+ self.size+ )+ };++ // Block for response.++ unsafe {+ self.handle_response();+ }++ // Start next request.++ let rect = self.display.rect();++ self.loading ^= !0;+ self.request = unsafe {+ xcb_shm_get_image_unchecked(+ self.display.server().raw(),+ self.display.root(),+ rect.x, rect.y,+ rect.w, rect.h,+ !0,+ XCB_IMAGE_FORMAT_Z_PIXMAP,+ self.xcbid,+ (self.loading & self.size) as u32+ )+ };++ // Return!++ result+ }++ unsafe fn handle_response(&self) {+ let response = xcb_shm_get_image_reply(+ self.display.server().raw(),+ self.request,+ ptr::null_mut()+ );++ libc::free(response as *mut _);+ }+}++impl Drop for Capturer {+ fn drop(&mut self) {+ unsafe {+ // Process pending request.+ self.handle_response();+ // Detach segment from XCB.+ xcb_shm_detach(self.display.server().raw(), self.xcbid);+ // Detach segment from our space.+ libc::shmdt(self.buffer as *mut _);+ // Destroy the shared memory segment.+ libc::shmctl(self.shmid, libc::IPC_RMID, ptr::null_mut());+ }+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/x11/display.rs b/apps/desktop/src-tauri/src/capture/src/x11/display.rsnew file mode 100644index 000000000..e71a6df1f--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/x11/display.rs@@ -0,0 +1,35 @@+use std::rc::Rc;+use super::Server;+use super::ffi::*;++#[derive(Debug)]+pub struct Display {+ server: Rc<Server>,+ default: bool,+ rect: Rect,+ root: xcb_window_t,+}++#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]+pub struct Rect {+ pub x: i16,+ pub y: i16,+ pub w: u16,+ pub h: u16,+}++impl Display {+ pub unsafe fn new(+ server: Rc<Server>,+ default: bool,+ rect: Rect,+ root: xcb_window_t+ ) -> Display {+ Display { server, default, rect, root }+ }++ pub fn server(&self) -> &Rc<Server> { &self.server }+ pub fn is_default(&self) -> bool { self.default }+ pub fn rect(&self) -> Rect { self.rect }+ pub fn root(&self) -> xcb_window_t { self.root }+}diff --git a/apps/desktop/src-tauri/src/capture/src/x11/ffi.rs b/apps/desktop/src-tauri/src/capture/src/x11/ffi.rsnew file mode 100644index 000000000..6e31cbf0a--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/x11/ffi.rs@@ -0,0 +1,225 @@+#![allow(non_camel_case_types)]++use libc::c_void;++#[link(name="xcb")]+#[link(name="xcb-shm")]+#[link(name="xcb-randr")]+extern {+ pub fn xcb_connect(+ displayname: *const i8,+ screenp: *mut i32+ ) -> *mut xcb_connection_t;++ pub fn xcb_disconnect(+ c: *mut xcb_connection_t+ );++ pub fn xcb_connection_has_error(+ c: *mut xcb_connection_t+ ) -> i32;++ pub fn xcb_get_setup(+ c: *mut xcb_connection_t+ ) -> *const xcb_setup_t;++ pub fn xcb_setup_roots_iterator(+ r: *const xcb_setup_t+ ) -> xcb_screen_iterator_t;++ pub fn xcb_screen_next(+ i: *mut xcb_screen_iterator_t+ );++ pub fn xcb_generate_id(+ c: *mut xcb_connection_t+ ) -> u32;++ pub fn xcb_shm_attach(+ c: *mut xcb_connection_t,+ shmseg: xcb_shm_seg_t,+ shmid: u32,+ read_only: u8+ ) -> xcb_void_cookie_t;++ pub fn xcb_shm_detach(+ c: *mut xcb_connection_t,+ shmseg: xcb_shm_seg_t+ ) -> xcb_void_cookie_t;++ pub fn xcb_shm_get_image_unchecked(+ c: *mut xcb_connection_t,+ drawable: xcb_drawable_t,+ x: i16,+ y: i16,+ width: u16,+ height: u16,+ plane_mask: u32,+ format: u8,+ shmseg: xcb_shm_seg_t,+ offset: u32+ ) -> xcb_shm_get_image_cookie_t;++ pub fn xcb_shm_get_image_reply(+ c: *mut xcb_connection_t,+ cookie: xcb_shm_get_image_cookie_t,+ e: *mut *mut xcb_generic_error_t+ ) -> *mut xcb_shm_get_image_reply_t;++ pub fn xcb_randr_get_monitors_unchecked(+ c: *mut xcb_connection_t,+ window: xcb_window_t,+ get_active: u8,+ ) -> xcb_randr_get_monitors_cookie_t;++ pub fn xcb_randr_get_monitors_reply(+ c: *mut xcb_connection_t,+ cookie: xcb_randr_get_monitors_cookie_t,+ e: *mut *mut xcb_generic_error_t,+ ) -> *mut xcb_randr_get_monitors_reply_t;++ pub fn xcb_randr_get_monitors_monitors_iterator(+ r: *const xcb_randr_get_monitors_reply_t,+ ) -> xcb_randr_monitor_info_iterator_t;++ pub fn xcb_randr_monitor_info_next(+ i: *mut xcb_randr_monitor_info_iterator_t,+ );+}++pub const XCB_IMAGE_FORMAT_Z_PIXMAP: u8 = 2;++pub type xcb_atom_t = u32;+pub type xcb_connection_t = c_void;+pub type xcb_window_t = u32;+pub type xcb_keycode_t = u8;+pub type xcb_visualid_t = u32;+pub type xcb_timestamp_t = u32;+pub type xcb_colormap_t = u32;+pub type xcb_shm_seg_t = u32;+pub type xcb_drawable_t = u32;++#[repr(C)]+pub struct xcb_setup_t {+ pub status: u8,+ pub pad0: u8,+ pub protocol_major_version: u16,+ pub protocol_minor_version: u16,+ pub length: u16,+ pub release_number: u32,+ pub resource_id_base: u32,+ pub resource_id_mask: u32,+ pub motion_buffer_size: u32,+ pub vendor_len: u16,+ pub maximum_request_length: u16,+ pub roots_len: u8,+ pub pixmap_formats_len: u8,+ pub image_byte_order: u8,+ pub bitmap_format_bit_order: u8,+ pub bitmap_format_scanline_unit: u8,+ pub bitmap_format_scanline_pad: u8,+ pub min_keycode: xcb_keycode_t,+ pub max_keycode: xcb_keycode_t,+ pub pad1: [u8; 4]+}++#[repr(C)]+pub struct xcb_screen_iterator_t {+ pub data: *mut xcb_screen_t,+ pub rem: i32,+ pub index: i32+}++#[repr(C)]+pub struct xcb_screen_t {+ pub root: xcb_window_t,+ pub default_colormap: xcb_colormap_t,+ pub white_pixel: u32,+ pub black_pixel: u32,+ pub current_input_masks: u32,+ pub width_in_pixels: u16,+ pub height_in_pixels: u16,+ pub width_in_millimeters: u16,+ pub height_in_millimeters: u16,+ pub min_installed_maps: u16,+ pub max_installed_maps: u16,+ pub root_visual: xcb_visualid_t,+ pub backing_stores: u8,+ pub save_unders: u8,+ pub root_depth: u8,+ pub allowed_depths_len: u8+}++#[repr(C)]+pub struct xcb_randr_monitor_info_iterator_t {+ pub data: *mut xcb_randr_monitor_info_t,+ pub rem: i32,+ pub index: i32,+}++#[repr(C)]+pub struct xcb_randr_monitor_info_t {+ pub name: xcb_atom_t,+ pub primary: u8,+ pub automatic: u8,+ pub n_output: u16,+ pub x: i16,+ pub y: i16,+ pub width: u16,+ pub height: u16,+ pub width_mm: u32,+ pub height_mm: u32,+}++#[repr(C)]+#[derive(Clone, Copy)]+pub struct xcb_randr_get_monitors_cookie_t {+ pub sequence: u32+}++#[repr(C)]+#[derive(Clone, Copy)]+pub struct xcb_shm_get_image_cookie_t {+ pub sequence: u32+}++#[repr(C)]+#[derive(Clone, Copy)]+pub struct xcb_void_cookie_t {+ pub sequence: u32+}++#[repr(C)]+pub struct xcb_generic_error_t {+ pub response_type: u8,+ pub error_code: u8,+ pub sequence: u16,+ pub resource_id: u32,+ pub minor_code: u16,+ pub major_code: u8,+ pub pad0: u8,+ pub pad: [u32; 5],+ pub full_sequence: u32+}++#[repr(C)]+pub struct xcb_shm_get_image_reply_t {+ pub response_type: u8,+ pub depth: u8,+ pub sequence: u16,+ pub length: u32,+ pub visual: xcb_visualid_t,+ pub size: u32+}++#[repr(C)]+pub struct xcb_randr_get_monitors_reply_t {+ pub response_type: u8,+ pub pad0: u8,+ pub sequence: u16,+ pub length: u32,+ pub timestamp: xcb_timestamp_t,+ pub n_monitors: u32,+ pub n_outputs: u32,+ pub pad1: [u8; 12],+}diff --git a/apps/desktop/src-tauri/src/capture/src/x11/iter.rs b/apps/desktop/src-tauri/src/capture/src/x11/iter.rsnew file mode 100644index 000000000..f705294bd--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/x11/iter.rs@@ -0,0 +1,89 @@+use libc;+use std::ptr;+use std::rc::Rc;+use super::{Display, Rect, Server};+use super::ffi::*;++//TODO: Do I have to free the displays?++pub struct DisplayIter {+ outer: xcb_screen_iterator_t,+ inner: Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)>,+ server: Rc<Server>,+}++impl DisplayIter {+ pub unsafe fn new(server: Rc<Server>) -> DisplayIter {+ let mut outer = xcb_setup_roots_iterator(server.setup());+ let inner = Self::next_screen(&mut outer, &server);+ DisplayIter { outer, inner, server }+ }++ fn next_screen(+ outer: &mut xcb_screen_iterator_t,+ server: &Server+ ) -> Option<(xcb_randr_monitor_info_iterator_t, xcb_window_t)> {+ if outer.rem == 0 {+ return None;+ }++ unsafe {+ let root = (*outer.data).root;++ let cookie = xcb_randr_get_monitors_unchecked(+ server.raw(),+ root,+ 1, //TODO: I don't know if this should be true or false.+ );++ let response = xcb_randr_get_monitors_reply(+ server.raw(),+ cookie,+ ptr::null_mut(),+ );++ let inner = xcb_randr_get_monitors_monitors_iterator(response);++ libc::free(response as *mut _);+ xcb_screen_next(outer);++ Some((inner, root))+ }+ }+}++impl Iterator for DisplayIter {+ type Item = Display;++ fn next(&mut self) -> Option<Display> {+ loop {+ if let Some((ref mut inner, root)) = self.inner {+ // If there is something in the current screen, return that.+ if inner.rem != 0 {unsafe {+ let data = &*inner.data;++ let display = Display::new(+ self.server.clone(),+ data.primary != 0,+ Rect {+ x: data.x,+ y: data.y,+ w: data.width,+ h: data.height,+ },+ root+ );++ xcb_randr_monitor_info_next(inner);+ return Some(display);+ }}+ } else {+ // If there is no current screen, the screen iterator is empty.+ return None;+ }++ // The current screen was empty, so try the next screen.+ self.inner = Self::next_screen(&mut self.outer, &self.server);+ }+ }+}diff --git a/apps/desktop/src-tauri/src/capture/src/x11/mod.rs b/apps/desktop/src-tauri/src/capture/src/x11/mod.rsnew file mode 100644index 000000000..600027f65--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/x11/mod.rs@@ -0,0 +1,10 @@+mod capturer;+mod display;+mod ffi;+mod iter;+mod server;++pub use self::capturer::*;+pub use self::display::*;+pub use self::iter::*;+pub use self::server::*;diff --git a/apps/desktop/src-tauri/src/capture/src/x11/server.rs b/apps/desktop/src-tauri/src/capture/src/x11/server.rsnew file mode 100644index 000000000..16461a646--- /dev/null+++ b/apps/desktop/src-tauri/src/capture/src/x11/server.rs@@ -0,0 +1,75 @@+use std::ptr;+use std::rc::Rc;+use super::DisplayIter;+use super::ffi::*;++#[derive(Debug)]+pub struct Server {+ raw: *mut xcb_connection_t,+ screenp: i32,+ setup: *const xcb_setup_t+}++impl Server {+ pub fn displays(slf: Rc<Server>) -> DisplayIter {+ unsafe {+ DisplayIter::new(slf)+ }+ }++ pub fn default() -> Result<Server, Error> {+ Server::connect(ptr::null())+ }++ pub fn connect(addr: *const i8) -> Result<Server, Error> {+ unsafe {+ let mut screenp = 0;+ let raw = xcb_connect(addr, &mut screenp);++ let error = xcb_connection_has_error(raw);+ if error != 0 {+ xcb_disconnect(raw);+ Err(Error::from(error))+ } else {+ let setup = xcb_get_setup(raw);+ Ok(Server { raw, screenp, setup })+ }+ }+ }++ pub fn raw(&self) -> *mut xcb_connection_t { self.raw }+ pub fn screenp(&self) -> i32 { self.screenp }+ pub fn setup(&self) -> *const xcb_setup_t { self.setup }+}++impl Drop for Server {+ fn drop(&mut self) {+ unsafe {+ xcb_disconnect(self.raw);+ }+ }+}++#[derive(Clone, Copy, Debug)]+pub enum Error {+ Generic,+ UnsupportedExtension,+ InsufficientMemory,+ RequestTooLong,+ ParseError,+ InvalidScreen+}++impl From<i32> for Error {+ fn from(x: i32) -> Error {+ use self::Error::*;+ match x {+ 2 => UnsupportedExtension,+ 3 => InsufficientMemory,+ 4 => RequestTooLong,+ 5 => ParseError,+ 6 => InvalidScreen,+ _ => Generic+ }+ }+}diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex eae5a47ca..3bce94aa5 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -8,6 +8,7 @@ use s3::creds::Credentials;use s3::region::Region;use s3::error::S3Error;use tauri::{Manager, Window};+use tauri_plugin_positioner::{WindowExt, Position};use ffmpeg_sidecar::{command::ffmpeg_is_installed,@@ -32,7 +33,6 @@ fn start_screen_recording(window: Window, recorder: tauri::State<'_, Arc<Mutex<S});}-#[tauri::command]fn stop_screen_recording(recorder: tauri::State<'_, Arc<Mutex<ScreenRecorder>>>) {let recorder = recorder.lock().expect("Failed to lock recorder.");@@ -133,6 +133,7 @@ fn main() {}tauri::Builder::default()+ .plugin(tauri_plugin_positioner::init()).setup(|app| {tauri::async_runtime::block_on(async {if let Err(e) = setup_s3_client().await {@@ -154,6 +155,15 @@ fn main() {let shared_recorder = Arc::new(Mutex::new(recorder));app.manage(shared_recorder);++ if let Some(camera_window) = app.get_window("camera") {+ let _ = camera_window.move_window(Position::BottomRight);+ }++ if let Some(options_window) = app.get_window("options") {+ let _ = options_window.move_window(Position::Center);+ }+Ok(())}).invoke_handler(tauri::generate_handler![diff --git a/apps/desktop/src-tauri/src/recorder.rs b/apps/desktop/src-tauri/src/recorder.rsindex 6fc9e3d34..1edbe09e8 100644--- a/apps/desktop/src-tauri/src/recorder.rs+++ b/apps/desktop/src-tauri/src/recorder.rs@@ -1,5 +1,5 @@use std::io::{ErrorKind::WouldBlock, Write};-use std::process::{Command, Stdio};+use std::process::{Command};use std::sync::{Arc, Mutex};use std::thread;use std::time::{Duration, Instant};@@ -7,7 +7,7 @@ use std::path::{PathBuf, Path};use std::fs;use std::fs::File;use std::sync::atomic::{AtomicBool, Ordering};-use scrap::{Capturer, Display};+use capture::{Capturer, Display};#[derive(Clone, PartialEq)]pub enum RecordingState {@@ -46,7 +46,7 @@ impl ScreenRecorder {let (w, h) = (display.width(), display.height());let adjusted_height = h & !1;let capture_size = w * adjusted_height * BYTES_PER_PIXEL;- let framerate = 30;+ let framerate = 60;// Check current recording statelet mut state_guard = state.lock().map_err(|_| "Failed to acquire state lock".to_string())?;@@ -68,69 +68,71 @@ impl ScreenRecorder {}let output_path_str = output_path.to_str().ok_or_else(|| "Failed to construct output file path string".to_string())?.to_owned();- // Spawn the recording thread- let ffmpeg_handle = thread::spawn(move || {- // Start the capture session and open the temporary file+ let ffmpeg_handle = thread::spawn(move || {let mut capturer = Capturer::new(display).expect("Failed to start capture");- let mut raw_file = File::create(&tmp_file_path)- .map_err(|e| format!("Failed to create temporary raw file: {}", e))?;-+ let (sender, receiver) = std::sync::mpsc::channel::<Vec<u8>>();let frame_duration = Duration::from_secs_f64(1.0 / framerate as f64);-- loop {- // Start timing the frame capture- let frame_start = Instant::now();-- // Stop the loop if the recording is set to be stopped- if should_stop.load(Ordering::SeqCst) {- break;- }- // Capture a frame, handling potential errors- let buffer = match capturer.frame() {- Ok(buffer) => buffer,+ let write_handle = {+ let tmp_file_path = tmp_file_path.clone();+ let buffer_size = 100;+ let mut buffer = Vec::new();+ thread::spawn(move || {+ let mut raw_file = File::create(&tmp_file_path).expect("Failed to create temporary raw file");+ for data in receiver {+ buffer.push(data);+ if buffer.len() >= buffer_size {+ for frame_data in buffer.drain(..) {+ raw_file.write_all(&frame_data).expect("Failed to write frame data to file");+ }+ }+ }+ // Write any remaining frames in the buffer+ for frame_data in buffer {+ raw_file.write_all(&frame_data).expect("Failed to write frame data to file");+ }+ })+ };++ // Capture loop+ while !should_stop.load(Ordering::SeqCst) {+ let time_started = Instant::now();+ let frame = match capturer.frame() {+ Ok(frame) => frame,Err(error) if error.kind() == WouldBlock => {- // If capturing would block, wait a bit and retry- thread::sleep(Duration::from_micros(100));continue;},- Err(e) => return Err(format!("Error capturing frame: {}", e)),+ Err(error) => return Err(format!("Capture error: {}", error)),};-- let stride = buffer[..capture_size].len() / adjusted_height;-++ let stride = frame[..capture_size].len() / adjusted_height;+ let mut frame_data = Vec::with_capacity(capture_size);for row in 0..adjusted_height {let start = row * stride;let end = start + stride;- if let Err(e) = raw_file.write_all(&buffer[start..end]) {- eprintln!("Failed to write frame: {:?}", e);- *state.lock().unwrap() = RecordingState::Stopping;- break;- }+ frame_data.extend_from_slice(&frame[start..end]);}- // Calculate the time to sleep to maintain the target framerate- let elapsed_time = frame_start.elapsed();- if let Some(remaining_sleep_duration) = frame_duration.checked_sub(elapsed_time) {- thread::sleep(remaining_sleep_duration);- }+ sender.send(frame_data).expect("Failed to send frame data to the writer thread");}- // Close the temporary file to ensure all data is flushed- drop(raw_file);- // Start the encoding process using FFmpeg+ // End capture loop+ drop(sender); // Send the terminating signal to the writing thread.+ write_handle.join().expect("Failed to join the writer handle");++ // Encoding with FFmpeglet status = Command::new(&ffmpeg_path).args(&["-f", "rawvideo","-pix_fmt", "bgra","-s", &format!("{}x{}", w, adjusted_height),"-r", &framerate.to_string(),- "-i", tmp_file_path.to_str().unwrap(),+ "-i", tmp_file_path.to_str().ok_or_else(|| "Failed to convert temporary file path to string".to_owned())?,"-c:v", "libx264","-preset", "veryfast","-crf", "15","-pix_fmt", "yuv420p",- "-y",+ "-y", // Overwrite output file without asking"-movflags", "+faststart",&output_path_str,])@@ -140,7 +142,7 @@ impl ScreenRecorder {match status {Ok(output) if output.status.success() => {// Encoding succeeded, remove the temporary file- fs::remove_file(&tmp_file_path).map_err(|e| format!("Failed to remove temporary file: {}", e))?;+ let _ = fs::remove_file(&tmp_file_path);Ok(())},Ok(output) => {diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.jsonindex 3cb937ce8..9d43b2f36 100644--- a/apps/desktop/src-tauri/tauri.conf.json+++ b/apps/desktop/src-tauri/tauri.conf.json@@ -28,7 +28,8 @@"unminimize": true,"startDragging": true,"setAlwaysOnTop": true,- "setIgnoreCursorEvents": true+ "setIgnoreCursorEvents": true,+ "setPosition": true},"fs": {"scope": ["**"],diff --git a/apps/desktop/src/components/windows/Camera.tsx b/apps/desktop/src/components/windows/Camera.tsxindex 1e70a8a07..818a31a6e 100644--- a/apps/desktop/src/components/windows/Camera.tsx+++ b/apps/desktop/src/components/windows/Camera.tsx@@ -1,5 +1,4 @@import { Preview } from "@/components/recording/Preview";-import { setWindowPosition } from "@/utils/helpers";import { useMediaDevices } from "@/utils/recording/MediaDeviceContext";import { ReactMediaRecorder } from "@/utils/recording/client";import { useRef } from "react";@@ -7,7 +6,6 @@ import { useRef } from "react";export const Camera = () => {const videoRef = useRef<HTMLVideoElement | null>(null);const { selectedVideoDevice } = useMediaDevices();- setWindowPosition("bottom_right");return (<div className="w-full h-full">diff --git a/apps/desktop/src/components/windows/Options.tsx b/apps/desktop/src/components/windows/Options.tsxindex 8f7a7390b..43a1676c8 100644--- a/apps/desktop/src/components/windows/Options.tsx+++ b/apps/desktop/src/components/windows/Options.tsx@@ -1,13 +1,10 @@import { Recorder } from "@/components/windows/inner/Recorder";import { SignIn } from "@/components/windows/inner/SignIn";-import { setWindowPosition } from "@/utils/helpers";import { supabase } from "@/utils/database/client";import { AuthSession } from "@supabase/supabase-js";import { useEffect, useState } from "react";export const Options = () => {- setWindowPosition("bottom_center");-const [session, setSession] = useState<AuthSession | null>(null);useEffect(() => {supabase.auth.getSession().then(({ data: { session } }) => {