Skip to content

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.

feat(v0.22): SFX fire in video export — and the changelog catches up

Ashiq Hussain Mirfd1c50366a0d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 66e4fa7..6f6e6dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -61,9 +61,102 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- e2e: the wave-4 local-tools spec now also pins that the engine toggle
exists, defaults to Provider, and that the no-provider fallback really
enlarges (8→16px through the designs API) with its honest toast.
+- **AI video goes live — the z-ai dialect beside the Sora one** (user
+ request; `videoGeneration:false` was pure config, but the configured
+ provider speaks a different contract than the Sora-style one the
+ route implemented). `src/app/api/ai/video/route.ts` now speaks both:
+ - Sora: `POST /videos/generations` → `GET …/:id` → `GET …/:id/content`.
+ z-ai: `POST /video/generation` → `GET /async-result?id=…` (MP4 at a
+ plain CDN url inside `video_result`). Dialect choice happens at
+ create time — Sora first (deployed providers unchanged), z-ai when
+ that path 404s — remembered statelessly by prefixing the task id
+ with `z:`; every later poll and the content proxy routes on it. No
+ server memory, no sticky sessions. The z-ai content proxy re-polls
+ the async result and streams the CDN url through our origin
+ (same-origin MP4, no CORS, no expiring links).
+ - The provider stack learns companion auth headers (`slot.headers`,
+ `providerHeaders(slot)` merged into every direct fetch) — the z-ai
+ async-result endpoint demands `X-Token` (401 without it).
+ `normalizeVideoStatus` understands both envelopes; the `z:` prefix
+ is preserved on proxy URLs so the video element src keeps routing.
+ - Verified LIVE end-to-end (`scripts/verify-video-live.ts`, dev
+ provider): capabilities `videoGeneration:true` → POST → z:-prefixed
+ task → 28 polls → 4.68 MB MP4 through the same-origin proxy
+ (ftypisom magic), 145 s total. +4 unit tests (z-ai envelope
+ mapping).
+- **The PPTX limits wave — fonts embed, animations/transitions/SFX
+ carry, re-wrap safety** (user request; closes the three honest
+ limits `docs/PPTX-EXPORT.md` carried):
+ - **Text re-wrap safety**: every text body now carries a bare
+ `<a:normAutofit/>` — when PowerPoint's line engine wraps
+ differently and overflows the shape, it shrinks the text instead
+ of spilling it out; when our engine already auto-fit, the measured
+ `fontScale` rides along.
+ - **Font embedding**: document text faces resolve through the SAME
+ collector + font ladder the PDF exporter uses
+ (`collectTextFaces` → `resolveFontFaces`), ride as
+ `ppt/fonts/fontN.fntdata` + `embeddedFontLst`, wired through
+ `ppt/_rels/presentation.xml.rels` (font rel ids can't collide with
+ slide/master ids). Failure degrades to the pre-v0.22 behaviour —
+ typefaces referenced by family, viewer substitutes — and
+ `fontsEmbedded: 0` in the export result is the honest signal.
+ - **Transitions**: fade native (`p:fade`), slide directional
+ (`p:push dir`), morph → fade (the documented nearest-universal —
+ PowerPoint's own Morph needs object-matching extensions), speeds
+ mapped from durations.
+ - **Entrance animations** ride the `p:timing` tree as ONE click
+ group (our present-mode semantics: one advance, then the sequence
+ plays itself): first element `clickEffect`, the rest `withEffect`
+ at their delays. fade/rise → Fade entrance; pan/wipe → Wipe
+ (directional filter); zoom/pop → Fade (the documented
+ approximation — hand-built Zoom trees repair-prompt); rotate/
+ breathe (emphasis/loops) are dropped, documented, never silently
+ mangled. `+ transitions, sounds, animated, fontsEmbedded` in the
+ result toast's data.
+ - **Page SFX** embed as `media/sfxN.wav` (fetched once per id, the
+ media-bag posture) and wire into the transition sound slot
+ (`p:sndAc`/`p:stSnd`) through an audio relationship on the slide.
+ - Tested: 12 new unit tests (autofit presence, transition XML +
+ schema position, the timing tree — click group, delays, wipe
+ filters, rotate dropped honestly — SFX embedding, media
+ placement); a v0.22 e2e case asserts the whole package
+ (transition + timing + `embeddedFontLst` + fntdata + media
+ placement) and does the LibreOffice round-trip; a node
+ round-trip script exercises the full feature set through
+ `soffice --convert-to pdf` with pixel checks.
+- **SFX fire in video export** (closes the last documented Sound-wave
+ gap — "video export does not fire sfxId triggers in v1"):
+ `buildSfxCues` (new, pure) maps the present-mode triggers onto the
+ recorder's timeline — the incoming page's transition SFX when the
+ transition into it begins (page 0 at t=0), element SFX when the
+ page-local animation clock crosses each delay, same-id retriggers
+ within 60 ms collapsed (the player's guard). Sounds decode once per
+ id through the export's own AudioContext and schedule as one-shot
+ `AudioBufferSource`s on the audio clock, paired with the frame
+ loop's wall clock. SFX count as timeline audio for the engine
+ choice (`hasSfxCues` in `VideoEngineInputs`, the dialog mirrors
+ it): a design with cues but no page audio rides the audio-muxing
+ MediaRecorder instead of the silent WebCodecs path. Every step
+ guarded — a failed fetch/decode drops that one sound, never the
+ export; formats without an audio track (GIF, WebCodecs WebM) still
+ carry no sound (documented in `docs/SOUND.md`). +12 unit tests
+ (cue semantics, retrigger collapse, engine matrix).
### Fixed
+- **PPTX media parts landed at the package root** — the slide rels
+ say `../media/imageN.png` (relative to `ppt/slides/_rels/`), which
+ resolves to `ppt/media/…`, but the writer placed parts at the zip
+ root: every image AND sound in an exported PPTX was a broken
+ reference. Parts now land under `ppt/media/` (asserted by unit +
+ e2e + the round-trip script).
+- **`collectTextFaces` crashed on pre-series-chart documents** —
+ documents saved before the series/labels chart shape (and hostile
+ hand-built ones) have neither field; the face walk now skips them
+ instead of throwing during PDF/PPTX export.
+- **`loadImage` crashed the export in node** (SSR pass / unit tests
+ have no `Image` constructor): a missing bitmap now degrades to the
+ placeholder paths instead of rejecting the whole export.
- **Landing-page counts told the v0.1.0 story** — the stats strip still
advertised "15 fonts bundled / 11 starter templates" and the typography
card "15 hand-picked Google Fonts" while the shipped library is 369
diff --git a/docs/SOUND.md b/docs/SOUND.md
index 44a9b6a..c6462e4 100644
--- a/docs/SOUND.md
+++ b/docs/SOUND.md
@@ -91,11 +91,23 @@ nullable, no migration) name one of the 16 pack sounds:
validate the id against the pack catalogue — hostile or stale
input can only pick from the bundled files, and unknown ids are
dropped, never stored.
-- **Video export does not fire sfxId triggers in v1** (the export
- muxer mixes page audio elements, not per-animation triggers —
- recorded here so nobody has to rediscover it). The panel says the
- workaround inline: insert the sound from the Audio panel as an
- autoplay audio element and it rides the existing export path.
+- **Video export fires the triggers (v0.22)**: `buildSfxCues` maps
+ the present-mode semantics onto the recorder's timeline — the
+ incoming page's transition SFX when the transition into it
+ begins (page 0 at t=0), element SFX when the page-local
+ animation clock crosses each delay, same-id retriggers within
+ 60 ms collapsed (the player's guard). The sounds decode once per
+ id through the export's own AudioContext and schedule as
+ one-shot `AudioBufferSource`s on the audio clock, paired with
+ the frame loop's wall clock. Every step is guarded — a failed
+ fetch or decode drops that one sound, never the export. SFX
+ count as timeline audio for the engine choice: a design with
+ cues but no page audio rides the audio-muxing MediaRecorder
+ instead of the silent WebCodecs path (and if no audio-capable
+ recorder exists, the export is honestly silent, as before).
+ Formats without an audio track (GIF, and WebCodecs WebM) still
+ carry no sound; the Audio-panel workaround (insert as an
+ autoplay audio element) still applies there.
## API surface
diff --git a/src/components/editor/ExportDialog.tsx b/src/components/editor/ExportDialog.tsx
index ee8e663..7b3624e 100644
--- a/src/components/editor/ExportDialog.tsx
+++ b/src/components/editor/ExportDialog.tsx
@@ -16,6 +16,7 @@ import {
estimateVideoDuration,
exportVideo,
pagesHaveAutoplayAudio,
+ pagesHaveSfxCues,
pagesHaveAutoplayVideo,
type VideoExportEngineDecision,
} from '@/lib/video-export'
@@ -119,6 +120,9 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChan
mediaRecorder: mr !== null,
mediaRecorderAudio: mr?.audio ?? false,
hasPageAudio: pagesHaveAutoplayAudio(pages),
+ // v0.22: transition/element SFX are timeline audio too — the
+ // dialog's engine note must match what exportVideo will do
+ hasSfxCues: pagesHaveSfxCues(pages),
})
if (live) setEngine(decision)
})()
diff --git a/src/lib/sfx.ts b/src/lib/sfx.ts
index 1d625ca..98ef0fb 100644
--- a/src/lib/sfx.ts
+++ b/src/lib/sfx.ts
@@ -13,10 +13,11 @@
//
// Used by the preview/presenter playback engines (element
// animation SFX at their delay, page-transition SFX on page
-// change) and by the Audio panel's audition buttons. Video export
-// does NOT play sfxId triggers in v1 — documented in
-// docs/SOUND.md; inserted pack sounds as AUDIO ELEMENTS ride the
-// existing export path.
+// change) and by the Audio panel's audition buttons. Since v0.22
+// the video export fires the same triggers onto its recorded audio
+// track (buildSfxCues in video-export.ts — this player stays
+// UI-only; the export schedules decoded buffers on the recorder's
+// audio clock instead of pooling <audio> elements).
// ─────────────────────────────────────────────────────────────
import { isSfxId, sfxUrl } from '@/lib/assets/sfx-pack'
diff --git a/src/lib/video-export.test.ts b/src/lib/video-export.test.ts
index e0079c9..fbd2e6d 100644
--- a/src/lib/video-export.test.ts
+++ b/src/lib/video-export.test.ts
@@ -18,12 +18,14 @@
import { describe, expect, it } from 'vitest'
import {
+ buildSfxCues,
chooseVideoExportEngine,
computeExportSize,
isPlayableExportVideo,
MAX_EXPORT_VIDEOS,
pagesHaveAutoplayAudio,
pagesHaveAutoplayVideo,
+ pagesHaveSfxCues,
windowedSourceTime,
} from './video-export'
import type { PageData } from './types'
@@ -228,3 +230,175 @@ describe('isPlayableExportVideo / pagesHaveAutoplayVideo — the R3 gate', () =>
expect(MAX_EXPORT_VIDEOS).toBe(12)
})
})
+
+// ── v0.22: SFX on the export timeline ─────────────────────────
+
+describe('buildSfxCues — the present-mode triggers on the recorder timeline', () => {
+ const seg = (elements: unknown[], hold: number, transition: number, extra: Record<string, unknown> = {}) => ({
+ page: { ...page(elements), ...extra } as PageData,
+ hold,
+ transition,
+ })
+
+ it('fires the incoming page transition sfx at mount: page 0 at t=0, page i when the transition into it begins', () => {
+ const cues = buildSfxCues([
+ seg([], 3, 0.5, { transition: { kind: 'fade', duration: 0.5, sfxId: 'whoosh-soft' } }),
+ seg([], 2, 0.8, { transition: { kind: 'slide', duration: 0.8, direction: 'left', sfxId: 'chime' } }),
+ seg([], 2, 0),
+ ])
+ // page 0 mounts at 0; page 1 mounts when seg0's hold ends (3.0);
+ // page 2 has no transition sfx
+ expect(cues).toEqual([
+ { id: 'whoosh-soft', t: 0, volume: 0.7, kind: 'transition' },
+ { id: 'chime', t: 3, volume: 0.7, kind: 'transition' },
+ ])
+ })
+
+ it('fires element sfx at the page-local clock crossing each delay (segment start + delay)', () => {
+ const cues = buildSfxCues([
+ seg(
+ [
+ { type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 1.2, easing: 'easeOut', sfxId: 'pop' } },
+ { type: 'rect', visible: true, animation: { kind: 'pan', duration: 0.5, delay: 2.4, easing: 'easeOut', direction: 'left', sfxId: 'thud' } },
+ ],
+ 3,
+ 0.5,
+ ),
+ seg([], 2, 0),
+ ])
+ expect(cues).toEqual([
+ { id: 'pop', t: 1.2, volume: 0.8, kind: 'element' },
+ { id: 'thud', t: 2.4, volume: 0.8, kind: 'element' },
+ ])
+ })
+
+ it('drops what never plays: hidden elements, kind none, unknown ids, cues past the page window', () => {
+ const cues = buildSfxCues([
+ seg(
+ [
+ // hidden → never drawn, never animated
+ { type: 'rect', visible: false, animation: { kind: 'fade', duration: 0.5, delay: 0, easing: 'easeOut', sfxId: 'pop' } },
+ // animation kind 'none' → no trigger
+ { type: 'rect', visible: true, animation: { kind: 'none', duration: 0.5, delay: 0, easing: 'easeOut', sfxId: 'pop' } },
+ // unknown pack id → sanitize-equivalent drop
+ { type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 0, easing: 'easeOut', sfxId: 'not-a-pack-sound' } },
+ // delay lands past the page's whole visible window (start 0 + 10 ≥ hold 3 + transition 0.5)
+ { type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 10, easing: 'easeOut', sfxId: 'thud' } },
+ ],
+ 3,
+ 0.5,
+ { transition: { kind: 'none', duration: 0.5, sfxId: 'chime' } }, // kind none → no transition sound either
+ ),
+ seg([], 2, 0),
+ ])
+ expect(cues).toEqual([])
+ })
+
+ it('collapses same-id retriggers within 60 ms (the player guard), keeps genuinely separate fires', () => {
+ const cues = buildSfxCues([
+ seg(
+ [
+ { type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 1.0, easing: 'easeOut', sfxId: 'pop' } },
+ // 30 ms after the first pop — machine-gun, collapsed
+ { type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 1.03, easing: 'easeOut', sfxId: 'pop' } },
+ // a full second later — a real second hit
+ { type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 2.0, easing: 'easeOut', sfxId: 'pop' } },
+ ],
+ 3,
+ 0,
+ ),
+ seg([], 2, 0),
+ ])
+ expect(cues.map((c) => c.t)).toEqual([1.0, 2.0])
+ })
+
+ it('returns the sheet sorted by fire time regardless of construction order', () => {
+ const cues = buildSfxCues([
+ seg(
+ [
+ { type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 2.0, easing: 'easeOut', sfxId: 'thud' } },
+ ],
+ 3,
+ 0.5,
+ { transition: { kind: 'fade', duration: 0.5, sfxId: 'whoosh-soft' } },
+ ),
+ seg(
+ [
+ { type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 0.5, easing: 'easeOut', sfxId: 'pop' } },
+ ],
+ 2,
+ 0,
+ ),
+ ])
+ // page1 starts at 3.5; its element fires at 4.0 — still after page0's
+ expect(cues.map((c) => c.t)).toEqual([0, 2.0, 4.0])
+ })
+})
+
+describe('pagesHaveSfxCues — the dialog/engine mirror of buildSfxCues', () => {
+ it('a valid transition sfx on a non-none transition counts', () => {
+ expect(
+ pagesHaveSfxCues([{ ...page([]), transition: { kind: 'fade', duration: 0.5, sfxId: 'whoosh-soft' } }]),
+ ).toBe(true)
+ })
+
+ it('a none-kind transition never counts, whatever the id', () => {
+ expect(
+ pagesHaveSfxCues([{ ...page([]), transition: { kind: 'none', duration: 0.5, sfxId: 'whoosh-soft' } }]),
+ ).toBe(false)
+ })
+
+ it('a visible animated element with a pack sound counts; hidden or unknown-id ones do not', () => {
+ expect(
+ pagesHaveSfxCues([
+ page([{ type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 0, easing: 'easeOut', sfxId: 'pop' } }]),
+ ]),
+ ).toBe(true)
+ expect(
+ pagesHaveSfxCues([
+ page([{ type: 'rect', visible: false, animation: { kind: 'fade', duration: 0.5, delay: 0, easing: 'easeOut', sfxId: 'pop' } }]),
+ ]),
+ ).toBe(false)
+ expect(
+ pagesHaveSfxCues([
+ page([{ type: 'rect', visible: true, animation: { kind: 'fade', duration: 0.5, delay: 0, easing: 'easeOut', sfxId: 'nope' } }]),
+ ]),
+ ).toBe(false)
+ })
+
+ it('a design with nothing triggerable stays false', () => {
+ expect(pagesHaveSfxCues([page([]), page([{ type: 'rect', visible: true }])])).toBe(false)
+ })
+})
+
+describe('chooseVideoExportEngine — v0.22 SFX cues are timeline audio', () => {
+ it('SFX cues alone + an audio-muxing recorder rides MediaRecorder', () => {
+ const d = chooseVideoExportEngine({
+ webcodecs: true,
+ mediaRecorder: true,
+ mediaRecorderAudio: true,
+ hasPageAudio: false,
+ hasSfxCues: true,
+ })
+ expect(d.engine).toBe('mediarecorder')
+ expect(d.reason).toContain('SFX')
+ })
+
+ it('SFX cues + WebCodecs but NO audio-capable recorder → WebCodecs, honestly silent', () => {
+ const d = chooseVideoExportEngine({
+ webcodecs: true,
+ mediaRecorder: true,
+ mediaRecorderAudio: false,
+ hasPageAudio: false,
+ hasSfxCues: true,
+ })
+ expect(d.engine).toBe('webcodecs')
+ expect(d.reason).toContain('silent')
+ })
+
+ it('hasSfxCues omitted (pre-v0.22 callers) keeps the old silent-design behaviour', () => {
+ const d = chooseVideoExportEngine({ webcodecs: true, mediaRecorder: true, mediaRecorderAudio: true, hasPageAudio: false })
+ expect(d.engine).toBe('webcodecs')
+ expect(d.reason).toContain('frame-exact')
+ })
+})
diff --git a/src/lib/video-export.ts b/src/lib/video-export.ts
index 23b99ff..7d111e9 100644
--- a/src/lib/video-export.ts
+++ b/src/lib/video-export.ts
@@ -32,6 +32,7 @@ import { stickerDataUrl } from '@/lib/sticker-image'
import { fitFontSize } from '@/lib/text-fit'
import { layoutListLines } from '@/lib/list-text'
import { WebMMuxer } from '@/lib/webm-muxer'
+import { isSfxId, sfxUrl } from '@/lib/assets/sfx-pack'
export interface VideoExportOptions {
designWidth: number
@@ -107,7 +108,15 @@ export function estimateVideoDuration(pages: PageData[]): number {
function loadImage(src: string): Promise<HTMLImageElement | null> {
return new Promise((resolve) => {
- const img = new Image()
+ // v0.22 robustness: node (SSR pass / unit tests) has no Image —
+ // a missing bitmap degrades to the placeholder paths instead of
+ // crashing the whole export (the loadStickerImage posture)
+ const Ctor = (globalThis as { Image?: typeof Image }).Image
+ if (typeof Ctor !== 'function') {
+ resolve(null)
+ return
+ }
+ const img = new Ctor()
img.crossOrigin = 'anonymous'
img.onload = () => resolve(img)
img.onerror = () => resolve(null)
@@ -1049,6 +1058,78 @@ export function pagesHaveAutoplayAudio(pages: PageData[]): boolean {
)
}
+// ── v0.22: SFX on the export timeline ─────────────────────────
+
+/** One scheduled pack sound. Mirrors the present-mode triggers
+ * (preview-stage): the incoming page's transition SFX at 0.7, an
+ * element's animation SFX at 0.8 when the page-local clock
+ * crosses its delay. */
+export interface SfxCue {
+ /** pack catalogue id */
+ id: string
+ /** timeline time (seconds) the sound fires */
+ t: number
+ volume: number
+ kind: 'transition' | 'element'
+}
+
+/** Build the SFX cue sheet for the export timeline — pure, so the
+ * engine decision and the tests can reason about it without a
+ * browser. Semantics (the preview-stage mirror):
+ * - page i's ELEMENT sfx fire at `start_i + delay` — the page's
+ * animation clock runs from its segment start (during the
+ * transition into it the incoming page is drawn frozen at
+ * local 0, so nothing fires early)
+ * - the TRANSITION sfx (stored on the incoming page) fires when
+ * that page mounts: page 0 at t=0, page i at the moment the
+ * transition into it begins (`start_{i-1} + hold_{i-1}`)
+ * - same-id retriggers within 60 ms collapse to the first — the
+ * player's retrigger guard, kept so the sheet is faithful
+ * - a cue past the page's whole visible window is dropped: its
+ * trigger never arrives on screen */
+export function buildSfxCues(segments: TimelineSegment[]): SfxCue[] {
+ const starts: number[] = []
+ let acc = 0
+ for (const s of segments) {
+ starts.push(acc)
+ acc += s.hold + s.transition
+ }
+ const cues: SfxCue[] = []
+ for (let i = 0; i < segments.length; i++) {
+ const seg = segments[i]
+ const start = starts[i]
+ const end = start + seg.hold + seg.transition
+ const tr = seg.page.transition
+ if (tr && tr.kind !== 'none' && isSfxId(tr.sfxId)) {
+ cues.push({ id: tr.sfxId, t: i === 0 ? 0 : starts[i - 1] + segments[i - 1].hold, volume: 0.7, kind: 'transition' })
+ }
+ for (const el of seg.page.elements) {
+ const a = el.animation
+ if (!el.visible || !a || a.kind === 'none' || !isSfxId(a.sfxId)) continue
+ const t = start + Math.max(0, a.delay || 0)
+ if (t < end) cues.push({ id: a.sfxId, t, volume: 0.8, kind: 'element' })
+ }
+ }
+ cues.sort((a, b) => a.t - b.t)
+ const last: Record<string, number> = {}
+ return cues.filter((c) => {
+ if (last[c.id] !== undefined && c.t - last[c.id] < 0.06) return false
+ last[c.id] = c.t
+ return true
+ })
+}
+
+/** Does any page carry a triggerable pack sound? (The dialog's
+ * mirror of what buildSfxCues would schedule — the same facts the
+ * engine decision needs, before a timeline is built.) */
+export function pagesHaveSfxCues(pages: PageData[]): boolean {
+ return pages.some(
+ (p) =>
+ (p.transition?.kind !== 'none' && isSfxId(p.transition?.sfxId)) ||
+ p.elements.some((el) => el.visible && el.animation && el.animation.kind !== 'none' && isSfxId(el.animation.sfxId)),
+ )
+}
+
// ── v0.15 (R3): moving video in exports ──────────────────────
/** Hard cap on simultaneously decoded export videos — each is a live
@@ -1146,6 +1227,11 @@ export interface VideoEngineInputs {
/** the recorder candidate can mux audio (mp4a/opus in its mime) */
mediaRecorderAudio: boolean
hasPageAudio: boolean
+ /** v0.22: the design carries triggerable pack sounds (transition
+ * SFX / element animation SFX) — these also need the audio-muxing
+ * recorder, exactly like page audio. Optional: pre-v0.22 callers
+ * and tests that only know about page audio keep compiling. */
+ hasSfxCues?: boolean
}
export type VideoExportEngineDecision =
@@ -1154,17 +1240,19 @@ export type VideoExportEngineDecision =
| { engine: null; reason: string }
/** The engine matrix, as one pure function (unit-tested):
- * - page audio + a recorder that can mux it → MediaRecorder
- * (the WebCodecs path is silent; Opus-in-WebM via AudioEncoder
- * is a documented post-R3 evaluation)
+ * - timeline audio (page audio OR v0.22 SFX cues) + a recorder
+ * that can mux it → MediaRecorder (the WebCodecs path is
+ * silent; Opus-in-WebM via AudioEncoder is a documented
+ * post-R3 evaluation)
* - WebCodecs available otherwise → WebCodecs (frame-exact)
* - neither → null (exportVideo throws, as before) */
export function chooseVideoExportEngine(inputs: VideoEngineInputs): VideoExportEngineDecision {
- if (inputs.hasPageAudio && inputs.mediaRecorder && inputs.mediaRecorderAudio) {
- return { engine: 'mediarecorder', reason: 'page audio — MediaRecorder muxes it (the WebCodecs path is video-only for now)' }
+ const hasTimelineAudio = inputs.hasPageAudio || (inputs.hasSfxCues ?? false)
+ if (hasTimelineAudio && inputs.mediaRecorder && inputs.mediaRecorderAudio) {
+ return { engine: 'mediarecorder', reason: 'page audio or SFX — MediaRecorder muxes it (the WebCodecs path is video-only for now)' }
}
if (inputs.webcodecs) {
- if (inputs.hasPageAudio) {
+ if (hasTimelineAudio) {
return {
engine: 'webcodecs',
reason: inputs.mediaRecorder
@@ -1507,6 +1595,9 @@ export async function exportVideo(opts: VideoExportOptions): Promise<VideoExport
mediaRecorder: mr !== null,
mediaRecorderAudio: mr?.audio ?? false,
hasPageAudio: pagesHaveAutoplayAudio(opts.pages),
+ // v0.22: pack sounds (transition/element SFX) are timeline audio
+ // too — they ride the same MediaRecorder mux the page audio does
+ hasSfxCues: pagesHaveSfxCues(opts.pages),
})
if (decision.engine === 'webcodecs' && wc.codecId && wc.codecString) {
return exportViaWebCodecs(opts, wc, { fps, width, height, segments, total, totalFrames })
@@ -1675,7 +1766,14 @@ async function exportViaMediaRecorder(
)
let audioCtx: AudioContext | null = null
let audioDest: MediaStreamAudioDestinationNode | null = null
- if (format.audio && segmentAudio.some((els) => els.length)) {
+ // v0.22: the SFX cue sheet — present-mode triggers (the incoming
+ // page's transition sound, element sounds at their animation
+ // delays) mapped onto the recorder's timeline. Pure schedule;
+ // the bytes decode below through the SAME context the page audio
+ // uses, so both flow one audio track.
+ const sfxCues = format.audio ? buildSfxCues(segments) : []
+ const sfxBuffers = new Map<string, AudioBuffer>()
+ if (format.audio && (segmentAudio.some((els) => els.length) || sfxCues.length > 0)) {
try {
const Ctx: typeof AudioContext =
window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext
@@ -1693,6 +1791,28 @@ async function exportViaMediaRecorder(
for (const els of segmentAudio) {
for (const a of els) audioCtx.createMediaElementSource(a).connect(audioDest)
}
+ // v0.22: decode each distinct SFX id ONCE (the media-bag
+ // posture). Individually guarded — a failed fetch or decode
+ // drops that one sound, never the export; bounded like the
+ // element-buffer wait so a dead network still exports.
+ if (sfxCues.length) {
+ const actx: AudioContext = audioCtx
+ await Promise.race([
+ Promise.all(
+ [...new Set(sfxCues.map((c) => c.id))].map(async (id) => {
+ try {
+ const res = await fetch(sfxUrl(id), { signal: AbortSignal.timeout(8000) })
+ if (!res.ok) return
+ const buf = await actx.decodeAudioData(await res.arrayBuffer())
+ sfxBuffers.set(id, buf)
+ } catch {
+ /* that sound stays silent */
+ }
+ }),
+ ),
+ new Promise<void>((r) => setTimeout(r, 4000)),
+ ])
+ }
} catch {
audioCtx = null
audioDest = null
@@ -1772,6 +1892,33 @@ async function exportViaMediaRecorder(
})
const startWall = performance.now()
+ // v0.22: schedule the SFX cue sheet on the audio clock. t0 pairs
+ // with startWall — captured back-to-back, so the residual gap is
+ // far below audibility — and every cue fires as a one-shot
+ // BufferSource at its timeline second. Sounds whose id failed to
+ // decode simply never schedule (the honest-silence posture).
+ if (audioCtx && audioDest && sfxCues.length) {
+ const actx: AudioContext = audioCtx
+ const dest: MediaStreamAudioDestinationNode = audioDest
+ const t0 = actx.currentTime
+ for (const cue of sfxCues) {
+ const buf = sfxBuffers.get(cue.id)
+ if (!buf) continue
+ const when = t0 + Math.max(0, cue.t)
+ if (when <= actx.currentTime) continue // the moment passed (late decode) — never fire late
+ try {
+ const src = actx.createBufferSource()
+ src.buffer = buf
+ const gain = actx.createGain()
+ gain.gain.value = cue.volume
+ src.connect(gain)
+ gain.connect(dest)
+ src.start(when)
+ } catch {
+ /* one bad schedule never kills the export */
+ }
+ }
+ }
const deadline = startWall + total * 1000 + 15_000 // hard safety cap
let frame = 0
let activeSeg = -1