Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

basic cropping

Brendan Allan9e0e25fcb9ae
diff --git a/apps/desktop-solid/app.config.timestamp_1725628327725.js b/apps/desktop-solid/app.config.timestamp_1725628327725.js
deleted file mode 100644
index 54c1eb9e8..000000000
--- a/apps/desktop-solid/app.config.timestamp_1725628327725.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/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rs
index f4673035d..8142dcd41 100644
--- a/apps/desktop-solid/src-tauri/src/lib.rs
+++ b/apps/desktop-solid/src-tauri/src/lib.rs
@@ -25,6 +25,7 @@ use image::{ImageBuffer, Rgba};
use mp4::Mp4Reader;
use num_traits::ToBytes;
use objc2_app_kit::NSScreenSaverWindowLevel;
+use project_recordings::ProjectRecordings;
use recording::{DisplaySource, InProgressRecording};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -565,6 +566,7 @@ struct SerializedEditorInstance {
frames_socket_url: String,
recording_duration: f64,
saved_project_config: Option<ProjectConfiguration>,
+ recordings: ProjectRecordings,
}
#[tauri::command]
@@ -583,6 +585,7 @@ async fn create_editor_instance(
)
.ok()
.and_then(|s| serde_json::from_str(&s).ok()),
+ recordings: editor_instance.recordings.clone(),
})
}
diff --git a/apps/desktop-solid/src-tauri/src/project_recordings.rs b/apps/desktop-solid/src-tauri/src/project_recordings.rs
index 0c3ed35e7..94be0688c 100644
--- a/apps/desktop-solid/src-tauri/src/project_recordings.rs
+++ b/apps/desktop-solid/src-tauri/src/project_recordings.rs
@@ -1,10 +1,12 @@
use std::path::PathBuf;
use cap_project::RecordingMeta;
+use serde::Serialize;
+use specta::Type;
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, Serialize, Type)]
pub struct Video {
- pub duration: i64,
+ pub duration: f64,
pub width: u32,
pub height: u32,
pub fps: f32,
@@ -29,15 +31,15 @@ impl Video {
Video {
width: video_decoder.width(),
height: video_decoder.height(),
- duration: input.duration(),
+ duration: (input.duration() / 1_000_000) as f64,
fps: frame_rate.numerator() as f32 / frame_rate.denominator() as f32,
}
}
}
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, Serialize, Type)]
pub struct Audio {
- pub duration: i64,
+ pub duration: f64,
pub sample_rate: u32,
pub channels: u16,
}
@@ -57,14 +59,14 @@ impl Audio {
.unwrap();
Audio {
- duration: input.duration(),
+ duration: (input.duration() / 1_000_000) as f64,
sample_rate: video_decoder.rate(),
channels: video_decoder.channels(),
}
}
}
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, Serialize, Type)]
pub struct ProjectRecordings {
pub display: Video,
pub camera: Option<Video>,
@@ -91,16 +93,15 @@ impl ProjectRecordings {
}
pub fn duration(&self) -> f64 {
- let duration_ns = [
+ let mut duration_ns = [
Some(self.display.duration),
self.camera.as_ref().map(|s| s.duration),
self.audio.as_ref().map(|s| s.duration),
]
.into_iter()
.flatten()
- .max()
- .unwrap();
-
- duration_ns as f64 / 1_000_000.0
+ .collect::<Vec<_>>();
+ duration_ns.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
+ duration_ns[0]
}
}
diff --git a/apps/desktop-solid/src/routes/editor/Editor.tsx b/apps/desktop-solid/src/routes/editor/Editor.tsx
index e05ab0d41..b8bb8de22 100644
--- a/apps/desktop-solid/src/routes/editor/Editor.tsx
+++ b/apps/desktop-solid/src/routes/editor/Editor.tsx
@@ -20,8 +20,10 @@ import {
Match,
Show,
Switch,
+ batch,
createEffect,
createMemo,
+ createRoot,
createSignal,
on,
onMount,
@@ -65,9 +67,17 @@ export function Editor() {
<Show when={videoId()} fallback="No video id available" keyed>
{(videoId) => (
<EditorInstanceContextProvider videoId={videoId}>
- <Show when={useEditorInstanceContext().editorInstance()}>
- {(editorInstance) => (
- <EditorContextProvider editorInstance={editorInstance()}>
+ <Show
+ when={(() => {
+ const ctx = useEditorInstanceContext();
+ const editorInstance = ctx.editorInstance();
+
+ if (!editorInstance) return;
+ return { editorInstance };
+ })()}
+ >
+ {(values) => (
+ <EditorContextProvider {...values()}>
<Inner />
</EditorContextProvider>
)}
@@ -79,7 +89,7 @@ export function Editor() {
}
function Inner() {
- const { setCanvasRef, state, videoId, editorInstance, history } =
+ const { state, videoId, editorInstance, history, currentFrame, setDialog } =
useEditorContext();
const duration = () => editorInstance.recordingDuration;
@@ -161,6 +171,15 @@ function Inner() {
};
});
+ let canvasRef: HTMLCanvasElement;
+
+ createEffect(() => {
+ const frame = currentFrame();
+ if (!frame) return;
+ const ctx = canvasRef.getContext("2d");
+ ctx?.putImageData(frame, 0, 0);
+ });
+
return (
<div
class="p-5 flex flex-col gap-4 w-screen h-screen divide-y bg-gray-50 rounded-lg leading-5"
@@ -173,7 +192,26 @@ function Inner() {
<div class="flex flex-row justify-between font-medium p-[0.75rem] text-[0.875rem]">
<div class="flex flex-row items-center gap-[0.5rem]">
<AspectRatioSelect />
- <EditorButton leftIcon={<IconCapCrop />}>Crop</EditorButton>
+ <EditorButton
+ leftIcon={<IconCapCrop />}
+ onClick={() => {
+ setDialog({
+ open: true,
+ type: "crop",
+ position: {
+ ...(state.background.crop?.position ?? { x: 0, y: 0 }),
+ },
+ size: {
+ ...(state.background.crop?.size ?? {
+ x: editorInstance.recordings.display.width,
+ y: editorInstance.recordings.display.height,
+ }),
+ },
+ });
+ }}
+ >
+ Crop
+ </EditorButton>
<PresetsDropdown />
</div>
<div class="flex flex-row place-items-center gap-2">
@@ -196,7 +234,8 @@ function Inner() {
<div class="bg-gray-100 flex items-center justify-center flex-1 flex-row object-contain p-4">
<canvas
class="bg-blue-50 w-full"
- ref={setCanvasRef}
+ // biome-ignore lint/style/noNonNullAssertion: ref
+ ref={canvasRef!}
id="canvas"
width={OUTPUT_SIZE.width}
height={OUTPUT_SIZE.height}
@@ -345,7 +384,7 @@ function Header() {
);
}
-import { Channel } from "@tauri-apps/api/core";
+import { Channel, convertFileSrc } from "@tauri-apps/api/core";
import { save } from "@tauri-apps/plugin-dialog";
import {
EditorInstanceContextProvider,
@@ -357,6 +396,10 @@ import {
DEFAULT_GRADIENT_FROM,
DEFAULT_GRADIENT_TO,
} from "./projectConfig";
+import {
+ createEventListener,
+ createEventListenerMap,
+} from "@solid-primitives/event-listener";
function ExportButton() {
const { videoId, state: project } = useEditorContext();
@@ -954,7 +997,7 @@ function AspectRatioSelect() {
{(state) => {
const text = () => {
const option = state.selectedOption();
- option === "auto" ? "Auto" : ASPECT_RATIOS[option].name;
+ return option === "auto" ? "Auto" : ASPECT_RATIOS[option].name;
};
return <>{text()}</>;
}}
@@ -1104,6 +1147,7 @@ function Dialogs() {
return (
<Dialog.Root
+ size={dialog().type === "crop" ? "lg" : "sm"}
open={dialog().open}
onOpenChange={(o) => {
if (!o) setDialog((d) => ({ ...d, open: false }));
@@ -1183,6 +1227,323 @@ function Dialogs() {
</DialogContent>
)}
</Match>
+ <Match
+ when={(() => {
+ const d = dialog();
+ if (d.type === "crop") return d;
+ })()}
+ >
+ {(dialog) => {
+ const { setState, editorInstance } = useEditorContext();
+ const [params] = useSearchParams<{ path: string }>();
+ const [crop, setCrop] = createStore({
+ position: dialog().position,
+ size: dialog().size,
+ });
+
+ const display = editorInstance.recordings.display;
+
+ const styles = createMemo(() => {
+ return {
+ left: `${(crop.position.x / display.width) * 100}%`,
+ top: `${(crop.position.y / display.height) * 100}%`,
+ right: `calc(${
+ ((display.width - crop.size.x - crop.position.x) /
+ display.width) *
+ 100
+ }%)`,
+ bottom: `calc(${
+ ((display.height - crop.size.y - crop.position.y) /
+ display.height) *
+ 100
+ }%)`,
+ };
+ });
+
+ return (
+ <>
+ <Dialog.Header>
+ <div class="flex flex-row space-x-[0.75rem]">
+ {/* <AspectRatioSelect />*/}
+ <div class="flex flex-row items-center space-x-[0.5rem] text-gray-400">
+ <span>Size</span>
+ <Input
+ class="w-[3.25rem]"
+ value={crop.size.x}
+ disabled
+ />
+ <span>x</span>
+ <Input
+ class="w-[3.25rem]"
+ value={crop.size.y}
+ disabled
+ />
+ </div>
+ <div class="flex flex-row items-center space-x-[0.5rem] text-gray-400">
+ <span>Position</span>
+ <Input
+ class="w-[3.25rem]"
+ value={crop.position.x}
+ disabled
+ />
+ <span>x</span>
+ <Input
+ class="w-[3.25rem]"
+ value={crop.position.y}
+ disabled
+ />
+ </div>
+ </div>
+ <EditorButton
+ leftIcon={<IconCapCircleX />}
+ class="ml-auto"
+ onClick={() =>
+ setCrop({
+ position: { x: 0, y: 0 },
+ size: {
+ x: editorInstance.recordings.display.width,
+ y: editorInstance.recordings.display.height,
+ },
+ })
+ }
+ >
+ Reset
+ </EditorButton>
+ </Dialog.Header>
+ <Dialog.Content>
+ <div class="relative">
+ <div class="divide-black-transparent-10 overflow-hidden rounded-lg">
+ <img
+ class="shadow pointer-events-none"
+ alt="screenshot"
+ src={convertFileSrc(
+ `${params.path}/screenshots/display.jpg`
+ )}
+ />
+ </div>
+ <div
+ class="bg-white-transparent-20 absolute cursor-move"
+ style={styles()}
+ onMouseDown={(downEvent) => {
+ const parentDiv =
+ downEvent.target.parentElement?.parentElement;
+ if (!parentDiv) return;
+
+ const original = {
+ position: { ...crop.position },
+ size: { ...crop.size },
+ };
+
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mouseup: () => dispose(),
+ mousemove: (moveEvent) => {
+ const width = crop.size.x;
+ const height = crop.size.y;
+
+ const diff = {
+ x:
+ (moveEvent.clientX - downEvent.clientX) /
+ parentDiv.clientWidth,
+ y:
+ (moveEvent.clientY - downEvent.clientY) /
+ parentDiv.clientHeight,
+ };
+
+ batch(() => {
+ if (original.position.x + diff.x < 0)
+ setCrop("position", "x", 0);
+ else if (
+ original.position.x + diff.x + width >
+ 1
+ )
+ setCrop("position", "x", 1);
+ else
+ setCrop(
+ "position",
+ "x",
+ original.position.x + diff.x
+ );
+
+ if (original.position.y + diff.y < 0)
+ setCrop("position", "y", 0);
+ else if (
+ original.position.y + diff.y + height >
+ 1
+ )
+ setCrop("position", "y", 1);
+ else
+ setCrop(
+ "position",
+ "y",
+ original.position.y + diff.y
+ );
+ });
+ },
+ });
+ });
+ }}
+ >
+ <For
+ each={Array.from({ length: 4 }, (_, i) => ({
+ x: i < 2 ? ("l" as const) : ("r" as const),
+ y: i % 2 === 0 ? ("t" as const) : ("b" as const),
+ }))}
+ >
+ {(pos) => {
+ const behaviours = {
+ x:
+ pos.x === "l"
+ ? ("both" as const)
+ : ("resize" as const),
+ y:
+ pos.y === "t"
+ ? ("both" as const)
+ : ("resize" as const),
+ };
+
+ return (
+ <button
+ type="button"
+ class="absolute"
+ style={{
+ ...(pos.x === "l"
+ ? { left: "0px" }
+ : { right: "0px" }),
+ ...(pos.y === "t"
+ ? { top: "0px" }
+ : { bottom: "0px" }),
+ }}
+ onMouseDown={(downEvent) => {
+ downEvent.stopPropagation();
+
+ const parentDiv =
+ downEvent.target.parentElement
+ ?.parentElement?.parentElement;
+ if (!parentDiv) return;
+
+ const original = {
+ position: { ...crop.position },
+ size: { ...crop.size },
+ };
+
+ const MIN_SIZE = 100;
+
+ createRoot((dispose) => {
+ createEventListenerMap(window, {
+ mouseup: () => dispose(),
+ mousemove: (moveEvent) => {
+ batch(() => {
+ const diff = {
+ x:
+ ((moveEvent.clientX -
+ downEvent.clientX) /
+ parentDiv.clientWidth) *
+ display.width,
+ y:
+ ((moveEvent.clientY -
+ downEvent.clientY) /
+ parentDiv.clientHeight) *
+ display.height,
+ };
+
+ if (behaviours.x === "resize") {
+ setCrop(
+ "size",
+ "x",
+ clamp(
+ original.size.x + diff.x,
+ MIN_SIZE,
+ editorInstance.recordings
+ .display.width -
+ crop.position.x
+ )
+ );
+ } else {
+ setCrop(
+ "position",
+ "x",
+ clamp(
+ original.position.x + diff.x,
+ 0,
+ editorInstance.recordings
+ .display.width - MIN_SIZE
+ )
+ );
+ setCrop(
+ "size",
+ "x",
+ clamp(
+ original.size.x - diff.x,
+ MIN_SIZE,
+ editorInstance.recordings
+ .display.width
+ )
+ );
+ }
+
+ if (behaviours.y === "resize") {
+ setCrop(
+ "size",
+ "y",
+ clamp(
+ original.size.y + diff.y,
+ MIN_SIZE,
+ editorInstance.recordings
+ .display.height -
+ crop.position.y
+ )
+ );
+ } else {
+ setCrop(
+ "position",
+ "y",
+ clamp(
+ original.position.y + diff.y,
+ 0,
+ editorInstance.recordings
+ .display.height - MIN_SIZE
+ )
+ );
+ setCrop(
+ "size",
+ "y",
+ clamp(
+ original.size.y - diff.y,
+ MIN_SIZE,
+ editorInstance.recordings
+ .display.height
+ )
+ );
+ }
+ });
+ },
+ });
+ });
+ }}
+ >
+ <div class="size-[1rem] bg-gray-500 border border-gray-50 rounded-full absolute -top-[0.5rem] -left-[0.5rem]" />
+ </button>
+ );
+ }}
+ </For>
+ </div>
+ </div>
+ </Dialog.Content>
+ <Dialog.Footer>
+ <Button
+ onClick={() => {
+ setState("background", "crop", crop);
+ setDialog((d) => ({ ...d, open: false }));
+ }}
+ >
+ Save
+ </Button>
+ </Dialog.Footer>
+ </>
+ );
+ }}
+ </Match>
</Switch>
)}
</Show>
@@ -1255,3 +1616,7 @@ function hexToRgb(hex: string): [number, number, number] | null {
if (!match) return null;
return match.slice(1).map((c) => Number.parseInt(c, 16)) as any;
}
+
+function clamp(n: number, min = 0, max = 1) {
+ return Math.max(min, Math.min(max, n));
+}
diff --git a/apps/desktop-solid/src/routes/editor/context.ts b/apps/desktop-solid/src/routes/editor/context.ts
index d71676de9..f52466156 100644
--- a/apps/desktop-solid/src/routes/editor/context.ts
+++ b/apps/desktop-solid/src/routes/editor/context.ts
@@ -1,5 +1,5 @@
import { createContextProvider } from "@solid-primitives/context";
-import { createEffect, createSignal, on } from "solid-js";
+import { type Accessor, createEffect, createSignal, on } from "solid-js";
import { createStore, reconcile, unwrap } from "solid-js/store";
import { debounce } from "@solid-primitives/scheduled";
import { createUndoHistory } from "@solid-primitives/history";
@@ -10,6 +10,7 @@ import {
type SerializedEditorInstance,
type ProjectConfiguration,
commands,
+ type XY,
} from "../../utils/tauri";
import { useEditorInstanceContext } from "./editorInstanceContext";
import { DEFAULT_PROJECT_CONFIG } from "./projectConfig";
@@ -18,7 +19,7 @@ export type CurrentDialog =
| { type: "createPreset" }
| { type: "renamePreset"; presetId: string }
| { type: "deletePreset"; presetId: string }
- | { type: "crop" };
+ | { type: "crop"; position: XY<number>; size: XY<number> };
export type DialogState = { open: false } | ({ open: boolean } & CurrentDialog);
diff --git a/apps/desktop-solid/src/routes/editor/editorInstanceContext.ts b/apps/desktop-solid/src/routes/editor/editorInstanceContext.ts
index 2060fe9a1..f5f6fc9a9 100644
--- a/apps/desktop-solid/src/routes/editor/editorInstanceContext.ts
+++ b/apps/desktop-solid/src/routes/editor/editorInstanceContext.ts
@@ -1,6 +1,8 @@
import { createContextProvider } from "@solid-primitives/context";
import { createResource, createSignal } from "solid-js";
-import { commands } from "../../utils/tauri";
+
+import { events, commands } from "../../utils/tauri";
+import { DEFAULT_PROJECT_CONFIG } from "./projectConfig";
export const OUTPUT_SIZE = {
width: 1920,
@@ -9,30 +11,36 @@ export const OUTPUT_SIZE = {
export const [EditorInstanceContextProvider, useEditorInstanceContext] =
createContextProvider((props: { videoId: string }) => {
+ const [currentFrame, setCurrentFrame] = createSignal<ImageData>();
+
const [editorInstance] = createResource(async () => {
const instance = await commands.createEditorInstance(props.videoId);
if (instance.status !== "ok") throw new Error("Failed to start editor");
const ws = new WebSocket(instance.data.framesSocketUrl);
+ ws.onopen = () => {
+ events.renderFrameEvent.emit({
+ frame_number: Math.floor(0),
+ project: instance.data.savedProjectConfig ?? DEFAULT_PROJECT_CONFIG,
+ });
+ };
ws.binaryType = "arraybuffer";
ws.onmessage = (event) => {
- const ctx = canvasRef()?.getContext("2d");
- if (!ctx) return;
const clamped = new Uint8ClampedArray(event.data);
const imageData = new ImageData(
clamped,
OUTPUT_SIZE.width,
OUTPUT_SIZE.height
);
- ctx.putImageData(imageData, 0, 0);
+ setCurrentFrame(imageData);
};
return instance.data;
});
- const [canvasRef, setCanvasRef] = createSignal<HTMLCanvasElement | null>(
- null
- );
-
- return { canvasRef, setCanvasRef, editorInstance, videoId: props.videoId };
+ return {
+ editorInstance,
+ videoId: props.videoId,
+ currentFrame,
+ };
}, null!);
diff --git a/apps/desktop-solid/src/routes/editor/ui.tsx b/apps/desktop-solid/src/routes/editor/ui.tsx
index 6a9255582..aa12c859e 100644
--- a/apps/desktop-solid/src/routes/editor/ui.tsx
+++ b/apps/desktop-solid/src/routes/editor/ui.tsx
@@ -90,7 +90,7 @@ export function Input(props: ComponentProps<"input">) {
<input
{...props}
class={cx(
- "rounded-[0.5rem] h-[2rem] p-[0.375rem] border w-full text-gray-500 text-[0.875rem] focus:border-blue-300 outline-none",
+ "rounded-[0.5rem] h-[2rem] p-[0.375rem] border w-full text-[0.875rem] focus:border-blue-300 outline-none",
props.class
)}
/>
@@ -98,7 +98,12 @@ export function Input(props: ComponentProps<"input">) {
}
export const Dialog = {
- Root(props: ComponentProps<typeof KDialog> & { hideOverlay?: boolean }) {
+ Root(
+ props: ComponentProps<typeof KDialog> & {
+ hideOverlay?: boolean;
+ size?: "sm" | "lg";
+ }
+ ) {
return (
<KDialog {...props}>
<KDialog.Portal>
@@ -106,7 +111,12 @@ export const Dialog = {
<KDialog.Overlay class="fixed inset-0 z-50 bg-black-transparent-80 ui-expanded:animate-in ui-expanded:fade-in ui-closed:animate-out ui-closed:fade-out" />
)}
<div class="fixed inset-0 z-50 flex items-center justify-center">
- <KDialog.Content class="z-50 divide-y text-sm rounded-[1.25rem] overflow-hidden max-w-96 border border-gray-200 bg-gray-50 min-w-[22rem] ui-expanded:animate-in ui-expanded:fade-in ui-expanded:zoom-in-95 origin-top ui-closed:animate-out ui-closed:fade-out ui-closed:zoom-out-95">
+ <KDialog.Content
+ class={cx(
+ "z-50 divide-y text-sm rounded-[1.25rem] overflow-hidden border border-gray-200 bg-gray-50 min-w-[22rem] ui-expanded:animate-in ui-expanded:fade-in ui-expanded:zoom-in-95 origin-top ui-closed:animate-out ui-closed:fade-out ui-closed:zoom-out-95",
+ (props.size ?? "sm") === "sm" ? "max-w-96" : "max-w-3xl"
+ )}
+ >
{props.children}
</KDialog.Content>
</div>
@@ -142,11 +152,9 @@ export const Dialog = {
</div>
);
},
- Header(props: { title: string } & ComponentProps<"div">) {
+ Header(props: ComponentProps<"div">) {
return (
- <div {...props} class="h-[3.5rem] px-[1rem] flex flex-row items-center">
- <KDialog.Title>{props.title}</KDialog.Title>
- </div>
+ <div {...props} class="h-[3.5rem] px-[1rem] flex flex-row items-center" />
);
},
Content(props: ComponentProps<"div">) {
@@ -159,7 +167,9 @@ export function DialogContent(
) {
return (
<>
- <Dialog.Header title={props.title} />
+ <Dialog.Header>
+ <KDialog.Title>{props.title}</KDialog.Title>
+ </Dialog.Header>
<Dialog.Content class={props.class}>{props.children}</Dialog.Content>
<Dialog.Footer>{props.confirm}</Dialog.Footer>
</>
diff --git a/apps/desktop-solid/src/utils/tauri.ts b/apps/desktop-solid/src/utils/tauri.ts
index b8543da4e..cd9ec184b 100644
--- a/apps/desktop-solid/src/utils/tauri.ts
+++ b/apps/desktop-solid/src/utils/tauri.ts
@@ -174,8 +174,9 @@ showCapturesPanel: "show-captures-panel"
/** user-defined types **/
export type AspectRatio = "wide" | "vertical" | "square" | "classic" | "tall"
+export type Audio = { duration: number; sample_rate: number; channels: number }
export type AudioConfiguration = { mute: boolean; improve: boolean }
-export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; inset: number }
+export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; inset: number; crop: Crop | null }
export type BackgroundSource = { type: "wallpaper"; id: number } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number] } | { type: "gradient"; from: [number, number, number]; to: [number, number, number] }
export type Bounds = { x: number; y: number; width: number; height: number }
export type CameraConfiguration = { hide: boolean; mirror: boolean; position: CameraPosition; rounding: number; shadow: number }
@@ -184,6 +185,7 @@ export type CameraXPosition = "left" | "center" | "right"
export type CameraYPosition = "top" | "bottom"
export type CaptureTarget = { type: "screen" } | { type: "window"; id: number }
export type CaptureWindow = { id: number; name: string }
+export type Crop = { position: XY<number>; size: XY<number> }
export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: CursorType }
export type CursorType = "pointer" | "circle"
export type DisplaySource = { variant: "screen" } | { variant: "window"; bounds: Bounds }
@@ -193,13 +195,16 @@ export type InProgressRecording = { recordingDir: string; displaySource: Display
export type JsonValue<T> = [T]
export type NewRecordingAdded = { path: string }
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: CameraConfiguration; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration }
+export type ProjectRecordings = { display: Video; camera: Video | null; audio: Audio | null }
export type RecordingOptions = { captureTarget: CaptureTarget; cameraLabel: string | null; audioInputName: string | null }
export type RecordingOptionsChanged = null
export type RenderFrameEvent = { frame_number: number; project: ProjectConfiguration }
export type RenderProgress = { type: "Starting"; total_frames: number } | { type: "EstimatedTotalFrames"; total_frames: number } | { type: "FrameRendered"; current_frame: number }
-export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration | null }
+export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration | null; recordings: ProjectRecordings }
export type ShowCapturesPanel = null
+export type Video = { duration: number; width: number; height: number; fps: number }
export type VideoType = "screen" | "output"
+export type XY<T> = { x: T; y: T }
/** tauri-specta globals **/
diff --git a/apps/desktop-solid/tsconfig.json b/apps/desktop-solid/tsconfig.json
index 4e5903705..68f22bc61 100644
--- a/apps/desktop-solid/tsconfig.json
+++ b/apps/desktop-solid/tsconfig.json
@@ -14,7 +14,7 @@
"noEmit": true,
"jsx": "preserve",
"jsxImportSource": "solid-js",
- "types": ["vite/client", "vinxi/client", "@cap/ui-solid/types"],
+ "types": ["vinxi/client", "@cap/ui-solid/types"],
/* Linting */
"strict": true
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 5a7b310f3..b7483c59f 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -29,6 +29,20 @@ impl Default for BackgroundSource {
}
}
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct XY<T> {
+ pub x: T,
+ pub y: T,
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct Crop {
+ pub position: XY<f32>,
+ pub size: XY<f32>
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct BackgroundConfiguration {
@@ -37,6 +51,7 @@ pub struct BackgroundConfiguration {
pub padding: f32,
pub rounding: f32,
pub inset: u32,
+ pub crop: Option<Crop>,
}
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index fdf17c2f3..120ef6a42 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -9,7 +9,9 @@ use std::collections::HashMap;
use wgpu::util::DeviceExt;
use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
-use cap_project::{BackgroundSource, CameraXPosition, CameraYPosition, ProjectConfiguration};
+use cap_project::{
+ BackgroundSource, CameraXPosition, CameraYPosition, Crop, ProjectConfiguration, XY,
+};
use std::time::Instant;
@@ -331,14 +333,33 @@ impl ProjectUniforms {
let output_size = [options.output_size.0 as f32, options.output_size.1 as f32];
let display = {
- let frame_size = [options.screen_size.0 as f32, options.screen_size.1 as f32];
- let frame_aspect = frame_size[0] / frame_size[1];
- let min_axis = frame_size[0].min(frame_size[1]);
+ let size = [options.screen_size.0 as f32, options.screen_size.1 as f32];
+
+ let crop_bounds = {
+ let crop = project.background.crop.clone().unwrap_or(Crop {
+ position: XY { x: 0.0, y: 0.0 },
+ size: XY { x: size[0], y: size[1] },
+ });
+
+ [
+ crop.position.x,
+ crop.position.y,
+ crop.position.x + crop.size.x,
+ crop.position.y + crop.size.y,
+ ]
+ };
+
+ let cropped_size = [
+ crop_bounds[2] - crop_bounds[0],
+ crop_bounds[3] - crop_bounds[1],
+ ];
+ let cropped_aspect = cropped_size[0] / cropped_size[1];
+
let y_padding =
project.background.padding / 100.0 * SCREEN_MAX_PADDING * output_size[1];
let target_height = (output_size[1] - y_padding) - y_padding;
- let target_width = target_height * frame_aspect;
+ let target_width = target_height * cropped_aspect;
let target_left_bounds = (output_size[0] - target_width) / 2.0;
let target_bounds = [
target_left_bounds,
@@ -351,8 +372,8 @@ impl ProjectUniforms {
CompositeVideoFrameUniforms {
output_size,
- frame_size,
- crop_bounds: [0.0, 0.0, frame_size[0], frame_size[1]],
+ frame_size: size,
+ crop_bounds,
target_bounds,
target_size,
rounding_px: project.background.rounding / 100.0 * 0.5 * min_target_axis,
diff --git a/crates/rendering/src/shaders/background.wgsl b/crates/rendering/src/shaders/background.wgsl
deleted file mode 100644
index 37a44b721..000000000
--- a/crates/rendering/src/shaders/background.wgsl
+++ /dev/null
@@ -1,10 +0,0 @@
-
-@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
deleted file mode 100644
index 22a7a3f63..000000000
--- a/crates/rendering/src/shaders/composite.wgsl
+++ /dev/null
@@ -1,64 +0,0 @@
-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
deleted file mode 100644
index ce5e33161..000000000
--- a/crates/rendering/src/shaders/render-frame.wgsl
+++ /dev/null
@@ -1,90 +0,0 @@
-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 border_width = 00.0;
-
- let origin = vec2<f32>(uniforms.x_offset, 0.0);
- let size = uniforms.fb_size.xy - border_width * 2;
- let position = clip_position.xy - border_width;
-
- var final_color = crop_texture(position, origin, size);
-
- final_color = round_corners(final_color, position, size);
-
- let distance_from_center = abs(clip_position.xy - uniforms.fb_size.xy / 2);
-
- // if(distance_from_center.x > size.x / 2 && distance_from_center.x < uniforms.fb_size.x - uniforms.x_offset * 2
- // || distance_from_center.y > size.y / 2 && distance_from_center.y < uniforms.fb_size.y
- // ) {
- // let x_pc = clamp(1.0 - (distance_from_center.x - size.x / 2) / border_width, 0.0, 1.0);
- // let y_pc = clamp(1.0 - (distance_from_center.y - size.y / 2) / border_width, 0.0, 1.0);
-
- // final_color = vec4<f32>(0, 0, 0, 0.75 * x_pc * y_pc);
- // }
-
- return final_color;
-}