Spaces:
Running
Running
Download index.html from Longpipe/longpipe-demo: direct link, hf CLI and curl.
- Browser
- Download file 46.1 kB
-
https://huggingface.co/spaces/Longpipe/longpipe-demo/resolve/main/index.html
- Command line
-
hf download hf://spaces/Longpipe/longpipe-demo/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Longpipe/longpipe-demo/resolve/main/index.html
46.1 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>π</text></svg>" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" />
<title>Longpipe demo: live virtual backgrounds in your browser</title>
<meta name="description" content="Live demo of Longpipe, an open-source browser SDK for video-call effects: virtual backgrounds, touch-up and auto-reframe running on your GPU. Nothing is uploaded." />
<style>
/* Brand palette β mirrors the Longpipe website tokens */
:root {
--bg: #ecfdf5; /* emerald-50 */
--bg-card: #ffffff;
--bg-card-tint: #d1fae5; /* emerald-100 */
--border: #a7f3d0; /* emerald-200 */
--border-strong: #6ee7b7; /* emerald-300 */
--text: #022c22; /* emerald-950 */
--muted: #065f46; /* emerald-700 */
--accent: #059669; /* emerald-600 */
--accent-hover: #047857; /* emerald-700 */
--accent-soft: #d1fae5; /* emerald-100 */
--error: #dc2626;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: 'Inter', system-ui, sans-serif;
min-height: 100vh;
display: flex;
flex-direction: column;
}
a { color: var(--accent); text-decoration: none; }
a:hover { color: var(--accent-hover); }
code, kbd, samp { font-family: 'JetBrains Mono', ui-monospace, monospace; }
/* Nav (matches site header style) */
nav {
padding: 14px 24px;
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
justify-content: space-between;
background: var(--bg);
position: sticky;
top: 0;
z-index: 10;
}
nav .brand {
display: flex;
align-items: center;
gap: 8px;
font-family: 'JetBrains Mono', monospace;
font-weight: 600;
color: var(--text);
}
nav .brand img { width: 24px; height: 24px; }
nav .links { display: flex; gap: 18px; font-size: 14px; color: var(--muted); }
nav .links a { color: var(--muted); }
nav .links a:hover { color: var(--text); }
main {
flex: 1;
max-width: 980px;
margin: 0 auto;
padding: 40px 24px 56px;
width: 100%;
}
h1 {
margin: 0 0 8px;
font-size: 32px;
font-weight: 800;
letter-spacing: -0.02em;
}
h1 .accent { color: var(--accent); }
.intro {
color: var(--muted);
margin: 0 0 32px;
max-width: 600px;
line-height: 1.55;
font-size: 15px;
}
/* Output video */
.video-card {
position: relative;
background: #000;
border-radius: 16px;
overflow: hidden;
box-shadow: 0 12px 32px -12px rgba(5, 95, 70, 0.28);
margin-bottom: 14px;
}
.video-card video {
display: block;
width: 100%;
aspect-ratio: 16/9;
background: #000;
}
.fps-badge {
position: absolute;
top: 10px;
right: 12px;
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
line-height: 1.45;
white-space: pre;
text-align: right;
color: #d1fae5;
background: rgba(2, 44, 34, 0.62);
padding: 5px 9px;
border-radius: 7px;
pointer-events: none;
backdrop-filter: blur(2px);
}
.fps-badge:empty { display: none; }
/* Loading spinner β centered over the preview while the model loads
(pipeline.ready / MediaPipe's first frame). Fades out, doesn't block. */
.spinner-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.28);
opacity: 1;
transition: opacity 400ms ease;
pointer-events: none;
}
.spinner-overlay.hidden { opacity: 0; }
.spinner {
width: 54px;
height: 54px;
border: 5px solid rgba(255, 255, 255, 0.22);
border-top-color: var(--border-strong); /* emerald accent */
border-radius: 50%;
animation: spin 0.9s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
.status {
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
color: var(--muted);
padding: 0 4px 24px;
min-height: 18px;
}
.status.error { color: var(--error); }
/* Control cards */
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
margin-bottom: 16px;
}
@media (max-width: 720px) {
.controls { grid-template-columns: 1fr; }
}
.card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 18px 20px;
}
.card-label {
margin: 0 0 12px;
font-size: 11px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--muted);
}
/* Segmented buttons */
.segmented {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.segmented button {
flex: 1;
min-width: 0;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
background: transparent;
color: var(--text);
border: 1px solid var(--border);
padding: 10px 12px;
border-radius: 8px;
font-family: inherit;
font-size: 14px;
cursor: pointer;
transition: background 120ms, border-color 120ms, color 120ms;
}
.segmented button:hover { background: var(--accent-soft); }
.rf-now {
border: 1px solid var(--accent); background: var(--accent-soft);
color: var(--accent-ink, #064e3b); border-radius: 6px;
padding: 0.35rem 0.75rem; font: inherit; font-size: 0.85rem; cursor: pointer;
}
.rf-now:hover { background: var(--accent); color: #fff; }
/* Touch-up and auto-reframe are Longpipe features; MediaPipe has no
equivalent, so the cards dim rather than silently doing nothing. */
.card.lp-only-off { opacity: 0.45; pointer-events: none; }
.segmented button.active {
background: var(--accent);
color: white;
border-color: var(--accent);
}
.upload-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
margin-left: 2px;
border-radius: 4px;
opacity: 0.55;
cursor: pointer;
transition: opacity 120ms, background 120ms;
}
.upload-icon:hover {
opacity: 1;
background: rgba(2, 44, 34, 0.08);
}
.segmented button.active .upload-icon { opacity: 0.85; }
.segmented button.active .upload-icon:hover {
opacity: 1;
background: rgba(255, 255, 255, 0.18);
}
.upload-icon svg { width: 13px; height: 13px; display: block; }
/* Background sub-options (color / blur sigma) */
.bg-extra {
margin-top: 12px;
display: none;
gap: 10px;
align-items: center;
font-size: 13px;
}
.bg-extra.show { display: flex; }
.bg-extra label { color: var(--muted); min-width: 60px; }
.bg-extra input[type=color] {
background: var(--bg);
border: 1px solid var(--border);
padding: 0;
width: 36px;
height: 32px;
border-radius: 6px;
cursor: pointer;
}
.bg-extra input[type=range] {
flex: 1;
accent-color: var(--accent);
}
.bg-extra .val {
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
color: var(--muted);
min-width: 32px;
text-align: right;
}
/* Preview-an-effect card */
.preview-card { margin-bottom: 16px; }
.preview-card.disabled { opacity: 0.5; pointer-events: none; }
.preview-body {
display: flex;
gap: 18px;
align-items: stretch;
}
@media (max-width: 640px) { .preview-body { flex-direction: column; } }
.preview-canvas-wrap {
position: relative;
width: 240px;
flex: 0 0 auto;
align-self: flex-start; /* don't stretch to the controls' height β keep 16:9 */
aspect-ratio: 16 / 9;
background: #000;
border-radius: 10px;
overflow: hidden;
}
@media (max-width: 640px) { .preview-canvas-wrap { width: 100%; } }
.preview-canvas-wrap canvas {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.preview-empty {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
font-family: 'JetBrains Mono', monospace;
font-size: 12px;
color: #6ee7b7;
}
.preview-empty.hidden { display: none; }
.preview-controls {
flex: 1;
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
}
.preview-actions { display: flex; gap: 8px; margin-top: auto; }
.preview-actions button {
flex: 1;
padding: 10px 12px;
border-radius: 8px;
border: 1px solid var(--border);
background: transparent;
color: var(--text);
font-family: inherit;
font-size: 14px;
cursor: pointer;
transition: background 120ms, border-color 120ms, color 120ms;
}
.preview-actions button:disabled { opacity: 0.45; cursor: default; }
.preview-actions #previewApply:not(:disabled) {
background: var(--accent);
color: white;
border-color: var(--accent);
}
.preview-actions #previewApply:not(:disabled):hover { background: var(--accent-hover); }
.preview-actions #previewStop:not(:disabled):hover { background: var(--accent-soft); }
/* Advanced (preset) */
details.advanced {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 14px 20px;
margin-bottom: 28px;
}
details.advanced[open] { padding-bottom: 18px; }
details.advanced summary {
cursor: pointer;
font-size: 13px;
font-weight: 600;
color: var(--muted);
list-style: none;
user-select: none;
}
details.advanced summary::-webkit-details-marker { display: none; }
details.advanced summary::before {
content: "βΈ";
display: inline-block;
margin-right: 8px;
transition: transform 150ms;
}
details.advanced[open] summary::before { transform: rotate(90deg); }
details.advanced .preset-row { margin-top: 14px; }
/* Bottom CTA row */
.cta-row {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
padding-top: 16px;
border-top: 1px solid var(--border);
}
.cta-row a.btn {
padding: 10px 18px;
border-radius: 8px;
font-size: 14px;
font-weight: 600;
transition: all 120ms;
}
.cta-row a.primary {
background: var(--accent);
color: white;
}
.cta-row a.primary:hover { background: var(--accent-hover); }
.cta-row a.outline {
border: 1px solid var(--border-strong);
color: var(--muted);
}
.cta-row a.outline:hover { background: var(--accent-soft); }
.cta-row .install {
margin-left: auto;
font-family: 'JetBrains Mono', monospace;
font-size: 13px;
color: var(--muted);
background: var(--bg-card-tint);
padding: 8px 12px;
border-radius: 6px;
}
.cta-row .install::before { content: "$ "; opacity: 0.5; }
.space-links { margin-top: 20px; font-size: 13px; color: var(--muted); }
.space-links a { color: var(--accent); }
</style>
</head>
<body>
<nav>
<a href="https://longpipe.dev" class="brand" target="_blank" rel="noopener">
<span>π Longpipe</span>
</a>
<div class="links">
<a href="https://longpipe.dev" target="_blank" rel="noopener">longpipe.dev</a>
<a href="https://longpipe.dev/docs" target="_blank" rel="noopener">Docs</a>
<a href="https://www.npmjs.com/package/longpipe" target="_blank" rel="noopener">npm</a>
<a href="https://huggingface.co/Longpipe/longpipe" target="_blank" rel="noopener">Models</a>
<a href="https://github.com/sb2702/longpipe" target="_blank" rel="noopener">GitHub</a>
</div>
</nav>
<main>
<h1>Try <span class="accent">Longpipe</span>.</h1>
<p class="intro">
Live virtual backgrounds, running entirely in your browser. Pick a source,
pick a background β segmentation, compositing, the works run on your GPU
via WebGPU (or WebGL2 fallback). No server, no upload: nothing leaves your device.
The webcam is only used if you click <b>My webcam</b>.
</p>
<div class="video-card">
<video id="output" autoplay muted playsinline></video>
<div id="fps" class="fps-badge"></div>
<div id="spinner" class="spinner-overlay"><div class="spinner"></div></div>
</div>
<div class="status" id="status">startingβ¦</div>
<div class="controls">
<div class="card">
<p class="card-label">Source</p>
<div class="segmented" id="sourceSeg">
<button data-source="video" class="active">Sample video</button>
<button data-source="webcam">My webcam</button>
</div>
</div>
<div class="card">
<p class="card-label">Background</p>
<div class="segmented" id="bgSeg">
<button data-bg="image" class="active">
<span>Image</span>
<span class="upload-icon" data-upload="image" title="Upload your own image" role="button" aria-label="Upload image">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<polyline points="17 8 12 3 7 8"/>
<line x1="12" y1="3" x2="12" y2="15"/>
</svg>
</span>
</button>
<button data-bg="blur"><span>Blur</span></button>
<button data-bg="color"><span>Color</span></button>
<button data-bg="video">
<span>Video</span>
<span class="upload-icon" data-upload="video" title="Upload an mp4 or webm" role="button" aria-label="Upload video">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<polyline points="17 8 12 3 7 8"/>
<line x1="12" y1="3" x2="12" y2="15"/>
</svg>
</span>
</button>
<button data-bg="none"><span>None</span></button>
</div>
<input type="file" id="imageUpload" accept="image/*" hidden />
<input type="file" id="videoUpload" accept="video/mp4,video/webm" hidden />
<div class="bg-extra" id="bgBlurRow">
<label for="bgBlurSigma">Strength</label>
<input type="range" id="bgBlurSigma" min="0" max="1" step="0.05" value="0.5" />
<span class="val" id="bgBlurVal">0.5</span>
</div>
<div class="bg-extra" id="bgColorRow">
<label for="bgColor">Color</label>
<input type="color" id="bgColor" value="#00b050" />
<span class="val" id="bgColorVal">#00b050</span>
</div>
</div>
<div class="card" id="touchupCard">
<p class="card-label">
Touch-up
<span style="text-transform:none;font-weight:400;opacity:0.7">(runs alongside the background β one shared encoder pass)</span>
</p>
<div class="segmented" id="touchupSeg">
<button data-tu="off" class="active"><span>Off</span></button>
<button data-tu="freq-sep"><span>Smooth</span></button>
<button data-tu="bilateral"><span>Bilateral</span></button>
</div>
<div class="bg-extra" id="tuStrengthRow">
<label for="tuStrength">Strength</label>
<input type="range" id="tuStrength" min="0" max="1" step="0.05" value="0.6" />
<span class="val" id="tuStrengthVal">0.6</span>
</div>
</div>
<div class="card" id="reframeCard">
<p class="card-label">
Auto-reframe
<span style="text-transform:none;font-weight:400;opacity:0.7">(no extra model β rides the same face keypoints)</span>
</p>
<div class="segmented" id="reframeSeg">
<button data-rf="off" class="active"><span>Off</span></button>
<button data-rf="auto"><span>Auto</span></button>
<button data-rf="manual"><span>Manual</span></button>
</div>
<div class="bg-extra" id="rfZoomRow">
<label for="rfZoom">Zoom</label>
<input type="range" id="rfZoom" min="1" max="2.5" step="0.05" value="1.35" />
<span class="val" id="rfZoomVal">1.35</span>
</div>
<div class="bg-extra" id="rfNowRow">
<label>Framing</label>
<button id="rfNow" class="rf-now">Reframe now</button>
</div>
</div>
</div>
<div class="card preview-card" id="previewCard">
<p class="card-label">
Preview an effect
<span style="text-transform:none;font-weight:400;opacity:0.7">(see a candidate before applying β the outgoing stream above keeps its current effect)</span>
</p>
<div class="preview-body">
<div class="preview-canvas-wrap" id="previewCanvasWrap">
<div class="preview-empty" id="previewEmpty">no preview</div>
</div>
<div class="preview-controls">
<div class="segmented" id="previewSeg">
<button data-pv="image">Image</button>
<button data-pv="blur">Blur</button>
<button data-pv="color">Green</button>
<button data-pv="none">None</button>
</div>
<div class="preview-actions">
<button id="previewApply" disabled>Apply to stream</button>
<button id="previewStop" disabled>Stop preview</button>
</div>
</div>
</div>
</div>
<details class="advanced" open>
<summary>Advanced</summary>
<div class="preset-row">
<p class="card-label">Preset</p>
<div class="segmented" id="presetSeg">
<button data-preset="auto" class="active">Auto</button>
<button data-preset="fast">Fast</button>
<button data-preset="balanced">Balanced</button>
<button data-preset="quality">Quality</button>
</div>
</div>
<div class="preset-row">
<p class="card-label">Model <span style="text-transform:none;font-weight:400;opacity:0.7">(explicit segmenter β overrides preset; compare against MediaPipe)</span></p>
<div class="segmented" id="modelSeg">
<button data-model="xs">XS</button>
<button data-model="small">Small</button>
<button data-model="medium">Medium</button>
<button data-model="large">Large</button>
<button data-model="xl">XL</button>
<button data-model="mediapipe" title="MediaPipe Selfie Segmentation (off-the-shelf, runs on main thread)">MediaPipe</button>
</div>
</div>
</details>
<div class="cta-row">
<a href="https://longpipe.dev/docs/getting-started" class="btn primary" target="_blank" rel="noopener">Get started</a>
<a href="https://longpipe.dev/docs/api" class="btn outline" target="_blank" rel="noopener">API reference</a>
<span class="install">npm install longpipe</span>
</div>
<p class="space-links">
<a href="https://longpipe.dev" target="_blank" rel="noopener">longpipe.dev</a> Β·
<a href="https://github.com/sb2702/longpipe" target="_blank" rel="noopener">GitHub: sb2702/longpipe</a> Β·
<a href="https://www.npmjs.com/package/longpipe" target="_blank" rel="noopener">npm: longpipe</a> Β·
<a href="https://huggingface.co/Longpipe/longpipe" target="_blank" rel="noopener">ONNX models: Longpipe/longpipe</a>
</p>
</main>
<script type="module">
import { EffectsPipeline } from 'https://esm.sh/longpipe@0.0.16'
const $output = document.getElementById('output')
const $status = document.getElementById('status')
const $sourceSeg = document.getElementById('sourceSeg')
const $bgSeg = document.getElementById('bgSeg')
const $imageUpload = document.getElementById('imageUpload')
const $videoUpload = document.getElementById('videoUpload')
const $bgBlurSigma = document.getElementById('bgBlurSigma')
const $bgBlurVal = document.getElementById('bgBlurVal')
const $bgBlurRow = document.getElementById('bgBlurRow')
const $bgColor = document.getElementById('bgColor')
const $bgColorVal = document.getElementById('bgColorVal')
const $bgColorRow = document.getElementById('bgColorRow')
const $presetSeg = document.getElementById('presetSeg')
const $modelSeg = document.getElementById('modelSeg')
const $fps = document.getElementById('fps')
const $spinner = document.getElementById('spinner')
const $previewCard = document.getElementById('previewCard')
const $previewCanvasWrap = document.getElementById('previewCanvasWrap')
const $previewEmpty = document.getElementById('previewEmpty')
const $previewSeg = document.getElementById('previewSeg')
const $previewApply = document.getElementById('previewApply')
const $previewStop = document.getElementById('previewStop')
const showSpinner = () => $spinner.classList.remove('hidden')
const hideSpinner = () => $spinner.classList.add('hidden')
let pipeline = null
let inputVideo = null
let webcamStream = null
let cachedDefaultBgImage = null
let uploadedImageUrl = null // blob URL for user-uploaded image (null = use default)
let uploadedVideoUrl = null // blob URL for user-uploaded video (null = no video yet)
let currentSource = 'video'
let currentBg = 'image'
let currentPreset = 'auto'
// Preview state. previewCanvasEl is recreated per pipeline build β
// attachPreview's transferControlToOffscreen is one-shot per element.
let previewCanvasEl = null
let previewKind = null // active candidate kind, or null when not previewing
// Which segmenter is active: 'longpipe' or 'mediapipe' (off-the-shelf, for
// a live A/B). The package doesn't export PRESETS, so the explicit per-tier
// ManualPresets are inlined here (model + skipFrames are what the renderer
// uses; resolution/dtype are advisory β dtype auto-forces to f16 when the
// device supports it, and the network resolution comes from the tier config).
let engine = 'longpipe'
const MODEL_PRESETS = {
xs: { model: 'xs', dtype: 'f16', resolution: { w: 384, h: 216 }, skipFrames: 2 },
small: { model: 'small', dtype: 'f16', resolution: { w: 384, h: 216 }, skipFrames: 1 },
medium: { model: 'medium', dtype: 'f16', resolution: { w: 512, h: 288 }, skipFrames: 1 },
large: { model: 'large', dtype: 'f32', resolution: { w: 640, h: 360 }, skipFrames: 0 },
xl: { model: 'xl', dtype: 'f32', resolution: { w: 1280, h: 720 }, skipFrames: 0 },
}
// MediaPipe state (only set while engine === 'mediapipe').
let mp = null, mpVideo = null, mpCanvas = null, mpStream = null, mpBgImage = null
let mpRunning = false, mpScriptPromise = null
// FPS readout. Longpipe: poll getStats(). MediaPipe: rolling 1s window.
let statsTimer = null, mpFrameTimes = [], mpLastShown = 0
function setStatus(s, ok = true) {
$status.textContent = s
$status.className = ok ? 'status' : 'status error'
}
function clearFps() {
if (statsTimer) { clearInterval(statsTimer); statsTimer = null }
mpFrameTimes = []
mpLastShown = 0
$fps.textContent = ''
}
// Longpipe: poll the worker's pre-tracked counters. s.fps = composited
// frames/sec; s.modelFps = network runs/sec (lower on skip-frame tiers).
function startLongpipeFps() {
if (statsTimer) clearInterval(statsTimer)
statsTimer = setInterval(async () => {
if (!pipeline) return
try {
const s = await pipeline.getStats()
$fps.textContent = `${s.fps} fps\n${s.modelFps}/s model`
} catch { /* transient during teardown */ }
}, 500)
}
// MediaPipe: tick per onResults into a rolling 1s window; repaint every 2s.
function tickMpFps() {
const now = performance.now()
mpFrameTimes.push(now)
while (mpFrameTimes.length && mpFrameTimes[0] < now - 1000) mpFrameTimes.shift()
if (now - mpLastShown >= 2000) {
$fps.textContent = `${mpFrameTimes.length} fps\nMediaPipe`
mpLastShown = now
}
}
async function loadDefaultBgImage() {
if (cachedDefaultBgImage) return cachedDefaultBgImage
const res = await fetch('./snowy_forest.jpg')
cachedDefaultBgImage = await createImageBitmap(await res.blob())
return cachedDefaultBgImage
}
async function resolveBg() {
switch (currentBg) {
case 'image': return uploadedImageUrl ?? await loadDefaultBgImage()
case 'blur': return { blur: { strength: parseFloat($bgBlurSigma.value) } }
case 'color': return { color: $bgColor.value }
case 'video': return uploadedVideoUrl ? { video: uploadedVideoUrl } : await loadDefaultBgImage()
case 'none': return 'none'
}
}
async function getInputStream() {
if (currentSource === 'webcam') {
webcamStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false })
return webcamStream
}
// Sample video β captureStream
inputVideo = document.createElement('video')
// The Space serves the mp4 via a cross-origin (CORS-enabled) LFS redirect;
// request it with CORS so captureStream() isn't blocked as cross-origin.
inputVideo.crossOrigin = 'anonymous'
inputVideo.src = './woman_on_video_call.mp4'
inputVideo.loop = true
inputVideo.muted = true
inputVideo.playsInline = true
await inputVideo.play()
// Wait until dimensions are reported
if (!inputVideo.videoWidth) {
await new Promise(res => inputVideo.addEventListener('loadedmetadata', res, { once: true }))
}
return inputVideo.captureStream()
}
function teardown() {
clearFps()
teardownPreview()
if (pipeline) {
try { pipeline.destroy() } catch {}
pipeline = null
}
// MediaPipe teardown: stop the pump loop, close the graph, drop streams.
mpRunning = false
if (mp) { try { mp.close() } catch {} mp = null }
if (mpStream) { for (const t of mpStream.getTracks()) t.stop(); mpStream = null }
if (mpVideo) { mpVideo.pause(); mpVideo.srcObject = null; mpVideo = null }
mpCanvas = null
if (inputVideo) {
inputVideo.pause()
inputVideo.removeAttribute('src')
inputVideo.load()
inputVideo = null
}
if (webcamStream) {
for (const t of webcamStream.getTracks()) t.stop()
webcamStream = null
}
}
async function buildPipeline() {
teardown()
showSpinner()
setStatus('initializing pipelineβ¦')
let inputStream
try {
inputStream = await getInputStream()
} catch (err) {
setStatus('source unavailable: ' + (err.message || err), false)
// Revert source toggle to "video" if webcam was denied
if (currentSource === 'webcam') {
currentSource = 'video'
for (const b of $sourceSeg.querySelectorAll('button')) {
b.classList.toggle('active', b.dataset.source === 'video')
}
return buildPipeline()
}
hideSpinner()
return
}
const bg = await resolveBg()
pipeline = new EffectsPipeline(inputStream, {
background: bg,
touchup: touchupMode === 'off' ? undefined : touchupOpts(),
reframe: reframeMode === 'off' ? undefined : reframeOpts(),
preset: currentPreset,
audio: 'drop',
onError: (err) => setStatus('error: ' + (err.message || err), false),
})
$output.srcObject = pipeline.stream
try {
await pipeline.ready
const stats = await pipeline.getStats().catch(() => null)
const tag = stats?.preset
? `${stats.preset}${stats.skipFrames ? ` Β· 1-in-${stats.skipFrames + 1} frames` : ''}`
: 'live'
setStatus(`live β ${tag} on your GPU`)
startLongpipeFps()
setupPreview()
hideSpinner()
} catch (err) {
setStatus('init failed: ' + (err.message || err), false)
hideSpinner()
}
}
// ββ Preview an effect ββββββββββββββββββββββββββββββββββββββββββββββββββββ
// attachPreview (once per build), setPreview (the candidate β shares the
// network with the main render), clearPreview, and Apply = setBackground.
function resolvePreviewCandidate(kind) {
switch (kind) {
case 'image': return uploadedImageUrl ?? cachedDefaultBgImage ?? './snowy_forest.jpg'
case 'blur': return { blur: { strength: 0.8 } }
case 'color': return { color: '#00b050' }
case 'none': return 'none'
}
}
function resetPreviewUI() {
previewKind = null
for (const b of $previewSeg.querySelectorAll('button')) b.classList.remove('active')
$previewApply.disabled = true
$previewStop.disabled = true
$previewEmpty.classList.remove('hidden')
}
// Fresh canvas per build (attachPreview transfers control to the worker β
// can't reuse a transferred element). The worker resizes the backing to the
// output resolution; CSS scales the visible element down.
function setupPreview() {
if (engine !== 'longpipe' || !pipeline) return
previewCanvasEl = document.createElement('canvas')
$previewCanvasWrap.insertBefore(previewCanvasEl, $previewEmpty)
pipeline.attachPreview(previewCanvasEl)
resetPreviewUI()
$previewCard.classList.remove('disabled')
}
function teardownPreview() {
if (previewCanvasEl) { previewCanvasEl.remove(); previewCanvasEl = null }
resetPreviewUI()
}
$previewSeg.addEventListener('click', async (e) => {
const btn = e.target.closest('button')
if (!btn || !pipeline || engine !== 'longpipe') return
previewKind = btn.dataset.pv
for (const b of $previewSeg.querySelectorAll('button')) b.classList.toggle('active', b === btn)
$previewEmpty.classList.add('hidden')
$previewApply.disabled = false
$previewStop.disabled = false
try {
await pipeline.setPreview({ background: resolvePreviewCandidate(previewKind), fps: 15 })
} catch (err) {
setStatus('preview failed: ' + (err.message || err), false)
}
})
// Apply = commit the previewed candidate as the main outgoing effect, then
// stop previewing. Sync the relevant bg control so applyBg() resolves to the
// same candidate value.
$previewApply.addEventListener('click', async () => {
if (!pipeline || !previewKind) return
const kind = previewKind
if (kind === 'blur') { $bgBlurSigma.value = '0.8'; $bgBlurVal.textContent = '0.8' }
if (kind === 'color') { $bgColor.value = '#00b050'; $bgColorVal.textContent = '#00b050' }
pipeline.clearPreview()
setBgActive(kind)
await applyBg()
resetPreviewUI()
})
$previewStop.addEventListener('click', () => {
if (pipeline) pipeline.clearPreview()
resetPreviewUI()
})
// ββ MediaPipe Selfie Segmentation (off-the-shelf comparison engine) ββββββ
// Loaded as a classic <script> (the @mediapipe package attaches a global +
// loads its own wasm/data via locateFile). Runs on the main thread and
// composites the person over the SAME background as Longpipe β a true A/B.
const MP_CDN = 'https://cdn.jsdelivr.net/npm/@mediapipe/selfie_segmentation@0.1'
function loadMediaPipeScript() {
if (mpScriptPromise) return mpScriptPromise
mpScriptPromise = new Promise((resolve, reject) => {
const s = document.createElement('script')
s.src = `${MP_CDN}/selfie_segmentation.js`
s.crossOrigin = 'anonymous'
s.onload = () => resolve()
s.onerror = () => { mpScriptPromise = null; reject(new Error('failed to load MediaPipe script')) }
document.head.appendChild(s)
})
return mpScriptPromise
}
async function refreshMpBg() {
mpBgImage = (currentBg === 'image' || currentBg === 'video')
? (uploadedImageUrl ? await createImageBitmap(await (await fetch(uploadedImageUrl)).blob())
: await loadDefaultBgImage())
: null
}
function drawMpBackground(ctx, image, w, h) {
if (currentBg === 'color') {
ctx.fillStyle = $bgColor.value
ctx.fillRect(0, 0, w, h)
} else if (currentBg === 'blur') {
// Map 0β1 strength to a CSS-blur px comparable to Longpipe's sigma 4β16
// range, so the A/B blur looks fair.
const px = 4 + parseFloat($bgBlurSigma.value) * 12
ctx.filter = `blur(${px}px)`
ctx.drawImage(image, 0, 0, w, h)
ctx.filter = 'none'
} else if (mpBgImage) {
ctx.drawImage(mpBgImage, 0, 0, w, h)
} else {
ctx.fillStyle = '#000'; ctx.fillRect(0, 0, w, h)
}
}
function compositeMP(ctx, results) {
const w = mpCanvas.width, h = mpCanvas.height
ctx.save()
ctx.clearRect(0, 0, w, h)
if (currentBg === 'none') {
ctx.drawImage(results.image, 0, 0, w, h)
ctx.restore()
return
}
ctx.drawImage(results.segmentationMask, 0, 0, w, h) // person = white
ctx.globalCompositeOperation = 'source-in'
ctx.drawImage(results.image, 0, 0, w, h) // person pixels only
ctx.globalCompositeOperation = 'destination-over'
drawMpBackground(ctx, results.image, w, h) // background behind
ctx.restore()
}
async function buildMediaPipe() {
teardown()
// Preview shares the Longpipe inference path β not available for MediaPipe.
$previewCard.classList.add('disabled')
showSpinner()
setStatus('loading MediaPipeβ¦')
let inputStream
try {
inputStream = await getInputStream()
} catch (err) {
setStatus('source unavailable: ' + (err.message || err), false)
hideSpinner()
return
}
try {
await loadMediaPipeScript()
await refreshMpBg()
mpVideo = document.createElement('video')
mpVideo.muted = true; mpVideo.playsInline = true; mpVideo.autoplay = true
mpVideo.srcObject = inputStream
await mpVideo.play()
if (!mpVideo.videoWidth) {
await new Promise(r => mpVideo.addEventListener('loadedmetadata', r, { once: true }))
}
mpCanvas = document.createElement('canvas')
mpCanvas.width = mpVideo.videoWidth || 1280
mpCanvas.height = mpVideo.videoHeight || 720
const ctx = mpCanvas.getContext('2d')
mp = new window.SelfieSegmentation({ locateFile: (f) => `${MP_CDN}/${f}` })
mp.setOptions({ modelSelection: 1, selfieMode: false }) // 1 = landscape model
mp.onResults((results) => { if (mpRunning) { compositeMP(ctx, results); tickMpFps(); hideSpinner() } })
// Pipe the composite canvas into the existing <video> so the output
// area + styling are identical to the Longpipe path.
mpStream = mpCanvas.captureStream(30)
$output.srcObject = mpStream
mpRunning = true
const pump = async () => {
if (!mpRunning || !mp || !mpVideo) return
try { await mp.send({ image: mpVideo }) } catch {}
if (!mpRunning) return
if (mpVideo.requestVideoFrameCallback) mpVideo.requestVideoFrameCallback(pump)
else requestAnimationFrame(pump)
}
if (mpVideo.requestVideoFrameCallback) mpVideo.requestVideoFrameCallback(pump)
else requestAnimationFrame(pump)
setStatus('live β MediaPipe Selfie Segmentation (off-the-shelf)')
} catch (err) {
setStatus('MediaPipe init failed: ' + (err.message || err), false)
hideSpinner()
}
}
// Dispatch to the active engine's builder.
function rebuild() {
return engine === 'mediapipe' ? buildMediaPipe() : buildPipeline()
}
function wireSeg(container, onChange) {
container.addEventListener('click', (e) => {
const btn = e.target.closest('button')
if (!btn) return
for (const b of container.querySelectorAll('button')) b.classList.remove('active')
btn.classList.add('active')
onChange(btn.dataset)
})
}
wireSeg($sourceSeg, ({ source }) => {
if (source === currentSource) return
currentSource = source
rebuild()
})
function setBgActive(bg) {
currentBg = bg
for (const b of $bgSeg.querySelectorAll('button')) {
b.classList.toggle('active', b.dataset.bg === bg)
}
$bgBlurRow.classList.toggle('show', bg === 'blur')
$bgColorRow.classList.toggle('show', bg === 'color')
}
async function applyBg() {
if (engine === 'mediapipe') {
// compositeMP reads color/blur/none live each frame; only the image
// bitmap needs (re)loading here.
await refreshMpBg().catch(() => {})
return
}
if (!pipeline) return
try {
await pipeline.setBackground(await resolveBg())
} catch (err) {
setStatus('background swap failed: ' + (err.message || err), false)
}
}
// Custom bg handler β clicks on the upload icon trigger the file picker
// instead of toggling bg type. Clicking "Video" with no file uploaded
// yet auto-opens the picker.
$bgSeg.addEventListener('click', (e) => {
const uploadIcon = e.target.closest('.upload-icon')
if (uploadIcon) {
e.stopPropagation()
const which = uploadIcon.dataset.upload
if (which === 'image') $imageUpload.click()
else if (which === 'video') $videoUpload.click()
return
}
const btn = e.target.closest('button')
if (!btn || !btn.dataset.bg) return
const bg = btn.dataset.bg
if (bg === 'video' && !uploadedVideoUrl) {
// Switching to video for the first time β open the picker. Don't
// change the active bg until the user actually picks a file.
$videoUpload.click()
return
}
setBgActive(bg)
applyBg()
})
// Preset (named) and Model (explicit tier / MediaPipe) are two ways to pick
// the active segmenter; selecting from either row clears the other's active
// state so it's always clear what's running.
function setActiveModelBtn(clickedBtn) {
for (const b of [...$presetSeg.querySelectorAll('button'), ...$modelSeg.querySelectorAll('button')]) {
b.classList.toggle('active', b === clickedBtn)
}
}
function selectPreset(value, clickedBtn) {
if (clickedBtn.classList.contains('active')) return
engine = 'longpipe'
currentPreset = value
setActiveModelBtn(clickedBtn)
syncFaceCards()
buildPipeline()
}
function selectMediaPipe(clickedBtn) {
if (clickedBtn.classList.contains('active')) return
engine = 'mediapipe'
setActiveModelBtn(clickedBtn)
syncFaceCards()
buildMediaPipe()
}
$presetSeg.addEventListener('click', (e) => {
const btn = e.target.closest('button')
if (btn) selectPreset(btn.dataset.preset, btn)
})
$modelSeg.addEventListener('click', (e) => {
const btn = e.target.closest('button')
if (!btn) return
if (btn.dataset.model === 'mediapipe') selectMediaPipe(btn)
else selectPreset(MODEL_PRESETS[btn.dataset.model], btn)
})
$imageUpload.addEventListener('change', () => {
const file = $imageUpload.files[0]
if (!file) return
if (uploadedImageUrl) URL.revokeObjectURL(uploadedImageUrl)
uploadedImageUrl = URL.createObjectURL(file)
setBgActive('image')
applyBg()
$imageUpload.value = '' // allow re-uploading the same filename
})
$videoUpload.addEventListener('change', () => {
const file = $videoUpload.files[0]
if (!file) return
if (uploadedVideoUrl) URL.revokeObjectURL(uploadedVideoUrl)
uploadedVideoUrl = URL.createObjectURL(file)
setBgActive('video')
applyBg()
$videoUpload.value = ''
})
$bgBlurSigma.addEventListener('input', () => {
$bgBlurVal.textContent = $bgBlurSigma.value
// Longpipe: 0β1 strength. (MediaPipe reads the value live in compositeMP.)
if (pipeline && currentBg === 'blur') {
pipeline.setBackground({ blur: { strength: parseFloat($bgBlurSigma.value) } })
}
})
$bgColor.addEventListener('input', () => {
$bgColorVal.textContent = $bgColor.value
if (pipeline && currentBg === 'color') {
pipeline.setBackground({ color: $bgColor.value })
}
})
// ββ Touch-up ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Composes with the background rather than replacing it: both ride one
// encoder pass, so enabling this doesn't cost a second inference. Everyone in
// frame is smoothed (up to four faces on medium and above).
const $touchupCard = document.getElementById('touchupCard')
const $touchupSeg = document.getElementById('touchupSeg')
const $tuStrengthRow = document.getElementById('tuStrengthRow')
const $tuStrength = document.getElementById('tuStrength')
const $tuStrengthVal = document.getElementById('tuStrengthVal')
let touchupMode = 'off'
const touchupOpts = () => ({ style: touchupMode, strength: parseFloat($tuStrength.value) })
function applyTouchup() {
if (!pipeline || engine !== 'longpipe') return
pipeline.setTouchup(touchupMode === 'off' ? null : touchupOpts())
.catch(err => setStatus('touch-up failed: ' + (err.message || err), false))
}
$touchupSeg.addEventListener('click', (e) => {
const btn = e.target.closest('button')
if (!btn) return
for (const b of $touchupSeg.querySelectorAll('button')) b.classList.toggle('active', b === btn)
touchupMode = btn.dataset.tu
$tuStrengthRow.classList.toggle('show', touchupMode !== 'off')
applyTouchup()
})
$tuStrength.addEventListener('input', () => {
$tuStrengthVal.textContent = $tuStrength.value
if (touchupMode !== 'off') applyTouchup()
})
// ββ Auto-reframe ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// auto = follows the subject with a deadband (hold, deliberate move, hold).
// manual = solve once and freeze; "Reframe now" is the method a Meet-style
// button would call. Sitting in a far corner correctly does nothing β the
// crop must stay in frame AND contain you.
const $reframeCard = document.getElementById('reframeCard')
const $reframeSeg = document.getElementById('reframeSeg')
const $rfZoomRow = document.getElementById('rfZoomRow')
const $rfNowRow = document.getElementById('rfNowRow')
const $rfZoom = document.getElementById('rfZoom')
const $rfZoomVal = document.getElementById('rfZoomVal')
const $rfNow = document.getElementById('rfNow')
let reframeMode = 'off'
const reframeOpts = () => ({ zoom: parseFloat($rfZoom.value), auto: reframeMode === 'auto' })
function applyReframe() {
if (!pipeline || engine !== 'longpipe') return
pipeline.setReframe(reframeMode === 'off' ? null : reframeOpts())
.catch(err => setStatus('reframe failed: ' + (err.message || err), false))
}
$reframeSeg.addEventListener('click', (e) => {
const btn = e.target.closest('button')
if (!btn) return
for (const b of $reframeSeg.querySelectorAll('button')) b.classList.toggle('active', b === btn)
reframeMode = btn.dataset.rf
$rfZoomRow.classList.toggle('show', reframeMode !== 'off')
$rfNowRow.classList.toggle('show', reframeMode === 'manual')
applyReframe()
})
$rfNow.addEventListener('click', () => {
if (pipeline && engine === 'longpipe') pipeline.reframe()
})
$rfZoom.addEventListener('input', () => {
$rfZoomVal.textContent = $rfZoom.value
if (reframeMode !== 'off') applyReframe()
})
// Both are Longpipe-only. MediaPipe is here as a segmentation baseline and
// has no equivalent, so dim the cards instead of leaving dead controls.
function syncFaceCards() {
const off = engine !== 'longpipe'
$touchupCard.classList.toggle('lp-only-off', off)
$reframeCard.classList.toggle('lp-only-off', off)
}
buildPipeline().catch(err => setStatus('startup failed: ' + (err.message || err), false))
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>π</text></svg>" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet" />
<title>Longpipe demo: live virtual backgrounds in your browser</title>
<meta name="description" content="Live demo of Longpipe, an open-source browser SDK for video-call effects: virtual backgrounds, touch-up and auto-reframe running on your GPU. Nothing is uploaded." />
<style>
/* Brand palette β mirrors the Longpipe website tokens */
:root {
--bg: #ecfdf5; /* emerald-50 */
--bg-card: #ffffff;
--bg-card-tint: #d1fae5; /* emerald-100 */
--border: #a7f3d0; /* emerald-200 */
--border-strong: #6ee7b7; /* emerald-300 */
--text: #022c22; /* emerald-950 */
--muted: #065f46; /* emerald-700 */
--accent: #059669; /* emerald-600 */
--accent-hover: #047857; /* emerald-700 */
--accent-soft: #d1fae5; /* emerald-100 */
--error: #dc2626;
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: 'Inter', system-ui, sans-serif;
min-height: 100vh;
display: flex;
flex-direction: column;
}
a { color: var(--accent); text-decoration: none; }
a:hover { color: var(--accent-hover); }
code, kbd, samp { font-family: 'JetBrains Mono', ui-monospace, monospace; }
/* Nav (matches site header style) */
nav {
padding: 14px 24px;
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
justify-content: space-between;
background: var(--bg);
position: sticky;
top: 0;
z-index: 10;
}
nav .brand {
display: flex;
align-items: center;
gap: 8px;
font-family: 'JetBrains Mono', monospace;
font-weight: 600;
color: var(--text);
}
nav .brand img { width: 24px; height: 24px; }
nav .links { display: flex; gap: 18px; font-size: 14px; color: var(--muted); }
nav .links a { color: var(--muted); }
nav .links a:hover { color: var(--text); }
main {
flex: 1;
max-width: 980px;
margin: 0 auto;
padding: 40px 24px 56px;
width: 100%;
}
h1 {
margin: 0 0 8px;
font-size: 32px;
font-weight: 800;
letter-spacing: -0.02em;
}
h1 .accent { color: var(--accent); }
.intro {
color: var(--muted);
margin: 0 0 32px;
max-width: 600px;
line-height: 1.55;
font-size: 15px;
}
/* Output video */
.video-card {
position: relative;
background: #000;
border-radius: 16px;
overflow: hidden;
box-shadow: 0 12px 32px -12px rgba(5, 95, 70, 0.28);
margin-bottom: 14px;
}
.video-card video {
display: block;
width: 100%;