Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix: wallpaper backgrounds black in exported video (#376)

Enriquefftd145f8004155
diff --git a/electron-builder.json5 b/electron-builder.json5
index 18498df64..441eda426 100644
--- a/electron-builder.json5
+++ b/electron-builder.json5
@@ -23,7 +23,7 @@
"extraResources": [
{
"from": "public/wallpapers",
- "to": "assets/wallpapers"
+ "to": "wallpapers"
}
],
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 261d93fc7..6aec9712e 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -801,15 +801,16 @@ export function registerIpcHandlers(
}
});
- // Return base path for assets so renderer can resolve file:// paths in production
+ // Return base path for assets so renderer can resolve file:// paths in production.
+ // Packaged: electron-builder extraResources copies public/wallpapers -> resources/wallpapers.
+ // Unpackaged: wallpapers live at <appPath>/public/wallpapers.
+ // Single convention: "<base>/wallpapers/x.jpg" resolves in both modes.
ipcMain.handle("get-asset-base-path", () => {
try {
- if (app.isPackaged) {
- const assetPath = path.join(process.resourcesPath, "assets");
- return pathToFileURL(`${assetPath}${path.sep}`).toString();
- }
- const assetPath = path.join(app.getAppPath(), "public", "assets");
- return pathToFileURL(`${assetPath}${path.sep}`).toString();
+ const baseDir = app.isPackaged
+ ? process.resourcesPath
+ : path.join(app.getAppPath(), "public");
+ return pathToFileURL(`${baseDir}${path.sep}`).toString();
} catch (err) {
console.error("Failed to resolve asset base path:", err);
return null;
diff --git a/nix/package.nix b/nix/package.nix
index 195043f21..13a8658bd 100644
--- a/nix/package.nix
+++ b/nix/package.nix
@@ -68,10 +68,10 @@ buildNpmPackage {
cp -r node_modules "$out/lib/openscreen/"
# Asset resolution: when app.isPackaged is false, the main process resolves
- # assets at <appPath>/public/assets/. Mirror the electron-builder
- # extraResources layout so wallpapers load correctly.
- mkdir -p "$out/lib/openscreen/public/assets"
- cp -r public/wallpapers "$out/lib/openscreen/public/assets/wallpapers"
+ # assets at <appPath>/public/. Place wallpapers at that root to match the
+ # packaged layout (electron-builder extraResources -> resources/wallpapers).
+ mkdir -p "$out/lib/openscreen/public"
+ cp -r public/wallpapers "$out/lib/openscreen/public/wallpapers"
# Wrap system electron with the app directory
mkdir -p "$out/bin"
diff --git a/src/components/video-editor/VideoEditor.tsx b/src/components/video-editor/VideoEditor.tsx
index 6d21d13c9..3694d9ef0 100644
--- a/src/components/video-editor/VideoEditor.tsx
+++ b/src/components/video-editor/VideoEditor.tsx
@@ -32,6 +32,7 @@ import { computeFrameStepTime } from "@/lib/frameStep";
import type { ProjectMedia } from "@/lib/recordingSession";
import { matchesShortcut } from "@/lib/shortcuts";
import { loadUserPreferences, saveUserPreferences } from "@/lib/userPreferences";
+import { BackgroundLoadError } from "@/lib/wallpaper";
import {
getAspectRatioValue,
getNativeAspectRatioValue,
@@ -1566,9 +1567,15 @@ export default function VideoEditor() {
}
} catch (error) {
console.error("Export error:", error);
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
- setExportError(errorMessage);
- toast.error(`Export failed: ${errorMessage}`);
+ if (error instanceof BackgroundLoadError) {
+ const message = t("errors.exportBackgroundLoadFailed", { url: error.url });
+ setExportError(message);
+ toast.error(message);
+ } else {
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
+ setExportError(errorMessage);
+ toast.error(t("errors.exportFailedWithError", { error: errorMessage }));
+ }
} finally {
setIsExporting(false);
exporterRef.current = null;
@@ -1601,6 +1608,7 @@ export default function VideoEditor() {
exportQuality,
handleExportSaved,
cursorTelemetry,
+ t,
],
);
diff --git a/src/components/video-editor/VideoPlayback.tsx b/src/components/video-editor/VideoPlayback.tsx
index b798641e4..db69310fb 100644
--- a/src/components/video-editor/VideoPlayback.tsx
+++ b/src/components/video-editor/VideoPlayback.tsx
@@ -18,7 +18,6 @@ import {
useRef,
useState,
} from "react";
-import { getAssetPath } from "@/lib/assetPath";
import {
getWebcamLayoutCssBoxShadow,
type Size,
@@ -26,6 +25,7 @@ import {
type WebcamLayoutPreset,
type WebcamSizePreset,
} from "@/lib/compositeLayout";
+import { classifyWallpaper, DEFAULT_WALLPAPER, resolveImageWallpaperUrl } from "@/lib/wallpaper";
import { getCssClipPath } from "@/lib/webcamMaskShapes";
import {
type AspectRatio,
@@ -1179,49 +1179,14 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(
useEffect(() => {
let mounted = true;
(async () => {
- try {
- if (!wallpaper) {
- const def = await getAssetPath("wallpapers/wallpaper1.jpg");
- if (mounted) setResolvedWallpaper(def);
- return;
- }
-
- if (
- wallpaper.startsWith("#") ||
- wallpaper.startsWith("linear-gradient") ||
- wallpaper.startsWith("radial-gradient")
- ) {
- if (mounted) setResolvedWallpaper(wallpaper);
- return;
- }
-
- // If it's a data URL (custom uploaded image), use as-is
- if (wallpaper.startsWith("data:")) {
- if (mounted) setResolvedWallpaper(wallpaper);
- return;
- }
-
- // If it's an absolute web/http or file path, use as-is
- if (
- wallpaper.startsWith("http") ||
- wallpaper.startsWith("file://") ||
- wallpaper.startsWith("/")
- ) {
- // If it's an absolute server path (starts with '/'), resolve via getAssetPath as well
- if (wallpaper.startsWith("/")) {
- const rel = wallpaper.replace(/^\//, "");
- const p = await getAssetPath(rel);
- if (mounted) setResolvedWallpaper(p);
- return;
- }
- if (mounted) setResolvedWallpaper(wallpaper);
- return;
- }
- const p = await getAssetPath(wallpaper.replace(/^\//, ""));
- if (mounted) setResolvedWallpaper(p);
- } catch (_err) {
- if (mounted) setResolvedWallpaper(wallpaper || "/wallpapers/wallpaper1.jpg");
+ const source = wallpaper || DEFAULT_WALLPAPER;
+ const classified = classifyWallpaper(source);
+ if (classified.kind !== "image") {
+ if (mounted) setResolvedWallpaper(classified.value);
+ return;
}
+ const resolved = await resolveImageWallpaperUrl(classified.path);
+ if (mounted) setResolvedWallpaper(resolved);
})();
return () => {
mounted = false;
diff --git a/src/components/video-editor/projectPersistence.ts b/src/components/video-editor/projectPersistence.ts
index c085e0d4c..f9640e4bb 100644
--- a/src/components/video-editor/projectPersistence.ts
+++ b/src/components/video-editor/projectPersistence.ts
@@ -2,6 +2,7 @@ import { normalizeBlurColor, normalizeBlurType } from "@/lib/blurEffects";
import type { ExportFormat, ExportQuality, GifFrameRate, GifSizePreset } from "@/lib/exporter";
import type { ProjectMedia } from "@/lib/recordingSession";
import { normalizeProjectMedia } from "@/lib/recordingSession";
+import { DEFAULT_WALLPAPER } from "@/lib/wallpaper";
import { ASPECT_RATIOS, type AspectRatio, isPortraitAspectRatio } from "@/utils/aspectRatioUtils";
import {
type AnnotationRegion,
@@ -425,7 +426,7 @@ export function normalizeProjectEditor(editor: Partial<ProjectEditorState>): Pro
const cropHeight = clamp(rawCropHeight, 0.01, 1 - cropY);
return {
- wallpaper: typeof editor.wallpaper === "string" ? editor.wallpaper : WALLPAPER_PATHS[0],
+ wallpaper: typeof editor.wallpaper === "string" ? editor.wallpaper : DEFAULT_WALLPAPER,
shadowIntensity: typeof editor.shadowIntensity === "number" ? editor.shadowIntensity : 0,
showBlur: typeof editor.showBlur === "boolean" ? editor.showBlur : false,
motionBlurAmount: isFiniteNumber(editor.motionBlurAmount)
diff --git a/src/hooks/useEditorHistory.ts b/src/hooks/useEditorHistory.ts
index cc19222d6..bd410dae9 100644
--- a/src/hooks/useEditorHistory.ts
+++ b/src/hooks/useEditorHistory.ts
@@ -17,6 +17,7 @@ import {
DEFAULT_WEBCAM_POSITION,
DEFAULT_WEBCAM_SIZE_PRESET,
} from "@/components/video-editor/types";
+import { DEFAULT_WALLPAPER } from "@/lib/wallpaper";
import type { AspectRatio } from "@/utils/aspectRatioUtils";
// Undoable state — selection IDs are intentionally excluded (undoing a
@@ -46,7 +47,7 @@ export const INITIAL_EDITOR_STATE: EditorState = {
speedRegions: [],
annotationRegions: [],
cropRegion: DEFAULT_CROP_REGION,
- wallpaper: "/wallpapers/wallpaper1.jpg",
+ wallpaper: DEFAULT_WALLPAPER,
shadowIntensity: 0,
showBlur: false,
motionBlurAmount: 0,
diff --git a/src/i18n/locales/en/editor.json b/src/i18n/locales/en/editor.json
index a171b1690..254272dcc 100644
--- a/src/i18n/locales/en/editor.json
+++ b/src/i18n/locales/en/editor.json
@@ -14,6 +14,7 @@
"failedToSaveVideo": "Failed to save video",
"exportFailed": "Export failed",
"exportFailedWithError": "Export failed: {{error}}",
+ "exportBackgroundLoadFailed": "Export failed: could not load background image ({{url}})",
"failedToSaveExport": "Failed to save export",
"failedToSaveExportedVideo": "Failed to save exported video",
"failedToRevealInFolder": "Error revealing in folder: {{error}}"
diff --git a/src/i18n/locales/es/editor.json b/src/i18n/locales/es/editor.json
index 7956b7550..c71368af2 100644
--- a/src/i18n/locales/es/editor.json
+++ b/src/i18n/locales/es/editor.json
@@ -8,6 +8,7 @@
"failedToSaveVideo": "Error al guardar el video",
"exportFailed": "La exportación falló",
"exportFailedWithError": "La exportación falló: {{error}}",
+ "exportBackgroundLoadFailed": "La exportación falló: no se pudo cargar la imagen de fondo ({{url}})",
"failedToSaveExport": "Error al guardar la exportación",
"failedToSaveExportedVideo": "Error al guardar el video exportado",
"failedToRevealInFolder": "Error al mostrar en la carpeta: {{error}}"
diff --git a/src/i18n/locales/fr/editor.json b/src/i18n/locales/fr/editor.json
index 03596bde6..ae48fdf13 100644
--- a/src/i18n/locales/fr/editor.json
+++ b/src/i18n/locales/fr/editor.json
@@ -14,6 +14,7 @@
"failedToSaveVideo": "Échec de l'enregistrement de la vidéo",
"exportFailed": "L'export a échoué",
"exportFailedWithError": "L'export a échoué : {{error}}",
+ "exportBackgroundLoadFailed": "L'export a échoué : impossible de charger l'image d'arrière-plan ({{url}})",
"failedToSaveExport": "Échec de l'enregistrement de l'export",
"failedToSaveExportedVideo": "Échec de l'enregistrement de la vidéo exportée",
"failedToRevealInFolder": "Erreur lors de l'affichage dans le dossier : {{error}}"
diff --git a/src/i18n/locales/ko-KR/editor.json b/src/i18n/locales/ko-KR/editor.json
index 4db7d1fb6..eed0261f6 100644
--- a/src/i18n/locales/ko-KR/editor.json
+++ b/src/i18n/locales/ko-KR/editor.json
@@ -14,6 +14,7 @@
"failedToSaveVideo": "비디오 저장에 실패했습니다",
"exportFailed": "내보내기에 실패했습니다",
"exportFailedWithError": "내보내기 실패: {{error}}",
+ "exportBackgroundLoadFailed": "내보내기 실패: 배경 이미지를 불러올 수 없습니다 ({{url}})",
"failedToSaveExport": "내보낸 파일 저장에 실패했습니다",
"failedToSaveExportedVideo": "내보낸 비디오 저장에 실패했습니다",
"failedToRevealInFolder": "폴더에서 파일 표시 오류: {{error}}"
diff --git a/src/i18n/locales/tr/editor.json b/src/i18n/locales/tr/editor.json
index dfa4cb1f3..c34d64b35 100644
--- a/src/i18n/locales/tr/editor.json
+++ b/src/i18n/locales/tr/editor.json
@@ -8,6 +8,7 @@
"failedToSaveVideo": "Video kaydedilemedi",
"exportFailed": "Dışa aktarım başarısız oldu",
"exportFailedWithError": "Dışa aktarım başarısız: {{error}}",
+ "exportBackgroundLoadFailed": "Dışa aktarım başarısız: arka plan görüntüsü yüklenemedi ({{url}})",
"failedToSaveExport": "Dışa aktarım kaydedilemedi",
"failedToSaveExportedVideo": "Dışa aktarılan video kaydedilemedi",
"failedToRevealInFolder": "Klasörde gösterme hatası: {{error}}"
diff --git a/src/i18n/locales/zh-CN/editor.json b/src/i18n/locales/zh-CN/editor.json
index 19803541e..f2eba2ed2 100644
--- a/src/i18n/locales/zh-CN/editor.json
+++ b/src/i18n/locales/zh-CN/editor.json
@@ -14,6 +14,7 @@
"failedToSaveVideo": "保存视频失败",
"exportFailed": "导出失败",
"exportFailedWithError": "导出失败:{{error}}",
+ "exportBackgroundLoadFailed": "导出失败:无法加载背景图片({{url}})",
"failedToSaveExport": "保存导出文件失败",
"failedToSaveExportedVideo": "保存导出的视频失败",
"failedToRevealInFolder": "在文件夹中显示时出错:{{error}}"
diff --git a/src/i18n/locales/zh-TW/editor.json b/src/i18n/locales/zh-TW/editor.json
index 73a3f4e87..ee502fbad 100644
--- a/src/i18n/locales/zh-TW/editor.json
+++ b/src/i18n/locales/zh-TW/editor.json
@@ -14,6 +14,7 @@
"failedToSaveVideo": "儲存影片失敗",
"exportFailed": "匯出失敗",
"exportFailedWithError": "匯出失敗:{{error}}",
+ "exportBackgroundLoadFailed": "匯出失敗:無法載入背景圖片({{url}})",
"failedToSaveExport": "儲存匯出檔案失敗",
"failedToSaveExportedVideo": "儲存匯出的影片失敗",
"failedToRevealInFolder": "在資料夾中顯示時出錯:{{error}}"
diff --git a/src/lib/exporter/frameRenderer.ts b/src/lib/exporter/frameRenderer.ts
index 9b1cf6d68..e7362eb5d 100644
--- a/src/lib/exporter/frameRenderer.ts
+++ b/src/lib/exporter/frameRenderer.ts
@@ -45,6 +45,7 @@ import {
type Size,
type StyledRenderRect,
} from "@/lib/compositeLayout";
+import { BackgroundLoadError, classifyWallpaper, resolveImageWallpaperUrl } from "@/lib/wallpaper";
import { drawCanvasClipPath } from "@/lib/webcamMaskShapes";
import { renderAnnotations } from "./annotationRenderer";
import {
@@ -231,123 +232,93 @@ export class FrameRenderer {
private async setupBackground(): Promise<void> {
const wallpaper = this.config.wallpaper;
- // Create background canvas for separate rendering (not affected by zoom)
const bgCanvas = document.createElement("canvas");
bgCanvas.width = this.config.width;
bgCanvas.height = this.config.height;
const bgCtx = bgCanvas.getContext("2d")!;
- try {
- // Render background based on type
- if (
- wallpaper.startsWith("file://") ||
- wallpaper.startsWith("data:") ||
- wallpaper.startsWith("/") ||
- wallpaper.startsWith("http")
- ) {
- // Image background
- const img = new Image();
- // Don't set crossOrigin for same-origin images to avoid CORS taint
- // Only set it for cross-origin URLs
- let imageUrl: string;
- if (wallpaper.startsWith("http")) {
- imageUrl = wallpaper;
- if (!imageUrl.startsWith(window.location.origin)) {
- img.crossOrigin = "anonymous";
- }
- } else if (wallpaper.startsWith("file://") || wallpaper.startsWith("data:")) {
- imageUrl = wallpaper;
- } else {
- imageUrl = window.location.origin + wallpaper;
- }
+ const classified = classifyWallpaper(wallpaper);
+
+ if (classified.kind === "color") {
+ bgCtx.fillStyle = classified.value;
+ bgCtx.fillRect(0, 0, this.config.width, this.config.height);
+ } else if (classified.kind === "gradient") {
+ const parsedGradient = parseCssGradient(classified.value);
+ if (!parsedGradient) {
+ throw new BackgroundLoadError(classified.value);
+ }
+ const gradient =
+ parsedGradient.type === "linear"
+ ? (() => {
+ const points = getLinearGradientPoints(
+ resolveLinearGradientAngle(parsedGradient.descriptor),
+ this.config.width,
+ this.config.height,
+ );
+ return bgCtx.createLinearGradient(points.x0, points.y0, points.x1, points.y1);
+ })()
+ : (() => {
+ const shape = getRadialGradientShape(
+ parsedGradient.descriptor,
+ this.config.width,
+ this.config.height,
+ );
+ return bgCtx.createRadialGradient(
+ shape.cx,
+ shape.cy,
+ 0,
+ shape.cx,
+ shape.cy,
+ shape.radius,
+ );
+ })();
+
+ parsedGradient.stops.forEach((stop) => {
+ gradient.addColorStop(stop.offset, stop.color);
+ });
+
+ bgCtx.fillStyle = gradient;
+ bgCtx.fillRect(0, 0, this.config.width, this.config.height);
+ } else {
+ const imageUrl = await resolveImageWallpaperUrl(classified.path);
+ const img = new Image();
+ if (imageUrl.startsWith("http") && !imageUrl.startsWith(window.location.origin)) {
+ img.crossOrigin = "anonymous";
+ }
+ try {
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve();
- img.onerror = (err) => {
- console.error("[FrameRenderer] Failed to load background image:", imageUrl, err);
- reject(new Error(`Failed to load background image: ${imageUrl}`));
- };
+ img.onerror = (err) => reject(err);
img.src = imageUrl;
});
+ } catch (err) {
+ throw new BackgroundLoadError(imageUrl, err);
+ }
- // Draw the image using cover and center positioning
- const imgAspect = img.width / img.height;
- const canvasAspect = this.config.width / this.config.height;
-
- let drawWidth, drawHeight, drawX, drawY;
+ const imgAspect = img.width / img.height;
+ const canvasAspect = this.config.width / this.config.height;
- if (imgAspect > canvasAspect) {
- drawHeight = this.config.height;
- drawWidth = drawHeight * imgAspect;
- drawX = (this.config.width - drawWidth) / 2;
- drawY = 0;
- } else {
- drawWidth = this.config.width;
- drawHeight = drawWidth / imgAspect;
- drawX = 0;
- drawY = (this.config.height - drawHeight) / 2;
- }
+ let drawWidth: number;
+ let drawHeight: number;
+ let drawX: number;
+ let drawY: number;
- bgCtx.drawImage(img, drawX, drawY, drawWidth, drawHeight);
- } else if (wallpaper.startsWith("#")) {
- bgCtx.fillStyle = wallpaper;
- bgCtx.fillRect(0, 0, this.config.width, this.config.height);
- } else if (
- wallpaper.startsWith("linear-gradient") ||
- wallpaper.startsWith("radial-gradient")
- ) {
- const parsedGradient = parseCssGradient(wallpaper);
- if (parsedGradient) {
- const gradient =
- parsedGradient.type === "linear"
- ? (() => {
- const points = getLinearGradientPoints(
- resolveLinearGradientAngle(parsedGradient.descriptor),
- this.config.width,
- this.config.height,
- );
-
- return bgCtx.createLinearGradient(points.x0, points.y0, points.x1, points.y1);
- })()
- : (() => {
- const shape = getRadialGradientShape(
- parsedGradient.descriptor,
- this.config.width,
- this.config.height,
- );
-
- return bgCtx.createRadialGradient(
- shape.cx,
- shape.cy,
- 0,
- shape.cx,
- shape.cy,
- shape.radius,
- );
- })();
-
- parsedGradient.stops.forEach((stop) => {
- gradient.addColorStop(stop.offset, stop.color);
- });
-
- bgCtx.fillStyle = gradient;
- bgCtx.fillRect(0, 0, this.config.width, this.config.height);
- } else {
- console.warn("[FrameRenderer] Could not parse gradient, using black fallback");
- bgCtx.fillStyle = "#000000";
- bgCtx.fillRect(0, 0, this.config.width, this.config.height);
- }
+ if (imgAspect > canvasAspect) {
+ drawHeight = this.config.height;
+ drawWidth = drawHeight * imgAspect;
+ drawX = (this.config.width - drawWidth) / 2;
+ drawY = 0;
} else {
- bgCtx.fillStyle = wallpaper;
- bgCtx.fillRect(0, 0, this.config.width, this.config.height);
+ drawWidth = this.config.width;
+ drawHeight = drawWidth / imgAspect;
+ drawX = 0;
+ drawY = (this.config.height - drawHeight) / 2;
}
- } catch (error) {
- console.error("[FrameRenderer] Error setting up background, using fallback:", error);
- bgCtx.fillStyle = "#000000";
- bgCtx.fillRect(0, 0, this.config.width, this.config.height);
+
+ bgCtx.drawImage(img, drawX, drawY, drawWidth, drawHeight);
}
- // Store the background canvas for compositing
this.backgroundSprite = bgCanvas;
}
diff --git a/src/lib/exporter/gifExporter.browser.test.ts b/src/lib/exporter/gifExporter.browser.test.ts
index db9b14467..5a6946890 100644
--- a/src/lib/exporter/gifExporter.browser.test.ts
+++ b/src/lib/exporter/gifExporter.browser.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import sampleVideoUrl from "../../../tests/fixtures/sample.webm?url";
+import { BackgroundLoadError } from "../wallpaper";
import { GifExporter } from "./gifExporter";
import type { ExportProgress } from "./types";
@@ -40,4 +41,44 @@ describe("GifExporter (real browser)", () => {
expect(finalizing.length).toBeGreaterThan(0);
expect(finalizing.at(-1)!.percentage).toBe(100);
});
+
+ it("exports successfully with an image wallpaper (served by Vite dev server)", async () => {
+ const exporter = new GifExporter({
+ videoUrl: sampleVideoUrl,
+ width: 320,
+ height: 180,
+ frameRate: 15,
+ loop: true,
+ sizePreset: "medium",
+ wallpaper: "/wallpapers/wallpaper1.jpg",
+ zoomRegions: [],
+ showShadow: false,
+ shadowIntensity: 0,
+ showBlur: false,
+ cropRegion: { x: 0, y: 0, width: 1, height: 1 },
+ });
+
+ const result = await exporter.export();
+ expect(result.success, result.error).toBe(true);
+ expect(result.blob!.size).toBeGreaterThan(1024);
+ });
+
+ it("throws BackgroundLoadError when wallpaper fails to load (no silent black fallback)", async () => {
+ const exporter = new GifExporter({
+ videoUrl: sampleVideoUrl,
+ width: 320,
+ height: 180,
+ frameRate: 15,
+ loop: true,
+ sizePreset: "medium",
+ wallpaper: "/wallpapers/does-not-exist.jpg",
+ zoomRegions: [],
+ showShadow: false,
+ shadowIntensity: 0,
+ showBlur: false,
+ cropRegion: { x: 0, y: 0, width: 1, height: 1 },
+ });
+
+ await expect(exporter.export()).rejects.toBeInstanceOf(BackgroundLoadError);
+ });
});
diff --git a/src/lib/exporter/gifExporter.ts b/src/lib/exporter/gifExporter.ts
index 46ac6a074..f073d6be5 100644
--- a/src/lib/exporter/gifExporter.ts
+++ b/src/lib/exporter/gifExporter.ts
@@ -8,6 +8,7 @@ import type {
WebcamSizePreset,
ZoomRegion,
} from "@/components/video-editor/types";
+import { BackgroundLoadError } from "@/lib/wallpaper";
import { getPlatform } from "@/utils/platformUtils";
import { AsyncVideoFrameQueue } from "./asyncVideoFrameQueue";
import { FrameRenderer } from "./frameRenderer";
@@ -326,6 +327,9 @@ export class GifExporter {
return { success: true, blob };
} catch (error) {
+ if (error instanceof BackgroundLoadError) {
+ throw error;
+ }
console.error("GIF Export error:", error);
return {
success: false,
diff --git a/src/lib/exporter/videoExporter.browser.test.ts b/src/lib/exporter/videoExporter.browser.test.ts
index ec2b0f65e..ae8c7bc3f 100644
--- a/src/lib/exporter/videoExporter.browser.test.ts
+++ b/src/lib/exporter/videoExporter.browser.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import sampleVideoUrl from "../../../tests/fixtures/sample.webm?url";
+import { BackgroundLoadError } from "../wallpaper";
import type { ExportProgress } from "./types";
import { VideoExporter } from "./videoExporter";
@@ -40,4 +41,42 @@ describe("VideoExporter (real browser)", () => {
expect(finalizing.length).toBeGreaterThan(0);
expect(finalizing.at(-1)!.percentage).toBe(100);
});
+
+ it("exports successfully with an image wallpaper (served by Vite dev server)", async () => {
+ const exporter = new VideoExporter({
+ videoUrl: sampleVideoUrl,
+ width: 320,
+ height: 180,
+ frameRate: 15,
+ bitrate: 1_000_000,
+ wallpaper: "/wallpapers/wallpaper1.jpg",
+ zoomRegions: [],
+ showShadow: false,
+ shadowIntensity: 0,
+ showBlur: false,
+ cropRegion: { x: 0, y: 0, width: 1, height: 1 },
+ });
+
+ const result = await exporter.export();
+ expect(result.success, result.error).toBe(true);
+ expect(result.blob!.size).toBeGreaterThan(1024);
+ });
+
+ it("throws BackgroundLoadError when wallpaper fails to load (no silent black fallback)", async () => {
+ const exporter = new VideoExporter({
+ videoUrl: sampleVideoUrl,
+ width: 320,
+ height: 180,
+ frameRate: 15,
+ bitrate: 1_000_000,
+ wallpaper: "/wallpapers/does-not-exist.jpg",
+ zoomRegions: [],
+ showShadow: false,
+ shadowIntensity: 0,
+ showBlur: false,
+ cropRegion: { x: 0, y: 0, width: 1, height: 1 },
+ });
+
+ await expect(exporter.export()).rejects.toBeInstanceOf(BackgroundLoadError);
+ });
});
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index 44c1b88e7..0ea1ec6ac 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -7,6 +7,7 @@ import type {
WebcamSizePreset,
ZoomRegion,
} from "@/components/video-editor/types";
+import { BackgroundLoadError } from "@/lib/wallpaper";
import { getPlatform } from "@/utils/platformUtils";
import { AsyncVideoFrameQueue } from "./asyncVideoFrameQueue";
import { AudioProcessor } from "./audioEncoder";
@@ -82,6 +83,11 @@ export class VideoExporter {
return { success: false, error: "Export cancelled" };
}
+ if (normalizedError instanceof BackgroundLoadError) {
+ this.cleanup();
+ throw normalizedError;
+ }
+
if (encoderPreferences.length > 1) {
console.warn(
`[VideoExporter] ${encoderPreference} export attempt failed:`,
diff --git a/src/lib/wallpaper.test.ts b/src/lib/wallpaper.test.ts
new file mode 100644
index 000000000..dbb5e3c1e
--- /dev/null
+++ b/src/lib/wallpaper.test.ts
@@ -0,0 +1,167 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ BackgroundLoadError,
+ classifyWallpaper,
+ DEFAULT_WALLPAPER,
+ resolveImageWallpaperUrl,
+} from "./wallpaper";
+
+describe("classifyWallpaper", () => {
+ it("classifies hex color", () => {
+ expect(classifyWallpaper("#1a1a2e")).toEqual({ kind: "color", value: "#1a1a2e" });
+ });
+
+ it("classifies linear gradient", () => {
+ const value = "linear-gradient(90deg, red, blue)";
+ expect(classifyWallpaper(value)).toEqual({ kind: "gradient", value });
+ });
+
+ it("classifies radial gradient", () => {
+ const value = "radial-gradient(circle, red, blue)";
+ expect(classifyWallpaper(value)).toEqual({ kind: "gradient", value });
+ });
+
+ it("classifies leading-slash image path", () => {
+ expect(classifyWallpaper("/wallpapers/wallpaper1.jpg")).toEqual({
+ kind: "image",
+ path: "/wallpapers/wallpaper1.jpg",
+ });
+ });
+
+ it("classifies http URL as image", () => {
+ expect(classifyWallpaper("https://example.com/bg.jpg")).toEqual({
+ kind: "image",
+ path: "https://example.com/bg.jpg",
+ });
+ });
+
+ it("classifies file:// URL as image", () => {
+ expect(classifyWallpaper("file:///tmp/bg.jpg")).toEqual({
+ kind: "image",
+ path: "file:///tmp/bg.jpg",
+ });
+ });
+
+ it("classifies data URI as image", () => {
+ expect(classifyWallpaper("data:image/png;base64,AAA")).toEqual({
+ kind: "image",
+ path: "data:image/png;base64,AAA",
+ });
+ });
+
+ it("DEFAULT_WALLPAPER classifies as image", () => {
+ expect(classifyWallpaper(DEFAULT_WALLPAPER)).toEqual({
+ kind: "image",
+ path: DEFAULT_WALLPAPER,
+ });
+ });
+});
+
+describe("resolveImageWallpaperUrl", () => {
+ beforeEach(() => {
+ vi.stubGlobal("window", {
+ ...globalThis.window,
+ location: { protocol: "http:" },
+ electronAPI: undefined,
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("passes through http URL unchanged", async () => {
+ expect(await resolveImageWallpaperUrl("http://example.com/bg.jpg")).toBe(
+ "http://example.com/bg.jpg",
+ );
+ });
+
+ it("passes through https URL unchanged", async () => {
+ expect(await resolveImageWallpaperUrl("https://example.com/bg.jpg")).toBe(
+ "https://example.com/bg.jpg",
+ );
+ });
+
+ it("passes through file:// URL unchanged", async () => {
+ expect(await resolveImageWallpaperUrl("file:///tmp/bg.jpg")).toBe("file:///tmp/bg.jpg");
+ });
+
+ it("passes through data URI unchanged", async () => {
+ const uri = "data:image/png;base64,AAAA";
+ expect(await resolveImageWallpaperUrl(uri)).toBe(uri);
+ });
+
+ it("resolves leading-slash path via http dev server fallback", async () => {
+ expect(await resolveImageWallpaperUrl("/wallpapers/wallpaper1.jpg")).toBe(
+ "/wallpapers/wallpaper1.jpg",
+ );
+ });
+
+ it("resolves bare relative path via http dev server fallback", async () => {
+ expect(await resolveImageWallpaperUrl("wallpapers/wallpaper1.jpg")).toBe(
+ "/wallpapers/wallpaper1.jpg",
+ );
+ });
+
+ it("encodes path segments with special characters", async () => {
+ expect(await resolveImageWallpaperUrl("/wallpapers/my image.jpg")).toBe(
+ "/wallpapers/my%20image.jpg",
+ );
+ });
+
+ it("resolves via electronAPI when not http protocol", async () => {
+ vi.stubGlobal("window", {
+ ...globalThis.window,
+ location: { protocol: "file:" },
+ electronAPI: {
+ getAssetBasePath: vi.fn().mockResolvedValue("file:///opt/app/public/"),
+ },
+ });
+ expect(await resolveImageWallpaperUrl("/wallpapers/wallpaper1.jpg")).toBe(
+ "file:///opt/app/public/wallpapers/wallpaper1.jpg",
+ );
+ });
+
+ it("electronAPI branch appends trailing slash to base if missing", async () => {
+ vi.stubGlobal("window", {
+ ...globalThis.window,
+ location: { protocol: "file:" },
+ electronAPI: {
+ getAssetBasePath: vi.fn().mockResolvedValue("file:///opt/app/public"),
+ },
+ });
+ expect(await resolveImageWallpaperUrl("/wallpapers/wallpaper1.jpg")).toBe(
+ "file:///opt/app/public/wallpapers/wallpaper1.jpg",
+ );
+ });
+
+ it("falls back to leading-slash relative when electronAPI returns null", async () => {
+ vi.stubGlobal("window", {
+ ...globalThis.window,
+ location: { protocol: "file:" },
+ electronAPI: {
+ getAssetBasePath: vi.fn().mockResolvedValue(null),
+ },
+ });
+ expect(await resolveImageWallpaperUrl("/wallpapers/wallpaper1.jpg")).toBe(
+ "/wallpapers/wallpaper1.jpg",
+ );
+ });
+});
+
+describe("BackgroundLoadError", () => {
+ it("carries the failing URL and is instanceof Error", () => {
+ const err = new BackgroundLoadError("file:///missing.jpg");
+ expect(err).toBeInstanceOf(Error);
+ expect(err).toBeInstanceOf(BackgroundLoadError);
+ expect(err.url).toBe("file:///missing.jpg");
+ expect(err.name).toBe("BackgroundLoadError");
+ expect(err.message).toContain("file:///missing.jpg");
+ });
+
+ it("preserves cause when provided", () => {
+ const cause = new Error("inner");
+ const err = new BackgroundLoadError("file:///missing.jpg", cause);
+ expect(err.cause).toBe(cause);
+ });
+});
diff --git a/src/lib/wallpaper.ts b/src/lib/wallpaper.ts
new file mode 100644
index 000000000..f949177f6
--- /dev/null
+++ b/src/lib/wallpaper.ts
@@ -0,0 +1,43 @@
+import { getAssetPath } from "@/lib/assetPath";
+
+export const DEFAULT_WALLPAPER = "/wallpapers/wallpaper1.jpg";
+
+export type WallpaperClassification =
+ | { kind: "color"; value: string }
+ | { kind: "gradient"; value: string }
+ | { kind: "image"; path: string };
+
+export function classifyWallpaper(value: string): WallpaperClassification {
+ if (value.startsWith("#")) {
+ return { kind: "color", value };
+ }
+ if (value.startsWith("linear-gradient") || value.startsWith("radial-gradient")) {
+ return { kind: "gradient", value };
+ }
+ return { kind: "image", path: value };
+}
+
+export async function resolveImageWallpaperUrl(imagePath: string): Promise<string> {
+ if (
+ imagePath.startsWith("http://") ||
+ imagePath.startsWith("https://") ||
+ imagePath.startsWith("file://") ||
+ imagePath.startsWith("data:")
+ ) {
+ return imagePath;
+ }
+ const relative = imagePath.replace(/^\/+/, "");
+ return getAssetPath(relative);
+}
+
+export class BackgroundLoadError extends Error {
+ readonly url: string;
+ readonly cause?: unknown;
+
+ constructor(url: string, cause?: unknown) {
+ super(`Failed to load background image: ${url}`);
+ this.name = "BackgroundLoadError";
+ this.url = url;
+ this.cause = cause;
+ }
+}