Real-Time & Streaming From Zero · Episode 07

Broadcast & Recording: Build Your Own OBS

Broadcast & Recording: Build Your Own OBS is Episode 07 of Real-Time & Streaming From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 07 · Real-Time & Streaming From Zero

Every stream you've ever watched — the gameplay with the webcam in the corner, the name that slides in under the speaker, the little logo bug in the corner, the scrolling ticker — is one picture being assembled live and then shoved down a pipe. The tool that assembles it is a compositor, and the famous one is OBS. Today you build a tiny version of it in the browser, in plain JavaScript, with no install: draw a video feed and animated graphics onto a single canvas, turn that canvas into a live MediaStream, and record the result to a file you can download.

The demo below boots into a synthetic feed — the same animated fake-camera canvas we've used all series — so it's a working broadcast the instant the page paints, with no permission and on any origin. Then you layer on overlays: a lower-third title bar, a scene frame with a corner bug and a scrolling ticker, and a picture-in-picture inset. Flip the whole composite into a broadcast-ready stream, preview it in a real <video>, and hit record to capture a .webm clip. By the end you own the entire pipeline from pixels to playable file.

feed (synthetic / camera) ─┐ lower-third overlay ─┤ scene frame + ticker ─┼─▶ [ COMPOSITOR CANVAS ] ──captureStream()──▶ MediaStream picture-in-picture inset ─┘ │ │ │ ┌─────┴─────┐ ▼ ▼ ▼ one drawn frame <video> preview MediaRecorder ──▶ .webm
0 fps
synthetic feed — broadcasting on first paint
synthetic · 0 overlays
A single video feed drawn onto the compositor canvas — frame zero of a broadcast.

Broadcast stream

captureStream() — idle (enable at stage 5)

Recording

MediaRecorder — idle. Hit ● record to capture a clip.

What you're looking at

The big frame is the compositor canvas. Sixty times a second we wipe it and redraw, bottom layer first: the video feed, then any overlays you've toggled on, each painted on top of the last. That ordering — back to front, feed then graphics — is the whole secret. A broadcast isn't magic; it's just drawImage and some fillRects in the right sequence, every frame.

Below the compositor is the output rack. The left tile is a real <video> playing compositorCanvas.captureStream() — proof that our hand-drawn picture is now a genuine MediaStream, the same kind of object a camera produces and the same kind you'd hand to a peer connection from Episode 03. The right tile is the recorder: a MediaRecorder wrapped around that stream, collecting chunks into a Blob you can download and play in any video app.

Everything is alive without permission. The feed defaults to the synthetic source; flip source → camera to upgrade it to your real webcam (one prompt, gated, and if it fails we quietly stay synthetic). Nothing here needs a server, a second person, or even a camera.

Stage 1 — Base feed

Start at the bottom of the stack: one video feed, drawn onto the compositor each frame. The feed lives in a hidden <video> element whose srcObject is a MediaStream — synthetic by default. Our job is to copy its current frame onto the compositor canvas, letterboxed so a 16:9 camera doesn't get stretched into our 16:10 frame.

// (a) the compositor loop — draw the feed, then overlays, every frame
function drawFrame() {
  // 1. clear to broadcast black
  ctx.fillStyle = '#000';
  ctx.fillRect(0, 0, W, H);

  // 2. the FEED — drawImage a <video> straight onto the canvas (letterboxed)
  if (feedVideo.readyState >= 2 && feedVideo.videoWidth) {
    drawContain(feedVideo, feedVideo.videoWidth, feedVideo.videoHeight);
  } else {
    drawContain(synthetic.canvas, synthetic.canvas.width, synthetic.canvas.height);
  }

  // 3. OVERLAYS, painted back-to-front on top of the feed
  if (overlays.scene) drawScene(t);   // frame + bug + ticker
  if (overlays.lower) drawLowerThird(t);
  if (overlays.pip)   drawPip();       // a second source, inset

  requestAnimationFrame(drawFrame);
}

A <video> element is a valid first argument to drawImage — the browser hands you whatever frame it has decoded right now. The one rule: the video must actually be playing. A paused video paints a frozen frame (or nothing). That's why every feed video in this demo gets autoplay playsinline muted and a .play() kick — the same autoplay incantation from Episode 02.

Stage 2 — Lower-third

The classic broadcast graphic: a bar that slides in from the left with a name and a subtitle. It's the "this is who's talking" overlay on every news channel and interview. Because we redraw every frame anyway, animating it is free — we drive a slide-in with an eased 0→1 progress value and an accent stripe, then stack two lines of text. It's all fillRect and fillText on the compositor's 2D context, drawn after the feed so it sits on top.

// an animated lower-third: eased slide-in + accent stripe + two text lines
function drawLowerThird(t) {
  const p   = easeOut(Math.min(1, (t - lowerShownAt) / 0.5)); // 0→1 over 0.5s
  const w   = W * 0.46, h = H * 0.16;
  const x   = -w + (W * 0.06 + w) * p;             // slide in from off-screen left
  const y   = H * 0.74;

  ctx.fillStyle = 'rgba(8,12,24,0.86)';            // translucent slab
  ctx.fillRect(x, y, w, h);
  ctx.fillStyle = '#38bdf8';                        // accent stripe
  ctx.fillRect(x, y, W * 0.008, h);

  ctx.fillStyle = '#fff';
  ctx.font = `600 ${Math.round(H*0.052)}px ui-sans-serif, system-ui`;
  ctx.fillText('Ada Lovelace', x + W * 0.03, y + h * 0.42);
  ctx.fillStyle = '#93c5fd';
  ctx.font = `${Math.round(H*0.032)}px ui-monospace, monospace`;
  ctx.fillText('LIVE · building a compositor', x + W * 0.03, y + h * 0.74);
}

Notice we measure sizes as fractions of the canvas (W * 0.46, H * 0.052) instead of hard pixels. The compositor is DPR-scaled and can be any size, so resolution-independent graphics keep the lower-third looking right whether you render at 1280×800 or on a Retina display at twice that.

Stage 3 — Scene frame

Now the "channel furniture": a thin border framing the whole shot, a station bug in the top-right corner, and a ticker scrolling across the bottom. These are the overlays that brand a stream and never move with the content — they live in screen space, on top of everything. The ticker is the fun one: it's a single line of text whose x-offset we advance every frame, wrapping when it scrolls fully off the left.

// scene furniture: border + corner bug + a scrolling ticker (screen-space)
function drawScene(t) {
  // 1. frame border
  ctx.strokeStyle = 'rgba(56,189,248,0.5)';
  ctx.lineWidth = Math.max(2, H * 0.006);
  ctx.strokeRect(ctx.lineWidth, ctx.lineWidth, W - ctx.lineWidth*2, H - ctx.lineWidth*2);

  // 2. corner bug
  ctx.fillStyle = 'rgba(0,0,0,0.55)';
  ctx.fillRect(W - W*0.16, H*0.04, W*0.12, H*0.07);
  ctx.fillStyle = '#fbbf24';
  ctx.font = `700 ${Math.round(H*0.04)}px ui-monospace, monospace`;
  ctx.fillText('◉ ZERO-TV', W - W*0.15, H*0.092);

  // 3. ticker — advance x every frame, wrap when it clears the screen
  const barY = H * 0.92, barH = H * 0.06;
  ctx.fillStyle = 'rgba(8,12,24,0.9)';
  ctx.fillRect(0, barY, W, barH);
  ctx.fillStyle = '#e5e5e5';
  ctx.font = `${Math.round(H*0.035)}px ui-monospace, monospace`;
  const msg = 'BREAKING — you are compositing a live broadcast in the browser   ✦   ';
  const tw  = ctx.measureText(msg).width;
  const off = (t * 90) % tw;                       // 90 px/s scroll
  ctx.fillText(msg, W - off,          barY + barH*0.7);
  ctx.fillText(msg, W - off + tw,     barY + barH*0.7); // second copy = seamless loop
}

The seamless-loop trick is worth keeping: draw the string twice, one text width apart. As the first copy scrolls off the left, the second has already taken its place, so there's never a gap. Modulo the offset by the text width and it repeats forever with two fillText calls.

Stage 4 — Picture-in-picture

The webcam-in-the-corner shot. PiP is just a second source drawn small, in a rounded box, on top of the main feed. Here the inset is its own little synthetic "camera" — a second animated canvas, completely independent of the main feed — so the demo shows two live sources composited at once with nothing plugged in. In a real studio this inset would be your webcam while the main feed is your gameplay or screen share.

// picture-in-picture: a SECOND source, inset in the corner with a border
function drawPip() {
  const pw = W * 0.26, ph = pw * 0.625;          // 16:10 inset
  const px = W - pw - W * 0.03, py = H * 0.05;

  ctx.fillStyle = '#000';
  ctx.fillRect(px - 3, py - 3, pw + 6, ph + 6);   // border mat
  // drawImage the SECOND synthetic source's canvas, scaled into the box
  ctx.drawImage(pipSource.canvas, px, py, pw, ph);
  ctx.strokeStyle = '#38bdf8';
  ctx.lineWidth = 2;
  ctx.strokeRect(px, py, pw, ph);
  ctx.fillStyle = 'rgba(0,0,0,0.6)';
  ctx.fillRect(px, py + ph - H*0.04, pw*0.4, H*0.04);
  ctx.fillStyle = '#34d399';
  ctx.font = `${Math.round(H*0.026)}px ui-monospace, monospace`;
  ctx.fillText('● CAM 2', px + 6, py + ph - H*0.012);
}

That's the entire compositor: feed, then three overlays, in z-order. Toggle them in any combination with the buttons. Each one is independent — that's exactly how a real switcher's scene is built, as a stack of sources you can show, hide, and reorder.

Stage 5 — The composite is a stream

Here's the move that makes this a broadcast and not just a drawing: call captureStream() on the compositor canvas. It returns a live MediaStream whose single video track is whatever the canvas shows, updated every time we paint. Point a <video> at it and you're watching your own broadcast feed — the same object you could send to a peer, a recorder, or (with a server) the whole internet.

// (b) turn the compositor canvas INTO a broadcast-ready MediaStream
function startBroadcast(fps) {
  // one video track, driven by the canvas at up to `fps` frames/sec
  broadcastStream = compositor.captureStream(fps);

  // preview it in a real <video> (muted so autoplay is allowed)
  preview.srcObject = broadcastStream;
  preview.play().catch(() => {});

  const tr = broadcastStream.getVideoTracks()[0];
  const s  = tr.getSettings();
  setStreamMeta(`live · ${s.width}×${s.height} @ ${fps}fps · 1 video track`);
}

Two subtleties. First, captureStream(fps) takes a frame-rate hint — pass 0 and it captures on demand (each time the canvas changes); pass a number and it caps the track there. Second, the stream is live: it must exist and be flowing before anything downstream — a recorder, a peer — tries to consume it. Capture an empty or not-yet-drawn canvas and you get a black or stalled track. We start drawing first, then capture.

A MediaStream doesn't care where its frames come from. Camera, screen, another peer, or — as here — a canvas you painted by hand. To everything downstream, our compositor is indistinguishable from a real camera. That's the entire reason this series can teach streaming with no hardware.

Stage 6 — Record a clip

The payoff: wrap that stream in a MediaRecorder and you get a downloadable video file. The recorder watches the stream, encodes it in the background, and hands you the compressed bytes in ondataavailable events. Collect those chunks, and when you stop, stitch them into a Blob and make a download link. This is, end to end, how every in-browser screen recorder and "save your clip" button works.

The first job is picking a container/codec the browser actually supports, because that varies wildly — Chrome loves vp9, Safari historically wanted mp4/H.264, and you must feature-detect rather than assume:

// (c) MediaRecorder setup — feature-detect a supported mime, then start
function pickMime() {
  const candidates = [
    'video/webm;codecs=vp9',
    'video/webm;codecs=vp8',
    'video/webm;codecs=h264',
    'video/webm',
    'video/mp4',                              // Safari
  ];
  // MediaRecorder.isTypeSupported is the ONLY reliable check
  for (const m of candidates) {
    if (window.MediaRecorder && MediaRecorder.isTypeSupported(m)) return m;
  }
  return '';                                    // '' = let the browser choose its default
}

let recorder = null, chunks = [];

function startRecording() {
  if (!broadcastStream) return;                  // stream MUST be live first
  const mime = pickMime();
  chunks = [];
  recorder = new MediaRecorder(broadcastStream, mime ? { mimeType: mime } : undefined);

  recorder.ondataavailable = (e) => { if (e.data.size > 0) chunks.push(e.data); };
  recorder.onstop = () => finishRecording(mime);
  recorder.start(1000);                            // emit a chunk every 1s (timeslice)
}

function stopRecording() {
  if (recorder && recorder.state !== 'inactive') recorder.stop();
}

When the recorder stops it fires onstop, and now we own a list of encoded chunks. Concatenate them into one Blob, mint an object URL, and wire it to a download link. The detail people forget: revoke that URL when you replace it, or every recording leaks a blob into memory for the life of the page.

// (d) build the Blob from the chunks → a downloadable file
let lastUrl = null;

function finishRecording(mime) {
  const type = mime || 'video/webm';
  const blob = new Blob(chunks, { type });         // stitch chunks → one file

  if (lastUrl) URL.revokeObjectURL(lastUrl);     // free the PREVIOUS clip (no leaks)
  lastUrl = URL.createObjectURL(blob);

  const ext = type.includes('mp4') ? 'mp4' : 'webm';
  dl.href = lastUrl;
  dl.download = `broadcast-clip.${ext}`;          // the filename the browser saves
  dl.style.display = 'inline-block';
  setRecMeta(`saved · ${(blob.size/1e6).toFixed(2)} MB · ${type}`);
}

Click ● record, let it run a few seconds while overlays animate, then click ■ stop. A download link appears in the rack; the .webm it saves contains your composited broadcast — feed, lower-third, ticker, PiP and all — playable in any video app. You just built the record button from OBS.

The pipeline, end to end

Four objects, one chain. Worth memorizing, because every browser recording or canvas-broadcast pipeline is some version of this:

StageAPIProduces
Compositectx.drawImage + fill* in a rAF loopA canvas that updates every frame
Broadcastcanvas.captureStream(fps)A live MediaStream (video track)
Encodenew MediaRecorder(stream, { mimeType })Blob chunks via ondataavailable
Savenew Blob(chunks) + URL.createObjectURLA downloadable file

Swap the synthetic feed for a camera (the source dropdown) or, conceptually, a screen share, and the rest of the chain is byte-for-byte identical. Add a peer connection between "Broadcast" and the network and you've got a one-to-many live stream. The compositor is the heart; everything else is plumbing it into a different pipe.

Common pitfalls

  • Drawing a paused <video>. drawImage only copies the frame the video currently has decoded. If the element is paused, not yet play()ed, or still buffering (readyState < 2), you'll paint a frozen frame or nothing. Set autoplay playsinline muted and call .play(), and guard the draw on readyState.
  • Assuming a mime type. MediaRecorder support is genuinely fragmented — video/webm;codecs=vp9 in Chrome, often video/mp4 in Safari, and passing an unsupported mimeType throws or yields an empty file. Always loop candidates through MediaRecorder.isTypeSupported() and fall back to the browser default (undefined).
  • Capturing before the stream is live. Build the recorder (or peer connection) after captureStream and after the canvas has started drawing. Wrap a recorder around a not-yet-painted canvas and you record black frames or a stalled track.
  • Leaking object URLs. Every URL.createObjectURL pins its Blob in memory until you revokeObjectURL it. Record ten clips without revoking and you've leaked ten videos. Revoke the previous URL before minting the next, and on pagehide.
  • Stretching the feed. A 16:9 camera squashed into a 16:10 compositor looks wrong. Letterbox (object-fit: contain) or crop (cover) on purpose — compute a scale from the source and destination aspect ratios rather than passing drawImage the raw canvas size.
  • Recording with no audio. canvas.captureStream() carries only video — a canvas has no sound. A recording of it is silent until you add an audio track (see the first exercise). Many "why is my clip silent?" bugs are exactly this.

Exercises

  1. Add audio to the recording. A canvas stream is video-only. Grab a mic with getUserMedia({ audio: true }) (gated behind a click, like Episode 02), then add its track to the broadcast stream before recording: broadcastStream.addTrack(micStream.getAudioTracks()[0]). Now your .webm has sound. Bonus: mix in a second source (e.g. synthetic background music from an OscillatorNode) with a Web Audio graph and record the mix.
  2. A transition between scenes. Add a second "scene" (different overlays / colors) and a wipe between them: animate a 0→1 progress and either crossfade by drawing the new scene at rising globalAlpha, or do a hard wipe by clipping the new scene to an expanding rectangle. This is the cut/transition bar in any switcher.
  3. A live viewer-count overlay. Draw a "👁 1,234 watching" badge that ticks up over time (fake it with a counter, or wire it to the BroadcastChannel presence count from a later episode). Animate the number rolling, and flash it when it crosses a milestone — the kind of dynamic, data-driven overlay that makes a stream feel live.

What's next

Episode 08 — Season Finale: A Shared Live Space. We bring the whole season together into one room: synthetic peers and real tabs, media and data channels, presence and netcode — a little world you can walk into, populated solo and instantly multiplayer when someone else joins. The compositor you built today becomes one participant's broadcast in a space full of them.