Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

settings design + dynamic aspect ratios (#85)

Brendan Allanf8137fa357ec
diff --git a/apps/desktop/app.config.ts b/apps/desktop/app.config.ts
index 02b5134f7..dea69fb48 100644
--- a/apps/desktop/app.config.ts
+++ b/apps/desktop/app.config.ts
@@ -1,5 +1,6 @@
import { defineConfig } from "@solidjs/start/config";
import capUIPlugin from "@cap/ui-solid/vite";
+import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({
ssr: false,
@@ -19,6 +20,12 @@ export default defineConfig({
// 3. to make use of `TAURI_DEBUG` and other env variables
// https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
envPrefix: ["VITE_", "TAURI_"],
- plugins: [capUIPlugin],
+ plugins: [
+ capUIPlugin,
+ tsconfigPaths({
+ // If this isn't set Vinxi hangs on startup
+ root: ".",
+ }),
+ ],
}),
});
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 462f85d3c..4e55fe1dd 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -55,6 +55,7 @@
"@tauri-apps/cli": ">=2.0.0-rc.0",
"@types/dom-webcodecs": "^0.1.11",
"typescript": "^5.2.2",
- "vite": "^5.4.3"
+ "vite": "^5.4.3",
+ "vite-tsconfig-paths": "^5.0.1"
}
}
diff --git a/apps/desktop/src-tauri/src/editor.rs b/apps/desktop/src-tauri/src/editor.rs
index fb51457d8..4a6f0bf3d 100644
--- a/apps/desktop/src-tauri/src/editor.rs
+++ b/apps/desktop/src-tauri/src/editor.rs
@@ -7,6 +7,8 @@ use tokio::{
task::JoinHandle,
};
+use crate::editor_instance::SocketMessage;
+
struct EditorState {
config: ProjectConfiguration,
playback_position: u32,
@@ -107,7 +109,7 @@ pub enum RendererMessage {
pub struct Renderer {
rx: mpsc::Receiver<RendererMessage>,
- frame_tx: mpsc::UnboundedSender<Vec<u8>>,
+ frame_tx: mpsc::UnboundedSender<SocketMessage>,
render_constants: Arc<RenderVideoConstants>,
}
@@ -118,7 +120,7 @@ pub struct RendererHandle {
impl Renderer {
pub fn spawn(
render_constants: Arc<RenderVideoConstants>,
- frame_tx: mpsc::UnboundedSender<Vec<u8>>,
+ frame_tx: mpsc::UnboundedSender<SocketMessage>,
) -> RendererHandle {
let (tx, rx) = mpsc::channel(4);
@@ -168,7 +170,13 @@ impl Renderer {
.await
.unwrap();
- frame_tx.send(frame).ok();
+ frame_tx
+ .send(SocketMessage::Frame {
+ data: frame,
+ width: uniforms.output_size.0,
+ height: uniforms.output_size.1,
+ })
+ .ok();
finished.send(()).ok();
}));
}
diff --git a/apps/desktop/src-tauri/src/editor_instance.rs b/apps/desktop/src-tauri/src/editor_instance.rs
index 296c6aada..9e7513bd6 100644
--- a/apps/desktop/src-tauri/src/editor_instance.rs
+++ b/apps/desktop/src-tauri/src/editor_instance.rs
@@ -15,6 +15,7 @@ type PreviewFrameInstruction = (u32, ProjectConfiguration);
pub struct EditorState {
pub playhead_position: u32,
pub playback_task: Option<PlaybackHandle>,
+ pub preview_task: Option<tokio::task::JoinHandle<()>>,
}
pub struct EditorInstance {
@@ -57,12 +58,9 @@ impl EditorInstance {
let recordings = ProjectRecordings::new(&meta);
- const OUTPUT_SIZE: (u32, u32) = (1920, 1080);
-
let render_options = RenderOptions {
screen_size: (recordings.display.width, recordings.display.height),
camera_size: recordings.camera.as_ref().map(|c| (c.width, c.height)),
- output_size: OUTPUT_SIZE,
};
let screen_decoder =
@@ -126,12 +124,14 @@ impl EditorInstance {
state: Mutex::new(EditorState {
playhead_position: 0,
playback_task: None,
+ preview_task: None,
}),
on_state_change: Box::new(on_state_change),
preview_tx,
});
- this.clone().spawn_preview_renderer(preview_rx);
+ this.state.lock().await.preview_task =
+ Some(this.clone().spawn_preview_renderer(preview_rx));
this
}
@@ -147,6 +147,10 @@ impl EditorInstance {
println!("stopping playback");
handle.stop();
};
+ if let Some(task) = state.preview_task.take() {
+ println!("stopping preview");
+ task.abort();
+ }
}
pub async fn modify_and_emit_state(&self, modify: impl Fn(&mut EditorState)) {
@@ -207,10 +211,10 @@ impl EditorInstance {
fn spawn_preview_renderer(
self: Arc<Self>,
mut preview_rx: watch::Receiver<Option<PreviewFrameInstruction>>,
- ) {
+ ) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
loop {
- preview_rx.changed().await.ok();
+ preview_rx.changed().await.unwrap();
let Some((frame_number, project)) = preview_rx.borrow().deref().clone() else {
continue;
};
@@ -224,7 +228,7 @@ impl EditorInstance {
let Some((screen_frame, camera_frame)) =
self.decoders.get_frames((time * FPS as f64) as u32).await
else {
- return;
+ continue;
};
self.renderer
@@ -236,13 +240,21 @@ impl EditorInstance {
)
.await;
}
- });
+ })
}
}
pub const FRAMES_WS_PATH: &str = "/frames-ws";
-async fn create_frames_ws(frame_rx: mpsc::UnboundedReceiver<Vec<u8>>) -> u16 {
+pub enum SocketMessage {
+ Frame {
+ data: Vec<u8>,
+ width: u32,
+ height: u32,
+ },
+}
+
+async fn create_frames_ws(frame_rx: mpsc::UnboundedReceiver<SocketMessage>) -> u16 {
use axum::{
extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
@@ -253,7 +265,7 @@ async fn create_frames_ws(frame_rx: mpsc::UnboundedReceiver<Vec<u8>>) -> u16 {
};
use tokio::sync::{mpsc::UnboundedReceiver, Mutex};
- type RouterState = Arc<Mutex<UnboundedReceiver<Vec<u8>>>>;
+ type RouterState = Arc<Mutex<UnboundedReceiver<SocketMessage>>>;
async fn ws_handler(
ws: WebSocketUpgrade,
@@ -274,8 +286,17 @@ async fn create_frames_ws(frame_rx: mpsc::UnboundedReceiver<Vec<u8>>) -> u16 {
break;
}
msg = rx.recv() => {
- if let Some(chunk) = msg {
- socket.send(Message::Binary(chunk)).await.unwrap();
+ let Some(chunk) = msg else {
+ continue;
+ };
+
+ match chunk {
+ SocketMessage::Frame { width, height, mut data } => {
+ data.extend_from_slice(&height.to_le_bytes());
+ data.extend_from_slice(&width.to_le_bytes());
+
+ socket.send(Message::Binary(data)).await.unwrap();
+ }
}
}
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index b3167dab4..bb8e579fc 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -16,6 +16,7 @@ use auth::AuthStore;
use camera::{create_camera_window, list_cameras};
use cap_ffmpeg::FFmpeg;
use cap_project::{ProjectConfiguration, RecordingMeta, SharingMeta};
+use cap_rendering::ProjectUniforms;
use cap_utils::create_named_pipe;
use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
use editor_instance::{EditorInstance, EditorState, FRAMES_WS_PATH};
@@ -445,6 +446,8 @@ async fn render_to_file_impl(
let output_path_clone = output_path.clone();
let recording_dir_clone = recording_dir.clone();
+ let output_size = ProjectUniforms::get_output_size(&options, &project);
+
let ffmpeg_handle = tokio::spawn({
let project = project.clone();
async move {
@@ -496,8 +499,8 @@ async fn render_to_file_impl(
create_named_pipe(&video_pipe_path).unwrap();
ffmpeg.add_input(cap_ffmpeg::FFmpegRawVideoInput {
- width: options.output_size.0,
- height: options.output_size.1,
+ width: output_size.0,
+ height: output_size.1,
fps: 30,
pix_fmt: "rgba",
input: video_pipe_path.clone().into_os_string(),
@@ -585,8 +588,8 @@ async fn render_to_file_impl(
// Save the first frame as a screenshot and thumbnail
if let Some(frame_data) = first_frame {
- let width = options.output_size.0;
- let height = options.output_size.1;
+ let width = output_size.0;
+ let height = output_size.1;
let rgba_img: ImageBuffer<Rgba<u8>, Vec<u8>> =
ImageBuffer::from_raw(width, height, frame_data)
.expect("Failed to create image from frame data");
@@ -1250,6 +1253,28 @@ async fn open_feedback_window(app: AppHandle) {
window.set_traffic_lights_inset(14.0, 22.0).unwrap();
}
+#[tauri::command]
+#[specta::specta]
+async fn open_settings_window(app: AppHandle) {
+ let window =
+ WebviewWindow::builder(&app, "settings", tauri::WebviewUrl::App("/settings".into()))
+ .title("Cap Settings")
+ .inner_size(600.0, 450.0)
+ .resizable(true)
+ .maximized(false)
+ .shadow(true)
+ .accept_first_mouse(true)
+ .transparent(true)
+ .hidden_title(true)
+ .title_bar_style(tauri::TitleBarStyle::Overlay)
+ .build()
+ .unwrap();
+
+ window.create_overlay_titlebar().unwrap();
+ #[cfg(target_os = "macos")]
+ window.set_traffic_lights_inset(14.0, 22.0).unwrap();
+}
+
#[tauri::command]
#[specta::specta]
async fn upload_rendered_video(
@@ -1367,7 +1392,8 @@ pub fn run() {
permissions::request_permission,
upload_rendered_video,
get_recording_meta,
- open_feedback_window
+ open_feedback_window,
+ open_settings_window
])
.events(tauri_specta::collect_events![
RecordingOptionsChanged,
diff --git a/apps/desktop/src/routes/(main)/feedback.tsx b/apps/desktop/src/routes/(main)/feedback.tsx
index bcedc74cc..ec0c36820 100644
--- a/apps/desktop/src/routes/(main)/feedback.tsx
+++ b/apps/desktop/src/routes/(main)/feedback.tsx
@@ -1,5 +1,5 @@
import { Button } from "@cap/ui-solid";
-import { clientEnv } from "../../utils/env";
+import { clientEnv } from "~/utils/env";
import { createSignal, onMount, Show } from "solid-js";
import { authStore } from "../../store";
import { getCurrentWindow } from "@tauri-apps/api/window";
diff --git a/apps/desktop/src/routes/(main)/index.tsx b/apps/desktop/src/routes/(main)/index.tsx
index 757003a4c..4056066ba 100644
--- a/apps/desktop/src/routes/(main)/index.tsx
+++ b/apps/desktop/src/routes/(main)/index.tsx
@@ -6,14 +6,14 @@ import { createMutation } from "@tanstack/solid-query";
import { createEventListener } from "@solid-primitives/event-listener";
import { cache, createAsync, redirect, useNavigate } from "@solidjs/router";
-import { createCameraForLabel, createCameras } from "../../utils/media";
+import { createCameraForLabel, createCameras } from "~/utils/media";
import {
createAudioDevicesQuery,
createCurrentRecordingQuery,
createOptionsQuery,
createWindowsQuery,
-} from "../../utils/queries";
-import { type CaptureWindow, commands, events } from "../../utils/tauri";
+} from "~/utils/queries";
+import { type CaptureWindow, commands, events } from "~/utils/tauri";
import {
MenuItemList,
PopperContent,
@@ -21,7 +21,7 @@ import {
MenuItem,
topRightAnimateClasses,
} from "../editor/ui";
-import { authStore } from "../../store";
+import { authStore } from "~/store";
const getAuth = cache(async () => {
const value = await authStore.get();
@@ -112,8 +112,14 @@ export default function () {
Feedback
</Button>
</div>
- <div class="flex items-center justify-between">
+ <div class="flex items-center justify-between pb-[0.25rem]">
<IconCapLogoFull class="w-[90px] h-auto" />
+ {/*<button
+ type="button"
+ onClick={() => commands.openSettingsWindow()}
+ >
+ <IconCapSettings class="text-gray-400 hover:text-gray-500" />
+ </button>*/}
</div>
<KSelect<CaptureWindow | null>
options={windows.data ?? []}
@@ -393,6 +399,8 @@ import * as updater from "@tauri-apps/plugin-updater";
let hasChecked = false;
function createUpdateCheck() {
+ if (import.meta.env.DEV) return;
+
const navigate = useNavigate();
onMount(async () => {
diff --git a/apps/desktop/src/routes/(main)/signin.tsx b/apps/desktop/src/routes/(main)/signin.tsx
index 861d63be9..cdf23d40f 100644
--- a/apps/desktop/src/routes/(main)/signin.tsx
+++ b/apps/desktop/src/routes/(main)/signin.tsx
@@ -5,8 +5,8 @@ import { invoke } from "@tauri-apps/api/core";
import { action, redirect, useAction, useSubmission } from "@solidjs/router";
import callbackTemplate from "./callback.template";
-import { authStore } from "../../store";
-import { clientEnv } from "../../utils/env";
+import { authStore } from "~/store";
+import { clientEnv } from "~/utils/env";
import { getCurrentWindow } from "@tauri-apps/api/window";
const signInAction = action(async () => {
diff --git a/apps/desktop/src/routes/(main)/update.tsx b/apps/desktop/src/routes/(main)/update.tsx
index 62a0b10d2..7f26f1405 100644
--- a/apps/desktop/src/routes/(main)/update.tsx
+++ b/apps/desktop/src/routes/(main)/update.tsx
@@ -1,14 +1,6 @@
import { useNavigate } from "@solidjs/router";
import { check } from "@tauri-apps/plugin-updater";
-import {
- createResource,
- createSignal,
- Match,
- onMount,
- Show,
- Switch,
-} from "solid-js";
-import * as dialog from "@tauri-apps/plugin-dialog";
+import { createResource, Match, Show, Switch } from "solid-js";
import { relaunch } from "@tauri-apps/plugin-process";
import { Button } from "@cap/ui-solid";
diff --git a/apps/desktop/src/routes/camera.tsx b/apps/desktop/src/routes/camera.tsx
index 7557a170c..48c3ada27 100644
--- a/apps/desktop/src/routes/camera.tsx
+++ b/apps/desktop/src/routes/camera.tsx
@@ -18,9 +18,9 @@ import { createStore } from "solid-js/store";
import { ToggleButton as KToggleButton } from "@kobalte/core/toggle-button";
import { cx } from "cva";
-import { createCameraForLabel } from "../utils/media";
-import { createOptionsQuery } from "../utils/queries";
-import { commands } from "../utils/tauri";
+import { createCameraForLabel } from "~/utils/media";
+import { createOptionsQuery } from "~/utils/queries";
+import { commands } from "~/utils/tauri";
namespace CameraWindow {
export type Size = "sm" | "lg";
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 67e6a7d07..176689699 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -9,7 +9,7 @@ import { type Component, For, ParentProps, Show } from "solid-js";
import { Dynamic } from "solid-js/web";
import { createWritableMemo } from "@solid-primitives/memo";
-import type { BackgroundSource, CursorType } from "../../utils/tauri";
+import type { BackgroundSource, CursorType } from "~/utils/tauri";
import { useEditorContext } from "./context";
import { ComingSoonTooltip, Field, Slider, Subfield, Toggle } from "./ui";
import { DEFAULT_GRADIENT_FROM, DEFAULT_GRADIENT_TO } from "./projectConfig";
@@ -57,7 +57,7 @@ export function ConfigSidebar() {
return (
<KTabs
value={selectedTab()}
- class="flex flex-col shrink-0 overflow-x-hidden overflow-y-hidden w-[25.5rem]"
+ class="flex flex-col shrink-0 overflow-x-hidden overflow-y-hidden w-[25.5rem] z-10 bg-gray-50"
>
<KTabs.List class="h-[3.5rem] flex flex-row divide-x divide-gray-200 text-black/50 text-lg relative z-40 overflow-x-auto border-b border-gray-200">
<For
diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsx
index 3dfc16482..56e404b5b 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -20,7 +20,7 @@ import { createMutation } from "@tanstack/solid-query";
import { createEventListenerMap } from "@solid-primitives/event-listener";
import { convertFileSrc } from "@tauri-apps/api/core";
-import { events, commands } from "../../utils/tauri";
+import { events, commands } from "~/utils/tauri";
import { EditorContextProvider, useEditorContext } from "./context";
import {
Dialog,
@@ -153,7 +153,7 @@ function Inner() {
data-tauri-drag-region
>
<Header />
- <div class="rounded-2xl shadow border flex-1 flex flex-col divide-y bg-white">
+ <div class="rounded-2xl overflow-hidden shadow border flex-1 flex flex-col divide-y bg-white">
<div class="flex flex-row flex-1 divide-x overflow-y-hidden">
<Player />
<ConfigSidebar />
@@ -434,43 +434,35 @@ function Dialogs() {
display.height,
};
- batch(() => {
- if (original.position.x + diff.x < 0)
- setCrop("position", "x", 0);
- else if (
- original.position.x + diff.x >
- display.width - crop.size.x
- )
- setCrop(
- "position",
- "x",
+ const x = Math.floor(
+ (() => {
+ if (original.position.x + diff.x < 0)
+ return 0;
+ if (
+ original.position.x + diff.x >
display.width - crop.size.x
- );
- 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 >
- display.height - crop.size.y
- )
- setCrop(
- "position",
- "y",
+ )
+ return display.width - crop.size.x;
+
+ return original.position.x + diff.x;
+ })()
+ );
+
+ const y = Math.floor(
+ (() => {
+ if (original.position.y + diff.y < 0)
+ return 0;
+ if (
+ original.position.y + diff.y >
display.height - crop.size.y
- );
- else
- setCrop(
- "position",
- "y",
- original.position.y + diff.y
- );
- });
+ )
+ return display.height - crop.size.y;
+
+ return original.position.y + diff.y;
+ })()
+ );
+
+ setCrop("position", { x, y });
},
});
});
@@ -539,34 +531,41 @@ function Dialogs() {
setCrop(
"size",
"x",
- clamp(
- original.size.x + diff.x,
- MIN_SIZE,
- editorInstance.recordings
- .display.width -
- crop.position.x
+ Math.floor(
+ 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
+ Math.floor(
+ 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
+ Math.floor(
+ clamp(
+ original.size.x - diff.x,
+ MIN_SIZE,
+ editorInstance.recordings
+ .display.width
+ )
)
);
}
@@ -575,34 +574,41 @@ function Dialogs() {
setCrop(
"size",
"y",
- clamp(
- original.size.y + diff.y,
- MIN_SIZE,
- editorInstance.recordings
- .display.height -
- crop.position.y
+ Math.floor(
+ 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
+ Math.floor(
+ 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
+ Math.floor(
+ clamp(
+ original.size.y - diff.y,
+ MIN_SIZE,
+ editorInstance.recordings
+ .display.height
+ )
)
);
}
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index d5d3aa215..78d1ed65c 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -4,7 +4,8 @@ import { Match, Show, Switch, createResource } from "solid-js";
import { platform } from "@tauri-apps/plugin-os";
import { createStore, reconcile } from "solid-js/store";
-import { type RenderProgress, commands } from "../../utils/tauri";
+import { type RenderProgress, commands } from "~/utils/tauri";
+
import { useEditorContext } from "./context";
import { Dialog, DialogContent } from "./ui";
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 41e6cd5b3..6bd1257b4 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -5,8 +5,10 @@ import { cx } from "cva";
import { For, Show, Suspense, createEffect, createSignal } from "solid-js";
import { reconcile } from "solid-js/store";
-import { type AspectRatio, commands } from "../../utils/tauri";
+import { type AspectRatio, commands } from "~/utils/tauri";
import { useEditorContext } from "./context";
+import { OUTPUT_SIZE } from "./editorInstanceContext";
+import { ASPECT_RATIOS } from "./projectConfig";
import {
ComingSoonTooltip,
DropdownItem,
@@ -17,9 +19,8 @@ import {
dropdownContainerClasses,
topLeftAnimateClasses,
} from "./ui";
-import { ASPECT_RATIOS } from "./projectConfig";
-import { OUTPUT_SIZE } from "./editorInstanceContext";
import { formatTime } from "./utils";
+import { createElementBounds } from "@solid-primitives/bounds";
export function Player() {
const {
@@ -41,12 +42,16 @@ export function Player() {
const frame = currentFrame();
if (!frame) return;
const ctx = canvasRef.getContext("2d");
- ctx?.putImageData(frame, 0, 0);
+ ctx?.putImageData(frame.data, 0, 0);
});
+ const [canvasContainerRef, setCanvasContainerRef] =
+ createSignal<HTMLDivElement>();
+ const containerBounds = createElementBounds(canvasContainerRef);
+
return (
<div class="flex flex-col divide-y flex-1">
- <div class="flex flex-row justify-between font-medium p-[0.75rem] text-[0.875rem]">
+ <div class="flex flex-row justify-between font-medium p-[0.75rem] text-[0.875rem] z-10 bg-gray-50">
<div class="flex flex-row items-center gap-[0.5rem]">
<AspectRatioSelect />
<EditorButton
@@ -91,17 +96,66 @@ export function Player() {
</EditorButton>
</div>
</div>
- <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"
- // biome-ignore lint/style/noNonNullAssertion: ref
- ref={canvasRef!}
- id="canvas"
- width={OUTPUT_SIZE.width}
- height={OUTPUT_SIZE.height}
- />
+ <div ref={setCanvasContainerRef} class="bg-gray-100 flex-1 relative">
+ <Show when={currentFrame()}>
+ {(currentFrame) => {
+ const padding = 16;
+
+ const containerAspect = () => {
+ if (containerBounds.width && containerBounds.height) {
+ return containerBounds.width / containerBounds.height;
+ }
+
+ return 1;
+ };
+
+ const frameAspect = () =>
+ currentFrame().width / currentFrame().height;
+
+ const width = () => {
+ if (frameAspect() < containerAspect()) {
+ return (
+ ((containerBounds.height ?? 0) - padding * 2) * frameAspect()
+ );
+ }
+
+ return (containerBounds.width ?? 0) - padding * 2;
+ };
+
+ const height = () => {
+ if (frameAspect() > containerAspect()) {
+ return width() / frameAspect();
+ }
+
+ return (containerBounds.height ?? 0) - padding * 2;
+ };
+
+ return (
+ <canvas
+ style={{
+ left: `${Math.max(
+ ((containerBounds.width ?? 0) - width()) / 2,
+ padding
+ )}px`,
+ top: `${Math.max(
+ ((containerBounds.height ?? 0) - height()) / 2,
+ padding
+ )}px`,
+ width: `${width()}px`,
+ height: `${height()}px`,
+ }}
+ class="bg-blue-50 absolute rounded"
+ // biome-ignore lint/style/noNonNullAssertion: ref
+ ref={canvasRef!}
+ id="canvas"
+ width={currentFrame().width}
+ height={currentFrame().height}
+ />
+ );
+ }}
+ </Show>
</div>
- <div class="flex flex-row items-center p-[0.75rem]">
+ <div class="flex flex-row items-center p-[0.75rem] z-10 bg-gray-50">
<div class="flex-1" />
<div class="flex flex-row items-center justify-center gap-[0.5rem] text-gray-400 text-[0.875rem]">
<span>{formatTime(playbackTime())}</span>
@@ -164,7 +218,6 @@ function AspectRatioSelect() {
return (
<ComingSoonTooltip>
<KSelect<AspectRatio | "auto">
- disabled
value={project.aspectRatio ?? "auto"}
onChange={(v) => {
if (v === null) return;
@@ -178,7 +231,7 @@ function AspectRatioSelect() {
itemComponent={(props) => {
const item = () =>
ASPECT_RATIOS[
- props.item.rawValue === "auto" ? "wide" : props.item.rawValue
+ props.item.rawValue === "auto" ? "auto" : props.item.rawValue
];
return (
diff --git a/apps/desktop/src/routes/editor/Timeline.tsx b/apps/desktop/src/routes/editor/Timeline.tsx
index 52aab691c..3fa248208 100644
--- a/apps/desktop/src/routes/editor/Timeline.tsx
+++ b/apps/desktop/src/routes/editor/Timeline.tsx
@@ -1,7 +1,8 @@
import { createElementBounds } from "@solid-primitives/bounds";
import { For, Show, createRoot, createSignal, onMount } from "solid-js";
-import { commands } from "../../utils/tauri";
+import { commands } from "~/utils/tauri";
+
import { useEditorContext } from "./context";
import { createEventListenerMap } from "@solid-primitives/event-listener";
import { formatTime } from "./utils";
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index 09d479a21..3b0d8bc7a 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -1,21 +1,20 @@
import { createContextProvider } from "@solid-primitives/context";
-import { 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";
import { captureStoreUpdates, trackStore } from "@solid-primitives/deep";
import { createEventListener } from "@solid-primitives/event-listener";
+import { createUndoHistory } from "@solid-primitives/history";
+import { debounce } from "@solid-primitives/scheduled";
+import { createEffect, createSignal, on } from "solid-js";
+import { createStore, reconcile, unwrap } from "solid-js/store";
+import type { PresetsStore } from "../../store";
import {
- type SerializedEditorInstance,
type ProjectConfiguration,
- commands,
+ type SerializedEditorInstance,
type XY,
-} from "../../utils/tauri";
+ commands,
+} from "~/utils/tauri";
import { useEditorInstanceContext } from "./editorInstanceContext";
import { DEFAULT_PROJECT_CONFIG } from "./projectConfig";
-import type { PresetsStore } from "../createPresets";
-import { createElementBounds } from "@solid-primitives/bounds";
export type CurrentDialog =
| { type: "createPreset" }
diff --git a/apps/desktop/src/routes/editor/editorInstanceContext.ts b/apps/desktop/src/routes/editor/editorInstanceContext.ts
index 3b90bb9a3..b400556fd 100644
--- a/apps/desktop/src/routes/editor/editorInstanceContext.ts
+++ b/apps/desktop/src/routes/editor/editorInstanceContext.ts
@@ -1,18 +1,27 @@
import { createContextProvider } from "@solid-primitives/context";
import { createResource, createSignal } from "solid-js";
-import { events, commands } from "../../utils/tauri";
+import { events, commands } from "~/utils/tauri";
import { DEFAULT_PROJECT_CONFIG } from "./projectConfig";
-import { createPresets } from "../createPresets";
+import { createPresets } from "~/utils/createPresets";
export const OUTPUT_SIZE = {
width: 1920,
height: 1080,
};
+export type FrameData = { width: number; height: number; data: ImageData };
+
export const [EditorInstanceContextProvider, useEditorInstanceContext] =
createContextProvider((props: { videoId: string }) => {
- const [currentFrame, setCurrentFrame] = createSignal<ImageData>();
+ let res: ((frame: FrameData) => void) | undefined;
+
+ const [currentFrame, currentFrameActions] = createResource(
+ () =>
+ new Promise<FrameData>((r) => {
+ res = r;
+ })
+ );
const [editorInstance] = createResource(async () => {
const instance = await commands.createEditorInstance(props.videoId);
@@ -27,13 +36,35 @@ export const [EditorInstanceContextProvider, useEditorInstanceContext] =
};
ws.binaryType = "arraybuffer";
ws.onmessage = (event) => {
- const clamped = new Uint8ClampedArray(event.data);
+ const buffer = event.data as ArrayBuffer;
+ const clamped = new Uint8ClampedArray(buffer);
+
+ const widthArr = clamped.slice(clamped.length - 4);
+ const heightArr = clamped.slice(clamped.length - 8, clamped.length - 4);
+
+ const width =
+ widthArr[0] +
+ (widthArr[1] << 8) +
+ (widthArr[2] << 16) +
+ (widthArr[3] << 24);
+ const height =
+ heightArr[0] +
+ (heightArr[1] << 8) +
+ (heightArr[2] << 16) +
+ (heightArr[3] << 24);
+
const imageData = new ImageData(
- clamped,
- OUTPUT_SIZE.width,
- OUTPUT_SIZE.height
+ clamped.slice(0, clamped.length - 8),
+ width,
+ height
);
- setCurrentFrame(imageData);
+
+ if (res) {
+ res({ data: imageData, width, height });
+ res = undefined;
+ } else {
+ currentFrameActions.mutate({ data: imageData, width, height });
+ }
};
return instance.data;
diff --git a/apps/desktop/src/routes/editor/projectConfig.ts b/apps/desktop/src/routes/editor/projectConfig.ts
index 8932b5c65..2f5001db6 100644
--- a/apps/desktop/src/routes/editor/projectConfig.ts
+++ b/apps/desktop/src/routes/editor/projectConfig.ts
@@ -1,4 +1,4 @@
-import type { AspectRatio, ProjectConfiguration } from "../../utils/tauri";
+import type { AspectRatio, ProjectConfiguration } from "~/utils/tauri";
export type RGBColor = [number, number, number];
diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsx
index da95014ec..32b07d693 100644
--- a/apps/desktop/src/routes/in-progress-recording.tsx
+++ b/apps/desktop/src/routes/in-progress-recording.tsx
@@ -1,6 +1,6 @@
import { createEffect, createSignal, type ComponentProps } from "solid-js";
-import { commands } from "../utils/tauri";
+import { commands } from "~/utils/tauri";
import { createTimer } from "@solid-primitives/timer";
import { createMutation } from "@tanstack/solid-query";
diff --git a/apps/desktop/src/routes/mac-permissions.png b/apps/desktop/src/routes/mac-permissions.png
deleted file mode 100644
index 4e0965ee8..000000000
Binary files a/apps/desktop/src/routes/mac-permissions.png and /dev/null differ
diff --git a/apps/desktop/src/routes/permissions.tsx b/apps/desktop/src/routes/permissions.tsx
index 229f4d5f5..c58d973c5 100644
--- a/apps/desktop/src/routes/permissions.tsx
+++ b/apps/desktop/src/routes/permissions.tsx
@@ -1,7 +1,7 @@
import { Button } from "@cap/ui-solid";
import { exit } from "@tauri-apps/plugin-process";
-import { commands, type OSPermissionStatus } from "../utils/tauri";
+import { commands, type OSPermissionStatus } from "~/utils/tauri";
import {
createEffect,
createResource,
diff --git a/apps/desktop/src/routes/prev-recordings.tsx b/apps/desktop/src/routes/prev-recordings.tsx
index 0809ff29e..475d906dd 100644
--- a/apps/desktop/src/routes/prev-recordings.tsx
+++ b/apps/desktop/src/routes/prev-recordings.tsx
@@ -23,9 +23,9 @@ import { TransitionGroup } from "solid-transition-group";
import { createStore, produce } from "solid-js/store";
import { makePersisted } from "@solid-primitives/storage";
-import { commands, events } from "../utils/tauri";
+import { commands, events } from "~/utils/tauri";
import { DEFAULT_PROJECT_CONFIG } from "./editor/projectConfig";
-import { createPresets } from "./createPresets";
+import { createPresets } from "~/utils/createPresets";
type RecordingEntry = {
path: string;
diff --git a/apps/desktop/src/routes/recording-permissions.tsx b/apps/desktop/src/routes/recording-permissions.tsx
deleted file mode 100644
index 6f2d35d9e..000000000
--- a/apps/desktop/src/routes/recording-permissions.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { Dialog as KDialog } from "@kobalte/core/dialog";
-
-import MacPermissionsImage from "./mac-permissions.png";
-import { Dialog, DialogContent } from "./editor/ui";
-
-export default function () {
- return (
- <KDialog forceMount>
- <KDialog.Content class="text-sm divide-y rounded-[1.25rem] border overflow-hidden border-gray-200 font-[500] bg-gray-50">
- <Dialog.Header data-tauri-drag-region title="Recording Permissions" />
-
- <Dialog.Content class="space-y-[0.75rem]">
- <p class="text-gray-400">
- Open{" "}
- <span class="text-gray-500">
- Screen & System Audio Recording Settings
- </span>{" "}
- and enable Cap.
- </p>
- <img
- aria-hidden="true"
- src={MacPermissionsImage}
- class="border rounded-lg border-gray-200"
- />
- <p class="text-gray-400">
- After enabling Cap, restart the application for the changes to take
- effect.
- </p>
- </Dialog.Content>
-
- <Dialog.Footer>
- <Dialog.ConfirmButton>Settings</Dialog.ConfirmButton>
- </Dialog.Footer>
- </KDialog.Content>
- </KDialog>
- );
-}
diff --git a/apps/desktop/src/routes/settings.tsx b/apps/desktop/src/routes/settings.tsx
new file mode 100644
index 000000000..6d802a4b5
--- /dev/null
+++ b/apps/desktop/src/routes/settings.tsx
@@ -0,0 +1,20 @@
+import type { RouteSectionProps } from "@solidjs/router";
+
+import Header from "~/components/Header";
+
+export default function (props: RouteSectionProps) {
+ return (
+ <div class="rounded-[1.5rem] bg-gray-100 border border-gray-200 w-screen h-screen flex flex-col overflow-hidden">
+ <Header />
+ <div class="h-full flex flex-row divide-x divide-gray-200 text-[0.875rem] leading-[1.25rem]">
+ <ul class="min-w-[12rem] h-full p-[0.625rem]">
+ <li class="bg-gray-50 border border-gray-200 rounded-lg h-[2rem] px-[0.375rem] flex flex-row items-center gap-[0.375rem]">
+ <IconCapHotkeys class="size-[1.25rem]" />
+ <span>Shortcuts</span>
+ </li>
+ </ul>
+ <div class="flex-1 bg-gray-50">{props.children}</div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/routes/settings/hotkeys.tsx b/apps/desktop/src/routes/settings/hotkeys.tsx
new file mode 100644
index 000000000..f0ef72541
--- /dev/null
+++ b/apps/desktop/src/routes/settings/hotkeys.tsx
@@ -0,0 +1,27 @@
+import { Button } from "@cap/ui-solid";
+import { For } from "solid-js";
+
+export default function () {
+ return (
+ <div class="flex flex-col w-full h-full divide-y divide-gray-200">
+ <ul class="flex-1 p-[0.625rem] flex flex-col gap-[0.5rem] w-full">
+ <For each={["Start Recording", "Stop Recording"]}>
+ {(item) => (
+ <li class="w-full flex flex-row justify-between items-center">
+ <span>{item}</span>
+ <button
+ type="button"
+ class="w-[9rem] h-[2rem] border border-gray-200 rounded-lg text-gray-400"
+ >
+ Ctrl + Alt + R
+ </button>
+ </li>
+ )}
+ </For>
+ </ul>
+ <div class="flex flex-row-reverse p-[1rem]">
+ <Button variant="secondary">Restore Defaults</Button>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/routes/settings/index.tsx b/apps/desktop/src/routes/settings/index.tsx
new file mode 100644
index 000000000..11977a3c8
--- /dev/null
+++ b/apps/desktop/src/routes/settings/index.tsx
@@ -0,0 +1,5 @@
+import { Navigate } from "@solidjs/router";
+
+export default function () {
+ return <Navigate href="hotkeys" />;
+}
diff --git a/apps/desktop/src/routes/window-capture-occluder.tsx b/apps/desktop/src/routes/window-capture-occluder.tsx
index 508f5adbb..4878ebbc4 100644
--- a/apps/desktop/src/routes/window-capture-occluder.tsx
+++ b/apps/desktop/src/routes/window-capture-occluder.tsx
@@ -1,5 +1,5 @@
import { Show, Suspense } from "solid-js";
-import { createCurrentRecordingQuery } from "../utils/queries";
+import { createCurrentRecordingQuery } from "~/utils/queries";
export default function () {
const currentRecording = createCurrentRecordingQuery();
diff --git a/apps/desktop/src/store.ts b/apps/desktop/src/store.ts
index 514438f57..cbcc4125c 100644
--- a/apps/desktop/src/store.ts
+++ b/apps/desktop/src/store.ts
@@ -1,6 +1,6 @@
import { Store } from "@tauri-apps/plugin-store";
-import type { AuthStore, ProjectConfiguration } from "./utils/tauri";
+import type { AuthStore, ProjectConfiguration } from "~/utils/tauri";
const store = new Store("store");
diff --git a/apps/desktop/src/routes/createPresets.ts b/apps/desktop/src/utils/createPresets.ts
similarity index 93%
rename from apps/desktop/src/routes/createPresets.ts
rename to apps/desktop/src/utils/createPresets.ts
index 34163cb62..da71ff3ff 100644
--- a/apps/desktop/src/routes/createPresets.ts
+++ b/apps/desktop/src/utils/createPresets.ts
@@ -1,7 +1,7 @@
import { createResource, onCleanup } from "solid-js";
-import type { ProjectConfiguration } from "../utils/tauri";
-import { presetsStore, type PresetsStore } from "../store";
+import type { ProjectConfiguration } from "~/utils/tauri";
+import { presetsStore, type PresetsStore } from "~/store";
export type CreatePreset = {
name: string;
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index d7a5bd490..0e42e7875 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -173,6 +173,9 @@ async getRecordingMeta(id: string) : Promise<RecordingMeta> {
},
async openFeedbackWindow() : Promise<void> {
await TAURI_INVOKE("open_feedback_window");
+},
+async openSettingsWindow() : Promise<void> {
+ await TAURI_INVOKE("open_settings_window");
}
}
diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.json
index 4e5903705..9d33cb6e3 100644
--- a/apps/desktop/tsconfig.json
+++ b/apps/desktop/tsconfig.json
@@ -17,7 +17,10 @@
"types": ["vite/client", "vinxi/client", "@cap/ui-solid/types"],
/* Linting */
- "strict": true
+ "strict": true,
+ "paths": {
+ "~/*": ["./src/*"]
+ }
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 55b904c34..9082de364 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -39,8 +39,14 @@ pub struct XY<T> {
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct Crop {
- pub position: XY<f32>,
- pub size: XY<f32>,
+ pub position: XY<u32>,
+ pub size: XY<u32>,
+}
+
+impl Crop {
+ pub fn aspect_ratio(&self) -> f32 {
+ self.size.x as f32 / self.size.y as f32
+ }
}
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rs
index 4032764f3..3726f73f9 100644
--- a/crates/rendering/src/decoder.rs
+++ b/crates/rendering/src/decoder.rs
@@ -120,8 +120,6 @@ impl AsyncVideoDecoder {
while let Ok(r) = peekable_requests.recv() {
match r {
VideoDecoderMessage::GetFrame(frame_number, sender) => {
- // println!("received request for frame {frame_number}");
-
let mut sender = if let Some(cached) = cache.get(&frame_number) {
sender.send(Some(cached.clone())).ok();
continue;
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index b47ef61b9..627e77260 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -10,7 +10,7 @@ use wgpu::util::DeviceExt;
use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
use cap_project::{
- BackgroundSource, CameraXPosition, CameraYPosition, Crop, ProjectConfiguration, XY,
+ AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, ProjectConfiguration, XY,
};
use std::time::Instant;
@@ -22,7 +22,6 @@ pub use decoder::DecodedFrame;
pub struct RenderOptions {
pub camera_size: Option<(u32, u32)>,
pub screen_size: (u32, u32),
- pub output_size: (u32, u32),
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
@@ -194,12 +193,6 @@ pub struct RenderVideoConstants {
pub options: RenderOptions,
composite_video_frame_pipeline: CompositeVideoFramePipeline,
gradient_or_color_pipeline: GradientOrColorPipeline,
- pub output_texture: wgpu::Texture,
- pub output_texture_view: wgpu::TextureView,
- pub output_texture_size: wgpu::Extent3d,
- pub output_buffer: wgpu::Buffer,
- pub padded_bytes_per_row: u32,
- pub unpadded_bytes_per_row: u32,
}
impl RenderVideoConstants {
@@ -215,45 +208,6 @@ impl RenderVideoConstants {
.await
.map_err(|e| e.to_string())?;
- let output_texture_size = wgpu::Extent3d {
- width: options.output_size.0,
- height: options.output_size.1,
- depth_or_array_layers: 1,
- };
-
- let output_texture = device.create_texture(
- &(wgpu::TextureDescriptor {
- size: output_texture_size,
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8UnormSrgb,
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
- label: Some("output_texture"),
- view_formats: &[],
- }),
- );
-
- // Calculate the aligned bytes per row
- let align = COPY_BYTES_PER_ROW_ALIGNMENT;
- let unpadded_bytes_per_row = options.output_size.0 * 4;
- let padding = (align - (unpadded_bytes_per_row % align)) % align;
- let padded_bytes_per_row = unpadded_bytes_per_row + padding;
-
- // Ensure the padded_bytes_per_row is a multiple of 4 (32 bits)
- let padded_bytes_per_row = (padded_bytes_per_row + 3) & !3;
-
- let output_buffer_size = (padded_bytes_per_row * options.output_size.1) as u64;
-
- let output_buffer = device.create_buffer(
- &(wgpu::BufferDescriptor {
- size: output_buffer_size,
- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
- label: Some("Output Buffer"),
- mapped_at_creation: false,
- }),
- );
-
Ok(Self {
composite_video_frame_pipeline: CompositeVideoFramePipeline::new(&device),
gradient_or_color_pipeline: GradientOrColorPipeline::new(&device),
@@ -262,19 +216,13 @@ impl RenderVideoConstants {
queue,
device,
options,
- output_texture_size,
- output_texture_view: output_texture
- .create_view(&wgpu::TextureViewDescriptor::default()),
- output_texture,
- output_buffer,
- unpadded_bytes_per_row,
- padded_bytes_per_row,
})
}
}
#[derive(Clone, Debug)]
pub struct ProjectUniforms {
+ pub output_size: (u32, u32),
display: CompositeVideoFrameUniforms,
camera: Option<CompositeVideoFrameUniforms>,
}
@@ -285,48 +233,85 @@ const CAMERA_UV_WIDTH: f32 = 0.3;
const SCREEN_MAX_PADDING: f32 = 0.4;
impl ProjectUniforms {
+ fn get_crop(options: &RenderOptions, project: &ProjectConfiguration) -> Crop {
+ project.background.crop.clone().unwrap_or(Crop {
+ position: XY { x: 0, y: 0 },
+ size: XY {
+ x: options.screen_size.0,
+ y: options.screen_size.1,
+ },
+ })
+ }
+
+ fn get_padding(options: &RenderOptions, project: &ProjectConfiguration) -> f32 {
+ let crop = Self::get_crop(options, project);
+
+ let basis = u32::max(crop.size.x, crop.size.y);
+ let padding_factor = project.background.padding / 100.0 * SCREEN_MAX_PADDING;
+
+ basis as f32 * padding_factor
+ }
+
+ pub fn get_output_size(options: &RenderOptions, project: &ProjectConfiguration) -> (u32, u32) {
+ let crop = Self::get_crop(options, project);
+
+ let crop_aspect = crop.aspect_ratio();
+
+ let padding = Self::get_padding(options, project) * 2.0;
+
+ let aspect = match &project.aspect_ratio {
+ None => {
+ return (
+ (crop.size.x as f32 + padding) as u32,
+ (crop.size.y as f32 + padding) as u32,
+ );
+ }
+ Some(AspectRatio::Square) => 1.0,
+ Some(AspectRatio::Wide) => 16.0 / 9.0,
+ Some(AspectRatio::Vertical) => 9.0 / 16.0,
+ Some(AspectRatio::Classic) => 4.0 / 3.0,
+ Some(AspectRatio::Tall) => 3.0 / 4.0,
+ };
+
+ if crop_aspect > aspect {
+ (crop.size.x, (crop.size.x as f32 / aspect) as u32)
+ } else if crop_aspect < aspect {
+ ((crop.size.y as f32 * aspect) as u32, crop.size.y)
+ } else {
+ (crop.size.x, crop.size.y)
+ }
+ }
+
pub fn new(constants: &RenderVideoConstants, project: &ProjectConfiguration) -> Self {
let options = &constants.options;
- let output_size = [options.output_size.0 as f32, options.output_size.1 as f32];
- let output_aspect = output_size[0] / output_size[1];
+ let output_size = Self::get_output_size(options, project);
+ let output_aspect = output_size.0 as f32 / output_size.1 as f32;
let display = {
+ let output_size = [output_size.0 as f32, output_size.1 as f32];
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 crop = Self::get_crop(options, project);
+
+ let crop_bounds = [
+ crop.position.x as f32,
+ crop.position.y as f32,
+ (crop.position.x + crop.size.x) as f32,
+ (crop.position.y + crop.size.y) as f32,
+ ];
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 cropped_aspect = cropped_size[0] as f32 / cropped_size[1] as f32;
+ let padding = Self::get_padding(options, project);
let is_height_constrained = cropped_aspect <= output_aspect;
- let padding_factor = project.background.padding / 100.0 * SCREEN_MAX_PADDING;
-
- let padding = [
- output_size[0] * padding_factor * !is_height_constrained as u8 as f32,
- output_size[1] * padding_factor * is_height_constrained as u8 as f32,
- ];
let available_size = [
- output_size[0] - 2.0 * padding[0],
- output_size[1] - 2.0 * padding[1],
+ output_size[0] - 2.0 * padding,
+ output_size[1] - 2.0 * padding,
];
let target_size = if is_height_constrained {
@@ -341,9 +326,9 @@ impl ProjectUniforms {
];
let target_start = if is_height_constrained {
- [target_offset[0], padding[1]]
+ [target_offset[0], padding]
} else {
- [padding[0], target_offset[1]]
+ [padding, target_offset[1]]
};
let target_bounds = [
@@ -371,8 +356,10 @@ impl ProjectUniforms {
.camera_size
.filter(|_| !project.camera.hide)
.map(|camera_size| {
+ let output_size = [output_size.0 as f32, output_size.1 as f32];
+
let frame_size = [camera_size.0 as f32, camera_size.1 as f32];
- let min_axis = frame_size[0].min(frame_size[1]);
+ let min_axis = output_size[0].min(output_size[1]);
let size = [
min_axis * CAMERA_UV_WIDTH + CAMERA_PADDING,
@@ -420,7 +407,11 @@ impl ProjectUniforms {
}
});
- Self { display, camera }
+ Self {
+ output_size,
+ display,
+ camera,
+ }
}
}
@@ -431,10 +422,6 @@ pub async fn produce_frame(
composite_video_frame_pipeline,
gradient_or_color_pipeline,
queue,
- output_texture_size,
- output_buffer,
- padded_bytes_per_row,
- unpadded_bytes_per_row,
..
}: &RenderVideoConstants,
screen_frame: &Vec<u8>,
@@ -450,8 +437,8 @@ pub async fn produce_frame(
let output_texture_desc = wgpu::TextureDescriptor {
size: wgpu::Extent3d {
- width: options.output_size.0,
- height: options.output_size.1,
+ width: uniforms.output_size.0,
+ height: uniforms.output_size.1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
@@ -543,23 +530,6 @@ pub async fn produce_frame(
},
);
- // let padding = 30.0;
- // let frame_size = (frame_size.0 as f32, frame_size.1 as f32);
- // let output_size = (options.output_size.0 as f32, options.output_size.1 as f32);
- // let x_scale = output_size.0 / frame_size.0;
- // let target_bounds = [
- // padding,
- // padding,
- // output_size.0 - padding,
- // frame_size.1 * x_scale - padding * x_scale,
- // ];
- // let target_size = [
- // target_bounds[2] - target_bounds[0],
- // target_bounds[3] - target_bounds[1],
- // ];
- // let rounding_pc = 0.1;
- // let rounding_px = f32::min(target_size[0], target_size[1]) * 0.5 * rounding_pc;
-
do_render_pass(
&mut encoder,
get_either(texture_views, output_is_left),
@@ -567,16 +537,6 @@ pub async fn produce_frame(
composite_video_frame_pipeline.bind_group(
device,
&uniforms.display.to_buffer(device),
- // &dbg!(CompositeVideoFrameUniforms {
- // output_size: [output_size.0, output_size.1],
- // frame_size: [frame_size.0, frame_size.1],
- // crop_bounds: [0.0, 0.0, frame_size.0, frame_size.1],
- // target_bounds,
- // target_size,
- // rounding_px,
- // ..Default::default()
- // })
- // .to_buffer(device),
&texture_view,
get_either(texture_views, !output_is_left),
),
@@ -629,18 +589,6 @@ pub async fn produce_frame(
},
);
- // let padding = 30.0;
- // let frame_size = (camera_size.0 as f32, camera_size.1 as f32);
- // let output_size = (options.output_size.0 as f32, options.output_size.1 as f32);
- // let x_scale = output_size.0 / frame_size.0;
- // let target_bounds = [padding, padding, 300.0, 300.0];
- // let target_size = [
- // target_bounds[2] - target_bounds[0],
- // target_bounds[3] - target_bounds[1],
- // ];
- // let rounding_pc = 0.1;
- // let rounding_px = f32::min(target_size[0], target_size[1]) * 0.5 * rounding_pc;
-
do_render_pass(
&mut encoder,
get_either(texture_views, output_is_left),
@@ -648,21 +596,6 @@ pub async fn produce_frame(
composite_video_frame_pipeline.bind_group(
device,
&uniforms.to_buffer(device),
- // &dbg!(CompositeVideoFrameUniforms {
- // output_size: [output_size.0, output_size.1],
- // frame_size: [frame_size.0, frame_size.1],
- // crop_bounds: [
- // (frame_size.0 - frame_size.1) / 2.0,
- // 0.0,
- // frame_size.0 - (frame_size.0 - frame_size.1) / 2.0,
- // frame_size.1
- // ],
- // target_bounds,
- // target_size,
- // rounding_px,
- // ..Default::default()
- // })
- // .to_buffer(device),
&texture_view,
get_either(texture_views, !output_is_left),
),
@@ -673,6 +606,32 @@ pub async fn produce_frame(
queue.submit(std::iter::once(encoder.finish()));
+ let output_texture_size = wgpu::Extent3d {
+ width: uniforms.output_size.0,
+ height: uniforms.output_size.1,
+ depth_or_array_layers: 1,
+ };
+
+ // Calculate the aligned bytes per row
+ let align = COPY_BYTES_PER_ROW_ALIGNMENT;
+ let unpadded_bytes_per_row = uniforms.output_size.0 * 4;
+ let padding = (align - (unpadded_bytes_per_row % align)) % align;
+ let padded_bytes_per_row = unpadded_bytes_per_row + padding;
+
+ // Ensure the padded_bytes_per_row is a multiple of 4 (32 bits)
+ let padded_bytes_per_row = (padded_bytes_per_row + 3) & !3;
+
+ let output_buffer_size = (padded_bytes_per_row * uniforms.output_size.1) as u64;
+
+ let output_buffer = device.create_buffer(
+ &(wgpu::BufferDescriptor {
+ size: output_buffer_size,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ label: Some("Output Buffer"),
+ mapped_at_creation: false,
+ }),
+ );
+
{
let mut encoder = device.create_command_encoder(
&(wgpu::CommandEncoderDescriptor {
@@ -688,14 +647,14 @@ pub async fn produce_frame(
aspect: wgpu::TextureAspect::All,
},
wgpu::ImageCopyBuffer {
- buffer: output_buffer,
+ buffer: &output_buffer,
layout: wgpu::ImageDataLayout {
offset: 0,
- bytes_per_row: Some(*padded_bytes_per_row),
- rows_per_image: Some(options.output_size.1),
+ bytes_per_row: Some(padded_bytes_per_row),
+ rows_per_image: Some(uniforms.output_size.1),
},
},
- *output_texture_size,
+ output_texture_size,
);
queue.submit(std::iter::once(encoder.finish()));
@@ -719,9 +678,9 @@ pub async fn produce_frame(
let data = buffer_slice.get_mapped_range();
let padded_data: Vec<u8> = data.to_vec(); // Ensure the type is Vec<u8>
let mut image_data =
- Vec::with_capacity((options.output_size.0 * options.output_size.1 * 4) as usize);
- for chunk in padded_data.chunks(*padded_bytes_per_row as usize) {
- image_data.extend_from_slice(&chunk[..*unpadded_bytes_per_row as usize]);
+ Vec::with_capacity((uniforms.output_size.0 * uniforms.output_size.1 * 4) as usize);
+ for chunk in padded_data.chunks(padded_bytes_per_row as usize) {
+ image_data.extend_from_slice(&chunk[..unpadded_bytes_per_row as usize]);
}
// Unmap the buffer
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c858aa59e..488d3ab4d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -168,6 +168,9 @@ importers:
vite:
specifier: ^5.4.3
version: 5.4.3(@types/[email protected])([email protected])
+ vite-tsconfig-paths:
+ specifier: ^5.0.1
apps/embed:
dependencies:
@@ -212,7 +215,7 @@ importers:
next-auth:
specifier: ^4.24.5
react:
specifier: ^18.2.0
version: 18.2.0
@@ -506,16 +509,16 @@ importers:
version: 2.30.1
next:
specifier: 14.2.3
next-auth:
specifier: ^4.24.5
next-mdx-remote:
specifier: ^4.4.1
nextjs-cors:
specifier: ^2.2.0
posthog-js:
specifier: ^1.129.0
version: 1.129.0
@@ -673,7 +676,7 @@ importers:
version: 5.0.4
next:
specifier: 14.2.9
next-auth:
specifier: ^4.24.5
@@ -10762,6 +10765,16 @@ packages:
typescript:
optional: true
+ resolution: {integrity: sha512-ulNZP1SVpRDesxeMLON/LtWM8HIgAJEIVpVVhBM6gsmvQ8+Rh+ZG7FWGvHh7Ah3pRABwVJWklWCr/BTZSv0xnQ==}
+ engines: {node: ^18 || >=20}
+ hasBin: true
+ peerDependencies:
+ typescript: ^5.0.0
+ peerDependenciesMeta:
+ typescript:
+ optional: true
+
resolution: {integrity: sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==}
@@ -11290,6 +11303,14 @@ packages:
vite:
optional: true
+ resolution: {integrity: sha512-yqwv+LstU7NwPeNqajZzLEBVpUFU6Dugtb2P84FXuvaoYA+/70l9MHE+GYfYAycVyPSDYZ7mjOFuYBRqlEpTig==}
+ peerDependencies:
+ vite: '*'
+ peerDependenciesMeta:
+ vite:
+ optional: true
+
resolution: {integrity: sha512-AXXFaAJ8yebyqzoNB9fu2pHoo/nWX+xZlaRwoeYUxEqBO+Zj4msE5G+BhGBll9lYEKv9Hfks52PAF2X7qDYXQA==}
engines: {node: ^14.18.0 || >=16.0.0}
@@ -12763,7 +12784,7 @@ snapshots:
'@babel/traverse': 7.23.7
'@babel/types': 7.23.6
convert-source-map: 2.0.0
- debug: 4.3.4([email protected])
+ debug: 4.3.6
gensync: 1.0.0-beta.2
json5: 2.2.3
semver: 6.3.1
@@ -14221,7 +14242,7 @@ snapshots:
'@eslint/[email protected]':
dependencies:
ajv: 6.12.6
- debug: 4.3.4([email protected])
+ debug: 4.3.6
espree: 9.6.1
globals: 13.24.0
ignore: 5.3.1
@@ -14286,7 +14307,7 @@ snapshots:
'@humanwhocodes/[email protected]':
dependencies:
'@humanwhocodes/object-schema': 2.0.2
- debug: 4.3.4([email protected])
+ debug: 4.3.6
minimatch: 3.1.2
transitivePeerDependencies:
- supports-color
@@ -17570,7 +17591,7 @@ snapshots:
dependencies:
'@typescript-eslint/typescript-estree': 7.13.1([email protected])
'@typescript-eslint/utils': 7.13.1([email protected])([email protected])
- debug: 4.3.4([email protected])
+ debug: 4.3.6
eslint: 8.57.0
ts-api-utils: 1.3.0([email protected])
optionalDependencies:
@@ -17628,7 +17649,7 @@ snapshots:
dependencies:
'@typescript-eslint/types': 7.13.1
'@typescript-eslint/visitor-keys': 7.13.1
- debug: 4.3.4([email protected])
+ debug: 4.3.6
globby: 11.1.0
is-glob: 4.0.3
minimatch: 9.0.4
@@ -22324,13 +22345,13 @@ snapshots:
dependencies:
'@babel/runtime': 7.23.8
'@panva/hkdf': 1.1.1
cookie: 0.5.0
jose: 4.15.4
oauth: 0.9.15
openid-client: 5.6.4
preact: 10.19.3
@@ -22341,7 +22362,7 @@ snapshots:
optionalDependencies:
nodemailer: 6.9.8
dependencies:
'@babel/runtime': 7.23.8
'@panva/hkdf': 1.1.1
@@ -22358,6 +22379,23 @@ snapshots:
optionalDependencies:
nodemailer: 6.9.8
+ dependencies:
+ '@babel/runtime': 7.23.8
+ '@panva/hkdf': 1.1.1
+ cookie: 0.5.0
+ jose: 4.15.4
+ oauth: 0.9.15
+ openid-client: 5.6.4
+ preact: 10.19.3
+ preact-render-to-string: 5.2.6([email protected])
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ uuid: 8.3.2
+ optionalDependencies:
+ nodemailer: 6.9.8
+
dependencies:
'@mdx-js/mdx': 2.3.0
@@ -22371,7 +22409,7 @@ snapshots:
dependencies:
'@next/env': 14.2.3
'@swc/helpers': 0.5.5
@@ -22381,7 +22419,7 @@ snapshots:
postcss: 8.4.31
react: 18.2.0
react-dom: 18.2.0([email protected])
- styled-jsx: 5.1.1(@babel/[email protected])([email protected])
+ styled-jsx: 5.1.1(@babel/[email protected])([email protected])
optionalDependencies:
'@next/swc-darwin-arm64': 14.2.3
'@next/swc-darwin-x64': 14.2.3
@@ -22421,10 +22459,35 @@ snapshots:
- '@babel/core'
- babel-plugin-macros
+ dependencies:
+ '@next/env': 14.2.9
+ '@swc/helpers': 0.5.5
+ busboy: 1.6.0
+ caniuse-lite: 1.0.30001647
+ graceful-fs: 4.2.11
+ postcss: 8.4.31
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ styled-jsx: 5.1.1(@babel/[email protected])([email protected])
+ optionalDependencies:
+ '@next/swc-darwin-arm64': 14.2.9
+ '@next/swc-darwin-x64': 14.2.9
+ '@next/swc-linux-arm64-gnu': 14.2.9
+ '@next/swc-linux-arm64-musl': 14.2.9
+ '@next/swc-linux-x64-gnu': 14.2.9
+ '@next/swc-linux-x64-musl': 14.2.9
+ '@next/swc-win32-arm64-msvc': 14.2.9
+ '@next/swc-win32-ia32-msvc': 14.2.9
+ '@next/swc-win32-x64-msvc': 14.2.9
+ transitivePeerDependencies:
+ - '@babel/core'
+ - babel-plugin-macros
+
dependencies:
cors: 2.8.5
dependencies:
@@ -24118,6 +24181,13 @@ snapshots:
optionalDependencies:
'@babel/core': 7.23.7
+ dependencies:
+ client-only: 0.0.1
+ react: 18.2.0
+ optionalDependencies:
+ '@babel/core': 7.25.2
+
@@ -24134,7 +24204,7 @@ snapshots:
dependencies:
component-emitter: 1.3.1
cookiejar: 2.1.4
- debug: 4.3.4([email protected])
+ debug: 4.3.6
fast-safe-stringify: 2.1.1
form-data: 4.0.0
formidable: 2.1.2
@@ -24559,6 +24629,10 @@ snapshots:
optionalDependencies:
typescript: 5.5.4
+ optionalDependencies:
+ typescript: 5.5.4
+
dependencies:
'@types/json5': 0.0.29
@@ -25196,6 +25270,17 @@ snapshots:
- supports-color
- typescript
+ dependencies:
+ debug: 4.3.6
+ globrex: 0.1.2
+ tsconfck: 3.1.3([email protected])
+ optionalDependencies:
+ vite: 5.4.3(@types/[email protected])([email protected])
+ transitivePeerDependencies:
+ - supports-color
+ - typescript
+
dependencies:
esbuild: 0.18.20