Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

feat: add device detection and export time estimates

Augustus Otuf2680bc65b8d
diff --git a/apps/web/src/components/editor/ExportDialog.tsx b/apps/web/src/components/editor/ExportDialog.tsx
index dc8c7655..637cf8a0 100644
--- a/apps/web/src/components/editor/ExportDialog.tsx
+++ b/apps/web/src/components/editor/ExportDialog.tsx
@@ -14,12 +14,29 @@ import {
Video,
Share2,
Sparkles,
+ Cpu,
+ Gauge,
+ Zap,
+ CheckCircle,
+ Info,
} from "lucide-react";
import {
exportPresetsManager,
type PlatformExportPreset,
} from "../../services/export-presets";
import type { VideoExportSettings, UpscaleQuality } from "@openreel/core";
+import {
+ getDeviceProfile,
+ estimateExportTime,
+ runBenchmark,
+ getCodecRecommendations,
+ formatDeviceSummary,
+ shouldRecommendBenchmark,
+ type DeviceProfile,
+ type BenchmarkProgress,
+ type TimeEstimate,
+ type CodecRecommendation,
+} from "@openreel/core";
interface ExportDialogProps {
isOpen: boolean;
@@ -125,14 +142,74 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
},
});
+ const [deviceProfile, setDeviceProfile] = useState<DeviceProfile | null>(null);
+ const [timeEstimate, setTimeEstimate] = useState<TimeEstimate | null>(null);
+ const [codecRecommendations, setCodecRecommendations] = useState<CodecRecommendation[]>([]);
+ const [isBenchmarking, setIsBenchmarking] = useState(false);
+ const [benchmarkProgress, setBenchmarkProgress] = useState<BenchmarkProgress | null>(null);
+ const [showDeviceInfo, setShowDeviceInfo] = useState(false);
+
useEffect(() => {
if (isOpen) {
setPresets(exportPresetsManager.getAllPresets());
setPlatforms(exportPresetsManager.getPlatforms());
setSelectedPlatform("recommended");
setSelectedPreset(null);
+
+ getDeviceProfile().then((profile) => {
+ setDeviceProfile(profile);
+ setCodecRecommendations(
+ getCodecRecommendations(profile, { width: projectWidth, height: projectHeight })
+ );
+ });
+ }
+ }, [isOpen, projectWidth, projectHeight]);
+
+ useEffect(() => {
+ if (!deviceProfile || duration <= 0) {
+ setTimeEstimate(null);
+ return;
+ }
+
+ const settings =
+ activeTab === "presets" && selectedPreset
+ ? (selectedPreset.settings as VideoExportSettings)
+ : customSettings;
+
+ const estimate = estimateExportTime(deviceProfile, {
+ width: settings.width,
+ height: settings.height,
+ frameRate: settings.frameRate,
+ duration,
+ codec: settings.codec as "h264" | "h265" | "vp9" | "av1",
+ });
+
+ setTimeEstimate(estimate);
+ }, [deviceProfile, duration, activeTab, selectedPreset, customSettings]);
+
+ const handleRunBenchmark = useCallback(async () => {
+ if (isBenchmarking) return;
+
+ setIsBenchmarking(true);
+ setBenchmarkProgress(null);
+
+ try {
+ await runBenchmark((progress) => {
+ setBenchmarkProgress(progress);
+ });
+
+ const updatedProfile = await getDeviceProfile(true);
+ setDeviceProfile(updatedProfile);
+ setCodecRecommendations(
+ getCodecRecommendations(updatedProfile, { width: projectWidth, height: projectHeight })
+ );
+ } catch (error) {
+ console.error("Benchmark failed:", error);
+ } finally {
+ setIsBenchmarking(false);
+ setBenchmarkProgress(null);
}
- }, [isOpen]);
+ }, [isBenchmarking, projectWidth, projectHeight]);
const recommendedForVideo = getRecommendedPresetsForAspectRatio(
presets,
@@ -631,6 +708,101 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
)}
</div>
+ {deviceProfile && (
+ <div className="px-4 py-3 border-t border-border bg-background-tertiary/50">
+ <div className="flex items-center justify-between">
+ <button
+ onClick={() => setShowDeviceInfo(!showDeviceInfo)}
+ className="flex items-center gap-2 text-xs text-text-secondary hover:text-text-primary transition-colors"
+ >
+ <Cpu size={12} />
+ <span>{formatDeviceSummary(deviceProfile)}</span>
+ <Info size={10} className="text-text-muted" />
+ </button>
+
+ {timeEstimate && (
+ <div className="flex items-center gap-3">
+ <div className="flex items-center gap-1.5 text-xs">
+ {timeEstimate.confidence === "measured" ? (
+ <CheckCircle size={12} className="text-green-500" />
+ ) : (
+ <Gauge size={12} className="text-yellow-500" />
+ )}
+ <span className="text-text-secondary">Est. time:</span>
+ <span className="font-medium text-text-primary">
+ {timeEstimate.formatted}
+ </span>
+ </div>
+
+ {shouldRecommendBenchmark(deviceProfile) && !isBenchmarking && (
+ <button
+ onClick={handleRunBenchmark}
+ className="flex items-center gap-1 px-2 py-1 text-[10px] text-primary bg-primary/10 rounded hover:bg-primary/20 transition-colors"
+ >
+ <Zap size={10} />
+ Get accurate estimate
+ </button>
+ )}
+
+ {isBenchmarking && benchmarkProgress && (
+ <div className="flex items-center gap-2 text-[10px] text-text-muted">
+ <div className="w-16 h-1 bg-background-tertiary rounded-full overflow-hidden">
+ <div
+ className="h-full bg-primary transition-all"
+ style={{ width: `${benchmarkProgress.progress * 100}%` }}
+ />
+ </div>
+ <span>Testing...</span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {showDeviceInfo && (
+ <div className="mt-3 pt-3 border-t border-border/50 grid grid-cols-4 gap-4 text-[10px]">
+ <div>
+ <span className="text-text-muted">CPU</span>
+ <p className="text-text-primary font-medium">
+ {deviceProfile.cpu.cores} cores ({deviceProfile.cpu.tier})
+ </p>
+ </div>
+ <div>
+ <span className="text-text-muted">Memory</span>
+ <p className="text-text-primary font-medium">
+ {deviceProfile.memory.gb}GB ({deviceProfile.memory.tier})
+ </p>
+ </div>
+ <div>
+ <span className="text-text-muted">GPU</span>
+ <p className="text-text-primary font-medium truncate" title={deviceProfile.gpu.renderer}>
+ {deviceProfile.gpu.hasHardwareEncoding ? "HW Encode ✓" : "Software only"}
+ </p>
+ </div>
+ <div>
+ <span className="text-text-muted">Codecs</span>
+ <div className="flex gap-1 flex-wrap">
+ {codecRecommendations.slice(0, 3).map((rec) => (
+ <span
+ key={rec.codec}
+ className={`px-1 py-0.5 rounded text-[9px] ${
+ rec.speedRating === "fast"
+ ? "bg-green-500/20 text-green-400"
+ : rec.speedRating === "medium"
+ ? "bg-yellow-500/20 text-yellow-400"
+ : "bg-red-500/20 text-red-400"
+ }`}
+ >
+ {rec.codec.toUpperCase()}
+ </span>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
<div className="flex items-center justify-between p-4 border-t border-border bg-background-tertiary">
<div className="flex items-center gap-4 text-xs text-text-muted">
{duration > 0 && (
@@ -649,6 +821,12 @@ export const ExportDialog: React.FC<ExportDialogProps> = ({
duration,
)}
</div>
+ {timeEstimate && deviceProfile?.encoding[customSettings.codec as keyof typeof deviceProfile.encoding]?.hardware && (
+ <div className="flex items-center gap-1 text-green-500">
+ <Zap size={12} />
+ Hardware accelerated
+ </div>
+ )}
</>
)}
</div>
diff --git a/packages/core/src/device/device-capabilities.ts b/packages/core/src/device/device-capabilities.ts
new file mode 100644
index 00000000..5fd1fba7
--- /dev/null
+++ b/packages/core/src/device/device-capabilities.ts
@@ -0,0 +1,446 @@
+export type DeviceTier = "low" | "mid" | "high";
+
+export interface CpuInfo {
+ cores: number;
+ tier: DeviceTier;
+}
+
+export interface MemoryInfo {
+ gb: number;
+ tier: DeviceTier;
+}
+
+export interface GpuInfo {
+ vendor: string;
+ renderer: string;
+ tier: DeviceTier;
+ hasHardwareEncoding: boolean;
+}
+
+export interface DeviceCodecSupport {
+ hardware: boolean;
+ supported: boolean;
+ maxResolution?: { width: number; height: number };
+}
+
+export interface EncodingSupport {
+ h264: DeviceCodecSupport;
+ h265: DeviceCodecSupport;
+ vp9: DeviceCodecSupport;
+ av1: DeviceCodecSupport;
+}
+
+export interface BenchmarkResult {
+ framesPerSecond: number;
+ codec: string;
+ resolution: { width: number; height: number };
+ testedAt: number;
+}
+
+export interface DeviceProfile {
+ cpu: CpuInfo;
+ memory: MemoryInfo;
+ gpu: GpuInfo;
+ encoding: EncodingSupport;
+ benchmark?: BenchmarkResult;
+ platform: {
+ os: string;
+ browser: string;
+ isMobile: boolean;
+ };
+ overallTier: DeviceTier;
+}
+
+export interface CodecRecommendation {
+ codec: "h264" | "h265" | "vp9" | "av1";
+ label: string;
+ recommended: boolean;
+ reason: string;
+ speedRating: "fast" | "medium" | "slow" | "very-slow";
+ qualityRating: "good" | "better" | "best";
+}
+
+const STORAGE_KEY = "openreel_device_profile";
+
+function getCpuTier(cores: number): DeviceTier {
+ if (cores >= 8) return "high";
+ if (cores >= 4) return "mid";
+ return "low";
+}
+
+function getMemoryTier(gb: number): DeviceTier {
+ if (gb >= 8) return "high";
+ if (gb >= 4) return "mid";
+ return "low";
+}
+
+function getGpuTier(renderer: string): DeviceTier {
+ const r = renderer.toLowerCase();
+
+ const highEndPatterns = [
+ "nvidia rtx",
+ "nvidia geforce rtx",
+ "radeon rx 6",
+ "radeon rx 7",
+ "apple m1 pro",
+ "apple m1 max",
+ "apple m2",
+ "apple m3",
+ "intel arc",
+ ];
+
+ const midEndPatterns = [
+ "nvidia gtx 1",
+ "nvidia geforce gtx",
+ "radeon rx 5",
+ "apple m1",
+ "intel iris",
+ "intel uhd",
+ ];
+
+ if (highEndPatterns.some((p) => r.includes(p))) return "high";
+ if (midEndPatterns.some((p) => r.includes(p))) return "mid";
+ return "low";
+}
+
+function detectPlatform(): DeviceProfile["platform"] {
+ const ua = navigator.userAgent;
+
+ let os = "Unknown";
+ if (ua.includes("Windows")) os = "Windows";
+ else if (ua.includes("Mac")) os = "macOS";
+ else if (ua.includes("Linux")) os = "Linux";
+ else if (ua.includes("Android")) os = "Android";
+ else if (ua.includes("iPhone") || ua.includes("iPad")) os = "iOS";
+ else if (ua.includes("CrOS")) os = "ChromeOS";
+
+ let browser = "Unknown";
+ if (ua.includes("Chrome") && !ua.includes("Edg")) browser = "Chrome";
+ else if (ua.includes("Firefox")) browser = "Firefox";
+ else if (ua.includes("Safari") && !ua.includes("Chrome")) browser = "Safari";
+ else if (ua.includes("Edg")) browser = "Edge";
+
+ const isMobile =
+ /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
+
+ return { os, browser, isMobile };
+}
+
+function detectGpu(): Omit<GpuInfo, "hasHardwareEncoding"> {
+ try {
+ const canvas = document.createElement("canvas");
+ const gl =
+ canvas.getContext("webgl2") ||
+ canvas.getContext("webgl") ||
+ canvas.getContext("experimental-webgl");
+
+ if (!gl) {
+ return { vendor: "Unknown", renderer: "Unknown", tier: "low" };
+ }
+
+ const debugInfo = (gl as WebGLRenderingContext).getExtension(
+ "WEBGL_debug_renderer_info"
+ );
+
+ if (debugInfo) {
+ const vendor = (gl as WebGLRenderingContext).getParameter(
+ debugInfo.UNMASKED_VENDOR_WEBGL
+ );
+ const renderer = (gl as WebGLRenderingContext).getParameter(
+ debugInfo.UNMASKED_RENDERER_WEBGL
+ );
+
+ return {
+ vendor: vendor || "Unknown",
+ renderer: renderer || "Unknown",
+ tier: getGpuTier(renderer || ""),
+ };
+ }
+
+ return { vendor: "Unknown", renderer: "Unknown", tier: "mid" };
+ } catch {
+ return { vendor: "Unknown", renderer: "Unknown", tier: "low" };
+ }
+}
+
+async function checkCodecSupport(
+ codecString: string,
+ width: number,
+ height: number
+): Promise<DeviceCodecSupport> {
+ if (typeof VideoEncoder === "undefined") {
+ return { hardware: false, supported: false };
+ }
+
+ try {
+ const baseConfig = {
+ codec: codecString,
+ width,
+ height,
+ bitrate: 5_000_000,
+ framerate: 30,
+ };
+
+ const hwResult = await VideoEncoder.isConfigSupported({
+ ...baseConfig,
+ hardwareAcceleration: "prefer-hardware",
+ });
+
+ const swResult = await VideoEncoder.isConfigSupported({
+ ...baseConfig,
+ hardwareAcceleration: "prefer-software",
+ });
+
+ const isHardware =
+ hwResult.supported === true &&
+ hwResult.config?.hardwareAcceleration === "prefer-hardware";
+
+ return {
+ hardware: isHardware,
+ supported: hwResult.supported === true || swResult.supported === true,
+ maxResolution: { width, height },
+ };
+ } catch {
+ return { hardware: false, supported: false };
+ }
+}
+
+async function detectEncodingSupport(): Promise<EncodingSupport> {
+ const codecs = {
+ h264: "avc1.42001E",
+ h265: "hvc1.1.6.L93.B0",
+ vp9: "vp09.00.10.08",
+ av1: "av01.0.04M.08",
+ };
+
+ const [h264, h265, vp9, av1] = await Promise.all([
+ checkCodecSupport(codecs.h264, 1920, 1080),
+ checkCodecSupport(codecs.h265, 1920, 1080),
+ checkCodecSupport(codecs.vp9, 1920, 1080),
+ checkCodecSupport(codecs.av1, 1920, 1080),
+ ]);
+
+ return { h264, h265, vp9, av1 };
+}
+
+function calculateOverallTier(
+ cpu: CpuInfo,
+ memory: MemoryInfo,
+ gpu: GpuInfo
+): DeviceTier {
+ const tierValues: Record<DeviceTier, number> = { low: 1, mid: 2, high: 3 };
+ const avg =
+ (tierValues[cpu.tier] +
+ tierValues[memory.tier] +
+ tierValues[gpu.tier] * 1.5) /
+ 3.5;
+
+ if (avg >= 2.5) return "high";
+ if (avg >= 1.5) return "mid";
+ return "low";
+}
+
+export async function detectDeviceCapabilities(): Promise<DeviceProfile> {
+ const cores = navigator.hardwareConcurrency || 4;
+ const memory = (navigator as unknown as { deviceMemory?: number })
+ .deviceMemory || 4;
+
+ const cpu: CpuInfo = { cores, tier: getCpuTier(cores) };
+ const memoryInfo: MemoryInfo = { gb: memory, tier: getMemoryTier(memory) };
+ const gpuBase = detectGpu();
+ const encoding = await detectEncodingSupport();
+ const platform = detectPlatform();
+
+ const hasHardwareEncoding = Object.values(encoding).some((e) => e.hardware);
+ const gpu: GpuInfo = { ...gpuBase, hasHardwareEncoding };
+
+ const overallTier = calculateOverallTier(cpu, memoryInfo, gpu);
+
+ const cached = loadCachedBenchmark();
+
+ return {
+ cpu,
+ memory: memoryInfo,
+ gpu,
+ encoding,
+ platform,
+ overallTier,
+ benchmark: cached,
+ };
+}
+
+export function getCodecRecommendations(
+ profile: DeviceProfile,
+ resolution: { width: number; height: number }
+): CodecRecommendation[] {
+ const is4K = resolution.width * resolution.height > 1920 * 1080;
+ const recommendations: CodecRecommendation[] = [];
+
+ if (profile.encoding.h264.supported) {
+ const hasHw = profile.encoding.h264.hardware;
+ recommendations.push({
+ codec: "h264",
+ label: "H.264 (MP4)",
+ recommended: true,
+ reason: hasHw ? "Hardware accelerated" : "Fast software encoding",
+ speedRating: hasHw ? "fast" : "medium",
+ qualityRating: "good",
+ });
+ }
+
+ if (profile.encoding.h265.supported) {
+ const hasHw = profile.encoding.h265.hardware;
+ recommendations.push({
+ codec: "h265",
+ label: "H.265/HEVC (MP4)",
+ recommended: hasHw && !is4K,
+ reason: hasHw
+ ? "Hardware accelerated, better compression"
+ : "Better compression, slower encoding",
+ speedRating: hasHw ? "medium" : "slow",
+ qualityRating: "better",
+ });
+ }
+
+ if (profile.encoding.vp9.supported) {
+ recommendations.push({
+ codec: "vp9",
+ label: "VP9 (WebM)",
+ recommended: false,
+ reason: "Good for web, software encoding only",
+ speedRating: "slow",
+ qualityRating: "better",
+ });
+ }
+
+ if (profile.encoding.av1.supported) {
+ const hasHw = profile.encoding.av1.hardware;
+ recommendations.push({
+ codec: "av1",
+ label: "AV1 (MP4/WebM)",
+ recommended: hasHw && profile.overallTier === "high",
+ reason: hasHw
+ ? "Best compression, hardware accelerated"
+ : "Best compression, very slow encoding",
+ speedRating: hasHw ? "medium" : "very-slow",
+ qualityRating: "best",
+ });
+ }
+
+ return recommendations.sort((a, b) => {
+ if (a.recommended && !b.recommended) return -1;
+ if (!a.recommended && b.recommended) return 1;
+ return 0;
+ });
+}
+
+export function getResolutionRecommendations(
+ profile: DeviceProfile
+): Array<{ width: number; height: number; label: string; recommended: boolean; warning?: string }> {
+ const recommendations = [];
+
+ recommendations.push({
+ width: 1280,
+ height: 720,
+ label: "720p HD",
+ recommended: profile.overallTier === "low",
+ });
+
+ recommendations.push({
+ width: 1920,
+ height: 1080,
+ label: "1080p Full HD",
+ recommended: profile.overallTier === "mid" || profile.overallTier === "high",
+ });
+
+ if (profile.memory.gb >= 4) {
+ recommendations.push({
+ width: 2560,
+ height: 1440,
+ label: "1440p QHD",
+ recommended: profile.overallTier === "high",
+ warning:
+ profile.overallTier !== "high" ? "May be slow on this device" : undefined,
+ });
+ }
+
+ if (profile.memory.gb >= 8 && profile.overallTier !== "low") {
+ recommendations.push({
+ width: 3840,
+ height: 2160,
+ label: "4K UHD",
+ recommended: false,
+ warning:
+ profile.overallTier !== "high"
+ ? "Requires significant processing time"
+ : "High memory usage",
+ });
+ }
+
+ return recommendations;
+}
+
+function loadCachedBenchmark(): BenchmarkResult | undefined {
+ try {
+ const cached = localStorage.getItem(STORAGE_KEY);
+ if (cached) {
+ const data = JSON.parse(cached);
+ const oneWeek = 7 * 24 * 60 * 60 * 1000;
+ if (data.benchmark && Date.now() - data.benchmark.testedAt < oneWeek) {
+ return data.benchmark;
+ }
+ }
+ } catch {
+ // Ignore cache errors
+ }
+ return undefined;
+}
+
+export function saveBenchmarkResult(result: BenchmarkResult): void {
+ try {
+ const existing = localStorage.getItem(STORAGE_KEY);
+ const data = existing ? JSON.parse(existing) : {};
+ data.benchmark = result;
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
+ } catch {
+ // Ignore storage errors
+ }
+}
+
+export function clearBenchmarkCache(): void {
+ try {
+ localStorage.removeItem(STORAGE_KEY);
+ } catch {
+ // Ignore
+ }
+}
+
+let cachedProfile: DeviceProfile | null = null;
+
+export async function getDeviceProfile(
+ forceRefresh = false
+): Promise<DeviceProfile> {
+ if (!forceRefresh && cachedProfile) {
+ return cachedProfile;
+ }
+
+ cachedProfile = await detectDeviceCapabilities();
+ return cachedProfile;
+}
+
+export function formatDeviceSummary(profile: DeviceProfile): string {
+ const parts = [];
+
+ if (profile.gpu.renderer !== "Unknown") {
+ const gpuName = profile.gpu.renderer
+ .replace(/ANGLE \(|, .*\)/g, "")
+ .replace(/Direct3D11 vs_\d+_\d+ ps_\d+_\d+/g, "")
+ .trim();
+ parts.push(gpuName);
+ }
+
+ parts.push(`${profile.cpu.cores} cores`);
+ parts.push(`${profile.memory.gb}GB RAM`);
+
+ return parts.join(" · ");
+}
diff --git a/packages/core/src/device/export-estimator.ts b/packages/core/src/device/export-estimator.ts
new file mode 100644
index 00000000..ac45e02d
--- /dev/null
+++ b/packages/core/src/device/export-estimator.ts
@@ -0,0 +1,363 @@
+import type { DeviceProfile, BenchmarkResult } from "./device-capabilities";
+import { saveBenchmarkResult } from "./device-capabilities";
+
+export interface ExportEstimateSettings {
+ width: number;
+ height: number;
+ frameRate: number;
+ duration: number;
+ codec: "h264" | "h265" | "vp9" | "av1";
+ hasEffects?: boolean;
+ hasTransitions?: boolean;
+ trackCount?: number;
+}
+
+export interface TimeEstimate {
+ seconds: number;
+ formatted: string;
+ confidence: "measured" | "estimated" | "rough";
+ breakdown?: {
+ rendering: number;
+ encoding: number;
+ muxing: number;
+ };
+}
+
+export interface BenchmarkProgress {
+ phase: "preparing" | "rendering" | "encoding" | "complete";
+ progress: number;
+ framesProcessed: number;
+ totalFrames: number;
+}
+
+const BASE_FPS_ESTIMATES: Record<string, Record<string, number>> = {
+ h264: {
+ hardware_high: 120,
+ hardware_mid: 90,
+ hardware_low: 60,
+ software_high: 45,
+ software_mid: 30,
+ software_low: 15,
+ },
+ h265: {
+ hardware_high: 60,
+ hardware_mid: 45,
+ hardware_low: 30,
+ software_high: 15,
+ software_mid: 8,
+ software_low: 4,
+ },
+ vp9: {
+ hardware_high: 30,
+ hardware_mid: 20,
+ hardware_low: 15,
+ software_high: 20,
+ software_mid: 12,
+ software_low: 6,
+ },
+ av1: {
+ hardware_high: 45,
+ hardware_mid: 30,
+ hardware_low: 20,
+ software_high: 8,
+ software_mid: 4,
+ software_low: 2,
+ },
+};
+
+const RESOLUTION_MULTIPLIERS: Record<string, number> = {
+ "1280x720": 1.5,
+ "1920x1080": 1.0,
+ "2560x1440": 0.6,
+ "3840x2160": 0.25,
+};
+
+function getResolutionMultiplier(width: number, height: number): number {
+ const key = `${width}x${height}`;
+ if (RESOLUTION_MULTIPLIERS[key]) {
+ return RESOLUTION_MULTIPLIERS[key];
+ }
+
+ const pixels = width * height;
+ const basePixels = 1920 * 1080;
+ return basePixels / pixels;
+}
+
+function getComplexityMultiplier(settings: ExportEstimateSettings): number {
+ let multiplier = 1.0;
+
+ if (settings.hasEffects) {
+ multiplier *= 0.7;
+ }
+
+ if (settings.hasTransitions) {
+ multiplier *= 0.85;
+ }
+
+ if (settings.trackCount && settings.trackCount > 2) {
+ multiplier *= Math.max(0.5, 1 - (settings.trackCount - 2) * 0.1);
+ }
+
+ return multiplier;
+}
+
+function formatTime(seconds: number): string {
+ if (seconds < 60) {
+ return `~${Math.round(seconds)} seconds`;
+ }
+
+ const minutes = Math.floor(seconds / 60);
+ const remainingSeconds = Math.round(seconds % 60);
+
+ if (minutes < 60) {
+ if (remainingSeconds === 0) {
+ return `~${minutes} minute${minutes > 1 ? "s" : ""}`;
+ }
+ return `~${minutes}m ${remainingSeconds}s`;
+ }
+
+ const hours = Math.floor(minutes / 60);
+ const remainingMinutes = minutes % 60;
+ return `~${hours}h ${remainingMinutes}m`;
+}
+
+export function estimateExportTime(
+ profile: DeviceProfile,
+ settings: ExportEstimateSettings
+): TimeEstimate {
+ const totalFrames = Math.ceil(settings.duration * settings.frameRate);
+
+ if (profile.benchmark) {
+ const benchmarkResPixels =
+ profile.benchmark.resolution.width * profile.benchmark.resolution.height;
+ const targetResPixels = settings.width * settings.height;
+ const resolutionFactor = benchmarkResPixels / targetResPixels;
+
+ let codecFactor = 1.0;
+ if (profile.benchmark.codec !== settings.codec) {
+ const codecSpeeds: Record<string, number> = {
+ h264: 1.0,
+ h265: 0.4,
+ vp9: 0.5,
+ av1: 0.2,
+ };
+ codecFactor =
+ (codecSpeeds[profile.benchmark.codec] || 1) /
+ (codecSpeeds[settings.codec] || 1);
+ }
+
+ const adjustedFps =
+ profile.benchmark.framesPerSecond *
+ resolutionFactor *
+ codecFactor *
+ getComplexityMultiplier(settings);
+
+ const seconds = totalFrames / Math.max(1, adjustedFps);
+
+ return {
+ seconds,
+ formatted: formatTime(seconds),
+ confidence: "measured",
+ breakdown: {
+ rendering: seconds * 0.4,
+ encoding: seconds * 0.55,
+ muxing: seconds * 0.05,
+ },
+ };
+ }
+
+ const codecSupport = profile.encoding[settings.codec];
+ const isHardware = codecSupport?.hardware || false;
+ const tier = profile.overallTier;
+
+ const encodingType = isHardware ? "hardware" : "software";
+ const key = `${encodingType}_${tier}`;
+
+ const baseFps = BASE_FPS_ESTIMATES[settings.codec]?.[key] || 15;
+ const resolutionMultiplier = getResolutionMultiplier(
+ settings.width,
+ settings.height
+ );
+ const complexityMultiplier = getComplexityMultiplier(settings);
+
+ const estimatedFps = baseFps * resolutionMultiplier * complexityMultiplier;
+ const seconds = totalFrames / Math.max(1, estimatedFps);
+
+ return {
+ seconds,
+ formatted: formatTime(seconds),
+ confidence: "estimated",
+ breakdown: {
+ rendering: seconds * 0.4,
+ encoding: seconds * 0.55,
+ muxing: seconds * 0.05,
+ },
+ };
+}
+
+export function compareCodecEstimates(
+ profile: DeviceProfile,
+ settings: Omit<ExportEstimateSettings, "codec">
+): Array<{ codec: string; estimate: TimeEstimate; speedLabel: string }> {
+ const codecs: Array<"h264" | "h265" | "vp9" | "av1"> = [
+ "h264",
+ "h265",
+ "vp9",
+ "av1",
+ ];
+
+ const results = codecs
+ .filter((codec) => profile.encoding[codec]?.supported)
+ .map((codec) => {
+ const estimate = estimateExportTime(profile, { ...settings, codec });
+ let speedLabel = "";
+
+ if (estimate.seconds < 60) {
+ speedLabel = "⚡ Fast";
+ } else if (estimate.seconds < 300) {
+ speedLabel = "✓ Good";
+ } else if (estimate.seconds < 900) {
+ speedLabel = "⚠️ Slow";
+ } else {
+ speedLabel = "🐢 Very slow";
+ }
+
+ return { codec, estimate, speedLabel };
+ });
+
+ return results.sort((a, b) => a.estimate.seconds - b.estimate.seconds);
+}
+
+export async function runBenchmark(
+ onProgress?: (progress: BenchmarkProgress) => void
+): Promise<BenchmarkResult> {
+ const BENCHMARK_FRAMES = 60;
+ const WIDTH = 1920;
+ const HEIGHT = 1080;
+
+ onProgress?.({
+ phase: "preparing",
+ progress: 0,
+ framesProcessed: 0,
+ totalFrames: BENCHMARK_FRAMES,
+ });
+
+ const canvas = new OffscreenCanvas(WIDTH, HEIGHT);
+ const ctx = canvas.getContext("2d");
+
+ if (!ctx) {
+ throw new Error("Failed to create canvas context for benchmark");
+ }
+
+ const frames: ImageBitmap[] = [];
+ for (let i = 0; i < BENCHMARK_FRAMES; i++) {
+ ctx.fillStyle = `hsl(${(i * 6) % 360}, 70%, 50%)`;
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
+
+ ctx.fillStyle = "white";
+ ctx.font = "48px sans-serif";
+ ctx.fillText(`Frame ${i + 1}`, WIDTH / 2 - 80, HEIGHT / 2);
+
+ const bitmap = await createImageBitmap(canvas);
+ frames.push(bitmap);
+
+ onProgress?.({
+ phase: "rendering",
+ progress: ((i + 1) / BENCHMARK_FRAMES) * 0.3,
+ framesProcessed: i + 1,
+ totalFrames: BENCHMARK_FRAMES,
+ });
+ }
+
+ if (typeof VideoEncoder === "undefined") {
+ frames.forEach((f) => f.close());
+ throw new Error("VideoEncoder not supported");
+ }
+
+ const encodedChunks: EncodedVideoChunk[] = [];
+ let encodedCount = 0;
+
+ const encoder = new VideoEncoder({
+ output: (chunk) => {
+ encodedChunks.push(chunk);
+ encodedCount++;
+ onProgress?.({
+ phase: "encoding",
+ progress: 0.3 + (encodedCount / BENCHMARK_FRAMES) * 0.65,
+ framesProcessed: encodedCount,
+ totalFrames: BENCHMARK_FRAMES,
+ });
+ },
+ error: (e) => {
+ console.error("Benchmark encoder error:", e);
+ },
+ });
+
+ const config: VideoEncoderConfig = {
+ codec: "avc1.42001E",
+ width: WIDTH,
+ height: HEIGHT,
+ bitrate: 5_000_000,
+ framerate: 30,
+ hardwareAcceleration: "prefer-hardware",
+ };
+
+ const supported = await VideoEncoder.isConfigSupported(config);
+ if (!supported.supported) {
+ config.hardwareAcceleration = "prefer-software";
+ }
+
+ encoder.configure(config);
+
+ const startTime = performance.now();
+
+ for (let i = 0; i < frames.length; i++) {
+ const frame = new VideoFrame(frames[i], {
+ timestamp: i * (1_000_000 / 30),
+ duration: 1_000_000 / 30,
+ });
+
+ encoder.encode(frame, { keyFrame: i % 30 === 0 });
+ frame.close();
+ }
+
+ await encoder.flush();
+ encoder.close();
+
+ const endTime = performance.now();
+ const elapsedSeconds = (endTime - startTime) / 1000;
+ const framesPerSecond = BENCHMARK_FRAMES / elapsedSeconds;
+
+ frames.forEach((f) => f.close());
+
+ onProgress?.({
+ phase: "complete",
+ progress: 1,
+ framesProcessed: BENCHMARK_FRAMES,
+ totalFrames: BENCHMARK_FRAMES,
+ });
+
+ const result: BenchmarkResult = {
+ framesPerSecond,
+ codec: "h264",
+ resolution: { width: WIDTH, height: HEIGHT },
+ testedAt: Date.now(),
+ };
+
+ saveBenchmarkResult(result);
+
+ return result;
+}
+
+export function shouldRecommendBenchmark(profile: DeviceProfile): boolean {
+ if (!profile.benchmark) {
+ return true;
+ }
+
+ const oneWeek = 7 * 24 * 60 * 60 * 1000;
+ if (Date.now() - profile.benchmark.testedAt > oneWeek) {
+ return true;
+ }
+
+ return false;
+}
diff --git a/packages/core/src/device/index.ts b/packages/core/src/device/index.ts
new file mode 100644
index 00000000..3150f140
--- /dev/null
+++ b/packages/core/src/device/index.ts
@@ -0,0 +1,28 @@
+export {
+ type DeviceTier,
+ type CpuInfo,
+ type MemoryInfo,
+ type GpuInfo,
+ type DeviceCodecSupport,
+ type EncodingSupport,
+ type BenchmarkResult,
+ type DeviceProfile,
+ type CodecRecommendation,
+ detectDeviceCapabilities,
+ getDeviceProfile,
+ getCodecRecommendations,
+ getResolutionRecommendations,
+ saveBenchmarkResult,
+ clearBenchmarkCache,
+ formatDeviceSummary,
+} from "./device-capabilities";
+
+export {
+ type ExportEstimateSettings,
+ type TimeEstimate,
+ type BenchmarkProgress,
+ estimateExportTime,
+ compareCodecEstimates,
+ runBenchmark,
+ shouldRecommendBenchmark,
+} from "./export-estimator";
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 4ffb9dd4..5809ae77 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -14,6 +14,7 @@ export * from "./template";
export * from "./ai";
export * from "./animation";
export * from "./effects";
+export * from "./device";
export {
ExportEngine,
getExportEngine,