Create polished demo videos without editing skills. Mac/Windows/Linux
merge main into beta/pr410-native-gpu-export-test
wiiiii12393e13129789f
diff --cc electron/ipc/project/manager.tsindex 07ccc5be,1ff91c3c..404654b1--- a/electron/ipc/project/manager.ts+++ b/electron/ipc/project/manager.ts@@@ -1,4 -1,5 +1,4 @@@- import { existsSync, constants as fsConstants } from "node:fs";-import { constants as fsConstants } from "node:fs";-import { existsSync, realpathSync } from "node:fs";++import { existsSync, constants as fsConstants, realpathSync } from "node:fs";import fs from "node:fs/promises";import path from "node:path";import { app } from "electron";@@@ -22,15 -24,13 +22,14 @@@ importsetCustomRecordingsDir,setRecordingsDirLoaded,} from "../state";+import type { ProjectLibraryEntry, RecordingSessionData } from "../types";import {+ getRecordingsDir,normalizePath,normalizeVideoSourcePath,- getRecordingsDir,+ parseJsonWithByteOrderMark,} from "../utils";--export { normalizePath, normalizeVideoSourcePath };export function getAssetRootPath() {@@@ -51,13 -51,42 +50,47 @@@ export function isPathInsideDirectory(c}export function isAllowedLocalReadPath(candidatePath: string) {-- const allowedPrefixes = [RECORDINGS_DIR, USER_DATA_PATH, getAssetRootPath(), app.getPath("temp")];++ const allowedPrefixes = [++ RECORDINGS_DIR,++ USER_DATA_PATH,++ getAssetRootPath(),++ app.getPath("temp"),++ ];const normalizedCandidatePath = normalizePath(candidatePath);- return (- existsSync(normalizedCandidatePath) ||+ // Canonicalize so a symlink placed under an allowed prefix can't smuggle in a+ // target that lives outside it. realpathSync throws when the path doesn't+ // exist yet (e.g. a pending export approved before the file is written) — in+ // that case fall back to the lexical path, which can only succeed via the+ // approvedLocalReadPaths check below since no symlink target exists yet.+ let canonicalCandidatePath = normalizedCandidatePath;+ try {+ canonicalCandidatePath = normalizePath(realpathSync(normalizedCandidatePath));+ } catch {+ // File may not exist yet; keep the lexical path.+ }++ // Security: only allow paths under app-managed directories or paths the user+ // has explicitly opted into (recording session sources, files chosen via+ // dialog, app-produced exports). The lexical path must satisfy the policy+ // AND the canonical (real) path must satisfy it too, so a symlink under an+ // allowed prefix that points outside the allowlist is rejected. Previously+ // this returned true for any existing file, which made the allowlist a no-op+ // for read-local-file and the local media URL handler.+ const lexicalAllowed =allowedPrefixes.some((prefix) => isPathInsideDirectory(normalizedCandidatePath, prefix)) ||- approvedLocalReadPaths.has(normalizedCandidatePath)+ approvedLocalReadPaths.has(normalizedCandidatePath);+ if (!lexicalAllowed) {+ return false;+ }++ if (canonicalCandidatePath === normalizedCandidatePath) {+ return true;+ }++ return (+ allowedPrefixes.some((prefix) => isPathInsideDirectory(canonicalCandidatePath, prefix)) ||+ approvedLocalReadPaths.has(canonicalCandidatePath));}@@@ -122,7 -153,7 +157,9 @@@ export async function resolveApprovedLoreturn realPath;}--export async function replaceApprovedSessionLocalReadPaths(filePaths: Array<string | null | undefined>) {++export async function replaceApprovedSessionLocalReadPaths(++ filePaths: Array<string | null | undefined>,++) {const nextApprovedPaths = new Set<string>();const approvedPathLists = await Promise.all(filePaths.map((filePath) => collectApprovedLocalReadPaths(filePath)),@@@ -140,7 -171,7 +177,9 @@@}}--export async function resolveProjectMediaSources(project: unknown): Promise<++export async function resolveProjectMediaSources(++ project: unknown,++): Promise<| { success: true; videoPath: string; webcamPath: string | null }| { success: false; message: string }> {@@@ -303,10 -334,10 +342,15 @@@ export async function buildProjectLibrareturn {path: normalizedPath,-- name: path.basename(normalizedPath).replace(-- new RegExp(`\\.(${[PROJECT_FILE_EXTENSION, ...LEGACY_PROJECT_FILE_EXTENSIONS].join("|")})$`, "i"),-- "",-- ),++ name: path++ .basename(normalizedPath)++ .replace(++ new RegExp(++ `\\.(${[PROJECT_FILE_EXTENSION, ...LEGACY_PROJECT_FILE_EXTENSIONS].join("|")})$`,++ "i",++ ),++ "",++ ),updatedAt: stats.mtimeMs,thumbnailPath: thumbnailExists ? thumbnailPath : null,isCurrent: Boolean(diff --cc electron/ipc/register/export.tsindex 8a73e17b,3ba40c38..8ff7199b--- a/electron/ipc/register/export.ts+++ b/electron/ipc/register/export.ts@@@ -15,7 -15,7 +15,8 @@@ import} from "../export/exportStream";import {enqueueNativeVideoExportFrameWrite,+ enqueueNativeVideoExportFrameWrites,+ exportNativeStaticLayoutVideo,flushNativeVideoExportPendingWriteRequests,getNativeVideoExportMaxQueuedWriteBytes,getNativeVideoExportSessionError,@@@ -244,86 -219,79 +245,159 @@@ export function registerExportHandlers(},);+ ipcMain.handle("probe-native-video-metadata", async (_, filePath: string) => {+ try {+ if (typeof filePath !== "string" || filePath.trim().length === 0) {+ throw new Error("Native metadata probe requires a file path");+ }++ const metadata = await probeNativeVideoMetadata(getFfmpegBinaryPath(), filePath);+ return {+ success: true,+ metadata,+ };+ } catch (error) {+ console.warn("[probe-native-video-metadata] Failed:", error);+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ };+ }+ });++ ipcMain.handle(+ "native-static-layout-export",+ async (event, options: NativeStaticLayoutExportOptions) => {+ try {+ if (!options || typeof options.inputPath !== "string") {+ throw new Error("Native static layout export requires an input path");+ }++ const result = await exportNativeStaticLayoutVideo(+ getFfmpegBinaryPath(),+ options,+ (progress) => {+ if (event.sender.isDestroyed()) {+ return;+ }++ event.sender.send("native-static-layout-export-progress", progress);+ },+ );+ registerOwnedExportPath(result.outputPath);+ const primaryBackend = result.metrics.chunks[0]?.backend;+ return {+ success: true,+ tempPath: result.outputPath,+ encoderName:+ primaryBackend === "nvidia-cuda-compositor"+ ? "nvidia-cuda-compositor"+ : primaryBackend === "windows-d3d11-compositor"+ ? "windows-d3d11-compositor"+ : result.metrics.chunkCount > 1+ ? "chunked-h264-nvenc"+ : "static-layout-h264-nvenc",+ metrics: result.metrics,+ };+ } catch (error) {+ console.warn("[native-static-layout-export] Failed:", error);+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error),+ };+ }+ },+ );++ ipcMain.handle("native-static-layout-export-cancel", async (_, sessionId: string) => {+ const session = nativeStaticLayoutExportSessions.get(sessionId);+ if (!session) {+ return { success: true };+ }++ session.terminating = true;+ try {+ session.currentProcess?.kill("SIGKILL");+ } catch {+ // Process may already be closed.+ }++ return { success: true };+ });++ ipcMain.on(+ "native-video-export-write-frames-async",+ (+ event,+ payload: {+ sessionId: string;+ requestId: number;+ frameDataList: Uint8Array[];+ },+ ) => {+ const sessionId = payload?.sessionId;+ const requestId = payload?.requestId;+ const frameDataList = payload?.frameDataList;++ if (+ typeof sessionId !== "string" ||+ typeof requestId !== "number" ||+ !Array.isArray(frameDataList) ||+ frameDataList.length === 0+ ) {+ return;+ }++ const session = nativeVideoExportSessions.get(sessionId);+ if (!session) {+ sendNativeVideoExportWriteFrameResult(event.sender, sessionId, requestId, {+ success: false,+ error: "Invalid native export session",+ });+ return;+ }++ session.sender = event.sender;+ session.pendingWriteRequestIds.add(requestId);++ if (session.terminating) {+ settleNativeVideoExportWriteFrameRequest(sessionId, session, requestId, {+ success: false,+ error: "Native video export session was cancelled",+ });+ return;+ }++ if (+ session.inputMode !== "h264-stream" &&+ frameDataList.some((frameData) => frameData.byteLength !== session.inputByteSize)+ ) {+ settleNativeVideoExportWriteFrameRequest(sessionId, session, requestId, {+ success: false,+ error: "Native video export batch contained invalid frame sizes",+ });+ return;+ }++ void enqueueNativeVideoExportFrameWrites(session, frameDataList)+ .then(() => {+ settleNativeVideoExportWriteFrameRequest(sessionId, session, requestId, {+ success: true,+ });+ })+ .catch((error) => {+ session.stdinError = error instanceof Error ? error : new Error(String(error));+ settleNativeVideoExportWriteFrameRequest(sessionId, session, requestId, {+ success: false,+ error: getNativeVideoExportSessionError(+ session,+ session.stdinError.message,+ ),+ });+ });+ },+ );+ipcMain.on("native-video-export-write-frame-async",(diff --cc src/components/video-editor/VideoEditor.tsxindex 609f09d7,72cbb0c3..22a12e7a--- a/src/components/video-editor/VideoEditor.tsx+++ b/src/components/video-editor/VideoEditor.tsx@@@ -330,7 -330,20 +340,8 @@@ const SMOKE_EXPORT_READY_TIMEOUT_MS = 3const DEFAULT_MP4_EXPORT_FRAME_RATE: ExportMp4FrameRate = 30;const SOURCE_AUDIO_FALLBACK_TOAST_ID = "source-audio-fallback-error";const PROJECT_AUTOSAVE_DELAY_MS = 1000;+ const EXPORT_ERROR_TOAST_DURATION_MS = 20000;-function getEncodingModeBitrateMultiplier(encodingMode: ExportEncodingMode): number {- switch (encodingMode) {- case "fast":- return 0.1;- case "quality":- return 0.9;- case "balanced":- default:- return 0.7;- }-}-function summarizeErrorMessage(message: string): string {const firstLine = message.split(/\r?\n/)@@@ -2456,9 -2515,8 +2546,10 @@@ export default function VideoEditor()loadInitialData();}, [applyLoadedProject,+ applySessionPresentation,autoApplyFreshRecordingAutoZooms,+ devOpenRecordingConfig.inputPath,+ devOpenRecordingConfig.webcamInputPath,initialEditorPreferences,smokeExportConfig.enabled,smokeExportConfig.inputPath,diff --cc src/components/video-editor/VideoPlayback.tsxindex 8f6778b1,7202f25a..d2d65cb6--- a/src/components/video-editor/VideoPlayback.tsx+++ b/src/components/video-editor/VideoPlayback.tsx@@@ -1508,17 -1438,24 +1618,25 @@@ const VideoPlayback = forwardRef<VideoPreturn;}+ const webcamDuration = Number.isFinite(webcamVideo.duration)+ ? webcamVideo.duration+ : null;const targetTime = getWebcamMediaTargetTimeSeconds({currentTime,- webcamDuration: Number.isFinite(webcamVideo.duration) ? webcamVideo.duration : null,- timeOffsetMs: webcam.timeOffsetMs,+ webcamDuration,+ timeOffsetMs: webcamTimeOffsetMs,});+ const mediaTargetTime =+ targetTime <= 0 && webcamDuration !== null && webcamDuration > 0+ ? Math.min(1 / 60, webcamDuration)+ : targetTime;+ const timelineTimeMs = currentTime * 1000;const activeSpeedRegion = speedRegionsRef.current.find(- (region) => targetTime * 1000 >= region.startMs && targetTime * 1000 < region.endMs,+ (region) => timelineTimeMs >= region.startMs && timelineTimeMs < region.endMs,);const targetPlaybackRate = activeSpeedRegion ? activeSpeedRegion.speed : 1;+ enablePitchPreservingPlayback(webcamVideo);if (Math.abs(webcamVideo.playbackRate - targetPlaybackRate) > 0.001) {webcamVideo.playbackRate = targetPlaybackRate;}diff --cc src/lib/exporter/backendPolicy.test.tsindex 51eaaca0,5362b202..7c532a18--- a/src/lib/exporter/backendPolicy.test.ts+++ b/src/lib/exporter/backendPolicy.test.ts@@@ -14,14 -10,10 +14,14 @@@ describe("backendPolicy", () =>expect(normalizeLightningRuntimePlatform("unknown")).toBe("unknown");});- it("keeps auto backend WebCodecs-first on every platform", () => {- expect(shouldPreferNativeAutoBackend("win32")).toBe(false);+ it("prefers native auto backend on desktop platforms with the fastest native path", () => {+ expect(shouldPreferNativeAutoBackend("win32")).toBe(true);expect(shouldPreferNativeAutoBackend("linux")).toBe(false);- expect(shouldPreferNativeAutoBackend("darwin")).toBe(false);+ expect(shouldPreferNativeAutoBackend("darwin")).toBe(true);expect(shouldPreferNativeAutoBackend("unknown")).toBe(false);});++ it("keeps Lightning exports on the stable WebGL renderer by default", () => {+ expect(getDefaultLightningRenderBackend()).toBe("webgl");+ });});diff --cc src/lib/exporter/backendPolicy.tsindex 88e65a91,0b9f10d0..60f4f509--- a/src/lib/exporter/backendPolicy.ts+++ b/src/lib/exporter/backendPolicy.ts@@@ -25,9 -23,5 +25,9 @@@ export function normalizeLightningRunti}export function shouldPreferNativeAutoBackend(_platform: LightningRuntimePlatform): boolean {- return false;+ return _platform === "darwin" || _platform === "win32";}++export function getDefaultLightningRenderBackend(): ExportRenderBackend {+ return "webgl";+}diff --cc src/lib/exporter/modernVideoExporter.tsindex 0d2e31a6,64405cd6..263c5721--- a/src/lib/exporter/modernVideoExporter.ts+++ b/src/lib/exporter/modernVideoExporter.ts@@@ -13,43 -14,9 +14,40 @@@ import typeZoomRegion,ZoomTransitionEasing,} from "@/components/video-editor/types";+import { ZOOM_DEPTH_SCALES } from "@/components/video-editor/types";+import { DEFAULT_FOCUS } from "@/components/video-editor/videoPlayback/constants";+import {+ computeCursorFollowFocus,+ createCursorFollowCameraState,+ SNAP_TO_EDGES_RATIO_AUTO,+} from "@/components/video-editor/videoPlayback/cursorFollowCamera";+import { buildNativeCursorAtlas } from "@/components/video-editor/videoPlayback/cursorRenderer";+import { computePaddedLayout } from "@/components/video-editor/videoPlayback/layoutUtils";+import {+ createSpringState,+ getZoomSpringConfig,+ resetSpringState,+ stepSpringValue,+} from "@/components/video-editor/videoPlayback/motionSmoothing";+import { getCursorStyleSizeMultiplier } from "@/components/video-editor/videoPlayback/uploadedCursorAssets";+import { findDominantRegion } from "@/components/video-editor/videoPlayback/zoomRegionUtils";+import {+ computeFocusFromTransform,+ computeZoomTransform,+} from "@/components/video-editor/videoPlayback/zoomTransform";+import {+ getWebcamOverlayPosition,+ getWebcamOverlaySizePx,+} from "@/components/video-editor/webcamOverlay";import { extensionHost } from "@/lib/extensions";+import { getEffectiveVideoStreamDurationSeconds } from "@/lib/mediaTiming";+import {+ DEFAULT_WALLPAPER_PATH,+ DEFAULT_WALLPAPER_RELATIVE_PATH,+ isVideoWallpaperSource,+} from "@/lib/wallpapers";import { AudioProcessor, isAacAudioEncodingSupported } from "./audioEncoder";- import {- getDefaultLightningRenderBackend,- normalizeLightningRuntimePlatform,- } from "./backendPolicy";+ import { normalizeLightningRuntimePlatform, shouldPreferNativeAutoBackend } from "./backendPolicy";import { buildEditedTrackSourceSegments, classifyEditedTrackStrategy } from "./editedTrackStrategy";import {type ExportBackpressureProfile,@@@ -164,105 -130,13 +166,107 @@@ type NativeAudioPlaneditedTrackSegments: Array<{ startMs: number; endMs: number; speed: number }>;};+const FILTERGRAPH_FALLBACK_AUDIO_SAMPLE_RATE = 48_000;+const MIN_NATIVE_STATIC_LAYOUT_SPEED = 0.25;+const MAX_NATIVE_STATIC_LAYOUT_SPEED = 30;++type NativeStaticLayoutTimelineSegment = {+ sourceStartMs: number;+ sourceEndMs: number;+ outputStartMs: number;+ outputEndMs: number;+ speed: number;+};++function canUseNativeStaticLayoutSpeed(speed: number): boolean {+ return (+ Number.isFinite(speed) &&+ speed >= MIN_NATIVE_STATIC_LAYOUT_SPEED &&+ speed <= MAX_NATIVE_STATIC_LAYOUT_SPEED+ );+}++function buildNativeStaticLayoutTimelineSegments(+ segments: Array<{ startMs: number; endMs: number; speed: number }>,+): NativeStaticLayoutTimelineSegment[] {+ const timelineSegments: NativeStaticLayoutTimelineSegment[] = [];+ let outputCursorMs = 0;++ for (const segment of segments) {+ const sourceStartMs = Math.max(0, segment.startMs);+ const sourceEndMs = Math.max(sourceStartMs, segment.endMs);+ const speed = segment.speed;+ if (+ !Number.isFinite(sourceStartMs) ||+ !Number.isFinite(sourceEndMs) ||+ !Number.isFinite(speed) ||+ sourceEndMs - sourceStartMs <= 0.5 ||+ speed <= 0+ ) {+ return [];+ }++ const outputDurationMs = (sourceEndMs - sourceStartMs) / speed;+ if (!Number.isFinite(outputDurationMs) || outputDurationMs <= 0.5) {+ return [];+ }++ const outputStartMs = outputCursorMs;+ const outputEndMs = outputStartMs + outputDurationMs;+ timelineSegments.push({+ sourceStartMs,+ sourceEndMs,+ outputStartMs,+ outputEndMs,+ speed,+ });+ outputCursorMs = outputEndMs;+ }++ return timelineSegments;+}++type NativeStaticLayoutBackground =+ | {+ backgroundColor: string;+ backgroundImagePath?: null;+ temporaryPath?: string;+ }+ | {+ backgroundColor: string;+ backgroundImagePath: string;+ temporaryPath?: string;+ };++type NativeStaticLayoutWebcamOverlay = {+ inputPath: string;+ left: number;+ top: number;+ size: number;+ radius: number;+ shadowIntensity: number;+ mirror: boolean;+ timeOffsetMs: number;+};++type NativeStaticLayoutZoomSample = {+ timeMs: number;+ scale: number;+ x: number;+ y: number;+};+const NATIVE_EXPORT_ENGINE_NAME = "Breeze";const LIGHTNING_PIPELINE_NAME = "Lightning (Beta)";+const STATIC_LAYOUT_CHUNK_DURATION_SEC = 120;+const MISSING_NATIVE_WALLPAPER_FALLBACK_COLOR = "#ffffff";+const NATIVE_STATIC_LAYOUT_MAX_EXTRACTING_PROGRESS = 95;+const NATIVE_STATIC_LAYOUT_FRAME_COMPLETE_PROGRESS = 96;export class ModernVideoExporter {- private static readonly NATIVE_ENCODER_QUEUE_LIMIT = 32;+ private static readonly NATIVE_ENCODER_QUEUE_LIMIT = 64;+ private static readonly NATIVE_WRITE_BATCH_MAX_CHUNKS = 12;+ private static readonly NATIVE_WRITE_BATCH_MAX_BYTES = 2 * 1024 * 1024;private config: VideoExporterConfig;private streamingDecoder: StreamingVideoDecoder | null = null;@@@ -285,16 -159,12 +289,17 @@@private encoderName: string | null = null;private backpressureProfile: ExportBackpressureProfile | null = null;private nativeExportSessionId: string | null = null;+ private nativeStaticLayoutSessionId: string | null = null;+ private nativeStaticLayoutAverageFps: number | null = null;- private nativePendingWrite: Promise<void> = Promise.resolve();private nativeWritePromises = new Set<Promise<void>>();private nativeWriteError: Error | null = null;+ private pendingNativeWriteChunks: Uint8Array[] = [];+ private pendingNativeWriteBytes = 0;private maxNativeWriteInFlight = 1;private lastNativeExportError: string | null = null;+ private nativeStaticLayoutSkipReason: string | null = null;+ private nativeStaticLayoutSkipReasons: string[] = [];+ private nativeStaticLayoutBackgroundSkipReason: string | null = null;private nativeH264Encoder: VideoEncoder | null = null;private nativeEncoderError: Error | null = null;private effectiveDurationSec = 0;@@@ -331,21 -203,38 +338,38 @@@this.cancelled = false;this.encoderError = null;this.nativeEncoderError = null;+ this.nativeStaticLayoutSkipReason = null;+ this.nativeStaticLayoutSkipReasons = [];+ this.nativeStaticLayoutBackgroundSkipReason = null;this.totalExportStartTimeMs = this.getNowMs();const backendPreference = this.config.backendPreference ?? "auto";+ const runtimePlatform = this.getRuntimePlatform();let useNativeEncoder = false;+ let triedNativeStaticLayoutWithProbe = false;+ const shouldDeferNativeEncoderStart = backendPreference === "breeze";this.lastNativeExportError = null;let stageStartedAt = this.getNowMs();if (backendPreference === "breeze") {- useNativeEncoder = await this.tryStartNativeVideoExport();- this.nativeSessionStartTimeMs = this.getNowMs() - stageStartedAt;- if (!useNativeEncoder) {- throw new Error(- this.lastNativeExportError ??- `${NATIVE_EXPORT_ENGINE_NAME} export is unavailable for this output profile on this system.`,- );- }+ // Defer the streaming native encoder until after metadata is known.+ // Static-layout exports can then use the faster Windows D3D compositor+ // instead of unnecessarily rendering every frame through JS first.+ } else if (+ backendPreference === "auto" &&+ shouldPreferNativeAutoBackend(runtimePlatform)+ ) {+ stageStartedAt = this.getNowMs();+ useNativeEncoder = await this.tryStartNativeVideoExport();+ this.nativeSessionStartTimeMs = this.getNowMs() - stageStartedAt;++ if (!useNativeEncoder) {+ console.warn(+ `[VideoExporter] ${NATIVE_EXPORT_ENGINE_NAME} auto-preferred native export was unavailable; falling back to WebCodecs.`,+ this.lastNativeExportError,+ );+ stageStartedAt = this.getNowMs();+ await this.initializeEncoder();+ }} else {try {const configuredWebCodecsPath = await this.initializeEncoder();@@@ -2875,17 -1365,75 +2877,82 @@@}this.lastFinalizationRenderProgress = nextProgress.lastRenderProgress;this.lastFinalizationAudioProgress = nextProgress.lastAudioProgress;- this.reportProgress(totalFrames, totalFrames, "finalizing", renderProgress, audioProgress);+ this.reportProgress(+ totalFrames,+ totalFrames,+ "finalizing",+ nextProgress.lastRenderProgress,+ typeof audioProgress === "number" && Number.isFinite(audioProgress)+ ? nextProgress.lastAudioProgress+ : undefined,+ );}+ private queueNativeWriteChunk(sessionId: string, chunk: Uint8Array): void {+ this.pendingNativeWriteChunks.push(chunk);+ this.pendingNativeWriteBytes += chunk.byteLength;++ if (+ this.pendingNativeWriteChunks.length >=+ ModernVideoExporter.NATIVE_WRITE_BATCH_MAX_CHUNKS ||+ this.pendingNativeWriteBytes >= ModernVideoExporter.NATIVE_WRITE_BATCH_MAX_BYTES+ ) {+ this.flushPendingNativeWriteBatch(sessionId);+ }+ }++ private flushPendingNativeWriteBatch(sessionId: string): void {+ if (this.pendingNativeWriteChunks.length === 0) {+ return;+ }++ const chunks = this.pendingNativeWriteChunks;+ this.pendingNativeWriteChunks = [];+ this.pendingNativeWriteBytes = 0;+ const writePromise = window.electronAPI+ .nativeVideoExportWriteFrames(sessionId, chunks)+ .then((writeResult) => {+ if (!writeResult.success && !this.cancelled) {+ throw new Error(+ writeResult.error || "Failed to write H.264 chunks to native encoder",+ );+ }+ })+ .catch((error) => {+ if (!this.cancelled) {- const resolvedError =- error instanceof Error ? error : new Error(String(error));++ const resolvedError = error instanceof Error ? error : new Error(String(error));+ if (!this.nativeEncoderError) {+ this.nativeEncoderError = resolvedError;+ }+ if (!this.nativeWriteError) {+ this.nativeWriteError = resolvedError;+ }+ }+ throw error;+ });++ this.trackNativeWritePromise(writePromise);+ this.notifyEncodeCapacityAvailable();+ }++ private waitForEncodeCapacity(): Promise<void> {+ return new Promise((resolve) => {+ this.encodeCapacityWaiters.add(resolve);+ });+ }++ private notifyEncodeCapacityAvailable(): void {+ if (this.encodeCapacityWaiters.size === 0) {+ return;+ }++ const waiters = [...this.encodeCapacityWaiters];+ this.encodeCapacityWaiters.clear();+ for (const resolve of waiters) {+ resolve();+ }+ }+private reportProgress(currentFrame: number,totalFrames: number,@@@ -2899,7 -1447,14 +2966,18 @@@const sampleElapsedMs = Math.max(nowMs - this.lastProgressSampleTimeMs, 1);const sampleFrameDelta = Math.max(currentFrame - this.lastProgressSampleFrame, 0);const sampleRenderFps = (sampleFrameDelta * 1000) / sampleElapsedMs;- const displayedRenderFps = this.nativeStaticLayoutAverageFps ?? sampleRenderFps;- if (sampleElapsedMs >= 500 || currentFrame === totalFrames) {++ if (this.nativeStaticLayoutAverageFps !== null) {++ this.displayedRenderFps = this.nativeStaticLayoutAverageFps;++ } else if (sampleElapsedMs >= 500 || currentFrame === totalFrames) {+ this.displayedRenderFps =+ this.displayedRenderFps > 0+ ? this.displayedRenderFps * 0.35 + sampleRenderFps * 0.65+ : sampleRenderFps;+ } else if (this.displayedRenderFps <= 0) {+ this.displayedRenderFps = averageRenderFps;+ }++ const displayedRenderFps =++ this.displayedRenderFps > 0 ? this.displayedRenderFps : sampleRenderFps;const remainingFrames = Math.max(totalFrames - currentFrame, 0);const estimatedTimeRemaining =averageRenderFps > 0 ? remainingFrames / averageRenderFps : 0;