DEV Community

Uchit Chakma
Uchit Chakma

Posted on Originally published at ucdreams.com

Zero-Upload In-Browser Video Compression: WebCodecs VideoEncoder, Adaptive Bitrate Budgeting & FFmpeg.wasm Remuxing

Zero-Upload In-Browser Video Compression: WebCodecs VideoEncoder, Adaptive Bitrate Budgeting & FFmpeg.wasm Remuxing

Most online video compressors force you through a slow, bandwidth-heavy loop: upload a 400 MB MP4 or MOV recording to a remote transcoding server, wait in a queue, download a watermarked output, and hope your private footage is actually deleted afterward.

To eliminate server compute bottlenecks and keep raw footage strictly on the user's device, our engineering team at UCDREAMS built UCDREAMS Free Online Video Compressor — a zero-upload, watermark-free video shrinker that runs directly inside the browser using WebCodecs (VideoEncoder / VideoDecoder), Adaptive Bitrate Budgeting, and FFmpeg.wasm container muxing.

Here is how the client-side compression pipeline works under the hood.


1. Adaptive Bitrate & Resolution Budgeting

When a user targets a specific output file size (for example, shrinking a 180 MB screen recording under 25 MB for Discord or email, or preparing assets before a peer-to-peer transfer on FileShareOnline), blind CRF guesses frequently overshoot the budget.

Instead, we calculate an explicit bits-per-pixel-frame (BPP) budget before initializing the encoder:

export interface CompressionPlan {
  targetWidth: number;
  targetHeight: number;
  videoBitrateBps: number;
  audioBitrateBps: number;
  fps: number;
}

export function planBitrateBudget(
  sourceWidth: number,
  sourceHeight: number,
  durationSec: number,
  targetSizeMb: number,
  fps = 30
): CompressionPlan {
  const safeDuration = Math.max(durationSec, 1);
  // Reserve 6% container/muxing overhead (moov atom + interleaving)
  const totalBitsBudget = targetSizeMb * 8 * 1024 * 1024 * 0.94;
  const audioBitrateBps = targetSizeMb <= 10 ? 96_000 : 128_000;
  const rawVideoBitrate = Math.max(
    180_000,
    Math.floor(totalBitsBudget / safeDuration - audioBitrateBps)
  );

  // Downscale cleanly only if bits-per-pixel drops below visual comfort threshold
  let scale = 1;
  const pixelsPerSec = sourceWidth * sourceHeight * fps;
  const bpp = rawVideoBitrate / Math.max(pixelsPerSec, 1);
  if (bpp < 0.045 && sourceHeight > 720) scale = 720 / sourceHeight;
  if (bpp < 0.025 && sourceHeight > 480) scale = 480 / sourceHeight;

  const even = (n: number) => Math.max(2, Math.floor(n / 2) * 2);
  return {
    targetWidth: even(sourceWidth * scale),
    targetHeight: even(sourceHeight * scale),
    videoBitrateBps: rawVideoBitrate,
    audioBitrateBps,
    fps,
  };
}
Enter fullscreen mode Exit fullscreen mode

Keeping width and height divisible by 2 prevents H.264/AVC chroma subsampling (yuv420p) encoder rejections across Safari, Chrome, and Edge hardware accelerators.


2. Backpressure-Aware VideoEncoder Loop

Browser GPU encoders can easily crash or stall tab memory if frames are pushed faster than hardware encodes them. Monitoring encoder.encodeQueueSize with explicit flush() backpressure keeps RAM usage flat even on 4K source clips:

async function compressFrames(
  frames: AsyncIterable<VideoFrame>,
  plan: CompressionPlan,
  onChunk: (chunk: EncodedVideoChunk, meta?: EncodedVideoChunkMetadata) => void
) {
  const encoder = new VideoEncoder({
    output: onChunk,
    error: (err) => {
      throw new Error(`WebCodecs VideoEncoder failed: ${err.message}`);
    },
  });

  encoder.configure({
    codec: "avc1.4D4028", // H.264 Main Profile Level 4.0
    width: plan.targetWidth,
    height: plan.targetHeight,
    bitrate: plan.videoBitrateBps,
    framerate: plan.fps,
    hardwareAcceleration: "prefer-hardware",
    latencyMode: "quality",
  });

  let index = 0;
  for await (const frame of frames) {
    while (encoder.encodeQueueSize > 6) {
      await new Promise((r) => setTimeout(r, 8));
    }
    const keyFrame = index % (plan.fps * 2) === 0;
    encoder.encode(frame, { keyFrame });
    frame.close(); // Immediately free GPU-backed VideoFrame memory
    index++;
  }

  await encoder.flush();
  encoder.close();
}
Enter fullscreen mode Exit fullscreen mode

Calling frame.close() immediately after encoder.encode() is mandatory in WebCodecs — omitting it leaks GPU surface textures and causes Chrome/Safari to throw QuotaExceededError within seconds.


3. Remuxing & Complementary Browser Media Tools

When browsers lack hardware WebCodecs codecs for legacy .mov or exotic audio streams, our pipeline falls back smoothly to FFmpeg.wasm in an isolated Web Worker with faststart (-movflags +faststart) so compressed MP4s stream immediately on web pages without waiting for full file downloads.

You can test the full zero-upload pipeline and companion utilities right in your browser:


Built by UCDREAMS Engineering Studio

We build high-performance client-side WebAssembly/WebCodecs web tools, real-time WebSocket platforms, custom React & Django web apps, and 95+ Mobile PageSpeed custom websites. Test any live site with our Free Website Speed Tester or discuss your next build at https://ucdreams.com/contact-us/.

Top comments (0)