Skip to content

The free and privacy-friendly screen recorder with no limits πŸŽ₯

Webcodecs recorder complete

Alyssa X6748c3a8dbbb
diff --git a/src/pages/Background/recording/restartRecording.js b/src/pages/Background/recording/restartRecording.js
index 317fcff..5692da1 100644
--- a/src/pages/Background/recording/restartRecording.js
+++ b/src/pages/Background/recording/restartRecording.js
@@ -1,13 +1,15 @@
import { sendMessageRecord } from "./sendMessageRecord";
-import { removeTab } from "../tabManagement";
import { resetActiveTabRestart } from "../tabManagement/resetActiveTab";
export const handleRestart = async () => {
chrome.storage.local.set({ restarting: true });
+ sendMessageRecord({ type: "restart-recording-tab" });
+
resetActiveTabRestart();
};
export const handleRestartRecordingTab = async (request) => {
- sendMessageRecord({ type: "restart-recording-tab" });
+ handleRestart();
+ //sendMessageRecord({ type: "restart-recording-tab" });
};
diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsx
index ace38f0..b974d2c 100644
--- a/src/pages/Recorder/Recorder.jsx
+++ b/src/pages/Recorder/Recorder.jsx
@@ -67,6 +67,10 @@ const Recorder = () => {
const MAX_PENDING_BYTES = 8 * 1024 * 1024;
const pendingBytes = useRef(0);
+ const uiClosing = useRef(false);
+
+ const isRecording = useRef(false);
+
async function canFitChunk(byteLength) {
const now = performance.now();
if (now - lastEstimateAt.current < ESTIMATE_INTERVAL_MS) {
@@ -241,6 +245,7 @@ const Recorder = () => {
restarting: false,
});
+ isRecording.current = true;
isRestarting.current = false;
index.current = 0;
@@ -525,6 +530,7 @@ const Recorder = () => {
return;
}
isFinishing.current = true;
+ isRecording.current = false;
try {
if (
@@ -545,38 +551,78 @@ const Recorder = () => {
await waitForDrain();
recorder.current = null;
- if (liveStream.current) {
- liveStream.current.getTracks().forEach((t) => t.stop());
- liveStream.current = null;
- }
+ // ❗ Only fully release tracks if the user is NOT restarting
+ if (!isRestarting.current) {
+ console.log("[RECORDER] stopRecording(): fully stopping all tracks");
+ liveStream.current?.getTracks().forEach((t) => t.stop());
+ helperVideoStream.current?.getTracks().forEach((t) => t.stop());
+ helperAudioStream.current?.getTracks().forEach((t) => t.stop());
- if (helperVideoStream.current) {
- helperVideoStream.current.getTracks().forEach((t) => t.stop());
+ liveStream.current = null;
helperVideoStream.current = null;
- }
-
- if (helperAudioStream.current) {
- helperAudioStream.current.getTracks().forEach((t) => t.stop());
helperAudioStream.current = null;
+ } else {
+ console.log("[RECORDER] stopRecording(): preserving streams for restart");
}
}
- const dismissRecording = async () => {
- isRestarting.current = true;
- if (recorder.current !== null) {
- recorder.current.stop();
- recorder.current = null;
- }
+ const dismissRecording = () => {
+ uiClosing.current = true;
+ isRecording.current = false;
window.close();
};
const restartRecording = async () => {
+ if (isRestarting.current) {
+ console.warn("[RECORDER] duplicate restart ignored");
+ return;
+ }
+ console.log("[RECORDER] restartRecording()");
+
isRestarting.current = true;
- if (recorder.current !== null) {
- recorder.current.stop();
+ isRecording.current = false;
+ sentLast.current = false;
+ isFinishing.current = false;
+
+ // Stop encoders, but keep tracks alive
+ try {
+ if (
+ useWebCodecs.current &&
+ recorder.current instanceof WebCodecsRecorder
+ ) {
+ recorder.current.running = false;
+ recorder.current.paused = false;
+ await recorder.current.cleanup();
+ } else if (recorder.current instanceof MediaRecorder) {
+ recorder.current.ondataavailable = null;
+ recorder.current.onstop = null;
+ recorder.current.onerror = null;
+ if (recorder.current.state !== "inactive") recorder.current.stop();
+ }
+ } catch (err) {
+ console.warn("[RECORDER] restart stop error", err);
}
+
recorder.current = null;
- chrome.runtime.sendMessage({ type: "reset-active-tab-restart" });
+
+ // Reset chunks + timestamps
+ pending.current = [];
+ pendingBytes.current = 0;
+ draining.current = false;
+ hasChunks.current = false;
+ savedCount.current = 0;
+ lastSize.current = 0;
+ lastTimecode.current = 0;
+ await chunksStore.clear();
+
+ // ❌ DO NOT start recording here
+ // UI will decide when to start
+ console.log("[RECORDER] ready for restart β€” waiting for startRecording()");
+
+ // Ensure next start uses WebCodecs cleanly
+ useWebCodecs.current = false;
+
+ isRestarting.current = false;
};
async function startAudioStream(id) {
@@ -779,6 +825,17 @@ const Recorder = () => {
// Add the tracks to the stream
liveStream.current.addTrack(helperVideoStream.current.getVideoTracks()[0]);
+
+ const mainVideoTrack = liveStream.current?.getVideoTracks()[0];
+ if (mainVideoTrack) {
+ mainVideoTrack.onmute = () => {
+ console.warn("[RECORDER] video track muted β€” possible display sleep");
+ };
+ mainVideoTrack.oninactive = () => {
+ console.warn("[RECORDER] video track inactive β€” auto-stop");
+ stopRecording();
+ };
+ }
if (
(helperAudioStream.current != null &&
helperAudioStream.current.getAudioTracks().length > 0) ||
@@ -858,17 +915,22 @@ const Recorder = () => {
// FLAG: add protection on page close
useEffect(() => {
- const handleClose = () => {
- try {
- stopRecording();
- } catch {}
+ const handleClose = (e) => {
+ // OK to close if:
+ if (uiClosing.current || !isRecording.current) return;
+
+ console.warn("[RECORDER] Prevented accidental tab close!");
+
+ // Stop everything immediately but prevent loss
+ stopRecording();
+
+ // Show native "are you sure?" dialog to prevent closing
+ e.preventDefault();
+ e.returnValue = "";
};
- window.addEventListener("pagehide", handleClose);
window.addEventListener("beforeunload", handleClose);
-
return () => {
- window.removeEventListener("pagehide", handleClose);
window.removeEventListener("beforeunload", handleClose);
};
}, []);
@@ -892,7 +954,11 @@ const Recorder = () => {
} else if (request.type === "start-recording-tab") {
startRecording();
} else if (request.type === "restart-recording-tab") {
- restartRecording();
+ if (!isRestarting.current) {
+ restartRecording();
+ } else {
+ console.warn("[RECORDER] ignoring duplicate restart request");
+ }
} else if (request.type === "stop-recording-tab") {
stopRecording();
} else if (request.type === "set-mic-active-tab") {
diff --git a/src/pages/Recorder/audioManager.js b/src/pages/Recorder/audioManager.js
deleted file mode 100644
index 5dd137f..0000000
--- a/src/pages/Recorder/audioManager.js
+++ /dev/null
@@ -1,101 +0,0 @@
-// Audio management for screen recording
-export class AudioManager {
- constructor() {
- this.aCtx = null;
- this.destination = null;
- this.audioInputSource = null;
- this.audioOutputSource = null;
- this.audioInputGain = null;
- this.audioOutputGain = null;
- this.helperAudioStream = null;
- }
-
- async initialize() {
- this.aCtx = new AudioContext();
- this.destination = this.aCtx.createMediaStreamDestination();
- return this.destination;
- }
-
- async startAudioStream(id) {
- const audioStreamOptions = {
- mimeType: "video/webm;codecs=vp8,opus",
- audio: {
- deviceId: {
- exact: id,
- },
- },
- };
-
- try {
- const stream = await navigator.mediaDevices.getUserMedia(
- audioStreamOptions
- );
- return stream;
- } catch (err) {
- // Try again without the device ID
- const fallbackOptions = {
- mimeType: "video/webm;codecs=vp8,opus",
- audio: true,
- };
-
- try {
- return await navigator.mediaDevices.getUserMedia(fallbackOptions);
- } catch (err) {
- return null;
- }
- }
- }
-
- setupAudioNodes(micStream, videoStream) {
- // Set up microphone audio if available
- if (micStream && micStream.getAudioTracks().length > 0) {
- this.helperAudioStream = micStream;
- this.audioInputGain = this.aCtx.createGain();
- this.audioInputSource = this.aCtx.createMediaStreamSource(micStream);
- this.audioInputSource
- .connect(this.audioInputGain)
- .connect(this.destination);
- }
-
- // Set up system audio if available
- if (videoStream && videoStream.getAudioTracks().length > 0) {
- this.audioOutputGain = this.aCtx.createGain();
- this.audioOutputSource = this.aCtx.createMediaStreamSource(videoStream);
- this.audioOutputSource
- .connect(this.audioOutputGain)
- .connect(this.destination);
- }
-
- return this.destination.stream;
- }
-
- setInputVolume(volume) {
- if (this.audioInputGain) {
- this.audioInputGain.gain.value = volume;
- }
- }
-
- setOutputVolume(volume) {
- if (this.audioOutputGain) {
- this.audioOutputGain.gain.value = volume;
- }
- }
-
- cleanup() {
- if (this.helperAudioStream) {
- this.helperAudioStream.getTracks().forEach((track) => track.stop());
- this.helperAudioStream = null;
- }
-
- if (this.aCtx) {
- this.aCtx.close();
- this.aCtx = null;
- }
-
- this.destination = null;
- this.audioInputSource = null;
- this.audioOutputSource = null;
- this.audioInputGain = null;
- this.audioOutputGain = null;
- }
-}
diff --git a/src/pages/Recorder/useUnifiedRecorder.js b/src/pages/Recorder/useUnifiedRecorder.js
new file mode 100644
index 0000000..b3f5401
--- /dev/null
+++ b/src/pages/Recorder/useUnifiedRecorder.js
@@ -0,0 +1,305 @@
+/*!
+ * Screenity Unified Recorder Backend (WebCodecs + Fallback)
+ * Copyright (c) 2025 Serial Labs Ltd.
+ *
+ * This file is part of Screenity and is licensed under the GNU GPLv3.
+ * See the LICENSE file in the project root for details.
+ *
+ * This module unifies recorder logic for:
+ * - Main recorder (popup/panel)
+ * - Region recorder (iframe capture)
+ * - Tab capture and full desktop capture
+ *
+ * WebCodecs primary path:
+ * - Better quality
+ * - Lower latency + faster finalization
+ * - Avoids huge memory spikes during long recordings
+ *
+ * If reused outside Screenity, GPLv3 obligations apply.
+ */
+
+// Imports shared through your monorepo structure
+import localforage from "localforage";
+import { WebCodecsRecorder } from "./webcodecs/WebCodecsRecorder";
+import { sendRecordingError, sendStopRecording } from "../messaging";
+import { getBitrates } from "../recorderConfig";
+import { getResolutionForQuality } from "../recorderConfig";
+
+// === Persistent storage for chunks (indexedDB) ===
+const chunksStore = localforage.createInstance({
+ name: "chunks",
+});
+
+// === Constants ===
+const ESTIMATE_INTERVAL_MS = 5000;
+const MIN_HEADROOM = 25 * 1024 * 1024; // ~25MB
+const MAX_PENDING_BYTES = 8 * 1024 * 1024;
+
+// === Unified Recorder Factory ===
+export function useUnifiedRecorder() {
+ const recorderRef = {
+ recorder: null,
+ useWebCodecs: false,
+ running: false,
+ finishing: false,
+ restarting: false,
+ savedCount: 0,
+ index: 0,
+ pendingBytes: 0,
+ pendingQueue: [],
+ draining: false,
+ lastEstimateAt: 0,
+ lowStorageAbort: false,
+ };
+
+ const estimateStorage = async (size = 0) => {
+ const now = performance.now();
+ if (now - recorderRef.lastEstimateAt < ESTIMATE_INTERVAL_MS) {
+ return !recorderRef.lowStorageAbort;
+ }
+ recorderRef.lastEstimateAt = now;
+
+ try {
+ const { usage = 0, quota = 0 } = await navigator.storage.estimate();
+ const remaining = quota - usage;
+ return remaining > MIN_HEADROOM + size;
+ } catch {
+ return !recorderRef.lowStorageAbort;
+ }
+ };
+
+ const saveChunkDirect = async (blob, ts) => {
+ try {
+ await chunksStore.setItem(`chunk_${recorderRef.index}`, {
+ index: recorderRef.index,
+ chunk: blob,
+ timestamp: ts,
+ });
+ recorderRef.index++;
+ recorderRef.savedCount++;
+ return true;
+ } catch (err) {
+ console.error("[UnifiedRecorder] saveChunkDirect failed", err);
+ return false;
+ }
+ };
+
+ const handleChunk = async (blob, timestampMs) => {
+ const allowed = await estimateStorage(blob.size);
+ if (!allowed) {
+ abortForLowStorage();
+ return;
+ }
+ await saveChunkDirect(blob, timestampMs ?? 0);
+ };
+
+ function abortForLowStorage() {
+ recorderRef.lowStorageAbort = true;
+ chrome.storage.local.set({
+ recording: false,
+ restarting: false,
+ memoryError: true,
+ });
+ chrome.runtime.sendMessage({ type: "stop-recording-tab" });
+ }
+
+ async function warmUpStream(liveStream) {
+ const videoTrack = liveStream.getVideoTracks()[0];
+ const audioTrack = liveStream.getAudioTracks()[0];
+
+ if (!videoTrack) throw new Error("No video track present for warm-up");
+
+ // ensure at least one real frame exists
+ await new Promise(async (resolve) => {
+ const proc = new MediaStreamTrackProcessor({ track: videoTrack });
+ const reader = proc.readable.getReader();
+
+ while (true) {
+ const { value: frame } = await reader.read();
+ if (frame && frame.codedWidth > 0) {
+ frame.close();
+ reader.releaseLock();
+ resolve();
+ break;
+ }
+ frame?.close();
+ }
+ });
+
+ if (audioTrack) {
+ await new Promise(async (resolve) => {
+ const proc = new MediaStreamTrackProcessor({ track: audioTrack });
+ const reader = proc.readable.getReader();
+
+ while (true) {
+ const { value: audio } = await reader.read();
+ if (audio && audio.numberOfFrames > 0) {
+ audio.close?.();
+ reader.releaseLock();
+ resolve();
+ break;
+ }
+ audio?.close?.();
+ }
+ });
+ }
+
+ console.log("[UnifiedRecorder] warm-up complete");
+ }
+
+ async function start(liveStream) {
+ if (!liveStream || recorderRef.running) return false;
+
+ recorderRef.running = true;
+ recorderRef.restart = false;
+ recorderRef.index = 0;
+ recorderRef.savedCount = 0;
+ recorderRef.pendingBytes = 0;
+
+ await chunksStore.clear();
+
+ const { qualityValue } = await chrome.storage.local.get(["qualityValue"]);
+ const { audioBitsPerSecond, videoBitsPerSecond } =
+ getBitrates(qualityValue);
+
+ const vidTrack = liveStream.getVideoTracks()[0];
+ if (!vidTrack) {
+ sendRecordingError("No video track");
+ return false;
+ }
+
+ const settings = vidTrack.getSettings();
+ const width = settings.width ?? 1920;
+ const height = settings.height ?? 1080;
+
+ const { fpsValue } = await chrome.storage.local.get(["fpsValue"]);
+ let fps = parseInt(fpsValue);
+ if (Number.isNaN(fps)) fps = 30;
+
+ const useWC =
+ typeof VideoEncoder !== "undefined" &&
+ typeof AudioEncoder !== "undefined" &&
+ typeof MediaStreamTrackProcessor !== "undefined";
+
+ // Warm up tracks β€” ensures first frames exist
+ await warmUpStream(liveStream);
+
+ if (useWC) {
+ recorderRef.useWebCodecs = true;
+ recorderRef.recorder = new WebCodecsRecorder(liveStream, {
+ width,
+ height,
+ fps,
+ videoBitrate: videoBitsPerSecond,
+ audioBitrate: audioBitsPerSecond,
+ onChunk: async (chunk, timestampUs) => {
+ const ts = timestampUs ? Math.floor(timestampUs / 1000) : 0;
+ const blob = new Blob([chunk], { type: "video/mp4" });
+ await handleChunk(blob, ts);
+ },
+ onFinalized: () => {
+ chrome.runtime.sendMessage({ type: "video-ready" });
+ },
+ onError: (err) => {
+ console.error("[UnifiedRecorder][WC] error", err);
+ sendRecordingError(String(err));
+ },
+ });
+
+ const ok = await recorderRef.recorder.start();
+ if (!ok) {
+ console.warn("[UnifiedRecorder] WC failed β€” fallback");
+ recorderRef.useWebCodecs = false;
+ recorderRef.recorder = null;
+ return await start(liveStream);
+ }
+ } else {
+ recorderRef.useWebCodecs = false;
+ const mime = "video/webm;codecs=vp8,opus";
+ const mr = new MediaRecorder(liveStream, {
+ mimeType: mime,
+ audioBitsPerSecond,
+ videoBitsPerSecond,
+ });
+
+ mr.ondataavailable = async (e) => {
+ if (!e.data || !e.data.size) return;
+ await handleChunk(e.data, e.timecode ?? 0);
+ };
+
+ mr.onerror = (ev) => {
+ sendRecordingError("MediaRecorder error");
+ };
+
+ mr.onstop = async () => {
+ chrome.runtime.sendMessage({ type: "video-ready" });
+ };
+
+ recorderRef.recorder = mr;
+ mr.start(1000);
+ }
+
+ chrome.storage.local.set({ recording: true, restarting: false });
+ return true;
+ }
+
+ async function stop(preserveStreams = false) {
+ if (!recorderRef.running) return;
+ recorderRef.running = false;
+
+ try {
+ if (recorderRef.useWebCodecs) {
+ await recorderRef.recorder.stop();
+ } else {
+ recorderRef.recorder.stop();
+ }
+ } catch {}
+
+ recorderRef.recorder = null;
+ chrome.storage.local.set({ recording: false });
+ if (!preserveStreams) {
+ sendStopRecording();
+ }
+ }
+
+ function pause() {
+ if (!recorderRef.running) return;
+ try {
+ recorderRef.recorder.pause();
+ } catch {}
+ }
+
+ function resume() {
+ if (!recorderRef.running) return;
+ try {
+ recorderRef.recorder.resume();
+ } catch {}
+ }
+
+ async function restart() {
+ recorderRef.restarting = true;
+ recorderRef.running = false;
+ recorderRef.finishing = false;
+
+ if (recorderRef.useWebCodecs) {
+ await recorderRef.recorder.cleanup();
+ } else {
+ try {
+ recorderRef.recorder.stop();
+ } catch {}
+ }
+
+ recorderRef.recorder = null;
+ recorderRef.useWebCodecs = false;
+
+ await chunksStore.clear();
+ recorderRef.index = 0;
+ recorderRef.savedCount = 0;
+ recorderRef.pendingQueue = [];
+ recorderRef.pendingBytes = 0;
+ recorderRef.restarting = false;
+ chrome.storage.local.set({ restarting: false });
+ }
+
+ return { start, stop, pause, resume, restart };
+}
diff --git a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
index 133e268..036124d 100644
--- a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
+++ b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
@@ -1,4 +1,15 @@
-// webcodecs/Mp4MuxerWrapper.ts
+/*!
+ * Screenity WebCodecs Recorder
+ * Copyright (c) 2025 Serial Labs Ltd.
+ *
+ * This file is part of Screenity and is licensed under the GNU GPLv3.
+ * See the LICENSE file in the project root for details.
+ *
+ * This module implements complex WebCodecs-based recording logic
+ * for video/audio sync, muxing, and safe timestamp management.
+ * If you reuse or modify this file in another project, GPLv3
+ * obligations (including copyleft and attribution) apply.
+ */
// @ts-nocheck
import {
@@ -221,17 +232,21 @@ private normalizeSampleTimestamp(
// Fallback when encoder doesn’t give timestamps
if (typeof timestampUs !== "number") {
- const next = (this as any)[lastKey] + durationUs || durationUs;
- (this as any)[lastKey] = next;
- return next;
+ const prev = (this as any)[lastKey] ?? 0;
+ const next = prev + durationUs;
+ (this as any)[lastKey] = next;
+ return next;
}
let baseOffset = (this as any)[offsetKey] as number | null;
// If we explicitly set an audio offset, prefer that
- if (kind === "audio" && this.audioTimestampOffsetUs != null) {
- baseOffset = this.audioTimestampOffsetUs;
- } else if (baseOffset == null) {
+ if (kind === "audio") {
+ if (this.audioTimestampOffsetUs == null) {
+ this.audioTimestampOffsetUs = timestampUs;
+ }
+ baseOffset = this.audioTimestampOffsetUs;
+ } else if (baseOffset == null) {
// First sample for this track: establish base offset
baseOffset = timestampUs;
(this as any)[offsetKey] = baseOffset;
diff --git a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
index e47c9b9..b6e129c 100644
--- a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
+++ b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
@@ -1,4 +1,15 @@
-// extension/webcodecs/WebCodecsRecorder.js
+/*!
+ * Screenity WebCodecs Recorder
+ * Copyright (c) 2025 Serial Labs Ltd.
+ *
+ * This file is part of Screenity and is licensed under the GNU GPLv3.
+ * See the LICENSE file in the project root for details.
+ *
+ * This module implements complex WebCodecs-based recording logic
+ * for video/audio sync, muxing, and safe timestamp management.
+ * If you reuse or modify this file in another project, GPLv3
+ * obligations (including copyleft and attribution) apply.
+ */
import { Mp4MuxerWrapper } from "./Mp4MuxerWrapper";
export class WebCodecsRecorder {
@@ -157,9 +168,17 @@ export class WebCodecsRecorder {
const audioConfig = await this.prepareAudioEncoderConfig();
this._pendingAudioConfig = audioConfig;
- console.log("[WCR] Video config chosen:", videoConfig);
console.log("[WCR] Audio config:", audioConfig);
+ if (!audioConfig) {
+ console.warn(
+ "[WCR] No audio track available β€” disabling audio in muxer"
+ );
+ this.options.audioBitrate = undefined;
+ this.options.enableAudio = false;
+ this._audioReady = false;
+ }
+
console.log("[WCR] creating MediaStreamTrackProcessors...");
this.videoProcessor = new MediaStreamTrackProcessor({
track: this.videoTrack,
@@ -177,10 +196,9 @@ export class WebCodecsRecorder {
this.audioReader = null;
}
- // --- START AUDIO LOOP IMMEDIATELY (BEFORE VIDEO) ---
- if (this.audioReader) {
+ if (this.audioReader && this.options.enableAudio) {
console.log("[WCR] starting early audio buffering loop");
- this.readAudioLoop(); // <-- THIS IS NOW CORRECTLY PLACED
+ this.readAudioLoop();
}
console.log("[WCR] creating muxer...");
@@ -191,12 +209,12 @@ export class WebCodecsRecorder {
videoBitrate: this.options.videoBitrate,
audioBitrate: this.options.audioBitrate,
videoCodec: videoConfig.containerCodec,
- audioCodec: audioConfig ? "aac" : undefined,
+ audioCodec: this.options.enableAudio ? "aac" : undefined,
onChunk: this.options.onChunk,
});
console.log("[WCR] muxer created");
- if (audioConfig) {
+ if (this.options.enableAudio) {
this.muxer.enableAudio();
}
@@ -328,12 +346,10 @@ export class WebCodecsRecorder {
this.audioEncoder?.close();
} catch {}
- try {
- this.videoTrack?.stop();
- } catch {}
- try {
- this.audioTrack?.stop();
- } catch {}
+ // ❌ DO NOT stop the shared capture tracks here.
+ // The owner (Recorder) decides when to stop/release them.
+ // try { this.videoTrack?.stop(); } catch {}
+ // try { this.audioTrack?.stop(); } catch {}
this.videoProcessor = null;
this.audioProcessor = null;
@@ -341,6 +357,10 @@ export class WebCodecsRecorder {
this.audioReader = null;
this.videoEncoder = null;
this.audioEncoder = null;
+
+ this.videoTrack = null;
+ this.audioTrack = null;
+
this.videoTimestampOffsetUs = null;
this.videoFallbackStartMs = null;
this.firstVideoFrame = undefined;
@@ -510,6 +530,16 @@ export class WebCodecsRecorder {
// Fallback for browsers without timestamps
const now = performance.now();
+ if (!this._lastFrameTime) this._lastFrameTime = now;
+ const delta = now - this._lastFrameTime;
+ this._lastFrameTime = now;
+
+ // If encoder falls behind (e.g. >150ms per frame, ~7 FPS)
+ if (delta > 160 && !this._warnedBackpressure) {
+ this._warnedBackpressure = true;
+ console.warn("[WCR] encoding overload detected:", delta, "ms/frame");
+ this.options.onError?.({ type: "encoder-overload", delta });
+ }
if (this.videoFallbackStartMs === null) {
this.videoFallbackStartMs = now;
}
@@ -555,7 +585,18 @@ export class WebCodecsRecorder {
const { value: frame, done } = await this.videoReader
.read()
.catch(() => ({ done: true }));
- if (done || !frame) break;
+
+ if (done) {
+ console.warn("[WCR] video track ended β€” stopping");
+ this.options.onError?.({ type: "video-ended" });
+ break;
+ }
+ if (!frame) break;
+
+ if (frame.codedWidth === 0 || frame.codedHeight === 0) {
+ console.warn("[WCR] zero-size video frame β€” possible track loss");
+ this.options.onError?.({ type: "video-lost" });
+ }
ensureResizeCanvas();
@@ -643,6 +684,12 @@ export class WebCodecsRecorder {
break;
}
+ if (!this.audioTrack || this.audioTrack.readyState === "ended") {
+ console.warn("[WCR] audio track ended β€” mic lost");
+ this.options.onError?.({ type: "audio-lost" });
+ break;
+ }
+
if (!this._audioReady) {
// buffer raw audio frames until video baseline is known
this._prebufferedAudio.push(audioData);