Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add camera aspect ratio option (#603)

Richie McIlroy1e594b9c6721
diff --git a/apps/desktop/src/routes/camera.tsx b/apps/desktop/src/routes/camera.tsx
index d0025d35a..b79b5f14c 100644
--- a/apps/desktop/src/routes/camera.tsx
+++ b/apps/desktop/src/routes/camera.tsx
@@ -28,7 +28,7 @@ import {
namespace CameraWindow {
export type Size = "sm" | "lg";
- export type Shape = "round" | "square";
+ export type Shape = "round" | "square" | "full";
export type State = {
size: Size;
shape: Shape;
@@ -67,31 +67,44 @@ function Page() {
data: ImageData;
} | null>();
+ const [frameDimensions, setFrameDimensions] = createSignal<{
+ width: number;
+ height: number;
+ } | null>(null);
+
+ function imageDataHandler(imageData: { width: number; data: ImageData }) {
+ setLatestFrame(imageData);
+
+ const currentDimensions = frameDimensions();
+ if (
+ !currentDimensions ||
+ currentDimensions.width !== imageData.data.width ||
+ currentDimensions.height !== imageData.data.height
+ ) {
+ setFrameDimensions({
+ width: imageData.data.width,
+ height: imageData.data.height,
+ });
+ }
+
+ const ctx = cameraCanvasRef?.getContext("2d");
+ ctx?.putImageData(imageData.data, 0, 0);
+ }
+
const [ws, isConnected] = createImageDataWS(
`ws://localhost:${cameraWsPort}`,
- (imageData) => {
- setLatestFrame(imageData);
- const ctx = cameraCanvasRef?.getContext("2d");
- ctx?.putImageData(imageData.data, 0, 0);
- }
+ imageDataHandler
);
- // Attempt to reconnect every 5 seconds if not connected
const reconnectInterval = setInterval(() => {
if (!isConnected()) {
console.log("Attempting to reconnect...");
ws.close();
- // Create a new WebSocket connection
const newWs = createImageDataWS(
`ws://localhost:${cameraWsPort}`,
- (imageData) => {
- setLatestFrame(imageData);
- const ctx = cameraCanvasRef?.getContext("2d");
- ctx?.putImageData(imageData.data, 0, 0);
- }
+ imageDataHandler
);
- // Update the ws reference
Object.assign(ws, newWs[0]);
}
}, 5000);
@@ -102,21 +115,32 @@ function Page() {
});
const [windowSize] = createResource(
- () => state.size,
- async (size) => {
+ () =>
+ [
+ state.size,
+ state.shape,
+ frameDimensions()?.width,
+ frameDimensions()?.height,
+ ] as const,
+ async ([size, shape, frameWidth, frameHeight]) => {
const monitor = await currentMonitor();
- const windowSize = size === "sm" ? 230 : 400;
- const windowHeight = windowSize + BAR_HEIGHT;
+ const base = size === "sm" ? 230 : 400;
+ const aspect = frameWidth && frameHeight ? frameWidth / frameHeight : 1;
+ const windowWidth =
+ shape === "full" ? (aspect >= 1 ? base * aspect : base) : base;
+ const windowHeight =
+ shape === "full" ? (aspect >= 1 ? base : base / aspect) : base;
+ const totalHeight = windowHeight + BAR_HEIGHT;
if (!monitor) return;
const scalingFactor = monitor.scaleFactor;
- const width = monitor.size.width / scalingFactor - windowSize - 100;
- const height = monitor.size.height / scalingFactor - windowHeight - 100;
+ const width = monitor.size.width / scalingFactor - windowWidth - 100;
+ const height = monitor.size.height / scalingFactor - totalHeight - 100;
const currentWindow = getCurrentWindow();
- currentWindow.setSize(new LogicalSize(windowSize, windowHeight));
+ currentWindow.setSize(new LogicalSize(windowWidth, totalHeight));
currentWindow.setPosition(
new LogicalPosition(
width + monitor.position.toLogical(scalingFactor).x,
@@ -124,7 +148,7 @@ function Page() {
)
);
- return { width, height, size: windowSize };
+ return { width, height, size: base, windowWidth, windowHeight };
}
);
@@ -163,12 +187,18 @@ function Page() {
<IconCapEnlarge class="size-5.5" />
</ControlButton>
<ControlButton
- pressed={state.shape === "square"}
+ pressed={state.shape !== "round"}
onClick={() =>
- setState("shape", (s) => (s === "round" ? "square" : "round"))
+ setState("shape", (s) =>
+ s === "round" ? "square" : s === "square" ? "full" : "round"
+ )
}
>
- <IconCapSquare class="size-5.5" />
+ {state.shape === "round" && <IconCapCircle class="size-5.5" />}
+ {state.shape === "square" && <IconCapSquare class="size-5.5" />}
+ {state.shape === "full" && (
+ <IconLucideRectangleHorizontal class="size-5.5" />
+ )}
</ControlButton>
<ControlButton
pressed={state.mirrored}
@@ -193,25 +223,33 @@ function Page() {
const aspectRatio =
latestFrame().data.width / latestFrame().data.height;
- const windowWidth = windowSize.latest?.size ?? 0;
+ const base = windowSize.latest?.size ?? 0;
+ const winWidth = windowSize.latest?.windowWidth ?? base;
+ const winHeight = windowSize.latest?.windowHeight ?? base;
+
+ if (state.shape === "full") {
+ return {
+ width: `${winWidth}px`,
+ height: `${winHeight}px`,
+ transform: state.mirrored ? "scaleX(-1)" : "scaleX(1)",
+ };
+ }
const size = (() => {
if (aspectRatio > 1)
return {
- width: windowWidth * aspectRatio,
- height: windowWidth,
+ width: base * aspectRatio,
+ height: base,
};
else
return {
- width: windowWidth,
- height: windowWidth * aspectRatio,
+ width: base,
+ height: base * aspectRatio,
};
})();
- const left =
- aspectRatio > 1 ? (size.width - windowWidth) / 2 : 0;
- const top =
- aspectRatio > 1 ? 0 : (windowWidth - size.height) / 2;
+ const left = aspectRatio > 1 ? (size.width - base) / 2 : 0;
+ const top = aspectRatio > 1 ? 0 : (base - size.height) / 2;
return {
width: `${size.width}px`,
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index e547b3f44..eddb0837d 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -42,6 +42,7 @@ import { Toggle } from "~/components/Toggle";
import { generalSettingsStore } from "~/store";
import {
type BackgroundSource,
+ CameraShape,
StereoMode,
TimelineSegment,
ZoomSegment,
@@ -182,6 +183,17 @@ const STEREO_MODES = [
{ name: "Mono R", value: "monoR" },
] satisfies Array<{ name: string; value: StereoMode }>;
+const CAMERA_SHAPES = [
+ {
+ name: "Square",
+ value: "square",
+ },
+ {
+ name: "Source",
+ value: "source",
+ },
+] satisfies Array<{ name: string; value: CameraShape }>;
+
const BACKGROUND_THEMES = {
macOS: "macOS",
dark: "Dark",
@@ -1519,6 +1531,65 @@ function CameraConfig(props: { scrollRef: HTMLDivElement }) {
onChange={(mirror) => setProject("camera", "mirror", mirror)}
/>
</Subfield>
+ <Subfield name="Shape">
+ <KSelect<{ name: string; value: CameraShape }>
+ options={CAMERA_SHAPES}
+ optionValue="value"
+ optionTextValue="name"
+ value={CAMERA_SHAPES.find(
+ (v) => v.value === project.camera.shape
+ )}
+ onChange={(v) => {
+ if (v) setProject("camera", "shape", v.value);
+ }}
+ disallowEmptySelection
+ itemComponent={(props) => (
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
+ <KSelect.ItemLabel class="flex-1">
+ {props.item.rawValue.name}
+ </KSelect.ItemLabel>
+ </MenuItem>
+ )}
+ >
+ <KSelect.Trigger class="flex flex-row gap-2 items-center px-2 w-full h-8 rounded-lg transition-colors bg-gray-3 disabled:text-gray-11">
+ <KSelect.Value<{
+ name: string;
+ value: StereoMode;
+ }> class="flex-1 text-sm text-left truncate text-[--gray-500] font-normal">
+ {(state) => <span>{state.selectedOption().name}</span>}
+ </KSelect.Value>
+ <KSelect.Icon<ValidComponent>
+ as={(props) => (
+ <IconCapChevronDown
+ {...props}
+ class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180 text-[--gray-500]"
+ />
+ )}
+ />
+ </KSelect.Trigger>
+ <KSelect.Portal>
+ <PopperContent<typeof KSelect.Content>
+ as={KSelect.Content}
+ class={cx(topSlideAnimateClasses, "z-50")}
+ >
+ <MenuItemList<typeof KSelect.Listbox>
+ class="overflow-y-auto max-h-32"
+ as={KSelect.Listbox}
+ />
+ </PopperContent>
+ </KSelect.Portal>
+ </KSelect>
+ </Subfield>
+
+ {/* <Subfield name="Use Camera Aspect Ratio">
+ <Toggle
+ checked={project.camera.use_camera_aspect}
+ onChange={(v) => setProject("camera", "use_camera_aspect", v)}
+ />
+ </Subfield> */}
</div>
</Field>
{/** Dashed divider */}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index d0a9e35e7..1bf6982a8 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -294,8 +294,9 @@ export type AuthenticationInvalid = null
export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; inset: number; crop: Crop | null; shadow?: number; advancedShadow?: ShadowConfiguration | null }
export type BackgroundSource = { type: "wallpaper"; path: string | null } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number] } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number }
export type Bounds = { x: number; y: number; width: number; height: number }
-export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition; size: number; zoom_size: number | null; rounding?: number; shadow?: number; advanced_shadow?: ShadowConfiguration | null }
+export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition; size: number; zoom_size: number | null; rounding?: number; shadow?: number; advanced_shadow?: ShadowConfiguration | null; shape?: CameraShape }
export type CameraPosition = { x: CameraXPosition; y: CameraYPosition }
+export type CameraShape = "square" | "source"
export type CameraXPosition = "left" | "center" | "right"
export type CameraYPosition = "top" | "bottom"
export type CaptionData = { segments: CaptionSegment[]; settings: CaptionSettings | null }
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index b40d850ff..3e29d07c3 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -235,6 +235,16 @@ pub struct Camera {
pub shadow: f32,
#[serde(default)]
pub advanced_shadow: Option<ShadowConfiguration>,
+ #[serde(default)]
+ pub shape: CameraShape,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, Type, Default)]
+#[serde(rename_all = "camelCase")]
+pub enum CameraShape {
+ #[default]
+ Square,
+ Source,
}
impl Camera {
@@ -262,6 +272,7 @@ impl Default for Camera {
opacity: 44.2,
blur: 10.5,
}),
+ shape: CameraShape::Square,
}
}
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index e2dac5153..25467af87 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1,7 +1,7 @@
use anyhow::Result;
use cap_project::{
- AspectRatio, CameraXPosition, CameraYPosition, Crop, CursorEvents, ProjectConfiguration,
- RecordingMeta, StudioRecordingMeta, XY,
+ AspectRatio, CameraShape, CameraXPosition, CameraYPosition, Crop, CursorEvents,
+ ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY,
};
use composite_frame::CompositeVideoFrameUniforms;
use core::f64;
@@ -768,10 +768,26 @@ impl ProjectUniforms {
let zoomed_size =
(zoom.t as f32) * zoom_size * base_size + (1.0 - zoom.t as f32) * base_size;
- let size = [
- min_axis * zoomed_size + CAMERA_PADDING,
- min_axis * zoomed_size + CAMERA_PADDING,
- ];
+ let aspect = frame_size[0] / frame_size[1];
+ let size = match project.camera.shape {
+ CameraShape::Source => {
+ if aspect >= 1.0 {
+ [
+ (min_axis * zoomed_size + CAMERA_PADDING) * aspect,
+ min_axis * zoomed_size + CAMERA_PADDING,
+ ]
+ } else {
+ [
+ min_axis * zoomed_size + CAMERA_PADDING,
+ (min_axis * zoomed_size + CAMERA_PADDING) / aspect,
+ ]
+ }
+ }
+ CameraShape::Square => [
+ min_axis * zoomed_size + CAMERA_PADDING,
+ min_axis * zoomed_size + CAMERA_PADDING,
+ ],
+ };
let position = {
let x = match &project.camera.position.x {
@@ -800,18 +816,21 @@ impl ProjectUniforms {
CompositeVideoFrameUniforms {
output_size,
frame_size,
- 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],
- ],
+ crop_bounds: match project.camera.shape {
+ CameraShape::Source => [0.0, 0.0, frame_size[0], frame_size[1]],
+ CameraShape::Square => [
+ (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: [
target_bounds[2] - target_bounds[0],
target_bounds[3] - target_bounds[1],
],
- rounding_px: project.camera.rounding / 100.0 * 0.5 * size[0],
+ rounding_px: project.camera.rounding / 100.0 * 0.5 * size[0].min(size[1]),
mirror_x: if project.camera.mirror { 1.0 } else { 0.0 },
velocity_uv: [0.0, 0.0],
motion_blur_amount,
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index 09ff520c5..d20fda030 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -15,6 +15,7 @@ declare global {
const IconCapCaptions: typeof import('~icons/cap/captions.jsx')['default']
const IconCapCheck: typeof import("~icons/cap/check.jsx")["default"]
const IconCapChevronDown: typeof import('~icons/cap/chevron-down.jsx')['default']
+ const IconCapCircle: typeof import('~icons/cap/circle.jsx')['default']
const IconCapCircleCheck: typeof import('~icons/cap/circle-check.jsx')['default']
const IconCapCirclePlus: typeof import('~icons/cap/circle-plus.jsx')['default']
const IconCapCircleX: typeof import('~icons/cap/circle-x.jsx')['default']
@@ -67,6 +68,7 @@ declare global {
const IconCapTrash: typeof import('~icons/cap/trash.jsx')['default']
const IconCapUndo: typeof import('~icons/cap/undo.jsx')['default']
const IconCapUpload: typeof import('~icons/cap/upload.jsx')['default']
+ const IconCapWindow: typeof import('~icons/cap/window.jsx')['default']
const IconCapX: typeof import('~icons/cap/x.jsx')['default']
const IconCapZoomIn: typeof import('~icons/cap/zoom-in.jsx')['default']
const IconCapZoomOut: typeof import('~icons/cap/zoom-out.jsx')['default']
@@ -93,6 +95,9 @@ declare global {
const IconLucideMicOff: typeof import('~icons/lucide/mic-off.jsx')['default']
const IconLucideMonitor: typeof import('~icons/lucide/monitor.jsx')['default']
const IconLucideRabbit: typeof import("~icons/lucide/rabbit.jsx")["default"]
+ const IconLucideRectangle: typeof import('~icons/lucide/rectangle.jsx')['default']
+ const IconLucideRectangleHorizontal: typeof import('~icons/lucide/rectangle-horizontal.jsx')['default']
+ const IconLucideRectangleSquare: typeof import('~icons/lucide/rectangle-square.jsx')['default']
const IconLucideRotateCcw: typeof import('~icons/lucide/rotate-ccw.jsx')['default']
const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default']
const IconLucideSquarePlay: typeof import('~icons/lucide/square-play.jsx')['default']