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.15): moving video in exports — frame-accurate autoplay videos on both engines, one shared windowedSourceTime mapping (R3)
Ashiq Hussain Mir3705076dc89a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da179e6..afae012 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,54 @@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.15.2] — 2026-11-06++### Added++- **Rich content & export, part 3 — moving video in exports (R3).**+ Autoplay video elements render their MOVING content in exported+ videos — frame-accurately — instead of the poster frame they had+ shown since v0.11.+ - **`windowedSourceTime`** — the one source-time mapping both export+ engines share (pure, unit-tested): page-local t=0 → trimStart,+ looping wraps within the trim window, non-looping holds the final+ frame, a trim past the file clamps to the loaded duration, and+ every input is garbage-safe (never NaN, never negative).+ - **WebCodecs engine: seek + draw per fixed timestep.** Before each+ frame is composited, every visible autoplay video is seeked to its+ exact source position — seeks are deduped (same rounded target ⇒+ no-op), parallel across videos and individually bounded (3 s); a+ seek that never completes draws the last decoded frame, so a slow+ video source can only make the export take longer, never drop or+ duplicate a frame (R2's deterministic pacing preserved).+ - **MediaRecorder engine: wall-clock playback.** Autoplay videos+ play beside the page audio — segment entry seeks to trimStart and+ plays (muted — the export muxes page audio only; that boundary is+ the R3 acceptance, unchanged), segment exit pauses + resets, and+ the frame loop applies the trim window with the same rule the+ presentation rAF tick uses.+ - **Honest degradation everywhere**: non-autoplay videos keep the+ static poster render (the presentation semantic); a source that+ fails to load (CORS-blocked remote, gone media id, 12 s canplay+ budget missed) falls back to the poster — fail-closed, the same+ rule as the image loader; decode is capped at 12 simultaneous+ videos (`MAX_EXPORT_VIDEOS`), the rest keep posters. Live videos+ render without the play chip (an editor affordance — this one is+ playing).+ - The export dialog says so before you click: "Autoplay videos+ export with their moving content frame-accurately."+ - CPU cost, on the record: each visible autoplay video costs one+ seek round-trip per exported frame on the WebCodecs path+ (typically ~5–15 ms in Chromium — a 30 fps × 10 s page with one+ video ≈ 300 seeks ≈ a few extra seconds); the MediaRecorder path+ decodes in real time, same as presentation.+ - New anonymous zero-registration e2e acceptance: a moving+ test-pattern video uploads through the media store and exports+ through BOTH engines; extracted frames at t=0.6 vs t=1.8 must+ differ substantially (moving content) — while the same design+ with autoplay OFF must stay static (the poster gate). Plus the+ pure mapping/filter contracts in the unit suite.+## [0.15.1] — 2026-11-05### Addeddiff --git a/README.md b/README.mdindex 6afc387..d2182a6 100644--- a/README.md+++ b/README.md@@ -253,12 +253,14 @@ is right here.Honest format detection is shown before you export. No uploads, no serverrendering. 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`+- **Audio/video elements & Beat Sync** *(v0.11, video export v0.15)* —+ 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 in the editor. Media+ plays in Preview/Present — and autoplay videos render their MOVING+ content in exported videos, frame-accurately *(v0.15 R3)*. **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",@@ -1059,6 +1061,25 @@ tool descriptions so agents pick the right format.~30 KB muxing dependency (mux.js et al.) — rejected for now; MP4stays on the MediaRecorder path where the browser can encodeH.264. *(v0.15.1)*+- [x] Moving video in exports (v0.15 R3) — autoplay VIDEO elements+ render their moving content, frame-accurately, in exported videos+ (poster-only since v0.11). **`windowedSourceTime`** is the one+ source-time mapping both engines share: page-local t=0 → trimStart,+ looping wraps within the trim window, non-looping holds the final+ frame, a trim past the file clamps to the file — garbage-safe (never+ NaN, never negative). Each engine gets its own scheduler: the+ **WebCodecs** engine seeks every visible video to its exact+ per-frame position before drawing (seeks deduped, parallel,+ individually bounded — a stuck seek draws the last decoded frame, so+ a slow source can only make the export take longer, never wrong);+ the **MediaRecorder** engine plays the videos in wall clock beside+ the page audio (segment entry seeks to trimStart + plays; the loop+ applies the trim window with the same rule the presentation tick+ uses). Live videos are always muted — the export muxes page audio+ only (audio mux unchanged, per the acceptance). Non-autoplay videos+ and load failures (CORS-blocked remotes, gone media ids) keep the+ poster render — the presentation semantic, fail-closed. Decode is+ capped at 12 simultaneous videos; the rest keep posters. *(v0.15.2)*- [ ] Mobile editor polish — touch-first selection handles, gesturezoom/pan without modifier keys, bottom-sheet property panels(the responsive groundwork from v0.11.3 makes this tractable)diff --git a/package.json b/package.jsonindex 29cb205..3cd72b8 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.15.1",+ "version": "0.15.2","private": false,"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/components/editor/ExportDialog.tsx b/src/components/editor/ExportDialog.tsxindex 54b1416..232f52d 100644--- a/src/components/editor/ExportDialog.tsx+++ b/src/components/editor/ExportDialog.tsx@@ -15,6 +15,7 @@ import {estimateVideoDuration,exportVideo,pagesHaveAutoplayAudio,+ pagesHaveAutoplayVideo,type VideoExportEngineDecision,} from '@/lib/video-export'import { toast } from '@/hooks/use-toast'@@ -268,6 +269,9 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChan<span className="text-red-500">This browser cannot export video — try Chrome or Edge.</span>)}</p>+ {pagesHaveAutoplayVideo(pages) ? (+ <p>Autoplay videos export with their moving content frame-accurately — non-autoplay videos keep their poster.</p>+ ) : null}</div>) : (<>diff --git a/src/lib/types.ts b/src/lib/types.tsindex 4891bf0..6f02ec8 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -380,9 +380,10 @@ export interface AudioElement extends BaseElement {/** 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). */+ * playback runs in presentation/preview AND in video exports (v0.15 R3:+ * autoplay videos render their moving content frame-accurately through+ * windowedSourceTime in src/lib/video-export.ts; non-autoplay videos and+ * load failures keep the poster render — the presentation semantic). */export interface VideoElement extends BaseElement {type: 'video'src: stringdiff --git a/src/lib/video-export.test.ts b/src/lib/video-export.test.tsindex ff8a966..e0079c9 100644--- a/src/lib/video-export.test.ts+++ b/src/lib/video-export.test.ts@@ -17,7 +17,15 @@// ─────────────────────────────────────────────────────────────import { describe, expect, it } from 'vitest'-import { chooseVideoExportEngine, computeExportSize, pagesHaveAutoplayAudio } from './video-export'+import {+ chooseVideoExportEngine,+ computeExportSize,+ isPlayableExportVideo,+ MAX_EXPORT_VIDEOS,+ pagesHaveAutoplayAudio,+ pagesHaveAutoplayVideo,+ windowedSourceTime,+} from './video-export'import type { PageData } from './types'function page(elements: unknown[]): PageData {@@ -131,3 +139,92 @@ describe('pagesHaveAutoplayAudio — mirrors the recorder filter exactly', () =>).toBe(false)})})++// ─────────────────────────────────────────────────────────────+// v0.15 R3 — moving video in exports+//+// windowedSourceTime is the ONE source-time mapping both engines+// share (WebCodecs seeks to it per frame; MediaRecorder's trim tick+// and segment resets assume it), and the playability filter decides+// which videos get a live <video> at all. Both are pure — the whole+// contract is unit-testable without a browser.+// ─────────────────────────────────────────────────────────────++describe('windowedSourceTime — the R3 source-time mapping', () => {+ it('t = 0 → trimStart; plain playback advances 1:1 with page time', () => {+ expect(windowedSourceTime(0.1, 1.8, false, 0)).toBe(0.1)+ expect(windowedSourceTime(0.1, 1.8, false, 0.5)).toBe(0.6)+ expect(windowedSourceTime(0, 6, false, 2.2)).toBe(2.2)+ })++ it('non-looping HOLDS the final frame once the window is spent', () => {+ expect(windowedSourceTime(0.1, 1.8, false, 5)).toBe(1.8)+ expect(windowedSourceTime(0, 6, false, 100)).toBe(6)+ })++ it('looping wraps within [trimStart, end]', () => {+ // span = 1.7: 3.5 = 2 × 1.7 + 0.1 → 0.1 past the start+ expect(windowedSourceTime(0.1, 1.8, true, 3.5)).toBeCloseTo(0.2, 10)+ // an exact multiple of the span lands back on the start+ expect(windowedSourceTime(0.1, 1.8, true, 1.7)).toBe(0.1)+ expect(windowedSourceTime(0, 6, true, 14.5)).toBeCloseTo(2.5, 10)+ })++ it('a trim past what the file contains clamps to the loaded duration', () => {+ expect(windowedSourceTime(0.1, 1.8, false, 0.5, 1.0)).toBe(0.6)+ expect(windowedSourceTime(0.1, 1.8, false, 5, 1.0)).toBe(1.0)+ expect(windowedSourceTime(0, 6, true, 14.5, 2.0)).toBeCloseTo(0.5, 10)+ })++ it('degenerate window (end ≤ start) holds the start, never NaN', () => {+ expect(windowedSourceTime(2, 1, false, 10)).toBe(1)+ expect(windowedSourceTime(1, 1, true, 10)).toBe(1)+ })++ it('garbage inputs never produce NaN or negative times', () => {+ expect(windowedSourceTime(Number.NaN, Number.NaN, false, Number.NaN, Number.NaN)).toBe(0)+ expect(windowedSourceTime(Number.NaN, Number.NaN, true, Number.NaN, 5)).toBe(0)+ expect(windowedSourceTime(0, 10, false, -5)).toBe(0)+ expect(windowedSourceTime(0.5, 2, true, -3)).toBe(0.5)+ // Infinity page time is garbage too — clamped, and the loop branch+ // can never reach Infinity % span = NaN+ expect(windowedSourceTime(0, 10, false, Number.POSITIVE_INFINITY)).toBe(0)+ expect(windowedSourceTime(0, 10, true, Number.POSITIVE_INFINITY)).toBe(0)+ })+})++describe('isPlayableExportVideo / pagesHaveAutoplayVideo — the R3 gate', () => {+ it('video + visible + autoplay plays in the export', () => {+ expect(isPlayableExportVideo({ type: 'video', visible: true, autoplay: true } as never)).toBe(true)+ })++ it('non-autoplay and hidden videos keep the poster render', () => {+ expect(isPlayableExportVideo({ type: 'video', visible: true, autoplay: false } as never)).toBe(false)+ expect(isPlayableExportVideo({ type: 'video', visible: false, autoplay: true } as never)).toBe(false)+ expect(isPlayableExportVideo({ type: 'video', visible: false, autoplay: false } as never)).toBe(false)+ })++ it('any other element type never counts', () => {+ expect(isPlayableExportVideo({ type: 'audio', visible: true, autoplay: true } as never)).toBe(false)+ expect(isPlayableExportVideo({ type: 'rect', visible: true, autoplay: true } as never)).toBe(false)+ })++ it('pagesHaveAutoplayVideo walks groups and needs at least one playable video', () => {+ expect(pagesHaveAutoplayVideo([page([{ type: 'video', visible: true, autoplay: true }])])).toBe(true)+ expect(+ pagesHaveAutoplayVideo([+ page([{ type: 'group', children: [{ type: 'video', visible: true, autoplay: true }] }]),+ ]),+ ).toBe(true)+ expect(+ pagesHaveAutoplayVideo([+ page([]),+ page([{ type: 'group', children: [{ type: 'video', visible: true, autoplay: false }] }]),+ ]),+ ).toBe(false)+ })++ it('MAX_EXPORT_VIDEOS pins the decode cap', () => {+ expect(MAX_EXPORT_VIDEOS).toBe(12)+ })+})diff --git a/src/lib/video-export.ts b/src/lib/video-export.tsindex 5141538..5ca31b7 100644--- a/src/lib/video-export.ts+++ b/src/lib/video-export.ts@@ -7,6 +7,11 @@// latencyMode 'quality') — or — MediaRecorder canvas capture// → MP4 (H.264 where the browser can encode it) / WebM,// which stays the path for page-audio designs (it muxes audio).+// [v0.15 R3] autoplay VIDEO elements render their moving content+// frame-accurately: windowedSourceTime is the one source-time+// mapping; the WebCodecs engine seeks each video to its exact+// per-frame position, the MediaRecorder engine plays them in wall+// clock beside the page audio.//// Static PNG/JPG/PDF/SVG exports are unaffected (animations are// ignored there). See chooseVideoExportEngine for the matrix.@@ -153,6 +158,102 @@ async function collectImages(pages: PageData[]): Promise<Map<string, HTMLImageElreturn map}+// ── v0.15 (R3): live video preload ──────────────────────────++/** A preloaded live <video> backing one autoplay video element. */+interface VideoAsset {+ el: HTMLVideoElement+ /** canplay fired within budget — false ⇒ the node keeps the poster */+ ok: boolean+ /** the loaded file's duration (NaN until metadata arrives) */+ duration: number+ /** last requested seek target in whole ms (−1 = never sought) */+ lastSeekMs: number+}++/** Bounded wait for a media event — resolves false on timeout or the+ * error event, and always removes its listeners. */+function waitMediaEvent(v: HTMLMediaElement, event: string, budgetMs: number): Promise<boolean> {+ return new Promise((resolve) => {+ let settled = false+ const done = (val: boolean) => {+ if (settled) return+ settled = true+ v.removeEventListener(event, onOk)+ v.removeEventListener('error', onErr)+ clearTimeout(timer)+ resolve(val)+ }+ const onOk = () => done(true)+ const onErr = () => done(false)+ const timer = setTimeout(() => done(false), budgetMs)+ v.addEventListener(event, onOk)+ v.addEventListener('error', onErr)+ })+}++/** R3: preload one live, MUTED <video> per autoplay video element.+ * Presentation semantics: a video moves in an export exactly when+ * presentation would play it — visible + autoplay; everything else+ * keeps the static poster render and gets no asset here.+ *+ * CORS-clean by construction: crossOrigin='anonymous' means same-origin+ * media ids and data URLs load trivially while a remote without CORS+ * headers FAILS to load (poster fallback) instead of tainting the+ * canvas — fail-closed, the same rule as the image loader. Videos are+ * always muted: the export muxes page AUDIO only (the R3 acceptance+ * keeps that boundary — “audio mux unchanged”). Capped at+ * MAX_EXPORT_VIDEOS so a hostile design cannot demand unbounded+ * decode; elements past the cap fall back to their poster. */+async function collectVideos(+ pages: PageData[],+ onProgress?: (ratio: number, stage: string) => void,+): Promise<Map<string, VideoAsset>> {+ const assets = new Map<string, VideoAsset>()+ const els: VideoElement[] = []+ const walk = (list: AnyElement[]): void => {+ for (const el of list) {+ if (isPlayableExportVideo(el)) els.push(el)+ else if (el.type === 'group') walk(el.children)+ }+ }+ for (const p of pages) walk(p.elements)+ if (els.length === 0) return assets+ onProgress?.(0, 'Loading videos…')+ await Promise.all(+ els.slice(0, MAX_EXPORT_VIDEOS).map(async (vd) => {+ const v = document.createElement('video')+ v.crossOrigin = 'anonymous'+ v.muted = true+ v.playsInline = true+ v.preload = 'auto'+ const asset: VideoAsset = { el: v, ok: false, duration: Number.NaN, lastSeekMs: -1 }+ assets.set(vd.id, asset)+ const loaded = waitMediaEvent(v, 'canplay', 12_000)+ v.src = vd.src+ asset.ok = await loaded+ if (Number.isFinite(v.duration)) asset.duration = v.duration+ if (!asset.ok) return+ // park at the trim start so pre-roll and incoming transitions+ // show the window's first frame in BOTH engines (bounded,+ // best-effort — a failed park just means the first explicit+ // seek / seek+play does the work instead)+ const start = Math.max(0, Number.isFinite(vd.trimStart) ? vd.trimStart : 0)+ if (start > 0.05) {+ try {+ v.currentTime = start+ if (await waitMediaEvent(v, 'seeked', 3_000)) asset.lastSeekMs = Math.round(start * 1000)+ } catch {+ /* not seekable yet */+ }+ } else {+ asset.lastSeekMs = 0 // a fresh canplay sits at 0+ }+ }),+ )+ return assets+}+// ── Konva node builders (geometry mirrors element-node.tsx) ──/** clip function for a frame shape (mirrors v06-nodes frameClip) */@@ -200,7 +301,11 @@ function frameClipFunc(fr: FrameElement): (ctx: Konva.Context) => void {* the geometry module, the D7 charts pattern). */const videoRichMeasure = createCanvasMeasure()-function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>): Konva.Node {+function buildKonvaNode(+ el: AnyElement,+ images: Map<string, HTMLImageElement>,+ videos: Map<string, VideoAsset>,+): Konva.Node {switch (el.type) {case 'text': {const t = el@@ -498,6 +603,22 @@ function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>):const vd = el as VideoElementconst 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' }))+ // v0.15 (R3): an autoplay video with a loaded source renders its+ // LIVE frame — the moving content IS the export representation+ // (no play chip: that is an editor affordance, and this video is+ // playing). Everything else keeps the v0.11 poster render.+ const asset = videos.get(vd.id)+ if (vd.autoplay && asset?.ok) {+ group.add(+ new Konva.Image({+ width: vd.width,+ height: vd.height,+ cornerRadius: 12,+ image: asset.el,+ }),+ )+ return group+ }group.add(new Konva.Image({width: vd.width,@@ -707,7 +828,7 @@ function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>):const g = elconst group = new Konva.Group({ id: g.id, x: g.x, y: g.y, rotation: g.rotation ?? 0 })for (const child of g.children.filter((c) => c.visible)) {- const childNode = buildKonvaNode(child, images)+ const childNode = buildKonvaNode(child, images, videos)childNode.x(child.x - g.x)childNode.y(child.y - g.y)group.add(childNode as Konva.Shape | Konva.Group)@@ -786,6 +907,63 @@ export function pagesHaveAutoplayAudio(pages: PageData[]): boolean {)}+// ── v0.15 (R3): moving video in exports ──────────────────────++/** Hard cap on simultaneously decoded export videos — each is a live+ * <video> the compositor seeks or plays; a hostile design must not be+ * able to demand unbounded decode. Elements past the cap keep their+ * poster render. */+export const MAX_EXPORT_VIDEOS = 12++/** The filter every export path shares (asset preload, the recorder's+ * segment lists, the dialog note): a video renders MOVING content in+ * an export exactly when presentation would play it — visible ++ * autoplay. Non-autoplay videos deliberately keep the static poster+ * render (the presentation semantic). */+export function isPlayableExportVideo(el: AnyElement): el is VideoElement {+ return el.type === 'video' && el.visible !== false && !!el.autoplay+}++/** Does any page carry a video that will move in the export? (dialog+ * honesty note — same shape as pagesHaveAutoplayAudio.) */+export function pagesHaveAutoplayVideo(pages: PageData[]): boolean {+ const walk = (els: AnyElement[]): boolean => els.some((el) => isPlayableExportVideo(el) || (el.type === 'group' && walk(el.children)))+ return pages.some((p) => walk(p.elements))+}++/**+ * The ONE source-time mapping both export engines share — the position+ * (seconds into the source file) an autoplay video must show at+ * PAGE-LOCAL time t. Mirrors presentation semantics exactly:+ *+ * t = 0 → trimStart (the page appearing starts playback there)+ * looping → wraps within [trimStart, end]+ * non-looping → HOLDS the final frame once the window is spent+ * end → min(trimEnd, loadedDuration): a trim past what the+ * file actually contains clamps to the file+ *+ * Every input is garbage-safe (finite-clamped with sane defaults): the+ * mapping can never return NaN or a negative time.+ */+export function windowedSourceTime(+ trimStart: number,+ trimEnd: number,+ loop: boolean,+ t: number,+ loadedDuration = Number.POSITIVE_INFINITY,+): number {+ const finite = (v: number, dflt: number): number => (Number.isFinite(v) ? v : dflt)+ const dur = finite(loadedDuration, Number.POSITIVE_INFINITY)+ let end = finite(trimEnd, 0)+ if (Number.isFinite(dur) && dur > 0) end = Math.min(end, dur)+ let start = Math.max(0, finite(trimStart, 0))+ if (start > end) start = end+ const span = end - start+ if (span <= 0) return start+ const tt = Math.max(0, finite(t, 0))+ return loop ? start + (tt % span) : Math.min(start + tt, end)+}+export interface WebCodecsVideoSupport {supported: boolean/** Matroska CodecID the muxer should declare. */@@ -868,7 +1046,13 @@ interface RenderSession {readonly segments: TimelineSegment[]readonly segStarts: number[]readonly totalFrames: number+ /** R3: preloaded live videos by element id (empty when no autoplay videos) */+ readonly videos: ReadonlyMap<string, VideoAsset>renderFrameAt(frameNo: number, t: number): void+ /** R3: deterministic engines call this BEFORE renderFrameAt so every+ * visible video sits at its exact source frame when the composite is+ * drawn (a no-op when the design has no autoplay videos). */+ prepareFrameAt(t: number): Promise<void>destroy(): void}@@ -882,6 +1066,10 @@ async function createRenderSession(// preload every image source first (dataURLs resolve instantly)opts.onProgress?.(0, 'Loading images…')const images = await collectImages(opts.pages)+ // v0.15 (R3): live videos for the moving-content render (no-op when+ // the design has none — the map stays empty and every code path+ // below degrades to the v0.11 poster behaviour)+ const videos = await collectVideos(opts.pages, opts.onProgress)const canvas = document.createElement('canvas')canvas.width = width@@ -934,7 +1122,7 @@ async function createRenderSession(nodes = page.elements.filter((el) => el.visible).map((el) => {- const node = buildKonvaNode(el, images)+ const node = buildKonvaNode(el, images, videos)const shape = node as Konva.Shapeif (el.shadow?.enabled && typeof shape.shadowColor === 'function') {shape.shadowColor(el.shadow.color)@@ -1014,10 +1202,12 @@ async function createRenderSession(return start})- /** render the composite for timeline time t onto the recorder canvas */- const renderFrameAt = (frameNo: number, t: number): void => {- void frameNo- // locate the active segment+ /** which pages are on screen at timeline time t: the active segment+ * (holding — or frozen at its FINAL state once its out-transition+ * starts) and, mid-transition, the incoming page entering at local+ * t = 0. One definition shared by the compositor and the R3 video+ * scheduler, so the two can never disagree about what is visible. */+ const pagesVisibleAt = (t: number): { outSeg: number; outLocal: number; incSeg: number | null; progress: number } => {let segIdx = segments.length - 1let segLocal = t - segStarts[segments.length - 1]for (let i = 0; i < segments.length; i++) {@@ -1031,20 +1221,31 @@ async function createRenderSession(}const seg = segments[segIdx]const inTransition = segLocal >= seg.hold && seg.transition > 0- const p = inTransition ? (segLocal - seg.hold) / seg.transition : 0+ return {+ outSeg: segIdx,+ outLocal: inTransition ? seg.hold + seg.transition : segLocal,+ incSeg: inTransition ? segIdx + 1 : null,+ progress: inTransition ? (segLocal - seg.hold) / seg.transition : 0,+ }+ }++ /** render the composite for timeline time t onto the recorder canvas */+ const renderFrameAt = (frameNo: number, t: number): void => {+ void frameNo+ const { outSeg, outLocal, incSeg, progress: p } = pagesVisibleAt(t)ctx.fillStyle = '#FFFFFF'ctx.fillRect(0, 0, width, height)- if (!inTransition) {- const pageCanvas = drawPage(segIdx, segLocal)+ if (incSeg === null) {+ const pageCanvas = drawPage(outSeg, outLocal)if (pageCanvas) ctx.drawImage(pageCanvas, 0, 0, width, height)} else {// transition: outgoing holds its final state; incoming enters- const outCanvas = drawPage(segIdx, seg.hold + seg.transition) // final state- const inCanvas = drawPage(segIdx + 1, 0)+ const outCanvas = drawPage(outSeg, outLocal) // final state+ const inCanvas = drawPage(incSeg, 0)- const nextSeg = segments[segIdx + 1]+ const nextSeg = segments[incSeg]const kind = nextSeg.page.transition?.kind ?? 'fade'const dir = nextSeg.page.transition?.direction ?? 'left'@@ -1075,15 +1276,65 @@ async function createRenderSession(}}+ /** v0.15 (R3): put every VISIBLE autoplay video at its exact source+ * position for timeline time t — the deterministic engine's+ * pre-render step. Seeks are deduped (same rounded target ⇒ no-op),+ * run in parallel across videos and are individually bounded: a seek+ * that never completes draws the last decoded frame — the export can+ * stall on NOTHING, it can only get slower. */+ const prepareFrameAt = async (t: number): Promise<void> => {+ if (videos.size === 0) return+ const vis = pagesVisibleAt(t)+ const jobs: Promise<void>[] = []+ const schedulePage = (segIndex: number, localT: number): void => {+ const walk = (els: AnyElement[]): void => {+ for (const el of els) {+ if (isPlayableExportVideo(el)) {+ const asset = videos.get(el.id)+ if (!asset?.ok) continue+ const target = windowedSourceTime(el.trimStart, el.trimEnd, !!el.loop, localT, asset.duration)+ const targetMs = Math.round(target * 1000)+ if (targetMs === asset.lastSeekMs) continue // dedupe+ asset.lastSeekMs = targetMs+ jobs.push(+ (async () => {+ try {+ asset.el.currentTime = target+ } catch {+ return // not seekable — keep the last decoded frame+ }+ await waitMediaEvent(asset.el, 'seeked', 3_000)+ })(),+ )+ } else if (el.type === 'group') walk(el.children)+ }+ }+ walk(segments[segIndex].page.elements)+ }+ schedulePage(vis.outSeg, vis.outLocal)+ if (vis.incSeg !== null) schedulePage(vis.incSeg, 0)+ if (jobs.length > 0) await Promise.all(jobs)+ }+/** tear down the Konva stages + hidden host (stream/audio teardown* belongs to the engine path that created them). */const destroy = (): void => {for (const stage of stageForPage.values()) stage.destroy()host.remove()+ // R3: release the video decoders+ for (const asset of videos.values()) {+ try {+ asset.el.pause()+ asset.el.removeAttribute('src')+ asset.el.load()+ } catch {+ /* already released */+ }+ }}- return { canvas, ctx, segments, segStarts, totalFrames, renderFrameAt, destroy }+ return { canvas, ctx, segments, segStarts, totalFrames, videos, renderFrameAt, prepareFrameAt, destroy }}export async function exportVideo(opts: VideoExportOptions): Promise<VideoExportResult> {@@ -1181,6 +1432,7 @@ async function exportViaWebCodecs(for (let frame = 0; frame < totalFrames; frame++) {if (encodeError) throw encodeErrorconst t = frame / fps+ await session.prepareFrameAt(t) // R3: every video at its exact framerenderFrameAt(frame, t)while (encoder.encodeQueueSize > 4 && !encodeError) await breathe()const videoFrame = new VideoFrame(canvas, {@@ -1222,7 +1474,28 @@ async function exportViaMediaRecorder(): Promise<VideoExportResult> {const { fps, width, height, segments, total, totalFrames } = sizedconst session = await createRenderSession(opts, width, height, segments, totalFrames)- const { canvas, ctx, renderFrameAt, segStarts } = session+ const { canvas, ctx, renderFrameAt, segStarts, videos } = session++ // ── v0.15 (R3): moving video on the wall-clock engine ───────+ // The recorder paces frames against real time, so autoplay videos+ // PLAY alongside it — exactly how the page audio works — instead of+ // being seeked per frame. Segment entry: seek to trimStart + play+ // (muted — the export never muxes video-element audio). Segment+ // exit: pause + reset. The loop's trim tick applies the window with+ // the same rule the presentation rAF tick uses.+ const segmentVideos = segments.map((s) => {+ const list: { asset: VideoAsset; vd: VideoElement }[] = []+ const walk = (els: AnyElement[]): void => {+ for (const el of els) {+ if (isPlayableExportVideo(el)) {+ const asset = videos.get(el.id)+ if (asset?.ok) list.push({ asset, vd: el })+ } else if (el.type === 'group') walk(el.children)+ }+ }+ walk(s.page.elements)+ return list+ })const stream = canvas.captureStream(0)const track = stream.getVideoTracks()[0] as MediaStreamTrack & { requestFrame?: () => void }@@ -1371,11 +1644,48 @@ async function exportViaMediaRecorder(/* not seekable yet */}}+ // R3: the outgoing page's videos pause + reset to their window+ for (const { asset, vd } of segmentVideos[activeSeg]) {+ asset.el.pause()+ try {+ asset.el.currentTime = Math.max(0, vd.trimStart)+ } catch {+ /* not seekable yet */+ }+ }}for (const a of segmentAudio[segIdx]) void a.play().catch(() => { /* stays silent */ })+ // R3: the incoming page's videos start at their trim window+ for (const { asset, vd } of segmentVideos[segIdx]) {+ try {+ asset.el.currentTime = Math.max(0, vd.trimStart)+ } catch {+ /* not seekable — plays from wherever it sits */+ }+ void asset.el.play().catch(() => { /* muted autoplay cannot be policy-blocked; belt and braces */ })+ }activeSeg = segIdx}+ // R3: trim window on the playing videos — looping wraps back to+ // trimStart, non-looping pauses and holds its final frame (only+ // fight the element when the trim truly ends before the file:+ // the same guard the presentation tick uses)+ if (activeSeg >= 0) {+ for (const { asset, vd } of segmentVideos[activeSeg]) {+ const v = asset.el+ if (Number.isFinite(asset.duration) && vd.trimEnd < asset.duration && v.currentTime >= vd.trimEnd) {+ if (vd.loop) {+ try {+ v.currentTime = Math.max(0, vd.trimStart)+ } catch {+ /* not seekable */+ }+ } else v.pause()+ }+ }+ }+// behind schedule? skip ahead to the frame the clock says we should renderlet now = performance.now()if (now > targetWall + 250) {diff --git a/tests/e2e/moving-video-export.spec.ts b/tests/e2e/moving-video-export.spec.tsnew file mode 100644index 0000000..22f69a2--- /dev/null+++ b/tests/e2e/moving-video-export.spec.ts@@ -0,0 +1,349 @@+import { test, expect, type APIRequestContext, type Page } from '@playwright/test'+import { execFileSync } from 'node:child_process'+import { existsSync, readFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++/**+ * v0.15 (R3): moving video in exports — acceptance.+ *+ * 1. (WebCodecs engine) a SILENT design whose only moving element is+ * an autoplay video exports the VIDEO CONTENT, not the poster:+ * grayscale frames extracted at two timeline points must differ+ * substantially (testsrc changes every frame — the poster path+ * cannot move).+ * 2. the GATE: the same design with autoplay OFF exports the static+ * poster render — the two extracted frames are (near-)identical.+ * This pins the presentation semantic (non-autoplay = poster) and+ * proves spec 1 moved because of R3, not because "something" moved.+ * 3. (MediaRecorder engine) a page-audio design (the engine matrix+ * routes it to MediaRecorder) also renders the moving video — the+ * wall-clock engine plays videos beside the audio instead of+ * seeking them per frame.+ *+ * Register budget: ZERO — anonymous designs, fresh contexts (the+ * PR #26/#30 lesson).+ */++test.use({+ launchOptions: { args: ['--autoplay-policy=no-user-gesture-required'] },+})++const BASE = process.env.BASE_URL ?? 'http://localhost:3000'++/** the export pipeline's fixed fps */+const FPS = 30++// ── fixtures ──────────────────────────────────────────────────++/** 6 s of MOVING test pattern as VP8 WebM (open codec — decodable in+ * stock Chromium, the same choice the v0110 smoke makes). Cached. */+function makeMovingWebm(): Buffer | null {+ const p = join(tmpdir(), 'canvix-r3-moving.webm')+ try {+ if (!existsSync(p)) {+ execFileSync(+ 'ffmpeg',+ [+ '-y', '-loglevel', 'error',+ '-f', 'lavfi', '-i', 'testsrc=duration=6:size=320x240:rate=15',+ '-c:v', 'libvpx', '-b:v', '200k', p,+ ],+ { timeout: 30_000 },+ )+ }+ return readFileSync(p)+ } catch {+ return null+ }+}++/** mono 16-bit PCM WAV, 120 BPM click track (the v0110 payload) */+function makeWav(seconds = 2.5): Buffer {+ const sampleRate = 44_100+ const samples = Math.floor(sampleRate * seconds)+ const buf = Buffer.alloc(44 + samples * 2)+ buf.write('RIFF', 0)+ buf.writeUInt32LE(36 + samples * 2, 4)+ buf.write('WAVE', 8)+ buf.write('fmt ', 12)+ buf.writeUInt32LE(16, 16)+ buf.writeUInt16LE(1, 20)+ buf.writeUInt16LE(1, 22)+ buf.writeUInt32LE(sampleRate, 24)+ buf.writeUInt32LE(sampleRate * 2, 28)+ buf.writeUInt16LE(2, 32)+ buf.writeUInt16LE(16, 34)+ buf.write('data', 36)+ buf.writeUInt32LE(samples * 2, 40)+ const period = sampleRate / 2 // 120 BPM+ 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+ buf.writeInt16LE(v, 44 + i * 2)+ }+ return buf+}++// ── shared API helpers (anonymous, link-editable designs) ─────++const created = { designs: [] as string[], media: [] as string[] }++async function uploadMedia(request: APIRequestContext, mime: string, bytes: Buffer): Promise<string | null> {+ const init = await request.post(`${BASE}/api/media`, { data: { mime, size: bytes.length } })+ if (!init.ok()) return null+ const { id, chunkSize } = (await init.json()) as { id: string; chunkSize: number }+ created.media.push(id)+ for (let off = 0; off < bytes.length; off += chunkSize) {+ const part = bytes.subarray(off, Math.min(off + chunkSize, bytes.length))+ const r = await request.patch(`${BASE}/api/media/${id}?offset=${off}`, {+ headers: { 'content-type': 'application/octet-stream' },+ data: part,+ })+ if (!r.ok()) return null+ }+ const fin = await request.put(`${BASE}/api/media/${id}`, { data: { expectedSize: bytes.length } })+ return fin.ok() ? id : null+}++/** the 1×1 transparent PNG poster (the v0110 fixture) — anything the+ * static path shows over it is Canvix chrome, never video content */+const POSTER_1PX =+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='++async function createDesign(+ request: APIRequestContext,+ webmId: string,+ opts: { autoplay: boolean; withAudio?: string },+): Promise<string> {+ const video = {+ id: 'VID1', type: 'video',+ x: 160, y: 120, width: 480, height: 360,+ rotation: 0, opacity: 1, locked: false, visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ src: `/api/media/${webmId}`,+ poster: POSTER_1PX,+ duration: 6, volume: 0.7, muted: false, loop: false, autoplay: opts.autoplay,+ trimStart: 0, trimEnd: 6,+ }+ const audio = opts.withAudio+ ? [+ {+ id: 'AUD1', type: 'audio',+ x: 40, y: 470, width: 420, height: 80,+ rotation: 0, opacity: 1, locked: false, visible: true,+ shadow: { enabled: false, color: '#000000', blur: 12, offsetX: 0, offsetY: 6 },+ src: `/api/media/${opts.withAudio}`,+ name: 'probe-clicks.wav',+ duration: 2.5, volume: 0.9, loop: true, autoplay: true,+ peaks: [0.1, 0.9, 0.2, 0.7, 0.3], bpm: 120,+ beats: Array.from({ length: 5 }, (_, i) => 0.1 + i * 0.5),+ },+ ]+ : []+ const res = await request.post(`${BASE}/api/designs`, {+ data: {+ name: 'r3 moving video acceptance',+ width: 800,+ height: 600,+ pages: [+ {+ id: 'p1',+ background: { type: 'solid', color: '#ffffff' },+ elements: [video, ...audio],+ },+ ],+ },+ })+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)+ const id = ((await res.json()) as { id: string }).id+ created.designs.push(id)+ return id+}++async function openEditor(page: Page, designId: string): Promise<void> {+ await page.goto(`/design/${designId}`)+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })+}++/** run the real export flow and return the downloaded file path */+async function exportVideoFile(page: Page, designId: string): Promise<string> {+ await openEditor(page, designId)+ await page.getByLabel('Download').click()+ const dlg = page.getByRole('dialog')+ await expect(dlg.getByText('Download your design')).toBeVisible()+ await dlg.getByRole('button', { name: /Video/ }).click()+ const [download] = await Promise.all([+ page.waitForEvent('download', { timeout: 200_000 }),+ dlg.getByRole('button', { name: /^Download/ }).click(),+ ])+ return (await download.path())!+}++// ── frame comparison ──────────────────────────────────────────++/** decode ONE grayscale frame of the file at t seconds (raw bytes),+ * cropped to the video element's box (480×360 at 160,120 on the+ * 800×600 export — the design is exported at 1:1, no downscale) so+ * the diff measures the VIDEO CONTENT, not the static page around it */+function frameGray(path: string, tSec: number): Buffer {+ const out = join(tmpdir(), `canvix-r3-${process.pid}-${String(tSec).replace('.', '_')}.raw`)+ execFileSync(+ 'ffmpeg',+ ['-y', '-loglevel', 'error', '-i', path, '-ss', String(tSec), '-map', '0:v:0', '-frames:v', '1', '-vf', 'crop=480:360:160:120', '-pix_fmt', 'gray', '-f', 'rawvideo', out],+ { timeout: 30_000 },+ )+ return readFileSync(out)+}++/** mean absolute pixel difference of two same-size gray frames */+function meanAbsDiff(a: Buffer, b: Buffer): number {+ if (a.length === 0 || a.length !== b.length) return Number.POSITIVE_INFINITY+ let s = 0+ for (let i = 0; i < a.length; i++) s += Math.abs(a[i] - b[i])+ return s / a.length+}++/** must this browser be able to seek a VP8 WebM + encode VP9? */+async function webcodecsAvailable(page: Page): Promise<boolean> {+ return page.evaluate(async () => {+ if (typeof VideoEncoder === 'undefined' || typeof VideoFrame === 'undefined') return false+ try {+ const probe = await VideoEncoder.isConfigSupported({ codec: 'vp09.00.10.08', width: 800, height: 600, bitrate: 1_000_000, framerate: 30 })+ return probe.supported === true+ } catch {+ return false+ }+ })+}++// ═══ 1. WebCodecs engine renders the moving video ═════════════++test('silent design with an autoplay video exports the MOVING content via WebCodecs', async ({ page, request }) => {+ test.setTimeout(240_000)++ const webmBuf = makeMovingWebm()+ test.skip(!webmBuf, 'ffmpeg unavailable — cannot build the moving fixture')+ const webmId = (await uploadMedia(request, 'video/webm', webmBuf!))!+ expect(webmId, 'media upload').toBeTruthy()++ const designId = await createDesign(request, webmId, { autoplay: true })+ await openEditor(page, designId)+ test.skip(!(await webcodecsAvailable(page)), 'this browser has no WebCodecs VideoEncoder for VP9')++ await page.getByLabel('Download').click()+ const dlg = page.getByRole('dialog')+ await expect(dlg.getByText('Download your design')).toBeVisible()+ await dlg.getByRole('button', { name: /Video/ }).click()++ // the engine line + the R3 honesty note are both visible BEFORE the export+ await expect(dlg.getByText(/WebCodecs → WebM \(VP9\)/)).toBeVisible({ timeout: 30_000 })+ await expect(dlg.getByText(/moving content frame-accurately/)).toBeVisible()++ const [download] = await Promise.all([+ page.waitForEvent('download', { timeout: 200_000 }),+ dlg.getByRole('button', { name: /^Download/ }).click(),+ ])+ const path = (await download.path())!+ expect(download.suggestedFilename()).toMatch(/\.webm$/)++ // ── ffprobe: WebM, VP9 video stream, NO audio stream ──+ const probe = JSON.parse(+ execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=format_name,duration', '-show_entries', 'stream=codec_type,codec_name', '-of', 'json', path]).toString(),+ ) as { format: { format_name: string; duration: string }; streams: { codec_type: string; codec_name: string }[] }+ expect(probe.format.format_name).toContain('webm')+ expect(probe.streams, `streams: ${JSON.stringify(probe.streams)}`).toHaveLength(1)+ expect(probe.streams[0].codec_type).toBe('video')+ expect(probe.streams[0].codec_name).toBe('vp9')++ // single page, one element → 2.2 s hold+ const duration = Number(probe.format.duration)+ expect(duration).toBeGreaterThanOrEqual(2.0)+ expect(duration).toBeLessThan(4.0)++ // ── THE ACCEPTANCE: the exported frames MOVE ──+ // The design has no animation and no other element — the video is+ // the only thing that CAN change between t=0.6 and t=1.8. The poster+ // path (spec 2) cannot move; a mean gray diff this large is moving+ // video content, not codec noise.+ const diff = meanAbsDiff(frameGray(path, 0.6), frameGray(path, 1.8))+ expect(diff, 'mean gray diff between t=0.6 and t=1.8').toBeGreaterThan(5)+})++// ═══ 2. the gate: non-autoplay keeps the poster ═══════════════++test('the same design with autoplay OFF exports the static poster render', async ({ page, request }) => {+ test.setTimeout(240_000)++ const webmBuf = makeMovingWebm()+ test.skip(!webmBuf, 'ffmpeg unavailable — cannot build the moving fixture')+ const webmId = (await uploadMedia(request, 'video/webm', webmBuf!))!+ expect(webmId, 'media upload').toBeTruthy()++ const designId = await createDesign(request, webmId, { autoplay: false })+ await openEditor(page, designId)+ test.skip(!(await webcodecsAvailable(page)), 'this browser has no WebCodecs VideoEncoder for VP9')++ // no autoplay video ⇒ no R3 note in the dialog+ await page.getByLabel('Download').click()+ const dlg = page.getByRole('dialog')+ await expect(dlg.getByText('Download your design')).toBeVisible()+ await dlg.getByRole('button', { name: /Video/ }).click()+ await expect(dlg.getByText(/WebCodecs → WebM \(VP9\)/)).toBeVisible({ timeout: 30_000 })+ await expect(dlg.getByText(/moving content frame-accurately/)).toBeHidden()++ const [download] = await Promise.all([+ page.waitForEvent('download', { timeout: 200_000 }),+ dlg.getByRole('button', { name: /^Download/ }).click(),+ ])+ const path = (await download.path())!++ // the static poster render cannot move: identical pixels at both+ // times (a hair of tolerance for VP9 quantisation across GOPs)+ const diff = meanAbsDiff(frameGray(path, 0.6), frameGray(path, 1.8))+ expect(diff, 'mean gray diff between t=0.6 and t=1.8').toBeLessThan(1)+})++// ═══ 3. MediaRecorder engine plays the video in wall clock ════++test('a page-audio design (MediaRecorder engine) also renders the moving video', async ({ page, request }) => {+ test.setTimeout(240_000)++ const webmBuf = makeMovingWebm()+ test.skip(!webmBuf, 'ffmpeg unavailable — cannot build the moving fixture')+ const wavId = (await uploadMedia(request, 'audio/wav', makeWav()))!+ const webmId = (await uploadMedia(request, 'video/webm', webmBuf!))!+ expect(wavId && webmId, 'media uploads').toBeTruthy()++ // the autoplay AUDIO forces the engine matrix onto MediaRecorder+ const designId = await createDesign(request, webmId, { autoplay: true, withAudio: wavId })+ await openEditor(page, designId)++ const mrAvailable = await page.evaluate(() => typeof MediaRecorder !== 'undefined')+ test.skip(!mrAvailable, 'this browser has no MediaRecorder')++ await page.getByLabel('Download').click()+ const dlg = page.getByRole('dialog')+ await expect(dlg.getByText('Download your design')).toBeVisible()+ await dlg.getByRole('button', { name: /Video/ }).click()+ await expect(dlg.getByText(/MediaRecorder/)).toBeVisible({ timeout: 30_000 })++ const [download] = await Promise.all([+ page.waitForEvent('download', { timeout: 200_000 }),+ dlg.getByRole('button', { name: /^Download/ }).click(),+ ])+ const path = (await download.path())!+ expect(download.suggestedFilename()).toMatch(/\.(webm|mp4)$/)++ // the recorder muxes the page audio → one video + one audio stream+ const probe = JSON.parse(+ execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type', '-of', 'json', path]).toString(),+ ) as { streams: { codec_type: string }[] }+ expect(probe.streams.filter((s) => s.codec_type === 'video'), 'video streams').toHaveLength(1)+ expect(probe.streams.filter((s) => s.codec_type === 'audio'), 'audio streams').toHaveLength(1)++ // and the video content still MOVES on the wall-clock engine+ const diff = meanAbsDiff(frameGray(path, 0.6), frameGray(path, 1.8))+ expect(diff, 'mean gray diff between t=0.6 and t=1.8').toBeGreaterThan(5)+})