🎥 Make videos programmatically with React
introduce progress interval
Jonny Burger1059f92a7eac
diff --git a/packages/docs/docs/media-parser/parse-media.mdx b/packages/docs/docs/media-parser/parse-media.mdxindex b60f496487..2e8dc9db50 100644--- a/packages/docs/docs/media-parser/parse-media.mdx+++ b/packages/docs/docs/media-parser/parse-media.mdx@@ -278,6 +278,14 @@ You may make this an async function, and while it is not resolved, **the parsingThis is useful if you want to add a small delay inbetween progress steps to keep the UI interactive.:::+### `progressIntervalInMs?`++_number_++The interval in milliseconds at which the [`onParseProgress`](#onparseprogress) callback is called.+Default `100`. Set to `0` for unthrottled updates.+Note that updates are fired very often and updating the DOM often may slow down the conversion process.+### `logLevel?`One of `"error"`, `"warn"`, `"info"`, `"debug"`, `"trace"`.diff --git a/packages/media-parser/src/parse-media.ts b/packages/media-parser/src/parse-media.tsindex 4ae7436d64..9a8b5bc4a9 100644--- a/packages/media-parser/src/parse-media.ts+++ b/packages/media-parser/src/parse-media.ts@@ -17,6 +17,7 @@ import type {ParseResult} from './parse-result';import {parseVideo} from './parse-video';import {fetchReader} from './readers/from-fetch';import {makeParserState} from './state/parser-state';+import {throttledStateUpdate} from './throttled-progress';export const parseMedia: ParseMedia = async function <F extends Options<ParseMediaFields>,@@ -28,7 +29,8 @@ export const parseMedia: ParseMedia = async function <onVideoTrack,signal,logLevel = 'info',- onParseProgress,+ onParseProgress: onParseProgressDoNotCallDirectly,+ progressIntervalInMs,...more}: ParseMediaOptions<F>) {let parseResult: ParseResult | null = null;@@ -77,6 +79,13 @@ export const parseMedia: ParseMedia = async function <const returnValue = {} as ParseMediaResult<AllParseMediaFields>;const moreFields = more as ParseMediaCallbacks;+ const throttledState = throttledStateUpdate({+ updateFn: onParseProgressDoNotCallDirectly ?? null,+ everyMilliseconds: progressIntervalInMs ?? 100,+ signal,+ totalBytes: contentLength,+ });+const triggerInfoEmit = () => {const availableInfo = getAvailableInfo({fieldsToFetch: fields,@@ -146,14 +155,13 @@ export const parseMedia: ParseMedia = async function <await fetchMoreData();}- // TODO: Throttle parse progress- await onParseProgress?.({+ throttledState.update?.(() => ({bytes: iterator.counter.getOffset(),percentage: contentLength? iterator.counter.getOffset() / contentLength: null,totalBytes: contentLength,- });+ }));triggerInfoEmit();diff --git a/packages/media-parser/src/throttled-progress.ts b/packages/media-parser/src/throttled-progress.tsnew file mode 100644index 0000000000..c33c87fdba--- /dev/null+++ b/packages/media-parser/src/throttled-progress.ts@@ -0,0 +1,69 @@+import type {ParseMediaOnProgress, ParseMediaProgress} from './options';++type ReturnType = {+ get: () => ParseMediaProgress;+ update: ParseMediaProgressFn | null;+ stopAndGetLastProgress: () => void;+};++export type ParseMediaProgressFn = (+ state: (prevState: ParseMediaProgress) => ParseMediaProgress,+) => void;++export const throttledStateUpdate = ({+ updateFn,+ everyMilliseconds,+ signal,+}: {+ updateFn: ParseMediaOnProgress | null;+ everyMilliseconds: number;+ signal: AbortSignal | undefined;+ totalBytes: number | null;+}): ReturnType => {+ let currentState: ParseMediaProgress = {+ bytes: 0,+ percentage: null,+ totalBytes: null,+ };++ if (!updateFn) {+ return {+ get: () => currentState,+ update: null,+ stopAndGetLastProgress: () => {},+ };+ }++ let lastUpdated: ParseMediaProgress | null = null;++ const callUpdateIfChanged = () => {+ if (currentState === lastUpdated) {+ return;+ }++ updateFn(currentState);+ lastUpdated = currentState;+ };++ const interval = setInterval(() => {+ callUpdateIfChanged();+ }, everyMilliseconds);++ const onAbort = () => {+ clearInterval(interval);+ };++ signal?.addEventListener('abort', onAbort, {once: true});++ return {+ get: () => currentState,+ update: (fn) => {+ currentState = fn(currentState);+ },+ stopAndGetLastProgress: () => {+ clearInterval(interval);+ signal?.removeEventListener('abort', onAbort);+ return currentState;+ },+ };+};