@motionhub/runtime 0.7.0 → 0.8.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.
Files changed (4) hide show
  1. package/README.md +12 -3
  2. package/index.d.ts +27 -8
  3. package/index.js +85 -19
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -51,6 +51,14 @@ check it scene by scene without running it:
51
51
  (without one, an equal share of the time to the next line that gives its `at`, or to the scene's end), so lines that give no time share
52
52
  their scene evenly. `<Film captions>` draws the line being said as a `<Caption>`, over everything, fading in and out; `<Caption line="id">`
53
53
  draws one line's caption where a component wants it, while that line is said.
54
+ - **A narration**: `<Film voice="provider:name">` names the voice a film's lines are spoken in, and the engine that speaks them gives each
55
+ voiced line's speech in its runtime (`voice: {[line id]: {seconds, words: [{text, start, end}]}}`, word times into the speech). A voiced
56
+ line lasts as long as its speech, after a lead (0.4 s, before a scene's first line) or a hold (0.4 s, between lines) when it gives no
57
+ `at` (`NARRATION`); its `dur` gives way to the speech. Speech that runs past its scene's end, or into the next line that gives its `at`,
58
+ is cut there, and the line says by how much (`over`), for the engine to tell; lines it leaves no time are said where it ends, in none.
59
+ Speech never makes the outline fail, since its length is the engine's; times the author wrote that cannot all hold still do. A voiced line in the outline has `voiced` and its `words`, in the film's seconds. `useLine(id)` gives a
60
+ line's `{start, end, words}` in its scene's time, so a picture can move with what is said; `<Film captions="words">` draws a voiced line
61
+ word by word, each full once it is said.
54
62
  - **`<Sound src at dur trim loop volume fadeIn fadeOut duck>`**: a sound the film plays, the file `src` (a path the engine serves), from
55
63
  `at` seconds of its scene, or of the film when it is one of `<Film>`'s own; `dur` seconds of it, from `trim` seconds into the file (the
56
64
  whole file when left out); with `loop`, again and again to the end of its scene or of the film; at `volume` dB (0 is the file as it is),
@@ -61,8 +69,9 @@ check it scene by scene without running it:
61
69
  engine that places each scene itself. A Remotion project exported from the Open Motion Studio puts each scene in a `Series.Sequence`
62
70
  this way, so the scenes are named clips on Remotion Studio's timeline. A scene the film does not have is an error.
63
71
  - `filmOutline(children, {width, height})` reads that structure from the elements themselves, without drawing them: `{seconds, scenes:
64
- [{id, start, duration, layers, lines, sounds}], layers, sounds, captions}`, each line `{id, text, start, end}` and each sound `{src, at, dur, until, trim, loop, volume, fadeIn, fadeOut,
65
- duck?}` in the film's seconds (`dur` null for the whole file). `<Film>` reports it to the engine's `onFilm` while it is drawn, once for each structure (a new `onFilm` function on every
72
+ [{id, start, duration, layers, lines, sounds}], layers, sounds, captions, voice}`, each line `{id, text, start, end}` (and, voiced,
73
+ `voiced`, `words` and `over`) and each sound `{src, at, dur, until, trim, loop, volume, fadeIn, fadeOut,
74
+ duck?}` in the film's seconds (`dur` null for the whole file). A line's and a word's times are in whole milliseconds. `<Film>` reports it to the engine's `onFilm` while it is drawn, once for each structure (a new `onFilm` function on every
66
75
  render is not called again for the same structure), when its value has one. A scene without an
67
76
  id or a positive duration, an id used twice (scenes, lines, layers in one scene, the film's own layers), a sound without a `src`, a line
68
77
  that starts past its scene's end or before the line before it ends, lines that would be left no time, and a time that is no number of
@@ -72,4 +81,4 @@ check it scene by scene without running it:
72
81
 
73
82
  `@motionhub/runtime/sound` synthesises a motion's sound, with no React and no audio API: `renderSound({seconds, cues, sound, rate})` returns mono samples from the motion's `react/sound.json` (a bed at a tempo, and a voice for each role: `land`, `move`, `draw`, `count`, `cut`, `out`) and a list of cues (`[{at, role, dur}]`, a reel's `export const cues`). The same input gives the same samples, so a player plays them and a renderer can write them to a WAV for Remotion's `<Audio>` or a HyperFrames track.
74
83
 
75
- An engine binding passes `<MotionRuntimeProvider value>` an object with `useTime` and `useCompositionTime` (hooks returning seconds), `fps`, `width`, `height`, `tokens` (resolved), if it plays video `Video`, and, if it wants a `<Film>`'s structure, `onFilm(outline)`.
84
+ An engine binding passes `<MotionRuntimeProvider value>` an object with `useTime` and `useCompositionTime` (hooks returning seconds), `fps`, `width`, `height`, `tokens` (resolved), if it plays video `Video`, if it wants a `<Film>`'s structure, `onFilm(outline)`, and, if it speaks the film's lines, `voice`.
package/index.d.ts CHANGED
@@ -28,6 +28,8 @@ export type MotionRuntime = {
28
28
  Video?: FC<VideoProps>;
29
29
  /** called with a <Film>'s structure when it is drawn */
30
30
  onFilm?(outline: FilmOutline): void;
31
+ /** Each voiced line's speech, by line id: how long it is and its words, each from and to seconds into it */
32
+ voice?: Record<string, {seconds: number; words?: {text: string; start: number; end: number}[]}>;
31
33
  };
32
34
  export declare const MotionRuntimeProvider: FC<{value: MotionRuntime; children?: ReactNode}>;
33
35
 
@@ -41,7 +43,7 @@ export declare const MotionRoot: FC<{tokens?: Tokens; style?: CSSProperties; chi
41
43
  /** Its children drawn in another motion: its tokens (a tokens.json, or resolved), keeping the engine's time; one per scene or part of a frame */
42
44
  export declare const MotionScope: FC<{tokens: unknown; root?: boolean; children?: ReactNode}>;
43
45
  /** One spoken line, styled by the caption tokens; with `line`, that line of the film's, while it is said */
44
- export declare const Caption: FC<{line?: string; children?: ReactNode; opacity?: number; style?: CSSProperties}>;
46
+ export declare const Caption: FC<{line?: string; words?: boolean; children?: ReactNode; opacity?: number; style?: CSSProperties}>;
45
47
 
46
48
  export type EasingFn = (x: number) => number;
47
49
  export declare const Easing: {linear: EasingFn; bezier(x1: number, y1: number, x2: number, y2: number): EasingFn; inOutSine: EasingFn; outCubic: EasingFn; outQuart: EasingFn; inOutCubic: EasingFn; outBack: EasingFn};
@@ -61,14 +63,31 @@ export type FilmOutline = {
61
63
  scenes: {id: string; start: number; duration: number; layers: LayerBox[]; lines: FilmLine[]; sounds: FilmSound[]}[];
62
64
  layers: LayerBox[];
63
65
  sounds: FilmSound[];
64
- /** Whether the film draws its lines as captions */
65
- captions: boolean;
66
+ /** Whether the film draws its lines as captions, whole or word by word */
67
+ captions: boolean | 'words';
68
+ /** The film's voice, `provider:name`, or null */
69
+ voice: string | null;
66
70
  };
67
- /** A line of a scene, and when it is said, in the film's seconds */
68
- export type FilmLine = {id: string; text: string; start: number; end: number};
69
- export declare function filmOutline(children: ReactNode, frame?: {width?: number; height?: number; captions?: boolean}): FilmOutline;
70
- /** Its <Scene>s laid end to end, each drawn in its span on its own clock; anything else drawn across them all; with `captions`, its lines as captions */
71
- export declare const Film: FC<{captions?: boolean; children?: ReactNode}>;
71
+ /** A word of a voiced line, and when it is said */
72
+ export type FilmWord = {text: string; start: number; end: number};
73
+ /**
74
+ * A line of a scene, and when it is said, in the film's seconds; a voiced one with its words, and `over`, the seconds of its speech
75
+ * past its scene's end
76
+ */
77
+ export type FilmLine = {id: string; text: string; start: number; end: number; voiced?: true; words?: FilmWord[]; over?: number};
78
+ /** How long a scene waits before its first spoken line, and between spoken lines, in seconds */
79
+ export declare const NARRATION: {lead: number; hold: number};
80
+ /** When a line is said, in its scene's time (as useTime() counts there), with its words where it is voiced */
81
+ export declare function useLine(id: string): {start: number; end: number; words: FilmWord[]};
82
+ export declare function filmOutline(
83
+ children: ReactNode,
84
+ frame?: {width?: number; height?: number; captions?: boolean | 'words'; voice?: MotionRuntime['voice']; speaker?: string},
85
+ ): FilmOutline;
86
+ /**
87
+ * Its <Scene>s laid end to end, each drawn in its span on its own clock; anything else drawn across them all; with `captions`, its lines as
88
+ * captions (`"words"`: word by word, where they are voiced); `voice`, the voice its lines are spoken in (`provider:name`)
89
+ */
90
+ export declare const Film: FC<{captions?: boolean | 'words'; voice?: string; children?: ReactNode}>;
72
91
  export declare const Scene: FC<{id: string; duration: number; children?: ReactNode}>;
73
92
  /** A box of the frame (`x`, `y`, `w`, `h` in pixels, the whole frame when left out), stacked by `z`, shown for its whole scene */
74
93
  export declare const Layer: FC<{id: string; x?: number; y?: number; w?: number; h?: number; z?: number; style?: CSSProperties; children?: ReactNode}>;
package/index.js CHANGED
@@ -157,18 +157,38 @@ const sound = (e, start, until) => {
157
157
  };
158
158
  };
159
159
 
160
+ /** How long a scene waits before its first spoken line, and between spoken lines, in seconds */
161
+ export const NARRATION = {lead: 0.4, hold: 0.4};
162
+
163
+ /** A line's clip as the engine gives it (`voice[id]`): its length in seconds and its words, each from and to seconds into it */
164
+ const clipOf = (where, clip) => {
165
+ if (clip === undefined) return undefined;
166
+ if (!clip || !(Number.isFinite(clip.seconds) && clip.seconds > 0)) throw new Error(`${where}: its voice is no length of speech`);
167
+ // Within the speech, and each ending after it starts: an engine's word times can be a little off.
168
+ const within = (t) => Math.min(clip.seconds, Math.max(0, t));
169
+ const words = Array.isArray(clip.words)
170
+ ? clip.words
171
+ .filter((w) => w && typeof w.text === 'string' && Number.isFinite(w.start) && Number.isFinite(w.end) && w.end >= w.start)
172
+ .map((w) => ({text: w.text, start: within(w.start), end: within(w.end)}))
173
+ : [];
174
+ return {seconds: clip.seconds, words};
175
+ };
176
+
160
177
  /**
161
178
  * When each of a scene's lines is said, `start` and `end` in the film's seconds. A line's `at` is seconds into its scene,
162
179
  * and without one it starts where the line before it ends (the first, at the scene's start); a line without `dur` takes an
163
180
  * equal share of the time to the next line that gives its `at`, or to the scene's end. So lines that give no time share
164
- * their scene evenly.
181
+ * their scene evenly. A line the engine has a voice for (`voice[id]`) lasts as long as its speech, after a lead (the first)
182
+ * or a hold (the rest) when it gives no `at`; speech that runs past the scene's end is cut there, and `over` says by how much.
165
183
  */
166
- const timeLines = (lines, start, duration) => {
167
- const given = lines.map((e) => {
184
+ const timeLines = (lines, start, duration, voice = {}) => {
185
+ const given = lines.map((e, i) => {
168
186
  const where = `<Line id="${e.props.id}">`;
169
187
  const at = seconds(where, 'at', e.props.at, undefined);
170
188
  if (at !== undefined && at >= duration) throw new Error(`${where}: at is ${at} s, past the end of its scene (${duration} s)`);
171
- return {where, at, dur: seconds(where, 'dur', e.props.dur, undefined, {above: true})};
189
+ const clip = clipOf(where, voice[e.props.id]);
190
+ if (clip) return {where, at, dur: clip.seconds, gap: at === undefined ? (i === 0 ? NARRATION.lead : NARRATION.hold) : 0, clip};
191
+ return {where, at, dur: seconds(where, 'dur', e.props.dur, undefined, {above: true}), gap: 0};
172
192
  });
173
193
  // Lines are said in the order they are written.
174
194
  let last = -Infinity;
@@ -188,18 +208,38 @@ const timeLines = (lines, start, duration) => {
188
208
  if (from < cursor - 1e-9) throw new Error(`${given[i].where}: at is ${from} s, before the line before it ends (${round(cursor)} s into the scene)`);
189
209
  const to = next < given.length ? given[next].at : duration;
190
210
  const run = given.slice(i, next);
191
- const fixed = run.reduce((sum, g) => sum + (g.dur ?? 0), 0);
211
+ const fixed = run.reduce((sum, g) => sum + (g.dur ?? 0) + g.gap, 0);
192
212
  const free = run.filter((g) => g.dur === undefined);
193
213
  const left = to - from - fixed;
194
- // Lines that give no time would be said in none, and never shown.
195
- if (free.length && left <= 1e-9) {
214
+ // Lines that give no time would be said in none, and never shown: the author's to fix, unless it is speech that takes the time,
215
+ // whose length the author does not write. Then they are said where it ends, in what is left, and none if nothing is.
216
+ if (free.length && left <= 1e-9 && !run.some((g) => g.clip)) {
196
217
  throw new Error(`${free[0].where}: no time is left for it before ${next < given.length ? `${given[next].where} at ${to} s` : `the end of its scene (${to} s)`}; give it an at, or shorten the lines before it`);
197
218
  }
198
- const share = free.length ? left / free.length : 0;
219
+ const share = free.length ? Math.max(0, left) / free.length : 0;
199
220
  cursor = from;
200
221
  for (const g of run) {
201
- const end = Math.min(duration, cursor + (g.dur ?? share));
202
- times.push({start: start + cursor, end: start + end});
222
+ // Speech is cut where the next line that gives its at begins, or the scene ends, and says by how much (over); a dur the
223
+ // author wrote runs on, and one that runs into the next line is an error there.
224
+ const limit = g.clip ? to : duration;
225
+ const begin = Math.min(limit, cursor + g.gap);
226
+ const wanted = begin + (g.dur ?? share);
227
+ const end = Math.min(limit, wanted);
228
+ const at = start + begin;
229
+ // In whole milliseconds, so the times read as written and add up as they should.
230
+ times.push({
231
+ start: round(at),
232
+ end: round(start + end),
233
+ ...(g.clip
234
+ ? {
235
+ voiced: true,
236
+ words: g.clip.words
237
+ .filter((w) => begin + w.start < end)
238
+ .map((w) => ({text: w.text, start: round(at + w.start), end: round(at + Math.min(w.end, end - begin))})),
239
+ ...(wanted - limit > 1e-9 ? {over: round(wanted - limit)} : {}),
240
+ }
241
+ : {}),
242
+ });
203
243
  cursor = end;
204
244
  }
205
245
  i = next;
@@ -214,7 +254,10 @@ const timeLines = (lines, start, duration) => {
214
254
  * film's seconds. `layers` and `sounds` are the film's own, across every scene. A scene without an id or a positive duration, an id used
215
255
  * twice where it must be unique, and a sound with no file or a time that is no number of seconds, are errors.
216
256
  */
217
- export function filmOutline(children, {width = 1920, height = 1080, captions = false} = {}) {
257
+ export function filmOutline(children, {width = 1920, height = 1080, captions = false, voice = {}, speaker} = {}) {
258
+ if (speaker !== undefined && !(typeof speaker === 'string' && /^[\w.-]+:\S+$/.test(speaker))) {
259
+ throw new Error(`<Film voice="${speaker}">: a voice is its provider and its name, as voice="edge:en-US-AriaNeural"`);
260
+ }
218
261
  const box = (e) => ({id: named('Layer', e.props.id), x: e.props.x ?? 0, y: e.props.y ?? 0, w: e.props.w ?? width, h: e.props.h ?? height, z: e.props.z ?? 0});
219
262
  const unique = (what, items) => {
220
263
  const seen = new Set();
@@ -237,7 +280,7 @@ export function filmOutline(children, {width = 1920, height = 1080, captions = f
237
280
  if (!(Number.isFinite(duration) && duration > 0)) throw new Error(`<Scene id="${id}"> needs its duration in seconds: duration={4}`);
238
281
  const inner = elements(e.props.children).filter(isValidElement);
239
282
  const said = inner.filter((c) => c.type === Line);
240
- const times = timeLines(said, start, duration);
283
+ const times = timeLines(said, start, duration, voice ?? {});
241
284
  const lines = said.map((c, i) => ({id: named('Line', c.props.id), text: c.props.text ?? words(c.props.children), ...times[i]}));
242
285
  const sounds = inner.filter((c) => c.type === Sound).map((c) => sound(c, start, start + duration));
243
286
  scenes.push({id, start, duration, layers: unique(`layers in scene "${id}"`, inner.filter((c) => c.type === Layer).map(box)), lines, sounds});
@@ -257,7 +300,14 @@ export function filmOutline(children, {width = 1920, height = 1080, captions = f
257
300
  const taken = scene.layers.find((layer) => layers.some((own) => own.id === layer.id));
258
301
  if (taken) throw new Error(`scene "${scene.id}" has a layer called "${taken.id}", the name of one of the film's own layers`);
259
302
  }
260
- return {seconds: start, scenes, layers, sounds: own.map((e) => sound(e, 0, start)), captions: captions === true};
303
+ return {
304
+ seconds: start,
305
+ scenes,
306
+ layers,
307
+ sounds: own.map((e) => sound(e, 0, start)),
308
+ captions: captions === true || captions === 'words' ? captions : false,
309
+ voice: speaker ?? null,
310
+ };
261
311
  }
262
312
 
263
313
  /**
@@ -265,12 +315,12 @@ export function filmOutline(children, {width = 1920, height = 1080, captions = f
265
315
  * at the film's end), and anything else among its children (a <Layer>, a background) drawn across them all. It reports its structure
266
316
  * (filmOutline) to the engine's `onFilm`, if the engine has one, while it is drawn: the engine learns the length from the scenes.
267
317
  */
268
- export const Film = ({captions = false, children}) => {
318
+ export const Film = ({captions = false, voice, children}) => {
269
319
  const r = runtime();
270
320
  // Read on every frame (it is cheap: a film's children are new elements each frame), and reported while drawing, once for each
271
321
  // structure, whether or not the engine's onFilm is the same function each time: an engine that renders the film once, off the
272
322
  // page, learns it before the first frame is shown.
273
- const outline = filmOutline(children, {...r, captions});
323
+ const outline = filmOutline(children, {...r, captions, voice: r.voice, speaker: voice});
274
324
  const reported = JSON.stringify(outline);
275
325
  const onFilm = r.onFilm;
276
326
  useMemo(() => onFilm?.(JSON.parse(reported)), [reported]); // eslint-disable-line react-hooks/exhaustive-deps
@@ -284,7 +334,7 @@ export const Film = ({captions = false, children}) => {
284
334
  const engine = only === null ? r : {...r, useTime: r.useCompositionTime};
285
335
  // The film's time, for its lines: the engine's, or, drawn as one scene, that scene's start on from the engine's.
286
336
  const now = only === null ? t : (outline.scenes.find((scene) => scene.id === only)?.start ?? 0) + t;
287
- const lines = outline.scenes.flatMap((scene) => scene.lines);
337
+ const lines = outline.scenes.flatMap((scene) => scene.lines.map((line) => ({...line, scene: scene.start})));
288
338
  const spoken = lines.find((line) => now >= line.start && now < line.end);
289
339
  let index = 0;
290
340
  return createElement(Runtime.Provider, {value: engine}, createElement(InFilm.Provider, {value: true}, createElement(Said.Provider, {value: {lines, now}}, elements(children).map((e) => {
@@ -297,11 +347,23 @@ export const Film = ({captions = false, children}) => {
297
347
  const value = {...r, useTime: () => r.useTime() - scene.start};
298
348
  return createElement(Runtime.Provider, {key, value}, e);
299
349
  }), captions && spoken ? createElement('div', {key: 'captions', style: {position: 'absolute', inset: 0, zIndex: 2147483647, pointerEvents: 'none'}},
300
- createElement(Caption, {line: spoken.id})) : null)));
350
+ createElement(Caption, {line: spoken.id, words: outline.captions === 'words'})) : null)));
301
351
  };
302
352
 
303
353
  /** The film's lines and its time, for a <Caption line> anywhere in it */
304
354
  const Said = createContext(null);
355
+
356
+ /**
357
+ * When a line of the film is said, in the time of its scene (as useTime() counts there): `{start, end, words}`, each word `{text, start,
358
+ * end}` where the engine has its voice (none otherwise). So a picture can move with what is said: `const {start} = useLine('intro-1')`.
359
+ */
360
+ export const useLine = (id) => {
361
+ const said = useContext(Said);
362
+ const line = said?.lines.find((l) => l.id === id);
363
+ if (!line) throw new Error(`useLine("${id}"): ${said ? 'the film has no line by that id' : 'a line is read inside a <Film>'}`);
364
+ const shift = (t) => round(t - line.scene);
365
+ return {start: shift(line.start), end: shift(line.end), words: (line.words ?? []).map((w) => ({text: w.text, start: shift(w.start), end: shift(w.end)}))};
366
+ };
305
367
  /** How long a line's caption takes to come and go, in seconds */
306
368
  const CAPTION_FADE = 0.15;
307
369
 
@@ -370,7 +432,7 @@ export const MotionScope = ({tokens, root = true, children}) => {
370
432
  * `opacity` fades it; it stays a function of what you pass. With `line`, the id of one of its <Film>'s lines, it draws that line's words while
371
433
  * it is said, fading in and out, and nothing at other times.
372
434
  */
373
- export const Caption = ({line, children, opacity = 1, style}) => {
435
+ export const Caption = ({line, words = false, children, opacity = 1, style}) => {
374
436
  // Both read before anything branches, so a caption calls the same hooks with a line or without.
375
437
  const said = useContext(Said);
376
438
  const c = useTokens().caption ?? {};
@@ -379,7 +441,11 @@ export const Caption = ({line, children, opacity = 1, style}) => {
379
441
  if (!spoken) throw new Error(`<Caption line="${line}">: ${said ? 'the film has no line by that id' : 'a caption of a line is drawn inside a <Film>'}`);
380
442
  const fade = Math.min(1, (said.now - spoken.start) / CAPTION_FADE, (spoken.end - said.now) / CAPTION_FADE);
381
443
  if (fade <= 0) return null;
382
- return createElement(Caption, {opacity: opacity * fade, style}, children ?? spoken.text);
444
+ // Word by word, where the line is voiced: each word full once it is said, the rest waiting faint.
445
+ const shown = words && spoken.words?.length
446
+ ? spoken.words.map((w, i) => createElement('span', {key: i, style: {opacity: said.now >= w.start ? 1 : 0.35}}, `${i ? ' ' : ''}${w.text}`))
447
+ : spoken.text;
448
+ return createElement(Caption, {opacity: opacity * fade, style}, children ?? shown);
383
449
  }
384
450
  const py = c['padding-y'] ?? 10, pad = `${py}px ${c['padding-x'] ?? 26}px`;
385
451
  const rule = c['rule-left']
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@motionhub/runtime",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "What a motion's React components draw with (time, frame, tokens, seeded randomness, video, caption), and a film of scenes and sounds, in any engine that provides it.",
5
5
  "license": "MIT",
6
6
  "repository": {