Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

use multiple render passes

Brendan Allan88187469f475
diff --git a/Cargo.lock b/Cargo.lock
index bdffe9114..24a63635a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -644,7 +644,7 @@ dependencies = [
"cpal",
"dirs",
"dotenvy_macro",
- "ffmpeg-sidecar",
+ "ffmpeg-sidecar 1.1.0 (git+https://github.com/CapSoftware/ffmpeg-sidecar?branch=main)",
"fix-path-env",
"futures",
"image 0.24.9",
@@ -682,6 +682,46 @@ dependencies = [
"winit",
]
+[[package]]
+name = "cap-ffmpeg"
+version = "0.1.0"
+dependencies = [
+ "cap-utils",
+ "ffmpeg-sidecar 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+]
+
+[[package]]
+name = "cap-project"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "specta",
+]
+
+[[package]]
+name = "cap-rendering"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "bytemuck",
+ "cap-ffmpeg",
+ "cap-project",
+ "futures-intrusive",
+ "nix 0.29.0",
+ "serde",
+ "serde_json",
+ "specta",
+ "tokio",
+ "wgpu",
+]
+
+[[package]]
+name = "cap-utils"
+version = "0.1.0"
+dependencies = [
+ "nix 0.29.0",
+]
+
[[package]]
name = "cargo-platform"
version = "0.1.8"
@@ -1419,10 +1459,14 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bytemuck",
+ "cap-ffmpeg",
+ "cap-project",
+ "cap-rendering",
+ "cap-utils",
"cocoa 0.26.0",
"core-foundation 0.10.0",
"core-graphics 0.24.0",
- "ffmpeg-sidecar",
+ "ffmpeg-sidecar 1.1.0 (git+https://github.com/CapSoftware/ffmpeg-sidecar?branch=main)",
"futures-intrusive",
"image 0.25.2",
"mp4",
@@ -1692,6 +1736,15 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "ffmpeg-sidecar"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bec830aba6cd3da7621c58e8f06727e3b750e8383bcd934d789f2b9c3c4ea595"
+dependencies = [
+ "anyhow",
+]
+
[[package]]
name = "ffmpeg-sidecar"
version = "1.1.0"
@@ -5272,9 +5325,9 @@ dependencies = [
[[package]]
name = "serde"
-version = "1.0.208"
+version = "1.0.209"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cff085d2cb684faa248efb494c39b68e522822ac0de72ccf08109abde717cfb2"
+checksum = "99fce0ffe7310761ca6bf9faf5115afbc19688edd00171d81b1bb1b116c63e09"
dependencies = [
"serde_derive",
]
@@ -5292,9 +5345,9 @@ dependencies = [
[[package]]
name = "serde_derive"
-version = "1.0.208"
+version = "1.0.209"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "24008e81ff7613ed8e5ba0cfaf24e2c2f1e5b8a0495711e44fcd4882fca62bcf"
+checksum = "a5831b979fd7b5439637af1752d535ff49f4860c0f341d1baeb6faf0f4242170"
dependencies = [
"proc-macro2",
"quote",
@@ -5314,9 +5367,9 @@ dependencies = [
[[package]]
name = "serde_json"
-version = "1.0.125"
+version = "1.0.127"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "83c8e735a073ccf5be70aa8066aa984eaf2fa000db6c8d0100ae605b366d31ed"
+checksum = "8043c06d9f82bd7271361ed64f415fe5e12a77fdb52e573e7f06a516dea329ad"
dependencies = [
"itoa 1.0.11",
"memchr",
diff --git a/Cargo.toml b/Cargo.toml
index 1269abd48..489ecde61 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,3 +1,10 @@
[workspace]
resolver = "2"
-members = ["apps/desktop/src-tauri", "apps/desktop-solid/src-tauri"]
+members = [
+ "apps/desktop/src-tauri",
+ "apps/desktop-solid/src-tauri",
+ "crates/rendering",
+ "crates/ffmpeg",
+ "crates/utils",
+ "crates/project",
+]
diff --git a/apps/desktop-solid/app.config.timestamp_1724352470513.js b/apps/desktop-solid/app.config.timestamp_1724352470513.js
deleted file mode 100644
index 54c1eb9e8..000000000
--- a/apps/desktop-solid/app.config.timestamp_1724352470513.js
+++ /dev/null
@@ -1,27 +0,0 @@
-// app.config.ts
-import { defineConfig } from "@solidjs/start/config";
-import capUIPlugin from "@cap/ui-solid/vite";
-var app_config_default = defineConfig({
- ssr: false,
- server: { preset: "static" },
- // https://vitejs.dev/config
- vite: () => ({
- // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
- // 1. tauri expects a fixed port, fail if that port is not available
- server: {
- port: 1420,
- strictPort: true,
- watch: {
- // 2. tell vite to ignore watching `src-tauri`
- ignored: ["**/src-tauri/**"]
- }
- },
- // 3. to make use of `TAURI_DEBUG` and other env variables
- // https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
- envPrefix: ["VITE_", "TAURI_"],
- plugins: [capUIPlugin]
- })
-});
-export {
- app_config_default as default
-};
diff --git a/apps/desktop-solid/app.config.timestamp_1724433455035.js b/apps/desktop-solid/app.config.timestamp_1724433455035.js
deleted file mode 100644
index 54c1eb9e8..000000000
--- a/apps/desktop-solid/app.config.timestamp_1724433455035.js
+++ /dev/null
@@ -1,27 +0,0 @@
-// app.config.ts
-import { defineConfig } from "@solidjs/start/config";
-import capUIPlugin from "@cap/ui-solid/vite";
-var app_config_default = defineConfig({
- ssr: false,
- server: { preset: "static" },
- // https://vitejs.dev/config
- vite: () => ({
- // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
- // 1. tauri expects a fixed port, fail if that port is not available
- server: {
- port: 1420,
- strictPort: true,
- watch: {
- // 2. tell vite to ignore watching `src-tauri`
- ignored: ["**/src-tauri/**"]
- }
- },
- // 3. to make use of `TAURI_DEBUG` and other env variables
- // https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
- envPrefix: ["VITE_", "TAURI_"],
- plugins: [capUIPlugin]
- })
-});
-export {
- app_config_default as default
-};
diff --git a/apps/desktop-solid/src-tauri/Cargo.toml b/apps/desktop-solid/src-tauri/Cargo.toml
index b9518081c..20f75a7e8 100644
--- a/apps/desktop-solid/src-tauri/Cargo.toml
+++ b/apps/desktop-solid/src-tauri/Cargo.toml
@@ -48,3 +48,8 @@ anyhow = "1.0.86"
cocoa = "0.26.0"
objc = "0.2.7"
mp4 = "0.14.0"
+
+cap-utils = { path = "../../../crates/utils" }
+cap-project = { path = "../../../crates/project" }
+cap-rendering = { path = "../../../crates/rendering" }
+cap-ffmpeg = { path = "../../../crates/ffmpeg" }
diff --git a/apps/desktop-solid/src-tauri/src/camera.rs b/apps/desktop-solid/src-tauri/src/camera.rs
index e0793a605..ecec01a8e 100644
--- a/apps/desktop-solid/src-tauri/src/camera.rs
+++ b/apps/desktop-solid/src-tauri/src/camera.rs
@@ -6,7 +6,7 @@ use tokio::sync::oneshot;
use tauri::{AppHandle, Manager, WebviewUrl};
-use crate::ffmpeg::NamedPipeCapture;
+use cap_ffmpeg::NamedPipeCapture;
pub const WINDOW_LABEL: &str = "camera";
const CAMERA_ROUTE: &str = "/camera";
diff --git a/apps/desktop-solid/src-tauri/src/display.rs b/apps/desktop-solid/src-tauri/src/display.rs
index 14e499801..c4e31a3c8 100644
--- a/apps/desktop-solid/src-tauri/src/display.rs
+++ b/apps/desktop-solid/src-tauri/src/display.rs
@@ -8,7 +8,8 @@ use scap::{
use serde::{Deserialize, Serialize};
use specta::Type;
-use crate::{ffmpeg::NamedPipeCapture, macos};
+use crate::macos;
+use cap_ffmpeg::NamedPipeCapture;
#[derive(Type, Serialize, Deserialize, Debug, Clone)]
pub struct Bounds {
diff --git a/apps/desktop-solid/src-tauri/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rs
index 5aa54e468..55f30dfb1 100644
--- a/apps/desktop-solid/src-tauri/src/lib.rs
+++ b/apps/desktop-solid/src-tauri/src/lib.rs
@@ -1,15 +1,11 @@
mod camera;
mod display;
-mod ffmpeg;
mod macos;
-mod project;
mod recording;
-mod utils;
-mod video_renderer;
+use cap_project::ProjectConfiguration;
use mp4::Mp4Reader;
use objc2_app_kit::NSScreenSaverWindowLevel;
-use project::ProjectConfiguration;
use recording::{DisplaySource, InProgressRecording};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -26,9 +22,9 @@ use tauri_plugin_decorum::WebviewWindowExt;
use tauri_specta::Event;
use tokio::{sync::RwLock, time::sleep};
-use crate::utils::ffmpeg_path_as_str;
-use crate::video_renderer::{render_video, RenderOptions};
use camera::{create_camera_window, get_cameras};
+use cap_ffmpeg::ffmpeg_path_as_str;
+use cap_rendering::RenderOptions;
use display::{get_capture_windows, Bounds, CaptureTarget};
use ffmpeg_sidecar::{
@@ -270,9 +266,7 @@ async fn get_rendered_video(
if output_path.exists() {
Ok(output_path)
} else {
- use recording::recording_meta::*;
-
- let meta: RecordingMeta = serde_json::from_str(
+ let meta: cap_project::RecordingMeta = serde_json::from_str(
&std::fs::read_to_string(video_dir.join("recording-meta.json")).unwrap(),
)
.unwrap();
@@ -283,7 +277,8 @@ async fn get_rendered_video(
output_path: output_path.clone(),
screen_recording_path: video_dir.join("content/display.mp4"),
webcam_recording_path: video_dir.join("content/camera.mp4"),
- webcam_size: meta.camera.map(|c| (c.width, c.height)).unwrap_or((0, 0)),
+ screen_size: (meta.display.width, meta.display.height),
+ camera_size: meta.camera.map(|c| (c.width, c.height)).unwrap_or((0, 0)),
// webcam_style: WebcamStyle {
// border_radius: 10.0,
// shadow_color: [0.0, 0.0, 0.0, 0.5],
@@ -291,7 +286,6 @@ async fn get_rendered_video(
// shadow_offset: (2.0, 2.0),
// },
output_size: (meta.display.width, meta.display.height),
- // background: Background::Color([0.0, 0.0, 0.0, 1.0]),
};
render_video(render_options, project).await?;
@@ -606,6 +600,15 @@ fn focus_captures_panel(app: AppHandle) {
panel.make_key_window();
}
+#[tauri::command]
+#[specta::specta]
+async fn render_video(
+ options: RenderOptions,
+ project: ProjectConfiguration,
+) -> Result<PathBuf, String> {
+ cap_rendering::render_video(options, project).await
+}
+
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let specta_builder = tauri_specta::Builder::new()
diff --git a/apps/desktop-solid/src-tauri/src/recording.rs b/apps/desktop-solid/src-tauri/src/recording.rs
index 46ca23003..521eb6ba8 100644
--- a/apps/desktop-solid/src-tauri/src/recording.rs
+++ b/apps/desktop-solid/src-tauri/src/recording.rs
@@ -1,15 +1,15 @@
-use serde::{Deserialize, Serialize};
+use serde::Serialize;
use specta::Type;
use std::path::PathBuf;
use crate::{
camera,
display::{self, get_window_bounds, CaptureTarget},
- ffmpeg::*,
Bounds, RecordingOptions,
};
-use crate::video_renderer::RenderOptions;
+use cap_ffmpeg::*;
+use cap_rendering::RenderOptions;
#[derive(Clone, Type, Serialize)]
#[serde(rename_all = "camelCase", tag = "variant")]
@@ -89,7 +89,7 @@ pub async fn start(
let ffmpeg_process = ffmpeg.start();
- use recording_meta::*;
+ use cap_project::*;
let meta = RecordingMeta {
display: Display {
width: display.input.width,
@@ -218,25 +218,3 @@ async fn start_display_recording(
output_path,
}
}
-
-pub mod recording_meta {
- use super::*;
-
- #[derive(Serialize, Deserialize, Debug)]
- pub struct Display {
- pub width: u32,
- pub height: u32,
- }
-
- #[derive(Serialize, Deserialize, Debug)]
- pub struct Camera {
- pub width: u32,
- pub height: u32,
- }
-
- #[derive(Serialize, Deserialize, Debug)]
- pub struct RecordingMeta {
- pub display: Display,
- pub camera: Option<Camera>,
- }
-}
diff --git a/apps/desktop-solid/src-tauri/src/shaders/composite.wgsl b/apps/desktop-solid/src-tauri/src/shaders/composite.wgsl
deleted file mode 100644
index 76e0ac6b1..000000000
--- a/apps/desktop-solid/src-tauri/src/shaders/composite.wgsl
+++ /dev/null
@@ -1,143 +0,0 @@
-struct VertexOutput {
- @builtin(position) clip_position: vec4<f32>,
- @location(0) tex_coords: vec2<f32>,
-};
-
-@group(0) @binding(0) var screen_texture: texture_2d<f32>;
-@group(0) @binding(1) var screen_sampler: sampler;
-@group(0) @binding(2) var webcam_texture: texture_2d<f32>;
-@group(0) @binding(3) var webcam_sampler: sampler;
-
-struct CompositeParams {
- background_start: vec4<f32>,
- background_end: vec4<f32>,
-
- shadow_color: vec4<f32>,
- shadow_offset: vec2<f32>,
-
- webcam_position: vec2<f32>,
- webcam_size: vec2<f32>,
-
- screen_padding: f32,
- screen_rounding:f32,
- camera_rounding: f32,
-
- shadow_blur: f32,
-
- background_angle: f32,
- // _padding: vec3<f32>,
-};
-
-@group(0) @binding(4) var<uniform> params: CompositeParams;
-
-@vertex
-fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> VertexOutput {
- var out: VertexOutput;
- let x = f32(i32(in_vertex_index & 1u) * 4 - 1);
- let y = f32(i32(in_vertex_index & 2u) * 2 - 1);
- out.clip_position = vec4<f32>(x, y, 0.0, 1.0);
- out.tex_coords = vec2<f32>(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
- return out;
-}
-
-fn gradient(uv: vec2<f32>) -> vec4<f32> {
- let angle_rad = params.background_angle * 3.14159 / 180.0;
- let rotated_uv = vec2<f32>(
- cos(angle_rad) * uv.x - sin(angle_rad) * uv.y,
- sin(angle_rad) * uv.x + cos(angle_rad) * uv.y
- );
- // Create a more vibrant gradient
- let gradient_color = mix(
- vec4<f32>(params.background_start.rgb, 1),
- vec4<f32>(params.background_end.rgb, 1),
- rotated_uv.x
- );
- return vec4<f32>(gradient_color.rgb, gradient_color.a);
-}
-
-fn apply_shadow(base_color: vec4<f32>, uv: vec2<f32>, shadow_uv: vec2<f32>) -> vec4<f32> {
- let distance = length(uv - shadow_uv) / (params.shadow_blur * 3.0); // Increase blur area for softer shadow
- let shadow_alpha = smoothstep(1.0, 0.0, distance) * 0.2; // Set max opacity to 0.2
- let shadow_color = vec4<f32>(0.0, 0.0, 0.0, shadow_alpha); // Black color with calculated alpha
- return mix(base_color, shadow_color, shadow_alpha);
-}
-
-fn rounded_rect(uv: vec2<f32>, size: vec2<f32>, radius: f32) -> f32 {
- let distance = vec2<f32>(
- abs(uv.x - 0.5) - (size.x * 0.5 - radius),
- abs(uv.y - 0.5) - (size.y * 0.5 - radius)
- );
- let outside_distance = length(max(distance, vec2<f32>(0.0)));
- let inside_distance = min(max(distance.x, distance.y), 0.0);
- let edge_distance = outside_distance + inside_distance - radius;
- return step(edge_distance, 0.0);
-}
-
-fn add_shadow(base_color: vec4<f32>, uv: vec2<f32>) -> vec4<f32> {
- let centered_uv = (uv * 2) - 1;
-
- let distance = length(centered_uv);
-
- var alpha = 0.0;
-
- if (uv[0] < 0.0) {
- alpha = min(-uv[0], 1.0);
- } else {
- alpha = min(2.0 - uv[0], 1.0);
- }
-
- return mix(base_color, vec4<f32>(0.0, 0.0, 0.0, 1.0), alpha);
-}
-
-@fragment
-fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
- // Apply gradient background
- var final_color = gradient(in.tex_coords);
-
- // Calculate screen recording size and position
- let screen_scale = 1.0 - params.screen_padding; // 0.9; // Make screen recording slightly smaller
- let screen_offset = (1.0 - screen_scale) / 2.0;
- let screen_uv = (in.tex_coords - vec2<f32>(screen_offset)) / screen_scale;
-
- // Apply screen recording if within bounds
- if (screen_uv.x >= 0.0 && screen_uv.x <= 1.0 && screen_uv.y >= 0.0 && screen_uv.y <= 1.0) {
- let screen_color = textureSample(screen_texture, screen_sampler, screen_uv);
- let screen_radius = params.screen_rounding; // 0.02; // Adjust this value to change the border radius
- let screen_alpha = rounded_rect(screen_uv, vec2<f32>(1.0), screen_radius);
- final_color = mix(final_color, screen_color, screen_color.a * screen_alpha);
- }
-
- let ratio = 16.0 / 9.0;
-
- let webcam_scale = 0.2;
- let webcam_height = 0.2 / ratio;
-
- let gap = 2 * (webcam_scale - webcam_height);
-
- let x_scale = 1 / (1 - gap * 2);
- let webcam_uv = ((in.tex_coords - params.webcam_position) / 0.2) * vec2<f32>(x_scale, 1); // Change let to var
-
- // Apply box shadow
- let shadow_size = 0.01;
- let shadow_offset = vec2<f32>(shadow_size, -shadow_size);
- let shadow_uv = webcam_uv - shadow_offset / webcam_scale;
- let scaled_webcam_uv = webcam_uv / vec2<f32>(x_scale, 1) + vec2<f32>(gap, 0.0);
-
- // final_color = add_shadow(final_color, webcam_uv);
-
- // Apply webcam overlay
- if (webcam_uv.x >= 0 && webcam_uv.x <= 1 && webcam_uv.y >= 0.0 && webcam_uv.y <= 1.0) {
- let webcam_color = textureSample(
- webcam_texture,
- webcam_sampler,
- scaled_webcam_uv
- );
-
- // Apply border radius
- let border_alpha = rounded_rect(webcam_uv, vec2<f32>(1.0), params.camera_rounding / 2);
-
- final_color = mix(final_color, webcam_color, webcam_color.a * border_alpha);
- }
-
- return final_color;
-}
diff --git a/apps/desktop-solid/src/routes/editor/Editor.tsx b/apps/desktop-solid/src/routes/editor/Editor.tsx
index 687775fbd..ea29c2b13 100644
--- a/apps/desktop-solid/src/routes/editor/Editor.tsx
+++ b/apps/desktop-solid/src/routes/editor/Editor.tsx
@@ -88,10 +88,10 @@ function Inner() {
let timelineRef: HTMLDivElement;
let videoRef: HTMLVideoElement;
- createEffect(() => {
- const time = previewTime();
- if (time !== undefined) videoRef.currentTime = time;
- });
+ // createEffect(() => {
+ // const time = previewTime();
+ // if (time !== undefined) videoRef.currentTime = time;
+ // });
let timelineWidth = 0;
diff --git a/apps/desktop-solid/src/routes/editor/context.ts b/apps/desktop-solid/src/routes/editor/context.ts
index 39bb47591..2394efda8 100644
--- a/apps/desktop-solid/src/routes/editor/context.ts
+++ b/apps/desktop-solid/src/routes/editor/context.ts
@@ -32,8 +32,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
// source: { type: "color", value: [255, 0, ] },
source: {
type: "gradient",
- from: [/*71, 133, */ 0, 0, 255],
- to: [255, 0, 0 /*71, 102*/],
+ from: [71, 133, 255],
+ to: [255, 71, 102],
},
blur: 0,
padding: 10,
diff --git a/apps/desktop-solid/src/utils/tauri.ts b/apps/desktop-solid/src/utils/tauri.ts
index 8ca717687..25db3c37a 100644
--- a/apps/desktop-solid/src/utils/tauri.ts
+++ b/apps/desktop-solid/src/utils/tauri.ts
@@ -155,7 +155,7 @@ export type JsonValue<T> = [T]
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: CameraConfiguration; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration }
export type RecordingOptions = { captureTarget: CaptureTarget; cameraLabel: string | null }
export type RecordingOptionsChanged = null
-export type RenderOptions = { output_path: string; screen_recording_path: string; webcam_recording_path: string; webcam_size: [number, number]; output_size: [number, number] }
+export type RenderOptions = { output_path: string; screen_recording_path: string; webcam_recording_path: string; camera_size: [number, number]; screen_size: [number, number]; output_size: [number, number] }
export type ShowCapturesPanel = null
/** tauri-specta globals **/
diff --git a/crates/ffmpeg/Cargo.toml b/crates/ffmpeg/Cargo.toml
new file mode 100644
index 000000000..80c721da1
--- /dev/null
+++ b/crates/ffmpeg/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "cap-ffmpeg"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+ffmpeg-sidecar = "1.1.0"
+cap-utils = { path = "../utils" }
diff --git a/apps/desktop-solid/src-tauri/src/ffmpeg.rs b/crates/ffmpeg/src/lib.rs
similarity index 85%
rename from apps/desktop-solid/src-tauri/src/ffmpeg.rs
rename to crates/ffmpeg/src/lib.rs
index 4d863dad9..a9eab1f2e 100644
--- a/apps/desktop-solid/src-tauri/src/ffmpeg.rs
+++ b/crates/ffmpeg/src/lib.rs
@@ -1,22 +1,26 @@
+mod utils;
+pub use utils::*;
+
use std::{
ffi::OsString,
- io::{ Read, Write },
+ io::{Read, Write},
ops::Deref,
path::PathBuf,
- process::{ Child, ChildStdin, Command, Stdio },
- sync::{ atomic::{ AtomicBool, Ordering }, Arc },
+ process::{Child, ChildStdin, Command, Stdio},
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
};
use ffmpeg_sidecar::{
command::ffmpeg_is_installed,
- download::{ check_latest_version, download_ffmpeg_package, ffmpeg_download_url, unpack_ffmpeg },
+ download::{check_latest_version, download_ffmpeg_package, ffmpeg_download_url, unpack_ffmpeg},
paths::sidecar_dir,
version::ffmpeg_version,
};
-use std::io;
-
-use crate::utils::{ create_named_pipe, ffmpeg_path_as_str };
+use cap_utils::create_named_pipe;
pub struct FFmpegProcess {
pub ffmpeg_stdin: ChildStdin,
@@ -25,14 +29,11 @@ pub struct FFmpegProcess {
impl FFmpegProcess {
pub fn spawn(mut command: Command) -> Self {
- let mut cmd = command
- .stdin(Stdio::piped())
- .spawn()
- .unwrap_or_else(|e| {
- println!("Failed to start FFmpeg: {}", e);
- println!("Command: {:?}", command);
- panic!("Failed to start FFmpeg");
- });
+ let mut cmd = command.stdin(Stdio::piped()).spawn().unwrap_or_else(|e| {
+ println!("Failed to start FFmpeg: {}", e);
+ println!("Command: {:?}", command);
+ panic!("Failed to start FFmpeg");
+ });
let ffmpeg_stdin = cmd.stdin.take().unwrap_or_else(|| {
println!("Failed to capture FFmpeg stdin");
@@ -61,7 +62,7 @@ impl FFmpegProcess {
pub fn wait_with_timeout(
&mut self,
- timeout: std::time::Duration
+ timeout: std::time::Duration,
) -> std::io::Result<Option<std::process::ExitStatus>> {
let start = std::time::Instant::now();
while start.elapsed() < timeout {
@@ -77,7 +78,7 @@ impl FFmpegProcess {
pub fn read_video_frame(
&mut self,
- frame_size: usize
+ frame_size: usize,
) -> Result<Option<Vec<u8>>, std::io::Error> {
let mut buffer = vec![0u8; frame_size];
match self.cmd.stdout.as_mut().unwrap().read_exact(&mut buffer) {
@@ -95,12 +96,10 @@ impl FFmpegProcess {
while !remaining.is_empty() {
match self.ffmpeg_stdin.write(remaining) {
Ok(0) => {
- return Err(
- std::io::Error::new(
- std::io::ErrorKind::WriteZero,
- "Failed to write data to FFmpeg"
- )
- );
+ return Err(std::io::Error::new(
+ std::io::ErrorKind::WriteZero,
+ "Failed to write data to FFmpeg",
+ ));
}
Ok(n) => {
remaining = &remaining[n..];
@@ -246,7 +245,12 @@ impl FFmpeg {
pub fn add_output(&mut self, output: FFmpegOutput) {
match output {
- FFmpegOutput::File { path, codec, preset, crf } => {
+ FFmpegOutput::File {
+ path,
+ codec,
+ preset,
+ crf,
+ } => {
self.command
.arg("-i")
.arg("pipe:0")
@@ -255,7 +259,11 @@ impl FFmpeg {
.args(&["-crf", &crf.to_string()])
.arg(path);
}
- FFmpegOutput::RawVideo { format, width, height } => {
+ FFmpegOutput::RawVideo {
+ format,
+ width,
+ height,
+ } => {
self.command
.arg("-i")
.arg("pipe:0")
@@ -284,9 +292,8 @@ pub fn handle_ffmpeg_installation() -> Result<(), String> {
let download_url = ffmpeg_download_url().map_err(|e| e.to_string())?;
let destination = sidecar_dir().map_err(|e| e.to_string())?;
- let archive_path = download_ffmpeg_package(download_url, &destination).map_err(|e|
- e.to_string()
- )?;
+ let archive_path =
+ download_ffmpeg_package(download_url, &destination).map_err(|e| e.to_string())?;
unpack_ffmpeg(&archive_path, &destination).map_err(|e| e.to_string())?;
diff --git a/apps/desktop-solid/src-tauri/src/utils.rs b/crates/ffmpeg/src/utils.rs
similarity index 69%
rename from apps/desktop-solid/src-tauri/src/utils.rs
rename to crates/ffmpeg/src/utils.rs
index dc77e34d5..aa3778450 100644
--- a/apps/desktop-solid/src-tauri/src/utils.rs
+++ b/crates/ffmpeg/src/utils.rs
@@ -1,15 +1,6 @@
use ffmpeg_sidecar::paths::sidecar_dir;
use std::path::Path;
-#[cfg(unix)]
-pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
- use nix::sys::stat;
- use nix::unistd;
- std::fs::remove_file(&path).ok();
- unistd::mkfifo(path, stat::Mode::S_IRWXU)?;
- Ok(())
-}
-
pub fn ffmpeg_path_as_str() -> Result<String, String> {
let binary_name = if cfg!(target_os = "windows") {
"ffmpeg.exe"
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
new file mode 100644
index 000000000..39546f43b
--- /dev/null
+++ b/crates/project/Cargo.toml
@@ -0,0 +1,8 @@
+[package]
+name = "cap-project"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+specta = { version = "=2.0.0-rc.19", features = ["derive"] }
+serde = { version = "1.0.209", features = ["derive"] }
diff --git a/apps/desktop-solid/src-tauri/src/project.rs b/crates/project/src/configuration.rs
similarity index 68%
rename from apps/desktop-solid/src-tauri/src/project.rs
rename to crates/project/src/configuration.rs
index 485cc4eeb..f94479222 100644
--- a/apps/desktop-solid/src-tauri/src/project.rs
+++ b/crates/project/src/configuration.rs
@@ -1,9 +1,10 @@
use serde::{Deserialize, Serialize};
use specta::Type;
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub enum AspectRatio {
+ #[default]
Wide,
Vertical,
Square,
@@ -22,7 +23,13 @@ pub enum BackgroundSource {
Gradient { from: Color, to: Color },
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+impl Default for BackgroundSource {
+ fn default() -> Self {
+ BackgroundSource::Color { value: [255, 0, 0] }
+ }
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct BackgroundConfiguration {
pub source: BackgroundSource,
@@ -32,29 +39,31 @@ pub struct BackgroundConfiguration {
pub inset: u32,
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub enum CameraXPosition {
Left,
Center,
+ #[default]
Right,
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub enum CameraYPosition {
Top,
+ #[default]
Bottom,
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct CameraPosition {
pub x: CameraXPosition,
pub y: CameraYPosition,
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct CameraConfiguration {
pub hide: bool,
@@ -64,21 +73,22 @@ pub struct CameraConfiguration {
pub shadow: u32,
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct AudioConfiguration {
mute: bool,
improve: bool,
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub enum CursorType {
+ #[default]
Pointer,
Circle,
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct CursorConfiguration {
hide_when_idle: bool,
@@ -86,13 +96,13 @@ pub struct CursorConfiguration {
r#type: CursorType,
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct HotkeysConfiguration {
show: bool,
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct ProjectConfiguration {
pub aspect_ratio: Option<AspectRatio>,
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
new file mode 100644
index 000000000..29986c1c6
--- /dev/null
+++ b/crates/project/src/lib.rs
@@ -0,0 +1,22 @@
+mod configuration;
+
+pub use configuration::*;
+use serde::{Deserialize, Serialize};
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct Display {
+ pub width: u32,
+ pub height: u32,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct Camera {
+ pub width: u32,
+ pub height: u32,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct RecordingMeta {
+ pub display: Display,
+ pub camera: Option<Camera>,
+}
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
new file mode 100644
index 000000000..ae53a6688
--- /dev/null
+++ b/crates/rendering/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "cap-rendering"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+anyhow = "1.0.86"
+bytemuck = { version = "1.7", features = ["derive"] }
+futures-intrusive = "0.5.0"
+serde = "1.0.209"
+specta = "2.0.0-rc.19"
+wgpu = "22.1.0"
+
+cap-ffmpeg = { path = "../ffmpeg" }
+cap-project = { path = "../project" }
+tokio = { version = "1.39.3", features = ["macros", "sync", "rt", "rt-multi-thread"] }
+nix = { version = "0.29.0", features = ["fs"] }
+serde_json = "1.0.127"
diff --git a/apps/desktop-solid/src-tauri/src/video_renderer.rs b/crates/rendering/src/lib.rs
similarity index 52%
rename from apps/desktop-solid/src-tauri/src/video_renderer.rs
rename to crates/rendering/src/lib.rs
index 347dc48c9..4b64a2aed 100644
--- a/apps/desktop-solid/src-tauri/src/video_renderer.rs
+++ b/crates/rendering/src/lib.rs
@@ -11,9 +11,8 @@ use std::thread;
use wgpu::util::DeviceExt;
use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
-use crate::ffmpeg::{FFmpeg, FFmpegRawVideoInput};
-use crate::project::{BackgroundSource, CameraXPosition, CameraYPosition, ProjectConfiguration};
-use crate::utils::ffmpeg_path_as_str;
+use cap_ffmpeg::{ffmpeg_path_as_str, FFmpeg, FFmpegRawVideoInput};
+use cap_project::{BackgroundSource, CameraXPosition, CameraYPosition, ProjectConfiguration};
use std::io::{BufReader, Read};
use std::process::Command;
@@ -24,7 +23,8 @@ pub struct RenderOptions {
pub output_path: PathBuf,
pub screen_recording_path: PathBuf,
pub webcam_recording_path: PathBuf,
- pub webcam_size: (u32, u32),
+ pub camera_size: (u32, u32),
+ pub screen_size: (u32, u32),
// pub webcam_style: WebcamStyle,
pub output_size: (u32, u32),
// pub background: Background,
@@ -49,8 +49,7 @@ pub struct CompositeParams {
shadow_offset: [f32; 2],
webcam_position: [f32; 2],
- webcam_size: [f32; 2],
-
+ // webcam_size: [f32; 2],
screen_padding: f32,
screen_rounding: f32,
camera_rounding: f32,
@@ -72,7 +71,7 @@ pub enum Background {
},
}
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub struct UV<T> {
pub u: T,
pub v: T,
@@ -96,8 +95,6 @@ impl<T> From<UV<T>> for [T; 2] {
}
}
-#[tauri::command]
-#[specta::specta]
pub async fn render_video(
options: RenderOptions,
project: ProjectConfiguration,
@@ -139,135 +136,22 @@ pub async fn render_video(
);
let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());
- println!("Creating shader module...");
- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: Some("Shader"),
- source: wgpu::ShaderSource::Wgsl(include_str!("shaders/composite.wgsl").into()),
- });
-
- println!("Creating bind group layout and pipeline...");
- let bind_group_layout = device.create_bind_group_layout(
- &(wgpu::BindGroupLayoutDescriptor {
- label: Some("Bind Group Layout"),
- entries: &[
- // Screen texture
- wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Texture {
- sample_type: wgpu::TextureSampleType::Float { filterable: true },
- view_dimension: wgpu::TextureViewDimension::D2,
- multisampled: false,
- },
- count: None,
- },
- // Screen sampler
- wgpu::BindGroupLayoutEntry {
- binding: 1,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
- count: None,
- },
- // Webcam texture
- wgpu::BindGroupLayoutEntry {
- binding: 2,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Texture {
- sample_type: wgpu::TextureSampleType::Float { filterable: true },
- view_dimension: wgpu::TextureViewDimension::D2,
- multisampled: false,
- },
- count: None,
- },
- // Webcam sampler
- wgpu::BindGroupLayoutEntry {
- binding: 3,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
- count: None,
- },
- // Uniform buffer
- wgpu::BindGroupLayoutEntry {
- binding: 4,
- visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
- ty: wgpu::BindingType::Buffer {
- ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
- },
- count: None,
- },
- ],
- }),
- );
-
- let pipeline_layout = device.create_pipeline_layout(
- &(wgpu::PipelineLayoutDescriptor {
- label: Some("Render Pipeline Layout"),
- bind_group_layouts: &[&bind_group_layout],
- push_constant_ranges: &[],
- }),
- );
-
- let compilation_options = wgpu::PipelineCompilationOptions {
- constants: &HashMap::new(),
- zero_initialize_workgroup_memory: false,
- vertex_pulling_transform: false,
- };
-
- let render_pipeline = device.create_render_pipeline(
- &(wgpu::RenderPipelineDescriptor {
- label: Some("Render Pipeline"),
- layout: Some(&pipeline_layout),
- vertex: wgpu::VertexState {
- module: &shader,
- entry_point: "vs_main",
- buffers: &[],
- compilation_options: compilation_options.clone(),
- },
- fragment: Some(wgpu::FragmentState {
- module: &shader,
- entry_point: "fs_main",
- targets: &[Some(wgpu::ColorTargetState {
- format: wgpu::TextureFormat::Rgba8UnormSrgb,
- blend: Some(wgpu::BlendState::REPLACE),
- write_mask: wgpu::ColorWrites::ALL,
- })],
- compilation_options,
- }),
- primitive: wgpu::PrimitiveState {
- topology: wgpu::PrimitiveTopology::TriangleList,
- strip_index_format: None,
- front_face: wgpu::FrontFace::Ccw,
- cull_mode: Some(wgpu::Face::Back),
- polygon_mode: wgpu::PolygonMode::Fill,
- unclipped_depth: false,
- conservative: false,
- },
- depth_stencil: None,
- multisample: wgpu::MultisampleState {
- count: 1,
- mask: !0,
- alpha_to_coverage_enabled: false,
- },
- multiview: None,
- cache: None,
- }),
- );
+ let composite = Composite::new(&device);
+ let render_frame = RenderFrame::new(&device);
println!("Creating uniform buffer...");
- let (background_start, background_end, background_angle) = match &project.background.source {
+ let (background_start, background_end, _background_angle) = match &project.background.source {
BackgroundSource::Color { value } => (
[
- value[0] as f32 / 256.0,
- value[1] as f32 / 256.0,
- value[2] as f32 / 256.0,
+ srgb_to_linear(value[0]),
+ srgb_to_linear(value[1]),
+ srgb_to_linear(value[2]),
1.0,
],
[
- value[0] as f32 / 256.0,
- value[1] as f32 / 256.0,
- value[2] as f32 / 256.0,
+ srgb_to_linear(value[0]),
+ srgb_to_linear(value[1]),
+ srgb_to_linear(value[2]),
1.0,
],
0.0,
@@ -277,15 +161,15 @@ pub async fn render_video(
to, /*angle*/
} => (
[
- from[0] as f32 / 256.0,
- from[1] as f32 / 256.0,
- from[2] as f32 / 256.0,
+ srgb_to_linear(from[0]),
+ srgb_to_linear(from[1]),
+ srgb_to_linear(from[2]),
1.0,
],
[
- to[0] as f32 / 256.0,
- to[1] as f32 / 256.0,
- to[2] as f32 / 256.0,
+ srgb_to_linear(to[0]),
+ srgb_to_linear(to[1]),
+ srgb_to_linear(to[2]),
1.0,
],
0.0,
@@ -293,59 +177,93 @@ pub async fn render_video(
_ => todo!(),
};
- let webcam_size = UV::new(
- CAMERA_UV_WIDTH,
- options.webcam_size.1 as f32 / options.webcam_size.0 as f32 * CAMERA_UV_WIDTH,
- );
-
- const CAMERA_PADDING: f32 = 100.0;
- const CAMERA_UV_WIDTH: f32 = 0.2;
+ const CAMERA_PADDING: f32 = 50.0;
+ const CAMERA_UV_WIDTH: f32 = 0.3;
let camera_padding = UV::new(
CAMERA_PADDING / options.output_size.0 as f32,
CAMERA_PADDING / options.output_size.1 as f32,
);
+ let webcam_size = options.output_size.1 as f32 * CAMERA_UV_WIDTH;
+
let webcam_position = {
let x = match &project.camera.position.x {
CameraXPosition::Left => camera_padding.u,
- CameraXPosition::Center => 0.5 - (CAMERA_UV_WIDTH /*webcam_size.u*/ / 2.0),
- CameraXPosition::Right => 1.0 - camera_padding.u - webcam_size.u, //webcam_size.u,
+ CameraXPosition::Center => 0.5 - (webcam_size / options.output_size.0 as f32) / 2.0,
+ CameraXPosition::Right => {
+ 1.0 - camera_padding.u - webcam_size / options.output_size.0 as f32
+ }
};
let y = match &project.camera.position.y {
CameraYPosition::Top => camera_padding.v,
- CameraYPosition::Bottom => 1.0 - camera_padding.v - webcam_size.v, // webcam_size.v,
+ CameraYPosition::Bottom => 1.0 - CAMERA_UV_WIDTH - camera_padding.v,
};
UV::new(x, y)
};
- dbg!(&webcam_position);
- dbg!(&webcam_size);
+ let screen_uniforms_buffer = device.create_buffer_init(
+ &(wgpu::util::BufferInitDescriptor {
+ label: Some("Uniform Buffer"),
+ contents: bytemuck::cast_slice(&[render_frame::Uniforms {
+ fb_size: [options.screen_size.0 as f32, options.screen_size.1 as f32],
+ border_pc: project.background.rounding as f32,
+ x_offset: 0.0,
+ mirror: false as u32,
+ _padding: [0.0],
+ }]),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ }),
+ );
- let uniform_data = CompositeParams {
- webcam_position: webcam_position.into(),
- webcam_size: webcam_size.into(),
+ let camera_uniforms_buffer = device.create_buffer_init(
+ &(wgpu::util::BufferInitDescriptor {
+ label: Some("Uniform Buffer 2"),
+ contents: bytemuck::cast_slice(&[render_frame::Uniforms {
+ fb_size: [options.camera_size.1 as f32, options.camera_size.1 as f32],
+ border_pc: project.camera.rounding as f32,
+ x_offset: (options.camera_size.0 - options.camera_size.1) as f32 / 2.0,
+ mirror: project.camera.mirror as u32,
+ _padding: [0.0],
+ }]),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ }),
+ );
- screen_padding: project.background.padding as f32 / 100.0,
- screen_rounding: project.background.rounding as f32 / 700.0,
- camera_rounding: project.camera.rounding as f32 / 100.0,
+ let screen_xy = (
+ options.output_size.0 as f32 / 2.0,
+ options.output_size.1 as f32 / 2.0,
+ );
+ let screen_scale = 1.0 - project.background.padding as f32 / 100.0;
- shadow_color: [0.0, 0.0, 0.0, 0.5],
- shadow_blur: project.camera.shadow as f32 / 500.0,
- shadow_offset: [2.0, 2.0],
+ let output_ratio = options.output_size.0 as f32 / options.output_size.1 as f32;
+ let screen_ratio = options.screen_size.0 as f32 / options.screen_size.1 as f32;
+ let camera_ratio = options.camera_size.0 as f32 / options.camera_size.1 as f32;
- background_start,
- background_end,
- background_angle: 0.25,
+ let screen_size_uv = UV::new(screen_scale * (screen_ratio / output_ratio), screen_scale);
- _padding1: 0.0,
- };
+ let screen_uv = UV::new(
+ ((screen_xy.0 / options.output_size.0 as f32) - 0.5)
+ + (1.0 - screen_scale) / 2.0
+ + (screen_scale - screen_size_uv.u) / 2.0,
+ ((screen_xy.1 / options.output_size.1 as f32) - 0.5) + (1.0 - screen_scale) / 2.0,
+ );
- let uniform_buffer = device.create_buffer_init(
+ let composite_uniforms_buffer = device.create_buffer_init(
&(wgpu::util::BufferInitDescriptor {
- label: Some("Uniform Buffer"),
- contents: bytemuck::cast_slice(&[uniform_data]),
+ label: Some("Uniform Buffer 2"),
+ contents: bytemuck::cast_slice(&[composite::Uniforms {
+ screen_bounds: [screen_uv.u, screen_uv.v, screen_size_uv.u, screen_size_uv.v],
+ webcam_bounds: [
+ webcam_position.u,
+ webcam_position.v,
+ CAMERA_UV_WIDTH * (camera_ratio / output_ratio),
+ CAMERA_UV_WIDTH,
+ ],
+ background_start,
+ background_end,
+ }]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
}),
);
@@ -354,8 +272,8 @@ pub async fn render_video(
let ffmpeg_binary_path_str = ffmpeg_path_as_str().unwrap().to_owned();
- let screen_frame_size = (options.output_size.0 * options.output_size.1 * 4) as usize;
- let webcam_frame_size = (options.webcam_size.0 * options.webcam_size.1 * 4) as usize;
+ let screen_frame_size = (options.screen_size.0 * options.screen_size.1 * 4) as usize;
+ let webcam_frame_size = (options.camera_size.0 * options.camera_size.1 * 4) as usize;
let (tx_image_data, rx_image_data) = mpsc::channel::<Vec<u8>>();
let (screen_tx, mut screen_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
@@ -419,7 +337,7 @@ pub async fn render_video(
"-pix_fmt",
"rgba",
"-s",
- &format!("{}x{}", options.output_size.0, options.output_size.1),
+ &format!("{}x{}", options.screen_size.0, options.screen_size.1),
"-c:v",
"rawvideo",
"pipe:1",
@@ -467,7 +385,7 @@ pub async fn render_video(
"-pix_fmt",
"rgba",
"-s",
- &format!("{}x{}", options.webcam_size.0, options.webcam_size.1),
+ &format!("{}x{}", options.camera_size.0, options.camera_size.1),
"-c:v",
"rawvideo",
"pipe:1",
@@ -543,156 +461,96 @@ pub async fn render_video(
}
};
+ let mut encoder = device.create_command_encoder(
+ &(wgpu::CommandEncoderDescriptor {
+ label: Some("Render Encoder"),
+ }),
+ );
+
let screen_texture = device.create_texture(
&(wgpu::TextureDescriptor {
size: wgpu::Extent3d {
- width: options.output_size.0,
- height: options.output_size.1,
+ width: options.screen_size.0,
+ height: options.screen_size.1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- label: Some("screen_texture"),
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ label: Some("texture"),
view_formats: &[],
}),
);
+ let screen_texture_view =
+ screen_texture.create_view(&wgpu::TextureViewDescriptor::default());
+
let webcam_texture = device.create_texture(
&(wgpu::TextureDescriptor {
size: wgpu::Extent3d {
- width: options.webcam_size.0,
- height: options.webcam_size.1,
+ width: options.camera_size.0,
+ height: options.camera_size.1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- label: Some("webcam_texture"),
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ label: Some("webcam texture"),
view_formats: &[],
}),
);
- let screen_view = screen_texture.create_view(&wgpu::TextureViewDescriptor::default());
- let webcam_view = webcam_texture.create_view(&wgpu::TextureViewDescriptor::default());
-
- let sampler = device.create_sampler(
- &(wgpu::SamplerDescriptor {
- address_mode_u: wgpu::AddressMode::ClampToEdge,
- address_mode_v: wgpu::AddressMode::ClampToEdge,
- address_mode_w: wgpu::AddressMode::ClampToEdge,
- mag_filter: wgpu::FilterMode::Linear,
- min_filter: wgpu::FilterMode::Nearest,
- mipmap_filter: wgpu::FilterMode::Nearest,
- ..Default::default()
- }),
- );
-
- let bind_group = device.create_bind_group(
- &(wgpu::BindGroupDescriptor {
- layout: &bind_group_layout,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::TextureView(&screen_view),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::Sampler(&sampler),
- },
- wgpu::BindGroupEntry {
- binding: 2,
- resource: wgpu::BindingResource::TextureView(&webcam_view),
- },
- wgpu::BindGroupEntry {
- binding: 3,
- resource: wgpu::BindingResource::Sampler(&sampler),
- },
- wgpu::BindGroupEntry {
- binding: 4,
- resource: uniform_buffer.as_entire_binding(),
- },
- ],
- label: Some("bind_group"),
- }),
+ let webcam_texture_view =
+ webcam_texture.create_view(&wgpu::TextureViewDescriptor::default());
+
+ do_render_pass(
+ &mut encoder,
+ &screen_texture_view,
+ &render_frame.render_pipeline,
+ render_frame::bind_group(
+ &device,
+ &queue,
+ &render_frame.bind_group_layout,
+ &screen_uniforms_buffer,
+ options.screen_size,
+ screen_frame,
+ ),
);
- queue.write_texture(
- wgpu::ImageCopyTexture {
- texture: &screen_texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- &screen_frame,
- wgpu::ImageDataLayout {
- offset: 0,
- bytes_per_row: Some(options.output_size.0 * 4),
- rows_per_image: None,
- },
- wgpu::Extent3d {
- width: options.output_size.0,
- height: options.output_size.1,
- depth_or_array_layers: 1,
- },
+ do_render_pass(
+ &mut encoder,
+ &webcam_texture_view,
+ &render_frame.render_pipeline,
+ render_frame::bind_group(
+ &device,
+ &queue,
+ &render_frame.bind_group_layout,
+ &camera_uniforms_buffer,
+ options.camera_size,
+ webcam_frame,
+ ),
);
- queue.write_texture(
- wgpu::ImageCopyTexture {
- texture: &webcam_texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- &webcam_frame,
- wgpu::ImageDataLayout {
- offset: 0,
- bytes_per_row: Some(options.webcam_size.0 * 4),
- rows_per_image: None,
- },
- wgpu::Extent3d {
- width: options.webcam_size.0,
- height: options.webcam_size.1,
- depth_or_array_layers: 1,
- },
+ do_render_pass(
+ &mut encoder,
+ &output_view,
+ &composite.render_pipeline,
+ composite::bind_group(
+ &device,
+ &composite.bind_group_layout,
+ &screen_texture_view,
+ &webcam_texture_view,
+ &composite_uniforms_buffer,
+ ),
);
- {
- let mut encoder = device.create_command_encoder(
- &(wgpu::CommandEncoderDescriptor {
- label: Some("Render Encoder"),
- }),
- );
-
- {
- let mut render_pass = encoder.begin_render_pass(
- &(wgpu::RenderPassDescriptor {
- label: Some("Render Pass"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &output_view,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
- store: wgpu::StoreOp::Store,
- },
- })],
- depth_stencil_attachment: None,
- timestamp_writes: None,
- occlusion_query_set: None,
- }),
- );
-
- render_pass.set_pipeline(&render_pipeline);
- render_pass.set_bind_group(0, &bind_group, &[]);
- render_pass.draw(0..3, 0..1);
- }
-
- queue.submit(std::iter::once(encoder.finish()));
- }
+ queue.submit(std::iter::once(encoder.finish()));
// Copy the output texture to a buffer
let output_buffer = device.create_buffer(
@@ -806,3 +664,386 @@ pub async fn render_video(
Ok(output_path)
}
+
+mod render_frame {
+ use super::*;
+
+ #[derive(Debug, Clone, Copy, Pod, Zeroable)]
+ #[repr(C)]
+ pub struct Uniforms {
+ pub fb_size: [f32; 2],
+ pub border_pc: f32,
+ pub x_offset: f32,
+ pub mirror: u32,
+ pub _padding: [f32; 1],
+ }
+
+ pub const SHADER: &str = include_str!("shaders/render-frame.wgsl");
+
+ pub fn bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Bind Group Layout"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ })
+ }
+
+ pub fn bind_group(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ layout: &wgpu::BindGroupLayout,
+ uniform_buffer: &wgpu::Buffer,
+ frame_size: (u32, u32),
+ frame_data: Vec<u8>,
+ ) -> wgpu::BindGroup {
+ let texture = device.create_texture(
+ &(wgpu::TextureDescriptor {
+ size: wgpu::Extent3d {
+ width: frame_size.0,
+ height: frame_size.1,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ label: Some("texture"),
+ view_formats: &[],
+ }),
+ );
+
+ let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
+
+ let sampler = device.create_sampler(
+ &(wgpu::SamplerDescriptor {
+ address_mode_u: wgpu::AddressMode::ClampToEdge,
+ address_mode_v: wgpu::AddressMode::ClampToEdge,
+ address_mode_w: wgpu::AddressMode::ClampToEdge,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Nearest,
+ mipmap_filter: wgpu::FilterMode::Nearest,
+ ..Default::default()
+ }),
+ );
+
+ let bind_group = device.create_bind_group(
+ &(wgpu::BindGroupDescriptor {
+ layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&texture_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ ],
+ label: Some("bind_group"),
+ }),
+ );
+
+ queue.write_texture(
+ wgpu::ImageCopyTexture {
+ texture: &texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ &frame_data,
+ wgpu::ImageDataLayout {
+ offset: 0,
+ bytes_per_row: Some(frame_size.0 * 4),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width: frame_size.0,
+ height: frame_size.1,
+ depth_or_array_layers: 1,
+ },
+ );
+
+ bind_group
+ }
+}
+
+struct Composite {
+ pub bind_group_layout: wgpu::BindGroupLayout,
+ pub render_pipeline: wgpu::RenderPipeline,
+}
+
+impl Composite {
+ pub fn new(device: &wgpu::Device) -> Self {
+ let bind_group_layout = composite::bind_group_layout(&device);
+ let render_pipeline =
+ create_shader_render_pipeline(&device, &bind_group_layout, composite::SHADER);
+
+ Self {
+ bind_group_layout,
+ render_pipeline,
+ }
+ }
+}
+
+struct RenderFrame {
+ pub bind_group_layout: wgpu::BindGroupLayout,
+ pub render_pipeline: wgpu::RenderPipeline,
+}
+
+impl RenderFrame {
+ pub fn new(device: &wgpu::Device) -> Self {
+ let bind_group_layout = render_frame::bind_group_layout(&device);
+ let render_pipeline =
+ create_shader_render_pipeline(&device, &bind_group_layout, render_frame::SHADER);
+
+ Self {
+ bind_group_layout,
+ render_pipeline,
+ }
+ }
+}
+
+mod composite {
+ use super::*;
+
+ #[derive(Debug, Clone, Copy, Pod, Zeroable)]
+ #[repr(C)]
+ pub struct Uniforms {
+ pub screen_bounds: [f32; 4],
+ pub webcam_bounds: [f32; 4],
+ pub background_start: [f32; 4],
+ pub background_end: [f32; 4],
+ }
+
+ pub const SHADER: &str = include_str!("shaders/composite.wgsl");
+
+ pub fn bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Composite Everything Bind Group Layout"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 3,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 4,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ })
+ }
+
+ pub fn bind_group(
+ device: &wgpu::Device,
+ layout: &wgpu::BindGroupLayout,
+ one: &wgpu::TextureView,
+ two: &wgpu::TextureView,
+ uniforms: &wgpu::Buffer,
+ ) -> wgpu::BindGroup {
+ let sampler = device.create_sampler(
+ &(wgpu::SamplerDescriptor {
+ address_mode_u: wgpu::AddressMode::ClampToEdge,
+ address_mode_v: wgpu::AddressMode::ClampToEdge,
+ address_mode_w: wgpu::AddressMode::ClampToEdge,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Nearest,
+ mipmap_filter: wgpu::FilterMode::Nearest,
+ ..Default::default()
+ }),
+ );
+
+ let bind_group = device.create_bind_group(
+ &(wgpu::BindGroupDescriptor {
+ layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniforms.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(one),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ wgpu::BindGroupEntry {
+ binding: 3,
+ resource: wgpu::BindingResource::TextureView(two),
+ },
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ ],
+ label: Some("bind_group"),
+ }),
+ );
+
+ bind_group
+ }
+}
+
+fn do_render_pass(
+ encoder: &mut wgpu::CommandEncoder,
+ output_view: &wgpu::TextureView,
+ render_pipeline: &wgpu::RenderPipeline,
+ bind_group: wgpu::BindGroup,
+) {
+ let mut render_pass = encoder.begin_render_pass(
+ &(wgpu::RenderPassDescriptor {
+ label: Some("Render Pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &output_view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ }),
+ );
+
+ render_pass.set_pipeline(&render_pipeline);
+ render_pass.set_bind_group(0, &bind_group, &[]);
+ render_pass.draw(0..3, 0..1);
+}
+
+fn create_shader_render_pipeline(
+ device: &wgpu::Device,
+ bind_group_layout: &wgpu::BindGroupLayout,
+ wgsl_shader: &str,
+) -> wgpu::RenderPipeline {
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("Shader"),
+ source: wgpu::ShaderSource::Wgsl(wgsl_shader.into()),
+ });
+
+ let compilation_options = wgpu::PipelineCompilationOptions {
+ constants: &HashMap::new(),
+ zero_initialize_workgroup_memory: false,
+ vertex_pulling_transform: false,
+ };
+
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Render Pipeline"),
+ layout: Some(&device.create_pipeline_layout(
+ &(wgpu::PipelineLayoutDescriptor {
+ label: Some("Render Pipeline Layout"),
+ bind_group_layouts: &[&bind_group_layout],
+ push_constant_ranges: &[],
+ }),
+ )),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: "vs_main",
+ buffers: &[],
+ compilation_options: compilation_options.clone(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: "fs_main",
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ blend: Some(wgpu::BlendState::REPLACE),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options,
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ strip_index_format: None,
+ front_face: wgpu::FrontFace::Ccw,
+ cull_mode: Some(wgpu::Face::Back),
+ polygon_mode: wgpu::PolygonMode::Fill,
+ unclipped_depth: false,
+ conservative: false,
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState {
+ count: 1,
+ mask: !0,
+ alpha_to_coverage_enabled: false,
+ },
+ multiview: None,
+ cache: None,
+ })
+}
+
+fn srgb_to_linear(c: u16) -> f32 {
+ let c = c as f32 / 255.0;
+ if c <= 0.04045 {
+ c / 12.92
+ } else {
+ ((c + 0.055) / 1.055).powf(2.4)
+ }
+}
diff --git a/crates/rendering/src/main.rs b/crates/rendering/src/main.rs
new file mode 100644
index 000000000..bfab69008
--- /dev/null
+++ b/crates/rendering/src/main.rs
@@ -0,0 +1,44 @@
+use std::path::PathBuf;
+
+use cap_project::{BackgroundSource, ProjectConfiguration, RecordingMeta};
+use cap_rendering::render_video;
+
+#[tokio::main]
+async fn main() {
+ let project_path = PathBuf::from(
+ r#"/Users/brendonovich/Library/Application Support/so.cap.desktop-solid/recordings/414f2abd-8186-479f-85e7-08a64411a33c.cap"#,
+ );
+
+ let mut project: ProjectConfiguration = ProjectConfiguration::default();
+
+ project.camera.position.x = cap_project::CameraXPosition::Right;
+ project.camera.position.y = cap_project::CameraYPosition::Top;
+ project.camera.rounding = 40;
+ project.camera.mirror = false;
+
+ project.background.source = BackgroundSource::Gradient {
+ from: [71, 133, 255],
+ to: [255, 71, 102],
+ };
+ project.background.rounding = 10;
+ project.background.padding = 10;
+
+ let meta: RecordingMeta = serde_json::from_str(
+ &std::fs::read_to_string(project_path.join("recording-meta.json")).unwrap(),
+ )
+ .unwrap();
+
+ render_video(
+ cap_rendering::RenderOptions {
+ output_path: project_path.join("output/result.mp4"),
+ screen_recording_path: project_path.join("content/display.mp4"),
+ webcam_recording_path: project_path.join("content/camera.mp4"),
+ camera_size: meta.camera.map(|c| (c.width, c.height)).unwrap_or_default(),
+ screen_size: (meta.display.width, meta.display.height),
+ output_size: (1920, 1080),
+ },
+ project,
+ )
+ .await
+ .ok();
+}
diff --git a/crates/rendering/src/shaders/background.wgsl b/crates/rendering/src/shaders/background.wgsl
new file mode 100644
index 000000000..37a44b721
--- /dev/null
+++ b/crates/rendering/src/shaders/background.wgsl
@@ -0,0 +1,10 @@
+
+@vertex
+fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> VertexOutput {
+ var out: VertexOutput;
+ let x = f32(i32(in_vertex_index & 1u) * 4 - 1);
+ let y = f32(i32(in_vertex_index & 2u) * 2 - 1);
+ out.clip_position = vec4<f32>(x, y, 0.0, 1.0);
+ out.tex_coords = vec2<f32>(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
+ return out;
+}
diff --git a/crates/rendering/src/shaders/composite.wgsl b/crates/rendering/src/shaders/composite.wgsl
new file mode 100644
index 000000000..22a7a3f63
--- /dev/null
+++ b/crates/rendering/src/shaders/composite.wgsl
@@ -0,0 +1,64 @@
+struct VertexOutput {
+ @builtin(position) clip_position: vec4<f32>,
+ @location(0) tex_coords: vec2<f32>,
+};
+
+@group(0) @binding(0) var<uniform> uniforms: Uniforms;
+@group(0) @binding(1) var screen_texture: texture_2d<f32>;
+@group(0) @binding(2) var screen_sampler: sampler;
+@group(0) @binding(3) var webcam_texture: texture_2d<f32>;
+@group(0) @binding(4) var webcam_sampler: sampler;
+
+struct Uniforms {
+ screen_bounds: vec4<f32>,
+ webcam_bounds: vec4<f32>,
+ background_start: vec4<f32>,
+ background_end: vec4<f32>,
+}
+
+@vertex
+fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> VertexOutput {
+ var out: VertexOutput;
+ let x = f32(i32(in_vertex_index & 1u) * 4 - 1);
+ let y = f32(i32(in_vertex_index & 2u) * 2 - 1);
+ out.tex_coords = vec2<f32>(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
+ out.clip_position = vec4<f32>(x, y, 0.0, 1.0);
+
+ return out;
+}
+
+fn gradient(uv: vec2<f32>) -> vec4<f32> {
+ let angle_rad = 0.0 /*uniforms.background_angle*/ * 3.14159 / 180.0;
+ let rotated_uv = vec2<f32>(
+ cos(angle_rad) * uv.x - sin(angle_rad) * uv.y,
+ sin(angle_rad) * uv.x + cos(angle_rad) * uv.y
+ );
+
+ let gradient_color = mix(
+ vec4<f32>(uniforms.background_start.rgb * (25.0 / 33.0), 1),
+ vec4<f32>(uniforms.background_end.rgb * (25.0 / 33.0), 1),
+ rotated_uv.x
+ );
+ return vec4<f32>(gradient_color.rgb, gradient_color.a);
+}
+
+@fragment
+fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
+ var final_color = gradient(in.tex_coords);
+
+ let relative_to_screen = (in.tex_coords - uniforms.screen_bounds.xy) / uniforms.screen_bounds.zw;
+
+ if (relative_to_screen.x >= 0 && relative_to_screen.y >= 0 && relative_to_screen.x <= 1 && relative_to_screen.y <= 1) {
+ let screen_color = textureSample(screen_texture, screen_sampler, relative_to_screen);
+ final_color = mix(final_color, screen_color, screen_color.a);
+ }
+
+ let relative_to_webcam = (in.tex_coords - uniforms.webcam_bounds.xy) / uniforms.webcam_bounds.zw;
+
+ if (relative_to_webcam.x >= 0 && relative_to_webcam.y >= 0 && relative_to_webcam.x <= 1 && relative_to_webcam.y <= 1) {
+ let webcam_color = textureSample(webcam_texture, webcam_sampler, relative_to_webcam);
+ final_color = mix(final_color, webcam_color, webcam_color.a);
+ }
+
+ return final_color;
+}
diff --git a/crates/rendering/src/shaders/render-frame.wgsl b/crates/rendering/src/shaders/render-frame.wgsl
new file mode 100644
index 000000000..3cd921447
--- /dev/null
+++ b/crates/rendering/src/shaders/render-frame.wgsl
@@ -0,0 +1,76 @@
+struct Uniforms {
+ fb_size: vec2<f32>,
+ border_pc: f32,
+ x_offset: f32,
+ mirror: u32,
+};
+
+@group(0) @binding(0) var<uniform> uniforms: Uniforms;
+@group(0) @binding(1) var texture: texture_2d<f32>;
+@group(0) @binding(2) var sample: sampler;
+
+struct VertexOutput {
+ @builtin(position) clip_position: vec4<f32>,
+ @location(0) tex_coords: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> VertexOutput {
+ var out: VertexOutput;
+ let x = f32(i32(in_vertex_index & 1u) * 4 - 1);
+ let y = f32(i32(in_vertex_index & 2u) * 2 - 1);
+ out.tex_coords = vec2<f32>(x * 0.5 + 0.5, 1.0 - (y * 0.5 + 0.5));
+ out.clip_position = vec4<f32>(x, y, 0.0, 1.0);
+
+ return out;
+}
+
+fn round_corners(color: vec4<f32>, clip_position: vec2<f32>, size: vec2<f32>) -> vec4<f32> {
+ let smallest_axis = min(size.x, size.y);
+ let border_radius = smallest_axis * min(max(uniforms.border_pc / 100.0, 0.0), 1.0);
+
+ if (clip_position.x > size.x || clip_position.y > size.y) {
+ return vec4<f32>(0.0);
+ }
+
+ let corner = size - border_radius;
+ let relative_to_corner = abs((clip_position - (size / 2)) * 2);
+
+ let distance = length(relative_to_corner - corner);
+
+ if(relative_to_corner.x > corner.x && relative_to_corner.y > corner.y && distance > border_radius) {
+ return vec4<f32>(0.0);
+ }
+
+ return color;
+}
+
+fn crop_texture(clip_position: vec2<f32>, origin: vec2<f32>, size: vec2<f32>) -> vec4<f32> {
+ let divisor = (size + vec2<f32>(origin.x * 2, 0.0));
+ var position = (clip_position.xy + origin) / divisor;
+
+ if(uniforms.mirror == 1) {
+ position.x = 1.0 - position.x;
+ }
+
+ return textureSample(
+ texture,
+ sample,
+ position
+ );
+}
+
+@fragment
+fn fs_main(
+ @location(0) tex_coords: vec2<f32>,
+ @builtin(position) clip_position: vec4<f32>
+) -> @location(0) vec4<f32> {
+ let origin = vec2<f32>(uniforms.x_offset, 0.0);
+ let size = uniforms.fb_size.xy;
+
+ var final_color = crop_texture(clip_position.xy , origin, size);
+
+ final_color = round_corners(final_color, clip_position.xy, size);
+
+ return final_color;
+}
diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.toml
new file mode 100644
index 000000000..7ab270f35
--- /dev/null
+++ b/crates/utils/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "cap-utils"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+nix = "0.29.0"
diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rs
new file mode 100644
index 000000000..fed6c0163
--- /dev/null
+++ b/crates/utils/src/lib.rs
@@ -0,0 +1,10 @@
+use std::path::Path;
+
+#[cfg(unix)]
+pub fn create_named_pipe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
+ use nix::sys::stat;
+ use nix::unistd;
+ std::fs::remove_file(&path).ok();
+ unistd::mkfifo(path, stat::Mode::S_IRWXU)?;
+ Ok(())
+}