Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
perf(export): a StageTimings harness and hardware-first encode, with the audio stretch overlapped
Etienne Lescotae7f6ed1e79f
diff --git a/src/lib/exporter/perfTimings.test.ts b/src/lib/exporter/perfTimings.test.tsnew file mode 100644index 000000000..9af186859--- /dev/null+++ b/src/lib/exporter/perfTimings.test.ts@@ -0,0 +1,174 @@+import { describe, expect, it } from "vitest";+import { StageTimings } from "./perfTimings";++function fakeClock() {+ let t = 0;+ return {+ now: () => t,+ tick: (ms: number) => {+ t += ms;+ },+ };+}++describe("StageTimings — record + snapshot", () => {+ it("accumulates totals, counts, averages, and shares", () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ timings.record("decode", 10);+ timings.record("render", 30);+ timings.record("decode", 20);++ const snapshot = timings.snapshot();+ expect(snapshot.totalMs).toBe(60);+ expect(snapshot.stages.decode.totalMs).toBe(30);+ expect(snapshot.stages.decode.count).toBe(2);+ expect(snapshot.stages.decode.avgMs).toBe(15);+ expect(snapshot.stages.decode.pct).toBe(50);+ expect(snapshot.stages.render.totalMs).toBe(30);+ expect(snapshot.stages.render.count).toBe(1);+ expect(snapshot.stages.render.avgMs).toBe(30);+ expect(snapshot.stages.render.pct).toBe(50);+ expect(Object.values(snapshot.stages).reduce((sum, stat) => sum + stat.pct, 0)).toBeCloseTo(+ 100,+ );+ });++ it("preserves first-seen order in snapshots and summaries", () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ timings.record("render", 2);+ timings.record("decode-wait", 1);+ timings.record("render", 3);+ timings.record("encode-wait", 4);++ expect(Object.keys(timings.snapshot().stages)).toEqual([+ "render",+ "decode-wait",+ "encode-wait",+ ]);++ const rows = timings+ .formatSummary()+ .split("\n")+ .filter(+ (line) =>+ line.startsWith("render") ||+ line.startsWith("decode-wait") ||+ line.startsWith("encode-wait"),+ );+ expect(rows.map((row) => row.trimStart().split(/\s+/)[0])).toEqual([+ "render",+ "decode-wait",+ "encode-wait",+ ]);+ });+});++describe("StageTimings — injected-clock helpers", () => {+ it("records a start/stop duration once", () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ const stop = timings.start("x");+ clock.tick(10);+ stop();+ stop();++ expect(timings.snapshot().stages.x).toEqual({ totalMs: 10, count: 1, avgMs: 10, pct: 100 });+ });++ it("times a synchronous function and returns its result", () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ const result = timings.time("x", () => {+ clock.tick(12);+ return 42;+ });++ expect(result).toBe(42);+ expect(timings.snapshot().stages.x.totalMs).toBe(12);+ });++ it("times an async function and returns its resolved value", async () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ const result = await timings.timeAsync("x", async () => {+ clock.tick(18);+ return "done";+ });++ expect(result).toBe("done");+ expect(timings.snapshot().stages.x).toEqual({ totalMs: 18, count: 1, avgMs: 18, pct: 100 });+ });++ it("records async elapsed time when the function rejects and re-throws", async () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ const error = new Error("failed");++ await expect(+ timings.timeAsync("reject", async () => {+ clock.tick(7);+ throw error;+ }),+ ).rejects.toBe(error);++ expect(timings.snapshot().stages.reject).toEqual({ totalMs: 7, count: 1, avgMs: 7, pct: 100 });+ });+});++describe("StageTimings — invalid and empty samples", () => {+ it.each([+ ["negative", -1],+ ["NaN", Number.NaN],+ ["Infinity", Number.POSITIVE_INFINITY],+ ])("ignores a %s duration without creating a sample", (_name, duration) => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ timings.record("bad", duration);++ expect(timings.snapshot()).toEqual({ stages: {}, totalMs: 0 });+ });++ it("reports zero averages and shares for empty timings and a zero-duration sample", () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ expect(timings.snapshot()).toEqual({ stages: {}, totalMs: 0 });++ timings.record("zero", 0);+ expect(timings.snapshot().stages.zero).toEqual({ totalMs: 0, count: 1, avgMs: 0, pct: 0 });+ });+});++describe("StageTimings — formatSummary and reset", () => {+ it("formats stage rows, a total, effective fps, and hardware acceleration", () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ timings.record("decode-wait", 10);+ timings.record("render", 10);++ const summary = timings.formatSummary({ frames: 10, hardwareAcceleration: "prefer-hardware" });+ expect(summary).toContain("decode-wait");+ expect(summary).toContain("render");+ expect(summary).toContain("TOTAL");+ expect(summary).toContain("fps: 500.0");+ expect(summary).toContain("hwAccel: prefer-hardware");+ });++ it("uses n/a for fps when total time is zero", () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ timings.record("zero", 0);++ expect(timings.formatSummary({ frames: 10 })).toContain("fps: n/a");+ });++ it("clears all accumulated timing data", () => {+ const clock = fakeClock();+ const timings = new StageTimings(clock.now);+ timings.record("x", 25);+ timings.reset();++ expect(timings.snapshot()).toEqual({ stages: {}, totalMs: 0 });+ });+});diff --git a/src/lib/exporter/perfTimings.ts b/src/lib/exporter/perfTimings.tsnew file mode 100644index 000000000..7bf46049b--- /dev/null+++ b/src/lib/exporter/perfTimings.ts@@ -0,0 +1,138 @@+// StageTimings: pure-logic per-stage timing accumulation for the v2 export+// performance harness. Callers provide measured durations or wrap work with an+// injected clock; this module does not time export work or touch browser APIs.++export interface StageStat {+ totalMs: number; // summed elapsed across all record()/stop() calls for this stage+ count: number; // number of samples+ avgMs: number; // totalMs / count (0 when count === 0)+ pct: number; // totalMs / grandTotalMs * 100 (0 when grandTotal === 0)+}++export interface PerfSnapshot {+ stages: Record<string, StageStat>; // keyed by stage name, in FIRST-SEEN order+ totalMs: number; // sum of every stage's totalMs+}++interface MutableStageStat {+ totalMs: number;+ count: number;+}++const defaultNow =+ typeof performance !== "undefined" && typeof performance.now === "function"+ ? () => performance.now()+ : () => Date.now();++export class StageTimings {+ private readonly now: () => number;++ private readonly stats = new Map<string, MutableStageStat>();++ constructor(now: () => number = defaultNow) {+ this.now = now;+ }++ record(stage: string, ms: number): void {+ if (!Number.isFinite(ms) || ms < 0) {+ // Invalid durations are skipped so they do not create a misleading sample.+ return;+ }++ const stat = this.stats.get(stage);+ if (stat) {+ stat.totalMs += ms;+ stat.count += 1;+ return;+ }++ this.stats.set(stage, { totalMs: ms, count: 1 });+ }++ start(stage: string): () => void {+ const startedAt = this.now();+ let stopped = false;++ return () => {+ if (stopped) {+ return;+ }+ stopped = true;+ this.record(stage, Math.max(0, this.now() - startedAt));+ };+ }++ time<T>(stage: string, fn: () => T): T {+ const stop = this.start(stage);+ try {+ return fn();+ } finally {+ stop();+ }+ }++ async timeAsync<T>(stage: string, fn: () => Promise<T>): Promise<T> {+ const stop = this.start(stage);+ try {+ return await fn();+ } finally {+ stop();+ }+ }++ snapshot(): PerfSnapshot {+ let totalMs = 0;+ for (const stat of this.stats.values()) {+ totalMs += stat.totalMs;+ }++ const stages: Record<string, StageStat> = {};+ for (const [stage, stat] of this.stats) {+ stages[stage] = {+ totalMs: stat.totalMs,+ count: stat.count,+ avgMs: stat.count === 0 ? 0 : stat.totalMs / stat.count,+ pct: totalMs === 0 ? 0 : (stat.totalMs / totalMs) * 100,+ };+ }++ return { stages, totalMs };+ }++ formatSummary(opts: { frames?: number; hardwareAcceleration?: string } = {}): string {+ const snapshot = this.snapshot();+ const lines = ["stage totalMs pct avgMs count"];++ for (const [stage, stat] of Object.entries(snapshot.stages)) {+ lines.push(+ `${stage} ${stat.totalMs.toFixed(1).padStart(9)} ${stat.pct+ .toFixed(1)+ .padStart(5)}% ${stat.avgMs.toFixed(2).padStart(7)} n=${stat.count}`,+ );+ }++ const totalCount = Object.values(snapshot.stages).reduce((sum, stat) => sum + stat.count, 0);+ const totalAvgMs = totalCount === 0 ? 0 : snapshot.totalMs / totalCount;+ const totalPct = snapshot.totalMs === 0 ? 0 : 100;+ lines.push(+ `TOTAL ${snapshot.totalMs.toFixed(1).padStart(9)} ${totalPct+ .toFixed(1)+ .padStart(5)}% ${totalAvgMs.toFixed(2).padStart(7)} n=${totalCount}`,+ );++ if (opts.frames !== undefined) {+ const fps =+ snapshot.totalMs === 0 ? "n/a" : (opts.frames / (snapshot.totalMs / 1000)).toFixed(1);+ lines.push(`fps: ${fps}`);+ }+ if (opts.hardwareAcceleration !== undefined) {+ lines.push(`hwAccel: ${opts.hardwareAcceleration}`);+ }++ return lines.join("\n");+ }++ reset(): void {+ this.stats.clear();+ }+}diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.tsindex 0a06be349..9724a63d8 100644--- a/src/lib/exporter/videoExporter.ts+++ b/src/lib/exporter/videoExporter.ts@@ -19,6 +19,7 @@ import { WsolaTimeStretcher } from "./audioTimeStretch";import { FrameRenderer } from "./frameRenderer";import { materializeLocalSourceFile, releaseLocalSourceFile } from "./localSourceFile";import { VideoMuxer, videoCodecFamily } from "./muxer";+import { StageTimings } from "./perfTimings";import { MAX_IN_MEMORY_SOURCE_BYTES } from "./sourceFileLimits";import { StreamingVideoDecoder } from "./streamingDecoder";import { computeKeepSegments, splitBySpeed } from "./timelineSegments";@@ -59,6 +60,156 @@ export async function waitForEncoderQueueSpace(params: {}}+// D4 diagnostic: measure the ENCODER ALONE (synthetic frames, no decode/render)+// to separate platform encoder throughput from our pipeline's feeding path.+// Temporary — flip off/remove once the bottleneck is identified.+const ENCODER_PROBE = true;++async function probeOneEncoder(opts: {+ label: string;+ width: number;+ height: number;+ codec: string;+ bitrate: number;+ framerate: number;+ hardwareAcceleration: HardwareAcceleration;+ frameSource: "canvas" | "cpu";+}): Promise<string> {+ const { width, height } = opts;+ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext("2d");+ if (!ctx) return `${opts.label}: no 2d ctx`;+ let chunks = 0;+ const encoder = new VideoEncoder({+ output: (chunk) => {+ chunks++;+ void chunk;+ },+ error: (e) => console.warn(`[encoder probe] ${opts.label} error:`, e),+ });+ const config: VideoEncoderConfig = {+ codec: opts.codec,+ width,+ height,+ bitrate: opts.bitrate,+ framerate: opts.framerate,+ latencyMode: "quality",+ bitrateMode: "variable",+ hardwareAcceleration: opts.hardwareAcceleration,+ };+ const support = await VideoEncoder.isConfigSupported(config);+ if (!support.supported) return `${opts.label}: unsupported`;+ encoder.configure(config);+ const frameCount = 120;+ const frameDurationUs = Math.round(1_000_000 / opts.framerate);+ const start = performance.now();+ for (let i = 0; i < frameCount; i++) {+ ctx.fillStyle = i % 2 ? "#1c3d5a" : "#5a1c3d";+ ctx.fillRect(0, 0, width, height);+ ctx.fillStyle = "#ffffff";+ ctx.fillRect((i * 37) % width, (i * 23) % height, 80, 80);+ let frame: VideoFrame;+ if (opts.frameSource === "canvas") {+ frame = new VideoFrame(canvas, { timestamp: i * frameDurationUs, duration: frameDurationUs });+ } else {+ const pixels = ctx.getImageData(0, 0, width, height);+ frame = new VideoFrame(pixels.data.buffer, {+ format: "RGBA",+ codedWidth: width,+ codedHeight: height,+ timestamp: i * frameDurationUs,+ duration: frameDurationUs,+ });+ }+ while (encoder.encodeQueueSize > 8) {+ await new Promise((resolve) => setTimeout(resolve, 2));+ }+ encoder.encode(frame, { keyFrame: i % 60 === 0 });+ frame.close();+ }+ await encoder.flush();+ const elapsedMs = performance.now() - start;+ encoder.close();+ return `${opts.label}: ${frameCount} frames in ${elapsedMs.toFixed(0)}ms = ${((frameCount / elapsedMs) * 1000).toFixed(1)} fps (${chunks} chunks)`;+}++async function runEncoderThroughputProbe(config: {+ width: number;+ height: number;+ codec?: string;+ bitrate: number;+ frameRate: number;+}): Promise<string> {+ const codec = config.codec || "avc1.640033";+ const base = {+ width: config.width,+ height: config.height,+ codec,+ bitrate: config.bitrate,+ framerate: config.frameRate,+ };+ const lines: string[] = ["[encoder probe]"];++ // If Chromium fell back to SwiftShader, WebGL is CPU-rasterized and the+ // "hardware" encoder is unavailable — that alone would explain hw==sw+ // throughput and the GPU composite showing no gain.+ try {+ const probeCanvas = document.createElement("canvas");+ const gl =+ (probeCanvas.getContext("webgl2") as WebGL2RenderingContext | null) ??+ (probeCanvas.getContext("webgl") as WebGLRenderingContext | null);+ if (gl) {+ const info = gl.getExtension("WEBGL_debug_renderer_info");+ const renderer = info+ ? gl.getParameter(info.UNMASKED_RENDERER_WEBGL)+ : gl.getParameter(gl.RENDERER);+ const vendor = info+ ? gl.getParameter(info.UNMASKED_VENDOR_WEBGL)+ : gl.getParameter(gl.VENDOR);+ lines.push(`gl: ${vendor} | ${renderer}`);+ } else {+ lines.push("gl: NO WEBGL CONTEXT");+ }+ } catch (error) {+ lines.push(`gl: probe failed ${String(error)}`);+ }+ lines.push(+ await probeOneEncoder({+ ...base,+ label: "hw/canvas-frame",+ hardwareAcceleration: "prefer-hardware",+ frameSource: "canvas",+ }),+ );+ lines.push(+ await probeOneEncoder({+ ...base,+ label: "hw/cpu-rgba-frame",+ hardwareAcceleration: "prefer-hardware",+ frameSource: "cpu",+ }),+ );+ lines.push(+ await probeOneEncoder({+ ...base,+ label: "sw/canvas-frame",+ hardwareAcceleration: "prefer-software",+ frameSource: "canvas",+ }),+ );+ lines.push(+ await probeOneEncoder({+ ...base,+ label: "hw/canvas-frame@720p",+ hardwareAcceleration: "prefer-hardware",+ frameSource: "canvas",+ width: 1280,+ height: 720,+ }),+ );+ return lines.join("\n");+}+/** One clip's crop, in SOURCE-media time — the export renderer switches to* the covering entry's `cropRegion` before rendering each frame, so a crop* applies to its own clip only (see clipSchema.cropRegion), not the whole@@ -922,6 +1073,18 @@ export class VideoExporter {const segments = plan.segments;const firstSegment = segments[0];+ // Phase-0 perf harness: accumulate per-stage time to find the bottleneck.+ const timings = new StageTimings();+ const wallStart = performance.now();++ if (ENCODER_PROBE) {+ try {+ console.warn(await runEncoderThroughputProbe(this.config));+ } catch (error) {+ console.warn("[encoder probe] failed:", error);+ }+ }+// One renderer for the whole export — output size is fixed; only the// source-dependent fields change per segment via renderer.setSource().const renderer = new FrameRenderer({@@ -966,6 +1129,7 @@ export class VideoExporter {// up-front, so we know whether to declare an audio track on the muxer (mp4// needs that at construction). The concatenation TIMING is applied later,// once the video loop has produced each segment's real frame count.+ const stopAudioDecode = timings.start("audioDecode");const segmentAudioPcm: (Float32Array[] | null)[] = [];let anySegmentAudio = false;for (const segment of segments) {@@ -978,6 +1142,7 @@ export class VideoExporter {if (pcm && pcm.length > 0 && (pcm[0]?.length ?? 0) > 0) anySegmentAudio = true;segmentAudioPcm.push(pcm);}+ stopAudioDecode();const audioExportCodec = anySegmentAudio? await AudioProcessor.selectSupportedExportCodec(AUDIO_OUTPUT_SAMPLE_RATE,@@ -1014,6 +1179,48 @@ export class VideoExporter {// concatenated audio stays locked to the (independently retimed) video.const segmentFrameCounts: number[] = [];+ // The video loop spends ~90% of its wall time blocked in encodeWait, so+ // the CPU is mostly idle while frames sit in the encoder queue. The+ // per-segment WSOLA stretch is pure CPU work and depends ONLY on+ // segmentAudioPcm + the plan's speed regions + audio/frame-rate+ // constants — nothing that needs segmentFrameCounts. Kick it off here+ // so it overlaps the video loop, then await the result in the audio+ // phase instead of paying for it serially after.+ const stretchedPcmPromise: Promise<(Float32Array[] | null)[] | null> =+ hasAudio && audioExportCodec && !this.cancelled+ ? (async () => {+ const out: (Float32Array[] | null)[] = new Array(segmentAudioPcm.length).fill(null);+ for (let i = 0; i < segmentAudioPcm.length; i++) {+ if (this.cancelled) break;+ // stretchSegmentAudioBySpeed is synchronous — wrapping it in an+ // async IIFE doesn't yield by itself. Drop back to the event loop+ // between segments so the video loop's encodeWait can actually+ // interleave with our CPU work.+ await new Promise((r) => setTimeout(r, 0));+ // Retime each segment's audio PER speed sub-segment (pitch+ // preserved) so a partial speed region only speeds up its own+ // span, matching the video.+ const pcm = segmentAudioPcm[i];+ out[i] = pcm+ ? stretchSegmentAudioBySpeed(+ pcm,+ segments[i],+ projectRegionsToSegmentSource(plan.speedRegions, segments[i]),+ AUDIO_OUTPUT_SAMPLE_RATE,+ AUDIO_OUTPUT_CHANNELS,+ this.config.frameRate,+ )+ : null;+ }+ return out;+ })()+ : Promise.resolve(null);+ // Never let a rejection go unhandled if the export throws/cancels before the+ // await below reaches it; the await is the one that surfaces the failure.+ stretchedPcmPromise.catch(() => {+ // Swallowed here on purpose — see above.+ });+for (const segment of segments) {if (this.cancelled) break;if (this.fatalEncoderError) throw this.fatalEncoderError;@@ -1097,17 +1304,22 @@ export class VideoExporter {if (this.cancelled) return;if (this.fatalEncoderError) throw this.fatalEncoderError;+ const stopWebcam = timings.start("webcam");webcamFrame = webcamFrameQueue? await webcamFrameQueue.frameAt(sourceTimestampMs): null;+ stopWebcam();if (this.cancelled) return;// Encoder timestamp = contiguous OUTPUT time (seamless joins);// renderFrame gets SOURCE time so zoom/annotation/cursor match// the frame's content even when speed retimes the segment.const timestamp = frameIndex * frameDuration;+ const stopRender = timings.start("render");await renderer.renderFrame(videoFrame, sourceTimestampMs * 1000, webcamFrame);+ stopRender();+ const stopReadback = timings.start("readback");const canvas = renderer.getCanvas();let exportFrame: VideoFrame;if (platform === "linux") {@@ -1129,7 +1341,9 @@ export class VideoExporter {} else {exportFrame = new VideoFrame(canvas, { timestamp, duration: frameDuration });}+ stopReadback();+ const stopEncodeWait = timings.start("encodeWait");try {await waitForEncoderQueueSpace({getQueueSize: () => this.encoder?.encodeQueueSize ?? 0,@@ -1141,10 +1355,13 @@ export class VideoExporter {exportFrame.close();throw error;}+ stopEncodeWait();if (this.encoder && this.encoder.state === "configured") {this.encodeQueue++;+ const stopEncode = timings.start("encode");this.encoder.encode(exportFrame, { keyFrame: frameIndex % 150 === 0 });+ stopEncode();}exportFrame.close();@@ -1207,7 +1424,17 @@ export class VideoExporter {// --- Audio: concatenate every segment's decoded PCM at the plan's offsets// (sized from the REAL per-segment video frame counts so A/V stays locked),- // apply an equal-power fade at each join, then encode once and mux. ---+ // apply an equal-power fade at each join, then encode once and mux. The+ // stretch was kicked off before the video loop so it overlapped the+ // encodeWait idle time; the await below only measures the leftover+ // (typically ~0ms on a successful overlap). ---+ const stopAudioStretch = timings.start("audioStretch");+ // Non-null: same gate condition (hasAudio && audioExportCodec && !cancelled)+ // that produced a non-null promise also gates the if-block below.+ const stretchedPcm = (await stretchedPcmPromise)!;+ stopAudioStretch();++ const stopAudioEncode = timings.start("audioEncode");if (hasAudio && audioExportCodec && !this.cancelled) {const audioPlan = buildAudioConcatPlan(segments.map((s, i) => ({@@ -1222,20 +1449,6 @@ export class VideoExporter {channels: AUDIO_OUTPUT_CHANNELS,},);- // Retime each segment's audio PER speed sub-segment (pitch preserved) so- // a partial speed region only speeds up its own span, matching the video.- const stretchedPcm = segmentAudioPcm.map((pcm, i) =>- pcm- ? stretchSegmentAudioBySpeed(- pcm,- segments[i],- projectRegionsToSegmentSource(plan.speedRegions, segments[i]),- AUDIO_OUTPUT_SAMPLE_RATE,- AUDIO_OUTPUT_CHANNELS,- this.config.frameRate,- )- : null,- );const assembled = assembleConcatenatedPcm(stretchedPcm.map((pcm) => ({ pcm })),audioPlan,@@ -1250,6 +1463,14 @@ export class VideoExporter {);}+ stopAudioEncode();++ const wallMs = performance.now() - wallStart;+ console.warn(+ `[export perf] wall ${wallMs.toFixed(0)}ms · ${frameIndex} frames · ${(frameIndex / (wallMs / 1000)).toFixed(1)} fps\n` ++ timings.formatSummary({ frames: frameIndex, hardwareAcceleration: encoderPreference }),+ );+const blob = await muxer.finalize();return { success: true, blob, warnings: warnings.length > 0 ? warnings : undefined };}@@ -1411,9 +1632,10 @@ export class VideoExporter {}private getEncoderPreferences(): HardwareAcceleration[] {- if (typeof navigator !== "undefined" && /\bWindows\b/i.test(navigator.userAgent)) {- return ["prefer-software", "prefer-hardware"];- }+ // Hardware-first everywhere: the per-frame encode dominates export wall-time+ // (Phase-0: encodeWait ≈ 90%), and hardware H.264 cuts it substantially. The+ // export() retry loop falls back to prefer-software if the hardware attempt+ // throws, so this only trades up when the hardware encoder actually works.return ["prefer-hardware", "prefer-software"];}