π₯ Make videos programmatically with React
Add preview pitch shifting to @remotion/media
Jonny Burger38a754fad53b
diff --git a/packages/docs/docs/audio/pitch.mdx b/packages/docs/docs/audio/pitch.mdxindex 85e80150a0..66ca91f7eb 100644--- a/packages/docs/docs/audio/pitch.mdx+++ b/packages/docs/docs/audio/pitch.mdx@@ -6,22 +6,25 @@ id: pitchcrumb: 'Audio'----Use the `toneFrequency` prop to control the pitch of audio during [server-side rendering](/docs/ssr). It is supported by [`<Audio>`](/docs/media/audio), [`<Video>`](/docs/media/video), [`<Html5Audio>`](/docs/html5-audio), [`<Html5Video>`](/docs/html5-video), and [`<OffthreadVideo>`](/docs/offthreadvideo).+Use the `toneFrequency` prop to control the pitch of audio. During preview, it is supported by [`<Audio>`](/docs/media/audio) and [`<Video>`](/docs/media/video) from `@remotion/media`. During [server-side rendering](/docs/ssr), it is also supported by [`<Html5Audio>`](/docs/html5-audio), [`<Html5Video>`](/docs/html5-video), and [`<OffthreadVideo>`](/docs/offthreadvideo).-`toneFrequency` is not supported during preview or [client-side rendering](/docs/client-side-rendering).+`toneFrequency` is not supported during [client-side rendering](/docs/client-side-rendering).Values between `0.01` and `2` are accepted, where `1` represents the original pitch. Values less than `1` will decrease the pitch, while values greater than `1` will increase it.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.+```tsx twoslash {7} title="MyComp.tsx"-import {Html5Audio, staticFile, AbsoluteFill} from 'remotion';+import {Audio} from '@remotion/media';+import {AbsoluteFill, staticFile} from 'remotion';export const MyComposition = () => {return (<AbsoluteFill><div>Hello World!</div>- <Html5Audio src={staticFile('audio.mp3')} toneFrequency={0.8} />+ <Audio src={staticFile('audio.mp3')} toneFrequency={0.8} /></AbsoluteFill>);};diff --git a/packages/docs/docs/media/audio.mdx b/packages/docs/docs/media/audio.mdxindex 595996819d..c1c547894b 100644--- a/packages/docs/docs/media/audio.mdx+++ b/packages/docs/docs/media/audio.mdx@@ -311,12 +311,11 @@ Accepts a number between `0.01` and `2`, where `1` represents the original pitchA `toneFrequency` of 0.5 would lower the pitch by half, and a `toneFrequency` of `1.5` would increase the pitch by 50%.-The value must stay the same across the entire time the video tag is mounted.+The value can be changed while previewing. It must stay constant across the composition timeline during rendering.-:::warning-Only works in server-side rendering.-Does not currently work in preview or in [client-side rendering](/docs/client-side-rendering/).-:::+Works during preview and server-side rendering. It is not supported during [client-side rendering](/docs/client-side-rendering/).++If the component [falls back to `<Html5Audio>`](/docs/media/fallback) during preview, pitch shifting is not applied.### `fallbackHtml5AudioProps?`diff --git a/packages/docs/docs/media/video.mdx b/packages/docs/docs/media/video.mdxindex bc02a143cf..bc0f11e0d0 100644--- a/packages/docs/docs/media/video.mdx+++ b/packages/docs/docs/media/video.mdx@@ -430,12 +430,11 @@ Accepts a number between `0.01` and `2`, where `1` represents the original pitchA `toneFrequency` of 0.5 would lower the pitch by half, and a `toneFrequency` of `1.5` would increase the pitch by 50%.-The value must stay the same across the entire time the video tag is mounted.+The value can be changed while previewing. It must stay constant across the composition timeline during rendering.-:::warning-Only works in server-side rendering.-Does not currently work in preview or in [client-side rendering](/docs/client-side-rendering/).-:::+Works during preview and server-side rendering. It is not supported during [client-side rendering](/docs/client-side-rendering/).++If the component [falls back to `<OffthreadVideo>`](/docs/media/fallback) during preview, pitch shifting is not applied.### `headless?`<AvailableFrom v="4.0.387" />diff --git a/packages/docs/docs/video-tags.mdx b/packages/docs/docs/video-tags.mdxindex 6be1c24ecf..9121e0ce7d 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) | Only during server-side rendering | Only during server-side rendering | Only during server-side rendering |+| **`toneFrequency`** <br/> (Pitch Change) | During preview and server-side rendering | 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-iterator-manager.ts b/packages/media/src/audio-iterator-manager.tsindex 3599b64756..52f94fbc7b 100644--- a/packages/media/src/audio-iterator-manager.ts+++ b/packages/media/src/audio-iterator-manager.ts@@ -13,6 +13,7 @@ import {type QueuedPeriod,} from './audio/audio-preview-iterator';import {getScheduledTime} from './audio/get-scheduled-time';+import {pitchShiftAudioIterator} from './audio/pitch-shift';import {processNext,StaleWaiterError,@@ -78,6 +79,7 @@ export const audioIteratorManager = ({getStartTime,initialMuted,initialVolume,+ toneFrequency,drawDebugOverlay,}: {audioTrack: InputAudioTrack;@@ -89,10 +91,12 @@ export const audioIteratorManager = ({getStartTime: () => number;initialMuted: boolean;initialVolume: number;+ toneFrequency: number;drawDebugOverlay: () => void;}) => {let muted = initialMuted;let currentVolume = Math.max(0, initialVolume);+ let currentToneFrequency = toneFrequency;let currentSeek: {time: number;playbackRate: number;@@ -431,7 +435,7 @@ export const audioIteratorManager = ({const maximumContinuousTimestamp =startFromSecond + getSequenceDurationInSeconds() * playbackRate;- const source = loop+ const unshiftedSource = loop? makeLoopingIterator({audioSink,seekTimeInSeconds: startFromSecond,@@ -444,6 +448,10 @@ export const audioIteratorManager = ({timeToSeek: startFromSecond,maximumTimestamp,});+ const source = pitchShiftAudioIterator({+ iterator: unshiftedSource,+ toneFrequency: currentToneFrequency,+ });const iterator = makeAudioIterator({startFromSecond,iterator: source,@@ -660,6 +668,9 @@ export const audioIteratorManager = ({currentVolume = Math.max(0, volume);gainNode.gain.value = muted ? 0 : currentVolume;},+ setToneFrequency: (newToneFrequency: number) => {+ currentToneFrequency = newToneFrequency;+ },scheduleAudioChunk,waitForNScheduledNodes,};diff --git a/packages/media/src/audio/audio-for-preview.tsx b/packages/media/src/audio/audio-for-preview.tsxindex 6a4742088a..58c5062bdb 100644--- a/packages/media/src/audio/audio-for-preview.tsx+++ b/packages/media/src/audio/audio-for-preview.tsx@@ -79,6 +79,7 @@ const AudioForPreviewAssertedShowing: React.FC<NewAudioForPreviewProps> = ({const mediaPlayerRef = useRef<MediaPlayer | null>(null);const initialTrimBeforeRef = useRef(trimBefore);const initialTrimAfterRef = useRef(trimAfter);+ const initialToneFrequencyRef = useRef(toneFrequency ?? 1);const [initialRequestInit] = useState(requestInit);const [mediaPlayerReady, setMediaPlayerReady] = useState(false);@@ -158,6 +159,7 @@ const AudioForPreviewAssertedShowing: React.FC<NewAudioForPreviewProps> = ({effectiveMuted,userPreferredVolume,playbackRate,+ toneFrequency: toneFrequency ?? 1,globalPlaybackRate,fps: videoConfig.fps,sequenceOffset,@@ -203,6 +205,7 @@ const AudioForPreviewAssertedShowing: React.FC<NewAudioForPreviewProps> = ({fps: videoConfig.fps,canvas: null,playbackRate: initialPlaybackRate.current,+ toneFrequency: initialToneFrequencyRef.current,audioStreamIndex: audioStreamIndex ?? null,debugOverlay: false,bufferState: buffer,diff --git a/packages/media/src/audio/audio.tsx b/packages/media/src/audio/audio.tsxindex f319fc1bfe..102adcf324 100644--- a/packages/media/src/audio/audio.tsx+++ b/packages/media/src/audio/audio.tsx@@ -10,6 +10,7 @@ import {type InteractivitySchema,} from 'remotion';import {getLoopDisplay} from '../show-in-timeline';+import {validateToneFrequency} from '../validate-tone-frequency';import {AudioForPreview} from './audio-for-preview';import {AudioForRendering} from './audio-for-rendering';import type {AudioProps} from './props';@@ -43,6 +44,16 @@ export const audioSchema: InteractivitySchema = {hiddenFromList: false,keyframable: false,},+ toneFrequency: {+ type: 'number',+ min: 0.01,+ max: 2,+ step: 0.01,+ default: 1,+ description: 'Pitch',+ hiddenFromList: false,+ keyframable: false,+ },muted: {type: 'boolean', default: false, description: 'Muted'},loop: {type: 'boolean', default: false, description: 'Loop'},} as const satisfies InteractivitySchema;@@ -158,6 +169,10 @@ const AudioInner: React.FC<{playbackRate: props.playbackRate, volume: props.volume},'Audio',);+ validateToneFrequency({+ toneFrequency: props.toneFrequency,+ component: 'Audio',+ });if (sequenceDurationInFrames === 0) {return null;diff --git a/packages/media/src/audio/pitch-shift.ts b/packages/media/src/audio/pitch-shift.tsnew file mode 100644index 0000000000..8fa6f8b7c5--- /dev/null+++ b/packages/media/src/audio/pitch-shift.ts@@ -0,0 +1,631 @@+import type {AudioBufferSlice} from '../make-iterator-with-priming';++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(+ 0,+ Math.round(slice.sourceOffsetInSeconds * buffer.sampleRate),+ );+ const numberOfFrames = Math.min(+ buffer.length - startFrame,+ Math.round(slice.sourceDurationInSeconds * buffer.sampleRate),+ );++ return new Array(buffer.numberOfChannels)+ .fill(null)+ .map((_, channel) =>+ buffer+ .getChannelData(channel)+ .slice(startFrame, startFrame + numberOfFrames),+ );+};++const makeAudioBufferSlice = ({+ audio,+ timelineTimestamp,+ sampleRate,+}: {+ audio: PlanarAudio;+ timelineTimestamp: number;+ sampleRate: number;+}): AudioBufferSlice => {+ const buffer = new AudioBuffer({+ length: audio[0].length,+ numberOfChannels: audio.length,+ sampleRate,+ });+ for (let channel = 0; channel < audio.length; channel++) {+ buffer.copyToChannel(new Float32Array(audio[channel]), channel);+ }++ const duration = audio[0].length / sampleRate;+ return {+ buffer: {buffer, timestamp: timelineTimestamp, duration},+ timelineTimestamp,+ sourceOffsetInSeconds: 0,+ sourceDurationInSeconds: duration,+ };+};++export async function* pitchShiftAudioIterator({+ iterator,+ toneFrequency,+}: {+ iterator: AsyncGenerator<AudioBufferSlice, void, unknown>;+ toneFrequency: number;+}): AsyncGenerator<AudioBufferSlice, void, unknown> {+ if (toneFrequency === 1) {+ yield* iterator;+ return;+ }++ let shifter: StreamingPitchShifter | null = null;+ let sampleRate = 0;+ let numberOfChannels = 0;+ let segmentStart = 0;+ let segmentInputFrames = 0;+ let segmentOutputFrames = 0;++ const flush = () => {+ if (!shifter) {+ return null;+ }++ const audio = shifter.finalize();+ const slice =+ audio[0].length === 0+ ? null+ : makeAudioBufferSlice({+ audio,+ timelineTimestamp: segmentStart + segmentOutputFrames / sampleRate,+ sampleRate,+ });+ shifter = null;+ return slice;+ };++ for await (const slice of iterator) {+ const planar = getPlanarSlice(slice);+ if (planar[0].length === 0) {+ continue;+ }++ const nextSampleRate = slice.buffer.buffer.sampleRate;+ const nextNumberOfChannels = slice.buffer.buffer.numberOfChannels;+ const expectedTimestamp = segmentStart + segmentInputFrames / sampleRate;+ const startsNewSegment =+ !shifter ||+ nextSampleRate !== sampleRate ||+ nextNumberOfChannels !== numberOfChannels ||+ Math.abs(slice.timelineTimestamp - expectedTimestamp) >+ 1.5 / nextSampleRate;++ if (startsNewSegment) {+ const previousSegmentFinalSlice = flush();+ if (previousSegmentFinalSlice) {+ yield previousSegmentFinalSlice;+ }++ sampleRate = nextSampleRate;+ numberOfChannels = nextNumberOfChannels;+ segmentStart = slice.timelineTimestamp;+ segmentInputFrames = 0;+ segmentOutputFrames = 0;+ shifter = new StreamingPitchShifter({+ numberOfChannels,+ sampleRate,+ toneFrequency,+ });+ }++ if (!shifter) {+ throw new Error('Pitch shifter was not initialized.');+ }++ segmentInputFrames += planar[0].length;+ const output = shifter.append(planar);+ if (output[0].length > 0) {+ yield makeAudioBufferSlice({+ audio: output,+ timelineTimestamp: segmentStart + segmentOutputFrames / sampleRate,+ sampleRate,+ });+ segmentOutputFrames += output[0].length;+ }+ }++ const finalSlice = flush();+ if (finalSlice) {+ yield finalSlice;+ }+}diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.tsindex 08fae41fbe..b00dc7e8dc 100644--- a/packages/media/src/media-player.ts+++ b/packages/media/src/media-player.ts@@ -51,6 +51,7 @@ export class MediaPlayer {private src: string;private logLevel: LogLevel;private playbackRate: number;+ private toneFrequency: number;private globalPlaybackRate: number;private audioStreamIndex: number | null;@@ -97,6 +98,7 @@ export class MediaPlayer {trimBefore,trimAfter,playbackRate,+ toneFrequency,globalPlaybackRate,audioStreamIndex,fps,@@ -122,6 +124,7 @@ export class MediaPlayer {trimBefore: number | undefined;trimAfter: number | undefined;playbackRate: number;+ toneFrequency: number;globalPlaybackRate: number;audioStreamIndex: number | null;fps: number;@@ -147,6 +150,7 @@ export class MediaPlayer {this.logLevel = logLevel;this.sharedAudioContext = sharedAudioContext;this.playbackRate = playbackRate;+ this.toneFrequency = toneFrequency;this.globalPlaybackRate = globalPlaybackRate;this.loop = loop;this.trimBefore = trimBefore;@@ -398,6 +402,7 @@ export class MediaPlayer {getStartTime: () => this.getStartTime(),initialMuted,initialVolume,+ toneFrequency: this.toneFrequency,drawDebugOverlay: this.drawDebugOverlay,getSequenceDurationInSeconds: () =>this.getSequenceDurationInSeconds(),@@ -621,6 +626,22 @@ export class MediaPlayer {}}+ public async setToneFrequency(+ toneFrequency: number,+ unloopedTimeInSeconds: number,+ ): Promise<void> {+ if (this.toneFrequency !== toneFrequency) {+ this.toneFrequency = toneFrequency;+ if (!this.audioIteratorManager) {+ return;+ }++ this.audioIteratorManager.setToneFrequency(toneFrequency);+ this.audioIteratorManager.destroyIterator();+ await this.seekTo(unloopedTimeInSeconds);+ }+ }+public async setGlobalPlaybackRate(rate: number,unloopedTimeInSeconds: number,diff --git a/packages/media/src/test/audio-iterator.test.ts b/packages/media/src/test/audio-iterator.test.tsindex 0ef85a2803..562d6f4472 100644--- a/packages/media/src/test/audio-iterator.test.ts+++ b/packages/media/src/test/audio-iterator.test.ts@@ -77,6 +77,7 @@ const prepare = async (options?: {getStartTime: () => startTime,initialMuted: false,initialVolume: 1,+ toneFrequency: 1,drawDebugOverlay: () => {},});diff --git a/packages/media/src/test/media-player.test.ts b/packages/media/src/test/media-player.test.tsindex e2b4a824db..ff494bf1c8 100644--- a/packages/media/src/test/media-player.test.ts+++ b/packages/media/src/test/media-player.test.ts@@ -45,6 +45,7 @@ const makeAudioPlayer = (trimBefore: undefined,trimAfter: undefined,playbackRate: 1,+ toneFrequency: 1,globalPlaybackRate: 1,audioStreamIndex: null,fps: 30,@@ -147,6 +148,7 @@ test('dispose should immediately unblock playback delays', async () => {trimBefore: undefined,trimAfter: undefined,playbackRate: 1,+ toneFrequency: 1,globalPlaybackRate: 1,audioStreamIndex: 0,fps: 30,diff --git a/packages/media/src/test/pitch-shift-preview.test.tsx b/packages/media/src/test/pitch-shift-preview.test.tsxnew file mode 100644index 0000000000..7e5ac9f1ff--- /dev/null+++ b/packages/media/src/test/pitch-shift-preview.test.tsx@@ -0,0 +1,193 @@+import {Player} from '@remotion/player';+import React from 'react';+import {flushSync} from 'react-dom';+import {createRoot} from 'react-dom/client';+import {expect, test, vi} from 'vitest';+import {Audio} from '../audio/audio';+import {Video} from '../video/video';++type ToneFrequencyProps = {+ readonly toneFrequency: number;+};++const makeSineWaveUrl = ({+ frequency,+ sampleRate,+ durationInSeconds,+}: {+ frequency: number;+ sampleRate: number;+ durationInSeconds: number;+}) => {+ const numberOfFrames = sampleRate * durationInSeconds;+ const bytesPerSample = 2;+ const dataLength = numberOfFrames * bytesPerSample;+ const buffer = new ArrayBuffer(44 + dataLength);+ const view = new DataView(buffer);+ const writeString = (offset: number, value: string) => {+ for (let index = 0; index < value.length; index++) {+ view.setUint8(offset + index, value.charCodeAt(index));+ }+ };++ writeString(0, 'RIFF');+ view.setUint32(4, 36 + dataLength, true);+ writeString(8, 'WAVE');+ writeString(12, 'fmt ');+ view.setUint32(16, 16, true);+ view.setUint16(20, 1, true);+ view.setUint16(22, 1, true);+ view.setUint32(24, sampleRate, true);+ view.setUint32(28, sampleRate * bytesPerSample, true);+ view.setUint16(32, bytesPerSample, true);+ view.setUint16(34, bytesPerSample * 8, true);+ writeString(36, 'data');+ view.setUint32(40, dataLength, true);++ for (let frame = 0; frame < numberOfFrames; frame++) {+ const sample = Math.round(+ Math.sin((frame / sampleRate) * frequency * Math.PI * 2) * 16_000,+ );+ view.setInt16(44 + frame * bytesPerSample, sample, true);+ }++ return URL.createObjectURL(new Blob([buffer], {type: 'audio/wav'}));+};++const waitFor = async (predicate: () => boolean) => {+ const start = Date.now();+ while (Date.now() - start < 10_000) {+ if (predicate()) {+ return;+ }++ await new Promise((resolve) => setTimeout(resolve, 10));+ }++ throw new Error('Timed out while waiting for preview audio buffers.');+};++const estimateFrequency = ({+ audio,+ sampleRate,+}: {+ audio: Float32Array;+ sampleRate: number;+}) => {+ let positiveCrossings = 0;+ for (let frame = 1; frame < audio.length; frame++) {+ if (audio[frame - 1] <= 0 && audio[frame] > 0) {+ positiveCrossings++;+ }+ }++ return positiveCrossings / (audio.length / sampleRate);+};++test('Audio and Video update toneFrequency during preview', async () => {+ const src = makeSineWaveUrl({+ frequency: 440,+ sampleRate: 48_000,+ durationInSeconds: 1,+ });+ const originalCreateBufferSource = AudioContext.prototype.createBufferSource;+ const createdNodes: AudioBufferSourceNode[] = [];+ const createBufferSourceSpy = vi+ .spyOn(AudioContext.prototype, 'createBufferSource')+ .mockImplementation(function (this: AudioContext) {+ const node = originalCreateBufferSource.call(this);+ createdNodes.push(node);+ return node;+ });++ const verify = async (component: React.ComponentType<ToneFrequencyProps>) => {+ createdNodes.length = 0;+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);+ let setToneFrequency: React.Dispatch<React.SetStateAction<number>> | null =+ null;+ const StatefulComposition: React.FC = () => {+ const [toneFrequency, setCurrentToneFrequency] = React.useState(1);+ setToneFrequency = setCurrentToneFrequency;+ return React.createElement(component, {toneFrequency});+ };++ root.render(+ <Player+ acknowledgeRemotionLicense+ component={StatefulComposition}+ compositionHeight={100}+ compositionWidth={100}+ durationInFrames={30}+ fps={30}+ inputProps={{}}+ />,+ );++ try {+ await waitFor(+ () => createdNodes.filter((node) => node.buffer !== null).length >= 20,+ );+ const getScheduledFrequency = () => {+ const buffers = createdNodes+ .map((node) => node.buffer)+ .filter((buffer): buffer is AudioBuffer => buffer !== null);+ const samples = new Float32Array(+ buffers.reduce((sum, buffer) => sum + buffer.length, 0),+ );+ let offset = 0;+ for (const buffer of buffers) {+ samples.set(buffer.getChannelData(0), offset);+ offset += buffer.length;+ }++ return estimateFrequency({+ audio: samples,+ sampleRate: buffers[0].sampleRate,+ });+ };++ expect(getScheduledFrequency()).toBeCloseTo(440, -1);+ createdNodes.length = 0;+ if (!setToneFrequency) {+ throw new Error('Composition did not mount.');+ }++ flushSync(() => setToneFrequency?.(1.5));+ await waitFor(+ () => createdNodes.filter((node) => node.buffer !== null).length >= 20,+ );+ expect(getScheduledFrequency()).toBeCloseTo(660, -1);+ } finally {+ root.unmount();+ container.remove();+ }+ };++ const AudioComposition: React.FC<ToneFrequencyProps> = ({toneFrequency}) => (+ <Audio+ disallowFallbackToHtml5Audio+ logLevel="error"+ src={src}+ toneFrequency={toneFrequency}+ />+ );+ const VideoComposition: React.FC<ToneFrequencyProps> = ({toneFrequency}) => (+ <Video+ disallowFallbackToOffthreadVideo+ headless+ logLevel="error"+ src={src}+ toneFrequency={toneFrequency}+ />+ );++ try {+ await verify(AudioComposition);+ await verify(VideoComposition);+ } finally {+ createBufferSourceSpy.mockRestore();+ URL.revokeObjectURL(src);+ }+});diff --git a/packages/media/src/test/pitch-shift.test.ts b/packages/media/src/test/pitch-shift.test.tsnew file mode 100644index 0000000000..075c1727e8--- /dev/null+++ b/packages/media/src/test/pitch-shift.test.ts@@ -0,0 +1,83 @@+import {expect, test} from 'vitest';+import {StreamingPitchShifter} from '../audio/pitch-shift';++const makeSine = ({+ frequency,+ sampleRate,+ durationInSeconds,+}: {+ frequency: number;+ sampleRate: number;+ durationInSeconds: number;+}) => {+ const audio = new Float32Array(sampleRate * durationInSeconds);+ for (let frame = 0; frame < audio.length; frame++) {+ audio[frame] = Math.sin((frame / sampleRate) * frequency * Math.PI * 2);+ }++ return audio;+};++const concatenate = (chunks: Float32Array[]) => {+ const result = new Float32Array(+ chunks.reduce((sum, chunk) => sum + chunk.length, 0),+ );+ let offset = 0;+ for (const chunk of chunks) {+ result.set(chunk, offset);+ offset += chunk.length;+ }++ return result;+};++const estimateFrequency = ({+ audio,+ sampleRate,+}: {+ audio: Float32Array;+ sampleRate: number;+}) => {+ const start = Math.floor(sampleRate * 0.2);+ const end = Math.floor(sampleRate * 0.8);+ let positiveCrossings = 0;+ for (let frame = start + 1; frame < end; frame++) {+ if (audio[frame - 1] <= 0 && audio[frame] > 0) {+ positiveCrossings++;+ }+ }++ return positiveCrossings / ((end - start) / sampleRate);+};++test('changes pitch while preserving the sample count', () => {+ const sampleRate = 48_000;+ const source = makeSine({+ frequency: 440,+ sampleRate,+ durationInSeconds: 1,+ });++ for (const toneFrequency of [0.75, 1.5]) {+ const shifter = new StreamingPitchShifter({+ numberOfChannels: 1,+ sampleRate,+ toneFrequency,+ });+ const chunks: Float32Array[] = [];+ for (let frame = 0; frame < source.length; frame += 128) {+ const output = shifter.append([source.slice(frame, frame + 128)])[0];+ if (output.length > 0) {+ chunks.push(output);+ }+ }++ chunks.push(shifter.finalize()[0]);+ const shifted = concatenate(chunks);+ expect(shifted.length).toBe(source.length);+ expect(estimateFrequency({audio: shifted, sampleRate})).toBeCloseTo(+ 440 * toneFrequency,+ -1,+ );+ }+});diff --git a/packages/media/src/test/premount-arm-kicks-scheduler.test.ts b/packages/media/src/test/premount-arm-kicks-scheduler.test.tsindex c2dd40f687..3b67fcb5a6 100644--- a/packages/media/src/test/premount-arm-kicks-scheduler.test.ts+++ b/packages/media/src/test/premount-arm-kicks-scheduler.test.ts@@ -19,6 +19,7 @@ const makePlayer = ({trimBefore: undefined,trimAfter: undefined,playbackRate: 1,+ toneFrequency: 1,globalPlaybackRate: 1,audioStreamIndex: 0,fps: 30,diff --git a/packages/media/src/test/trim-change-seek.test.ts b/packages/media/src/test/trim-change-seek.test.tsindex 531b5bb52f..011848ecda 100644--- a/packages/media/src/test/trim-change-seek.test.ts+++ b/packages/media/src/test/trim-change-seek.test.ts@@ -11,6 +11,7 @@ test('setTrimBefore and setTrimAfter should update frame when paused', async ()trimBefore: undefined,trimAfter: undefined,playbackRate: 1,+ toneFrequency: 1,globalPlaybackRate: 1,audioStreamIndex: 0,fps: 30,diff --git a/packages/media/src/test/video-with-no-frames-in-beginning.test.ts b/packages/media/src/test/video-with-no-frames-in-beginning.test.tsindex 00dc28d128..9c9aa03219 100644--- a/packages/media/src/test/video-with-no-frames-in-beginning.test.ts+++ b/packages/media/src/test/video-with-no-frames-in-beginning.test.ts@@ -126,6 +126,7 @@ test('same goes for audio', async () => {getStartTime: () => 0,initialMuted: false,initialVolume: 1,+ toneFrequency: 1,drawDebugOverlay: () => {},});diff --git a/packages/media/src/use-common-effects.ts b/packages/media/src/use-common-effects.tsindex 2269c62d24..879770f775 100644--- a/packages/media/src/use-common-effects.ts+++ b/packages/media/src/use-common-effects.ts@@ -16,6 +16,7 @@ export const useCommonEffects = ({effectiveMuted,userPreferredVolume,playbackRate,+ toneFrequency,globalPlaybackRate,fps,sequenceOffset,@@ -38,6 +39,7 @@ export const useCommonEffects = ({readonly effectiveMuted: boolean;readonly userPreferredVolume: number;readonly playbackRate: number;+ readonly toneFrequency: number;readonly globalPlaybackRate: number;readonly fps: number;readonly sequenceOffset: number;@@ -128,6 +130,15 @@ export const useCommonEffects = ({mediaPlayer.setPlaybackRate(playbackRate, currentTimeRef.current);}, [playbackRate, mediaPlayerReady, mediaPlayerRef, currentTimeRef]);+ useLayoutEffect(() => {+ const mediaPlayer = mediaPlayerRef.current;+ if (!mediaPlayer || !mediaPlayerReady) {+ return;+ }++ mediaPlayer.setToneFrequency(toneFrequency, currentTimeRef.current);+ }, [toneFrequency, mediaPlayerReady, mediaPlayerRef, currentTimeRef]);+useLayoutEffect(() => {const mediaPlayer = mediaPlayerRef.current;if (!mediaPlayer || !mediaPlayerReady) {diff --git a/packages/media/src/validate-tone-frequency.ts b/packages/media/src/validate-tone-frequency.tsnew file mode 100644index 0000000000..e21bc50d2a--- /dev/null+++ b/packages/media/src/validate-tone-frequency.ts@@ -0,0 +1,22 @@+export const validateToneFrequency = ({+ toneFrequency,+ component,+}: {+ toneFrequency: number | undefined;+ component: 'Audio' | 'Video';+}) => {+ if (toneFrequency === undefined) {+ return;+ }++ if (+ typeof toneFrequency !== 'number' ||+ !Number.isFinite(toneFrequency) ||+ toneFrequency < 0.01 ||+ toneFrequency > 2+ ) {+ throw new TypeError(+ `The \`toneFrequency\` prop of <${component}> must be a finite number between 0.01 and 2, but got ${String(toneFrequency)}.`,+ );+ }+};diff --git a/packages/media/src/video/video-for-preview.tsx b/packages/media/src/video/video-for-preview.tsxindex 1191ca0d42..fbf619bfb8 100644--- a/packages/media/src/video/video-for-preview.tsx+++ b/packages/media/src/video/video-for-preview.tsx@@ -53,6 +53,7 @@ type VideoForPreviewProps = NativeVideoProps & {readonly src: string;readonly style: React.CSSProperties | undefined;readonly playbackRate: number;+ readonly toneFrequency: number;readonly logLevel: LogLevel;readonly className: string | undefined;readonly muted: boolean;@@ -87,6 +88,7 @@ const VideoForPreviewAssertedShowing: React.FC<src: unpreloadedSrc,style,playbackRate,+ toneFrequency,logLevel,className,muted,@@ -204,6 +206,7 @@ const VideoForPreviewAssertedShowing: React.FC<const initialIsPostmounting = useRef(isPostmounting);const initialGlobalPlaybackRate = useRef(globalPlaybackRate);const initialPlaybackRate = useRef(playbackRate);+ const initialToneFrequency = useRef(toneFrequency);const initialMuted = useRef(effectiveMuted);const initialVolume = useRef(userPreferredVolume);const initialSequenceDuration = useRef(videoConfig.durationInFrames);@@ -282,6 +285,7 @@ const VideoForPreviewAssertedShowing: React.FC<trimBefore: initialTrimBeforeRef.current,fps: videoConfig.fps,playbackRate: initialPlaybackRate.current,+ toneFrequency: initialToneFrequency.current,audioStreamIndex,debugOverlay,bufferState: buffer,@@ -474,6 +478,7 @@ const VideoForPreviewAssertedShowing: React.FC<effectiveMuted,userPreferredVolume,playbackRate,+ toneFrequency,globalPlaybackRate,fps: videoConfig.fps,sequenceOffset,@@ -538,6 +543,7 @@ const VideoForPreviewAssertedShowing: React.FC<trimAfter={trimAfter}trimBefore={trimBefore}playbackRate={playbackRate}+ toneFrequency={toneFrequency}loopVolumeCurveBehavior={loopVolumeCurveBehavior}name={'<Html5Video> (fallback)'}loop={loop}diff --git a/packages/media/src/video/video.tsx b/packages/media/src/video/video.tsxindex 73ffad7ca5..b1ec516317 100644--- a/packages/media/src/video/video.tsx+++ b/packages/media/src/video/video.tsx@@ -10,6 +10,7 @@ import {type InteractivitySchema,} from 'remotion';import {getLoopDisplay} from '../show-in-timeline';+import {validateToneFrequency} from '../validate-tone-frequency';import {getVideoSequenceDuration} from './get-video-sequence-duration';import type {InnerVideoProps, VideoProps} from './props';import {VideoForPreview} from './video-for-preview';@@ -49,6 +50,16 @@ export const videoSchema: InteractivitySchema = {hiddenFromList: false,keyframable: false,},+ toneFrequency: {+ type: 'number',+ min: 0.01,+ max: 2,+ step: 0.01,+ default: 1,+ description: 'Pitch',+ hiddenFromList: false,+ keyframable: false,+ },muted: {type: 'boolean', default: false, description: 'Muted'},loop: {type: 'boolean', default: false, description: 'Loop'},...Internals.transformSchema,@@ -123,6 +134,7 @@ const InnerVideo: React.FC<});validateMediaProps({playbackRate, volume}, 'Video');+ validateToneFrequency({toneFrequency, component: 'Video'});if (environment.isRendering) {return (@@ -173,6 +185,7 @@ const InnerVideo: React.FC<muted={muted}onVideoFrame={onVideoFrame}playbackRate={playbackRate}+ toneFrequency={toneFrequency ?? 1}src={src}style={style}volume={volume}