Spaces:
Running
Running
Download main.js from WeReCooking/Flowframes-WebGPU: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/spaces/WeReCooking/Flowframes-WebGPU/resolve/main/main.js
- Command line
-
hf download hf://spaces/WeReCooking/Flowframes-WebGPU/main.js
-
curl -L -o main.js https://huggingface.co/spaces/WeReCooking/Flowframes-WebGPU/resolve/main/main.js
11.8 kB
| import { Input, ALL_FORMATS, BlobSource, CanvasSink, Output, Mp4OutputFormat, BufferTarget, CanvasSource, EncodedPacketSink, | |
| EncodedAudioPacketSource, getFirstEncodableVideoCodec } from './vendor/mediabunny.min.mjs'; | |
| import { createRife, packRgb, unpackRgba, padTo } from './rife.js'; | |
| const q = new URLSearchParams(location.search); | |
| const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null); // test hooks: same-origin paths only | |
| const MODEL = local(q.get('model')) || 'models/rife49.onnx'; | |
| const ORT_URL = local(q.get('ort')) || 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.webgpu.min.mjs'; | |
| const $ = (id) => document.getElementById(id); | |
| const ui = { drop: $('drop'), file: $('file'), opts: $('opts'), factor: $('factor'), side: $('side'), go: $('go'), stop: $('stop'), status: $('status'), bar: $('bar').firstElementChild, | |
| examples: $('examples'), result: $('result'), video: $('video'), save: $('save'), info: $('info'), store: $('store'), free: $('free'), wipe: $('wipe') }; | |
| const mb = (b) => `${Math.round(b / 1e6)} MB`; | |
| let ortP = null, rifeP = null, source = null, cancel = false; | |
| function status(text, frac = null, bad = false) { | |
| ui.status.textContent = text; ui.status.classList.toggle('bad', bad); | |
| if (frac !== null) ui.bar.style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`; | |
| } | |
| const getOrt = () => (ortP ||= (async () => { | |
| if (!navigator.gpu || !(await navigator.gpu.requestAdapter())) throw new Error('This browser has no WebGPU. Use Chrome or Edge 121+, Android 12+ or Safari 26.'); | |
| const ort = await import(ORT_URL); ort.env.logLevel = 'error'; return ort; | |
| })()); | |
| // The 21 MB model is kept in the browser's origin-private storage after the first download, so it can be deleted again from the page. | |
| const MODEL_FILE = 'rife49.onnx'; | |
| async function modelBytes() { | |
| const dir = await navigator.storage.getDirectory(); | |
| try { const f = await (await dir.getFileHandle(MODEL_FILE)).getFile(); await dir.getFileHandle(MODEL_FILE + '.ok'); return new Uint8Array(await f.arrayBuffer()); } catch { /* not cached yet */ } | |
| status('Downloading RIFE (21 MB)…', 0); | |
| const r = await fetch(MODEL); if (!r.ok) throw new Error(`model download failed (HTTP ${r.status})`); | |
| const total = +r.headers.get('content-length') || 21463211, chunks = []; let got = 0; | |
| for (const rd = r.body.getReader(); ;) { const { done, value } = await rd.read(); if (done) break; chunks.push(value); got += value.length; status(`Downloading RIFE: ${mb(got)} of ${mb(total)}`, got / total); } | |
| const bytes = new Uint8Array(got); let o = 0; for (const c of chunks) { bytes.set(c, o); o += c.length; } | |
| try { | |
| const w = await (await dir.getFileHandle(MODEL_FILE, { create: true })).createWritable(); await w.write(bytes); await w.close(); | |
| await (await dir.getFileHandle(MODEL_FILE + '.ok', { create: true })).createWritable().then((x) => x.close()); | |
| } catch { /* no storage: it simply downloads again next time */ } | |
| return bytes; | |
| } | |
| const getRife = () => (rifeP ||= (async () => { | |
| const ort = await getOrt(), bytes = await modelBytes(); | |
| status('Starting RIFE on your GPU…', 1); | |
| const rife = await createRife(ort, bytes); showStore(); return rife; | |
| })().catch((e) => { rifeP = null; throw e; })); | |
| // Give back the GPU memory (the model session) and the finished video; the model stays on disk until it is deleted. | |
| async function freeMemory() { | |
| if (rifeP) { try { await (await rifeP).release(); } catch { /* already gone */ } rifeP = null; } | |
| if (ui.video.src.startsWith('blob:')) URL.revokeObjectURL(ui.video.src); | |
| ui.video.removeAttribute('src'); ui.video.load(); ui.result.hidden = true; | |
| } | |
| const showStore = async () => { try { const e = await navigator.storage.estimate(); ui.store.textContent = `This site stores ${mb(e.usage || 0)} in this browser.`; } catch { ui.store.textContent = ''; } }; | |
| ui.free.addEventListener('click', async () => { await freeMemory(); status('GPU memory freed. The model reloads next time you press Interpolate.', 0); }); | |
| ui.wipe.addEventListener('click', async () => { | |
| await freeMemory(); | |
| try { const dir = await navigator.storage.getDirectory(); for await (const [n] of dir.entries()) await dir.removeEntry(n, { recursive: true }); } catch { /* nothing cached */ } | |
| await showStore(); status('Deleted. The model downloads again next time.', 0); | |
| }); | |
| // ---------------------------------------------------------------- input | |
| async function openFile(file) { | |
| if (source) { try { source.input.dispose?.(); } catch { /* ignore */ } source = null; } | |
| ui.result.hidden = true; ui.opts.hidden = true; | |
| status(`Reading ${file.name}…`, 0); | |
| try { | |
| const input = new Input({ source: new BlobSource(file), formats: ALL_FORMATS }); | |
| const vt = await input.getPrimaryVideoTrack(); | |
| if (!vt) throw new Error('no video track in this file'); | |
| if (!(await vt.canDecode())) throw new Error('this browser cannot decode the video codec of this file'); | |
| const stats = await vt.computePacketStats(200), at = await input.getPrimaryAudioTrack(); | |
| const dur = await input.computeDuration(); | |
| source = { file, input, vt, at, fps: stats.averagePacketRate, w: vt.displayWidth, h: vt.displayHeight, dur, frames: Math.round(stats.averagePacketRate * dur) }; | |
| ui.info.textContent = `${file.name}: ${source.w}×${source.h}, ${source.fps.toFixed(2)} fps, ${dur.toFixed(1)} s, about ${source.frames} frames${at ? ', with audio' : ''}`; | |
| ui.opts.hidden = false; status('Pick the frame-rate multiplier and press Interpolate.', 0); | |
| } catch (e) { console.error(e); status(`Cannot open this file: ${e.message}`, 0, true); } | |
| } | |
| ui.file.addEventListener('change', () => ui.file.files[0] && openFile(ui.file.files[0])); | |
| ui.drop.addEventListener('dragover', (e) => { e.preventDefault(); ui.drop.classList.add('over'); }); | |
| ui.drop.addEventListener('dragleave', () => ui.drop.classList.remove('over')); | |
| ui.drop.addEventListener('drop', (e) => { e.preventDefault(); ui.drop.classList.remove('over'); const f = e.dataTransfer.files[0]; if (f) openFile(f); }); | |
| // ---------------------------------------------------------------- interpolate | |
| const even = (n) => Math.max(2, Math.round(n / 2) * 2); | |
| // Decode -> RIFE -> encode, one pair of frames at a time (memory does not grow with the clip, except the finished file). | |
| // Output frame 2i is source frame i untouched, the frames in between are generated at t = k/factor. | |
| async function interpolate(clip, factor, cap) { | |
| let w = clip.w, h = clip.h; | |
| if (cap && h > cap) { w = even(w * cap / h); h = cap; } else { w = even(w); h = even(h); } // yuv420p needs even sizes | |
| const rife = await getRife(); | |
| const pw = padTo(w), ph = padTo(h); | |
| const codec = await getFirstEncodableVideoCodec(['avc', 'vp9', 'av1'], { width: w, height: h }); | |
| if (!codec) throw new Error('this browser cannot encode video at this size'); | |
| const outFps = clip.fps * factor; | |
| const canvas = new OffscreenCanvas(w, h), ctx = canvas.getContext('2d', { willReadFrequently: true }); | |
| const target = new BufferTarget(), output = new Output({ format: new Mp4OutputFormat(), target }); | |
| const video = new CanvasSource(canvas, { codec, bitrate: Math.max(1.5e6, Math.min(40e6, w * h * outFps * 0.1)), keyFrameInterval: 2 }); | |
| output.addVideoTrack(video, { frameRate: outFps }); | |
| let audio = null, audioCfg = null; | |
| if (clip.at) { | |
| try { | |
| audioCfg = await clip.at.getDecoderConfig(); | |
| if (audioCfg && output.format.getSupportedAudioCodecs().includes(clip.at.codec)) { audio = new EncodedAudioPacketSource(clip.at.codec); output.addAudioTrack(audio); } | |
| } catch { audio = null; } // video only | |
| } | |
| await output.start(); | |
| const show = new ImageData(w, h), frameA = new Uint8Array(pw * ph * 3), frameB = new Uint8Array(pw * ph * 3); | |
| const draw = async (rgba, ts, dur) => { show.data.set(rgba); ctx.putImageData(show, 0, 0); await video.add(ts, dur); }; | |
| let prevPx = null, prevTs = 0, lastDur = 1 / clip.fps, cur = frameA, prev = frameB, n = 0, made = 0; | |
| const t0 = performance.now(); | |
| for await (const f of new CanvasSink(clip.vt, { width: w, height: h, fit: 'fill' }).canvases()) { | |
| if (cancel) break; | |
| const own = f.canvas.getContext?.('2d'); // the sink already drew the frame at w x h: read it where it is | |
| if (!own) ctx.drawImage(f.canvas, 0, 0, w, h); | |
| const px = (own || ctx).getImageData(0, 0, w, h).data; | |
| packRgb(px, w, h, pw, ph, cur); | |
| if (prevPx) { | |
| const step = (f.timestamp - prevTs) / factor; | |
| await draw(prevPx, prevTs, step); | |
| for (let k = 1; k < factor; k++) { | |
| const planes = await rife.run(prev, cur, k / factor, pw, ph); | |
| unpackRgba(planes, w, h, pw, ph, show.data); ctx.putImageData(show, 0, 0); | |
| await video.add(prevTs + step * k, step); made++; | |
| } | |
| } | |
| prevPx = px; prevTs = f.timestamp; lastDur = f.duration || lastDur; | |
| [cur, prev] = [prev, cur]; n++; | |
| status(`Frame ${n} of about ${clip.frames} · ${made} generated · ${(made / Math.max(.001, (performance.now() - t0) / 1000)).toFixed(1)} new frames/s`, n / clip.frames); | |
| } | |
| if (prevPx && !cancel) await draw(prevPx, prevTs, lastDur); | |
| if (audio && !cancel) { | |
| status('Copying the audio…'); | |
| let first = true; | |
| for await (const p of new EncodedPacketSink(clip.at).packets()) { await audio.add(p, first ? { decoderConfig: audioCfg } : undefined); first = false; } | |
| } | |
| if (cancel) { await output.cancel(); return null; } | |
| await output.finalize(); | |
| return { blob: new Blob([target.buffer], { type: 'video/mp4' }), codec, w, h, fps: outFps, frames: n + made, made, sec: (performance.now() - t0) / 1000, audio: !!audio }; | |
| } | |
| function showResult(url, name) { | |
| ui.video.src = url; ui.save.href = url; ui.save.download = name; ui.result.hidden = false; | |
| } | |
| ui.go.addEventListener('click', async () => { | |
| if (!source) return; | |
| cancel = false; ui.go.disabled = true; ui.stop.hidden = false; ui.result.hidden = true; | |
| try { | |
| const r = await interpolate(source, +ui.factor.value, +ui.side.value || 0); | |
| if (!r) status('Stopped.', 0); | |
| else { | |
| showResult(URL.createObjectURL(r.blob), source.file.name.replace(/\.[^.]+$/, '') + `_x${ui.factor.value}.mp4`); | |
| status(`Done: ${r.frames} frames at ${r.fps.toFixed(2)} fps (${r.w}×${r.h}, ${r.codec === 'avc' ? 'H.264' : r.codec}), ${r.made} generated in ${r.sec.toFixed(1)} s${source.at && !r.audio ? ' · audio could not be copied' : ''}.`, 1); | |
| } | |
| } catch (e) { console.error(e); status(e?.message || String(e), null, true); } | |
| ui.go.disabled = false; ui.stop.hidden = true; showStore(); | |
| }); | |
| ui.stop.addEventListener('click', () => { cancel = true; }); | |
| // ---------------------------------------------------------------- examples (shipped with the page: the clip and its precomputed x2 result) | |
| const EXAMPLES = [{ label: 'Sample clip (720p, 6 s)', src: 'examples/sample.mp4', result: 'examples/sample_x2.mp4', factor: 2 }]; | |
| for (const ex of EXAMPLES) { | |
| const btn = document.createElement('button'); btn.type = 'button'; btn.textContent = ex.label; | |
| btn.addEventListener('click', async () => { | |
| try { | |
| const blob = await (await fetch(ex.src)).blob(); | |
| await openFile(new File([blob], ex.src.split('/').pop(), { type: blob.type })); | |
| ui.factor.value = String(ex.factor); ui.side.value = '0'; | |
| showResult(ex.result, 'sample_x2.mp4'); | |
| status('Showing the precomputed ×2 result. Press Interpolate to run it yourself on your GPU.', 0); | |
| } catch (e) { status(`Cannot load the example: ${e.message}`, 0, true); } | |
| }); | |
| ui.examples.append(btn); | |
| } | |
| showStore(); | |
| window.__ff = { interpolate, openFile, getRife, getOrt, packRgb, unpackRgba, padTo, get source() { return source; } }; // test hook | |