Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

renderer: add transparent background for gif exporting (#1306)

Brendan Allan47a0e07d801a
diff --git a/Cargo.lock b/Cargo.lock
index 69d71f73d..6d1754b2b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1529,6 +1529,7 @@ dependencies = [
"cap-project",
"cap-video-decode",
"cidre 0.11.0",
+ "clap",
"ffmpeg-hw-device",
"ffmpeg-next",
"futures",
@@ -1540,6 +1541,7 @@ dependencies = [
"reactive_graph",
"resvg",
"serde",
+ "serde_json",
"specta",
"thiserror 1.0.69",
"tiny-skia",
diff --git a/apps/desktop/src/components/Tooltip.tsx b/apps/desktop/src/components/Tooltip.tsx
index 24a136f86..c208e7598 100644
--- a/apps/desktop/src/components/Tooltip.tsx
+++ b/apps/desktop/src/components/Tooltip.tsx
@@ -4,7 +4,7 @@ import { cx } from "cva";
import type { ComponentProps, JSX } from "solid-js";
interface Props extends ComponentProps<typeof KTooltip.Root> {
- content: JSX.Element;
+ content?: JSX.Element;
childClass?: string;
kbd?: string[];
}
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index b5ae2287b..f07cd4761 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -113,6 +113,7 @@ const BACKGROUND_COLORS = [
"#A9A9A9", // Dark Gray
"#FFFFFF", // White
"#000000", // Black
+ "#00000000", // Transparent
];
const BACKGROUND_GRADIENTS = [
@@ -1467,22 +1468,33 @@ function BackgroundConfig(props: { scrollRef: HTMLDivElement }) {
class="sr-only peer"
name="colorPicker"
onChange={(e) => {
- if (e.target.checked) {
- backgrounds.color = {
- type: "color",
- value: hexToRgb(color) ?? [0, 0, 0],
- };
- setProject(
- "background",
- "source",
- backgrounds.color,
- );
- }
+ if (!e.target.checked) return;
+
+ const rgbValue = hexToRgb(color);
+ if (!rgbValue) return;
+
+ const [r, g, b, a] = rgbValue;
+ backgrounds.color = {
+ type: "color",
+ value: [r, g, b],
+ alpha: a,
+ };
+
+ setProject(
+ "background",
+ "source",
+ backgrounds.color,
+ );
}}
/>
<div
class="rounded-lg transition-all duration-200 cursor-pointer size-8 peer-checked:hover:opacity-100 peer-hover:opacity-70 peer-checked:ring-2 peer-checked:ring-gray-500 peer-checked:ring-offset-2 peer-checked:ring-offset-gray-200"
- style={{ "background-color": color }}
+ style={{
+ background:
+ color === "#00000000"
+ ? CHECKERED_BUTTON_BACKGROUND
+ : color,
+ }}
/>
</label>
)}
@@ -2762,7 +2774,11 @@ function RgbInput(props: {
value={rgbToHex(props.value)}
onChange={(e) => {
const value = hexToRgb(e.target.value);
- if (value) props.onChange(value);
+ if (!value) return;
+
+ // RgbInput only handles RGB values, so extract RGB part if RGBA is returned
+ const [r, g, b] = value;
+ props.onChange([r, g, b]);
}}
/>
<TextInput
@@ -2775,14 +2791,24 @@ function RgbInput(props: {
setText(e.currentTarget.value);
const value = hexToRgb(e.target.value);
- if (value) props.onChange(value);
+ if (!value) return;
+
+ const [r, g, b] = value;
+ props.onChange([r, g, b]);
}}
onBlur={(e) => {
const value = hexToRgb(e.target.value);
- if (value) props.onChange(value);
- else {
+ if (value) {
+ const [r, g, b] = value;
+ // RgbInput only handles RGB values, so extract RGB part if RGBA is returned
+ props.onChange([r, g, b]);
+ } else {
setText(prevHex);
- props.onChange(hexToRgb(text())!);
+ const fallbackValue = hexToRgb(text());
+ if (!fallbackValue) return;
+
+ const [r, g, b] = fallbackValue;
+ props.onChange([r, g, b]);
}
}}
/>
@@ -2797,8 +2823,26 @@ function rgbToHex(rgb: [number, number, number]) {
.toUpperCase()}`;
}
-function hexToRgb(hex: string): [number, number, number] | null {
- const match = hex.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
+function hexToRgb(hex: string): [number, number, number, number] | null {
+ // Support both 6-digit (RGB) and 8-digit (RGBA) hex colors
+ const match = hex.match(
+ /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i,
+ );
if (!match) return null;
- return match.slice(1).map((c) => Number.parseInt(c, 16)) as any;
+
+ const [, r, g, b, a] = match;
+ const rgb = [
+ Number.parseInt(r, 16),
+ Number.parseInt(g, 16),
+ Number.parseInt(b, 16),
+ ] as const;
+
+ // If alpha is provided, return RGBA tuple
+ if (a) {
+ return [...rgb, Number.parseInt(a, 16)];
+ }
+
+ return [...rgb, 255];
}
+
+const CHECKERED_BUTTON_BACKGROUND = `url("data:image/svg+xml,%3Csvg width='16' height='16' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='8' height='8' fill='%23a0a0a0'/%3E%3Crect x='8' y='8' width='8' height='8' fill='%23a0a0a0'/%3E%3C/svg%3E")`;
diff --git a/apps/desktop/src/routes/editor/ExportDialog.tsx b/apps/desktop/src/routes/editor/ExportDialog.tsx
index d64f99e91..92271f183 100644
--- a/apps/desktop/src/routes/editor/ExportDialog.tsx
+++ b/apps/desktop/src/routes/editor/ExportDialog.tsx
@@ -16,6 +16,7 @@ import {
For,
type JSX,
Match,
+ mergeProps,
on,
Show,
Switch,
@@ -24,6 +25,7 @@ import {
import { createStore, produce, reconcile } from "solid-js/store";
import toast from "solid-toast";
import { SignInButton } from "~/components/SignInButton";
+import Tooltip from "~/components/Tooltip";
import { authStore } from "~/store";
import { trackEvent } from "~/utils/analytics";
import { createSignInMutation } from "~/utils/auth";
@@ -92,7 +94,7 @@ export const EXPORT_TO_OPTIONS = [
type ExportFormat = ExportSettings["format"];
-export const FORMAT_OPTIONS = [
+const FORMAT_OPTIONS = [
{ label: "MP4", value: "Mp4" },
{ label: "GIF", value: "Gif" },
] as { label: string; value: ExportFormat; disabled?: boolean }[];
@@ -119,7 +121,17 @@ export function ExportDialog() {
const auth = authStore.createQuery();
- const [settings, setSettings] = makePersisted(
+ const hasTransparentBackground = () => {
+ const backgroundSource =
+ editorInstance.savedProjectConfig.background.source;
+ return (
+ backgroundSource.type === "color" &&
+ backgroundSource.alpha !== undefined &&
+ backgroundSource.alpha < 255
+ );
+ };
+
+ const [_settings, setSettings] = makePersisted(
createStore<Settings>({
format: "Mp4",
fps: 30,
@@ -130,6 +142,14 @@ export function ExportDialog() {
{ name: "export_settings" },
);
+ const settings = mergeProps(_settings, () => {
+ const ret: Partial<Settings> = {};
+ if (hasTransparentBackground() && _settings.format === "Mp4")
+ ret.format = "Gif";
+
+ return ret;
+ });
+
if (!["Mp4", "Gif"].includes(settings.format)) setSettings("format", "Mp4");
// Ensure GIF is not selected when exportTo is "link"
@@ -530,59 +550,68 @@ export function ExportDialog() {
<div class="flex flex-row gap-2">
<For each={FORMAT_OPTIONS}>
{(option) => {
- const isGifDisabled = () =>
- option.value === "Gif" && settings.exportTo === "link";
+ const disabledReason = () => {
+ if (
+ option.value === "Mp4" &&
+ hasTransparentBackground()
+ )
+ return "MP4 format does not support transparent backgrounds";
+ if (
+ option.value === "Gif" &&
+ settings.exportTo === "link"
+ )
+ return "Shareable links cannot be made from GIFs";
+ };
return (
- <Button
- variant="gray"
- disabled={isGifDisabled()}
- onClick={() => {
- if (isGifDisabled()) return;
- setSettings(
- produce((newSettings) => {
- newSettings.format =
- option.value as ExportFormat;
+ <Tooltip
+ content={disabledReason()}
+ disabled={disabledReason() === undefined}
+ >
+ <Button
+ variant="gray"
+ onClick={() => {
+ setSettings(
+ produce((newSettings) => {
+ newSettings.format =
+ option.value as ExportFormat;
- if (
- option.value === "Gif" &&
- !(
- settings.resolution.value === "720p" ||
- settings.resolution.value === "1080p"
+ if (
+ option.value === "Gif" &&
+ !(
+ settings.resolution.value === "720p" ||
+ settings.resolution.value === "1080p"
+ )
)
- )
- newSettings.resolution = {
- ...RESOLUTION_OPTIONS._720p,
- };
+ newSettings.resolution = {
+ ...RESOLUTION_OPTIONS._720p,
+ };
- if (
- option.value === "Gif" &&
- GIF_FPS_OPTIONS.every(
- (v) => v.value === settings.fps,
+ if (
+ option.value === "Gif" &&
+ GIF_FPS_OPTIONS.every(
+ (v) => v.value !== settings.fps,
+ )
)
- )
- newSettings.fps = 15;
+ newSettings.fps = 15;
- if (
- option.value === "Mp4" &&
- FPS_OPTIONS.every(
- (v) => v.value !== settings.fps,
+ if (
+ option.value === "Mp4" &&
+ FPS_OPTIONS.every(
+ (v) => v.value !== settings.fps,
+ )
)
- )
- newSettings.fps = 30;
- }),
- );
- }}
- autofocus={false}
- data-selected={settings.format === option.value}
- class={
- isGifDisabled()
- ? "opacity-50 cursor-not-allowed"
- : ""
- }
- >
- {option.label}
- </Button>
+ newSettings.fps = 30;
+ }),
+ );
+ }}
+ autofocus={false}
+ data-selected={settings.format === option.value}
+ disabled={!!disabledReason()}
+ >
+ {option.label}
+ </Button>
+ </Tooltip>
);
}}
</For>
@@ -919,7 +948,7 @@ export function ExportDialog() {
>
<div class="relative">
<a
- href={meta().sharing!.link}
+ href={meta().sharing?.link}
target="_blank"
rel="noreferrer"
class="block"
@@ -930,7 +959,7 @@ export function ExportDialog() {
setTimeout(() => {
setCopyPressed(false);
}, 2000);
- navigator.clipboard.writeText(meta().sharing!.link!);
+ navigator.clipboard.writeText(meta().sharing?.link!);
}}
variant="dark"
class="flex gap-2 justify-center items-center"
diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsx
index 0ec23721b..f090484f7 100644
--- a/apps/desktop/src/routes/editor/Player.tsx
+++ b/apps/desktop/src/routes/editor/Player.tsx
@@ -329,6 +329,18 @@ export function Player() {
);
}
+// CSS for checkerboard grid (adaptive to light/dark mode)
+const gridStyle = {
+ "background-image":
+ "linear-gradient(45deg, rgba(128,128,128,0.12) 25%, transparent 25%), " +
+ "linear-gradient(-45deg, rgba(128,128,128,0.12) 25%, transparent 25%), " +
+ "linear-gradient(45deg, transparent 75%, rgba(128,128,128,0.12) 75%), " +
+ "linear-gradient(-45deg, transparent 75%, rgba(128,128,128,0.12) 75%)",
+ "background-size": "40px 40px",
+ "background-position": "0 0, 0 20px, 20px -20px, -20px 0px",
+ "background-color": "rgba(200,200,200,0.08)",
+};
+
function PreviewCanvas() {
const { latestFrame } = useEditorContext();
@@ -393,8 +405,9 @@ function PreviewCanvas() {
style={{
width: `${size().width - padding * 2}px`,
height: `${size().height}px`,
+ ...gridStyle,
}}
- class="bg-blue-50 rounded"
+ class="rounded"
ref={canvasRef}
id="canvas"
width={currentFrame().width}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 2a3a71458..17987f9b9 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -354,7 +354,7 @@ start_time?: number | null }
export type AuthSecret = { api_key: string } | { token: string; expires: number }
export type AuthStore = { secret: AuthSecret; user_id: string | null; plan: Plan | null; intercom_hash: string | null }
export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; inset: number; crop: Crop | null; shadow?: number; advancedShadow?: ShadowConfiguration | null; border?: BorderConfiguration | 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 BackgroundSource = { type: "wallpaper"; path: string | null } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number]; alpha?: number } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number }
export type BorderConfiguration = { enabled: boolean; width: number; color: [number, number, number]; opacity: number }
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 CameraInfo = { device_id: string; model_id: ModelIDType | null; display_name: string }
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 5f4210d71..dd6164fe4 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -31,6 +31,8 @@ pub enum BackgroundSource {
},
Color {
value: Color,
+ #[serde(default = "default_alpha")]
+ alpha: u8,
},
Gradient {
from: Color,
@@ -44,6 +46,10 @@ fn default_gradient_angle() -> u16 {
90
}
+fn default_alpha() -> u8 {
+ u8::MAX
+}
+
impl Default for BackgroundSource {
fn default() -> Self {
BackgroundSource::Wallpaper {
diff --git a/crates/rendering-skia/src/bin/test_background.rs b/crates/rendering-skia/src/bin/test_background.rs
index faf1c2dfe..8ed54cfba 100644
--- a/crates/rendering-skia/src/bin/test_background.rs
+++ b/crates/rendering-skia/src/bin/test_background.rs
@@ -69,7 +69,10 @@ fn test_color_background(
for (color, name) in colors {
let uniforms = SkiaProjectUniforms {
output_size: (width, height),
- background: BackgroundSource::Color { value: color },
+ background: BackgroundSource::Color {
+ value: color,
+ alpha: 255,
+ },
border: None,
};
diff --git a/crates/rendering-skia/src/layers/background.rs b/crates/rendering-skia/src/layers/background.rs
index df4e34c76..a6318fbe7 100644
--- a/crates/rendering-skia/src/layers/background.rs
+++ b/crates/rendering-skia/src/layers/background.rs
@@ -26,7 +26,7 @@ pub enum Background {
impl From<BackgroundSource> for Background {
fn from(source: BackgroundSource) -> Self {
match source {
- BackgroundSource::Color { value } => Background::Color(value),
+ BackgroundSource::Color { value, .. } => Background::Color(value),
BackgroundSource::Gradient { from, to, angle } => {
Background::Gradient { from, to, angle }
}
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 51555ec57..98be71a67 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -21,6 +21,7 @@ futures-intrusive = "0.5.0"
image = "0.25.2"
log = "0.4"
serde = { workspace = true }
+serde_json = "1.0"
specta.workspace = true
thiserror.workspace = true
wgpu.workspace = true
@@ -30,6 +31,7 @@ glyphon = "0.9.0"
tracing.workspace = true
resvg = "0.45"
tiny-skia = "0.11"
+clap = { version = "4.5", features = ["derive"] }
[target.'cfg(target_os = "macos")'.dependencies]
cidre.workspace = true
diff --git a/crates/rendering/src/layers/background.rs b/crates/rendering/src/layers/background.rs
index c4d5418c6..199245f58 100644
--- a/crates/rendering/src/layers/background.rs
+++ b/crates/rendering/src/layers/background.rs
@@ -33,11 +33,11 @@ pub enum Background {
impl From<BackgroundSource> for Background {
fn from(value: BackgroundSource) -> Self {
match value {
- BackgroundSource::Color { value } => Background::Color([
+ BackgroundSource::Color { value, alpha } => Background::Color([
srgb_to_linear(value[0]),
srgb_to_linear(value[1]),
srgb_to_linear(value[2]),
- 1.0,
+ alpha as f32 / 255.0,
]),
BackgroundSource::Gradient { from, to, angle } => Background::Gradient(Gradient {
start: [
@@ -434,14 +434,29 @@ impl From<Background> for GradientOrColorUniforms {
fn from(value: Background) -> Self {
match value {
Background::Color(color) => Self {
- start: color,
- end: color,
+ start: [
+ color[0] * color[3],
+ color[1] * color[3],
+ color[2] * color[3],
+ color[3],
+ ],
+ end: [
+ color[0] * color[3],
+ color[1] * color[3],
+ color[2] * color[3],
+ color[3],
+ ],
angle: 0.0,
_padding: [0.0; 3],
},
Background::Gradient(Gradient { start, end, angle }) => Self {
- start,
- end,
+ start: [
+ start[0] * start[3],
+ start[1] * start[3],
+ start[2] * start[3],
+ start[3],
+ ],
+ end: [end[0] * end[3], end[1] * end[3], end[2] * end[3], end[3]],
angle,
_padding: [0.0; 3],
},
@@ -494,3 +509,51 @@ impl GradientOrColorPipeline {
})
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cap_project::BackgroundSource;
+
+ #[test]
+ fn test_transparent_color_conversion() {
+ let source = BackgroundSource::Color {
+ value: [255, 0, 0], // Red
+ alpha: 128, // 50% opacity
+ };
+ let background = Background::from(source);
+ match background {
+ Background::Color(color) => {
+ assert!((color[0] - 1.0).abs() < 1e-6); // Red in linear
+ assert_eq!(color[1], 0.0);
+ assert_eq!(color[2], 0.0);
+ assert!((color[3] - 0.5).abs() < 0.01); // Alpha 128/255 ≈ 0.5
+ }
+ _ => panic!("Expected Color variant"),
+ }
+ }
+
+ #[test]
+ fn test_transparent_gradient_conversion() {
+ let source = BackgroundSource::Gradient {
+ from: [0, 255, 0], // Green
+ to: [0, 0, 255], // Blue
+ angle: 90,
+ };
+ let background = Background::from(source);
+ match background {
+ Background::Gradient(gradient) => {
+ assert_eq!(gradient.start[0], 0.0);
+ assert_eq!(gradient.start[1], 1.0); // Green in linear
+ assert_eq!(gradient.start[2], 0.0);
+ assert_eq!(gradient.start[3], 1.0); // Alpha 255/255 = 1.0
+ assert_eq!(gradient.end[0], 0.0);
+ assert_eq!(gradient.end[1], 0.0);
+ assert_eq!(gradient.end[2], 1.0); // Blue in linear
+ assert_eq!(gradient.end[3], 0.0); // Alpha 0/255 = 0.0
+ assert_eq!(gradient.angle, 90.0);
+ }
+ _ => panic!("Expected Gradient variant"),
+ }
+ }
+}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 137a096a5..2e4e63e16 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -1143,7 +1143,7 @@ impl RendererLayers {
{
let mut pass = render_pass!(
session.current_texture_view(),
- wgpu::LoadOp::Clear(wgpu::Color::BLACK)
+ wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
);
self.background.render(&mut pass);
}
diff --git a/crates/rendering/src/main.rs b/crates/rendering/src/main.rs
index 0a27549fa..9f98d9459 100644
--- a/crates/rendering/src/main.rs
+++ b/crates/rendering/src/main.rs
@@ -1,43 +1,253 @@
-// use cap_project::{BackgroundSource, ProjectConfiguration, RecordingMeta};
+use anyhow::{Context, Result};
+use cap_project::{ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY};
+use cap_rendering::{
+ ProjectRecordingsMeta, RecordingSegmentDecoders, RenderSegment, RenderVideoConstants,
+ RenderedFrame, SegmentVideoPaths,
+};
+use clap::{Parser, ValueEnum};
+use image::{ImageBuffer, ImageFormat};
+use std::path::PathBuf;
+use std::sync::Arc;
+use tokio::sync::mpsc;
+
+#[derive(Parser, Debug)]
+#[command(author, version, about, long_about = None)]
+struct Args {
+ /// Path to the Cap project directory
+ project_path: PathBuf,
+
+ /// Output format for the rendered frame
+ #[arg(short, long, default_value = "png")]
+ format: OutputFormat,
+
+ /// Output file path (defaults to frame.png/jpeg/raw in current directory)
+ #[arg(short, long)]
+ output: Option<PathBuf>,
+
+ /// Output resolution width (defaults to project resolution)
+ #[arg(long)]
+ width: Option<u32>,
+
+ /// Output resolution height (defaults to project resolution)
+ #[arg(long)]
+ height: Option<u32>,
+}
+
+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug)]
+enum OutputFormat {
+ /// PNG format (lossless, supports transparency)
+ Png,
+ /// JPEG format (lossy compression)
+ Jpeg,
+ /// Raw RGBA data
+ Raw,
+}
+
+impl std::fmt::Display for OutputFormat {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ OutputFormat::Png => write!(f, "png"),
+ OutputFormat::Jpeg => write!(f, "jpeg"),
+ OutputFormat::Raw => write!(f, "raw"),
+ }
+ }
+}
#[tokio::main]
-async fn main() {
- // let project_path = PathBuf::from(
- // r#"/Users/brendonovich/Library/Application Support/so.cap.desktop/recordings/414f2abd-8186-479f-85e7-08a64411a33c.cap"#,
- // );
-
- // let mut project: ProjectConfiguration = ProjectConfiguration::default();
-
- // project.camera.position.x = cap_project::CameraXPosition::Right;
- // project.camera.position.y = cap_project::CameraYPosition::Top;
- // project.camera.rounding = 0;
- // project.camera.mirror = false;
-
- // project.background.source = BackgroundSource::Gradient {
- // from: [71, 133, 255],
- // to: [255, 71, 102],
- // };
- // project.background.rounding = 0;
- // project.background.padding = 0;
-
- // let meta: RecordingMeta = serde_json::from_str(
- // &std::fs::read_to_string(project_path.join("recording-meta.json")).unwrap(),
- // )
- // .unwrap();
-
- // render_video_to_file(
- // cap_rendering::RenderOptions {
- // camera_size: meta.camera.map(|c| (c.width, c.height)),
- // screen_size: (meta.display.width, meta.display.height),
- // output_size: (1920, 1080),
- // },
- // project,
- // project_path.join("output/result.mp4"),
- // VideoDecoderActor::new(project_path.join("content/display.mp4").clone()),
- // meta.camera
- // .map(|_| VideoDecoderActor::new(project_path.join("content/camera.mp4").clone())),
- // |_| {},
- // )
- // .await
- // .ok();
+async fn main() -> Result<()> {
+ let args = Args::parse();
+
+ // Load the project similar to ExporterBase
+ println!("Loading project from: {}", args.project_path.display());
+
+ let project_config: ProjectConfiguration = serde_json::from_reader(
+ std::fs::File::open(args.project_path.join("project-config.json"))
+ .context("Failed to open project-config.json")?,
+ )
+ .context("Failed to parse project configuration")?;
+
+ let recording_meta = RecordingMeta::load_for_project(&args.project_path)
+ .map_err(|e| anyhow::anyhow!("Failed to load recording metadata: {}", e))?;
+ let studio_meta = recording_meta
+ .studio_meta()
+ .context("Project is not a studio recording")?
+ .clone();
+
+ let recordings = Arc::new(
+ ProjectRecordingsMeta::new(&recording_meta.project_path, &studio_meta)
+ .map_err(|e| anyhow::anyhow!("Failed to create project recordings meta: {}", e))?,
+ );
+
+ let render_constants = Arc::new(
+ RenderVideoConstants::new(
+ &recordings.segments,
+ recording_meta.clone(),
+ studio_meta.clone(),
+ )
+ .await
+ .context("Failed to create render constants")?,
+ );
+
+ let render_segments: Vec<RenderSegment> = match &studio_meta {
+ StudioRecordingMeta::SingleSegment { segment } => {
+ let decoders = RecordingSegmentDecoders::new(
+ &recording_meta,
+ &studio_meta,
+ SegmentVideoPaths {
+ display: recording_meta.path(&segment.display.path),
+ camera: segment
+ .camera
+ .as_ref()
+ .map(|c| recording_meta.path(&c.path)),
+ },
+ 0,
+ )
+ .await
+ .map_err(|e| anyhow::anyhow!("Failed to create decoders for single segment: {}", e))?;
+
+ vec![RenderSegment {
+ cursor: Arc::new(Default::default()),
+ decoders,
+ }]
+ }
+ StudioRecordingMeta::MultipleSegments { inner, .. } => {
+ let mut segments = Vec::new();
+ for (i, s) in inner.segments.iter().enumerate() {
+ let decoders = RecordingSegmentDecoders::new(
+ &recording_meta,
+ &studio_meta,
+ SegmentVideoPaths {
+ display: recording_meta.path(&s.display.path),
+ camera: s.camera.as_ref().map(|c| recording_meta.path(&c.path)),
+ },
+ i,
+ )
+ .await
+ .map_err(|e| {
+ anyhow::anyhow!("Failed to create decoders for segment {}: {}", i, e)
+ })?;
+
+ let cursor = Arc::new(s.cursor_events(&recording_meta));
+
+ segments.push(RenderSegment { cursor, decoders });
+ }
+ segments
+ }
+ };
+
+ // Determine output size
+ let output_size = if let (Some(width), Some(height)) = (args.width, args.height) {
+ (width, height)
+ } else {
+ (1920, 1080) // Default resolution
+ };
+
+ // Determine output path
+ let output_path = args.output.unwrap_or_else(|| {
+ let extension = match args.format {
+ OutputFormat::Png => "png",
+ OutputFormat::Jpeg => "jpg",
+ OutputFormat::Raw => "raw",
+ };
+ PathBuf::from(format!("frame.{}", extension))
+ });
+
+ // Ensure output directory exists
+ if let Some(parent) = output_path.parent() {
+ std::fs::create_dir_all(parent).context("Failed to create output directory")?;
+ }
+
+ println!(
+ "Rendering first frame at {}x{}",
+ output_size.0, output_size.1
+ );
+ println!("Output: {}", output_path.display());
+
+ // Set up rendering pipeline
+ let (tx, mut rx) = mpsc::channel::<(RenderedFrame, u32)>(1);
+
+ // Start rendering in a separate task
+ let render_task = tokio::task::spawn(async move {
+ cap_rendering::render_video_to_channel(
+ &render_constants,
+ &project_config,
+ tx,
+ &recording_meta.clone(),
+ &studio_meta,
+ render_segments,
+ 1, // Only render 1 frame
+ XY::new(output_size.0, output_size.1),
+ &recordings,
+ )
+ .await
+ });
+
+ // Wait for the first frame
+ let (frame, frame_number) = rx
+ .recv()
+ .await
+ .ok_or_else(|| anyhow::anyhow!("No frame received"))?;
+ println!(
+ "Received frame {} ({}x{})",
+ frame_number, frame.width, frame.height
+ );
+
+ // Cancel the render task since we only want the first frame
+ render_task.abort();
+
+ // Save the frame in the requested format
+ match args.format {
+ OutputFormat::Png => save_as_png(&frame, &output_path)?,
+ OutputFormat::Jpeg => save_as_jpeg(&frame, &output_path)?,
+ OutputFormat::Raw => save_as_raw(&frame, &output_path)?,
+ }
+
+ println!("✅ Frame saved to: {}", output_path.display());
+ Ok(())
+}
+
+fn save_as_png(frame: &RenderedFrame, output_path: &PathBuf) -> Result<()> {
+ // Use RGBA data directly for PNG to preserve transparency
+ let rgba_data: Vec<u8> = frame
+ .data
+ .chunks(frame.padded_bytes_per_row as usize)
+ .flat_map(|row| row[0..(frame.width * 4) as usize].to_vec())
+ .collect();
+
+ let rgba_img =
+ ImageBuffer::<image::Rgba<u8>, Vec<u8>>::from_raw(frame.width, frame.height, rgba_data)
+ .context("Failed to create image from frame data")?;
+
+ rgba_img
+ .save_with_format(output_path, ImageFormat::Png)
+ .context("Failed to save PNG")?;
+ Ok(())
+}
+
+fn save_as_jpeg(frame: &RenderedFrame, output_path: &PathBuf) -> Result<()> {
+ // Convert RGBA data to RGB for JPEG
+ let rgb_data: Vec<u8> = frame
+ .data
+ .chunks(frame.padded_bytes_per_row as usize)
+ .flat_map(|row| {
+ row[0..(frame.width * 4) as usize]
+ .chunks(4)
+ .flat_map(|chunk| [chunk[0], chunk[1], chunk[2]]) // Skip alpha channel
+ })
+ .collect();
+
+ let rgb_img =
+ ImageBuffer::<image::Rgb<u8>, Vec<u8>>::from_raw(frame.width, frame.height, rgb_data)
+ .context("Failed to create image from frame data")?;
+
+ rgb_img
+ .save_with_format(output_path, ImageFormat::Jpeg)
+ .context("Failed to save JPEG")?;
+ Ok(())
+}
+
+fn save_as_raw(frame: &RenderedFrame, output_path: &PathBuf) -> Result<()> {
+ // Save raw RGBA data
+ std::fs::write(output_path, &frame.data).context("Failed to save raw frame data")?;
+ Ok(())
}
diff --git a/crates/rendering/src/shaders/gradient-or-color.wgsl b/crates/rendering/src/shaders/gradient-or-color.wgsl
index 371c5c0cf..000a8748e 100644
--- a/crates/rendering/src/shaders/gradient-or-color.wgsl
+++ b/crates/rendering/src/shaders/gradient-or-color.wgsl
@@ -20,7 +20,7 @@ fn gradient(uv: vec2<f32>) -> vec4<f32> {
let t = clamp(proj, 0.0, 1.0);
- return mix(vec4<f32>(u.start.rgb, 1.0), vec4<f32>(u.end.rgb, 1.0), t);
+ return mix(u.start, u.end, t);
}
struct VertexOutput {