Skip to content

Play a finished motion-graphics ad in sync with the rough drafts it grew from, and export the breakdown as MP4.

Launch preview: final ad over its black-and-white HyperFrames drafts

wasely97964a516b97
diff --git a/AGENTS.md b/AGENTS.md
index bd60ba5..750c20b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,6 +6,7 @@ This is an independent public UI starter. Keep its history, configuration, and d
- Browser requests must use this project's origin. Never hardcode another local companion or copy personal databases, credentials, renders, or provider settings.
- Preserve the inherited interface. Verify UI changes in a real browser at narrow and wide widths.
- Generation, rendering, and Premiere are unconnected. Keep UI status honest until those services exist.
-- The launch editor is the homepage. Reference media is explicitly imported for the local promotion demo and stays in ignored `.local-media/` and `public/references/` directories. Do not publish it automatically.
+- The launch preview (`demo.html`: full reference on top, super-simple black-and-white HyperFrames drafts per section from `drafts.mjs`, a playhead across equal-size draft cards, frame-accurate MP4 export) is the homepage; the launch editor lives at `/editor`. Reference media is explicitly imported for the local promotion demo and stays in ignored `.local-media/` and `public/references/` directories. Do not publish it automatically.
+- The only published references are the three in `showcase/` (Infinite, SaaS launch sequence, Motion study 08), chosen by the owner and built by `npm run showcase`. The server falls back to `showcase/` when the local library is absent. Never add another reference to `showcase/` or Git without the owner's explicit choice.
- Imported segments are non-destructive time ranges. Preserve the original source videos. The preview is browser composition, not AI generation.
- Preserve bundled third-party notices. Do not introduce a project license without the owner's decision.
diff --git a/README.md b/README.md
index 329ade6..1a7facc 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,12 @@
# Null
-A launch-film concept editor built on Null Motion's visual foundation and MotionClone's reference-segment workflow. A large branded preview sits above a clip timeline and a library of reference moments.
+A launch-film preview: a finished motion-graphics ad plays on top, and underneath it the super-simple black-and-white HyperFrames drafts it grew from — one per section, each an HTML scene driven by a GSAP timeline. A playhead runs across the drafts; the draft for the section on screen follows the film exactly and is outlined in orange. **Download → Whole preview** renders the film and its drafts frame by frame into a high-bitrate MP4 with the film's audio (Chrome or Edge).
-This is a **promotion demo**, with working reference playback, in/out trimming, clip insertion, drag reordering, undo/redo, search, browser-local saving, and live brand controls. The film preview combines source clips with a browser-rendered brand composition. It is not an AI-reconstructed or exported video; generation and rendering are not connected.
+The earlier launch editor (reference timeline, trimming, brand controls) is at `/editor`, and the original Null Motion gallery at `/index.html`.
-The original Null Motion gallery remains at `/index.html`.
+## Showcase
+
+The repository ships three references in `showcase/`: **Infinite · Global payments**, **SaaS · Launch sequence** and **Motion study 08**, with their drafts. They are reference clips from other creators, shown as examples; they are not claims of commissioned work. A fresh checkout plays these three. A locally imported library (below) takes precedence and is never committed.
## Run locally
@@ -26,10 +28,12 @@ python scripts/import-motionclone.py --source /path/to/MotionClone
The importer includes saved source videos and the standalone Nexa/Troovy reference folders. It creates non-destructive segments of roughly four seconds, extracts a thumbnail for each segment, and links the videos into `.local-media/`. The source and this project must be on the same filesystem for hard links. Original files are read only; no encoding or source cutting occurs. Full source videos remain playable and segment in/out points are editable.
-Media, reference titles, and extracted thumbnails stay local and are excluded from Git. The server supports byte ranges so seeking does not read entire videos into memory. A fresh checkout opens with an empty library until references are imported or uploaded. Browser uploads last for the current session.
+Media, reference titles, and extracted thumbnails stay local and are excluded from Git. The server supports byte ranges so seeking does not read entire videos into memory. A fresh checkout shows only the showcase until references are imported. Browser uploads last for the current session.
The curated local library contains 20 motion-graphics references and 142 segments. The live-action Astra promo is excluded by `data/reference-policy.json`; reimporting does not restore it. These are reference clips, not claims of commissioned work. Public hosting needs separately supplied media you can distribute.
+`npm run showcase` rebuilds `showcase/` from the local library (re-encoded 1080p video, audio, posters, sections and drafts for the three showcase references). `scripts/plan-sections.mjs` splits references into sections at scene changes; the drafts themselves are authored in `public/references/drafts.json`.
+
The preview displays source footage full-frame at its original proportions, with optional brand overlays, safe-area guides, and presentation mode. Brand layers do not rewrite text already in the footage. Saved custom sequences are retained; excluded references are removed from saved timelines when loaded.
The optional `PORT` environment variable changes the port. `HOST` defaults to `127.0.0.1`; set it to your hosting environment's required bind address when deploying. This repository does not provision a hosted service.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 595a839..adf8255 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -2,4 +2,8 @@
`public/_vendor/gsap.min.js` is GSAP 3.14.2. Its original copyright and license header is preserved. License terms: <https://gsap.com/standard-license>.
+`public/_vendor/mp4-muxer.js` is mp4-muxer 5.2.1 by Vanilagy, MIT License (Copyright (c) 2023 Vanilagy). License: <https://github.com/Vanilagy/mp4-muxer/blob/main/LICENSE>.
+
+`public/_vendor/mp4-muxer.js` is mp4-muxer 5.2.1 by Vanilagy, MIT License (Copyright (c) 2023 Vanilagy). License: <https://github.com/Vanilagy/mp4-muxer/blob/main/LICENSE>.
+
Template previews include third-party application marks for illustrative purposes. Those marks remain the property of their respective owners; their inclusion does not imply endorsement or grant trademark rights.
diff --git a/media.js b/media.js
index 925a4d6..32000a1 100644
--- a/media.js
+++ b/media.js
@@ -1,5 +1,6 @@
import { createReadStream } from 'node:fs';
-import { stat } from 'node:fs/promises';
+import { stat, rename, unlink } from 'node:fs/promises';
+import { spawn } from 'node:child_process';
export function byteRange(value, size) {
const match = /^bytes=(\d*)-(\d*)$/.exec(value || '');
@@ -8,14 +9,14 @@ export function byteRange(value, size) {
const end = match[1] && match[2] ? Math.min(size - 1, Number(match[2])) : size - 1;
return Number.isSafeInteger(start) && Number.isSafeInteger(end) && start >= 0 && start <= end && start < size ? { start, end } : null;
}
-export async function streamVideo(request, response, filename) {
+export async function streamVideo(request, response, filename, type = 'video/mp4') {
let size;
try { size = (await stat(filename)).size; } catch {
response.writeHead(404); response.end('Reference unavailable.'); return;
}
const range = request.headers.range ? byteRange(request.headers.range, size) : { start: 0, end: size - 1 };
if (!range) { response.writeHead(416, { 'Content-Range': `bytes */${size}` }); response.end(); return; }
- const headers = { 'Content-Type': 'video/mp4', 'Accept-Ranges': 'bytes', 'Content-Length': range.end - range.start + 1, 'Cache-Control': 'private, max-age=3600' };
+ const headers = { 'Content-Type': type, 'Accept-Ranges': 'bytes', 'Content-Length': range.end - range.start + 1, 'Cache-Control': 'private, max-age=3600' };
if (request.headers.range) headers['Content-Range'] = `bytes ${range.start}-${range.end}/${size}`;
response.writeHead(request.headers.range ? 206 : 200, headers);
if (request.method === 'HEAD') { response.end(); return; }
@@ -24,3 +25,23 @@ export async function streamVideo(request, response, filename) {
response.on('close', () => stream.destroy());
stream.pipe(response);
}
+
+// The preview export needs the reference's audio on its own. Copy the AAC track out of the
+// source once (no re-encode) and keep it beside the video; later requests reuse it.
+const extracting = new Map();
+export function extractAudio(video, audio) {
+ if (!extracting.has(audio)) {
+ extracting.set(audio, (async () => {
+ try { await stat(audio); return true; } catch {}
+ const partial = audio + '.part';
+ const ok = await new Promise(resolve => {
+ const ffmpeg = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-y', '-i', video, '-vn', '-c:a', 'aac', '-b:a', '192k', '-f', 'adts', partial]);
+ ffmpeg.on('error', () => resolve(false));
+ ffmpeg.on('close', code => resolve(code === 0));
+ });
+ if (ok) await rename(partial, audio); else await unlink(partial).catch(() => {});
+ return ok;
+ })().finally(() => extracting.delete(audio)));
+ }
+ return extracting.get(audio);
+}
diff --git a/package.json b/package.json
index 0708f41..beb53a4 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,9 @@
"start": "node server.js",
"dev": "node --watch server.js",
"test": "node --test",
- "check": "node scripts/check.js"
+ "check": "node scripts/check.js",
+ "waveforms": "node scripts/build-waveforms.mjs",
+ "showcase": "node scripts/build-showcase.mjs"
},
"engines": { "node": ">=22" }
}
diff --git a/public/_vendor/mp4-muxer.js b/public/_vendor/mp4-muxer.js
new file mode 100644
index 0000000..10cbbd3
--- /dev/null
+++ b/public/_vendor/mp4-muxer.js
@@ -0,0 +1,1904 @@
+"use strict";
+var Mp4Muxer = (() => {
+ var __defProp = Object.defineProperty;
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
+ var __getOwnPropNames = Object.getOwnPropertyNames;
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
+ var __export = (target, all) => {
+ for (var name in all)
+ __defProp(target, name, { get: all[name], enumerable: true });
+ };
+ var __copyProps = (to, from, except, desc) => {
+ if (from && typeof from === "object" || typeof from === "function") {
+ for (let key of __getOwnPropNames(from))
+ if (!__hasOwnProp.call(to, key) && key !== except)
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
+ }
+ return to;
+ };
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
+ var __accessCheck = (obj, member, msg) => {
+ if (!member.has(obj))
+ throw TypeError("Cannot " + msg);
+ };
+ var __privateGet = (obj, member, getter) => {
+ __accessCheck(obj, member, "read from private field");
+ return getter ? getter.call(obj) : member.get(obj);
+ };
+ var __privateAdd = (obj, member, value) => {
+ if (member.has(obj))
+ throw TypeError("Cannot add the same private member more than once");
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
+ };
+ var __privateSet = (obj, member, value, setter) => {
+ __accessCheck(obj, member, "write to private field");
+ setter ? setter.call(obj, value) : member.set(obj, value);
+ return value;
+ };
+ var __privateWrapper = (obj, member, setter, getter) => ({
+ set _(value) {
+ __privateSet(obj, member, value, setter);
+ },
+ get _() {
+ return __privateGet(obj, member, getter);
+ }
+ });
+ var __privateMethod = (obj, member, method) => {
+ __accessCheck(obj, member, "access private method");
+ return method;
+ };
+
+ // src/index.ts
+ var src_exports = {};
+ __export(src_exports, {
+ ArrayBufferTarget: () => ArrayBufferTarget,
+ FileSystemWritableFileStreamTarget: () => FileSystemWritableFileStreamTarget,
+ Muxer: () => Muxer,
+ StreamTarget: () => StreamTarget
+ });
+
+ // src/misc.ts
+ var bytes = new Uint8Array(8);
+ var view = new DataView(bytes.buffer);
+ var u8 = (value) => {
+ return [(value % 256 + 256) % 256];
+ };
+ var u16 = (value) => {
+ view.setUint16(0, value, false);
+ return [bytes[0], bytes[1]];
+ };
+ var i16 = (value) => {
+ view.setInt16(0, value, false);
+ return [bytes[0], bytes[1]];
+ };
+ var u24 = (value) => {
+ view.setUint32(0, value, false);
+ return [bytes[1], bytes[2], bytes[3]];
+ };
+ var u32 = (value) => {
+ view.setUint32(0, value, false);
+ return [bytes[0], bytes[1], bytes[2], bytes[3]];
+ };
+ var i32 = (value) => {
+ view.setInt32(0, value, false);
+ return [bytes[0], bytes[1], bytes[2], bytes[3]];
+ };
+ var u64 = (value) => {
+ view.setUint32(0, Math.floor(value / 2 ** 32), false);
+ view.setUint32(4, value, false);
+ return [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
+ };
+ var fixed_8_8 = (value) => {
+ view.setInt16(0, 2 ** 8 * value, false);
+ return [bytes[0], bytes[1]];
+ };
+ var fixed_16_16 = (value) => {
+ view.setInt32(0, 2 ** 16 * value, false);
+ return [bytes[0], bytes[1], bytes[2], bytes[3]];
+ };
+ var fixed_2_30 = (value) => {
+ view.setInt32(0, 2 ** 30 * value, false);
+ return [bytes[0], bytes[1], bytes[2], bytes[3]];
+ };
+ var ascii = (text, nullTerminated = false) => {
+ let bytes2 = Array(text.length).fill(null).map((_, i) => text.charCodeAt(i));
+ if (nullTerminated)
+ bytes2.push(0);
+ return bytes2;
+ };
+ var last = (arr) => {
+ return arr && arr[arr.length - 1];
+ };
+ var lastPresentedSample = (samples) => {
+ let result = void 0;
+ for (let sample of samples) {
+ if (!result || sample.presentationTimestamp > result.presentationTimestamp) {
+ result = sample;
+ }
+ }
+ return result;
+ };
+ var intoTimescale = (timeInSeconds, timescale, round = true) => {
+ let value = timeInSeconds * timescale;
+ return round ? Math.round(value) : value;
+ };
+ var rotationMatrix = (rotationInDegrees) => {
+ let theta = rotationInDegrees * (Math.PI / 180);
+ let cosTheta = Math.cos(theta);
+ let sinTheta = Math.sin(theta);
+ return [
+ cosTheta,
+ sinTheta,
+ 0,
+ -sinTheta,
+ cosTheta,
+ 0,
+ 0,
+ 0,
+ 1
+ ];
+ };
+ var IDENTITY_MATRIX = rotationMatrix(0);
+ var matrixToBytes = (matrix) => {
+ return [
+ fixed_16_16(matrix[0]),
+ fixed_16_16(matrix[1]),
+ fixed_2_30(matrix[2]),
+ fixed_16_16(matrix[3]),
+ fixed_16_16(matrix[4]),
+ fixed_2_30(matrix[5]),
+ fixed_16_16(matrix[6]),
+ fixed_16_16(matrix[7]),
+ fixed_2_30(matrix[8])
+ ];
+ };
+ var deepClone = (x) => {
+ if (!x)
+ return x;
+ if (typeof x !== "object")
+ return x;
+ if (Array.isArray(x))
+ return x.map(deepClone);
+ return Object.fromEntries(Object.entries(x).map(([key, value]) => [key, deepClone(value)]));
+ };
+ var isU32 = (value) => {
+ return value >= 0 && value < 2 ** 32;
+ };
+
+ // src/box.ts
+ var box = (type, contents, children) => ({
+ type,
+ contents: contents && new Uint8Array(contents.flat(10)),
+ children
+ });
+ var fullBox = (type, version, flags, contents, children) => box(
+ type,
+ [u8(version), u24(flags), contents ?? []],
+ children
+ );
+ var ftyp = (details) => {
+ let minorVersion = 512;
+ if (details.fragmented)
+ return box("ftyp", [
+ ascii("iso5"),
+ // Major brand
+ u32(minorVersion),
+ // Minor version
+ // Compatible brands
+ ascii("iso5"),
+ ascii("iso6"),
+ ascii("mp41")
+ ]);
+ return box("ftyp", [
+ ascii("isom"),
+ // Major brand
+ u32(minorVersion),
+ // Minor version
+ // Compatible brands
+ ascii("isom"),
+ details.holdsAvc ? ascii("avc1") : [],
+ ascii("mp41")
+ ]);
+ };
+ var mdat = (reserveLargeSize) => ({ type: "mdat", largeSize: reserveLargeSize });
+ var free = (size) => ({ type: "free", size });
+ var moov = (tracks, creationTime, fragmented = false) => box("moov", null, [
+ mvhd(creationTime, tracks),
+ ...tracks.map((x) => trak(x, creationTime)),
+ fragmented ? mvex(tracks) : null
+ ]);
+ var mvhd = (creationTime, tracks) => {
+ let duration = intoTimescale(Math.max(
+ 0,
+ ...tracks.filter((x) => x.samples.length > 0).map((x) => {
+ const lastSample = lastPresentedSample(x.samples);
+ return lastSample.presentationTimestamp + lastSample.duration;
+ })
+ ), GLOBAL_TIMESCALE);
+ let nextTrackId = Math.max(...tracks.map((x) => x.id)) + 1;
+ let needsU64 = !isU32(creationTime) || !isU32(duration);
+ let u32OrU64 = needsU64 ? u64 : u32;
+ return fullBox("mvhd", +needsU64, 0, [
+ u32OrU64(creationTime),
+ // Creation time
+ u32OrU64(creationTime),
+ // Modification time
+ u32(GLOBAL_TIMESCALE),
+ // Timescale
+ u32OrU64(duration),
+ // Duration
+ fixed_16_16(1),
+ // Preferred rate
+ fixed_8_8(1),
+ // Preferred volume
+ Array(10).fill(0),
+ // Reserved
+ matrixToBytes(IDENTITY_MATRIX),
+ // Matrix
+ Array(24).fill(0),
+ // Pre-defined
+ u32(nextTrackId)
+ // Next track ID
+ ]);
+ };
+ var trak = (track, creationTime) => box("trak", null, [
+ tkhd(track, creationTime),
+ mdia(track, creationTime)
+ ]);
+ var tkhd = (track, creationTime) => {
+ let lastSample = lastPresentedSample(track.samples);
+ let durationInGlobalTimescale = intoTimescale(
+ lastSample ? lastSample.presentationTimestamp + lastSample.duration : 0,
+ GLOBAL_TIMESCALE
+ );
+ let needsU64 = !isU32(creationTime) || !isU32(durationInGlobalTimescale);
+ let u32OrU64 = needsU64 ? u64 : u32;
+ let matrix;
+ if (track.info.type === "video") {
+ matrix = typeof track.info.rotation === "number" ? rotationMatrix(track.info.rotation) : track.info.rotation;
+ } else {
+ matrix = IDENTITY_MATRIX;
+ }
+ return fullBox("tkhd", +needsU64, 3, [
+ u32OrU64(creationTime),
+ // Creation time
+ u32OrU64(creationTime),
+ // Modification time
+ u32(track.id),
+ // Track ID
+ u32(0),
+ // Reserved
+ u32OrU64(durationInGlobalTimescale),
+ // Duration
+ Array(8).fill(0),
+ // Reserved
+ u16(0),
+ // Layer
+ u16(0),
+ // Alternate group
+ fixed_8_8(track.info.type === "audio" ? 1 : 0),
+ // Volume
+ u16(0),
+ // Reserved
+ matrixToBytes(matrix),
+ // Matrix
+ fixed_16_16(track.info.type === "video" ? track.info.width : 0),
+ // Track width
+ fixed_16_16(track.info.type === "video" ? track.info.height : 0)
+ // Track height
+ ]);
+ };
+ var mdia = (track, creationTime) => box("mdia", null, [
+ mdhd(track, creationTime),
+ hdlr(track.info.type === "video" ? "vide" : "soun"),
+ minf(track)
+ ]);
+ var mdhd = (track, creationTime) => {
+ let lastSample = lastPresentedSample(track.samples);
+ let localDuration = intoTimescale(
+ lastSample ? lastSample.presentationTimestamp + lastSample.duration : 0,
+ track.timescale
+ );
+ let needsU64 = !isU32(creationTime) || !isU32(localDuration);
+ let u32OrU64 = needsU64 ? u64 : u32;
+ return fullBox("mdhd", +needsU64, 0, [
+ u32OrU64(creationTime),
+ // Creation time
+ u32OrU64(creationTime),
+ // Modification time
+ u32(track.timescale),
+ // Timescale
+ u32OrU64(localDuration),
+ // Duration
+ u16(21956),
+ // Language ("und", undetermined)
+ u16(0)
+ // Quality
+ ]);
+ };
+ var hdlr = (componentSubtype) => fullBox("hdlr", 0, 0, [
+ ascii("mhlr"),
+ // Component type
+ ascii(componentSubtype),
+ // Component subtype
+ u32(0),
+ // Component manufacturer
+ u32(0),
+ // Component flags
+ u32(0),
+ // Component flags mask
+ ascii("mp4-muxer-hdlr", true)
+ // Component name
+ ]);
+ var minf = (track) => box("minf", null, [
+ track.info.type === "video" ? vmhd() : smhd(),
+ dinf(),
+ stbl(track)
+ ]);
+ var vmhd = () => fullBox("vmhd", 0, 1, [
+ u16(0),
+ // Graphics mode
+ u16(0),
+ // Opcolor R
+ u16(0),
+ // Opcolor G
+ u16(0)
+ // Opcolor B
+ ]);
+ var smhd = () => fullBox("smhd", 0, 0, [
+ u16(0),
+ // Balance
+ u16(0)
+ // Reserved
+ ]);
+ var dinf = () => box("dinf", null, [
+ dref()
+ ]);
+ var dref = () => fullBox("dref", 0, 0, [
+ u32(1)
+ // Entry count
+ ], [
+ url()
+ ]);
+ var url = () => fullBox("url ", 0, 1);
+ var stbl = (track) => {
+ const needsCtts = track.compositionTimeOffsetTable.length > 1 || track.compositionTimeOffsetTable.some((x) => x.sampleCompositionTimeOffset !== 0);
+ return box("stbl", null, [
+ stsd(track),
+ stts(track),
+ stss(track),
+ stsc(track),
+ stsz(track),
+ stco(track),
+ needsCtts ? ctts(track) : null
+ ]);
+ };
+ var stsd = (track) => fullBox("stsd", 0, 0, [
+ u32(1)
+ // Entry count
+ ], [
+ track.info.type === "video" ? videoSampleDescription(
+ VIDEO_CODEC_TO_BOX_NAME[track.info.codec],
+ track
+ ) : soundSampleDescription(
+ AUDIO_CODEC_TO_BOX_NAME[track.info.codec],
+ track
+ )
+ ]);
+ var videoSampleDescription = (compressionType, track) => box(compressionType, [
+ Array(6).fill(0),
+ // Reserved
+ u16(1),
+ // Data reference index
+ u16(0),
+ // Pre-defined
+ u16(0),
+ // Reserved
+ Array(12).fill(0),
+ // Pre-defined
+ u16(track.info.width),
+ // Width
+ u16(track.info.height),
+ // Height
+ u32(4718592),
+ // Horizontal resolution
+ u32(4718592),
+ // Vertical resolution
+ u32(0),
+ // Reserved
+ u16(1),
+ // Frame count
+ Array(32).fill(0),
+ // Compressor name
+ u16(24),
+ // Depth
+ i16(65535)
+ // Pre-defined
+ ], [
+ VIDEO_CODEC_TO_CONFIGURATION_BOX[track.info.codec](track),
+ track.info.decoderConfig.colorSpace ? colr(track) : null
+ ]);
+ var COLOR_PRIMARIES_MAP = {
+ "bt709": 1,
+ // ITU-R BT.709
+ "bt470bg": 5,
+ // ITU-R BT.470BG
+ "smpte170m": 6
+ // ITU-R BT.601 525 - SMPTE 170M
+ };
+ var TRANSFER_CHARACTERISTICS_MAP = {
+ "bt709": 1,
+ // ITU-R BT.709
+ "smpte170m": 6,
+ // SMPTE 170M
+ "iec61966-2-1": 13
+ // IEC 61966-2-1
+ };
+ var MATRIX_COEFFICIENTS_MAP = {
+ "rgb": 0,
+ // Identity
+ "bt709": 1,
+ // ITU-R BT.709
+ "bt470bg": 5,
+ // ITU-R BT.470BG
+ "smpte170m": 6
+ // SMPTE 170M
+ };
+ var colr = (track) => box("colr", [
+ ascii("nclx"),
+ // Colour type
+ u16(COLOR_PRIMARIES_MAP[track.info.decoderConfig.colorSpace.primaries]),
+ // Colour primaries
+ u16(TRANSFER_CHARACTERISTICS_MAP[track.info.decoderConfig.colorSpace.transfer]),
+ // Transfer characteristics
+ u16(MATRIX_COEFFICIENTS_MAP[track.info.decoderConfig.colorSpace.matrix]),
+ // Matrix coefficients
+ u8((track.info.decoderConfig.colorSpace.fullRange ? 1 : 0) << 7)
+ // Full range flag
+ ]);
+ var avcC = (track) => track.info.decoderConfig && box("avcC", [
+ // For AVC, description is an AVCDecoderConfigurationRecord, so nothing else to do here
+ ...new Uint8Array(track.info.decoderConfig.description)
+ ]);
+ var hvcC = (track) => track.info.decoderConfig && box("hvcC", [
+ // For HEVC, description is a HEVCDecoderConfigurationRecord, so nothing else to do here
+ ...new Uint8Array(track.info.decoderConfig.description)
+ ]);
+ var vpcC = (track) => {
+ if (!track.info.decoderConfig) {
+ return null;
+ }
+ let decoderConfig = track.info.decoderConfig;
+ if (!decoderConfig.colorSpace) {
+ throw new Error(`'colorSpace' is required in the decoder config for VP9.`);
+ }
+ let parts = decoderConfig.codec.split(".");
+ let profile = Number(parts[1]);
+ let level = Number(parts[2]);
+ let bitDepth = Number(parts[3]);
+ let chromaSubsampling = 0;
+ let thirdByte = (bitDepth << 4) + (chromaSubsampling << 1) + Number(decoderConfig.colorSpace.fullRange);
+ let colourPrimaries = 2;
+ let transferCharacteristics = 2;
+ let matrixCoefficients = 2;
+ return fullBox("vpcC", 1, 0, [
+ u8(profile),
+ // Profile
+ u8(level),
+ // Level
+ u8(thirdByte),
+ // Bit depth, chroma subsampling, full range
+ u8(colourPrimaries),
+ // Colour primaries
+ u8(transferCharacteristics),
+ // Transfer characteristics
+ u8(matrixCoefficients),
+ // Matrix coefficients
+ u16(0)
+ // Codec initialization data size
+ ]);
+ };
+ var av1C = () => {
+ let marker = 1;
+ let version = 1;
+ let firstByte = (marker << 7) + version;
+ return box("av1C", [
+ firstByte,
+ 0,
+ 0,
+ 0
+ ]);
+ };
+ var soundSampleDescription = (compressionType, track) => box(compressionType, [
+ Array(6).fill(0),
+ // Reserved
+ u16(1),
+ // Data reference index
+ u16(0),
+ // Version
+ u16(0),
+ // Revision level
+ u32(0),
+ // Vendor
+ u16(track.info.numberOfChannels),
+ // Number of channels
+ u16(16),
+ // Sample size (bits)
+ u16(0),
+ // Compression ID
+ u16(0),
+ // Packet size
+ fixed_16_16(track.info.sampleRate)
+ // Sample rate
+ ], [
+ AUDIO_CODEC_TO_CONFIGURATION_BOX[track.info.codec](track)
+ ]);
+ var esds = (track) => {
+ let description = new Uint8Array(track.info.decoderConfig.description);
+ return fullBox("esds", 0, 0, [
+ // https://stackoverflow.com/a/54803118
+ u32(58753152),
+ // TAG(3) = Object Descriptor ([2])
+ u8(32 + description.byteLength),
+ // length of this OD (which includes the next 2 tags)
+ u16(1),
+ // ES_ID = 1
+ u8(0),
+ // flags etc = 0
+ u32(75530368),
+ // TAG(4) = ES Descriptor ([2]) embedded in above OD
+ u8(18 + description.byteLength),
+ // length of this ESD
+ u8(64),
+ // MPEG-4 Audio
+ u8(21),
+ // stream type(6bits)=5 audio, flags(2bits)=1
+ u24(0),
+ // 24bit buffer size
+ u32(130071),
+ // max bitrate
+ u32(130071),
+ // avg bitrate
+ u32(92307584),
+ // TAG(5) = ASC ([2],[3]) embedded in above OD
+ u8(description.byteLength),
+ // length
+ ...description,
+ u32(109084800),
+ // TAG(6)
+ u8(1),
+ // length
+ u8(2)
+ // data
+ ]);
+ };
+ var dOps = (track) => {
+ let preskip = 3840;
+ let gain = 0;
+ const description = track.info.decoderConfig?.description;
+ if (description) {
+ if (description.byteLength < 18) {
+ throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");
+ }
+ const view2 = ArrayBuffer.isView(description) ? new DataView(description.buffer, description.byteOffset, description.byteLength) : new DataView(description);
+ preskip = view2.getUint16(10, true);
+ gain = view2.getInt16(14, true);
+ }
+ return box("dOps", [
+ u8(0),
+ // Version
+ u8(track.info.numberOfChannels),
+ // OutputChannelCount
+ u16(preskip),
+ u32(track.info.sampleRate),
+ // InputSampleRate
+ fixed_8_8(gain),
+ // OutputGain
+ u8(0)
+ // ChannelMappingFamily
+ ]);
+ };
+ var stts = (track) => {
+ return fullBox("stts", 0, 0, [
+ u32(track.timeToSampleTable.length),
+ // Number of entries
+ track.timeToSampleTable.map((x) => [
+ // Time-to-sample table
+ u32(x.sampleCount),
+ // Sample count
+ u32(x.sampleDelta)
+ // Sample duration
+ ])
+ ]);
+ };
+ var stss = (track) => {
+ if (track.samples.every((x) => x.type === "key"))
+ return null;
+ let keySamples = [...track.samples.entries()].filter(([, sample]) => sample.type === "key");
+ return fullBox("stss", 0, 0, [
+ u32(keySamples.length),
+ // Number of entries
+ keySamples.map(([index]) => u32(index + 1))
+ // Sync sample table
+ ]);
+ };
+ var stsc = (track) => {
+ return fullBox("stsc", 0, 0, [
+ u32(track.compactlyCodedChunkTable.length),
+ // Number of entries
+ track.compactlyCodedChunkTable.map((x) => [
+ // Sample-to-chunk table
+ u32(x.firstChunk),
+ // First chunk
+ u32(x.samplesPerChunk),
+ // Samples per chunk
+ u32(1)
+ // Sample description index
+ ])
+ ]);
+ };
+ var stsz = (track) => fullBox("stsz", 0, 0, [
+ u32(0),
+ // Sample size (0 means non-constant size)
+ u32(track.samples.length),
+ // Number of entries
+ track.samples.map((x) => u32(x.size))
+ // Sample size table
+ ]);
+ var stco = (track) => {
+ if (track.finalizedChunks.length > 0 && last(track.finalizedChunks).offset >= 2 ** 32) {
+ return fullBox("co64", 0, 0, [
+ u32(track.finalizedChunks.length),
+ // Number of entries
+ track.finalizedChunks.map((x) => u64(x.offset))
+ // Chunk offset table
+ ]);
+ }
+ return fullBox("stco", 0, 0, [
+ u32(track.finalizedChunks.length),
+ // Number of entries
+ track.finalizedChunks.map((x) => u32(x.offset))
+ // Chunk offset table
+ ]);
+ };
+ var ctts = (track) => {
+ return fullBox("ctts", 0, 0, [
+ u32(track.compositionTimeOffsetTable.length),
+ // Number of entries
+ track.compositionTimeOffsetTable.map((x) => [
+ // Time-to-sample table
+ u32(x.sampleCount),
+ // Sample count
+ u32(x.sampleCompositionTimeOffset)
+ // Sample offset
+ ])
+ ]);
+ };
+ var mvex = (tracks) => {
+ return box("mvex", null, tracks.map(trex));
+ };
+ var trex = (track) => {
+ return fullBox("trex", 0, 0, [
+ u32(track.id),
+ // Track ID
+ u32(1),
+ // Default sample description index
+ u32(0),
+ // Default sample duration
+ u32(0),
+ // Default sample size
+ u32(0)
+ // Default sample flags
+ ]);
+ };
+ var moof = (sequenceNumber, tracks) => {
+ return box("moof", null, [
+ mfhd(sequenceNumber),
+ ...tracks.map(traf)
+ ]);
+ };
+ var mfhd = (sequenceNumber) => {
+ return fullBox("mfhd", 0, 0, [
+ u32(sequenceNumber)
+ // Sequence number
+ ]);
+ };
+ var fragmentSampleFlags = (sample) => {
+ let byte1 = 0;
+ let byte2 = 0;
+ let byte3 = 0;
+ let byte4 = 0;
+ let sampleIsDifferenceSample = sample.type === "delta";
+ byte2 |= +sampleIsDifferenceSample;
+ if (sampleIsDifferenceSample) {
+ byte1 |= 1;
+ } else {
+ byte1 |= 2;
+ }
+ return byte1 << 24 | byte2 << 16 | byte3 << 8 | byte4;
+ };
+ var traf = (track) => {
+ return box("traf", null, [
+ tfhd(track),
+ tfdt(track),
+ trun(track)
+ ]);
+ };
+ var tfhd = (track) => {
+ let tfFlags = 0;
+ tfFlags |= 8;
+ tfFlags |= 16;
+ tfFlags |= 32;
+ tfFlags |= 131072;
+ let referenceSample = track.currentChunk.samples[1] ?? track.currentChunk.samples[0];
+ let referenceSampleInfo = {
+ duration: referenceSample.timescaleUnitsToNextSample,
+ size: referenceSample.size,
+ flags: fragmentSampleFlags(referenceSample)
+ };
+ return fullBox("tfhd", 0, tfFlags, [
+ u32(track.id),
+ // Track ID
+ u32(referenceSampleInfo.duration),
+ // Default sample duration
+ u32(referenceSampleInfo.size),
+ // Default sample size
+ u32(referenceSampleInfo.flags)
+ // Default sample flags
+ ]);
+ };
+ var tfdt = (track) => {
+ return fullBox("tfdt", 1, 0, [
+ u64(intoTimescale(track.currentChunk.startTimestamp, track.timescale))
+ // Base Media Decode Time
+ ]);
+ };
+ var trun = (track) => {
+ let allSampleDurations = track.currentChunk.samples.map((x) => x.timescaleUnitsToNextSample);
+ let allSampleSizes = track.currentChunk.samples.map((x) => x.size);
+ let allSampleFlags = track.currentChunk.samples.map(fragmentSampleFlags);
+ let allSampleCompositionTimeOffsets = track.currentChunk.samples.map((x) => intoTimescale(x.presentationTimestamp - x.decodeTimestamp, track.timescale));
+ let uniqueSampleDurations = new Set(allSampleDurations);
+ let uniqueSampleSizes = new Set(allSampleSizes);
+ let uniqueSampleFlags = new Set(allSampleFlags);
+ let uniqueSampleCompositionTimeOffsets = new Set(allSampleCompositionTimeOffsets);
+ let firstSampleFlagsPresent = uniqueSampleFlags.size === 2 && allSampleFlags[0] !== allSampleFlags[1];
+ let sampleDurationPresent = uniqueSampleDurations.size > 1;
+ let sampleSizePresent = uniqueSampleSizes.size > 1;
+ let sampleFlagsPresent = !firstSampleFlagsPresent && uniqueSampleFlags.size > 1;
+ let sampleCompositionTimeOffsetsPresent = uniqueSampleCompositionTimeOffsets.size > 1 || [...uniqueSampleCompositionTimeOffsets].some((x) => x !== 0);
+ let flags = 0;
+ flags |= 1;
+ flags |= 4 * +firstSampleFlagsPresent;
+ flags |= 256 * +sampleDurationPresent;
+ flags |= 512 * +sampleSizePresent;
+ flags |= 1024 * +sampleFlagsPresent;
+ flags |= 2048 * +sampleCompositionTimeOffsetsPresent;
+ return fullBox("trun", 1, flags, [
+ u32(track.currentChunk.samples.length),
+ // Sample count
+ u32(track.currentChunk.offset - track.currentChunk.moofOffset || 0),
+ // Data offset
+ firstSampleFlagsPresent ? u32(allSampleFlags[0]) : [],
+ track.currentChunk.samples.map((_, i) => [
+ sampleDurationPresent ? u32(allSampleDurations[i]) : [],
+ // Sample duration
+ sampleSizePresent ? u32(allSampleSizes[i]) : [],
+ // Sample size
+ sampleFlagsPresent ? u32(allSampleFlags[i]) : [],
+ // Sample flags
+ // Sample composition time offsets
+ sampleCompositionTimeOffsetsPresent ? i32(allSampleCompositionTimeOffsets[i]) : []
+ ])
+ ]);
+ };
+ var mfra = (tracks) => {
+ return box("mfra", null, [
+ ...tracks.map(tfra),
+ mfro()
+ ]);
+ };
+ var tfra = (track, trackIndex) => {
+ let version = 1;
+ return fullBox("tfra", version, 0, [
+ u32(track.id),
+ // Track ID
+ u32(63),
+ // This specifies that traf number, trun number and sample number are 32-bit ints
+ u32(track.finalizedChunks.length),
+ // Number of entries
+ track.finalizedChunks.map((chunk) => [
+ u64(intoTimescale(chunk.startTimestamp, track.timescale)),
+ // Time
+ u64(chunk.moofOffset),
+ // moof offset
+ u32(trackIndex + 1),
+ // traf number
+ u32(1),
+ // trun number
+ u32(1)
+ // Sample number
+ ])
+ ]);
+ };
+ var mfro = () => {
+ return fullBox("mfro", 0, 0, [
+ // This value needs to be overwritten manually from the outside, where the actual size of the enclosing mfra box
+ // is known
+ u32(0)
+ // Size
+ ]);
+ };
+ var VIDEO_CODEC_TO_BOX_NAME = {
+ "avc": "avc1",
+ "hevc": "hvc1",
+ "vp9": "vp09",
+ "av1": "av01"
+ };
+ var VIDEO_CODEC_TO_CONFIGURATION_BOX = {
+ "avc": avcC,
+ "hevc": hvcC,
+ "vp9": vpcC,
+ "av1": av1C
+ };
+ var AUDIO_CODEC_TO_BOX_NAME = {
+ "aac": "mp4a",
+ "opus": "Opus"
+ };
+ var AUDIO_CODEC_TO_CONFIGURATION_BOX = {
+ "aac": esds,
+ "opus": dOps
+ };
+
+ // src/target.ts
+ var isTarget = Symbol("isTarget");
+ var Target = class {
+ };
+ isTarget;
+ var ArrayBufferTarget = class extends Target {
+ constructor() {
+ super(...arguments);
+ this.buffer = null;
+ }
+ };
+ var StreamTarget = class extends Target {
+ constructor(options) {
+ super();
+ this.options = options;
+ if (typeof options !== "object") {
+ throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");
+ }
+ if (options.onData) {
+ if (typeof options.onData !== "function") {
+ throw new TypeError("options.onData, when provided, must be a function.");
+ }
+ if (options.onData.length < 2) {
+ throw new TypeError(
+ "options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs."
+ );
+ }
+ }
+ if (options.chunked !== void 0 && typeof options.chunked !== "boolean") {
+ throw new TypeError("options.chunked, when provided, must be a boolean.");
+ }
+ if (options.chunkSize !== void 0 && (!Number.isInteger(options.chunkSize) || options.chunkSize < 1024)) {
+ throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");
+ }
+ }
+ };
+ var FileSystemWritableFileStreamTarget = class extends Target {
+ constructor(stream, options) {
+ super();
+ this.stream = stream;
+ this.options = options;
+ if (!(stream instanceof FileSystemWritableFileStream)) {
+ throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");
+ }
+ if (options !== void 0 && typeof options !== "object") {
+ throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");
+ }
+ if (options) {
+ if (options.chunkSize !== void 0 && (!Number.isInteger(options.chunkSize) || options.chunkSize <= 0)) {
+ throw new TypeError("options.chunkSize, when provided, must be a positive integer");
+ }
+ }
+ }
+ };
+
+ // src/writer.ts
+ var _helper, _helperView;
+ var Writer = class {
+ constructor() {
+ this.pos = 0;
+ __privateAdd(this, _helper, new Uint8Array(8));
+ __privateAdd(this, _helperView, new DataView(__privateGet(this, _helper).buffer));
+ /**
+ * Stores the position from the start of the file to where boxes elements have been written. This is used to
+ * rewrite/edit elements that were already added before, and to measure sizes of things.
+ */
+ this.offsets = /* @__PURE__ */ new WeakMap();
+ }
+ /** Sets the current position for future writes to a new one. */
+ seek(newPos) {
+ this.pos = newPos;
+ }
+ writeU32(value) {
+ __privateGet(this, _helperView).setUint32(0, value, false);
+ this.write(__privateGet(this, _helper).subarray(0, 4));
+ }
+ writeU64(value) {
+ __privateGet(this, _helperView).setUint32(0, Math.floor(value / 2 ** 32), false);
+ __privateGet(this, _helperView).setUint32(4, value, false);
+ this.write(__privateGet(this, _helper).subarray(0, 8));
+ }
+ writeAscii(text) {
+ for (let i = 0; i < text.length; i++) {
+ __privateGet(this, _helperView).setUint8(i % 8, text.charCodeAt(i));
+ if (i % 8 === 7)
+ this.write(__privateGet(this, _helper));
+ }
+ if (text.length % 8 !== 0) {
+ this.write(__privateGet(this, _helper).subarray(0, text.length % 8));
+ }
+ }
+ writeBox(box2) {
+ this.offsets.set(box2, this.pos);
+ if (box2.contents && !box2.children) {
+ this.writeBoxHeader(box2, box2.size ?? box2.contents.byteLength + 8);
+ this.write(box2.contents);
+ } else {
+ let startPos = this.pos;
+ this.writeBoxHeader(box2, 0);
+ if (box2.contents)
+ this.write(box2.contents);
+ if (box2.children) {
+ for (let child of box2.children)
+ if (child)
+ this.writeBox(child);
+ }
+ let endPos = this.pos;
+ let size = box2.size ?? endPos - startPos;
+ this.seek(startPos);
+ this.writeBoxHeader(box2, size);
+ this.seek(endPos);
+ }
+ }
+ writeBoxHeader(box2, size) {
+ this.writeU32(box2.largeSize ? 1 : size);
+ this.writeAscii(box2.type);
+ if (box2.largeSize)
+ this.writeU64(size);
+ }
+ measureBoxHeader(box2) {
+ return 8 + (box2.largeSize ? 8 : 0);
+ }
+ patchBox(box2) {
+ let endPos = this.pos;
+ this.seek(this.offsets.get(box2));
+ this.writeBox(box2);
+ this.seek(endPos);
+ }
+ measureBox(box2) {
+ if (box2.contents && !box2.children) {
+ let headerSize = this.measureBoxHeader(box2);
+ return headerSize + box2.contents.byteLength;
+ } else {
+ let result = this.measureBoxHeader(box2);
+ if (box2.contents)
+ result += box2.contents.byteLength;
+ if (box2.children) {
+ for (let child of box2.children)
+ if (child)
+ result += this.measureBox(child);
+ }
+ return result;
+ }
+ }
+ };
+ _helper = new WeakMap();
+ _helperView = new WeakMap();
+ var _target, _buffer, _bytes, _maxPos, _ensureSize, ensureSize_fn;
+ var ArrayBufferTargetWriter = class extends Writer {
+ constructor(target) {
+ super();
+ __privateAdd(this, _ensureSize);
+ __privateAdd(this, _target, void 0);
+ __privateAdd(this, _buffer, new ArrayBuffer(2 ** 16));
+ __privateAdd(this, _bytes, new Uint8Array(__privateGet(this, _buffer)));
+ __privateAdd(this, _maxPos, 0);
+ __privateSet(this, _target, target);
+ }
+ write(data) {
+ __privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos + data.byteLength);
+ __privateGet(this, _bytes).set(data, this.pos);
+ this.pos += data.byteLength;
+ __privateSet(this, _maxPos, Math.max(__privateGet(this, _maxPos), this.pos));
+ }
+ finalize() {
+ __privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos);
+ __privateGet(this, _target).buffer = __privateGet(this, _buffer).slice(0, Math.max(__privateGet(this, _maxPos), this.pos));
+ }
+ };
+ _target = new WeakMap();
+ _buffer = new WeakMap();
+ _bytes = new WeakMap();
+ _maxPos = new WeakMap();
+ _ensureSize = new WeakSet();
+ ensureSize_fn = function(size) {
+ let newLength = __privateGet(this, _buffer).byteLength;
+ while (newLength < size)
+ newLength *= 2;
+ if (newLength === __privateGet(this, _buffer).byteLength)
+ return;
+ let newBuffer = new ArrayBuffer(newLength);
+ let newBytes = new Uint8Array(newBuffer);
+ newBytes.set(__privateGet(this, _bytes), 0);
+ __privateSet(this, _buffer, newBuffer);
+ __privateSet(this, _bytes, newBytes);
+ };
+ var DEFAULT_CHUNK_SIZE = 2 ** 24;
+ var MAX_CHUNKS_AT_ONCE = 2;
+ var _target2, _sections, _chunked, _chunkSize, _chunks, _writeDataIntoChunks, writeDataIntoChunks_fn, _insertSectionIntoChunk, insertSectionIntoChunk_fn, _createChunk, createChunk_fn, _flushChunks, flushChunks_fn;
+ var StreamTargetWriter = class extends Writer {
+ constructor(target) {
+ super();
+ __privateAdd(this, _writeDataIntoChunks);
+ __privateAdd(this, _insertSectionIntoChunk);
+ __privateAdd(this, _createChunk);
+ __privateAdd(this, _flushChunks);
+ __privateAdd(this, _target2, void 0);
+ __privateAdd(this, _sections, []);
+ __privateAdd(this, _chunked, void 0);
+ __privateAdd(this, _chunkSize, void 0);
+ /**
+ * The data is divided up into fixed-size chunks, whose contents are first filled in RAM and then flushed out.
+ * A chunk is flushed if all of its contents have been written.
+ */
+ __privateAdd(this, _chunks, []);
+ __privateSet(this, _target2, target);
+ __privateSet(this, _chunked, target.options?.chunked ?? false);
+ __privateSet(this, _chunkSize, target.options?.chunkSize ?? DEFAULT_CHUNK_SIZE);
+ }
+ write(data) {
+ __privateGet(this, _sections).push({
+ data: data.slice(),
+ start: this.pos
+ });
+ this.pos += data.byteLength;
+ }
+ flush() {
+ if (__privateGet(this, _sections).length === 0)
+ return;
+ let chunks = [];
+ let sorted = [...__privateGet(this, _sections)].sort((a, b) => a.start - b.start);
+ chunks.push({
+ start: sorted[0].start,
+ size: sorted[0].data.byteLength
+ });
+ for (let i = 1; i < sorted.length; i++) {
+ let lastChunk = chunks[chunks.length - 1];
+ let section = sorted[i];
+ if (section.start <= lastChunk.start + lastChunk.size) {
+ lastChunk.size = Math.max(lastChunk.size, section.start + section.data.byteLength - lastChunk.start);
+ } else {
+ chunks.push({
+ start: section.start,
+ size: section.data.byteLength
+ });
+ }
+ }
+ for (let chunk of chunks) {
+ chunk.data = new Uint8Array(chunk.size);
+ for (let section of __privateGet(this, _sections)) {
+ if (chunk.start <= section.start && section.start < chunk.start + chunk.size) {
+ chunk.data.set(section.data, section.start - chunk.start);
+ }
+ }
+ if (__privateGet(this, _chunked)) {
+ __privateMethod(this, _writeDataIntoChunks, writeDataIntoChunks_fn).call(this, chunk.data, chunk.start);
+ __privateMethod(this, _flushChunks, flushChunks_fn).call(this);
+ } else {
+ __privateGet(this, _target2).options.onData?.(chunk.data, chunk.start);
+ }
+ }
+ __privateGet(this, _sections).length = 0;
+ }
+ finalize() {
+ if (__privateGet(this, _chunked)) {
+ __privateMethod(this, _flushChunks, flushChunks_fn).call(this, true);
+ }
+ }
+ };
+ _target2 = new WeakMap();
+ _sections = new WeakMap();
+ _chunked = new WeakMap();
+ _chunkSize = new WeakMap();
+ _chunks = new WeakMap();
+ _writeDataIntoChunks = new WeakSet();
+ writeDataIntoChunks_fn = function(data, position) {
+ let chunkIndex = __privateGet(this, _chunks).findIndex((x) => x.start <= position && position < x.start + __privateGet(this, _chunkSize));
+ if (chunkIndex === -1)
+ chunkIndex = __privateMethod(this, _createChunk, createChunk_fn).call(this, position);
+ let chunk = __privateGet(this, _chunks)[chunkIndex];
+ let relativePosition = position - chunk.start;
+ let toWrite = data.subarray(0, Math.min(__privateGet(this, _chunkSize) - relativePosition, data.byteLength));
+ chunk.data.set(toWrite, relativePosition);
+ let section = {
+ start: relativePosition,
+ end: relativePosition + toWrite.byteLength
+ };
+ __privateMethod(this, _insertSectionIntoChunk, insertSectionIntoChunk_fn).call(this, chunk, section);
+ if (chunk.written[0].start === 0 && chunk.written[0].end === __privateGet(this, _chunkSize)) {
+ chunk.shouldFlush = true;
+ }
+ if (__privateGet(this, _chunks).length > MAX_CHUNKS_AT_ONCE) {
+ for (let i = 0; i < __privateGet(this, _chunks).length - 1; i++) {
+ __privateGet(this, _chunks)[i].shouldFlush = true;
+ }
+ __privateMethod(this, _flushChunks, flushChunks_fn).call(this);
+ }
+ if (toWrite.byteLength < data.byteLength) {
+ __privateMethod(this, _writeDataIntoChunks, writeDataIntoChunks_fn).call(this, data.subarray(toWrite.byteLength), position + toWrite.byteLength);
+ }
+ };
+ _insertSectionIntoChunk = new WeakSet();
+ insertSectionIntoChunk_fn = function(chunk, section) {
+ let low = 0;
+ let high = chunk.written.length - 1;
+ let index = -1;
+ while (low <= high) {
+ let mid = Math.floor(low + (high - low + 1) / 2);
+ if (chunk.written[mid].start <= section.start) {
+ low = mid + 1;
+ index = mid;
+ } else {
+ high = mid - 1;
+ }
+ }
+ chunk.written.splice(index + 1, 0, section);
+ if (index === -1 || chunk.written[index].end < section.start)
+ index++;
+ while (index < chunk.written.length - 1 && chunk.written[index].end >= chunk.written[index + 1].start) {
+ chunk.written[index].end = Math.max(chunk.written[index].end, chunk.written[index + 1].end);
+ chunk.written.splice(index + 1, 1);
+ }
+ };
+ _createChunk = new WeakSet();
+ createChunk_fn = function(includesPosition) {
+ let start = Math.floor(includesPosition / __privateGet(this, _chunkSize)) * __privateGet(this, _chunkSize);
+ let chunk = {
+ start,
+ data: new Uint8Array(__privateGet(this, _chunkSize)),
+ written: [],
+ shouldFlush: false
+ };
+ __privateGet(this, _chunks).push(chunk);
+ __privateGet(this, _chunks).sort((a, b) => a.start - b.start);
+ return __privateGet(this, _chunks).indexOf(chunk);
+ };
+ _flushChunks = new WeakSet();
+ flushChunks_fn = function(force = false) {
+ for (let i = 0; i < __privateGet(this, _chunks).length; i++) {
+ let chunk = __privateGet(this, _chunks)[i];
+ if (!chunk.shouldFlush && !force)
+ continue;
+ for (let section of chunk.written) {
+ __privateGet(this, _target2).options.onData?.(
+ chunk.data.subarray(section.start, section.end),
+ chunk.start + section.start
+ );
+ }
+ __privateGet(this, _chunks).splice(i--, 1);
+ }
+ };
+ var FileSystemWritableFileStreamTargetWriter = class extends StreamTargetWriter {
+ constructor(target) {
+ super(new StreamTarget({
+ onData: (data, position) => target.stream.write({
+ type: "write",
+ data,
+ position
+ }),
+ chunked: true,
+ chunkSize: target.options?.chunkSize
+ }));
+ }
+ };
+
+ // src/muxer.ts
+ var GLOBAL_TIMESCALE = 1e3;
+ var SUPPORTED_VIDEO_CODECS = ["avc", "hevc", "vp9", "av1"];
+ var SUPPORTED_AUDIO_CODECS = ["aac", "opus"];
+ var TIMESTAMP_OFFSET = 2082844800;
+ var FIRST_TIMESTAMP_BEHAVIORS = ["strict", "offset", "cross-track-offset"];
+ var _options, _writer, _ftypSize, _mdat, _videoTrack, _audioTrack, _creationTime, _finalizedChunks, _nextFragmentNumber, _videoSampleQueue, _audioSampleQueue, _finalized, _validateOptions, validateOptions_fn, _writeHeader, writeHeader_fn, _computeMoovSizeUpperBound, computeMoovSizeUpperBound_fn, _prepareTracks, prepareTracks_fn, _generateMpeg4AudioSpecificConfig, generateMpeg4AudioSpecificConfig_fn, _createSampleForTrack, createSampleForTrack_fn, _addSampleToTrack, addSampleToTrack_fn, _validateTimestamp, validateTimestamp_fn, _finalizeCurrentChunk, finalizeCurrentChunk_fn, _finalizeFragment, finalizeFragment_fn, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn, _ensureNotFinalized, ensureNotFinalized_fn;
+ var Muxer = class {
+ constructor(options) {
+ __privateAdd(this, _validateOptions);
+ __privateAdd(this, _writeHeader);
+ __privateAdd(this, _computeMoovSizeUpperBound);
+ __privateAdd(this, _prepareTracks);
+ // https://wiki.multimedia.cx/index.php/MPEG-4_Audio
+ __privateAdd(this, _generateMpeg4AudioSpecificConfig);
+ __privateAdd(this, _createSampleForTrack);
+ __privateAdd(this, _addSampleToTrack);
+ __privateAdd(this, _validateTimestamp);
+ __privateAdd(this, _finalizeCurrentChunk);
+ __privateAdd(this, _finalizeFragment);
+ __privateAdd(this, _maybeFlushStreamingTargetWriter);
+ __privateAdd(this, _ensureNotFinalized);
+ __privateAdd(this, _options, void 0);
+ __privateAdd(this, _writer, void 0);
+ __privateAdd(this, _ftypSize, void 0);
+ __privateAdd(this, _mdat, void 0);
+ __privateAdd(this, _videoTrack, null);
+ __privateAdd(this, _audioTrack, null);
+ __privateAdd(this, _creationTime, Math.floor(Date.now() / 1e3) + TIMESTAMP_OFFSET);
+ __privateAdd(this, _finalizedChunks, []);
+ // Fields for fragmented MP4:
+ __privateAdd(this, _nextFragmentNumber, 1);
+ __privateAdd(this, _videoSampleQueue, []);
+ __privateAdd(this, _audioSampleQueue, []);
+ __privateAdd(this, _finalized, false);
+ __privateMethod(this, _validateOptions, validateOptions_fn).call(this, options);
+ options.video = deepClone(options.video);
+ options.audio = deepClone(options.audio);
+ options.fastStart = deepClone(options.fastStart);
+ this.target = options.target;
+ __privateSet(this, _options, {
+ firstTimestampBehavior: "strict",
+ ...options
+ });
+ if (options.target instanceof ArrayBufferTarget) {
+ __privateSet(this, _writer, new ArrayBufferTargetWriter(options.target));
+ } else if (options.target instanceof StreamTarget) {
+ __privateSet(this, _writer, new StreamTargetWriter(options.target));
+ } else if (options.target instanceof FileSystemWritableFileStreamTarget) {
+ __privateSet(this, _writer, new FileSystemWritableFileStreamTargetWriter(options.target));
+ } else {
+ throw new Error(`Invalid target: ${options.target}`);
+ }
+ __privateMethod(this, _prepareTracks, prepareTracks_fn).call(this);
+ __privateMethod(this, _writeHeader, writeHeader_fn).call(this);
+ }
+ addVideoChunk(sample, meta, timestamp, compositionTimeOffset) {
+ if (!(sample instanceof EncodedVideoChunk)) {
+ throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");
+ }
+ if (meta && typeof meta !== "object") {
+ throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");
+ }
+ if (timestamp !== void 0 && (!Number.isFinite(timestamp) || timestamp < 0)) {
+ throw new TypeError(
+ "addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number."
+ );
+ }
+ if (compositionTimeOffset !== void 0 && !Number.isFinite(compositionTimeOffset)) {
+ throw new TypeError(
+ "addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number."
+ );
+ }
+ let data = new Uint8Array(sample.byteLength);
+ sample.copyTo(data);
+ this.addVideoChunkRaw(
+ data,
+ sample.type,
+ timestamp ?? sample.timestamp,
+ sample.duration,
+ meta,
+ compositionTimeOffset
+ );
+ }
+ addVideoChunkRaw(data, type, timestamp, duration, meta, compositionTimeOffset) {
+ if (!(data instanceof Uint8Array)) {
+ throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");
+ }
+ if (type !== "key" && type !== "delta") {
+ throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");
+ }
+ if (!Number.isFinite(timestamp) || timestamp < 0) {
+ throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");
+ }
+ if (!Number.isFinite(duration) || duration < 0) {
+ throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");
+ }
+ if (meta && typeof meta !== "object") {
+ throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");
+ }
+ if (compositionTimeOffset !== void 0 && !Number.isFinite(compositionTimeOffset)) {
+ throw new TypeError(
+ "addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number."
+ );
+ }
+ __privateMethod(this, _ensureNotFinalized, ensureNotFinalized_fn).call(this);
+ if (!__privateGet(this, _options).video)
+ throw new Error("No video track declared.");
+ if (typeof __privateGet(this, _options).fastStart === "object" && __privateGet(this, _videoTrack).samples.length === __privateGet(this, _options).fastStart.expectedVideoChunks) {
+ throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${__privateGet(this, _options).fastStart.expectedVideoChunks}).`);
+ }
+ let videoSample = __privateMethod(this, _createSampleForTrack, createSampleForTrack_fn).call(this, __privateGet(this, _videoTrack), data, type, timestamp, duration, meta, compositionTimeOffset);
+ if (__privateGet(this, _options).fastStart === "fragmented" && __privateGet(this, _audioTrack)) {
+ while (__privateGet(this, _audioSampleQueue).length > 0 && __privateGet(this, _audioSampleQueue)[0].decodeTimestamp <= videoSample.decodeTimestamp) {
+ let audioSample = __privateGet(this, _audioSampleQueue).shift();
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
+ }
+ if (videoSample.decodeTimestamp <= __privateGet(this, _audioTrack).lastDecodeTimestamp) {
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
+ } else {
+ __privateGet(this, _videoSampleQueue).push(videoSample);
+ }
+ } else {
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
+ }
+ }
+ addAudioChunk(sample, meta, timestamp) {
+ if (!(sample instanceof EncodedAudioChunk)) {
+ throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");
+ }
+ if (meta && typeof meta !== "object") {
+ throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");
+ }
+ if (timestamp !== void 0 && (!Number.isFinite(timestamp) || timestamp < 0)) {
+ throw new TypeError(
+ "addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number."
+ );
+ }
+ let data = new Uint8Array(sample.byteLength);
+ sample.copyTo(data);
+ this.addAudioChunkRaw(data, sample.type, timestamp ?? sample.timestamp, sample.duration, meta);
+ }
+ addAudioChunkRaw(data, type, timestamp, duration, meta) {
+ if (!(data instanceof Uint8Array)) {
+ throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");
+ }
+ if (type !== "key" && type !== "delta") {
+ throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");
+ }
+ if (!Number.isFinite(timestamp) || timestamp < 0) {
+ throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");
+ }
+ if (!Number.isFinite(duration) || duration < 0) {
+ throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");
+ }
+ if (meta && typeof meta !== "object") {
+ throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");
+ }
+ __privateMethod(this, _ensureNotFinalized, ensureNotFinalized_fn).call(this);
+ if (!__privateGet(this, _options).audio)
+ throw new Error("No audio track declared.");
+ if (typeof __privateGet(this, _options).fastStart === "object" && __privateGet(this, _audioTrack).samples.length === __privateGet(this, _options).fastStart.expectedAudioChunks) {
+ throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${__privateGet(this, _options).fastStart.expectedAudioChunks}).`);
+ }
+ let audioSample = __privateMethod(this, _createSampleForTrack, createSampleForTrack_fn).call(this, __privateGet(this, _audioTrack), data, type, timestamp, duration, meta);
+ if (__privateGet(this, _options).fastStart === "fragmented" && __privateGet(this, _videoTrack)) {
+ while (__privateGet(this, _videoSampleQueue).length > 0 && __privateGet(this, _videoSampleQueue)[0].decodeTimestamp <= audioSample.decodeTimestamp) {
+ let videoSample = __privateGet(this, _videoSampleQueue).shift();
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
+ }
+ if (audioSample.decodeTimestamp <= __privateGet(this, _videoTrack).lastDecodeTimestamp) {
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
+ } else {
+ __privateGet(this, _audioSampleQueue).push(audioSample);
+ }
+ } else {
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
+ }
+ }
+ /** Finalizes the file, making it ready for use. Must be called after all video and audio chunks have been added. */
+ finalize() {
+ if (__privateGet(this, _finalized)) {
+ throw new Error("Cannot finalize a muxer more than once.");
+ }
+ if (__privateGet(this, _options).fastStart === "fragmented") {
+ for (let videoSample of __privateGet(this, _videoSampleQueue))
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
+ for (let audioSample of __privateGet(this, _audioSampleQueue))
+ __privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
+ __privateMethod(this, _finalizeFragment, finalizeFragment_fn).call(this, false);
+ } else {
+ if (__privateGet(this, _videoTrack))
+ __privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, __privateGet(this, _videoTrack));
+ if (__privateGet(this, _audioTrack))
+ __privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, __privateGet(this, _audioTrack));
+ }
+ let tracks = [__privateGet(this, _videoTrack), __privateGet(this, _audioTrack)].filter(Boolean);
+ if (__privateGet(this, _options).fastStart === "in-memory") {
+ let mdatSize;
+ for (let i = 0; i < 2; i++) {
+ let movieBox2 = moov(tracks, __privateGet(this, _creationTime));
+ let movieBoxSize = __privateGet(this, _writer).measureBox(movieBox2);
+ mdatSize = __privateGet(this, _writer).measureBox(__privateGet(this, _mdat));
+ let currentChunkPos = __privateGet(this, _writer).pos + movieBoxSize + mdatSize;
+ for (let chunk of __privateGet(this, _finalizedChunks)) {
+ chunk.offset = currentChunkPos;
+ for (let { data } of chunk.samples) {
+ currentChunkPos += data.byteLength;
+ mdatSize += data.byteLength;
+ }
+ }
+ if (currentChunkPos < 2 ** 32)
+ break;
+ if (mdatSize >= 2 ** 32)
+ __privateGet(this, _mdat).largeSize = true;
+ }
+ let movieBox = moov(tracks, __privateGet(this, _creationTime));
+ __privateGet(this, _writer).writeBox(movieBox);
+ __privateGet(this, _mdat).size = mdatSize;
+ __privateGet(this, _writer).writeBox(__privateGet(this, _mdat));
+ for (let chunk of __privateGet(this, _finalizedChunks)) {
+ for (let sample of chunk.samples) {
+ __privateGet(this, _writer).write(sample.data);
+ sample.data = null;
+ }
+ }
+ } else if (__privateGet(this, _options).fastStart === "fragmented") {
+ let startPos = __privateGet(this, _writer).pos;
+ let mfraBox = mfra(tracks);
+ __privateGet(this, _writer).writeBox(mfraBox);
+ let mfraBoxSize = __privateGet(this, _writer).pos - startPos;
+ __privateGet(this, _writer).seek(__privateGet(this, _writer).pos - 4);
+ __privateGet(this, _writer).writeU32(mfraBoxSize);
+ } else {
+ let mdatPos = __privateGet(this, _writer).offsets.get(__privateGet(this, _mdat));
+ let mdatSize = __privateGet(this, _writer).pos - mdatPos;
+ __privateGet(this, _mdat).size = mdatSize;
+ __privateGet(this, _mdat).largeSize = mdatSize >= 2 ** 32;
+ __privateGet(this, _writer).patchBox(__privateGet(this, _mdat));
+ let movieBox = moov(tracks, __privateGet(this, _creationTime));
+ if (typeof __privateGet(this, _options).fastStart === "object") {
+ __privateGet(this, _writer).seek(__privateGet(this, _ftypSize));
+ __privateGet(this, _writer).writeBox(movieBox);
+ let remainingBytes = mdatPos - __privateGet(this, _writer).pos;
+ __privateGet(this, _writer).writeBox(free(remainingBytes));
+ } else {
+ __privateGet(this, _writer).writeBox(movieBox);
+ }
+ }
+ __privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
+ __privateGet(this, _writer).finalize();
+ __privateSet(this, _finalized, true);
+ }
+ };
+ _options = new WeakMap();
+ _writer = new WeakMap();
+ _ftypSize = new WeakMap();
+ _mdat = new WeakMap();
+ _videoTrack = new WeakMap();
+ _audioTrack = new WeakMap();
+ _creationTime = new WeakMap();
+ _finalizedChunks = new WeakMap();
+ _nextFragmentNumber = new WeakMap();
+ _videoSampleQueue = new WeakMap();
+ _audioSampleQueue = new WeakMap();
+ _finalized = new WeakMap();
+ _validateOptions = new WeakSet();
+ validateOptions_fn = function(options) {
+ if (typeof options !== "object") {
+ throw new TypeError("The muxer requires an options object to be passed to its constructor.");
+ }
+ if (!(options.target instanceof Target)) {
+ throw new TypeError("The target must be provided and an instance of Target.");
+ }
+ if (options.video) {
+ if (!SUPPORTED_VIDEO_CODECS.includes(options.video.codec)) {
+ throw new TypeError(`Unsupported video codec: ${options.video.codec}`);
+ }
+ if (!Number.isInteger(options.video.width) || options.video.width <= 0) {
+ throw new TypeError(`Invalid video width: ${options.video.width}. Must be a positive integer.`);
+ }
+ if (!Number.isInteger(options.video.height) || options.video.height <= 0) {
+ throw new TypeError(`Invalid video height: ${options.video.height}. Must be a positive integer.`);
+ }
+ const videoRotation = options.video.rotation;
+ if (typeof videoRotation === "number" && ![0, 90, 180, 270].includes(videoRotation)) {
+ throw new TypeError(`Invalid video rotation: ${videoRotation}. Has to be 0, 90, 180 or 270.`);
+ } else if (Array.isArray(videoRotation) && (videoRotation.length !== 9 || videoRotation.some((value) => typeof value !== "number"))) {
+ throw new TypeError(`Invalid video transformation matrix: ${videoRotation.join()}`);
+ }
+ if (options.video.frameRate !== void 0 && (!Number.isInteger(options.video.frameRate) || options.video.frameRate <= 0)) {
+ throw new TypeError(
+ `Invalid video frame rate: ${options.video.frameRate}. Must be a positive integer.`
+ );
+ }
+ }
+ if (options.audio) {
+ if (!SUPPORTED_AUDIO_CODECS.includes(options.audio.codec)) {
+ throw new TypeError(`Unsupported audio codec: ${options.audio.codec}`);
+ }
+ if (!Number.isInteger(options.audio.numberOfChannels) || options.audio.numberOfChannels <= 0) {
+ throw new TypeError(
+ `Invalid number of audio channels: ${options.audio.numberOfChannels}. Must be a positive integer.`
+ );
+ }
+ if (!Number.isInteger(options.audio.sampleRate) || options.audio.sampleRate <= 0) {
+ throw new TypeError(
+ `Invalid audio sample rate: ${options.audio.sampleRate}. Must be a positive integer.`
+ );
+ }
+ }
+ if (options.firstTimestampBehavior && !FIRST_TIMESTAMP_BEHAVIORS.includes(options.firstTimestampBehavior)) {
+ throw new TypeError(`Invalid first timestamp behavior: ${options.firstTimestampBehavior}`);
+ }
+ if (typeof options.fastStart === "object") {
+ if (options.video) {
+ if (options.fastStart.expectedVideoChunks === void 0) {
+ throw new TypeError(`'fastStart' is an object but is missing property 'expectedVideoChunks'.`);
+ } else if (!Number.isInteger(options.fastStart.expectedVideoChunks) || options.fastStart.expectedVideoChunks < 0) {
+ throw new TypeError(`'expectedVideoChunks' must be a non-negative integer.`);
+ }
+ }
+ if (options.audio) {
+ if (options.fastStart.expectedAudioChunks === void 0) {
+ throw new TypeError(`'fastStart' is an object but is missing property 'expectedAudioChunks'.`);
+ } else if (!Number.isInteger(options.fastStart.expectedAudioChunks) || options.fastStart.expectedAudioChunks < 0) {
+ throw new TypeError(`'expectedAudioChunks' must be a non-negative integer.`);
+ }
+ }
+ } else if (![false, "in-memory", "fragmented"].includes(options.fastStart)) {
+ throw new TypeError(`'fastStart' option must be false, 'in-memory', 'fragmented' or an object.`);
+ }
+ if (options.minFragmentDuration !== void 0 && (!Number.isFinite(options.minFragmentDuration) || options.minFragmentDuration < 0)) {
+ throw new TypeError(`'minFragmentDuration' must be a non-negative number.`);
+ }
+ };
+ _writeHeader = new WeakSet();
+ writeHeader_fn = function() {
+ __privateGet(this, _writer).writeBox(ftyp({
+ holdsAvc: __privateGet(this, _options).video?.codec === "avc",
+ fragmented: __privateGet(this, _options).fastStart === "fragmented"
+ }));
+ __privateSet(this, _ftypSize, __privateGet(this, _writer).pos);
+ if (__privateGet(this, _options).fastStart === "in-memory") {
+ __privateSet(this, _mdat, mdat(false));
+ } else if (__privateGet(this, _options).fastStart === "fragmented") {
+ } else {
+ if (typeof __privateGet(this, _options).fastStart === "object") {
+ let moovSizeUpperBound = __privateMethod(this, _computeMoovSizeUpperBound, computeMoovSizeUpperBound_fn).call(this);
+ __privateGet(this, _writer).seek(__privateGet(this, _writer).pos + moovSizeUpperBound);
+ }
+ __privateSet(this, _mdat, mdat(true));
+ __privateGet(this, _writer).writeBox(__privateGet(this, _mdat));
+ }
+ __privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
+ };
+ _computeMoovSizeUpperBound = new WeakSet();
+ computeMoovSizeUpperBound_fn = function() {
+ if (typeof __privateGet(this, _options).fastStart !== "object")
+ return;
+ let upperBound = 0;
+ let sampleCounts = [
+ __privateGet(this, _options).fastStart.expectedVideoChunks,
+ __privateGet(this, _options).fastStart.expectedAudioChunks
+ ];
+ for (let n of sampleCounts) {
+ if (!n)
+ continue;
+ upperBound += (4 + 4) * Math.ceil(2 / 3 * n);
+ upperBound += 4 * n;
+ upperBound += (4 + 4 + 4) * Math.ceil(2 / 3 * n);
+ upperBound += 4 * n;
+ upperBound += 8 * n;
+ }
+ upperBound += 4096;
+ return upperBound;
+ };
+ _prepareTracks = new WeakSet();
+ prepareTracks_fn = function() {
+ if (__privateGet(this, _options).video) {
+ __privateSet(this, _videoTrack, {
+ id: 1,
+ info: {
+ type: "video",
+ codec: __privateGet(this, _options).video.codec,
+ width: __privateGet(this, _options).video.width,
+ height: __privateGet(this, _options).video.height,
+ rotation: __privateGet(this, _options).video.rotation ?? 0,
+ decoderConfig: null
+ },
+ // The fallback contains many common frame rates as factors
+ timescale: __privateGet(this, _options).video.frameRate ?? 57600,
+ samples: [],
+ finalizedChunks: [],
+ currentChunk: null,
+ firstDecodeTimestamp: void 0,
+ lastDecodeTimestamp: -1,
+ timeToSampleTable: [],
+ compositionTimeOffsetTable: [],
+ lastTimescaleUnits: null,
+ lastSample: null,
+ compactlyCodedChunkTable: []
+ });
+ }
+ if (__privateGet(this, _options).audio) {
+ __privateSet(this, _audioTrack, {
+ id: __privateGet(this, _options).video ? 2 : 1,
+ info: {
+ type: "audio",
+ codec: __privateGet(this, _options).audio.codec,
+ numberOfChannels: __privateGet(this, _options).audio.numberOfChannels,
+ sampleRate: __privateGet(this, _options).audio.sampleRate,
+ decoderConfig: null
+ },
+ timescale: __privateGet(this, _options).audio.sampleRate,
+ samples: [],
+ finalizedChunks: [],
+ currentChunk: null,
+ firstDecodeTimestamp: void 0,
+ lastDecodeTimestamp: -1,
+ timeToSampleTable: [],
+ compositionTimeOffsetTable: [],
+ lastTimescaleUnits: null,
+ lastSample: null,
+ compactlyCodedChunkTable: []
+ });
+ if (__privateGet(this, _options).audio.codec === "aac") {
+ let guessedCodecPrivate = __privateMethod(this, _generateMpeg4AudioSpecificConfig, generateMpeg4AudioSpecificConfig_fn).call(
+ this,
+ 2,
+ // Object type for AAC-LC, since it's the most common
+ __privateGet(this, _options).audio.sampleRate,
+ __privateGet(this, _options).audio.numberOfChannels
+ );
+ __privateGet(this, _audioTrack).info.decoderConfig = {
+ codec: __privateGet(this, _options).audio.codec,
+ description: guessedCodecPrivate,
+ numberOfChannels: __privateGet(this, _options).audio.numberOfChannels,
+ sampleRate: __privateGet(this, _options).audio.sampleRate
+ };
+ }
+ }
+ };
+ _generateMpeg4AudioSpecificConfig = new WeakSet();
+ generateMpeg4AudioSpecificConfig_fn = function(objectType, sampleRate, numberOfChannels) {
+ let frequencyIndices = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
+ let frequencyIndex = frequencyIndices.indexOf(sampleRate);
+ let channelConfig = numberOfChannels;
+ let configBits = "";
+ configBits += objectType.toString(2).padStart(5, "0");
+ configBits += frequencyIndex.toString(2).padStart(4, "0");
+ if (frequencyIndex === 15)
+ configBits += sampleRate.toString(2).padStart(24, "0");
+ configBits += channelConfig.toString(2).padStart(4, "0");
+ let paddingLength = Math.ceil(configBits.length / 8) * 8;
+ configBits = configBits.padEnd(paddingLength, "0");
+ let configBytes = new Uint8Array(configBits.length / 8);
+ for (let i = 0; i < configBits.length; i += 8) {
+ configBytes[i / 8] = parseInt(configBits.slice(i, i + 8), 2);
+ }
+ return configBytes;
+ };
+ _createSampleForTrack = new WeakSet();
+ createSampleForTrack_fn = function(track, data, type, timestamp, duration, meta, compositionTimeOffset) {
+ let presentationTimestampInSeconds = timestamp / 1e6;
+ let decodeTimestampInSeconds = (timestamp - (compositionTimeOffset ?? 0)) / 1e6;
+ let durationInSeconds = duration / 1e6;
+ let adjusted = __privateMethod(this, _validateTimestamp, validateTimestamp_fn).call(this, presentationTimestampInSeconds, decodeTimestampInSeconds, track);
+ presentationTimestampInSeconds = adjusted.presentationTimestamp;
+ decodeTimestampInSeconds = adjusted.decodeTimestamp;
+ if (meta?.decoderConfig) {
+ if (track.info.decoderConfig === null) {
+ track.info.decoderConfig = meta.decoderConfig;
+ } else {
+ Object.assign(track.info.decoderConfig, meta.decoderConfig);
+ }
+ }
+ let sample = {
+ presentationTimestamp: presentationTimestampInSeconds,
+ decodeTimestamp: decodeTimestampInSeconds,
+ duration: durationInSeconds,
+ data,
+ size: data.byteLength,
+ type,
+ // Will be refined once the next sample comes in
+ timescaleUnitsToNextSample: intoTimescale(durationInSeconds, track.timescale)
+ };
+ return sample;
+ };
+ _addSampleToTrack = new WeakSet();
+ addSampleToTrack_fn = function(track, sample) {
+ if (__privateGet(this, _options).fastStart !== "fragmented") {
+ track.samples.push(sample);
+ }
+ const sampleCompositionTimeOffset = intoTimescale(sample.presentationTimestamp - sample.decodeTimestamp, track.timescale);
+ if (track.lastTimescaleUnits !== null) {
+ let timescaleUnits = intoTimescale(sample.decodeTimestamp, track.timescale, false);
+ let delta = Math.round(timescaleUnits - track.lastTimescaleUnits);
+ track.lastTimescaleUnits += delta;
+ track.lastSample.timescaleUnitsToNextSample = delta;
+ if (__privateGet(this, _options).fastStart !== "fragmented") {
+ let lastTableEntry = last(track.timeToSampleTable);
+ if (lastTableEntry.sampleCount === 1) {
+ lastTableEntry.sampleDelta = delta;
+ lastTableEntry.sampleCount++;
+ } else if (lastTableEntry.sampleDelta === delta) {
+ lastTableEntry.sampleCount++;
+ } else {
+ lastTableEntry.sampleCount--;
+ track.timeToSampleTable.push({
+ sampleCount: 2,
+ sampleDelta: delta
+ });
+ }
+ const lastCompositionTimeOffsetTableEntry = last(track.compositionTimeOffsetTable);
+ if (lastCompositionTimeOffsetTableEntry.sampleCompositionTimeOffset === sampleCompositionTimeOffset) {
+ lastCompositionTimeOffsetTableEntry.sampleCount++;
+ } else {
+ track.compositionTimeOffsetTable.push({
+ sampleCount: 1,
+ sampleCompositionTimeOffset
+ });
+ }
+ }
+ } else {
+ track.lastTimescaleUnits = 0;
+ if (__privateGet(this, _options).fastStart !== "fragmented") {
+ track.timeToSampleTable.push({
+ sampleCount: 1,
+ sampleDelta: intoTimescale(sample.duration, track.timescale)
+ });
+ track.compositionTimeOffsetTable.push({
+ sampleCount: 1,
+ sampleCompositionTimeOffset
+ });
+ }
+ }
+ track.lastSample = sample;
+ let beginNewChunk = false;
+ if (!track.currentChunk) {
+ beginNewChunk = true;
+ } else {
+ let currentChunkDuration = sample.presentationTimestamp - track.currentChunk.startTimestamp;
+ if (__privateGet(this, _options).fastStart === "fragmented") {
+ let mostImportantTrack = __privateGet(this, _videoTrack) ?? __privateGet(this, _audioTrack);
+ const chunkDuration = __privateGet(this, _options).minFragmentDuration ?? 1;
+ if (track === mostImportantTrack && sample.type === "key" && currentChunkDuration >= chunkDuration) {
+ beginNewChunk = true;
+ __privateMethod(this, _finalizeFragment, finalizeFragment_fn).call(this);
+ }
+ } else {
+ beginNewChunk = currentChunkDuration >= 0.5;
+ }
+ }
+ if (beginNewChunk) {
+ if (track.currentChunk) {
+ __privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, track);
+ }
+ track.currentChunk = {
+ startTimestamp: sample.presentationTimestamp,
+ samples: []
+ };
+ }
+ track.currentChunk.samples.push(sample);
+ };
+ _validateTimestamp = new WeakSet();
+ validateTimestamp_fn = function(presentationTimestamp, decodeTimestamp, track) {
+ const strictTimestampBehavior = __privateGet(this, _options).firstTimestampBehavior === "strict";
+ const noLastDecodeTimestamp = track.lastDecodeTimestamp === -1;
+ const timestampNonZero = decodeTimestamp !== 0;
+ if (strictTimestampBehavior && noLastDecodeTimestamp && timestampNonZero) {
+ throw new Error(
+ `The first chunk for your media track must have a timestamp of 0 (received DTS=${decodeTimestamp}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want.
+
+If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
+`
+ );
+ } else if (__privateGet(this, _options).firstTimestampBehavior === "offset" || __privateGet(this, _options).firstTimestampBehavior === "cross-track-offset") {
+ if (track.firstDecodeTimestamp === void 0) {
+ track.firstDecodeTimestamp = decodeTimestamp;
+ }
+ let baseDecodeTimestamp;
+ if (__privateGet(this, _options).firstTimestampBehavior === "offset") {
+ baseDecodeTimestamp = track.firstDecodeTimestamp;
+ } else {
+ baseDecodeTimestamp = Math.min(
+ __privateGet(this, _videoTrack)?.firstDecodeTimestamp ?? Infinity,
+ __privateGet(this, _audioTrack)?.firstDecodeTimestamp ?? Infinity
+ );
+ }
+ decodeTimestamp -= baseDecodeTimestamp;
+ presentationTimestamp -= baseDecodeTimestamp;
+ }
+ if (decodeTimestamp < track.lastDecodeTimestamp) {
+ throw new Error(
+ `Timestamps must be monotonically increasing (DTS went from ${track.lastDecodeTimestamp * 1e6} to ${decodeTimestamp * 1e6}).`
+ );
+ }
+ track.lastDecodeTimestamp = decodeTimestamp;
+ return { presentationTimestamp, decodeTimestamp };
+ };
+ _finalizeCurrentChunk = new WeakSet();
+ finalizeCurrentChunk_fn = function(track) {
+ if (__privateGet(this, _options).fastStart === "fragmented") {
+ throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");
+ }
+ if (!track.currentChunk)
+ return;
+ track.finalizedChunks.push(track.currentChunk);
+ __privateGet(this, _finalizedChunks).push(track.currentChunk);
+ if (track.compactlyCodedChunkTable.length === 0 || last(track.compactlyCodedChunkTable).samplesPerChunk !== track.currentChunk.samples.length) {
+ track.compactlyCodedChunkTable.push({
+ firstChunk: track.finalizedChunks.length,
+ // 1-indexed
+ samplesPerChunk: track.currentChunk.samples.length
+ });
+ }
+ if (__privateGet(this, _options).fastStart === "in-memory") {
+ track.currentChunk.offset = 0;
+ return;
+ }
+ track.currentChunk.offset = __privateGet(this, _writer).pos;
+ for (let sample of track.currentChunk.samples) {
+ __privateGet(this, _writer).write(sample.data);
+ sample.data = null;
+ }
+ __privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
+ };
+ _finalizeFragment = new WeakSet();
+ finalizeFragment_fn = function(flushStreamingWriter = true) {
+ if (__privateGet(this, _options).fastStart !== "fragmented") {
+ throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");
+ }
+ let tracks = [__privateGet(this, _videoTrack), __privateGet(this, _audioTrack)].filter((track) => track && track.currentChunk);
+ if (tracks.length === 0)
+ return;
+ let fragmentNumber = __privateWrapper(this, _nextFragmentNumber)._++;
+ if (fragmentNumber === 1) {
+ let movieBox = moov(tracks, __privateGet(this, _creationTime), true);
+ __privateGet(this, _writer).writeBox(movieBox);
+ }
+ let moofOffset = __privateGet(this, _writer).pos;
+ let moofBox = moof(fragmentNumber, tracks);
+ __privateGet(this, _writer).writeBox(moofBox);
+ {
+ let mdatBox = mdat(false);
+ let totalTrackSampleSize = 0;
+ for (let track of tracks) {
+ for (let sample of track.currentChunk.samples) {
+ totalTrackSampleSize += sample.size;
+ }
+ }
+ let mdatSize = __privateGet(this, _writer).measureBox(mdatBox) + totalTrackSampleSize;
+ if (mdatSize >= 2 ** 32) {
+ mdatBox.largeSize = true;
+ mdatSize = __privateGet(this, _writer).measureBox(mdatBox) + totalTrackSampleSize;
+ }
+ mdatBox.size = mdatSize;
+ __privateGet(this, _writer).writeBox(mdatBox);
+ }
+ for (let track of tracks) {
+ track.currentChunk.offset = __privateGet(this, _writer).pos;
+ track.currentChunk.moofOffset = moofOffset;
+ for (let sample of track.currentChunk.samples) {
+ __privateGet(this, _writer).write(sample.data);
+ sample.data = null;
+ }
+ }
+ let endPos = __privateGet(this, _writer).pos;
+ __privateGet(this, _writer).seek(__privateGet(this, _writer).offsets.get(moofBox));
+ let newMoofBox = moof(fragmentNumber, tracks);
+ __privateGet(this, _writer).writeBox(newMoofBox);
+ __privateGet(this, _writer).seek(endPos);
+ for (let track of tracks) {
+ track.finalizedChunks.push(track.currentChunk);
+ __privateGet(this, _finalizedChunks).push(track.currentChunk);
+ track.currentChunk = null;
+ }
+ if (flushStreamingWriter) {
+ __privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
+ }
+ };
+ _maybeFlushStreamingTargetWriter = new WeakSet();
+ maybeFlushStreamingTargetWriter_fn = function() {
+ if (__privateGet(this, _writer) instanceof StreamTargetWriter) {
+ __privateGet(this, _writer).flush();
+ }
+ };
+ _ensureNotFinalized = new WeakSet();
+ ensureNotFinalized_fn = function() {
+ if (__privateGet(this, _finalized)) {
+ throw new Error("Cannot add new video or audio chunks after the file has been finalized.");
+ }
+ };
+ return __toCommonJS(src_exports);
+})();
+if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, Mp4Muxer)
diff --git a/public/demo.css b/public/demo.css
new file mode 100644
index 0000000..a7d5fe8
--- /dev/null
+++ b/public/demo.css
@@ -0,0 +1,100 @@
+/* Null launch preview: the final film above the rough drafts it was assembled from. */
+:root {
+ color-scheme: dark;
+ --bg: #0b0b0c;
+ --line: #222225;
+ --text: #ededee;
+ --muted: #7d7d83;
+ --faint: #45454a;
+ --accent: #ff5a1f;
+ --w: min(1120px, calc((100svh - 250px) * 1.5), calc(100vw - 48px));
+ --gap: 8px;
+ font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif;
+}
+* { box-sizing: border-box; }
+body { margin: 0; min-height: 100svh; background: var(--bg); color: var(--text); font-size: 13px; -webkit-font-smoothing: antialiased; }
+button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
+:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
+
+.bar { display: flex; align-items: center; gap: 16px; height: 56px; padding: 0 24px; }
+.logo { color: var(--text); text-decoration: none; font-size: 16px; font-weight: 600; letter-spacing: -.02em; }
+.logo span { color: var(--accent); }
+.bar-meta { color: var(--muted); font-size: 12px; }
+.bar-link { margin-left: auto; color: var(--muted); font-size: 12px; text-decoration: none; }
+.bar-link:hover { color: var(--text); }
+
+.stage { width: var(--w); margin: 4px auto 32px; display: flex; flex-direction: column; }
+
+/* Final film */
+.final { position: relative; aspect-ratio: 16 / 9; border-radius: 14px; overflow: hidden; background: #000; box-shadow: 0 0 0 1px var(--line), 0 30px 80px -40px rgba(0, 0, 0, .9); }
+.final video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+.final-toggle { position: absolute; inset: 0; display: grid; place-items: center; }
+.final-icon { width: 56px; height: 56px; border-radius: 50%; background: rgba(12, 12, 13, .55); backdrop-filter: blur(8px); opacity: 0; transform: scale(.9); transition: opacity .25s, transform .25s; position: relative; }
+.final-icon::before { content: ""; position: absolute; left: 22px; top: 18px; border-left: 15px solid #fff; border-top: 10px solid transparent; border-bottom: 10px solid transparent; }
+.final.paused .final-icon, .final-toggle:focus-visible .final-icon { opacity: 1; transform: none; }
+.final:not(.paused) .final-icon::before { left: 20px; top: 19px; width: 5px; height: 18px; border: 0; background: #fff; box-shadow: 10px 0 #fff; }
+.sound { position: absolute; top: 14px; font-size: 11px; padding: 4px 9px; border-radius: 99px; background: rgba(12, 12, 13, .5); backdrop-filter: blur(8px); color: #fff; }
+.sound { right: 14px; color: rgba(255, 255, 255, .8); transition: opacity .2s; }
+.final:not(:hover) .sound:not(:focus-visible) { opacity: 0; }
+
+/* Sections: every draft is the same 16:9 size, named underneath. Six or more fill the
+ row; fewer keep the six-across size and centre. The playhead runs straight across them. */
+.strip { position: relative; margin-top: 16px; cursor: pointer; touch-action: none; user-select: none; -webkit-user-select: none; }
+.scraps { display: flex; justify-content: center; gap: var(--gap); }
+.seg { flex: 1 1 0; min-width: 0; display: flex; flex-direction: column; gap: 9px; }
+.scraps[data-count="1"] .seg, .scraps[data-count="2"] .seg, .scraps[data-count="3"] .seg, .scraps[data-count="4"] .seg, .scraps[data-count="5"] .seg { flex: 0 1 calc((var(--w) - var(--gap) * 5) / 6); }
+.scrap { position: relative; aspect-ratio: 16 / 9; border-radius: 8px; overflow: hidden; background: #fff; box-shadow: 0 0 0 1px var(--line); transition: box-shadow .3s; pointer-events: none; }
+.seg:hover .scrap { box-shadow: 0 0 0 1px #55555a; }
+.seg.active .scrap { box-shadow: 0 0 0 2px var(--accent); }
+.scrap-canvas { position: absolute; left: 0; top: 0; width: 640px; height: 360px; transform-origin: 0 0; transform: translate(var(--x, 0), var(--y, 0)) scale(var(--scale, .25)); overflow: hidden; }
+.seg-name { font: 500 12.5px/1.2 Inter, system-ui, sans-serif; letter-spacing: -.005em; text-align: center; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: color .3s; }
+.seg.active .seg-name { color: var(--text); }
+.playhead { position: absolute; top: -7px; left: 0; width: 0; height: calc(var(--card-h, 60px) + 14px); pointer-events: none; z-index: 2; }
+.playhead::after { content: ""; position: absolute; top: 5px; bottom: 0; left: -1px; width: 2px; border-radius: 1px; background: #fff; box-shadow: 0 0 0 1px rgba(0, 0, 0, .35); }
+.playhead span { position: absolute; top: 0; left: -5px; width: 10px; height: 10px; border-radius: 50%; background: #fff; box-shadow: 0 0 0 1px rgba(0, 0, 0, .35); }
+.seek { position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; }
+.stage:has(.seek:focus-visible) .strip { outline: 2px solid var(--accent); outline-offset: 6px; border-radius: 8px; }
+.times { display: flex; justify-content: space-between; margin-top: 10px; font: 500 11px Inter, system-ui, sans-serif; color: var(--muted); font-variant-numeric: tabular-nums; }
+.times strong { color: var(--text); font-weight: 500; }
+
+/* Download */
+.download { position: relative; }
+.download-button { display: inline-flex; align-items: center; gap: 7px; height: 32px; padding: 0 14px; border-radius: 99px; background: var(--text); color: #0b0b0c; font-size: 12px; font-weight: 500; transition: opacity .2s; }
+.download-button:hover { opacity: .9; }
+.download-button:disabled { opacity: .7; cursor: progress; }
+.download-button svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
+.download-menu { position: absolute; right: 0; top: 40px; z-index: 10; width: 260px; padding: 6px; border-radius: 12px; background: #161618; box-shadow: 0 0 0 1px var(--line), 0 20px 50px -20px #000; }
+.download-menu[hidden] { display: none; }
+.download-menu button { display: block; width: 100%; padding: 9px 10px; border-radius: 8px; text-align: left; }
+.download-menu button:hover, .download-menu button:focus-visible { background: #202023; outline: none; }
+.download-menu strong { display: block; font-size: 12px; font-weight: 500; }
+.download-menu span { display: block; margin-top: 2px; font-size: 11px; color: var(--muted); }
+
+
+/* Every reference, below the fold */
+.library { width: var(--w); margin: 24px auto 64px; }
+.library-head { display: flex; align-items: baseline; gap: 10px; margin-bottom: 14px; }
+.library-head h2 { margin: 0; font-size: 14px; font-weight: 500; }
+.library-head span { font-size: 12px; color: var(--muted); }
+.library-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 18px 14px; }
+.video-card { display: block; width: 100%; text-align: left; }
+.video-thumb { position: relative; display: block; aspect-ratio: 16 / 9; border-radius: 9px; overflow: hidden; background: #151517; box-shadow: 0 0 0 1px var(--line); transition: box-shadow .25s, transform .25s; }
+.video-thumb img, .video-thumb video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+.video-card:hover .video-thumb { transform: translateY(-2px); box-shadow: 0 0 0 1px #3a3a3f; }
+.video-card.current .video-thumb { box-shadow: 0 0 0 2px var(--accent); }
+.video-length { position: absolute; right: 7px; bottom: 7px; padding: 2px 6px; border-radius: 99px; font-size: 10px; color: #fff; background: rgba(12, 12, 13, .65); font-variant-numeric: tabular-nums; }
+.video-name { display: block; margin-top: 8px; font-size: 12px; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.video-card.current .video-name { color: var(--accent); }
+
+.notice { display: grid; place-items: center; position: absolute; inset: 0; color: var(--muted); font-size: 12px; }
+
+@media (max-width: 720px) {
+ :root { --w: calc(100vw - 32px); }
+ .bar { padding: 0 16px; }
+ .bar-meta { display: none; }
+ :root { --gap: 3px; }
+ .scrap { border-radius: 5px; }
+ .seg-name { font-size: 10px; }
+ .library-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px 10px; }
+}
+@media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
diff --git a/public/demo.html b/public/demo.html
new file mode 100644
index 0000000..47d514c
--- /dev/null
+++ b/public/demo.html
@@ -0,0 +1,42 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="theme-color" content="#0b0b0c"><title>Null — Launch Studio</title>
+ <link rel="icon" href="assets/null-logo.png"><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap"><link rel="stylesheet" href="demo.css">
+ <script src="_vendor/gsap.min.js"></script>
+ <script src="_vendor/mp4-muxer.js"></script>
+ <script type="module" src="demo.mjs"></script>
+</head>
+<body>
+<header class="bar">
+ <a class="logo" href="/">null<span>.</span></a>
+ <span class="bar-meta" id="bar-meta"></span>
+ <a class="bar-link" href="/editor">Open editor</a>
+ <div class="download">
+ <button class="download-button" id="download" aria-haspopup="menu" aria-expanded="false"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v11m-5-5 5 5 5-5M5 20h14"/></svg><span id="download-label">Download</span></button>
+ <div class="download-menu" id="download-menu" role="menu" hidden>
+ <button role="menuitem" id="download-all"><strong>Whole preview</strong><span>Final film and its drafts in one MP4</span></button>
+ <button role="menuitem" id="download-final"><strong>Final film only</strong><span>The original reference video</span></button>
+ </div>
+ </div>
+</header>
+<main class="stage" id="stage">
+ <section class="final" aria-label="Final video">
+ <video id="final-video" muted playsinline loop preload="auto"></video>
+ <button class="final-toggle" id="final-toggle" aria-label="Pause"><span class="final-icon" aria-hidden="true"></span></button>
+ <button class="sound" id="sound" aria-label="Unmute" aria-pressed="false">Sound off</button>
+ </section>
+ <section class="strip" id="strip" aria-label="Sections">
+ <div class="scraps" id="scraps"></div>
+ <div class="playhead" id="playhead"><span></span></div>
+ </section>
+ <div class="times"><strong id="time-now">0:00.0</strong><span id="time-total">0:00</span></div>
+ <input class="seek" id="seek" type="range" min="0" max="1" step="0.01" value="0" aria-label="Seek">
+</main>
+<section class="library" aria-labelledby="library-title">
+ <div class="library-head"><h2 id="library-title">All videos</h2><span id="library-count"></span></div>
+ <div class="library-grid" id="library"></div>
+</section>
+</body>
+</html>
diff --git a/public/demo.mjs b/public/demo.mjs
new file mode 100644
index 0000000..8b6de6d
--- /dev/null
+++ b/public/demo.mjs
@@ -0,0 +1,350 @@
+import { buildScrap, scrapNames } from './scraps.mjs';
+import { buildDraft } from './drafts.mjs';
+
+// The full reference plays on top; below it, the super-simple HyperFrames drafts it grew
+// from — one per section. The draft for the section on screen follows the film exactly;
+// the rest keep looping their own part. Each draft is as wide as its section is long, and
+// the playhead runs straight across them.
+const HAND_BUILT = { id: '5924a2f28506', cuts: [0, 3, 5.75, 9.5, 13, 16.5] };
+const $ = id => document.getElementById(id);
+const video = $('final-video');
+const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
+let references = [], drafts = { aliases: {}, drafts: {} }, bounds = {}, cuts = {}, current = null, duration = 1;
+let sections = [], clock = performance.now(), dragging = false, exporting = null;
+
+const clockText = t => `${Math.floor(t / 60)}:${String(Math.floor(t % 60)).padStart(2, '0')}`;
+const preciseText = t => `${clockText(t)}.${Math.floor((t % 1) * 10)}`;
+const sectionAt = t => Math.max(0, sections.findLastIndex(section => t >= section.start));
+const shortName = reference => reference.name.split(' · ')[0].split(' ')[0];
+
+// ---------- Sections ----------
+function planSections(reference) {
+ if (reference.id === HAND_BUILT.id) {
+ return HAND_BUILT.cuts.map((start, index) => ({ start, end: HAND_BUILT.cuts[index + 1] ?? duration, name: scrapNames[index], scrap: index }));
+ }
+ const key = drafts.aliases[reference.id] || reference.id, spec = drafts.drafts[key];
+ let spans = bounds[reference.id] || bounds[key];
+ if (!spans?.length) {
+ const count = Math.max(3, Math.min(8, Math.round(duration / 4.5)));
+ spans = Array.from({ length: count }, (_, i) => ({ start: duration * i / count, end: duration * (i + 1) / count }));
+ }
+ const sceneCuts = cuts[reference.id] || cuts[key] || [];
+ return spans.map(({ start, end }, index) => {
+ const section = spec?.sections[index], beats = section?.beats || [['text', `Part ${index + 1}`]];
+ end = index === spans.length - 1 ? duration : end;
+ return { start, end, name: section?.name || `Part ${index + 1}`, beats, starts: beatStarts(beats.length, start, end, sceneCuts),
+ palette: spec?.palette || { bg: '#111113', fg: '#f1f1f1', accent: '#ff5a1f' } };
+ });
+}
+// A two-beat draft switches where the film itself cuts: the scene change between 30% and
+// 80% of the section (where its two reference frames were sampled) nearest the middle.
+function beatStarts(count, start, end, sceneCuts) {
+ const length = end - start;
+ if (count !== 2) return Array.from({ length: count }, (_, i) => length * i / count);
+ const inside = sceneCuts.map(cut => cut - start).filter(t => t > length * .3 && t < length * .8);
+ inside.sort((a, b) => Math.abs(a - length * .55) - Math.abs(b - length * .55));
+ return [0, inside[0] ?? length * .55];
+}
+
+function buildSections() {
+ sections.forEach(section => section.timeline?.kill());
+ sections = planSections(current);
+ const row = $('scraps'); row.replaceChildren(); row.dataset.count = sections.length;
+ sections.forEach(section => {
+ section.length = section.end - section.start;
+ const segment = document.createElement('div');
+ segment.className = 'seg';
+ const card = document.createElement('div'); card.className = 'scrap';
+ const canvas = document.createElement('div'); canvas.className = 'scrap-canvas';
+ const name = document.createElement('div'); name.className = 'seg-name'; name.textContent = section.name;
+ card.append(canvas); segment.append(card, name); row.append(segment);
+ section.canvas = canvas; section.card = card; section.segment = segment;
+ section.timeline = section.scrap !== undefined ? buildScrap(section.scrap, canvas, section.length) : buildDraft(canvas, section.beats, section.length, section.palette, section.starts);
+ section.loop = section.length * .55;
+ });
+ $('time-total').textContent = clockText(duration);
+ $('bar-meta').textContent = `${shortName(current)} · from ${sections.length} HyperFrames drafts`;
+ layout();
+}
+
+// ---------- Geometry shared by the page and the export ----------
+function spans() {
+ const origin = $('strip').getBoundingClientRect().left;
+ return sections.map(section => { const box = section.card.getBoundingClientRect(); return { left: box.left - origin, width: box.width }; });
+}
+function timeToX(time, layout) {
+ const index = sectionAt(time), box = layout[index], section = sections[index];
+ if (!box) return 0;
+ return box.left + box.width * Math.min(1, Math.max(0, (time - section.start) / section.length));
+}
+
+function layout() {
+ for (const section of sections) section.card.style.setProperty('--scale', section.card.clientWidth / 640);
+ $('strip').style.setProperty('--card-h', `${sections[0]?.card.clientHeight || 60}px`);
+ render();
+}
+
+function render() {
+ if (exporting) return; // the export drives the drafts' timelines itself
+ const now = performance.now(), delta = (now - clock) / 1000; clock = now;
+ const time = video.currentTime || 0, active = sectionAt(time), layout = spans();
+ sections.forEach((section, index) => {
+ const isActive = index === active;
+ if (!video.paused && !reducedMotion) section.loop = (section.loop + delta) % section.length;
+ section.timeline.seek(isActive ? time - section.start : section.loop, false);
+ section.segment.classList.toggle('active', isActive);
+ });
+ $('playhead').style.left = `${timeToX(time, layout)}px`;
+ $('seek').value = time; $('seek').max = duration;
+ $('time-now').textContent = preciseText(time);
+ document.querySelector('.final').classList.toggle('paused', video.paused);
+}
+function frame() { render(); requestAnimationFrame(frame); }
+
+// ---------- Library ----------
+function renderLibrary() {
+ $('library').replaceChildren(...references.map(reference => {
+ const card = document.createElement('button');
+ card.type = 'button'; card.className = 'video-card'; card.dataset.id = reference.id;
+ card.innerHTML = '<span class="video-thumb"><img alt="" loading="lazy"><span class="video-length"></span></span><span class="video-name"></span>';
+ card.querySelector('img').src = reference.poster;
+ card.querySelector('.video-length').textContent = clockText(reference.duration);
+ card.querySelector('.video-name').textContent = reference.name;
+ card.addEventListener('click', () => { load(reference); scrollTo({ top: 0, behavior: reducedMotion ? 'instant' : 'smooth' }); });
+ card.addEventListener('mouseenter', () => hoverPreview(card, reference));
+ card.addEventListener('mouseleave', () => card.querySelector('video')?.remove());
+ return card;
+ }));
+ $('library-count').textContent = `${references.length} references`;
+}
+function hoverPreview(card, reference) {
+ if (reducedMotion || !matchMedia('(hover: hover)').matches) return;
+ const player = Object.assign(document.createElement('video'), { muted: true, playsInline: true, loop: true, preload: 'metadata', src: reference.src });
+ player.addEventListener('loadedmetadata', () => { player.currentTime = Math.min(reference.duration * .3, 4); player.play().catch(() => {}); });
+ card.querySelector('.video-thumb').append(player);
+}
+
+function load(reference) {
+ if (exporting || current?.id === reference.id) return;
+ current = reference; duration = reference.duration;
+ video.src = reference.src; video.poster = reference.poster;
+ document.querySelectorAll('.video-card').forEach(card => card.classList.toggle('current', card.dataset.id === reference.id));
+ history.replaceState(null, '', reference.id === HAND_BUILT.id ? '/' : `/?v=${encodeURIComponent(reference.id)}`);
+ buildSections();
+ if (!reducedMotion) video.play().catch(() => {});
+}
+
+// ---------- Controls ----------
+function seekFrom(event) {
+ const layout = spans(), x = event.clientX - $('strip').getBoundingClientRect().left;
+ let index = layout.findIndex(box => x < box.left + box.width + 3);
+ if (index < 0) index = layout.length - 1;
+ const box = layout[index], section = sections[index];
+ video.currentTime = Math.min(duration - .01, section.start + section.length * Math.min(1, Math.max(0, (x - box.left) / box.width)));
+ render();
+}
+$('strip').addEventListener('pointerdown', event => { if (exporting) return; dragging = true; $('strip').setPointerCapture(event.pointerId); seekFrom(event); });
+$('strip').addEventListener('pointermove', event => { if (dragging) seekFrom(event); });
+$('strip').addEventListener('pointerup', () => { dragging = false; });
+$('seek').addEventListener('input', () => { video.currentTime = Number($('seek').value); render(); });
+$('final-toggle').addEventListener('click', () => {
+ if (exporting) return;
+ if (video.paused) video.play().catch(() => {}); else video.pause();
+ $('final-toggle').setAttribute('aria-label', video.paused ? 'Play' : 'Pause');
+});
+$('sound').addEventListener('click', () => {
+ video.muted = !video.muted;
+ $('sound').textContent = video.muted ? 'Sound off' : 'Sound on';
+ $('sound').setAttribute('aria-pressed', !video.muted);
+ $('sound').setAttribute('aria-label', video.muted ? 'Unmute' : 'Mute');
+});
+document.addEventListener('keydown', event => {
+ if (event.code === 'Space' && !event.target.closest('button, input')) { event.preventDefault(); $('final-toggle').click(); }
+});
+new ResizeObserver(layout).observe($('stage'));
+
+// ---------- Download ----------
+// "Whole preview" renders the film and its drafts frame by frame, not in real time: a hidden
+// copy of the film plays, every decoded frame is captured exactly once, the drafts are drawn
+// at that frame's exact time, and the result is encoded at a high bitrate with the frame's
+// own timestamp (WebCodecs + mp4-muxer). The film's audio is added from the reference.
+// The frame is the film plus the drafts and their names, with a thin margin of page.
+const EXPORT_WIDTH = 1920, EXPORT_MARGIN = 20;
+function exportGeometry() {
+ const film = document.querySelector('.final').getBoundingClientRect(), strip = $('strip').getBoundingClientRect();
+ const left = film.left - EXPORT_MARGIN, top = film.top - EXPORT_MARGIN;
+ const scale = EXPORT_WIDTH / (film.width + EXPORT_MARGIN * 2);
+ const map = rect => ({ x: (rect.left - left) * scale, y: (rect.top - top) * scale, w: rect.width * scale, h: rect.height * scale });
+ const playhead = $('playhead').getBoundingClientRect();
+ return {
+ scale, width: EXPORT_WIDTH, height: Math.round((strip.bottom - film.top + EXPORT_MARGIN * 2) * scale / 2) * 2,
+ film: map(film), layout: spans(), stripLeft: (strip.left - left) * scale, playheadTop: (playhead.top - top) * scale, playheadHeight: playhead.height * scale,
+ cards: sections.map(section => map(section.card.getBoundingClientRect())),
+ names: sections.map(section => map(section.segment.querySelector('.seg-name').getBoundingClientRect()))
+ };
+}
+function rasterize(section) {
+ const node = section.canvas.cloneNode(true); node.style.transform = 'none';
+ const markup = `<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><foreignObject width="640" height="360">${new XMLSerializer().serializeToString(node)}</foreignObject></svg>`;
+ const image = new Image(); image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(markup);
+ return image.decode().then(() => image, () => null);
+}
+async function drawExportFrame(context, geometry, film, time) {
+ const { scale } = geometry, active = sectionAt(time);
+ const rounded = (x, y, w, h, r) => { context.beginPath(); context.roundRect(x, y, w, h, r); };
+ // Same rule as the page: the current section follows the film, the rest loop their part.
+ sections.forEach((section, index) => section.timeline.seek(index === active ? time - section.start : (section.length * .55 + time) % section.length, false));
+ const drafts = await Promise.all(sections.map(rasterize));
+ context.fillStyle = '#0b0b0c'; context.fillRect(0, 0, geometry.width, geometry.height);
+ const f = geometry.film;
+ context.save(); rounded(f.x, f.y, f.w, f.h, 14 * scale); context.clip(); context.drawImage(film, f.x, f.y, f.w, f.h); context.restore();
+ context.textBaseline = 'middle'; context.textAlign = 'center'; context.font = `500 ${12.5 * scale}px Inter, system-ui, sans-serif`;
+ sections.forEach((section, index) => {
+ const { x, y, w, h } = geometry.cards[index], isActive = index === active;
+ context.save(); rounded(x, y, w, h, 8 * scale); context.clip();
+ context.fillStyle = '#ffffff'; context.fillRect(x, y, w, h);
+ if (drafts[index]) context.drawImage(drafts[index], x, y, w, h);
+ context.restore();
+ const line = (isActive ? 2 : 1) * scale;
+ context.strokeStyle = isActive ? '#ff5a1f' : '#222225'; context.lineWidth = line;
+ rounded(x - line / 2, y - line / 2, w + line, h + line, 8 * scale + line / 2); context.stroke();
+ const name = geometry.names[index];
+ context.save(); context.beginPath(); context.rect(name.x, name.y - 4 * scale, name.w, name.h + 8 * scale); context.clip();
+ context.fillStyle = isActive ? '#ededee' : '#7d7d83'; context.fillText(section.name, name.x + name.w / 2, name.y + name.h / 2);
+ context.restore();
+ });
+ const px = geometry.stripLeft + timeToX(time, geometry.layout) * scale, py = geometry.playheadTop;
+ // White with a thin dark edge, as on the page, so it reads over white drafts too.
+ context.fillStyle = 'rgba(0,0,0,.45)'; context.fillRect(px - 2 * scale, py + 5 * scale, 4 * scale, geometry.playheadHeight - 5 * scale);
+ context.beginPath(); context.arc(px, py + 5 * scale, 6 * scale, 0, Math.PI * 2); context.fill();
+ context.fillStyle = '#ffffff'; context.fillRect(px - scale, py + 5 * scale, 2 * scale, geometry.playheadHeight - 5 * scale);
+ context.beginPath(); context.arc(px, py + 5 * scale, 5 * scale, 0, Math.PI * 2); context.fill();
+}
+async function referenceAudio(reference) {
+ try {
+ const response = await fetch(reference.src.replace(/\.mp4$/, '.aac'));
+ if (!response.ok) return null;
+ return await new OfflineAudioContext(2, 1, 48000).decodeAudioData(await response.arrayBuffer());
+ } catch { return null; }
+}
+async function encodeAudio(buffer, muxer, seconds) {
+ let failure = null;
+ const encoder = new AudioEncoder({ output: (chunk, meta) => muxer.addAudioChunk(chunk, meta), error: error => { failure = error; } });
+ const channels = buffer.numberOfChannels, rate = buffer.sampleRate;
+ encoder.configure({ codec: 'mp4a.40.2', sampleRate: rate, numberOfChannels: channels, bitrate: 192000 });
+ const total = Math.min(buffer.length, Math.round(seconds * rate)), step = rate;
+ for (let offset = 0; offset < total && !failure; offset += step) {
+ const frames = Math.min(step, total - offset), data = new Float32Array(frames * channels);
+ for (let c = 0; c < channels; c++) data.set(buffer.getChannelData(c).subarray(offset, offset + frames), c * frames);
+ const chunk = new AudioData({ format: 'f32-planar', sampleRate: rate, numberOfFrames: frames, numberOfChannels: channels, timestamp: Math.round(offset / rate * 1e6), data });
+ encoder.encode(chunk); chunk.close();
+ }
+ await encoder.flush(); encoder.close();
+ if (failure) throw failure;
+}
+function save(url, name) {
+ const link = Object.assign(document.createElement('a'), { href: url, download: name });
+ document.body.append(link); link.click(); link.remove();
+}
+const fileName = reference => reference.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || reference.id;
+async function exportPreview() {
+ if (exporting || !current) return;
+ if (!('VideoEncoder' in window) || !('requestVideoFrameCallback' in HTMLVideoElement.prototype)) {
+ $('download-label').textContent = 'Needs Chrome or Edge'; setTimeout(() => { $('download-label').textContent = 'Download'; }, 2500); return;
+ }
+ const reference = current, geometry = exportGeometry(), wasPlaying = !video.paused;
+ exporting = true; video.pause(); $('download').disabled = true; $('download-label').textContent = 'Preparing…';
+ const canvas = Object.assign(document.createElement('canvas'), { width: geometry.width, height: geometry.height });
+ const context = canvas.getContext('2d');
+ const film = Object.assign(document.createElement('video'), { muted: true, playsInline: true, preload: 'auto', src: reference.src });
+ film.style.cssText = 'position:fixed;left:0;top:0;width:2px;height:2px;opacity:0;pointer-events:none';
+ document.body.append(film);
+ let encoder;
+ try {
+ const [audio] = await Promise.all([referenceAudio(reference), new Promise((resolve, reject) => { film.onloadeddata = resolve; film.onerror = reject; })]);
+ const muxer = new Mp4Muxer.Muxer({
+ target: new Mp4Muxer.ArrayBufferTarget(), fastStart: 'in-memory', firstTimestampBehavior: 'offset',
+ video: { codec: 'avc', width: geometry.width, height: geometry.height },
+ ...(audio ? { audio: { codec: 'aac', numberOfChannels: audio.numberOfChannels, sampleRate: audio.sampleRate } } : {})
+ });
+ let failure = null;
+ encoder = new VideoEncoder({ output: (chunk, meta) => muxer.addVideoChunk(chunk, meta), error: error => { failure = error; } });
+ encoder.configure({ codec: 'avc1.640033', width: geometry.width, height: geometry.height, bitrate: 24e6, framerate: 30, latencyMode: 'quality', avc: { format: 'avc' } });
+
+ // Capture every decoded frame. If encoding falls behind, pause the hidden film until it
+ // catches up, so no frame is ever skipped.
+ const queue = []; let ended = false, lastKey = -Infinity, lastTime = -1, working = false, wake = null;
+ const capture = (now, meta) => {
+ if (meta.mediaTime > lastTime) { lastTime = meta.mediaTime; queue.push({ time: meta.mediaTime, frame: new VideoFrame(film, { timestamp: Math.round(meta.mediaTime * 1e6) }) }); }
+ if (queue.length >= 2) film.pause();
+ if (!ended) film.requestVideoFrameCallback(capture);
+ wake?.();
+ };
+ film.requestVideoFrameCallback(capture);
+ film.onended = () => { ended = true; wake?.(); };
+ film.playbackRate = .5; // headroom so the renderer never lets a frame slip by
+ await film.play();
+ while (!failure) {
+ if (!queue.length) {
+ if (ended) break;
+ if (film.paused && !working) film.play().catch(() => {});
+ await new Promise(resolve => { wake = resolve; setTimeout(resolve, 250); }); wake = null;
+ continue;
+ }
+ working = true;
+ const { time, frame } = queue.shift();
+ await drawExportFrame(context, geometry, frame, time); frame.close();
+ const output = new VideoFrame(canvas, { timestamp: Math.round(time * 1e6) });
+ const keyFrame = time - lastKey >= 2; if (keyFrame) lastKey = time;
+ encoder.encode(output, { keyFrame }); output.close();
+ while (encoder.encodeQueueSize > 4) await new Promise(resolve => setTimeout(resolve, 5));
+ working = false;
+ if (film.paused && !ended && queue.length < 2) film.play().catch(() => {});
+ $('download-label').textContent = `Rendering ${Math.min(99, Math.floor(time / reference.duration * 100))}%`;
+ }
+ queue.forEach(item => item.frame.close());
+ if (failure) throw failure;
+ await encoder.flush();
+ if (audio) { $('download-label').textContent = 'Adding sound…'; await encodeAudio(audio, muxer, lastTime + 1 / 30); }
+ muxer.finalize();
+ const url = URL.createObjectURL(new Blob([muxer.target.buffer], { type: 'video/mp4' }));
+ save(url, `${fileName(reference)}-null-preview.mp4`);
+ setTimeout(() => URL.revokeObjectURL(url), 60000);
+ $('download-label').textContent = 'Download';
+ } catch (error) {
+ console.error('Export failed', error);
+ $('download-label').textContent = 'Export failed';
+ setTimeout(() => { $('download-label').textContent = 'Download'; }, 3000);
+ } finally {
+ if (encoder && encoder.state !== 'closed') encoder.close();
+ film.pause(); film.removeAttribute('src'); film.load(); film.remove();
+ exporting = null; $('download').disabled = false;
+ if (wasPlaying) video.play().catch(() => {});
+ }
+}
+function toggleMenu(open = $('download-menu').hidden) {
+ $('download-menu').hidden = !open; $('download').setAttribute('aria-expanded', open);
+ if (open) $('download-all').focus();
+}
+$('download').addEventListener('click', () => toggleMenu());
+$('download-all').addEventListener('click', () => { toggleMenu(false); exportPreview(); });
+$('download-final').addEventListener('click', () => { toggleMenu(false); if (current) save(current.src, `${fileName(current)}.mp4`); });
+document.addEventListener('click', event => { if (!event.target.closest('.download')) toggleMenu(false); });
+document.addEventListener('keydown', event => { if (event.key === 'Escape' && !$('download-menu').hidden) { toggleMenu(false); $('download').focus(); } });
+
+async function start() {
+ const json = async url => { try { const response = await fetch(url); return response.ok ? await response.json() : null; } catch { return null; } };
+ const [catalog, spec, planned, changes] = await Promise.all([json('/api/references'), json('/references/drafts.json'), json('/references/sections.json'), json('/references/cuts.json')]);
+ references = catalog?.references || []; drafts = spec || drafts; bounds = planned || {}; cuts = changes || {};
+ if (!references.length) {
+ const notice = document.createElement('div'); notice.className = 'notice';
+ notice.textContent = 'Import the MotionClone references to play this preview.';
+ document.querySelector('.final').append(notice);
+ return;
+ }
+ renderLibrary();
+ const wanted = new URLSearchParams(location.search).get('v');
+ load(references.find(reference => reference.id === wanted) || references.find(reference => reference.id === HAND_BUILT.id) || references[0]);
+ requestAnimationFrame(frame);
+}
+start();
diff --git a/public/drafts.mjs b/public/drafts.mjs
new file mode 100644
index 0000000..8c92733
--- /dev/null
+++ b/public/drafts.mjs
@@ -0,0 +1,254 @@
+// Super-simple HyperFrames drafts. A draft is a 640×360 HTML scene driven by a paused GSAP
+// timeline. Each section of a reference is described by one or two "beats" — [kind, text,
+// options] — and every kind is a deliberately basic layout: flat shapes, plain type, one
+// entrance and a slow drift.
+const W = 640, H = 360;
+
+function el(parent, css, text) {
+ const node = document.createElement('div');
+ node.style.cssText = 'position:absolute;' + css;
+ if (text !== undefined) node.textContent = text;
+ parent.append(node);
+ return node;
+}
+const center = 'left:50%;top:50%;transform:translate(-50%,-50%);';
+const fontFor = text => text.length < 8 ? 84 : text.length < 16 ? 50 : text.length < 28 ? 36 : 28;
+const bars = (parent, count, css, color) => Array.from({ length: count }, (_, i) =>
+ el(parent, `left:0;top:${i * 18}px;height:8px;border-radius:4px;width:${[100, 82, 64, 90, 70][i % 5]}%;background:${color};`)).map((bar, i, all) => (bar.style.position = 'absolute', bar));
+function drift(tl, target, span, amount = .04) { tl.fromTo(target, { scale: 1 }, { scale: 1 + amount, duration: span, ease: 'none' }, 0); }
+
+function words(parent, text, size, c, css = '', weight = size >= 64 ? 700 : 400) {
+ const row = el(parent, `${center}width:580px;display:flex;flex-wrap:wrap;justify-content:center;gap:0 .26em;font-size:${size}px;line-height:1.1;font-weight:${weight};letter-spacing:${size >= 64 ? '-.03em' : '0'};text-align:center;${css}`);
+ for (const word of text.split(' ')) {
+ const span = document.createElement('span');
+ span.textContent = word; span.style.display = 'inline-block';
+ row.append(span);
+ }
+ return row;
+}
+const placed = o => o.x !== undefined || o.y !== undefined ? `left:${(o.x ?? .5) * W}px;top:${(o.y ?? .5) * H}px;` : '';
+
+const KINDS = {
+ text(b, t, o, c, tl, span) {
+ const row = words(b, t, o.size || fontFor(t), c, placed(o), o.weight);
+ tl.from(row.children, { y: 24, opacity: 0, stagger: .09, duration: .45, ease: 'power3.out' }, 0);
+ drift(tl, row, span);
+ },
+ logo(b, t, o, c, tl, span) {
+ const group = el(b, `${center}display:flex;align-items:center;gap:18px;white-space:nowrap`);
+ const mark = o.mark ? el(group, `position:relative;font-size:${o.markSize || 56}px;line-height:1;font-weight:700`, o.mark)
+ : el(group, `position:relative;width:48px;height:48px;border-radius:12px;background:${c.fg};flex:none`);
+ const word = el(group, `position:relative;font-size:${o.size || (t.length > 10 ? 36 : 48)}px;font-weight:700;letter-spacing:-.02em`, t);
+ tl.from(mark, { scale: 0, rotation: -40, duration: .55, ease: 'back.out(1.8)' }, 0);
+ tl.fromTo(word, { clipPath: 'inset(0 100% 0 0)' }, { clipPath: 'inset(0 0% 0 0)', duration: .6, ease: 'power2.out' }, .3);
+ if (o.sub) {
+ const sub = el(b, `left:0;right:0;top:${H / 2 + 50}px;text-align:center;font-size:18px;color:${c.muted}`, o.sub);
+ tl.from(sub, { opacity: 0, y: 8, duration: .4 }, .8);
+ }
+ drift(tl, group, span, .03);
+ },
+ input(b, t, o, c, tl, span) {
+ if (o.h) { const title = el(b, `left:0;right:0;top:64px;text-align:center;font-size:32px;font-weight:700`, o.h); tl.from(title, { opacity: 0, y: 12, duration: .4 }, 0); }
+ const box = el(b, `left:100px;top:${o.h ? 130 : 130}px;width:440px;height:100px;border-radius:18px;border:2px solid ${c.line};background:${c.card}`);
+ const typed = el(box, `left:22px;top:20px;right:60px;font-size:20px;white-space:nowrap;overflow:hidden`, t);
+ el(box, `left:22px;bottom:16px;font-size:22px;color:${c.muted}`, '+');
+ const send = el(box, `right:16px;bottom:14px;width:30px;height:30px;border-radius:50%;background:${c.accent}`);
+ tl.from(box, { opacity: 0, y: 20, duration: .4, ease: 'power2.out' }, .1);
+ tl.fromTo(typed, { clipPath: 'inset(0 100% 0 0)' }, { clipPath: 'inset(0 0% 0 0)', duration: Math.min(1.6, span * .5), ease: `steps(${Math.max(4, t.length)})` }, .4);
+ tl.to(send, { scale: 1.25, duration: .15, yoyo: true, repeat: 1 }, Math.min(2.1, span * .7));
+ },
+ chat(b, t, o, c, tl, span) {
+ const bubble = el(b, `right:70px;top:70px;max-width:360px;padding:16px 20px;border-radius:18px 18px 4px 18px;background:${c.accent};color:${c.onAccent};font-size:20px;line-height:1.3`, t);
+ const reply = el(b, 'left:70px;top:200px;width:380px;height:80px');
+ el(reply, `left:0;top:0;width:34px;height:34px;border-radius:50%;background:${c.muted}`);
+ const lines = el(reply, 'left:50px;top:6px;right:0;height:60px');
+ const rows = bars(lines, 3, '', c.line);
+ tl.from(bubble, { opacity: 0, y: 16, scale: .95, duration: .4, ease: 'power2.out' }, .1);
+ tl.from(reply, { opacity: 0, duration: .3 }, .7);
+ tl.from(rows, { width: 0, stagger: .15, duration: .5 }, .8);
+ },
+ window(b, t, o, c, tl, span) {
+ const win = el(b, `left:90px;top:44px;width:460px;height:272px;border-radius:14px;border:2px solid ${c.line};background:${c.card};overflow:hidden`);
+ [0, 1, 2].forEach(i => el(win, `left:${14 + i * 14}px;top:12px;width:8px;height:8px;border-radius:50%;background:${c.line}`));
+ el(win, 'left:0;right:0;top:32px;height:2px;background:' + c.line);
+ const side = el(win, `left:14px;top:48px;width:70px;bottom:14px`); bars(side, 6, '', c.line);
+ const title = el(win, `left:100px;top:46px;right:16px;font-size:${t.length > 24 ? 16 : 20}px;font-weight:700;white-space:nowrap;overflow:hidden`, t);
+ const tiles = [0, 1, 2].map(i => el(win, `left:${100 + i * 116}px;top:86px;width:104px;height:60px;border-radius:8px;background:${c.fill};border:1.5px solid ${c.line}`));
+ const block = el(win, `left:100px;top:160px;right:16px;bottom:16px;border-radius:8px;background:${c.fill};border:1.5px solid ${c.line}`);
+ const pointer = el(b, `left:470px;top:300px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-bottom:20px solid ${c.fg};transform:rotate(-25deg)`);
+ tl.from(win, { opacity: 0, y: 30, scale: .95, duration: .5, ease: 'power3.out' }, 0);
+ tl.from([title, ...tiles, block], { opacity: 0, y: 8, stagger: .08, duration: .3 }, .35);
+ tl.fromTo(pointer, { x: 0, y: 0 }, { x: -260, y: -150, duration: span * .8, ease: 'sine.inOut' }, .3);
+ },
+ phone(b, t, o, c, tl, span) {
+ const stacked = o.stack && t;
+ const phone = el(b, `left:${stacked || !t ? 245 : 110}px;top:${stacked ? 96 : 34}px;width:150px;height:292px;border-radius:28px;border:3px solid ${c.fg};background:${c.card};overflow:hidden`);
+ el(phone, `left:50px;top:10px;width:44px;height:10px;border-radius:5px;background:${c.fg}`);
+ const rows = [0, 1, 2, 3, 4].map(i => el(phone, `left:12px;right:12px;top:${40 + i * 48}px;height:38px;border-radius:9px;background:${i === 1 ? c.fg : c.fill}`));
+ tl.from(phone, { y: 80, opacity: 0, duration: .55, ease: 'power3.out' }, 0);
+ tl.from(rows, { opacity: 0, x: -10, stagger: .08, duration: .3 }, .4);
+ if (stacked) {
+ const caption = words(b, t, 28, c, 'top:56px', 700);
+ tl.from(caption.children, { opacity: 0, y: 10, stagger: .08, duration: .35 }, .2);
+ } else if (t) {
+ const caption = words(b, t, t.length > 20 ? 28 : 36, c, 'left:300px;transform:translateY(-50%);width:300px;justify-content:flex-start;text-align:left');
+ tl.from(caption.children, { opacity: 0, y: 14, stagger: .08, duration: .35 }, .5);
+ }
+ drift(tl, phone, span, .03);
+ },
+ cards(b, t, o, c, tl, span) {
+ const top = t ? 104 : 70;
+ if (t) { const title = el(b, `left:0;right:0;top:40px;text-align:center;font-size:30px;font-weight:700`, t); tl.from(title, { opacity: 0, y: 10, duration: .4 }, 0); }
+ const tiles = Array.from({ length: 6 }, (_, i) => el(b, `left:${95 + (i % 3) * 154}px;top:${top + Math.floor(i / 3) * 112}px;width:142px;height:98px;border-radius:12px;background:${i % 2 ? c.card : c.fill};border:1.5px solid ${c.line}`));
+ tl.from(tiles, { scale: 0, opacity: 0, stagger: .07, duration: .4, ease: 'back.out(1.6)' }, .2);
+ drift(tl, tiles, span, .03);
+ },
+ list(b, t, o, c, tl, span) {
+ const items = t.split('|');
+ const box = el(b, `left:110px;top:${180 - items.length * 30}px;width:420px`);
+ items.forEach((item, i) => {
+ const row = el(box, `left:0;top:${i * 60}px;right:0;height:44px;display:flex;align-items:center;gap:16px;font-size:22px;font-weight:600`);
+ const dot = el(row, `position:relative;width:26px;height:26px;border-radius:50%;border:3px solid ${c.fg};flex:none`);
+ row.append(item);
+ tl.from(row, { opacity: 0, x: -16, duration: .35 }, .15 + i * .15);
+ tl.to(dot, { backgroundColor: c.accent, borderColor: c.accent, duration: .2 }, .9 + i * Math.min(.6, span / 6));
+ });
+ },
+ chart(b, t, o, c, tl, span) {
+ const svgNS = 'http://www.w3.org/2000/svg';
+ const svg = document.createElementNS(svgNS, 'svg');
+ svg.setAttribute('width', W); svg.setAttribute('height', H); svg.style.cssText = 'position:absolute;left:0;top:0';
+ const axis = document.createElementNS(svgNS, 'path'); axis.setAttribute('d', 'M80 60 V300 H560'); axis.setAttribute('stroke', c.line); axis.setAttribute('stroke-width', '3'); axis.setAttribute('fill', 'none');
+ const line = document.createElementNS(svgNS, 'path'); line.setAttribute('d', 'M90 270 C170 250 200 200 260 210 S360 120 420 140 S500 80 550 70');
+ line.setAttribute('stroke', c.accent); line.setAttribute('stroke-width', '6'); line.setAttribute('fill', 'none'); line.setAttribute('stroke-linecap', 'round');
+ line.setAttribute('stroke-dasharray', '700'); line.setAttribute('stroke-dashoffset', '700');
+ svg.append(axis, line); b.append(svg);
+ tl.to(line, { attr: { 'stroke-dashoffset': 0 }, duration: Math.min(2, span * .7), ease: 'power2.inOut' }, .2);
+ if (t) { const tag = el(b, `left:380px;top:170px;padding:10px 18px;border-radius:12px;background:${c.card};border:2px solid ${c.line};font-size:24px;font-weight:700`, t); tl.from(tag, { opacity: 0, scale: .8, duration: .35 }, .9); }
+ },
+ notify(b, t, o, c, tl, span) {
+ const pill = el(b, `left:110px;top:130px;width:420px;height:84px;border-radius:22px;background:${c.card};border:2px solid ${c.line};display:flex;align-items:center;gap:16px;padding:0 18px;box-sizing:border-box`);
+ el(pill, `position:relative;width:46px;height:46px;border-radius:12px;background:${c.accent};flex:none`);
+ el(pill, 'position:relative;font-size:20px;font-weight:700;white-space:nowrap;overflow:hidden', t);
+ tl.from(pill, { y: -160, duration: .6, ease: 'back.out(1.3)' }, .1);
+ drift(tl, pill, span, .03);
+ },
+ icons(b, t, o, c, tl, span) {
+ const dots = Array.from({ length: 15 }, (_, i) => el(b, `left:${140 + (i % 5) * 80}px;top:${70 + Math.floor(i / 5) * 80}px;width:56px;height:56px;border-radius:${i % 2 ? 50 : 14}%;background:${i % 3 ? c.fill : c.fg};border:1.5px solid ${c.line}`));
+ tl.from(dots, { scale: 0, duration: .4, stagger: { each: .04, from: 'center' }, ease: 'back.out(2)' }, 0);
+ tl.to(b, { rotation: 4, duration: span, ease: 'none' }, 0);
+ },
+ hub(b, t, o, c, tl, span) {
+ const core = el(b, `${center}width:96px;height:96px;border-radius:26px;background:${c.accent}`);
+ const pills = [[120, 80], [430, 90], [110, 250], [420, 250]].map(([x, y], i) => el(b, `left:${x}px;top:${y}px;width:110px;height:36px;border-radius:18px;background:${c.card};border:1.5px solid ${c.fg}`));
+ tl.from(core, { scale: 0, duration: .5, ease: 'back.out(2)' }, 0);
+ tl.from(pills, { opacity: 0, x: (i) => i % 2 ? 60 : -60, stagger: .1, duration: .45 }, .3);
+ tl.to(pills, { y: (i) => i < 2 ? 12 : -12, duration: span, ease: 'sine.inOut' }, .3);
+ if (t) { const label = el(b, `left:0;right:0;top:${H / 2 + 70}px;text-align:center;font-size:24px;font-weight:700`, t); tl.from(label, { opacity: 0, duration: .3 }, .6); }
+ },
+ cloud(b, t, o, c, tl, span) {
+ const [main, ...rest] = t.split('|');
+ const spots = [[.3, .2], [.66, .3], [.34, .36], [.8, .54], [.2, .66], [.66, .8], [.5, .88]];
+ const small = rest.map((word, i) => el(b, `left:${spots[i % spots.length][0] * W}px;top:${spots[i % spots.length][1] * H}px;transform:translate(-50%,-50%);font-size:${i === rest.length - 1 ? 30 : 18}px;color:${c.muted};white-space:nowrap`, word));
+ const hero = el(b, `${center}font-size:52px;font-weight:700;letter-spacing:-.02em;white-space:nowrap`, main);
+ tl.from(hero, { opacity: 0, scale: .9, duration: .5, ease: 'power3.out' }, 0);
+ tl.from(small, { opacity: 0, stagger: .1, duration: .4 }, .3);
+ tl.to(small, { y: (i) => i % 2 ? -10 : 10, duration: span, ease: 'sine.inOut' }, .3);
+ },
+ collage(b, t, o, c, tl, span) {
+ const spots = [[70, 40, 90, 70], [460, 30, 100, 80], [60, 230, 110, 80], [470, 220, 90, 90], [260, 250, 80, 60]];
+ const photos = spots.map(([x, y, w, h], i) => el(b, `left:${x}px;top:${y}px;width:${w}px;height:${h}px;border-radius:8px;background:${c.fill};border:1.5px solid ${c.line}`));
+ const row = words(b, t, 34, c);
+ tl.from(photos, { scale: 0, rotation: (i) => i % 2 ? 12 : -12, stagger: .08, duration: .45, ease: 'back.out(1.6)' }, 0);
+ tl.from(row.children, { opacity: 0, y: 14, stagger: .08, duration: .35 }, .4);
+ tl.to(photos, { y: (i) => i % 2 ? -10 : 10, duration: span, ease: 'sine.inOut' }, .4);
+ },
+ logos(b, t, o, c, tl, span) {
+ const rows = [0, 1, 2].map(r => {
+ const strip = el(b, `left:-60px;top:${60 + r * 90}px;display:flex;gap:16px`);
+ for (let i = 0; i < 6; i++) el(strip, `position:relative;width:140px;height:62px;border-radius:14px;background:${(i + r) % 3 ? c.card : c.fill};border:1.5px solid ${c.line}`);
+ return strip;
+ });
+ tl.from(rows, { opacity: 0, duration: .3, stagger: .08 }, 0);
+ tl.to(rows, { x: (i) => i % 2 ? -120 : 90, duration: span, ease: 'none' }, 0);
+ },
+ // A hero object: a flat tile that drops in tilted, settles, then turns slowly in 3D
+ // while a highlight sweeps across it.
+ shape(b, t, o, c, tl, span) {
+ const stage = el(b, `left:${t ? 150 : 250}px;top:110px;width:140px;height:140px;perspective:600px`);
+ const tile = el(stage, `left:0;top:0;width:140px;height:140px;border-radius:32px;background:${c.fill};border:2px solid ${c.fg};overflow:hidden;box-sizing:border-box`);
+ el(tile, `left:36px;top:36px;width:64px;height:64px;border-radius:16px;background:${c.fg}`);
+ const shine = el(tile, `left:-80px;top:-20px;width:40px;height:200px;background:${c.bg};opacity:.35;transform:rotate(20deg)`);
+ const shadow = el(b, `left:${t ? 160 : 260}px;top:278px;width:120px;height:8px;border-radius:50%;background:${c.line}`);
+ tl.fromTo(tile, { y: -60, opacity: 0, rotationX: 50, rotationZ: -12 }, { y: 0, opacity: 1, rotationX: 0, rotationZ: 0, duration: .8, ease: 'back.out(1.4)' }, 0);
+ tl.from(shadow, { scaleX: .3, opacity: 0, duration: .8, ease: 'power2.out' }, 0);
+ tl.to(tile, { rotationY: 28, rotationX: -8, duration: Math.max(1, span - .8), ease: 'sine.inOut' }, .8);
+ tl.fromTo(shine, { x: 0 }, { x: 260, duration: 1.1, ease: 'power2.inOut' }, .7);
+ if (t) { const caption = words(b, t, 40, c, 'left:340px;transform:translateY(-50%);width:270px;justify-content:flex-start;text-align:left'); tl.from(caption.children, { opacity: 0, y: 12, stagger: .08, duration: .35 }, .4); }
+ },
+ burst(b, t, o, c, tl, span) {
+ const line = el(b, `left:0;right:0;top:${H / 2 - 1}px;height:3px;background:${c.fg};transform:scaleX(0)`);
+ const star = el(b, `${center}width:60px;height:60px`);
+ [0, 45].forEach(r => el(star, `left:0;top:0;width:60px;height:60px;background:${c.accent};transform:rotate(${r}deg) scale(.7);border-radius:6px`));
+ tl.to(line, { scaleX: 1, duration: .7, ease: 'power2.out' }, 0);
+ tl.from(star, { scale: 0, rotation: -90, duration: .6, ease: 'back.out(2)' }, .2);
+ tl.to(star, { rotation: 90, duration: span, ease: 'none' }, .8);
+ if (t) { const label = el(b, `left:0;right:0;top:${H / 2 + 50}px;text-align:center;font-size:26px;font-weight:700`, t); tl.from(label, { opacity: 0, duration: .3 }, .6); }
+ },
+ grid(b, t, o, c, tl, span) {
+ const cells = (o.cells || t.split('|')).slice(0, 4);
+ const tiles = cells.map((cell, i) => {
+ const tile = el(b, `left:${i % 2 ? 324 : 12}px;top:${i < 2 ? 12 : 184}px;width:304px;height:164px;border-radius:12px;background:${cell ? c.card : c.fill};border:1.5px solid ${c.line};display:grid;place-items:center;text-align:center;font-size:20px;font-weight:400;padding:0 18px;box-sizing:border-box`, cell);
+ return tile;
+ });
+ tl.from(tiles, { opacity: 0, scale: .9, stagger: .12, duration: .4, ease: 'power2.out' }, 0);
+ drift(tl, tiles, span, .02);
+ },
+ split(b, t, o, c, tl, span) {
+ const panel = el(b, `left:0;top:0;bottom:0;width:300px;background:${c.accent};color:${c.onAccent};display:flex;align-items:center;padding:0 30px;box-sizing:border-box;font-size:28px;font-weight:400;line-height:1.2`, t);
+ const side = el(b, 'left:340px;top:90px;width:250px;height:180px'); const rows = bars(side, 9, '', c.line);
+ tl.from(panel, { xPercent: -100, duration: .55, ease: 'power3.out' }, 0);
+ tl.from(rows, { width: 0, stagger: .05, duration: .35 }, .4);
+ },
+ face(b, t, o, c, tl, span) {
+ const blob = el(b, `left:${t ? 120 : 230}px;top:90px;width:180px;height:180px;border-radius:50%;background:${c.accent}`);
+ const eyes = [60, 100].map(x => el(blob, `left:${x}px;top:80px;width:22px;height:30px;border-radius:50%;background:${c.bg}`));
+ tl.from(blob, { scale: 0, duration: .55, ease: 'back.out(1.8)' }, 0);
+ tl.to(eyes, { scaleY: .1, duration: .08, yoyo: true, repeat: 1 }, Math.min(1.4, span * .5));
+ tl.to(blob, { y: -14, duration: span / 2, yoyo: true, repeat: 1, ease: 'sine.inOut' }, .5);
+ if (t) { const caption = words(b, t, 40, c, 'left:340px;transform:translateY(-50%);width:270px;justify-content:flex-start;text-align:left'); tl.from(caption.children, { opacity: 0, y: 12, stagger: .08, duration: .35 }, .4); }
+ }
+};
+
+const luminance = hex => { const n = parseInt(hex.slice(1), 16); return ((n >> 16) * .3 + ((n >> 8) & 255) * .59 + (n & 255) * .11) / 255; };
+// Drafts are strictly black and white: only whether a frame is light or dark is kept from
+// the finished film; every colour becomes black, white or a grey.
+function colors(palette, override = {}) {
+ let dark = luminance(palette.bg || '#ffffff') < .5;
+ if (override.bg === 'accent') dark = !dark;
+ else if (override.bg) dark = luminance(override.bg) < .5;
+ return dark
+ ? { bg: '#000000', fg: '#ffffff', accent: '#ffffff', onAccent: '#000000', card: '#0d0d0d', line: '#3a3a3a', muted: '#8c8c8c', fill: '#262626' }
+ : { bg: '#ffffff', fg: '#000000', accent: '#000000', onAccent: '#ffffff', card: '#ffffff', line: '#d0d0d0', muted: '#7a7a7a', fill: '#ececec' };
+}
+
+// `starts` optionally gives each beat's start (seconds into the section), so a draft can
+// switch beats exactly where the finished film cuts; otherwise beats share the time evenly.
+export function buildDraft(root, beats, duration, palette = {}, starts = beats.map((_, i) => duration * i / beats.length)) {
+ const base = colors(palette);
+ root.style.cssText += `;background:${base.bg};color:${base.fg};font-family:Arial,Helvetica,sans-serif;overflow:hidden`;
+ const tl = gsap.timeline({ paused: true });
+ beats.forEach(([kind, text = '', options = {}], index) => {
+ const begin = starts[index], span = (starts[index + 1] ?? duration) - begin;
+ const c = colors(palette, options);
+ const beat = el(root, `left:0;top:0;width:${W}px;height:${H}px;overflow:hidden;background:${c.bg};color:${c.fg}`);
+ const local = gsap.timeline();
+ (KINDS[kind] || KINDS.text)(beat, text, options, c, local, span);
+ if (local.duration() < span) local.to({}, { duration: span - local.duration() });
+ tl.add(local, begin);
+ if (index) { gsap.set(beat, { autoAlpha: 0 }); tl.set(beat, { autoAlpha: 1 }, begin); }
+ if (index < beats.length - 1) tl.set(beat, { autoAlpha: 0 }, begin + span);
+ });
+ if (tl.duration() < duration) tl.to({}, { duration: duration - tl.duration() });
+ return tl;
+}
diff --git a/public/editor-preview.css b/public/editor-preview.css
index c66f9f2..6e25b39 100644
--- a/public/editor-preview.css
+++ b/public/editor-preview.css
@@ -1,31 +1,86 @@
-/* Film-first monitor and calmer, more legible workspace chrome. */
-:root{--bg:#111214;--panel:#191a1d;--surface:#222326;--line:#2e3035;--muted:#a0a3ab;--lime:#d7d7fa}
-.topbar{height:64px;background:#151619;padding-inline:24px;border-bottom-color:#292b30}
-.logo-mark{background:#e5e5eb}.logo-dot{color:#c5bef3}.logo{font-size:25px}.project-link,.project-name{font-size:12px}.save-state{font-size:11px}.top-actions .button{font-size:12px;min-height:35px}.avatar{background:#2b2d36;border-color:#4c4d60;color:#d9d6ee}.demo-label{font-size:9px;color:#a2a2ae}
-.rail{width:68px;background:#151619;border-color:#292b30;gap:10px}.rail-item.active{background:#2b2a38;color:#d8d0fa}.rail-item{font-size:10px;height:61px;gap:8px}.rail-item:hover{background:#2b2c33}.rail-bottom{font-size:9px}
-main{max-width:1920px}.studio-heading{height:72px;padding-inline:30px}.studio-title{gap:10px}.studio-title h1{font-size:19px;font-weight:530;letter-spacing:-.6px}.live-dot{width:6px;height:6px;background:#bdb4e9}.subtle-label{font-size:11px;margin-left:14px;color:#989ba5}.view-toggle{background:#191a1e;border-color:#34353e;padding:4px}.view-toggle button{font-size:11px;padding:6px 14px}.view-toggle .active{background:#34343e}
-.upper-workspace{padding:0 30px 22px;grid-template-columns:minmax(0,1fr) 236px;gap:30px;align-items:start}.preview-area{min-width:0;max-width:900px;width:100%;margin:auto}.canvas-top{font-size:10px;letter-spacing:1px;height:33px;padding:0 0 12px;align-items:center}.canvas-top>span{display:flex;align-items:center}.canvas-top>span:last-child{font-size:9px;letter-spacing:.5px;color:#999da7}.monitor-dot{width:6px;height:6px;background:#c4c1e5;display:inline-block;border-radius:50%;margin-right:8px}.monitor-option{background:none;color:#aaa9b8;width:25px;height:23px;font-size:18px;margin-left:12px;border-radius:4px}.monitor-option:hover,.monitor-option[aria-pressed=true]{color:#e0d9ff;background:#35323e}
-.canvas-wrap{width:100%;max-width:800px;margin-inline:auto;aspect-ratio:16/9;height:auto;min-height:0;border:1px solid #393b43;border-radius:10px;background:#07080a;box-shadow:0 22px 50px #0005,0 0 0 5px #ffffff02;overflow:hidden}
-.film-stage{position:relative;width:100%;height:100%;aspect-ratio:auto;max-width:none;max-height:none;background:#07080a;color:#fff;container-type:inline-size;flex-shrink:0;isolation:isolate}
-.film-stage>video{position:absolute;inset:0;display:block;width:100%;height:100%;object-fit:contain;background:#07080a}
-.video-loading{inset:0;z-index:6;background:#121318;color:#adaebb;font-size:12px;letter-spacing:.2px}.video-loading[hidden]{display:none}
-.monitor-brand{position:absolute;left:3.5%;top:6%;display:flex;align-items:center;gap:8px;padding:7px 10px 7px 7px;border:1px solid #ffffff25;border-radius:7px;backdrop-filter:blur(12px);background:#101218b0;box-shadow:0 2px 12px #0002;font-size:1.5cqw;z-index:2;max-width:80%;color:#f6f5fc}
-.monitor-brand .film-monogram{background:var(--accent);color:#16151b;width:2.7cqw;height:2.7cqw;min-width:18px;min-height:18px;border-radius:5px;font-size:1.7cqw;padding:0;letter-spacing:-.1em;font-weight:850}
-#film-brand-name{font-weight:600;font-size:1.6cqw;letter-spacing:-.04em;overflow-wrap:anywhere}.brand-overlay-divider{height:12px;width:1px;background:#ffffff30;margin-inline:4px}.monitor-brand>span:last-child{font-size:.75cqw;letter-spacing:.17em;color:#ddd8ec;white-space:nowrap}
-.monitor-caption{position:absolute;bottom:6%;left:3.5%;max-width:80%;display:flex;gap:9px;align-items:center;padding:10px 13px;background:#0c0d14c9;border:1px solid #ffffff1f;border-radius:5px;backdrop-filter:blur(12px);z-index:2;color:#eeedf6;font-size:1.35cqw;line-height:1.4;letter-spacing:-.01em}
-.caption-accent{display:block;width:3px;height:18px;background:var(--accent);flex-shrink:0;border-radius:3px}.monitor-caption #film-headline{max-width:100%;overflow-wrap:anywhere}.reference-mode .monitor-brand,.reference-mode .monitor-caption,.no-brand .monitor-brand,.no-brand .monitor-caption{display:none}
-.monitor-guides{position:absolute;inset:5%;border:1px dashed #fff6;pointer-events:none;z-index:4}.monitor-guides[hidden]{display:none}.monitor-guides:after{content:"";position:absolute;inset:5.5%;border:1px solid #fff3}.monitor-guides>span{position:absolute;left:50%;top:50%;width:14px;height:14px;transform:translate(-50%,-50%)}.monitor-guides>span:before,.monitor-guides>span:after{content:"";position:absolute;inset:6px 0;background:#fff8;height:1px}.monitor-guides>span:after{transform:rotate(90deg)}
-.canvas-play{position:absolute;z-index:5;left:50%;top:50%;transform:translate(-50%,-50%);width:58px;height:58px;border-radius:50%;background:#171821ad;backdrop-filter:blur(15px);border:1px solid #ffffff5c;color:white;display:grid;place-items:center;opacity:0;transition:opacity .16s,background .16s;font-size:20px}.canvas-play svg{width:20px;height:20px}.canvas-wrap:hover .canvas-play,.canvas-play:focus-visible{opacity:1}.canvas-play:hover{background:#373442bd}
-.transport{height:56px;max-width:800px;margin:auto;gap:12px}.transport-start{gap:13px}.transport-play{height:32px;width:38px;border-radius:6px;background:#e6e5ee;color:#202026}.transport-play:hover{background:white}.transport-play svg{height:15px;width:15px}.time-readout{font-size:12px;gap:11px;color:#999ca7}.time-readout strong{color:#e5e5ee}.icon-button{width:30px;height:30px;color:#a4a7b1}.icon-button svg{width:16px;height:16px}.cut-label{font:9px monospace;color:#9094a1;margin-right:7px;letter-spacing:.7px}.cut-label>span{color:#dedde8;margin-left:8px}.monitor-source{display:flex;justify-content:space-between;align-items:center;gap:12px;max-width:800px;margin:auto;border-top:1px solid #2b2d34;padding-top:10px;font-size:10px;color:#9b9fac}.monitor-source>span:first-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.monitor-source>span:last-child{font:8px monospace;letter-spacing:.6px;white-space:nowrap;display:flex;align-items:center;gap:8px;color:#91949f}.monitor-source i{width:3px;height:3px;background:#747782;border-radius:50%}.preview-description{display:block}
-.brand-panel{border-left:0;margin-top:33px;padding:20px 18px;background:linear-gradient(145deg,#202125,#191a1d);border:1px solid #32343a;border-radius:10px;min-width:0;box-shadow:0 8px 30px #0001}.panel-title h2{font-size:14px;letter-spacing:-.3px}.panel-title svg{color:#c9c0ec}.panel-description{font-size:12px;line-height:1.5;color:#a7a8b2;margin:10px 0 12px}.brand-panel .field-label{font-size:11px;color:#b1b2bd;margin:12px 0 6px}.brand-panel input:not([type=color]):not([type=checkbox]),.brand-panel textarea,.brand-panel select{background:#15161a;border-color:#373941;font-size:12px;padding:9px 10px;border-radius:6px;color:#ededf4}.brand-panel textarea{min-height:48px}.brand-panel select{height:36px}.palette{gap:10px;margin-top:9px}.swatch{width:26px;height:26px;border-color:#202125}.swatch.active{outline-color:#e5e2f6}.custom-color{width:24px;height:24px;border-color:#777789}.brand-divider{background:#36373e;margin:14px 0 12px}.identity-footnote{font-size:10px;color:#c0bacc;display:flex;align-items:center;gap:4px}.identity-footnote .tiny-dot{background:#a9ae92}.concept-note{font-size:10px;line-height:1.6;color:#9696a3;margin-top:8px}.overlay-toggle{position:relative;display:flex;align-items:center;justify-content:space-between;margin-top:14px;font-size:11px;color:#c0bfcd;cursor:pointer}.overlay-toggle input{position:absolute;right:0;width:30px;height:18px;opacity:0;cursor:pointer;z-index:1}.toggle-track{width:30px;height:18px;border-radius:20px;background:#4d4d59;padding:3px;transition:background .15s}.toggle-track:before{content:"";display:block;background:#c6c4d1;width:12px;height:12px;border-radius:50%;transition:transform .15s}.overlay-toggle input:checked+.toggle-track{background:#a6a0cb}.overlay-toggle input:checked+.toggle-track:before{transform:translateX(12px);background:#fff}.overlay-toggle input:focus-visible+.toggle-track{outline:2px solid #d9cffc;outline-offset:3px}
-.timeline-panel{margin:0 30px;border:1px solid #33343c;border-radius:10px;background:#1a1b1f;overflow:hidden;box-shadow:0 8px 26px #0001}.timeline-toolbar{height:47px;padding-inline:18px}.timeline-heading h2{font-size:12px}.timeline-heading svg{color:#a9a6bd}.clip-count{font-size:10px;border-color:#42424d;background:#27272f;padding:3px 6px;color:#c5c3d1}.timeline-tools .small{font-size:11px;padding:5px 10px}.timeline-hint{font-size:10px;color:#999baa}.timeline-scroll{padding-inline:18px}.ruler{background-color:#1a1b1f;font-size:9px;color:#a3a1b2;background-image:repeating-linear-gradient(90deg,#0000 0,#0000 calc(2.5% - 1px),#474752 calc(2.5% - 1px),#474752 2.5%)}.ruler span{background:#1a1b1f}.clips-track{height:65px}.timeline-clip,.timeline-clip:nth-child(2n),.timeline-clip:nth-child(3n){border-color:#656174;background:#35313d;border-radius:4px}.timeline-clip.selected{border-color:#d1c2f3;box-shadow:0 0 0 1px #100f14}.timeline-clip img{opacity:.82}.timeline-clip>span{font-size:10px}.timeline-clip small{font-size:9px;color:#e0dce9}.lane-label{font-size:10px;color:#a7a5b7}.brand-track{background:#2d2838;border-color:#4c425e;color:#c1b7d5;font-size:9px}.brand-track-name{color:#e0d5ef}.brand-track-line{background:linear-gradient(90deg,#8c74b0,#8c74b033)}.playhead{background:#dbd0fb;box-shadow:none}.playhead>span{background:#dbd0fb}.clip-inspector{font-size:10px;padding:6px 18px;border-color:#33313d;color:#bcb7ca}.clip-inspector label{font-size:10px;color:#9f9aaa}.clip-inspector input{font-size:10px;background:#232129;border-color:#46404f;color:#e0dbea;width:54px}.text-button{font-size:11px;color:#c1b8cc}.remove-clip{color:#d7b4b2}
-.library-panel{padding:28px 30px 20px}.library-heading{margin-bottom:20px}.library-heading h2{font-size:22px;font-weight:520;letter-spacing:-.8px}.library-heading p{font-size:12px;line-height:1.6;margin-top:6px;color:#a4a2b0}.library-title-row{gap:14px}.library-count{font-size:10px;color:#c3bbdb;background:#282532;border-color:#41394d;padding:4px 7px}.search-box{height:35px;background:#19191f;border-color:#38363f;padding-inline:11px}.search-box input{font-size:11px;width:148px}.upload-button{font-size:11px}.reference-tabs{gap:8px;margin-bottom:9px;padding-bottom:11px}.reference-tab{font-size:11px;min-height:39px;border-color:#34313e;background:#1c1b22;gap:9px}.reference-tab img{width:40px;height:26px;filter:none}.reference-tab.active{background:#302a3d;border-color:#77668e;color:#ebe3f8}.reference-tab:hover{border-color:#8b789e}.source-heading{font-size:11px;margin-bottom:14px;color:#c0baca}.source-heading>span:last-child{font-size:10px;color:#9f98ad}.segment-grid{grid-template-columns:repeat(5,minmax(0,1fr));gap:20px 15px}.segment-visual{aspect-ratio:16/10;border-radius:8px;border-color:#393541;transition:border-color .15s,transform .2s;box-shadow:0 7px 15px #0002}.segment-card:hover .segment-visual{border-color:#afa0c6;transform:translateY(-2px)}.segment-add{background:#e4dff1;color:#292233;border-color:#f6f3ffad;width:29px;height:29px}.segment-add:hover{background:#fff}.segment-number,.segment-length{font-size:9px;background:#19141fce;padding:4px 5px}.segment-meta{font-size:12px;margin-top:10px;color:#e0dae9}.segment-meta small{font-size:9px;color:#b2a8c0}.segment-subtitle{font-size:10px;line-height:1.5;color:#a299ae;margin-top:4px}.studio-footer{margin-inline:30px;font-size:10px;color:#9b93a7}.studio-footer>span:last-child{font-size:9px}.footer-mark{color:#c1b5d2}.toast{background:#e6e0f1;color:#2c2339;border-color:#f5eefe}
-.canvas-wrap.portrait,.canvas-wrap.square{aspect-ratio:16/9;background:repeating-conic-gradient(#17171d 0% 25%,#131319 0% 50%) 50%/18px 18px;display:flex;align-items:center;justify-content:center}.portrait .film-stage{height:100%;width:auto;aspect-ratio:9/16}.square .film-stage{height:100%;width:auto;aspect-ratio:1}.portrait .monitor-brand{font-size:3cqw;padding:5px;gap:5px;top:3%;left:5%;max-width:90%}.portrait #film-brand-name{font-size:4cqw}.portrait .film-monogram{width:6cqw;height:6cqw;font-size:4cqw}.portrait .monitor-brand>span:last-child{font-size:1.5cqw}.portrait .monitor-caption{font-size:3cqw;left:5%;bottom:4%;padding:6px;max-width:90%}.square .monitor-caption{font-size:2cqw}.square #film-brand-name{font-size:2.4cqw}
-.present-mode .upper-workspace{padding:20px;height:100vh;align-items:center}.present-mode .preview-area{max-width:calc((100vh - 130px)*16/9);height:auto}.present-mode .canvas-wrap{width:100%;max-width:none;height:auto;aspect-ratio:16/9}.present-mode .film-stage{height:100%;width:100%}.present-mode .transport,.present-mode .monitor-source{max-width:none}.canvas-wrap:fullscreen{max-width:none;aspect-ratio:auto;background:#07080a}.canvas-wrap:fullscreen .film-stage{width:100%;height:100%;aspect-ratio:auto}.canvas-wrap:fullscreen video{object-fit:contain}
-@media(min-width:1650px){.upper-workspace{grid-template-columns:minmax(0,1fr) 260px;gap:40px}.preview-area{max-width:1040px}.canvas-wrap,.transport,.monitor-source{max-width:920px}.brand-panel{padding:24px}.segment-grid{grid-template-columns:repeat(6,minmax(0,1fr))}}
-@media(max-width:1150px){.upper-workspace{padding-inline:22px;grid-template-columns:minmax(0,1fr) 218px;gap:22px}.studio-heading{padding-inline:22px}.studio-title h1{font-size:17px}.subtle-label{display:none}.brand-panel{padding:17px 14px}.panel-description{font-size:11px;margin-bottom:14px}.brand-panel .field-label{margin-top:13px}.brand-panel textarea{min-height:54px}.brand-panel input:not([type=color]):not([type=checkbox]),.brand-panel textarea,.brand-panel select{font-size:11px}.concept-note{font-size:9px}.monitor-source>span:last-child{display:none}.timeline-panel{margin-inline:22px}.library-panel{padding-inline:22px}.library-heading h2{font-size:20px}.segment-grid{grid-template-columns:repeat(4,minmax(0,1fr))}.library-heading p{font-size:11px}.time-readout{font-size:11px;gap:8px}.cut-label{display:none}.brand-panel{margin-top:33px}.studio-footer{margin-inline:22px}}
-@media(max-width:850px){.upper-workspace{grid-template-columns:1fr;padding-inline:20px;gap:16px}.studio-heading{height:65px;padding-inline:20px}.brand-panel{margin:0;display:grid;grid-template-columns:90px minmax(0,1fr) 90px minmax(0,1fr);gap:10px 12px;padding:16px}.brand-panel .panel-title{grid-column:1/-1;margin-bottom:2px}.brand-panel .panel-description,.brand-panel .brand-divider,.identity-footnote,.concept-note{display:none}.brand-panel>.field-label{margin:0;font-size:11px}.brand-panel>input,.brand-panel>textarea,.brand-panel select,.brand-panel .palette{grid-column:auto;margin:0}.brand-panel textarea{min-height:38px;height:38px;resize:vertical}.brand-panel .palette{gap:7px}.overlay-toggle{grid-column:3/-1;margin:0}.brand-panel .swatch{width:23px;height:23px}.brand-panel .custom-color{width:22px;height:22px}.timeline-panel{margin-inline:20px}.library-panel{padding-inline:20px}.segment-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.library-heading{gap:16px}.library-actions{justify-content:space-between;width:100%}.library-heading p{max-width:none}.search-box{flex:1;max-width:none}.search-box input{width:100%}.topbar .save-state{display:none}.monitor-caption{font-size:1.55cqw}.canvas-wrap{max-width:none}.preview-area{margin:0}.transport,.monitor-source{max-width:none}}
-@media(max-width:550px){.topbar{height:58px;padding-inline:16px}.rail{display:none}.topbar .button{font-size:11px}.studio-heading{height:65px;padding:0 16px;gap:8px}.studio-title h1{font-size:16px;letter-spacing:-.5px}.studio-title .live-dot{display:none}.view-toggle button{font-size:10px;padding:6px 9px}.view-toggle{padding:3px}.upper-workspace{padding:0 16px 18px;gap:17px}.canvas-top{height:29px;font-size:9px;letter-spacing:.8px}.canvas-top>span:last-child{font-size:8px}.canvas-sep{margin-inline:6px}.monitor-option{margin-left:5px}.canvas-wrap{height:auto;aspect-ratio:16/9;border-radius:7px;box-shadow:0 10px 30px #0003}.monitor-brand{padding:4px 6px 4px 4px;gap:5px;border-radius:5px;top:6%}.monitor-brand .film-monogram{width:17px;height:17px;min-width:17px;min-height:17px;font-size:11px;border-radius:3px}#film-brand-name{font-size:11px}.monitor-brand>span:last-child{font-size:6px}.brand-overlay-divider{margin-inline:1px;height:10px}.monitor-caption{font-size:9px;padding:5px 7px;gap:6px;bottom:6%;max-width:88%;border-radius:4px}.caption-accent{height:13px;width:2px}.canvas-play{width:44px;height:44px}.transport{height:52px}.transport-start{gap:9px}.transport-play{width:33px;height:30px}.transport-end{gap:4px}.time-readout{font-size:10px;gap:7px}.monitor-source{padding-top:9px;font-size:10px}.brand-panel{grid-template-columns:76px minmax(0,1fr);padding:14px;gap:10px 11px;border-radius:8px}.brand-panel input:not([type=color]):not([type=checkbox]),.brand-panel textarea,.brand-panel select{font-size:12px}.brand-panel>.field-label{font-size:11px}.brand-panel>.overlay-toggle{grid-column:1/-1;margin-top:3px}.brand-panel .palette{gap:10px}.brand-panel .swatch{width:25px;height:25px}.panel-title h2{font-size:13px}.timeline-panel{margin-inline:16px;border-radius:8px}.timeline-toolbar{height:46px;padding-inline:12px}.timeline-tools .small{font-size:10px}.timeline-heading{gap:7px}.timeline-heading svg{display:none}.timeline-scroll{padding-inline:12px}.timeline-tools .tool-divider{display:none}.clip-inspector{padding-inline:12px;font-size:10px;gap:8px}.clip-inspector>div{gap:8px}.library-panel{padding:25px 16px 10px}.library-title-row{gap:9px;flex-wrap:wrap}.library-heading h2{font-size:21px}.library-heading p{font-size:11px;margin-top:8px}.library-count{font-size:9px}.library-heading{gap:15px}.reference-tabs{padding-top:2px;margin-bottom:7px}.reference-tab{font-size:10px}.segment-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:19px 12px}.segment-meta{font-size:11px}.segment-meta small{font-size:8px}.segment-add{width:30px;height:30px}.segment-subtitle{font-size:9px}.source-heading{font-size:11px;gap:10px}.source-heading>span:last-child{font-size:8px;max-width:126px;line-height:1.5}.studio-footer{margin-inline:16px;font-size:9px}.portrait .monitor-brand>span:last-child{display:none}.portrait .brand-overlay-divider{display:none}.portrait #film-brand-name{font-size:9px}.portrait .film-monogram{min-width:13px;min-height:13px;width:13px;height:13px;font-size:9px}.portrait .monitor-caption{font-size:7px;padding:4px}.canvas-wrap:fullscreen{height:100vh;width:100vw}}
-.present-mode .portrait .film-stage,.canvas-wrap.portrait:fullscreen .film-stage{width:auto;height:100%;aspect-ratio:9/16}
-.present-mode .square .film-stage,.canvas-wrap.square:fullscreen .film-stage{width:auto;height:100%;aspect-ratio:1}
-@media(prefers-reduced-motion:reduce){.canvas-play,.segment-visual,.toggle-track,.toggle-track:before{transition:none}}
+/* Film preview stage: the video, the brand layer, guides, presentation view. */
+
+.canvas-wrap {
+ display: flex; align-items: center; justify-content: center;
+ height: clamp(280px, 26vw, 420px);
+ background: #000;
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+ overflow: hidden;
+}
+
+.film-stage {
+ position: relative;
+ height: 100%;
+ aspect-ratio: 16 / 9;
+ max-width: 100%;
+ background: #000;
+ overflow: hidden;
+}
+.canvas-wrap.portrait .film-stage { aspect-ratio: 9 / 16; }
+.canvas-wrap.square .film-stage { aspect-ratio: 1 / 1; }
+
+#preview-video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; background: #000; }
+
+.video-loading {
+ position: absolute; inset: 0; z-index: 2;
+ display: grid; place-items: center;
+ font-size: 11px; color: var(--faint);
+ background: #000;
+}
+.video-loading[hidden] { display: none; }
+
+/* Brand layer */
+
+.monitor-brand, .monitor-caption { position: absolute; z-index: 3; display: flex; align-items: center; gap: 8px; }
+
+.monitor-brand {
+ top: 14px; left: 14px;
+ font-size: 10px; letter-spacing: .1em; text-transform: uppercase; color: rgba(255, 255, 255, .78);
+ text-shadow: 0 1px 6px rgba(0, 0, 0, .7);
+}
+.film-monogram {
+ display: grid; place-items: center; width: 18px; height: 18px; border-radius: 3px;
+ background: var(--accent); color: #101010; font-size: 11px; letter-spacing: 0; font-weight: 600;
+}
+
+.monitor-caption { left: 14px; bottom: 14px; font-size: 13px; color: #fff; text-shadow: 0 1px 8px rgba(0, 0, 0, .75); }
+.caption-accent { width: 2px; height: 15px; background: var(--accent); flex: none; }
+
+.film-stage.no-brand .monitor-brand,
+.film-stage.no-brand .monitor-caption,
+.canvas-wrap.reference-mode .monitor-brand,
+.canvas-wrap.reference-mode .monitor-caption { display: none; }
+
+/* Safe-area guides */
+
+.monitor-guides { position: absolute; inset: 5%; z-index: 4; border: 1px solid rgba(255, 255, 255, .22); pointer-events: none; }
+.monitor-guides[hidden] { display: none; }
+.monitor-guides span { position: absolute; inset: 5%; border: 1px solid rgba(255, 255, 255, .12); }
+
+/* Centre play button */
+
+.canvas-play {
+ position: absolute; inset: 0; z-index: 5;
+ display: grid; place-items: center;
+ color: #fff; background: rgba(0, 0, 0, .18);
+ transition: opacity .15s;
+}
+.canvas-play svg { width: 34px; height: 34px; filter: drop-shadow(0 2px 8px rgba(0, 0, 0, .6)); }
+.canvas-wrap.is-playing .canvas-play { opacity: 0; }
+.canvas-wrap.is-playing .canvas-play:hover, .canvas-wrap.is-playing .canvas-play:focus-visible { opacity: 1; }
+
+/* Presentation view */
+
+.present-mode { overflow: hidden; }
+.present-mode .topbar,
+.present-mode .rail,
+.present-mode .studio-heading,
+.present-mode .brand-panel,
+.present-mode .timeline-panel,
+.present-mode .library-panel,
+.present-mode .canvas-top,
+.present-mode .monitor-source,
+.present-mode .transport { display: none; }
+.present-mode .upper-workspace { grid-template-columns: 1fr; padding: 0; gap: 0; }
+.present-mode .canvas-wrap { height: 100vh; border: 0; border-radius: 0; background: #000; }
diff --git a/public/editor.css b/public/editor.css
index 0b538e0..0785ebe 100644
--- a/public/editor.css
+++ b/public/editor.css
@@ -1,16 +1,386 @@
-:root{color-scheme:dark;--bg:#101112;--panel:#151618;--surface:#1c1e20;--line:#2a2c2e;--text:#eeefec;--muted:#989b9e;--lime:#dbed91;--accent:#daef79;--paper:#eeefdf;font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",Arial,sans-serif;font-synthesis:none}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font-size:12px;-webkit-font-smoothing:antialiased}button,input,select,textarea{font:inherit}button,a,input,textarea,select{-webkit-tap-highlight-color:transparent}button{cursor:pointer}button:disabled{opacity:.35;cursor:default}button,a{color:inherit}a{text-decoration:none}button{border:0}svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0}svg use[href="#i-play"]{fill:currentColor;stroke:none}.svg-library{position:absolute;width:0;height:0;overflow:hidden}button:focus-visible,a:focus-visible,input:focus-visible,textarea:focus-visible,select:focus-visible{outline:2px solid var(--lime);outline-offset:4px}.skip-link{position:fixed;top:-70px;z-index:100;background:var(--lime);color:#111;padding:12px}.skip-link:focus{top:5px}.topbar{height:65px;padding:0 24px;display:flex;align-items:center;gap:19px;border-bottom:1px solid var(--line);background:#131416}.logo{display:flex;gap:9px;align-items:center;font-size:24px;font-weight:650;letter-spacing:-1.2px}.logo-mark{display:grid;place-items:center;width:28px;height:28px;background:#ededdf;border-radius:7px;color:#17181b;font-size:18px;font-weight:850;letter-spacing:-2px}.logo-dot{color:var(--lime);margin-left:-8px}.top-divider{height:23px;width:1px;background:#37393a}.project-link,.crumb{color:#95989c;font-size:11px}.project-name{font-size:11px;font-weight:550}.project-caret{padding-left:14px;color:#a5a5a5}.save-state{font-size:10px;color:#969b95;display:flex;align-items:center;gap:6px}.save-state>span{width:5px;height:5px;background:#8baa82;border-radius:50%}.top-actions{margin-left:auto;display:flex;align-items:center;gap:12px}.demo-label{font:9px monospace;letter-spacing:1.1px;color:#888c90;margin-right:6px}.button{display:inline-flex;justify-content:center;align-items:center;gap:7px;padding:9px 13px;min-height:34px;border:1px solid var(--line);border-radius:7px;font-size:11px;font-weight:550;background:#222426;white-space:nowrap;transition:background .16s,transform .16s}.button:hover{background:#2e3133}.button.primary{color:#151810;background:var(--lime);border-color:var(--lime)}.button.primary:hover{background:#e9f6b2}.button.subtle{background:transparent}.button.subtle:hover{background:#252729}.button.small{min-height:27px;padding:4px 10px;font-size:10px}.button svg{width:14px;height:14px}.avatar{width:29px;height:29px;display:grid;place-items:center;font-size:10px;background:#363a33;border:1px solid #555c4b;border-radius:50%;color:#d9e5c2}.workspace{display:flex}.rail{width:73px;flex-shrink:0;border-right:1px solid var(--line);display:flex;flex-direction:column;align-items:center;padding-top:18px;gap:12px;position:sticky;top:0;height:calc(100vh - 65px)}.rail-item{width:55px;height:58px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:7px;border-radius:8px;background:none;color:#8d9195;font-size:9px}.rail-item svg{width:19px;height:19px}.rail-item.active{background:#252922;color:#e1efb1}.rail-item:hover{background:#252729;color:#fff}.rail-bottom{margin-top:auto;margin-bottom:20px;font:8px monospace;color:#65686b;letter-spacing:1.4px}main{min-width:0;width:100%;max-width:1850px;margin:auto}.studio-heading{height:56px;padding:0 26px;display:flex;align-items:center;justify-content:space-between;gap:16px}.studio-title{display:flex;align-items:center;gap:9px;min-width:0}.studio-title h1{font-size:12px;font-weight:550;margin:0}.live-dot{width:6px;height:6px;border-radius:50%;background:var(--lime)}.subtle-label{font-size:10px;color:#74797e;margin-left:10px}.view-toggle{display:flex;align-items:center;background:#191b1d;border:1px solid var(--line);border-radius:6px;padding:3px}.view-toggle button{background:none;color:#9ca1a4;font-size:10px;padding:5px 13px;border-radius:4px}.view-toggle .active{background:#343739;color:#f3f4ee;box-shadow:0 1px 3px #0004}.upper-workspace{display:grid;grid-template-columns:minmax(0,1fr) 240px;padding:0 26px 0;gap:25px}.preview-area{min-width:0}.canvas-top{display:flex;align-items:center;justify-content:space-between;color:#858a8c;font:9px monospace;letter-spacing:1px;padding:3px 1px 13px}.canvas-sep{margin:0 9px;color:#55595a}.tiny-dot{display:inline-block;width:5px;height:5px;border-radius:50%;background:#b9c991;margin-right:4px}.canvas-wrap{display:flex;align-items:center;justify-content:center;background:#0b0c0d;border:1px solid #2e3131;border-radius:9px;position:relative;overflow:hidden;height:clamp(330px,30vw,485px);box-shadow:0 16px 45px #0002}.film-stage{container-type:inline-size;aspect-ratio:16/9;max-height:100%;width:100%;overflow:hidden;position:relative;background:var(--paper);color:#23261d;isolation:isolate}.stage-grain{position:absolute;inset:0;opacity:.045;z-index:5;pointer-events:none;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 120 120' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.8' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' opacity='.9' filter='url(%23noise)'/%3E%3C/svg%3E")}.stage-orbit{position:absolute;border:1px solid #343c2520;border-radius:50%;width:70%;aspect-ratio:1;right:-16%;top:-27%;z-index:-1}.orbit-two{width:88%;right:-25%;top:-44%}.film-brand{position:absolute;top:7%;left:6%;display:flex;gap:8px;align-items:center;font-size:2.1cqw;font-weight:700;letter-spacing:-.08em}.film-monogram{font-size:1.6cqw;display:grid;place-items:center;width:2.6cqw;height:2.6cqw;border-radius:.55cqw;background:#20281e;color:var(--paper);letter-spacing:-.15em;padding-right:.2em}.film-brand-plus{font-size:1cqw;align-self:start;letter-spacing:0}.film-copy{position:absolute;left:6%;top:27%;width:47%;z-index:2}.film-kicker{font-size:.82cqw;letter-spacing:.16em;font-weight:600;display:block;margin-bottom:2cqw;color:#596147}.film-copy h2{font-size:6.25cqw;line-height:.95;letter-spacing:-.075em;font-weight:650;margin:0 0 2cqw;overflow-wrap:anywhere;max-width:100%}.film-copy em{font-weight:500;font-family:Georgia,serif;letter-spacing:-.08em}.film-copy p{font-size:1.05cqw;color:#596147;margin:0 0 2.4cqw}.film-cta{display:inline-flex;gap:2.5cqw;font-size:.95cqw;font-weight:600;align-items:center;background:#262c21;color:var(--paper);padding:1cqw 1.3cqw;border-radius:4cqw}.film-cta>span{color:var(--accent)}.motion-window{position:absolute;width:49%;height:56%;right:-1.5%;top:26%;background:#111416;border-radius:1.1cqw;border:.6cqw solid #222724;box-shadow:-1.4cqw 2cqw 5cqw #3c482a35;transform:perspective(1000px) rotateY(-9deg) rotateZ(-4deg);overflow:hidden;transition:transform .7s cubic-bezier(.2,.65,.3,1),background .3s}.window-chrome{height:13%;display:flex;align-items:center;justify-content:space-between;padding:0 1cqw;background:#222724;color:#9fa99c;font-size:.68cqw}.window-dots{font-size:.55cqw;letter-spacing:.3cqw;color:#7c8771}.motion-window video{width:100%;height:87%;display:block;object-fit:cover;background:#151817}.video-loading{position:absolute;inset:13% 0 0;display:grid;place-items:center;color:#aaa;font-size:11px;background:#1b1d1a}.video-loading[hidden]{display:none}.film-footer{position:absolute;bottom:7%;left:6%;right:6%;display:flex;justify-content:space-between;font-size:.64cqw;letter-spacing:.14em;color:#6c745d}.film-timecode{position:absolute;transform:rotate(-90deg);transform-origin:0 0;right:-9%;top:72%;font-size:.6cqw;letter-spacing:.15em;color:#6c745d}.film-stage[data-scene="1"] .motion-window{transform:perspective(1000px) rotateY(5deg) rotateZ(3deg)}.film-stage[data-scene="2"] .motion-window{transform:perspective(1000px) rotateY(-4deg) rotateZ(-1deg);box-shadow:0 2cqw 5cqw #3c482a40}.film-stage[data-scene="3"] .motion-window{transform:perspective(1000px) rotateY(0) rotateZ(1deg)}.canvas-badge{position:absolute;right:12px;bottom:12px;display:flex;gap:5px;align-items:center;font-size:8px;color:#d8dfcf;background:#171b17db;border:1px solid #faffeb16;padding:5px 7px;border-radius:5px;z-index:6}.canvas-badge span{width:4px;height:4px;border-radius:50%;background:#bddf7a}.reference-mode .film-stage{background:#090a0b}.reference-mode .film-brand,.reference-mode .film-copy,.reference-mode .film-footer,.reference-mode .film-timecode,.reference-mode .stage-orbit,.reference-mode .stage-grain{display:none}.reference-mode .motion-window{inset:0;width:100%;height:100%;transform:none;border:0;border-radius:0;box-shadow:none}.reference-mode .window-chrome{display:none}.reference-mode .motion-window video{height:100%;object-fit:contain}.reference-mode .canvas-badge{display:none}.portrait .film-stage{aspect-ratio:9/16;width:auto;height:100%}.square .film-stage{aspect-ratio:1;width:auto;height:100%}.portrait .film-copy{top:25%;width:88%}.portrait .film-copy h2{font-size:10cqw}.portrait .motion-window{top:58%;width:80%;height:26%;right:10%}.portrait .film-brand{font-size:5cqw}.portrait .film-monogram{font-size:4cqw;width:6cqw;height:6cqw}.portrait .film-kicker{font-size:2cqw}.portrait .film-copy p,.portrait .film-cta{font-size:2.5cqw}.portrait .film-footer{font-size:1.2cqw}.square .film-copy{top:24%;width:55%}.square .film-copy h2{font-size:7cqw}.square .motion-window{height:45%;top:39%}.transport{height:48px;display:flex;align-items:center;justify-content:space-between;gap:8px}.transport-start,.transport-end{display:flex;align-items:center;gap:11px}.icon-button{width:29px;height:29px;display:inline-flex;justify-content:center;align-items:center;background:none;color:#9b9fa2;font-size:19px;border-radius:5px;position:relative}.icon-button:hover{background:#2b2e2f;color:#fff}.icon-button svg{width:15px;height:15px}.transport-play{width:30px;height:28px;display:grid;place-items:center;background:#2d3031;border-radius:5px;color:#eeefe9}.transport-play svg{width:14px;height:14px}.time-readout{display:flex;gap:8px;font:10px monospace;color:#818689}.time-readout strong{font-weight:400;color:#dcdfd8}.preview-description{font-size:9px;color:#7f8587}.mute-slash{position:absolute;width:19px;height:1px;background:#a0a4a0;transform:rotate(-45deg)}.brand-panel{padding:1px 0 0 23px;border-left:1px solid var(--line);min-width:0}.panel-title{display:flex;justify-content:space-between;align-items:center}.panel-title h2{font-size:12px;font-weight:600;margin:0}.panel-title svg{width:15px;height:15px;color:#aebc8e}.panel-description{font-size:11px;line-height:1.55;color:#92979a;margin:13px 0 18px}.field-label{display:block;font-size:10px;font-weight:500;color:#aaafb1;margin:14px 0 7px}.brand-panel input:not([type=color]),.brand-panel textarea,.brand-panel select{width:100%;border:1px solid #333638;background:#1d1f21;color:#e4e5e0;border-radius:6px;padding:9px 10px;font-size:11px;min-width:0}.brand-panel textarea{resize:vertical;line-height:1.5;min-height:52px}.brand-panel select{height:34px}.palette{display:flex;gap:9px;align-items:center;margin-top:10px}.swatch{background:var(--swatch);width:24px;height:24px;border-radius:50%;border:3px solid #151618;outline:1px solid transparent}.swatch.active{outline:1px solid #cbd2be}.custom-color{position:relative;width:23px;height:23px;border:1px dashed #6a7169;border-radius:50%;color:#abb2a5;display:grid;place-items:center;font-size:14px;overflow:hidden;cursor:pointer}.custom-color input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}.brand-divider{height:1px;background:var(--line);margin:18px 0 12px}.direction-label{display:flex;align-items:center;justify-content:space-between;color:#868f7c}.direction-label .field-label{margin:0}.direction-copy{font-size:10px;color:#8d9395;line-height:1.65;margin:9px 0 13px}.concept-note{font-size:8px;color:#969d8f;line-height:1.6}.concept-note .tiny-dot{width:4px;height:4px}.timeline-panel{border-top:1px solid var(--line);border-bottom:1px solid var(--line);background:#151719}.timeline-toolbar{height:48px;display:flex;justify-content:space-between;align-items:center;padding:0 25px;gap:12px}.timeline-heading,.timeline-tools{display:flex;align-items:center;gap:10px}.timeline-heading svg{width:14px;height:14px;color:#a0a697}.timeline-heading h2{font-size:11px;font-weight:550;margin:0}.clip-count{font:9px monospace;color:#8f9596;border:1px solid #363b3c;border-radius:4px;padding:2px 5px}.timeline-hint{font-size:9px;color:#727a7e;margin-right:8px}.timeline-tools{gap:6px}.tool-divider{height:16px;width:1px;background:var(--line);margin:0 8px}.timeline-scroll{overflow-x:auto;padding:0 25px;scrollbar-width:thin;scrollbar-color:#464c44 transparent}.timeline-body{position:relative;min-width:650px;padding-top:23px}.ruler{position:absolute;top:0;left:77px;right:2px;display:flex;justify-content:space-between;color:#697378;font:8px monospace;height:21px;border-bottom:1px solid #33393b;background:repeating-linear-gradient(90deg,#0000 0,#0000 calc(2.5% - 1px),#384042 calc(2.5% - 1px),#384042 2.5%);background-size:100% 4px;background-repeat:no-repeat;background-position:bottom}.ruler span{padding:0 0 9px;background:#151719}.timeline-lane{display:flex;gap:14px;align-items:center}.lane-label{display:flex;align-items:center;gap:7px;width:63px;flex-shrink:0;font-size:9px;color:#848d8f;letter-spacing:.1px}.lane-label svg{width:14px;height:14px}.clips-track{display:flex;gap:4px;height:63px;flex:1;min-width:0;position:relative}.timeline-clip{min-width:42px;flex-shrink:1;position:relative;overflow:hidden;border:1px solid #798e64;border-radius:5px;padding:0;display:flex;align-items:end;background:#253022;cursor:grab;color:#ebf0e5;text-align:left}.timeline-clip:nth-child(2n){border-color:#636e86}.timeline-clip:nth-child(3n){border-color:#917866}.timeline-clip img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:.75;pointer-events:none}.timeline-clip::after{content:"";position:absolute;inset:0;background:linear-gradient(0deg,#121710e8,#12171005 90%)}.timeline-clip.selected{border:2px solid var(--lime);box-shadow:0 0 0 1px #121712}.timeline-clip.dragging{opacity:.4}.timeline-clip>span{z-index:1;font-size:9px;padding:6px 8px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;width:100%}.timeline-clip small{display:block;font:8px monospace;color:#c3cdbd;margin-bottom:4px}.empty-track{flex:1;border:1px dashed #59614f;border-radius:5px;color:#a3ac95;display:grid;place-items:center;font-size:11px}.brand-lane{display:flex;gap:14px;margin:7px 0 13px;height:23px}.brand-track{background:#252c20;border:1px solid #414c34;border-radius:4px;display:flex;align-items:center;gap:18px;flex:1;padding:0 9px;color:#a7b38e;font-size:8px}.brand-track-name{font-weight:600;color:#dce8c4}.brand-track-line{flex:1;height:1px;background:linear-gradient(90deg,#667547,#66754744)}.playhead{position:absolute;top:16px;bottom:1px;left:77px;width:1px;background:#ddedaa;z-index:3;pointer-events:none;box-shadow:0 0 3px #bddd6370}.playhead>span{position:absolute;width:8px;height:11px;top:-11px;left:-3.5px;background:#ddedaa;clip-path:polygon(0 0,100% 0,100% 65%,50% 100%,0 65%)}.timeline-scrubber{position:absolute;top:0;left:77px;width:calc(100% - 77px);height:23px;opacity:0;margin:0;cursor:ew-resize}.timeline-scrubber:focus-visible{opacity:.6}.clip-inspector{min-height:32px;padding:4px 26px;border-top:1px solid #252b2d;display:flex;justify-content:space-between;align-items:center;gap:10px;font-size:9px;color:#9ca4a2}.clip-inspector>div{display:flex;align-items:center;gap:13px}.clip-inspector label{display:flex;align-items:center;gap:6px;color:#707b80;font:9px monospace}.clip-inspector input{width:52px;background:#1e2325;border:1px solid #363e40;border-radius:3px;padding:3px 4px;color:#d5ddd6;font:9px monospace}.text-button{background:none;color:#9aa59a;padding:4px;font-size:10px;border-radius:3px;min-width:24px;min-height:24px}.text-button:hover{background:#343b31;color:#e8eddf}.remove-clip{color:#be9c8a}.library-panel{padding:25px 26px 20px}.library-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:20px}.library-title-row{display:flex;gap:12px;align-items:center}.library-heading h2{font-size:18px;letter-spacing:-.6px;font-weight:500;margin:0}.library-heading p{font-size:10px;color:#878e91;margin:8px 0 0}.library-count{color:#9da68c;background:#252b20;border:1px solid #373f2e;border-radius:4px;padding:3px 6px;font:8px monospace}.library-actions{display:flex;align-items:center;gap:10px}.search-box{height:32px;border:1px solid var(--line);background:#181a1c;display:flex;gap:7px;align-items:center;padding:0 10px;border-radius:6px;color:#7c8589}.search-box svg{width:13px;height:13px}.search-box input{background:none;border:0;outline:0;color:#ddd;font-size:10px;width:130px}.search-box:focus-within{border-color:#748258}.search-box input::placeholder{color:#788084}.upload-button{cursor:pointer;font-size:10px}.reference-tabs{display:flex;gap:8px;overflow:auto;scrollbar-width:thin;scrollbar-color:#414938 transparent;padding:2px 2px 10px;margin-bottom:12px}.reference-tab{background:#1b1e20;border:1px solid #303638;color:#a4adae;display:flex;align-items:center;gap:8px;padding:5px 10px 5px 5px;border-radius:6px;font-size:9px;white-space:nowrap;min-height:36px;max-width:230px;flex-shrink:0;text-align:left}.reference-tab img{width:36px;height:23px;object-fit:cover;border-radius:3px;filter:saturate(.7)}.reference-tab span{overflow:hidden;text-overflow:ellipsis}.reference-tab.active{color:#e1eccc;background:#292f23;border-color:#718252}.reference-tab:hover{border-color:#758263}.source-heading{display:flex;justify-content:space-between;align-items:center;gap:15px;font-size:10px;color:#adb4ae;margin:0 0 12px}.source-heading>span:last-child{font:9px monospace;color:#778184}.segment-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:13px}.segment-card{min-width:0;position:relative}.segment-visual{position:relative;aspect-ratio:16/10;border-radius:7px;overflow:hidden;background:#24292a;border:1px solid #353d3e}.segment-visual>img,.segment-visual>video{width:100%;height:100%;object-fit:cover;display:block}.segment-visual>video{position:absolute;inset:0;z-index:1;pointer-events:none}.segment-preview{position:absolute;inset:0;z-index:2;background:none;width:100%;height:100%;border:0;color:#fff;display:grid;place-items:center}.segment-preview svg{width:27px;height:27px;background:#151b18b5;border:1px solid #fff4;border-radius:50%;padding:6px;opacity:0;transition:opacity .2s}.segment-preview:hover svg,.segment-preview:focus-visible svg{opacity:1}.segment-number{position:absolute;z-index:3;top:7px;left:7px;font:8px monospace;color:#eee;background:#141918b8;border:1px solid #fff2;border-radius:3px;padding:3px 5px;pointer-events:none}.segment-length{position:absolute;z-index:3;bottom:7px;left:7px;font:8px monospace;color:#eee;background:#121915bb;border-radius:3px;padding:3px 5px;pointer-events:none}.segment-add{position:absolute;z-index:4;bottom:6px;right:6px;width:27px;height:27px;background:#e0eacb;color:#28301f;border:1px solid #f3f6d5aa;border-radius:5px;display:grid;place-items:center}.segment-add:hover{background:#efffcf}.segment-add svg{width:14px;height:14px}.segment-meta{display:flex;justify-content:space-between;align-items:center;margin-top:8px;gap:6px;font-size:10px;color:#d2d7cf}.segment-meta>span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.segment-meta small{font:8px monospace;white-space:nowrap;color:#8c9695}.segment-subtitle{font-size:8px;color:#768287;margin-top:5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.library-loading,.library-empty{grid-column:1/-1;padding:35px;text-align:center;background:#191d1d;border:1px dashed #414b3d;border-radius:8px;color:#a1ab96}.studio-footer{margin:10px 26px 0;border-top:1px solid #282f2f;min-height:54px;display:flex;align-items:center;justify-content:space-between;gap:20px;color:#697574;font-size:9px}.studio-footer>span{display:flex;align-items:center;gap:9px}.studio-footer>span:last-child{font:8px monospace;letter-spacing:.8px}.footer-mark{font-weight:800;color:#9ea99a;font-size:14px}.footer-dot{color:#869575}.toast{position:fixed;bottom:24px;left:50%;transform:translate(-50%,15px);background:#e8efd7;color:#25331e;box-shadow:0 10px 40px #0005;border:1px solid #f4f8e9;border-radius:8px;padding:11px 18px;font-size:12px;z-index:60;opacity:0;pointer-events:none;transition:opacity .18s,transform .18s;max-width:calc(100% - 32px);text-align:center}.toast.show{opacity:1;transform:translate(-50%,0)}dialog{width:min(840px,calc(100% - 30px));padding:22px;border:1px solid #414b41;border-radius:12px;background:#191d1b;color:#e1e7db;box-shadow:0 25px 100px #0009}dialog::backdrop{background:#070b0bc9;backdrop-filter:blur(7px)}.dialog-top,.dialog-bottom{display:flex;align-items:center;justify-content:space-between;gap:15px}.dialog-top{margin-bottom:17px}.dialog-top h2{font-size:17px;font-weight:500;margin:7px 0 0}.eyebrow{font:8px monospace;letter-spacing:1.6px;color:#a0b087}dialog video{width:100%;max-height:60vh;display:block;border-radius:6px;background:#080b0a}.dialog-bottom{margin-top:16px;color:#a9b2a2;font:11px monospace}.present-mode .topbar,.present-mode .rail,.present-mode .studio-heading,.present-mode .brand-panel,.present-mode .timeline-panel,.present-mode .library-panel,.present-mode .studio-footer,.present-mode .canvas-top{display:none}.present-mode .upper-workspace{display:block;padding:20px}.present-mode .canvas-wrap{height:calc(100vh - 95px)}.present-mode .preview-description::after{content:" · Esc to exit"}.canvas-wrap:fullscreen{height:100vh;width:100vw;border:0;border-radius:0}.canvas-wrap:fullscreen .film-stage{height:auto;width:100%;max-height:100vh}
-.canvas-wrap{height:clamp(300px,23vw,390px)}
-.film-stage{height:100%;width:auto;max-width:100%;max-height:100%;flex-shrink:1}
-.brand-panel .field-label{margin-top:10px;margin-bottom:6px}
-.panel-description{margin:10px 0 12px}
-.brand-divider{margin:13px 0}
-.direction-label,.direction-copy{display:none}
-.library-panel{padding-top:20px}
-.library-heading{margin-bottom:14px}
-.reference-tabs{margin-bottom:7px}
-.subtle-label,.timeline-hint,.preview-description,.ruler,.studio-footer,.rail-bottom{color:#939d9e}
-@media(min-width:1650px){.upper-workspace{grid-template-columns:minmax(0,1fr) 275px}.brand-panel{padding-left:27px}.brand-panel .field-label{margin-top:15px}.brand-panel input:not([type=color]),.brand-panel textarea{font-size:12px;padding:11px}.segment-grid{grid-template-columns:repeat(7,minmax(0,1fr))}}
-@media(max-width:1150px){.topbar{gap:12px;padding:0 18px}.save-state,.demo-label,.subtle-label{display:none}.upper-workspace{grid-template-columns:minmax(0,1fr) 205px;gap:18px;padding:0 20px}.brand-panel{padding-left:18px}.canvas-wrap{height:330px}.panel-description{margin-bottom:12px}.brand-panel .field-label{margin-top:11px}.brand-divider{margin:14px 0 9px}.direction-copy{margin:7px 0}.preview-description{display:none}.segment-grid{grid-template-columns:repeat(4,minmax(0,1fr))}.rail{width:62px}.rail-item{width:49px}.studio-heading{padding:0 20px}.library-panel{padding:22px 20px}.library-heading{align-items:start}.library-heading p{max-width:370px;line-height:1.5}.library-actions{flex-wrap:wrap;justify-content:end}.timeline-hint{display:none}.studio-footer{margin:10px 20px 0}}
-@media(max-width:800px){.upper-workspace{grid-template-columns:1fr}.brand-panel{border-left:0;border-top:1px solid var(--line);padding:15px 0 18px;display:grid;grid-template-columns:110px minmax(0,1fr) 110px;gap:8px 14px;align-items:center}.brand-panel .panel-title{grid-column:1/-1}.panel-description,.brand-divider,.direction-label,.direction-copy,.concept-note{display:none}.brand-panel>.field-label{margin:0}.brand-panel>input,.brand-panel>textarea{grid-column:2/-1}.brand-panel .palette{margin:0;grid-column:2/-1}.brand-panel select{grid-column:2/-1}.canvas-wrap{height:clamp(235px,50vw,400px)}.library-heading{flex-direction:column;gap:14px}.library-actions{width:100%;justify-content:space-between}.search-box{flex:1;max-width:300px}.search-box input{width:100%}.segment-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.studio-footer>span:last-child{display:none}.brand-panel textarea{min-height:45px}.project-link,.crumb{display:none}}
-@media(max-width:550px){.topbar{height:57px;padding:0 14px;gap:10px}.logo{font-size:22px}.logo-mark{width:25px;height:25px;font-size:16px}.top-divider,.project-name,.top-actions .subtle,.avatar{display:none}.top-actions{gap:5px}.button{font-size:10px;padding:8px 10px}.rail{display:none}.studio-heading{height:57px;padding:0 14px;gap:8px}.studio-title h1{font-size:11px}.view-toggle button{padding:5px 9px;font-size:9px}.upper-workspace{padding:0 14px;gap:4px}.canvas-top{font-size:8px;letter-spacing:.5px}.canvas-wrap{height:230px}.film-stage{min-height:0}.canvas-badge{font-size:7px;bottom:7px;right:7px}.brand-panel{grid-template-columns:82px 1fr;gap:9px 12px}.brand-panel .panel-title{margin:4px 0}.brand-panel input:not([type=color]),.brand-panel textarea{font-size:12px}.transport{height:47px}.transport-start{gap:7px}.time-readout{font-size:9px;gap:5px}.timeline-toolbar{padding:0 14px}.timeline-tools{gap:1px}.timeline-tools .tool-divider{margin:0 4px}.timeline-scroll{padding:0 14px}.clip-inspector{padding:8px 14px;flex-wrap:wrap;gap:7px}.clip-inspector>span{max-width:100%;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.clip-inspector>div{width:100%;justify-content:space-between;gap:6px}.library-panel{padding:24px 14px 12px}.library-title-row{gap:8px;flex-wrap:wrap}.library-heading h2{font-size:20px}.library-heading p{font-size:11px;line-height:1.6;margin-top:9px}.library-actions{gap:8px}.search-box{min-width:0;flex:1}.search-box input{min-width:0}.reference-tabs{margin-bottom:8px}.reference-tab{font-size:10px}.source-heading{font-size:10px;align-items:start}.source-heading>span:last-child{font-size:8px;max-width:130px;text-align:right;line-height:1.5}.segment-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:17px 11px}.segment-add{width:32px;height:32px}.segment-preview svg{opacity:.8}.segment-meta{font-size:10px}.segment-subtitle{font-size:9px}.studio-footer{margin:12px 14px 0;font-size:9px}.toast{font-size:11px}.canvas-wrap:fullscreen .film-stage{height:auto;width:100%}}
-@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;transition:none!important;animation:none!important}}
+/* Null — Launch Studio. Minimal dark theme.
+ One neutral surface scale, one brand accent, no decoration. */
+
+:root {
+ color-scheme: dark;
+ --bg: #0c0c0d;
+ --panel: #111112;
+ --surface: #17171a;
+ --raised: #1e1e21;
+ --line: #242427;
+ --line-soft: #1b1b1e;
+ --text: #ececee;
+ --muted: #86868c;
+ --faint: #5c5c62;
+ --accent: #daef79;
+ --paper: #eeefdf;
+ --radius: 6px;
+ --gutter: 24px;
+ font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif;
+ font-synthesis: none;
+}
+
+* { box-sizing: border-box; }
+
+body {
+ margin: 0;
+ background: var(--bg);
+ color: var(--text);
+ font-size: 13px;
+ line-height: 1.45;
+ -webkit-font-smoothing: antialiased;
+}
+
+h1, h2 { font-size: 13px; font-weight: 500; margin: 0; letter-spacing: 0; }
+
+button, input, textarea, select { font: inherit; color: inherit; }
+button { background: none; border: 0; padding: 0; cursor: pointer; }
+button:disabled { opacity: .35; cursor: default; }
+a { color: inherit; text-decoration: none; }
+
+svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; flex: none; }
+use[href="#i-play"], use[href="#i-spark"] { fill: currentColor; stroke: none; }
+.svg-library { display: none; }
+
+:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+.skip-link {
+ position: fixed; top: 8px; left: 8px; z-index: 50;
+ padding: 8px 12px; background: var(--raised); border-radius: var(--radius);
+ transform: translateY(-200%);
+}
+.skip-link:focus { transform: none; }
+
+/* Decoration the simple theme drops. */
+.logo-dot, .logo-mark, .crumb, .project-caret, .demo-label, .live-dot,
+.top-divider, .avatar, .subtle-label, .panel-description, .identity-footnote,
+.concept-note, .brand-divider, .tiny-dot, .studio-footer, .monitor-dot,
+.library-heading p, .timeline-hint, .direction-label, .direction-copy,
+.footer-mark, .footer-dot, .brand-overlay-divider { display: none; }
+
+/* ---------- Buttons ---------- */
+
+.button {
+ display: inline-flex; align-items: center; gap: 7px;
+ height: 30px; padding: 0 12px;
+ border: 1px solid var(--line); border-radius: var(--radius);
+ background: var(--surface); color: var(--text);
+ font-size: 12px; white-space: nowrap;
+}
+.button:hover:not(:disabled) { background: var(--raised); }
+.button.primary { background: var(--accent); border-color: var(--accent); color: #101010; }
+.button.primary:hover:not(:disabled) { filter: brightness(1.08); }
+.button.subtle { background: none; color: var(--muted); }
+.button.subtle:hover { color: var(--text); }
+.button.small { height: 26px; padding: 0 10px; font-size: 11px; }
+
+.icon-button {
+ display: inline-flex; align-items: center; justify-content: center; position: relative;
+ width: 28px; height: 28px; border-radius: var(--radius); color: var(--muted);
+}
+.icon-button:hover:not(:disabled) { background: var(--surface); color: var(--text); }
+.mute-slash { position: absolute; width: 17px; height: 1px; background: currentColor; transform: rotate(-45deg); }
+.text-button { color: var(--muted); font-size: 12px; padding: 4px 6px; border-radius: 4px; }
+.text-button:hover:not(:disabled) { color: var(--text); background: var(--surface); }
+.text-button.remove-clip:hover:not(:disabled) { color: #f08a7a; }
+
+/* ---------- Top bar ---------- */
+
+.topbar {
+ position: sticky; top: 0; z-index: 20;
+ display: flex; align-items: center; gap: 14px;
+ height: 48px; padding: 0 var(--gutter);
+ background: var(--bg); border-bottom: 1px solid var(--line);
+}
+.logo { font-size: 15px; font-weight: 600; letter-spacing: -.02em; }
+.project-link { color: var(--muted); font-size: 12px; }
+.project-link:hover { color: var(--text); }
+.project-name { font-size: 12px; color: var(--muted); }
+.save-state { margin-left: auto; display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--faint); }
+.save-state span { width: 5px; height: 5px; border-radius: 50%; background: var(--faint); }
+.top-actions { display: flex; align-items: center; gap: 8px; }
+
+/* ---------- Shell ---------- */
+
+.workspace { display: flex; align-items: flex-start; }
+
+.rail {
+ position: sticky; top: 48px;
+ display: flex; flex-direction: column; gap: 2px;
+ width: 64px; padding: 12px 8px; flex: none;
+ border-right: 1px solid var(--line);
+ height: calc(100vh - 48px);
+}
+.rail-item {
+ display: flex; flex-direction: column; align-items: center; gap: 4px;
+ padding: 9px 0; border-radius: var(--radius);
+ color: var(--faint); font-size: 10px;
+}
+.rail-item:hover { color: var(--text); background: var(--surface); }
+.rail-item.active { color: var(--text); }
+.rail-bottom { margin-top: auto; text-align: center; font-size: 10px; color: #303034; }
+
+main { flex: 1; min-width: 0; }
+
+.studio-heading {
+ display: flex; align-items: center; justify-content: space-between; gap: 16px;
+ padding: 16px var(--gutter) 0;
+}
+.studio-title { display: flex; align-items: center; gap: 10px; min-width: 0; }
+.studio-title h1 { font-size: 14px; font-weight: 500; }
+
+.view-toggle { display: flex; gap: 2px; padding: 2px; background: var(--surface); border-radius: var(--radius); }
+.view-toggle button { padding: 5px 11px; border-radius: 4px; font-size: 11px; color: var(--muted); }
+.view-toggle button.active { background: var(--raised); color: var(--text); }
+
+/* ---------- Preview + brand ---------- */
+
+.upper-workspace {
+ display: grid; grid-template-columns: minmax(0, 1fr) 248px;
+ gap: 24px; padding: 16px var(--gutter) 24px;
+}
+.preview-area { min-width: 0; display: flex; flex-direction: column; gap: 8px; }
+
+.canvas-top, .monitor-source {
+ display: flex; align-items: center; justify-content: space-between; gap: 12px;
+ font-size: 10px; letter-spacing: .07em; text-transform: uppercase; color: var(--faint);
+}
+.canvas-top span, .monitor-source span { display: flex; align-items: center; gap: 7px; }
+.canvas-sep { color: #2e2e32; }
+.monitor-source i { width: 3px; height: 3px; border-radius: 50%; background: #2e2e32; display: inline-block; }
+.monitor-option { width: 20px; height: 20px; border-radius: 4px; color: var(--faint); }
+.monitor-option:hover, .monitor-option[aria-pressed="true"] { color: var(--text); background: var(--surface); }
+
+.transport {
+ display: flex; align-items: center; justify-content: space-between; gap: 12px;
+ padding: 6px 8px; background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius);
+}
+.transport-start, .transport-end { display: flex; align-items: center; gap: 8px; }
+.transport-play {
+ display: inline-flex; align-items: center; justify-content: center;
+ width: 30px; height: 30px; border-radius: 50%; background: var(--accent); color: #101010;
+}
+.transport-play:disabled { background: var(--raised); color: var(--faint); }
+.time-readout { display: flex; gap: 5px; font-size: 11px; color: var(--faint); font-variant-numeric: tabular-nums; }
+.time-readout strong { color: var(--text); font-weight: 500; }
+.cut-label { font-size: 10px; letter-spacing: .07em; color: var(--faint); }
+
+.brand-panel { scroll-margin-top: 64px; border-left: 1px solid var(--line); padding-left: 24px; }
+.panel-title { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; color: var(--muted); }
+.panel-title svg { color: var(--faint); }
+.field-label { display: block; margin: 14px 0 6px; font-size: 10px; letter-spacing: .07em; text-transform: uppercase; color: var(--faint); }
+.brand-panel > .field-label:first-of-type { margin-top: 0; }
+
+.brand-panel input:not([type=color]), .brand-panel textarea, .brand-panel select {
+ width: 100%; padding: 8px 10px; font-size: 12px;
+ background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius);
+ resize: none;
+}
+.brand-panel input:focus, .brand-panel textarea:focus, .brand-panel select:focus { border-color: #3a3a40; outline: none; }
+.brand-panel select { appearance: none; cursor: pointer; }
+
+.palette { display: flex; align-items: center; gap: 7px; }
+.swatch { width: 20px; height: 20px; border-radius: 50%; background: var(--swatch); border: 1px solid transparent; }
+.swatch.active { box-shadow: 0 0 0 1px var(--bg), 0 0 0 2px var(--swatch); }
+.custom-color { position: relative; width: 20px; height: 20px; display: grid; place-items: center; border: 1px dashed #333338; border-radius: 50%; color: var(--faint); cursor: pointer; font-size: 12px; }
+.custom-color input { position: absolute; inset: 0; opacity: 0; cursor: pointer; }
+
+.overlay-toggle { position: relative; display: flex; align-items: center; justify-content: space-between; margin-top: 16px; font-size: 12px; color: var(--muted); cursor: pointer; }
+.overlay-toggle input { position: absolute; right: 0; width: 1px; height: 1px; opacity: 0; }
+.toggle-track { width: 30px; height: 17px; border-radius: 9px; background: var(--raised); position: relative; transition: background .15s; }
+.toggle-track::after { content: ""; position: absolute; top: 3px; left: 3px; width: 11px; height: 11px; border-radius: 50%; background: var(--muted); transition: transform .15s, background .15s; }
+.overlay-toggle input:checked + .toggle-track { background: var(--accent); }
+.overlay-toggle input:checked + .toggle-track::after { transform: translateX(13px); background: #101010; }
+
+/* ---------- Timeline ---------- */
+
+.timeline-panel { padding: 0 var(--gutter) 24px; border-top: 1px solid var(--line); padding-top: 16px; }
+.timeline-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 10px; }
+.timeline-heading { display: flex; align-items: center; gap: 8px; color: var(--muted); }
+.timeline-heading h2 { color: var(--text); }
+.clip-count { font-size: 11px; color: var(--faint); }
+.timeline-tools { display: flex; align-items: center; gap: 4px; }
+.tool-divider { width: 1px; height: 16px; background: var(--line); margin: 0 4px; }
+
+.timeline-scroll { background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px 12px 14px; overflow-x: auto; scrollbar-width: thin; }
+.timeline-body { position: relative; }
+
+/* Sections: one live box per clip, each looping its own part of the reference.
+ Widths follow clip length, so every box sits directly above its span on the waveform. */
+.timeline-body { min-width: 100%; }
+.clips-track { display: flex; gap: 8px; min-height: 96px; }
+.empty-track {
+ flex: 1; display: grid; place-items: center; min-height: 96px;
+ border: 1px dashed var(--line); border-radius: var(--radius);
+ font-size: 11px; color: var(--faint);
+}
+.timeline-clip {
+ position: relative; min-width: 72px; height: 96px;
+ border: 1px solid var(--line); border-radius: var(--radius);
+ background: #000; text-align: left;
+}
+.timeline-clip .section-video {
+ position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover;
+ border-radius: calc(var(--radius) - 1px); opacity: .6; transition: opacity .2s; pointer-events: none;
+}
+.timeline-clip span {
+ position: absolute; inset: 0; display: flex; flex-direction: column; justify-content: flex-end; gap: 1px;
+ padding: 6px 8px; font-size: 11px; line-height: 1.25; border-radius: inherit;
+ background: linear-gradient(transparent 45%, rgba(0, 0, 0, .8));
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+}
+.timeline-clip small { font-size: 9px; color: #b9b9be; letter-spacing: .04em; }
+.clip-progress {
+ position: absolute; left: 0; right: 0; bottom: 0; height: 2px; border-radius: 0 0 var(--radius) var(--radius);
+ background: var(--accent); transform: scaleX(0); transform-origin: left;
+}
+/* Pointer from each section down to its span on the waveform. */
+.timeline-clip::after {
+ content: ""; position: absolute; left: 50%; bottom: -8px; transform: translateX(-50%);
+ border: 5px solid transparent; border-bottom: 0; border-top: 6px solid #36363b;
+}
+.timeline-clip.selected, .timeline-clip.playing { border-color: var(--accent); }
+.timeline-clip.playing::after { border-top-color: var(--accent); }
+.timeline-clip.selected .section-video, .timeline-clip.playing .section-video, .timeline-clip:hover .section-video { opacity: 1; }
+.timeline-clip.dragging { opacity: .4; }
+
+.ruler { position: relative; height: 14px; margin: 16px 0 4px; font-size: 10px; color: #3d3d42; font-variant-numeric: tabular-nums; }
+.ruler span { position: absolute; top: 0; transform: translateX(-50%); }
+.ruler span:first-child { transform: none; }
+.ruler span:last-child { transform: translateX(-100%); }
+
+/* Waveform lane: the sequence's audio, section spans, and the moving playhead. */
+.wave-lane { position: relative; height: 64px; border-radius: 4px; background: var(--bg); cursor: pointer; }
+.wave-canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
+.wave-spans { position: absolute; inset: 0; display: flex; gap: 8px; pointer-events: none; }
+.wave-spans i { position: relative; min-width: 72px; border-left: 1px solid var(--line); }
+.wave-spans i:first-child { border-left-color: transparent; }
+.wave-spans i::before { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 2px; background: var(--line); }
+.wave-spans i.playing::before { background: var(--accent); }
+
+.playhead { position: absolute; top: -6px; bottom: -4px; left: 0; width: 1px; background: var(--text); pointer-events: none; z-index: 2; }
+.playhead span { position: absolute; top: -3px; left: -4px; width: 9px; height: 9px; border-radius: 2px; background: var(--text); }
+
+.timeline-scrubber { position: absolute; inset: 0; z-index: 3; width: 100%; height: 100%; margin: 0; opacity: 0; pointer-events: none; }
+.wave-lane:has(.timeline-scrubber:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+.clip-inspector {
+ display: flex; align-items: center; justify-content: space-between; gap: 12px;
+ margin-top: 22px; font-size: 12px; color: var(--muted);
+}
+.clip-inspector > div { display: flex; align-items: center; gap: 6px; }
+.clip-inspector label { display: flex; align-items: center; gap: 5px; font-size: 11px; color: var(--faint); }
+.clip-inspector input {
+ width: 62px; padding: 5px 7px; font-size: 11px; font-variant-numeric: tabular-nums;
+ background: var(--surface); border: 1px solid var(--line); border-radius: 4px;
+}
+.clip-inspector input:focus { outline: none; border-color: #3a3a40; }
+
+/* ---------- Library ---------- */
+
+.library-panel { scroll-margin-top: 56px; padding: 20px var(--gutter) 40px; border-top: 1px solid var(--line); }
+.library-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 12px; }
+.library-title-row { display: flex; align-items: center; gap: 10px; }
+.library-title-row h2 { font-size: 14px; }
+.library-count { font-size: 11px; color: var(--faint); }
+.library-actions { display: flex; align-items: center; gap: 8px; }
+
+.search-box {
+ display: flex; align-items: center; gap: 7px; width: 220px; height: 30px; padding: 0 10px;
+ background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); color: var(--faint);
+}
+.search-box:focus-within { border-color: #3a3a40; }
+.search-box input { flex: 1; min-width: 0; background: none; border: 0; outline: none; font-size: 12px; }
+.upload-button { position: relative; cursor: pointer; }
+
+.reference-tabs { display: flex; gap: 6px; overflow-x: auto; padding-bottom: 8px; scrollbar-width: thin; }
+.reference-tab {
+ display: flex; align-items: center; gap: 6px; flex: none;
+ height: 28px; padding: 0 10px; border-radius: var(--radius);
+ background: var(--surface); border: 1px solid var(--line);
+ font-size: 11px; color: var(--muted); white-space: nowrap; max-width: 190px;
+}
+.reference-tab span { overflow: hidden; text-overflow: ellipsis; }
+.reference-tab img { width: 20px; height: 13px; object-fit: cover; border-radius: 2px; }
+.reference-tab:hover { color: var(--text); }
+.reference-tab.active { border-color: #3d3d43; color: var(--text); background: var(--raised); }
+
+.source-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 10px 0 12px; font-size: 11px; color: var(--faint); }
+
+.segment-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 14px; }
+.library-loading, .library-empty { grid-column: 1 / -1; padding: 40px 0; text-align: center; font-size: 12px; color: var(--faint); }
+
+.segment-card { cursor: grab; }
+.segment-visual {
+ position: relative; aspect-ratio: 16 / 9; overflow: hidden;
+ background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius);
+}
+.segment-visual img, .segment-visual video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+.segment-visual video { z-index: 1; }
+.segment-card:hover .segment-visual { border-color: #3d3d43; }
+
+.segment-number, .segment-length {
+ position: absolute; z-index: 2; top: 6px; font-size: 9px; letter-spacing: .06em;
+ padding: 2px 5px; border-radius: 3px; background: rgba(8, 8, 9, .72); color: #c9c9ce;
+}
+.segment-number { left: 6px; }
+.segment-length { right: 6px; }
+.segment-preview {
+ position: absolute; inset: 0; z-index: 2; display: grid; place-items: center;
+ color: #fff; opacity: 0; transition: opacity .12s;
+}
+.segment-card:hover .segment-preview { opacity: 1; }
+.segment-preview svg { width: 26px; height: 26px; filter: drop-shadow(0 1px 4px rgba(0, 0, 0, .6)); }
+.segment-add {
+ position: absolute; z-index: 3; right: 6px; bottom: 6px;
+ display: grid; place-items: center; width: 24px; height: 24px; border-radius: 50%;
+ background: var(--accent); color: #101010; opacity: 0; transition: opacity .12s;
+}
+.segment-card:hover .segment-add, .segment-add:focus-visible { opacity: 1; }
+
+.segment-meta { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; margin-top: 7px; font-size: 12px; }
+.segment-meta span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.segment-meta small { font-size: 10px; color: var(--faint); font-variant-numeric: tabular-nums; flex: none; }
+.segment-subtitle { margin-top: 2px; font-size: 11px; color: var(--faint); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+
+/* ---------- Toast + dialog ---------- */
+
+.toast {
+ position: fixed; left: 50%; bottom: 24px; z-index: 40;
+ transform: translate(-50%, 14px); opacity: 0; pointer-events: none;
+ padding: 9px 14px; font-size: 12px;
+ background: var(--raised); border: 1px solid var(--line); border-radius: var(--radius);
+ transition: opacity .18s, transform .18s;
+}
+.toast.show { opacity: 1; transform: translate(-50%, 0); }
+
+dialog {
+ width: min(760px, 92vw); padding: 16px; color: var(--text);
+ background: var(--panel); border: 1px solid var(--line); border-radius: 10px;
+}
+dialog::backdrop { background: rgba(6, 6, 7, .8); }
+.dialog-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
+.dialog-top h2 { font-size: 14px; }
+.eyebrow { display: block; font-size: 10px; letter-spacing: .08em; color: var(--faint); margin-bottom: 3px; }
+#dialog-video { width: 100%; aspect-ratio: 16 / 9; background: #000; border-radius: var(--radius); }
+.dialog-bottom { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 12px; font-size: 11px; color: var(--faint); }
+
+/* ---------- Responsive ---------- */
+
+@media (max-width: 1080px) {
+ :root { --gutter: 16px; }
+ .upper-workspace { grid-template-columns: minmax(0, 1fr) 210px; gap: 18px; }
+ .brand-panel { padding-left: 18px; }
+ .save-state { display: none; }
+}
+@media (max-width: 820px) {
+ .rail { display: none; }
+ .upper-workspace { grid-template-columns: 1fr; }
+ .brand-panel { scroll-margin-top: 64px; border-left: 0; border-top: 1px solid var(--line); padding: 16px 0 0; }
+ .library-heading, .library-actions { flex-wrap: wrap; }
+ .search-box { width: 150px; }
+ .project-name, .project-link { display: none; }
+}
+@media (prefers-reduced-motion: reduce) {
+ *, *::before, *::after { transition: none !important; animation: none !important; scroll-behavior: auto !important; }
+}
diff --git a/public/editor.html b/public/editor.html
index c3d4b65..e1329a0 100644
--- a/public/editor.html
+++ b/public/editor.html
@@ -57,8 +57,8 @@
</aside>
</section>
<section class="timeline-panel" aria-labelledby="timeline-title">
- <div class="timeline-toolbar"><div class="timeline-heading"><svg><use href="#i-film"/></svg><h2 id="timeline-title">Your film</h2><span class="clip-count" id="clip-count">0 clips</span></div><div class="timeline-tools"><span class="timeline-hint">Drag to reorder · select to edit</span><button class="icon-button" id="undo" title="Undo" aria-label="Undo last timeline change">↶</button><button class="icon-button" id="redo" title="Redo" aria-label="Redo timeline change">↷</button><span class="tool-divider"></span><button class="button small subtle" id="reset-demo">Load demo</button></div></div>
- <div class="timeline-scroll"><div class="timeline-body" id="timeline-body"><div class="ruler" id="ruler" aria-hidden="true"></div><div class="timeline-lane"><div class="lane-label"><svg><use href="#i-film"/></svg><span>Video</span></div><div class="clips-track" id="clips-track" aria-label="Film clips"></div></div><div class="brand-lane"><span class="lane-label">Aa <span>Brand</span></span><div class="brand-track"><span class="brand-track-name">null</span><span class="brand-track-line"></span><span>Your identity, throughout</span></div></div><div class="playhead" id="playhead"><span></span></div><input id="scrubber" class="timeline-scrubber" type="range" min="0" max="1" step="0.01" value="0" aria-label="Sequence playhead"></div></div>
+ <div class="timeline-toolbar"><div class="timeline-heading"><svg><use href="#i-film"/></svg><h2 id="timeline-title">Your film</h2><span class="clip-count" id="clip-count">0 clips</span></div><div class="timeline-tools"><span class="timeline-hint">Drag sections to reorder · click the waveform to jump</span><button class="icon-button" id="undo" title="Undo" aria-label="Undo last timeline change">↶</button><button class="icon-button" id="redo" title="Redo" aria-label="Redo timeline change">↷</button><span class="tool-divider"></span><button class="button small subtle" id="reset-demo">Load demo</button></div></div>
+ <div class="timeline-scroll"><div class="timeline-body" id="timeline-body"><div class="clips-track" id="clips-track" aria-label="Film sections"></div><div class="ruler" id="ruler" aria-hidden="true"></div><div class="wave-lane" id="wave-lane"><canvas class="wave-canvas" id="wave-canvas" aria-hidden="true"></canvas><div class="wave-spans" id="wave-spans" aria-hidden="true"></div><div class="playhead" id="playhead"><span></span></div><input id="scrubber" class="timeline-scrubber" type="range" min="0" max="1" step="0.01" value="0" aria-label="Sequence playhead"></div></div></div>
<div class="clip-inspector" id="clip-inspector"><span id="selected-clip-name">Choose a clip to fine-tune</span><div><label>In <input id="clip-in" type="number" min="0" step="0.1" aria-label="Clip in point"></label><label>Out <input id="clip-out" type="number" min="0" step="0.1" aria-label="Clip out point"></label><button class="text-button" id="move-left" aria-label="Move selected clip earlier">←</button><button class="text-button" id="move-right" aria-label="Move selected clip later">→</button><button class="text-button remove-clip" id="remove-clip">Remove</button></div></div>
</section>
<section class="library-panel" id="library-panel" aria-labelledby="library-title"><div class="library-heading"><div><div class="library-title-row"><h2 id="library-title">Motion worth borrowing.</h2><span class="library-count" id="library-count">Loading library…</span></div><p>Great openings. Clever transitions. Unforgettable reveals.</p></div><div class="library-actions"><label class="search-box"><svg><use href="#i-search"/></svg><input id="search" type="search" placeholder="Find a reference…" aria-label="Search reference videos"></label><label class="button subtle upload-button"><svg><use href="#i-plus"/></svg>Add video<input id="upload" type="file" accept="video/*" hidden></label></div></div>
diff --git a/public/editor.mjs b/public/editor.mjs
index cfb9536..da518be 100644
--- a/public/editor.mjs
+++ b/public/editor.mjs
@@ -5,7 +5,7 @@ const video = $('preview-video');
const STORAGE = 'null-launch-studio-v1';
const state = { references: [], clips: [], selected: 0, activeReference: 'all', current: 0, playing: false, mode: 'concept', past: [], future: [], dragged: null, dialogSegment: null, initialized: false };
const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches;
-let frame = 0, toastTimer = 0, hoveredVideo = null, dialogTrigger = null, savedTimer = 0;
+let frame = 0, toastTimer = 0, hoveredVideo = null, hoveredSection = null, dialogTrigger = null, savedTimer = 0;
const refFor = id => state.references.find(reference => reference.id === id);
const total = () => sequenceDuration(state.clips);
const startOf = index => sequenceDuration(state.clips.slice(0, index));
@@ -20,6 +20,101 @@ function element(tag, className, text) {
if (text !== undefined) node.textContent = text;
return node;
}
+// Each section box is its own muted video that loops just that clip's part of the reference.
+// While the film plays they all run together; the box for the current cut follows the big preview.
+const LIVE_SECTIONS = 8, SECTION_GAP = 8;
+const waves = new Map();
+function sectionVideo(clip, reference) {
+ const player = element('video', 'section-video');
+ player.muted = true; player.playsInline = true; player.preload = 'metadata'; player.disablePictureInPicture = true;
+ player.poster = clip.poster || reference?.poster || '';
+ if (reference) player.src = reference.src;
+ player.addEventListener('loadedmetadata', () => { player.currentTime = clip.in; });
+ player.addEventListener('timeupdate', () => { if (player.currentTime >= clip.out - .03 && !player.dataset.follow) player.currentTime = clip.in; });
+ return player;
+}
+function syncSections() {
+ const position = locateClip(state.clips, state.current);
+ document.querySelectorAll('.timeline-clip').forEach((button, index) => {
+ const player = button.querySelector('.section-video'), clip = state.clips[index];
+ if (!player || !clip || player.readyState < 1) return;
+ const active = Boolean(position) && index === position.index;
+ const live = state.playing && !reducedMotion && (!position || state.clips.length <= LIVE_SECTIONS || Math.abs(index - position.index) <= LIVE_SECTIONS / 2);
+ if (active) {
+ player.dataset.follow = '1';
+ if (Math.abs(player.currentTime - position.local) > .25) player.currentTime = position.local;
+ } else if (player.dataset.follow) { delete player.dataset.follow; player.currentTime = clip.in; }
+ if (live && player.paused) player.play().catch(() => {});
+ else if (!live && !player.paused && button !== hoveredSection) player.pause();
+ });
+}
+function spans() {
+ return [...document.querySelectorAll('.timeline-clip')].map(button => ({ left: button.offsetLeft, width: button.offsetWidth }));
+}
+function timeToX(time, layout = spans()) {
+ const position = locateClip(state.clips, time);
+ if (!position || !layout[position.index]) return 0;
+ const clip = state.clips[position.index], box = layout[position.index];
+ return box.left + box.width * Math.min(1, Math.max(0, (position.local - clip.in) / (clip.out - clip.in || 1)));
+}
+function xToTime(x) {
+ const layout = spans(); if (!layout.length) return 0;
+ let index = layout.findIndex(box => x < box.left + box.width + SECTION_GAP / 2);
+ if (index < 0) index = layout.length - 1;
+ const clip = state.clips[index], box = layout[index];
+ return startOf(index) + (clip.out - clip.in) * Math.min(1, Math.max(0, (x - box.left) / box.width));
+}
+async function loadWaves() {
+ const ids = [...new Set(state.clips.map(clip => clip.ref))].filter(id => !waves.has(id) && !refFor(id)?.uploaded);
+ await Promise.all(ids.map(async id => {
+ waves.set(id, null);
+ try { const response = await fetch(`/references/${id}.wave.json`); if (response.ok) waves.set(id, await response.json()); } catch {}
+ }));
+ drawWave();
+}
+function drawWave() {
+ const canvas = $('wave-canvas'), ratio = devicePixelRatio || 1;
+ const width = canvas.clientWidth, height = canvas.clientHeight;
+ if (!width || !height) return;
+ if (canvas.width !== Math.round(width * ratio) || canvas.height !== Math.round(height * ratio)) { canvas.width = Math.round(width * ratio); canvas.height = Math.round(height * ratio); }
+ const context = canvas.getContext('2d');
+ context.setTransform(ratio, 0, 0, ratio, 0, 0); context.clearRect(0, 0, width, height);
+ const layout = spans(), played = timeToX(state.current, layout), middle = height / 2;
+ const accent = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim() || '#daef79';
+ const BAR = 2, STEP = 3;
+ state.clips.forEach((clip, index) => {
+ const box = layout[index]; if (!box) return;
+ const wave = waves.get(clip.ref), length = clip.out - clip.in;
+ for (let x = 0; x < box.width - 1; x += STEP) {
+ let level = .04;
+ if (wave?.peaks?.length) {
+ const from = Math.floor((clip.in + length * x / box.width) * wave.rate);
+ const to = Math.max(from + 1, Math.floor((clip.in + length * (x + STEP) / box.width) * wave.rate));
+ let peak = 0; for (let i = from; i < to && i < wave.peaks.length; i++) peak = Math.max(peak, wave.peaks[i]);
+ level = Math.max(.04, peak / 100);
+ }
+ const bar = Math.max(1, level * (height - 12));
+ context.fillStyle = box.left + x < played ? accent : '#3a3a3f';
+ context.fillRect(box.left + x, middle - bar / 2, BAR, bar);
+ }
+ });
+}
+function paintProgress() {
+ const position = locateClip(state.clips, state.current);
+ const markers = $('wave-spans').children;
+ document.querySelectorAll('.timeline-clip').forEach((button, index) => {
+ const clip = state.clips[index], bar = button.querySelector('.clip-progress');
+ if (!clip || !bar) return;
+ const length = clip.out - clip.in;
+ const share = !position || index > position.index ? 0
+ : index < position.index || !length ? 1
+ : Math.min(1, Math.max(0, (position.local - clip.in) / length));
+ bar.style.transform = `scaleX(${share})`;
+ const playing = Boolean(position) && index === position.index;
+ button.classList.toggle('playing', playing); markers[index]?.classList.toggle('playing', playing);
+ });
+ drawWave();
+}
function toast(message) {
$('toast').textContent = message; $('toast').classList.add('show');
clearTimeout(toastTimer); toastTimer = setTimeout(() => $('toast').classList.remove('show'), 2800);
@@ -61,7 +156,6 @@ function loadDemo() {
function brand() {
const name = $('brand-name').value.trim() || 'Your brand';
$('film-brand-name').textContent = name;
- document.querySelector('.brand-track-name').textContent = name;
document.querySelector('.film-monogram').textContent = name[0].toUpperCase();
const message = $('brand-message').value.trim() || 'Good ideas. Great motion.';
$('film-headline').textContent = message;
@@ -75,7 +169,7 @@ function palette(accent, paper) {
button.classList.toggle('active', active); button.setAttribute('aria-pressed', active);
});
$('custom-color').value = accent;
- persist();
+ drawWave(); persist();
}
function setAspect() {
$('canvas-wrap').classList.toggle('portrait', $('aspect').value === 'portrait');
@@ -93,21 +187,31 @@ function renderTimeline() {
button.style.flexBasis = '0'; button.type = 'button'; button.draggable = true; button.dataset.index = index;
button.setAttribute('aria-label', `Clip ${index + 1}: ${reference?.name || 'Reference'}, ${seconds(clip.out - clip.in)}`);
button.setAttribute('aria-pressed', index === state.selected);
- const image = element('img'); image.src = clip.poster || reference?.poster || ''; image.alt = ''; image.draggable = false;
const caption = element('span', '', clip.label || reference?.name || 'Reference');
caption.prepend(element('small', '', `${String(index + 1).padStart(2, '0')} · ${seconds(clip.out - clip.in)}`));
- button.append(image, caption);
+ button.append(sectionVideo(clip, reference), caption, element('i', 'clip-progress'));
button.addEventListener('click', () => { state.selected = index; pause(); seek(startOf(index)); renderSelection(); });
+ button.addEventListener('mouseenter', () => previewSection(button));
+ button.addEventListener('mouseleave', () => stopSection(button));
button.addEventListener('dragstart', event => { state.dragged = { type: 'clip', index }; event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/plain', String(index)); button.classList.add('dragging'); });
button.addEventListener('dragend', () => { state.dragged = null; button.classList.remove('dragging'); });
track.append(button);
});
$('clip-count').textContent = `${state.clips.length} clips`;
$('time-total').textContent = timecode(total()); $('scrubber').max = Math.max(total(), .01);
- $('ruler').replaceChildren(...Array.from({ length: 9 }, (_, i) => element('span', '', `${Math.round(total() * i / 8)}s`)));
+ $('wave-spans').replaceChildren(...state.clips.map(clip => { const marker = element('i'); marker.style.flex = `${clip.out - clip.in} 1 0`; return marker; }));
+ $('timeline-body').style.minWidth = `${state.clips.length * 80}px`;
$('undo').disabled = !state.past.length; $('redo').disabled = !state.future.length;
$('play').disabled = $('play-top').disabled = !state.clips.length;
- renderSelection(); updatePlayhead();
+ renderSelection(); updatePlayhead(); requestAnimationFrame(renderRuler); loadWaves();
+}
+function renderRuler() {
+ const layout = spans(), count = Math.max(2, Math.min(9, Math.floor($('timeline-body').clientWidth / 110) + 1));
+ $('ruler').replaceChildren(...Array.from({ length: state.clips.length ? count : 0 }, (_, i) => {
+ const time = total() * i / (count - 1), label = element('span', '', `${time.toFixed(time < 10 && i ? 1 : 0)}s`);
+ label.style.left = `${timeToX(time, layout)}px`; return label;
+ }));
+ updatePlayhead();
}
function renderSelection() {
document.querySelectorAll('.timeline-clip').forEach((button, index) => {
@@ -123,9 +227,9 @@ function renderSelection() {
}
}
function updatePlayhead() {
- const percent = total() ? state.current / total() : 0;
- $('playhead').style.left = `calc(77px + (100% - 77px) * ${Math.min(1, percent)})`;
+ $('playhead').style.left = `${timeToX(state.current)}px`;
$('scrubber').value = state.current; $('time-current').textContent = timecode(state.current);
+ paintProgress();
}
function updateScene(index) {
const clip = state.clips[index]; if (!clip) return;
@@ -170,9 +274,10 @@ function tick() {
seek(startOf(next) + .001);
} else { state.current = Math.min(total(), startOf(position.index) + Math.max(0, video.currentTime - clip.in)); updatePlayhead(); }
}
+ syncSections();
frame = requestAnimationFrame(tick);
}
-function pause() { state.playing = false; video.pause(); cancelAnimationFrame(frame); playButtons(); }
+function pause() { state.playing = false; video.pause(); cancelAnimationFrame(frame); playButtons(); syncSections(); }
function togglePlay() {
if (state.playing) return pause();
if (!state.clips.length) return;
@@ -181,6 +286,8 @@ function togglePlay() {
playButtons(); cancelAnimationFrame(frame); frame = requestAnimationFrame(tick);
}
video.addEventListener('loadeddata', () => { $('video-loading').hidden = true; });
+video.addEventListener('seeked', syncSections);
+new ResizeObserver(renderRuler).observe($('timeline-body'));
video.addEventListener('error', () => { $('video-loading').hidden = false; $('video-loading').textContent = 'Reference unavailable. Choose another moment.'; pause(); });
function addSegment(segment, index = state.clips.length) {
if (state.clips.length >= 24) return toast('This concept can hold up to 24 moments.');
@@ -219,6 +326,18 @@ function hoverPreview(card, segment) {
player.addEventListener('timeupdate', () => { if (player.currentTime >= segment.out) player.currentTime = segment.in; });
card.querySelector('.segment-visual').append(player);
}
+function previewSection(button) {
+ if (reducedMotion || state.playing || !matchMedia('(hover:hover)').matches) return;
+ const player = button.querySelector('.section-video'); if (!player) return;
+ stopHover(); hoveredSection = button; player.play().catch(() => {});
+}
+function stopSection(button) {
+ if (hoveredSection !== button) return;
+ hoveredSection = null;
+ const player = button.querySelector('.section-video'), clip = state.clips[Number(button.dataset.index)];
+ if (player && clip && !state.playing) { player.pause(); if (!player.dataset.follow) player.currentTime = clip.in; }
+ syncSections();
+}
function openReference(segment, trigger) {
stopHover(); pause(); state.dialogSegment = segment; dialogTrigger = trigger;
const reference = refFor(segment.ref);
@@ -310,6 +429,13 @@ $('brand-visible').addEventListener('change', () => {
});
$('restart').addEventListener('click', () => { pause(); seek(0); });
$('scrubber').addEventListener('input', () => { pause(); seek(Number($('scrubber').value)); });
+$('wave-lane').addEventListener('pointerdown', event => {
+ if (!state.clips.length) return;
+ event.preventDefault(); pause();
+ const lane = $('wave-lane'), scrub = move => seek(xToTime(move.clientX - lane.getBoundingClientRect().left));
+ lane.setPointerCapture(event.pointerId); scrub(event);
+ lane.onpointermove = scrub; lane.onpointerup = lane.onpointercancel = () => { lane.onpointermove = lane.onpointerup = lane.onpointercancel = null; };
+});
$('mute').addEventListener('click', () => { video.muted = !video.muted; $('mute').setAttribute('aria-pressed', video.muted); $('mute').setAttribute('aria-label', video.muted ? 'Unmute reference audio' : 'Mute reference audio'); document.querySelector('.mute-slash').hidden = !video.muted; });
$('fullscreen').addEventListener('click', () => { if (document.fullscreenElement) document.exitFullscreen(); else $('canvas-wrap').requestFullscreen?.().catch(() => toast('Fullscreen is unavailable in this browser.')); });
$('present').addEventListener('click', () => { document.body.classList.add('present-mode'); toast('Presentation view · press Esc to exit'); });
diff --git a/public/scraps.mjs b/public/scraps.mjs
new file mode 100644
index 0000000..3ded7cf
--- /dev/null
+++ b/public/scraps.mjs
@@ -0,0 +1,126 @@
+// Six rough HyperFrames-style drafts, one per section of the Interface (Replit) reference.
+// Each is a 640×360 HTML scene driven by a paused GSAP timeline, so the page can seek it
+// to any local time. They are deliberately crude: placeholder bars, flat blocks, plain type.
+const ORANGE = '#000000', INK = '#000000', PINK = '#e6e6e6', GREY = '#d0d0d0', LILAC = '#ececec';
+
+function box(parent, css, text) {
+ const node = document.createElement('div');
+ node.style.cssText = 'position:absolute;' + css;
+ if (text !== undefined) node.textContent = text;
+ parent.append(node);
+ return node;
+}
+function paper(root) {
+ root.style.cssText += `;background:#ffffff;font-family:Arial,Helvetica,sans-serif;color:${INK}`;
+}
+const words = (parent, css, list) => list.map(([text, style = '']) => box(parent, `position:relative;display:inline-block;${style}`, text))
+ .reduce((row, word) => (row.append(word), row), box(parent, `display:flex;gap:10px;align-items:center;white-space:nowrap;${css}`));
+const bar = (parent, css) => box(parent, `height:8px;border-radius:4px;background:${GREY};${css}`);
+function dashboard(parent, css) {
+ const win = box(parent, `background:#fff;border:2px solid ${GREY};border-radius:10px;overflow:hidden;${css}`);
+ bar(win, 'left:14px;top:14px;width:120px;');
+ bar(win, 'left:14px;top:30px;width:70px;height:6px;');
+ const cards = [0, 1, 2, 3].map(i => box(win, `left:calc(14px + ${i * 24}%);top:56px;width:calc(24% - 12px);height:40px;border-radius:6px;background:${LILAC};`));
+ const chart = box(win, `left:14px;top:108px;right:34%;bottom:14px;border-radius:6px;background:${LILAC};opacity:.8`);
+ const side = box(win, `right:14px;top:108px;width:28%;bottom:14px;border-radius:6px;background:${LILAC};opacity:.6`);
+ return { win, cards, chart, side };
+}
+function cursor(parent, color, css) {
+ const node = box(parent, `width:0;height:0;border-left:9px solid transparent;border-right:9px solid transparent;border-bottom:22px solid ${color};transform:rotate(-20deg);${css}`);
+ return node;
+}
+
+const scenes = [
+ { name: 'Intro', build(root, tl) {
+ const line = words(root, 'left:50%;top:50%;transform:translate(-50%,-50%);font-size:52px;', [['Now'], ['everyone'], ['■', `color:${ORANGE};font-size:44px`], ['can build']]);
+ tl.from(line.children, { y: 18, opacity: 0, stagger: .22, duration: .4, ease: 'power3.out' }, 0);
+ tl.to(line, { opacity: 0, scale: .8, duration: .3 }, 1.45);
+ const grid = box(root, 'left:50%;top:50%;width:300px;height:190px;transform:translate(-50%,-50%) scale(1.45)');
+ const tiles = [
+ box(grid, `left:0;top:0;width:170px;height:80px;border-radius:14px;background:${INK};color:#fff;font-size:30px;display:grid;place-items:center`, 'safely'),
+ box(grid, `left:182px;top:0;width:80px;height:80px;border-radius:14px;background:${ORANGE}`),
+ box(grid, `left:0;top:92px;width:80px;height:92px;border-radius:14px;border:2px dashed ${GREY};background:#fff`),
+ box(grid, `left:92px;top:100px;width:90px;height:80px;border-radius:14px;background:${ORANGE}`),
+ box(grid, `left:194px;top:96px;width:88px;height:88px;border-radius:50%;border:2px solid ${INK};background:#fff`)
+ ];
+ tl.from(tiles, { scale: 0, opacity: 0, stagger: .1, duration: .45, ease: 'back.out(1.6)' }, 1.6);
+ } },
+ { name: 'Logo', build(root, tl) {
+ const mark = box(root, 'left:50%;top:50%;width:150px;height:150px;transform:translate(-50%,-50%)');
+ [['0', '0'], ['50px', '50px'], ['0', '100px']].forEach(([left, top]) => box(mark, `left:${left};top:${top};width:62px;height:50px;border-radius:12px;background:${ORANGE}`));
+ tl.from(mark, { scale: 1.8, duration: .8, ease: 'power3.out' }, 0);
+ tl.to(mark, { scale: .55, x: -120, duration: .6, ease: 'power3.inOut' }, 1);
+ const word = box(root, 'left:262px;top:140px;font-size:72px;overflow:hidden;white-space:nowrap;width:0', 'Replit');
+ tl.to(word, { width: 230, duration: .6, ease: 'steps(6)' }, 1.5);
+ const tag = box(root, 'left:150px;top:250px;display:flex;gap:8px;align-items:center');
+ bar(tag, 'position:relative;width:60px'); bar(tag, `position:relative;width:70px;background:${ORANGE}`); bar(tag, 'position:relative;width:170px');
+ tl.from(tag, { opacity: 0, y: 10, duration: .4 }, 2.05);
+ } },
+ { name: 'Prompt', build(root, tl) {
+ const title = box(root, 'left:0;right:0;top:70px;text-align:center;font-size:48px', 'What will you build?');
+ tl.from(title, { opacity: 0, y: 14, duration: .4 }, 0);
+ const input = box(root, `left:100px;top:150px;width:440px;height:110px;border:2px solid ${PINK};border-radius:12px;background:#fff`);
+ const typed = bar(input, 'left:20px;top:22px;width:0;height:12px;border-radius:6px;background:#bdbdbd');
+ box(input, `right:16px;bottom:16px;width:22px;height:22px;border-radius:50%;background:${ORANGE}`);
+ tl.from(input, { opacity: 0, scaleX: .8, duration: .4 }, .25);
+ tl.to(typed, { width: 340, duration: 1.3, ease: 'steps(18)' }, .6);
+ tl.to([title, input], { opacity: 0, y: -20, duration: .3 }, 2.1);
+ const line = box(root, `left:120px;top:270px;width:0;height:4px;background:${ORANGE}`);
+ const button = box(root, `left:255px;top:115px;width:130px;height:130px;border-radius:50%;background:${ORANGE};color:#fff;font-size:60px;display:grid;place-items:center`, '→');
+ tl.from(button, { scale: 0, duration: .4, ease: 'back.out(2)' }, 2.25);
+ tl.to(line, { width: 400, duration: .6, ease: 'power2.out' }, 2.4);
+ } },
+ { name: 'Build', build(root, tl) {
+ const bubble = box(root, `left:300px;top:50px;width:280px;height:70px;border-radius:14px;background:${PINK}`);
+ bar(bubble, 'left:18px;top:18px;width:230px;height:12px;border-radius:6px;background:#c4c4c4'); bar(bubble, 'left:18px;top:40px;width:150px;height:12px;border-radius:6px;background:#c4c4c4');
+ const working = box(root, 'left:90px;top:160px;display:flex;align-items:center;gap:14px;font-size:34px;color:#7a7a7a');
+ box(working, `position:relative;width:34px;height:34px;border-radius:8px;background:${ORANGE}`); working.append('working…');
+ tl.from(bubble, { opacity: 0, x: 30, duration: .4 }, 0);
+ tl.from(working, { opacity: 0, duration: .3 }, .4);
+ tl.to(working.firstChild, { rotation: 360, duration: .8, repeat: 1 }, .4);
+ const { win, cards, chart, side } = dashboard(root, 'left:110px;top:120px;width:420px;height:210px');
+ tl.from(win, { opacity: 0, scale: .4, y: 60, duration: .7, ease: 'power3.out' }, 1.4);
+ tl.to([bubble, working], { opacity: 0, duration: .3 }, 1.4);
+ tl.to(win, { left: 20, top: 20, width: 600, height: 320, duration: .7, ease: 'power2.inOut' }, 2.4);
+ tl.from([...cards, chart, side], { opacity: 0, y: 10, stagger: .08, duration: .3 }, 1.9);
+ } },
+ { name: 'Team', build(root, tl) {
+ const line = words(root, 'left:50%;top:120px;transform:translateX(-50%);font-size:50px', [['Build'], ['with'], ['your'], ['team']]);
+ tl.from(line.children, { opacity: 0, y: 12, stagger: .15, duration: .35 }, 0);
+ const { win } = dashboard(root, 'left:40px;top:30px;width:560px;height:300px');
+ const cursors = [cursor(root, INK, 'left:110px;top:250px;scale:1.8'), cursor(root, INK, 'left:310px;top:250px;scale:1.8'), cursor(root, INK, 'left:510px;top:240px;scale:1.8')];
+ tl.from(cursors, { opacity: 0, y: 40, stagger: .12, duration: .4 }, .5);
+ tl.to(cursors, { y: -70, x: i => [40, -20, -60][i], duration: .8, ease: 'power2.inOut' }, 1);
+ tl.to(line, { opacity: 0, duration: .3 }, 1.7);
+ tl.from(win, { opacity: 0, scale: .85, duration: .5, ease: 'power3.out' }, 1.8);
+ tl.to(cursors, { x: i => [160, 80, -120][i], y: i => [-150, -60, -120][i], duration: 1.2, ease: 'sine.inOut' }, 2.2);
+ } },
+ { name: 'Secure', build(root, tl) {
+ const top = box(root, 'left:70px;top:50px;display:flex;gap:14px;transform:scale(1.5);transform-origin:0 0');
+ const tiles = [0, 1].map(() => box(top, `position:relative;width:62px;height:62px;border-radius:14px;background:${PINK}`));
+ const pill = box(top, `position:relative;height:62px;padding:0 24px;border-radius:14px;background:#fff;border:2px solid ${GREY};color:${ORANGE};font-size:24px;display:grid;place-items:center`, 'Secure');
+ const cta = box(root, `left:70px;top:170px;height:84px;padding:0 36px;border-radius:20px;background:${ORANGE};color:#fff;font-size:36px;display:grid;place-items:center;white-space:nowrap`, 'with enterprise controls');
+ tl.from([...tiles, pill], { scale: 0, stagger: .1, duration: .4, ease: 'back.out(1.7)' }, 0);
+ tl.from(cta, { opacity: 0, y: 16, duration: .4 }, .45);
+ tl.to([top, cta], { opacity: 0, scale: .9, duration: .3 }, 1.5);
+ const rows = [0, 1, 2, 3].map(row => {
+ const strip = box(root, `left:-40px;top:${40 + row * 78}px;display:flex;gap:14px`);
+ for (let i = 0; i < 6; i++) box(strip, `position:relative;width:130px;height:56px;border-radius:10px;background:${(i + row) % 2 ? '#ffffff' : LILAC};border:1.5px solid ${GREY};box-sizing:border-box`);
+ return strip;
+ });
+ const band = box(root, 'left:0;right:0;top:158px;height:44px;background:#ffffff');
+ const label = box(root, 'left:0;right:0;top:170px;text-align:center;font-size:26px', 'Trusted by');
+ tl.from(rows, { opacity: 0, duration: .3, stagger: .05 }, 1.75);
+ tl.to(rows, { x: i => i % 2 ? -110 : 70, duration: 2, ease: 'none' }, 1.75);
+ tl.from([band, label], { opacity: 0, duration: .3 }, 2);
+ } }
+];
+
+export function buildScrap(index, root, duration) {
+ paper(root);
+ const tl = gsap.timeline({ paused: true });
+ scenes[index].build(root, tl);
+ if (tl.duration() < duration) tl.to({}, { duration: duration - tl.duration() });
+ return tl;
+}
+export const scrapNames = scenes.map(scene => scene.name);
diff --git a/scripts/build-showcase.mjs b/scripts/build-showcase.mjs
new file mode 100644
index 0000000..1675403
--- /dev/null
+++ b/scripts/build-showcase.mjs
@@ -0,0 +1,41 @@
+// Build the committed showcase: the only references published with the repository.
+// Copies the chosen references' posters, sections, scene cuts and drafts from the local
+// library into showcase/references/, and re-encodes their videos (1080p H.264, web-sized)
+// plus an AAC track into showcase/media/. The rest of the library stays local and ignored.
+import { spawn } from 'node:child_process';
+import { copyFile, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+
+const SHOWCASE = ['69614b10fa87', '227b019e7968', '5db95a3a7c73'];
+const root = new URL('../', import.meta.url), library = new URL('public/references/', root);
+const out = new URL('showcase/', root), refs = new URL('references/', out), media = new URL('media/', out);
+const path = url => fileURLToPath(url);
+const ffmpeg = args => new Promise((resolve, reject) => {
+ const child = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-y', ...args], { stdio: 'inherit' });
+ child.on('error', reject); child.on('close', code => code === 0 ? resolve() : reject(new Error(`ffmpeg exited ${code}`)));
+});
+const readJson = async name => JSON.parse(await readFile(new URL(name, library), 'utf8'));
+const pick = object => Object.fromEntries(SHOWCASE.filter(id => object[id]).map(id => [id, object[id]]));
+
+await rm(out, { recursive: true, force: true });
+await mkdir(refs, { recursive: true }); await mkdir(media, { recursive: true });
+
+const catalog = await readJson('catalog.json');
+const references = catalog.references.filter(reference => SHOWCASE.includes(reference.id))
+ .map(({ originalName, ...reference }) => reference);
+await writeFile(new URL('catalog.json', refs), JSON.stringify({ references }, null, 2));
+const drafts = await readJson('drafts.json');
+await writeFile(new URL('drafts.json', refs), JSON.stringify({ aliases: {}, drafts: pick(drafts.drafts) }, null, 1));
+await writeFile(new URL('sections.json', refs), JSON.stringify(pick(await readJson('sections.json')), null, 1));
+await writeFile(new URL('cuts.json', refs), JSON.stringify(pick(await readJson('cuts.json'))));
+
+for (const file of await readdir(library)) {
+ if (SHOWCASE.some(id => file.startsWith(`${id}-`) && file.endsWith('.jpg'))) await copyFile(new URL(file, library), new URL(file, refs));
+}
+for (const id of SHOWCASE) {
+ const source = path(new URL(`.local-media/${id}.mp4`, root)), video = path(new URL(`${id}.mp4`, media));
+ await ffmpeg(['-i', source, '-map', '0:v:0', '-map', '0:a:0?', '-c:v', 'libx264', '-preset', 'medium', '-threads', '2', '-crf', '20', '-maxrate', '6M', '-bufsize', '12M',
+ '-pix_fmt', 'yuv420p', '-vf', 'scale=-2:min(1080\\,ih)', '-c:a', 'aac', '-b:a', '192k', '-movflags', '+faststart', video]);
+ await ffmpeg(['-i', video, '-vn', '-c:a', 'copy', '-f', 'adts', path(new URL(`${id}.aac`, media))]);
+ console.log('showcase', id);
+}
diff --git a/scripts/build-waveforms.mjs b/scripts/build-waveforms.mjs
new file mode 100644
index 0000000..9f7c00e
--- /dev/null
+++ b/scripts/build-waveforms.mjs
@@ -0,0 +1,40 @@
+// Precompute a small audio envelope for every imported reference so the timeline can
+// draw a waveform without the browser decoding multi-hundred-megabyte source videos.
+// Writes public/references/<id>.wave.json ({ rate, peaks }) next to the thumbnails.
+import { spawn } from 'node:child_process';
+import { readFile, writeFile, access } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+
+const RATE = 50, SAMPLE_RATE = 4000, WINDOW = SAMPLE_RATE / RATE;
+const root = new URL('../', import.meta.url);
+const force = process.argv.includes('--force');
+
+function envelope(file) {
+ return new Promise((resolve, reject) => {
+ const ffmpeg = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', file, '-vn', '-ac', '1', '-ar', String(SAMPLE_RATE), '-f', 's16le', 'pipe:1']);
+ const peaks = []; let peak = 0, count = 0, carry = Buffer.alloc(0);
+ ffmpeg.stdout.on('data', chunk => {
+ const data = carry.length ? Buffer.concat([carry, chunk]) : chunk;
+ const usable = data.length - (data.length % 2);
+ for (let offset = 0; offset < usable; offset += 2) {
+ peak = Math.max(peak, Math.abs(data.readInt16LE(offset)));
+ if (++count === WINDOW) { peaks.push(peak); peak = 0; count = 0; }
+ }
+ carry = data.subarray(usable);
+ });
+ ffmpeg.on('error', reject);
+ ffmpeg.on('close', code => code === 0 ? resolve(peaks) : reject(new Error(`ffmpeg exited ${code}`)));
+ });
+}
+
+const catalog = JSON.parse(await readFile(new URL('public/references/catalog.json', root), 'utf8'));
+for (const reference of catalog.references || []) {
+ const output = new URL(`public/references/${reference.id}.wave.json`, root);
+ if (!force) { try { await access(output); continue; } catch {} }
+ try {
+ const peaks = await envelope(fileURLToPath(new URL(`.local-media/${reference.id}.mp4`, root)));
+ const max = Math.max(1, ...peaks);
+ await writeFile(output, JSON.stringify({ rate: RATE, peaks: peaks.map(value => Math.round(value / max * 100)) }));
+ console.log(`${reference.id} ${peaks.length} peaks`);
+ } catch (error) { console.warn(`${reference.id} skipped: ${error.message}`); }
+}
diff --git a/scripts/plan-sections.mjs b/scripts/plan-sections.mjs
new file mode 100644
index 0000000..ef81554
--- /dev/null
+++ b/scripts/plan-sections.mjs
@@ -0,0 +1,50 @@
+// Split every imported reference into 3–8 draft sections at real scene changes and
+// save a contact sheet per reference (two frames per section) for authoring drafts.
+// Writes public/references/sections.json, public/references/cuts.json (every detected scene
+// change, used to time the beats inside a draft) and .artifacts/sections/<id>.jpg.
+import { spawn } from 'node:child_process';
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+
+const root = new URL('../', import.meta.url);
+const run = (args, collect = false) => new Promise((resolve, reject) => {
+ const child = spawn('ffmpeg', ['-hide_banner', ...args]);
+ let log = ''; child.stderr.on('data', chunk => { if (collect) log += chunk; });
+ child.on('error', reject); child.on('close', code => code === 0 ? resolve(log) : reject(new Error(`ffmpeg ${code}`)));
+});
+
+async function sceneCuts(file) {
+ const log = await run(['-i', file, '-an', '-vf', "scale=320:-2,select='gt(scene,0.18)',showinfo", '-f', 'null', '-'], true);
+ return [...log.matchAll(/pts_time:([\d.]+)/g)].map(match => Number(match[1]));
+}
+
+function plan(duration, cuts) {
+ const count = Math.max(3, Math.min(8, Math.round(duration / 4.5)));
+ const bounds = [0];
+ for (let i = 1; i < count; i++) {
+ const ideal = duration * i / count, previous = bounds.at(-1);
+ const near = cuts.filter(cut => cut > previous + 1.2 && cut < duration - 1.2 && Math.abs(cut - ideal) < duration / count * .45);
+ bounds.push(+(near.sort((a, b) => Math.abs(a - ideal) - Math.abs(b - ideal))[0] ?? ideal).toFixed(2));
+ }
+ return bounds.map((start, i) => ({ start, end: +(bounds[i + 1] ?? duration).toFixed(3) }));
+}
+
+const catalog = JSON.parse(await readFile(new URL('public/references/catalog.json', root), 'utf8'));
+const policy = JSON.parse(await readFile(new URL('data/reference-policy.json', root), 'utf8'));
+await mkdir(new URL('.artifacts/sections/', root), { recursive: true });
+const result = {}, allCuts = {};
+for (const reference of catalog.references) {
+ if (policy.excluded?.[reference.id]) continue;
+ const file = fileURLToPath(new URL(`.local-media/${reference.id}.mp4`, root));
+ const cuts = await sceneCuts(file);
+ allCuts[reference.id] = cuts.map(cut => +cut.toFixed(2));
+ const sections = plan(reference.duration, cuts);
+ result[reference.id] = sections;
+ const times = sections.flatMap(({ start, end }) => [start + (end - start) * .3, start + (end - start) * .8]);
+ const select = times.map(t => `lt(prev_t\\,${t.toFixed(2)})*gte(t\\,${t.toFixed(2)})`).join('+');
+ await run(['-y', '-loglevel', 'error', '-i', file, '-an', '-vf', `select='${select}',scale=320:-2,tile=2x${sections.length}:padding=4`, '-frames:v', '1', '-vsync', 'vfr',
+ fileURLToPath(new URL(`.artifacts/sections/${reference.id}.jpg`, root))]);
+ console.log(reference.id, sections.map(s => `${s.start}-${s.end}`).join(' '));
+}
+await writeFile(new URL('public/references/sections.json', root), JSON.stringify(result, null, 1));
+await writeFile(new URL('public/references/cuts.json', root), JSON.stringify(allCuts));
diff --git a/server.js b/server.js
index cb20573..8bb60ac 100644
--- a/server.js
+++ b/server.js
@@ -1,8 +1,8 @@
import http from 'node:http';
-import { readFile, realpath, stat } from 'node:fs/promises';
+import { mkdir, readFile, realpath, stat } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { streamVideo } from './media.js';
+import { streamVideo, extractAudio } from './media.js';
import { curateReferences } from './public/reference-policy.mjs';
const root = fileURLToPath(new URL('./public/', import.meta.url));
@@ -41,6 +41,30 @@ function json(response, status, body) {
response.end(JSON.stringify(body));
}
+// Reference media comes from the ignored local library (.local-media/, public/references/)
+// when it has been imported, and otherwise from the small committed showcase in showcase/.
+const showcase = new URL('./showcase/', import.meta.url);
+const exists = async url => { try { await stat(url); return true; } catch { return false; } };
+const firstExisting = async (...urls) => { for (const url of urls) if (await exists(url)) return url; return null; };
+const localMedia = file => new URL(`./.local-media/${file}`, import.meta.url);
+
+async function serveFile(response, request, directory, pathname) {
+ let filename = path.resolve(directory, '.' + pathname);
+ try {
+ if ((await stat(filename)).isDirectory()) filename = path.join(filename, 'index.html');
+ const [canonicalRoot, canonicalFile] = await Promise.all([realpath(directory), realpath(filename)]);
+ const relative = path.relative(canonicalRoot, canonicalFile);
+ if (relative.startsWith('..') || path.isAbsolute(relative) || !mime[path.extname(filename)]) {
+ return json(response, 403, { error: 'Forbidden.' });
+ }
+ const data = await readFile(canonicalFile);
+ response.writeHead(200, { 'Content-Type': mime[path.extname(filename)], 'Content-Length': data.length });
+ response.end(request.method === 'HEAD' ? undefined : data);
+ } catch (error) {
+ json(response, error.code === 'ENOENT' || error.code === 'ENOTDIR' ? 404 : 500, { error: 'File unavailable.' });
+ }
+}
+
export function createApp() {
return http.createServer(async (request, response) => {
response.setHeader('X-Content-Type-Options', 'nosniff');
@@ -54,17 +78,33 @@ export function createApp() {
}
if (pathname === '/api/references') {
try {
- const library = JSON.parse(await readFile(new URL('./public/references/catalog.json', import.meta.url), 'utf8'));
+ const catalog = await firstExisting(new URL('./public/references/catalog.json', import.meta.url), new URL('references/catalog.json', showcase));
+ const library = JSON.parse(await readFile(catalog, 'utf8'));
return json(response, 200, { references: curateReferences(library.references || [], referencePolicy) });
}
catch { return json(response, 200, { references: [] }); }
}
+ const audioMatch = pathname.match(/^\/media\/references\/([a-z0-9-]+)\.aac$/);
+ if (audioMatch) {
+ if (Object.hasOwn(referencePolicy.excluded, audioMatch[1])) return json(response, 404, { error: 'Reference removed from this library.' });
+ const id = audioMatch[1];
+ const ready = await firstExisting(localMedia(`${id}.aac`), new URL(`media/${id}.aac`, showcase));
+ if (ready) return streamVideo(request, response, fileURLToPath(ready), 'audio/aac');
+ const video = await firstExisting(localMedia(`${id}.mp4`), new URL(`media/${id}.mp4`, showcase));
+ if (!video) return json(response, 404, { error: 'Audio unavailable.' });
+ await mkdir(localMedia(''), { recursive: true });
+ const audio = fileURLToPath(localMedia(`${id}.aac`));
+ if (!(await extractAudio(fileURLToPath(video), audio))) return json(response, 404, { error: 'Audio unavailable.' });
+ return streamVideo(request, response, audio, 'audio/aac');
+ }
const mediaMatch = pathname.match(/^\/media\/references\/([a-z0-9-]+)\.mp4$/);
if (mediaMatch) {
if (Object.hasOwn(referencePolicy.excluded, mediaMatch[1])) return json(response, 404, { error: 'Reference removed from this library.' });
- return streamVideo(request, response, fileURLToPath(new URL(`./.local-media/${mediaMatch[1]}.mp4`, import.meta.url)));
+ const video = await firstExisting(localMedia(`${mediaMatch[1]}.mp4`), new URL(`media/${mediaMatch[1]}.mp4`, showcase));
+ return streamVideo(request, response, fileURLToPath(video || localMedia(`${mediaMatch[1]}.mp4`)));
}
- if (pathname === '/' || pathname === '/editor') pathname = '/editor.html';
+ if (pathname === '/') pathname = '/demo.html';
+ else if (pathname === '/editor') pathname = '/editor.html';
if (readOnly.has(pathname)) return json(response, 200, readOnly.get(pathname));
const sourceMatch = pathname.match(/^\/api\/v1\/templates\/([^/]+)\/source$/);
if (sourceMatch) {
@@ -77,20 +117,10 @@ export function createApp() {
// Keep the inherited /null/ links working without involving another server.
if (pathname === '/null') pathname = '/';
else if (pathname.startsWith('/null/')) pathname = pathname.slice(5);
- let filename = path.resolve(root, '.' + pathname);
- try {
- if ((await stat(filename)).isDirectory()) filename = path.join(filename, 'index.html');
- const [canonicalRoot, canonicalFile] = await Promise.all([realpath(root), realpath(filename)]);
- const relative = path.relative(canonicalRoot, canonicalFile);
- if (relative.startsWith('..') || path.isAbsolute(relative) || !mime[path.extname(filename)]) {
- return json(response, 403, { error: 'Forbidden.' });
- }
- const data = await readFile(canonicalFile);
- response.writeHead(200, { 'Content-Type': mime[path.extname(filename)], 'Content-Length': data.length });
- response.end(request.method === 'HEAD' ? undefined : data);
- } catch (error) {
- json(response, error.code === 'ENOENT' || error.code === 'ENOTDIR' ? 404 : 500, { error: 'File unavailable.' });
+ if (pathname.startsWith('/references/') && !(await exists(path.resolve(root, '.' + pathname)))) {
+ return serveFile(response, request, fileURLToPath(showcase), pathname);
}
+ return serveFile(response, request, root, pathname);
});
}
diff --git a/showcase/media/227b019e7968.aac b/showcase/media/227b019e7968.aac
new file mode 100644
index 0000000..b23b1af
Binary files /dev/null and b/showcase/media/227b019e7968.aac differ
diff --git a/showcase/media/227b019e7968.mp4 b/showcase/media/227b019e7968.mp4
new file mode 100644
index 0000000..3098be0
Binary files /dev/null and b/showcase/media/227b019e7968.mp4 differ
diff --git a/showcase/media/5db95a3a7c73.aac b/showcase/media/5db95a3a7c73.aac
new file mode 100644
index 0000000..2ed63ed
Binary files /dev/null and b/showcase/media/5db95a3a7c73.aac differ
diff --git a/showcase/media/5db95a3a7c73.mp4 b/showcase/media/5db95a3a7c73.mp4
new file mode 100644
index 0000000..6fe0d9b
Binary files /dev/null and b/showcase/media/5db95a3a7c73.mp4 differ
diff --git a/showcase/media/69614b10fa87.aac b/showcase/media/69614b10fa87.aac
new file mode 100644
index 0000000..964e9ee
Binary files /dev/null and b/showcase/media/69614b10fa87.aac differ
diff --git a/showcase/media/69614b10fa87.mp4 b/showcase/media/69614b10fa87.mp4
new file mode 100644
index 0000000..cb0e6fb
Binary files /dev/null and b/showcase/media/69614b10fa87.mp4 differ
diff --git a/showcase/references/227b019e7968-0.jpg b/showcase/references/227b019e7968-0.jpg
new file mode 100644
index 0000000..2d02a6b
Binary files /dev/null and b/showcase/references/227b019e7968-0.jpg differ
diff --git a/showcase/references/227b019e7968-1.jpg b/showcase/references/227b019e7968-1.jpg
new file mode 100644
index 0000000..fd56e2a
Binary files /dev/null and b/showcase/references/227b019e7968-1.jpg differ
diff --git a/showcase/references/227b019e7968-10.jpg b/showcase/references/227b019e7968-10.jpg
new file mode 100644
index 0000000..f6d3a46
Binary files /dev/null and b/showcase/references/227b019e7968-10.jpg differ
diff --git a/showcase/references/227b019e7968-11.jpg b/showcase/references/227b019e7968-11.jpg
new file mode 100644
index 0000000..c85d185
Binary files /dev/null and b/showcase/references/227b019e7968-11.jpg differ
diff --git a/showcase/references/227b019e7968-12.jpg b/showcase/references/227b019e7968-12.jpg
new file mode 100644
index 0000000..51816de
Binary files /dev/null and b/showcase/references/227b019e7968-12.jpg differ
diff --git a/showcase/references/227b019e7968-13.jpg b/showcase/references/227b019e7968-13.jpg
new file mode 100644
index 0000000..19081ad
Binary files /dev/null and b/showcase/references/227b019e7968-13.jpg differ
diff --git a/showcase/references/227b019e7968-14.jpg b/showcase/references/227b019e7968-14.jpg
new file mode 100644
index 0000000..bc8160c
Binary files /dev/null and b/showcase/references/227b019e7968-14.jpg differ
diff --git a/showcase/references/227b019e7968-2.jpg b/showcase/references/227b019e7968-2.jpg
new file mode 100644
index 0000000..7b5bf77
Binary files /dev/null and b/showcase/references/227b019e7968-2.jpg differ
diff --git a/showcase/references/227b019e7968-3.jpg b/showcase/references/227b019e7968-3.jpg
new file mode 100644
index 0000000..358fe3a
Binary files /dev/null and b/showcase/references/227b019e7968-3.jpg differ
diff --git a/showcase/references/227b019e7968-4.jpg b/showcase/references/227b019e7968-4.jpg
new file mode 100644
index 0000000..1d41a40
Binary files /dev/null and b/showcase/references/227b019e7968-4.jpg differ
diff --git a/showcase/references/227b019e7968-5.jpg b/showcase/references/227b019e7968-5.jpg
new file mode 100644
index 0000000..1ab5829
Binary files /dev/null and b/showcase/references/227b019e7968-5.jpg differ
diff --git a/showcase/references/227b019e7968-6.jpg b/showcase/references/227b019e7968-6.jpg
new file mode 100644
index 0000000..789a92a
Binary files /dev/null and b/showcase/references/227b019e7968-6.jpg differ
diff --git a/showcase/references/227b019e7968-7.jpg b/showcase/references/227b019e7968-7.jpg
new file mode 100644
index 0000000..cf72156
Binary files /dev/null and b/showcase/references/227b019e7968-7.jpg differ
diff --git a/showcase/references/227b019e7968-8.jpg b/showcase/references/227b019e7968-8.jpg
new file mode 100644
index 0000000..f1df01a
Binary files /dev/null and b/showcase/references/227b019e7968-8.jpg differ
diff --git a/showcase/references/227b019e7968-9.jpg b/showcase/references/227b019e7968-9.jpg
new file mode 100644
index 0000000..7ccbb85
Binary files /dev/null and b/showcase/references/227b019e7968-9.jpg differ
diff --git a/showcase/references/5db95a3a7c73-0.jpg b/showcase/references/5db95a3a7c73-0.jpg
new file mode 100644
index 0000000..006eac3
Binary files /dev/null and b/showcase/references/5db95a3a7c73-0.jpg differ
diff --git a/showcase/references/69614b10fa87-0.jpg b/showcase/references/69614b10fa87-0.jpg
new file mode 100644
index 0000000..3cf1ee4
Binary files /dev/null and b/showcase/references/69614b10fa87-0.jpg differ
diff --git a/showcase/references/69614b10fa87-1.jpg b/showcase/references/69614b10fa87-1.jpg
new file mode 100644
index 0000000..6a34b23
Binary files /dev/null and b/showcase/references/69614b10fa87-1.jpg differ
diff --git a/showcase/references/69614b10fa87-2.jpg b/showcase/references/69614b10fa87-2.jpg
new file mode 100644
index 0000000..ad90866
Binary files /dev/null and b/showcase/references/69614b10fa87-2.jpg differ
diff --git a/showcase/references/69614b10fa87-3.jpg b/showcase/references/69614b10fa87-3.jpg
new file mode 100644
index 0000000..1b10f76
Binary files /dev/null and b/showcase/references/69614b10fa87-3.jpg differ
diff --git a/showcase/references/69614b10fa87-4.jpg b/showcase/references/69614b10fa87-4.jpg
new file mode 100644
index 0000000..33aa240
Binary files /dev/null and b/showcase/references/69614b10fa87-4.jpg differ
diff --git a/showcase/references/69614b10fa87-5.jpg b/showcase/references/69614b10fa87-5.jpg
new file mode 100644
index 0000000..f50493d
Binary files /dev/null and b/showcase/references/69614b10fa87-5.jpg differ
diff --git a/showcase/references/69614b10fa87-6.jpg b/showcase/references/69614b10fa87-6.jpg
new file mode 100644
index 0000000..636ef39
Binary files /dev/null and b/showcase/references/69614b10fa87-6.jpg differ
diff --git a/showcase/references/catalog.json b/showcase/references/catalog.json
new file mode 100644
index 0000000..2ec8eb6
--- /dev/null
+++ b/showcase/references/catalog.json
@@ -0,0 +1,198 @@
+{
+ "references": [
+ {
+ "id": "69614b10fa87",
+ "name": "Infinite · Global payments",
+ "duration": 30.058,
+ "width": 1920,
+ "height": 1080,
+ "src": "/media/references/69614b10fa87.mp4",
+ "poster": "/references/69614b10fa87-0.jpg",
+ "segments": [
+ {
+ "ref": "69614b10fa87",
+ "in": 0,
+ "out": 4.294,
+ "part": 1,
+ "poster": "/references/69614b10fa87-0.jpg"
+ },
+ {
+ "ref": "69614b10fa87",
+ "in": 4.294,
+ "out": 8.588,
+ "part": 2,
+ "poster": "/references/69614b10fa87-1.jpg"
+ },
+ {
+ "ref": "69614b10fa87",
+ "in": 8.588,
+ "out": 12.882,
+ "part": 3,
+ "poster": "/references/69614b10fa87-2.jpg"
+ },
+ {
+ "ref": "69614b10fa87",
+ "in": 12.882,
+ "out": 17.176,
+ "part": 4,
+ "poster": "/references/69614b10fa87-3.jpg"
+ },
+ {
+ "ref": "69614b10fa87",
+ "in": 17.176,
+ "out": 21.47,
+ "part": 5,
+ "poster": "/references/69614b10fa87-4.jpg"
+ },
+ {
+ "ref": "69614b10fa87",
+ "in": 21.47,
+ "out": 25.764,
+ "part": 6,
+ "poster": "/references/69614b10fa87-5.jpg"
+ },
+ {
+ "ref": "69614b10fa87",
+ "in": 25.764,
+ "out": 30.058,
+ "part": 7,
+ "poster": "/references/69614b10fa87-6.jpg"
+ }
+ ]
+ },
+ {
+ "id": "227b019e7968",
+ "name": "SaaS · Launch sequence",
+ "duration": 62.997,
+ "width": 1920,
+ "height": 1080,
+ "src": "/media/references/227b019e7968.mp4",
+ "poster": "/references/227b019e7968-0.jpg",
+ "segments": [
+ {
+ "ref": "227b019e7968",
+ "in": 0,
+ "out": 4.2,
+ "part": 1,
+ "poster": "/references/227b019e7968-0.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 4.2,
+ "out": 8.4,
+ "part": 2,
+ "poster": "/references/227b019e7968-1.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 8.4,
+ "out": 12.599,
+ "part": 3,
+ "poster": "/references/227b019e7968-2.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 12.599,
+ "out": 16.799,
+ "part": 4,
+ "poster": "/references/227b019e7968-3.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 16.799,
+ "out": 20.999,
+ "part": 5,
+ "poster": "/references/227b019e7968-4.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 20.999,
+ "out": 25.199,
+ "part": 6,
+ "poster": "/references/227b019e7968-5.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 25.199,
+ "out": 29.399,
+ "part": 7,
+ "poster": "/references/227b019e7968-6.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 29.399,
+ "out": 33.598,
+ "part": 8,
+ "poster": "/references/227b019e7968-7.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 33.598,
+ "out": 37.798,
+ "part": 9,
+ "poster": "/references/227b019e7968-8.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 37.798,
+ "out": 41.998,
+ "part": 10,
+ "poster": "/references/227b019e7968-9.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 41.998,
+ "out": 46.198,
+ "part": 11,
+ "poster": "/references/227b019e7968-10.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 46.198,
+ "out": 50.398,
+ "part": 12,
+ "poster": "/references/227b019e7968-11.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 50.398,
+ "out": 54.597,
+ "part": 13,
+ "poster": "/references/227b019e7968-12.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 54.597,
+ "out": 58.797,
+ "part": 14,
+ "poster": "/references/227b019e7968-13.jpg"
+ },
+ {
+ "ref": "227b019e7968",
+ "in": 58.797,
+ "out": 62.997,
+ "part": 15,
+ "poster": "/references/227b019e7968-14.jpg"
+ }
+ ]
+ },
+ {
+ "id": "5db95a3a7c73",
+ "name": "Motion study 08",
+ "duration": 2.837,
+ "width": 1920,
+ "height": 1080,
+ "src": "/media/references/5db95a3a7c73.mp4",
+ "poster": "/references/5db95a3a7c73-0.jpg",
+ "segments": [
+ {
+ "ref": "5db95a3a7c73",
+ "in": 0,
+ "out": 2.837,
+ "part": 1,
+ "poster": "/references/5db95a3a7c73-0.jpg"
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/showcase/references/cuts.json b/showcase/references/cuts.json
new file mode 100644
index 0000000..9ae851c
--- /dev/null
+++ b/showcase/references/cuts.json
@@ -0,0 +1 @@
+{"69614b10fa87":[6.83,7.77,22.83,23.77],"227b019e7968":[4.78,5.97,5.98,7.7,7.72,9.37,12.73,16.7,18.75,29.65,32.25,33.68,38.95,44.82,47.58,49.35,55.98,59.25,59.27,61.05],"5db95a3a7c73":[1.12]}
\ No newline at end of file
diff --git a/showcase/references/drafts.json b/showcase/references/drafts.json
new file mode 100644
index 0000000..9f4cbf8
--- /dev/null
+++ b/showcase/references/drafts.json
@@ -0,0 +1,299 @@
+{
+ "aliases": {},
+ "drafts": {
+ "69614b10fa87": {
+ "palette": {
+ "bg": "#070708",
+ "fg": "#f2f2f2",
+ "accent": "#43d3c9"
+ },
+ "sections": [
+ {
+ "name": "Hook",
+ "beats": [
+ [
+ "text",
+ "Global payments",
+ {
+ "size": 30,
+ "y": 0.47
+ }
+ ],
+ [
+ "text",
+ "a pain",
+ {
+ "size": 150,
+ "x": 0.58,
+ "y": 0.55
+ }
+ ]
+ ]
+ },
+ {
+ "name": "Coin",
+ "beats": [
+ [
+ "burst"
+ ],
+ [
+ "shape"
+ ]
+ ]
+ },
+ {
+ "name": "Reveal",
+ "beats": [
+ [
+ "logo",
+ "Infinite",
+ {
+ "mark": "∞",
+ "markSize": 60,
+ "size": 40
+ }
+ ],
+ [
+ "hub",
+ "Global"
+ ]
+ ]
+ },
+ {
+ "name": "App",
+ "beats": [
+ [
+ "phone",
+ "Sign Up In Seconds",
+ {
+ "stack": true
+ }
+ ],
+ [
+ "phone",
+ "Send Funds Anywhere",
+ {
+ "stack": true
+ }
+ ]
+ ]
+ },
+ {
+ "name": "Products",
+ "beats": [
+ [
+ "shape",
+ "Dash"
+ ],
+ [
+ "shape",
+ "SDK"
+ ]
+ ]
+ },
+ {
+ "name": "Stablecoins",
+ "beats": [
+ [
+ "text",
+ "Powered by Stablecoins",
+ {
+ "size": 34,
+ "y": 0.2
+ }
+ ]
+ ]
+ },
+ {
+ "name": "End card",
+ "beats": [
+ [
+ "logo",
+ "Infinite",
+ {
+ "mark": "∞",
+ "markSize": 44,
+ "size": 30,
+ "sub": "INFINITE.DEV"
+ }
+ ]
+ ]
+ }
+ ]
+ },
+ "227b019e7968": {
+ "palette": {
+ "bg": "#fbeef3",
+ "fg": "#2a0a19",
+ "accent": "#b3125d"
+ },
+ "sections": [
+ {
+ "name": "Hook",
+ "beats": [
+ [
+ "icons",
+ "",
+ {
+ "bg": "#8c0f4a"
+ }
+ ],
+ [
+ "window",
+ "Newsroom"
+ ]
+ ]
+ },
+ {
+ "name": "Problem",
+ "beats": [
+ [
+ "text",
+ "Try building their",
+ {
+ "size": 30
+ }
+ ],
+ [
+ "notify",
+ "broken tools"
+ ]
+ ]
+ },
+ {
+ "name": "Platform",
+ "beats": [
+ [
+ "burst"
+ ],
+ [
+ "text",
+ "publishing platform."
+ ]
+ ]
+ },
+ {
+ "name": "No code",
+ "beats": [
+ [
+ "phone",
+ "No coding"
+ ],
+ [
+ "cards",
+ "Choose your site"
+ ]
+ ]
+ },
+ {
+ "name": "Launch",
+ "beats": [
+ [
+ "text",
+ "Launch your platform",
+ {
+ "size": 42
+ }
+ ],
+ [
+ "text",
+ "Everything works together",
+ {
+ "size": 40
+ }
+ ]
+ ]
+ },
+ {
+ "name": "Analytics",
+ "beats": [
+ [
+ "window",
+ "Analytics"
+ ],
+ [
+ "chart",
+ "58.6K"
+ ]
+ ]
+ },
+ {
+ "name": "Generate",
+ "beats": [
+ [
+ "text",
+ "Can Generate",
+ {
+ "size": 44,
+ "y": 0.35
+ }
+ ],
+ [
+ "cards",
+ "Social post · AI images"
+ ]
+ ]
+ },
+ {
+ "name": "End card",
+ "beats": [
+ [
+ "shape",
+ "Build your audience.",
+ {
+ "bg": "#5c0930"
+ }
+ ],
+ [
+ "logo",
+ "Newsroom",
+ {
+ "bg": "#5c0930"
+ }
+ ]
+ ]
+ }
+ ]
+ },
+ "5db95a3a7c73": {
+ "palette": {
+ "bg": "#7fd3ea",
+ "fg": "#ffffff",
+ "accent": "#1f2a33"
+ },
+ "sections": [
+ {
+ "name": "Search",
+ "beats": [
+ [
+ "input",
+ "Rajzmotion Motion Exploration",
+ {
+ "bg": "#7fd3ea",
+ "fg": "#1f2a33"
+ }
+ ]
+ ]
+ },
+ {
+ "name": "Profile",
+ "beats": [
+ [
+ "phone",
+ "@rajzmotion"
+ ]
+ ]
+ },
+ {
+ "name": "Follow",
+ "beats": [
+ [
+ "phone",
+ "Motion Designer"
+ ]
+ ]
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/showcase/references/sections.json b/showcase/references/sections.json
new file mode 100644
index 0000000..0a9a542
--- /dev/null
+++ b/showcase/references/sections.json
@@ -0,0 +1,80 @@
+{
+ "69614b10fa87": [
+ {
+ "start": 0,
+ "end": 4.29
+ },
+ {
+ "start": 4.29,
+ "end": 7.77
+ },
+ {
+ "start": 7.77,
+ "end": 12.88
+ },
+ {
+ "start": 12.88,
+ "end": 17.18
+ },
+ {
+ "start": 17.18,
+ "end": 22.83
+ },
+ {
+ "start": 22.83,
+ "end": 25.76
+ },
+ {
+ "start": 25.76,
+ "end": 30.058
+ }
+ ],
+ "227b019e7968": [
+ {
+ "start": 0,
+ "end": 7.72
+ },
+ {
+ "start": 7.72,
+ "end": 16.7
+ },
+ {
+ "start": 16.7,
+ "end": 23.62
+ },
+ {
+ "start": 23.62,
+ "end": 32.25
+ },
+ {
+ "start": 32.25,
+ "end": 38.95
+ },
+ {
+ "start": 38.95,
+ "end": 47.58
+ },
+ {
+ "start": 47.58,
+ "end": 55.98
+ },
+ {
+ "start": 55.98,
+ "end": 62.997
+ }
+ ],
+ "5db95a3a7c73": [
+ {
+ "start": 0,
+ "end": 0.95
+ },
+ {
+ "start": 0.95,
+ "end": 1.89
+ },
+ {
+ "start": 1.89,
+ "end": 2.837
+ }
+ ]
+}
\ No newline at end of file
diff --git a/test/server.test.js b/test/server.test.js
index ad88359..c8b5e30 100644
--- a/test/server.test.js
+++ b/test/server.test.js
@@ -13,6 +13,7 @@ test('public workspace is standalone, read-only, and serves its own previews', a
const home = await get('/');
assert.equal(home.status, 200);
assert.match(await home.text(), /Null.*Launch Studio/);
+ assert.match(await (await get('/editor')).text(), /id="clips-track"/);
assert.match(await (await get('/index.html')).text(), /Template Gallery/);
const catalog = await (await get('/api/v1/templates')).json();
assert.ok(catalog.templates.length > 0);