Seven failures, no useful diagnosis

SubtitleGenerator renders burned-in captions in the browser. You select a local video, generate a transcript, edit the captions, and export an MP4 with the captions rendered into its frames. The video rendering runs locally in the browser.

In one session, a user received their transcript and then made seven unsuccessful attempts to export a video with burned-in captions. We observed no further events from that session.

The failure UI appended the same generic advice to the error message every time:

Your project is safe. Try again or use a current desktop Chrome browser.

When I went to find out why the exports failed, I couldn't. Our analytics sent a single hard-coded error category for every export failure, so the specific error code was thrown away at the moment of capture. There was no export table in the database, no error reporting on the export path, and the local export history only recorded successes. Other exports succeeded during the same period, so the evidence did not point to a service-wide failure.

So this article is not a root-cause story for that one session. That cause is unrecoverable. It is about the two things I could fix:

  1. The app only checked what the browser could really do after an export attempt had already started.
  2. The app suggested retrying failures that an immediate retry was unlikely to fix.

If you render, encode or package anything heavy in the browser (WebCodecs, OPFS, canvas, workers), the same two problems are probably waiting in your code.

What the original export path actually checked

The export pipeline looks like this:

local source file -> decode video (WebCodecs, via mediabunny) -> draw captions on an OffscreenCanvas in a worker -> VideoFrame -> encode AVC -> mux MP4, write to OPFS -> verify output, hand the file to the user 

Browser video export pipeline showing where each check runs: before an export attempt starts, after it starts but before rendering, and after the file is produced.

Before letting anyone press export, the app checked this:

export function browserHasExportPrimitives(): boolean { return ( typeof globalThis.VideoDecoder !== 'undefined' && typeof globalThis.VideoEncoder !== 'undefined' && typeof globalThis.OffscreenCanvas !== 'undefined' && typeof globalThis.Worker !== 'undefined' && typeof globalThis.navigator !== 'undefined' && typeof globalThis.navigator.storage?.getDirectory === 'function' ); } 

It checks that the APIs exist. It does not check that they work for this file at this size. VideoEncoder can exist and still refuse the codec, resolution or bitrate you need. VideoDecoder can exist and still be unable to decode the user's source.

The real capability checks did exist (can this profile be encoded, can this source be decoded, is there enough quota), but they ran after an export attempt had started. Some of them could reject the attempt before rendering began, and output verification only ran after the file was produced. Either way, the user had to spend an attempt to find out, and the UI then offered the same generic retry advice.

Moving capability checks before rendering

The fix was a small preflight that runs when the export dialog opens, before an export attempt starts. It asks four questions, in this order:

  1. Encode: can this browser encode AVC at the resolved width, height and bitrate?
  2. Decode: does the source file have a primary video track this browser can decode?
  3. Storage: is the estimated output smaller than the remaining browser storage quota?
  4. Fonts: can the font resources the captions need be collected for the worker?

The design decision that matters most is what happens when a probe itself breaks. A probe is new code running against browser APIs that behave differently across versions and devices. If a probe throws, I can't tell whether the browser is unsupported or my probe is wrong. Blocking the user in that case would turn a bug in my checking code into a new way to stop people from exporting.

So every probe is wrapped, and a throw means "unknown", which lets the export continue:

async function probeOrFailOpen<T>( probe: () => Promise<T> ): Promise<{ ok: true; value: T } | { ok: false }> { try { return { ok: true, value: await probe() }; } catch { return { ok: false }; } } const encode = await probeOrFailOpen(() => capabilities.canEncodeVideo({ codec: 'avc', width, height, bitrate }) ); if (!encode.ok) return { supported: true }; // the probe broke: unknown, let it run if (!encode.value) { return { supported: false, kind: 'unsupported-browser' }; // a definite "no" } // Decode and fonts follow the same boolean pattern. // Storage returns an object, so the kernel checks storage.value.ok. 

The kernel returns a negative result for unsupported encoding, unsupported decoding, insufficient storage, or a false font result. The dialog blocks the capability failures but leaves storage shortfalls retryable, because the user can fix those.

The encode probe uses mediabunny's canEncodeVideo with the codec, resolved dimensions and bitrate of the free export profile. The decode probe opens the user's file and asks the primary video track whether it can decode.

Two scope limits are worth stating plainly:

  • The dialog only probes the free export profile. A device that can encode the free profile but not the HD one will still fail at runtime, and that failure goes through the error handling described below instead of a preflight block.
  • The preflight only runs for local files, the path where rendering happens in the browser.

The storage check came first

The storage check was not new. It came from an earlier failure: during testing, a 30-minute export at 8 Mbps on a 16 GB machine ran almost to the end and then failed with QuotaExceededError when the file was finalized in OPFS. Everything before that point was wasted work.

The guard estimates the output size and compares it with the quota. The calculation below omits the surrounding fail-open error handling:

export const EXPORT_STORAGE_OVERHEAD_RATIO = 1.15; const neededBytes = Math.ceil( durationSeconds * (bitrateBps / 8) * EXPORT_STORAGE_OVERHEAD_RATIO ); const estimate = await navigator.storage.estimate(); const availableBytes = (estimate.quota ?? 0) - (estimate.usage ?? 0); 

The 1.15 ratio is a safety margin for muxing overhead, not a guarantee. An estimate is not a reservation, and other tabs can use storage between the check and the render. If estimate() itself throws, the check is skipped. When I built the dialog preflight, I reused this guard instead of writing a second one.

Because low storage is fixable, it doesn't disable the export button. Once the export starts, the same check runs again, and if it still fails, the message says how much space is needed and how much is available.

Preventing the preflight itself from blocking export

During review of the first version I found a gap: probeOrFailOpen handles a probe that throws, but not one that never settles. Without a timeout, the dialog could stay stuck checking capabilities and prevent the user from starting an export at all.

The fix is a single time limit around the whole preflight:

const EXPORT_PREFLIGHT_TIMEOUT_MS = 8_000; function failOpenOnTimeoutOrReject( promise: Promise<ExportPreflightResult> ): Promise<ExportPreflightResult> { return new Promise((resolve) => { const timer = window.setTimeout( () => resolve({ supported: true }), EXPORT_PREFLIGHT_TIMEOUT_MS ); promise.then( (result) => { window.clearTimeout(timer); resolve(result); }, () => { window.clearTimeout(timer); resolve({ supported: true }); } ); }); } 

It is important to be honest about what fail-open gives up:

  • "Allowed" means "not known to fail", not "verified". A timed-out or broken probe lets the export run and possibly fail later, which is exactly the old behavior for that case.
  • The timeout stops waiting. It does not cancel the probe. Whatever the stuck probe was doing may keep running in the background.
  • One broken probe skips the probes after it. When an exception reaches probeOrFailOpen, the function returns "allowed" right away and later checks don't run. The storage probe is different: checkExportStorage catches its own estimate() error, so the font check still runs after it.

I accepted those costs because the preflight's job is to catch definite, cheap-to-detect failures early. It is not a gate that has to be right every time. The runtime error handling still has to be correct on its own.

Turning error codes into useful next actions

The second problem was the message. "Try again" is a promise. If a capability check rejects the requested AVC profile, immediately repeating the same attempt is unlikely to help.

The export already threw typed errors. The fix was to decide, per code, what the user should do next:

  • unsupported-browser, unsupported-source, invalid-output: no immediate retry. The user sees "This browser can't finish the video export", a suggestion to open the project in a current desktop Chrome or Edge, and a note that the project is safe and nothing was charged.
  • insufficient-storage: retry after freeing space. The message says how much space is needed versus available.
  • render-failed from an interrupted export: retry. The user sees the interruption message with a retry.
  • Anything else: retry. "The browser couldn't finish this export. Your project is safe. Try again."

This is a policy, not a diagnosis. For three error codes, the policy removes the immediate retry action and recommends a current desktop Chrome or Edge browser. That is a suggestion, not a guarantee that another browser will succeed. The mapping also can't prove that every render-failed is temporary, so unknown errors still default to a retry.

When the preflight returns a definite "unsupported", the dialog shows a similar redirect before an export attempt starts: "This browser can't export a burned-in video. Open in a current desktop Chrome or Edge to export. Your subtitles are safe — keep editing here."

Export-failure events now also carry a six-value export_failure_kind field alongside the generic category. When an event is captured, we can see which kind of error it was, although render-failed still groups several possible causes.

Testing the boundaries, including what probes miss

The preflight kernel was written against a failing test first. Its unit tests cover the decision rules by injecting probe results:

  • encode probe says no → unsupported-browser
  • decode probe says no → unsupported-source
  • quota estimate too small → insufficient-storage
  • font probe returns false → unsupported-browser
  • a probe throws → allowed
  • every probe says yes → allowed

The font case tests the kernel's rule, not the real adapter. In the app, the font adapter returns true when collection succeeds and throws when it fails, and a throw is allowed.

End-to-end tests use an injection hook, available only in test mode, that forces the encode probe to report "unsupported" or to throw. That covers both sides of fail-open in a real browser: the blocked state with its redirect copy, and the throwing probe that must not block. At a 390px viewport width, another test injects an insufficient-storage error and checks the shortfall message, a visible retry button and an enabled export button. It doesn't run a second attempt.

One gap I should name: I haven't found a test that directly asserts the eight-second timeout. The timeout is implemented, but it isn't covered the way the other branches are.

What the tests can't show is everything the probes don't cover. In a later Android investigation, export failed immediately with render-failed. On the tested phone (a Xiaomi 13 Ultra on Chrome 151), FontFaceSet.load rejected font requests that included the next/font fallback backed by local(). Loading only the primary family for export fixed that failure.

Our font preflight only collects the font resources. It doesn't run the font loading that happens later in the export path. I don't have a record of what the preflight returned on that phone, so I won't claim it passed and then failed. The point is narrower: that failure was in a step the preflight doesn't exercise. A preflight is a sample of the pipeline, not a dry run of it.

A checklist for expensive browser operations

If your app does heavy work in the browser before handing something to the user, here is what I would check:

  1. Existence is not capability. For each API, can you ask the real question (this codec, this size, this file) before the expensive step instead of after?
  2. Decide what a broken check means. If your probe throws or hangs, do you block or allow? Write that decision down. Bound how long the UI waits for the preflight, and be clear about whether that deadline also cancels the underlying work.
  3. Classify failures by whether an immediate retry can help. Don't show "Try again" for a failure you already expect to repeat. Offer a concrete next step without promising that a different browser will succeed.
  4. Keep the error code. If your analytics flattens failures into one category, you may see the same failure pattern I did, with no evidence to explain it.
  5. Write down what the preflight doesn't cover. Every stage the preflight skips remains a possible source of runtime failure, so runtime error handling has to stand on its own.

What is still unsolved: the cause of those seven failures is gone for good. Some older devices still fail at runtime in places no preflight covers yet. And a passing preflight can still end in a failed export, which is why the error mapping matters as much as the checks.

The export code described here runs in SubtitleGenerator. The lesson isn't specific to captions, though: check what you can before the expensive step, and don't ask people to retry something you already expect to fail.