Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
cleanup progress handling
Brendan Allanf2289aeab2bb
diff --git a/.gitignore b/.gitignoreindex d538b67ae..ae63d5913 100644--- a/.gitignore+++ b/.gitignore@@ -36,3 +36,5 @@ pnpm-lock.yamlnative-deps*apps/storybook/storybook-statictauri.*.conf.json++*.tsbuildinfodiff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rsindex ac0d9894c..90b2c1e0f 100644--- a/apps/cli/src/main.rs+++ b/apps/cli/src/main.rs@@ -103,7 +103,9 @@ window {}:RequestedFormatType::AbsoluteHighestFrameRate,);- let mut camera = Camera::new(camera_info.index().clone(), format).unwrap();+ let Ok(mut camera) = Camera::new(camera_info.index().clone(), format) else {+ continue;+ };info.push(json!({"index": camera_info.index().to_string(),diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 868beb830..27a6be2b0 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -1157,7 +1157,6 @@ fn open_main_window(app: AppHandle) {#[derive(Serialize, Type, tauri_specta::Event, Debug, Clone)]pub struct UploadProgress {- stage: String,progress: f64,message: String,}@@ -1233,7 +1232,6 @@ async fn upload_exported_video(// Start upload progressUploadProgress {- stage: "uploading".to_string(),progress: 0.0,message: "Starting upload...".to_string(),}@@ -1265,7 +1263,6 @@ async fn upload_exported_video(Ok(uploaded_video) => {// Emit upload completeUploadProgress {- stage: "uploading".to_string(),progress: 1.0,message: "Upload complete!".to_string(),}diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 2a77eddd5..acd67f002 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -229,7 +229,6 @@ pub async fn upload_video(// Emit progress every chunkUploadProgress {- stage: "uploading".to_string(),progress: current / total_size,message: format!("{:.0}%", (current / total_size * 100.0)),}@@ -289,7 +288,6 @@ pub async fn upload_video(if response.status().is_success() {// Final progress updateUploadProgress {- stage: "uploading".to_string(),progress: 1.0,message: "100%".to_string(),}diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsxindex 25ec6551e..7e3799593 100644--- a/apps/desktop/src/routes/editor/Header.tsx+++ b/apps/desktop/src/routes/editor/Header.tsx@@ -1,9 +1,8 @@import { Button } from "@cap/ui-solid";import { cx } from "cva";import {- Match,+ Setter,Show,- Switch,batch,createEffect,createResource,@@ -15,14 +14,13 @@ import { type as ostype } from "@tauri-apps/plugin-os";import { Tooltip } from "@kobalte/core";import { Select as KSelect } from "@kobalte/core/select";import { createMutation } from "@tanstack/solid-query";-import { getRequestEvent } from "solid-js/web";import { save } from "@tauri-apps/plugin-dialog";-import { Channel } from "@tauri-apps/api/core";import type { UnlistenFn } from "@tauri-apps/api/event";import { getCurrentWindow, ProgressBarStatus } from "@tauri-apps/api/window";+import { createStore, produce } from "solid-js/store";-import { type RenderProgress, commands, events } from "~/utils/tauri";-import { FPS, useEditorContext } from "./context";+import { commands, events, RenderProgress } from "~/utils/tauri";+import { useEditorContext } from "./context";import { authStore } from "~/store";import {Dialog,@@ -32,14 +30,9 @@ import {PopperContent,topLeftAnimateClasses,} from "./ui";-import { DEFAULT_PROJECT_CONFIG } from "./projectConfig";-import {- type ProgressState,- progressState,- setProgressState,-} from "~/store/progress";import Titlebar from "~/components/titlebar/Titlebar";import { initializeTitlebar, setTitlebar } from "~/utils/titlebar-state";+import { Channel } from "@tauri-apps/api/core";type ResolutionOption = {label: string;@@ -67,9 +60,7 @@ export interface ExportEstimates {export function Header() {const currentWindow = getCurrentWindow();- const { videoId, project, prettyName } = useEditorContext();- const [showExportOptions, setShowExportOptions] = createSignal(false);const [selectedFps, setSelectedFps] = createSignal(Number(localStorage.getItem("cap-export-fps")) || 30);@@ -80,142 +71,17 @@ export function Header() {) || RESOLUTION_OPTIONS[0]);- const [exportEstimates] = createResource(- () => ({- videoId,- resolution: {- x: selectedResolution()?.width || RESOLUTION_OPTIONS[0].width,- y: selectedResolution()?.height || RESOLUTION_OPTIONS[0].height,- },- fps: selectedFps(),- }),- async (params) => {- return commands.getExportEstimates(- params.videoId,- params.resolution,- params.fps- );- }- );-- let unlistenTitlebar: UnlistenFn | undefined;- onMount(async () => {- unlistenTitlebar = await initializeTitlebar();- });- onCleanup(() => unlistenTitlebar?.());-// Save settings when they changecreateEffect(() => {localStorage.setItem("cap-export-fps", selectedFps().toString());localStorage.setItem("cap-export-resolution", selectedResolution().value);});- createEffect(() => {- const state = progressState;- if (state === undefined || state.type === "idle") {- currentWindow.setProgressBar({ status: ProgressBarStatus.None });- return;- }-- let percentage: number | undefined;- if (state.type === "saving") {- percentage =- state.stage === "rendering"- ? Math.min(- ((state.renderProgress || 0) / (state.totalFrames || 1)) * 100,- 100- )- : Math.min(state.progress || 0, 100);- }-- if (percentage)- currentWindow.setProgressBar({ progress: Math.round(percentage) });+ let unlistenTitlebar: UnlistenFn | undefined;+ onMount(async () => {+ unlistenTitlebar = await initializeTitlebar();});-- const exportWithSettings = async () => {- setShowExportOptions(false);-- const path = await save({- filters: [{ name: "mp4 filter", extensions: ["mp4"] }],- defaultPath: `~/Desktop/${prettyName()}.mp4`,- });- if (!path) return;-- setProgressState({- type: "saving",- progress: 0,- renderProgress: 0,- totalFrames: 0,- message: "Preparing to render...",- mediaPath: path,- stage: "rendering",- });-- const progress = new Channel<RenderProgress>();- progress.onmessage = (p) => {- if (p.type === "FrameRendered" && progressState.type === "saving") {- const percentComplete = Math.min(- Math.round(- (p.current_frame / (progressState.totalFrames || 1)) * 100- ),- 100- );-- setProgressState({- ...progressState,- renderProgress: p.current_frame,- message: `Rendering video - ${percentComplete}%`,- });-- // If rendering is complete, update to finalizing state- if (percentComplete === 100) {- setProgressState({- ...progressState,- message: "Finalizing export...",- });- }- }- if (- p.type === "EstimatedTotalFrames" &&- progressState.type === "saving"- ) {- setProgressState({- ...progressState,- totalFrames: p.total_frames,- message: "Starting render...",- });- }- };-- try {- const videoPath = await commands.exportVideo(- videoId,- project,- progress,- true,- selectedFps(),- {- x: selectedResolution()?.width || RESOLUTION_OPTIONS[0].width,- y: selectedResolution()?.height || RESOLUTION_OPTIONS[0].height,- }- );- await commands.copyFileToPath(videoPath, path);-- setProgressState({- type: "saving",- progress: 100,- message: "Saved successfully!",- mediaPath: path,- });-- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);- } catch (error) {- setProgressState({ type: "idle" });- throw error;- }- };+ onCleanup(() => unlistenTitlebar?.());batch(() => {setTitlebar("border", false);@@ -236,355 +102,347 @@ export function Header() {selectedResolution={selectedResolution}selectedFps={selectedFps}/>- <div class="relative">+ <ExportButton+ selectedResolution={selectedResolution()}+ selectedFps={selectedFps()}+ setSelectedFps={setSelectedFps}+ setSelectedResolution={setSelectedResolution}+ />+ </div>+ </div>+ );+ });++ return <Titlebar />;+}++function ExportButton(props: {+ selectedFps: number;+ selectedResolution: ResolutionOption;+ setSelectedResolution: Setter<ResolutionOption>;+ setSelectedFps: Setter<number>;+}) {+ const { videoId, project, prettyName } = useEditorContext();+ const [showExportOptions, setShowExportOptions] = createSignal(false);++ const [exportEstimates] = createResource(+ () => ({+ videoId,+ resolution: {+ x: props.selectedResolution.width,+ y: props.selectedResolution.height,+ },+ fps: props.selectedFps,+ }),+ (params) =>+ commands.getExportEstimates(params.videoId, params.resolution, params.fps)+ );++ const exportWithSettings = createMutation(() => ({+ mutationFn: async () => {+ setExportState({ type: "idle" });++ setShowExportOptions(false);++ const path = await save({+ filters: [{ name: "mp4 filter", extensions: ["mp4"] }],+ defaultPath: `~/Desktop/${prettyName()}.mp4`,+ });+ if (!path) return;++ setExportState({ type: "starting" });++ const progress = new Channel<RenderProgress>();++ progress.onmessage = (msg) => {+ if (msg.type === "EstimatedTotalFrames")+ setExportState({+ type: "rendering",+ renderedFrames: 0,+ totalFrames: msg.total_frames,+ });+ else+ setExportState(+ produce((state) => {+ if (msg.type === "FrameRendered" && state.type === "rendering")+ state.renderedFrames = msg.current_frame;+ })+ );+ };++ try {+ const videoPath = await commands.exportVideo(+ videoId,+ project,+ progress,+ true,+ props.selectedFps,+ {+ x: props.selectedResolution.width,+ y: props.selectedResolution.height,+ }+ );++ setExportState({ type: "saving", done: false });++ await commands.copyFileToPath(videoPath, path);++ setExportState({ type: "saving", done: false });+ } catch (error) {+ throw error;+ }+ },+ onSettled() {+ setTimeout(() => {+ exportWithSettings.reset();+ }, 2000);+ },+ }));++ const [exportState, setExportState] = createStore<+ | { type: "idle" }+ | { type: "starting" }+ | { type: "rendering"; renderedFrames: number; totalFrames: number }+ | { type: "saving"; done: boolean }+ >({ type: "idle" });++ createProgressBar(() => {+ if (exportWithSettings.isIdle || exportState.type === "idle") return;+ if (exportState.type === "starting") return 0;+ if (exportState.type === "rendering")+ return (exportState.renderedFrames / exportState.totalFrames) * 100;+ return 100;+ });++ return (+ <div class="relative">+ <Button+ variant="primary"+ onClick={() => setShowExportOptions(!showExportOptions())}+ >+ Export+ </Button>+ <Show when={showExportOptions()}>+ <div class="absolute right-0 top-full mt-2 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-40 p-4 min-w-[240px]">+ <div class="space-y-4">+ <div>+ <label class="block text-sm font-medium mb-1 text-gray-500 dark:text-gray-400">+ Resolution+ </label>+ <KSelect<ResolutionOption>+ options={RESOLUTION_OPTIONS}+ optionValue="value"+ optionTextValue="label"+ placeholder="Select Resolution"+ value={props.selectedResolution}+ onChange={props.setSelectedResolution}+ itemComponent={(props) => (+ <MenuItem<typeof KSelect.Item>+ as={KSelect.Item}+ item={props.item}+ >+ <KSelect.ItemLabel class="flex-1">+ {props.item.rawValue.label}+ </KSelect.ItemLabel>+ </MenuItem>+ )}+ >+ <KSelect.Trigger class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors KSelect">+ <KSelect.Value<ResolutionOption> class="flex-1 text-sm text-left truncate text-[--gray-500]">+ {(state) => <span>{state.selectedOption()?.label}</span>}+ </KSelect.Value>+ <KSelect.Icon>+ <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180 text-[--gray-500]" />+ </KSelect.Icon>+ </KSelect.Trigger>+ <KSelect.Portal>+ <PopperContent<typeof KSelect.Content>+ as={KSelect.Content}+ class={cx(topLeftAnimateClasses, "z-50")}+ >+ <MenuItemList<typeof KSelect.Listbox>+ class="max-h-32 overflow-y-auto"+ as={KSelect.Listbox}+ />+ </PopperContent>+ </KSelect.Portal>+ </KSelect>+ </div>+ <div>+ <label class="block text-sm font-medium mb-1 text-gray-500 dark:text-gray-400">+ FPS+ </label>+ <KSelect+ options={FPS_OPTIONS}+ optionValue="value"+ optionTextValue="label"+ placeholder="Select FPS"+ value={FPS_OPTIONS.find(+ (opt) => opt.value === props.selectedFps+ )}+ onChange={(option) => props.setSelectedFps(option?.value ?? 30)}+ itemComponent={(props) => (+ <MenuItem<typeof KSelect.Item>+ as={KSelect.Item}+ item={props.item}+ >+ <KSelect.ItemLabel class="flex-1">+ {props.item.rawValue.label}+ </KSelect.ItemLabel>+ </MenuItem>+ )}+ >+ <KSelect.Trigger class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors KSelect">+ <KSelect.Value<+ (typeof FPS_OPTIONS)[number]+ > class="flex-1 text-sm text-left truncate text-[--gray-500]">+ {(state) => <span>{state.selectedOption()?.label}</span>}+ </KSelect.Value>+ <KSelect.Icon>+ <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180 text-[--gray-500]" />+ </KSelect.Icon>+ </KSelect.Trigger>+ <KSelect.Portal>+ <PopperContent<typeof KSelect.Content>+ as={KSelect.Content}+ class={cx(topLeftAnimateClasses, "z-50")}+ >+ <MenuItemList<typeof KSelect.Listbox>+ class="max-h-32 overflow-y-auto"+ as={KSelect.Listbox}+ />+ </PopperContent>+ </KSelect.Portal>+ </KSelect>+ </div><Buttonvariant="primary"- onClick={() => setShowExportOptions(!showExportOptions())}+ class="w-full justify-center"+ onClick={() => exportWithSettings.mutate()}>- Export+ Export Video</Button>- <Show when={showExportOptions()}>- <div class="absolute right-0 top-full mt-2 bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg z-40 p-4 min-w-[240px]">- <div class="space-y-4">- <div>- <label class="block text-sm font-medium mb-1 text-gray-500 dark:text-gray-400">- Resolution- </label>- <KSelect<ResolutionOption>- options={RESOLUTION_OPTIONS}- optionValue="value"- optionTextValue="label"- placeholder="Select Resolution"- value={selectedResolution()}- onChange={setSelectedResolution}- itemComponent={(props) => (- <MenuItem<typeof KSelect.Item>- as={KSelect.Item}- item={props.item}- >- <KSelect.ItemLabel class="flex-1">- {props.item.rawValue.label}- </KSelect.ItemLabel>- </MenuItem>- )}- >- <KSelect.Trigger class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors KSelect">- <KSelect.Value<ResolutionOption> class="flex-1 text-sm text-left truncate text-[--gray-500]">- {(state) => (- <span>{state.selectedOption()?.label}</span>- )}- </KSelect.Value>- <KSelect.Icon>- <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180 text-[--gray-500]" />- </KSelect.Icon>- </KSelect.Trigger>- <KSelect.Portal>- <PopperContent<typeof KSelect.Content>- as={KSelect.Content}- class={cx(topLeftAnimateClasses, "z-50")}- >- <MenuItemList<typeof KSelect.Listbox>- class="max-h-32 overflow-y-auto"- as={KSelect.Listbox}- />- </PopperContent>- </KSelect.Portal>- </KSelect>- </div>- <div>- <label class="block text-sm font-medium mb-1 text-gray-500 dark:text-gray-400">- FPS- </label>- <KSelect- options={FPS_OPTIONS}- optionValue="value"- optionTextValue="label"- placeholder="Select FPS"- value={FPS_OPTIONS.find(- (opt) => opt.value === selectedFps()- )}- onChange={(option) => setSelectedFps(option?.value ?? 30)}- itemComponent={(props) => (- <MenuItem<typeof KSelect.Item>- as={KSelect.Item}- item={props.item}- >- <KSelect.ItemLabel class="flex-1">- {props.item.rawValue.label}- </KSelect.ItemLabel>- </MenuItem>- )}- >- <KSelect.Trigger class="flex flex-row items-center h-[2rem] px-[0.375rem] gap-[0.375rem] border rounded-lg border-gray-200 w-full disabled:text-gray-400 transition-colors KSelect">- <KSelect.Value<- (typeof FPS_OPTIONS)[number]- > class="flex-1 text-sm text-left truncate text-[--gray-500]">- {(state) => (- <span>{state.selectedOption()?.label}</span>- )}- </KSelect.Value>- <KSelect.Icon>- <IconCapChevronDown class="size-4 shrink-0 transform transition-transform ui-expanded:rotate-180 text-[--gray-500]" />- </KSelect.Icon>- </KSelect.Trigger>- <KSelect.Portal>- <PopperContent<typeof KSelect.Content>- as={KSelect.Content}- class={cx(topLeftAnimateClasses, "z-50")}- >- <MenuItemList<typeof KSelect.Listbox>- class="max-h-32 overflow-y-auto"- as={KSelect.Listbox}- />- </PopperContent>- </KSelect.Portal>- </KSelect>- </div>- <Button- variant="primary"- class="w-full justify-center"- onClick={exportWithSettings}- >- Export Video- </Button>- <Show when={exportEstimates()}>- {(est) => (- <div- class={cx(- "font-medium z-40 flex justify-between items-center pointer-events-none transition-all max-w-full overflow-hidden text-xs"- )}- >- <p class="flex items-center gap-4">- <span class="flex items-center text-[--gray-500]">- <IconCapCamera class="w-[14px] h-[14px] mr-1.5 text-[--gray-500]" />- {(() => {- const totalSeconds = Math.round(- est().duration_seconds- );- const hours = Math.floor(totalSeconds / 3600);- const minutes = Math.floor(- (totalSeconds % 3600) / 60- );- const seconds = totalSeconds % 60;-- if (hours > 0) {- return `${hours}:${minutes- .toString()- .padStart(2, "0")}:${seconds- .toString()- .padStart(2, "0")}`;- }- return `${minutes}:${seconds- .toString()- .padStart(2, "0")}`;- })()}- </span>- <span class="flex items-center text-[--gray-500]">- <IconLucideHardDrive class="w-[14px] h-[14px] mr-1.5 text-[--gray-500]" />- {est().estimated_size_mb.toFixed(2)} MB- </span>- <span class="flex items-center text-[--gray-500]">- <IconLucideClock class="w-[14px] h-[14px] mr-1.5 text-[--gray-500]" />- {(() => {- const totalSeconds = Math.round(- est().estimated_time_seconds- );- const hours = Math.floor(totalSeconds / 3600);- const minutes = Math.floor(- (totalSeconds % 3600) / 60- );- const seconds = totalSeconds % 60;-- if (hours > 0) {- return `~${hours}:${minutes- .toString()- .padStart(2, "0")}:${seconds- .toString()- .padStart(2, "0")}`;- }- return `~${minutes}:${seconds- .toString()- .padStart(2, "0")}`;- })()}- </span>- </p>- </div>- )}- </Show>+ <Show when={exportEstimates.latest}>+ {(est) => (+ <div+ class={cx(+ "font-medium z-40 flex justify-between items-center pointer-events-none transition-all max-w-full overflow-hidden text-xs"+ )}+ >+ <p class="flex items-center gap-4">+ <span class="flex items-center text-[--gray-500]">+ <IconCapCamera class="w-[14px] h-[14px] mr-1.5 text-[--gray-500]" />+ {(() => {+ const totalSeconds = Math.round(est().duration_seconds);+ const hours = Math.floor(totalSeconds / 3600);+ const minutes = Math.floor((totalSeconds % 3600) / 60);+ const seconds = totalSeconds % 60;++ if (hours > 0) {+ return `${hours}:${minutes+ .toString()+ .padStart(2, "0")}:${seconds+ .toString()+ .padStart(2, "0")}`;+ }+ return `${minutes}:${seconds+ .toString()+ .padStart(2, "0")}`;+ })()}+ </span>+ <span class="flex items-center text-[--gray-500]">+ <IconLucideHardDrive class="w-[14px] h-[14px] mr-1.5 text-[--gray-500]" />+ {est().estimated_size_mb.toFixed(2)} MB+ </span>+ <span class="flex items-center text-[--gray-500]">+ <IconLucideClock class="w-[14px] h-[14px] mr-1.5 text-[--gray-500]" />+ {(() => {+ const totalSeconds = Math.round(+ est().estimated_time_seconds+ );+ const hours = Math.floor(totalSeconds / 3600);+ const minutes = Math.floor((totalSeconds % 3600) / 60);+ const seconds = totalSeconds % 60;++ if (hours > 0) {+ return `~${hours}:${minutes+ .toString()+ .padStart(2, "0")}:${seconds+ .toString()+ .padStart(2, "0")}`;+ }+ return `~${minutes}:${seconds+ .toString()+ .padStart(2, "0")}`;+ })()}+ </span>+ </p></div>- </div>+ )}</Show></div></div>- </div>- );- });-- return (- <>- <Titlebar />- <Dialog.Root open={progressState.type !== "idle"} onOpenChange={() => {}}>+ </Show>+ <Dialog.Root+ open={!exportWithSettings.isIdle && exportState.type !== "idle"}+ onOpenChange={(o) => {+ // cancellation doesn't work yet+ // if (!o) exportWithSettings.reset();+ }}+ ><DialogContent- title={- progressState.type === "copying"- ? "Link Copied"- : progressState.type === "uploading"- ? "Creating Shareable Link"- : "Exporting Recording"- }+ title="Exporting Recording"confirm={<></>}+ close={<></>}class="bg-gray-600 text-gray-500 dark:text-gray-500">- <div class="min-h-[120px] flex items-center justify-center relative">- <Switch>- <Match when={progressState.type === "copying"}>- {(when) => {- const state = progressState as Extract<- ProgressState,- { type: "copying" }- >;- return (- <div class="w-[80%] text-center mx-auto relative z-10">- <h3 class="text-sm font-medium mb-3 text-gray-50">- {state.stage === "rendering"- ? "Rendering video"- : "Copying to clipboard"}- </h3>-- <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">- <div- class="bg-blue-300 h-2.5 rounded-full transition-all duration-200"- style={{- width: `${- state.stage === "rendering"- ? Math.min(- ((state.renderProgress || 0) /- (state.totalFrames || 1)) *- 100,- 100- )- : Math.min(state.progress || 0, 100)- }%`,- }}- />- </div>-- <p class="text-xs mt-3 relative z-10">- {state.stage === "rendering" &&- state.renderProgress &&- state.totalFrames- ? `${state.message} (${state.renderProgress}/${state.totalFrames} frames)`- : state.message}- </p>- </div>- );- }}- </Match>- <Match when={progressState.type === "saving"}>- {(when) => {- const state = progressState as Extract<- ProgressState,- { type: "saving" }- >;- return (- <div class="w-[80%] text-center mx-auto relative z-10">- <h3 class="text-sm font-medium mb-3 text-gray-50">- {state.stage === "rendering"- ? "Rendering video"- : "Saving file"}- </h3>-- <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">- <div- class="bg-blue-300 h-2.5 rounded-full transition-all duration-200"- style={{- width: `${- state.stage === "rendering"- ? Math.min(- ((state.renderProgress || 0) /- (state.totalFrames || 1)) *- 100,- 100- )- : Math.min(state.progress || 0, 100)- }%`,- }}- />- </div>-- <p class="text-xs mt-3 relative z-10">- {state.stage === "rendering" &&- state.renderProgress &&- state.totalFrames- ? `${state.message} (${state.renderProgress}/${state.totalFrames} frames)`- : state.message}- </p>- </div>- );- }}- </Match>- <Match when={progressState.type === "uploading"}>- {(when) => {- const state = progressState as Extract<- ProgressState,- { type: "uploading" }- >;- return (- <div class="w-[80%] text-center mx-auto relative z-10">- <h3 class="text-sm font-medium mb-3 text-gray-50">- {state.stage === "rendering"- ? "Rendering video"- : "Creating shareable link"}- </h3>-- <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">- <div- class="bg-blue-300 h-2.5 rounded-full transition-all duration-200"- style={{- width: `${- state.stage === "rendering"- ? Math.min(state.renderProgress || 0, 100)- : Math.min(- (state.uploadProgress || 0) * 100,- 100- )- }%`,- }}- />- </div>-- <p class="text-xs text-white mt-3 relative z-10">- {state.stage === "rendering"- ? `Rendering - ${Math.round(- state.renderProgress || 0- )}%`- : state.message}- </p>- </div>- );+ <div class="w-[80%] text-center mx-auto relative z-10 space-y-6 py-4">+ <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">+ <div+ class="bg-blue-300 h-2.5 rounded-full"+ style={{+ width: `${+ exportState.type === "saving"+ ? 100+ : exportState.type === "rendering"+ ? Math.min(+ (exportState.renderedFrames /+ exportState.totalFrames) *+ 100,+ 100+ )+ : 0+ }%`,}}- </Match>- </Switch>+ />+ </div>+ <p class="text-xs mt-3 relative z-10">+ {exportState.type == "idle" || exportState.type === "starting"+ ? "Preparing to render..."+ : exportState.type === "rendering"+ ? `Rendering video (${exportState.renderedFrames}/${exportState.totalFrames} frames)`+ : "Exported successfully!"}+ </p></div></DialogContent></Dialog.Root>- </>+ </div>);}-type ShareButtonProps = {+function ShareButton(props: {selectedResolution: () => ResolutionOption;selectedFps: () => number;-};--function ShareButton(props: ShareButtonProps) {- const { videoId, project, presets } = useEditorContext();+}) {+ const { videoId, project } = useEditorContext();const [recordingMeta, metaActions] = createResource(() =>commands.getRecordingMeta(videoId, "recording"));const uploadVideo = createMutation(() => ({- mutationFn: async (useCustomMuxer: boolean) => {+ mutationFn: async () => {+ setUploadState({ type: "idle" });+console.log("Starting upload process...");// Check authentication first@@ -616,86 +474,42 @@ function ShareButton(props: ShareButtonProps) {}}- let unlisten: (() => void) | undefined;+ const unlisten = await events.uploadProgress.listen((event) => {+ console.log("Upload progress event:", event.payload);+ setUploadState(+ produce((state) => {+ if (state.type !== "uploading") return;++ state.progress = Math.round(event.payload.progress * 100);+ })+ );+ });try {- setProgressState({- type: "uploading",- renderProgress: 0,- uploadProgress: 0,- message: "Rendering - 0%",- mediaPath: videoId,- stage: "rendering",- });+ setUploadState({ type: "starting" });// Setup progress listener before starting upload- unlisten = await events.uploadProgress.listen((event) => {- console.log("Upload progress event:", event.payload);- if (progressState.type === "uploading") {- const progress = Math.round(event.payload.progress * 100);- if (event.payload.stage === "rendering") {- setProgressState({- type: "uploading",- renderProgress: progress,- uploadProgress: 0,- message: `Rendering - ${progress}%`,- mediaPath: videoId,- stage: "rendering",- });- } else {- setProgressState({- type: "uploading",- renderProgress: 100,- uploadProgress: progress / 100,- message: `Uploading - ${progress}%`,- mediaPath: videoId,- stage: "uploading",- });- }- }- });console.log("Starting actual upload...");- setProgressState({- type: "uploading",- renderProgress: 0,- uploadProgress: 0,- message: "Rendering - 0%",- mediaPath: videoId,- stage: "rendering",- });-const progress = new Channel<RenderProgress>();- progress.onmessage = (p) => {- console.log("Progress channel message:", p);- if (- p.type === "FrameRendered" &&- progressState.type === "uploading"- ) {- const renderProgress = Math.round(- (p.current_frame / (progressState.totalFrames || 1)) * 100- );- setProgressState({- ...progressState,- message: `Rendering - ${renderProgress}%`,- renderProgress,- });- }- if (- p.type === "EstimatedTotalFrames" &&- progressState.type === "uploading"- ) {- console.log("Got total frames:", p.total_frames);- setProgressState({- ...progressState,- totalFrames: p.total_frames,++ progress.onmessage = (msg) => {+ if (msg.type === "EstimatedTotalFrames")+ setUploadState({+ type: "rendering",+ renderedFrames: 0,+ totalFrames: msg.total_frames,});- }+ else+ setUploadState(+ produce((state) => {+ if (msg.type === "FrameRendered" && state.type === "rendering")+ state.renderedFrames = msg.current_frame;+ })+ );};- getRequestEvent()?.nativeEvent;-await commands.exportVideo(videoId,project,@@ -710,6 +524,8 @@ function ShareButton(props: ShareButtonProps) {});+ setUploadState({ type: "uploading", progress: 0 });+// Now proceed with uploadconst result = recordingMeta()?.sharing? await commands.uploadExportedVideo(videoId, "Reupload")@@ -720,123 +536,179 @@ function ShareButton(props: ShareButtonProps) {if (result === "NotAuthenticated") {await commands.showWindow("SignIn");throw new Error("You need to sign in to share recordings");- }- if (result === "PlanCheckFailed") {+ } else if (result === "PlanCheckFailed")throw new Error("Failed to verify your subscription status");- }- if (result === "UpgradeRequired") {+ else if (result === "UpgradeRequired")throw new Error("This feature requires an upgraded plan");- }-- // Show success state briefly before resetting- setProgressState({- type: "uploading",- renderProgress: 100,- uploadProgress: 100,- message: "Upload complete!",- mediaPath: videoId,- stage: "uploading",- });-- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);return result;} catch (error) {console.error("Upload error:", error);- setProgressState({ type: "idle" });throw error instanceof Error? error: new Error("Failed to upload recording");} finally {- if (unlisten) {- console.log("Cleaning up upload progress listener");- unlisten();- }+ unlisten();}},onSuccess: () => {- console.log("Upload successful, refreshing metadata");metaActions.refetch();},onError: (error) => {- console.error("Upload mutation error:", error);- setProgressState({ type: "idle" });commands.globalMessageDialog(error instanceof Error ? error.message : "Failed to upload recording");},+ onSettled() {+ setTimeout(() => {+ setUploadState({ type: "idle" });+ }, 1500);+ },}));+ const [uploadState, setUploadState] = createStore<+ | { type: "idle" }+ | { type: "starting" }+ | { type: "rendering"; renderedFrames: number; totalFrames: number }+ | { type: "uploading"; progress: number }+ | { type: "link-copied" }+ >({ type: "idle" });++ createProgressBar(() => {+ if (uploadVideo.isIdle || uploadState.type === "idle") return;+ if (uploadState.type === "starting") return 0;+ if (uploadState.type === "rendering")+ return (uploadState.renderedFrames / uploadState.totalFrames) * 100;+ if (uploadState.type === "uploading") return uploadState.progress;+ return 100;+ });+return (- <Show- when={recordingMeta()?.sharing}- fallback={- <Button- disabled={uploadVideo.isPending}- onClick={(e) =>- uploadVideo.mutate((e.ctrlKey || e.metaKey) && e.shiftKey)+ <div class="relative">+ <Show+ when={recordingMeta()?.sharing}+ fallback={+ <Button+ disabled={uploadVideo.isPending}+ onClick={(e) => uploadVideo.mutate()}+ variant="primary"+ class="flex items-center space-x-1"+ >+ {uploadVideo.isPending ? (+ <>+ <span>Uploading Cap</span>+ <IconLucideLoaderCircle class="size-[1rem] animate-spin" />+ </>+ ) : (+ "Create Shareable Link"+ )}+ </Button>+ }+ >+ {(sharing) => {+ const url = () => new URL(sharing().link);++ return (+ <div class="flex flex-row items-center gap-2">+ <Tooltip.Root openDelay={0} closeDelay={0}>+ <Tooltip.Trigger>+ <Button+ disabled={uploadVideo.isPending}+ onClick={(e) => uploadVideo.mutate()}+ variant="secondary"+ class="flex items-center space-x-1"+ >+ {uploadVideo.isPending ? (+ <IconLucideLoaderCircle class="size-[1rem] animate-spin" />+ ) : (+ <IconLucideRotateCcw class="size-[1rem]" />+ )}+ </Button>+ </Tooltip.Trigger>+ <Tooltip.Portal>+ <Tooltip.Content class="z-50 px-2 py-1 text-xs text-gray-50 bg-gray-500 rounded shadow-lg animate-in fade-in duration-100">+ {uploadVideo.isPending+ ? "Reuploading video"+ : "Reupload video"}+ <Tooltip.Arrow class="fill-gray-500" />+ </Tooltip.Content>+ </Tooltip.Portal>+ </Tooltip.Root>+ <a+ class="rounded-full h-[2rem] px-[1rem] flex flex-row items-center gap-[0.375rem] bg-gray-200 hover:bg-gray-300 transition-colors duration-100"+ href={sharing().link}+ target="_blank"+ rel="noreferrer"+ >+ <span class="text-[0.875rem] text-gray-500">+ {url().host}+ {url().pathname}+ </span>+ </a>+ </div>+ );+ }}+ </Show>+ <Dialog.Root open={!uploadVideo.isIdle}>+ <DialogContent+ title={+ uploadState.type === "uploading"+ ? "Creating Shareable Link"+ : uploadState.type === "link-copied"+ ? "Link Copied"+ : "Exporting Recording"}- variant="primary"- class="flex items-center space-x-1"+ confirm={<></>}+ close={<></>}+ class="bg-gray-600 text-gray-500 dark:text-gray-500">- {uploadVideo.isPending ? (- <>- <span>Uploading Cap</span>- <IconLucideLoaderCircle class="size-[1rem] animate-spin" />- </>- ) : (- "Create Shareable Link"- )}- </Button>- }- >- {(sharing) => {- const url = () => new URL(sharing().link);-- return (- <div class="flex flex-row items-center gap-2">- <Tooltip.Root openDelay={0} closeDelay={0}>- <Tooltip.Trigger>- <Button- disabled={uploadVideo.isPending}- onClick={(e) =>- uploadVideo.mutate((e.ctrlKey || e.metaKey) && e.shiftKey)- }- variant="secondary"- class="flex items-center space-x-1"- >- {uploadVideo.isPending ? (- <IconLucideLoaderCircle class="size-[1rem] animate-spin" />- ) : (- <IconLucideRotateCcw class="size-[1rem]" />- )}- </Button>- </Tooltip.Trigger>- <Tooltip.Portal>- <Tooltip.Content class="z-50 px-2 py-1 text-xs text-gray-50 bg-gray-500 rounded shadow-lg animate-in fade-in duration-100">- {uploadVideo.isPending- ? "Reuploading video"- : "Reupload video"}- <Tooltip.Arrow class="fill-gray-500" />- </Tooltip.Content>- </Tooltip.Portal>- </Tooltip.Root>- <a- class="rounded-full h-[2rem] px-[1rem] flex flex-row items-center gap-[0.375rem] bg-gray-200 hover:bg-gray-300 transition-colors duration-100"- href={sharing().link}- target="_blank"- rel="noreferrer"- >- <span class="text-[0.875rem] text-gray-500">- {url().host}- {url().pathname}- </span>- </a>+ <div class="w-[80%] text-center mx-auto relative z-10 space-y-6 py-4">+ <div class="w-full bg-gray-200 rounded-full h-2.5 mb-2">+ <div+ class="bg-blue-300 h-2.5 rounded-full"+ style={{+ width: `${+ uploadState.type === "uploading"+ ? uploadState.progress+ : uploadState.type === "link-copied"+ ? 100+ : uploadState.type === "rendering"+ ? Math.min(+ (uploadState.renderedFrames /+ uploadState.totalFrames) *+ 100,+ 100+ )+ : 0+ }%`,+ }}+ />+ </div>++ <p class="text-xs text-white mt-3 relative z-10">+ {uploadState.type == "idle" || uploadState.type === "starting"+ ? "Preparing to render..."+ : uploadState.type === "rendering"+ ? `Rendering video (${uploadState.renderedFrames}/${uploadState.totalFrames} frames)`+ : uploadState.type === "uploading"+ ? `Uploading - ${Math.floor(uploadState.progress)}%`+ : "Link copied to clipboard!"}+ </p></div>- );- }}- </Show>+ </DialogContent>+ </Dialog.Root>+ </div>);}++function createProgressBar(progress: () => number | undefined) {+ const currentWindow = getCurrentWindow();++ createEffect(() => {+ const p = progress();+ console.log({ p });+ if (p === undefined)+ currentWindow.setProgressBar({ status: ProgressBarStatus.None });+ else currentWindow.setProgressBar({ progress: Math.round(p) });+ });+}diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.tsindex 42eb6ab12..e556c9d45 100644--- a/apps/desktop/src/routes/editor/context.ts+++ b/apps/desktop/src/routes/editor/context.ts@@ -34,7 +34,7 @@ export type CurrentDialog =export type DialogState = { open: false } | ({ open: boolean } & CurrentDialog);-export const FPS = 60;+export const FPS = 30;export const OUTPUT_SIZE = {x: 1920,diff --git a/apps/desktop/src/routes/editor/ui.tsx b/apps/desktop/src/routes/editor/ui.tsxindex baa062795..f375044b5 100644--- a/apps/desktop/src/routes/editor/ui.tsx+++ b/apps/desktop/src/routes/editor/ui.tsx@@ -147,7 +147,7 @@ export const Dialog = {);return <Button {...props} />;},- Footer(props: ComponentProps<"div">) {+ Footer(props: ComponentProps<"div"> & { close?: JSX.Element }) {return (<divclass={cx(@@ -156,7 +156,7 @@ export const Dialog = {)}{...props}>- <Dialog.CloseButton />+ {props.close ?? <Dialog.CloseButton />}{props.children}</div>);@@ -172,7 +172,12 @@ export const Dialog = {};export function DialogContent(- props: ParentProps<{ title: string; confirm: JSX.Element; class?: string }>+ props: ParentProps<{+ title: string;+ confirm: JSX.Element;+ class?: string;+ close?: JSX.Element;+ }>) {return (<>@@ -182,7 +187,7 @@ export function DialogContent(</KDialog.Title></Dialog.Header><Dialog.Content class={props.class}>{props.children}</Dialog.Content>- <Dialog.Footer>{props.confirm}</Dialog.Footer>+ <Dialog.Footer close={props.close}>{props.confirm}</Dialog.Footer></>);}diff --git a/apps/desktop/src/routes/recordings-overlay.tsx b/apps/desktop/src/routes/recordings-overlay.tsxindex 06bc1dc9f..48c2441f5 100644--- a/apps/desktop/src/routes/recordings-overlay.tsx+++ b/apps/desktop/src/routes/recordings-overlay.tsx@@ -1,5 +1,5 @@import { createMutation, createQuery } from "@tanstack/solid-query";-import { convertFileSrc } from "@tauri-apps/api/core";+import { Channel, convertFileSrc } from "@tauri-apps/api/core";import { cx } from "cva";import {type Accessor,@@ -22,19 +22,13 @@ import { Button } from "@cap/ui-solid";import { createElementBounds } from "@solid-primitives/bounds";import { TransitionGroup } from "solid-transition-group";import { makePersisted } from "@solid-primitives/storage";-import { Channel } from "@tauri-apps/api/core";-import { createStore, produce } from "solid-js/store";+import { createStore, produce, SetStoreFunction } from "solid-js/store";import IconLucideClock from "~icons/lucide/clock";-import {- commands,- events,- UploadResult,- type RenderProgress,-} from "~/utils/tauri";+import { commands, events, RenderProgress, UploadResult } from "~/utils/tauri";import { DEFAULT_PROJECT_CONFIG } from "./editor/projectConfig";import { createPresets } from "~/utils/createPresets";-import { progressState, setProgressState } from "~/store/progress";+import { RenderState } from "~/store/progress";import { FPS, OUTPUT_SIZE } from "./editor/context";import { authStore } from "~/store";@@ -60,46 +54,6 @@ export default function () {{ name: "screenshots-store" });- onMount(async () => {- console.log("Setting up event listeners");-- const unlisten = await events.uploadProgress.listen((event) => {- console.log("Upload progress event:", event.payload);- if (progressState.type === "uploading") {- if (event.payload.stage === "rendering") {- setProgressState({- type: "uploading",- renderProgress: Math.round(event.payload.progress * 100),- uploadProgress: 0,- message: event.payload.message,- mediaPath: progressState.mediaPath,- stage: "rendering",- });- } else {- setProgressState({- type: "uploading",- renderProgress: 100,- uploadProgress: Math.round(event.payload.progress * 100),- message: event.payload.message,- mediaPath: progressState.mediaPath,- stage: "uploading",- });-- if (event.payload.progress === 1) {- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);- }- }- }- });-- onCleanup(() => {- console.log("Cleaning up event listeners");- unlisten();- });- });-const addMediaEntry = (path: string, type?: "recording" | "screenshot") => {const setMedia = type === "screenshot" ? setScreenshots : setRecordings;setMedia(@@ -161,12 +115,10 @@ export default function () {const type = media.type ?? "recording";const isRecording = type !== "screenshot";- const { copy, save, upload } = createRecordingMutations(- media,- (e) => {+ const { copy, save, upload, actionState } =+ createRecordingMutations(media, (e) => {if (e === "upgradeRequired") setShowUpgradeTooltip(true);- }- );+ });const [metadata] = createResource(async () => {if (!isRecording) return null;@@ -250,166 +202,88 @@ export default function () {/></Show>- <Show- when={- progressState.type !== "idle" &&- progressState.mediaPath === media.path- }- >- <div- style={{- "background-color": "rgba(0, 0, 0, 0.85)",- }}- class="absolute inset-0 flex items-center justify-center z-[999999] pointer-events-auto"+ <Switch>+ <Match+ when={+ actionState.type === "copy" && actionState.state+ }+ keyed>- <div class="w-[80%] text-center">- <h3 class="text-sm font-medium mb-3 text-gray-50 dark:text-gray-500">- <Switch>- <Match- when={- progressState.type === "copying" &&- progressState- }- >- {(state) => (- <h3 class="text-sm font-medium mb-3 text-gray-50 dark:text-gray-500">- {isRecording- ? state().stage === "rendering"- ? "Rendering video"- : "Copying to clipboard"- : "Copying image to clipboard"}- </h3>- )}- </Match>- <Match- when={- progressState.type === "saving" &&- progressState- }- >- {(state) => (- <h3 class="text-sm font-medium mb-3 text-gray-50 dark:text-gray-500">- {isRecording- ? state().stage === "rendering"- ? "Rendering video"- : "Saving video"- : "Saving image"}- </h3>- )}- </Match>- <Match- when={- progressState.type === "uploading" &&- progressState- }- >- {(state) => (- <h3 class="text-sm font-medium mb-3 text-gray-50 dark:text-gray-500">- {state().stage === "rendering"- ? "Rendering video"- : "Creating shareable link"}- </h3>- )}- </Match>- </Switch>- </h3>-- <div class="w-full bg-gray-400 rounded-full h-2.5 mb-2">- <div- class="bg-blue-300 text-gray-50 dark:text-gray-500 h-2.5 rounded-full transition-all duration-200"- style={{- width: `${(() => {- if (- !progressState ||- progressState.type === "idle"- )- return 0;-- // For rendering progress- if (- progressState.stage === "rendering" &&- progressState.renderProgress !==- undefined &&- progressState.totalFrames- ) {- return Math.min(- Math.round(- (progressState.renderProgress /- progressState.totalFrames) *- 100- ),- 100- );- }-- // For upload progress- if (- progressState.type === "uploading" &&- progressState.stage === "uploading"- ) {- return Math.min(- progressState.uploadProgress * 100,- 100- );- }-- // For other progress types- return Math.min(- ("progress" in progressState &&- progressState.progress) ||- 0,- 100- );- })()}%`,- }}- />- </div>-- <p class="text-xs text-gray-50 dark:text-gray-500 mt-2">- {(() => {- if (- !progressState ||- progressState.type === "idle"- )- return;-- if (- progressState.stage === "rendering" &&- progressState.renderProgress !==- undefined &&- progressState.totalFrames- ) {- const progress = Math.min(- Math.round(- (progressState.renderProgress /- progressState.totalFrames) *- 100- ),- 100- );-- // If we hit 100%, transition to the next stage- if (- progress === 100 &&- progressState.type === "uploading"- ) {- setProgressState({- ...progressState,- stage: "uploading",- message: "Starting upload...",- uploadProgress: 0,- });- }-- return `${progress}%`;+ {(state) => (+ <ActionProgressOverlay+ title={+ state.type === "rendering"+ ? "Rendering video"+ : state.type === "copying"+ ? "Copying to clipboard"+ : "Copied to clipboard"+ }+ progressPercentage={actionProgressPercentage(+ actionState+ )}+ />+ )}+ </Match>+ <Match+ when={+ actionState.type === "save" && actionState.state+ }+ keyed+ >+ {(state) => (+ <ActionProgressOverlay+ title={(() => {+ if (state.type === "choosing-location")+ return "Preparing";++ if (isRecording) {+ if (state.type === "rendering")+ return "Rendering video";+ if (state.type === "saving")+ return "Saving video";+ return "Saved video";+ } else {+ if (state.type === "rendering")+ return "Rendering image";+ if (state.type === "saving")+ return "Saving image";+ return "Saved image";}-- return progressState.message;})()}- </p>- </div>- </div>- </Show>+ progressPercentage={actionProgressPercentage(+ actionState+ )}+ progressMessage={+ state.type === "choosing-location" &&+ `Choose where to ${+ isRecording ? "export video" : "save image"+ }...`+ }+ />+ )}+ </Match>+ <Match+ when={+ actionState.type === "upload" && actionState.state+ }+ keyed+ >+ {(state) => (+ <ActionProgressOverlay+ title={+ state.type === "rendering"+ ? "Rendering video"+ : state.type === "uploading"+ ? "Creating shareable link"+ : "Shareable link copied"+ }+ progressPercentage={actionProgressPercentage(+ actionState+ )}+ />+ )}+ </Match>+ </Switch><divstyle={{@@ -417,7 +291,7 @@ export default function () {}}class={cx("w-full h-full absolute inset-0 transition-all duration-150 pointer-events-auto rounded-[7.4px]",- isLoading() || showUpgradeTooltip()+ showUpgradeTooltip()? "opacity-100": "opacity-0 group-hover:opacity-100","backdrop-blur text-white p-2"@@ -489,102 +363,29 @@ export default function () {: "Copy to Clipboard"}tooltipPlacement="left"- onClick={(e) =>- copy.mutate(- (e.ctrlKey || e.metaKey) && e.shiftKey- )- }- disabled={save.isPending || upload.isPending}+ onClick={() => copy.mutate()}>- <Switch- fallback={<IconCapCopy class="size-[1rem]" />}- >- <Match when={copy.isPending}>- <IconLucideLoaderCircle class="size-[1rem] animate-spin" />- </Match>- <Match when={copy.isSuccess}>- {(_) => {- setTimeout(() => {- if (!copy.isPending) copy.reset();- }, 2000);-- return (- <IconLucideCheck class="size-[1rem]" />- );- }}- </Match>- </Switch>+ <IconCapCopy class="size-[1rem]" /></TooltipIconButton><TooltipIconButtonclass="absolute right-3 bottom-3 z-[998]"tooltipText={recordingMeta.data?.sharing? "Copy Shareable Link"- : upload.isPending- ? "Uploading Cap"- : showUpgradeTooltip()- ? "Upgrade Required": "Create Shareable Link"}tooltipPlacement="left"- onClick={(e) => {- upload.mutate(- (e.ctrlKey || e.metaKey) && e.shiftKey- );- }}- disabled={- copy.isPending ||- save.isPending ||- recordingMeta.isLoading ||- recordingMeta.isError- }+ onClick={() => upload.mutate()}>- <Switch- fallback={<IconCapUpload class="size-[1rem]" />}- >- <Match when={upload.isPending}>- <IconLucideLoaderCircle class="size-[1rem] animate-spin" />- </Match>- <Match when={upload.isSuccess}>- {(_) => {- setTimeout(() => {- if (!upload.isPending) upload.reset();- }, 2000);-- return (- <IconLucideCheck class="size-[1rem]" />- );- }}- </Match>- </Switch>+ <IconCapUpload class="size-[1rem]" /></TooltipIconButton><div class="absolute inset-0 flex items-center justify-center"><Buttonvariant="white"size="sm"- onClick={(e) =>- save.mutate(- (e.ctrlKey || e.metaKey) && e.shiftKey- )- }- disabled={copy.isPending || upload.isPending}+ onClick={() => save.mutate()}>- <Switch fallback="Export">- <Match when={save.isPending}>- Exporting...- </Match>- <Match- when={save.isSuccess && save.data === true}- >- {(_) => {- setTimeout(() => {- if (!save.isPending) save.reset();- }, 2000);-- return "Exported!";- }}- </Match>- </Switch>+ Export</Button></div></div>@@ -646,6 +447,42 @@ export default function () {);}+function ActionProgressOverlay(props: {+ title: string;+ // percentage 0-100+ progressPercentage: number;+ progressMessage?: string | false;+}) {+ return (+ <div+ style={{+ "background-color": "rgba(0, 0, 0, 0.85)",+ }}+ class="absolute inset-0 flex items-center justify-center z-[999999] pointer-events-auto"+ >+ <div class="w-[80%] text-center">+ <h3 class="text-sm font-medium mb-3 text-gray-50 dark:text-gray-500">+ {props.title}+ </h3>+ <div class="w-full bg-gray-400 rounded-full h-2.5 mb-2">+ <div+ class="bg-blue-300 text-gray-50 dark:text-gray-500 h-2.5 rounded-full transition-all duration-200"+ style={{+ width: `${Math.max(0, Math.min(100, props.progressPercentage))}%`,+ }}+ />+ </div>++ <p class="text-xs text-gray-50 dark:text-gray-500 mt-2">+ {typeof props.progressMessage === "string"+ ? props.progressMessage+ : `${Math.floor(props.progressPercentage)}%`}+ </p>+ </div>+ </div>+ );+}+const IconButton = (props: ComponentProps<"button">) => {return (<button@@ -747,49 +584,15 @@ function createRecordingMutations(}));const copy = createMutation(() => ({- mutationFn: async (useCustomMuxer: boolean) => {- setProgressState({- type: "copying",- progress: 0,- renderProgress: 0,- totalFrames: 0,- message: "Preparing...",- mediaPath: media.path,- stage: "rendering",+ mutationFn: async () => {+ setActionState({+ type: "copy",+ state: { type: "rendering", state: { type: "starting" } },});try {if (isRecording) {- const progress = new Channel<RenderProgress>();- progress.onmessage = (p) => {- console.log("Progress channel message:", p);- if (- p.type === "FrameRendered" &&- progressState.type === "copying"- ) {- console.log(- "Frame rendered:",- p.current_frame,- "Total frames:",- progressState.totalFrames- );- setProgressState({- ...progressState,- message: "Rendering video...",- renderProgress: p.current_frame,- });- }- if (- p.type === "EstimatedTotalFrames" &&- progressState.type === "copying"- ) {- console.log("Got total frames:", p.total_frames);- setProgressState({- ...progressState,- totalFrames: p.total_frames,- });- }- };+ const progress = createRenderProgressChannel("copy", setActionState);// First try to get existing rendered videoconst outputPath = await commands.exportVideo(@@ -802,182 +605,121 @@ function createRecordingMutations();// Show quick progress animation for existing video- setProgressState({- type: "copying",- progress: 0,- renderProgress: 100,- totalFrames: 100,- message: "Copying to clipboard...",- mediaPath: media.path,- stage: "rendering",- });+ setActionState(+ produce((s) => {+ if (+ s.type === "copy" &&+ s.state.type === "rendering" &&+ s.state.state.type === "rendering"+ )+ s.state.state.renderedFrames = s.state.state.totalFrames;+ })+ );await commands.copyVideoToClipboard(outputPath);} else {// For screenshots, show quick progress animation- setProgressState({- type: "copying",- progress: 50,- renderProgress: 100,- totalFrames: 100,- message: "Copying image to clipboard...",- mediaPath: media.path,- stage: "rendering",+ setActionState({+ type: "copy",+ state: { type: "copying" },});await commands.copyScreenshotToClipboard(media.path);}- setProgressState({- type: "copying",- progress: 100,- renderProgress: 100,- totalFrames: 100,- message: "Copied successfully!",- mediaPath: media.path,- stage: "rendering",+ setActionState({+ type: "copy",+ state: { type: "copied" },});-- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);} catch (error) {console.error("Error in copy media:", error);- setProgressState({ type: "idle" });throw error;}},+ onSuccess() {+ setTimeout(() => {+ setActionState({ type: "idle" });+ }, 1500);+ },}));const save = createMutation(() => ({- mutationFn: async (useCustomMuxer: boolean) => {- setProgressState({- type: "saving",- progress: 0,- renderProgress: 0,- totalFrames: 0,- message: isRecording- ? "Choose where to export video..."- : "Choose where to save image...",- mediaPath: media.path,- stage: "rendering",- });-- try {- const meta = recordingMeta.data;- if (!meta) {- throw new Error("Recording metadata not available");- }+ mutationFn: async () => {+ const meta = recordingMeta.data;+ if (!meta) {+ throw new Error("Recording metadata not available");+ }- const defaultName = isRecording- ? "Cap Recording"- : media.path.split(".cap/")[1];- const suggestedName = meta.pretty_name || defaultName;+ const defaultName = isRecording+ ? "Cap Recording"+ : media.path.split(".cap/")[1];+ const suggestedName = meta.pretty_name || defaultName;- const fileType = isRecording ? "recording" : "screenshot";- const extension = isRecording ? ".mp4" : ".png";+ const fileType = isRecording ? "recording" : "screenshot";+ const extension = isRecording ? ".mp4" : ".png";- const fullFileName = suggestedName.endsWith(extension)- ? suggestedName- : `${suggestedName}${extension}`;+ const fullFileName = suggestedName.endsWith(extension)+ ? suggestedName+ : `${suggestedName}${extension}`;- const savePath = await commands.saveFileDialog(fullFileName, fileType);+ setActionState({+ type: "save",+ state: {+ type: "choosing-location",+ mediaType: isRecording ? "video" : "screenshot",+ },+ });- if (!savePath) {- setProgressState({ type: "idle" });- return false;- }+ const savePath = await commands.saveFileDialog(fullFileName, fileType);- if (isRecording) {- // Create a progress channel to track rendering- const progress = new Channel<RenderProgress>();- progress.onmessage = (p) => {- console.log("Progress channel message:", p);- if (p.type === "FrameRendered" && progressState.type === "saving") {- console.log(- "Frame rendered:",- p.current_frame,- "Total frames:",- progressState.totalFrames- );- setProgressState({- ...progressState,- message: "Rendering video",- renderProgress: p.current_frame,- });- }- if (- p.type === "EstimatedTotalFrames" &&- progressState.type === "saving"- ) {- console.log("Got total frames:", p.total_frames);- setProgressState({- ...progressState,- totalFrames: p.total_frames,- });- }- };+ if (!savePath) {+ setActionState({ type: "idle" });+ return false;+ }- // Always force re-render when saving- const outputPath = await commands.exportVideo(- mediaId,- presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,- progress,- true, // Force re-render- FPS,- OUTPUT_SIZE- );+ setActionState({+ type: "save",+ state: {+ type: "rendering",+ state: { type: "starting" },+ },+ });- await commands.copyFileToPath(outputPath, savePath);- } else {- // For screenshots, show quick progress animation- setProgressState({- type: "saving",- progress: 50,- renderProgress: 0,- totalFrames: 0,- message: "Saving image...",- mediaPath: media.path,- stage: "rendering",- });+ if (isRecording) {+ const progress = createRenderProgressChannel("save", setActionState);++ // Always force re-render when saving+ const outputPath = await commands.exportVideo(+ mediaId,+ presets.getDefaultConfig() ?? DEFAULT_PROJECT_CONFIG,+ progress,+ true, // Force re-render+ FPS,+ OUTPUT_SIZE+ );- await commands.copyFileToPath(media.path, savePath);- }+ await commands.copyFileToPath(outputPath, savePath);+ } else {+ // For screenshots, show quick progress animation+ setActionState({ type: "save", state: { type: "saving" } });- setProgressState({- type: "saving",- progress: 100,- renderProgress: 100,- totalFrames: 100,- message: "Exported successfully!",- mediaPath: media.path,- stage: "rendering",- });+ await commands.copyFileToPath(media.path, savePath);+ }- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);+ setActionState({ type: "save", state: { type: "saved" } });- return true;- } catch (error) {- setProgressState({ type: "idle" });- throw error;- }+ return true;+ },+ onSettled() {+ setTimeout(() => {+ setActionState({ type: "idle" });+ }, 1500);},}));const upload = createMutation(() => ({- mutationFn: async (useCustomMuxer: boolean) => {+ mutationFn: async () => {if (recordingMeta.data?.sharing) {- setProgressState({- type: "copying",- progress: 100,- message: "Link copied to clipboard!",- mediaPath: media.path,- });-- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);+ setActionState({ type: "upload", state: { type: "link-copied" } });await commands.writeClipboardString(recordingMeta.data.sharing.link);@@ -1007,63 +749,35 @@ function createRecordingMutations(}}- if (!isRecording) {- setProgressState({- type: "uploading",- renderProgress: 0,- uploadProgress: 0,- message: "Uploading screenshot...",- mediaPath: media.path,- stage: "uploading",- });- } else {- setProgressState({- type: "uploading",- renderProgress: 0,- uploadProgress: 0,- message: "Preparing to render...",- mediaPath: media.path,- stage: "rendering",- });- }+ const unlisten = await events.uploadProgress.listen((event) => {+ console.log("Upload progress event:", event.payload);+ setActionState(+ produce((actionState) => {+ if (+ actionState.type !== "upload" ||+ actionState.state.type !== "uploading"+ )+ return;++ actionState.state.progress = Math.round(+ event.payload.progress * 100+ );+ })+ );+ });try {let res: UploadResult;if (isRecording) {- const progress = new Channel<RenderProgress>();- progress.onmessage = (p) => {- console.log("Progress channel message:", p);- if (- p.type === "FrameRendered" &&- progressState.type === "uploading"- ) {- console.log(- "Frame rendered:",- p.current_frame,- "Total frames:",- progressState.totalFrames- );- setProgressState({- ...progressState,- message: "Rendering video...",- renderProgress: progressState.totalFrames- ? Math.round(- (p.current_frame / progressState.totalFrames) * 100- )- : 0,- });- }- if (- p.type === "EstimatedTotalFrames" &&- progressState.type === "uploading"- ) {- console.log("Got total frames:", p.total_frames);- setProgressState({- ...progressState,- totalFrames: p.total_frames,- });- }- };+ setActionState({+ type: "upload",+ state: { type: "rendering", state: { type: "starting" } },+ });++ const progress = createRenderProgressChannel(+ "upload",+ setActionState+ );// First try to get existing rendered videoawait commands.exportVideo(@@ -1077,19 +791,31 @@ function createRecordingMutations(console.log("Using existing rendered video");// Show quick progress animation for existing video- setProgressState({- type: "uploading",- renderProgress: 100,- uploadProgress: 0,- message: "Starting upload...",- mediaPath: media.path,- stage: "uploading",+ setActionState(+ produce((s) => {+ if (+ s.type === "copy" &&+ s.state.type === "rendering" &&+ s.state.state.type === "rendering"+ )+ s.state.state.renderedFrames = s.state.state.totalFrames;+ })+ );++ setActionState({+ type: "upload",+ state: { type: "uploading", progress: 0 },});res = await commands.uploadExportedVideo(mediaId, {Initial: { pre_created_video: null },});} else {+ setActionState({+ type: "upload",+ state: { type: "uploading", progress: 0 },+ });+res = await commands.uploadScreenshot(media.path);}@@ -1099,32 +825,132 @@ function createRecordingMutations(case "PlanCheckFailed":throw new Error("Plan check failed");case "UpgradeRequired":- setProgressState({ type: "idle" });onEvent("upgradeRequired");return;default:break;}-- setProgressState({- type: "uploading",- renderProgress: 100,- uploadProgress: 100,- message: "Link copied to clipboard!",- mediaPath: media.path,- stage: "uploading",- });-- setTimeout(() => {- setProgressState({ type: "idle" });- }, 1500);- } catch (error) {- setProgressState({ type: "idle" });- throw error;+ } finally {+ unlisten();}++ setActionState({ type: "upload", state: { type: "link-copied" } });+ },+ onSettled() {+ setTimeout(() => {+ setActionState({ type: "idle" });+ }, 1500);},onSuccess: () => startTransition(() => recordingMeta.refetch()),}));- return { copy, save, upload };+ const [actionState, setActionState] = createStore<ActionState>({+ type: "idle",+ });++ return { copy, save, upload, actionState };}++type ActionState =+ | { type: "idle" }+ | {+ type: "copy";+ state:+ | { type: "rendering"; state: RenderState }+ | { type: "copying" }+ | { type: "copied" };+ }+ | {+ type: "save";+ state:+ | { type: "choosing-location"; mediaType: "video" | "screenshot" }+ | { type: "rendering"; state: RenderState }+ | { type: "saving" }+ | { type: "saved" };+ }+ | {+ type: "upload";+ state:+ | { type: "rendering"; state: RenderState }+ | {+ type: "uploading";+ // 0-100+ progress: number;+ }+ | { type: "link-copied" };+ };++function createRenderProgressChannel(+ actionType: Exclude<ActionState["type"], "idle">,+ setActionState: SetStoreFunction<ActionState>+) {+ const progress = new Channel<RenderProgress>();++ progress.onmessage = (msg) => {+ setActionState(+ produce((progressState) => {+ if (+ progressState.type !== actionType ||+ progressState.state.type !== "rendering"+ )+ return;++ const renderState = progressState.state.state;++ if (+ msg.type === "EstimatedTotalFrames" &&+ renderState.type === "starting"+ )+ progressState.state.state = {+ type: "rendering",+ renderedFrames: 0,+ totalFrames: msg.total_frames,+ };+ else if (+ msg.type === "FrameRendered" &&+ renderState.type === "rendering"+ )+ renderState.renderedFrames = msg.current_frame;+ })+ );+ };++ return progress;+}++function actionProgressPercentage(state: ActionState): number {+ function renderPercentage(state: RenderState) {+ if (state.type === "starting") return 0;+ else+ return Math.floor(+ Math.min((state.renderedFrames / state.totalFrames) * 100, 100)+ );+ }++ if (state.type === "idle") return 0;++ if (state.state.type === "rendering")+ return renderPercentage(state.state.state);++ switch (state.type) {+ case "copy": {+ return state.state.type === "copied" ? 100 : 50;+ }+ case "save": {+ if (state.state.type === "choosing-location") return 0;+ return state.state.type === "saved" ? 100 : 50;+ }+ case "upload": {+ if (state.state.type === "link-copied") return 100;+ return state.state.progress;+ }+ }+}++type RenderState =+ | {+ type: "rendering";+ renderedFrames: number;+ totalFrames: number;+ }+ | { type: "starting" };diff --git a/apps/desktop/src/store/progress.ts b/apps/desktop/src/store/progress.tsdeleted file mode 100644index b11e3ce18..000000000--- a/apps/desktop/src/store/progress.ts+++ /dev/null@@ -1,39 +0,0 @@-import { createStore } from "solid-js/store";--export type ProgressState =- | {- type: "idle";- }- | {- type: "copying";- progress: number;- message: string;- mediaPath?: string;- stage: "rendering" | undefined;- renderProgress?: number;- totalFrames?: number;- }- | {- type: "saving";- progress: number;- message: string;- mediaPath?: string;- stage: "rendering" | undefined;- renderProgress?: number;- totalFrames?: number;- }- | {- type: "uploading";- renderProgress: number;- uploadProgress: number;- message: string;- mediaPath?: string;- stage: "rendering" | "uploading";- totalFrames?: number;- };--const [progressState, setProgressState] = createStore<ProgressState>({- type: "idle",-});--export { progressState, setProgressState };\ No newline at end of filediff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 0b166cfbc..2ceeb9fec 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -289,7 +289,7 @@ export type SingleSegment = { display: Display; camera?: CameraMeta | null; audiexport type TimelineConfiguration = { segments: TimelineSegment[]; zoomSegments: ZoomSegment[] }export type TimelineSegment = { recordingSegment: number | null; timescale: number; start: number; end: number }export type UploadMode = { Initial: { pre_created_video: PreCreatedVideo | null } } | "Reupload"-export type UploadProgress = { stage: string; progress: number; message: string }+export type UploadProgress = { progress: number; message: string }export type UploadResult = { Success: string } | "NotAuthenticated" | "PlanCheckFailed" | "UpgradeRequired"export type Video = { duration: number; width: number; height: number; fps: number }export type VideoRecordingMetadata = { duration: number; size: number }diff --git a/apps/desktop/tsconfig.tsbuildinfo b/apps/desktop/tsconfig.tsbuildinfoindex 64c5e7d2f..69cca36f4 100644--- a/apps/desktop/tsconfig.tsbuildinfo+++ b/apps/desktop/tsconfig.tsbuildinfo@@ -1 +1 @@-{"root":["./src/app.tsx","./src/entry-client.tsx","./src/entry-server.tsx","./src/global.d.ts","./src/icons.tsx","./src/store.ts","./src/vite-env.d.ts","./src/components/loader.tsx","./src/components/switchtab.tsx","./src/components/titlebar/titlebar.tsx","./src/components/titlebar/controls/captioncontrolswindows11.tsx","./src/components/titlebar/controls/windowcontrolbutton.tsx","./src/routes/(window-chrome).tsx","./src/routes/camera.tsx","./src/routes/in-progress-recording.tsx","./src/routes/notifications.tsx","./src/routes/prev-recordings.tsx","./src/routes/window-capture-occluder.tsx","./src/routes/(window-chrome)/(main).tsx","./src/routes/(window-chrome)/callback.template.ts","./src/routes/(window-chrome)/settings.tsx","./src/routes/(window-chrome)/setup.tsx","./src/routes/(window-chrome)/signin.tsx","./src/routes/(window-chrome)/update.tsx","./src/routes/(window-chrome)/upgrade.tsx","./src/routes/(window-chrome)/settings/changelog.tsx","./src/routes/(window-chrome)/settings/feedback.tsx","./src/routes/(window-chrome)/settings/general.tsx","./src/routes/(window-chrome)/settings/hotkeys.tsx","./src/routes/(window-chrome)/settings/index.tsx","./src/routes/(window-chrome)/settings/recordings.tsx","./src/routes/(window-chrome)/settings/screenshots.tsx","./src/routes/(window-chrome)/settings/apps/index.tsx","./src/routes/(window-chrome)/settings/apps/s3-config.tsx","./src/routes/editor/configsidebar.tsx","./src/routes/editor/editor.tsx","./src/routes/editor/header.tsx","./src/routes/editor/player.tsx","./src/routes/editor/timeline.tsx","./src/routes/editor/context.ts","./src/routes/editor/editorinstancecontext.ts","./src/routes/editor/index.tsx","./src/routes/editor/projectconfig.ts","./src/routes/editor/ui.tsx","./src/routes/editor/utils.ts","./src/store/progress.ts","./src/utils/createpresets.ts","./src/utils/env.ts","./src/utils/events.ts","./src/utils/plans.ts","./src/utils/queries.ts","./src/utils/socket.ts","./src/utils/tauri.ts","./src/utils/titlebar-state.ts","./src/utils/web-api.ts"],"version":"5.7.2"}\ No newline at end of file+{"root":["./src/app.tsx","./src/entry-client.tsx","./src/entry-server.tsx","./src/global.d.ts","./src/icons.tsx","./src/store.ts","./src/vite-env.d.ts","./src/components/loader.tsx","./src/components/switchtab.tsx","./src/components/titlebar/titlebar.tsx","./src/components/titlebar/controls/captioncontrolswindows11.tsx","./src/components/titlebar/controls/windowcontrolbutton.tsx","./src/routes/(window-chrome).tsx","./src/routes/camera.tsx","./src/routes/in-progress-recording.tsx","./src/routes/notifications.tsx","./src/routes/recordings-overlay.tsx","./src/routes/window-capture-occluder.tsx","./src/routes/(window-chrome)/(main).tsx","./src/routes/(window-chrome)/callback.template.ts","./src/routes/(window-chrome)/settings.tsx","./src/routes/(window-chrome)/setup.tsx","./src/routes/(window-chrome)/signin.tsx","./src/routes/(window-chrome)/update.tsx","./src/routes/(window-chrome)/upgrade.tsx","./src/routes/(window-chrome)/settings/changelog.tsx","./src/routes/(window-chrome)/settings/config.tsx","./src/routes/(window-chrome)/settings/feedback.tsx","./src/routes/(window-chrome)/settings/general.tsx","./src/routes/(window-chrome)/settings/hotkeys.tsx","./src/routes/(window-chrome)/settings/index.tsx","./src/routes/(window-chrome)/settings/recordings.tsx","./src/routes/(window-chrome)/settings/screenshots.tsx","./src/routes/(window-chrome)/settings/apps/index.tsx","./src/routes/(window-chrome)/settings/apps/s3-config.tsx","./src/routes/editor/configsidebar.tsx","./src/routes/editor/editor.tsx","./src/routes/editor/header.tsx","./src/routes/editor/player.tsx","./src/routes/editor/timeline.tsx","./src/routes/editor/context.ts","./src/routes/editor/index.tsx","./src/routes/editor/projectconfig.ts","./src/routes/editor/ui.tsx","./src/routes/editor/utils.ts","./src/store/progress.ts","./src/utils/createpresets.ts","./src/utils/env.ts","./src/utils/events.ts","./src/utils/plans.ts","./src/utils/queries.ts","./src/utils/socket.ts","./src/utils/tauri.ts","./src/utils/titlebar-state.ts","./src/utils/web-api.ts"],"version":"5.7.2"}\ No newline at end of filediff --git a/crates/media/src/data.rs b/crates/media/src/data.rsindex 2e1b23f14..1e7eb6940 100644--- a/crates/media/src/data.rs+++ b/crates/media/src/data.rs@@ -173,6 +173,7 @@ impl AudioInfo {let interleaved_chunk_size = sample_size * self.channels;let samples = data.len() / interleaved_chunk_size;+ dbg!(samples);let mut frame = FFAudio::new(self.sample_format, samples, self.channel_layout());frame.set_pts(Some(timestamp));frame.set_rate(self.sample_rate);diff --git a/crates/media/src/encoders/mp4.rs b/crates/media/src/encoders/mp4.rsindex 36f760f33..e1478d473 100644--- a/crates/media/src/encoders/mp4.rs+++ b/crates/media/src/encoders/mp4.rs@@ -203,6 +203,7 @@ impl MP4Encoder {// frame.samples()// );+ dbg!(audio.encoder.frame_size());audio.buffer.consume(frame);// Process all buffered frames@@ -220,6 +221,10 @@ impl MP4Encoder {output.set_pts(Some(pts));}+ let data = output.data(0);+ let data_f32 =+ unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, data.len() / 4) };+// Send frame to encoderaudio.encoder.send_frame(&output).unwrap();diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rsindex b2c20a6e7..20bd60cc1 100644--- a/crates/media/src/feeds/camera.rs+++ b/crates/media/src/feeds/camera.rs@@ -414,185 +414,3 @@ fn buffer_to_ffvideo(buffer: nokhwa::Buffer) -> FFVideo {frame}--struct FrameConverter {- video_info: VideoInfo,- context: scaling::Context,- pub format: FrameFormat,- hw_converter: Option<HwConverter>,-}--pub enum HwConverter {- NV12(NV12ToRGBA),- UYVY(UYVYToRGBA),-}--impl FrameConverter {- fn build(camera_format: CameraFormat) -> Self {- let format = match camera_format.format() {- FrameFormat::MJPEG => RawVideoFormat::Mjpeg,- FrameFormat::YUYV => RawVideoFormat::YUYV420,- FrameFormat::NV12 => RawVideoFormat::Nv12,- FrameFormat::GRAY => RawVideoFormat::Gray,- FrameFormat::RAWRGB => RawVideoFormat::RawRgb,- FrameFormat::BGRA => RawVideoFormat::Bgra,- };-- let video_info = VideoInfo::from_raw(- format,- camera_format.width(),- camera_format.height(),- camera_format.frame_rate(),- );-- // Create FFmpeg converter- let context = ffmpeg::software::converter(- (video_info.width, video_info.height),- if camera_format.format() == FrameFormat::YUYV {- ffmpeg::format::Pixel::UYVY422- } else {- video_info.pixel_format- },- ffmpeg::format::Pixel::RGBA,- )- .unwrap();-- Self {- video_info,- context,- format: camera_format.format(),- hw_converter: None, // Don't use hardware converters- }- }-- fn rgba(&mut self, buffer: &nokhwa::Buffer) -> Vec<u8> {- let resolution = buffer.resolution();-- match self.format {- FrameFormat::YUYV => self.convert_with_ffmpeg(buffer, resolution),- _ => match &self.hw_converter {- Some(HwConverter::NV12(converter)) => converter.convert(- NV12Input::from_buffer(- buffer.buffer(),- resolution.width(),- resolution.height(),- ),- resolution.width(),- resolution.height(),- ),- _ => self.convert_with_ffmpeg(buffer, resolution),- },- }- }-- fn convert_with_ffmpeg(&mut self, buffer: &nokhwa::Buffer, resolution: Resolution) -> Vec<u8> {- if self.format == FrameFormat::YUYV {- // For YUYV, we need to handle the conversion differently- let stride = resolution.width() as usize * 2; // YUYV uses 2 bytes per pixel- let src = buffer.buffer();-- // Create input frame with YUYV format and copy data- let mut input_frame = FFVideo::new(- ffmpeg::format::Pixel::UYVY422,- resolution.width(),- resolution.height(),- );-- // Copy data line by line- {- let dst_stride = input_frame.stride(0);- let dst = input_frame.data_mut(0);- for y in 0..resolution.height() as usize {- let src_offset = y * stride;- let dst_offset = y * dst_stride;- dst[dst_offset..dst_offset + stride]- .copy_from_slice(&src[src_offset..src_offset + stride]);- }- }-- // Create output frame- let mut rgba_frame = FFVideo::new(- ffmpeg::format::Pixel::RGBA,- resolution.width(),- resolution.height(),- );-- // Convert the frame- if self.context.run(&input_frame, &mut rgba_frame).is_ok() {- rgba_frame.data(0).to_vec()- } else {- vec![0; (resolution.width() * resolution.height() * 4) as usize]- }- } else {- // For other formats, use the normal conversion path- let stride = match self.format {- FrameFormat::NV12 => resolution.width() as usize,- FrameFormat::BGRA => resolution.width() as usize * 4,- FrameFormat::MJPEG => resolution.width() as usize * 4,- FrameFormat::GRAY => resolution.width() as usize,- FrameFormat::RAWRGB => resolution.width() as usize * 3,- _ => buffer.buffer_bytes().len() / resolution.height() as usize,- };-- // Create input frame and copy data- let mut input_frame = FFVideo::new(- match self.format {- FrameFormat::NV12 => ffmpeg::format::Pixel::NV12,- FrameFormat::BGRA => ffmpeg::format::Pixel::BGRA,- FrameFormat::MJPEG => ffmpeg::format::Pixel::RGBA,- FrameFormat::GRAY => ffmpeg::format::Pixel::GRAY8,- FrameFormat::RAWRGB => ffmpeg::format::Pixel::RGB24,- _ => ffmpeg::format::Pixel::RGBA,- },- resolution.width(),- resolution.height(),- );-- // Copy data line by line- {- let dst_stride = input_frame.stride(0);- let dst = input_frame.data_mut(0);- let src = buffer.buffer();- for y in 0..resolution.height() as usize {- let src_offset = y * stride;- let dst_offset = y * dst_stride;- dst[dst_offset..dst_offset + stride]- .copy_from_slice(&src[src_offset..src_offset + stride]);- }- }-- // Create output frame- let mut rgba_frame = FFVideo::new(- ffmpeg::format::Pixel::RGBA,- resolution.width(),- resolution.height(),- );-- // Convert the frame- if self.context.run(&input_frame, &mut rgba_frame).is_ok() {- rgba_frame.data(0).to_vec()- } else {- vec![0; (resolution.width() * resolution.height() * 4) as usize]- }- }- }-- fn raw(&mut self, buffer: &nokhwa::Buffer) -> FFVideo {- dbg!(buffer.source_frame_format());- self.video_info.wrap_frame(- buffer.buffer(),- 0,- buffer.buffer_bytes().len() / buffer.resolution().height() as usize,- )- }-}--fn dropping_send<T>(sender: &Sender<T>, value: T) -> Result<(), flume::SendError<T>> {- sender.try_send(value).or_else(|error| match error {- flume::TrySendError::Full(_) => {- // tracing::debug!("Channel is full. Dropping camera frame");- Ok(())- }- flume::TrySendError::Disconnected(v) => Err(flume::SendError(v)),- })-}diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rsindex 0ef7f34db..67c87a0e3 100644--- a/crates/media/src/sources/screen_capture.rs+++ b/crates/media/src/sources/screen_capture.rs@@ -220,7 +220,7 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {show_highlight: true,target: Some(target),crop_area,- output_type: self.output_type.unwrap_or(FrameType::YUVFrame),+ output_type: self.output_type.unwrap_or(FrameType::BGRAFrame),output_resolution: self.output_resolution.unwrap_or(ScapResolution::Captured),excluded_targets: Some(excluded_targets),}