Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/web-renderer`: Add client-side pitch shifting with `toneFrequency`

JonnyBurger0a961e1a3460
diff --git a/packages/core/src/audio/streaming-pitch-shifter.ts b/packages/core/src/audio/streaming-pitch-shifter.ts
new file mode 100644
index 0000000000..fc269421ce
--- /dev/null
+++ b/packages/core/src/audio/streaming-pitch-shifter.ts
@@ -0,0 +1,491 @@
+// The pitch-shifting algorithm is adapted from Vanilagy's WSOLA audio
+// stretcher: https://gist.github.com/Vanilagy/05f7901f4c4398356657e3a86c7aee05
+const REFERENCE_SAMPLE_RATE = 48_000;
+const REFERENCE_HOP_SIZE = 512;
+
+type PlanarAudio = Float32Array[];
+
+const makePlanarAudio = (numberOfChannels: number, length: number) => {
+ return new Array(numberOfChannels)
+ .fill(null)
+ .map(() => new Float32Array(length));
+};
+
+const ensurePlanarCapacity = ({
+ buffers,
+ requiredLength,
+}: {
+ buffers: PlanarAudio;
+ requiredLength: number;
+}) => {
+ if (buffers[0].length >= requiredLength) {
+ return buffers;
+ }
+
+ let newLength = buffers[0].length;
+ while (newLength < requiredLength) {
+ newLength *= 2;
+ }
+
+ return buffers.map((buffer) => {
+ const expanded = new Float32Array(newLength);
+ expanded.set(buffer);
+ return expanded;
+ });
+};
+
+class PlanarAudioQueue {
+ private chunks: PlanarAudio[] = [];
+ private length = 0;
+
+ public push(audio: PlanarAudio) {
+ if (audio[0].length === 0) {
+ return;
+ }
+
+ this.chunks.push(audio);
+ this.length += audio[0].length;
+ }
+
+ public take(numberOfFrames: number, numberOfChannels: number): PlanarAudio {
+ const framesToTake = Math.min(numberOfFrames, this.length);
+ const result = makePlanarAudio(numberOfChannels, framesToTake);
+ let written = 0;
+
+ while (written < framesToTake) {
+ const first = this.chunks[0];
+ const available = first[0].length;
+ const count = Math.min(available, framesToTake - written);
+
+ for (let channel = 0; channel < numberOfChannels; channel++) {
+ result[channel].set(first[channel].subarray(0, count), written);
+ }
+
+ if (count === available) {
+ this.chunks.shift();
+ } else {
+ this.chunks[0] = first.map((channel) => channel.subarray(count));
+ }
+
+ written += count;
+ this.length -= count;
+ }
+
+ return result;
+ }
+
+ public getLength() {
+ return this.length;
+ }
+}
+
+// A streaming implementation of Waveform Similarity Overlap-Add. It changes
+// duration while retaining pitch. Pitch shifting is achieved by following this
+// stage with a resampler that restores the original duration.
+class StreamingTimeStretcher {
+ private readonly numberOfChannels: number;
+ private readonly factor: number;
+ private readonly hopSize: number;
+ private readonly windowSize: number;
+ private readonly searchRadius: number;
+ private readonly analysisHop: number;
+ private input: PlanarAudio;
+ private inputLength = 0;
+ private output: PlanarAudio;
+ private outputLength = 0;
+ private analysisPosition = 0;
+ private synthesisPosition = 0;
+ private initialized = false;
+ private finalized = false;
+ private totalInputFrames = 0;
+ private totalOutputFrames = 0;
+
+ public constructor({
+ numberOfChannels,
+ sampleRate,
+ factor,
+ }: {
+ numberOfChannels: number;
+ sampleRate: number;
+ factor: number;
+ }) {
+ this.numberOfChannels = numberOfChannels;
+ this.factor = factor;
+ this.hopSize = Math.max(
+ 32,
+ Math.round((REFERENCE_HOP_SIZE * sampleRate) / REFERENCE_SAMPLE_RATE),
+ );
+ this.windowSize = this.hopSize * 2;
+ this.searchRadius = this.hopSize;
+ this.analysisHop = this.hopSize / factor;
+ this.input = makePlanarAudio(numberOfChannels, 65_536);
+ this.output = makePlanarAudio(numberOfChannels, 65_536);
+ }
+
+ public append(audio: PlanarAudio) {
+ if (this.finalized) {
+ throw new Error(
+ 'Cannot append audio after the time stretcher was finalized.',
+ );
+ }
+
+ const {length} = audio[0];
+ this.input = ensurePlanarCapacity({
+ buffers: this.input,
+ requiredLength: this.inputLength + length,
+ });
+
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ this.input[channel].set(audio[channel], this.inputLength);
+ }
+
+ this.inputLength += length;
+ this.totalInputFrames += length;
+ this.process();
+ return this.drainFinalizedOutput();
+ }
+
+ private findBestAnalysisPosition({
+ expectedPosition,
+ nextSynthesisPosition,
+ }: {
+ expectedPosition: number;
+ nextSynthesisPosition: number;
+ }) {
+ const minimum = Math.max(
+ 0,
+ Math.floor(expectedPosition - this.searchRadius),
+ );
+ const maximum = Math.min(
+ this.inputLength - this.windowSize,
+ Math.ceil(expectedPosition + this.searchRadius),
+ );
+
+ let bestPosition = minimum;
+ let bestCorrelation = -Infinity;
+
+ for (let candidate = minimum; candidate <= maximum; candidate += 4) {
+ let dotProduct = 0;
+ let previousEnergy = 0;
+ let candidateEnergy = 0;
+
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ const previous = this.output[channel];
+ const incoming = this.input[channel];
+ for (let frame = 0; frame < this.hopSize; frame += 2) {
+ const previousValue = previous[nextSynthesisPosition + frame];
+ const candidateValue = incoming[candidate + frame];
+ dotProduct += previousValue * candidateValue;
+ previousEnergy += previousValue * previousValue;
+ candidateEnergy += candidateValue * candidateValue;
+ }
+ }
+
+ const correlation =
+ dotProduct /
+ (Math.sqrt(previousEnergy * candidateEnergy) || Number.EPSILON);
+ if (correlation > bestCorrelation) {
+ bestCorrelation = correlation;
+ bestPosition = candidate;
+ }
+ }
+
+ const fineMinimum = Math.max(minimum, bestPosition - 4);
+ const fineMaximum = Math.min(maximum, bestPosition + 4);
+ for (let candidate = fineMinimum; candidate <= fineMaximum; candidate++) {
+ let dotProduct = 0;
+ let previousEnergy = 0;
+ let candidateEnergy = 0;
+
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ const previous = this.output[channel];
+ const incoming = this.input[channel];
+ for (let frame = 0; frame < this.hopSize; frame++) {
+ const previousValue = previous[nextSynthesisPosition + frame];
+ const candidateValue = incoming[candidate + frame];
+ dotProduct += previousValue * candidateValue;
+ previousEnergy += previousValue * previousValue;
+ candidateEnergy += candidateValue * candidateValue;
+ }
+ }
+
+ const correlation =
+ dotProduct /
+ (Math.sqrt(previousEnergy * candidateEnergy) || Number.EPSILON);
+ if (correlation > bestCorrelation) {
+ bestCorrelation = correlation;
+ bestPosition = candidate;
+ }
+ }
+
+ return bestPosition;
+ }
+
+ private process() {
+ if (!this.initialized) {
+ if (this.inputLength < this.windowSize + this.searchRadius) {
+ return;
+ }
+
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ this.output[channel].set(
+ this.input[channel].subarray(0, this.windowSize),
+ );
+ }
+
+ this.outputLength = this.windowSize;
+ this.initialized = true;
+ }
+
+ while (true) {
+ const expectedPosition = this.analysisPosition + this.analysisHop;
+ if (
+ expectedPosition + this.searchRadius + this.windowSize >
+ this.inputLength
+ ) {
+ break;
+ }
+
+ const nextSynthesisPosition = this.synthesisPosition + this.hopSize;
+ this.output = ensurePlanarCapacity({
+ buffers: this.output,
+ requiredLength: nextSynthesisPosition + this.windowSize,
+ });
+ const bestPosition = this.findBestAnalysisPosition({
+ expectedPosition,
+ nextSynthesisPosition,
+ });
+
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ for (let frame = 0; frame < this.hopSize; frame++) {
+ const fadeIn =
+ 0.5 - 0.5 * Math.cos((Math.PI * (frame + 1)) / (this.hopSize + 1));
+ const outputIndex = nextSynthesisPosition + frame;
+ this.output[channel][outputIndex] =
+ this.output[channel][outputIndex] * (1 - fadeIn) +
+ this.input[channel][bestPosition + frame] * fadeIn;
+ }
+
+ this.output[channel].set(
+ this.input[channel].subarray(
+ bestPosition + this.hopSize,
+ bestPosition + this.windowSize,
+ ),
+ nextSynthesisPosition + this.hopSize,
+ );
+ }
+
+ // Keep the analysis clock independent from the correlation correction.
+ // Periodic signals can have equally good matches at an earlier period; if
+ // the correction became the next clock position, the iterator could stop
+ // making forward progress.
+ this.analysisPosition = expectedPosition;
+ this.synthesisPosition = nextSynthesisPosition;
+ this.outputLength = nextSynthesisPosition + this.windowSize;
+ }
+ }
+
+ private drainFinalizedOutput() {
+ if (!this.initialized) {
+ return makePlanarAudio(this.numberOfChannels, 0);
+ }
+
+ const finalizedLength = Math.max(0, this.synthesisPosition + this.hopSize);
+ const result = this.output.map((channel) =>
+ channel.slice(0, finalizedLength),
+ );
+ this.totalOutputFrames += finalizedLength;
+
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ this.output[channel].copyWithin(0, finalizedLength, this.outputLength);
+ }
+
+ this.outputLength -= finalizedLength;
+ this.synthesisPosition -= finalizedLength;
+
+ const inputFramesToDiscard = Math.max(
+ 0,
+ Math.floor(this.analysisPosition) - this.searchRadius,
+ );
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ this.input[channel].copyWithin(0, inputFramesToDiscard, this.inputLength);
+ }
+
+ this.inputLength -= inputFramesToDiscard;
+ this.analysisPosition -= inputFramesToDiscard;
+ return result;
+ }
+
+ public finalize() {
+ if (this.finalized) {
+ throw new Error('The time stretcher has already been finalized.');
+ }
+
+ this.finalized = true;
+ const targetLength = Math.round(this.totalInputFrames * this.factor);
+ const padding = makePlanarAudio(
+ this.numberOfChannels,
+ this.windowSize + this.searchRadius * 2,
+ );
+ this.input = ensurePlanarCapacity({
+ buffers: this.input,
+ requiredLength: this.inputLength + padding[0].length,
+ });
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ this.input[channel].set(padding[channel], this.inputLength);
+ }
+
+ this.inputLength += padding[0].length;
+ this.process();
+ const finalized = this.drainFinalizedOutput();
+ const remaining = Math.max(
+ 0,
+ targetLength - this.totalOutputFrames + finalized[0].length,
+ );
+
+ if (finalized[0].length >= remaining) {
+ return finalized.map((channel) => channel.slice(0, remaining));
+ }
+
+ const result = makePlanarAudio(this.numberOfChannels, remaining);
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ result[channel].set(finalized[channel]);
+ }
+
+ return result;
+ }
+}
+
+class StreamingLinearResampler {
+ private readonly numberOfChannels: number;
+ private readonly step: number;
+ private input: PlanarAudio;
+ private inputLength = 0;
+ private position = 0;
+
+ public constructor({
+ numberOfChannels,
+ step,
+ }: {
+ numberOfChannels: number;
+ step: number;
+ }) {
+ this.numberOfChannels = numberOfChannels;
+ this.step = step;
+ this.input = makePlanarAudio(numberOfChannels, 65_536);
+ }
+
+ public append(audio: PlanarAudio) {
+ this.input = ensurePlanarCapacity({
+ buffers: this.input,
+ requiredLength: this.inputLength + audio[0].length,
+ });
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ this.input[channel].set(audio[channel], this.inputLength);
+ }
+
+ this.inputLength += audio[0].length;
+ return this.process(false);
+ }
+
+ private process(finalizing: boolean) {
+ const outputLength = Math.max(
+ 0,
+ Math.floor(
+ (this.inputLength - (finalizing ? 0 : 1) - this.position) / this.step,
+ ) + 1,
+ );
+ const result = makePlanarAudio(this.numberOfChannels, outputLength);
+
+ for (let outputFrame = 0; outputFrame < outputLength; outputFrame++) {
+ const leftIndex = Math.floor(this.position);
+ const rightIndex = Math.min(leftIndex + 1, this.inputLength - 1);
+ const fraction = this.position - leftIndex;
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ const left = this.input[channel][leftIndex];
+ const right = this.input[channel][rightIndex];
+ result[channel][outputFrame] = left + (right - left) * fraction;
+ }
+
+ this.position += this.step;
+ }
+
+ const discard = Math.min(Math.floor(this.position), this.inputLength);
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ this.input[channel].copyWithin(0, discard, this.inputLength);
+ }
+
+ this.inputLength -= discard;
+ this.position -= discard;
+ return result;
+ }
+
+ public finalize() {
+ return this.process(true);
+ }
+}
+
+export class StreamingPitchShifter {
+ private readonly numberOfChannels: number;
+ private readonly stretcher: StreamingTimeStretcher;
+ private readonly resampler: StreamingLinearResampler;
+ private readonly outputQueue = new PlanarAudioQueue();
+ private totalInputFrames = 0;
+ private totalOutputFrames = 0;
+
+ public constructor({
+ numberOfChannels,
+ sampleRate,
+ toneFrequency,
+ }: {
+ numberOfChannels: number;
+ sampleRate: number;
+ toneFrequency: number;
+ }) {
+ this.numberOfChannels = numberOfChannels;
+ this.stretcher = new StreamingTimeStretcher({
+ numberOfChannels,
+ sampleRate,
+ factor: toneFrequency,
+ });
+ this.resampler = new StreamingLinearResampler({
+ numberOfChannels,
+ step: toneFrequency,
+ });
+ }
+
+ public append(audio: PlanarAudio) {
+ this.totalInputFrames += audio[0].length;
+ const stretched = this.stretcher.append(audio);
+ this.outputQueue.push(this.resampler.append(stretched));
+ return this.takeAvailableOutput();
+ }
+
+ private takeAvailableOutput() {
+ const availableInputFrames = this.totalInputFrames - this.totalOutputFrames;
+ const framesToTake = Math.min(
+ availableInputFrames,
+ this.outputQueue.getLength(),
+ );
+ const result = this.outputQueue.take(framesToTake, this.numberOfChannels);
+ this.totalOutputFrames += framesToTake;
+ return result;
+ }
+
+ public finalize() {
+ this.outputQueue.push(this.resampler.append(this.stretcher.finalize()));
+ this.outputQueue.push(this.resampler.finalize());
+ const remaining = this.totalInputFrames - this.totalOutputFrames;
+ const available = this.outputQueue.take(
+ Math.min(remaining, this.outputQueue.getLength()),
+ this.numberOfChannels,
+ );
+ const result = makePlanarAudio(this.numberOfChannels, remaining);
+ for (let channel = 0; channel < this.numberOfChannels; channel++) {
+ result[channel].set(available[channel]);
+ }
+
+ this.totalOutputFrames += remaining;
+ return result;
+ }
+}
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index 51d3c6e813..c43405a4dd 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -11,6 +11,7 @@ import {
SharedAudioTagsContextProvider,
type ScheduleAudioNodeOptions,
} from './audio/shared-audio-tags.js';
+import {StreamingPitchShifter} from './audio/streaming-pitch-shifter.js';
import type {RemotionAudioContextState} from './audio/use-audio-context.js';
import {
useFrameForVolumeProp,
@@ -298,6 +299,7 @@ const compositionSelectorRef = createRef<{
// Mark them as Internals so use don't assume this is public
// API and are less likely to use it
export const Internals = {
+ StreamingPitchShifter,
AbsoluteFillElement,
MaxMediaCacheSizeContext,
getMediabunnyInputResourceKey,
diff --git a/packages/docs/docs/audio/pitch.mdx b/packages/docs/docs/audio/pitch.mdx
index a1fa591818..7e39257334 100644
--- a/packages/docs/docs/audio/pitch.mdx
+++ b/packages/docs/docs/audio/pitch.mdx
@@ -10,8 +10,8 @@ Use the `toneFrequency` prop to control the pitch of audio.
| Tag | Preview | [Server-side rendering](/docs/ssr) | [Client-side rendering](/docs/client-side-rendering) |
| ---------------------------------------------------------- | --------------------------------------- | --------------------------------------- | ---------------------------------------------------- |
-| [`<Audio>`](/docs/media/audio) from `@remotion/media` | βœ… <AvailableFrom v="4.0.520" inline /> | βœ… <AvailableFrom v="4.0.357" inline /> | ❌ |
-| [`<Video>`](/docs/media/video) from `@remotion/media` | βœ… <AvailableFrom v="4.0.520" inline /> | βœ… <AvailableFrom v="4.0.357" inline /> | ❌ |
+| [`<Audio>`](/docs/media/audio) from `@remotion/media` | βœ… <AvailableFrom v="4.0.520" inline /> | βœ… <AvailableFrom v="4.0.357" inline /> | βœ… <AvailableFrom v="4.0.523" inline /> |
+| [`<Video>`](/docs/media/video) from `@remotion/media` | βœ… <AvailableFrom v="4.0.520" inline /> | βœ… <AvailableFrom v="4.0.357" inline /> | βœ… <AvailableFrom v="4.0.523" inline /> |
| [`<Html5Audio>`](/docs/html5-audio) from `remotion` | ❌ | βœ… <AvailableFrom v="4.0.47" inline /> | ❌ |
| [`<Html5Video>`](/docs/html5-video) from `remotion` | ❌ | βœ… <AvailableFrom v="4.0.47" inline /> | ❌ |
| [`<OffthreadVideo>`](/docs/offthreadvideo) from `remotion` | ❌ | βœ… <AvailableFrom v="4.0.47" inline /> | ❌ |
@@ -20,7 +20,7 @@ Values between `0.01` and `2` are accepted, where `1` represents the original pi
A `toneFrequency` of 0.5 would lower the pitch by half, and a `toneFrequency` of `1.5` would increase the pitch by 50%.
-The value can be changed while previewing, but it cannot be keyframed.
+The value can be changed while previewing. During rendering, it must stay constant for each audio or video asset.
```tsx twoslash {7} title="MyComp.tsx"
import {Audio} from '@remotion/media';
diff --git a/packages/docs/docs/client-side-rendering/limitations.mdx b/packages/docs/docs/client-side-rendering/limitations.mdx
index c280e68168..54664b2fe3 100644
--- a/packages/docs/docs/client-side-rendering/limitations.mdx
+++ b/packages/docs/docs/client-side-rendering/limitations.mdx
@@ -189,6 +189,8 @@ const MyComp = () => {
The limitations from [`@remotion/media`](/docs/media/support) apply.
+The [`toneFrequency`](/docs/audio/pitch) prop of `<Audio>` and `<Video>` from `@remotion/media` is supported from <AvailableFrom v="4.0.523" inline />. Its value must stay constant for each audio or video asset throughout the render.
+
## Single concurrency
There is no multithreading for client-side rendering.
diff --git a/packages/docs/docs/media/audio.mdx b/packages/docs/docs/media/audio.mdx
index c1c547894b..0323ddcecf 100644
--- a/packages/docs/docs/media/audio.mdx
+++ b/packages/docs/docs/media/audio.mdx
@@ -313,7 +313,7 @@ A `toneFrequency` of 0.5 would lower the pitch by half, and a `toneFrequency` of
The value can be changed while previewing. It must stay constant across the composition timeline during rendering.
-Works during preview and server-side rendering. It is not supported during [client-side rendering](/docs/client-side-rendering/).
+Works during preview and server-side rendering. [Client-side rendering](/docs/client-side-rendering/) is supported from <AvailableFrom v="4.0.523" inline />.
If the component [falls back to `<Html5Audio>`](/docs/media/fallback) during preview, pitch shifting is not applied.
diff --git a/packages/docs/docs/media/video.mdx b/packages/docs/docs/media/video.mdx
index bc0f11e0d0..f6ad7a1d2b 100644
--- a/packages/docs/docs/media/video.mdx
+++ b/packages/docs/docs/media/video.mdx
@@ -432,7 +432,7 @@ A `toneFrequency` of 0.5 would lower the pitch by half, and a `toneFrequency` of
The value can be changed while previewing. It must stay constant across the composition timeline during rendering.
-Works during preview and server-side rendering. It is not supported during [client-side rendering](/docs/client-side-rendering/).
+Works during preview and server-side rendering. [Client-side rendering](/docs/client-side-rendering/) is supported from <AvailableFrom v="4.0.523" inline />.
If the component [falls back to `<OffthreadVideo>`](/docs/media/fallback) during preview, pitch shifting is not applied.
diff --git a/packages/docs/docs/video-tags.mdx b/packages/docs/docs/video-tags.mdx
index 9121e0ce7d..fe643d81e6 100644
--- a/packages/docs/docs/video-tags.mdx
+++ b/packages/docs/docs/video-tags.mdx
@@ -30,7 +30,7 @@ The comparison below shows when a fallback or alternative may be relevant.
| **CORS required** | Yes | No | No |
| **Loopable** | βœ… | ❌ | βœ… |
| **`playbackRate`** <br/> (Speed Change) | βœ…, but audio pitch changes with the speed | βœ…, audio pitch is preserved by default | βœ…, audio pitch is preserved by default |
-| **`toneFrequency`** <br/> (Pitch Change) | During preview and server-side rendering | Only during server-side rendering | Only during server-side rendering |
+| **`toneFrequency`** <br/> (Pitch Change) | During preview, server-side rendering, and client-side rendering (from v4.0.523) | Only during server-side rendering | Only during server-side rendering |
| **[Three.js texture](/docs/videos/as-threejs-texture)** | [Snippet](/docs/videos/as-threejs-texture) - works best | [`useOffthreadVideoTexture()`](/docs/use-offthread-video-texture) | [ `useVideoTexture()` ](/docs/use-video-texture) |
| **[Client-side rendering](/docs/client-side-rendering)** | βœ… | ❌ | ❌ |
diff --git a/packages/media/src/audio/pitch-shift.ts b/packages/media/src/audio/pitch-shift.ts
index d0790c4a8e..c203b03b35 100644
--- a/packages/media/src/audio/pitch-shift.ts
+++ b/packages/media/src/audio/pitch-shift.ts
@@ -1,497 +1,6 @@
+import {Internals} from 'remotion';
import type {AudioBufferSlice} from '../make-iterator-with-priming';
-// The pitch-shifting algorithm is adapted from Vanilagy's WSOLA audio
-// stretcher: https://gist.github.com/Vanilagy/05f7901f4c4398356657e3a86c7aee05
-const REFERENCE_SAMPLE_RATE = 48_000;
-const REFERENCE_HOP_SIZE = 512;
-
-type PlanarAudio = Float32Array[];
-
-const makePlanarAudio = (numberOfChannels: number, length: number) => {
- return new Array(numberOfChannels)
- .fill(null)
- .map(() => new Float32Array(length));
-};
-
-const ensurePlanarCapacity = ({
- buffers,
- requiredLength,
-}: {
- buffers: PlanarAudio;
- requiredLength: number;
-}) => {
- if (buffers[0].length >= requiredLength) {
- return buffers;
- }
-
- let newLength = buffers[0].length;
- while (newLength < requiredLength) {
- newLength *= 2;
- }
-
- return buffers.map((buffer) => {
- const expanded = new Float32Array(newLength);
- expanded.set(buffer);
- return expanded;
- });
-};
-
-class PlanarAudioQueue {
- private chunks: PlanarAudio[] = [];
- private length = 0;
-
- public push(audio: PlanarAudio) {
- if (audio[0].length === 0) {
- return;
- }
-
- this.chunks.push(audio);
- this.length += audio[0].length;
- }
-
- public take(numberOfFrames: number, numberOfChannels: number): PlanarAudio {
- const framesToTake = Math.min(numberOfFrames, this.length);
- const result = makePlanarAudio(numberOfChannels, framesToTake);
- let written = 0;
-
- while (written < framesToTake) {
- const first = this.chunks[0];
- const available = first[0].length;
- const count = Math.min(available, framesToTake - written);
-
- for (let channel = 0; channel < numberOfChannels; channel++) {
- result[channel].set(first[channel].subarray(0, count), written);
- }
-
- if (count === available) {
- this.chunks.shift();
- } else {
- this.chunks[0] = first.map((channel) => channel.subarray(count));
- }
-
- written += count;
- this.length -= count;
- }
-
- return result;
- }
-
- public getLength() {
- return this.length;
- }
-}
-
-// A streaming implementation of Waveform Similarity Overlap-Add. It changes
-// duration while retaining pitch. Pitch shifting is achieved by following this
-// stage with a resampler that restores the original duration.
-class StreamingTimeStretcher {
- private readonly numberOfChannels: number;
- private readonly factor: number;
- private readonly hopSize: number;
- private readonly windowSize: number;
- private readonly searchRadius: number;
- private readonly analysisHop: number;
- private input: PlanarAudio;
- private inputLength = 0;
- private output: PlanarAudio;
- private outputLength = 0;
- private analysisPosition = 0;
- private synthesisPosition = 0;
- private initialized = false;
- private finalized = false;
- private totalInputFrames = 0;
- private totalOutputFrames = 0;
-
- public constructor({
- numberOfChannels,
- sampleRate,
- factor,
- }: {
- numberOfChannels: number;
- sampleRate: number;
- factor: number;
- }) {
- this.numberOfChannels = numberOfChannels;
- this.factor = factor;
- this.hopSize = Math.max(
- 32,
- Math.round((REFERENCE_HOP_SIZE * sampleRate) / REFERENCE_SAMPLE_RATE),
- );
- this.windowSize = this.hopSize * 2;
- this.searchRadius = this.hopSize;
- this.analysisHop = this.hopSize / factor;
- this.input = makePlanarAudio(numberOfChannels, 65_536);
- this.output = makePlanarAudio(numberOfChannels, 65_536);
- }
-
- public append(audio: PlanarAudio) {
- if (this.finalized) {
- throw new Error(
- 'Cannot append audio after the time stretcher was finalized.',
- );
- }
-
- const {length} = audio[0];
- this.input = ensurePlanarCapacity({
- buffers: this.input,
- requiredLength: this.inputLength + length,
- });
-
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- this.input[channel].set(audio[channel], this.inputLength);
- }
-
- this.inputLength += length;
- this.totalInputFrames += length;
- this.process();
- return this.drainFinalizedOutput();
- }
-
- private findBestAnalysisPosition({
- expectedPosition,
- nextSynthesisPosition,
- }: {
- expectedPosition: number;
- nextSynthesisPosition: number;
- }) {
- const minimum = Math.max(
- 0,
- Math.floor(expectedPosition - this.searchRadius),
- );
- const maximum = Math.min(
- this.inputLength - this.windowSize,
- Math.ceil(expectedPosition + this.searchRadius),
- );
-
- let bestPosition = minimum;
- let bestCorrelation = -Infinity;
-
- for (let candidate = minimum; candidate <= maximum; candidate += 4) {
- let dotProduct = 0;
- let previousEnergy = 0;
- let candidateEnergy = 0;
-
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- const previous = this.output[channel];
- const incoming = this.input[channel];
- for (let frame = 0; frame < this.hopSize; frame += 2) {
- const previousValue = previous[nextSynthesisPosition + frame];
- const candidateValue = incoming[candidate + frame];
- dotProduct += previousValue * candidateValue;
- previousEnergy += previousValue * previousValue;
- candidateEnergy += candidateValue * candidateValue;
- }
- }
-
- const correlation =
- dotProduct /
- (Math.sqrt(previousEnergy * candidateEnergy) || Number.EPSILON);
- if (correlation > bestCorrelation) {
- bestCorrelation = correlation;
- bestPosition = candidate;
- }
- }
-
- const fineMinimum = Math.max(minimum, bestPosition - 4);
- const fineMaximum = Math.min(maximum, bestPosition + 4);
- for (let candidate = fineMinimum; candidate <= fineMaximum; candidate++) {
- let dotProduct = 0;
- let previousEnergy = 0;
- let candidateEnergy = 0;
-
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- const previous = this.output[channel];
- const incoming = this.input[channel];
- for (let frame = 0; frame < this.hopSize; frame++) {
- const previousValue = previous[nextSynthesisPosition + frame];
- const candidateValue = incoming[candidate + frame];
- dotProduct += previousValue * candidateValue;
- previousEnergy += previousValue * previousValue;
- candidateEnergy += candidateValue * candidateValue;
- }
- }
-
- const correlation =
- dotProduct /
- (Math.sqrt(previousEnergy * candidateEnergy) || Number.EPSILON);
- if (correlation > bestCorrelation) {
- bestCorrelation = correlation;
- bestPosition = candidate;
- }
- }
-
- return bestPosition;
- }
-
- private process() {
- if (!this.initialized) {
- if (this.inputLength < this.windowSize + this.searchRadius) {
- return;
- }
-
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- this.output[channel].set(
- this.input[channel].subarray(0, this.windowSize),
- );
- }
-
- this.outputLength = this.windowSize;
- this.initialized = true;
- }
-
- while (true) {
- const expectedPosition = this.analysisPosition + this.analysisHop;
- if (
- expectedPosition + this.searchRadius + this.windowSize >
- this.inputLength
- ) {
- break;
- }
-
- const nextSynthesisPosition = this.synthesisPosition + this.hopSize;
- this.output = ensurePlanarCapacity({
- buffers: this.output,
- requiredLength: nextSynthesisPosition + this.windowSize,
- });
- const bestPosition = this.findBestAnalysisPosition({
- expectedPosition,
- nextSynthesisPosition,
- });
-
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- for (let frame = 0; frame < this.hopSize; frame++) {
- const fadeIn =
- 0.5 - 0.5 * Math.cos((Math.PI * (frame + 1)) / (this.hopSize + 1));
- const outputIndex = nextSynthesisPosition + frame;
- this.output[channel][outputIndex] =
- this.output[channel][outputIndex] * (1 - fadeIn) +
- this.input[channel][bestPosition + frame] * fadeIn;
- }
-
- this.output[channel].set(
- this.input[channel].subarray(
- bestPosition + this.hopSize,
- bestPosition + this.windowSize,
- ),
- nextSynthesisPosition + this.hopSize,
- );
- }
-
- // Keep the analysis clock independent from the correlation correction.
- // Periodic signals can have equally good matches at an earlier period; if
- // the correction became the next clock position, the iterator could stop
- // making forward progress.
- this.analysisPosition = expectedPosition;
- this.synthesisPosition = nextSynthesisPosition;
- this.outputLength = nextSynthesisPosition + this.windowSize;
- }
- }
-
- private drainFinalizedOutput() {
- if (!this.initialized) {
- return makePlanarAudio(this.numberOfChannels, 0);
- }
-
- const finalizedLength = Math.max(0, this.synthesisPosition + this.hopSize);
- const result = this.output.map((channel) =>
- channel.slice(0, finalizedLength),
- );
- this.totalOutputFrames += finalizedLength;
-
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- this.output[channel].copyWithin(0, finalizedLength, this.outputLength);
- }
-
- this.outputLength -= finalizedLength;
- this.synthesisPosition -= finalizedLength;
-
- const inputFramesToDiscard = Math.max(
- 0,
- Math.floor(this.analysisPosition) - this.searchRadius,
- );
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- this.input[channel].copyWithin(0, inputFramesToDiscard, this.inputLength);
- }
-
- this.inputLength -= inputFramesToDiscard;
- this.analysisPosition -= inputFramesToDiscard;
- return result;
- }
-
- public finalize() {
- if (this.finalized) {
- throw new Error('The time stretcher has already been finalized.');
- }
-
- this.finalized = true;
- const targetLength = Math.round(this.totalInputFrames * this.factor);
- const padding = makePlanarAudio(
- this.numberOfChannels,
- this.windowSize + this.searchRadius * 2,
- );
- this.input = ensurePlanarCapacity({
- buffers: this.input,
- requiredLength: this.inputLength + padding[0].length,
- });
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- this.input[channel].set(padding[channel], this.inputLength);
- }
-
- this.inputLength += padding[0].length;
- this.process();
- const finalized = this.drainFinalizedOutput();
- const remaining = Math.max(
- 0,
- targetLength - this.totalOutputFrames + finalized[0].length,
- );
-
- if (finalized[0].length >= remaining) {
- return finalized.map((channel) => channel.slice(0, remaining));
- }
-
- const result = makePlanarAudio(this.numberOfChannels, remaining);
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- result[channel].set(finalized[channel]);
- }
-
- return result;
- }
-}
-
-class StreamingLinearResampler {
- private readonly numberOfChannels: number;
- private readonly step: number;
- private input: PlanarAudio;
- private inputLength = 0;
- private position = 0;
-
- public constructor({
- numberOfChannels,
- step,
- }: {
- numberOfChannels: number;
- step: number;
- }) {
- this.numberOfChannels = numberOfChannels;
- this.step = step;
- this.input = makePlanarAudio(numberOfChannels, 65_536);
- }
-
- public append(audio: PlanarAudio) {
- this.input = ensurePlanarCapacity({
- buffers: this.input,
- requiredLength: this.inputLength + audio[0].length,
- });
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- this.input[channel].set(audio[channel], this.inputLength);
- }
-
- this.inputLength += audio[0].length;
- return this.process(false);
- }
-
- private process(finalizing: boolean) {
- const outputLength = Math.max(
- 0,
- Math.floor(
- (this.inputLength - (finalizing ? 0 : 1) - this.position) / this.step,
- ) + 1,
- );
- const result = makePlanarAudio(this.numberOfChannels, outputLength);
-
- for (let outputFrame = 0; outputFrame < outputLength; outputFrame++) {
- const leftIndex = Math.floor(this.position);
- const rightIndex = Math.min(leftIndex + 1, this.inputLength - 1);
- const fraction = this.position - leftIndex;
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- const left = this.input[channel][leftIndex];
- const right = this.input[channel][rightIndex];
- result[channel][outputFrame] = left + (right - left) * fraction;
- }
-
- this.position += this.step;
- }
-
- const discard = Math.min(Math.floor(this.position), this.inputLength);
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- this.input[channel].copyWithin(0, discard, this.inputLength);
- }
-
- this.inputLength -= discard;
- this.position -= discard;
- return result;
- }
-
- public finalize() {
- return this.process(true);
- }
-}
-
-export class StreamingPitchShifter {
- private readonly numberOfChannels: number;
- private readonly stretcher: StreamingTimeStretcher;
- private readonly resampler: StreamingLinearResampler;
- private readonly outputQueue = new PlanarAudioQueue();
- private totalInputFrames = 0;
- private totalOutputFrames = 0;
-
- public constructor({
- numberOfChannels,
- sampleRate,
- toneFrequency,
- }: {
- numberOfChannels: number;
- sampleRate: number;
- toneFrequency: number;
- }) {
- this.numberOfChannels = numberOfChannels;
- this.stretcher = new StreamingTimeStretcher({
- numberOfChannels,
- sampleRate,
- factor: toneFrequency,
- });
- this.resampler = new StreamingLinearResampler({
- numberOfChannels,
- step: toneFrequency,
- });
- }
-
- public append(audio: PlanarAudio) {
- this.totalInputFrames += audio[0].length;
- const stretched = this.stretcher.append(audio);
- this.outputQueue.push(this.resampler.append(stretched));
- return this.takeAvailableOutput();
- }
-
- private takeAvailableOutput() {
- const availableInputFrames = this.totalInputFrames - this.totalOutputFrames;
- const framesToTake = Math.min(
- availableInputFrames,
- this.outputQueue.getLength(),
- );
- const result = this.outputQueue.take(framesToTake, this.numberOfChannels);
- this.totalOutputFrames += framesToTake;
- return result;
- }
-
- public finalize() {
- this.outputQueue.push(this.resampler.append(this.stretcher.finalize()));
- this.outputQueue.push(this.resampler.finalize());
- const remaining = this.totalInputFrames - this.totalOutputFrames;
- const available = this.outputQueue.take(
- Math.min(remaining, this.outputQueue.getLength()),
- this.numberOfChannels,
- );
- const result = makePlanarAudio(this.numberOfChannels, remaining);
- for (let channel = 0; channel < this.numberOfChannels; channel++) {
- result[channel].set(available[channel]);
- }
-
- this.totalOutputFrames += remaining;
- return result;
- }
-}
-
const getPlanarSlice = (slice: AudioBufferSlice) => {
const {buffer} = slice.buffer;
const startFrame = Math.max(
@@ -517,7 +26,7 @@ const makeAudioBufferSlice = ({
timelineTimestamp,
sampleRate,
}: {
- audio: PlanarAudio;
+ audio: Float32Array[];
timelineTimestamp: number;
sampleRate: number;
}): AudioBufferSlice => {
@@ -551,7 +60,8 @@ export async function* pitchShiftAudioIterator({
return;
}
- let shifter: StreamingPitchShifter | null = null;
+ let shifter: InstanceType<typeof Internals.StreamingPitchShifter> | null =
+ null;
let sampleRate = 0;
let numberOfChannels = 0;
let segmentStart = 0;
@@ -603,7 +113,7 @@ export async function* pitchShiftAudioIterator({
segmentStart = slice.timelineTimestamp;
segmentInputFrames = 0;
segmentOutputFrames = 0;
- shifter = new StreamingPitchShifter({
+ shifter = new Internals.StreamingPitchShifter({
numberOfChannels,
sampleRate,
toneFrequency,
diff --git a/packages/media/src/convert-audiodata/convert-audiodata.ts b/packages/media/src/convert-audiodata/convert-audiodata.ts
index ffa617aeac..a24a45453c 100644
--- a/packages/media/src/convert-audiodata/convert-audiodata.ts
+++ b/packages/media/src/convert-audiodata/convert-audiodata.ts
@@ -79,7 +79,10 @@ export const convertAudioDataToS16 = ({
? ceilButNotIfFloatingPointIssue(unroundedFrameCount)
: Math.round(unroundedFrameCount);
- const srcChannels = new Int16Array(srcNumberOfChannels * frameCount);
+ // Copy the full decoded sample before trimming in JavaScript. Firefox's
+ // AudioData.copyTo() can use the wrong channel offset/stride for partial
+ // copies, introducing discontinuities at every rendered video frame.
+ const srcChannels = new Int16Array(srcNumberOfChannels * numberOfFrames);
// https://github.com/remotion-dev/remotion/issues/6493
const isF32 = audioData.format === 'f32' || audioData.format === 'f32-planar';
@@ -87,19 +90,24 @@ export const convertAudioDataToS16 = ({
if (isF32) {
// Firefox decodes as f32 β€” normalize to f32-planar first so the
// final s16 conversion always starts from the same representation.
- const bytesPerPlane = frameCount * 4;
+ const bytesPerPlane = numberOfFrames * 4;
const f32Buffer = new ArrayBuffer(srcNumberOfChannels * bytesPerPlane);
for (let ch = 0; ch < srcNumberOfChannels; ch++) {
audioData.copyTo(
- new Float32Array(f32Buffer, ch * bytesPerPlane, frameCount),
- {planeIndex: ch, frameOffset, frameCount, format: 'f32-planar'},
+ new Float32Array(f32Buffer, ch * bytesPerPlane, numberOfFrames),
+ {
+ planeIndex: ch,
+ frameOffset: 0,
+ frameCount: numberOfFrames,
+ format: 'f32-planar',
+ },
);
}
const f32AudioData = new AudioData({
format: 'f32-planar',
sampleRate: currentSampleRate,
- numberOfFrames: frameCount,
+ numberOfFrames,
numberOfChannels: srcNumberOfChannels,
timestamp: audioData.timestamp,
data: f32Buffer,
@@ -109,7 +117,7 @@ export const convertAudioDataToS16 = ({
planeIndex: 0,
format: FORMAT,
frameOffset: 0,
- frameCount,
+ frameCount: numberOfFrames,
});
f32AudioData.close();
} else {
@@ -117,8 +125,8 @@ export const convertAudioDataToS16 = ({
audioData.copyTo(srcChannels, {
planeIndex: 0,
format: FORMAT,
- frameOffset,
- frameCount,
+ frameOffset: 0,
+ frameCount: numberOfFrames,
});
}
@@ -126,7 +134,10 @@ export const convertAudioDataToS16 = ({
(frameOffset / audioData.sampleRate) * 1_000_000;
return {
- data: srcChannels,
+ data: srcChannels.subarray(
+ frameOffset * srcNumberOfChannels,
+ (frameOffset + frameCount) * srcNumberOfChannels,
+ ),
numberOfChannels: srcNumberOfChannels,
numberOfFrames: frameCount,
sampleRate: currentSampleRate,
diff --git a/packages/media/src/test/pitch-shift.test.ts b/packages/media/src/test/pitch-shift.test.ts
index 075c1727e8..e01954c469 100644
--- a/packages/media/src/test/pitch-shift.test.ts
+++ b/packages/media/src/test/pitch-shift.test.ts
@@ -1,5 +1,5 @@
+import {Internals} from 'remotion';
import {expect, test} from 'vitest';
-import {StreamingPitchShifter} from '../audio/pitch-shift';
const makeSine = ({
frequency,
@@ -59,7 +59,7 @@ test('changes pitch while preserving the sample count', () => {
});
for (const toneFrequency of [0.75, 1.5]) {
- const shifter = new StreamingPitchShifter({
+ const shifter = new Internals.StreamingPitchShifter({
numberOfChannels: 1,
sampleRate,
toneFrequency,
diff --git a/packages/web-renderer/src/audio.ts b/packages/web-renderer/src/audio.ts
index 30b9a4b893..c3f13a28da 100644
--- a/packages/web-renderer/src/audio.ts
+++ b/packages/web-renderer/src/audio.ts
@@ -1,70 +1,176 @@
-import type {TRenderAsset} from 'remotion';
+import {Internals, type TRenderAsset} from 'remotion';
const TARGET_NUMBER_OF_CHANNELS = 2;
-function mixAudio(waves: Int16Array[], length: number) {
- if (waves.length === 0) {
- return new Int16Array(length);
- }
-
- if (waves.length === 1 && waves[0].length === length) {
- return waves[0];
- }
-
- const mixed = new Int16Array(length);
-
- if (waves.length === 1) {
- mixed.set(waves[0].subarray(0, length));
- return mixed;
- }
-
- for (let i = 0; i < length; i++) {
- const sum = waves.reduce((acc, wave) => {
- return acc + (wave[i] ?? 0);
- }, 0);
- // Clamp to Int16 range
- mixed[i] = Math.max(-32768, Math.min(32767, sum));
- }
+type PendingAudioFrame = {
+ timestamp: number;
+ mixed: Float64Array;
+ pendingAssets: number;
+};
- return mixed;
-}
+type PitchShiftState = {
+ shifter: InstanceType<typeof Internals.StreamingPitchShifter>;
+ pending: {frame: PendingAudioFrame; written: number}[];
+};
-export const onlyInlineAudio = ({
- assets,
+// A shifter may need input from later video frames before it can finish an
+// earlier audio frame. Keep those frames until every contributing asset is ready.
+export const createAudioMixer = ({
fps,
- timestamp,
sampleRate,
}: {
- assets: TRenderAsset[];
fps: number;
- timestamp: number;
sampleRate: number;
-}): AudioData => {
- const inlineAudio = assets.filter((asset) => asset.type === 'inline-audio');
-
- const expectedLength = Math.round(
- (TARGET_NUMBER_OF_CHANNELS * sampleRate) / fps,
- );
+}) => {
+ const toneFrequencies = new Map<string, number>();
+ const shifters = new Map<string, PitchShiftState>();
+ const pendingFrames: PendingAudioFrame[] = [];
+ let frameIndex = 0;
- for (const asset of inlineAudio) {
- if (asset.toneFrequency !== 1) {
- throw new Error(
- 'Setting the toneFrequency is not supported yet in web rendering.',
+ const mixShiftedOutput = (state: PitchShiftState, output: Float32Array[]) => {
+ let offset = 0;
+ while (offset < output[0].length) {
+ const pending = state.pending[0];
+ const frameLength =
+ pending.frame.mixed.length / TARGET_NUMBER_OF_CHANNELS;
+ const count = Math.min(
+ frameLength - pending.written,
+ output[0].length - offset,
);
+ for (let i = 0; i < count; i++) {
+ for (let channel = 0; channel < TARGET_NUMBER_OF_CHANNELS; channel++) {
+ pending.frame.mixed[
+ (pending.written + i) * TARGET_NUMBER_OF_CHANNELS + channel
+ ] += output[channel][offset + i] * 32768;
+ }
+ }
+
+ pending.written += count;
+ offset += count;
+ if (pending.written === frameLength) {
+ pending.frame.pendingAssets--;
+ state.pending.shift();
+ }
}
- }
-
- const mixedAudio = mixAudio(
- inlineAudio.map((asset) => asset.audio as Int16Array),
- expectedLength,
- ) as Int16Array<ArrayBuffer>;
-
- return new AudioData({
- data: mixedAudio,
- format: 's16',
- numberOfChannels: TARGET_NUMBER_OF_CHANNELS,
- numberOfFrames: expectedLength / TARGET_NUMBER_OF_CHANNELS,
- sampleRate,
- timestamp,
- });
+ };
+
+ return {
+ addFrame: ({
+ assets,
+ timestamp,
+ isLastFrame,
+ }: {
+ assets: TRenderAsset[];
+ timestamp: number;
+ isLastFrame: boolean;
+ }) => {
+ const inlineAudio = assets.filter(
+ (asset) => asset.type === 'inline-audio',
+ );
+ const activeIds = new Set(inlineAudio.map((asset) => asset.id));
+ for (const [id, state] of shifters) {
+ if (!activeIds.has(id)) {
+ mixShiftedOutput(state, state.shifter.finalize());
+ shifters.delete(id);
+ }
+ }
+
+ // Round sample boundaries cumulatively so fractional samples per video
+ // frame do not accumulate into audio/video drift.
+ const numberOfFrames =
+ Math.round(((frameIndex + 1) * sampleRate) / fps) -
+ Math.round((frameIndex * sampleRate) / fps);
+ frameIndex++;
+ const frame: PendingAudioFrame = {
+ timestamp,
+ mixed: new Float64Array(numberOfFrames * TARGET_NUMBER_OF_CHANNELS),
+ pendingAssets: 0,
+ };
+ pendingFrames.push(frame);
+
+ for (const asset of inlineAudio) {
+ const previousFrequency = toneFrequencies.get(asset.id);
+ if (
+ previousFrequency !== undefined &&
+ previousFrequency !== asset.toneFrequency
+ ) {
+ throw new Error(
+ `toneFrequency must be the same across the entire audio, got ${asset.toneFrequency}, but before it was ${previousFrequency}`,
+ );
+ }
+
+ toneFrequencies.set(asset.id, asset.toneFrequency);
+ if (asset.toneFrequency === 1) {
+ for (
+ let i = 0;
+ i < Math.min(asset.audio.length, frame.mixed.length);
+ i++
+ ) {
+ frame.mixed[i] += asset.audio[i];
+ }
+
+ continue;
+ }
+
+ let state = shifters.get(asset.id);
+ if (!state) {
+ state = {
+ shifter: new Internals.StreamingPitchShifter({
+ numberOfChannels: TARGET_NUMBER_OF_CHANNELS,
+ sampleRate,
+ toneFrequency: asset.toneFrequency,
+ }),
+ pending: [],
+ };
+ shifters.set(asset.id, state);
+ }
+
+ const planar = Array.from(
+ {length: TARGET_NUMBER_OF_CHANNELS},
+ (_, channel) => {
+ const data = new Float32Array(numberOfFrames);
+ for (let i = 0; i < numberOfFrames; i++) {
+ data[i] =
+ (asset.audio[i * TARGET_NUMBER_OF_CHANNELS + channel] ?? 0) /
+ 32768;
+ }
+
+ return data;
+ },
+ );
+ frame.pendingAssets++;
+ state.pending.push({frame, written: 0});
+ mixShiftedOutput(state, state.shifter.append(planar));
+ }
+
+ if (isLastFrame) {
+ for (const state of shifters.values()) {
+ mixShiftedOutput(state, state.shifter.finalize());
+ }
+
+ shifters.clear();
+ }
+ },
+ getReadyAudio: (): AudioData | null => {
+ const frame = pendingFrames[0];
+ if (!frame || frame.pendingAssets > 0) {
+ return null;
+ }
+
+ pendingFrames.shift();
+ const data = new Int16Array(frame.mixed.length);
+ for (let i = 0; i < data.length; i++) {
+ data[i] = Math.max(-32768, Math.min(32767, frame.mixed[i]));
+ }
+
+ return new AudioData({
+ data,
+ format: 's16',
+ numberOfChannels: TARGET_NUMBER_OF_CHANNELS,
+ numberOfFrames: data.length / TARGET_NUMBER_OF_CHANNELS,
+ sampleRate,
+ timestamp: frame.timestamp,
+ });
+ },
+ };
};
diff --git a/packages/web-renderer/src/create-scaffold.tsx b/packages/web-renderer/src/create-scaffold.tsx
index 2f498a16a6..a3c0f08194 100644
--- a/packages/web-renderer/src/create-scaffold.tsx
+++ b/packages/web-renderer/src/create-scaffold.tsx
@@ -141,6 +141,7 @@ export function createScaffold<Props extends Record<string, unknown>>({
defaultOutName,
useHtmlInCanvas,
pixelDensity,
+ sampleRate,
}: {
width: number;
height: number;
@@ -160,6 +161,7 @@ export function createScaffold<Props extends Record<string, unknown>>({
defaultOutName: string | null;
useHtmlInCanvas: boolean;
pixelDensity: number;
+ sampleRate: number | null;
}): {
delayRenderScope: DelayRenderScope;
div: HTMLDivElement;
@@ -318,6 +320,7 @@ export function createScaffold<Props extends Record<string, unknown>>({
>
<UpdateTime
audioEnabled={audioEnabled}
+ sampleRate={sampleRate}
videoEnabled={videoEnabled}
logLevel={logLevel}
compId={id}
diff --git a/packages/web-renderer/src/render-media-on-web.tsx b/packages/web-renderer/src/render-media-on-web.tsx
index 72d87674ac..dffedc9d89 100644
--- a/packages/web-renderer/src/render-media-on-web.tsx
+++ b/packages/web-renderer/src/render-media-on-web.tsx
@@ -11,7 +11,7 @@ import type {z} from 'zod';
import type {$ZodObject} from 'zod/v4/core';
import {addAudioSample, addVideoSampleAndCloseFrame} from './add-sample';
import {handleArtifacts, type WebRendererOnArtifact} from './artifact';
-import {onlyInlineAudio} from './audio';
+import {createAudioMixer} from './audio';
import {createBackgroundKeepalive} from './background-keepalive';
import {canUseWebFsWriter} from './can-use-webfs-target';
import {createAudioSampleSource} from './create-audio-sample-source';
@@ -324,6 +324,15 @@ const internalRenderMediaOnWeb = async <
return Promise.reject(new Error('renderMediaOnWeb() was cancelled'));
}
+ // Media extraction reads this value before the audio context effect runs.
+ const previousSampleRate = window.remotion_sampleRate;
+ using _sampleRateScope = {
+ [Symbol.dispose]: () => {
+ window.remotion_sampleRate = previousSampleRate;
+ },
+ };
+ window.remotion_sampleRate = sampleRate;
+
using scaffold = createScaffold({
width: resolved.width,
height: resolved.height,
@@ -343,6 +352,7 @@ const internalRenderMediaOnWeb = async <
defaultOutName: resolved.defaultOutName,
useHtmlInCanvas: allowHtmlInCanvas,
pixelDensity: scale,
+ sampleRate,
});
const {
@@ -512,6 +522,24 @@ const internalRenderMediaOnWeb = async <
throw new Error('renderMediaOnWeb() was cancelled');
}
+ const audioMixer = createAudioMixer({fps: resolved.fps, sampleRate});
+ const encodeReadyAudio = async () => {
+ if (!audioSampleSource) {
+ return;
+ }
+
+ let audio: AudioData | null;
+ while ((audio = audioMixer.getReadyAudio())) {
+ try {
+ await addAudioSample(audio, audioSampleSource.audioSampleSource);
+ } finally {
+ audio.close();
+ }
+
+ await waitForPageResponsiveness();
+ }
+ };
+
let timeOfLastFrame = Date.now();
const progress = {
renderedFrames: 0,
@@ -632,9 +660,14 @@ const internalRenderMediaOnWeb = async <
await waitForPageResponsiveness();
- const audio = muted
- ? null
- : onlyInlineAudio({assets, fps: resolved.fps, timestamp, sampleRate});
+ if (audioSampleSource) {
+ audioMixer.addFrame({
+ assets,
+ timestamp,
+ isLastFrame: frame === realFrameRange[1],
+ });
+ }
+
internalState.addAudioMixingTime(performance.now() - audioCombineStart);
await waitForPageResponsiveness();
@@ -650,11 +683,7 @@ const internalRenderMediaOnWeb = async <
);
}
- if (audio && audioSampleSource) {
- encodingPromises.push(
- addAudioSample(audio, audioSampleSource.audioSampleSource),
- );
- }
+ encodingPromises.push(encodeReadyAudio());
await Promise.all(encodingPromises);
internalState.addAddSampleTime(performance.now() - addSampleStart);
diff --git a/packages/web-renderer/src/render-still-on-web.tsx b/packages/web-renderer/src/render-still-on-web.tsx
index 34113e99a6..6e346ef3e3 100644
--- a/packages/web-renderer/src/render-still-on-web.tsx
+++ b/packages/web-renderer/src/render-still-on-web.tsx
@@ -122,6 +122,7 @@ async function internalRenderStillOnWeb<
});
using scaffold = createScaffold({
+ sampleRate: null,
width: resolved.width,
height: resolved.height,
delayRenderTimeoutInMilliseconds,
diff --git a/packages/web-renderer/src/test/Root.tsx b/packages/web-renderer/src/test/Root.tsx
index c63cef7d33..3a17449d81 100644
--- a/packages/web-renderer/src/test/Root.tsx
+++ b/packages/web-renderer/src/test/Root.tsx
@@ -63,6 +63,7 @@ import {overflowHidden} from './fixtures/overflow-hidden';
import {overflowHidden3dTransform} from './fixtures/overflow-hidden-3d-transform';
import {parentRotatedSvg} from './fixtures/parent-rotated-svg';
import {parentTransformOrigin} from './fixtures/parent-transform-origin';
+import {pitchShiftAudio} from './fixtures/pitch-shift-audio';
import {pixelDensity} from './fixtures/pixel-density';
import {pixelTransformOrigin} from './fixtures/pixel-transform-origin';
import {rotatedCanvas} from './fixtures/rotated-canvas';
@@ -203,6 +204,7 @@ export const Root: React.FC = () => {
<Composition {...filterText} />
</Folder>
<Folder name="Projects">
+ <Composition {...pitchShiftAudio} />
<Composition {...unwrapped} />
<Composition {...orthographic} />
<Composition {...withMargin} />
diff --git a/packages/web-renderer/src/test/audio.test.tsx b/packages/web-renderer/src/test/audio.test.tsx
index fc33dde01d..3db4d673bd 100644
--- a/packages/web-renderer/src/test/audio.test.tsx
+++ b/packages/web-renderer/src/test/audio.test.tsx
@@ -28,36 +28,6 @@ const getAudioCodecFromBlob = async (
return track.codec;
};
-test(
- 'should not be able to set toneFrequency on web rendering',
- {retry: 3},
- async (t) => {
- const Component: React.FC = () => {
- return <Audio src={staticFile('dialogue.wav')} toneFrequency={0.5} />;
- };
-
- await expect(async () => {
- const result = await renderMediaOnWeb({
- licenseKey: 'free-license',
- composition: {
- component: Component,
- id: 'audio',
- width: 100,
- height: 100,
- fps: 30,
- durationInFrames: 1,
- calculateMetadata: null,
- },
- outputTarget:
- t.task.file.projectName === 'webkit' ? 'arraybuffer' : 'web-fs',
- });
- throw new Error('Did resolve' + JSON.stringify(result));
- }).rejects.toThrow(
- 'Setting the toneFrequency is not supported yet in web rendering.',
- );
- },
-);
-
test('should be able to render 2 audios', async (t) => {
if (t.task.file.projectName === 'chromium') {
// Chromium in CI doesn't support video codec decoding in this test environment
diff --git a/packages/web-renderer/src/test/fixtures/pitch-shift-audio.tsx b/packages/web-renderer/src/test/fixtures/pitch-shift-audio.tsx
new file mode 100644
index 0000000000..61c17bfd7a
--- /dev/null
+++ b/packages/web-renderer/src/test/fixtures/pitch-shift-audio.tsx
@@ -0,0 +1,86 @@
+import {Audio} from '@remotion/media';
+import {useState} from 'react';
+import {Sequence} from 'remotion';
+
+// A stereo tone with distinguishable channels, without codec or network variance.
+export const makeToneWav = () => {
+ const sampleRate = 48000;
+ const data = new ArrayBuffer(44 + sampleRate * 4);
+ const view = new DataView(data);
+ for (const [offset, text] of [
+ [0, 'RIFF'],
+ [8, 'WAVE'],
+ [12, 'fmt '],
+ [36, 'data'],
+ ] as const) {
+ for (let i = 0; i < text.length; i++) {
+ view.setUint8(offset + i, text.charCodeAt(i));
+ }
+ }
+
+ view.setUint32(4, data.byteLength - 8, true);
+ view.setUint32(16, 16, true);
+ view.setUint16(20, 1, true);
+ view.setUint16(22, 2, true);
+ view.setUint32(24, sampleRate, true);
+ view.setUint32(28, sampleRate * 4, true);
+ view.setUint16(32, 4, true);
+ view.setUint16(34, 16, true);
+ view.setUint32(40, sampleRate * 4, true);
+ for (let frame = 0; frame < sampleRate; frame++) {
+ for (let channel = 0; channel < 2; channel++) {
+ view.setInt16(
+ 44 + frame * 4 + channel * 2,
+ Math.round(
+ Math.sin(
+ (frame / sampleRate) * (channel === 0 ? 440 : 660) * Math.PI * 2,
+ ) * 10000,
+ ),
+ true,
+ );
+ }
+ }
+
+ let binary = '';
+ const bytes = new Uint8Array(data);
+ for (let i = 0; i < bytes.length; i += 8192) {
+ binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
+ }
+
+ return `data:audio/wav;base64,${btoa(binary)}`;
+};
+
+const Component: React.FC = () => {
+ const [src] = useState(makeToneWav);
+ return (
+ <>
+ <Sequence durationInFrames={30}>
+ <Audio src={src} toneFrequency={0.75} />
+ </Sequence>
+ <Sequence from={15} durationInFrames={30}>
+ <Audio
+ src={src}
+ toneFrequency={1.5}
+ loop
+ trimBefore={3}
+ playbackRate={1.25}
+ />
+ </Sequence>
+ <Sequence from={45} durationInFrames={9}>
+ <Audio src={src} />
+ </Sequence>
+ <Sequence from={59} durationInFrames={1}>
+ <Audio src={src} toneFrequency={0.5} />
+ </Sequence>
+ </>
+ );
+};
+
+export const pitchShiftAudio = {
+ component: Component,
+ id: 'pitch-shift-audio',
+ width: 100,
+ height: 100,
+ fps: 30,
+ durationInFrames: 60,
+} as const;
diff --git a/packages/web-renderer/src/test/html-in-canvas.test.tsx b/packages/web-renderer/src/test/html-in-canvas.test.tsx
index 0b63736488..942f90e9ad 100644
--- a/packages/web-renderer/src/test/html-in-canvas.test.tsx
+++ b/packages/web-renderer/src/test/html-in-canvas.test.tsx
@@ -177,6 +177,7 @@ test('does not create a nested HTML-in-canvas capture', async () => {
test('keeps a scaffold without HTML-in-canvas hidden', () => {
const scaffold = createScaffold({
+ sampleRate: null,
Component: () => null,
audioEnabled: false,
defaultCodec: null,
@@ -212,6 +213,7 @@ test('keeps a scaffold without HTML-in-canvas hidden', () => {
test('keeps the DOM composer scaffold paintable', () => {
const scaffold = createScaffold({
+ sampleRate: null,
Component: () => (
<canvas
ref={(node) => {
diff --git a/packages/web-renderer/src/test/pitch-shift-audio.test.tsx b/packages/web-renderer/src/test/pitch-shift-audio.test.tsx
new file mode 100644
index 0000000000..62d74cebf6
--- /dev/null
+++ b/packages/web-renderer/src/test/pitch-shift-audio.test.tsx
@@ -0,0 +1,245 @@
+import {Audio, Video} from '@remotion/media';
+import {ALL_FORMATS, AudioBufferSink, BlobSource, Input} from 'mediabunny';
+import {useCurrentFrame} from 'remotion';
+import {expect, test} from 'vitest';
+import {renderMediaOnWeb} from '../render-media-on-web';
+import {makeToneWav, pitchShiftAudio} from './fixtures/pitch-shift-audio';
+import '../symbol-dispose';
+
+// Measure both requested tones in overlapping regions, where zero crossings
+// cannot distinguish which asset was pitch shifted.
+const amplitudeAt = (
+ audio: Float32Array,
+ sampleRate: number,
+ range: [number, number],
+ frequency: number,
+) => {
+ let real = 0;
+ let imaginary = 0;
+ const from = Math.round(range[0] * sampleRate);
+ const to = Math.round(range[1] * sampleRate);
+ for (let i = from; i < to; i++) {
+ const phase = (i / sampleRate) * frequency * Math.PI * 2;
+ real += audio[i] * Math.cos(phase);
+ imaginary += audio[i] * Math.sin(phase);
+ }
+
+ return (2 * Math.hypot(real, imaginary)) / (to - from);
+};
+
+test.each([48000, 44100])(
+ 'renders pitch-shifted stereo audio at %i Hz with preserved timing',
+ async (sampleRate) => {
+ const result = await renderMediaOnWeb({
+ licenseKey: 'free-license',
+ composition: {...pitchShiftAudio, calculateMetadata: null},
+ container: 'wav',
+ outputTarget: 'arraybuffer',
+ sampleRate,
+ });
+ using input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(await result.getBlob()),
+ });
+ const track = await input.getPrimaryAudioTrack();
+ expect(track).not.toBeNull();
+ const channels = [
+ new Float32Array(sampleRate * 2),
+ new Float32Array(sampleRate * 2),
+ ];
+ let totalSamples = 0;
+ for await (const {buffer, timestamp} of new AudioBufferSink(
+ track!,
+ ).buffers()) {
+ expect(timestamp).toBeCloseTo(totalSamples / sampleRate, 5);
+ for (let channel = 0; channel < 2; channel++) {
+ channels[channel].set(buffer.getChannelData(channel), totalSamples);
+ }
+
+ totalSamples += buffer.length;
+ }
+
+ expect(totalSamples).toBe(sampleRate * 2);
+ for (let channel = 0; channel < 2; channel++) {
+ const sourceFrequency = channel === 0 ? 440 : 660;
+ const lower = sourceFrequency * 0.75;
+ // The rendering playbackRate resampler also scales pitch.
+ const higher = sourceFrequency * 1.5 * 1.25;
+ const audio = channels[channel];
+ expect(amplitudeAt(audio, sampleRate, [0.2, 0.4], lower)).toBeGreaterThan(
+ 0.2,
+ );
+ expect(
+ amplitudeAt(audio, sampleRate, [0.2, 0.4], sourceFrequency),
+ ).toBeLessThan(0.02);
+ expect(
+ amplitudeAt(audio, sampleRate, [0.65, 0.85], lower),
+ ).toBeGreaterThan(0.2);
+ expect(
+ amplitudeAt(audio, sampleRate, [0.65, 0.85], higher),
+ ).toBeGreaterThan(0.15);
+ expect(
+ amplitudeAt(audio, sampleRate, [1.1, 1.3], higher),
+ ).toBeGreaterThan(0.15);
+ expect(
+ amplitudeAt(audio, sampleRate, [1.55, 1.7], sourceFrequency),
+ ).toBeGreaterThan(0.2);
+ expect(
+ audio
+ .subarray(Math.round(1.8 * sampleRate), Math.round(1.96 * sampleRate))
+ .every((sample) => sample === 0),
+ ).toBe(true);
+ // Even a one-frame clip must be flushed before finalizing the output.
+ expect(
+ audio
+ .subarray(Math.round((59 / 30) * sampleRate))
+ .some((sample) => Math.abs(sample) > 0.1),
+ ).toBe(true);
+
+ // A reset at each video frame produces discontinuities in this sine wave.
+ for (let frame = 3; frame < 12; frame++) {
+ const boundary = Math.round((frame / 30) * sampleRate);
+ expect(Math.abs(audio[boundary] - audio[boundary - 1])).toBeLessThan(
+ 0.05,
+ );
+ }
+ }
+ },
+);
+
+test('rejects changing toneFrequency, including after a silent gap', async () => {
+ const src = makeToneWav();
+ for (const initialFrequency of [1, 0.75]) {
+ const Component: React.FC = () => {
+ const frame = useCurrentFrame();
+ return (
+ <Audio
+ src={src}
+ muted={frame === 1}
+ toneFrequency={frame < 2 ? initialFrequency : 1.5}
+ />
+ );
+ };
+
+ await expect(
+ renderMediaOnWeb({
+ licenseKey: 'free-license',
+ composition: {
+ ...pitchShiftAudio,
+ component: Component,
+ durationInFrames: 3,
+ calculateMetadata: null,
+ },
+ container: 'wav',
+ outputTarget: 'arraybuffer',
+ }),
+ ).rejects.toThrow(
+ `toneFrequency must be the same across the entire audio, got 1.5, but before it was ${initialFrequency}`,
+ );
+ }
+});
+
+test('renders a partial frame range with video and pitch shifts Video audio', async () => {
+ const renderedVideo = await renderMediaOnWeb({
+ licenseKey: 'free-license',
+ composition: {...pitchShiftAudio, calculateMetadata: null},
+ frameRange: [15, 44],
+ outputTarget: 'arraybuffer',
+ });
+ const src = URL.createObjectURL(await renderedVideo.getBlob());
+ try {
+ const Component: React.FC = () => <Video src={src} toneFrequency={0.8} />;
+ const result = await renderMediaOnWeb({
+ licenseKey: 'free-license',
+ composition: {
+ ...pitchShiftAudio,
+ component: Component,
+ durationInFrames: 30,
+ calculateMetadata: null,
+ },
+ container: 'wav',
+ outputTarget: 'arraybuffer',
+ });
+ using input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(await result.getBlob()),
+ });
+ const track = await input.getPrimaryAudioTrack();
+ const audio = new Float32Array(48000);
+ let totalSamples = 0;
+ for await (const {buffer, timestamp} of new AudioBufferSink(
+ track!,
+ ).buffers()) {
+ expect(timestamp).toBeCloseTo(totalSamples / 48000, 5);
+ audio.set(buffer.getChannelData(0), totalSamples);
+ totalSamples += buffer.length;
+ }
+
+ expect(totalSamples).toBe(48000);
+ expect(
+ amplitudeAt(audio, 48000, [0.2, 0.4], 440 * 0.75 * 0.8),
+ ).toBeGreaterThan(0.1);
+ expect(
+ amplitudeAt(audio, 48000, [0.65, 0.85], 440 * 1.25 * 1.5 * 0.8),
+ ).toBeGreaterThan(0.1);
+ } finally {
+ URL.revokeObjectURL(src);
+ }
+});
+
+test.each([0.01, 2])(
+ 'flushes short clips and muted gaps at toneFrequency=%s',
+ async (toneFrequency) => {
+ const src = makeToneWav();
+ const fps = 59.94;
+ const sampleRate = 44100;
+ const Component: React.FC = () => {
+ const frame = useCurrentFrame();
+ return (
+ <Audio src={src} toneFrequency={toneFrequency} muted={frame === 4} />
+ );
+ };
+
+ const result = await renderMediaOnWeb({
+ licenseKey: 'free-license',
+ composition: {
+ ...pitchShiftAudio,
+ component: Component,
+ fps,
+ durationInFrames: 8,
+ calculateMetadata: null,
+ },
+ frameRange: [2, 7],
+ container: 'wav',
+ outputTarget: 'arraybuffer',
+ sampleRate,
+ });
+ using input = new Input({
+ formats: ALL_FORMATS,
+ source: new BlobSource(await result.getBlob()),
+ });
+ const track = await input.getPrimaryAudioTrack();
+ const audio = new Float32Array(Math.round((6 * sampleRate) / fps));
+ let totalSamples = 0;
+ for await (const {buffer, timestamp} of new AudioBufferSink(
+ track!,
+ ).buffers()) {
+ expect(timestamp).toBeCloseTo(totalSamples / sampleRate, 5);
+ audio.set(buffer.getChannelData(0), totalSamples);
+ totalSamples += buffer.length;
+ }
+
+ expect(totalSamples).toBe(audio.length);
+ const gapStart = Math.round((2 * sampleRate) / fps);
+ const gapEnd = Math.round((3 * sampleRate) / fps);
+ expect(
+ audio.subarray(0, gapStart).some((sample) => Math.abs(sample) > 0.1),
+ ).toBe(true);
+ expect(
+ audio.subarray(gapStart, gapEnd).every((sample) => sample === 0),
+ ).toBe(true);
+ expect(
+ audio.subarray(gapEnd).some((sample) => Math.abs(sample) > 0.1),
+ ).toBe(true);
+ },
+);
diff --git a/packages/web-renderer/src/update-time.tsx b/packages/web-renderer/src/update-time.tsx
index 96cc75d516..fecc90b9cb 100644
--- a/packages/web-renderer/src/update-time.tsx
+++ b/packages/web-renderer/src/update-time.tsx
@@ -10,6 +10,7 @@ export type TimeUpdaterRef = {
export const UpdateTime: React.FC<{
readonly children: React.ReactNode;
readonly audioEnabled: boolean;
+ readonly sampleRate: number | null;
readonly videoEnabled: boolean;
readonly logLevel: LogLevel;
readonly compId: string;
@@ -18,6 +19,7 @@ export const UpdateTime: React.FC<{
}> = ({
children,
audioEnabled,
+ sampleRate,
videoEnabled,
logLevel,
compId,
@@ -42,7 +44,7 @@ export const UpdateTime: React.FC<{
logLevel={logLevel}
numberOfAudioTags={0}
audioLatencyHint="interactive"
- previewSampleRate={null}
+ previewSampleRate={sampleRate}
frameState={{
[compId]: frame,
}}