Skip to content

🎥 Make videos programmatically with React

`@remotion/media-utils`: Fix useWindowedAudioData() reading beyond the end of the file

Jonny Burgerb2ac7634ef65
diff --git a/packages/media-utils/src/get-partial-wave-data.ts b/packages/media-utils/src/get-partial-wave-data.ts
index 1ead5f7922..c48479f508 100644
--- a/packages/media-utils/src/get-partial-wave-data.ts
+++ b/packages/media-utils/src/get-partial-wave-data.ts
@@ -26,10 +26,11 @@ export const getPartialWaveData = async ({
}) => {
const startByte =
dataOffset + Math.floor(fromSeconds * sampleRate) * blockAlign;
- const endByte = Math.min(
- fileSize - 1,
- dataOffset + Math.floor(toSeconds * sampleRate - 1) * blockAlign,
- );
+ const endByte =
+ Math.min(
+ fileSize,
+ (dataOffset + Math.floor(toSeconds * sampleRate)) * blockAlign,
+ ) - 1;
const response = await fetchWithCorsCatch(src, {
headers: {
@@ -38,6 +39,12 @@ export const getPartialWaveData = async ({
signal,
});
+ if (response.status === 416) {
+ throw new Error(
+ `Tried to read bytes ${startByte}-${endByte} from ${src}, but the response status code was 416 "Range Not Satisfiable". Were too many bytes requested? The file is ${fileSize} bytes long.`,
+ );
+ }
+
if (response.status !== 206) {
throw new Error(
`Tried to read bytes ${startByte}-${endByte} from ${src}, but the response status code was ${response.status} (expected was 206). This means the server might not support returning a partial response.`,
diff --git a/packages/media-utils/src/probe-wave-file.ts b/packages/media-utils/src/probe-wave-file.ts
index 0ccaddbf3f..2810c141af 100644
--- a/packages/media-utils/src/probe-wave-file.ts
+++ b/packages/media-utils/src/probe-wave-file.ts
@@ -53,6 +53,13 @@ export const probeWaveFile = async (src: string): Promise<WaveProbe> => {
range: 'bytes=0-256',
},
});
+
+ if (response.status === 416) {
+ throw new Error(
+ `Tried to read bytes 0-256 from ${src}, but the response status code was 416 "Range Not Satisfiable". Is the file at least 256 bytes long?`,
+ );
+ }
+
if (response.status !== 206) {
throw new Error(
`Tried to read bytes 0-256 from ${src}, but the response status code was ${response.status} (expected was 206). This means the server might not support returning a partial response.`,
diff --git a/packages/media-utils/src/use-windowed-audio-data.ts b/packages/media-utils/src/use-windowed-audio-data.ts
index 3c704af785..fefb4fcc2a 100644
--- a/packages/media-utils/src/use-windowed-audio-data.ts
+++ b/packages/media-utils/src/use-windowed-audio-data.ts
@@ -98,7 +98,9 @@ export const useWindowedAudioData = ({
}
const maxWindowIndex = Math.floor(
- waveProbe.durationInSeconds / windowInSeconds,
+ // If an audio is exactly divisible by windowInSeconds, we need to
+ // subtract 0.000000000001 to avoid fetching an extra window.
+ waveProbe.durationInSeconds / windowInSeconds - 0.000000000001,
);
// needs to be in order because we rely on the concatenation below