Skip to content

Create polished demo videos without editing skills. Mac/Windows/Linux

Fix Lightning export fallback and preview sync

webadderalla5746906deac
diff --git a/package-lock.json b/package-lock.json
index 9488569f..a0127ca3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "recordly",
- "version": "1.1.14",
+ "version": "1.1.15",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "recordly",
- "version": "1.1.14",
+ "version": "1.1.15",
"hasInstallScript": true,
"dependencies": {
"capturekit": "^1.0.13",
diff --git a/package.json b/package.json
index 06aa4eda..32e593cf 100644
--- a/package.json
+++ b/package.json
@@ -12,7 +12,7 @@
"url": "https://github.com/webadderall/Recordly/issues"
},
"private": true,
- "version": "1.1.14",
+ "version": "1.1.15",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/src/components/video-editor/VideoEditor.tsx b/src/components/video-editor/VideoEditor.tsx
index d77ec1e9..d79d864d 100644
--- a/src/components/video-editor/VideoEditor.tsx
+++ b/src/components/video-editor/VideoEditor.tsx
@@ -48,7 +48,11 @@ import {
VideoExporter,
} from "@/lib/exporter";
import { resolveMediaElementSource } from "@/lib/exporter/localMediaSource";
-import { clampMediaTimeToDuration, getMediaSyncPlaybackRate } from "@/lib/mediaTiming";
+import {
+ clampMediaTimeToDuration,
+ estimateCompanionAudioStartDelaySeconds,
+ getMediaSyncPlaybackRate,
+} from "@/lib/mediaTiming";
import { matchesShortcut } from "@/lib/shortcuts";
import { type AspectRatio, getAspectRatioValue } from "@/utils/aspectRatioUtils";
import { resolveAutoCaptionSourcePath } from "./autoCaptionSource";
@@ -2954,7 +2958,15 @@ export default function VideoEditor() {
for (const audio of sourceAudioElementsRef.current.values()) {
const audioDuration = Number.isFinite(audio.duration) ? audio.duration : null;
- const targetTime = clampMediaTimeToDuration(currentTime, audioDuration);
+ const startDelaySeconds = estimateCompanionAudioStartDelaySeconds(
+ duration,
+ audioDuration,
+ );
+ const beforeAudioStart = currentTime + 0.001 < startDelaySeconds;
+ const targetTime = clampMediaTimeToDuration(
+ currentTime - startDelaySeconds,
+ audioDuration,
+ );
if (timelineJumped || Math.abs(audio.currentTime - targetTime) > driftThreshold) {
try {
@@ -2974,7 +2986,7 @@ export default function VideoEditor() {
}
const atEnd = audioDuration !== null && targetTime >= audioDuration;
- if (isPlaying && !atEnd) {
+ if (isPlaying && !beforeAudioStart && !atEnd) {
audio.play().catch(() => undefined);
} else if (!audio.paused) {
audio.pause();
@@ -2982,7 +2994,7 @@ export default function VideoEditor() {
}
lastSourceAudioSyncTimeRef.current = currentTime;
- }, [currentTime, isPlaying, sourceAudioFallbackPaths, speedRegions]);
+ }, [currentTime, duration, isPlaying, sourceAudioFallbackPaths, speedRegions]);
const showExportSuccessToast = useCallback((filePath: string) => {
toast.success(`Exported successfully to ${filePath}`, {
@@ -3723,14 +3735,14 @@ export default function VideoEditor() {
const isExportSaving = exportProgress?.phase === "saving";
const isExportFinalizing = exportProgress?.phase === "finalizing";
- const exportFinalizingProgress = isExportFinalizing
- ? Math.min(
- typeof exportProgress?.renderProgress === "number"
- ? exportProgress.renderProgress
- : (exportProgress?.percentage ?? 99),
- 99,
- )
- : null;
+ const exportFinalizingProgress = isExportFinalizing
+ ? Math.min(
+ typeof exportProgress?.renderProgress === "number"
+ ? exportProgress.renderProgress
+ : (exportProgress?.percentage ?? 99),
+ 99,
+ )
+ : null;
const isLightningExportInProgress =
exportFormat === "mp4" && exportPipelineModel === "modern" && (isExporting || exportProgress !== null);
const isLegacyExportInProgress =
@@ -3746,9 +3758,9 @@ export default function VideoEditor() {
const exportPercentLabel = exportProgress
? isExportSaving
? t("editor.exportStatus.saving", "Opening save dialog...")
- : isExportFinalizing
+ : isExportFinalizing
? t("editor.exportStatus.finalizingPercent", "Finalizing {{percent}}%", {
- percent: Math.round(exportFinalizingProgress ?? 99),
+ percent: Math.round(exportFinalizingProgress ?? 99),
})
: t("editor.exportStatus.completePercent", "{{percent}}% complete", {
percent: Math.round(exportProgress.percentage),
@@ -3950,7 +3962,7 @@ export default function VideoEditor() {
<div
className="h-full bg-[#2563EB] transition-all duration-300 ease-out"
style={{
- width: `${Math.min(exportFinalizingProgress ?? (exportProgress?.percentage ?? 8), 100)}%`,
+ width: `${Math.min(exportFinalizingProgress ?? (exportProgress?.percentage ?? 8), 100)}%`,
}}
/>
)}
diff --git a/src/lib/exporter/modernVideoExporter.ts b/src/lib/exporter/modernVideoExporter.ts
index 3dacb6cc..049af21b 100644
--- a/src/lib/exporter/modernVideoExporter.ts
+++ b/src/lib/exporter/modernVideoExporter.ts
@@ -14,7 +14,10 @@ import type {
} from "@/components/video-editor/types";
import { AudioProcessor } from "./audioEncoder";
import { FrameRenderer as ModernFrameRenderer } from "./modernFrameRenderer";
-import { MP4_CODEC_FALLBACK_LIST, type SupportedMp4EncoderPath } from "./mp4Support";
+import {
+ getOrderedSupportedMp4EncoderCandidates,
+ type SupportedMp4EncoderPath,
+} from "./mp4Support";
import { VideoMuxer } from "./muxer";
import { captureCanvasFrameForNativeExport } from "./nativeFrameCapture";
import { type DecodedVideoInfo, StreamingVideoDecoder } from "./streamingDecoder";
@@ -122,7 +125,7 @@ export class ModernVideoExporter {
private nativeWriteError: Error | null = null;
private maxNativeWriteInFlight = 1;
private lastNativeExportError: string | null = null;
- private readonly WINDOWS_FINALIZATION_TIMEOUT_MS = 600_000;
+ private readonly FINALIZATION_TIMEOUT_MS = 600_000;
private totalExportStartTimeMs = 0;
private metadataLoadTimeMs = 0;
private rendererInitTimeMs = 0;
@@ -170,7 +173,21 @@ export class ModernVideoExporter {
}
} else {
try {
- await this.initializeEncoder();
+ const configuredWebCodecsPath = await this.initializeEncoder();
+ if (
+ backendPreference === "auto" &&
+ configuredWebCodecsPath.hardwareAcceleration === "prefer-software"
+ ) {
+ console.warn(
+ "[VideoExporter] Auto backend resolved to a software WebCodecs encoder; trying Breeze native export instead.",
+ );
+ stageStartedAt = this.getNowMs();
+ useNativeEncoder = await this.tryStartNativeVideoExport();
+ this.nativeSessionStartTimeMs = this.getNowMs() - stageStartedAt;
+ if (useNativeEncoder) {
+ this.disposeEncoder();
+ }
+ }
} catch (error) {
const webCodecsError = error instanceof Error ? error : new Error(String(error));
if (backendPreference === "webcodecs") {
@@ -354,11 +371,11 @@ export class ModernVideoExporter {
return { success: false, error: "Export cancelled", metrics: this.buildExportMetrics() };
}
- this.reportFinalizingProgress(totalFrames, 96);
+ this.reportFinalizingProgress(totalFrames, 96);
if (useNativeEncoder) {
stageStartedAt = this.getNowMs();
- this.reportFinalizingProgress(totalFrames, 99);
+ this.reportFinalizingProgress(totalFrames, 99);
const finishResult = await this.finishNativeVideoExport(nativeAudioPlan);
this.finalizationTimeMs = this.getNowMs() - stageStartedAt;
if (!finishResult.success || !finishResult.blob) {
@@ -378,12 +395,12 @@ export class ModernVideoExporter {
stageStartedAt = this.getNowMs();
if (this.encoder && this.encoder.state === "configured") {
- this.reportFinalizingProgress(totalFrames, 97);
- await this.awaitWithWindowsTimeout(this.encoder.flush(), "encoder flush");
+ this.reportFinalizingProgress(totalFrames, 97);
+ await this.awaitWithFinalizationTimeout(this.encoder.flush(), "encoder flush");
}
- this.reportFinalizingProgress(totalFrames, 98);
- await this.awaitWithWindowsTimeout(this.pendingMuxing, "muxing queued video chunks");
+ this.reportFinalizingProgress(totalFrames, 98);
+ await this.awaitWithFinalizationTimeout(this.pendingMuxing, "muxing queued video chunks");
if (nativeAudioPlan.audioMode !== "none" && !this.cancelled) {
const demuxer = this.streamingDecoder.getDemuxer();
@@ -393,8 +410,8 @@ export class ModernVideoExporter {
(this.config.sourceAudioFallbackPaths ?? []).length > 0
) {
this.audioProcessor = new AudioProcessor();
- this.reportFinalizingProgress(totalFrames, 99);
- await this.awaitWithWindowsTimeout(
+ this.reportFinalizingProgress(totalFrames, 99);
+ await this.awaitWithFinalizationTimeout(
this.audioProcessor.process(
demuxer,
this.muxer!,
@@ -410,8 +427,8 @@ export class ModernVideoExporter {
}
}
- this.reportFinalizingProgress(totalFrames, 99);
- const blob = await this.awaitWithWindowsTimeout(this.muxer!.finalize(), "muxer finalization");
+ this.reportFinalizingProgress(totalFrames, 99);
+ const blob = await this.awaitWithFinalizationTimeout(this.muxer!.finalize(), "muxer finalization");
this.finalizationTimeMs = this.getNowMs() - stageStartedAt;
return { success: true, blob, metrics: this.buildExportMetrics() };
@@ -435,13 +452,6 @@ export class ModernVideoExporter {
}
}
- private isWindowsPlatform(): boolean {
- if (typeof navigator === "undefined") {
- return false;
- }
- return /Win/i.test(navigator.platform);
- }
-
private getPlatformLabel(): string {
if (typeof navigator === "undefined") {
return "Unknown";
@@ -542,11 +552,7 @@ export class ModernVideoExporter {
return lines.join("\n");
}
- private async awaitWithWindowsTimeout<T>(promise: Promise<T>, stage: string): Promise<T> {
- if (!this.isWindowsPlatform()) {
- return promise;
- }
-
+ private async awaitWithFinalizationTimeout<T>(promise: Promise<T>, stage: string): Promise<T> {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
try {
@@ -554,12 +560,12 @@ export class ModernVideoExporter {
promise,
new Promise<T>((_, reject) => {
timeoutId = setTimeout(() => {
- reject(
- new Error(
- `Export timed out during ${stage} on Windows after ${Math.round(this.WINDOWS_FINALIZATION_TIMEOUT_MS / 60_000)} minutes`,
- ),
- );
- }, this.WINDOWS_FINALIZATION_TIMEOUT_MS);
+ reject(
+ new Error(
+ `Export timed out during ${stage} after ${Math.round(this.FINALIZATION_TIMEOUT_MS / 60_000)} minutes`,
+ ),
+ );
+ }, this.FINALIZATION_TIMEOUT_MS);
}),
]);
} finally {
@@ -788,7 +794,7 @@ export class ModernVideoExporter {
if (audioPlan.audioMode === "edited-track") {
this.audioProcessor = new AudioProcessor();
- const audioBlob = await this.awaitWithWindowsTimeout(
+ const audioBlob = await this.awaitWithFinalizationTimeout(
this.audioProcessor.renderEditedAudioTrack(
this.config.videoUrl,
this.config.trimRegions,
@@ -812,7 +818,7 @@ export class ModernVideoExporter {
await this.awaitPendingNativeWrites();
- const result = await this.awaitWithWindowsTimeout(
+ const result = await this.awaitWithFinalizationTimeout(
window.electronAPI.nativeVideoExportFinish(sessionId, {
audioMode: audioPlan.audioMode,
audioSourcePath:
@@ -899,15 +905,15 @@ export class ModernVideoExporter {
}
}
- private reportFinalizingProgress(totalFrames: number, renderProgress: number) {
- this.reportProgress(totalFrames, totalFrames, "finalizing", renderProgress);
- }
+ private reportFinalizingProgress(totalFrames: number, renderProgress: number) {
+ this.reportProgress(totalFrames, totalFrames, "finalizing", renderProgress);
+ }
private reportProgress(
currentFrame: number,
totalFrames: number,
phase: ExportProgress["phase"] = "extracting",
- renderProgress?: number,
+ renderProgress?: number,
) {
const nowMs = this.getNowMs();
const elapsedSeconds = Math.max((nowMs - this.exportStartTimeMs) / 1000, 0.001);
@@ -917,16 +923,16 @@ export class ModernVideoExporter {
const sampleRenderFps = (sampleFrameDelta * 1000) / sampleElapsedMs;
const remainingFrames = Math.max(totalFrames - currentFrame, 0);
const estimatedTimeRemaining = averageRenderFps > 0 ? remainingFrames / averageRenderFps : 0;
- const safeRenderProgress =
- phase === "finalizing"
- ? Math.max(0, Math.min(renderProgress ?? 99, 99))
- : undefined;
- const percentage =
- phase === "finalizing"
- ? safeRenderProgress ?? 99
- : totalFrames > 0
- ? (currentFrame / totalFrames) * 100
- : 100;
+ const safeRenderProgress =
+ phase === "finalizing"
+ ? Math.max(0, Math.min(renderProgress ?? 99, 99))
+ : undefined;
+ const percentage =
+ phase === "finalizing"
+ ? safeRenderProgress ?? 99
+ : totalFrames > 0
+ ? (currentFrame / totalFrames) * 100
+ : 100;
if (nowMs - this.lastThroughputLogTimeMs >= 1000 || currentFrame === totalFrames) {
const safeFrameCount = Math.max(this.processedFrameCount, 1);
@@ -970,14 +976,14 @@ export class ModernVideoExporter {
this.config.onProgress({
currentFrame,
totalFrames,
- percentage,
+ percentage,
estimatedTimeRemaining,
renderFps: sampleRenderFps,
renderBackend: this.renderBackend ?? undefined,
encodeBackend: this.encodeBackend ?? undefined,
encoderName: this.encoderName ?? undefined,
phase,
- renderProgress: safeRenderProgress,
+ renderProgress: safeRenderProgress,
});
}
}
@@ -1075,7 +1081,7 @@ export class ModernVideoExporter {
return Date.now();
}
- private async initializeEncoder(): Promise<void> {
+ private async initializeEncoder(): Promise<SupportedMp4EncoderPath> {
this.encodeQueue = 0;
this.webCodecsEncodeQueueLimit =
this.config.maxEncodeQueue ??
@@ -1188,7 +1194,7 @@ export class ModernVideoExporter {
`[VideoExporter] Using ${candidate.hardwareAcceleration} ${latencyMode} encoder path with codec ${candidate.codec}`,
);
this.encoder.configure(config);
- return;
+ return candidate;
}
console.warn(
@@ -1208,31 +1214,9 @@ export class ModernVideoExporter {
}
private getEncoderCandidates(): SupportedMp4EncoderPath[] {
- const candidates: SupportedMp4EncoderPath[] = [];
-
- if (this.config.preferredEncoderPath) {
- candidates.push(this.config.preferredEncoderPath);
- }
-
- const codecCandidates = this.config.codec
- ? [this.config.codec, ...MP4_CODEC_FALLBACK_LIST]
- : [...MP4_CODEC_FALLBACK_LIST];
-
- for (const codec of codecCandidates) {
- for (const hardwareAcceleration of ["prefer-hardware", "prefer-software"] as const) {
- candidates.push({ codec, hardwareAcceleration });
- }
- }
-
- return candidates.filter((candidate, index, values) => {
- return (
- values.findIndex((value) => {
- return (
- value.codec === candidate.codec &&
- value.hardwareAcceleration === candidate.hardwareAcceleration
- );
- }) === index
- );
+ return getOrderedSupportedMp4EncoderCandidates({
+ codec: this.config.codec,
+ preferredEncoderPath: this.config.preferredEncoderPath,
});
}
diff --git a/src/lib/exporter/mp4Support.test.ts b/src/lib/exporter/mp4Support.test.ts
new file mode 100644
index 00000000..fa1c4a66
--- /dev/null
+++ b/src/lib/exporter/mp4Support.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from "vitest";
+
+import { getOrderedSupportedMp4EncoderCandidates } from "./mp4Support";
+
+describe("getOrderedSupportedMp4EncoderCandidates", () => {
+ it("keeps hardware candidates ahead of a preferred software hint", () => {
+ const candidates = getOrderedSupportedMp4EncoderCandidates({
+ codec: "avc1.640033",
+ preferredEncoderPath: {
+ codec: "avc1.640033",
+ hardwareAcceleration: "prefer-software",
+ },
+ });
+
+ expect(candidates[0]).toEqual({
+ codec: "avc1.640033",
+ hardwareAcceleration: "prefer-hardware",
+ });
+ expect(candidates[1]).toEqual({
+ codec: "avc1.4d4033",
+ hardwareAcceleration: "prefer-hardware",
+ });
+ expect(candidates).toContainEqual({
+ codec: "avc1.640033",
+ hardwareAcceleration: "prefer-software",
+ });
+ expect(
+ candidates.findIndex((candidate) => {
+ return (
+ candidate.codec === "avc1.640033" &&
+ candidate.hardwareAcceleration === "prefer-software"
+ );
+ }),
+ ).toBeGreaterThan(
+ candidates.findIndex((candidate) => {
+ return (
+ candidate.codec === "avc1.42001f" &&
+ candidate.hardwareAcceleration === "prefer-hardware"
+ );
+ }),
+ );
+ });
+
+ it("preserves a preferred hardware path at the front of the list", () => {
+ const candidates = getOrderedSupportedMp4EncoderCandidates({
+ codec: "avc1.640033",
+ preferredEncoderPath: {
+ codec: "avc1.4d401f",
+ hardwareAcceleration: "prefer-hardware",
+ },
+ });
+
+ expect(candidates[0]).toEqual({
+ codec: "avc1.4d401f",
+ hardwareAcceleration: "prefer-hardware",
+ });
+ });
+});
diff --git a/src/lib/exporter/mp4Support.ts b/src/lib/exporter/mp4Support.ts
index 422f76cc..cbe2b23f 100644
--- a/src/lib/exporter/mp4Support.ts
+++ b/src/lib/exporter/mp4Support.ts
@@ -59,6 +59,66 @@ function scaleDimensions(width: number, height: number, scale: number): { width:
};
}
+function appendEncoderCandidate(
+ candidates: SupportedMp4EncoderPath[],
+ candidate: SupportedMp4EncoderPath | null | undefined,
+): void {
+ if (!candidate) {
+ return;
+ }
+
+ const alreadyIncluded = candidates.some((value) => {
+ return (
+ value.codec === candidate.codec &&
+ value.hardwareAcceleration === candidate.hardwareAcceleration
+ );
+ });
+
+ if (!alreadyIncluded) {
+ candidates.push(candidate);
+ }
+}
+
+export function getOrderedSupportedMp4EncoderCandidates(options: {
+ codec?: string;
+ preferredEncoderPath?: SupportedMp4EncoderPath | null;
+}): SupportedMp4EncoderPath[] {
+ const orderedCodecs = Array.from(
+ new Set(
+ [
+ options.preferredEncoderPath?.codec,
+ options.codec,
+ ...MP4_CODEC_FALLBACK_LIST,
+ ].filter((value): value is string => typeof value === "string" && value.length > 0),
+ ),
+ );
+ const candidates: SupportedMp4EncoderPath[] = [];
+
+ if (options.preferredEncoderPath?.hardwareAcceleration === "prefer-hardware") {
+ appendEncoderCandidate(candidates, options.preferredEncoderPath);
+ }
+
+ for (const codec of orderedCodecs) {
+ appendEncoderCandidate(candidates, {
+ codec,
+ hardwareAcceleration: "prefer-hardware",
+ });
+ }
+
+ if (options.preferredEncoderPath?.hardwareAcceleration === "prefer-software") {
+ appendEncoderCandidate(candidates, options.preferredEncoderPath);
+ }
+
+ for (const codec of orderedCodecs) {
+ appendEncoderCandidate(candidates, {
+ codec,
+ hardwareAcceleration: "prefer-software",
+ });
+ }
+
+ return candidates;
+}
+
export async function resolveSupportedMp4EncoderPath(
options: ResolveMp4EncoderPathOptions,
): Promise<SupportedMp4EncoderPath | null> {
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index 1275d01a..8a939a52 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -95,7 +95,7 @@ export class VideoExporter {
private videoColorSpace: VideoColorSpaceInit | undefined;
private pendingMuxing: Promise<void> = Promise.resolve();
private chunkCount = 0;
- private readonly WINDOWS_FINALIZATION_TIMEOUT_MS = 600_000;
+ private readonly FINALIZATION_TIMEOUT_MS = 600_000;
private exportStartTimeMs = 0;
private progressSampleStartTimeMs = 0;
private progressSampleStartFrame = 0;
@@ -250,19 +250,19 @@ export class VideoExporter {
// Finalize encoding
if (this.encoder && this.encoder.state === "configured") {
this.reportFinalizingProgress(totalFrames, 97);
- await this.awaitWithWindowsTimeout(this.encoder.flush(), "encoder flush");
+ await this.awaitWithFinalizationTimeout(this.encoder.flush(), "encoder flush");
}
// Wait for queued muxing operations to complete
this.reportFinalizingProgress(totalFrames, 98);
- await this.awaitWithWindowsTimeout(this.pendingMuxing, "muxing queued video chunks");
+ await this.awaitWithFinalizationTimeout(this.pendingMuxing, "muxing queued video chunks");
if (hasAudio && !this.cancelled) {
const demuxer = this.streamingDecoder.getDemuxer();
if (demuxer || hasAudioRegions || hasSourceAudioFallback) {
this.audioProcessor = new AudioProcessor();
this.reportFinalizingProgress(totalFrames, 99);
- await this.awaitWithWindowsTimeout(
+ await this.awaitWithFinalizationTimeout(
this.audioProcessor.process(
demuxer,
this.muxer!,
@@ -280,7 +280,7 @@ export class VideoExporter {
// Finalize muxer and get output blob
this.reportFinalizingProgress(totalFrames, 99);
- const blob = await this.awaitWithWindowsTimeout(this.muxer!.finalize(), "muxer finalization");
+ const blob = await this.awaitWithFinalizationTimeout(this.muxer!.finalize(), "muxer finalization");
return { success: true, blob };
} catch (error) {
@@ -314,18 +314,7 @@ export class VideoExporter {
return false;
}
- private isWindowsPlatform(): boolean {
- if (typeof navigator === "undefined") {
- return false;
- }
- return /Win/i.test(navigator.platform);
- }
-
- private async awaitWithWindowsTimeout<T>(promise: Promise<T>, stage: string): Promise<T> {
- if (!this.isWindowsPlatform()) {
- return promise;
- }
-
+ private async awaitWithFinalizationTimeout<T>(promise: Promise<T>, stage: string): Promise<T> {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
try {
@@ -335,10 +324,10 @@ export class VideoExporter {
timeoutId = setTimeout(() => {
reject(
new Error(
- `Export timed out during ${stage} on Windows after ${Math.round(this.WINDOWS_FINALIZATION_TIMEOUT_MS / 60_000)} minutes`,
+ `Export timed out during ${stage} after ${Math.round(this.FINALIZATION_TIMEOUT_MS / 60_000)} minutes`,
),
);
- }, this.WINDOWS_FINALIZATION_TIMEOUT_MS);
+ }, this.FINALIZATION_TIMEOUT_MS);
}),
]);
} finally {
@@ -520,7 +509,7 @@ export class VideoExporter {
if (audioPlan.audioMode === "edited-track") {
this.audioProcessor = new AudioProcessor();
- const audioBlob = await this.awaitWithWindowsTimeout(
+ const audioBlob = await this.awaitWithFinalizationTimeout(
this.audioProcessor.renderEditedAudioTrack(
this.config.videoUrl,
this.config.trimRegions,
@@ -537,7 +526,7 @@ export class VideoExporter {
const sessionId = this.nativeExportSessionId;
this.nativeExportSessionId = null;
- const result = await this.awaitWithWindowsTimeout(
+ const result = await this.awaitWithFinalizationTimeout(
window.electronAPI.nativeVideoExportFinish(sessionId, {
audioMode: audioPlan.audioMode,
audioSourcePath:
diff --git a/src/lib/mediaTiming.test.ts b/src/lib/mediaTiming.test.ts
index f06be380..cc595dac 100644
--- a/src/lib/mediaTiming.test.ts
+++ b/src/lib/mediaTiming.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
clampMediaTimeToDuration,
+ estimateCompanionAudioStartDelaySeconds,
getEffectiveVideoStreamDurationSeconds,
getEffectiveRecordingDurationMs,
getMediaSyncPlaybackRate,
@@ -19,6 +20,17 @@ describe("clampMediaTimeToDuration", () => {
});
});
+describe("estimateCompanionAudioStartDelaySeconds", () => {
+ it("returns the positive tail gap when companion audio is shorter", () => {
+ expect(estimateCompanionAudioStartDelaySeconds(10, 9.6)).toBeCloseTo(0.4);
+ });
+
+ it("ignores tiny or negative differences", () => {
+ expect(estimateCompanionAudioStartDelaySeconds(10, 9.97)).toBe(0);
+ expect(estimateCompanionAudioStartDelaySeconds(10, 10.5)).toBe(0);
+ });
+});
+
describe("getEffectiveRecordingDurationMs", () => {
it("subtracts accumulated paused time", () => {
expect(
diff --git a/src/lib/mediaTiming.ts b/src/lib/mediaTiming.ts
index 29583eaf..d41419cb 100644
--- a/src/lib/mediaTiming.ts
+++ b/src/lib/mediaTiming.ts
@@ -10,6 +10,21 @@ export function clampMediaTimeToDuration(
return Math.max(0, Math.min(safeTargetTime, Math.max(0, duration)));
}
+export function estimateCompanionAudioStartDelaySeconds(
+ timelineDuration?: number | null,
+ audioDuration?: number | null,
+): number {
+ if (!Number.isFinite(timelineDuration) || !Number.isFinite(audioDuration)) {
+ return 0;
+ }
+
+ const safeTimelineDuration = Math.max(0, timelineDuration ?? 0);
+ const safeAudioDuration = Math.max(0, audioDuration ?? 0);
+ const estimatedDelaySeconds = safeTimelineDuration - safeAudioDuration;
+
+ return estimatedDelaySeconds > 0.05 ? estimatedDelaySeconds : 0;
+}
+
export function getMediaSyncPlaybackRate({
basePlaybackRate,
currentTime,