@hyperframes/core 0.9.91 → 0.9.93

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 (36) hide show
  1. package/dist/audioAnalysis.d.ts +3 -0
  2. package/dist/audioAnalysis.js +18 -1
  3. package/dist/audioCarve.js +15 -24
  4. package/dist/audioDecode.d.ts +22 -0
  5. package/dist/audioDecode.js +64 -0
  6. package/dist/audioLeveller.js +3 -17
  7. package/dist/beats/beatDetection.js +2 -3
  8. package/dist/clipFacts.d.ts +5 -0
  9. package/dist/clipFacts.js +21 -6
  10. package/dist/compositionSource.d.ts +2 -0
  11. package/dist/compositionSource.js +5 -0
  12. package/dist/generated/runtime-inline.js +1 -1
  13. package/dist/hyperframe.runtime.iife.js +69 -69
  14. package/dist/runtime/editing/gsapSet.d.ts +3 -1
  15. package/dist/runtime/editing/gsapSet.js +4 -2
  16. package/dist/runtime/editing/gsapSnapshot.d.ts +1 -0
  17. package/dist/runtime/editing/gsapSnapshot.js +20 -3
  18. package/dist/runtime/editing/textEdit.d.ts +23 -0
  19. package/dist/runtime/editing/textEdit.js +88 -3
  20. package/dist/runtime/editingElement.js +8 -7
  21. package/dist/runtime/editingGestureStart.d.ts +3 -0
  22. package/dist/runtime/editingGestureStart.js +46 -3
  23. package/dist/runtime/editingPort.d.ts +26 -4
  24. package/dist/runtime/editingPort.js +29 -3
  25. package/dist/runtime/positionEdits.js +2 -2
  26. package/dist/safePath.d.ts +5 -1
  27. package/dist/safePath.js +38 -4
  28. package/dist/studioPreviewMark.d.ts +1 -0
  29. package/dist/studioPreviewMark.js +1 -0
  30. package/dist/utils/htmlAttrSafety.js +7 -1
  31. package/dist/utils/inlineTextStyleRange.d.ts +33 -0
  32. package/dist/utils/inlineTextStyleRange.js +503 -0
  33. package/dist/utils/inlineTextStyleRead.d.ts +20 -0
  34. package/dist/utils/inlineTextStyleRead.js +72 -0
  35. package/dist/utils/richTextSanitize.js +16 -2
  36. package/package.json +12 -4
@@ -105,6 +105,9 @@ export declare const signalDuration: (signal: AudioSignal) => number;
105
105
  /** Per-sample energy. Channels are squared first, so a reversed channel stays audible. */
106
106
  export declare function energyMix(signal: AudioSignal): Float32Array;
107
107
  export declare function energyMixSteps(signal: AudioSignal): Steps<Float32Array>;
108
+ export declare const windowSizeFor: (sampleRate: number, seconds: number) => number;
109
+ /** Level in dB of one window, or -Infinity for silence. */
110
+ export declare function windowDb(samples: Float32Array, from: number, count: number): number;
108
111
  export declare function envelope(signal: AudioSignal, options?: EnvelopeOptions): Envelope;
109
112
  export declare function onsets(signal: AudioSignal, options?: OnsetOptions): Onsets;
110
113
  export declare function moments(signal: AudioSignal, options?: MomentOptions): Moments | null;
@@ -50,7 +50,24 @@ function rmsFrames(samples, sampleRate, hopMs, windowMs) {
50
50
  }
51
51
  return frames;
52
52
  }
53
- const fftSizeFor = (sampleRate) => 2 ** Math.round(Math.log2(sampleRate * 0.023));
53
+ export const windowSizeFor = (sampleRate, seconds) => 2 ** Math.round(Math.log2(sampleRate * seconds));
54
+ /** Level in dB of one window, or -Infinity for silence. */
55
+ export function windowDb(samples, from, count) {
56
+ let sum = 0;
57
+ let n = 0;
58
+ for (let i = from; i < from + count; i++) {
59
+ const s = samples[i];
60
+ if (s === undefined)
61
+ break;
62
+ sum += s * s;
63
+ n += 1;
64
+ }
65
+ if (n === 0)
66
+ return Number.NEGATIVE_INFINITY;
67
+ const rms = Math.sqrt(sum / n);
68
+ return rms > 0 ? 20 * Math.log10(rms) : Number.NEGATIVE_INFINITY;
69
+ }
70
+ const fftSizeFor = (sampleRate) => windowSizeFor(sampleRate, 0.023);
54
71
  /** Magnitude spectra of Hann-windowed frames centred on each hop, limited to `band`. */
55
72
  /** The FFT bins inside `band`, as [first, end). */
56
73
  function bandBins(sampleRate, size, band) {
@@ -11,12 +11,19 @@
11
11
  * chain the studio generated rather than a separate rendering path.
12
12
  */
13
13
  import { defaultAudioFxParams, HF_AUDIO_FX_CHAIN_VERSION, } from "./audioFx.js";
14
+ import { windowDb, windowSizeFor } from "./audioAnalysis.js";
14
15
  import { fft } from "./fft.js";
16
+ /** A symmetric Hann window of `size` samples. */
17
+ function hannWindow(size) {
18
+ const window = new Float32Array(size);
19
+ for (let i = 0; i < size; i++)
20
+ window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (size - 1));
21
+ return window;
22
+ }
15
23
  export const HF_AUDIO_CARVE_ATTR = "data-fx-carve";
16
24
  /** Third-octave centres spanning the range speech actually occupies. */
17
25
  const CANDIDATE_CENTERS_HZ = [160, 250, 400, 630, 1000, 1600, 2500, 4000, 6000];
18
- const FRAME = 4096;
19
- const HOP = 2048;
26
+ const FRAME_SECONDS = 4096 / 48_000;
20
27
  /** Short, deliberately dull effects. Nothing here is ever a voiceover. */
21
28
  const SFX_NAME = /sfx|foley|whoosh|impact|riser|stinger|swoosh|thud|boom|click|ding|beep|ambien|room[-_ ]?tone/i;
22
29
  // `\b` treats `_` as a word character, so `\bbed\b` does not match `bed_01`
@@ -236,6 +243,8 @@ export function mixCarveSources(parts, sampleRate) {
236
243
  }
237
244
  /** Averaged power spectrum, Welch-style. */
238
245
  function powerSpectrum(mono, sampleRate) {
246
+ const FRAME = windowSizeFor(sampleRate, FRAME_SECONDS);
247
+ const HOP = FRAME / 2;
239
248
  const n = Math.max(mono.length, FRAME);
240
249
  const padded = mono.length >= FRAME
241
250
  ? mono
@@ -244,9 +253,7 @@ function powerSpectrum(mono, sampleRate) {
244
253
  p.set(mono);
245
254
  return p;
246
255
  })();
247
- const window = new Float32Array(FRAME);
248
- for (let i = 0; i < FRAME; i++)
249
- window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FRAME - 1));
256
+ const window = hannWindow(FRAME);
250
257
  const bins = FRAME / 2 + 1;
251
258
  const acc = new Float64Array(bins);
252
259
  // Reused across hops. These used to be allocated inside the loop: a 5-minute
@@ -452,9 +459,8 @@ function simplifyStepPoints(raw, stepDb) {
452
459
  export function analyseCarveDynamics(voice, sampleRate, bands) {
453
460
  if (voice.length === 0 || bands.length === 0)
454
461
  return [];
455
- const window = new Float32Array(FRAME);
456
- for (let i = 0; i < FRAME; i++)
457
- window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FRAME - 1));
462
+ const FRAME = windowSizeFor(sampleRate, FRAME_SECONDS);
463
+ const window = hannWindow(FRAME);
458
464
  // One window per emitted point, so the hop is what keeps the lane in budget.
459
465
  const hop = Math.max(FRAME, Math.ceil(voice.length / POINT_BUDGET));
460
466
  const bins = FRAME / 2 + 1;
@@ -503,22 +509,6 @@ export function analyseCarveDynamics(voice, sampleRate, bands) {
503
509
  return { freq: band.freq, points };
504
510
  });
505
511
  }
506
- /** Level in dB of one window, or -Infinity for silence. */
507
- function windowDb(samples, from, count) {
508
- let sum = 0;
509
- let n = 0;
510
- for (let i = from; i < from + count; i++) {
511
- const s = samples[i];
512
- if (s === undefined)
513
- break;
514
- sum += s * s;
515
- n += 1;
516
- }
517
- if (n === 0)
518
- return Number.NEGATIVE_INFINITY;
519
- const rms = Math.sqrt(sum / n);
520
- return rms > 0 ? 20 * Math.log10(rms) : Number.NEGATIVE_INFINITY;
521
- }
522
512
  /**
523
513
  * The level envelope that keeps a bed under a voice.
524
514
  *
@@ -536,6 +526,7 @@ function windowDb(samples, from, count) {
536
526
  export function analyseCarveDuck(voice, bed, sampleRate, profile, offsetSeconds) {
537
527
  if (voice.length === 0 || profile.duckDb <= 0)
538
528
  return [];
529
+ const FRAME = windowSizeFor(sampleRate, FRAME_SECONDS);
539
530
  const hop = Math.max(FRAME, Math.ceil(voice.length / POINT_BUDGET));
540
531
  const bedOffset = Math.round(offsetSeconds * sampleRate);
541
532
  const voiceDbs = [];
@@ -0,0 +1,22 @@
1
+ /** A whole decode in a page peaks at ~2x the file as stereo 48 kHz, whatever the context's rate (90 min: 4 GB). */
2
+ export declare const DECODE_PEAK_BUDGET_BYTES: number;
3
+ export declare const decodePeakBytes: (seconds: number) => number;
4
+ /** Analysis PCM rate: 48 kHz up to 20 minutes, 24 kHz past it, so a long file holds half the samples. */
5
+ export declare const pcmRateFor: (seconds: number) => 48000 | 24000;
6
+ export declare class AudioTooLong extends Error {
7
+ readonly seconds: number | null;
8
+ constructor(seconds: number | null);
9
+ }
10
+ /** The length a media element reads from the file's header (metadata only, no audio decoded); null when unread. */
11
+ export declare function headerSeconds(url: string): Promise<number | null>;
12
+ /** An unread length (a recorded blob reads Infinity): its bytes alone keep the peak in budget even at 8 kbps. */
13
+ export declare const UNREAD_LENGTH_MAX_BYTES: number;
14
+ /** Throws AudioTooLong when `url`'s length, from `knownSeconds` (the caller's own element) or the file's header, is
15
+ * past DECODE_PEAK_BUDGET_BYTES. Resolves "unread" when neither gives a length: unreadFits judges its bytes. */
16
+ export declare function assertDecodeFits(url: string, knownSeconds?: number): Promise<"read" | "unread">;
17
+ export declare const unreadFits: (byteLength: number) => boolean;
18
+ /** `url` decoded whole into `context` within the budget: a read length past it is never fetched. */
19
+ export declare function decodeAudioWithin(context: BaseAudioContext, url: string, options?: {
20
+ fetch?: (url: string) => Promise<Response>;
21
+ knownSeconds?: number;
22
+ }): Promise<AudioBuffer>;
@@ -0,0 +1,64 @@
1
+ /** A whole decode in a page peaks at ~2x the file as stereo 48 kHz, whatever the context's rate (90 min: 4 GB). */
2
+ import { wallClearTimeout, wallSetTimeout } from "./runtime/wallClock.js";
3
+ const PEAK_BYTES_PER_SECOND = 48_000 * 2 * 4 * 2;
4
+ export const DECODE_PEAK_BUDGET_BYTES = 1.5 * 1024 ** 3;
5
+ export const decodePeakBytes = (seconds) => seconds * PEAK_BYTES_PER_SECOND;
6
+ /** Analysis PCM rate: 48 kHz up to 20 minutes, 24 kHz past it, so a long file holds half the samples. */
7
+ export const pcmRateFor = (seconds) => seconds <= 20 * 60 ? 48_000 : 24_000;
8
+ export class AudioTooLong extends Error {
9
+ seconds;
10
+ constructor(seconds) {
11
+ super("This clip is too long to decode here.");
12
+ this.seconds = seconds;
13
+ this.name = "AudioTooLong";
14
+ }
15
+ }
16
+ const HEADER_READ_MS = 10_000;
17
+ /** The length a media element reads from the file's header (metadata only, no audio decoded); null when unread. */
18
+ export function headerSeconds(url) {
19
+ if (typeof document === "undefined")
20
+ return Promise.resolve(null);
21
+ return new Promise((resolve) => {
22
+ const audio = document.createElement("audio");
23
+ audio.preload = "metadata";
24
+ // timer-ok: a stalled header read counts as unread. Wall clock: a render runs page timers on film time.
25
+ const late = wallSetTimeout(() => done(null), HEADER_READ_MS);
26
+ const done = (seconds) => {
27
+ wallClearTimeout(late);
28
+ audio.onloadedmetadata = audio.onerror = null;
29
+ audio.removeAttribute("src");
30
+ audio.load();
31
+ resolve(seconds);
32
+ };
33
+ audio.onloadedmetadata = () => done(Number.isFinite(audio.duration) ? audio.duration : null);
34
+ audio.onerror = () => done(null);
35
+ audio.src = url;
36
+ audio.load();
37
+ });
38
+ }
39
+ /** An unread length (a recorded blob reads Infinity): its bytes alone keep the peak in budget even at 8 kbps. */
40
+ export const UNREAD_LENGTH_MAX_BYTES = (DECODE_PEAK_BUDGET_BYTES / PEAK_BYTES_PER_SECOND) * 1_000;
41
+ /** Throws AudioTooLong when `url`'s length, from `knownSeconds` (the caller's own element) or the file's header, is
42
+ * past DECODE_PEAK_BUDGET_BYTES. Resolves "unread" when neither gives a length: unreadFits judges its bytes. */
43
+ export async function assertDecodeFits(url, knownSeconds) {
44
+ const seconds = knownSeconds !== undefined && Number.isFinite(knownSeconds) && knownSeconds > 0
45
+ ? knownSeconds
46
+ : await headerSeconds(url);
47
+ if (seconds === null)
48
+ return "unread";
49
+ if (decodePeakBytes(seconds) > DECODE_PEAK_BUDGET_BYTES)
50
+ throw new AudioTooLong(seconds);
51
+ return "read";
52
+ }
53
+ export const unreadFits = (byteLength) => byteLength <= UNREAD_LENGTH_MAX_BYTES;
54
+ /** `url` decoded whole into `context` within the budget: a read length past it is never fetched. */
55
+ export async function decodeAudioWithin(context, url, options = {}) {
56
+ const length = await assertDecodeFits(url, options.knownSeconds);
57
+ const response = await (options.fetch ?? globalThis.fetch)(url);
58
+ if (!response.ok)
59
+ throw new Error(`Audio request failed (${response.status})`);
60
+ const bytes = await response.arrayBuffer();
61
+ if (length === "unread" && !unreadFits(bytes.byteLength))
62
+ throw new AudioTooLong(null);
63
+ return context.decodeAudioData(bytes);
64
+ }
@@ -25,9 +25,10 @@
25
25
  * automation lane rides when a track has to move".
26
26
  */
27
27
  import { fxAutomationTarget, } from "./audioAutomation.js";
28
+ import { windowDb, windowSizeFor } from "./audioAnalysis.js";
28
29
  import { HF_AUDIO_FX_CHAIN_VERSION, mintAudioFxNodeId, normalizeAudioFxParams, } from "./audioFx.js";
29
30
  /** One window per emitted point; the hop keeps the lane inside its budget. */
30
- const FRAME = 4096;
31
+ const FRAME_SECONDS = 4096 / 48_000;
31
32
  const POINT_BUDGET = 400;
32
33
  /** Below this, a window is silence rather than a quiet passage worth lifting. */
33
34
  const FLOOR_BELOW_PEAK_DB = 42;
@@ -50,22 +51,6 @@ export function levellerProfile(strength) {
50
51
  const s = Number.isFinite(strength) ? Math.min(1, Math.max(0, strength)) : 0.5;
51
52
  return { correction: Number((0.25 + s * 0.6).toFixed(3)) };
52
53
  }
53
- /** Level in dB of one window, or -Infinity for silence. */
54
- function windowDb(samples, from, count) {
55
- let sum = 0;
56
- let n = 0;
57
- for (let i = from; i < from + count; i += 1) {
58
- const s = samples[i];
59
- if (s === undefined)
60
- break;
61
- sum += s * s;
62
- n += 1;
63
- }
64
- if (n === 0)
65
- return Number.NEGATIVE_INFINITY;
66
- const rms = Math.sqrt(sum / n);
67
- return rms > 0 ? 20 * Math.log10(rms) : Number.NEGATIVE_INFINITY;
68
- }
69
54
  /**
70
55
  * Measure a track and return the gain moves that even it out, in dB against
71
56
  * clip-local seconds. Empty when there is nothing worth correcting.
@@ -74,6 +59,7 @@ export function analyseLevelling(samples, sampleRate, strength = DEFAULT_LEVELLE
74
59
  if (samples.length === 0 || sampleRate <= 0)
75
60
  return [];
76
61
  const profile = levellerProfile(strength);
62
+ const FRAME = windowSizeFor(sampleRate, FRAME_SECONDS);
77
63
  const hop = Math.max(FRAME, Math.ceil(samples.length / POINT_BUDGET));
78
64
  const levels = [];
79
65
  const times = [];
@@ -1,6 +1,7 @@
1
1
  import { energyMixSteps } from "../audioAnalysis.js";
2
2
  import { rhythmSteps, tempoOf } from "../audioRhythm.js";
3
3
  import { finish } from "../audioSteps.js";
4
+ import { decodeAudioWithin } from "../audioDecode.js";
4
5
  const STRENGTH_WINDOW_S = 0.05; // ±50ms RMS window
5
6
  /** Local RMS amplitude at a given audio-file time. */
6
7
  export function computeRmsAt(channelData, sampleRate, time) {
@@ -72,9 +73,7 @@ export async function analyzeMusicFromUrl(url, options = {}) {
72
73
  await options.pause?.();
73
74
  const audioContext = new AudioContext();
74
75
  try {
75
- const response = await fetch(url);
76
- const arrayBuffer = await response.arrayBuffer();
77
- const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
76
+ const audioBuffer = await decodeAudioWithin(audioContext, url);
78
77
  return analyzeMusicFromBuffer(audioBuffer, options);
79
78
  }
80
79
  finally {
@@ -29,4 +29,9 @@ export interface ClipFact {
29
29
  }
30
30
  export declare const byStart: (a: ClipFact, b: ClipFact) => number;
31
31
  export { instantTolerance, isInsideSpan, sameInstant, spansOverlap, spansShareTime, } from "@hyperframes/parsers/time-spans";
32
+ export declare const PROMPT_LABEL_MAX = 160;
33
+ /** A project value as one quoted line that reads back to exactly the value, so text around it cannot be imitated. */
34
+ export declare function promptField(value: string): string;
35
+ /** A display label as one quoted line, its whitespace collapsed and its length capped. */
36
+ export declare function promptLabel(value: string): string;
32
37
  export declare function formatClipLine(clip: ClipFact): string;
package/dist/clipFacts.js CHANGED
@@ -3,20 +3,35 @@ export const byStart = (a, b) => a.start - b.start || a.trackIndex - b.trackInde
3
3
  const roundTo3 = (n) => Math.round(n * 1000) / 1000;
4
4
  const num = (n) => String(roundTo3(n));
5
5
  export { instantTolerance, isInsideSpan, sameInstant, spansOverlap, spansShareTime, } from "@hyperframes/parsers/time-spans";
6
+ const CONTROL_BIDI_OR_LINE_SEPARATOR = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
7
+ export const PROMPT_LABEL_MAX = 160;
8
+ const escaped = (character) => Array.from({ length: character.length }, (_, i) => `\\u${character.charCodeAt(i).toString(16).padStart(4, "0")}`).join("");
9
+ /** A project value as one quoted line that reads back to exactly the value, so text around it cannot be imitated. */
10
+ export function promptField(value) {
11
+ return JSON.stringify(value).replace(CONTROL_BIDI_OR_LINE_SEPARATOR, escaped);
12
+ }
13
+ /** A display label as one quoted line, its whitespace collapsed and its length capped. */
14
+ export function promptLabel(value) {
15
+ const flat = Array.from(value.replace(CONTROL_BIDI_OR_LINE_SEPARATOR, " ").replace(/\s+/g, " ").trim());
16
+ const kept = flat.length > PROMPT_LABEL_MAX
17
+ ? `${flat.slice(0, PROMPT_LABEL_MAX - 1).join("")}…`
18
+ : flat.join("");
19
+ return JSON.stringify(kept);
20
+ }
6
21
  export function formatClipLine(clip) {
7
22
  const parts = [
8
- `${clip.kind} "${clip.id}"`,
9
- clip.src && `src=${clip.src}`,
23
+ `${promptField(clip.kind)} ${promptField(clip.id)}`,
24
+ clip.src && `src=${promptField(clip.src)}`,
10
25
  `start=${num(clip.start)}`,
11
26
  `duration=${num(clip.duration)}`,
12
27
  `end=${num(clip.end)}`,
13
28
  `track=${clip.trackIndex}`,
14
29
  clip.volume !== null && `volume=${num(clip.volume)}`,
15
30
  clip.playbackRate !== null && `rate=${num(clip.playbackRate)}`,
16
- clip.audioGroup && `group=${clip.audioGroup}`,
17
- clip.role && `role=${clip.role}`,
18
- clip.sourceFile && `file=${clip.sourceFile}`,
19
- ...clip.lanes.map((lane) => `${lane.target}-lane=[${lane.points.map((p) => `${num(p.t)}:${num(p.v)}`).join(", ")}]`),
31
+ clip.audioGroup && `group=${promptField(clip.audioGroup)}`,
32
+ clip.role && `role=${promptField(clip.role)}`,
33
+ clip.sourceFile && `file=${promptField(clip.sourceFile)}`,
34
+ ...clip.lanes.map((lane) => `lane ${promptField(lane.target)}=[${lane.points.map((p) => `${num(p.t)}:${num(p.v)}`).join(", ")}]`),
20
35
  ];
21
36
  return `- ${parts.filter(Boolean).join(" ")}`;
22
37
  }
@@ -1,2 +1,4 @@
1
1
  export declare const COMPOSITION_SRC_ATTR = "data-composition-src";
2
2
  export declare const CODE_LOADING_ATTRS: ReadonlySet<string>;
3
+ export declare const SOURCE_HOST_ATTRS: readonly ["data-composition-file", "data-composition-src"];
4
+ export declare const COMPOSITION_ROOT_ATTRS: readonly ["data-composition-id", "data-hf-original-composition-id"];
@@ -1,2 +1,7 @@
1
1
  export const COMPOSITION_SRC_ATTR = "data-composition-src";
2
2
  export const CODE_LOADING_ATTRS = new Set([COMPOSITION_SRC_ATTR]);
3
+ export const SOURCE_HOST_ATTRS = ["data-composition-file", COMPOSITION_SRC_ATTR];
4
+ export const COMPOSITION_ROOT_ATTRS = [
5
+ "data-composition-id",
6
+ "data-hf-original-composition-id",
7
+ ];