Case file 02Frontend8 min read

The fallback that saves you when WebCodecs doesn't

Video trimming that runs in the browser with two engines, and two bugs that only showed up with real files in a real browser.

Read by an AI voice of Sajib. Words light up as he reads.

I pressed Stop in the middle of a video edit. The dialog said “Applying…” and then never changed again. Every mocked test for this code was green.

That bug came near the end of a long project: video trimming and editing that runs inside the browser, for a social media management product. The goal was easy to say: if the user can play the video, they should get a file back.

Below are the first version I threw away, the two-engine design that shipped, and two bugs that only appeared with real files in a real browser.

Why trim in the browser

Brands on the product generate short videos with an AI model. The model accepts a reference clip of about 15 seconds. Users don’t have 15-second clips, though. They upload whatever they filmed, up to 200 MB.

We could upload the whole file and trim it on the server. That means a long upload, a server encode and a compute bill, just to throw most of the file away.

The browser already has the file. Modern browsers can also decode and encode video through WebCodecs, a browser API that gives JavaScript direct access to the video and audio encoders and decoders. So the plan was to cut the clip on the user’s machine and upload only the clip.

One requirement was firm: it had to work for everyone who can play the video, including the files that are hard to handle.

What I tried first

The first version used mediabunny, an open-source TypeScript library built on WebCodecs. You give it a file, an output format, and a start and end time. It re-encodes just that part into an MP4 file.

Re-encoding matters because a cheaper trim cuts at the nearest keyframe, a full picture inside the video stream, and keyframes can be two seconds apart. Re-encoding every frame gives a cut that is accurate to the frame.

The library had one problem. Sometimes the trim start landed in the middle of an audio packet, and the encoder received a sample with a tiny negative timestamp and threw an error. I tried two things:

  1. Move the start time forward to the next 50 millisecond boundary, so the cut lands between audio packets. At 30 frames per second, that moves the cut by at most 1.5 frames.
  2. If the error still happened, try again without the audio track.

I kept the first idea and deleted the second one, because a silent clip looks like success. The user uploads it and only later notices that the sound is gone.

The retry also handled only one error message. A codec the library could not read, or an encoder failure on some graphics card, would still leave the user with an error and no file. That version lived on my branch for 34 minutes.

The design that shipped: two engines

I kept the fast engine. When it fails for any reason, except the user pressing Stop, the code switches to a second engine. The second engine depends only on something every browser does well: playing video.

The fast engine is the WebCodecs path. On an Apple Silicon laptop, it produced a 15-second clip in about 1.7 seconds.

The slow engine plays the video in a hidden <video> element and records it. The code draws each frame onto a canvas, and the audio goes through the Web Audio API. MediaRecorder, a built-in browser API, records both into one file. This engine runs in real time, so a 15-second clip takes about 15 seconds. But it adds no code to the bundle, and it works in almost every browser.

Fig. 2.1 · Every error except Stop moves to the slow engine. The user always gets a file.

A small function between the two engines holds the whole guarantee. In its catch block, only the user’s Stop ends the chain; every other error moves on to the slow engine.

async function trimWithFallback(args: TrimArgs) {
  if (supportsWebCodecs()) {
    try {
      return await fastEngine(args);
    } catch (err) {
      if (userPressedStop(err)) throw err; // Stop is not a failure
      args.onEngineSwitch?.();
    }
  }
  return await realtimeEngine(args);
}

Without the Stop rule, pressing Stop during a fast trim would quietly start a 15-second recording. And I didn’t try to list the errors that deserve a fallback, because that list would always miss one.

Making the slow path feel deliberate

A switch in the middle of a trim changes the wait from about 3 seconds to about 15. If the progress bar simply stopped moving, the user would think the app was broken.

So on a switch, the interface resets the progress bar and changes its time estimate to match the full clip length. It also changes the label to “Hang tight, this format takes a bit more time…”. The user never sees words like WebCodecs, encoder or fallback. The name of the engine that ran goes to the console, for support.

Some small details mattered as much as the engines. When a user adds a file, a quick check finds videos that the browser cannot decode, usually HEVC video in Chrome. The user sees a plain explanation instead of a broken editor.

Round two: an editor with a safety net

In October the product got an “Edit video” dialog for videos already on our servers. Users can trim, cut sections out and change the speed. The backend team’s service does the encode with ffmpeg. The dialog shows a live preview, so nothing is encoded until the user clicks Apply.

The server accepts videos up to two minutes long, and sometimes it answers that it is busy. For both cases there is a browser path. It downloads the video, encodes only the kept parts into one MP4 file with the same library, uploads the result and saves it.

Two decisions were different from the trimmer. First, the browser path locks the speed to 1x. Browsers have no good offline way to stretch audio without changing its pitch. Second, the recording engine is not a fallback here. On Chrome and Firefox it writes WebM files, and the social platforms reject WebM. A browser that can’t encode MP4 gets a clear note instead of a file that fails later, at publish time.

The mocked tests passed. Then I used the feature in real Chrome, first on a test page and then against the real backend. Two bugs appeared within hours.

The Stop button that never finished

This is the bug from the start of the article. When I pressed Stop during a browser encode, the dialog stayed on “Applying…” forever.

The cause was inside the library. In the version we used, cancel didn’t always end the encode: sometimes one track was paused, waiting for the other track to catch up, and cancel never woke it, so the promise never settled. A newer version of the library fixed this.

I didn’t upgrade as part of this fix, because a version in between changed how trims work. That deserved its own change.

The fix stops waiting for the library. It uses Promise.race, which takes several promises and settles as soon as the first one settles. cancel() still asks the library to stop, and it also ends the promise right away.

function encodeSegments(args: SegmentArgs) {
  let stop!: (e: Error) => void;
  const stopped = new Promise<never>((_, reject) => { stop = reject; });
  const work = runEncode(args); // may never settle after cancel

  return {
    promise: Promise.race([work, stopped]),
    cancel() {
      library.cancel(); // still ask the library to stop
      stop(new DOMException("Cancelled", "AbortError")); // but finish now
    },
  };
}

Its test simulates an encode that never returns after cancel. The old code times out, and the new code passes.

The audio that was a second too long

The second bug needed the real backend and one particular file. I cut a section out of the middle of a video, and the result had 4.0 seconds of video and 5.08 seconds of audio. Everything after the cut was out of sync.

It was a chain of reasonable steps. The file’s audio was recorded at 32 kHz, which means 32,000 samples per second. Chrome’s audio encoder doesn’t accept 32 kHz, so the library converted the audio to 48 kHz. During that conversion, the library passed audio to my code in chunks of up to 5 seconds.

My code kept or dropped each chunk as a whole, based on its start time. With normal audio, a chunk is about 21 milliseconds long, so this worked well. But a 5-second chunk that starts before a cut counts as “kept”, and the part that should be cut comes with it.

The fix cuts audio more precisely. A small function takes the time span of each chunk and returns only the parts that fall inside the kept sections, along with where each part belongs in the output. The code copies just those parts. Each part starts exactly where the last one ended, so rounding errors can’t make the audio overlap.

I tested the fix on a clip with a steadily rising tone, where any delay is easy to measure. With one cut and with three cuts, I measured no added delay.

What is still not great

Every encode through the library plays its audio about 43 milliseconds late. An ffmpeg encode of the same clip has no delay. The difference is within broadcast tolerance, so I documented it but did not fix it.

Stepping frame by frame with the arrow keys assumes 30 frames per second, so on 24 or 60 fps videos it is slightly off. That is still on the to-do list.

What I learned

Design the fallback for any failure, not for a list of known failures. My first version handled one error message. The version that shipped handles everything except the user’s own Stop.

A library’s cancel is only a request. If your interface depends on cancel finishing, make it finish yourself.

Keep-or-drop logic is safe only while the pieces are small. It breaks quietly on the day something upstream starts sending bigger pieces.

Test with real files early. Both October bugs appeared within hours of using real Chrome, while the mocked tests were green. Next time I would keep a small set of difficult files, such as 32 kHz audio, 120 fps video, HEVC and variable frame rate, and run every engine change against them.

Product names and some details are changed or left out. The engineering is real.