commit 3f3f841755a6ac82de12adf03667ccc1c316a39c
parent 8fe8fb2ac3ebfd2c716c4f103532e97707467e36
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 13:04:26 -0400
Merge lane/bench-pitch: the clip editor keeps the pitch at any speed (up to 4x); a window umtool cannot read is no window, the saved-video store readable
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 485 insertions(+), 14 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,8 @@
# Changelog
## [Unreleased]
+- **umtool's clip editor keeps a voice's pitch at any speed, and goes up to 4×.** A selection, an edge, a transcript line or the auto-audition played at 1.5× or 2× used to rise in pitch with the speed (2× was an octave up), unlike the same video at 2× in a player: the bench plays a range from decoded audio, whose speed control is a tape-speed knob. At any speed but 1× the range is now time-stretched at its own pitch first (waveform-similarity overlap-add) and played at 1×, still starting and stopping on the exact sample; a clip's selection is stretched ahead while the editor is idle, so playing it does not wait. The speed list adds 1.75×, 2.5×, 3×, 3.5× and 4×. Needs a restart of umtool.
+- **A clip whose recording umtool cannot play is skipped by the clip walk, not opened broken.** A whole recording saved with **Fetch the whole recording** sits in the saved-video store, which umtool was not allowed to read: a clip it alone held counted as fetched, the walk stopped on it, and the player answered "outside the roots" (`costco-ok`). The store (`SAVED_VIDEOS_DIR`, else `transcripts/saved-videos`) is now readable, as the corpus is, so such a clip plays; and a window umtool may not read is no longer counted at all, so a clip with no window it can play is passed by and comes back once one is fetched. Needs a restart of umtool.
- **Record live reads Rumble's new segment packaging.** Rumble's CDN now serves a stream's pieces as byte ranges of one `.tar` file, which ffmpeg refused by its name ("not in allowed_segment_extensions"), so a recording through the browser path ended with nothing recorded. The recorder now also allows `tar` segments, and nothing looser. Needs a rebuild of the editor.
- **Jobs that ask a site are spaced apart, and X jobs start only on fresh cookies.** On 2026-10-23 thirteen X fetches queued in one loop ran less than a second apart on a cookie jar refreshed 16 days earlier; X answered with a Cloudflare challenge and the account needed a human verification. Now every job that sends requests to a platform waits after the previous one on the same platform ended — 5 minutes for X, 1 minute for forums and Bluesky, 20 seconds for everything else — and its row on /jobs and its log say so: "waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)". The gaps are on /settings beside the download sleep (`pacing.jobGapSeconds`), and the last job's end is remembered across a restart. With the connected X profile, a job that asks X is refused — when it is queued and again when its turn comes — unless the cookies were refreshed within the last hour: "X cookies were last refreshed 16 days ago (limit 60 min): press Refresh cookies (or Connect X account) on /settings, then fetch again." The limit is in the X account section of /settings (`social.x.maxCookieAgeMinutes`, 0 turns it off). The editor never refreshes the cookies itself, because a refresh loads x.com. With the browser login the age cannot be read; the job says so and runs. A job that asks a site can no longer be run "(immediate)": the queue picker leaves the option out, and `"queueKey": ""` from `pnpm ops` is refused with a sentence. Needs a restart of the editor.
- **An X challenge stops X.** When gallery-dl prints a Cloudflare challenge, a 401 or 403, or a login wall, the fetch now fails even if gallery-dl exits cleanly (the posts it read are kept), and the dashboard shows an **X needs fresh cookies** banner. While it is up, every X job (Fetch posts, the older walk, an X search, Capture posts, Import one post, Check deleted posts, the scheduler's fetches) is refused before it asks anything, and the refused jobs are listed for **Re-run stopped jobs**. Pass X's check by hand, press **Refresh cookies** on /settings, then **Recheck**: for X it sends no request and clears the banner when the login on disk is newer than the challenge. `pnpm ops get services` and `archilyzer doctor` list it as `x`. Needs a restart of the editor.
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -29,6 +29,7 @@ import {
muteRamp,
playheadAt,
} from "@/lib/report/playback.mjs";
+import { timeStretch, wantsStretch } from "@/lib/report/timeStretch.mjs";
import {
DeckFrame,
NeutralFrame,
@@ -290,7 +291,9 @@ const round2 = (n: number) => Number(n.toFixed(2));
// window throws on access rather than returning null.
// ---------------------------------------------------------------------------
const PLAYBACK_KEY = "umtool.bench.playback";
-const RATES = [0.75, 1, 1.25, 1.5, 2] as const;
+// Past 2x in half steps: a long clip skimmed at 3-4x, still at its own pitch
+// (timeStretch.mjs; the element keeps it by itself up to 4x).
+const RATES = [0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3, 3.5, 4] as const;
type Playback = { rate: number; auto: boolean };
const PLAYBACK_DEFAULT: Playback = { rate: 1, auto: false };
@@ -358,6 +361,12 @@ type PlayInfo = {
/** The scheduled end, in source seconds. */
to: number;
rate: number;
+ /**
+ * Web Audio at a speed but 1x: the range was time-stretched and played at
+ * 1x, so it keeps its pitch as the element does (`preservesPitch`). False at
+ * 1x, and for the element, which keeps the pitch by itself.
+ */
+ stretched: boolean;
/** Context clock: when the source starts and when it is told to stop. */
ctxStart: number | null;
ctxStop: number | null;
@@ -652,6 +661,9 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
/** The decoded audio for the cached window: one decode per window. */
const decoded = useRef<Decoded | null>(null);
const decoding = useRef<{ key: string; p: Promise<Decoded> } | null>(null);
+ // The last few time-stretched ranges: a replay at the same speed, and the
+ // clip's selection stretched ahead of the first play, cost nothing.
+ const stretchedRanges = useRef<{ key: string; buf: AudioBuffer }[]>([]);
const actx = useRef<AudioContext | null>(null);
const session = useRef<Session | null>(null);
const playGen = useRef(0);
@@ -738,6 +750,57 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cachedName]);
+ /**
+ * The range [offset, offset + duration) of a decoded buffer, time-stretched
+ * to `rate` at its own pitch (timeStretch.mjs): played at 1x it lasts
+ * duration / rate -- the wall length bufferSchedule computed -- and starts
+ * and ends on the range's own samples.
+ */
+ const stretchFor = useCallback((d: Decoded, offset: number, duration: number, rate: number): AudioBuffer => {
+ const key = `${d.name}|${d.span.from}|${offset.toFixed(5)}|${duration.toFixed(5)}|${rate}`;
+ const hit = stretchedRanges.current.find((r) => r.key === key);
+ if (hit) return hit.buf;
+ const sr = d.buf.sampleRate;
+ const a = Math.max(0, Math.min(d.buf.length, Math.round(offset * sr)));
+ const b = Math.max(a, Math.min(d.buf.length, a + Math.round(duration * sr)));
+ const channels: Float32Array[] = [];
+ for (let c = 0; c < d.buf.numberOfChannels; c++) channels.push(d.buf.getChannelData(c).subarray(a, b));
+ const out = timeStretch(channels, sr, rate);
+ const buf = new AudioBuffer({
+ length: Math.max(1, out[0]?.length ?? 0),
+ numberOfChannels: Math.max(1, out.length),
+ sampleRate: sr,
+ });
+ out.forEach((ch, c) => buf.copyToChannel(ch as Float32Array<ArrayBuffer>, c));
+ stretchedRanges.current = [{ key, buf }, ...stretchedRanges.current.filter((r) => r.key !== key)].slice(0, 4);
+ return buf;
+ }, []);
+
+ // At a speed but 1x, the clip's selection is stretched while the bench is
+ // idle, so "play the clip" does not wait for it (a minute of stereo is a
+ // few hundred ms).
+ useEffect(() => {
+ const rate = playback.rate;
+ if (audio.state !== "ready" || !wantsStretch(rate)) return;
+ const d = decoded.current;
+ if (!d) return;
+ const sch = bufferSchedule(d.span, d.buf.duration, clip.start, clip.end, rate);
+ if (!sch) return;
+ const w = window as Window & {
+ requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number;
+ cancelIdleCallback?: (id: number) => void;
+ };
+ const run = () => {
+ if (decoded.current === d) stretchFor(d, sch.offset, sch.duration, rate);
+ };
+ if (w.requestIdleCallback) {
+ const id = w.requestIdleCallback(run, { timeout: 2000 });
+ return () => w.cancelIdleCallback?.(id);
+ }
+ const id = window.setTimeout(run, 250);
+ return () => window.clearTimeout(id);
+ }, [audio.state, playback.rate, clip.start, clip.end, stretchFor]);
+
/** Stop whatever is playing, Web Audio or element, and let go of it. */
const stopPlayback = useCallback(() => {
const s = session.current;
@@ -792,7 +855,17 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
mutedBefore: el.muted,
};
session.current = s;
- setPlayInfo({ engine: "element", state: "playing", from, to, rate, ctxStart: null, ctxStop: null, endedAt: null });
+ setPlayInfo({
+ engine: "element",
+ state: "playing",
+ from,
+ to,
+ rate,
+ stretched: false,
+ ctxStart: null,
+ ctxStop: null,
+ endedAt: null,
+ });
const stopNow = () => {
if (session.current !== s) return;
pauseVideo(el);
@@ -869,9 +942,15 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
const sch = bufferSchedule(d.span, d.buf.duration, from, to, rate);
if (!sch) return;
+ // At a speed but 1x the range is stretched at its own pitch and played
+ // at 1x; a buffer's playbackRate is tape speed, an octave up at 2x.
+ const stretched = wantsStretch(rate);
+ const buf = stretched ? stretchFor(d, sch.offset, sch.duration, rate) : d.buf;
+ if (gen !== playGen.current) return;
+
const node = ctx.createBufferSource();
- node.buffer = d.buf;
- node.playbackRate.value = rate;
+ node.buffer = buf;
+ node.playbackRate.value = stretched ? 1 : rate;
const gain = ctx.createGain();
node.connect(gain);
gain.connect(ctx.destination);
@@ -890,7 +969,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
// The stop is a TIME on the context's clock, not start()'s duration
// argument: that one is buffer content, and a clock time means the same
// thing at every speed.
- node.start(t0, sch.offset);
+ node.start(t0, stretched ? 0 : sch.offset);
node.stop(ctxStop);
const el = video.current;
@@ -915,6 +994,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
from,
to: s.to,
rate,
+ stretched,
ctxStart: t0,
ctxStop,
endedAt: null,
@@ -977,7 +1057,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
};
s.raf = requestAnimationFrame(tick);
},
- [cached, fetchStart, playback.rate, ensureDecoded, playElement, stopPlayback, pauseVideo],
+ [cached, fetchStart, playback.rate, ensureDecoded, playElement, stopPlayback, pauseVideo, stretchFor],
);
// A speed change mid-playback would leave the picture and the sound at two
@@ -2317,6 +2397,7 @@ export default function ClipBench({ data }: { data: ClipBenchData }) {
data-play-from={playInfo?.from ?? ""}
data-play-to={playInfo?.to ?? ""}
data-play-rate={playInfo?.rate ?? ""}
+ data-play-stretched={playInfo ? String(playInfo.stretched) : ""}
data-play-ctx-start={playInfo?.ctxStart ?? ""}
data-play-ctx-stop={playInfo?.ctxStop ?? ""}
data-play-ended-at={playInfo?.endedAt ?? ""}
diff --git a/umtool/e2e/clip-bench.spec.ts b/umtool/e2e/clip-bench.spec.ts
@@ -906,6 +906,7 @@ const lastPlay = async (page: import("@playwright/test").Page) => {
from: await n("from"),
to: await n("to"),
rate: await n("rate"),
+ stretched: await p.getAttribute("data-play-stretched"),
ctxStart: await n("ctx-start"),
ctxStop: await n("ctx-stop"),
};
@@ -965,6 +966,9 @@ test("a play-selection stops within one audio render quantum of its end, at any
expect(play.from).toBeCloseTo(3, 3);
expect(play.to).toBeCloseTo(5, 3);
expect(play.rate).toBe(Number(rate));
+ // At 2x the range is time-stretched and played at 1x (its own pitch, as
+ // the element keeps it), and still stops on the same clock.
+ expect(play.stretched).toBe(rate === "1" ? "false" : "true");
expect(tap, "the tap saw the bench's audio").not.toBeNull();
const { first, last, sr } = tap!;
expect(last).toBeGreaterThan(first);
diff --git a/umtool/lib/paths.mjs b/umtool/lib/paths.mjs
@@ -270,10 +270,25 @@ export const ARTICLES_DIR = path.resolve(
);
export { ARTICLES_KEY };
+// The SAVED-VIDEO STORE -- `transcripts/saved-videos/<slug>/<id>/`, where a
+// "fetch the whole recording" (`full: true`) puts a source, and the window
+// every clip of that video then cuts from. Resolved as common/lib/paths.ts
+// resolves its savedVideosDir (`SAVED_VIDEOS_DIR`, else
+// `<TRANSCRIPTS_DIR>/saved-videos`). Readable only, as the corpus is. Without
+// it a saved source was listed as the clip's window, the walk counted the clip
+// fetched, and the bench answered "outside the roots" (costco-ok, 2026-10-23).
+export const SAVED_VIDEOS_DIR = path.resolve(
+ /* turbopackIgnore: true */
+ process.env.SAVED_VIDEOS_DIR ??
+ (process.env.TRANSCRIPTS_DIR
+ ? path.join(/* turbopackIgnore: true */ process.env.TRANSCRIPTS_DIR, "saved-videos")
+ : path.join(/* turbopackIgnore: true */ REPO_ROOT, "transcripts", "saved-videos")),
+);
+
export const READ_ROOTS = dedupe(
process.env.MIX_ROOTS
? process.env.MIX_ROOTS.split(":").filter(Boolean)
- : [SONG_REPORTS, REPORTS_ROOT, SONG_DATA, SONG_SCRATCH, CHANNELS_DIR, MEDIA_ROOT, SITES_DIR, ARTICLES_DIR],
+ : [SONG_REPORTS, REPORTS_ROOT, SONG_DATA, SONG_SCRATCH, CHANNELS_DIR, SAVED_VIDEOS_DIR, MEDIA_ROOT, SITES_DIR, ARTICLES_DIR],
);
/** A site id or a report id: one lowercase url-safe segment (common/lib/report/schema.ts REPORT_ID_RE). */
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -16,7 +16,7 @@ import {
import { rawCacheOf } from "../report/raw-cache.mjs";
import { resolveVideoDirSync } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
import { deliverablesState, finishCommand, outDirState, leftoversOf } from "../report/storage.mjs";
-import { CHANNELS_DIR, inside } from "../paths.mjs";
+import { CHANNELS_DIR, inside, resolveInRoots } from "../paths.mjs";
import { channelName, cleanTitle } from "umtool-report-to-video/attribution";
import { deckOn, resolveDeck, teaserTitle } from "umtool-report-to-video/deck";
import { originQrsOf } from "umtool-report-to-video/lint";
@@ -400,8 +400,11 @@ export async function readAvailability(dir) {
* window the next one does not -- and a saved whole source, reached through
* the store's pointer (`full: true` puts the recording there, not in clips/)
* or still in the video dir. A dangling link -- a drive not mounted -- is no
- * window, never an error. One entry per distinct (channel, video) the
- * timeline cites.
+ * window, never an error. Nor is a file umtool may not read (outside every
+ * read root): the bench could not play it, so a clip it alone holds is NOT
+ * fetched -- the walk passes it by and comes back when a window it can play
+ * is there (`readable`: resolveInRoots, the media route's own check). One
+ * entry per distinct (channel, video) the timeline cites.
*
* A WHOLE CONTAINER'S SPAN COMES FROM THE CUES, not from an ffprobe as the
* render's does: the cue doc is the archive's own record of how long the
@@ -409,7 +412,7 @@ export async function readAvailability(dir) {
* only when a container is actually there -- which keeps the index load as
* cheap as it was. No duration is no window rather than a guess.
*/
-export const clipWindowDirs = async (m, channelsDir) => {
+export const clipWindowDirs = async (m, channelsDir, { readable = (p) => resolveInRoots(p) !== null } = {}) => {
const root = channelsDir ?? GLOBAL_CHANNELS_DIR();
const seen = new Set();
const out = [];
@@ -425,7 +428,9 @@ export const clipWindowDirs = async (m, channelsDir) => {
const duration = Number((await readCues(cueFile))?.duration);
return Number.isFinite(duration) && duration > 0 ? { duration } : null;
};
- const windows = await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe });
+ const windows = (await corpusWindowsOf({ video: e.video, slug: chan, channelsDir: root, probe })).filter((w) =>
+ readable(w.path),
+ );
if (windows.length) out.push({ video: e.video, windows });
}
return out;
diff --git a/umtool/lib/report/raw-cache.test.mjs b/umtool/lib/report/raw-cache.test.mjs
@@ -70,7 +70,7 @@ test("clipWindowDirs: corpus windows and a saved source, and the render resolves
{ id: "c4", type: "clip", video: "nope99", start: 1, end: 2 },
],
};
- const extra = await clipWindowDirs(m, f.channelsDir);
+ const extra = await clipWindowDirs(m, f.channelsDir, { readable: () => true });
assert.deepEqual(
extra.map((e) => [e.video, e.windows.map((w) => [w.kind, w.name, w.from, w.to])]),
[
@@ -124,7 +124,7 @@ test("a Twitch v<n> clip reads its cue file and windows from data/<n>/, and keep
],
};
assert.equal(cuePathFor(m, m.timeline[0], f.channelsDir), path.join(dir, "transcript.cues.json"));
- const extra = await clipWindowDirs(m, f.channelsDir);
+ const extra = await clipWindowDirs(m, f.channelsDir, { readable: () => true });
assert.deepEqual(
extra.map((e) => [e.video, e.windows.map((w) => [w.kind, w.name, w.from, w.to])]),
[[`v${n}`, [["corpus-window", "100.00-160.00.mp4", 100, 160], ["saved-video", "source-media.mp4", 0, 1800]]]],
@@ -133,3 +133,42 @@ test("a Twitch v<n> clip reads its cue file and windows from data/<n>/, and keep
await rm(f.root, { recursive: true, force: true });
}
});
+
+test("clipWindowDirs: a window umtool may not read is no window, so the walk passes its clip by", async () => {
+ // costco-ok, 2026-10-23: the whole recording was in the saved-video store,
+ // which was under no read root. Listed, it made the clip "fetched", the walk
+ // stopped on it, and the bench answered "outside the roots".
+ const f = await fixture();
+ try {
+ const a = await f.video("abc123");
+ await touch(path.join(a, "clips", "100.00-160.00.mp4"));
+ const store = path.join(f.root, "store", SLUG, "abc123");
+ await mkdir(store, { recursive: true });
+ await touch(path.join(store, "source-media.mp4"));
+ await writeFile(path.join(a, "saved-video.json"), JSON.stringify({ dir: store, file: "source-media.mp4", bytes: 16 }));
+ await writeFile(path.join(a, "transcript.cues.json"), JSON.stringify({ duration: 1800, cues: [] }));
+ const m = {
+ provenance: { channelSlug: SLUG },
+ timeline: [
+ { id: "inside", type: "clip", video: "abc123", start: 110, end: 120 },
+ { id: "store-only", type: "clip", video: "abc123", start: 1000, end: 1010 },
+ ],
+ };
+ // The corpus is readable, the store is not.
+ const readable = (p) => p.startsWith(f.channelsDir + path.sep);
+ const extra = await clipWindowDirs(m, f.channelsDir, { readable });
+ assert.deepEqual(
+ extra.map((e) => e.windows.map((w) => w.name)),
+ [["100.00-160.00.mp4"]],
+ );
+ const c = await rawCacheOf(f.projectDir, { extraWindows: extra });
+ assert.equal(c.isFetched(m.timeline[0]), true, "a window it can play still counts");
+ assert.equal(c.isFetched(m.timeline[1]), false, "the store's copy it cannot serve does not");
+
+ // By default the check is the media route's own: a temp dir is under no
+ // read root, so nothing here is listed at all.
+ assert.deepEqual(await clipWindowDirs(m, f.channelsDir), []);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/timeStretch.mjs b/umtool/lib/report/timeStretch.mjs
@@ -0,0 +1,201 @@
+// Speed without the chipmunk: a range of decoded audio made shorter (or
+// longer) at the SAME pitch, for the clip bench's bounded playback.
+//
+// The bench plays a selection from decoded audio on an AudioBufferSourceNode
+// (playback.mjs says why: a stop on the exact sample). That node's
+// `playbackRate` is a tape-speed knob -- 2x is an octave up -- where a <video>
+// element at 2x keeps the voice where it was (`preservesPitch`, on by
+// default). Working at 1.5-2x, the bench sounded nothing like the player.
+//
+// So at any rate but 1 the range is time-stretched first and the result is
+// played at 1x: the start, the stop and the wall length are the ones
+// `bufferSchedule` already computes, only the samples between differ.
+//
+// WSOLA (waveform-similarity overlap-add): frames of FRAME_MS, Hann-windowed,
+// laid down every half frame in the output; each frame's input position
+// advances by half a frame times the rate, then moves by up to SEEK_MS to
+// where the input looks most like the natural continuation of the frame
+// before -- so the overlaps add in phase and a voice stays a voice. The search
+// is coarse to fine on a mono mix (~4 kHz, ~16 kHz, then the full rate); every
+// channel is cut at the one position it chose.
+//
+// The EDGES are the input's own: the first frame starts at input sample 0 and
+// is not faded in, the last ends at the input's last sample and is not faded
+// out, and the output is normalised by the summed window. A stretched range
+// begins and ends on the samples the unstretched one would.
+//
+// Pure: Float32Arrays in, Float32Arrays out. No Web Audio, so it is
+// unit-tested; the component makes the AudioBuffer.
+
+/** Frame length, ms. Long enough to hold a pitch period of a low voice. */
+export const FRAME_MS = 30;
+/** How far a frame may move from its nominal input position, ms. */
+export const SEEK_MS = 8;
+/** The search's levels, coarse to fine, in Hz (approximately); then the full rate. */
+export const SEARCH_LEVELS_HZ = [4000, 16000];
+/** Rates this close to 1 are played as they are. */
+export const RATE_EPSILON = 0.005;
+
+/**
+ * Does playback at this rate want stretching?
+ *
+ * @param {number} rate
+ */
+export function wantsStretch(rate) {
+ return Number.isFinite(rate) && rate > 0 && Math.abs(rate - 1) > RATE_EPSILON;
+}
+
+/** The output's length in samples: the input's, divided by the rate. */
+export function stretchedLength(inputLength, rate) {
+ return Math.max(0, Math.floor(inputLength / rate));
+}
+
+function hann(n) {
+ // Periodic: half-overlapped copies sum to exactly 1.
+ const w = new Float32Array(n);
+ for (let i = 0; i < n; i++) w[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / n);
+ return w;
+}
+
+/** A plain resample, for a range too short to frame (under one frame). */
+function resampleLinear(channels, outLen) {
+ return channels.map((x) => {
+ const y = new Float32Array(outLen);
+ if (x.length === 0) return y;
+ const step = outLen > 1 ? (x.length - 1) / (outLen - 1) : 0;
+ for (let i = 0; i < outLen; i++) {
+ const p = i * step;
+ const j = Math.floor(p);
+ const f = p - j;
+ y[i] = j + 1 < x.length ? x[j] * (1 - f) + x[j + 1] * f : x[x.length - 1];
+ }
+ return y;
+ });
+}
+
+/**
+ * Time-stretch audio at a constant pitch.
+ *
+ * `rate` is the playback speed: 2 halves the length, 0.5 doubles it. Every
+ * channel must be the same length.
+ *
+ * @param {Float32Array[]} channels
+ * @param {number} sampleRate
+ * @param {number} rate
+ * @returns {Float32Array[]} the same number of channels, each
+ * `stretchedLength(length, rate)` samples
+ */
+export function timeStretch(channels, sampleRate, rate) {
+ if (!channels.length) return [];
+ const inLen = channels[0].length;
+ if (!wantsStretch(rate)) return channels.map((c) => new Float32Array(c));
+ const outLen = stretchedLength(inLen, rate);
+
+ let N = Math.round((sampleRate * FRAME_MS) / 1000);
+ N += N % 2;
+ const Hs = N / 2;
+ if (inLen < N + 2 || outLen < N) return resampleLinear(channels, outLen);
+ const Ha = Hs * rate;
+ const seek = Math.max(1, Math.round((sampleRate * SEEK_MS) / 1000));
+ const win = hann(N);
+
+ // The search's signals: a mono mix, and box-filtered decimations of it.
+ const mono = new Float32Array(inLen);
+ for (const c of channels) for (let i = 0; i < inLen; i++) mono[i] += c[i];
+ const levels = [];
+ for (const hz of SEARCH_LEVELS_HZ) {
+ const D = Math.max(1, Math.round(sampleRate / hz));
+ if (D < 2 || levels.some((l) => l.D === D)) continue;
+ const len = Math.floor(inLen / D);
+ const sig = new Float32Array(len);
+ for (let i = 0; i < len; i++) {
+ let s = 0;
+ for (let k = 0; k < D; k++) s += mono[i * D + k];
+ sig[i] = s;
+ }
+ levels.push({ D, sig });
+ }
+ levels.push({ D: 1, sig: mono });
+
+ // Score of a candidate: its first half-frame against the target's, the
+ // correlation over the candidate's own energy (so a loud stretch does not
+ // win for being loud).
+ const score = (sig, target, cand, len) => {
+ let xy = 0;
+ let yy = 1e-9;
+ for (let i = 0; i < len; i++) {
+ const y = sig[cand + i];
+ xy += sig[target + i] * y;
+ yy += y * y;
+ }
+ return xy / Math.sqrt(yy);
+ };
+
+ // The best start in [lo, hi] (input samples) for a frame that should look
+ // like `target`: the whole window at the coarsest level, then each finer
+ // level around the last pick, one coarser step either side.
+ const search = (target, lo, hi) => {
+ let best = Math.round((lo + hi) / 2);
+ let from = lo;
+ let to = hi;
+ for (const { D, sig } of levels) {
+ const len = Math.max(1, Math.floor(Hs / D));
+ const t = Math.floor(target / D);
+ if (t + len > sig.length) continue;
+ let bestScore = -Infinity;
+ for (let c = Math.ceil(from / D); c <= Math.floor(to / D) && c + len <= sig.length; c++) {
+ const s = score(sig, t, c, len);
+ if (s > bestScore) {
+ bestScore = s;
+ best = c * D;
+ }
+ }
+ from = Math.max(lo, best - D);
+ to = Math.min(hi, best + D);
+ }
+ return best;
+ };
+
+ const acc = channels.map(() => new Float32Array(outLen));
+ const wsum = new Float32Array(outLen);
+ const maxStart = inLen - N;
+ const add = (outPos, start, edge) => {
+ const n = Math.min(N, outLen - outPos, inLen - start);
+ for (let i = 0; i < n; i++) {
+ // An edge's outer half is the input's own samples. At the end that
+ // REPLACES what is there: the frame before may reach past this one's
+ // middle, and averaging it in would move the last sound off the end.
+ if (edge === "last" && i >= Hs) {
+ wsum[outPos + i] = 1;
+ for (let ch = 0; ch < channels.length; ch++) acc[ch][outPos + i] = channels[ch][start + i];
+ continue;
+ }
+ const w = edge === "first" && i < Hs ? 1 : win[i];
+ wsum[outPos + i] += w;
+ for (let ch = 0; ch < channels.length; ch++) acc[ch][outPos + i] += channels[ch][start + i] * w;
+ }
+ };
+
+ // Frames every half frame, while a whole one still fits before the last.
+ let prev = 0;
+ add(0, 0, "first");
+ const lastOut = outLen - N;
+ for (let k = 1, outPos = Hs; outPos < lastOut; k++, outPos += Hs) {
+ const nominal = Math.round(k * Ha);
+ // Where the previous frame would have gone on: what this one should look
+ // like at its start.
+ const target = Math.min(prev + Hs, maxStart);
+ const lo = Math.max(0, Math.min(maxStart, nominal - seek));
+ const hi = Math.max(0, Math.min(maxStart, nominal + seek));
+ prev = search(target, lo, hi);
+ add(outPos, prev, null);
+ }
+ // The last frame ends on the input's last sample: the range's own end.
+ add(lastOut, maxStart, "last");
+
+ for (let ch = 0; ch < acc.length; ch++) {
+ const a = acc[ch];
+ for (let i = 0; i < outLen; i++) a[i] = wsum[i] > 1e-6 ? a[i] / wsum[i] : 0;
+ }
+ return acc;
+}
diff --git a/umtool/lib/report/timeStretch.test.mjs b/umtool/lib/report/timeStretch.test.mjs
@@ -0,0 +1,121 @@
+// Speed without the chipmunk: timeStretch keeps the pitch and the edges.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { stretchedLength, timeStretch, wantsStretch } from "./timeStretch.mjs";
+
+const SR = 48000;
+
+const tone = (hz, seconds, sr = SR, amp = 0.5) => {
+ const x = new Float32Array(Math.round(seconds * sr));
+ for (let i = 0; i < x.length; i++) x[i] = amp * Math.sin((2 * Math.PI * hz * i) / sr);
+ return x;
+};
+
+// The frequency, from upward zero crossings over the middle of the signal
+// (away from either edge).
+const frequency = (x, sr = SR) => {
+ const a = Math.floor(x.length * 0.1);
+ const b = Math.floor(x.length * 0.9);
+ let n = 0;
+ let first = -1;
+ let last = -1;
+ for (let i = a + 1; i < b; i++) {
+ if (x[i - 1] < 0 && x[i] >= 0) {
+ if (first < 0) first = i;
+ last = i;
+ n++;
+ }
+ }
+ return ((n - 1) * sr) / (last - first);
+};
+
+test("1x (and anything within a hair of it) is played as it is", () => {
+ assert.equal(wantsStretch(1), false);
+ assert.equal(wantsStretch(1.004), false);
+ assert.equal(wantsStretch(1.25), true);
+ assert.equal(wantsStretch(0.75), true);
+ assert.equal(wantsStretch(0), false);
+ assert.equal(wantsStretch(Number.NaN), false);
+ const x = tone(220, 0.5);
+ const [y] = timeStretch([x], SR, 1);
+ assert.deepEqual(y, x);
+ assert.notEqual(y, x, "a copy, not the decoded buffer's own array");
+});
+
+test("the length is the input's divided by the rate, on every channel", () => {
+ for (const rate of [1.25, 1.5, 2, 3, 4, 0.5]) {
+ const out = timeStretch([tone(220, 2), tone(330, 2)], SR, rate);
+ assert.equal(out.length, 2);
+ for (const ch of out) assert.equal(ch.length, stretchedLength(2 * SR, rate), `at ${rate}x`);
+ }
+});
+
+test("the pitch stays where it was: a 220 Hz tone at 2x is still 220 Hz", () => {
+ for (const rate of [1.25, 1.5, 2, 2.5, 3, 3.5, 4]) {
+ const [y] = timeStretch([tone(220, 3)], SR, rate);
+ const f = frequency(y);
+ assert.ok(Math.abs(f - 220) < 3, `${f.toFixed(1)} Hz at ${rate}x`);
+ // A tape-speed playback would have been 220 * rate.
+ }
+ // And a lower voice, a higher one, a slower speed.
+ for (const hz of [110, 440]) {
+ const f = frequency(timeStretch([tone(hz, 3)], SR, 1.75)[0]);
+ assert.ok(Math.abs(f - hz) < hz * 0.015, `${f.toFixed(1)} Hz for ${hz} Hz at 1.75x`);
+ }
+ const f = frequency(timeStretch([tone(220, 2)], SR, 0.5)[0]);
+ assert.ok(Math.abs(f - 220) < 3, `${f.toFixed(1)} Hz at 0.5x`);
+});
+
+test("a steady tone comes out steady: no dips where the frames overlap", () => {
+ const [y] = timeStretch([tone(220, 3)], SR, 2);
+ // RMS over 10 ms windows, away from the edges, stays near the tone's own
+ // (0.5 / sqrt 2): an out-of-phase overlap would cancel and dip.
+ const want = 0.5 / Math.SQRT2;
+ const w = SR / 100;
+ for (let s = w * 5; s + w < y.length - w * 5; s += w) {
+ let e = 0;
+ for (let i = s; i < s + w; i++) e += y[i] * y[i];
+ const rms = Math.sqrt(e / w);
+ assert.ok(Math.abs(rms - want) < want * 0.08, `rms ${rms.toFixed(3)} at ${(s / SR).toFixed(2)} s`);
+ }
+});
+
+test("the range begins with its own first samples, unfaded", () => {
+ const x = tone(180, 1);
+ const [y] = timeStretch([x], SR, 2);
+ for (let i = 0; i < 600; i++) assert.ok(Math.abs(y[i] - x[i]) < 1e-6, `sample ${i}`);
+});
+
+test("silence stays silent and a short range is still the right length", () => {
+ const [z] = timeStretch([new Float32Array(SR)], SR, 1.5);
+ assert.equal(z.length, stretchedLength(SR, 1.5));
+ assert.ok(z.every((v) => v === 0));
+ // Under one frame: resampled, the length still right.
+ const [s] = timeStretch([tone(220, 0.02)], SR, 2);
+ assert.equal(s.length, stretchedLength(Math.round(0.02 * SR), 2));
+ assert.deepEqual(timeStretch([], SR, 2), []);
+});
+
+test("the decode cap (120 s of stereo) stretches in well under a click's patience", () => {
+ const a = tone(140, 120);
+ const b = tone(150, 120);
+ const t = performance.now();
+ const out = timeStretch([a, b], SR, 1.5);
+ const ms = performance.now() - t;
+ assert.equal(out[0].length, stretchedLength(a.length, 1.5));
+ // Generous for a loaded CI box; on this machine it is a few hundred ms.
+ assert.ok(ms < 4000, `${Math.round(ms)} ms`);
+});
+
+test("the range ends with its own last samples, unfaded", () => {
+ const x = tone(180, 1);
+ for (const rate of [1.5, 2]) {
+ const [y] = timeStretch([x], SR, rate);
+ for (let i = 1; i <= 600; i++) {
+ assert.ok(Math.abs(y[y.length - i] - x[x.length - i]) < 1e-6, `sample -${i} at ${rate}x`);
+ }
+ }
+});
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -136,6 +136,9 @@ export default defineConfig({
// var. CHANNELS_DIR has to be said explicitly: it is where a report
// video's cue files live, and its default is the real 3 GB corpus.
`CHANNELS_DIR=${FIXTURE}/channels ` +
+ // The saved-video store is a read root too (a whole recording a clip
+ // cuts from): the fixture's own, never the real store.
+ `SAVED_VIDEOS_DIR=${FIXTURE}/saved-videos ` +
// The sites (/sites, article notes): the fixture's own, never the real
// transcripts/sites -- the one corpus file umtool writes is a report's
// notes.json, and the suite writes them.