Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.11.0): audio/video elements + Beat Sync
Ashiq Hussain Mir3a6b343f42cb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0b5f102..aaa522e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,53 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.11.0] — 2026-10-29++The "sound & motion" release: native audio/video elements, a chunked+media store, and Beat Sync. Full design: `research/MEDIA-AND-BEAT-SYNC.md`.++### Audio & video elements+- **Audio** renders as a waveform player card (peaks baked in at upload,+ so every replica draws it without the multi-MB file) with volume,+ loop, "play on page open" and a BPM chip when a tempo was detected.+- **Video** renders its poster frame on the canvas (dataURL, replicates+ through the document) and plays frames in preview/present, with+ volume, mute, loop, autoplay and a trim window.+- **Media store** (migration `0005`): A/V files live in Postgres `bytea`+ behind `/api/media/<id>` — **chunked uploads** (3 MB per PATCH) work+ within every serverless body limit; appends are offset-guarded so+ replayed chunks 409 instead of corrupting the stream; GET is+ Range-aware (206/416) with immutable caching; `CANVIX_MAX_MEDIA_MB`+ (default 32) caps file size; unfinalized uploads GC after 24 h.++### Beat Sync+- Uploading audio analyzes it in-browser (pure DSP, unit-tested):+ onset envelope → mean-centered autocorrelation tempo (60–180 BPM,+ harmonic-checked toward 90–180) → phase-aligned beat grid, capped at+ 480 beats. No grid detected → the feature simply stays hidden.+- Any element gets a **Beat** popover (0–100 % pulse) when its page has+ a beat-carrying audio element; pulses run in preview, presentation+ and video export, composing with entry animations.++### Playback & export+- Preview/present plays page audio, swaps video posters for live+ `<video>` frames, and rAF-drives beat pulses off the audio clock.+- Video export renders media cards + beat pulses and **muxes the page+ audio** (best-effort: needs a MediaRecorder mime with an audio codec;+ otherwise a correct silent video). Honest limitation: exports render+ the video poster, not moving frames.++### Verification+- 285 unit tests (18 new: click tracks at 90/120/140/160 BPM, silence,+ white noise — which caught and fixed a false-tempo autocorrelation+ bias — grid spacing, envelope decay, source selection).+- `scripts/verify-media.ts` — live probe, **19/19 green** against the+ production DB: two-chunk byte-exact round-trip, offset-guard replay+ → 409, finalize guards, Range 206/416, immutable headers, audio+ element save/load round-trip, mime/size/CSRF rejections.+- Offline-merge regression probe still 18/18; Cloudflare 2.14 MB gz /+ Netlify 19.6 MB zip unchanged.+## [0.10.1] — 2026-10-29Production hotfix: the presence P2002 storm + 30-second function hangs.diff --git a/README.md b/README.mdindex c7c7c25..4292323 100644--- a/README.md+++ b/README.md@@ -245,7 +245,14 @@ is right here.is rendered frame-by-frame to an offscreen canvas and encoded locally viaMediaRecorder — **MP4 (H.264)** where the browser can encode it, WebM otherwise.Honest format detection is shown before you export. No uploads, no server- rendering+ rendering. Since **v0.11** the page's audio is muxed into the recording+ (best-effort per browser) and beat-synced pulses render into the video+- **Audio/video elements & Beat Sync** *(v0.11)* — upload MP3/WAV/MP4/WebM+ through the chunked media store (works within every serverless body limit);+ audio renders as a waveform card with the tempo detected in-browser, video+ as a poster frame. Media plays in Preview/Present, and **any element can+ pulse on the music's beats** — in the editor preview, presentation and+ exported video. See `research/MEDIA-AND-BEAT-SYNC.md`- **AI Assistant 2.0** — the assistant is now design-aware: it sees your page'selements, colors, fonts and selection, and answers with **structured, validatedactions** ("move the title to the top", "change all heading colors to purple",@@ -717,7 +724,9 @@ tool descriptions so agents pick the right format.- [x] Yjs-grade offline merge for collaboration — HLC-stamped elementLWW + delete tombstones, persisted offline doc/op-queue (IndexedDB),server-side merge on divergent autosaves *(v0.10.0)*-- [ ] Audio/video elements & Beat Sync+- [x] Audio/video elements & Beat Sync — chunked media store (bytea ++ Range streaming), in-browser tempo/beat analysis, per-element beat+ pulses in preview/present/export *(v0.11.0)*- [ ] Plugin system (external, installable apps)## 🤝 Contributingdiff --git a/package.json b/package.jsonindex 571769d..7acd305 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.10.1",+ "version": "0.11.0","private": false,"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/prisma/migrations/0005_media_store/migration.sql b/prisma/migrations/0005_media_store/migration.sqlnew file mode 100644index 0000000..a112220--- /dev/null+++ b/prisma/migrations/0005_media_store/migration.sql@@ -0,0 +1,21 @@+-- v0.11 — media store for audio/video uploads.+--+-- A/V files are too large for the dataURL-in-element pattern images use;+-- they live here as bytea and elements reference `/api/media/<id>`.+-- Uploads are chunked (serverless body limits), appended via a raw+-- `bytes || chunk` UPDATE, and marked complete by `finalizedAt`.+CREATE TABLE "Media" (+ "id" TEXT NOT NULL,+ "mime" TEXT NOT NULL,+ "size" INTEGER NOT NULL,+ "bytes" BYTEA NOT NULL,+ "ownerId" TEXT,+ "anonKey" TEXT,+ "finalizedAt" TIMESTAMP,+ "createdAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ CONSTRAINT "Media_pkey" PRIMARY KEY ("id")+);++CREATE INDEX "Media_ownerId_idx" ON "Media"("ownerId");+CREATE INDEX "Media_anonKey_idx" ON "Media"("anonKey");+CREATE INDEX "Media_finalizedAt_createdAt_idx" ON "Media"("finalizedAt", "createdAt");diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex cf62dac..0e97922 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -175,6 +175,29 @@ model Comment {@@index([designId, resolved])}+// ── v0.11: media store (audio/video uploads) ─────────────────+// A/V files are far too large for the dataURL-in-element pattern images+// use (multi-MB per autosave). They live here as bytea; elements+// reference them by id (`/api/media/<id>`). Chunks are appended with a+// raw `bytes || chunk` UPDATE (offset-guarded) because serverless body+// limits force chunked uploads. Access mirrors designs: link-accessible+// once the id is known; ownership columns exist for future GC/quota.+model Media {+ id String @id @default(cuid())+ mime String+ size Int+ bytes Bytes+ ownerId String?+ anonKey String?+ // set by finalize — GET 404s until the upload is complete+ finalizedAt DateTime?+ createdAt DateTime @default(now())++ @@index([ownerId])+ @@index([anonKey])+ @@index([finalizedAt, createdAt])+}+// Provider accounting + abuse telemetry for AI routes.model AIUsage {id String @id @default(cuid())diff --git a/research/MEDIA-AND-BEAT-SYNC.md b/research/MEDIA-AND-BEAT-SYNC.mdnew file mode 100644index 0000000..f64875c--- /dev/null+++ b/research/MEDIA-AND-BEAT-SYNC.md@@ -0,0 +1,123 @@+# Canvix v0.11 — Audio/Video elements & Beat Sync++Date: 2026-10-29 · Status: **implemented, unit-verified (285 tests),+live-verified against the production database (19/19 media checks,+18/18 collab checks).**++## What shipped++- **Audio elements** — a native waveform player card on the canvas, a+ media store for the actual file, and playback in preview/present plus+ video export.+- **Video elements** — poster-frame representation on the canvas (what+ every replica and every export renders), frame playback in+ preview/present, trim window, volume/mute/loop.+- **Beat Sync** — audio uploaded to Canvix is analyzed in the browser+ (tempo + beat grid + waveform peaks); any element can pulse on the+ beats, in preview, presentation and video export.++## The design++### Why a media store (not dataURLs like images)++Images embed as dataURLs inside the element — fine for ~100 KB assets,+catastrophic for 4–32 MB audio/video: every autosave PUT would carry the+whole file. A/V lives in a new `Media` table (migration 0005, `bytea`),+and elements reference it by id: `src = /api/media/<id>`.++Chunked upload, because serverless body limits (Vercel 4.5 MB) would+cap files at a useless size:++| Step | Route | Notes |+|---|---|---|+| init | `POST /api/media` `{mime,size}` | 201 → `{id, chunkSize}`; mime must be audio/* or video/*; cap `CANVIX_MAX_MEDIA_MB` (default 32) |+| append | `PATCH /api/media/<id>?offset=n` (raw body) | **offset-guarded** raw SQL `UPDATE … SET bytes = bytes ‖ chunk WHERE octet_length(bytes) = n` — a replayed or racing chunk gets 409 instead of interleaving |+| finalize | `PUT /api/media/<id>` `{expectedSize}` | verifies length; sets `finalizedAt`; GET 404s until then |+| stream | `GET /api/media/<id>` | Range-aware (206/416), immutable cache, `Accept-Ranges` |++Unfinalized uploads are GC'd after 24 h (lazy, on init). Finalized media+has no delete API in v0.11 — deleting a design does not delete its media+(honest limitation: orphans are possible; documented, bounded by the+upload cap).++### Analysis baked into the element++`src/lib/media/beat-detect.ts` (pure DSP, Node-testable) ++`decode.ts` (browser glue):++1. decode via Web Audio → mono, downsampled to 11.025 kHz+2. onset envelope: RMS energy per ~11.6 ms window → positive first+ difference (energy flux)+3. tempo: **mean-centered** autocorrelation over the 60–180 BPM lag+ range (centering is what keeps white noise from false-positive+ tempi — the unit tests caught that), harmonic check preferring+ 90–180 BPM+4. beat grid: phase-aligned to the strongest onset, capped at+ `MAX_BEATS = 480`++The result (`peaks` ≤ 200, `bpm`, `beats`, `duration`) rides the element+— every replica renders the waveform and beat-syncs **without the+multi-MB file**. Sizes respect the collab validator (≤ 500-array,+≤ 256 KB per op).++### Playback model (where media actually plays)++- **Editor canvas**: never — the canvas always shows the poster /+ waveform card (editing stays deterministic; a playing video would+ fight the transformer).+- **Preview / Present** (`preview-stage.tsx`): audio elements with+ "Play on page open" play via DOM `Audio`; video elements swap their+ poster Konva image for a live `<video>` (restored on unmount); the+ first audio with a beat grid drives a rAF loop that scales+ beat-synced elements (`1 + strength × 0.12 × envelope`).+- **Video export** (`video-export.ts`): waveform cards + posters render+ (mirroring the canvas geometry); beat pulses are applied in+ `drawPage` so they compose with entry animations; page audio is+ **muxed into the recording** (best-effort: AudioContext+ MediaStreamDestination + a codec that declares audio, e.g.+ `vp9,opus`; browsers that refuse — autoplay policies — produce a+ correct silent video).++### Beat Sync UX++Any single-selected element gets a "Beat" popover when its page has an+audio element with a detected grid: a 0–100 % pulse strength. The audio+element itself exposes volume / loop / "play on page open" (and BPM+chip); video adds mute + trim start/end. The popover tells the user to+enable autoplay on the audio — pulses run only while the music runs.++## Verification++- **Unit (18 new, 285 total):** synthetic click tracks at 90/120/140/160+ BPM (±2 %), silence → no tempo + flat waveform, white noise → no+ tempo, beat-grid spacing, envelope decay, `beatSourceOf` selection,+ peaks normalization/caps.+- **Live (`scripts/verify-media.ts`, 19 checks, production DB):**+ two-chunk upload with exact byte round-trip, **replayed chunk → 409**+ (the offset guard), pre-finalize 404, wrong-size finalize → 409,+ Range 206 + 416, immutable cache headers, design save/load round-trip+ of a full audio element, mime/size rejections, CSRF. All green; probe+ media cleaned up afterwards.+- **Collab regression:** the offline-merge probe still 18/18 — new+ element types flow through the same stamped ops.+- Cloudflare 2.14 MB gz / Netlify 19.6 MB zip — unchanged.++## Honest limitations (documented, deliberate)++- **Video in exports**: exports render the poster + play affordance ++ beat pulses, not the moving frames (the frame renderer is page-hold+ based; re-timing it around video playback is future work). Audio IS+ muxed (best-effort).+- **Audio muxing is browser-dependent** — requires a MediaRecorder mime+ with an audio codec and a resumable AudioContext; falls back to+ silent video without failing the export.+- **Media has no delete/GC once finalized** — orphaned uploads persist+ until an operator clears them (`DELETE FROM "Media" WHERE …`). The+ 32 MB default cap bounds the damage; a usage view + GC is roadmap+ material.+- **Beat detection is onset-based** — steady percussive music works+ great; ambient/drone/free-tempo material yields no grid (the element+ then simply has no Beat Sync chip, and pulses don't run).+- **One beat clock per page** — the first visible audio element with a+ grid; multiple beat-synced audio files on one page pulse to the+ first.diff --git a/scripts/verify-media.ts b/scripts/verify-media.tsnew file mode 100644index 0000000..54f1191--- /dev/null+++ b/scripts/verify-media.ts@@ -0,0 +1,266 @@+// scripts/verify-media.ts — v0.11 media store live regression probe.+// Point at a RUNNING server; exercises the full chunked-upload lifecycle+// against the real database:+// init → append (multi-chunk) → offset-guard replay → finalize guards+// → full GET (bytes + headers) → Range GET (206) → out-of-range (416)+// → mime/size rejections → CSRF → design roundtrip with an audio element+// Usage: npx tsx scripts/verify-media.ts [BASE_URL] (default localhost:3000)++export {} // module scope — keeps top-level names out of other scripts++const BASE = (process.argv[2] ?? process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '')++let failures = 0+let checks = 0+function pass(label: string, detail: string) {+ checks+++ console.log(` ✓ ${label} — ${detail}`)+}+function fail(label: string, detail: string) {+ failures+++ checks+++ console.error(` ✗ ${label} — ${detail}`)+}++const CHUNK = 3 * 1024 * 1024++/** minimal mono 16-bit PCM WAV (~4 MB → forces two upload chunks) */+function makeWav(): Uint8Array<ArrayBuffer> {+ const sampleRate = 44_100+ const samples = Math.floor((4.2 * 1024 * 1024) / 2)+ const buf = new Uint8Array(44 + samples * 2)+ const dv = new DataView(buf.buffer)+ const w = (off: number, s: string) => {+ for (let i = 0; i < s.length; i++) dv.setUint8(off + i, s.charCodeAt(i))+ }+ w(0, 'RIFF')+ dv.setUint32(4, 36 + samples * 2, true)+ w(8, 'WAVE')+ w(12, 'fmt ')+ dv.setUint32(16, 16, true)+ dv.setUint16(20, 1, true)+ dv.setUint16(22, 1, true)+ dv.setUint32(24, sampleRate, true)+ dv.setUint32(28, sampleRate * 2, true)+ dv.setUint16(32, 2, true)+ dv.setUint16(34, 16, true)+ w(36, 'data')+ dv.setUint32(40, samples * 2, true)+ // 120 BPM click track (not needed by the store, but a realistic payload)+ const period = Math.floor(sampleRate * 0.5)+ for (let i = 0; i < samples; i++) {+ const t = i % period+ const v = t < 400 ? Math.round(Math.exp(-t / 80) * 22000 * (t % 4 < 2 ? 1 : -1)) : 0+ dv.setInt16(44 + i * 2, v, true)+ }+ return buf+}++async function main() {+ console.log(`verify-media → ${BASE}`)+ const wav = makeWav()++ // 1. init+ const init = await fetch(`${BASE}/api/media`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ mime: 'audio/wav', size: wav.length }),+ })+ const initJson = (await init.json().catch(() => null)) as { id?: string; chunkSize?: number } | null+ if (init.status === 201 && initJson?.id) pass('init', `id=${initJson.id.slice(0, 10)}… chunkSize=${initJson.chunkSize}`)+ else return fail('init', `status ${init.status}`)+ const id = initJson!.id!++ try {+ // 2. chunk 1+ const c1 = new Uint8Array(wav.buffer, 0, CHUNK)+ const r1 = await fetch(`${BASE}/api/media/${id}?offset=0`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/octet-stream' },+ body: c1,+ })+ const r1j = (await r1.json().catch(() => null)) as { size?: number } | null+ if (r1.status === 200 && r1j?.size === c1.length) pass('append chunk 1', `${c1.length} bytes stored`)+ else fail('append chunk 1', `status ${r1.status} size=${r1j?.size}`)++ // 3. replaying chunk 1 at the same offset must be rejected (409) —+ // the offset guard is what makes retried chunks safe+ const rr = await fetch(`${BASE}/api/media/${id}?offset=0`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/octet-stream' },+ body: c1,+ })+ if (rr.status === 409) pass('offset guard', 'replayed chunk rejected with 409')+ else fail('offset guard', `status ${rr.status} (duplicate chunk accepted!)`)++ // 4. chunk 2+ const c2 = new Uint8Array(wav.buffer, CHUNK, wav.length - CHUNK)+ const r2 = await fetch(`${BASE}/api/media/${id}?offset=${CHUNK}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/octet-stream' },+ body: c2,+ })+ const r2j = (await r2.json().catch(() => null)) as { size?: number } | null+ if (r2.status === 200 && r2j?.size === wav.length) pass('append chunk 2', `total ${r2j?.size} bytes`)+ else fail('append chunk 2', `status ${r2.status} size=${r2j?.size}`)++ // 5. GET before finalize → 404+ const early = await fetch(`${BASE}/api/media/${id}`)+ if (early.status === 404) pass('pre-finalize GET', '404 until finalized')+ else fail('pre-finalize GET', `status ${early.status}`)++ // 6. finalize with the wrong size → 409+ const badFin = await fetch(`${BASE}/api/media/${id}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ expectedSize: wav.length + 10 }),+ })+ if (badFin.status === 409) pass('finalize guard', 'wrong expectedSize rejected with 409')+ else fail('finalize guard', `status ${badFin.status}`)++ // 7. finalize correctly+ const fin = await fetch(`${BASE}/api/media/${id}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ expectedSize: wav.length }),+ })+ if (fin.status === 200) pass('finalize', 'upload marked complete')+ else fail('finalize', `status ${fin.status}`)++ // 8. full GET — bytes must round-trip exactly+ const got = await fetch(`${BASE}/api/media/${id}`)+ if (got.status !== 200) {+ fail('full GET', `status ${got.status}`)+ } else {+ const buf = new Uint8Array(await got.arrayBuffer())+ const ct = got.headers.get('content-type') ?? ''+ const cl = Number(got.headers.get('content-length') ?? 0)+ const ar = got.headers.get('accept-ranges')+ const cc = got.headers.get('cache-control') ?? ''+ if (buf.length === wav.length) pass('full GET length', `${buf.length} bytes`)+ else fail('full GET length', `${buf.length} (want ${wav.length})`)+ let equal = buf.length === wav.length+ for (let i = 0; equal && i < wav.length; i += 997) if (buf[i] !== wav[i]) equal = false+ if (buf.length === wav.length) {+ for (let i = 0; i < wav.length; i++) if (buf[i] !== wav[i]) { equal = false; break }+ }+ if (equal) pass('full GET bytes', 'content identical (chunked append intact)')+ else fail('full GET bytes', 'content differs from the uploaded file')+ if (ct === 'audio/wav') pass('content-type', ct)+ else fail('content-type', ct)+ if (cl === wav.length) pass('content-length', String(cl))+ else fail('content-length', String(cl))+ if (ar === 'bytes' && cc.includes('immutable')) pass('headers', 'accept-ranges + immutable cache')+ else fail('headers', `accept-ranges=${ar} cache=${cc}`)+ }++ // 9. Range GET → 206 partial+ const range = await fetch(`${BASE}/api/media/${id}`, { headers: { range: 'bytes=100-199' } })+ const rbuf = new Uint8Array(await range.arrayBuffer().catch(() => new ArrayBuffer(0)))+ if (range.status === 206 && rbuf.length === 100) {+ const cr = range.headers.get('content-range') ?? ''+ const matches = rbuf.every((b, i) => b === wav[100 + i])+ if (matches && cr === `bytes 100-199/${wav.length}`) pass('range GET', '206 + correct slice + content-range')+ else fail('range GET', `slice match=${matches} content-range=${cr}`)+ } else fail('range GET', `status ${range.status} len=${rbuf.length}`)++ // 10. out-of-range → 416+ const oor = await fetch(`${BASE}/api/media/${id}`, { headers: { range: `bytes=${wav.length + 5}-` } })+ if (oor.status === 416) pass('range 416', 'out-of-range rejected')+ else fail('range 416', `status ${oor.status}`)++ // 11. design roundtrip — an audio element (peaks/beats/src) survives jsonb+ const created = await fetch(`${BASE}/api/designs`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ name: 'media-probe',+ width: 800,+ height: 600,+ pages: [+ {+ id: 'p1',+ background: { kind: 'solid', color: '#ffffff' },+ elements: [+ {+ id: 'AU1',+ type: 'audio',+ x: 40, y: 40, width: 420, height: 96,+ rotation: 0, opacity: 1, locked: false, visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ src: `/api/media/${id}`,+ name: 'probe-clicks',+ duration: 47.8,+ volume: 0.8,+ loop: false,+ autoplay: true,+ peaks: [0.1, 0.9, 0.2],+ bpm: 120,+ beats: [0.1, 0.6, 1.1],+ },+ ],+ },+ ],+ }),+ })+ if (created.status !== 201) {+ fail('design roundtrip', `create → ${created.status}`)+ } else {+ const d = (await created.json()) as { id: string }+ const got2 = await fetch(`${BASE}/api/designs/${d.id}`)+ const dj = (await got2.json()) as { pages?: Array<{ elements?: Array<Record<string, unknown>> }> }+ const el = dj.pages?.[0]?.elements?.find((e) => e.id === 'AU1')+ if (+ el &&+ el.type === 'audio' &&+ el.src === `/api/media/${id}` &&+ Array.isArray(el.peaks) && Array.isArray(el.beats) && el.bpm === 120+ ) {+ pass('design roundtrip', 'audio element (peaks/beats/bpm/src) survives save + load')+ } else {+ fail('design roundtrip', `element after load: ${JSON.stringify(el).slice(0, 120)}`)+ }+ const del = await fetch(`${BASE}/api/designs/${d.id}?permanent=1`, { method: 'DELETE' })+ if (del.status === 200) pass('probe design cleanup', 'deleted')+ else fail('probe design cleanup', `status ${del.status} (manual: ${d.id})`)+ }+ } finally {+ // media row cleanup via raw SQL is not possible over HTTP — the file+ // stays (bounded, GC'd only if unfinalized). Note it honestly.+ console.log(' (media bytes remain in the store — no delete API by design; unfinalized rows GC after 24 h)')+ }++ // 12. rejections+ const badMime = await fetch(`${BASE}/api/media`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ mime: 'image/png', size: 1000 }),+ })+ if (badMime.status === 415) pass('mime rejection', 'image/png → 415')+ else fail('mime rejection', `status ${badMime.status}`)++ const badSize = await fetch(`${BASE}/api/media`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ mime: 'audio/wav', size: 999 * 1024 * 1024 }),+ })+ if (badSize.status === 413) pass('size rejection', '999 MB → 413')+ else fail('size rejection', `status ${badSize.status}`)++ // 13. CSRF — cross-site mutation rejected+ const csrf = await fetch(`${BASE}/api/media`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Origin: 'https://evil.example' },+ body: JSON.stringify({ mime: 'audio/wav', size: 10 }),+ })+ if (csrf.status === 403) pass('CSRF', 'cross-site init rejected')+ else fail('CSRF', `status ${csrf.status}`)++ console.log(`\n${failures === 0 ? 'ALL GREEN' : 'FAILURES PRESENT'} — ${checks - failures}/${checks} checks passed`)+ process.exit(failures === 0 ? 0 : 1)+}++main().catch((err) => {+ console.error('probe crashed:', err)+ process.exit(1)+})diff --git a/src/app/api/media/[id]/route.ts b/src/app/api/media/[id]/route.tsnew file mode 100644index 0000000..2fb0753--- /dev/null+++ b/src/app/api/media/[id]/route.ts@@ -0,0 +1,133 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'++export const runtime = 'nodejs'+export const maxDuration = 30++// ── v0.11 media store: append / finalize / stream ────────────+// See POST /api/media for the protocol. The append is a single raw SQL+// UPDATE with an offset guard (`octet_length(bytes) = $offset`) so a+// retried or racing chunk can never corrupt the byte stream.++const MAX_CHUNK = 3 * 1024 * 1024 + 64 * 1024 // transport headroom over the client chunk size++/** PATCH /api/media/[id]?offset=<n> — append one chunk (raw body). */+export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ const { id } = await params+ try {+ const offset = Number(req.nextUrl.searchParams.get('offset'))+ if (!Number.isFinite(offset) || offset < 0 || offset > 2 ** 31) {+ return NextResponse.json({ error: 'Bad offset.' }, { status: 400 })+ }+ const chunk = new Uint8Array(await req.arrayBuffer())+ if (!chunk.length) return NextResponse.json({ error: 'Empty chunk.' }, { status: 400 })+ if (chunk.length > MAX_CHUNK) return NextResponse.json({ error: 'Chunk too large.' }, { status: 413 })++ // offset-guarded append: the UPDATE only lands when the stored length+ // matches — a replayed/racing chunk is rejected instead of interleaved+ const updated = await db.$executeRawUnsafe(+ `UPDATE "Media" SET bytes = bytes || $1 WHERE id = $2 AND "finalizedAt" IS NULL AND octet_length(bytes) = $3`,+ Buffer.from(chunk),+ id,+ Math.round(offset),+ )+ if (updated === 0) {+ return NextResponse.json({ error: 'Offset mismatch — restart the upload.' }, { status: 409 })+ }+ const len = await db.$queryRawUnsafe<{ len: number }[]>(+ `SELECT octet_length(bytes)::int AS len FROM "Media" WHERE id = $1`,+ id,+ )+ return NextResponse.json({ size: len[0]?.len ?? offset + chunk.length })+ } catch (error) {+ console.error('[media/append] failed', error)+ return NextResponse.json({ error: 'Could not store the chunk.' }, { status: 500 })+ }+}++/** PUT /api/media/[id] — finalize: verify length, mark complete. */+export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ const { id } = await params+ try {+ const body = (await req.json().catch(() => ({}))) as { expectedSize?: unknown }+ const expected = Number(body.expectedSize)+ if (!Number.isFinite(expected) || expected <= 0) {+ return NextResponse.json({ error: 'Bad expectedSize.' }, { status: 400 })+ }+ const rows = await db.$queryRawUnsafe<{ len: number }[]>(+ `SELECT octet_length(bytes)::int AS len FROM "Media" WHERE id = $1 AND "finalizedAt" IS NULL`,+ id,+ )+ if (!rows.length) return NextResponse.json({ error: 'Not found or already finalized.' }, { status: 404 })+ if (rows[0].len !== Math.round(expected)) {+ return NextResponse.json(+ { error: `Upload incomplete (${rows[0].len}/${Math.round(expected)} bytes).` },+ { status: 409 },+ )+ }+ await db.media.update({ where: { id }, data: { finalizedAt: new Date() } })+ return NextResponse.json({ id })+ } catch (error) {+ console.error('[media/finalize] failed', error)+ return NextResponse.json({ error: 'Could not finalize the upload.' }, { status: 500 })+ }+}++/** GET /api/media/[id] — stream the bytes (Range-aware for <audio>/<video>+ * seeking). Finalized media only; immutable content-addressed by id. */+export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params+ try {+ const rows = await db.$queryRawUnsafe<{ bytes: Buffer; mime: string }[]>(+ `SELECT bytes, mime FROM "Media" WHERE id = $1 AND "finalizedAt" IS NOT NULL`,+ id,+ )+ if (!rows.length) return new Response('Not found', { status: 404 })+ const buf = rows[0].bytes+ const mime = rows[0].mime || 'application/octet-stream'+ const total = buf.length++ const range = req.headers.get('range')+ if (range) {+ const m = /bytes=(\d*)-(\d*)/.exec(range)+ if (m) {+ const start = m[1] ? Number(m[1]) : 0+ const end = m[2] ? Math.min(Number(m[2]), total - 1) : total - 1+ if (Number.isFinite(start) && start <= end && start < total) {+ const slice = buf.subarray(start, end + 1)+ return new Response(new Uint8Array(slice), {+ status: 206,+ headers: {+ 'Content-Type': mime,+ 'Content-Length': String(slice.length),+ 'Content-Range': `bytes ${start}-${end}/${total}`,+ 'Accept-Ranges': 'bytes',+ 'Cache-Control': 'public, max-age=31536000, immutable',+ },+ })+ }+ }+ // malformed / out-of-range → 416 per RFC+ return new Response(null, {+ status: 416,+ headers: { 'Content-Range': `bytes */${total}` },+ })+ }++ return new Response(new Uint8Array(buf), {+ status: 200,+ headers: {+ 'Content-Type': mime,+ 'Content-Length': String(total),+ 'Accept-Ranges': 'bytes',+ 'Cache-Control': 'public, max-age=31536000, immutable',+ },+ })+ } catch (error) {+ console.error('[media/get] failed', error)+ return new Response('Media unavailable', { status: 500 })+ }+}diff --git a/src/app/api/media/route.ts b/src/app/api/media/route.tsnew file mode 100644index 0000000..f38c702--- /dev/null+++ b/src/app/api/media/route.ts@@ -0,0 +1,68 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'+import { getSessionUser } from '@/lib/auth/session'+import { anonKeyHash, newAnonToken, readAnonToken, setAnonCookie } from '@/lib/auth/anon'++export const runtime = 'nodejs'+export const maxDuration = 30++// ── v0.11 media store: upload init ───────────────────────────+// Serverless body limits (Vercel 4.5 MB) force chunked uploads:+// POST /api/media { mime, size, name? } → 201 { id, chunkSize }+// PATCH /api/media/<id>?off= raw chunk bytes → 200 { size }+// PUT /api/media/<id> { expectedSize } → 200 { id }+// GET /api/media/<id> stream (Range-aware) → 200/206++/** default cap: 32 MB per file (audio usually ≤ 8 MB, video ≤ 32 MB) */+const MAX_MEDIA_MB = Math.max(1, Number(process.env.CANVIX_MAX_MEDIA_MB ?? 32))++const ALLOWED_PREFIXES = ['audio/', 'video/']++export async function POST(req: NextRequest) {+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ try {+ const body = (await req.json().catch(() => ({}))) as { mime?: unknown; size?: unknown }+ const mime = typeof body.mime === 'string' ? body.mime.slice(0, 100) : ''+ const size = Number(body.size)++ if (!ALLOWED_PREFIXES.some((p) => mime.startsWith(p))) {+ return NextResponse.json({ error: 'Only audio and video files are supported.' }, { status: 415 })+ }+ if (!Number.isFinite(size) || size <= 0 || size > MAX_MEDIA_MB * 1024 * 1024) {+ return NextResponse.json(+ { error: `File must be between 1 byte and ${MAX_MEDIA_MB} MB.` },+ { status: 413 },+ )+ }++ // ownership stamping mirrors designs: account id or anon cookie hash+ const user = await getSessionUser(req)+ const token = readAnonToken(req) ?? newAnonToken()+ const ownerId = user?.id ?? null+ const anonKey = user ? null : anonKeyHash(token)++ // lazy GC: abandoned (never finalized) uploads die after 24 h+ await db.media+ .deleteMany({ where: { finalizedAt: null, createdAt: { lt: new Date(Date.now() - 86_400_000) } } })+ .catch(() => { /* GC is best-effort */ })++ const media = await db.media.create({+ data: {+ mime,+ size: Math.round(size),+ bytes: new Uint8Array(0),+ ownerId,+ anonKey,+ },+ select: { id: true },+ })++ const res = NextResponse.json({ id: media.id, chunkSize: 3 * 1024 * 1024 }, { status: 201 })+ if (!user) setAnonCookie(res, token)+ return res+ } catch (error) {+ console.error('[media/init] failed', error)+ return NextResponse.json({ error: 'Could not start the upload.' }, { status: 500 })+ }+}diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex 47f4282..8e0d2bc 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -9,11 +9,13 @@ import {AlignHorizontalJustifyStart, AlignHorizontalJustifyCenter, AlignHorizontalJustifyEnd,FlipHorizontal, FlipVertical, Sun, Contrast, Palette, RotateCcw, Replace, Lock, LockOpen,Layers, SquareDashed, Crop, Spline, Table2, Rows3, Columns3, Trash, Upload, ExternalLink,+ Music, Film, Play, Repeat, Volume2, VolumeX, SlidersHorizontal, Activity,} from 'lucide-react'import { useEditorStore, selectedElements, currentPageData } from '@/store/editor-store'-import type { EmbedElement, FrameElement, ImageElement, LineElement, ShapeElement, StickerElement, TableElement, TextElement, AnyElement, FrameShape } from '@/lib/types'+import type { AudioElement, EmbedElement, FrameElement, ImageElement, LineElement, ShapeElement, StickerElement, TableElement, TextElement, VideoElement, AnyElement, FrameShape } from '@/lib/types'import { FRAME_SHAPES, isGroup } from '@/lib/types'import { TEXT_EFFECTS } from '@/lib/types'+import { beatSourceOf } from '@/lib/media/beat-detect'import { cn } from '@/lib/utils'import { FontDropdown } from './toolbar/FontDropdown'import { ColorMenu } from './toolbar/ColorMenu'@@ -61,6 +63,10 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'mconst table = first.type === 'table' ? (first as TableElement) : nullconst frame = first.type === 'frame' ? (first as FrameElement) : nullconst embed = first.type === 'embed' ? (first as EmbedElement) : null+ const audio = first.type === 'audio' ? (first as AudioElement) : null+ const video = first.type === 'video' ? (first as VideoElement) : null+ // v0.11: the page's beat grid — powers the Beat Sync popover below+ const beatSource = beatSourceOf(currentPageData(state))const canGroup = isMulticonst canUngroup = sel.some((e) => isGroup(e))@@ -382,11 +388,155 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm<Divider /><PositionPopover ids={ids} count={1} element={first} /></>+ ) : audio ? (+ <>+ <span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5">+ <Music size={13} /> Audio+ </span>+ <MediaToolbar+ ids={ids}+ volume={audio.volume}+ loop={audio.loop}+ autoplay={audio.autoplay}+ muted={false}+ onMuted={undefined}+ duration={audio.duration}+ trim={undefined}+ />+ {audio.bpm ? (+ <span className="text-[11px] font-semibold text-[#02C0CC] bg-[#02C0CC]/10 border border-[#02C0CC]/25 rounded-full px-2 py-0.5 shrink-0 tabular-nums" title="Detected tempo (Beat Sync grid)">+ {Math.round(audio.bpm)} BPM+ </span>+ ) : null}+ <Divider />+ <PositionPopover ids={ids} count={1} element={first} />+ </>+ ) : video ? (+ <>+ <span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5">+ <Film size={13} /> Video+ </span>+ <MediaToolbar+ ids={ids}+ volume={video.volume}+ loop={video.loop}+ autoplay={video.autoplay}+ muted={video.muted}+ onMuted={(v) => update(ids, { muted: v })}+ duration={video.duration}+ trim={{ start: video.trimStart, end: video.trimEnd }}+ />+ <Divider />+ <PositionPopover ids={ids} count={1} element={first} />+ </>) : null}++ {/* ── v0.11: Beat Sync — available on any single-selected element ── */}+ {!isMulti && beatSource && (+ <>+ <Divider />+ <BeatSyncPopover el={first} ids={ids} bpm={beatSource.bpm} />+ </>+ )}</div>)}+// ── v0.11: media + beat sync toolbars ──────────────────────++function MediaToolbar({+ ids,+ volume,+ loop,+ autoplay,+ muted,+ onMuted,+ duration,+ trim,+}: {+ ids: string[]+ volume: number+ loop: boolean+ autoplay: boolean+ muted: boolean+ onMuted?: (v: boolean) => void+ duration: number+ trim?: { start: number; end: number }+}) {+ const update = useEditorStore((s) => s.updateElements)+ const updateLive = useEditorStore((s) => s.updateElementsLive)+ return (+ <ToolbarPopover+ width={264}+ trigger={(open) => (+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Media settings" title="Media settings">+ <SlidersHorizontal size={14} /> <span className="text-[12px] hidden lg:inline">Media</span>+ </button>+ )}+ >+ <SliderRow label="Volume" value={Math.round(volume * 100)} min={0} max={100} step={1}+ onChange={(v) => updateLive(ids, { volume: v / 100 })}+ onCommit={() => update(ids, { volume })}+ format={(v) => `${v}%`} />+ <div className="flex gap-1.5 mt-1">+ <TBtn onClick={() => update(ids, { loop: !loop })} dataActive={loop} title="Loop" ariaLabel="Loop">+ <Repeat size={14} />+ </TBtn>+ <TBtn onClick={() => update(ids, { autoplay: !autoplay })} dataActive={autoplay} title="Play when the page appears (Preview / Present / video export)" ariaLabel="Play on page open">+ <Play size={14} />+ </TBtn>+ {onMuted ? (+ <TBtn onClick={() => onMuted(!muted)} dataActive={muted} title="Mute" ariaLabel="Mute">+ {muted ? <VolumeX size={14} /> : <Volume2 size={14} />}+ </TBtn>+ ) : null}+ </div>+ {trim && Number.isFinite(duration) && duration > 0.2 ? (+ <div className="mt-2 border-t border-white/[0.08] pt-2">+ <SliderRow label="Trim start" value={Number(trim.start.toFixed(1))} min={0} max={Math.max(0.1, duration - 0.1)} step={0.1}+ onChange={(v) => updateLive(ids, { trimStart: Math.min(v, trim.end - 0.1) })}+ onCommit={() => update(ids, { trimStart: trim.start })}+ format={(v) => `${v.toFixed(1)}s`} />+ <SliderRow label="Trim end" value={Number(trim.end.toFixed(1))} min={0.1} max={duration} step={0.1}+ onChange={(v) => updateLive(ids, { trimEnd: Math.max(v, trim.start + 0.1) })}+ onCommit={() => update(ids, { trimEnd: trim.end })}+ format={(v) => `${v.toFixed(1)}s`} />+ </div>+ ) : null}+ <p className="text-[10px] text-white/40 leading-relaxed mt-2">+ Media plays in Preview / Present mode and in exported video (audio muxing is best-effort per browser).+ </p>+ </ToolbarPopover>+ )+}++function BeatSyncPopover({ el, ids, bpm }: { el: AnyElement; ids: string[]; bpm: number }) {+ const update = useEditorStore((s) => s.updateElements)+ const updateLive = useEditorStore((s) => s.updateElementsLive)+ const strength = Math.round((el.beatPulse ?? 0) * 100)+ return (+ <ToolbarPopover+ width={252}+ trigger={(open) => (+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open || strength > 0} aria-label="Beat Sync" title="Beat Sync — pulse this element on the music's beats">+ <Activity size={14} /> <span className="text-[12px] hidden lg:inline">Beat{strength > 0 ? ` ${strength}%` : ''}</span>+ </button>+ )}+ >+ <div className="text-[10px] font-semibold text-white/45 uppercase tracking-wide mb-1.5">+ Beat Sync · {Math.round(bpm)} BPM+ </div>+ <SliderRow label="Pulse" value={strength} min={0} max={100} step={1}+ onChange={(v) => updateLive(ids, { beatPulse: v / 100 })}+ onCommit={() => update(ids, { beatPulse: (el.beatPulse ?? 0) })}+ format={(v) => (v === 0 ? 'off' : `+${(v * 0.12).toFixed(2)}× scale`)} />+ <p className="text-[10px] text-white/40 leading-relaxed mt-2">+ The element scales on every beat of the page's audio (Preview, Present and video export). Enable “Play on page open” on the audio element so the music runs with it.+ </p>+ </ToolbarPopover>+ )+}+// ── v0.6: table / frame / embed toolbars ──────────────────────function TableToolbar({ table, ids }: { table: TableElement; ids: string[] }) {diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.tsindex f50793a..c9a43d1 100644--- a/src/components/editor/add-element.ts+++ b/src/components/editor/add-element.ts@@ -329,3 +329,57 @@ export function addImageAt(src: string, naturalWidth: number, naturalHeight: num}))}++// ── v0.11: audio/video elements ──────────────────────────────++/**+ * Upload an audio file to the media store, analyze it (waveform peaks ++ * BPM + beat grid — all baked into the element so every replica renders+ * and beat-syncs without the multi-MB file), and add it to the canvas.+ * onProgress reports upload chunks (0..1).+ */+export async function addAudioFromFile(+ file: File,+ onProgress?: (ratio: number) => void,+): Promise<void> {+ const { uploadMediaFile, mediaSrc } = await import('@/lib/media/media-client')+ const { analyzeAudioFile } = await import('@/lib/media/decode')+ const { createAudioElement } = await import('@/lib/types')+ const [handle, analysis] = await Promise.all([uploadMediaFile(file, onProgress), analyzeAudioFile(file)])+ const store = useEditorStore.getState()+ const w = Math.min(520, Math.max(360, store.width * 0.55))+ const pos = placement(w, 96, store.pages[store.currentPage].elements.length)+ store.addElement(+ createAudioElement(mediaSrc(handle.id), file.name.replace(/\.[^.]+$/, '').slice(0, 60), analysis.duration, {+ ...pos,+ width: Math.round(w),+ height: 96,+ peaks: analysis.peaks,+ bpm: analysis.bpm,+ beats: analysis.beats,+ })+ )+}++/** Upload a video file, capture its poster frame, and add it to the canvas. */+export async function addVideoFromFile(+ file: File,+ onProgress?: (ratio: number) => void,+): Promise<void> {+ const { uploadMediaFile, mediaSrc } = await import('@/lib/media/media-client')+ const { probeVideoFile } = await import('@/lib/media/decode')+ const { createVideoElement } = await import('@/lib/types')+ const [handle, probe] = await Promise.all([uploadMediaFile(file, onProgress), probeVideoFile(file)])+ const store = useEditorStore.getState()+ const maxW = store.width * 0.7+ const w = Math.round(Math.min(maxW, Math.max(200, probe.naturalWidth || 480)))+ const h = Math.round(probe.naturalWidth ? (w * probe.naturalHeight) / probe.naturalWidth : w * 0.5625)+ const pos = placement(w, h, store.pages[store.currentPage].elements.length)+ store.addElement(+ createVideoElement(mediaSrc(handle.id), probe.poster, probe.duration, probe.naturalWidth, probe.naturalHeight, {+ ...pos,+ width: w,+ height: h,+ })+ )+}diff --git a/src/components/editor/canvas/element-node.tsx b/src/components/editor/canvas/element-node.tsxindex 51cff28..9890ea0 100644--- a/src/components/editor/canvas/element-node.tsx+++ b/src/components/editor/canvas/element-node.tsx@@ -6,6 +6,7 @@ import { Ellipse, Group, Image as KonvaImage, Line, Path, Rect, Star, Text } froimport type { KonvaEventObject } from 'konva/lib/Node'import type {AnyElement,+ AudioElement,EmbedElement,FrameElement,GroupElement,@@ -16,6 +17,7 @@ import type {StrokeElement,TableElement,TextElement,+ VideoElement,} from '@/lib/types'import { isLine, withAlpha, type GradientFill } from '@/lib/types'import { elementGradientProps } from '@/lib/editor-utils'@@ -126,6 +128,131 @@ function ImageNode({ el, common }: { el: ImageElement; common: Record<string, un)}+/** v0.11: audio — waveform player card. Pure vector: dark rounded card,+ * peak bars from the baked-in analysis (so every replica renders it+ * without the multi-MB file), a play glyph, the name, duration and a+ * Beat Sync chip when a grid was detected. Playback happens in+ * preview/present (see preview-stage.tsx), never in the editor canvas. */+function AudioNode({ el, common }: { el: AudioElement; common: Record<string, unknown> }) {+ const peaks = el.peaks && el.peaks.length ? el.peaks : null+ const barCount = peaks ? Math.min(peaks.length, Math.max(24, Math.floor(el.width / 6))) : 48+ const bars: number[] = []+ if (peaks) {+ for (let i = 0; i < barCount; i++) {+ bars.push(peaks[Math.floor((i / barCount) * peaks.length)] ?? 0)+ }+ }+ const barW = 3+ const gap = peaks ? Math.max(1.5, (el.width - 116 - barCount * barW) / Math.max(1, barCount - 1)) : 4+ const midY = el.height / 2++ return (+ <Group {...common} clip={undefined}>+ <Rect width={el.width} height={el.height} cornerRadius={14} fill="#1B1D27" stroke="#FFFFFF22" strokeWidth={1} />+ {/* play glyph */}+ <Path+ x={18}+ y={midY - 13}+ data="M13 0 L26 13 L13 26 Z"+ fill="#02C0CC"+ />+ {/* waveform */}+ {bars.length > 0 ? (+ bars.map((v, i) => {+ const h = Math.max(2, v * (el.height - 34))+ return (+ <Rect+ key={i}+ x={116 + i * (barW + gap)}+ y={midY - h / 2}+ width={barW}+ height={h}+ cornerRadius={1.5}+ fill="#7BE8E1"+ opacity={0.35 + 0.65 * v}+ />+ )+ })+ ) : (+ <Text x={116} y={midY - 8} text="♪" fontSize={20} fill="#7BE8E1" />+ )}+ {/* label + duration */}+ <Text+ x={18}+ y={el.height - 20}+ text={el.name.slice(0, 42)}+ fontSize={11}+ fontFamily="Inter, system-ui, sans-serif"+ fill="#FFFFFF99"+ width={el.width - 36}+ ellipsis+ />+ <Text+ x={el.width - 62}+ y={10}+ text={formatDuration(el.duration)}+ fontSize={11}+ fontFamily="Inter, system-ui, sans-serif"+ fill="#FFFFFF66"+ />+ {el.bpm ? (+ <Group x={el.width - 62} y={el.height - 21}>+ <Rect width={50} height={14} cornerRadius={7} fill="#02C0CC26" />+ <Text x={4} y={2.5} text={`${Math.round(el.bpm)} BPM`} fontSize={9} fontFamily="Inter, system-ui, sans-serif" fill="#02C0CC" />+ </Group>+ ) : null}+ </Group>+ )+}++/** v0.11: video — poster frame + play affordance + duration chip. The+ * poster is a dataURL captured at upload, so it renders identically on+ * every replica and in exports. Frame playback runs in preview/present. */+function VideoNode({ el, common }: { el: VideoElement; common: Record<string, unknown> }) {+ const image = useLoadedImage(el.poster)+ const isTrimmed = el.trimStart > 0.05 || el.trimEnd < el.duration - 0.05+ return (+ <Group {...common} clip={undefined}>+ <Rect width={el.width} height={el.height} cornerRadius={12} fill="#101218" />+ <KonvaImage+ image={image ?? undefined}+ x={0}+ y={0}+ width={el.width}+ height={el.height}+ cornerRadius={12}+ crop={undefined}+ />+ {/* play affordance */}+ <Group x={el.width / 2 - 24} y={el.height / 2 - 24} opacity={0.92}>+ <Ellipse radiusX={24} radiusY={24} fill="#000000AA" />+ <Path x={24 - 8} y={24 - 10} data="M0 0 L16 10 L0 20 Z" fill="#FFFFFF" />+ </Group>+ <Text+ x={el.width - 62}+ y={10}+ text={formatDuration(el.duration)}+ fontSize={11}+ fontFamily="Inter, system-ui, sans-serif"+ fill="#FFFFFFCC"+ />+ {isTrimmed && (+ <Group x={12} y={10}>+ <Rect width={44} height={14} cornerRadius={7} fill="#FFB84C26" />+ <Text x={5} y={2.5} text="TRIM" fontSize={9} fontFamily="Inter, system-ui, sans-serif" fill="#FFB84C" />+ </Group>+ )}+ </Group>+ )+}++function formatDuration(sec: number): string {+ if (!Number.isFinite(sec) || sec <= 0) return '0:00'+ const m = Math.floor(sec / 60)+ const s = Math.floor(sec % 60)+ return `${m}:${String(s).padStart(2, '0')}`+}+function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerNode, onDragMoveNode, onDragEndNode, onDoubleClick, nested }: ElementNodeProps) {// v0.7 rendering performance: this component no longer subscribes to the// editor store. Store actions are read at event time via getState(), and@@ -478,6 +605,16 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerNreturn <ImageNode el={im} common={common} />}+ case 'audio': {+ const au = el as AudioElement+ return <AudioNode el={au} common={common} />+ }++ case 'video': {+ const vd = el as VideoElement+ return <VideoNode el={vd} common={common} />+ }+case 'table': {const tb = el as TableElementreturn (diff --git a/src/components/editor/canvas/preview-stage.tsx b/src/components/editor/canvas/preview-stage.tsxindex 48262e1..15ce7ea 100644--- a/src/components/editor/canvas/preview-stage.tsx+++ b/src/components/editor/canvas/preview-stage.tsx@@ -3,9 +3,10 @@import { useEffect, useRef, useState } from 'react'import type Konva from 'konva'import { Layer, Rect, Stage } from 'react-konva'-import type { PageData } from '@/lib/types'+import type { AudioElement, PageData, VideoElement } from '@/lib/types'import { gradientProps } from '@/lib/editor-utils'import { animateElementAt, pageAnimationDuration } from '@/lib/animations'+import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'import { PreviewElements } from './element-node'interface PreviewStageProps {@@ -130,6 +131,131 @@ export default function PreviewStage({ page, designWidth, designHeight, animated}}, [page, hasAnimations, reduceMotion, playKey, designWidth, designHeight])+ // ── v0.11: media playback — audio elements, video frames, Beat Sync ──+ // Presentation/preview is where media plays (the editor canvas always+ // shows the poster/waveform representation). Audio drives the beat clock:+ // pulses run only while the beat-source audio is actually playing.+ useEffect(() => {+ const layer = layerRef.current+ if (!layer || !animated) return++ const cleanups: Array<() => void> = []+ const clamp01 = (v: number) => Math.min(1, Math.max(0, Number.isFinite(v) ? v : 0))++ // 1. audio: play every autoplay audio element; the first one with a+ // beat grid becomes the Beat Sync clock+ let beatAudio: HTMLAudioElement | null = null+ for (const el of page.elements as PageData['elements']) {+ if (el.type !== 'audio' || el.visible === false || !el.autoplay) continue+ const a = el as AudioElement+ const audio = new Audio(a.src)+ audio.volume = clamp01(a.volume)+ audio.loop = a.loop+ void audio.play().catch(() => { /* autoplay policy — stays silent */ })+ cleanups.push(() => {+ audio.pause()+ audio.removeAttribute('src')+ })+ if (!beatAudio && a.beats?.length) beatAudio = audio+ }++ // 2. video: swap the poster Konva image for a live <video> + redraw+ const videos: Array<{ v: HTMLVideoElement; node: Konva.Image; prev: CanvasImageSource | undefined; trimEnd: number; loop: boolean }> = []+ if (!reduceMotion) {+ for (const el of page.elements as PageData['elements']) {+ if (el.type !== 'video' || el.visible === false || !el.autoplay) continue+ const vd = el as VideoElement+ const node = layer.findOne<Konva.Image>(`#${vd.id}`)+ if (!node || typeof node.image !== 'function') continue+ const v = document.createElement('video')+ v.src = vd.src+ v.loop = vd.loop+ v.muted = vd.muted+ v.volume = clamp01(vd.volume)+ v.playsInline = true+ const prev = node.image() as CanvasImageSource | undefined+ const onCanPlay = () => {+ try {+ v.currentTime = vd.trimStart+ } catch {+ /* seek not ready */+ }+ void v.play().catch(() => { /* autoplay policy — poster stays */ })+ }+ v.addEventListener('canplay', onCanPlay)+ node.image(v)+ videos.push({ v, node, prev, trimEnd: vd.trimEnd, loop: vd.loop })+ cleanups.push(() => {+ v.removeEventListener('canplay', onCanPlay)+ v.pause()+ v.removeAttribute('src')+ v.load()+ node.image(prev ?? undefined)+ })+ }+ }++ // 3. beat pulses + continuous video redraw+ const beatTargets = (page.elements as PageData['elements']).filter(+ (e) => (e.beatPulse ?? 0) > 0 && e.visible !== false,+ )+ const beats = beatSourceOf(page)?.beats+ const bases = new Map<string, { x: number; y: number; scaleX: number; scaleY: number; offsetX: number; offsetY: number }>()+ for (const el of beatTargets) {+ const node = layer.findOne(`#${el.id}`)+ if (!node) continue+ bases.set(el.id, { x: node.x(), y: node.y(), scaleX: node.scaleX(), scaleY: node.scaleY(), offsetX: node.offsetX(), offsetY: node.offsetY() })+ }++ const restoreBeatTargets = () => {+ for (const el of beatTargets) {+ const node = layer.findOne(`#${el.id}`)+ const base = bases.get(el.id)+ if (node && base) {+ node.x(base.x)+ node.y(base.y)+ node.scaleX(base.scaleX)+ node.scaleY(base.scaleY)+ node.offsetX(base.offsetX)+ node.offsetY(base.offsetY)+ }+ }+ layer.batchDraw()+ }++ if (videos.length > 0 || (beatTargets.length > 0 && beatAudio && beats && !reduceMotion)) {+ let raf = 0+ const tick = () => {+ for (const { v, node, trimEnd, loop } of videos) {+ if (!loop && trimEnd < v.duration && v.currentTime >= trimEnd) v.pause()+ node.getLayer()?.batchDraw()+ }+ if (beatAudio && beats) {+ const t = beatAudio.currentTime+ for (const el of beatTargets) {+ const node = layer.findOne(`#${el.id}`)+ const base = bases.get(el.id)+ if (!node || !base) continue+ const pulse = 1 + (el.beatPulse ?? 0) * 0.12 * beatEnvelopeAt(beats, t)+ node.scaleX(base.scaleX * pulse)+ node.scaleY(base.scaleY * pulse)+ node.x(base.x)+ node.y(base.y)+ }+ layer.batchDraw()+ }+ raf = requestAnimationFrame(tick)+ }+ raf = requestAnimationFrame(tick)+ cleanups.push(() => cancelAnimationFrame(raf))+ }++ return () => {+ for (const fn of cleanups) fn()+ restoreBeatTargets()+ }+ }, [page, animated, reduceMotion, playKey])+return (<div ref={containerRef} className="w-full h-full overflow-hidden" data-testid="preview-stage">{scale > 0 && (diff --git a/src/components/editor/panels/UploadsPanel.tsx b/src/components/editor/panels/UploadsPanel.tsxindex b949757..ecbf675 100644--- a/src/components/editor/panels/UploadsPanel.tsx+++ b/src/components/editor/panels/UploadsPanel.tsx@@ -1,8 +1,8 @@'use client'import { useRef, useState } from 'react'-import { Upload, Trash2, ImageIcon, Replace, Wallpaper } from 'lucide-react'-import { addImageFromFile, addImageFromSrc, readImageFile, replaceSelectedImage } from '../add-element'+import { Upload, Trash2, ImageIcon, Replace, Wallpaper, Music, Film, Loader2 } from 'lucide-react'+import { addImageFromFile, addImageFromSrc, readImageFile, replaceSelectedImage, addAudioFromFile, addVideoFromFile } from '../add-element'import { createImageElement } from '@/lib/types'import { useEditorStore } from '@/store/editor-store'import { toast } from '@/hooks/use-toast'@@ -17,9 +17,19 @@ interface UploadItem {const uploadGallery: { items: UploadItem[] } = { items: [] }+/** v0.11: in-flight media uploads (audio/video) shown with progress */+interface MediaUpload {+ key: string+ name: string+ kind: 'audio' | 'video'+ ratio: number+ failed?: boolean+}+export function UploadsPanel() {const fileRef = useRef<HTMLInputElement>(null)const [, force] = useState(0)+ const [mediaUploads, setMediaUploads] = useState<MediaUpload[]>([])const selectedIds = useEditorStore((s) => s.selectedIds)const pages = useEditorStore((s) => s.pages)const currentPage = useEditorStore((s) => s.currentPage)@@ -30,7 +40,12 @@ export function UploadsPanel() {const handleFiles = async (files: FileList | null) => {if (!files?.length) returnlet ok = 0+ const media: File[] = []for (const file of Array.from(files)) {+ if (file.type.startsWith('audio/') || file.type.startsWith('video/')) {+ media.push(file)+ continue+ }try {const { src, w, h } = await readImageFile(file)uploadGallery.items.unshift({ src, w, h })@@ -40,9 +55,30 @@ export function UploadsPanel() {// ignore this file}}- if (ok === 0) toast({ title: 'Could not upload images', variant: 'destructive' })- else toast({ title: `${ok} image${ok > 1 ? 's' : ''} uploaded` })- force((n) => n + 1)+ if (ok > 0) toast({ title: `${ok} image${ok > 1 ? 's' : ''} uploaded` })++ // v0.11: audio/video → media store (chunked) + analysis, with progress+ for (const file of media) {+ const kind: 'audio' | 'video' = file.type.startsWith('audio/') ? 'audio' : 'video'+ const key = `${file.name}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`+ setMediaUploads((prev) => [...prev, { key, name: file.name, kind, ratio: 0 }])+ try {+ const add = kind === 'audio' ? addAudioFromFile : addVideoFromFile+ await add(file, (ratio) => {+ setMediaUploads((prev) => prev.map((u) => (u.key === key ? { ...u, ratio } : u)))+ })+ toast({ title: kind === 'audio' ? 'Audio added — open Preview to play it' : 'Video added — open Preview to play it' })+ } catch (err) {+ setMediaUploads((prev) => prev.map((u) => (u.key === key ? { ...u, failed: true } : u)))+ toast({+ title: `Could not upload ${kind}`,+ description: err instanceof Error ? err.message.slice(0, 140) : undefined,+ variant: 'destructive',+ })+ } finally {+ setTimeout(() => setMediaUploads((prev) => prev.filter((u) => u.key !== key)), 30_000)+ }+ }}const applyGalleryItem = (item: UploadItem) => {@@ -101,16 +137,16 @@ export function UploadsPanel() {<buttononClick={() => fileRef.current?.click()}className="w-full rounded-xl border-2 border-dashed border-white/15 hover:border-[#7630D7] hover:bg-[#7630D7]/10 transition-all py-8 flex flex-col items-center gap-2 text-white/50"- aria-label="Upload images"+ aria-label="Upload images and media"><Upload size={22} />- <span className="text-sm font-medium text-white/80">Click or drag images here</span>- <span className="text-xs">PNG, JPG, SVG, GIF — or drop straight onto the canvas</span>+ <span className="text-sm font-medium text-white/80">Click or drag files here</span>+ <span className="text-xs">PNG, JPG, SVG, GIF — plus MP3/WAV audio & MP4/WebM video</span></button><inputref={fileRef}type="file"- accept="image/*"+ accept="image/*,audio/*,video/*"multipleclassName="hidden"onChange={(e) => {@@ -120,6 +156,46 @@ export function UploadsPanel() {aria-label="File upload"/>+ {mediaUploads.length > 0 && (+ <div className="mt-4 flex flex-col gap-2">+ <h4 className="text-xs font-semibold text-white/50">Media uploads</h4>+ {mediaUploads.map((u) => (+ <div+ key={u.key}+ className={cn(+ 'rounded-lg border px-3 py-2.5 flex items-center gap-2.5',+ u.failed ? 'border-red-500/40 bg-red-500/10' : 'border-white/10 bg-white/[0.04]',+ )}+ >+ {u.failed ? (+ <Film size={16} className="text-red-400 shrink-0" />+ ) : (+ <Loader2 size={16} className="text-[#02C0CC] shrink-0 animate-spin" />+ )}+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5">+ {u.kind === 'audio' ? <Music size={11} className="text-white/50 shrink-0" /> : null}+ <span className="text-xs truncate text-white/80">{u.name}</span>+ {u.failed ? <span className="text-[10px] font-semibold text-red-400 shrink-0">failed</span> : null}+ </div>+ {!u.failed && (+ <div className="mt-1.5 h-1 rounded-full bg-white/10 overflow-hidden">+ <div+ className="h-full rounded-full bg-[#02C0CC] transition-all"+ style={{ width: `${Math.round(Math.max(0.04, u.ratio) * 100)}%` }}+ />+ </div>+ )}+ </div>+ {!u.failed && <span className="text-[10px] text-white/40 shrink-0 tabular-nums">{Math.round(u.ratio * 100)}%</span>}+ </div>+ ))}+ <p className="text-[11px] text-white/35 leading-relaxed">+ Audio is analyzed for tempo & beats (Beat Sync). Media plays in Preview / Present mode.+ </p>+ </div>+ )}+{uploadGallery.items.length > 0 ? (<><div className="flex items-center justify-between mt-6 mb-2">diff --git a/src/lib/media/beat-detect.test.ts b/src/lib/media/beat-detect.test.tsnew file mode 100644index 0000000..cc883eb--- /dev/null+++ b/src/lib/media/beat-detect.test.ts@@ -0,0 +1,176 @@+// beat-detect tests — synthetic signals with KNOWN tempi, so the DSP is+// verified without any audio fixture (pure Float32Array in, numbers out).+import { describe, expect, it } from 'vitest'+import {+ ANALYSIS_RATE,+ analyzeMono,+ beatEnvelopeAt,+ beatGrid,+ beatSourceOf,+ computePeaks,+ detectBpm,+} from './beat-detect'++/** clicks: short exponential-decay bursts at `bpm` for `seconds`, with a+ * touch of noise so the signal is not mathematically perfect. */+function clickTrack(bpm: number, seconds: number, clickMs = 12): Float32Array {+ const n = Math.floor(seconds * ANALYSIS_RATE)+ const out = new Float32Array(n)+ const period = 60 / bpm+ const clickLen = Math.floor((clickMs / 1000) * ANALYSIS_RATE)+ let t = 0+ let next = 0.1 // first click at 100 ms+ for (let i = 0; i < n; i++) {+ t = i / ANALYSIS_RATE+ if (t >= next) {+ for (let j = 0; j < clickLen && i + j < n; j++) {+ out[i + j] += Math.exp(-j / (clickLen / 5)) * (j % 2 === 0 ? 1 : -1)+ }+ next += period+ }+ out[i] += (Math.random() - 0.5) * 0.01+ }+ return out+}++function onsetOf(samples: Float32Array): Float32Array {+ // reuse the module's internals through analyzeMono's public path+ const win = Math.max(1, Math.round(ANALYSIS_RATE / 86))+ const n = Math.floor(samples.length / win)+ const env = new Float32Array(n)+ for (let i = 0; i < n; i++) {+ let sum = 0+ for (let j = 0; j < win; j++) {+ const v = samples[i * win + j]+ sum += v * v+ }+ env[i] = Math.sqrt(sum / win)+ }+ const out = new Float32Array(Math.max(0, env.length - 1))+ for (let i = 1; i < env.length; i++) {+ const d = env[i] - env[i - 1]+ out[i - 1] = d > 0 ? d : 0+ }+ return out+}++describe('computePeaks', () => {+ it('normalizes to 0..1 with the max at 1', () => {+ const samples = new Float32Array([0, 0.5, -0.25, 0.1, 0, 0, 0, 0])+ const peaks = computePeaks(samples, 4)+ expect(peaks).toHaveLength(4)+ expect(Math.max(...peaks)).toBeCloseTo(1, 2)+ expect(peaks.every((p) => p >= 0 && p <= 1)).toBe(true)+ })++ it('returns empty for empty input', () => {+ expect(computePeaks(new Float32Array(0))).toEqual([])+ })++ it('caps the bucket count at MAX_PEAKS', () => {+ const samples = new Float32Array(ANALYSIS_RATE * 60) // a minute+ expect(computePeaks(samples).length).toBeLessThanOrEqual(200)+ })+})++describe('detectBpm', () => {+ it.each([+ { bpm: 120, label: '120 (2 Hz)' },+ { bpm: 90, label: '90' },+ { bpm: 140, label: '140' },+ { bpm: 160, label: '160' },+ ])('detects a click track at $label', ({ bpm }) => {+ const track = clickTrack(bpm, 12)+ const got = detectBpm(onsetOf(track), ANALYSIS_RATE / Math.max(1, Math.round(ANALYSIS_RATE / 86)))+ expect(got).toBeDefined()+ // within ±2% or exactly half/double (the felt-tempo ambiguity is+ // resolved toward 90–180; all four test tempi live in that band)+ expect(got!).toBeGreaterThan(bpm * 0.98)+ expect(got!).toBeLessThan(bpm * 1.02)+ })++ it('returns undefined for near-silence', () => {+ const silence = new Float32Array(ANALYSIS_RATE * 6).fill(0.0001)+ expect(detectBpm(onsetOf(silence), ANALYSIS_RATE / Math.max(1, Math.round(ANALYSIS_RATE / 86)))).toBeUndefined()+ })++ it('returns undefined for white noise (no periodicity)', () => {+ const noise = new Float32Array(ANALYSIS_RATE * 8)+ for (let i = 0; i < noise.length; i++) noise[i] = Math.random() * 2 - 1+ expect(detectBpm(onsetOf(noise), ANALYSIS_RATE / Math.max(1, Math.round(ANALYSIS_RATE / 86)))).toBeUndefined()+ })+})++describe('beatGrid', () => {+ it('spans the duration with ~period spacing', () => {+ const bpm = 120+ const beats = beatGrid(bpm, onsetOf(clickTrack(bpm, 10)), ANALYSIS_RATE / Math.max(1, Math.round(ANALYSIS_RATE / 86)), 10)+ expect(beats.length).toBeGreaterThan(10)+ const gaps = beats.slice(1).map((b, i) => b - beats[i])+ const avg = gaps.reduce((a, b) => a + b, 0) / gaps.length+ expect(avg).toBeCloseTo(0.5, 2) // 60/120+ })++ it('is empty without a tempo', () => {+ expect(beatGrid(undefined, new Float32Array(0), 86, 10)).toEqual([])+ })+})++describe('analyzeMono (end-to-end on synthetic audio)', () => {+ it('produces peaks, tempo and a beat grid for a 120 BPM track', () => {+ const a = analyzeMono(clickTrack(120, 12), ANALYSIS_RATE)+ expect(a.duration).toBeCloseTo(12, 1)+ expect(a.peaks.length).toBeGreaterThan(50)+ expect(a.bpm).toBeDefined()+ expect(Math.abs(a.bpm! - 120)).toBeLessThan(2.5)+ expect(a.beats?.length).toBeGreaterThan(20)+ if (a.beats) {+ for (const b of a.beats) expect(b).toBeGreaterThanOrEqual(0)+ }+ })++ it('renders silence as a flat (all-zero) waveform, no tempo', () => {+ const a = analyzeMono(new Float32Array(ANALYSIS_RATE * 8), ANALYSIS_RATE, 8)+ expect(a.bpm).toBeUndefined()+ expect(a.beats).toBeUndefined()+ expect(a.peaks.length).toBeGreaterThan(0)+ expect(a.peaks.every((p) => p === 0)).toBe(true)+ })+})++describe('beatEnvelopeAt', () => {+ const beats = [0, 0.5, 1, 1.5]++ it('peaks exactly on a beat', () => {+ expect(beatEnvelopeAt(beats, 0.5)).toBeCloseTo(1, 3)+ })++ it('decays after a beat and hits 0 before the first beat', () => {+ const v = beatEnvelopeAt(beats, 0.57)+ expect(v).toBeGreaterThan(0)+ expect(v).toBeLessThan(1)+ expect(beatEnvelopeAt(beats, -0.1)).toBe(0)+ })++ it('returns 0 with no grid', () => {+ expect(beatEnvelopeAt([], 1)).toBe(0)+ })+})++describe('beatSourceOf', () => {+ it('finds the first visible audio element carrying a grid', () => {+ const page = {+ elements: [+ { type: 'text', id: 't', visible: true },+ { type: 'audio', id: 'a', visible: true, bpm: 128, beats: [0, 0.46] },+ ],+ }+ expect(beatSourceOf(page)?.bpm).toBe(128)+ })++ it('skips hidden or grid-less audio elements', () => {+ expect(beatSourceOf({ elements: [{ type: 'audio', id: 'a', visible: false, bpm: 100, beats: [0] }] })).toBeNull()+ expect(beatSourceOf({ elements: [{ type: 'audio', id: 'a', visible: true, bpm: undefined }] })).toBeNull()+ expect(beatSourceOf({ elements: [] })).toBeNull()+ })+})diff --git a/src/lib/media/beat-detect.ts b/src/lib/media/beat-detect.tsnew file mode 100644index 0000000..47f43d1--- /dev/null+++ b/src/lib/media/beat-detect.ts@@ -0,0 +1,236 @@+// ─────────────────────────────────────────────────────────────+// beat-detect — tempo + beat-grid extraction (v0.11 Beat Sync)+//+// Pure DSP on a mono Float32Array (the browser glue that decodes an+// AudioBuffer lives in decode.ts — everything here is testable in Node).+//+// Pipeline (classic onset/beat induction, kept deliberately small):+// 1. onset envelope: RMS energy per short window, then the positive+// first difference (energy flux) — percussive events stand out+// 2. tempo: autocorrelate the envelope over the 60–180 BPM lag range;+// pick the strongest lag, then harmonic-check (prefer 90–180 BPM by+// comparing the half-tempo and double-tempo candidates)+// 3. beat grid: phase = the envelope peak nearest the strongest beat+// period; beats at phase + k·period, clipped to duration+//+// Everything is capped to the element-friendly sizes the collab op+// validator accepts (MAX_PEAKS / MAX_BEATS in lib/types.ts).+// ─────────────────────────────────────────────────────────────++import { MAX_BEATS, MAX_PEAKS } from '@/lib/types'++/** analysis sample rate — 11.025 kHz is plenty for onset detection and+ * keeps even a 5-minute track at ~3.3M samples */+export const ANALYSIS_RATE = 11_025++export interface BeatAnalysis {+ /** abs-peak envelope, 0..1, at most MAX_PEAKS buckets */+ peaks: number[]+ /** detected tempo — undefined when no stable beat was found */+ bpm?: number+ /** beat grid (seconds), at most MAX_BEATS entries */+ beats?: number[]+ duration: number+}++/** Downsampled abs-peak envelope for the waveform card. */+export function computePeaks(samples: Float32Array, buckets = MAX_PEAKS): number[] {+ if (!samples.length) return []+ const out: number[] = []+ // ceil guarantees at most `buckets` buckets (floor can spill one)+ const bucketSize = Math.max(1, Math.ceil(samples.length / buckets))+ let max = 0+ for (let i = 0; i < samples.length; i += bucketSize) {+ let peak = 0+ const end = Math.min(i + bucketSize, samples.length)+ for (let j = i; j < end; j++) {+ const a = Math.abs(samples[j])+ if (a > peak) peak = a+ }+ out.push(peak)+ if (peak > max) max = peak+ }+ if (max > 0) for (let i = 0; i < out.length; i++) out[i] = Math.round((out[i] / max) * 1000) / 1000+ return out+}++/** RMS energy per window (window = win samples). */+function energyEnvelope(samples: Float32Array, win: number): Float32Array {+ const n = Math.floor(samples.length / win)+ const env = new Float32Array(n)+ for (let i = 0; i < n; i++) {+ let sum = 0+ const base = i * win+ for (let j = 0; j < win; j++) {+ const v = samples[base + j]+ sum += v * v+ }+ env[i] = Math.sqrt(sum / win)+ }+ return env+}++/** positive first difference (energy flux) — the onset envelope. */+function onsetEnvelope(env: Float32Array): Float32Array {+ const out = new Float32Array(Math.max(0, env.length - 1))+ for (let i = 1; i < env.length; i++) {+ const d = env[i] - env[i - 1]+ out[i - 1] = d > 0 ? d : 0+ }+ return out+}++/** autocorrelation score for one lag (in frames), normalized. */+function autocorr(envelope: Float32Array, lag: number): number {+ if (lag <= 0 || lag >= envelope.length) return 0+ let dot = 0+ let na = 0+ let nb = 0+ for (let i = lag; i < envelope.length; i++) {+ dot += envelope[i] * envelope[i - lag]+ na += envelope[i] * envelope[i]+ nb += envelope[i - lag] * envelope[i - lag]+ }+ if (na === 0 || nb === 0) return 0+ return dot / Math.sqrt(na * nb)+}++/**+ * Detect tempo (BPM) of an onset envelope sampled at `fps` frames/sec.+ * Returns undefined when nothing is periodic enough (silence, noise).+ */+export function detectBpm(onsets: Float32Array, fps: number): number | undefined {+ if (onsets.length < fps * 2) return undefined // < 2 s of audio+ const minBpm = 60+ const maxBpm = 180+ const maxLag = Math.floor((fps * 60) / minBpm)+ const minLag = Math.max(2, Math.floor((fps * 60) / maxBpm))+ if (minLag >= maxLag || maxLag >= onsets.length) return undefined++ // mean-center first: onset flux is non-negative, so its raw autocorrelation+ // has a positive baseline that white noise rides (a false-tempo source the+ // v0.11 tests caught). Centered, uncorrelated signals score ~0.+ let mean = 0+ for (let i = 0; i < onsets.length; i++) mean += onsets[i]+ mean /= onsets.length+ const centered = new Float32Array(onsets.length)+ for (let i = 0; i < onsets.length; i++) centered[i] = onsets[i] - mean++ let bestLag = 0+ let bestScore = 0+ for (let lag = minLag; lag <= maxLag; lag++) {+ const s = autocorr(centered, lag)+ if (s > bestScore) {+ bestScore = s+ bestLag = lag+ }+ }+ if (!bestLag || bestScore < 0.12) return undefined++ // harmonic check: the raw winner may be a double/half of the felt tempo.+ // prefer the candidate in 90–180 BPM; fall back to the raw winner.+ const bpmOf = (lag: number) => (fps * 60) / lag+ const raw = bpmOf(bestLag)+ const half = bpmOf(bestLag * 2)+ const dbl = bpmOf(Math.max(1, Math.round(bestLag / 2)))+ const inPreferred = (b: number) => b >= 90 && b <= 180+ if (!inPreferred(raw)) {+ if (inPreferred(half) && half >= minBpm) {+ bestLag *= 2+ } else if (inPreferred(dbl) && dbl <= maxBpm) {+ bestLag = Math.max(1, Math.round(bestLag / 2))+ }+ }+ const bpm = bpmOf(bestLag)+ return Math.round(bpm * 10) / 10+}++/**+ * Beat grid from a tempo + onset envelope: phase-align to the strongest+ * onset, then emit beats every period until duration. Empty when the+ * tempo is unknown or the grid would be pure guesswork.+ */+export function beatGrid(bpm: number | undefined, onsets: Float32Array, fps: number, duration: number): number[] {+ if (!bpm || !Number.isFinite(bpm) || bpm <= 0 || duration <= 0) return []+ const period = 60 / bpm+ // phase = onset frame with the maximum envelope value+ let peakFrame = -1+ let peakVal = 0+ for (let i = 0; i < onsets.length; i++) {+ if (onsets[i] > peakVal) {+ peakVal = onsets[i]+ peakFrame = i+ }+ }+ const phase = peakFrame >= 0 ? (peakFrame / fps) % period : 0+ const beats: number[] = []+ for (let t = phase; t <= duration && beats.length < MAX_BEATS; t += period) {+ beats.push(Math.round(t * 1000) / 1000)+ }+ return beats+}++/**+ * Full analysis of a mono signal at `sampleRate`.+ * Pure — decode.ts is the only place that touches Web Audio.+ */+export function analyzeMono(samples: Float32Array, sampleRate: number, duration?: number): BeatAnalysis {+ const dur = duration ?? samples.length / sampleRate+ const peaks = computePeaks(samples)+ const win = Math.max(1, Math.round(sampleRate / 86)) // ~11.6 ms windows → ~86 fps+ const fps = sampleRate / win+ const env = energyEnvelope(samples, win)+ const onsets = onsetEnvelope(env)+ const bpm = detectBpm(onsets, fps)+ const beats = beatGrid(bpm, onsets, fps, dur)+ return {+ peaks,+ bpm: bpm && beats.length >= 4 ? bpm : undefined,+ beats: beats.length >= 4 ? beats : undefined,+ duration: dur,+ }+}++// ── Beat Sync playback helpers (pure, shared by preview + export) ──++/** Find the audio element a page's Beat Sync pulses follow: the first+ * visible audio element with a beat grid (autoplay preference ignored —+ * the user may mute it but still want the grid). */+export function beatSourceOf(page: { elements: unknown[] }): {+ beats: number[]+ bpm: number+} | null {+ for (const el of page.elements as Array<{ type?: string; visible?: boolean; beats?: number[]; bpm?: number }>) {+ if (el?.type === 'audio' && el.visible !== false && Array.isArray(el.beats) && el.beats.length && el.bpm) {+ return { beats: el.beats, bpm: el.bpm }+ }+ }+ return null+}++/**+ * Beat envelope at time `t`: 1 at each beat, decaying to ~0 midway to the+ * next. Used by preview playback and video export to scale beat-synced+ * elements: `scale = 1 + strength * beatEnvelopeAt(...)`.+ */+export function beatEnvelopeAt(beats: number[], t: number, decay = 0.14): number {+ if (!beats.length) return 0+ // binary search the last beat <= t+ let lo = 0+ let hi = beats.length - 1+ let idx = -1+ while (lo <= hi) {+ const mid = (lo + hi) >> 1+ if (beats[mid] <= t) {+ idx = mid+ lo = mid + 1+ } else {+ hi = mid - 1+ }+ }+ if (idx < 0) return 0+ const dt = t - beats[idx]+ const nextGap = idx + 1 < beats.length ? beats[idx + 1] - beats[idx] : 0.5+ if (dt >= nextGap) return 0+ return Math.exp(-dt / decay)+}diff --git a/src/lib/media/decode.ts b/src/lib/media/decode.tsnew file mode 100644index 0000000..ab0e708--- /dev/null+++ b/src/lib/media/decode.ts@@ -0,0 +1,92 @@+// ─────────────────────────────────────────────────────────────+// decode — browser glue for beat-detect (v0.11).+//+// Turns a media File into (a) the analysis Beat Sync needs and (b) a+// poster frame for video. All heavy lifting is pure (beat-detect.ts);+// this file only touches Web Audio / DOM media APIs.+// ─────────────────────────────────────────────────────────────++import { ANALYSIS_RATE, analyzeMono, type BeatAnalysis } from './beat-detect'++/** Decode an audio file and run the beat analysis (mono, downsampled). */+export async function analyzeAudioFile(file: File | Blob): Promise<BeatAnalysis> {+ const arrayBuffer = await file.arrayBuffer()+ const Ctx: typeof AudioContext =+ window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext+ const ctx = new Ctx()+ try {+ const buffer = await ctx.decodeAudioData(arrayBuffer)+ // downmix to mono+ const mono = new Float32Array(buffer.length)+ for (let ch = 0; ch < buffer.numberOfChannels; ch++) {+ const data = buffer.getChannelData(ch)+ for (let i = 0; i < buffer.length; i++) mono[i] += data[i] / buffer.numberOfChannels+ }+ // downsample to ANALYSIS_RATE (linear pick — fine for onset work)+ const ratio = buffer.sampleRate / ANALYSIS_RATE+ const n = Math.floor(mono.length / ratio)+ const down = new Float32Array(Math.max(1, n))+ for (let i = 0; i < n; i++) down[i] = mono[Math.floor(i * ratio)]+ return analyzeMono(down, ANALYSIS_RATE, buffer.duration)+ } finally {+ void ctx.close().catch(() => {})+ }+}++export interface VideoProbe {+ duration: number+ naturalWidth: number+ naturalHeight: number+ /** JPEG dataURL captured near the first frame */+ poster: string+}++/**+ * Probe a video file: duration, dimensions, and a poster frame (seeked to+ * ~10% or 0.5 s, whichever is smaller — trailers often fade in from black+ * at t=0). The poster is a JPEG dataURL so it rides the document (jsonb)+ * and replicates through collab without touching the media store.+ */+export function probeVideoFile(file: File): Promise<VideoProbe> {+ return new Promise((resolve, reject) => {+ const url = URL.createObjectURL(file)+ const video = document.createElement('video')+ video.preload = 'metadata'+ video.muted = true+ video.playsInline = true+ const cleanup = () => URL.revokeObjectURL(url)+ const fail = (err: Error) => {+ cleanup()+ reject(err)+ }+ video.onloadedmetadata = () => {+ const duration = Number.isFinite(video.duration) ? video.duration : 0+ const seekTo = Math.min(0.5, duration * 0.1)+ const capture = () => {+ try {+ const w = video.videoWidth || 640+ const h = video.videoHeight || 360+ const canvas = document.createElement('canvas')+ const scale = Math.min(1, 640 / Math.max(w, h))+ canvas.width = Math.max(2, Math.round(w * scale))+ canvas.height = Math.max(2, Math.round(h * scale))+ canvas.getContext('2d')?.drawImage(video, 0, 0, canvas.width, canvas.height)+ const poster = canvas.toDataURL('image/jpeg', 0.72)+ cleanup()+ resolve({ duration, naturalWidth: w, naturalHeight: h, poster })+ } catch (err) {+ fail(err instanceof Error ? err : new Error('poster capture failed'))+ }+ }+ // some browsers need canplay before seek/capture works+ video.onseeked = capture+ try {+ video.currentTime = seekTo+ } catch {+ capture()+ }+ }+ video.onerror = () => fail(new Error('Could not read this video file.'))+ video.src = url+ })+}diff --git a/src/lib/media/media-client.ts b/src/lib/media/media-client.tsnew file mode 100644index 0000000..909ff58--- /dev/null+++ b/src/lib/media/media-client.ts@@ -0,0 +1,77 @@+// ─────────────────────────────────────────────────────────────+// media-client — chunked upload to the media store (v0.11).+//+// Serverless platforms cap request bodies (Vercel: 4.5 MB), so uploads+// are chunked: POST /api/media (init) → PATCH append (offset-guarded,+// resumable) → PUT finalize. 3 MB chunks keep every platform happy.+// ─────────────────────────────────────────────────────────────++export const CHUNK_SIZE = 3 * 1024 * 1024++export interface UploadHandle {+ id: string+ size: number+ mime: string+}++async function jsonFetch(url: string, init: RequestInit): Promise<{ status: number; json: any }> {+ const res = await fetch(url, init)+ let json: any = null+ try {+ json = await res.json()+ } catch {+ /* non-JSON error body */+ }+ return { status: res.status, json }+}++/** Upload a media file in chunks; onProgress reports 0..1. */+export async function uploadMediaFile(+ file: File,+ onProgress?: (ratio: number) => void,+): Promise<UploadHandle> {+ const init = await jsonFetch('/api/media', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ mime: file.type || 'application/octet-stream', size: file.size, name: file.name }),+ })+ if (init.status !== 201 || !init.json?.id) {+ throw new Error(init.json?.error ?? `Upload rejected (${init.status})`)+ }+ const id = init.json.id as string++ let offset = 0+ while (offset < file.size) {+ const chunk = file.slice(offset, Math.min(offset + CHUNK_SIZE, file.size))+ const res = await fetch(`/api/media/${id}?offset=${offset}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/octet-stream' },+ body: chunk,+ })+ if (res.status !== 200) {+ let msg = `chunk failed (${res.status})`+ try {+ msg = (await res.json())?.error ?? msg+ } catch {+ /* keep default */+ }+ throw new Error(msg)+ }+ offset += chunk.size+ onProgress?.(Math.min(1, offset / Math.max(1, file.size)))+ }++ const fin = await jsonFetch(`/api/media/${id}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ expectedSize: file.size }),+ })+ if (fin.status !== 200) throw new Error(fin.json?.error ?? 'Finalize failed')++ return { id, size: file.size, mime: file.type || 'application/octet-stream' }+}++/** The element-facing src for a media id (same-origin, immutable cache). */+export function mediaSrc(id: string): string {+ return `/api/media/${id}`+}diff --git a/src/lib/types.ts b/src/lib/types.tsindex c195e6b..9489973 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -17,6 +17,8 @@ export type ElementType =| 'table'| 'frame'| 'embed'+ | 'audio'+ | 'video'export type TextAlign = 'left' | 'center' | 'right' | 'justify'@@ -99,6 +101,10 @@ export interface BaseElement {name?: string/** v0.5: entry animation (undefined = none) */animation?: ElementAnimation+ /** v0.11 Beat Sync: pulse strength on the page audio's beats+ * (0..1, undefined/0 = off). Applied in preview/present playback and+ * video export — see src/lib/media/beat-detect.ts. */+ beatPulse?: number/** v0.10 offline-merge: hybrid-logical-clock stamp of the last write to* this element ("w:counter:actor"). Older documents lack it — treated as* epoch "0" so stamped writes deterministically win over legacy state.@@ -263,6 +269,62 @@ export interface EmbedElement extends BaseElement {tint: string}+// ── v0.11: audio/video elements + Beat Sync ──────────────────++/** Hard caps keeping collab ops + saved documents small: the waveform and+ * beat grid are downsampled on upload (src/lib/media/beat-detect.ts) and+ * clipped here — a full-resolution analysis would blow MAX_EVENT_BYTES. */+export const MAX_PEAKS = 200+export const MAX_BEATS = 480++/** Native audio element — renders as a waveform player card on the canvas+ * (poster-free), and plays during presentation/preview + video export.+ * `src` points at the media store (`/api/media/<id>`) or a CORS https URL.+ * Beats/waveform are baked in at upload so every replica renders + syncs+ * without re-decoding the (multi-MB) file. */+export interface AudioElement extends BaseElement {+ type: 'audio'+ src: string+ /** file label shown on the card */+ name: string+ /** seconds */+ duration: number+ /** 0..1 */+ volume: number+ loop: boolean+ /** start playing when the page appears (presentation/export) */+ autoplay: boolean+ /** downsampled abs-peak envelope (0..1) for the waveform card */+ peaks?: number[]+ /** detected tempo — undefined when analysis found no stable beat */+ bpm?: number+ /** beat grid in seconds (aligned to the strongest onset) */+ beats?: number[]+}++/** Native video element — the editor renders the poster frame (captured at+ * upload, stored as a dataURL so it replicates through the document);+ * playback runs in presentation/preview. Honest scope for v0.11: video+ * exports render the poster + beat pulses; the video itself is not+ * re-rendered into exports (documented in research/MEDIA-AND-BEAT-SYNC.md). */+export interface VideoElement extends BaseElement {+ type: 'video'+ src: string+ /** first-frame thumbnail (dataURL) — the canvas + export representation */+ poster: string+ /** seconds */+ duration: number+ /** 0..1 */+ volume: number+ muted: boolean+ loop: boolean+ /** start playing when the page appears (presentation) */+ autoplay: boolean+ /** playback window (seconds into the source) */+ trimStart: number+ trimEnd: number+}+/** Brand kit — persisted per browser (localStorage) */export interface BrandKit {colors: string[]@@ -297,6 +359,8 @@ export type AnyElement =| TableElement| FrameElement| EmbedElement+ | AudioElement+ | VideoElementexport type Background =| { type: 'solid'; color: string }@@ -600,6 +664,55 @@ export function detectEmbedKind(url: string): EmbedKind {}}+/** v0.11: audio factory — media-store src + the analysis baked in at upload. */+export function createAudioElement(+ src: string,+ name: string,+ duration: number,+ init: BaseInit & Partial<AudioElement> = {}+): AudioElement {+ return {+ ...baseElement('audio', { width: 420, height: 96, ...init }),+ type: 'audio',+ src,+ name,+ duration,+ volume: 0.8,+ loop: false,+ autoplay: false,+ ...init,+ }+}++/** v0.11: video factory — poster dataURL captured at upload. */+export function createVideoElement(+ src: string,+ poster: string,+ duration: number,+ naturalWidth: number,+ naturalHeight: number,+ init: BaseInit & Partial<VideoElement> = {}+): VideoElement {+ const width = init.width ?? Math.min(560, naturalWidth || 560)+ const height = init.height ?? (naturalHeight ? Math.round((width * naturalHeight) / (naturalWidth || 1)) : 315)+ return {+ ...baseElement('video', { width, height, ...init }),+ type: 'video',+ src,+ poster,+ duration,+ volume: 0.8,+ muted: false,+ loop: false,+ autoplay: false,+ trimStart: 0,+ trimEnd: duration,+ ...init,+ width,+ height,+ }+}+function embedTitleFrom(url: string, kind: EmbedKind): string {try {const u = new URL(url)diff --git a/src/lib/video-export.ts b/src/lib/video-export.tsindex acdad9f..c8fef04 100644--- a/src/lib/video-export.ts+++ b/src/lib/video-export.ts@@ -12,8 +12,9 @@// ─────────────────────────────────────────────────────────────import Konva from 'konva'-import type { AnyElement, ImageElement, PageData } from '@/lib/types'+import type { AnyElement, AudioElement, ImageElement, PageData, VideoElement } from '@/lib/types'import { animateElementAt, pageHoldDuration } from '@/lib/animations'+import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'export interface VideoExportOptions {designWidth: number@@ -33,15 +34,20 @@ export interface VideoExportResult {frames: number}-/** Detect the best supported output format (honest — no fake MP4). */-export function detectVideoFormat(): { mimeType: string; extension: string; label: string } | null {+/** Detect the best supported output format (honest — no fake MP4).+ * v0.11: candidates that declare an audio codec can mux the page audio;+ * the recorder only gets an audio track when the mime supports it. */+export function detectVideoFormat(): { mimeType: string; extension: string; label: string; audio: boolean } | null {if (typeof MediaRecorder === 'undefined') return null- const candidates: { mimeType: string; extension: string; label: string }[] = [- { mimeType: 'video/mp4;codecs=avc1.42E01E', extension: 'mp4', label: 'MP4 (H.264)' },- { mimeType: 'video/mp4', extension: 'mp4', label: 'MP4' },- { mimeType: 'video/webm;codecs=vp9', extension: 'webm', label: 'WebM (VP9)' },- { mimeType: 'video/webm;codecs=vp8', extension: 'webm', label: 'WebM (VP8)' },- { mimeType: 'video/webm', extension: 'webm', label: 'WebM' },+ const candidates: { mimeType: string; extension: string; label: string; audio: boolean }[] = [+ { mimeType: 'video/mp4;codecs=avc1.42E01E,mp4a.40.2', extension: 'mp4', label: 'MP4 (H.264 + AAC)', audio: true },+ { mimeType: 'video/webm;codecs=vp9,opus', extension: 'webm', label: 'WebM (VP9 + Opus)', audio: true },+ { mimeType: 'video/webm;codecs=vp8,opus', extension: 'webm', label: 'WebM (VP8 + Opus)', audio: true },+ { mimeType: 'video/mp4;codecs=avc1.42E01E', extension: 'mp4', label: 'MP4 (H.264)', audio: false },+ { mimeType: 'video/mp4', extension: 'mp4', label: 'MP4', audio: false },+ { mimeType: 'video/webm;codecs=vp9', extension: 'webm', label: 'WebM (VP9)', audio: false },+ { mimeType: 'video/webm;codecs=vp8', extension: 'webm', label: 'WebM (VP8)', audio: false },+ { mimeType: 'video/webm', extension: 'webm', label: 'WebM', audio: false },]for (const c of candidates) {try {@@ -98,6 +104,7 @@ async function collectImages(pages: PageData[]): Promise<Map<string, HTMLImageElconst walk = (els: AnyElement[]) => {for (const el of els) {if (el.type === 'image') sources.push(el.src)+ else if (el.type === 'video') sources.push(el.poster) // v0.11: poster dataURLelse if (el.type === 'group') walk(el.children)}}@@ -272,6 +279,71 @@ function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>):})return node}+ case 'audio': {+ // vector waveform card — geometry mirrors element-node.tsx AudioNode+ const au = el as AudioElement+ const group = new Konva.Group({ id: au.id, x: au.x, y: au.y })+ group.add(+ new Konva.Rect({+ width: au.width,+ height: au.height,+ cornerRadius: 14,+ fill: '#1B1D27',+ stroke: 'rgba(255,255,255,0.13)',+ strokeWidth: 1,+ }),+ )+ group.add(new Konva.Path({ x: 18, y: au.height / 2 - 13, data: 'M13 0 L26 13 L13 26 Z', fill: '#02C0CC' }))+ const peaks = au.peaks?.length ? au.peaks : null+ const barCount = peaks ? Math.min(peaks.length, Math.max(24, Math.floor(au.width / 6))) : 32+ const barW = 3+ const gap = peaks ? Math.max(1.5, (au.width - 116 - barCount * barW) / Math.max(1, barCount - 1)) : 4+ for (let i = 0; i < barCount; i++) {+ const v = peaks ? peaks[Math.floor((i / barCount) * peaks.length)] ?? 0 : 0.35 + 0.3 * Math.abs(Math.sin(i * 1.7))+ const h = Math.max(2, v * (au.height - 34))+ group.add(+ new Konva.Rect({+ x: 116 + i * (barW + gap),+ y: au.height / 2 - h / 2,+ width: barW,+ height: h,+ cornerRadius: 1.5,+ fill: '#7BE8E1',+ opacity: 0.35 + 0.65 * v,+ }),+ )+ }+ group.add(+ new Konva.Text({+ x: 18,+ y: au.height - 20,+ text: au.name.slice(0, 42),+ fontSize: 11,+ fontFamily: 'Inter, system-ui, sans-serif',+ fill: 'rgba(255,255,255,0.6)',+ width: au.width - 36,+ }),+ )+ return group+ }+ case 'video': {+ const vd = el as VideoElement+ const group = new Konva.Group({ id: vd.id, x: vd.x, y: vd.y })+ group.add(new Konva.Rect({ width: vd.width, height: vd.height, cornerRadius: 12, fill: '#101218' }))+ group.add(+ new Konva.Image({+ width: vd.width,+ height: vd.height,+ cornerRadius: 12,+ image: images.get(vd.poster) ?? undefined,+ }),+ )+ const play = new Konva.Group({ x: vd.width / 2 - 24, y: vd.height / 2 - 24, opacity: 0.92 })+ play.add(new Konva.Ellipse({ radiusX: 24, radiusY: 24, fill: 'rgba(0,0,0,0.67)' }))+ play.add(new Konva.Path({ x: 16, y: 14, data: 'M0 0 L16 10 L0 20 Z', fill: '#FFFFFF' }))+ group.add(play)+ return group+ }case 'group': {const g = elconst group = new Konva.Group({ id: g.id, x: g.x, y: g.y, rotation: g.rotation ?? 0 })@@ -337,7 +409,42 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportconst stream = canvas.captureStream(0)const track = stream.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void }- const recorder = new MediaRecorder(stream, {+ // ── v0.11: page-audio muxing (best-effort) ──────────────────+ // Each segment's autoplay audio elements play through a shared+ // AudioContext MediaStreamDestination while their page is on the+ // timeline; the wall-clock pacing of the frame loop keeps A/V aligned.+ // Every step is individually guarded — a browser that refuses any of+ // this (autoplay policy, codec) still produces a correct silent video.+ const segmentAudio: HTMLAudioElement[][] = segments.map((s) =>+ (s.page.elements as AnyElement[])+ .filter((e): e is AudioElement => e.type === 'audio' && e.visible !== false && e.autoplay)+ .map((el) => {+ const a = new Audio(el.src)+ a.volume = Math.min(1, Math.max(0, Number.isFinite(el.volume) ? el.volume : 0.8))+ a.loop = el.loop+ return a+ }),+ )+ let audioCtx: AudioContext | null = null+ let audioDest: MediaStreamAudioDestinationNode | null = null+ if (format.audio && segmentAudio.some((els) => els.length)) {+ try {+ const Ctx: typeof AudioContext =+ window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext+ audioCtx = new Ctx()+ void audioCtx.resume().catch(() => { /* suspended → silent track */ })+ audioDest = audioCtx.createMediaStreamDestination()+ for (const els of segmentAudio) {+ for (const a of els) audioCtx.createMediaElementSource(a).connect(audioDest)+ }+ } catch {+ audioCtx = null+ audioDest = null+ }+ }+ const recordStream = audioDest ? new MediaStream([track, ...audioDest.stream.getAudioTracks()]) : stream++ const recorder = new MediaRecorder(recordStream, {mimeType: format.mimeType,videoBitsPerSecond: Math.round(width * height * fps * 0.12),})@@ -357,6 +464,8 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportconst nodesForPage = new Map<number, { node: Konva.Node; el: AnyElement }[]>()const stageForPage = new Map<number, Konva.Stage>()+ // v0.11: Beat Sync sources per page (beats ride the audio element)+ const beatsForPage = new Map<number, { beats: number[]; bpm: number } | null>()const buildPage = (index: number): { node: Konva.Node; el: AnyElement }[] => {let nodes = nodesForPage.get(index)@@ -406,25 +515,31 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportlayer.batchDraw()nodesForPage.set(index, nodes)stageForPage.set(index, stage)+ beatsForPage.set(index, beatSourceOf(page))return nodes}- /** apply animation state at page-local time t and draw */+ /** apply animation + beat-pulse state at page-local time t and draw */const drawPage = (index: number, t: number): HTMLCanvasElement | null => {const nodes = buildPage(index)+ const beatSrc = beatsForPage.get(index)for (const { node, el } of nodes) {+ // v0.11: Beat Sync — pulses multiply whatever the entry animation+ // (or rest state) produced, so beats compose with any animation+ const beatScale =+ beatSrc && (el.beatPulse ?? 0) > 0 ? 1 + (el.beatPulse ?? 0) * 0.12 * beatEnvelopeAt(beatSrc.beats, t) : 1const a = el.animationif (a && a.kind !== 'none') {const state = animateElementAt(el, t)node.opacity((el.opacity ?? 1) * state.opacity)if (state.reveal < 1) {const r = Math.max(0.001, state.reveal)- node.scale({ x: r, y: 1 })+ node.scale({ x: r * beatScale, y: 1 })node.offsetY(el.height / 2)node.x(el.x + state.dx)node.y(el.y + state.dy + el.height / 2)- } else if (state.scaleX !== 1 || state.scaleY !== 1) {- node.scale({ x: state.scaleX, y: state.scaleY })+ } else if (state.scaleX !== 1 || state.scaleY !== 1 || beatScale !== 1) {+ node.scale({ x: state.scaleX * beatScale, y: state.scaleY * beatScale })node.offsetX(el.width / 2)node.offsetY(el.height / 2)node.x(el.x + state.dx + el.width / 2)@@ -439,11 +554,19 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportnode.rotation((el.rotation ?? 0) + state.rotation)} else {node.opacity(el.opacity ?? 1)- node.scale({ x: 1, y: 1 })- node.offsetX(0)- node.offsetY(0)- node.x(el.x)- node.y(el.y)+ if (beatScale !== 1) {+ node.scale({ x: beatScale, y: beatScale })+ node.offsetX(el.width / 2)+ node.offsetY(el.height / 2)+ node.x(el.x + el.width / 2)+ node.y(el.y + el.height / 2)+ } else {+ node.scale({ x: 1, y: 1 })+ node.offsetX(0)+ node.offsetY(0)+ node.x(el.x)+ node.y(el.y)+ }node.rotation(el.rotation ?? 0)}}@@ -546,11 +669,38 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportconst startWall = performance.now()const deadline = startWall + total * 1000 + 15_000 // hard safety caplet frame = 0+ let activeSeg = -1+ /** segment index owning timeline time t (mirrors renderFrameAt) */+ const segmentIndexAt = (t: number): number => {+ for (let i = 0; i < segments.length; i++) {+ const start = segStarts[i]+ if (t >= start && t < start + segments[i].hold + segments[i].transition) return i+ }+ return segments.length - 1+ }while (frame < totalFrames) {const t = frame / fpsconst targetWall = startWall + t * 1000+ // v0.11: swap the playing page's audio as the timeline crosses a+ // segment boundary (loops within the segment, like presentation)+ const segIdx = segmentIndexAt(t)+ if (segIdx !== activeSeg) {+ if (activeSeg >= 0) {+ for (const a of segmentAudio[activeSeg]) {+ a.pause()+ try {+ a.currentTime = 0+ } catch {+ /* not seekable yet */+ }+ }+ }+ for (const a of segmentAudio[segIdx]) void a.play().catch(() => { /* stays silent */ })+ activeSeg = segIdx+ }+// behind schedule? skip ahead to the frame the clock says we should renderlet now = performance.now()if (now > targetWall + 250) {@@ -586,6 +736,13 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportfor (const stage of stageForPage.values()) stage.destroy()host.remove()stream.getTracks().forEach((tr) => tr.stop())+ for (const els of segmentAudio) {+ for (const a of els) {+ a.pause()+ a.removeAttribute('src')+ }+ }+ void audioCtx?.close().catch(() => {})}const blob = new Blob(chunks, { type: format.mimeType })