Skip to content

🎥 Make videos programmatically with React

wsola again

JonnyBurgereab6dc5105b7
diff --git a/packages/media/src/convert-audiodata/apply-tonefrequency.ts b/packages/media/src/convert-audiodata/apply-tonefrequency.ts
index 79b7c572f8..1e721d91cb 100644
--- a/packages/media/src/convert-audiodata/apply-tonefrequency.ts
+++ b/packages/media/src/convert-audiodata/apply-tonefrequency.ts
@@ -1,6 +1,6 @@
import {FORMAT, type PcmS16AudioData} from './convert-audiodata';
import {resampleAudioData, TARGET_SAMPLE_RATE} from './resample-audiodata';
-import {atempoInt16Interleaved} from './wsola';
+import {wsolaInt16Interleaved} from './wsola';
export const applyToneFrequency = (
audioData: PcmS16AudioData,
@@ -45,7 +45,7 @@ export const applyToneFrequency = (
timestamp: audioData.timestamp,
};
- const step3Data = atempoInt16Interleaved(
+ const step3Data = wsolaInt16Interleaved(
step2AudioData.data,
step2AudioData.numberOfChannels,
toneFrequency,
diff --git a/packages/media/src/convert-audiodata/wsola.ts b/packages/media/src/convert-audiodata/wsola.ts
index ae335fda14..5a49f7e9a3 100644
--- a/packages/media/src/convert-audiodata/wsola.ts
+++ b/packages/media/src/convert-audiodata/wsola.ts
@@ -4,62 +4,70 @@ function clamp16(x: number): number {
}
/**
- * Time-scale modification (tempo change) with approximate pitch preservation
- * for interleaved Int16 PCM with multiple channels, using a SOLA/WSOLA-like method.
+ * WSOLA time-scale modification for interleaved Int16 PCM (multi-channel).
+ * - Preserves pitch approximately while changing tempo by factor f.
+ * - Works for N interleaved channels.
+ * - Mitigates head/tail fade-out via overlap-weight normalization and boundary reinforcement.
*
- * @param input Interleaved Int16 PCM samples (e.g., LR LR LR ...)
- * @param channels Number of channels (e.g., 2 for stereo)
- * @param f Tempo factor: >1.0 = faster (shorter), <1.0 = slower (longer)
+ * @param input Interleaved Int16 PCM (e.g., LRLRLR... for stereo)
+ * @param channels Number of channels (>=1)
+ * @param f Tempo factor: >1 = faster/shorter, <1 = slower/longer
* @param opts Optional tuning parameters
- * @returns Interleaved Int16 PCM with length ≈ round(input.length * f)
+ * @returns Interleaved Int16Array with length ≈ round(input.length * f)
*/
-export function atempoInt16Interleaved(
+export function wsolaInt16Interleaved(
input: Int16Array,
channels: number,
f: number,
): Int16Array {
- const sampleRate = 48000;
- if (!Number.isFinite(f) || f <= 0) {
+ if (!Number.isFinite(f) || f <= 0)
throw new Error('f must be a positive finite number');
- }
-
- if (!Number.isInteger(channels) || channels <= 0) {
+ if (!Number.isInteger(channels) || channels <= 0)
throw new Error('channels must be a positive integer');
- }
const n = input.length;
if (n === 0) return new Int16Array(0);
- if (n % channels !== 0) {
- throw new Error(
- 'input length must be a multiple of channels (interleaved PCM)',
- );
- }
+ if (n % channels !== 0)
+ throw new Error('input length must be a multiple of channels');
- const frameMs = Math.round(1000 * (1 / 24));
+ // Parameters and sensible defaults
+ const sampleRate = 48_000;
+ const frameMs = 30; // 20–40 ms typical
const overlapRatio = 0.5;
- const searchMs = 15;
+ const searchMs = 8; // +/- 8 ms local search
+ const winKind = 'hann';
+ const headReinf = 3;
+ const tailReinf = 3;
- // Work in samples per channel
+ // Work per-channel
const samplesPerChannel = (n / channels) | 0;
- // Frame sizing and hops (per channel)
+ // Frame and hop sizing
const frameSize = Math.max(128, Math.floor((sampleRate * frameMs) / 1_000));
const overlap = Math.floor(frameSize * overlapRatio);
const anaHop = Math.max(1, frameSize - overlap);
const synHop = Math.max(1, Math.round(anaHop * f));
+
+ // Search radius in samples
const searchRadius = Math.max(0, Math.floor((sampleRate * searchMs) / 1_000));
// Window
const win = new Float32Array(frameSize);
for (let i = 0; i < frameSize; i++) {
const x = (Math.PI * 2 * i) / (frameSize - 1);
- win[i] = 0.5 * (1 - Math.cos(x));
+ win[i] =
+ winKind === 'hann' ? 0.5 * (1 - Math.cos(x)) : 0.54 - 0.46 * Math.cos(x); // Hamming
}
- // Output buffers as float accumulators per channel
- const estFrames = Math.ceil((samplesPerChannel - frameSize) / anaHop) + 1;
+ // Estimate output length per channel and allocate with extra headroom
+ const estFrames = Math.max(
+ 1,
+ Math.ceil(Math.max(0, samplesPerChannel - frameSize) / anaHop) + 1,
+ );
const estLen = Math.max(0, frameSize + synHop * (estFrames - 1));
- const outLenAlloc = estLen + frameSize + searchRadius + 16;
+ const extraHead = frameSize * (headReinf + 1);
+ const extraTail = frameSize * (tailReinf + 2);
+ const outLenAlloc = estLen + searchRadius + extraHead + extraTail;
const out = Array.from(
{length: channels},
@@ -67,34 +75,30 @@ export function atempoInt16Interleaved(
);
const outWeight = new Float32Array(outLenAlloc);
- // Helper: read one channel’s frame from interleaved PCM
+ // Temporary buffers
+ const chanFrames = Array.from(
+ {length: channels},
+ () => new Float32Array(frameSize),
+ );
+ const guideFrame = new Float32Array(frameSize);
+
+ // Helpers
function readChannelFrame(chan: number, start: number, dst: Float32Array) {
- // start is per-channel sample index
let srcIndex = start * channels + chan;
for (let i = 0; i < frameSize; i++) {
const pos = start + i;
- let v = 0;
- if (pos >= 0 && pos < samplesPerChannel) {
- v = input[srcIndex];
- }
-
- dst[i] = v;
+ dst[i] = pos >= 0 && pos < samplesPerChannel ? input[srcIndex] : 0;
srcIndex += channels;
}
}
- // Build a mono guide frame (mid/mono mix) to drive alignment
- const guideFrame = new Float32Array(frameSize);
function readGuideFrame(start: number) {
for (let i = 0; i < frameSize; i++) {
const pos = start + i;
if (pos >= 0 && pos < samplesPerChannel) {
let sum = 0;
- const base = (pos * channels) | 0;
- for (let c = 0; c < channels; c++) {
- sum += input[base + c];
- }
-
+ const base = pos * channels;
+ for (let c = 0; c < channels; c++) sum += input[base + c];
guideFrame[i] = sum / channels;
} else {
guideFrame[i] = 0;
@@ -102,20 +106,18 @@ export function atempoInt16Interleaved(
}
}
- // Cross-correlation on overlap region using guide to find best local alignment
- function bestAlignment(outPoss: number, baseShift: number): number {
- let bestShift = baseShift;
+ // Find best local alignment around outPos using normalized cross-correlation
+ function bestAlignment(outPoss: number): number {
+ let bestShift = 0;
let bestScore = -Infinity;
-
for (let shift = -searchRadius; shift <= searchRadius; shift++) {
const pos = outPoss + shift - overlap;
let score = 0;
let normA = 0;
let normB = 0;
-
for (let i = 0; i < overlap; i++) {
- const outIdx = pos + i;
- const outVal = outIdx >= 0 && outIdx < outLenAlloc ? out[0][outIdx] : 0; // use channel 0 accumulator as proxy
+ const idx = pos + i;
+ const outVal = idx >= 0 && idx < outLenAlloc ? out[0][idx] : 0; // channel 0 proxy
const frmVal = guideFrame[i];
score += outVal * frmVal;
normA += outVal * outVal;
@@ -133,75 +135,96 @@ export function atempoInt16Interleaved(
return bestShift;
}
- // Temp buffers per channel
- const chanFrames = Array.from(
- {length: channels},
- () => new Float32Array(frameSize),
- );
-
- let inPos = 0; // per-channel sample index
- let outPos = 0; // per-channel sample index in accumulators
-
- // First frame: place directly
- readGuideFrame(0);
- for (let c = 0; c < channels; c++) {
- readChannelFrame(c, 0, chanFrames[c]);
- for (let i = 0; i < frameSize; i++) {
- const w = win[i];
- const idx = i; // write starting at 0
- out[c][idx] += chanFrames[c][i] * w;
- if (c === 0) outWeight[idx] += w;
- }
- }
-
- inPos += anaHop;
- outPos += synHop;
-
- // Process remaining frames
- while (inPos < samplesPerChannel - 1) {
- readGuideFrame(inPos);
-
- // Find best alignment using guide
- const shift = bestAlignment(outPos, 0);
- const writeStart = outPos + shift - overlap;
-
- // Windowed overlap-add for each channel using same alignment
+ // Overlap-add a frame for all channels at writeStart with windowing
+ function olaAllChannels(writeStart: number) {
for (let c = 0; c < channels; c++) {
- readChannelFrame(c, inPos, chanFrames[c]);
for (let i = 0; i < frameSize; i++) {
const idx = writeStart + i;
if (idx >= 0 && idx < outLenAlloc) {
const w = win[i];
out[c][idx] += chanFrames[c][i] * w;
- if (c === 0) outWeight[idx] += w;
+ if (c === 0) outWeight[idx] += w; // track weights once
}
}
}
+ }
+
+ // 1) Seed: place the first frame at t=0
+ readGuideFrame(0);
+ for (let c = 0; c < channels; c++) readChannelFrame(c, 0, chanFrames[c]);
+ olaAllChannels(0);
+
+ // 2) Head reinforcement: place extra frames whose writeStart <= 0
+ for (let h = 0; h < headReinf; h++) {
+ // Option 1: reuse the first analysis position to strengthen early region
+ const headIn = Math.min(
+ anaHop * h,
+ Math.max(0, samplesPerChannel - frameSize),
+ );
+ readGuideFrame(headIn);
+ for (let c = 0; c < channels; c++)
+ readChannelFrame(c, headIn, chanFrames[c]);
+ // Align around outPos=0 so we bias writeStart near/before 0
+ const shift = bestAlignment(0);
+ const writeStart = shift - overlap; // likely negative; ok, we clamp on write
+ olaAllChannels(writeStart);
+ }
+
+ // 3) Main WSOLA loop
+ let inPos = anaHop; // next analysis position (we already seeded at 0)
+ let outPos = synHop; // next synthesis position
+
+ while (inPos < samplesPerChannel - 1) {
+ readGuideFrame(inPos);
+ for (let c = 0; c < channels; c++)
+ readChannelFrame(c, inPos, chanFrames[c]);
+
+ const shift = bestAlignment(outPos);
+ const writeStart = outPos + shift - overlap;
+ olaAllChannels(writeStart);
inPos += anaHop;
outPos += synHop;
- if (outPos + frameSize + searchRadius + 8 >= outLenAlloc) break;
+ // Safety: if we're very close to capacity, break to handle tail separately
+ if (outPos > outLenAlloc - (frameSize + searchRadius + 8)) break;
}
- // Normalize by accumulated window weights
+ // 4) Tail reinforcement: ensure the end gets full coverage
+ // Place a few extra frames around the last outPos using the last available input frames.
+ for (let t = 0; t < tailReinf; t++) {
+ const tailIn = Math.max(
+ 0,
+ Math.min(samplesPerChannel - frameSize, inPos - anaHop * t),
+ );
+ readGuideFrame(tailIn);
+ for (let c = 0; c < channels; c++)
+ readChannelFrame(c, tailIn, chanFrames[c]);
+
+ const shift = bestAlignment(outPos);
+ const writeStart = outPos + shift - overlap;
+ olaAllChannels(writeStart);
+
+ outPos += synHop;
+ }
+
+ // 5) Normalize by accumulated weights BEFORE trimming
for (let i = 0; i < outLenAlloc; i++) {
const w = outWeight[i];
if (w > 1e-9) {
const inv = 1 / w;
- for (let c = 0; c < channels; c++) {
- out[c][i] *= inv;
- }
+ for (let c = 0; c < channels; c++) out[c][i] *= inv;
+ } else {
+ for (let c = 0; c < channels; c++) out[c][i] = 0;
}
}
- // Target per-channel length and interleave
+ // 6) Produce final interleaved Int16Array with length ≈ round(n * f)
const targetPerChan = Math.max(1, Math.round(samplesPerChannel * f));
const targetTotal = targetPerChan * channels;
-
const result = new Int16Array(targetTotal);
- // Clamp/convert and interleave
+ // Interleave and clamp/round
for (let i = 0; i < targetPerChan; i++) {
for (let c = 0; c < channels; c++) {
const v = i < out[c].length ? out[c][i] : 0;