Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Add GIF export support to the editor (#648)

Richie McIlroyd81cb3b3b3e4
diff --git a/Cargo.lock b/Cargo.lock
index a049a5c6d..17dac484e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1085,6 +1085,7 @@ dependencies = [
"tempfile",
"thiserror 1.0.69",
"tokio",
+ "tracing",
]
[[package]]
@@ -1128,6 +1129,8 @@ dependencies = [
"ffmpeg-sys-next",
"flume 0.11.0",
"futures",
+ "gif",
+ "image 0.25.5",
"indexmap 2.5.0",
"nokhwa",
"nokhwa-bindings-macos",
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs
index 4acf3c481..dc0b5f364 100644
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@ -6,8 +6,7 @@ use std::{
sync::Arc,
};
-use cap_editor::create_segments;
-use cap_export::{ExportCompression, ExportSettings, Exporter};
+use cap_export::ExporterBase;
use cap_media::sources::get_target_fps;
use cap_project::{RecordingMeta, XY};
use cap_rendering::{ProjectRecordingsMeta, RenderVideoConstants};
@@ -165,27 +164,24 @@ struct Export {
impl Export {
async fn run(self) -> Result<(), String> {
- let exporter = Exporter::builder(self.project_path)
+ let exporter_base = ExporterBase::builder(self.project_path)
.build()
.await
- .map_err(|v| v.to_string())?;
+ .map_err(|v| format!("Exporter build error: {}", v.to_string()))?;
let mut stdout = stdout();
- let exporter_output_path = exporter
- .export_mp4(
- ExportSettings {
- fps: 60,
- resolution_base: XY::new(1920, 1080),
- compression: ExportCompression::Minimal,
- },
- move |f| {
- print!("\rrendered frame {f}");
-
- stdout.flush().unwrap();
- },
- )
- .await
- .map_err(|v| v.to_string())?;
+
+ let exporter_output_path = cap_export::gif::GifExportSettings {
+ fps: 10,
+ resolution_base: XY::new(1920, 1080),
+ }
+ .export(exporter_base, move |f| {
+ print!("\rrendered frame {f}");
+
+ stdout.flush().unwrap();
+ })
+ .await
+ .map_err(|v| format!("Exporter error: {}", v.to_string()))?;
let output_path = if let Some(output_path) = self.output_path {
std::fs::copy(&exporter_output_path, &output_path).unwrap();
@@ -194,7 +190,7 @@ impl Export {
exporter_output_path
};
- println!("Exported video to '{}'", output_path.display());
+ info!("Exported video to '{}'", output_path.display());
Ok(())
}
diff --git a/apps/desktop/src-tauri/src/captions.rs b/apps/desktop/src-tauri/src/captions.rs
index a7a76b57a..9ac4f022e 100644
--- a/apps/desktop/src-tauri/src/captions.rs
+++ b/apps/desktop/src-tauri/src/captions.rs
@@ -980,7 +980,6 @@ pub async fn load_captions(
video_id: String,
app: AppHandle,
) -> Result<Option<CaptionData>, String> {
- tracing::info!("Loading captions for video_id: {}", video_id);
let captions_dir = app_captions_dir(&app, &video_id)?;
let captions_path = captions_dir.join("captions.json");
@@ -1203,7 +1202,6 @@ pub async fn export_captions_srt(
tracing::info!("Starting SRT export for video_id: {}", video_id);
// Load captions
- tracing::info!("Loading captions from storage");
let captions = match load_captions(video_id.clone(), app.clone()).await? {
Some(c) => {
tracing::info!("Found {} caption segments to export", c.segments.len());
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index 1e89e6112..ec3be2188 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -1,8 +1,26 @@
use crate::{get_video_metadata, FramesRendered};
-use cap_export::{ExportSettings, Exporter};
+use cap_export::ExporterBase;
use cap_project::{RecordingMeta, XY};
+use serde::Deserialize;
+use specta::Type;
use std::path::PathBuf;
+#[derive(Deserialize, Clone, Copy, Debug, Type)]
+#[serde(tag = "format")]
+pub enum ExportSettings {
+ Mp4(cap_export::mp4::Mp4ExportSettings),
+ Gif(cap_export::gif::GifExportSettings),
+}
+
+impl ExportSettings {
+ fn fps(&self) -> u32 {
+ match self {
+ ExportSettings::Mp4(settings) => settings.fps,
+ ExportSettings::Gif(settings) => settings.fps,
+ }
+ }
+}
+
#[tauri::command]
#[specta::specta]
pub async fn export_video(
@@ -10,31 +28,49 @@ pub async fn export_video(
progress: tauri::ipc::Channel<FramesRendered>,
settings: ExportSettings,
) -> Result<PathBuf, String> {
- let exporter = Exporter::builder(project_path).build().await.map_err(|e| {
- sentry::capture_message(&e.to_string(), sentry::Level::Error);
- e.to_string()
- })?;
+ let exporter_base = ExporterBase::builder(project_path)
+ .build()
+ .await
+ .map_err(|e| {
+ sentry::capture_message(&e.to_string(), sentry::Level::Error);
+ e.to_string()
+ })?;
- let total_frames = exporter.total_frames(&settings);
+ let total_frames = exporter_base.total_frames(settings.fps());
let _ = progress.send(FramesRendered {
rendered_count: 0,
total_frames,
});
- exporter
- .export_mp4(settings, move |frame_index| {
- // Ensure progress never exceeds total frames
- let _ = progress.send(FramesRendered {
- rendered_count: (frame_index + 1).min(total_frames),
- total_frames,
- });
- })
- .await
- .map_err(|e| {
- sentry::capture_message(&e.to_string(), sentry::Level::Error);
- e.to_string()
- })
+ match settings {
+ ExportSettings::Mp4(settings) => {
+ settings
+ .export(exporter_base, move |frame_index| {
+ // Ensure progress never exceeds total frames
+ let _ = progress.send(FramesRendered {
+ rendered_count: (frame_index + 1).min(total_frames),
+ total_frames,
+ });
+ })
+ .await
+ }
+ ExportSettings::Gif(settings) => {
+ settings
+ .export(exporter_base, move |frame_index| {
+ // Ensure progress never exceeds total frames
+ let _ = progress.send(FramesRendered {
+ rendered_count: (frame_index + 1).min(total_frames),
+ total_frames,
+ });
+ })
+ .await
+ }
+ }
+ .map_err(|e| {
+ sentry::capture_message(&e.to_string(), sentry::Level::Error);
+ e.to_string()
+ })
}
#[derive(Debug, serde::Serialize, specta::Type)]
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 9b6ae3c23..17c335d4d 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -524,13 +524,14 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
println!("Attempting to copy file from {} to {}", src, dst);
let is_screenshot = src.contains("screenshots/");
+ let is_gif = src.ends_with(".gif") || dst.ends_with(".gif");
let src_path = std::path::Path::new(&src);
if !src_path.exists() {
return Err(format!("Source file {} does not exist", src));
}
- if !is_screenshot {
+ if !is_screenshot && !is_gif {
if !is_valid_mp4(src_path) {
let mut attempts = 0;
while attempts < 10 {
@@ -580,7 +581,7 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(
continue;
}
- if !is_screenshot && !is_valid_mp4(std::path::Path::new(&dst)) {
+ if !is_screenshot && !is_gif && !is_valid_mp4(std::path::Path::new(&dst)) {
last_error = Some("Destination file is not a valid MP4".to_string());
let _ = tokio::fs::remove_file(&dst).await;
attempts += 1;
diff --git a/apps/desktop/src/routes/editor/ExportDialog.tsx b/apps/desktop/src/routes/editor/ExportDialog.tsx
index 819afa4e1..b096ca686 100644
--- a/apps/desktop/src/routes/editor/ExportDialog.tsx
+++ b/apps/desktop/src/routes/editor/ExportDialog.tsx
@@ -9,6 +9,7 @@ import {
import { save as saveDialog } from "@tauri-apps/plugin-dialog";
import { cx } from "cva";
import {
+ batch,
createEffect,
createRoot,
createSignal,
@@ -23,7 +24,6 @@ import {
import { createStore, produce, reconcile } from "solid-js/store";
import toast from "solid-toast";
-import Tooltip from "~/components/Tooltip";
import { authStore } from "~/store";
import { trackEvent } from "~/utils/analytics";
import { exportVideo } from "~/utils/export";
@@ -31,6 +31,7 @@ import {
commands,
events,
ExportCompression,
+ ExportSettings,
FramesRendered,
} from "~/utils/tauri";
import { RenderState, useEditorContext } from "./context";
@@ -60,6 +61,14 @@ export const FPS_OPTIONS = [
{ label: "60 FPS", value: 60 },
] satisfies Array<{ label: string; value: number }>;
+export const GIF_FPS_OPTIONS = [
+ { label: "10 FPS", value: 10 },
+ { label: "15 FPS", value: 15 },
+ { label: "20 FPS", value: 20 },
+ { label: "25 FPS", value: 25 },
+ { label: "30 FPS", value: 30 },
+] satisfies Array<{ label: string; value: number }>;
+
export const EXPORT_TO_OPTIONS = [
{
label: "File",
@@ -78,10 +87,12 @@ export const EXPORT_TO_OPTIONS = [
},
] as const;
+type ExportFormat = ExportSettings["format"];
+
export const FORMAT_OPTIONS = [
- { label: "MP4", value: "mp4" },
- { label: "GIF", value: "gif", disabled: true },
-] as { label: string; value: string; disabled?: boolean }[];
+ { label: "MP4", value: "Mp4" },
+ { label: "GIF", value: "Gif" },
+] as { label: string; value: ExportFormat; disabled?: boolean }[];
type ExportToOption = (typeof EXPORT_TO_OPTIONS)[number]["value"];
@@ -98,7 +109,7 @@ export function ExportDialog() {
const [settings, setSettings] = makePersisted(
createStore({
- format: "mp4" as "mp4" | "gif",
+ format: "MP4" as ExportFormat,
fps: 30,
exportTo: "file" as ExportToOption,
resolution: { label: "720p", value: "720p", width: 1280, height: 720 },
@@ -107,11 +118,11 @@ export function ExportDialog() {
{ name: "export_settings" }
);
- // just a wrapper of exportVideo that provides the current settings
const exportWithSettings = (onProgress: (progress: FramesRendered) => void) =>
exportVideo(
projectPath,
{
+ format: settings.format,
fps: settings.fps,
resolution_base: {
x: settings.resolution.width,
@@ -186,7 +197,12 @@ export function ExportDialog() {
)
);
});
- } else toast.success("Recording exported to clipboard");
+ } else
+ toast.success(
+ `${
+ settings.format === "Gif" ? "GIF" : "Recording"
+ } exported to clipboard`
+ );
},
}));
@@ -194,9 +210,15 @@ export function ExportDialog() {
mutationFn: async () => {
if (exportState.type !== "idle") return;
+ const extension = settings.format === "Gif" ? "gif" : "mp4";
const savePath = await saveDialog({
- filters: [{ name: "mp4 filter", extensions: ["mp4"] }],
- defaultPath: `~/Desktop/${meta().prettyName}.mp4`,
+ filters: [
+ {
+ name: `${extension.toUpperCase()} filter`,
+ extensions: [extension],
+ },
+ ],
+ defaultPath: `~/Desktop/${meta().prettyName}.${extension}`,
});
if (!savePath) {
setExportState(reconcile({ type: "idle" }));
@@ -242,7 +264,10 @@ export function ExportDialog() {
)
);
});
- } else toast.success("Recording exported to file");
+ } else
+ toast.success(
+ `${settings.format === "Gif" ? "GIF" : "Recording"} exported to file`
+ );
},
}));
@@ -427,41 +452,47 @@ export function ExportDialog() {
<h3 class="text-gray-12">Format</h3>
<div class="flex flex-row gap-2">
<For each={FORMAT_OPTIONS}>
- {(option) =>
- option.disabled ? (
- <Tooltip content={"Coming soon"}>
- <Button
- variant="secondary"
- onClick={() =>
- setSettings(
- "format",
- option.value as "mp4" | "gif"
+ {(option) => (
+ <Button
+ variant="secondary"
+ onClick={() => {
+ setSettings(
+ produce((newSettings) => {
+ newSettings.format = option.value as ExportFormat;
+
+ if (
+ option.value === "Gif" &&
+ settings.resolution.value !== "720p"
)
- }
- disabled={option.disabled}
- autofocus={false}
- class={cx(
- settings.format === option.value && selectedStyle
- )}
- >
- {option.label}
- </Button>
- </Tooltip>
- ) : (
- <Button
- variant="secondary"
- onClick={() =>
- setSettings("format", option.value as "mp4")
- }
- autofocus={false}
- class={cx(
- settings.format === option.value && selectedStyle
- )}
- >
- {option.label}
- </Button>
- )
- }
+ newSettings.resolution =
+ RESOLUTION_OPTIONS._720p;
+
+ if (
+ option.value === "Gif" &&
+ GIF_FPS_OPTIONS.every(
+ (v) => v.value === settings.fps
+ )
+ )
+ newSettings.fps = 15;
+
+ if (
+ option.value === "Mp4" &&
+ FPS_OPTIONS.every(
+ (v) => v.value !== settings.fps
+ )
+ )
+ newSettings.fps = 30;
+ })
+ );
+ }}
+ autofocus={false}
+ class={cx(
+ settings.format === option.value && selectedStyle
+ )}
+ >
+ {option.label}
+ </Button>
+ )}
</For>
</div>
</div>
@@ -470,14 +501,20 @@ export function ExportDialog() {
<div class="overflow-hidden relative p-4 rounded-xl bg-gray-2">
<div class="flex flex-col gap-3">
<h3 class="text-gray-12">Frame rate</h3>
- <KSelect
- options={FPS_OPTIONS}
+ <KSelect<{ label: string; value: number }>
+ options={
+ settings.format === "Gif" ? GIF_FPS_OPTIONS : FPS_OPTIONS
+ }
optionValue="value"
optionTextValue="label"
placeholder="Select FPS"
- value={FPS_OPTIONS.find((opt) => opt.value === settings.fps)}
+ value={(settings.format === "Gif"
+ ? GIF_FPS_OPTIONS
+ : FPS_OPTIONS
+ ).find((opt) => opt.value === settings.fps)}
onChange={(option) => {
- const value = option?.value ?? 30;
+ const value =
+ option?.value ?? (settings.format === "Gif" ? 10 : 30);
trackEvent("export_fps_changed", {
fps: value,
});
@@ -578,11 +615,15 @@ export function ExportDialog() {
<h3 class="text-gray-12">Resolution</h3>
<div class="flex gap-2">
<For
- each={[
- RESOLUTION_OPTIONS._720p,
- RESOLUTION_OPTIONS._1080p,
- RESOLUTION_OPTIONS._4k,
- ]}
+ each={
+ settings.format === "Gif"
+ ? [RESOLUTION_OPTIONS._720p]
+ : [
+ RESOLUTION_OPTIONS._720p,
+ RESOLUTION_OPTIONS._1080p,
+ RESOLUTION_OPTIONS._4k,
+ ]
+ }
>
{(option) => (
<Button
@@ -646,7 +687,9 @@ export function ExportDialog() {
{copyState.type === "starting"
? "Preparing..."
: copyState.type === "rendering"
- ? "Rendering video..."
+ ? settings.format === "Gif"
+ ? "Rendering GIF..."
+ : "Rendering video..."
: copyState.type === "copying"
? "Copying to clipboard..."
: "Copied to clipboard"}
@@ -660,7 +703,10 @@ export function ExportDialog() {
keyed
>
{(copyState) => (
- <RenderProgress state={copyState} />
+ <RenderProgress
+ state={copyState}
+ format={settings.format}
+ />
)}
</Show>
</div>
@@ -683,7 +729,9 @@ export function ExportDialog() {
{saveState.type === "starting"
? "Preparing..."
: saveState.type === "rendering"
- ? "Rendering video..."
+ ? settings.format === "Gif"
+ ? "Rendering GIF..."
+ : "Rendering video..."
: saveState.type === "copying"
? "Exporting to file..."
: "Export completed"}
@@ -697,7 +745,10 @@ export function ExportDialog() {
keyed
>
{(copyState) => (
- <RenderProgress state={copyState} />
+ <RenderProgress
+ state={copyState}
+ format={settings.format}
+ />
)}
</Show>
</>
@@ -713,7 +764,11 @@ export function ExportDialog() {
Export Completed
</h1>
<p class="text-sm text-gray-11">
- Your video has successfully been exported
+ Your{" "}
+ {settings.format === "Gif"
+ ? "GIF"
+ : "video"}{" "}
+ has successfully been exported
</p>
</div>
</div>
@@ -762,7 +817,10 @@ export function ExportDialog() {
keyed
>
{(renderState) => (
- <RenderProgress state={renderState} />
+ <RenderProgress
+ state={renderState}
+ format={settings.format}
+ />
)}
</Match>
</Switch>
@@ -853,7 +911,11 @@ export function ExportDialog() {
setClipboardCopyPressed(false);
}, 2000);
await commands.copyVideoToClipboard(path);
- toast.success("Video copied to clipboard");
+ toast.success(
+ `${
+ settings.format === "Gif" ? "GIF" : "Video"
+ } copied to clipboard`
+ );
}
}}
>
@@ -875,7 +937,7 @@ export function ExportDialog() {
);
}
-function RenderProgress(props: { state: RenderState }) {
+function RenderProgress(props: { state: RenderState; format?: ExportFormat }) {
return (
<ProgressView
amount={
@@ -887,7 +949,9 @@ function RenderProgress(props: { state: RenderState }) {
}
label={
props.state.type === "rendering"
- ? `Rendering video (${props.state.progress.renderedCount}/${props.state.progress.totalFrames} frames)`
+ ? `Rendering ${props.format === "Gif" ? "GIF" : "video"} (${
+ props.state.progress.renderedCount
+ }/${props.state.progress.totalFrames} frames)`
: "Preparing to render..."
}
/>
diff --git a/apps/desktop/src/routes/editor/ShareButton.tsx b/apps/desktop/src/routes/editor/ShareButton.tsx
index 7dbc499f0..431f9473d 100644
--- a/apps/desktop/src/routes/editor/ShareButton.tsx
+++ b/apps/desktop/src/routes/editor/ShareButton.tsx
@@ -72,6 +72,7 @@ function ShareButton() {
await exportVideo(
projectPath,
{
+ format: "Mp4",
fps: 30,
resolution_base: {
x: RESOLUTION_OPTIONS._1080p.width,
diff --git a/apps/desktop/src/routes/recordings-overlay.tsx b/apps/desktop/src/routes/recordings-overlay.tsx
index 45cca1075..2c342df4d 100644
--- a/apps/desktop/src/routes/recordings-overlay.tsx
+++ b/apps/desktop/src/routes/recordings-overlay.tsx
@@ -6,20 +6,20 @@ import { createMutation, createQuery } from "@tanstack/solid-query";
import { convertFileSrc } from "@tauri-apps/api/core";
import { cx } from "cva";
import {
- type Accessor,
- type ComponentProps,
- createEffect,
- createMemo,
- createResource,
- createSignal,
- For,
- Match,
- onCleanup,
- onMount,
- Show,
- startTransition,
- Suspense,
- Switch,
+ type Accessor,
+ type ComponentProps,
+ createEffect,
+ createMemo,
+ createResource,
+ createSignal,
+ For,
+ Match,
+ onCleanup,
+ onMount,
+ Show,
+ startTransition,
+ Suspense,
+ Switch,
} from "solid-js";
import { createStore, produce, SetStoreFunction } from "solid-js/store";
import { TransitionGroup } from "solid-transition-group";
@@ -558,7 +558,12 @@ function createRecordingMutations(
) =>
exportVideo(
media.path,
- { fps: FPS, resolution_base: OUTPUT_SIZE, compression: "Web" },
+ {
+ format: "Mp4",
+ fps: FPS,
+ resolution_base: OUTPUT_SIZE,
+ compression: "Web",
+ },
onProgress
);
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index e032c06a5..00722d98d 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -327,7 +327,7 @@ export type DownloadProgress = { progress: number; message: string }
export type EditorStateChanged = { playhead_position: number }
export type ExportCompression = "Minimal" | "Social" | "Web" | "Potato"
export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }
-export type ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression }
+export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ format: "Gif" } & GifExportSettings)
export type Flags = { captions: boolean }
export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }
export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; customCursorCapture?: boolean; serverUrl?: string;
@@ -335,6 +335,7 @@ export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?
* @deprecated
*/
openEditorAfterRecording?: boolean }
+export type GifExportSettings = { fps: number; resolution_base: XY<number> }
export type HapticPattern = "Alignment" | "LevelChange" | "Generic"
export type HapticPerformanceTime = "Default" | "Now" | "DrawCompleted"
export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean; shift: boolean }
@@ -344,6 +345,7 @@ export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }
export type InstantRecordingMeta = { fps: number; sample_rate: number | null }
export type JsonValue<T> = [T]
export type MainWindowRecordingStartBehaviour = "close" | "minimise"
+export type Mp4ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression }
export type MultipleSegment = { display: VideoMeta; camera?: VideoMeta | null; mic?: AudioMeta | null; system_audio?: AudioMeta | null; cursor?: string | null }
export type MultipleSegments = { segments: MultipleSegment[]; cursors: Cursors }
export type NewNotification = { title: string; body: string; is_error: boolean }
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index cfd2cf279..c8bcb78b2 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -21,3 +21,4 @@ ffmpeg = { workspace = true }
serde = "1.0.219"
specta.workspace = true
serde_json = "1.0.140"
+tracing.workspace = true
diff --git a/crates/export/src/gif.rs b/crates/export/src/gif.rs
new file mode 100644
index 000000000..00f2a1fe2
--- /dev/null
+++ b/crates/export/src/gif.rs
@@ -0,0 +1,106 @@
+use std::path::PathBuf;
+
+use cap_media::encoders::GifEncoderWrapper;
+use cap_project::XY;
+use cap_rendering::{ProjectUniforms, RenderSegment, RenderedFrame};
+use futures::FutureExt;
+use serde::Deserialize;
+use specta::Type;
+use tracing::trace;
+
+use crate::{ExportError, ExporterBase};
+
+#[derive(Deserialize, Clone, Copy, Debug, Type)]
+pub struct GifExportSettings {
+ pub fps: u32,
+ pub resolution_base: XY<u32>,
+}
+
+impl GifExportSettings {
+ pub async fn export(
+ self,
+ base: ExporterBase,
+ mut on_progress: impl FnMut(u32) + Send + 'static,
+ ) -> Result<PathBuf, String> {
+ let meta = &base.studio_meta;
+
+ let (tx_image_data, mut video_rx) = tokio::sync::mpsc::channel::<(RenderedFrame, u32)>(4);
+
+ let fps = self.fps;
+
+ let output_size = ProjectUniforms::get_output_size(
+ &base.render_constants.options,
+ &base.project_config,
+ self.resolution_base,
+ );
+
+ // Ensure the output path has .gif extension
+ let mut gif_output_path = base.output_path.clone();
+ if gif_output_path.extension() != Some(std::ffi::OsStr::new("gif")) {
+ gif_output_path.set_extension("gif");
+ }
+
+ std::fs::create_dir_all(gif_output_path.parent().unwrap()).map_err(|e| e.to_string())?;
+
+ trace!(
+ "Creating GIF encoder at path '{}'",
+ gif_output_path.display()
+ );
+ let mut gif_encoder =
+ GifEncoderWrapper::new(&gif_output_path, output_size.0, output_size.1, fps)
+ .map_err(|e| format!("Failed to create GIF encoder: {}", e))?;
+
+ let encoder_thread = tokio::task::spawn_blocking(move || {
+ let mut frame_count = 0;
+
+ while let Some((frame, _frame_number)) = video_rx.blocking_recv() {
+ (on_progress)(frame_count);
+
+ if let Err(e) =
+ gif_encoder.add_frame(&frame.data, frame.padded_bytes_per_row as usize)
+ {
+ return Err(ExportError::Other(format!(
+ "Failed to add frame to GIF: {}",
+ e
+ )));
+ }
+
+ frame_count += 1;
+ }
+
+ if let Err(e) = gif_encoder.finish() {
+ return Err(ExportError::Other(format!("Failed to finish GIF: {}", e)));
+ }
+
+ Ok(gif_output_path)
+ })
+ .then(|f| async {
+ f.map_err(|e| e.to_string())
+ .and_then(|v| v.map_err(|v| v.to_string()))
+ });
+
+ let render_video_task = cap_rendering::render_video_to_channel(
+ &base.render_constants,
+ &base.project_config,
+ tx_image_data,
+ &base.recording_meta,
+ meta,
+ base.segments
+ .iter()
+ .map(|s| RenderSegment {
+ cursor: s.cursor.clone(),
+ decoders: s.decoders.clone(),
+ })
+ .collect(),
+ fps,
+ self.resolution_base,
+ &base.recordings,
+ )
+ .then(|f| async { f.map_err(|v| v.to_string()) });
+
+ let (output_path, _) =
+ tokio::try_join!(encoder_thread, render_video_task).map_err(|e| e.to_string())?;
+
+ Ok(output_path)
+ }
+}
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 737826a13..bff3971c3 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -1,21 +1,11 @@
-use cap_editor::{get_audio_segments, Segment};
-use cap_media::{
- data::{RawVideoFormat, VideoInfo},
- encoders::{AACEncoder, AudioEncoder, H264Encoder, MP4Input},
- feeds::AudioRenderer,
-};
-use cap_project::{
- ProjectConfiguration, RecordingMeta, RecordingMetaInner, StudioRecordingMeta, XY,
-};
-use cap_rendering::{
- ProjectRecordingsMeta, ProjectUniforms, RenderSegment, RenderVideoConstants, RenderedFrame,
-};
-use futures::FutureExt;
-use image::ImageBuffer;
-use serde::Deserialize;
-use specta::Type;
-use std::{path::PathBuf, sync::Arc, time::Duration};
-use tokio::time::timeout;
+pub mod gif;
+pub mod mp4;
+
+use cap_editor::Segment;
+use cap_project::{ProjectConfiguration, RecordingMeta, StudioRecordingMeta, XY};
+use cap_rendering::{ProjectRecordingsMeta, RenderVideoConstants};
+use std::{path::PathBuf, sync::Arc};
+use tracing::error;
#[derive(thiserror::Error, Debug)]
pub enum ExportError {
@@ -41,32 +31,6 @@ pub enum ExportError {
Timeout(#[from] tokio::time::error::Elapsed),
}
-#[derive(Deserialize, Type, Clone, Copy, Debug)]
-pub struct ExportSettings {
- pub fps: u32,
- pub resolution_base: XY<u32>,
- pub compression: ExportCompression,
-}
-
-#[derive(Deserialize, Clone, Copy, Debug, Type)]
-pub enum ExportCompression {
- Minimal,
- Social,
- Web,
- Potato,
-}
-
-impl ExportCompression {
- pub fn bits_per_pixel(&self) -> f32 {
- match self {
- Self::Minimal => 0.3,
- Self::Social => 0.15,
- Self::Web => 0.08,
- Self::Potato => 0.04,
- }
- }
-}
-
#[derive(thiserror::Error, Debug)]
pub enum ExporterBuildError {
#[error("Failled to load config: {0}")]
@@ -95,7 +59,7 @@ impl ExporterBuilder {
self
}
- pub async fn build(self) -> Result<Exporter, ExporterBuildError> {
+ pub async fn build(self) -> Result<ExporterBase, ExporterBuildError> {
type Error = ExporterBuildError;
let project_config = serde_json::from_reader(
@@ -125,7 +89,7 @@ impl ExporterBuilder {
.await
.map_err(Error::MediaLoad)?;
- Ok(Exporter {
+ Ok(ExporterBase {
output_path: self
.output_path
.unwrap_or_else(|| recording_meta.output_path()),
@@ -140,7 +104,7 @@ impl ExporterBuilder {
}
}
-pub struct Exporter {
+pub struct ExporterBase {
project_path: PathBuf,
recording_meta: RecordingMeta,
project_config: ProjectConfiguration,
@@ -151,16 +115,8 @@ pub struct Exporter {
output_path: PathBuf,
}
-impl Exporter {
- pub fn builder(project_path: PathBuf) -> ExporterBuilder {
- ExporterBuilder {
- project_path,
- config: None,
- output_path: None,
- }
- }
-
- pub fn total_frames(&self, export_settings: &ExportSettings) -> u32 {
+impl ExporterBase {
+ pub fn total_frames(&self, fps: u32) -> u32 {
let duration = cap_rendering::get_duration(
&self.recordings,
&self.recording_meta,
@@ -168,184 +124,14 @@ impl Exporter {
&self.project_config,
);
- (export_settings.fps as f64 * duration).ceil() as u32
+ (fps as f64 * duration).ceil() as u32
}
- pub async fn export_mp4(
- self,
- export_settings: ExportSettings,
- mut on_progress: impl FnMut(u32) + Send + 'static,
- ) -> Result<PathBuf, Box<dyn std::error::Error>> {
- let output_path = self.output_path.clone();
- let meta = match &self.recording_meta.inner {
- RecordingMetaInner::Studio(meta) => meta,
- _ => panic!("Not a studio recording"),
- };
-
- println!("Exporting with custom muxer");
-
- let (tx_image_data, mut video_rx) = tokio::sync::mpsc::channel::<(RenderedFrame, u32)>(4);
- let (frame_tx, frame_rx) = std::sync::mpsc::sync_channel::<MP4Input>(4);
-
- let fps = export_settings.fps;
-
- let output_size = ProjectUniforms::get_output_size(
- &self.render_constants.options,
- &self.project_config,
- export_settings.resolution_base,
- );
-
- let mut video_info =
- VideoInfo::from_raw(RawVideoFormat::Rgba, output_size.0, output_size.1, fps);
- video_info.time_base = ffmpeg::Rational::new(1, fps as i32);
-
- let audio_segments = get_audio_segments(&self.segments);
-
- let mut audio_renderer = audio_segments
- .get(0)
- .filter(|_| !self.project_config.audio.mute)
- .map(|_| AudioRenderer::new(audio_segments.clone()));
- let has_audio = audio_renderer.is_some();
-
- let encoder_thread = tokio::task::spawn_blocking(move || {
- let mut encoder = cap_media::encoders::MP4File::init(
- "output",
- self.output_path.clone(),
- |o| {
- H264Encoder::builder("output_video", video_info)
- .with_bpp(export_settings.compression.bits_per_pixel())
- .build(o)
- },
- |o| {
- has_audio.then(|| {
- AACEncoder::init("output_audio", AudioRenderer::info(), o)
- .map(|v| v.boxed())
- })
- },
- )?;
-
- while let Ok(frame) = frame_rx.recv() {
- encoder.queue_video_frame(frame.video);
- if let Some(audio) = frame.audio {
- encoder.queue_audio_frame(audio);
- }
- }
-
- encoder.finish();
-
- Ok::<_, ExportError>(self.output_path)
- })
- .then(|f| async { f.map_err(Into::into).and_then(|v| v) });
-
- let render_task = tokio::spawn({
- let project = self.project_config.clone();
- let project_path = self.project_path.clone();
- async move {
- println!("Starting FFmpeg output process...");
-
- let mut frame_count = 0;
- let mut first_frame = None;
-
- let audio_samples_per_frame =
- (f64::from(AudioRenderer::SAMPLE_RATE) / f64::from(fps)).ceil() as usize;
-
- loop {
- let Some((frame, frame_number)) =
- timeout(Duration::from_secs(6), video_rx.recv()).await?
- else {
- break;
- };
-
- (on_progress)(frame_count);
-
- if frame_count == 0 {
- first_frame = Some(frame.clone());
- if let Some(audio) = &mut audio_renderer {
- audio.set_playhead(0.0, &project);
- }
- }
-
- let audio_frame = audio_renderer
- .as_mut()
- .and_then(|audio| audio.render_frame(audio_samples_per_frame, &project))
- .map(|mut frame| {
- let pts = ((frame_number * frame.rate()) as f64 / fps as f64) as i64;
- frame.set_pts(Some(pts));
- frame
- });
-
- frame_tx
- .send(MP4Input {
- audio: audio_frame,
- video: video_info.wrap_frame(
- &frame.data,
- frame_number as i64,
- frame.padded_bytes_per_row as usize,
- ),
- })
- .ok();
-
- frame_count += 1;
- }
-
- if let Some(frame) = first_frame {
- let rgb_img = ImageBuffer::<image::Rgb<u8>, Vec<u8>>::from_raw(
- frame.width,
- frame.height,
- 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]])
- })
- .collect::<Vec<_>>(),
- )
- .expect("Failed to create image from frame data");
-
- let screenshots_dir = project_path.join("screenshots");
- std::fs::create_dir_all(&screenshots_dir).unwrap_or_else(|e| {
- eprintln!("Failed to create screenshots directory: {:?}", e);
- });
-
- // Save full-size screenshot
- let screenshot_path = screenshots_dir.join("display.jpg");
- rgb_img.save(&screenshot_path).unwrap_or_else(|e| {
- eprintln!("Failed to save screenshot: {:?}", e);
- });
- } else {
- eprintln!("No frames were processed, cannot save screenshot or thumbnail");
- }
-
- Ok::<_, ExportError>(())
- }
- })
- .then(|f| async { f.map_err(Into::into).and_then(|v| v) });
-
- println!("Rendering video to channel");
-
- let render_video_task = cap_rendering::render_video_to_channel(
- &self.render_constants,
- &self.project_config,
- tx_image_data,
- &self.recording_meta,
- meta,
- self.segments
- .iter()
- .map(|s| RenderSegment {
- cursor: s.cursor.clone(),
- decoders: s.decoders.clone(),
- })
- .collect(),
- fps,
- export_settings.resolution_base,
- &self.recordings,
- )
- .then(|f| async { f.map_err(Into::into) });
-
- let _ = tokio::try_join!(encoder_thread, render_video_task, render_task)?;
-
- Ok(output_path)
+ pub fn builder(project_path: PathBuf) -> ExporterBuilder {
+ ExporterBuilder {
+ project_path,
+ config: None,
+ output_path: None,
+ }
}
}
diff --git a/crates/export/src/mp4.rs b/crates/export/src/mp4.rs
new file mode 100644
index 000000000..6a71429e5
--- /dev/null
+++ b/crates/export/src/mp4.rs
@@ -0,0 +1,224 @@
+use std::{path::PathBuf, time::Duration};
+
+use cap_editor::get_audio_segments;
+use cap_media::{
+ data::{RawVideoFormat, VideoInfo},
+ encoders::{AACEncoder, AudioEncoder, H264Encoder, MP4Input},
+ feeds::AudioRenderer,
+};
+use cap_project::XY;
+use cap_rendering::{ProjectUniforms, RenderSegment, RenderedFrame};
+use futures::FutureExt;
+use image::ImageBuffer;
+use serde::Deserialize;
+use specta::Type;
+use tracing::{info, warn};
+
+use crate::{ExportError, ExporterBase};
+
+#[derive(Deserialize, Type, Clone, Copy, Debug)]
+pub enum ExportCompression {
+ Minimal,
+ Social,
+ Web,
+ Potato,
+}
+
+impl ExportCompression {
+ pub fn bits_per_pixel(&self) -> f32 {
+ match self {
+ Self::Minimal => 0.3,
+ Self::Social => 0.15,
+ Self::Web => 0.08,
+ Self::Potato => 0.04,
+ }
+ }
+}
+
+#[derive(Deserialize, Type, Clone, Copy, Debug)]
+pub struct Mp4ExportSettings {
+ pub fps: u32,
+ pub resolution_base: XY<u32>,
+ pub compression: ExportCompression,
+}
+
+impl Mp4ExportSettings {
+ pub async fn export(
+ self,
+ base: ExporterBase,
+ mut on_progress: impl FnMut(u32) + Send + 'static,
+ ) -> Result<PathBuf, String> {
+ let output_path = base.output_path.clone();
+ let meta = &base.studio_meta;
+
+ info!("Exporting mp4 with settings: {:?}", &self);
+ info!("Expected to render {} frames", base.total_frames(self.fps));
+
+ let (tx_image_data, mut video_rx) = tokio::sync::mpsc::channel::<(RenderedFrame, u32)>(4);
+ let (frame_tx, frame_rx) = std::sync::mpsc::sync_channel::<MP4Input>(4);
+
+ let fps = self.fps;
+
+ let output_size = ProjectUniforms::get_output_size(
+ &base.render_constants.options,
+ &base.project_config,
+ self.resolution_base,
+ );
+
+ let mut video_info =
+ VideoInfo::from_raw(RawVideoFormat::Rgba, output_size.0, output_size.1, fps);
+ video_info.time_base = ffmpeg::Rational::new(1, fps as i32);
+
+ let audio_segments = get_audio_segments(&base.segments);
+
+ let mut audio_renderer = audio_segments
+ .get(0)
+ .filter(|_| !base.project_config.audio.mute)
+ .map(|_| AudioRenderer::new(audio_segments.clone()));
+ let has_audio = audio_renderer.is_some();
+
+ let encoder_thread = tokio::task::spawn_blocking(move || {
+ let mut encoder = cap_media::encoders::MP4File::init(
+ "output",
+ base.output_path.clone(),
+ |o| {
+ H264Encoder::builder("output_video", video_info)
+ .with_bpp(self.compression.bits_per_pixel())
+ .build(o)
+ },
+ |o| {
+ has_audio.then(|| {
+ AACEncoder::init("output_audio", AudioRenderer::info(), o)
+ .map(|v| v.boxed())
+ })
+ },
+ )
+ .map_err(|v| v.to_string())?;
+
+ while let Ok(frame) = frame_rx.recv() {
+ encoder.queue_video_frame(frame.video);
+ if let Some(audio) = frame.audio {
+ encoder.queue_audio_frame(audio);
+ }
+ }
+
+ encoder.finish();
+
+ Ok::<_, String>(base.output_path)
+ });
+
+ let render_task = tokio::spawn({
+ let project = base.project_config.clone();
+ let project_path = base.project_path.clone();
+ async move {
+ let mut frame_count = 0;
+ let mut first_frame = None;
+
+ let audio_samples_per_frame =
+ (f64::from(AudioRenderer::SAMPLE_RATE) / f64::from(fps)).ceil() as usize;
+
+ loop {
+ let (frame, frame_number) =
+ match tokio::time::timeout(Duration::from_secs(6), video_rx.recv()).await {
+ Err(_) => {
+ warn!("render_task frame receive timed out");
+ break;
+ }
+ Ok(Some(v)) => v,
+ _ => {
+ break;
+ }
+ };
+
+ (on_progress)(frame_count);
+
+ if frame_count == 0 {
+ first_frame = Some(frame.clone());
+ if let Some(audio) = &mut audio_renderer {
+ audio.set_playhead(0.0, &project);
+ }
+ }
+
+ let audio_frame = audio_renderer
+ .as_mut()
+ .and_then(|audio| audio.render_frame(audio_samples_per_frame, &project))
+ .map(|mut frame| {
+ let pts = ((frame_number * frame.rate()) as f64 / fps as f64) as i64;
+ frame.set_pts(Some(pts));
+ frame
+ });
+
+ frame_tx
+ .send(MP4Input {
+ audio: audio_frame,
+ video: video_info.wrap_frame(
+ &frame.data,
+ frame_number as i64,
+ frame.padded_bytes_per_row as usize,
+ ),
+ })
+ .ok();
+
+ frame_count += 1;
+ }
+
+ if let Some(frame) = first_frame {
+ let rgb_img = ImageBuffer::<image::Rgb<u8>, Vec<u8>>::from_raw(
+ frame.width,
+ frame.height,
+ 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]])
+ })
+ .collect::<Vec<_>>(),
+ )
+ .expect("Failed to create image from frame data");
+
+ let screenshots_dir = project_path.join("screenshots");
+ std::fs::create_dir_all(&screenshots_dir).unwrap_or_else(|e| {
+ eprintln!("Failed to create screenshots directory: {:?}", e);
+ });
+
+ // Save full-size screenshot
+ let screenshot_path = screenshots_dir.join("display.jpg");
+ rgb_img.save(&screenshot_path).unwrap_or_else(|e| {
+ eprintln!("Failed to save screenshot: {:?}", e);
+ });
+ } else {
+ warn!("No frames were processed, cannot save screenshot or thumbnail");
+ }
+
+ Ok::<_, ExportError>(())
+ }
+ })
+ .then(|f| async { f.map(|v| v.map_err(|e| e.to_string())) });
+
+ let render_video_task = cap_rendering::render_video_to_channel(
+ &base.render_constants,
+ &base.project_config,
+ tx_image_data,
+ &base.recording_meta,
+ meta,
+ base.segments
+ .iter()
+ .map(|s| RenderSegment {
+ cursor: s.cursor.clone(),
+ decoders: s.decoders.clone(),
+ })
+ .collect(),
+ fps,
+ self.resolution_base,
+ &base.recordings,
+ )
+ .then(|v| async { Ok(v.map_err(|e| e.to_string())) });
+
+ let _ = tokio::try_join!(encoder_thread, render_video_task, render_task)
+ .map_err(|e| e.to_string())?;
+
+ Ok(output_path)
+ }
+}
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index 11485e166..6a9e1f760 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -35,6 +35,8 @@ futures = "0.3.31"
axum = { version = "0.7.9", features = ["macros", "ws"] }
tokio.workspace = true
cap-fail = { version = "0.1.0", path = "../fail" }
+image = { version = "0.25.2", features = ["gif"] }
+gif = "0.13.1"
[target.'cfg(target_os = "macos")'.dependencies]
cidre = { workspace = true, default-features = false, features = [
diff --git a/crates/media/src/encoders/gif.rs b/crates/media/src/encoders/gif.rs
new file mode 100644
index 000000000..0f1a79d5e
--- /dev/null
+++ b/crates/media/src/encoders/gif.rs
@@ -0,0 +1,201 @@
+use gif::{Encoder, Frame, Repeat};
+use std::fs::File;
+use std::path::Path;
+use thiserror::Error;
+
+#[derive(Error, Debug)]
+pub enum GifEncodingError {
+ #[error("IO error: {0}")]
+ Io(#[from] std::io::Error),
+ #[error("GIF encoding error: {0}")]
+ Gif(#[from] gif::EncodingError),
+ #[error("Invalid frame data")]
+ InvalidFrameData,
+}
+
+pub struct GifEncoderWrapper {
+ encoder: Encoder<File>,
+ width: u16,
+ height: u16,
+ frame_delay: u16,
+}
+
+impl GifEncoderWrapper {
+ pub fn new<P: AsRef<Path>>(
+ path: P,
+ width: u32,
+ height: u32,
+ fps: u32,
+ ) -> Result<Self, GifEncodingError> {
+ let file = File::create(path)?;
+
+ let global_palette = create_default_palette();
+ let mut encoder = Encoder::new(file, width as u16, height as u16, &global_palette)?;
+ encoder.set_repeat(Repeat::Infinite)?;
+
+ let frame_delay = (100.0 / fps as f32) as u16;
+
+ Ok(Self {
+ encoder,
+ width: width as u16,
+ height: height as u16,
+ frame_delay,
+ })
+ }
+
+ pub fn add_frame(
+ &mut self,
+ frame_data: &[u8],
+ padded_bytes_per_row: usize,
+ ) -> Result<(), GifEncodingError> {
+ let width = self.width as usize;
+ let height = self.height as usize;
+ let mut indexed_data = Vec::with_capacity(width * height);
+
+ let mut rgb_data = Vec::with_capacity(width * height * 3);
+ for y in 0..height {
+ let row_start = y * padded_bytes_per_row;
+ for x in 0..width {
+ let pixel_start = row_start + x * 4;
+ if pixel_start + 2 < frame_data.len() {
+ rgb_data.push(frame_data[pixel_start] as i32);
+ rgb_data.push(frame_data[pixel_start + 1] as i32);
+ rgb_data.push(frame_data[pixel_start + 2] as i32);
+ } else {
+ return Err(GifEncodingError::InvalidFrameData);
+ }
+ }
+ }
+
+ for y in 0..height {
+ for x in 0..width {
+ let idx = (y * width + x) * 3;
+ let r = rgb_data[idx].clamp(0, 255) as u8;
+ let g = rgb_data[idx + 1].clamp(0, 255) as u8;
+ let b = rgb_data[idx + 2].clamp(0, 255) as u8;
+
+ let palette_idx = find_closest_palette_index(r, g, b);
+ indexed_data.push(palette_idx);
+
+ let (pr, pg, pb) = get_palette_color(palette_idx);
+
+ let er = r as i32 - pr as i32;
+ let eg = g as i32 - pg as i32;
+ let eb = b as i32 - pb as i32;
+
+ if x + 1 < width {
+ let idx_right = (y * width + x + 1) * 3;
+ rgb_data[idx_right] += (er * 7) / 16;
+ rgb_data[idx_right + 1] += (eg * 7) / 16;
+ rgb_data[idx_right + 2] += (eb * 7) / 16;
+ }
+ if y + 1 < height {
+ if x > 0 {
+ let idx_bottom_left = ((y + 1) * width + x - 1) * 3;
+ rgb_data[idx_bottom_left] += (er * 3) / 16;
+ rgb_data[idx_bottom_left + 1] += (eg * 3) / 16;
+ rgb_data[idx_bottom_left + 2] += (eb * 3) / 16;
+ }
+ let idx_bottom = ((y + 1) * width + x) * 3;
+ rgb_data[idx_bottom] += (er * 5) / 16;
+ rgb_data[idx_bottom + 1] += (eg * 5) / 16;
+ rgb_data[idx_bottom + 2] += (eb * 5) / 16;
+
+ if x + 1 < width {
+ let idx_bottom_right = ((y + 1) * width + x + 1) * 3;
+ rgb_data[idx_bottom_right] += er / 16;
+ rgb_data[idx_bottom_right + 1] += eg / 16;
+ rgb_data[idx_bottom_right + 2] += eb / 16;
+ }
+ }
+ }
+ }
+
+ let mut frame = Frame::from_indexed_pixels(self.width, self.height, indexed_data, None);
+ frame.delay = self.frame_delay;
+
+ self.encoder.write_frame(&frame)?;
+ Ok(())
+ }
+
+ pub fn finish(self) -> Result<(), GifEncodingError> {
+ drop(self.encoder);
+ Ok(())
+ }
+}
+
+fn create_default_palette() -> Vec<u8> {
+ let mut palette = Vec::with_capacity(256 * 3);
+
+ for r in 0..6 {
+ for g in 0..7 {
+ for b in 0..6 {
+ palette.push((r * 255 / 5) as u8);
+ palette.push((g * 255 / 6) as u8);
+ palette.push((b * 255 / 5) as u8);
+ }
+ }
+ }
+
+ palette.push(0);
+ palette.push(0);
+ palette.push(0);
+ palette.push(85);
+ palette.push(85);
+ palette.push(85);
+ palette.push(170);
+ palette.push(170);
+ palette.push(170);
+ palette.push(255);
+ palette.push(255);
+ palette.push(255);
+
+ assert_eq!(palette.len(), 256 * 3, "Palette must be exactly 256 colors");
+ palette
+}
+
+fn find_closest_palette_index(r: u8, g: u8, b: u8) -> u8 {
+ let r_idx = ((r as u32 * 5) / 255).min(5) as u8;
+ let g_idx = ((g as u32 * 6) / 255).min(6) as u8;
+ let b_idx = ((b as u32 * 5) / 255).min(5) as u8;
+
+ if (r as i32 - g as i32).abs() < 30
+ && (g as i32 - b as i32).abs() < 30
+ && (r as i32 - b as i32).abs() < 30
+ {
+ let gray = ((r as u32 + g as u32 + b as u32) / 3) as u8;
+ if gray < 43 {
+ return 252;
+ } else if gray < 128 {
+ return 253;
+ } else if gray < 213 {
+ return 254;
+ } else {
+ return 255;
+ }
+ }
+
+ r_idx * 42 + g_idx * 6 + b_idx
+}
+
+fn get_palette_color(index: u8) -> (u8, u8, u8) {
+ if index < 252 {
+ let r_idx = (index / 42) as u32;
+ let rem = index % 42;
+ let g_idx = (rem / 6) as u32;
+ let b_idx = (rem % 6) as u32;
+
+ let r = ((r_idx * 255) / 5) as u8;
+ let g = ((g_idx * 255) / 6) as u8;
+ let b = ((b_idx * 255) / 5) as u8;
+ (r, g, b)
+ } else {
+ match index {
+ 252 => (0, 0, 0),
+ 253 => (85, 85, 85),
+ 254 => (170, 170, 170),
+ 255 => (255, 255, 255),
+ _ => (0, 0, 0),
+ }
+ }
+}
diff --git a/crates/media/src/encoders/mod.rs b/crates/media/src/encoders/mod.rs
index 28b42af81..d017f6786 100644
--- a/crates/media/src/encoders/mod.rs
+++ b/crates/media/src/encoders/mod.rs
@@ -1,5 +1,6 @@
mod aac;
mod audio;
+mod gif;
mod h264;
mod mp4;
#[cfg(target_os = "macos")]
@@ -8,6 +9,7 @@ mod opus;
pub use aac::*;
pub use audio::*;
+pub use gif::*;
pub use h264::*;
pub use mp4::*;
#[cfg(target_os = "macos")]
diff --git a/crates/media/src/encoders/mp4.rs b/crates/media/src/encoders/mp4.rs
index a3640ed96..0f84b4329 100644
--- a/crates/media/src/encoders/mp4.rs
+++ b/crates/media/src/encoders/mp4.rs
@@ -8,6 +8,7 @@ use std::{
path::PathBuf,
sync::{Arc, Mutex},
};
+use tracing::info;
use super::{audio::AudioEncoder, H264Encoder};
@@ -19,6 +20,25 @@ pub struct MP4File {
is_finished: bool,
}
+#[derive(thiserror::Error, Debug)]
+pub enum InitError {
+ #[error("ffmpeg error: {0}")]
+ Ffmpeg(ffmpeg::Error),
+ #[error("video init: {0}")]
+ VideoInit(MediaError),
+ #[error("audio init: {0}")]
+ AudioInit(MediaError),
+}
+
+impl From<InitError> for MediaError {
+ fn from(value: InitError) -> Self {
+ match value {
+ InitError::AudioInit(e) | InitError::VideoInit(e) => e,
+ InitError::Ffmpeg(e) => Self::FFmpeg(e),
+ }
+ }
+}
+
impl MP4File {
pub fn init(
tag: &'static str,
@@ -27,15 +47,19 @@ impl MP4File {
audio: impl FnOnce(
&mut format::context::Output,
) -> Option<Result<Box<dyn AudioEncoder + Send>, MediaError>>,
- ) -> Result<Self, MediaError> {
+ ) -> Result<Self, InitError> {
output.set_extension("mp4");
- let mut output = format::output(&output)?;
+ let mut output = format::output(&output).map_err(InitError::Ffmpeg)?;
+
+ let video = video(&mut output).map_err(InitError::VideoInit)?;
+ let audio = audio(&mut output)
+ .transpose()
+ .map_err(InitError::AudioInit)?;
- let video = video(&mut output)?;
- let audio = audio(&mut output).transpose()?;
+ info!("Prepared encoders for mp4 file");
// make sure this happens after adding all encoders!
- output.write_header()?;
+ output.write_header().map_err(InitError::Ffmpeg)?;
Ok(Self {
tag,
diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rs
index 386bf4836..45e0e0560 100644
--- a/crates/project/src/meta.rs
+++ b/crates/project/src/meta.rs
@@ -293,7 +293,6 @@ impl MultipleSegment {
};
let full_path = meta.path(cursor_path);
- println!("Loading cursor data from: {:?}", full_path);
// Try to load the cursor data
match CursorEvents::load_from_file(&full_path) {
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index db47baec8..bc8d65920 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -795,7 +795,8 @@ async fn create_segment_pipeline(
output_path.clone(),
|o| H264Encoder::builder("camera", camera_config).build(o),
|_| None,
- )?;
+ )
+ .map_err(|e| RecordingError::Media(e.into()))?;
pipeline_builder.spawn_source("camera_capture", camera_source);
diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rs
index c8a778415..0e9d87b22 100644
--- a/crates/rendering/src/decoder/avassetreader.rs
+++ b/crates/rendering/src/decoder/avassetreader.rs
@@ -398,7 +398,5 @@ impl AVAssetReaderDecoder {
}
}
}
-
- println!("Decoder thread ended");
}
}
diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rs
index db57576aa..0068cfc75 100644
--- a/crates/rendering/src/layers/captions.rs
+++ b/crates/rendering/src/layers/captions.rs
@@ -65,9 +65,7 @@ pub struct CaptionsLayer {
}
impl CaptionsLayer {
- /// Create a new captions layer
pub fn new(device: &Device, queue: &Queue) -> Self {
- info!("Initializing new CaptionsLayer");
// Create default settings buffer
let settings = CaptionSettings::default();
let settings_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 25467af87..64bb6e5db 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -193,10 +193,6 @@ pub async fn render_video_to_channel(
let duration = get_duration(recordings, recording_meta, meta, &project);
let total_frames = (fps as f64 * duration).ceil() as u32;
- println!(
- "Final export duration: {} seconds ({} frames at {}fps)",
- duration, total_frames, fps
- );
let mut frame_number = 0;
@@ -266,7 +262,6 @@ pub fn get_duration(
project: &ProjectConfiguration,
) -> f64 {
let mut max_duration = recordings.duration();
- println!("Initial screen recording duration: {}", max_duration);
// Check camera duration if it exists
if let Some(camera_path) = meta.camera_path() {
@@ -281,7 +276,6 @@ pub fn get_duration(
// If there's a timeline, ensure all segments extend to the max duration
if let Some(timeline) = &project.timeline {
- println!("Found timeline with {} segments", timeline.segments.len());
// for (i, segment) in timeline.segments.iter().enumerate() {
// println!(
// "Segment {} - current end: {}, max_duration: {}",
@@ -292,12 +286,7 @@ pub fn get_duration(
// println!("Extended segment {} to new end: {}", i, segment.end);
// }
// }
- let final_duration = timeline.duration();
- println!(
- "Final timeline duration after adjustments: {}",
- final_duration
- );
- final_duration
+ timeline.duration()
} else {
println!("No timeline found, using max_duration: {}", max_duration);
max_duration
@@ -333,7 +322,6 @@ impl RenderVideoConstants {
.map(|c| XY::new(c.width, c.height)),
};
- println!("Initializing wgpu...");
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default());
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions::default())
@@ -432,7 +420,6 @@ impl RenderVideoConstants {
hotspot: cursor.hotspot.map(|v| v as f32),
},
);
- println!("Successfully loaded cursor texture: {}", cursor_id);
}
Err(e) => {
println!(
@@ -446,10 +433,6 @@ impl RenderVideoConstants {
}
}
- println!(
- "Completed loading cursor textures. Total loaded: {}",
- textures.len()
- );
textures
}
}