@phil65/demoreel 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/scene.d.ts CHANGED
@@ -1,11 +1,7 @@
1
- /**
2
- * Scenario API on top of Playwright. Every method drives the real page and records what happened
3
- * (cursor samples on the recording clock, action boxes) so zoom regions and the cursor overlay can
4
- * be derived afterwards.
5
- */
6
1
  import type { Locator, Page } from "playwright";
7
2
  import { type Point } from "./motion.ts";
8
- import type { ActionRecord, Caption, CursorSample, Depth, Viewport, ZoomHint } from "./types.ts";
3
+ import type { ActionRecord, Caption, CursorSample, Depth, Viewport, VoiceCue, ZoomHint } from "./types.ts";
4
+ import { type SayDeliveryOptions, type VoiceConfig, type VoiceSynthesizer } from "./voice.ts";
9
5
  /** Minimal recording clock (satisfied by ScreencastRecorder and dry-run clocks). */
10
6
  export interface SceneClock {
11
7
  now(): number;
@@ -112,6 +108,29 @@ export interface PressOptions {
112
108
  /** How long the keycap HUD stays visible (ms). */
113
109
  duration?: number;
114
110
  }
111
+ export interface SayOptions extends SayDeliveryOptions {
112
+ /** Wait for the cue to finish speaking before returning (default `true`; always awaited when a callback `fn` is passed). */
113
+ wait?: boolean;
114
+ /** Extra hold after speech finishes (ms, overrides `voice.padMs`, default `220`). */
115
+ padMs?: number;
116
+ /** Minimum breath gap after any previous cue finishes (ms, overrides `voice.gapMs`, default `250`). */
117
+ gapMs?: number;
118
+ /** Override caption mode for this cue (`"vtt" | "burned" | "off"`). */
119
+ captions?: "vtt" | "burned" | "off";
120
+ /** Shown in timeline.json / marks.json (default: truncated spoken text). */
121
+ label?: string;
122
+ }
123
+ export interface VoiceCueHandle {
124
+ readonly cue: VoiceCue;
125
+ /** Waits until this cue's speech (+ padMs) has finished. */
126
+ done(): Promise<void>;
127
+ /**
128
+ * Waits until the narrator reaches `word` (case-insensitive word match, optionally shifted by
129
+ * `offsetMs`, e.g. `-150` to begin moving the cursor just before the word is spoken).
130
+ * Returns immediately if the clock is already past that timestamp or during dry-runs.
131
+ */
132
+ at(word: string | RegExp, offsetMs?: number): Promise<void>;
133
+ }
115
134
  /** Applies a `data-demoreel-zoom` value to an action's zoom setting. */
116
135
  export declare function applyZoomAnchor(zoom: boolean | ZoomHint, anchor: {
117
136
  value: string;
@@ -120,6 +139,7 @@ export declare class Scene {
120
139
  readonly samples: CursorSample[];
121
140
  readonly actions: ActionRecord[];
122
141
  readonly captions: Caption[];
142
+ readonly voiceCues: VoiceCue[];
123
143
  private cursor;
124
144
  private cursorKind;
125
145
  private cursorBox;
@@ -128,6 +148,10 @@ export declare class Scene {
128
148
  private startRecording;
129
149
  private fast;
130
150
  private clickRipple;
151
+ private voiceConfig;
152
+ private voiceSynthesizer;
153
+ private voiceOutDir;
154
+ private lastVoiceEndMs;
131
155
  pacing: PacingOptions;
132
156
  /** The underlying Playwright page, for anything the Scene API does not cover. */
133
157
  readonly page: Page;
@@ -136,6 +160,9 @@ export declare class Scene {
136
160
  seed?: number;
137
161
  pacing?: Partial<PacingOptions>;
138
162
  clickRipple?: boolean | ClickRippleOptions;
163
+ voice?: VoiceConfig;
164
+ voiceSynthesizer?: VoiceSynthesizer;
165
+ voiceOutDir?: string;
139
166
  fast?: boolean;
140
167
  });
141
168
  private ensureRecording;
@@ -220,4 +247,17 @@ export declare class Scene {
220
247
  duration?: number;
221
248
  wait?: boolean;
222
249
  }): Promise<void>;
250
+ private getVoiceSynthesizer;
251
+ /**
252
+ * Speaks a voiceover line (synthesized & cached via `@phil65/anyvoice`), automatically synced
253
+ * to the recording timeline and muxed into the rendered MP4 (+ `.vtt` subtitles).
254
+ *
255
+ * Three ways to synchronize speech and UI actions:
256
+ * - Standalone beat: `await scene.say("Welcome to FormCAD.")` (holds for speech duration)
257
+ * - Narrate while acting: `await scene.say("Pick Bracket.", async (cue) => { await scene.click(...); })`
258
+ * - Non-blocking: `const cue = await scene.say("...", { wait: false }); ...; await cue.done();`
259
+ */
260
+ say(text: string): Promise<VoiceCueHandle>;
261
+ say(text: string, fn: (cue: VoiceCueHandle) => Promise<void> | void): Promise<VoiceCueHandle>;
262
+ say(text: string, opts: SayOptions, fn?: (cue: VoiceCueHandle) => Promise<void> | void): Promise<VoiceCueHandle>;
223
263
  }
package/dist/scene.js CHANGED
@@ -1,4 +1,12 @@
1
+ /**
2
+ * Scenario API on top of Playwright. Every method drives the real page and records what happened
3
+ * (cursor samples on the recording clock, action boxes) so zoom regions and the cursor overlay can
4
+ * be derived afterwards.
5
+ */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
1
8
  import { easeAimed, makePath, mulberry32, sleep, travelDuration } from "./motion.js";
9
+ import { createVoiceSynthesizer, DEFAULT_VOICE_GAP_MS, DEFAULT_VOICE_PAD_MS, findWordTiming, } from "./voice.js";
2
10
  function isLocator(target) {
3
11
  return typeof target === "object" && target !== null && typeof target.filter === "function";
4
12
  }
@@ -110,6 +118,7 @@ export class Scene {
110
118
  samples = [];
111
119
  actions = [];
112
120
  captions = [];
121
+ voiceCues = [];
113
122
  cursor;
114
123
  cursorKind = "arrow";
115
124
  cursorBox = null;
@@ -118,6 +127,10 @@ export class Scene {
118
127
  startRecording;
119
128
  fast;
120
129
  clickRipple;
130
+ voiceConfig;
131
+ voiceSynthesizer;
132
+ voiceOutDir;
133
+ lastVoiceEndMs = 0;
121
134
  pacing;
122
135
  /** The underlying Playwright page, for anything the Scene API does not cover. */
123
136
  page;
@@ -130,6 +143,9 @@ export class Scene {
130
143
  this.rand = mulberry32(opts.seed ?? 42);
131
144
  this.pacing = { ...DEFAULT_PACING, ...opts.pacing };
132
145
  this.cursor = { x: viewport.width * 0.62, y: viewport.height * 0.72 };
146
+ this.voiceConfig = opts.voice ?? {};
147
+ this.voiceSynthesizer = opts.voiceSynthesizer ?? null;
148
+ this.voiceOutDir = opts.voiceOutDir ?? null;
133
149
  this.clickRipple = opts.clickRipple
134
150
  ? {
135
151
  color: (typeof opts.clickRipple === "object" ? opts.clickRipple.color : undefined) ?? "rgba(96, 165, 250, 0.9)",
@@ -700,4 +716,116 @@ export class Scene {
700
716
  if (opts.wait && !this.fast)
701
717
  await sleep(duration);
702
718
  }
719
+ getVoiceSynthesizer() {
720
+ if (!this.voiceSynthesizer) {
721
+ this.voiceSynthesizer = createVoiceSynthesizer(this.voiceConfig);
722
+ }
723
+ return this.voiceSynthesizer;
724
+ }
725
+ async say(text, optsOrFn, maybeFn) {
726
+ const opts = typeof optsOrFn === "function" ? {} : (optsOrFn ?? {});
727
+ const fn = typeof optsOrFn === "function" ? optsOrFn : maybeFn;
728
+ await this.ensureRecording();
729
+ if (this.voiceConfig.enabled === false) {
730
+ const now = this.now();
731
+ const cue = {
732
+ id: `cue-${String(this.voiceCues.length + 1).padStart(2, "0")}`,
733
+ text,
734
+ startMs: Math.round(now),
735
+ endMs: Math.round(now),
736
+ durationMs: 0,
737
+ audioFile: "",
738
+ timings: [],
739
+ };
740
+ const noop = {
741
+ cue,
742
+ done: async () => { },
743
+ at: async () => { },
744
+ };
745
+ if (fn)
746
+ await fn(noop);
747
+ return noop;
748
+ }
749
+ const synth = this.getVoiceSynthesizer();
750
+ const audio = await synth.synthesize(text, {
751
+ voice: opts.voice,
752
+ speed: opts.speed,
753
+ pitch: opts.pitch,
754
+ volume: opts.volume,
755
+ instructions: opts.instructions,
756
+ });
757
+ // Anti-overlap: wait for any previous still-speaking cue (+ breath gap) before starting.
758
+ const gapMs = opts.gapMs ?? this.voiceConfig.gapMs ?? DEFAULT_VOICE_GAP_MS;
759
+ if (!this.fast && this.lastVoiceEndMs > 0) {
760
+ const waitUntil = this.lastVoiceEndMs + gapMs;
761
+ const remaining = waitUntil - this.now();
762
+ if (remaining > 0)
763
+ await sleep(remaining);
764
+ }
765
+ const startMs = this.now();
766
+ const endMs = startMs + audio.durationMs;
767
+ const id = `cue-${String(this.voiceCues.length + 1).padStart(2, "0")}`;
768
+ let audioFile = "";
769
+ if (this.voiceOutDir) {
770
+ fs.mkdirSync(this.voiceOutDir, { recursive: true });
771
+ const rel = path.join("voice", `${id}.wav`);
772
+ fs.writeFileSync(path.join(this.voiceOutDir, `${id}.wav`), audio.wav);
773
+ audioFile = rel;
774
+ }
775
+ const cue = {
776
+ id,
777
+ text,
778
+ startMs: Math.round(startMs),
779
+ endMs: Math.round(endMs),
780
+ durationMs: Math.round(audio.durationMs),
781
+ audioFile,
782
+ timings: audio.timings,
783
+ };
784
+ this.voiceCues.push(cue);
785
+ this.lastVoiceEndMs = endMs;
786
+ const captionsMode = opts.captions ?? this.voiceConfig.captions ?? "vtt";
787
+ if (captionsMode === "burned") {
788
+ this.captions.push({ text, startMs, endMs });
789
+ }
790
+ const padMs = opts.padMs ?? this.voiceConfig.padMs ?? DEFAULT_VOICE_PAD_MS;
791
+ let wordCursor = 0;
792
+ const handle = {
793
+ cue,
794
+ done: async () => {
795
+ if (this.fast)
796
+ return;
797
+ const remaining = endMs + padMs - this.now();
798
+ if (remaining > 0)
799
+ await sleep(remaining);
800
+ },
801
+ at: async (word, offsetMs = 0) => {
802
+ if (this.fast)
803
+ return;
804
+ const hit = findWordTiming(cue.timings, word, wordCursor);
805
+ if (!hit)
806
+ return;
807
+ wordCursor = hit.index + 1;
808
+ const targetMs = startMs + hit.timing.offsetMs + offsetMs;
809
+ const remaining = targetMs - this.now();
810
+ if (remaining > 0)
811
+ await sleep(remaining);
812
+ },
813
+ };
814
+ const label = opts.label ?? (text.length > 52 ? `${text.slice(0, 49)}...` : text);
815
+ if (fn) {
816
+ const tAct = this.now();
817
+ await fn(handle);
818
+ cue.actionDurationMs = Math.round(this.now() - tAct);
819
+ await handle.done();
820
+ this.record({ kind: "say", startMs, arriveMs: startMs, endMs: Math.max(endMs, this.now()), text, label });
821
+ }
822
+ else if (opts.wait !== false) {
823
+ await handle.done();
824
+ this.record({ kind: "say", startMs, arriveMs: startMs, endMs: Math.max(endMs, this.now()), text, label });
825
+ }
826
+ else {
827
+ this.record({ kind: "say", startMs, arriveMs: startMs, endMs, text, label });
828
+ }
829
+ return handle;
830
+ }
703
831
  }
package/dist/types.d.ts CHANGED
@@ -21,7 +21,7 @@ export interface CursorSample {
21
21
  interactionType?: "move" | "click" | "mouseup";
22
22
  assetId?: string | null;
23
23
  }
24
- export type ActionKind = "goto" | "click" | "select" | "drag" | "type" | "hover" | "scroll" | "pause" | "caption" | "press" | "move" | "zoom" | "highlight";
24
+ export type ActionKind = "goto" | "click" | "select" | "drag" | "type" | "hover" | "scroll" | "pause" | "caption" | "press" | "move" | "zoom" | "highlight" | "say";
25
25
  /** One scripted step, as it actually happened during recording. */
26
26
  export interface ActionRecord {
27
27
  kind: ActionKind;
@@ -91,6 +91,31 @@ export interface SpeedRegion {
91
91
  endMs: number;
92
92
  speed: number;
93
93
  }
94
+ export interface WordTiming {
95
+ text: string;
96
+ /** Start offset relative to the beginning of this voice cue (ms). */
97
+ offsetMs: number;
98
+ /** Word duration (ms). */
99
+ durationMs: number;
100
+ /** True when estimated proportionally rather than reported natively by the TTS engine. */
101
+ estimated: boolean;
102
+ }
103
+ export interface VoiceCue {
104
+ id: string;
105
+ text: string;
106
+ /** Recording-clock start time (ms). */
107
+ startMs: number;
108
+ /** Recording-clock end time (ms, `startMs + durationMs`). */
109
+ endMs: number;
110
+ /** Exact synthesized audio duration (ms). */
111
+ durationMs: number;
112
+ /** Relative path to the `.wav` clip inside the output directory (e.g. `voice/cue-01.wav`). */
113
+ audioFile: string;
114
+ /** Word-level timestamps relative to `startMs`. */
115
+ timings: WordTiming[];
116
+ /** Duration of the paired action callback in `scene.say(text, fn)` (ms), if any. */
117
+ actionDurationMs?: number;
118
+ }
94
119
  export interface RecordingResult {
95
120
  videoPath: string;
96
121
  durationMs: number;
@@ -100,6 +125,7 @@ export interface RecordingResult {
100
125
  samples: CursorSample[];
101
126
  actions: ActionRecord[];
102
127
  captions: Caption[];
128
+ voiceCues?: VoiceCue[];
103
129
  /** Recording-clock times (ms) of every captured screencast frame (= a visual change). */
104
130
  frameTimes: number[];
105
131
  frameCount: number;
@@ -0,0 +1,88 @@
1
+ import type { SpeedRegion, TrimRegion, VoiceCue, WordTiming } from "./types.ts";
2
+ export type VoiceProviderName = "edge" | "openai" | "elevenlabs";
3
+ export interface VoiceConfig {
4
+ /** TTS provider (default `"edge"` — free, no API key required). */
5
+ provider?: VoiceProviderName;
6
+ /** Provider voice ID (e.g. `"en-US-AndrewMultilingualNeural"`, `"nova"`). */
7
+ voice?: string;
8
+ /** Provider model (e.g. `"gpt-4o-mini-tts"`, `"tts-1"`, `"eleven_flash_v2_5"`). */
9
+ model?: string;
10
+ /** API key override (defaults to `OPENAI_API_KEY` / `ELEVENLABS_API_KEY`). */
11
+ apiKey?: string;
12
+ /** Custom base URL for OpenAI-compatible servers (e.g. local Kokoro/Speaches) or ElevenLabs. */
13
+ baseUrl?: string;
14
+ /** Default speech speed multiplier (`1.0` = normal). */
15
+ speed?: number;
16
+ /** Default pitch offset in Hz (`0` = neutral). */
17
+ pitch?: number;
18
+ /** Default volume multiplier (`1.0` = normal). */
19
+ volume?: number;
20
+ /** Default natural-language delivery instructions (OpenAI `gpt-4o-mini-tts`). */
21
+ instructions?: string;
22
+ /** Minimum silence gap between chained `scene.say()` cues (ms, default `250`). */
23
+ gapMs?: number;
24
+ /** Extra hold after a blocking cue finishes speaking (ms, default `220`). */
25
+ padMs?: number;
26
+ /** Subtitle mode: `"vtt"` (default sidecar `.vtt`), `"burned"` (also draw on-video caption), or `"off"`. */
27
+ captions?: "vtt" | "burned" | "off";
28
+ /** SHA-256 disk cache directory (default `.demoreel/voice-cache`). */
29
+ cacheDir?: string;
30
+ /** Set to `false` to skip TTS synthesis (e.g. `--no-voice`). */
31
+ enabled?: boolean;
32
+ }
33
+ export interface SayDeliveryOptions {
34
+ voice?: string;
35
+ speed?: number;
36
+ pitch?: number;
37
+ volume?: number;
38
+ instructions?: string;
39
+ }
40
+ export interface SynthesizedCue {
41
+ wav: Buffer;
42
+ durationMs: number;
43
+ sampleRate: number;
44
+ channels: number;
45
+ timings: WordTiming[];
46
+ }
47
+ /** Minimal synthesis backend interface (implemented by `@phil65/anyvoice`, mockable in tests). */
48
+ export interface VoiceSynthesizer {
49
+ synthesize(text: string, opts?: SayDeliveryOptions): Promise<SynthesizedCue>;
50
+ }
51
+ export interface VoiceFinding {
52
+ severity: "error" | "warning";
53
+ code: string;
54
+ message: string;
55
+ cueId?: string;
56
+ }
57
+ export declare const DEFAULT_VOICE_GAP_MS = 250;
58
+ export declare const DEFAULT_VOICE_PAD_MS = 220;
59
+ /** Creates a cached `@phil65/anyvoice` synthesizer from a `VoiceConfig`. */
60
+ export declare function createVoiceSynthesizer(config?: VoiceConfig, defaultCacheDir?: string): VoiceSynthesizer;
61
+ /** Matches a word in `timings` (case-insensitive, stripping outer punctuation) starting at `fromIndex`. */
62
+ export declare function findWordTiming(timings: WordTiming[], query: string | RegExp, fromIndex?: number): {
63
+ timing: WordTiming;
64
+ index: number;
65
+ } | null;
66
+ /** Builds a WebVTT subtitle file from voice cues, mapped onto rendered output timestamps. */
67
+ export declare function buildVoiceVtt(cues: VoiceCue[], trims?: TrimRegion[], speeds?: SpeedRegion[], wordsPerCue?: number): string;
68
+ /**
69
+ * Mixes all voice cue `.wav` files into an AAC audio track at their post-trim output timestamps
70
+ * and stream-copies the video (`-c:v copy`) so OpenScreen's H.264 output is never re-encoded.
71
+ */
72
+ export declare function muxVoiceTrack(videoPath: string, cues: VoiceCue[], baseDir: string, opts?: {
73
+ trims?: TrimRegion[];
74
+ speeds?: SpeedRegion[];
75
+ writeVtt?: boolean;
76
+ }): Promise<{
77
+ audioMuxed: boolean;
78
+ vttPath?: string;
79
+ }>;
80
+ /**
81
+ * Automated audio/sync checks so an agent (which cannot listen to the MP4) gets deterministic
82
+ * feedback on overlaps, clipping, trim collisions, and speech↔action pacing mismatches.
83
+ */
84
+ export declare function lintVoiceCues(cues: VoiceCue[], outputDurationMs: number, trims?: TrimRegion[], speeds?: SpeedRegion[]): VoiceFinding[];
85
+ /** Dry-run voice summary (reports exact synthesized durations & word counts without false wall-clock overlap checks). */
86
+ export declare function formatDryRunVoiceSummary(cues: VoiceCue[]): string;
87
+ /** Human- and agent-readable summary of voice cues and sync lint findings. */
88
+ export declare function formatVoiceSummary(cues: VoiceCue[], outputDurationMs: number, trims?: TrimRegion[], speeds?: SpeedRegion[]): string;