Skip to content

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

Fix WebCodecs finalize issues and improve recording reliability

Alyssa X284b43a26844
diff --git a/src/manifest.json b/src/manifest.json
index f5639fe..adbe0fe 100755
--- a/src/manifest.json
+++ b/src/manifest.json
@@ -3,7 +3,7 @@
"name": "__MSG_extName__",
"description": "__MSG_extDesc__",
"default_locale": "en",
- "version": "4.3.7",
+ "version": "4.3.8",
"background": {
"service_worker": "background.bundle.js"
},
diff --git a/src/pages/Background/index.js b/src/pages/Background/index.js
index 4567b69..c01f990 100644
--- a/src/pages/Background/index.js
+++ b/src/pages/Background/index.js
@@ -79,6 +79,43 @@ setupHandlers();
// can dispatch any queued events to this worker.
clearStaleLocks();
+// One-time migration for users upgrading from 4.3.7. The finalize-hang bug on
+// abrupt stream end caused sticky-disable to fire for many WebCodecs users;
+// the underlying cause is fixed in this release (fragmented MP4 + streaming),
+// so the sticky flags are no longer warranted and should be cleared once so
+// affected users get WebCodecs again on their next recording. The user's
+// explicit opt-out (useWebCodecsRecorder === false) is preserved.
+const CURRENT_MIGRATION_VERSION = "4.3.8";
+const runUpgradeMigrations = async () => {
+ try {
+ const { screenityMigratedForVersion } = await chrome.storage.local.get([
+ "screenityMigratedForVersion",
+ ]);
+ if (screenityMigratedForVersion === CURRENT_MIGRATION_VERSION) return;
+
+ await chrome.storage.local.remove([
+ "fastRecorderDisabledForDevice",
+ "fastRecorderDisabledReason",
+ "fastRecorderDisabledAt",
+ "fastRecorderDisabledDetails",
+ "fastRecorderValidationFailed",
+ "fastRecorderValidation",
+ "lastWebCodecsFailureAt",
+ "lastWebCodecsFailureCode",
+ "lastFailedValidation",
+ ]);
+ await chrome.storage.local.set({
+ screenityMigratedForVersion: CURRENT_MIGRATION_VERSION,
+ });
+ console.info(
+ "[Screenity][BG] Cleared stale 4.3.7 sticky-disable flags on upgrade",
+ );
+ } catch (err) {
+ console.error("[Screenity][BG] Upgrade migration failed:", err);
+ }
+};
+runUpgradeMigrations();
+
// Hydrate the diagnostic log from storage and record that the SW (re)started.
hydrateDiagnosticLog().then(() => {
diagEvent("sw-init", { ts: Date.now() });
diff --git a/src/pages/Background/listeners/onTabUpdatedListener.js b/src/pages/Background/listeners/onTabUpdatedListener.js
index 8cabf29..fd93ab2 100644
--- a/src/pages/Background/listeners/onTabUpdatedListener.js
+++ b/src/pages/Background/listeners/onTabUpdatedListener.js
@@ -1,73 +1,8 @@
import { sendMessageTab } from "../tabManagement";
import { diagEvent } from "../../utils/diagnosticLog";
-import { videoReady } from "../recording/recordingHelpers";
-import { chunksStore } from "../recording/chunkHandler";
export const handleTabUpdate = async (tabId, changeInfo, tab) => {
try {
- // React to URL changes EARLY (fires at navigation start, before the new
- // page loads) so we can clear recording state before the new content
- // script re-injects the region UI.
- if (changeInfo.url) {
- const {
- recording,
- tabRecordedID,
- recorderSession,
- customRegion,
- recordingType,
- restarting,
- } = await chrome.storage.local.get([
- "recording",
- "tabRecordedID",
- "recorderSession",
- "customRegion",
- "recordingType",
- "restarting",
- ]);
-
- const isActivelyRecording =
- recording ||
- (recorderSession && recorderSession.status === "recording");
- const isRegionRecording = customRegion || recordingType === "region";
-
- if (
- !restarting &&
- isActivelyRecording &&
- isRegionRecording &&
- tabRecordedID &&
- tabRecordedID === tabId
- ) {
- diagEvent("region-nav-stop", { tabId });
- // Clear ALL recording state IMMEDIATELY so the new page's content
- // script won't see an active recording, and so the status=complete
- // handler won't send a recording-check that re-enables the UI.
- // Also clear recordingTab so stopRecording() opens the editor
- // instead of thinking it was already handled.
- await chrome.storage.local.set({
- recording: false,
- customRegion: false,
- recordingTab: null,
- postStopEditorOpening: false,
- postStopEditorOpened: false,
- recorderSession: recorderSession
- ? { ...recorderSession, status: "stopped" }
- : null,
- });
- const chunkCount = await chunksStore.length().catch(() => 0);
- if (chunkCount === 0) {
- diagEvent("region-nav-no-chunks");
- sendMessageTab(tabId, {
- type: "show-toast",
- message: chrome.i18n.getMessage("recordingTooShortToast"),
- timeout: 5000,
- }).catch(() => {});
- return;
- }
- await videoReady();
- return; // Skip the status=complete handler for this event
- }
- }
-
if (changeInfo.status === "complete") {
const {
recording,
@@ -107,8 +42,6 @@ export const handleTabUpdate = async (tabId, changeInfo, tab) => {
} else if (isActivelyRecording) {
if (tabRecordedID && tabRecordedID === tabId) {
diagEvent("recorded-tab-navigated");
-
- // For non-region recordings, send a check to the content script
sendMessageTab(tabId, {
type: "recording-check",
force: true,
diff --git a/src/pages/Background/messaging/handlers.js b/src/pages/Background/messaging/handlers.js
index 2e60d36..1892b12 100644
--- a/src/pages/Background/messaging/handlers.js
+++ b/src/pages/Background/messaging/handlers.js
@@ -805,18 +805,21 @@ export const setupHandlers = () => {
// Fired by Region/Recorder.jsx pagehide β€” the iframe is being torn down
// because the user navigated away from the recorded tab.
registerMessage("region-iframe-destroyed", async () => {
- const { recording, recorderSession, customRegion, recordingType } =
+ const { recording, recorderSession, customRegion } =
await chrome.storage.local.get([
"recording",
"recorderSession",
"customRegion",
- "recordingType",
]);
const isActivelyRecording =
recording ||
(recorderSession && recorderSession.status === "recording");
- const isRegionRecording = customRegion || recordingType === "region";
- if (!isActivelyRecording || !isRegionRecording) return;
+ if (!isActivelyRecording) return;
+ // Only treat as a real region-recording teardown when the iframe was
+ // actually hosting the MediaRecorder (customRegion flow). Plain
+ // tab-area records in the pinned recorder tab, so navigation of the
+ // recorded page must not tear it down.
+ if (!customRegion) return;
diagEvent("region-iframe-destroyed");
await chrome.storage.local.set({
diff --git a/src/pages/Content/context/messaging/handlers.js b/src/pages/Content/context/messaging/handlers.js
index efe4c1f..2e93069 100644
--- a/src/pages/Content/context/messaging/handlers.js
+++ b/src/pages/Content/context/messaging/handlers.js
@@ -661,6 +661,7 @@ export const setupHandlers = () => {
...prev,
showPopup: false,
showExtension: false,
+ recording: false,
}));
});
diff --git a/src/pages/Content/context/utils/checkRecording.js b/src/pages/Content/context/utils/checkRecording.js
index c2ce104..4e6b6eb 100644
--- a/src/pages/Content/context/utils/checkRecording.js
+++ b/src/pages/Content/context/utils/checkRecording.js
@@ -1,19 +1,6 @@
-import { setContentState } from "../ContentState";
-
-export const checkRecording = async (id) => {
- const { recording } = await chrome.storage.local.get("recording");
- const { tabRecordedID } = await chrome.storage.local.get("tabRecordedID");
- if (id == null && tabRecordedID) {
- setContentState((prevContentState) => ({
- ...prevContentState,
- recording: false,
- }));
- } else if (recording && tabRecordedID) {
- if (id != tabRecordedID) {
- setContentState((prevContentState) => ({
- ...prevContentState,
- recording: false,
- }));
- }
- }
-};
+// Intentionally a no-op. Local recording state is managed by the background
+// via explicit messages (`recording-check force:true` on the recorded tab,
+// `hide-popup-recording` on other tabs). An earlier version of this function
+// force-cleared local `recording` whenever `tabRecordedID` was set, which
+// clobbered `recording-check` after a same-tab navigation.
+export const checkRecording = async () => {};
diff --git a/src/pages/Recorder/Recorder.jsx b/src/pages/Recorder/Recorder.jsx
index a7aca21..382f9af 100644
--- a/src/pages/Recorder/Recorder.jsx
+++ b/src/pages/Recorder/Recorder.jsx
@@ -953,7 +953,7 @@ const Recorder = () => {
const { useWebCodecsRecorder } = await chrome.storage.local.get([
"useWebCodecsRecorder",
]);
- // Default-on as of 4.3.7: treat undefined as enabled; only explicit `false` opts out.
+ // Default-on: treat undefined as enabled; only explicit `false` opts out.
const userSetting = useWebCodecsRecorder === false ? false : true;
const stickyState = await getFastRecorderStickyState();
const probeResult = await probeFastRecorderSupport();
@@ -1061,64 +1061,72 @@ const Recorder = () => {
return;
}
if (useWebCodecs.current) {
+ if (lowStorageAbort.current) return;
+
+ // Fragmented MP4 + StreamTarget: chunks stream in throughout the
+ // recording as the muxer writes fragments (~1MB each, coalesced
+ // upstream). Each chunk is already file-byte-order; concatenating
+ // them reconstructs a valid fMP4, which plays directly in <video>
+ // and is re-muxed to standard MP4 at download time.
const blob =
data instanceof Blob ? data : new Blob([data], { type: "video/mp4" });
const ts = timestampMs ?? 0;
- // The WebCodecs Mp4 muxer emits the ENTIRE MP4 as a single chunk at
- // finalize(). For long recordings that can be 50+ MB. Two problems if
- // we store it as one IDB entry:
- // 1. chrome.runtime.sendMessage (used to relay chunks base64-encoded
- // to the sandbox) has a ~64MB serialization limit. base64 adds
- // 33% overhead, so a 50MB raw chunk becomes ~67MB base64 β†’ fails.
- // 2. Encoding a huge blob to base64 via FileReader in the SW is
- // slow and memory-heavy.
- // Split into smaller slices at IDB write time. Downstream paths
- // (rebuildBlobFromChunks + BG sendChunks + sandbox handleBatch)
- // all concatenate parts, so slicing is transparent to them.
- const SLICE_SIZE = 2 * 1024 * 1024;
+ // Pre-flight the IDB write: if the device is running out of storage
+ // quota, abort cleanly so the user gets a toast + the already-saved
+ // fragments are preserved. Without this, setItem would throw
+ // QuotaExceededError mid-recording and the fragments after that point
+ // would silently vanish.
+ if (!(await canFitChunk(blob.size))) {
+ if (!lowStorageAbort.current) {
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("toastStorageCritical"),
+ timeout: 8000,
+ });
+ }
+ lowStorageAbort.current = true;
+ chrome.storage.local.set({
+ recording: false,
+ restarting: false,
+ tabRecordedID: null,
+ memoryError: true,
+ lowStorageAbortAt: Date.now(),
+ lowStorageAbortChunks: index.current,
+ });
+ requestStop("low-storage", {
+ memoryError: true,
+ savedChunks: savedCount.current,
+ });
+ return;
+ }
try {
- let offset = 0;
- let isFirstSlice = true;
- while (offset < blob.size || (offset === 0 && blob.size === 0)) {
- const i = index.current;
- const end = Math.min(offset + SLICE_SIZE, blob.size);
- const slice =
- blob.size <= SLICE_SIZE && offset === 0
- ? blob
- : blob.slice(offset, end, blob.type || "video/mp4");
- await chunksStore.setItem(`chunk_${i}`, {
- index: i,
- chunk: slice,
- timestamp: ts,
- });
- if (isFirstSlice) {
- // Update watchdog heartbeat. Without this, the recording-stall
- // detector in handleAlarm.js sees lastChunkAt as null, computes
- // a huge age, and fires stall-unrecoverable at ~30s β€” killing
- // every WebCodecs recording silently.
- const heartbeatUpdate = { lastChunkAt: Date.now() };
- if (i === 0) heartbeatUpdate.firstChunkAt = Date.now();
- chrome.storage.local.set(heartbeatUpdate).catch(() => {});
- if (!hasChunks.current) {
- chrome.runtime
- .sendMessage({ type: "cancel-first-chunk-watchdog" })
- .catch(() => {});
- }
- hasChunks.current = true;
- isFirstSlice = false;
- }
- index.current = i + 1;
- savedCount.current += 1;
- if (blob.size === 0) break;
- offset = end;
+ const i = index.current;
+ await chunksStore.setItem(`chunk_${i}`, {
+ index: i,
+ chunk: blob,
+ timestamp: ts,
+ });
+
+ // Heartbeat + first-chunk watchdog fire on the first fragment
+ // only, so the SW's stall detector doesn't kill us early.
+ const heartbeatUpdate = { lastChunkAt: Date.now() };
+ if (i === 0) heartbeatUpdate.firstChunkAt = Date.now();
+ chrome.storage.local.set(heartbeatUpdate).catch(() => {});
+ if (!hasChunks.current) {
+ chrome.runtime
+ .sendMessage({ type: "cancel-first-chunk-watchdog" })
+ .catch(() => {});
+ hasChunks.current = true;
}
- const i = index.current - 1;
+ index.current = i + 1;
+ savedCount.current += 1;
+
if (DEBUG_RECORDER) {
- debug("WebCodecs chunk saved", {
+ debug("WebCodecs fragment saved", {
i,
ts,
size: blob.size,
@@ -1131,6 +1139,36 @@ const Recorder = () => {
}
} catch (err) {
debugError("Failed to save WebCodecs chunk", err);
+ // Quota check above is a best-effort pre-flight; the actual write
+ // can still fail (QuotaExceededError, IDB transaction aborted,
+ // disk full). Handle it the same way as a canFitChunk miss so the
+ // user gets a clear toast and already-saved fragments are kept.
+ const name = err?.name || "";
+ const msg = String(err?.message || err || "").toLowerCase();
+ const looksLikeQuotaError =
+ name === "QuotaExceededError" ||
+ msg.includes("quota") ||
+ msg.includes("disk");
+ if (looksLikeQuotaError && !lowStorageAbort.current) {
+ chrome.runtime.sendMessage({
+ type: "show-toast",
+ message: chrome.i18n.getMessage("toastStorageCritical"),
+ timeout: 8000,
+ });
+ lowStorageAbort.current = true;
+ chrome.storage.local.set({
+ recording: false,
+ restarting: false,
+ tabRecordedID: null,
+ memoryError: true,
+ lowStorageAbortAt: Date.now(),
+ lowStorageAbortChunks: index.current,
+ });
+ requestStop("low-storage", {
+ memoryError: true,
+ savedChunks: savedCount.current,
+ });
+ }
}
return;
diff --git a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
index 4caacb9..83e5767 100644
--- a/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
+++ b/src/pages/Recorder/webcodecs/Mp4MuxerWrapper.ts
@@ -7,7 +7,7 @@
import {
Output,
Mp4OutputFormat,
- BufferTarget,
+ StreamTarget,
EncodedVideoPacketSource,
EncodedAudioPacketSource,
EncodedPacket,
@@ -25,9 +25,15 @@ interface Mp4MuxerWrapperOptions {
debug?: boolean;
}
+// Flush buffered stream writes to chunksStore when we hit ~1MB or 1s,
+// whichever first. Small enough that losing the last buffer on a hard crash
+// only costs ~1s of video; large enough that chunksStore writes stay cheap.
+const FLUSH_BYTES = 1 * 1024 * 1024;
+const FLUSH_INTERVAL_MS = 1000;
+
export class Mp4MuxerWrapper {
private output: Output;
- private target: BufferTarget;
+ private target: StreamTarget;
private videoSource: EncodedVideoPacketSource;
private audioSource: EncodedAudioPacketSource | null = null;
@@ -44,6 +50,16 @@ export class Mp4MuxerWrapper {
private _lastDecoderConfig: any = null;
+ // Write-buffer state: coalesces many small StreamTarget writes into
+ // fewer, larger IDB entries. Fragmented MP4 can emit dozens of tiny
+ // writes per second (per-fragment headers, sample data, trailing bytes);
+ // without this, IDB would get hammered with small puts.
+ private _writeBuffer: Uint8Array[] = [];
+ private _writeBufferBytes = 0;
+ private _writeBufferTimer: any = null;
+ private _pendingFlush: Promise<void> = Promise.resolve();
+ private _closed = false;
+
private debug: boolean;
private log: (...args: any[]) => void;
private warn: (...args: any[]) => void;
@@ -59,10 +75,27 @@ export class Mp4MuxerWrapper {
this.videoCodec = options.videoCodec || "avc";
this.audioCodec = options.audioCodec || "aac";
- this.target = new BufferTarget();
+ // Fragmented MP4 via StreamTarget. Writes stream out as fragments are
+ // produced throughout recording, so if finalize() hangs or the recorder
+ // crashes, chunksStore already holds the vast majority of the file as
+ // self-contained fMP4 fragments (moov at start, moof+mdat pairs after).
+ // Playable directly in <video> and re-muxable to standard MP4 on
+ // download for universal compatibility.
+ const writable = new WritableStream<{ data: Uint8Array; position: number; type: string }>({
+ write: (chunk) => {
+ // With an append-only fragmented output, writes arrive in byte-order
+ // and position is monotonic, so we ignore position and just append.
+ this.bufferWrite(chunk.data);
+ },
+ });
+ this.target = new StreamTarget(writable);
this.output = new Output({
format: new Mp4OutputFormat({
- fastStart: false, // metadata at end, more compatible
+ fastStart: "fragmented",
+ // Align fragment boundaries with our keyframe interval (~2s at 30fps).
+ // Larger fragments = fewer moof headers overhead; smaller = finer-
+ // grained recovery on crash. 1s is a good middle ground.
+ minimumFragmentDuration: 1,
}),
target: this.target,
});
@@ -73,6 +106,52 @@ export class Mp4MuxerWrapper {
});
}
+ private bufferWrite(data: Uint8Array) {
+ if (this._closed) return;
+ // StreamTarget reuses its internal buffer across writes, so we must
+ // copy here. Storing the reference would leave us with stale bytes
+ // by the time the flush runs.
+ const copy = new Uint8Array(data.byteLength);
+ copy.set(data);
+ this._writeBuffer.push(copy);
+ this._writeBufferBytes += copy.byteLength;
+
+ if (this._writeBufferBytes >= FLUSH_BYTES) {
+ this.flushWriteBuffer();
+ } else if (!this._writeBufferTimer) {
+ this._writeBufferTimer = setTimeout(
+ () => this.flushWriteBuffer(),
+ FLUSH_INTERVAL_MS,
+ );
+ }
+ }
+
+ private flushWriteBuffer() {
+ if (this._writeBufferTimer) {
+ clearTimeout(this._writeBufferTimer);
+ this._writeBufferTimer = null;
+ }
+ if (this._writeBuffer.length === 0) return;
+
+ const parts = this._writeBuffer;
+ const total = this._writeBufferBytes;
+ this._writeBuffer = [];
+ this._writeBufferBytes = 0;
+
+ const merged = new Uint8Array(total);
+ let offset = 0;
+ for (const p of parts) {
+ merged.set(p, offset);
+ offset += p.byteLength;
+ }
+
+ // Serialize emits via a promise chain so chunksStore sees writes in the
+ // order they were produced (critical for file byte-order integrity).
+ this._pendingFlush = this._pendingFlush
+ .catch(() => {})
+ .then(() => this.emitChunk(merged, null));
+ }
+
enableAudio() {
if (!this.audioSource) {
this.log("[MUXER] enableAudio");
@@ -112,15 +191,29 @@ export class Mp4MuxerWrapper {
async finalize() {
this.log("[MUXER] finalize");
- await this.output.finalize();
-
- const data = this.target.buffer;
- if (data?.byteLength) {
- this.log("[MUXER] emitting final file", data.byteLength, "bytes");
- this.emitChunk(new Uint8Array(data), null);
+ try {
+ await this.output.finalize();
+ } finally {
+ // Whatever finalize did (or didn't) write, flush the coalescing
+ // buffer and mark closed so late writes are dropped rather than
+ // leaking into a future recording.
+ this.flushWriteBuffer();
+ this._closed = true;
+ // Let any in-flight emitChunk calls settle before returning. The
+ // caller's onFinalized depends on chunksStore being consistent.
+ await this._pendingFlush;
}
}
+ // Force-flush pending writes without running output.finalize(). Called
+ // when the muxer hangs, to preserve whatever fragments have already
+ // streamed out so the recording is still recoverable.
+ async flushPending() {
+ this.flushWriteBuffer();
+ this._closed = true;
+ await this._pendingFlush;
+ }
+
// No-op: WebCodecsRecorder already subtracts paused time from timestamps,
// so a second subtraction here would break monotonicity. Kept for API compat.
setPausedOffset(_offsetUs: number) {}
diff --git a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
index b7c7f2a..19b554e 100644
--- a/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
+++ b/src/pages/Recorder/webcodecs/WebCodecsRecorder.js
@@ -409,16 +409,46 @@ export class WebCodecsRecorder {
}
}
- try {
- if (this.muxer) {
- await this.muxer.finalize();
- if (this.options.onFinalized) {
- await this.options.onFinalized();
- }
+ // Finalize the muxer with a hard timeout. On abrupt stream end (e.g. user
+ // clicks Chrome's "Stop sharing" bar and the video track is torn down
+ // mid-pipeline), output.finalize() can hang. With fragmented MP4 +
+ // StreamTarget the vast majority of the file has already been streamed
+ // to chunksStore throughout the recording, so a hung finalize at most
+ // costs us the last fragment (~1s). flushPending() drops the muxer into
+ // a closed state and flushes any buffered writes, preserving what we have.
+ let muxerFinalizeOk = false;
+ if (this.muxer) {
+ try {
+ await Promise.race([
+ this.muxer.finalize().then(() => {
+ muxerFinalizeOk = true;
+ }),
+ new Promise((_, reject) =>
+ setTimeout(
+ () => reject(new Error("muxer-finalize-timeout")),
+ 5000,
+ ),
+ ),
+ ]);
+ } catch (err) {
+ this.err("[WCR] muxer.finalize:", err);
+ this.options.onError?.(err);
+ try {
+ await this.muxer.flushPending();
+ } catch {}
+ }
+ }
+
+ // Always invoke onFinalized so the Recorder layer can decide what to do
+ // next (validate whatever chunks landed, mark the recording as failed,
+ // send video-ready to unblock the editor). Skipping this on finalize
+ // failure is what caused the stuck-at-90% bug on stream-end.
+ if (this.options.onFinalized) {
+ try {
+ await this.options.onFinalized({ muxerFinalizeOk });
+ } catch (err) {
+ this.err("[WCR] onFinalized threw:", err);
}
- } catch (err) {
- this.err("[WCR] muxer.finalize:", err);
- this.options.onError?.(err);
}
this.cleanup();
diff --git a/src/pages/Region/Recorder.jsx b/src/pages/Region/Recorder.jsx
index 067417a..3fb6ed5 100644
--- a/src/pages/Region/Recorder.jsx
+++ b/src/pages/Region/Recorder.jsx
@@ -629,7 +629,7 @@ const Recorder = () => {
const { useWebCodecsRecorder } = await chrome.storage.local.get([
"useWebCodecsRecorder",
]);
- // Default-on as of 4.3.7: treat undefined as enabled; only explicit `false` opts out.
+ // Default-on: treat undefined as enabled; only explicit `false` opts out.
const userSetting = useWebCodecsRecorder === false ? false : true;
const stickyState = await getFastRecorderStickyState();
const probeResult = await probeFastRecorderSupport();
diff --git a/src/pages/Sandbox/context/ContentState.jsx b/src/pages/Sandbox/context/ContentState.jsx
index 1acfda4..2444c3b 100644
--- a/src/pages/Sandbox/context/ContentState.jsx
+++ b/src/pages/Sandbox/context/ContentState.jsx
@@ -22,6 +22,15 @@ import {
isRecordingDebugEnabled,
} from "../../utils/recordingDebug";
import { diagForward } from "../../utils/diagForward";
+import {
+ Input,
+ Output,
+ BlobSource,
+ BufferTarget,
+ Mp4OutputFormat,
+ ALL_FORMATS,
+ Conversion,
+} from "mediabunny";
localforage.config({
driver: localforage.INDEXEDDB,
@@ -2139,6 +2148,42 @@ const ContentState = (props) => {
});
};
+ // Re-mux a fragmented MP4 blob to a standard (non-fragmented) MP4 blob
+ // via container copy (no re-decode, no re-encode). The recorder writes
+ // fMP4 for crash safety, but users expect a standard MP4 on download
+ // for universal compatibility (QuickTime seeking, editors, etc.).
+ // Typical cost: ~1-3 seconds for a 10-min recording.
+ //
+ // Uses BufferTarget despite the memory cost. fastStart: false is NOT a
+ // pure append-only write: mediabunny writes an mdat header placeholder
+ // up front, then samples, then patches the mdat size at the end via a
+ // positioned write. A naive stream-to-blob pipe drops those positioned
+ // patches, producing a file with an empty mdat and orphan samples that
+ // no player can open. A positioned StreamTarget would need a random-
+ // access backing store (a buffer), so BufferTarget is the right tool.
+ const remuxFragmentedToStandardMp4 = async (fragmentedBlob, onProgress) => {
+ const input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(fragmentedBlob),
+ });
+ const target = new BufferTarget();
+ const output = new Output({
+ target,
+ format: new Mp4OutputFormat({ fastStart: false }),
+ });
+ const conversion = await Conversion.init({
+ input,
+ output,
+ video: { forceTranscode: false },
+ audio: { forceTranscode: false },
+ });
+ if (typeof onProgress === "function") {
+ conversion.onProgress = (p) => onProgress(p);
+ }
+ await conversion.execute();
+ return new Blob([target.buffer], { type: "video/mp4" });
+ };
+
const download = async () => {
if (contentState.isFfmpegRunning || contentState.downloading) return;
@@ -2146,19 +2191,45 @@ const ContentState = (props) => {
...prev,
downloading: true,
isFfmpegRunning: true,
+ processingProgress: 0,
}));
try {
- const url = URL.createObjectURL(contentState.blob);
+ // Re-mux fragmented MP4 β†’ standard MP4 for universal compatibility.
+ // Editor plays fMP4 directly (Chrome handles it), but downloaded
+ // files need the standard layout so they seek cleanly in QuickTime,
+ // DaVinci, Premiere, etc. Container-only operation, no re-encode.
+ const remuxedBlob = await remuxFragmentedToStandardMp4(
+ contentState.blob,
+ (p) =>
+ setContentState((prev) => ({
+ ...prev,
+ processingProgress: Math.round(p * 100),
+ })),
+ );
+ const url = URL.createObjectURL(remuxedBlob);
await requestDownload(url, ".mp4");
+ URL.revokeObjectURL(url);
setContentState((prev) => ({ ...prev, saved: true }));
} catch (err) {
console.error("MP4 download failed:", err);
+ // Fallback: serve the fMP4 as-is so the user doesn't lose the
+ // recording if re-mux fails. Chrome/VLC/most modern players read it
+ // fine; older tools may struggle with seeking.
+ try {
+ const url = URL.createObjectURL(contentState.blob);
+ await requestDownload(url, ".mp4");
+ URL.revokeObjectURL(url);
+ setContentState((prev) => ({ ...prev, saved: true }));
+ } catch (fallbackErr) {
+ console.error("MP4 fallback download failed:", fallbackErr);
+ }
} finally {
setContentState((prev) => ({
...prev,
downloading: false,
isFfmpegRunning: false,
+ processingProgress: 0,
}));
}
};