🎥 Make videos programmatically with React
allow to pass an onProgress() callback to prefetch()
Jonny Burgerbd9d522245b2
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex dbbfa7a2e2..a7ff7ae0c7 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -118,7 +118,7 @@ export {random,RandomSeed,} from './no-react';-export {prefetch} from './prefetch.js';+export {prefetch, PrefetchOnProgress} from './prefetch.js';export {registerRoot} from './register-root.js';export {LayoutAndStyle,diff --git a/packages/core/src/prefetch.ts b/packages/core/src/prefetch.tsindex 6ce283cfec..c741955178 100644--- a/packages/core/src/prefetch.ts+++ b/packages/core/src/prefetch.ts@@ -30,6 +30,52 @@ const blobToBase64 = function (blob: Blob): Promise<string> {});};+export type PrefetchOnProgress = (options: {+ totalBytes: number | null;+ loadedBytes: number;+}) => {};++const getBlobFromReader = async ({+ reader,+ contentType,+ contentLength,+ onProgress,+}: {+ reader: ReadableStreamDefaultReader<Uint8Array>;+ contentType: string | null;+ contentLength: number | null;+ onProgress: PrefetchOnProgress | undefined;+}): Promise<Blob> => {+ let receivedLength = 0;+ const chunks = [];+ // eslint-disable-next-line no-constant-condition+ while (true) {+ const {done, value} = await reader.read();++ if (done) {+ break;+ }++ chunks.push(value);+ receivedLength += value.length;+ if (onProgress) {+ onProgress({loadedBytes: receivedLength, totalBytes: contentLength});+ }+ }++ const chunksAll = new Uint8Array(receivedLength);+ let position = 0;++ for (const chunk of chunks) {+ chunksAll.set(chunk, position);+ position += chunk.length;+ }++ return new Blob([chunksAll], {+ type: contentType ?? undefined,+ });+};+/*** @description When you call the preFetch() function, an asset will be fetched and kept in memory so it is ready when you want to play it in a <Player>.* @see [Documentation](https://www.remotion.dev/docs/prefetch)@@ -39,6 +85,7 @@ export const prefetch = (options?: {method?: 'blob-url' | 'base64';contentType?: string;+ onProgress?: PrefetchOnProgress;},): FetchAndPreload => {const method = options?.method ?? 'blob-url';@@ -76,25 +123,42 @@ export const prefetch = (throw new Error(`HTTP error, status = ${res.status}`);}- return res.blob();- })- .then((buf) => {- if (!buf) {- return;- }+ const headerContentType = res.headers.get('Content-Type');++ const contentType = options?.contentType ?? headerContentType;+ const hasProperContentType =+ contentType &&+ (contentType.startsWith('video/') ||+ contentType.startsWith('audio/') ||+ contentType.startsWith('image/'));- if (- !buf.type.startsWith('video/') &&- !buf.type.startsWith('audio/') &&- !buf.type.startsWith('image/') &&- !options?.contentType- ) {+ if (!hasProperContentType) {// eslint-disable-next-line no-consoleconsole.warn(- `Called prefetch() on ${src} which returned a "Content-Type" of ${buf.type}. Prefetched content should have a proper content type (video/... or audio/...) or a contentType passed the options of prefetch(). Otherwise, prefetching will not work properly in all browsers.`,+ `Called prefetch() on ${src} which returned a "Content-Type" of ${headerContentType}. Prefetched content should have a proper content type (video/... or audio/...) or a contentType passed the options of prefetch(). Otherwise, prefetching will not work properly in all browsers.`,);}+ if (!res.body) {+ throw new Error(`HTTP response of ${src} has no body`);+ }++ const reader = res.body.getReader();++ return getBlobFromReader({+ reader,+ contentType: options?.contentType ?? headerContentType ?? null,+ contentLength: res.headers.get('Content-Length')+ ? parseInt(res.headers.get('Content-Length')!, 10)+ : null,+ onProgress: options?.onProgress,+ });+ })+ .then((buf) => {+ if (!buf) {+ return;+ }+const actualBlob = options?.contentType? new Blob([buf], {type: options.contentType}): buf;diff --git a/packages/docs/docs/prefetch.md b/packages/docs/docs/prefetch.mdindex 2ce411e1ef..552ca2e9fd 100644--- a/packages/docs/docs/prefetch.md+++ b/packages/docs/docs/prefetch.md@@ -71,6 +71,28 @@ Read below for which option is suitable for you.Set a content type for the blob. By default, the content type from the HTTP response is taken. We recommend setting an appropriate content type for the media, e.g `video/mp4` only if the HTTP resource does not contain the right one by default.+#### `onProgress?`<AvailableFrom v="4.0.85" />++Callback for progress events.++```tsx twoslash+import type { PrefetchOnProgress } from "remotion";++const onProgress: PrefetchOnProgress = (progress) => {+ if (progress.totalBytes === null) {+ // HTTP response has no "Content-Length" header,+ // therefore no relative progress can be calculated.+ console.log("Loaded bytes:", progress.loadedBytes);+ return;+ }++ console.log(+ "Loading progress:",+ Math.round(progress.loadedBytes / progress.totalBytes / 100) + "%",+ );+};+```+## Return valueAn object with: